diff --git a/CMakeLists.txt b/CMakeLists.txt index 027ca16521e..93096ad07b9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -353,6 +353,12 @@ How swift-C++ bridging code is compiled: DEFAULT: based on the build configuration ]=] DEFAULT) +option(SWIFT_USE_SYMLINKS "Use symlinks instead of copying binaries" ${CMAKE_HOST_UNIX}) +set(SWIFT_COPY_OR_SYMLINK "copy") +if(SWIFT_USE_SYMLINKS) + set(SWIFT_COPY_OR_SYMLINK "create_symlink") +endif() + # The following only works with the Ninja generator in CMake >= 3.0. set(SWIFT_PARALLEL_LINK_JOBS "" CACHE STRING "Define the maximum number of linker jobs for swift.") @@ -1333,6 +1339,15 @@ endif() add_subdirectory(include) if(SWIFT_INCLUDE_TOOLS) + + # TODO Remove this once release/5.9 is done and we can finish migrating Swift + # off of `llvm::None`/`llvm::Optional`, and `llvm::makeArrayRef`. + # This is to silence the avalanche of deprecation warnings from LLVM headers + # until we can actually do something about them. This is nasty, but it's + # better than losing context due to the sheer number in-actionable deprecation + # warnings or the massive number of merge-conflicts we would get otherwise. + add_definitions(-DSWIFT_TARGET) + # Include 'swift-syntax'. # This is a function because we want to set some 'CMAKE_*' variables temporarily.' # TODO: Replace this with 'block()' after CMake 3.25 diff --git a/cmake/modules/Libdispatch.cmake b/cmake/modules/Libdispatch.cmake index 2c3f26c3385..79a988005a3 100644 --- a/cmake/modules/Libdispatch.cmake +++ b/cmake/modules/Libdispatch.cmake @@ -8,15 +8,14 @@ if(NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin") set(SWIFT_LIBDISPATCH_CXX_COMPILER ${CMAKE_CXX_COMPILER}) elseif(CMAKE_SYSTEM_NAME STREQUAL CMAKE_HOST_SYSTEM_NAME) if(CMAKE_SYSTEM_NAME STREQUAL "Windows") - if(CMAKE_SYSTEM_PROCESSOR STREQUAL CMAKE_HOST_SYSTEM_PROCESSOR AND - TARGET clang) + if(DEFINED SWIFT_CLANG_LOCATION) + set(SWIFT_LIBDISPATCH_C_COMPILER ${SWIFT_CLANG_LOCATION}/clang-cl${CMAKE_EXECUTABLE_SUFFIX}) + set(SWIFT_LIBDISPATCH_CXX_COMPILER ${SWIFT_CLANG_LOCATION}/clang-cl${CMAKE_EXECUTABLE_SUFFIX}) + elseif(CMAKE_SYSTEM_PROCESSOR STREQUAL CMAKE_HOST_SYSTEM_PROCESSOR AND TARGET clang) set(SWIFT_LIBDISPATCH_C_COMPILER $/clang-cl${CMAKE_EXECUTABLE_SUFFIX}) set(SWIFT_LIBDISPATCH_CXX_COMPILER $/clang-cl${CMAKE_EXECUTABLE_SUFFIX}) - elseif(DEFINED SWIFT_CLANG_LOCATION) - set(SWIFT_LIBDISPATCH_C_COMPILER ${SWIFT_CLANG_LOCATION}/clang-cl${CMAKE_EXECUTABLE_SUFFIX}) - set(SWIFT_LIBDISPATCH_CXX_COMPILER ${SWIFT_CLANG_LOCATION}/clang-cl${CMAKE_EXECUTABLE_SUFFIX}) else() set(SWIFT_LIBDISPATCH_C_COMPILER clang-cl${CMAKE_EXECUTABLE_SUFFIX}) set(SWIFT_LIBDISPATCH_CXX_COMPILER clang-cl${CMAKE_EXECUTABLE_SUFFIX}) diff --git a/cmake/modules/SwiftComponents.cmake b/cmake/modules/SwiftComponents.cmake index c29f5286e1a..019a8d6c345 100644 --- a/cmake/modules/SwiftComponents.cmake +++ b/cmake/modules/SwiftComponents.cmake @@ -203,6 +203,9 @@ function(swift_install_symlink_component component) # otherwise. install(DIRECTORY DESTINATION "${ARG_DESTINATION}" COMPONENT ${component}) install(SCRIPT ${INSTALL_SYMLINK} - CODE "install_symlink(${ARG_LINK_NAME} ${ARG_TARGET} ${ARG_DESTINATION})" + CODE "install_symlink(${ARG_LINK_NAME} + ${ARG_TARGET} + ${ARG_DESTINATION} + ${SWIFT_COPY_OR_SYMLINK})" COMPONENT ${component}) endfunction() diff --git a/include/swift/ABI/ObjectFile.h b/include/swift/ABI/ObjectFile.h index 719d021e1fa..f352ee91ecf 100644 --- a/include/swift/ABI/ObjectFile.h +++ b/include/swift/ABI/ObjectFile.h @@ -7,8 +7,9 @@ #ifndef SWIFT_ABI_OBJECTFILE_H #define SWIFT_ABI_OBJECTFILE_H -#include "llvm/Support/ErrorHandling.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/StringRef.h" +#include "llvm/Support/ErrorHandling.h" namespace swift { diff --git a/include/swift/AST/ASTContext.h b/include/swift/AST/ASTContext.h index dea584a39cd..c6a25ae8b3d 100644 --- a/include/swift/AST/ASTContext.h +++ b/include/swift/AST/ASTContext.h @@ -506,9 +506,9 @@ public: return StringRef(Result.data(), Result.size()); } - template + template MutableArrayRef - AllocateCopy(llvm::SetVector setVector, + AllocateCopy(llvm::SetVector setVector, AllocationArena arena = AllocationArena::Permanent) const { return MutableArrayRef(AllocateCopy(setVector.begin(), setVector.end(), diff --git a/include/swift/AST/ASTWalker.h b/include/swift/AST/ASTWalker.h index a4fb1a4544c..ada0e3ee484 100644 --- a/include/swift/AST/ASTWalker.h +++ b/include/swift/AST/ASTWalker.h @@ -15,6 +15,7 @@ #include "swift/Basic/LLVM.h" #include "llvm/ADT/Optional.h" +#include "llvm/ADT/None.h" #include "llvm/ADT/PointerUnion.h" #include diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h index 5f4fafb144f..0c99f9076d7 100644 --- a/include/swift/AST/Decl.h +++ b/include/swift/AST/Decl.h @@ -5020,7 +5020,7 @@ class ProtocolDecl final : public NominalTypeDecl { /// \c None if it hasn't yet been computed. llvm::Optional getCachedHasSelfOrAssociatedTypeRequirements() { if (Bits.ProtocolDecl.HasSelfOrAssociatedTypeRequirementsValid) - return Bits.ProtocolDecl.HasSelfOrAssociatedTypeRequirements; + return static_cast(Bits.ProtocolDecl.HasSelfOrAssociatedTypeRequirements); return llvm::None; } diff --git a/include/swift/AST/FileUnit.h b/include/swift/AST/FileUnit.h index aca067ebbfc..053607a7932 100644 --- a/include/swift/AST/FileUnit.h +++ b/include/swift/AST/FileUnit.h @@ -122,7 +122,7 @@ public: /// collecting the identifiers in \p spiGroups. virtual void lookupImportedSPIGroups( const ModuleDecl *importedModule, - SmallSetVector &spiGroups) const {}; + llvm::SmallSetVector &spiGroups) const {}; /// Checks whether this file imports \c module as \c @_weakLinked. virtual bool importsModuleAsWeakLinked(const ModuleDecl *module) const { diff --git a/include/swift/AST/IRGenOptions.h b/include/swift/AST/IRGenOptions.h index bfc554efd71..5718e2567cb 100644 --- a/include/swift/AST/IRGenOptions.h +++ b/include/swift/AST/IRGenOptions.h @@ -502,6 +502,15 @@ public: /// The calling convention used to perform non-swift calls. llvm::CallingConv::ID PlatformCCallingConvention; + /// Use CAS based object format as the output. + bool UseCASBackend; + + /// The output mode for the CAS Backend. + llvm::CASBackendMode CASObjMode; + + /// Emit a .casid file next to the object file if CAS Backend is used. + bool EmitCASIDFile; + IRGenOptions() : DWARFVersion(2), OutputKind(IRGenOutputKind::LLVMAssemblyAfterOptimization), @@ -513,9 +522,9 @@ public: DebugInfoFormat(IRGenDebugInfoFormat::None), DisableClangModuleSkeletonCUs(false), UseJIT(false), DisableLLVMOptzns(false), DisableSwiftSpecificLLVMOptzns(false), - Playground(false), - EmitStackPromotionChecks(false), UseSingleModuleLLVMEmission(false), - FunctionSections(false), PrintInlineTree(false), AlwaysCompile(false), + Playground(false), EmitStackPromotionChecks(false), + UseSingleModuleLLVMEmission(false), FunctionSections(false), + PrintInlineTree(false), AlwaysCompile(false), EmbedMode(IRGenEmbedMode::None), LLVMLTOKind(IRGenLLVMLTOKind::None), SwiftAsyncFramePointer(SwiftAsyncFramePointerKind::Auto), HasValueNamesSetting(false), ValueNames(false), @@ -538,13 +547,12 @@ public: WitnessMethodElimination(false), ConditionalRuntimeRecords(false), InternalizeAtLink(false), InternalizeSymbols(false), EmitGenericRODatas(false), NoPreallocatedInstantiationCaches(false), - DisableReadonlyStaticObjects(false), - CollocatedMetadataFunctions(false), - ColocateTypeDescriptors(true), - UseRelativeProtocolWitnessTables(false), CmdArgs(), - SanitizeCoverage(llvm::SanitizerCoverageOptions()), + DisableReadonlyStaticObjects(false), CollocatedMetadataFunctions(false), + ColocateTypeDescriptors(true), UseRelativeProtocolWitnessTables(false), + CmdArgs(), SanitizeCoverage(llvm::SanitizerCoverageOptions()), TypeInfoFilter(TypeInfoDumpFilter::All), - PlatformCCallingConvention(llvm::CallingConv::C) { + PlatformCCallingConvention(llvm::CallingConv::C), UseCASBackend(false), + CASObjMode(llvm::CASBackendMode::Native) { #ifndef NDEBUG DisableRoundTripDebugTypes = false; #else diff --git a/include/swift/AST/Import.h b/include/swift/AST/Import.h index 2f2096a830c..e274a7cf183 100644 --- a/include/swift/AST/Import.h +++ b/include/swift/AST/Import.h @@ -776,7 +776,7 @@ struct DenseMapInfo> { SourceLocDMI::getEmptyKey(), ImportOptionsDMI::getEmptyKey(), StringRefDMI::getEmptyKey(), - {}, {}, None, + {}, {}, llvm::None, swift::AccessLevel::Public, {}); } static inline AttributedImport getTombstoneKey() { @@ -784,7 +784,7 @@ struct DenseMapInfo> { SourceLocDMI::getEmptyKey(), ImportOptionsDMI::getTombstoneKey(), StringRefDMI::getTombstoneKey(), - {}, {}, None, + {}, {}, llvm::None, swift::AccessLevel::Public, {}); } static inline unsigned getHashValue(const AttributedImport &import) { diff --git a/include/swift/AST/Module.h b/include/swift/AST/Module.h index 17de1ac41f6..b1eb3ac1a5c 100644 --- a/include/swift/AST/Module.h +++ b/include/swift/AST/Module.h @@ -33,6 +33,7 @@ #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SetVector.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/ErrorHandling.h" diff --git a/include/swift/AST/ModuleLoader.h b/include/swift/AST/ModuleLoader.h index 416c587fe26..2a15923ee31 100644 --- a/include/swift/AST/ModuleLoader.h +++ b/include/swift/AST/ModuleLoader.h @@ -24,6 +24,7 @@ #include "swift/Basic/LLVM.h" #include "swift/Basic/Located.h" #include "swift/Basic/SourceLoc.h" +#include "clang/Basic/FileManager.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SetVector.h" #include "llvm/ADT/StringSet.h" diff --git a/include/swift/AST/ResilienceExpansion.h b/include/swift/AST/ResilienceExpansion.h index b4319d3afb9..a381964ef4c 100644 --- a/include/swift/AST/ResilienceExpansion.h +++ b/include/swift/AST/ResilienceExpansion.h @@ -14,6 +14,7 @@ #define SWIFT_AST_RESILIENCE_EXPANSION_H #include "llvm/Support/raw_ostream.h" +#include "llvm/Support/ErrorHandling.h" namespace swift { diff --git a/include/swift/AST/SearchPathOptions.h b/include/swift/AST/SearchPathOptions.h index dd4c8baf8f7..97eed1314c4 100644 --- a/include/swift/AST/SearchPathOptions.h +++ b/include/swift/AST/SearchPathOptions.h @@ -19,6 +19,8 @@ #include "llvm/ADT/Hashing.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/StringMap.h" +#include "llvm/ADT/Optional.h" +#include "llvm/ADT/None.h" #include "llvm/Support/Error.h" #include "llvm/Support/VirtualFileSystem.h" diff --git a/include/swift/Basic/BlotMapVector.h b/include/swift/Basic/BlotMapVector.h index 49b902cc686..16657370c3f 100644 --- a/include/swift/Basic/BlotMapVector.h +++ b/include/swift/Basic/BlotMapVector.h @@ -16,6 +16,7 @@ #include "llvm/ADT/DenseMap.h" #include "swift/Basic/LLVM.h" #include "swift/Basic/Range.h" +#include "llvm/ADT/Optional.h" #include namespace swift { diff --git a/include/swift/Basic/Cache.h b/include/swift/Basic/Cache.h index aca3761e2eb..580a9dcc05c 100644 --- a/include/swift/Basic/Cache.h +++ b/include/swift/Basic/Cache.h @@ -15,8 +15,9 @@ #include "llvm/ADT/DenseMapInfo.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" -#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" +#include "llvm/ADT/StringRef.h" namespace swift { namespace sys { diff --git a/include/swift/Basic/ClusteredBitVector.h b/include/swift/Basic/ClusteredBitVector.h index 4a623fb1a52..1db3b461afc 100644 --- a/include/swift/Basic/ClusteredBitVector.h +++ b/include/swift/Basic/ClusteredBitVector.h @@ -216,7 +216,7 @@ public: /// Count the number of set bits in this vector. size_t count() const { - return Bits ? Bits.value().countPopulation() : 0; + return Bits ? Bits.value().popcount() : 0; } /// Determine if there are any bits set in this vector. diff --git a/include/swift/Basic/EncodedSequence.h b/include/swift/Basic/EncodedSequence.h index 9378b4aea92..8b041731d5d 100644 --- a/include/swift/Basic/EncodedSequence.h +++ b/include/swift/Basic/EncodedSequence.h @@ -25,7 +25,7 @@ #include "swift/Basic/LLVM.h" #include "swift/Basic/PrefixMap.h" #include "llvm/ADT/ArrayRef.h" -#include "llvm/Support/Host.h" +#include "llvm/TargetParser/Host.h" #include "llvm/Support/TrailingObjects.h" #include diff --git a/include/swift/Basic/Fingerprint.h b/include/swift/Basic/Fingerprint.h index 8e6327a6c5a..a731b8af1da 100644 --- a/include/swift/Basic/Fingerprint.h +++ b/include/swift/Basic/Fingerprint.h @@ -18,6 +18,7 @@ #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" +#include "llvm/Support/raw_ostream.h" #include diff --git a/include/swift/Basic/FixedBitSet.h b/include/swift/Basic/FixedBitSet.h index df72afab4f8..20fc60ffe33 100644 --- a/include/swift/Basic/FixedBitSet.h +++ b/include/swift/Basic/FixedBitSet.h @@ -218,9 +218,8 @@ public: ValueType operator*() const { assert(remainingChunk && "dereferencing a completed iterator"); - return ValueType(chunkIndex * chunkSize - + llvm::findFirstSet(remainingChunk, - llvm::ZB_Undefined)); + return ValueType(chunkIndex * chunkSize + + llvm::countr_zero(remainingChunk)); } bool operator==(const iterator &other) const { diff --git a/include/swift/Basic/ImmutablePointerSet.h b/include/swift/Basic/ImmutablePointerSet.h index c1f73f08919..2d833aac4c4 100644 --- a/include/swift/Basic/ImmutablePointerSet.h +++ b/include/swift/Basic/ImmutablePointerSet.h @@ -48,10 +48,11 @@ #ifndef SWIFT_BASIC_IMMUTABLEPOINTERSET_H #define SWIFT_BASIC_IMMUTABLEPOINTERSET_H -#include "swift/Basic/STLExtras.h" #include "swift/Basic/NullablePtr.h" -#include "llvm/Support/Allocator.h" +#include "swift/Basic/STLExtras.h" +#include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/FoldingSet.h" +#include "llvm/Support/Allocator.h" #include #include diff --git a/include/swift/Basic/LLVM.h b/include/swift/Basic/LLVM.h index d6514765b2f..827d360b800 100644 --- a/include/swift/Basic/LLVM.h +++ b/include/swift/Basic/LLVM.h @@ -53,7 +53,6 @@ namespace llvm { template class SmallVector; #endif template class SmallString; - template class SmallSetVector; #if SWIFT_LLVM_ODR_SAFE template class ArrayRef; template class MutableArrayRef; @@ -93,7 +92,6 @@ namespace swift { using llvm::SmallBitVector; using llvm::SmallPtrSet; using llvm::SmallPtrSetImpl; - using llvm::SmallSetVector; using llvm::SmallString; #if SWIFT_LLVM_ODR_SAFE using llvm::SmallVector; diff --git a/include/swift/Basic/LLVMExtras.h b/include/swift/Basic/LLVMExtras.h new file mode 100644 index 00000000000..1f21d808a5b --- /dev/null +++ b/include/swift/Basic/LLVMExtras.h @@ -0,0 +1,36 @@ +//===--- LLVMExtras.h -----------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// +// +// This file provides additional functionality on top of LLVM types +// +//===----------------------------------------------------------------------===// + +#ifndef SWIFT_BASIC_LLVMEXTRAS_H +#define SWIFT_BASIC_LLVMEXTRAS_H + +#include "llvm/ADT/DenseSet.h" +#include "llvm/ADT/SetVector.h" +#include "llvm/ADT/SmallVector.h" + +namespace swift { + +/// A SetVector that does no allocations under the specified size +/// +/// swift::SmallSetVector provides the old SmallSetVector semantics that allow +/// storing types that don't have `operator==`. +template +using SmallSetVector = llvm::SetVector, + llvm::SmallDenseSet>>; + +} // namespace swift + +#endif // SWIFT_BASIC_LLVMEXTRAS_H diff --git a/include/swift/Basic/LangOptions.h b/include/swift/Basic/LangOptions.h index fda64a4c9ad..61e836eef87 100644 --- a/include/swift/Basic/LangOptions.h +++ b/include/swift/Basic/LangOptions.h @@ -32,7 +32,7 @@ #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/Support/Regex.h" #include "llvm/Support/VersionTuple.h" #include "llvm/Support/raw_ostream.h" diff --git a/include/swift/Basic/MultiMapCache.h b/include/swift/Basic/MultiMapCache.h index 2d6840f1527..e72d61050fa 100644 --- a/include/swift/Basic/MultiMapCache.h +++ b/include/swift/Basic/MultiMapCache.h @@ -16,6 +16,9 @@ #include "swift/Basic/LLVM.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" +#include "llvm/ADT/Optional.h" +#include "llvm/ADT/None.h" +#include "swift/Basic/STLExtras.h" namespace swift { @@ -61,7 +64,8 @@ public: // If we already have a cached value, just return the cached value. if (!iter.second) { - return iter.first->second.transform( + + return swift::transform(iter.first->second, [&](std::tuple startLengthRange) { return llvm::makeArrayRef(data).slice( std::get(startLengthRange), diff --git a/include/swift/Basic/Program.h b/include/swift/Basic/Program.h index 6efa12b4077..3571cd5c94a 100644 --- a/include/swift/Basic/Program.h +++ b/include/swift/Basic/Program.h @@ -14,6 +14,7 @@ #define SWIFT_BASIC_PROGRAM_H #include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/ErrorOr.h" diff --git a/include/swift/Basic/STLExtras.h b/include/swift/Basic/STLExtras.h index 3abee1f1e08..a5d05f6775e 100644 --- a/include/swift/Basic/STLExtras.h +++ b/include/swift/Basic/STLExtras.h @@ -28,6 +28,7 @@ #include #include #include +#include namespace swift { @@ -783,6 +784,17 @@ void emplace_back_all(VectorType &vector, ValueType &&value, template void emplace_back_all(VectorType &vector) {} +/// Apply a function to the value if present; otherwise return None. +template +auto transform(const llvm::Optional &value, + const Function &operation) + -> llvm::Optional { + + if (value) { + return operation(*value); + } + return llvm::None; +} } // end namespace swift #endif // SWIFT_BASIC_STLEXTRAS_H diff --git a/include/swift/Basic/Sanitizers.def b/include/swift/Basic/Sanitizers.def index 079f8350b08..d79fecb5951 100644 --- a/include/swift/Basic/Sanitizers.def +++ b/include/swift/Basic/Sanitizers.def @@ -24,6 +24,6 @@ SANITIZER(0, Address, address, asan) SANITIZER(1, Thread, thread, tsan) SANITIZER(2, Undefined, undefined, ubsan) SANITIZER(3, Fuzzer, fuzzer, fuzzer) -SANITIZER(4, Scudo, scudo, scudo) +SANITIZER(4, Scudo, scudo, scudo_standalone) #undef SANITIZER diff --git a/include/swift/Basic/TargetInfo.h b/include/swift/Basic/TargetInfo.h index eae57eddd47..c43fabe96e5 100644 --- a/include/swift/Basic/TargetInfo.h +++ b/include/swift/Basic/TargetInfo.h @@ -19,6 +19,8 @@ #include "swift/Basic/LLVM.h" +#include "llvm/ADT/Optional.h" + namespace llvm { class Triple; class VersionTuple; diff --git a/include/swift/ClangImporter/CXXMethodBridging.h b/include/swift/ClangImporter/CXXMethodBridging.h index 3f2507718a3..51b3cf31e46 100644 --- a/include/swift/ClangImporter/CXXMethodBridging.h +++ b/include/swift/ClangImporter/CXXMethodBridging.h @@ -26,7 +26,7 @@ struct CXXMethodBridging { nameKind != NameKind::lower && nameKind != NameKind::snake) return Kind::unknown; - if (getClangName().startswith_insensitive("set")) { + if (getClangName().starts_with_insensitive("set")) { // Setters only have one parameter. if (method->getNumParams() != 1) return Kind::unknown; @@ -43,7 +43,7 @@ struct CXXMethodBridging { if (method->getReturnType()->isVoidType()) return Kind::unknown; - if (getClangName().startswith_insensitive("get")) { + if (getClangName().starts_with_insensitive("get")) { // Getters cannot take arguments. if (method->getNumParams() != 0) return Kind::unknown; diff --git a/include/swift/ClangImporter/ClangImporter.h b/include/swift/ClangImporter/ClangImporter.h index 3b599dbb260..cf2c80117d1 100644 --- a/include/swift/ClangImporter/ClangImporter.h +++ b/include/swift/ClangImporter/ClangImporter.h @@ -436,7 +436,7 @@ public: using RemapPathCallback = llvm::function_ref; llvm::SmallVector, 1> bridgeClangModuleDependencies( - const clang::tooling::dependencies::ModuleDepsGraph &clangDependencies, + clang::tooling::dependencies::ModuleDepsGraph &clangDependencies, StringRef moduleOutputPath, RemapPathCallback remapPath = nullptr); llvm::SmallVector, 1> diff --git a/include/swift/Driver/Action.h b/include/swift/Driver/Action.h index abd23f492ba..1c88bd8c267 100644 --- a/include/swift/Driver/Action.h +++ b/include/swift/Driver/Action.h @@ -17,6 +17,7 @@ #include "swift/Basic/LLVM.h" #include "swift/Driver/Util.h" #include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/None.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/Support/Chrono.h" diff --git a/include/swift/Driver/ToolChain.h b/include/swift/Driver/ToolChain.h index 5829dd543fd..e13906142d8 100644 --- a/include/swift/Driver/ToolChain.h +++ b/include/swift/Driver/ToolChain.h @@ -18,7 +18,7 @@ #include "swift/Driver/Action.h" #include "swift/Driver/Job.h" #include "swift/Option/Options.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/Option/Option.h" #include diff --git a/include/swift/Frontend/CompileJobCacheResult.h b/include/swift/Frontend/CompileJobCacheResult.h index bc704664365..0fb516b813c 100644 --- a/include/swift/Frontend/CompileJobCacheResult.h +++ b/include/swift/Frontend/CompileJobCacheResult.h @@ -50,7 +50,7 @@ public: Output getOutput(size_t I) const; /// Retrieves a specific output specified by \p Kind, if it exists. - llvm::Optional getOutput(file_types::ID Kind) const; + std::optional getOutput(file_types::ID Kind) const; /// Print this result to \p OS. llvm::Error print(llvm::raw_ostream &OS); diff --git a/include/swift/Frontend/Frontend.h b/include/swift/Frontend/Frontend.h index 53dcd46670a..867de5f0824 100644 --- a/include/swift/Frontend/Frontend.h +++ b/include/swift/Frontend/Frontend.h @@ -51,7 +51,7 @@ #include "llvm/Option/ArgList.h" #include "llvm/Support/BLAKE3.h" #include "llvm/Support/HashingOutputBackend.h" -#include "llvm/Support/Host.h" +#include "llvm/TargetParser/Host.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/VirtualOutputBackend.h" @@ -165,6 +165,10 @@ public: return LangOpts.Target.str(); } + bool requiresCAS() const { + return FrontendOpts.EnableCaching || FrontendOpts.UseCASBackend; + } + void setClangModuleCachePath(StringRef Path) { ClangImporterOpts.ModuleCachePath = Path.str(); } diff --git a/include/swift/Frontend/FrontendOptions.h b/include/swift/Frontend/FrontendOptions.h index 6e2c7ebaead..f79b7a5cda5 100644 --- a/include/swift/Frontend/FrontendOptions.h +++ b/include/swift/Frontend/FrontendOptions.h @@ -14,15 +14,17 @@ #define SWIFT_FRONTEND_FRONTENDOPTIONS_H #include "swift/Basic/FileTypes.h" -#include "swift/Basic/Version.h" #include "swift/Basic/PathRemapper.h" +#include "swift/Basic/Version.h" #include "swift/Frontend/FrontendInputsAndOutputs.h" #include "swift/Frontend/InputFile.h" +#include "clang/CAS/CASOptions.h" #include "llvm/ADT/Hashing.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringMap.h" -#include "clang/CAS/CASOptions.h" +#include "llvm/MC/MCTargetOptions.h" +#include #include #include @@ -148,6 +150,15 @@ public: /// CacheKey for input file. std::string InputFileKey; + /// Enable using the LLVM MCCAS backend for object file output. + bool UseCASBackend = false; + + /// The output mode for the CAS Backend. + llvm::CASBackendMode CASObjMode; + + /// Emit a .casid file next to the object file if CAS Backend is used. + bool EmitCASIDFile = false; + /// CacheReplay PrefixMap. std::vector CacheReplayPrefixMap; diff --git a/include/swift/IDE/CodeCompletionString.h b/include/swift/IDE/CodeCompletionString.h index f5e40309743..2ef1b7a03b9 100644 --- a/include/swift/IDE/CodeCompletionString.h +++ b/include/swift/IDE/CodeCompletionString.h @@ -16,6 +16,8 @@ #include "swift/Basic/Debug.h" #include "swift/Basic/LLVM.h" #include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/None.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Error.h" diff --git a/include/swift/IDE/ModuleInterfacePrinting.h b/include/swift/IDE/ModuleInterfacePrinting.h index 05587bc3a2f..a8ce488bfab 100644 --- a/include/swift/IDE/ModuleInterfacePrinting.h +++ b/include/swift/IDE/ModuleInterfacePrinting.h @@ -16,6 +16,8 @@ #include "swift/Basic/LLVM.h" #include "swift/Basic/OptionSet.h" +#include "llvm/ADT/Optional.h" + #include #include diff --git a/include/swift/Immediate/SwiftMaterializationUnit.h b/include/swift/Immediate/SwiftMaterializationUnit.h index 93e9491220d..68f2b93e3fe 100644 --- a/include/swift/Immediate/SwiftMaterializationUnit.h +++ b/include/swift/Immediate/SwiftMaterializationUnit.h @@ -98,9 +98,11 @@ private: llvm::Error notifyFailed(llvm::orc::MaterializationResponsibility &MR) override; - llvm::Error notifyRemovingResources(llvm::orc::ResourceKey K) override; + llvm::Error notifyRemovingResources(llvm::orc::JITDylib &JD, + llvm::orc::ResourceKey K) override; - void notifyTransferringResources(llvm::orc::ResourceKey DstKey, + void notifyTransferringResources(llvm::orc::JITDylib &JD, + llvm::orc::ResourceKey DstKey, llvm::orc::ResourceKey SrcKey) override; }; diff --git a/include/swift/LLVMPasses/Passes.h b/include/swift/LLVMPasses/Passes.h index 1c727f390ea..c434310bdc0 100644 --- a/include/swift/LLVMPasses/Passes.h +++ b/include/swift/LLVMPasses/Passes.h @@ -144,12 +144,6 @@ namespace swift { llvm::ModuleAnalysisManager &AM); }; - struct SwiftDbgAddrBlockSplitterPass - : public llvm::PassInfoMixin { - llvm::PreservedAnalyses run(llvm::Function &F, - llvm::FunctionAnalysisManager &AM); - }; - struct InlineTreePrinterPass : public llvm::PassInfoMixin { llvm::PreservedAnalyses run(llvm::Module &M, diff --git a/include/swift/LLVMPasses/PassesFwd.h b/include/swift/LLVMPasses/PassesFwd.h index 3141ef25cd4..c4cc31d634b 100644 --- a/include/swift/LLVMPasses/PassesFwd.h +++ b/include/swift/LLVMPasses/PassesFwd.h @@ -24,7 +24,6 @@ namespace llvm { void initializeSwiftARCContractPass(PassRegistry &); void initializeInlineTreePrinterPass(PassRegistry &); void initializeLegacySwiftMergeFunctionsPass(PassRegistry &); - void initializeSwiftDbgAddrBlockSplitterPass(PassRegistry &); } namespace swift { @@ -33,7 +32,6 @@ namespace swift { llvm::ModulePass *createInlineTreePrinterPass(); llvm::ModulePass *createLegacySwiftMergeFunctionsPass(bool ptrAuthEnabled, unsigned ptrAuthKey); - llvm::FunctionPass *createSwiftDbgAddrBlockSplitter(); llvm::ImmutablePass *createSwiftAAWrapperPass(); } // end namespace swift diff --git a/include/swift/Option/Options.td b/include/swift/Option/Options.td index 900236a10bf..b38fe2ac9c4 100644 --- a/include/swift/Option/Options.td +++ b/include/swift/Option/Options.td @@ -1900,6 +1900,19 @@ def external_plugin_path : Separate<["-"], "external-plugin-path">, Group, HelpText<"Add directory to the plugin search path with a plugin server executable">, MetaVarName<"#">; + +def cas_backend: Flag<["-"], "cas-backend">, + Flags<[FrontendOption, NoDriverOption]>, + HelpText<"Enable using CASBackend for object file output">; + +def cas_backend_mode: Joined<["-"], "cas-backend-mode=">, + Flags<[FrontendOption, NoDriverOption]>, + HelpText<"CASBackendMode for output kind">, + MetaVarName<"native|casid|verify">; + +def cas_emit_casid_file: Flag<["-"], "cas-emit-casid-file">, + Flags<[FrontendOption, NoDriverOption]>, + HelpText<"Emit .casid file next to object file when CAS Backend is enabled">; def load_plugin_library: Separate<["-"], "load-plugin-library">, Group, diff --git a/include/swift/Option/SanitizerOptions.h b/include/swift/Option/SanitizerOptions.h index 1a5f58cc2b7..e43e6765efc 100644 --- a/include/swift/Option/SanitizerOptions.h +++ b/include/swift/Option/SanitizerOptions.h @@ -15,7 +15,7 @@ #include "swift/Basic/Sanitizers.h" #include "swift/Basic/OptionSet.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" // FIXME: This include is just for llvm::SanitizerCoverageOptions. We should diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm-c/DataTypes.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm-c/DataTypes.h new file mode 100644 index 00000000000..4eb0ac97d97 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm-c/DataTypes.h @@ -0,0 +1,80 @@ +/*===-- include/llvm-c/DataTypes.h - Define fixed size types ------*- C -*-===*\ +|* *| +|* 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 *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This file contains definitions to figure out the size of _HOST_ data types.*| +|* This file is important because different host OS's define different macros,*| +|* which makes portability tough. This file exports the following *| +|* definitions: *| +|* *| +|* [u]int(32|64)_t : typedefs for signed and unsigned 32/64 bit system types*| +|* [U]INT(8|16|32|64)_(MIN|MAX) : Constants for the min and max values. *| +|* *| +|* No library is required when using these functions. *| +|* *| +|*===----------------------------------------------------------------------===*/ + +/* Please leave this file C-compatible. */ + +#ifndef LLVM_C_DATATYPES_H +#define LLVM_C_DATATYPES_H + +#include +#include + +#ifndef _MSC_VER + +#if !defined(UINT32_MAX) +# error "The standard header is not C++11 compliant. Must #define "\ + "__STDC_LIMIT_MACROS before #including llvm-c/DataTypes.h" +#endif + +#if !defined(UINT32_C) +# error "The standard header is not C++11 compliant. Must #define "\ + "__STDC_CONSTANT_MACROS before #including llvm-c/DataTypes.h" +#endif + +/* Note that includes , if this is a C99 system. */ +#include + +#ifdef _AIX +// GCC is strict about defining large constants: they must have LL modifier. +#undef INT64_MAX +#undef INT64_MIN +#endif + +#else /* _MSC_VER */ +#ifdef __cplusplus +#include +#include +#else +#include +#include +#endif +#include + +#if defined(_WIN64) +typedef signed __int64 ssize_t; +#else +typedef signed int ssize_t; +#endif /* _WIN64 */ + +#endif /* _MSC_VER */ + +/* Set defaults for constants which we cannot find. */ +#if !defined(INT64_MAX) +# define INT64_MAX 9223372036854775807LL +#endif +#if !defined(INT64_MIN) +# define INT64_MIN ((-INT64_MAX)-1) +#endif +#if !defined(UINT64_MAX) +# define UINT64_MAX 0xffffffffffffffffULL +#endif + +#endif /* LLVM_C_DATATYPES_H */ diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm-c/Error.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm-c/Error.h new file mode 100644 index 00000000000..c3baaf65186 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm-c/Error.h @@ -0,0 +1,83 @@ +/*===------- llvm-c/Error.h - llvm::Error class C Interface -------*- C -*-===*\ +|* *| +|* 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 *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This file defines the C interface to LLVM's Error class. *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifndef LLVM_C_ERROR_H +#define LLVM_C_ERROR_H + +#include "llvm-c/ExternC.h" + +LLVM_C_EXTERN_C_BEGIN + +/** + * @defgroup LLVMCError Error Handling + * @ingroup LLVMC + * + * @{ + */ + +#define LLVMErrorSuccess 0 + +/** + * Opaque reference to an error instance. Null serves as the 'success' value. + */ +typedef struct LLVMOpaqueError *LLVMErrorRef; + +/** + * Error type identifier. + */ +typedef const void *LLVMErrorTypeId; + +/** + * Returns the type id for the given error instance, which must be a failure + * value (i.e. non-null). + */ +LLVMErrorTypeId LLVMGetErrorTypeId(LLVMErrorRef Err); + +/** + * Dispose of the given error without handling it. This operation consumes the + * error, and the given LLVMErrorRef value is not usable once this call returns. + * Note: This method *only* needs to be called if the error is not being passed + * to some other consuming operation, e.g. LLVMGetErrorMessage. + */ +void LLVMConsumeError(LLVMErrorRef Err); + +/** + * Returns the given string's error message. This operation consumes the error, + * and the given LLVMErrorRef value is not usable once this call returns. + * The caller is responsible for disposing of the string by calling + * LLVMDisposeErrorMessage. + */ +char *LLVMGetErrorMessage(LLVMErrorRef Err); + +/** + * Dispose of the given error message. + */ +void LLVMDisposeErrorMessage(char *ErrMsg); + +/** + * Returns the type id for llvm StringError. + */ +LLVMErrorTypeId LLVMGetStringErrorTypeId(void); + +/** + * Create a StringError. + */ +LLVMErrorRef LLVMCreateStringError(const char *ErrMsg); + +/** + * @} + */ + +LLVM_C_EXTERN_C_END + +#endif diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm-c/ExternC.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm-c/ExternC.h new file mode 100644 index 00000000000..dfa21bdc085 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm-c/ExternC.h @@ -0,0 +1,39 @@ +/*===- llvm-c/ExternC.h - Wrapper for 'extern "C"' ----------------*- C -*-===*\ +|* *| +|* 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 *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This file defines an 'extern "C"' wrapper *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifndef LLVM_C_EXTERNC_H +#define LLVM_C_EXTERNC_H + +#ifdef __clang__ +#define LLVM_C_STRICT_PROTOTYPES_BEGIN \ + _Pragma("clang diagnostic push") \ + _Pragma("clang diagnostic error \"-Wstrict-prototypes\"") +#define LLVM_C_STRICT_PROTOTYPES_END _Pragma("clang diagnostic pop") +#else +#define LLVM_C_STRICT_PROTOTYPES_BEGIN +#define LLVM_C_STRICT_PROTOTYPES_END +#endif + +#ifdef __cplusplus +#define LLVM_C_EXTERN_C_BEGIN \ + extern "C" { \ + LLVM_C_STRICT_PROTOTYPES_BEGIN +#define LLVM_C_EXTERN_C_END \ + LLVM_C_STRICT_PROTOTYPES_END \ + } +#else +#define LLVM_C_EXTERN_C_BEGIN LLVM_C_STRICT_PROTOTYPES_BEGIN +#define LLVM_C_EXTERN_C_END LLVM_C_STRICT_PROTOTYPES_END +#endif + +#endif diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm-c/Types.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm-c/Types.h new file mode 100644 index 00000000000..4e9967372d7 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm-c/Types.h @@ -0,0 +1,173 @@ +/*===-- llvm-c/Support.h - C Interface Types declarations ---------*- C -*-===*\ +|* *| +|* 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 *| +|* *| +|*===----------------------------------------------------------------------===*| +|* *| +|* This file defines types used by the C interface to LLVM. *| +|* *| +\*===----------------------------------------------------------------------===*/ + +#ifndef LLVM_C_TYPES_H +#define LLVM_C_TYPES_H + +#include "llvm-c/DataTypes.h" +#include "llvm-c/ExternC.h" + +LLVM_C_EXTERN_C_BEGIN + +/** + * @defgroup LLVMCSupportTypes Types and Enumerations + * + * @{ + */ + +typedef int LLVMBool; + +/* Opaque types. */ + +/** + * LLVM uses a polymorphic type hierarchy which C cannot represent, therefore + * parameters must be passed as base types. Despite the declared types, most + * of the functions provided operate only on branches of the type hierarchy. + * The declared parameter names are descriptive and specify which type is + * required. Additionally, each type hierarchy is documented along with the + * functions that operate upon it. For more detail, refer to LLVM's C++ code. + * If in doubt, refer to Core.cpp, which performs parameter downcasts in the + * form unwrap(Param). + */ + +/** + * Used to pass regions of memory through LLVM interfaces. + * + * @see llvm::MemoryBuffer + */ +typedef struct LLVMOpaqueMemoryBuffer *LLVMMemoryBufferRef; + +/** + * The top-level container for all LLVM global data. See the LLVMContext class. + */ +typedef struct LLVMOpaqueContext *LLVMContextRef; + +/** + * The top-level container for all other LLVM Intermediate Representation (IR) + * objects. + * + * @see llvm::Module + */ +typedef struct LLVMOpaqueModule *LLVMModuleRef; + +/** + * Each value in the LLVM IR has a type, an LLVMTypeRef. + * + * @see llvm::Type + */ +typedef struct LLVMOpaqueType *LLVMTypeRef; + +/** + * Represents an individual value in LLVM IR. + * + * This models llvm::Value. + */ +typedef struct LLVMOpaqueValue *LLVMValueRef; + +/** + * Represents a basic block of instructions in LLVM IR. + * + * This models llvm::BasicBlock. + */ +typedef struct LLVMOpaqueBasicBlock *LLVMBasicBlockRef; + +/** + * Represents an LLVM Metadata. + * + * This models llvm::Metadata. + */ +typedef struct LLVMOpaqueMetadata *LLVMMetadataRef; + +/** + * Represents an LLVM Named Metadata Node. + * + * This models llvm::NamedMDNode. + */ +typedef struct LLVMOpaqueNamedMDNode *LLVMNamedMDNodeRef; + +/** + * Represents an entry in a Global Object's metadata attachments. + * + * This models std::pair + */ +typedef struct LLVMOpaqueValueMetadataEntry LLVMValueMetadataEntry; + +/** + * Represents an LLVM basic block builder. + * + * This models llvm::IRBuilder. + */ +typedef struct LLVMOpaqueBuilder *LLVMBuilderRef; + +/** + * Represents an LLVM debug info builder. + * + * This models llvm::DIBuilder. + */ +typedef struct LLVMOpaqueDIBuilder *LLVMDIBuilderRef; + +/** + * Interface used to provide a module to JIT or interpreter. + * This is now just a synonym for llvm::Module, but we have to keep using the + * different type to keep binary compatibility. + */ +typedef struct LLVMOpaqueModuleProvider *LLVMModuleProviderRef; + +/** @see llvm::PassManagerBase */ +typedef struct LLVMOpaquePassManager *LLVMPassManagerRef; + +/** + * Used to get the users and usees of a Value. + * + * @see llvm::Use */ +typedef struct LLVMOpaqueUse *LLVMUseRef; + +/** + * Used to represent an attributes. + * + * @see llvm::Attribute + */ +typedef struct LLVMOpaqueAttributeRef *LLVMAttributeRef; + +/** + * @see llvm::DiagnosticInfo + */ +typedef struct LLVMOpaqueDiagnosticInfo *LLVMDiagnosticInfoRef; + +/** + * @see llvm::Comdat + */ +typedef struct LLVMComdat *LLVMComdatRef; + +/** + * @see llvm::Module::ModuleFlagEntry + */ +typedef struct LLVMOpaqueModuleFlagEntry LLVMModuleFlagEntry; + +/** + * @see llvm::JITEventListener + */ +typedef struct LLVMOpaqueJITEventListener *LLVMJITEventListenerRef; + +/** + * @see llvm::object::Binary + */ +typedef struct LLVMOpaqueBinary *LLVMBinaryRef; + +/** + * @} + */ + +LLVM_C_EXTERN_C_END + +#endif diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/ADT/BitmaskEnum.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/ADT/BitmaskEnum.h new file mode 100644 index 00000000000..976fddde725 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/ADT/BitmaskEnum.h @@ -0,0 +1,190 @@ +//===-- llvm/ADT/BitmaskEnum.h ----------------------------------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_ADT_BITMASKENUM_H +#define LLVM_ADT_BITMASKENUM_H + +#include +#include +#include + +#include "llvm/Support/MathExtras.h" + +/// LLVM_MARK_AS_BITMASK_ENUM lets you opt in an individual enum type so you can +/// perform bitwise operations on it without putting static_cast everywhere. +/// +/// \code +/// enum MyEnum { +/// E1 = 1, E2 = 2, E3 = 4, E4 = 8, +/// LLVM_MARK_AS_BITMASK_ENUM(/* LargestValue = */ E4) +/// }; +/// +/// void Foo() { +/// MyEnum A = (E1 | E2) & E3 ^ ~E4; // Look, ma: No static_cast! +/// } +/// \endcode +/// +/// Normally when you do a bitwise operation on an enum value, you get back an +/// instance of the underlying type (e.g. int). But using this macro, bitwise +/// ops on your enum will return you back instances of the enum. This is +/// particularly useful for enums which represent a combination of flags. +/// +/// The parameter to LLVM_MARK_AS_BITMASK_ENUM should be the largest individual +/// value in your enum. +/// +/// All of the enum's values must be non-negative. +#define LLVM_MARK_AS_BITMASK_ENUM(LargestValue) \ + LLVM_BITMASK_LARGEST_ENUMERATOR = LargestValue + +/// LLVM_DECLARE_ENUM_AS_BITMASK can be used to declare an enum type as a bit +/// set, so that bitwise operation on such enum does not require static_cast. +/// +/// \code +/// enum MyEnum { E1 = 1, E2 = 2, E3 = 4, E4 = 8 }; +/// LLVM_DECLARE_ENUM_AS_BITMASK(MyEnum, E4); +/// +/// void Foo() { +/// MyEnum A = (E1 | E2) & E3 ^ ~E4; // No static_cast +/// } +/// \endcode +/// +/// The second parameter to LLVM_DECLARE_ENUM_AS_BITMASK specifies the largest +/// bit value of the enum type. +/// +/// LLVM_DECLARE_ENUM_AS_BITMASK should be used in llvm namespace. +/// +/// This a non-intrusive alternative for LLVM_MARK_AS_BITMASK_ENUM. It allows +/// declaring more than one non-scoped enumerations as bitmask types in the same +/// scope. Otherwise it provides the same functionality as +/// LLVM_MARK_AS_BITMASK_ENUM. +#define LLVM_DECLARE_ENUM_AS_BITMASK(Enum, LargestValue) \ + template <> struct is_bitmask_enum : std::true_type {}; \ + template <> struct largest_bitmask_enum_bit { \ + static constexpr std::underlying_type_t value = LargestValue; \ + } + +/// LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE() pulls the operator overloads used +/// by LLVM_MARK_AS_BITMASK_ENUM into the current namespace. +/// +/// Suppose you have an enum foo::bar::MyEnum. Before using +/// LLVM_MARK_AS_BITMASK_ENUM on MyEnum, you must put +/// LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE() somewhere inside namespace foo or +/// namespace foo::bar. This allows the relevant operator overloads to be found +/// by ADL. +/// +/// You don't need to use this macro in namespace llvm; it's done at the bottom +/// of this file. +#define LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE() \ + using ::llvm::BitmaskEnumDetail::operator~; \ + using ::llvm::BitmaskEnumDetail::operator|; \ + using ::llvm::BitmaskEnumDetail::operator&; \ + using ::llvm::BitmaskEnumDetail::operator^; \ + using ::llvm::BitmaskEnumDetail::operator|=; \ + using ::llvm::BitmaskEnumDetail::operator&=; \ + /* Force a semicolon at the end of this macro. */ \ + using ::llvm::BitmaskEnumDetail::operator^= + +namespace llvm { + +/// Traits class to determine whether an enum has a +/// LLVM_BITMASK_LARGEST_ENUMERATOR enumerator. +template +struct is_bitmask_enum : std::false_type {}; + +template +struct is_bitmask_enum< + E, std::enable_if_t= 0>> + : std::true_type {}; + +/// Trait class to determine bitmask enumeration largest bit. +template struct largest_bitmask_enum_bit; + +template +struct largest_bitmask_enum_bit< + E, std::enable_if_t= 0>> { + using UnderlyingTy = std::underlying_type_t; + static constexpr UnderlyingTy value = + static_cast(E::LLVM_BITMASK_LARGEST_ENUMERATOR); +}; + +namespace BitmaskEnumDetail { + +/// Get a bitmask with 1s in all places up to the high-order bit of E's largest +/// value. +template constexpr std::underlying_type_t Mask() { + // On overflow, NextPowerOf2 returns zero with the type uint64_t, so + // subtracting 1 gives us the mask with all bits set, like we want. + return NextPowerOf2(largest_bitmask_enum_bit::value) - 1; +} + +/// Check that Val is in range for E, and return Val cast to E's underlying +/// type. +template constexpr std::underlying_type_t Underlying(E Val) { + auto U = static_cast>(Val); + assert(U >= 0 && "Negative enum values are not allowed."); + assert(U <= Mask() && "Enum value too large (or largest val too small?)"); + return U; +} + +constexpr unsigned bitWidth(uint64_t Value) { + return Value ? 1 + bitWidth(Value >> 1) : 0; +} + +template ::value>> +constexpr E operator~(E Val) { + return static_cast(~Underlying(Val) & Mask()); +} + +template ::value>> +constexpr E operator|(E LHS, E RHS) { + return static_cast(Underlying(LHS) | Underlying(RHS)); +} + +template ::value>> +constexpr E operator&(E LHS, E RHS) { + return static_cast(Underlying(LHS) & Underlying(RHS)); +} + +template ::value>> +constexpr E operator^(E LHS, E RHS) { + return static_cast(Underlying(LHS) ^ Underlying(RHS)); +} + +// |=, &=, and ^= return a reference to LHS, to match the behavior of the +// operators on builtin types. + +template ::value>> +E &operator|=(E &LHS, E RHS) { + LHS = LHS | RHS; + return LHS; +} + +template ::value>> +E &operator&=(E &LHS, E RHS) { + LHS = LHS & RHS; + return LHS; +} + +template ::value>> +E &operator^=(E &LHS, E RHS) { + LHS = LHS ^ RHS; + return LHS; +} + +} // namespace BitmaskEnumDetail + +// Enable bitmask enums in namespace ::llvm and all nested namespaces. +LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE(); +template ::value>> +constexpr unsigned BitWidth = BitmaskEnumDetail::bitWidth(uint64_t{ + static_cast>( + E::LLVM_BITMASK_LARGEST_ENUMERATOR)}); + +} // namespace llvm + +#endif diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/COFF.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/COFF.h new file mode 100644 index 00000000000..522ee37da6e --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/COFF.h @@ -0,0 +1,817 @@ +//===-- llvm/BinaryFormat/COFF.h --------------------------------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file contains an definitions used in Windows COFF Files. +// +// Structures and enums defined within this file where created using +// information from Microsoft's publicly available PE/COFF format document: +// +// Microsoft Portable Executable and Common Object File Format Specification +// Revision 8.1 - February 15, 2008 +// +// As of 5/2/2010, hosted by Microsoft at: +// http://www.microsoft.com/whdc/system/platform/firmware/pecoff.mspx +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_BINARYFORMAT_COFF_H +#define LLVM_BINARYFORMAT_COFF_H + +#include "llvm/Support/DataTypes.h" +#include + +namespace llvm { +namespace COFF { + +// The maximum number of sections that a COFF object can have (inclusive). +const int32_t MaxNumberOfSections16 = 65279; + +// The PE signature bytes that follows the DOS stub header. +static const char PEMagic[] = {'P', 'E', '\0', '\0'}; + +static const char BigObjMagic[] = { + '\xc7', '\xa1', '\xba', '\xd1', '\xee', '\xba', '\xa9', '\x4b', + '\xaf', '\x20', '\xfa', '\xf6', '\x6a', '\xa4', '\xdc', '\xb8', +}; + +static const char ClGlObjMagic[] = { + '\x38', '\xfe', '\xb3', '\x0c', '\xa5', '\xd9', '\xab', '\x4d', + '\xac', '\x9b', '\xd6', '\xb6', '\x22', '\x26', '\x53', '\xc2', +}; + +// The signature bytes that start a .res file. +static const char WinResMagic[] = { + '\x00', '\x00', '\x00', '\x00', '\x20', '\x00', '\x00', '\x00', + '\xff', '\xff', '\x00', '\x00', '\xff', '\xff', '\x00', '\x00', +}; + +// Sizes in bytes of various things in the COFF format. +enum { + Header16Size = 20, + Header32Size = 56, + NameSize = 8, + Symbol16Size = 18, + Symbol32Size = 20, + SectionSize = 40, + RelocationSize = 10 +}; + +struct header { + uint16_t Machine; + int32_t NumberOfSections; + uint32_t TimeDateStamp; + uint32_t PointerToSymbolTable; + uint32_t NumberOfSymbols; + uint16_t SizeOfOptionalHeader; + uint16_t Characteristics; +}; + +struct BigObjHeader { + enum : uint16_t { MinBigObjectVersion = 2 }; + + uint16_t Sig1; ///< Must be IMAGE_FILE_MACHINE_UNKNOWN (0). + uint16_t Sig2; ///< Must be 0xFFFF. + uint16_t Version; + uint16_t Machine; + uint32_t TimeDateStamp; + uint8_t UUID[16]; + uint32_t unused1; + uint32_t unused2; + uint32_t unused3; + uint32_t unused4; + uint32_t NumberOfSections; + uint32_t PointerToSymbolTable; + uint32_t NumberOfSymbols; +}; + +enum MachineTypes : unsigned { + MT_Invalid = 0xffff, + + IMAGE_FILE_MACHINE_UNKNOWN = 0x0, + IMAGE_FILE_MACHINE_AM33 = 0x1D3, + IMAGE_FILE_MACHINE_AMD64 = 0x8664, + IMAGE_FILE_MACHINE_ARM = 0x1C0, + IMAGE_FILE_MACHINE_ARMNT = 0x1C4, + IMAGE_FILE_MACHINE_ARM64 = 0xAA64, + IMAGE_FILE_MACHINE_ARM64EC = 0xA641, + IMAGE_FILE_MACHINE_ARM64X = 0xA64E, + IMAGE_FILE_MACHINE_EBC = 0xEBC, + IMAGE_FILE_MACHINE_I386 = 0x14C, + IMAGE_FILE_MACHINE_IA64 = 0x200, + IMAGE_FILE_MACHINE_M32R = 0x9041, + IMAGE_FILE_MACHINE_MIPS16 = 0x266, + IMAGE_FILE_MACHINE_MIPSFPU = 0x366, + IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466, + IMAGE_FILE_MACHINE_POWERPC = 0x1F0, + IMAGE_FILE_MACHINE_POWERPCFP = 0x1F1, + IMAGE_FILE_MACHINE_R4000 = 0x166, + IMAGE_FILE_MACHINE_RISCV32 = 0x5032, + IMAGE_FILE_MACHINE_RISCV64 = 0x5064, + IMAGE_FILE_MACHINE_RISCV128 = 0x5128, + IMAGE_FILE_MACHINE_SH3 = 0x1A2, + IMAGE_FILE_MACHINE_SH3DSP = 0x1A3, + IMAGE_FILE_MACHINE_SH4 = 0x1A6, + IMAGE_FILE_MACHINE_SH5 = 0x1A8, + IMAGE_FILE_MACHINE_THUMB = 0x1C2, + IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169 +}; + +template bool isArm64EC(T Machine) { + return Machine == IMAGE_FILE_MACHINE_ARM64EC || + Machine == IMAGE_FILE_MACHINE_ARM64X; +} + +template bool isAnyArm64(T Machine) { + return Machine == IMAGE_FILE_MACHINE_ARM64 || isArm64EC(Machine); +} + +template bool is64Bit(T Machine) { + return Machine == IMAGE_FILE_MACHINE_AMD64 || isAnyArm64(Machine); +} + +enum Characteristics : unsigned { + C_Invalid = 0, + + /// The file does not contain base relocations and must be loaded at its + /// preferred base. If this cannot be done, the loader will error. + IMAGE_FILE_RELOCS_STRIPPED = 0x0001, + /// The file is valid and can be run. + IMAGE_FILE_EXECUTABLE_IMAGE = 0x0002, + /// COFF line numbers have been stripped. This is deprecated and should be + /// 0. + IMAGE_FILE_LINE_NUMS_STRIPPED = 0x0004, + /// COFF symbol table entries for local symbols have been removed. This is + /// deprecated and should be 0. + IMAGE_FILE_LOCAL_SYMS_STRIPPED = 0x0008, + /// Aggressively trim working set. This is deprecated and must be 0. + IMAGE_FILE_AGGRESSIVE_WS_TRIM = 0x0010, + /// Image can handle > 2GiB addresses. + IMAGE_FILE_LARGE_ADDRESS_AWARE = 0x0020, + /// Little endian: the LSB precedes the MSB in memory. This is deprecated + /// and should be 0. + IMAGE_FILE_BYTES_REVERSED_LO = 0x0080, + /// Machine is based on a 32bit word architecture. + IMAGE_FILE_32BIT_MACHINE = 0x0100, + /// Debugging info has been removed. + IMAGE_FILE_DEBUG_STRIPPED = 0x0200, + /// If the image is on removable media, fully load it and copy it to swap. + IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP = 0x0400, + /// If the image is on network media, fully load it and copy it to swap. + IMAGE_FILE_NET_RUN_FROM_SWAP = 0x0800, + /// The image file is a system file, not a user program. + IMAGE_FILE_SYSTEM = 0x1000, + /// The image file is a DLL. + IMAGE_FILE_DLL = 0x2000, + /// This file should only be run on a uniprocessor machine. + IMAGE_FILE_UP_SYSTEM_ONLY = 0x4000, + /// Big endian: the MSB precedes the LSB in memory. This is deprecated + /// and should be 0. + IMAGE_FILE_BYTES_REVERSED_HI = 0x8000 +}; + +enum ResourceTypeID : unsigned { + RID_Cursor = 1, + RID_Bitmap = 2, + RID_Icon = 3, + RID_Menu = 4, + RID_Dialog = 5, + RID_String = 6, + RID_FontDir = 7, + RID_Font = 8, + RID_Accelerator = 9, + RID_RCData = 10, + RID_MessageTable = 11, + RID_Group_Cursor = 12, + RID_Group_Icon = 14, + RID_Version = 16, + RID_DLGInclude = 17, + RID_PlugPlay = 19, + RID_VXD = 20, + RID_AniCursor = 21, + RID_AniIcon = 22, + RID_HTML = 23, + RID_Manifest = 24, +}; + +struct symbol { + char Name[NameSize]; + uint32_t Value; + int32_t SectionNumber; + uint16_t Type; + uint8_t StorageClass; + uint8_t NumberOfAuxSymbols; +}; + +enum SymbolSectionNumber : int32_t { + IMAGE_SYM_DEBUG = -2, + IMAGE_SYM_ABSOLUTE = -1, + IMAGE_SYM_UNDEFINED = 0 +}; + +/// Storage class tells where and what the symbol represents +enum SymbolStorageClass { + SSC_Invalid = 0xff, + + IMAGE_SYM_CLASS_END_OF_FUNCTION = -1, ///< Physical end of function + IMAGE_SYM_CLASS_NULL = 0, ///< No symbol + IMAGE_SYM_CLASS_AUTOMATIC = 1, ///< Stack variable + IMAGE_SYM_CLASS_EXTERNAL = 2, ///< External symbol + IMAGE_SYM_CLASS_STATIC = 3, ///< Static + IMAGE_SYM_CLASS_REGISTER = 4, ///< Register variable + IMAGE_SYM_CLASS_EXTERNAL_DEF = 5, ///< External definition + IMAGE_SYM_CLASS_LABEL = 6, ///< Label + IMAGE_SYM_CLASS_UNDEFINED_LABEL = 7, ///< Undefined label + IMAGE_SYM_CLASS_MEMBER_OF_STRUCT = 8, ///< Member of structure + IMAGE_SYM_CLASS_ARGUMENT = 9, ///< Function argument + IMAGE_SYM_CLASS_STRUCT_TAG = 10, ///< Structure tag + IMAGE_SYM_CLASS_MEMBER_OF_UNION = 11, ///< Member of union + IMAGE_SYM_CLASS_UNION_TAG = 12, ///< Union tag + IMAGE_SYM_CLASS_TYPE_DEFINITION = 13, ///< Type definition + IMAGE_SYM_CLASS_UNDEFINED_STATIC = 14, ///< Undefined static + IMAGE_SYM_CLASS_ENUM_TAG = 15, ///< Enumeration tag + IMAGE_SYM_CLASS_MEMBER_OF_ENUM = 16, ///< Member of enumeration + IMAGE_SYM_CLASS_REGISTER_PARAM = 17, ///< Register parameter + IMAGE_SYM_CLASS_BIT_FIELD = 18, ///< Bit field + /// ".bb" or ".eb" - beginning or end of block + IMAGE_SYM_CLASS_BLOCK = 100, + /// ".bf" or ".ef" - beginning or end of function + IMAGE_SYM_CLASS_FUNCTION = 101, + IMAGE_SYM_CLASS_END_OF_STRUCT = 102, ///< End of structure + IMAGE_SYM_CLASS_FILE = 103, ///< File name + /// Line number, reformatted as symbol + IMAGE_SYM_CLASS_SECTION = 104, + IMAGE_SYM_CLASS_WEAK_EXTERNAL = 105, ///< Duplicate tag + /// External symbol in dmert public lib + IMAGE_SYM_CLASS_CLR_TOKEN = 107 +}; + +enum SymbolBaseType : unsigned { + IMAGE_SYM_TYPE_NULL = 0, ///< No type information or unknown base type. + IMAGE_SYM_TYPE_VOID = 1, ///< Used with void pointers and functions. + IMAGE_SYM_TYPE_CHAR = 2, ///< A character (signed byte). + IMAGE_SYM_TYPE_SHORT = 3, ///< A 2-byte signed integer. + IMAGE_SYM_TYPE_INT = 4, ///< A natural integer type on the target. + IMAGE_SYM_TYPE_LONG = 5, ///< A 4-byte signed integer. + IMAGE_SYM_TYPE_FLOAT = 6, ///< A 4-byte floating-point number. + IMAGE_SYM_TYPE_DOUBLE = 7, ///< An 8-byte floating-point number. + IMAGE_SYM_TYPE_STRUCT = 8, ///< A structure. + IMAGE_SYM_TYPE_UNION = 9, ///< An union. + IMAGE_SYM_TYPE_ENUM = 10, ///< An enumerated type. + IMAGE_SYM_TYPE_MOE = 11, ///< A member of enumeration (a specific value). + IMAGE_SYM_TYPE_BYTE = 12, ///< A byte; unsigned 1-byte integer. + IMAGE_SYM_TYPE_WORD = 13, ///< A word; unsigned 2-byte integer. + IMAGE_SYM_TYPE_UINT = 14, ///< An unsigned integer of natural size. + IMAGE_SYM_TYPE_DWORD = 15 ///< An unsigned 4-byte integer. +}; + +enum SymbolComplexType : unsigned { + IMAGE_SYM_DTYPE_NULL = 0, ///< No complex type; simple scalar variable. + IMAGE_SYM_DTYPE_POINTER = 1, ///< A pointer to base type. + IMAGE_SYM_DTYPE_FUNCTION = 2, ///< A function that returns a base type. + IMAGE_SYM_DTYPE_ARRAY = 3, ///< An array of base type. + + /// Type is formed as (base + (derived << SCT_COMPLEX_TYPE_SHIFT)) + SCT_COMPLEX_TYPE_SHIFT = 4 +}; + +enum AuxSymbolType { IMAGE_AUX_SYMBOL_TYPE_TOKEN_DEF = 1 }; + +struct section { + char Name[NameSize]; + uint32_t VirtualSize; + uint32_t VirtualAddress; + uint32_t SizeOfRawData; + uint32_t PointerToRawData; + uint32_t PointerToRelocations; + uint32_t PointerToLineNumbers; + uint16_t NumberOfRelocations; + uint16_t NumberOfLineNumbers; + uint32_t Characteristics; +}; + +enum SectionCharacteristics : uint32_t { + SC_Invalid = 0xffffffff, + + IMAGE_SCN_TYPE_NOLOAD = 0x00000002, + IMAGE_SCN_TYPE_NO_PAD = 0x00000008, + IMAGE_SCN_CNT_CODE = 0x00000020, + IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040, + IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080, + IMAGE_SCN_LNK_OTHER = 0x00000100, + IMAGE_SCN_LNK_INFO = 0x00000200, + IMAGE_SCN_LNK_REMOVE = 0x00000800, + IMAGE_SCN_LNK_COMDAT = 0x00001000, + IMAGE_SCN_GPREL = 0x00008000, + IMAGE_SCN_MEM_PURGEABLE = 0x00020000, + IMAGE_SCN_MEM_16BIT = 0x00020000, + IMAGE_SCN_MEM_LOCKED = 0x00040000, + IMAGE_SCN_MEM_PRELOAD = 0x00080000, + IMAGE_SCN_ALIGN_1BYTES = 0x00100000, + IMAGE_SCN_ALIGN_2BYTES = 0x00200000, + IMAGE_SCN_ALIGN_4BYTES = 0x00300000, + IMAGE_SCN_ALIGN_8BYTES = 0x00400000, + IMAGE_SCN_ALIGN_16BYTES = 0x00500000, + IMAGE_SCN_ALIGN_32BYTES = 0x00600000, + IMAGE_SCN_ALIGN_64BYTES = 0x00700000, + IMAGE_SCN_ALIGN_128BYTES = 0x00800000, + IMAGE_SCN_ALIGN_256BYTES = 0x00900000, + IMAGE_SCN_ALIGN_512BYTES = 0x00A00000, + IMAGE_SCN_ALIGN_1024BYTES = 0x00B00000, + IMAGE_SCN_ALIGN_2048BYTES = 0x00C00000, + IMAGE_SCN_ALIGN_4096BYTES = 0x00D00000, + IMAGE_SCN_ALIGN_8192BYTES = 0x00E00000, + IMAGE_SCN_ALIGN_MASK = 0x00F00000, + IMAGE_SCN_LNK_NRELOC_OVFL = 0x01000000, + IMAGE_SCN_MEM_DISCARDABLE = 0x02000000, + IMAGE_SCN_MEM_NOT_CACHED = 0x04000000, + IMAGE_SCN_MEM_NOT_PAGED = 0x08000000, + IMAGE_SCN_MEM_SHARED = 0x10000000, + IMAGE_SCN_MEM_EXECUTE = 0x20000000, + IMAGE_SCN_MEM_READ = 0x40000000, + IMAGE_SCN_MEM_WRITE = 0x80000000 +}; + +struct relocation { + uint32_t VirtualAddress; + uint32_t SymbolTableIndex; + uint16_t Type; +}; + +enum RelocationTypeI386 : unsigned { + IMAGE_REL_I386_ABSOLUTE = 0x0000, + IMAGE_REL_I386_DIR16 = 0x0001, + IMAGE_REL_I386_REL16 = 0x0002, + IMAGE_REL_I386_DIR32 = 0x0006, + IMAGE_REL_I386_DIR32NB = 0x0007, + IMAGE_REL_I386_SEG12 = 0x0009, + IMAGE_REL_I386_SECTION = 0x000A, + IMAGE_REL_I386_SECREL = 0x000B, + IMAGE_REL_I386_TOKEN = 0x000C, + IMAGE_REL_I386_SECREL7 = 0x000D, + IMAGE_REL_I386_REL32 = 0x0014 +}; + +enum RelocationTypeAMD64 : unsigned { + IMAGE_REL_AMD64_ABSOLUTE = 0x0000, + IMAGE_REL_AMD64_ADDR64 = 0x0001, + IMAGE_REL_AMD64_ADDR32 = 0x0002, + IMAGE_REL_AMD64_ADDR32NB = 0x0003, + IMAGE_REL_AMD64_REL32 = 0x0004, + IMAGE_REL_AMD64_REL32_1 = 0x0005, + IMAGE_REL_AMD64_REL32_2 = 0x0006, + IMAGE_REL_AMD64_REL32_3 = 0x0007, + IMAGE_REL_AMD64_REL32_4 = 0x0008, + IMAGE_REL_AMD64_REL32_5 = 0x0009, + IMAGE_REL_AMD64_SECTION = 0x000A, + IMAGE_REL_AMD64_SECREL = 0x000B, + IMAGE_REL_AMD64_SECREL7 = 0x000C, + IMAGE_REL_AMD64_TOKEN = 0x000D, + IMAGE_REL_AMD64_SREL32 = 0x000E, + IMAGE_REL_AMD64_PAIR = 0x000F, + IMAGE_REL_AMD64_SSPAN32 = 0x0010 +}; + +enum RelocationTypesARM : unsigned { + IMAGE_REL_ARM_ABSOLUTE = 0x0000, + IMAGE_REL_ARM_ADDR32 = 0x0001, + IMAGE_REL_ARM_ADDR32NB = 0x0002, + IMAGE_REL_ARM_BRANCH24 = 0x0003, + IMAGE_REL_ARM_BRANCH11 = 0x0004, + IMAGE_REL_ARM_TOKEN = 0x0005, + IMAGE_REL_ARM_BLX24 = 0x0008, + IMAGE_REL_ARM_BLX11 = 0x0009, + IMAGE_REL_ARM_REL32 = 0x000A, + IMAGE_REL_ARM_SECTION = 0x000E, + IMAGE_REL_ARM_SECREL = 0x000F, + IMAGE_REL_ARM_MOV32A = 0x0010, + IMAGE_REL_ARM_MOV32T = 0x0011, + IMAGE_REL_ARM_BRANCH20T = 0x0012, + IMAGE_REL_ARM_BRANCH24T = 0x0014, + IMAGE_REL_ARM_BLX23T = 0x0015, + IMAGE_REL_ARM_PAIR = 0x0016, +}; + +enum RelocationTypesARM64 : unsigned { + IMAGE_REL_ARM64_ABSOLUTE = 0x0000, + IMAGE_REL_ARM64_ADDR32 = 0x0001, + IMAGE_REL_ARM64_ADDR32NB = 0x0002, + IMAGE_REL_ARM64_BRANCH26 = 0x0003, + IMAGE_REL_ARM64_PAGEBASE_REL21 = 0x0004, + IMAGE_REL_ARM64_REL21 = 0x0005, + IMAGE_REL_ARM64_PAGEOFFSET_12A = 0x0006, + IMAGE_REL_ARM64_PAGEOFFSET_12L = 0x0007, + IMAGE_REL_ARM64_SECREL = 0x0008, + IMAGE_REL_ARM64_SECREL_LOW12A = 0x0009, + IMAGE_REL_ARM64_SECREL_HIGH12A = 0x000A, + IMAGE_REL_ARM64_SECREL_LOW12L = 0x000B, + IMAGE_REL_ARM64_TOKEN = 0x000C, + IMAGE_REL_ARM64_SECTION = 0x000D, + IMAGE_REL_ARM64_ADDR64 = 0x000E, + IMAGE_REL_ARM64_BRANCH19 = 0x000F, + IMAGE_REL_ARM64_BRANCH14 = 0x0010, + IMAGE_REL_ARM64_REL32 = 0x0011, +}; + +enum COMDATType : uint8_t { + IMAGE_COMDAT_SELECT_NODUPLICATES = 1, + IMAGE_COMDAT_SELECT_ANY, + IMAGE_COMDAT_SELECT_SAME_SIZE, + IMAGE_COMDAT_SELECT_EXACT_MATCH, + IMAGE_COMDAT_SELECT_ASSOCIATIVE, + IMAGE_COMDAT_SELECT_LARGEST, + IMAGE_COMDAT_SELECT_NEWEST +}; + +// Auxiliary Symbol Formats +struct AuxiliaryFunctionDefinition { + uint32_t TagIndex; + uint32_t TotalSize; + uint32_t PointerToLinenumber; + uint32_t PointerToNextFunction; + char unused[2]; +}; + +struct AuxiliarybfAndefSymbol { + uint8_t unused1[4]; + uint16_t Linenumber; + uint8_t unused2[6]; + uint32_t PointerToNextFunction; + uint8_t unused3[2]; +}; + +struct AuxiliaryWeakExternal { + uint32_t TagIndex; + uint32_t Characteristics; + uint8_t unused[10]; +}; + +enum WeakExternalCharacteristics : unsigned { + IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY = 1, + IMAGE_WEAK_EXTERN_SEARCH_LIBRARY = 2, + IMAGE_WEAK_EXTERN_SEARCH_ALIAS = 3, + IMAGE_WEAK_EXTERN_ANTI_DEPENDENCY = 4 +}; + +struct AuxiliarySectionDefinition { + uint32_t Length; + uint16_t NumberOfRelocations; + uint16_t NumberOfLinenumbers; + uint32_t CheckSum; + uint32_t Number; + uint8_t Selection; + char unused; +}; + +struct AuxiliaryCLRToken { + uint8_t AuxType; + uint8_t unused1; + uint32_t SymbolTableIndex; + char unused2[12]; +}; + +union Auxiliary { + AuxiliaryFunctionDefinition FunctionDefinition; + AuxiliarybfAndefSymbol bfAndefSymbol; + AuxiliaryWeakExternal WeakExternal; + AuxiliarySectionDefinition SectionDefinition; +}; + +/// The Import Directory Table. +/// +/// There is a single array of these and one entry per imported DLL. +struct ImportDirectoryTableEntry { + uint32_t ImportLookupTableRVA; + uint32_t TimeDateStamp; + uint32_t ForwarderChain; + uint32_t NameRVA; + uint32_t ImportAddressTableRVA; +}; + +/// The PE32 Import Lookup Table. +/// +/// There is an array of these for each imported DLL. It represents either +/// the ordinal to import from the target DLL, or a name to lookup and import +/// from the target DLL. +/// +/// This also happens to be the same format used by the Import Address Table +/// when it is initially written out to the image. +struct ImportLookupTableEntry32 { + uint32_t data; + + /// Is this entry specified by ordinal, or name? + bool isOrdinal() const { return data & 0x80000000; } + + /// Get the ordinal value of this entry. isOrdinal must be true. + uint16_t getOrdinal() const { + assert(isOrdinal() && "ILT entry is not an ordinal!"); + return data & 0xFFFF; + } + + /// Set the ordinal value and set isOrdinal to true. + void setOrdinal(uint16_t o) { + data = o; + data |= 0x80000000; + } + + /// Get the Hint/Name entry RVA. isOrdinal must be false. + uint32_t getHintNameRVA() const { + assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!"); + return data; + } + + /// Set the Hint/Name entry RVA and set isOrdinal to false. + void setHintNameRVA(uint32_t rva) { data = rva; } +}; + +/// The DOS compatible header at the front of all PEs. +struct DOSHeader { + uint16_t Magic; + uint16_t UsedBytesInTheLastPage; + uint16_t FileSizeInPages; + uint16_t NumberOfRelocationItems; + uint16_t HeaderSizeInParagraphs; + uint16_t MinimumExtraParagraphs; + uint16_t MaximumExtraParagraphs; + uint16_t InitialRelativeSS; + uint16_t InitialSP; + uint16_t Checksum; + uint16_t InitialIP; + uint16_t InitialRelativeCS; + uint16_t AddressOfRelocationTable; + uint16_t OverlayNumber; + uint16_t Reserved[4]; + uint16_t OEMid; + uint16_t OEMinfo; + uint16_t Reserved2[10]; + uint32_t AddressOfNewExeHeader; +}; + +struct PE32Header { + enum { PE32 = 0x10b, PE32_PLUS = 0x20b }; + + uint16_t Magic; + uint8_t MajorLinkerVersion; + uint8_t MinorLinkerVersion; + uint32_t SizeOfCode; + uint32_t SizeOfInitializedData; + uint32_t SizeOfUninitializedData; + uint32_t AddressOfEntryPoint; // RVA + uint32_t BaseOfCode; // RVA + uint32_t BaseOfData; // RVA + uint64_t ImageBase; + uint32_t SectionAlignment; + uint32_t FileAlignment; + uint16_t MajorOperatingSystemVersion; + uint16_t MinorOperatingSystemVersion; + uint16_t MajorImageVersion; + uint16_t MinorImageVersion; + uint16_t MajorSubsystemVersion; + uint16_t MinorSubsystemVersion; + uint32_t Win32VersionValue; + uint32_t SizeOfImage; + uint32_t SizeOfHeaders; + uint32_t CheckSum; + uint16_t Subsystem; + // FIXME: This should be DllCharacteristics to match the COFF spec. + uint16_t DLLCharacteristics; + uint64_t SizeOfStackReserve; + uint64_t SizeOfStackCommit; + uint64_t SizeOfHeapReserve; + uint64_t SizeOfHeapCommit; + uint32_t LoaderFlags; + // FIXME: This should be NumberOfRvaAndSizes to match the COFF spec. + uint32_t NumberOfRvaAndSize; +}; + +struct DataDirectory { + uint32_t RelativeVirtualAddress; + uint32_t Size; +}; + +enum DataDirectoryIndex : unsigned { + EXPORT_TABLE = 0, + IMPORT_TABLE, + RESOURCE_TABLE, + EXCEPTION_TABLE, + CERTIFICATE_TABLE, + BASE_RELOCATION_TABLE, + DEBUG_DIRECTORY, + ARCHITECTURE, + GLOBAL_PTR, + TLS_TABLE, + LOAD_CONFIG_TABLE, + BOUND_IMPORT, + IAT, + DELAY_IMPORT_DESCRIPTOR, + CLR_RUNTIME_HEADER, + + NUM_DATA_DIRECTORIES +}; + +enum WindowsSubsystem : unsigned { + IMAGE_SUBSYSTEM_UNKNOWN = 0, ///< An unknown subsystem. + IMAGE_SUBSYSTEM_NATIVE = 1, ///< Device drivers and native Windows processes + IMAGE_SUBSYSTEM_WINDOWS_GUI = 2, ///< The Windows GUI subsystem. + IMAGE_SUBSYSTEM_WINDOWS_CUI = 3, ///< The Windows character subsystem. + IMAGE_SUBSYSTEM_OS2_CUI = 5, ///< The OS/2 character subsystem. + IMAGE_SUBSYSTEM_POSIX_CUI = 7, ///< The POSIX character subsystem. + IMAGE_SUBSYSTEM_NATIVE_WINDOWS = 8, ///< Native Windows 9x driver. + IMAGE_SUBSYSTEM_WINDOWS_CE_GUI = 9, ///< Windows CE. + IMAGE_SUBSYSTEM_EFI_APPLICATION = 10, ///< An EFI application. + IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER = 11, ///< An EFI driver with boot + /// services. + IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER = 12, ///< An EFI driver with run-time + /// services. + IMAGE_SUBSYSTEM_EFI_ROM = 13, ///< An EFI ROM image. + IMAGE_SUBSYSTEM_XBOX = 14, ///< XBOX. + IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION = 16 ///< A BCD application. +}; + +enum DLLCharacteristics : unsigned { + /// ASLR with 64 bit address space. + IMAGE_DLL_CHARACTERISTICS_HIGH_ENTROPY_VA = 0x0020, + /// DLL can be relocated at load time. + IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE = 0x0040, + /// Code integrity checks are enforced. + IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY = 0x0080, + ///< Image is NX compatible. + IMAGE_DLL_CHARACTERISTICS_NX_COMPAT = 0x0100, + /// Isolation aware, but do not isolate the image. + IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION = 0x0200, + /// Does not use structured exception handling (SEH). No SEH handler may be + /// called in this image. + IMAGE_DLL_CHARACTERISTICS_NO_SEH = 0x0400, + /// Do not bind the image. + IMAGE_DLL_CHARACTERISTICS_NO_BIND = 0x0800, + ///< Image should execute in an AppContainer. + IMAGE_DLL_CHARACTERISTICS_APPCONTAINER = 0x1000, + ///< A WDM driver. + IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER = 0x2000, + ///< Image supports Control Flow Guard. + IMAGE_DLL_CHARACTERISTICS_GUARD_CF = 0x4000, + /// Terminal Server aware. + IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE = 0x8000 +}; + +enum ExtendedDLLCharacteristics : unsigned { + /// Image is CET compatible + IMAGE_DLL_CHARACTERISTICS_EX_CET_COMPAT = 0x0001 +}; + +enum DebugType : unsigned { + IMAGE_DEBUG_TYPE_UNKNOWN = 0, + IMAGE_DEBUG_TYPE_COFF = 1, + IMAGE_DEBUG_TYPE_CODEVIEW = 2, + IMAGE_DEBUG_TYPE_FPO = 3, + IMAGE_DEBUG_TYPE_MISC = 4, + IMAGE_DEBUG_TYPE_EXCEPTION = 5, + IMAGE_DEBUG_TYPE_FIXUP = 6, + IMAGE_DEBUG_TYPE_OMAP_TO_SRC = 7, + IMAGE_DEBUG_TYPE_OMAP_FROM_SRC = 8, + IMAGE_DEBUG_TYPE_BORLAND = 9, + IMAGE_DEBUG_TYPE_RESERVED10 = 10, + IMAGE_DEBUG_TYPE_CLSID = 11, + IMAGE_DEBUG_TYPE_VC_FEATURE = 12, + IMAGE_DEBUG_TYPE_POGO = 13, + IMAGE_DEBUG_TYPE_ILTCG = 14, + IMAGE_DEBUG_TYPE_MPX = 15, + IMAGE_DEBUG_TYPE_REPRO = 16, + IMAGE_DEBUG_TYPE_EX_DLLCHARACTERISTICS = 20, +}; + +enum BaseRelocationType : unsigned { + IMAGE_REL_BASED_ABSOLUTE = 0, + IMAGE_REL_BASED_HIGH = 1, + IMAGE_REL_BASED_LOW = 2, + IMAGE_REL_BASED_HIGHLOW = 3, + IMAGE_REL_BASED_HIGHADJ = 4, + IMAGE_REL_BASED_MIPS_JMPADDR = 5, + IMAGE_REL_BASED_ARM_MOV32A = 5, + IMAGE_REL_BASED_ARM_MOV32T = 7, + IMAGE_REL_BASED_MIPS_JMPADDR16 = 9, + IMAGE_REL_BASED_DIR64 = 10 +}; + +enum ImportType : unsigned { + IMPORT_CODE = 0, + IMPORT_DATA = 1, + IMPORT_CONST = 2 +}; + +enum ImportNameType : unsigned { + /// Import is by ordinal. This indicates that the value in the Ordinal/Hint + /// field of the import header is the import's ordinal. If this constant is + /// not specified, then the Ordinal/Hint field should always be interpreted + /// as the import's hint. + IMPORT_ORDINAL = 0, + /// The import name is identical to the public symbol name + IMPORT_NAME = 1, + /// The import name is the public symbol name, but skipping the leading ?, + /// @, or optionally _. + IMPORT_NAME_NOPREFIX = 2, + /// The import name is the public symbol name, but skipping the leading ?, + /// @, or optionally _, and truncating at the first @. + IMPORT_NAME_UNDECORATE = 3 +}; + +enum class GuardFlags : uint32_t { + /// Module performs control flow integrity checks using system-supplied + /// support. + CF_INSTRUMENTED = 0x100, + /// Module performs control flow and write integrity checks. + CFW_INSTRUMENTED = 0x200, + /// Module contains valid control flow target metadata. + CF_FUNCTION_TABLE_PRESENT = 0x400, + /// Module does not make use of the /GS security cookie. + SECURITY_COOKIE_UNUSED = 0x800, + /// Module supports read only delay load IAT. + PROTECT_DELAYLOAD_IAT = 0x1000, + /// Delayload import table in its own .didat section (with nothing else in it) + /// that can be freely reprotected. + DELAYLOAD_IAT_IN_ITS_OWN_SECTION = 0x2000, + /// Module contains suppressed export information. This also infers that the + /// address taken IAT table is also present in the load config. + CF_EXPORT_SUPPRESSION_INFO_PRESENT = 0x4000, + /// Module enables suppression of exports. + CF_ENABLE_EXPORT_SUPPRESSION = 0x8000, + /// Module contains longjmp target information. + CF_LONGJUMP_TABLE_PRESENT = 0x10000, + /// Module contains EH continuation target information. + EH_CONTINUATION_TABLE_PRESENT = 0x400000, + /// Mask for the subfield that contains the stride of Control Flow Guard + /// function table entries (that is, the additional count of bytes per table + /// entry). + CF_FUNCTION_TABLE_SIZE_MASK = 0xF0000000, + CF_FUNCTION_TABLE_SIZE_5BYTES = 0x10000000, + CF_FUNCTION_TABLE_SIZE_6BYTES = 0x20000000, + CF_FUNCTION_TABLE_SIZE_7BYTES = 0x30000000, + CF_FUNCTION_TABLE_SIZE_8BYTES = 0x40000000, + CF_FUNCTION_TABLE_SIZE_9BYTES = 0x50000000, + CF_FUNCTION_TABLE_SIZE_10BYTES = 0x60000000, + CF_FUNCTION_TABLE_SIZE_11BYTES = 0x70000000, + CF_FUNCTION_TABLE_SIZE_12BYTES = 0x80000000, + CF_FUNCTION_TABLE_SIZE_13BYTES = 0x90000000, + CF_FUNCTION_TABLE_SIZE_14BYTES = 0xA0000000, + CF_FUNCTION_TABLE_SIZE_15BYTES = 0xB0000000, + CF_FUNCTION_TABLE_SIZE_16BYTES = 0xC0000000, + CF_FUNCTION_TABLE_SIZE_17BYTES = 0xD0000000, + CF_FUNCTION_TABLE_SIZE_18BYTES = 0xE0000000, + CF_FUNCTION_TABLE_SIZE_19BYTES = 0xF0000000, +}; + +struct ImportHeader { + uint16_t Sig1; ///< Must be IMAGE_FILE_MACHINE_UNKNOWN (0). + uint16_t Sig2; ///< Must be 0xFFFF. + uint16_t Version; + uint16_t Machine; + uint32_t TimeDateStamp; + uint32_t SizeOfData; + uint16_t OrdinalHint; + uint16_t TypeInfo; + + ImportType getType() const { return static_cast(TypeInfo & 0x3); } + + ImportNameType getNameType() const { + return static_cast((TypeInfo & 0x1C) >> 2); + } +}; + +enum CodeViewIdentifiers { + DEBUG_SECTION_MAGIC = 0x4, + DEBUG_HASHES_SECTION_MAGIC = 0x133C9C5 +}; + +// These flags show up in the @feat.00 symbol. They appear to be some kind of +// compiler features bitfield read by link.exe. +enum Feat00Flags : uint32_t { + // Object is compatible with /safeseh. + SafeSEH = 0x1, + // Object was compiled with /GS. + GuardStack = 0x100, + // Object was compiled with /sdl. + SDL = 0x200, + // Object was compiled with /guard:cf. + GuardCF = 0x800, + // Object was compiled with /guard:ehcont. + GuardEHCont = 0x4000, + // Object was compiled with /kernel. + Kernel = 0x40000000, +}; + +inline bool isReservedSectionNumber(int32_t SectionNumber) { + return SectionNumber <= 0; +} + +/// Encode section name based on string table offset. +/// The size of Out must be at least COFF::NameSize. +bool encodeSectionName(char *Out, uint64_t Offset); + +} // End namespace COFF. +} // End namespace llvm. + +#endif diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/DynamicTags.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/DynamicTags.def new file mode 100644 index 00000000000..f393b82406b --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/DynamicTags.def @@ -0,0 +1,265 @@ +#ifndef DYNAMIC_TAG +#error "DYNAMIC_TAG must be defined" +#endif + +// Add separate macros for the architecture specific tags and the markers +// such as DT_HIOS, etc. to allow using this file to in other contexts. +// For example we can use it to generate a stringification switch statement. + +#ifndef AARCH64_DYNAMIC_TAG +#define AARCH64_DYNAMIC_TAG(name, value) DYNAMIC_TAG(name, value) +#define AARCH64_DYNAMIC_TAG_DEFINED +#endif + +#ifndef HEXAGON_DYNAMIC_TAG +#define HEXAGON_DYNAMIC_TAG(name, value) DYNAMIC_TAG(name, value) +#define HEXAGON_DYNAMIC_TAG_DEFINED +#endif + +#ifndef MIPS_DYNAMIC_TAG +#define MIPS_DYNAMIC_TAG(name, value) DYNAMIC_TAG(name, value) +#define MIPS_DYNAMIC_TAG_DEFINED +#endif + +#ifndef PPC_DYNAMIC_TAG +#define PPC_DYNAMIC_TAG(name, value) DYNAMIC_TAG(name, value) +#define PPC_DYNAMIC_TAG_DEFINED +#endif + +#ifndef PPC64_DYNAMIC_TAG +#define PPC64_DYNAMIC_TAG(name, value) DYNAMIC_TAG(name, value) +#define PPC64_DYNAMIC_TAG_DEFINED +#endif + +#ifndef RISCV_DYNAMIC_TAG +#define RISCV_DYNAMIC_TAG(name, value) DYNAMIC_TAG(name, value) +#define RISCV_DYNAMIC_TAG_DEFINED +#endif + +#ifndef DYNAMIC_TAG_MARKER +#define DYNAMIC_TAG_MARKER(name, value) DYNAMIC_TAG(name, value) +#define DYNAMIC_TAG_MARKER_DEFINED +#endif + +DYNAMIC_TAG(NULL, 0) // Marks end of dynamic array. +DYNAMIC_TAG(NEEDED, 1) // String table offset of needed library. +DYNAMIC_TAG(PLTRELSZ, 2) // Size of relocation entries in PLT. +DYNAMIC_TAG(PLTGOT, 3) // Address associated with linkage table. +DYNAMIC_TAG(HASH, 4) // Address of symbolic hash table. +DYNAMIC_TAG(STRTAB, 5) // Address of dynamic string table. +DYNAMIC_TAG(SYMTAB, 6) // Address of dynamic symbol table. +DYNAMIC_TAG(RELA, 7) // Address of relocation table (Rela entries). +DYNAMIC_TAG(RELASZ, 8) // Size of Rela relocation table. +DYNAMIC_TAG(RELAENT, 9) // Size of a Rela relocation entry. +DYNAMIC_TAG(STRSZ, 10) // Total size of the string table. +DYNAMIC_TAG(SYMENT, 11) // Size of a symbol table entry. +DYNAMIC_TAG(INIT, 12) // Address of initialization function. +DYNAMIC_TAG(FINI, 13) // Address of termination function. +DYNAMIC_TAG(SONAME, 14) // String table offset of a shared objects name. +DYNAMIC_TAG(RPATH, 15) // String table offset of library search path. +DYNAMIC_TAG(SYMBOLIC, 16) // Changes symbol resolution algorithm. +DYNAMIC_TAG(REL, 17) // Address of relocation table (Rel entries). +DYNAMIC_TAG(RELSZ, 18) // Size of Rel relocation table. +DYNAMIC_TAG(RELENT, 19) // Size of a Rel relocation entry. +DYNAMIC_TAG(PLTREL, 20) // Type of relocation entry used for linking. +DYNAMIC_TAG(DEBUG, 21) // Reserved for debugger. +DYNAMIC_TAG(TEXTREL, 22) // Relocations exist for non-writable segments. +DYNAMIC_TAG(JMPREL, 23) // Address of relocations associated with PLT. +DYNAMIC_TAG(BIND_NOW, 24) // Process all relocations before execution. +DYNAMIC_TAG(INIT_ARRAY, 25) // Pointer to array of initialization functions. +DYNAMIC_TAG(FINI_ARRAY, 26) // Pointer to array of termination functions. +DYNAMIC_TAG(INIT_ARRAYSZ, 27) // Size of DT_INIT_ARRAY. +DYNAMIC_TAG(FINI_ARRAYSZ, 28) // Size of DT_FINI_ARRAY. +DYNAMIC_TAG(RUNPATH, 29) // String table offset of lib search path. +DYNAMIC_TAG(FLAGS, 30) // Flags. +DYNAMIC_TAG_MARKER(ENCODING, 32) // Values from here to DT_LOOS follow the rules + // for the interpretation of the d_un union. + +DYNAMIC_TAG(PREINIT_ARRAY, 32) // Pointer to array of preinit functions. +DYNAMIC_TAG(PREINIT_ARRAYSZ, 33) // Size of the DT_PREINIT_ARRAY array. + +DYNAMIC_TAG(SYMTAB_SHNDX, 34) // Address of the SHT_SYMTAB_SHNDX section. + +// Experimental support for SHT_RELR sections. For details, see proposal +// at https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg +DYNAMIC_TAG(RELRSZ, 35) // Size of Relr relocation table. +DYNAMIC_TAG(RELR, 36) // Address of relocation table (Relr entries). +DYNAMIC_TAG(RELRENT, 37) // Size of a Relr relocation entry. + +DYNAMIC_TAG_MARKER(LOOS, 0x60000000) // Start of environment specific tags. +DYNAMIC_TAG_MARKER(HIOS, 0x6FFFFFFF) // End of environment specific tags. +DYNAMIC_TAG_MARKER(LOPROC, 0x70000000) // Start of processor specific tags. +DYNAMIC_TAG_MARKER(HIPROC, 0x7FFFFFFF) // End of processor specific tags. + +// Android packed relocation section tags. +// https://android.googlesource.com/platform/bionic/+/6f12bfece5dcc01325e0abba56a46b1bcf991c69/tools/relocation_packer/src/elf_file.cc#31 +DYNAMIC_TAG(ANDROID_REL, 0x6000000F) +DYNAMIC_TAG(ANDROID_RELSZ, 0x60000010) +DYNAMIC_TAG(ANDROID_RELA, 0x60000011) +DYNAMIC_TAG(ANDROID_RELASZ, 0x60000012) + +// Android's experimental support for SHT_RELR sections. +// https://android.googlesource.com/platform/bionic/+/b7feec74547f84559a1467aca02708ff61346d2a/libc/include/elf.h#253 +DYNAMIC_TAG(ANDROID_RELR, 0x6FFFE000) // Address of relocation table (Relr entries). +DYNAMIC_TAG(ANDROID_RELRSZ, 0x6FFFE001) // Size of Relr relocation table. +DYNAMIC_TAG(ANDROID_RELRENT, 0x6FFFE003) // Size of a Relr relocation entry. + +DYNAMIC_TAG(GNU_HASH, 0x6FFFFEF5) // Reference to the GNU hash table. +DYNAMIC_TAG(TLSDESC_PLT, 0x6FFFFEF6) // Location of PLT entry for TLS + // descriptor resolver calls. +DYNAMIC_TAG(TLSDESC_GOT, 0x6FFFFEF7) // Location of GOT entry used by TLS + // descriptor resolver PLT entry. +DYNAMIC_TAG(RELACOUNT, 0x6FFFFFF9) // ELF32_Rela count. +DYNAMIC_TAG(RELCOUNT, 0x6FFFFFFA) // ELF32_Rel count. + +DYNAMIC_TAG(FLAGS_1, 0X6FFFFFFB) // Flags_1. + +DYNAMIC_TAG(VERSYM, 0x6FFFFFF0) // The address of .gnu.version section. +DYNAMIC_TAG(VERDEF, 0X6FFFFFFC) // The address of the version definition + // table. +DYNAMIC_TAG(VERDEFNUM, 0X6FFFFFFD) // The number of entries in DT_VERDEF. +DYNAMIC_TAG(VERNEED, 0X6FFFFFFE) // The address of the version dependency + // table. +DYNAMIC_TAG(VERNEEDNUM, 0X6FFFFFFF) // The number of entries in DT_VERNEED. + +// AArch64 specific dynamic table entries +AARCH64_DYNAMIC_TAG(AARCH64_BTI_PLT, 0x70000001) +AARCH64_DYNAMIC_TAG(AARCH64_PAC_PLT, 0x70000003) +AARCH64_DYNAMIC_TAG(AARCH64_VARIANT_PCS, 0x70000005) +AARCH64_DYNAMIC_TAG(AARCH64_MEMTAG_MODE, 0x70000009) +AARCH64_DYNAMIC_TAG(AARCH64_MEMTAG_HEAP, 0x7000000b) +AARCH64_DYNAMIC_TAG(AARCH64_MEMTAG_STACK, 0x7000000c) +AARCH64_DYNAMIC_TAG(AARCH64_MEMTAG_GLOBALS, 0x7000000d) +AARCH64_DYNAMIC_TAG(AARCH64_MEMTAG_GLOBALSSZ, 0x7000000f) + +// Hexagon specific dynamic table entries +HEXAGON_DYNAMIC_TAG(HEXAGON_SYMSZ, 0x70000000) +HEXAGON_DYNAMIC_TAG(HEXAGON_VER, 0x70000001) +HEXAGON_DYNAMIC_TAG(HEXAGON_PLT, 0x70000002) + +// Mips specific dynamic table entry tags. + +MIPS_DYNAMIC_TAG(MIPS_RLD_VERSION, 0x70000001) // 32 bit version number for + // runtime linker interface. +MIPS_DYNAMIC_TAG(MIPS_TIME_STAMP, 0x70000002) // Time stamp. +MIPS_DYNAMIC_TAG(MIPS_ICHECKSUM, 0x70000003) // Checksum of external strings + // and common sizes. +MIPS_DYNAMIC_TAG(MIPS_IVERSION, 0x70000004) // Index of version string + // in string table. +MIPS_DYNAMIC_TAG(MIPS_FLAGS, 0x70000005) // 32 bits of flags. +MIPS_DYNAMIC_TAG(MIPS_BASE_ADDRESS, 0x70000006) // Base address of the segment. +MIPS_DYNAMIC_TAG(MIPS_MSYM, 0x70000007) // Address of .msym section. +MIPS_DYNAMIC_TAG(MIPS_CONFLICT, 0x70000008) // Address of .conflict section. +MIPS_DYNAMIC_TAG(MIPS_LIBLIST, 0x70000009) // Address of .liblist section. +MIPS_DYNAMIC_TAG(MIPS_LOCAL_GOTNO, 0x7000000a) // Number of local global offset + // table entries. +MIPS_DYNAMIC_TAG(MIPS_CONFLICTNO, 0x7000000b) // Number of entries + // in the .conflict section. +MIPS_DYNAMIC_TAG(MIPS_LIBLISTNO, 0x70000010) // Number of entries + // in the .liblist section. +MIPS_DYNAMIC_TAG(MIPS_SYMTABNO, 0x70000011) // Number of entries + // in the .dynsym section. +MIPS_DYNAMIC_TAG(MIPS_UNREFEXTNO, 0x70000012) // Index of first external dynamic + // symbol not referenced locally. +MIPS_DYNAMIC_TAG(MIPS_GOTSYM, 0x70000013) // Index of first dynamic symbol + // in global offset table. +MIPS_DYNAMIC_TAG(MIPS_HIPAGENO, 0x70000014) // Number of page table entries + // in global offset table. +MIPS_DYNAMIC_TAG(MIPS_RLD_MAP, 0x70000016) // Address of run time loader map + // used for debugging. +MIPS_DYNAMIC_TAG(MIPS_DELTA_CLASS, 0x70000017) // Delta C++ class definition. +MIPS_DYNAMIC_TAG(MIPS_DELTA_CLASS_NO, 0x70000018) // Number of entries + // in DT_MIPS_DELTA_CLASS. +MIPS_DYNAMIC_TAG(MIPS_DELTA_INSTANCE, 0x70000019) // Delta C++ class instances. +MIPS_DYNAMIC_TAG(MIPS_DELTA_INSTANCE_NO, 0x7000001A) // Number of entries + // in DT_MIPS_DELTA_INSTANCE. +MIPS_DYNAMIC_TAG(MIPS_DELTA_RELOC, 0x7000001B) // Delta relocations. +MIPS_DYNAMIC_TAG(MIPS_DELTA_RELOC_NO, 0x7000001C) // Number of entries + // in DT_MIPS_DELTA_RELOC. +MIPS_DYNAMIC_TAG(MIPS_DELTA_SYM, 0x7000001D) // Delta symbols that Delta + // relocations refer to. +MIPS_DYNAMIC_TAG(MIPS_DELTA_SYM_NO, 0x7000001E) // Number of entries + // in DT_MIPS_DELTA_SYM. +MIPS_DYNAMIC_TAG(MIPS_DELTA_CLASSSYM, 0x70000020) // Delta symbols that hold + // class declarations. +MIPS_DYNAMIC_TAG(MIPS_DELTA_CLASSSYM_NO, 0x70000021) // Number of entries + // in DT_MIPS_DELTA_CLASSSYM. + +MIPS_DYNAMIC_TAG(MIPS_CXX_FLAGS, 0x70000022) // Flags indicating information + // about C++ flavor. +MIPS_DYNAMIC_TAG(MIPS_PIXIE_INIT, 0x70000023) // Pixie information. +MIPS_DYNAMIC_TAG(MIPS_SYMBOL_LIB, 0x70000024) // Address of .MIPS.symlib +MIPS_DYNAMIC_TAG(MIPS_LOCALPAGE_GOTIDX, 0x70000025) // The GOT index of the first PTE + // for a segment +MIPS_DYNAMIC_TAG(MIPS_LOCAL_GOTIDX, 0x70000026) // The GOT index of the first PTE + // for a local symbol +MIPS_DYNAMIC_TAG(MIPS_HIDDEN_GOTIDX, 0x70000027) // The GOT index of the first PTE + // for a hidden symbol +MIPS_DYNAMIC_TAG(MIPS_PROTECTED_GOTIDX, 0x70000028) // The GOT index of the first PTE + // for a protected symbol +MIPS_DYNAMIC_TAG(MIPS_OPTIONS, 0x70000029) // Address of `.MIPS.options'. +MIPS_DYNAMIC_TAG(MIPS_INTERFACE, 0x7000002A) // Address of `.interface'. +MIPS_DYNAMIC_TAG(MIPS_DYNSTR_ALIGN, 0x7000002B) // Unknown. +MIPS_DYNAMIC_TAG(MIPS_INTERFACE_SIZE, 0x7000002C) // Size of the .interface section. +MIPS_DYNAMIC_TAG(MIPS_RLD_TEXT_RESOLVE_ADDR, 0x7000002D) // Size of rld_text_resolve + // function stored in the GOT. +MIPS_DYNAMIC_TAG(MIPS_PERF_SUFFIX, 0x7000002E) // Default suffix of DSO to be added + // by rld on dlopen() calls. +MIPS_DYNAMIC_TAG(MIPS_COMPACT_SIZE, 0x7000002F) // Size of compact relocation + // section (O32). +MIPS_DYNAMIC_TAG(MIPS_GP_VALUE, 0x70000030) // GP value for auxiliary GOTs. +MIPS_DYNAMIC_TAG(MIPS_AUX_DYNAMIC, 0x70000031) // Address of auxiliary .dynamic. +MIPS_DYNAMIC_TAG(MIPS_PLTGOT, 0x70000032) // Address of the base of the PLTGOT. +MIPS_DYNAMIC_TAG(MIPS_RWPLT, 0x70000034) // Points to the base + // of a writable PLT. +MIPS_DYNAMIC_TAG(MIPS_RLD_MAP_REL, 0x70000035) // Relative offset of run time loader + // map, used for debugging. +MIPS_DYNAMIC_TAG(MIPS_XHASH, 0x70000036) // GNU-style hash table with xlat. + +// PPC specific dynamic table entries. +PPC_DYNAMIC_TAG(PPC_GOT, 0x70000000) // Uses Secure PLT ABI. +PPC_DYNAMIC_TAG(PPC_OPT, 0x70000001) // Has TLS optimization. + +// PPC64 specific dynamic table entries. +PPC64_DYNAMIC_TAG(PPC64_GLINK, 0x70000000) // Address of 32 bytes before the + // first glink lazy resolver stub. +PPC64_DYNAMIC_TAG(PPC64_OPT, 0x70000003) // Flags to control optimizations + // for TLS and multiple TOCs. + +// RISC-V specific dynamic array tags. +RISCV_DYNAMIC_TAG(RISCV_VARIANT_CC, 0x70000001) + +// Sun machine-independent extensions. +DYNAMIC_TAG(AUXILIARY, 0x7FFFFFFD) // Shared object to load before self +DYNAMIC_TAG(USED, 0x7FFFFFFE) // Same as DT_NEEDED +DYNAMIC_TAG(FILTER, 0x7FFFFFFF) // Shared object to get values from + + +#ifdef DYNAMIC_TAG_MARKER_DEFINED +#undef DYNAMIC_TAG_MARKER +#undef DYNAMIC_TAG_MARKER_DEFINED +#endif +#ifdef AARCH64_DYNAMIC_TAG_DEFINED +#undef AARCH64_DYNAMIC_TAG +#undef AARCH64_DYNAMIC_TAG_DEFINED +#endif +#ifdef MIPS_DYNAMIC_TAG_DEFINED +#undef MIPS_DYNAMIC_TAG +#undef MIPS_DYNAMIC_TAG_DEFINED +#endif +#ifdef HEXAGON_DYNAMIC_TAG_DEFINED +#undef HEXAGON_DYNAMIC_TAG +#undef HEXAGON_DYNAMIC_TAG_DEFINED +#endif +#ifdef PPC_DYNAMIC_TAG_DEFINED +#undef PPC_DYNAMIC_TAG +#undef PPC_DYNAMIC_TAG_DEFINED +#endif +#ifdef PPC64_DYNAMIC_TAG_DEFINED +#undef PPC64_DYNAMIC_TAG +#undef PPC64_DYNAMIC_TAG_DEFINED +#endif +#ifdef RISCV_DYNAMIC_TAG_DEFINED +#undef RISCV_DYNAMIC_TAG +#undef RISCV_DYNAMIC_TAG_DEFINED +#endif diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELF.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELF.h new file mode 100644 index 00000000000..f5a7cdb387a --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELF.h @@ -0,0 +1,1853 @@ +//===- llvm/BinaryFormat/ELF.h - ELF constants and structures ---*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This header contains common, non-processor-specific data structures and +// constants for the ELF file format. +// +// The details of the ELF32 bits in this file are largely based on the Tool +// Interface Standard (TIS) Executable and Linking Format (ELF) Specification +// Version 1.2, May 1995. The ELF64 stuff is based on ELF-64 Object File Format +// Version 1.5, Draft 2, May 1998 as well as OpenBSD header files. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_BINARYFORMAT_ELF_H +#define LLVM_BINARYFORMAT_ELF_H + +#include "llvm/ADT/StringRef.h" +#include +#include + +namespace llvm { +namespace ELF { + +using Elf32_Addr = uint32_t; // Program address +using Elf32_Off = uint32_t; // File offset +using Elf32_Half = uint16_t; +using Elf32_Word = uint32_t; +using Elf32_Sword = int32_t; + +using Elf64_Addr = uint64_t; +using Elf64_Off = uint64_t; +using Elf64_Half = uint16_t; +using Elf64_Word = uint32_t; +using Elf64_Sword = int32_t; +using Elf64_Xword = uint64_t; +using Elf64_Sxword = int64_t; + +// Object file magic string. +static const char ElfMagic[] = {0x7f, 'E', 'L', 'F', '\0'}; + +// e_ident size and indices. +enum { + EI_MAG0 = 0, // File identification index. + EI_MAG1 = 1, // File identification index. + EI_MAG2 = 2, // File identification index. + EI_MAG3 = 3, // File identification index. + EI_CLASS = 4, // File class. + EI_DATA = 5, // Data encoding. + EI_VERSION = 6, // File version. + EI_OSABI = 7, // OS/ABI identification. + EI_ABIVERSION = 8, // ABI version. + EI_PAD = 9, // Start of padding bytes. + EI_NIDENT = 16 // Number of bytes in e_ident. +}; + +struct Elf32_Ehdr { + unsigned char e_ident[EI_NIDENT]; // ELF Identification bytes + Elf32_Half e_type; // Type of file (see ET_* below) + Elf32_Half e_machine; // Required architecture for this file (see EM_*) + Elf32_Word e_version; // Must be equal to 1 + Elf32_Addr e_entry; // Address to jump to in order to start program + Elf32_Off e_phoff; // Program header table's file offset, in bytes + Elf32_Off e_shoff; // Section header table's file offset, in bytes + Elf32_Word e_flags; // Processor-specific flags + Elf32_Half e_ehsize; // Size of ELF header, in bytes + Elf32_Half e_phentsize; // Size of an entry in the program header table + Elf32_Half e_phnum; // Number of entries in the program header table + Elf32_Half e_shentsize; // Size of an entry in the section header table + Elf32_Half e_shnum; // Number of entries in the section header table + Elf32_Half e_shstrndx; // Sect hdr table index of sect name string table + + bool checkMagic() const { + return (memcmp(e_ident, ElfMagic, strlen(ElfMagic))) == 0; + } + + unsigned char getFileClass() const { return e_ident[EI_CLASS]; } + unsigned char getDataEncoding() const { return e_ident[EI_DATA]; } +}; + +// 64-bit ELF header. Fields are the same as for ELF32, but with different +// types (see above). +struct Elf64_Ehdr { + unsigned char e_ident[EI_NIDENT]; + Elf64_Half e_type; + Elf64_Half e_machine; + Elf64_Word e_version; + Elf64_Addr e_entry; + Elf64_Off e_phoff; + Elf64_Off e_shoff; + Elf64_Word e_flags; + Elf64_Half e_ehsize; + Elf64_Half e_phentsize; + Elf64_Half e_phnum; + Elf64_Half e_shentsize; + Elf64_Half e_shnum; + Elf64_Half e_shstrndx; + + bool checkMagic() const { + return (memcmp(e_ident, ElfMagic, strlen(ElfMagic))) == 0; + } + + unsigned char getFileClass() const { return e_ident[EI_CLASS]; } + unsigned char getDataEncoding() const { return e_ident[EI_DATA]; } +}; + +// File types. +// See current registered ELF types at: +// http://www.sco.com/developers/gabi/latest/ch4.eheader.html +enum { + ET_NONE = 0, // No file type + ET_REL = 1, // Relocatable file + ET_EXEC = 2, // Executable file + ET_DYN = 3, // Shared object file + ET_CORE = 4, // Core file + ET_LOOS = 0xfe00, // Beginning of operating system-specific codes + ET_HIOS = 0xfeff, // Operating system-specific + ET_LOPROC = 0xff00, // Beginning of processor-specific codes + ET_HIPROC = 0xffff // Processor-specific +}; + +// Versioning +enum { EV_NONE = 0, EV_CURRENT = 1 }; + +// Machine architectures +// See current registered ELF machine architectures at: +// http://www.uxsglobal.com/developers/gabi/latest/ch4.eheader.html +enum { + EM_NONE = 0, // No machine + EM_M32 = 1, // AT&T WE 32100 + EM_SPARC = 2, // SPARC + EM_386 = 3, // Intel 386 + EM_68K = 4, // Motorola 68000 + EM_88K = 5, // Motorola 88000 + EM_IAMCU = 6, // Intel MCU + EM_860 = 7, // Intel 80860 + EM_MIPS = 8, // MIPS R3000 + EM_S370 = 9, // IBM System/370 + EM_MIPS_RS3_LE = 10, // MIPS RS3000 Little-endian + EM_PARISC = 15, // Hewlett-Packard PA-RISC + EM_VPP500 = 17, // Fujitsu VPP500 + EM_SPARC32PLUS = 18, // Enhanced instruction set SPARC + EM_960 = 19, // Intel 80960 + EM_PPC = 20, // PowerPC + EM_PPC64 = 21, // PowerPC64 + EM_S390 = 22, // IBM System/390 + EM_SPU = 23, // IBM SPU/SPC + EM_V800 = 36, // NEC V800 + EM_FR20 = 37, // Fujitsu FR20 + EM_RH32 = 38, // TRW RH-32 + EM_RCE = 39, // Motorola RCE + EM_ARM = 40, // ARM + EM_ALPHA = 41, // DEC Alpha + EM_SH = 42, // Hitachi SH + EM_SPARCV9 = 43, // SPARC V9 + EM_TRICORE = 44, // Siemens TriCore + EM_ARC = 45, // Argonaut RISC Core + EM_H8_300 = 46, // Hitachi H8/300 + EM_H8_300H = 47, // Hitachi H8/300H + EM_H8S = 48, // Hitachi H8S + EM_H8_500 = 49, // Hitachi H8/500 + EM_IA_64 = 50, // Intel IA-64 processor architecture + EM_MIPS_X = 51, // Stanford MIPS-X + EM_COLDFIRE = 52, // Motorola ColdFire + EM_68HC12 = 53, // Motorola M68HC12 + EM_MMA = 54, // Fujitsu MMA Multimedia Accelerator + EM_PCP = 55, // Siemens PCP + EM_NCPU = 56, // Sony nCPU embedded RISC processor + EM_NDR1 = 57, // Denso NDR1 microprocessor + EM_STARCORE = 58, // Motorola Star*Core processor + EM_ME16 = 59, // Toyota ME16 processor + EM_ST100 = 60, // STMicroelectronics ST100 processor + EM_TINYJ = 61, // Advanced Logic Corp. TinyJ embedded processor family + EM_X86_64 = 62, // AMD x86-64 architecture + EM_PDSP = 63, // Sony DSP Processor + EM_PDP10 = 64, // Digital Equipment Corp. PDP-10 + EM_PDP11 = 65, // Digital Equipment Corp. PDP-11 + EM_FX66 = 66, // Siemens FX66 microcontroller + EM_ST9PLUS = 67, // STMicroelectronics ST9+ 8/16 bit microcontroller + EM_ST7 = 68, // STMicroelectronics ST7 8-bit microcontroller + EM_68HC16 = 69, // Motorola MC68HC16 Microcontroller + EM_68HC11 = 70, // Motorola MC68HC11 Microcontroller + EM_68HC08 = 71, // Motorola MC68HC08 Microcontroller + EM_68HC05 = 72, // Motorola MC68HC05 Microcontroller + EM_SVX = 73, // Silicon Graphics SVx + EM_ST19 = 74, // STMicroelectronics ST19 8-bit microcontroller + EM_VAX = 75, // Digital VAX + EM_CRIS = 76, // Axis Communications 32-bit embedded processor + EM_JAVELIN = 77, // Infineon Technologies 32-bit embedded processor + EM_FIREPATH = 78, // Element 14 64-bit DSP Processor + EM_ZSP = 79, // LSI Logic 16-bit DSP Processor + EM_MMIX = 80, // Donald Knuth's educational 64-bit processor + EM_HUANY = 81, // Harvard University machine-independent object files + EM_PRISM = 82, // SiTera Prism + EM_AVR = 83, // Atmel AVR 8-bit microcontroller + EM_FR30 = 84, // Fujitsu FR30 + EM_D10V = 85, // Mitsubishi D10V + EM_D30V = 86, // Mitsubishi D30V + EM_V850 = 87, // NEC v850 + EM_M32R = 88, // Mitsubishi M32R + EM_MN10300 = 89, // Matsushita MN10300 + EM_MN10200 = 90, // Matsushita MN10200 + EM_PJ = 91, // picoJava + EM_OPENRISC = 92, // OpenRISC 32-bit embedded processor + EM_ARC_COMPACT = 93, // ARC International ARCompact processor (old + // spelling/synonym: EM_ARC_A5) + EM_XTENSA = 94, // Tensilica Xtensa Architecture + EM_VIDEOCORE = 95, // Alphamosaic VideoCore processor + EM_TMM_GPP = 96, // Thompson Multimedia General Purpose Processor + EM_NS32K = 97, // National Semiconductor 32000 series + EM_TPC = 98, // Tenor Network TPC processor + EM_SNP1K = 99, // Trebia SNP 1000 processor + EM_ST200 = 100, // STMicroelectronics (www.st.com) ST200 + EM_IP2K = 101, // Ubicom IP2xxx microcontroller family + EM_MAX = 102, // MAX Processor + EM_CR = 103, // National Semiconductor CompactRISC microprocessor + EM_F2MC16 = 104, // Fujitsu F2MC16 + EM_MSP430 = 105, // Texas Instruments embedded microcontroller msp430 + EM_BLACKFIN = 106, // Analog Devices Blackfin (DSP) processor + EM_SE_C33 = 107, // S1C33 Family of Seiko Epson processors + EM_SEP = 108, // Sharp embedded microprocessor + EM_ARCA = 109, // Arca RISC Microprocessor + EM_UNICORE = 110, // Microprocessor series from PKU-Unity Ltd. and MPRC + // of Peking University + EM_EXCESS = 111, // eXcess: 16/32/64-bit configurable embedded CPU + EM_DXP = 112, // Icera Semiconductor Inc. Deep Execution Processor + EM_ALTERA_NIOS2 = 113, // Altera Nios II soft-core processor + EM_CRX = 114, // National Semiconductor CompactRISC CRX + EM_XGATE = 115, // Motorola XGATE embedded processor + EM_C166 = 116, // Infineon C16x/XC16x processor + EM_M16C = 117, // Renesas M16C series microprocessors + EM_DSPIC30F = 118, // Microchip Technology dsPIC30F Digital Signal + // Controller + EM_CE = 119, // Freescale Communication Engine RISC core + EM_M32C = 120, // Renesas M32C series microprocessors + EM_TSK3000 = 131, // Altium TSK3000 core + EM_RS08 = 132, // Freescale RS08 embedded processor + EM_SHARC = 133, // Analog Devices SHARC family of 32-bit DSP + // processors + EM_ECOG2 = 134, // Cyan Technology eCOG2 microprocessor + EM_SCORE7 = 135, // Sunplus S+core7 RISC processor + EM_DSP24 = 136, // New Japan Radio (NJR) 24-bit DSP Processor + EM_VIDEOCORE3 = 137, // Broadcom VideoCore III processor + EM_LATTICEMICO32 = 138, // RISC processor for Lattice FPGA architecture + EM_SE_C17 = 139, // Seiko Epson C17 family + EM_TI_C6000 = 140, // The Texas Instruments TMS320C6000 DSP family + EM_TI_C2000 = 141, // The Texas Instruments TMS320C2000 DSP family + EM_TI_C5500 = 142, // The Texas Instruments TMS320C55x DSP family + EM_MMDSP_PLUS = 160, // STMicroelectronics 64bit VLIW Data Signal Processor + EM_CYPRESS_M8C = 161, // Cypress M8C microprocessor + EM_R32C = 162, // Renesas R32C series microprocessors + EM_TRIMEDIA = 163, // NXP Semiconductors TriMedia architecture family + EM_HEXAGON = 164, // Qualcomm Hexagon processor + EM_8051 = 165, // Intel 8051 and variants + EM_STXP7X = 166, // STMicroelectronics STxP7x family of configurable + // and extensible RISC processors + EM_NDS32 = 167, // Andes Technology compact code size embedded RISC + // processor family + EM_ECOG1 = 168, // Cyan Technology eCOG1X family + EM_ECOG1X = 168, // Cyan Technology eCOG1X family + EM_MAXQ30 = 169, // Dallas Semiconductor MAXQ30 Core Micro-controllers + EM_XIMO16 = 170, // New Japan Radio (NJR) 16-bit DSP Processor + EM_MANIK = 171, // M2000 Reconfigurable RISC Microprocessor + EM_CRAYNV2 = 172, // Cray Inc. NV2 vector architecture + EM_RX = 173, // Renesas RX family + EM_METAG = 174, // Imagination Technologies META processor + // architecture + EM_MCST_ELBRUS = 175, // MCST Elbrus general purpose hardware architecture + EM_ECOG16 = 176, // Cyan Technology eCOG16 family + EM_CR16 = 177, // National Semiconductor CompactRISC CR16 16-bit + // microprocessor + EM_ETPU = 178, // Freescale Extended Time Processing Unit + EM_SLE9X = 179, // Infineon Technologies SLE9X core + EM_L10M = 180, // Intel L10M + EM_K10M = 181, // Intel K10M + EM_AARCH64 = 183, // ARM AArch64 + EM_AVR32 = 185, // Atmel Corporation 32-bit microprocessor family + EM_STM8 = 186, // STMicroeletronics STM8 8-bit microcontroller + EM_TILE64 = 187, // Tilera TILE64 multicore architecture family + EM_TILEPRO = 188, // Tilera TILEPro multicore architecture family + EM_MICROBLAZE = 189, // Xilinx MicroBlaze 32-bit RISC soft processor core + EM_CUDA = 190, // NVIDIA CUDA architecture + EM_TILEGX = 191, // Tilera TILE-Gx multicore architecture family + EM_CLOUDSHIELD = 192, // CloudShield architecture family + EM_COREA_1ST = 193, // KIPO-KAIST Core-A 1st generation processor family + EM_COREA_2ND = 194, // KIPO-KAIST Core-A 2nd generation processor family + EM_ARC_COMPACT2 = 195, // Synopsys ARCompact V2 + EM_OPEN8 = 196, // Open8 8-bit RISC soft processor core + EM_RL78 = 197, // Renesas RL78 family + EM_VIDEOCORE5 = 198, // Broadcom VideoCore V processor + EM_78KOR = 199, // Renesas 78KOR family + EM_56800EX = 200, // Freescale 56800EX Digital Signal Controller (DSC) + EM_BA1 = 201, // Beyond BA1 CPU architecture + EM_BA2 = 202, // Beyond BA2 CPU architecture + EM_XCORE = 203, // XMOS xCORE processor family + EM_MCHP_PIC = 204, // Microchip 8-bit PIC(r) family + EM_INTEL205 = 205, // Reserved by Intel + EM_INTEL206 = 206, // Reserved by Intel + EM_INTEL207 = 207, // Reserved by Intel + EM_INTEL208 = 208, // Reserved by Intel + EM_INTEL209 = 209, // Reserved by Intel + EM_KM32 = 210, // KM211 KM32 32-bit processor + EM_KMX32 = 211, // KM211 KMX32 32-bit processor + EM_KMX16 = 212, // KM211 KMX16 16-bit processor + EM_KMX8 = 213, // KM211 KMX8 8-bit processor + EM_KVARC = 214, // KM211 KVARC processor + EM_CDP = 215, // Paneve CDP architecture family + EM_COGE = 216, // Cognitive Smart Memory Processor + EM_COOL = 217, // iCelero CoolEngine + EM_NORC = 218, // Nanoradio Optimized RISC + EM_CSR_KALIMBA = 219, // CSR Kalimba architecture family + EM_AMDGPU = 224, // AMD GPU architecture + EM_RISCV = 243, // RISC-V + EM_LANAI = 244, // Lanai 32-bit processor + EM_BPF = 247, // Linux kernel bpf virtual machine + EM_VE = 251, // NEC SX-Aurora VE + EM_CSKY = 252, // C-SKY 32-bit processor + EM_LOONGARCH = 258, // LoongArch +}; + +// Object file classes. +enum { + ELFCLASSNONE = 0, + ELFCLASS32 = 1, // 32-bit object file + ELFCLASS64 = 2 // 64-bit object file +}; + +// Object file byte orderings. +enum { + ELFDATANONE = 0, // Invalid data encoding. + ELFDATA2LSB = 1, // Little-endian object file + ELFDATA2MSB = 2 // Big-endian object file +}; + +// OS ABI identification. +enum { + ELFOSABI_NONE = 0, // UNIX System V ABI + ELFOSABI_HPUX = 1, // HP-UX operating system + ELFOSABI_NETBSD = 2, // NetBSD + ELFOSABI_GNU = 3, // GNU/Linux + ELFOSABI_LINUX = 3, // Historical alias for ELFOSABI_GNU. + ELFOSABI_HURD = 4, // GNU/Hurd + ELFOSABI_SOLARIS = 6, // Solaris + ELFOSABI_AIX = 7, // AIX + ELFOSABI_IRIX = 8, // IRIX + ELFOSABI_FREEBSD = 9, // FreeBSD + ELFOSABI_TRU64 = 10, // TRU64 UNIX + ELFOSABI_MODESTO = 11, // Novell Modesto + ELFOSABI_OPENBSD = 12, // OpenBSD + ELFOSABI_OPENVMS = 13, // OpenVMS + ELFOSABI_NSK = 14, // Hewlett-Packard Non-Stop Kernel + ELFOSABI_AROS = 15, // AROS + ELFOSABI_FENIXOS = 16, // FenixOS + ELFOSABI_CLOUDABI = 17, // Nuxi CloudABI + ELFOSABI_FIRST_ARCH = 64, // First architecture-specific OS ABI + ELFOSABI_AMDGPU_HSA = 64, // AMD HSA runtime + ELFOSABI_AMDGPU_PAL = 65, // AMD PAL runtime + ELFOSABI_AMDGPU_MESA3D = 66, // AMD GCN GPUs (GFX6+) for MESA runtime + ELFOSABI_ARM = 97, // ARM + ELFOSABI_C6000_ELFABI = 64, // Bare-metal TMS320C6000 + ELFOSABI_C6000_LINUX = 65, // Linux TMS320C6000 + ELFOSABI_STANDALONE = 255, // Standalone (embedded) application + ELFOSABI_LAST_ARCH = 255 // Last Architecture-specific OS ABI +}; + +// AMDGPU OS ABI Version identification. +enum { + // ELFABIVERSION_AMDGPU_HSA_V1 does not exist because OS ABI identification + // was never defined for V1. + ELFABIVERSION_AMDGPU_HSA_V2 = 0, + ELFABIVERSION_AMDGPU_HSA_V3 = 1, + ELFABIVERSION_AMDGPU_HSA_V4 = 2, + ELFABIVERSION_AMDGPU_HSA_V5 = 3 +}; + +#define ELF_RELOC(name, value) name = value, + +// X86_64 relocations. +enum { +#include "ELFRelocs/x86_64.def" +}; + +// i386 relocations. +enum { +#include "ELFRelocs/i386.def" +}; + +// ELF Relocation types for PPC32 +enum { +#include "ELFRelocs/PowerPC.def" +}; + +// Specific e_flags for PPC64 +enum { + // e_flags bits specifying ABI: + // 1 for original ABI using function descriptors, + // 2 for revised ABI without function descriptors, + // 0 for unspecified or not using any features affected by the differences. + EF_PPC64_ABI = 3 +}; + +// Special values for the st_other field in the symbol table entry for PPC64. +enum { + STO_PPC64_LOCAL_BIT = 5, + STO_PPC64_LOCAL_MASK = (7 << STO_PPC64_LOCAL_BIT) +}; +static inline int64_t decodePPC64LocalEntryOffset(unsigned Other) { + unsigned Val = (Other & STO_PPC64_LOCAL_MASK) >> STO_PPC64_LOCAL_BIT; + return ((1 << Val) >> 2) << 2; +} + +// ELF Relocation types for PPC64 +enum { +#include "ELFRelocs/PowerPC64.def" +}; + +// ELF Relocation types for AArch64 +enum { +#include "ELFRelocs/AArch64.def" +}; + +// Special values for the st_other field in the symbol table entry for AArch64. +enum { + // Symbol may follow different calling convention than base PCS. + STO_AARCH64_VARIANT_PCS = 0x80 +}; + +// ARM Specific e_flags +enum : unsigned { + EF_ARM_SOFT_FLOAT = 0x00000200U, // Legacy pre EABI_VER5 + EF_ARM_ABI_FLOAT_SOFT = 0x00000200U, // EABI_VER5 + EF_ARM_VFP_FLOAT = 0x00000400U, // Legacy pre EABI_VER5 + EF_ARM_ABI_FLOAT_HARD = 0x00000400U, // EABI_VER5 + EF_ARM_BE8 = 0x00800000U, + EF_ARM_EABI_UNKNOWN = 0x00000000U, + EF_ARM_EABI_VER1 = 0x01000000U, + EF_ARM_EABI_VER2 = 0x02000000U, + EF_ARM_EABI_VER3 = 0x03000000U, + EF_ARM_EABI_VER4 = 0x04000000U, + EF_ARM_EABI_VER5 = 0x05000000U, + EF_ARM_EABIMASK = 0xFF000000U +}; + +// ELF Relocation types for ARM +enum { +#include "ELFRelocs/ARM.def" +}; + +// ARC Specific e_flags +enum : unsigned { + EF_ARC_MACH_MSK = 0x000000ff, + EF_ARC_OSABI_MSK = 0x00000f00, + E_ARC_MACH_ARC600 = 0x00000002, + E_ARC_MACH_ARC601 = 0x00000004, + E_ARC_MACH_ARC700 = 0x00000003, + EF_ARC_CPU_ARCV2EM = 0x00000005, + EF_ARC_CPU_ARCV2HS = 0x00000006, + E_ARC_OSABI_ORIG = 0x00000000, + E_ARC_OSABI_V2 = 0x00000200, + E_ARC_OSABI_V3 = 0x00000300, + E_ARC_OSABI_V4 = 0x00000400, + EF_ARC_PIC = 0x00000100 +}; + +// ELF Relocation types for ARC +enum { +#include "ELFRelocs/ARC.def" +}; + +// AVR specific e_flags +enum : unsigned { + EF_AVR_ARCH_AVR1 = 1, + EF_AVR_ARCH_AVR2 = 2, + EF_AVR_ARCH_AVR25 = 25, + EF_AVR_ARCH_AVR3 = 3, + EF_AVR_ARCH_AVR31 = 31, + EF_AVR_ARCH_AVR35 = 35, + EF_AVR_ARCH_AVR4 = 4, + EF_AVR_ARCH_AVR5 = 5, + EF_AVR_ARCH_AVR51 = 51, + EF_AVR_ARCH_AVR6 = 6, + EF_AVR_ARCH_AVRTINY = 100, + EF_AVR_ARCH_XMEGA1 = 101, + EF_AVR_ARCH_XMEGA2 = 102, + EF_AVR_ARCH_XMEGA3 = 103, + EF_AVR_ARCH_XMEGA4 = 104, + EF_AVR_ARCH_XMEGA5 = 105, + EF_AVR_ARCH_XMEGA6 = 106, + EF_AVR_ARCH_XMEGA7 = 107, + + EF_AVR_ARCH_MASK = 0x7f, // EF_AVR_ARCH_xxx selection mask + + EF_AVR_LINKRELAX_PREPARED = 0x80, // The file is prepared for linker + // relaxation to be applied +}; + +// ELF Relocation types for AVR +enum { +#include "ELFRelocs/AVR.def" +}; + +// Mips Specific e_flags +enum : unsigned { + EF_MIPS_NOREORDER = 0x00000001, // Don't reorder instructions + EF_MIPS_PIC = 0x00000002, // Position independent code + EF_MIPS_CPIC = 0x00000004, // Call object with Position independent code + EF_MIPS_ABI2 = 0x00000020, // File uses N32 ABI + EF_MIPS_32BITMODE = 0x00000100, // Code compiled for a 64-bit machine + // in 32-bit mode + EF_MIPS_FP64 = 0x00000200, // Code compiled for a 32-bit machine + // but uses 64-bit FP registers + EF_MIPS_NAN2008 = 0x00000400, // Uses IEE 754-2008 NaN encoding + + // ABI flags + EF_MIPS_ABI_O32 = 0x00001000, // This file follows the first MIPS 32 bit ABI + EF_MIPS_ABI_O64 = 0x00002000, // O32 ABI extended for 64-bit architecture. + EF_MIPS_ABI_EABI32 = 0x00003000, // EABI in 32 bit mode. + EF_MIPS_ABI_EABI64 = 0x00004000, // EABI in 64 bit mode. + EF_MIPS_ABI = 0x0000f000, // Mask for selecting EF_MIPS_ABI_ variant. + + // MIPS machine variant + EF_MIPS_MACH_NONE = 0x00000000, // A standard MIPS implementation. + EF_MIPS_MACH_3900 = 0x00810000, // Toshiba R3900 + EF_MIPS_MACH_4010 = 0x00820000, // LSI R4010 + EF_MIPS_MACH_4100 = 0x00830000, // NEC VR4100 + EF_MIPS_MACH_4650 = 0x00850000, // MIPS R4650 + EF_MIPS_MACH_4120 = 0x00870000, // NEC VR4120 + EF_MIPS_MACH_4111 = 0x00880000, // NEC VR4111/VR4181 + EF_MIPS_MACH_SB1 = 0x008a0000, // Broadcom SB-1 + EF_MIPS_MACH_OCTEON = 0x008b0000, // Cavium Networks Octeon + EF_MIPS_MACH_XLR = 0x008c0000, // RMI Xlr + EF_MIPS_MACH_OCTEON2 = 0x008d0000, // Cavium Networks Octeon2 + EF_MIPS_MACH_OCTEON3 = 0x008e0000, // Cavium Networks Octeon3 + EF_MIPS_MACH_5400 = 0x00910000, // NEC VR5400 + EF_MIPS_MACH_5900 = 0x00920000, // MIPS R5900 + EF_MIPS_MACH_5500 = 0x00980000, // NEC VR5500 + EF_MIPS_MACH_9000 = 0x00990000, // Unknown + EF_MIPS_MACH_LS2E = 0x00a00000, // ST Microelectronics Loongson 2E + EF_MIPS_MACH_LS2F = 0x00a10000, // ST Microelectronics Loongson 2F + EF_MIPS_MACH_LS3A = 0x00a20000, // Loongson 3A + EF_MIPS_MACH = 0x00ff0000, // EF_MIPS_MACH_xxx selection mask + + // ARCH_ASE + EF_MIPS_MICROMIPS = 0x02000000, // microMIPS + EF_MIPS_ARCH_ASE_M16 = 0x04000000, // Has Mips-16 ISA extensions + EF_MIPS_ARCH_ASE_MDMX = 0x08000000, // Has MDMX multimedia extensions + EF_MIPS_ARCH_ASE = 0x0f000000, // Mask for EF_MIPS_ARCH_ASE_xxx flags + + // ARCH + EF_MIPS_ARCH_1 = 0x00000000, // MIPS1 instruction set + EF_MIPS_ARCH_2 = 0x10000000, // MIPS2 instruction set + EF_MIPS_ARCH_3 = 0x20000000, // MIPS3 instruction set + EF_MIPS_ARCH_4 = 0x30000000, // MIPS4 instruction set + EF_MIPS_ARCH_5 = 0x40000000, // MIPS5 instruction set + EF_MIPS_ARCH_32 = 0x50000000, // MIPS32 instruction set per linux not elf.h + EF_MIPS_ARCH_64 = 0x60000000, // MIPS64 instruction set per linux not elf.h + EF_MIPS_ARCH_32R2 = 0x70000000, // mips32r2, mips32r3, mips32r5 + EF_MIPS_ARCH_64R2 = 0x80000000, // mips64r2, mips64r3, mips64r5 + EF_MIPS_ARCH_32R6 = 0x90000000, // mips32r6 + EF_MIPS_ARCH_64R6 = 0xa0000000, // mips64r6 + EF_MIPS_ARCH = 0xf0000000 // Mask for applying EF_MIPS_ARCH_ variant +}; + +// MIPS-specific section indexes +enum { + SHN_MIPS_ACOMMON = 0xff00, // Common symbols which are defined and allocated + SHN_MIPS_TEXT = 0xff01, // Not ABI compliant + SHN_MIPS_DATA = 0xff02, // Not ABI compliant + SHN_MIPS_SCOMMON = 0xff03, // Common symbols for global data area + SHN_MIPS_SUNDEFINED = 0xff04 // Undefined symbols for global data area +}; + +// ELF Relocation types for Mips +enum { +#include "ELFRelocs/Mips.def" +}; + +// Special values for the st_other field in the symbol table entry for MIPS. +enum { + STO_MIPS_OPTIONAL = 0x04, // Symbol whose definition is optional + STO_MIPS_PLT = 0x08, // PLT entry related dynamic table record + STO_MIPS_PIC = 0x20, // PIC func in an object mixes PIC/non-PIC + STO_MIPS_MICROMIPS = 0x80, // MIPS Specific ISA for MicroMips + STO_MIPS_MIPS16 = 0xf0 // MIPS Specific ISA for Mips16 +}; + +// .MIPS.options section descriptor kinds +enum { + ODK_NULL = 0, // Undefined + ODK_REGINFO = 1, // Register usage information + ODK_EXCEPTIONS = 2, // Exception processing options + ODK_PAD = 3, // Section padding options + ODK_HWPATCH = 4, // Hardware patches applied + ODK_FILL = 5, // Linker fill value + ODK_TAGS = 6, // Space for tool identification + ODK_HWAND = 7, // Hardware AND patches applied + ODK_HWOR = 8, // Hardware OR patches applied + ODK_GP_GROUP = 9, // GP group to use for text/data sections + ODK_IDENT = 10, // ID information + ODK_PAGESIZE = 11 // Page size information +}; + +// Hexagon-specific e_flags +enum { + // Object processor version flags, bits[11:0] + EF_HEXAGON_MACH_V2 = 0x00000001, // Hexagon V2 + EF_HEXAGON_MACH_V3 = 0x00000002, // Hexagon V3 + EF_HEXAGON_MACH_V4 = 0x00000003, // Hexagon V4 + EF_HEXAGON_MACH_V5 = 0x00000004, // Hexagon V5 + EF_HEXAGON_MACH_V55 = 0x00000005, // Hexagon V55 + EF_HEXAGON_MACH_V60 = 0x00000060, // Hexagon V60 + EF_HEXAGON_MACH_V62 = 0x00000062, // Hexagon V62 + EF_HEXAGON_MACH_V65 = 0x00000065, // Hexagon V65 + EF_HEXAGON_MACH_V66 = 0x00000066, // Hexagon V66 + EF_HEXAGON_MACH_V67 = 0x00000067, // Hexagon V67 + EF_HEXAGON_MACH_V67T = 0x00008067, // Hexagon V67T + EF_HEXAGON_MACH_V68 = 0x00000068, // Hexagon V68 + EF_HEXAGON_MACH_V69 = 0x00000069, // Hexagon V69 + EF_HEXAGON_MACH_V71 = 0x00000071, // Hexagon V71 + EF_HEXAGON_MACH_V71T = 0x00008071, // Hexagon V71T + EF_HEXAGON_MACH_V73 = 0x00000073, // Hexagon V73 + EF_HEXAGON_MACH = 0x000003ff, // Hexagon V.. + + // Highest ISA version flags + EF_HEXAGON_ISA_MACH = 0x00000000, // Same as specified in bits[11:0] + // of e_flags + EF_HEXAGON_ISA_V2 = 0x00000010, // Hexagon V2 ISA + EF_HEXAGON_ISA_V3 = 0x00000020, // Hexagon V3 ISA + EF_HEXAGON_ISA_V4 = 0x00000030, // Hexagon V4 ISA + EF_HEXAGON_ISA_V5 = 0x00000040, // Hexagon V5 ISA + EF_HEXAGON_ISA_V55 = 0x00000050, // Hexagon V55 ISA + EF_HEXAGON_ISA_V60 = 0x00000060, // Hexagon V60 ISA + EF_HEXAGON_ISA_V62 = 0x00000062, // Hexagon V62 ISA + EF_HEXAGON_ISA_V65 = 0x00000065, // Hexagon V65 ISA + EF_HEXAGON_ISA_V66 = 0x00000066, // Hexagon V66 ISA + EF_HEXAGON_ISA_V67 = 0x00000067, // Hexagon V67 ISA + EF_HEXAGON_ISA_V68 = 0x00000068, // Hexagon V68 ISA + EF_HEXAGON_ISA_V69 = 0x00000069, // Hexagon V69 ISA + EF_HEXAGON_ISA_V71 = 0x00000071, // Hexagon V71 ISA + EF_HEXAGON_ISA_V73 = 0x00000073, // Hexagon V73 ISA + EF_HEXAGON_ISA_V75 = 0x00000075, // Hexagon V75 ISA + EF_HEXAGON_ISA = 0x000003ff, // Hexagon V.. ISA +}; + +// Hexagon-specific section indexes for common small data +enum { + SHN_HEXAGON_SCOMMON = 0xff00, // Other access sizes + SHN_HEXAGON_SCOMMON_1 = 0xff01, // Byte-sized access + SHN_HEXAGON_SCOMMON_2 = 0xff02, // Half-word-sized access + SHN_HEXAGON_SCOMMON_4 = 0xff03, // Word-sized access + SHN_HEXAGON_SCOMMON_8 = 0xff04 // Double-word-size access +}; + +// ELF Relocation types for Hexagon +enum { +#include "ELFRelocs/Hexagon.def" +}; + +// ELF Relocation type for Lanai. +enum { +#include "ELFRelocs/Lanai.def" +}; + +// RISCV Specific e_flags +enum : unsigned { + EF_RISCV_RVC = 0x0001, + EF_RISCV_FLOAT_ABI = 0x0006, + EF_RISCV_FLOAT_ABI_SOFT = 0x0000, + EF_RISCV_FLOAT_ABI_SINGLE = 0x0002, + EF_RISCV_FLOAT_ABI_DOUBLE = 0x0004, + EF_RISCV_FLOAT_ABI_QUAD = 0x0006, + EF_RISCV_RVE = 0x0008, + EF_RISCV_TSO = 0x0010, +}; + +// ELF Relocation types for RISC-V +enum { +#include "ELFRelocs/RISCV.def" +}; + +enum { + // Symbol may follow different calling convention than the standard calling + // convention. + STO_RISCV_VARIANT_CC = 0x80 +}; + +// ELF Relocation types for S390/zSeries +enum { +#include "ELFRelocs/SystemZ.def" +}; + +// ELF Relocation type for Sparc. +enum { +#include "ELFRelocs/Sparc.def" +}; + +// AMDGPU specific e_flags. +enum : unsigned { + // Processor selection mask for EF_AMDGPU_MACH_* values. + EF_AMDGPU_MACH = 0x0ff, + + // Not specified processor. + EF_AMDGPU_MACH_NONE = 0x000, + + // R600-based processors. + + // Radeon HD 2000/3000 Series (R600). + EF_AMDGPU_MACH_R600_R600 = 0x001, + EF_AMDGPU_MACH_R600_R630 = 0x002, + EF_AMDGPU_MACH_R600_RS880 = 0x003, + EF_AMDGPU_MACH_R600_RV670 = 0x004, + // Radeon HD 4000 Series (R700). + EF_AMDGPU_MACH_R600_RV710 = 0x005, + EF_AMDGPU_MACH_R600_RV730 = 0x006, + EF_AMDGPU_MACH_R600_RV770 = 0x007, + // Radeon HD 5000 Series (Evergreen). + EF_AMDGPU_MACH_R600_CEDAR = 0x008, + EF_AMDGPU_MACH_R600_CYPRESS = 0x009, + EF_AMDGPU_MACH_R600_JUNIPER = 0x00a, + EF_AMDGPU_MACH_R600_REDWOOD = 0x00b, + EF_AMDGPU_MACH_R600_SUMO = 0x00c, + // Radeon HD 6000 Series (Northern Islands). + EF_AMDGPU_MACH_R600_BARTS = 0x00d, + EF_AMDGPU_MACH_R600_CAICOS = 0x00e, + EF_AMDGPU_MACH_R600_CAYMAN = 0x00f, + EF_AMDGPU_MACH_R600_TURKS = 0x010, + + // Reserved for R600-based processors. + EF_AMDGPU_MACH_R600_RESERVED_FIRST = 0x011, + EF_AMDGPU_MACH_R600_RESERVED_LAST = 0x01f, + + // First/last R600-based processors. + EF_AMDGPU_MACH_R600_FIRST = EF_AMDGPU_MACH_R600_R600, + EF_AMDGPU_MACH_R600_LAST = EF_AMDGPU_MACH_R600_TURKS, + + // AMDGCN-based processors. + EF_AMDGPU_MACH_AMDGCN_GFX600 = 0x020, + EF_AMDGPU_MACH_AMDGCN_GFX601 = 0x021, + EF_AMDGPU_MACH_AMDGCN_GFX700 = 0x022, + EF_AMDGPU_MACH_AMDGCN_GFX701 = 0x023, + EF_AMDGPU_MACH_AMDGCN_GFX702 = 0x024, + EF_AMDGPU_MACH_AMDGCN_GFX703 = 0x025, + EF_AMDGPU_MACH_AMDGCN_GFX704 = 0x026, + EF_AMDGPU_MACH_AMDGCN_RESERVED_0X27 = 0x027, + EF_AMDGPU_MACH_AMDGCN_GFX801 = 0x028, + EF_AMDGPU_MACH_AMDGCN_GFX802 = 0x029, + EF_AMDGPU_MACH_AMDGCN_GFX803 = 0x02a, + EF_AMDGPU_MACH_AMDGCN_GFX810 = 0x02b, + EF_AMDGPU_MACH_AMDGCN_GFX900 = 0x02c, + EF_AMDGPU_MACH_AMDGCN_GFX902 = 0x02d, + EF_AMDGPU_MACH_AMDGCN_GFX904 = 0x02e, + EF_AMDGPU_MACH_AMDGCN_GFX906 = 0x02f, + EF_AMDGPU_MACH_AMDGCN_GFX908 = 0x030, + EF_AMDGPU_MACH_AMDGCN_GFX909 = 0x031, + EF_AMDGPU_MACH_AMDGCN_GFX90C = 0x032, + EF_AMDGPU_MACH_AMDGCN_GFX1010 = 0x033, + EF_AMDGPU_MACH_AMDGCN_GFX1011 = 0x034, + EF_AMDGPU_MACH_AMDGCN_GFX1012 = 0x035, + EF_AMDGPU_MACH_AMDGCN_GFX1030 = 0x036, + EF_AMDGPU_MACH_AMDGCN_GFX1031 = 0x037, + EF_AMDGPU_MACH_AMDGCN_GFX1032 = 0x038, + EF_AMDGPU_MACH_AMDGCN_GFX1033 = 0x039, + EF_AMDGPU_MACH_AMDGCN_GFX602 = 0x03a, + EF_AMDGPU_MACH_AMDGCN_GFX705 = 0x03b, + EF_AMDGPU_MACH_AMDGCN_GFX805 = 0x03c, + EF_AMDGPU_MACH_AMDGCN_GFX1035 = 0x03d, + EF_AMDGPU_MACH_AMDGCN_GFX1034 = 0x03e, + EF_AMDGPU_MACH_AMDGCN_GFX90A = 0x03f, + EF_AMDGPU_MACH_AMDGCN_GFX940 = 0x040, + EF_AMDGPU_MACH_AMDGCN_GFX1100 = 0x041, + EF_AMDGPU_MACH_AMDGCN_GFX1013 = 0x042, + EF_AMDGPU_MACH_AMDGCN_GFX1150 = 0x043, + EF_AMDGPU_MACH_AMDGCN_GFX1103 = 0x044, + EF_AMDGPU_MACH_AMDGCN_GFX1036 = 0x045, + EF_AMDGPU_MACH_AMDGCN_GFX1101 = 0x046, + EF_AMDGPU_MACH_AMDGCN_GFX1102 = 0x047, + EF_AMDGPU_MACH_AMDGCN_RESERVED_0X48 = 0x048, + EF_AMDGPU_MACH_AMDGCN_RESERVED_0X49 = 0x049, + EF_AMDGPU_MACH_AMDGCN_GFX1151 = 0x04a, + EF_AMDGPU_MACH_AMDGCN_GFX941 = 0x04b, + EF_AMDGPU_MACH_AMDGCN_GFX942 = 0x04c, + + // First/last AMDGCN-based processors. + EF_AMDGPU_MACH_AMDGCN_FIRST = EF_AMDGPU_MACH_AMDGCN_GFX600, + EF_AMDGPU_MACH_AMDGCN_LAST = EF_AMDGPU_MACH_AMDGCN_GFX942, + + // Indicates if the "xnack" target feature is enabled for all code contained + // in the object. + // + // Only valid for ELFOSABI_AMDGPU_HSA and ELFABIVERSION_AMDGPU_HSA_V2. + EF_AMDGPU_FEATURE_XNACK_V2 = 0x01, + // Indicates if the trap handler is enabled for all code contained + // in the object. + // + // Only valid for ELFOSABI_AMDGPU_HSA and ELFABIVERSION_AMDGPU_HSA_V2. + EF_AMDGPU_FEATURE_TRAP_HANDLER_V2 = 0x02, + + // Indicates if the "xnack" target feature is enabled for all code contained + // in the object. + // + // Only valid for ELFOSABI_AMDGPU_HSA and ELFABIVERSION_AMDGPU_HSA_V3. + EF_AMDGPU_FEATURE_XNACK_V3 = 0x100, + // Indicates if the "sramecc" target feature is enabled for all code + // contained in the object. + // + // Only valid for ELFOSABI_AMDGPU_HSA and ELFABIVERSION_AMDGPU_HSA_V3. + EF_AMDGPU_FEATURE_SRAMECC_V3 = 0x200, + + // XNACK selection mask for EF_AMDGPU_FEATURE_XNACK_* values. + // + // Only valid for ELFOSABI_AMDGPU_HSA and ELFABIVERSION_AMDGPU_HSA_V4. + EF_AMDGPU_FEATURE_XNACK_V4 = 0x300, + // XNACK is not supported. + EF_AMDGPU_FEATURE_XNACK_UNSUPPORTED_V4 = 0x000, + // XNACK is any/default/unspecified. + EF_AMDGPU_FEATURE_XNACK_ANY_V4 = 0x100, + // XNACK is off. + EF_AMDGPU_FEATURE_XNACK_OFF_V4 = 0x200, + // XNACK is on. + EF_AMDGPU_FEATURE_XNACK_ON_V4 = 0x300, + + // SRAMECC selection mask for EF_AMDGPU_FEATURE_SRAMECC_* values. + // + // Only valid for ELFOSABI_AMDGPU_HSA and ELFABIVERSION_AMDGPU_HSA_V4. + EF_AMDGPU_FEATURE_SRAMECC_V4 = 0xc00, + // SRAMECC is not supported. + EF_AMDGPU_FEATURE_SRAMECC_UNSUPPORTED_V4 = 0x000, + // SRAMECC is any/default/unspecified. + EF_AMDGPU_FEATURE_SRAMECC_ANY_V4 = 0x400, + // SRAMECC is off. + EF_AMDGPU_FEATURE_SRAMECC_OFF_V4 = 0x800, + // SRAMECC is on. + EF_AMDGPU_FEATURE_SRAMECC_ON_V4 = 0xc00, +}; + +// ELF Relocation types for AMDGPU +enum { +#include "ELFRelocs/AMDGPU.def" +}; + +// ELF Relocation types for BPF +enum { +#include "ELFRelocs/BPF.def" +}; + +// ELF Relocation types for M68k +enum { +#include "ELFRelocs/M68k.def" +}; + +// MSP430 specific e_flags +enum : unsigned { + EF_MSP430_MACH_MSP430x11 = 11, + EF_MSP430_MACH_MSP430x11x1 = 110, + EF_MSP430_MACH_MSP430x12 = 12, + EF_MSP430_MACH_MSP430x13 = 13, + EF_MSP430_MACH_MSP430x14 = 14, + EF_MSP430_MACH_MSP430x15 = 15, + EF_MSP430_MACH_MSP430x16 = 16, + EF_MSP430_MACH_MSP430x20 = 20, + EF_MSP430_MACH_MSP430x22 = 22, + EF_MSP430_MACH_MSP430x23 = 23, + EF_MSP430_MACH_MSP430x24 = 24, + EF_MSP430_MACH_MSP430x26 = 26, + EF_MSP430_MACH_MSP430x31 = 31, + EF_MSP430_MACH_MSP430x32 = 32, + EF_MSP430_MACH_MSP430x33 = 33, + EF_MSP430_MACH_MSP430x41 = 41, + EF_MSP430_MACH_MSP430x42 = 42, + EF_MSP430_MACH_MSP430x43 = 43, + EF_MSP430_MACH_MSP430x44 = 44, + EF_MSP430_MACH_MSP430X = 45, + EF_MSP430_MACH_MSP430x46 = 46, + EF_MSP430_MACH_MSP430x47 = 47, + EF_MSP430_MACH_MSP430x54 = 54, +}; + +// ELF Relocation types for MSP430 +enum { +#include "ELFRelocs/MSP430.def" +}; + +// ELF Relocation type for VE. +enum { +#include "ELFRelocs/VE.def" +}; + +// CSKY Specific e_flags +enum : unsigned { + EF_CSKY_801 = 0xa, + EF_CSKY_802 = 0x10, + EF_CSKY_803 = 0x9, + EF_CSKY_805 = 0x11, + EF_CSKY_807 = 0x6, + EF_CSKY_810 = 0x8, + EF_CSKY_860 = 0xb, + EF_CSKY_800 = 0x1f, + EF_CSKY_FLOAT = 0x2000, + EF_CSKY_DSP = 0x4000, + EF_CSKY_ABIV2 = 0x20000000, + EF_CSKY_EFV1 = 0x1000000, + EF_CSKY_EFV2 = 0x2000000, + EF_CSKY_EFV3 = 0x3000000 +}; + +// ELF Relocation types for CSKY +enum { +#include "ELFRelocs/CSKY.def" +}; + +// LoongArch Specific e_flags +enum : unsigned { + // Definitions from LoongArch ELF psABI v2.01. + // Reference: https://github.com/loongson/LoongArch-Documentation + // (commit hash 296de4def055c871809068e0816325a4ac04eb12) + + // Base ABI Modifiers + EF_LOONGARCH_ABI_SOFT_FLOAT = 0x1, + EF_LOONGARCH_ABI_SINGLE_FLOAT = 0x2, + EF_LOONGARCH_ABI_DOUBLE_FLOAT = 0x3, + EF_LOONGARCH_ABI_MODIFIER_MASK = 0x7, + + // Object file ABI versions + EF_LOONGARCH_OBJABI_V0 = 0x0, + EF_LOONGARCH_OBJABI_V1 = 0x40, + EF_LOONGARCH_OBJABI_MASK = 0xC0, +}; + +// ELF Relocation types for LoongArch +enum { +#include "ELFRelocs/LoongArch.def" +}; + +// Xtensa specific e_flags +enum : unsigned { + // Four-bit Xtensa machine type mask. + EF_XTENSA_MACH = 0x0000000f, + // Various CPU types. + EF_XTENSA_MACH_NONE = 0x00000000, // A base Xtensa implementation + EF_XTENSA_XT_INSN = 0x00000100, + EF_XTENSA_XT_LIT = 0x00000200, +}; + +// ELF Relocation types for Xtensa +enum { +#include "ELFRelocs/Xtensa.def" +}; + +#undef ELF_RELOC + +// Section header. +struct Elf32_Shdr { + Elf32_Word sh_name; // Section name (index into string table) + Elf32_Word sh_type; // Section type (SHT_*) + Elf32_Word sh_flags; // Section flags (SHF_*) + Elf32_Addr sh_addr; // Address where section is to be loaded + Elf32_Off sh_offset; // File offset of section data, in bytes + Elf32_Word sh_size; // Size of section, in bytes + Elf32_Word sh_link; // Section type-specific header table index link + Elf32_Word sh_info; // Section type-specific extra information + Elf32_Word sh_addralign; // Section address alignment + Elf32_Word sh_entsize; // Size of records contained within the section +}; + +// Section header for ELF64 - same fields as ELF32, different types. +struct Elf64_Shdr { + Elf64_Word sh_name; + Elf64_Word sh_type; + Elf64_Xword sh_flags; + Elf64_Addr sh_addr; + Elf64_Off sh_offset; + Elf64_Xword sh_size; + Elf64_Word sh_link; + Elf64_Word sh_info; + Elf64_Xword sh_addralign; + Elf64_Xword sh_entsize; +}; + +// Special section indices. +enum { + SHN_UNDEF = 0, // Undefined, missing, irrelevant, or meaningless + SHN_LORESERVE = 0xff00, // Lowest reserved index + SHN_LOPROC = 0xff00, // Lowest processor-specific index + SHN_HIPROC = 0xff1f, // Highest processor-specific index + SHN_LOOS = 0xff20, // Lowest operating system-specific index + SHN_HIOS = 0xff3f, // Highest operating system-specific index + SHN_ABS = 0xfff1, // Symbol has absolute value; does not need relocation + SHN_COMMON = 0xfff2, // FORTRAN COMMON or C external global variables + SHN_XINDEX = 0xffff, // Mark that the index is >= SHN_LORESERVE + SHN_HIRESERVE = 0xffff // Highest reserved index +}; + +// Section types. +enum : unsigned { + SHT_NULL = 0, // No associated section (inactive entry). + SHT_PROGBITS = 1, // Program-defined contents. + SHT_SYMTAB = 2, // Symbol table. + SHT_STRTAB = 3, // String table. + SHT_RELA = 4, // Relocation entries; explicit addends. + SHT_HASH = 5, // Symbol hash table. + SHT_DYNAMIC = 6, // Information for dynamic linking. + SHT_NOTE = 7, // Information about the file. + SHT_NOBITS = 8, // Data occupies no space in the file. + SHT_REL = 9, // Relocation entries; no explicit addends. + SHT_SHLIB = 10, // Reserved. + SHT_DYNSYM = 11, // Symbol table. + SHT_INIT_ARRAY = 14, // Pointers to initialization functions. + SHT_FINI_ARRAY = 15, // Pointers to termination functions. + SHT_PREINIT_ARRAY = 16, // Pointers to pre-init functions. + SHT_GROUP = 17, // Section group. + SHT_SYMTAB_SHNDX = 18, // Indices for SHN_XINDEX entries. + // Experimental support for SHT_RELR sections. For details, see proposal + // at https://groups.google.com/forum/#!topic/generic-abi/bX460iggiKg + SHT_RELR = 19, // Relocation entries; only offsets. + SHT_LOOS = 0x60000000, // Lowest operating system-specific type. + // Android packed relocation section types. + // https://android.googlesource.com/platform/bionic/+/6f12bfece5dcc01325e0abba56a46b1bcf991c69/tools/relocation_packer/src/elf_file.cc#37 + SHT_ANDROID_REL = 0x60000001, + SHT_ANDROID_RELA = 0x60000002, + SHT_LLVM_ODRTAB = 0x6fff4c00, // LLVM ODR table. + SHT_LLVM_LINKER_OPTIONS = 0x6fff4c01, // LLVM Linker Options. + SHT_LLVM_ADDRSIG = 0x6fff4c03, // List of address-significant symbols + // for safe ICF. + SHT_LLVM_DEPENDENT_LIBRARIES = + 0x6fff4c04, // LLVM Dependent Library Specifiers. + SHT_LLVM_SYMPART = 0x6fff4c05, // Symbol partition specification. + SHT_LLVM_PART_EHDR = 0x6fff4c06, // ELF header for loadable partition. + SHT_LLVM_PART_PHDR = 0x6fff4c07, // Phdrs for loadable partition. + SHT_LLVM_BB_ADDR_MAP_V0 = + 0x6fff4c08, // LLVM Basic Block Address Map (old version kept for + // backward-compatibility). + SHT_LLVM_CALL_GRAPH_PROFILE = 0x6fff4c09, // LLVM Call Graph Profile. + SHT_LLVM_BB_ADDR_MAP = 0x6fff4c0a, // LLVM Basic Block Address Map. + SHT_LLVM_OFFLOADING = 0x6fff4c0b, // LLVM device offloading data. + SHT_LLVM_LTO = 0x6fff4c0c, // .llvm.lto for fat LTO. + // Android's experimental support for SHT_RELR sections. + // https://android.googlesource.com/platform/bionic/+/b7feec74547f84559a1467aca02708ff61346d2a/libc/include/elf.h#512 + SHT_ANDROID_RELR = 0x6fffff00, // Relocation entries; only offsets. + SHT_GNU_ATTRIBUTES = 0x6ffffff5, // Object attributes. + SHT_GNU_HASH = 0x6ffffff6, // GNU-style hash table. + SHT_GNU_verdef = 0x6ffffffd, // GNU version definitions. + SHT_GNU_verneed = 0x6ffffffe, // GNU version references. + SHT_GNU_versym = 0x6fffffff, // GNU symbol versions table. + SHT_HIOS = 0x6fffffff, // Highest operating system-specific type. + SHT_LOPROC = 0x70000000, // Lowest processor arch-specific type. + // Fixme: All this is duplicated in MCSectionELF. Why?? + // Exception Index table + SHT_ARM_EXIDX = 0x70000001U, + // BPABI DLL dynamic linking pre-emption map + SHT_ARM_PREEMPTMAP = 0x70000002U, + // Object file compatibility attributes + SHT_ARM_ATTRIBUTES = 0x70000003U, + SHT_ARM_DEBUGOVERLAY = 0x70000004U, + SHT_ARM_OVERLAYSECTION = 0x70000005U, + // Special aarch64-specific sections for MTE support, as described in: + // https://github.com/ARM-software/abi-aa/blob/main/memtagabielf64/memtagabielf64.rst#7section-types + SHT_AARCH64_MEMTAG_GLOBALS_STATIC = 0x70000007U, + SHT_AARCH64_MEMTAG_GLOBALS_DYNAMIC = 0x70000008U, + SHT_HEX_ORDERED = 0x70000000, // Link editor is to sort the entries in + // this section based on their sizes + SHT_X86_64_UNWIND = 0x70000001, // Unwind information + + SHT_MIPS_REGINFO = 0x70000006, // Register usage information + SHT_MIPS_OPTIONS = 0x7000000d, // General options + SHT_MIPS_DWARF = 0x7000001e, // DWARF debugging section. + SHT_MIPS_ABIFLAGS = 0x7000002a, // ABI information. + + SHT_MSP430_ATTRIBUTES = 0x70000003U, + + SHT_RISCV_ATTRIBUTES = 0x70000003U, + + SHT_CSKY_ATTRIBUTES = 0x70000001U, + + SHT_HIPROC = 0x7fffffff, // Highest processor arch-specific type. + SHT_LOUSER = 0x80000000, // Lowest type reserved for applications. + SHT_HIUSER = 0xffffffff // Highest type reserved for applications. +}; + +// Section flags. +enum : unsigned { + // Section data should be writable during execution. + SHF_WRITE = 0x1, + + // Section occupies memory during program execution. + SHF_ALLOC = 0x2, + + // Section contains executable machine instructions. + SHF_EXECINSTR = 0x4, + + // The data in this section may be merged. + SHF_MERGE = 0x10, + + // The data in this section is null-terminated strings. + SHF_STRINGS = 0x20, + + // A field in this section holds a section header table index. + SHF_INFO_LINK = 0x40U, + + // Adds special ordering requirements for link editors. + SHF_LINK_ORDER = 0x80U, + + // This section requires special OS-specific processing to avoid incorrect + // behavior. + SHF_OS_NONCONFORMING = 0x100U, + + // This section is a member of a section group. + SHF_GROUP = 0x200U, + + // This section holds Thread-Local Storage. + SHF_TLS = 0x400U, + + // Identifies a section containing compressed data. + SHF_COMPRESSED = 0x800U, + + // This section should not be garbage collected by the linker. + SHF_GNU_RETAIN = 0x200000, + + // This section is excluded from the final executable or shared library. + SHF_EXCLUDE = 0x80000000U, + + // Start of target-specific flags. + + SHF_MASKOS = 0x0ff00000, + + // Solaris equivalent of SHF_GNU_RETAIN. + SHF_SUNW_NODISCARD = 0x00100000, + + // Bits indicating processor-specific flags. + SHF_MASKPROC = 0xf0000000, + + /// All sections with the "d" flag are grouped together by the linker to form + /// the data section and the dp register is set to the start of the section by + /// the boot code. + XCORE_SHF_DP_SECTION = 0x10000000, + + /// All sections with the "c" flag are grouped together by the linker to form + /// the constant pool and the cp register is set to the start of the constant + /// pool by the boot code. + XCORE_SHF_CP_SECTION = 0x20000000, + + // If an object file section does not have this flag set, then it may not hold + // more than 2GB and can be freely referred to in objects using smaller code + // models. Otherwise, only objects using larger code models can refer to them. + // For example, a medium code model object can refer to data in a section that + // sets this flag besides being able to refer to data in a section that does + // not set it; likewise, a small code model object can refer only to code in a + // section that does not set this flag. + SHF_X86_64_LARGE = 0x10000000, + + // All sections with the GPREL flag are grouped into a global data area + // for faster accesses + SHF_HEX_GPREL = 0x10000000, + + // Section contains text/data which may be replicated in other sections. + // Linker must retain only one copy. + SHF_MIPS_NODUPES = 0x01000000, + + // Linker must generate implicit hidden weak names. + SHF_MIPS_NAMES = 0x02000000, + + // Section data local to process. + SHF_MIPS_LOCAL = 0x04000000, + + // Do not strip this section. + SHF_MIPS_NOSTRIP = 0x08000000, + + // Section must be part of global data area. + SHF_MIPS_GPREL = 0x10000000, + + // This section should be merged. + SHF_MIPS_MERGE = 0x20000000, + + // Address size to be inferred from section entry size. + SHF_MIPS_ADDR = 0x40000000, + + // Section data is string data by default. + SHF_MIPS_STRING = 0x80000000, + + // Make code section unreadable when in execute-only mode + SHF_ARM_PURECODE = 0x20000000 +}; + +// Section Group Flags +enum : unsigned { + GRP_COMDAT = 0x1, + GRP_MASKOS = 0x0ff00000, + GRP_MASKPROC = 0xf0000000 +}; + +// Symbol table entries for ELF32. +struct Elf32_Sym { + Elf32_Word st_name; // Symbol name (index into string table) + Elf32_Addr st_value; // Value or address associated with the symbol + Elf32_Word st_size; // Size of the symbol + unsigned char st_info; // Symbol's type and binding attributes + unsigned char st_other; // Must be zero; reserved + Elf32_Half st_shndx; // Which section (header table index) it's defined in + + // These accessors and mutators correspond to the ELF32_ST_BIND, + // ELF32_ST_TYPE, and ELF32_ST_INFO macros defined in the ELF specification: + unsigned char getBinding() const { return st_info >> 4; } + unsigned char getType() const { return st_info & 0x0f; } + void setBinding(unsigned char b) { setBindingAndType(b, getType()); } + void setType(unsigned char t) { setBindingAndType(getBinding(), t); } + void setBindingAndType(unsigned char b, unsigned char t) { + st_info = (b << 4) + (t & 0x0f); + } +}; + +// Symbol table entries for ELF64. +struct Elf64_Sym { + Elf64_Word st_name; // Symbol name (index into string table) + unsigned char st_info; // Symbol's type and binding attributes + unsigned char st_other; // Must be zero; reserved + Elf64_Half st_shndx; // Which section (header tbl index) it's defined in + Elf64_Addr st_value; // Value or address associated with the symbol + Elf64_Xword st_size; // Size of the symbol + + // These accessors and mutators are identical to those defined for ELF32 + // symbol table entries. + unsigned char getBinding() const { return st_info >> 4; } + unsigned char getType() const { return st_info & 0x0f; } + void setBinding(unsigned char b) { setBindingAndType(b, getType()); } + void setType(unsigned char t) { setBindingAndType(getBinding(), t); } + void setBindingAndType(unsigned char b, unsigned char t) { + st_info = (b << 4) + (t & 0x0f); + } +}; + +// The size (in bytes) of symbol table entries. +enum { + SYMENTRY_SIZE32 = 16, // 32-bit symbol entry size + SYMENTRY_SIZE64 = 24 // 64-bit symbol entry size. +}; + +// Symbol bindings. +enum { + STB_LOCAL = 0, // Local symbol, not visible outside obj file containing def + STB_GLOBAL = 1, // Global symbol, visible to all object files being combined + STB_WEAK = 2, // Weak symbol, like global but lower-precedence + STB_GNU_UNIQUE = 10, + STB_LOOS = 10, // Lowest operating system-specific binding type + STB_HIOS = 12, // Highest operating system-specific binding type + STB_LOPROC = 13, // Lowest processor-specific binding type + STB_HIPROC = 15 // Highest processor-specific binding type +}; + +// Symbol types. +enum { + STT_NOTYPE = 0, // Symbol's type is not specified + STT_OBJECT = 1, // Symbol is a data object (variable, array, etc.) + STT_FUNC = 2, // Symbol is executable code (function, etc.) + STT_SECTION = 3, // Symbol refers to a section + STT_FILE = 4, // Local, absolute symbol that refers to a file + STT_COMMON = 5, // An uninitialized common block + STT_TLS = 6, // Thread local data object + STT_GNU_IFUNC = 10, // GNU indirect function + STT_LOOS = 10, // Lowest operating system-specific symbol type + STT_HIOS = 12, // Highest operating system-specific symbol type + STT_LOPROC = 13, // Lowest processor-specific symbol type + STT_HIPROC = 15, // Highest processor-specific symbol type + + // AMDGPU symbol types + STT_AMDGPU_HSA_KERNEL = 10 +}; + +enum { + STV_DEFAULT = 0, // Visibility is specified by binding type + STV_INTERNAL = 1, // Defined by processor supplements + STV_HIDDEN = 2, // Not visible to other components + STV_PROTECTED = 3 // Visible in other components but not preemptable +}; + +// Symbol number. +enum { STN_UNDEF = 0 }; + +// Special relocation symbols used in the MIPS64 ELF relocation entries +enum { + RSS_UNDEF = 0, // None + RSS_GP = 1, // Value of gp + RSS_GP0 = 2, // Value of gp used to create object being relocated + RSS_LOC = 3 // Address of location being relocated +}; + +// Relocation entry, without explicit addend. +struct Elf32_Rel { + Elf32_Addr r_offset; // Location (file byte offset, or program virtual addr) + Elf32_Word r_info; // Symbol table index and type of relocation to apply + + // These accessors and mutators correspond to the ELF32_R_SYM, ELF32_R_TYPE, + // and ELF32_R_INFO macros defined in the ELF specification: + Elf32_Word getSymbol() const { return (r_info >> 8); } + unsigned char getType() const { return (unsigned char)(r_info & 0x0ff); } + void setSymbol(Elf32_Word s) { setSymbolAndType(s, getType()); } + void setType(unsigned char t) { setSymbolAndType(getSymbol(), t); } + void setSymbolAndType(Elf32_Word s, unsigned char t) { + r_info = (s << 8) + t; + } +}; + +// Relocation entry with explicit addend. +struct Elf32_Rela { + Elf32_Addr r_offset; // Location (file byte offset, or program virtual addr) + Elf32_Word r_info; // Symbol table index and type of relocation to apply + Elf32_Sword r_addend; // Compute value for relocatable field by adding this + + // These accessors and mutators correspond to the ELF32_R_SYM, ELF32_R_TYPE, + // and ELF32_R_INFO macros defined in the ELF specification: + Elf32_Word getSymbol() const { return (r_info >> 8); } + unsigned char getType() const { return (unsigned char)(r_info & 0x0ff); } + void setSymbol(Elf32_Word s) { setSymbolAndType(s, getType()); } + void setType(unsigned char t) { setSymbolAndType(getSymbol(), t); } + void setSymbolAndType(Elf32_Word s, unsigned char t) { + r_info = (s << 8) + t; + } +}; + +// Relocation entry without explicit addend or info (relative relocations only). +typedef Elf32_Word Elf32_Relr; // offset/bitmap for relative relocations + +// Relocation entry, without explicit addend. +struct Elf64_Rel { + Elf64_Addr r_offset; // Location (file byte offset, or program virtual addr). + Elf64_Xword r_info; // Symbol table index and type of relocation to apply. + + // These accessors and mutators correspond to the ELF64_R_SYM, ELF64_R_TYPE, + // and ELF64_R_INFO macros defined in the ELF specification: + Elf64_Word getSymbol() const { return (r_info >> 32); } + Elf64_Word getType() const { return (Elf64_Word)(r_info & 0xffffffffL); } + void setSymbol(Elf64_Word s) { setSymbolAndType(s, getType()); } + void setType(Elf64_Word t) { setSymbolAndType(getSymbol(), t); } + void setSymbolAndType(Elf64_Word s, Elf64_Word t) { + r_info = ((Elf64_Xword)s << 32) + (t & 0xffffffffL); + } +}; + +// Relocation entry with explicit addend. +struct Elf64_Rela { + Elf64_Addr r_offset; // Location (file byte offset, or program virtual addr). + Elf64_Xword r_info; // Symbol table index and type of relocation to apply. + Elf64_Sxword r_addend; // Compute value for relocatable field by adding this. + + // These accessors and mutators correspond to the ELF64_R_SYM, ELF64_R_TYPE, + // and ELF64_R_INFO macros defined in the ELF specification: + Elf64_Word getSymbol() const { return (r_info >> 32); } + Elf64_Word getType() const { return (Elf64_Word)(r_info & 0xffffffffL); } + void setSymbol(Elf64_Word s) { setSymbolAndType(s, getType()); } + void setType(Elf64_Word t) { setSymbolAndType(getSymbol(), t); } + void setSymbolAndType(Elf64_Word s, Elf64_Word t) { + r_info = ((Elf64_Xword)s << 32) + (t & 0xffffffffL); + } +}; + +// Relocation entry without explicit addend or info (relative relocations only). +typedef Elf64_Xword Elf64_Relr; // offset/bitmap for relative relocations + +// Program header for ELF32. +struct Elf32_Phdr { + Elf32_Word p_type; // Type of segment + Elf32_Off p_offset; // File offset where segment is located, in bytes + Elf32_Addr p_vaddr; // Virtual address of beginning of segment + Elf32_Addr p_paddr; // Physical address of beginning of segment (OS-specific) + Elf32_Word p_filesz; // Num. of bytes in file image of segment (may be zero) + Elf32_Word p_memsz; // Num. of bytes in mem image of segment (may be zero) + Elf32_Word p_flags; // Segment flags + Elf32_Word p_align; // Segment alignment constraint +}; + +// Program header for ELF64. +struct Elf64_Phdr { + Elf64_Word p_type; // Type of segment + Elf64_Word p_flags; // Segment flags + Elf64_Off p_offset; // File offset where segment is located, in bytes + Elf64_Addr p_vaddr; // Virtual address of beginning of segment + Elf64_Addr p_paddr; // Physical addr of beginning of segment (OS-specific) + Elf64_Xword p_filesz; // Num. of bytes in file image of segment (may be zero) + Elf64_Xword p_memsz; // Num. of bytes in mem image of segment (may be zero) + Elf64_Xword p_align; // Segment alignment constraint +}; + +// Segment types. +enum { + PT_NULL = 0, // Unused segment. + PT_LOAD = 1, // Loadable segment. + PT_DYNAMIC = 2, // Dynamic linking information. + PT_INTERP = 3, // Interpreter pathname. + PT_NOTE = 4, // Auxiliary information. + PT_SHLIB = 5, // Reserved. + PT_PHDR = 6, // The program header table itself. + PT_TLS = 7, // The thread-local storage template. + PT_LOOS = 0x60000000, // Lowest operating system-specific pt entry type. + PT_HIOS = 0x6fffffff, // Highest operating system-specific pt entry type. + PT_LOPROC = 0x70000000, // Lowest processor-specific program hdr entry type. + PT_HIPROC = 0x7fffffff, // Highest processor-specific program hdr entry type. + + // x86-64 program header types. + // These all contain stack unwind tables. + PT_GNU_EH_FRAME = 0x6474e550, + PT_SUNW_EH_FRAME = 0x6474e550, + PT_SUNW_UNWIND = 0x6464e550, + + PT_GNU_STACK = 0x6474e551, // Indicates stack executability. + PT_GNU_RELRO = 0x6474e552, // Read-only after relocation. + PT_GNU_PROPERTY = 0x6474e553, // .note.gnu.property notes sections. + + PT_OPENBSD_MUTABLE = 0x65a3dbe5, // Like bss, but not immutable. + PT_OPENBSD_RANDOMIZE = 0x65a3dbe6, // Fill with random data. + PT_OPENBSD_WXNEEDED = 0x65a3dbe7, // Program does W^X violations. + PT_OPENBSD_NOBTCFI = 0x65a3dbe8, // Do not enforce branch target CFI. + PT_OPENBSD_BOOTDATA = 0x65a41be6, // Section for boot arguments. + + // ARM program header types. + PT_ARM_ARCHEXT = 0x70000000, // Platform architecture compatibility info + // These all contain stack unwind tables. + PT_ARM_EXIDX = 0x70000001, + PT_ARM_UNWIND = 0x70000001, + // MTE memory tag segment type + PT_AARCH64_MEMTAG_MTE = 0x70000002, + + // MIPS program header types. + PT_MIPS_REGINFO = 0x70000000, // Register usage information. + PT_MIPS_RTPROC = 0x70000001, // Runtime procedure table. + PT_MIPS_OPTIONS = 0x70000002, // Options segment. + PT_MIPS_ABIFLAGS = 0x70000003, // Abiflags segment. + + // RISCV program header types. + PT_RISCV_ATTRIBUTES = 0x70000003, +}; + +// Segment flag bits. +enum : unsigned { + PF_X = 1, // Execute + PF_W = 2, // Write + PF_R = 4, // Read + PF_MASKOS = 0x0ff00000, // Bits for operating system-specific semantics. + PF_MASKPROC = 0xf0000000 // Bits for processor-specific semantics. +}; + +// Dynamic table entry for ELF32. +struct Elf32_Dyn { + Elf32_Sword d_tag; // Type of dynamic table entry. + union { + Elf32_Word d_val; // Integer value of entry. + Elf32_Addr d_ptr; // Pointer value of entry. + } d_un; +}; + +// Dynamic table entry for ELF64. +struct Elf64_Dyn { + Elf64_Sxword d_tag; // Type of dynamic table entry. + union { + Elf64_Xword d_val; // Integer value of entry. + Elf64_Addr d_ptr; // Pointer value of entry. + } d_un; +}; + +// Dynamic table entry tags. +enum { +#define DYNAMIC_TAG(name, value) DT_##name = value, +#include "DynamicTags.def" +#undef DYNAMIC_TAG +}; + +// DT_FLAGS values. +enum { + DF_ORIGIN = 0x01, // The object may reference $ORIGIN. + DF_SYMBOLIC = 0x02, // Search the shared lib before searching the exe. + DF_TEXTREL = 0x04, // Relocations may modify a non-writable segment. + DF_BIND_NOW = 0x08, // Process all relocations on load. + DF_STATIC_TLS = 0x10 // Reject attempts to load dynamically. +}; + +// State flags selectable in the `d_un.d_val' element of the DT_FLAGS_1 entry. +enum { + DF_1_NOW = 0x00000001, // Set RTLD_NOW for this object. + DF_1_GLOBAL = 0x00000002, // Set RTLD_GLOBAL for this object. + DF_1_GROUP = 0x00000004, // Set RTLD_GROUP for this object. + DF_1_NODELETE = 0x00000008, // Set RTLD_NODELETE for this object. + DF_1_LOADFLTR = 0x00000010, // Trigger filtee loading at runtime. + DF_1_INITFIRST = 0x00000020, // Set RTLD_INITFIRST for this object. + DF_1_NOOPEN = 0x00000040, // Set RTLD_NOOPEN for this object. + DF_1_ORIGIN = 0x00000080, // $ORIGIN must be handled. + DF_1_DIRECT = 0x00000100, // Direct binding enabled. + DF_1_TRANS = 0x00000200, + DF_1_INTERPOSE = 0x00000400, // Object is used to interpose. + DF_1_NODEFLIB = 0x00000800, // Ignore default lib search path. + DF_1_NODUMP = 0x00001000, // Object can't be dldump'ed. + DF_1_CONFALT = 0x00002000, // Configuration alternative created. + DF_1_ENDFILTEE = 0x00004000, // Filtee terminates filters search. + DF_1_DISPRELDNE = 0x00008000, // Disp reloc applied at build time. + DF_1_DISPRELPND = 0x00010000, // Disp reloc applied at run-time. + DF_1_NODIRECT = 0x00020000, // Object has no-direct binding. + DF_1_IGNMULDEF = 0x00040000, + DF_1_NOKSYMS = 0x00080000, + DF_1_NOHDR = 0x00100000, + DF_1_EDITED = 0x00200000, // Object is modified after built. + DF_1_NORELOC = 0x00400000, + DF_1_SYMINTPOSE = 0x00800000, // Object has individual interposers. + DF_1_GLOBAUDIT = 0x01000000, // Global auditing required. + DF_1_SINGLETON = 0x02000000, // Singleton symbols are used. + DF_1_PIE = 0x08000000, // Object is a position-independent executable. +}; + +// DT_MIPS_FLAGS values. +enum { + RHF_NONE = 0x00000000, // No flags. + RHF_QUICKSTART = 0x00000001, // Uses shortcut pointers. + RHF_NOTPOT = 0x00000002, // Hash size is not a power of two. + RHS_NO_LIBRARY_REPLACEMENT = 0x00000004, // Ignore LD_LIBRARY_PATH. + RHF_NO_MOVE = 0x00000008, // DSO address may not be relocated. + RHF_SGI_ONLY = 0x00000010, // SGI specific features. + RHF_GUARANTEE_INIT = 0x00000020, // Guarantee that .init will finish + // executing before any non-init + // code in DSO is called. + RHF_DELTA_C_PLUS_PLUS = 0x00000040, // Contains Delta C++ code. + RHF_GUARANTEE_START_INIT = 0x00000080, // Guarantee that .init will start + // executing before any non-init + // code in DSO is called. + RHF_PIXIE = 0x00000100, // Generated by pixie. + RHF_DEFAULT_DELAY_LOAD = 0x00000200, // Delay-load DSO by default. + RHF_REQUICKSTART = 0x00000400, // Object may be requickstarted + RHF_REQUICKSTARTED = 0x00000800, // Object has been requickstarted + RHF_CORD = 0x00001000, // Generated by cord. + RHF_NO_UNRES_UNDEF = 0x00002000, // Object contains no unresolved + // undef symbols. + RHF_RLD_ORDER_SAFE = 0x00004000 // Symbol table is in a safe order. +}; + +// ElfXX_VerDef structure version (GNU versioning) +enum { VER_DEF_NONE = 0, VER_DEF_CURRENT = 1 }; + +// VerDef Flags (ElfXX_VerDef::vd_flags) +enum { VER_FLG_BASE = 0x1, VER_FLG_WEAK = 0x2, VER_FLG_INFO = 0x4 }; + +// Special constants for the version table. (SHT_GNU_versym/.gnu.version) +enum { + VER_NDX_LOCAL = 0, // Unversioned local symbol + VER_NDX_GLOBAL = 1, // Unversioned global symbol + VERSYM_VERSION = 0x7fff, // Version Index mask + VERSYM_HIDDEN = 0x8000 // Hidden bit (non-default version) +}; + +// ElfXX_VerNeed structure version (GNU versioning) +enum { VER_NEED_NONE = 0, VER_NEED_CURRENT = 1 }; + +// SHT_NOTE section types. + +// Generic note types. +enum : unsigned { + NT_VERSION = 1, + NT_ARCH = 2, + NT_GNU_BUILD_ATTRIBUTE_OPEN = 0x100, + NT_GNU_BUILD_ATTRIBUTE_FUNC = 0x101, +}; + +// Core note types. +enum : unsigned { + NT_PRSTATUS = 1, + NT_FPREGSET = 2, + NT_PRPSINFO = 3, + NT_TASKSTRUCT = 4, + NT_AUXV = 6, + NT_PSTATUS = 10, + NT_FPREGS = 12, + NT_PSINFO = 13, + NT_LWPSTATUS = 16, + NT_LWPSINFO = 17, + NT_WIN32PSTATUS = 18, + + NT_PPC_VMX = 0x100, + NT_PPC_VSX = 0x102, + NT_PPC_TAR = 0x103, + NT_PPC_PPR = 0x104, + NT_PPC_DSCR = 0x105, + NT_PPC_EBB = 0x106, + NT_PPC_PMU = 0x107, + NT_PPC_TM_CGPR = 0x108, + NT_PPC_TM_CFPR = 0x109, + NT_PPC_TM_CVMX = 0x10a, + NT_PPC_TM_CVSX = 0x10b, + NT_PPC_TM_SPR = 0x10c, + NT_PPC_TM_CTAR = 0x10d, + NT_PPC_TM_CPPR = 0x10e, + NT_PPC_TM_CDSCR = 0x10f, + + NT_386_TLS = 0x200, + NT_386_IOPERM = 0x201, + NT_X86_XSTATE = 0x202, + + NT_S390_HIGH_GPRS = 0x300, + NT_S390_TIMER = 0x301, + NT_S390_TODCMP = 0x302, + NT_S390_TODPREG = 0x303, + NT_S390_CTRS = 0x304, + NT_S390_PREFIX = 0x305, + NT_S390_LAST_BREAK = 0x306, + NT_S390_SYSTEM_CALL = 0x307, + NT_S390_TDB = 0x308, + NT_S390_VXRS_LOW = 0x309, + NT_S390_VXRS_HIGH = 0x30a, + NT_S390_GS_CB = 0x30b, + NT_S390_GS_BC = 0x30c, + + NT_ARM_VFP = 0x400, + NT_ARM_TLS = 0x401, + NT_ARM_HW_BREAK = 0x402, + NT_ARM_HW_WATCH = 0x403, + NT_ARM_SVE = 0x405, + NT_ARM_PAC_MASK = 0x406, + NT_ARM_SSVE = 0x40b, + NT_ARM_ZA = 0x40c, + NT_ARM_ZT = 0x40d, + + NT_FILE = 0x46494c45, + NT_PRXFPREG = 0x46e62b7f, + NT_SIGINFO = 0x53494749, +}; + +// LLVM-specific notes. +enum { + NT_LLVM_HWASAN_GLOBALS = 3, +}; + +// GNU note types. +enum { + NT_GNU_ABI_TAG = 1, + NT_GNU_HWCAP = 2, + NT_GNU_BUILD_ID = 3, + NT_GNU_GOLD_VERSION = 4, + NT_GNU_PROPERTY_TYPE_0 = 5, + FDO_PACKAGING_METADATA = 0xcafe1a7e, +}; + +// Android note types. +enum { + NT_ANDROID_TYPE_IDENT = 1, + NT_ANDROID_TYPE_KUSER = 3, + NT_ANDROID_TYPE_MEMTAG = 4, +}; + +// Memory tagging values used in NT_ANDROID_TYPE_MEMTAG notes. +enum { + // Enumeration to determine the tagging mode. In Android-land, 'SYNC' means + // running all threads in MTE Synchronous mode, and 'ASYNC' means to use the + // kernels auto-upgrade feature to allow for either MTE Asynchronous, + // Asymmetric, or Synchronous mode. This allows silicon vendors to specify, on + // a per-cpu basis what 'ASYNC' should mean. Generally, the expectation is + // "pick the most precise mode that's very fast". + NT_MEMTAG_LEVEL_NONE = 0, + NT_MEMTAG_LEVEL_ASYNC = 1, + NT_MEMTAG_LEVEL_SYNC = 2, + NT_MEMTAG_LEVEL_MASK = 3, + // Bits indicating whether the loader should prepare for MTE to be enabled on + // the heap and/or stack. + NT_MEMTAG_HEAP = 4, + NT_MEMTAG_STACK = 8, +}; + +// Property types used in GNU_PROPERTY_TYPE_0 notes. +enum : unsigned { + GNU_PROPERTY_STACK_SIZE = 1, + GNU_PROPERTY_NO_COPY_ON_PROTECTED = 2, + GNU_PROPERTY_AARCH64_FEATURE_1_AND = 0xc0000000, + GNU_PROPERTY_X86_FEATURE_1_AND = 0xc0000002, + + GNU_PROPERTY_X86_UINT32_OR_LO = 0xc0008000, + GNU_PROPERTY_X86_FEATURE_2_NEEDED = GNU_PROPERTY_X86_UINT32_OR_LO + 1, + GNU_PROPERTY_X86_ISA_1_NEEDED = GNU_PROPERTY_X86_UINT32_OR_LO + 2, + + GNU_PROPERTY_X86_UINT32_OR_AND_LO = 0xc0010000, + GNU_PROPERTY_X86_FEATURE_2_USED = GNU_PROPERTY_X86_UINT32_OR_AND_LO + 1, + GNU_PROPERTY_X86_ISA_1_USED = GNU_PROPERTY_X86_UINT32_OR_AND_LO + 2, +}; + +// aarch64 processor feature bits. +enum : unsigned { + GNU_PROPERTY_AARCH64_FEATURE_1_BTI = 1 << 0, + GNU_PROPERTY_AARCH64_FEATURE_1_PAC = 1 << 1, +}; + +// x86 processor feature bits. +enum : unsigned { + GNU_PROPERTY_X86_FEATURE_1_IBT = 1 << 0, + GNU_PROPERTY_X86_FEATURE_1_SHSTK = 1 << 1, + + GNU_PROPERTY_X86_FEATURE_2_X86 = 1 << 0, + GNU_PROPERTY_X86_FEATURE_2_X87 = 1 << 1, + GNU_PROPERTY_X86_FEATURE_2_MMX = 1 << 2, + GNU_PROPERTY_X86_FEATURE_2_XMM = 1 << 3, + GNU_PROPERTY_X86_FEATURE_2_YMM = 1 << 4, + GNU_PROPERTY_X86_FEATURE_2_ZMM = 1 << 5, + GNU_PROPERTY_X86_FEATURE_2_FXSR = 1 << 6, + GNU_PROPERTY_X86_FEATURE_2_XSAVE = 1 << 7, + GNU_PROPERTY_X86_FEATURE_2_XSAVEOPT = 1 << 8, + GNU_PROPERTY_X86_FEATURE_2_XSAVEC = 1 << 9, + + GNU_PROPERTY_X86_ISA_1_BASELINE = 1 << 0, + GNU_PROPERTY_X86_ISA_1_V2 = 1 << 1, + GNU_PROPERTY_X86_ISA_1_V3 = 1 << 2, + GNU_PROPERTY_X86_ISA_1_V4 = 1 << 3, +}; + +// FreeBSD note types. +enum { + NT_FREEBSD_ABI_TAG = 1, + NT_FREEBSD_NOINIT_TAG = 2, + NT_FREEBSD_ARCH_TAG = 3, + NT_FREEBSD_FEATURE_CTL = 4, +}; + +// NT_FREEBSD_FEATURE_CTL values (see FreeBSD's sys/sys/elf_common.h). +enum { + NT_FREEBSD_FCTL_ASLR_DISABLE = 0x00000001, + NT_FREEBSD_FCTL_PROTMAX_DISABLE = 0x00000002, + NT_FREEBSD_FCTL_STKGAP_DISABLE = 0x00000004, + NT_FREEBSD_FCTL_WXNEEDED = 0x00000008, + NT_FREEBSD_FCTL_LA48 = 0x00000010, + NT_FREEBSD_FCTL_ASG_DISABLE = 0x00000020, +}; + +// FreeBSD core note types. +enum { + NT_FREEBSD_THRMISC = 7, + NT_FREEBSD_PROCSTAT_PROC = 8, + NT_FREEBSD_PROCSTAT_FILES = 9, + NT_FREEBSD_PROCSTAT_VMMAP = 10, + NT_FREEBSD_PROCSTAT_GROUPS = 11, + NT_FREEBSD_PROCSTAT_UMASK = 12, + NT_FREEBSD_PROCSTAT_RLIMIT = 13, + NT_FREEBSD_PROCSTAT_OSREL = 14, + NT_FREEBSD_PROCSTAT_PSSTRINGS = 15, + NT_FREEBSD_PROCSTAT_AUXV = 16, +}; + +// NetBSD core note types. +enum { + NT_NETBSDCORE_PROCINFO = 1, + NT_NETBSDCORE_AUXV = 2, + NT_NETBSDCORE_LWPSTATUS = 24, +}; + +// OpenBSD core note types. +enum { + NT_OPENBSD_PROCINFO = 10, + NT_OPENBSD_AUXV = 11, + NT_OPENBSD_REGS = 20, + NT_OPENBSD_FPREGS = 21, + NT_OPENBSD_XFPREGS = 22, + NT_OPENBSD_WCOOKIE = 23, +}; + +// AMDGPU-specific section indices. +enum { + SHN_AMDGPU_LDS = 0xff00, // Variable in LDS; symbol encoded like SHN_COMMON +}; + +// AMD vendor specific notes. (Code Object V2) +enum { + NT_AMD_HSA_CODE_OBJECT_VERSION = 1, + NT_AMD_HSA_HSAIL = 2, + NT_AMD_HSA_ISA_VERSION = 3, + // Note types with values between 4 and 9 (inclusive) are reserved. + NT_AMD_HSA_METADATA = 10, + NT_AMD_HSA_ISA_NAME = 11, + NT_AMD_PAL_METADATA = 12 +}; + +// AMDGPU vendor specific notes. (Code Object V3) +enum { + // Note types with values between 0 and 31 (inclusive) are reserved. + NT_AMDGPU_METADATA = 32 +}; + +// LLVMOMPOFFLOAD specific notes. +enum : unsigned { + NT_LLVM_OPENMP_OFFLOAD_VERSION = 1, + NT_LLVM_OPENMP_OFFLOAD_PRODUCER = 2, + NT_LLVM_OPENMP_OFFLOAD_PRODUCER_VERSION = 3 +}; + +enum { + GNU_ABI_TAG_LINUX = 0, + GNU_ABI_TAG_HURD = 1, + GNU_ABI_TAG_SOLARIS = 2, + GNU_ABI_TAG_FREEBSD = 3, + GNU_ABI_TAG_NETBSD = 4, + GNU_ABI_TAG_SYLLABLE = 5, + GNU_ABI_TAG_NACL = 6, +}; + +constexpr const char *ELF_NOTE_GNU = "GNU"; + +// Android packed relocation group flags. +enum { + RELOCATION_GROUPED_BY_INFO_FLAG = 1, + RELOCATION_GROUPED_BY_OFFSET_DELTA_FLAG = 2, + RELOCATION_GROUPED_BY_ADDEND_FLAG = 4, + RELOCATION_GROUP_HAS_ADDEND_FLAG = 8, +}; + +// Compressed section header for ELF32. +struct Elf32_Chdr { + Elf32_Word ch_type; + Elf32_Word ch_size; + Elf32_Word ch_addralign; +}; + +// Compressed section header for ELF64. +struct Elf64_Chdr { + Elf64_Word ch_type; + Elf64_Word ch_reserved; + Elf64_Xword ch_size; + Elf64_Xword ch_addralign; +}; + +// Note header for ELF32. +struct Elf32_Nhdr { + Elf32_Word n_namesz; + Elf32_Word n_descsz; + Elf32_Word n_type; +}; + +// Note header for ELF64. +struct Elf64_Nhdr { + Elf64_Word n_namesz; + Elf64_Word n_descsz; + Elf64_Word n_type; +}; + +// Legal values for ch_type field of compressed section header. +enum { + ELFCOMPRESS_ZLIB = 1, // ZLIB/DEFLATE algorithm. + ELFCOMPRESS_ZSTD = 2, // Zstandard algorithm + ELFCOMPRESS_LOOS = 0x60000000, // Start of OS-specific. + ELFCOMPRESS_HIOS = 0x6fffffff, // End of OS-specific. + ELFCOMPRESS_LOPROC = 0x70000000, // Start of processor-specific. + ELFCOMPRESS_HIPROC = 0x7fffffff // End of processor-specific. +}; + +/// Convert an architecture name into ELF's e_machine value. +uint16_t convertArchNameToEMachine(StringRef Arch); + +/// Convert an ELF's e_machine value into an architecture name. +StringRef convertEMachineToArchName(uint16_t EMachine); + +} // end namespace ELF +} // end namespace llvm + +#endif // LLVM_BINARYFORMAT_ELF_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/AArch64.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/AArch64.def new file mode 100644 index 00000000000..96a4efe8256 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/AArch64.def @@ -0,0 +1,225 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +// Based on ABI release 1.1-beta, dated 6 November 2013. NB: The cover page of +// this document, IHI0056C_beta_aaelf64.pdf, on infocenter.arm.com, still +// labels this as release 1.0. +ELF_RELOC(R_AARCH64_NONE, 0) +ELF_RELOC(R_AARCH64_ABS64, 0x101) +ELF_RELOC(R_AARCH64_ABS32, 0x102) +ELF_RELOC(R_AARCH64_ABS16, 0x103) +ELF_RELOC(R_AARCH64_PREL64, 0x104) +ELF_RELOC(R_AARCH64_PREL32, 0x105) +ELF_RELOC(R_AARCH64_PREL16, 0x106) +ELF_RELOC(R_AARCH64_MOVW_UABS_G0, 0x107) +ELF_RELOC(R_AARCH64_MOVW_UABS_G0_NC, 0x108) +ELF_RELOC(R_AARCH64_MOVW_UABS_G1, 0x109) +ELF_RELOC(R_AARCH64_MOVW_UABS_G1_NC, 0x10a) +ELF_RELOC(R_AARCH64_MOVW_UABS_G2, 0x10b) +ELF_RELOC(R_AARCH64_MOVW_UABS_G2_NC, 0x10c) +ELF_RELOC(R_AARCH64_MOVW_UABS_G3, 0x10d) +ELF_RELOC(R_AARCH64_MOVW_SABS_G0, 0x10e) +ELF_RELOC(R_AARCH64_MOVW_SABS_G1, 0x10f) +ELF_RELOC(R_AARCH64_MOVW_SABS_G2, 0x110) +ELF_RELOC(R_AARCH64_LD_PREL_LO19, 0x111) +ELF_RELOC(R_AARCH64_ADR_PREL_LO21, 0x112) +ELF_RELOC(R_AARCH64_ADR_PREL_PG_HI21, 0x113) +ELF_RELOC(R_AARCH64_ADR_PREL_PG_HI21_NC, 0x114) +ELF_RELOC(R_AARCH64_ADD_ABS_LO12_NC, 0x115) +ELF_RELOC(R_AARCH64_LDST8_ABS_LO12_NC, 0x116) +ELF_RELOC(R_AARCH64_TSTBR14, 0x117) +ELF_RELOC(R_AARCH64_CONDBR19, 0x118) +ELF_RELOC(R_AARCH64_JUMP26, 0x11a) +ELF_RELOC(R_AARCH64_CALL26, 0x11b) +ELF_RELOC(R_AARCH64_LDST16_ABS_LO12_NC, 0x11c) +ELF_RELOC(R_AARCH64_LDST32_ABS_LO12_NC, 0x11d) +ELF_RELOC(R_AARCH64_LDST64_ABS_LO12_NC, 0x11e) +ELF_RELOC(R_AARCH64_MOVW_PREL_G0, 0x11f) +ELF_RELOC(R_AARCH64_MOVW_PREL_G0_NC, 0x120) +ELF_RELOC(R_AARCH64_MOVW_PREL_G1, 0x121) +ELF_RELOC(R_AARCH64_MOVW_PREL_G1_NC, 0x122) +ELF_RELOC(R_AARCH64_MOVW_PREL_G2, 0x123) +ELF_RELOC(R_AARCH64_MOVW_PREL_G2_NC, 0x124) +ELF_RELOC(R_AARCH64_MOVW_PREL_G3, 0x125) +ELF_RELOC(R_AARCH64_LDST128_ABS_LO12_NC, 0x12b) +ELF_RELOC(R_AARCH64_MOVW_GOTOFF_G0, 0x12c) +ELF_RELOC(R_AARCH64_MOVW_GOTOFF_G0_NC, 0x12d) +ELF_RELOC(R_AARCH64_MOVW_GOTOFF_G1, 0x12e) +ELF_RELOC(R_AARCH64_MOVW_GOTOFF_G1_NC, 0x12f) +ELF_RELOC(R_AARCH64_MOVW_GOTOFF_G2, 0x130) +ELF_RELOC(R_AARCH64_MOVW_GOTOFF_G2_NC, 0x131) +ELF_RELOC(R_AARCH64_MOVW_GOTOFF_G3, 0x132) +ELF_RELOC(R_AARCH64_GOTREL64, 0x133) +ELF_RELOC(R_AARCH64_GOTREL32, 0x134) +ELF_RELOC(R_AARCH64_GOT_LD_PREL19, 0x135) +ELF_RELOC(R_AARCH64_LD64_GOTOFF_LO15, 0x136) +ELF_RELOC(R_AARCH64_ADR_GOT_PAGE, 0x137) +ELF_RELOC(R_AARCH64_LD64_GOT_LO12_NC, 0x138) +ELF_RELOC(R_AARCH64_LD64_GOTPAGE_LO15, 0x139) +ELF_RELOC(R_AARCH64_PLT32, 0x13a) +ELF_RELOC(R_AARCH64_TLSGD_ADR_PREL21, 0x200) +ELF_RELOC(R_AARCH64_TLSGD_ADR_PAGE21, 0x201) +ELF_RELOC(R_AARCH64_TLSGD_ADD_LO12_NC, 0x202) +ELF_RELOC(R_AARCH64_TLSGD_MOVW_G1, 0x203) +ELF_RELOC(R_AARCH64_TLSGD_MOVW_G0_NC, 0x204) +ELF_RELOC(R_AARCH64_TLSLD_ADR_PREL21, 0x205) +ELF_RELOC(R_AARCH64_TLSLD_ADR_PAGE21, 0x206) +ELF_RELOC(R_AARCH64_TLSLD_ADD_LO12_NC, 0x207) +ELF_RELOC(R_AARCH64_TLSLD_MOVW_G1, 0x208) +ELF_RELOC(R_AARCH64_TLSLD_MOVW_G0_NC, 0x209) +ELF_RELOC(R_AARCH64_TLSLD_LD_PREL19, 0x20a) +ELF_RELOC(R_AARCH64_TLSLD_MOVW_DTPREL_G2, 0x20b) +ELF_RELOC(R_AARCH64_TLSLD_MOVW_DTPREL_G1, 0x20c) +ELF_RELOC(R_AARCH64_TLSLD_MOVW_DTPREL_G1_NC, 0x20d) +ELF_RELOC(R_AARCH64_TLSLD_MOVW_DTPREL_G0, 0x20e) +ELF_RELOC(R_AARCH64_TLSLD_MOVW_DTPREL_G0_NC, 0x20f) +ELF_RELOC(R_AARCH64_TLSLD_ADD_DTPREL_HI12, 0x210) +ELF_RELOC(R_AARCH64_TLSLD_ADD_DTPREL_LO12, 0x211) +ELF_RELOC(R_AARCH64_TLSLD_ADD_DTPREL_LO12_NC, 0x212) +ELF_RELOC(R_AARCH64_TLSLD_LDST8_DTPREL_LO12, 0x213) +ELF_RELOC(R_AARCH64_TLSLD_LDST8_DTPREL_LO12_NC, 0x214) +ELF_RELOC(R_AARCH64_TLSLD_LDST16_DTPREL_LO12, 0x215) +ELF_RELOC(R_AARCH64_TLSLD_LDST16_DTPREL_LO12_NC, 0x216) +ELF_RELOC(R_AARCH64_TLSLD_LDST32_DTPREL_LO12, 0x217) +ELF_RELOC(R_AARCH64_TLSLD_LDST32_DTPREL_LO12_NC, 0x218) +ELF_RELOC(R_AARCH64_TLSLD_LDST64_DTPREL_LO12, 0x219) +ELF_RELOC(R_AARCH64_TLSLD_LDST64_DTPREL_LO12_NC, 0x21a) +ELF_RELOC(R_AARCH64_TLSIE_MOVW_GOTTPREL_G1, 0x21b) +ELF_RELOC(R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC, 0x21c) +ELF_RELOC(R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21, 0x21d) +ELF_RELOC(R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC, 0x21e) +ELF_RELOC(R_AARCH64_TLSIE_LD_GOTTPREL_PREL19, 0x21f) +ELF_RELOC(R_AARCH64_TLSLE_MOVW_TPREL_G2, 0x220) +ELF_RELOC(R_AARCH64_TLSLE_MOVW_TPREL_G1, 0x221) +ELF_RELOC(R_AARCH64_TLSLE_MOVW_TPREL_G1_NC, 0x222) +ELF_RELOC(R_AARCH64_TLSLE_MOVW_TPREL_G0, 0x223) +ELF_RELOC(R_AARCH64_TLSLE_MOVW_TPREL_G0_NC, 0x224) +ELF_RELOC(R_AARCH64_TLSLE_ADD_TPREL_HI12, 0x225) +ELF_RELOC(R_AARCH64_TLSLE_ADD_TPREL_LO12, 0x226) +ELF_RELOC(R_AARCH64_TLSLE_ADD_TPREL_LO12_NC, 0x227) +ELF_RELOC(R_AARCH64_TLSLE_LDST8_TPREL_LO12, 0x228) +ELF_RELOC(R_AARCH64_TLSLE_LDST8_TPREL_LO12_NC, 0x229) +ELF_RELOC(R_AARCH64_TLSLE_LDST16_TPREL_LO12, 0x22a) +ELF_RELOC(R_AARCH64_TLSLE_LDST16_TPREL_LO12_NC, 0x22b) +ELF_RELOC(R_AARCH64_TLSLE_LDST32_TPREL_LO12, 0x22c) +ELF_RELOC(R_AARCH64_TLSLE_LDST32_TPREL_LO12_NC, 0x22d) +ELF_RELOC(R_AARCH64_TLSLE_LDST64_TPREL_LO12, 0x22e) +ELF_RELOC(R_AARCH64_TLSLE_LDST64_TPREL_LO12_NC, 0x22f) +ELF_RELOC(R_AARCH64_TLSDESC_LD_PREL19, 0x230) +ELF_RELOC(R_AARCH64_TLSDESC_ADR_PREL21, 0x231) +ELF_RELOC(R_AARCH64_TLSDESC_ADR_PAGE21, 0x232) +ELF_RELOC(R_AARCH64_TLSDESC_LD64_LO12, 0x233) +ELF_RELOC(R_AARCH64_TLSDESC_ADD_LO12, 0x234) +ELF_RELOC(R_AARCH64_TLSDESC_OFF_G1, 0x235) +ELF_RELOC(R_AARCH64_TLSDESC_OFF_G0_NC, 0x236) +ELF_RELOC(R_AARCH64_TLSDESC_LDR, 0x237) +ELF_RELOC(R_AARCH64_TLSDESC_ADD, 0x238) +ELF_RELOC(R_AARCH64_TLSDESC_CALL, 0x239) +ELF_RELOC(R_AARCH64_TLSLE_LDST128_TPREL_LO12, 0x23a) +ELF_RELOC(R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC, 0x23b) +ELF_RELOC(R_AARCH64_TLSLD_LDST128_DTPREL_LO12, 0x23c) +ELF_RELOC(R_AARCH64_TLSLD_LDST128_DTPREL_LO12_NC, 0x23d) +// Dynamic relocations start +ELF_RELOC(R_AARCH64_COPY, 0x400) +ELF_RELOC(R_AARCH64_GLOB_DAT, 0x401) +ELF_RELOC(R_AARCH64_JUMP_SLOT, 0x402) +ELF_RELOC(R_AARCH64_RELATIVE, 0x403) +// 0x404 and 0x405 are now R_AARCH64_TLS_IMPDEF1 and R_AARCH64_TLS_IMPDEF2 +// We follow GNU and define TLS_IMPDEF1 as TLS_DTPMOD64 and TLS_IMPDEF2 as +// TLS_DTPREL64 +ELF_RELOC(R_AARCH64_TLS_DTPMOD64, 0x404) +ELF_RELOC(R_AARCH64_TLS_DTPREL64, 0x405) +ELF_RELOC(R_AARCH64_TLS_TPREL64, 0x406) +ELF_RELOC(R_AARCH64_TLSDESC, 0x407) +ELF_RELOC(R_AARCH64_IRELATIVE, 0x408) + +// ELF_RELOC(R_AARCH64_P32_NONE, 0) +ELF_RELOC(R_AARCH64_P32_ABS32, 0x001) +ELF_RELOC(R_AARCH64_P32_ABS16, 0x002) +ELF_RELOC(R_AARCH64_P32_PREL32, 0x003) +ELF_RELOC(R_AARCH64_P32_PREL16, 0x004) +ELF_RELOC(R_AARCH64_P32_MOVW_UABS_G0, 0x005) +ELF_RELOC(R_AARCH64_P32_MOVW_UABS_G0_NC, 0x006) +ELF_RELOC(R_AARCH64_P32_MOVW_UABS_G1, 0x007) +ELF_RELOC(R_AARCH64_P32_MOVW_SABS_G0, 0x008) +ELF_RELOC(R_AARCH64_P32_LD_PREL_LO19, 0x009) +ELF_RELOC(R_AARCH64_P32_ADR_PREL_LO21, 0x00a) +ELF_RELOC(R_AARCH64_P32_ADR_PREL_PG_HI21, 0x00b) +ELF_RELOC(R_AARCH64_P32_ADD_ABS_LO12_NC, 0x00c) +ELF_RELOC(R_AARCH64_P32_LDST8_ABS_LO12_NC, 0x00d) +ELF_RELOC(R_AARCH64_P32_LDST16_ABS_LO12_NC, 0x00e) +ELF_RELOC(R_AARCH64_P32_LDST32_ABS_LO12_NC, 0x00f) +ELF_RELOC(R_AARCH64_P32_LDST64_ABS_LO12_NC, 0x010) +ELF_RELOC(R_AARCH64_P32_LDST128_ABS_LO12_NC, 0x011) +ELF_RELOC(R_AARCH64_P32_TSTBR14, 0x012) +ELF_RELOC(R_AARCH64_P32_CONDBR19, 0x013) +ELF_RELOC(R_AARCH64_P32_JUMP26, 0x014) +ELF_RELOC(R_AARCH64_P32_CALL26, 0x015) +ELF_RELOC(R_AARCH64_P32_MOVW_PREL_G0, 0x016) +ELF_RELOC(R_AARCH64_P32_MOVW_PREL_G0_NC, 0x017) +ELF_RELOC(R_AARCH64_P32_MOVW_PREL_G1, 0x018) +ELF_RELOC(R_AARCH64_P32_GOT_LD_PREL19, 0x019) +ELF_RELOC(R_AARCH64_P32_ADR_GOT_PAGE, 0x01a) +ELF_RELOC(R_AARCH64_P32_LD32_GOT_LO12_NC, 0x01b) +ELF_RELOC(R_AARCH64_P32_LD32_GOTPAGE_LO14, 0x01c) +ELF_RELOC(R_AARCH64_P32_PLT32, 0x01d) +ELF_RELOC(R_AARCH64_P32_TLSGD_ADR_PREL21, 0x050) +ELF_RELOC(R_AARCH64_P32_TLSGD_ADR_PAGE21, 0x051) +ELF_RELOC(R_AARCH64_P32_TLSGD_ADD_LO12_NC, 0x052) +ELF_RELOC(R_AARCH64_P32_TLSLD_ADR_PREL21, 0x053) +ELF_RELOC(R_AARCH64_P32_TLSLD_ADR_PAGE21, 0x054) +ELF_RELOC(R_AARCH64_P32_TLSLD_ADD_LO12_NC, 0x055) +ELF_RELOC(R_AARCH64_P32_TLSLD_LD_PREL19, 0x056) +ELF_RELOC(R_AARCH64_P32_TLSLD_MOVW_DTPREL_G1, 0x057) +ELF_RELOC(R_AARCH64_P32_TLSLD_MOVW_DTPREL_G0, 0x058) +ELF_RELOC(R_AARCH64_P32_TLSLD_MOVW_DTPREL_G0_NC, 0x059) +ELF_RELOC(R_AARCH64_P32_TLSLD_ADD_DTPREL_HI12, 0x05a) +ELF_RELOC(R_AARCH64_P32_TLSLD_ADD_DTPREL_LO12, 0x05b) +ELF_RELOC(R_AARCH64_P32_TLSLD_ADD_DTPREL_LO12_NC, 0x05c) +ELF_RELOC(R_AARCH64_P32_TLSLD_LDST8_DTPREL_LO12, 0x05d) +ELF_RELOC(R_AARCH64_P32_TLSLD_LDST8_DTPREL_LO12_NC, 0x05e) +ELF_RELOC(R_AARCH64_P32_TLSLD_LDST16_DTPREL_LO12, 0x05f) +ELF_RELOC(R_AARCH64_P32_TLSLD_LDST16_DTPREL_LO12_NC, 0x060) +ELF_RELOC(R_AARCH64_P32_TLSLD_LDST32_DTPREL_LO12, 0x061) +ELF_RELOC(R_AARCH64_P32_TLSLD_LDST32_DTPREL_LO12_NC, 0x062) +ELF_RELOC(R_AARCH64_P32_TLSLD_LDST64_DTPREL_LO12, 0x063) +ELF_RELOC(R_AARCH64_P32_TLSLD_LDST64_DTPREL_LO12_NC, 0x064) +ELF_RELOC(R_AARCH64_P32_TLSLD_LDST128_DTPREL_LO12, 0x065) +ELF_RELOC(R_AARCH64_P32_TLSLD_LDST128_DTPREL_LO12_NC,0x066) +ELF_RELOC(R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21, 0x067) +ELF_RELOC(R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC, 0x068) +ELF_RELOC(R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19, 0x069) +ELF_RELOC(R_AARCH64_P32_TLSLE_MOVW_TPREL_G1, 0x06a) +ELF_RELOC(R_AARCH64_P32_TLSLE_MOVW_TPREL_G0, 0x06b) +ELF_RELOC(R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC, 0x06c) +ELF_RELOC(R_AARCH64_P32_TLSLE_ADD_TPREL_HI12, 0x06d) +ELF_RELOC(R_AARCH64_P32_TLSLE_ADD_TPREL_LO12, 0x06e) +ELF_RELOC(R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC, 0x06f) +ELF_RELOC(R_AARCH64_P32_TLSLE_LDST8_TPREL_LO12, 0x070) +ELF_RELOC(R_AARCH64_P32_TLSLE_LDST8_TPREL_LO12_NC, 0x071) +ELF_RELOC(R_AARCH64_P32_TLSLE_LDST16_TPREL_LO12, 0x072) +ELF_RELOC(R_AARCH64_P32_TLSLE_LDST16_TPREL_LO12_NC, 0x073) +ELF_RELOC(R_AARCH64_P32_TLSLE_LDST32_TPREL_LO12, 0x074) +ELF_RELOC(R_AARCH64_P32_TLSLE_LDST32_TPREL_LO12_NC, 0x075) +ELF_RELOC(R_AARCH64_P32_TLSLE_LDST64_TPREL_LO12, 0x076) +ELF_RELOC(R_AARCH64_P32_TLSLE_LDST64_TPREL_LO12_NC, 0x077) +ELF_RELOC(R_AARCH64_P32_TLSLE_LDST128_TPREL_LO12, 0x078) +ELF_RELOC(R_AARCH64_P32_TLSLE_LDST128_TPREL_LO12_NC, 0x079) +ELF_RELOC(R_AARCH64_P32_TLSDESC_LD_PREL19, 0x07a) +ELF_RELOC(R_AARCH64_P32_TLSDESC_ADR_PREL21, 0x07b) +ELF_RELOC(R_AARCH64_P32_TLSDESC_ADR_PAGE21, 0x07c) +ELF_RELOC(R_AARCH64_P32_TLSDESC_LD32_LO12, 0x07d) +ELF_RELOC(R_AARCH64_P32_TLSDESC_ADD_LO12, 0x07e) +ELF_RELOC(R_AARCH64_P32_TLSDESC_CALL, 0x07f) +// Dynamic relocations start +ELF_RELOC(R_AARCH64_P32_COPY, 0x0b4) +ELF_RELOC(R_AARCH64_P32_GLOB_DAT, 0x0b5) +ELF_RELOC(R_AARCH64_P32_JUMP_SLOT, 0x0b6) +ELF_RELOC(R_AARCH64_P32_RELATIVE, 0x0b7) +ELF_RELOC(R_AARCH64_P32_TLS_DTPREL, 0x0b8) +ELF_RELOC(R_AARCH64_P32_TLS_DTPMOD, 0x0b9) +ELF_RELOC(R_AARCH64_P32_TLS_TPREL, 0x0ba) +ELF_RELOC(R_AARCH64_P32_TLSDESC, 0x0bb) +ELF_RELOC(R_AARCH64_P32_IRELATIVE, 0x0bc) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/AMDGPU.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/AMDGPU.def new file mode 100644 index 00000000000..0ff7b4c766c --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/AMDGPU.def @@ -0,0 +1,18 @@ +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +ELF_RELOC(R_AMDGPU_NONE, 0) +ELF_RELOC(R_AMDGPU_ABS32_LO, 1) +ELF_RELOC(R_AMDGPU_ABS32_HI, 2) +ELF_RELOC(R_AMDGPU_ABS64, 3) +ELF_RELOC(R_AMDGPU_REL32, 4) +ELF_RELOC(R_AMDGPU_REL64, 5) +ELF_RELOC(R_AMDGPU_ABS32, 6) +ELF_RELOC(R_AMDGPU_GOTPCREL, 7) +ELF_RELOC(R_AMDGPU_GOTPCREL32_LO, 8) +ELF_RELOC(R_AMDGPU_GOTPCREL32_HI, 9) +ELF_RELOC(R_AMDGPU_REL32_LO, 10) +ELF_RELOC(R_AMDGPU_REL32_HI, 11) +ELF_RELOC(R_AMDGPU_RELATIVE64, 13) +ELF_RELOC(R_AMDGPU_REL16, 14) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/ARC.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/ARC.def new file mode 100644 index 00000000000..5691fb3458e --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/ARC.def @@ -0,0 +1,74 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +ELF_RELOC(R_ARC_NONE, 0) +ELF_RELOC(R_ARC_8, 1) +ELF_RELOC(R_ARC_16, 2) +ELF_RELOC(R_ARC_24, 3) +ELF_RELOC(R_ARC_32, 4) +ELF_RELOC(R_ARC_N8, 8) +ELF_RELOC(R_ARC_N16, 9) +ELF_RELOC(R_ARC_N24, 10) +ELF_RELOC(R_ARC_N32, 11) +ELF_RELOC(R_ARC_SDA, 12) +ELF_RELOC(R_ARC_SECTOFF, 13) +ELF_RELOC(R_ARC_S21H_PCREL, 14) +ELF_RELOC(R_ARC_S21W_PCREL, 15) +ELF_RELOC(R_ARC_S25H_PCREL, 16) +ELF_RELOC(R_ARC_S25W_PCREL, 17) +ELF_RELOC(R_ARC_SDA32, 18) +ELF_RELOC(R_ARC_SDA_LDST, 19) +ELF_RELOC(R_ARC_SDA_LDST1, 20) +ELF_RELOC(R_ARC_SDA_LDST2, 21) +ELF_RELOC(R_ARC_SDA16_LD, 22) +ELF_RELOC(R_ARC_SDA16_LD1, 23) +ELF_RELOC(R_ARC_SDA16_LD2, 24) +ELF_RELOC(R_ARC_S13_PCREL, 25) +ELF_RELOC(R_ARC_W, 26) +ELF_RELOC(R_ARC_32_ME, 27) +ELF_RELOC(R_ARC_32_ME_S, 105) +ELF_RELOC(R_ARC_N32_ME, 28) +ELF_RELOC(R_ARC_SECTOFF_ME, 29) +ELF_RELOC(R_ARC_SDA32_ME, 30) +ELF_RELOC(R_ARC_W_ME, 31) +ELF_RELOC(R_AC_SECTOFF_U8, 35) +ELF_RELOC(R_AC_SECTOFF_U8_1, 36) +ELF_RELOC(R_AC_SECTOFF_U8_2, 37) +ELF_RELOC(R_AC_SECTOFF_S9, 38) +ELF_RELOC(R_AC_SECTOFF_S9_1, 39) +ELF_RELOC(R_AC_SECTOFF_S9_2, 40) +ELF_RELOC(R_ARC_SECTOFF_ME_1, 41) +ELF_RELOC(R_ARC_SECTOFF_ME_2, 42) +ELF_RELOC(R_ARC_SECTOFF_1, 43) +ELF_RELOC(R_ARC_SECTOFF_2, 44) +ELF_RELOC(R_ARC_SDA_12, 45) +ELF_RELOC(R_ARC_SDA16_ST2, 48) +ELF_RELOC(R_ARC_32_PCREL, 49) +ELF_RELOC(R_ARC_PC32, 50) +ELF_RELOC(R_ARC_GOT32, 59) +ELF_RELOC(R_ARC_GOTPC32, 51) +ELF_RELOC(R_ARC_PLT32, 52) +ELF_RELOC(R_ARC_COPY, 53) +ELF_RELOC(R_ARC_GLOB_DAT, 54) +ELF_RELOC(R_ARC_JMP_SLOT, 55) +ELF_RELOC(R_ARC_RELATIVE, 56) +ELF_RELOC(R_ARC_GOTOFF, 57) +ELF_RELOC(R_ARC_GOTPC, 58) +ELF_RELOC(R_ARC_S21W_PCREL_PLT, 60) +ELF_RELOC(R_ARC_S25H_PCREL_PLT, 61) +ELF_RELOC(R_ARC_JLI_SECTOFF, 63) +ELF_RELOC(R_ARC_TLS_DTPMOD, 66) +ELF_RELOC(R_ARC_TLS_TPOFF, 68) +ELF_RELOC(R_ARC_TLS_GD_GOT, 69) +ELF_RELOC(R_ARC_TLS_GD_LD, 70) +ELF_RELOC(R_ARC_TLS_GD_CALL, 71) +ELF_RELOC(R_ARC_TLS_IE_GOT, 72) +ELF_RELOC(R_ARC_TLS_DTPOFF, 67) +ELF_RELOC(R_ARC_TLS_DTPOFF_S9, 73) +ELF_RELOC(R_ARC_TLS_LE_S9, 74) +ELF_RELOC(R_ARC_TLS_LE_32, 75) +ELF_RELOC(R_ARC_S25W_PCREL_PLT, 76) +ELF_RELOC(R_ARC_S21H_PCREL_PLT, 77) +ELF_RELOC(R_ARC_NPS_CMEM16, 78) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/ARM.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/ARM.def new file mode 100644 index 00000000000..47084d1eb0a --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/ARM.def @@ -0,0 +1,145 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +// Meets 2.09 ABI Specs. +ELF_RELOC(R_ARM_NONE, 0x00) +ELF_RELOC(R_ARM_PC24, 0x01) +ELF_RELOC(R_ARM_ABS32, 0x02) +ELF_RELOC(R_ARM_REL32, 0x03) +ELF_RELOC(R_ARM_LDR_PC_G0, 0x04) +ELF_RELOC(R_ARM_ABS16, 0x05) +ELF_RELOC(R_ARM_ABS12, 0x06) +ELF_RELOC(R_ARM_THM_ABS5, 0x07) +ELF_RELOC(R_ARM_ABS8, 0x08) +ELF_RELOC(R_ARM_SBREL32, 0x09) +ELF_RELOC(R_ARM_THM_CALL, 0x0a) +ELF_RELOC(R_ARM_THM_PC8, 0x0b) +ELF_RELOC(R_ARM_BREL_ADJ, 0x0c) +ELF_RELOC(R_ARM_TLS_DESC, 0x0d) +ELF_RELOC(R_ARM_THM_SWI8, 0x0e) +ELF_RELOC(R_ARM_XPC25, 0x0f) +ELF_RELOC(R_ARM_THM_XPC22, 0x10) +ELF_RELOC(R_ARM_TLS_DTPMOD32, 0x11) +ELF_RELOC(R_ARM_TLS_DTPOFF32, 0x12) +ELF_RELOC(R_ARM_TLS_TPOFF32, 0x13) +ELF_RELOC(R_ARM_COPY, 0x14) +ELF_RELOC(R_ARM_GLOB_DAT, 0x15) +ELF_RELOC(R_ARM_JUMP_SLOT, 0x16) +ELF_RELOC(R_ARM_RELATIVE, 0x17) +ELF_RELOC(R_ARM_GOTOFF32, 0x18) +ELF_RELOC(R_ARM_BASE_PREL, 0x19) +ELF_RELOC(R_ARM_GOT_BREL, 0x1a) +ELF_RELOC(R_ARM_PLT32, 0x1b) +ELF_RELOC(R_ARM_CALL, 0x1c) +ELF_RELOC(R_ARM_JUMP24, 0x1d) +ELF_RELOC(R_ARM_THM_JUMP24, 0x1e) +ELF_RELOC(R_ARM_BASE_ABS, 0x1f) +ELF_RELOC(R_ARM_ALU_PCREL_7_0, 0x20) +ELF_RELOC(R_ARM_ALU_PCREL_15_8, 0x21) +ELF_RELOC(R_ARM_ALU_PCREL_23_15, 0x22) +ELF_RELOC(R_ARM_LDR_SBREL_11_0_NC, 0x23) +ELF_RELOC(R_ARM_ALU_SBREL_19_12_NC, 0x24) +ELF_RELOC(R_ARM_ALU_SBREL_27_20_CK, 0x25) +ELF_RELOC(R_ARM_TARGET1, 0x26) +ELF_RELOC(R_ARM_SBREL31, 0x27) +ELF_RELOC(R_ARM_V4BX, 0x28) +ELF_RELOC(R_ARM_TARGET2, 0x29) +ELF_RELOC(R_ARM_PREL31, 0x2a) +ELF_RELOC(R_ARM_MOVW_ABS_NC, 0x2b) +ELF_RELOC(R_ARM_MOVT_ABS, 0x2c) +ELF_RELOC(R_ARM_MOVW_PREL_NC, 0x2d) +ELF_RELOC(R_ARM_MOVT_PREL, 0x2e) +ELF_RELOC(R_ARM_THM_MOVW_ABS_NC, 0x2f) +ELF_RELOC(R_ARM_THM_MOVT_ABS, 0x30) +ELF_RELOC(R_ARM_THM_MOVW_PREL_NC, 0x31) +ELF_RELOC(R_ARM_THM_MOVT_PREL, 0x32) +ELF_RELOC(R_ARM_THM_JUMP19, 0x33) +ELF_RELOC(R_ARM_THM_JUMP6, 0x34) +ELF_RELOC(R_ARM_THM_ALU_PREL_11_0, 0x35) +ELF_RELOC(R_ARM_THM_PC12, 0x36) +ELF_RELOC(R_ARM_ABS32_NOI, 0x37) +ELF_RELOC(R_ARM_REL32_NOI, 0x38) +ELF_RELOC(R_ARM_ALU_PC_G0_NC, 0x39) +ELF_RELOC(R_ARM_ALU_PC_G0, 0x3a) +ELF_RELOC(R_ARM_ALU_PC_G1_NC, 0x3b) +ELF_RELOC(R_ARM_ALU_PC_G1, 0x3c) +ELF_RELOC(R_ARM_ALU_PC_G2, 0x3d) +ELF_RELOC(R_ARM_LDR_PC_G1, 0x3e) +ELF_RELOC(R_ARM_LDR_PC_G2, 0x3f) +ELF_RELOC(R_ARM_LDRS_PC_G0, 0x40) +ELF_RELOC(R_ARM_LDRS_PC_G1, 0x41) +ELF_RELOC(R_ARM_LDRS_PC_G2, 0x42) +ELF_RELOC(R_ARM_LDC_PC_G0, 0x43) +ELF_RELOC(R_ARM_LDC_PC_G1, 0x44) +ELF_RELOC(R_ARM_LDC_PC_G2, 0x45) +ELF_RELOC(R_ARM_ALU_SB_G0_NC, 0x46) +ELF_RELOC(R_ARM_ALU_SB_G0, 0x47) +ELF_RELOC(R_ARM_ALU_SB_G1_NC, 0x48) +ELF_RELOC(R_ARM_ALU_SB_G1, 0x49) +ELF_RELOC(R_ARM_ALU_SB_G2, 0x4a) +ELF_RELOC(R_ARM_LDR_SB_G0, 0x4b) +ELF_RELOC(R_ARM_LDR_SB_G1, 0x4c) +ELF_RELOC(R_ARM_LDR_SB_G2, 0x4d) +ELF_RELOC(R_ARM_LDRS_SB_G0, 0x4e) +ELF_RELOC(R_ARM_LDRS_SB_G1, 0x4f) +ELF_RELOC(R_ARM_LDRS_SB_G2, 0x50) +ELF_RELOC(R_ARM_LDC_SB_G0, 0x51) +ELF_RELOC(R_ARM_LDC_SB_G1, 0x52) +ELF_RELOC(R_ARM_LDC_SB_G2, 0x53) +ELF_RELOC(R_ARM_MOVW_BREL_NC, 0x54) +ELF_RELOC(R_ARM_MOVT_BREL, 0x55) +ELF_RELOC(R_ARM_MOVW_BREL, 0x56) +ELF_RELOC(R_ARM_THM_MOVW_BREL_NC, 0x57) +ELF_RELOC(R_ARM_THM_MOVT_BREL, 0x58) +ELF_RELOC(R_ARM_THM_MOVW_BREL, 0x59) +ELF_RELOC(R_ARM_TLS_GOTDESC, 0x5a) +ELF_RELOC(R_ARM_TLS_CALL, 0x5b) +ELF_RELOC(R_ARM_TLS_DESCSEQ, 0x5c) +ELF_RELOC(R_ARM_THM_TLS_CALL, 0x5d) +ELF_RELOC(R_ARM_PLT32_ABS, 0x5e) +ELF_RELOC(R_ARM_GOT_ABS, 0x5f) +ELF_RELOC(R_ARM_GOT_PREL, 0x60) +ELF_RELOC(R_ARM_GOT_BREL12, 0x61) +ELF_RELOC(R_ARM_GOTOFF12, 0x62) +ELF_RELOC(R_ARM_GOTRELAX, 0x63) +ELF_RELOC(R_ARM_GNU_VTENTRY, 0x64) +ELF_RELOC(R_ARM_GNU_VTINHERIT, 0x65) +ELF_RELOC(R_ARM_THM_JUMP11, 0x66) +ELF_RELOC(R_ARM_THM_JUMP8, 0x67) +ELF_RELOC(R_ARM_TLS_GD32, 0x68) +ELF_RELOC(R_ARM_TLS_LDM32, 0x69) +ELF_RELOC(R_ARM_TLS_LDO32, 0x6a) +ELF_RELOC(R_ARM_TLS_IE32, 0x6b) +ELF_RELOC(R_ARM_TLS_LE32, 0x6c) +ELF_RELOC(R_ARM_TLS_LDO12, 0x6d) +ELF_RELOC(R_ARM_TLS_LE12, 0x6e) +ELF_RELOC(R_ARM_TLS_IE12GP, 0x6f) +ELF_RELOC(R_ARM_PRIVATE_0, 0x70) +ELF_RELOC(R_ARM_PRIVATE_1, 0x71) +ELF_RELOC(R_ARM_PRIVATE_2, 0x72) +ELF_RELOC(R_ARM_PRIVATE_3, 0x73) +ELF_RELOC(R_ARM_PRIVATE_4, 0x74) +ELF_RELOC(R_ARM_PRIVATE_5, 0x75) +ELF_RELOC(R_ARM_PRIVATE_6, 0x76) +ELF_RELOC(R_ARM_PRIVATE_7, 0x77) +ELF_RELOC(R_ARM_PRIVATE_8, 0x78) +ELF_RELOC(R_ARM_PRIVATE_9, 0x79) +ELF_RELOC(R_ARM_PRIVATE_10, 0x7a) +ELF_RELOC(R_ARM_PRIVATE_11, 0x7b) +ELF_RELOC(R_ARM_PRIVATE_12, 0x7c) +ELF_RELOC(R_ARM_PRIVATE_13, 0x7d) +ELF_RELOC(R_ARM_PRIVATE_14, 0x7e) +ELF_RELOC(R_ARM_PRIVATE_15, 0x7f) +ELF_RELOC(R_ARM_ME_TOO, 0x80) +ELF_RELOC(R_ARM_THM_TLS_DESCSEQ16, 0x81) +ELF_RELOC(R_ARM_THM_TLS_DESCSEQ32, 0x82) +ELF_RELOC(R_ARM_THM_ALU_ABS_G0_NC, 0x84) +ELF_RELOC(R_ARM_THM_ALU_ABS_G1_NC, 0x85) +ELF_RELOC(R_ARM_THM_ALU_ABS_G2_NC, 0x86) +ELF_RELOC(R_ARM_THM_ALU_ABS_G3, 0x87) +ELF_RELOC(R_ARM_THM_BF16, 0x88) +ELF_RELOC(R_ARM_THM_BF12, 0x89) +ELF_RELOC(R_ARM_THM_BF18, 0x8a) +ELF_RELOC(R_ARM_IRELATIVE, 0xa0) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/AVR.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/AVR.def new file mode 100644 index 00000000000..696fc60b0f5 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/AVR.def @@ -0,0 +1,41 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +ELF_RELOC(R_AVR_NONE, 0) +ELF_RELOC(R_AVR_32, 1) +ELF_RELOC(R_AVR_7_PCREL, 2) +ELF_RELOC(R_AVR_13_PCREL, 3) +ELF_RELOC(R_AVR_16, 4) +ELF_RELOC(R_AVR_16_PM, 5) +ELF_RELOC(R_AVR_LO8_LDI, 6) +ELF_RELOC(R_AVR_HI8_LDI, 7) +ELF_RELOC(R_AVR_HH8_LDI, 8) +ELF_RELOC(R_AVR_LO8_LDI_NEG, 9) +ELF_RELOC(R_AVR_HI8_LDI_NEG, 10) +ELF_RELOC(R_AVR_HH8_LDI_NEG, 11) +ELF_RELOC(R_AVR_LO8_LDI_PM, 12) +ELF_RELOC(R_AVR_HI8_LDI_PM, 13) +ELF_RELOC(R_AVR_HH8_LDI_PM, 14) +ELF_RELOC(R_AVR_LO8_LDI_PM_NEG, 15) +ELF_RELOC(R_AVR_HI8_LDI_PM_NEG, 16) +ELF_RELOC(R_AVR_HH8_LDI_PM_NEG, 17) +ELF_RELOC(R_AVR_CALL, 18) +ELF_RELOC(R_AVR_LDI, 19) +ELF_RELOC(R_AVR_6, 20) +ELF_RELOC(R_AVR_6_ADIW, 21) +ELF_RELOC(R_AVR_MS8_LDI, 22) +ELF_RELOC(R_AVR_MS8_LDI_NEG, 23) +ELF_RELOC(R_AVR_LO8_LDI_GS, 24) +ELF_RELOC(R_AVR_HI8_LDI_GS, 25) +ELF_RELOC(R_AVR_8, 26) +ELF_RELOC(R_AVR_8_LO8, 27) +ELF_RELOC(R_AVR_8_HI8, 28) +ELF_RELOC(R_AVR_8_HLO8, 29) +ELF_RELOC(R_AVR_DIFF8, 30) +ELF_RELOC(R_AVR_DIFF16, 31) +ELF_RELOC(R_AVR_DIFF32, 32) +ELF_RELOC(R_AVR_LDS_STS_16, 33) +ELF_RELOC(R_AVR_PORT6, 34) +ELF_RELOC(R_AVR_PORT5, 35) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/BPF.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/BPF.def new file mode 100644 index 00000000000..cc18a65d1fd --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/BPF.def @@ -0,0 +1,11 @@ +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +// No relocation +ELF_RELOC(R_BPF_NONE, 0) +ELF_RELOC(R_BPF_64_64, 1) +ELF_RELOC(R_BPF_64_ABS64, 2) +ELF_RELOC(R_BPF_64_ABS32, 3) +ELF_RELOC(R_BPF_64_NODYLD32, 4) +ELF_RELOC(R_BPF_64_32, 10) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/CSKY.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/CSKY.def new file mode 100644 index 00000000000..c5f2dbae803 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/CSKY.def @@ -0,0 +1,74 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +ELF_RELOC(R_CKCORE_NONE, 0) +ELF_RELOC(R_CKCORE_ADDR32, 1) +ELF_RELOC(R_CKCORE_PCREL_IMM8_4, 2) +ELF_RELOC(R_CKCORE_PCREL_IMM11_2, 3) +ELF_RELOC(R_CKCORE_PCREL_IMM4_2, 4) +ELF_RELOC(R_CKCORE_PCREL32, 5) +ELF_RELOC(R_CKCORE_PCREL_JSR_IMM11_2, 6) +ELF_RELOC(R_CKCORE_GNU_VTINHERIT, 7) +ELF_RELOC(R_CKCORE_GNU_VTENTRY, 8) +ELF_RELOC(R_CKCORE_RELATIVE, 9) +ELF_RELOC(R_CKCORE_COPY, 10) +ELF_RELOC(R_CKCORE_GLOB_DAT, 11) +ELF_RELOC(R_CKCORE_JUMP_SLOT, 12) +ELF_RELOC(R_CKCORE_GOTOFF, 13) +ELF_RELOC(R_CKCORE_GOTPC, 14) +ELF_RELOC(R_CKCORE_GOT32, 15) +ELF_RELOC(R_CKCORE_PLT32, 16) +ELF_RELOC(R_CKCORE_ADDRGOT, 17) +ELF_RELOC(R_CKCORE_ADDRPLT, 18) +ELF_RELOC(R_CKCORE_PCREL_IMM26_2, 19) +ELF_RELOC(R_CKCORE_PCREL_IMM16_2, 20) +ELF_RELOC(R_CKCORE_PCREL_IMM16_4, 21) +ELF_RELOC(R_CKCORE_PCREL_IMM10_2, 22) +ELF_RELOC(R_CKCORE_PCREL_IMM10_4, 23) +ELF_RELOC(R_CKCORE_ADDR_HI16, 24) +ELF_RELOC(R_CKCORE_ADDR_LO16, 25) +ELF_RELOC(R_CKCORE_GOTPC_HI16, 26) +ELF_RELOC(R_CKCORE_GOTPC_LO16, 27) +ELF_RELOC(R_CKCORE_GOTOFF_HI16, 28) +ELF_RELOC(R_CKCORE_GOTOFF_LO16, 29) +ELF_RELOC(R_CKCORE_GOT12, 30) +ELF_RELOC(R_CKCORE_GOT_HI16, 31) +ELF_RELOC(R_CKCORE_GOT_LO16, 32) +ELF_RELOC(R_CKCORE_PLT12, 33) +ELF_RELOC(R_CKCORE_PLT_HI16, 34) +ELF_RELOC(R_CKCORE_PLT_LO16, 35) +ELF_RELOC(R_CKCORE_ADDRGOT_HI16, 36) +ELF_RELOC(R_CKCORE_ADDRGOT_LO16, 37) +ELF_RELOC(R_CKCORE_ADDRPLT_HI16, 38) +ELF_RELOC(R_CKCORE_ADDRPLT_LO16, 39) +ELF_RELOC(R_CKCORE_PCREL_JSR_IMM26_2, 40) +ELF_RELOC(R_CKCORE_TOFFSET_LO16, 41) +ELF_RELOC(R_CKCORE_DOFFSET_LO16, 42) +ELF_RELOC(R_CKCORE_PCREL_IMM18_2, 43) +ELF_RELOC(R_CKCORE_DOFFSET_IMM18, 44) +ELF_RELOC(R_CKCORE_DOFFSET_IMM18_2, 45) +ELF_RELOC(R_CKCORE_DOFFSET_IMM18_4, 46) +ELF_RELOC(R_CKCORE_GOTOFF_IMM18, 47) +ELF_RELOC(R_CKCORE_GOT_IMM18_4, 48) +ELF_RELOC(R_CKCORE_PLT_IMM18_4, 49) +ELF_RELOC(R_CKCORE_PCREL_IMM7_4, 50) +ELF_RELOC(R_CKCORE_TLS_LE32, 51) +ELF_RELOC(R_CKCORE_TLS_IE32, 52) +ELF_RELOC(R_CKCORE_TLS_GD32, 53) +ELF_RELOC(R_CKCORE_TLS_LDM32, 54) +ELF_RELOC(R_CKCORE_TLS_LDO32, 55) +ELF_RELOC(R_CKCORE_TLS_DTPMOD32, 56) +ELF_RELOC(R_CKCORE_TLS_DTPOFF32, 57) +ELF_RELOC(R_CKCORE_TLS_TPOFF32, 58) +ELF_RELOC(R_CKCORE_PCREL_FLRW_IMM8_4, 59) +ELF_RELOC(R_CKCORE_NOJSRI, 60) +ELF_RELOC(R_CKCORE_CALLGRAPH, 61) +ELF_RELOC(R_CKCORE_IRELATIVE, 62) +ELF_RELOC(R_CKCORE_PCREL_BLOOP_IMM4_4, 63) +ELF_RELOC(R_CKCORE_PCREL_BLOOP_IMM12_4, 64) +ELF_RELOC(R_CKCORE_PCREL_VLRW_IMM12_1, 65) +ELF_RELOC(R_CKCORE_PCREL_VLRW_IMM12_2, 66) +ELF_RELOC(R_CKCORE_PCREL_VLRW_IMM12_4, 67) +ELF_RELOC(R_CKCORE_PCREL_VLRW_IMM12_8, 68) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/Hexagon.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/Hexagon.def new file mode 100644 index 00000000000..5021e2b26ce --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/Hexagon.def @@ -0,0 +1,106 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +// Release 5 ABI +ELF_RELOC(R_HEX_NONE, 0) +ELF_RELOC(R_HEX_B22_PCREL, 1) +ELF_RELOC(R_HEX_B15_PCREL, 2) +ELF_RELOC(R_HEX_B7_PCREL, 3) +ELF_RELOC(R_HEX_LO16, 4) +ELF_RELOC(R_HEX_HI16, 5) +ELF_RELOC(R_HEX_32, 6) +ELF_RELOC(R_HEX_16, 7) +ELF_RELOC(R_HEX_8, 8) +ELF_RELOC(R_HEX_GPREL16_0, 9) +ELF_RELOC(R_HEX_GPREL16_1, 10) +ELF_RELOC(R_HEX_GPREL16_2, 11) +ELF_RELOC(R_HEX_GPREL16_3, 12) +ELF_RELOC(R_HEX_HL16, 13) +ELF_RELOC(R_HEX_B13_PCREL, 14) +ELF_RELOC(R_HEX_B9_PCREL, 15) +ELF_RELOC(R_HEX_B32_PCREL_X, 16) +ELF_RELOC(R_HEX_32_6_X, 17) +ELF_RELOC(R_HEX_B22_PCREL_X, 18) +ELF_RELOC(R_HEX_B15_PCREL_X, 19) +ELF_RELOC(R_HEX_B13_PCREL_X, 20) +ELF_RELOC(R_HEX_B9_PCREL_X, 21) +ELF_RELOC(R_HEX_B7_PCREL_X, 22) +ELF_RELOC(R_HEX_16_X, 23) +ELF_RELOC(R_HEX_12_X, 24) +ELF_RELOC(R_HEX_11_X, 25) +ELF_RELOC(R_HEX_10_X, 26) +ELF_RELOC(R_HEX_9_X, 27) +ELF_RELOC(R_HEX_8_X, 28) +ELF_RELOC(R_HEX_7_X, 29) +ELF_RELOC(R_HEX_6_X, 30) +ELF_RELOC(R_HEX_32_PCREL, 31) +ELF_RELOC(R_HEX_COPY, 32) +ELF_RELOC(R_HEX_GLOB_DAT, 33) +ELF_RELOC(R_HEX_JMP_SLOT, 34) +ELF_RELOC(R_HEX_RELATIVE, 35) +ELF_RELOC(R_HEX_PLT_B22_PCREL, 36) +ELF_RELOC(R_HEX_GOTREL_LO16, 37) +ELF_RELOC(R_HEX_GOTREL_HI16, 38) +ELF_RELOC(R_HEX_GOTREL_32, 39) +ELF_RELOC(R_HEX_GOT_LO16, 40) +ELF_RELOC(R_HEX_GOT_HI16, 41) +ELF_RELOC(R_HEX_GOT_32, 42) +ELF_RELOC(R_HEX_GOT_16, 43) +ELF_RELOC(R_HEX_DTPMOD_32, 44) +ELF_RELOC(R_HEX_DTPREL_LO16, 45) +ELF_RELOC(R_HEX_DTPREL_HI16, 46) +ELF_RELOC(R_HEX_DTPREL_32, 47) +ELF_RELOC(R_HEX_DTPREL_16, 48) +ELF_RELOC(R_HEX_GD_PLT_B22_PCREL, 49) +ELF_RELOC(R_HEX_GD_GOT_LO16, 50) +ELF_RELOC(R_HEX_GD_GOT_HI16, 51) +ELF_RELOC(R_HEX_GD_GOT_32, 52) +ELF_RELOC(R_HEX_GD_GOT_16, 53) +ELF_RELOC(R_HEX_IE_LO16, 54) +ELF_RELOC(R_HEX_IE_HI16, 55) +ELF_RELOC(R_HEX_IE_32, 56) +ELF_RELOC(R_HEX_IE_GOT_LO16, 57) +ELF_RELOC(R_HEX_IE_GOT_HI16, 58) +ELF_RELOC(R_HEX_IE_GOT_32, 59) +ELF_RELOC(R_HEX_IE_GOT_16, 60) +ELF_RELOC(R_HEX_TPREL_LO16, 61) +ELF_RELOC(R_HEX_TPREL_HI16, 62) +ELF_RELOC(R_HEX_TPREL_32, 63) +ELF_RELOC(R_HEX_TPREL_16, 64) +ELF_RELOC(R_HEX_6_PCREL_X, 65) +ELF_RELOC(R_HEX_GOTREL_32_6_X, 66) +ELF_RELOC(R_HEX_GOTREL_16_X, 67) +ELF_RELOC(R_HEX_GOTREL_11_X, 68) +ELF_RELOC(R_HEX_GOT_32_6_X, 69) +ELF_RELOC(R_HEX_GOT_16_X, 70) +ELF_RELOC(R_HEX_GOT_11_X, 71) +ELF_RELOC(R_HEX_DTPREL_32_6_X, 72) +ELF_RELOC(R_HEX_DTPREL_16_X, 73) +ELF_RELOC(R_HEX_DTPREL_11_X, 74) +ELF_RELOC(R_HEX_GD_GOT_32_6_X, 75) +ELF_RELOC(R_HEX_GD_GOT_16_X, 76) +ELF_RELOC(R_HEX_GD_GOT_11_X, 77) +ELF_RELOC(R_HEX_IE_32_6_X, 78) +ELF_RELOC(R_HEX_IE_16_X, 79) +ELF_RELOC(R_HEX_IE_GOT_32_6_X, 80) +ELF_RELOC(R_HEX_IE_GOT_16_X, 81) +ELF_RELOC(R_HEX_IE_GOT_11_X, 82) +ELF_RELOC(R_HEX_TPREL_32_6_X, 83) +ELF_RELOC(R_HEX_TPREL_16_X, 84) +ELF_RELOC(R_HEX_TPREL_11_X, 85) +ELF_RELOC(R_HEX_LD_PLT_B22_PCREL, 86) +ELF_RELOC(R_HEX_LD_GOT_LO16, 87) +ELF_RELOC(R_HEX_LD_GOT_HI16, 88) +ELF_RELOC(R_HEX_LD_GOT_32, 89) +ELF_RELOC(R_HEX_LD_GOT_16, 90) +ELF_RELOC(R_HEX_LD_GOT_32_6_X, 91) +ELF_RELOC(R_HEX_LD_GOT_16_X, 92) +ELF_RELOC(R_HEX_LD_GOT_11_X, 93) +ELF_RELOC(R_HEX_23_REG, 94) +ELF_RELOC(R_HEX_GD_PLT_B22_PCREL_X, 95) +ELF_RELOC(R_HEX_GD_PLT_B32_PCREL_X, 96) +ELF_RELOC(R_HEX_LD_PLT_B22_PCREL_X, 97) +ELF_RELOC(R_HEX_LD_PLT_B32_PCREL_X, 98) +ELF_RELOC(R_HEX_27_REG, 99) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/Lanai.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/Lanai.def new file mode 100644 index 00000000000..77ecb048403 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/Lanai.def @@ -0,0 +1,19 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +// No relocation +ELF_RELOC(R_LANAI_NONE, 0) +// 21-bit symbol relocation +ELF_RELOC(R_LANAI_21, 1) +// 21-bit symbol relocation with last two bits masked to 0 +ELF_RELOC(R_LANAI_21_F, 2) +// 25-bit branch targets +ELF_RELOC(R_LANAI_25, 3) +// General 32-bit relocation +ELF_RELOC(R_LANAI_32, 4) +// Upper 16-bits of a symbolic relocation +ELF_RELOC(R_LANAI_HI16, 5) +// Lower 16-bits of a symbolic relocation +ELF_RELOC(R_LANAI_LO16, 6) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/LoongArch.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/LoongArch.def new file mode 100644 index 00000000000..02bce3c7171 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/LoongArch.def @@ -0,0 +1,120 @@ +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +// These types and values are from the LoongArch ELF psABI which can be found at +// https://github.com/loongson/LoongArch-Documentation +// and these definitions has been adopted by binutils (include/elf/loongarch.h). +// The commit hash (main branch) we reference is: +// 9b3bd9f4a497115913c22f1a2a47863798fbc02a + +ELF_RELOC(R_LARCH_NONE, 0) +ELF_RELOC(R_LARCH_32, 1) +ELF_RELOC(R_LARCH_64, 2) +ELF_RELOC(R_LARCH_RELATIVE, 3) +ELF_RELOC(R_LARCH_COPY, 4) +ELF_RELOC(R_LARCH_JUMP_SLOT, 5) +ELF_RELOC(R_LARCH_TLS_DTPMOD32, 6) +ELF_RELOC(R_LARCH_TLS_DTPMOD64, 7) +ELF_RELOC(R_LARCH_TLS_DTPREL32, 8) +ELF_RELOC(R_LARCH_TLS_DTPREL64, 9) +ELF_RELOC(R_LARCH_TLS_TPREL32, 10) +ELF_RELOC(R_LARCH_TLS_TPREL64, 11) +ELF_RELOC(R_LARCH_IRELATIVE, 12) +ELF_RELOC(R_LARCH_MARK_LA, 20) +ELF_RELOC(R_LARCH_MARK_PCREL, 21) +ELF_RELOC(R_LARCH_SOP_PUSH_PCREL, 22) +ELF_RELOC(R_LARCH_SOP_PUSH_ABSOLUTE, 23) +ELF_RELOC(R_LARCH_SOP_PUSH_DUP, 24) +ELF_RELOC(R_LARCH_SOP_PUSH_GPREL, 25) +ELF_RELOC(R_LARCH_SOP_PUSH_TLS_TPREL, 26) +ELF_RELOC(R_LARCH_SOP_PUSH_TLS_GOT, 27) +ELF_RELOC(R_LARCH_SOP_PUSH_TLS_GD, 28) +ELF_RELOC(R_LARCH_SOP_PUSH_PLT_PCREL, 29) +ELF_RELOC(R_LARCH_SOP_ASSERT, 30) +ELF_RELOC(R_LARCH_SOP_NOT, 31) +ELF_RELOC(R_LARCH_SOP_SUB, 32) +ELF_RELOC(R_LARCH_SOP_SL, 33) +ELF_RELOC(R_LARCH_SOP_SR, 34) +ELF_RELOC(R_LARCH_SOP_ADD, 35) +ELF_RELOC(R_LARCH_SOP_AND, 36) +ELF_RELOC(R_LARCH_SOP_IF_ELSE, 37) +ELF_RELOC(R_LARCH_SOP_POP_32_S_10_5, 38) +ELF_RELOC(R_LARCH_SOP_POP_32_U_10_12, 39) +ELF_RELOC(R_LARCH_SOP_POP_32_S_10_12, 40) +ELF_RELOC(R_LARCH_SOP_POP_32_S_10_16, 41) +ELF_RELOC(R_LARCH_SOP_POP_32_S_10_16_S2, 42) +ELF_RELOC(R_LARCH_SOP_POP_32_S_5_20, 43) +ELF_RELOC(R_LARCH_SOP_POP_32_S_0_5_10_16_S2, 44) +ELF_RELOC(R_LARCH_SOP_POP_32_S_0_10_10_16_S2, 45) +ELF_RELOC(R_LARCH_SOP_POP_32_U, 46) +ELF_RELOC(R_LARCH_ADD8, 47) +ELF_RELOC(R_LARCH_ADD16, 48) +ELF_RELOC(R_LARCH_ADD24, 49) +ELF_RELOC(R_LARCH_ADD32, 50) +ELF_RELOC(R_LARCH_ADD64, 51) +ELF_RELOC(R_LARCH_SUB8, 52) +ELF_RELOC(R_LARCH_SUB16, 53) +ELF_RELOC(R_LARCH_SUB24, 54) +ELF_RELOC(R_LARCH_SUB32, 55) +ELF_RELOC(R_LARCH_SUB64, 56) +ELF_RELOC(R_LARCH_GNU_VTINHERIT, 57) +ELF_RELOC(R_LARCH_GNU_VTENTRY, 58) + +// Relocs whose processing do not require a stack machine. +// +// Spec addition: https://github.com/loongson/LoongArch-Documentation/pull/57 +// Binutils commit 6d13722a97cee3fd397e116bde3bcedbb1e220be +// and commit 9801120721c3a702ce3bd50433ef920f92a83502 +ELF_RELOC(R_LARCH_B16, 64) +ELF_RELOC(R_LARCH_B21, 65) +ELF_RELOC(R_LARCH_B26, 66) +ELF_RELOC(R_LARCH_ABS_HI20, 67) +ELF_RELOC(R_LARCH_ABS_LO12, 68) +ELF_RELOC(R_LARCH_ABS64_LO20, 69) +ELF_RELOC(R_LARCH_ABS64_HI12, 70) +ELF_RELOC(R_LARCH_PCALA_HI20, 71) +ELF_RELOC(R_LARCH_PCALA_LO12, 72) +ELF_RELOC(R_LARCH_PCALA64_LO20, 73) +ELF_RELOC(R_LARCH_PCALA64_HI12, 74) +ELF_RELOC(R_LARCH_GOT_PC_HI20, 75) +ELF_RELOC(R_LARCH_GOT_PC_LO12, 76) +ELF_RELOC(R_LARCH_GOT64_PC_LO20, 77) +ELF_RELOC(R_LARCH_GOT64_PC_HI12, 78) +ELF_RELOC(R_LARCH_GOT_HI20, 79) +ELF_RELOC(R_LARCH_GOT_LO12, 80) +ELF_RELOC(R_LARCH_GOT64_LO20, 81) +ELF_RELOC(R_LARCH_GOT64_HI12, 82) +ELF_RELOC(R_LARCH_TLS_LE_HI20, 83) +ELF_RELOC(R_LARCH_TLS_LE_LO12, 84) +ELF_RELOC(R_LARCH_TLS_LE64_LO20, 85) +ELF_RELOC(R_LARCH_TLS_LE64_HI12, 86) +ELF_RELOC(R_LARCH_TLS_IE_PC_HI20, 87) +ELF_RELOC(R_LARCH_TLS_IE_PC_LO12, 88) +ELF_RELOC(R_LARCH_TLS_IE64_PC_LO20, 89) +ELF_RELOC(R_LARCH_TLS_IE64_PC_HI12, 90) +ELF_RELOC(R_LARCH_TLS_IE_HI20, 91) +ELF_RELOC(R_LARCH_TLS_IE_LO12, 92) +ELF_RELOC(R_LARCH_TLS_IE64_LO20, 93) +ELF_RELOC(R_LARCH_TLS_IE64_HI12, 94) +ELF_RELOC(R_LARCH_TLS_LD_PC_HI20, 95) +ELF_RELOC(R_LARCH_TLS_LD_HI20, 96) +ELF_RELOC(R_LARCH_TLS_GD_PC_HI20, 97) +ELF_RELOC(R_LARCH_TLS_GD_HI20, 98) +ELF_RELOC(R_LARCH_32_PCREL, 99) +ELF_RELOC(R_LARCH_RELAX, 100) + +// Relocs added in ELF for the LoongArchâ„¢ Architecture v20230519, part of the +// v2.10 LoongArch ABI specs. +// +// Spec addition: https://github.com/loongson/la-abi-specs/pull/1 +// Binutils commit 57a930e3bfe4b2c7fd6463ed39311e1938513138 +ELF_RELOC(R_LARCH_DELETE, 101) +ELF_RELOC(R_LARCH_ALIGN, 102) +ELF_RELOC(R_LARCH_PCREL20_S2, 103) +ELF_RELOC(R_LARCH_CFA, 104) +ELF_RELOC(R_LARCH_ADD6, 105) +ELF_RELOC(R_LARCH_SUB6, 106) +ELF_RELOC(R_LARCH_ADD_ULEB128, 107) +ELF_RELOC(R_LARCH_SUB_ULEB128, 108) +ELF_RELOC(R_LARCH_64_PCREL, 109) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/M68k.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/M68k.def new file mode 100644 index 00000000000..11f148566c7 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/M68k.def @@ -0,0 +1,49 @@ +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +ELF_RELOC(R_68K_NONE, 0) /* No reloc */ +ELF_RELOC(R_68K_32, 1) /* Direct 32 bit */ +ELF_RELOC(R_68K_16, 2) /* Direct 16 bit */ +ELF_RELOC(R_68K_8, 3) /* Direct 8 bit */ +ELF_RELOC(R_68K_PC32, 4) /* PC relative 32 bit */ +ELF_RELOC(R_68K_PC16, 5) /* PC relative 16 bit */ +ELF_RELOC(R_68K_PC8, 6) /* PC relative 8 bit */ +ELF_RELOC(R_68K_GOTPCREL32, 7) /* 32 bit PC relative GOT entry */ +ELF_RELOC(R_68K_GOTPCREL16, 8) /* 16 bit PC relative GOT entry */ +ELF_RELOC(R_68K_GOTPCREL8, 9) /* 8 bit PC relative GOT entry */ +ELF_RELOC(R_68K_GOTOFF32, 10) /* 32 bit GOT offset */ +ELF_RELOC(R_68K_GOTOFF16, 11) /* 16 bit GOT offset */ +ELF_RELOC(R_68K_GOTOFF8, 12) /* 8 bit GOT offset */ +ELF_RELOC(R_68K_PLT32, 13) /* 32 bit PC relative PLT address */ +ELF_RELOC(R_68K_PLT16, 14) /* 16 bit PC relative PLT address */ +ELF_RELOC(R_68K_PLT8, 15) /* 8 bit PC relative PLT address */ +ELF_RELOC(R_68K_PLTOFF32, 16) /* 32 bit PLT offset */ +ELF_RELOC(R_68K_PLTOFF16, 17) /* 16 bit PLT offset */ +ELF_RELOC(R_68K_PLTOFF8, 18) /* 8 bit PLT offset */ +ELF_RELOC(R_68K_COPY, 19) /* Copy symbol at runtime */ +ELF_RELOC(R_68K_GLOB_DAT, 20) /* Create GOT entry */ +ELF_RELOC(R_68K_JMP_SLOT, 21) /* Create PLT entry */ +ELF_RELOC(R_68K_RELATIVE, 22) /* Adjust by program base */ +/* These are GNU extensions to enable C++ vtable garbage collection. */ +ELF_RELOC(R_68K_GNU_VTINHERIT, 23) +ELF_RELOC(R_68K_GNU_VTENTRY, 24) +/* TLS static relocations. */ +ELF_RELOC(R_68K_TLS_GD32, 25) +ELF_RELOC(R_68K_TLS_GD16, 26) +ELF_RELOC(R_68K_TLS_GD8, 27) +ELF_RELOC(R_68K_TLS_LDM32, 28) +ELF_RELOC(R_68K_TLS_LDM16, 29) +ELF_RELOC(R_68K_TLS_LDM8, 30) +ELF_RELOC(R_68K_TLS_LDO32, 31) +ELF_RELOC(R_68K_TLS_LDO16, 32) +ELF_RELOC(R_68K_TLS_LDO8, 33) +ELF_RELOC(R_68K_TLS_IE32, 34) +ELF_RELOC(R_68K_TLS_IE16, 35) +ELF_RELOC(R_68K_TLS_IE8, 36) +ELF_RELOC(R_68K_TLS_LE32, 37) +ELF_RELOC(R_68K_TLS_LE16, 38) +ELF_RELOC(R_68K_TLS_LE8, 39) +ELF_RELOC(R_68K_TLS_DTPMOD32, 40) +ELF_RELOC(R_68K_TLS_DTPREL32, 41) +ELF_RELOC(R_68K_TLS_TPREL32, 42) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/MSP430.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/MSP430.def new file mode 100644 index 00000000000..96990abf2db --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/MSP430.def @@ -0,0 +1,16 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +ELF_RELOC(R_MSP430_NONE, 0) +ELF_RELOC(R_MSP430_32, 1) +ELF_RELOC(R_MSP430_10_PCREL, 2) +ELF_RELOC(R_MSP430_16, 3) +ELF_RELOC(R_MSP430_16_PCREL, 4) +ELF_RELOC(R_MSP430_16_BYTE, 5) +ELF_RELOC(R_MSP430_16_PCREL_BYTE, 6) +ELF_RELOC(R_MSP430_2X_PCREL, 7) +ELF_RELOC(R_MSP430_RL_PCREL, 8) +ELF_RELOC(R_MSP430_8, 9) +ELF_RELOC(R_MSP430_SYM_DIFF, 10) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/Mips.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/Mips.def new file mode 100644 index 00000000000..bc0088dff3f --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/Mips.def @@ -0,0 +1,117 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +ELF_RELOC(R_MIPS_NONE, 0) +ELF_RELOC(R_MIPS_16, 1) +ELF_RELOC(R_MIPS_32, 2) +ELF_RELOC(R_MIPS_REL32, 3) +ELF_RELOC(R_MIPS_26, 4) +ELF_RELOC(R_MIPS_HI16, 5) +ELF_RELOC(R_MIPS_LO16, 6) +ELF_RELOC(R_MIPS_GPREL16, 7) +ELF_RELOC(R_MIPS_LITERAL, 8) +ELF_RELOC(R_MIPS_GOT16, 9) +ELF_RELOC(R_MIPS_PC16, 10) +ELF_RELOC(R_MIPS_CALL16, 11) +ELF_RELOC(R_MIPS_GPREL32, 12) +ELF_RELOC(R_MIPS_UNUSED1, 13) +ELF_RELOC(R_MIPS_UNUSED2, 14) +ELF_RELOC(R_MIPS_UNUSED3, 15) +ELF_RELOC(R_MIPS_SHIFT5, 16) +ELF_RELOC(R_MIPS_SHIFT6, 17) +ELF_RELOC(R_MIPS_64, 18) +ELF_RELOC(R_MIPS_GOT_DISP, 19) +ELF_RELOC(R_MIPS_GOT_PAGE, 20) +ELF_RELOC(R_MIPS_GOT_OFST, 21) +ELF_RELOC(R_MIPS_GOT_HI16, 22) +ELF_RELOC(R_MIPS_GOT_LO16, 23) +ELF_RELOC(R_MIPS_SUB, 24) +ELF_RELOC(R_MIPS_INSERT_A, 25) +ELF_RELOC(R_MIPS_INSERT_B, 26) +ELF_RELOC(R_MIPS_DELETE, 27) +ELF_RELOC(R_MIPS_HIGHER, 28) +ELF_RELOC(R_MIPS_HIGHEST, 29) +ELF_RELOC(R_MIPS_CALL_HI16, 30) +ELF_RELOC(R_MIPS_CALL_LO16, 31) +ELF_RELOC(R_MIPS_SCN_DISP, 32) +ELF_RELOC(R_MIPS_REL16, 33) +ELF_RELOC(R_MIPS_ADD_IMMEDIATE, 34) +ELF_RELOC(R_MIPS_PJUMP, 35) +ELF_RELOC(R_MIPS_RELGOT, 36) +ELF_RELOC(R_MIPS_JALR, 37) +ELF_RELOC(R_MIPS_TLS_DTPMOD32, 38) +ELF_RELOC(R_MIPS_TLS_DTPREL32, 39) +ELF_RELOC(R_MIPS_TLS_DTPMOD64, 40) +ELF_RELOC(R_MIPS_TLS_DTPREL64, 41) +ELF_RELOC(R_MIPS_TLS_GD, 42) +ELF_RELOC(R_MIPS_TLS_LDM, 43) +ELF_RELOC(R_MIPS_TLS_DTPREL_HI16, 44) +ELF_RELOC(R_MIPS_TLS_DTPREL_LO16, 45) +ELF_RELOC(R_MIPS_TLS_GOTTPREL, 46) +ELF_RELOC(R_MIPS_TLS_TPREL32, 47) +ELF_RELOC(R_MIPS_TLS_TPREL64, 48) +ELF_RELOC(R_MIPS_TLS_TPREL_HI16, 49) +ELF_RELOC(R_MIPS_TLS_TPREL_LO16, 50) +ELF_RELOC(R_MIPS_GLOB_DAT, 51) +ELF_RELOC(R_MIPS_PC21_S2, 60) +ELF_RELOC(R_MIPS_PC26_S2, 61) +ELF_RELOC(R_MIPS_PC18_S3, 62) +ELF_RELOC(R_MIPS_PC19_S2, 63) +ELF_RELOC(R_MIPS_PCHI16, 64) +ELF_RELOC(R_MIPS_PCLO16, 65) +ELF_RELOC(R_MIPS16_26, 100) +ELF_RELOC(R_MIPS16_GPREL, 101) +ELF_RELOC(R_MIPS16_GOT16, 102) +ELF_RELOC(R_MIPS16_CALL16, 103) +ELF_RELOC(R_MIPS16_HI16, 104) +ELF_RELOC(R_MIPS16_LO16, 105) +ELF_RELOC(R_MIPS16_TLS_GD, 106) +ELF_RELOC(R_MIPS16_TLS_LDM, 107) +ELF_RELOC(R_MIPS16_TLS_DTPREL_HI16, 108) +ELF_RELOC(R_MIPS16_TLS_DTPREL_LO16, 109) +ELF_RELOC(R_MIPS16_TLS_GOTTPREL, 110) +ELF_RELOC(R_MIPS16_TLS_TPREL_HI16, 111) +ELF_RELOC(R_MIPS16_TLS_TPREL_LO16, 112) +ELF_RELOC(R_MIPS_COPY, 126) +ELF_RELOC(R_MIPS_JUMP_SLOT, 127) +ELF_RELOC(R_MICROMIPS_26_S1, 133) +ELF_RELOC(R_MICROMIPS_HI16, 134) +ELF_RELOC(R_MICROMIPS_LO16, 135) +ELF_RELOC(R_MICROMIPS_GPREL16, 136) +ELF_RELOC(R_MICROMIPS_LITERAL, 137) +ELF_RELOC(R_MICROMIPS_GOT16, 138) +ELF_RELOC(R_MICROMIPS_PC7_S1, 139) +ELF_RELOC(R_MICROMIPS_PC10_S1, 140) +ELF_RELOC(R_MICROMIPS_PC16_S1, 141) +ELF_RELOC(R_MICROMIPS_CALL16, 142) +ELF_RELOC(R_MICROMIPS_GOT_DISP, 145) +ELF_RELOC(R_MICROMIPS_GOT_PAGE, 146) +ELF_RELOC(R_MICROMIPS_GOT_OFST, 147) +ELF_RELOC(R_MICROMIPS_GOT_HI16, 148) +ELF_RELOC(R_MICROMIPS_GOT_LO16, 149) +ELF_RELOC(R_MICROMIPS_SUB, 150) +ELF_RELOC(R_MICROMIPS_HIGHER, 151) +ELF_RELOC(R_MICROMIPS_HIGHEST, 152) +ELF_RELOC(R_MICROMIPS_CALL_HI16, 153) +ELF_RELOC(R_MICROMIPS_CALL_LO16, 154) +ELF_RELOC(R_MICROMIPS_SCN_DISP, 155) +ELF_RELOC(R_MICROMIPS_JALR, 156) +ELF_RELOC(R_MICROMIPS_HI0_LO16, 157) +ELF_RELOC(R_MICROMIPS_TLS_GD, 162) +ELF_RELOC(R_MICROMIPS_TLS_LDM, 163) +ELF_RELOC(R_MICROMIPS_TLS_DTPREL_HI16, 164) +ELF_RELOC(R_MICROMIPS_TLS_DTPREL_LO16, 165) +ELF_RELOC(R_MICROMIPS_TLS_GOTTPREL, 166) +ELF_RELOC(R_MICROMIPS_TLS_TPREL_HI16, 169) +ELF_RELOC(R_MICROMIPS_TLS_TPREL_LO16, 170) +ELF_RELOC(R_MICROMIPS_GPREL7_S2, 172) +ELF_RELOC(R_MICROMIPS_PC23_S2, 173) +ELF_RELOC(R_MICROMIPS_PC21_S1, 174) +ELF_RELOC(R_MICROMIPS_PC26_S1, 175) +ELF_RELOC(R_MICROMIPS_PC18_S3, 176) +ELF_RELOC(R_MICROMIPS_PC19_S2, 177) +ELF_RELOC(R_MIPS_NUM, 218) +ELF_RELOC(R_MIPS_PC32, 248) +ELF_RELOC(R_MIPS_EH, 249) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/PowerPC.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/PowerPC.def new file mode 100644 index 00000000000..28036889cca --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/PowerPC.def @@ -0,0 +1,156 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +// glibc's PowerPC asm/sigcontext.h, when compiling for PPC64, has the +// unfortunate behavior of including asm/elf.h, which defines R_PPC_NONE, etc. +// to their corresponding integer values. As a result, we need to undef them +// here before continuing. + +#undef R_PPC_NONE +#undef R_PPC_ADDR32 +#undef R_PPC_ADDR24 +#undef R_PPC_ADDR16 +#undef R_PPC_ADDR16_LO +#undef R_PPC_ADDR16_HI +#undef R_PPC_ADDR16_HA +#undef R_PPC_ADDR14 +#undef R_PPC_ADDR14_BRTAKEN +#undef R_PPC_ADDR14_BRNTAKEN +#undef R_PPC_REL24 +#undef R_PPC_REL14 +#undef R_PPC_REL14_BRTAKEN +#undef R_PPC_REL14_BRNTAKEN +#undef R_PPC_GOT16 +#undef R_PPC_GOT16_LO +#undef R_PPC_GOT16_HI +#undef R_PPC_GOT16_HA +#undef R_PPC_PLTREL24 +#undef R_PPC_COPY +#undef R_PPC_GLOB_DAT +#undef R_PPC_JMP_SLOT +#undef R_PPC_RELATIVE +#undef R_PPC_LOCAL24PC +#undef R_PPC_UADDR32 +#undef R_PPC_UADDR16 +#undef R_PPC_REL32 +#undef R_PPC_PLT32 +#undef R_PPC_PLTREL32 +#undef R_PPC_PLT16_LO +#undef R_PPC_PLT16_HI +#undef R_PPC_PLT16_HA +#undef R_PPC_SDAREL16 +#undef R_PPC_SECTOFF +#undef R_PPC_SECTOFF_LO +#undef R_PPC_SECTOFF_HI +#undef R_PPC_SECTOFF_HA +#undef R_PPC_ADDR30 +#undef R_PPC_TLS +#undef R_PPC_DTPMOD32 +#undef R_PPC_TPREL16 +#undef R_PPC_TPREL16_LO +#undef R_PPC_TPREL16_HI +#undef R_PPC_TPREL16_HA +#undef R_PPC_TPREL32 +#undef R_PPC_DTPREL16 +#undef R_PPC_DTPREL16_LO +#undef R_PPC_DTPREL16_HI +#undef R_PPC_DTPREL16_HA +#undef R_PPC_DTPREL32 +#undef R_PPC_GOT_TLSGD16 +#undef R_PPC_GOT_TLSGD16_LO +#undef R_PPC_GOT_TLSGD16_HI +#undef R_PPC_GOT_TLSGD16_HA +#undef R_PPC_GOT_TLSLD16 +#undef R_PPC_GOT_TLSLD16_LO +#undef R_PPC_GOT_TLSLD16_HI +#undef R_PPC_GOT_TLSLD16_HA +#undef R_PPC_GOT_TPREL16 +#undef R_PPC_GOT_TPREL16_LO +#undef R_PPC_GOT_TPREL16_HI +#undef R_PPC_GOT_TPREL16_HA +#undef R_PPC_GOT_DTPREL16 +#undef R_PPC_GOT_DTPREL16_LO +#undef R_PPC_GOT_DTPREL16_HI +#undef R_PPC_GOT_DTPREL16_HA +#undef R_PPC_TLSGD +#undef R_PPC_TLSLD +#undef R_PPC_REL16 +#undef R_PPC_REL16_LO +#undef R_PPC_REL16_HI +#undef R_PPC_REL16_HA + +ELF_RELOC(R_PPC_NONE, 0) /* No relocation. */ +ELF_RELOC(R_PPC_ADDR32, 1) +ELF_RELOC(R_PPC_ADDR24, 2) +ELF_RELOC(R_PPC_ADDR16, 3) +ELF_RELOC(R_PPC_ADDR16_LO, 4) +ELF_RELOC(R_PPC_ADDR16_HI, 5) +ELF_RELOC(R_PPC_ADDR16_HA, 6) +ELF_RELOC(R_PPC_ADDR14, 7) +ELF_RELOC(R_PPC_ADDR14_BRTAKEN, 8) +ELF_RELOC(R_PPC_ADDR14_BRNTAKEN, 9) +ELF_RELOC(R_PPC_REL24, 10) +ELF_RELOC(R_PPC_REL14, 11) +ELF_RELOC(R_PPC_REL14_BRTAKEN, 12) +ELF_RELOC(R_PPC_REL14_BRNTAKEN, 13) +ELF_RELOC(R_PPC_GOT16, 14) +ELF_RELOC(R_PPC_GOT16_LO, 15) +ELF_RELOC(R_PPC_GOT16_HI, 16) +ELF_RELOC(R_PPC_GOT16_HA, 17) +ELF_RELOC(R_PPC_PLTREL24, 18) +ELF_RELOC(R_PPC_COPY, 19) +ELF_RELOC(R_PPC_GLOB_DAT, 20) +ELF_RELOC(R_PPC_JMP_SLOT, 21) +ELF_RELOC(R_PPC_RELATIVE, 22) +ELF_RELOC(R_PPC_LOCAL24PC, 23) +ELF_RELOC(R_PPC_UADDR32, 24) +ELF_RELOC(R_PPC_UADDR16, 25) +ELF_RELOC(R_PPC_REL32, 26) +ELF_RELOC(R_PPC_PLT32, 27) +ELF_RELOC(R_PPC_PLTREL32, 28) +ELF_RELOC(R_PPC_PLT16_LO, 29) +ELF_RELOC(R_PPC_PLT16_HI, 30) +ELF_RELOC(R_PPC_PLT16_HA, 31) +ELF_RELOC(R_PPC_SDAREL16, 32) +ELF_RELOC(R_PPC_SECTOFF, 33) +ELF_RELOC(R_PPC_SECTOFF_LO, 34) +ELF_RELOC(R_PPC_SECTOFF_HI, 35) +ELF_RELOC(R_PPC_SECTOFF_HA, 36) +ELF_RELOC(R_PPC_ADDR30, 37) +ELF_RELOC(R_PPC_TLS, 67) +ELF_RELOC(R_PPC_DTPMOD32, 68) +ELF_RELOC(R_PPC_TPREL16, 69) +ELF_RELOC(R_PPC_TPREL16_LO, 70) +ELF_RELOC(R_PPC_TPREL16_HI, 71) +ELF_RELOC(R_PPC_TPREL16_HA, 72) +ELF_RELOC(R_PPC_TPREL32, 73) +ELF_RELOC(R_PPC_DTPREL16, 74) +ELF_RELOC(R_PPC_DTPREL16_LO, 75) +ELF_RELOC(R_PPC_DTPREL16_HI, 76) +ELF_RELOC(R_PPC_DTPREL16_HA, 77) +ELF_RELOC(R_PPC_DTPREL32, 78) +ELF_RELOC(R_PPC_GOT_TLSGD16, 79) +ELF_RELOC(R_PPC_GOT_TLSGD16_LO, 80) +ELF_RELOC(R_PPC_GOT_TLSGD16_HI, 81) +ELF_RELOC(R_PPC_GOT_TLSGD16_HA, 82) +ELF_RELOC(R_PPC_GOT_TLSLD16, 83) +ELF_RELOC(R_PPC_GOT_TLSLD16_LO, 84) +ELF_RELOC(R_PPC_GOT_TLSLD16_HI, 85) +ELF_RELOC(R_PPC_GOT_TLSLD16_HA, 86) +ELF_RELOC(R_PPC_GOT_TPREL16, 87) +ELF_RELOC(R_PPC_GOT_TPREL16_LO, 88) +ELF_RELOC(R_PPC_GOT_TPREL16_HI, 89) +ELF_RELOC(R_PPC_GOT_TPREL16_HA, 90) +ELF_RELOC(R_PPC_GOT_DTPREL16, 91) +ELF_RELOC(R_PPC_GOT_DTPREL16_LO, 92) +ELF_RELOC(R_PPC_GOT_DTPREL16_HI, 93) +ELF_RELOC(R_PPC_GOT_DTPREL16_HA, 94) +ELF_RELOC(R_PPC_TLSGD, 95) +ELF_RELOC(R_PPC_TLSLD, 96) +ELF_RELOC(R_PPC_IRELATIVE, 248) +ELF_RELOC(R_PPC_REL16, 249) +ELF_RELOC(R_PPC_REL16_LO, 250) +ELF_RELOC(R_PPC_REL16_HI, 251) +ELF_RELOC(R_PPC_REL16_HA, 252) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/PowerPC64.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/PowerPC64.def new file mode 100644 index 00000000000..0422aa0606d --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/PowerPC64.def @@ -0,0 +1,215 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +// glibc's PowerPC asm/sigcontext.h, when compiling for PPC64, has the +// unfortunate behavior of including asm/elf.h, which defines R_PPC_NONE, etc. +// to their corresponding integer values. As a result, we need to undef them +// here before continuing. + +#undef R_PPC64_NONE +#undef R_PPC64_ADDR32 +#undef R_PPC64_ADDR24 +#undef R_PPC64_ADDR16 +#undef R_PPC64_ADDR16_LO +#undef R_PPC64_ADDR16_HI +#undef R_PPC64_ADDR16_HA +#undef R_PPC64_ADDR14 +#undef R_PPC64_ADDR14_BRTAKEN +#undef R_PPC64_ADDR14_BRNTAKEN +#undef R_PPC64_REL24 +#undef R_PPC64_REL14 +#undef R_PPC64_REL14_BRTAKEN +#undef R_PPC64_REL14_BRNTAKEN +#undef R_PPC64_GOT16 +#undef R_PPC64_GOT16_LO +#undef R_PPC64_GOT16_HI +#undef R_PPC64_GOT16_HA +#undef R_PPC64_COPY +#undef R_PPC64_GLOB_DAT +#undef R_PPC64_JMP_SLOT +#undef R_PPC64_RELATIVE +#undef R_PPC64_REL32 +#undef R_PPC64_ADDR64 +#undef R_PPC64_ADDR16_HIGHER +#undef R_PPC64_ADDR16_HIGHERA +#undef R_PPC64_ADDR16_HIGHEST +#undef R_PPC64_ADDR16_HIGHESTA +#undef R_PPC64_REL64 +#undef R_PPC64_TOC16 +#undef R_PPC64_TOC16_LO +#undef R_PPC64_TOC16_HI +#undef R_PPC64_TOC16_HA +#undef R_PPC64_TOC +#undef R_PPC64_ADDR16_DS +#undef R_PPC64_ADDR16_LO_DS +#undef R_PPC64_GOT16_DS +#undef R_PPC64_GOT16_LO_DS +#undef R_PPC64_TOC16_DS +#undef R_PPC64_TOC16_LO_DS +#undef R_PPC64_TLS +#undef R_PPC64_DTPMOD64 +#undef R_PPC64_TPREL16 +#undef R_PPC64_TPREL16_LO +#undef R_PPC64_TPREL16_HI +#undef R_PPC64_TPREL16_HA +#undef R_PPC64_TPREL64 +#undef R_PPC64_DTPREL16 +#undef R_PPC64_DTPREL16_LO +#undef R_PPC64_DTPREL16_HI +#undef R_PPC64_DTPREL16_HA +#undef R_PPC64_DTPREL64 +#undef R_PPC64_GOT_TLSGD16 +#undef R_PPC64_GOT_TLSGD16_LO +#undef R_PPC64_GOT_TLSGD16_HI +#undef R_PPC64_GOT_TLSGD16_HA +#undef R_PPC64_GOT_TLSLD16 +#undef R_PPC64_GOT_TLSLD16_LO +#undef R_PPC64_GOT_TLSLD16_HI +#undef R_PPC64_GOT_TLSLD16_HA +#undef R_PPC64_GOT_TPREL16_DS +#undef R_PPC64_GOT_TPREL16_LO_DS +#undef R_PPC64_GOT_TPREL16_HI +#undef R_PPC64_GOT_TPREL16_HA +#undef R_PPC64_GOT_DTPREL16_DS +#undef R_PPC64_GOT_DTPREL16_LO_DS +#undef R_PPC64_GOT_DTPREL16_HI +#undef R_PPC64_GOT_DTPREL16_HA +#undef R_PPC64_TPREL16_DS +#undef R_PPC64_TPREL16_LO_DS +#undef R_PPC64_TPREL16_HIGHER +#undef R_PPC64_TPREL16_HIGHERA +#undef R_PPC64_TPREL16_HIGHEST +#undef R_PPC64_TPREL16_HIGHESTA +#undef R_PPC64_DTPREL16_DS +#undef R_PPC64_DTPREL16_LO_DS +#undef R_PPC64_DTPREL16_HIGHER +#undef R_PPC64_DTPREL16_HIGHERA +#undef R_PPC64_DTPREL16_HIGHEST +#undef R_PPC64_DTPREL16_HIGHESTA +#undef R_PPC64_TLSGD +#undef R_PPC64_TLSLD +#undef R_PPC64_ADDR16_HIGH +#undef R_PPC64_ADDR16_HIGHA +#undef R_PPC64_TPREL16_HIGH +#undef R_PPC64_TPREL16_HIGHA +#undef R_PPC64_DTPREL16_HIGH +#undef R_PPC64_DTPREL16_HIGHA +#undef R_PPC64_REL24_NOTOC +#undef R_PPC64_PCREL_OPT +#undef R_PPC64_PCREL34 +#undef R_PPC64_GOT_PCREL34 +#undef R_PPC64_TPREL34 +#undef R_PPC64_DTPREL34 +#undef R_PPC64_GOT_TLSGD_PCREL34 +#undef R_PPC64_GOT_TLSLD_PCREL34 +#undef R_PPC64_GOT_TPREL_PCREL34 +#undef R_PPC64_IRELATIVE +#undef R_PPC64_REL16 +#undef R_PPC64_REL16_LO +#undef R_PPC64_REL16_HI +#undef R_PPC64_REL16_HA + +ELF_RELOC(R_PPC64_NONE, 0) +ELF_RELOC(R_PPC64_ADDR32, 1) +ELF_RELOC(R_PPC64_ADDR24, 2) +ELF_RELOC(R_PPC64_ADDR16, 3) +ELF_RELOC(R_PPC64_ADDR16_LO, 4) +ELF_RELOC(R_PPC64_ADDR16_HI, 5) +ELF_RELOC(R_PPC64_ADDR16_HA, 6) +ELF_RELOC(R_PPC64_ADDR14, 7) +ELF_RELOC(R_PPC64_ADDR14_BRTAKEN, 8) +ELF_RELOC(R_PPC64_ADDR14_BRNTAKEN, 9) +ELF_RELOC(R_PPC64_REL24, 10) +ELF_RELOC(R_PPC64_REL14, 11) +ELF_RELOC(R_PPC64_REL14_BRTAKEN, 12) +ELF_RELOC(R_PPC64_REL14_BRNTAKEN, 13) +ELF_RELOC(R_PPC64_GOT16, 14) +ELF_RELOC(R_PPC64_GOT16_LO, 15) +ELF_RELOC(R_PPC64_GOT16_HI, 16) +ELF_RELOC(R_PPC64_GOT16_HA, 17) +ELF_RELOC(R_PPC64_COPY, 19) +ELF_RELOC(R_PPC64_GLOB_DAT, 20) +ELF_RELOC(R_PPC64_JMP_SLOT, 21) +ELF_RELOC(R_PPC64_RELATIVE, 22) +ELF_RELOC(R_PPC64_REL32, 26) +ELF_RELOC(R_PPC64_ADDR64, 38) +ELF_RELOC(R_PPC64_ADDR16_HIGHER, 39) +ELF_RELOC(R_PPC64_ADDR16_HIGHERA, 40) +ELF_RELOC(R_PPC64_ADDR16_HIGHEST, 41) +ELF_RELOC(R_PPC64_ADDR16_HIGHESTA, 42) +ELF_RELOC(R_PPC64_REL64, 44) +ELF_RELOC(R_PPC64_TOC16, 47) +ELF_RELOC(R_PPC64_TOC16_LO, 48) +ELF_RELOC(R_PPC64_TOC16_HI, 49) +ELF_RELOC(R_PPC64_TOC16_HA, 50) +ELF_RELOC(R_PPC64_TOC, 51) +ELF_RELOC(R_PPC64_ADDR16_DS, 56) +ELF_RELOC(R_PPC64_ADDR16_LO_DS, 57) +ELF_RELOC(R_PPC64_GOT16_DS, 58) +ELF_RELOC(R_PPC64_GOT16_LO_DS, 59) +ELF_RELOC(R_PPC64_TOC16_DS, 63) +ELF_RELOC(R_PPC64_TOC16_LO_DS, 64) +ELF_RELOC(R_PPC64_TLS, 67) +ELF_RELOC(R_PPC64_DTPMOD64, 68) +ELF_RELOC(R_PPC64_TPREL16, 69) +ELF_RELOC(R_PPC64_TPREL16_LO, 70) +ELF_RELOC(R_PPC64_TPREL16_HI, 71) +ELF_RELOC(R_PPC64_TPREL16_HA, 72) +ELF_RELOC(R_PPC64_TPREL64, 73) +ELF_RELOC(R_PPC64_DTPREL16, 74) +ELF_RELOC(R_PPC64_DTPREL16_LO, 75) +ELF_RELOC(R_PPC64_DTPREL16_HI, 76) +ELF_RELOC(R_PPC64_DTPREL16_HA, 77) +ELF_RELOC(R_PPC64_DTPREL64, 78) +ELF_RELOC(R_PPC64_GOT_TLSGD16, 79) +ELF_RELOC(R_PPC64_GOT_TLSGD16_LO, 80) +ELF_RELOC(R_PPC64_GOT_TLSGD16_HI, 81) +ELF_RELOC(R_PPC64_GOT_TLSGD16_HA, 82) +ELF_RELOC(R_PPC64_GOT_TLSLD16, 83) +ELF_RELOC(R_PPC64_GOT_TLSLD16_LO, 84) +ELF_RELOC(R_PPC64_GOT_TLSLD16_HI, 85) +ELF_RELOC(R_PPC64_GOT_TLSLD16_HA, 86) +ELF_RELOC(R_PPC64_GOT_TPREL16_DS, 87) +ELF_RELOC(R_PPC64_GOT_TPREL16_LO_DS, 88) +ELF_RELOC(R_PPC64_GOT_TPREL16_HI, 89) +ELF_RELOC(R_PPC64_GOT_TPREL16_HA, 90) +ELF_RELOC(R_PPC64_GOT_DTPREL16_DS, 91) +ELF_RELOC(R_PPC64_GOT_DTPREL16_LO_DS, 92) +ELF_RELOC(R_PPC64_GOT_DTPREL16_HI, 93) +ELF_RELOC(R_PPC64_GOT_DTPREL16_HA, 94) +ELF_RELOC(R_PPC64_TPREL16_DS, 95) +ELF_RELOC(R_PPC64_TPREL16_LO_DS, 96) +ELF_RELOC(R_PPC64_TPREL16_HIGHER, 97) +ELF_RELOC(R_PPC64_TPREL16_HIGHERA, 98) +ELF_RELOC(R_PPC64_TPREL16_HIGHEST, 99) +ELF_RELOC(R_PPC64_TPREL16_HIGHESTA, 100) +ELF_RELOC(R_PPC64_DTPREL16_DS, 101) +ELF_RELOC(R_PPC64_DTPREL16_LO_DS, 102) +ELF_RELOC(R_PPC64_DTPREL16_HIGHER, 103) +ELF_RELOC(R_PPC64_DTPREL16_HIGHERA, 104) +ELF_RELOC(R_PPC64_DTPREL16_HIGHEST, 105) +ELF_RELOC(R_PPC64_DTPREL16_HIGHESTA, 106) +ELF_RELOC(R_PPC64_TLSGD, 107) +ELF_RELOC(R_PPC64_TLSLD, 108) +ELF_RELOC(R_PPC64_ADDR16_HIGH, 110) +ELF_RELOC(R_PPC64_ADDR16_HIGHA, 111) +ELF_RELOC(R_PPC64_TPREL16_HIGH, 112) +ELF_RELOC(R_PPC64_TPREL16_HIGHA, 113) +ELF_RELOC(R_PPC64_DTPREL16_HIGH, 114) +ELF_RELOC(R_PPC64_DTPREL16_HIGHA, 115) +ELF_RELOC(R_PPC64_REL24_NOTOC, 116) +ELF_RELOC(R_PPC64_PCREL_OPT, 123) +ELF_RELOC(R_PPC64_PCREL34, 132) +ELF_RELOC(R_PPC64_GOT_PCREL34, 133) +ELF_RELOC(R_PPC64_TPREL34, 146) +ELF_RELOC(R_PPC64_DTPREL34, 147) +ELF_RELOC(R_PPC64_GOT_TLSGD_PCREL34, 148) +ELF_RELOC(R_PPC64_GOT_TLSLD_PCREL34, 149) +ELF_RELOC(R_PPC64_GOT_TPREL_PCREL34, 150) +ELF_RELOC(R_PPC64_IRELATIVE, 248) +ELF_RELOC(R_PPC64_REL16, 249) +ELF_RELOC(R_PPC64_REL16_LO, 250) +ELF_RELOC(R_PPC64_REL16_HI, 251) +ELF_RELOC(R_PPC64_REL16_HA, 252) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/RISCV.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/RISCV.def new file mode 100644 index 00000000000..9a126df0153 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/RISCV.def @@ -0,0 +1,57 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +ELF_RELOC(R_RISCV_NONE, 0) +ELF_RELOC(R_RISCV_32, 1) +ELF_RELOC(R_RISCV_64, 2) +ELF_RELOC(R_RISCV_RELATIVE, 3) +ELF_RELOC(R_RISCV_COPY, 4) +ELF_RELOC(R_RISCV_JUMP_SLOT, 5) +ELF_RELOC(R_RISCV_TLS_DTPMOD32, 6) +ELF_RELOC(R_RISCV_TLS_DTPMOD64, 7) +ELF_RELOC(R_RISCV_TLS_DTPREL32, 8) +ELF_RELOC(R_RISCV_TLS_DTPREL64, 9) +ELF_RELOC(R_RISCV_TLS_TPREL32, 10) +ELF_RELOC(R_RISCV_TLS_TPREL64, 11) +ELF_RELOC(R_RISCV_BRANCH, 16) +ELF_RELOC(R_RISCV_JAL, 17) +ELF_RELOC(R_RISCV_CALL, 18) +ELF_RELOC(R_RISCV_CALL_PLT, 19) +ELF_RELOC(R_RISCV_GOT_HI20, 20) +ELF_RELOC(R_RISCV_TLS_GOT_HI20, 21) +ELF_RELOC(R_RISCV_TLS_GD_HI20, 22) +ELF_RELOC(R_RISCV_PCREL_HI20, 23) +ELF_RELOC(R_RISCV_PCREL_LO12_I, 24) +ELF_RELOC(R_RISCV_PCREL_LO12_S, 25) +ELF_RELOC(R_RISCV_HI20, 26) +ELF_RELOC(R_RISCV_LO12_I, 27) +ELF_RELOC(R_RISCV_LO12_S, 28) +ELF_RELOC(R_RISCV_TPREL_HI20, 29) +ELF_RELOC(R_RISCV_TPREL_LO12_I, 30) +ELF_RELOC(R_RISCV_TPREL_LO12_S, 31) +ELF_RELOC(R_RISCV_TPREL_ADD, 32) +ELF_RELOC(R_RISCV_ADD8, 33) +ELF_RELOC(R_RISCV_ADD16, 34) +ELF_RELOC(R_RISCV_ADD32, 35) +ELF_RELOC(R_RISCV_ADD64, 36) +ELF_RELOC(R_RISCV_SUB8, 37) +ELF_RELOC(R_RISCV_SUB16, 38) +ELF_RELOC(R_RISCV_SUB32, 39) +ELF_RELOC(R_RISCV_SUB64, 40) +ELF_RELOC(R_RISCV_GNU_VTINHERIT, 41) +ELF_RELOC(R_RISCV_GNU_VTENTRY, 42) +ELF_RELOC(R_RISCV_ALIGN, 43) +ELF_RELOC(R_RISCV_RVC_BRANCH, 44) +ELF_RELOC(R_RISCV_RVC_JUMP, 45) +ELF_RELOC(R_RISCV_RVC_LUI, 46) +ELF_RELOC(R_RISCV_RELAX, 51) +ELF_RELOC(R_RISCV_SUB6, 52) +ELF_RELOC(R_RISCV_SET6, 53) +ELF_RELOC(R_RISCV_SET8, 54) +ELF_RELOC(R_RISCV_SET16, 55) +ELF_RELOC(R_RISCV_SET32, 56) +ELF_RELOC(R_RISCV_32_PCREL, 57) +ELF_RELOC(R_RISCV_IRELATIVE, 58) +ELF_RELOC(R_RISCV_PLT32, 59) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/Sparc.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/Sparc.def new file mode 100644 index 00000000000..7e01a4a8a0a --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/Sparc.def @@ -0,0 +1,89 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +ELF_RELOC(R_SPARC_NONE, 0) +ELF_RELOC(R_SPARC_8, 1) +ELF_RELOC(R_SPARC_16, 2) +ELF_RELOC(R_SPARC_32, 3) +ELF_RELOC(R_SPARC_DISP8, 4) +ELF_RELOC(R_SPARC_DISP16, 5) +ELF_RELOC(R_SPARC_DISP32, 6) +ELF_RELOC(R_SPARC_WDISP30, 7) +ELF_RELOC(R_SPARC_WDISP22, 8) +ELF_RELOC(R_SPARC_HI22, 9) +ELF_RELOC(R_SPARC_22, 10) +ELF_RELOC(R_SPARC_13, 11) +ELF_RELOC(R_SPARC_LO10, 12) +ELF_RELOC(R_SPARC_GOT10, 13) +ELF_RELOC(R_SPARC_GOT13, 14) +ELF_RELOC(R_SPARC_GOT22, 15) +ELF_RELOC(R_SPARC_PC10, 16) +ELF_RELOC(R_SPARC_PC22, 17) +ELF_RELOC(R_SPARC_WPLT30, 18) +ELF_RELOC(R_SPARC_COPY, 19) +ELF_RELOC(R_SPARC_GLOB_DAT, 20) +ELF_RELOC(R_SPARC_JMP_SLOT, 21) +ELF_RELOC(R_SPARC_RELATIVE, 22) +ELF_RELOC(R_SPARC_UA32, 23) +ELF_RELOC(R_SPARC_PLT32, 24) +ELF_RELOC(R_SPARC_HIPLT22, 25) +ELF_RELOC(R_SPARC_LOPLT10, 26) +ELF_RELOC(R_SPARC_PCPLT32, 27) +ELF_RELOC(R_SPARC_PCPLT22, 28) +ELF_RELOC(R_SPARC_PCPLT10, 29) +ELF_RELOC(R_SPARC_10, 30) +ELF_RELOC(R_SPARC_11, 31) +ELF_RELOC(R_SPARC_64, 32) +ELF_RELOC(R_SPARC_OLO10, 33) +ELF_RELOC(R_SPARC_HH22, 34) +ELF_RELOC(R_SPARC_HM10, 35) +ELF_RELOC(R_SPARC_LM22, 36) +ELF_RELOC(R_SPARC_PC_HH22, 37) +ELF_RELOC(R_SPARC_PC_HM10, 38) +ELF_RELOC(R_SPARC_PC_LM22, 39) +ELF_RELOC(R_SPARC_WDISP16, 40) +ELF_RELOC(R_SPARC_WDISP19, 41) +ELF_RELOC(R_SPARC_7, 43) +ELF_RELOC(R_SPARC_5, 44) +ELF_RELOC(R_SPARC_6, 45) +ELF_RELOC(R_SPARC_DISP64, 46) +ELF_RELOC(R_SPARC_PLT64, 47) +ELF_RELOC(R_SPARC_HIX22, 48) +ELF_RELOC(R_SPARC_LOX10, 49) +ELF_RELOC(R_SPARC_H44, 50) +ELF_RELOC(R_SPARC_M44, 51) +ELF_RELOC(R_SPARC_L44, 52) +ELF_RELOC(R_SPARC_REGISTER, 53) +ELF_RELOC(R_SPARC_UA64, 54) +ELF_RELOC(R_SPARC_UA16, 55) +ELF_RELOC(R_SPARC_TLS_GD_HI22, 56) +ELF_RELOC(R_SPARC_TLS_GD_LO10, 57) +ELF_RELOC(R_SPARC_TLS_GD_ADD, 58) +ELF_RELOC(R_SPARC_TLS_GD_CALL, 59) +ELF_RELOC(R_SPARC_TLS_LDM_HI22, 60) +ELF_RELOC(R_SPARC_TLS_LDM_LO10, 61) +ELF_RELOC(R_SPARC_TLS_LDM_ADD, 62) +ELF_RELOC(R_SPARC_TLS_LDM_CALL, 63) +ELF_RELOC(R_SPARC_TLS_LDO_HIX22, 64) +ELF_RELOC(R_SPARC_TLS_LDO_LOX10, 65) +ELF_RELOC(R_SPARC_TLS_LDO_ADD, 66) +ELF_RELOC(R_SPARC_TLS_IE_HI22, 67) +ELF_RELOC(R_SPARC_TLS_IE_LO10, 68) +ELF_RELOC(R_SPARC_TLS_IE_LD, 69) +ELF_RELOC(R_SPARC_TLS_IE_LDX, 70) +ELF_RELOC(R_SPARC_TLS_IE_ADD, 71) +ELF_RELOC(R_SPARC_TLS_LE_HIX22, 72) +ELF_RELOC(R_SPARC_TLS_LE_LOX10, 73) +ELF_RELOC(R_SPARC_TLS_DTPMOD32, 74) +ELF_RELOC(R_SPARC_TLS_DTPMOD64, 75) +ELF_RELOC(R_SPARC_TLS_DTPOFF32, 76) +ELF_RELOC(R_SPARC_TLS_DTPOFF64, 77) +ELF_RELOC(R_SPARC_TLS_TPOFF32, 78) +ELF_RELOC(R_SPARC_TLS_TPOFF64, 79) +ELF_RELOC(R_SPARC_GOTDATA_HIX22, 80) +ELF_RELOC(R_SPARC_GOTDATA_LOX10, 81) +ELF_RELOC(R_SPARC_GOTDATA_OP_HIX22, 82) +ELF_RELOC(R_SPARC_GOTDATA_OP_LOX10, 83) +ELF_RELOC(R_SPARC_GOTDATA_OP, 84) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/SystemZ.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/SystemZ.def new file mode 100644 index 00000000000..d6c0b79d40a --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/SystemZ.def @@ -0,0 +1,71 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +ELF_RELOC(R_390_NONE, 0) +ELF_RELOC(R_390_8, 1) +ELF_RELOC(R_390_12, 2) +ELF_RELOC(R_390_16, 3) +ELF_RELOC(R_390_32, 4) +ELF_RELOC(R_390_PC32, 5) +ELF_RELOC(R_390_GOT12, 6) +ELF_RELOC(R_390_GOT32, 7) +ELF_RELOC(R_390_PLT32, 8) +ELF_RELOC(R_390_COPY, 9) +ELF_RELOC(R_390_GLOB_DAT, 10) +ELF_RELOC(R_390_JMP_SLOT, 11) +ELF_RELOC(R_390_RELATIVE, 12) +ELF_RELOC(R_390_GOTOFF, 13) +ELF_RELOC(R_390_GOTPC, 14) +ELF_RELOC(R_390_GOT16, 15) +ELF_RELOC(R_390_PC16, 16) +ELF_RELOC(R_390_PC16DBL, 17) +ELF_RELOC(R_390_PLT16DBL, 18) +ELF_RELOC(R_390_PC32DBL, 19) +ELF_RELOC(R_390_PLT32DBL, 20) +ELF_RELOC(R_390_GOTPCDBL, 21) +ELF_RELOC(R_390_64, 22) +ELF_RELOC(R_390_PC64, 23) +ELF_RELOC(R_390_GOT64, 24) +ELF_RELOC(R_390_PLT64, 25) +ELF_RELOC(R_390_GOTENT, 26) +ELF_RELOC(R_390_GOTOFF16, 27) +ELF_RELOC(R_390_GOTOFF64, 28) +ELF_RELOC(R_390_GOTPLT12, 29) +ELF_RELOC(R_390_GOTPLT16, 30) +ELF_RELOC(R_390_GOTPLT32, 31) +ELF_RELOC(R_390_GOTPLT64, 32) +ELF_RELOC(R_390_GOTPLTENT, 33) +ELF_RELOC(R_390_PLTOFF16, 34) +ELF_RELOC(R_390_PLTOFF32, 35) +ELF_RELOC(R_390_PLTOFF64, 36) +ELF_RELOC(R_390_TLS_LOAD, 37) +ELF_RELOC(R_390_TLS_GDCALL, 38) +ELF_RELOC(R_390_TLS_LDCALL, 39) +ELF_RELOC(R_390_TLS_GD32, 40) +ELF_RELOC(R_390_TLS_GD64, 41) +ELF_RELOC(R_390_TLS_GOTIE12, 42) +ELF_RELOC(R_390_TLS_GOTIE32, 43) +ELF_RELOC(R_390_TLS_GOTIE64, 44) +ELF_RELOC(R_390_TLS_LDM32, 45) +ELF_RELOC(R_390_TLS_LDM64, 46) +ELF_RELOC(R_390_TLS_IE32, 47) +ELF_RELOC(R_390_TLS_IE64, 48) +ELF_RELOC(R_390_TLS_IEENT, 49) +ELF_RELOC(R_390_TLS_LE32, 50) +ELF_RELOC(R_390_TLS_LE64, 51) +ELF_RELOC(R_390_TLS_LDO32, 52) +ELF_RELOC(R_390_TLS_LDO64, 53) +ELF_RELOC(R_390_TLS_DTPMOD, 54) +ELF_RELOC(R_390_TLS_DTPOFF, 55) +ELF_RELOC(R_390_TLS_TPOFF, 56) +ELF_RELOC(R_390_20, 57) +ELF_RELOC(R_390_GOT20, 58) +ELF_RELOC(R_390_GOTPLT20, 59) +ELF_RELOC(R_390_TLS_GOTIE20, 60) +ELF_RELOC(R_390_IRELATIVE, 61) +ELF_RELOC(R_390_PC12DBL, 62) +ELF_RELOC(R_390_PLT12DBL, 63) +ELF_RELOC(R_390_PC24DBL, 64) +ELF_RELOC(R_390_PLT24DBL, 65) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/VE.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/VE.def new file mode 100644 index 00000000000..9bfdbf1b096 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/VE.def @@ -0,0 +1,48 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +// Relocation types defined in following documents. +// +// - System V Application Binary Interface - VE Architecture +// Processor Supplement +// - ELF Handling For Thread-Local Storage - VE Architecture +// Processor Supplement + +ELF_RELOC(R_VE_NONE, 0) +ELF_RELOC(R_VE_REFLONG, 1) +ELF_RELOC(R_VE_REFQUAD, 2) +ELF_RELOC(R_VE_SREL32, 3) +ELF_RELOC(R_VE_HI32, 4) +ELF_RELOC(R_VE_LO32, 5) +ELF_RELOC(R_VE_PC_HI32, 6) +ELF_RELOC(R_VE_PC_LO32, 7) +ELF_RELOC(R_VE_GOT32, 8) +ELF_RELOC(R_VE_GOT_HI32, 9) +ELF_RELOC(R_VE_GOT_LO32, 10) +ELF_RELOC(R_VE_GOTOFF32, 11) +ELF_RELOC(R_VE_GOTOFF_HI32, 12) +ELF_RELOC(R_VE_GOTOFF_LO32, 13) +ELF_RELOC(R_VE_PLT32, 14) +ELF_RELOC(R_VE_PLT_HI32, 15) +ELF_RELOC(R_VE_PLT_LO32, 16) +ELF_RELOC(R_VE_RELATIVE, 17) +ELF_RELOC(R_VE_GLOB_DAT, 18) +ELF_RELOC(R_VE_JUMP_SLOT, 19) +ELF_RELOC(R_VE_COPY, 20) +ELF_RELOC(R_VE_DTPMOD64, 22) +ELF_RELOC(R_VE_DTPOFF64, 23) +// ELF_RELOC(R_VE_TPOFF64, 24) +ELF_RELOC(R_VE_TLS_GD_HI32, 25) +ELF_RELOC(R_VE_TLS_GD_LO32, 26) +// ELF_RELOC(R_VE_TLS_LD_HI32, 27) +// ELF_RELOC(R_VE_TLS_LD_LO32, 28) +// ELF_RELOC(R_VE_DTPOFF32, 29) +// ELF_RELOC(R_VE_TLS_IE_HI32, 30) +// ELF_RELOC(R_VE_TLS_IE_LO32, 31) +ELF_RELOC(R_VE_TPOFF_HI32, 32) +ELF_RELOC(R_VE_TPOFF_LO32, 33) +// ELF_RELOC(R_VE_TPOFF32, 34) +ELF_RELOC(R_VE_CALL_HI32, 35) +ELF_RELOC(R_VE_CALL_LO32, 36) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/Xtensa.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/Xtensa.def new file mode 100644 index 00000000000..6791a842181 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/Xtensa.def @@ -0,0 +1,60 @@ +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +ELF_RELOC(R_XTENSA_NONE, 0) +ELF_RELOC(R_XTENSA_32, 1) +ELF_RELOC(R_XTENSA_RTLD, 2) +ELF_RELOC(R_XTENSA_GLOB_DAT, 3) +ELF_RELOC(R_XTENSA_JMP_SLOT, 4) +ELF_RELOC(R_XTENSA_RELATIVE, 5) +ELF_RELOC(R_XTENSA_PLT, 6) +// RELOC '7' currently is not used. +ELF_RELOC(R_XTENSA_OP0, 8) +ELF_RELOC(R_XTENSA_OP1, 9) +ELF_RELOC(R_XTENSA_OP2, 10) +ELF_RELOC(R_XTENSA_ASM_EXPAND, 11) +ELF_RELOC(R_XTENSA_ASM_SIMPLIFY, 12) +ELF_RELOC(R_XTENSA_32_PCREL, 14) +ELF_RELOC(R_XTENSA_GNU_VTINHERIT, 15) +ELF_RELOC(R_XTENSA_GNU_VTENTRY, 16) +ELF_RELOC(R_XTENSA_DIFF8, 17) +ELF_RELOC(R_XTENSA_DIFF16, 18) +ELF_RELOC(R_XTENSA_DIFF32, 19) +ELF_RELOC(R_XTENSA_SLOT0_OP, 20) +ELF_RELOC(R_XTENSA_SLOT1_OP, 21) +ELF_RELOC(R_XTENSA_SLOT2_OP, 22) +ELF_RELOC(R_XTENSA_SLOT3_OP, 23) +ELF_RELOC(R_XTENSA_SLOT4_OP, 24) +ELF_RELOC(R_XTENSA_SLOT5_OP, 25) +ELF_RELOC(R_XTENSA_SLOT6_OP, 26) +ELF_RELOC(R_XTENSA_SLOT7_OP, 27) +ELF_RELOC(R_XTENSA_SLOT8_OP, 28) +ELF_RELOC(R_XTENSA_SLOT9_OP, 29) +ELF_RELOC(R_XTENSA_SLOT10_OP, 30) +ELF_RELOC(R_XTENSA_SLOT11_OP, 31) +ELF_RELOC(R_XTENSA_SLOT12_OP, 32) +ELF_RELOC(R_XTENSA_SLOT13_OP, 33) +ELF_RELOC(R_XTENSA_SLOT14_OP, 34) +ELF_RELOC(R_XTENSA_SLOT0_ALT, 35) +ELF_RELOC(R_XTENSA_SLOT1_ALT, 36) +ELF_RELOC(R_XTENSA_SLOT2_ALT, 37) +ELF_RELOC(R_XTENSA_SLOT3_ALT, 38) +ELF_RELOC(R_XTENSA_SLOT4_ALT, 39) +ELF_RELOC(R_XTENSA_SLOT5_ALT, 40) +ELF_RELOC(R_XTENSA_SLOT6_ALT, 41) +ELF_RELOC(R_XTENSA_SLOT7_ALT, 42) +ELF_RELOC(R_XTENSA_SLOT8_ALT, 43) +ELF_RELOC(R_XTENSA_SLOT9_ALT, 44) +ELF_RELOC(R_XTENSA_SLOT10_ALT, 45) +ELF_RELOC(R_XTENSA_SLOT11_ALT, 46) +ELF_RELOC(R_XTENSA_SLOT12_ALT, 47) +ELF_RELOC(R_XTENSA_SLOT13_ALT, 48) +ELF_RELOC(R_XTENSA_SLOT14_ALT, 49) +ELF_RELOC(R_XTENSA_TLSDESC_FN, 50) +ELF_RELOC(R_XTENSA_TLSDESC_ARG, 51) +ELF_RELOC(R_XTENSA_TLS_DTPOFF, 52) +ELF_RELOC(R_XTENSA_TLS_TPOFF, 53) +ELF_RELOC(R_XTENSA_TLS_FUNC, 54) +ELF_RELOC(R_XTENSA_TLS_ARG, 55) +ELF_RELOC(R_XTENSA_TLS_CALL, 56) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/i386.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/i386.def new file mode 100644 index 00000000000..1d28cf595cd --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/i386.def @@ -0,0 +1,47 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +// TODO: this is just a subset +ELF_RELOC(R_386_NONE, 0) +ELF_RELOC(R_386_32, 1) +ELF_RELOC(R_386_PC32, 2) +ELF_RELOC(R_386_GOT32, 3) +ELF_RELOC(R_386_PLT32, 4) +ELF_RELOC(R_386_COPY, 5) +ELF_RELOC(R_386_GLOB_DAT, 6) +ELF_RELOC(R_386_JUMP_SLOT, 7) +ELF_RELOC(R_386_RELATIVE, 8) +ELF_RELOC(R_386_GOTOFF, 9) +ELF_RELOC(R_386_GOTPC, 10) +ELF_RELOC(R_386_32PLT, 11) +ELF_RELOC(R_386_TLS_TPOFF, 14) +ELF_RELOC(R_386_TLS_IE, 15) +ELF_RELOC(R_386_TLS_GOTIE, 16) +ELF_RELOC(R_386_TLS_LE, 17) +ELF_RELOC(R_386_TLS_GD, 18) +ELF_RELOC(R_386_TLS_LDM, 19) +ELF_RELOC(R_386_16, 20) +ELF_RELOC(R_386_PC16, 21) +ELF_RELOC(R_386_8, 22) +ELF_RELOC(R_386_PC8, 23) +ELF_RELOC(R_386_TLS_GD_32, 24) +ELF_RELOC(R_386_TLS_GD_PUSH, 25) +ELF_RELOC(R_386_TLS_GD_CALL, 26) +ELF_RELOC(R_386_TLS_GD_POP, 27) +ELF_RELOC(R_386_TLS_LDM_32, 28) +ELF_RELOC(R_386_TLS_LDM_PUSH, 29) +ELF_RELOC(R_386_TLS_LDM_CALL, 30) +ELF_RELOC(R_386_TLS_LDM_POP, 31) +ELF_RELOC(R_386_TLS_LDO_32, 32) +ELF_RELOC(R_386_TLS_IE_32, 33) +ELF_RELOC(R_386_TLS_LE_32, 34) +ELF_RELOC(R_386_TLS_DTPMOD32, 35) +ELF_RELOC(R_386_TLS_DTPOFF32, 36) +ELF_RELOC(R_386_TLS_TPOFF32, 37) +ELF_RELOC(R_386_TLS_GOTDESC, 39) +ELF_RELOC(R_386_TLS_DESC_CALL, 40) +ELF_RELOC(R_386_TLS_DESC, 41) +ELF_RELOC(R_386_IRELATIVE, 42) +ELF_RELOC(R_386_GOT32X, 43) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/x86_64.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/x86_64.def new file mode 100644 index 00000000000..18fdcf9472d --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/ELFRelocs/x86_64.def @@ -0,0 +1,45 @@ + +#ifndef ELF_RELOC +#error "ELF_RELOC must be defined" +#endif + +ELF_RELOC(R_X86_64_NONE, 0) +ELF_RELOC(R_X86_64_64, 1) +ELF_RELOC(R_X86_64_PC32, 2) +ELF_RELOC(R_X86_64_GOT32, 3) +ELF_RELOC(R_X86_64_PLT32, 4) +ELF_RELOC(R_X86_64_COPY, 5) +ELF_RELOC(R_X86_64_GLOB_DAT, 6) +ELF_RELOC(R_X86_64_JUMP_SLOT, 7) +ELF_RELOC(R_X86_64_RELATIVE, 8) +ELF_RELOC(R_X86_64_GOTPCREL, 9) +ELF_RELOC(R_X86_64_32, 10) +ELF_RELOC(R_X86_64_32S, 11) +ELF_RELOC(R_X86_64_16, 12) +ELF_RELOC(R_X86_64_PC16, 13) +ELF_RELOC(R_X86_64_8, 14) +ELF_RELOC(R_X86_64_PC8, 15) +ELF_RELOC(R_X86_64_DTPMOD64, 16) +ELF_RELOC(R_X86_64_DTPOFF64, 17) +ELF_RELOC(R_X86_64_TPOFF64, 18) +ELF_RELOC(R_X86_64_TLSGD, 19) +ELF_RELOC(R_X86_64_TLSLD, 20) +ELF_RELOC(R_X86_64_DTPOFF32, 21) +ELF_RELOC(R_X86_64_GOTTPOFF, 22) +ELF_RELOC(R_X86_64_TPOFF32, 23) +ELF_RELOC(R_X86_64_PC64, 24) +ELF_RELOC(R_X86_64_GOTOFF64, 25) +ELF_RELOC(R_X86_64_GOTPC32, 26) +ELF_RELOC(R_X86_64_GOT64, 27) +ELF_RELOC(R_X86_64_GOTPCREL64, 28) +ELF_RELOC(R_X86_64_GOTPC64, 29) +ELF_RELOC(R_X86_64_GOTPLT64, 30) +ELF_RELOC(R_X86_64_PLTOFF64, 31) +ELF_RELOC(R_X86_64_SIZE32, 32) +ELF_RELOC(R_X86_64_SIZE64, 33) +ELF_RELOC(R_X86_64_GOTPC32_TLSDESC, 34) +ELF_RELOC(R_X86_64_TLSDESC_CALL, 35) +ELF_RELOC(R_X86_64_TLSDESC, 36) +ELF_RELOC(R_X86_64_IRELATIVE, 37) +ELF_RELOC(R_X86_64_GOTPCRELX, 41) +ELF_RELOC(R_X86_64_REX_GOTPCRELX, 42) diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/MachO.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/MachO.def new file mode 100644 index 00000000000..d841b42ee80 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/MachO.def @@ -0,0 +1,124 @@ +//,,,-- llvm/Support/MachO.def - The MachO file definitions -----*- C++ -*-,,,// +// +// 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 +// +//,,,----------------------------------------------------------------------,,,// +// +// Definitions for MachO files +// +//,,,----------------------------------------------------------------------,,,// + +#ifdef HANDLE_LOAD_COMMAND + +HANDLE_LOAD_COMMAND(LC_SEGMENT, 0x00000001u, segment_command) +HANDLE_LOAD_COMMAND(LC_SYMTAB, 0x00000002u, symtab_command) +// LC_SYMSEG is obsolete and no longer supported. +HANDLE_LOAD_COMMAND(LC_SYMSEG, 0x00000003u, symseg_command) +HANDLE_LOAD_COMMAND(LC_THREAD, 0x00000004u, thread_command) +HANDLE_LOAD_COMMAND(LC_UNIXTHREAD, 0x00000005u, thread_command) +// LC_LOADFVMLIB is obsolete and no longer supported. +HANDLE_LOAD_COMMAND(LC_LOADFVMLIB, 0x00000006u, fvmlib_command) +// LC_IDFVMLIB is obsolete and no longer supported. +HANDLE_LOAD_COMMAND(LC_IDFVMLIB, 0x00000007u, fvmlib_command) +// LC_IDENT is obsolete and no longer supported. +HANDLE_LOAD_COMMAND(LC_IDENT, 0x00000008u, ident_command) +// LC_FVMFILE is obsolete and no longer supported. +HANDLE_LOAD_COMMAND(LC_FVMFILE, 0x00000009u, fvmfile_command) +// LC_PREPAGE is obsolete and no longer supported. +HANDLE_LOAD_COMMAND(LC_PREPAGE, 0x0000000Au, load_command) +HANDLE_LOAD_COMMAND(LC_DYSYMTAB, 0x0000000Bu, dysymtab_command) +HANDLE_LOAD_COMMAND(LC_LOAD_DYLIB, 0x0000000Cu, dylib_command) +HANDLE_LOAD_COMMAND(LC_ID_DYLIB, 0x0000000Du, dylib_command) +HANDLE_LOAD_COMMAND(LC_LOAD_DYLINKER, 0x0000000Eu, dylinker_command) +HANDLE_LOAD_COMMAND(LC_ID_DYLINKER, 0x0000000Fu, dylinker_command) +// LC_PREBOUND_DYLIB is obsolete and no longer supported. +HANDLE_LOAD_COMMAND(LC_PREBOUND_DYLIB, 0x00000010u, prebound_dylib_command) +HANDLE_LOAD_COMMAND(LC_ROUTINES, 0x00000011u, routines_command) +HANDLE_LOAD_COMMAND(LC_SUB_FRAMEWORK, 0x00000012u, sub_framework_command) +HANDLE_LOAD_COMMAND(LC_SUB_UMBRELLA, 0x00000013u, sub_umbrella_command) +HANDLE_LOAD_COMMAND(LC_SUB_CLIENT, 0x00000014u, sub_client_command) +HANDLE_LOAD_COMMAND(LC_SUB_LIBRARY, 0x00000015u, sub_library_command) +// LC_TWOLEVEL_HINTS is obsolete and no longer supported. +HANDLE_LOAD_COMMAND(LC_TWOLEVEL_HINTS, 0x00000016u, twolevel_hints_command) +// LC_PREBIND_CKSUM is obsolete and no longer supported. +HANDLE_LOAD_COMMAND(LC_PREBIND_CKSUM, 0x00000017u, prebind_cksum_command) +// LC_LOAD_WEAK_DYLIB is obsolete and no longer supported. +HANDLE_LOAD_COMMAND(LC_LOAD_WEAK_DYLIB, 0x80000018u, dylib_command) +HANDLE_LOAD_COMMAND(LC_SEGMENT_64, 0x00000019u, segment_command_64) +HANDLE_LOAD_COMMAND(LC_ROUTINES_64, 0x0000001Au, routines_command_64) +HANDLE_LOAD_COMMAND(LC_UUID, 0x0000001Bu, uuid_command) +HANDLE_LOAD_COMMAND(LC_RPATH, 0x8000001Cu, rpath_command) +HANDLE_LOAD_COMMAND(LC_CODE_SIGNATURE, 0x0000001Du, linkedit_data_command) +HANDLE_LOAD_COMMAND(LC_SEGMENT_SPLIT_INFO, 0x0000001Eu, linkedit_data_command) +HANDLE_LOAD_COMMAND(LC_REEXPORT_DYLIB, 0x8000001Fu, dylib_command) +HANDLE_LOAD_COMMAND(LC_LAZY_LOAD_DYLIB, 0x00000020u, dylib_command) +HANDLE_LOAD_COMMAND(LC_ENCRYPTION_INFO, 0x00000021u, encryption_info_command) +HANDLE_LOAD_COMMAND(LC_DYLD_INFO, 0x00000022u, dyld_info_command) +HANDLE_LOAD_COMMAND(LC_DYLD_INFO_ONLY, 0x80000022u, dyld_info_command) +HANDLE_LOAD_COMMAND(LC_LOAD_UPWARD_DYLIB, 0x80000023u, dylib_command) +HANDLE_LOAD_COMMAND(LC_VERSION_MIN_MACOSX, 0x00000024u, version_min_command) +HANDLE_LOAD_COMMAND(LC_VERSION_MIN_IPHONEOS, 0x00000025u, version_min_command) +HANDLE_LOAD_COMMAND(LC_FUNCTION_STARTS, 0x00000026u, linkedit_data_command) +HANDLE_LOAD_COMMAND(LC_DYLD_ENVIRONMENT, 0x00000027u, dylinker_command) +HANDLE_LOAD_COMMAND(LC_MAIN, 0x80000028u, entry_point_command) +HANDLE_LOAD_COMMAND(LC_DATA_IN_CODE, 0x00000029u, linkedit_data_command) +HANDLE_LOAD_COMMAND(LC_SOURCE_VERSION, 0x0000002Au, source_version_command) +HANDLE_LOAD_COMMAND(LC_DYLIB_CODE_SIGN_DRS, 0x0000002Bu, linkedit_data_command) +HANDLE_LOAD_COMMAND(LC_ENCRYPTION_INFO_64, 0x0000002Cu, + encryption_info_command_64) +HANDLE_LOAD_COMMAND(LC_LINKER_OPTION, 0x0000002Du, linker_option_command) +HANDLE_LOAD_COMMAND(LC_LINKER_OPTIMIZATION_HINT, 0x0000002Eu, linkedit_data_command) +HANDLE_LOAD_COMMAND(LC_VERSION_MIN_TVOS, 0x0000002Fu, version_min_command) +HANDLE_LOAD_COMMAND(LC_VERSION_MIN_WATCHOS, 0x00000030u, version_min_command) +HANDLE_LOAD_COMMAND(LC_NOTE, 0x00000031u, note_command) +HANDLE_LOAD_COMMAND(LC_BUILD_VERSION, 0x00000032u, build_version_command) +HANDLE_LOAD_COMMAND(LC_DYLD_EXPORTS_TRIE, 0x80000033u, linkedit_data_command) +HANDLE_LOAD_COMMAND(LC_DYLD_CHAINED_FIXUPS, 0x80000034u, linkedit_data_command) +HANDLE_LOAD_COMMAND(LC_FILESET_ENTRY, 0x80000035u, fileset_entry_command) +HANDLE_LOAD_COMMAND(LC_ATOM_INFO, 0x00000036u, linkedit_data_command) + +#endif + +#ifdef LOAD_COMMAND_STRUCT + +LOAD_COMMAND_STRUCT(dyld_info_command) +LOAD_COMMAND_STRUCT(dylib_command) +LOAD_COMMAND_STRUCT(dylinker_command) +LOAD_COMMAND_STRUCT(dysymtab_command) +LOAD_COMMAND_STRUCT(encryption_info_command) +LOAD_COMMAND_STRUCT(encryption_info_command_64) +LOAD_COMMAND_STRUCT(entry_point_command) +LOAD_COMMAND_STRUCT(fvmfile_command) +LOAD_COMMAND_STRUCT(fvmlib_command) +LOAD_COMMAND_STRUCT(ident_command) +LOAD_COMMAND_STRUCT(linkedit_data_command) +LOAD_COMMAND_STRUCT(linker_option_command) +LOAD_COMMAND_STRUCT(load_command) +LOAD_COMMAND_STRUCT(prebind_cksum_command) +LOAD_COMMAND_STRUCT(prebound_dylib_command) +LOAD_COMMAND_STRUCT(routines_command) +LOAD_COMMAND_STRUCT(routines_command_64) +LOAD_COMMAND_STRUCT(rpath_command) +LOAD_COMMAND_STRUCT(segment_command) +LOAD_COMMAND_STRUCT(segment_command_64) +LOAD_COMMAND_STRUCT(source_version_command) +LOAD_COMMAND_STRUCT(sub_client_command) +LOAD_COMMAND_STRUCT(sub_framework_command) +LOAD_COMMAND_STRUCT(sub_library_command) +LOAD_COMMAND_STRUCT(sub_umbrella_command) +LOAD_COMMAND_STRUCT(symseg_command) +LOAD_COMMAND_STRUCT(symtab_command) +LOAD_COMMAND_STRUCT(thread_command) +LOAD_COMMAND_STRUCT(twolevel_hints_command) +LOAD_COMMAND_STRUCT(uuid_command) +LOAD_COMMAND_STRUCT(version_min_command) +LOAD_COMMAND_STRUCT(note_command) +LOAD_COMMAND_STRUCT(build_version_command) +LOAD_COMMAND_STRUCT(fileset_entry_command) + +#endif + +#undef HANDLE_LOAD_COMMAND +#undef LOAD_COMMAND_STRUCT diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/MachO.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/MachO.h new file mode 100644 index 00000000000..35b6bce574b --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/MachO.h @@ -0,0 +1,2424 @@ +//===-- llvm/BinaryFormat/MachO.h - The MachO file format -------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file defines manifest constants for the MachO object file format. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_BINARYFORMAT_MACHO_H +#define LLVM_BINARYFORMAT_MACHO_H + +#include "llvm/Support/Compiler.h" +#include "llvm/Support/DataTypes.h" +#include "llvm/Support/Error.h" +#include "llvm/Support/SwapByteOrder.h" + +namespace llvm { + +class Triple; + +namespace MachO { +// Enums from +enum : uint32_t { + // Constants for the "magic" field in llvm::MachO::mach_header and + // llvm::MachO::mach_header_64 + MH_MAGIC = 0xFEEDFACEu, + MH_CIGAM = 0xCEFAEDFEu, + MH_MAGIC_64 = 0xFEEDFACFu, + MH_CIGAM_64 = 0xCFFAEDFEu, + FAT_MAGIC = 0xCAFEBABEu, + FAT_CIGAM = 0xBEBAFECAu, + FAT_MAGIC_64 = 0xCAFEBABFu, + FAT_CIGAM_64 = 0xBFBAFECAu +}; + +enum HeaderFileType { + // Constants for the "filetype" field in llvm::MachO::mach_header and + // llvm::MachO::mach_header_64 + MH_OBJECT = 0x1u, + MH_EXECUTE = 0x2u, + MH_FVMLIB = 0x3u, + MH_CORE = 0x4u, + MH_PRELOAD = 0x5u, + MH_DYLIB = 0x6u, + MH_DYLINKER = 0x7u, + MH_BUNDLE = 0x8u, + MH_DYLIB_STUB = 0x9u, + MH_DSYM = 0xAu, + MH_KEXT_BUNDLE = 0xBu, + MH_FILESET = 0xCu, +}; + +enum { + // Constant bits for the "flags" field in llvm::MachO::mach_header and + // llvm::MachO::mach_header_64 + MH_NOUNDEFS = 0x00000001u, + MH_INCRLINK = 0x00000002u, + MH_DYLDLINK = 0x00000004u, + MH_BINDATLOAD = 0x00000008u, + MH_PREBOUND = 0x00000010u, + MH_SPLIT_SEGS = 0x00000020u, + MH_LAZY_INIT = 0x00000040u, + MH_TWOLEVEL = 0x00000080u, + MH_FORCE_FLAT = 0x00000100u, + MH_NOMULTIDEFS = 0x00000200u, + MH_NOFIXPREBINDING = 0x00000400u, + MH_PREBINDABLE = 0x00000800u, + MH_ALLMODSBOUND = 0x00001000u, + MH_SUBSECTIONS_VIA_SYMBOLS = 0x00002000u, + MH_CANONICAL = 0x00004000u, + MH_WEAK_DEFINES = 0x00008000u, + MH_BINDS_TO_WEAK = 0x00010000u, + MH_ALLOW_STACK_EXECUTION = 0x00020000u, + MH_ROOT_SAFE = 0x00040000u, + MH_SETUID_SAFE = 0x00080000u, + MH_NO_REEXPORTED_DYLIBS = 0x00100000u, + MH_PIE = 0x00200000u, + MH_DEAD_STRIPPABLE_DYLIB = 0x00400000u, + MH_HAS_TLV_DESCRIPTORS = 0x00800000u, + MH_NO_HEAP_EXECUTION = 0x01000000u, + MH_APP_EXTENSION_SAFE = 0x02000000u, + MH_NLIST_OUTOFSYNC_WITH_DYLDINFO = 0x04000000u, + MH_SIM_SUPPORT = 0x08000000u, + MH_DYLIB_IN_CACHE = 0x80000000u, +}; + +enum : uint32_t { + // Flags for the "cmd" field in llvm::MachO::load_command + LC_REQ_DYLD = 0x80000000u +}; + +#define HANDLE_LOAD_COMMAND(LCName, LCValue, LCStruct) LCName = LCValue, + +enum LoadCommandType : uint32_t { +#include "llvm/BinaryFormat/MachO.def" +}; + +#undef HANDLE_LOAD_COMMAND + +enum : uint32_t { + // Constant bits for the "flags" field in llvm::MachO::segment_command + SG_HIGHVM = 0x1u, + SG_FVMLIB = 0x2u, + SG_NORELOC = 0x4u, + SG_PROTECTED_VERSION_1 = 0x8u, + SG_READ_ONLY = 0x10u, + + // Constant masks for the "flags" field in llvm::MachO::section and + // llvm::MachO::section_64 + SECTION_TYPE = 0x000000ffu, // SECTION_TYPE + SECTION_ATTRIBUTES = 0xffffff00u, // SECTION_ATTRIBUTES + SECTION_ATTRIBUTES_USR = 0xff000000u, // SECTION_ATTRIBUTES_USR + SECTION_ATTRIBUTES_SYS = 0x00ffff00u // SECTION_ATTRIBUTES_SYS +}; + +/// These are the section type and attributes fields. A MachO section can +/// have only one Type, but can have any of the attributes specified. +enum SectionType : uint32_t { + // Constant masks for the "flags[7:0]" field in llvm::MachO::section and + // llvm::MachO::section_64 (mask "flags" with SECTION_TYPE) + + /// S_REGULAR - Regular section. + S_REGULAR = 0x00u, + /// S_ZEROFILL - Zero fill on demand section. + S_ZEROFILL = 0x01u, + /// S_CSTRING_LITERALS - Section with literal C strings. + S_CSTRING_LITERALS = 0x02u, + /// S_4BYTE_LITERALS - Section with 4 byte literals. + S_4BYTE_LITERALS = 0x03u, + /// S_8BYTE_LITERALS - Section with 8 byte literals. + S_8BYTE_LITERALS = 0x04u, + /// S_LITERAL_POINTERS - Section with pointers to literals. + S_LITERAL_POINTERS = 0x05u, + /// S_NON_LAZY_SYMBOL_POINTERS - Section with non-lazy symbol pointers. + S_NON_LAZY_SYMBOL_POINTERS = 0x06u, + /// S_LAZY_SYMBOL_POINTERS - Section with lazy symbol pointers. + S_LAZY_SYMBOL_POINTERS = 0x07u, + /// S_SYMBOL_STUBS - Section with symbol stubs, byte size of stub in + /// the Reserved2 field. + S_SYMBOL_STUBS = 0x08u, + /// S_MOD_INIT_FUNC_POINTERS - Section with only function pointers for + /// initialization. + S_MOD_INIT_FUNC_POINTERS = 0x09u, + /// S_MOD_TERM_FUNC_POINTERS - Section with only function pointers for + /// termination. + S_MOD_TERM_FUNC_POINTERS = 0x0au, + /// S_COALESCED - Section contains symbols that are to be coalesced. + S_COALESCED = 0x0bu, + /// S_GB_ZEROFILL - Zero fill on demand section (that can be larger than 4 + /// gigabytes). + S_GB_ZEROFILL = 0x0cu, + /// S_INTERPOSING - Section with only pairs of function pointers for + /// interposing. + S_INTERPOSING = 0x0du, + /// S_16BYTE_LITERALS - Section with only 16 byte literals. + S_16BYTE_LITERALS = 0x0eu, + /// S_DTRACE_DOF - Section contains DTrace Object Format. + S_DTRACE_DOF = 0x0fu, + /// S_LAZY_DYLIB_SYMBOL_POINTERS - Section with lazy symbol pointers to + /// lazy loaded dylibs. + S_LAZY_DYLIB_SYMBOL_POINTERS = 0x10u, + /// S_THREAD_LOCAL_REGULAR - Thread local data section. + S_THREAD_LOCAL_REGULAR = 0x11u, + /// S_THREAD_LOCAL_ZEROFILL - Thread local zerofill section. + S_THREAD_LOCAL_ZEROFILL = 0x12u, + /// S_THREAD_LOCAL_VARIABLES - Section with thread local variable + /// structure data. + S_THREAD_LOCAL_VARIABLES = 0x13u, + /// S_THREAD_LOCAL_VARIABLE_POINTERS - Section with pointers to thread + /// local structures. + S_THREAD_LOCAL_VARIABLE_POINTERS = 0x14u, + /// S_THREAD_LOCAL_INIT_FUNCTION_POINTERS - Section with thread local + /// variable initialization pointers to functions. + S_THREAD_LOCAL_INIT_FUNCTION_POINTERS = 0x15u, + /// S_INIT_FUNC_OFFSETS - Section with 32-bit offsets to initializer + /// functions. + S_INIT_FUNC_OFFSETS = 0x16u, + + LAST_KNOWN_SECTION_TYPE = S_INIT_FUNC_OFFSETS +}; + +enum : uint32_t { + // Constant masks for the "flags[31:24]" field in llvm::MachO::section and + // llvm::MachO::section_64 (mask "flags" with SECTION_ATTRIBUTES_USR) + + /// S_ATTR_PURE_INSTRUCTIONS - Section contains only true machine + /// instructions. + S_ATTR_PURE_INSTRUCTIONS = 0x80000000u, + /// S_ATTR_NO_TOC - Section contains coalesced symbols that are not to be + /// in a ranlib table of contents. + S_ATTR_NO_TOC = 0x40000000u, + /// S_ATTR_STRIP_STATIC_SYMS - Ok to strip static symbols in this section + /// in files with the MY_DYLDLINK flag. + S_ATTR_STRIP_STATIC_SYMS = 0x20000000u, + /// S_ATTR_NO_DEAD_STRIP - No dead stripping. + S_ATTR_NO_DEAD_STRIP = 0x10000000u, + /// S_ATTR_LIVE_SUPPORT - Blocks are live if they reference live blocks. + S_ATTR_LIVE_SUPPORT = 0x08000000u, + /// S_ATTR_SELF_MODIFYING_CODE - Used with i386 code stubs written on by + /// dyld. + S_ATTR_SELF_MODIFYING_CODE = 0x04000000u, + /// S_ATTR_DEBUG - A debug section. + S_ATTR_DEBUG = 0x02000000u, + + // Constant masks for the "flags[23:8]" field in llvm::MachO::section and + // llvm::MachO::section_64 (mask "flags" with SECTION_ATTRIBUTES_SYS) + + /// S_ATTR_SOME_INSTRUCTIONS - Section contains some machine instructions. + S_ATTR_SOME_INSTRUCTIONS = 0x00000400u, + /// S_ATTR_EXT_RELOC - Section has external relocation entries. + S_ATTR_EXT_RELOC = 0x00000200u, + /// S_ATTR_LOC_RELOC - Section has local relocation entries. + S_ATTR_LOC_RELOC = 0x00000100u, + + // Constant masks for the value of an indirect symbol in an indirect + // symbol table + INDIRECT_SYMBOL_LOCAL = 0x80000000u, + INDIRECT_SYMBOL_ABS = 0x40000000u +}; + +enum DataRegionType { + // Constants for the "kind" field in a data_in_code_entry structure + DICE_KIND_DATA = 1u, + DICE_KIND_JUMP_TABLE8 = 2u, + DICE_KIND_JUMP_TABLE16 = 3u, + DICE_KIND_JUMP_TABLE32 = 4u, + DICE_KIND_ABS_JUMP_TABLE32 = 5u +}; + +enum RebaseType { + REBASE_TYPE_POINTER = 1u, + REBASE_TYPE_TEXT_ABSOLUTE32 = 2u, + REBASE_TYPE_TEXT_PCREL32 = 3u +}; + +enum { REBASE_OPCODE_MASK = 0xF0u, REBASE_IMMEDIATE_MASK = 0x0Fu }; + +enum RebaseOpcode { + REBASE_OPCODE_DONE = 0x00u, + REBASE_OPCODE_SET_TYPE_IMM = 0x10u, + REBASE_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB = 0x20u, + REBASE_OPCODE_ADD_ADDR_ULEB = 0x30u, + REBASE_OPCODE_ADD_ADDR_IMM_SCALED = 0x40u, + REBASE_OPCODE_DO_REBASE_IMM_TIMES = 0x50u, + REBASE_OPCODE_DO_REBASE_ULEB_TIMES = 0x60u, + REBASE_OPCODE_DO_REBASE_ADD_ADDR_ULEB = 0x70u, + REBASE_OPCODE_DO_REBASE_ULEB_TIMES_SKIPPING_ULEB = 0x80u +}; + +enum BindType { + BIND_TYPE_POINTER = 1u, + BIND_TYPE_TEXT_ABSOLUTE32 = 2u, + BIND_TYPE_TEXT_PCREL32 = 3u +}; + +enum BindSpecialDylib { + BIND_SPECIAL_DYLIB_SELF = 0, + BIND_SPECIAL_DYLIB_MAIN_EXECUTABLE = -1, + BIND_SPECIAL_DYLIB_FLAT_LOOKUP = -2, + BIND_SPECIAL_DYLIB_WEAK_LOOKUP = -3 +}; + +enum { + BIND_SYMBOL_FLAGS_WEAK_IMPORT = 0x1u, + BIND_SYMBOL_FLAGS_NON_WEAK_DEFINITION = 0x8u, + + BIND_OPCODE_MASK = 0xF0u, + BIND_IMMEDIATE_MASK = 0x0Fu +}; + +enum BindOpcode { + BIND_OPCODE_DONE = 0x00u, + BIND_OPCODE_SET_DYLIB_ORDINAL_IMM = 0x10u, + BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB = 0x20u, + BIND_OPCODE_SET_DYLIB_SPECIAL_IMM = 0x30u, + BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM = 0x40u, + BIND_OPCODE_SET_TYPE_IMM = 0x50u, + BIND_OPCODE_SET_ADDEND_SLEB = 0x60u, + BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB = 0x70u, + BIND_OPCODE_ADD_ADDR_ULEB = 0x80u, + BIND_OPCODE_DO_BIND = 0x90u, + BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB = 0xA0u, + BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED = 0xB0u, + BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB = 0xC0u +}; + +enum { + EXPORT_SYMBOL_FLAGS_KIND_MASK = 0x03u, + EXPORT_SYMBOL_FLAGS_WEAK_DEFINITION = 0x04u, + EXPORT_SYMBOL_FLAGS_REEXPORT = 0x08u, + EXPORT_SYMBOL_FLAGS_STUB_AND_RESOLVER = 0x10u +}; + +enum ExportSymbolKind { + EXPORT_SYMBOL_FLAGS_KIND_REGULAR = 0x00u, + EXPORT_SYMBOL_FLAGS_KIND_THREAD_LOCAL = 0x01u, + EXPORT_SYMBOL_FLAGS_KIND_ABSOLUTE = 0x02u +}; + +enum { + // Constant masks for the "n_type" field in llvm::MachO::nlist and + // llvm::MachO::nlist_64 + N_STAB = 0xe0, + N_PEXT = 0x10, + N_TYPE = 0x0e, + N_EXT = 0x01 +}; + +enum NListType : uint8_t { + // Constants for the "n_type & N_TYPE" llvm::MachO::nlist and + // llvm::MachO::nlist_64 + N_UNDF = 0x0u, + N_ABS = 0x2u, + N_SECT = 0xeu, + N_PBUD = 0xcu, + N_INDR = 0xau +}; + +enum SectionOrdinal { + // Constants for the "n_sect" field in llvm::MachO::nlist and + // llvm::MachO::nlist_64 + NO_SECT = 0u, + MAX_SECT = 0xffu +}; + +enum { + // Constant masks for the "n_desc" field in llvm::MachO::nlist and + // llvm::MachO::nlist_64 + // The low 3 bits are the for the REFERENCE_TYPE. + REFERENCE_TYPE = 0x7, + REFERENCE_FLAG_UNDEFINED_NON_LAZY = 0, + REFERENCE_FLAG_UNDEFINED_LAZY = 1, + REFERENCE_FLAG_DEFINED = 2, + REFERENCE_FLAG_PRIVATE_DEFINED = 3, + REFERENCE_FLAG_PRIVATE_UNDEFINED_NON_LAZY = 4, + REFERENCE_FLAG_PRIVATE_UNDEFINED_LAZY = 5, + // Flag bits (some overlap with the library ordinal bits). + N_ARM_THUMB_DEF = 0x0008u, + REFERENCED_DYNAMICALLY = 0x0010u, + N_NO_DEAD_STRIP = 0x0020u, + N_WEAK_REF = 0x0040u, + N_WEAK_DEF = 0x0080u, + N_SYMBOL_RESOLVER = 0x0100u, + N_ALT_ENTRY = 0x0200u, + N_COLD_FUNC = 0x0400u, + // For undefined symbols coming from libraries, see GET_LIBRARY_ORDINAL() + // as these are in the top 8 bits. + SELF_LIBRARY_ORDINAL = 0x0, + MAX_LIBRARY_ORDINAL = 0xfd, + DYNAMIC_LOOKUP_ORDINAL = 0xfe, + EXECUTABLE_ORDINAL = 0xff +}; + +enum StabType { + // Constant values for the "n_type" field in llvm::MachO::nlist and + // llvm::MachO::nlist_64 when "(n_type & N_STAB) != 0" + N_GSYM = 0x20u, + N_FNAME = 0x22u, + N_FUN = 0x24u, + N_STSYM = 0x26u, + N_LCSYM = 0x28u, + N_BNSYM = 0x2Eu, + N_PC = 0x30u, + N_AST = 0x32u, + N_OPT = 0x3Cu, + N_RSYM = 0x40u, + N_SLINE = 0x44u, + N_ENSYM = 0x4Eu, + N_SSYM = 0x60u, + N_SO = 0x64u, + N_OSO = 0x66u, + N_LSYM = 0x80u, + N_BINCL = 0x82u, + N_SOL = 0x84u, + N_PARAMS = 0x86u, + N_VERSION = 0x88u, + N_OLEVEL = 0x8Au, + N_PSYM = 0xA0u, + N_EINCL = 0xA2u, + N_ENTRY = 0xA4u, + N_LBRAC = 0xC0u, + N_EXCL = 0xC2u, + N_RBRAC = 0xE0u, + N_BCOMM = 0xE2u, + N_ECOMM = 0xE4u, + N_ECOML = 0xE8u, + N_LENG = 0xFEu +}; + +enum : uint32_t { + // Constant values for the r_symbolnum field in an + // llvm::MachO::relocation_info structure when r_extern is 0. + R_ABS = 0, + + // Constant bits for the r_address field in an + // llvm::MachO::relocation_info structure. + R_SCATTERED = 0x80000000 +}; + +enum RelocationInfoType { + // Constant values for the r_type field in an + // llvm::MachO::relocation_info or llvm::MachO::scattered_relocation_info + // structure. + GENERIC_RELOC_INVALID = 0xff, + GENERIC_RELOC_VANILLA = 0, + GENERIC_RELOC_PAIR = 1, + GENERIC_RELOC_SECTDIFF = 2, + GENERIC_RELOC_PB_LA_PTR = 3, + GENERIC_RELOC_LOCAL_SECTDIFF = 4, + GENERIC_RELOC_TLV = 5, + + // Constant values for the r_type field in a PowerPC architecture + // llvm::MachO::relocation_info or llvm::MachO::scattered_relocation_info + // structure. + PPC_RELOC_VANILLA = GENERIC_RELOC_VANILLA, + PPC_RELOC_PAIR = GENERIC_RELOC_PAIR, + PPC_RELOC_BR14 = 2, + PPC_RELOC_BR24 = 3, + PPC_RELOC_HI16 = 4, + PPC_RELOC_LO16 = 5, + PPC_RELOC_HA16 = 6, + PPC_RELOC_LO14 = 7, + PPC_RELOC_SECTDIFF = 8, + PPC_RELOC_PB_LA_PTR = 9, + PPC_RELOC_HI16_SECTDIFF = 10, + PPC_RELOC_LO16_SECTDIFF = 11, + PPC_RELOC_HA16_SECTDIFF = 12, + PPC_RELOC_JBSR = 13, + PPC_RELOC_LO14_SECTDIFF = 14, + PPC_RELOC_LOCAL_SECTDIFF = 15, + + // Constant values for the r_type field in an ARM architecture + // llvm::MachO::relocation_info or llvm::MachO::scattered_relocation_info + // structure. + ARM_RELOC_VANILLA = GENERIC_RELOC_VANILLA, + ARM_RELOC_PAIR = GENERIC_RELOC_PAIR, + ARM_RELOC_SECTDIFF = GENERIC_RELOC_SECTDIFF, + ARM_RELOC_LOCAL_SECTDIFF = 3, + ARM_RELOC_PB_LA_PTR = 4, + ARM_RELOC_BR24 = 5, + ARM_THUMB_RELOC_BR22 = 6, + ARM_THUMB_32BIT_BRANCH = 7, // obsolete + ARM_RELOC_HALF = 8, + ARM_RELOC_HALF_SECTDIFF = 9, + + // Constant values for the r_type field in an ARM64 architecture + // llvm::MachO::relocation_info or llvm::MachO::scattered_relocation_info + // structure. + + // For pointers. + ARM64_RELOC_UNSIGNED = 0, + // Must be followed by an ARM64_RELOC_UNSIGNED + ARM64_RELOC_SUBTRACTOR = 1, + // A B/BL instruction with 26-bit displacement. + ARM64_RELOC_BRANCH26 = 2, + // PC-rel distance to page of target. + ARM64_RELOC_PAGE21 = 3, + // Offset within page, scaled by r_length. + ARM64_RELOC_PAGEOFF12 = 4, + // PC-rel distance to page of GOT slot. + ARM64_RELOC_GOT_LOAD_PAGE21 = 5, + // Offset within page of GOT slot, scaled by r_length. + ARM64_RELOC_GOT_LOAD_PAGEOFF12 = 6, + // For pointers to GOT slots. + ARM64_RELOC_POINTER_TO_GOT = 7, + // PC-rel distance to page of TLVP slot. + ARM64_RELOC_TLVP_LOAD_PAGE21 = 8, + // Offset within page of TLVP slot, scaled by r_length. + ARM64_RELOC_TLVP_LOAD_PAGEOFF12 = 9, + // Must be followed by ARM64_RELOC_PAGE21 or ARM64_RELOC_PAGEOFF12. + ARM64_RELOC_ADDEND = 10, + // An authenticated pointer. + ARM64_RELOC_AUTHENTICATED_POINTER = 11, + + // Constant values for the r_type field in an x86_64 architecture + // llvm::MachO::relocation_info or llvm::MachO::scattered_relocation_info + // structure + X86_64_RELOC_UNSIGNED = 0, + X86_64_RELOC_SIGNED = 1, + X86_64_RELOC_BRANCH = 2, + X86_64_RELOC_GOT_LOAD = 3, + X86_64_RELOC_GOT = 4, + X86_64_RELOC_SUBTRACTOR = 5, + X86_64_RELOC_SIGNED_1 = 6, + X86_64_RELOC_SIGNED_2 = 7, + X86_64_RELOC_SIGNED_4 = 8, + X86_64_RELOC_TLV = 9 +}; + +// Values for segment_command.initprot. +// From +enum { VM_PROT_READ = 0x1, VM_PROT_WRITE = 0x2, VM_PROT_EXECUTE = 0x4 }; + +// Values for platform field in build_version_command. +enum PlatformType { + PLATFORM_UNKNOWN = 0, + PLATFORM_MACOS = 1, + PLATFORM_IOS = 2, + PLATFORM_TVOS = 3, + PLATFORM_WATCHOS = 4, + PLATFORM_BRIDGEOS = 5, + PLATFORM_MACCATALYST = 6, + PLATFORM_IOSSIMULATOR = 7, + PLATFORM_TVOSSIMULATOR = 8, + PLATFORM_WATCHOSSIMULATOR = 9, + PLATFORM_DRIVERKIT = 10, +}; + +// Values for tools enum in build_tool_version. +enum { TOOL_CLANG = 1, TOOL_SWIFT = 2, TOOL_LD = 3, TOOL_LLD = 4 }; + +// Structs from + +struct mach_header { + uint32_t magic; + uint32_t cputype; + uint32_t cpusubtype; + uint32_t filetype; + uint32_t ncmds; + uint32_t sizeofcmds; + uint32_t flags; +}; + +struct mach_header_64 { + uint32_t magic; + uint32_t cputype; + uint32_t cpusubtype; + uint32_t filetype; + uint32_t ncmds; + uint32_t sizeofcmds; + uint32_t flags; + uint32_t reserved; +}; + +struct load_command { + uint32_t cmd; + uint32_t cmdsize; +}; + +struct segment_command { + uint32_t cmd; + uint32_t cmdsize; + char segname[16]; + uint32_t vmaddr; + uint32_t vmsize; + uint32_t fileoff; + uint32_t filesize; + uint32_t maxprot; + uint32_t initprot; + uint32_t nsects; + uint32_t flags; +}; + +struct segment_command_64 { + uint32_t cmd; + uint32_t cmdsize; + char segname[16]; + uint64_t vmaddr; + uint64_t vmsize; + uint64_t fileoff; + uint64_t filesize; + uint32_t maxprot; + uint32_t initprot; + uint32_t nsects; + uint32_t flags; +}; + +struct section { + char sectname[16]; + char segname[16]; + uint32_t addr; + uint32_t size; + uint32_t offset; + uint32_t align; + uint32_t reloff; + uint32_t nreloc; + uint32_t flags; + uint32_t reserved1; + uint32_t reserved2; +}; + +struct section_64 { + char sectname[16]; + char segname[16]; + uint64_t addr; + uint64_t size; + uint32_t offset; + uint32_t align; + uint32_t reloff; + uint32_t nreloc; + uint32_t flags; + uint32_t reserved1; + uint32_t reserved2; + uint32_t reserved3; +}; + +inline bool isVirtualSection(uint8_t type) { + return (type == MachO::S_ZEROFILL || type == MachO::S_GB_ZEROFILL || + type == MachO::S_THREAD_LOCAL_ZEROFILL); +} + +struct fvmlib { + uint32_t name; + uint32_t minor_version; + uint32_t header_addr; +}; + +// The fvmlib_command is obsolete and no longer supported. +struct fvmlib_command { + uint32_t cmd; + uint32_t cmdsize; + struct fvmlib fvmlib; +}; + +struct dylib { + uint32_t name; + uint32_t timestamp; + uint32_t current_version; + uint32_t compatibility_version; +}; + +struct dylib_command { + uint32_t cmd; + uint32_t cmdsize; + struct dylib dylib; +}; + +struct sub_framework_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t umbrella; +}; + +struct sub_client_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t client; +}; + +struct sub_umbrella_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t sub_umbrella; +}; + +struct sub_library_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t sub_library; +}; + +// The prebound_dylib_command is obsolete and no longer supported. +struct prebound_dylib_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t name; + uint32_t nmodules; + uint32_t linked_modules; +}; + +struct dylinker_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t name; +}; + +struct thread_command { + uint32_t cmd; + uint32_t cmdsize; +}; + +struct routines_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t init_address; + uint32_t init_module; + uint32_t reserved1; + uint32_t reserved2; + uint32_t reserved3; + uint32_t reserved4; + uint32_t reserved5; + uint32_t reserved6; +}; + +struct routines_command_64 { + uint32_t cmd; + uint32_t cmdsize; + uint64_t init_address; + uint64_t init_module; + uint64_t reserved1; + uint64_t reserved2; + uint64_t reserved3; + uint64_t reserved4; + uint64_t reserved5; + uint64_t reserved6; +}; + +struct symtab_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t symoff; + uint32_t nsyms; + uint32_t stroff; + uint32_t strsize; +}; + +struct dysymtab_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t ilocalsym; + uint32_t nlocalsym; + uint32_t iextdefsym; + uint32_t nextdefsym; + uint32_t iundefsym; + uint32_t nundefsym; + uint32_t tocoff; + uint32_t ntoc; + uint32_t modtaboff; + uint32_t nmodtab; + uint32_t extrefsymoff; + uint32_t nextrefsyms; + uint32_t indirectsymoff; + uint32_t nindirectsyms; + uint32_t extreloff; + uint32_t nextrel; + uint32_t locreloff; + uint32_t nlocrel; +}; + +struct dylib_table_of_contents { + uint32_t symbol_index; + uint32_t module_index; +}; + +struct dylib_module { + uint32_t module_name; + uint32_t iextdefsym; + uint32_t nextdefsym; + uint32_t irefsym; + uint32_t nrefsym; + uint32_t ilocalsym; + uint32_t nlocalsym; + uint32_t iextrel; + uint32_t nextrel; + uint32_t iinit_iterm; + uint32_t ninit_nterm; + uint32_t objc_module_info_addr; + uint32_t objc_module_info_size; +}; + +struct dylib_module_64 { + uint32_t module_name; + uint32_t iextdefsym; + uint32_t nextdefsym; + uint32_t irefsym; + uint32_t nrefsym; + uint32_t ilocalsym; + uint32_t nlocalsym; + uint32_t iextrel; + uint32_t nextrel; + uint32_t iinit_iterm; + uint32_t ninit_nterm; + uint32_t objc_module_info_size; + uint64_t objc_module_info_addr; +}; + +struct dylib_reference { + uint32_t isym : 24, flags : 8; +}; + +// The twolevel_hints_command is obsolete and no longer supported. +struct twolevel_hints_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t offset; + uint32_t nhints; +}; + +// The twolevel_hints_command is obsolete and no longer supported. +struct twolevel_hint { + uint32_t isub_image : 8, itoc : 24; +}; + +// The prebind_cksum_command is obsolete and no longer supported. +struct prebind_cksum_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t cksum; +}; + +struct uuid_command { + uint32_t cmd; + uint32_t cmdsize; + uint8_t uuid[16]; +}; + +struct rpath_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t path; +}; + +struct linkedit_data_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t dataoff; + uint32_t datasize; +}; + +struct data_in_code_entry { + uint32_t offset; + uint16_t length; + uint16_t kind; +}; + +struct source_version_command { + uint32_t cmd; + uint32_t cmdsize; + uint64_t version; +}; + +struct encryption_info_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t cryptoff; + uint32_t cryptsize; + uint32_t cryptid; +}; + +struct encryption_info_command_64 { + uint32_t cmd; + uint32_t cmdsize; + uint32_t cryptoff; + uint32_t cryptsize; + uint32_t cryptid; + uint32_t pad; +}; + +struct version_min_command { + uint32_t cmd; // LC_VERSION_MIN_MACOSX or + // LC_VERSION_MIN_IPHONEOS + uint32_t cmdsize; // sizeof(struct version_min_command) + uint32_t version; // X.Y.Z is encoded in nibbles xxxx.yy.zz + uint32_t sdk; // X.Y.Z is encoded in nibbles xxxx.yy.zz +}; + +struct note_command { + uint32_t cmd; // LC_NOTE + uint32_t cmdsize; // sizeof(struct note_command) + char data_owner[16]; // owner name for this LC_NOTE + uint64_t offset; // file offset of this data + uint64_t size; // length of data region +}; + +struct build_tool_version { + uint32_t tool; // enum for the tool + uint32_t version; // version of the tool +}; + +struct build_version_command { + uint32_t cmd; // LC_BUILD_VERSION + uint32_t cmdsize; // sizeof(struct build_version_command) + + // ntools * sizeof(struct build_tool_version) + uint32_t platform; // platform + uint32_t minos; // X.Y.Z is encoded in nibbles xxxx.yy.zz + uint32_t sdk; // X.Y.Z is encoded in nibbles xxxx.yy.zz + uint32_t ntools; // number of tool entries following this +}; + +struct dyld_env_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t name; +}; + +struct dyld_info_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t rebase_off; + uint32_t rebase_size; + uint32_t bind_off; + uint32_t bind_size; + uint32_t weak_bind_off; + uint32_t weak_bind_size; + uint32_t lazy_bind_off; + uint32_t lazy_bind_size; + uint32_t export_off; + uint32_t export_size; +}; + +struct linker_option_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t count; +}; + +struct fileset_entry_command { + uint32_t cmd; + uint32_t cmdsize; + uint64_t vmaddr; + uint64_t fileoff; + uint32_t entry_id; +}; + +// The symseg_command is obsolete and no longer supported. +struct symseg_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t offset; + uint32_t size; +}; + +// The ident_command is obsolete and no longer supported. +struct ident_command { + uint32_t cmd; + uint32_t cmdsize; +}; + +// The fvmfile_command is obsolete and no longer supported. +struct fvmfile_command { + uint32_t cmd; + uint32_t cmdsize; + uint32_t name; + uint32_t header_addr; +}; + +struct tlv_descriptor_32 { + uint32_t thunk; + uint32_t key; + uint32_t offset; +}; + +struct tlv_descriptor_64 { + uint64_t thunk; + uint64_t key; + uint64_t offset; +}; + +struct tlv_descriptor { + uintptr_t thunk; + uintptr_t key; + uintptr_t offset; +}; + +struct entry_point_command { + uint32_t cmd; + uint32_t cmdsize; + uint64_t entryoff; + uint64_t stacksize; +}; + +// Structs from +struct fat_header { + uint32_t magic; + uint32_t nfat_arch; +}; + +struct fat_arch { + uint32_t cputype; + uint32_t cpusubtype; + uint32_t offset; + uint32_t size; + uint32_t align; +}; + +struct fat_arch_64 { + uint32_t cputype; + uint32_t cpusubtype; + uint64_t offset; + uint64_t size; + uint32_t align; + uint32_t reserved; +}; + +// Structs from +struct relocation_info { + int32_t r_address; + uint32_t r_symbolnum : 24, r_pcrel : 1, r_length : 2, r_extern : 1, + r_type : 4; +}; + +struct scattered_relocation_info { +#if defined(BYTE_ORDER) && defined(BIG_ENDIAN) && (BYTE_ORDER == BIG_ENDIAN) + uint32_t r_scattered : 1, r_pcrel : 1, r_length : 2, r_type : 4, + r_address : 24; +#else + uint32_t r_address : 24, r_type : 4, r_length : 2, r_pcrel : 1, + r_scattered : 1; +#endif + int32_t r_value; +}; + +// Structs NOT from , but that make LLVM's life easier +struct any_relocation_info { + uint32_t r_word0, r_word1; +}; + +// Structs from +struct nlist_base { + uint32_t n_strx; + uint8_t n_type; + uint8_t n_sect; + uint16_t n_desc; +}; + +struct nlist { + uint32_t n_strx; + uint8_t n_type; + uint8_t n_sect; + int16_t n_desc; + uint32_t n_value; +}; + +struct nlist_64 { + uint32_t n_strx; + uint8_t n_type; + uint8_t n_sect; + uint16_t n_desc; + uint64_t n_value; +}; + +// Values for dyld_chained_fixups_header::imports_format. +enum ChainedImportFormat { + DYLD_CHAINED_IMPORT = 1, + DYLD_CHAINED_IMPORT_ADDEND = 2, + DYLD_CHAINED_IMPORT_ADDEND64 = 3, +}; + +// Values for dyld_chained_fixups_header::symbols_format. +enum { + DYLD_CHAINED_SYMBOL_UNCOMPRESSED = 0, + DYLD_CHAINED_SYMBOL_ZLIB = 1, +}; + +// Values for dyld_chained_starts_in_segment::page_start. +enum { + DYLD_CHAINED_PTR_START_NONE = 0xFFFF, + DYLD_CHAINED_PTR_START_MULTI = 0x8000, // page which has multiple starts + DYLD_CHAINED_PTR_START_LAST = 0x8000, // last chain_start for a given page +}; + +// Values for dyld_chained_starts_in_segment::pointer_format. +enum { + DYLD_CHAINED_PTR_ARM64E = 1, + DYLD_CHAINED_PTR_64 = 2, + DYLD_CHAINED_PTR_32 = 3, + DYLD_CHAINED_PTR_32_CACHE = 4, + DYLD_CHAINED_PTR_32_FIRMWARE = 5, + DYLD_CHAINED_PTR_64_OFFSET = 6, + DYLD_CHAINED_PTR_ARM64E_KERNEL = 7, + DYLD_CHAINED_PTR_64_KERNEL_CACHE = 8, + DYLD_CHAINED_PTR_ARM64E_USERLAND = 9, + DYLD_CHAINED_PTR_ARM64E_FIRMWARE = 10, + DYLD_CHAINED_PTR_X86_64_KERNEL_CACHE = 11, + DYLD_CHAINED_PTR_ARM64E_USERLAND24 = 12, +}; + +/// Structs for dyld chained fixups. +/// dyld_chained_fixups_header is the data pointed to by LC_DYLD_CHAINED_FIXUPS +/// load command. +struct dyld_chained_fixups_header { + uint32_t fixups_version; ///< 0 + uint32_t starts_offset; ///< Offset of dyld_chained_starts_in_image. + uint32_t imports_offset; ///< Offset of imports table in chain_data. + uint32_t symbols_offset; ///< Offset of symbol strings in chain_data. + uint32_t imports_count; ///< Number of imported symbol names. + uint32_t imports_format; ///< DYLD_CHAINED_IMPORT* + uint32_t symbols_format; ///< 0 => uncompressed, 1 => zlib compressed +}; + +/// dyld_chained_starts_in_image is embedded in LC_DYLD_CHAINED_FIXUPS payload. +/// Each each seg_info_offset entry is the offset into this struct for that +/// segment followed by pool of dyld_chain_starts_in_segment data. +struct dyld_chained_starts_in_image { + uint32_t seg_count; + uint32_t seg_info_offset[1]; +}; + +struct dyld_chained_starts_in_segment { + uint32_t size; ///< Size of this, including chain_starts entries + uint16_t page_size; ///< Page size in bytes (0x1000 or 0x4000) + uint16_t pointer_format; ///< DYLD_CHAINED_PTR* + uint64_t segment_offset; ///< VM offset from the __TEXT segment + uint32_t max_valid_pointer; ///< Values beyond this are not pointers on 32-bit + uint16_t page_count; ///< Length of the page_start array + uint16_t page_start[1]; ///< Page offset of first fixup on each page, or + ///< DYLD_CHAINED_PTR_START_NONE if no fixups +}; + +// DYLD_CHAINED_IMPORT +struct dyld_chained_import { + uint32_t lib_ordinal : 8; + uint32_t weak_import : 1; + uint32_t name_offset : 23; +}; + +// DYLD_CHAINED_IMPORT_ADDEND +struct dyld_chained_import_addend { + uint32_t lib_ordinal : 8; + uint32_t weak_import : 1; + uint32_t name_offset : 23; + int32_t addend; +}; + +// DYLD_CHAINED_IMPORT_ADDEND64 +struct dyld_chained_import_addend64 { + uint64_t lib_ordinal : 16; + uint64_t weak_import : 1; + uint64_t reserved : 15; + uint64_t name_offset : 32; + uint64_t addend; +}; + +// The `bind` field (most significant bit) of the encoded fixup determines +// whether it is dyld_chained_ptr_64_bind or dyld_chained_ptr_64_rebase. + +// DYLD_CHAINED_PTR_64/DYLD_CHAINED_PTR_64_OFFSET +struct dyld_chained_ptr_64_bind { + uint64_t ordinal : 24; + uint64_t addend : 8; + uint64_t reserved : 19; + uint64_t next : 12; + uint64_t bind : 1; // set to 1 +}; + +// DYLD_CHAINED_PTR_64/DYLD_CHAINED_PTR_64_OFFSET +struct dyld_chained_ptr_64_rebase { + uint64_t target : 36; + uint64_t high8 : 8; + uint64_t reserved : 7; + uint64_t next : 12; + uint64_t bind : 1; // set to 0 +}; + +// Byte order swapping functions for MachO structs + +inline void swapStruct(fat_header &mh) { + sys::swapByteOrder(mh.magic); + sys::swapByteOrder(mh.nfat_arch); +} + +inline void swapStruct(fat_arch &mh) { + sys::swapByteOrder(mh.cputype); + sys::swapByteOrder(mh.cpusubtype); + sys::swapByteOrder(mh.offset); + sys::swapByteOrder(mh.size); + sys::swapByteOrder(mh.align); +} + +inline void swapStruct(fat_arch_64 &mh) { + sys::swapByteOrder(mh.cputype); + sys::swapByteOrder(mh.cpusubtype); + sys::swapByteOrder(mh.offset); + sys::swapByteOrder(mh.size); + sys::swapByteOrder(mh.align); + sys::swapByteOrder(mh.reserved); +} + +inline void swapStruct(mach_header &mh) { + sys::swapByteOrder(mh.magic); + sys::swapByteOrder(mh.cputype); + sys::swapByteOrder(mh.cpusubtype); + sys::swapByteOrder(mh.filetype); + sys::swapByteOrder(mh.ncmds); + sys::swapByteOrder(mh.sizeofcmds); + sys::swapByteOrder(mh.flags); +} + +inline void swapStruct(mach_header_64 &H) { + sys::swapByteOrder(H.magic); + sys::swapByteOrder(H.cputype); + sys::swapByteOrder(H.cpusubtype); + sys::swapByteOrder(H.filetype); + sys::swapByteOrder(H.ncmds); + sys::swapByteOrder(H.sizeofcmds); + sys::swapByteOrder(H.flags); + sys::swapByteOrder(H.reserved); +} + +inline void swapStruct(load_command &lc) { + sys::swapByteOrder(lc.cmd); + sys::swapByteOrder(lc.cmdsize); +} + +inline void swapStruct(symtab_command &lc) { + sys::swapByteOrder(lc.cmd); + sys::swapByteOrder(lc.cmdsize); + sys::swapByteOrder(lc.symoff); + sys::swapByteOrder(lc.nsyms); + sys::swapByteOrder(lc.stroff); + sys::swapByteOrder(lc.strsize); +} + +inline void swapStruct(segment_command_64 &seg) { + sys::swapByteOrder(seg.cmd); + sys::swapByteOrder(seg.cmdsize); + sys::swapByteOrder(seg.vmaddr); + sys::swapByteOrder(seg.vmsize); + sys::swapByteOrder(seg.fileoff); + sys::swapByteOrder(seg.filesize); + sys::swapByteOrder(seg.maxprot); + sys::swapByteOrder(seg.initprot); + sys::swapByteOrder(seg.nsects); + sys::swapByteOrder(seg.flags); +} + +inline void swapStruct(segment_command &seg) { + sys::swapByteOrder(seg.cmd); + sys::swapByteOrder(seg.cmdsize); + sys::swapByteOrder(seg.vmaddr); + sys::swapByteOrder(seg.vmsize); + sys::swapByteOrder(seg.fileoff); + sys::swapByteOrder(seg.filesize); + sys::swapByteOrder(seg.maxprot); + sys::swapByteOrder(seg.initprot); + sys::swapByteOrder(seg.nsects); + sys::swapByteOrder(seg.flags); +} + +inline void swapStruct(section_64 §) { + sys::swapByteOrder(sect.addr); + sys::swapByteOrder(sect.size); + sys::swapByteOrder(sect.offset); + sys::swapByteOrder(sect.align); + sys::swapByteOrder(sect.reloff); + sys::swapByteOrder(sect.nreloc); + sys::swapByteOrder(sect.flags); + sys::swapByteOrder(sect.reserved1); + sys::swapByteOrder(sect.reserved2); +} + +inline void swapStruct(section §) { + sys::swapByteOrder(sect.addr); + sys::swapByteOrder(sect.size); + sys::swapByteOrder(sect.offset); + sys::swapByteOrder(sect.align); + sys::swapByteOrder(sect.reloff); + sys::swapByteOrder(sect.nreloc); + sys::swapByteOrder(sect.flags); + sys::swapByteOrder(sect.reserved1); + sys::swapByteOrder(sect.reserved2); +} + +inline void swapStruct(dyld_info_command &info) { + sys::swapByteOrder(info.cmd); + sys::swapByteOrder(info.cmdsize); + sys::swapByteOrder(info.rebase_off); + sys::swapByteOrder(info.rebase_size); + sys::swapByteOrder(info.bind_off); + sys::swapByteOrder(info.bind_size); + sys::swapByteOrder(info.weak_bind_off); + sys::swapByteOrder(info.weak_bind_size); + sys::swapByteOrder(info.lazy_bind_off); + sys::swapByteOrder(info.lazy_bind_size); + sys::swapByteOrder(info.export_off); + sys::swapByteOrder(info.export_size); +} + +inline void swapStruct(dylib_command &d) { + sys::swapByteOrder(d.cmd); + sys::swapByteOrder(d.cmdsize); + sys::swapByteOrder(d.dylib.name); + sys::swapByteOrder(d.dylib.timestamp); + sys::swapByteOrder(d.dylib.current_version); + sys::swapByteOrder(d.dylib.compatibility_version); +} + +inline void swapStruct(sub_framework_command &s) { + sys::swapByteOrder(s.cmd); + sys::swapByteOrder(s.cmdsize); + sys::swapByteOrder(s.umbrella); +} + +inline void swapStruct(sub_umbrella_command &s) { + sys::swapByteOrder(s.cmd); + sys::swapByteOrder(s.cmdsize); + sys::swapByteOrder(s.sub_umbrella); +} + +inline void swapStruct(sub_library_command &s) { + sys::swapByteOrder(s.cmd); + sys::swapByteOrder(s.cmdsize); + sys::swapByteOrder(s.sub_library); +} + +inline void swapStruct(sub_client_command &s) { + sys::swapByteOrder(s.cmd); + sys::swapByteOrder(s.cmdsize); + sys::swapByteOrder(s.client); +} + +inline void swapStruct(routines_command &r) { + sys::swapByteOrder(r.cmd); + sys::swapByteOrder(r.cmdsize); + sys::swapByteOrder(r.init_address); + sys::swapByteOrder(r.init_module); + sys::swapByteOrder(r.reserved1); + sys::swapByteOrder(r.reserved2); + sys::swapByteOrder(r.reserved3); + sys::swapByteOrder(r.reserved4); + sys::swapByteOrder(r.reserved5); + sys::swapByteOrder(r.reserved6); +} + +inline void swapStruct(routines_command_64 &r) { + sys::swapByteOrder(r.cmd); + sys::swapByteOrder(r.cmdsize); + sys::swapByteOrder(r.init_address); + sys::swapByteOrder(r.init_module); + sys::swapByteOrder(r.reserved1); + sys::swapByteOrder(r.reserved2); + sys::swapByteOrder(r.reserved3); + sys::swapByteOrder(r.reserved4); + sys::swapByteOrder(r.reserved5); + sys::swapByteOrder(r.reserved6); +} + +inline void swapStruct(thread_command &t) { + sys::swapByteOrder(t.cmd); + sys::swapByteOrder(t.cmdsize); +} + +inline void swapStruct(dylinker_command &d) { + sys::swapByteOrder(d.cmd); + sys::swapByteOrder(d.cmdsize); + sys::swapByteOrder(d.name); +} + +inline void swapStruct(uuid_command &u) { + sys::swapByteOrder(u.cmd); + sys::swapByteOrder(u.cmdsize); +} + +inline void swapStruct(rpath_command &r) { + sys::swapByteOrder(r.cmd); + sys::swapByteOrder(r.cmdsize); + sys::swapByteOrder(r.path); +} + +inline void swapStruct(source_version_command &s) { + sys::swapByteOrder(s.cmd); + sys::swapByteOrder(s.cmdsize); + sys::swapByteOrder(s.version); +} + +inline void swapStruct(entry_point_command &e) { + sys::swapByteOrder(e.cmd); + sys::swapByteOrder(e.cmdsize); + sys::swapByteOrder(e.entryoff); + sys::swapByteOrder(e.stacksize); +} + +inline void swapStruct(encryption_info_command &e) { + sys::swapByteOrder(e.cmd); + sys::swapByteOrder(e.cmdsize); + sys::swapByteOrder(e.cryptoff); + sys::swapByteOrder(e.cryptsize); + sys::swapByteOrder(e.cryptid); +} + +inline void swapStruct(encryption_info_command_64 &e) { + sys::swapByteOrder(e.cmd); + sys::swapByteOrder(e.cmdsize); + sys::swapByteOrder(e.cryptoff); + sys::swapByteOrder(e.cryptsize); + sys::swapByteOrder(e.cryptid); + sys::swapByteOrder(e.pad); +} + +inline void swapStruct(dysymtab_command &dst) { + sys::swapByteOrder(dst.cmd); + sys::swapByteOrder(dst.cmdsize); + sys::swapByteOrder(dst.ilocalsym); + sys::swapByteOrder(dst.nlocalsym); + sys::swapByteOrder(dst.iextdefsym); + sys::swapByteOrder(dst.nextdefsym); + sys::swapByteOrder(dst.iundefsym); + sys::swapByteOrder(dst.nundefsym); + sys::swapByteOrder(dst.tocoff); + sys::swapByteOrder(dst.ntoc); + sys::swapByteOrder(dst.modtaboff); + sys::swapByteOrder(dst.nmodtab); + sys::swapByteOrder(dst.extrefsymoff); + sys::swapByteOrder(dst.nextrefsyms); + sys::swapByteOrder(dst.indirectsymoff); + sys::swapByteOrder(dst.nindirectsyms); + sys::swapByteOrder(dst.extreloff); + sys::swapByteOrder(dst.nextrel); + sys::swapByteOrder(dst.locreloff); + sys::swapByteOrder(dst.nlocrel); +} + +inline void swapStruct(any_relocation_info &reloc) { + sys::swapByteOrder(reloc.r_word0); + sys::swapByteOrder(reloc.r_word1); +} + +inline void swapStruct(nlist_base &S) { + sys::swapByteOrder(S.n_strx); + sys::swapByteOrder(S.n_desc); +} + +inline void swapStruct(nlist &sym) { + sys::swapByteOrder(sym.n_strx); + sys::swapByteOrder(sym.n_desc); + sys::swapByteOrder(sym.n_value); +} + +inline void swapStruct(nlist_64 &sym) { + sys::swapByteOrder(sym.n_strx); + sys::swapByteOrder(sym.n_desc); + sys::swapByteOrder(sym.n_value); +} + +inline void swapStruct(linkedit_data_command &C) { + sys::swapByteOrder(C.cmd); + sys::swapByteOrder(C.cmdsize); + sys::swapByteOrder(C.dataoff); + sys::swapByteOrder(C.datasize); +} + +inline void swapStruct(linker_option_command &C) { + sys::swapByteOrder(C.cmd); + sys::swapByteOrder(C.cmdsize); + sys::swapByteOrder(C.count); +} + +inline void swapStruct(fileset_entry_command &C) { + sys::swapByteOrder(C.cmd); + sys::swapByteOrder(C.cmdsize); + sys::swapByteOrder(C.vmaddr); + sys::swapByteOrder(C.fileoff); + sys::swapByteOrder(C.entry_id); +} + +inline void swapStruct(version_min_command &C) { + sys::swapByteOrder(C.cmd); + sys::swapByteOrder(C.cmdsize); + sys::swapByteOrder(C.version); + sys::swapByteOrder(C.sdk); +} + +inline void swapStruct(note_command &C) { + sys::swapByteOrder(C.cmd); + sys::swapByteOrder(C.cmdsize); + sys::swapByteOrder(C.offset); + sys::swapByteOrder(C.size); +} + +inline void swapStruct(build_version_command &C) { + sys::swapByteOrder(C.cmd); + sys::swapByteOrder(C.cmdsize); + sys::swapByteOrder(C.platform); + sys::swapByteOrder(C.minos); + sys::swapByteOrder(C.sdk); + sys::swapByteOrder(C.ntools); +} + +inline void swapStruct(build_tool_version &C) { + sys::swapByteOrder(C.tool); + sys::swapByteOrder(C.version); +} + +inline void swapStruct(data_in_code_entry &C) { + sys::swapByteOrder(C.offset); + sys::swapByteOrder(C.length); + sys::swapByteOrder(C.kind); +} + +inline void swapStruct(uint32_t &C) { sys::swapByteOrder(C); } + +// The prebind_cksum_command is obsolete and no longer supported. +inline void swapStruct(prebind_cksum_command &C) { + sys::swapByteOrder(C.cmd); + sys::swapByteOrder(C.cmdsize); + sys::swapByteOrder(C.cksum); +} + +// The twolevel_hints_command is obsolete and no longer supported. +inline void swapStruct(twolevel_hints_command &C) { + sys::swapByteOrder(C.cmd); + sys::swapByteOrder(C.cmdsize); + sys::swapByteOrder(C.offset); + sys::swapByteOrder(C.nhints); +} + +// The prebound_dylib_command is obsolete and no longer supported. +inline void swapStruct(prebound_dylib_command &C) { + sys::swapByteOrder(C.cmd); + sys::swapByteOrder(C.cmdsize); + sys::swapByteOrder(C.name); + sys::swapByteOrder(C.nmodules); + sys::swapByteOrder(C.linked_modules); +} + +// The fvmfile_command is obsolete and no longer supported. +inline void swapStruct(fvmfile_command &C) { + sys::swapByteOrder(C.cmd); + sys::swapByteOrder(C.cmdsize); + sys::swapByteOrder(C.name); + sys::swapByteOrder(C.header_addr); +} + +// The symseg_command is obsolete and no longer supported. +inline void swapStruct(symseg_command &C) { + sys::swapByteOrder(C.cmd); + sys::swapByteOrder(C.cmdsize); + sys::swapByteOrder(C.offset); + sys::swapByteOrder(C.size); +} + +// The ident_command is obsolete and no longer supported. +inline void swapStruct(ident_command &C) { + sys::swapByteOrder(C.cmd); + sys::swapByteOrder(C.cmdsize); +} + +inline void swapStruct(fvmlib &C) { + sys::swapByteOrder(C.name); + sys::swapByteOrder(C.minor_version); + sys::swapByteOrder(C.header_addr); +} + +// The fvmlib_command is obsolete and no longer supported. +inline void swapStruct(fvmlib_command &C) { + sys::swapByteOrder(C.cmd); + sys::swapByteOrder(C.cmdsize); + swapStruct(C.fvmlib); +} + +// Get/Set functions from + +inline uint16_t GET_LIBRARY_ORDINAL(uint16_t n_desc) { + return (((n_desc) >> 8u) & 0xffu); +} + +inline void SET_LIBRARY_ORDINAL(uint16_t &n_desc, uint8_t ordinal) { + n_desc = (((n_desc)&0x00ff) | (((ordinal)&0xff) << 8)); +} + +inline uint8_t GET_COMM_ALIGN(uint16_t n_desc) { + return (n_desc >> 8u) & 0x0fu; +} + +inline void SET_COMM_ALIGN(uint16_t &n_desc, uint8_t align) { + n_desc = ((n_desc & 0xf0ffu) | ((align & 0x0fu) << 8u)); +} + +// Enums from +enum : uint32_t { + // Capability bits used in the definition of cpu_type. + CPU_ARCH_MASK = 0xff000000, // Mask for architecture bits + CPU_ARCH_ABI64 = 0x01000000, // 64 bit ABI + CPU_ARCH_ABI64_32 = 0x02000000, // ILP32 ABI on 64-bit hardware +}; + +// Constants for the cputype field. +enum CPUType { + CPU_TYPE_ANY = -1, + CPU_TYPE_X86 = 7, + CPU_TYPE_I386 = CPU_TYPE_X86, + CPU_TYPE_X86_64 = CPU_TYPE_X86 | CPU_ARCH_ABI64, + /* CPU_TYPE_MIPS = 8, */ + CPU_TYPE_MC98000 = 10, // Old Motorola PowerPC + CPU_TYPE_ARM = 12, + CPU_TYPE_ARM64 = CPU_TYPE_ARM | CPU_ARCH_ABI64, + CPU_TYPE_ARM64_32 = CPU_TYPE_ARM | CPU_ARCH_ABI64_32, + CPU_TYPE_SPARC = 14, + CPU_TYPE_POWERPC = 18, + CPU_TYPE_POWERPC64 = CPU_TYPE_POWERPC | CPU_ARCH_ABI64 +}; + +enum : uint32_t { + // Capability bits used in the definition of cpusubtype. + CPU_SUBTYPE_MASK = 0xff000000, // Mask for architecture bits + CPU_SUBTYPE_LIB64 = 0x80000000, // 64 bit libraries + + // Special CPU subtype constants. + CPU_SUBTYPE_MULTIPLE = ~0u +}; + +// Constants for the cpusubtype field. +enum CPUSubTypeX86 { + CPU_SUBTYPE_I386_ALL = 3, + CPU_SUBTYPE_386 = 3, + CPU_SUBTYPE_486 = 4, + CPU_SUBTYPE_486SX = 0x84, + CPU_SUBTYPE_586 = 5, + CPU_SUBTYPE_PENT = CPU_SUBTYPE_586, + CPU_SUBTYPE_PENTPRO = 0x16, + CPU_SUBTYPE_PENTII_M3 = 0x36, + CPU_SUBTYPE_PENTII_M5 = 0x56, + CPU_SUBTYPE_CELERON = 0x67, + CPU_SUBTYPE_CELERON_MOBILE = 0x77, + CPU_SUBTYPE_PENTIUM_3 = 0x08, + CPU_SUBTYPE_PENTIUM_3_M = 0x18, + CPU_SUBTYPE_PENTIUM_3_XEON = 0x28, + CPU_SUBTYPE_PENTIUM_M = 0x09, + CPU_SUBTYPE_PENTIUM_4 = 0x0a, + CPU_SUBTYPE_PENTIUM_4_M = 0x1a, + CPU_SUBTYPE_ITANIUM = 0x0b, + CPU_SUBTYPE_ITANIUM_2 = 0x1b, + CPU_SUBTYPE_XEON = 0x0c, + CPU_SUBTYPE_XEON_MP = 0x1c, + + CPU_SUBTYPE_X86_ALL = 3, + CPU_SUBTYPE_X86_64_ALL = 3, + CPU_SUBTYPE_X86_ARCH1 = 4, + CPU_SUBTYPE_X86_64_H = 8 +}; +inline int CPU_SUBTYPE_INTEL(int Family, int Model) { + return Family | (Model << 4); +} +inline int CPU_SUBTYPE_INTEL_FAMILY(CPUSubTypeX86 ST) { + return ((int)ST) & 0x0f; +} +inline int CPU_SUBTYPE_INTEL_MODEL(CPUSubTypeX86 ST) { return ((int)ST) >> 4; } +enum { CPU_SUBTYPE_INTEL_FAMILY_MAX = 15, CPU_SUBTYPE_INTEL_MODEL_ALL = 0 }; + +enum CPUSubTypeARM { + CPU_SUBTYPE_ARM_ALL = 0, + CPU_SUBTYPE_ARM_V4T = 5, + CPU_SUBTYPE_ARM_V6 = 6, + CPU_SUBTYPE_ARM_V5 = 7, + CPU_SUBTYPE_ARM_V5TEJ = 7, + CPU_SUBTYPE_ARM_XSCALE = 8, + CPU_SUBTYPE_ARM_V7 = 9, + // unused ARM_V7F = 10, + CPU_SUBTYPE_ARM_V7S = 11, + CPU_SUBTYPE_ARM_V7K = 12, + CPU_SUBTYPE_ARM_V6M = 14, + CPU_SUBTYPE_ARM_V7M = 15, + CPU_SUBTYPE_ARM_V7EM = 16 +}; + +enum CPUSubTypeARM64 { + CPU_SUBTYPE_ARM64_ALL = 0, + CPU_SUBTYPE_ARM64_V8 = 1, + CPU_SUBTYPE_ARM64E = 2, + + // arm64 reserves bits in the high byte for subtype-specific flags. + // On arm64e, the 6 low bits represent the ptrauth ABI version. + CPU_SUBTYPE_ARM64E_PTRAUTH_MASK = 0x3f000000, + // On arm64e, the top bit tells whether the Mach-O is versioned. + CPU_SUBTYPE_ARM64E_VERSIONED_PTRAUTH_ABI_MASK = 0x80000000, + // On arm64e, the 2nd high bit tells whether the Mach-O is using kernel ABI. + CPU_SUBTYPE_ARM64E_KERNEL_PTRAUTH_ABI_MASK = 0x40000000 +}; + +inline int CPU_SUBTYPE_ARM64E_PTRAUTH_VERSION(unsigned ST) { + return (ST & CPU_SUBTYPE_ARM64E_PTRAUTH_MASK) >> 24; +} + +inline unsigned +CPU_SUBTYPE_ARM64E_WITH_PTRAUTH_VERSION(unsigned PtrAuthABIVersion, + bool PtrAuthKernelABIVersion) { + assert((PtrAuthABIVersion <= 0x3F) && + "ptrauth abi version must fit in 6 bits"); + return CPU_SUBTYPE_ARM64E | CPU_SUBTYPE_ARM64E_VERSIONED_PTRAUTH_ABI_MASK | + (PtrAuthKernelABIVersion ? CPU_SUBTYPE_ARM64E_KERNEL_PTRAUTH_ABI_MASK + : 0) | + (PtrAuthABIVersion << 24); +} + +inline unsigned CPU_SUBTYPE_ARM64E_IS_VERSIONED_PTRAUTH_ABI(unsigned ST) { + return ST & CPU_SUBTYPE_ARM64E_VERSIONED_PTRAUTH_ABI_MASK; +} + +inline unsigned CPU_SUBTYPE_ARM64E_IS_KERNEL_PTRAUTH_ABI(unsigned ST) { + return ST & CPU_SUBTYPE_ARM64E_KERNEL_PTRAUTH_ABI_MASK; +} + +enum CPUSubTypeARM64_32 { CPU_SUBTYPE_ARM64_32_V8 = 1 }; + +enum CPUSubTypeSPARC { CPU_SUBTYPE_SPARC_ALL = 0 }; + +enum CPUSubTypePowerPC { + CPU_SUBTYPE_POWERPC_ALL = 0, + CPU_SUBTYPE_POWERPC_601 = 1, + CPU_SUBTYPE_POWERPC_602 = 2, + CPU_SUBTYPE_POWERPC_603 = 3, + CPU_SUBTYPE_POWERPC_603e = 4, + CPU_SUBTYPE_POWERPC_603ev = 5, + CPU_SUBTYPE_POWERPC_604 = 6, + CPU_SUBTYPE_POWERPC_604e = 7, + CPU_SUBTYPE_POWERPC_620 = 8, + CPU_SUBTYPE_POWERPC_750 = 9, + CPU_SUBTYPE_POWERPC_7400 = 10, + CPU_SUBTYPE_POWERPC_7450 = 11, + CPU_SUBTYPE_POWERPC_970 = 100, + + CPU_SUBTYPE_MC980000_ALL = CPU_SUBTYPE_POWERPC_ALL, + CPU_SUBTYPE_MC98601 = CPU_SUBTYPE_POWERPC_601 +}; + +Expected getCPUType(const Triple &T); +Expected getCPUSubType(const Triple &T); +Expected getCPUSubType(const Triple &T, unsigned PtrAuthABIVersion, + bool PtrAuthKernelABIVersion); + +struct x86_thread_state32_t { + uint32_t eax; + uint32_t ebx; + uint32_t ecx; + uint32_t edx; + uint32_t edi; + uint32_t esi; + uint32_t ebp; + uint32_t esp; + uint32_t ss; + uint32_t eflags; + uint32_t eip; + uint32_t cs; + uint32_t ds; + uint32_t es; + uint32_t fs; + uint32_t gs; +}; + +struct x86_thread_state64_t { + uint64_t rax; + uint64_t rbx; + uint64_t rcx; + uint64_t rdx; + uint64_t rdi; + uint64_t rsi; + uint64_t rbp; + uint64_t rsp; + uint64_t r8; + uint64_t r9; + uint64_t r10; + uint64_t r11; + uint64_t r12; + uint64_t r13; + uint64_t r14; + uint64_t r15; + uint64_t rip; + uint64_t rflags; + uint64_t cs; + uint64_t fs; + uint64_t gs; +}; + +enum x86_fp_control_precis { + x86_FP_PREC_24B = 0, + x86_FP_PREC_53B = 2, + x86_FP_PREC_64B = 3 +}; + +enum x86_fp_control_rc { + x86_FP_RND_NEAR = 0, + x86_FP_RND_DOWN = 1, + x86_FP_RND_UP = 2, + x86_FP_CHOP = 3 +}; + +struct fp_control_t { + unsigned short invalid : 1, denorm : 1, zdiv : 1, ovrfl : 1, undfl : 1, + precis : 1, : 2, pc : 2, rc : 2, : 1, : 3; +}; + +struct fp_status_t { + unsigned short invalid : 1, denorm : 1, zdiv : 1, ovrfl : 1, undfl : 1, + precis : 1, stkflt : 1, errsumm : 1, c0 : 1, c1 : 1, c2 : 1, tos : 3, + c3 : 1, busy : 1; +}; + +struct mmst_reg_t { + char mmst_reg[10]; + char mmst_rsrv[6]; +}; + +struct xmm_reg_t { + char xmm_reg[16]; +}; + +struct x86_float_state64_t { + int32_t fpu_reserved[2]; + fp_control_t fpu_fcw; + fp_status_t fpu_fsw; + uint8_t fpu_ftw; + uint8_t fpu_rsrv1; + uint16_t fpu_fop; + uint32_t fpu_ip; + uint16_t fpu_cs; + uint16_t fpu_rsrv2; + uint32_t fpu_dp; + uint16_t fpu_ds; + uint16_t fpu_rsrv3; + uint32_t fpu_mxcsr; + uint32_t fpu_mxcsrmask; + mmst_reg_t fpu_stmm0; + mmst_reg_t fpu_stmm1; + mmst_reg_t fpu_stmm2; + mmst_reg_t fpu_stmm3; + mmst_reg_t fpu_stmm4; + mmst_reg_t fpu_stmm5; + mmst_reg_t fpu_stmm6; + mmst_reg_t fpu_stmm7; + xmm_reg_t fpu_xmm0; + xmm_reg_t fpu_xmm1; + xmm_reg_t fpu_xmm2; + xmm_reg_t fpu_xmm3; + xmm_reg_t fpu_xmm4; + xmm_reg_t fpu_xmm5; + xmm_reg_t fpu_xmm6; + xmm_reg_t fpu_xmm7; + xmm_reg_t fpu_xmm8; + xmm_reg_t fpu_xmm9; + xmm_reg_t fpu_xmm10; + xmm_reg_t fpu_xmm11; + xmm_reg_t fpu_xmm12; + xmm_reg_t fpu_xmm13; + xmm_reg_t fpu_xmm14; + xmm_reg_t fpu_xmm15; + char fpu_rsrv4[6 * 16]; + uint32_t fpu_reserved1; +}; + +struct x86_exception_state64_t { + uint16_t trapno; + uint16_t cpu; + uint32_t err; + uint64_t faultvaddr; +}; + +inline void swapStruct(x86_thread_state32_t &x) { + sys::swapByteOrder(x.eax); + sys::swapByteOrder(x.ebx); + sys::swapByteOrder(x.ecx); + sys::swapByteOrder(x.edx); + sys::swapByteOrder(x.edi); + sys::swapByteOrder(x.esi); + sys::swapByteOrder(x.ebp); + sys::swapByteOrder(x.esp); + sys::swapByteOrder(x.ss); + sys::swapByteOrder(x.eflags); + sys::swapByteOrder(x.eip); + sys::swapByteOrder(x.cs); + sys::swapByteOrder(x.ds); + sys::swapByteOrder(x.es); + sys::swapByteOrder(x.fs); + sys::swapByteOrder(x.gs); +} + +inline void swapStruct(x86_thread_state64_t &x) { + sys::swapByteOrder(x.rax); + sys::swapByteOrder(x.rbx); + sys::swapByteOrder(x.rcx); + sys::swapByteOrder(x.rdx); + sys::swapByteOrder(x.rdi); + sys::swapByteOrder(x.rsi); + sys::swapByteOrder(x.rbp); + sys::swapByteOrder(x.rsp); + sys::swapByteOrder(x.r8); + sys::swapByteOrder(x.r9); + sys::swapByteOrder(x.r10); + sys::swapByteOrder(x.r11); + sys::swapByteOrder(x.r12); + sys::swapByteOrder(x.r13); + sys::swapByteOrder(x.r14); + sys::swapByteOrder(x.r15); + sys::swapByteOrder(x.rip); + sys::swapByteOrder(x.rflags); + sys::swapByteOrder(x.cs); + sys::swapByteOrder(x.fs); + sys::swapByteOrder(x.gs); +} + +inline void swapStruct(x86_float_state64_t &x) { + sys::swapByteOrder(x.fpu_reserved[0]); + sys::swapByteOrder(x.fpu_reserved[1]); + // TODO swap: fp_control_t fpu_fcw; + // TODO swap: fp_status_t fpu_fsw; + sys::swapByteOrder(x.fpu_fop); + sys::swapByteOrder(x.fpu_ip); + sys::swapByteOrder(x.fpu_cs); + sys::swapByteOrder(x.fpu_rsrv2); + sys::swapByteOrder(x.fpu_dp); + sys::swapByteOrder(x.fpu_ds); + sys::swapByteOrder(x.fpu_rsrv3); + sys::swapByteOrder(x.fpu_mxcsr); + sys::swapByteOrder(x.fpu_mxcsrmask); + sys::swapByteOrder(x.fpu_reserved1); +} + +inline void swapStruct(x86_exception_state64_t &x) { + sys::swapByteOrder(x.trapno); + sys::swapByteOrder(x.cpu); + sys::swapByteOrder(x.err); + sys::swapByteOrder(x.faultvaddr); +} + +struct x86_state_hdr_t { + uint32_t flavor; + uint32_t count; +}; + +struct x86_thread_state_t { + x86_state_hdr_t tsh; + union { + x86_thread_state64_t ts64; + x86_thread_state32_t ts32; + } uts; +}; + +struct x86_float_state_t { + x86_state_hdr_t fsh; + union { + x86_float_state64_t fs64; + } ufs; +}; + +struct x86_exception_state_t { + x86_state_hdr_t esh; + union { + x86_exception_state64_t es64; + } ues; +}; + +inline void swapStruct(x86_state_hdr_t &x) { + sys::swapByteOrder(x.flavor); + sys::swapByteOrder(x.count); +} + +enum X86ThreadFlavors { + x86_THREAD_STATE32 = 1, + x86_FLOAT_STATE32 = 2, + x86_EXCEPTION_STATE32 = 3, + x86_THREAD_STATE64 = 4, + x86_FLOAT_STATE64 = 5, + x86_EXCEPTION_STATE64 = 6, + x86_THREAD_STATE = 7, + x86_FLOAT_STATE = 8, + x86_EXCEPTION_STATE = 9, + x86_DEBUG_STATE32 = 10, + x86_DEBUG_STATE64 = 11, + x86_DEBUG_STATE = 12 +}; + +inline void swapStruct(x86_thread_state_t &x) { + swapStruct(x.tsh); + if (x.tsh.flavor == x86_THREAD_STATE64) + swapStruct(x.uts.ts64); +} + +inline void swapStruct(x86_float_state_t &x) { + swapStruct(x.fsh); + if (x.fsh.flavor == x86_FLOAT_STATE64) + swapStruct(x.ufs.fs64); +} + +inline void swapStruct(x86_exception_state_t &x) { + swapStruct(x.esh); + if (x.esh.flavor == x86_EXCEPTION_STATE64) + swapStruct(x.ues.es64); +} + +const uint32_t x86_THREAD_STATE32_COUNT = + sizeof(x86_thread_state32_t) / sizeof(uint32_t); + +const uint32_t x86_THREAD_STATE64_COUNT = + sizeof(x86_thread_state64_t) / sizeof(uint32_t); +const uint32_t x86_FLOAT_STATE64_COUNT = + sizeof(x86_float_state64_t) / sizeof(uint32_t); +const uint32_t x86_EXCEPTION_STATE64_COUNT = + sizeof(x86_exception_state64_t) / sizeof(uint32_t); + +const uint32_t x86_THREAD_STATE_COUNT = + sizeof(x86_thread_state_t) / sizeof(uint32_t); +const uint32_t x86_FLOAT_STATE_COUNT = + sizeof(x86_float_state_t) / sizeof(uint32_t); +const uint32_t x86_EXCEPTION_STATE_COUNT = + sizeof(x86_exception_state_t) / sizeof(uint32_t); + +struct arm_thread_state32_t { + uint32_t r[13]; + uint32_t sp; + uint32_t lr; + uint32_t pc; + uint32_t cpsr; +}; + +inline void swapStruct(arm_thread_state32_t &x) { + for (int i = 0; i < 13; i++) + sys::swapByteOrder(x.r[i]); + sys::swapByteOrder(x.sp); + sys::swapByteOrder(x.lr); + sys::swapByteOrder(x.pc); + sys::swapByteOrder(x.cpsr); +} + +struct arm_thread_state64_t { + uint64_t x[29]; + uint64_t fp; + uint64_t lr; + uint64_t sp; + uint64_t pc; + uint32_t cpsr; + uint32_t pad; +}; + +inline void swapStruct(arm_thread_state64_t &x) { + for (int i = 0; i < 29; i++) + sys::swapByteOrder(x.x[i]); + sys::swapByteOrder(x.fp); + sys::swapByteOrder(x.lr); + sys::swapByteOrder(x.sp); + sys::swapByteOrder(x.pc); + sys::swapByteOrder(x.cpsr); +} + +struct arm_state_hdr_t { + uint32_t flavor; + uint32_t count; +}; + +struct arm_thread_state_t { + arm_state_hdr_t tsh; + union { + arm_thread_state32_t ts32; + } uts; +}; + +inline void swapStruct(arm_state_hdr_t &x) { + sys::swapByteOrder(x.flavor); + sys::swapByteOrder(x.count); +} + +enum ARMThreadFlavors { + ARM_THREAD_STATE = 1, + ARM_VFP_STATE = 2, + ARM_EXCEPTION_STATE = 3, + ARM_DEBUG_STATE = 4, + ARN_THREAD_STATE_NONE = 5, + ARM_THREAD_STATE64 = 6, + ARM_EXCEPTION_STATE64 = 7 +}; + +inline void swapStruct(arm_thread_state_t &x) { + swapStruct(x.tsh); + if (x.tsh.flavor == ARM_THREAD_STATE) + swapStruct(x.uts.ts32); +} + +const uint32_t ARM_THREAD_STATE_COUNT = + sizeof(arm_thread_state32_t) / sizeof(uint32_t); + +const uint32_t ARM_THREAD_STATE64_COUNT = + sizeof(arm_thread_state64_t) / sizeof(uint32_t); + +struct ppc_thread_state32_t { + uint32_t srr0; + uint32_t srr1; + uint32_t r0; + uint32_t r1; + uint32_t r2; + uint32_t r3; + uint32_t r4; + uint32_t r5; + uint32_t r6; + uint32_t r7; + uint32_t r8; + uint32_t r9; + uint32_t r10; + uint32_t r11; + uint32_t r12; + uint32_t r13; + uint32_t r14; + uint32_t r15; + uint32_t r16; + uint32_t r17; + uint32_t r18; + uint32_t r19; + uint32_t r20; + uint32_t r21; + uint32_t r22; + uint32_t r23; + uint32_t r24; + uint32_t r25; + uint32_t r26; + uint32_t r27; + uint32_t r28; + uint32_t r29; + uint32_t r30; + uint32_t r31; + uint32_t ct; + uint32_t xer; + uint32_t lr; + uint32_t ctr; + uint32_t mq; + uint32_t vrsave; +}; + +inline void swapStruct(ppc_thread_state32_t &x) { + sys::swapByteOrder(x.srr0); + sys::swapByteOrder(x.srr1); + sys::swapByteOrder(x.r0); + sys::swapByteOrder(x.r1); + sys::swapByteOrder(x.r2); + sys::swapByteOrder(x.r3); + sys::swapByteOrder(x.r4); + sys::swapByteOrder(x.r5); + sys::swapByteOrder(x.r6); + sys::swapByteOrder(x.r7); + sys::swapByteOrder(x.r8); + sys::swapByteOrder(x.r9); + sys::swapByteOrder(x.r10); + sys::swapByteOrder(x.r11); + sys::swapByteOrder(x.r12); + sys::swapByteOrder(x.r13); + sys::swapByteOrder(x.r14); + sys::swapByteOrder(x.r15); + sys::swapByteOrder(x.r16); + sys::swapByteOrder(x.r17); + sys::swapByteOrder(x.r18); + sys::swapByteOrder(x.r19); + sys::swapByteOrder(x.r20); + sys::swapByteOrder(x.r21); + sys::swapByteOrder(x.r22); + sys::swapByteOrder(x.r23); + sys::swapByteOrder(x.r24); + sys::swapByteOrder(x.r25); + sys::swapByteOrder(x.r26); + sys::swapByteOrder(x.r27); + sys::swapByteOrder(x.r28); + sys::swapByteOrder(x.r29); + sys::swapByteOrder(x.r30); + sys::swapByteOrder(x.r31); + sys::swapByteOrder(x.ct); + sys::swapByteOrder(x.xer); + sys::swapByteOrder(x.lr); + sys::swapByteOrder(x.ctr); + sys::swapByteOrder(x.mq); + sys::swapByteOrder(x.vrsave); +} + +struct ppc_state_hdr_t { + uint32_t flavor; + uint32_t count; +}; + +struct ppc_thread_state_t { + ppc_state_hdr_t tsh; + union { + ppc_thread_state32_t ts32; + } uts; +}; + +inline void swapStruct(ppc_state_hdr_t &x) { + sys::swapByteOrder(x.flavor); + sys::swapByteOrder(x.count); +} + +enum PPCThreadFlavors { + PPC_THREAD_STATE = 1, + PPC_FLOAT_STATE = 2, + PPC_EXCEPTION_STATE = 3, + PPC_VECTOR_STATE = 4, + PPC_THREAD_STATE64 = 5, + PPC_EXCEPTION_STATE64 = 6, + PPC_THREAD_STATE_NONE = 7 +}; + +inline void swapStruct(ppc_thread_state_t &x) { + swapStruct(x.tsh); + if (x.tsh.flavor == PPC_THREAD_STATE) + swapStruct(x.uts.ts32); +} + +const uint32_t PPC_THREAD_STATE_COUNT = + sizeof(ppc_thread_state32_t) / sizeof(uint32_t); + +// Define a union of all load command structs +#define LOAD_COMMAND_STRUCT(LCStruct) LCStruct LCStruct##_data; + +LLVM_PACKED_START +union alignas(4) macho_load_command { +#include "llvm/BinaryFormat/MachO.def" +}; +LLVM_PACKED_END + +inline void swapStruct(dyld_chained_fixups_header &C) { + sys::swapByteOrder(C.fixups_version); + sys::swapByteOrder(C.starts_offset); + sys::swapByteOrder(C.imports_offset); + sys::swapByteOrder(C.symbols_offset); + sys::swapByteOrder(C.imports_count); + sys::swapByteOrder(C.imports_format); + sys::swapByteOrder(C.symbols_format); +} + +inline void swapStruct(dyld_chained_starts_in_image &C) { + sys::swapByteOrder(C.seg_count); + // getStructOrErr() cannot copy the variable-length seg_info_offset array. + // Its elements must be byte swapped manually. +} + +inline void swapStruct(dyld_chained_starts_in_segment &C) { + sys::swapByteOrder(C.size); + sys::swapByteOrder(C.page_size); + sys::swapByteOrder(C.pointer_format); + sys::swapByteOrder(C.segment_offset); + sys::swapByteOrder(C.max_valid_pointer); + sys::swapByteOrder(C.page_count); + // seg_info_offset entries must be byte swapped manually. +} + +/* code signing attributes of a process */ + +enum CodeSignAttrs { + CS_VALID = 0x00000001, /* dynamically valid */ + CS_ADHOC = 0x00000002, /* ad hoc signed */ + CS_GET_TASK_ALLOW = 0x00000004, /* has get-task-allow entitlement */ + CS_INSTALLER = 0x00000008, /* has installer entitlement */ + + CS_FORCED_LV = + 0x00000010, /* Library Validation required by Hardened System Policy */ + CS_INVALID_ALLOWED = 0x00000020, /* (macOS Only) Page invalidation allowed by + task port policy */ + + CS_HARD = 0x00000100, /* don't load invalid pages */ + CS_KILL = 0x00000200, /* kill process if it becomes invalid */ + CS_CHECK_EXPIRATION = 0x00000400, /* force expiration checking */ + CS_RESTRICT = 0x00000800, /* tell dyld to treat restricted */ + + CS_ENFORCEMENT = 0x00001000, /* require enforcement */ + CS_REQUIRE_LV = 0x00002000, /* require library validation */ + CS_ENTITLEMENTS_VALIDATED = + 0x00004000, /* code signature permits restricted entitlements */ + CS_NVRAM_UNRESTRICTED = + 0x00008000, /* has com.apple.rootless.restricted-nvram-variables.heritable + entitlement */ + + CS_RUNTIME = 0x00010000, /* Apply hardened runtime policies */ + CS_LINKER_SIGNED = 0x00020000, /* Automatically signed by the linker */ + + CS_ALLOWED_MACHO = + (CS_ADHOC | CS_HARD | CS_KILL | CS_CHECK_EXPIRATION | CS_RESTRICT | + CS_ENFORCEMENT | CS_REQUIRE_LV | CS_RUNTIME | CS_LINKER_SIGNED), + + CS_EXEC_SET_HARD = 0x00100000, /* set CS_HARD on any exec'ed process */ + CS_EXEC_SET_KILL = 0x00200000, /* set CS_KILL on any exec'ed process */ + CS_EXEC_SET_ENFORCEMENT = + 0x00400000, /* set CS_ENFORCEMENT on any exec'ed process */ + CS_EXEC_INHERIT_SIP = + 0x00800000, /* set CS_INSTALLER on any exec'ed process */ + + CS_KILLED = 0x01000000, /* was killed by kernel for invalidity */ + CS_DYLD_PLATFORM = + 0x02000000, /* dyld used to load this is a platform binary */ + CS_PLATFORM_BINARY = 0x04000000, /* this is a platform binary */ + CS_PLATFORM_PATH = + 0x08000000, /* platform binary by the fact of path (osx only) */ + + CS_DEBUGGED = 0x10000000, /* process is currently or has previously been + debugged and allowed to run with invalid pages */ + CS_SIGNED = 0x20000000, /* process has a signature (may have gone invalid) */ + CS_DEV_CODE = + 0x40000000, /* code is dev signed, cannot be loaded into prod signed code + (will go away with rdar://problem/28322552) */ + CS_DATAVAULT_CONTROLLER = + 0x80000000, /* has Data Vault controller entitlement */ + + CS_ENTITLEMENT_FLAGS = (CS_GET_TASK_ALLOW | CS_INSTALLER | + CS_DATAVAULT_CONTROLLER | CS_NVRAM_UNRESTRICTED), +}; + +/* executable segment flags */ + +enum CodeSignExecSegFlags { + + CS_EXECSEG_MAIN_BINARY = 0x1, /* executable segment denotes main binary */ + CS_EXECSEG_ALLOW_UNSIGNED = 0x10, /* allow unsigned pages (for debugging) */ + CS_EXECSEG_DEBUGGER = 0x20, /* main binary is debugger */ + CS_EXECSEG_JIT = 0x40, /* JIT enabled */ + CS_EXECSEG_SKIP_LV = 0x80, /* OBSOLETE: skip library validation */ + CS_EXECSEG_CAN_LOAD_CDHASH = 0x100, /* can bless cdhash for execution */ + CS_EXECSEG_CAN_EXEC_CDHASH = 0x200, /* can execute blessed cdhash */ + +}; + +/* Magic numbers used by Code Signing */ + +enum CodeSignMagic { + CSMAGIC_REQUIREMENT = 0xfade0c00, /* single Requirement blob */ + CSMAGIC_REQUIREMENTS = + 0xfade0c01, /* Requirements vector (internal requirements) */ + CSMAGIC_CODEDIRECTORY = 0xfade0c02, /* CodeDirectory blob */ + CSMAGIC_EMBEDDED_SIGNATURE = 0xfade0cc0, /* embedded form of signature data */ + CSMAGIC_EMBEDDED_SIGNATURE_OLD = 0xfade0b02, /* XXX */ + CSMAGIC_EMBEDDED_ENTITLEMENTS = 0xfade7171, /* embedded entitlements */ + CSMAGIC_DETACHED_SIGNATURE = + 0xfade0cc1, /* multi-arch collection of embedded signatures */ + CSMAGIC_BLOBWRAPPER = 0xfade0b01, /* CMS Signature, among other things */ + + CS_SUPPORTSSCATTER = 0x20100, + CS_SUPPORTSTEAMID = 0x20200, + CS_SUPPORTSCODELIMIT64 = 0x20300, + CS_SUPPORTSEXECSEG = 0x20400, + CS_SUPPORTSRUNTIME = 0x20500, + CS_SUPPORTSLINKAGE = 0x20600, + + CSSLOT_CODEDIRECTORY = 0, /* slot index for CodeDirectory */ + CSSLOT_INFOSLOT = 1, + CSSLOT_REQUIREMENTS = 2, + CSSLOT_RESOURCEDIR = 3, + CSSLOT_APPLICATION = 4, + CSSLOT_ENTITLEMENTS = 5, + + CSSLOT_ALTERNATE_CODEDIRECTORIES = + 0x1000, /* first alternate CodeDirectory, if any */ + CSSLOT_ALTERNATE_CODEDIRECTORY_MAX = 5, /* max number of alternate CD slots */ + CSSLOT_ALTERNATE_CODEDIRECTORY_LIMIT = + CSSLOT_ALTERNATE_CODEDIRECTORIES + + CSSLOT_ALTERNATE_CODEDIRECTORY_MAX, /* one past the last */ + + CSSLOT_SIGNATURESLOT = 0x10000, /* CMS Signature */ + CSSLOT_IDENTIFICATIONSLOT = 0x10001, + CSSLOT_TICKETSLOT = 0x10002, + + CSTYPE_INDEX_REQUIREMENTS = 0x00000002, /* compat with amfi */ + CSTYPE_INDEX_ENTITLEMENTS = 0x00000005, /* compat with amfi */ + + CS_HASHTYPE_SHA1 = 1, + CS_HASHTYPE_SHA256 = 2, + CS_HASHTYPE_SHA256_TRUNCATED = 3, + CS_HASHTYPE_SHA384 = 4, + + CS_SHA1_LEN = 20, + CS_SHA256_LEN = 32, + CS_SHA256_TRUNCATED_LEN = 20, + + CS_CDHASH_LEN = 20, /* always - larger hashes are truncated */ + CS_HASH_MAX_SIZE = 48, /* max size of the hash we'll support */ + + /* + * Currently only to support Legacy VPN plugins, and Mac App Store + * but intended to replace all the various platform code, dev code etc. bits. + */ + CS_SIGNER_TYPE_UNKNOWN = 0, + CS_SIGNER_TYPE_LEGACYVPN = 5, + CS_SIGNER_TYPE_MAC_APP_STORE = 6, + + CS_SUPPL_SIGNER_TYPE_UNKNOWN = 0, + CS_SUPPL_SIGNER_TYPE_TRUSTCACHE = 7, + CS_SUPPL_SIGNER_TYPE_LOCAL = 8, +}; + +struct CS_CodeDirectory { + uint32_t magic; /* magic number (CSMAGIC_CODEDIRECTORY) */ + uint32_t length; /* total length of CodeDirectory blob */ + uint32_t version; /* compatibility version */ + uint32_t flags; /* setup and mode flags */ + uint32_t hashOffset; /* offset of hash slot element at index zero */ + uint32_t identOffset; /* offset of identifier string */ + uint32_t nSpecialSlots; /* number of special hash slots */ + uint32_t nCodeSlots; /* number of ordinary (code) hash slots */ + uint32_t codeLimit; /* limit to main image signature range */ + uint8_t hashSize; /* size of each hash in bytes */ + uint8_t hashType; /* type of hash (cdHashType* constants) */ + uint8_t platform; /* platform identifier; zero if not platform binary */ + uint8_t pageSize; /* log2(page size in bytes); 0 => infinite */ + uint32_t spare2; /* unused (must be zero) */ + + /* Version 0x20100 */ + uint32_t scatterOffset; /* offset of optional scatter vector */ + + /* Version 0x20200 */ + uint32_t teamOffset; /* offset of optional team identifier */ + + /* Version 0x20300 */ + uint32_t spare3; /* unused (must be zero) */ + uint64_t codeLimit64; /* limit to main image signature range, 64 bits */ + + /* Version 0x20400 */ + uint64_t execSegBase; /* offset of executable segment */ + uint64_t execSegLimit; /* limit of executable segment */ + uint64_t execSegFlags; /* executable segment flags */ +}; + +static_assert(sizeof(CS_CodeDirectory) == 88); + +struct CS_BlobIndex { + uint32_t type; /* type of entry */ + uint32_t offset; /* offset of entry */ +}; + +struct CS_SuperBlob { + uint32_t magic; /* magic number */ + uint32_t length; /* total length of SuperBlob */ + uint32_t count; /* number of index entries following */ + /* followed by Blobs in no particular order as indicated by index offsets */ +}; + +enum SecCSDigestAlgorithm { + kSecCodeSignatureNoHash = 0, /* null value */ + kSecCodeSignatureHashSHA1 = 1, /* SHA-1 */ + kSecCodeSignatureHashSHA256 = 2, /* SHA-256 */ + kSecCodeSignatureHashSHA256Truncated = + 3, /* SHA-256 truncated to first 20 bytes */ + kSecCodeSignatureHashSHA384 = 4, /* SHA-384 */ + kSecCodeSignatureHashSHA512 = 5, /* SHA-512 */ +}; + +enum LinkerOptimizationHintKind { + LOH_ARM64_ADRP_ADRP = 1, + LOH_ARM64_ADRP_LDR = 2, + LOH_ARM64_ADRP_ADD_LDR = 3, + LOH_ARM64_ADRP_LDR_GOT_LDR = 4, + LOH_ARM64_ADRP_ADD_STR = 5, + LOH_ARM64_ADRP_LDR_GOT_STR = 6, + LOH_ARM64_ADRP_ADD = 7, + LOH_ARM64_ADRP_LDR_GOT = 8, +}; + +} // end namespace MachO +} // end namespace llvm + +#endif diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/Magic.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/Magic.h new file mode 100644 index 00000000000..329c96f5c14 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/Magic.h @@ -0,0 +1,82 @@ +//===- llvm/BinaryFormat/Magic.h - File magic identification ----*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_BINARYFORMAT_MAGIC_H +#define LLVM_BINARYFORMAT_MAGIC_H + +#include + +namespace llvm { +class StringRef; +class Twine; + +/// file_magic - An "enum class" enumeration of file types based on magic (the +/// first N bytes of the file). +struct file_magic { + enum Impl { + unknown = 0, ///< Unrecognized file + bitcode, ///< Bitcode file + archive, ///< ar style archive file + elf, ///< ELF Unknown type + elf_relocatable, ///< ELF Relocatable object file + elf_executable, ///< ELF Executable image + elf_shared_object, ///< ELF dynamically linked shared lib + elf_core, ///< ELF core image + goff_object, ///< GOFF object file + macho_object, ///< Mach-O Object file + macho_executable, ///< Mach-O Executable + macho_fixed_virtual_memory_shared_lib, ///< Mach-O Shared Lib, FVM + macho_core, ///< Mach-O Core File + macho_preload_executable, ///< Mach-O Preloaded Executable + macho_dynamically_linked_shared_lib, ///< Mach-O dynlinked shared lib + macho_dynamic_linker, ///< The Mach-O dynamic linker + macho_bundle, ///< Mach-O Bundle file + macho_dynamically_linked_shared_lib_stub, ///< Mach-O Shared lib stub + macho_dsym_companion, ///< Mach-O dSYM companion file + macho_kext_bundle, ///< Mach-O kext bundle file + macho_universal_binary, ///< Mach-O universal binary + macho_file_set, ///< Mach-O file set binary + minidump, ///< Windows minidump file + coff_cl_gl_object, ///< Microsoft cl.exe's intermediate code file + coff_object, ///< COFF object file + coff_import_library, ///< COFF import library + pecoff_executable, ///< PECOFF executable file + windows_resource, ///< Windows compiled resource file (.res) + xcoff_object_32, ///< 32-bit XCOFF object file + xcoff_object_64, ///< 64-bit XCOFF object file + wasm_object, ///< WebAssembly Object file + pdb, ///< Windows PDB debug info file + tapi_file, ///< Text-based Dynamic Library Stub file + cuda_fatbinary, ///< CUDA Fatbinary object file + offload_binary, ///< LLVM offload object file + dxcontainer_object, ///< DirectX container file + }; + + bool is_object() const { return V != unknown; } + + file_magic() = default; + file_magic(Impl V) : V(V) {} + operator Impl() const { return V; } + +private: + Impl V = unknown; +}; + +/// Identify the type of a binary file based on how magical it is. +file_magic identify_magic(StringRef magic); + +/// Get and identify \a path's type based on its content. +/// +/// @param path Input path. +/// @param result Set to the type of file, or file_magic::unknown. +/// @returns errc::success if result has been successfully set, otherwise a +/// platform-specific error_code. +std::error_code identify_magic(const Twine &path, file_magic &result); +} // namespace llvm + +#endif diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/Swift.def b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/Swift.def new file mode 100644 index 00000000000..05b60e40632 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/Swift.def @@ -0,0 +1,33 @@ +//===- llvm/BinaryFormat/Swift.def - Swift definitions ---------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// Macros for running through Swift enumerators. +// +//===----------------------------------------------------------------------===// + +#if !(defined HANDLE_SWIFT_SECTION) +#error "Missing macro definition of HANDLE_SWIFT_SECTION" +#endif + +#ifndef HANDLE_SWIFT_SECTION +#define HANDLE_SWIFT_SECTION(KIND, MACHO, ELF, COFF) +#endif + +HANDLE_SWIFT_SECTION(fieldmd, "__swift5_fieldmd", "swift5_fieldmd", ".sw5flmd") +HANDLE_SWIFT_SECTION(assocty, "__swift5_assocty", "swift5_assocty", ".sw5asty") +HANDLE_SWIFT_SECTION(builtin, "__swift5_builtin", "swift5_builtin", ".sw5bltn") +HANDLE_SWIFT_SECTION(capture, "__swift5_capture", "swift5_capture", ".sw5cptr") +HANDLE_SWIFT_SECTION(typeref, "__swift5_typeref", "swift5_typeref", ".sw5tyrf") +HANDLE_SWIFT_SECTION(reflstr, "__swift5_reflstr", "swift5_reflstr", ".sw5rfst") +HANDLE_SWIFT_SECTION(conform, "__swift5_proto", "swift5_protocol_conformances", + ".sw5prtc$B") +HANDLE_SWIFT_SECTION(protocs, "__swift5_protos", "swift5_protocols", + ".sw5prt$B") +HANDLE_SWIFT_SECTION(acfuncs, "__swift5_acfuncs", "swift5_accessible_functions", + ".sw5acfn$B") +HANDLE_SWIFT_SECTION(mpenum, "__swift5_mpenum", "swift5_mpenum", ".sw5mpen$B") diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/Swift.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/Swift.h new file mode 100644 index 00000000000..68c04f11196 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/BinaryFormat/Swift.h @@ -0,0 +1,24 @@ +//===-- llvm/BinaryFormat/Swift.h ---Swift Constants-------------*- C++ -*-===// +// +// 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 +// + +#ifndef LLVM_BINARYFORMAT_SWIFT_H +#define LLVM_BINARYFORMAT_SWIFT_H + +namespace llvm { +namespace binaryformat { + +enum Swift5ReflectionSectionKind { +#define HANDLE_SWIFT_SECTION(KIND, MACHO, ELF, COFF) KIND, +#include "llvm/BinaryFormat/Swift.def" +#undef HANDLE_SWIFT_SECTION + unknown, + last = unknown +}; +} // end of namespace binaryformat +} // end of namespace llvm + +#endif diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/Binary.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/Binary.h new file mode 100644 index 00000000000..ce870e25aca --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/Binary.h @@ -0,0 +1,252 @@ +//===- Binary.h - A generic binary file -------------------------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file declares the Binary class. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_OBJECT_BINARY_H +#define LLVM_OBJECT_BINARY_H + +#include "llvm-c/Types.h" +#include "llvm/Object/Error.h" +#include "llvm/Support/CBindingWrapping.h" +#include "llvm/Support/Error.h" +#include "llvm/Support/MemoryBuffer.h" +#include "llvm/TargetParser/Triple.h" +#include +#include + +namespace llvm { + +class LLVMContext; +class StringRef; + +namespace object { + +class Binary { +private: + unsigned int TypeID; + +protected: + MemoryBufferRef Data; + + Binary(unsigned int Type, MemoryBufferRef Source); + + enum { + ID_Archive, + ID_MachOUniversalBinary, + ID_COFFImportFile, + ID_IR, // LLVM IR + ID_TapiUniversal, // Text-based Dynamic Library Stub file. + ID_TapiFile, // Text-based Dynamic Library Stub file. + + ID_Minidump, + + ID_WinRes, // Windows resource (.res) file. + + ID_Offload, // Offloading binary file. + + // Object and children. + ID_StartObjects, + ID_COFF, + + ID_XCOFF32, // AIX XCOFF 32-bit + ID_XCOFF64, // AIX XCOFF 64-bit + + ID_ELF32L, // ELF 32-bit, little endian + ID_ELF32B, // ELF 32-bit, big endian + ID_ELF64L, // ELF 64-bit, little endian + ID_ELF64B, // ELF 64-bit, big endian + + ID_MachO32L, // MachO 32-bit, little endian + ID_MachO32B, // MachO 32-bit, big endian + ID_MachO64L, // MachO 64-bit, little endian + ID_MachO64B, // MachO 64-bit, big endian + + ID_GOFF, + ID_Wasm, + + ID_EndObjects + }; + + static inline unsigned int getELFType(bool isLE, bool is64Bits) { + if (isLE) + return is64Bits ? ID_ELF64L : ID_ELF32L; + else + return is64Bits ? ID_ELF64B : ID_ELF32B; + } + + static unsigned int getMachOType(bool isLE, bool is64Bits) { + if (isLE) + return is64Bits ? ID_MachO64L : ID_MachO32L; + else + return is64Bits ? ID_MachO64B : ID_MachO32B; + } + +public: + Binary() = delete; + Binary(const Binary &other) = delete; + virtual ~Binary(); + + virtual Error initContent() { return Error::success(); }; + + StringRef getData() const; + StringRef getFileName() const; + MemoryBufferRef getMemoryBufferRef() const; + + // Cast methods. + unsigned int getType() const { return TypeID; } + + // Convenience methods + bool isObject() const { + return TypeID > ID_StartObjects && TypeID < ID_EndObjects; + } + + bool isSymbolic() const { + return isIR() || isObject() || isCOFFImportFile() || isTapiFile(); + } + + bool isArchive() const { return TypeID == ID_Archive; } + + bool isMachOUniversalBinary() const { + return TypeID == ID_MachOUniversalBinary; + } + + bool isTapiUniversal() const { return TypeID == ID_TapiUniversal; } + + bool isELF() const { + return TypeID >= ID_ELF32L && TypeID <= ID_ELF64B; + } + + bool isMachO() const { + return TypeID >= ID_MachO32L && TypeID <= ID_MachO64B; + } + + bool isCOFF() const { + return TypeID == ID_COFF; + } + + bool isXCOFF() const { return TypeID == ID_XCOFF32 || TypeID == ID_XCOFF64; } + + bool isWasm() const { return TypeID == ID_Wasm; } + + bool isOffloadFile() const { return TypeID == ID_Offload; } + + bool isCOFFImportFile() const { + return TypeID == ID_COFFImportFile; + } + + bool isIR() const { + return TypeID == ID_IR; + } + + bool isGOFF() const { return TypeID == ID_GOFF; } + + bool isMinidump() const { return TypeID == ID_Minidump; } + + bool isTapiFile() const { return TypeID == ID_TapiFile; } + + bool isLittleEndian() const { + return !(TypeID == ID_ELF32B || TypeID == ID_ELF64B || + TypeID == ID_MachO32B || TypeID == ID_MachO64B || + TypeID == ID_XCOFF32 || TypeID == ID_XCOFF64); + } + + bool isWinRes() const { return TypeID == ID_WinRes; } + + Triple::ObjectFormatType getTripleObjectFormat() const { + if (isCOFF()) + return Triple::COFF; + if (isMachO()) + return Triple::MachO; + if (isELF()) + return Triple::ELF; + if (isGOFF()) + return Triple::GOFF; + return Triple::UnknownObjectFormat; + } + + static Error checkOffset(MemoryBufferRef M, uintptr_t Addr, + const uint64_t Size) { + if (Addr + Size < Addr || Addr + Size < Size || + Addr + Size > reinterpret_cast(M.getBufferEnd()) || + Addr < reinterpret_cast(M.getBufferStart())) { + return errorCodeToError(object_error::unexpected_eof); + } + return Error::success(); + } +}; + +// Create wrappers for C Binding types (see CBindingWrapping.h). +DEFINE_ISA_CONVERSION_FUNCTIONS(Binary, LLVMBinaryRef) + +/// Create a Binary from Source, autodetecting the file type. +/// +/// @param Source The data to create the Binary from. +Expected> createBinary(MemoryBufferRef Source, + LLVMContext *Context = nullptr, + bool InitContent = true); + +template class OwningBinary { + std::unique_ptr Bin; + std::unique_ptr Buf; + +public: + OwningBinary(); + OwningBinary(std::unique_ptr Bin, std::unique_ptr Buf); + OwningBinary(OwningBinary&& Other); + OwningBinary &operator=(OwningBinary &&Other); + + std::pair, std::unique_ptr> takeBinary(); + + T* getBinary(); + const T* getBinary() const; +}; + +template +OwningBinary::OwningBinary(std::unique_ptr Bin, + std::unique_ptr Buf) + : Bin(std::move(Bin)), Buf(std::move(Buf)) {} + +template OwningBinary::OwningBinary() = default; + +template +OwningBinary::OwningBinary(OwningBinary &&Other) + : Bin(std::move(Other.Bin)), Buf(std::move(Other.Buf)) {} + +template +OwningBinary &OwningBinary::operator=(OwningBinary &&Other) { + Bin = std::move(Other.Bin); + Buf = std::move(Other.Buf); + return *this; +} + +template +std::pair, std::unique_ptr> +OwningBinary::takeBinary() { + return std::make_pair(std::move(Bin), std::move(Buf)); +} + +template T* OwningBinary::getBinary() { + return Bin.get(); +} + +template const T* OwningBinary::getBinary() const { + return Bin.get(); +} + +Expected> createBinary(StringRef Path, + LLVMContext *Context = nullptr, + bool InitContent = true); + +} // end namespace object + +} // end namespace llvm + +#endif // LLVM_OBJECT_BINARY_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/COFF.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/COFF.h new file mode 100644 index 00000000000..4bad7f10323 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/COFF.h @@ -0,0 +1,1362 @@ +//===- COFF.h - COFF object file implementation -----------------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file declares the COFFObjectFile class. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_OBJECT_COFF_H +#define LLVM_OBJECT_COFF_H + +#include "llvm/ADT/iterator_range.h" +#include "llvm/BinaryFormat/COFF.h" +#include "llvm/Object/Binary.h" +#include "llvm/Object/CVDebugRecord.h" +#include "llvm/Object/Error.h" +#include "llvm/Object/ObjectFile.h" +#include "llvm/Support/BinaryByteStream.h" +#include "llvm/Support/ConvertUTF.h" +#include "llvm/Support/Endian.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/TargetParser/SubtargetFeature.h" +#include +#include +#include +#include + +namespace llvm { + +template class ArrayRef; + +namespace object { + +class BaseRelocRef; +class DelayImportDirectoryEntryRef; +class ExportDirectoryEntryRef; +class ImportDirectoryEntryRef; +class ImportedSymbolRef; +class ResourceSectionRef; + +using import_directory_iterator = content_iterator; +using delay_import_directory_iterator = + content_iterator; +using export_directory_iterator = content_iterator; +using imported_symbol_iterator = content_iterator; +using base_reloc_iterator = content_iterator; + +/// The DOS compatible header at the front of all PE/COFF executables. +struct dos_header { + char Magic[2]; + support::ulittle16_t UsedBytesInTheLastPage; + support::ulittle16_t FileSizeInPages; + support::ulittle16_t NumberOfRelocationItems; + support::ulittle16_t HeaderSizeInParagraphs; + support::ulittle16_t MinimumExtraParagraphs; + support::ulittle16_t MaximumExtraParagraphs; + support::ulittle16_t InitialRelativeSS; + support::ulittle16_t InitialSP; + support::ulittle16_t Checksum; + support::ulittle16_t InitialIP; + support::ulittle16_t InitialRelativeCS; + support::ulittle16_t AddressOfRelocationTable; + support::ulittle16_t OverlayNumber; + support::ulittle16_t Reserved[4]; + support::ulittle16_t OEMid; + support::ulittle16_t OEMinfo; + support::ulittle16_t Reserved2[10]; + support::ulittle32_t AddressOfNewExeHeader; +}; + +struct coff_file_header { + support::ulittle16_t Machine; + support::ulittle16_t NumberOfSections; + support::ulittle32_t TimeDateStamp; + support::ulittle32_t PointerToSymbolTable; + support::ulittle32_t NumberOfSymbols; + support::ulittle16_t SizeOfOptionalHeader; + support::ulittle16_t Characteristics; + + bool isImportLibrary() const { return NumberOfSections == 0xffff; } +}; + +struct coff_bigobj_file_header { + support::ulittle16_t Sig1; + support::ulittle16_t Sig2; + support::ulittle16_t Version; + support::ulittle16_t Machine; + support::ulittle32_t TimeDateStamp; + uint8_t UUID[16]; + support::ulittle32_t unused1; + support::ulittle32_t unused2; + support::ulittle32_t unused3; + support::ulittle32_t unused4; + support::ulittle32_t NumberOfSections; + support::ulittle32_t PointerToSymbolTable; + support::ulittle32_t NumberOfSymbols; +}; + +/// The 32-bit PE header that follows the COFF header. +struct pe32_header { + support::ulittle16_t Magic; + uint8_t MajorLinkerVersion; + uint8_t MinorLinkerVersion; + support::ulittle32_t SizeOfCode; + support::ulittle32_t SizeOfInitializedData; + support::ulittle32_t SizeOfUninitializedData; + support::ulittle32_t AddressOfEntryPoint; + support::ulittle32_t BaseOfCode; + support::ulittle32_t BaseOfData; + support::ulittle32_t ImageBase; + support::ulittle32_t SectionAlignment; + support::ulittle32_t FileAlignment; + support::ulittle16_t MajorOperatingSystemVersion; + support::ulittle16_t MinorOperatingSystemVersion; + support::ulittle16_t MajorImageVersion; + support::ulittle16_t MinorImageVersion; + support::ulittle16_t MajorSubsystemVersion; + support::ulittle16_t MinorSubsystemVersion; + support::ulittle32_t Win32VersionValue; + support::ulittle32_t SizeOfImage; + support::ulittle32_t SizeOfHeaders; + support::ulittle32_t CheckSum; + support::ulittle16_t Subsystem; + // FIXME: This should be DllCharacteristics. + support::ulittle16_t DLLCharacteristics; + support::ulittle32_t SizeOfStackReserve; + support::ulittle32_t SizeOfStackCommit; + support::ulittle32_t SizeOfHeapReserve; + support::ulittle32_t SizeOfHeapCommit; + support::ulittle32_t LoaderFlags; + // FIXME: This should be NumberOfRvaAndSizes. + support::ulittle32_t NumberOfRvaAndSize; +}; + +/// The 64-bit PE header that follows the COFF header. +struct pe32plus_header { + support::ulittle16_t Magic; + uint8_t MajorLinkerVersion; + uint8_t MinorLinkerVersion; + support::ulittle32_t SizeOfCode; + support::ulittle32_t SizeOfInitializedData; + support::ulittle32_t SizeOfUninitializedData; + support::ulittle32_t AddressOfEntryPoint; + support::ulittle32_t BaseOfCode; + support::ulittle64_t ImageBase; + support::ulittle32_t SectionAlignment; + support::ulittle32_t FileAlignment; + support::ulittle16_t MajorOperatingSystemVersion; + support::ulittle16_t MinorOperatingSystemVersion; + support::ulittle16_t MajorImageVersion; + support::ulittle16_t MinorImageVersion; + support::ulittle16_t MajorSubsystemVersion; + support::ulittle16_t MinorSubsystemVersion; + support::ulittle32_t Win32VersionValue; + support::ulittle32_t SizeOfImage; + support::ulittle32_t SizeOfHeaders; + support::ulittle32_t CheckSum; + support::ulittle16_t Subsystem; + support::ulittle16_t DLLCharacteristics; + support::ulittle64_t SizeOfStackReserve; + support::ulittle64_t SizeOfStackCommit; + support::ulittle64_t SizeOfHeapReserve; + support::ulittle64_t SizeOfHeapCommit; + support::ulittle32_t LoaderFlags; + support::ulittle32_t NumberOfRvaAndSize; +}; + +struct data_directory { + support::ulittle32_t RelativeVirtualAddress; + support::ulittle32_t Size; +}; + +struct debug_directory { + support::ulittle32_t Characteristics; + support::ulittle32_t TimeDateStamp; + support::ulittle16_t MajorVersion; + support::ulittle16_t MinorVersion; + support::ulittle32_t Type; + support::ulittle32_t SizeOfData; + support::ulittle32_t AddressOfRawData; + support::ulittle32_t PointerToRawData; +}; + +template +struct import_lookup_table_entry { + IntTy Data; + + bool isOrdinal() const { return Data < 0; } + + uint16_t getOrdinal() const { + assert(isOrdinal() && "ILT entry is not an ordinal!"); + return Data & 0xFFFF; + } + + uint32_t getHintNameRVA() const { + assert(!isOrdinal() && "ILT entry is not a Hint/Name RVA!"); + return Data & 0xFFFFFFFF; + } +}; + +using import_lookup_table_entry32 = + import_lookup_table_entry; +using import_lookup_table_entry64 = + import_lookup_table_entry; + +struct delay_import_directory_table_entry { + // dumpbin reports this field as "Characteristics" instead of "Attributes". + support::ulittle32_t Attributes; + support::ulittle32_t Name; + support::ulittle32_t ModuleHandle; + support::ulittle32_t DelayImportAddressTable; + support::ulittle32_t DelayImportNameTable; + support::ulittle32_t BoundDelayImportTable; + support::ulittle32_t UnloadDelayImportTable; + support::ulittle32_t TimeStamp; +}; + +struct export_directory_table_entry { + support::ulittle32_t ExportFlags; + support::ulittle32_t TimeDateStamp; + support::ulittle16_t MajorVersion; + support::ulittle16_t MinorVersion; + support::ulittle32_t NameRVA; + support::ulittle32_t OrdinalBase; + support::ulittle32_t AddressTableEntries; + support::ulittle32_t NumberOfNamePointers; + support::ulittle32_t ExportAddressTableRVA; + support::ulittle32_t NamePointerRVA; + support::ulittle32_t OrdinalTableRVA; +}; + +union export_address_table_entry { + support::ulittle32_t ExportRVA; + support::ulittle32_t ForwarderRVA; +}; + +using export_name_pointer_table_entry = support::ulittle32_t; +using export_ordinal_table_entry = support::ulittle16_t; + +struct StringTableOffset { + support::ulittle32_t Zeroes; + support::ulittle32_t Offset; +}; + +template +struct coff_symbol { + union { + char ShortName[COFF::NameSize]; + StringTableOffset Offset; + } Name; + + support::ulittle32_t Value; + SectionNumberType SectionNumber; + + support::ulittle16_t Type; + + uint8_t StorageClass; + uint8_t NumberOfAuxSymbols; +}; + +using coff_symbol16 = coff_symbol; +using coff_symbol32 = coff_symbol; + +// Contains only common parts of coff_symbol16 and coff_symbol32. +struct coff_symbol_generic { + union { + char ShortName[COFF::NameSize]; + StringTableOffset Offset; + } Name; + support::ulittle32_t Value; +}; + +struct coff_aux_section_definition; +struct coff_aux_weak_external; + +class COFFSymbolRef { +public: + COFFSymbolRef() = default; + COFFSymbolRef(const coff_symbol16 *CS) : CS16(CS) {} + COFFSymbolRef(const coff_symbol32 *CS) : CS32(CS) {} + + const void *getRawPtr() const { + return CS16 ? static_cast(CS16) : CS32; + } + + const coff_symbol_generic *getGeneric() const { + if (CS16) + return reinterpret_cast(CS16); + return reinterpret_cast(CS32); + } + + friend bool operator<(COFFSymbolRef A, COFFSymbolRef B) { + return A.getRawPtr() < B.getRawPtr(); + } + + bool isBigObj() const { + if (CS16) + return false; + if (CS32) + return true; + llvm_unreachable("COFFSymbolRef points to nothing!"); + } + + const char *getShortName() const { + return CS16 ? CS16->Name.ShortName : CS32->Name.ShortName; + } + + const StringTableOffset &getStringTableOffset() const { + assert(isSet() && "COFFSymbolRef points to nothing!"); + return CS16 ? CS16->Name.Offset : CS32->Name.Offset; + } + + uint32_t getValue() const { + assert(isSet() && "COFFSymbolRef points to nothing!"); + return CS16 ? CS16->Value : CS32->Value; + } + + int32_t getSectionNumber() const { + assert(isSet() && "COFFSymbolRef points to nothing!"); + if (CS16) { + // Reserved sections are returned as negative numbers. + if (CS16->SectionNumber <= COFF::MaxNumberOfSections16) + return CS16->SectionNumber; + return static_cast(CS16->SectionNumber); + } + return static_cast(CS32->SectionNumber); + } + + uint16_t getType() const { + assert(isSet() && "COFFSymbolRef points to nothing!"); + return CS16 ? CS16->Type : CS32->Type; + } + + uint8_t getStorageClass() const { + assert(isSet() && "COFFSymbolRef points to nothing!"); + return CS16 ? CS16->StorageClass : CS32->StorageClass; + } + + uint8_t getNumberOfAuxSymbols() const { + assert(isSet() && "COFFSymbolRef points to nothing!"); + return CS16 ? CS16->NumberOfAuxSymbols : CS32->NumberOfAuxSymbols; + } + + uint8_t getBaseType() const { return getType() & 0x0F; } + + uint8_t getComplexType() const { + return (getType() & 0xF0) >> COFF::SCT_COMPLEX_TYPE_SHIFT; + } + + template const T *getAux() const { + return CS16 ? reinterpret_cast(CS16 + 1) + : reinterpret_cast(CS32 + 1); + } + + const coff_aux_section_definition *getSectionDefinition() const { + if (!getNumberOfAuxSymbols() || + getStorageClass() != COFF::IMAGE_SYM_CLASS_STATIC) + return nullptr; + return getAux(); + } + + const coff_aux_weak_external *getWeakExternal() const { + if (!getNumberOfAuxSymbols() || + getStorageClass() != COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL) + return nullptr; + return getAux(); + } + + bool isAbsolute() const { + return getSectionNumber() == -1; + } + + bool isExternal() const { + return getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL; + } + + bool isCommon() const { + return (isExternal() || isSection()) && + getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED && getValue() != 0; + } + + bool isUndefined() const { + return isExternal() && getSectionNumber() == COFF::IMAGE_SYM_UNDEFINED && + getValue() == 0; + } + + bool isWeakExternal() const { + return getStorageClass() == COFF::IMAGE_SYM_CLASS_WEAK_EXTERNAL; + } + + bool isFunctionDefinition() const { + return isExternal() && getBaseType() == COFF::IMAGE_SYM_TYPE_NULL && + getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION && + !COFF::isReservedSectionNumber(getSectionNumber()); + } + + bool isFunctionLineInfo() const { + return getStorageClass() == COFF::IMAGE_SYM_CLASS_FUNCTION; + } + + bool isAnyUndefined() const { + return isUndefined() || isWeakExternal(); + } + + bool isFileRecord() const { + return getStorageClass() == COFF::IMAGE_SYM_CLASS_FILE; + } + + bool isSection() const { + return getStorageClass() == COFF::IMAGE_SYM_CLASS_SECTION; + } + + bool isSectionDefinition() const { + // C++/CLI creates external ABS symbols for non-const appdomain globals. + // These are also followed by an auxiliary section definition. + bool isAppdomainGlobal = + getStorageClass() == COFF::IMAGE_SYM_CLASS_EXTERNAL && + getSectionNumber() == COFF::IMAGE_SYM_ABSOLUTE; + bool isOrdinarySection = getStorageClass() == COFF::IMAGE_SYM_CLASS_STATIC; + if (!getNumberOfAuxSymbols()) + return false; + return isAppdomainGlobal || isOrdinarySection; + } + + bool isCLRToken() const { + return getStorageClass() == COFF::IMAGE_SYM_CLASS_CLR_TOKEN; + } + +private: + bool isSet() const { return CS16 || CS32; } + + const coff_symbol16 *CS16 = nullptr; + const coff_symbol32 *CS32 = nullptr; +}; + +struct coff_section { + char Name[COFF::NameSize]; + support::ulittle32_t VirtualSize; + support::ulittle32_t VirtualAddress; + support::ulittle32_t SizeOfRawData; + support::ulittle32_t PointerToRawData; + support::ulittle32_t PointerToRelocations; + support::ulittle32_t PointerToLinenumbers; + support::ulittle16_t NumberOfRelocations; + support::ulittle16_t NumberOfLinenumbers; + support::ulittle32_t Characteristics; + + // Returns true if the actual number of relocations is stored in + // VirtualAddress field of the first relocation table entry. + bool hasExtendedRelocations() const { + return (Characteristics & COFF::IMAGE_SCN_LNK_NRELOC_OVFL) && + NumberOfRelocations == UINT16_MAX; + } + + uint32_t getAlignment() const { + // The IMAGE_SCN_TYPE_NO_PAD bit is a legacy way of getting to + // IMAGE_SCN_ALIGN_1BYTES. + if (Characteristics & COFF::IMAGE_SCN_TYPE_NO_PAD) + return 1; + + // Bit [20:24] contains section alignment. 0 means use a default alignment + // of 16. + uint32_t Shift = (Characteristics >> 20) & 0xF; + if (Shift > 0) + return 1U << (Shift - 1); + return 16; + } +}; + +struct coff_relocation { + support::ulittle32_t VirtualAddress; + support::ulittle32_t SymbolTableIndex; + support::ulittle16_t Type; +}; + +struct coff_aux_function_definition { + support::ulittle32_t TagIndex; + support::ulittle32_t TotalSize; + support::ulittle32_t PointerToLinenumber; + support::ulittle32_t PointerToNextFunction; + char Unused1[2]; +}; + +static_assert(sizeof(coff_aux_function_definition) == 18, + "auxiliary entry must be 18 bytes"); + +struct coff_aux_bf_and_ef_symbol { + char Unused1[4]; + support::ulittle16_t Linenumber; + char Unused2[6]; + support::ulittle32_t PointerToNextFunction; + char Unused3[2]; +}; + +static_assert(sizeof(coff_aux_bf_and_ef_symbol) == 18, + "auxiliary entry must be 18 bytes"); + +struct coff_aux_weak_external { + support::ulittle32_t TagIndex; + support::ulittle32_t Characteristics; + char Unused1[10]; +}; + +static_assert(sizeof(coff_aux_weak_external) == 18, + "auxiliary entry must be 18 bytes"); + +struct coff_aux_section_definition { + support::ulittle32_t Length; + support::ulittle16_t NumberOfRelocations; + support::ulittle16_t NumberOfLinenumbers; + support::ulittle32_t CheckSum; + support::ulittle16_t NumberLowPart; + uint8_t Selection; + uint8_t Unused; + support::ulittle16_t NumberHighPart; + int32_t getNumber(bool IsBigObj) const { + uint32_t Number = static_cast(NumberLowPart); + if (IsBigObj) + Number |= static_cast(NumberHighPart) << 16; + return static_cast(Number); + } +}; + +static_assert(sizeof(coff_aux_section_definition) == 18, + "auxiliary entry must be 18 bytes"); + +struct coff_aux_clr_token { + uint8_t AuxType; + uint8_t Reserved; + support::ulittle32_t SymbolTableIndex; + char MBZ[12]; +}; + +static_assert(sizeof(coff_aux_clr_token) == 18, + "auxiliary entry must be 18 bytes"); + +struct coff_import_header { + support::ulittle16_t Sig1; + support::ulittle16_t Sig2; + support::ulittle16_t Version; + support::ulittle16_t Machine; + support::ulittle32_t TimeDateStamp; + support::ulittle32_t SizeOfData; + support::ulittle16_t OrdinalHint; + support::ulittle16_t TypeInfo; + + int getType() const { return TypeInfo & 0x3; } + int getNameType() const { return (TypeInfo >> 2) & 0x7; } +}; + +struct coff_import_directory_table_entry { + support::ulittle32_t ImportLookupTableRVA; + support::ulittle32_t TimeDateStamp; + support::ulittle32_t ForwarderChain; + support::ulittle32_t NameRVA; + support::ulittle32_t ImportAddressTableRVA; + + bool isNull() const { + return ImportLookupTableRVA == 0 && TimeDateStamp == 0 && + ForwarderChain == 0 && NameRVA == 0 && ImportAddressTableRVA == 0; + } +}; + +template +struct coff_tls_directory { + IntTy StartAddressOfRawData; + IntTy EndAddressOfRawData; + IntTy AddressOfIndex; + IntTy AddressOfCallBacks; + support::ulittle32_t SizeOfZeroFill; + support::ulittle32_t Characteristics; + + uint32_t getAlignment() const { + // Bit [20:24] contains section alignment. + uint32_t Shift = (Characteristics & COFF::IMAGE_SCN_ALIGN_MASK) >> 20; + if (Shift > 0) + return 1U << (Shift - 1); + return 0; + } + + void setAlignment(uint32_t Align) { + uint32_t AlignBits = 0; + if (Align) { + assert(llvm::isPowerOf2_32(Align) && "alignment is not a power of 2"); + assert(llvm::Log2_32(Align) <= 13 && "alignment requested is too large"); + AlignBits = (llvm::Log2_32(Align) + 1) << 20; + } + Characteristics = + (Characteristics & ~COFF::IMAGE_SCN_ALIGN_MASK) | AlignBits; + } +}; + +using coff_tls_directory32 = coff_tls_directory; +using coff_tls_directory64 = coff_tls_directory; + +enum class frame_type : uint16_t { Fpo = 0, Trap = 1, Tss = 2, NonFpo = 3 }; + +struct coff_load_config_code_integrity { + support::ulittle16_t Flags; + support::ulittle16_t Catalog; + support::ulittle32_t CatalogOffset; + support::ulittle32_t Reserved; +}; + +/// 32-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY32) +struct coff_load_configuration32 { + support::ulittle32_t Size; + support::ulittle32_t TimeDateStamp; + support::ulittle16_t MajorVersion; + support::ulittle16_t MinorVersion; + support::ulittle32_t GlobalFlagsClear; + support::ulittle32_t GlobalFlagsSet; + support::ulittle32_t CriticalSectionDefaultTimeout; + support::ulittle32_t DeCommitFreeBlockThreshold; + support::ulittle32_t DeCommitTotalFreeThreshold; + support::ulittle32_t LockPrefixTable; + support::ulittle32_t MaximumAllocationSize; + support::ulittle32_t VirtualMemoryThreshold; + support::ulittle32_t ProcessAffinityMask; + support::ulittle32_t ProcessHeapFlags; + support::ulittle16_t CSDVersion; + support::ulittle16_t DependentLoadFlags; + support::ulittle32_t EditList; + support::ulittle32_t SecurityCookie; + support::ulittle32_t SEHandlerTable; + support::ulittle32_t SEHandlerCount; + + // Added in MSVC 2015 for /guard:cf. + support::ulittle32_t GuardCFCheckFunction; + support::ulittle32_t GuardCFCheckDispatch; + support::ulittle32_t GuardCFFunctionTable; + support::ulittle32_t GuardCFFunctionCount; + support::ulittle32_t GuardFlags; // coff_guard_flags + + // Added in MSVC 2017 + coff_load_config_code_integrity CodeIntegrity; + support::ulittle32_t GuardAddressTakenIatEntryTable; + support::ulittle32_t GuardAddressTakenIatEntryCount; + support::ulittle32_t GuardLongJumpTargetTable; + support::ulittle32_t GuardLongJumpTargetCount; + support::ulittle32_t DynamicValueRelocTable; + support::ulittle32_t CHPEMetadataPointer; + support::ulittle32_t GuardRFFailureRoutine; + support::ulittle32_t GuardRFFailureRoutineFunctionPointer; + support::ulittle32_t DynamicValueRelocTableOffset; + support::ulittle16_t DynamicValueRelocTableSection; + support::ulittle16_t Reserved2; + support::ulittle32_t GuardRFVerifyStackPointerFunctionPointer; + support::ulittle32_t HotPatchTableOffset; + + // Added in MSVC 2019 + support::ulittle32_t Reserved3; + support::ulittle32_t EnclaveConfigurationPointer; + support::ulittle32_t VolatileMetadataPointer; + support::ulittle32_t GuardEHContinuationTable; + support::ulittle32_t GuardEHContinuationCount; + support::ulittle32_t GuardXFGCheckFunctionPointer; + support::ulittle32_t GuardXFGDispatchFunctionPointer; + support::ulittle32_t GuardXFGTableDispatchFunctionPointer; + support::ulittle32_t CastGuardOsDeterminedFailureMode; +}; + +/// 64-bit load config (IMAGE_LOAD_CONFIG_DIRECTORY64) +struct coff_load_configuration64 { + support::ulittle32_t Size; + support::ulittle32_t TimeDateStamp; + support::ulittle16_t MajorVersion; + support::ulittle16_t MinorVersion; + support::ulittle32_t GlobalFlagsClear; + support::ulittle32_t GlobalFlagsSet; + support::ulittle32_t CriticalSectionDefaultTimeout; + support::ulittle64_t DeCommitFreeBlockThreshold; + support::ulittle64_t DeCommitTotalFreeThreshold; + support::ulittle64_t LockPrefixTable; + support::ulittle64_t MaximumAllocationSize; + support::ulittle64_t VirtualMemoryThreshold; + support::ulittle64_t ProcessAffinityMask; + support::ulittle32_t ProcessHeapFlags; + support::ulittle16_t CSDVersion; + support::ulittle16_t DependentLoadFlags; + support::ulittle64_t EditList; + support::ulittle64_t SecurityCookie; + support::ulittle64_t SEHandlerTable; + support::ulittle64_t SEHandlerCount; + + // Added in MSVC 2015 for /guard:cf. + support::ulittle64_t GuardCFCheckFunction; + support::ulittle64_t GuardCFCheckDispatch; + support::ulittle64_t GuardCFFunctionTable; + support::ulittle64_t GuardCFFunctionCount; + support::ulittle32_t GuardFlags; + + // Added in MSVC 2017 + coff_load_config_code_integrity CodeIntegrity; + support::ulittle64_t GuardAddressTakenIatEntryTable; + support::ulittle64_t GuardAddressTakenIatEntryCount; + support::ulittle64_t GuardLongJumpTargetTable; + support::ulittle64_t GuardLongJumpTargetCount; + support::ulittle64_t DynamicValueRelocTable; + support::ulittle64_t CHPEMetadataPointer; + support::ulittle64_t GuardRFFailureRoutine; + support::ulittle64_t GuardRFFailureRoutineFunctionPointer; + support::ulittle32_t DynamicValueRelocTableOffset; + support::ulittle16_t DynamicValueRelocTableSection; + support::ulittle16_t Reserved2; + support::ulittle64_t GuardRFVerifyStackPointerFunctionPointer; + support::ulittle32_t HotPatchTableOffset; + + // Added in MSVC 2019 + support::ulittle32_t Reserved3; + support::ulittle64_t EnclaveConfigurationPointer; + support::ulittle64_t VolatileMetadataPointer; + support::ulittle64_t GuardEHContinuationTable; + support::ulittle64_t GuardEHContinuationCount; + support::ulittle64_t GuardXFGCheckFunctionPointer; + support::ulittle64_t GuardXFGDispatchFunctionPointer; + support::ulittle64_t GuardXFGTableDispatchFunctionPointer; + support::ulittle64_t CastGuardOsDeterminedFailureMode; +}; + +struct chpe_metadata { + support::ulittle32_t Version; + support::ulittle32_t CodeMap; + support::ulittle32_t CodeMapCount; + support::ulittle32_t CodeRangesToEntryPoints; + support::ulittle32_t RedirectionMetadata; + support::ulittle32_t __os_arm64x_dispatch_call_no_redirect; + support::ulittle32_t __os_arm64x_dispatch_ret; + support::ulittle32_t __os_arm64x_dispatch_call; + support::ulittle32_t __os_arm64x_dispatch_icall; + support::ulittle32_t __os_arm64x_dispatch_icall_cfg; + support::ulittle32_t AlternateEntryPoint; + support::ulittle32_t AuxiliaryIAT; + support::ulittle32_t CodeRangesToEntryPointsCount; + support::ulittle32_t RedirectionMetadataCount; + support::ulittle32_t GetX64InformationFunctionPointer; + support::ulittle32_t SetX64InformationFunctionPointer; + support::ulittle32_t ExtraRFETable; + support::ulittle32_t ExtraRFETableSize; + support::ulittle32_t __os_arm64x_dispatch_fptr; + support::ulittle32_t AuxiliaryIATCopy; +}; + +struct chpe_range_entry { + support::ulittle32_t StartOffset; + support::ulittle32_t Length; +}; + +enum chpe_range_type { CHPE_RANGE_ARM64, CHPE_RANGE_ARM64EC, CHPE_RANGE_AMD64 }; + +struct chpe_code_range_entry { + support::ulittle32_t StartRva; + support::ulittle32_t EndRva; + support::ulittle32_t EntryPoint; +}; + +struct chpe_redirection_entry { + support::ulittle32_t Source; + support::ulittle32_t Destination; +}; + +struct coff_runtime_function_x64 { + support::ulittle32_t BeginAddress; + support::ulittle32_t EndAddress; + support::ulittle32_t UnwindInformation; +}; + +struct coff_base_reloc_block_header { + support::ulittle32_t PageRVA; + support::ulittle32_t BlockSize; +}; + +struct coff_base_reloc_block_entry { + support::ulittle16_t Data; + + int getType() const { return Data >> 12; } + int getOffset() const { return Data & ((1 << 12) - 1); } +}; + +struct coff_resource_dir_entry { + union { + support::ulittle32_t NameOffset; + support::ulittle32_t ID; + uint32_t getNameOffset() const { + return maskTrailingOnes(31) & NameOffset; + } + // Even though the PE/COFF spec doesn't mention this, the high bit of a name + // offset is set. + void setNameOffset(uint32_t Offset) { NameOffset = Offset | (1 << 31); } + } Identifier; + union { + support::ulittle32_t DataEntryOffset; + support::ulittle32_t SubdirOffset; + + bool isSubDir() const { return SubdirOffset >> 31; } + uint32_t value() const { + return maskTrailingOnes(31) & SubdirOffset; + } + + } Offset; +}; + +struct coff_resource_data_entry { + support::ulittle32_t DataRVA; + support::ulittle32_t DataSize; + support::ulittle32_t Codepage; + support::ulittle32_t Reserved; +}; + +struct coff_resource_dir_table { + support::ulittle32_t Characteristics; + support::ulittle32_t TimeDateStamp; + support::ulittle16_t MajorVersion; + support::ulittle16_t MinorVersion; + support::ulittle16_t NumberOfNameEntries; + support::ulittle16_t NumberOfIDEntries; +}; + +struct debug_h_header { + support::ulittle32_t Magic; + support::ulittle16_t Version; + support::ulittle16_t HashAlgorithm; +}; + +class COFFObjectFile : public ObjectFile { +private: + COFFObjectFile(MemoryBufferRef Object); + + friend class ImportDirectoryEntryRef; + friend class ExportDirectoryEntryRef; + const coff_file_header *COFFHeader; + const coff_bigobj_file_header *COFFBigObjHeader; + const pe32_header *PE32Header; + const pe32plus_header *PE32PlusHeader; + const data_directory *DataDirectory; + const coff_section *SectionTable; + const coff_symbol16 *SymbolTable16; + const coff_symbol32 *SymbolTable32; + const char *StringTable; + uint32_t StringTableSize; + const coff_import_directory_table_entry *ImportDirectory; + const delay_import_directory_table_entry *DelayImportDirectory; + uint32_t NumberOfDelayImportDirectory; + const export_directory_table_entry *ExportDirectory; + const coff_base_reloc_block_header *BaseRelocHeader; + const coff_base_reloc_block_header *BaseRelocEnd; + const debug_directory *DebugDirectoryBegin; + const debug_directory *DebugDirectoryEnd; + const coff_tls_directory32 *TLSDirectory32; + const coff_tls_directory64 *TLSDirectory64; + // Either coff_load_configuration32 or coff_load_configuration64. + const void *LoadConfig = nullptr; + const chpe_metadata *CHPEMetadata = nullptr; + + Expected getString(uint32_t offset) const; + + template + const coff_symbol_type *toSymb(DataRefImpl Symb) const; + const coff_section *toSec(DataRefImpl Sec) const; + const coff_relocation *toRel(DataRefImpl Rel) const; + + // Finish initializing the object and return success or an error. + Error initialize(); + + Error initSymbolTablePtr(); + Error initImportTablePtr(); + Error initDelayImportTablePtr(); + Error initExportTablePtr(); + Error initBaseRelocPtr(); + Error initDebugDirectoryPtr(); + Error initTLSDirectoryPtr(); + Error initLoadConfigPtr(); + +public: + static Expected> + create(MemoryBufferRef Object); + + uintptr_t getSymbolTable() const { + if (SymbolTable16) + return reinterpret_cast(SymbolTable16); + if (SymbolTable32) + return reinterpret_cast(SymbolTable32); + return uintptr_t(0); + } + + uint16_t getMachine() const { + if (COFFHeader) { + if (CHPEMetadata) { + switch (COFFHeader->Machine) { + case COFF::IMAGE_FILE_MACHINE_AMD64: + return COFF::IMAGE_FILE_MACHINE_ARM64EC; + case COFF::IMAGE_FILE_MACHINE_ARM64: + return COFF::IMAGE_FILE_MACHINE_ARM64X; + } + } + return COFFHeader->Machine; + } + if (COFFBigObjHeader) + return COFFBigObjHeader->Machine; + llvm_unreachable("no COFF header!"); + } + + uint16_t getSizeOfOptionalHeader() const { + if (COFFHeader) + return COFFHeader->isImportLibrary() ? 0 + : COFFHeader->SizeOfOptionalHeader; + // bigobj doesn't have this field. + if (COFFBigObjHeader) + return 0; + llvm_unreachable("no COFF header!"); + } + + uint16_t getCharacteristics() const { + if (COFFHeader) + return COFFHeader->isImportLibrary() ? 0 : COFFHeader->Characteristics; + // bigobj doesn't have characteristics to speak of, + // editbin will silently lie to you if you attempt to set any. + if (COFFBigObjHeader) + return 0; + llvm_unreachable("no COFF header!"); + } + + uint32_t getTimeDateStamp() const { + if (COFFHeader) + return COFFHeader->TimeDateStamp; + if (COFFBigObjHeader) + return COFFBigObjHeader->TimeDateStamp; + llvm_unreachable("no COFF header!"); + } + + uint32_t getNumberOfSections() const { + if (COFFHeader) + return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSections; + if (COFFBigObjHeader) + return COFFBigObjHeader->NumberOfSections; + llvm_unreachable("no COFF header!"); + } + + uint32_t getPointerToSymbolTable() const { + if (COFFHeader) + return COFFHeader->isImportLibrary() ? 0 + : COFFHeader->PointerToSymbolTable; + if (COFFBigObjHeader) + return COFFBigObjHeader->PointerToSymbolTable; + llvm_unreachable("no COFF header!"); + } + + uint32_t getRawNumberOfSymbols() const { + if (COFFHeader) + return COFFHeader->isImportLibrary() ? 0 : COFFHeader->NumberOfSymbols; + if (COFFBigObjHeader) + return COFFBigObjHeader->NumberOfSymbols; + llvm_unreachable("no COFF header!"); + } + + uint32_t getNumberOfSymbols() const { + if (!SymbolTable16 && !SymbolTable32) + return 0; + return getRawNumberOfSymbols(); + } + + uint32_t getStringTableSize() const { return StringTableSize; } + + const export_directory_table_entry *getExportTable() const { + return ExportDirectory; + } + + const coff_load_configuration32 *getLoadConfig32() const { + assert(!is64()); + return reinterpret_cast(LoadConfig); + } + + const coff_load_configuration64 *getLoadConfig64() const { + assert(is64()); + return reinterpret_cast(LoadConfig); + } + + const chpe_metadata *getCHPEMetadata() const { return CHPEMetadata; } + + StringRef getRelocationTypeName(uint16_t Type) const; + +protected: + void moveSymbolNext(DataRefImpl &Symb) const override; + Expected getSymbolName(DataRefImpl Symb) const override; + Expected getSymbolAddress(DataRefImpl Symb) const override; + uint32_t getSymbolAlignment(DataRefImpl Symb) const override; + uint64_t getSymbolValueImpl(DataRefImpl Symb) const override; + uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const override; + Expected getSymbolFlags(DataRefImpl Symb) const override; + Expected getSymbolType(DataRefImpl Symb) const override; + Expected getSymbolSection(DataRefImpl Symb) const override; + void moveSectionNext(DataRefImpl &Sec) const override; + Expected getSectionName(DataRefImpl Sec) const override; + uint64_t getSectionAddress(DataRefImpl Sec) const override; + uint64_t getSectionIndex(DataRefImpl Sec) const override; + uint64_t getSectionSize(DataRefImpl Sec) const override; + Expected> + getSectionContents(DataRefImpl Sec) const override; + uint64_t getSectionAlignment(DataRefImpl Sec) const override; + bool isSectionCompressed(DataRefImpl Sec) const override; + bool isSectionText(DataRefImpl Sec) const override; + bool isSectionData(DataRefImpl Sec) const override; + bool isSectionBSS(DataRefImpl Sec) const override; + bool isSectionVirtual(DataRefImpl Sec) const override; + bool isDebugSection(DataRefImpl Sec) const override; + relocation_iterator section_rel_begin(DataRefImpl Sec) const override; + relocation_iterator section_rel_end(DataRefImpl Sec) const override; + + void moveRelocationNext(DataRefImpl &Rel) const override; + uint64_t getRelocationOffset(DataRefImpl Rel) const override; + symbol_iterator getRelocationSymbol(DataRefImpl Rel) const override; + uint64_t getRelocationType(DataRefImpl Rel) const override; + void getRelocationTypeName(DataRefImpl Rel, + SmallVectorImpl &Result) const override; + +public: + basic_symbol_iterator symbol_begin() const override; + basic_symbol_iterator symbol_end() const override; + section_iterator section_begin() const override; + section_iterator section_end() const override; + + bool is64Bit() const override { return false; } + + const coff_section *getCOFFSection(const SectionRef &Section) const; + COFFSymbolRef getCOFFSymbol(const DataRefImpl &Ref) const; + COFFSymbolRef getCOFFSymbol(const SymbolRef &Symbol) const; + const coff_relocation *getCOFFRelocation(const RelocationRef &Reloc) const; + unsigned getSectionID(SectionRef Sec) const; + unsigned getSymbolSectionID(SymbolRef Sym) const; + + uint8_t getBytesInAddress() const override; + StringRef getFileFormatName() const override; + Triple::ArchType getArch() const override; + Expected getStartAddress() const override; + Expected getFeatures() const override { + return SubtargetFeatures(); + } + + import_directory_iterator import_directory_begin() const; + import_directory_iterator import_directory_end() const; + delay_import_directory_iterator delay_import_directory_begin() const; + delay_import_directory_iterator delay_import_directory_end() const; + export_directory_iterator export_directory_begin() const; + export_directory_iterator export_directory_end() const; + base_reloc_iterator base_reloc_begin() const; + base_reloc_iterator base_reloc_end() const; + const debug_directory *debug_directory_begin() const { + return DebugDirectoryBegin; + } + const debug_directory *debug_directory_end() const { + return DebugDirectoryEnd; + } + + iterator_range import_directories() const; + iterator_range + delay_import_directories() const; + iterator_range export_directories() const; + iterator_range base_relocs() const; + iterator_range debug_directories() const { + return make_range(debug_directory_begin(), debug_directory_end()); + } + + const coff_tls_directory32 *getTLSDirectory32() const { + return TLSDirectory32; + } + const coff_tls_directory64 *getTLSDirectory64() const { + return TLSDirectory64; + } + + const dos_header *getDOSHeader() const { + if (!PE32Header && !PE32PlusHeader) + return nullptr; + return reinterpret_cast(base()); + } + + const coff_file_header *getCOFFHeader() const { return COFFHeader; } + const coff_bigobj_file_header *getCOFFBigObjHeader() const { + return COFFBigObjHeader; + } + const pe32_header *getPE32Header() const { return PE32Header; } + const pe32plus_header *getPE32PlusHeader() const { return PE32PlusHeader; } + + const data_directory *getDataDirectory(uint32_t index) const; + Expected getSection(int32_t index) const; + + Expected getSymbol(uint32_t index) const { + if (index >= getNumberOfSymbols()) + return errorCodeToError(object_error::parse_failed); + if (SymbolTable16) + return COFFSymbolRef(SymbolTable16 + index); + if (SymbolTable32) + return COFFSymbolRef(SymbolTable32 + index); + return errorCodeToError(object_error::parse_failed); + } + + template + Error getAuxSymbol(uint32_t index, const T *&Res) const { + Expected S = getSymbol(index); + if (Error E = S.takeError()) + return E; + Res = reinterpret_cast(S->getRawPtr()); + return Error::success(); + } + + Expected getSymbolName(COFFSymbolRef Symbol) const; + Expected getSymbolName(const coff_symbol_generic *Symbol) const; + + ArrayRef getSymbolAuxData(COFFSymbolRef Symbol) const; + + uint32_t getSymbolIndex(COFFSymbolRef Symbol) const; + + size_t getSymbolTableEntrySize() const { + if (COFFHeader) + return sizeof(coff_symbol16); + if (COFFBigObjHeader) + return sizeof(coff_symbol32); + llvm_unreachable("null symbol table pointer!"); + } + + ArrayRef getRelocations(const coff_section *Sec) const; + + Expected getSectionName(const coff_section *Sec) const; + uint64_t getSectionSize(const coff_section *Sec) const; + Error getSectionContents(const coff_section *Sec, + ArrayRef &Res) const; + + uint64_t getImageBase() const; + Error getVaPtr(uint64_t VA, uintptr_t &Res) const; + Error getRvaPtr(uint32_t Rva, uintptr_t &Res, + const char *ErrorContext = nullptr) const; + + /// Given an RVA base and size, returns a valid array of bytes or an error + /// code if the RVA and size is not contained completely within a valid + /// section. + Error getRvaAndSizeAsBytes(uint32_t RVA, uint32_t Size, + ArrayRef &Contents, + const char *ErrorContext = nullptr) const; + + Error getHintName(uint32_t Rva, uint16_t &Hint, + StringRef &Name) const; + + /// Get PDB information out of a codeview debug directory entry. + Error getDebugPDBInfo(const debug_directory *DebugDir, + const codeview::DebugInfo *&Info, + StringRef &PDBFileName) const; + + /// Get PDB information from an executable. If the information is not present, + /// Info will be set to nullptr and PDBFileName will be empty. An error is + /// returned only on corrupt object files. Convenience accessor that can be + /// used if the debug directory is not already handy. + Error getDebugPDBInfo(const codeview::DebugInfo *&Info, + StringRef &PDBFileName) const; + + bool isRelocatableObject() const override; + bool is64() const { return PE32PlusHeader; } + + StringRef mapDebugSectionName(StringRef Name) const override; + + static bool classof(const Binary *v) { return v->isCOFF(); } +}; + +// The iterator for the import directory table. +class ImportDirectoryEntryRef { +public: + ImportDirectoryEntryRef() = default; + ImportDirectoryEntryRef(const coff_import_directory_table_entry *Table, + uint32_t I, const COFFObjectFile *Owner) + : ImportTable(Table), Index(I), OwningObject(Owner) {} + + bool operator==(const ImportDirectoryEntryRef &Other) const; + void moveNext(); + + imported_symbol_iterator imported_symbol_begin() const; + imported_symbol_iterator imported_symbol_end() const; + iterator_range imported_symbols() const; + + imported_symbol_iterator lookup_table_begin() const; + imported_symbol_iterator lookup_table_end() const; + iterator_range lookup_table_symbols() const; + + Error getName(StringRef &Result) const; + Error getImportLookupTableRVA(uint32_t &Result) const; + Error getImportAddressTableRVA(uint32_t &Result) const; + + Error + getImportTableEntry(const coff_import_directory_table_entry *&Result) const; + +private: + const coff_import_directory_table_entry *ImportTable; + uint32_t Index; + const COFFObjectFile *OwningObject = nullptr; +}; + +class DelayImportDirectoryEntryRef { +public: + DelayImportDirectoryEntryRef() = default; + DelayImportDirectoryEntryRef(const delay_import_directory_table_entry *T, + uint32_t I, const COFFObjectFile *Owner) + : Table(T), Index(I), OwningObject(Owner) {} + + bool operator==(const DelayImportDirectoryEntryRef &Other) const; + void moveNext(); + + imported_symbol_iterator imported_symbol_begin() const; + imported_symbol_iterator imported_symbol_end() const; + iterator_range imported_symbols() const; + + Error getName(StringRef &Result) const; + Error getDelayImportTable( + const delay_import_directory_table_entry *&Result) const; + Error getImportAddress(int AddrIndex, uint64_t &Result) const; + +private: + const delay_import_directory_table_entry *Table; + uint32_t Index; + const COFFObjectFile *OwningObject = nullptr; +}; + +// The iterator for the export directory table entry. +class ExportDirectoryEntryRef { +public: + ExportDirectoryEntryRef() = default; + ExportDirectoryEntryRef(const export_directory_table_entry *Table, uint32_t I, + const COFFObjectFile *Owner) + : ExportTable(Table), Index(I), OwningObject(Owner) {} + + bool operator==(const ExportDirectoryEntryRef &Other) const; + void moveNext(); + + Error getDllName(StringRef &Result) const; + Error getOrdinalBase(uint32_t &Result) const; + Error getOrdinal(uint32_t &Result) const; + Error getExportRVA(uint32_t &Result) const; + Error getSymbolName(StringRef &Result) const; + + Error isForwarder(bool &Result) const; + Error getForwardTo(StringRef &Result) const; + +private: + const export_directory_table_entry *ExportTable; + uint32_t Index; + const COFFObjectFile *OwningObject = nullptr; +}; + +class ImportedSymbolRef { +public: + ImportedSymbolRef() = default; + ImportedSymbolRef(const import_lookup_table_entry32 *Entry, uint32_t I, + const COFFObjectFile *Owner) + : Entry32(Entry), Entry64(nullptr), Index(I), OwningObject(Owner) {} + ImportedSymbolRef(const import_lookup_table_entry64 *Entry, uint32_t I, + const COFFObjectFile *Owner) + : Entry32(nullptr), Entry64(Entry), Index(I), OwningObject(Owner) {} + + bool operator==(const ImportedSymbolRef &Other) const; + void moveNext(); + + Error getSymbolName(StringRef &Result) const; + Error isOrdinal(bool &Result) const; + Error getOrdinal(uint16_t &Result) const; + Error getHintNameRVA(uint32_t &Result) const; + +private: + const import_lookup_table_entry32 *Entry32; + const import_lookup_table_entry64 *Entry64; + uint32_t Index; + const COFFObjectFile *OwningObject = nullptr; +}; + +class BaseRelocRef { +public: + BaseRelocRef() = default; + BaseRelocRef(const coff_base_reloc_block_header *Header, + const COFFObjectFile *Owner) + : Header(Header), Index(0) {} + + bool operator==(const BaseRelocRef &Other) const; + void moveNext(); + + Error getType(uint8_t &Type) const; + Error getRVA(uint32_t &Result) const; + +private: + const coff_base_reloc_block_header *Header; + uint32_t Index; +}; + +class ResourceSectionRef { +public: + ResourceSectionRef() = default; + explicit ResourceSectionRef(StringRef Ref) : BBS(Ref, support::little) {} + + Error load(const COFFObjectFile *O); + Error load(const COFFObjectFile *O, const SectionRef &S); + + Expected> + getEntryNameString(const coff_resource_dir_entry &Entry); + Expected + getEntrySubDir(const coff_resource_dir_entry &Entry); + Expected + getEntryData(const coff_resource_dir_entry &Entry); + Expected getBaseTable(); + Expected + getTableEntry(const coff_resource_dir_table &Table, uint32_t Index); + + Expected getContents(const coff_resource_data_entry &Entry); + +private: + BinaryByteStream BBS; + + SectionRef Section; + const COFFObjectFile *Obj = nullptr; + + std::vector Relocs; + + Expected getTableAtOffset(uint32_t Offset); + Expected + getTableEntryAtOffset(uint32_t Offset); + Expected + getDataEntryAtOffset(uint32_t Offset); + Expected> getDirStringAtOffset(uint32_t Offset); +}; + +// Corresponds to `_FPO_DATA` structure in the PE/COFF spec. +struct FpoData { + support::ulittle32_t Offset; // ulOffStart: Offset 1st byte of function code + support::ulittle32_t Size; // cbProcSize: # bytes in function + support::ulittle32_t NumLocals; // cdwLocals: # bytes in locals/4 + support::ulittle16_t NumParams; // cdwParams: # bytes in params/4 + support::ulittle16_t Attributes; + + // cbProlog: # bytes in prolog + int getPrologSize() const { return Attributes & 0xF; } + + // cbRegs: # regs saved + int getNumSavedRegs() const { return (Attributes >> 8) & 0x7; } + + // fHasSEH: true if seh is func + bool hasSEH() const { return (Attributes >> 9) & 1; } + + // fUseBP: true if EBP has been allocated + bool useBP() const { return (Attributes >> 10) & 1; } + + // cbFrame: frame pointer + frame_type getFP() const { return static_cast(Attributes >> 14); } +}; + +class SectionStrippedError + : public ErrorInfo { +public: + SectionStrippedError() { setErrorCode(object_error::section_stripped); } +}; + +} // end namespace object + +} // end namespace llvm + +#endif // LLVM_OBJECT_COFF_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/CVDebugRecord.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/CVDebugRecord.h new file mode 100644 index 00000000000..d41c7391f70 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/CVDebugRecord.h @@ -0,0 +1,54 @@ +//===- CVDebugRecord.h ------------------------------------------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_OBJECT_CVDEBUGRECORD_H +#define LLVM_OBJECT_CVDEBUGRECORD_H + +#include "llvm/Support/Endian.h" + +namespace llvm { +namespace OMF { +struct Signature { + enum ID : uint32_t { + PDB70 = 0x53445352, // RSDS + PDB20 = 0x3031424e, // NB10 + CV50 = 0x3131424e, // NB11 + CV41 = 0x3930424e, // NB09 + }; + + support::ulittle32_t CVSignature; + support::ulittle32_t Offset; +}; +} + +namespace codeview { +struct PDB70DebugInfo { + support::ulittle32_t CVSignature; + uint8_t Signature[16]; + support::ulittle32_t Age; + // char PDBFileName[]; +}; + +struct PDB20DebugInfo { + support::ulittle32_t CVSignature; + support::ulittle32_t Offset; + support::ulittle32_t Signature; + support::ulittle32_t Age; + // char PDBFileName[]; +}; + +union DebugInfo { + struct OMF::Signature Signature; + struct PDB20DebugInfo PDB20; + struct PDB70DebugInfo PDB70; +}; +} +} + +#endif + diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/Error.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/Error.h new file mode 100644 index 00000000000..8875fb6e1a2 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/Error.h @@ -0,0 +1,97 @@ +//===- Error.h - system_error extensions for Object -------------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This declares a new error_category for the Object library. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_OBJECT_ERROR_H +#define LLVM_OBJECT_ERROR_H + +#include "llvm/Support/Error.h" +#include + +namespace llvm { + +class Twine; + +namespace object { + +const std::error_category &object_category(); + +enum class object_error { + // Error code 0 is absent. Use std::error_code() instead. + arch_not_found = 1, + invalid_file_type, + parse_failed, + unexpected_eof, + string_table_non_null_end, + invalid_section_index, + bitcode_section_not_found, + invalid_symbol_index, + section_stripped, +}; + +inline std::error_code make_error_code(object_error e) { + return std::error_code(static_cast(e), object_category()); +} + +/// Base class for all errors indicating malformed binary files. +/// +/// Having a subclass for all malformed binary files allows archive-walking +/// code to skip malformed files without having to understand every possible +/// way that a binary file might be malformed. +/// +/// Currently inherits from ECError for easy interoperability with +/// std::error_code, but this will be removed in the future. +class BinaryError : public ErrorInfo { + void anchor() override; +public: + static char ID; + BinaryError() { + // Default to parse_failed, can be overridden with setErrorCode. + setErrorCode(make_error_code(object_error::parse_failed)); + } +}; + +/// Generic binary error. +/// +/// For errors that don't require their own specific sub-error (most errors) +/// this class can be used to describe the error via a string message. +class GenericBinaryError : public ErrorInfo { +public: + static char ID; + GenericBinaryError(const Twine &Msg); + GenericBinaryError(const Twine &Msg, object_error ECOverride); + const std::string &getMessage() const { return Msg; } + void log(raw_ostream &OS) const override; +private: + std::string Msg; +}; + +/// isNotObjectErrorInvalidFileType() is used when looping through the children +/// of an archive after calling getAsBinary() on the child and it returns an +/// llvm::Error. In the cases we want to loop through the children and ignore the +/// non-objects in the archive this is used to test the error to see if an +/// error() function needs to called on the llvm::Error. +Error isNotObjectErrorInvalidFileType(llvm::Error Err); + +inline Error createError(const Twine &Err) { + return make_error(Err, object_error::parse_failed); +} + +} // end namespace object. + +} // end namespace llvm. + +namespace std { +template <> +struct is_error_code_enum : std::true_type {}; +} + +#endif diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/ObjectFile.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/ObjectFile.h new file mode 100644 index 00000000000..2b614185c69 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/ObjectFile.h @@ -0,0 +1,665 @@ +//===- ObjectFile.h - File format independent object file -------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file declares a file format independent ObjectFile class. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_OBJECT_OBJECTFILE_H +#define LLVM_OBJECT_OBJECTFILE_H + +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/Hashing.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/iterator_range.h" +#include "llvm/BinaryFormat/Magic.h" +#include "llvm/BinaryFormat/Swift.h" +#include "llvm/Object/Binary.h" +#include "llvm/Object/Error.h" +#include "llvm/Object/SymbolicFile.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/Error.h" +#include "llvm/Support/MemoryBufferRef.h" +#include "llvm/TargetParser/Triple.h" +#include +#include +#include + +namespace llvm { + +class SubtargetFeatures; + +namespace object { + +class COFFObjectFile; +class MachOObjectFile; +class ObjectFile; +class SectionRef; +class SymbolRef; +class symbol_iterator; +class WasmObjectFile; + +using section_iterator = content_iterator; + +typedef std::function SectionFilterPredicate; +/// This is a value type class that represents a single relocation in the list +/// of relocations in the object file. +class RelocationRef { + DataRefImpl RelocationPimpl; + const ObjectFile *OwningObject = nullptr; + +public: + RelocationRef() = default; + RelocationRef(DataRefImpl RelocationP, const ObjectFile *Owner); + + bool operator==(const RelocationRef &Other) const; + + void moveNext(); + + uint64_t getOffset() const; + symbol_iterator getSymbol() const; + uint64_t getType() const; + + /// Get a string that represents the type of this relocation. + /// + /// This is for display purposes only. + void getTypeName(SmallVectorImpl &Result) const; + + DataRefImpl getRawDataRefImpl() const; + const ObjectFile *getObject() const; +}; + +using relocation_iterator = content_iterator; + +/// This is a value type class that represents a single section in the list of +/// sections in the object file. +class SectionRef { + friend class SymbolRef; + + DataRefImpl SectionPimpl; + const ObjectFile *OwningObject = nullptr; + +public: + SectionRef() = default; + SectionRef(DataRefImpl SectionP, const ObjectFile *Owner); + + bool operator==(const SectionRef &Other) const; + bool operator!=(const SectionRef &Other) const; + bool operator<(const SectionRef &Other) const; + + void moveNext(); + + Expected getName() const; + uint64_t getAddress() const; + uint64_t getIndex() const; + uint64_t getSize() const; + Expected getContents() const; + + /// Get the alignment of this section. + Align getAlignment() const; + + bool isCompressed() const; + /// Whether this section contains instructions. + bool isText() const; + /// Whether this section contains data, not instructions. + bool isData() const; + /// Whether this section contains BSS uninitialized data. + bool isBSS() const; + bool isVirtual() const; + bool isBitcode() const; + bool isStripped() const; + + /// Whether this section will be placed in the text segment, according to the + /// Berkeley size format. This is true if the section is allocatable, and + /// contains either code or readonly data. + bool isBerkeleyText() const; + /// Whether this section will be placed in the data segment, according to the + /// Berkeley size format. This is true if the section is allocatable and + /// contains data (e.g. PROGBITS), but is not text. + bool isBerkeleyData() const; + + /// Whether this section is a debug section. + bool isDebugSection() const; + + bool containsSymbol(SymbolRef S) const; + + relocation_iterator relocation_begin() const; + relocation_iterator relocation_end() const; + iterator_range relocations() const { + return make_range(relocation_begin(), relocation_end()); + } + + /// Returns the related section if this section contains relocations. The + /// returned section may or may not have applied its relocations. + Expected getRelocatedSection() const; + + DataRefImpl getRawDataRefImpl() const; + const ObjectFile *getObject() const; +}; + +struct SectionedAddress { + const static uint64_t UndefSection = UINT64_MAX; + + uint64_t Address = 0; + uint64_t SectionIndex = UndefSection; +}; + +inline bool operator<(const SectionedAddress &LHS, + const SectionedAddress &RHS) { + return std::tie(LHS.SectionIndex, LHS.Address) < + std::tie(RHS.SectionIndex, RHS.Address); +} + +inline bool operator==(const SectionedAddress &LHS, + const SectionedAddress &RHS) { + return std::tie(LHS.SectionIndex, LHS.Address) == + std::tie(RHS.SectionIndex, RHS.Address); +} + +raw_ostream &operator<<(raw_ostream &OS, const SectionedAddress &Addr); + +/// This is a value type class that represents a single symbol in the list of +/// symbols in the object file. +class SymbolRef : public BasicSymbolRef { + friend class SectionRef; + +public: + enum Type { + ST_Unknown, // Type not specified + ST_Other, + ST_Data, + ST_Debug, + ST_File, + ST_Function, + }; + + SymbolRef() = default; + SymbolRef(DataRefImpl SymbolP, const ObjectFile *Owner); + SymbolRef(const BasicSymbolRef &B) : BasicSymbolRef(B) { + assert(isa(BasicSymbolRef::getObject())); + } + + Expected getName() const; + /// Returns the symbol virtual address (i.e. address at which it will be + /// mapped). + Expected getAddress() const; + + /// Return the value of the symbol depending on the object this can be an + /// offset or a virtual address. + Expected getValue() const; + + /// Get the alignment of this symbol as the actual value (not log 2). + uint32_t getAlignment() const; + uint64_t getCommonSize() const; + Expected getType() const; + + /// Get section this symbol is defined in reference to. Result is + /// end_sections() if it is undefined or is an absolute symbol. + Expected getSection() const; + + const ObjectFile *getObject() const; +}; + +class symbol_iterator : public basic_symbol_iterator { +public: + symbol_iterator(SymbolRef Sym) : basic_symbol_iterator(Sym) {} + symbol_iterator(const basic_symbol_iterator &B) + : basic_symbol_iterator(SymbolRef(B->getRawDataRefImpl(), + cast(B->getObject()))) {} + + const SymbolRef *operator->() const { + const BasicSymbolRef &P = basic_symbol_iterator::operator *(); + return static_cast(&P); + } + + const SymbolRef &operator*() const { + const BasicSymbolRef &P = basic_symbol_iterator::operator *(); + return static_cast(P); + } +}; + +/// This class is the base class for all object file types. Concrete instances +/// of this object are created by createObjectFile, which figures out which type +/// to create. +class ObjectFile : public SymbolicFile { + virtual void anchor(); + +protected: + ObjectFile(unsigned int Type, MemoryBufferRef Source); + + const uint8_t *base() const { + return reinterpret_cast(Data.getBufferStart()); + } + + // These functions are for SymbolRef to call internally. The main goal of + // this is to allow SymbolRef::SymbolPimpl to point directly to the symbol + // entry in the memory mapped object file. SymbolPimpl cannot contain any + // virtual functions because then it could not point into the memory mapped + // file. + // + // Implementations assume that the DataRefImpl is valid and has not been + // modified externally. It's UB otherwise. + friend class SymbolRef; + + virtual Expected getSymbolName(DataRefImpl Symb) const = 0; + Error printSymbolName(raw_ostream &OS, + DataRefImpl Symb) const override; + virtual Expected getSymbolAddress(DataRefImpl Symb) const = 0; + virtual uint64_t getSymbolValueImpl(DataRefImpl Symb) const = 0; + virtual uint32_t getSymbolAlignment(DataRefImpl Symb) const; + virtual uint64_t getCommonSymbolSizeImpl(DataRefImpl Symb) const = 0; + virtual Expected getSymbolType(DataRefImpl Symb) const = 0; + virtual Expected + getSymbolSection(DataRefImpl Symb) const = 0; + + // Same as above for SectionRef. + friend class SectionRef; + + virtual void moveSectionNext(DataRefImpl &Sec) const = 0; + virtual Expected getSectionName(DataRefImpl Sec) const = 0; + virtual uint64_t getSectionAddress(DataRefImpl Sec) const = 0; + virtual uint64_t getSectionIndex(DataRefImpl Sec) const = 0; + virtual uint64_t getSectionSize(DataRefImpl Sec) const = 0; + virtual Expected> + getSectionContents(DataRefImpl Sec) const = 0; + virtual uint64_t getSectionAlignment(DataRefImpl Sec) const = 0; + virtual bool isSectionCompressed(DataRefImpl Sec) const = 0; + virtual bool isSectionText(DataRefImpl Sec) const = 0; + virtual bool isSectionData(DataRefImpl Sec) const = 0; + virtual bool isSectionBSS(DataRefImpl Sec) const = 0; + // A section is 'virtual' if its contents aren't present in the object image. + virtual bool isSectionVirtual(DataRefImpl Sec) const = 0; + virtual bool isSectionBitcode(DataRefImpl Sec) const; + virtual bool isSectionStripped(DataRefImpl Sec) const; + virtual bool isBerkeleyText(DataRefImpl Sec) const; + virtual bool isBerkeleyData(DataRefImpl Sec) const; + virtual bool isDebugSection(DataRefImpl Sec) const; + virtual relocation_iterator section_rel_begin(DataRefImpl Sec) const = 0; + virtual relocation_iterator section_rel_end(DataRefImpl Sec) const = 0; + virtual Expected getRelocatedSection(DataRefImpl Sec) const; + + // Same as above for RelocationRef. + friend class RelocationRef; + virtual void moveRelocationNext(DataRefImpl &Rel) const = 0; + virtual uint64_t getRelocationOffset(DataRefImpl Rel) const = 0; + virtual symbol_iterator getRelocationSymbol(DataRefImpl Rel) const = 0; + virtual uint64_t getRelocationType(DataRefImpl Rel) const = 0; + virtual void getRelocationTypeName(DataRefImpl Rel, + SmallVectorImpl &Result) const = 0; + + virtual llvm::binaryformat::Swift5ReflectionSectionKind + mapReflectionSectionNameToEnumValue(StringRef SectionName) const { + return llvm::binaryformat::Swift5ReflectionSectionKind::unknown; + }; + + Expected getSymbolValue(DataRefImpl Symb) const; + +public: + ObjectFile() = delete; + ObjectFile(const ObjectFile &other) = delete; + + uint64_t getCommonSymbolSize(DataRefImpl Symb) const { + Expected SymbolFlagsOrErr = getSymbolFlags(Symb); + if (!SymbolFlagsOrErr) + // TODO: Actually report errors helpfully. + report_fatal_error(SymbolFlagsOrErr.takeError()); + assert(*SymbolFlagsOrErr & SymbolRef::SF_Common); + return getCommonSymbolSizeImpl(Symb); + } + + virtual std::vector dynamic_relocation_sections() const { + return std::vector(); + } + + using symbol_iterator_range = iterator_range; + symbol_iterator_range symbols() const { + return symbol_iterator_range(symbol_begin(), symbol_end()); + } + + virtual section_iterator section_begin() const = 0; + virtual section_iterator section_end() const = 0; + + using section_iterator_range = iterator_range; + section_iterator_range sections() const { + return section_iterator_range(section_begin(), section_end()); + } + + virtual bool hasDebugInfo() const; + + /// The number of bytes used to represent an address in this object + /// file format. + virtual uint8_t getBytesInAddress() const = 0; + + virtual StringRef getFileFormatName() const = 0; + virtual Triple::ArchType getArch() const = 0; + virtual Expected getFeatures() const = 0; + virtual std::optional tryGetCPUName() const { + return std::nullopt; + }; + virtual void setARMSubArch(Triple &TheTriple) const { } + virtual Expected getStartAddress() const { + return errorCodeToError(object_error::parse_failed); + }; + + /// Create a triple from the data in this object file. + Triple makeTriple() const; + + /// Maps a debug section name to a standard DWARF section name. + virtual StringRef mapDebugSectionName(StringRef Name) const { return Name; } + + /// True if this is a relocatable object (.o/.obj). + virtual bool isRelocatableObject() const = 0; + + /// True if the reflection section can be stripped by the linker. + bool isReflectionSectionStrippable( + llvm::binaryformat::Swift5ReflectionSectionKind ReflectionSectionKind) + const; + + /// @returns Pointer to ObjectFile subclass to handle this type of object. + /// @param ObjectPath The path to the object file. ObjectPath.isObject must + /// return true. + /// Create ObjectFile from path. + static Expected> + createObjectFile(StringRef ObjectPath); + + static Expected> + createObjectFile(MemoryBufferRef Object, llvm::file_magic Type, + bool InitContent = true); + static Expected> + createObjectFile(MemoryBufferRef Object) { + return createObjectFile(Object, llvm::file_magic::unknown); + } + + static bool classof(const Binary *v) { + return v->isObject(); + } + + static Expected> + createCOFFObjectFile(MemoryBufferRef Object); + + static Expected> + createXCOFFObjectFile(MemoryBufferRef Object, unsigned FileType); + + static Expected> + createELFObjectFile(MemoryBufferRef Object, bool InitContent = true); + + static Expected> + createMachOObjectFile(MemoryBufferRef Object, + uint32_t UniversalCputype = 0, + uint32_t UniversalIndex = 0); + + static Expected> + createGOFFObjectFile(MemoryBufferRef Object); + + static Expected> + createWasmObjectFile(MemoryBufferRef Object); +}; + +/// A filtered iterator for SectionRefs that skips sections based on some given +/// predicate. +class SectionFilterIterator { +public: + SectionFilterIterator(SectionFilterPredicate Pred, + const section_iterator &Begin, + const section_iterator &End) + : Predicate(std::move(Pred)), Iterator(Begin), End(End) { + scanPredicate(); + } + const SectionRef &operator*() const { return *Iterator; } + SectionFilterIterator &operator++() { + ++Iterator; + scanPredicate(); + return *this; + } + bool operator!=(const SectionFilterIterator &Other) const { + return Iterator != Other.Iterator; + } + +private: + void scanPredicate() { + while (Iterator != End && !Predicate(*Iterator)) { + ++Iterator; + } + } + SectionFilterPredicate Predicate; + section_iterator Iterator; + section_iterator End; +}; + +/// Creates an iterator range of SectionFilterIterators for a given Object and +/// predicate. +class SectionFilter { +public: + SectionFilter(SectionFilterPredicate Pred, const ObjectFile &Obj) + : Predicate(std::move(Pred)), Object(Obj) {} + SectionFilterIterator begin() { + return SectionFilterIterator(Predicate, Object.section_begin(), + Object.section_end()); + } + SectionFilterIterator end() { + return SectionFilterIterator(Predicate, Object.section_end(), + Object.section_end()); + } + +private: + SectionFilterPredicate Predicate; + const ObjectFile &Object; +}; + +// Inline function definitions. +inline SymbolRef::SymbolRef(DataRefImpl SymbolP, const ObjectFile *Owner) + : BasicSymbolRef(SymbolP, Owner) {} + +inline Expected SymbolRef::getName() const { + return getObject()->getSymbolName(getRawDataRefImpl()); +} + +inline Expected SymbolRef::getAddress() const { + return getObject()->getSymbolAddress(getRawDataRefImpl()); +} + +inline Expected SymbolRef::getValue() const { + return getObject()->getSymbolValue(getRawDataRefImpl()); +} + +inline uint32_t SymbolRef::getAlignment() const { + return getObject()->getSymbolAlignment(getRawDataRefImpl()); +} + +inline uint64_t SymbolRef::getCommonSize() const { + return getObject()->getCommonSymbolSize(getRawDataRefImpl()); +} + +inline Expected SymbolRef::getSection() const { + return getObject()->getSymbolSection(getRawDataRefImpl()); +} + +inline Expected SymbolRef::getType() const { + return getObject()->getSymbolType(getRawDataRefImpl()); +} + +inline const ObjectFile *SymbolRef::getObject() const { + const SymbolicFile *O = BasicSymbolRef::getObject(); + return cast(O); +} + +/// SectionRef +inline SectionRef::SectionRef(DataRefImpl SectionP, + const ObjectFile *Owner) + : SectionPimpl(SectionP) + , OwningObject(Owner) {} + +inline bool SectionRef::operator==(const SectionRef &Other) const { + return OwningObject == Other.OwningObject && + SectionPimpl == Other.SectionPimpl; +} + +inline bool SectionRef::operator!=(const SectionRef &Other) const { + return !(*this == Other); +} + +inline bool SectionRef::operator<(const SectionRef &Other) const { + assert(OwningObject == Other.OwningObject); + return SectionPimpl < Other.SectionPimpl; +} + +inline void SectionRef::moveNext() { + return OwningObject->moveSectionNext(SectionPimpl); +} + +inline Expected SectionRef::getName() const { + return OwningObject->getSectionName(SectionPimpl); +} + +inline uint64_t SectionRef::getAddress() const { + return OwningObject->getSectionAddress(SectionPimpl); +} + +inline uint64_t SectionRef::getIndex() const { + return OwningObject->getSectionIndex(SectionPimpl); +} + +inline uint64_t SectionRef::getSize() const { + return OwningObject->getSectionSize(SectionPimpl); +} + +inline Expected SectionRef::getContents() const { + Expected> Res = + OwningObject->getSectionContents(SectionPimpl); + if (!Res) + return Res.takeError(); + return StringRef(reinterpret_cast(Res->data()), Res->size()); +} + +inline Align SectionRef::getAlignment() const { + return MaybeAlign(OwningObject->getSectionAlignment(SectionPimpl)) + .valueOrOne(); +} + +inline bool SectionRef::isCompressed() const { + return OwningObject->isSectionCompressed(SectionPimpl); +} + +inline bool SectionRef::isText() const { + return OwningObject->isSectionText(SectionPimpl); +} + +inline bool SectionRef::isData() const { + return OwningObject->isSectionData(SectionPimpl); +} + +inline bool SectionRef::isBSS() const { + return OwningObject->isSectionBSS(SectionPimpl); +} + +inline bool SectionRef::isVirtual() const { + return OwningObject->isSectionVirtual(SectionPimpl); +} + +inline bool SectionRef::isBitcode() const { + return OwningObject->isSectionBitcode(SectionPimpl); +} + +inline bool SectionRef::isStripped() const { + return OwningObject->isSectionStripped(SectionPimpl); +} + +inline bool SectionRef::isBerkeleyText() const { + return OwningObject->isBerkeleyText(SectionPimpl); +} + +inline bool SectionRef::isBerkeleyData() const { + return OwningObject->isBerkeleyData(SectionPimpl); +} + +inline bool SectionRef::isDebugSection() const { + return OwningObject->isDebugSection(SectionPimpl); +} + +inline relocation_iterator SectionRef::relocation_begin() const { + return OwningObject->section_rel_begin(SectionPimpl); +} + +inline relocation_iterator SectionRef::relocation_end() const { + return OwningObject->section_rel_end(SectionPimpl); +} + +inline Expected SectionRef::getRelocatedSection() const { + return OwningObject->getRelocatedSection(SectionPimpl); +} + +inline DataRefImpl SectionRef::getRawDataRefImpl() const { + return SectionPimpl; +} + +inline const ObjectFile *SectionRef::getObject() const { + return OwningObject; +} + +/// RelocationRef +inline RelocationRef::RelocationRef(DataRefImpl RelocationP, + const ObjectFile *Owner) + : RelocationPimpl(RelocationP) + , OwningObject(Owner) {} + +inline bool RelocationRef::operator==(const RelocationRef &Other) const { + return RelocationPimpl == Other.RelocationPimpl; +} + +inline void RelocationRef::moveNext() { + return OwningObject->moveRelocationNext(RelocationPimpl); +} + +inline uint64_t RelocationRef::getOffset() const { + return OwningObject->getRelocationOffset(RelocationPimpl); +} + +inline symbol_iterator RelocationRef::getSymbol() const { + return OwningObject->getRelocationSymbol(RelocationPimpl); +} + +inline uint64_t RelocationRef::getType() const { + return OwningObject->getRelocationType(RelocationPimpl); +} + +inline void RelocationRef::getTypeName(SmallVectorImpl &Result) const { + return OwningObject->getRelocationTypeName(RelocationPimpl, Result); +} + +inline DataRefImpl RelocationRef::getRawDataRefImpl() const { + return RelocationPimpl; +} + +inline const ObjectFile *RelocationRef::getObject() const { + return OwningObject; +} + +} // end namespace object + +template <> struct DenseMapInfo { + static bool isEqual(const object::SectionRef &A, + const object::SectionRef &B) { + return A == B; + } + static object::SectionRef getEmptyKey() { + return object::SectionRef({}, nullptr); + } + static object::SectionRef getTombstoneKey() { + object::DataRefImpl TS; + TS.p = (uintptr_t)-1; + return object::SectionRef(TS, nullptr); + } + static unsigned getHashValue(const object::SectionRef &Sec) { + object::DataRefImpl Raw = Sec.getRawDataRefImpl(); + return hash_combine(Raw.p, Raw.d.a, Raw.d.b); + } +}; + +} // end namespace llvm + +#endif // LLVM_OBJECT_OBJECTFILE_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/SymbolicFile.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/SymbolicFile.h new file mode 100644 index 00000000000..b13588c147d --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Object/SymbolicFile.h @@ -0,0 +1,221 @@ +//===- SymbolicFile.h - Interface that only provides symbols ----*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file declares the SymbolicFile interface. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_OBJECT_SYMBOLICFILE_H +#define LLVM_OBJECT_SYMBOLICFILE_H + +#include "llvm/ADT/iterator_range.h" +#include "llvm/BinaryFormat/Magic.h" +#include "llvm/Object/Binary.h" +#include "llvm/Support/Error.h" +#include "llvm/Support/Format.h" +#include "llvm/Support/MemoryBufferRef.h" +#include +#include +#include +#include +#include + +namespace llvm { + +class LLVMContext; +class raw_ostream; + +namespace object { + +union DataRefImpl { + // This entire union should probably be a + // char[max(8, sizeof(uintptr_t))] and require the impl to cast. + struct { + uint32_t a, b; + } d; + uintptr_t p; + + DataRefImpl() { std::memset(this, 0, sizeof(DataRefImpl)); } +}; + +template +OStream& operator<<(OStream &OS, const DataRefImpl &D) { + OS << "(" << format("0x%08" PRIxPTR, D.p) << " (" << format("0x%08x", D.d.a) + << ", " << format("0x%08x", D.d.b) << "))"; + return OS; +} + +inline bool operator==(const DataRefImpl &a, const DataRefImpl &b) { + // Check bitwise identical. This is the only legal way to compare a union w/o + // knowing which member is in use. + return std::memcmp(&a, &b, sizeof(DataRefImpl)) == 0; +} + +inline bool operator!=(const DataRefImpl &a, const DataRefImpl &b) { + return !operator==(a, b); +} + +inline bool operator<(const DataRefImpl &a, const DataRefImpl &b) { + // Check bitwise identical. This is the only legal way to compare a union w/o + // knowing which member is in use. + return std::memcmp(&a, &b, sizeof(DataRefImpl)) < 0; +} + +template class content_iterator { + content_type Current; + +public: + using iterator_category = std::forward_iterator_tag; + using value_type = content_type; + using difference_type = std::ptrdiff_t; + using pointer = value_type *; + using reference = value_type &; + + content_iterator(content_type symb) : Current(std::move(symb)) {} + + const content_type *operator->() const { return &Current; } + + const content_type &operator*() const { return Current; } + + bool operator==(const content_iterator &other) const { + return Current == other.Current; + } + + bool operator!=(const content_iterator &other) const { + return !(*this == other); + } + + content_iterator &operator++() { // preincrement + Current.moveNext(); + return *this; + } +}; + +class SymbolicFile; + +/// This is a value type class that represents a single symbol in the list of +/// symbols in the object file. +class BasicSymbolRef { + DataRefImpl SymbolPimpl; + const SymbolicFile *OwningObject = nullptr; + +public: + enum Flags : unsigned { + SF_None = 0, + SF_Undefined = 1U << 0, // Symbol is defined in another object file + SF_Global = 1U << 1, // Global symbol + SF_Weak = 1U << 2, // Weak symbol + SF_Absolute = 1U << 3, // Absolute symbol + SF_Common = 1U << 4, // Symbol has common linkage + SF_Indirect = 1U << 5, // Symbol is an alias to another symbol + SF_Exported = 1U << 6, // Symbol is visible to other DSOs + SF_FormatSpecific = 1U << 7, // Specific to the object file format + // (e.g. section symbols) + SF_Thumb = 1U << 8, // Thumb symbol in a 32-bit ARM binary + SF_Hidden = 1U << 9, // Symbol has hidden visibility + SF_Const = 1U << 10, // Symbol value is constant + SF_Executable = 1U << 11, // Symbol points to an executable section + // (IR only) + }; + + BasicSymbolRef() = default; + BasicSymbolRef(DataRefImpl SymbolP, const SymbolicFile *Owner); + + bool operator==(const BasicSymbolRef &Other) const; + bool operator<(const BasicSymbolRef &Other) const; + + void moveNext(); + + Error printName(raw_ostream &OS) const; + + /// Get symbol flags (bitwise OR of SymbolRef::Flags) + Expected getFlags() const; + + DataRefImpl getRawDataRefImpl() const; + const SymbolicFile *getObject() const; +}; + +using basic_symbol_iterator = content_iterator; + +class SymbolicFile : public Binary { +public: + SymbolicFile(unsigned int Type, MemoryBufferRef Source); + ~SymbolicFile() override; + + // virtual interface. + virtual void moveSymbolNext(DataRefImpl &Symb) const = 0; + + virtual Error printSymbolName(raw_ostream &OS, DataRefImpl Symb) const = 0; + + virtual Expected getSymbolFlags(DataRefImpl Symb) const = 0; + + virtual basic_symbol_iterator symbol_begin() const = 0; + + virtual basic_symbol_iterator symbol_end() const = 0; + + virtual bool is64Bit() const = 0; + + // convenience wrappers. + using basic_symbol_iterator_range = iterator_range; + basic_symbol_iterator_range symbols() const { + return basic_symbol_iterator_range(symbol_begin(), symbol_end()); + } + + // construction aux. + static Expected> + createSymbolicFile(MemoryBufferRef Object, llvm::file_magic Type, + LLVMContext *Context, bool InitContent = true); + + static Expected> + createSymbolicFile(MemoryBufferRef Object) { + return createSymbolicFile(Object, llvm::file_magic::unknown, nullptr); + } + + static bool classof(const Binary *v) { + return v->isSymbolic(); + } + + static bool isSymbolicFile(file_magic Type, const LLVMContext *Context); +}; + +inline BasicSymbolRef::BasicSymbolRef(DataRefImpl SymbolP, + const SymbolicFile *Owner) + : SymbolPimpl(SymbolP), OwningObject(Owner) {} + +inline bool BasicSymbolRef::operator==(const BasicSymbolRef &Other) const { + return SymbolPimpl == Other.SymbolPimpl; +} + +inline bool BasicSymbolRef::operator<(const BasicSymbolRef &Other) const { + return SymbolPimpl < Other.SymbolPimpl; +} + +inline void BasicSymbolRef::moveNext() { + return OwningObject->moveSymbolNext(SymbolPimpl); +} + +inline Error BasicSymbolRef::printName(raw_ostream &OS) const { + return OwningObject->printSymbolName(OS, SymbolPimpl); +} + +inline Expected BasicSymbolRef::getFlags() const { + return OwningObject->getSymbolFlags(SymbolPimpl); +} + +inline DataRefImpl BasicSymbolRef::getRawDataRefImpl() const { + return SymbolPimpl; +} + +inline const SymbolicFile *BasicSymbolRef::getObject() const { + return OwningObject; +} + +} // end namespace object +} // end namespace llvm + +#endif // LLVM_OBJECT_SYMBOLICFILE_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/BinaryByteStream.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/BinaryByteStream.h new file mode 100644 index 00000000000..474a8df3ab3 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/BinaryByteStream.h @@ -0,0 +1,270 @@ +//===- BinaryByteStream.h ---------------------------------------*- C++ -*-===// +// +// 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 +//===----------------------------------------------------------------------===// +// A BinaryStream which stores data in a single continguous memory buffer. +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_BINARYBYTESTREAM_H +#define LLVM_SUPPORT_BINARYBYTESTREAM_H + +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/Support/BinaryStream.h" +#include "llvm/Support/BinaryStreamError.h" +#include "llvm/Support/Error.h" +#include "llvm/Support/FileOutputBuffer.h" +#include "llvm/Support/MemoryBuffer.h" +#include +#include +#include + +namespace llvm { + +/// An implementation of BinaryStream which holds its entire data set +/// in a single contiguous buffer. BinaryByteStream guarantees that no read +/// operation will ever incur a copy. Note that BinaryByteStream does not +/// own the underlying buffer. +class BinaryByteStream : public BinaryStream { +public: + BinaryByteStream() = default; + BinaryByteStream(ArrayRef Data, llvm::support::endianness Endian) + : Endian(Endian), Data(Data) {} + BinaryByteStream(StringRef Data, llvm::support::endianness Endian) + : Endian(Endian), Data(Data.bytes_begin(), Data.bytes_end()) {} + + llvm::support::endianness getEndian() const override { return Endian; } + + Error readBytes(uint64_t Offset, uint64_t Size, + ArrayRef &Buffer) override { + if (auto EC = checkOffsetForRead(Offset, Size)) + return EC; + Buffer = Data.slice(Offset, Size); + return Error::success(); + } + + Error readLongestContiguousChunk(uint64_t Offset, + ArrayRef &Buffer) override { + if (auto EC = checkOffsetForRead(Offset, 1)) + return EC; + Buffer = Data.slice(Offset); + return Error::success(); + } + + uint64_t getLength() override { return Data.size(); } + + ArrayRef data() const { return Data; } + + StringRef str() const { + const char *CharData = reinterpret_cast(Data.data()); + return StringRef(CharData, Data.size()); + } + +protected: + llvm::support::endianness Endian; + ArrayRef Data; +}; + +/// An implementation of BinaryStream whose data is backed by an llvm +/// MemoryBuffer object. MemoryBufferByteStream owns the MemoryBuffer in +/// question. As with BinaryByteStream, reading from a MemoryBufferByteStream +/// will never cause a copy. +class MemoryBufferByteStream : public BinaryByteStream { +public: + MemoryBufferByteStream(std::unique_ptr Buffer, + llvm::support::endianness Endian) + : BinaryByteStream(Buffer->getBuffer(), Endian), + MemBuffer(std::move(Buffer)) {} + + std::unique_ptr MemBuffer; +}; + +/// An implementation of BinaryStream which holds its entire data set +/// in a single contiguous buffer. As with BinaryByteStream, the mutable +/// version also guarantees that no read operation will ever incur a copy, +/// and similarly it does not own the underlying buffer. +class MutableBinaryByteStream : public WritableBinaryStream { +public: + MutableBinaryByteStream() = default; + MutableBinaryByteStream(MutableArrayRef Data, + llvm::support::endianness Endian) + : Data(Data), ImmutableStream(Data, Endian) {} + + llvm::support::endianness getEndian() const override { + return ImmutableStream.getEndian(); + } + + Error readBytes(uint64_t Offset, uint64_t Size, + ArrayRef &Buffer) override { + return ImmutableStream.readBytes(Offset, Size, Buffer); + } + + Error readLongestContiguousChunk(uint64_t Offset, + ArrayRef &Buffer) override { + return ImmutableStream.readLongestContiguousChunk(Offset, Buffer); + } + + uint64_t getLength() override { return ImmutableStream.getLength(); } + + Error writeBytes(uint64_t Offset, ArrayRef Buffer) override { + if (Buffer.empty()) + return Error::success(); + + if (auto EC = checkOffsetForWrite(Offset, Buffer.size())) + return EC; + + uint8_t *DataPtr = const_cast(Data.data()); + ::memcpy(DataPtr + Offset, Buffer.data(), Buffer.size()); + return Error::success(); + } + + Error commit() override { return Error::success(); } + + MutableArrayRef data() const { return Data; } + +private: + MutableArrayRef Data; + BinaryByteStream ImmutableStream; +}; + +/// An implementation of WritableBinaryStream which can write at its end +/// causing the underlying data to grow. This class owns the underlying data. +class AppendingBinaryByteStream : public WritableBinaryStream { + std::vector Data; + llvm::support::endianness Endian = llvm::support::little; + +public: + AppendingBinaryByteStream() = default; + AppendingBinaryByteStream(llvm::support::endianness Endian) + : Endian(Endian) {} + + void clear() { Data.clear(); } + + llvm::support::endianness getEndian() const override { return Endian; } + + Error readBytes(uint64_t Offset, uint64_t Size, + ArrayRef &Buffer) override { + if (auto EC = checkOffsetForWrite(Offset, Buffer.size())) + return EC; + + Buffer = ArrayRef(Data).slice(Offset, Size); + return Error::success(); + } + + void insert(uint64_t Offset, ArrayRef Bytes) { + Data.insert(Data.begin() + Offset, Bytes.begin(), Bytes.end()); + } + + Error readLongestContiguousChunk(uint64_t Offset, + ArrayRef &Buffer) override { + if (auto EC = checkOffsetForWrite(Offset, 1)) + return EC; + + Buffer = ArrayRef(Data).slice(Offset); + return Error::success(); + } + + uint64_t getLength() override { return Data.size(); } + + Error writeBytes(uint64_t Offset, ArrayRef Buffer) override { + if (Buffer.empty()) + return Error::success(); + + // This is well-defined for any case except where offset is strictly + // greater than the current length. If offset is equal to the current + // length, we can still grow. If offset is beyond the current length, we + // would have to decide how to deal with the intermediate uninitialized + // bytes. So we punt on that case for simplicity and just say it's an + // error. + if (Offset > getLength()) + return make_error(stream_error_code::invalid_offset); + + uint64_t RequiredSize = Offset + Buffer.size(); + if (RequiredSize > Data.size()) + Data.resize(RequiredSize); + + ::memcpy(Data.data() + Offset, Buffer.data(), Buffer.size()); + return Error::success(); + } + + Error commit() override { return Error::success(); } + + /// Return the properties of this stream. + BinaryStreamFlags getFlags() const override { return BSF_Write | BSF_Append; } + + MutableArrayRef data() { return Data; } +}; + +/// An implementation of WritableBinaryStream backed by an llvm +/// FileOutputBuffer. +class FileBufferByteStream : public WritableBinaryStream { +private: + class StreamImpl : public MutableBinaryByteStream { + public: + StreamImpl(std::unique_ptr Buffer, + llvm::support::endianness Endian) + : MutableBinaryByteStream( + MutableArrayRef(Buffer->getBufferStart(), + Buffer->getBufferEnd()), + Endian), + FileBuffer(std::move(Buffer)) {} + + Error commit() override { + if (FileBuffer->commit()) + return make_error( + stream_error_code::filesystem_error); + return Error::success(); + } + + /// Returns a pointer to the start of the buffer. + uint8_t *getBufferStart() const { return FileBuffer->getBufferStart(); } + + /// Returns a pointer to the end of the buffer. + uint8_t *getBufferEnd() const { return FileBuffer->getBufferEnd(); } + + private: + std::unique_ptr FileBuffer; + }; + +public: + FileBufferByteStream(std::unique_ptr Buffer, + llvm::support::endianness Endian) + : Impl(std::move(Buffer), Endian) {} + + llvm::support::endianness getEndian() const override { + return Impl.getEndian(); + } + + Error readBytes(uint64_t Offset, uint64_t Size, + ArrayRef &Buffer) override { + return Impl.readBytes(Offset, Size, Buffer); + } + + Error readLongestContiguousChunk(uint64_t Offset, + ArrayRef &Buffer) override { + return Impl.readLongestContiguousChunk(Offset, Buffer); + } + + uint64_t getLength() override { return Impl.getLength(); } + + Error writeBytes(uint64_t Offset, ArrayRef Data) override { + return Impl.writeBytes(Offset, Data); + } + + Error commit() override { return Impl.commit(); } + + /// Returns a pointer to the start of the buffer. + uint8_t *getBufferStart() const { return Impl.getBufferStart(); } + + /// Returns a pointer to the end of the buffer. + uint8_t *getBufferEnd() const { return Impl.getBufferEnd(); } + +private: + StreamImpl Impl; +}; + +} // end namespace llvm + +#endif // LLVM_SUPPORT_BINARYBYTESTREAM_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/BinaryStream.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/BinaryStream.h new file mode 100644 index 00000000000..e87129d8c20 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/BinaryStream.h @@ -0,0 +1,101 @@ +//===- BinaryStream.h - Base interface for a stream of data -----*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_BINARYSTREAM_H +#define LLVM_SUPPORT_BINARYSTREAM_H + +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/BitmaskEnum.h" +#include "llvm/Support/BinaryStreamError.h" +#include "llvm/Support/Endian.h" +#include "llvm/Support/Error.h" +#include + +namespace llvm { + +enum BinaryStreamFlags { + BSF_None = 0, + BSF_Write = 1, // Stream supports writing. + BSF_Append = 2, // Writing can occur at offset == length. + LLVM_MARK_AS_BITMASK_ENUM(/* LargestValue = */ BSF_Append) +}; + +/// An interface for accessing data in a stream-like format, but which +/// discourages copying. Instead of specifying a buffer in which to copy +/// data on a read, the API returns an ArrayRef to data owned by the stream's +/// implementation. Since implementations may not necessarily store data in a +/// single contiguous buffer (or even in memory at all), in such cases a it may +/// be necessary for an implementation to cache such a buffer so that it can +/// return it. +class BinaryStream { +public: + virtual ~BinaryStream() = default; + + virtual llvm::support::endianness getEndian() const = 0; + + /// Given an offset into the stream and a number of bytes, attempt to + /// read the bytes and set the output ArrayRef to point to data owned by the + /// stream. + virtual Error readBytes(uint64_t Offset, uint64_t Size, + ArrayRef &Buffer) = 0; + + /// Given an offset into the stream, read as much as possible without + /// copying any data. + virtual Error readLongestContiguousChunk(uint64_t Offset, + ArrayRef &Buffer) = 0; + + /// Return the number of bytes of data in this stream. + virtual uint64_t getLength() = 0; + + /// Return the properties of this stream. + virtual BinaryStreamFlags getFlags() const { return BSF_None; } + +protected: + Error checkOffsetForRead(uint64_t Offset, uint64_t DataSize) { + if (Offset > getLength()) + return make_error(stream_error_code::invalid_offset); + if (getLength() < DataSize + Offset) + return make_error(stream_error_code::stream_too_short); + return Error::success(); + } +}; + +/// A BinaryStream which can be read from as well as written to. Note +/// that writing to a BinaryStream always necessitates copying from the input +/// buffer to the stream's backing store. Streams are assumed to be buffered +/// so that to be portable it is necessary to call commit() on the stream when +/// all data has been written. +class WritableBinaryStream : public BinaryStream { +public: + ~WritableBinaryStream() override = default; + + /// Attempt to write the given bytes into the stream at the desired + /// offset. This will always necessitate a copy. Cannot shrink or grow the + /// stream, only writes into existing allocated space. + virtual Error writeBytes(uint64_t Offset, ArrayRef Data) = 0; + + /// For buffered streams, commits changes to the backing store. + virtual Error commit() = 0; + + /// Return the properties of this stream. + BinaryStreamFlags getFlags() const override { return BSF_Write; } + +protected: + Error checkOffsetForWrite(uint64_t Offset, uint64_t DataSize) { + if (!(getFlags() & BSF_Append)) + return checkOffsetForRead(Offset, DataSize); + + if (Offset > getLength()) + return make_error(stream_error_code::invalid_offset); + return Error::success(); + } +}; + +} // end namespace llvm + +#endif // LLVM_SUPPORT_BINARYSTREAM_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/BinaryStreamError.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/BinaryStreamError.h new file mode 100644 index 00000000000..cf6e034ffd2 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/BinaryStreamError.h @@ -0,0 +1,47 @@ +//===- BinaryStreamError.h - Error extensions for Binary Streams *- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_BINARYSTREAMERROR_H +#define LLVM_SUPPORT_BINARYSTREAMERROR_H + +#include "llvm/ADT/StringRef.h" +#include "llvm/Support/Error.h" + +#include + +namespace llvm { +enum class stream_error_code { + unspecified, + stream_too_short, + invalid_array_size, + invalid_offset, + filesystem_error +}; + +/// Base class for errors originating when parsing raw PDB files +class BinaryStreamError : public ErrorInfo { +public: + static char ID; + explicit BinaryStreamError(stream_error_code C); + explicit BinaryStreamError(StringRef Context); + BinaryStreamError(stream_error_code C, StringRef Context); + + void log(raw_ostream &OS) const override; + std::error_code convertToErrorCode() const override; + + StringRef getErrorMessage() const; + + stream_error_code getErrorCode() const { return Code; } + +private: + std::string ErrMsg; + stream_error_code Code; +}; +} // namespace llvm + +#endif // LLVM_SUPPORT_BINARYSTREAMERROR_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/CBindingWrapping.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/CBindingWrapping.h new file mode 100644 index 00000000000..46d6b4e3fa7 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/CBindingWrapping.h @@ -0,0 +1,46 @@ +//===- llvm/Support/CBindingWrapping.h - C Interface Wrapping ---*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file declares the wrapping macros for the C interface. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_CBINDINGWRAPPING_H +#define LLVM_SUPPORT_CBINDINGWRAPPING_H + +#include "llvm-c/Types.h" +#include "llvm/Support/Casting.h" + +#define DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref) \ + inline ty *unwrap(ref P) { \ + return reinterpret_cast(P); \ + } \ + \ + inline ref wrap(const ty *P) { \ + return reinterpret_cast(const_cast(P)); \ + } + +#define DEFINE_ISA_CONVERSION_FUNCTIONS(ty, ref) \ + DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref) \ + \ + template \ + inline T *unwrap(ref P) { \ + return cast(unwrap(P)); \ + } + +#define DEFINE_STDCXX_CONVERSION_FUNCTIONS(ty, ref) \ + DEFINE_SIMPLE_CONVERSION_FUNCTIONS(ty, ref) \ + \ + template \ + inline T *unwrap(ref P) { \ + T *Q = (T*)unwrap(P); \ + assert(Q && "Invalid cast!"); \ + return Q; \ + } + +#endif diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/ConvertUTF.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/ConvertUTF.h new file mode 100644 index 00000000000..c892bb3c03c --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/ConvertUTF.h @@ -0,0 +1,348 @@ +/*===--- ConvertUTF.h - Universal Character Names conversions ---------------=== + * + * 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 + * + *==------------------------------------------------------------------------==*/ +/* + * Copyright © 1991-2015 Unicode, Inc. All rights reserved. + * Distributed under the Terms of Use in + * http://www.unicode.org/copyright.html. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of the Unicode data files and any associated documentation + * (the "Data Files") or Unicode software and any associated documentation + * (the "Software") to deal in the Data Files or Software + * without restriction, including without limitation the rights to use, + * copy, modify, merge, publish, distribute, and/or sell copies of + * the Data Files or Software, and to permit persons to whom the Data Files + * or Software are furnished to do so, provided that + * (a) this copyright and permission notice appear with all copies + * of the Data Files or Software, + * (b) this copyright and permission notice appear in associated + * documentation, and + * (c) there is clear notice in each modified Data File or in the Software + * as well as in the documentation associated with the Data File(s) or + * Software that the data or software has been modified. + * + * THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF + * ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT OF THIRD PARTY RIGHTS. + * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN THIS + * NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL + * DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, + * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER + * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + * PERFORMANCE OF THE DATA FILES OR SOFTWARE. + * + * Except as contained in this notice, the name of a copyright holder + * shall not be used in advertising or otherwise to promote the sale, + * use or other dealings in these Data Files or Software without prior + * written authorization of the copyright holder. + */ + +/* --------------------------------------------------------------------- + + Conversions between UTF32, UTF-16, and UTF-8. Header file. + + Several funtions are included here, forming a complete set of + conversions between the three formats. UTF-7 is not included + here, but is handled in a separate source file. + + Each of these routines takes pointers to input buffers and output + buffers. The input buffers are const. + + Each routine converts the text between *sourceStart and sourceEnd, + putting the result into the buffer between *targetStart and + targetEnd. Note: the end pointers are *after* the last item: e.g. + *(sourceEnd - 1) is the last item. + + The return result indicates whether the conversion was successful, + and if not, whether the problem was in the source or target buffers. + (Only the first encountered problem is indicated.) + + After the conversion, *sourceStart and *targetStart are both + updated to point to the end of last text successfully converted in + the respective buffers. + + Input parameters: + sourceStart - pointer to a pointer to the source buffer. + The contents of this are modified on return so that + it points at the next thing to be converted. + targetStart - similarly, pointer to pointer to the target buffer. + sourceEnd, targetEnd - respectively pointers to the ends of the + two buffers, for overflow checking only. + + These conversion functions take a ConversionFlags argument. When this + flag is set to strict, both irregular sequences and isolated surrogates + will cause an error. When the flag is set to lenient, both irregular + sequences and isolated surrogates are converted. + + Whether the flag is strict or lenient, all illegal sequences will cause + an error return. This includes sequences such as: , , + or in UTF-8, and values above 0x10FFFF in UTF-32. Conformant code + must check for illegal sequences. + + When the flag is set to lenient, characters over 0x10FFFF are converted + to the replacement character; otherwise (when the flag is set to strict) + they constitute an error. + + Output parameters: + The value "sourceIllegal" is returned from some routines if the input + sequence is malformed. When "sourceIllegal" is returned, the source + value will point to the illegal value that caused the problem. E.g., + in UTF-8 when a sequence is malformed, it points to the start of the + malformed sequence. + + Author: Mark E. Davis, 1994. + Rev History: Rick McGowan, fixes & updates May 2001. + Fixes & updates, Sept 2001. + +------------------------------------------------------------------------ */ + +#ifndef LLVM_SUPPORT_CONVERTUTF_H +#define LLVM_SUPPORT_CONVERTUTF_H + +#include +#include + +#if defined(_WIN32) +#include +#endif + +// Wrap everything in namespace llvm so that programs can link with llvm and +// their own version of the unicode libraries. + +namespace llvm { + +/* --------------------------------------------------------------------- + The following 4 definitions are compiler-specific. + The C standard does not guarantee that wchar_t has at least + 16 bits, so wchar_t is no less portable than unsigned short! + All should be unsigned values to avoid sign extension during + bit mask & shift operations. +------------------------------------------------------------------------ */ + +typedef unsigned int UTF32; /* at least 32 bits */ +typedef unsigned short UTF16; /* at least 16 bits */ +typedef unsigned char UTF8; /* typically 8 bits */ +typedef unsigned char Boolean; /* 0 or 1 */ + +/* Some fundamental constants */ +#define UNI_REPLACEMENT_CHAR (UTF32)0x0000FFFD +#define UNI_MAX_BMP (UTF32)0x0000FFFF +#define UNI_MAX_UTF16 (UTF32)0x0010FFFF +#define UNI_MAX_UTF32 (UTF32)0x7FFFFFFF +#define UNI_MAX_LEGAL_UTF32 (UTF32)0x0010FFFF + +#define UNI_MAX_UTF8_BYTES_PER_CODE_POINT 4 + +#define UNI_UTF16_BYTE_ORDER_MARK_NATIVE 0xFEFF +#define UNI_UTF16_BYTE_ORDER_MARK_SWAPPED 0xFFFE + +#define UNI_UTF32_BYTE_ORDER_MARK_NATIVE 0x0000FEFF +#define UNI_UTF32_BYTE_ORDER_MARK_SWAPPED 0xFFFE0000 + +typedef enum { + conversionOK, /* conversion successful */ + sourceExhausted, /* partial character in source, but hit end */ + targetExhausted, /* insuff. room in target for conversion */ + sourceIllegal /* source sequence is illegal/malformed */ +} ConversionResult; + +typedef enum { + strictConversion = 0, + lenientConversion +} ConversionFlags; + +ConversionResult ConvertUTF8toUTF16 ( + const UTF8** sourceStart, const UTF8* sourceEnd, + UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags); + +/** + * Convert a partial UTF8 sequence to UTF32. If the sequence ends in an + * incomplete code unit sequence, returns \c sourceExhausted. + */ +ConversionResult ConvertUTF8toUTF32Partial( + const UTF8** sourceStart, const UTF8* sourceEnd, + UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); + +/** + * Convert a partial UTF8 sequence to UTF32. If the sequence ends in an + * incomplete code unit sequence, returns \c sourceIllegal. + */ +ConversionResult ConvertUTF8toUTF32( + const UTF8** sourceStart, const UTF8* sourceEnd, + UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); + +ConversionResult ConvertUTF16toUTF8 ( + const UTF16** sourceStart, const UTF16* sourceEnd, + UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags); + +ConversionResult ConvertUTF32toUTF8 ( + const UTF32** sourceStart, const UTF32* sourceEnd, + UTF8** targetStart, UTF8* targetEnd, ConversionFlags flags); + +ConversionResult ConvertUTF16toUTF32 ( + const UTF16** sourceStart, const UTF16* sourceEnd, + UTF32** targetStart, UTF32* targetEnd, ConversionFlags flags); + +ConversionResult ConvertUTF32toUTF16 ( + const UTF32** sourceStart, const UTF32* sourceEnd, + UTF16** targetStart, UTF16* targetEnd, ConversionFlags flags); + +Boolean isLegalUTF8Sequence(const UTF8 *source, const UTF8 *sourceEnd); + +Boolean isLegalUTF8String(const UTF8 **source, const UTF8 *sourceEnd); + +unsigned getUTF8SequenceSize(const UTF8 *source, const UTF8 *sourceEnd); + +unsigned getNumBytesForUTF8(UTF8 firstByte); + +/*************************************************************************/ +/* Below are LLVM-specific wrappers of the functions above. */ + +template class ArrayRef; +template class SmallVectorImpl; +class StringRef; + +/** + * Convert an UTF8 StringRef to UTF8, UTF16, or UTF32 depending on + * WideCharWidth. The converted data is written to ResultPtr, which needs to + * point to at least WideCharWidth * (Source.Size() + 1) bytes. On success, + * ResultPtr will point one after the end of the copied string. On failure, + * ResultPtr will not be changed, and ErrorPtr will be set to the location of + * the first character which could not be converted. + * \return true on success. + */ +bool ConvertUTF8toWide(unsigned WideCharWidth, llvm::StringRef Source, + char *&ResultPtr, const UTF8 *&ErrorPtr); + +/** +* Converts a UTF-8 StringRef to a std::wstring. +* \return true on success. +*/ +bool ConvertUTF8toWide(llvm::StringRef Source, std::wstring &Result); + +/** +* Converts a UTF-8 C-string to a std::wstring. +* \return true on success. +*/ +bool ConvertUTF8toWide(const char *Source, std::wstring &Result); + +/** +* Converts a std::wstring to a UTF-8 encoded std::string. +* \return true on success. +*/ +bool convertWideToUTF8(const std::wstring &Source, std::string &Result); + + +/** + * Convert an Unicode code point to UTF8 sequence. + * + * \param Source a Unicode code point. + * \param [in,out] ResultPtr pointer to the output buffer, needs to be at least + * \c UNI_MAX_UTF8_BYTES_PER_CODE_POINT bytes. On success \c ResultPtr is + * updated one past end of the converted sequence. + * + * \returns true on success. + */ +bool ConvertCodePointToUTF8(unsigned Source, char *&ResultPtr); + +/** + * Convert the first UTF8 sequence in the given source buffer to a UTF32 + * code point. + * + * \param [in,out] source A pointer to the source buffer. If the conversion + * succeeds, this pointer will be updated to point to the byte just past the + * end of the converted sequence. + * \param sourceEnd A pointer just past the end of the source buffer. + * \param [out] target The converted code + * \param flags Whether the conversion is strict or lenient. + * + * \returns conversionOK on success + * + * \sa ConvertUTF8toUTF32 + */ +inline ConversionResult convertUTF8Sequence(const UTF8 **source, + const UTF8 *sourceEnd, + UTF32 *target, + ConversionFlags flags) { + if (*source == sourceEnd) + return sourceExhausted; + unsigned size = getNumBytesForUTF8(**source); + if ((ptrdiff_t)size > sourceEnd - *source) + return sourceExhausted; + return ConvertUTF8toUTF32(source, *source + size, &target, target + 1, flags); +} + +/** + * Returns true if a blob of text starts with a UTF-16 big or little endian byte + * order mark. + */ +bool hasUTF16ByteOrderMark(ArrayRef SrcBytes); + +/** + * Converts a stream of raw bytes assumed to be UTF16 into a UTF8 std::string. + * + * \param [in] SrcBytes A buffer of what is assumed to be UTF-16 encoded text. + * \param [out] Out Converted UTF-8 is stored here on success. + * \returns true on success + */ +bool convertUTF16ToUTF8String(ArrayRef SrcBytes, std::string &Out); + +/** +* Converts a UTF16 string into a UTF8 std::string. +* +* \param [in] Src A buffer of UTF-16 encoded text. +* \param [out] Out Converted UTF-8 is stored here on success. +* \returns true on success +*/ +bool convertUTF16ToUTF8String(ArrayRef Src, std::string &Out); + +/** + * Converts a stream of raw bytes assumed to be UTF32 into a UTF8 std::string. + * + * \param [in] SrcBytes A buffer of what is assumed to be UTF-32 encoded text. + * \param [out] Out Converted UTF-8 is stored here on success. + * \returns true on success + */ +bool convertUTF32ToUTF8String(ArrayRef SrcBytes, std::string &Out); + +/** + * Converts a UTF32 string into a UTF8 std::string. + * + * \param [in] Src A buffer of UTF-32 encoded text. + * \param [out] Out Converted UTF-8 is stored here on success. + * \returns true on success + */ +bool convertUTF32ToUTF8String(ArrayRef Src, std::string &Out); + +/** + * Converts a UTF-8 string into a UTF-16 string with native endianness. + * + * \returns true on success + */ +bool convertUTF8ToUTF16String(StringRef SrcUTF8, + SmallVectorImpl &DstUTF16); + +#if defined(_WIN32) +namespace sys { +namespace windows { +std::error_code UTF8ToUTF16(StringRef utf8, SmallVectorImpl &utf16); +/// Convert to UTF16 from the current code page used in the system +std::error_code CurCPToUTF16(StringRef utf8, SmallVectorImpl &utf16); +std::error_code UTF16ToUTF8(const wchar_t *utf16, size_t utf16_len, + SmallVectorImpl &utf8); +/// Convert from UTF16 to the current code page used in the system +std::error_code UTF16ToCurCP(const wchar_t *utf16, size_t utf16_len, + SmallVectorImpl &utf8); +} // namespace windows +} // namespace sys +#endif + +} /* end namespace llvm */ + +#endif diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/DataTypes.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/DataTypes.h new file mode 100644 index 00000000000..00eab0ed3e6 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/DataTypes.h @@ -0,0 +1,21 @@ +//===-- llvm/Support/DataTypes.h - Define fixed size types ------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// Due to layering constraints (Support depends on llvm-c) this is a thin +// wrapper around the implementation that lives in llvm-c, though most clients +// can/should think of this as being provided by Support for simplicity (not +// many clients are aware of their dependency on llvm-c). +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_DATATYPES_H +#define LLVM_SUPPORT_DATATYPES_H + +#include "llvm-c/DataTypes.h" + +#endif // LLVM_SUPPORT_DATATYPES_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/Debug.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/Debug.h new file mode 100644 index 00000000000..5788ab3b213 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/Debug.h @@ -0,0 +1,105 @@ +//===- llvm/Support/Debug.h - Easy way to add debug output ------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file implements a handy way of adding debugging information to your +// code, without it being enabled all of the time, and without having to add +// command line options to enable it. +// +// In particular, just wrap your code with the LLVM_DEBUG() macro, and it will +// be enabled automatically if you specify '-debug' on the command-line. +// LLVM_DEBUG() requires the DEBUG_TYPE macro to be defined. Set it to "foo" +// specify that your debug code belongs to class "foo". Be careful that you only +// do this after including Debug.h and not around any #include of headers. +// Headers should define and undef the macro acround the code that needs to use +// the LLVM_DEBUG() macro. Then, on the command line, you can specify +// '-debug-only=foo' to enable JUST the debug information for the foo class. +// +// When compiling without assertions, the -debug-* options and all code in +// LLVM_DEBUG() statements disappears, so it does not affect the runtime of the +// code. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_DEBUG_H +#define LLVM_SUPPORT_DEBUG_H + +namespace llvm { + +class raw_ostream; + +#ifndef NDEBUG + +/// isCurrentDebugType - Return true if the specified string is the debug type +/// specified on the command line, or if none was specified on the command line +/// with the -debug-only=X option. +/// +bool isCurrentDebugType(const char *Type); + +/// setCurrentDebugType - Set the current debug type, as if the -debug-only=X +/// option were specified. Note that DebugFlag also needs to be set to true for +/// debug output to be produced. +/// +void setCurrentDebugType(const char *Type); + +/// setCurrentDebugTypes - Set the current debug type, as if the +/// -debug-only=X,Y,Z option were specified. Note that DebugFlag +/// also needs to be set to true for debug output to be produced. +/// +void setCurrentDebugTypes(const char **Types, unsigned Count); + +/// DEBUG_WITH_TYPE macro - This macro should be used by passes to emit debug +/// information. In the '-debug' option is specified on the commandline, and if +/// this is a debug build, then the code specified as the option to the macro +/// will be executed. Otherwise it will not be. Example: +/// +/// DEBUG_WITH_TYPE("bitset", dbgs() << "Bitset contains: " << Bitset << "\n"); +/// +/// This will emit the debug information if -debug is present, and -debug-only +/// is not specified, or is specified as "bitset". +#define DEBUG_WITH_TYPE(TYPE, X) \ + do { if (::llvm::DebugFlag && ::llvm::isCurrentDebugType(TYPE)) { X; } \ + } while (false) + +#else +#define isCurrentDebugType(X) (false) +#define setCurrentDebugType(X) do { (void)(X); } while (false) +#define setCurrentDebugTypes(X, N) do { (void)(X); (void)(N); } while (false) +#define DEBUG_WITH_TYPE(TYPE, X) do { } while (false) +#endif + +/// This boolean is set to true if the '-debug' command line option +/// is specified. This should probably not be referenced directly, instead, use +/// the DEBUG macro below. +/// +extern bool DebugFlag; + +/// EnableDebugBuffering - This defaults to false. If true, the debug +/// stream will install signal handlers to dump any buffered debug +/// output. It allows clients to selectively allow the debug stream +/// to install signal handlers if they are certain there will be no +/// conflict. +/// +extern bool EnableDebugBuffering; + +/// dbgs() - This returns a reference to a raw_ostream for debugging +/// messages. If debugging is disabled it returns errs(). Use it +/// like: dbgs() << "foo" << "bar"; +raw_ostream &dbgs(); + +// DEBUG macro - This macro should be used by passes to emit debug information. +// In the '-debug' option is specified on the commandline, and if this is a +// debug build, then the code specified as the option to the macro will be +// executed. Otherwise it will not be. Example: +// +// LLVM_DEBUG(dbgs() << "Bitset contains: " << Bitset << "\n"); +// +#define LLVM_DEBUG(X) DEBUG_WITH_TYPE(DEBUG_TYPE, X) + +} // end namespace llvm + +#endif // LLVM_SUPPORT_DEBUG_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/Endian.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/Endian.h new file mode 100644 index 00000000000..5e7c1e961b9 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/Endian.h @@ -0,0 +1,427 @@ +//===- Endian.h - Utilities for IO with endian specific data ----*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file declares generic functions to read and write endian specific data. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_ENDIAN_H +#define LLVM_SUPPORT_ENDIAN_H + +#include "llvm/Support/Compiler.h" +#include "llvm/Support/SwapByteOrder.h" +#include +#include +#include +#include +#include + +namespace llvm { +namespace support { + +enum endianness {big, little, native}; + +// These are named values for common alignments. +enum {aligned = 0, unaligned = 1}; + +namespace detail { + +/// ::value is either alignment, or alignof(T) if alignment is 0. +template +struct PickAlignment { + enum { value = alignment == 0 ? alignof(T) : alignment }; +}; + +} // end namespace detail + +namespace endian { + +constexpr endianness system_endianness() { + return sys::IsBigEndianHost ? big : little; +} + +template +inline value_type byte_swap(value_type value, endianness endian) { + if ((endian != native) && (endian != system_endianness())) + sys::swapByteOrder(value); + return value; +} + +/// Swap the bytes of value to match the given endianness. +template +inline value_type byte_swap(value_type value) { + return byte_swap(value, endian); +} + +/// Read a value of a particular endianness from memory. +template +inline value_type read(const void *memory, endianness endian) { + value_type ret; + + memcpy(&ret, + LLVM_ASSUME_ALIGNED( + memory, (detail::PickAlignment::value)), + sizeof(value_type)); + return byte_swap(ret, endian); +} + +template +inline value_type read(const void *memory) { + return read(memory, endian); +} + +/// Read a value of a particular endianness from a buffer, and increment the +/// buffer past that value. +template +inline value_type readNext(const CharT *&memory, endianness endian) { + value_type ret = read(memory, endian); + memory += sizeof(value_type); + return ret; +} + +template +inline value_type readNext(const CharT *&memory) { + return readNext(memory, endian); +} + +/// Write a value to memory with a particular endianness. +template +inline void write(void *memory, value_type value, endianness endian) { + value = byte_swap(value, endian); + memcpy(LLVM_ASSUME_ALIGNED( + memory, (detail::PickAlignment::value)), + &value, sizeof(value_type)); +} + +template +inline void write(void *memory, value_type value) { + write(memory, value, endian); +} + +template +using make_unsigned_t = std::make_unsigned_t; + +/// Read a value of a particular endianness from memory, for a location +/// that starts at the given bit offset within the first byte. +template +inline value_type readAtBitAlignment(const void *memory, uint64_t startBit) { + assert(startBit < 8); + if (startBit == 0) + return read(memory); + else { + // Read two values and compose the result from them. + value_type val[2]; + memcpy(&val[0], + LLVM_ASSUME_ALIGNED( + memory, (detail::PickAlignment::value)), + sizeof(value_type) * 2); + val[0] = byte_swap(val[0]); + val[1] = byte_swap(val[1]); + + // Shift bits from the lower value into place. + make_unsigned_t lowerVal = val[0] >> startBit; + // Mask off upper bits after right shift in case of signed type. + make_unsigned_t numBitsFirstVal = + (sizeof(value_type) * 8) - startBit; + lowerVal &= ((make_unsigned_t)1 << numBitsFirstVal) - 1; + + // Get the bits from the upper value. + make_unsigned_t upperVal = + val[1] & (((make_unsigned_t)1 << startBit) - 1); + // Shift them in to place. + upperVal <<= numBitsFirstVal; + + return lowerVal | upperVal; + } +} + +/// Write a value to memory with a particular endianness, for a location +/// that starts at the given bit offset within the first byte. +template +inline void writeAtBitAlignment(void *memory, value_type value, + uint64_t startBit) { + assert(startBit < 8); + if (startBit == 0) + write(memory, value); + else { + // Read two values and shift the result into them. + value_type val[2]; + memcpy(&val[0], + LLVM_ASSUME_ALIGNED( + memory, (detail::PickAlignment::value)), + sizeof(value_type) * 2); + val[0] = byte_swap(val[0]); + val[1] = byte_swap(val[1]); + + // Mask off any existing bits in the upper part of the lower value that + // we want to replace. + val[0] &= ((make_unsigned_t)1 << startBit) - 1; + make_unsigned_t numBitsFirstVal = + (sizeof(value_type) * 8) - startBit; + make_unsigned_t lowerVal = value; + if (startBit > 0) { + // Mask off the upper bits in the new value that are not going to go into + // the lower value. This avoids a left shift of a negative value, which + // is undefined behavior. + lowerVal &= (((make_unsigned_t)1 << numBitsFirstVal) - 1); + // Now shift the new bits into place + lowerVal <<= startBit; + } + val[0] |= lowerVal; + + // Mask off any existing bits in the lower part of the upper value that + // we want to replace. + val[1] &= ~(((make_unsigned_t)1 << startBit) - 1); + // Next shift the bits that go into the upper value into position. + make_unsigned_t upperVal = value >> numBitsFirstVal; + // Mask off upper bits after right shift in case of signed type. + upperVal &= ((make_unsigned_t)1 << startBit) - 1; + val[1] |= upperVal; + + // Finally, rewrite values. + val[0] = byte_swap(val[0]); + val[1] = byte_swap(val[1]); + memcpy(LLVM_ASSUME_ALIGNED( + memory, (detail::PickAlignment::value)), + &val[0], sizeof(value_type) * 2); + } +} + +} // end namespace endian + +namespace detail { + +template ::value> +struct packed_endian_specific_integral { + using value_type = ValueType; + static constexpr endianness endian = Endian; + static constexpr std::size_t alignment = Alignment; + + packed_endian_specific_integral() = default; + + explicit packed_endian_specific_integral(value_type val) { *this = val; } + + operator value_type() const { + return endian::read( + (const void*)Value.buffer); + } + + void operator=(value_type newValue) { + endian::write( + (void*)Value.buffer, newValue); + } + + packed_endian_specific_integral &operator+=(value_type newValue) { + *this = *this + newValue; + return *this; + } + + packed_endian_specific_integral &operator-=(value_type newValue) { + *this = *this - newValue; + return *this; + } + + packed_endian_specific_integral &operator|=(value_type newValue) { + *this = *this | newValue; + return *this; + } + + packed_endian_specific_integral &operator&=(value_type newValue) { + *this = *this & newValue; + return *this; + } + +private: + struct { + alignas(ALIGN) char buffer[sizeof(value_type)]; + } Value; + +public: + struct ref { + explicit ref(void *Ptr) : Ptr(Ptr) {} + + operator value_type() const { + return endian::read(Ptr); + } + + void operator=(value_type NewValue) { + endian::write(Ptr, NewValue); + } + + private: + void *Ptr; + }; +}; + +} // end namespace detail + +using ulittle16_t = + detail::packed_endian_specific_integral; +using ulittle32_t = + detail::packed_endian_specific_integral; +using ulittle64_t = + detail::packed_endian_specific_integral; + +using little16_t = + detail::packed_endian_specific_integral; +using little32_t = + detail::packed_endian_specific_integral; +using little64_t = + detail::packed_endian_specific_integral; + +using aligned_ulittle16_t = + detail::packed_endian_specific_integral; +using aligned_ulittle32_t = + detail::packed_endian_specific_integral; +using aligned_ulittle64_t = + detail::packed_endian_specific_integral; + +using aligned_little16_t = + detail::packed_endian_specific_integral; +using aligned_little32_t = + detail::packed_endian_specific_integral; +using aligned_little64_t = + detail::packed_endian_specific_integral; + +using ubig16_t = + detail::packed_endian_specific_integral; +using ubig32_t = + detail::packed_endian_specific_integral; +using ubig64_t = + detail::packed_endian_specific_integral; + +using big16_t = + detail::packed_endian_specific_integral; +using big32_t = + detail::packed_endian_specific_integral; +using big64_t = + detail::packed_endian_specific_integral; + +using aligned_ubig16_t = + detail::packed_endian_specific_integral; +using aligned_ubig32_t = + detail::packed_endian_specific_integral; +using aligned_ubig64_t = + detail::packed_endian_specific_integral; + +using aligned_big16_t = + detail::packed_endian_specific_integral; +using aligned_big32_t = + detail::packed_endian_specific_integral; +using aligned_big64_t = + detail::packed_endian_specific_integral; + +using unaligned_uint16_t = + detail::packed_endian_specific_integral; +using unaligned_uint32_t = + detail::packed_endian_specific_integral; +using unaligned_uint64_t = + detail::packed_endian_specific_integral; + +using unaligned_int16_t = + detail::packed_endian_specific_integral; +using unaligned_int32_t = + detail::packed_endian_specific_integral; +using unaligned_int64_t = + detail::packed_endian_specific_integral; + +template +using little_t = detail::packed_endian_specific_integral; +template +using big_t = detail::packed_endian_specific_integral; + +template +using aligned_little_t = + detail::packed_endian_specific_integral; +template +using aligned_big_t = detail::packed_endian_specific_integral; + +namespace endian { + +template inline T read(const void *P, endianness E) { + return read(P, E); +} + +template inline T read(const void *P) { + return *(const detail::packed_endian_specific_integral *)P; +} + +inline uint16_t read16(const void *P, endianness E) { + return read(P, E); +} +inline uint32_t read32(const void *P, endianness E) { + return read(P, E); +} +inline uint64_t read64(const void *P, endianness E) { + return read(P, E); +} + +template inline uint16_t read16(const void *P) { + return read(P); +} +template inline uint32_t read32(const void *P) { + return read(P); +} +template inline uint64_t read64(const void *P) { + return read(P); +} + +inline uint16_t read16le(const void *P) { return read16(P); } +inline uint32_t read32le(const void *P) { return read32(P); } +inline uint64_t read64le(const void *P) { return read64(P); } +inline uint16_t read16be(const void *P) { return read16(P); } +inline uint32_t read32be(const void *P) { return read32(P); } +inline uint64_t read64be(const void *P) { return read64(P); } + +template inline void write(void *P, T V, endianness E) { + write(P, V, E); +} + +template inline void write(void *P, T V) { + *(detail::packed_endian_specific_integral *)P = V; +} + +inline void write16(void *P, uint16_t V, endianness E) { + write(P, V, E); +} +inline void write32(void *P, uint32_t V, endianness E) { + write(P, V, E); +} +inline void write64(void *P, uint64_t V, endianness E) { + write(P, V, E); +} + +template inline void write16(void *P, uint16_t V) { + write(P, V); +} +template inline void write32(void *P, uint32_t V) { + write(P, V); +} +template inline void write64(void *P, uint64_t V) { + write(P, V); +} + +inline void write16le(void *P, uint16_t V) { write16(P, V); } +inline void write32le(void *P, uint32_t V) { write32(P, V); } +inline void write64le(void *P, uint64_t V) { write64(P, V); } +inline void write16be(void *P, uint16_t V) { write16(P, V); } +inline void write32be(void *P, uint32_t V) { write32(P, V); } +inline void write64be(void *P, uint64_t V) { write64(P, V); } + +} // end namespace endian + +} // end namespace support +} // end namespace llvm + +#endif // LLVM_SUPPORT_ENDIAN_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/Error.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/Error.h new file mode 100644 index 00000000000..2292770a97c --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/Error.h @@ -0,0 +1,1405 @@ +//===- llvm/Support/Error.h - Recoverable error handling --------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file defines an API used to report recoverable errors. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_ERROR_H +#define LLVM_SUPPORT_ERROR_H + +#include "llvm-c/Error.h" +#include "llvm/ADT/Twine.h" +#include "llvm/Config/abi-breaking.h" +#include "llvm/Support/AlignOf.h" +#include "llvm/Support/Compiler.h" +#include "llvm/Support/Debug.h" +#include "llvm/Support/ErrorHandling.h" +#include "llvm/Support/ErrorOr.h" +#include "llvm/Support/Format.h" +#include "llvm/Support/raw_ostream.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace llvm { + +class ErrorSuccess; + +/// Base class for error info classes. Do not extend this directly: Extend +/// the ErrorInfo template subclass instead. +class ErrorInfoBase { +public: + virtual ~ErrorInfoBase() = default; + + /// Print an error message to an output stream. + virtual void log(raw_ostream &OS) const = 0; + + /// Return the error message as a string. + virtual std::string message() const { + std::string Msg; + raw_string_ostream OS(Msg); + log(OS); + return OS.str(); + } + + /// Convert this error to a std::error_code. + /// + /// This is a temporary crutch to enable interaction with code still + /// using std::error_code. It will be removed in the future. + virtual std::error_code convertToErrorCode() const = 0; + + // Returns the class ID for this type. + static const void *classID() { return &ID; } + + // Returns the class ID for the dynamic type of this ErrorInfoBase instance. + virtual const void *dynamicClassID() const = 0; + + // Check whether this instance is a subclass of the class identified by + // ClassID. + virtual bool isA(const void *const ClassID) const { + return ClassID == classID(); + } + + // Check whether this instance is a subclass of ErrorInfoT. + template bool isA() const { + return isA(ErrorInfoT::classID()); + } + +private: + virtual void anchor(); + + static char ID; +}; + +/// Lightweight error class with error context and mandatory checking. +/// +/// Instances of this class wrap a ErrorInfoBase pointer. Failure states +/// are represented by setting the pointer to a ErrorInfoBase subclass +/// instance containing information describing the failure. Success is +/// represented by a null pointer value. +/// +/// Instances of Error also contains a 'Checked' flag, which must be set +/// before the destructor is called, otherwise the destructor will trigger a +/// runtime error. This enforces at runtime the requirement that all Error +/// instances be checked or returned to the caller. +/// +/// There are two ways to set the checked flag, depending on what state the +/// Error instance is in. For Error instances indicating success, it +/// is sufficient to invoke the boolean conversion operator. E.g.: +/// +/// @code{.cpp} +/// Error foo(<...>); +/// +/// if (auto E = foo(<...>)) +/// return E; // <- Return E if it is in the error state. +/// // We have verified that E was in the success state. It can now be safely +/// // destroyed. +/// @endcode +/// +/// A success value *can not* be dropped. For example, just calling 'foo(<...>)' +/// without testing the return value will raise a runtime error, even if foo +/// returns success. +/// +/// For Error instances representing failure, you must use either the +/// handleErrors or handleAllErrors function with a typed handler. E.g.: +/// +/// @code{.cpp} +/// class MyErrorInfo : public ErrorInfo { +/// // Custom error info. +/// }; +/// +/// Error foo(<...>) { return make_error(...); } +/// +/// auto E = foo(<...>); // <- foo returns failure with MyErrorInfo. +/// auto NewE = +/// handleErrors(E, +/// [](const MyErrorInfo &M) { +/// // Deal with the error. +/// }, +/// [](std::unique_ptr M) -> Error { +/// if (canHandle(*M)) { +/// // handle error. +/// return Error::success(); +/// } +/// // Couldn't handle this error instance. Pass it up the stack. +/// return Error(std::move(M)); +/// ); +/// // Note - we must check or return NewE in case any of the handlers +/// // returned a new error. +/// @endcode +/// +/// The handleAllErrors function is identical to handleErrors, except +/// that it has a void return type, and requires all errors to be handled and +/// no new errors be returned. It prevents errors (assuming they can all be +/// handled) from having to be bubbled all the way to the top-level. +/// +/// *All* Error instances must be checked before destruction, even if +/// they're moved-assigned or constructed from Success values that have already +/// been checked. This enforces checking through all levels of the call stack. +class [[nodiscard]] Error { + // ErrorList needs to be able to yank ErrorInfoBase pointers out of Errors + // to add to the error list. It can't rely on handleErrors for this, since + // handleErrors does not support ErrorList handlers. + friend class ErrorList; + + // handleErrors needs to be able to set the Checked flag. + template + friend Error handleErrors(Error E, HandlerTs &&... Handlers); + + // Expected needs to be able to steal the payload when constructed from an + // error. + template friend class Expected; + + // wrap needs to be able to steal the payload. + friend LLVMErrorRef wrap(Error); + +protected: + /// Create a success value. Prefer using 'Error::success()' for readability + Error() { + setPtr(nullptr); + setChecked(false); + } + +public: + /// Create a success value. + static ErrorSuccess success(); + + // Errors are not copy-constructable. + Error(const Error &Other) = delete; + + /// Move-construct an error value. The newly constructed error is considered + /// unchecked, even if the source error had been checked. The original error + /// becomes a checked Success value, regardless of its original state. + Error(Error &&Other) { + setChecked(true); + *this = std::move(Other); + } + + /// Create an error value. Prefer using the 'make_error' function, but + /// this constructor can be useful when "re-throwing" errors from handlers. + Error(std::unique_ptr Payload) { + setPtr(Payload.release()); + setChecked(false); + } + + // Errors are not copy-assignable. + Error &operator=(const Error &Other) = delete; + + /// Move-assign an error value. The current error must represent success, you + /// you cannot overwrite an unhandled error. The current error is then + /// considered unchecked. The source error becomes a checked success value, + /// regardless of its original state. + Error &operator=(Error &&Other) { + // Don't allow overwriting of unchecked values. + assertIsChecked(); + setPtr(Other.getPtr()); + + // This Error is unchecked, even if the source error was checked. + setChecked(false); + + // Null out Other's payload and set its checked bit. + Other.setPtr(nullptr); + Other.setChecked(true); + + return *this; + } + + /// Destroy a Error. Fails with a call to abort() if the error is + /// unchecked. + ~Error() { + assertIsChecked(); + delete getPtr(); + } + + /// Bool conversion. Returns true if this Error is in a failure state, + /// and false if it is in an accept state. If the error is in a Success state + /// it will be considered checked. + explicit operator bool() { + setChecked(getPtr() == nullptr); + return getPtr() != nullptr; + } + + /// Check whether one error is a subclass of another. + template bool isA() const { + return getPtr() && getPtr()->isA(ErrT::classID()); + } + + /// Returns the dynamic class id of this error, or null if this is a success + /// value. + const void* dynamicClassID() const { + if (!getPtr()) + return nullptr; + return getPtr()->dynamicClassID(); + } + +private: +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + // assertIsChecked() happens very frequently, but under normal circumstances + // is supposed to be a no-op. So we want it to be inlined, but having a bunch + // of debug prints can cause the function to be too large for inlining. So + // it's important that we define this function out of line so that it can't be + // inlined. + [[noreturn]] void fatalUncheckedError() const; +#endif + + void assertIsChecked() { +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + if (LLVM_UNLIKELY(!getChecked() || getPtr())) + fatalUncheckedError(); +#endif + } + + ErrorInfoBase *getPtr() const { +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + return reinterpret_cast( + reinterpret_cast(Payload) & + ~static_cast(0x1)); +#else + return Payload; +#endif + } + + void setPtr(ErrorInfoBase *EI) { +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + Payload = reinterpret_cast( + (reinterpret_cast(EI) & + ~static_cast(0x1)) | + (reinterpret_cast(Payload) & 0x1)); +#else + Payload = EI; +#endif + } + + bool getChecked() const { +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + return (reinterpret_cast(Payload) & 0x1) == 0; +#else + return true; +#endif + } + + void setChecked(bool V) { +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + Payload = reinterpret_cast( + (reinterpret_cast(Payload) & + ~static_cast(0x1)) | + (V ? 0 : 1)); +#endif + } + + std::unique_ptr takePayload() { + std::unique_ptr Tmp(getPtr()); + setPtr(nullptr); + setChecked(true); + return Tmp; + } + + friend raw_ostream &operator<<(raw_ostream &OS, const Error &E) { + if (auto *P = E.getPtr()) + P->log(OS); + else + OS << "success"; + return OS; + } + + ErrorInfoBase *Payload = nullptr; +}; + +/// Subclass of Error for the sole purpose of identifying the success path in +/// the type system. This allows to catch invalid conversion to Expected at +/// compile time. +class ErrorSuccess final : public Error {}; + +inline ErrorSuccess Error::success() { return ErrorSuccess(); } + +/// Make a Error instance representing failure using the given error info +/// type. +template Error make_error(ArgTs &&... Args) { + return Error(std::make_unique(std::forward(Args)...)); +} + +/// Base class for user error types. Users should declare their error types +/// like: +/// +/// class MyError : public ErrorInfo { +/// .... +/// }; +/// +/// This class provides an implementation of the ErrorInfoBase::kind +/// method, which is used by the Error RTTI system. +template +class ErrorInfo : public ParentErrT { +public: + using ParentErrT::ParentErrT; // inherit constructors + + static const void *classID() { return &ThisErrT::ID; } + + const void *dynamicClassID() const override { return &ThisErrT::ID; } + + bool isA(const void *const ClassID) const override { + return ClassID == classID() || ParentErrT::isA(ClassID); + } +}; + +/// Special ErrorInfo subclass representing a list of ErrorInfos. +/// Instances of this class are constructed by joinError. +class ErrorList final : public ErrorInfo { + // handleErrors needs to be able to iterate the payload list of an + // ErrorList. + template + friend Error handleErrors(Error E, HandlerTs &&... Handlers); + + // joinErrors is implemented in terms of join. + friend Error joinErrors(Error, Error); + +public: + void log(raw_ostream &OS) const override { + OS << "Multiple errors:\n"; + for (const auto &ErrPayload : Payloads) { + ErrPayload->log(OS); + OS << "\n"; + } + } + + std::error_code convertToErrorCode() const override; + + // Used by ErrorInfo::classID. + static char ID; + +private: + ErrorList(std::unique_ptr Payload1, + std::unique_ptr Payload2) { + assert(!Payload1->isA() && !Payload2->isA() && + "ErrorList constructor payloads should be singleton errors"); + Payloads.push_back(std::move(Payload1)); + Payloads.push_back(std::move(Payload2)); + } + + static Error join(Error E1, Error E2) { + if (!E1) + return E2; + if (!E2) + return E1; + if (E1.isA()) { + auto &E1List = static_cast(*E1.getPtr()); + if (E2.isA()) { + auto E2Payload = E2.takePayload(); + auto &E2List = static_cast(*E2Payload); + for (auto &Payload : E2List.Payloads) + E1List.Payloads.push_back(std::move(Payload)); + } else + E1List.Payloads.push_back(E2.takePayload()); + + return E1; + } + if (E2.isA()) { + auto &E2List = static_cast(*E2.getPtr()); + E2List.Payloads.insert(E2List.Payloads.begin(), E1.takePayload()); + return E2; + } + return Error(std::unique_ptr( + new ErrorList(E1.takePayload(), E2.takePayload()))); + } + + std::vector> Payloads; +}; + +/// Concatenate errors. The resulting Error is unchecked, and contains the +/// ErrorInfo(s), if any, contained in E1, followed by the +/// ErrorInfo(s), if any, contained in E2. +inline Error joinErrors(Error E1, Error E2) { + return ErrorList::join(std::move(E1), std::move(E2)); +} + +/// Tagged union holding either a T or a Error. +/// +/// This class parallels ErrorOr, but replaces error_code with Error. Since +/// Error cannot be copied, this class replaces getError() with +/// takeError(). It also adds an bool errorIsA() method for testing the +/// error class type. +/// +/// Example usage of 'Expected' as a function return type: +/// +/// @code{.cpp} +/// Expected myDivide(int A, int B) { +/// if (B == 0) { +/// // return an Error +/// return createStringError(inconvertibleErrorCode(), +/// "B must not be zero!"); +/// } +/// // return an integer +/// return A / B; +/// } +/// @endcode +/// +/// Checking the results of to a function returning 'Expected': +/// @code{.cpp} +/// if (auto E = Result.takeError()) { +/// // We must consume the error. Typically one of: +/// // - return the error to our caller +/// // - toString(), when logging +/// // - consumeError(), to silently swallow the error +/// // - handleErrors(), to distinguish error types +/// errs() << "Problem with division " << toString(std::move(E)) << "\n"; +/// return; +/// } +/// // use the result +/// outs() << "The answer is " << *Result << "\n"; +/// @endcode +/// +/// For unit-testing a function returning an 'Expected', see the +/// 'EXPECT_THAT_EXPECTED' macros in llvm/Testing/Support/Error.h + +template class [[nodiscard]] Expected { + template friend class ExpectedAsOutParameter; + template friend class Expected; + + static constexpr bool isRef = std::is_reference_v; + + using wrap = std::reference_wrapper>; + + using error_type = std::unique_ptr; + +public: + using storage_type = std::conditional_t; + using value_type = T; + +private: + using reference = std::remove_reference_t &; + using const_reference = const std::remove_reference_t &; + using pointer = std::remove_reference_t *; + using const_pointer = const std::remove_reference_t *; + +public: + /// Create an Expected error value from the given Error. + Expected(Error Err) + : HasError(true) +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + // Expected is unchecked upon construction in Debug builds. + , Unchecked(true) +#endif + { + assert(Err && "Cannot create Expected from Error success value."); + new (getErrorStorage()) error_type(Err.takePayload()); + } + + /// Forbid to convert from Error::success() implicitly, this avoids having + /// Expected foo() { return Error::success(); } which compiles otherwise + /// but triggers the assertion above. + Expected(ErrorSuccess) = delete; + + /// Create an Expected success value from the given OtherT value, which + /// must be convertible to T. + template + Expected(OtherT &&Val, + std::enable_if_t> * = nullptr) + : HasError(false) +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + // Expected is unchecked upon construction in Debug builds. + , + Unchecked(true) +#endif + { + new (getStorage()) storage_type(std::forward(Val)); + } + + /// Move construct an Expected value. + Expected(Expected &&Other) { moveConstruct(std::move(Other)); } + + /// Move construct an Expected value from an Expected, where OtherT + /// must be convertible to T. + template + Expected(Expected &&Other, + std::enable_if_t> * = nullptr) { + moveConstruct(std::move(Other)); + } + + /// Move construct an Expected value from an Expected, where OtherT + /// isn't convertible to T. + template + explicit Expected( + Expected &&Other, + std::enable_if_t> * = nullptr) { + moveConstruct(std::move(Other)); + } + + /// Move-assign from another Expected. + Expected &operator=(Expected &&Other) { + moveAssign(std::move(Other)); + return *this; + } + + /// Destroy an Expected. + ~Expected() { + assertIsChecked(); + if (!HasError) + getStorage()->~storage_type(); + else + getErrorStorage()->~error_type(); + } + + /// Return false if there is an error. + explicit operator bool() { +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + Unchecked = HasError; +#endif + return !HasError; + } + + /// Returns a reference to the stored T value. + reference get() { + assertIsChecked(); + return *getStorage(); + } + + /// Returns a const reference to the stored T value. + const_reference get() const { + assertIsChecked(); + return const_cast *>(this)->get(); + } + + /// Returns \a takeError() after moving the held T (if any) into \p V. + template + Error moveInto( + OtherT &Value, + std::enable_if_t> * = nullptr) && { + if (*this) + Value = std::move(get()); + return takeError(); + } + + /// Check that this Expected is an error of type ErrT. + template bool errorIsA() const { + return HasError && (*getErrorStorage())->template isA(); + } + + /// Take ownership of the stored error. + /// After calling this the Expected is in an indeterminate state that can + /// only be safely destructed. No further calls (beside the destructor) should + /// be made on the Expected value. + Error takeError() { +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + Unchecked = false; +#endif + return HasError ? Error(std::move(*getErrorStorage())) : Error::success(); + } + + /// Returns a pointer to the stored T value. + pointer operator->() { + assertIsChecked(); + return toPointer(getStorage()); + } + + /// Returns a const pointer to the stored T value. + const_pointer operator->() const { + assertIsChecked(); + return toPointer(getStorage()); + } + + /// Returns a reference to the stored T value. + reference operator*() { + assertIsChecked(); + return *getStorage(); + } + + /// Returns a const reference to the stored T value. + const_reference operator*() const { + assertIsChecked(); + return *getStorage(); + } + +private: + template + static bool compareThisIfSameType(const T1 &a, const T1 &b) { + return &a == &b; + } + + template + static bool compareThisIfSameType(const T1 &, const T2 &) { + return false; + } + + template void moveConstruct(Expected &&Other) { + HasError = Other.HasError; +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + Unchecked = true; + Other.Unchecked = false; +#endif + + if (!HasError) + new (getStorage()) storage_type(std::move(*Other.getStorage())); + else + new (getErrorStorage()) error_type(std::move(*Other.getErrorStorage())); + } + + template void moveAssign(Expected &&Other) { + assertIsChecked(); + + if (compareThisIfSameType(*this, Other)) + return; + + this->~Expected(); + new (this) Expected(std::move(Other)); + } + + pointer toPointer(pointer Val) { return Val; } + + const_pointer toPointer(const_pointer Val) const { return Val; } + + pointer toPointer(wrap *Val) { return &Val->get(); } + + const_pointer toPointer(const wrap *Val) const { return &Val->get(); } + + storage_type *getStorage() { + assert(!HasError && "Cannot get value when an error exists!"); + return reinterpret_cast(&TStorage); + } + + const storage_type *getStorage() const { + assert(!HasError && "Cannot get value when an error exists!"); + return reinterpret_cast(&TStorage); + } + + error_type *getErrorStorage() { + assert(HasError && "Cannot get error when a value exists!"); + return reinterpret_cast(&ErrorStorage); + } + + const error_type *getErrorStorage() const { + assert(HasError && "Cannot get error when a value exists!"); + return reinterpret_cast(&ErrorStorage); + } + + // Used by ExpectedAsOutParameter to reset the checked flag. + void setUnchecked() { +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + Unchecked = true; +#endif + } + +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + [[noreturn]] LLVM_ATTRIBUTE_NOINLINE void fatalUncheckedExpected() const { + dbgs() << "Expected must be checked before access or destruction.\n"; + if (HasError) { + dbgs() << "Unchecked Expected contained error:\n"; + (*getErrorStorage())->log(dbgs()); + } else + dbgs() << "Expected value was in success state. (Note: Expected " + "values in success mode must still be checked prior to being " + "destroyed).\n"; + abort(); + } +#endif + + void assertIsChecked() const { +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + if (LLVM_UNLIKELY(Unchecked)) + fatalUncheckedExpected(); +#endif + } + + union { + AlignedCharArrayUnion TStorage; + AlignedCharArrayUnion ErrorStorage; + }; + bool HasError : 1; +#if LLVM_ENABLE_ABI_BREAKING_CHECKS + bool Unchecked : 1; +#endif +}; + +/// Report a serious error, calling any installed error handler. See +/// ErrorHandling.h. +[[noreturn]] void report_fatal_error(Error Err, bool gen_crash_diag = true); + +/// Report a fatal error if Err is a failure value. +/// +/// This function can be used to wrap calls to fallible functions ONLY when it +/// is known that the Error will always be a success value. E.g. +/// +/// @code{.cpp} +/// // foo only attempts the fallible operation if DoFallibleOperation is +/// // true. If DoFallibleOperation is false then foo always returns +/// // Error::success(). +/// Error foo(bool DoFallibleOperation); +/// +/// cantFail(foo(false)); +/// @endcode +inline void cantFail(Error Err, const char *Msg = nullptr) { + if (Err) { + if (!Msg) + Msg = "Failure value returned from cantFail wrapped call"; +#ifndef NDEBUG + std::string Str; + raw_string_ostream OS(Str); + OS << Msg << "\n" << Err; + Msg = OS.str().c_str(); +#endif + llvm_unreachable(Msg); + } +} + +/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and +/// returns the contained value. +/// +/// This function can be used to wrap calls to fallible functions ONLY when it +/// is known that the Error will always be a success value. E.g. +/// +/// @code{.cpp} +/// // foo only attempts the fallible operation if DoFallibleOperation is +/// // true. If DoFallibleOperation is false then foo always returns an int. +/// Expected foo(bool DoFallibleOperation); +/// +/// int X = cantFail(foo(false)); +/// @endcode +template +T cantFail(Expected ValOrErr, const char *Msg = nullptr) { + if (ValOrErr) + return std::move(*ValOrErr); + else { + if (!Msg) + Msg = "Failure value returned from cantFail wrapped call"; +#ifndef NDEBUG + std::string Str; + raw_string_ostream OS(Str); + auto E = ValOrErr.takeError(); + OS << Msg << "\n" << E; + Msg = OS.str().c_str(); +#endif + llvm_unreachable(Msg); + } +} + +/// Report a fatal error if ValOrErr is a failure value, otherwise unwraps and +/// returns the contained reference. +/// +/// This function can be used to wrap calls to fallible functions ONLY when it +/// is known that the Error will always be a success value. E.g. +/// +/// @code{.cpp} +/// // foo only attempts the fallible operation if DoFallibleOperation is +/// // true. If DoFallibleOperation is false then foo always returns a Bar&. +/// Expected foo(bool DoFallibleOperation); +/// +/// Bar &X = cantFail(foo(false)); +/// @endcode +template +T& cantFail(Expected ValOrErr, const char *Msg = nullptr) { + if (ValOrErr) + return *ValOrErr; + else { + if (!Msg) + Msg = "Failure value returned from cantFail wrapped call"; +#ifndef NDEBUG + std::string Str; + raw_string_ostream OS(Str); + auto E = ValOrErr.takeError(); + OS << Msg << "\n" << E; + Msg = OS.str().c_str(); +#endif + llvm_unreachable(Msg); + } +} + +/// Helper for testing applicability of, and applying, handlers for +/// ErrorInfo types. +template +class ErrorHandlerTraits + : public ErrorHandlerTraits< + decltype(&std::remove_reference_t::operator())> {}; + +// Specialization functions of the form 'Error (const ErrT&)'. +template class ErrorHandlerTraits { +public: + static bool appliesTo(const ErrorInfoBase &E) { + return E.template isA(); + } + + template + static Error apply(HandlerT &&H, std::unique_ptr E) { + assert(appliesTo(*E) && "Applying incorrect handler"); + return H(static_cast(*E)); + } +}; + +// Specialization functions of the form 'void (const ErrT&)'. +template class ErrorHandlerTraits { +public: + static bool appliesTo(const ErrorInfoBase &E) { + return E.template isA(); + } + + template + static Error apply(HandlerT &&H, std::unique_ptr E) { + assert(appliesTo(*E) && "Applying incorrect handler"); + H(static_cast(*E)); + return Error::success(); + } +}; + +/// Specialization for functions of the form 'Error (std::unique_ptr)'. +template +class ErrorHandlerTraits)> { +public: + static bool appliesTo(const ErrorInfoBase &E) { + return E.template isA(); + } + + template + static Error apply(HandlerT &&H, std::unique_ptr E) { + assert(appliesTo(*E) && "Applying incorrect handler"); + std::unique_ptr SubE(static_cast(E.release())); + return H(std::move(SubE)); + } +}; + +/// Specialization for functions of the form 'void (std::unique_ptr)'. +template +class ErrorHandlerTraits)> { +public: + static bool appliesTo(const ErrorInfoBase &E) { + return E.template isA(); + } + + template + static Error apply(HandlerT &&H, std::unique_ptr E) { + assert(appliesTo(*E) && "Applying incorrect handler"); + std::unique_ptr SubE(static_cast(E.release())); + H(std::move(SubE)); + return Error::success(); + } +}; + +// Specialization for member functions of the form 'RetT (const ErrT&)'. +template +class ErrorHandlerTraits + : public ErrorHandlerTraits {}; + +// Specialization for member functions of the form 'RetT (const ErrT&) const'. +template +class ErrorHandlerTraits + : public ErrorHandlerTraits {}; + +// Specialization for member functions of the form 'RetT (const ErrT&)'. +template +class ErrorHandlerTraits + : public ErrorHandlerTraits {}; + +// Specialization for member functions of the form 'RetT (const ErrT&) const'. +template +class ErrorHandlerTraits + : public ErrorHandlerTraits {}; + +/// Specialization for member functions of the form +/// 'RetT (std::unique_ptr)'. +template +class ErrorHandlerTraits)> + : public ErrorHandlerTraits)> {}; + +/// Specialization for member functions of the form +/// 'RetT (std::unique_ptr) const'. +template +class ErrorHandlerTraits) const> + : public ErrorHandlerTraits)> {}; + +inline Error handleErrorImpl(std::unique_ptr Payload) { + return Error(std::move(Payload)); +} + +template +Error handleErrorImpl(std::unique_ptr Payload, + HandlerT &&Handler, HandlerTs &&... Handlers) { + if (ErrorHandlerTraits::appliesTo(*Payload)) + return ErrorHandlerTraits::apply(std::forward(Handler), + std::move(Payload)); + return handleErrorImpl(std::move(Payload), + std::forward(Handlers)...); +} + +/// Pass the ErrorInfo(s) contained in E to their respective handlers. Any +/// unhandled errors (or Errors returned by handlers) are re-concatenated and +/// returned. +/// Because this function returns an error, its result must also be checked +/// or returned. If you intend to handle all errors use handleAllErrors +/// (which returns void, and will abort() on unhandled errors) instead. +template +Error handleErrors(Error E, HandlerTs &&... Hs) { + if (!E) + return Error::success(); + + std::unique_ptr Payload = E.takePayload(); + + if (Payload->isA()) { + ErrorList &List = static_cast(*Payload); + Error R; + for (auto &P : List.Payloads) + R = ErrorList::join( + std::move(R), + handleErrorImpl(std::move(P), std::forward(Hs)...)); + return R; + } + + return handleErrorImpl(std::move(Payload), std::forward(Hs)...); +} + +/// Behaves the same as handleErrors, except that by contract all errors +/// *must* be handled by the given handlers (i.e. there must be no remaining +/// errors after running the handlers, or llvm_unreachable is called). +template +void handleAllErrors(Error E, HandlerTs &&... Handlers) { + cantFail(handleErrors(std::move(E), std::forward(Handlers)...)); +} + +/// Check that E is a non-error, then drop it. +/// If E is an error, llvm_unreachable will be called. +inline void handleAllErrors(Error E) { + cantFail(std::move(E)); +} + +/// Handle any errors (if present) in an Expected, then try a recovery path. +/// +/// If the incoming value is a success value it is returned unmodified. If it +/// is a failure value then it the contained error is passed to handleErrors. +/// If handleErrors is able to handle the error then the RecoveryPath functor +/// is called to supply the final result. If handleErrors is not able to +/// handle all errors then the unhandled errors are returned. +/// +/// This utility enables the follow pattern: +/// +/// @code{.cpp} +/// enum FooStrategy { Aggressive, Conservative }; +/// Expected foo(FooStrategy S); +/// +/// auto ResultOrErr = +/// handleExpected( +/// foo(Aggressive), +/// []() { return foo(Conservative); }, +/// [](AggressiveStrategyError&) { +/// // Implicitly conusme this - we'll recover by using a conservative +/// // strategy. +/// }); +/// +/// @endcode +template +Expected handleExpected(Expected ValOrErr, RecoveryFtor &&RecoveryPath, + HandlerTs &&... Handlers) { + if (ValOrErr) + return ValOrErr; + + if (auto Err = handleErrors(ValOrErr.takeError(), + std::forward(Handlers)...)) + return std::move(Err); + + return RecoveryPath(); +} + +/// Log all errors (if any) in E to OS. If there are any errors, ErrorBanner +/// will be printed before the first one is logged. A newline will be printed +/// after each error. +/// +/// This function is compatible with the helpers from Support/WithColor.h. You +/// can pass any of them as the OS. Please consider using them instead of +/// including 'error: ' in the ErrorBanner. +/// +/// This is useful in the base level of your program to allow clean termination +/// (allowing clean deallocation of resources, etc.), while reporting error +/// information to the user. +void logAllUnhandledErrors(Error E, raw_ostream &OS, Twine ErrorBanner = {}); + +/// Write all error messages (if any) in E to a string. The newline character +/// is used to separate error messages. +std::string toString(Error E); + +/// Consume a Error without doing anything. This method should be used +/// only where an error can be considered a reasonable and expected return +/// value. +/// +/// Uses of this method are potentially indicative of design problems: If it's +/// legitimate to do nothing while processing an "error", the error-producer +/// might be more clearly refactored to return an std::optional. +inline void consumeError(Error Err) { + handleAllErrors(std::move(Err), [](const ErrorInfoBase &) {}); +} + +/// Convert an Expected to an Optional without doing anything. This method +/// should be used only where an error can be considered a reasonable and +/// expected return value. +/// +/// Uses of this method are potentially indicative of problems: perhaps the +/// error should be propagated further, or the error-producer should just +/// return an Optional in the first place. +template std::optional expectedToOptional(Expected &&E) { + if (E) + return std::move(*E); + consumeError(E.takeError()); + return std::nullopt; +} + +template std::optional expectedToStdOptional(Expected &&E) { + if (E) + return std::move(*E); + consumeError(E.takeError()); + return std::nullopt; +} + +/// Helper for converting an Error to a bool. +/// +/// This method returns true if Err is in an error state, or false if it is +/// in a success state. Puts Err in a checked state in both cases (unlike +/// Error::operator bool(), which only does this for success states). +inline bool errorToBool(Error Err) { + bool IsError = static_cast(Err); + if (IsError) + consumeError(std::move(Err)); + return IsError; +} + +/// Helper for Errors used as out-parameters. +/// +/// This helper is for use with the Error-as-out-parameter idiom, where an error +/// is passed to a function or method by reference, rather than being returned. +/// In such cases it is helpful to set the checked bit on entry to the function +/// so that the error can be written to (unchecked Errors abort on assignment) +/// and clear the checked bit on exit so that clients cannot accidentally forget +/// to check the result. This helper performs these actions automatically using +/// RAII: +/// +/// @code{.cpp} +/// Result foo(Error &Err) { +/// ErrorAsOutParameter ErrAsOutParam(&Err); // 'Checked' flag set +/// // +/// // <- 'Checked' flag auto-cleared when ErrAsOutParam is destructed. +/// } +/// @endcode +/// +/// ErrorAsOutParameter takes an Error* rather than Error& so that it can be +/// used with optional Errors (Error pointers that are allowed to be null). If +/// ErrorAsOutParameter took an Error reference, an instance would have to be +/// created inside every condition that verified that Error was non-null. By +/// taking an Error pointer we can just create one instance at the top of the +/// function. +class ErrorAsOutParameter { +public: + ErrorAsOutParameter(Error *Err) : Err(Err) { + // Raise the checked bit if Err is success. + if (Err) + (void)!!*Err; + } + + ~ErrorAsOutParameter() { + // Clear the checked bit. + if (Err && !*Err) + *Err = Error::success(); + } + +private: + Error *Err; +}; + +/// Helper for Expecteds used as out-parameters. +/// +/// See ErrorAsOutParameter. +template +class ExpectedAsOutParameter { +public: + ExpectedAsOutParameter(Expected *ValOrErr) + : ValOrErr(ValOrErr) { + if (ValOrErr) + (void)!!*ValOrErr; + } + + ~ExpectedAsOutParameter() { + if (ValOrErr) + ValOrErr->setUnchecked(); + } + +private: + Expected *ValOrErr; +}; + +/// This class wraps a std::error_code in a Error. +/// +/// This is useful if you're writing an interface that returns a Error +/// (or Expected) and you want to call code that still returns +/// std::error_codes. +class ECError : public ErrorInfo { + friend Error errorCodeToError(std::error_code); + + void anchor() override; + +public: + void setErrorCode(std::error_code EC) { this->EC = EC; } + std::error_code convertToErrorCode() const override { return EC; } + void log(raw_ostream &OS) const override { OS << EC.message(); } + + // Used by ErrorInfo::classID. + static char ID; + +protected: + ECError() = default; + ECError(std::error_code EC) : EC(EC) {} + + std::error_code EC; +}; + +/// The value returned by this function can be returned from convertToErrorCode +/// for Error values where no sensible translation to std::error_code exists. +/// It should only be used in this situation, and should never be used where a +/// sensible conversion to std::error_code is available, as attempts to convert +/// to/from this error will result in a fatal error. (i.e. it is a programmatic +/// error to try to convert such a value). +std::error_code inconvertibleErrorCode(); + +/// Helper for converting an std::error_code to a Error. +Error errorCodeToError(std::error_code EC); + +/// Helper for converting an ECError to a std::error_code. +/// +/// This method requires that Err be Error() or an ECError, otherwise it +/// will trigger a call to abort(). +std::error_code errorToErrorCode(Error Err); + +/// Convert an ErrorOr to an Expected. +template Expected errorOrToExpected(ErrorOr &&EO) { + if (auto EC = EO.getError()) + return errorCodeToError(EC); + return std::move(*EO); +} + +/// Convert an Expected to an ErrorOr. +template ErrorOr expectedToErrorOr(Expected &&E) { + if (auto Err = E.takeError()) + return errorToErrorCode(std::move(Err)); + return std::move(*E); +} + +/// This class wraps a string in an Error. +/// +/// StringError is useful in cases where the client is not expected to be able +/// to consume the specific error message programmatically (for example, if the +/// error message is to be presented to the user). +/// +/// StringError can also be used when additional information is to be printed +/// along with a error_code message. Depending on the constructor called, this +/// class can either display: +/// 1. the error_code message (ECError behavior) +/// 2. a string +/// 3. the error_code message and a string +/// +/// These behaviors are useful when subtyping is required; for example, when a +/// specific library needs an explicit error type. In the example below, +/// PDBError is derived from StringError: +/// +/// @code{.cpp} +/// Expected foo() { +/// return llvm::make_error(pdb_error_code::dia_failed_loading, +/// "Additional information"); +/// } +/// @endcode +/// +class StringError : public ErrorInfo { +public: + static char ID; + + // Prints EC + S and converts to EC + StringError(std::error_code EC, const Twine &S = Twine()); + + // Prints S and converts to EC + StringError(const Twine &S, std::error_code EC); + + void log(raw_ostream &OS) const override; + std::error_code convertToErrorCode() const override; + + const std::string &getMessage() const { return Msg; } + +private: + std::string Msg; + std::error_code EC; + const bool PrintMsgOnly = false; +}; + +/// Create formatted StringError object. +template +inline Error createStringError(std::error_code EC, char const *Fmt, + const Ts &... Vals) { + std::string Buffer; + raw_string_ostream Stream(Buffer); + Stream << format(Fmt, Vals...); + return make_error(Stream.str(), EC); +} + +Error createStringError(std::error_code EC, char const *Msg); + +inline Error createStringError(std::error_code EC, const Twine &S) { + return createStringError(EC, S.str().c_str()); +} + +template +inline Error createStringError(std::errc EC, char const *Fmt, + const Ts &... Vals) { + return createStringError(std::make_error_code(EC), Fmt, Vals...); +} + +/// This class wraps a filename and another Error. +/// +/// In some cases, an error needs to live along a 'source' name, in order to +/// show more detailed information to the user. +class FileError final : public ErrorInfo { + + friend Error createFileError(const Twine &, Error); + friend Error createFileError(const Twine &, size_t, Error); + +public: + void log(raw_ostream &OS) const override { + assert(Err && "Trying to log after takeError()."); + OS << "'" << FileName << "': "; + if (Line) + OS << "line " << *Line << ": "; + Err->log(OS); + } + + std::string messageWithoutFileInfo() const { + std::string Msg; + raw_string_ostream OS(Msg); + Err->log(OS); + return OS.str(); + } + + StringRef getFileName() const { return FileName; } + + Error takeError() { return Error(std::move(Err)); } + + std::error_code convertToErrorCode() const override; + + // Used by ErrorInfo::classID. + static char ID; + +private: + FileError(const Twine &F, std::optional LineNum, + std::unique_ptr E) { + assert(E && "Cannot create FileError from Error success value."); + FileName = F.str(); + Err = std::move(E); + Line = std::move(LineNum); + } + + static Error build(const Twine &F, std::optional Line, Error E) { + std::unique_ptr Payload; + handleAllErrors(std::move(E), + [&](std::unique_ptr EIB) -> Error { + Payload = std::move(EIB); + return Error::success(); + }); + return Error( + std::unique_ptr(new FileError(F, Line, std::move(Payload)))); + } + + std::string FileName; + std::optional Line; + std::unique_ptr Err; +}; + +/// Concatenate a source file path and/or name with an Error. The resulting +/// Error is unchecked. +inline Error createFileError(const Twine &F, Error E) { + return FileError::build(F, std::optional(), std::move(E)); +} + +/// Concatenate a source file path and/or name with line number and an Error. +/// The resulting Error is unchecked. +inline Error createFileError(const Twine &F, size_t Line, Error E) { + return FileError::build(F, std::optional(Line), std::move(E)); +} + +/// Concatenate a source file path and/or name with a std::error_code +/// to form an Error object. +inline Error createFileError(const Twine &F, std::error_code EC) { + return createFileError(F, errorCodeToError(EC)); +} + +/// Concatenate a source file path and/or name with line number and +/// std::error_code to form an Error object. +inline Error createFileError(const Twine &F, size_t Line, std::error_code EC) { + return createFileError(F, Line, errorCodeToError(EC)); +} + +Error createFileError(const Twine &F, ErrorSuccess) = delete; + +/// Helper for check-and-exit error handling. +/// +/// For tool use only. NOT FOR USE IN LIBRARY CODE. +/// +class ExitOnError { +public: + /// Create an error on exit helper. + ExitOnError(std::string Banner = "", int DefaultErrorExitCode = 1) + : Banner(std::move(Banner)), + GetExitCode([=](const Error &) { return DefaultErrorExitCode; }) {} + + /// Set the banner string for any errors caught by operator(). + void setBanner(std::string Banner) { this->Banner = std::move(Banner); } + + /// Set the exit-code mapper function. + void setExitCodeMapper(std::function GetExitCode) { + this->GetExitCode = std::move(GetExitCode); + } + + /// Check Err. If it's in a failure state log the error(s) and exit. + void operator()(Error Err) const { checkError(std::move(Err)); } + + /// Check E. If it's in a success state then return the contained value. If + /// it's in a failure state log the error(s) and exit. + template T operator()(Expected &&E) const { + checkError(E.takeError()); + return std::move(*E); + } + + /// Check E. If it's in a success state then return the contained reference. If + /// it's in a failure state log the error(s) and exit. + template T& operator()(Expected &&E) const { + checkError(E.takeError()); + return *E; + } + +private: + void checkError(Error Err) const { + if (Err) { + int ExitCode = GetExitCode(Err); + logAllUnhandledErrors(std::move(Err), errs(), Banner); + exit(ExitCode); + } + } + + std::string Banner; + std::function GetExitCode; +}; + +/// Conversion from Error to LLVMErrorRef for C error bindings. +inline LLVMErrorRef wrap(Error Err) { + return reinterpret_cast(Err.takePayload().release()); +} + +/// Conversion from LLVMErrorRef to Error for C error bindings. +inline Error unwrap(LLVMErrorRef ErrRef) { + return Error(std::unique_ptr( + reinterpret_cast(ErrRef))); +} + +} // end namespace llvm + +#endif // LLVM_SUPPORT_ERROR_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/ErrorOr.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/ErrorOr.h new file mode 100644 index 00000000000..97c7abe1f20 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/ErrorOr.h @@ -0,0 +1,271 @@ +//===- llvm/Support/ErrorOr.h - Error Smart Pointer -------------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// +/// Provides ErrorOr smart pointer. +/// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_ERROROR_H +#define LLVM_SUPPORT_ERROROR_H + +#include "llvm/Support/AlignOf.h" +#include +#include +#include +#include + +namespace llvm { + +/// Represents either an error or a value T. +/// +/// ErrorOr is a pointer-like class that represents the result of an +/// operation. The result is either an error, or a value of type T. This is +/// designed to emulate the usage of returning a pointer where nullptr indicates +/// failure. However instead of just knowing that the operation failed, we also +/// have an error_code and optional user data that describes why it failed. +/// +/// It is used like the following. +/// \code +/// ErrorOr getBuffer(); +/// +/// auto buffer = getBuffer(); +/// if (error_code ec = buffer.getError()) +/// return ec; +/// buffer->write("adena"); +/// \endcode +/// +/// +/// Implicit conversion to bool returns true if there is a usable value. The +/// unary * and -> operators provide pointer like access to the value. Accessing +/// the value when there is an error has undefined behavior. +/// +/// When T is a reference type the behavior is slightly different. The reference +/// is held in a std::reference_wrapper::type>, and +/// there is special handling to make operator -> work as if T was not a +/// reference. +/// +/// T cannot be a rvalue reference. +template +class ErrorOr { + template friend class ErrorOr; + + static constexpr bool isRef = std::is_reference_v; + + using wrap = std::reference_wrapper>; + +public: + using storage_type = std::conditional_t; + +private: + using reference = std::remove_reference_t &; + using const_reference = const std::remove_reference_t &; + using pointer = std::remove_reference_t *; + using const_pointer = const std::remove_reference_t *; + +public: + template + ErrorOr(E ErrorCode, + std::enable_if_t::value || + std::is_error_condition_enum::value, + void *> = nullptr) + : HasError(true) { + new (getErrorStorage()) std::error_code(make_error_code(ErrorCode)); + } + + ErrorOr(std::error_code EC) : HasError(true) { + new (getErrorStorage()) std::error_code(EC); + } + + template + ErrorOr(OtherT &&Val, + std::enable_if_t> * = nullptr) + : HasError(false) { + new (getStorage()) storage_type(std::forward(Val)); + } + + ErrorOr(const ErrorOr &Other) { + copyConstruct(Other); + } + + template + ErrorOr(const ErrorOr &Other, + std::enable_if_t> * = nullptr) { + copyConstruct(Other); + } + + template + explicit ErrorOr( + const ErrorOr &Other, + std::enable_if_t> * = nullptr) { + copyConstruct(Other); + } + + ErrorOr(ErrorOr &&Other) { + moveConstruct(std::move(Other)); + } + + template + ErrorOr(ErrorOr &&Other, + std::enable_if_t> * = nullptr) { + moveConstruct(std::move(Other)); + } + + // This might eventually need SFINAE but it's more complex than is_convertible + // & I'm too lazy to write it right now. + template + explicit ErrorOr( + ErrorOr &&Other, + std::enable_if_t> * = nullptr) { + moveConstruct(std::move(Other)); + } + + ErrorOr &operator=(const ErrorOr &Other) { + copyAssign(Other); + return *this; + } + + ErrorOr &operator=(ErrorOr &&Other) { + moveAssign(std::move(Other)); + return *this; + } + + ~ErrorOr() { + if (!HasError) + getStorage()->~storage_type(); + } + + /// Return false if there is an error. + explicit operator bool() const { + return !HasError; + } + + reference get() { return *getStorage(); } + const_reference get() const { return const_cast *>(this)->get(); } + + std::error_code getError() const { + return HasError ? *getErrorStorage() : std::error_code(); + } + + pointer operator ->() { + return toPointer(getStorage()); + } + + const_pointer operator->() const { return toPointer(getStorage()); } + + reference operator *() { + return *getStorage(); + } + + const_reference operator*() const { return *getStorage(); } + +private: + template + void copyConstruct(const ErrorOr &Other) { + if (!Other.HasError) { + // Get the other value. + HasError = false; + new (getStorage()) storage_type(*Other.getStorage()); + } else { + // Get other's error. + HasError = true; + new (getErrorStorage()) std::error_code(Other.getError()); + } + } + + template + static bool compareThisIfSameType(const T1 &a, const T1 &b) { + return &a == &b; + } + + template + static bool compareThisIfSameType(const T1 &a, const T2 &b) { + return false; + } + + template + void copyAssign(const ErrorOr &Other) { + if (compareThisIfSameType(*this, Other)) + return; + + this->~ErrorOr(); + new (this) ErrorOr(Other); + } + + template + void moveConstruct(ErrorOr &&Other) { + if (!Other.HasError) { + // Get the other value. + HasError = false; + new (getStorage()) storage_type(std::move(*Other.getStorage())); + } else { + // Get other's error. + HasError = true; + new (getErrorStorage()) std::error_code(Other.getError()); + } + } + + template + void moveAssign(ErrorOr &&Other) { + if (compareThisIfSameType(*this, Other)) + return; + + this->~ErrorOr(); + new (this) ErrorOr(std::move(Other)); + } + + pointer toPointer(pointer Val) { + return Val; + } + + const_pointer toPointer(const_pointer Val) const { return Val; } + + pointer toPointer(wrap *Val) { + return &Val->get(); + } + + const_pointer toPointer(const wrap *Val) const { return &Val->get(); } + + storage_type *getStorage() { + assert(!HasError && "Cannot get value when an error exists!"); + return reinterpret_cast(&TStorage); + } + + const storage_type *getStorage() const { + assert(!HasError && "Cannot get value when an error exists!"); + return reinterpret_cast(&TStorage); + } + + std::error_code *getErrorStorage() { + assert(HasError && "Cannot get error when a value exists!"); + return reinterpret_cast(&ErrorStorage); + } + + const std::error_code *getErrorStorage() const { + return const_cast *>(this)->getErrorStorage(); + } + + union { + AlignedCharArrayUnion TStorage; + AlignedCharArrayUnion ErrorStorage; + }; + bool HasError : 1; +}; + +template +std::enable_if_t::value || + std::is_error_condition_enum::value, + bool> +operator==(const ErrorOr &Err, E Code) { + return Err.getError() == Code; +} + +} // end namespace llvm + +#endif // LLVM_SUPPORT_ERROROR_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/FileOutputBuffer.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/FileOutputBuffer.h new file mode 100644 index 00000000000..d4b73522115 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/FileOutputBuffer.h @@ -0,0 +1,86 @@ +//=== FileOutputBuffer.h - File Output Buffer -------------------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// Utility for creating a in-memory buffer that will be written to a file. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_FILEOUTPUTBUFFER_H +#define LLVM_SUPPORT_FILEOUTPUTBUFFER_H + +#include "llvm/ADT/StringRef.h" +#include "llvm/Support/DataTypes.h" +#include "llvm/Support/Error.h" + +namespace llvm { +/// FileOutputBuffer - This interface provides simple way to create an in-memory +/// buffer which will be written to a file. During the lifetime of these +/// objects, the content or existence of the specified file is undefined. That +/// is, creating an OutputBuffer for a file may immediately remove the file. +/// If the FileOutputBuffer is committed, the target file's content will become +/// the buffer content at the time of the commit. If the FileOutputBuffer is +/// not committed, the file will be deleted in the FileOutputBuffer destructor. +class FileOutputBuffer { +public: + enum { + /// Set the 'x' bit on the resulting file. + F_executable = 1, + + /// Don't use mmap and instead write an in-memory buffer to a file when this + /// buffer is closed. + F_no_mmap = 2, + }; + + /// Factory method to create an OutputBuffer object which manages a read/write + /// buffer of the specified size. When committed, the buffer will be written + /// to the file at the specified path. + /// + /// When F_modify is specified and \p FilePath refers to an existing on-disk + /// file \p Size may be set to -1, in which case the entire file is used. + /// Otherwise, the file shrinks or grows as necessary based on the value of + /// \p Size. It is an error to specify F_modify and Size=-1 if \p FilePath + /// does not exist. + static Expected> + create(StringRef FilePath, size_t Size, unsigned Flags = 0); + + /// Returns a pointer to the start of the buffer. + virtual uint8_t *getBufferStart() const = 0; + + /// Returns a pointer to the end of the buffer. + virtual uint8_t *getBufferEnd() const = 0; + + /// Returns size of the buffer. + virtual size_t getBufferSize() const = 0; + + /// Returns path where file will show up if buffer is committed. + StringRef getPath() const { return FinalPath; } + + /// Flushes the content of the buffer to its file and deallocates the + /// buffer. If commit() is not called before this object's destructor + /// is called, the file is deleted in the destructor. The optional parameter + /// is used if it turns out you want the file size to be smaller than + /// initially requested. + virtual Error commit() = 0; + + /// If this object was previously committed, the destructor just deletes + /// this object. If this object was not committed, the destructor + /// deallocates the buffer and the target file is never written. + virtual ~FileOutputBuffer() = default; + + /// This removes the temporary file (unless it already was committed) + /// but keeps the memory mapping alive. + virtual void discard() {} + +protected: + FileOutputBuffer(StringRef Path) : FinalPath(Path) {} + + std::string FinalPath; +}; +} // end namespace llvm + +#endif diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/Format.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/Format.h new file mode 100644 index 00000000000..89b6ae35ba5 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/Format.h @@ -0,0 +1,260 @@ +//===- Format.h - Efficient printf-style formatting for streams -*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file implements the format() function, which can be used with other +// LLVM subsystems to provide printf-style formatting. This gives all the power +// and risk of printf. This can be used like this (with raw_ostreams as an +// example): +// +// OS << "mynumber: " << format("%4.5f", 1234.412) << '\n'; +// +// Or if you prefer: +// +// OS << format("mynumber: %4.5f\n", 1234.412); +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_FORMAT_H +#define LLVM_SUPPORT_FORMAT_H + +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/Support/DataTypes.h" +#include +#include +#include +#include +#include + +namespace llvm { + +/// This is a helper class used for handling formatted output. It is the +/// abstract base class of a templated derived class. +class format_object_base { +protected: + const char *Fmt; + ~format_object_base() = default; // Disallow polymorphic deletion. + format_object_base(const format_object_base &) = default; + virtual void home(); // Out of line virtual method. + + /// Call snprintf() for this object, on the given buffer and size. + virtual int snprint(char *Buffer, unsigned BufferSize) const = 0; + +public: + format_object_base(const char *fmt) : Fmt(fmt) {} + + /// Format the object into the specified buffer. On success, this returns + /// the length of the formatted string. If the buffer is too small, this + /// returns a length to retry with, which will be larger than BufferSize. + unsigned print(char *Buffer, unsigned BufferSize) const { + assert(BufferSize && "Invalid buffer size!"); + + // Print the string, leaving room for the terminating null. + int N = snprint(Buffer, BufferSize); + + // VC++ and old GlibC return negative on overflow, just double the size. + if (N < 0) + return BufferSize * 2; + + // Other implementations yield number of bytes needed, not including the + // final '\0'. + if (unsigned(N) >= BufferSize) + return N + 1; + + // Otherwise N is the length of output (not including the final '\0'). + return N; + } +}; + +/// These are templated helper classes used by the format function that +/// capture the object to be formatted and the format string. When actually +/// printed, this synthesizes the string into a temporary buffer provided and +/// returns whether or not it is big enough. + +// Helper to validate that format() parameters are scalars or pointers. +template struct validate_format_parameters; +template +struct validate_format_parameters { + static_assert(std::is_scalar_v, + "format can't be used with non fundamental / non pointer type"); + validate_format_parameters() { validate_format_parameters(); } +}; +template <> struct validate_format_parameters<> {}; + +template +class format_object final : public format_object_base { + std::tuple Vals; + + template + int snprint_tuple(char *Buffer, unsigned BufferSize, + std::index_sequence) const { +#ifdef _MSC_VER + return _snprintf(Buffer, BufferSize, Fmt, std::get(Vals)...); +#else + return snprintf(Buffer, BufferSize, Fmt, std::get(Vals)...); +#endif + } + +public: + format_object(const char *fmt, const Ts &... vals) + : format_object_base(fmt), Vals(vals...) { + validate_format_parameters(); + } + + int snprint(char *Buffer, unsigned BufferSize) const override { + return snprint_tuple(Buffer, BufferSize, std::index_sequence_for()); + } +}; + +/// These are helper functions used to produce formatted output. They use +/// template type deduction to construct the appropriate instance of the +/// format_object class to simplify their construction. +/// +/// This is typically used like: +/// \code +/// OS << format("%0.4f", myfloat) << '\n'; +/// \endcode + +template +inline format_object format(const char *Fmt, const Ts &... Vals) { + return format_object(Fmt, Vals...); +} + +/// This is a helper class for left_justify, right_justify, and center_justify. +class FormattedString { +public: + enum Justification { JustifyNone, JustifyLeft, JustifyRight, JustifyCenter }; + FormattedString(StringRef S, unsigned W, Justification J) + : Str(S), Width(W), Justify(J) {} + +private: + StringRef Str; + unsigned Width; + Justification Justify; + friend class raw_ostream; +}; + +/// left_justify - append spaces after string so total output is +/// \p Width characters. If \p Str is larger that \p Width, full string +/// is written with no padding. +inline FormattedString left_justify(StringRef Str, unsigned Width) { + return FormattedString(Str, Width, FormattedString::JustifyLeft); +} + +/// right_justify - add spaces before string so total output is +/// \p Width characters. If \p Str is larger that \p Width, full string +/// is written with no padding. +inline FormattedString right_justify(StringRef Str, unsigned Width) { + return FormattedString(Str, Width, FormattedString::JustifyRight); +} + +/// center_justify - add spaces before and after string so total output is +/// \p Width characters. If \p Str is larger that \p Width, full string +/// is written with no padding. +inline FormattedString center_justify(StringRef Str, unsigned Width) { + return FormattedString(Str, Width, FormattedString::JustifyCenter); +} + +/// This is a helper class used for format_hex() and format_decimal(). +class FormattedNumber { + uint64_t HexValue; + int64_t DecValue; + unsigned Width; + bool Hex; + bool Upper; + bool HexPrefix; + friend class raw_ostream; + +public: + FormattedNumber(uint64_t HV, int64_t DV, unsigned W, bool H, bool U, + bool Prefix) + : HexValue(HV), DecValue(DV), Width(W), Hex(H), Upper(U), + HexPrefix(Prefix) {} +}; + +/// format_hex - Output \p N as a fixed width hexadecimal. If number will not +/// fit in width, full number is still printed. Examples: +/// OS << format_hex(255, 4) => 0xff +/// OS << format_hex(255, 4, true) => 0xFF +/// OS << format_hex(255, 6) => 0x00ff +/// OS << format_hex(255, 2) => 0xff +inline FormattedNumber format_hex(uint64_t N, unsigned Width, + bool Upper = false) { + assert(Width <= 18 && "hex width must be <= 18"); + return FormattedNumber(N, 0, Width, true, Upper, true); +} + +/// format_hex_no_prefix - Output \p N as a fixed width hexadecimal. Does not +/// prepend '0x' to the outputted string. If number will not fit in width, +/// full number is still printed. Examples: +/// OS << format_hex_no_prefix(255, 2) => ff +/// OS << format_hex_no_prefix(255, 2, true) => FF +/// OS << format_hex_no_prefix(255, 4) => 00ff +/// OS << format_hex_no_prefix(255, 1) => ff +inline FormattedNumber format_hex_no_prefix(uint64_t N, unsigned Width, + bool Upper = false) { + assert(Width <= 16 && "hex width must be <= 16"); + return FormattedNumber(N, 0, Width, true, Upper, false); +} + +/// format_decimal - Output \p N as a right justified, fixed-width decimal. If +/// number will not fit in width, full number is still printed. Examples: +/// OS << format_decimal(0, 5) => " 0" +/// OS << format_decimal(255, 5) => " 255" +/// OS << format_decimal(-1, 3) => " -1" +/// OS << format_decimal(12345, 3) => "12345" +inline FormattedNumber format_decimal(int64_t N, unsigned Width) { + return FormattedNumber(0, N, Width, false, false, false); +} + +class FormattedBytes { + ArrayRef Bytes; + + // If not std::nullopt, display offsets for each line relative to starting + // value. + std::optional FirstByteOffset; + uint32_t IndentLevel; // Number of characters to indent each line. + uint32_t NumPerLine; // Number of bytes to show per line. + uint8_t ByteGroupSize; // How many hex bytes are grouped without spaces + bool Upper; // Show offset and hex bytes as upper case. + bool ASCII; // Show the ASCII bytes for the hex bytes to the right. + friend class raw_ostream; + +public: + FormattedBytes(ArrayRef B, uint32_t IL, std::optional O, + uint32_t NPL, uint8_t BGS, bool U, bool A) + : Bytes(B), FirstByteOffset(O), IndentLevel(IL), NumPerLine(NPL), + ByteGroupSize(BGS), Upper(U), ASCII(A) { + + if (ByteGroupSize > NumPerLine) + ByteGroupSize = NumPerLine; + } +}; + +inline FormattedBytes +format_bytes(ArrayRef Bytes, + std::optional FirstByteOffset = std::nullopt, + uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4, + uint32_t IndentLevel = 0, bool Upper = false) { + return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine, + ByteGroupSize, Upper, false); +} + +inline FormattedBytes +format_bytes_with_ascii(ArrayRef Bytes, + std::optional FirstByteOffset = std::nullopt, + uint32_t NumPerLine = 16, uint8_t ByteGroupSize = 4, + uint32_t IndentLevel = 0, bool Upper = false) { + return FormattedBytes(Bytes, IndentLevel, FirstByteOffset, NumPerLine, + ByteGroupSize, Upper, true); +} + +} // end namespace llvm + +#endif diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/Memory.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/Memory.h new file mode 100644 index 00000000000..d7d60371d31 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/Memory.h @@ -0,0 +1,181 @@ +//===- llvm/Support/Memory.h - Memory Support -------------------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file declares the llvm::sys::Memory class. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_MEMORY_H +#define LLVM_SUPPORT_MEMORY_H + +#include "llvm/Support/DataTypes.h" +#include + +namespace llvm { + +// Forward declare raw_ostream: it is used for debug dumping below. +class raw_ostream; + +namespace sys { + + /// This class encapsulates the notion of a memory block which has an address + /// and a size. It is used by the Memory class (a friend) as the result of + /// various memory allocation operations. + /// @see Memory + /// Memory block abstraction. + class MemoryBlock { + public: + MemoryBlock() : Address(nullptr), AllocatedSize(0) {} + MemoryBlock(void *addr, size_t allocatedSize) + : Address(addr), AllocatedSize(allocatedSize) {} + void *base() const { return Address; } + /// The size as it was allocated. This is always greater or equal to the + /// size that was originally requested. + size_t allocatedSize() const { return AllocatedSize; } + + private: + void *Address; ///< Address of first byte of memory area + size_t AllocatedSize; ///< Size, in bytes of the memory area + unsigned Flags = 0; + friend class Memory; + }; + + /// This class provides various memory handling functions that manipulate + /// MemoryBlock instances. + /// @since 1.4 + /// An abstraction for memory operations. + class Memory { + public: + enum ProtectionFlags { + MF_READ = 0x1000000, + MF_WRITE = 0x2000000, + MF_EXEC = 0x4000000, + MF_RWE_MASK = 0x7000000, + + /// The \p MF_HUGE_HINT flag is used to indicate that the request for + /// a memory block should be satisfied with large pages if possible. + /// This is only a hint and small pages will be used as fallback. + /// + /// The presence or absence of this flag in the returned memory block + /// is (at least currently) *not* a reliable indicator that the memory + /// block will use or will not use large pages. On some systems a request + /// without this flag can be backed by large pages without this flag being + /// set, and on some other systems a request with this flag can fallback + /// to small pages without this flag being cleared. + MF_HUGE_HINT = 0x0000001 + }; + + /// This method allocates a block of memory that is suitable for loading + /// dynamically generated code (e.g. JIT). An attempt to allocate + /// \p NumBytes bytes of virtual memory is made. + /// \p NearBlock may point to an existing allocation in which case + /// an attempt is made to allocate more memory near the existing block. + /// The actual allocated address is not guaranteed to be near the requested + /// address. + /// \p Flags is used to set the initial protection flags for the block + /// of the memory. + /// \p EC [out] returns an object describing any error that occurs. + /// + /// This method may allocate more than the number of bytes requested. The + /// actual number of bytes allocated is indicated in the returned + /// MemoryBlock. + /// + /// The start of the allocated block must be aligned with the + /// system allocation granularity (64K on Windows, page size on Linux). + /// If the address following \p NearBlock is not so aligned, it will be + /// rounded up to the next allocation granularity boundary. + /// + /// \r a non-null MemoryBlock if the function was successful, + /// otherwise a null MemoryBlock is with \p EC describing the error. + /// + /// Allocate mapped memory. + static MemoryBlock allocateMappedMemory(size_t NumBytes, + const MemoryBlock *const NearBlock, + unsigned Flags, + std::error_code &EC); + + /// This method releases a block of memory that was allocated with the + /// allocateMappedMemory method. It should not be used to release any + /// memory block allocated any other way. + /// \p Block describes the memory to be released. + /// + /// \r error_success if the function was successful, or an error_code + /// describing the failure if an error occurred. + /// + /// Release mapped memory. + static std::error_code releaseMappedMemory(MemoryBlock &Block); + + /// This method sets the protection flags for a block of memory to the + /// state specified by /p Flags. The behavior is not specified if the + /// memory was not allocated using the allocateMappedMemory method. + /// \p Block describes the memory block to be protected. + /// \p Flags specifies the new protection state to be assigned to the block. + /// + /// If \p Flags is MF_WRITE, the actual behavior varies + /// with the operating system (i.e. MF_READ | MF_WRITE on Windows) and the + /// target architecture (i.e. MF_WRITE -> MF_READ | MF_WRITE on i386). + /// + /// \r error_success if the function was successful, or an error_code + /// describing the failure if an error occurred. + /// + /// Set memory protection state. + static std::error_code protectMappedMemory(const MemoryBlock &Block, + unsigned Flags); + + /// InvalidateInstructionCache - Before the JIT can run a block of code + /// that has been emitted it must invalidate the instruction cache on some + /// platforms. + static void InvalidateInstructionCache(const void *Addr, size_t Len); + }; + + /// Owning version of MemoryBlock. + class OwningMemoryBlock { + public: + OwningMemoryBlock() = default; + explicit OwningMemoryBlock(MemoryBlock M) : M(M) {} + OwningMemoryBlock(OwningMemoryBlock &&Other) { + M = Other.M; + Other.M = MemoryBlock(); + } + OwningMemoryBlock& operator=(OwningMemoryBlock &&Other) { + M = Other.M; + Other.M = MemoryBlock(); + return *this; + } + ~OwningMemoryBlock() { + if (M.base()) + Memory::releaseMappedMemory(M); + } + void *base() const { return M.base(); } + /// The size as it was allocated. This is always greater or equal to the + /// size that was originally requested. + size_t allocatedSize() const { return M.allocatedSize(); } + MemoryBlock getMemoryBlock() const { return M; } + std::error_code release() { + std::error_code EC; + if (M.base()) { + EC = Memory::releaseMappedMemory(M); + M = MemoryBlock(); + } + return EC; + } + private: + MemoryBlock M; + }; + +#ifndef NDEBUG + /// Debugging output for Memory::ProtectionFlags. + raw_ostream &operator<<(raw_ostream &OS, const Memory::ProtectionFlags &PF); + + /// Debugging output for MemoryBlock. + raw_ostream &operator<<(raw_ostream &OS, const MemoryBlock &MB); +#endif // ifndef NDEBUG + } // end namespace sys + } // end namespace llvm + +#endif diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/MemoryBuffer.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/MemoryBuffer.h new file mode 100644 index 00000000000..b3477f1db0e --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/MemoryBuffer.h @@ -0,0 +1,291 @@ +//===--- MemoryBuffer.h - Memory Buffer Interface ---------------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file defines the MemoryBuffer interface. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_MEMORYBUFFER_H +#define LLVM_SUPPORT_MEMORYBUFFER_H + +#include "llvm-c/Types.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/ADT/Twine.h" +#include "llvm/Support/Alignment.h" +#include "llvm/Support/CBindingWrapping.h" +#include "llvm/Support/ErrorOr.h" +#include "llvm/Support/MemoryBufferRef.h" +#include +#include +#include + +namespace llvm { +namespace sys { +namespace fs { +// Duplicated from FileSystem.h to avoid a dependency. +#if defined(_WIN32) +// A Win32 HANDLE is a typedef of void* +using file_t = void *; +#else +using file_t = int; +#endif +} // namespace fs +} // namespace sys + +/// This interface provides simple read-only access to a block of memory, and +/// provides simple methods for reading files and standard input into a memory +/// buffer. In addition to basic access to the characters in the file, this +/// interface guarantees you can read one character past the end of the file, +/// and that this character will read as '\0'. +/// +/// The '\0' guarantee is needed to support an optimization -- it's intended to +/// be more efficient for clients which are reading all the data to stop +/// reading when they encounter a '\0' than to continually check the file +/// position to see if it has reached the end of the file. +class MemoryBuffer { + const char *BufferStart; // Start of the buffer. + const char *BufferEnd; // End of the buffer. + +protected: + MemoryBuffer() = default; + + void init(const char *BufStart, const char *BufEnd, + bool RequiresNullTerminator); + +public: + MemoryBuffer(const MemoryBuffer &) = delete; + MemoryBuffer &operator=(const MemoryBuffer &) = delete; + virtual ~MemoryBuffer(); + + const char *getBufferStart() const { return BufferStart; } + const char *getBufferEnd() const { return BufferEnd; } + size_t getBufferSize() const { return BufferEnd-BufferStart; } + + StringRef getBuffer() const { + return StringRef(BufferStart, getBufferSize()); + } + + /// Return an identifier for this buffer, typically the filename it was read + /// from. + virtual StringRef getBufferIdentifier() const { return "Unknown buffer"; } + + /// For read-only MemoryBuffer_MMap, mark the buffer as unused in the near + /// future and the kernel can free resources associated with it. Further + /// access is supported but may be expensive. This calls + /// madvise(MADV_DONTNEED) on read-only file mappings on *NIX systems. This + /// function should not be called on a writable buffer. + virtual void dontNeedIfMmap() {} + + /// Open the specified file as a MemoryBuffer, returning a new MemoryBuffer + /// if successful, otherwise returning null. + /// + /// \param IsText Set to true to indicate that the file should be read in + /// text mode. + /// + /// \param IsVolatile Set to true to indicate that the contents of the file + /// can change outside the user's control, e.g. when libclang tries to parse + /// while the user is editing/updating the file or if the file is on an NFS. + /// + /// \param Alignment Set to indicate that the buffer should be aligned to at + /// least the specified alignment. + static ErrorOr> + getFile(const Twine &Filename, bool IsText = false, + bool RequiresNullTerminator = true, bool IsVolatile = false, + std::optional Alignment = std::nullopt); + + /// Read all of the specified file into a MemoryBuffer as a stream + /// (i.e. until EOF reached). This is useful for special files that + /// look like a regular file but have 0 size (e.g. /proc/cpuinfo on Linux). + static ErrorOr> + getFileAsStream(const Twine &Filename); + + /// Given an already-open file descriptor, map some slice of it into a + /// MemoryBuffer. The slice is specified by an \p Offset and \p MapSize. + /// Since this is in the middle of a file, the buffer is not null terminated. + static ErrorOr> + getOpenFileSlice(sys::fs::file_t FD, const Twine &Filename, uint64_t MapSize, + int64_t Offset, bool IsVolatile = false, + std::optional Alignment = std::nullopt); + + /// Given an already-open file descriptor, read the file and return a + /// MemoryBuffer. + /// + /// \param IsVolatile Set to true to indicate that the contents of the file + /// can change outside the user's control, e.g. when libclang tries to parse + /// while the user is editing/updating the file or if the file is on an NFS. + /// + /// \param Alignment Set to indicate that the buffer should be aligned to at + /// least the specified alignment. + static ErrorOr> + getOpenFile(sys::fs::file_t FD, const Twine &Filename, uint64_t FileSize, + bool RequiresNullTerminator = true, bool IsVolatile = false, + std::optional Alignment = std::nullopt); + + /// Open the specified memory range as a MemoryBuffer. Note that InputData + /// must be null terminated if RequiresNullTerminator is true. + static std::unique_ptr + getMemBuffer(StringRef InputData, StringRef BufferName = "", + bool RequiresNullTerminator = true); + + static std::unique_ptr + getMemBuffer(MemoryBufferRef Ref, bool RequiresNullTerminator = true); + + /// Open the specified memory range as a MemoryBuffer, copying the contents + /// and taking ownership of it. InputData does not have to be null terminated. + static std::unique_ptr + getMemBufferCopy(StringRef InputData, const Twine &BufferName = ""); + + /// Read all of stdin into a file buffer, and return it. + static ErrorOr> getSTDIN(); + + /// Open the specified file as a MemoryBuffer, or open stdin if the Filename + /// is "-". + static ErrorOr> + getFileOrSTDIN(const Twine &Filename, bool IsText = false, + bool RequiresNullTerminator = true, + std::optional Alignment = std::nullopt); + + /// Map a subrange of the specified file as a MemoryBuffer. + static ErrorOr> + getFileSlice(const Twine &Filename, uint64_t MapSize, uint64_t Offset, + bool IsVolatile = false, + std::optional Alignment = std::nullopt); + + //===--------------------------------------------------------------------===// + // Provided for performance analysis. + //===--------------------------------------------------------------------===// + + /// The kind of memory backing used to support the MemoryBuffer. + enum BufferKind { + MemoryBuffer_Malloc, + MemoryBuffer_MMap + }; + + /// Return information on the memory mechanism used to support the + /// MemoryBuffer. + virtual BufferKind getBufferKind() const = 0; + + MemoryBufferRef getMemBufferRef() const; +}; + +/// This class is an extension of MemoryBuffer, which allows copy-on-write +/// access to the underlying contents. It only supports creation methods that +/// are guaranteed to produce a writable buffer. For example, mapping a file +/// read-only is not supported. +class WritableMemoryBuffer : public MemoryBuffer { +protected: + WritableMemoryBuffer() = default; + +public: + using MemoryBuffer::getBuffer; + using MemoryBuffer::getBufferEnd; + using MemoryBuffer::getBufferStart; + + // const_cast is well-defined here, because the underlying buffer is + // guaranteed to have been initialized with a mutable buffer. + char *getBufferStart() { + return const_cast(MemoryBuffer::getBufferStart()); + } + char *getBufferEnd() { + return const_cast(MemoryBuffer::getBufferEnd()); + } + MutableArrayRef getBuffer() { + return {getBufferStart(), getBufferEnd()}; + } + + static ErrorOr> + getFile(const Twine &Filename, bool IsVolatile = false, + std::optional Alignment = std::nullopt); + + /// Map a subrange of the specified file as a WritableMemoryBuffer. + static ErrorOr> + getFileSlice(const Twine &Filename, uint64_t MapSize, uint64_t Offset, + bool IsVolatile = false, + std::optional Alignment = std::nullopt); + + /// Allocate a new MemoryBuffer of the specified size that is not initialized. + /// Note that the caller should initialize the memory allocated by this + /// method. The memory is owned by the MemoryBuffer object. + /// + /// \param Alignment Set to indicate that the buffer should be aligned to at + /// least the specified alignment. + static std::unique_ptr + getNewUninitMemBuffer(size_t Size, const Twine &BufferName = "", + std::optional Alignment = std::nullopt); + + /// Allocate a new zero-initialized MemoryBuffer of the specified size. Note + /// that the caller need not initialize the memory allocated by this method. + /// The memory is owned by the MemoryBuffer object. + static std::unique_ptr + getNewMemBuffer(size_t Size, const Twine &BufferName = ""); + +private: + // Hide these base class factory function so one can't write + // WritableMemoryBuffer::getXXX() + // and be surprised that he got a read-only Buffer. + using MemoryBuffer::getFileAsStream; + using MemoryBuffer::getFileOrSTDIN; + using MemoryBuffer::getMemBuffer; + using MemoryBuffer::getMemBufferCopy; + using MemoryBuffer::getOpenFile; + using MemoryBuffer::getOpenFileSlice; + using MemoryBuffer::getSTDIN; +}; + +/// This class is an extension of MemoryBuffer, which allows write access to +/// the underlying contents and committing those changes to the original source. +/// It only supports creation methods that are guaranteed to produce a writable +/// buffer. For example, mapping a file read-only is not supported. +class WriteThroughMemoryBuffer : public MemoryBuffer { +protected: + WriteThroughMemoryBuffer() = default; + +public: + using MemoryBuffer::getBuffer; + using MemoryBuffer::getBufferEnd; + using MemoryBuffer::getBufferStart; + + // const_cast is well-defined here, because the underlying buffer is + // guaranteed to have been initialized with a mutable buffer. + char *getBufferStart() { + return const_cast(MemoryBuffer::getBufferStart()); + } + char *getBufferEnd() { + return const_cast(MemoryBuffer::getBufferEnd()); + } + MutableArrayRef getBuffer() { + return {getBufferStart(), getBufferEnd()}; + } + + static ErrorOr> + getFile(const Twine &Filename, int64_t FileSize = -1); + + /// Map a subrange of the specified file as a ReadWriteMemoryBuffer. + static ErrorOr> + getFileSlice(const Twine &Filename, uint64_t MapSize, uint64_t Offset); + +private: + // Hide these base class factory function so one can't write + // WritableMemoryBuffer::getXXX() + // and be surprised that he got a read-only Buffer. + using MemoryBuffer::getFileAsStream; + using MemoryBuffer::getFileOrSTDIN; + using MemoryBuffer::getMemBuffer; + using MemoryBuffer::getMemBufferCopy; + using MemoryBuffer::getOpenFile; + using MemoryBuffer::getOpenFileSlice; + using MemoryBuffer::getSTDIN; +}; + +// Create wrappers for C Binding types (see CBindingWrapping.h). +DEFINE_SIMPLE_CONVERSION_FUNCTIONS(MemoryBuffer, LLVMMemoryBufferRef) + +} // end namespace llvm + +#endif // LLVM_SUPPORT_MEMORYBUFFER_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/MemoryBufferRef.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/MemoryBufferRef.h new file mode 100644 index 00000000000..b38a1f3b656 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/MemoryBufferRef.h @@ -0,0 +1,56 @@ +//===- MemoryBufferRef.h - Memory Buffer Reference --------------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file defines the MemoryBuffer interface. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_MEMORYBUFFERREF_H +#define LLVM_SUPPORT_MEMORYBUFFERREF_H + +#include "llvm/ADT/StringRef.h" + +namespace llvm { + +class MemoryBuffer; + +class MemoryBufferRef { + StringRef Buffer; + StringRef Identifier; + +public: + MemoryBufferRef() = default; + MemoryBufferRef(const MemoryBuffer &Buffer); + MemoryBufferRef(StringRef Buffer, StringRef Identifier) + : Buffer(Buffer), Identifier(Identifier) {} + + StringRef getBuffer() const { return Buffer; } + StringRef getBufferIdentifier() const { return Identifier; } + + const char *getBufferStart() const { return Buffer.begin(); } + const char *getBufferEnd() const { return Buffer.end(); } + size_t getBufferSize() const { return Buffer.size(); } + + /// Check pointer identity (not value) of identifier and data. + friend bool operator==(const MemoryBufferRef &LHS, + const MemoryBufferRef &RHS) { + return LHS.Buffer.begin() == RHS.Buffer.begin() && + LHS.Buffer.end() == RHS.Buffer.end() && + LHS.Identifier.begin() == RHS.Identifier.begin() && + LHS.Identifier.end() == RHS.Identifier.end(); + } + + friend bool operator!=(const MemoryBufferRef &LHS, + const MemoryBufferRef &RHS) { + return !(LHS == RHS); + } +}; + +} // namespace llvm + +#endif // LLVM_SUPPORT_MEMORYBUFFERREF_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/VersionTuple.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/VersionTuple.h new file mode 100644 index 00000000000..715108af0d7 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/VersionTuple.h @@ -0,0 +1,222 @@ +//===- VersionTuple.h - Version Number Handling -----------------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +/// +/// \file +/// Defines the llvm::VersionTuple class, which represents a version in +/// the form major[.minor[.subminor]]. +/// +//===----------------------------------------------------------------------===// +#ifndef LLVM_SUPPORT_VERSIONTUPLE_H +#define LLVM_SUPPORT_VERSIONTUPLE_H + +#include "llvm/ADT/DenseMapInfo.h" +#include "llvm/ADT/Hashing.h" +#include "llvm/Support/Endian.h" +#include +#include +#include + +namespace llvm { +template +class HashBuilderImpl; +class raw_ostream; +class StringRef; + +/// Represents a version number in the form major[.minor[.subminor[.build]]]. +class VersionTuple { + unsigned Major : 32; + + unsigned Minor : 31; + unsigned HasMinor : 1; + + unsigned Subminor : 31; + unsigned HasSubminor : 1; + + unsigned Build : 31; + unsigned HasBuild : 1; + +public: + constexpr VersionTuple() + : Major(0), Minor(0), HasMinor(false), Subminor(0), HasSubminor(false), + Build(0), HasBuild(false) {} + + explicit constexpr VersionTuple(unsigned Major) + : Major(Major), Minor(0), HasMinor(false), Subminor(0), + HasSubminor(false), Build(0), HasBuild(false) {} + + explicit constexpr VersionTuple(unsigned Major, unsigned Minor) + : Major(Major), Minor(Minor), HasMinor(true), Subminor(0), + HasSubminor(false), Build(0), HasBuild(false) {} + + explicit constexpr VersionTuple(unsigned Major, unsigned Minor, + unsigned Subminor) + : Major(Major), Minor(Minor), HasMinor(true), Subminor(Subminor), + HasSubminor(true), Build(0), HasBuild(false) {} + + explicit constexpr VersionTuple(unsigned Major, unsigned Minor, + unsigned Subminor, unsigned Build) + : Major(Major), Minor(Minor), HasMinor(true), Subminor(Subminor), + HasSubminor(true), Build(Build), HasBuild(true) {} + + /// Determine whether this version information is empty + /// (e.g., all version components are zero). + bool empty() const { + return Major == 0 && Minor == 0 && Subminor == 0 && Build == 0; + } + + /// Whether this is a non-empty version tuple. + explicit operator bool () const { return !empty(); } + + /// Retrieve the major version number. + unsigned getMajor() const { return Major; } + + /// Retrieve the minor version number, if provided. + std::optional getMinor() const { + if (!HasMinor) + return std::nullopt; + return Minor; + } + + /// Retrieve the subminor version number, if provided. + std::optional getSubminor() const { + if (!HasSubminor) + return std::nullopt; + return Subminor; + } + + /// Retrieve the build version number, if provided. + std::optional getBuild() const { + if (!HasBuild) + return std::nullopt; + return Build; + } + + /// Return a version tuple that contains only the first 3 version components. + VersionTuple withoutBuild() const { + if (HasBuild) + return VersionTuple(Major, Minor, Subminor); + return *this; + } + + /// Return a version tuple that contains a different major version but + /// everything else is the same. + VersionTuple withMajorReplaced(unsigned NewMajor) const { + return VersionTuple(NewMajor, Minor, Subminor, Build); + } + + /// Return a version tuple that contains only components that are non-zero. + VersionTuple normalize() const { + VersionTuple Result = *this; + if (Result.Build == 0) { + Result.HasBuild = false; + if (Result.Subminor == 0) { + Result.HasSubminor = false; + if (Result.Minor == 0) + Result.HasMinor = false; + } + } + return Result; + } + + /// Determine if two version numbers are equivalent. If not + /// provided, minor and subminor version numbers are considered to be zero. + friend bool operator==(const VersionTuple &X, const VersionTuple &Y) { + return X.Major == Y.Major && X.Minor == Y.Minor && + X.Subminor == Y.Subminor && X.Build == Y.Build; + } + + /// Determine if two version numbers are not equivalent. + /// + /// If not provided, minor and subminor version numbers are considered to be + /// zero. + friend bool operator!=(const VersionTuple &X, const VersionTuple &Y) { + return !(X == Y); + } + + /// Determine whether one version number precedes another. + /// + /// If not provided, minor and subminor version numbers are considered to be + /// zero. + friend bool operator<(const VersionTuple &X, const VersionTuple &Y) { + return std::tie(X.Major, X.Minor, X.Subminor, X.Build) < + std::tie(Y.Major, Y.Minor, Y.Subminor, Y.Build); + } + + /// Determine whether one version number follows another. + /// + /// If not provided, minor and subminor version numbers are considered to be + /// zero. + friend bool operator>(const VersionTuple &X, const VersionTuple &Y) { + return Y < X; + } + + /// Determine whether one version number precedes or is + /// equivalent to another. + /// + /// If not provided, minor and subminor version numbers are considered to be + /// zero. + friend bool operator<=(const VersionTuple &X, const VersionTuple &Y) { + return !(Y < X); + } + + /// Determine whether one version number follows or is + /// equivalent to another. + /// + /// If not provided, minor and subminor version numbers are considered to be + /// zero. + friend bool operator>=(const VersionTuple &X, const VersionTuple &Y) { + return !(X < Y); + } + + friend hash_code hash_value(const VersionTuple &VT) { + return hash_combine(VT.Major, VT.Minor, VT.Subminor, VT.Build); + } + + template + friend void addHash(HashBuilderImpl &HBuilder, + const VersionTuple &VT) { + HBuilder.add(VT.Major, VT.Minor, VT.Subminor, VT.Build); + } + + /// Retrieve a string representation of the version number. + std::string getAsString() const; + + /// Try to parse the given string as a version number. + /// \returns \c true if the string does not match the regular expression + /// [0-9]+(\.[0-9]+){0,3} + bool tryParse(StringRef string); +}; + +/// Print a version number. +raw_ostream &operator<<(raw_ostream &Out, const VersionTuple &V); + +// Provide DenseMapInfo for version tuples. +template <> struct DenseMapInfo { + static inline VersionTuple getEmptyKey() { return VersionTuple(0x7FFFFFFF); } + static inline VersionTuple getTombstoneKey() { + return VersionTuple(0x7FFFFFFE); + } + static unsigned getHashValue(const VersionTuple &Value) { + unsigned Result = Value.getMajor(); + if (auto Minor = Value.getMinor()) + Result = detail::combineHashValue(Result, *Minor); + if (auto Subminor = Value.getSubminor()) + Result = detail::combineHashValue(Result, *Subminor); + if (auto Build = Value.getBuild()) + Result = detail::combineHashValue(Result, *Build); + + return Result; + } + + static bool isEqual(const VersionTuple &LHS, const VersionTuple &RHS) { + return LHS == RHS; + } +}; + +} // end namespace llvm +#endif // LLVM_SUPPORT_VERSIONTUPLE_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/raw_ostream.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/raw_ostream.h new file mode 100644 index 00000000000..1e01eb9ea19 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/Support/raw_ostream.h @@ -0,0 +1,771 @@ +//===--- raw_ostream.h - Raw output stream ----------------------*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +// This file defines the raw_ostream class. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_SUPPORT_RAW_OSTREAM_H +#define LLVM_SUPPORT_RAW_OSTREAM_H + +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/Support/DataTypes.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace llvm { + +class Duration; +class formatv_object_base; +class format_object_base; +class FormattedString; +class FormattedNumber; +class FormattedBytes; +template class [[nodiscard]] Expected; + +namespace sys { +namespace fs { +enum FileAccess : unsigned; +enum OpenFlags : unsigned; +enum CreationDisposition : unsigned; +class FileLocker; +} // end namespace fs +} // end namespace sys + +/// This class implements an extremely fast bulk output stream that can *only* +/// output to a stream. It does not support seeking, reopening, rewinding, line +/// buffered disciplines etc. It is a simple buffer that outputs +/// a chunk at a time. +class raw_ostream { +public: + // Class kinds to support LLVM-style RTTI. + enum class OStreamKind { + OK_OStream, + OK_FDStream, + }; + +private: + OStreamKind Kind; + + /// The buffer is handled in such a way that the buffer is + /// uninitialized, unbuffered, or out of space when OutBufCur >= + /// OutBufEnd. Thus a single comparison suffices to determine if we + /// need to take the slow path to write a single character. + /// + /// The buffer is in one of three states: + /// 1. Unbuffered (BufferMode == Unbuffered) + /// 1. Uninitialized (BufferMode != Unbuffered && OutBufStart == 0). + /// 2. Buffered (BufferMode != Unbuffered && OutBufStart != 0 && + /// OutBufEnd - OutBufStart >= 1). + /// + /// If buffered, then the raw_ostream owns the buffer if (BufferMode == + /// InternalBuffer); otherwise the buffer has been set via SetBuffer and is + /// managed by the subclass. + /// + /// If a subclass installs an external buffer using SetBuffer then it can wait + /// for a \see write_impl() call to handle the data which has been put into + /// this buffer. + char *OutBufStart, *OutBufEnd, *OutBufCur; + bool ColorEnabled = false; + + /// Optional stream this stream is tied to. If this stream is written to, the + /// tied-to stream will be flushed first. + raw_ostream *TiedStream = nullptr; + + enum class BufferKind { + Unbuffered = 0, + InternalBuffer, + ExternalBuffer + } BufferMode; + +public: + // color order matches ANSI escape sequence, don't change + enum class Colors { + BLACK = 0, + RED, + GREEN, + YELLOW, + BLUE, + MAGENTA, + CYAN, + WHITE, + SAVEDCOLOR, + RESET, + }; + + static constexpr Colors BLACK = Colors::BLACK; + static constexpr Colors RED = Colors::RED; + static constexpr Colors GREEN = Colors::GREEN; + static constexpr Colors YELLOW = Colors::YELLOW; + static constexpr Colors BLUE = Colors::BLUE; + static constexpr Colors MAGENTA = Colors::MAGENTA; + static constexpr Colors CYAN = Colors::CYAN; + static constexpr Colors WHITE = Colors::WHITE; + static constexpr Colors SAVEDCOLOR = Colors::SAVEDCOLOR; + static constexpr Colors RESET = Colors::RESET; + + explicit raw_ostream(bool unbuffered = false, + OStreamKind K = OStreamKind::OK_OStream) + : Kind(K), BufferMode(unbuffered ? BufferKind::Unbuffered + : BufferKind::InternalBuffer) { + // Start out ready to flush. + OutBufStart = OutBufEnd = OutBufCur = nullptr; + } + + raw_ostream(const raw_ostream &) = delete; + void operator=(const raw_ostream &) = delete; + + virtual ~raw_ostream(); + + /// tell - Return the current offset with the file. + uint64_t tell() const { return current_pos() + GetNumBytesInBuffer(); } + + OStreamKind get_kind() const { return Kind; } + + //===--------------------------------------------------------------------===// + // Configuration Interface + //===--------------------------------------------------------------------===// + + /// If possible, pre-allocate \p ExtraSize bytes for stream data. + /// i.e. it extends internal buffers to keep additional ExtraSize bytes. + /// So that the stream could keep at least tell() + ExtraSize bytes + /// without re-allocations. reserveExtraSpace() does not change + /// the size/data of the stream. + virtual void reserveExtraSpace(uint64_t ExtraSize) {} + + /// Set the stream to be buffered, with an automatically determined buffer + /// size. + void SetBuffered(); + + /// Set the stream to be buffered, using the specified buffer size. + void SetBufferSize(size_t Size) { + flush(); + SetBufferAndMode(new char[Size], Size, BufferKind::InternalBuffer); + } + + size_t GetBufferSize() const { + // If we're supposed to be buffered but haven't actually gotten around + // to allocating the buffer yet, return the value that would be used. + if (BufferMode != BufferKind::Unbuffered && OutBufStart == nullptr) + return preferred_buffer_size(); + + // Otherwise just return the size of the allocated buffer. + return OutBufEnd - OutBufStart; + } + + /// Set the stream to be unbuffered. When unbuffered, the stream will flush + /// after every write. This routine will also flush the buffer immediately + /// when the stream is being set to unbuffered. + void SetUnbuffered() { + flush(); + SetBufferAndMode(nullptr, 0, BufferKind::Unbuffered); + } + + size_t GetNumBytesInBuffer() const { + return OutBufCur - OutBufStart; + } + + //===--------------------------------------------------------------------===// + // Data Output Interface + //===--------------------------------------------------------------------===// + + void flush() { + if (OutBufCur != OutBufStart) + flush_nonempty(); + } + + raw_ostream &operator<<(char C) { + if (OutBufCur >= OutBufEnd) + return write(C); + *OutBufCur++ = C; + return *this; + } + + raw_ostream &operator<<(unsigned char C) { + if (OutBufCur >= OutBufEnd) + return write(C); + *OutBufCur++ = C; + return *this; + } + + raw_ostream &operator<<(signed char C) { + if (OutBufCur >= OutBufEnd) + return write(C); + *OutBufCur++ = C; + return *this; + } + + raw_ostream &operator<<(StringRef Str) { + // Inline fast path, particularly for strings with a known length. + size_t Size = Str.size(); + + // Make sure we can use the fast path. + if (Size > (size_t)(OutBufEnd - OutBufCur)) + return write(Str.data(), Size); + + if (Size) { + memcpy(OutBufCur, Str.data(), Size); + OutBufCur += Size; + } + return *this; + } + +#if defined(__cpp_char8_t) + // When using `char8_t *` integers or pointers are written to the ostream + // instead of UTF-8 code as one might expect. This might lead to unexpected + // behavior, especially as `u8""` literals are of type `char8_t*` instead of + // type `char_t*` from C++20 onwards. Thus we disallow using them with + // raw_ostreams. + // If you have u8"" literals to stream, you can rewrite them as ordinary + // literals with escape sequences + // e.g. replace `u8"\u00a0"` by `"\xc2\xa0"` + // or use `reinterpret_cast`: + // e.g. replace `u8"\u00a0"` by `reinterpret_cast(u8"\u00a0")` + raw_ostream &operator<<(const char8_t *Str) = delete; +#endif + + raw_ostream &operator<<(const char *Str) { + // Inline fast path, particularly for constant strings where a sufficiently + // smart compiler will simplify strlen. + + return this->operator<<(StringRef(Str)); + } + + raw_ostream &operator<<(const std::string &Str) { + // Avoid the fast path, it would only increase code size for a marginal win. + return write(Str.data(), Str.length()); + } + + raw_ostream &operator<<(const std::string_view &Str) { + return write(Str.data(), Str.length()); + } + + raw_ostream &operator<<(const SmallVectorImpl &Str) { + return write(Str.data(), Str.size()); + } + + raw_ostream &operator<<(unsigned long N); + raw_ostream &operator<<(long N); + raw_ostream &operator<<(unsigned long long N); + raw_ostream &operator<<(long long N); + raw_ostream &operator<<(const void *P); + + raw_ostream &operator<<(unsigned int N) { + return this->operator<<(static_cast(N)); + } + + raw_ostream &operator<<(int N) { + return this->operator<<(static_cast(N)); + } + + raw_ostream &operator<<(double N); + + /// Output \p N in hexadecimal, without any prefix or padding. + raw_ostream &write_hex(unsigned long long N); + + // Change the foreground color of text. + raw_ostream &operator<<(Colors C); + + /// Output a formatted UUID with dash separators. + using uuid_t = uint8_t[16]; + raw_ostream &write_uuid(const uuid_t UUID); + + /// Output \p Str, turning '\\', '\t', '\n', '"', and anything that doesn't + /// satisfy llvm::isPrint into an escape sequence. + raw_ostream &write_escaped(StringRef Str, bool UseHexEscapes = false); + + raw_ostream &write(unsigned char C); + raw_ostream &write(const char *Ptr, size_t Size); + + // Formatted output, see the format() function in Support/Format.h. + raw_ostream &operator<<(const format_object_base &Fmt); + + // Formatted output, see the leftJustify() function in Support/Format.h. + raw_ostream &operator<<(const FormattedString &); + + // Formatted output, see the formatHex() function in Support/Format.h. + raw_ostream &operator<<(const FormattedNumber &); + + // Formatted output, see the formatv() function in Support/FormatVariadic.h. + raw_ostream &operator<<(const formatv_object_base &); + + // Formatted output, see the format_bytes() function in Support/Format.h. + raw_ostream &operator<<(const FormattedBytes &); + + /// indent - Insert 'NumSpaces' spaces. + raw_ostream &indent(unsigned NumSpaces); + + /// write_zeros - Insert 'NumZeros' nulls. + raw_ostream &write_zeros(unsigned NumZeros); + + /// Changes the foreground color of text that will be output from this point + /// forward. + /// @param Color ANSI color to use, the special SAVEDCOLOR can be used to + /// change only the bold attribute, and keep colors untouched + /// @param Bold bold/brighter text, default false + /// @param BG if true change the background, default: change foreground + /// @returns itself so it can be used within << invocations + virtual raw_ostream &changeColor(enum Colors Color, bool Bold = false, + bool BG = false); + + /// Resets the colors to terminal defaults. Call this when you are done + /// outputting colored text, or before program exit. + virtual raw_ostream &resetColor(); + + /// Reverses the foreground and background colors. + virtual raw_ostream &reverseColor(); + + /// This function determines if this stream is connected to a "tty" or + /// "console" window. That is, the output would be displayed to the user + /// rather than being put on a pipe or stored in a file. + virtual bool is_displayed() const { return false; } + + /// This function determines if this stream is displayed and supports colors. + /// The result is unaffected by calls to enable_color(). + virtual bool has_colors() const { return is_displayed(); } + + // Enable or disable colors. Once enable_colors(false) is called, + // changeColor() has no effect until enable_colors(true) is called. + virtual void enable_colors(bool enable) { ColorEnabled = enable; } + + bool colors_enabled() const { return ColorEnabled; } + + /// Tie this stream to the specified stream. Replaces any existing tied-to + /// stream. Specifying a nullptr unties the stream. + void tie(raw_ostream *TieTo) { TiedStream = TieTo; } + + //===--------------------------------------------------------------------===// + // Subclass Interface + //===--------------------------------------------------------------------===// + +private: + /// The is the piece of the class that is implemented by subclasses. This + /// writes the \p Size bytes starting at + /// \p Ptr to the underlying stream. + /// + /// This function is guaranteed to only be called at a point at which it is + /// safe for the subclass to install a new buffer via SetBuffer. + /// + /// \param Ptr The start of the data to be written. For buffered streams this + /// is guaranteed to be the start of the buffer. + /// + /// \param Size The number of bytes to be written. + /// + /// \invariant { Size > 0 } + virtual void write_impl(const char *Ptr, size_t Size) = 0; + + /// Return the current position within the stream, not counting the bytes + /// currently in the buffer. + virtual uint64_t current_pos() const = 0; + +protected: + /// Use the provided buffer as the raw_ostream buffer. This is intended for + /// use only by subclasses which can arrange for the output to go directly + /// into the desired output buffer, instead of being copied on each flush. + void SetBuffer(char *BufferStart, size_t Size) { + SetBufferAndMode(BufferStart, Size, BufferKind::ExternalBuffer); + } + + /// Return an efficient buffer size for the underlying output mechanism. + virtual size_t preferred_buffer_size() const; + + /// Return the beginning of the current stream buffer, or 0 if the stream is + /// unbuffered. + const char *getBufferStart() const { return OutBufStart; } + + //===--------------------------------------------------------------------===// + // Private Interface + //===--------------------------------------------------------------------===// +private: + /// Install the given buffer and mode. + void SetBufferAndMode(char *BufferStart, size_t Size, BufferKind Mode); + + /// Flush the current buffer, which is known to be non-empty. This outputs the + /// currently buffered data and resets the buffer to empty. + void flush_nonempty(); + + /// Copy data into the buffer. Size must not be greater than the number of + /// unused bytes in the buffer. + void copy_to_buffer(const char *Ptr, size_t Size); + + /// Compute whether colors should be used and do the necessary work such as + /// flushing. The result is affected by calls to enable_color(). + bool prepare_colors(); + + /// Flush the tied-to stream (if present) and then write the required data. + void flush_tied_then_write(const char *Ptr, size_t Size); + + virtual void anchor(); +}; + +/// Call the appropriate insertion operator, given an rvalue reference to a +/// raw_ostream object and return a stream of the same type as the argument. +template +std::enable_if_t && + std::is_base_of_v, + OStream &&> +operator<<(OStream &&OS, const T &Value) { + OS << Value; + return std::move(OS); +} + +/// An abstract base class for streams implementations that also support a +/// pwrite operation. This is useful for code that can mostly stream out data, +/// but needs to patch in a header that needs to know the output size. +class raw_pwrite_stream : public raw_ostream { + virtual void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) = 0; + void anchor() override; + +public: + explicit raw_pwrite_stream(bool Unbuffered = false, + OStreamKind K = OStreamKind::OK_OStream) + : raw_ostream(Unbuffered, K) {} + void pwrite(const char *Ptr, size_t Size, uint64_t Offset) { +#ifndef NDEBUG + uint64_t Pos = tell(); + // /dev/null always reports a pos of 0, so we cannot perform this check + // in that case. + if (Pos) + assert(Size + Offset <= Pos && "We don't support extending the stream"); +#endif + pwrite_impl(Ptr, Size, Offset); + } +}; + +//===----------------------------------------------------------------------===// +// File Output Streams +//===----------------------------------------------------------------------===// + +/// A raw_ostream that writes to a file descriptor. +/// +class raw_fd_ostream : public raw_pwrite_stream { + int FD; + bool ShouldClose; + bool SupportsSeeking = false; + bool IsRegularFile = false; + mutable std::optional HasColors; + +#ifdef _WIN32 + /// True if this fd refers to a Windows console device. Mintty and other + /// terminal emulators are TTYs, but they are not consoles. + bool IsWindowsConsole = false; +#endif + + std::error_code EC; + + uint64_t pos = 0; + + /// See raw_ostream::write_impl. + void write_impl(const char *Ptr, size_t Size) override; + + void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override; + + /// Return the current position within the stream, not counting the bytes + /// currently in the buffer. + uint64_t current_pos() const override { return pos; } + + /// Determine an efficient buffer size. + size_t preferred_buffer_size() const override; + + void anchor() override; + +protected: + /// Set the flag indicating that an output error has been encountered. + void error_detected(std::error_code EC) { this->EC = EC; } + + /// Return the file descriptor. + int get_fd() const { return FD; } + + // Update the file position by increasing \p Delta. + void inc_pos(uint64_t Delta) { pos += Delta; } + +public: + /// Open the specified file for writing. If an error occurs, information + /// about the error is put into EC, and the stream should be immediately + /// destroyed; + /// \p Flags allows optional flags to control how the file will be opened. + /// + /// As a special case, if Filename is "-", then the stream will use + /// STDOUT_FILENO instead of opening a file. This will not close the stdout + /// descriptor. + raw_fd_ostream(StringRef Filename, std::error_code &EC); + raw_fd_ostream(StringRef Filename, std::error_code &EC, + sys::fs::CreationDisposition Disp); + raw_fd_ostream(StringRef Filename, std::error_code &EC, + sys::fs::FileAccess Access); + raw_fd_ostream(StringRef Filename, std::error_code &EC, + sys::fs::OpenFlags Flags); + raw_fd_ostream(StringRef Filename, std::error_code &EC, + sys::fs::CreationDisposition Disp, sys::fs::FileAccess Access, + sys::fs::OpenFlags Flags); + + /// FD is the file descriptor that this writes to. If ShouldClose is true, + /// this closes the file when the stream is destroyed. If FD is for stdout or + /// stderr, it will not be closed. + raw_fd_ostream(int fd, bool shouldClose, bool unbuffered = false, + OStreamKind K = OStreamKind::OK_OStream); + + ~raw_fd_ostream() override; + + /// Manually flush the stream and close the file. Note that this does not call + /// fsync. + void close(); + + bool supportsSeeking() const { return SupportsSeeking; } + + bool isRegularFile() const { return IsRegularFile; } + + /// Flushes the stream and repositions the underlying file descriptor position + /// to the offset specified from the beginning of the file. + uint64_t seek(uint64_t off); + + bool is_displayed() const override; + + bool has_colors() const override; + + std::error_code error() const { return EC; } + + /// Return the value of the flag in this raw_fd_ostream indicating whether an + /// output error has been encountered. + /// This doesn't implicitly flush any pending output. Also, it doesn't + /// guarantee to detect all errors unless the stream has been closed. + bool has_error() const { return bool(EC); } + + /// Set the flag read by has_error() to false. If the error flag is set at the + /// time when this raw_ostream's destructor is called, report_fatal_error is + /// called to report the error. Use clear_error() after handling the error to + /// avoid this behavior. + /// + /// "Errors should never pass silently. + /// Unless explicitly silenced." + /// - from The Zen of Python, by Tim Peters + /// + void clear_error() { EC = std::error_code(); } + + /// Locks the underlying file. + /// + /// @returns RAII object that releases the lock upon leaving the scope, if the + /// locking was successful. Otherwise returns corresponding + /// error code. + /// + /// The function blocks the current thread until the lock become available or + /// error occurs. + /// + /// Possible use of this function may be as follows: + /// + /// @code{.cpp} + /// if (auto L = stream.lock()) { + /// // ... do action that require file to be locked. + /// } else { + /// handleAllErrors(std::move(L.takeError()), [&](ErrorInfoBase &EIB) { + /// // ... handle lock error. + /// }); + /// } + /// @endcode + [[nodiscard]] Expected lock(); + + /// Tries to lock the underlying file within the specified period. + /// + /// @returns RAII object that releases the lock upon leaving the scope, if the + /// locking was successful. Otherwise returns corresponding + /// error code. + /// + /// It is used as @ref lock. + [[nodiscard]] Expected + tryLockFor(Duration const &Timeout); +}; + +/// This returns a reference to a raw_fd_ostream for standard output. Use it +/// like: outs() << "foo" << "bar"; +raw_fd_ostream &outs(); + +/// This returns a reference to a raw_ostream for standard error. +/// Use it like: errs() << "foo" << "bar"; +/// By default, the stream is tied to stdout to ensure stdout is flushed before +/// stderr is written, to ensure the error messages are written in their +/// expected place. +raw_fd_ostream &errs(); + +/// This returns a reference to a raw_ostream which simply discards output. +raw_ostream &nulls(); + +//===----------------------------------------------------------------------===// +// File Streams +//===----------------------------------------------------------------------===// + +/// A raw_ostream of a file for reading/writing/seeking. +/// +class raw_fd_stream : public raw_fd_ostream { +public: + /// Open the specified file for reading/writing/seeking. If an error occurs, + /// information about the error is put into EC, and the stream should be + /// immediately destroyed. + raw_fd_stream(StringRef Filename, std::error_code &EC); + + /// This reads the \p Size bytes into a buffer pointed by \p Ptr. + /// + /// \param Ptr The start of the buffer to hold data to be read. + /// + /// \param Size The number of bytes to be read. + /// + /// On success, the number of bytes read is returned, and the file position is + /// advanced by this number. On error, -1 is returned, use error() to get the + /// error code. + ssize_t read(char *Ptr, size_t Size); + + /// Check if \p OS is a pointer of type raw_fd_stream*. + static bool classof(const raw_ostream *OS); +}; + +//===----------------------------------------------------------------------===// +// Output Stream Adaptors +//===----------------------------------------------------------------------===// + +/// A raw_ostream that writes to an std::string. This is a simple adaptor +/// class. This class does not encounter output errors. +/// raw_string_ostream operates without a buffer, delegating all memory +/// management to the std::string. Thus the std::string is always up-to-date, +/// may be used directly and there is no need to call flush(). +class raw_string_ostream : public raw_ostream { + std::string &OS; + + /// See raw_ostream::write_impl. + void write_impl(const char *Ptr, size_t Size) override; + + /// Return the current position within the stream, not counting the bytes + /// currently in the buffer. + uint64_t current_pos() const override { return OS.size(); } + +public: + explicit raw_string_ostream(std::string &O) : OS(O) { + SetUnbuffered(); + } + + /// Returns the string's reference. In most cases it is better to simply use + /// the underlying std::string directly. + /// TODO: Consider removing this API. + std::string &str() { return OS; } + + void reserveExtraSpace(uint64_t ExtraSize) override { + OS.reserve(tell() + ExtraSize); + } +}; + +/// A raw_ostream that writes to an SmallVector or SmallString. This is a +/// simple adaptor class. This class does not encounter output errors. +/// raw_svector_ostream operates without a buffer, delegating all memory +/// management to the SmallString. Thus the SmallString is always up-to-date, +/// may be used directly and there is no need to call flush(). +class raw_svector_ostream : public raw_pwrite_stream { + SmallVectorImpl &OS; + + /// See raw_ostream::write_impl. + void write_impl(const char *Ptr, size_t Size) override; + + void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override; + + /// Return the current position within the stream. + uint64_t current_pos() const override; + +public: + /// Construct a new raw_svector_ostream. + /// + /// \param O The vector to write to; this should generally have at least 128 + /// bytes free to avoid any extraneous memory overhead. + explicit raw_svector_ostream(SmallVectorImpl &O) : OS(O) { + SetUnbuffered(); + } + + ~raw_svector_ostream() override = default; + + void flush() = delete; + + /// Return a StringRef for the vector contents. + StringRef str() const { return StringRef(OS.data(), OS.size()); } + + void reserveExtraSpace(uint64_t ExtraSize) override { + OS.reserve(tell() + ExtraSize); + } +}; + +/// A raw_ostream that discards all output. +class raw_null_ostream : public raw_pwrite_stream { + /// See raw_ostream::write_impl. + void write_impl(const char *Ptr, size_t size) override; + void pwrite_impl(const char *Ptr, size_t Size, uint64_t Offset) override; + + /// Return the current position within the stream, not counting the bytes + /// currently in the buffer. + uint64_t current_pos() const override; + +public: + explicit raw_null_ostream() = default; + ~raw_null_ostream() override; +}; + +class buffer_ostream : public raw_svector_ostream { + raw_ostream &OS; + SmallVector Buffer; + + void anchor() override; + +public: + buffer_ostream(raw_ostream &OS) : raw_svector_ostream(Buffer), OS(OS) {} + ~buffer_ostream() override { OS << str(); } +}; + +class buffer_unique_ostream : public raw_svector_ostream { + std::unique_ptr OS; + SmallVector Buffer; + + void anchor() override; + +public: + buffer_unique_ostream(std::unique_ptr OS) + : raw_svector_ostream(Buffer), OS(std::move(OS)) { + // Turn off buffering on OS, which we now own, to avoid allocating a buffer + // when the destructor writes only to be immediately flushed again. + this->OS->SetUnbuffered(); + } + ~buffer_unique_ostream() override { *OS << str(); } +}; + +class Error; + +/// This helper creates an output stream and then passes it to \p Write. +/// The stream created is based on the specified \p OutputFileName: +/// llvm::outs for "-", raw_null_ostream for "/dev/null", and raw_fd_ostream +/// for other names. For raw_fd_ostream instances, the stream writes to +/// a temporary file. The final output file is atomically replaced with the +/// temporary file after the \p Write function is finished. +Error writeToOutput(StringRef OutputFileName, + std::function Write); + +raw_ostream &operator<<(raw_ostream &OS, std::nullopt_t); + +template () + << std::declval())> +raw_ostream &operator<<(raw_ostream &OS, const std::optional &O) { + if (O) + OS << *O; + else + OS << std::nullopt; + return OS; +} + +} // end namespace llvm + +#endif // LLVM_SUPPORT_RAW_OSTREAM_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/TargetParser/SubtargetFeature.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/TargetParser/SubtargetFeature.h new file mode 100644 index 00000000000..c6f463d84bb --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/TargetParser/SubtargetFeature.h @@ -0,0 +1,236 @@ +//=== llvm/TargetParser/SubtargetFeature.h - CPU characteristics-*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// +// +/// \file Defines and manages user or tool specified CPU characteristics. +/// The intent is to be able to package specific features that should or should +/// not be used on a specific target processor. A tool, such as llc, could, as +/// as example, gather chip info from the command line, a long with features +/// that should be used on that chip. +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_TARGETPARSER_SUBTARGETFEATURE_H +#define LLVM_TARGETPARSER_SUBTARGETFEATURE_H + +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/StringRef.h" +#include "llvm/Support/MathExtras.h" +#include +#include +#include +#include + +namespace llvm { + +class raw_ostream; +class Triple; + +const unsigned MAX_SUBTARGET_WORDS = 4; +const unsigned MAX_SUBTARGET_FEATURES = MAX_SUBTARGET_WORDS * 64; + +/// Container class for subtarget features. +/// This is a constexpr reimplementation of a subset of std::bitset. It would be +/// nice to use std::bitset directly, but it doesn't support constant +/// initialization. +class FeatureBitset { + static_assert((MAX_SUBTARGET_FEATURES % 64) == 0, + "Should be a multiple of 64!"); + std::array Bits{}; + +protected: + constexpr FeatureBitset(const std::array &B) + : Bits{B} {} + +public: + constexpr FeatureBitset() = default; + constexpr FeatureBitset(std::initializer_list Init) { + for (auto I : Init) + set(I); + } + + FeatureBitset &set() { + std::fill(std::begin(Bits), std::end(Bits), -1ULL); + return *this; + } + + constexpr FeatureBitset &set(unsigned I) { + // GCC <6.2 crashes if this is written in a single statement. + uint64_t NewBits = Bits[I / 64] | (uint64_t(1) << (I % 64)); + Bits[I / 64] = NewBits; + return *this; + } + + constexpr FeatureBitset &reset(unsigned I) { + // GCC <6.2 crashes if this is written in a single statement. + uint64_t NewBits = Bits[I / 64] & ~(uint64_t(1) << (I % 64)); + Bits[I / 64] = NewBits; + return *this; + } + + constexpr FeatureBitset &flip(unsigned I) { + // GCC <6.2 crashes if this is written in a single statement. + uint64_t NewBits = Bits[I / 64] ^ (uint64_t(1) << (I % 64)); + Bits[I / 64] = NewBits; + return *this; + } + + constexpr bool operator[](unsigned I) const { + uint64_t Mask = uint64_t(1) << (I % 64); + return (Bits[I / 64] & Mask) != 0; + } + + constexpr bool test(unsigned I) const { return (*this)[I]; } + + constexpr size_t size() const { return MAX_SUBTARGET_FEATURES; } + + bool any() const { + return llvm::any_of(Bits, [](uint64_t I) { return I != 0; }); + } + bool none() const { return !any(); } + size_t count() const { + size_t Count = 0; + for (auto B : Bits) + Count += llvm::countPopulation(B); + return Count; + } + + constexpr FeatureBitset &operator^=(const FeatureBitset &RHS) { + for (unsigned I = 0, E = Bits.size(); I != E; ++I) { + Bits[I] ^= RHS.Bits[I]; + } + return *this; + } + constexpr FeatureBitset operator^(const FeatureBitset &RHS) const { + FeatureBitset Result = *this; + Result ^= RHS; + return Result; + } + + constexpr FeatureBitset &operator&=(const FeatureBitset &RHS) { + for (unsigned I = 0, E = Bits.size(); I != E; ++I) { + Bits[I] &= RHS.Bits[I]; + } + return *this; + } + constexpr FeatureBitset operator&(const FeatureBitset &RHS) const { + FeatureBitset Result = *this; + Result &= RHS; + return Result; + } + + constexpr FeatureBitset &operator|=(const FeatureBitset &RHS) { + for (unsigned I = 0, E = Bits.size(); I != E; ++I) { + Bits[I] |= RHS.Bits[I]; + } + return *this; + } + constexpr FeatureBitset operator|(const FeatureBitset &RHS) const { + FeatureBitset Result = *this; + Result |= RHS; + return Result; + } + + constexpr FeatureBitset operator~() const { + FeatureBitset Result = *this; + for (auto &B : Result.Bits) + B = ~B; + return Result; + } + + bool operator==(const FeatureBitset &RHS) const { + return std::equal(std::begin(Bits), std::end(Bits), std::begin(RHS.Bits)); + } + + bool operator!=(const FeatureBitset &RHS) const { return !(*this == RHS); } + + bool operator < (const FeatureBitset &Other) const { + for (unsigned I = 0, E = size(); I != E; ++I) { + bool LHS = test(I), RHS = Other.test(I); + if (LHS != RHS) + return LHS < RHS; + } + return false; + } +}; + +/// Class used to store the subtarget bits in the tables created by tablegen. +class FeatureBitArray : public FeatureBitset { +public: + constexpr FeatureBitArray(const std::array &B) + : FeatureBitset(B) {} + + const FeatureBitset &getAsBitset() const { return *this; } +}; + +//===----------------------------------------------------------------------===// + +/// Manages the enabling and disabling of subtarget specific features. +/// +/// Features are encoded as a string of the form +/// "+attr1,+attr2,-attr3,...,+attrN" +/// A comma separates each feature from the next (all lowercase.) +/// Each of the remaining features is prefixed with + or - indicating whether +/// that feature should be enabled or disabled contrary to the cpu +/// specification. +class SubtargetFeatures { + std::vector Features; ///< Subtarget features as a vector + +public: + explicit SubtargetFeatures(StringRef Initial = ""); + + /// Returns features as a string. + std::string getString() const; + + /// Adds Features. + void AddFeature(StringRef String, bool Enable = true); + + void addFeaturesVector(const ArrayRef OtherFeatures); + + /// Returns the vector of individual subtarget features. + const std::vector &getFeatures() const { return Features; } + + /// Prints feature string. + void print(raw_ostream &OS) const; + + // Dumps feature info. + void dump() const; + + /// Adds the default features for the specified target triple. + void getDefaultSubtargetFeatures(const Triple& Triple); + + /// Determine if a feature has a flag; '+' or '-' + static bool hasFlag(StringRef Feature) { + assert(!Feature.empty() && "Empty string"); + // Get first character + char Ch = Feature[0]; + // Check if first character is '+' or '-' flag + return Ch == '+' || Ch =='-'; + } + + /// Return string stripped of flag. + static StringRef StripFlag(StringRef Feature) { + return hasFlag(Feature) ? Feature.substr(1) : Feature; + } + + /// Return true if enable flag; '+'. + static inline bool isEnabled(StringRef Feature) { + assert(!Feature.empty() && "Empty string"); + // Get first character + char Ch = Feature[0]; + // Check if first character is '+' for enabled + return Ch == '+'; + } + + /// Splits a string of comma separated items in to a vector of strings. + static void Split(std::vector &V, StringRef S); +}; + +} // end namespace llvm + +#endif // LLVM_TARGETPARSER_SUBTARGETFEATURE_H diff --git a/include/swift/RemoteInspection/RuntimeHeaders/llvm/TargetParser/Triple.h b/include/swift/RemoteInspection/RuntimeHeaders/llvm/TargetParser/Triple.h new file mode 100644 index 00000000000..79ccd644a50 --- /dev/null +++ b/include/swift/RemoteInspection/RuntimeHeaders/llvm/TargetParser/Triple.h @@ -0,0 +1,1141 @@ +//===-- llvm/TargetParser/Triple.h - Target triple helper class--*- C++ -*-===// +// +// 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 +// +//===----------------------------------------------------------------------===// + +#ifndef LLVM_TARGETPARSER_TRIPLE_H +#define LLVM_TARGETPARSER_TRIPLE_H + +#include "llvm/ADT/Twine.h" +#include "llvm/Support/VersionTuple.h" + +// Some system headers or GCC predefined macros conflict with identifiers in +// this file. Undefine them here. +#undef NetBSD +#undef mips +#undef sparc + +namespace llvm { + +/// Triple - Helper class for working with autoconf configuration names. For +/// historical reasons, we also call these 'triples' (they used to contain +/// exactly three fields). +/// +/// Configuration names are strings in the canonical form: +/// ARCHITECTURE-VENDOR-OPERATING_SYSTEM +/// or +/// ARCHITECTURE-VENDOR-OPERATING_SYSTEM-ENVIRONMENT +/// +/// This class is used for clients which want to support arbitrary +/// configuration names, but also want to implement certain special +/// behavior for particular configurations. This class isolates the mapping +/// from the components of the configuration name to well known IDs. +/// +/// At its core the Triple class is designed to be a wrapper for a triple +/// string; the constructor does not change or normalize the triple string. +/// Clients that need to handle the non-canonical triples that users often +/// specify should use the normalize method. +/// +/// See autoconf/config.guess for a glimpse into what configuration names +/// look like in practice. +class Triple { +public: + enum ArchType { + UnknownArch, + + arm, // ARM (little endian): arm, armv.*, xscale + armeb, // ARM (big endian): armeb + aarch64, // AArch64 (little endian): aarch64 + aarch64_be, // AArch64 (big endian): aarch64_be + aarch64_32, // AArch64 (little endian) ILP32: aarch64_32 + arc, // ARC: Synopsys ARC + avr, // AVR: Atmel AVR microcontroller + bpfel, // eBPF or extended BPF or 64-bit BPF (little endian) + bpfeb, // eBPF or extended BPF or 64-bit BPF (big endian) + csky, // CSKY: csky + dxil, // DXIL 32-bit DirectX bytecode + hexagon, // Hexagon: hexagon + loongarch32, // LoongArch (32-bit): loongarch32 + loongarch64, // LoongArch (64-bit): loongarch64 + m68k, // M68k: Motorola 680x0 family + mips, // MIPS: mips, mipsallegrex, mipsr6 + mipsel, // MIPSEL: mipsel, mipsallegrexe, mipsr6el + mips64, // MIPS64: mips64, mips64r6, mipsn32, mipsn32r6 + mips64el, // MIPS64EL: mips64el, mips64r6el, mipsn32el, mipsn32r6el + msp430, // MSP430: msp430 + ppc, // PPC: powerpc + ppcle, // PPCLE: powerpc (little endian) + ppc64, // PPC64: powerpc64, ppu + ppc64le, // PPC64LE: powerpc64le + r600, // R600: AMD GPUs HD2XXX - HD6XXX + amdgcn, // AMDGCN: AMD GCN GPUs + riscv32, // RISC-V (32-bit): riscv32 + riscv64, // RISC-V (64-bit): riscv64 + sparc, // Sparc: sparc + sparcv9, // Sparcv9: Sparcv9 + sparcel, // Sparc: (endianness = little). NB: 'Sparcle' is a CPU variant + systemz, // SystemZ: s390x + tce, // TCE (http://tce.cs.tut.fi/): tce + tcele, // TCE little endian (http://tce.cs.tut.fi/): tcele + thumb, // Thumb (little endian): thumb, thumbv.* + thumbeb, // Thumb (big endian): thumbeb + x86, // X86: i[3-9]86 + x86_64, // X86-64: amd64, x86_64 + xcore, // XCore: xcore + xtensa, // Tensilica: Xtensa + nvptx, // NVPTX: 32-bit + nvptx64, // NVPTX: 64-bit + le32, // le32: generic little-endian 32-bit CPU (PNaCl) + le64, // le64: generic little-endian 64-bit CPU (PNaCl) + amdil, // AMDIL + amdil64, // AMDIL with 64-bit pointers + hsail, // AMD HSAIL + hsail64, // AMD HSAIL with 64-bit pointers + spir, // SPIR: standard portable IR for OpenCL 32-bit version + spir64, // SPIR: standard portable IR for OpenCL 64-bit version + spirv32, // SPIR-V with 32-bit pointers + spirv64, // SPIR-V with 64-bit pointers + kalimba, // Kalimba: generic kalimba + shave, // SHAVE: Movidius vector VLIW processors + lanai, // Lanai: Lanai 32-bit + wasm32, // WebAssembly with 32-bit pointers + wasm64, // WebAssembly with 64-bit pointers + renderscript32, // 32-bit RenderScript + renderscript64, // 64-bit RenderScript + ve, // NEC SX-Aurora Vector Engine + LastArchType = ve + }; + enum SubArchType { + NoSubArch, + + ARMSubArch_v9_4a, + ARMSubArch_v9_3a, + ARMSubArch_v9_2a, + ARMSubArch_v9_1a, + ARMSubArch_v9, + ARMSubArch_v8_9a, + ARMSubArch_v8_8a, + ARMSubArch_v8_7a, + ARMSubArch_v8_6a, + ARMSubArch_v8_5a, + ARMSubArch_v8_4a, + ARMSubArch_v8_3a, + ARMSubArch_v8_2a, + ARMSubArch_v8_1a, + ARMSubArch_v8, + ARMSubArch_v8r, + ARMSubArch_v8m_baseline, + ARMSubArch_v8m_mainline, + ARMSubArch_v8_1m_mainline, + ARMSubArch_v7, + ARMSubArch_v7em, + ARMSubArch_v7m, + ARMSubArch_v7s, + ARMSubArch_v7k, + ARMSubArch_v7ve, + ARMSubArch_v6, + ARMSubArch_v6m, + ARMSubArch_v6k, + ARMSubArch_v6t2, + ARMSubArch_v5, + ARMSubArch_v5te, + ARMSubArch_v4t, + + AArch64SubArch_arm64e, + AArch64SubArch_arm64ec, + + KalimbaSubArch_v3, + KalimbaSubArch_v4, + KalimbaSubArch_v5, + + MipsSubArch_r6, + + PPCSubArch_spe, + + // SPIR-V sub-arch corresponds to its version. + SPIRVSubArch_v10, + SPIRVSubArch_v11, + SPIRVSubArch_v12, + SPIRVSubArch_v13, + SPIRVSubArch_v14, + SPIRVSubArch_v15, + }; + enum VendorType { + UnknownVendor, + + Apple, + PC, + SCEI, + Freescale, + IBM, + ImaginationTechnologies, + MipsTechnologies, + NVIDIA, + CSR, + Myriad, + AMD, + Mesa, + SUSE, + OpenEmbedded, + LastVendorType = OpenEmbedded + }; + enum OSType { + UnknownOS, + + Ananas, + CloudABI, + Darwin, + DragonFly, + FreeBSD, + Fuchsia, + IOS, + KFreeBSD, + Linux, + Lv2, // PS3 + MacOSX, + NetBSD, + OpenBSD, + Solaris, + UEFI, + Win32, + ZOS, + Haiku, + Minix, + RTEMS, + NaCl, // Native Client + AIX, + CUDA, // NVIDIA CUDA + NVCL, // NVIDIA OpenCL + AMDHSA, // AMD HSA Runtime + PS4, + PS5, + ELFIAMCU, + TvOS, // Apple tvOS + WatchOS, // Apple watchOS + DriverKit, // Apple DriverKit + Mesa3D, + Contiki, + AMDPAL, // AMD PAL Runtime + HermitCore, // HermitCore Unikernel/Multikernel + Hurd, // GNU/Hurd + WASI, // Experimental WebAssembly OS + Emscripten, + ShaderModel, // DirectX ShaderModel + LiteOS, + LastOSType = LiteOS + }; + enum EnvironmentType { + UnknownEnvironment, + + GNU, + GNUABIN32, + GNUABI64, + GNUEABI, + GNUEABIHF, + GNUF32, + GNUF64, + GNUSF, + GNUX32, + GNUILP32, + CODE16, + EABI, + EABIHF, + Android, + Musl, + MuslEABI, + MuslEABIHF, + MuslX32, + + MSVC, + Itanium, + Cygnus, + CoreCLR, + Simulator, // Simulator variants of other systems, e.g., Apple's iOS + MacABI, // Mac Catalyst variant of Apple's iOS deployment target. + + // Shader Stages + // The order of these values matters, and must be kept in sync with the + // language options enum in Clang. The ordering is enforced in + // static_asserts in Triple.cpp and in Clang. + Pixel, + Vertex, + Geometry, + Hull, + Domain, + Compute, + Library, + RayGeneration, + Intersection, + AnyHit, + ClosestHit, + Miss, + Callable, + Mesh, + Amplification, + OpenHOS, + LastEnvironmentType = OpenHOS + }; + enum ObjectFormatType { + UnknownObjectFormat, + + COFF, + DXContainer, + ELF, + GOFF, + MachO, + SPIRV, + Wasm, + XCOFF, + }; + +private: + std::string Data; + + /// The parsed arch type. + ArchType Arch{}; + + /// The parsed subarchitecture type. + SubArchType SubArch{}; + + /// The parsed vendor type. + VendorType Vendor{}; + + /// The parsed OS type. + OSType OS{}; + + /// The parsed Environment type. + EnvironmentType Environment{}; + + /// The object format type. + ObjectFormatType ObjectFormat{}; + +public: + /// @name Constructors + /// @{ + + /// Default constructor is the same as an empty string and leaves all + /// triple fields unknown. + Triple() = default; + + explicit Triple(const Twine &Str); + Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr); + Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr, + const Twine &EnvironmentStr); + + bool operator==(const Triple &Other) const { + return Arch == Other.Arch && SubArch == Other.SubArch && + Vendor == Other.Vendor && OS == Other.OS && + Environment == Other.Environment && + ObjectFormat == Other.ObjectFormat; + } + + bool operator!=(const Triple &Other) const { + return !(*this == Other); + } + + /// @} + /// @name Normalization + /// @{ + + /// Turn an arbitrary machine specification into the canonical triple form (or + /// something sensible that the Triple class understands if nothing better can + /// reasonably be done). In particular, it handles the common case in which + /// otherwise valid components are in the wrong order. + static std::string normalize(StringRef Str); + + /// Return the normalized form of this triple's string. + std::string normalize() const { return normalize(Data); } + + /// @} + /// @name Typed Component Access + /// @{ + + /// Get the parsed architecture type of this triple. + ArchType getArch() const { return Arch; } + + /// get the parsed subarchitecture type for this triple. + SubArchType getSubArch() const { return SubArch; } + + /// Get the parsed vendor type of this triple. + VendorType getVendor() const { return Vendor; } + + /// Get the parsed operating system type of this triple. + OSType getOS() const { return OS; } + + /// Does this triple have the optional environment (fourth) component? + bool hasEnvironment() const { + return getEnvironmentName() != ""; + } + + /// Get the parsed environment type of this triple. + EnvironmentType getEnvironment() const { return Environment; } + + /// Parse the version number from the OS name component of the + /// triple, if present. + /// + /// For example, "fooos1.2.3" would return (1, 2, 3). + VersionTuple getEnvironmentVersion() const; + + /// Get the object format for this triple. + ObjectFormatType getObjectFormat() const { return ObjectFormat; } + + /// Parse the version number from the OS name component of the triple, if + /// present. + /// + /// For example, "fooos1.2.3" would return (1, 2, 3). + VersionTuple getOSVersion() const; + + /// Return just the major version number, this is specialized because it is a + /// common query. + unsigned getOSMajorVersion() const { return getOSVersion().getMajor(); } + + /// Parse the version number as with getOSVersion and then translate generic + /// "darwin" versions to the corresponding OS X versions. This may also be + /// called with IOS triples but the OS X version number is just set to a + /// constant 10.4.0 in that case. Returns true if successful. + bool getMacOSXVersion(VersionTuple &Version) const; + + /// Parse the version number as with getOSVersion. This should only be called + /// with IOS or generic triples. + VersionTuple getiOSVersion() const; + + /// Parse the version number as with getOSVersion. This should only be called + /// with WatchOS or generic triples. + VersionTuple getWatchOSVersion() const; + + /// Parse the version number as with getOSVersion. + VersionTuple getDriverKitVersion() const; + + /// @} + /// @name Direct Component Access + /// @{ + + const std::string &str() const { return Data; } + + const std::string &getTriple() const { return Data; } + + /// Get the architecture (first) component of the triple. + StringRef getArchName() const; + + /// Get the architecture name based on Kind and SubArch. + StringRef getArchName(ArchType Kind, SubArchType SubArch = NoSubArch) const; + + /// Get the vendor (second) component of the triple. + StringRef getVendorName() const; + + /// Get the operating system (third) component of the triple. + StringRef getOSName() const; + + /// Get the optional environment (fourth) component of the triple, or "" if + /// empty. + StringRef getEnvironmentName() const; + + /// Get the operating system and optional environment components as a single + /// string (separated by a '-' if the environment component is present). + StringRef getOSAndEnvironmentName() const; + + /// @} + /// @name Convenience Predicates + /// @{ + + /// Test whether the architecture is 64-bit + /// + /// Note that this tests for 64-bit pointer width, and nothing else. Note + /// that we intentionally expose only three predicates, 64-bit, 32-bit, and + /// 16-bit. The inner details of pointer width for particular architectures + /// is not summed up in the triple, and so only a coarse grained predicate + /// system is provided. + bool isArch64Bit() const; + + /// Test whether the architecture is 32-bit + /// + /// Note that this tests for 32-bit pointer width, and nothing else. + bool isArch32Bit() const; + + /// Test whether the architecture is 16-bit + /// + /// Note that this tests for 16-bit pointer width, and nothing else. + bool isArch16Bit() const; + + /// Helper function for doing comparisons against version numbers included in + /// the target triple. + bool isOSVersionLT(unsigned Major, unsigned Minor = 0, + unsigned Micro = 0) const { + if (Minor == 0) { + return getOSVersion() < VersionTuple(Major); + } + if (Micro == 0) { + return getOSVersion() < VersionTuple(Major, Minor); + } + return getOSVersion() < VersionTuple(Major, Minor, Micro); + } + + bool isOSVersionLT(const Triple &Other) const { + return getOSVersion() < Other.getOSVersion(); + } + + /// Comparison function for checking OS X version compatibility, which handles + /// supporting skewed version numbering schemes used by the "darwin" triples. + bool isMacOSXVersionLT(unsigned Major, unsigned Minor = 0, + unsigned Micro = 0) const; + + /// Is this a Mac OS X triple. For legacy reasons, we support both "darwin" + /// and "osx" as OS X triples. + bool isMacOSX() const { + return getOS() == Triple::Darwin || getOS() == Triple::MacOSX; + } + + /// Is this an iOS triple. + /// Note: This identifies tvOS as a variant of iOS. If that ever + /// changes, i.e., if the two operating systems diverge or their version + /// numbers get out of sync, that will need to be changed. + /// watchOS has completely different version numbers so it is not included. + bool isiOS() const { + return getOS() == Triple::IOS || isTvOS(); + } + + /// Is this an Apple tvOS triple. + bool isTvOS() const { + return getOS() == Triple::TvOS; + } + + /// Is this an Apple watchOS triple. + bool isWatchOS() const { + return getOS() == Triple::WatchOS; + } + + bool isWatchABI() const { + return getSubArch() == Triple::ARMSubArch_v7k; + } + + /// Is this an Apple DriverKit triple. + bool isDriverKit() const { return getOS() == Triple::DriverKit; } + + bool isOSzOS() const { return getOS() == Triple::ZOS; } + + /// Is this a "Darwin" OS (macOS, iOS, tvOS, watchOS, or DriverKit). + bool isOSDarwin() const { + return isMacOSX() || isiOS() || isWatchOS() || isDriverKit(); + } + + bool isSimulatorEnvironment() const { + return getEnvironment() == Triple::Simulator; + } + + bool isMacCatalystEnvironment() const { + return getEnvironment() == Triple::MacABI; + } + + /// Returns true for targets that run on a macOS machine. + bool isTargetMachineMac() const { + return isMacOSX() || (isOSDarwin() && (isSimulatorEnvironment() || + isMacCatalystEnvironment())); + } + + bool isOSNetBSD() const { + return getOS() == Triple::NetBSD; + } + + bool isOSOpenBSD() const { + return getOS() == Triple::OpenBSD; + } + + bool isOSFreeBSD() const { + return getOS() == Triple::FreeBSD; + } + + bool isOSFuchsia() const { + return getOS() == Triple::Fuchsia; + } + + bool isOSDragonFly() const { return getOS() == Triple::DragonFly; } + + bool isOSSolaris() const { + return getOS() == Triple::Solaris; + } + + bool isOSIAMCU() const { + return getOS() == Triple::ELFIAMCU; + } + + bool isOSUnknown() const { return getOS() == Triple::UnknownOS; } + + bool isGNUEnvironment() const { + EnvironmentType Env = getEnvironment(); + return Env == Triple::GNU || Env == Triple::GNUABIN32 || + Env == Triple::GNUABI64 || Env == Triple::GNUEABI || + Env == Triple::GNUEABIHF || Env == Triple::GNUF32 || + Env == Triple::GNUF64 || Env == Triple::GNUSF || + Env == Triple::GNUX32; + } + + bool isOSContiki() const { + return getOS() == Triple::Contiki; + } + + /// Tests whether the OS is Haiku. + bool isOSHaiku() const { + return getOS() == Triple::Haiku; + } + + /// Tests whether the OS is UEFI. + bool isUEFI() const { + return getOS() == Triple::UEFI; + } + + /// Tests whether the OS is Windows. + bool isOSWindows() const { + return getOS() == Triple::Win32; + } + + /// Checks if the environment is MSVC. + bool isKnownWindowsMSVCEnvironment() const { + return isOSWindows() && getEnvironment() == Triple::MSVC; + } + + /// Checks if the environment could be MSVC. + bool isWindowsMSVCEnvironment() const { + return isKnownWindowsMSVCEnvironment() || + (isOSWindows() && getEnvironment() == Triple::UnknownEnvironment); + } + + // Checks if we're using the Windows Arm64EC ABI. + bool isWindowsArm64EC() const { + return getArch() == Triple::aarch64 && + getSubArch() == Triple::AArch64SubArch_arm64ec; + } + + bool isWindowsCoreCLREnvironment() const { + return isOSWindows() && getEnvironment() == Triple::CoreCLR; + } + + bool isWindowsItaniumEnvironment() const { + return isOSWindows() && getEnvironment() == Triple::Itanium; + } + + bool isWindowsCygwinEnvironment() const { + return isOSWindows() && getEnvironment() == Triple::Cygnus; + } + + bool isWindowsGNUEnvironment() const { + return isOSWindows() && getEnvironment() == Triple::GNU; + } + + /// Tests for either Cygwin or MinGW OS + bool isOSCygMing() const { + return isWindowsCygwinEnvironment() || isWindowsGNUEnvironment(); + } + + /// Is this a "Windows" OS targeting a "MSVCRT.dll" environment. + bool isOSMSVCRT() const { + return isWindowsMSVCEnvironment() || isWindowsGNUEnvironment() || + isWindowsItaniumEnvironment(); + } + + /// Tests whether the OS is NaCl (Native Client) + bool isOSNaCl() const { + return getOS() == Triple::NaCl; + } + + /// Tests whether the OS is Linux. + bool isOSLinux() const { + return getOS() == Triple::Linux; + } + + /// Tests whether the OS is kFreeBSD. + bool isOSKFreeBSD() const { + return getOS() == Triple::KFreeBSD; + } + + /// Tests whether the OS is Hurd. + bool isOSHurd() const { + return getOS() == Triple::Hurd; + } + + /// Tests whether the OS is WASI. + bool isOSWASI() const { + return getOS() == Triple::WASI; + } + + /// Tests whether the OS is Emscripten. + bool isOSEmscripten() const { + return getOS() == Triple::Emscripten; + } + + /// Tests whether the OS uses glibc. + bool isOSGlibc() const { + return (getOS() == Triple::Linux || getOS() == Triple::KFreeBSD || + getOS() == Triple::Hurd) && + !isAndroid(); + } + + /// Tests whether the OS is AIX. + bool isOSAIX() const { + return getOS() == Triple::AIX; + } + + /// Tests whether the OS uses the ELF binary format. + bool isOSBinFormatELF() const { + return getObjectFormat() == Triple::ELF; + } + + /// Tests whether the OS uses the COFF binary format. + bool isOSBinFormatCOFF() const { + return getObjectFormat() == Triple::COFF; + } + + /// Tests whether the OS uses the GOFF binary format. + bool isOSBinFormatGOFF() const { return getObjectFormat() == Triple::GOFF; } + + /// Tests whether the environment is MachO. + bool isOSBinFormatMachO() const { + return getObjectFormat() == Triple::MachO; + } + + /// Tests whether the OS uses the Wasm binary format. + bool isOSBinFormatWasm() const { + return getObjectFormat() == Triple::Wasm; + } + + /// Tests whether the OS uses the XCOFF binary format. + bool isOSBinFormatXCOFF() const { + return getObjectFormat() == Triple::XCOFF; + } + + /// Tests whether the OS uses the DXContainer binary format. + bool isOSBinFormatDXContainer() const { + return getObjectFormat() == Triple::DXContainer; + } + + /// Tests whether the target is the PS4 platform. + bool isPS4() const { + return getArch() == Triple::x86_64 && + getVendor() == Triple::SCEI && + getOS() == Triple::PS4; + } + + /// Tests whether the target is the PS5 platform. + bool isPS5() const { + return getArch() == Triple::x86_64 && + getVendor() == Triple::SCEI && + getOS() == Triple::PS5; + } + + /// Tests whether the target is the PS4 or PS5 platform. + bool isPS() const { return isPS4() || isPS5(); } + + /// Tests whether the target is Android + bool isAndroid() const { return getEnvironment() == Triple::Android; } + + bool isAndroidVersionLT(unsigned Major) const { + assert(isAndroid() && "Not an Android triple!"); + + VersionTuple Version = getEnvironmentVersion(); + + // 64-bit targets did not exist before API level 21 (Lollipop). + if (isArch64Bit() && Version.getMajor() < 21) + return VersionTuple(21) < VersionTuple(Major); + + return Version < VersionTuple(Major); + } + + /// Tests whether the environment is musl-libc + bool isMusl() const { + return getEnvironment() == Triple::Musl || + getEnvironment() == Triple::MuslEABI || + getEnvironment() == Triple::MuslEABIHF || + getEnvironment() == Triple::MuslX32 || + getEnvironment() == Triple::OpenHOS || isOSLiteOS(); + } + + /// Tests whether the target is OHOS + /// LiteOS default enviroment is also OHOS, but omited on triple. + bool isOHOSFamily() const { return isOpenHOS() || isOSLiteOS(); } + + bool isOpenHOS() const { return getEnvironment() == Triple::OpenHOS; } + + bool isOSLiteOS() const { return getOS() == Triple::LiteOS; } + + /// Tests whether the target is DXIL. + bool isDXIL() const { + return getArch() == Triple::dxil; + } + + /// Tests whether the target is SPIR (32- or 64-bit). + bool isSPIR() const { + return getArch() == Triple::spir || getArch() == Triple::spir64; + } + + /// Tests whether the target is SPIR-V (32/64-bit). + bool isSPIRV() const { + return getArch() == Triple::spirv32 || getArch() == Triple::spirv64; + } + + /// Tests whether the target is NVPTX (32- or 64-bit). + bool isNVPTX() const { + return getArch() == Triple::nvptx || getArch() == Triple::nvptx64; + } + + /// Tests whether the target is AMDGCN + bool isAMDGCN() const { return getArch() == Triple::amdgcn; } + + bool isAMDGPU() const { + return getArch() == Triple::r600 || getArch() == Triple::amdgcn; + } + + /// Tests whether the target is Thumb (little and big endian). + bool isThumb() const { + return getArch() == Triple::thumb || getArch() == Triple::thumbeb; + } + + /// Tests whether the target is ARM (little and big endian). + bool isARM() const { + return getArch() == Triple::arm || getArch() == Triple::armeb; + } + + /// Tests whether the target supports the EHABI exception + /// handling standard. + bool isTargetEHABICompatible() const { + return (isARM() || isThumb()) && + (getEnvironment() == Triple::EABI || + getEnvironment() == Triple::GNUEABI || + getEnvironment() == Triple::MuslEABI || + getEnvironment() == Triple::EABIHF || + getEnvironment() == Triple::GNUEABIHF || + getEnvironment() == Triple::OpenHOS || + getEnvironment() == Triple::MuslEABIHF || isAndroid()) && + isOSBinFormatELF(); + } + + /// Tests whether the target is T32. + bool isArmT32() const { + switch (getSubArch()) { + case Triple::ARMSubArch_v8m_baseline: + case Triple::ARMSubArch_v7s: + case Triple::ARMSubArch_v7k: + case Triple::ARMSubArch_v7ve: + case Triple::ARMSubArch_v6: + case Triple::ARMSubArch_v6m: + case Triple::ARMSubArch_v6k: + case Triple::ARMSubArch_v6t2: + case Triple::ARMSubArch_v5: + case Triple::ARMSubArch_v5te: + case Triple::ARMSubArch_v4t: + return false; + default: + return true; + } + } + + /// Tests whether the target is an M-class. + bool isArmMClass() const { + switch (getSubArch()) { + case Triple::ARMSubArch_v6m: + case Triple::ARMSubArch_v7m: + case Triple::ARMSubArch_v7em: + case Triple::ARMSubArch_v8m_mainline: + case Triple::ARMSubArch_v8m_baseline: + case Triple::ARMSubArch_v8_1m_mainline: + return true; + default: + return false; + } + } + + /// Tests whether the target is AArch64 (little and big endian). + bool isAArch64() const { + return getArch() == Triple::aarch64 || getArch() == Triple::aarch64_be || + getArch() == Triple::aarch64_32; + } + + /// Tests whether the target is AArch64 and pointers are the size specified by + /// \p PointerWidth. + bool isAArch64(int PointerWidth) const { + assert(PointerWidth == 64 || PointerWidth == 32); + if (!isAArch64()) + return false; + return getArch() == Triple::aarch64_32 || + getEnvironment() == Triple::GNUILP32 + ? PointerWidth == 32 + : PointerWidth == 64; + } + + /// Tests whether the target is 32-bit LoongArch. + bool isLoongArch32() const { return getArch() == Triple::loongarch32; } + + /// Tests whether the target is 64-bit LoongArch. + bool isLoongArch64() const { return getArch() == Triple::loongarch64; } + + /// Tests whether the target is LoongArch (32- and 64-bit). + bool isLoongArch() const { return isLoongArch32() || isLoongArch64(); } + + /// Tests whether the target is MIPS 32-bit (little and big endian). + bool isMIPS32() const { + return getArch() == Triple::mips || getArch() == Triple::mipsel; + } + + /// Tests whether the target is MIPS 64-bit (little and big endian). + bool isMIPS64() const { + return getArch() == Triple::mips64 || getArch() == Triple::mips64el; + } + + /// Tests whether the target is MIPS (little and big endian, 32- or 64-bit). + bool isMIPS() const { + return isMIPS32() || isMIPS64(); + } + + /// Tests whether the target is PowerPC (32- or 64-bit LE or BE). + bool isPPC() const { + return getArch() == Triple::ppc || getArch() == Triple::ppc64 || + getArch() == Triple::ppcle || getArch() == Triple::ppc64le; + } + + /// Tests whether the target is 32-bit PowerPC (little and big endian). + bool isPPC32() const { + return getArch() == Triple::ppc || getArch() == Triple::ppcle; + } + + /// Tests whether the target is 64-bit PowerPC (little and big endian). + bool isPPC64() const { + return getArch() == Triple::ppc64 || getArch() == Triple::ppc64le; + } + + /// Tests whether the target 64-bit PowerPC big endian ABI is ELFv2. + bool isPPC64ELFv2ABI() const { + return (getArch() == Triple::ppc64 && + ((getOS() == Triple::FreeBSD && + (getOSMajorVersion() >= 13 || getOSVersion().empty())) || + getOS() == Triple::OpenBSD || isMusl())); + } + + /// Tests whether the target 32-bit PowerPC uses Secure PLT. + bool isPPC32SecurePlt() const { + return ((getArch() == Triple::ppc || getArch() == Triple::ppcle) && + ((getOS() == Triple::FreeBSD && + (getOSMajorVersion() >= 13 || getOSVersion().empty())) || + getOS() == Triple::NetBSD || getOS() == Triple::OpenBSD || + isMusl())); + } + + /// Tests whether the target is 32-bit RISC-V. + bool isRISCV32() const { return getArch() == Triple::riscv32; } + + /// Tests whether the target is 64-bit RISC-V. + bool isRISCV64() const { return getArch() == Triple::riscv64; } + + /// Tests whether the target is RISC-V (32- and 64-bit). + bool isRISCV() const { return isRISCV32() || isRISCV64(); } + + /// Tests whether the target is 32-bit SPARC (little and big endian). + bool isSPARC32() const { + return getArch() == Triple::sparc || getArch() == Triple::sparcel; + } + + /// Tests whether the target is 64-bit SPARC (big endian). + bool isSPARC64() const { return getArch() == Triple::sparcv9; } + + /// Tests whether the target is SPARC. + bool isSPARC() const { return isSPARC32() || isSPARC64(); } + + /// Tests whether the target is SystemZ. + bool isSystemZ() const { + return getArch() == Triple::systemz; + } + + /// Tests whether the target is x86 (32- or 64-bit). + bool isX86() const { + return getArch() == Triple::x86 || getArch() == Triple::x86_64; + } + + /// Tests whether the target is VE + bool isVE() const { + return getArch() == Triple::ve; + } + + /// Tests whether the target is wasm (32- and 64-bit). + bool isWasm() const { + return getArch() == Triple::wasm32 || getArch() == Triple::wasm64; + } + + // Tests whether the target is CSKY + bool isCSKY() const { + return getArch() == Triple::csky; + } + + /// Tests whether the target is the Apple "arm64e" AArch64 subarch. + bool isArm64e() const { + return getArch() == Triple::aarch64 && + getSubArch() == Triple::AArch64SubArch_arm64e; + } + + /// Tests whether the target is X32. + bool isX32() const { + EnvironmentType Env = getEnvironment(); + return Env == Triple::GNUX32 || Env == Triple::MuslX32; + } + + /// Tests whether the target is eBPF. + bool isBPF() const { + return getArch() == Triple::bpfel || getArch() == Triple::bpfeb; + } + + /// Tests whether the target supports comdat + bool supportsCOMDAT() const { + return !(isOSBinFormatMachO() || isOSBinFormatXCOFF() || + isOSBinFormatDXContainer()); + } + + /// Tests whether the target uses emulated TLS as default. + /// + /// Note: Android API level 29 (10) introduced ELF TLS. + bool hasDefaultEmulatedTLS() const { + return (isAndroid() && isAndroidVersionLT(29)) || isOSOpenBSD() || + isWindowsCygwinEnvironment() || isOHOSFamily(); + } + + /// Tests whether the target uses -data-sections as default. + bool hasDefaultDataSections() const { + return isOSBinFormatXCOFF() || isWasm(); + } + + /// Tests if the environment supports dllimport/export annotations. + bool hasDLLImportExport() const { return isOSWindows() || isPS(); } + + /// @} + /// @name Mutators + /// @{ + + /// Set the architecture (first) component of the triple to a known type. + void setArch(ArchType Kind, SubArchType SubArch = NoSubArch); + + /// Set the vendor (second) component of the triple to a known type. + void setVendor(VendorType Kind); + + /// Set the operating system (third) component of the triple to a known type. + void setOS(OSType Kind); + + /// Set the environment (fourth) component of the triple to a known type. + void setEnvironment(EnvironmentType Kind); + + /// Set the object file format. + void setObjectFormat(ObjectFormatType Kind); + + /// Set all components to the new triple \p Str. + void setTriple(const Twine &Str); + + /// Set the architecture (first) component of the triple by name. + void setArchName(StringRef Str); + + /// Set the vendor (second) component of the triple by name. + void setVendorName(StringRef Str); + + /// Set the operating system (third) component of the triple by name. + void setOSName(StringRef Str); + + /// Set the optional environment (fourth) component of the triple by name. + void setEnvironmentName(StringRef Str); + + /// Set the operating system and optional environment components with a single + /// string. + void setOSAndEnvironmentName(StringRef Str); + + /// @} + /// @name Helpers to build variants of a particular triple. + /// @{ + + /// Form a triple with a 32-bit variant of the current architecture. + /// + /// This can be used to move across "families" of architectures where useful. + /// + /// \returns A new triple with a 32-bit architecture or an unknown + /// architecture if no such variant can be found. + llvm::Triple get32BitArchVariant() const; + + /// Form a triple with a 64-bit variant of the current architecture. + /// + /// This can be used to move across "families" of architectures where useful. + /// + /// \returns A new triple with a 64-bit architecture or an unknown + /// architecture if no such variant can be found. + llvm::Triple get64BitArchVariant() const; + + /// Form a triple with a big endian variant of the current architecture. + /// + /// This can be used to move across "families" of architectures where useful. + /// + /// \returns A new triple with a big endian architecture or an unknown + /// architecture if no such variant can be found. + llvm::Triple getBigEndianArchVariant() const; + + /// Form a triple with a little endian variant of the current architecture. + /// + /// This can be used to move across "families" of architectures where useful. + /// + /// \returns A new triple with a little endian architecture or an unknown + /// architecture if no such variant can be found. + llvm::Triple getLittleEndianArchVariant() const; + + /// Tests whether the target triple is little endian. + /// + /// \returns true if the triple is little endian, false otherwise. + bool isLittleEndian() const; + + /// Test whether target triples are compatible. + bool isCompatibleWith(const Triple &Other) const; + + /// Merge target triples. + std::string merge(const Triple &Other) const; + + /// Some platforms have different minimum supported OS versions that + /// varies by the architecture specified in the triple. This function + /// returns the minimum supported OS version for this triple if one an exists, + /// or an invalid version tuple if this triple doesn't have one. + VersionTuple getMinimumSupportedOSVersion() const; + + /// @} + /// @name Static helpers for IDs. + /// @{ + + /// Get the canonical name for the \p Kind architecture. + static StringRef getArchTypeName(ArchType Kind); + + /// Get the "prefix" canonical name for the \p Kind architecture. This is the + /// prefix used by the architecture specific builtins, and is suitable for + /// passing to \see Intrinsic::getIntrinsicForClangBuiltin(). + /// + /// \return - The architecture prefix, or 0 if none is defined. + static StringRef getArchTypePrefix(ArchType Kind); + + /// Get the canonical name for the \p Kind vendor. + static StringRef getVendorTypeName(VendorType Kind); + + /// Get the canonical name for the \p Kind operating system. + static StringRef getOSTypeName(OSType Kind); + + /// Get the canonical name for the \p Kind environment. + static StringRef getEnvironmentTypeName(EnvironmentType Kind); + + /// Get the name for the \p Object format. + static StringRef getObjectFormatTypeName(ObjectFormatType ObjectFormat); + + /// @} + /// @name Static helpers for converting alternate architecture names. + /// @{ + + /// The canonical type for the given LLVM architecture name (e.g., "x86"). + static ArchType getArchTypeForLLVMName(StringRef Str); + + /// @} + + /// Returns a canonicalized OS version number for the specified OS. + static VersionTuple getCanonicalVersionForOS(OSType OSKind, + const VersionTuple &Version); +}; + +} // End llvm namespace + + +#endif diff --git a/include/swift/Runtime/RuntimeFnWrappersGen.h b/include/swift/Runtime/RuntimeFnWrappersGen.h index 3548bc2f99a..92dbc17c473 100644 --- a/include/swift/Runtime/RuntimeFnWrappersGen.h +++ b/include/swift/Runtime/RuntimeFnWrappersGen.h @@ -44,6 +44,7 @@ llvm::Constant *getRuntimeFn(llvm::Module &Module, llvm::Constant *&cache, llvm::ArrayRef retTypes, llvm::ArrayRef argTypes, llvm::ArrayRef attrs, + llvm::ArrayRef memEffects, irgen::IRGenModule *IGM = nullptr); llvm::FunctionType *getRuntimeFnType(llvm::Module &Module, diff --git a/include/swift/Runtime/RuntimeFunctions.def b/include/swift/Runtime/RuntimeFunctions.def index 5a788b02bf7..44cde707d17 100644 --- a/include/swift/Runtime/RuntimeFunctions.def +++ b/include/swift/Runtime/RuntimeFunctions.def @@ -29,6 +29,7 @@ /// list of expressions meant to be looked up in IRGenModule. /// Attrs is a parenthesized list of attributes. /// Effect is a list of runtime effects as defined by RuntimeEffect. +/// MemEffects is a list of memory effects /// /// By default, passes Id to FUNCTION_ID. Therefore, the valid uses of /// this database define either: @@ -40,8 +41,11 @@ /// NO_ARGS /// ATTRS /// NO_ATTRS +/// MEMEFFECTS +/// UNKNOWN_MEMEFFECTS + #ifndef FUNCTION -#define FUNCTION(Id, Name, CC, Availability, ReturnTys, ArgTys, Attrs, Effect) \ +#define FUNCTION(Id, Name, CC, Availability, ReturnTys, ArgTys, Attrs, Effect, MemEffects) \ FUNCTION_ID(Id) #endif @@ -49,7 +53,8 @@ FUNCTION(AllocBox, swift_allocBox, SwiftCC, AlwaysAvailable, RETURNS(RefCountedPtrTy, OpaquePtrTy), ARGS(TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(Allocating)) + EFFECT(Allocating), + UNKNOWN_MEMEFFECTS) // BoxPair swift_makeBoxUnique(OpaqueValue *buffer, Metadata *type, size_t alignMask); FUNCTION(MakeBoxUnique, @@ -58,33 +63,38 @@ FUNCTION(MakeBoxUnique, RETURNS(RefCountedPtrTy, OpaquePtrTy), ARGS(OpaquePtrTy, TypeMetadataPtrTy, SizeTy), ATTRS(NoUnwind), - EFFECT(Allocating)) + EFFECT(Allocating), + UNKNOWN_MEMEFFECTS) FUNCTION(DeallocBox, swift_deallocBox, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(RefCountedPtrTy), ATTRS(NoUnwind), - EFFECT(Deallocating)) + EFFECT(Deallocating), + UNKNOWN_MEMEFFECTS) // swift_projectBox reads object metadata so cannot be marked ReadNone. FUNCTION(ProjectBox, swift_projectBox, C_CC, AlwaysAvailable, RETURNS(OpaquePtrTy), ARGS(RefCountedPtrTy), - ATTRS(NoUnwind, ReadOnly, ArgMemOnly, WillReturn), - EFFECT(NoEffect)) + ATTRS(NoUnwind, WillReturn), + EFFECT(NoEffect), + MEMEFFECTS(ArgMemReadOnly)) FUNCTION(AllocEmptyBox, swift_allocEmptyBox, C_CC, AlwaysAvailable, RETURNS(RefCountedPtrTy), ARGS(), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // RefCounted *swift_allocObject(Metadata *type, size_t size, size_t alignMask); FUNCTION(AllocObject, swift_allocObject, C_CC, AlwaysAvailable, RETURNS(RefCountedPtrTy), ARGS(TypeMetadataPtrTy, SizeTy, SizeTy), ATTRS(NoUnwind), - EFFECT(Allocating)) + EFFECT(Allocating), + UNKNOWN_MEMEFFECTS) // HeapObject *swift_initStackObject(HeapMetadata const *metadata, // HeapObject *object); @@ -92,7 +102,8 @@ FUNCTION(InitStackObject, swift_initStackObject, C_CC, AlwaysAvailable, RETURNS(RefCountedPtrTy), ARGS(TypeMetadataPtrTy, RefCountedPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // HeapObject *swift_initStaticObject(HeapMetadata const *metadata, // HeapObject *object); @@ -100,21 +111,24 @@ FUNCTION(InitStaticObject, swift_initStaticObject, C_CC, AlwaysAvailable, RETURNS(RefCountedPtrTy), ARGS(TypeMetadataPtrTy, RefCountedPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(Locking)) + EFFECT(Locking), + UNKNOWN_MEMEFFECTS) // void swift_verifyEndOfLifetime(HeapObject *object); FUNCTION(VerifyEndOfLifetime, swift_verifyEndOfLifetime, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(RefCountedPtrTy), ATTRS(NoUnwind), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_deallocObject(HeapObject *obj, size_t size, size_t alignMask); FUNCTION(DeallocObject, swift_deallocObject, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(RefCountedPtrTy, SizeTy, SizeTy), ATTRS(NoUnwind), - EFFECT(Deallocating)) + EFFECT(Deallocating), + UNKNOWN_MEMEFFECTS) // void swift_deallocUninitializedObject(HeapObject *obj, size_t size, size_t alignMask); FUNCTION(DeallocUninitializedObject, swift_deallocUninitializedObject, @@ -122,14 +136,16 @@ FUNCTION(DeallocUninitializedObject, swift_deallocUninitializedObject, RETURNS(VoidTy), ARGS(RefCountedPtrTy, SizeTy, SizeTy), ATTRS(NoUnwind), - EFFECT(Deallocating)) + EFFECT(Deallocating), + UNKNOWN_MEMEFFECTS) // void swift_deallocClassInstance(HeapObject *obj, size_t size, size_t alignMask); FUNCTION(DeallocClassInstance, swift_deallocClassInstance, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(RefCountedPtrTy, SizeTy, SizeTy), ATTRS(NoUnwind), - EFFECT(Deallocating)) + EFFECT(Deallocating), + UNKNOWN_MEMEFFECTS) // void swift_deallocPartialClassInstance(HeapObject *obj, HeapMetadata *type, size_t size, size_t alignMask); FUNCTION(DeallocPartialClassInstance, swift_deallocPartialClassInstance, @@ -137,77 +153,88 @@ FUNCTION(DeallocPartialClassInstance, swift_deallocPartialClassInstance, RETURNS(VoidTy), ARGS(RefCountedPtrTy, TypeMetadataPtrTy, SizeTy, SizeTy), ATTRS(NoUnwind), - EFFECT(Deallocating)) + EFFECT(Deallocating), + UNKNOWN_MEMEFFECTS) // void *swift_slowAlloc(size_t size, size_t alignMask); FUNCTION(SlowAlloc, swift_slowAlloc, C_CC, AlwaysAvailable, RETURNS(Int8PtrTy), ARGS(SizeTy, SizeTy), ATTRS(NoUnwind), - EFFECT(Allocating)) + EFFECT(Allocating), + UNKNOWN_MEMEFFECTS) // void swift_slowDealloc(void *ptr, size_t size, size_t alignMask); FUNCTION(SlowDealloc, swift_slowDealloc, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(Int8PtrTy, SizeTy, SizeTy), ATTRS(NoUnwind), - EFFECT(Deallocating)) + EFFECT(Deallocating), + UNKNOWN_MEMEFFECTS) // void swift_willThrow(error *ptr); FUNCTION(WillThrow, swift_willThrow, SwiftCC, AlwaysAvailable, RETURNS(VoidTy), ARGS(Int8PtrTy, ErrorPtrTy->getPointerTo()), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void swift_errorInMain(error *ptr); FUNCTION(ErrorInMain, swift_errorInMain, SwiftCC, AlwaysAvailable, RETURNS(VoidTy), ARGS(ErrorPtrTy), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void swift_unexpectedError(error *ptr); FUNCTION(UnexpectedError, swift_unexpectedError, SwiftCC, AlwaysAvailable, RETURNS(VoidTy), ARGS(ErrorPtrTy), ATTRS(NoUnwind, NoReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void *swift_copyPOD(void *dest, void *src, Metadata *self); FUNCTION(CopyPOD, swift_copyPOD, C_CC, AlwaysAvailable, RETURNS(OpaquePtrTy), ARGS(OpaquePtrTy, OpaquePtrTy, TypeMetadataPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void *swift_retain(void *ptr); FUNCTION(NativeStrongRetain, swift_retain, C_CC, AlwaysAvailable, RETURNS(RefCountedPtrTy), ARGS(RefCountedPtrTy), ATTRS(NoUnwind, FirstParamReturned, WillReturn), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_release(void *ptr); FUNCTION(NativeStrongRelease, swift_release, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(RefCountedPtrTy), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void *swift_retain_n(void *ptr, int32_t n); FUNCTION(NativeStrongRetainN, swift_retain_n, C_CC, AlwaysAvailable, RETURNS(RefCountedPtrTy), ARGS(RefCountedPtrTy, Int32Ty), ATTRS(NoUnwind, FirstParamReturned, WillReturn), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void *swift_release_n(void *ptr, int32_t n); FUNCTION(NativeStrongReleaseN, swift_release_n, C_CC, AlwaysAvailable, RETURNS(RefCountedPtrTy), ARGS(RefCountedPtrTy, Int32Ty), ATTRS(NoUnwind, FirstParamReturned), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void swift_setDeallocating(void *ptr); FUNCTION(NativeSetDeallocating, swift_setDeallocating, @@ -215,21 +242,24 @@ FUNCTION(NativeSetDeallocating, swift_setDeallocating, RETURNS(VoidTy), ARGS(RefCountedPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void *swift_nonatomic_retain_n(void *ptr, int32_t n); FUNCTION(NativeNonAtomicStrongRetainN, swift_nonatomic_retain_n, C_CC, AlwaysAvailable, RETURNS(RefCountedPtrTy), ARGS(RefCountedPtrTy, Int32Ty), ATTRS(NoUnwind, FirstParamReturned, WillReturn), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_nonatomic_release_n(void *ptr, int32_t n); FUNCTION(NativeNonAtomicStrongReleaseN, swift_nonatomic_release_n, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(RefCountedPtrTy, Int32Ty), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void *swift_unknownObjectRetain_n(void *ptr, int32_t n); FUNCTION(UnknownObjectRetainN, swift_unknownObjectRetain_n, @@ -237,7 +267,8 @@ FUNCTION(UnknownObjectRetainN, swift_unknownObjectRetain_n, RETURNS(RefCountedPtrTy), ARGS(RefCountedPtrTy, Int32Ty), ATTRS(NoUnwind, FirstParamReturned), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_unknownObjectRelease_n(void *ptr, int32_t n); FUNCTION(UnknownObjectReleaseN, swift_unknownObjectRelease_n, @@ -245,7 +276,8 @@ FUNCTION(UnknownObjectReleaseN, swift_unknownObjectRelease_n, RETURNS(VoidTy), ARGS(RefCountedPtrTy, Int32Ty), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void *swift_nonatomic_unknownObjectRetain_n(void *ptr, int32_t n); FUNCTION(NonAtomicUnknownObjectRetainN, swift_nonatomic_unknownObjectRetain_n, @@ -253,7 +285,8 @@ FUNCTION(NonAtomicUnknownObjectRetainN, swift_nonatomic_unknownObjectRetain_n, RETURNS(RefCountedPtrTy), ARGS(RefCountedPtrTy, Int32Ty), ATTRS(NoUnwind, FirstParamReturned), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_nonatomic_unknownObjectRelease_n(void *ptr, int32_t n); FUNCTION(NonAtomicUnknownObjectReleaseN, swift_nonatomic_unknownObjectRelease_n, @@ -261,7 +294,8 @@ FUNCTION(NonAtomicUnknownObjectReleaseN, swift_nonatomic_unknownObjectRelease_n, RETURNS(VoidTy), ARGS(RefCountedPtrTy, Int32Ty), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void swift_bridgeObjectRetain_n(void *ptr, int32_t n); FUNCTION(BridgeObjectRetainN, swift_bridgeObjectRetain_n, @@ -269,7 +303,8 @@ FUNCTION(BridgeObjectRetainN, swift_bridgeObjectRetain_n, RETURNS(BridgeObjectPtrTy), ARGS(BridgeObjectPtrTy, Int32Ty), ATTRS(NoUnwind, FirstParamReturned), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_bridgeObjectRelease_n(void *ptr, int32_t n); FUNCTION(BridgeObjectReleaseN, swift_bridgeObjectRelease_n, @@ -277,7 +312,8 @@ FUNCTION(BridgeObjectReleaseN, swift_bridgeObjectRelease_n, RETURNS(VoidTy), ARGS(BridgeObjectPtrTy, Int32Ty), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void swift_nonatomic_bridgeObjectRetain_n(void *ptr, int32_t n); FUNCTION(NonAtomicBridgeObjectRetainN, swift_nonatomic_bridgeObjectRetain_n, @@ -285,7 +321,8 @@ FUNCTION(NonAtomicBridgeObjectRetainN, swift_nonatomic_bridgeObjectRetain_n, RETURNS(BridgeObjectPtrTy), ARGS(BridgeObjectPtrTy, Int32Ty), ATTRS(NoUnwind, FirstParamReturned), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_nonatomic_bridgeObjectRelease_n(void *ptr, int32_t n); FUNCTION(NonAtomicBridgeObjectReleaseN, swift_nonatomic_bridgeObjectRelease_n, @@ -293,7 +330,8 @@ FUNCTION(NonAtomicBridgeObjectReleaseN, swift_nonatomic_bridgeObjectRelease_n, RETURNS(VoidTy), ARGS(BridgeObjectPtrTy, Int32Ty), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void *swift_nonatomic_retain(void *ptr); FUNCTION(NativeNonAtomicStrongRetain, swift_nonatomic_retain, @@ -301,7 +339,8 @@ FUNCTION(NativeNonAtomicStrongRetain, swift_nonatomic_retain, RETURNS(RefCountedPtrTy), ARGS(RefCountedPtrTy), ATTRS(NoUnwind, FirstParamReturned, WillReturn), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_nonatomic_release(void *ptr); FUNCTION(NativeNonAtomicStrongRelease, swift_nonatomic_release, @@ -309,28 +348,32 @@ FUNCTION(NativeNonAtomicStrongRelease, swift_nonatomic_release, RETURNS(VoidTy), ARGS(RefCountedPtrTy), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void *swift_tryRetain(void *ptr); FUNCTION(NativeTryRetain, swift_tryRetain, C_CC, AlwaysAvailable, RETURNS(RefCountedPtrTy), ARGS(RefCountedPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(RefCounting, Locking)) + EFFECT(RefCounting, Locking), + UNKNOWN_MEMEFFECTS) // bool swift_isDeallocating(void *ptr); FUNCTION(IsDeallocating, swift_isDeallocating, C_CC, AlwaysAvailable, RETURNS(Int1Ty), ARGS(RefCountedPtrTy), ATTRS(NoUnwind, ZExt, WillReturn), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void *swift_unknownObjectRetain(void *ptr); FUNCTION(UnknownObjectRetain, swift_unknownObjectRetain, C_CC, AlwaysAvailable, RETURNS(UnknownRefCountedPtrTy), ARGS(UnknownRefCountedPtrTy), ATTRS(NoUnwind, FirstParamReturned), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_unknownObjectRelease(void *ptr); FUNCTION(UnknownObjectRelease, swift_unknownObjectRelease, @@ -338,7 +381,8 @@ FUNCTION(UnknownObjectRelease, swift_unknownObjectRelease, RETURNS(VoidTy), ARGS(UnknownRefCountedPtrTy), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void *swift_nonatomic_unknownObjectRetain(void *ptr); FUNCTION(NonAtomicUnknownObjectRetain, swift_nonatomic_unknownObjectRetain, @@ -346,7 +390,8 @@ FUNCTION(NonAtomicUnknownObjectRetain, swift_nonatomic_unknownObjectRetain, RETURNS(UnknownRefCountedPtrTy), ARGS(UnknownRefCountedPtrTy), ATTRS(NoUnwind, FirstParamReturned), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_nonatomic_unknownObjectRelease(void *ptr); FUNCTION(NonAtomicUnknownObjectRelease, swift_nonatomic_unknownObjectRelease, @@ -354,7 +399,8 @@ FUNCTION(NonAtomicUnknownObjectRelease, swift_nonatomic_unknownObjectRelease, RETURNS(VoidTy), ARGS(UnknownRefCountedPtrTy), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void *swift_bridgeObjectRetain(void *ptr); FUNCTION(BridgeObjectStrongRetain, swift_bridgeObjectRetain, @@ -362,7 +408,8 @@ FUNCTION(BridgeObjectStrongRetain, swift_bridgeObjectRetain, RETURNS(BridgeObjectPtrTy), ARGS(BridgeObjectPtrTy), ATTRS(NoUnwind, FirstParamReturned), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_bridgeRelease(void *ptr); FUNCTION(BridgeObjectStrongRelease, swift_bridgeObjectRelease, @@ -370,7 +417,8 @@ FUNCTION(BridgeObjectStrongRelease, swift_bridgeObjectRelease, RETURNS(VoidTy), ARGS(BridgeObjectPtrTy), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void *swift_nonatomic_bridgeObjectRetain(void *ptr); FUNCTION(NonAtomicBridgeObjectStrongRetain, swift_nonatomic_bridgeObjectRetain, @@ -378,7 +426,8 @@ FUNCTION(NonAtomicBridgeObjectStrongRetain, swift_nonatomic_bridgeObjectRetain, RETURNS(BridgeObjectPtrTy), ARGS(BridgeObjectPtrTy), ATTRS(NoUnwind, FirstParamReturned), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_nonatomic_bridgeRelease(void *ptr); FUNCTION(NonAtomicBridgeObjectStrongRelease, @@ -387,7 +436,8 @@ FUNCTION(NonAtomicBridgeObjectStrongRelease, RETURNS(VoidTy), ARGS(BridgeObjectPtrTy), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // error *swift_errorRetain(error *ptr); @@ -396,7 +446,8 @@ FUNCTION(ErrorStrongRetain, swift_errorRetain, RETURNS(ErrorPtrTy), ARGS(ErrorPtrTy), ATTRS(NoUnwind), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_errorRelease(void *ptr); FUNCTION(ErrorStrongRelease, swift_errorRelease, @@ -404,7 +455,8 @@ FUNCTION(ErrorStrongRelease, swift_errorRelease, RETURNS(VoidTy), ARGS(ErrorPtrTy), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) #define NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Nativeness, SymName, UnknownPrefix) \ /* void swift_##SymName##Destroy(Name##Reference *object); */ \ @@ -413,63 +465,73 @@ FUNCTION(ErrorStrongRelease, swift_errorRelease, RETURNS(VoidTy), \ ARGS(Name##ReferencePtrTy), \ ATTRS(NoUnwind), \ - EFFECT(RefCounting, Deallocating)) \ + EFFECT(RefCounting, Deallocating), \ + UNKNOWN_MEMEFFECTS) \ /* void swift_##SymName##Init(Name##Reference *object, void *value); */ \ FUNCTION(Nativeness##Name##Init, swift_##SymName##Init, \ C_CC, AlwaysAvailable, \ RETURNS(Name##ReferencePtrTy), \ ARGS(Name##ReferencePtrTy, UnknownPrefix##RefCountedPtrTy), \ ATTRS(NoUnwind, FirstParamReturned, WillReturn), \ - EFFECT(NoEffect)) \ + EFFECT(NoEffect), \ + UNKNOWN_MEMEFFECTS) \ /* Name##Reference *swift_##SymName##Assign(Name##Reference *object, void *value); */ \ FUNCTION(Nativeness##Name##Assign, swift_##SymName##Assign, \ C_CC, AlwaysAvailable, \ RETURNS(Name##ReferencePtrTy), \ ARGS(Name##ReferencePtrTy, UnknownPrefix##RefCountedPtrTy), \ ATTRS(NoUnwind, FirstParamReturned), \ - EFFECT(RefCounting, Deallocating)) \ + EFFECT(RefCounting, Deallocating), \ + UNKNOWN_MEMEFFECTS) \ /* void *swift_##SymName##Load(Name##Reference *object); */ \ FUNCTION(Nativeness##Name##LoadStrong, swift_##SymName##LoadStrong, \ C_CC, AlwaysAvailable, \ RETURNS(UnknownPrefix##RefCountedPtrTy), \ ARGS(Name##ReferencePtrTy), \ ATTRS(NoUnwind, WillReturn), \ - EFFECT(NoEffect)) \ + EFFECT(NoEffect), \ + UNKNOWN_MEMEFFECTS) \ /* void *swift_##SymName##Take(Name##Reference *object); */ \ FUNCTION(Nativeness##Name##TakeStrong, swift_##SymName##TakeStrong, \ C_CC, AlwaysAvailable, \ RETURNS(UnknownPrefix##RefCountedPtrTy), \ ARGS(Name##ReferencePtrTy), \ ATTRS(NoUnwind, WillReturn), \ - EFFECT(NoEffect)) \ + EFFECT(NoEffect), \ + UNKNOWN_MEMEFFECTS) \ /* Name##Reference *swift_##SymName##CopyInit(Name##Reference *dest, Name##Reference *src); */ \ FUNCTION(Nativeness##Name##CopyInit, swift_##SymName##CopyInit, \ C_CC, AlwaysAvailable, \ RETURNS(Name##ReferencePtrTy), \ ARGS(Name##ReferencePtrTy, Name##ReferencePtrTy), \ ATTRS(NoUnwind, FirstParamReturned, WillReturn), \ - EFFECT(RefCounting)) \ + EFFECT(RefCounting), \ + UNKNOWN_MEMEFFECTS) \ /* void *swift_##SymName##TakeInit(Name##Reference *dest, Name##Reference *src); */ \ FUNCTION(Nativeness##Name##TakeInit, swift_##SymName##TakeInit, \ C_CC, AlwaysAvailable, \ RETURNS(Name##ReferencePtrTy), \ ARGS(Name##ReferencePtrTy, Name##ReferencePtrTy), \ ATTRS(NoUnwind, FirstParamReturned, WillReturn), \ - EFFECT(NoEffect)) \ + EFFECT(NoEffect), \ + UNKNOWN_MEMEFFECTS) \ /* Name##Reference *swift_##SymName##CopyAssign(Name##Reference *dest, Name##Reference *src); */ \ FUNCTION(Nativeness##Name##CopyAssign, swift_##SymName##CopyAssign, \ C_CC, AlwaysAvailable, \ RETURNS(Name##ReferencePtrTy), \ ARGS(Name##ReferencePtrTy, Name##ReferencePtrTy), \ ATTRS(NoUnwind, FirstParamReturned), \ - EFFECT(RefCounting, Deallocating)) \ + EFFECT(RefCounting, Deallocating), \ + UNKNOWN_MEMEFFECTS) \ /* Name##Reference *swift_##SymName##TakeAssign(Name##Reference *dest, Name##Reference *src); */ \ FUNCTION(Nativeness##Name##TakeAssign, swift_##SymName##TakeAssign, \ C_CC, AlwaysAvailable, \ RETURNS(Name##ReferencePtrTy), \ ARGS(Name##ReferencePtrTy, Name##ReferencePtrTy), \ ATTRS(NoUnwind, FirstParamReturned), \ - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), \ + UNKNOWN_MEMEFFECTS) + #define NEVER_LOADABLE_CHECKED_REF_STORAGE(Name, name, ...) \ NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Native, name, ) \ NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Unknown, unknownObject##Name, Unknown) @@ -480,21 +542,24 @@ FUNCTION(ErrorStrongRelease, swift_errorRelease, RETURNS(RefCountedPtrTy), \ ARGS(RefCountedPtrTy), \ ATTRS(NoUnwind, FirstParamReturned, WillReturn), \ - EFFECT(RefCounting)) \ + EFFECT(RefCounting), \ + UNKNOWN_MEMEFFECTS) \ /* void swift_##prefix##name##Release(void *ptr); */ \ FUNCTION(Prefix##Name##Release, swift_##prefix##name##Release, \ C_CC, AlwaysAvailable, \ RETURNS(VoidTy), \ ARGS(RefCountedPtrTy), \ ATTRS(NoUnwind), \ - EFFECT(RefCounting, Deallocating)) \ + EFFECT(RefCounting, Deallocating), \ + UNKNOWN_MEMEFFECTS) \ /* void *swift_##prefix##name##RetainStrong(void *ptr); */ \ FUNCTION(Prefix##StrongRetain##Name, swift_##prefix##name##RetainStrong, \ C_CC, AlwaysAvailable, \ RETURNS(RefCountedPtrTy), \ ARGS(RefCountedPtrTy), \ ATTRS(NoUnwind, FirstParamReturned, WillReturn), \ - EFFECT(RefCounting)) \ + EFFECT(RefCounting), \ + UNKNOWN_MEMEFFECTS) \ /* void swift_##prefix##name##RetainStrongAndRelease(void *ptr); */ \ FUNCTION(Prefix##StrongRetainAnd##Name##Release, \ swift_##prefix##name##RetainStrongAndRelease, \ @@ -502,7 +567,8 @@ FUNCTION(ErrorStrongRelease, swift_errorRelease, RETURNS(VoidTy), \ ARGS(RefCountedPtrTy), \ ATTRS(NoUnwind), \ - EFFECT(RefCounting)) + EFFECT(RefCounting), \ + UNKNOWN_MEMEFFECTS) #define SOMETIMES_LOADABLE_CHECKED_REF_STORAGE(Name, name, ...) \ NEVER_LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, Unknown, unknownObject##Name, Unknown) \ LOADABLE_CHECKED_REF_STORAGE_HELPER(Name, name, Native, ) \ @@ -520,7 +586,8 @@ FUNCTION(IsUniquelyReferencedNonObjC, swift_isUniquelyReferencedNonObjC, RETURNS(Int1Ty), ARGS(UnknownRefCountedPtrTy), ATTRS(NoUnwind, ZExt, WillReturn), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // bool swift_isUniquelyReferencedNonObjC_nonNull(const void *); FUNCTION(IsUniquelyReferencedNonObjC_nonNull, @@ -529,7 +596,8 @@ FUNCTION(IsUniquelyReferencedNonObjC_nonNull, RETURNS(Int1Ty), ARGS(UnknownRefCountedPtrTy), ATTRS(NoUnwind, ZExt, WillReturn), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // bool swift_isUniquelyReferencedNonObjC_nonNull_bridgeObject( // uintptr_t bits); @@ -539,7 +607,8 @@ FUNCTION(IsUniquelyReferencedNonObjC_nonNull_bridgeObject, RETURNS(Int1Ty), ARGS(BridgeObjectPtrTy), ATTRS(NoUnwind, ZExt, WillReturn), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // bool swift_isUniquelyReferenced(const void *); FUNCTION(IsUniquelyReferenced, swift_isUniquelyReferenced, @@ -547,7 +616,8 @@ FUNCTION(IsUniquelyReferenced, swift_isUniquelyReferenced, RETURNS(Int1Ty), ARGS(UnknownRefCountedPtrTy), ATTRS(NoUnwind, ZExt, WillReturn), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // bool swift_isUniquelyReferenced_nonNull(const void *); FUNCTION(IsUniquelyReferenced_nonNull, @@ -556,7 +626,8 @@ FUNCTION(IsUniquelyReferenced_nonNull, RETURNS(Int1Ty), ARGS(UnknownRefCountedPtrTy), ATTRS(NoUnwind, ZExt, WillReturn), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // bool swift_isUniquelyReferenced_nonNull_bridgeObject( // uintptr_t bits); @@ -566,7 +637,8 @@ FUNCTION(IsUniquelyReferenced_nonNull_bridgeObject, RETURNS(Int1Ty), ARGS(BridgeObjectPtrTy), ATTRS(NoUnwind, ZExt, WillReturn), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // bool swift_isUniquelyReferenced_native(const struct HeapObject *); FUNCTION(IsUniquelyReferenced_native, swift_isUniquelyReferenced_native, @@ -574,7 +646,8 @@ FUNCTION(IsUniquelyReferenced_native, swift_isUniquelyReferenced_native, RETURNS(Int1Ty), ARGS(RefCountedPtrTy), ATTRS(NoUnwind, ZExt, WillReturn), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // bool swift_isUniquelyReferenced_nonNull_native(const struct HeapObject *); FUNCTION(IsUniquelyReferenced_nonNull_native, @@ -583,7 +656,8 @@ FUNCTION(IsUniquelyReferenced_nonNull_native, RETURNS(Int1Ty), ARGS(RefCountedPtrTy), ATTRS(NoUnwind, ZExt, WillReturn), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // bool swift_isEscapingClosureAtFileLocation(const struct HeapObject *object, // const unsigned char *filename, @@ -596,7 +670,8 @@ FUNCTION(IsEscapingClosureAtFileLocation, swift_isEscapingClosureAtFileLocation, RETURNS(Int1Ty), ARGS(RefCountedPtrTy, Int8PtrTy, Int32Ty, Int32Ty, Int32Ty, Int32Ty), ATTRS(NoUnwind, ZExt), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_arrayInitWithCopy(opaque*, opaque*, size_t, type*); FUNCTION(ArrayInitWithCopy, swift_arrayInitWithCopy, @@ -604,7 +679,8 @@ FUNCTION(ArrayInitWithCopy, swift_arrayInitWithCopy, RETURNS(VoidTy), ARGS(OpaquePtrTy, OpaquePtrTy, SizeTy, TypeMetadataPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_arrayInitWithTakeNoAlias(opaque*, opaque*, size_t, type*); FUNCTION(ArrayInitWithTakeNoAlias, swift_arrayInitWithTakeNoAlias, @@ -612,7 +688,8 @@ FUNCTION(ArrayInitWithTakeNoAlias, swift_arrayInitWithTakeNoAlias, RETURNS(VoidTy), ARGS(OpaquePtrTy, OpaquePtrTy, SizeTy, TypeMetadataPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void swift_arrayInitWithTakeFrontToBack(opaque*, opaque*, size_t, type*); FUNCTION(ArrayInitWithTakeFrontToBack, swift_arrayInitWithTakeFrontToBack, @@ -620,7 +697,8 @@ FUNCTION(ArrayInitWithTakeFrontToBack, swift_arrayInitWithTakeFrontToBack, RETURNS(VoidTy), ARGS(OpaquePtrTy, OpaquePtrTy, SizeTy, TypeMetadataPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void swift_arrayInitWithTakeBackToFront(opaque*, opaque*, size_t, type*); FUNCTION(ArrayInitWithTakeBackToFront, swift_arrayInitWithTakeBackToFront, @@ -628,7 +706,8 @@ FUNCTION(ArrayInitWithTakeBackToFront, swift_arrayInitWithTakeBackToFront, RETURNS(VoidTy), ARGS(OpaquePtrTy, OpaquePtrTy, SizeTy, TypeMetadataPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void swift_arrayAssignWithCopyNoAlias(opaque*, opaque*, size_t, type*); FUNCTION(ArrayAssignWithCopyNoAlias, swift_arrayAssignWithCopyNoAlias, @@ -636,7 +715,8 @@ FUNCTION(ArrayAssignWithCopyNoAlias, swift_arrayAssignWithCopyNoAlias, RETURNS(VoidTy), ARGS(OpaquePtrTy, OpaquePtrTy, SizeTy, TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void swift_arrayAssignWithCopyFrontToBack(opaque*, opaque*, size_t, type*); FUNCTION(ArrayAssignWithCopyFrontToBack, swift_arrayAssignWithCopyFrontToBack, @@ -644,7 +724,8 @@ FUNCTION(ArrayAssignWithCopyFrontToBack, swift_arrayAssignWithCopyFrontToBack, RETURNS(VoidTy), ARGS(OpaquePtrTy, OpaquePtrTy, SizeTy, TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void swift_arrayAssignWithCopyBackToFront(opaque*, opaque*, size_t, type*); FUNCTION(ArrayAssignWithCopyBackToFront, swift_arrayAssignWithCopyBackToFront, @@ -652,21 +733,24 @@ FUNCTION(ArrayAssignWithCopyBackToFront, swift_arrayAssignWithCopyBackToFront, RETURNS(VoidTy), ARGS(OpaquePtrTy, OpaquePtrTy, SizeTy, TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void swift_arrayAssignWithTake(opaque*, opaque*, size_t, type*); FUNCTION(ArrayAssignWithTake, swift_arrayAssignWithTake, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(OpaquePtrTy, OpaquePtrTy, SizeTy, TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void swift_arrayDestroy(opaque*, size_t, type*); FUNCTION(ArrayDestroy, swift_arrayDestroy, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(OpaquePtrTy, SizeTy, TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(RefCounting, Deallocating)) + EFFECT(RefCounting, Deallocating), + UNKNOWN_MEMEFFECTS) // Metadata *swift_getFunctionTypeMetadata(unsigned long flags, // const Metadata **parameters, @@ -679,8 +763,9 @@ FUNCTION(GetFunctionMetadata, swift_getFunctionTypeMetadata, TypeMetadataPtrTy->getPointerTo(0), Int32Ty->getPointerTo(0), TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadOnly), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) // Metadata * // swift_getFunctionTypeMetadataDifferentiable(unsigned long flags, @@ -697,8 +782,9 @@ FUNCTION(GetFunctionMetadataDifferentiable, TypeMetadataPtrTy->getPointerTo(0), Int32Ty->getPointerTo(0), TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadOnly), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) // Metadata * // swift_getFunctionTypeMetadataGlobalActor(unsigned long flags, @@ -717,8 +803,9 @@ FUNCTION(GetFunctionMetadataGlobalActor, Int32Ty->getPointerTo(0), TypeMetadataPtrTy, TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadOnly), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) // Metadata * // swift_getFunctionTypeMetadataGlobalActorBackDeploy(unsigned long flags, @@ -737,8 +824,9 @@ FUNCTION(GetFunctionMetadataGlobalActorBackDeploy, Int32Ty->getPointerTo(0), TypeMetadataPtrTy, TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadOnly), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) // Metadata *swift_getFunctionTypeMetadata0(unsigned long flags, // const Metadata *resultMetadata); @@ -746,8 +834,9 @@ FUNCTION(GetFunctionMetadata0, swift_getFunctionTypeMetadata0, C_CC, AlwaysAvailable, RETURNS(TypeMetadataPtrTy), ARGS(SizeTy, TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadNone), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ReadNone)) // Metadata *swift_getFunctionTypeMetadata1(unsigned long flags, // const Metadata *arg0, @@ -756,8 +845,9 @@ FUNCTION(GetFunctionMetadata1, swift_getFunctionTypeMetadata1, C_CC, AlwaysAvailable, RETURNS(TypeMetadataPtrTy), ARGS(SizeTy, TypeMetadataPtrTy, TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadNone), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ReadNone)) // Metadata *swift_getFunctionTypeMetadata2(unsigned long flags, // const Metadata *arg0, @@ -767,8 +857,9 @@ FUNCTION(GetFunctionMetadata2, swift_getFunctionTypeMetadata2, C_CC, AlwaysAvailable, RETURNS(TypeMetadataPtrTy), ARGS(SizeTy, TypeMetadataPtrTy, TypeMetadataPtrTy, TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadNone), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ReadNone)) // Metadata *swift_getFunctionTypeMetadata3(unsigned long flags, // const Metadata *arg0, @@ -780,16 +871,18 @@ FUNCTION(GetFunctionMetadata3, swift_getFunctionTypeMetadata3, RETURNS(TypeMetadataPtrTy), ARGS(SizeTy, TypeMetadataPtrTy, TypeMetadataPtrTy, TypeMetadataPtrTy, TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadNone), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ReadNone)) // Metadata *swift_getForeignTypeMetadata(Metadata *nonUnique); FUNCTION(GetForeignTypeMetadata, swift_getForeignTypeMetadata, SwiftCC, AlwaysAvailable, RETURNS(TypeMetadataResponseTy), ARGS(SizeTy, TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadNone), // only writes to runtime-private fields - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ReadNone)) // only writes to runtime-private fields // SWIFT_RUNTIME_EXPORT // SWIFT_CC(swift) @@ -801,8 +894,9 @@ FUNCTION(CompareTypeContextDescriptors, RETURNS(Int1Ty), ARGS(TypeContextDescriptorPtrTy, TypeContextDescriptorPtrTy), - ATTRS(NoUnwind, ReadNone, WillReturn), - EFFECT(NoEffect)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(NoEffect), // ? + MEMEFFECTS(ReadNone)) // MetadataResponse swift_getSingletonMetadata(MetadataRequest request, // TypeContextDescriptor *type); @@ -810,8 +904,9 @@ FUNCTION(GetSingletonMetadata, swift_getSingletonMetadata, SwiftCC, AlwaysAvailable, RETURNS(TypeMetadataResponseTy), ARGS(SizeTy, TypeContextDescriptorPtrTy), - ATTRS(NoUnwind, ReadNone), - EFFECT(MetaData)) // ? + ATTRS(NoUnwind), + EFFECT(MetaData), // ? + MEMEFFECTS(ReadNone)) // MetadataResponse swift_getGenericMetadata(MetadataRequest request, // const void * const *arguments, @@ -820,8 +915,9 @@ FUNCTION(GetGenericMetadata, swift_getGenericMetadata, SwiftCC, AlwaysAvailable, RETURNS(TypeMetadataResponseTy), ARGS(SizeTy, Int8PtrTy, TypeContextDescriptorPtrTy), - ATTRS(NoUnwind, ReadOnly), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) // MetadataResponse swift_getCanonicalSpecializedMetadata(MetadataRequest request, // Metadata *candidate); @@ -829,8 +925,9 @@ FUNCTION(GetCanonicalSpecializedMetadata, swift_getCanonicalSpecializedMetadata, SwiftCC, GetCanonicalSpecializedMetadataAvailability, RETURNS(TypeMetadataResponseTy), ARGS(SizeTy, TypeMetadataPtrTy, TypeMetadataPtrPtrTy), - ATTRS(NoUnwind, ReadOnly), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) // MetadataResponse // swift_getCanonicalPrespecializedGenericMetadata(MetadataRequest request, @@ -842,8 +939,9 @@ FUNCTION(GetCanonicalPrespecializedGenericMetadata, SwiftCC, GetCanonicalPrespecializedGenericMetadataAvailability, RETURNS(TypeMetadataResponseTy), ARGS(SizeTy, Int8PtrTy, TypeContextDescriptorPtrTy, OnceTy->getPointerTo()), - ATTRS(NoUnwind, ReadOnly), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) // MetadataResponse swift_getOpaqueTypeMetadata(MetadataRequest request, // const void * const *arguments, @@ -853,8 +951,10 @@ FUNCTION(GetOpaqueTypeMetadata, swift_getOpaqueTypeMetadata, SwiftCC, OpaqueTypeAvailability, RETURNS(TypeMetadataResponseTy), ARGS(SizeTy, Int8PtrTy, OpaqueTypeDescriptorPtrTy, SizeTy), - ATTRS(NoUnwind, ReadOnly), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) + // MetadataResponse swift_getOpaqueTypeMetadata2(MetadataRequest request, // const void * const *arguments, @@ -864,8 +964,10 @@ FUNCTION(GetOpaqueTypeMetadata2, swift_getOpaqueTypeMetadata2, SwiftCC, SignedDescriptorAvailability, RETURNS(TypeMetadataResponseTy), ARGS(SizeTy, Int8PtrTy, OpaqueTypeDescriptorPtrTy, SizeTy), - ATTRS(NoUnwind, ReadOnly), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) + // const WitnessTable *swift_getOpaqueTypeConformance(const void * const *arguments, // const OpaqueTypeDescriptor *descriptor, @@ -874,8 +976,9 @@ FUNCTION(GetOpaqueTypeConformance, swift_getOpaqueTypeConformance, SwiftCC, OpaqueTypeAvailability, RETURNS(WitnessTablePtrTy), ARGS(Int8PtrTy, OpaqueTypeDescriptorPtrTy, SizeTy), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(MetaData)) + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) // const WitnessTable *swift_getOpaqueTypeConformance2(const void * const *arguments, // const OpaqueTypeDescriptor *descriptor, @@ -884,8 +987,9 @@ FUNCTION(GetOpaqueTypeConformance2, swift_getOpaqueTypeConformance2, SwiftCC, SignedDescriptorAvailability, RETURNS(WitnessTablePtrTy), ARGS(Int8PtrTy, OpaqueTypeDescriptorPtrTy, SizeTy), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(MetaData)) + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) // Metadata *swift_allocateGenericClassMetadata(ClassDescriptor *type, // const void * const *arguments, @@ -895,7 +999,8 @@ FUNCTION(AllocateGenericClassMetadata, swift_allocateGenericClassMetadata, RETURNS(TypeMetadataPtrTy), ARGS(TypeContextDescriptorPtrTy, Int8PtrPtrTy, Int8PtrTy), ATTRS(NoUnwind), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // Metadata *swift_allocateGenericClassMetadataWithLayoutString( // ClassDescriptor *type, @@ -907,7 +1012,8 @@ FUNCTION(AllocateGenericClassMetadataWithLayoutString, RETURNS(TypeMetadataPtrTy), ARGS(TypeContextDescriptorPtrTy, Int8PtrPtrTy, Int8PtrTy), ATTRS(NoUnwind), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // Metadata *swift_allocateGenericValueMetadata(ValueTypeDescriptor *type, // const void * const *arguments, @@ -918,7 +1024,8 @@ FUNCTION(AllocateGenericValueMetadata, swift_allocateGenericValueMetadata, RETURNS(TypeMetadataPtrTy), ARGS(TypeContextDescriptorPtrTy, Int8PtrPtrTy, Int8PtrTy, SizeTy), ATTRS(NoUnwind), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // Metadata *swift_allocateGenericValueMetadataWithLayoutString( // ValueTypeDescriptor *type, @@ -931,7 +1038,8 @@ FUNCTION(AllocateGenericValueMetadataWithLayoutString, RETURNS(TypeMetadataPtrTy), ARGS(TypeContextDescriptorPtrTy, Int8PtrPtrTy, Int8PtrTy, SizeTy), ATTRS(NoUnwind), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // MetadataResponse swift_checkMetadataState(MetadataRequest request, // const Metadata *type); @@ -939,8 +1047,10 @@ FUNCTION(CheckMetadataState, swift_checkMetadataState, SwiftCC, AlwaysAvailable, RETURNS(TypeMetadataResponseTy), ARGS(SizeTy, TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(MetaData)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), // ? + MEMEFFECTS(ReadOnly)) + // const ProtocolWitnessTable * // swift_getWitnessTable(const ProtocolConformanceDescriptor *conf, @@ -951,15 +1061,18 @@ FUNCTION(GetWitnessTable, swift_getWitnessTable, C_CC, AlwaysAvailable, ARGS(ProtocolConformanceDescriptorPtrTy, TypeMetadataPtrTy, WitnessTablePtrPtrTy), - ATTRS(NoUnwind, ReadOnly), - EFFECT(MetaData)) // ? + ATTRS(NoUnwind), + EFFECT(MetaData), // ? + MEMEFFECTS(ReadOnly)) + FUNCTION(GetWitnessTableRelative, swift_getWitnessTableRelative, C_CC, AlwaysAvailable, RETURNS(WitnessTablePtrTy), ARGS(ProtocolConformanceDescriptorPtrTy, TypeMetadataPtrTy, WitnessTablePtrPtrTy), - ATTRS(NoUnwind, ReadOnly), - EFFECT(MetaData)) // ? + ATTRS(NoUnwind), + EFFECT(MetaData), // ? + MEMEFFECTS(ReadOnly)) // MetadataResponse swift_getAssociatedTypeWitness( // MetadataRequest request, @@ -975,8 +1088,9 @@ FUNCTION(GetAssociatedTypeWitness, swift_getAssociatedTypeWitness, TypeMetadataPtrTy, ProtocolRequirementStructTy->getPointerTo(), ProtocolRequirementStructTy->getPointerTo()), - ATTRS(NoUnwind, ReadNone, WillReturn), - EFFECT(MetaData)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), // ? + MEMEFFECTS(ReadNone)) FUNCTION(GetAssociatedTypeWitnessRelative, swift_getAssociatedTypeWitnessRelative, SwiftCC, AlwaysAvailable, RETURNS(TypeMetadataResponseTy), @@ -985,8 +1099,9 @@ FUNCTION(GetAssociatedTypeWitnessRelative, swift_getAssociatedTypeWitnessRelativ TypeMetadataPtrTy, ProtocolRequirementStructTy->getPointerTo(), ProtocolRequirementStructTy->getPointerTo()), - ATTRS(NoUnwind, ReadNone, WillReturn), - EFFECT(MetaData)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), // ? + MEMEFFECTS(ReadNone)) // SWIFT_RUNTIME_EXPORT SWIFT_CC(swift) // const WitnessTable *swift_getAssociatedConformanceWitness( @@ -1003,8 +1118,9 @@ FUNCTION(GetAssociatedConformanceWitness, TypeMetadataPtrTy, ProtocolRequirementStructTy->getPointerTo(), ProtocolRequirementStructTy->getPointerTo()), - ATTRS(NoUnwind, ReadNone, WillReturn), - EFFECT(MetaData)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), // ? + MEMEFFECTS(ReadNone)) FUNCTION(GetAssociatedConformanceWitnessRelative, swift_getAssociatedConformanceWitnessRelative, SwiftCC, AlwaysAvailable, RETURNS(WitnessTablePtrTy), @@ -1013,8 +1129,9 @@ FUNCTION(GetAssociatedConformanceWitnessRelative, TypeMetadataPtrTy, ProtocolRequirementStructTy->getPointerTo(), ProtocolRequirementStructTy->getPointerTo()), - ATTRS(NoUnwind, ReadNone, WillReturn), - EFFECT(MetaData)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), // ? + MEMEFFECTS(ReadNone)) // SWIFT_RUNTIME_EXPORT // SWIFT_CC(swift) bool swift_compareProtocolConformanceDescriptors( @@ -1026,8 +1143,9 @@ FUNCTION(CompareProtocolConformanceDescriptors, RETURNS(Int1Ty), ARGS(ProtocolConformanceDescriptorPtrTy, ProtocolConformanceDescriptorPtrTy), - ATTRS(NoUnwind, ReadNone, WillReturn), - EFFECT(NoEffect)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(NoEffect), // ? + MEMEFFECTS(ReadNone)) // SWIFT_RUNTIME_EXPORT SWIFT_CC(swift) // const Metadata * const * @@ -1038,7 +1156,8 @@ FUNCTION(AllocateMetadataPack, RETURNS(TypeMetadataPtrPtrTy), ARGS(TypeMetadataPtrPtrTy, SizeTy), ATTRS(NoUnwind, WillReturn), - EFFECT(MetaData)) // ? + EFFECT(MetaData), // ? + UNKNOWN_MEMEFFECTS) // SWIFT_RUNTIME_EXPORT SWIFT_CC(swift) // const WitnessTable * const * @@ -1049,38 +1168,43 @@ FUNCTION(AllocateWitnessTablePack, RETURNS(WitnessTablePtrPtrTy), ARGS(WitnessTablePtrPtrTy, SizeTy), ATTRS(NoUnwind, WillReturn), - EFFECT(MetaData)) // ? + EFFECT(MetaData), // ? + UNKNOWN_MEMEFFECTS) // Metadata *swift_getMetatypeMetadata(Metadata *instanceTy); FUNCTION(GetMetatypeMetadata, swift_getMetatypeMetadata, C_CC, AlwaysAvailable, RETURNS(TypeMetadataPtrTy), ARGS(TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadNone, WillReturn), - EFFECT(MetaData)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), // ? + MEMEFFECTS(ReadNone)) // Metadata *swift_getExistentialMetatypeMetadata(Metadata *instanceTy); FUNCTION(GetExistentialMetatypeMetadata, swift_getExistentialMetatypeMetadata, C_CC, AlwaysAvailable, RETURNS(TypeMetadataPtrTy), ARGS(TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadNone, WillReturn), - EFFECT(MetaData)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), // ? + MEMEFFECTS(ReadNone)) // Metadata *swift_getObjCClassMetadata(objc_class *theClass); FUNCTION(GetObjCClassMetadata, swift_getObjCClassMetadata, C_CC, AlwaysAvailable, RETURNS(TypeMetadataPtrTy), ARGS(ObjCClassPtrTy), - ATTRS(NoUnwind, ReadNone, WillReturn), - EFFECT(MetaData)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), // ? + MEMEFFECTS(ReadNone)) // Metadata *swift_getObjCClassFromMetadata(objc_class *theClass); FUNCTION(GetObjCClassFromMetadata, swift_getObjCClassFromMetadata, C_CC, AlwaysAvailable, RETURNS(ObjCClassPtrTy), ARGS(TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadNone, WillReturn), - EFFECT(NoEffect)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(NoEffect), // ? + MEMEFFECTS(ReadNone)) // Metadata *swift_getObjCClassFromObject(id object); // This reads object metadata so cannot be marked ReadNone. @@ -1088,8 +1212,9 @@ FUNCTION(GetObjCClassFromObject, swift_getObjCClassFromObject, C_CC, AlwaysAvailable, RETURNS(ObjCClassPtrTy), ARGS(ObjCPtrTy), - ATTRS(NoUnwind, ReadOnly, ArgMemOnly, WillReturn), - EFFECT(NoEffect)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(NoEffect), // ? + MEMEFFECTS(ArgMemReadOnly)) // MetadataResponse swift_getTupleTypeMetadata(MetadataRequest request, // TupleTypeFlags flags, @@ -1100,8 +1225,9 @@ FUNCTION(GetTupleMetadata, swift_getTupleTypeMetadata, SwiftCC, AlwaysAvailable, RETURNS(TypeMetadataResponseTy), ARGS(SizeTy, SizeTy, TypeMetadataPtrTy->getPointerTo(0), Int8PtrTy, WitnessTablePtrTy), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(MetaData)) + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) // MetadataResponse swift_getTupleTypeMetadata2(MetadataRequest request, // Metadata *elt0, Metadata *elt1, @@ -1111,8 +1237,9 @@ FUNCTION(GetTupleMetadata2, swift_getTupleTypeMetadata2, SwiftCC, AlwaysAvailabl RETURNS(TypeMetadataResponseTy), ARGS(SizeTy, TypeMetadataPtrTy, TypeMetadataPtrTy, Int8PtrTy, WitnessTablePtrTy), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(MetaData)) + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) // MetadataResponse swift_getTupleTypeMetadata3(MetadataRequest request, // Metadata *elt0, Metadata *elt1, @@ -1123,8 +1250,9 @@ FUNCTION(GetTupleMetadata3, swift_getTupleTypeMetadata3, SwiftCC, AlwaysAvailabl RETURNS(TypeMetadataResponseTy), ARGS(SizeTy, TypeMetadataPtrTy, TypeMetadataPtrTy, TypeMetadataPtrTy, Int8PtrTy, WitnessTablePtrTy), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(MetaData)) + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) // void swift_getTupleTypeLayout(TypeLayout *result, // uint32_t offsets, @@ -1135,7 +1263,8 @@ FUNCTION(GetTupleLayout, swift_getTupleTypeLayout, SwiftCC, AlwaysAvailable, ARGS(FullTypeLayoutTy->getPointerTo(0), Int32Ty->getPointerTo(0), SizeTy, Int8PtrPtrTy->getPointerTo(0)), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // size_t swift_getTupleTypeLayout2(TypeLayout *layout, // const TypeLayout *elt0, @@ -1144,7 +1273,8 @@ FUNCTION(GetTupleLayout2, swift_getTupleTypeLayout2, SwiftCC, AlwaysAvailable, RETURNS(SizeTy), ARGS(FullTypeLayoutTy->getPointerTo(0), Int8PtrPtrTy, Int8PtrPtrTy), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // OffsetPair swift_getTupleTypeLayout3(TypeLayout *layout, // const TypeLayout *elt0, @@ -1155,7 +1285,8 @@ FUNCTION(GetTupleLayout3, swift_getTupleTypeLayout3, SwiftCC, AlwaysAvailable, ARGS(FullTypeLayoutTy->getPointerTo(0), Int8PtrPtrTy, Int8PtrPtrTy, Int8PtrPtrTy), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // Metadata *swift_getExistentialTypeMetadata( // ProtocolClassConstraint classConstraint, @@ -1170,8 +1301,10 @@ FUNCTION(GetExistentialMetadata, RETURNS(TypeMetadataPtrTy), ARGS(Int1Ty, TypeMetadataPtrTy, SizeTy, ProtocolDescriptorRefTy->getPointerTo()), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(MetaData)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), // ? + MEMEFFECTS(ReadOnly)) + // const ExtendedExistentialTypeShape * // swift_getExtendedExistentialTypeShape( @@ -1180,8 +1313,9 @@ FUNCTION(GetExtendedExistentialTypeShape, swift_getExtendedExistentialTypeShape, C_CC, AlwaysAvailable, RETURNS(TypeMetadataPtrTy), ARGS(Int8PtrTy, Int8PtrPtrTy), - ATTRS(NoUnwind, ArgMemOnly, WillReturn), - EFFECT(MetaData)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), // ? + MEMEFFECTS(ArgMemOnly)) // Metadata *swift_getExtendedExistentialTypeMetadata( // const NonUniqueExtendedExistentialTypeShape *shape, @@ -1190,8 +1324,9 @@ FUNCTION(GetExtendedExistentialTypeMetadata, swift_getExtendedExistentialTypeMetadata, C_CC, AlwaysAvailable, RETURNS(TypeMetadataPtrTy), ARGS(Int8PtrTy, Int8PtrPtrTy), - ATTRS(NoUnwind, ArgMemOnly, WillReturn), - EFFECT(MetaData)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), // ? + MEMEFFECTS(ArgMemOnly)) // Metadata *swift_getExtendedExistentialTypeMetadata_unique( // const ExtendedExistentialTypeShape *shape, @@ -1200,8 +1335,9 @@ FUNCTION(GetExtendedExistentialTypeMetadataUnique, swift_getExtendedExistentialTypeMetadata_unique, C_CC, AlwaysAvailable, RETURNS(TypeMetadataPtrTy), ARGS(Int8PtrTy, Int8PtrPtrTy), - ATTRS(NoUnwind, ArgMemOnly, WillReturn), - EFFECT(MetaData)) // ? + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), // ? + MEMEFFECTS(ArgMemOnly)) // Metadata *swift_relocateClassMetadata(TypeContextDescriptor *descriptor, // const void *pattern); @@ -1210,7 +1346,8 @@ FUNCTION(RelocateClassMetadata, RETURNS(TypeMetadataPtrTy), ARGS(TypeContextDescriptorPtrTy, Int8PtrTy), ATTRS(NoUnwind), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // void swift_initClassMetadata(Metadata *self, // ClassLayoutFlags flags, @@ -1224,7 +1361,8 @@ FUNCTION(InitClassMetadata, Int8PtrPtrTy->getPointerTo(), SizeTy->getPointerTo()), ATTRS(NoUnwind), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // void swift_updateClassMetadata(Metadata *self, // ClassLayoutFlags flags, @@ -1238,7 +1376,8 @@ FUNCTION(UpdateClassMetadata, Int8PtrPtrTy->getPointerTo(), SizeTy->getPointerTo()), ATTRS(NoUnwind), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // MetadataDependency swift_initClassMetadata2(Metadata *self, // ClassLayoutFlags flags, @@ -1252,7 +1391,8 @@ FUNCTION(InitClassMetadata2, Int8PtrPtrTy->getPointerTo(), SizeTy->getPointerTo()), ATTRS(NoUnwind), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // MetadataDependency swift_updateClassMetadata2(Metadata *self, // ClassLayoutFlags flags, @@ -1266,7 +1406,8 @@ FUNCTION(UpdateClassMetadata2, Int8PtrPtrTy->getPointerTo(), SizeTy->getPointerTo()), ATTRS(NoUnwind), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // void *swift_lookUpClassMethod(Metadata *metadata, // ClassDescriptor *description, @@ -1278,7 +1419,8 @@ FUNCTION(LookUpClassMethod, MethodDescriptorStructTy->getPointerTo(), TypeContextDescriptorPtrTy), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void swift_initStructMetadata(Metadata *structType, // StructLayoutFlags flags, @@ -1292,7 +1434,8 @@ FUNCTION(InitStructMetadata, Int8PtrPtrTy->getPointerTo(0), Int32Ty->getPointerTo()), ATTRS(NoUnwind), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // void swift_initStructMetadataWithLayoutString(Metadata *structType, // StructLayoutFlags flags, @@ -1308,7 +1451,8 @@ FUNCTION(InitStructMetadataWithLayoutString, Int8PtrTy, Int32Ty->getPointerTo()), ATTRS(NoUnwind), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // void swift_initEnumMetadataSingleCase(Metadata *enumType, // EnumLayoutFlags flags, @@ -1319,7 +1463,8 @@ FUNCTION(InitEnumMetadataSingleCase, RETURNS(VoidTy), ARGS(TypeMetadataPtrTy, SizeTy, Int8PtrPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // void swift_initEnumMetadataSingleCaseWithLayoutString(Metadata *enumType, // EnumLayoutFlags flags, @@ -1330,7 +1475,8 @@ FUNCTION(InitEnumMetadataSingleCaseWithLayoutString, RETURNS(VoidTy), ARGS(TypeMetadataPtrTy, SizeTy, TypeMetadataPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // void swift_initEnumMetadataSinglePayload(Metadata *enumType, // EnumLayoutFlags flags, @@ -1342,7 +1488,8 @@ FUNCTION(InitEnumMetadataSinglePayload, RETURNS(VoidTy), ARGS(TypeMetadataPtrTy, SizeTy, Int8PtrPtrTy, Int32Ty), ATTRS(NoUnwind, WillReturn), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // void swift_initEnumMetadataSinglePayloadWithLayoutString(Metadata *enumType, // EnumLayoutFlags flags, @@ -1354,7 +1501,8 @@ FUNCTION(InitEnumMetadataSinglePayloadWithLayoutString, RETURNS(VoidTy), ARGS(TypeMetadataPtrTy, SizeTy, TypeMetadataPtrTy, Int32Ty), ATTRS(NoUnwind, WillReturn), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // void swift_initEnumMetadataMultiPayload(Metadata *enumType, // EnumLayoutFlags layoutFlags, @@ -1366,7 +1514,8 @@ FUNCTION(InitEnumMetadataMultiPayload, RETURNS(VoidTy), ARGS(TypeMetadataPtrTy, SizeTy, SizeTy, Int8PtrPtrTy->getPointerTo(0)), ATTRS(NoUnwind, WillReturn), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // void // swift_initEnumMetadataMultiPayloadWithLayoutString(Metadata *enumType, @@ -1379,7 +1528,8 @@ FUNCTION(InitEnumMetadataMultiPayloadWithLayoutString, RETURNS(VoidTy), ARGS(TypeMetadataPtrTy, SizeTy, SizeTy, TypeMetadataPtrPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // int swift_getEnumCaseMultiPayload(opaque_t *obj, Metadata *enumTy); FUNCTION(GetEnumCaseMultiPayload, @@ -1387,8 +1537,9 @@ FUNCTION(GetEnumCaseMultiPayload, C_CC, AlwaysAvailable, RETURNS(Int32Ty), ARGS(OpaquePtrTy, TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(NoEffect)) + ATTRS(NoUnwind, WillReturn), + EFFECT(NoEffect), + MEMEFFECTS(ReadOnly)) // int swift_getEnumTagSinglePayloadGeneric(opaque_t *obj, // unsigned num_empty_cases, @@ -1404,8 +1555,9 @@ FUNCTION(GetEnumTagSinglePayloadGeneric, llvm::FunctionType::get(Int32Ty, {OpaquePtrTy, Int32Ty, TypeMetadataPtrTy}, false)->getPointerTo()), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(NoEffect)) + ATTRS(NoUnwind, WillReturn), + EFFECT(NoEffect), + MEMEFFECTS(ReadOnly)) // void swift_storeEnumTagSinglePayloadGeneric(opaque_t *obj, @@ -1425,7 +1577,8 @@ FUNCTION(StoreEnumTagSinglePayloadGeneric, TypeMetadataPtrTy}, false)->getPointerTo()), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void swift_storeEnumTagMultiPayload(opaque_t *obj, Metadata *enumTy, // int case_index); @@ -1435,7 +1588,8 @@ FUNCTION(StoreEnumTagMultiPayload, RETURNS(VoidTy), ARGS(OpaquePtrTy, TypeMetadataPtrTy, Int32Ty), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // Class object_getClass(id object); // @@ -1444,82 +1598,94 @@ FUNCTION(StoreEnumTagMultiPayload, FUNCTION(GetObjectClass, object_getClass, C_CC, AlwaysAvailable, RETURNS(ObjCClassPtrTy), ARGS(ObjCPtrTy), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(ObjectiveC)) + ATTRS(NoUnwind, WillReturn), + EFFECT(ObjectiveC), + MEMEFFECTS(ReadOnly)) + // id object_dispose(id object); FUNCTION(ObjectDispose, object_dispose, C_CC, AlwaysAvailable, RETURNS(ObjCPtrTy), ARGS(ObjCPtrTy), ATTRS(NoUnwind), - EFFECT(ObjectiveC, Deallocating)) + EFFECT(ObjectiveC, Deallocating), + UNKNOWN_MEMEFFECTS) // Class objc_lookUpClass(const char *name); FUNCTION(LookUpClass, objc_lookUpClass, C_CC, AlwaysAvailable, RETURNS(ObjCClassPtrTy), ARGS(Int8PtrTy), - ATTRS(NoUnwind, ReadNone, WillReturn), - EFFECT(MetaData)) + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), + MEMEFFECTS(ReadNone)) // Class objc_setSuperclass(Class cls, Class newSuper); FUNCTION(SetSuperclass, class_setSuperclass, C_CC, AlwaysAvailable, RETURNS(ObjCClassPtrTy), ARGS(ObjCClassPtrTy, ObjCClassPtrTy), ATTRS(NoUnwind), - EFFECT(ObjectiveC)) + EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) // Metadata *swift_getObjectType(id object); FUNCTION(GetObjectType, swift_getObjectType, C_CC, AlwaysAvailable, RETURNS(TypeMetadataPtrTy), ARGS(ObjCPtrTy), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(MetaData)) + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) // Metadata *swift_getDynamicType(opaque_t *obj, Metadata *self); FUNCTION(GetDynamicType, swift_getDynamicType, C_CC, AlwaysAvailable, RETURNS(TypeMetadataPtrTy), ARGS(OpaquePtrTy, TypeMetadataPtrTy, Int1Ty), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(MetaData)) + ATTRS(NoUnwind, WillReturn), + EFFECT(MetaData), + MEMEFFECTS(ReadOnly)) // void *swift_dynamicCastClass(void*, void*); FUNCTION(DynamicCastClass, swift_dynamicCastClass, C_CC, AlwaysAvailable, RETURNS(Int8PtrTy), ARGS(Int8PtrTy, Int8PtrTy), - ATTRS(NoUnwind, ReadOnly), - EFFECT(Casting)) + ATTRS(NoUnwind), + EFFECT(Casting), + MEMEFFECTS(ReadOnly)) // void *swift_dynamicCastClassUnconditional(void*, void*); FUNCTION(DynamicCastClassUnconditional, swift_dynamicCastClassUnconditional, C_CC, AlwaysAvailable, RETURNS(Int8PtrTy), ARGS(Int8PtrTy, Int8PtrTy, Int8PtrTy, Int32Ty, Int32Ty), - ATTRS(NoUnwind, ReadOnly), - EFFECT(Casting)) + ATTRS(NoUnwind), + EFFECT(Casting), + MEMEFFECTS(ReadOnly)) // void *swift_dynamicCastObjCClass(void*, void*); FUNCTION(DynamicCastObjCClass, swift_dynamicCastObjCClass, C_CC, AlwaysAvailable, RETURNS(Int8PtrTy), ARGS(Int8PtrTy, Int8PtrTy), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(Casting)) + ATTRS(NoUnwind, WillReturn), + EFFECT(Casting), + MEMEFFECTS(ReadOnly)) // void *swift_dynamicCastObjCClassUnconditional(void*, void*); FUNCTION(DynamicCastObjCClassUnconditional, swift_dynamicCastObjCClassUnconditional, C_CC, AlwaysAvailable, RETURNS(Int8PtrTy), ARGS(Int8PtrTy, Int8PtrTy, Int8PtrTy, Int32Ty, Int32Ty), - ATTRS(NoUnwind, ReadOnly), - EFFECT(Casting)) + ATTRS(NoUnwind), + EFFECT(Casting), + MEMEFFECTS(ReadOnly)) // void *swift_dynamicCastUnknownClass(void*, void*); FUNCTION(DynamicCastUnknownClass, swift_dynamicCastUnknownClass, C_CC, AlwaysAvailable, RETURNS(Int8PtrTy), ARGS(Int8PtrTy, Int8PtrTy), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(Casting)) + ATTRS(NoUnwind, WillReturn), + EFFECT(Casting), + MEMEFFECTS(ReadOnly)) // void *swift_dynamicCastUnknownClassUnconditional(void*, void*); FUNCTION(DynamicCastUnknownClassUnconditional, @@ -1527,16 +1693,18 @@ FUNCTION(DynamicCastUnknownClassUnconditional, C_CC, AlwaysAvailable, RETURNS(Int8PtrTy), ARGS(Int8PtrTy, Int8PtrTy, Int8PtrTy, Int32Ty, Int32Ty), - ATTRS(NoUnwind, ReadOnly), - EFFECT(Casting)) + ATTRS(NoUnwind), + EFFECT(Casting), + MEMEFFECTS(ReadOnly)) // type *swift_dynamicCastMetatype(type*, type*); FUNCTION(DynamicCastMetatype, swift_dynamicCastMetatype, C_CC, AlwaysAvailable, RETURNS(TypeMetadataPtrTy), ARGS(TypeMetadataPtrTy, TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(Casting)) + ATTRS(NoUnwind, WillReturn), + EFFECT(Casting), + MEMEFFECTS(ReadOnly)) // type *swift_dynamicCastMetatypeUnconditional(type*, type*); FUNCTION(DynamicCastMetatypeUnconditional, @@ -1544,16 +1712,18 @@ FUNCTION(DynamicCastMetatypeUnconditional, C_CC, AlwaysAvailable, RETURNS(TypeMetadataPtrTy), ARGS(TypeMetadataPtrTy, TypeMetadataPtrTy, Int8PtrTy, Int32Ty, Int32Ty), - ATTRS(NoUnwind, ReadOnly), - EFFECT(Casting)) + ATTRS(NoUnwind), + EFFECT(Casting), + MEMEFFECTS(ReadOnly)) // objc_class *swift_dynamicCastObjCClassMetatype(objc_class*, objc_class*); FUNCTION(DynamicCastObjCClassMetatype, swift_dynamicCastObjCClassMetatype, C_CC, AlwaysAvailable, RETURNS(ObjCClassPtrTy), ARGS(ObjCClassPtrTy, ObjCClassPtrTy), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(Casting)) + ATTRS(NoUnwind, WillReturn), + EFFECT(Casting), + MEMEFFECTS(ReadOnly)) // objc_class *swift_dynamicCastObjCClassMetatypeUnconditional(objc_class*, objc_class*); FUNCTION(DynamicCastObjCClassMetatypeUnconditional, @@ -1561,8 +1731,9 @@ FUNCTION(DynamicCastObjCClassMetatypeUnconditional, C_CC, AlwaysAvailable, RETURNS(ObjCClassPtrTy), ARGS(ObjCClassPtrTy, ObjCClassPtrTy, Int8PtrTy, Int32Ty, Int32Ty), - ATTRS(NoUnwind, ReadOnly), - EFFECT(Casting)) + ATTRS(NoUnwind), + EFFECT(Casting), + MEMEFFECTS(ReadOnly)) // bool swift_dynamicCast(opaque*, opaque*, type*, type*, size_t); FUNCTION(DynamicCast, swift_dynamicCast, C_CC, AlwaysAvailable, @@ -1570,7 +1741,8 @@ FUNCTION(DynamicCast, swift_dynamicCast, C_CC, AlwaysAvailable, ARGS(OpaquePtrTy, OpaquePtrTy, TypeMetadataPtrTy, TypeMetadataPtrTy, SizeTy), ATTRS(ZExt, NoUnwind), - EFFECT(Casting)) + EFFECT(Casting), + UNKNOWN_MEMEFFECTS) // type* swift_dynamicCastTypeToObjCProtocolUnconditional(type* object, // size_t numProtocols, @@ -1581,7 +1753,8 @@ FUNCTION(DynamicCastTypeToObjCProtocolUnconditional, RETURNS(TypeMetadataPtrTy), ARGS(TypeMetadataPtrTy, SizeTy, Int8PtrPtrTy, Int8PtrTy, Int32Ty, Int32Ty), ATTRS(NoUnwind), - EFFECT(Casting)) + EFFECT(Casting), + UNKNOWN_MEMEFFECTS) // type* swift_dynamicCastTypeToObjCProtocolConditional(type* object, // size_t numProtocols, @@ -1592,7 +1765,8 @@ FUNCTION(DynamicCastTypeToObjCProtocolConditional, RETURNS(TypeMetadataPtrTy), ARGS(TypeMetadataPtrTy, SizeTy, Int8PtrPtrTy), ATTRS(NoUnwind), - EFFECT(Casting)) + EFFECT(Casting), + UNKNOWN_MEMEFFECTS) // id swift_dynamicCastObjCProtocolUnconditional(id object, // size_t numProtocols, @@ -1602,7 +1776,8 @@ FUNCTION(DynamicCastObjCProtocolUnconditional, RETURNS(ObjCPtrTy), ARGS(ObjCPtrTy, SizeTy, Int8PtrPtrTy, Int8PtrTy, Int32Ty, Int32Ty), ATTRS(NoUnwind), - EFFECT(Casting)) + EFFECT(Casting), + UNKNOWN_MEMEFFECTS) // id swift_dynamicCastObjCProtocolConditional(id object, // size_t numProtocols, @@ -1612,55 +1787,62 @@ FUNCTION(DynamicCastObjCProtocolConditional, RETURNS(ObjCPtrTy), ARGS(ObjCPtrTy, SizeTy, Int8PtrPtrTy), ATTRS(NoUnwind), - EFFECT(Casting)) + EFFECT(Casting), + UNKNOWN_MEMEFFECTS) // id swift_dynamicCastMetatypeToObjectUnconditional(type *type); FUNCTION(DynamicCastMetatypeToObjectUnconditional, swift_dynamicCastMetatypeToObjectUnconditional, C_CC, AlwaysAvailable, RETURNS(ObjCPtrTy), ARGS(TypeMetadataPtrTy, Int8PtrTy, Int32Ty, Int32Ty), - ATTRS(NoUnwind, ReadNone), - EFFECT(Casting)) + ATTRS(NoUnwind), + EFFECT(Casting), + MEMEFFECTS(ReadNone)) // id swift_dynamicCastMetatypeToObjectConditional(type *type); FUNCTION(DynamicCastMetatypeToObjectConditional, swift_dynamicCastMetatypeToObjectConditional, C_CC, AlwaysAvailable, RETURNS(ObjCPtrTy), ARGS(TypeMetadataPtrTy), - ATTRS(NoUnwind, ReadNone, WillReturn), - EFFECT(Casting)) + ATTRS(NoUnwind, WillReturn), + EFFECT(Casting), + MEMEFFECTS(ReadNone)) // witness_table* swift_conformsToProtocol(type*, protocol*); FUNCTION(ConformsToProtocol, swift_conformsToProtocol, C_CC, AlwaysAvailable, RETURNS(WitnessTablePtrTy), ARGS(TypeMetadataPtrTy, ProtocolDescriptorPtrTy), - ATTRS(NoUnwind, ReadNone), - EFFECT(Casting)) + ATTRS(NoUnwind), + EFFECT(Casting), + MEMEFFECTS(ReadNone)) // witness_table* swift_conformsToProtocol2(type*, protocol*); FUNCTION(ConformsToProtocol2, swift_conformsToProtocol2, C_CC, SignedConformsToProtocolAvailability, RETURNS(WitnessTablePtrTy), ARGS(TypeMetadataPtrTy, ProtocolDescriptorPtrTy), - ATTRS(NoUnwind, ReadNone), - EFFECT(Casting)) + ATTRS(NoUnwind), + EFFECT(Casting), + MEMEFFECTS(ReadNone)) // bool swift_isClassType(type*); FUNCTION(IsClassType, swift_isClassType, C_CC, AlwaysAvailable, RETURNS(Int1Ty), ARGS(TypeMetadataPtrTy), - ATTRS(ZExt, NoUnwind, ReadNone, WillReturn), - EFFECT(Casting)) + ATTRS(ZExt, NoUnwind, WillReturn), + EFFECT(Casting), + MEMEFFECTS(ReadNone)) // bool swift_isOptionalType(type*); FUNCTION(IsOptionalType, swift_isOptionalType, C_CC, AlwaysAvailable, RETURNS(Int1Ty), ARGS(TypeMetadataPtrTy), - ATTRS(ZExt, NoUnwind, ReadNone, WillReturn), - EFFECT(Casting)) + ATTRS(ZExt, NoUnwind, WillReturn), + EFFECT(Casting), + MEMEFFECTS(ReadNone)) // void swift_once(swift_once_t *predicate, // void (*function_code)(RefCounted*), @@ -1669,7 +1851,8 @@ FUNCTION(Once, swift_once, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(OnceTy->getPointerTo(), Int8PtrTy, Int8PtrTy), ATTRS(NoUnwind), - EFFECT(Locking)) + EFFECT(Locking), + UNKNOWN_MEMEFFECTS) // void swift_registerProtocols(const ProtocolRecord *begin, // const ProtocolRecord *end) @@ -1678,7 +1861,8 @@ FUNCTION(RegisterProtocols, RETURNS(VoidTy), ARGS(ProtocolRecordPtrTy, ProtocolRecordPtrTy), ATTRS(NoUnwind), - EFFECT(Locking)) + EFFECT(Locking), + UNKNOWN_MEMEFFECTS) // void swift_registerProtocolConformances(const ProtocolConformanceRecord *begin, // const ProtocolConformanceRecord *end) @@ -1687,189 +1871,224 @@ FUNCTION(RegisterProtocolConformances, RETURNS(VoidTy), ARGS(RelativeAddressPtrTy, RelativeAddressPtrTy), ATTRS(NoUnwind), - EFFECT(Locking)) + EFFECT(Locking), + UNKNOWN_MEMEFFECTS) FUNCTION(RegisterTypeMetadataRecords, swift_registerTypeMetadataRecords, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(TypeMetadataRecordPtrTy, TypeMetadataRecordPtrTy), ATTRS(NoUnwind), - EFFECT(Locking)) + EFFECT(Locking), + UNKNOWN_MEMEFFECTS) // void swift_beginAccess(void *pointer, ValueBuffer *scratch, size_t flags); FUNCTION(BeginAccess, swift_beginAccess, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(Int8PtrTy, getFixedBufferTy()->getPointerTo(), SizeTy, Int8PtrTy), ATTRS(NoUnwind), - EFFECT(ExclusivityChecking)) + EFFECT(ExclusivityChecking), + UNKNOWN_MEMEFFECTS) // void swift_endAccess(ValueBuffer *scratch); FUNCTION(EndAccess, swift_endAccess, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(getFixedBufferTy()->getPointerTo()), ATTRS(NoUnwind), - EFFECT(ExclusivityChecking)) + EFFECT(ExclusivityChecking), + UNKNOWN_MEMEFFECTS) FUNCTION(GetOrigOfReplaceable, swift_getOrigOfReplaceable, C_CC, DynamicReplacementAvailability, RETURNS(FunctionPtrTy), ARGS(FunctionPtrTy->getPointerTo()), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) FUNCTION(GetReplacement, swift_getFunctionReplacement, C_CC, DynamicReplacementAvailability, RETURNS(FunctionPtrTy), ARGS(FunctionPtrTy->getPointerTo(), FunctionPtrTy), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) FUNCTION(InstantiateObjCClass, swift_instantiateObjCClass, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) FUNCTION(ObjCAllocWithZone, objc_allocWithZone, C_CC, AlwaysAvailable, RETURNS(ObjCPtrTy), ARGS(ObjCClassPtrTy), ATTRS(NoUnwind), - EFFECT(Allocating)) + EFFECT(Allocating), + UNKNOWN_MEMEFFECTS) FUNCTION(ObjCMsgSend, objc_msgSend, C_CC, AlwaysAvailable, - RETURNS(VoidTy), NO_ARGS, NO_ATTRS, EFFECT(ObjectiveC)) + RETURNS(VoidTy), NO_ARGS, NO_ATTRS, EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(ObjCMsgSendStret, objc_msgSend_stret, C_CC, AlwaysAvailable, - RETURNS(VoidTy), NO_ARGS, NO_ATTRS, EFFECT(ObjectiveC)) + RETURNS(VoidTy), NO_ARGS, NO_ATTRS, EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(ObjCMsgSendSuper, objc_msgSendSuper, C_CC, AlwaysAvailable, - RETURNS(VoidTy), NO_ARGS, NO_ATTRS, EFFECT(ObjectiveC)) + RETURNS(VoidTy), NO_ARGS, NO_ATTRS, EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(ObjCMsgSendSuperStret, objc_msgSendSuper_stret, C_CC, AlwaysAvailable, - RETURNS(VoidTy), NO_ARGS, NO_ATTRS, EFFECT(ObjectiveC)) + RETURNS(VoidTy), NO_ARGS, NO_ATTRS, EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(ObjCMsgSendSuper2, objc_msgSendSuper2, C_CC, AlwaysAvailable, - RETURNS(VoidTy), NO_ARGS, NO_ATTRS, EFFECT(ObjectiveC)) + RETURNS(VoidTy), NO_ARGS, NO_ATTRS, EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(ObjCMsgSendSuperStret2, objc_msgSendSuper2_stret, C_CC, AlwaysAvailable, - RETURNS(VoidTy), NO_ARGS, NO_ATTRS, EFFECT(ObjectiveC)) + RETURNS(VoidTy), NO_ARGS, NO_ATTRS, EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(ObjCSelRegisterName, sel_registerName, C_CC, AlwaysAvailable, - RETURNS(ObjCSELTy), ARGS(Int8PtrTy), ATTRS(NoUnwind, ReadNone), - EFFECT(ObjectiveC)) + RETURNS(ObjCSELTy), ARGS(Int8PtrTy), ATTRS(NoUnwind), + EFFECT(ObjectiveC), + MEMEFFECTS(ReadNone)) FUNCTION(ClassReplaceMethod, class_replaceMethod, C_CC, AlwaysAvailable, RETURNS(Int8PtrTy), ARGS(ObjCClassPtrTy, Int8PtrTy, Int8PtrTy, Int8PtrTy), ATTRS(NoUnwind), - EFFECT(ObjectiveC)) + EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(ClassAddProtocol, class_addProtocol, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(ObjCClassPtrTy, Int8PtrTy), ATTRS(NoUnwind), - EFFECT(ObjectiveC)) + EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(ObjCGetClass, objc_getClass, C_CC, AlwaysAvailable, RETURNS(ObjCClassPtrTy), ARGS(Int8PtrTy), ATTRS(NoUnwind), - EFFECT(ObjectiveC)) + EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(ObjCGetRequiredClass, objc_getRequiredClass, C_CC, AlwaysAvailable, RETURNS(ObjCClassPtrTy), ARGS(Int8PtrTy), ATTRS(NoUnwind), - EFFECT(ObjectiveC)) + EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(ObjCGetMetaClass, objc_getMetaClass, C_CC, AlwaysAvailable, RETURNS(ObjCClassPtrTy), ARGS(Int8PtrTy), ATTRS(NoUnwind), - EFFECT(ObjectiveC)) + EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(ObjCClassGetName, class_getName, C_CC, AlwaysAvailable, RETURNS(Int8PtrTy), ARGS(ObjCClassPtrTy), ATTRS(NoUnwind), - EFFECT(ObjectiveC)) + EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(GetObjCProtocol, objc_getProtocol, C_CC, AlwaysAvailable, RETURNS(ProtocolDescriptorPtrTy), ARGS(Int8PtrTy), ATTRS(NoUnwind), - EFFECT(ObjectiveC)) + EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(AllocateObjCProtocol, objc_allocateProtocol, C_CC, AlwaysAvailable, RETURNS(ProtocolDescriptorPtrTy), ARGS(Int8PtrTy), ATTRS(NoUnwind), - EFFECT(ObjectiveC, Allocating)) + EFFECT(ObjectiveC, Allocating), + UNKNOWN_MEMEFFECTS) FUNCTION(RegisterObjCProtocol, objc_registerProtocol, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(ProtocolDescriptorPtrTy), ATTRS(NoUnwind), - EFFECT(ObjectiveC)) + EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(ProtocolAddMethodDescription, protocol_addMethodDescription, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(ProtocolDescriptorPtrTy, Int8PtrTy, Int8PtrTy, ObjCBoolTy, ObjCBoolTy), ATTRS(NoUnwind), - EFFECT(ObjectiveC)) + EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(ProtocolAddProtocol, protocol_addProtocol, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(ProtocolDescriptorPtrTy, ProtocolDescriptorPtrTy), ATTRS(NoUnwind), - EFFECT(ObjectiveC)) + EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(ObjCOptSelf, objc_opt_self, C_CC, AlwaysAvailable, RETURNS(ObjCClassPtrTy), ARGS(ObjCClassPtrTy), ATTRS(NoUnwind), - EFFECT(ObjectiveC)) + EFFECT(ObjectiveC), + UNKNOWN_MEMEFFECTS) FUNCTION(Malloc, malloc, C_CC, AlwaysAvailable, RETURNS(Int8PtrTy), ARGS(SizeTy), NO_ATTRS, - EFFECT(Allocating)) + EFFECT(Allocating), + UNKNOWN_MEMEFFECTS) FUNCTION(Free, free, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(Int8PtrTy), NO_ATTRS, - EFFECT(Deallocating)) + EFFECT(Deallocating), + UNKNOWN_MEMEFFECTS) // void *_Block_copy(void *block); FUNCTION(BlockCopy, _Block_copy, C_CC, AlwaysAvailable, RETURNS(ObjCBlockPtrTy), ARGS(ObjCBlockPtrTy), NO_ATTRS, - EFFECT(RefCounting)) + EFFECT(RefCounting), + UNKNOWN_MEMEFFECTS) // void _Block_release(void *block); FUNCTION(BlockRelease, _Block_release, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(ObjCBlockPtrTy), ATTRS(NoUnwind), - EFFECT(Deallocating, RefCounting)) + EFFECT(Deallocating, RefCounting), + UNKNOWN_MEMEFFECTS) // void swift_deletedMethodError(); FUNCTION(DeletedMethodError, swift_deletedMethodError, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) FUNCTION(AllocError, swift_allocError, SwiftCC, AlwaysAvailable, RETURNS(ErrorPtrTy, OpaquePtrTy), ARGS(TypeMetadataPtrTy, WitnessTablePtrTy, OpaquePtrTy, Int1Ty), ATTRS(NoUnwind), - EFFECT(Allocating)) + EFFECT(Allocating), + UNKNOWN_MEMEFFECTS) FUNCTION(DeallocError, swift_deallocError, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(ErrorPtrTy, TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(Deallocating)) + EFFECT(Deallocating), + UNKNOWN_MEMEFFECTS) FUNCTION(GetErrorValue, swift_getErrorValue, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(ErrorPtrTy, Int8PtrPtrTy, OpenedErrorTriplePtrTy), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void __tsan_external_write(void *addr, void *caller_pc, void *tag); // This is a Thread Sanitizer instrumentation entry point in compiler-rt. @@ -1877,7 +2096,8 @@ FUNCTION(TSanInoutAccess, __tsan_external_write, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(Int8PtrTy, Int8PtrTy, Int8PtrTy), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // int32 __isPlatformVersionAtLeast(uint32_t platform, uint32_t major, // uint32_t minor, uint32_t patch); @@ -1887,26 +2107,30 @@ FUNCTION(PlatformVersionAtLeast, __isPlatformVersionAtLeast, RETURNS(Int32Ty), ARGS(Int32Ty, Int32Ty, Int32Ty, Int32Ty), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) FUNCTION(GetKeyPath, swift_getKeyPath, C_CC, AlwaysAvailable, RETURNS(RefCountedPtrTy), ARGS(Int8PtrTy, Int8PtrTy), ATTRS(NoUnwind), - EFFECT(Allocating)) + EFFECT(Allocating), + UNKNOWN_MEMEFFECTS) FUNCTION(CopyKeyPathTrivialIndices, swift_copyKeyPathTrivialIndices, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(Int8PtrTy, Int8PtrTy, SizeTy), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) FUNCTION(GetInitializedObjCClass, swift_getInitializedObjCClass, C_CC, AlwaysAvailable, RETURNS(ObjCClassPtrTy), ARGS(ObjCClassPtrTy), ATTRS(NoUnwind), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // void swift_objc_swift3ImplicitObjCEntrypoint(id self, SEL selector) FUNCTION(Swift3ImplicitObjCEntrypoint, swift_objc_swift3ImplicitObjCEntrypoint, @@ -1914,26 +2138,31 @@ FUNCTION(Swift3ImplicitObjCEntrypoint, swift_objc_swift3ImplicitObjCEntrypoint, RETURNS(VoidTy), ARGS(ObjCPtrTy, ObjCSELTy, Int8PtrTy, SizeTy, SizeTy, SizeTy, Int8PtrTy), ATTRS(NoUnwind), - EFFECT(ObjectiveC, Allocating)) + EFFECT(ObjectiveC, Allocating), + UNKNOWN_MEMEFFECTS) FUNCTION(VerifyTypeLayoutAttribute, _swift_debug_verifyTypeLayoutAttribute, C_CC, AlwaysAvailable, RETURNS(VoidTy), ARGS(TypeMetadataPtrTy, Int8PtrTy, Int8PtrTy, SizeTy, Int8PtrTy), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // float swift_intToFloat32(const size_t *data, IntegerLiteralFlags flags); FUNCTION(IntToFloat32, swift_intToFloat32, SwiftCC, AlwaysAvailable, RETURNS(FloatTy), ARGS(SizeTy->getPointerTo(), SizeTy), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(NoEffect)) + ATTRS(NoUnwind, WillReturn), + EFFECT(NoEffect), + MEMEFFECTS(ReadOnly)) + FUNCTION(IntToFloat64, swift_intToFloat64, SwiftCC, AlwaysAvailable, RETURNS(DoubleTy), ARGS(SizeTy->getPointerTo(), SizeTy), - ATTRS(NoUnwind, ReadOnly, WillReturn), - EFFECT(NoEffect)) + ATTRS(NoUnwind, WillReturn), + EFFECT(NoEffect), + MEMEFFECTS(ReadOnly)) // const Metadata *swift_getTypeByMangledNameInContext( // const char *typeNameStart, @@ -1944,8 +2173,9 @@ FUNCTION(GetTypeByMangledNameInContext, swift_getTypeByMangledNameInContext, SwiftCC, AlwaysAvailable, RETURNS(TypeMetadataPtrTy), ARGS(Int8PtrTy, SizeTy, TypeContextDescriptorPtrTy, Int8PtrPtrTy), - ATTRS(NoUnwind, ArgMemOnly), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ArgMemOnly)) // const Metadata *swift_getTypeByMangledNameInContext2( // const char *typeNameStart, @@ -1956,8 +2186,9 @@ FUNCTION(GetTypeByMangledNameInContext2, swift_getTypeByMangledNameInContext2, SwiftCC, SignedDescriptorAvailability, RETURNS(TypeMetadataPtrTy), ARGS(Int8PtrTy, SizeTy, TypeContextDescriptorPtrTy, Int8PtrPtrTy), - ATTRS(NoUnwind, ArgMemOnly), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ArgMemOnly)) // const Metadata *swift_getTypeByMangledNameInContextInMetadataState( // size_t metadataState, @@ -1971,8 +2202,9 @@ FUNCTION(GetTypeByMangledNameInContextInMetadataState, RETURNS(TypeMetadataPtrTy), ARGS(SizeTy, Int8PtrTy, SizeTy, TypeContextDescriptorPtrTy, Int8PtrPtrTy), - ATTRS(NoUnwind, ArgMemOnly), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ArgMemOnly)) // const Metadata *swift_getTypeByMangledNameInContextInMetadataState2( // size_t metadataState, @@ -1986,8 +2218,9 @@ FUNCTION(GetTypeByMangledNameInContextInMetadataState2, RETURNS(TypeMetadataPtrTy), ARGS(SizeTy, Int8PtrTy, SizeTy, TypeContextDescriptorPtrTy, Int8PtrPtrTy), - ATTRS(NoUnwind, ArgMemOnly), - EFFECT(MetaData)) + ATTRS(NoUnwind), + EFFECT(MetaData), + MEMEFFECTS(ArgMemOnly)) // AsyncTask *swift_task_getCurrent();s FUNCTION(GetCurrentTask, @@ -1995,8 +2228,9 @@ FUNCTION(GetCurrentTask, ConcurrencyAvailability, RETURNS(SwiftTaskPtrTy), ARGS(), - ATTRS(NoUnwind, ReadNone, WillReturn), - EFFECT(Concurrency)) + ATTRS(NoUnwind, WillReturn), + EFFECT(Concurrency), + MEMEFFECTS(ReadNone)) // void *swift_task_alloc(size_t size); FUNCTION(TaskAlloc, @@ -2004,8 +2238,9 @@ FUNCTION(TaskAlloc, ConcurrencyAvailability, RETURNS(Int8PtrTy), ARGS(SizeTy), - ATTRS(NoUnwind, ArgMemOnly), - EFFECT(Concurrency)) + ATTRS(NoUnwind), + EFFECT(Concurrency), + MEMEFFECTS(ArgMemOnly)) // void swift_task_dealloc(void *ptr); FUNCTION(TaskDealloc, @@ -2013,8 +2248,9 @@ FUNCTION(TaskDealloc, ConcurrencyAvailability, RETURNS(VoidTy), ARGS(Int8PtrTy), - ATTRS(NoUnwind, ArgMemOnly), - EFFECT(Concurrency)) + ATTRS(NoUnwind), + EFFECT(Concurrency), + MEMEFFECTS(ArgMemOnly)) // void swift_task_cancel(AsyncTask *task); FUNCTION(TaskCancel, @@ -2022,8 +2258,9 @@ FUNCTION(TaskCancel, ConcurrencyAvailability, RETURNS(VoidTy), ARGS(SwiftTaskPtrTy), - ATTRS(NoUnwind, ArgMemOnly), - EFFECT(Concurrency)) + ATTRS(NoUnwind), + EFFECT(Concurrency), + MEMEFFECTS(ArgMemOnly)) // AsyncTaskAndContext swift_task_create( // size_t taskCreateFlags, @@ -2039,8 +2276,9 @@ FUNCTION(TaskCreate, TypeMetadataPtrTy, Int8PtrTy, RefCountedPtrTy), - ATTRS(NoUnwind, ArgMemOnly), - EFFECT(Concurrency)) + ATTRS(NoUnwind), + EFFECT(Concurrency), + MEMEFFECTS(ArgMemOnly)) // void swift_task_switch(AsyncContext *resumeContext, // TaskContinuationFunction *resumeFunction, @@ -2051,7 +2289,8 @@ FUNCTION(TaskSwitchFunc, RETURNS(VoidTy), ARGS(SwiftContextPtrTy, Int8PtrTy, ExecutorFirstTy, ExecutorSecondTy), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) // AsyncTask *swift_continuation_init(AsyncContext *continuationContext, // AsyncContinuationFlags); @@ -2061,7 +2300,8 @@ FUNCTION(ContinuationInit, RETURNS(SwiftTaskPtrTy), ARGS(ContinuationAsyncContextPtrTy, SizeTy), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) // void swift_continuation_await(AsyncContext *continuationContext); FUNCTION(ContinuationAwait, @@ -2070,7 +2310,8 @@ FUNCTION(ContinuationAwait, RETURNS(VoidTy), ARGS(ContinuationAsyncContextPtrTy), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) // void swift_continuation_resume(AsyncTask *continuation); FUNCTION(ContinuationResume, @@ -2079,7 +2320,8 @@ FUNCTION(ContinuationResume, RETURNS(VoidTy), ARGS(SwiftTaskPtrTy), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) // void swift_continuation_throwingResume(AsyncTask *continuation); FUNCTION(ContinuationThrowingResume, @@ -2088,7 +2330,8 @@ FUNCTION(ContinuationThrowingResume, RETURNS(VoidTy), ARGS(SwiftTaskPtrTy), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) // void swift_continuation_throwingResumeWithError(AsyncTask *continuation, // SwiftError *error); @@ -2098,7 +2341,8 @@ FUNCTION(ContinuationThrowingResumeWithError, RETURNS(VoidTy), ARGS(SwiftTaskPtrTy, ErrorPtrTy), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) // ExecutorRef swift_task_getCurrentExecutor(); FUNCTION(TaskGetCurrentExecutor, @@ -2106,8 +2350,9 @@ FUNCTION(TaskGetCurrentExecutor, ConcurrencyAvailability, RETURNS(SwiftExecutorTy), ARGS(), - ATTRS(NoUnwind, ArgMemOnly, WillReturn), - EFFECT(Concurrency)) + ATTRS(NoUnwind, WillReturn), + EFFECT(Concurrency), + MEMEFFECTS(ArgMemOnly)) // ExecutorRef swift_task_getMainExecutor(); FUNCTION(TaskGetMainExecutor, @@ -2115,8 +2360,9 @@ FUNCTION(TaskGetMainExecutor, ConcurrencyAvailability, RETURNS(SwiftExecutorTy), ARGS(), - ATTRS(NoUnwind, ArgMemOnly, WillReturn), - EFFECT(Concurrency)) + ATTRS(NoUnwind, WillReturn), + EFFECT(Concurrency), + MEMEFFECTS(ArgMemOnly)) // void swift_defaultActor_initialize(DefaultActor *actor); FUNCTION(DefaultActorInitialize, @@ -2125,7 +2371,8 @@ FUNCTION(DefaultActorInitialize, RETURNS(VoidTy), ARGS(RefCountedPtrTy), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) // void swift_defaultActor_destroy(DefaultActor *actor); FUNCTION(DefaultActorDestroy, @@ -2134,7 +2381,8 @@ FUNCTION(DefaultActorDestroy, RETURNS(VoidTy), ARGS(RefCountedPtrTy), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) // void swift_defaultActor_deallocate(DefaultActor *actor); FUNCTION(DefaultActorDeallocate, @@ -2143,7 +2391,8 @@ FUNCTION(DefaultActorDeallocate, RETURNS(VoidTy), ARGS(RefCountedPtrTy), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) // void swift_defaultActor_deallocateResilient(HeapObject *actor); FUNCTION(DefaultActorDeallocateResilient, @@ -2152,7 +2401,8 @@ FUNCTION(DefaultActorDeallocateResilient, RETURNS(VoidTy), ARGS(RefCountedPtrTy), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) // void swift_nonDefaultDistributedActor_initialize(NonDefaultDistributedActor *actor); FUNCTION(NonDefaultDistributedActorInitialize, @@ -2161,7 +2411,8 @@ FUNCTION(NonDefaultDistributedActorInitialize, RETURNS(VoidTy), ARGS(RefCountedPtrTy), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) // OpaqueValue* swift_distributedActor_remote_initialize( // const Metadata *actorType @@ -2172,7 +2423,8 @@ FUNCTION(DistributedActorInitializeRemote, RETURNS(OpaquePtrTy), ARGS(TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) /// void swift_asyncLet_start( /// AsyncLet *alet, @@ -2191,8 +2443,9 @@ FUNCTION(AsyncLetStart, Int8PtrTy, // closureEntry OpaquePtrTy // closureContext ), - ATTRS(NoUnwind, ArgMemOnly), - EFFECT(Concurrency)) + ATTRS(NoUnwind), + EFFECT(Concurrency), + MEMEFFECTS(ArgMemOnly)) /// void swift_asyncLet_begin( /// AsyncLet *alet, @@ -2213,8 +2466,9 @@ FUNCTION(AsyncLetBegin, OpaquePtrTy, // closureContext Int8PtrTy ), - ATTRS(NoUnwind, ArgMemOnly), - EFFECT(Concurrency)) + ATTRS(NoUnwind), + EFFECT(Concurrency), + MEMEFFECTS(ArgMemOnly)) // void swift_asyncLet_end(AsyncLet *alet); FUNCTION(EndAsyncLet, @@ -2223,7 +2477,8 @@ FUNCTION(EndAsyncLet, RETURNS(VoidTy), ARGS(SwiftAsyncLetPtrTy), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) /// void swift_task_run_inline( /// OpaqueValue *result, @@ -2241,7 +2496,8 @@ FUNCTION(TaskRunInline, TypeMetadataPtrTy, // const Metadata *futureResultType ), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void swift_taskGroup_initialize(TaskGroup *group); FUNCTION(TaskGroupInitialize, @@ -2250,7 +2506,8 @@ FUNCTION(TaskGroupInitialize, RETURNS(VoidTy), ARGS(Int8PtrTy, TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) // void swift_taskGroup_initializeWithFlags(size_t flags, TaskGroup *group); FUNCTION(TaskGroupInitializeWithFlags, @@ -2262,7 +2519,8 @@ FUNCTION(TaskGroupInitializeWithFlags, TypeMetadataPtrTy // T.Type ), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) // void swift_taskGroup_destroy(TaskGroup *group); FUNCTION(TaskGroupDestroy, @@ -2271,7 +2529,8 @@ FUNCTION(TaskGroupDestroy, RETURNS(VoidTy), ARGS(Int8PtrTy), ATTRS(NoUnwind), - EFFECT(Concurrency)) + EFFECT(Concurrency), + UNKNOWN_MEMEFFECTS) // AutoDiffLinearMapContext *swift_autoDiffCreateLinearMapContextWithType(const Metadata *); FUNCTION(AutoDiffCreateLinearMapContextWithType, @@ -2279,8 +2538,9 @@ FUNCTION(AutoDiffCreateLinearMapContextWithType, DifferentiationAvailability, RETURNS(RefCountedPtrTy), ARGS(TypeMetadataPtrTy), - ATTRS(NoUnwind, ArgMemOnly), - EFFECT(AutoDiff)) + ATTRS(NoUnwind), + EFFECT(AutoDiff), + MEMEFFECTS(ArgMemOnly)) // void *swift_autoDiffProjectTopLevelSubcontext(AutoDiffLinearMapContext *); FUNCTION(AutoDiffProjectTopLevelSubcontext, @@ -2288,8 +2548,9 @@ FUNCTION(AutoDiffProjectTopLevelSubcontext, DifferentiationAvailability, RETURNS(Int8PtrTy), ARGS(RefCountedPtrTy), - ATTRS(NoUnwind, ArgMemOnly), - EFFECT(AutoDiff)) + ATTRS(NoUnwind), + EFFECT(AutoDiff), + MEMEFFECTS(ArgMemOnly)) // void *swift_autoDiffAllocateSubcontextWithType(AutoDiffLinearMapContext *, const Metadata *); FUNCTION(AutoDiffAllocateSubcontextWithType, @@ -2297,8 +2558,9 @@ FUNCTION(AutoDiffAllocateSubcontextWithType, DifferentiationAvailability, RETURNS(Int8PtrTy), ARGS(RefCountedPtrTy, TypeMetadataPtrTy), - ATTRS(NoUnwind, ArgMemOnly), - EFFECT(AutoDiff)) + ATTRS(NoUnwind), + EFFECT(AutoDiff), + MEMEFFECTS(ArgMemOnly)) // SWIFT_RUNTIME_EXPORT // unsigned swift_getMultiPayloadEnumTagSinglePayload(const OpaqueValue *value, @@ -2310,7 +2572,8 @@ FUNCTION(GetMultiPayloadEnumTagSinglePayload, RETURNS(Int32Ty), ARGS(OpaquePtrTy, Int32Ty, TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // SWIFT_RUNTIME_EXPORT // void swift_storeMultiPayloadEnumTagSinglePayload(OpaqueValue *value, @@ -2323,7 +2586,8 @@ FUNCTION(StoreMultiPayloadEnumTagSinglePayload, RETURNS(VoidTy), ARGS(OpaquePtrTy, Int32Ty, Int32Ty, TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void swift_generic_destroy(opaque*, const Metadata* type); FUNCTION(GenericDestroy, @@ -2332,7 +2596,8 @@ FUNCTION(GenericDestroy, RETURNS(VoidTy), ARGS(Int8PtrTy, TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(Deallocating)) + EFFECT(Deallocating), + UNKNOWN_MEMEFFECTS) // void *swift_generic_assignWithCopy(opaque* dest, opaque* src, const Metadata* type); @@ -2342,7 +2607,8 @@ FUNCTION(GenericAssignWithCopy, RETURNS(Int8PtrTy), ARGS(Int8PtrTy, Int8PtrTy, TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(Refcounting, Deallocating)) + EFFECT(Refcounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void *swift_generic_assignWithTake(opaque* dest, opaque* src, const Metadata* type); FUNCTION(GenericAssignWithTake, @@ -2351,7 +2617,8 @@ FUNCTION(GenericAssignWithTake, RETURNS(Int8PtrTy), ARGS(Int8PtrTy, Int8PtrTy, TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(Refcounting, Deallocating)) + EFFECT(Refcounting, Deallocating), + UNKNOWN_MEMEFFECTS) // void *swift_generic_initWithCopy(opaque* dest, opaque* src, const Metadata* type); FUNCTION(GenericInitWithCopy, @@ -2360,7 +2627,8 @@ FUNCTION(GenericInitWithCopy, RETURNS(Int8PtrTy), ARGS(Int8PtrTy, Int8PtrTy, TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(Refcounting)) + EFFECT(Refcounting), + UNKNOWN_MEMEFFECTS) // void *swift_generic_initWithTake(opaque* dest, opaque* src, const Metadata* type); FUNCTION(GenericInitWithTake, @@ -2369,7 +2637,8 @@ FUNCTION(GenericInitWithTake, RETURNS(Int8PtrTy), ARGS(Int8PtrTy, Int8PtrTy, TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(Refcounting)) + EFFECT(Refcounting), + UNKNOWN_MEMEFFECTS) // void *swift_generic_initializeBufferWithCopyOfBuffer(ValueBuffer* dest, ValueBuffer* src, const Metadata* type); FUNCTION(GenericInitializeBufferWithCopyOfBuffer, @@ -2380,7 +2649,8 @@ FUNCTION(GenericInitializeBufferWithCopyOfBuffer, getFixedBufferTy()->getPointerTo(), TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(Refcounting)) + EFFECT(Refcounting), + UNKNOWN_MEMEFFECTS) // unsigned swift_singletonEnum_getEnumTag(swift::OpaqueValue *address, // const Metadata *metadata); @@ -2390,7 +2660,8 @@ FUNCTION(SingletonEnumGetEnumTag, RETURNS(Int32Ty), ARGS(Int8PtrTy, TypeMetadataPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void swift_singletonEnum_destructiveInjectEnumTag(swift::OpaqueValue *address, // unsigned tag, @@ -2401,7 +2672,8 @@ FUNCTION(SingletonEnumDestructiveInjectEnumTag, RETURNS(VoidTy), ARGS(Int8PtrTy, Int32Ty, TypeMetadataPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // unsigned swift_enumSimple_getEnumTag(swift::OpaqueValue *address, // const Metadata *metadata); @@ -2411,7 +2683,8 @@ FUNCTION(EnumSimpleGetEnumTag, RETURNS(Int32Ty), ARGS(Int8PtrTy, TypeMetadataPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // unsigned swift_enumSimple_destructiveInjectEnumTag(swift::OpaqueValue *address, // unsigned tag, @@ -2422,7 +2695,8 @@ FUNCTION(EnumSimpleDestructiveInjectEnumTag, RETURNS(VoidTy), ARGS(Int8PtrTy, Int32Ty, TypeMetadataPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // unsigned swift_enumFn_getEnumTag(swift::OpaqueValue *address, // const Metadata *metadata); @@ -2432,7 +2706,8 @@ FUNCTION(EnumFnGetEnumTag, RETURNS(Int32Ty), ARGS(Int8PtrTy, TypeMetadataPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // unsigned swift_multiPayloadEnumGeneric_getEnumTag(opaque* address, // const Metadata *type); @@ -2442,7 +2717,8 @@ FUNCTION(MultiPayloadEnumGenericGetEnumTag, RETURNS(Int32Ty), ARGS(Int8PtrTy, TypeMetadataPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void swift_multiPayloadEnumGeneric_destructiveInjectEnumTag(swift::OpaqueValue *address, // unsigned tag, @@ -2453,7 +2729,8 @@ FUNCTION(MultiPayloadEnumGenericDestructiveInjectEnumTag, RETURNS(VoidTy), ARGS(Int8PtrTy, Int32Ty, TypeMetadataPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // unsigned swift_singlePayloadEnumGeneric_getEnumTag(swift::OpaqueValue *address, // const Metadata *metadata); @@ -2463,7 +2740,8 @@ FUNCTION(SinglePayloadEnumGenericGetEnumTag, RETURNS(Int32Ty), ARGS(Int8PtrTy, TypeMetadataPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void swift_singlePayloadEnumGeneric_destructiveInjectEnumTag(swift::OpaqueValue *address, // unsigned tag, @@ -2474,7 +2752,8 @@ FUNCTION(SinglePayloadEnumGenericDestructiveInjectEnumTag, RETURNS(VoidTy), ARGS(Int8PtrTy, Int32Ty, TypeMetadataPtrTy), ATTRS(NoUnwind, WillReturn), - EFFECT(NoEffect)) + EFFECT(NoEffect), + UNKNOWN_MEMEFFECTS) // void swift_generic_instantiateLayoutString(const uint8_t* layoutStr, // Metadata* type); @@ -2484,7 +2763,8 @@ FUNCTION(GenericInstantiateLayoutString, RETURNS(VoidTy), ARGS(Int8PtrTy, TypeMetadataPtrTy), ATTRS(NoUnwind), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) // void swift_initRawStructMetadata(Metadata *structType, // StructLayoutFlags flags, @@ -2496,7 +2776,8 @@ FUNCTION(InitRawStructMetadata, RETURNS(VoidTy), ARGS(TypeMetadataPtrTy, SizeTy, Int8PtrPtrTy->getPointerTo(0), Int32Ty), ATTRS(NoUnwind), - EFFECT(MetaData)) + EFFECT(MetaData), + UNKNOWN_MEMEFFECTS) #undef RETURNS #undef ARGS diff --git a/include/swift/SIL/PrunedLiveness.h b/include/swift/SIL/PrunedLiveness.h index 687e0cedd4b..b977d2f6edc 100644 --- a/include/swift/SIL/PrunedLiveness.h +++ b/include/swift/SIL/PrunedLiveness.h @@ -863,13 +863,13 @@ class DiagnosticPrunedLiveness : public SSAPrunedLiveness { /// A side array that stores any non lifetime ending uses we find in live out /// blocks. This is used to enable our callers to emit errors on non-lifetime /// ending uses that extend liveness into a loop body. - SmallSetVector *nonLifetimeEndingUsesInLiveOut; + llvm::SmallSetVector *nonLifetimeEndingUsesInLiveOut; public: DiagnosticPrunedLiveness( SILFunction *function, SmallVectorImpl *discoveredBlocks = nullptr, - SmallSetVector *nonLifetimeEndingUsesInLiveOut = + llvm::SmallSetVector *nonLifetimeEndingUsesInLiveOut = nullptr) : SSAPrunedLiveness(function, discoveredBlocks), nonLifetimeEndingUsesInLiveOut(nonLifetimeEndingUsesInLiveOut) {} diff --git a/include/swift/SIL/SILBuilder.h b/include/swift/SIL/SILBuilder.h index a03154895fa..2481926ec91 100644 --- a/include/swift/SIL/SILBuilder.h +++ b/include/swift/SIL/SILBuilder.h @@ -396,20 +396,7 @@ public: llvm::Optional substituteAnonymousArgs(llvm::SmallString<4> Name, llvm::Optional Var, - SILLocation Loc) { - if (Var && shouldDropVariable(*Var, Loc)) - return {}; - if (!Var || !Var->ArgNo || !Var->Name.empty()) - return Var; - - auto *VD = Loc.getAsASTNode(); - if (VD && !VD->getName().empty()) - return Var; - - llvm::raw_svector_ostream(Name) << '_' << (Var->ArgNo - 1); - Var->Name = Name; - return Var; - } + SILLocation Loc); AllocStackInst * createAllocStack(SILLocation Loc, SILType elementType, diff --git a/include/swift/SIL/SILFunction.h b/include/swift/SIL/SILFunction.h index 2dae88bc26b..b62e664728d 100644 --- a/include/swift/SIL/SILFunction.h +++ b/include/swift/SIL/SILFunction.h @@ -870,6 +870,10 @@ public: /// current SILModule. bool isPossiblyUsedExternally() const; + /// Helper method which returns whether this function should be preserved so + /// it can potentially be used in the debugger. + bool shouldBePreservedForDebugger() const; + /// In addition to isPossiblyUsedExternally() it returns also true if this /// is a (private or internal) vtable method which can be referenced by /// vtables of derived classes outside the compilation unit. diff --git a/include/swift/SILOptimizer/Analysis/LoopRegionAnalysis.h b/include/swift/SILOptimizer/Analysis/LoopRegionAnalysis.h index 945469dc760..d5eb30cbffd 100644 --- a/include/swift/SILOptimizer/Analysis/LoopRegionAnalysis.h +++ b/include/swift/SILOptimizer/Analysis/LoopRegionAnalysis.h @@ -219,7 +219,7 @@ public: return llvm::None; if ((*ID).IsNonLocal) return llvm::None; - return (*ID).ID; + return static_cast((*ID).ID); } }; @@ -230,7 +230,7 @@ public: return llvm::None; if (!(*ID).IsNonLocal) return llvm::None; - return (*ID).ID; + return static_cast((*ID).ID); } }; }; diff --git a/include/swift/SILOptimizer/Analysis/Reachability.h b/include/swift/SILOptimizer/Analysis/Reachability.h index 178805525a1..89432bf1953 100644 --- a/include/swift/SILOptimizer/Analysis/Reachability.h +++ b/include/swift/SILOptimizer/Analysis/Reachability.h @@ -247,7 +247,7 @@ public: /// reachability may extend. BasicBlockSetVector discoveredBlocks; /// The sublist of gens which are killed within the blocks where they occur. - SmallSetVector localGens; + llvm::SmallSetVector localGens; /// Construct a result for running IterativeBackwardReachability in a given /// function. diff --git a/include/swift/SILOptimizer/PassManager/PassManager.h b/include/swift/SILOptimizer/PassManager/PassManager.h index 5909b5444d9..43e188c8008 100644 --- a/include/swift/SILOptimizer/PassManager/PassManager.h +++ b/include/swift/SILOptimizer/PassManager/PassManager.h @@ -24,6 +24,7 @@ #include "llvm/Support/Chrono.h" #include "llvm/Support/ErrorHandling.h" #include +#include #ifndef SWIFT_SILOPTIMIZER_PASSMANAGER_PASSMANAGER_H #define SWIFT_SILOPTIMIZER_PASSMANAGER_PASSMANAGER_H diff --git a/include/swift/SILOptimizer/Utils/BasicBlockOptUtils.h b/include/swift/SILOptimizer/Utils/BasicBlockOptUtils.h index 1ae6d8ebd35..e14387c8883 100644 --- a/include/swift/SILOptimizer/Utils/BasicBlockOptUtils.h +++ b/include/swift/SILOptimizer/Utils/BasicBlockOptUtils.h @@ -138,7 +138,7 @@ class SinkAddressProjections { SmallVector oldProjections; // Cloned projections to avoid address phis. SmallVectorImpl *newProjections; - SmallSetVector inBlockDefs; + llvm::SmallSetVector inBlockDefs; // Transient per-projection data for use during cloning. SmallVector usesToReplace; diff --git a/include/swift/SILOptimizer/Utils/CanonicalizeOSSALifetime.h b/include/swift/SILOptimizer/Utils/CanonicalizeOSSALifetime.h index be895652447..fff173625d9 100644 --- a/include/swift/SILOptimizer/Utils/CanonicalizeOSSALifetime.h +++ b/include/swift/SILOptimizer/Utils/CanonicalizeOSSALifetime.h @@ -256,7 +256,7 @@ private: /// /// These blocks are not necessarily in the pruned live blocks since /// pruned liveness does not consider destroy_values. - SmallSetVector consumingBlocks; + llvm::SmallSetVector consumingBlocks; /// Record all interesting debug_value instructions here rather then treating /// them like a normal use. An interesting debug_value is one that may lie diff --git a/include/swift/SILOptimizer/Utils/InstructionDeleter.h b/include/swift/SILOptimizer/Utils/InstructionDeleter.h index 86dfd15c4b6..d758c012741 100644 --- a/include/swift/SILOptimizer/Utils/InstructionDeleter.h +++ b/include/swift/SILOptimizer/Utils/InstructionDeleter.h @@ -114,7 +114,7 @@ class InstructionDeleter { /// instructions in this set is important as when a dead instruction is /// removed, new instructions will be generated to fix the lifetime of the /// instruction's operands. This has to be deterministic. - SmallSetVector deadInstructions; + llvm::SmallSetVector deadInstructions; /// Callbacks used when adding/deleting instructions. InstModCallbacks callbacks; diff --git a/include/swift/Sema/CSBindings.h b/include/swift/Sema/CSBindings.h index 8eae86f44cb..419134d11f1 100644 --- a/include/swift/Sema/CSBindings.h +++ b/include/swift/Sema/CSBindings.h @@ -23,6 +23,7 @@ #include "swift/AST/Types.h" #include "swift/Basic/Debug.h" #include "swift/Basic/LLVM.h" +#include "swift/Basic/LLVMExtras.h" #include "swift/Sema/Constraint.h" #include "swift/Sema/ConstraintLocator.h" #include "llvm/ADT/APInt.h" @@ -298,6 +299,69 @@ public: void retract(Constraint *constraint); }; + +} // end namespace inference + +} // end namespace constraints + +} // end namespace swift + +namespace llvm { + +template <> +struct DenseMapInfo { + using Binding = swift::constraints::inference::PotentialBinding; + + static Binding getEmptyKey() { + return placeholderKey(llvm::DenseMapInfo::getEmptyKey()); + } + + static Binding getTombstoneKey() { + return placeholderKey( + llvm::DenseMapInfo::getTombstoneKey()); + } + + static unsigned getHashValue(const Binding &Val) { + return DenseMapInfo::getHashValue( + Val.BindingType->getCanonicalType()); + } + + static bool isEqual(const Binding &LHS, const Binding &RHS) { + auto lhsTy = LHS.BindingType.getPointer(); + auto rhsTy = RHS.BindingType.getPointer(); + + // Fast path: pointer equality. + if (DenseMapInfo::isEqual(lhsTy, rhsTy)) + return true; + + // If either side is empty or tombstone, let's use pointer equality. + { + auto emptyTy = llvm::DenseMapInfo::getEmptyKey(); + auto tombstoneTy = + llvm::DenseMapInfo::getTombstoneKey(); + + if (lhsTy == emptyTy || lhsTy == tombstoneTy) + return lhsTy == rhsTy; + + if (rhsTy == emptyTy || rhsTy == tombstoneTy) + return lhsTy == rhsTy; + } + + // Otherwise let's drop the sugar and check. + return LHS.BindingType->isEqual(RHS.BindingType); + } + +private: + static Binding placeholderKey(swift::Type type) { + return Binding::forPlaceholder(type); + } +}; + +} // end namespace llvm + +namespace swift { +namespace constraints { +namespace inference { class BindingSet { using BindingScore = std::tuple; @@ -311,7 +375,7 @@ class BindingSet { llvm::SmallPtrSet AdjacentVars; public: - llvm::SmallSetVector Bindings; + swift::SmallSetVector Bindings; llvm::SmallMapVector Literals; llvm::SmallDenseMap Defaults; @@ -473,7 +537,8 @@ public: void forEachLiteralRequirement( llvm::function_ref callback) const; - /// Return a literal requirement that has the most impact on the binding score. + /// Return a literal requirement that has the most impact on the binding + /// score. LiteralBindingKind getLiteralForScore() const; /// Check if this binding is favored over a disjunction e.g. @@ -563,77 +628,22 @@ private: /// Check whether the given binding set covers any of the /// literal protocols associated with this type variable. void determineLiteralCoverage(); - + StringRef getLiteralBindingKind(LiteralBindingKind K) const { - #define ENTRY(Kind, String) case LiteralBindingKind::Kind: return String +#define ENTRY(Kind, String) \ + case LiteralBindingKind::Kind: \ + return String switch (K) { - ENTRY(None, "none"); - ENTRY(Collection, "collection"); - ENTRY(Float, "float"); - ENTRY(Atom, "atom"); + ENTRY(None, "none"); + ENTRY(Collection, "collection"); + ENTRY(Float, "float"); + ENTRY(Atom, "atom"); } - #undef ENTRY - } - -}; - -} // end namespace inference - -} // end namespace constraints - -} // end namespace swift - -namespace llvm { - -template <> -struct DenseMapInfo { - using Binding = swift::constraints::inference::PotentialBinding; - - static Binding getEmptyKey() { - return placeholderKey(llvm::DenseMapInfo::getEmptyKey()); - } - - static Binding getTombstoneKey() { - return placeholderKey( - llvm::DenseMapInfo::getTombstoneKey()); - } - - static unsigned getHashValue(const Binding &Val) { - return DenseMapInfo::getHashValue( - Val.BindingType->getCanonicalType()); - } - - static bool isEqual(const Binding &LHS, const Binding &RHS) { - auto lhsTy = LHS.BindingType.getPointer(); - auto rhsTy = RHS.BindingType.getPointer(); - - // Fast path: pointer equality. - if (DenseMapInfo::isEqual(lhsTy, rhsTy)) - return true; - - // If either side is empty or tombstone, let's use pointer equality. - { - auto emptyTy = llvm::DenseMapInfo::getEmptyKey(); - auto tombstoneTy = - llvm::DenseMapInfo::getTombstoneKey(); - - if (lhsTy == emptyTy || lhsTy == tombstoneTy) - return lhsTy == rhsTy; - - if (rhsTy == emptyTy || rhsTy == tombstoneTy) - return lhsTy == rhsTy; - } - - // Otherwise let's drop the sugar and check. - return LHS.BindingType->isEqual(RHS.BindingType); - } - -private: - static Binding placeholderKey(swift::Type type) { - return Binding::forPlaceholder(type); +#undef ENTRY } }; - -} // end namespace llvm +} // namespace inference +} // namespace constraints +} // namespace swift #endif // SWIFT_SEMA_CSBINDINGS_H diff --git a/include/swift/Subsystems.h b/include/swift/Subsystems.h index 2ce46a717e7..86f742d0515 100644 --- a/include/swift/Subsystems.h +++ b/include/swift/Subsystems.h @@ -263,7 +263,8 @@ namespace swift { const IRGenOptions &opts, UnifiedStatsReporter *stats, DiagnosticEngine &diags, llvm::raw_pwrite_stream &out, - llvm::sys::Mutex *diagMutex = nullptr); + llvm::sys::Mutex *diagMutex = nullptr, + llvm::raw_pwrite_stream *casid = nullptr); /// Wrap a serialized module inside a swift AST section in an object file. void createSwiftModuleObjectFile(SILModule &SILMod, StringRef Buffer, diff --git a/include/swift/SymbolGraphGen/SymbolGraphOptions.h b/include/swift/SymbolGraphGen/SymbolGraphOptions.h index c611ffdbfcd..783860fdc1b 100644 --- a/include/swift/SymbolGraphGen/SymbolGraphOptions.h +++ b/include/swift/SymbolGraphGen/SymbolGraphOptions.h @@ -10,7 +10,7 @@ // //===----------------------------------------------------------------------===// -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "swift/AST/AttrKind.h" #ifndef SWIFT_SYMBOLGRAPHGEN_SYMBOLGRAPHOPTIONS_H diff --git a/lib/AST/AccessRequests.cpp b/lib/AST/AccessRequests.cpp index 2ed13f3370e..873fe7b5678 100644 --- a/lib/AST/AccessRequests.cpp +++ b/lib/AST/AccessRequests.cpp @@ -20,7 +20,9 @@ #include "swift/AST/SourceFile.h" #include "swift/AST/Types.h" -#include "llvm/Support/MathExtras.h" +#include "llvm/ADT/bit.h" + +#include using namespace swift; @@ -329,8 +331,15 @@ DefaultAndMaxAccessLevelRequest::getCachedResult() const { if (extensionDecl->hasDefaultAccessLevel()) { uint8_t Bits = extensionDecl->getDefaultAndMaxAccessLevelBits(); assert(Bits != 0x7 && "more than two bits set for Default and Max"); - AccessLevel Max = static_cast(llvm::findLastSet(Bits) + 1); - AccessLevel Default = static_cast(llvm::findFirstSet(Bits) + 1); + + uint8_t lastSet = Bits == 0 ? std::numeric_limits::max() + : (llvm::countl_zero(Bits) ^ + (std::numeric_limits::digits - 1)); + uint8_t firstSet = Bits == 0 ? std::numeric_limits::max() + : llvm::countr_zero(Bits); + AccessLevel Max = static_cast(lastSet + 1); + AccessLevel Default = static_cast(firstSet + 1); + assert(Max >= Default); return std::make_pair(Default, Max); } diff --git a/lib/AST/Builtins.cpp b/lib/AST/Builtins.cpp index aaed1cc2109..4bb87a294e6 100644 --- a/lib/AST/Builtins.cpp +++ b/lib/AST/Builtins.cpp @@ -2166,7 +2166,7 @@ Type IntrinsicTypeDecoder::decodeImmediate() { case IITDescriptor::Subdivide2Argument: case IITDescriptor::Subdivide4Argument: case IITDescriptor::PPCQuad: - case IITDescriptor::AnyPtrToElt: + case IITDescriptor::AArch64Svcount: // These types cannot be expressed in swift yet. return Type(); @@ -2211,14 +2211,6 @@ Type IntrinsicTypeDecoder::decodeImmediate() { case IITDescriptor::Argument: return getTypeArgument(D.getArgumentNumber()); - // A pointer to a type argument. - case IITDescriptor::PtrToArgument: { - Type argType = getTypeArgument(D.getArgumentNumber()); - if (!argType) return Type(); - unsigned addrspace = 0; // An apparent limitation of LLVM. - return makePointer(argType, addrspace); - } - // A vector of the same width as a type argument. case IITDescriptor::SameVecWidthArgument: { Type maybeVectorType = getTypeArgument(D.getArgumentNumber()); @@ -2228,15 +2220,6 @@ Type IntrinsicTypeDecoder::decodeImmediate() { return maybeMakeVectorized(eltType, maybeVectorType); } - // A pointer to the element type of a type argument, which must be a vector. - case IITDescriptor::PtrToElt: { - Type argType = getTypeArgument(D.getArgumentNumber()); - if (!argType) return Type(); - auto vecType = argType->getAs(); - if (!vecType) return Type(); - unsigned addrspace = 0; // An apparent limitation of LLVM. - return makePointer(vecType->getElementType(), addrspace); - } // A struct, which we translate as a tuple. case IITDescriptor::Struct: { diff --git a/lib/AST/ClangTypeConverter.cpp b/lib/AST/ClangTypeConverter.cpp index bf07ef9780b..bc358948d4b 100644 --- a/lib/AST/ClangTypeConverter.cpp +++ b/lib/AST/ClangTypeConverter.cpp @@ -74,6 +74,10 @@ getClangBuiltinTypeFromKind(const clang::ASTContext &context, case clang::BuiltinType::Id: \ return context.Id##Ty; #include "clang/Basic/RISCVVTypes.def" +#define WASM_REF_TYPE(Name, MangedNameBase, Id, SingletonId, AS) \ + case clang::BuiltinType::Id: \ + return context.SingletonId; +#include "clang/Basic/WebAssemblyReferenceTypes.def" } // Not a valid BuiltinType. diff --git a/lib/AST/ConformanceLookupTable.h b/lib/AST/ConformanceLookupTable.h index 9f1476fe5bb..cc41e28d306 100644 --- a/lib/AST/ConformanceLookupTable.h +++ b/lib/AST/ConformanceLookupTable.h @@ -27,6 +27,7 @@ #include "llvm/ADT/MapVector.h" #include "llvm/ADT/PointerUnion.h" #include "llvm/ADT/SetVector.h" +#include "llvm/ADT/TinyPtrVector.h" #include namespace swift { diff --git a/lib/AST/DocComment.cpp b/lib/AST/DocComment.cpp index d5b780e62f2..31e8f976387 100644 --- a/lib/AST/DocComment.cpp +++ b/lib/AST/DocComment.cpp @@ -192,7 +192,7 @@ bool extractSeparatedParams( auto ParagraphContent = ParagraphText->getLiteralContent(); auto PotentialMatch = ParagraphContent.substr(0, ParameterPrefix.size()); - if (!PotentialMatch.startswith_insensitive(ParameterPrefix)) { + if (!PotentialMatch.starts_with_insensitive(ParameterPrefix)) { NormalItems.push_back(Child); continue; } diff --git a/lib/AST/GenericSignature.cpp b/lib/AST/GenericSignature.cpp index 6108f2dd5e4..1fa30884d5c 100644 --- a/lib/AST/GenericSignature.cpp +++ b/lib/AST/GenericSignature.cpp @@ -568,8 +568,8 @@ GenericSignatureImpl::haveSameShape(Type type1, Type type2) const { return getRequirementMachine()->haveSameShape(type1, type2); } -SmallVector GenericSignatureImpl::getShapeClasses() const { - SmallSetVector result; +llvm::SmallVector GenericSignatureImpl::getShapeClasses() const { + llvm::SmallSetVector result; forEachParam([&](GenericTypeParamType *gp, bool canonical) { if (!canonical || !gp->isParameterPack()) diff --git a/lib/AST/Module.cpp b/lib/AST/Module.cpp index f3d7422961f..585ade2fdd4 100644 --- a/lib/AST/Module.cpp +++ b/lib/AST/Module.cpp @@ -626,7 +626,7 @@ void SourceLookupCache::lookupVisibleDecls(ImportPath::Access AccessPath, // 'names' in macro role attributes). Since expansions are cached, it doesn't // cause duplicated expansions, but different 'unexpandedDecl' may report the // same 'ValueDecl'. - SmallSetVector macroExpandedDecls; + llvm::SmallSetVector macroExpandedDecls; for (MissingDecl *unexpandedDecl : unexpandedDecls) { unexpandedDecl->forEachMacroExpandedDecl([&](ValueDecl *vd) { macroExpandedDecls.insert(vd); diff --git a/lib/AST/ModuleLoader.cpp b/lib/AST/ModuleLoader.cpp index a770c4bb163..9a3228da64e 100644 --- a/lib/AST/ModuleLoader.cpp +++ b/lib/AST/ModuleLoader.cpp @@ -49,6 +49,7 @@ DependencyTracker::addDependency(StringRef File, bool IsSystem) { // dimension, which we accept and pass along to the clang DependencyCollector. clangCollector->maybeAddDependency(File, /*FromModule=*/false, IsSystem, /*IsModuleFile=*/false, + /* FileManager=*/ nullptr, /*IsMissing=*/false); } diff --git a/lib/AST/RequirementMachine/RequirementLowering.cpp b/lib/AST/RequirementMachine/RequirementLowering.cpp index d9628c92520..2a417cd282b 100644 --- a/lib/AST/RequirementMachine/RequirementLowering.cpp +++ b/lib/AST/RequirementMachine/RequirementLowering.cpp @@ -1193,7 +1193,7 @@ ArrayRef ProtocolDependenciesRequest::evaluate(Evaluator &evaluator, ProtocolDecl *proto) const { auto &ctx = proto->getASTContext(); - SmallSetVector result; + llvm::SmallSetVector result; // If we have a serialized requirement signature, deserialize it and // look at conformance requirements. diff --git a/lib/AST/RequirementMachine/Rule.h b/lib/AST/RequirementMachine/Rule.h index bc92b8e77c7..4bd52f15e5a 100644 --- a/lib/AST/RequirementMachine/Rule.h +++ b/lib/AST/RequirementMachine/Rule.h @@ -14,6 +14,7 @@ #define SWIFT_RULE_H #include "llvm/ADT/Optional.h" +#include "llvm/ADT/None.h" #include "Symbol.h" #include "Term.h" diff --git a/lib/AST/TypeCheckRequests.cpp b/lib/AST/TypeCheckRequests.cpp index e65b35c404d..5d12902fd99 100644 --- a/lib/AST/TypeCheckRequests.cpp +++ b/lib/AST/TypeCheckRequests.cpp @@ -202,7 +202,7 @@ void EnumRawTypeRequest::noteCycleStep(DiagnosticEngine &diags) const { llvm::Optional IsObjCRequest::getCachedResult() const { auto decl = std::get<0>(getStorage()); if (decl->LazySemanticInfo.isObjCComputed) - return decl->LazySemanticInfo.isObjC; + return static_cast(decl->LazySemanticInfo.isObjC); return llvm::None; } @@ -298,7 +298,7 @@ void HasSelfOrAssociatedTypeRequirementsRequest::cacheResult(bool value) const { llvm::Optional IsFinalRequest::getCachedResult() const { auto decl = std::get<0>(getStorage()); if (decl->LazySemanticInfo.isFinalComputed) - return decl->LazySemanticInfo.isFinal; + return static_cast(decl->LazySemanticInfo.isFinal); return llvm::None; } @@ -320,7 +320,7 @@ void IsFinalRequest::cacheResult(bool value) const { llvm::Optional HasNoncopyableAnnotationRequest::getCachedResult() const { auto decl = std::get<0>(getStorage()); if (decl->LazySemanticInfo.isNoncopyableAnnotationComputed) - return decl->LazySemanticInfo.hasNoncopyableAnnotation; + return static_cast(decl->LazySemanticInfo.hasNoncopyableAnnotation); return llvm::None; } @@ -345,7 +345,7 @@ void HasNoncopyableAnnotationRequest::cacheResult(bool value) const { llvm::Optional IsEscapableRequest::getCachedResult() const { auto decl = std::get<0>(getStorage()); if (decl->LazySemanticInfo.isEscapableComputed) - return decl->LazySemanticInfo.isEscapable; + return static_cast(decl->LazySemanticInfo.isEscapable); return llvm::None; } @@ -368,7 +368,7 @@ void IsEscapableRequest::cacheResult(bool value) const { llvm::Optional IsDynamicRequest::getCachedResult() const { auto decl = std::get<0>(getStorage()); if (decl->LazySemanticInfo.isDynamicComputed) - return decl->LazySemanticInfo.isDynamic; + return static_cast(decl->LazySemanticInfo.isDynamic); return llvm::None; } @@ -670,7 +670,7 @@ void SelfAccessKindRequest::cacheResult(SelfAccessKind value) const { llvm::Optional IsGetterMutatingRequest::getCachedResult() const { auto *storage = std::get<0>(getStorage()); if (storage->LazySemanticInfo.IsGetterMutatingComputed) - return storage->LazySemanticInfo.IsGetterMutating; + return static_cast(storage->LazySemanticInfo.IsGetterMutating); return llvm::None; } @@ -686,7 +686,7 @@ void IsGetterMutatingRequest::cacheResult(bool value) const { llvm::Optional IsSetterMutatingRequest::getCachedResult() const { auto *storage = std::get<0>(getStorage()); if (storage->LazySemanticInfo.IsSetterMutatingComputed) - return storage->LazySemanticInfo.IsSetterMutating; + return static_cast(storage->LazySemanticInfo.IsSetterMutating); return llvm::None; } @@ -736,7 +736,7 @@ void StorageImplInfoRequest::cacheResult(StorageImplInfo value) const { llvm::Optional RequiresOpaqueAccessorsRequest::getCachedResult() const { auto *storage = std::get<0>(getStorage()); if (storage->LazySemanticInfo.RequiresOpaqueAccessorsComputed) - return storage->LazySemanticInfo.RequiresOpaqueAccessors; + return static_cast(storage->LazySemanticInfo.RequiresOpaqueAccessors); return llvm::None; } @@ -754,7 +754,7 @@ llvm::Optional RequiresOpaqueModifyCoroutineRequest::getCachedResult() const { auto *storage = std::get<0>(getStorage()); if (storage->LazySemanticInfo.RequiresOpaqueModifyCoroutineComputed) - return storage->LazySemanticInfo.RequiresOpaqueModifyCoroutine; + return static_cast(storage->LazySemanticInfo.RequiresOpaqueModifyCoroutine); return llvm::None; } @@ -816,7 +816,7 @@ llvm::Optional IsImplicitlyUnwrappedOptionalRequest::getCachedResult() const { auto *decl = std::get<0>(getStorage()); if (decl->LazySemanticInfo.isIUOComputed) - return decl->LazySemanticInfo.isIUO; + return static_cast(decl->LazySemanticInfo.isIUO); return llvm::None; } @@ -952,7 +952,7 @@ void IsStaticRequest::cacheResult(bool result) const { llvm::Optional NeedsNewVTableEntryRequest::getCachedResult() const { auto *decl = std::get<0>(getStorage()); if (decl->LazySemanticInfo.NeedsNewVTableEntryComputed) - return decl->LazySemanticInfo.NeedsNewVTableEntry; + return static_cast(decl->LazySemanticInfo.NeedsNewVTableEntry); return llvm::None; } diff --git a/lib/Basic/CMakeLists.txt b/lib/Basic/CMakeLists.txt index e6bf1cb1017..e895f800a11 100644 --- a/lib/Basic/CMakeLists.txt +++ b/lib/Basic/CMakeLists.txt @@ -90,7 +90,7 @@ add_swift_host_library(swiftBasic STATIC # Platform-agnostic fallback TaskQueue implementation Default/TaskQueue.inc - LLVM_LINK_COMPONENTS support) + LLVM_LINK_COMPONENTS support targetparser) _swift_gyb_target_sources(swiftBasic PRIVATE UnicodeExtendedGraphemeClusters.cpp.gyb) diff --git a/lib/Basic/EditorPlaceholder.cpp b/lib/Basic/EditorPlaceholder.cpp index 447f46ed649..83be47f0095 100644 --- a/lib/Basic/EditorPlaceholder.cpp +++ b/lib/Basic/EditorPlaceholder.cpp @@ -17,9 +17,9 @@ #include "swift/Basic/EditorPlaceholder.h" #include "llvm/ADT/Optional.h" +#include "llvm/ADT/None.h" using namespace swift; -using namespace llvm; // Placeholder text must start with '<#' and end with // '#>'. @@ -37,11 +37,11 @@ using namespace llvm; // or type-string. If this ends up not the case for some reason, we can consider // adding escaping for '##'. -Optional -swift::parseEditorPlaceholder(StringRef PlaceholderText) { +llvm::Optional +swift::parseEditorPlaceholder(llvm::StringRef PlaceholderText) { if (!PlaceholderText.startswith("<#") || !PlaceholderText.endswith("#>")) - return None; + return llvm::None; PlaceholderText = PlaceholderText.drop_front(2).drop_back(2); EditorPlaceholderData PHDataBasic; @@ -60,7 +60,7 @@ swift::parseEditorPlaceholder(StringRef PlaceholderText) { assert(PlaceholderText.startswith("T##")); PlaceholderText = PlaceholderText.drop_front(3); size_t Pos = PlaceholderText.find("##"); - if (Pos == StringRef::npos) { + if (Pos == llvm::StringRef::npos) { PHDataTyped.Display = PHDataTyped.Type = PHDataTyped.TypeForExpansion = PlaceholderText; return PHDataTyped; @@ -69,7 +69,7 @@ swift::parseEditorPlaceholder(StringRef PlaceholderText) { PlaceholderText = PlaceholderText.substr(Pos+2); Pos = PlaceholderText.find("##"); - if (Pos == StringRef::npos) { + if (Pos == llvm::StringRef::npos) { PHDataTyped.Type = PHDataTyped.TypeForExpansion = PlaceholderText; } else { PHDataTyped.Type = PlaceholderText.substr(0, Pos); @@ -79,6 +79,6 @@ swift::parseEditorPlaceholder(StringRef PlaceholderText) { return PHDataTyped; } -bool swift::isEditorPlaceholder(StringRef IdentifierText) { +bool swift::isEditorPlaceholder(llvm::StringRef IdentifierText) { return IdentifierText.startswith("<#"); } diff --git a/lib/Basic/FileSystem.cpp b/lib/Basic/FileSystem.cpp index 3d44e0a250c..15d2b8e34dc 100644 --- a/lib/Basic/FileSystem.cpp +++ b/lib/Basic/FileSystem.cpp @@ -13,6 +13,7 @@ #include "swift/Basic/FileSystem.h" #include "clang/Basic/FileManager.h" +#include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" diff --git a/lib/Basic/Platform.cpp b/lib/Basic/Platform.cpp index 1de1426e540..f652d874b63 100644 --- a/lib/Basic/Platform.cpp +++ b/lib/Basic/Platform.cpp @@ -13,7 +13,7 @@ #include "swift/Basic/Platform.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/StringSwitch.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/Support/VersionTuple.h" using namespace swift; @@ -234,6 +234,9 @@ StringRef swift::getPlatformNameForTriple(const llvm::Triple &triple) { return "wasi"; case llvm::Triple::UnknownOS: return "none"; + case llvm::Triple::UEFI: + case llvm::Triple::LiteOS: + llvm_unreachable("unsupported OS"); } llvm_unreachable("unsupported OS"); } diff --git a/lib/Basic/StringExtras.cpp b/lib/Basic/StringExtras.cpp index 8a6747813d1..da33b28e676 100644 --- a/lib/Basic/StringExtras.cpp +++ b/lib/Basic/StringExtras.cpp @@ -433,7 +433,7 @@ static bool matchNameWordToTypeWord(StringRef nameWord, StringRef typeWord) { // We can match the suffix of the type so long as everything preceding the // match is neither a lowercase letter nor a '_'. This ignores type // prefixes for acronyms, e.g., the 'NS' in 'NSURL'. - if (typeWord.endswith_insensitive(nameWord) && + if (typeWord.ends_with_insensitive(nameWord) && !clang::isLowercase(typeWord[typeWord.size() - nameWord.size()])) { // Check that everything preceding the match is neither a lowercase letter // nor a '_'. @@ -446,7 +446,7 @@ static bool matchNameWordToTypeWord(StringRef nameWord, StringRef typeWord) { // We can match a prefix so long as everything following the match is // a number. - if (typeWord.startswith_insensitive(nameWord)) { + if (typeWord.starts_with_insensitive(nameWord)) { for (unsigned i = nameWord.size(), n = typeWord.size(); i != n; ++i) { if (!clang::isDigit(typeWord[i])) return false; } diff --git a/lib/ClangImporter/ClangAdapter.cpp b/lib/ClangImporter/ClangAdapter.cpp index 86f423ef7fb..4539925e037 100644 --- a/lib/ClangImporter/ClangAdapter.cpp +++ b/lib/ClangImporter/ClangAdapter.cpp @@ -457,10 +457,10 @@ OmissionTypeName importer::getClangTypeNameForOmission(clang::ASTContext &ctx, case clang::BuiltinType::OCLIntelSubgroupAVCImeResult: case clang::BuiltinType::OCLIntelSubgroupAVCRefResult: case clang::BuiltinType::OCLIntelSubgroupAVCSicResult: - case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleRefStreamout: - case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualRefStreamout: - case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleRefStreamin: - case clang::BuiltinType::OCLIntelSubgroupAVCImeDualRefStreamin: + case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleReferenceStreamout: + case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualReferenceStreamout: + case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleReferenceStreamin: + case clang::BuiltinType::OCLIntelSubgroupAVCImeDualReferenceStreamin: return OmissionTypeName(); // OpenMP types that don't have Swift equivalents. @@ -483,6 +483,11 @@ OmissionTypeName importer::getClangTypeNameForOmission(clang::ASTContext &ctx, #define RVV_TYPE(Name, Id, Size) case clang::BuiltinType::Id: #include "clang/Basic/RISCVVTypes.def" return OmissionTypeName(); + + // WAM builtin types that don't have Swift equivalents. +#define WASM_TYPE(Name, Id, Size) case clang::BuiltinType::Id: +#include "clang/Basic/WebAssemblyReferenceTypes.def" + return OmissionTypeName(); } } @@ -749,11 +754,9 @@ bool importer::isUnavailableInSwift( OptionalTypeKind importer::getParamOptionality(const clang::ParmVarDecl *param, bool knownNonNull) { - auto &clangCtx = param->getASTContext(); - // If nullability is available on the type, use it. clang::QualType paramTy = param->getType(); - if (auto nullability = paramTy->getNullability(clangCtx)) { + if (auto nullability = paramTy->getNullability()) { return translateNullability(*nullability); } diff --git a/lib/ClangImporter/ClangImporter.cpp b/lib/ClangImporter/ClangImporter.cpp index e5df04b97c9..71b604b8c72 100644 --- a/lib/ClangImporter/ClangImporter.cpp +++ b/lib/ClangImporter/ClangImporter.cpp @@ -51,6 +51,7 @@ #include "swift/Subsystems.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Mangle.h" +#include "clang/Basic/FileEntry.h" #include "clang/Basic/IdentifierTable.h" #include "clang/Basic/Module.h" #include "clang/Basic/TargetInfo.h" @@ -111,7 +112,7 @@ namespace { void InclusionDirective( clang::SourceLocation HashLoc, const clang::Token &IncludeTok, StringRef FileName, bool IsAngled, clang::CharSourceRange FilenameRange, - llvm::Optional File, StringRef SearchPath, + clang::OptionalFileEntryRef File, StringRef SearchPath, StringRef RelativePath, const clang::Module *Imported, clang::SrcMgr::CharacteristicKind FileType) override { handleImport(Imported); @@ -286,7 +287,7 @@ private: void InclusionDirective(clang::SourceLocation HashLoc, const clang::Token &IncludeTok, StringRef FileName, bool IsAngled, clang::CharSourceRange FilenameRange, - llvm::Optional File, + clang::OptionalFileEntryRef File, StringRef SearchPath, StringRef RelativePath, const clang::Module *Imported, clang::SrcMgr::CharacteristicKind FileType) override { @@ -376,11 +377,12 @@ public: } void maybeAddDependency(StringRef Filename, bool FromModule, bool IsSystem, - bool IsModuleFile, bool IsMissing) override { + bool IsModuleFile, clang::FileManager *fileManager, + bool IsMissing) override { if (FileCollector) FileCollector->addFile(Filename); clang::DependencyCollector::maybeAddDependency( - Filename, FromModule, IsSystem, IsModuleFile, IsMissing); + Filename, FromModule, IsSystem, IsModuleFile, fileManager, IsMissing); } }; } // end anonymous namespace @@ -440,7 +442,7 @@ ClangImporter::~ClangImporter() { static bool clangSupportsPragmaAttributeWithSwiftAttr() { clang::AttributeCommonInfo swiftAttrInfo(clang::SourceRange(), clang::AttributeCommonInfo::AT_SwiftAttr, - clang::AttributeCommonInfo::AS_GNU); + clang::AttributeCommonInfo::Form::GNU()); auto swiftAttrParsedInfo = clang::ParsedAttrInfo::get(swiftAttrInfo); return swiftAttrParsedInfo.IsSupportedByPragmaAttribute; } @@ -890,8 +892,8 @@ bool ClangImporter::canReadPCH(StringRef PCHFilename) { invocation->getPreprocessorOpts().DisablePCHOrModuleValidation = clang::DisableValidationForModuleKind::None; invocation->getHeaderSearchOpts().ModulesValidateSystemHeaders = true; - invocation->getLangOpts()->NeededByPCHOrCompilationUsesPCH = true; - invocation->getLangOpts()->CacheGeneratedPCH = true; + invocation->getLangOpts().NeededByPCHOrCompilationUsesPCH = true; + invocation->getLangOpts().CacheGeneratedPCH = true; // If the underlying invocation is allowing PCH errors, then it "can be read", // even if it has its error bit set. Thus, don't override // `AllowPCHWithCompilerErrors`. @@ -1734,15 +1736,15 @@ std::string ClangImporter::getBridgingHeaderContents(StringRef headerPath, /// Returns the appropriate source input language based on language options. static clang::Language getLanguageFromOptions( - const clang::LangOptions *LangOpts) { - if (LangOpts->OpenCL) + const clang::LangOptions &LangOpts) { + if (LangOpts.OpenCL) return clang::Language::OpenCL; - if (LangOpts->CUDA) + if (LangOpts.CUDA) return clang::Language::CUDA; - if (LangOpts->ObjC) - return LangOpts->CPlusPlus ? + if (LangOpts.ObjC) + return LangOpts.CPlusPlus ? clang::Language::ObjCXX : clang::Language::ObjC; - return LangOpts->CPlusPlus ? clang::Language::CXX : clang::Language::C; + return LangOpts.CPlusPlus ? clang::Language::CXX : clang::Language::C; } /// Wraps the given frontend action in an index data recording action if the @@ -1792,9 +1794,9 @@ bool ClangImporter::emitBridgingPCH( auto emitInstance = cloneCompilerInstanceForPrecompiling(); auto &invocation = emitInstance->getInvocation(); - auto LangOpts = invocation.getLangOpts(); - LangOpts->NeededByPCHOrCompilationUsesPCH = true; - LangOpts->CacheGeneratedPCH = cached; + auto &LangOpts = invocation.getLangOpts(); + LangOpts.NeededByPCHOrCompilationUsesPCH = true; + LangOpts.CacheGeneratedPCH = cached; auto language = getLanguageFromOptions(LangOpts); auto inputFile = clang::FrontendInputFile(headerPath, language); @@ -1822,7 +1824,7 @@ bool ClangImporter::runPreprocessor( StringRef inputPath, StringRef outputPath) { auto emitInstance = cloneCompilerInstanceForPrecompiling(); auto &invocation = emitInstance->getInvocation(); - auto LangOpts = invocation.getLangOpts(); + auto &LangOpts = invocation.getLangOpts(); auto &OutputOpts = invocation.getPreprocessorOutputOpts(); OutputOpts.ShowCPP = 1; OutputOpts.ShowComments = 0; @@ -1849,10 +1851,10 @@ bool ClangImporter::emitPrecompiledModule( auto emitInstance = cloneCompilerInstanceForPrecompiling(); auto &invocation = emitInstance->getInvocation(); - auto LangOpts = invocation.getLangOpts(); - LangOpts->setCompilingModule(clang::LangOptions::CMK_ModuleMap); - LangOpts->ModuleName = moduleName.str(); - LangOpts->CurrentModule = LangOpts->ModuleName; + auto &LangOpts = invocation.getLangOpts(); + LangOpts.setCompilingModule(clang::LangOptions::CMK_ModuleMap); + LangOpts.ModuleName = moduleName.str(); + LangOpts.CurrentModule = LangOpts.ModuleName; auto language = getLanguageFromOptions(LangOpts); @@ -2036,7 +2038,7 @@ ModuleDecl *ClangImporter::Implementation::loadModuleClang( // For explicit module build, module should always exist but module map might // not be exist. Go straight to module loader. - if (Instance->getInvocation().getLangOpts()->ImplicitModules) { + if (Instance->getInvocation().getLangOpts().ImplicitModules) { // Look up the top-level module first, to see if it exists at all. clang::Module *clangModule = clangHeaderSearch.lookupModule( realModuleName, /*ImportLoc=*/clang::SourceLocation(), @@ -3093,7 +3095,7 @@ bool ClangImporter::lookupDeclsFromHeader(StringRef Filename, if (ClangLoc.isInvalid()) return false; - llvm::Optional LocRef = + clang::OptionalFileEntryRef LocRef = ClangSM.getFileEntryRefForID(ClangSM.getFileID(ClangLoc)); if (!LocRef || *LocRef != File) return false; diff --git a/lib/ClangImporter/ClangModuleDependencyScanner.cpp b/lib/ClangImporter/ClangModuleDependencyScanner.cpp index 702220f662b..ea337d9da95 100644 --- a/lib/ClangImporter/ClangModuleDependencyScanner.cpp +++ b/lib/ClangImporter/ClangModuleDependencyScanner.cpp @@ -128,7 +128,7 @@ static std::vector getClangDepScanningInvocationArguments( } ModuleDependencyVector ClangImporter::bridgeClangModuleDependencies( - const clang::tooling::dependencies::ModuleDepsGraph &clangDependencies, + clang::tooling::dependencies::ModuleDepsGraph &clangDependencies, StringRef moduleOutputPath, RemapPathCallback callback) { const auto &ctx = Impl.SwiftContext; ModuleDependencyVector result; @@ -146,7 +146,7 @@ ModuleDependencyVector ClangImporter::bridgeClangModuleDependencies( ("-fapinotes-swift-version=" + ctx.LangOpts.EffectiveLanguageVersion.asAPINotesVersionString())}; - for (const auto &clangModuleDep : clangDependencies) { + for (auto &clangModuleDep : clangDependencies) { // File dependencies for this module. std::vector fileDeps; for (const auto &fileDep : clangModuleDep.FileDeps) { @@ -201,9 +201,9 @@ ModuleDependencyVector ClangImporter::bridgeClangModuleDependencies( new clang::IgnoringDiagConsumer()); llvm::SmallVector clangArgs; - llvm::for_each(clangModuleDep.BuildArguments, [&](const std::string &Arg) { - clangArgs.push_back(Arg.c_str()); - }); + llvm::for_each( + clangModuleDep.getBuildArguments(), + [&](const std::string &Arg) { clangArgs.push_back(Arg.c_str()); }); bool success = clang::CompilerInvocation::CreateFromArgs( depsInvocation, clangArgs, clangDiags); diff --git a/lib/ClangImporter/ImportDecl.cpp b/lib/ClangImporter/ImportDecl.cpp index 26e1037989b..99561a95c4a 100644 --- a/lib/ClangImporter/ImportDecl.cpp +++ b/lib/ClangImporter/ImportDecl.cpp @@ -2245,7 +2245,7 @@ namespace { if (auto field = dyn_cast(nd)) { // Non-nullable pointers can't be zero-initialized. if (auto nullability = - field->getType()->getNullability(Impl.getClangASTContext())) { + field->getType()->getNullability()) { if (*nullability == clang::NullabilityKind::NonNull) hasZeroInitializableStorage = false; } @@ -4395,8 +4395,7 @@ namespace { isIUO = false; OptionalTypeKind nullability = OTK_ImplicitlyUnwrappedOptional; - if (auto typeNullability = decl->getReturnType()->getNullability( - Impl.getClangASTContext())) { + if (auto typeNullability = decl->getReturnType()->getNullability()) { // If the return type has nullability, use it. nullability = translateNullability(*typeNullability); } diff --git a/lib/ClangImporter/ImportName.cpp b/lib/ClangImporter/ImportName.cpp index 8a2bfdd10a5..7dd5689a98b 100644 --- a/lib/ClangImporter/ImportName.cpp +++ b/lib/ClangImporter/ImportName.cpp @@ -26,6 +26,7 @@ #include "swift/AST/NameLookup.h" #include "swift/AST/TypeRepr.h" #include "swift/AST/Types.h" +#include "swift/Basic/STLExtras.h" #include "swift/Basic/StringExtras.h" #include "swift/ClangImporter/ClangImporterRequests.h" #include "swift/Parse/Parser.h" @@ -45,6 +46,7 @@ #include "llvm/Support/ErrorHandling.h" #include #include +#include #include "llvm/ADT/Statistic.h" #define DEBUG_TYPE "Import Name" @@ -257,10 +259,8 @@ static const char AltErrorSuffix[] = "WithError"; /// \param method The Clang method. static OptionalTypeKind getResultOptionality( const clang::ObjCMethodDecl *method) { - auto &clangCtx = method->getASTContext(); - // If nullability is available on the type, use it. - if (auto nullability = method->getReturnType()->getNullability(clangCtx)) { + if (auto nullability = method->getReturnType()->getNullability()) { return translateNullability(*nullability); } @@ -1226,8 +1226,7 @@ bool swift::isCompletionHandlerParamName(StringRef paramName) { } // Determine whether the given type is a nullable NSError type. -static bool isNullableNSErrorType( - clang::ASTContext &clangCtx, clang::QualType type) { +static bool isNullableNSErrorType(clang::QualType type) { auto objcPtrType = type->getAs(); if (!objcPtrType) return false; @@ -1237,7 +1236,7 @@ static bool isNullableNSErrorType( return false; // If nullability is specified, check it. - if (auto nullability = type->getNullability(clangCtx)) { + if (auto nullability = type->getNullability()) { switch (translateNullability(*nullability)) { case OTK_None: return false; @@ -1388,12 +1387,11 @@ llvm::Optional NameImporter::considerAsyncImport( completionHandlerParamTypes = prototype->getParamTypes(); } - auto &clangCtx = clangDecl->getASTContext(); for (unsigned paramIdx : indices(completionHandlerParamTypes)) { auto paramType = completionHandlerParamTypes[paramIdx]; // We are only interested in nullable NSError parameters. - if (!isNullableNSErrorType(clangCtx, paramType)) + if (!isNullableNSErrorType(paramType)) continue; // If this is the first nullable error parameter, note that. @@ -2393,14 +2391,14 @@ ImportedName NameImporter::importNameImpl(const clang::NamedDecl *D, method->getDeclContext(), getNonNullArgs(method, params), result.getErrorInfo() ? llvm::Optional( - result.getErrorInfo()->ErrorParameterIndex) + static_cast(result.getErrorInfo()->ErrorParameterIndex)) : llvm::None, method->hasRelatedResultType(), method->isInstanceMethod(), - result.getAsyncInfo().transform( + swift::transform(result.getAsyncInfo(), [](const ForeignAsyncConvention::Info &info) { return info.completionHandlerParamIndex(); }), - result.getAsyncInfo().transform( + swift::transform(result.getAsyncInfo(), [&](const ForeignAsyncConvention::Info &info) { return method->getDeclName().getObjCSelector().getNameForSlot( info.completionHandlerParamIndex()); diff --git a/lib/ClangImporter/ImportType.cpp b/lib/ClangImporter/ImportType.cpp index fe915dd30a9..d03fc7d014e 100644 --- a/lib/ClangImporter/ImportType.cpp +++ b/lib/ClangImporter/ImportType.cpp @@ -366,10 +366,10 @@ namespace { case clang::BuiltinType::OCLIntelSubgroupAVCImeResult: case clang::BuiltinType::OCLIntelSubgroupAVCRefResult: case clang::BuiltinType::OCLIntelSubgroupAVCSicResult: - case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleRefStreamout: - case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualRefStreamout: - case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleRefStreamin: - case clang::BuiltinType::OCLIntelSubgroupAVCImeDualRefStreamin: + case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleReferenceStreamout: + case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualReferenceStreamout: + case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleReferenceStreamin: + case clang::BuiltinType::OCLIntelSubgroupAVCImeDualReferenceStreamin: return Type(); // OpenMP types that don't have Swift equivalents. @@ -392,6 +392,11 @@ namespace { #define RVV_TYPE(Name, Id, Size) case clang::BuiltinType::Id: #include "clang/Basic/RISCVVTypes.def" return Type(); + +#define WASM_TYPE(Name, Id, Size) case clang::BuiltinType::Id: +#include "clang/Basic/WebAssemblyReferenceTypes.def" + return Type(); + } llvm_unreachable("Invalid BuiltinType."); @@ -1669,7 +1674,7 @@ ImportedType ClangImporter::Implementation::importType( // If nullability is provided as part of the type, that overrides // optionality provided externally. - if (auto nullability = type->getNullability(clangContext)) { + if (auto nullability = type->getNullability()) { bool stripNonResultOptionality = importKind == ImportTypeKind::CompletionHandlerResultParameter; diff --git a/lib/Driver/Driver.cpp b/lib/Driver/Driver.cpp index 4335a6fdc95..a15a49956a5 100644 --- a/lib/Driver/Driver.cpp +++ b/lib/Driver/Driver.cpp @@ -1095,7 +1095,7 @@ Driver::buildCompilation(const ToolChain &TC, return nullptr; } - buildJobs(TopLevelActions, OI, OFM ? OFM.getPointer() : nullptr, + buildJobs(TopLevelActions, OI, OFM ? &*OFM : nullptr, workingDirectory, TC, *C); if (DriverPrintDerivedOutputFileMap) { diff --git a/lib/DriverTool/driver.cpp b/lib/DriverTool/driver.cpp index af3b576aef2..1a1d6417b68 100644 --- a/lib/DriverTool/driver.cpp +++ b/lib/DriverTool/driver.cpp @@ -32,7 +32,7 @@ #include "swift/FrontendTool/FrontendTool.h" #include "swift/DriverTool/DriverTool.h" #include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/ConvertUTF.h" #include "llvm/Support/Errno.h" diff --git a/lib/DriverTool/swift_cache_tool_main.cpp b/lib/DriverTool/swift_cache_tool_main.cpp index eabd08d6b0a..4c3ae67eeef 100644 --- a/lib/DriverTool/swift_cache_tool_main.cpp +++ b/lib/DriverTool/swift_cache_tool_main.cpp @@ -65,7 +65,10 @@ enum ID { #undef OPTION }; -#define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE; +#define PREFIX(NAME, VALUE) \ + constexpr llvm::StringLiteral NAME##_init[] = VALUE; \ + constexpr llvm::ArrayRef NAME( \ + NAME##_init, std::size(NAME##_init) - 1); #include "SwiftCacheToolOptions.inc" #undef PREFIX @@ -78,9 +81,9 @@ static const OptTable::Info InfoTable[] = { #undef OPTION }; -class CacheToolOptTable : public llvm::opt::OptTable { +class CacheToolOptTable : public llvm::opt::GenericOptTable { public: - CacheToolOptTable() : OptTable(InfoTable) {} + CacheToolOptTable() : GenericOptTable(InfoTable) {} }; class SwiftCacheToolInvocation { @@ -100,18 +103,14 @@ public: Instance.addDiagnosticConsumer(&PDC); } - std::unique_ptr createOptTable() { - return std::unique_ptr(new CacheToolOptTable()); - } - int parseArgs(ArrayRef Args) { auto &Diags = Instance.getDiags(); - std::unique_ptr Table = createOptTable(); + CacheToolOptTable Table; unsigned MissingIndex; unsigned MissingCount; llvm::opt::InputArgList ParsedArgs = - Table->ParseArgs(Args, MissingIndex, MissingCount); + Table.ParseArgs(Args, MissingIndex, MissingCount); if (MissingCount) { Diags.diagnose(SourceLoc(), diag::error_missing_arg_value, ParsedArgs.getArgString(MissingIndex), MissingCount); @@ -121,8 +120,8 @@ public: if (ParsedArgs.getLastArg(OPT_help)) { std::string ExecutableName = llvm::sys::path::stem(MainExecutablePath).str(); - Table->printHelp(llvm::outs(), ExecutableName.c_str(), "Swift Cache Tool", - 0, 0, /*ShowAllAliases*/ false); + Table.printHelp(llvm::outs(), ExecutableName.c_str(), "Swift Cache Tool", + 0, 0, /*ShowAllAliases*/ false); return 0; } diff --git a/lib/DriverTool/swift_llvm_opt_main.cpp b/lib/DriverTool/swift_llvm_opt_main.cpp index 06cf46adbc7..a40a5358c3e 100644 --- a/lib/DriverTool/swift_llvm_opt_main.cpp +++ b/lib/DriverTool/swift_llvm_opt_main.cpp @@ -28,7 +28,7 @@ #include "swift/LLVMPasses/PassesFwd.h" #include "swift/LLVMPasses/Passes.h" #include "llvm/ADT/Statistic.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/Analysis/CallGraph.h" #include "llvm/Analysis/CallGraphSCCPass.h" #include "llvm/Analysis/LoopPass.h" @@ -42,15 +42,17 @@ #include "llvm/IR/DebugInfo.h" #include "llvm/IR/IRPrintingPasses.h" #include "llvm/IR/LLVMContext.h" -#include "llvm/IR/LegacyPassManager.h" -#include "llvm/IR/LegacyPassNameParser.h" #include "llvm/IR/Module.h" +#include "llvm/Passes/PassBuilder.h" +#include "llvm/Passes/PassPlugin.h" +#include "llvm/Passes/StandardInstrumentations.h" #include "llvm/IR/Verifier.h" +#include "llvm/IRPrinter/IRPrintingPasses.h" #include "llvm/IRReader/IRReader.h" #include "llvm/InitializePasses.h" #include "llvm/LinkAllIR.h" #include "llvm/LinkAllPasses.h" -#include "llvm/MC/SubtargetFeature.h" +#include "llvm/TargetParser/SubtargetFeature.h" #include "llvm/MC/TargetRegistry.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FileSystem.h" @@ -64,7 +66,7 @@ #include "llvm/Support/TargetSelect.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Target/TargetMachine.h" -#include "llvm/Transforms/IPO/PassManagerBuilder.h" +#include "llvm/Transforms/Scalar/LoopPassManager.h" using namespace swift; @@ -75,23 +77,9 @@ static llvm::codegen::RegisterCodeGenFlags CGF; //===----------------------------------------------------------------------===// struct SwiftLLVMOptOptions { - // The OptimizationList is automatically populated with registered passes by the - // PassNameParser. - // - llvm::cl::list - PassList = llvm::cl::list(llvm::cl::desc("Optimizations available:")); - llvm::cl::opt Optimized = llvm::cl::opt("O", llvm::cl::desc("Optimization level O. Similar to swift -O")); - // TODO: I wanted to call this 'verify', but some other pass is using this - // option. - llvm::cl::opt - VerifyEach = llvm::cl::opt( - "verify-each", - llvm::cl::desc("Should we spend time verifying that the IR is well " - "formed")); - llvm::cl::opt TargetTriple = llvm::cl::opt("mtriple", llvm::cl::desc("Override target triple for module")); @@ -117,6 +105,11 @@ struct SwiftLLVMOptOptions { llvm::cl::value_desc("layout-string"), llvm::cl::init("")); }; +static llvm::cl::opt PassPipeline( + "passes", + llvm::cl::desc( + "A textual description of the pass pipeline. To have analysis passes " + "available before a certain pass, add 'require'.")); //===----------------------------------------------------------------------===// // Helper Methods //===----------------------------------------------------------------------===// @@ -148,71 +141,6 @@ getTargetMachine(llvm::Triple TheTriple, StringRef CPUStr, llvm::codegen::getExplicitCodeModel(), GetCodeGenOptLevel(options)); } -static void dumpOutput(llvm::Module &M, llvm::raw_ostream &os) { - // For now just always dump assembly. - llvm::legacy::PassManager EmitPasses; - EmitPasses.add(createPrintModulePass(os)); - EmitPasses.run(M); -} - -static inline void addPass(llvm::legacy::PassManagerBase &PM, llvm::Pass *P, - const SwiftLLVMOptOptions &options) { - // Add the pass to the pass manager... - PM.add(P); - if (P->getPassID() == &SwiftAAWrapperPass::ID) { - PM.add(llvm::createExternalAAWrapperPass([](llvm::Pass &P, llvm::Function &, - llvm::AAResults &AAR) { - if (auto *WrapperPass = P.getAnalysisIfAvailable()) - AAR.addAAResult(WrapperPass->getResult()); - })); - } - - // If we are verifying all of the intermediate steps, add the verifier... - if (options.VerifyEach) - PM.add(llvm::createVerifierPass()); -} - -static void runSpecificPasses(StringRef Binary, llvm::Module *M, - llvm::TargetMachine *TM, - llvm::Triple &ModuleTriple, - const SwiftLLVMOptOptions &options) { - llvm::legacy::PassManager Passes; - llvm::TargetLibraryInfoImpl TLII(ModuleTriple); - Passes.add(new llvm::TargetLibraryInfoWrapperPass(TLII)); - - const llvm::DataLayout &DL = M->getDataLayout(); - if (DL.isDefault() && !options.DefaultDataLayout.empty()) { - M->setDataLayout(options.DefaultDataLayout); - } - - // Add internal analysis passes from the target machine. - Passes.add(createTargetTransformInfoWrapperPass( - TM ? TM->getTargetIRAnalysis() : llvm::TargetIRAnalysis())); - - if (TM) { - // FIXME: We should dyn_cast this when supported. - auto <M = static_cast(*TM); - llvm::Pass *TPC = LTM.createPassConfig(Passes); - Passes.add(TPC); - } - - for (const llvm::PassInfo *PassInfo : options.PassList) { - llvm::Pass *P = nullptr; - if (PassInfo->getNormalCtor()) - P = PassInfo->getNormalCtor()(); - else - llvm::errs() << Binary - << ": cannot create pass: " << PassInfo->getPassName() - << "\n"; - if (P) { - addPass(Passes, P, options); - } - } - - // Do it. - Passes.run(*M); -} - //===----------------------------------------------------------------------===// // Main Implementation //===----------------------------------------------------------------------===// @@ -220,34 +148,6 @@ static void runSpecificPasses(StringRef Binary, llvm::Module *M, int swift_llvm_opt_main(ArrayRef argv, void *MainAddr) { INITIALIZE_LLVM(); - // Initialize passes - llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry(); - initializeCore(Registry); - initializeScalarOpts(Registry); - initializeObjCARCOpts(Registry); - initializeVectorization(Registry); - initializeIPO(Registry); - initializeAnalysis(Registry); - initializeTransformUtils(Registry); - initializeInstCombine(Registry); - initializeInstrumentation(Registry); - initializeTarget(Registry); - // For codegen passes, only passes that do IR to IR transformation are - // supported. - initializeCodeGenPreparePass(Registry); - initializeAtomicExpandPass(Registry); - initializeRewriteSymbolsLegacyPassPass(Registry); - initializeWinEHPreparePass(Registry); - initializeDwarfEHPrepareLegacyPassPass(Registry); - initializeSjLjEHPreparePass(Registry); - - // Register Swift Only Passes. - initializeSwiftAAWrapperPassPass(Registry); - initializeSwiftARCOptPass(Registry); - initializeSwiftARCContractPass(Registry); - initializeInlineTreePrinterPass(Registry); - initializeLegacySwiftMergeFunctionsPass(Registry); - SwiftLLVMOptOptions options; llvm::cl::ParseCommandLineOptions(argv.size(), argv.data(), "Swift LLVM optimizer\n"); @@ -317,9 +217,87 @@ int swift_llvm_opt_main(ArrayRef argv, void *MainAddr) { // Then perform the optimizations. performLLVMOptimizations(Opts, M.get(), TM.get(), &Out->os()); } else { - runSpecificPasses(argv[0], M.get(), TM.get(), ModuleTriple, options); - // Finally dump the output. - dumpOutput(*M, Out->os()); + std::string Pipeline = PassPipeline; + llvm::TargetLibraryInfoImpl TLII(ModuleTriple); + if (TM) + TM->setPGOOption(std::nullopt); + llvm::LoopAnalysisManager LAM; + llvm::FunctionAnalysisManager FAM; + llvm::CGSCCAnalysisManager CGAM; + llvm::ModuleAnalysisManager MAM; + + std::optional P = std::nullopt; + llvm::PassInstrumentationCallbacks PIC; + llvm::PrintPassOptions PrintPassOpts; + + PrintPassOpts.Verbose = false; + PrintPassOpts.SkipAnalyses = false; + auto &Mod = *M; + llvm::StandardInstrumentations SI(M->getContext(), false, false, PrintPassOpts); + SI.registerCallbacks(PIC, &MAM); + + llvm::PipelineTuningOptions PTO; + // LoopUnrolling defaults on to true and DisableLoopUnrolling is initialized + // to false above so we shouldn't necessarily need to check whether or not the + // option has been enabled. + PTO.LoopUnrolling = true; + llvm::PassBuilder PB(TM.get(), PTO, P, &PIC); + + PB.registerPipelineParsingCallback( + [ModuleTriple](StringRef Name, llvm::ModulePassManager &PM, + ArrayRef) { + if (Name == "swift-merge-functions") { + if (ModuleTriple.isArm64e()) + PM.addPass(SwiftMergeFunctionsPass(true, 0)); + else + PM.addPass(SwiftMergeFunctionsPass(false, 0)); + return true; + } + return false; + }); + PB.registerPipelineParsingCallback( + [ModuleTriple](StringRef Name, llvm::FunctionPassManager &PM, + ArrayRef) { + if (Name == "swift-llvm-arc-optimize") { + PM.addPass(SwiftARCOptPass()); + return true; + } + return false; + }); + PB.registerPipelineParsingCallback( + [ModuleTriple](StringRef Name, llvm::FunctionPassManager &PM, + ArrayRef) { + if (Name == "swift-llvm-arc-contract") { + PM.addPass(SwiftARCContractPass()); + return true; + } + return false; + }); + auto AA = PB.buildDefaultAAPipeline(); + AA.registerFunctionAnalysis(); + + // Register the AA manager first so that our version is the one used. + FAM.registerPass([&] { return std::move(AA); }); + FAM.registerPass([&] { return SwiftAA(); }); + // Register our TargetLibraryInfoImpl. + FAM.registerPass([&] { return llvm::TargetLibraryAnalysis(TLII); }); + + // Register all the basic analyses with the managers. + PB.registerModuleAnalyses(MAM); + PB.registerCGSCCAnalyses(CGAM); + PB.registerFunctionAnalyses(FAM); + PB.registerLoopAnalyses(LAM); + PB.crossRegisterProxies(LAM, FAM, CGAM, MAM); + + llvm::ModulePassManager MPM; + if (!Pipeline.empty()) { + if (auto Err = PB.parsePassPipeline(MPM, Pipeline)) { + llvm::errs() << argv[0] << ": " << toString(std::move(Err)) << "\n"; + return 1; + } + } + MPM.addPass(llvm::PrintModulePass(Out.get()->os(), "", false, false)); + MPM.run(*M, MAM); } return 0; diff --git a/lib/Frontend/ArgsToFrontendOptionsConverter.cpp b/lib/Frontend/ArgsToFrontendOptionsConverter.cpp index 1bc41cbd1bd..e52b3b9afdf 100644 --- a/lib/Frontend/ArgsToFrontendOptionsConverter.cpp +++ b/lib/Frontend/ArgsToFrontendOptionsConverter.cpp @@ -22,7 +22,7 @@ #include "swift/Parse/Lexer.h" #include "swift/Strings.h" #include "llvm/ADT/STLExtras.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/CAS/ObjectStore.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" @@ -386,6 +386,17 @@ bool ArgsToFrontendOptionsConverter::convert( Opts.BlocklistConfigFilePaths.push_back(A); } + if (Arg *A = Args.getLastArg(OPT_cas_backend_mode)) { + Opts.CASObjMode = llvm::StringSwitch(A->getValue()) + .Case("native", llvm::CASBackendMode::Native) + .Case("casid", llvm::CASBackendMode::CASID) + .Case("verify", llvm::CASBackendMode::Verify) + .Default(llvm::CASBackendMode::Native); + } + + Opts.UseCASBackend = Args.hasArg(OPT_cas_backend); + Opts.EmitCASIDFile = Args.hasArg(OPT_cas_emit_casid_file); + return false; } diff --git a/lib/Frontend/ArgsToFrontendOutputsConverter.cpp b/lib/Frontend/ArgsToFrontendOutputsConverter.cpp index 9b8fb60d39c..f048aa0d96f 100644 --- a/lib/Frontend/ArgsToFrontendOutputsConverter.cpp +++ b/lib/Frontend/ArgsToFrontendOutputsConverter.cpp @@ -21,7 +21,7 @@ #include "swift/Option/SanitizerOptions.h" #include "swift/Strings.h" #include "llvm/ADT/STLExtras.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/Option.h" diff --git a/lib/Frontend/CompileJobCacheResult.cpp b/lib/Frontend/CompileJobCacheResult.cpp index 55c3f0476f8..3f3e5fbeb6c 100644 --- a/lib/Frontend/CompileJobCacheResult.cpp +++ b/lib/Frontend/CompileJobCacheResult.cpp @@ -74,7 +74,7 @@ CompileJobCacheResult::Output CompileJobCacheResult::getOutput(size_t I) const { return Output{getOutputObject(I), getOutputKind(I)}; } -Optional +std::optional CompileJobCacheResult::getOutput(file_types::ID Kind) const { size_t Count = getNumOutputs(); for (size_t I = 0; I < Count; ++I) { @@ -82,7 +82,7 @@ CompileJobCacheResult::getOutput(file_types::ID Kind) const { if (Kind == K) return Output{getOutputObject(I), Kind}; } - return None; + return {}; } Error CompileJobCacheResult::print(llvm::raw_ostream &OS) { diff --git a/lib/Frontend/CompilerInvocation.cpp b/lib/Frontend/CompilerInvocation.cpp index df2cc78828c..e7f82765b14 100644 --- a/lib/Frontend/CompilerInvocation.cpp +++ b/lib/Frontend/CompilerInvocation.cpp @@ -23,7 +23,7 @@ #include "swift/Strings.h" #include "swift/SymbolGraphGen/SymbolGraphOptions.h" #include "llvm/ADT/STLExtras.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/Option.h" @@ -269,6 +269,10 @@ setIRGenOutputOptsFromFrontendOptions(IRGenOptions &IRGenOpts, } }(FrontendOpts.RequestedAction); + IRGenOpts.UseCASBackend = FrontendOpts.UseCASBackend; + IRGenOpts.CASObjMode = FrontendOpts.CASObjMode; + IRGenOpts.EmitCASIDFile = FrontendOpts.EmitCASIDFile; + // If we're in JIT mode, set the requisite flags. if (FrontendOpts.RequestedAction == FrontendOptions::ActionType::Immediate) { IRGenOpts.UseJIT = true; @@ -1484,8 +1488,7 @@ static bool ValidateModulesOnceOptions(const ClangImporterOptions &Opts, return false; } -static bool ParseClangImporterArgs(ClangImporterOptions &Opts, - ArgList &Args, +static bool ParseClangImporterArgs(ClangImporterOptions &Opts, ArgList &Args, DiagnosticEngine &Diags, StringRef workingDirectory, const LangOptions &LangOpts, diff --git a/lib/Frontend/Frontend.cpp b/lib/Frontend/Frontend.cpp index 625324988b9..ac7cbbae2e8 100644 --- a/lib/Frontend/Frontend.cpp +++ b/lib/Frontend/Frontend.cpp @@ -44,7 +44,7 @@ #include "llvm/ADT/Hashing.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/SmallVector.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/CAS/ActionCache.h" #include "llvm/CAS/BuiltinUnifiedCASDatabases.h" #include "llvm/CAS/CASFileSystem.h" @@ -425,7 +425,7 @@ void CompilerInstance::setupDependencyTrackerIfNeeded() { bool CompilerInstance::setupCASIfNeeded(ArrayRef Args) { const auto &Opts = getInvocation().getFrontendOptions(); - if (!Opts.EnableCaching) + if (!getInvocation().requiresCAS()) return false; auto MaybeDB= Opts.CASOpts.getOrCreateDatabases(); diff --git a/lib/Frontend/PrintingDiagnosticConsumer.cpp b/lib/Frontend/PrintingDiagnosticConsumer.cpp index a7c8da2fb17..838d1f192ae 100644 --- a/lib/Frontend/PrintingDiagnosticConsumer.cpp +++ b/lib/Frontend/PrintingDiagnosticConsumer.cpp @@ -29,6 +29,7 @@ #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/raw_ostream.h" #include +#include using namespace swift; using namespace swift::markup; @@ -436,7 +437,7 @@ void PrintingDiagnosticConsumer::queueBuffer( parentID, positionInParent); queuedBuffers[bufferID] = sourceFile; } -#endif +#endif // SWIFT_BUILD_SWIFT_SYNTAX // MARK: Main DiagnosticConsumer entrypoint. void PrintingDiagnosticConsumer::handleDiagnostic(SourceManager &SM, diff --git a/lib/FrontendTool/FrontendTool.cpp b/lib/FrontendTool/FrontendTool.cpp index 573b2573d67..e143d9ebe47 100644 --- a/lib/FrontendTool/FrontendTool.cpp +++ b/lib/FrontendTool/FrontendTool.cpp @@ -1706,6 +1706,7 @@ static bool generateCode(CompilerInstance &Instance, StringRef OutputFilename, std::unique_ptr TargetMachine = createTargetMachine(opts, Instance.getASTContext()); + TargetMachine->Options.MCOptions.CAS = Instance.getSharedCASInstance(); // Free up some compiler resources now that we have an IRModule. freeASTContextIfPossible(Instance); diff --git a/lib/IDETool/CompilerInvocation.cpp b/lib/IDETool/CompilerInvocation.cpp index f2027c6a123..e24de74d141 100644 --- a/lib/IDETool/CompilerInvocation.cpp +++ b/lib/IDETool/CompilerInvocation.cpp @@ -381,11 +381,11 @@ bool ide::initInvocationByClangArguments(ArrayRef ArgList, CCArgs.push_back(Entry); } - if (!ClangInvok->getLangOpts()->isCompilingModule()) { + if (!ClangInvok->getLangOpts().isCompilingModule()) { CCArgs.push_back("-Xclang"); llvm::SmallString<64> Str; Str += "-fmodule-name="; - Str += ClangInvok->getLangOpts()->CurrentModule; + Str += ClangInvok->getLangOpts().CurrentModule; CCArgs.push_back(std::string(Str.str())); } diff --git a/lib/IDETool/DependencyChecking.h b/lib/IDETool/DependencyChecking.h index dcaf9caf92b..4798f1373b9 100644 --- a/lib/IDETool/DependencyChecking.h +++ b/lib/IDETool/DependencyChecking.h @@ -11,6 +11,7 @@ //===----------------------------------------------------------------------===// #include "swift/Basic/LLVM.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/Chrono.h" #include "llvm/Support/VirtualFileSystem.h" diff --git a/lib/IRGen/APIGen.h b/lib/IRGen/APIGen.h index fcaff1d31a5..dc71350192b 100644 --- a/lib/IRGen/APIGen.h +++ b/lib/IRGen/APIGen.h @@ -18,7 +18,7 @@ #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSet.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/Error.h" diff --git a/lib/IRGen/Address.h b/lib/IRGen/Address.h index d5019932d07..f7901f81ddc 100644 --- a/lib/IRGen/Address.h +++ b/lib/IRGen/Address.h @@ -43,9 +43,6 @@ public: if (addr == llvm::DenseMapInfo::getEmptyKey() || llvm::DenseMapInfo::getTombstoneKey()) return; - assert(llvm::cast(addr->getType()) - ->isOpaqueOrPointeeTypeMatches(elementType) && - "Incorrect pointer element type"); assert(addr != nullptr && "building an invalid address"); } diff --git a/lib/IRGen/CMakeLists.txt b/lib/IRGen/CMakeLists.txt index 7d1241b7cec..f0f90c03c77 100644 --- a/lib/IRGen/CMakeLists.txt +++ b/lib/IRGen/CMakeLists.txt @@ -70,7 +70,9 @@ add_swift_host_library(swiftIRGen STATIC LLVM_LINK_COMPONENTS target + targetparser transformutils + irprinter ) target_link_libraries(swiftIRGen INTERFACE clangCodeGen diff --git a/lib/IRGen/Callee.h b/lib/IRGen/Callee.h index 207235ac222..7ff6094f3c5 100644 --- a/lib/IRGen/Callee.h +++ b/lib/IRGen/Callee.h @@ -363,9 +363,6 @@ namespace irgen { llvm::Type *awaitSignature = nullptr) : kind(kind), Value(value), SecondaryValue(secondaryValue), AuthInfo(authInfo), Sig(signature), awaitSignature(awaitSignature) { - // The function pointer should have function type. - assert(!value->getContext().supportsTypedPointers() || - value->getType()->getNonOpaquePointerElementType()->isFunctionTy()); // TODO: maybe assert similarity to signature.getType()? if (authInfo) { if (kind == Kind::Function) { diff --git a/lib/IRGen/EnumPayload.cpp b/lib/IRGen/EnumPayload.cpp index 7a6c372833c..d55b20ecae3 100644 --- a/lib/IRGen/EnumPayload.cpp +++ b/lib/IRGen/EnumPayload.cpp @@ -321,7 +321,7 @@ void EnumPayload::emitSwitch(IRGenFunction &IGF, // Otherwise emit a switch statement. auto &C = IGF.IGM.getLLVMContext(); - unsigned numBits = mask.countPopulation(); + unsigned numBits = mask.popcount(); auto target = emitGatherSpareBits(IGF, SpareBitVector::fromAPInt(mask), 0, numBits); auto swi = IGF.Builder.CreateSwitch(target, dflt.getPointer(), cases.size()); @@ -514,7 +514,7 @@ void EnumPayload::emitScatterBits(IRGenModule &IGM, auto &DL = IGM.DataLayout; unsigned valueBits = DL.getTypeSizeInBits(value->getType()); - auto totalBits = std::min(valueBits, mask.countPopulation()); + auto totalBits = std::min(valueBits, mask.popcount()); auto maskReader = BitPatternReader(getLowestNSetBits(mask, totalBits), DL.isLittleEndian()); auto usedBits = 0u; @@ -529,7 +529,7 @@ void EnumPayload::emitScatterBits(IRGenModule &IGM, } // Calculate the number of bits we are going to scatter. - auto partCount = partMask.countPopulation(); + auto partCount = partMask.popcount(); // Scatter bits from the source into the bits specified by the mask. auto offset = usedBits; @@ -573,7 +573,7 @@ EnumPayload::emitGatherSpareBits(IRGenFunction &IGF, auto mask = getLowestNSetBits(spareBits.asAPInt(), resultBitWidth - firstBitOffset); - auto bitWidth = mask.countPopulation(); + auto bitWidth = mask.popcount(); auto spareBitReader = BitPatternReader(std::move(mask), DL.isLittleEndian()); auto usedBits = firstBitOffset; @@ -590,7 +590,7 @@ EnumPayload::emitGatherSpareBits(IRGenFunction &IGF, // Slice the spare bit vector. unsigned size = DL.getTypeSizeInBits(v->getType()); auto spareBitsPart = spareBitReader.read(size); - unsigned numBitsInPart = spareBitsPart.countPopulation(); + unsigned numBitsInPart = spareBitsPart.popcount(); // If there were no spare bits in this part, it has nothing to add. if (numBitsInPart == 0) diff --git a/lib/IRGen/GenArchetype.cpp b/lib/IRGen/GenArchetype.cpp index 9fea7046fc0..f9ab66a9dde 100644 --- a/lib/IRGen/GenArchetype.cpp +++ b/lib/IRGen/GenArchetype.cpp @@ -492,7 +492,7 @@ MetadataResponse irgen::emitOpaqueTypeMetadataRef(IRGenFunction &IGF, {request.get(IGF), genericArgs, descriptor, indexValue}); result->setDoesNotThrow(); result->setCallingConv(IGF.IGM.SwiftCC); - result->addFnAttr(llvm::Attribute::ReadOnly); + result->setOnlyReadsMemory(); }); assert(result); @@ -556,7 +556,7 @@ llvm::Value *irgen::emitOpaqueTypeWitnessTableRef(IRGenFunction &IGF, {genericArgs, descriptor, indexValue}); result->setDoesNotThrow(); result->setCallingConv(IGF.IGM.SwiftCC); - result->addFnAttr(llvm::Attribute::ReadOnly); + result->setOnlyReadsMemory(); }); assert(result); diff --git a/lib/IRGen/GenCall.cpp b/lib/IRGen/GenCall.cpp index 9df078482f3..e9e37af35f5 100644 --- a/lib/IRGen/GenCall.cpp +++ b/lib/IRGen/GenCall.cpp @@ -850,9 +850,9 @@ NativeConventionSchema::getCoercionTypes( paddingSize.getQuantity()); elts.push_back(padding); } - if (!packed && - !begin.isMultipleOf(clang::CharUnits::fromQuantity( - IGM.DataLayout.getABITypeAlignment(type)))) + + if (!packed && !begin.isMultipleOf(clang::CharUnits::fromQuantity( + IGM.DataLayout.getABITypeAlign(type)))) packed = true; elts.push_back(type); expandedTyIndicesMap.push_back(idx - 1); @@ -891,7 +891,7 @@ NativeConventionSchema::getCoercionTypes( } if (!packed && !begin.isMultipleOf(clang::CharUnits::fromQuantity( - IGM.DataLayout.getABITypeAlignment(type)))) + IGM.DataLayout.getABITypeAlign(type)))) packed = true; elts.push_back(type); expandedTyIndicesMap.push_back(idx - 1); @@ -1151,10 +1151,10 @@ namespace { case clang::BuiltinType::OCLIntelSubgroupAVCImeResult: case clang::BuiltinType::OCLIntelSubgroupAVCRefResult: case clang::BuiltinType::OCLIntelSubgroupAVCSicResult: - case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleRefStreamout: - case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualRefStreamout: - case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleRefStreamin: - case clang::BuiltinType::OCLIntelSubgroupAVCImeDualRefStreamin: + case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleReferenceStreamout: + case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualReferenceStreamout: + case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleReferenceStreamin: + case clang::BuiltinType::OCLIntelSubgroupAVCImeDualReferenceStreamin: llvm_unreachable("OpenCL type in ABI lowering"); // We should never see ARM SVE types at all. @@ -1172,6 +1172,10 @@ namespace { #include "clang/Basic/RISCVVTypes.def" llvm_unreachable("RISC-V V type in ABI lowering"); +#define WASM_TYPE(Name, Id, Size) case clang::BuiltinType::Id: +#include "clang/Basic/WebAssemblyReferenceTypes.def" + llvm_unreachable("WASM type in ABI lowering"); + // Handle all the integer types as opaque values. #define BUILTIN_TYPE(Id, SingletonId) #define SIGNED_TYPE(Id, SingletonId) \ @@ -4841,7 +4845,7 @@ Address IRGenFunction::getCallerTypedErrorResultSlot() { /// insertion point that most blocks should be inserted before. void IRGenFunction::emitBBForReturn() { ReturnBB = createBasicBlock("return"); - CurFn->getBasicBlockList().push_back(ReturnBB); + CurFn->insert(CurFn->end(), ReturnBB); } llvm::BasicBlock *IRGenFunction::createExceptionUnwindBlock() { @@ -4882,8 +4886,8 @@ void IRGenFunction::createExceptionTrapScope( void IRGenFunction::emitPrologue() { // Set up the IRBuilder. llvm::BasicBlock *EntryBB = createBasicBlock("entry"); - assert(CurFn->getBasicBlockList().empty() && "prologue already emitted?"); - CurFn->getBasicBlockList().push_back(EntryBB); + assert(CurFn->empty() && "prologue already emitted?"); + CurFn->insert(CurFn->end(), EntryBB); Builder.SetInsertPoint(EntryBB); // Set up the alloca insertion point. @@ -4980,7 +4984,7 @@ void IRGenFunction::emitEpilogue() { CurFn->setPersonalityFn(IGM.getForeignExceptionHandlingPersonalityFunc()); } for (auto *bb : ExceptionUnwindBlocks) - CurFn->getBasicBlockList().push_back(bb); + CurFn->insert(CurFn->end(), bb); } std::pair @@ -4996,10 +5000,10 @@ irgen::allocateForCoercion(IRGenFunction &IGF, ? fromTy : toTy; - auto alignment = std::max(DL.getABITypeAlignment(fromTy), - DL.getABITypeAlignment(toTy)); + llvm::Align alignment = + std::max(DL.getABITypeAlign(fromTy), DL.getABITypeAlign(toTy)); - auto buffer = IGF.createAlloca(bufferTy, Alignment(alignment), + auto buffer = IGF.createAlloca(bufferTy, Alignment(alignment.value()), basename + ".coerced"); Size size(std::max(fromSize, toSize)); diff --git a/lib/IRGen/GenControl.cpp b/lib/IRGen/GenControl.cpp index 3476f6837b7..413eb889543 100644 --- a/lib/IRGen/GenControl.cpp +++ b/lib/IRGen/GenControl.cpp @@ -28,7 +28,7 @@ void IRBuilder::emitBlock(llvm::BasicBlock *BB) { assert(ClearedIP == nullptr); llvm::BasicBlock *CurBB = GetInsertBlock(); assert(CurBB && "current insertion point is invalid"); - CurBB->getParent()->getBasicBlockList().insertAfter(CurBB->getIterator(), BB); + CurBB->getParent()->insert(std::next(CurBB->getIterator()), BB); IRBuilderBase::SetInsertPoint(BB); } diff --git a/lib/IRGen/GenDecl.cpp b/lib/IRGen/GenDecl.cpp index e82c7a39699..daccf7d168e 100644 --- a/lib/IRGen/GenDecl.cpp +++ b/lib/IRGen/GenDecl.cpp @@ -1252,12 +1252,6 @@ static bool isLazilyEmittedFunction(SILFunction &f, SILModule &m) { if (f.getDynamicallyReplacedFunction()) return false; - // Needed by lldb to print global variables which are propagated by the - // mandatory GlobalOpt. - if (m.getOptions().OptMode == OptimizationMode::NoOptimization && - f.isGlobalInit()) - return false; - return true; } @@ -2930,8 +2924,10 @@ static void addLLVMFunctionAttributes(SILFunction *f, Signature &signature) { } if (isReadOnlyFunction(f)) { - attrs = attrs.addFnAttribute(signature.getType()->getContext(), - llvm::Attribute::ReadOnly); + auto &ctx = signature.getType()->getContext(); + attrs = + attrs.addFnAttribute(ctx, llvm::Attribute::getWithMemoryEffects( + ctx, llvm::MemoryEffects::readOnly())); } } @@ -3570,6 +3566,7 @@ llvm::Function *IRGenModule::getAddrOfSILFunction( // Mark as llvm.used if @_used, set section if @_section if (f->markedAsUsed()) addUsedGlobal(fn); + if (!f->section().empty()) fn->setSection(f->section()); @@ -3585,6 +3582,11 @@ llvm::Function *IRGenModule::getAddrOfSILFunction( } fn->addFnAttrs(attrBuilder); + // Also mark as llvm.used any functions that should be kept for the debugger. + // Only definitions should be kept. + if (f->shouldBePreservedForDebugger() && !fn->isDeclaration()) + addUsedGlobal(fn); + // If `hasCReferences` is true, then the function is either marked with // @_silgen_name OR @_cdecl. If it is the latter, it must have a definition // associated with it. The combination of the two allows us to identify the diff --git a/lib/IRGen/GenDistributed.cpp b/lib/IRGen/GenDistributed.cpp index 9f3631f3f31..437644d3a8e 100644 --- a/lib/IRGen/GenDistributed.cpp +++ b/lib/IRGen/GenDistributed.cpp @@ -40,6 +40,8 @@ #include "swift/AST/ProtocolConformanceRef.h" #include "swift/IRGen/Linking.h" #include "swift/SIL/SILFunction.h" +#include "llvm/IR/DataLayout.h" +#include "llvm/Support/Alignment.h" using namespace swift; using namespace irgen; @@ -363,14 +365,14 @@ void DistributedAccessor::decodeArguments(const ArgumentDecoderInfo &decoder, continue; } - auto offset = + Size offset = Size(i * IGM.DataLayout.getTypeAllocSize(IGM.TypeMetadataPtrTy)); - auto alignment = IGM.DataLayout.getABITypeAlignment(IGM.TypeMetadataPtrTy); + llvm::Align alignment = IGM.DataLayout.getABITypeAlign(IGM.TypeMetadataPtrTy); // Load metadata describing argument value from argument types buffer. auto typeLoc = IGF.emitAddressAtOffset( argumentTypes, Offset(offset), IGM.TypeMetadataPtrTy, - Alignment(alignment), "arg_type_loc"); + Alignment(alignment.value()), "arg_type_loc"); auto *argumentTy = IGF.Builder.CreateLoad(typeLoc, "arg_type"); @@ -719,12 +721,12 @@ void DistributedAccessor::emit() { for (unsigned index = 0; index < expandedSignature.numTypeMetadataPtrs; ++index) { auto offset = Size(index * IGM.DataLayout.getTypeAllocSize(IGM.TypeMetadataPtrTy)); - auto alignment = - IGM.DataLayout.getABITypeAlignment(IGM.TypeMetadataPtrTy); + llvm::Align alignment = + IGM.DataLayout.getABITypeAlign(IGM.TypeMetadataPtrTy); - auto substitution = - IGF.emitAddressAtOffset(substitutionBuffer, Offset(offset), - IGM.TypeMetadataPtrTy, Alignment(alignment)); + auto substitution = IGF.emitAddressAtOffset( + substitutionBuffer, Offset(offset), IGM.TypeMetadataPtrTy, + Alignment(alignment.value())); arguments.add(IGF.Builder.CreateLoad(substitution, "substitution")); } diff --git a/lib/IRGen/GenEnum.cpp b/lib/IRGen/GenEnum.cpp index af95df70160..40f4af334da 100644 --- a/lib/IRGen/GenEnum.cpp +++ b/lib/IRGen/GenEnum.cpp @@ -1071,7 +1071,7 @@ namespace { APInt getFixedExtraInhabitantMask(IRGenModule &IGM) const override { - return APInt::getAllOnesValue(cast(TI)->getFixedSize() + return APInt::getAllOnes(cast(TI)->getFixedSize() .getValueInBits()); } }; @@ -2045,7 +2045,7 @@ namespace { ElementsWithNoPayload.size() != extraInhabitantCount + 1) { payloadResult = payload.emitCompare( IGF, - extraInhabitantCount == 0 ? APInt::getAllOnesValue(PayloadBitCount) + extraInhabitantCount == 0 ? APInt::getAllOnes(PayloadBitCount) : ti.getFixedExtraInhabitantMask(IGF.IGM), payloadTag); } @@ -2221,7 +2221,7 @@ namespace { // FIXME: Provide a mask to only match the bits in the payload // whose extra inhabitants differ. - payload.emitSwitch(IGF, APInt::getAllOnesValue(PayloadBitCount), + payload.emitSwitch(IGF, APInt::getAllOnes(PayloadBitCount), cases, SwitchDefaultDest(unreachableBB, IsUnreachable)); } @@ -3468,7 +3468,7 @@ namespace { unsigned totalSize = cast(TI)->getFixedSize().getValueInBits(); if (payloadTI.isKnownEmpty(ResilienceExpansion::Maximal)) - return APInt::getAllOnesValue(totalSize); + return APInt::getAllOnes(totalSize); auto baseMask = getFixedPayloadTypeInfo().getFixedExtraInhabitantMask(IGM); auto mask = BitPatternBuilder(IGM.Triple.isLittleEndian()); @@ -3501,7 +3501,7 @@ namespace { Size size = cast(TI)->getFixedSize(); auto mask = BitPatternBuilder(IGM.Triple.isLittleEndian()); if (Size payloadSize = payloadTI.getFixedSize()) { - auto payloadMask = APInt::getNullValue(payloadSize.getValueInBits()); + auto payloadMask = APInt::getZero(payloadSize.getValueInBits()); if (getNumExtraInhabitantTagValues() > 0) payloadMask |= payloadTI.getFixedExtraInhabitantMask(IGM); if (ExtraTagBitCount > 0) @@ -3952,7 +3952,7 @@ namespace { IGM.getGetEnumCaseMultiPayloadFunctionPointer(), {addr.getAddress(), metadata}); call->setDoesNotThrow(); - call->addFnAttr(llvm::Attribute::ReadOnly); + call->setOnlyReadsMemory(); return call; } @@ -4129,7 +4129,7 @@ namespace { llvm::Value *match = IGF.Builder.CreateICmpEQ(parts.tag, tagValue); if (!CommonSpareBits.empty()) { auto payloadMatch = parts.payload - .emitCompare(IGF, APInt::getAllOnesValue(CommonSpareBits.size()), + .emitCompare(IGF, APInt::getAllOnes(CommonSpareBits.size()), payloadValue); match = IGF.Builder.CreateAnd(match, payloadMatch); } @@ -4243,7 +4243,7 @@ namespace { IGF.Builder.emitBlock(tagBB); - parts.payload.emitSwitch(IGF, APInt::getAllOnesValue(PayloadBitCount), + parts.payload.emitSwitch(IGF, APInt::getAllOnes(PayloadBitCount), cases, SwitchDefaultDest(defaultDest, isUnreachable)); } @@ -7314,7 +7314,7 @@ llvm::Value *irgen::emitGatherBits(IRGenFunction &IGF, result = result ? B.CreateOr(result, part) : part; // Update the offset and remaining mask. - usedBits += partMask.countPopulation(); + usedBits += partMask.popcount(); } return result; } @@ -7360,7 +7360,7 @@ llvm::Value *irgen::emitScatterBits(IRGenModule &IGM, // example we could take into account the packedLowBit. auto unknownBits = std::min(sourceTy->getBitWidth(), bitSize); bool needMask = !(mask.isShiftedMask() && - mask.countPopulation() >= unknownBits); + mask.popcount() >= unknownBits); // Shift each set of contiguous set bits into position and // accumulate them into the result. @@ -7391,7 +7391,7 @@ llvm::Value *irgen::emitScatterBits(IRGenModule &IGM, result = result ? builder.CreateOr(result, part) : part; // Update the offset and remaining mask. - usedBits += partMask.countPopulation(); + usedBits += partMask.popcount(); } return result; } @@ -7400,7 +7400,7 @@ llvm::Value *irgen::emitScatterBits(IRGenModule &IGM, llvm::APInt irgen::gatherBits(const llvm::APInt &mask, const llvm::APInt &value) { assert(mask.getBitWidth() == value.getBitWidth()); - llvm::APInt result = llvm::APInt(mask.countPopulation(), 0); + llvm::APInt result = llvm::APInt(mask.popcount(), 0); unsigned j = 0; for (unsigned i = 0; i < mask.getBitWidth(); ++i) { if (!mask[i]) { diff --git a/lib/IRGen/GenHasSymbol.cpp b/lib/IRGen/GenHasSymbol.cpp index 5d507ff4f80..a8214d61095 100644 --- a/lib/IRGen/GenHasSymbol.cpp +++ b/lib/IRGen/GenHasSymbol.cpp @@ -176,7 +176,7 @@ llvm::Function *IRGenModule::emitHasSymbolFunction(ValueDecl *decl) { func->setDoesNotThrow(); func->setCallingConv(DefaultCC); - func->addFnAttr(llvm::Attribute::ReadOnly); + func->setOnlyReadsMemory(); return func; } diff --git a/lib/IRGen/GenHeap.cpp b/lib/IRGen/GenHeap.cpp index dabd8c000fe..41c5b589956 100644 --- a/lib/IRGen/GenHeap.cpp +++ b/lib/IRGen/GenHeap.cpp @@ -713,7 +713,7 @@ APInt IRGenModule::getReferenceStorageExtraInhabitantMask( case ReferenceCounting::Error: llvm_unreachable("Unsupported reference-counting style"); } - return APInt::getAllOnesValue(getPointerSize().getValueInBits()); + return APInt::getAllOnes(getPointerSize().getValueInBits()); } llvm::Value *IRGenFunction::getReferenceStorageExtraInhabitantIndex(Address src, @@ -1999,7 +1999,7 @@ emitHeapMetadataRefForUnknownHeapObject(IRGenFunction &IGF, metadata->setName(object->getName() + ".Type"); metadata->setCallingConv(IGF.IGM.getOptions().PlatformCCallingConvention); metadata->setDoesNotThrow(); - metadata->addFnAttr(llvm::Attribute::ReadOnly); + metadata->setOnlyReadsMemory(); return metadata; } diff --git a/lib/IRGen/GenIntegerLiteral.cpp b/lib/IRGen/GenIntegerLiteral.cpp index 94a5852e7a4..8fbbbdc4095 100644 --- a/lib/IRGen/GenIntegerLiteral.cpp +++ b/lib/IRGen/GenIntegerLiteral.cpp @@ -154,7 +154,7 @@ ConstantIntegerLiteralMap::get(IRGenModule &IGM, APInt &&value) { auto &entry = map[value]; if (entry.Data) return entry; - assert(value.getMinSignedBits() == value.getBitWidth() && + assert(value.getSignificantBits() == value.getBitWidth() && "expected IntegerLiteral value to be maximally compact"); // We're going to break the value down into pointer-sized chunks. diff --git a/lib/IRGen/GenMeta.cpp b/lib/IRGen/GenMeta.cpp index cb48dfc8866..bc1c4954ed1 100644 --- a/lib/IRGen/GenMeta.cpp +++ b/lib/IRGen/GenMeta.cpp @@ -6138,7 +6138,7 @@ namespace { IGF.IGM.getGetForeignTypeMetadataFunctionPointer(), {request.get(IGF), candidate}); call->addFnAttr(llvm::Attribute::NoUnwind); - call->addFnAttr(llvm::Attribute::ReadNone); + call->setDoesNotAccessMemory(); return MetadataResponse::handle(IGF, request, call); }); diff --git a/lib/IRGen/GenObjC.cpp b/lib/IRGen/GenObjC.cpp index f3e25ac7afd..42049cddb32 100644 --- a/lib/IRGen/GenObjC.cpp +++ b/lib/IRGen/GenObjC.cpp @@ -605,9 +605,8 @@ void IRGenModule::emitLazyObjCProtocolDefinition(ProtocolDecl *proto) { cast(ObjCProtocols.find(proto)->second.record); // Move the new record to the placeholder's position. - Module.getGlobalList().remove(record); - Module.getGlobalList().insertAfter(placeholder->getIterator(), record); - + Module.removeGlobalVariable(record); + Module.insertGlobalVariable(std::next(placeholder->getIterator()), record); // Replace and destroy the placeholder. placeholder->replaceAllUsesWith( llvm::ConstantExpr::getBitCast(record, Int8PtrTy)); diff --git a/lib/IRGen/GenOpaque.cpp b/lib/IRGen/GenOpaque.cpp index 7a1f1707625..abcbb008da5 100644 --- a/lib/IRGen/GenOpaque.cpp +++ b/lib/IRGen/GenOpaque.cpp @@ -182,7 +182,9 @@ static llvm::AttributeList getValueWitnessAttrs(IRGenModule &IGM, return attrs.addParamAttribute(ctx, 0, llvm::Attribute::NoAlias); case ValueWitness::GetEnumTagSinglePayload: - return attrs.addFnAttribute(ctx, llvm::Attribute::ReadOnly) + return attrs + .addFnAttribute(ctx, llvm::Attribute::getWithMemoryEffects( + ctx, llvm::MemoryEffects::readOnly())) .addParamAttribute(ctx, 0, llvm::Attribute::NoAlias); // These have two arguments and they don't alias each other. @@ -847,7 +849,7 @@ getGetEnumTagSinglePayloadTrampolineFn(IRGenModule &IGM) { true /*noinline*/); // This function is readonly. - cast(func)->addFnAttr(llvm::Attribute::ReadOnly); + cast(func)->setOnlyReadsMemory(); return func; } diff --git a/lib/IRGen/GenReflection.cpp b/lib/IRGen/GenReflection.cpp index fa10becdc87..301f0fe9b9e 100644 --- a/lib/IRGen/GenReflection.cpp +++ b/lib/IRGen/GenReflection.cpp @@ -714,13 +714,6 @@ protected: return var; } - // Helpers to guide the C++ type system into converting lambda arguments - // to llvm::Optional - llvm::GlobalVariable *emit(llvm::function_ref getAddr, - const char *section) { - return emit(llvm::Optional>(getAddr), - section); - } llvm::GlobalVariable *emit(llvm::NoneType none, const char *section) { return emit(llvm::Optional>(), section); diff --git a/lib/IRGen/GenType.cpp b/lib/IRGen/GenType.cpp index 8f2463258c2..1e46b739fe4 100644 --- a/lib/IRGen/GenType.cpp +++ b/lib/IRGen/GenType.cpp @@ -934,7 +934,7 @@ FixedTypeInfo::storeSpareBitExtraInhabitant(IRGenFunction &IGF, occupiedIndex = index; spareIndex = spareBitBias; } else { - auto occupiedBitMask = APInt::getAllOnesValue(occupiedBitCount); + auto occupiedBitMask = APInt::getAllOnes(occupiedBitCount); occupiedBitMask = occupiedBitMask.zext(32); auto occupiedBitMaskValue = llvm::ConstantInt::get(C, occupiedBitMask); occupiedIndex = IGF.Builder.CreateAnd(index, occupiedBitMaskValue); @@ -2171,7 +2171,7 @@ convertPrimitiveBuiltin(IRGenModule &IGM, CanType canTy) { case BuiltinFloatType::IEEE80: { llvm::Type *floatTy = llvm::Type::getX86_FP80Ty(ctx); uint64_t ByteSize = IGM.DataLayout.getTypeAllocSize(floatTy); - unsigned align = IGM.DataLayout.getABITypeAlignment(floatTy); + unsigned align = IGM.DataLayout.getABITypeAlign(floatTy).value(); return RetTy{ floatTy, Size(ByteSize), Alignment(align) }; } case BuiltinFloatType::IEEE128: diff --git a/lib/IRGen/GenValueWitness.cpp b/lib/IRGen/GenValueWitness.cpp index 269ae3d9777..01869a28fcb 100644 --- a/lib/IRGen/GenValueWitness.cpp +++ b/lib/IRGen/GenValueWitness.cpp @@ -925,8 +925,8 @@ static llvm::Constant *getEnumTagFunction(IRGenModule &IGM, auto shiftedMask = mask.lshr(tzCount); auto toCount = shiftedMask.countTrailingOnes(); if (payloadTI.mayHaveExtraInhabitants(IGM) && - (mask.countPopulation() > 64 || - toCount != mask.countPopulation() || + (mask.popcount() > 64 || + toCount != mask.popcount() || (tzCount % toCount != 0))) { return IGM.getEnumFnGetEnumTagFn(); } else { @@ -962,7 +962,7 @@ getDestructiveInjectEnumTagFunction(IRGenModule &IGM, auto shiftedMask = mask.lshr(tzCount); auto toCount = shiftedMask.countTrailingOnes(); if (payloadTI.mayHaveExtraInhabitants(IGM) && - (mask.countPopulation() > 64 || toCount != mask.countPopulation() || + (mask.popcount() > 64 || toCount != mask.popcount() || (tzCount % toCount != 0))) { return nullptr; } else { diff --git a/lib/IRGen/IRGen.cpp b/lib/IRGen/IRGen.cpp index a96c40a6fd1..0dd2b50af2e 100644 --- a/lib/IRGen/IRGen.cpp +++ b/lib/IRGen/IRGen.cpp @@ -29,6 +29,7 @@ #include "swift/Basic/Dwarf.h" #include "swift/Basic/MD5Stream.h" #include "swift/Basic/Platform.h" +#include "swift/Basic/STLExtras.h" #include "swift/Basic/Statistic.h" #include "swift/Basic/Version.h" #include "swift/ClangImporter/ClangImporter.h" @@ -55,7 +56,7 @@ #include "llvm/CodeGen/TargetSubtargetInfo.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" -#include "llvm/IR/IRPrintingPasses.h" +#include "llvm/IRPrinter/IRPrintingPasses.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" @@ -63,7 +64,7 @@ #include "llvm/IR/ValueSymbolTable.h" #include "llvm/IR/Verifier.h" #include "llvm/Linker/Linker.h" -#include "llvm/MC/SubtargetFeature.h" +#include "llvm/TargetParser/SubtargetFeature.h" #include "llvm/MC/TargetRegistry.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Passes/PassBuilder.h" @@ -80,7 +81,6 @@ #include "llvm/Target/TargetMachine.h" #include "llvm/Transforms/IPO.h" #include "llvm/Transforms/IPO/AlwaysInliner.h" -#include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/Transforms/IPO/ThinLTOBitcodeWriter.h" #include "llvm/Transforms/Instrumentation.h" #include "llvm/Transforms/Instrumentation/AddressSanitizer.h" @@ -128,6 +128,12 @@ swift::getIRTargetOptions(const IRGenOptions &Opts, ASTContext &Ctx) { TargetOpts.DebuggerTuning = llvm::DebuggerKind::LLDB; TargetOpts.FunctionSections = Opts.FunctionSections; + // Set option to UseCASBackend if CAS was enabled on the command line. + TargetOpts.UseCASBackend = Opts.UseCASBackend; + + // Set option to select the CASBackendMode. + TargetOpts.MCOptions.CASObjMode = Opts.CASObjMode; + auto *Clang = static_cast(Ctx.getClangModuleLoader()); // WebAssembly doesn't support atomics yet, see @@ -232,9 +238,9 @@ void swift::performLLVMOptimizations(const IRGenOptions &Opts, PrintPassOptions PrintPassOpts; PrintPassOpts.Indent = DebugPassStructure; PrintPassOpts.SkipAnalyses = DebugPassStructure; - StandardInstrumentations SI(DebugPassStructure, /*VerifyEach*/ false, - PrintPassOpts); - SI.registerCallbacks(PIC, &FAM); + StandardInstrumentations SI(Module->getContext(), DebugPassStructure, + /*VerifyEach*/ false, PrintPassOpts); + SI.registerCallbacks(PIC, &MAM); PassBuilder PB(TargetMachine, PTO, PGOOpt, &PIC); @@ -314,13 +320,6 @@ void swift::performLLVMOptimizations(const IRGenOptions &Opts, } }); } - if (RunSwiftSpecificLLVMOptzns) { - PB.registerOptimizerLastEPCallback([&](ModulePassManager &MPM, - OptimizationLevel Level) { - MPM.addPass( - createModuleToFunctionPassAdaptor(SwiftDbgAddrBlockSplitterPass())); - }); - } if (Opts.GenerateProfile) { InstrProfOptions options; @@ -378,7 +377,8 @@ void swift::performLLVMOptimizations(const IRGenOptions &Opts, case IRGenOutputKind::Module: break; case IRGenOutputKind::LLVMAssemblyAfterOptimization: - MPM.addPass(PrintModulePass(*out, "", false)); + MPM.addPass(PrintModulePass(*out, "", /*ShouldPreserveUseListOrder=*/false, + /*EmitSummaryIndex=*/false)); break; case IRGenOutputKind::LLVMBitcode: { // Emit a module summary by default for Regular LTO except ld64-based ones @@ -497,11 +497,11 @@ static void countStatsPostIRGen(UnifiedStatsReporter &Stats, const llvm::Module& Module) { auto &C = Stats.getFrontendCounters(); // FIXME: calculate these in constant time if possible. - C.NumIRGlobals += Module.getGlobalList().size(); + C.NumIRGlobals += Module.global_size(); C.NumIRFunctions += Module.getFunctionList().size(); - C.NumIRAliases += Module.getAliasList().size(); - C.NumIRIFuncs += Module.getIFuncList().size(); - C.NumIRNamedMetaData += Module.getNamedMDList().size(); + C.NumIRAliases += Module.alias_size(); + C.NumIRIFuncs += Module.ifunc_size(); + C.NumIRNamedMetaData += Module.named_metadata_size(); C.NumIRValueSymbols += Module.getValueSymbolTable().size(); C.NumIRComdatSymbols += Module.getComdatSymbolTable().size(); for (auto const &Func : Module) { @@ -608,17 +608,31 @@ bool swift::performLLVM(const IRGenOptions &Opts, if (OutputFilename.empty()) return false; + std::unique_ptr CASIDFile; + if (Opts.UseCASBackend && Opts.EmitCASIDFile && + Opts.CASObjMode != llvm::CASBackendMode::CASID && + Opts.OutputKind == IRGenOutputKind::ObjectFile && OutputFilename != "-") { + std::string OutputFilenameCASID = std::string(OutputFilename); + OutputFilenameCASID.append(".casid"); + std::error_code EC; + CASIDFile = std::make_unique(OutputFilenameCASID, EC); + if (EC) { + diagnoseSync(Diags, DiagMutex, SourceLoc(), diag::error_opening_output, + OutputFilename, std::move(EC.message())); + return true; + } + } + return compileAndWriteLLVM(Module, TargetMachine, Opts, Stats, Diags, - *OutputFile, DiagMutex); + *OutputFile, DiagMutex, + CASIDFile ? CASIDFile.get() : nullptr); } -bool swift::compileAndWriteLLVM(llvm::Module *module, - llvm::TargetMachine *targetMachine, - const IRGenOptions &opts, - UnifiedStatsReporter *stats, - DiagnosticEngine &diags, - llvm::raw_pwrite_stream &out, - llvm::sys::Mutex *diagMutex) { +bool swift::compileAndWriteLLVM( + llvm::Module *module, llvm::TargetMachine *targetMachine, + const IRGenOptions &opts, UnifiedStatsReporter *stats, + DiagnosticEngine &diags, llvm::raw_pwrite_stream &out, + llvm::sys::Mutex *diagMutex, llvm::raw_pwrite_stream *casid) { // Set up the final code emission pass. Bitcode/LLVM IR is emitted as part of // the optimization pass pipeline. @@ -642,8 +656,8 @@ bool swift::compileAndWriteLLVM(llvm::Module *module, EmitPasses.add(createTargetTransformInfoWrapperPass( targetMachine->getTargetIRAnalysis())); - bool fail = targetMachine->addPassesToEmitFile(EmitPasses, out, nullptr, - FileType, !opts.Verify); + bool fail = targetMachine->addPassesToEmitFile( + EmitPasses, out, nullptr, FileType, !opts.Verify, nullptr, casid); if (fail) { diagnoseSync(diags, diagMutex, SourceLoc(), diag::error_codegen_init_fail); @@ -1476,13 +1490,13 @@ static void performParallelIRGeneration(IRGenDescriptor desc) { G.setLinkage(GlobalValue::ExternalLinkage); } }; - for (llvm::GlobalVariable &G : M->getGlobalList()) { + for (llvm::GlobalVariable &G : M->globals()) { collectReference(G); } for (llvm::Function &F : M->getFunctionList()) { collectReference(F); } - for (llvm::GlobalAlias &A : M->getAliasList()) { + for (llvm::GlobalAlias &A : M->aliases()) { collectReference(A); } } @@ -1502,13 +1516,13 @@ static void performParallelIRGeneration(IRGenDescriptor desc) { G.setLinkage(GlobalValue::WeakODRLinkage); } }; - for (llvm::GlobalVariable &G : M->getGlobalList()) { + for (llvm::GlobalVariable &G : M->globals()) { updateLinkage(G); } for (llvm::Function &F : M->getFunctionList()) { updateLinkage(F); } - for (llvm::GlobalAlias &A : M->getAliasList()) { + for (llvm::GlobalAlias &A : M->aliases()) { updateLinkage(A); } diff --git a/lib/IRGen/IRGenDebugInfo.cpp b/lib/IRGen/IRGenDebugInfo.cpp index 23946944901..7b72a4a4ccc 100644 --- a/lib/IRGen/IRGenDebugInfo.cpp +++ b/lib/IRGen/IRGenDebugInfo.cpp @@ -1190,7 +1190,7 @@ private: return createPointerSizedStruct(Scope, Name, FwdDecl, File, Line, Flags, MangledName); } else { - unsigned SizeInBits = CI.getTargetInfo().getPointerWidth(0); + unsigned SizeInBits = CI.getTargetInfo().getPointerWidth(clang::LangAS::Default); return createOpaqueStruct(Scope, Name, File, Line, SizeInBits, 0, Flags, MangledName); } @@ -1201,7 +1201,7 @@ private: llvm::DIFile *File, unsigned Line, llvm::DINode::DIFlags Flags, StringRef MangledName) { - unsigned PtrSize = CI.getTargetInfo().getPointerWidth(0); + unsigned PtrSize = CI.getTargetInfo().getPointerWidth(clang::LangAS::Default); auto PtrTy = DBuilder.createPointerType(PointeeTy, PtrSize, 0); llvm::Metadata *Elements[] = {DBuilder.createMemberType( Scope, "ptr", File, 0, PtrSize, 0, 0, Flags, PtrTy)}; @@ -1216,7 +1216,7 @@ private: llvm::DIType *PointeeTy, llvm::DIFile *File, unsigned Line, llvm::DINode::DIFlags Flags, StringRef MangledName) { - unsigned PtrSize = CI.getTargetInfo().getPointerWidth(0); + unsigned PtrSize = CI.getTargetInfo().getPointerWidth(clang::LangAS::Default); llvm::Metadata *Elements[] = { DBuilder.createMemberType( Scope, "ptr", File, 0, PtrSize, 0, 0, Flags, @@ -1232,7 +1232,7 @@ private: llvm::DIType *createFixedValueBufferStruct(llvm::DIType *PointeeTy) { unsigned Line = 0; - unsigned PtrSize = CI.getTargetInfo().getPointerWidth(0); + unsigned PtrSize = CI.getTargetInfo().getPointerWidth(clang::LangAS::Default); llvm::DINode::DIFlags Flags = llvm::DINode::FlagArtificial; llvm::DIFile *File = MainFile; llvm::DIScope *Scope = TheCU; @@ -1276,7 +1276,7 @@ private: auto FnTy = DBuilder.createSubroutineType(Params, Flags); llvm::DIType *DITy; if (FunTy->getRepresentation() == SILFunctionType::Representation::Thick) { - if (SizeInBits == 2 * CI.getTargetInfo().getPointerWidth(0)) + if (SizeInBits == 2 * CI.getTargetInfo().getPointerWidth(clang::LangAS::Default)) // This is a FunctionPairTy: { i8*, %swift.refcounted* }. DITy = createDoublePointerSizedStruct(Scope, MangledName, FnTy, MainFile, 0, Flags, MangledName); @@ -1285,7 +1285,7 @@ private: DITy = createOpaqueStruct(Scope, MangledName, MainFile, 0, SizeInBits, AlignInBits, Flags, MangledName); } else { - assert(SizeInBits == CI.getTargetInfo().getPointerWidth(0)); + assert(SizeInBits == CI.getTargetInfo().getPointerWidth(clang::LangAS::Default)); DITy = createPointerSizedStruct(Scope, MangledName, FnTy, MainFile, 0, Flags, MangledName); } @@ -1405,7 +1405,7 @@ private: } case TypeKind::BuiltinNativeObject: { - unsigned PtrSize = CI.getTargetInfo().getPointerWidth(0); + unsigned PtrSize = CI.getTargetInfo().getPointerWidth(clang::LangAS::Default); auto PTy = DBuilder.createPointerType(nullptr, PtrSize, 0, /* DWARFAddressSpace */ llvm::None, MangledName); @@ -1413,7 +1413,7 @@ private: } case TypeKind::BuiltinBridgeObject: { - unsigned PtrSize = CI.getTargetInfo().getPointerWidth(0); + unsigned PtrSize = CI.getTargetInfo().getPointerWidth(clang::LangAS::Default); auto PTy = DBuilder.createPointerType(nullptr, PtrSize, 0, /* DWARFAddressSpace */ llvm::None, MangledName); @@ -1421,21 +1421,21 @@ private: } case TypeKind::BuiltinRawPointer: { - unsigned PtrSize = CI.getTargetInfo().getPointerWidth(0); + unsigned PtrSize = CI.getTargetInfo().getPointerWidth(clang::LangAS::Default); return DBuilder.createPointerType(nullptr, PtrSize, 0, /* DWARFAddressSpace */ llvm::None, MangledName); } case TypeKind::BuiltinRawUnsafeContinuation: { - unsigned PtrSize = CI.getTargetInfo().getPointerWidth(0); + unsigned PtrSize = CI.getTargetInfo().getPointerWidth(clang::LangAS::Default); return DBuilder.createPointerType(nullptr, PtrSize, 0, /* DWARFAddressSpace */ llvm::None, MangledName); } case TypeKind::BuiltinJob: { - unsigned PtrSize = CI.getTargetInfo().getPointerWidth(0); + unsigned PtrSize = CI.getTargetInfo().getPointerWidth(clang::LangAS::Default); return DBuilder.createPointerType(nullptr, PtrSize, 0, /* DWARFAddressSpace */ llvm::None, MangledName); @@ -1494,7 +1494,7 @@ private: auto L = getFilenameAndLocation(*this, Decl); auto *File = getOrCreateFile(L.filename); unsigned FwdDeclLine = 0; - assert(SizeInBits == CI.getTargetInfo().getPointerWidth(0)); + assert(SizeInBits == CI.getTargetInfo().getPointerWidth(clang::LangAS::Default)); return createPointerSizedStruct(Scope, Decl->getNameStr(), File, FwdDeclLine, Flags, MangledName); } @@ -1529,7 +1529,7 @@ private: auto L = getFilenameAndLocation(*this, Decl); auto *File = getOrCreateFile(L.filename); unsigned FwdDeclLine = 0; - assert(SizeInBits == CI.getTargetInfo().getPointerWidth(0)); + assert(SizeInBits == CI.getTargetInfo().getPointerWidth(clang::LangAS::Default)); return createPointerSizedStruct(Scope, Decl ? Decl->getNameStr() : MangledName, File, FwdDeclLine, Flags, MangledName); @@ -1555,7 +1555,7 @@ private: // TODO: We may want to peek at Decl->isObjC() and set this // attribute accordingly. - assert(SizeInBits == CI.getTargetInfo().getPointerWidth(0)); + assert(SizeInBits == CI.getTargetInfo().getPointerWidth(clang::LangAS::Default)); return createPointerSizedStruct(Scope, Decl ? Decl->getNameStr() : MangledName, File, FwdDeclLine, Flags, MangledName); @@ -2769,7 +2769,7 @@ void IRGenDebugInfoImpl::emitVariableDeclaration( // Advance the offset for the next piece. OffsetInBits += SizeInBits; SizeInBits = IGM.DataLayout.getTypeSizeInBits(Piece->getType()); - AlignInBits = IGM.DataLayout.getABITypeAlignment(Piece->getType()); + AlignInBits = IGM.DataLayout.getABITypeAlign(Piece->getType()).value(); if (!AlignInBits) AlignInBits = SizeOfByte; @@ -2854,7 +2854,8 @@ struct DbgIntrinsicEmitter { llvm::Instruction *InsertBefore) { if (ForceDbgDeclare == AddrDbgInstrKind::DbgDeclare) return DIBuilder.insertDeclare(Addr, VarInfo, Expr, DL, InsertBefore); - return DIBuilder.insertDbgAddrIntrinsic(Addr, VarInfo, Expr, DL, + Expr = llvm::DIExpression::append(Expr, llvm::dwarf::DW_OP_deref); + return DIBuilder.insertDbgValueIntrinsic(Addr, VarInfo, Expr, DL, InsertBefore); } @@ -2864,7 +2865,8 @@ struct DbgIntrinsicEmitter { llvm::BasicBlock *Block) { if (ForceDbgDeclare == AddrDbgInstrKind::DbgDeclare) return DIBuilder.insertDeclare(Addr, VarInfo, Expr, DL, Block); - return DIBuilder.insertDbgAddrIntrinsic(Addr, VarInfo, Expr, DL, Block); + Expr = llvm::DIExpression::append(Expr, llvm::dwarf::DW_OP_deref); + return DIBuilder.insertDbgValueIntrinsic(Addr, VarInfo, Expr, DL, Block); } }; @@ -2959,15 +2961,15 @@ void IRGenDebugInfoImpl::emitDbgIntrinsic( InsertPt = &EntryBlock; } } else { - // For llvm.dbg.addr, we just want to insert the intrinsic at the current + // For llvm.dbg.value, we just want to insert the intrinsic at the current // insertion point. This is because our contract with the coroutine // splitter is that the coroutine splitter just needs to emit the - // llvm.dbg.addr where we placed them. It shouldn't move them or do + // llvm.dbg.value where we placed them. It shouldn't move them or do // anything special with it. Instead, we have previously inserted extra // debug_value clones previously after each instruction at the SIL level // that corresponds with a funclet edge. This operation effectively sets // up the rest of the pipeline to be stupid and just emit the - // llvm.dbg.addr in the correct places. This is done by the SILOptimizer + // llvm.dbg.value in the correct places. This is done by the SILOptimizer // pass DebugInfoCanonicalizer. auto InsertBefore = Builder.GetInsertPoint(); if (InsertBefore != ParentBlock->end()) { @@ -2980,10 +2982,10 @@ void IRGenDebugInfoImpl::emitDbgIntrinsic( // Ok, we now have our insert pt. Call the appropriate operations. assert(InsertPt); if (auto *InsertBefore = InsertPt.dyn_cast()) { - inserter.insert(Storage, Var, Expr, DL, InsertBefore); + auto *Inst = inserter.insert(Storage, Var, Expr, DL, InsertBefore); } else { - inserter.insert(Storage, Var, Expr, DL, - InsertPt.get()); + auto *Inst = inserter.insert(Storage, Var, Expr, DL, + InsertPt.get()); } return; } @@ -3056,12 +3058,12 @@ void IRGenDebugInfoImpl::emitTypeMetadata(IRGenFunction &IGF, static const char *Tau = SWIFT_UTF8("\u03C4"); llvm::raw_svector_ostream OS(Buf); OS << '$' << Tau << '_' << Depth << '_' << Index; - uint64_t PtrWidthInBits = CI.getTargetInfo().getPointerWidth(0); + uint64_t PtrWidthInBits = CI.getTargetInfo().getPointerWidth(clang::LangAS::Default); assert(PtrWidthInBits % 8 == 0); auto DbgTy = DebugTypeInfo::getTypeMetadata( getMetadataType(Name)->getDeclaredInterfaceType().getPointer(), Metadata->getType(), Size(PtrWidthInBits / 8), - Alignment(CI.getTargetInfo().getPointerAlign(0))); + Alignment(CI.getTargetInfo().getPointerAlign(clang::LangAS::Default))); emitVariableDeclaration(IGF.Builder, Metadata, DbgTy, IGF.getDebugScope(), {}, {OS.str().str(), 0, false}, // swift.type is already a pointer type, @@ -3082,7 +3084,7 @@ void IRGenDebugInfoImpl::emitPackCountParameter(IRGenFunction &IGF, if (!DS || DS->getInlinedFunction()->isTransparent()) return; - Type IntTy = BuiltinIntegerType::get(CI.getTargetInfo().getPointerWidth(0), + Type IntTy = BuiltinIntegerType::get(CI.getTargetInfo().getPointerWidth(clang::LangAS::Default), IGM.getSwiftModule()->getASTContext()); auto &TI = IGM.getTypeInfoForUnlowered(IntTy); auto DbgTy = *CompletedDebugTypeInfo::getFromTypeInfo(IntTy, TI, IGM); diff --git a/lib/IRGen/IRGenDebugInfo.h b/lib/IRGen/IRGenDebugInfo.h index 75c746e1bb7..6b2c0f7b31f 100644 --- a/lib/IRGen/IRGenDebugInfo.h +++ b/lib/IRGen/IRGenDebugInfo.h @@ -47,12 +47,12 @@ enum IndirectionKind { enum ArtificialKind : bool { RealValue = false, ArtificialValue = true }; /// Used to signal to emitDbgIntrinsic that we actually want to emit dbg.declare -/// instead of dbg.addr. By default, we now emit llvm.dbg.addr instead of -/// llvm.dbg.declare for normal variables. This is not true for metadata which +/// instead of dbg.value + op_deref. By default, we now emit dbg.value instead of +/// dbg.declare for normal variables. This is not true for metadata which /// truly are function wide and should be llvm.dbg.declare. enum class AddrDbgInstrKind : bool { DbgDeclare, - DbgAddr, + DbgValueDeref, }; /// Helper object that keeps track of the current CompileUnit, File, @@ -166,11 +166,11 @@ public: ArtificialKind Artificial = RealValue, AddrDbgInstrKind = AddrDbgInstrKind::DbgDeclare); - /// Emit a dbg.addr or dbg.value intrinsic, depending on Storage. If \p - /// ForceDbgDeclare is set to Yes, then instead of emitting a dbg.addr, we - /// will insert a dbg.declare. Please only use that if you know that the given - /// value can never be moved and have its lifetime ended early (e.x.: type - /// metadata). + /// Emit a dbg.value or dbg.declare intrinsic, depending on Storage. If \p + /// AddrDbgInstrKind is set to DbgDeclare, then instead of emitting a + /// dbg.value, we will insert a dbg.declare. Please only use that if you know + /// that the given value can never be moved and have its lifetime ended early + /// (e.x.: type metadata). void emitDbgIntrinsic(IRBuilder &Builder, llvm::Value *Storage, llvm::DILocalVariable *Var, llvm::DIExpression *Expr, unsigned Line, unsigned Col, llvm::DILocalScope *Scope, diff --git a/lib/IRGen/IRGenModule.cpp b/lib/IRGen/IRGenModule.cpp index 20a46d74e96..91c65a6e43a 100644 --- a/lib/IRGen/IRGenModule.cpp +++ b/lib/IRGen/IRGenModule.cpp @@ -14,20 +14,21 @@ // //===----------------------------------------------------------------------===// -#include "swift/AST/Availability.h" #include "swift/AST/ASTContext.h" -#include "swift/AST/Module.h" +#include "swift/AST/Availability.h" #include "swift/AST/DiagnosticsIRGen.h" #include "swift/AST/GenericSignature.h" #include "swift/AST/IRGenOptions.h" #include "swift/AST/IRGenRequests.h" +#include "swift/AST/Module.h" #include "swift/Basic/Dwarf.h" -#include "swift/Demangling/ManglingMacros.h" +#include "swift/Basic/LLVMExtras.h" #include "swift/ClangImporter/ClangImporter.h" +#include "swift/Demangling/ManglingMacros.h" #include "swift/IRGen/IRGenPublic.h" #include "swift/IRGen/Linking.h" -#include "swift/Runtime/RuntimeFnWrappersGen.h" #include "swift/Runtime/Config.h" +#include "swift/Runtime/RuntimeFnWrappersGen.h" #include "swift/Subsystems.h" #include "clang/AST/ASTContext.h" #include "clang/Basic/CharInfo.h" @@ -36,22 +37,25 @@ #include "clang/CodeGen/ModuleBuilder.h" #include "clang/CodeGen/SwiftCallingConv.h" #include "clang/Frontend/CompilerInstance.h" -#include "clang/Lex/Preprocessor.h" -#include "clang/Lex/PreprocessorOptions.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/HeaderSearchOptions.h" -#include "clang/Basic/CodeGenOptions.h" -#include "llvm/IR/IRBuilder.h" +#include "clang/Lex/Preprocessor.h" +#include "clang/Lex/PreprocessorOptions.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/PointerUnion.h" +#include "llvm/Frontend/Debug/Options.h" +#include "llvm/IR/Attributes.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DerivedTypes.h" +#include "llvm/IR/IRBuilder.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/MDBuilder.h" #include "llvm/IR/Module.h" #include "llvm/IR/Type.h" -#include "llvm/ADT/PointerUnion.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MD5.h" +#include "llvm/Support/ModRef.h" #include "Callee.h" #include "ConformanceDescription.h" @@ -96,26 +100,20 @@ static clang::CodeGenerator *createClangCodeGenerator(ASTContext &Context, auto &ClangContext = Importer->getClangASTContext(); auto &CGO = Importer->getCodeGenOpts(); - if (CGO.OpaquePointers) { - LLVMContext.setOpaquePointers(true); - } else { - LLVMContext.setOpaquePointers(false); - } - CGO.OptimizationLevel = Opts.shouldOptimize() ? 3 : 0; CGO.DebugTypeExtRefs = !Opts.DisableClangModuleSkeletonCUs; CGO.DiscardValueNames = !Opts.shouldProvideValueNames(); switch (Opts.DebugInfoLevel) { case IRGenDebugInfoLevel::None: - CGO.setDebugInfo(clang::codegenoptions::DebugInfoKind::NoDebugInfo); + CGO.setDebugInfo(llvm::codegenoptions::DebugInfoKind::NoDebugInfo); break; case IRGenDebugInfoLevel::LineTables: - CGO.setDebugInfo(clang::codegenoptions::DebugInfoKind::DebugLineTablesOnly); + CGO.setDebugInfo(llvm::codegenoptions::DebugInfoKind::DebugLineTablesOnly); break; case IRGenDebugInfoLevel::ASTTypes: case IRGenDebugInfoLevel::DwarfTypes: - CGO.setDebugInfo(clang::codegenoptions::DebugInfoKind::FullDebugInfo); + CGO.setDebugInfo(llvm::codegenoptions::DebugInfoKind::FullDebugInfo); break; } switch (Opts.DebugInfoFormat) { @@ -759,9 +757,10 @@ IRGenModule::~IRGenModule() { // They have to be non-local because otherwise we'll get warnings when // a particular x-macro expansion doesn't use one. namespace RuntimeConstants { - const auto ReadNone = llvm::Attribute::ReadNone; - const auto ReadOnly = llvm::Attribute::ReadOnly; - const auto ArgMemOnly = llvm::Attribute::ArgMemOnly; + const auto ReadNone = llvm::MemoryEffects::none(); + const auto ReadOnly = llvm::MemoryEffects::readOnly(); + const auto ArgMemOnly = llvm::MemoryEffects::argMemOnly(); + const auto ArgMemReadOnly = llvm::MemoryEffects::argMemOnly(llvm::ModRefInfo::Ref); const auto NoReturn = llvm::Attribute::NoReturn; const auto NoUnwind = llvm::Attribute::NoUnwind; const auto ZExt = llvm::Attribute::ZExt; @@ -945,6 +944,16 @@ static bool isReturnedAttribute(llvm::Attribute::AttrKind Attr) { return Attr == llvm::Attribute::Returned; } +static llvm::MemoryEffects mergeMemoryEffects(ArrayRef effects) { + if (effects.empty()) + return llvm::MemoryEffects::unknown(); + llvm::MemoryEffects mergedEffects = llvm::MemoryEffects::none(); + for (auto effect : effects) + mergedEffects |= effect; + return mergedEffects; +} + + namespace { bool isStandardLibrary(const llvm::Module &M) { if (auto *Flags = M.getNamedMetadata("swift.module.flags")) { @@ -984,15 +993,12 @@ llvm::FunctionType *swift::getRuntimeFnType(llvm::Module &Module, /*isVararg*/ false); } -llvm::Constant *swift::getRuntimeFn(llvm::Module &Module, - llvm::Constant *&cache, - const char *name, - llvm::CallingConv::ID cc, - RuntimeAvailability availability, - llvm::ArrayRef retTypes, - llvm::ArrayRef argTypes, - ArrayRef attrs, - IRGenModule *IGM) { +llvm::Constant *swift::getRuntimeFn( + llvm::Module &Module, llvm::Constant *&cache, const char *name, + llvm::CallingConv::ID cc, RuntimeAvailability availability, + llvm::ArrayRef retTypes, + llvm::ArrayRef argTypes, ArrayRef attrs, + ArrayRef memEffects, IRGenModule *IGM) { if (cache) return cache; @@ -1045,7 +1051,7 @@ llvm::Constant *swift::getRuntimeFn(llvm::Module &Module, if (!isStandardLibrary(Module) && IsExternal && ::useDllStorage(llvm::Triple(Module.getTargetTriple()))) fn->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass); - + if (IsExternal && isWeakLinked && !::useDllStorage(llvm::Triple(Module.getTargetTriple()))) fn->setLinkage(llvm::GlobalValue::ExternalWeakLinkage); @@ -1062,6 +1068,13 @@ llvm::Constant *swift::getRuntimeFn(llvm::Module &Module, else buildFnAttr.addAttribute(Attr); } + + llvm::MemoryEffects mergedEffects = mergeMemoryEffects(memEffects); + if (mergedEffects != llvm::MemoryEffects::unknown()) { + buildFnAttr.addAttribute(llvm::Attribute::getWithMemoryEffects( + Module.getContext(), mergedEffects)); + } + fn->addFnAttrs(buildFnAttr); fn->addRetAttrs(buildRetAttr); fn->addParamAttrs(0, buildFirstParamAttr); @@ -1110,9 +1123,10 @@ void IRGenModule::registerRuntimeEffect(ArrayRef effect, #define QUOTE(...) __VA_ARGS__ #define STR(X) #X -#define FUNCTION(ID, NAME, CC, AVAILABILITY, RETURNS, ARGS, ATTRS, EFFECT) \ - FUNCTION_IMPL(ID, NAME, CC, AVAILABILITY, QUOTE(RETURNS), QUOTE(ARGS), \ - QUOTE(ATTRS), QUOTE(EFFECT)) +#define FUNCTION(ID, NAME, CC, AVAILABILITY, RETURNS, ARGS, ATTRS, EFFECT, \ + MEMEFFECTS) \ + FUNCTION_IMPL(ID, NAME, CC, AVAILABILITY, QUOTE(RETURNS), QUOTE(ARGS), \ + QUOTE(ATTRS), QUOTE(EFFECT), QUOTE(MEMEFFECTS)) #define RETURNS(...) { __VA_ARGS__ } #define ARGS(...) { __VA_ARGS__ } @@ -1120,15 +1134,19 @@ void IRGenModule::registerRuntimeEffect(ArrayRef effect, #define ATTRS(...) { __VA_ARGS__ } #define NO_ATTRS {} #define EFFECT(...) { __VA_ARGS__ } +#define UNKNOWN_MEMEFFECTS \ + {} +#define MEMEFFECTS(...) \ + { __VA_ARGS__ } #define FUNCTION_IMPL(ID, NAME, CC, AVAILABILITY, RETURNS, ARGS, ATTRS, \ - EFFECT) \ + EFFECT, MEMEFFECTS) \ llvm::Constant *IRGenModule::get##ID##Fn() { \ using namespace RuntimeConstants; \ registerRuntimeEffect(EFFECT, #NAME); \ return getRuntimeFn(Module, ID##Fn, #NAME, CC, \ AVAILABILITY(this->Context), RETURNS, ARGS, ATTRS, \ - this); \ + MEMEFFECTS, this); \ } \ FunctionPointer IRGenModule::get##ID##FunctionPointer() { \ using namespace RuntimeConstants; \ @@ -1144,6 +1162,12 @@ void IRGenModule::registerRuntimeEffect(ArrayRef effect, else \ attrs = attrs.addFnAttribute(getLLVMContext(), Attr); \ } \ + llvm::MemoryEffects effects = mergeMemoryEffects(MEMEFFECTS); \ + if (effects != llvm::MemoryEffects::unknown()) { \ + attrs = attrs.addFnAttribute( \ + getLLVMContext(), \ + llvm::Attribute::getWithMemoryEffects(getLLVMContext(), effects)); \ + } \ auto sig = Signature(fnTy, attrs, CC); \ return FunctionPointer::forDirect(FunctionPointer::Kind::Function, fn, \ nullptr, sig); \ @@ -1186,7 +1210,7 @@ IRGenModule::createStringConstant(StringRef Str, bool willBeRelativelyAddressed, llvm::Constant *IRGenModule::get##NAME() { \ if (NAME) \ return NAME; \ - NAME = Module.getOrInsertGlobal(SYM, FullExistentialTypeMetadataStructTy); \ + NAME = Module.getOrInsertGlobal(SYM, FullExistentialTypeMetadataStructTy); \ if (useDllStorage() && !isStandardLibrary()) \ ApplyIRLinkage(IRLinkage::ExternalImport) \ .to(cast(NAME)); \ @@ -1445,7 +1469,7 @@ llvm::SmallString<32> getTargetDependentLibraryOption(const llvm::Triple &T, if (quote) buffer += '"'; buffer += library; - if (!library.endswith_insensitive(".lib")) + if (!library.ends_with_insensitive(".lib")) buffer += ".lib"; if (quote) buffer += '"'; @@ -1789,7 +1813,7 @@ void IRGenModule::emitAutolinkInfo() { StringRef AutolinkSectionName = Autolink.getSectionNameMetadata(); auto *Metadata = Module.getOrInsertNamedMetadata(AutolinkSectionName); - llvm::SmallSetVector Entries; + swift::SmallSetVector Entries; // Collect the linker options already in the module (from ClangCodeGen). for (auto Entry : Metadata->operands()) { diff --git a/lib/IRGen/IRGenSIL.cpp b/lib/IRGen/IRGenSIL.cpp index 24af2cc6677..deecf9878ca 100644 --- a/lib/IRGen/IRGenSIL.cpp +++ b/lib/IRGen/IRGenSIL.cpp @@ -1180,8 +1180,7 @@ public: if (!FailBBs.empty()) { // Move the trap basic blocks to the end of the function. for (auto *FailBB : FailBBs) { - auto &BlockList = CurFn->getBasicBlockList(); - BlockList.splice(BlockList.end(), BlockList, FailBB); + CurFn->splice(CurFn->end(), CurFn, FailBB->getIterator()); } } } @@ -2554,7 +2553,7 @@ void IRGenSILFunction::emitSILFunction() { // FIXME: Use the SIL basic block's name. llvm::BasicBlock *llBB = llvm::BasicBlock::Create(IGM.getLLVMContext()); auto phis = emitPHINodesForBBArgs(*this, &*bi, llBB); - CurFn->getBasicBlockList().push_back(llBB); + CurFn->insert(CurFn->end(), llBB); LoweredBBs[&*bi] = LoweredBB(llBB, std::move(phis)); } diff --git a/lib/IRGen/Linking.cpp b/lib/IRGen/Linking.cpp index 31f1359400f..8fde9ef38a3 100644 --- a/lib/IRGen/Linking.cpp +++ b/lib/IRGen/Linking.cpp @@ -22,7 +22,7 @@ #include "swift/ClangImporter/ClangModule.h" #include "swift/SIL/SILGlobalVariable.h" #include "swift/SIL/FormalLinkage.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/raw_ostream.h" diff --git a/lib/IRGen/MetadataRequest.cpp b/lib/IRGen/MetadataRequest.cpp index fa737c751f4..38ee48913bd 100644 --- a/lib/IRGen/MetadataRequest.cpp +++ b/lib/IRGen/MetadataRequest.cpp @@ -46,12 +46,13 @@ #include "swift/IRGen/Linking.h" #include "swift/SIL/FormalLinkage.h" #include "swift/SIL/TypeLowering.h" -#include "llvm/ADT/SmallSet.h" #include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallSet.h" #include "llvm/IR/Constant.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FormatVariadic.h" +#include "llvm/Support/ModRef.h" #include using namespace swift; @@ -2426,9 +2427,9 @@ IRGenFunction::emitGenericTypeMetadataAccessFunctionCall( accessFunction, callArgs); call->setDoesNotThrow(); call->setCallingConv(IGM.SwiftCC); - call->addFnAttr(allocatedArgsBuffer - ? llvm::Attribute::InaccessibleMemOrArgMemOnly - : llvm::Attribute::ReadNone); + call->setMemoryEffects(allocatedArgsBuffer + ? llvm::MemoryEffects::inaccessibleOrArgMemOnly() + : llvm::MemoryEffects::none()); // If we allocated a buffer for the arguments, end its lifetime. if (allocatedArgsBuffer) @@ -2485,7 +2486,7 @@ MetadataResponse irgen::emitGenericTypeMetadataAccessFunction( } call->setDoesNotThrow(); call->setCallingConv(IGM.SwiftCC); - call->addFnAttr(llvm::Attribute::ReadOnly); + call->setOnlyReadsMemory(); result = call; } else { static_assert(NumDirectGenericTypeMetadataAccessFunctionArgs == 3, diff --git a/lib/IRGen/Outlining.h b/lib/IRGen/Outlining.h index 97433fff239..87ad8be0a84 100644 --- a/lib/IRGen/Outlining.h +++ b/lib/IRGen/Outlining.h @@ -20,6 +20,7 @@ #include "LocalTypeDataKind.h" #include "swift/Basic/LLVM.h" #include "llvm/ADT/MapVector.h" +#include "LocalTypeDataKind.h" namespace llvm { class Value; diff --git a/lib/IRGen/StructLayout.cpp b/lib/IRGen/StructLayout.cpp index bda7bc676c4..172ead97435 100644 --- a/lib/IRGen/StructLayout.cpp +++ b/lib/IRGen/StructLayout.cpp @@ -440,7 +440,7 @@ void StructLayoutBuilder::addFixedSizeElement(ElementLayout &elt) { // The padding can be used as spare bits by enum layout. auto numBits = Size(paddingRequired).getValueInBits(); - auto mask = llvm::APInt::getAllOnesValue(numBits); + auto mask = llvm::APInt::getAllOnes(numBits); CurSpareBits.push_back(SpareBitVector::fromAPInt(mask)); } } diff --git a/lib/IRGen/SwiftTargetInfo.cpp b/lib/IRGen/SwiftTargetInfo.cpp index a09f66209f7..7c6eccf7550 100644 --- a/lib/IRGen/SwiftTargetInfo.cpp +++ b/lib/IRGen/SwiftTargetInfo.cpp @@ -17,7 +17,7 @@ #include "SwiftTargetInfo.h" #include "IRGenModule.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/IR/DataLayout.h" #include "swift/ABI/System.h" #include "swift/AST/ASTContext.h" diff --git a/lib/IRGen/SwiftTargetInfo.h b/lib/IRGen/SwiftTargetInfo.h index b01a1cc54de..42900f18be7 100644 --- a/lib/IRGen/SwiftTargetInfo.h +++ b/lib/IRGen/SwiftTargetInfo.h @@ -20,7 +20,7 @@ #include "swift/Basic/LLVM.h" #include "swift/Basic/ClusteredBitVector.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "IRGen.h" namespace swift { diff --git a/lib/IRGen/TBDGenVisitor.h b/lib/IRGen/TBDGenVisitor.h index c6673b26624..b01a6da89fd 100644 --- a/lib/IRGen/TBDGenVisitor.h +++ b/lib/IRGen/TBDGenVisitor.h @@ -24,7 +24,7 @@ #include "swift/IRGen/Linking.h" #include "swift/SIL/SILDeclRef.h" #include "llvm/ADT/StringSet.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/TextAPI/InterfaceFile.h" using namespace swift::irgen; diff --git a/lib/IRGen/TypeLayout.cpp b/lib/IRGen/TypeLayout.cpp index 0fb79920ae9..3e83433c016 100644 --- a/lib/IRGen/TypeLayout.cpp +++ b/lib/IRGen/TypeLayout.cpp @@ -2246,13 +2246,13 @@ bool EnumTypeLayoutEntry::buildSinglePayloadRefCountString( auto tzCount = mask.countTrailingZeros(); auto shiftedMask = mask.lshr(tzCount); auto toCount = shiftedMask.countTrailingOnes(); - if (mask.countPopulation() > 64 || toCount != mask.countPopulation() || + if (mask.popcount() > 64 || toCount != mask.popcount() || (tzCount % toCount != 0)) { // We currently don't handle cases with non-contiguous or > 64 bits of // extra inhabitants isSimple = false; } else { - xiBitCount = std::min(64u, mask.countPopulation()); + xiBitCount = std::min(64u, mask.popcount()); xiBitOffset = mask.countTrailingZeros(); zeroTagValue = lowValue.extractBitsAsZExtValue(xiBitCount, xiBitOffset); } diff --git a/lib/Immediate/Immediate.cpp b/lib/Immediate/Immediate.cpp index 759d6858997..994ebc4e0b2 100644 --- a/lib/Immediate/Immediate.cpp +++ b/lib/Immediate/Immediate.cpp @@ -42,7 +42,10 @@ #include "llvm/IR/LLVMContext.h" #include "llvm/Support/Path.h" #include "llvm/Transforms/IPO.h" -#include "llvm/Transforms/IPO/PassManagerBuilder.h" + +// TODO: Replace pass manager +// Removed in: d623b2f95fd559901f008a0588dddd0949a8db01 +/* #include "llvm/Transforms/IPO/PassManagerBuilder.h" */ #define DEBUG_TYPE "swift-immediate" @@ -255,15 +258,15 @@ int swift::RunImmediately(CompilerInstance &CI, const ProcessCmdLine &CmdLine, const IRGenOptions &IRGenOpts, const SILOptions &SILOpts, std::unique_ptr &&SM) { - + auto &Context = CI.getASTContext(); - + // Load libSwiftCore to setup process arguments. // // This must be done here, before any library loading has been done, to avoid // racing with the static initializers in user code. // Setup interpreted process arguments. - using ArgOverride = void (* SWIFT_CC(swift))(const char **, int); + using ArgOverride = void (*SWIFT_CC(swift))(const char **, int); #if defined(_WIN32) auto stdlib = loadSwiftRuntime(Context.SearchPathOpts.RuntimeLibraryPaths); if (!stdlib) { @@ -273,15 +276,15 @@ int swift::RunImmediately(CompilerInstance &CI, const ProcessCmdLine &CmdLine, } auto module = static_cast(stdlib); auto emplaceProcessArgs = reinterpret_cast( - GetProcAddress(module, "_swift_stdlib_overrideUnsafeArgvArgc")); + GetProcAddress(module, "_swift_stdlib_overrideUnsafeArgvArgc")); if (emplaceProcessArgs == nullptr) return -1; #else // In case the compiler is built with swift modules, it already has the stdlib // linked to. First try to lookup the symbol with the standard library // resolving. - auto emplaceProcessArgs - = (ArgOverride)dlsym(RTLD_DEFAULT, "_swift_stdlib_overrideUnsafeArgvArgc"); + auto emplaceProcessArgs = + (ArgOverride)dlsym(RTLD_DEFAULT, "_swift_stdlib_overrideUnsafeArgvArgc"); if (dlerror()) { // If this does not work (= the Swift modules are not linked to the tool), @@ -293,8 +296,8 @@ int swift::RunImmediately(CompilerInstance &CI, const ProcessCmdLine &CmdLine, return -1; } dlerror(); - emplaceProcessArgs - = (ArgOverride)dlsym(stdlib, "_swift_stdlib_overrideUnsafeArgvArgc"); + emplaceProcessArgs = + (ArgOverride)dlsym(stdlib, "_swift_stdlib_overrideUnsafeArgvArgc"); if (dlerror()) return -1; } diff --git a/lib/Immediate/SwiftMaterializationUnit.cpp b/lib/Immediate/SwiftMaterializationUnit.cpp index d15c7e6be96..4cddfde0907 100644 --- a/lib/Immediate/SwiftMaterializationUnit.cpp +++ b/lib/Immediate/SwiftMaterializationUnit.cpp @@ -82,7 +82,7 @@ SwiftJIT::Create(CompilerInstance &CI) { return EPCIU.takeError(); (*EPCIU)->createLazyCallThroughManager( - ES, llvm::pointerToJITTargetAddress(&handleLazyCompilationFailure)); + ES, llvm::orc::ExecutorAddr::fromPtr(&handleLazyCompilationFailure)); if (auto Err = setUpInProcessLCTMReentryViaEPCIU(**EPCIU)) return std::move(Err); @@ -199,8 +199,8 @@ renameFunctionBodies(llvm::orc::MaterializationResponsibility &MR, if (ToRename.count(Sym->getName())) { // FIXME: Get rid of the temporary when Swift's llvm-project is // updated to LLVM 17. - auto NewName = G.allocateString(mangle(Sym->getName())); - Sym->setName({NewName.data(), NewName.size()}); + auto NewName = G.allocateCString(Twine(mangle(Sym->getName()))); + Sym->setName({NewName.data(), NewName.size() - 1}); } } } @@ -221,12 +221,14 @@ SwiftJIT::Plugin::notifyFailed(llvm::orc::MaterializationResponsibility &MR) { } llvm::Error -SwiftJIT::Plugin::notifyRemovingResources(llvm::orc::ResourceKey K) { +SwiftJIT::Plugin::notifyRemovingResources(llvm::orc::JITDylib &JD, + llvm::orc::ResourceKey K) { return llvm::Error::success(); } void SwiftJIT::Plugin::notifyTransferringResources( - llvm::orc::ResourceKey DstKey, llvm::orc::ResourceKey SrcKey) {} + llvm::orc::JITDylib &JD, llvm::orc::ResourceKey DstKey, + llvm::orc::ResourceKey SrcKey) {} void SwiftJIT::handleLazyCompilationFailure() { llvm::errs() << "Lazy compilation error\n"; @@ -393,7 +395,7 @@ void LazySwiftMaterializationUnit::materialize( DefinedSymbols.insert(itr->getValue()); } } - + llvm::orc::SymbolFlagsMap UnrequestedSymbols; for (auto &[Sym, Flags] : MR->getSymbols()) { if (!DefinedSymbols.contains(Sym)) { diff --git a/lib/LLVMPasses/ARCEntryPointBuilder.h b/lib/LLVMPasses/ARCEntryPointBuilder.h index d7bf54bd83f..87da4a9cd58 100644 --- a/lib/LLVMPasses/ARCEntryPointBuilder.h +++ b/lib/LLVMPasses/ARCEntryPointBuilder.h @@ -18,7 +18,7 @@ #include "swift/Runtime/Config.h" #include "swift/Runtime/RuntimeFnWrappersGen.h" #include "llvm/ADT/APInt.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Module.h" @@ -224,7 +224,7 @@ private: getModule(), cache, isNonAtomic(OrigI) ? "swift_nonatomic_retain" : "swift_retain", DefaultCC, RuntimeAvailability::AlwaysAvailable, {ObjectPtrTy}, - {ObjectPtrTy}, {NoUnwind, FirstParamReturned}); + {ObjectPtrTy}, {NoUnwind, FirstParamReturned}, {}); return Retain.get(); } @@ -241,7 +241,7 @@ private: isNonAtomic(OrigI) ? "swift_nonatomic_release" : "swift_release", DefaultCC, RuntimeAvailability::AlwaysAvailable, - {VoidTy}, {ObjectPtrTy}, {NoUnwind}); + {VoidTy}, {ObjectPtrTy}, {NoUnwind}, {}); return Release.get(); } @@ -277,7 +277,7 @@ private: getModule(), cache, isNonAtomic(OrigI) ? "swift_nonatomic_retain_n" : "swift_retain_n", DefaultCC, RuntimeAvailability::AlwaysAvailable, {ObjectPtrTy}, - {ObjectPtrTy, Int32Ty}, {NoUnwind, FirstParamReturned}); + {ObjectPtrTy, Int32Ty}, {NoUnwind, FirstParamReturned}, {}); return RetainN.get(); } @@ -295,7 +295,7 @@ private: isNonAtomic(OrigI) ? "swift_nonatomic_release_n" : "swift_release_n", DefaultCC, RuntimeAvailability::AlwaysAvailable, - {VoidTy}, {ObjectPtrTy, Int32Ty}, {NoUnwind}); + {VoidTy}, {ObjectPtrTy, Int32Ty}, {NoUnwind}, {}); return ReleaseN.get(); } @@ -314,7 +314,7 @@ private: isNonAtomic(OrigI) ? "swift_nonatomic_unknownObjectRetain_n" : "swift_unknownObjectRetain_n", DefaultCC, RuntimeAvailability::AlwaysAvailable, {ObjectPtrTy}, - {ObjectPtrTy, Int32Ty}, {NoUnwind, FirstParamReturned}); + {ObjectPtrTy, Int32Ty}, {NoUnwind, FirstParamReturned}, {}); return UnknownObjectRetainN.get(); } @@ -333,7 +333,7 @@ private: isNonAtomic(OrigI) ? "swift_nonatomic_unknownObjectRelease_n" : "swift_unknownObjectRelease_n", DefaultCC, RuntimeAvailability::AlwaysAvailable, {VoidTy}, - {ObjectPtrTy, Int32Ty}, {NoUnwind}); + {ObjectPtrTy, Int32Ty}, {NoUnwind}, {}); return UnknownObjectReleaseN.get(); } @@ -351,7 +351,7 @@ private: isNonAtomic(OrigI) ? "swift_nonatomic_bridgeObjectRetain_n" : "swift_bridgeObjectRetain_n", DefaultCC, RuntimeAvailability::AlwaysAvailable, {BridgeObjectPtrTy}, - {BridgeObjectPtrTy, Int32Ty}, {NoUnwind}); + {BridgeObjectPtrTy, Int32Ty}, {NoUnwind}, {}); return BridgeRetainN.get(); } @@ -370,7 +370,7 @@ private: isNonAtomic(OrigI) ? "swift_nonatomic_bridgeObjectRelease_n" : "swift_bridgeObjectRelease_n", DefaultCC, RuntimeAvailability::AlwaysAvailable, {VoidTy}, - {BridgeObjectPtrTy, Int32Ty}, {NoUnwind}); + {BridgeObjectPtrTy, Int32Ty}, {NoUnwind}, {}); return BridgeReleaseN.get(); } diff --git a/lib/LLVMPasses/CMakeLists.txt b/lib/LLVMPasses/CMakeLists.txt index d1131c9ea2a..f666895fc97 100644 --- a/lib/LLVMPasses/CMakeLists.txt +++ b/lib/LLVMPasses/CMakeLists.txt @@ -6,10 +6,10 @@ add_swift_host_library(swiftLLVMPasses STATIC LLVMARCContract.cpp LLVMInlineTree.cpp LLVMMergeFunctions.cpp - DbgAddrBlockSplitter.cpp LLVM_LINK_COMPONENTS analysis + targetparser ) target_link_libraries(swiftLLVMPasses PRIVATE swiftDemangling) diff --git a/lib/LLVMPasses/DbgAddrBlockSplitter.cpp b/lib/LLVMPasses/DbgAddrBlockSplitter.cpp deleted file mode 100644 index abdc18e781d..00000000000 --- a/lib/LLVMPasses/DbgAddrBlockSplitter.cpp +++ /dev/null @@ -1,94 +0,0 @@ -//===--- DbgAddrBlockSplitter.cpp -----------------------------------------===// -// -// This source file is part of the Swift.org open source project -// -// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors -// Licensed under Apache License v2.0 with Runtime Library Exception -// -// See https://swift.org/LICENSE.txt for license information -// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors -// -//===----------------------------------------------------------------------===// -/// -/// This simple pass runs late after all LLVM level optimization passes have -/// completed and break blocks at llvm.dbg.addr when we are compiling at -/// -Onone. This helps us avoid bad behavior in SelectionDAG where SelectionDAG -/// in certain cases sink llvm.dbg.addr to the end of blocks. -/// -//===----------------------------------------------------------------------===// - -#include "swift/LLVMPasses/Passes.h" -#include "swift/LLVMPasses/PassesFwd.h" -#include "llvm/IR/IntrinsicInst.h" -#include "llvm/Pass.h" -#include "llvm/Transforms/Utils/BasicBlockUtils.h" - -using namespace llvm; - -namespace { - -struct SwiftDbgAddrBlockSplitter : FunctionPass { - static char ID; - SwiftDbgAddrBlockSplitter() : FunctionPass(ID) {} - - bool runOnFunction(Function &fn) override; -}; - -} // namespace - -static bool split(Function &fn) { - SmallVector breakBlockPoints; - - // If we are in the first block, - - for (auto &block : fn) { - for (auto &inst : block) { - if (isa(&inst)) { - breakBlockPoints.push_back(&*std::next(inst.getIterator())); - } - } - } - - if (breakBlockPoints.empty()) - return false; - - bool madeChange = false; - - while (!breakBlockPoints.empty()) { - auto *i = breakBlockPoints.pop_back_val(); - if (i->isTerminator()) - continue; - SplitBlock(i->getParent(), i); - madeChange = true; - } - - return madeChange; -} - -bool SwiftDbgAddrBlockSplitter::runOnFunction(Function &fn) { - return split(fn); -} - -char SwiftDbgAddrBlockSplitter::ID = 0; -INITIALIZE_PASS_BEGIN(SwiftDbgAddrBlockSplitter, - "swift-dbg-addr-block-splitter", - "Swift pass that splits blocks after llvm.dbg.addr", - false, false) -INITIALIZE_PASS_END(SwiftDbgAddrBlockSplitter, "swift-dbg-addr-block-splitter", - "Swift pass that splits blocks after llvm.dbg.addr", false, - false) - -llvm::FunctionPass *swift::createSwiftDbgAddrBlockSplitter() { - initializeSwiftDbgAddrBlockSplitterPass( - *llvm::PassRegistry::getPassRegistry()); - return new SwiftDbgAddrBlockSplitter(); -} - -llvm::PreservedAnalyses -swift::SwiftDbgAddrBlockSplitterPass::run(llvm::Function &F, - llvm::FunctionAnalysisManager &AM) { - bool changed = split(F); - if (!changed) - return PreservedAnalyses::all(); - return PreservedAnalyses::none(); -} diff --git a/lib/LLVMPasses/LLVMARCOpts.cpp b/lib/LLVMPasses/LLVMARCOpts.cpp index 2a59a9451dd..37bbe4dd256 100644 --- a/lib/LLVMPasses/LLVMARCOpts.cpp +++ b/lib/LLVMPasses/LLVMARCOpts.cpp @@ -37,7 +37,7 @@ #include "llvm/ADT/Statistic.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/TinyPtrVector.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/IR/InstIterator.h" #include "llvm/IR/IRBuilder.h" #include "llvm/Support/raw_ostream.h" diff --git a/lib/LLVMPasses/LLVMMergeFunctions.cpp b/lib/LLVMPasses/LLVMMergeFunctions.cpp index 07734c20e21..26816af0e76 100644 --- a/lib/LLVMPasses/LLVMMergeFunctions.cpp +++ b/lib/LLVMPasses/LLVMMergeFunctions.cpp @@ -39,7 +39,7 @@ #include "llvm/ADT/SmallSet.h" #include "llvm/ADT/Statistic.h" #include "llvm/ADT/Hashing.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/IR/Attributes.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" @@ -1092,9 +1092,7 @@ void SwiftMergeFunctions::mergeWithParams(const FunctionInfos &FInfos, LLVM_DEBUG(dbgs() << " Merge into " << NewFunction->getName() << '\n'); // Move the body of FirstF into the NewFunction. - NewFunction->getBasicBlockList().splice(NewFunction->begin(), - FirstF->getBasicBlockList()); - + NewFunction->splice(NewFunction->begin(), FirstF); auto NewArgIter = NewFunction->arg_begin(); for (Argument &OrigArg : FirstF->args()) { Argument &NewArg = *NewArgIter++; diff --git a/lib/Option/Options.cpp b/lib/Option/Options.cpp index 639a3320008..aeeed8dc979 100644 --- a/lib/Option/Options.cpp +++ b/lib/Option/Options.cpp @@ -19,11 +19,14 @@ using namespace swift::options; using namespace llvm::opt; -#define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE; +#define PREFIX(NAME, VALUE) \ + constexpr llvm::StringLiteral NAME##_init[] = VALUE; \ + constexpr llvm::ArrayRef NAME( \ + NAME##_init, std::size(NAME##_init) - 1); #include "swift/Option/Options.inc" #undef PREFIX -static const OptTable::Info InfoTable[] = { +static const llvm::opt::GenericOptTable::Info InfoTable[] = { #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \ HELPTEXT, METAVAR, VALUES) \ {PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, Option::KIND##Class, \ @@ -34,13 +37,13 @@ static const OptTable::Info InfoTable[] = { namespace { -class SwiftOptTable : public OptTable { +class SwiftOptTable : public llvm::opt::GenericOptTable { public: - SwiftOptTable() : OptTable(InfoTable) {} + SwiftOptTable() : GenericOptTable(InfoTable) {} }; } // end anonymous namespace std::unique_ptr swift::createSwiftOptTable() { - return std::unique_ptr(new SwiftOptTable()); + return std::unique_ptr(new SwiftOptTable()); } diff --git a/lib/Option/SanitizerOptions.cpp b/lib/Option/SanitizerOptions.cpp index af7b52644aa..f5ea30c13fb 100644 --- a/lib/Option/SanitizerOptions.cpp +++ b/lib/Option/SanitizerOptions.cpp @@ -25,7 +25,7 @@ #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" using namespace swift; @@ -182,36 +182,27 @@ OptionSet swift::parseSanitizerArgValues( + toStringRef(SanitizerKind::Thread)).toStringRef(b2)); } - // Scudo can only be run with ubsan. - if (sanitizerSet & SanitizerKind::Scudo) { - OptionSet allowedSet; - allowedSet |= SanitizerKind::Scudo; - allowedSet |= SanitizerKind::Undefined; - - auto forbiddenOptions = sanitizerSet - allowedSet; - - if (forbiddenOptions) { - SanitizerKind forbidden; - - if (forbiddenOptions & SanitizerKind::Address) { - forbidden = SanitizerKind::Address; - } else if (forbiddenOptions & SanitizerKind::Thread) { - forbidden = SanitizerKind::Thread; - } else { - assert(forbiddenOptions & SanitizerKind::Fuzzer); - forbidden = SanitizerKind::Fuzzer; + // Scudo must be run standalone + if (sanitizerSet.contains(SanitizerKind::Scudo) && + !sanitizerSet.containsOnly(SanitizerKind::Scudo)) { + auto diagnoseSanitizerKind = [&Diags, A, &sanitizerSet](SanitizerKind kind) { + // Don't diagnose Scudo, but diagnose anything else + if (kind != SanitizerKind::Scudo && sanitizerSet.contains(kind)) { + SmallString<128> b1; + SmallString<128> b2; + Diags.diagnose(SourceLoc(), diag::error_argument_not_allowed_with, + (A->getOption().getPrefixedName() + + toStringRef(SanitizerKind::Scudo)).toStringRef(b1), + (A->getOption().getPrefixedName() + + toStringRef(kind)).toStringRef(b2)); } + }; + +#define SANITIZER(enm, kind, name, file) \ + diagnoseSanitizerKind(SanitizerKind::kind); +#include "swift/Basic/Sanitizers.def" - SmallString<128> b1; - SmallString<128> b2; - Diags.diagnose(SourceLoc(), diag::error_argument_not_allowed_with, - (A->getOption().getPrefixedName() - + toStringRef(SanitizerKind::Scudo)).toStringRef(b1), - (A->getOption().getPrefixedName() - + toStringRef(forbidden)).toStringRef(b2)); - } } - return sanitizerSet; } diff --git a/lib/Parse/Lexer.cpp b/lib/Parse/Lexer.cpp index 80e0a7182b7..c7708adbd6d 100644 --- a/lib/Parse/Lexer.cpp +++ b/lib/Parse/Lexer.cpp @@ -25,6 +25,7 @@ #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/ADT/Twine.h" +#include "llvm/ADT/bit.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/MathExtras.h" #include "llvm/Support/MemoryBuffer.h" @@ -60,7 +61,7 @@ using clang::isWhitespace; static bool EncodeToUTF8(unsigned CharValue, SmallVectorImpl &Result) { // Number of bits in the value, ignoring leading zeros. - unsigned NumBits = 32-llvm::countLeadingZeros(CharValue); + unsigned NumBits = 32-llvm::countl_zero(CharValue); // Handle the leading byte, based on the number of bits in the value. unsigned NumTrailingBytes; @@ -100,7 +101,7 @@ static bool EncodeToUTF8(unsigned CharValue, /// CLO8 - Return the number of leading ones in the specified 8-bit value. static unsigned CLO8(unsigned char C) { - return llvm::countLeadingOnes(uint32_t(C) << 24); + return llvm::countl_one(uint32_t(C) << 24); } /// isStartOfUTF8Character - Return true if this isn't a UTF8 continuation @@ -162,7 +163,7 @@ uint32_t swift::validateUTF8CharacterAndAdvance(const char *&Ptr, // If we got here, we read the appropriate number of accumulated bytes. // Verify that the encoding was actually minimal. // Number of bits in the value, ignoring leading zeros. - unsigned NumBits = 32-llvm::countLeadingZeros(CharValue); + unsigned NumBits = 32-llvm::countl_zero(CharValue); if (NumBits <= 5+6) return EncodedBytes == 2 ? CharValue : ~0U; diff --git a/lib/Parse/ParseVersion.cpp b/lib/Parse/ParseVersion.cpp index 6daf483401e..a92227d780c 100644 --- a/lib/Parse/ParseVersion.cpp +++ b/lib/Parse/ParseVersion.cpp @@ -21,10 +21,10 @@ swift::version::Version version::getCurrentCompilerVersion() { #ifdef SWIFT_COMPILER_VERSION auto currentVersion = VersionParser::parseVersionString( SWIFT_COMPILER_VERSION, SourceLoc(), nullptr); - assert(currentVersion.hasValue() && + assert(static_cast(currentVersion) && "Embedded Swift language version couldn't be parsed: " "'" SWIFT_COMPILER_VERSION "'"); - return currentVersion.getValue(); + return *currentVersion; #else return Version(); #endif diff --git a/lib/PrintAsClang/PrintAsClang.cpp b/lib/PrintAsClang/PrintAsClang.cpp index 96afcffa186..082bdc5b64a 100644 --- a/lib/PrintAsClang/PrintAsClang.cpp +++ b/lib/PrintAsClang/PrintAsClang.cpp @@ -309,14 +309,13 @@ static void collectClangModuleHeaderIncludes( requiredTextualIncludes.insert(textualInclude); }; - if (clang::Module::Header umbrellaHeader = clangModule->getUmbrellaHeader()) { - addHeader(umbrellaHeader.Entry->tryGetRealPathName(), - umbrellaHeader.PathRelativeToRootModuleDirectory); - } else if (clang::Module::DirectoryName umbrellaDir = - clangModule->getUmbrellaDir()) { + if (llvm::Optional umbrellaHeader = clangModule->getUmbrellaHeaderAsWritten()) { + addHeader(umbrellaHeader->Entry.getFileEntry().tryGetRealPathName(), + umbrellaHeader->PathRelativeToRootModuleDirectory); + } else if (llvm::Optional umbrellaDir = clangModule->getUmbrellaDirAsWritten()) { SmallString<128> nativeUmbrellaDirPath; std::error_code errorCode; - llvm::sys::path::native(umbrellaDir.Entry->getName(), + llvm::sys::path::native(umbrellaDir->Entry.getDirEntry().getName(), nativeUmbrellaDirPath); llvm::vfs::FileSystem &fileSystem = fileManager.getVirtualFileSystem(); for (llvm::vfs::recursive_directory_iterator @@ -338,8 +337,8 @@ static void collectClangModuleHeaderIncludes( pathComponents.push_back(*pathIt); // Then append this to the path from module root to umbrella dir SmallString<128> relativeHeaderPath; - if (umbrellaDir.PathRelativeToRootModuleDirectory != ".") - relativeHeaderPath += umbrellaDir.PathRelativeToRootModuleDirectory; + if (umbrellaDir->PathRelativeToRootModuleDirectory != ".") + relativeHeaderPath += umbrellaDir->PathRelativeToRootModuleDirectory; for (auto it = pathComponents.rbegin(), end = pathComponents.rend(); it != end; ++it) { @@ -354,7 +353,7 @@ static void collectClangModuleHeaderIncludes( {clang::Module::HK_Normal, clang::Module::HK_Textual}) { for (const clang::Module::Header &header : clangModule->Headers[headerKind]) { - addHeader(header.Entry->tryGetRealPathName(), + addHeader(header.Entry.getFileEntry().tryGetRealPathName(), header.PathRelativeToRootModuleDirectory); } } @@ -527,6 +526,8 @@ static void writePostImportPrologue(raw_ostream &os, ModuleDecl &M) { "#pragma clang diagnostic ignored \"-Wnullability\"\n" "#pragma clang diagnostic ignored " "\"-Wdollar-in-identifier-extension\"\n" + "#pragma clang diagnostic ignored " + "\"-Wunsafe-buffer-usage\"\n" "\n" "#if __has_attribute(external_source_symbol)\n" "# pragma push_macro(\"any\")\n" diff --git a/lib/PrintAsClang/PrintSwiftToClangCoreScaffold.cpp b/lib/PrintAsClang/PrintSwiftToClangCoreScaffold.cpp index daf94efe1d5..8568f704e09 100644 --- a/lib/PrintAsClang/PrintSwiftToClangCoreScaffold.cpp +++ b/lib/PrintAsClang/PrintSwiftToClangCoreScaffold.cpp @@ -19,6 +19,7 @@ #include "swift/AST/Type.h" #include "swift/IRGen/IRABIDetailsProvider.h" #include "swift/IRGen/Linking.h" +#include "clang/Basic/AddressSpaces.h" #include "clang/Basic/TargetInfo.h" #include "llvm/ADT/STLExtras.h" @@ -178,7 +179,7 @@ void printPrimitiveGenericTypeTraits(raw_ostream &os, ASTContext &astContext, auto &clangTI = astContext.getClangModuleLoader()->getClangASTContext().getTargetInfo(); bool isSwiftIntLong = - clangTI.getPtrDiffType(0) == clang::TransferrableTargetInfo::SignedLong; + clangTI.getPtrDiffType(clang::LangAS::Default) == clang::TransferrableTargetInfo::SignedLong; bool isInt64Long = clangTI.getInt64Type() == clang::TransferrableTargetInfo::SignedLong; if (!(isSwiftIntLong && !isInt64Long)) diff --git a/lib/SIL/IR/SILBuilder.cpp b/lib/SIL/IR/SILBuilder.cpp index 6d2c39648f7..0eaf676b243 100644 --- a/lib/SIL/IR/SILBuilder.cpp +++ b/lib/SIL/IR/SILBuilder.cpp @@ -254,6 +254,24 @@ SILBasicBlock *SILBuilder::splitBlockForFallthrough() { return NewBB; } +llvm::Optional +SILBuilder::substituteAnonymousArgs(llvm::SmallString<4> Name, + llvm::Optional Var, + SILLocation Loc) { + if (Var && shouldDropVariable(*Var, Loc)) + return {}; + if (!Var || !Var->ArgNo || !Var->Name.empty()) + return Var; + + auto *VD = Loc.getAsASTNode(); + if (VD && !VD->getName().empty()) + return Var; + + llvm::raw_svector_ostream(Name) << '_' << (Var->ArgNo - 1); + Var->Name = Name; + return Var; +} + static bool setAccessToDeinit(BeginAccessInst *beginAccess) { // It's possible that AllocBoxToStack could catch some cases that // AccessEnforcementSelection does not promote to [static]. Ultimately, this diff --git a/lib/SIL/IR/SILFunction.cpp b/lib/SIL/IR/SILFunction.cpp index 2a4d1568a36..26bda8229e5 100644 --- a/lib/SIL/IR/SILFunction.cpp +++ b/lib/SIL/IR/SILFunction.cpp @@ -863,6 +863,9 @@ SILFunction::isPossiblyUsedExternally() const { if (markedAsUsed()) return true; + if (shouldBePreservedForDebugger()) + return true; + // Declaration marked as `@_alwaysEmitIntoClient` that // returns opaque result type with availability conditions // has to be kept alive to emit opaque type metadata descriptor. @@ -873,6 +876,39 @@ SILFunction::isPossiblyUsedExternally() const { return swift::isPossiblyUsedExternally(linkage, getModule().isWholeModule()); } +bool SILFunction::shouldBePreservedForDebugger() const { + // Only preserve for the debugger at Onone. + if (getEffectiveOptimizationMode() != OptimizationMode::NoOptimization) + return false; + + // Only keep functions defined in this module. + if (!isDefinition()) + return false; + + // Don't preserve anything markes as always emit into client. + if (markedAsAlwaysEmitIntoClient()) + return false; + + // Needed by lldb to print global variables which are propagated by the + // mandatory GlobalOpt. + if (isGlobalInit()) + return true; + + // Preserve any user-written functions. + if (auto declContext = getDeclContext()) + if (auto decl = declContext->getAsDecl()) + if (!decl->isImplicit()) + return true; + + // Keep any setters/getters, even compiler generated ones. + if (auto *accessorDecl = + llvm::dyn_cast_or_null(getDeclContext())) + if (accessorDecl->isGetterOrSetter()) + return true; + + return false; +} + bool SILFunction::isExternallyUsedSymbol() const { return swift::isPossiblyUsedExternally(getEffectiveSymbolLinkage(), getModule().isWholeModule()); diff --git a/lib/SIL/IR/SILInstruction.cpp b/lib/SIL/IR/SILInstruction.cpp index 03d62c6c4d1..fbbd335907d 100644 --- a/lib/SIL/IR/SILInstruction.cpp +++ b/lib/SIL/IR/SILInstruction.cpp @@ -1001,12 +1001,13 @@ MemoryBehavior SILInstruction::getMemoryBehavior() const { const IntrinsicInfo &IInfo = BI->getIntrinsicInfo(); if (IInfo.ID != llvm::Intrinsic::not_intrinsic) { auto IAttrs = IInfo.getOrCreateAttributes(getModule().getASTContext()); + auto MemEffects = IAttrs.getMemoryEffects(); // Read-only. - if (IAttrs.hasFnAttr(llvm::Attribute::ReadOnly) && + if (MemEffects.onlyReadsMemory() && IAttrs.hasFnAttr(llvm::Attribute::NoUnwind)) return MemoryBehavior::MayRead; // Read-none? - return IAttrs.hasFnAttr(llvm::Attribute::ReadNone) && + return MemEffects.doesNotAccessMemory() && IAttrs.hasFnAttr(llvm::Attribute::NoUnwind) ? MemoryBehavior::None : MemoryBehavior::MayHaveSideEffects; diff --git a/lib/SIL/IR/SILInstructions.cpp b/lib/SIL/IR/SILInstructions.cpp index fd7b11b719e..45e6b3e54da 100644 --- a/lib/SIL/IR/SILInstructions.cpp +++ b/lib/SIL/IR/SILInstructions.cpp @@ -814,7 +814,7 @@ DifferentiableFunctionInst *DifferentiableFunctionInst::create( auto derivativeFunctions = VJPAndJVPFunctions.has_value() ? ArrayRef( - reinterpret_cast(VJPAndJVPFunctions.getPointer()), + reinterpret_cast(&*VJPAndJVPFunctions), 2) : ArrayRef(); size_t size = totalSizeToAlloc(1 + derivativeFunctions.size()); @@ -841,7 +841,7 @@ LinearFunctionInst::LinearFunctionInst( : InstructionBaseWithTrailingOperands( OriginalFunction, TransposeFunction.has_value() - ? ArrayRef(TransposeFunction.getPointer(), 1) + ? ArrayRef(&*TransposeFunction, 1) : ArrayRef(), Loc, getLinearFunctionType(OriginalFunction, ParameterIndices), forwardingOwnershipKind), @@ -1068,7 +1068,7 @@ IntegerLiteralInst *IntegerLiteralInst::create(SILDebugLocation Loc, "IntegerLiteralInst APInt value's bit width doesn't match type"); } else { assert(Ty.is()); - assert(Value.getBitWidth() == Value.getMinSignedBits()); + assert(Value.getBitWidth() == Value.getSignificantBits()); } #endif @@ -1085,7 +1085,7 @@ static APInt getAPInt(AnyBuiltinIntegerType *anyIntTy, intmax_t value) { // Otherwise, build using the size of the type and then truncate to the // minimum width necessary. APInt result(8 * sizeof(value), value, /*signed*/ true); - result = result.trunc(result.getMinSignedBits()); + result = result.trunc(result.getSignificantBits()); return result; } diff --git a/lib/SIL/Utils/LoopInfo.cpp b/lib/SIL/Utils/LoopInfo.cpp index a2995d90f43..528ebbc9281 100644 --- a/lib/SIL/Utils/LoopInfo.cpp +++ b/lib/SIL/Utils/LoopInfo.cpp @@ -12,7 +12,7 @@ #include "swift/SIL/LoopInfo.h" #include "swift/SIL/Dominance.h" -#include "llvm/Analysis/LoopInfoImpl.h" +#include "llvm/Support/GenericLoopInfoImpl.h" #include "llvm/Support/Debug.h" using namespace swift; diff --git a/lib/SIL/Utils/OwnershipUtils.cpp b/lib/SIL/Utils/OwnershipUtils.cpp index 6ce21041ee4..a4af289b42f 100644 --- a/lib/SIL/Utils/OwnershipUtils.cpp +++ b/lib/SIL/Utils/OwnershipUtils.cpp @@ -490,7 +490,7 @@ bool swift::visitGuaranteedForwardingPhisForSSAValue( // guaranteedForwardingOps is a collection of all transitive // GuaranteedForwarding uses of \p value. It is a set, to avoid repeated // processing of structs and tuples which are GuaranteedForwarding. - SmallSetVector guaranteedForwardingOps; + llvm::SmallSetVector guaranteedForwardingOps; // Collect first-level GuaranteedForwarding uses, and call the visitor on any // GuaranteedForwardingPhi uses. for (auto *use : value->getUses()) { @@ -1171,7 +1171,7 @@ bool swift::getAllBorrowIntroducingValues(SILValue inputValue, if (inputValue->getOwnershipKind() != OwnershipKind::Guaranteed) return false; - SmallSetVector worklist; + llvm::SmallSetVector worklist; worklist.insert(inputValue); // worklist grows in this loop. @@ -1566,7 +1566,7 @@ void swift::visitExtendedReborrowPhiBaseValuePairs( // paths. // For that reason, worklist stores (reborrow, base value) pairs. // We need a SetVector to make sure we don't revisit the same pair again. - SmallSetVector, 4> worklist; + llvm::SmallSetVector, 4> worklist; // Find all reborrows of value and insert the (reborrow, base value) pair into // the worklist. @@ -1622,7 +1622,7 @@ void swift::visitExtendedGuaranteedForwardingPhiBaseValuePairs( // For that reason, worklist stores (GuaranteedForwardingPhi operand, base // value) pairs. We need a SetVector to make sure we don't revisit the same // pair again. - SmallSetVector, 4> worklist; + llvm::SmallSetVector, 4> worklist; auto collectGuaranteedForwardingPhis = [&](SILValue value, SILValue baseValue) { diff --git a/lib/SIL/Verifier/LinearLifetimeChecker.cpp b/lib/SIL/Verifier/LinearLifetimeChecker.cpp index 3d336f1251c..911bab0bbd6 100644 --- a/lib/SIL/Verifier/LinearLifetimeChecker.cpp +++ b/lib/SIL/Verifier/LinearLifetimeChecker.cpp @@ -103,7 +103,7 @@ struct State { /// A list of successor blocks that we must visit by the time the algorithm /// terminates. - SmallSetVector successorBlocksThatMustBeVisited; + llvm::SmallSetVector successorBlocksThatMustBeVisited; State( SILValue value, LinearLifetimeChecker::ErrorBuilder &errorBuilder, diff --git a/lib/SILGen/SILGenThunk.cpp b/lib/SILGen/SILGenThunk.cpp index 9846c4c5cbc..05efed128d3 100644 --- a/lib/SILGen/SILGenThunk.cpp +++ b/lib/SILGen/SILGenThunk.cpp @@ -32,6 +32,7 @@ #include "swift/AST/ForeignAsyncConvention.h" #include "swift/AST/ForeignErrorConvention.h" #include "swift/AST/GenericEnvironment.h" +#include "swift/Basic/STLExtras.h" #include "swift/SIL/FormalLinkage.h" #include "swift/SIL/PrettyStackTrace.h" #include "swift/SIL/SILArgument.h" @@ -325,9 +326,9 @@ SILFunction *SILGenModule::getOrCreateForeignAsyncCompletionHandlerImplFunction( // Check for an error if the convention includes one. // Increment the error and flag indices if present. They do not account // for the fact that they are preceded by the block_storage arguments. - auto errorIndex = convention.completionHandlerErrorParamIndex().transform( + auto errorIndex = swift::transform(convention.completionHandlerErrorParamIndex(), [](auto original) { return original + 1; }); - auto flagIndex = convention.completionHandlerFlagParamIndex().transform( + auto flagIndex = swift::transform(convention.completionHandlerFlagParamIndex(), [](auto original) { return original + 1; }); FuncDecl *resumeIntrinsic; diff --git a/lib/SILOptimizer/Analysis/ARCAnalysis.cpp b/lib/SILOptimizer/Analysis/ARCAnalysis.cpp index 466d7c32118..c9f3ec3a948 100644 --- a/lib/SILOptimizer/Analysis/ARCAnalysis.cpp +++ b/lib/SILOptimizer/Analysis/ARCAnalysis.cpp @@ -104,7 +104,7 @@ static bool canApplyOfBuiltinUseNonTrivialValues(BuiltinInst *BInst) { auto &II = BInst->getIntrinsicInfo(); if (II.ID != llvm::Intrinsic::not_intrinsic) { auto attrs = II.getOrCreateAttributes(F->getASTContext()); - if (attrs.hasFnAttr(llvm::Attribute::ReadNone)) { + if (attrs.getMemoryEffects().doesNotAccessMemory()) { for (auto &Op : BInst->getAllOperands()) { if (!Op.get()->getType().isTrivial(*F)) { return true; diff --git a/lib/SILOptimizer/Analysis/CallerAnalysis.cpp b/lib/SILOptimizer/Analysis/CallerAnalysis.cpp index dabe79dbacc..1cef7efe4ef 100644 --- a/lib/SILOptimizer/Analysis/CallerAnalysis.cpp +++ b/lib/SILOptimizer/Analysis/CallerAnalysis.cpp @@ -51,7 +51,7 @@ struct CallerAnalysis::ApplySiteFinderVisitor #ifndef NDEBUG SmallPtrSet visitedCallSites; - SmallSetVector callSitesThatMustBeVisited; + llvm::SmallSetVector callSitesThatMustBeVisited; #endif ApplySiteFinderVisitor(CallerAnalysis *analysis, SILFunction *callerFn) diff --git a/lib/SILOptimizer/Differentiation/Common.cpp b/lib/SILOptimizer/Differentiation/Common.cpp index aec5f1e09b3..fd9d1935758 100644 --- a/lib/SILOptimizer/Differentiation/Common.cpp +++ b/lib/SILOptimizer/Differentiation/Common.cpp @@ -14,6 +14,7 @@ // //===----------------------------------------------------------------------===// +#include "swift/Basic/STLExtras.h" #define DEBUG_TYPE "differentiation" #include "swift/SILOptimizer/Differentiation/Common.h" @@ -212,8 +213,8 @@ void collectMinimalIndicesForFunctionCall( results.reserve(calleeFnTy->getNumResults()); unsigned dirResIdx = 0; unsigned indResIdx = calleeConvs.getSILArgIndexOfFirstIndirectResult(); - for (auto &resAndIdx : enumerate(calleeConvs.getResults())) { - auto &res = resAndIdx.value(); + for (const auto &resAndIdx : enumerate(calleeConvs.getResults())) { + const auto &res = resAndIdx.value(); unsigned idx = resAndIdx.index(); if (res.isFormalDirect()) { results.push_back(directResults[dirResIdx]); @@ -231,8 +232,8 @@ void collectMinimalIndicesForFunctionCall( // Record all semantic result parameters as results. auto semanticResultParamResultIndex = calleeFnTy->getNumResults(); - for (auto ¶mAndIdx : enumerate(calleeConvs.getParameters())) { - auto ¶m = paramAndIdx.value(); + for (const auto ¶mAndIdx : enumerate(calleeConvs.getParameters())) { + const auto ¶m = paramAndIdx.value(); if (!param.isAutoDiffSemanticResult()) continue; unsigned idx = paramAndIdx.index() + calleeFnTy->getNumIndirectFormalResults(); @@ -252,12 +253,12 @@ void collectMinimalIndicesForFunctionCall( llvm::Optional> findDebugLocationAndVariable(SILValue originalValue) { if (auto *asi = dyn_cast(originalValue)) - return asi->getVarInfo().transform([&](SILDebugVariable var) { + return swift::transform(asi->getVarInfo(), [&](SILDebugVariable var) { return std::make_pair(asi->getDebugLocation(), var); }); for (auto *use : originalValue->getUses()) { if (auto *dvi = dyn_cast(use->getUser())) - return dvi->getVarInfo().transform([&](SILDebugVariable var) { + return swift::transform(dvi->getVarInfo(), [&](SILDebugVariable var) { // We need to drop `op_deref` here as we're transferring debug info // location from debug_value instruction (which describes how to get value) // into alloc_stack (which describes the location) diff --git a/lib/SILOptimizer/Differentiation/PullbackCloner.cpp b/lib/SILOptimizer/Differentiation/PullbackCloner.cpp index 8f02307b370..90f8148391f 100644 --- a/lib/SILOptimizer/Differentiation/PullbackCloner.cpp +++ b/lib/SILOptimizer/Differentiation/PullbackCloner.cpp @@ -15,6 +15,7 @@ // //===----------------------------------------------------------------------===// +#include "swift/Basic/STLExtras.h" #define DEBUG_TYPE "differentiation" #include "swift/SILOptimizer/Differentiation/PullbackCloner.h" @@ -110,7 +111,7 @@ private: /// Mapping from original basic blocks to local temporary values to be cleaned /// up. This is populated when pullback emission is run on one basic block and /// cleaned before processing another basic block. - llvm::DenseMap> + llvm::DenseMap> blockTemporaries; /// The scope cloner. @@ -651,7 +652,7 @@ private: llvm::SmallString<32> adjName; auto *newBuf = createFunctionLocalAllocation( bufType, loc, /*zeroInitialize*/ true, - debugInfo.transform( + swift::transform(debugInfo, [&](AdjointValue::DebugInfo di) { llvm::raw_svector_ostream adjNameStream(adjName); SILDebugVariable &dv = di.second; diff --git a/lib/SILOptimizer/LoopTransforms/ForEachLoopUnroll.cpp b/lib/SILOptimizer/LoopTransforms/ForEachLoopUnroll.cpp index ddc631ef15e..e6f6c6ff052 100644 --- a/lib/SILOptimizer/LoopTransforms/ForEachLoopUnroll.cpp +++ b/lib/SILOptimizer/LoopTransforms/ForEachLoopUnroll.cpp @@ -159,7 +159,7 @@ class ArrayInfo { llvm::DenseMap elementStoreMap; /// List of Sequence.forEach calls invoked on the array. - SmallSetVector forEachCalls; + llvm::SmallSetVector forEachCalls; /// Indicates whether the array could be modified after initialization. Note /// that this not include modifications to the elements of the array. When diff --git a/lib/SILOptimizer/Mandatory/ClosureLifetimeFixup.cpp b/lib/SILOptimizer/Mandatory/ClosureLifetimeFixup.cpp index 8af40201a34..3e5b5f180c8 100644 --- a/lib/SILOptimizer/Mandatory/ClosureLifetimeFixup.cpp +++ b/lib/SILOptimizer/Mandatory/ClosureLifetimeFixup.cpp @@ -722,9 +722,9 @@ static SILValue tryRewriteToPartialApplyStack( SmallVector discoveredBlocks; SSAPrunedLiveness closureLiveness(cvt->getFunction(), &discoveredBlocks); closureLiveness.initializeDef(closureOp); - - SmallSetVector borrowedOriginals; - + + llvm::SmallSetVector borrowedOriginals; + unsigned appliedArgStartIdx = newPA->getOrigCalleeType()->getNumParameters() - newPA->getNumArguments(); diff --git a/lib/SILOptimizer/Mandatory/ConsumeOperatorCopyableAddressesChecker.cpp b/lib/SILOptimizer/Mandatory/ConsumeOperatorCopyableAddressesChecker.cpp index bf2f21a9baa..180e929ec60 100644 --- a/lib/SILOptimizer/Mandatory/ConsumeOperatorCopyableAddressesChecker.cpp +++ b/lib/SILOptimizer/Mandatory/ConsumeOperatorCopyableAddressesChecker.cpp @@ -300,8 +300,8 @@ struct UseState { SILValue address; SmallVector markMoves; SmallPtrSet seenMarkMoves; - SmallSetVector inits; - SmallSetVector livenessUses; + llvm::SmallSetVector inits; + llvm::SmallSetVector livenessUses; SmallBlotSetVector destroys; llvm::SmallDenseMap destroyToIndexMap; SmallBlotSetVector reinits; @@ -2474,7 +2474,7 @@ class ConsumeOperatorCopyableAddressesCheckerPass assert(fn->getModule().getStage() == SILStage::Raw && "Should only run on Raw SIL"); - SmallSetVector addressesToCheck; + llvm::SmallSetVector addressesToCheck; for (auto *arg : fn->front().getSILFunctionArguments()) { if (arg->getType().isAddress() && diff --git a/lib/SILOptimizer/Mandatory/ConsumeOperatorCopyableValuesChecker.cpp b/lib/SILOptimizer/Mandatory/ConsumeOperatorCopyableValuesChecker.cpp index 10e7d3042e7..f685c986833 100644 --- a/lib/SILOptimizer/Mandatory/ConsumeOperatorCopyableValuesChecker.cpp +++ b/lib/SILOptimizer/Mandatory/ConsumeOperatorCopyableValuesChecker.cpp @@ -55,8 +55,8 @@ namespace { struct CheckerLivenessInfo { GraphNodeWorklist defUseWorklist; - SmallSetVector consumingUse; - SmallSetVector nonLifetimeEndingUsesInLiveOut; + llvm::SmallSetVector consumingUse; + llvm::SmallSetVector nonLifetimeEndingUsesInLiveOut; SmallVector interiorPointerTransitiveUses; BitfieldRef liveness; @@ -397,7 +397,7 @@ void ConsumeOperatorCopyableValuesChecker::emitDiagnosticForMove( } bool ConsumeOperatorCopyableValuesChecker::check() { - SmallSetVector valuesToCheck; + llvm::SmallSetVector valuesToCheck; for (auto *arg : fn->getEntryBlock()->getSILFunctionArguments()) { if (arg->getOwnershipKind() == OwnershipKind::Owned && diff --git a/lib/SILOptimizer/Mandatory/DataflowDiagnostics.cpp b/lib/SILOptimizer/Mandatory/DataflowDiagnostics.cpp index d6c5344dd13..3061d6e2f9f 100644 --- a/lib/SILOptimizer/Mandatory/DataflowDiagnostics.cpp +++ b/lib/SILOptimizer/Mandatory/DataflowDiagnostics.cpp @@ -180,7 +180,7 @@ static void diagnosePoundAssert(const SILInstruction *I, APInt intValue = value.getIntegerValue(); assert(intValue.getBitWidth() == 1 && "sema prevents non-int1 #assert condition"); - if (intValue.isNullValue()) { + if (intValue.isZero()) { auto *message = cast(builtinInst->getArguments()[1]); StringRef messageValue = message->getValue(); if (messageValue.empty()) diff --git a/lib/SILOptimizer/Mandatory/DefiniteInitialization.cpp b/lib/SILOptimizer/Mandatory/DefiniteInitialization.cpp index 34f8a435ad2..675763657e2 100644 --- a/lib/SILOptimizer/Mandatory/DefiniteInitialization.cpp +++ b/lib/SILOptimizer/Mandatory/DefiniteInitialization.cpp @@ -2747,7 +2747,7 @@ static void updateControlVariable(SILLocation Loc, // If the mask is all ones, do a simple store, otherwise do a // load/or/store sequence to mask in the bits. - if (!Bitmask.isAllOnesValue()) { + if (!Bitmask.isAllOnes()) { SILValue Tmp = B.createLoad(Loc, ControlVariable, LoadOwnershipQualifier::Trivial); if (!OrFn.get()) diff --git a/lib/SILOptimizer/Mandatory/DiagnoseInfiniteRecursion.cpp b/lib/SILOptimizer/Mandatory/DiagnoseInfiniteRecursion.cpp index 26afe1f60eb..24a025cbecc 100644 --- a/lib/SILOptimizer/Mandatory/DiagnoseInfiniteRecursion.cpp +++ b/lib/SILOptimizer/Mandatory/DiagnoseInfiniteRecursion.cpp @@ -41,6 +41,7 @@ #include "swift/AST/DiagnosticsSIL.h" #include "swift/SIL/SILArgument.h" #include "swift/SIL/SILInstruction.h" +#include "swift/Basic/LLVMExtras.h" #include "swift/SIL/ApplySite.h" #include "swift/SIL/MemAccessUtils.h" #include "swift/SIL/BasicBlockData.h" @@ -525,7 +526,7 @@ public: } }; -typedef SmallSetVector InvariantsSet; +typedef swift::SmallSetVector InvariantsSet; /// Collect invariants with which we should try the analysis and return true if /// there is at least one recursive call in the function. diff --git a/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp b/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp index 36663cc45cd..188db83982e 100644 --- a/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp +++ b/lib/SILOptimizer/Mandatory/DiagnoseStaticExclusivity.cpp @@ -977,7 +977,7 @@ static void checkStaticExclusivity(SILFunction &Fn, PostOrderFunctionInfo *PO, // The in-progress accesses for the current program point, represented // as map from storage locations to the accesses in progress for the // location. - State.Accesses = BBState.getPointer(); + State.Accesses = &*BBState; for (auto &I : *BB) checkForViolationsAtInstruction(I, State); } diff --git a/lib/SILOptimizer/Mandatory/MoveOnlyAddressCheckerTester.cpp b/lib/SILOptimizer/Mandatory/MoveOnlyAddressCheckerTester.cpp index 52294775fb8..334397919f3 100644 --- a/lib/SILOptimizer/Mandatory/MoveOnlyAddressCheckerTester.cpp +++ b/lib/SILOptimizer/Mandatory/MoveOnlyAddressCheckerTester.cpp @@ -95,7 +95,7 @@ class MoveOnlyAddressCheckerTesterPass : public SILFunctionTransform { auto *poa = getAnalysis(); DiagnosticEmitter diagnosticEmitter(fn); - SmallSetVector + llvm::SmallSetVector moveIntroducersToProcess; searchForCandidateAddressMarkUnresolvedNonCopyableValueInsts( fn, moveIntroducersToProcess, diagnosticEmitter); diff --git a/lib/SILOptimizer/Mandatory/MoveOnlyAddressCheckerUtils.cpp b/lib/SILOptimizer/Mandatory/MoveOnlyAddressCheckerUtils.cpp index e2f8587ebbd..a94e1361708 100644 --- a/lib/SILOptimizer/Mandatory/MoveOnlyAddressCheckerUtils.cpp +++ b/lib/SILOptimizer/Mandatory/MoveOnlyAddressCheckerUtils.cpp @@ -520,14 +520,14 @@ struct UseState { SmallFrozenMultiMap reinitToValueMultiMap; /// The set of drop_deinits of this mark_unresolved_non_copyable_value - SmallSetVector dropDeinitInsts; + llvm::SmallSetVector dropDeinitInsts; /// A "inout terminator use" is an implicit liveness use of the entire value /// placed on a terminator. We use this both so we add liveness for the /// terminator user and so that we can use the set to quickly identify later /// while emitting diagnostics that a liveness use is a terminator user and /// emit a specific diagnostic message. - SmallSetVector implicitEndOfLifetimeLivenessUses; + llvm::SmallSetVector implicitEndOfLifetimeLivenessUses; /// We add debug_values to liveness late after we diagnose, but before we /// hoist destroys to ensure that we do not hoist destroys out of access @@ -600,7 +600,7 @@ struct UseState { /// and precedes a reinit instruction in that block. bool precedesReinitInSameBlock(SILInstruction *inst) const { SILBasicBlock *block = inst->getParent(); - SmallSetVector sameBlockReinits; + llvm::SmallSetVector sameBlockReinits; // First, search for all reinits that are within the same block. for (auto &reinit : reinitInsts) { @@ -1326,7 +1326,7 @@ struct MoveOnlyAddressCheckerPImpl { /// A set of mark_unresolved_non_copyable_value that we are actually going to /// process. - SmallSetVector + llvm::SmallSetVector moveIntroducersToProcess; /// The instruction deleter used by \p canonicalizer. @@ -2633,7 +2633,7 @@ bool GlobalLivenessChecker::testInstVectorLiveness( LLVM_DEBUG(llvm::dbgs() << "Performing forward traversal from errorUse " "looking for the cause of liveness!\n"); - SmallSetVector violatingInst; + llvm::SmallSetVector violatingInst; bool foundSingleBlockError = false; while (auto *block = worklist.pop()) { LLVM_DEBUG(llvm::dbgs() @@ -3660,7 +3660,7 @@ static llvm::cl::opt llvm::cl::init(false)); bool MoveOnlyAddressChecker::check( - SmallSetVector + llvm::SmallSetVector &moveIntroducersToProcess) { assert(moveIntroducersToProcess.size() && "Must have checks to process to call this function"); diff --git a/lib/SILOptimizer/Mandatory/MoveOnlyAddressCheckerUtils.h b/lib/SILOptimizer/Mandatory/MoveOnlyAddressCheckerUtils.h index ef4bf9b7a31..93744f676d7 100644 --- a/lib/SILOptimizer/Mandatory/MoveOnlyAddressCheckerUtils.h +++ b/lib/SILOptimizer/Mandatory/MoveOnlyAddressCheckerUtils.h @@ -27,7 +27,7 @@ class DiagnosticEmitter; /// diagnosticEmitter.getDiagnosticCount(). void searchForCandidateAddressMarkUnresolvedNonCopyableValueInsts( SILFunction *fn, - SmallSetVector + llvm::SmallSetVector &moveIntroducersToProcess, DiagnosticEmitter &diagnosticEmitter); @@ -40,7 +40,7 @@ struct MoveOnlyAddressChecker { /// \returns true if we changed the IR. To see if we emitted a diagnostic, use /// \p diagnosticEmitter.getDiagnosticCount(). - bool check(SmallSetVector + bool check(llvm::SmallSetVector &moveIntroducersToProcess); }; diff --git a/lib/SILOptimizer/Mandatory/MoveOnlyBorrowToDestructureTester.cpp b/lib/SILOptimizer/Mandatory/MoveOnlyBorrowToDestructureTester.cpp index 731b8e3ac21..983d016f8d5 100644 --- a/lib/SILOptimizer/Mandatory/MoveOnlyBorrowToDestructureTester.cpp +++ b/lib/SILOptimizer/Mandatory/MoveOnlyBorrowToDestructureTester.cpp @@ -88,7 +88,7 @@ class MoveOnlyBorrowToDestructureTransformPass : public SILFunctionTransform { auto *postOrderAnalysis = getAnalysis(); - SmallSetVector + llvm::SmallSetVector moveIntroducersToProcess; DiagnosticEmitter diagnosticEmitter(getFunction()); diff --git a/lib/SILOptimizer/Mandatory/MoveOnlyChecker.cpp b/lib/SILOptimizer/Mandatory/MoveOnlyChecker.cpp index 0f0d9ff882d..7b1847c2d4e 100644 --- a/lib/SILOptimizer/Mandatory/MoveOnlyChecker.cpp +++ b/lib/SILOptimizer/Mandatory/MoveOnlyChecker.cpp @@ -94,7 +94,7 @@ struct MoveOnlyChecker { } // namespace void MoveOnlyChecker::checkObjects() { - SmallSetVector + llvm::SmallSetVector moveIntroducersToProcess; unsigned diagCount = diagnosticEmitter.getDiagnosticCount(); madeChange |= searchForCandidateObjectMarkUnresolvedNonCopyableValueInsts( @@ -183,7 +183,7 @@ void MoveOnlyChecker::completeObjectLifetimes( void MoveOnlyChecker::checkAddresses() { unsigned diagCount = diagnosticEmitter.getDiagnosticCount(); - SmallSetVector + llvm::SmallSetVector moveIntroducersToProcess; searchForCandidateAddressMarkUnresolvedNonCopyableValueInsts( fn, moveIntroducersToProcess, diagnosticEmitter); diff --git a/lib/SILOptimizer/Mandatory/MoveOnlyObjectCheckerTester.cpp b/lib/SILOptimizer/Mandatory/MoveOnlyObjectCheckerTester.cpp index 1506feca4dc..9cb4fb0ba29 100644 --- a/lib/SILOptimizer/Mandatory/MoveOnlyObjectCheckerTester.cpp +++ b/lib/SILOptimizer/Mandatory/MoveOnlyObjectCheckerTester.cpp @@ -97,7 +97,7 @@ class MoveOnlyObjectCheckerTesterPass : public SILFunctionTransform { borrowtodestructure::IntervalMapAllocator allocator; unsigned diagCount = diagnosticEmitter.getDiagnosticCount(); - SmallSetVector + llvm::SmallSetVector moveIntroducersToProcess; bool madeChange = searchForCandidateObjectMarkUnresolvedNonCopyableValueInsts( diff --git a/lib/SILOptimizer/Mandatory/MoveOnlyObjectCheckerUtils.cpp b/lib/SILOptimizer/Mandatory/MoveOnlyObjectCheckerUtils.cpp index 721fefd6130..49b4519ccd9 100644 --- a/lib/SILOptimizer/Mandatory/MoveOnlyObjectCheckerUtils.cpp +++ b/lib/SILOptimizer/Mandatory/MoveOnlyObjectCheckerUtils.cpp @@ -70,7 +70,7 @@ using namespace swift::siloptimizer; bool swift::siloptimizer:: searchForCandidateObjectMarkUnresolvedNonCopyableValueInsts( SILFunction *fn, - SmallSetVector + llvm::SmallSetVector &moveIntroducersToProcess, DiagnosticEmitter &emitter) { bool localChanged = false; diff --git a/lib/SILOptimizer/Mandatory/MoveOnlyObjectCheckerUtils.h b/lib/SILOptimizer/Mandatory/MoveOnlyObjectCheckerUtils.h index 84888c2f4d3..1bfec32966b 100644 --- a/lib/SILOptimizer/Mandatory/MoveOnlyObjectCheckerUtils.h +++ b/lib/SILOptimizer/Mandatory/MoveOnlyObjectCheckerUtils.h @@ -169,7 +169,7 @@ struct OSSACanonicalizer { /// must checks to process. bool searchForCandidateObjectMarkUnresolvedNonCopyableValueInsts( SILFunction *fn, - SmallSetVector + llvm::SmallSetVector &moveIntroducersToProcess, DiagnosticEmitter &diagnosticEmitter); diff --git a/lib/SILOptimizer/Mandatory/MoveOnlyTempAllocationFromLetTester.cpp b/lib/SILOptimizer/Mandatory/MoveOnlyTempAllocationFromLetTester.cpp index 6007dc783c9..8a172825a42 100644 --- a/lib/SILOptimizer/Mandatory/MoveOnlyTempAllocationFromLetTester.cpp +++ b/lib/SILOptimizer/Mandatory/MoveOnlyTempAllocationFromLetTester.cpp @@ -49,7 +49,7 @@ struct MoveOnlyTempAllocationFromLetTester : SILFunctionTransform { << "===> MoveOnlyTempAllocationFromLetTester. Visiting: " << fn->getName() << '\n'); - SmallSetVector + llvm::SmallSetVector moveIntroducersToProcess; DiagnosticEmitter diagnosticEmitter(getFunction()); diff --git a/lib/SILOptimizer/Mandatory/MoveOnlyWrappedTypeEliminator.cpp b/lib/SILOptimizer/Mandatory/MoveOnlyWrappedTypeEliminator.cpp index 9439ada3bd4..1be825ebc52 100644 --- a/lib/SILOptimizer/Mandatory/MoveOnlyWrappedTypeEliminator.cpp +++ b/lib/SILOptimizer/Mandatory/MoveOnlyWrappedTypeEliminator.cpp @@ -51,10 +51,10 @@ namespace { struct SILMoveOnlyWrappedTypeEliminatorVisitor : SILInstructionVisitor { - const SmallSetVector &touchedArgs; + const llvm::SmallSetVector &touchedArgs; SILMoveOnlyWrappedTypeEliminatorVisitor( - const SmallSetVector &touchedArgs) + const llvm::SmallSetVector &touchedArgs) : touchedArgs(touchedArgs) {} bool visitSILInstruction(SILInstruction *inst) { @@ -294,8 +294,8 @@ static bool isMoveOnlyWrappedTrivial(SILValue value) { bool SILMoveOnlyWrappedTypeEliminator::process() { bool madeChange = true; - SmallSetVector touchedArgs; - SmallSetVector touchedInsts; + llvm::SmallSetVector touchedArgs; + llvm::SmallSetVector touchedInsts; for (auto &bb : *fn) { for (auto *arg : bb.getArguments()) { diff --git a/lib/SILOptimizer/Mandatory/OSLogOptimization.cpp b/lib/SILOptimizer/Mandatory/OSLogOptimization.cpp index 7c54bd2c9e3..649836bed87 100644 --- a/lib/SILOptimizer/Mandatory/OSLogOptimization.cpp +++ b/lib/SILOptimizer/Mandatory/OSLogOptimization.cpp @@ -196,7 +196,7 @@ public: SILInstruction *beginInstruction; /// Instructions that mark the end points of constant evaluation. - SmallSetVector endInstructions; + llvm::SmallSetVector endInstructions; private: /// SIL values that were found to be constants during diff --git a/lib/SILOptimizer/Mandatory/PredictableMemOpt.cpp b/lib/SILOptimizer/Mandatory/PredictableMemOpt.cpp index 6845c8ea93e..4dcd1aeaa19 100644 --- a/lib/SILOptimizer/Mandatory/PredictableMemOpt.cpp +++ b/lib/SILOptimizer/Mandatory/PredictableMemOpt.cpp @@ -187,7 +187,7 @@ struct AvailableValue { /// If this gets too expensive in terms of copying, we can use an arena and a /// FrozenPtrSet like we do in ARC. - SmallSetVector InsertionPoints; + llvm::SmallSetVector InsertionPoints; /// Just for updating. SmallVectorImpl *Uses; diff --git a/lib/SILOptimizer/Mandatory/RawSILInstLowering.cpp b/lib/SILOptimizer/Mandatory/RawSILInstLowering.cpp index 74283192ba9..36c8b0d2717 100644 --- a/lib/SILOptimizer/Mandatory/RawSILInstLowering.cpp +++ b/lib/SILOptimizer/Mandatory/RawSILInstLowering.cpp @@ -181,7 +181,7 @@ static void emitInitAccessorInitialValueArgument( static void lowerAssignByWrapperInstruction(SILBuilderWithScope &b, AssignByWrapperInst *inst, - SmallSetVector &toDelete) { + llvm::SmallSetVector &toDelete) { LLVM_DEBUG(llvm::dbgs() << " *** Lowering " << *inst << "\n"); ++numAssignRewritten; @@ -263,7 +263,7 @@ lowerAssignByWrapperInstruction(SILBuilderWithScope &b, static void lowerAssignOrInitInstruction(SILBuilderWithScope &b, AssignOrInitInst *inst, - SmallSetVector &toDelete) { + llvm::SmallSetVector &toDelete) { LLVM_DEBUG(llvm::dbgs() << " *** Lowering " << *inst << "\n"); ++numAssignRewritten; @@ -422,7 +422,7 @@ static bool lowerRawSILOperations(SILFunction &fn) { bool changed = false; for (auto &bb : fn) { - SmallSetVector toDelete; + llvm::SmallSetVector toDelete; auto i = bb.begin(), e = bb.end(); while (i != e) { diff --git a/lib/SILOptimizer/SILCombiner/SILCombine.cpp b/lib/SILOptimizer/SILCombiner/SILCombine.cpp index 0959b8733a9..3f690bcc05a 100644 --- a/lib/SILOptimizer/SILCombiner/SILCombine.cpp +++ b/lib/SILOptimizer/SILCombiner/SILCombine.cpp @@ -298,7 +298,7 @@ void SILCombiner::canonicalizeOSSALifetimes(SILInstruction *currentInst) { if (!enableCopyPropagation || !Builder.hasOwnership()) return; - SmallSetVector defsToCanonicalize; + llvm::SmallSetVector defsToCanonicalize; // copyInst was either optimized by a SILCombine visitor or is a copy_value // produced by the visitor. Find the canonical def. diff --git a/lib/SILOptimizer/Transforms/DeadObjectElimination.cpp b/lib/SILOptimizer/Transforms/DeadObjectElimination.cpp index e8f25d569c1..71391340da1 100644 --- a/lib/SILOptimizer/Transforms/DeadObjectElimination.cpp +++ b/lib/SILOptimizer/Transforms/DeadObjectElimination.cpp @@ -328,7 +328,7 @@ static bool onlyStoresToTailObjects(BuiltinInst *destroyArray, AllocRefInstBase *allocRef) { // Get the number of destroyed elements. auto *literal = dyn_cast(destroyArray->getArguments()[2]); - if (!literal || literal->getValue().getMinSignedBits() > 32) + if (!literal || literal->getValue().getSignificantBits() > 32) return false; int numDestroyed = literal->getValue().getSExtValue(); diff --git a/lib/SILOptimizer/Transforms/DestroyAddrHoisting.cpp b/lib/SILOptimizer/Transforms/DestroyAddrHoisting.cpp index 36b42b2a5cf..755cc2d2ee8 100644 --- a/lib/SILOptimizer/Transforms/DestroyAddrHoisting.cpp +++ b/lib/SILOptimizer/Transforms/DestroyAddrHoisting.cpp @@ -113,7 +113,7 @@ struct KnownStorageUses : UniqueStorageUseVisitor { bool preserveDebugInfo; SmallPtrSet storageUsers; - SmallSetVector originalDestroys; + llvm::SmallSetVector originalDestroys; SmallPtrSet debugInsts; KnownStorageUses(AccessStorage storage, SILFunction *function) @@ -199,17 +199,17 @@ class DeinitBarriers final { public: // Instructions beyond which a destroy_addr cannot be hoisted, reachable from // a destroy_addr. Deinit barriers or storage uses. - SmallSetVector barrierInstructions; + llvm::SmallSetVector barrierInstructions; // Phis beyond which a destroy_addr cannot be hoisted, reachable from a // destroy_addr. - SmallSetVector barrierPhis; + llvm::SmallSetVector barrierPhis; // Blocks beyond the end of which a destroy_addr cannot be hoisted. - SmallSetVector barrierBlocks; + llvm::SmallSetVector barrierBlocks; // Debug instructions that are no longer within this lifetime after shrinking. - SmallSetVector deadUsers; + llvm::SmallSetVector deadUsers; // The access scopes which are hoisting barriers. // diff --git a/lib/SILOptimizer/Transforms/PhiArgumentOptimizations.cpp b/lib/SILOptimizer/Transforms/PhiArgumentOptimizations.cpp index 931436e99e8..23336e62ebe 100644 --- a/lib/SILOptimizer/Transforms/PhiArgumentOptimizations.cpp +++ b/lib/SILOptimizer/Transforms/PhiArgumentOptimizations.cpp @@ -95,7 +95,7 @@ void RedundantPhiEliminationPass::run() { #ifndef NDEBUG static bool hasOnlyNoneOwnershipIncomingValues(SILPhiArgument *phi) { - SmallSetVector worklist; + llvm::SmallSetVector worklist; SmallVector incomingValues; worklist.insert(phi); diff --git a/lib/SILOptimizer/Transforms/SILCodeMotion.cpp b/lib/SILOptimizer/Transforms/SILCodeMotion.cpp index 480d67542ec..30b0787bae0 100644 --- a/lib/SILOptimizer/Transforms/SILCodeMotion.cpp +++ b/lib/SILOptimizer/Transforms/SILCodeMotion.cpp @@ -819,7 +819,7 @@ void BBEnumTagDataflowState::dump() const { llvm::dbgs() << "Dumping state for BB" << BB.get()->getDebugID() << "\n"; llvm::dbgs() << "Block States:\n"; for (auto &P : ValueToCaseMap) { - if (!P.hasValue()) { + if (!P) { llvm::dbgs() << " Skipping blotted value.\n"; continue; } @@ -835,7 +835,7 @@ void BBEnumTagDataflowState::dump() const { llvm::dbgs() << "Predecessor States:\n"; // For each (EnumValue, [(BB, EnumTag)]) that we are tracking... for (auto &P : EnumToEnumBBCaseListMap) { - if (!P.hasValue()) { + if (!P) { llvm::dbgs() << " Skipping blotted value.\n"; continue; } diff --git a/lib/SILOptimizer/UtilityPasses/Link.cpp b/lib/SILOptimizer/UtilityPasses/Link.cpp index c84db616463..136410e7fdb 100644 --- a/lib/SILOptimizer/UtilityPasses/Link.cpp +++ b/lib/SILOptimizer/UtilityPasses/Link.cpp @@ -45,17 +45,20 @@ public: } void linkEmbeddedRuntimeFromStdlib() { - #define FUNCTION(ID, NAME, CC, AVAILABILITY, RETURNS, ARGS, ATTRS, EFFECT) \ - linkEmbeddedRuntimeFunctionByName(#NAME); +#define FUNCTION(ID, NAME, CC, AVAILABILITY, RETURNS, ARGS, ATTRS, EFFECT, \ + MEMORY_EFFECTS) \ + linkEmbeddedRuntimeFunctionByName(#NAME); - #define RETURNS(...) - #define ARGS(...) - #define NO_ARGS - #define ATTRS(...) - #define NO_ATTRS - #define EFFECT(...) +#define RETURNS(...) +#define ARGS(...) +#define NO_ARGS +#define ATTRS(...) +#define NO_ATTRS +#define EFFECT(...) +#define MEMORY_EFFECTS(...) +#define UNKNOWN_MEMEFFECTS - #include "swift/Runtime/RuntimeFunctions.def" +#include "swift/Runtime/RuntimeFunctions.def" } void linkEmbeddedRuntimeFunctionByName(StringRef name) { diff --git a/lib/SILOptimizer/Utils/ConstExpr.cpp b/lib/SILOptimizer/Utils/ConstExpr.cpp index 7cfc77dd673..cc3b0776a04 100644 --- a/lib/SILOptimizer/Utils/ConstExpr.cpp +++ b/lib/SILOptimizer/Utils/ConstExpr.cpp @@ -768,7 +768,7 @@ ConstExprFunctionState::computeConstantValueBuiltin(BuiltinInst *inst) { // Return a statically diagnosed overflow if the operation is supposed to // trap on overflow. - if (overflowed && !operand2.getIntegerValue().isNullValue()) + if (overflowed && !operand2.getIntegerValue().isZero()) return getUnknown(evaluator, SILValue(inst), UnknownReason::Overflow); auto &allocator = evaluator.getAllocator(); diff --git a/lib/SILOptimizer/Utils/Generics.cpp b/lib/SILOptimizer/Utils/Generics.cpp index f9d3f8f77bd..c8d22fa22bf 100644 --- a/lib/SILOptimizer/Utils/Generics.cpp +++ b/lib/SILOptimizer/Utils/Generics.cpp @@ -1119,7 +1119,7 @@ static bool hasNonSelfContainedRequirements(ArchetypeType *Archetype, // we should return true. auto First = Req.getFirstType()->getCanonicalType(); auto Second = Req.getSecondType()->getCanonicalType(); - SmallSetVector UsedGenericParams; + llvm::SmallSetVector UsedGenericParams; First.visit([&](Type Ty) { if (auto *GP = Ty->getAs()) { UsedGenericParams.insert(GP); @@ -1171,7 +1171,7 @@ static void collectRequirements(ArchetypeType *Archetype, GenericSignature Sig, // we should return true. auto First = Req.getFirstType()->getCanonicalType(); auto Second = Req.getSecondType()->getCanonicalType(); - SmallSetVector UsedGenericParams; + llvm::SmallSetVector UsedGenericParams; First.visit([&](Type Ty) { if (auto *GP = Ty->getAs()) { UsedGenericParams.insert(GP); @@ -2884,7 +2884,7 @@ bool usePrespecialized( } unsigned score = 0; - for (auto &entry : + for (const auto &entry : llvm::enumerate(apply.getSubstitutionMap().getReplacementTypes())) { auto genericParam = specializedSig.getGenericParams()[entry.index()]; diff --git a/lib/SILOptimizer/Utils/OwnershipOptUtils.cpp b/lib/SILOptimizer/Utils/OwnershipOptUtils.cpp index aefc0c2f0a7..dddede0f1bc 100644 --- a/lib/SILOptimizer/Utils/OwnershipOptUtils.cpp +++ b/lib/SILOptimizer/Utils/OwnershipOptUtils.cpp @@ -43,7 +43,7 @@ void swift::extendOwnedLifetime(SILValue ownedValue, PrunedLivenessBoundary &lifetimeBoundary, InstructionDeleter &deleter) { // Gather the current set of destroy_values, which may die. - SmallSetVector extraConsumes; + llvm::SmallSetVector extraConsumes; SmallPtrSet extraConsumers; for (Operand *use : ownedValue->getUses()) { if (use->isConsuming()) { @@ -1697,7 +1697,7 @@ SILBasicBlock::iterator OwnershipReplaceSingleUseHelper::perform() { class GuaranteedPhiBorrowFixup { // A phi in mustConvertPhis has already been determined to be part of this // new nested borrow scope. - SmallSetVector mustConvertPhis; + llvm::SmallSetVector mustConvertPhis; // Phi operands that are already within the new nested borrow scope. llvm::SmallDenseSet nestedPhiOperands; diff --git a/lib/Sema/CSBindings.cpp b/lib/Sema/CSBindings.cpp index 80ef61bc4bf..b79fc40c6c7 100644 --- a/lib/Sema/CSBindings.cpp +++ b/lib/Sema/CSBindings.cpp @@ -317,7 +317,7 @@ void BindingSet::inferTransitiveProtocolRequirements( // class, make it a "representative" and let it infer // supertypes and direct protocol requirements from // other members and their equivalence classes. - SmallSetVector equivalenceClass; + llvm::SmallSetVector equivalenceClass; { SmallVector workList; workList.push_back(currentVar); diff --git a/lib/Sema/ConstraintSystem.cpp b/lib/Sema/ConstraintSystem.cpp index fbc8c18de08..26e543eb640 100644 --- a/lib/Sema/ConstraintSystem.cpp +++ b/lib/Sema/ConstraintSystem.cpp @@ -38,6 +38,7 @@ #include "llvm/ADT/SmallString.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Format.h" +#include using namespace swift; using namespace constraints; @@ -4564,7 +4565,7 @@ static bool diagnoseConflictingGenericArguments(ConstraintSystem &cs, auto *typeVar = entry.first; auto GP = entry.second; - llvm::SmallSetVector arguments; + swift::SmallSetVector arguments; for (const auto &solution : solutions) { auto type = solution.typeBindings.lookup(typeVar); // Type variables gathered from a solution's type binding context may not @@ -5110,7 +5111,7 @@ static bool diagnoseContextualFunctionCallGenericAmbiguity( // So let's try to collect the set of fixed types for the generic parameter // from all the closure contextual fix/solutions and if there are more than // one fixed type diagnose it. - llvm::SmallSetVector genericParamInferredTypes; + swift::SmallSetVector genericParamInferredTypes; for (auto &fix : contextualFixes) genericParamInferredTypes.insert(fix.first->getFixedType(resultTypeVar)); diff --git a/lib/Sema/ImportResolution.cpp b/lib/Sema/ImportResolution.cpp index a2ea08a5ae0..3901120c470 100644 --- a/lib/Sema/ImportResolution.cpp +++ b/lib/Sema/ImportResolution.cpp @@ -34,7 +34,7 @@ #include "llvm/ADT/TinyPtrVector.h" #include "llvm/ADT/Twine.h" #include "llvm/Support/Debug.h" -#include "llvm/Support/Host.h" +#include "llvm/TargetParser/Host.h" #include "llvm/Support/Path.h" #include "llvm/Support/SaveAndRestore.h" #include @@ -167,7 +167,7 @@ class ImportResolver final : public DeclVisitor { /// We use a \c SmallSetVector here because this doubles as the worklist for /// cross-importing, so we want to keep it in order; this is feasible /// because this set is usually fairly small. - SmallSetVector, 64> crossImportableModules; + llvm::SmallSetVector, 32> crossImportableModules; /// The subset of \c crossImportableModules which may declare cross-imports. /// diff --git a/lib/Sema/TypeCheckDeclObjC.cpp b/lib/Sema/TypeCheckDeclObjC.cpp index a944cae3f57..c0fa27f66d2 100644 --- a/lib/Sema/TypeCheckDeclObjC.cpp +++ b/lib/Sema/TypeCheckDeclObjC.cpp @@ -2888,7 +2888,7 @@ class ObjCImplementationChecker { return diag; } - SmallSetVector unmatchedRequirements; + llvm::SmallSetVector unmatchedRequirements; /// Candidates with their explicit ObjC names, if any. llvm::SmallDenseMap unmatchedCandidates; @@ -3103,8 +3103,8 @@ private: // Requirements and candidates that have been matched (even ambiguously) and // should be removed from our unmatched lists. - SmallSetVector requirementsToRemove; - SmallSetVector candidatesToRemove; + llvm::SmallSetVector requirementsToRemove; + llvm::SmallSetVector candidatesToRemove; // First, loop through unsatisfied candidates and try the requirements. for (const auto &pair : unmatchedCandidates) { diff --git a/lib/Sema/TypeCheckStmt.cpp b/lib/Sema/TypeCheckStmt.cpp index 3d76eb01a5a..a759e765366 100644 --- a/lib/Sema/TypeCheckStmt.cpp +++ b/lib/Sema/TypeCheckStmt.cpp @@ -52,6 +52,7 @@ #include "llvm/Support/Debug.h" #include "llvm/Support/Format.h" #include "llvm/Support/Timer.h" +#include #include using namespace swift; diff --git a/lib/Serialization/ModuleFileSharedCore.h b/lib/Serialization/ModuleFileSharedCore.h index 0ad6d40bdb9..ec346b4598a 100644 --- a/lib/Serialization/ModuleFileSharedCore.h +++ b/lib/Serialization/ModuleFileSharedCore.h @@ -17,6 +17,7 @@ #include "swift/AST/LinkLibrary.h" #include "swift/AST/Module.h" #include "swift/Serialization/Validation.h" +#include "llvm/ADT/bit.h" #include "llvm/Bitstream/BitstreamReader.h" namespace llvm { @@ -119,7 +120,7 @@ public: const unsigned IsScoped : 1; static unsigned rawControlFromKind(ImportFilterKind importKind) { - return llvm::countTrailingZeros(static_cast(importKind)); + return llvm::countr_zero(static_cast(importKind)); } ImportFilterKind getImportControl() const { return static_cast(1 << RawImportControl); @@ -132,7 +133,7 @@ public: RawImportControl(rawControlFromKind(importControl)), IsHeader(isHeader), IsScoped(isScoped) { - assert(llvm::countPopulation(static_cast(importControl)) == 1 && + assert(llvm::popcount(static_cast(importControl)) == 1 && "must be a particular filter option, not a bitset"); assert(getImportControl() == importControl && "not enough bits"); } diff --git a/lib/Serialization/Serialization.cpp b/lib/Serialization/Serialization.cpp index 8ff99e5f884..48a912958ba 100644 --- a/lib/Serialization/Serialization.cpp +++ b/lib/Serialization/Serialization.cpp @@ -42,6 +42,7 @@ #include "swift/Basic/Defer.h" #include "swift/Basic/Dwarf.h" #include "swift/Basic/FileSystem.h" +#include "swift/Basic/LLVMExtras.h" #include "swift/Basic/PathRemapper.h" #include "swift/Basic/STLExtras.h" #include "swift/Basic/Version.h" @@ -2628,7 +2629,7 @@ static bool contextDependsOn(const NominalTypeDecl *decl, return false; } -static void collectDependenciesFromType(llvm::SmallSetVector &seen, +static void collectDependenciesFromType(swift::SmallSetVector &seen, Type ty, const DeclContext *excluding) { if (!ty) @@ -2644,7 +2645,7 @@ static void collectDependenciesFromType(llvm::SmallSetVector &seen, } static void -collectDependenciesFromRequirement(llvm::SmallSetVector &seen, +collectDependenciesFromRequirement(swift::SmallSetVector &seen, const Requirement &req, const DeclContext *excluding) { collectDependenciesFromType(seen, req.getFirstType(), excluding); @@ -2653,7 +2654,7 @@ collectDependenciesFromRequirement(llvm::SmallSetVector &seen, } static SmallVector collectDependenciesFromType(Type ty) { - llvm::SmallSetVector result; + swift::SmallSetVector result; collectDependenciesFromType(result, ty, /*excluding*/nullptr); return result.takeVector(); } @@ -3455,10 +3456,15 @@ private: void writeForeignAsyncConvention(const ForeignAsyncConvention &fac) { using namespace decls_block; TypeID completionHandlerTypeID = S.addTypeRef(fac.completionHandlerType()); - unsigned rawErrorParameterIndex = fac.completionHandlerErrorParamIndex() - .transform([](unsigned index) { return index + 1; }).value_or(0); - unsigned rawErrorFlagParameterIndex = fac.completionHandlerFlagParamIndex() - .transform([](unsigned index) { return index + 1; }).value_or(0); + + unsigned rawErrorParameterIndex = + swift::transform(fac.completionHandlerErrorParamIndex(), + [](unsigned index) { return index + 1; }) + .value_or(0); + unsigned rawErrorFlagParameterIndex = + swift::transform(fac.completionHandlerFlagParamIndex(), + [](unsigned index) { return index + 1; }) + .value_or(0); auto abbrCode = S.DeclTypeAbbrCodes[ForeignAsyncConventionLayout::Code]; ForeignAsyncConventionLayout::emitRecord(S.Out, S.ScratchRecord, abbrCode, completionHandlerTypeID, @@ -3832,7 +3838,7 @@ public: size_t numInherited = addInherited( extension->getInherited(), data); - llvm::SmallSetVector dependencies; + swift::SmallSetVector dependencies; collectDependenciesFromType( dependencies, extendedType, /*excluding*/nullptr); for (Requirement req : extension->getGenericRequirements()) { @@ -3993,7 +3999,7 @@ public: auto underlying = typeAlias->getUnderlyingType(); - llvm::SmallSetVector dependencies; + swift::SmallSetVector dependencies; collectDependenciesFromType(dependencies, underlying->getCanonicalType(), /*excluding*/nullptr); for (Requirement req : typeAlias->getGenericRequirements()) { @@ -4066,7 +4072,7 @@ public: addConformances(theStruct, ConformanceLookupKind::All, data); size_t numInherited = addInherited(theStruct->getInherited(), data); - llvm::SmallSetVector dependencyTypes; + swift::SmallSetVector dependencyTypes; for (Requirement req : theStruct->getGenericRequirements()) { collectDependenciesFromRequirement(dependencyTypes, req, /*excluding*/nullptr); @@ -4106,7 +4112,7 @@ public: addConformances(theEnum, ConformanceLookupKind::All, data); size_t numInherited = addInherited(theEnum->getInherited(), data); - llvm::SmallSetVector dependencyTypes; + swift::SmallSetVector dependencyTypes; for (const EnumElementDecl *nextElt : theEnum->getAllElements()) { if (!nextElt->hasAssociatedValues()) continue; @@ -4159,7 +4165,7 @@ public: addConformances(theClass, ConformanceLookupKind::NonInherited, data); size_t numInherited = addInherited(theClass->getInherited(), data); - llvm::SmallSetVector dependencyTypes; + swift::SmallSetVector dependencyTypes; if (theClass->hasSuperclass()) { // FIXME: Nested types can still be a problem here: it's possible that (for // whatever reason) they won't be able to be deserialized, in which case @@ -4209,7 +4215,7 @@ public: auto contextID = S.addDeclContextRef(proto->getDeclContext()); SmallVector inheritedAndDependencyTypes; - llvm::SmallSetVector dependencyTypes; + swift::SmallSetVector dependencyTypes; unsigned numInherited = addInherited( proto->getInherited(), inheritedAndDependencyTypes); diff --git a/lib/Serialization/Serialization.h b/lib/Serialization/Serialization.h index fa7bd928478..bf10890b0d3 100644 --- a/lib/Serialization/Serialization.h +++ b/lib/Serialization/Serialization.h @@ -18,6 +18,7 @@ #define SWIFT_SERIALIZATION_SERIALIZATION_H #include "ModuleFormat.h" +#include "swift/Basic/LLVMExtras.h" #include "swift/Serialization/SerializationOptions.h" #include "swift/Subsystems.h" #include "swift/AST/Identifier.h" @@ -289,7 +290,7 @@ public: // constructed, and then converted to a `DerivativeFunctionConfigTableData`. using UniquedDerivativeFunctionConfigTable = llvm::MapVector< Identifier, - llvm::SmallSetVector, 4>>; + swift::SmallSetVector, 4>>; // In-memory representation of what will eventually be an on-disk // hash table of the fingerprint associated with a serialized diff --git a/lib/Serialization/SerializedModuleLoader.cpp b/lib/Serialization/SerializedModuleLoader.cpp index 6cd330a1151..4ca51a01583 100644 --- a/lib/Serialization/SerializedModuleLoader.cpp +++ b/lib/Serialization/SerializedModuleLoader.cpp @@ -32,7 +32,7 @@ #include "llvm/ADT/StringSet.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FileSystem.h" -#include "llvm/Support/Host.h" +#include "llvm/TargetParser/Host.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/CommandLine.h" diff --git a/lib/SymbolGraphGen/CMakeLists.txt b/lib/SymbolGraphGen/CMakeLists.txt index 63392f19540..ca0bff98571 100644 --- a/lib/SymbolGraphGen/CMakeLists.txt +++ b/lib/SymbolGraphGen/CMakeLists.txt @@ -6,7 +6,11 @@ add_swift_host_library(swiftSymbolGraphGen STATIC Symbol.cpp SymbolGraph.cpp SymbolGraphGen.cpp - SymbolGraphASTWalker.cpp) + SymbolGraphASTWalker.cpp + + LLVM_LINK_COMPONENTS + TargetParser + ) target_link_libraries(swiftSymbolGraphGen PRIVATE swiftAST diff --git a/lib/SymbolGraphGen/JSON.h b/lib/SymbolGraphGen/JSON.h index 268d8c59f97..e5ed3d78bb9 100644 --- a/lib/SymbolGraphGen/JSON.h +++ b/lib/SymbolGraphGen/JSON.h @@ -15,7 +15,7 @@ #ifndef SWIFT_SYMBOLGRAPHGEN_JSON_H #define SWIFT_SYMBOLGRAPHGEN_JSON_H -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/Support/JSON.h" #include "llvm/Support/VersionTuple.h" #include "swift/AST/GenericSignature.h" diff --git a/stdlib/cmake/modules/AddSwiftStdlib.cmake b/stdlib/cmake/modules/AddSwiftStdlib.cmake index 61447d50f08..8d04aebb89a 100644 --- a/stdlib/cmake/modules/AddSwiftStdlib.cmake +++ b/stdlib/cmake/modules/AddSwiftStdlib.cmake @@ -788,6 +788,7 @@ function(add_swift_target_library_single target name) LINK_FLAGS LINK_LIBRARIES PRIVATE_LINK_LIBRARIES + PREFIX_INCLUDE_DIRS SWIFT_COMPILE_FLAGS MODULE_TARGETS) @@ -1075,6 +1076,8 @@ function(add_swift_target_library_single target name) # to ensure that the runtime is built with our local copy of LLVMSupport target_include_directories(${target} BEFORE PRIVATE ${SWIFT_SOURCE_DIR}/stdlib/include) + target_include_directories(${target} BEFORE PRIVATE + ${SWIFTLIB_SINGLE_PREFIX_INCLUDE_DIRS}) if(("${SWIFT_SDK_${SWIFTLIB_SINGLE_SDK}_OBJECT_FORMAT}" STREQUAL "ELF" OR "${SWIFT_SDK_${SWIFTLIB_SINGLE_SDK}_OBJECT_FORMAT}" STREQUAL "COFF")) if("${libkind}" STREQUAL "SHARED" AND NOT SWIFTLIB_SINGLE_NOSWIFTRT) @@ -1789,6 +1792,7 @@ function(add_swift_target_library name) INCORPORATE_OBJECT_LIBRARIES_SHARED_ONLY LINK_FLAGS LINK_LIBRARIES + PREFIX_INCLUDE_DIRS PRIVATE_LINK_LIBRARIES SWIFT_COMPILE_FLAGS SWIFT_COMPILE_FLAGS_IOS @@ -2283,6 +2287,7 @@ function(add_swift_target_library name) ${back_deployment_library_option} ENABLE_LTO "${SWIFT_STDLIB_ENABLE_LTO}" GYB_SOURCES ${SWIFTLIB_GYB_SOURCES} + PREFIX_INCLUDE_DIRS ${SWIFTLIB_PREFIX_INCLUDE_DIRS} ) if(NOT SWIFT_BUILT_STANDALONE AND NOT "${CMAKE_C_COMPILER_ID}" MATCHES "Clang") add_dependencies(${VARIANT_NAME} clang) diff --git a/stdlib/include/llvm/ADT/ArrayRef.h b/stdlib/include/llvm/ADT/ArrayRef.h index c4388414c78..9344915256a 100644 --- a/stdlib/include/llvm/ADT/ArrayRef.h +++ b/stdlib/include/llvm/ADT/ArrayRef.h @@ -469,6 +469,28 @@ namespace llvm { ~OwningArrayRef() { delete[] this->data(); } }; + /// C++17 ArrayRef deduction guides + template + ArrayRef(const T &) -> ArrayRef; + template + ArrayRef(const T *, size_t) -> ArrayRef; + template + ArrayRef(const T *, const T *) -> ArrayRef; + template + ArrayRef(const SmallVectorImpl &Vec) -> ArrayRef; + template + ArrayRef(const SmallVector &Vec) -> ArrayRef; + template + ArrayRef(const std::vector &) -> ArrayRef; + template + ArrayRef(const std::array &Vec) -> ArrayRef; + template + ArrayRef(const ArrayRef &Vec) -> ArrayRef; + template + ArrayRef(ArrayRef &Vec) -> ArrayRef; + template + ArrayRef(const T (&Arr)[N]) -> ArrayRef; + /// @name ArrayRef Convenience constructors /// @{ diff --git a/stdlib/public/RemoteInspection/TypeRefBuilder.cpp b/stdlib/public/RemoteInspection/TypeRefBuilder.cpp index fe36991d86f..2eb0205bbf1 100644 --- a/stdlib/public/RemoteInspection/TypeRefBuilder.cpp +++ b/stdlib/public/RemoteInspection/TypeRefBuilder.cpp @@ -348,8 +348,8 @@ RemoteRef TypeRefBuilder::getFieldTypeInfo(const TypeRef *TR) { } } - // On failure, fill out the cache, ReflectionInfo by ReflectionInfo, - // until we find the field descriptor we're looking for. + // If the heuristic didn't work, iterate over every reflection info + // that the external cache hasn't processed. for (size_t i = 0; i < ReflectionInfos.size(); ++i) { if (ExternalTypeRefCache && ExternalTypeRefCache->isReflectionInfoCached(i)) continue; @@ -357,6 +357,14 @@ RemoteRef TypeRefBuilder::getFieldTypeInfo(const TypeRef *TR) { return *FD; } + // If we still haven't found the field descriptor go over every reflection + // info, even the ones the external cache supposedly processed. + // TODO: if we find the field descriptor here there is a bug somewhere (most + // likely on the external cache). Log this somehow. + for (size_t i = 0; i < ReflectionInfos.size(); ++i) + if (auto FD = findFieldDescriptorAtIndex(i, *MangledName)) + return *FD; + return nullptr; } diff --git a/stdlib/public/SwiftRemoteMirror/CMakeLists.txt b/stdlib/public/SwiftRemoteMirror/CMakeLists.txt index 41d77375539..36e02f998da 100644 --- a/stdlib/public/SwiftRemoteMirror/CMakeLists.txt +++ b/stdlib/public/SwiftRemoteMirror/CMakeLists.txt @@ -6,9 +6,12 @@ add_swift_target_library(swiftRemoteMirror LINK_LIBRARIES swiftRemoteInspection C_COMPILE_FLAGS - ${SWIFT_RUNTIME_CXX_FLAGS} -DswiftRemoteMirror_EXPORTS -I${LLVM_MAIN_INCLUDE_DIR} + ${SWIFT_RUNTIME_CXX_FLAGS} + -DswiftRemoteMirror_EXPORTS LINK_FLAGS ${SWIFT_RUNTIME_LINK_FLAGS} + PREFIX_INCLUDE_DIRS + ${SWIFT_SOURCE_DIR}/include/swift/RemoteInspection/RuntimeHeaders INCORPORATE_OBJECT_LIBRARIES swiftLLVMSupport SWIFT_COMPILE_FLAGS ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} DARWIN_INSTALL_NAME_DIR "${SWIFTLIB_DARWIN_INSTALL_NAME_DIR}" diff --git a/stdlib/public/SwiftShims/swift/shims/CMakeLists.txt b/stdlib/public/SwiftShims/swift/shims/CMakeLists.txt index 27266602724..3b2ee99c04d 100644 --- a/stdlib/public/SwiftShims/swift/shims/CMakeLists.txt +++ b/stdlib/public/SwiftShims/swift/shims/CMakeLists.txt @@ -96,15 +96,20 @@ add_custom_target("copy_shim_headers" ALL DEPENDS "${outputs}" COMMENT "Copying SwiftShims module to ${output_dir}") -if ("${LLVM_PACKAGE_VERSION}" STREQUAL "") - message(FATAL_ERROR - "LLVM_PACKAGE_VERSION must be set before including subdirectories") +if (NOT CLANG_VERSION_MAJOR) + if (NOT LLVM_VERSION_MAJOR) + message(FATAL_ERROR + "CLANG_VERSION_MAJOR or LLVM_VERSION_MAJOR must be set \ + in order to infer the path to clang headers") + else() + message(WARNING + "CLANG_VERSION_MAJOR is not defined, falling back to \ + LLVM_VERSION_MAJOR to infer the path to clang headers") + set(CLANG_VERSION_MAJOR "${LLVM_VERSION_MAJOR}") + endif() endif() -# Symlink in the Clang headers. -# First extract the "version" used for Clang's resource directory. -string(REGEX MATCH "[0-9]+\\.[0-9]+(\\.[0-9]+)?" CLANG_VERSION - "${LLVM_PACKAGE_VERSION}") +# Symlink in the Clang headers from either the provided clang... if(NOT SWIFT_INCLUDE_TOOLS AND (SWIFT_BUILD_RUNTIME_WITH_HOST_COMPILER OR SWIFT_PREBUILT_CLANG)) if(SWIFT_COMPILER_IS_MSVC_LIKE) @@ -120,7 +125,8 @@ if(NOT SWIFT_INCLUDE_TOOLS AND endif() message(STATUS "Using clang Resource Directory: ${clang_headers_location}") else() - set(clang_headers_location "${LLVM_LIBRARY_OUTPUT_INTDIR}/clang/${CLANG_VERSION}") + # ... or the one we just built + set(clang_headers_location "${LLVM_LIBRARY_OUTPUT_INTDIR}/clang/${CLANG_VERSION_MAJOR}") endif() if("${CMAKE_SYSTEM_NAME}" STREQUAL "Windows") @@ -257,7 +263,7 @@ if(SWIFT_BUILD_RUNTIME_WITH_HOST_COMPILER OR SWIFT_PREBUILT_CLANG) # toolchain was built with SWIFT_INCLUDE_TOOLS. set(SWIFT_CLANG_RESOURCE_DIR_SYMLINK_INSTALL_TARGET_default ${clang_headers_location}) else() - set(SWIFT_CLANG_RESOURCE_DIR_SYMLINK_INSTALL_TARGET_default "../clang/${CLANG_VERSION}") + set(SWIFT_CLANG_RESOURCE_DIR_SYMLINK_INSTALL_TARGET_default "../clang/${CLANG_VERSION_MAJOR}") endif() set(SWIFT_CLANG_RESOURCE_DIR_SYMLINK_INSTALL_TARGET diff --git a/test/CAS/cas_fs.swift b/test/CAS/cas_fs.swift index 8ed83237d0e..a4b0e2cab6e 100644 --- a/test/CAS/cas_fs.swift +++ b/test/CAS/cas_fs.swift @@ -2,11 +2,11 @@ // RUN: mkdir -p %t/empty // RUN: mkdir -p %t/cas -// RUN: llvm-cas --cas %t/cas --ingest --data %t/empty > %t/empty.casid +// RUN: llvm-cas --cas %t/cas --ingest %t/empty > %t/empty.casid // RUN: not %target-swift-frontend -typecheck -cache-compile-job -cas-fs @%t/empty.casid -cas-path %t/cas %s 2>&1 | %FileCheck %s --check-prefix NO-INPUTS // NO-INPUTS: error: error opening input file -// RUN: llvm-cas --cas %t/cas --ingest --data %s > %t/source.casid +// RUN: llvm-cas --cas %t/cas --ingest %s > %t/source.casid // RUN: not %target-swift-frontend -typecheck -cache-compile-job -cas-fs @%t/source.casid -cas-path %t/cas %s 2>&1 | %FileCheck %s --check-prefix NO-RESOURCES // NO-RESOURCES: error: unable to load standard library diff --git a/test/CAS/mccas.swift b/test/CAS/mccas.swift new file mode 100644 index 00000000000..0b3ac17f91e --- /dev/null +++ b/test/CAS/mccas.swift @@ -0,0 +1,26 @@ +// REQUIRES: OS=macosx +// RUN: %empty-directory(%t) +// RUN: %target-swift-frontend -c %s -g -cas-backend -cas-backend-mode=verify -cas-path %t/cas -o %t/test-verify.o +// RUN: %llvm-dwarfdump %t/test-verify.o | %FileCheck %s --check-prefix=VERIFY-FILE +// VERIFY-FILE: .debug_info + +// RUN: %target-swift-frontend -c %s -g -cas-backend -cas-backend-mode=native -cas-path %t/cas -o %t/test-native.o +// RUN: %llvm-dwarfdump %t/test-native.o | %FileCheck %s --check-prefix=NATIVE-FILE +// NATIVE-FILE: .debug_info + +// RUN: %target-swift-frontend -c %s -g -cas-backend -cas-backend-mode=casid -cas-path %t/cas -o %t/test-casid.id +// RUN: cat %t/test-casid.id | %FileCheck %s --check-prefix=CASID-FILE +// CASID-FILE: llvmcas://{{.*}} + +// RUN: %target-swift-frontend -c %s -g -cas-backend -cas-emit-casid-file -cas-backend-mode=verify -cas-path %t/cas -o %t/test-verify-emit.o +// RUN: cat %t/test-verify-emit.o.casid | %FileCheck %s --check-prefix=VERIFY-EMIT +// VERIFY-EMIT: llvmcas://{{.*}} + +// RUN: %target-swift-frontend -c %s -g -cas-backend -cas-emit-casid-file -cas-backend-mode=native -cas-path %t/cas -o %t/test-native-emit.o +// RUN: cat %t/test-native-emit.o.casid | %FileCheck %s --check-prefix=NATIVE-EMIT +// NATIVE-EMIT: llvmcas://{{.*}} + +// RUN: %target-swift-frontend -c %s -g -cas-backend -cas-emit-casid-file -cas-backend-mode=casid -cas-path %t/cas -o %t/test.id +// RUN: not cat %t/test.id.casid + +func testFunc() {} \ No newline at end of file diff --git a/test/ClangImporter/SceneKit_test.swift b/test/ClangImporter/SceneKit_test.swift index 05dc38b52e6..f05ea319ba2 100644 --- a/test/ClangImporter/SceneKit_test.swift +++ b/test/ClangImporter/SceneKit_test.swift @@ -3,6 +3,10 @@ // REQUIRES: objc_interop // REQUIRES: OS=macosx +// SceneKit has two protocols sections, which clang treats as an error now +// rdar://113874614 +// XFAIL: * + import SceneKit import Foundation diff --git a/test/ClangImporter/objc_ir.swift b/test/ClangImporter/objc_ir.swift index 1d2cb44b4f0..ba04cf89641 100644 --- a/test/ClangImporter/objc_ir.swift +++ b/test/ClangImporter/objc_ir.swift @@ -349,7 +349,7 @@ func testBlocksWithGenerics(hba: HasBlockArray) -> Any { // CHECK: load ptr, ptr @"\01L_selector(initWithInt:)" // CHECK: call ptr @objc_msgSend -// CHECK: attributes [[NOUNWIND]] = { nounwind readonly } +// CHECK: attributes [[NOUNWIND]] = { nounwind memory(read) } // CHECK: ![[SWIFT_NAME_ALIAS_VAR]] = !DILocalVariable(name: "obj", arg: 1, scope: !{{[0-9]+}}, file: !{{[0-9]+}}, line: {{[0-9]+}}, type: ![[SWIFT_NAME_ALIAS_TYPE:[0-9]+]]) // CHECK: ![[LET_SWIFT_NAME_ALIAS_TYPE:[0-9]+]] = !DIDerivedType(tag: DW_TAG_const_type, baseType: ![[SWIFT_NAME_ALIAS_TYPE:[0-9]+]]) diff --git a/test/ClangImporter/private_frameworks.swift b/test/ClangImporter/private_frameworks.swift index 5db1f30035d..ea364041289 100644 --- a/test/ClangImporter/private_frameworks.swift +++ b/test/ClangImporter/private_frameworks.swift @@ -1,3 +1,5 @@ +// REQUIRES: rdar113413583 + // RUN: %empty-directory(%t) // FIXME: BEGIN -enable-source-import hackaround diff --git a/test/DebugInfo/BridgingHeaderPCH.swift b/test/DebugInfo/BridgingHeaderPCH.swift index 5fecc1eefe5..09570b2d302 100644 --- a/test/DebugInfo/BridgingHeaderPCH.swift +++ b/test/DebugInfo/BridgingHeaderPCH.swift @@ -1,3 +1,5 @@ +// REQUIRES: rdar114728459 + // RUN: %target-swift-frontend \ // RUN: -emit-pch %S/Inputs/InlineBridgingHeader.h -o %t.pch // RUN: %target-swift-frontend \ diff --git a/test/DebugInfo/ClangModuleBreadcrumbs.swift b/test/DebugInfo/ClangModuleBreadcrumbs.swift index 724f506c9f0..598c7a9ccae 100644 --- a/test/DebugInfo/ClangModuleBreadcrumbs.swift +++ b/test/DebugInfo/ClangModuleBreadcrumbs.swift @@ -1,3 +1,5 @@ +// REQUIRES: rdar114728459 + // RUN: %target-swift-frontend -emit-ir %s -g -I %S/Inputs \ // RUN: -Xcc -DFOO="foo" -Xcc -UBAR -o - | %FileCheck %s // diff --git a/test/DebugInfo/InlineBridgingHeader.swift b/test/DebugInfo/InlineBridgingHeader.swift index 64d89da2fc0..e21296dbf7e 100644 --- a/test/DebugInfo/InlineBridgingHeader.swift +++ b/test/DebugInfo/InlineBridgingHeader.swift @@ -9,6 +9,6 @@ // CHECK-SAME: language: {{DW_LANG_ObjC|DW_LANG_C}} // CHECK: ![[CONCURRENCY_SHIMS_CU]] = distinct !DICompileUnit( // CHECK-SAME: language: {{DW_LANG_ObjC|DW_LANG_C}} -// CHECK: DISubprogram(name: "Foo"{{.*}} unit: ![[CLANG_CU]], +// CHECK: DISubprogram(name: "Foo"{{.*}} unit: ![[CLANG_CU]] Foo() diff --git a/test/DebugInfo/Inputs/NonInlined.swift b/test/DebugInfo/Inputs/NonInlined.swift new file mode 100644 index 00000000000..1a423b307ce --- /dev/null +++ b/test/DebugInfo/Inputs/NonInlined.swift @@ -0,0 +1,5 @@ +public var x = Int64() + +public func use(_ x: T) -> T { return x } + +public func noinline(_ x: Int64) -> Int64 { return use(x) } diff --git a/test/DebugInfo/async-let-await.swift b/test/DebugInfo/async-let-await.swift index 24bd90ef224..c9d2a37ea71 100644 --- a/test/DebugInfo/async-let-await.swift +++ b/test/DebugInfo/async-let-await.swift @@ -12,7 +12,7 @@ public func getVegetables() async -> [String] { public func chopVegetables() async throws -> [String] { let veggies = await getVegetables() // CHECK-NOT: {{^define }} - // CHECK: call void @llvm.dbg.declare(metadata ptr %0, metadata ![[V:[0-9]+]], metadata !DIExpression(DW_OP_deref, DW_OP_plus_uconst, {{[0-9]+}}, DW_OP_plus_uconst, {{[0-9]+}}) + // CHECK: call void @llvm.dbg.declare(metadata ptr %0, metadata ![[V:[0-9]+]], metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_deref, DW_OP_plus_uconst, {{[0-9]+}}, DW_OP_plus_uconst, {{[0-9]+}}) // CHECK: ![[V]] = !DILocalVariable(name: "veggies" return veggies.map { "chopped \($0)" } } diff --git a/test/DebugInfo/async-local-var.swift b/test/DebugInfo/async-local-var.swift index 27c69b75db8..300c1336e03 100644 --- a/test/DebugInfo/async-local-var.swift +++ b/test/DebugInfo/async-local-var.swift @@ -16,7 +16,7 @@ public func makeDinner() async throws -> String { // CHECK-LABEL: define {{.*}} void @"$s1a10makeDinnerSSyYaKFTQ0_" // CHECK-NEXT: entryresume.0: // CHECK-NOT: {{ ret }} -// CHECK: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LOCAL:[0-9]+]], {{.*}}!DIExpression(DW_OP_deref, DW_OP_plus_uconst, {{[0-9]+}}) +// CHECK: call void @llvm.dbg.declare(metadata {{.*}}%0, metadata ![[LOCAL:[0-9]+]], {{.*}}!DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_deref, DW_OP_plus_uconst, {{[0-9]+}}) // CHECK: ![[LOCAL]] = !DILocalVariable(name: "local" return local } diff --git a/test/DebugInfo/implicitreturn.swift b/test/DebugInfo/implicitreturn.swift index 3501f902d46..119d716feee 100644 --- a/test/DebugInfo/implicitreturn.swift +++ b/test/DebugInfo/implicitreturn.swift @@ -7,9 +7,9 @@ func app() { var x : Bool = true x = !x x = !x -// CHECK: .loc [[FILEID]] [[@LINE+3]] 1 -// CHECK-NOT:.loc +// CHECK: .loc [[FILEID]] [[@LINE+2]] 1 // CHECK: ret } app() + diff --git a/test/DebugInfo/inlinescopes.swift b/test/DebugInfo/inlinescopes.swift index c6bfff7030a..e901a0ca5e1 100644 --- a/test/DebugInfo/inlinescopes.swift +++ b/test/DebugInfo/inlinescopes.swift @@ -1,27 +1,20 @@ // RUN: %empty-directory(%t) -// RUN: echo "public var x = Int64()" \ -// RUN: | %target-swift-frontend -module-name FooBar -emit-module -o %t - -// RUN: %target-swift-frontend %s -O -I %t -emit-ir -g -o %t.ll +// RUN: %target-swift-frontend -emit-ir -parse-as-library %S/Inputs/NonInlined.swift -emit-module -o %t/NonInlined.ll +// RUN: %target-swift-frontend -emit-ir -parse-as-library -g -module-name main %s -O -I %t -o %t.ll // RUN: %FileCheck %s < %t.ll // RUN: %FileCheck %s -check-prefix=TRANSPARENT-CHECK < %t.ll -// CHECK: define{{( dllexport)?}}{{( protected)?( signext)?}} i32 @main{{.*}} -// CHECK: call swiftcc i64 @"$s4main8noinlineys5Int64VADF"(i64 %{{.*}}) -// CHECK-SAME: !dbg ![[CALL:.*]] +// CHECK: define{{.*}}$s4main5entrys5Int64VyF +// CHECK-NOT: ret i64 +// CHECK: call {{.*}}8noinline{{.*}} !dbg ![[CALL:.*]] +// CHECK: ret i64 // CHECK-DAG: ![[TOPLEVEL:.*]] = !DIFile(filename: "{{.*}}inlinescopes.swift" -import FooBar - -@inline(never) -func use(_ x: Int64) -> Int64 { return x } - -@inline(never) -func noinline(_ x: Int64) -> Int64 { return use(x) } +import NonInlined @_transparent func transparent(_ x: Int64) -> Int64 { return noinline(x) } - @inline(__always) func inlined(_ x: Int64) -> Int64 { let result = transparent(x) @@ -33,5 +26,4 @@ func inlined(_ x: Int64) -> Int64 { // TRANSPARENT-CHECK-NOT: !DISubprogram(name: "transparent" return result } -// CHECK-DAG: !DIGlobalVariable(name: "y",{{.*}} file: ![[TOPLEVEL]],{{.*}} line: [[@LINE+1]] -public let y = inlined(x) +public func entry() -> Int64 { return inlined(x) } diff --git a/test/DebugInfo/move_function_dbginfo.swift b/test/DebugInfo/move_function_dbginfo.swift index b17a1963be4..437ea99e76d 100644 --- a/test/DebugInfo/move_function_dbginfo.swift +++ b/test/DebugInfo/move_function_dbginfo.swift @@ -1,3 +1,4 @@ +// REQUIRES: CPU=arm64 // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -parse-as-library -g -emit-ir -o - %s | %FileCheck %s // RUN: %target-swift-frontend -parse-as-library -g -c %s -o %t/out.o @@ -40,12 +41,10 @@ public var falseValue: Bool { false } // In contrast, we should have a dbg.declare for m since we aren't // CHECK: call void @llvm.dbg.declare(metadata ptr %m.debug, metadata ![[M_COPYABLE_VALUE_TEST:[0-9]*]], // -// We should have a llvm.dbg.addr for k since we moved it. -// CHECK: call void @llvm.dbg.addr(metadata ptr %k.debug, metadata ![[K_COPYABLE_VALUE_METADATA:[0-9]*]], metadata !DIExpression()), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br +// We should have a llvm.dbg.value for k since we moved it. +// CHECK: call void @llvm.dbg.value(metadata ptr %k.debug, metadata ![[K_COPYABLE_VALUE_METADATA:[0-9]*]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // -// Our undef should be an llvm.dbg.value. Counter-intuitively this works for -// both llvm.dbg.addr /and/ llvm.dbg.value. Importantly though its metadata +// Our undef should be an llvm.dbg.value. Importantly though its metadata // should be for k since that is the variable that we are telling the debugger // is no longer defined. // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[K_COPYABLE_VALUE_METADATA]], metadata !DIExpression()), !dbg ![[ADDR_LOC]] @@ -89,12 +88,10 @@ public func copyableValueTest() { // In contrast, we should have a dbg.declare for m since we aren't // CHECK: call void @llvm.dbg.declare(metadata ptr %m.debug, metadata ![[M_COPYABLE_VALUE_TEST:[0-9]*]], // -// We should have a llvm.dbg.addr for k since we moved it. -// CHECK: call void @llvm.dbg.addr(metadata ptr %k.debug, metadata ![[K_COPYABLE_VALUE_METADATA:[0-9]*]], metadata !DIExpression()), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br +// We should have a llvm.dbg.value for k since we moved it. +// CHECK: call void @llvm.dbg.value(metadata ptr %k.debug, metadata ![[K_COPYABLE_VALUE_METADATA:[0-9]*]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // -// Our undef should be an llvm.dbg.value. Counter-intuitively this works for -// both llvm.dbg.addr /and/ llvm.dbg.value. Importantly though its metadata +// Our undef should be an llvm.dbg.value. Importantly though its metadata // should be for k since that is the variable that we are telling the debugger // is no longer defined. // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[K_COPYABLE_VALUE_METADATA]], metadata !DIExpression()), !dbg ![[ADDR_LOC]] @@ -132,12 +129,10 @@ public func copyableArgTest(_ k: __owned Klass) { // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo15copyableVarTestyyF"() // CHECK: call void @llvm.dbg.declare(metadata ptr %m.debug, -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR:%.*]], metadata ![[K_COPYABLE_VAR_METADATA:[0-9]+]], metadata !DIExpression()), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR:%.*]], metadata ![[K_COPYABLE_VAR_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[K_COPYABLE_VAR_METADATA]], metadata !DIExpression()), !dbg ![[ADDR_LOC]] // TODO: Should this be a deref like the original? -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR]], metadata ![[K_COPYABLE_VAR_METADATA]], metadata !DIExpression()), !dbg ![[ADDR_LOC]] -// CHECK-NEXT: br +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR]], metadata ![[K_COPYABLE_VAR_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] // CHECK: ret void // CHECK-NEXT: } // @@ -177,12 +172,10 @@ public func copyableVarTest() { // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo18copyableVarArgTestyyAA5KlassCzF"( // CHECK: call void @llvm.dbg.declare(metadata ptr %m.debug, -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR:%.*]], metadata ![[K_COPYABLE_VAR_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR:%.*]], metadata ![[K_COPYABLE_VAR_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[K_COPYABLE_VAR_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] // TODO: Should this be a deref like the original? -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR]], metadata ![[K_COPYABLE_VAR_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] -// CHECK-NEXT: br +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR]], metadata ![[K_COPYABLE_VAR_METADATA]], metadata !DIExpression(DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC]] // CHECK: ret void // CHECK-NEXT: } // @@ -219,8 +212,7 @@ public func copyableVarArgTest(_ k: inout Klass) { } // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo20addressOnlyValueTestyyxAA1PRzlF"(ptr noalias %0, ptr %T, ptr %T.P) -// CHECK: @llvm.dbg.addr(metadata ptr %{{.*}}, metadata ![[K_ADDR_LET_METADATA:[0-9]+]], metadata !DIExpression()), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br +// CHECK: @llvm.dbg.value(metadata ptr %{{.*}}, metadata ![[K_ADDR_LET_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // CHECK: @llvm.dbg.value(metadata ptr undef, metadata ![[K_ADDR_LET_METADATA]], metadata !DIExpression()), !dbg ![[ADDR_LOC]] // CHECK: ret void // CHECK-NEXT: } @@ -269,8 +261,7 @@ public func addressOnlyValueTest(_ x: T) { // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo23addressOnlyValueArgTestyyxnAA1PRzlF"( // CHECK: @llvm.dbg.declare(metadata ptr %T1, // CHECK: @llvm.dbg.declare(metadata ptr %m.debug, -// CHECK: @llvm.dbg.addr(metadata ptr %k.debug, metadata ![[K_ADDR_LET_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br +// CHECK: @llvm.dbg.value(metadata ptr %k.debug, metadata ![[K_ADDR_LET_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // CHECK: @llvm.dbg.value(metadata ptr undef, metadata ![[K_ADDR_LET_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] // CHECK: ret void // CHECK-NEXT: } @@ -309,11 +300,10 @@ public func addressOnlyValueArgTest(_ k: __owned T) { } // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo18addressOnlyVarTestyyxAA1PRzlF"(ptr noalias %0, ptr %T, ptr %T.P) -// CHECK: @llvm.dbg.addr(metadata ptr %{{.*}}, metadata ![[K_ADDRONLY_VAR_METADATA:[0-9]+]], metadata !DIExpression()), !dbg ![[ADDR_LOC:[0-9]*]] +// CHECK: @llvm.dbg.value(metadata ptr %{{.*}}, metadata ![[K_ADDRONLY_VAR_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // CHECK-NEXT: br // CHECK: @llvm.dbg.value(metadata ptr undef, metadata ![[K_ADDRONLY_VAR_METADATA]], metadata !DIExpression()), !dbg ![[ADDR_LOC]] -// CHECK: @llvm.dbg.addr(metadata ptr %{{.*}}, metadata ![[K_ADDRONLY_VAR_METADATA]], metadata !DIExpression()), !dbg ![[ADDR_LOC]] -// CHECK-NEXT: br +// CHECK: @llvm.dbg.value(metadata ptr %{{.*}}, metadata ![[K_ADDRONLY_VAR_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] // CHECK: ret void // CHECK-NEXT: } // @@ -356,11 +346,9 @@ public func addressOnlyVarTest(_ x: T) { } // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo21addressOnlyVarArgTestyyxz_xtAA1PRzlF"( -// CHECK: call void @llvm.dbg.addr(metadata ptr %k.debug, metadata ![[K_ADDRONLY_VAR_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br +// CHECK: call void @llvm.dbg.value(metadata ptr %k.debug, metadata ![[K_ADDRONLY_VAR_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // CHECK: @llvm.dbg.value(metadata ptr undef, metadata ![[K_ADDRONLY_VAR_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] -// CHECK: @llvm.dbg.addr(metadata ptr %k.debug, metadata ![[K_ADDRONLY_VAR_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] -// CHECK-NEXT: br +// CHECK: @llvm.dbg.value(metadata ptr %k.debug, metadata ![[K_ADDRONLY_VAR_METADATA]], metadata !DIExpression(DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC]] // CHECK: ret void // CHECK-NEXT: } // @@ -405,10 +393,8 @@ public func addressOnlyVarArgTest(_ k: inout T, _ x: T) { /////////////////////// // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo23copyableValueCCFlowTestyyF"( -// CHECK: call void @llvm.dbg.addr(metadata ptr %k.debug, metadata ![[K_COPYABLE_LET_CCFLOW_METADATA:[0-9]+]], metadata !DIExpression()), !dbg ![[ADDR_LOC:[0-9]+]] -// CHECK-NEXT: br label %[[NEXT_BB:[a-z\.0-9]+]], +// CHECK: call void @llvm.dbg.value(metadata ptr %k.debug, metadata ![[K_COPYABLE_LET_CCFLOW_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] // -// CHECK: [[NEXT_BB]]: // CHECK: br i1 {{%[0-9]+}}, label %[[LHS:[0-9]+]], label %[[RHS:[0-9]+]], // // CHECK: [[LHS]]: @@ -423,10 +409,8 @@ public func copyableValueCCFlowTest() { } // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo26copyableValueArgCCFlowTestyyAA5KlassCnF"( -// CHECK: call void @llvm.dbg.addr(metadata ptr %k.debug, metadata ![[K_COPYABLE_LET_CCFLOW_METADATA:[0-9]+]], metadata !DIExpression()), !dbg ![[ADDR_LOC:[0-9]+]] -// CHECK-NEXT: br label %[[NEXT_BB:[a-z\.0-9]+]], +// CHECK: call void @llvm.dbg.value(metadata ptr %k.debug, metadata ![[K_COPYABLE_LET_CCFLOW_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] // -// CHECK: [[NEXT_BB]]: // CHECK: br i1 {{%[0-9]+}}, label %[[LHS:[0-9]+]], label %[[RHS:[0-9]+]], // // CHECK: [[LHS]]: @@ -441,10 +425,8 @@ public func copyableValueArgCCFlowTest(_ k: __owned Klass) { // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo037copyableVarTestCCFlowReinitOutOfBlockF0yyF"( // CHECK: call void @llvm.dbg.declare(metadata ptr %m.debug, -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR:%.*]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA:[0-9]+]], metadata !DIExpression()), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br label %[[BB_NEXT:[a-z0-9\.]+]], +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR:%.*]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // -// CHECK: [[BB_NEXT]]: // CHECK: br i1 %{{[0-9]+}}, label %[[LHS:[0-9]+]], label %[[RHS:[0-9]+]], // // CHECK: [[LHS]]: @@ -456,8 +438,7 @@ public func copyableValueArgCCFlowTest(_ k: __owned Klass) { // // CHECK: [[CONT_BB]]: // TODO: Should this be a deref like the original? -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA]], metadata !DIExpression()), !dbg ![[ADDR_LOC]] -// CHECK-NEXT: br +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] // CHECK: ret void // CHECK-NEXT: } public func copyableVarTestCCFlowReinitOutOfBlockTest() { @@ -473,10 +454,8 @@ public func copyableVarTestCCFlowReinitOutOfBlockTest() { // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo040copyableVarArgTestCCFlowReinitOutOfBlockG0yyAA5KlassCzF"( // CHECK: call void @llvm.dbg.declare(metadata ptr %m.debug, -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR:%.*]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br label %[[BB_NEXT:[a-z0-9\.]+]], +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR:%.*]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // -// CHECK: [[BB_NEXT]]: // CHECK: br i1 %{{[0-9]+}}, label %[[LHS:[0-9]+]], label %[[RHS:[0-9]+]], // // CHECK: [[LHS]]: @@ -487,8 +466,7 @@ public func copyableVarTestCCFlowReinitOutOfBlockTest() { // CHECK: br label %[[CONT_BB]], // // CHECK: [[CONT_BB]]: -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] -// CHECK-NEXT: br +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA]], metadata !DIExpression(DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC]] // CHECK: ret void // CHECK-NEXT: } public func copyableVarArgTestCCFlowReinitOutOfBlockTest(_ k: inout Klass) { @@ -504,19 +482,15 @@ public func copyableVarArgTestCCFlowReinitOutOfBlockTest(_ k: inout Klass) { // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo034copyableVarTestCCFlowReinitInBlockF0yyF"( // CHECK: entry: // CHECK: call void @llvm.dbg.declare(metadata ptr %m.debug, -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR:%.*]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA:[0-9]+]], metadata !DIExpression()), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br label %[[BB_NEXT:[a-z0-9\.]+]], +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR:%.*]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // -// CHECK: [[BB_NEXT]]: // CHECK: br i1 %{{[0-9]+}}, label %[[LHS:[0-9]+]], label %[[RHS:[0-9]+]], // // CHECK: [[LHS]]: // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA]], metadata !DIExpression()), !dbg ![[ADDR_LOC]] // TODO: Should this be a deref like the original? -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA]], metadata !DIExpression()), !dbg ![[ADDR_LOC]] -// CHECK-NEXT: br label %[[BB_NEXT_2:[a-z\.0-9]+]], +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] // -// CHECK: [[BB_NEXT_2]]: // CHECK: br label %[[CONT_BB:[a-z\.0-9]+]], // // CHECK: [[RHS]]: @@ -539,19 +513,15 @@ public func copyableVarTestCCFlowReinitInBlockTest() { // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo037copyableVarArgTestCCFlowReinitInBlockG0yyAA5KlassCzF"( // CHECK: entry: // CHECK: call void @llvm.dbg.declare(metadata ptr %m.debug, -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR:%.*]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br label %[[BB_NEXT:[a-z0-9\.]+]], +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR:%.*]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // -// CHECK: [[BB_NEXT]]: // CHECK: br i1 %{{[0-9]+}}, label %[[LHS:[0-9]+]], label %[[RHS:[0-9]+]], // // CHECK: [[LHS]]: // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] // TODO: Should this be a deref like the original? -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] -// CHECK-NEXT: br label %[[BB_NEXT_2:[a-z\.0-9]+]], +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR]], metadata ![[K_COPYABLE_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA]], metadata !DIExpression(DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC]] // -// CHECK: [[BB_NEXT_2]]: // CHECK: br label %[[CONT_BB:[a-z\.0-9]+]], // // CHECK: [[RHS]]: @@ -572,10 +542,8 @@ public func copyableVarArgTestCCFlowReinitInBlockTest(_ k: inout Klass) { // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo040addressOnlyVarTestCCFlowReinitOutOfBlockG0yyxmAA1PRzlF"( // CHECK: entry: -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR:%.*]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA:[0-9]+]], metadata !DIExpression()), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br label %[[BB_NEXT:[a-z0-9\.]+]], +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR:%.*]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // -// CHECK: [[BB_NEXT]]: // CHECK: br i1 %{{[0-9]+}}, label %[[LHS:[0-9]+]], label %[[RHS:[0-9]+]], // // CHECK: [[LHS]]: @@ -587,8 +555,7 @@ public func copyableVarArgTestCCFlowReinitInBlockTest(_ k: inout Klass) { // // CHECK: [[CONT_BB]]: // TODO: Should this be a deref like the original? -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA]], metadata !DIExpression()), !dbg ![[ADDR_LOC]] -// CHECK-NEXT: br +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] // CHECK: ret void // CHECK-NEXT: } public func addressOnlyVarTestCCFlowReinitOutOfBlockTest(_ x: T.Type) { @@ -604,10 +571,8 @@ public func addressOnlyVarTestCCFlowReinitOutOfBlockTest(_ x: T.Type) { // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo043addressOnlyVarArgTestCCFlowReinitOutOfBlockH0yyAA1P_pz_xmtAaCRzlF"( // CHECK: entry: -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR:%.*]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br label %[[BB_NEXT:[a-z0-9\.]+]], +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR:%.*]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // -// CHECK: [[BB_NEXT]]: // CHECK: br i1 %{{[0-9]+}}, label %[[LHS:[0-9]+]], label %[[RHS:[0-9]+]], // // CHECK: [[LHS]]: @@ -619,8 +584,7 @@ public func addressOnlyVarTestCCFlowReinitOutOfBlockTest(_ x: T.Type) { // // CHECK: [[CONT_BB]]: // TODO: Should this be a deref like the original? -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] -// CHECK-NEXT: br +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_OUT_BLOCK_METADATA]], metadata !DIExpression(DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC]] // CHECK: ret void // CHECK-NEXT: } public func addressOnlyVarArgTestCCFlowReinitOutOfBlockTest(_ k: inout (any P), _ x: T.Type) { @@ -635,19 +599,15 @@ public func addressOnlyVarArgTestCCFlowReinitOutOfBlockTest(_ k: inout (a // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo037addressOnlyVarTestCCFlowReinitInBlockG0yyxmAA1PRzlF"( // CHECK: entry: -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR:%.*]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA:[0-9]+]], metadata !DIExpression()), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br label %[[BB_NEXT:[a-z0-9\.]+]], +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR:%.*]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // -// CHECK: [[BB_NEXT]]: // CHECK: br i1 %{{[0-9]+}}, label %[[LHS:[0-9]+]], label %[[RHS:[0-9]+]], // // CHECK: [[LHS]]: // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA]], metadata !DIExpression()), !dbg ![[ADDR_LOC]] // TODO: Should this be a deref like the original? -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA]], metadata !DIExpression()), !dbg ![[ADDR_LOC]] -// CHECK-NEXT: br label %[[BB_NEXT_2:[a-z\.0-9]+]], +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] // -// CHECK: [[BB_NEXT_2]]: // CHECK: br label %[[CONT_BB:[a-z\.0-9]+]], // // CHECK: [[RHS]]: @@ -669,19 +629,15 @@ public func addressOnlyVarTestCCFlowReinitInBlockTest(_ x: T.Type) { // CHECK-LABEL: define swiftcc void @"$s21move_function_dbginfo040addressOnlyVarArgTestCCFlowReinitInBlockH0yyAA1P_pz_xmtAaCRzlF"( // CHECK: entry: -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR:%.*]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br label %[[BB_NEXT:[a-z0-9\.]+]], +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR:%.*]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // -// CHECK: [[BB_NEXT]]: // CHECK: br i1 %{{[0-9]+}}, label %[[LHS:[0-9]+]], label %[[RHS:[0-9]+]], // // CHECK: [[LHS]]: // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] // TODO: Should this be a deref like the original? -// CHECK: call void @llvm.dbg.addr(metadata ptr [[VAR]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] -// CHECK-NEXT: br label %[[BB_NEXT_2:[a-z\.0-9]+]], +// CHECK: call void @llvm.dbg.value(metadata ptr [[VAR]], metadata ![[K_ADDRESSONLY_VAR_CCFLOW_REINIT_IN_BLOCK_METADATA]], metadata !DIExpression(DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC]] // -// CHECK: [[BB_NEXT_2]]: // CHECK: br label %[[CONT_BB:[a-z\.0-9]+]], // // CHECK: [[RHS]]: diff --git a/test/DebugInfo/move_function_dbginfo_async.swift b/test/DebugInfo/move_function_dbginfo_async.swift index 2a27a90da07..6f02a9807b2 100644 --- a/test/DebugInfo/move_function_dbginfo_async.swift +++ b/test/DebugInfo/move_function_dbginfo_async.swift @@ -1,3 +1,4 @@ +// REQUIRES: CPU=arm64 // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -parse-as-library -disable-availability-checking -g -emit-sil -o - %s | %FileCheck -check-prefix=SIL %s // RUN: %target-swift-frontend -parse-as-library -disable-availability-checking -g -emit-ir -o - %s | %FileCheck %s @@ -5,7 +6,7 @@ // This test checks that: // -// 1. At the IR level, we insert the appropriate llvm.dbg.addr, llvm.dbg.value. +// 1. At the IR level, we insert the appropriate llvm.dbg.value. // // 2. At the Dwarf that we have proper locations with PC validity ranges where // the value isn't valid. @@ -45,19 +46,19 @@ public func forceSplit5() async {} // CHECK-LABEL: define swifttailcc void @"$s27move_function_dbginfo_async13letSimpleTestyyxnYalF"(ptr swiftasync %0, ptr noalias %1, ptr %T) // CHECK: entry: -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata ![[SIMPLE_TEST_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata ![[SIMPLE_TEST_METADATA:[0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] // CHECK: musttail call swifttailcc void // CHECK-NEXT: ret void // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async13letSimpleTestyyxnYalFTQ0_"(ptr swiftasync %0) // CHECK: entryresume.0: -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata ![[SIMPLE_TEST_METADATA_2:[0-9]+]], metadata !DIExpression(DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref)), +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata ![[SIMPLE_TEST_METADATA_2:[0-9]+]], metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref, DW_OP_deref)), // CHECK: musttail call swifttailcc void // CHECK-NEXT: ret void // // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async13letSimpleTestyyxnYalFTY1_"(ptr swiftasync %0) // CHECK: entryresume.1: -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata ![[SIMPLE_TEST_METADATA_3:[0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata ![[SIMPLE_TEST_METADATA_3:[0-9]+]], metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[SIMPLE_TEST_METADATA_3]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] // CHECK: musttail call swifttailcc void // CHECK-NEXT: ret void @@ -65,7 +66,8 @@ public func forceSplit5() async {} // RUN: %llvm-dwarfdump -c --name='$s3out13letSimpleTestyyxnYalF' %t/out.o | %FileCheck -check-prefix=DWARF1 %s // DWARF1: DW_AT_linkage_name ("$s3out13letSimpleTestyyxnYalF") // DWARF1: DW_TAG_formal_parameter -// DWARF1-NEXT: DW_AT_location (DW_OP_entry_value([[ASYNC_REG:DW_OP_.*]]), DW_OP_plus_uconst 0x10, DW_OP_plus_uconst 0x8, DW_OP_deref) +// DWARF1-NEXT: DW_AT_location +// DWARF1-NEXT: [[ASYNC_REG:DW_OP_.*]], DW_OP_plus_uconst 0x10, DW_OP_plus_uconst 0x8, DW_OP_deref // DWARF1-NEXT: DW_AT_name ("msg") // // RUN: %llvm-dwarfdump -c --name='$s3out13letSimpleTestyyxnYalFTQ0_' %t/out.o | %FileCheck -check-prefix=DWARF2 %s @@ -89,21 +91,21 @@ public func letSimpleTest(_ msg: __owned T) async { } // CHECK-LABEL: define swifttailcc void @"$s27move_function_dbginfo_async13varSimpleTestyyxz_xtYalF"(ptr swiftasync %0, ptr %1, ptr noalias %2, ptr %T) -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref)) +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref, DW_OP_deref)) // CHECK: musttail call swifttailcc void @"$s27move_function_dbginfo_async10forceSplityyYaF"(ptr swiftasync %{{[0-9]+}}) // CHECK-NEXT: ret void // CHECK-NEXT: } // // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async13varSimpleTestyyxz_xtYalFTQ0_"(ptr swiftasync %0) // CHECK: entryresume.0: -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref)) +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref, DW_OP_deref)) // CHECK: musttail call swifttailcc void @swift_task_switch(ptr swiftasync %{{[0-9]+}}, ptr @"$s27move_function_dbginfo_async13varSimpleTestyyxz_xtYalFTY1_", i64 0, i64 0) // CHECK-NEXT: ret void // CHECK-NEXT: } // // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async13varSimpleTestyyxz_xtYalFTY1_"(ptr swiftasync %0) // CHECK: entryresume.1: -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata ![[METADATA:[0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata ![[METADATA:[0-9]+]], metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] // CHECK: musttail call swifttailcc void @"$s27move_function_dbginfo_async10forceSplityyYaF"(ptr swiftasync // CHECK-NEXT: ret void @@ -114,9 +116,9 @@ public func letSimpleTest(_ msg: __owned T) async { // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async13varSimpleTestyyxz_xtYalFTY3_"(ptr swiftasync %0) // CHECK: entryresume.3: -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata ![[METADATA:[0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata ![[METADATA:[0-9]+]], metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata ![[METADATA]], metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref)), !dbg ![[ADDR_LOC]] +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata ![[METADATA]], metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC]] // CHECK: musttail call swifttailcc void @"$s27move_function_dbginfo_async10forceSplityyYaF"( // CHECK-NEXT: ret void // CHECK-NEXT: } @@ -125,7 +127,8 @@ public func letSimpleTest(_ msg: __owned T) async { // DWARF4: DW_AT_linkage_name ("$s3out13varSimpleTestyyxz_xtYalF") // DWARF4: DW_AT_name ("varSimpleTest") // DWARF4: DW_TAG_formal_parameter -// DWARF4-NEXT: DW_AT_location (DW_OP_entry_value([[ASYNC_REG:.*]]), DW_OP_plus_uconst 0x10, DW_OP_plus_uconst 0x8, DW_OP_deref) +// DWARF4-NEXT: DW_AT_location +// DWARF4-NEXT: [[ASYNC_REG:.*]], DW_OP_plus_uconst 0x10, DW_OP_plus_uconst 0x8, DW_OP_deref, DW_OP_deref // DWARF4-NEXT: DW_AT_name ("msg") // // RUN: %llvm-dwarfdump -c --name='$s3out13varSimpleTestyyxz_xtYalFTQ0_' %t/out.o | %FileCheck -check-prefix=DWARF5 %s @@ -198,34 +201,26 @@ public func varSimpleTest(_ msg: inout T, _ msg2: T) async { await forceSplit() } -// We don't have an argument here, so we shouldn't have an llvm.dbg.addr in the -// initial function. -// // CHECK-LABEL: define swifttailcc void @"$s27move_function_dbginfo_async16varSimpleTestVaryyYaF"(ptr swiftasync %0) -// CHECK-NOT: llvm.dbg.addr -// // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async16varSimpleTestVaryyYaFTY0_"(ptr swiftasync %0) -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8)) +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref)) // // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async16varSimpleTestVaryyYaFTQ1_"(ptr swiftasync %0) -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8)) +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref)) // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async16varSimpleTestVaryyYaFTY2_"(ptr swiftasync %0) -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata ![[METADATA:[0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8)), !dbg ![[ADDR_LOC:[0-9]+]] +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata ![[METADATA:[0-9]+]], metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[METADATA]], metadata !DIExpression()), !dbg ![[ADDR_LOC]] // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async16varSimpleTestVaryyYaFTQ3_"(ptr swiftasync %0) -// We should only see an llvm.dbg.value here. -// CHECK-NOT: llvm.dbg.addr // CHECK: call void @llvm.dbg.value(metadata ptr undef, -// CHECK-NOT: llvm.dbg.addr // // We should see first a llvm.dbg.value to undef the value until we reinit. Then -// we should see a llvm.dbg.addr to reinit. +// we should see a llvm.dbg.value to reinit. // // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async16varSimpleTestVaryyYaFTY4_"(ptr swiftasync %0) // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[METADATA:[0-9]+]], metadata !DIExpression()), !dbg ![[ADDR_LOC:[0-9]+]] -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata ![[METADATA]], metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8)), !dbg ![[ADDR_LOC]] +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata ![[METADATA]], metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref)), !dbg ![[ADDR_LOC]] // We are not an argument, so no problem here. // @@ -306,22 +301,19 @@ public func varSimpleTestVar() async { //////////////////////////////////// // CHECK-LABEL: define swifttailcc void @"$s27move_function_dbginfo_async20letArgCCFlowTrueTestyyxnYalF"( -// CHECK: call void @llvm.dbg.addr( +// CHECK: call void @llvm.dbg.value( // CHECK: musttail call swifttailcc void @"$s27move_function_dbginfo_async11forceSplit1yyYaF"( // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async20letArgCCFlowTrueTestyyxnYalFTQ0_"( -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref)), +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref, DW_OP_deref)), // CHECK: musttail call swifttailcc void @swift_task_switch(ptr swiftasync %{{[0-9]+}}, ptr @"$s27move_function_dbginfo_async20letArgCCFlowTrueTestyyxnYalFTY1_", i64 0, i64 0) // CHECK-NEXT: ret void // CHECK-NEXT: } // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async20letArgCCFlowTrueTestyyxnYalFTY1_"( -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata ![[METADATA:[0-9]*]], metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] -// CHECK-NEXT: br label %[[BLOCK:[a-zA-Z\.0-9]*]], -// -// CHECK: [[BLOCK]]: +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata ![[METADATA:[0-9]*]], metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]*]] // CHECK: br i1 %{{[0-9]}}, label %[[LHS_BLOCK:[a-zA-Z\.0-9]*]], label %[[RHS_BLOCK:[a-zA-Z\.0-9]*]], // // CHECK: [[LHS_BLOCK]]: @@ -330,8 +322,6 @@ public func varSimpleTestVar() async { // CHECK-NEXT: ret void // // CHECK: [[RHS_BLOCK]]: -// CHECK-NOT: call void @llvm.dbg.value( -// CHECK-NOT: call void @llvm.dbg.addr( // CHECK: musttail call swifttailcc void @"$s27move_function_dbginfo_async11forceSplit3yyYaF"( // CHECK-NEXT: ret void // @@ -349,7 +339,8 @@ public func varSimpleTestVar() async { // This is the false branch. // // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async20letArgCCFlowTrueTestyyxnYalFTQ3_"( -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref)) +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata ![[msg_var:[0-9]+]], metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 8, DW_OP_deref, DW_OP_deref)) +// CHECK-NEXT: call void @llvm.dbg.value(metadata ptr undef, metadata ![[msg_var]] // CHECK: musttail call swifttailcc void @"$s27move_function_dbginfo_async11forceSplit4yyYaF"( // CHECK-NEXT: ret void, // CHECK-NEXT: } @@ -364,7 +355,8 @@ public func varSimpleTestVar() async { // DWARF17: DW_AT_name ("letArgCCFlowTrueTest") // DWARF17: DW_TAG_formal_parameter -// DWARF17-NEXT: DW_AT_location (DW_OP_entry_value([[ASYNC_REG:.*]]), DW_OP_plus_uconst 0x10, DW_OP_plus_uconst 0x8, DW_OP_deref) +// DWARF17-NEXT: DW_AT_location +// DWARF17-NEXT: [[ASYNC_REG:.*]], DW_OP_plus_uconst 0x10, DW_OP_plus_uconst 0x8, DW_OP_deref, DW_OP_deref // DWARF17-NEXT: DW_AT_name ("msg") // // RUN: %llvm-dwarfdump -c --name='$s3out20letArgCCFlowTrueTestyyxnYalFTQ0_' %t/out.o | %FileCheck -check-prefix=DWARF18 %s @@ -393,9 +385,7 @@ public func varSimpleTestVar() async { // DWARF21: DW_AT_linkage_name ("$s3out20letArgCCFlowTrueTestyyxnYalFTQ3_") // DWARF21-NEXT: DW_AT_name ("letArgCCFlowTrueTest") // DWARF21: DW_TAG_formal_parameter -// DWARF21-NEXT: DW_AT_location (0x{{[a-f0-9]+}}: -// DWARF21-NEXT: [0x{{[a-f0-9]+}}, 0x{{[a-f0-9]+}}): DW_OP_entry_value([[ASYNC_REG:.*]]), DW_OP_deref, DW_OP_plus_uconst 0x10, DW_OP_plus_uconst 0x8, DW_OP_deref) -// DWARF21-NEXT: DW_AT_name ("msg") +// DWARF21-NEXT: DW_AT_name ("msg") // // RUN: %llvm-dwarfdump -c --name='$s3out20letArgCCFlowTrueTestyyxnYalFTQ4_' %t/out.o | %FileCheck -check-prefix=DWARF22 %s // DWARF22: DW_AT_linkage_name ("$s3out20letArgCCFlowTrueTestyyxnYalFTQ4_") @@ -451,14 +441,14 @@ public func letArgCCFlowTrueTest(_ msg: __owned T) async { // SIL: } // end sil function '$s27move_function_dbginfo_async20varArgCCFlowTrueTestyyxzYaAA1PRzlF' // CHECK-LABEL: define swifttailcc void @"$s27move_function_dbginfo_async20varArgCCFlowTrueTestyyxzYaAA1PRzlF"( -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 48, DW_OP_deref)), +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 48, DW_OP_deref, DW_OP_deref)), // CHECK: musttail call swifttailcc void @"$s27move_function_dbginfo_async11forceSplit1yyYaF"( // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async20varArgCCFlowTrueTestyyxzYaAA1PRzlFTQ0_"( -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 48, DW_OP_deref)), +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 48, DW_OP_deref, DW_OP_deref)), // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async20varArgCCFlowTrueTestyyxzYaAA1PRzlFTY1_"( -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata ![[METADATA:[0-9]+]], metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 48, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata ![[METADATA:[0-9]+]], metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 48, DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] // CHECK: br i1 %{{[0-9]+}}, label %[[LHS_BLOCK:[a-zA-Z0-9]+]], label %[[RHS_BLOCK:[a-zA-Z0-9]+]] // CHECK: [[LHS_BLOCK]]: @@ -466,37 +456,33 @@ public func letArgCCFlowTrueTest(_ msg: __owned T) async { // CHECK: musttail call swifttailcc void @"$s27move_function_dbginfo_async11forceSplit2yyYaF"( // CHECK: [[RHS_BLOCK]]: -// CHECK-NOT: call void @llvm.dbg.value // CHECK: musttail call swifttailcc void @"$s27move_function_dbginfo_async11forceSplit3yyYaF"( // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async20varArgCCFlowTrueTestyyxzYaAA1PRzlFTQ2_"( -// CHECK-NOT: @llvm.dbg.addr // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_deref)), -// CHECK-NOT: @llvm.dbg.addr // CHECK: musttail call swifttailcc void @swift_task_switch(ptr swiftasync %{{[0-9]+}}, ptr @"$s27move_function_dbginfo_async20varArgCCFlowTrueTestyyxzYaAA1PRzlFTY3_", i64 0, i64 0) // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async20varArgCCFlowTrueTestyyxzYaAA1PRzlFTY3_"( -// CHECK-NOT: @llvm.dbg.addr // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata ![[METADATA]], metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 48, DW_OP_deref)), !dbg ![[ADDR_LOC]] +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata ![[METADATA]], metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 48, DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC]] // CHECK: musttail call swifttailcc void @"$s27move_function_dbginfo_async11forceSplit4yyYaF"( // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async20varArgCCFlowTrueTestyyxzYaAA1PRzlFTQ4_"( // CHECK-NOT: @llvm.dbg.value -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata ![[METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 48, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata ![[METADATA:[0-9]+]], metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 48, DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] // CHECK: musttail call swifttailcc void @swift_task_switch(ptr swiftasync %{{[0-9]+}}, ptr @"$s27move_function_dbginfo_async20varArgCCFlowTrueTestyyxzYaAA1PRzlFTY5_", // CHECK: define internal swifttailcc void @"$s27move_function_dbginfo_async20varArgCCFlowTrueTestyyxzYaAA1PRzlFTY5_"( // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[METADATA:[0-9]+]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC:[0-9]+]] // CHECK: call void @llvm.dbg.value(metadata ptr undef, metadata ![[METADATA]], metadata !DIExpression(DW_OP_deref)), !dbg ![[ADDR_LOC]] -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata ![[METADATA]], metadata !DIExpression(DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 48, DW_OP_deref)), !dbg ![[ADDR_LOC]] +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata ![[METADATA]], metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 48, DW_OP_deref, DW_OP_deref)), !dbg ![[ADDR_LOC]] // CHECK: musttail call swifttailcc void @"$s27move_function_dbginfo_async11forceSplit4yyYaF"( // CHECK-LABEL: define internal swifttailcc void @"$s27move_function_dbginfo_async20varArgCCFlowTrueTestyyxzYaAA1PRzlFTQ6_"( // CHECK-NOT: @llvm.dbg.value( -// CHECK: call void @llvm.dbg.addr(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 48, DW_OP_deref)), +// CHECK: call void @llvm.dbg.value(metadata ptr %{{[0-9]+}}, metadata !{{[0-9]+}}, metadata !DIExpression(DW_OP_LLVM_entry_value, 1, DW_OP_deref, DW_OP_plus_uconst, 16, DW_OP_plus_uconst, 48, DW_OP_deref, DW_OP_deref)), // CHECK-NOT: @llvm.dbg.value( // CHECK: musttail call swifttailcc void %{{[0-9]+}}(ptr swiftasync // CHECK-NEXT: ret void, @@ -506,7 +492,8 @@ public func letArgCCFlowTrueTest(_ msg: __owned T) async { // DWARF24: DW_AT_linkage_name ("$s3out20varArgCCFlowTrueTestyyxzYaAA1PRzlF") // DWARF24: DW_AT_name ("varArgCCFlowTrueTest") // DWARF24: DW_TAG_formal_parameter -// DWARF24-NEXT: DW_AT_location (DW_OP_entry_value([[ASYNC_REG:.*]]), DW_OP_plus_uconst 0x10, DW_OP_plus_uconst 0x30, DW_OP_deref) +// DWARF24-NEXT: DW_AT_location +// DWARF24-NEXT: [[ASYNC_REG:.*]], DW_OP_plus_uconst 0x10, DW_OP_plus_uconst 0x30, DW_OP_deref, DW_OP_deref // DWARF24-NEXT: DW_AT_name ("msg") // @@ -544,9 +531,7 @@ public func letArgCCFlowTrueTest(_ msg: __owned T) async { // DWARF29: DW_AT_linkage_name ("$s3out20varArgCCFlowTrueTestyyxzYaAA1PRzlFTQ4_") // DWARF29-NEXT: DW_AT_name ("varArgCCFlowTrueTest") // DWARF29: DW_TAG_formal_parameter -// DWARF29-NEXT: DW_AT_location (0x{{[a-f0-9]+}}: -// DWARF29-NEXT: [0x{{[a-f0-9]+}}, 0x{{[a-f0-9]+}}): DW_OP_entry_value([[ASYNC_REG:.*]]), DW_OP_deref, DW_OP_plus_uconst 0x10, DW_OP_plus_uconst 0x30, DW_OP_deref) -// DWARF-NEXT: DW_AT_name ("msg") +// DWARF29-NEXT: DW_AT_name ("msg") // // RUN: %llvm-dwarfdump -c --name='$s3out20varArgCCFlowTrueTestyyxzYaAA1PRzlFTY5_' %t/out.o | %FileCheck -check-prefix=DWARF30 %s // DWARF30: DW_AT_linkage_name ("$s3out20varArgCCFlowTrueTestyyxzYaAA1PRzlFTY5_") diff --git a/test/Driver/Inputs/fake-resource-dir/lib/swift/clang/lib/linux/libclang_rt.scudo-x86_64.a b/test/Driver/Inputs/fake-resource-dir/lib/swift/clang/lib/linux/libclang_rt.scudo_standalone-x86_64.a similarity index 100% rename from test/Driver/Inputs/fake-resource-dir/lib/swift/clang/lib/linux/libclang_rt.scudo-x86_64.a rename to test/Driver/Inputs/fake-resource-dir/lib/swift/clang/lib/linux/libclang_rt.scudo_standalone-x86_64.a diff --git a/test/Driver/sanitize_scudo.swift b/test/Driver/sanitize_scudo.swift index cbc3051be02..8b86815a031 100644 --- a/test/Driver/sanitize_scudo.swift +++ b/test/Driver/sanitize_scudo.swift @@ -11,7 +11,7 @@ // RUN: not %swiftc_driver -resource-dir %S/Inputs/fake-resource-dir/lib/swift/ -driver-print-jobs -sanitize=scudo,address -target x86_64-unknown-linux-gnu %s 2>&1 | %FileCheck -check-prefix=SCUDO_ASAN %s // RUN: not %swiftc_driver -resource-dir %S/Inputs/fake-resource-dir/lib/swift/ -driver-print-jobs -sanitize=scudo,thread -target x86_64-unknown-linux-gnu %s 2>&1 | %FileCheck -check-prefix=SCUDO_TSAN %s -// RUN: %swiftc_driver -resource-dir %S/Inputs/fake-resource-dir/lib/swift/ -driver-print-jobs -sanitize=scudo,undefined -target x86_64-unknown-linux-gnu %s 2>&1 | %FileCheck -check-prefix=SCUDO_UBSAN_LINUX %s +// RUN: not %swiftc_driver -resource-dir %S/Inputs/fake-resource-dir/lib/swift/ -driver-print-jobs -sanitize=scudo,undefined -target x86_64-unknown-linux-gnu %s 2>&1 | %FileCheck -check-prefix=SCUDO_UBSAN %s /* @@ -34,7 +34,6 @@ // SCUDO_ASAN: argument '-sanitize=scudo' is not allowed with '-sanitize=address' // SCUDO_TSAN: argument '-sanitize=scudo' is not allowed with '-sanitize=thread' -// SCUDO_UBSAN_LINUX: -fsanitize=undefined,scudo +// SCUDO_UBSAN: argument '-sanitize=scudo' is not allowed with '-sanitize=undefined' // SCUDO_LIBRARY_LINUX: bin{{/|\\\\}}clang // SCUDO_LIBRARY_LINUX-NOT: -fsanitize=scudo - diff --git a/test/Frontend/dependencies-fine.swift b/test/Frontend/dependencies-fine.swift index 7aa13928459..aae02e727b4 100644 --- a/test/Frontend/dependencies-fine.swift +++ b/test/Frontend/dependencies-fine.swift @@ -1,3 +1,5 @@ +// REQUIRES: rdar114207865 + // RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-dependencies-path - -resolve-imports "%S/../Inputs/empty file.swift" | %FileCheck -check-prefix=CHECK-BASIC %s diff --git a/test/IRGen/asmname.swift b/test/IRGen/asmname.swift index 156aaea16cb..51a3165b816 100644 --- a/test/IRGen/asmname.swift +++ b/test/IRGen/asmname.swift @@ -11,19 +11,22 @@ _ = atan2test(0.0, 0.0) // Ordinary Swift definitions -// The unused internal and private functions are expected to be eliminated. +// The unused internal and private functions are expected to be kept as they +// may be used from the debugger in unoptimized builds. public func PlainPublic() { } internal func PlainInternal() { } private func PlainPrivate() { } // CHECK: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s7asmname11PlainPublic -// CHECK-NOT: PlainInternal -// CHECK-NOT: PlainPrivate +// CHECK: define{{( dllexport)?}}{{( protected)?}} hidden swiftcc void @"$s7asmname13PlainInternalyyF +// CHECK: define{{( dllexport)?}}{{( protected)?}} internal swiftcc void @"$s7asmname12PlainPrivate // Swift _silgen_name definitions -// The private function is expected to be eliminated -// but the internal function must survive for C use. +// The private function is expected +// to be eliminated as it may be used from the +// debugger in unoptimized builds, +// and the internal function must survive for C use. // Only the C-named definition is emitted. @_silgen_name("silgen_name_public") public func SilgenNamePublic() { } @@ -31,13 +34,13 @@ private func PlainPrivate() { } @_silgen_name("silgen_name_private") private func SilgenNamePrivate() { } // CHECK: define{{( dllexport)?}}{{( protected)?}} swiftcc void @silgen_name_public // CHECK: define hidden swiftcc void @silgen_name_internal -// CHECK-NOT: silgen_name_private +// CHECK: define internal swiftcc void @silgen_name_private // CHECK-NOT: SilgenName // Swift cdecl definitions -// The private functions are expected to be eliminated -// but the internal functions must survive for C use. +// The private functions are expected to be kept as it may be used from the debugger, +// and the internal functions must survive for C use. // Both a C-named definition and a Swift-named definition are emitted. @_cdecl("cdecl_public") public func CDeclPublic() { } @@ -47,4 +50,4 @@ private func PlainPrivate() { } // CHECK: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s7asmname11CDeclPublic // CHECK: define hidden void @cdecl_internal // CHECK: define hidden swiftcc void @"$s7asmname13CDeclInternal -// CHECK-NOT: cdecl_private +// CHECK: define internal void @cdecl_private() diff --git a/test/IRGen/associated_types.swift b/test/IRGen/associated_types.swift index b1e6d45abff..59ae355a870 100644 --- a/test/IRGen/associated_types.swift +++ b/test/IRGen/associated_types.swift @@ -102,5 +102,5 @@ public struct P0Impl : P0 { // CHECK: define{{.*}} swiftcc ptr @"$s16associated_types6P0ImplVAA0C0AA9ErrorTypeAaDP_s0E0PWT"(ptr %P0Impl.ErrorType, ptr %P0Impl, ptr %P0Impl.P0) // CHECK: ret ptr @"$ss5ErrorWS" -// CHECK: attributes [[NOUNWIND_READNONE]] = { nounwind readnone willreturn } +// CHECK: attributes [[NOUNWIND_READNONE]] = { nounwind willreturn memory(none) } diff --git a/test/IRGen/async/run-call-class-witnessmethod-void-to-void.swift b/test/IRGen/async/run-call-class-witnessmethod-void-to-void.swift index ca65a55bf0e..6cb1322bf1f 100644 --- a/test/IRGen/async/run-call-class-witnessmethod-void-to-void.swift +++ b/test/IRGen/async/run-call-class-witnessmethod-void-to-void.swift @@ -28,8 +28,8 @@ protocol P { // CHECK: exiting call_f // CHECK-LL: @"$s4main1PPAAE1fyyYaFTu" = hidden global %swift.async_func_pointer -// CHECK-LL: @"$s4main6call_fyyxYaAA1PRzlFTu" = hidden global %swift.async_func_pointer // CHECK-LL: @"$s4main1XCAA1PA2aDP1fyyYaFTWTu" = internal global %swift.async_func_pointer +// CHECK-LL: @"$s4main6call_fyyxYaAA1PRzlFTu" = hidden global %swift.async_func_pointer extension P { // CHECK-LL: define hidden swift{{(tail)?}}cc void @"$s4main1PPAAE1fyyYaF"( diff --git a/test/IRGen/c_globals.swift b/test/IRGen/c_globals.swift index 271ff817ee3..31211a3f62f 100644 --- a/test/IRGen/c_globals.swift +++ b/test/IRGen/c_globals.swift @@ -38,8 +38,8 @@ public func testCaptureGlobal() { // CHECK-x86_64-SYSV-DAG: attributes [[CLANG_FUNC_ATTR]] = { noinline nounwind {{.*}}"frame-pointer"="all"{{.*}} // CHECK-x86_64-SYSV-DAG: attributes [[SWIFT_FUNC_ATTR]] = { {{.*}}"frame-pointer"="all" {{.*}}"target-cpu" -// CHECK-x86_64-WIN-DAG: attributes [[CLANG_FUNC_ATTR]] = { noinline nounwind {{.*}}"frame-pointer"="none"{{.*}} -// CHECK-x86_64-WIN-DAG: attributes [[SWIFT_FUNC_ATTR]] = { {{.*}}"frame-pointer"="none" {{.*}}"target-cpu" +// CHECK-x86_64-WIN-DAG: attributes [[CLANG_FUNC_ATTR]] = { noinline nounwind {{.*}} +// CHECK-x86_64-WIN-DAG: attributes [[SWIFT_FUNC_ATTR]] = { {{.*}}"target-cpu" // CHECK-armv7-SYSV-DAG: attributes [[CLANG_FUNC_ATTR]] = { noinline nounwind {{.*}}"frame-pointer"="all"{{.*}} // CHECK-armv7-SYSV-DAG: attributes [[SWIFT_FUNC_ATTR]] = { {{.*}}"frame-pointer"="all" {{.*}}"target-cpu" diff --git a/test/IRGen/default_function_ir_attributes.swift b/test/IRGen/default_function_ir_attributes.swift index fc5093de656..1e59c67c93e 100644 --- a/test/IRGen/default_function_ir_attributes.swift +++ b/test/IRGen/default_function_ir_attributes.swift @@ -155,6 +155,6 @@ func test_computed_key_path_generic_thunks(value: T) -> KeyPat // unlikely that handrolled code generation would think to add one. // CHECK: attributes [[ATTRS_SIMPLE]] = { [[CUSTOM_ATTRS:.*target-cpu.*]] }{{$}} // CHECK-DAG: attributes [[ATTRS_NOINLINE_NOUNWIND]] = { noinline nounwind {{.*target-cpu.*}} } -// CHECK-DAG: attributes [[ATTRS_NOINLINE_READNONE_NOUNWIND_NOFRAME]] = { noinline nounwind readnone {{.*}}"frame-pointer"="non-leaf"{{.*target-cpu.*}} } -// CHECK-DAG: attributes [[ATTRS_NOINLINE_READONLY_NOUNWIND_NOFRAME]] = { noinline nounwind readonly willreturn {{.*}}"frame-pointer"="non-leaf"{{.*target-cpu.*}} } +// CHECK-DAG: attributes [[ATTRS_NOINLINE_READNONE_NOUNWIND_NOFRAME]] = { noinline nounwind memory(none) {{.*}}"frame-pointer"="non-leaf"{{.*target-cpu.*}} } +// CHECK-DAG: attributes [[ATTRS_NOINLINE_READONLY_NOUNWIND_NOFRAME]] = { noinline nounwind willreturn memory(read) {{.*}}"frame-pointer"="non-leaf"{{.*target-cpu.*}} } // CHECK-DAG: attributes [[ATTRS_NOUNWIND]] = { nounwind [[CUSTOM_ATTRS]] }{{$}} diff --git a/test/IRGen/framepointer.sil b/test/IRGen/framepointer.sil index 62062ec2eef..2ef0a5c2b7f 100644 --- a/test/IRGen/framepointer.sil +++ b/test/IRGen/framepointer.sil @@ -34,7 +34,7 @@ entry(%i : $Int32): // CHECK: } // CHECK-SYSV: attributes [[ATTR]] = { {{.*}}"frame-pointer"="all" -// CHECK-WIN: attributes [[ATTR]] = { {{.*}}"frame-pointer"="none" +// CHECK-WIN: attributes [[ATTR]] = { {{.*}} // CHECK-ALL: define{{.*}} swiftcc i32 @leaf_function_no_frame_pointer(i32 %0) [[ATTR:#.*]] { // CHECK-ALL: entry: @@ -48,7 +48,7 @@ entry(%i : $Int32): // CHECK-ALL: } // CHECK-SYSV-ALL: attributes [[ATTR]] = {{{.*}}"frame-pointer"="all" -// CHECK-WIN-ALL: attributes [[ATTR]] = {{{.*}}"frame-pointer"="none" +// CHECK-WIN-ALL: attributes [[ATTR]] = {{{.*}} // LEAF: define{{.*}} swiftcc i32 @leaf_function_no_frame_pointer(i32 %0) [[ATTR:#.*]] { // LEAF: entry: @@ -62,7 +62,7 @@ entry(%i : $Int32): // LEAF: } // LEAF-SYSV: attributes [[ATTR]] = {{{.*}}"frame-pointer"="non-leaf" -// LEAF-WIN: attributes [[ATTR]] = {{{.*}}"frame-pointer"="none" +// LEAF-WIN: attributes [[ATTR]] = {{{.*}} // NOFP: define{{.*}} swiftcc i32 @leaf_function_no_frame_pointer(i32 %0) [[ATTR:#.*]] { // NOFP: entry: @@ -75,7 +75,8 @@ entry(%i : $Int32): // NOFP: ret i32 %1 // NOFP: } -// NOFP: attributes [[ATTR]] = {{{.*}}"frame-pointer"="none" +// The clang frontend's -fomit-frame-pointer no longer leads to frame-pointer=none +// attributes [[ATTR]] = {{{.*}} // Silence other os-archs. // CHECKASM: {{.*}} diff --git a/test/IRGen/generic_metatypes.swift b/test/IRGen/generic_metatypes.swift index 8d7031d7461..d27fe84c461 100644 --- a/test/IRGen/generic_metatypes.swift +++ b/test/IRGen/generic_metatypes.swift @@ -100,19 +100,19 @@ func genericMetatype(_ x: A.Type) {} // CHECK-LABEL: define hidden swiftcc void @"$s17generic_metatypes20makeGenericMetatypesyyF"() {{.*}} { func makeGenericMetatypes() { - // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName{{.*}}({{.*}} @"$s17generic_metatypes6OneArgVyAA3FooVGMD") [[NOUNWIND_READNONE:#[0-9]+]] + // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName{{.*}}({{.*}} @"$s17generic_metatypes6OneArgVyAA3FooVGMD") [[NOUNWIND_READONLY:#[0-9]+]] genericMetatype(OneArg.self) - // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName{{.*}}({{.*}} @"$s17generic_metatypes7TwoArgsVyAA3FooVAA3BarCGMD") [[NOUNWIND_READNONE]] + // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName{{.*}}({{.*}} @"$s17generic_metatypes7TwoArgsVyAA3FooVAA3BarCGMD") [[NOUNWIND_READONLY]] genericMetatype(TwoArgs.self) - // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName{{.*}}({{.*}} @"$s17generic_metatypes9ThreeArgsVyAA3FooVAA3BarCAEGMD") [[NOUNWIND_READNONE]] + // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName{{.*}}({{.*}} @"$s17generic_metatypes9ThreeArgsVyAA3FooVAA3BarCAEGMD") [[NOUNWIND_READONLY]] genericMetatype(ThreeArgs.self) - // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName{{.*}}({{.*}} @"$s17generic_metatypes8FourArgsVyAA3FooVAA3BarCAeGGMD") [[NOUNWIND_READNONE]] + // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName{{.*}}({{.*}} @"$s17generic_metatypes8FourArgsVyAA3FooVAA3BarCAeGGMD") [[NOUNWIND_READONLY]] genericMetatype(FourArgs.self) - // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName{{.*}}({{.*}} @"$s17generic_metatypes8FiveArgsVyAA3FooVAA3BarCAegEGMD") [[NOUNWIND_READNONE]] + // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName{{.*}}({{.*}} @"$s17generic_metatypes8FiveArgsVyAA3FooVAA3BarCAegEGMD") [[NOUNWIND_READONLY]] genericMetatype(FiveArgs.self) } @@ -138,5 +138,5 @@ func makeGenericMetatypes() { // CHECK-NOT: call void @llvm.lifetime.end // CHECK: ret %swift.metadata_response -// CHECK-DAG: attributes [[NOUNWIND_READNONE]] = { nounwind readonly } +// CHECK-DAG: attributes [[NOUNWIND_READONLY]] = { nounwind memory(read) } // CHECK-DAG: attributes [[NOUNWIND_OPT]] = { noinline nounwind " diff --git a/test/IRGen/generic_metatypes_future.swift b/test/IRGen/generic_metatypes_future.swift index 7c37e70cf00..f1492f3c9f4 100644 --- a/test/IRGen/generic_metatypes_future.swift +++ b/test/IRGen/generic_metatypes_future.swift @@ -117,16 +117,16 @@ func makeGenericMetatypes() { // CHECK-SAME: ) genericMetatype(OneArg.self) - // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$s17generic_metatypes7TwoArgsVyAA3FooVAA3BarCGMD") [[NOUNWIND_READNONE:#[0-9]+]] + // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$s17generic_metatypes7TwoArgsVyAA3FooVAA3BarCGMD") [[NOUNWIND_READONLY:#[0-9]+]] genericMetatype(TwoArgs.self) - // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$s17generic_metatypes9ThreeArgsVyAA3FooVAA3BarCAEGMD") [[NOUNWIND_READNONE]] + // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$s17generic_metatypes9ThreeArgsVyAA3FooVAA3BarCAEGMD") [[NOUNWIND_READONLY]] genericMetatype(ThreeArgs.self) - // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$s17generic_metatypes8FourArgsVyAA3FooVAA3BarCAeGGMD") [[NOUNWIND_READNONE]] + // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$s17generic_metatypes8FourArgsVyAA3FooVAA3BarCAeGGMD") [[NOUNWIND_READONLY]] genericMetatype(FourArgs.self) - // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$s17generic_metatypes8FiveArgsVyAA3FooVAA3BarCAegEGMD") [[NOUNWIND_READNONE]] + // CHECK: call {{.*}} @__swift_instantiateConcreteTypeFromMangledName({{.*}} @"$s17generic_metatypes8FiveArgsVyAA3FooVAA3BarCAegEGMD") [[NOUNWIND_READONLY]] genericMetatype(FiveArgs.self) } @@ -152,5 +152,5 @@ func makeGenericMetatypes() { // CHECK-NOT: call void @llvm.lifetime.end // CHECK: ret %swift.metadata_response -// CHECK-DAG: attributes [[NOUNWIND_READNONE]] = { nounwind readonly } +// CHECK-DAG: attributes [[NOUNWIND_READONLY]] = { nounwind memory(read) } // CHECK-DAG: attributes [[NOUNWIND_OPT]] = { noinline nounwind " diff --git a/test/IRGen/objc_implementation.swift b/test/IRGen/objc_implementation.swift index 1b503308683..e474531f406 100644 --- a/test/IRGen/objc_implementation.swift +++ b/test/IRGen/objc_implementation.swift @@ -6,6 +6,9 @@ // RUN: %FileCheck --input-file %t.ir --check-prefix NEGATIVE %s // REQUIRES: objc_interop +// CHECK: [[selector_data_implProperty:@[^, ]+]] = private global [13 x i8] c"implProperty\00", section "__TEXT,__objc_methname,cstring_literals", align 1 +// CHECK: [[selector_data_setImplProperty_:@[^, ]+]] = private global [17 x i8] c"setImplProperty:\00", section "__TEXT,__objc_methname,cstring_literals", align 1 + // CHECK: [[selector_data_mainMethod_:@[^, ]+]] = private global [12 x i8] c"mainMethod:\00", section "__TEXT,__objc_methname,cstring_literals", align 1 // @@ -19,8 +22,6 @@ // TODO: Why the extra i32 field above? // Class -// CHECK: [[selector_data_implProperty:@[^, ]+]] = private global [13 x i8] c"implProperty\00", section "__TEXT,__objc_methname,cstring_literals", align 1 -// CHECK: [[selector_data_setImplProperty_:@[^, ]+]] = private global [17 x i8] c"setImplProperty:\00", section "__TEXT,__objc_methname,cstring_literals", align 1 // CHECK: [[selector_data__cxx_destruct:@[^, ]+]] = private global [14 x i8] c".cxx_destruct\00", section "__TEXT,__objc_methname,cstring_literals", align 1 // CHECK: [[_INSTANCE_METHODS_ImplClass:@[^, ]+]] = internal constant { i32, i32, [7 x { ptr, ptr, ptr }] } { i32 24, i32 7, [7 x { ptr, ptr, ptr }] [{ ptr, ptr, ptr } { ptr @"\01L_selector_data(init)", ptr @".str.7.@16@0:8", ptr @"$sSo9ImplClassC19objc_implementationEABycfcTo{{(\.ptrauth)?}}" }, { ptr, ptr, ptr } { ptr [[selector_data_implProperty]], ptr @".str.7.i16@0:8", ptr @"$sSo9ImplClassC19objc_implementationE12implPropertys5Int32VvgTo{{(\.ptrauth)?}}" }, { ptr, ptr, ptr } { ptr [[selector_data_setImplProperty_]], ptr @".str.10.v20@0:8i16", ptr @"$sSo9ImplClassC19objc_implementationE12implPropertys5Int32VvsTo{{(\.ptrauth)?}}" }, { ptr, ptr, ptr } { ptr [[selector_data_mainMethod_]], ptr @".str.10.v20@0:8i16", ptr @"$sSo9ImplClassC19objc_implementationE10mainMethodyys5Int32VFTo{{(\.ptrauth)?}}" }, { ptr, ptr, ptr } { ptr @"\01L_selector_data(copyWithZone:)", ptr @".str.11.@24@0:8^v16", ptr @"$sSo9ImplClassC19objc_implementationE4copy4withypSg10ObjectiveC6NSZoneVSg_tFTo{{(\.ptrauth)?}}" }, { ptr, ptr, ptr } { ptr @"\01L_selector_data(dealloc)", ptr @".str.7.v16@0:8", ptr @"$sSo9ImplClassC19objc_implementationEfDTo{{(\.ptrauth)?}}" }, { ptr, ptr, ptr } { ptr [[selector_data__cxx_destruct]], ptr @".str.7.v16@0:8", ptr @"$sSo9ImplClassCfETo{{(\.ptrauth)?}}" }] }, section "__DATA, __objc_data", align 8 // CHECK: [[_IVARS_ImplClass:@[^, ]+]] = internal constant { i32, i32, [2 x { ptr, ptr, ptr, i32, i32 }] } { i32 32, i32 2, [2 x { ptr, ptr, ptr, i32, i32 }] [{ ptr, ptr, ptr, i32, i32 } { ptr @"$sSo9ImplClassC19objc_implementationE12implPropertys5Int32VvpWvd", ptr @.str.12.implProperty, ptr @.str.0., i32 2, i32 4 }, { ptr, ptr, ptr, i32, i32 } { ptr @"$sSo9ImplClassC19objc_implementationE13implProperty2So8NSObjectCSgvpWvd", ptr @.str.13.implProperty2, ptr @.str.0., i32 3, i32 8 }] }, section "__DATA, __objc_const", align 8 diff --git a/test/IRGen/objc_ns_enum.swift b/test/IRGen/objc_ns_enum.swift index eb3475c279f..80c51dd7ff5 100644 --- a/test/IRGen/objc_ns_enum.swift +++ b/test/IRGen/objc_ns_enum.swift @@ -124,5 +124,5 @@ func objc_enum_method_calls(_ x: ObjCEnumMethods) { x.prop = x.enumOut() } -// CHECK: attributes [[NOUNWIND_READNONE]] = { nounwind readnone } +// CHECK: attributes [[NOUNWIND_READNONE]] = { nounwind memory(none) } diff --git a/test/IRGen/objc_super.swift b/test/IRGen/objc_super.swift index bc2dc9d9e0c..b8a8a2cdea6 100644 --- a/test/IRGen/objc_super.swift +++ b/test/IRGen/objc_super.swift @@ -83,6 +83,10 @@ class PartialApply : Gizmo { // CHECK: @objc_msgSendSuper2 // CHECK: } +// CHECK: define internal swiftcc void [[PARTIAL_FORWARDING_THUNK]](ptr swiftself %0) {{.*}} { +// CHECK: s10objc_super12PartialApplyC4frobyyFyycfu_ +// CHECK: } + class GenericRuncer : Gizmo { var x: Gizmo? = nil var y: T? @@ -120,7 +124,3 @@ class GenericRuncer : Gizmo { super.runce() } } - -// CHECK: define internal swiftcc void [[PARTIAL_FORWARDING_THUNK]](ptr swiftself %0) {{.*}} { -// CHECK: @"$ss12StaticStringV14withUTF8BufferyxxSRys5UInt8VGXElFxAFXEfU_yt_Tgq5" -// CHECK: } diff --git a/test/IRGen/object_type.swift b/test/IRGen/object_type.swift index 07874ca08f5..d009f91f142 100644 --- a/test/IRGen/object_type.swift +++ b/test/IRGen/object_type.swift @@ -35,8 +35,8 @@ func work() { // CHECK-IR: call {{.*}} @swift_getObjectType({{.*}}) #[[M:[0-9]+]] // CHECK-IR: declare {{.*}} @swift_getObjectType{{.*}} local_unnamed_addr #[[N:[0-9]+]] -// CHECK-IR: attributes #[[N]] = { mustprogress nofree nounwind readonly willreturn } -// CHECK-IR: attributes #[[M]] = { nounwind readonly willreturn } +// CHECK-IR: attributes #[[N]] = { mustprogress nofree nounwind willreturn memory(read) } +// CHECK-IR: attributes #[[M]] = { nounwind willreturn memory(read) } // CHECK: okay work() diff --git a/test/IRGen/opaque-pointer-llvm.swift b/test/IRGen/opaque-pointer-llvm.swift deleted file mode 100644 index 188b27a3f33..00000000000 --- a/test/IRGen/opaque-pointer-llvm.swift +++ /dev/null @@ -1,6 +0,0 @@ -// RUN: %target-swift-frontend -Xcc -Xclang -Xcc -opaque-pointers -primary-file %s -emit-ir | %FileCheck %s --check-prefix=CHECK -// RUN: %target-swift-frontend -Xcc -Xclang -Xcc -no-opaque-pointers -primary-file %s -emit-ir | %FileCheck %s --check-prefix=CHECK-NO - -// CHECK: define{{.*}} @{{main|__main_argc_argv}}({{.*}} %0, ptr %1) -// CHECK-NO: define{{.*}} @{{main|__main_argc_argv}}({{.*}} %0, i8** %1) -public func test() {} diff --git a/test/IRGen/ordering_x86.sil b/test/IRGen/ordering_x86.sil index 686bcd188ca..6630f829535 100644 --- a/test/IRGen/ordering_x86.sil +++ b/test/IRGen/ordering_x86.sil @@ -41,4 +41,4 @@ bb0: // the order of features differs. // X86_64: define{{( protected)?}} swiftcc void @baz{{.*}}#0 -// X86_64: #0 = {{.*}}"target-features"="+cx16,+cx8,+fxsr,+mmx,+sahf,+sse,+sse2,+sse3,+ssse3,+x87" +// X86_64: #0 = {{.*}}"target-features"="+cmov,+cx16,+cx8,+fxsr,+mmx,+sahf,+sse,+sse2,+sse3,+ssse3,+x87" diff --git a/test/IRGen/preserve_for_debugger.swift b/test/IRGen/preserve_for_debugger.swift new file mode 100644 index 00000000000..1a13ab4756a --- /dev/null +++ b/test/IRGen/preserve_for_debugger.swift @@ -0,0 +1,28 @@ +// RUN: %target-swiftc_driver %s -g -Onone -emit-ir | %FileCheck %s + +// Check that unused functions are preserved at Onone. +func unused() { +} + +// Property wrappers generate transparent getters, which we would like to check still exist at Onone. +@propertyWrapper +struct IntWrapper { + private var storage = 42 + var wrappedValue: Int { + return storage + } +} + +public class User { + @IntWrapper private var number: Int + + func f() { + // Force the generation of the getter + _ = self.number + } +} +let c = User() +c.f() + +// CHECK: !DISubprogram(name: "unused", linkageName: "$s21preserve_for_debugger6unusedyyF" +// CHECK: !DISubprogram(name: "number.get" diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-2argument-1_distinct_use-1st_argument_generic_class-2nd_argument_distinct_generic_class.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-2argument-1_distinct_use-1st_argument_generic_class-2nd_argument_distinct_generic_class.swift index 669befcdf43..2d70590d9d0 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-2argument-1_distinct_use-1st_argument_generic_class-2nd_argument_distinct_generic_class.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-2argument-1_distinct_use-1st_argument_generic_class-2nd_argument_distinct_generic_class.swift @@ -117,18 +117,6 @@ func doit() { } doit() -// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr [[ARGUMENT1_METADATA:%[0-9]+]], ptr [[ARGUMENT2_METADATA:%[0-9]+]]) #{{[0-9]+}} {{(section)?.*}}{ -// CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( -// CHECK-SAME: [[INT]] [[METADATA_REQUEST]], -// CHECK-SAME: ptr [[ARGUMENT1_METADATA]], -// CHECK-SAME: ptr [[ARGUMENT2_METADATA]], -// CHECK-SAME: ptr undef, -// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCMn -// CHECK-SAME: ) -// CHECK: ret %swift.metadata_response {{%[0-9]+}} -// CHECK: } - - // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_4]]LLCyAA9Argument1ACLLCySiGAA9Argument2ACLLCySSGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]}} {{(section)?.*}}{ // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @"$s4main9Argument1[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] 0) @@ -147,3 +135,13 @@ doit() // CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] // CHECK: } +// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr [[ARGUMENT1_METADATA:%[0-9]+]], ptr [[ARGUMENT2_METADATA:%[0-9]+]]) #{{[0-9]+}} {{(section)?.*}}{ +// CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( +// CHECK-SAME: [[INT]] [[METADATA_REQUEST]], +// CHECK-SAME: ptr [[ARGUMENT1_METADATA]], +// CHECK-SAME: ptr [[ARGUMENT2_METADATA]], +// CHECK-SAME: ptr undef, +// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCMn +// CHECK-SAME: ) +// CHECK: ret %swift.metadata_response {{%[0-9]+}} +// CHECK: } diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-2argument-1_distinct_use-1st_argument_generic_class-2nd_argument_same_generic_class_different_value.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-2argument-1_distinct_use-1st_argument_generic_class-2nd_argument_same_generic_class_different_value.swift index 4768fd3af59..138a8ede895 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-2argument-1_distinct_use-1st_argument_generic_class-2nd_argument_same_generic_class_different_value.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-2argument-1_distinct_use-1st_argument_generic_class-2nd_argument_same_generic_class_different_value.swift @@ -109,18 +109,6 @@ func doit() { } doit() -// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr [[ARGUMENT1_METADATA:%[0-9]+]], ptr [[ARGUMENT2_METADATA:%[0-9]+]]) #{{[0-9]+}} {{(section)?.*}}{ -// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( -// CHECK-SAME: [[INT]] [[METADATA_REQUEST]], -// CHECK-SAME: ptr [[ARGUMENT1_METADATA]], -// CHECK-SAME: ptr [[ARGUMENT2_METADATA]], -// CHECK-SAME: ptr undef, -// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCMn -// CHECK: ) -// CHECK: ret %swift.metadata_response {{%[0-9]+}} -// CHECK: } - - // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_4]]LLCyAA9Argument1ACLLCySiGAFySSGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]}} {{(section)?.*}}{ // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @"$s4main9Argument1[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] 0) @@ -141,4 +129,13 @@ doit() // CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] // CHECK: } - +// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr [[ARGUMENT1_METADATA:%[0-9]+]], ptr [[ARGUMENT2_METADATA:%[0-9]+]]) #{{[0-9]+}} {{(section)?.*}}{ +// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( +// CHECK-SAME: [[INT]] [[METADATA_REQUEST]], +// CHECK-SAME: ptr [[ARGUMENT1_METADATA]], +// CHECK-SAME: ptr [[ARGUMENT2_METADATA]], +// CHECK-SAME: ptr undef, +// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCMn +// CHECK: ) +// CHECK: ret %swift.metadata_response {{%[0-9]+}} +// CHECK: } diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-2argument-1_distinct_use-1st_argument_generic_class-2nd_argument_same_generic_class_same_value.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-2argument-1_distinct_use-1st_argument_generic_class-2nd_argument_same_generic_class_same_value.swift index 1c39ba896d9..c54dd9289a5 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-2argument-1_distinct_use-1st_argument_generic_class-2nd_argument_same_generic_class_same_value.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-2argument-1_distinct_use-1st_argument_generic_class-2nd_argument_same_generic_class_same_value.swift @@ -108,20 +108,6 @@ func doit() { } doit() -// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr [[ARGUMENT1_METADATA:%[0-9]+]], ptr [[ARGUMENT2_METADATA:%[0-9]+]]) #{{[0-9]+}} {{(section)?.*}}{ -// CHECK: entry: -// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( -// CHECK-SAME: [[INT]] [[METADATA_REQUEST]], -// CHECK-SAME: ptr [[ARGUMENT1_METADATA]], -// CHECK-SAME: ptr [[ARGUMENT2_METADATA]], -// CHECK-SAME: ptr undef, -// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCMn -// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCMz -// CHECK: ) -// CHECK: ret %swift.metadata_response {{%[0-9]+}} -// CHECK: } - - // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_4]]LLCyAA9Argument1ACLLCySiGAGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]}} {{(section)?.*}}{ // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @"$s4main9Argument1[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] 0) @@ -141,3 +127,16 @@ doit() // CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 // CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] // CHECK: } + +// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr [[ARGUMENT1_METADATA:%[0-9]+]], ptr [[ARGUMENT2_METADATA:%[0-9]+]]) #{{[0-9]+}} {{(section)?.*}}{ +// CHECK: entry: +// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( +// CHECK-SAME: [[INT]] [[METADATA_REQUEST]], +// CHECK-SAME: ptr [[ARGUMENT1_METADATA]], +// CHECK-SAME: ptr [[ARGUMENT2_METADATA]], +// CHECK-SAME: ptr undef, +// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCMn +// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCMz +// CHECK: ) +// CHECK: ret %swift.metadata_response {{%[0-9]+}} +// CHECK: } diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_con_int-2nd_anc_gen-1st-arg_con_double.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_con_int-2nd_anc_gen-1st-arg_con_double.swift index fa6d2aeb409..2b412a3f285 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_con_int-2nd_anc_gen-1st-arg_con_double.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_con_int-2nd_anc_gen-1st-arg_con_double.swift @@ -122,6 +122,18 @@ func doit() { } doit() +// CHECK: ; Function Attrs: noinline nounwind memory(none) +// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CySSGMb"([[INT]] {{%[0-9]+}}) #{{[0-9]+}} {{(section)?.*}}{ +// CHECK: call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMb"([[INT]] 0) +// CHECK-NOT: call swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]CySiGMb"([[INT]] 0) +// CHECK-unknown: ret +// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call ptr @objc_opt_self( +// CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]CySSGMf" +// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, ptr [[INITIALIZED_CLASS]], 0 +// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 +// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] +// CHECK: } + // CHECK: define internal swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]CMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( @@ -162,18 +174,6 @@ doit() // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: } -// CHECK: ; Function Attrs: noinline nounwind readnone -// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CySSGMb"([[INT]] {{%[0-9]+}}) #{{[0-9]+}} {{(section)?.*}}{ -// CHECK: call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMb"([[INT]] 0) -// CHECK-NOT: call swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]CySiGMb"([[INT]] 0) -// CHECK-unknown: ret -// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call ptr @objc_opt_self( -// CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]CySSGMf" -// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, ptr [[INITIALIZED_CLASS]], 0 -// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 -// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] -// CHECK: } - // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMb"([[INT]] {{%[0-9]+}}) // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]CySdGMb"([[INT]] {{%[0-9]+}}) diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_con_int-2nd_anc_gen-1st-arg_subclass_arg.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_con_int-2nd_anc_gen-1st-arg_subclass_arg.swift index 1a59f41d03a..5832a508ffa 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_con_int-2nd_anc_gen-1st-arg_subclass_arg.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_con_int-2nd_anc_gen-1st-arg_subclass_arg.swift @@ -120,6 +120,19 @@ func doit() { } doit() +// CHECK: ; Function Attrs: noinline nounwind memory(none) +// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CySSGMb"([[INT]] {{%[0-9]+}}) #{{[0-9]+}} {{(section)?.*}}{ +// CHECK: entry: +// CHECK: call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMb"([[INT]] 0) +// CHECK-NOT: call swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]CySiGMb"([[INT]] 0) +// CHECK-unknown: ret +// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call ptr @objc_opt_self( +// CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]CySSGMf" +// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, ptr [[INITIALIZED_CLASS]], 0 +// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 +// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] +// CHECK: } + // CHECK: define internal swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]CMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( @@ -156,19 +169,6 @@ doit() // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: } -// CHECK: ; Function Attrs: noinline nounwind readnone -// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CySSGMb"([[INT]] {{%[0-9]+}}) #{{[0-9]+}} {{(section)?.*}}{ -// CHECK: entry: -// CHECK: call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMb"([[INT]] 0) -// CHECK-NOT: call swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]CySiGMb"([[INT]] 0) -// CHECK-unknown: ret -// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call ptr @objc_opt_self( -// CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]CySSGMf" -// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, ptr [[INITIALIZED_CLASS]], 0 -// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 -// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] -// CHECK: } - // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMb"([[INT]] {{%[0-9]+}}) // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]CySiGMb"([[INT]] {{%[0-9]+}}) diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_subclass_arg-2nd_anc_gen-1st-arg_con_int.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_subclass_arg-2nd_anc_gen-1st-arg_con_int.swift index 09e1dbeef44..99cd13e20a9 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_subclass_arg-2nd_anc_gen-1st-arg_con_int.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_subclass_arg-2nd_anc_gen-1st-arg_con_int.swift @@ -120,6 +120,19 @@ func doit() { } doit() +// CHECK: ; Function Attrs: noinline nounwind memory(none) +// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCySSGMb"([[INT]] {{%[0-9]+}}) #{{[0-9]+}} {{(section)?.*}}{ +// CHECK: entry: +// CHECK: call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCySSGMb"([[INT]] 0) +// CHECK-NOT: call swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] 0) +// CHECK-unknown: ret +// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call ptr @objc_opt_self( +// CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]LLCySSGMf" +// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, ptr [[INITIALIZED_CLASS]], 0 +// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 +// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] +// CHECK: } + // CHECK: define internal swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( @@ -156,19 +169,6 @@ doit() // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: } -// CHECK: ; Function Attrs: noinline nounwind readnone -// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCySSGMb"([[INT]] {{%[0-9]+}}) #{{[0-9]+}} {{(section)?.*}}{ -// CHECK: entry: -// CHECK: call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCySSGMb"([[INT]] 0) -// CHECK-NOT: call swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] 0) -// CHECK-unknown: ret -// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call ptr @objc_opt_self( -// CHECK-SAME: @"$s4main5Value[[UNIQUE_ID_1]]LLCySSGMf" -// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, ptr [[INITIALIZED_CLASS]], 0 -// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 -// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] -// CHECK: } - // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCySSGMb"([[INT]] {{%[0-9]+}}) // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] {{%[0-9]+}}) diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_subcls_arg-2nd_anc_gen-1st-arg_subcls_arg.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_subcls_arg-2nd_anc_gen-1st-arg_subcls_arg.swift index 17cd4e844de..1722a716159 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_subcls_arg-2nd_anc_gen-1st-arg_subcls_arg.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1arg-2ancs-1distinct_use-1st_anc_gen-1arg-1st_arg_subcls_arg-2nd_anc_gen-1st-arg_subcls_arg.swift @@ -118,6 +118,19 @@ func doit() { } doit() +// CHECK: ; Function Attrs: noinline nounwind memory(none) +// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} {{(section)?.*}}{ +// CHECK: entry: +// CHECK: call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] 0) +// CHECK-NOT: call swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] 0) +// CHECK-unknown: ret +// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call ptr @objc_opt_self( +// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCySiGMf +// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, ptr [[INITIALIZED_CLASS]], 0 +// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 +// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] +// CHECK: } + // CHECK: define internal swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr [[ARGUMENT:%[0-9]+]]) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( @@ -154,19 +167,6 @@ doit() // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: } -// CHECK: ; Function Attrs: noinline nounwind readnone -// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} {{(section)?.*}}{ -// CHECK: entry: -// CHECK: call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] 0) -// CHECK-NOT: call swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] 0) -// CHECK-unknown: ret -// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call ptr @objc_opt_self( -// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCySiGMf -// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, ptr [[INITIALIZED_CLASS]], 0 -// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 -// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] -// CHECK: } - // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCySiGMb" diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_generic-1argument-1st_argument_constant_int.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_generic-1argument-1st_argument_constant_int.swift index 5f28f85297c..726d1d3c212 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_generic-1argument-1st_argument_constant_int.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_generic-1argument-1st_argument_constant_int.swift @@ -104,7 +104,7 @@ doit() // CHECK: call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CySSGMb" // CHECK: } -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CySSGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} {{(section)?.*}}{ // CHECK: [[SUPER_CLASS_METADATA:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]CySiGMb"([[INT]] 0) // CHECK-unknown: ret diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_generic-1argument-1st_argument_superclass.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_generic-1argument-1st_argument_superclass.swift index 94b5174cb0e..bbbefc78224 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_generic-1argument-1st_argument_superclass.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_generic-1argument-1st_argument_superclass.swift @@ -114,7 +114,7 @@ doit() // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCySSGMb" -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA9Ancestor1ACLLCySSGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} {{(section)?.*}}{ // CHECK-NEXT: entry: // CHECK: [[ARGUMENT_CLASS_METADATA:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCySSGMb"([[INT]] 0) diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_nongeneric-external-nonresilient.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_nongeneric-external-nonresilient.swift index 943346d0f3e..a92fc681222 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_nongeneric-external-nonresilient.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_nongeneric-external-nonresilient.swift @@ -90,7 +90,7 @@ doit() // CHECK: call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCySiGMb" // CHECK: } -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} {{(section)?.*}}{ // CHECK: [[SUPERCLASS_METADATA:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s10TestModule9Ancestor1CMa"([[INT]] 0) // CHECK-unknown: ret diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_nongeneric-fileprivate.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_nongeneric-fileprivate.swift index 4c47577a352..e9a4fe03b93 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_nongeneric-fileprivate.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1ancestor-1distinct_use-1st_ancestor_nongeneric-fileprivate.swift @@ -95,9 +95,7 @@ doit() // CHECK: call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCySiGMb" // CHECK: } -// CHECK: define internal swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCMa" - -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} {{(section)?.*}}{ // CHECK-NEXT: entry: // CHECK: [[SUPERCLASS_METADATA:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCMa"([[INT]] 0) @@ -109,4 +107,5 @@ doit() // CHECK-apple: ret %swift.metadata_response [[COMPLETE_RESPONSE]] // CHECK: } +// CHECK: define internal swiftcc %swift.metadata_response @"$s4main9Ancestor1[[UNIQUE_ID_1]]LLCMa" diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use-1st_argument_generic_class-1argument.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use-1st_argument_generic_class-1argument.swift index c72d3c2913b..1d2d0bee8e5 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use-1st_argument_generic_class-1argument.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use-1st_argument_generic_class-1argument.swift @@ -183,6 +183,16 @@ func doit() { } doit() +// CHECK:; Function Attrs: noinline nounwind memory(none) +// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CyAA9Argument1ACLLCySiGGMb"([[INT]] [[REQUEST:%[0-9]+]]) #{{[0-9]+}} {{(section)?.*}}{ +// CHECK-unknown: ret +// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call ptr @objc_opt_self( +// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CyAA9Argument1ACLLCySiGGMf +// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, ptr [[INITIALIZED_CLASS]], 0 +// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 +// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] +// CHECK: } + // CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( @@ -195,12 +205,3 @@ doit() // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: } -// CHECK:; Function Attrs: noinline nounwind readnone -// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CyAA9Argument1ACLLCySiGGMb"([[INT]] [[REQUEST:%[0-9]+]]) #{{[0-9]+}} {{(section)?.*}}{ -// CHECK-unknown: ret -// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call ptr @objc_opt_self( -// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CyAA9Argument1ACLLCySiGGMf -// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, ptr [[INITIALIZED_CLASS]], 0 -// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 -// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] -// CHECK: } diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use.swift index a357b2b5e50..74e90e8215c 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use.swift @@ -85,6 +85,14 @@ func doit() { } doit() +// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_4]]CySiGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]}} {{(section)?.*}}{ +// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call ptr @objc_opt_self( +// CHECK-apple-SAME: $s4main5Value[[UNIQUE_ID_1]]CySiGMf +// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, ptr [[INITIALIZED_CLASS]], 0 +// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 +// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] +// CHECK: } + // CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( // CHECK-SAME: [[INT]] [[METADATA_REQUEST]], @@ -95,11 +103,3 @@ doit() // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: } - -// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_4]]CySiGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]}} {{(section)?.*}}{ -// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call ptr @objc_opt_self( -// CHECK-apple-SAME: $s4main5Value[[UNIQUE_ID_1]]CySiGMf -// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, ptr [[INITIALIZED_CLASS]], 0 -// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 -// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] -// CHECK: } diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_class.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_class.swift index 3d1a8f7ad08..46b1bcda3ab 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_class.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_class.swift @@ -100,18 +100,7 @@ func doit() { } doit() -// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr %1) #{{[0-9]+}} {{(section)?.*}}{ -// CHECK: entry: -// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( -// CHECK-SAME: [[INT]] [[METADATA_REQUEST]], -// CHECK-SAME: ptr %1, -// CHECK-SAME: ptr undef, -// CHECK-SAME: ptr undef, -// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCMn -// CHECK: ret %swift.metadata_response {{%[0-9]+}} -// CHECK: } - -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA3BoxACLLCySiGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK-unknown: ret @@ -123,3 +112,14 @@ doit() // CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] // CHECK: } +// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr %1) #{{[0-9]+}} {{(section)?.*}}{ +// CHECK: entry: +// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( +// CHECK-SAME: [[INT]] [[METADATA_REQUEST]], +// CHECK-SAME: ptr %1, +// CHECK-SAME: ptr undef, +// CHECK-SAME: ptr undef, +// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCMn +// CHECK: ret %swift.metadata_response {{%[0-9]+}} +// CHECK: } + diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_class_specialized_at_generic_class.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_class_specialized_at_generic_class.swift index 72f398fb654..2bb84c288d5 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_class_specialized_at_generic_class.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_class_specialized_at_generic_class.swift @@ -109,19 +109,7 @@ func doit() { } doit() -// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr %1) #{{[0-9]+}} {{(section)?.*}}{ -// CHECK: entry: -// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( -// CHECK: [[INT]] [[METADATA_REQUEST]], -// CHECK: ptr %1, -// CHECK: ptr undef, -// CHECK: ptr undef, -// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCMn -// CHECK: ) -// CHECK: ret %swift.metadata_response {{%[0-9]+}} -// CHECK: } - -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCyAA3BoxACLLCyAA5InnerACLLCySiGGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK-unknown: ret @@ -138,4 +126,16 @@ doit() // CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] // CHECK: } +// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr %1) #{{[0-9]+}} {{(section)?.*}}{ +// CHECK: entry: +// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( +// CHECK: [[INT]] [[METADATA_REQUEST]], +// CHECK: ptr %1, +// CHECK: ptr undef, +// CHECK: ptr undef, +// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]LLCMn +// CHECK: ) +// CHECK: ret %swift.metadata_response {{%[0-9]+}} +// CHECK: } + diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_enum.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_enum.swift index 6d112b3f5d8..5117d5fb6fc 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_enum.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_enum.swift @@ -5,7 +5,9 @@ // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios -// CHECK: @"$s4main5Value[[UNIQUE_ID_1:[A-Za-z0-9_]+]]CyAA6EitherACLLOySiGGMf" = linkonce_odr hidden +// CHECK: @"$s4main6Either[[UNIQUE_ID_1:[A-Za-z0-9_]+]]OySiGMf" = + +// CHECK: @"$s4main5Value[[UNIQUE_ID_1]]CyAA6EitherACLLOySiGGMf" = linkonce_odr hidden // CHECK-apple-SAME: global // CHECK-unknown-SAME: constant // CHECK-SAME: <{ @@ -92,7 +94,6 @@ // CHECK-SAME: }>, // CHECK-SAME: align [[ALIGNMENT]] -// CHECK: @"$s4main6Either[[UNIQUE_ID_1]]OySiGMf" = fileprivate class Value { let first_Value: First @@ -125,18 +126,7 @@ func doit() { } doit() -// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr %1) #{{[0-9]+}} {{(section)?.*}}{ -// CHECK: entry: -// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( -// CHECK: [[INT]] [[METADATA_REQUEST]], -// CHECK: ptr %1, -// CHECK: ptr undef, -// CHECK: ptr undef, -// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CMn -// CHECK: ret %swift.metadata_response {{%[0-9]+}} -// CHECK: } - -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CyAA6EitherACLLOySiGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} {{(section)?.*}}{ // CHECK-unknown: ret // CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call ptr @objc_opt_self( @@ -153,3 +143,15 @@ doit() // CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 // CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] // CHECK: } + +// CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr %1) #{{[0-9]+}} {{(section)?.*}}{ +// CHECK: entry: +// CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( +// CHECK: [[INT]] [[METADATA_REQUEST]], +// CHECK: ptr %1, +// CHECK: ptr undef, +// CHECK: ptr undef, +// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CMn +// CHECK: ret %swift.metadata_response {{%[0-9]+}} +// CHECK: } + diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_struct.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_struct.swift index 6e005b7735b..53c46ec8dc4 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_struct.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-1distinct_use_generic_struct.swift @@ -5,7 +5,9 @@ // UNSUPPORTED: CPU=armv7 && OS=ios // UNSUPPORTED: CPU=armv7s && OS=ios -// CHECK: @"$s4main5Value[[UNIQUE_ID_1:[A-Za-z0-9_]+]]CyAA4LeftACLLVySiGGMf" = linkonce_odr hidden +// CHECK: @"$s4main4Left[[UNIQUE_ID_1:[A-Za-z0-9_]+]]VySiGMf" = + +// CHECK: @"$s4main5Value[[UNIQUE_ID_1]]CyAA4LeftACLLVySiGGMf" = linkonce_odr hidden // CHECK-apple-SAME: global // CHECK-unknown-SAME: constant // CHECK-SAME: <{ @@ -64,7 +66,6 @@ // CHECK-SAME: }>, // CHECK-SAME: align [[ALIGNMENT]] -// CHECK: @"$s4main4Left[[UNIQUE_ID_1]]VySiGMf" = fileprivate class Value { let first_Value: First @@ -96,6 +97,17 @@ func doit() { } doit() +// CHECK: ; Function Attrs: noinline nounwind memory(none) +// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CyAA4LeftACLLVySiGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} {{(section)?.*}}{ +// CHECK-unknown: ret +// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call ptr @objc_opt_self( +// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CyAA4LeftACLLVySiGGMf +// : ) +// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, ptr [[INITIALIZED_CLASS]], 0 +// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 +// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] +// CHECK: } + // CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CMa"([[INT]] [[METADATA_REQUEST:%[0-9]+]], ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( @@ -106,14 +118,3 @@ doit() // CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CMn // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: } - -// CHECK: ; Function Attrs: noinline nounwind readnone -// CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]CyAA4LeftACLLVySiGGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} {{(section)?.*}}{ -// CHECK-unknown: ret -// CHECK-apple: [[INITIALIZED_CLASS:%[0-9]+]] = call ptr @objc_opt_self( -// CHECK-SAME: $s4main5Value[[UNIQUE_ID_1]]CyAA4LeftACLLVySiGGMf -// : ) -// CHECK-apple: [[PARTIAL_METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response undef, ptr [[INITIALIZED_CLASS]], 0 -// CHECK-apple: [[METADATA_RESPONSE:%[0-9]+]] = insertvalue %swift.metadata_response [[PARTIAL_METADATA_RESPONSE]], [[INT]] 0, 1 -// CHECK-apple: ret %swift.metadata_response [[METADATA_RESPONSE]] -// CHECK: } diff --git a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-2ancestor-1du-1st_ancestor_generic-fileprivate-2nd_ancestor_nongeneric.swift b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-2ancestor-1du-1st_ancestor_generic-fileprivate-2nd_ancestor_nongeneric.swift index 4fce22a1162..8848d74180f 100644 --- a/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-2ancestor-1du-1st_ancestor_generic-fileprivate-2nd_ancestor_nongeneric.swift +++ b/test/IRGen/prespecialized-metadata/class-fileprivate-inmodule-1argument-2ancestor-1du-1st_ancestor_generic-fileprivate-2nd_ancestor_nongeneric.swift @@ -110,7 +110,7 @@ doit() // CHECK: call swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCySiGMb" // CHECK: } -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define linkonce_odr hidden swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] {{%[0-9]+}}) {{#[0-9]+}} {{(section)?.*}}{ // CHECK: [[SUPERCLASS_METADATA:%[0-9]+]] = call swiftcc %swift.metadata_response @"$s4main9Ancestor2[[UNIQUE_ID_1]]LLCySiGMb"([[INT]] 0) // CHECK-unknown: ret diff --git a/test/IRGen/prespecialized-metadata/enum-fileprivate-inmodule-1argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/enum-fileprivate-inmodule-1argument-1distinct_use.swift index bc6194a1ab7..76ca27707c8 100644 --- a/test/IRGen/prespecialized-metadata/enum-fileprivate-inmodule-1argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/enum-fileprivate-inmodule-1argument-1distinct_use.swift @@ -45,7 +45,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]OMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-0argument-within-class-1argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-0argument-within-class-1argument-1distinct_use.swift index b28cf83983c..f00c40f98f8 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-0argument-within-class-1argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-0argument-within-class-1argument-1distinct_use.swift @@ -52,7 +52,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceC5ValueOMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( // CHECK-SAME: [[INT]] %0, diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-0distinct_use.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-0distinct_use.swift index 18e942dcc3d..e7cd863bd2b 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-0distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-0distinct_use.swift @@ -21,7 +21,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-1distinct_use.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-1distinct_use.swift index 58eb75c03eb..c50291dd05a 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-1distinct_use.swift @@ -51,7 +51,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-external_nonresilient-1distinct_use.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-external_nonresilient-1distinct_use.swift index 36bf3dc544c..635085fda27 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-external_nonresilient-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-external_nonresilient-1distinct_use.swift @@ -45,7 +45,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-external_resilient-1distinct_use.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-external_resilient-1distinct_use.swift index 4a51083dba8..bdf76e488d5 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-external_resilient-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-external_resilient-1distinct_use.swift @@ -42,7 +42,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-public-1distinct_use.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-public-1distinct_use.swift index bb089101b2c..aba00c71965 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-public-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-public-1distinct_use.swift @@ -51,7 +51,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-stdlib_equatable-1distinct_use.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-stdlib_equatable-1distinct_use.swift index af74a3be195..e1dd2666cbe 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-stdlib_equatable-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1conformance-stdlib_equatable-1distinct_use.swift @@ -25,7 +25,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( // CHECK-SAME: [[INT]] %0, diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1distinct_generic_use.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1distinct_generic_use.swift index 2338b4e045c..3e015a2a0b9 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1distinct_generic_use.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1distinct_generic_use.swift @@ -49,7 +49,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5OuterOMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( // CHECK-SAME: [[INT]] %0, diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1distinct_use.swift index 5342ad4b3ae..0c47cc21aba 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-1distinct_use.swift @@ -56,7 +56,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-class-1argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-class-1argument-1distinct_use.swift index bf4736c0c56..1848cd95f52 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-class-1argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-class-1argument-1distinct_use.swift @@ -49,7 +49,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceC5ValueOMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-enum-1argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-enum-1argument-1distinct_use.swift index a008f2386ad..ea8866fa25a 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-enum-1argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-enum-1argument-1distinct_use.swift @@ -49,7 +49,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceO5ValueOMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-struct-1argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-struct-1argument-1distinct_use.swift index 9744757beaa..883e5c2d57b 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-struct-1argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-1argument-within-struct-1argument-1distinct_use.swift @@ -49,7 +49,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceV5ValueOMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-2argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-2argument-1distinct_use.swift index be98d0074de..08fb78fe021 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-2argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-2argument-1distinct_use.swift @@ -64,7 +64,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-3argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-3argument-1distinct_use.swift index 77cb0f2fd20..fe5530e590b 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-3argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-3argument-1distinct_use.swift @@ -66,7 +66,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, ptr %1, ptr %2, ptr %3) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-evolution-1argument-1distinct_use-external_resilient-frozen.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-evolution-1argument-1distinct_use-external_resilient-frozen.swift index 87af5dd5e43..5c273dc746a 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-evolution-1argument-1distinct_use-external_resilient-frozen.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-evolution-1argument-1distinct_use-external_resilient-frozen.swift @@ -51,7 +51,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-evolution-1argument-1distinct_use-external_resilient-nonfrozen.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-evolution-1argument-1distinct_use-external_resilient-nonfrozen.swift index c4cab219086..900844ece93 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-evolution-1argument-1distinct_use-external_resilient-nonfrozen.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-evolution-1argument-1distinct_use-external_resilient-nonfrozen.swift @@ -35,7 +35,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( // CHECK-SAME: [[INT]] %0, diff --git a/test/IRGen/prespecialized-metadata/enum-inmodule-evolution-1argument-1distinct_use-payload_size.swift b/test/IRGen/prespecialized-metadata/enum-inmodule-evolution-1argument-1distinct_use-payload_size.swift index 1a123165c6e..bc27ccf36a6 100644 --- a/test/IRGen/prespecialized-metadata/enum-inmodule-evolution-1argument-1distinct_use-payload_size.swift +++ b/test/IRGen/prespecialized-metadata/enum-inmodule-evolution-1argument-1distinct_use-payload_size.swift @@ -63,7 +63,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define{{( protected)?}} swiftcc %swift.metadata_response @"$s4main5ValueOMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( // CHECK-SAME: [[INT]] %0, diff --git a/test/IRGen/prespecialized-metadata/struct-fileprivate-inmodule-1argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-fileprivate-inmodule-1argument-1distinct_use.swift index e73a67887e7..dcfc2c40fcc 100644 --- a/test/IRGen/prespecialized-metadata/struct-fileprivate-inmodule-1argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-fileprivate-inmodule-1argument-1distinct_use.swift @@ -48,7 +48,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define internal swiftcc %swift.metadata_response @"$s4main5Value[[UNIQUE_ID_1]]VMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-0argument-within-class-1argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-0argument-within-class-1argument-1distinct_use.swift index 80d4fb78c8a..bff8bc7b218 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-0argument-within-class-1argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-0argument-within-class-1argument-1distinct_use.swift @@ -51,7 +51,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceC5ValueVMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-0distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-0distinct_use.swift index 2f721efda80..608c07a701f 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-0distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-0distinct_use.swift @@ -21,7 +21,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1conformance-1distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1conformance-1distinct_use.swift index 23c3570886a..3f19f49858d 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1conformance-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1conformance-1distinct_use.swift @@ -54,7 +54,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( // CHECK-SAME: [[INT]] %0, diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1conformance-stdlib_equatable-1distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1conformance-stdlib_equatable-1distinct_use.swift index 0d174dbaa7c..fed2fbe0874 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1conformance-stdlib_equatable-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1conformance-stdlib_equatable-1distinct_use.swift @@ -25,7 +25,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1distinct_generic_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1distinct_generic_use.swift index 11fc651e033..2c5a6d0aca9 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1distinct_generic_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1distinct_generic_use.swift @@ -39,7 +39,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5OuterVMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( @@ -52,7 +52,7 @@ doit() // CHECK: ret %swift.metadata_response {{%[0-9]+}} // CHECK: } -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5InnerVMa"([[INT]] %0, ptr [[TYPE:%[0-9]+]]) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1distinct_use.swift index 3daf8073fb0..39bff10c599 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-1distinct_use.swift @@ -48,7 +48,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( // CHECK-SAME: [[INT]] %0, diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-2conformance-1distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-2conformance-1distinct_use.swift index 3db214ef11f..b81ef37c7e0 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-2conformance-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-2conformance-1distinct_use.swift @@ -58,7 +58,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1, ptr %2, ptr %3) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-2distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-2distinct_use.swift index 95ff4c046e2..6e7fc4c9d98 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-2distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-2distinct_use.swift @@ -75,7 +75,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-3distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-3distinct_use.swift index a9d72b817d1..5970a439f59 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-3distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-3distinct_use.swift @@ -96,7 +96,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( // CHECK-SAME: [[INT]] %0, diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-4distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-4distinct_use.swift index 402a57af7f1..495f6d699e6 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-4distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-4distinct_use.swift @@ -118,7 +118,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-5distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-5distinct_use.swift index d4b65536d71..b829ddc7233 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-5distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-5distinct_use.swift @@ -164,7 +164,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-clang_node-1distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-clang_node-1distinct_use.swift index 8105f233e71..a252f61bb2e 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-clang_node-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-clang_node-1distinct_use.swift @@ -36,7 +36,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-class-1argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-class-1argument-1distinct_use.swift index c4cd3202d35..0ddfea6e156 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-class-1argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-class-1argument-1distinct_use.swift @@ -52,7 +52,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceC5ValueVMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-enum-1argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-enum-1argument-1distinct_use.swift index e5d5506066c..b1dabca6395 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-enum-1argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-enum-1argument-1distinct_use.swift @@ -52,7 +52,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceO5ValueVMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-struct-1argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-struct-1argument-1distinct_use.swift index 4d19b773f96..54b2b24916c 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-struct-1argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-struct-1argument-1distinct_use.swift @@ -52,7 +52,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceV5ValueVMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-struct-2argument-constrained_extension-equal_arguments-1distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-struct-2argument-constrained_extension-equal_arguments-1distinct_use.swift index d65e92c976b..a12ce30dd63 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-struct-2argument-constrained_extension-equal_arguments-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-1argument-within-struct-2argument-constrained_extension-equal_arguments-1distinct_use.swift @@ -59,7 +59,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceVAAq_RszrlE5ValueVMa"([[INT]] %0, ptr [[TYPE_1:%[0-9]+]], ptr [[TYPE_2:%[0-9]+]]) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-0distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-0distinct_use.swift index 8465e5bbf91..99c0d68390d 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-0distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-0distinct_use.swift @@ -22,7 +22,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-1distinct_use.swift index 4b293b59fd6..db3c4768f68 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-1distinct_use.swift @@ -57,7 +57,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-2distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-2distinct_use.swift index a1aee0bcdf8..ea2fd72e1c2 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-2distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-2distinct_use.swift @@ -93,7 +93,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-3distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-3distinct_use.swift index a9c7c567a98..db89a59a48a 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-3distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-3distinct_use.swift @@ -129,7 +129,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-4distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-4distinct_use.swift index c040cdac82d..dfab83e72ff 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-4distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-4distinct_use.swift @@ -165,7 +165,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-5distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-5distinct_use.swift index 72673ebc7cd..7d389919de5 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-5distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-5distinct_use.swift @@ -257,7 +257,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1, ptr %2) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: {{%[0-9]+}} = call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-within-class-1argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-within-class-1argument-1distinct_use.swift index cf39590dc21..7ad361cb8f8 100644 --- a/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-within-class-1argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-inmodule-2argument-within-class-1argument-1distinct_use.swift @@ -60,7 +60,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define hidden swiftcc %swift.metadata_response @"$s4main9NamespaceC5ValueVMa"([[INT]] %0, ptr %1, ptr %2, ptr %3) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: entry: // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( diff --git a/test/IRGen/prespecialized-metadata/struct-public-inmodule-1argument-1distinct_use.swift b/test/IRGen/prespecialized-metadata/struct-public-inmodule-1argument-1distinct_use.swift index afdfe16a87b..d53962f3439 100644 --- a/test/IRGen/prespecialized-metadata/struct-public-inmodule-1argument-1distinct_use.swift +++ b/test/IRGen/prespecialized-metadata/struct-public-inmodule-1argument-1distinct_use.swift @@ -49,7 +49,7 @@ func doit() { } doit() -// CHECK: ; Function Attrs: noinline nounwind readnone +// CHECK: ; Function Attrs: noinline nounwind memory(none) // CHECK: define{{( protected| dllexport)?}} swiftcc %swift.metadata_response @"$s4main5ValueVMa"([[INT]] %0, ptr %1) #{{[0-9]+}} {{(section)?.*}}{ // CHECK: call swiftcc %swift.metadata_response @__swift_instantiateCanonicalPrespecializedGenericMetadata( // CHECK-SAME: [[INT]] %0, diff --git a/test/IRGen/readonly.sil b/test/IRGen/readonly.sil index 9459ad8fa01..ab8cddf61b3 100644 --- a/test/IRGen/readonly.sil +++ b/test/IRGen/readonly.sil @@ -17,7 +17,7 @@ sil @XXX_ctor : $@convention(method) (@owned XXX) -> @owned XXX // to the LLVM read only attribute, unless IRGen can prove by analyzing // the function body that this function is really read only. -// CHECK-NOT: ; Function Attrs: readonly +// CHECK-NOT: ; Function Attrs:{{.*}}memory(read) // CHECK: define{{( dllexport)?}}{{( protected)?}} swiftcc void @function_foo( sil [readonly] @function_foo : $@convention(thin) (Int) -> () { bb0(%0 : $Int): @@ -30,7 +30,7 @@ bb0(%0 : $Int): // to the LLVM read only attribute, unless IRGen can prove by analyzing // the function body that this function is really read only or read none. -// CHECK-NOT: ; Function Attrs: readonly +// CHECK-NOT: ; Function Attrs:{{.*}}memory(read) // CHECK: define{{( dllexport)?}}{{( protected)?}} swiftcc void @function_foo2( sil [readnone] @function_foo2 : $@convention(thin) (Int) -> () { bb0(%0 : $Int): @@ -41,7 +41,7 @@ bb0(%0 : $Int): // There's an @owned parameter, and destructors can call arbitrary code // -- function is not read only at LLVM level -// CHECK-NOT: ; Function Attrs: readonly +// CHECK-NOT: ; Function Attrs:{{.*}}memory(read) // CHECK: define{{( dllexport)?}}{{( protected)?}} swiftcc void @function_bar( sil [readonly] @function_bar : $@convention(thin) (@owned XXX) -> () { bb0(%0 : $XXX): @@ -52,7 +52,7 @@ bb0(%0 : $XXX): // There's an @out parameter -- function is not read only at LLVM level -// CHECK-NOT: ; Function Attrs: readonly +// CHECK-NOT: ; Function Attrs:{{.*}}memory(read) // CHECK: define{{( dllexport)?}}{{( protected)?}} swiftcc void @function_baz( sil [readonly] @function_baz : $@convention(thin) () -> (@out Any) { bb0(%0 : $*Any): diff --git a/test/IRGen/relative_protocol_witness_table.swift b/test/IRGen/relative_protocol_witness_table.swift index d32fde8dba4..1457901f94e 100644 --- a/test/IRGen/relative_protocol_witness_table.swift +++ b/test/IRGen/relative_protocol_witness_table.swift @@ -156,7 +156,7 @@ func instantiate_conditional_conformance_2nd(_ t : T) where T: Sub, T.S == T // CHECK: @"$s1A7DStructVAA20WithAssocConformanceAAWP" = hidden constant [4 x i32] // CHECK-SAME: [i32 trunc (i64 sub (i64 ptrtoint (ptr @"$s1A7DStructVAA20WithAssocConformanceAAMc" to i64), // CHECK-SAME: i64 ptrtoint (ptr @"$s1A7DStructVAA20WithAssocConformanceAAWP" to i64)) to i32), -// CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint (ptr getelementptr inbounds (i8, ptr @"associated conformance 1A7DStructVAA20WithAssocConformanceAA0C4TypeAaDP_AA8FuncOnly", i64 1) to i64), +// CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint (ptr getelementptr (i8, ptr @"associated conformance 1A7DStructVAA20WithAssocConformanceAA0C4TypeAaDP_AA8FuncOnly", i64 1) to i64), // CHECK-SAME: i64 ptrtoint (ptr getelementptr inbounds ([4 x i32], ptr @"$s1A7DStructVAA20WithAssocConformanceAAWP", i32 0, i32 1) to i64)) to i32) // CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint (ptr getelementptr inbounds (i8, ptr @"symbolic _____ 1A7AStructV", i64 1) to i64), // CHECK-SAME: i64 ptrtoint (ptr getelementptr inbounds ([4 x i32], ptr @"$s1A7DStructVAA20WithAssocConformanceAAWP", i32 0, i32 2) to i64)) to i32) @@ -167,7 +167,7 @@ func instantiate_conditional_conformance_2nd(_ t : T) where T: Sub, T.S == T // CHECK: @"$s1A7GStructVyxGAA20WithAssocConformanceAAWP" = hidden constant [4 x i32] // CHECK-SAME: [i32 trunc (i64 sub (i64 ptrtoint (ptr @"$s1A7GStructVyxGAA20WithAssocConformanceAAMc" to i64), // CHECK-SAME: i64 ptrtoint (ptr @"$s1A7GStructVyxGAA20WithAssocConformanceAAWP" to i64)) to i32), -// CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint (ptr getelementptr inbounds (i8, ptr @"associated conformance 1A7GStructVyxGAA20WithAssocConformanceAA0C4TypeAaEP_AA8FuncOnly", i64 1) to i64), +// CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint (ptr getelementptr (i8, ptr @"associated conformance 1A7GStructVyxGAA20WithAssocConformanceAA0C4TypeAaEP_AA8FuncOnly", i64 1) to i64), // CHECK-SAME: i64 ptrtoint (ptr getelementptr inbounds ([4 x i32], ptr @"$s1A7GStructVyxGAA20WithAssocConformanceAAWP", i32 0, i32 1) to i64)) to i32) // CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint (ptr getelementptr inbounds (i8, ptr @"symbolic x", i64 1) to i64), // CHECK-SAME: i64 ptrtoint (ptr getelementptr inbounds ([4 x i32], ptr @"$s1A7GStructVyxGAA20WithAssocConformanceAAWP", i32 0, i32 2) to i64)) to i32) @@ -180,7 +180,7 @@ func instantiate_conditional_conformance_2nd(_ t : T) where T: Sub, T.S == T // CHECK: @"$s1A17ConditionalStructVyxGAA20WithAssocConformanceA2A8FuncOnlyRzAA5InitPRzlWP" = hidden constant [4 x i32] // CHECK-SAME: [i32 trunc (i64 sub (i64 ptrtoint (ptr @"$s1A17ConditionalStructVyxGAA20WithAssocConformanceA2A8FuncOnlyRzAA5InitPRzlMc" to i64), // CHECK-SAME: i64 ptrtoint (ptr @"$s1A17ConditionalStructVyxGAA20WithAssocConformanceA2A8FuncOnlyRzAA5InitPRzlWP" to i64)) to i32), -// CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint (ptr getelementptr inbounds (i8, ptr @"associated conformance 1A17ConditionalStructVyxGAA20WithAssocConformanceA2A8FuncOnlyRzAA5InitPRzl0D4TypeAaEP_AaF", i64 1) to i64), +// CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint (ptr getelementptr (i8, ptr @"associated conformance 1A17ConditionalStructVyxGAA20WithAssocConformanceA2A8FuncOnlyRzAA5InitPRzl0D4TypeAaEP_AaF", i64 1) to i64), // CHECK-SAME: i64 ptrtoint (ptr getelementptr inbounds ([4 x i32], ptr @"$s1A17ConditionalStructVyxGAA20WithAssocConformanceA2A8FuncOnlyRzAA5InitPRzlWP", i32 0, i32 1) to i64)) to i32) // CHECK-SAME: i32 trunc (i64 sub (i64 ptrtoint (ptr getelementptr inbounds (i8, ptr @"symbolic x", i64 1) to i64), // CHECK-SAME: i64 ptrtoint (ptr getelementptr inbounds ([4 x i32], ptr @"$s1A17ConditionalStructVyxGAA20WithAssocConformanceA2A8FuncOnlyRzAA5InitPRzlWP", i32 0, i32 2) to i64)) to i32) diff --git a/test/IRGen/static-vtable-stubs.swift b/test/IRGen/static-vtable-stubs.swift index a1011cae93c..9fda1d73833 100644 --- a/test/IRGen/static-vtable-stubs.swift +++ b/test/IRGen/static-vtable-stubs.swift @@ -15,11 +15,14 @@ open class C { private func foo() async {} } -// CHECK: @"$s1M1CC3foo33_{{.*}}Tu" = hidden global %swift.async_func_pointer <{ {{.*}} @_swift_dead_method_stub +// CHECK: @"$s1M1CC3foo33_{{.*}}Tu" = hidden global %swift.async_func_pointer <{ {{.*}} @"$s1M1CC1i33_807E3D81CC6CDD898084F3279464DDF9LLSDySOypGvg" -// CHECK: @"$s1M1CC1i33_807E3D81CC6CDD898084F3279464DDF9LLSDySOypGvg" = hidden alias void (), ptr @_swift_dead_method_stub -// CHECK: @"$s1M1CC1i33_807E3D81CC6CDD898084F3279464DDF9LLSDySOypGvs" = hidden alias void (), ptr @_swift_dead_method_stub -// CHECK: @"$s1M1CC1i33_807E3D81CC6CDD898084F3279464DDF9LLSDySOypGvM" = hidden alias void (), ptr @_swift_dead_method_stub +// CHECK: @"$s1M1CC1i33_807E3D81CC6CDD898084F3279464DDF9LLSDySOypGvs" = hidden alias void (), ptr @"$s1M1CC1i33_807E3D81CC6CDD898084F3279464DDF9LLSDySOypGvg" +// CHECK: @"$s1M1CC1i33_807E3D81CC6CDD898084F3279464DDF9LLSDySOypGvM" = hidden alias void (), ptr @"$s1M1CC1i33_807E3D81CC6CDD898084F3279464DDF9LLSDySOypGvg" + +// CHECK: define hidden void @"$s1M1CC1i33_807E3D81CC6CDD898084F3279464DDF9LLSDySOypGvg"() +// CHECK: entry: +// CHECK: tail call void @swift_deletedMethodError() //--- B.swift final class D: C { diff --git a/test/IRGen/weak_import_deployment_target.swift b/test/IRGen/weak_import_deployment_target.swift index b906c7df538..cc28f6b3025 100644 --- a/test/IRGen/weak_import_deployment_target.swift +++ b/test/IRGen/weak_import_deployment_target.swift @@ -23,11 +23,11 @@ public func callsNew() { } // CHECK-OLD-LABEL: declare swiftcc void @"$s36weak_import_deployment_target_helper13hasDefaultArgyySiF"(i64) +// CHECK-OLD-LABEL: declare swiftcc i64 @"$s36weak_import_deployment_target_helper8functionSiyF"() // CHECK-OLD-LABEL: declare extern_weak swiftcc void @"$s36weak_import_deployment_target_helper22hasAvailableDefaultArgyySiF"(i64) // CHECK-OLD-LABEL: declare extern_weak swiftcc i64 @"$s36weak_import_deployment_target_helper17availableFunctionSiyF"() -// CHECK-OLD-LABEL: declare swiftcc i64 @"$s36weak_import_deployment_target_helper8functionSiyF"() // CHECK-NEW-LABEL: declare swiftcc void @"$s36weak_import_deployment_target_helper13hasDefaultArgyySiF"(i64) +// CHECK-NEW-LABEL: declare swiftcc i64 @"$s36weak_import_deployment_target_helper8functionSiyF"() // CHECK-NEW-LABEL: declare swiftcc void @"$s36weak_import_deployment_target_helper22hasAvailableDefaultArgyySiF"(i64) // CHECK-NEW-LABEL: declare swiftcc i64 @"$s36weak_import_deployment_target_helper17availableFunctionSiyF"() -// CHECK-NEW-LABEL: declare swiftcc i64 @"$s36weak_import_deployment_target_helper8functionSiyF"() diff --git a/test/IRGen/zombies.swift b/test/IRGen/zombies.swift index aa775722bff..892effac719 100644 --- a/test/IRGen/zombies.swift +++ b/test/IRGen/zombies.swift @@ -8,5 +8,8 @@ class C { init(i: Int) { self.i = i } } -// CHECK: @"$s7zombies1CC1i33_{{.*}}vg" = hidden {{(dllexport )?}}alias void (), ptr @_swift_dead_method_stub -// CHECK: define internal void @_swift_dead_method_stub() +// CHECK: @"$s7zombies1CC1i33_{{.*}}vs" = hidden {{(dllexport )?}}alias void (), ptr @"$s7zombies1CC1i33_45489CBEFBF369AB7AEE3A799A95D78DLLSivg" + +// CHECK: define hidden void @"$s7zombies1CC1i33_45489CBEFBF369AB7AEE3A799A95D78DLLSivg"() +// CHECK: entry: +// CHECK: tail call void @swift_deletedMethodError() diff --git a/test/Interop/Cxx/exceptions/trap-on-exception-irgen-itanium.swift b/test/Interop/Cxx/exceptions/trap-on-exception-irgen-itanium.swift index 4df2a0a3f5b..1bade29c952 100644 --- a/test/Interop/Cxx/exceptions/trap-on-exception-irgen-itanium.swift +++ b/test/Interop/Cxx/exceptions/trap-on-exception-irgen-itanium.swift @@ -335,6 +335,8 @@ public func test() { // CHECK-NEXT: unreachable // CHECK-NEXT: } +// CHECK: i32 @__gxx_personality_v0(...) + // CHECK: define {{.*}} @"$s4test0A11MethodCallss5Int32VyF"() #[[#SWIFTUWMETA]] personality // CHECK: call swiftcc i32 @"$s4test8makeCInts5Int32VyF"() // CHECK: invoke i32 @_ZNK9TestClass6methodEi @@ -465,10 +467,7 @@ public func test() { // CHECK-NOT: invoke // CHECK: } -// CHECK: i32 @__gxx_personality_v0(...) - // CHECK: attributes #[[#SWIFTMETA]] = { -// CHECK-NOT: uwtable // CHECK: attributes #[[#SWIFTUWMETA]] = { // CHECK-SAME: uwtable diff --git a/test/Interop/Cxx/operators/member-inline-irgen.swift b/test/Interop/Cxx/operators/member-inline-irgen.swift index 6dd55a70484..af442111061 100644 --- a/test/Interop/Cxx/operators/member-inline-irgen.swift +++ b/test/Interop/Cxx/operators/member-inline-irgen.swift @@ -1,22 +1,22 @@ -// RUN: %target-swift-emit-ir %s -I %S/Inputs -enable-experimental-cxx-interop -Xcc -fignore-exceptions | %FileCheck %s -// -// We should be able to support windows now. We will remove XFAIL in follow up -// XFAIL: windows +// RUN: %target-swift-emit-ir %s -I %S/Inputs -enable-experimental-cxx-interop -Xcc -fignore-exceptions | %FileCheck %s -check-prefix CHECK -check-prefix CHECK-%target-abi import MemberInline public func sub(_ lhs: inout LoadableIntWrapper, _ rhs: LoadableIntWrapper) -> LoadableIntWrapper { lhs - rhs } -// CHECK: call [[RESA:i32|i64]] [[NAMEA:@(_ZN18LoadableIntWrappermiES_|"\?\?GLoadableIntWrapper@@QEAA\?AU0@U0@@Z")]](ptr {{%[0-9]+}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(.*\) align 4}} {{%[0-9]+}}) +// CHECK-SYSV: call [[RESA:i32|i64]] [[NAMEA:@_ZN18LoadableIntWrappermiES_]](ptr {{%[0-9]+}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(.*\) align 4}} {{%[0-9]+}}) +// CHECK-WIN: call [[RESA:void]] [[NAMEA:@"\?\?GLoadableIntWrapper@@QEAA\?AU0@U0@@Z"]](ptr {{%[0-9]+}}, ptr sret(%struct.LoadableIntWrapper) {{.*}}, i32 {{%[0-9]+}}) public func call(_ wrapper: inout LoadableIntWrapper, _ arg: Int32) -> Int32 { wrapper(arg) } -// CHECK: call [[RES:i32|i64]] [[NAME:@(_ZN18LoadableIntWrapperclEi|"\?\?GLoadableIntWrapper@@QEAAHH@Z")]](ptr {{%[0-9]+}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(.*\)}}{{.*}}) +// CHECK-SYSV: call [[RES:i32|i64]] [[NAME:@(_ZN18LoadableIntWrapperclEi|"\?\?GLoadableIntWrapper@@QEAAHH@Z")]](ptr {{%[0-9]+}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(.*\)}}{{.*}}) +// CHECK-WIN: call [[RES:i32]] [[NAME:@"\?\?RLoadableIntWrapper@@QEAAHH@Z"]](ptr {{%[0-9]+}}, i32 {{%[0-9]+}}) // CHECK: define {{.*}}[[RES]] [[NAME]](ptr {{.*}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(%struct.LoadableIntWrapper\)}}{{.*}}) public func call(_ wrapper: inout AddressOnlyIntWrapper) -> Int32 { wrapper() } -// CHECK: call [[RES:i32|i64]] [[NAME:@(_ZN21AddressOnlyIntWrapperclEv|"\?\?GAddressOnlyIntWrapper@@QEAAHXZ")]](ptr {{.*}}) +// CHECK-SYSV: call [[RES:i32|i64]] [[NAME:@_ZN21AddressOnlyIntWrapperclEv]](ptr {{.*}}) +// CHECK-WIN: call [[RES:i32]] [[NAME:@"\?\?RAddressOnlyIntWrapper@@QEAAHXZ"]](ptr {{.*}}) // CHECK: define {{.*}}[[RES]] [[NAME]](ptr {{.*}}) public func index(_ arr: inout ReadOnlyIntArray, _ arg: Int32) -> Int32 { arr[arg] } @@ -39,7 +39,8 @@ public func index(_ arr: inout ReadWriteIntArray, _ arg: Int32, _ val: Int32) { public func index(_ arr: inout NonTrivialIntArrayByVal, _ arg: Int32) -> Int32 { arr[arg] } -// CHECK: call [[RES:i32|i64]] [[NAME:@(_ZNK23NonTrivialIntArrayByValixEi|"\?\?ANonTrivialIntArrayByVal@@QEBAAEBHH@Z")]](ptr {{.*}}, {{i32|i64}}{{.*}}) +// CHECK-SYSV: call [[RES:i32|i64]] [[NAME:@_ZNK23NonTrivialIntArrayByValixEi]](ptr {{.*}}, {{i32|i64}}{{.*}}) +// CHECK-WIN: call [[RES:i32]] [[NAME:@"\?\?ANonTrivialIntArrayByVal@@QEBAHH@Z"]](ptr {{.*}}, i32 {{.*}}) // CHECK: define {{.*}}[[RES:i32|i64]] [[NAME]](ptr {{.*}}, {{i32|\[1 x i32\]|i64|%struct.NonTrivialIntArrayByVal\* byval\(%struct.NonTrivialIntArrayByVal\)}}{{.*}}) // CHECK: [[THIS:%.*]] = load ptr, ptr diff --git a/test/Interop/Cxx/operators/member-out-of-line-irgen.swift b/test/Interop/Cxx/operators/member-out-of-line-irgen.swift index 84ca875ea58..a283f348f78 100644 --- a/test/Interop/Cxx/operators/member-out-of-line-irgen.swift +++ b/test/Interop/Cxx/operators/member-out-of-line-irgen.swift @@ -1,11 +1,11 @@ -// RUN: %target-swift-emit-ir %s -I %S/Inputs -enable-experimental-cxx-interop -Xcc -fignore-exceptions | %FileCheck %s -// -// We should be able to support windows now. We will remove XFAIL in follow up -// XFAIL: windows +// RUN: %target-swift-emit-ir %s -I %S/Inputs -enable-experimental-cxx-interop -Xcc -fignore-exceptions | %FileCheck %s -check-prefix CHECK-%target-abi import MemberOutOfLine public func add(_ lhs: inout LoadableIntWrapper, _ rhs: LoadableIntWrapper) -> LoadableIntWrapper { lhs + rhs } -// CHECK: call {{i32|i64}} [[NAME:@_ZNK18LoadableIntWrapperplES_]](ptr %{{[0-9]+}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(.*\)}}{{.*}}) -// CHECK: declare {{.*}}{{i32|i64}} [[NAME]](ptr {{.*}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* .*byval\(%struct.LoadableIntWrapper\)}}{{.*}}) +// CHECK-SYSV: call {{i32|i64}} [[NAME:@_ZNK18LoadableIntWrapperplES_]](ptr %{{[0-9]+}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* byval\(.*\)}}{{.*}}) +// CHECK-SYSV: declare {{.*}}{{i32|i64}} [[NAME]](ptr {{.*}}, {{i32|\[1 x i32\]|i64|%struct.LoadableIntWrapper\* .*byval\(%struct.LoadableIntWrapper\)}}{{.*}}) + +// CHECK-WIN: call void [[NAME:@"\?\?HLoadableIntWrapper@@QEBA\?AU0@U0@@Z"]](ptr %{{[0-9]+}}, ptr sret(%struct.LoadableIntWrapper) {{.*}}, i32 %{{[0-9]+}}) +// CHECK-WIN: declare dso_local void [[NAME]](ptr {{.*}}, ptr sret(%struct.LoadableIntWrapper) {{.*}}, i32) diff --git a/test/Interop/Cxx/static/constexpr-static-member-var-errors.swift b/test/Interop/Cxx/static/constexpr-static-member-var-errors.swift index 644e86cd0e8..e7a94b8611b 100644 --- a/test/Interop/Cxx/static/constexpr-static-member-var-errors.swift +++ b/test/Interop/Cxx/static/constexpr-static-member-var-errors.swift @@ -4,7 +4,7 @@ // invalid decl. // Windows doesn't fail at all here which seems ok (and probably should be the case for other platforms too). -// XFAIL: windows +// XFAIL: OS=windows-msvc // CHECK: error: type 'int' cannot be used prior to '::' because it has no members // CHECK: {{note: in instantiation of template class 'GetTypeValue' requested here|note: in instantiation of static data member 'GetTypeValue::value' requested here}} diff --git a/test/Interop/Cxx/stdlib/foundation-and-std-module.swift b/test/Interop/Cxx/stdlib/foundation-and-std-module.swift index 8dcc93b45c7..7228558a866 100644 --- a/test/Interop/Cxx/stdlib/foundation-and-std-module.swift +++ b/test/Interop/Cxx/stdlib/foundation-and-std-module.swift @@ -1,14 +1,15 @@ // RUN: %empty-directory(%t) // RUN: %target-swift-frontend %s -c -enable-experimental-cxx-interop -Xcc -std=c++14 -Xcc -fmodules-cache-path=%t // RUN: %target-swift-frontend %s -c -enable-experimental-cxx-interop -Xcc -std=c++17 -Xcc -fmodules-cache-path=%t -// RUN: %target-swift-frontend %s -c -enable-experimental-cxx-interop -Xcc -std=c++20 -Xcc -fmodules-cache-path=%t +// RUN: %target-swift-frontend %s -c -enable-experimental-cxx-interop -Xcc -std=c++20 -Xcc -fmodules-cache-path=%t -Xcc -D_LIBCPP_DISABLE_AVAILABILITY // RUN: find %t | %FileCheck %s // RUN: %empty-directory(%t) // RUN: %target-swift-frontend %s -c -enable-experimental-cxx-interop -Xcc -std=c++17 -Xcc -fmodules-cache-path=%t -DADD_CXXSTDLIB -// RUN: %target-swift-frontend %s -c -enable-experimental-cxx-interop -Xcc -std=c++20 -Xcc -fmodules-cache-path=%t -DADD_CXXSTDLIB +// RUN: %target-swift-frontend %s -c -enable-experimental-cxx-interop -Xcc -std=c++20 -Xcc -fmodules-cache-path=%t -DADD_CXXSTDLIB -Xcc -D_LIBCPP_DISABLE_AVAILABILITY +// FIXME: remove _LIBCPP_DISABLE_AVAILABILITY above (https://github.com/apple/swift/issues/67841) // REQUIRES: OS=macosx || OS=linux-gnu diff --git a/test/Interop/CxxToSwiftToCxx/bridge-cxx-struct-back-to-cxx.swift b/test/Interop/CxxToSwiftToCxx/bridge-cxx-struct-back-to-cxx.swift index fb5f5206793..6270857f622 100644 --- a/test/Interop/CxxToSwiftToCxx/bridge-cxx-struct-back-to-cxx.swift +++ b/test/Interop/CxxToSwiftToCxx/bridge-cxx-struct-back-to-cxx.swift @@ -18,7 +18,8 @@ // Check that the generated header can be // built with Clang modules enabled in C++. -// RUN: %target-interop-build-clangxx -fsyntax-only -x c++-header %t/full-cxx-swift-cxx-bridging.h -std=gnu++20 -c -fmodules -fcxx-modules -I %t +// RUN: %target-interop-build-clangxx -fsyntax-only -x c++-header %t/full-cxx-swift-cxx-bridging.h -std=gnu++20 -c -fmodules -fcxx-modules -I %t -D_LIBCPP_DISABLE_AVAILABILITY +// FIXME: remove _LIBCPP_DISABLE_AVAILABILITY above (https://github.com/apple/swift/issues/67841) // XFAIL: OS=linux-android, OS=linux-androideabi diff --git a/test/Interop/CxxToSwiftToCxx/bridge-cxx-struct-back-to-objcxx.swift b/test/Interop/CxxToSwiftToCxx/bridge-cxx-struct-back-to-objcxx.swift index 09893eb82ba..1e5f62f748c 100644 --- a/test/Interop/CxxToSwiftToCxx/bridge-cxx-struct-back-to-objcxx.swift +++ b/test/Interop/CxxToSwiftToCxx/bridge-cxx-struct-back-to-objcxx.swift @@ -10,4 +10,5 @@ // REQUIRES: objc_interop -// RUN: %target-interop-build-clangxx -fsyntax-only -x objective-c++-header %t/full-cxx-swift-cxx-bridging.h -std=gnu++20 -c -fmodules -fcxx-modules -I %t +// RUN: %target-interop-build-clangxx -fsyntax-only -x objective-c++-header %t/full-cxx-swift-cxx-bridging.h -std=gnu++20 -c -fmodules -fcxx-modules -I %t -D_LIBCPP_DISABLE_AVAILABILITY +// FIXME: remove _LIBCPP_DISABLE_AVAILABILITY above (https://github.com/apple/swift/issues/67841) diff --git a/test/LLVMPasses/allocation-deletion.ll b/test/LLVMPasses/allocation-deletion.ll index 18524ae741d..81d9b181dc5 100644 --- a/test/LLVMPasses/allocation-deletion.ll +++ b/test/LLVMPasses/allocation-deletion.ll @@ -1,27 +1,27 @@ -; RUN: %swift-llvm-opt -swift-llvm-arc-optimize %s | %FileCheck %s +; RUN: %swift-llvm-opt -passes=swift-llvm-arc-optimize %s | %FileCheck %s target datalayout = "e-p:64:64:64-S128-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f16:16:16-f32:32:32-f64:64:64-f128:128:128-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64" target triple = "x86_64-apple-macosx10.9" -%swift.refcounted = type { %swift.heapmetadata*, i64 } -%swift.heapmetadata = type { i64 (%swift.refcounted*)*, i64 (%swift.refcounted*)* } +%swift.refcounted = type { ptr, i64 } +%swift.heapmetadata = type { ptr, ptr } -declare %swift.refcounted* @swift_allocObject(%swift.heapmetadata* , i64, i64) nounwind -declare void @swift_release(%swift.refcounted* nocapture) -declare void @swift_retain(%swift.refcounted* ) nounwind -declare { i64, i64, i64 } @swift_retainAndReturnThree(%swift.refcounted* , i64, i64 , i64 ) +declare ptr @swift_allocObject(ptr , i64, i64) nounwind +declare void @swift_release(ptr nocapture) +declare void @swift_retain(ptr ) nounwind +declare { i64, i64, i64 } @swift_retainAndReturnThree(ptr , i64, i64 , i64 ) ; rdar://11542743 define i64 @max_test(i64 %x) nounwind { entry: - %0 = tail call noalias %swift.refcounted* @swift_allocObject(%swift.heapmetadata* null, i64 24, i64 8) nounwind - tail call void @swift_retain(%swift.refcounted* %0) nounwind - tail call void @swift_release(%swift.refcounted* %0) nounwind + %0 = tail call noalias ptr @swift_allocObject(ptr null, i64 24, i64 8) nounwind + tail call void @swift_retain(ptr %0) nounwind + tail call void @swift_release(ptr %0) nounwind %1 = icmp sgt i64 %x, 0 %x.y.i = select i1 %1, i64 %x, i64 0 - tail call void @swift_retain(%swift.refcounted* %0) nounwind - tail call void @swift_release(%swift.refcounted* %0) nounwind - tail call void @swift_release(%swift.refcounted* %0) nounwind + tail call void @swift_retain(ptr %0) nounwind + tail call void @swift_release(ptr %0) nounwind + tail call void @swift_release(ptr %0) nounwind ret i64 %x.y.i } ; CHECK: @max_test @@ -35,20 +35,19 @@ entry: ; trivial_alloc_eliminate1 - Show that we can eliminate an allocation with a ; trivial destructor. -@trivial_dtor_metadata = internal constant %swift.heapmetadata { i64 (%swift.refcounted*)* @trivial_dtor, i64 (%swift.refcounted*)* null } -define internal i64 @trivial_dtor(%swift.refcounted* nocapture) nounwind readonly { +@trivial_dtor_metadata = internal constant %swift.heapmetadata { ptr @trivial_dtor, ptr null } +define internal i64 @trivial_dtor(ptr nocapture) nounwind readonly { entry: - %1 = getelementptr inbounds %swift.refcounted, %swift.refcounted* %0, i64 1 - %2 = bitcast %swift.refcounted* %1 to i64* - %length = load i64, i64* %2, align 8 - %3 = shl i64 %length, 3 - %4 = add i64 %3, 24 - ret i64 %4 + %1 = getelementptr inbounds %swift.refcounted, ptr %0, i64 1 + %length = load i64, ptr %1, align 8 + %2 = shl i64 %length, 3 + %3 = add i64 %2, 24 + ret i64 %3 } define void @trivial_alloc_eliminate1(i64 %x) nounwind { entry: - %0 = tail call noalias %swift.refcounted* @swift_allocObject(%swift.heapmetadata* @trivial_dtor_metadata, i64 24, i64 8) nounwind - tail call void @swift_release(%swift.refcounted* %0) nounwind + %0 = tail call noalias ptr @swift_allocObject(ptr @trivial_dtor_metadata, i64 24, i64 8) nounwind + tail call void @swift_release(ptr %0) nounwind ret void } ; CHECK: @trivial_alloc_eliminate1 @@ -59,18 +58,18 @@ entry: ; trivial_alloc_eliminate2 - Show that we can eliminate an allocation with a ; destructor that does a retain on the 'self' object. -@trivial_dtor_metadata2 = internal constant %swift.heapmetadata { i64 (%swift.refcounted*)* @trivial_dtor2, i64 (%swift.refcounted*)* null } -define internal i64 @trivial_dtor2(%swift.refcounted* nocapture %this) nounwind readonly { +@trivial_dtor_metadata2 = internal constant %swift.heapmetadata { ptr @trivial_dtor2, ptr null } +define internal i64 @trivial_dtor2(ptr nocapture %this) nounwind readonly { entry: - %0 = getelementptr inbounds %swift.refcounted, %swift.refcounted* %this, i64 1, i32 0 - store %swift.heapmetadata* inttoptr (i64 4 to %swift.heapmetadata*), %swift.heapmetadata** %0, align 8 - tail call void @swift_retain(%swift.refcounted* %this) + %0 = getelementptr inbounds %swift.refcounted, ptr %this, i64 1, i32 0 + store ptr inttoptr (i64 4 to ptr), ptr %0, align 8 + tail call void @swift_retain(ptr %this) ret i64 48 } define void @trivial_alloc_eliminate2(i64 %x) nounwind { entry: - %0 = tail call noalias %swift.refcounted* @swift_allocObject(%swift.heapmetadata* @trivial_dtor_metadata2, i64 24, i64 8) nounwind - tail call void @swift_release(%swift.refcounted* %0) nounwind + %0 = tail call noalias ptr @swift_allocObject(ptr @trivial_dtor_metadata2, i64 24, i64 8) nounwind + tail call void @swift_release(ptr %0) nounwind ret void } ; CHECK: @trivial_alloc_eliminate2 @@ -83,8 +82,8 @@ entry: @external_dtor_metadata = external global %swift.heapmetadata, align 8 define void @external_dtor_alloc_eliminate() nounwind { entry: - %0 = tail call noalias %swift.refcounted* @swift_allocObject(%swift.heapmetadata* nonnull @external_dtor_metadata, i64 24, i64 8) nounwind - tail call void @swift_release(%swift.refcounted* %0) nounwind + %0 = tail call noalias ptr @swift_allocObject(ptr nonnull @external_dtor_metadata, i64 24, i64 8) nounwind + tail call void @swift_release(ptr %0) nounwind ret void } diff --git a/test/LLVMPasses/basic.ll b/test/LLVMPasses/basic.ll index b144a6443b3..be8b54b3e16 100644 --- a/test/LLVMPasses/basic.ll +++ b/test/LLVMPasses/basic.ll @@ -1,48 +1,46 @@ -; RUN: %swift-llvm-opt -swift-llvm-arc-optimize %s | %FileCheck %s +; RUN: %swift-llvm-opt -passes=swift-llvm-arc-optimize %s | %FileCheck %s ; Use this testfile to check if the `swift-frontend -swift-dependency-tool` option works. -; RUN: %swift_frontend_plain -swift-llvm-opt -swift-llvm-arc-optimize %s | %FileCheck %s +; RUN: %swift_frontend_plain -swift-llvm-opt -passes=swift-llvm-arc-optimize %s | %FileCheck %s target datalayout = "e-p:64:64:64-S128-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f16:16:16-f32:32:32-f64:64:64-f128:128:128-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64" target triple = "x86_64-apple-macosx10.9" -%swift.refcounted = type { %swift.heapmetadata*, i64 } -%swift.heapmetadata = type { i64 (%swift.refcounted*)*, i64 (%swift.refcounted*)* } +%swift.refcounted = type { ptr, i64 } +%swift.heapmetadata = type { ptr, ptr } %objc_object = type opaque %swift.bridge = type opaque -declare %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* returned) -declare void @swift_unknownObjectRelease(%swift.refcounted*) -declare i8* @llvm.objc.retain(i8*) -declare void @llvm.objc.release(i8*) -declare %swift.refcounted* @swift_allocObject(%swift.heapmetadata* , i64, i64) nounwind -declare void @swift_release(%swift.refcounted* nocapture) -declare %swift.refcounted* @swift_retain(%swift.refcounted* returned) nounwind -declare %swift.bridge* @swift_bridgeObjectRetain(%swift.bridge*) -declare void @swift_bridgeObjectRelease(%swift.bridge*) -declare %swift.refcounted* @swift_retainUnowned(%swift.refcounted* returned) +declare ptr @swift_unknownObjectRetain(ptr returned) +declare void @swift_unknownObjectRelease(ptr) +declare ptr @llvm.objc.retain(ptr) +declare void @llvm.objc.release(ptr) +declare ptr @swift_allocObject(ptr , i64, i64) nounwind +declare void @swift_release(ptr nocapture) +declare ptr @swift_retain(ptr returned) nounwind +declare ptr @swift_bridgeObjectRetain(ptr) +declare void @swift_bridgeObjectRelease(ptr) +declare ptr @swift_retainUnowned(ptr returned) -declare void @user(%swift.refcounted *) nounwind -declare void @user_objc(i8*) nounwind +declare void @user(ptr) nounwind +declare void @user_objc(ptr) nounwind declare void @unknown_func() -define private void @__swift_fixLifetime(%swift.refcounted*) noinline nounwind { +define private void @__swift_fixLifetime(ptr) noinline nounwind { entry: ret void } ; CHECK-LABEL: @trivial_objc_canonicalization( ; CHECK-NEXT: entry: -; CHECK-NEXT: [[RET0:%.+]] = bitcast i8* %O to i8* -; CHECK-NEXT: [[RET1:%.+]] = tail call i8* @llvm.objc.retain(i8* [[RET0:%.+]]) -; CHECK-NEXT: call void @user_objc(i8* [[RET0:%.+]]) +; CHECK-NEXT: [[RET1:%.+]] = tail call ptr @llvm.objc.retain(ptr [[RET0:%.+]]) +; CHECK-NEXT: call void @user_objc(ptr [[RET0:%.+]]) ; CHECK-NEXT: ret void -define void @trivial_objc_canonicalization(i8* %O) { +define void @trivial_objc_canonicalization(ptr %O) { entry: - %0 = bitcast i8* %O to i8* - %1 = tail call i8* @llvm.objc.retain(i8* %0) - call void @user_objc(i8* %1) nounwind + %0 = tail call ptr @llvm.objc.retain(ptr %O) + call void @user_objc(ptr %0) nounwind ret void } @@ -51,40 +49,34 @@ entry: ; CHECK-NEXT: call void @user ; CHECK-NEXT: ret void -define void @trivial_retain_release(%swift.refcounted* %P, i8* %O, %swift.bridge * %B) { +define void @trivial_retain_release(ptr %P, ptr %O, ptr %B) { entry: - tail call %swift.refcounted* @swift_retain(%swift.refcounted* %P) - tail call void @swift_release(%swift.refcounted* %P) nounwind - tail call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %P) - tail call void @swift_unknownObjectRelease(%swift.refcounted* %P) - tail call i8* @llvm.objc.retain(i8* %O) - tail call void @llvm.objc.release(i8* %O) - %v = tail call %swift.bridge* @swift_bridgeObjectRetain(%swift.bridge* %B) - tail call void @swift_bridgeObjectRelease(%swift.bridge* %v) - call void @user(%swift.refcounted* %P) nounwind + tail call ptr @swift_retain(ptr %P) + tail call void @swift_release(ptr %P) nounwind + tail call ptr @swift_unknownObjectRetain(ptr %P) + tail call void @swift_unknownObjectRelease(ptr %P) + tail call ptr @llvm.objc.retain(ptr %O) + tail call void @llvm.objc.release(ptr %O) + %v = tail call ptr @swift_bridgeObjectRetain(ptr %B) + tail call void @swift_bridgeObjectRelease(ptr %v) + call void @user(ptr %P) nounwind ret void } ; CHECK-LABEL: @trivial_retain_release_with_rcidentity( ; CHECK-NEXT: entry: -; CHECK-NEXT: [[RET0:%.+]] = bitcast %swift.refcounted* %P to %swift.refcounted* -; CHECK-NEXT: [[RET1:%.+]] = bitcast %swift.refcounted* %P to %swift.refcounted* -; CHECK-NEXT: [[RET2:%.+]] = bitcast i8* %O to i8* ; CHECK-NEXT: call void @user ; CHECK-NEXT: ret void -define void @trivial_retain_release_with_rcidentity(%swift.refcounted* %P, i8* %O, %swift.bridge * %B) { +define void @trivial_retain_release_with_rcidentity(ptr %P, ptr %O, ptr %B) { entry: - tail call %swift.refcounted* @swift_retain(%swift.refcounted* %P) - %1 = bitcast %swift.refcounted* %P to %swift.refcounted* - tail call void @swift_release(%swift.refcounted* %1) nounwind - tail call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %P) - %3 = bitcast %swift.refcounted* %P to %swift.refcounted* - tail call void @swift_unknownObjectRelease(%swift.refcounted* %3) - tail call i8* @llvm.objc.retain(i8* %O) - %5 = bitcast i8* %O to i8* - tail call void @llvm.objc.release(i8* %5) - call void @user(%swift.refcounted* %P) nounwind + tail call ptr @swift_retain(ptr %P) + tail call void @swift_release(ptr %P) nounwind + tail call ptr @swift_unknownObjectRetain(ptr %P) + tail call void @swift_unknownObjectRelease(ptr %P) + tail call ptr @llvm.objc.retain(ptr %O) + tail call void @llvm.objc.release(ptr %O) + call void @user(ptr %P) nounwind ret void } @@ -92,16 +84,14 @@ entry: ; release an object. Release motion can't zap this. ; CHECK-LABEL: @retain_motion1( -; CHECK-NEXT: bitcast ; CHECK-NEXT: store i32 ; CHECK-NEXT: ret void -define void @retain_motion1(%swift.refcounted* %A) { - tail call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - %B = bitcast %swift.refcounted* %A to i32* - store i32 42, i32* %B - tail call void @swift_release(%swift.refcounted* %A) nounwind +define void @retain_motion1(ptr %A) { + tail call ptr @swift_retain(ptr %A) + store i32 42, ptr %A + tail call void @swift_release(ptr %A) nounwind ret void } @@ -113,8 +103,8 @@ define void @retain_motion1(%swift.refcounted* %A) { define void @objc_retain_release_null() { entry: - tail call void @llvm.objc.release(i8* null) nounwind - tail call i8* @llvm.objc.retain(i8* null) + tail call void @llvm.objc.release(ptr null) nounwind + tail call ptr @llvm.objc.retain(ptr null) ret void } @@ -124,8 +114,8 @@ entry: define void @swiftunknown_retain_release_null() { entry: - tail call void @swift_unknownObjectRelease(%swift.refcounted* null) - tail call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* null) nounwind + tail call void @swift_unknownObjectRelease(ptr null) + tail call ptr @swift_unknownObjectRetain(ptr null) nounwind ret void } @@ -135,10 +125,10 @@ entry: ; CHECK-NEXT: store i32 42 ; CHECK-NEXT: ret void -define void @objc_retain_release_opt(i8* %P, i32* %IP) { - tail call i8* @llvm.objc.retain(i8* %P) nounwind - store i32 42, i32* %IP - tail call void @llvm.objc.release(i8* %P) nounwind +define void @objc_retain_release_opt(ptr %P, ptr %IP) { + tail call ptr @llvm.objc.retain(ptr %P) nounwind + store i32 42, ptr %IP + tail call void @llvm.objc.release(ptr %P) nounwind ret void } @@ -146,11 +136,11 @@ define void @objc_retain_release_opt(i8* %P, i32* %IP) { ; CHECK: swift_retain ; CHECK: swift_fixLifetime ; CHECK: swift_release -define void @swift_fixLifetimeTest(%swift.refcounted* %A) { - tail call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) nounwind - call void @__swift_fixLifetime(%swift.refcounted* %A) - tail call void @swift_release(%swift.refcounted* %A) nounwind +define void @swift_fixLifetimeTest(ptr %A) { + tail call ptr @swift_retain(ptr %A) + call void @user(ptr %A) nounwind + call void @__swift_fixLifetime(ptr %A) + tail call void @swift_release(ptr %A) nounwind ret void } @@ -159,10 +149,10 @@ define void @swift_fixLifetimeTest(%swift.refcounted* %A) { ; CHECK: swift_unknownObjectRetain ; CHECK-NOT: swift_release ; CHECK: ret -define void @move_retain_across_unknown_retain(%swift.refcounted* %A, %swift.refcounted* %B) { - tail call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - tail call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %B) - tail call void @swift_release(%swift.refcounted* %A) nounwind +define void @move_retain_across_unknown_retain(ptr %A, ptr %B) { + tail call ptr @swift_retain(ptr %A) + tail call ptr @swift_unknownObjectRetain(ptr %B) + tail call void @swift_release(ptr %A) nounwind ret void } @@ -171,10 +161,10 @@ define void @move_retain_across_unknown_retain(%swift.refcounted* %A, %swift.ref ; CHECK: llvm.objc.retain ; CHECK-NOT: swift_release ; CHECK: ret -define void @move_retain_across_objc_retain(%swift.refcounted* %A, i8* %B) { - tail call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - tail call i8* @llvm.objc.retain(i8* %B) - tail call void @swift_release(%swift.refcounted* %A) nounwind +define void @move_retain_across_objc_retain(ptr %A, ptr %B) { + tail call ptr @swift_retain(ptr %A) + tail call ptr @llvm.objc.retain(ptr %B) + tail call void @swift_release(ptr %A) nounwind ret void } @@ -182,157 +172,149 @@ define void @move_retain_across_objc_retain(%swift.refcounted* %A, i8* %B) { ; CHECK-NOT: swift_retain ; CHECK-NOT: swift_release ; CHECK: ret -define i32 @move_retain_across_load(%swift.refcounted* %A, i32* %ptr) { - tail call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - %val = load i32, i32* %ptr - tail call void @swift_release(%swift.refcounted* %A) nounwind +define i32 @move_retain_across_load(ptr %A, ptr %ptr) { + tail call ptr @swift_retain(ptr %A) + %val = load i32, ptr %ptr + tail call void @swift_release(ptr %A) nounwind ret i32 %val } ; CHECK-LABEL: @move_retain_but_not_release_across_objc_fix_lifetime ; CHECK: call void @__swift_fixLifetime -; CHECK-NEXT: tail call %swift.refcounted* @swift_retain +; CHECK-NEXT: tail call ptr @swift_retain ; CHECK-NEXT: call void @user ; CHECK-NEXT: call void @__swift_fixLifetime ; CHECK-NEXT: call void @swift_release ; CHECK-NEXT: ret -define void @move_retain_but_not_release_across_objc_fix_lifetime(%swift.refcounted* %A) { - tail call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @__swift_fixLifetime(%swift.refcounted* %A) nounwind - call void @user(%swift.refcounted* %A) nounwind - call void @__swift_fixLifetime(%swift.refcounted* %A) nounwind - tail call void @swift_release(%swift.refcounted* %A) nounwind +define void @move_retain_but_not_release_across_objc_fix_lifetime(ptr %A) { + tail call ptr @swift_retain(ptr %A) + call void @__swift_fixLifetime(ptr %A) nounwind + call void @user(ptr %A) nounwind + call void @__swift_fixLifetime(ptr %A) nounwind + tail call void @swift_release(ptr %A) nounwind ret void } ; CHECK-LABEL: @optimize_retain_unowned -; CHECK-NEXT: bitcast ; CHECK-NEXT: load ; CHECK-NEXT: add ; CHECK-NEXT: load ; CHECK-NEXT: call void @swift_checkUnowned ; CHECK-NEXT: ret -define void @optimize_retain_unowned(%swift.refcounted* %A) { - tail call %swift.refcounted* @swift_retainUnowned(%swift.refcounted* %A) - %value = bitcast %swift.refcounted* %A to i64* +define void @optimize_retain_unowned(ptr %A) { + tail call ptr @swift_retainUnowned(ptr %A) ; loads from the %A and speculatively executable instructions - %L1 = load i64, i64* %value, align 8 + %L1 = load i64, ptr %A, align 8 %R1 = add i64 %L1, 1 - %L2 = load i64, i64* %value, align 8 + %L2 = load i64, ptr %A, align 8 - tail call void @swift_release(%swift.refcounted* %A) + tail call void @swift_release(ptr %A) ret void } ; CHECK-LABEL: @dont_optimize_retain_unowned -; CHECK-NEXT: call %swift.refcounted* @swift_retainUnowned -; CHECK-NEXT: bitcast +; CHECK-NEXT: call ptr @swift_retainUnowned ; CHECK-NEXT: load ; CHECK-NEXT: load ; CHECK-NEXT: call void @swift_release ; CHECK-NEXT: ret -define void @dont_optimize_retain_unowned(%swift.refcounted* %A) { - tail call %swift.refcounted* @swift_retainUnowned(%swift.refcounted* %A) - %value = bitcast %swift.refcounted* %A to i64** +define void @dont_optimize_retain_unowned(ptr %A) { + tail call ptr @swift_retainUnowned(ptr %A) - %L1 = load i64*, i64** %value, align 8 + %L1 = load ptr, ptr %A, align 8 ; Use of a potential garbage address from a load of %A. - %L2 = load i64, i64* %L1, align 8 + %L2 = load i64, ptr %L1, align 8 - tail call void @swift_release(%swift.refcounted* %A) + tail call void @swift_release(ptr %A) ret void } ; CHECK-LABEL: @dont_optimize_retain_unowned2 -; CHECK-NEXT: call %swift.refcounted* @swift_retainUnowned +; CHECK-NEXT: call ptr @swift_retainUnowned ; CHECK-NEXT: store ; CHECK-NEXT: call void @swift_release ; CHECK-NEXT: ret -define void @dont_optimize_retain_unowned2(%swift.refcounted* %A, i32* %B) { - tail call %swift.refcounted* @swift_retainUnowned(%swift.refcounted* %A) +define void @dont_optimize_retain_unowned2(ptr %A, ptr %B) { + tail call ptr @swift_retainUnowned(ptr %A) ; store to an unknown address - store i32 42, i32* %B + store i32 42, ptr %B - tail call void @swift_release(%swift.refcounted* %A) + tail call void @swift_release(ptr %A) ret void } ; CHECK-LABEL: @dont_optimize_retain_unowned3 -; CHECK-NEXT: call %swift.refcounted* @swift_retainUnowned +; CHECK-NEXT: call ptr @swift_retainUnowned ; CHECK-NEXT: call void @unknown_func ; CHECK-NEXT: call void @swift_release ; CHECK-NEXT: ret -define void @dont_optimize_retain_unowned3(%swift.refcounted* %A) { - tail call %swift.refcounted* @swift_retainUnowned(%swift.refcounted* %A) +define void @dont_optimize_retain_unowned3(ptr %A) { + tail call ptr @swift_retainUnowned(ptr %A) ; call of an unknown function call void @unknown_func() - tail call void @swift_release(%swift.refcounted* %A) + tail call void @swift_release(ptr %A) ret void } ; CHECK-LABEL: @dont_optimize_retain_unowned4 -; CHECK-NEXT: call %swift.refcounted* @swift_retainUnowned -; CHECK-NEXT: call %swift.refcounted* @swift_retain +; CHECK-NEXT: call ptr @swift_retainUnowned +; CHECK-NEXT: call ptr @swift_retain ; CHECK-NEXT: call void @swift_release ; CHECK-NEXT: ret -define void @dont_optimize_retain_unowned4(%swift.refcounted* %A, %swift.refcounted* %B) { - tail call %swift.refcounted* @swift_retainUnowned(%swift.refcounted* %A) +define void @dont_optimize_retain_unowned4(ptr %A, ptr %B) { + tail call ptr @swift_retainUnowned(ptr %A) ; retain of an unknown reference (%B could be equal to %A) - tail call %swift.refcounted* @swift_retain(%swift.refcounted* %B) + tail call ptr @swift_retain(ptr %B) - tail call void @swift_release(%swift.refcounted* %A) + tail call void @swift_release(ptr %A) ret void } ; CHECK-LABEL: @remove_redundant_check_unowned -; CHECK-NEXT: bitcast ; CHECK-NEXT: load ; CHECK-NEXT: call void @swift_checkUnowned ; CHECK-NEXT: load ; CHECK-NEXT: store ; CHECK-NEXT: load ; CHECK-NEXT: ret -define void @remove_redundant_check_unowned(%swift.refcounted* %A, %swift.refcounted* %B, i64* %C) { - tail call %swift.refcounted* @swift_retainUnowned(%swift.refcounted* %A) - %addr = bitcast %swift.refcounted* %A to i64* - %L1 = load i64, i64* %addr, align 8 - tail call void @swift_release(%swift.refcounted* %A) +define void @remove_redundant_check_unowned(ptr %A, ptr %B, ptr %C) { + tail call ptr @swift_retainUnowned(ptr %A) + %L1 = load i64, ptr %A, align 8 + tail call void @swift_release(ptr %A) ; Instructions which cannot do a release. - %L2 = load i64, i64* %C, align 8 - store i64 42, i64* %C + %L2 = load i64, ptr %C, align 8 + store i64 42, ptr %C - tail call %swift.refcounted* @swift_retainUnowned(%swift.refcounted* %A) - %L3 = load i64, i64* %addr, align 8 - tail call void @swift_release(%swift.refcounted* %A) + tail call ptr @swift_retainUnowned(ptr %A) + %L3 = load i64, ptr %A, align 8 + tail call void @swift_release(ptr %A) ret void } ; CHECK-LABEL: @dont_remove_redundant_check_unowned -; CHECK-NEXT: bitcast ; CHECK-NEXT: load ; CHECK-NEXT: call void @swift_checkUnowned ; CHECK-NEXT: call void @unknown_func ; CHECK-NEXT: load ; CHECK-NEXT: call void @swift_checkUnowned ; CHECK-NEXT: ret -define void @dont_remove_redundant_check_unowned(%swift.refcounted* %A, %swift.refcounted* %B, i64* %C) { - tail call %swift.refcounted* @swift_retainUnowned(%swift.refcounted* %A) - %addr = bitcast %swift.refcounted* %A to i64* - %L1 = load i64, i64* %addr, align 8 - tail call void @swift_release(%swift.refcounted* %A) +define void @dont_remove_redundant_check_unowned(ptr %A, ptr %B, ptr %C) { + tail call ptr @swift_retainUnowned(ptr %A) + %L1 = load i64, ptr %A, align 8 + tail call void @swift_release(ptr %A) ; Could do a release of %A call void @unknown_func() - tail call %swift.refcounted* @swift_retainUnowned(%swift.refcounted* %A) - %L3 = load i64, i64* %addr, align 8 - tail call void @swift_release(%swift.refcounted* %A) + tail call ptr @swift_retainUnowned(ptr %A) + %L3 = load i64, ptr %A, align 8 + tail call void @swift_release(ptr %A) ret void } @@ -341,10 +323,10 @@ define void @dont_remove_redundant_check_unowned(%swift.refcounted* %A, %swift.r ; CHECK-NEXT: swift_retain ; CHECK-NEXT: swift_retain ; CHECK-NEXT: ret -define void @unknown_retain_promotion(%swift.refcounted* %A) { - tail call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) - tail call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) - tail call %swift.refcounted* @swift_retain(%swift.refcounted* %A) +define void @unknown_retain_promotion(ptr %A) { + tail call ptr @swift_unknownObjectRetain(ptr %A) + tail call ptr @swift_unknownObjectRetain(ptr %A) + tail call ptr @swift_retain(ptr %A) ret void } @@ -353,10 +335,10 @@ define void @unknown_retain_promotion(%swift.refcounted* %A) { ; CHECK-NEXT: swift_release ; CHECK-NEXT: swift_release ; CHECK-NEXT: ret -define void @unknown_release_promotion(%swift.refcounted* %A) { - tail call void @swift_unknownObjectRelease(%swift.refcounted* %A) - tail call void @swift_unknownObjectRelease(%swift.refcounted* %A) - tail call void @swift_release(%swift.refcounted* %A) +define void @unknown_release_promotion(ptr %A) { + tail call void @swift_unknownObjectRelease(ptr %A) + tail call void @swift_unknownObjectRelease(ptr %A) + tail call void @swift_release(ptr %A) ret void } @@ -364,65 +346,65 @@ define void @unknown_release_promotion(%swift.refcounted* %A) { ; CHECK: bb1 ; CHECK-NOT: swift_retain ; CHECK: ret -define void @unknown_retain_nopromotion(%swift.refcounted* %A) { - tail call %swift.refcounted* @swift_retain(%swift.refcounted* %A) +define void @unknown_retain_nopromotion(ptr %A) { + tail call ptr @swift_retain(ptr %A) br label %bb1 bb1: - tail call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) + tail call ptr @swift_unknownObjectRetain(ptr %A) ret void } ; CHECK-LABEL: @releasemotion_forwarding ; CHECK-NOT: swift_retain ; CHECK-NOT: swift_release -; CHECK: call void @user(%swift.refcounted* %P) +; CHECK: call void @user(ptr %P) ; CHECK: ret -define void @releasemotion_forwarding(%swift.refcounted* %P, i8* %O, %swift.bridge* %B) { +define void @releasemotion_forwarding(ptr %P, ptr %O, ptr %B) { entry: - %res = tail call %swift.refcounted* @swift_retain(%swift.refcounted* %P) - tail call void @swift_release(%swift.refcounted* %res) nounwind - call void @user(%swift.refcounted* %res) nounwind + %res = tail call ptr @swift_retain(ptr %P) + tail call void @swift_release(ptr %res) nounwind + call void @user(ptr %res) nounwind ret void } ; CHECK-LABEL: @retainmotion_forwarding -; CHECK: store %swift.refcounted* %P, %swift.refcounted** %R, align 4 +; CHECK: store ptr %P, ptr %R, align 4 ; CHECK-NOT: swift_retain ; CHECK-NOT: swift_release ; CHECK: ret -define void @retainmotion_forwarding(%swift.refcounted* %P, %swift.refcounted** %R, %swift.bridge* %B) { +define void @retainmotion_forwarding(ptr %P, ptr %R, ptr %B) { entry: - %res = tail call %swift.refcounted* @swift_retain(%swift.refcounted* %P) - store %swift.refcounted* %res, %swift.refcounted** %R, align 4 - call void @swift_bridgeObjectRelease(%swift.bridge* %B) - tail call void @swift_release(%swift.refcounted* %res) nounwind + %res = tail call ptr @swift_retain(ptr %P) + store ptr %res, ptr %R, align 4 + call void @swift_bridgeObjectRelease(ptr %B) + tail call void @swift_release(ptr %res) nounwind ret void } ; CHECK-LABEL: @unknownreleasemotion_forwarding ; CHECK-NOT: swift_unknownObjectRetain ; CHECK-NOT: swift_unknownObjectRelease -; CHECK: call void @user(%swift.refcounted* %P) +; CHECK: call void @user(ptr %P) ; CHECK: ret -define void @unknownreleasemotion_forwarding(%swift.refcounted* %P, i8* %O, %swift.bridge* %B) { +define void @unknownreleasemotion_forwarding(ptr %P, ptr %O, ptr %B) { entry: - %res = tail call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %P) - tail call void @swift_unknownObjectRelease(%swift.refcounted* %res) nounwind - call void @user(%swift.refcounted* %res) nounwind + %res = tail call ptr @swift_unknownObjectRetain(ptr %P) + tail call void @swift_unknownObjectRelease(ptr %res) nounwind + call void @user(ptr %res) nounwind ret void } ; CHECK-LABEL: @unknownretainmotion_forwarding -; CHECK: store %swift.refcounted* %P, %swift.refcounted** %R, align 4 +; CHECK: store ptr %P, ptr %R, align 4 ; CHECK-NOT: swift_unknownObjectRetain ; CHECK-NOT: swift_unknownObjectRelease ; CHECK: ret -define void @unknownretainmotion_forwarding(%swift.refcounted* %P, %swift.refcounted** %R, %swift.bridge* %B) { +define void @unknownretainmotion_forwarding(ptr %P, ptr %R, ptr %B) { entry: - %res = tail call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %P) - store %swift.refcounted* %res, %swift.refcounted** %R, align 4 - call void @swift_bridgeObjectRelease(%swift.bridge* %B) - tail call void @swift_unknownObjectRelease(%swift.refcounted* %res) nounwind + %res = tail call ptr @swift_unknownObjectRetain(ptr %P) + store ptr %res, ptr %R, align 4 + call void @swift_bridgeObjectRelease(ptr %B) + tail call void @swift_unknownObjectRelease(ptr %res) nounwind ret void } diff --git a/test/LLVMPasses/contract.ll b/test/LLVMPasses/contract.ll index 130063a3fe6..d5081e5c9e3 100644 --- a/test/LLVMPasses/contract.ll +++ b/test/LLVMPasses/contract.ll @@ -1,289 +1,284 @@ -; RUN: %swift-llvm-opt -swift-arc-contract %s | %FileCheck %s +; RUN: %swift-llvm-opt -passes=swift-llvm-arc-contract %s | %FileCheck %s target datalayout = "e-p:64:64:64-S128-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f16:16:16-f32:32:32-f64:64:64-f128:128:128-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64" target triple = "x86_64-apple-macosx10.9" -%swift.refcounted = type { %swift.heapmetadata*, i64 } -%swift.heapmetadata = type { i64 (%swift.refcounted*)*, i64 (%swift.refcounted*)* } +%swift.refcounted = type { ptr, i64 } +%swift.heapmetadata = type { ptr, ptr } %swift.bridge = type opaque -declare %swift.refcounted* @swift_allocObject(%swift.heapmetadata* , i64, i64) nounwind -declare %swift.bridge* @swift_bridgeObjectRetain(%swift.bridge*) -declare void @swift_bridgeObjectRelease(%swift.bridge* ) -declare void @swift_release(%swift.refcounted* nocapture) -declare %swift.refcounted* @swift_retain(%swift.refcounted* ) nounwind -declare void @swift_unknownObjectRelease(%swift.refcounted* nocapture) -declare %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* ) nounwind -declare void @__swift_fixLifetime(%swift.refcounted*) -declare void @noread_user(%swift.refcounted*) readnone -declare void @user(%swift.refcounted*) -declare void @noread_user_bridged(%swift.bridge*) readnone -declare void @user_bridged(%swift.bridge*) -declare void @__swift_endBorrow(i8*, i8*) +declare ptr @swift_allocObject(ptr , i64, i64) nounwind +declare ptr @swift_bridgeObjectRetain(ptr) +declare void @swift_bridgeObjectRelease(ptr ) +declare void @swift_release(ptr nocapture) +declare ptr @swift_retain(ptr ) nounwind +declare void @swift_unknownObjectRelease(ptr nocapture) +declare ptr @swift_unknownObjectRetain(ptr ) nounwind +declare void @__swift_fixLifetime(ptr) +declare void @noread_user(ptr) readnone +declare void @user(ptr) +declare void @noread_user_bridged(ptr) readnone +declare void @user_bridged(ptr) +declare void @__swift_endBorrow(ptr, ptr) -; CHECK-LABEL: define{{( protected)?}} void @fixlifetime_removal(i8* %0) { +; CHECK-LABEL: define{{( protected)?}} void @fixlifetime_removal(ptr %0) { ; CHECK-NOT: call void @__swift_fixLifetime -define void @fixlifetime_removal(i8*) { +define void @fixlifetime_removal(ptr) { entry: - %1 = bitcast i8* %0 to %swift.refcounted* - call void @__swift_fixLifetime(%swift.refcounted* %1) + call void @__swift_fixLifetime(ptr %0) ret void } -; CHECK-LABEL: define{{( protected)?}} void @endBorrow_removal(i8* %0, i8* %1) { +; CHECK-LABEL: define{{( protected)?}} void @endBorrow_removal(ptr %0, ptr %1) { ; CHECK-NOT: call void @__swift_endBorrow -define void @endBorrow_removal(i8*, i8*) { +define void @endBorrow_removal(ptr, ptr) { entry: - call void @__swift_endBorrow(i8* %0, i8* %1) + call void @__swift_endBorrow(ptr %0, ptr %1) ret void } -; CHECK-LABEL: define{{( protected)?}} %swift.refcounted* @swift_contractRetainN(%swift.refcounted* %A) { +; CHECK-LABEL: define{{( protected)?}} ptr @swift_contractRetainN(ptr %A) { ; CHECK: entry: ; CHECK-NEXT: br i1 undef ; CHECK: bb1: -; CHECK-NEXT: call %swift.refcounted* @swift_retain_n(%swift.refcounted* %A, i32 2) -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) +; CHECK-NEXT: call ptr @swift_retain_n(ptr %A, i32 2) +; CHECK-NEXT: call void @noread_user(ptr %A) +; CHECK-NEXT: call void @noread_user(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb2: -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) -; CHECK-NEXT: call %swift.refcounted* @swift_retain(%swift.refcounted* %A) -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) +; CHECK-NEXT: call void @noread_user(ptr %A) +; CHECK-NEXT: call ptr @swift_retain(ptr %A) +; CHECK-NEXT: call void @noread_user(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb3: -; CHECK-NEXT: call %swift.refcounted* @swift_retain(%swift.refcounted* %A) -; CHECK-NEXT: ret %swift.refcounted* %A -define %swift.refcounted* @swift_contractRetainN(%swift.refcounted* %A) { +; CHECK-NEXT: call ptr @swift_retain(ptr %A) +; CHECK-NEXT: ret ptr %A +define ptr @swift_contractRetainN(ptr %A) { entry: br i1 undef, label %bb1, label %bb2 bb1: - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) + call ptr @swift_retain(ptr %A) + call void @noread_user(ptr %A) + call ptr @swift_retain(ptr %A) + call void @noread_user(ptr %A) br label %bb3 bb2: - call void @noread_user(%swift.refcounted* %A) - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) + call void @noread_user(ptr %A) + call ptr @swift_retain(ptr %A) + call void @noread_user(ptr %A) br label %bb3 bb3: - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - ret %swift.refcounted* %A + call ptr @swift_retain(ptr %A) + ret ptr %A } -; CHECK-LABEL: define{{( protected)?}} %swift.refcounted* @swift_contractRetainNWithRCIdentity(%swift.refcounted* %A) { +; CHECK-LABEL: define{{( protected)?}} ptr @swift_contractRetainNWithRCIdentity(ptr %A) { ; CHECK: entry: ; CHECK-NEXT: br i1 undef ; CHECK: bb1: -; CHECK-NEXT: call %swift.refcounted* @swift_retain_n(%swift.refcounted* %A, i32 2) -; CHECK-NEXT: %1 = bitcast %swift.refcounted* %A to %swift.refcounted* +; CHECK-NEXT: call ptr @swift_retain_n(ptr %A, i32 2) ; CHECK-NEXT: br label %bb3 ; CHECK: bb2: -; CHECK-NEXT: call %swift.refcounted* @swift_retain(%swift.refcounted* %A) +; CHECK-NEXT: call ptr @swift_retain(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb3: -; CHECK-NEXT: call %swift.refcounted* @swift_retain(%swift.refcounted* %A) -; CHECK-NEXT: ret %swift.refcounted* %A -define %swift.refcounted* @swift_contractRetainNWithRCIdentity(%swift.refcounted* %A) { +; CHECK-NEXT: call ptr @swift_retain(ptr %A) +; CHECK-NEXT: ret ptr %A +define ptr @swift_contractRetainNWithRCIdentity(ptr %A) { entry: br i1 undef, label %bb1, label %bb2 bb1: - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - %1 = bitcast %swift.refcounted* %A to %swift.refcounted* - call %swift.refcounted* @swift_retain(%swift.refcounted* %1) + call ptr @swift_retain(ptr %A) + call ptr @swift_retain(ptr %A) br label %bb3 bb2: - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) + call ptr @swift_retain(ptr %A) br label %bb3 bb3: - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - ret %swift.refcounted* %A + call ptr @swift_retain(ptr %A) + ret ptr %A } -; CHECK-LABEL: define{{( protected)?}} %swift.refcounted* @swift_contractReleaseN(%swift.refcounted* %A) { +; CHECK-LABEL: define{{( protected)?}} ptr @swift_contractReleaseN(ptr %A) { ; CHECK: entry: ; CHECK-NEXT: br i1 undef ; CHECK: bb1: -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) -; CHECK-NEXT: call void @swift_release_n(%swift.refcounted* %A, i32 2) -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) +; CHECK-NEXT: call void @noread_user(ptr %A) +; CHECK-NEXT: call void @swift_release_n(ptr %A, i32 2) +; CHECK-NEXT: call void @noread_user(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb2: -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) -; CHECK-NEXT: call void @swift_release(%swift.refcounted* %A) -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) +; CHECK-NEXT: call void @noread_user(ptr %A) +; CHECK-NEXT: call void @swift_release(ptr %A) +; CHECK-NEXT: call void @noread_user(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb3: -; CHECK-NEXT: call void @swift_release(%swift.refcounted* %A) -; CHECK-NEXT: ret %swift.refcounted* %A -define %swift.refcounted* @swift_contractReleaseN(%swift.refcounted* %A) { +; CHECK-NEXT: call void @swift_release(ptr %A) +; CHECK-NEXT: ret ptr %A +define ptr @swift_contractReleaseN(ptr %A) { entry: br i1 undef, label %bb1, label %bb2 bb1: - call void @swift_release(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) - call void @swift_release(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) + call void @swift_release(ptr %A) + call void @noread_user(ptr %A) + call void @swift_release(ptr %A) + call void @noread_user(ptr %A) br label %bb3 bb2: - call void @noread_user(%swift.refcounted* %A) - call void @swift_release(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) + call void @noread_user(ptr %A) + call void @swift_release(ptr %A) + call void @noread_user(ptr %A) br label %bb3 bb3: - call void @swift_release(%swift.refcounted* %A) - ret %swift.refcounted* %A + call void @swift_release(ptr %A) + ret ptr %A } -; CHECK-LABEL: define{{( protected)?}} %swift.refcounted* @swift_contractReleaseNWithRCIdentity(%swift.refcounted* %A) { +; CHECK-LABEL: define{{( protected)?}} ptr @swift_contractReleaseNWithRCIdentity(ptr %A) { ; CHECK: entry: ; CHECK-NEXT: br i1 undef ; CHECK: bb1: -; CHECK-NEXT: %0 = bitcast %swift.refcounted* %A to %swift.refcounted* -; CHECK-NEXT: call void @swift_release_n(%swift.refcounted* %A, i32 2) +; CHECK-NEXT: call void @swift_release_n(ptr %A, i32 2) ; CHECK-NEXT: br label %bb3 ; CHECK: bb2: -; CHECK-NEXT: call void @swift_release(%swift.refcounted* %A) +; CHECK-NEXT: call void @swift_release(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb3: -; CHECK-NEXT: call void @swift_release(%swift.refcounted* %A) -; CHECK-NEXT: ret %swift.refcounted* %A -define %swift.refcounted* @swift_contractReleaseNWithRCIdentity(%swift.refcounted* %A) { +; CHECK-NEXT: call void @swift_release(ptr %A) +; CHECK-NEXT: ret ptr %A +define ptr @swift_contractReleaseNWithRCIdentity(ptr %A) { entry: br i1 undef, label %bb1, label %bb2 bb1: - call void @swift_release(%swift.refcounted* %A) - %0 = bitcast %swift.refcounted* %A to %swift.refcounted* - call void @swift_release(%swift.refcounted* %0) + call void @swift_release(ptr %A) + call void @swift_release(ptr %A) br label %bb3 bb2: - call void @swift_release(%swift.refcounted* %A) + call void @swift_release(ptr %A) br label %bb3 bb3: - call void @swift_release(%swift.refcounted* %A) - ret %swift.refcounted* %A + call void @swift_release(ptr %A) + ret ptr %A } ; Make sure that we do not form retainN,releaseN over uses that may ; read the reference count of the object. -; CHECK-LABEL: define{{( protected)?}} %swift.refcounted* @swift_contractRetainNWithUnknown(%swift.refcounted* %A) { -; CHECK-NOT: call %swift.refcounted* @swift_retain_n -define %swift.refcounted* @swift_contractRetainNWithUnknown(%swift.refcounted* %A) { +; CHECK-LABEL: define{{( protected)?}} ptr @swift_contractRetainNWithUnknown(ptr %A) { +; CHECK-NOT: call ptr @swift_retain_n +define ptr @swift_contractRetainNWithUnknown(ptr %A) { entry: br i1 undef, label %bb1, label %bb2 bb1: - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) + call ptr @swift_retain(ptr %A) + call void @user(ptr %A) + call ptr @swift_retain(ptr %A) + call void @user(ptr %A) br label %bb3 bb2: - call void @user(%swift.refcounted* %A) - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) + call void @user(ptr %A) + call ptr @swift_retain(ptr %A) + call void @user(ptr %A) br label %bb3 bb3: - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - ret %swift.refcounted* %A + call ptr @swift_retain(ptr %A) + ret ptr %A } -; CHECK-LABEL: define{{( protected)?}} %swift.refcounted* @swift_contractReleaseNWithUnknown(%swift.refcounted* %A) { +; CHECK-LABEL: define{{( protected)?}} ptr @swift_contractReleaseNWithUnknown(ptr %A) { ; CHECK-NOT: call void @swift_release_n -define %swift.refcounted* @swift_contractReleaseNWithUnknown(%swift.refcounted* %A) { +define ptr @swift_contractReleaseNWithUnknown(ptr %A) { entry: br i1 undef, label %bb1, label %bb2 bb1: - call void @swift_release(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call void @swift_release(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) + call void @swift_release(ptr %A) + call void @user(ptr %A) + call void @swift_release(ptr %A) + call void @user(ptr %A) br label %bb3 bb2: - call void @user(%swift.refcounted* %A) - call void @swift_release(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) + call void @user(ptr %A) + call void @swift_release(ptr %A) + call void @user(ptr %A) br label %bb3 bb3: - call void @swift_release(%swift.refcounted* %A) - ret %swift.refcounted* %A + call void @swift_release(ptr %A) + ret ptr %A } ; But do make sure that we can form retainN, releaseN in between such uses -; CHECK-LABEL: define{{( protected)?}} %swift.refcounted* @swift_contractRetainNInterleavedWithUnknown(%swift.refcounted* %A) { +; CHECK-LABEL: define{{( protected)?}} ptr @swift_contractRetainNInterleavedWithUnknown(ptr %A) { ; CHECK: bb1: -; CHECK: call %swift.refcounted* @swift_retain(%swift.refcounted* %A) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call %swift.refcounted* @swift_retain_n(%swift.refcounted* %A, i32 3) -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call %swift.refcounted* @swift_retain_n(%swift.refcounted* %A, i32 2) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call %swift.refcounted* @swift_retain(%swift.refcounted* %A) +; CHECK: call ptr @swift_retain(ptr %A) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call ptr @swift_retain_n(ptr %A, i32 3) +; CHECK-NEXT: call void @noread_user(ptr %A) +; CHECK-NEXT: call void @noread_user(ptr %A) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call ptr @swift_retain_n(ptr %A, i32 2) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call ptr @swift_retain(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb2: -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call %swift.refcounted* @swift_retain(%swift.refcounted* %A) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call ptr @swift_retain(ptr %A) +; CHECK-NEXT: call void @user(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb3: -; CHECK-NEXT: call %swift.refcounted* @swift_retain(%swift.refcounted* %A) -; CHECK-NEXT: ret %swift.refcounted* %A -define %swift.refcounted* @swift_contractRetainNInterleavedWithUnknown(%swift.refcounted* %A) { +; CHECK-NEXT: call ptr @swift_retain(ptr %A) +; CHECK-NEXT: ret ptr %A +define ptr @swift_contractRetainNInterleavedWithUnknown(ptr %A) { entry: br i1 undef, label %bb1, label %bb2 bb1: - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) + call ptr @swift_retain(ptr %A) + call void @user(ptr %A) + call ptr @swift_retain(ptr %A) + call void @noread_user(ptr %A) + call ptr @swift_retain(ptr %A) + call void @noread_user(ptr %A) + call ptr @swift_retain(ptr %A) + call void @user(ptr %A) + call ptr @swift_retain(ptr %A) + call ptr @swift_retain(ptr %A) + call void @user(ptr %A) + call ptr @swift_retain(ptr %A) br label %bb3 bb2: - call void @user(%swift.refcounted* %A) - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) + call void @user(ptr %A) + call ptr @swift_retain(ptr %A) + call void @user(ptr %A) br label %bb3 bb3: - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - ret %swift.refcounted* %A + call ptr @swift_retain(ptr %A) + ret ptr %A } -; CHECK-LABEL: define{{( protected)?}} %swift.refcounted* @swift_contractReleaseNInterleavedWithUnknown(%swift.refcounted* %A) { +; CHECK-LABEL: define{{( protected)?}} ptr @swift_contractReleaseNInterleavedWithUnknown(ptr %A) { ; CHECK: bb1: ; CHECK-NEXT: @swift_release( ; CHECK-NEXT: @user @@ -291,139 +286,139 @@ bb3: ; CHECK-NEXT: @swift_release_n ; CHECK-NEXT: @user ; CHECK-NEXT: br label %bb3 -define %swift.refcounted* @swift_contractReleaseNInterleavedWithUnknown(%swift.refcounted* %A) { +define ptr @swift_contractReleaseNInterleavedWithUnknown(ptr %A) { entry: br i1 undef, label %bb1, label %bb2 bb1: - call void @swift_release(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call void @swift_release(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) - call void @swift_release(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) + call void @swift_release(ptr %A) + call void @user(ptr %A) + call void @swift_release(ptr %A) + call void @noread_user(ptr %A) + call void @swift_release(ptr %A) + call void @user(ptr %A) br label %bb3 bb2: - call void @user(%swift.refcounted* %A) - call void @swift_release(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) + call void @user(ptr %A) + call void @swift_release(ptr %A) + call void @user(ptr %A) br label %bb3 bb3: - call void @swift_release(%swift.refcounted* %A) - ret %swift.refcounted* %A + call void @swift_release(ptr %A) + ret ptr %A } -; CHECK-LABEL: define{{( protected)?}} %swift.refcounted* @swift_contractRetainReleaseNInterleavedWithUnknown(%swift.refcounted* %A) { +; CHECK-LABEL: define{{( protected)?}} ptr @swift_contractRetainReleaseNInterleavedWithUnknown(ptr %A) { ; CHECK: bb1: -; CHECK-NEXT: call %swift.refcounted* @swift_retain(%swift.refcounted* %A) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) -; CHECK-NEXT: call void @swift_release_n(%swift.refcounted* %A, i32 2) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call %swift.refcounted* @swift_retain_n(%swift.refcounted* %A, i32 2) -; CHECK-NEXT: call void @swift_release(%swift.refcounted* %A) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) -; CHECK-NEXT: call void @swift_release_n(%swift.refcounted* %A, i32 2) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) +; CHECK-NEXT: call ptr @swift_retain(ptr %A) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call void @noread_user(ptr %A) +; CHECK-NEXT: call void @swift_release_n(ptr %A, i32 2) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call ptr @swift_retain_n(ptr %A, i32 2) +; CHECK-NEXT: call void @swift_release(ptr %A) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call void @noread_user(ptr %A) +; CHECK-NEXT: call void @swift_release_n(ptr %A, i32 2) +; CHECK-NEXT: call void @user(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb2: -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call void @swift_release(%swift.refcounted* %A) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call void @swift_release(ptr %A) +; CHECK-NEXT: call void @user(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb3: -; CHECK-NEXT: call void @swift_release(%swift.refcounted* %A) -; CHECK-NEXT: ret %swift.refcounted* %A -define %swift.refcounted* @swift_contractRetainReleaseNInterleavedWithUnknown(%swift.refcounted* %A) { +; CHECK-NEXT: call void @swift_release(ptr %A) +; CHECK-NEXT: ret ptr %A +define ptr @swift_contractRetainReleaseNInterleavedWithUnknown(ptr %A) { entry: br i1 undef, label %bb1, label %bb2 bb1: - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call void @swift_release(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) - call void @swift_release(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call %swift.refcounted* @swift_retain(%swift.refcounted* %A) - call void @swift_release(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call void @swift_release(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) - call void @swift_release(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) + call ptr @swift_retain(ptr %A) + call void @user(ptr %A) + call void @swift_release(ptr %A) + call void @noread_user(ptr %A) + call void @swift_release(ptr %A) + call void @user(ptr %A) + call ptr @swift_retain(ptr %A) + call ptr @swift_retain(ptr %A) + call void @swift_release(ptr %A) + call void @user(ptr %A) + call void @swift_release(ptr %A) + call void @noread_user(ptr %A) + call void @swift_release(ptr %A) + call void @user(ptr %A) br label %bb3 bb2: - call void @user(%swift.refcounted* %A) - call void @swift_release(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) + call void @user(ptr %A) + call void @swift_release(ptr %A) + call void @user(ptr %A) br label %bb3 bb3: - call void @swift_release(%swift.refcounted* %A) - ret %swift.refcounted* %A + call void @swift_release(ptr %A) + ret ptr %A } -; CHECK-LABEL: define{{( protected)?}} %swift.refcounted* @swift_contractUnknownObjectRetainNInterleavedWithUnknown(%swift.refcounted* %A) { +; CHECK-LABEL: define{{( protected)?}} ptr @swift_contractUnknownObjectRetainNInterleavedWithUnknown(ptr %A) { ; CHECK: bb1: -; CHECK: call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call %swift.refcounted* @swift_unknownObjectRetain_n(%swift.refcounted* %A, i32 3) -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call %swift.refcounted* @swift_unknownObjectRetain_n(%swift.refcounted* %A, i32 2) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) +; CHECK: call ptr @swift_unknownObjectRetain(ptr %A) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call ptr @swift_unknownObjectRetain_n(ptr %A, i32 3) +; CHECK-NEXT: call void @noread_user(ptr %A) +; CHECK-NEXT: call void @noread_user(ptr %A) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call ptr @swift_unknownObjectRetain_n(ptr %A, i32 2) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call ptr @swift_unknownObjectRetain(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb2: -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call ptr @swift_unknownObjectRetain(ptr %A) +; CHECK-NEXT: call void @user(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb3: -; CHECK-NEXT: call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) -; CHECK-NEXT: ret %swift.refcounted* %A -define %swift.refcounted* @swift_contractUnknownObjectRetainNInterleavedWithUnknown(%swift.refcounted* %A) { +; CHECK-NEXT: call ptr @swift_unknownObjectRetain(ptr %A) +; CHECK-NEXT: ret ptr %A +define ptr @swift_contractUnknownObjectRetainNInterleavedWithUnknown(ptr %A) { entry: br i1 undef, label %bb1, label %bb2 bb1: - call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) - call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) - call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) - call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) + call ptr @swift_unknownObjectRetain(ptr %A) + call void @user(ptr %A) + call ptr @swift_unknownObjectRetain(ptr %A) + call void @noread_user(ptr %A) + call ptr @swift_unknownObjectRetain(ptr %A) + call void @noread_user(ptr %A) + call ptr @swift_unknownObjectRetain(ptr %A) + call void @user(ptr %A) + call ptr @swift_unknownObjectRetain(ptr %A) + call ptr @swift_unknownObjectRetain(ptr %A) + call void @user(ptr %A) + call ptr @swift_unknownObjectRetain(ptr %A) br label %bb3 bb2: - call void @user(%swift.refcounted* %A) - call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) + call void @user(ptr %A) + call ptr @swift_unknownObjectRetain(ptr %A) + call void @user(ptr %A) br label %bb3 bb3: - call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) - ret %swift.refcounted* %A + call ptr @swift_unknownObjectRetain(ptr %A) + ret ptr %A } -; CHECK-LABEL: define{{( protected)?}} %swift.refcounted* @swift_contractUnknownObjectReleaseNInterleavedWithUnknown(%swift.refcounted* %A) { +; CHECK-LABEL: define{{( protected)?}} ptr @swift_contractUnknownObjectReleaseNInterleavedWithUnknown(ptr %A) { ; CHECK: bb1: ; CHECK-NEXT: @swift_unknownObjectRelease( ; CHECK-NEXT: @user @@ -431,154 +426,154 @@ bb3: ; CHECK-NEXT: @swift_unknownObjectRelease_n ; CHECK-NEXT: @user ; CHECK-NEXT: br label %bb3 -define %swift.refcounted* @swift_contractUnknownObjectReleaseNInterleavedWithUnknown(%swift.refcounted* %A) { +define ptr @swift_contractUnknownObjectReleaseNInterleavedWithUnknown(ptr %A) { entry: br i1 undef, label %bb1, label %bb2 bb1: - call void @swift_unknownObjectRelease(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call void @swift_unknownObjectRelease(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) - call void @swift_unknownObjectRelease(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) + call void @swift_unknownObjectRelease(ptr %A) + call void @user(ptr %A) + call void @swift_unknownObjectRelease(ptr %A) + call void @noread_user(ptr %A) + call void @swift_unknownObjectRelease(ptr %A) + call void @user(ptr %A) br label %bb3 bb2: - call void @user(%swift.refcounted* %A) - call void @swift_unknownObjectRelease(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) + call void @user(ptr %A) + call void @swift_unknownObjectRelease(ptr %A) + call void @user(ptr %A) br label %bb3 bb3: - call void @swift_unknownObjectRelease(%swift.refcounted* %A) - ret %swift.refcounted* %A + call void @swift_unknownObjectRelease(ptr %A) + ret ptr %A } -; CHECK-LABEL: define{{( protected)?}} %swift.refcounted* @swift_contractUnknownObjectRetainReleaseNInterleavedWithUnknown(%swift.refcounted* %A) { +; CHECK-LABEL: define{{( protected)?}} ptr @swift_contractUnknownObjectRetainReleaseNInterleavedWithUnknown(ptr %A) { ; CHECK: bb1: -; CHECK-NEXT: call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) -; CHECK-NEXT: call void @swift_unknownObjectRelease_n(%swift.refcounted* %A, i32 2) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call %swift.refcounted* @swift_unknownObjectRetain_n(%swift.refcounted* %A, i32 2) -; CHECK-NEXT: call void @swift_unknownObjectRelease(%swift.refcounted* %A) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call void @noread_user(%swift.refcounted* %A) -; CHECK-NEXT: call void @swift_unknownObjectRelease_n(%swift.refcounted* %A, i32 2) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) +; CHECK-NEXT: call ptr @swift_unknownObjectRetain(ptr %A) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call void @noread_user(ptr %A) +; CHECK-NEXT: call void @swift_unknownObjectRelease_n(ptr %A, i32 2) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call ptr @swift_unknownObjectRetain_n(ptr %A, i32 2) +; CHECK-NEXT: call void @swift_unknownObjectRelease(ptr %A) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call void @noread_user(ptr %A) +; CHECK-NEXT: call void @swift_unknownObjectRelease_n(ptr %A, i32 2) +; CHECK-NEXT: call void @user(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb2: -; CHECK-NEXT: call void @user(%swift.refcounted* %A) -; CHECK-NEXT: call void @swift_unknownObjectRelease(%swift.refcounted* %A) -; CHECK-NEXT: call void @user(%swift.refcounted* %A) +; CHECK-NEXT: call void @user(ptr %A) +; CHECK-NEXT: call void @swift_unknownObjectRelease(ptr %A) +; CHECK-NEXT: call void @user(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb3: -; CHECK-NEXT: call void @swift_unknownObjectRelease(%swift.refcounted* %A) -; CHECK-NEXT: ret %swift.refcounted* %A -define %swift.refcounted* @swift_contractUnknownObjectRetainReleaseNInterleavedWithUnknown(%swift.refcounted* %A) { +; CHECK-NEXT: call void @swift_unknownObjectRelease(ptr %A) +; CHECK-NEXT: ret ptr %A +define ptr @swift_contractUnknownObjectRetainReleaseNInterleavedWithUnknown(ptr %A) { entry: br i1 undef, label %bb1, label %bb2 bb1: - call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call void @swift_unknownObjectRelease(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) - call void @swift_unknownObjectRelease(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) - call %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* %A) - call void @swift_unknownObjectRelease(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) - call void @swift_unknownObjectRelease(%swift.refcounted* %A) - call void @noread_user(%swift.refcounted* %A) - call void @swift_unknownObjectRelease(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) + call ptr @swift_unknownObjectRetain(ptr %A) + call void @user(ptr %A) + call void @swift_unknownObjectRelease(ptr %A) + call void @noread_user(ptr %A) + call void @swift_unknownObjectRelease(ptr %A) + call void @user(ptr %A) + call ptr @swift_unknownObjectRetain(ptr %A) + call ptr @swift_unknownObjectRetain(ptr %A) + call void @swift_unknownObjectRelease(ptr %A) + call void @user(ptr %A) + call void @swift_unknownObjectRelease(ptr %A) + call void @noread_user(ptr %A) + call void @swift_unknownObjectRelease(ptr %A) + call void @user(ptr %A) br label %bb3 bb2: - call void @user(%swift.refcounted* %A) - call void @swift_unknownObjectRelease(%swift.refcounted* %A) - call void @user(%swift.refcounted* %A) + call void @user(ptr %A) + call void @swift_unknownObjectRelease(ptr %A) + call void @user(ptr %A) br label %bb3 bb3: - call void @swift_unknownObjectRelease(%swift.refcounted* %A) - ret %swift.refcounted* %A + call void @swift_unknownObjectRelease(ptr %A) + ret ptr %A } -; CHECK-LABEL: define{{( protected)?}} %swift.bridge* @swift_contractBridgeRetainWithBridge(%swift.bridge* %A) { +; CHECK-LABEL: define{{( protected)?}} ptr @swift_contractBridgeRetainWithBridge(ptr %A) { ; CHECK: bb1: -; CHECK-NEXT: [[RET0:%.+]] = call %swift.bridge* @swift_bridgeObjectRetain_n(%swift.bridge* %A, i32 2) -; CHECK-NEXT: call void @swift_bridgeObjectRelease(%swift.bridge* [[RET0:%.+]]) -; CHECK-NEXT: call void @swift_bridgeObjectRelease(%swift.bridge* %A) -; CHECK-NEXT: ret %swift.bridge* %A -define %swift.bridge* @swift_contractBridgeRetainWithBridge(%swift.bridge* %A) { +; CHECK-NEXT: [[RET0:%.+]] = call ptr @swift_bridgeObjectRetain_n(ptr %A, i32 2) +; CHECK-NEXT: call void @swift_bridgeObjectRelease(ptr [[RET0:%.+]]) +; CHECK-NEXT: call void @swift_bridgeObjectRelease(ptr %A) +; CHECK-NEXT: ret ptr %A +define ptr @swift_contractBridgeRetainWithBridge(ptr %A) { bb1: - %0 = call %swift.bridge* @swift_bridgeObjectRetain(%swift.bridge* %A) - %1 = call %swift.bridge* @swift_bridgeObjectRetain(%swift.bridge* %A) - call void @swift_bridgeObjectRelease(%swift.bridge* %1) - call void @swift_bridgeObjectRelease(%swift.bridge* %A) - ret %swift.bridge* %A + %0 = call ptr @swift_bridgeObjectRetain(ptr %A) + %1 = call ptr @swift_bridgeObjectRetain(ptr %A) + call void @swift_bridgeObjectRelease(ptr %1) + call void @swift_bridgeObjectRelease(ptr %A) + ret ptr %A } -; CHECK-LABEL: define{{( protected)?}} %swift.bridge* @swift_contractBridgeRetainReleaseNInterleavedWithBridge(%swift.bridge* %A) { +; CHECK-LABEL: define{{( protected)?}} ptr @swift_contractBridgeRetainReleaseNInterleavedWithBridge(ptr %A) { ; CHECK: bb1: -; CHECK-NEXT: [[RET0:%.+]] = call %swift.bridge* @swift_bridgeObjectRetain(%swift.bridge* %A) -; CHECK-NEXT: call void @user_bridged(%swift.bridge* %A) -; CHECK-NEXT: call void @noread_user_bridged(%swift.bridge* %A) -; CHECK-NEXT: call void @swift_bridgeObjectRelease_n(%swift.bridge* %A, i32 2) -; CHECK-NEXT: call void @user_bridged(%swift.bridge* %A) -; CHECK-NEXT: [[RET1:%.+]] = call %swift.bridge* @swift_bridgeObjectRetain_n(%swift.bridge* %A, i32 2) -; CHECK-NEXT: call void @swift_bridgeObjectRelease(%swift.bridge* %A) -; CHECK-NEXT: call void @user_bridged(%swift.bridge* %A) -; CHECK-NEXT: call void @noread_user_bridged(%swift.bridge* %A) -; CHECK-NEXT: call void @swift_bridgeObjectRelease_n(%swift.bridge* %A, i32 2) -; CHECK-NEXT: call void @user_bridged(%swift.bridge* %A) +; CHECK-NEXT: [[RET0:%.+]] = call ptr @swift_bridgeObjectRetain(ptr %A) +; CHECK-NEXT: call void @user_bridged(ptr %A) +; CHECK-NEXT: call void @noread_user_bridged(ptr %A) +; CHECK-NEXT: call void @swift_bridgeObjectRelease_n(ptr %A, i32 2) +; CHECK-NEXT: call void @user_bridged(ptr %A) +; CHECK-NEXT: [[RET1:%.+]] = call ptr @swift_bridgeObjectRetain_n(ptr %A, i32 2) +; CHECK-NEXT: call void @swift_bridgeObjectRelease(ptr %A) +; CHECK-NEXT: call void @user_bridged(ptr %A) +; CHECK-NEXT: call void @noread_user_bridged(ptr %A) +; CHECK-NEXT: call void @swift_bridgeObjectRelease_n(ptr %A, i32 2) +; CHECK-NEXT: call void @user_bridged(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb2: -; CHECK-NEXT: call void @user_bridged(%swift.bridge* %A) -; CHECK-NEXT: call void @swift_bridgeObjectRelease(%swift.bridge* %A) -; CHECK-NEXT: call void @user_bridged(%swift.bridge* %A) +; CHECK-NEXT: call void @user_bridged(ptr %A) +; CHECK-NEXT: call void @swift_bridgeObjectRelease(ptr %A) +; CHECK-NEXT: call void @user_bridged(ptr %A) ; CHECK-NEXT: br label %bb3 ; CHECK: bb3: -; CHECK-NEXT: call void @swift_bridgeObjectRelease(%swift.bridge* %A) -; CHECK-NEXT: ret %swift.bridge* %A -define %swift.bridge* @swift_contractBridgeRetainReleaseNInterleavedWithBridge(%swift.bridge* %A) { +; CHECK-NEXT: call void @swift_bridgeObjectRelease(ptr %A) +; CHECK-NEXT: ret ptr %A +define ptr @swift_contractBridgeRetainReleaseNInterleavedWithBridge(ptr %A) { entry: br i1 undef, label %bb1, label %bb2 bb1: - call %swift.bridge* @swift_bridgeObjectRetain(%swift.bridge* %A) - call void @user_bridged(%swift.bridge* %A) - call void @swift_bridgeObjectRelease(%swift.bridge* %A) - call void @noread_user_bridged(%swift.bridge* %A) - call void @swift_bridgeObjectRelease(%swift.bridge* %A) - call void @user_bridged(%swift.bridge* %A) - call %swift.bridge* @swift_bridgeObjectRetain(%swift.bridge* %A) - call %swift.bridge* @swift_bridgeObjectRetain(%swift.bridge* %A) - call void @swift_bridgeObjectRelease(%swift.bridge* %A) - call void @user_bridged(%swift.bridge* %A) - call void @swift_bridgeObjectRelease(%swift.bridge* %A) - call void @noread_user_bridged(%swift.bridge* %A) - call void @swift_bridgeObjectRelease(%swift.bridge* %A) - call void @user_bridged(%swift.bridge* %A) + call ptr @swift_bridgeObjectRetain(ptr %A) + call void @user_bridged(ptr %A) + call void @swift_bridgeObjectRelease(ptr %A) + call void @noread_user_bridged(ptr %A) + call void @swift_bridgeObjectRelease(ptr %A) + call void @user_bridged(ptr %A) + call ptr @swift_bridgeObjectRetain(ptr %A) + call ptr @swift_bridgeObjectRetain(ptr %A) + call void @swift_bridgeObjectRelease(ptr %A) + call void @user_bridged(ptr %A) + call void @swift_bridgeObjectRelease(ptr %A) + call void @noread_user_bridged(ptr %A) + call void @swift_bridgeObjectRelease(ptr %A) + call void @user_bridged(ptr %A) br label %bb3 bb2: - call void @user_bridged(%swift.bridge* %A) - call void @swift_bridgeObjectRelease(%swift.bridge* %A) - call void @user_bridged(%swift.bridge* %A) + call void @user_bridged(ptr %A) + call void @swift_bridgeObjectRelease(ptr %A) + call void @user_bridged(ptr %A) br label %bb3 bb3: - call void @swift_bridgeObjectRelease(%swift.bridge* %A) - ret %swift.bridge* %A + call void @swift_bridgeObjectRelease(ptr %A) + ret ptr %A } !llvm.dbg.cu = !{!1} diff --git a/test/LLVMPasses/crash.ll b/test/LLVMPasses/crash.ll index 938274a54aa..020ce652624 100644 --- a/test/LLVMPasses/crash.ll +++ b/test/LLVMPasses/crash.ll @@ -1,14 +1,14 @@ -; RUN: %swift-llvm-opt -swift-llvm-arc-optimize %s > /dev/null +; RUN: %swift-llvm-opt -passes=swift-llvm-arc-optimize %s > /dev/null target datalayout = "e-p:64:64:64-S128-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f16:16:16-f32:32:32-f64:64:64-f128:128:128-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64" target triple = "x86_64-apple-macosx10.9" -%swift.refcounted = type { %swift.heapmetadata*, i64 } -%swift.heapmetadata = type { i64 (%swift.refcounted*)*, i64 (%swift.refcounted*)* } +%swift.refcounted = type { ptr, i64 } +%swift.heapmetadata = type { ptr, ptr } -declare { i8*, i64, %swift.refcounted* } @_Tsop1pFT3lhsNs6String3rhsS__S_(i8*, i64, %swift.refcounted*, i8*, i64, %swift.refcounted*) -declare { i8*, i64, %swift.refcounted* } @_TNs6String24convertFromStringLiteralFT3valp_S_(i8*) -declare void @swift_release(%swift.refcounted* nocapture) +declare { ptr, i64, ptr } @_Tsop1pFT3lhsNs6String3rhsS__S_(ptr, i64, ptr, ptr, i64, ptr) +declare { ptr, i64, ptr } @_TNs6String24convertFromStringLiteralFT3valp_S_(ptr) +declare void @swift_release(ptr nocapture) @0 = private unnamed_addr constant [3 x i8] c"So\00" @@ -17,20 +17,20 @@ declare void @swift_release(%swift.refcounted* nocapture) ; rdar://11558546 define void @release_past_extract() { entry: - %0 = call { i8*, i64, %swift.refcounted* } @_TNs6String24convertFromStringLiteralFT3valp_S_(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @0, i32 0, i32 0)) - %1 = extractvalue { i8*, i64, %swift.refcounted* } %0, 0 - %2 = extractvalue { i8*, i64, %swift.refcounted* } %0, 1 - %3 = extractvalue { i8*, i64, %swift.refcounted* } %0, 2 - %4 = call { i8*, i64, %swift.refcounted* } @_TNs6String24convertFromStringLiteralFT3valp_S_(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @1, i32 0, i32 0)) - %5 = extractvalue { i8*, i64, %swift.refcounted* } %4, 0 - %6 = extractvalue { i8*, i64, %swift.refcounted* } %4, 1 - %7 = extractvalue { i8*, i64, %swift.refcounted* } %4, 2 - %8 = call { i8*, i64, %swift.refcounted* } @_Tsop1pFT3lhsNs6String3rhsS__S_(i8* %1, i64 %2, %swift.refcounted* %3, i8* %5, i64 %6, %swift.refcounted* %7) - %9 = extractvalue { i8*, i64, %swift.refcounted* } %8, 0 - %10 = extractvalue { i8*, i64, %swift.refcounted* } %8, 1 - %11 = extractvalue { i8*, i64, %swift.refcounted* } %8, 2 - call void @swift_release(%swift.refcounted* null) nounwind - call void @swift_release(%swift.refcounted* %11) nounwind + %0 = call { ptr, i64, ptr } @_TNs6String24convertFromStringLiteralFT3valp_S_(ptr @0) + %1 = extractvalue { ptr, i64, ptr } %0, 0 + %2 = extractvalue { ptr, i64, ptr } %0, 1 + %3 = extractvalue { ptr, i64, ptr } %0, 2 + %4 = call { ptr, i64, ptr } @_TNs6String24convertFromStringLiteralFT3valp_S_(ptr @1) + %5 = extractvalue { ptr, i64, ptr } %4, 0 + %6 = extractvalue { ptr, i64, ptr } %4, 1 + %7 = extractvalue { ptr, i64, ptr } %4, 2 + %8 = call { ptr, i64, ptr } @_Tsop1pFT3lhsNs6String3rhsS__S_(ptr %1, i64 %2, ptr %3, ptr %5, i64 %6, ptr %7) + %9 = extractvalue { ptr, i64, ptr } %8, 0 + %10 = extractvalue { ptr, i64, ptr } %8, 1 + %11 = extractvalue { ptr, i64, ptr } %8, 2 + call void @swift_release(ptr null) nounwind + call void @swift_release(ptr %11) nounwind ret void } diff --git a/test/LLVMPasses/disable_llvm_optzns.ll b/test/LLVMPasses/disable_llvm_optzns.ll index 2ce46cefb29..e71f22ae88a 100644 --- a/test/LLVMPasses/disable_llvm_optzns.ll +++ b/test/LLVMPasses/disable_llvm_optzns.ll @@ -6,29 +6,29 @@ target datalayout = "e-p:64:64:64-S128-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f16:16:16-f32:32:32-f64:64:64-f128:128:128-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64" target triple = "x86_64-apple-macosx10.9" -%swift.refcounted = type { %swift.heapmetadata*, i64 } -%swift.heapmetadata = type { i64 (%swift.refcounted*)*, i64 (%swift.refcounted*)* } +%swift.refcounted = type { ptr, i64 } +%swift.heapmetadata = type { ptr, ptr } %objc_object = type opaque %swift.bridge = type opaque -declare %swift.refcounted* @swift_unknownObjectRetain(%swift.refcounted* returned) -declare void @swift_unknownObjectRelease(%swift.refcounted*) -declare i8* @llvm.objc.retain(i8*) -declare void @llvm.objc.release(i8*) -declare %swift.refcounted* @swift_allocObject(%swift.heapmetadata* , i64, i64) nounwind -declare void @swift_release(%swift.refcounted* nocapture) -declare %swift.refcounted* @swift_retain(%swift.refcounted* returned) nounwind -declare %swift.bridge* @swift_bridgeObjectRetain(%swift.bridge*) -declare void @swift_bridgeObjectRelease(%swift.bridge*) -declare %swift.refcounted* @swift_retainUnowned(%swift.refcounted* returned) +declare ptr @swift_unknownObjectRetain(ptr returned) +declare void @swift_unknownObjectRelease(ptr) +declare ptr @llvm.objc.retain(ptr) +declare void @llvm.objc.release(ptr) +declare ptr @swift_allocObject(ptr , i64, i64) nounwind +declare void @swift_release(ptr nocapture) +declare ptr @swift_retain(ptr returned) nounwind +declare ptr @swift_bridgeObjectRetain(ptr) +declare void @swift_bridgeObjectRelease(ptr) +declare ptr @swift_retainUnowned(ptr returned) -declare void @user(%swift.refcounted *) nounwind -declare void @user_objc(i8*) nounwind +declare void @user(ptr) nounwind +declare void @user_objc(ptr) nounwind declare void @unknown_func() ; CHECK-LABEL: @trivial_retain_release( ; CHECK-NEXT: entry: -; CHECK-NEXT: call %swift.refcounted* @swift_retain(%swift.refcounted* %P) +; CHECK-NEXT: call ptr @swift_retain(ptr %P) ; CHECK-NEXT: call void @swift_release( ; CHECK-NEXT: call void @user( ; CHECK-NEXT: ret void @@ -37,11 +37,11 @@ declare void @unknown_func() ; NEGATIVE-NEXT: entry: ; NEGATIVE-NEXT: call void @user( ; NEGATIVE-NEXT: ret void -define void @trivial_retain_release(%swift.refcounted* %P, i8* %O, %swift.bridge * %B) { +define void @trivial_retain_release(ptr %P, ptr %O, ptr %B) { entry: - call %swift.refcounted* @swift_retain(%swift.refcounted* %P) - call void @swift_release(%swift.refcounted* %P) nounwind - call void @user(%swift.refcounted* %P) nounwind + call ptr @swift_retain(ptr %P) + call void @swift_release(ptr %P) nounwind + call void @user(ptr %P) nounwind ret void } diff --git a/test/LLVMPasses/llvm-aa.ll b/test/LLVMPasses/llvm-aa.ll index 4832af98875..a125f4aaf95 100644 --- a/test/LLVMPasses/llvm-aa.ll +++ b/test/LLVMPasses/llvm-aa.ll @@ -1,18 +1,18 @@ -; RUN: %swift-llvm-opt -swift-aa -gvn %s | %FileCheck %s +; RUN: %swift-llvm-opt -passes=gvn %s | %FileCheck %s target datalayout = "e-p:64:64:64-S128-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f16:16:16-f32:32:32-f64:64:64-f128:128:128-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64" target triple = "x86_64-apple-macosx10.9" -declare void @swift_retain(i8 *) nounwind +declare void @swift_retain(ptr) nounwind -; CHECK-LABEL: define{{( protected)?}} i8 @test_eliminate_loads_over_retain(i8* %0) { +; CHECK-LABEL: define{{( protected)?}} i8 @test_eliminate_loads_over_retain(ptr %0) { ; CHECK: load ; CHECK-NOT: load -define i8 @test_eliminate_loads_over_retain(i8*) { +define i8 @test_eliminate_loads_over_retain(ptr) { entry: - %1 = load i8, i8* %0 - tail call void @swift_retain(i8* %0) - %2 = load i8, i8* %0 + %1 = load i8, ptr %0 + tail call void @swift_retain(ptr %0) + %2 = load i8, ptr %0 %3 = add i8 %1, %2 ret i8 %3 } diff --git a/test/LLVMPasses/merge_func.ll b/test/LLVMPasses/merge_func.ll index 89ed6f8c308..7a85b2af466 100644 --- a/test/LLVMPasses/merge_func.ll +++ b/test/LLVMPasses/merge_func.ll @@ -1,4 +1,4 @@ -; RUN: %swift-llvm-opt -swift-merge-functions -swiftmergefunc-threshold=4 %s | %FileCheck %s +; RUN: %swift-llvm-opt -passes='swift-merge-functions' -swiftmergefunc-threshold=4 %s | %FileCheck %s @g1 = external global i32 @g2 = external global i32 @@ -9,80 +9,80 @@ ; Test the most trivial example. ; CHECK-LABEL: define i32 @simple_func1(i32 %x, i32 %y) -; CHECK: %1 = tail call i32 @simple_func1Tm(i32 %x, i32 %y, i32* @g1) +; CHECK: %1 = tail call i32 @simple_func1Tm(i32 %x, i32 %y, ptr @g1) ; CHECK: ret i32 %1 define i32 @simple_func1(i32 %x, i32 %y) { %sum = add i32 %x, %y %sum2 = add i32 %sum, %y - %l = load i32, i32* @g1, align 4 + %l = load i32, ptr @g1, align 4 %sum3 = add i32 %sum2, %y ret i32 %sum3 } ; CHECK-LABEL: define i32 @simple_func2(i32 %x, i32 %y) -; CHECK: %1 = tail call i32 @simple_func1Tm(i32 %x, i32 %y, i32* @g2) +; CHECK: %1 = tail call i32 @simple_func1Tm(i32 %x, i32 %y, ptr @g2) ; CHECK: ret i32 %1 define i32 @simple_func2(i32 %x, i32 %y) { %sum = add i32 %x, %y %sum2 = add i32 %sum, %y - %l = load i32, i32* @g2, align 4 + %l = load i32, ptr @g2, align 4 %sum3 = add i32 %sum2, %y ret i32 %sum3 } -; CHECK-LABEL: define internal i32 @simple_func1Tm(i32 %0, i32 %1, i32* %2) -; CHECK: %l = load i32, i32* %2 +; CHECK-LABEL: define internal i32 @simple_func1Tm(i32 %0, i32 %1, ptr %2) +; CHECK: %l = load i32, ptr %2 ; CHECK: ret ; Merge 3 functions with 3 types of differing instructions: load, store and call. ; CHECK-LABEL: define i32 @func1_of_3(i32 %x) -; CHECK: %1 = tail call i32 @func1_of_3Tm(i32 %x, i32* @g1, i32* @g1, void (i32)* @callee1) +; CHECK: %1 = tail call i32 @func1_of_3Tm(i32 %x, ptr @g1, ptr @g1, ptr @callee1) ; CHECK: ret i32 %1 define i32 @func1_of_3(i32 %x) { - %l1 = load i32, i32* @g1, align 4 + %l1 = load i32, ptr @g1, align 4 %sum = add i32 %x, %l1 - %l2 = load i32, i32* @g1, align 4 + %l2 = load i32, ptr @g1, align 4 %sum2 = add i32 %sum, %l2 - store i32 %sum2, i32 *@g1, align 4 + store i32 %sum2, ptr @g1, align 4 call void @callee1(i32 %sum2) %sum3 = add i32 %sum2, %l2 ret i32 %sum3 } ; CHECK-LABEL: define i32 @func2_of_3(i32 %x) -; CHECK: %1 = tail call i32 @func1_of_3Tm(i32 %x, i32* @g2, i32* @g2, void (i32)* @callee2) +; CHECK: %1 = tail call i32 @func1_of_3Tm(i32 %x, ptr @g2, ptr @g2, ptr @callee2) ; CHECK: ret i32 %1 define i32 @func2_of_3(i32 %x) { - %l1 = load i32, i32* @g2, align 4 + %l1 = load i32, ptr @g2, align 4 %sum = add i32 %x, %l1 - %l2 = load i32, i32* @g2, align 4 + %l2 = load i32, ptr @g2, align 4 %sum2 = add i32 %sum, %l2 - store i32 %sum2, i32 *@g2, align 4 + store i32 %sum2, ptr @g2, align 4 call void @callee2(i32 %sum2) %sum3 = add i32 %sum2, %l2 ret i32 %sum3 } ; CHECK-LABEL: define i32 @func3_of_3(i32 %x) -; CHECK: %1 = tail call i32 @func1_of_3Tm(i32 %x, i32* @g3, i32* @g1, void (i32)* @callee3) +; CHECK: %1 = tail call i32 @func1_of_3Tm(i32 %x, ptr @g3, ptr @g1, ptr @callee3) ; CHECK: ret i32 %1 define i32 @func3_of_3(i32 %x) { - %l1 = load i32, i32* @g3, align 4 + %l1 = load i32, ptr @g3, align 4 %sum = add i32 %x, %l1 - %l2 = load i32, i32* @g1, align 4 + %l2 = load i32, ptr @g1, align 4 %sum2 = add i32 %sum, %l2 - store i32 %sum2, i32 *@g3, align 4 + store i32 %sum2, ptr @g3, align 4 call void @callee3(i32 %sum2) %sum3 = add i32 %sum2, %l2 ret i32 %sum3 } -; CHECK-LABEL: define internal i32 @func1_of_3Tm(i32 %0, i32* %1, i32* %2, void (i32)* %3) -; CHECK: %l1 = load i32, i32* %1 -; CHECK: %l2 = load i32, i32* %2 -; CHECK: store i32 %sum2, i32* %1 +; CHECK-LABEL: define internal i32 @func1_of_3Tm(i32 %0, ptr %1, ptr %2, ptr %3) +; CHECK: %l1 = load i32, ptr %1 +; CHECK: %l2 = load i32, ptr %2 +; CHECK: store i32 %sum2, ptr %1 ; CHECK: call void %3(i32 %sum2) ; CHECK: ret @@ -92,31 +92,31 @@ declare void @callee3(i32 %x) ; Preserve attributes -; CHECK-LABEL: define void @sret_func1(i32* sret(i32) %p, i32 %x, i32 %y) -; CHECK: tail call void @sret_func1Tm(i32* sret(i32) %p, i32 %x, i32 %y, i32* @g1) +; CHECK-LABEL: define void @sret_func1(ptr sret(i32) %p, i32 %x, i32 %y) +; CHECK: tail call void @sret_func1Tm(ptr sret(i32) %p, i32 %x, i32 %y, ptr @g1) ; CHECK: ret void -define void @sret_func1(i32* sret(i32) %p, i32 %x, i32 %y) { +define void @sret_func1(ptr sret(i32) %p, i32 %x, i32 %y) { %sum = add i32 %x, %y - %l = load i32, i32* @g1, align 4 + %l = load i32, ptr @g1, align 4 %sum2 = add i32 %sum, %l - store i32 %sum2, i32* %p + store i32 %sum2, ptr %p ret void } -; CHECK-LABEL: define void @sret_func2(i32* sret(i32) %p, i32 %x, i32 %y) -; CHECK: tail call void @sret_func1Tm(i32* sret(i32) %p, i32 %x, i32 %y, i32* @g2) +; CHECK-LABEL: define void @sret_func2(ptr sret(i32) %p, i32 %x, i32 %y) +; CHECK: tail call void @sret_func1Tm(ptr sret(i32) %p, i32 %x, i32 %y, ptr @g2) ; CHECK: ret void -define void @sret_func2(i32* sret(i32) %p, i32 %x, i32 %y) { +define void @sret_func2(ptr sret(i32) %p, i32 %x, i32 %y) { %sum = add i32 %x, %y - %l = load i32, i32* @g2, align 4 + %l = load i32, ptr @g2, align 4 %sum2 = add i32 %sum, %l - store i32 %sum2, i32* %p + store i32 %sum2, ptr %p ret void } -; CHECK-LABEL: define internal void @sret_func1Tm(i32* sret(i32) %0, i32 %1, i32 %2, i32* %3) -; CHECK: %l = load i32, i32* %3, align 4 -; CHECK: store i32 %sum2, i32* %0 +; CHECK-LABEL: define internal void @sret_func1Tm(ptr sret(i32) %0, i32 %1, i32 %2, ptr %3) +; CHECK: %l = load i32, ptr %3, align 4 +; CHECK: store i32 %sum2, ptr %0 ; CHECK: ret @@ -124,77 +124,77 @@ define void @sret_func2(i32* sret(i32) %p, i32 %x, i32 %y) { ; Instead merge those functions which match best. ; CHECK-LABEL: define i32 @func1_merged_with3(i32 %x) -; CHECK: %1 = tail call i32 @func1_merged_with3Tm(i32 %x, i32* @g1) +; CHECK: %1 = tail call i32 @func1_merged_with3Tm(i32 %x, ptr @g1) ; CHECK: ret i32 %1 define i32 @func1_merged_with3(i32 %x) { - %l1 = load i32, i32* @g1, align 4 + %l1 = load i32, ptr @g1, align 4 %sum = add i32 %x, %l1 - %l2 = load i32, i32* @g2, align 4 + %l2 = load i32, ptr @g2, align 4 %sum2 = add i32 %sum, %l2 - %l3 = load i32, i32* @g3, align 4 + %l3 = load i32, ptr @g3, align 4 %sum3 = add i32 %sum2, %l2 - %l4 = load i32, i32* @g4, align 4 + %l4 = load i32, ptr @g4, align 4 %sum4 = add i32 %sum3, %l2 - %l5 = load i32, i32* @g5, align 4 + %l5 = load i32, ptr @g5, align 4 %sum5 = add i32 %sum4, %l2 ret i32 %sum5 } ; CHECK-LABEL: define i32 @func2_merged_with4(i32 %x) -; CHECK: %1 = tail call i32 @func2_merged_with4Tm(i32 %x, i32* @g2) +; CHECK: %1 = tail call i32 @func2_merged_with4Tm(i32 %x, ptr @g2) ; CHECK: ret i32 %1 define i32 @func2_merged_with4(i32 %x) { - %l1 = load i32, i32* @g2, align 4 + %l1 = load i32, ptr @g2, align 4 %sum = add i32 %x, %l1 - %l2 = load i32, i32* @g3, align 4 + %l2 = load i32, ptr @g3, align 4 %sum2 = add i32 %sum, %l2 - %l3 = load i32, i32* @g4, align 4 + %l3 = load i32, ptr @g4, align 4 %sum3 = add i32 %sum2, %l2 - %l4 = load i32, i32* @g5, align 4 + %l4 = load i32, ptr @g5, align 4 %sum4 = add i32 %sum3, %l2 - %l5 = load i32, i32* @g1, align 4 + %l5 = load i32, ptr @g1, align 4 %sum5 = add i32 %sum4, %l2 ret i32 %sum5 } ; CHECK-LABEL: define i32 @func3_merged_with1(i32 %x) -; CHECK: %1 = tail call i32 @func1_merged_with3Tm(i32 %x, i32* @g2) +; CHECK: %1 = tail call i32 @func1_merged_with3Tm(i32 %x, ptr @g2) ; CHECK: ret i32 %1 define i32 @func3_merged_with1(i32 %x) { - %l1 = load i32, i32* @g2, align 4 + %l1 = load i32, ptr @g2, align 4 %sum = add i32 %x, %l1 - %l2 = load i32, i32* @g2, align 4 + %l2 = load i32, ptr @g2, align 4 %sum2 = add i32 %sum, %l2 - %l3 = load i32, i32* @g3, align 4 + %l3 = load i32, ptr @g3, align 4 %sum3 = add i32 %sum2, %l2 - %l4 = load i32, i32* @g4, align 4 + %l4 = load i32, ptr @g4, align 4 %sum4 = add i32 %sum3, %l2 - %l5 = load i32, i32* @g5, align 4 + %l5 = load i32, ptr @g5, align 4 %sum5 = add i32 %sum4, %l2 ret i32 %sum5 } -; CHECK-LABEL: define internal i32 @func1_merged_with3Tm(i32 %0, i32* %1) -; CHECK: load i32, i32* %1, align 4 -; CHECK: load i32, i32* @g2, align 4 -; CHECK: load i32, i32* @g3, align 4 -; CHECK: load i32, i32* @g4, align 4 -; CHECK: load i32, i32* @g5, align 4 +; CHECK-LABEL: define internal i32 @func1_merged_with3Tm(i32 %0, ptr %1) +; CHECK: load i32, ptr %1, align 4 +; CHECK: load i32, ptr @g2, align 4 +; CHECK: load i32, ptr @g3, align 4 +; CHECK: load i32, ptr @g4, align 4 +; CHECK: load i32, ptr @g5, align 4 ; CHECK: ret i32 ; CHECK-LABEL: define i32 @func4_merged_with2(i32 %x) { -; CHECK: %1 = tail call i32 @func2_merged_with4Tm(i32 %x, i32* @g1) +; CHECK: %1 = tail call i32 @func2_merged_with4Tm(i32 %x, ptr @g1) ; CHECK: ret i32 %1 define i32 @func4_merged_with2(i32 %x) { - %l1 = load i32, i32* @g1, align 4 + %l1 = load i32, ptr @g1, align 4 %sum = add i32 %x, %l1 - %l2 = load i32, i32* @g3, align 4 + %l2 = load i32, ptr @g3, align 4 %sum2 = add i32 %sum, %l2 - %l3 = load i32, i32* @g4, align 4 + %l3 = load i32, ptr @g4, align 4 %sum3 = add i32 %sum2, %l2 - %l4 = load i32, i32* @g5, align 4 + %l4 = load i32, ptr @g5, align 4 %sum4 = add i32 %sum3, %l2 - %l5 = load i32, i32* @g1, align 4 + %l5 = load i32, ptr @g1, align 4 %sum5 = add i32 %sum4, %l2 ret i32 %sum5 } @@ -206,18 +206,18 @@ define i32 @func4_merged_with2(i32 %x) { declare i32 @get_int(i32 %x) ; CHECK-LABEL: define i32 @Function1_merged_with_3(i32 %x) -; CHECK: %1 = tail call i32 @Function1_merged_with_3Tm(i32 %x, i32* @g1) +; CHECK: %1 = tail call i32 @Function1_merged_with_3Tm(i32 %x, ptr @g1) ; CHECK: ret i32 %1 define i32 @Function1_merged_with_3(i32 %x) { - %l1 = load i32, i32* @g1, align 4 + %l1 = load i32, ptr @g1, align 4 %sum = add i32 %x, %l1 - %l2 = load i32, i32* @g2, align 4 + %l2 = load i32, ptr @g2, align 4 %sum2 = add i32 %sum, %l2 - %l3 = load i32, i32* @g3, align 4 + %l3 = load i32, ptr @g3, align 4 %sum3 = add i32 %sum2, %l2 - %l4 = load i32, i32* @g4, align 4 + %l4 = load i32, ptr @g4, align 4 %sum4 = add i32 %sum3, %l2 - %l5 = load i32, i32* @g5, align 4 + %l5 = load i32, ptr @g5, align 4 %sum5 = add i32 %sum4, %l2 %c = call fastcc i32 @get_int(i32 %sum5) ret i32 %c @@ -231,39 +231,39 @@ define i32 @Function1_merged_with_3(i32 %x) { ; CHECK: %c = call fastcc i32 @get_int ; CHECK: ret i32 %c define i32 @Function2_not_merged(i32 %x) { - %l1 = load i32, i32* @g2, align 4 + %l1 = load i32, ptr @g2, align 4 %sum = add i32 %x, %l1 - %l2 = load i32, i32* @g3, align 4 + %l2 = load i32, ptr @g3, align 4 %sum2 = add i32 %sum, %l2 - %l3 = load i32, i32* @g4, align 4 + %l3 = load i32, ptr @g4, align 4 %sum3 = add i32 %sum2, %l2 - %l4 = load i32, i32* @g5, align 4 + %l4 = load i32, ptr @g5, align 4 %sum4 = add i32 %sum3, %l2 - %l5 = load i32, i32* @g1, align 4 + %l5 = load i32, ptr @g1, align 4 %sum5 = add i32 %sum4, %l2 %c = call fastcc i32 @get_int(i32 %sum5) ret i32 %c } ; CHECK-LABEL: define i32 @Function3_merged_with_1(i32 %x) -; CHECK: %1 = tail call i32 @Function1_merged_with_3Tm(i32 %x, i32* @g2) +; CHECK: %1 = tail call i32 @Function1_merged_with_3Tm(i32 %x, ptr @g2) ; CHECK: ret i32 %1 define i32 @Function3_merged_with_1(i32 %x) { - %l1 = load i32, i32* @g2, align 4 + %l1 = load i32, ptr @g2, align 4 %sum = add i32 %x, %l1 - %l2 = load i32, i32* @g2, align 4 + %l2 = load i32, ptr @g2, align 4 %sum2 = add i32 %sum, %l2 - %l3 = load i32, i32* @g3, align 4 + %l3 = load i32, ptr @g3, align 4 %sum3 = add i32 %sum2, %l2 - %l4 = load i32, i32* @g4, align 4 + %l4 = load i32, ptr @g4, align 4 %sum4 = add i32 %sum3, %l2 - %l5 = load i32, i32* @g5, align 4 + %l5 = load i32, ptr @g5, align 4 %sum5 = add i32 %sum4, %l2 %c = call fastcc i32 @get_int(i32 %sum5) ret i32 %c } -; CHECK-LABEL: define internal i32 @Function1_merged_with_3Tm(i32 %0, i32* %1) +; CHECK-LABEL: define internal i32 @Function1_merged_with_3Tm(i32 %0, ptr %1) ; CHECK: load ; CHECK: load ; CHECK: load @@ -276,18 +276,18 @@ define i32 @Function3_merged_with_1(i32 %x) { ; CHECK: load ; CHECK: load ; CHECK: load -; CHECK: %1 = call fastcc i32 @Function1_merged_with_3Tm(i32 %sum5, i32* @g1) +; CHECK: %1 = call fastcc i32 @Function1_merged_with_3Tm(i32 %sum5, ptr @g1) ; CHECK: ret i32 %1 define i32 @Function4_not_merged(i32 %x) { - %l1 = load i32, i32* @g1, align 4 + %l1 = load i32, ptr @g1, align 4 %sum = add i32 %x, %l1 - %l2 = load i32, i32* @g3, align 4 + %l2 = load i32, ptr @g3, align 4 %sum2 = add i32 %sum, %l2 - %l3 = load i32, i32* @g4, align 4 + %l3 = load i32, ptr @g4, align 4 %sum3 = add i32 %sum2, %l2 - %l4 = load i32, i32* @g5, align 4 + %l4 = load i32, ptr @g5, align 4 %sum4 = add i32 %sum3, %l2 - %l5 = load i32, i32* @g1, align 4 + %l5 = load i32, ptr @g1, align 4 %sum5 = add i32 %sum4, %l2 %c = call fastcc i32 @Function1_merged_with_3(i32 %sum5) ret i32 %c @@ -299,7 +299,7 @@ define i32 @Function4_not_merged(i32 %x) { ; Also check that the calling convention is preserved. ; CHECK-LABEL: define fastcc i32 @callee1_a(i32 %x, i32 %y) -; CHECK: %1 = tail call fastcc i32 @callee1_aTm(i32 %x, i32 %y, i32* @g1) +; CHECK: %1 = tail call fastcc i32 @callee1_aTm(i32 %x, i32 %y, ptr @g1) ; CHECK: ret i32 %1 define fastcc i32 @callee1_a(i32 %x, i32 %y) { %sum = add i32 %x, %y @@ -310,7 +310,7 @@ define fastcc i32 @callee1_a(i32 %x, i32 %y) { } ; CHECK-LABEL: define fastcc i32 @callee1_b(i32 %x, i32 %y) -; CHECK: %1 = tail call fastcc i32 @callee1_aTm(i32 %x, i32 %y, i32* @g2) +; CHECK: %1 = tail call fastcc i32 @callee1_aTm(i32 %x, i32 %y, ptr @g2) ; CHECK: ret i32 %1 define fastcc i32 @callee1_b(i32 %x, i32 %y) { %sum = add i32 %x, %y @@ -320,15 +320,15 @@ define fastcc i32 @callee1_b(i32 %x, i32 %y) { ret i32 %sum3 } -; CHECK-LABEL: define internal fastcc i32 @callee1_aTm(i32 %0, i32 %1, i32* %2) -; CHECK: call i32 @callee2_aTm(i32 %sum2, i32 %1, i32* %2) +; CHECK-LABEL: define internal fastcc i32 @callee1_aTm(i32 %0, i32 %1, ptr %2) +; CHECK: call i32 @callee2_aTm(i32 %sum2, i32 %1, ptr %2) ; CHECK: ret ; CHECK-NOT: @callee2_a( define internal i32 @callee2_a(i32 %x, i32 %y) { %sum = add i32 %x, %y %sum2 = sub i32 %sum, %y - %l = load i32, i32* @g1, align 4 + %l = load i32, ptr @g1, align 4 %sum3 = add i32 %sum2, %y ret i32 %sum3 } @@ -337,13 +337,13 @@ define internal i32 @callee2_a(i32 %x, i32 %y) { define internal i32 @callee2_b(i32 %x, i32 %y) { %sum = add i32 %x, %y %sum2 = sub i32 %sum, %y - %l = load i32, i32* @g2, align 4 + %l = load i32, ptr @g2, align 4 %sum3 = add i32 %sum2, %y ret i32 %sum3 } ; CHECK-LABEL: define i32 @caller_a(i32 %x, i32 %y) -; CHECK: %1 = tail call i32 @caller_aTm(i32 %x, i32 %y, i32* @g1) +; CHECK: %1 = tail call i32 @caller_aTm(i32 %x, i32 %y, ptr @g1) ; CHECK: ret i32 %1 define i32 @caller_a(i32 %x, i32 %y) { %sum = add i32 %x, %y @@ -354,7 +354,7 @@ define i32 @caller_a(i32 %x, i32 %y) { } ; CHECK-LABEL: define i32 @caller_b(i32 %x, i32 %y) -; CHECK: %1 = tail call i32 @caller_aTm(i32 %x, i32 %y, i32* @g2) +; CHECK: %1 = tail call i32 @caller_aTm(i32 %x, i32 %y, ptr @g2) ; CHECK: ret i32 %1 define i32 @caller_b(i32 %x, i32 %y) { %sum = add i32 %x, %y @@ -364,8 +364,8 @@ define i32 @caller_b(i32 %x, i32 %y) { ret i32 %sum3 } -; CHECK-LABEL: define internal i32 @caller_aTm(i32 %0, i32 %1, i32* %2) -; CHECK: call fastcc i32 @callee1_aTm(i32 %sum2, i32 %1, i32* %2) +; CHECK-LABEL: define internal i32 @caller_aTm(i32 %0, i32 %1, ptr %2) +; CHECK: call fastcc i32 @callee1_aTm(i32 %sum2, i32 %1, ptr %2) ; CHECK: ret @@ -421,13 +421,13 @@ done: ; Check self recursive functions ; CHECK-LABEL: define internal void @recursive1(i32 %x, i32 %y) -; CHECK: tail call void @recursive1Tm(i32 %x, i32 %y, i32* @g1, void (i32, i32)* @recursive1) +; CHECK: tail call void @recursive1Tm(i32 %x, i32 %y, ptr @g1, ptr @recursive1) ; CHECK: ret void define internal void @recursive1(i32 %x, i32 %y) { br i1 undef, label %bb1, label %bb2 bb1: - %l = load i32, i32* @g1, align 4 + %l = load i32, ptr @g1, align 4 call void @recursive1(i32 %x, i32 %y) br label %bb2 @@ -436,33 +436,33 @@ bb2: } ; CHECK-LABEL: define internal void @recursive2(i32 %x, i32 %y) -; CHECK: tail call void @recursive1Tm(i32 %x, i32 %y, i32* @g2, void (i32, i32)* @recursive2) +; CHECK: tail call void @recursive1Tm(i32 %x, i32 %y, ptr @g2, ptr @recursive2) ; CHECK: ret void define internal void @recursive2(i32 %x, i32 %y) { br i1 undef, label %bb1, label %bb2 bb1: - %l = load i32, i32* @g2, align 4 + %l = load i32, ptr @g2, align 4 call void @recursive2(i32 %x, i32 %y) br label %bb2 bb2: ret void } -; CHECK-LABEL: define internal void @recursive1Tm(i32 %0, i32 %1, i32* %2, void (i32, i32)* %3) -; CHECK: load i32, i32* %2 +; CHECK-LABEL: define internal void @recursive1Tm(i32 %0, i32 %1, ptr %2, ptr %3) +; CHECK: load i32, ptr %2 ; CHECK: call void %3(i32 %0, i32 %1) ; CHECK: ret void ; CHECK-LABEL: define internal void @another_recursive_func(i32 %x) -; CHECK: tail call void @another_recursive_funcTm(i32 %x, i32* @g1, void (i32)* @another_recursive_func) +; CHECK: tail call void @another_recursive_funcTm(i32 %x, ptr @g1, ptr @another_recursive_func) ; CHECK: ret void define internal void @another_recursive_func(i32 %x) { br i1 undef, label %bb1, label %bb2 bb1: - store i32 %x, i32 *@g1, align 4 + store i32 %x, ptr @g1, align 4 call void @another_recursive_func(i32 %x) br label %bb2 @@ -471,15 +471,15 @@ bb2: } ; CHECK-NOT: @not_really_recursive( -; CHECK-LABEL: define internal void @another_recursive_funcTm(i32 %0, i32* %1, void (i32)* %2) -; CHECK: store i32 %0, i32* %1 +; CHECK-LABEL: define internal void @another_recursive_funcTm(i32 %0, ptr %1, ptr %2) +; CHECK: store i32 %0, ptr %1 ; CHECK: call void %2(i32 %0) ; CHECK: ret void define internal void @not_really_recursive(i32 %x) { br i1 undef, label %bb1, label %bb2 bb1: - store i32 %x, i32 *@g2, align 4 + store i32 %x, ptr @g2, align 4 call void @callee1(i32 %x) br label %bb2 @@ -492,7 +492,7 @@ bb2: ; CHECK: call void @recursive1(i32 %x, i32 %x) ; CHECK: call void @recursive2(i32 %x, i32 %x) ; CHECK: call void @another_recursive_func(i32 %x) -; CHECK: call void @another_recursive_funcTm(i32 %x, i32* @g2, void (i32)* @callee1) +; CHECK: call void @another_recursive_funcTm(i32 %x, ptr @g2, ptr @callee1) ; CHECK: ret void define void @call_recursive_funcs(i32 %x) { call void @recursive1(i32 %x, i32 %x) @@ -512,7 +512,7 @@ declare void @"__dtrace_probe$Apple$Probe1$v1$696e74"(i32) local_unnamed_addr define i32 @use_dtrace_probe1(i32 %x, i32 %y) { %sum = add i32 %x, %y %sum2 = add i32 %sum, %y - %l = load i32, i32* @g1, align 4 + %l = load i32, ptr @g1, align 4 %sum3 = add i32 %sum2, %y tail call void @"__dtrace_probe$Apple$Probe1$v1$696e74"(i32 undef) ret i32 %sum3 @@ -525,7 +525,7 @@ declare void @"__dtrace_probe$Apple$Probe2$v1$696e74"(i32) local_unnamed_addr define i32 @use_dtrace_probe2(i32 %x, i32 %y) { %sum = add i32 %x, %y %sum2 = add i32 %sum, %y - %l = load i32, i32* @g2, align 4 + %l = load i32, ptr @g2, align 4 %sum3 = add i32 %sum2, %y tail call void @"__dtrace_probe$Apple$Probe2$v1$696e74"(i32 undef) ret i32 %sum3 diff --git a/test/LLVMPasses/merge_func_coff.ll b/test/LLVMPasses/merge_func_coff.ll index 6935018dc94..2c157f7252a 100644 --- a/test/LLVMPasses/merge_func_coff.ll +++ b/test/LLVMPasses/merge_func_coff.ll @@ -1,11 +1,11 @@ -; RUN: %swift-llvm-opt -mtriple i686-windows -swift-merge-functions -swiftmergefunc-threshold=4 %s | %FileCheck %s +; RUN: %swift-llvm-opt -mtriple i686-windows -passes='swift-merge-functions' -swiftmergefunc-threshold=4 %s | %FileCheck %s @g = external global i32 define dllexport i32 @f(i32 %x, i32 %y) { %sum = add i32 %x, %y %sum2 = add i32 %sum, %y - %l = load i32, i32* @g, align 4 + %l = load i32, ptr @g, align 4 %sum3 = add i32 %sum2, %y ret i32 %sum3 } @@ -13,7 +13,7 @@ define dllexport i32 @f(i32 %x, i32 %y) { define dllexport i32 @h(i32 %x, i32 %y) { %sum = add i32 %x, %y %sum2 = add i32 %sum, %y - %l = load i32, i32* @g, align 4 + %l = load i32, ptr @g, align 4 %sum3 = add i32 %sum2, %y ret i32 %sum3 } diff --git a/test/LLVMPasses/merge_func_ptrauth.ll b/test/LLVMPasses/merge_func_ptrauth.ll index d0e11aec3cd..57baba66b9a 100644 --- a/test/LLVMPasses/merge_func_ptrauth.ll +++ b/test/LLVMPasses/merge_func_ptrauth.ll @@ -1,4 +1,4 @@ -; RUN: %swift-llvm-opt -swift-merge-functions -swiftmergefunc-threshold=4 %s | %FileCheck %s +; RUN: %swift-llvm-opt -passes='swift-merge-functions' -swiftmergefunc-threshold=4 %s | %FileCheck %s ; REQUIRES: CODEGENERATOR=AArch64 target triple = "arm64e-apple-macosx11.0.0" diff --git a/test/LLVMPasses/merge_func_opaque_pointers.ll b/test/LLVMPasses/merge_func_return_type_cast.ll similarity index 87% rename from test/LLVMPasses/merge_func_opaque_pointers.ll rename to test/LLVMPasses/merge_func_return_type_cast.ll index 7165fc5b32f..afcca8cdfdd 100644 --- a/test/LLVMPasses/merge_func_opaque_pointers.ll +++ b/test/LLVMPasses/merge_func_return_type_cast.ll @@ -1,4 +1,4 @@ -; RUN: %swift-llvm-opt -swift-merge-functions -swiftmergefunc-threshold=4 -opaque-pointers %s | %FileCheck %s +; RUN: %swift-llvm-opt -passes='swift-merge-functions' -swiftmergefunc-threshold=4 %s | %FileCheck %s ; REQUIRES: PTRSIZE=64 diff --git a/test/LLVMPasses/missing_runtime_declarations.ll b/test/LLVMPasses/missing_runtime_declarations.ll index ebd870f3c98..3b5c20414af 100644 --- a/test/LLVMPasses/missing_runtime_declarations.ll +++ b/test/LLVMPasses/missing_runtime_declarations.ll @@ -1,44 +1,38 @@ -; RUN: %swift-llvm-opt -swift-arc-contract %s | %FileCheck %s +; RUN: %swift-llvm-opt -passes=swift-llvm-arc-contract %s | %FileCheck %s target datalayout = "e-p:64:64:64-S128-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-f16:16:16-f32:32:32-f64:64:64-f128:128:128-v64:64:64-v128:128:128-a0:0:64-s0:64:64-f80:128:128-n8:16:32:64" target triple = "x86_64-apple-macosx10.9" -; CHECK: %a = type opaque -; CHECK: %swift.bridge = type opaque -; CHECK: declare void @swift_bridgeObjectRelease(%a* nocapture) +; CHECK: declare void @swift_bridgeObjectRelease(ptr nocapture) %a = type opaque -declare void @swift_bridgeObjectRelease(%a* nocapture) -declare %a *@swift_bridgeObjectRetain(%a* nocapture) +declare void @swift_bridgeObjectRelease(ptr nocapture) +declare ptr @swift_bridgeObjectRetain(ptr nocapture) -; CHECK-LABEL: define void @testcase1(%a* %0) { +; CHECK-LABEL: define void @testcase1(ptr %0) { ; CHECK: entry: -; CHECK-NEXT: [[CAST:%.*]] = bitcast %a* %0 to %swift.bridge* -; CHECK-NEXT: call void @swift_bridgeObjectRelease_n(%swift.bridge* [[CAST]], i32 2) +; CHECK-NEXT: call void @swift_bridgeObjectRelease_n(ptr %0, i32 2) ; CHECK-NEXT: ret void -define void @testcase1(%a*) { +define void @testcase1(ptr) { entry: - call void @swift_bridgeObjectRelease(%a* %0) - call void @swift_bridgeObjectRelease(%a* %0) + call void @swift_bridgeObjectRelease(ptr %0) + call void @swift_bridgeObjectRelease(ptr %0) ret void } -declare void @user(%a*) +declare void @user(ptr) -; CHECK-LABEL: define %a* @testcase2(%a* %0) { +; CHECK-LABEL: define ptr @testcase2(ptr %0) { ; CHECK: entry: -; CHECK-NEXT: [[CAST1:%.*]] = bitcast %a* %0 to %swift.bridge* -; CHECK-NEXT: [[RESULT:%.*]] ={{( tail)?}} call %swift.bridge* @swift_bridgeObjectRetain_n(%swift.bridge* [[CAST1]], i32 2) -; CHECK-NEXT: [[RESULT_CAST1:%.*]] = bitcast %swift.bridge* %2 to %a* -; CHECK-NEXT: [[RESULT_CAST2:%.*]] = bitcast %swift.bridge* %2 to %a* -; CHECK-NEXT: call void @user(%a* [[RESULT_CAST1]]) -; CHECK-NEXT: call void @user(%a* [[RESULT_CAST2]]) -; CHECK-NEXT: ret %a* [[RESULT_CAST2]] -define %a* @testcase2(%a*) { +; CHECK-NEXT: [[RESULT:%.*]] ={{( tail)?}} call ptr @swift_bridgeObjectRetain_n(ptr %0, i32 2) +; CHECK-NEXT: call void @user(ptr %1) +; CHECK-NEXT: call void @user(ptr %1) +; CHECK-NEXT: ret ptr %1 +define ptr @testcase2(ptr) { entry: - %1 = call %a* @swift_bridgeObjectRetain(%a* %0) - %2 = call %a* @swift_bridgeObjectRetain(%a* %0) - call void @user(%a* %1) - call void @user(%a* %2) - ret %a* %2 + %1 = call ptr @swift_bridgeObjectRetain(ptr %0) + %2 = call ptr @swift_bridgeObjectRetain(ptr %0) + call void @user(ptr %1) + call void @user(ptr %2) + ret ptr %2 } diff --git a/test/Profiler/coverage_dead_code_elim_onone.swift b/test/Profiler/coverage_dead_code_elim_onone.swift index 91c97723463..f3c7d91d639 100644 --- a/test/Profiler/coverage_dead_code_elim_onone.swift +++ b/test/Profiler/coverage_dead_code_elim_onone.swift @@ -1,8 +1,9 @@ // RUN: %target-swift-frontend -emit-sil -profile-generate -profile-coverage-mapping -module-name coverage_deadcode %s | %FileCheck %s -check-prefix SIL // RUN: %target-swift-frontend -emit-ir -profile-generate -profile-coverage-mapping -module-name coverage_deadcode %s | %FileCheck %s -check-prefix IR -// This function needs to be present in the SIL for the mandatory passes, but -// we can drop it in IRGen. We still need to emit its coverage map though. +// This function needs to be present in the SIL for the mandatory passes, +// and in the IR as it may be used in the debugger, we need to emit its +// coverage map as well. func unused() -> Int { 5 } // SIL: sil hidden @$s17coverage_deadcode6unusedSiyF : $@convention(thin) () -> Int @@ -11,4 +12,4 @@ func unused() -> Int { 5 } // IR: @__covrec // IR: @__llvm_coverage_mapping // IR: @__llvm_prf_nm -// IR-NOT: define {{.*}} @"$s17coverage_deadcode6unusedSiyF" +// IR: define {{.*}} @"$s17coverage_deadcode6unusedSiyF" diff --git a/test/Sanitizers/scudo.swift b/test/Sanitizers/scudo.swift index 69b8b838b88..99ed58f4ed4 100644 --- a/test/Sanitizers/scudo.swift +++ b/test/Sanitizers/scudo.swift @@ -1,5 +1,5 @@ // RUN: %target-swiftc_driver %s -g -sanitize=scudo -o %t_scudo-binary -// RUN: not %target-run %t_scudo-binary 2>&1 | %FileCheck %s +// RUN: not --crash %target-run %t_scudo-binary 2>&1 | %FileCheck %s // REQUIRES: executable_test // REQUIRES: OS=linux-gnu // REQUIRES: scudo_runtime diff --git a/test/stdlib/symbol-visibility-linux.test-sh b/test/stdlib/symbol-visibility-linux.test-sh index d2012cfd67c..c38bd92a2dd 100644 --- a/test/stdlib/symbol-visibility-linux.test-sh +++ b/test/stdlib/symbol-visibility-linux.test-sh @@ -249,6 +249,7 @@ // RUN: -e _ZStplIcSt11char_traitsIcESaIcEENSt7__cxx1112basic_stringIT_T0_T1_EEOS8_S9_ \ // RUN: -e _ZStplIcSt11char_traitsIcESaIcEESbIT_T0_T1_EOS6_PKS3_ \ // RUN: -e _ZStplIcSt11char_traitsIcESaIcEESbIT_T0_T1_EPKS3_OS6_ \ +// RUN: -e _ZNSt6vectorIjSaIjEE17_M_realloc_insertIJRKjEEEvN9__gnu_cxx17__normal_iteratorIPjS1_EEDpOT_ \ // RUN: > %t/swiftCore-all.txt // RUN: %llvm-nm --defined-only --extern-only --no-weak %platform-dylib-dir/%target-library-name(swiftCore) > %t/swiftCore-no-weak.txt // RUN: diff -u %t/swiftCore-all.txt %t/swiftCore-no-weak.txt @@ -496,6 +497,7 @@ // RUN: -e _ZStplIcSt11char_traitsIcESaIcEENSt7__cxx1112basic_stringIT_T0_T1_EEOS8_S9_ \ // RUN: -e _ZStplIcSt11char_traitsIcESaIcEESbIT_T0_T1_EOS6_PKS3_ \ // RUN: -e _ZStplIcSt11char_traitsIcESaIcEESbIT_T0_T1_EPKS3_OS6_ \ +// RUN: -e _ZNSt6vectorIjSaIjEE17_M_realloc_insertIJRKjEEEvN9__gnu_cxx17__normal_iteratorIPjS1_EEDpOT_ \ // RUN: > %t/swiftRemoteMirror-all.txt // RUN: %llvm-nm --defined-only --extern-only --no-weak %platform-dylib-dir/%target-library-name(swiftRemoteMirror) > %t/swiftRemoteMirror-no-weak.txt // RUN: diff -u %t/swiftRemoteMirror-all.txt %t/swiftRemoteMirror-no-weak.txt diff --git a/tools/SourceKit/include/SourceKit/Core/Context.h b/tools/SourceKit/include/SourceKit/Core/Context.h index c9e2e150896..2dedcc0928f 100644 --- a/tools/SourceKit/include/SourceKit/Core/Context.h +++ b/tools/SourceKit/include/SourceKit/Core/Context.h @@ -16,6 +16,7 @@ #include "SourceKit/Core/LLVM.h" #include "SourceKit/Support/CancellationToken.h" #include "SourceKit/Support/Concurrency.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/Mutex.h" diff --git a/tools/SourceKit/include/SourceKit/Core/LLVM.h b/tools/SourceKit/include/SourceKit/Core/LLVM.h index d19272cf919..4af9a92ff63 100644 --- a/tools/SourceKit/include/SourceKit/Core/LLVM.h +++ b/tools/SourceKit/include/SourceKit/Core/LLVM.h @@ -34,8 +34,8 @@ namespace llvm { template class ArrayRef; template class SmallString; template class SmallVector; - template class SmallVectorImpl; - template class Optional; + template + class SmallVectorImpl; template struct SaveAndRestore; diff --git a/tools/SourceKit/include/SourceKit/Core/LangSupport.h b/tools/SourceKit/include/SourceKit/Core/LangSupport.h index 2d66f6105cc..9a729e571fc 100644 --- a/tools/SourceKit/include/SourceKit/Core/LangSupport.h +++ b/tools/SourceKit/include/SourceKit/Core/LangSupport.h @@ -26,6 +26,7 @@ #include #include #include +#include namespace llvm { class MemoryBuffer; diff --git a/tools/SourceKit/lib/Support/Concurrency-libdispatch.cpp b/tools/SourceKit/lib/Support/Concurrency-libdispatch.cpp index b158e66ce98..f06ba4b9e07 100644 --- a/tools/SourceKit/lib/Support/Concurrency-libdispatch.cpp +++ b/tools/SourceKit/lib/Support/Concurrency-libdispatch.cpp @@ -10,8 +10,9 @@ // //===----------------------------------------------------------------------===// -#include "SourceKit/Support/Concurrency.h" #include "SourceKit/Config/config.h" +#include "SourceKit/Support/Concurrency.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/SmallString.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/thread.h" diff --git a/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp b/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp index 9f89e28c9a8..7bafd86fddc 100644 --- a/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp +++ b/tools/SourceKit/lib/SwiftLang/CodeCompletionOrganizer.cpp @@ -533,7 +533,7 @@ void CodeCompletionOrganizer::Impl::addCompletionsWithFilter( if (options.fuzzyMatching && filterText.size() >= options.minFuzzyLength) { match = pattern.matchesCandidate(completion->getFilterName()); } else { - match = completion->getFilterName().startswith_insensitive(filterText); + match = completion->getFilterName().starts_with_insensitive(filterText); } bool isExactMatch = diff --git a/tools/SourceKit/tools/sourcekitd-test/TestOptions.cpp b/tools/SourceKit/tools/sourcekitd-test/TestOptions.cpp index 9148acc26a4..125d65c3ee6 100644 --- a/tools/SourceKit/tools/sourcekitd-test/TestOptions.cpp +++ b/tools/SourceKit/tools/sourcekitd-test/TestOptions.cpp @@ -12,6 +12,7 @@ #include "TestOptions.h" #include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" @@ -36,7 +37,10 @@ enum Opt { }; // Create prefix string literals used in Options.td. -#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE; +#define PREFIX(NAME, VALUE) \ + constexpr llvm::StringLiteral NAME##_init[] = VALUE; \ + constexpr llvm::ArrayRef NAME( \ + NAME##_init, std::size(NAME##_init) - 1); #include "Options.inc" #undef PREFIX @@ -53,9 +57,9 @@ static const llvm::opt::OptTable::Info InfoTable[] = { }; // Create OptTable class for parsing actual command line arguments -class TestOptTable : public llvm::opt::OptTable { +class TestOptTable : public llvm::opt::GenericOptTable { public: - TestOptTable() : OptTable(InfoTable, std::size(InfoTable)){} + TestOptTable() : GenericOptTable(InfoTable) {} }; } // end anonymous namespace diff --git a/tools/SourceKit/tools/sourcekitd/lib/Service/Requests.cpp b/tools/SourceKit/tools/sourcekitd/lib/Service/Requests.cpp index dc9990e4ff1..4e3c322c28a 100644 --- a/tools/SourceKit/tools/sourcekitd/lib/Service/Requests.cpp +++ b/tools/SourceKit/tools/sourcekitd/lib/Service/Requests.cpp @@ -37,6 +37,7 @@ #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" +#include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" @@ -580,12 +581,12 @@ handleRequestGlobalConfiguration(const RequestDict &Req, ResponseBuilder RB; auto dict = RB.getDictionary(); - Optional CompletionMaxASTContextReuseCount = - Req.getOptionalInt64(KeyCompletionMaxASTContextReuseCount) - .transform([](int64_t v) -> unsigned { return v; }); - Optional CompletionCheckDependencyInterval = - Req.getOptionalInt64(KeyCompletionCheckDependencyInterval) - .transform([](int64_t v) -> unsigned { return v; }); + Optional CompletionMaxASTContextReuseCount = swift::transform( + Req.getOptionalInt64(KeyCompletionMaxASTContextReuseCount), + [](int64_t v) -> unsigned { return v; }); + Optional CompletionCheckDependencyInterval = swift::transform( + Req.getOptionalInt64(KeyCompletionCheckDependencyInterval), + [](int64_t v) -> unsigned { return v; }); GlobalConfig::Settings UpdatedConfig = Config->update(CompletionMaxASTContextReuseCount, @@ -1674,10 +1675,12 @@ handleRequestCollectVariableType(const RequestDict &Req, if (getCompilerArgumentsForRequestOrEmitError(Req, Args, Rec)) return; - Optional Offset = Req.getOptionalInt64(KeyOffset).transform( - [](int64_t v) -> unsigned { return v; }); - Optional Length = Req.getOptionalInt64(KeyLength).transform( - [](int64_t v) -> unsigned { return v; }); + Optional Offset = + swift::transform(Req.getOptionalInt64(KeyOffset), + [](int64_t v) -> unsigned { return v; }); + Optional Length = + swift::transform(Req.getOptionalInt64(KeyLength), + [](int64_t v) -> unsigned { return v; }); int64_t FullyQualified = false; Req.getInt64(KeyFullyQualified, FullyQualified, /*isOptional=*/true); return Lang.collectVariableTypes( diff --git a/tools/libMockPlugin/MockPlugin.cpp b/tools/libMockPlugin/MockPlugin.cpp index c554c149006..36c795c7670 100644 --- a/tools/libMockPlugin/MockPlugin.cpp +++ b/tools/libMockPlugin/MockPlugin.cpp @@ -11,6 +11,7 @@ //===----------------------------------------------------------------------===// #include "swift-c/MockPlugin/MockPlugin.h" +#include "llvm/ADT/StringExtras.h" #include "llvm/Support/Endian.h" #include "llvm/Support/JSON.h" diff --git a/tools/libSwiftScan/CMakeLists.txt b/tools/libSwiftScan/CMakeLists.txt index ced11bf4184..2fcd94db97e 100644 --- a/tools/libSwiftScan/CMakeLists.txt +++ b/tools/libSwiftScan/CMakeLists.txt @@ -93,10 +93,12 @@ else() ${CMAKE_INSTALL_PREFIX}/lib${LLVM_LIBDIR_SUFFIX}/swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR} ${CMAKE_INSTALL_PREFIX}/lib${LLVM_LIBDIR_SUFFIX}/swift/host/lib${SWIFT_SCAN_LIB_NAME}${CMAKE_SHARED_LIBRARY_SUFFIX}) message(STATUS "Installing symlink (${target_install_relative_path}) to lib${LLVM_LIBDIR_SUFFIX}/swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}/lib${SWIFT_SCAN_LIB_NAME}${CMAKE_SHARED_LIBRARY_SUFFIX}") + install(SCRIPT ${INSTALL_SYMLINK} CODE "install_symlink(lib${SWIFT_SCAN_LIB_NAME}${CMAKE_SHARED_LIBRARY_SUFFIX} ${target_install_relative_path} - lib${LLVM_LIBDIR_SUFFIX}/swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR})" + lib${LLVM_LIBDIR_SUFFIX}/swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR} + ${SWIFT_COPY_OR_SYMLINK})" COMPONENT compiler) endif() diff --git a/tools/libSwiftScan/libSwiftScan.cpp b/tools/libSwiftScan/libSwiftScan.cpp index ed3853b7768..43283041c15 100644 --- a/tools/libSwiftScan/libSwiftScan.cpp +++ b/tools/libSwiftScan/libSwiftScan.cpp @@ -605,7 +605,7 @@ static void addFrontendFlagOption(llvm::opt::OptTable &table, std::vector &frontendOptions) { if (table.getOption(id).hasFlag(swift::options::FrontendOption)) { auto name = table.getOptionName(id); - if (strlen(name) > 0) { + if (!name.empty()) { frontendOptions.push_back(std::string(name)); } } diff --git a/unittests/ClangImporter/ClangImporterTests.cpp b/unittests/ClangImporter/ClangImporterTests.cpp index 8bbcad21c89..53627d8dd7a 100644 --- a/unittests/ClangImporter/ClangImporterTests.cpp +++ b/unittests/ClangImporter/ClangImporterTests.cpp @@ -12,6 +12,7 @@ #include "llvm/Support/Path.h" #include "llvm/Support/VirtualOutputBackends.h" #include "llvm/Support/raw_ostream.h" +#include "llvm/TargetParser/Host.h" #include "gtest/gtest.h" using namespace swift; diff --git a/unittests/DependencyScan/Features.cpp b/unittests/DependencyScan/Features.cpp index 47e76bfe97b..a35315819cb 100644 --- a/unittests/DependencyScan/Features.cpp +++ b/unittests/DependencyScan/Features.cpp @@ -27,7 +27,7 @@ testHasOption(llvm::opt::OptTable &table, options::ID id, const std::unordered_set &optionSet) { if (table.getOption(id).hasFlag(swift::options::FrontendOption)) { auto name = table.getOptionName(id); - if (strlen(name) > 0) { + if (!name.empty() && name[0] != '\0') { auto nameStr = std::string(name); bool setContainsOption = optionSet.find(nameStr) != optionSet.end(); EXPECT_EQ(setContainsOption, true) << "Missing Option: " << nameStr; diff --git a/unittests/DependencyScan/ModuleDeps.cpp b/unittests/DependencyScan/ModuleDeps.cpp index a29539512ab..de84702f34f 100644 --- a/unittests/DependencyScan/ModuleDeps.cpp +++ b/unittests/DependencyScan/ModuleDeps.cpp @@ -13,7 +13,7 @@ #include "ScanFixture.h" #include "swift/Basic/Platform.h" #include "swift/Basic/Defer.h" -#include "llvm/ADT/Triple.h" +#include "llvm/TargetParser/Triple.h" #include "llvm/Support/Host.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" diff --git a/unittests/Parse/BuildConfigTests.cpp b/unittests/Parse/BuildConfigTests.cpp index c233c096c7f..ee9da1eaa0e 100644 --- a/unittests/Parse/BuildConfigTests.cpp +++ b/unittests/Parse/BuildConfigTests.cpp @@ -41,14 +41,14 @@ TEST_F(VersionTest, VersionComparison) { EXPECT_GE(currentVersion, currentVersion); EXPECT_GE(currentVersion, V("1.0").value()); EXPECT_GE(currentVersion, V("2").value()); - EXPECT_FALSE(V("2.n").hasValue()); - EXPECT_FALSE(V("").hasValue()); - EXPECT_FALSE(V("\"2.0\"").hasValue()); - EXPECT_FALSE(V("2..").hasValue()); - EXPECT_FALSE(V(".").hasValue()); - EXPECT_FALSE(V("..").hasValue()); - EXPECT_TRUE(V("1.").hasValue()); - EXPECT_FALSE(V(".1").hasValue()); + EXPECT_FALSE(V("2.n").has_value()); + EXPECT_FALSE(V("").has_value()); + EXPECT_FALSE(V("\"2.0\"").has_value()); + EXPECT_FALSE(V("2..").has_value()); + EXPECT_FALSE(V(".").has_value()); + EXPECT_FALSE(V("..").has_value()); + EXPECT_TRUE(V("1.").has_value()); + EXPECT_FALSE(V(".1").has_value()); } diff --git a/unittests/Sema/SemaFixture.h b/unittests/Sema/SemaFixture.h index 7856fce2147..a1add414dd3 100644 --- a/unittests/Sema/SemaFixture.h +++ b/unittests/Sema/SemaFixture.h @@ -23,7 +23,7 @@ #include "swift/SymbolGraphGen/SymbolGraphOptions.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/StringRef.h" -#include "llvm/Support/Host.h" +#include "llvm/TargetParser/Host.h" #include "llvm/Support/Path.h" #include "gtest/gtest.h" #include diff --git a/utils/build-presets.ini b/utils/build-presets.ini index bd3a312ae17..6f45edf775d 100644 --- a/utils/build-presets.ini +++ b/utils/build-presets.ini @@ -914,6 +914,10 @@ install-foundation install-libdispatch reconfigure +# gcc version on amazon linux 2 is too old to configure and build tablegen. +# Use the clang that we install in the path for macros +llvm-cmake-options=-DCROSS_TOOLCHAIN_FLAGS_LLVM_NATIVE='-DCMAKE_C_COMPILER=clang;-DCMAKE_CXX_COMPILER=clang++' + [preset: buildbot_linux] mixin-preset= mixin_lightweight_assertions,no-stdlib-asserts diff --git a/utils/build-windows-toolchain.bat b/utils/build-windows-toolchain.bat index d50e4d68f10..ae08dc559e3 100644 --- a/utils/build-windows-toolchain.bat +++ b/utils/build-windows-toolchain.bat @@ -209,6 +209,7 @@ cmake ^ -D CMAKE_Swift_COMPILER="%BuildRoot%/toolchains/5.9.0/Library/Developer/Toolchains/unknown-Asserts-development.xctoolchain/usr/bin/swiftc.exe" ^ -D CMAKE_Swift_FLAGS="-sdk %BuildRoot%/toolchains/5.9.0/Library/Developer/Platforms/Windows.platform/Developer/SDKs/Windows.sdk" ^ + -D SWIFT_CLANG_LOCATION="%BuildRoot%/toolchains/5.9.0/Library/Developer/Toolchains/unknown-Asserts-development.xctoolchain/usr/bin" ^ -D LLVM_DEFAULT_TARGET_TRIPLE=x86_64-unknown-windows-msvc ^ diff --git a/utils/build_swift/build_swift/defaults.py b/utils/build_swift/build_swift/defaults.py index 5bcc1942558..dfb5f99e6b4 100644 --- a/utils/build_swift/build_swift/defaults.py +++ b/utils/build_swift/build_swift/defaults.py @@ -47,7 +47,7 @@ CMAKE_GENERATOR = 'Ninja' COMPILER_VENDOR = 'none' SWIFT_USER_VISIBLE_VERSION = Version('5.11') -CLANG_USER_VISIBLE_VERSION = Version('15.0.0') +CLANG_USER_VISIBLE_VERSION = Version('17.0.0') SWIFT_ANALYZE_CODE_COVERAGE = 'false' DARWIN_XCRUN_TOOLCHAIN = 'default' diff --git a/utils/update_checkout/update-checkout-config.json b/utils/update_checkout/update-checkout-config.json index d14f13e8e9a..76e4f21c7b2 100644 --- a/utils/update_checkout/update-checkout-config.json +++ b/utils/update_checkout/update-checkout-config.json @@ -91,10 +91,10 @@ "default-branch-scheme": "main", "branch-schemes": { "main": { - "aliases": ["swift/main", "main", "stable/20221013"], + "aliases": ["swift/main", "main", "stable/20230725"], "repos": { - "llvm-project": "stable/20221013", - "swift-llvm-bindings": "stable/20221013", + "llvm-project": "stable/20230725", + "swift-llvm-bindings": "stable/20230725", "swift": "main", "cmark": "gfm", "llbuild": "main", @@ -179,7 +179,7 @@ } }, "rebranch": { - "aliases": ["rebranch", "stable/20230725"], + "aliases": ["rebranch"], "repos": { "llvm-project": "stable/20230725", "swift-llvm-bindings": "stable/20230725",