From 22311168e9a5e51f001da7eb61246ecd2656af4b Mon Sep 17 00:00:00 2001 From: Finagolfin Date: Mon, 4 Mar 2024 14:06:42 +0530 Subject: [PATCH] bump(swift): 5.10.1 to 6.0.2 --- packages/libdispatch/build.sh | 8 +- packages/llbuild/build.sh | 8 +- packages/swift/build.sh | 67 +- packages/swift/swift-android-ndk26.patch | 207 - packages/swift/swift-android-spawn.patch | 30 +- packages/swift/swift-arm-casts.patch | 26 + packages/swift/swift-arm.patch | 746 ++ .../swift/swift-change-library-lookup.patch | 2 +- packages/swift/swift-cmake.patch | 214 +- .../swift-crosscompile-swift-syntax.patch | 47 + .../swift/swift-deduplicate-libraries.patch | 30 + packages/swift/swift-foundation-armv7.patch | 168 + packages/swift/swift-foundation-ndk27.patch | 459 ++ packages/swift/swift-foundation.patch | 189 + packages/swift/swift-import-android.patch | 266 + .../swift/swift-lib-AST-ASTDumper.cpp.patch | 13 + .../swift-lib-Demangling-Errors.cpp.patch | 13 - packages/swift/swift-ndk27.patch | 62 + packages/swift/swift-pure-bridging.patch | 6451 ----------------- .../swift/swift-remove-relative-rpaths.patch | 50 +- .../swift/swift-runtime-aarch64.subpackage.sh | 2 +- .../swift/swift-runtime-arm.subpackage.sh | 2 +- .../swift/swift-runtime-x86-64.subpackage.sh | 2 +- .../swift/swift-sdk-aarch64.subpackage.sh | 10 +- packages/swift/swift-sdk-arm.subpackage.sh | 10 +- packages/swift/swift-sdk-x86-64.subpackage.sh | 10 +- packages/swift/swift-syntax.patch | 77 + .../swift-utils-build-script-impl-flags.patch | 41 +- packages/swift/trigger-command | 8 +- scripts/build/setup/termux_setup_swift.sh | 2 +- 30 files changed, 2277 insertions(+), 6943 deletions(-) delete mode 100644 packages/swift/swift-android-ndk26.patch create mode 100644 packages/swift/swift-arm-casts.patch create mode 100644 packages/swift/swift-arm.patch create mode 100644 packages/swift/swift-crosscompile-swift-syntax.patch create mode 100644 packages/swift/swift-deduplicate-libraries.patch create mode 100644 packages/swift/swift-foundation-armv7.patch create mode 100644 packages/swift/swift-foundation-ndk27.patch create mode 100644 packages/swift/swift-foundation.patch create mode 100644 packages/swift/swift-import-android.patch create mode 100644 packages/swift/swift-lib-AST-ASTDumper.cpp.patch delete mode 100644 packages/swift/swift-lib-Demangling-Errors.cpp.patch create mode 100644 packages/swift/swift-ndk27.patch delete mode 100644 packages/swift/swift-pure-bridging.patch create mode 100644 packages/swift/swift-syntax.patch diff --git a/packages/libdispatch/build.sh b/packages/libdispatch/build.sh index 741c427f537061..7885d1debfc74e 100644 --- a/packages/libdispatch/build.sh +++ b/packages/libdispatch/build.sh @@ -1,9 +1,9 @@ -TERMUX_PKG_HOMEPAGE=https://github.com/apple/swift-corelibs-libdispatch +TERMUX_PKG_HOMEPAGE=https://github.com/swiftlang/swift-corelibs-libdispatch TERMUX_PKG_DESCRIPTION="The libdispatch project, for concurrency on multicore hardware" TERMUX_PKG_LICENSE="Apache-2.0" TERMUX_PKG_MAINTAINER="@finagolfin" -TERMUX_PKG_VERSION="1:5.10" -TERMUX_PKG_SRCURL=https://github.com/apple/swift-corelibs-libdispatch/archive/swift-${TERMUX_PKG_VERSION:2}-RELEASE.tar.gz -TERMUX_PKG_SHA256=16e088cf12654d22658879710b9694a6fad1c94d5e5d0c597741b71fbcb3e034 +TERMUX_PKG_VERSION="1:6.0.2" +TERMUX_PKG_SRCURL=https://github.com/swiftlang/swift-corelibs-libdispatch/archive/swift-${TERMUX_PKG_VERSION:2}-RELEASE.tar.gz +TERMUX_PKG_SHA256=3df429b22d9294c0ca5291c86e83a35f6326600a1c271933107bba199b919008 TERMUX_PKG_AUTO_UPDATE=false TERMUX_PKG_DEPENDS="libc++, libblocksruntime" diff --git a/packages/llbuild/build.sh b/packages/llbuild/build.sh index 07dae2dfc81735..b5e6973a4cce30 100644 --- a/packages/llbuild/build.sh +++ b/packages/llbuild/build.sh @@ -1,9 +1,9 @@ -TERMUX_PKG_HOMEPAGE=https://github.com/apple/swift-llbuild +TERMUX_PKG_HOMEPAGE=https://github.com/swiftlang/swift-llbuild TERMUX_PKG_DESCRIPTION="A low-level build system, used by the Swift Package Manager" TERMUX_PKG_LICENSE="Apache-2.0, NCSA" TERMUX_PKG_MAINTAINER="@finagolfin" -TERMUX_PKG_VERSION=5.10 -TERMUX_PKG_SRCURL=https://github.com/apple/swift-llbuild/archive/swift-${TERMUX_PKG_VERSION}-RELEASE.tar.gz -TERMUX_PKG_SHA256=ae8962d59244abac157c02813d05e1c077915bbd6022fe9fb62040806ac8dc55 +TERMUX_PKG_VERSION=6.0.2 +TERMUX_PKG_SRCURL=https://github.com/swiftlang/swift-llbuild/archive/swift-${TERMUX_PKG_VERSION}-RELEASE.tar.gz +TERMUX_PKG_SHA256=40ada0511f0218fb3ca0478c8fff1b4d0958478056a0cc5408677753e8c8f7a7 TERMUX_PKG_DEPENDS="libc++, libandroid-spawn, libsqlite" TERMUX_PKG_NO_STATICSPLIT=true diff --git a/packages/swift/build.sh b/packages/swift/build.sh index 5de38335742b34..aec557c963bcf9 100644 --- a/packages/swift/build.sh +++ b/packages/swift/build.sh @@ -2,17 +2,23 @@ TERMUX_PKG_HOMEPAGE=https://swift.org/ TERMUX_PKG_DESCRIPTION="Swift is a high-performance system programming language" TERMUX_PKG_LICENSE="Apache-2.0, NCSA" TERMUX_PKG_MAINTAINER="@finagolfin" -TERMUX_PKG_VERSION=5.10.1 -TERMUX_PKG_REVISION=1 +TERMUX_PKG_VERSION=6.0.2 SWIFT_RELEASE="RELEASE" -TERMUX_PKG_SRCURL=https://github.com/apple/swift/archive/swift-$TERMUX_PKG_VERSION-$SWIFT_RELEASE.tar.gz -TERMUX_PKG_SHA256=087c59a1b79c46dd23f8e6cb4fe12a27935a5b6581282f48db952827bb3fdf57 +TERMUX_PKG_SRCURL=https://github.com/swiftlang/swift/archive/swift-$TERMUX_PKG_VERSION-$SWIFT_RELEASE.tar.gz +TERMUX_PKG_SHA256=1489681860e92cee5ddd869a06531d7a1746b2f4ea105a2ff3b631ebcbcffd34 TERMUX_PKG_AUTO_UPDATE=false TERMUX_PKG_HOSTBUILD=true -TERMUX_PKG_DEPENDS="clang, libandroid-glob, libandroid-posix-semaphore, libandroid-spawn, libcurl, libicu, libicu-static, libsqlite, libuuid, libxml2, libdispatch, llbuild, pkg-config, swift-sdk-${TERMUX_ARCH/_/-}" +TERMUX_PKG_DEPENDS="clang, libandroid-execinfo, libandroid-glob, libandroid-posix-semaphore, libandroid-shmem, libandroid-spawn, libandroid-spawn-static, libandroid-sysv-semaphore, libcurl, libsqlite, libuuid, libxml2, libdispatch, llbuild, pkg-config, swift-sdk-${TERMUX_ARCH/_/-}" TERMUX_PKG_BUILD_DEPENDS="rsync" TERMUX_PKG_BLACKLISTED_ARCHES="i686" TERMUX_PKG_NO_STATICSPLIT=true +# Temporary hack only needed for x86_64 +TERMUX_PKG_UNDEF_SYMBOLS_FILES=" +./opt/ndk-multilib/arm-linux-androideabi/lib/libFoundation.so +./opt/ndk-multilib/arm-linux-androideabi/lib/libFoundationNetworking.so +./opt/ndk-multilib/x86_64-linux-android/lib/libFoundation.so +./opt/ndk-multilib/x86_64-linux-android/lib/libFoundationNetworking.so +" # Building swift uses CMake, but the standard # termux_step_configure_cmake function is not used. Instead, we set # TERMUX_PKG_FORCE_CMAKE to make the build system aware that CMake is @@ -36,26 +42,28 @@ termux_step_post_get_source() { mv .temp swift declare -A library_checksums - library_checksums[swift-cmark]=6d209b8bf81fe0d67ae6d55913e7750ec752bc7fc29fc0ef5da2fdf8a6057406 - library_checksums[llvm-project]=fad2de34c6c005b7bc63ce7b4f20d6cdf0e1d60109a7a589ffd782180c23102b - library_checksums[swift-experimental-string-processing]=7e6ea60653b580abaf0801d697971610e7e22b4eb427edcee486b741b14d2724 - library_checksums[swift-syntax]=500ff2c6d9435311fa42ad2e87927a3025b6c3682c18ecb9710c522c0be52a53 - library_checksums[swift-corelibs-libdispatch]=affa3544b0fdb60f8f175bc0d2846177436d5848ef8ca73e3e560d23986f38b3 - library_checksums[swift-corelibs-foundation]=94dadc18f527f25cf1ce486d0ddce7de00f725063bc43526bdb73e534c8d97c3 - library_checksums[swift-corelibs-xctest]=cec269b435a9f32edcf90958abec16fcf50febcb99e389ed56e9e692c3270e27 - library_checksums[swift-llbuild]=64d135c1aaf96636b0ff6a2682e605474fe9e33f740a8ba2a3c469e2c8ae9f38 + library_checksums[swift-cmark]=2bfeab8747f4bcfea6aa70ed0494fe2185ec2532f1c9b7a0e17214cd401e9f31 + library_checksums[llvm-project]=991e9d63548a5ae8ce4fdda4052e98cb2bf2b193cafac8bbeea8f830f8cede96 + library_checksums[swift-experimental-string-processing]=e0380895e1cf5dc49aef321256f8192986185a6fa6ea83c143f171b643450fc0 + library_checksums[swift-syntax]=82cb7640775a23cf7483197f0cd6a6342a29a61d4bb75239905490bf47a64a75 + library_checksums[swift-corelibs-libdispatch]=3df429b22d9294c0ca5291c86e83a35f6326600a1c271933107bba199b919008 + library_checksums[swift-corelibs-foundation]=8af719f14a05cee2d32625cf455261fc74d13eeef3ba9e5b9547316743d5cde9 + library_checksums[swift-foundation]=a677ad3a712fb4d8330bccd28904aaa1b10749264d57ad9370215a89156ba1d3 + library_checksums[swift-foundation-icu]=a48f0d6f998ba6db710f89f0e987c4cf00f3845338afae116ab3e29c04dad127 + library_checksums[swift-corelibs-xctest]=a671062f178c68dd1fb0fdcf6a7c00589b343a63009a59b522206e03c9850d97 + library_checksums[swift-llbuild]=40ada0511f0218fb3ca0478c8fff1b4d0958478056a0cc5408677753e8c8f7a7 library_checksums[swift-argument-parser]=4a10bbef290a2167c5cc340b39f1f7ff6a8cf4e1b5433b68548bf5f1e542e908 - library_checksums[Yams]=ec1ad699c30f0db45520006c63a88cc1c946a7d7b36dff32a96460388c0a4af2 - library_checksums[swift-collections]=d0f584b197860db26fd939175c9d1a7badfe7b89949b4bd52d4f626089776e0a + library_checksums[Yams]=a81c6b93f5d26bae1b619b7f8babbfe7c8abacf95b85916961d488888df886fb + library_checksums[swift-collections]=cd30d2f93c72424df48d182006417abdeebe74d250cb99d1cda78daf40aca569 library_checksums[swift-crypto]=5c860c0306d0393ff06268f361aaf958656e1288353a0e23c3ad20de04319154 - library_checksums[swift-system]=865b8c380455eef27e73109835142920c60ae4c4f4178a3d12ad04acc83f1371 + library_checksums[swift-system]=02e13a7f77887c387f5aa1de05f4d4b8b158c35145450e1d9557d6c42b06cd1f library_checksums[swift-asn1]=e0da995ae53e6fcf8251887f44d4030f6600e2f8f8451d9c92fcaf52b41b6c35 library_checksums[swift-certificates]=fcaca458aab45ee69b0f678b72c2194b15664cc5f6f5e48d0e3f62bc5d1202ca - library_checksums[swift-driver]=75530eab66f4dffb9cecf422d0c5e582f08f84c8289ce245d48010e73ad1fc71 - library_checksums[swift-tools-support-core]=fbc2d5dcf4eb27e7e786a19559e4ab5af6469238e3e89b910511145874bdfc52 - library_checksums[swift-package-manager]=3d35e35b6e7a061042d3cd4913030525462faa357901a91a2d2f037d12e5987c - library_checksums[indexstore-db]=8be52307236e21e942972417fd3c8182a7865757f7890eec167851c75d156996 - library_checksums[sourcekit-lsp]=f83aabe6e66adc2d3ffb7e948ddfd805f7f58fd43c6b33d48bb4a50186ce0abb + library_checksums[swift-driver]=c6db9d058c8d5122f8e368087e397d59cf17ce5be686d4713025269658f0467e + library_checksums[swift-tools-support-core]=2f88a0790e9fe6fc0efa6a1fc1382d71c010126f871a6516ba56fb05dd1d23a0 + library_checksums[swift-package-manager]=00e40c3bce9b63fdd24d783909af003c7f86431898ee6b8bf44174d023d08402 + library_checksums[indexstore-db]=61f6d010edc11f31b5e01efb3628958501a1883b07ee4c741bbebc8c7d43d03d + library_checksums[sourcekit-lsp]=26175c4774f9817ad32c62c004ca76e9f09d8b77a253fca0e4eafdb33f33b2d2 for library in "${!library_checksums[@]}"; do \ GH_ORG="apple" @@ -69,19 +77,20 @@ termux_step_post_get_source() { SRC_VERSION="1.0.1" TAR_NAME=$SRC_VERSION elif [ "$library" = "swift-collections" ]; then - SRC_VERSION="1.0.5" + SRC_VERSION="1.1.2" TAR_NAME=$SRC_VERSION elif [ "$library" = "swift-crypto" ]; then SRC_VERSION="3.0.0" TAR_NAME=$SRC_VERSION elif [ "$library" = "swift-system" ]; then - SRC_VERSION="1.1.1" + SRC_VERSION="1.3.0" TAR_NAME=$SRC_VERSION elif [ "$library" = "Yams" ]; then GH_ORG="jpsim" - SRC_VERSION="5.0.1" + SRC_VERSION="5.0.6" TAR_NAME=$SRC_VERSION else + GH_ORG="swiftlang" SRC_VERSION=$SWIFT_RELEASE TAR_NAME=swift-$TERMUX_PKG_VERSION-$SWIFT_RELEASE fi @@ -127,6 +136,9 @@ termux_step_make() { if [ "$TERMUX_ON_DEVICE_BUILD" = "false" ]; then termux_setup_swift ln -sf $TERMUX_PKG_HOSTBUILD_DIR/llvm-linux-x86_64 $TERMUX_PKG_BUILDDIR/llvm-linux-x86_64 + for header in execinfo.h glob.h iconv.h spawn.h sys/sem.h sys/shm.h; do + ln -sf $TERMUX_PREFIX/include/$header $TERMUX_STANDALONE_TOOLCHAIN/sysroot/usr/include/$header + done SWIFT_BUILD_FLAGS="$SWIFT_BUILD_FLAGS --android --android-ndk $TERMUX_STANDALONE_TOOLCHAIN --android-arch $SWIFT_ARCH @@ -144,17 +156,20 @@ termux_step_make() { --swift-install-components=$SWIFT_COMPONENTS --llvm-install-components=IndexStore \ --install-llvm --install-swift --install-libdispatch --install-foundation \ --install-xctest --install-llbuild --install-swiftpm --install-swift-driver --install-sourcekit-lsp + + rm $TERMUX_STANDALONE_TOOLCHAIN/sysroot/usr/include/{execinfo.h,glob.h,iconv.h,spawn.h,sys/sem.h,sys/shm.h} } termux_step_make_install() { + rm -rf $TERMUX_PREFIX/lib/swift{,_static}/{Block,os} + rm $TERMUX_PREFIX/lib/swift{,_static}/dispatch/*.h rm $TERMUX_PREFIX/lib/swift/android/lib{dispatch,BlocksRuntime}.so mv $TERMUX_PREFIX/lib/swift/android/lib[^_]*.so $TERMUX_PREFIX/opt/ndk-multilib/$TERMUX_ARCH-linux-android*/lib + mv $TERMUX_PREFIX/lib/swift/android/lib_FoundationICU.so $TERMUX_PREFIX/opt/ndk-multilib/$TERMUX_ARCH-linux-android*/lib mv $TERMUX_PREFIX/lib/swift/android/lib*.a $TERMUX_PREFIX/lib/swift/android/$SWIFT_ARCH mv $TERMUX_PREFIX/lib/swift_static/android/lib*.a $TERMUX_PREFIX/lib/swift_static/android/$SWIFT_ARCH if [ "$TERMUX_ON_DEVICE_BUILD" = "false" ]; then rm $TERMUX_PREFIX/swiftpm-android-$SWIFT_ARCH.json - mv $TERMUX_PREFIX/glibc-native.modulemap \ - $TERMUX_PREFIX/lib/swift/android/$SWIFT_ARCH/glibc.modulemap fi } diff --git a/packages/swift/swift-android-ndk26.patch b/packages/swift/swift-android-ndk26.patch deleted file mode 100644 index e8467103e8e750..00000000000000 --- a/packages/swift/swift-android-ndk26.patch +++ /dev/null @@ -1,207 +0,0 @@ -diff --git a/swift/stdlib/cmake/modules/AddSwiftStdlib.cmake b/swift/stdlib/cmake/modules/AddSwiftStdlib.cmake -index 61447d50f08..b533b9291af 100644 ---- a/swift/stdlib/cmake/modules/AddSwiftStdlib.cmake -+++ b/swift/stdlib/cmake/modules/AddSwiftStdlib.cmake -@@ -522,7 +522,11 @@ function(_add_target_variant_link_flags) - # We need to add the math library, which is linked implicitly by libc++ - list(APPEND result "-lm") - if(NOT "${SWIFT_ANDROID_NDK_PATH}" STREQUAL "") -- file(GLOB RESOURCE_DIR ${SWIFT_SDK_ANDROID_ARCH_${LFLAGS_ARCH}_PATH}/../lib64/clang/*) -+ if("${SWIFT_ANDROID_NDK_PATH}" MATCHES "r26") -+ file(GLOB RESOURCE_DIR ${SWIFT_SDK_ANDROID_ARCH_${LFLAGS_ARCH}_PATH}/../lib/clang/*) -+ else() -+ file(GLOB RESOURCE_DIR ${SWIFT_SDK_ANDROID_ARCH_${LFLAGS_ARCH}_PATH}/../lib64/clang/*) -+ endif() - list(APPEND result "-resource-dir=${RESOURCE_DIR}") - endif() - -diff --git a/swift/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift b/swift/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift -index f8daa50325c..66be85a77f0 100644 ---- a/swift/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift -+++ b/swift/stdlib/private/SwiftPrivateLibcExtras/SwiftPrivateLibcExtras.swift -@@ -131,6 +131,8 @@ public func _stdlib_pipe() -> (readEnd: CInt, writeEnd: CInt, error: CInt) { - return _pipe(unsafeFds.baseAddress, 0, 0) - #elseif os(WASI) - preconditionFailure("No pipes available on WebAssembly/WASI") -+#elseif os(Android) -+ return pipe(unsafeFds.baseAddress!) - #else - return pipe(unsafeFds.baseAddress) - #endif -diff --git a/swift/stdlib/public/SwiftShims/swift/shims/LibcShims.h b/swift/stdlib/public/SwiftShims/swift/shims/LibcShims.h -index 1e4132f6279..045b8a28746 100644 ---- a/swift/stdlib/public/SwiftShims/swift/shims/LibcShims.h -+++ b/swift/stdlib/public/SwiftShims/swift/shims/LibcShims.h -@@ -61,7 +61,7 @@ SWIFT_READONLY - static inline int _swift_stdlib_memcmp(const void *s1, const void *s2, - __swift_size_t n) { - // FIXME: Is there a way to identify Glibc specifically? --#if defined(__gnu_linux__) -+#if defined(__gnu_linux__) || defined(__ANDROID__) - extern int memcmp(const void * _Nonnull, const void * _Nonnull, __swift_size_t); - #else - extern int memcmp(const void * _Null_unspecified, const void * _Null_unspecified, __swift_size_t); -diff --git a/swift-corelibs-foundation/Sources/Foundation/FileHandle.swift b/swift-corelibs-foundation/Sources/Foundation/FileHandle.swift -index a538a297..0a757c4b 100644 ---- a/swift-corelibs-foundation/Sources/Foundation/FileHandle.swift -+++ b/swift-corelibs-foundation/Sources/Foundation/FileHandle.swift -@@ -310,9 +310,15 @@ open class FileHandle : NSObject { - let data = mmap(nil, mapSize, PROT_READ, MAP_PRIVATE, _fd, 0) - // Swift does not currently expose MAP_FAILURE - if data != UnsafeMutableRawPointer(bitPattern: -1) { -+ #if os(Android) -+ return NSData.NSDataReadResult(bytes: data, length: mapSize) { buffer, length in -+ munmap(buffer, length) -+ } -+ #else - return NSData.NSDataReadResult(bytes: data!, length: mapSize) { buffer, length in - munmap(buffer, length) - } -+ #endif - } - } - -diff --git a/swift-corelibs-foundation/Sources/Foundation/FileManager+POSIX.swift b/swift-corelibs-foundation/Sources/Foundation/FileManager+POSIX.swift -index d90ece91..d2bbd22b 100644 ---- a/swift-corelibs-foundation/Sources/Foundation/FileManager+POSIX.swift -+++ b/swift-corelibs-foundation/Sources/Foundation/FileManager+POSIX.swift -@@ -741,20 +741,26 @@ extension FileManager { - if rmdir(fsRep) == 0 { - return - } else if errno == ENOTEMPTY { -+ #if os(Android) -+ let ps = UnsafeMutablePointer>.allocate(capacity: 2) -+ ps.initialize(to: UnsafeMutablePointer(mutating: fsRep)) -+ ps.advanced(by: 1).initialize(to: unsafeBitCast(0, to: UnsafeMutablePointer.self)) -+ #else - let ps = UnsafeMutablePointer?>.allocate(capacity: 2) - ps.initialize(to: UnsafeMutablePointer(mutating: fsRep)) - ps.advanced(by: 1).initialize(to: nil) -+ #endif - let stream = fts_open(ps, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR | FTS_NOSTAT, nil) - ps.deinitialize(count: 2) - ps.deallocate() - -- if stream != nil { -+ if let openStream = stream { - defer { -- fts_close(stream) -+ fts_close(openStream) - } - -- while let current = fts_read(stream)?.pointee { -- let itemPath = string(withFileSystemRepresentation: current.fts_path, length: Int(current.fts_pathlen)) -+ while let current = fts_read(openStream)?.pointee, let current_path = current.fts_path { -+ let itemPath = string(withFileSystemRepresentation: current_path, length: Int(current.fts_pathlen)) - guard alreadyConfirmed || shouldRemoveItemAtPath(itemPath, isURL: isURL) else { - continue - } -@@ -762,11 +768,11 @@ extension FileManager { - do { - switch Int32(current.fts_info) { - case FTS_DEFAULT, FTS_F, FTS_NSOK, FTS_SL, FTS_SLNONE: -- if unlink(current.fts_path) == -1 { -+ if unlink(current_path) == -1 { - throw _NSErrorWithErrno(errno, reading: false, path: itemPath) - } - case FTS_DP: -- if rmdir(current.fts_path) == -1 { -+ if rmdir(current_path) == -1 { - throw _NSErrorWithErrno(errno, reading: false, path: itemPath) - } - case FTS_DNR, FTS_ERR, FTS_NS: -@@ -1085,10 +1091,18 @@ extension FileManager { - do { - guard fm.fileExists(atPath: _url.path) else { throw _NSErrorWithErrno(ENOENT, reading: true, url: url) } - _stream = try FileManager.default._fileSystemRepresentation(withPath: _url.path) { fsRep in -+ #if os(Android) -+ let ps = UnsafeMutablePointer>.allocate(capacity: 2) -+ #else - let ps = UnsafeMutablePointer?>.allocate(capacity: 2) -+ #endif - defer { ps.deallocate() } - ps.initialize(to: UnsafeMutablePointer(mutating: fsRep)) -+ #if os(Android) -+ ps.advanced(by: 1).initialize(to: unsafeBitCast(0, to: UnsafeMutablePointer.self)) -+ #else - ps.advanced(by: 1).initialize(to: nil) -+ #endif - return fts_open(ps, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR | FTS_NOSTAT, nil) - } - if _stream == nil { -@@ -1135,14 +1149,14 @@ extension FileManager { - } - - _current = fts_read(stream) -- while let current = _current { -- let filename = FileManager.default.string(withFileSystemRepresentation: current.pointee.fts_path, length: Int(current.pointee.fts_pathlen)) -+ while let current = _current, let current_path = current.pointee.fts_path { -+ let filename = FileManager.default.string(withFileSystemRepresentation: current_path, length: Int(current.pointee.fts_pathlen)) - - switch Int32(current.pointee.fts_info) { - case FTS_D: - let (showFile, skipDescendants) = match(filename: filename, to: _options, isDir: true) - if skipDescendants { -- fts_set(_stream, _current, FTS_SKIP) -+ fts_set(stream, current, FTS_SKIP) - } - if showFile { - return URL(fileURLWithPath: filename, isDirectory: true) -@@ -1315,7 +1329,7 @@ extension FileManager { - let finalErrno = originalItemURL.withUnsafeFileSystemRepresentation { (originalFS) -> Int32? in - return newItemURL.withUnsafeFileSystemRepresentation { (newItemFS) -> Int32? in - // This is an atomic operation in many OSes, but is not guaranteed to be atomic by the standard. -- if rename(newItemFS, originalFS) == 0 { -+ if let newFS = newItemFS, let origFS = originalFS, rename(newFS, origFS) == 0 { - return nil - } else { - return errno -diff --git a/swift-corelibs-foundation/Sources/Foundation/FileManager.swift b/swift-corelibs-foundation/Sources/Foundation/FileManager.swift -index 1aa3038a..9fdb495c 100644 ---- a/swift-corelibs-foundation/Sources/Foundation/FileManager.swift -+++ b/swift-corelibs-foundation/Sources/Foundation/FileManager.swift -@@ -568,13 +568,13 @@ open class FileManager : NSObject { - let attributes = try windowsFileAttributes(atPath: path) - let type = FileAttributeType(attributes: attributes, atPath: path) - #else -- if let pwd = getpwuid(s.st_uid), pwd.pointee.pw_name != nil { -- let name = String(cString: pwd.pointee.pw_name) -+ if let pwd = getpwuid(s.st_uid), let pwd_name = pwd.pointee.pw_name { -+ let name = String(cString: pwd_name) - result[.ownerAccountName] = name - } - -- if let grd = getgrgid(s.st_gid), grd.pointee.gr_name != nil { -- let name = String(cString: grd.pointee.gr_name) -+ if let grd = getgrgid(s.st_gid), let grd_name = grd.pointee.gr_name { -+ let name = String(cString: grd_name) - result[.groupOwnerAccountName] = name - } - -diff --git a/swift-corelibs-foundation/Sources/Foundation/Host.swift b/swift-corelibs-foundation/Sources/Foundation/Host.swift -index 5fe7b29c..ce571abe 100644 ---- a/swift-corelibs-foundation/Sources/Foundation/Host.swift -+++ b/swift-corelibs-foundation/Sources/Foundation/Host.swift -@@ -25,7 +25,8 @@ import WinSDK - - // getnameinfo uses size_t for its 4th and 6th arguments. - private func getnameinfo(_ addr: UnsafePointer?, _ addrlen: socklen_t, _ host: UnsafeMutablePointer?, _ hostlen: socklen_t, _ serv: UnsafeMutablePointer?, _ servlen: socklen_t, _ flags: Int32) -> Int32 { -- return Glibc.getnameinfo(addr, addrlen, host, Int(hostlen), serv, Int(servlen), flags) -+ guard let saddr = addr else { return -1 } -+ return Glibc.getnameinfo(saddr, addrlen, host, Int(hostlen), serv, Int(servlen), flags) - } - - // getifaddrs and freeifaddrs are not available in Android 6.0 or earlier, so call these functions dynamically. -diff --git a/swift-driver/Sources/SwiftDriver/Driver/ToolExecutionDelegate.swift b/swift-driver/Sources/SwiftDriver/Driver/ToolExecutionDelegate.swift -index 4d6577d0..aa22dade 100644 ---- a/swift-driver/Sources/SwiftDriver/Driver/ToolExecutionDelegate.swift -+++ b/swift-driver/Sources/SwiftDriver/Driver/ToolExecutionDelegate.swift -@@ -136,7 +136,7 @@ import var TSCBasic.stdoutStream - } - #else - case .signalled(let signal): -- let errorMessage = strsignal(signal).map { String(cString: $0) } ?? "" -+ let errorMessage = String(cString: strsignal(signal)) ?? "" - messages = constructJobSignalledMessages(job: job, error: errorMessage, output: output, - signal: signal, pid: pid).map { - ParsableMessage(name: job.kind.rawValue, kind: .signalled($0)) diff --git a/packages/swift/swift-android-spawn.patch b/packages/swift/swift-android-spawn.patch index b1ab87e6bd8393..c116b972501061 100644 --- a/packages/swift/swift-android-spawn.patch +++ b/packages/swift/swift-android-spawn.patch @@ -37,20 +37,30 @@ diff --git a/swift-corelibs-foundation/Sources/Foundation/CMakeLists.txt b/swift index 016bf294..cd534f16 100644 --- a/swift-corelibs-foundation/Sources/Foundation/CMakeLists.txt +++ b/swift-corelibs-foundation/Sources/Foundation/CMakeLists.txt -@@ -166,6 +166,13 @@ if(CMAKE_SYSTEM_NAME STREQUAL Windows) - $) - elseif(NOT CMAKE_SYSTEM_NAME STREQUAL Darwin) - target_link_options(Foundation PRIVATE "SHELL:-no-toolchain-stdlib-rpath") -+ if(${CMAKE_SYSTEM_NAME} STREQUAL Android) -+ target_link_libraries(Foundation PRIVATE android-spawn) -+ if(CMAKE_FIND_ROOT_PATH) -+ target_include_directories(Foundation PUBLIC ${CMAKE_FIND_ROOT_PATH}/usr/include) -+ target_link_directories(Foundation PUBLIC ${CMAKE_FIND_ROOT_PATH}/usr/lib) +@@ -162,6 +162,10 @@ if(NOT BUILD_SHARED_LIBS) + "SHELL:$<$:-Xfrontend -public-autolink-library -Xfrontend _FoundationICU>") + target_compile_options(Foundation PRIVATE + "SHELL:$<$:-Xfrontend -public-autolink-library -Xfrontend swiftSynchronization>") ++ if(${CMAKE_SYSTEM_NAME} STREQUAL Android) ++ target_compile_options(Foundation PRIVATE ++ "SHELL:$<$:-Xfrontend -public-autolink-library -Xfrontend android-spawn>") + endif() -+ endif() endif() + set_target_properties(Foundation PROPERTIES +@@ -174,6 +174,12 @@ + target_link_libraries(Foundation PUBLIC + swiftDispatch) + endif() ++ if(${CMAKE_SYSTEM_NAME} STREQUAL Android) ++ target_link_libraries(Foundation PRIVATE android-spawn) ++ list(GET CMAKE_FIND_ROOT_PATH 0 SPAWN_DIR) ++ target_include_directories(Foundation PUBLIC ${SPAWN_DIR}/usr/include) ++ target_link_directories(Foundation PUBLIC ${SPAWN_DIR}/usr/lib) ++ endif() + if(LINKER_SUPPORTS_BUILD_ID) + target_link_options(Foundation PRIVATE "LINKER:--build-id=sha1") diff --git a/swift-driver/Utilities/build-script-helper.py b/swift-driver/Utilities/build-script-helper.py index 18f22fb0..bc2b1308 100755 --- a/swift-driver/Utilities/build-script-helper.py diff --git a/packages/swift/swift-arm-casts.patch b/packages/swift/swift-arm-casts.patch new file mode 100644 index 00000000000000..d4b21fec01c747 --- /dev/null +++ b/packages/swift/swift-arm-casts.patch @@ -0,0 +1,26 @@ +diff --git a/swift/include/swift/AST/Attr.h b/swift/include/swift/AST/Attr.h +index 0255b38af1b..3949e62e750 100644 +--- a/swift/include/swift/AST/Attr.h ++++ b/swift/include/swift/AST/Attr.h +@@ -2661,7 +2661,7 @@ public: + + ArrayRef getSuppressedFeatures() const { + return {getTrailingObjects(), +- Bits.AllowFeatureSuppressionAttr.NumFeatures}; ++ static_cast(Bits.AllowFeatureSuppressionAttr.NumFeatures)}; + } + + static bool classof(const DeclAttribute *DA) { +diff --git a/swift/lib/ExternalGenericMetadataBuilder/ExternalGenericMetadataBuilder.cpp b/swift/lib/ExternalGenericMetadataBuilder/ExternalGenericMetadataBuilder.cpp +index 7617abe7ee7..a0016e575c7 100644 +--- a/swift/lib/ExternalGenericMetadataBuilder/ExternalGenericMetadataBuilder.cpp ++++ b/swift/lib/ExternalGenericMetadataBuilder/ExternalGenericMetadataBuilder.cpp +@@ -1488,7 +1488,7 @@ template + llvm::Error ExternalGenericMetadataBuilderContext::addImageInMemory( + const void *start, uint64_t length, const std::string &path) { + LOG(LogLevel::Info, "Adding %s in memory", path.c_str()); +- llvm::StringRef stringRef{reinterpret_cast(start), length}; ++ llvm::StringRef stringRef{reinterpret_cast(start), static_cast(length)}; + llvm::MemoryBufferRef bufferRef{stringRef, {}}; + auto binary = llvm::object::createBinary(bufferRef); + if (!binary) diff --git a/packages/swift/swift-arm.patch b/packages/swift/swift-arm.patch new file mode 100644 index 00000000000000..2824510464cb48 --- /dev/null +++ b/packages/swift/swift-arm.patch @@ -0,0 +1,746 @@ +From 7afa419dd47cc537c02b788dd3e0428749d38cd0 +From: Erik Eckstein +Date: Thu, 21 Mar 2024 15:19:33 +0100 +Subject: SIL: improve inline bitfields in SILNode, SILBasicBlock + and Operand + +* Let the customBits and lastInitializedBitfieldID share a single uint64_t. This increases the number of available bits in SILNode and Operand from 8 to 20. Also, it simplifies the Operand class because no PointerIntPairs are used anymore to store the operand pointer fields. +* Instead make the "deleted" flag a separate bool field in SILNode (instead of encoding it with the sign of lastInitializedBitfieldID). Another simplification +* Enable important invariant checks also in release builds by using `require` instead of `assert`. Not catching such errors in release builds would be a disaster. +* Let the Swift optimization passes use all the available bits and not only a fixed amount of 8 (SILNode) and 16 (SILBasicBlock). + +diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/DataStructures/Set.swift b/swift/SwiftCompilerSources/Sources/Optimizer/DataStructures/Set.swift +index 4cb20cbe2cc76..d2ab37357656e 100644 +--- a/swift/SwiftCompilerSources/Sources/Optimizer/DataStructures/Set.swift ++++ b/swift/SwiftCompilerSources/Sources/Optimizer/DataStructures/Set.swift +@@ -176,3 +176,55 @@ struct InstructionSet : IntrusiveSet { + context.freeNodeSet(bridged) + } + } ++ ++/// A set of operands. ++/// ++/// This is an extremely efficient implementation which does not need memory ++/// allocations or hash lookups. ++/// ++/// This type should be a move-only type, but unfortunately we don't have move-only ++/// types yet. Therefore it's needed to call `deinitialize()` explicitly to ++/// destruct this data structure, e.g. in a `defer {}` block. ++struct OperandSet : IntrusiveSet { ++ ++ private let context: BridgedPassContext ++ private let bridged: BridgedOperandSet ++ ++ init(_ context: some Context) { ++ self.context = context._bridged ++ self.bridged = self.context.allocOperandSet() ++ } ++ ++ func contains(_ operand: Operand) -> Bool { ++ bridged.contains(operand.bridged) ++ } ++ ++ /// Returns true if `inst` was not contained in the set before inserting. ++ @discardableResult ++ mutating func insert(_ operand: Operand) -> Bool { ++ bridged.insert(operand.bridged) ++ } ++ ++ mutating func erase(_ operand: Operand) { ++ bridged.erase(operand.bridged) ++ } ++ ++ var description: String { ++ let function = bridged.getFunction().function ++ var d = "{\n" ++ for inst in function.instructions { ++ for op in inst.operands { ++ if contains(op) { ++ d += op.description ++ } ++ } ++ } ++ d += "}\n" ++ return d ++ } ++ ++ /// TODO: once we have move-only types, make this a real deinit. ++ mutating func deinitialize() { ++ context.freeOperandSet(bridged) ++ } ++} +diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/DataStructures/Worklist.swift b/swift/SwiftCompilerSources/Sources/Optimizer/DataStructures/Worklist.swift +index c36002ab59e8b..a5d1a00ff9ec3 100644 +--- a/swift/SwiftCompilerSources/Sources/Optimizer/DataStructures/Worklist.swift ++++ b/swift/SwiftCompilerSources/Sources/Optimizer/DataStructures/Worklist.swift +@@ -75,3 +75,4 @@ struct Worklist : CustomStringConvertible, NoReflectionChildr + typealias BasicBlockWorklist = Worklist + typealias InstructionWorklist = Worklist + typealias ValueWorklist = Worklist ++typealias OperandWorklist = Worklist +diff --git a/swift/SwiftCompilerSources/Sources/SIL/Operand.swift b/swift/SwiftCompilerSources/Sources/SIL/Operand.swift +index f3369ae01a843..d353cf45aef6a 100644 +--- a/swift/SwiftCompilerSources/Sources/SIL/Operand.swift ++++ b/swift/SwiftCompilerSources/Sources/SIL/Operand.swift +@@ -14,7 +14,7 @@ import SILBridging + + /// An operand of an instruction. + public struct Operand : CustomStringConvertible, NoReflectionChildren { +- fileprivate let bridged: BridgedOperand ++ public let bridged: BridgedOperand + + public init(bridged: BridgedOperand) { + self.bridged = bridged +diff --git a/swift/include/swift/Basic/Require.h b/swift/include/swift/Basic/Require.h +new file mode 100644 +index 0000000000000..54d1aed574c59 +--- /dev/null ++++ b/swift/include/swift/Basic/Require.h +@@ -0,0 +1,34 @@ ++//===--- Require.h ----------------------------------------------*- C++ -*-===// ++// ++// This source file is part of the Swift.org open source project ++// ++// Copyright (c) 2014 - 2024 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 defines swift_unreachable, which provides the ++// functionality of llvm_unreachable without necessarily depending on ++// the LLVM support libraries. ++// ++//===----------------------------------------------------------------------===// ++ ++#ifndef SWIFT_BASIC_REQUIRE_H ++#define SWIFT_BASIC_REQUIRE_H ++ ++#include "llvm/Support/raw_ostream.h" ++namespace swift { ++/// Checks the `condition` and if it's false abort with `message`. ++/// In contrast to `assert` and similar functions, `require` works in ++/// no-assert builds the same way as in debug builds. ++inline void require(bool condition, const char *message) { ++ if (!condition) { ++ llvm::errs() << message << '\n'; ++ abort(); ++ } ++} ++} ++#endif +diff --git a/swift/include/swift/SIL/SILBasicBlock.h b/swift/include/swift/SIL/SILBasicBlock.h +index d1a72d5a6f683..ddd81e02b89e6 100644 +--- a/swift/include/swift/SIL/SILBasicBlock.h ++++ b/swift/include/swift/SIL/SILBasicBlock.h +@@ -130,16 +130,13 @@ public SwiftObjectHeader { + /// DD and EEE are uninitialized + /// + /// See also: SILBitfield::bitfieldID, SILFunction::currentBitfieldID. +- int64_t lastInitializedBitfieldID = 0; ++ uint64_t lastInitializedBitfieldID = 0; + + // Used by `BasicBlockBitfield`. + unsigned getCustomBits() const { return customBits; } + // Used by `BasicBlockBitfield`. + void setCustomBits(unsigned value) { customBits = value; } + +- // Used by `BasicBlockBitfield`. +- enum { numCustomBits = std::numeric_limits::digits }; +- + friend struct llvm::ilist_traits; + + SILBasicBlock(); +@@ -155,7 +152,8 @@ public SwiftObjectHeader { + + ~SILBasicBlock(); + +- bool isMarkedAsDeleted() const { return lastInitializedBitfieldID < 0; } ++ enum { numCustomBits = std::numeric_limits::digits }; ++ enum { maxBitfieldID = std::numeric_limits::max() }; + + /// Gets the ID (= index in the function's block list) of the block. + /// +diff --git a/swift/include/swift/SIL/SILBitfield.h b/swift/include/swift/SIL/SILBitfield.h +index 7e445a72b5262..148c0109a9924 100644 +--- a/swift/include/swift/SIL/SILBitfield.h ++++ b/swift/include/swift/SIL/SILBitfield.h +@@ -17,6 +17,7 @@ + #ifndef SWIFT_SIL_SILBITFIELD_H + #define SWIFT_SIL_SILBITFIELD_H + ++#include "swift/Basic/Require.h" + #include "swift/SIL/SILFunction.h" + + namespace swift { +@@ -30,7 +31,7 @@ template class SILBitfield { + /// that the bits of that block are not initialized yet. + /// See also: SILBasicBlock::lastInitializedBitfieldID, + /// SILFunction::currentBitfieldID +- int64_t bitfieldID; ++ uint64_t bitfieldID; + + short startBit; + short endBit; +@@ -55,11 +56,13 @@ template class SILBitfield { + parent(parent), + function(function) { + assert(size > 0 && "bit field size must be > 0"); +- assert(endBit <= T::numCustomBits && "too many/large bit fields allocated in function"); ++ require(endBit <= T::numCustomBits, ++ "too many/large bit fields allocated in function"); + assert((!parent || bitfieldID > parent->bitfieldID) && + "BasicBlockBitfield indices are not in order"); ++ require(function->currentBitfieldID < T::maxBitfieldID, ++ "currentBitfieldID overflow"); + ++function->currentBitfieldID; +- assert(function->currentBitfieldID != 0 && "currentBitfieldID overflow"); + } + + SILBitfield(const SILBitfield &) = delete; +@@ -85,9 +88,6 @@ template class SILBitfield { + unsigned clearMask = mask; + if (bitfieldID > entity->lastInitializedBitfieldID) { + +- if (entity->isMarkedAsDeleted()) +- return; +- + // The bitfield is not initialized yet in this block. + // Initialize the bitfield, and also initialize all parent bitfields, + // which are not initialized, yet. Example: +diff --git a/swift/include/swift/SIL/SILFunction.h b/swift/include/swift/SIL/SILFunction.h +index 27fd1b5d91505..a624914c7574f 100644 +--- a/swift/include/swift/SIL/SILFunction.h ++++ b/swift/include/swift/SIL/SILFunction.h +@@ -294,7 +294,7 @@ class SILFunction + /// A monotonically increasing ID which is incremented whenever a + /// BasicBlockBitfield, NodeBitfield, or OperandBitfield is constructed. For + /// details see SILBitfield::bitfieldID; +- int64_t currentBitfieldID = 1; ++ uint64_t currentBitfieldID = 1; + + /// Unique identifier for vector indexing and deterministic sorting. + /// May be reused when zombie functions are recovered. +diff --git a/swift/include/swift/SIL/SILNode.h b/swift/include/swift/SIL/SILNode.h +index 74f8ac228970b..b72705f5e8324 100644 +--- a/swift/include/swift/SIL/SILNode.h ++++ b/swift/include/swift/SIL/SILNode.h +@@ -126,6 +126,9 @@ class alignas(8) SILNode : + enum { NumAllocRefTailTypesBits = 4 }; + enum { NumMarkDependenceKindBits = 2 }; + ++ enum { numCustomBits = 20 }; ++ enum { maxBitfieldID = std::numeric_limits::max() >> numCustomBits }; ++ + protected: + friend class SILInstruction; + template friend class SILBitfield; +@@ -135,11 +138,7 @@ class alignas(8) SILNode : + + uint8_t kind; + +- // Used by `NodeBitfield`. +- enum { numCustomBits = 8 }; +- +- // Used by `NodeBitfield`. +- uint8_t customBits; ++ bool deleted = false; + + // Part of SILInstruction's debug location. Together with + // `SILInstruction::locationStorage` this forms the SILLocation. +@@ -364,6 +363,9 @@ class alignas(8) SILNode : + + //===---------------------- end of shared fields ------------------------===// + ++ // Used by `NodeBitfield`. ++ uint64_t customBits : numCustomBits; ++ + /// The NodeBitfield ID of the last initialized bitfield in `customBits`. + /// Example: + /// +@@ -377,20 +379,19 @@ class alignas(8) SILNode : + /// -> AAA, BB and C are initialized, + /// DD and EEE are uninitialized + /// +- /// If the ID is negative, it means that the node (in case it's an instruction) +- /// is deleted, i.e. it does not belong to the function anymore. Conceptually +- /// this results in setting all bitfields to zero, which e.g. "removes" the +- /// node from all NodeSets. ++ /// The size of lastInitializedBitfieldID should be more than 32 bits to ++ /// absolutely avoid an overflow. + /// + /// See also: SILBitfield::bitfieldID, SILFunction::currentBitfieldID. +- int64_t lastInitializedBitfieldID = 0; ++ uint64_t lastInitializedBitfieldID : (64 - numCustomBits); + + private: + SwiftMetatype getSILNodeMetatype(SILNodeKind kind); + + protected: + SILNode(SILNodeKind kind) : SwiftObjectHeader(getSILNodeMetatype(kind)), +- kind((uint8_t)kind) { ++ kind((uint8_t)kind), ++ customBits(0), lastInitializedBitfieldID(0) { + _sharedUInt8_private.opaque = 0; + _sharedUInt32_private.opaque = 0; + } +@@ -442,11 +443,8 @@ class alignas(8) SILNode : + lastInitializedBitfieldID = 0; + } + +- void markAsDeleted() { +- lastInitializedBitfieldID = -1; +- } +- +- bool isMarkedAsDeleted() const { return lastInitializedBitfieldID < 0; } ++ void markAsDeleted() { deleted = true; } ++ bool isMarkedAsDeleted() const { return deleted; } + + static SILNode *instAsNode(SILInstruction *inst); + static const SILNode *instAsNode(const SILInstruction *inst); +diff --git a/swift/include/swift/SIL/SILValue.h b/swift/include/swift/SIL/SILValue.h +index 5916b686b76dd..756e96e95ae58 100644 +--- a/swift/include/swift/SIL/SILValue.h ++++ b/swift/include/swift/SIL/SILValue.h +@@ -1019,38 +1019,40 @@ ValueOwnershipKind::getForwardingOperandOwnership(bool allowUnowned) const { + /// A formal SIL reference to a value, suitable for use as a stored + /// operand. + class Operand { ++public: ++ enum { numCustomBits = 8 }; ++ enum { maxBitfieldID = std::numeric_limits::max() >> numCustomBits }; ++ ++private: + template friend class SILBitfield; + +- /// The value used as this operand combined with three bits we use for +- /// `customBits`. +- llvm::PointerIntPair TheValueAndThreeBits = {SILValue(), 0}; ++ /// The value used as this operand. ++ SILValue TheValue; + +- /// The next operand in the use-chain. Note that the chain holds every use of +- /// the current ValueBase, not just those of the designated result. +- /// +- /// We use 3 bits of the pointer for customBits. +- llvm::PointerIntPair NextUseAndThreeBits = {nullptr, 0}; ++ /// The next operand in the use-chain. Note that the chain holds ++ /// every use of the current ValueBase, not just those of the ++ /// designated result. ++ Operand *NextUse = nullptr; + + /// A back-pointer in the use-chain, required for fast patching + /// of use-chains. +- /// +- /// We use 2 bits of the pointer for customBits. +- llvm::PointerIntPair BackAndThreeBits = {nullptr, 0}; ++ Operand **Back = nullptr; + + /// The owner of this operand. + /// FIXME: this could be space-compressed. + SILInstruction *Owner; + +- /// Used by `OperandBitfield` +- enum { numCustomBits = 8 }; ++ uint64_t customBits : numCustomBits; + +- /// Used by `OperandBitfield` +- int64_t lastInitializedBitfieldID = 0; ++ // For details see SILNode::lastInitializedBitfieldID ++ uint64_t lastInitializedBitfieldID : (64 - numCustomBits); + + public: +- Operand(SILInstruction *owner) : Owner(owner) {} ++ Operand(SILInstruction *owner) ++ : Owner(owner), customBits(0), lastInitializedBitfieldID(0) {} + Operand(SILInstruction *owner, SILValue theValue) +- : TheValueAndThreeBits(theValue), Owner(owner) { ++ : TheValue(theValue), Owner(owner), ++ customBits(0), lastInitializedBitfieldID(0) { + insertIntoCurrent(); + } + +@@ -1062,14 +1064,14 @@ class Operand { + Operand &operator=(Operand &&) = default; + + /// Return the current value being used by this operand. +- SILValue get() const { return TheValueAndThreeBits.getPointer(); } ++ SILValue get() const { return TheValue; } + + /// Set the current value being used by this operand. + void set(SILValue newValue) { + // It's probably not worth optimizing for the case of switching + // operands on a single value. + removeFromCurrent(); +- TheValueAndThreeBits.setPointer(newValue); ++ TheValue = newValue; + insertIntoCurrent(); + } + +@@ -1083,9 +1085,9 @@ class Operand { + /// Remove this use of the operand. + void drop() { + removeFromCurrent(); +- TheValueAndThreeBits = {SILValue(), 0}; +- NextUseAndThreeBits = {nullptr, 0}; +- BackAndThreeBits = {nullptr, 0}; ++ TheValue = SILValue(); ++ NextUse = nullptr; ++ Back = nullptr; + Owner = nullptr; + } + +@@ -1097,7 +1099,7 @@ class Operand { + SILInstruction *getUser() { return Owner; } + const SILInstruction *getUser() const { return Owner; } + +- Operand *getNextUse() const { return NextUseAndThreeBits.getPointer(); } ++ Operand *getNextUse() const { return NextUse; } + + /// Return true if this operand is a type dependent operand. + /// +@@ -1147,32 +1149,14 @@ class Operand { + SILBasicBlock *getParentBlock() const; + SILFunction *getParentFunction() const; + +- unsigned getCustomBits() const { +- unsigned bits = 0; +- bits |= TheValueAndThreeBits.getInt(); +- bits |= NextUseAndThreeBits.getInt() << 3; +- bits |= BackAndThreeBits.getInt() << 2; +- return bits; +- } +- +- void setCustomBits(unsigned bits) { +- assert(bits < 256 && "Can only store a byte?!"); +- TheValueAndThreeBits.setInt(bits & 0x7); +- NextUseAndThreeBits.setInt((bits >> 3) & 0x7); +- BackAndThreeBits.setInt((bits >> 6) & 0x3); +- } ++ unsigned getCustomBits() const { return customBits; } ++ void setCustomBits(unsigned bits) {customBits = bits; } + + // Called when transferring basic blocks from one function to another. + void resetBitfields() { + lastInitializedBitfieldID = 0; + } + +- void markAsDeleted() { +- lastInitializedBitfieldID = -1; +- } +- +- bool isMarkedAsDeleted() const { return lastInitializedBitfieldID < 0; } +- + SILFunction *getFunction() const; + + void print(llvm::raw_ostream &os) const; +@@ -1180,30 +1164,21 @@ class Operand { + + private: + void removeFromCurrent() { +- auto *back = getBack(); +- if (!back) +- return; +- auto *nextUse = getNextUse(); +- *back = nextUse; +- if (nextUse) +- nextUse->setBack(back); ++ if (!Back) ++ return; ++ *Back = NextUse; ++ if (NextUse) ++ NextUse->Back = Back; + } + + void insertIntoCurrent() { +- auto **firstUse = &get()->FirstUse; +- setBack(firstUse); +- setNextUse(*firstUse); +- if (auto *nextUse = getNextUse()) +- nextUse->setBack(NextUseAndThreeBits.getAddrOfPointer()); +- get()->FirstUse = this; ++ Back = &TheValue->FirstUse; ++ NextUse = TheValue->FirstUse; ++ if (NextUse) ++ NextUse->Back = &NextUse; ++ TheValue->FirstUse = this; + } + +- void setNextUse(Operand *op) { NextUseAndThreeBits.setPointer(op); } +- +- Operand **getBack() const { return BackAndThreeBits.getPointer(); } +- +- void setBack(Operand **newValue) { BackAndThreeBits.setPointer(newValue); } +- + friend class ValueBase; + friend class ValueBaseUseIterator; + friend class ConsumingUseIterator; +diff --git a/swift/include/swift/SILOptimizer/OptimizerBridging.h b/swift/include/swift/SILOptimizer/OptimizerBridging.h +index e0194a2b7b48a..ea8ef4210fec8 100644 +--- a/swift/include/swift/SILOptimizer/OptimizerBridging.h ++++ b/swift/include/swift/SILOptimizer/OptimizerBridging.h +@@ -50,6 +50,7 @@ class DominanceInfo; + class PostDominanceInfo; + class BasicBlockSet; + class NodeSet; ++class OperandSet; + class ClonerWithFixedLocation; + class SwiftPassInvocation; + class FixedSizeSlabPayload; +@@ -155,6 +156,15 @@ struct BridgedNodeSet { + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getFunction() const; + }; + ++struct BridgedOperandSet { ++ swift::OperandSet * _Nonnull set; ++ ++ BRIDGED_INLINE bool contains(BridgedOperand operand) const; ++ BRIDGED_INLINE bool insert(BridgedOperand operand) const; ++ BRIDGED_INLINE void erase(BridgedOperand operand) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getFunction() const; ++}; ++ + struct BridgedCloner { + swift::ClonerWithFixedLocation * _Nonnull cloner; + +@@ -244,6 +254,8 @@ struct BridgedPassContext { + BRIDGED_INLINE void freeBasicBlockSet(BridgedBasicBlockSet set) const; + SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedNodeSet allocNodeSet() const; + BRIDGED_INLINE void freeNodeSet(BridgedNodeSet set) const; ++ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedOperandSet allocOperandSet() const; ++ BRIDGED_INLINE void freeOperandSet(BridgedOperandSet set) const; + + // Stack nesting + +diff --git a/swift/include/swift/SILOptimizer/OptimizerBridgingImpl.h b/swift/include/swift/SILOptimizer/OptimizerBridgingImpl.h +index 81ec890a88e1b..c79133a6c5447 100644 +--- a/swift/include/swift/SILOptimizer/OptimizerBridgingImpl.h ++++ b/swift/include/swift/SILOptimizer/OptimizerBridgingImpl.h +@@ -129,6 +129,26 @@ BridgedFunction BridgedNodeSet::getFunction() const { + return {set->getFunction()}; + } + ++//===----------------------------------------------------------------------===// ++// BridgedOperandSet ++//===----------------------------------------------------------------------===// ++ ++bool BridgedOperandSet::contains(BridgedOperand operand) const { ++ return set->contains(operand.op); ++} ++ ++bool BridgedOperandSet::insert(BridgedOperand operand) const { ++ return set->insert(operand.op); ++} ++ ++void BridgedOperandSet::erase(BridgedOperand operand) const { ++ set->erase(operand.op); ++} ++ ++BridgedFunction BridgedOperandSet::getFunction() const { ++ return {set->getFunction()}; ++} ++ + //===----------------------------------------------------------------------===// + // BridgedPassContext + //===----------------------------------------------------------------------===// +@@ -256,6 +276,14 @@ void BridgedPassContext::freeNodeSet(BridgedNodeSet set) const { + invocation->freeNodeSet(set.set); + } + ++BridgedOperandSet BridgedPassContext::allocOperandSet() const { ++ return {invocation->allocOperandSet()}; ++} ++ ++void BridgedPassContext::freeOperandSet(BridgedOperandSet set) const { ++ invocation->freeOperandSet(set.set); ++} ++ + void BridgedPassContext::notifyInvalidatedStackNesting() const { + invocation->setNeedFixStackNesting(true); + } +diff --git a/swift/include/swift/SILOptimizer/PassManager/PassManager.h b/swift/include/swift/SILOptimizer/PassManager/PassManager.h +index daf060c43829b..b1f12580f02ec 100644 +--- a/swift/include/swift/SILOptimizer/PassManager/PassManager.h ++++ b/swift/include/swift/SILOptimizer/PassManager/PassManager.h +@@ -14,6 +14,7 @@ + #include "swift/SIL/InstructionUtils.h" + #include "swift/SIL/BasicBlockBits.h" + #include "swift/SIL/NodeBits.h" ++#include "swift/SIL/OperandBits.h" + #include "swift/SILOptimizer/Analysis/Analysis.h" + #include "swift/SILOptimizer/PassManager/PassPipeline.h" + #include "swift/SILOptimizer/PassManager/Passes.h" +@@ -73,16 +74,21 @@ class SwiftPassInvocation { + + SILSSAUpdater *ssaUpdater = nullptr; + +- static constexpr int BlockSetCapacity = 16; ++ static constexpr int BlockSetCapacity = SILBasicBlock::numCustomBits; + char blockSetStorage[sizeof(BasicBlockSet) * BlockSetCapacity]; + bool aliveBlockSets[BlockSetCapacity]; + int numBlockSetsAllocated = 0; + +- static constexpr int NodeSetCapacity = 8; ++ static constexpr int NodeSetCapacity = SILNode::numCustomBits; + char nodeSetStorage[sizeof(NodeSet) * NodeSetCapacity]; + bool aliveNodeSets[NodeSetCapacity]; + int numNodeSetsAllocated = 0; + ++ static constexpr int OperandSetCapacity = Operand::numCustomBits; ++ char operandSetStorage[sizeof(OperandSet) * OperandSetCapacity]; ++ bool aliveOperandSets[OperandSetCapacity]; ++ int numOperandSetsAllocated = 0; ++ + int numClonersAllocated = 0; + + bool needFixStackNesting = false; +@@ -123,6 +129,10 @@ class SwiftPassInvocation { + + void freeNodeSet(NodeSet *set); + ++ OperandSet *allocOperandSet(); ++ ++ void freeOperandSet(OperandSet *set); ++ + /// The top-level API to erase an instruction, called from the Swift pass. + void eraseInstruction(SILInstruction *inst); + +diff --git a/swift/lib/SIL/IR/SILBasicBlock.cpp b/swift/lib/SIL/IR/SILBasicBlock.cpp +index 7198afb189837..8419eaf41a4f3 100644 +--- a/swift/lib/SIL/IR/SILBasicBlock.cpp ++++ b/swift/lib/SIL/IR/SILBasicBlock.cpp +@@ -335,6 +335,9 @@ transferNodesFromList(llvm::ilist_traits &SrcTraits, + for (SILValue result : II.getResults()) { + result->resetBitfields(); + } ++ for (Operand &op : II.getAllOperands()) { ++ op.resetBitfields(); ++ } + II.asSILNode()->resetBitfields(); + + II.setDebugScope(ScopeCloner.getOrCreateClonedScope(II.getDebugScope())); +diff --git a/swift/lib/SIL/IR/SILInstruction.cpp b/swift/lib/SIL/IR/SILInstruction.cpp +index 2f27bfe09b9b8..2d154494d60f3 100644 +--- a/swift/lib/SIL/IR/SILInstruction.cpp ++++ b/swift/lib/SIL/IR/SILInstruction.cpp +@@ -85,6 +85,9 @@ transferNodesFromList(llvm::ilist_traits &L2, + for (SILValue result : first->getResults()) { + result->resetBitfields(); + } ++ for (Operand &op : first->getAllOperands()) { ++ op.resetBitfields(); ++ } + first->asSILNode()->resetBitfields(); + } + } +diff --git a/swift/lib/SILOptimizer/PassManager/PassManager.cpp b/swift/lib/SILOptimizer/PassManager/PassManager.cpp +index c5d9025b00d22..651afa5cfb322 100644 +--- a/swift/lib/SILOptimizer/PassManager/PassManager.cpp ++++ b/swift/lib/SILOptimizer/PassManager/PassManager.cpp +@@ -1402,8 +1402,8 @@ FixedSizeSlab *SwiftPassInvocation::freeSlab(FixedSizeSlab *slab) { + } + + BasicBlockSet *SwiftPassInvocation::allocBlockSet() { +- assert(numBlockSetsAllocated < BlockSetCapacity - 1 && +- "too many BasicBlockSets allocated"); ++ require(numBlockSetsAllocated < BlockSetCapacity, ++ "too many BasicBlockSets allocated"); + + auto *storage = (BasicBlockSet *)blockSetStorage + numBlockSetsAllocated; + BasicBlockSet *set = new (storage) BasicBlockSet(function); +@@ -1426,8 +1426,8 @@ void SwiftPassInvocation::freeBlockSet(BasicBlockSet *set) { + } + + NodeSet *SwiftPassInvocation::allocNodeSet() { +- assert(numNodeSetsAllocated < NodeSetCapacity - 1 && +- "too many BasicNodeSets allocated"); ++ require(numNodeSetsAllocated < NodeSetCapacity, ++ "too many NodeSets allocated"); + + auto *storage = (NodeSet *)nodeSetStorage + numNodeSetsAllocated; + NodeSet *set = new (storage) NodeSet(function); +@@ -1449,6 +1449,30 @@ void SwiftPassInvocation::freeNodeSet(NodeSet *set) { + } + } + ++OperandSet *SwiftPassInvocation::allocOperandSet() { ++ require(numOperandSetsAllocated < OperandSetCapacity, ++ "too many OperandSets allocated"); ++ ++ auto *storage = (OperandSet *)operandSetStorage + numOperandSetsAllocated; ++ OperandSet *set = new (storage) OperandSet(function); ++ aliveOperandSets[numOperandSetsAllocated] = true; ++ ++numOperandSetsAllocated; ++ return set; ++} ++ ++void SwiftPassInvocation::freeOperandSet(OperandSet *set) { ++ int idx = set - (OperandSet *)operandSetStorage; ++ assert(idx >= 0 && idx < numOperandSetsAllocated); ++ assert(aliveOperandSets[idx] && "double free of OperandSet"); ++ aliveOperandSets[idx] = false; ++ ++ while (numOperandSetsAllocated > 0 && !aliveOperandSets[numOperandSetsAllocated - 1]) { ++ auto *set = (OperandSet *)operandSetStorage + numOperandSetsAllocated - 1; ++ set->~OperandSet(); ++ --numOperandSetsAllocated; ++ } ++} ++ + void SwiftPassInvocation::startModulePassRun(SILModuleTransform *transform) { + assert(!this->function && !this->transform && "a pass is already running"); + this->function = nullptr; +@@ -1493,6 +1517,7 @@ void SwiftPassInvocation::endPass() { + assert(allocatedSlabs.empty() && "StackList is leaking slabs"); + assert(numBlockSetsAllocated == 0 && "Not all BasicBlockSets deallocated"); + assert(numNodeSetsAllocated == 0 && "Not all NodeSets deallocated"); ++ assert(numOperandSetsAllocated == 0 && "Not all OperandSets deallocated"); + assert(numClonersAllocated == 0 && "Not all cloners deallocated"); + assert(!needFixStackNesting && "Stack nesting not fixed"); + if (ssaUpdater) { +@@ -1517,6 +1542,7 @@ void SwiftPassInvocation::endTransformFunction() { + function = nullptr; + assert(numBlockSetsAllocated == 0 && "Not all BasicBlockSets deallocated"); + assert(numNodeSetsAllocated == 0 && "Not all NodeSets deallocated"); ++ assert(numOperandSetsAllocated == 0 && "Not all OperandSets deallocated"); + } + + void SwiftPassInvocation::beginVerifyFunction(SILFunction *function) { +@@ -1535,6 +1561,7 @@ void SwiftPassInvocation::endVerifyFunction() { + "verifyication must not change the SIL of a function"); + assert(numBlockSetsAllocated == 0 && "Not all BasicBlockSets deallocated"); + assert(numNodeSetsAllocated == 0 && "Not all NodeSets deallocated"); ++ assert(numOperandSetsAllocated == 0 && "Not all OperandSets deallocated"); + function = nullptr; + } + } +diff --git a/swift/unittests/SIL/SILBitfieldTest.cpp b/swift/unittests/SIL/SILBitfieldTest.cpp +index c9d23bf06b8e1..a11ace8c5483e 100644 +--- a/swift/unittests/SIL/SILBitfieldTest.cpp ++++ b/swift/unittests/SIL/SILBitfieldTest.cpp +@@ -21,20 +21,20 @@ class BasicBlockBitfield; + + struct SILFunction { + BasicBlockBitfield *newestAliveBlockBitfield = nullptr; +- int64_t currentBitfieldID = 1; ++ uint64_t currentBitfieldID = 1; + }; + + struct SILBasicBlock { + SILFunction *function; + uint32_t customBits = 0; +- int64_t lastInitializedBitfieldID = 0; ++ uint64_t lastInitializedBitfieldID = 0; + + enum { numCustomBits = 32 }; ++ enum { maxBitfieldID = std::numeric_limits::max() }; + + SILBasicBlock(SILFunction *function): function(function) {} + + SILFunction *getFunction() const { return function; } +- bool isMarkedAsDeleted() const { return false; } + + unsigned getCustomBits() const { return customBits; } + void setCustomBits(unsigned value) { customBits = value; } diff --git a/packages/swift/swift-change-library-lookup.patch b/packages/swift/swift-change-library-lookup.patch index e1cde69f910530..614439a2d883df 100644 --- a/packages/swift/swift-change-library-lookup.patch +++ b/packages/swift/swift-change-library-lookup.patch @@ -17,9 +17,9 @@ index 0a57134a410..71b7f36a634 100644 --- a/swift/lib/Frontend/CompilerInvocation.cpp +++ b/swift/lib/Frontend/CompilerInvocation.cpp @@ -169,7 +169,7 @@ static void updateRuntimeLibraryPaths(SearchPathOptions &SearchPathOpts, + #endif llvm::sys::path::append(LibPath, LibSubDir); - SearchPathOpts.RuntimeLibraryPaths.clear(); - SearchPathOpts.RuntimeLibraryPaths.push_back(std::string(LibPath.str())); + SearchPathOpts.RuntimeLibraryPaths.push_back("@TERMUX_PREFIX@/lib"); if (Triple.isOSDarwin()) diff --git a/packages/swift/swift-cmake.patch b/packages/swift/swift-cmake.patch index 76061664c52797..6851e640c697c3 100644 --- a/packages/swift/swift-cmake.patch +++ b/packages/swift/swift-cmake.patch @@ -48,8 +48,20 @@ diff --git a/swift/CMakeLists.txt b/swift/CMakeLists.txt index b7503ecdd6..c643c2c9a5 100644 --- a/swift/CMakeLists.txt +++ b/swift/CMakeLists.txt +@@ -414,9 +414,9 @@ set(SWIFT_STDLIB_MSVC_RUNTIME_LIBRARY + + + if(BRIDGING_MODE STREQUAL "DEFAULT" OR NOT BRIDGING_MODE) +- if(CMAKE_BUILD_TYPE STREQUAL "Debug" OR "${SWIFT_HOST_VARIANT_SDK}" MATCHES "WINDOWS|ANDROID" OR (CMAKE_Swift_COMPILER AND CMAKE_Swift_COMPILER_VERSION VERSION_LESS 5.8)) ++ if(CMAKE_BUILD_TYPE STREQUAL "Debug" OR "${SWIFT_HOST_VARIANT_SDK}" STREQUAL "WINDOWS" OR (CMAKE_Swift_COMPILER AND CMAKE_Swift_COMPILER_VERSION VERSION_LESS 5.8)) + # In debug builds, to workaround a problem with LLDB's `po` command (rdar://115770255). +- # On Windows and Android, to workaround a build problem. ++ # On Windows, to workaround a build problem. + # If the host Swift version is less than 5.8, use pure mode to workaround a C++ interop compiler crash. + set(BRIDGING_MODE "PURE") + else() @@ -463,7 +463,7 @@ set(SWIFT_BUILD_HOST_DISPATCH FALSE) - if(SWIFT_ENABLE_DISPATCH AND NOT CMAKE_SYSTEM_NAME STREQUAL Darwin) + if(SWIFT_ENABLE_DISPATCH AND NOT CMAKE_SYSTEM_NAME STREQUAL "Darwin") # Only build libdispatch for the host if the host tools are being built and # specifically if these two libraries that depend on it are built. - if(SWIFT_INCLUDE_TOOLS AND SWIFT_BUILD_SOURCEKIT) @@ -57,23 +69,6 @@ index b7503ecdd6..c643c2c9a5 100644 set(SWIFT_BUILD_HOST_DISPATCH TRUE) endif() -@@ -857,7 +857,7 @@ endif() - - if(SWIFT_BUILD_SWIFT_SYNTAX) - # Only "HOSTTOOLS" is supported in Linux when Swift parser integration is enabled. -- if(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD|FREEBSD" AND NOT BOOTSTRAPPING_MODE STREQUAL "HOSTTOOLS") -+ if(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|OPENBSD|FREEBSD" AND NOT BOOTSTRAPPING_MODE STREQUAL "HOSTTOOLS") - message(WARNING "Force setting BOOTSTRAPPING=HOSTTOOLS because Swift parser integration is enabled") - set(BOOTSTRAPPING_MODE "HOSTTOOLS") - endif() -@@ -1187,6 +1187,7 @@ if(SWIFT_INCLUDE_TOOLS) - message(STATUS " Assertions: ${LLVM_ENABLE_ASSERTIONS}") - message(STATUS " LTO: ${SWIFT_TOOLS_ENABLE_LTO}") - message(STATUS " Bootstrapping: ${BOOTSTRAPPING_MODE}") -+ message(STATUS " C++ Bridging: ${BRIDGING_MODE}") - message(STATUS " Swift parser: ${SWIFT_BUILD_SWIFT_SYNTAX}") - message(STATUS "") - else() @@ -1279,7 +1280,8 @@ if (LLVM_ENABLE_DOXYGEN) message(STATUS "Doxygen: enabled") endif() @@ -84,80 +79,36 @@ index b7503ecdd6..c643c2c9a5 100644 include(Libdispatch) endif() -@@ -1345,6 +1345,9 @@ if(SWIFT_INCLUDE_TOOLS) - FetchContent_MakeAvailable(SwiftSyntax) - endfunction() - include_swift_syntax() -+ if (NOT "${SWIFT_ANDROID_NDK_PATH}" STREQUAL "") -+ add_dependencies(SwiftSyntax swift-stdlib-android-${SWIFT_HOST_VARIANT_ARCH}) -+ endif() - - add_subdirectory(lib) - diff --git a/swift/SwiftCompilerSources/CMakeLists.txt b/swift/SwiftCompilerSources/CMakeLists.txt -index f4a2eb2dddc..61a2548cf77 100644 +index 79413a711d4..9eca061e1ca 100644 --- a/swift/SwiftCompilerSources/CMakeLists.txt +++ b/swift/SwiftCompilerSources/CMakeLists.txt -@@ -102,7 +102,7 @@ function(add_swift_compiler_modules_library name) - elseif(${BOOTSTRAPPING_MODE} STREQUAL "CROSSCOMPILE") - set(sdk_option "-sdk" "${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_ARCH_${SWIFT_HOST_VARIANT_ARCH}_PATH}") - get_filename_component(swift_exec_bin_dir ${ALS_SWIFT_EXEC} DIRECTORY) -- set(sdk_option ${sdk_option} "-resource-dir" "${swift_exec_bin_dir}/../lib/swift") -+ set(sdk_option ${sdk_option} "-resource-dir" "${SWIFT_BINARY_DIR}/lib/swift") - endif() - get_versioned_target_triple(target ${SWIFT_HOST_VARIANT_SDK} - ${SWIFT_HOST_VARIANT_ARCH} "${deployment_version}") -@@ -186,6 +186,9 @@ function(add_swift_compiler_modules_library name) - - set("${module}_dep_target" ${dep_target}) - set(all_module_targets ${all_module_targets} ${dep_target}) -+ if(${BOOTSTRAPPING_MODE} STREQUAL "CROSSCOMPILE") -+ add_dependencies(${dep_target} swift-stdlib-android-${SWIFT_HOST_VARIANT_ARCH}) -+ endif() - endforeach() - - # Create a static library containing all module object files. -diff --git a/swift/cmake/modules/AddPureSwift.cmake b/swift/cmake/modules/AddPureSwift.cmake -index dc58b8fa0f6..37e9f817471 100644 ---- a/swift/cmake/modules/AddPureSwift.cmake -+++ b/swift/cmake/modules/AddPureSwift.cmake -@@ -44,6 +44,13 @@ function(_add_host_swift_compile_options name) - $<$:none>) - - target_compile_options(${name} PRIVATE $<$:-target;${SWIFT_HOST_TRIPLE}>) -+ if (NOT "${SWIFT_ANDROID_NDK_PATH}" STREQUAL "") -+ swift_android_tools_path(${SWIFT_HOST_VARIANT_ARCH} tools_path) -+ target_compile_options(${name} PRIVATE $<$:-resource-dir;${SWIFTLIB_DIR};> -+ $<$:-sdk;${SWIFT_SDK_ANDROID_ARCH_${SWIFT_HOST_VARIANT_ARCH}_PATH};> -+ $<$:-tools-directory;${tools_path};>) -+ add_dependencies(${name} swift-stdlib-android-${SWIFT_HOST_VARIANT_ARCH}) +@@ -172,7 +172,11 @@ function(add_swift_compiler_modules_library name) + # under `include/swift`. These are either located next to the compiler (in case of open source toolchains) or + # in the SDK (in case a Swift compiler from Xcode) + get_filename_component(swift_exec_bin_dir ${ALS_SWIFT_EXEC} DIRECTORY) ++ if(BOOTSTRAPPING_MODE STREQUAL "CROSSCOMPILE") ++ list(APPEND sdk_option "-I" "${SWIFTLIB_DIR}/../") ++ else() + list(APPEND sdk_option "-I" "${swift_exec_bin_dir}/../lib" "-I" "${sdk_path}/usr/lib") + endif() - _add_host_variant_swift_sanitizer_flags(${name}) - endfunction() - -diff --git a/swift/cmake/modules/AddSwift.cmake b/swift/cmake/modules/AddSwift.cmake -index a448bcb23c4..0ddbac17a52 100644 ---- a/swift/cmake/modules/AddSwift.cmake -+++ b/swift/cmake/modules/AddSwift.cmake -@@ -548,7 +548,7 @@ - get_filename_component(swift_bin_dir ${SWIFT_EXEC_FOR_SWIFT_MODULES} DIRECTORY) - get_filename_component(swift_dir ${swift_bin_dir} DIRECTORY) - endif() -- set(host_lib_dir "${swift_dir}/lib/swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}") -+ set(host_lib_dir "${SWIFT_BINARY_DIR}/lib/swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}") - set(host_lib_arch_dir "${host_lib_dir}/${SWIFT_HOST_VARIANT_ARCH}") - set(swiftrt "${host_lib_arch_dir}/swiftrt${CMAKE_C_OUTPUT_EXTENSION}") -@@ -606,6 +606,9 @@ function(_add_swift_runtime_link_flags target relpath_to_lib_dir bootstrapping) - endif() - endif() - endif() -+ if(SWIFT_HOST_VARIANT_SDK STREQUAL "ANDROID") -+ target_link_options(${target} PRIVATE "SHELL:-Xlinker -z -Xlinker nostart-stop-gc") -+ endif() - endif() - - set_property(TARGET ${target} PROPERTY BUILD_WITH_INSTALL_RPATH YES) + set(all_obj_files) + set(all_module_targets) +diff --git a/swift/lib/SwiftSyntax/CMakeLists.txt b/swift/lib/SwiftSyntax/CMakeLists.txt +index 5c7bd65fead..36f3bbc1b91 100644 +--- a/swift/lib/SwiftSyntax/CMakeLists.txt ++++ b/swift/lib/SwiftSyntax/CMakeLists.txt +@@ -80,6 +80,9 @@ endif() + + # Install Swift module interface files. + foreach(module ${SWIFT_SYNTAX_MODULES}) ++ if(BOOTSTRAPPING_MODE STREQUAL "CROSSCOMPILE") ++ add_dependencies(${module} swift-stdlib-${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}-${SWIFT_HOST_VARIANT_ARCH}) ++ endif() + set(module_dir "${module}.swiftmodule") + set(module_file "${SWIFT_HOST_LIBRARIES_DEST_DIR}/${module_dir}/${SWIFT_HOST_MODULE_TRIPLE}") + swift_install_in_component(FILES "${module_file}.swiftinterface" "${module_file}.private.swiftinterface" diff --git a/swift/localization/CMakeLists.txt b/swift/localization/CMakeLists.txt index 07a3585a66c..461a98b6856 100644 --- a/swift/localization/CMakeLists.txt @@ -172,19 +123,6 @@ index 07a3585a66c..461a98b6856 100644 PATTERN "*.strings" ) +endif() -diff --git a/swift/stdlib/cmake/modules/SwiftSource.cmake b/swift/stdlib/cmake/modules/SwiftSource.cmake -index 4bc312f7f89..d71f6408d9f 100644 ---- a/swift/stdlib/cmake/modules/SwiftSource.cmake -+++ b/swift/stdlib/cmake/modules/SwiftSource.cmake -@@ -708,7 +708,7 @@ function(_compile_swift_files - endif() - - set(swift_compiler_tool_dep) -- if(SWIFT_INCLUDE_TOOLS) -+ if(SWIFT_INCLUDE_TOOLS AND NOT ${BOOTSTRAPPING_MODE} STREQUAL "CROSSCOMPILE") - # Depend on the binary itself, in addition to the symlink. - set(swift_compiler_tool_dep "swift-frontend${target_suffix}") - endif() diff --git a/swift/stdlib/public/Concurrency/CMakeLists.txt b/swift/stdlib/public/Concurrency/CMakeLists.txt index 3313f56c8a6..59804ff6228 100644 --- a/swift/stdlib/public/Concurrency/CMakeLists.txt @@ -199,7 +137,7 @@ index 3313f56c8a6..59804ff6228 100644 + # dispatch) endif() elseif("${SWIFT_CONCURRENCY_GLOBAL_EXECUTOR}" STREQUAL "singlethreaded" OR - "${SWIFT_CONCURRENCY_GLOBAL_EXECUTOR}" STREQUAL "hooked") + "${SWIFT_CONCURRENCY_GLOBAL_EXECUTOR}" STREQUAL "hooked" OR @@ -120,6 +120,7 @@ add_swift_target_library(swift_Concurrency ${SWIFT_STDLIB_LIBRARY_BUILD_TYPES} I INCORPORATE_OBJECT_LIBRARIES_SHARED_ONLY ${swift_concurrency_incorporate_object_libraries_so} @@ -212,15 +150,15 @@ diff --git a/swift/stdlib/public/Platform/CMakeLists.txt b/swift/stdlib/public/P index f958d4ce899..ac6d7248606 100644 --- a/swift/stdlib/public/Platform/CMakeLists.txt +++ b/swift/stdlib/public/Platform/CMakeLists.txt -@@ -92,7 +92,7 @@ add_swift_target_library(swiftGlibc ${SWIFT_STDLIB_LIBRARY_BUILD_TYPES} IS_SDK_O +@@ -300,7 +300,7 @@ ${SWIFT_RUNTIME_SWIFT_COMPILE_FLAGS} ${SWIFT_STANDARD_LIBRARY_SWIFT_FLAGS} ${swift_platform_compile_flags} - LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS}" + LINK_FLAGS "${SWIFT_RUNTIME_SWIFT_LINK_FLAGS};-landroid-posix-semaphore" - TARGET_SDKS "${swiftGlibc_target_sdks}" + TARGET_SDKS "ANDROID" INSTALL_IN_COMPONENT sdk-overlay - DEPENDS glibc_modulemap) + DEPENDS android_modulemap) diff --git a/swift/tools/SourceKit/cmake/modules/AddSwiftSourceKit.cmake b/swift/tools/SourceKit/cmake/modules/AddSwiftSourceKit.cmake index 7a77e125f95..7eddfea2054 100644 --- a/swift/tools/SourceKit/cmake/modules/AddSwiftSourceKit.cmake @@ -234,16 +172,7 @@ index 7a77e125f95..7eddfea2054 100644 + ${SWIFT_ANDROID_NATIVE_SYSROOT}/usr/include) endfunction() - function(add_sourcekitd_swifrt_linking target path HAS_SWIFT_MODULES) -@@ -115,7 +115,7 @@ function(add_sourcekitd_swifrt_linking target path HAS_SWIFT_MODULES) - # installed host toolchain. - get_filename_component(swift_bin_dir ${SWIFT_EXEC_FOR_SWIFT_MODULES} DIRECTORY) - get_filename_component(swift_dir ${swift_bin_dir} DIRECTORY) -- set(host_lib_dir "${swift_dir}/lib/swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}") -+ set(host_lib_dir "${SWIFT_BINARY_DIR}/lib/swift/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}") - - target_link_libraries(${target} PRIVATE ${swiftrt}) - target_link_libraries(${target} PRIVATE "swiftCore") + function(add_sourcekit_swift_runtime_link_flags target path HAS_SWIFT_MODULES) diff --git a/swift/tools/swift-compatibility-symbols/CMakeLists.txt b/swift/tools/swift-compatibility-symbols/CMakeLists.txt index 11cda641cc2..bd2cb152725 100644 --- a/swift/tools/swift-compatibility-symbols/CMakeLists.txt @@ -258,46 +187,6 @@ index 11cda641cc2..bd2cb152725 100644 compiler ) +endif() -diff --git a/swift/tools/swift-plugin-server/CMakeLists.txt b/swift/tools/swift-plugin-server/CMakeLists.txt -index a21b79ed260..5b591a30514 100644 ---- a/swift/tools/swift-plugin-server/CMakeLists.txt -+++ b/swift/tools/swift-plugin-server/CMakeLists.txt -@@ -1,28 +1,19 @@ - if (SWIFT_BUILD_SWIFT_SYNTAX) -- # _swiftCSwiftPluginServer is just a C support library for swift-plugin-server -- # Don't bother to create '.a' for that. -- add_swift_host_library(_swiftCSwiftPluginServer OBJECT -- Sources/CSwiftPluginServer/PluginServer.cpp -- ) -- target_link_libraries(_swiftCSwiftPluginServer PRIVATE -- swiftDemangling -+ add_swift_host_tool(swift-plugin-server SWIFT_COMPONENT compiler Sources/CSwiftPluginServer/PluginServer.cpp) -+ add_pure_swift_host_library(SwiftPluginServer STATIC -+ Sources/swift-plugin-server/swift-plugin-server.swift - ) -- target_include_directories(_swiftCSwiftPluginServer PUBLIC -+ target_include_directories(SwiftPluginServer PUBLIC - Sources/CSwiftPluginServer/include - ) -- -- add_pure_swift_host_tool(swift-plugin-server -- Sources/swift-plugin-server/swift-plugin-server.swift -- DEPENDENCIES -+ target_link_libraries(SwiftPluginServer PRIVATE SwiftCompilerPluginMessageHandling) -+ target_link_libraries(swift-plugin-server PRIVATE - swiftDemangling -- $ -- SWIFT_COMPONENT -- compiler -- SWIFT_DEPENDENCIES - SwiftSyntaxMacros - SwiftSyntaxMacroExpansion - SwiftCompilerPluginMessageHandling - swiftLLVMJSON -+ SwiftPluginServer - ) - target_include_directories(swift-plugin-server PRIVATE - Sources/CSwiftPluginServer/include diff --git a/swift-corelibs-xctest/CMakeLists.txt b/swift-corelibs-xctest/CMakeLists.txt index 531e7c0..589930f 100644 --- a/swift-corelibs-xctest/CMakeLists.txt @@ -310,20 +199,3 @@ index 531e7c0..589930f 100644 endif() endif() set_target_properties(XCTest PROPERTIES -diff --git a/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake b/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake -index 951c2d2e..1157ec66 100644 ---- a/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake -+++ b/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake -@@ -87,6 +87,12 @@ function(add_swift_syntax_library name) - target_compile_options(${name} PRIVATE - $<$:-wmo>) - endif() -+ if (NOT "${SWIFT_ANDROID_NDK_PATH}" STREQUAL "") -+ swift_android_tools_path(${SWIFT_HOST_VARIANT_ARCH} tools_path) -+ target_compile_options(${name} PRIVATE $<$:-resource-dir;${SWIFTLIB_DIR};> -+ $<$:-sdk;${SWIFT_SDK_ANDROID_ARCH_${SWIFT_HOST_VARIANT_ARCH}_PATH};> -+ $<$:-tools-directory;${tools_path};>) -+ endif() - - if(LLVM_USE_LINKER) - target_link_options(${name} PRIVATE diff --git a/packages/swift/swift-crosscompile-swift-syntax.patch b/packages/swift/swift-crosscompile-swift-syntax.patch new file mode 100644 index 00000000000000..fc807b249be706 --- /dev/null +++ b/packages/swift/swift-crosscompile-swift-syntax.patch @@ -0,0 +1,47 @@ +diff --git a/swift-syntax/Sources/SwiftLibraryPluginProvider/LibraryPluginProvider.swift b/swift-syntax/Sources/SwiftLibraryPluginProvider/LibraryPluginProvider.swift +index 44be07e2..4450c8e3 100644 +--- a/swift-syntax/Sources/SwiftLibraryPluginProvider/LibraryPluginProvider.swift ++++ b/swift-syntax/Sources/SwiftLibraryPluginProvider/LibraryPluginProvider.swift +@@ -10,7 +10,7 @@ + // + //===----------------------------------------------------------------------===// + +-#if swift(>=6.0) ++#if compiler(>=6.0) + public import SwiftSyntaxMacros + @_spi(PluginMessage) public import SwiftCompilerPluginMessageHandling + private import _SwiftLibraryPluginProviderCShims +diff --git a/swift-syntax/Sources/SwiftSyntax/SyntaxText.swift b/swift-syntax/Sources/SwiftSyntax/SyntaxText.swift +index 4d877962..9e12e3a9 100644 +--- a/swift-syntax/Sources/SwiftSyntax/SyntaxText.swift ++++ b/swift-syntax/Sources/SwiftSyntax/SyntaxText.swift +@@ -10,7 +10,7 @@ + // + //===----------------------------------------------------------------------===// + +-#if swift(>=6.0) ++#if compiler(>=6.0) + #if canImport(Darwin) + private import Darwin + #elseif canImport(Glibc) +diff --git a/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake b/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake +index 2a16fa5e..b7fedd87 100644 +--- a/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake ++++ b/swift-syntax/cmake/modules/AddSwiftHostLibrary.cmake +@@ -97,6 +97,16 @@ function(add_swift_syntax_library name) + $<$:-color-diagnostics> + ) + ++ if(BOOTSTRAPPING_MODE STREQUAL "CROSSCOMPILE") ++ target_compile_options(${name} PRIVATE ++ $<$:-sdk;${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_ARCH_${SWIFT_HOST_VARIANT_ARCH}_PATH};> ++ $<$:-resource-dir;${SWIFTLIB_DIR};>) ++ if(SWIFT_HOST_VARIANT_SDK STREQUAL "ANDROID" AND NOT "${SWIFT_ANDROID_NDK_PATH}" STREQUAL "") ++ swift_android_tools_path(${SWIFT_HOST_VARIANT_ARCH} tools_path) ++ target_compile_options(${name} PRIVATE $<$:-tools-directory;${tools_path};>) ++ endif() ++ endif() ++ + if(LLVM_USE_LINKER) + target_link_options(${name} PRIVATE + "-use-ld=${LLVM_USE_LINKER}" diff --git a/packages/swift/swift-deduplicate-libraries.patch b/packages/swift/swift-deduplicate-libraries.patch new file mode 100644 index 00000000000000..b07ec8f156a4b6 --- /dev/null +++ b/packages/swift/swift-deduplicate-libraries.patch @@ -0,0 +1,30 @@ +From d1a88126f7d1e23afa1a1bab4c4abf0a9bce8a8d +From: Jeremy Schonfeld +Date: Tue, 3 Sep 2024 09:07:03 -0700 +Subject: [PATCH] Add new Foundation libraries to SwiftRuntimeLibsOrdered + (#76019) + +diff --git a/swift/lib/DriverTool/autolink_extract_main.cpp b/swift/lib/DriverTool/autolink_extract_main.cpp +index c74a473fce0e9..8c4381dfddd6c 100644 +--- a/swift/lib/DriverTool/autolink_extract_main.cpp ++++ b/swift/lib/DriverTool/autolink_extract_main.cpp +@@ -231,6 +231,7 @@ int autolink_extract_main(ArrayRef Args, const char *Argv0, + "-lswift_RegexBuilder", + "-lswift_RegexParser", + "-lswift_Backtracing", ++ "-lswiftSynchronization", + "-lswiftGlibc", + "-lBlocksRuntime", + // Dispatch-specific Swift runtime libs +@@ -238,8 +239,11 @@ int autolink_extract_main(ArrayRef Args, const char *Argv0, + "-lDispatchStubs", + "-lswiftDispatch", + // CoreFoundation and Foundation Swift runtime libs ++ "-l_FoundationICU", + "-lCoreFoundation", + "-lFoundation", ++ "-lFoundationEssentials", ++ "-lFoundationInternationalization", + "-lFoundationNetworking", + "-lFoundationXML", + // Foundation support libs diff --git a/packages/swift/swift-foundation-armv7.patch b/packages/swift/swift-foundation-armv7.patch new file mode 100644 index 00000000000000..6dd3fa7a5c76a5 --- /dev/null +++ b/packages/swift/swift-foundation-armv7.patch @@ -0,0 +1,168 @@ +commit ad6ca71b4eef90e3ae69b130e3cc989a21192020 +Author: Alex Lorenz +Date: Wed Aug 14 10:56:25 2024 -0700 + + [android] fix the LP32 armv7/i686 android build (#846) + + * [android] fix the LP32 armv7/i686 android build + + * Update Sources/FoundationEssentials/Android+Extensions.swift + + Co-authored-by: Jeremy Schonfeld <1004103+jmschonfeld@users.noreply.github.com> + + * drop the android Lp32 specific operator & + + --------- + + Co-authored-by: Jeremy Schonfeld <1004103+jmschonfeld@users.noreply.github.com> + +diff --git a/swift-foundation/Sources/FoundationEssentials/Data/Data+Reading.swift b/swift-foundation/Sources/FoundationEssentials/Data/Data+Reading.swift +index 2540b14..a779837 100644 +--- a/swift-foundation/Sources/FoundationEssentials/Data/Data+Reading.swift ++++ b/swift-foundation/Sources/FoundationEssentials/Data/Data+Reading.swift +@@ -325,7 +325,7 @@ internal func readBytesFromFile(path inPath: PathOrURL, reportProgress: Bool, ma + } + + let fileSize = min(Int(clamping: filestat.st_size), maxLength ?? Int.max) +- let fileType = filestat.st_mode & S_IFMT ++ let fileType = mode_t(filestat.st_mode) & S_IFMT + #if !NO_FILESYSTEM + let shouldMap = shouldMapFileDescriptor(fd, path: inPath, options: options) + #else +diff --git a/swift-foundation/Sources/FoundationEssentials/FileManager/FileManager+Basics.swift b/swift-foundation/Sources/FoundationEssentials/FileManager/FileManager+Basics.swift +index 991c5e8..d3e6de3 100644 +--- a/swift-foundation/Sources/FoundationEssentials/FileManager/FileManager+Basics.swift ++++ b/swift-foundation/Sources/FoundationEssentials/FileManager/FileManager+Basics.swift +@@ -221,7 +221,7 @@ internal struct _FileManagerImpl { + var statBuf = stat() + let fd = open(path, 0, 0) + guard fd >= 0 else { return nil } +- if fstat(fd, &statBuf) < 0 || statBuf.st_mode & S_IFMT == S_IFDIR { ++ if fstat(fd, &statBuf) < 0 || mode_t(statBuf.st_mode) & S_IFMT == S_IFDIR { + close(fd) + return nil + } +@@ -240,7 +240,7 @@ internal struct _FileManagerImpl { + } + + /* check for being same type */ +- if myInfo.st_mode & S_IFMT != otherInfo.st_mode & S_IFMT { ++ if mode_t(myInfo.st_mode) & S_IFMT != mode_t(otherInfo.st_mode) & S_IFMT { + return false + } + +diff --git a/swift-foundation/Sources/FoundationEssentials/FileManager/FileManager+Files.swift b/swift-foundation/Sources/FoundationEssentials/FileManager/FileManager+Files.swift +index b8cd50a..bee9fb3 100644 +--- a/swift-foundation/Sources/FoundationEssentials/FileManager/FileManager+Files.swift ++++ b/swift-foundation/Sources/FoundationEssentials/FileManager/FileManager+Files.swift +@@ -175,7 +175,8 @@ extension stat { + } + + fileprivate var fileAttributes: [FileAttributeKey : Any] { +- let fileType = st_mode.fileType ++ // On 32 bit Android, st_mode is UInt32. ++ let fileType = mode_t(st_mode).fileType + var result: [FileAttributeKey : Any] = [ + .size : _writeFileAttributePrimitive(st_size, as: UInt.self), + .modificationDate : modificationDate, +@@ -400,7 +401,7 @@ extension _FileManagerImpl { + guard stat(rep, &fileInfo) == 0 else { + return (false, false) + } +- let isDir = (fileInfo.st_mode & S_IFMT) == S_IFDIR ++ let isDir = (mode_t(fileInfo.st_mode) & S_IFMT) == S_IFDIR + return (true, isDir) + } + #endif +@@ -479,7 +480,7 @@ extension _FileManagerImpl { + return false + } + +- if ((dirInfo.st_mode & S_ISVTX) != 0) && fileManager.fileExists(atPath: path) { ++ if ((mode_t(dirInfo.st_mode) & S_ISVTX) != 0) && fileManager.fileExists(atPath: path) { + // its sticky so verify that we own the file + // otherwise we answer YES on the principle that if + // we create files we can delete them +diff --git a/swift-foundation/Sources/FoundationEssentials/FileManager/FileManager+Utilities.swift b/swift-foundation/Sources/FoundationEssentials/FileManager/FileManager+Utilities.swift +index 9bac967..e531cb5 100644 +--- a/swift-foundation/Sources/FoundationEssentials/FileManager/FileManager+Utilities.swift ++++ b/swift-foundation/Sources/FoundationEssentials/FileManager/FileManager+Utilities.swift +@@ -49,19 +49,19 @@ extension FILETIME { + #if !os(Windows) + extension stat { + var isDirectory: Bool { +- (self.st_mode & S_IFMT) == S_IFDIR ++ (mode_t(self.st_mode) & S_IFMT) == S_IFDIR + } + + var isRegular: Bool { +- (self.st_mode & S_IFMT) == S_IFREG ++ (mode_t(self.st_mode) & S_IFMT) == S_IFREG + } + + var isSymbolicLink: Bool { +- (self.st_mode & S_IFMT) == S_IFLNK ++ (mode_t(self.st_mode) & S_IFMT) == S_IFLNK + } + + var isSpecial: Bool { +- let type = self.st_mode & S_IFMT ++ let type = mode_t(self.st_mode) & S_IFMT + return type == S_IFBLK || type == S_IFCHR + } + } +diff --git a/swift-foundation/Sources/FoundationEssentials/FileManager/FileOperations+Enumeration.swift b/swift-foundation/Sources/FoundationEssentials/FileManager/FileOperations+Enumeration.swift +index 2c9a02f..500da1d 100644 +--- a/swift-foundation/Sources/FoundationEssentials/FileManager/FileOperations+Enumeration.swift ++++ b/swift-foundation/Sources/FoundationEssentials/FileManager/FileOperations+Enumeration.swift +@@ -367,7 +367,7 @@ struct _POSIXDirectoryContentsSequence: Sequence { + let statDir = directoryPath + "/" + fileName + if stat(statDir, &statBuf) == 0 { + // #define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) +- if (statBuf.st_mode & S_IFMT) == S_IFDIR { ++ if (mode_t(statBuf.st_mode) & S_IFMT) == S_IFDIR { + isDirectory = true + } + } +diff --git a/swift-foundation/Sources/FoundationEssentials/FileManager/FileOperations.swift b/swift-foundation/Sources/FoundationEssentials/FileManager/FileOperations.swift +index 03adcc6..92e609f 100644 +--- a/swift-foundation/Sources/FoundationEssentials/FileManager/FileOperations.swift ++++ b/swift-foundation/Sources/FoundationEssentials/FileManager/FileOperations.swift +@@ -867,7 +867,7 @@ enum _FileOperations { + defer { close(dstfd) } + + // Set the file permissions using fchmod() instead of when open()ing to avoid umask() issues +- let permissions = fileInfo.st_mode & ~S_IFMT ++ let permissions = mode_t(fileInfo.st_mode) & ~S_IFMT + guard fchmod(dstfd, permissions) == 0 else { + try delegate.throwIfNecessary(errno, String(cString: srcPtr), String(cString: dstPtr)) + return +diff --git a/swift-foundation/Sources/FoundationEssentials/ProcessInfo/ProcessInfo.swift b/swift-foundation/Sources/FoundationEssentials/ProcessInfo/ProcessInfo.swift +index 2e809fa..d01ca3f 100644 +--- a/swift-foundation/Sources/FoundationEssentials/ProcessInfo/ProcessInfo.swift ++++ b/swift-foundation/Sources/FoundationEssentials/ProcessInfo/ProcessInfo.swift +@@ -198,7 +198,10 @@ final class _ProcessInfo: Sendable { + } + + var fullUserName: String { +-#if canImport(Darwin) || os(Android) || canImport(Glibc) || canImport(Musl) ++#if os(Android) && (arch(i386) || arch(arm)) ++ // On LP32 Android, pw_gecos doesn't exist and is presumed to be NULL. ++ return "" ++#elseif canImport(Darwin) || os(Android) || canImport(Glibc) || canImport(Musl) + let (euid, _) = Platform.getUGIDs() + if let upwd = getpwuid(euid), + let fullname = upwd.pointee.pw_gecos { +diff --git a/swift-foundation/Sources/FoundationEssentials/String/String+Path.swift b/swift-foundation/Sources/FoundationEssentials/String/String+Path.swift +index 477d5d3..1ce75d6 100644 +--- a/swift-foundation/Sources/FoundationEssentials/String/String+Path.swift ++++ b/swift-foundation/Sources/FoundationEssentials/String/String+Path.swift +@@ -737,7 +737,7 @@ extension String { + if lstat(buffer.baseAddress!, &statBuf) < 0 { + return nil + } +- if statBuf.st_mode & S_IFMT == S_IFLNK { ++ if mode_t(statBuf.st_mode) & S_IFMT == S_IFLNK { + /* Examples: + * fspath == /foo/bar0baz/quux/froboz + * linkx == /tic/tac/toe diff --git a/packages/swift/swift-foundation-ndk27.patch b/packages/swift/swift-foundation-ndk27.patch new file mode 100644 index 00000000000000..afcb9d9dc7a8cb --- /dev/null +++ b/packages/swift/swift-foundation-ndk27.patch @@ -0,0 +1,459 @@ +diff --git a/swift-corelibs-foundation/CMakeLists.txt b/swift-corelibs-foundation/CMakeLists.txt +index 7f290d16..95366592 100644 +--- a/swift-corelibs-foundation/CMakeLists.txt ++++ b/swift-corelibs-foundation/CMakeLists.txt +@@ -51,6 +51,7 @@ if(NOT CMAKE_SYSTEM_NAME STREQUAL Windows) + endif() + endif() + ++set(CMAKE_SHARED_LINKER_FLAGS "") + set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin) +diff --git a/swift-corelibs-foundation/Sources/CoreFoundation/include/ForSwiftFoundationOnly.h b/swift-corelibs-foundation/Sources/CoreFoundation/include/ForSwiftFoundationOnly.h +index a2ba56cd..91a312dc 100644 +--- a/swift-corelibs-foundation/Sources/CoreFoundation/include/ForSwiftFoundationOnly.h ++++ b/swift-corelibs-foundation/Sources/CoreFoundation/include/ForSwiftFoundationOnly.h +@@ -69,6 +69,13 @@ + #include + #include + #include ++#include ++#ifdef __swift__ ++// The linux/stat header is private in the Android modulemap. ++#pragma clang module import posix_filesystem.linux_stat ++#else ++#include ++#endif + #elif TARGET_OS_WASI + #include + #include +diff --git a/swift-corelibs-foundation/Sources/Foundation/CGFloat.swift b/swift-corelibs-foundation/Sources/Foundation/CGFloat.swift +index ffe3a6c6..c59977f8 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/CGFloat.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/CGFloat.swift +@@ -7,6 +7,10 @@ + // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors + // + ++#if canImport(Android) ++import Android ++#endif ++ + @frozen + public struct CGFloat: Sendable { + #if arch(i386) || arch(arm) || arch(wasm32) +diff --git a/swift-corelibs-foundation/Sources/Foundation/FileHandle.swift b/swift-corelibs-foundation/Sources/Foundation/FileHandle.swift +index b07c49ac..b540e284 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/FileHandle.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/FileHandle.swift +@@ -34,6 +34,11 @@ import WASILibc + fileprivate let _read = WASILibc.read(_:_:_:) + fileprivate let _write = WASILibc.write(_:_:_:) + fileprivate let _close = WASILibc.close(_:) ++#elseif canImport(Android) ++import Android ++fileprivate let _read = Android.read(_:_:_:) ++fileprivate let _write = Android.write(_:_:_:) ++fileprivate let _close = Android.close(_:) + #endif + + #if canImport(WinSDK) +@@ -321,10 +326,15 @@ open class FileHandle : NSObject, @unchecked Sendable { + if options.contains(.alwaysMapped) { + // Filesizes are often 64bit even on 32bit systems + let mapSize = min(length, Int(clamping: statbuf.st_size)) ++ #if canImport(Android) ++ // Bionic mmap() now returns _Nonnull, so the force unwrap below isn't needed. + let data = mmap(nil, mapSize, PROT_READ, MAP_PRIVATE, _fd, 0) ++ #else ++ let data = mmap(nil, mapSize, PROT_READ, MAP_PRIVATE, _fd, 0)! ++ #endif + // Swift does not currently expose MAP_FAILURE + if data != UnsafeMutableRawPointer(bitPattern: -1) { +- return NSData.NSDataReadResult(bytes: data!, length: mapSize) { buffer, length in ++ return NSData.NSDataReadResult(bytes: data, length: mapSize) { buffer, length in + munmap(buffer, length) + } + } +diff --git a/swift-corelibs-foundation/Sources/Foundation/FileManager+POSIX.swift b/swift-corelibs-foundation/Sources/Foundation/FileManager+POSIX.swift +index e89b3bf6..a82fe1c2 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/FileManager+POSIX.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/FileManager+POSIX.swift +@@ -7,6 +7,10 @@ + // + #if !os(Windows) + ++#if canImport(Android) ++import Android ++#endif ++ + #if os(Android) && (arch(i386) || arch(arm)) // struct stat.st_mode is UInt32 + internal func &(left: UInt32, right: mode_t) -> mode_t { + return mode_t(left) & right +@@ -398,13 +402,13 @@ extension FileManager { + + _current = fts_read(stream) + while let current = _current { +- let filename = FileManager.default.string(withFileSystemRepresentation: current.pointee.fts_path, length: Int(current.pointee.fts_pathlen)) ++ let filename = FileManager.default.string(withFileSystemRepresentation: current.pointee.fts_path!, length: Int(current.pointee.fts_pathlen)) + + switch Int32(current.pointee.fts_info) { + case FTS_D: + let (showFile, skipDescendants) = match(filename: filename, to: _options, isDir: true) + if skipDescendants { +- fts_set(_stream, _current, FTS_SKIP) ++ fts_set(stream, current, FTS_SKIP) + } + if showFile { + return URL(fileURLWithPath: filename, isDirectory: true) +@@ -578,7 +582,7 @@ extension FileManager { + let finalErrno = originalItemURL.withUnsafeFileSystemRepresentation { (originalFS) -> Int32? in + return newItemURL.withUnsafeFileSystemRepresentation { (newItemFS) -> Int32? in + // This is an atomic operation in many OSes, but is not guaranteed to be atomic by the standard. +- if rename(newItemFS, originalFS) == 0 { ++ if rename(newItemFS!, originalFS!) == 0 { + return nil + } else { + return errno +diff --git a/swift-corelibs-foundation/Sources/Foundation/FileManager.swift b/swift-corelibs-foundation/Sources/Foundation/FileManager.swift +index a5d75820..a19464d7 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/FileManager.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/FileManager.swift +@@ -21,6 +21,8 @@ import WinSDK + + #if os(WASI) + import WASILibc ++#elseif canImport(Bionic) ++import Bionic + #endif + + #if os(Windows) +diff --git a/swift-corelibs-foundation/Sources/Foundation/Host.swift b/swift-corelibs-foundation/Sources/Foundation/Host.swift +index 6c4f5291..fb130631 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/Host.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/Host.swift +@@ -12,8 +12,9 @@ + import WinSDK + #endif + +-#if os(Android) +- // Android Glibc differs a little with respect to the Linux Glibc. ++#if canImport(Android) ++ import Android ++ // Android Bionic differs a little with respect to the Linux Glibc. + + // IFF_LOOPBACK is part of the enumeration net_device_flags, which needs to + // convert to UInt32. +@@ -24,8 +25,8 @@ import WinSDK + } + + // getnameinfo uses size_t for its 4th and 6th arguments. +- private func getnameinfo(_ addr: UnsafePointer?, _ addrlen: socklen_t, _ host: UnsafeMutablePointer?, _ hostlen: socklen_t, _ serv: UnsafeMutablePointer?, _ servlen: socklen_t, _ flags: Int32) -> Int32 { +- return Glibc.getnameinfo(addr, addrlen, host, Int(hostlen), serv, Int(servlen), flags) ++ private func getnameinfo(_ addr: UnsafePointer, _ addrlen: socklen_t, _ host: UnsafeMutablePointer?, _ hostlen: socklen_t, _ serv: UnsafeMutablePointer?, _ servlen: socklen_t, _ flags: Int32) -> Int32 { ++ return Android.getnameinfo(addr, addrlen, host, Int(hostlen), serv, Int(servlen), flags) + } + + // getifaddrs and freeifaddrs are not available in Android 6.0 or earlier, so call these functions dynamically. +diff --git a/swift-corelibs-foundation/Sources/Foundation/NSData.swift b/swift-corelibs-foundation/Sources/Foundation/NSData.swift +index ae54f971..65eb0d93 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/NSData.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/NSData.swift +@@ -11,6 +11,9 @@ + #if !os(WASI) + import Dispatch + #endif ++#if canImport(Android) ++import Android ++#endif + + extension NSData { + public typealias ReadingOptions = Data.ReadingOptions +@@ -469,6 +472,8 @@ open class NSData : NSObject, NSCopying, NSMutableCopying, NSSecureCoding { + let createMode = Int(Musl.S_IRUSR) | Int(Musl.S_IWUSR) | Int(Musl.S_IRGRP) | Int(Musl.S_IWGRP) | Int(Musl.S_IROTH) | Int(Musl.S_IWOTH) + #elseif canImport(WASILibc) + let createMode = Int(WASILibc.S_IRUSR) | Int(WASILibc.S_IWUSR) | Int(WASILibc.S_IRGRP) | Int(WASILibc.S_IWGRP) | Int(WASILibc.S_IROTH) | Int(WASILibc.S_IWOTH) ++#elseif canImport(Android) ++ let createMode = Int(Android.S_IRUSR) | Int(Android.S_IWUSR) | Int(Android.S_IRGRP) | Int(Android.S_IWGRP) | Int(Android.S_IROTH) | Int(Android.S_IWOTH) + #endif + guard let fh = FileHandle(path: path, flags: flags, createMode: createMode) else { + throw _NSErrorWithErrno(errno, reading: false, path: path) +diff --git a/swift-corelibs-foundation/Sources/Foundation/NSError.swift b/swift-corelibs-foundation/Sources/Foundation/NSError.swift +index 6f21d3a0..dcd6f3f1 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/NSError.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/NSError.swift +@@ -16,6 +16,8 @@ import Darwin + import Glibc + #elseif canImport(CRT) + import CRT ++#elseif canImport(Android) ++import Android + #endif + + @_implementationOnly import CoreFoundation +diff --git a/swift-corelibs-foundation/Sources/Foundation/NSLock.swift b/swift-corelibs-foundation/Sources/Foundation/NSLock.swift +index fe1d08b7..9d0fadc9 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/NSLock.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/NSLock.swift +@@ -11,6 +11,8 @@ + + #if canImport(Glibc) + import Glibc ++#elseif canImport(Bionic) ++import Bionic + #endif + + #if os(Windows) +diff --git a/swift-corelibs-foundation/Sources/Foundation/NSPlatform.swift b/swift-corelibs-foundation/Sources/Foundation/NSPlatform.swift +index a1809026..5424f5bb 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/NSPlatform.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/NSPlatform.swift +@@ -10,6 +10,9 @@ + #if os(macOS) || os(iOS) + fileprivate let _NSPageSize = Int(vm_page_size) + #elseif os(Linux) || os(Android) || os(OpenBSD) ++#if canImport(Android) ++import Android ++#endif + fileprivate let _NSPageSize = Int(getpagesize()) + #elseif os(Windows) + import WinSDK +diff --git a/swift-corelibs-foundation/Sources/Foundation/NSSwiftRuntime.swift b/swift-corelibs-foundation/Sources/Foundation/NSSwiftRuntime.swift +index 03176c17..1509c31d 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/NSSwiftRuntime.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/NSSwiftRuntime.swift +@@ -19,6 +19,8 @@ internal import Synchronization + @_exported import Glibc + #elseif canImport(Musl) + @_exported import Musl ++#elseif canImport(Bionic) ++@_exported import Bionic + #elseif os(WASI) + @_exported import WASILibc + #elseif os(Windows) +diff --git a/swift-corelibs-foundation/Sources/Foundation/NSURL.swift b/swift-corelibs-foundation/Sources/Foundation/NSURL.swift +index 6af73f16..9e6f20d0 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/NSURL.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/NSURL.swift +@@ -22,6 +22,8 @@ import Darwin + import Glibc + #elseif canImport(Musl) + import Musl ++#elseif canImport(Bionic) ++import Bionic + #endif + + // NOTE: this represents PLATFORM_PATH_STYLE +diff --git a/swift-corelibs-foundation/Sources/Foundation/Port.swift b/swift-corelibs-foundation/Sources/Foundation/Port.swift +index c4ed8282..e71f591b 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/Port.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/Port.swift +@@ -107,7 +107,7 @@ fileprivate let FOUNDATION_SOCK_STREAM = SOCK_STREAM + fileprivate let FOUNDATION_IPPROTO_TCP = IPPROTO_TCP + #endif + +-#if canImport(Glibc) && !os(Android) && !os(OpenBSD) ++#if canImport(Glibc) && !os(OpenBSD) + import Glibc + fileprivate let FOUNDATION_SOCK_STREAM = Int32(SOCK_STREAM.rawValue) + fileprivate let FOUNDATION_IPPROTO_TCP = Int32(IPPROTO_TCP) +@@ -119,14 +119,19 @@ fileprivate let FOUNDATION_SOCK_STREAM = Int32(SOCK_STREAM) + fileprivate let FOUNDATION_IPPROTO_TCP = Int32(IPPROTO_TCP) + #endif + +-#if canImport(Glibc) && os(Android) || os(OpenBSD) ++#if canImport(Glibc) && os(OpenBSD) + import Glibc + fileprivate let FOUNDATION_SOCK_STREAM = Int32(SOCK_STREAM) + fileprivate let FOUNDATION_IPPROTO_TCP = Int32(IPPROTO_TCP) + fileprivate let INADDR_ANY: in_addr_t = 0 +-#if os(OpenBSD) + fileprivate let INADDR_LOOPBACK = 0x7f000001 + #endif ++ ++#if canImport(Android) ++import Android ++fileprivate let FOUNDATION_SOCK_STREAM = Int32(Android.SOCK_STREAM) ++fileprivate let FOUNDATION_IPPROTO_TCP = Int32(Android.IPPROTO_TCP) ++fileprivate let INADDR_ANY: in_addr_t = 0 + #endif + + +diff --git a/swift-corelibs-foundation/Sources/Foundation/Process.swift b/swift-corelibs-foundation/Sources/Foundation/Process.swift +index ee35c23a..5e8cfbaa 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/Process.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/Process.swift +@@ -18,6 +18,8 @@ import struct WinSDK.HANDLE + + #if canImport(Darwin) + import Darwin ++#elseif canImport(Android) ++import Android + #endif + + internal import Synchronization +diff --git a/swift-corelibs-foundation/Sources/Foundation/Thread.swift b/swift-corelibs-foundation/Sources/Foundation/Thread.swift +index 5e79579c..0985a482 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/Thread.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/Thread.swift +@@ -17,6 +17,8 @@ import WinSDK + import Glibc + #elseif canImport(Musl) + import Musl ++#elseif canImport(Bionic) ++import Bionic + #endif + + // WORKAROUND_SR9811 +diff --git a/swift-corelibs-foundation/Sources/FoundationNetworking/HTTPCookie.swift b/swift-corelibs-foundation/Sources/FoundationNetworking/HTTPCookie.swift +index e0d1cbbd..237c1daf 100644 +--- a/swift-corelibs-foundation/Sources/FoundationNetworking/HTTPCookie.swift ++++ b/swift-corelibs-foundation/Sources/FoundationNetworking/HTTPCookie.swift +@@ -15,6 +15,8 @@ import Foundation + + #if os(Windows) + import WinSDK ++#elseif canImport(Android) ++import Android + #endif + + public struct HTTPCookiePropertyKey : RawRepresentable, Equatable, Hashable, Sendable { +diff --git a/swift-corelibs-foundation/Sources/plutil/main.swift b/swift-corelibs-foundation/Sources/plutil/main.swift +index 29316d16..29584596 100644 +--- a/swift-corelibs-foundation/Sources/plutil/main.swift ++++ b/swift-corelibs-foundation/Sources/plutil/main.swift +@@ -15,6 +15,9 @@ import Glibc + #elseif canImport(Musl) + import Foundation + import Musl ++#elseif canImport(Bionic) ++import Foundation ++import Bionic + #elseif canImport(CRT) + import Foundation + import CRT +diff --git a/swift-corelibs-foundation/Sources/xdgTestHelper/main.swift b/swift-corelibs-foundation/Sources/xdgTestHelper/main.swift +index d515a63f..fb037e24 100644 +--- a/swift-corelibs-foundation/Sources/xdgTestHelper/main.swift ++++ b/swift-corelibs-foundation/Sources/xdgTestHelper/main.swift +@@ -19,6 +19,8 @@ import FoundationNetworking + #endif + #if os(Windows) + import WinSDK ++#elseif canImport(Android) ++import Android + #endif + + enum HelperCheckStatus : Int32 { +diff --git a/swift-corelibs-foundation/Package.swift b/swift-corelibs-foundation/Package.swift +--- a/swift-corelibs-foundation/Package.swift ++++ b/swift-corelibs-foundation/Package.swift +@@ -176,7 +176,8 @@ + "BlockRuntime", + "CMakeLists.txt" + ], +- cSettings: coreFoundationBuildSettings ++ cSettings: coreFoundationBuildSettings, ++ linkerSettings: [.linkedLibrary("log", .when(platforms: [.android]))] + ), + .target( + name: "_CFXMLInterface", +diff --git a/swift-corelibs-foundation/Sources/Foundation/FileManager+POSIX.swift b/swift-corelibs-foundation/Sources/Foundation/FileManager+POSIX.swift +index e89b3bf6..a82fe1c2 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/FileManager+POSIX.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/FileManager+POSIX.swift +@@ -347,10 +351,17 @@ + do { + guard fm.fileExists(atPath: _url.path) else { throw _NSErrorWithErrno(ENOENT, reading: true, url: url) } + _stream = try FileManager.default._fileSystemRepresentation(withPath: _url.path) { fsRep in ++#if canImport(Android) ++ let ps = UnsafeMutablePointer>.allocate(capacity: 2) ++ defer { ps.deallocate() } ++ ps.initialize(to: UnsafeMutablePointer(mutating: fsRep)) ++ ps.advanced(by: 1).initialize(to: unsafeBitCast(0, to: UnsafeMutablePointer.self)) ++#else + let ps = UnsafeMutablePointer?>.allocate(capacity: 2) + defer { ps.deallocate() } + ps.initialize(to: UnsafeMutablePointer(mutating: fsRep)) + ps.advanced(by: 1).initialize(to: nil) ++#endif + return fts_open(ps, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR | FTS_NOSTAT, nil) + } + if _stream == nil { +diff --git a/swift-corelibs-foundation/Sources/Foundation/NSPathUtilities.swift b/swift-corelibs-foundation/Sources/Foundation/NSPathUtilities.swift +--- a/swift-corelibs-foundation/Sources/Foundation/NSPathUtilities.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/NSPathUtilities.swift +@@ -19,6 +19,8 @@ + get { WASILibc.errno } + set { WASILibc.errno = newValue } + } ++#elseif os(Android) ++import Android + #endif + + #if os(Windows) +diff --git a/swift-corelibs-foundation/Sources/Foundation/Process.swift b/swift-corelibs-foundation/Sources/Foundation/Process.swift +index 758dd1df..02970992 100644 +--- a/swift-corelibs-foundation/Sources/Foundation/Process.swift ++++ b/swift-corelibs-foundation/Sources/Foundation/Process.swift +@@ -927,8 +927,8 @@ open class Process: NSObject, @unchecked Sendable { + } + let useFallbackChdir: Bool + if let dir = currentDirectoryURL?.path { +- let chdirResult = _CFPosixSpawnFileActionsChdir(fileActions, dir) +- useFallbackChdir = chdirResult == ENOSYS ++ // let chdirResult = _CFPosixSpawnFileActionsChdir(fileActions, dir) ++ useFallbackChdir = true ; let chdirResult = ENOSYS + if !useFallbackChdir { + try _throwIfPosixError(chdirResult) + } +diff --git a/swift-foundation/Sources/FoundationEssentials/FileManager/FileOperations+Enumeration.swift b/swift-foundation/Sources/FoundationEssentials/FileManager/FileOperations+Enumeration.swift +--- a/swift-foundation/Sources/FoundationEssentials/FileManager/FileOperations+Enumeration.swift ++++ b/swift-foundation/Sources/FoundationEssentials/FileManager/FileOperations+Enumeration.swift +@@ -169,7 +169,7 @@ + return + } + +- state = [UnsafeMutablePointer(mutating: path), nil].withUnsafeBufferPointer { dirList in ++ state = [UnsafeMutablePointer(mutating: path), unsafeBitCast(0, to: UnsafeMutablePointer.self)].withUnsafeBufferPointer { dirList in + guard let stream = fts_open(dirList.baseAddress!, opts, nil) else { + return .error(errno, String(cString: path)) + } +diff --git a/swift-foundation/Sources/FoundationEssentials/String/String+Path.swift b/swift-foundation/Sources/FoundationEssentials/String/String+Path.swift +index f1cb26d..44600dd 100644 +--- a/swift-foundation/Sources/FoundationEssentials/String/String+Path.swift ++++ b/swift-foundation/Sources/FoundationEssentials/String/String+Path.swift +@@ -465,6 +465,7 @@ extension String { + return envVar.standardizingPath + } + ++ #if !canImport(Android) + // Next, attempt to find the home directory via getpwnam/getpwuid + var pass: UnsafeMutablePointer? + if let user { +@@ -478,9 +479,10 @@ extension String { + if let dir = pass?.pointee.pw_dir { + return String(cString: dir).standardizingPath + } ++ #endif + + // Fallback to HOME for the current user if possible +- if user == nil, let home = getenv("HOME") { ++ if let home = getenv("HOME") { + return String(cString: home).standardizingPath + } + +diff --git a/swift-foundation-icu/icuSources/CMakeLists.txt b/swift-foundation-icu/icuSources/CMakeLists.txt +index fde8755..343f3b4 100644 +--- a/swift-foundation-icu/icuSources/CMakeLists.txt ++++ b/swift-foundation-icu/icuSources/CMakeLists.txt +@@ -20,7 +20,7 @@ target_include_directories(_FoundationICU + + target_compile_options(_FoundationICU INTERFACE + "$<$:SHELL:-Xcc -fmodule-map-file=${CMAKE_CURRENT_SOURCE_DIR}/include/_foundation_unicode/module.modulemap>") +- ++target_link_options(_FoundationICU PRIVATE "SHELL:--target=$ENV{CCTERMUX_HOST_PLATFORM} -Xlinker -rpath=@TERMUX_PREFIX@/lib") + add_subdirectory(common) + add_subdirectory(i18n) + add_subdirectory(io) diff --git a/packages/swift/swift-foundation.patch b/packages/swift/swift-foundation.patch new file mode 100644 index 00000000000000..832a358a2bffd9 --- /dev/null +++ b/packages/swift/swift-foundation.patch @@ -0,0 +1,189 @@ +From d7239ae4001af292087c45dd46513285aba4ab34 +Date: Tue, 17 Sep 2024 21:10:40 +0530 +Subject: [PATCH] [Android] Enable more code and tests (#871) + +* [Android] Enable more code and tests + +while disabling setting extended file attributes and a test creating a hard link, +features not normally allowed on Android. + +* Remove incorrect WASI check + +diff --git a/swift-foundation/Sources/FoundationEssentials/Data/Data+Reading.swift b/swift-foundation/Sources/FoundationEssentials/Data/Data+Reading.swift +index 48b95214d..612681d2d 100644 +--- a/swift-foundation/Sources/FoundationEssentials/Data/Data+Reading.swift ++++ b/swift-foundation/Sources/FoundationEssentials/Data/Data+Reading.swift +@@ -34,7 +34,7 @@ import WASILibc + func _fgetxattr(_ fd: Int32, _ name: UnsafePointer!, _ value: UnsafeMutableRawPointer!, _ size: Int, _ position: UInt32, _ options: Int32) -> Int { + #if canImport(Darwin) + return fgetxattr(fd, name, value, size, position, options) +-#elseif canImport(Glibc) || canImport(Musl) ++#elseif canImport(Glibc) || canImport(Musl) || canImport(Android) + return fgetxattr(fd, name, value, size) + #else + return -1 +@@ -355,7 +355,7 @@ internal func readBytesFromFile(path inPath: PathOrURL, reportProgress: Bool, ma + let localProgress = (reportProgress && Progress.current() != nil) ? Progress(totalUnitCount: Int64(fileSize)) : nil + + if fileSize == 0 { +- #if os(Linux) ++ #if os(Linux) || os(Android) + // Linux has some files that may report a size of 0 but actually have contents + let chunkSize = 1024 * 4 + var buffer = malloc(chunkSize)! +diff --git a/swift-foundation/Sources/FoundationEssentials/Platform.swift b/swift-foundation/Sources/FoundationEssentials/Platform.swift +index 4549a4524..0a0aaa393 100644 +--- a/swift-foundation/Sources/FoundationEssentials/Platform.swift ++++ b/swift-foundation/Sources/FoundationEssentials/Platform.swift +@@ -192,7 +192,7 @@ extension Platform { + extension Platform { + @discardableResult + package static func copyCString(dst: UnsafeMutablePointer, src: UnsafePointer, size: Int) -> Int { +- #if canImport(Darwin) ++ #if canImport(Darwin) || canImport(Android) + return strlcpy(dst, src, size) + #else + // Glibc doesn't support strlcpy +@@ -267,7 +267,7 @@ extension Platform { + return String(cString: buffer.baseAddress!).standardizingPath + #endif + } +-#elseif os(Linux) ++#elseif os(Linux) || os(Android) + // For Linux, read /proc/self/exe + return try? FileManager.default.destinationOfSymbolicLink( + atPath: "/proc/self/exe").standardizingPath +diff --git a/swift-foundation/Sources/FoundationEssentials/ProcessInfo/ProcessInfo.swift b/swift-foundation/Sources/FoundationEssentials/ProcessInfo/ProcessInfo.swift +index eb55c273d..bb487c7f5 100644 +--- a/swift-foundation/Sources/FoundationEssentials/ProcessInfo/ProcessInfo.swift ++++ b/swift-foundation/Sources/FoundationEssentials/ProcessInfo/ProcessInfo.swift +@@ -437,7 +437,7 @@ extension _ProcessInfo { + var siInfo = SYSTEM_INFO() + GetSystemInfo(&siInfo) + return Int(siInfo.dwNumberOfProcessors) +-#elseif os(Linux) || os(FreeBSD) ++#elseif os(Linux) || os(FreeBSD) || canImport(Android) + return Int(sysconf(Int32(_SC_NPROCESSORS_CONF))) + #else + return 1 +@@ -454,7 +454,7 @@ extension _ProcessInfo { + return 0 + } + return Int(count) +-#elseif os(Linux) || os(FreeBSD) ++#elseif os(Linux) || os(FreeBSD) || canImport(Android) + #if os(Linux) + if let fsCount = Self.fsCoreCount() { + return fsCount +@@ -548,7 +548,7 @@ extension _ProcessInfo { + return 0 + } + return totalMemoryKB * 1024 +-#elseif os(Linux) || os(FreeBSD) ++#elseif os(Linux) || os(FreeBSD) || canImport(Android) + var memory = sysconf(Int32(_SC_PHYS_PAGES)) + memory *= sysconf(Int32(_SC_PAGESIZE)) + return UInt64(memory) +diff --git a/swift-foundation/Sources/FoundationEssentials/TimeZone/TimeZone_Cache.swift b/swift-foundation/Sources/FoundationEssentials/TimeZone/TimeZone_Cache.swift +index 744d77b3b..efb8d678f 100644 +--- a/swift-foundation/Sources/FoundationEssentials/TimeZone/TimeZone_Cache.swift ++++ b/swift-foundation/Sources/FoundationEssentials/TimeZone/TimeZone_Cache.swift +@@ -173,7 +173,7 @@ struct TimeZoneCache : Sendable { + } + } + +-#if os(Linux) && !os(WASI) ++#if os(Linux) + // Try localtime + tzset() + var t = time(nil) +diff --git a/swift-foundation/Tests/FoundationEssentialsTests/DataIOTests.swift b/swift-foundation/Tests/FoundationEssentialsTests/DataIOTests.swift +index 5087168ac..6b9ecf3f4 100644 +--- a/swift-foundation/Tests/FoundationEssentialsTests/DataIOTests.swift ++++ b/swift-foundation/Tests/FoundationEssentialsTests/DataIOTests.swift +@@ -238,7 +238,7 @@ class DataIOTests : XCTestCase { + } + + func test_zeroSizeFile() throws { +- #if !os(Linux) ++ #if !os(Linux) && !os(Android) + throw XCTSkip("This test is only applicable on Linux") + #else + // Some files in /proc report a file size of 0 bytes via a stat call +diff --git a/swift-foundation/Tests/FoundationEssentialsTests/DataTests.swift b/swift-foundation/Tests/FoundationEssentialsTests/DataTests.swift +index 7eae4692f..88428bfef 100644 +--- a/swift-foundation/Tests/FoundationEssentialsTests/DataTests.swift ++++ b/swift-foundation/Tests/FoundationEssentialsTests/DataTests.swift +@@ -1837,7 +1837,7 @@ extension DataTests { + } + + func testEOPNOTSUPP() throws { +- #if !canImport(Darwin) && !os(Linux) ++ #if !canImport(Darwin) && !os(Linux) && !os(Android) + throw XCTSkip("POSIXError.Code is not supported on this platform") + #else + // Opening a socket via open(2) on Darwin can result in the EOPNOTSUPP error code +diff --git a/swift-foundation/Tests/FoundationEssentialsTests/FileManager/FileManagerTests.swift b/swift-foundation/Tests/FoundationEssentialsTests/FileManager/FileManagerTests.swift +index a25638ab4..62dc23260 100644 +--- a/swift-foundation/Tests/FoundationEssentialsTests/FileManager/FileManagerTests.swift ++++ b/swift-foundation/Tests/FoundationEssentialsTests/FileManager/FileManagerTests.swift +@@ -23,6 +23,10 @@ import TestSupport + @testable import Foundation + #endif + ++#if canImport(Android) ++import Android ++#endif ++ + extension FileManager { + fileprivate var delegateCaptures: DelegateCaptures { + (self.delegate as! CapturingFileManagerDelegate).captures +@@ -329,8 +333,13 @@ final class FileManagerTests : XCTestCase { + XCTAssertTrue($0.delegateCaptures.isEmpty) + try $0.linkItem(atPath: "foo", toPath: "bar") + XCTAssertEqual($0.delegateCaptures.shouldLink, [.init("foo", "bar")]) ++ #if os(Android) // Hard links are not normally allowed on Android. ++ XCTAssertEqual($0.delegateCaptures.shouldProceedAfterLinkError, [.init("foo", "bar", code: .fileWriteNoPermission)]) ++ XCTAssertFalse($0.fileExists(atPath: "bar")) ++ #else + XCTAssertEqual($0.delegateCaptures.shouldProceedAfterLinkError, []) + XCTAssertTrue($0.fileExists(atPath: "bar")) ++ #endif + } + + try FileManagerPlayground { +diff --git a/swift-foundation/Tests/FoundationEssentialsTests/PredicateTests.swift b/swift-foundation/Tests/FoundationEssentialsTests/PredicateTests.swift +index 340b21a4a..d0972b537 100644 +--- a/swift-foundation/Tests/FoundationEssentialsTests/PredicateTests.swift ++++ b/swift-foundation/Tests/FoundationEssentialsTests/PredicateTests.swift +@@ -364,7 +364,7 @@ final class PredicateTests: XCTestCase { + func testRegex_RegexBuilder() throws { + #if !canImport(RegexBuilder) + throw XCTSkip("RegexBuilder is unavavailable on this platform") +- #elseif !os(Linux) && !FOUNDATION_FRAMEWORK ++ #elseif !os(Linux) && !os(Android) && !FOUNDATION_FRAMEWORK + // Disable this test in swift-foundation macOS CI because of incorrect availability annotations in the StringProcessing module + throw XCTSkip("This test is currently disabled on this platform") + #else +diff --git a/swift-foundation/Tests/FoundationEssentialsTests/ProcessInfoTests.swift b/swift-foundation/Tests/FoundationEssentialsTests/ProcessInfoTests.swift +index 1e73a9fbf..5b2cc36cf 100644 +--- a/swift-foundation/Tests/FoundationEssentialsTests/ProcessInfoTests.swift ++++ b/swift-foundation/Tests/FoundationEssentialsTests/ProcessInfoTests.swift +@@ -115,7 +115,7 @@ final class ProcessInfoTests : XCTestCase { + let expectedMinMajorVersion = 2 + #endif + XCTAssertGreaterThanOrEqual(version.majorVersion, expectedMinMajorVersion, "Unrealistic major system version") +- #elseif os(Windows) || os(Linux) ++ #elseif os(Windows) || os(Linux) || os(Android) + let minVersion = OperatingSystemVersion(majorVersion: 1, minorVersion: 0, patchVersion: 0) + XCTAssertTrue(ProcessInfo.processInfo.isOperatingSystemAtLeast(minVersion)) + #else +@@ -171,7 +171,7 @@ final class ProcessInfoTests : XCTestCase { + func testProcessName() { + #if FOUNDATION_FRAMEWORK + let targetName = "TestHost" +-#elseif os(Linux) || os(Windows) ++#elseif os(Linux) || os(Windows) || os(Android) + let targetName = "FoundationPreviewPackageTests.xctest" + #else + let targetName = "xctest" diff --git a/packages/swift/swift-import-android.patch b/packages/swift/swift-import-android.patch new file mode 100644 index 00000000000000..a5e757c3a0ae0b --- /dev/null +++ b/packages/swift/swift-import-android.patch @@ -0,0 +1,266 @@ +diff --git a/llbuild/products/llbuildSwift/BuildSystemBindings.swift b/llbuild/products/llbuildSwift/BuildSystemBindings.swift +index 6962fff5..8f1bf502 100644 +--- a/llbuild/products/llbuildSwift/BuildSystemBindings.swift ++++ b/llbuild/products/llbuildSwift/BuildSystemBindings.swift +@@ -17,8 +17,8 @@ import WinSDK + import Glibc + #elseif canImport(Musl) + import Musl +-#elseif canImport(Bionic) +-import Bionic ++#elseif canImport(Android) ++import Android + #else + #error("Missing libc or equivalent") + #endif +@@ -1293,7 +1293,7 @@ public final class BuildSystem { + #elseif os(Windows) + info.pointee.mod_time.seconds = UInt64(s.st_mtime) + info.pointee.mod_time.nanoseconds = 0 +- #elseif canImport(Glibc) || canImport(Musl) || canImport(Bionic) ++ #elseif canImport(Glibc) || canImport(Musl) || canImport(Android) + info.pointee.mod_time.seconds = UInt64(s.st_mtim.tv_sec) + info.pointee.mod_time.nanoseconds = UInt64(s.st_mtim.tv_nsec) + #else +diff --git a/sourcekit-lsp/Sources/SKSupport/Process+Run.swift b/sourcekit-lsp/Sources/SKSupport/Process+Run.swift +--- a/sourcekit-lsp/Sources/SKSupport/Process+Run.swift ++++ b/sourcekit-lsp/Sources/SKSupport/Process+Run.swift +@@ -22,6 +22,8 @@ + + #if os(Windows) + import WinSDK ++#elseif canImport(Android) ++import Android + #endif + + extension Process { +diff --git a/sourcekit-lsp/Sources/sourcekit-lsp/SourceKitLSP.swift b/sourcekit-lsp/Sources/sourcekit-lsp/SourceKitLSP.swift +--- a/sourcekit-lsp/Sources/sourcekit-lsp/SourceKitLSP.swift ++++ b/sourcekit-lsp/Sources/sourcekit-lsp/SourceKitLSP.swift +@@ -28,6 +28,9 @@ + import struct TSCBasic.AbsolutePath + import struct TSCBasic.RelativePath + import var TSCBasic.localFileSystem ++#if canImport(Android) ++import Android ++#endif + + extension AbsolutePath { + public init?(argument: String) { +diff --git a/swift-argument-parser/Sources/ArgumentParser/Utilities/Platform.swift b/swift-argument-parser/Sources/ArgumentParser/Utilities/Platform.swift +index b7fa046..a94e3b8 100644 +--- a/swift-argument-parser/Sources/ArgumentParser/Utilities/Platform.swift ++++ b/swift-argument-parser/Sources/ArgumentParser/Utilities/Platform.swift +@@ -19,6 +19,8 @@ import Darwin + import CRT + #elseif canImport(WASILibc) + import WASILibc ++#elseif canImport(Android) ++import Android + #endif + + enum Platform {} +@@ -88,6 +90,8 @@ extension Platform { + ucrt._exit(code) + #elseif canImport(WASILibc) + WASILibc.exit(code) ++#elseif canImport(Android) ++ Android.exit(code) + #endif + } + } +@@ -108,7 +112,7 @@ extension Platform { + + // MARK: Terminal size + +-#if canImport(Glibc) ++#if canImport(Glibc) || canImport(Android) + func ioctl(_ a: Int32, _ b: Int32, _ p: UnsafeMutableRawPointer) -> Int32 { + ioctl(CInt(a), UInt(b), p) + } +diff --git a/swift-certificates/Sources/X509/Verifier/RFC5280/URIConstraints.swift b/swift-certificates/Sources/X509/Verifier/RFC5280/URIConstraints.swift +--- a/swift-certificates/Sources/X509/Verifier/RFC5280/URIConstraints.swift ++++ b/swift-certificates/Sources/X509/Verifier/RFC5280/URIConstraints.swift +@@ -21,6 +21,9 @@ + #elseif canImport(Musl) + import Musl + import CoreFoundation ++#elseif canImport(Android) ++import Android ++import CoreFoundation + #elseif canImport(Darwin) + import Darwin + #endif +diff --git "a/swift-crypto/Sources/Crypto/Key Derivation/HKDF.swift" "b/swift-crypto/Sources/Crypto/Key Derivation/HKDF.swift" +index 5f47c2f..4b5579e 100644 +--- "a/swift-crypto/Sources/Crypto/Key Derivation/HKDF.swift" ++++ "b/swift-crypto/Sources/Crypto/Key Derivation/HKDF.swift" +@@ -15,6 +15,9 @@ + @_exported import CryptoKit + #else + import Foundation ++#if canImport(Android) ++import Android ++#endif + + /// A standards-based implementation of an HMAC-based Key Derivation Function + /// (HKDF). +diff --git a/swift-system/Sources/System/Internals/CInterop.swift b/swift-system/Sources/System/Internals/CInterop.swift +index 13abc75..2ad551a 100644 +--- a/swift-system/Sources/System/Internals/CInterop.swift ++++ b/swift-system/Sources/System/Internals/CInterop.swift +@@ -25,6 +25,9 @@ import Glibc + #elseif canImport(Musl) + @_implementationOnly import CSystem + import Musl ++#elseif canImport(Bionic) ++@_implementationOnly import CSystem ++import Bionic + #else + #error("Unsupported Platform") + #endif +diff --git a/swift-system/Sources/System/Internals/Constants.swift b/swift-system/Sources/System/Internals/Constants.swift +index 53e215f..27039de 100644 +--- a/swift-system/Sources/System/Internals/Constants.swift ++++ b/swift-system/Sources/System/Internals/Constants.swift +@@ -18,6 +18,8 @@ import CSystem + import ucrt + #elseif canImport(Glibc) + import Glibc ++#elseif canImport(Android) ++import Android + #elseif canImport(Musl) + import CSystem + import Musl +diff --git a/swift-system/Sources/System/Internals/Exports.swift b/swift-system/Sources/System/Internals/Exports.swift +index 5b08725..899be25 100644 +--- a/swift-system/Sources/System/Internals/Exports.swift ++++ b/swift-system/Sources/System/Internals/Exports.swift +@@ -23,6 +23,9 @@ import Glibc + #elseif canImport(Musl) + @_implementationOnly import CSystem + import Musl ++#elseif canImport(Android) ++@_implementationOnly import CSystem ++import Android + #else + #error("Unsupported Platform") + #endif +@@ -58,6 +61,11 @@ internal var system_errno: CInt { + get { Musl.errno } + set { Musl.errno = newValue } + } ++#elseif canImport(Android) ++internal var system_errno: CInt { ++ get { Android.errno } ++ set { Android.errno = newValue } ++} + #endif + + // MARK: C stdlib decls +diff --git a/swift-system/Sources/System/Internals/Syscalls.swift b/swift-system/Sources/System/Internals/Syscalls.swift +index 555f63b..f0db35f 100644 +--- a/swift-system/Sources/System/Internals/Syscalls.swift ++++ b/swift-system/Sources/System/Internals/Syscalls.swift +@@ -15,6 +15,8 @@ import Glibc + import Musl + #elseif os(Windows) + import ucrt ++#elseif canImport(Android) ++import Android + #else + #error("Unsupported Platform") + #endif +diff --git a/swiftpm/Sources/Basics/AsyncProcess.swift b/swiftpm/Sources/Basics/AsyncProcess.swift +--- a/swiftpm/Sources/Basics/AsyncProcess.swift ++++ b/swiftpm/Sources/Basics/AsyncProcess.swift +@@ -14,6 +14,8 @@ + + #if os(Windows) + import TSCLibc ++#elseif canImport(Android) ++import Android + #endif + + #if os(Linux) +diff --git a/swiftpm/Sources/Basics/Cancellator.swift b/swiftpm/Sources/Basics/Cancellator.swift +--- a/swiftpm/Sources/Basics/Cancellator.swift ++++ b/swiftpm/Sources/Basics/Cancellator.swift +@@ -15,6 +15,8 @@ + import class TSCBasic.Thread + #if canImport(WinSDK) + import WinSDK ++#elseif canImport(Android) ++import Android + #endif + + public typealias CancellationHandler = @Sendable (DispatchTime) throws -> Void +diff --git a/swiftpm/Sources/Basics/Environment/Environment.swift b/swiftpm/Sources/Basics/Environment/Environment.swift +--- a/swiftpm/Sources/Basics/Environment/Environment.swift ++++ b/swiftpm/Sources/Basics/Environment/Environment.swift +@@ -19,8 +19,8 @@ + #elseif os(Windows) + import CRT + import WinSDK +-#elseif canImport(Bionic) +-import Bionic ++#elseif canImport(Android) ++import Android + #else + import Darwin.C + #endif +diff --git a/swiftpm/Sources/Commands/SwiftRunCommand.swift b/swiftpm/Sources/Commands/SwiftRunCommand.swift +--- a/swiftpm/Sources/Commands/SwiftRunCommand.swift ++++ b/swiftpm/Sources/Commands/SwiftRunCommand.swift +@@ -9,6 +9,9 @@ + // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors + // + //===----------------------------------------------------------------------===// ++#if canImport(Android) ++import Android ++#endif + + import ArgumentParser + import Basics +diff --git a/swiftpm/Sources/PackagePlugin/Plugin.swift b/swiftpm/Sources/PackagePlugin/Plugin.swift +--- a/swiftpm/Sources/PackagePlugin/Plugin.swift ++++ b/swiftpm/Sources/PackagePlugin/Plugin.swift +@@ -36,6 +36,8 @@ + return String(decodingCString: baseAddress, as: UTF16.self) + } + } ++#elseif canImport(Android) ++import Android + #endif + + // +diff --git a/swiftpm/Sources/PackageRegistryCommand/PackageRegistryCommand+Auth.swift b/swiftpm/Sources/PackageRegistryCommand/PackageRegistryCommand+Auth.swift +index 41df217ce..cb56fb5c3 100644 +--- a/swiftpm/Sources/PackageRegistryCommand/PackageRegistryCommand+Auth.swift ++++ b/swiftpm/Sources/PackageRegistryCommand/PackageRegistryCommand+Auth.swift +@@ -63,6 +63,10 @@ private func readpassword(_ prompt: String) throws -> String { + return password + } + #else ++#if canImport(Android) ++import Android ++#endif ++ + private func readpassword(_ prompt: String) throws -> String { + let password: String + +diff --git a/yams/Sources/Yams/Representer.swift b/yams/Sources/Yams/Representer.swift +index a749c52..b74ef8e 100644 +--- a/yams/Sources/Yams/Representer.swift ++++ b/yams/Sources/Yams/Representer.swift +@@ -14,6 +14,10 @@ private let cpow: (_: Double, _: Double) -> Double = Darwin.pow + #elseif os(Windows) + import ucrt + private let cpow: (_: Double, _: Double) -> Double = ucrt.pow ++#elseif canImport(Bionic) ++import CoreFoundation ++import Bionic ++private let cpow: (_: Double, _: Double) -> Double = Bionic.pow + #else + import CoreFoundation + import Glibc diff --git a/packages/swift/swift-lib-AST-ASTDumper.cpp.patch b/packages/swift/swift-lib-AST-ASTDumper.cpp.patch new file mode 100644 index 00000000000000..71aa8eca9ed927 --- /dev/null +++ b/packages/swift/swift-lib-AST-ASTDumper.cpp.patch @@ -0,0 +1,13 @@ +diff --git a/swift/lib/AST/ASTDumper.cpp b/swift/lib/AST/ASTDumper.cpp +index 0e42ac1250e..c9243a0da8d 100644 +--- a/swift/lib/AST/ASTDumper.cpp ++++ b/swift/lib/AST/ASTDumper.cpp +@@ -442,7 +442,7 @@ static StringRef getDumpString(RequirementKind kind) { + static unsigned getDumpString(unsigned value) { + return value; + } +-static size_t getDumpString(size_t value) { ++static unsigned long getDumpString(unsigned long value) { + return value; + } + diff --git a/packages/swift/swift-lib-Demangling-Errors.cpp.patch b/packages/swift/swift-lib-Demangling-Errors.cpp.patch deleted file mode 100644 index fd4f9678f5ccd2..00000000000000 --- a/packages/swift/swift-lib-Demangling-Errors.cpp.patch +++ /dev/null @@ -1,13 +0,0 @@ -diff --git a/swift/lib/Demangling/Errors.cpp b/swift/lib/Demangling/Errors.cpp -index ee87fa81513..ef37e16976f 100644 ---- a/swift/lib/Demangling/Errors.cpp -+++ b/swift/lib/Demangling/Errors.cpp -@@ -103,7 +103,7 @@ static void reportNow(uint32_t flags, const char *message) { - #endif - #if SWIFT_STDLIB_HAS_ASL - asl_log(nullptr, nullptr, ASL_LEVEL_ERR, "%s", message); --#elif defined(__ANDROID__) -+#elif defined(__ANDROID__) && !defined(__TERMUX__) - __android_log_print(ANDROID_LOG_FATAL, "SwiftDemangle", "%s", message); - #endif - } diff --git a/packages/swift/swift-ndk27.patch b/packages/swift/swift-ndk27.patch new file mode 100644 index 00000000000000..6030a6db55a8ad --- /dev/null +++ b/packages/swift/swift-ndk27.patch @@ -0,0 +1,62 @@ +From c88b9401da550ed2958a0e92e6936120216784e2 +Date: Sat, 14 Sep 2024 01:27:49 +0530 +Subject: [PATCH] [android] Update to LTS NDK 27c + +Add a new bits/ header to the Android overlay, add runtime libraries that are +auto-extracted and listed many times to the list of libraries to be de-duplicated, +and update the doc with new libraries that need to be available to run a simple +executable. +--- + lib/DriverTool/autolink_extract_main.cpp | 3 +++ + stdlib/cmake/modules/AddSwiftStdlib.cmake | 2 +- + stdlib/public/Platform/android.modulemap | 8 ++++++++ + 4 files changed, 23 insertions(+), 10 deletions(-) + +diff --git a/swift/lib/DriverTool/autolink_extract_main.cpp b/swift/lib/DriverTool/autolink_extract_main.cpp +index 332778d581d95..79d63e6ea5d74 100644 +--- a/swift/lib/DriverTool/autolink_extract_main.cpp ++++ b/swift/lib/DriverTool/autolink_extract_main.cpp +@@ -231,8 +231,11 @@ int autolink_extract_main(ArrayRef Args, const char *Argv0, + "-lswiftRegexBuilder", + "-lswift_RegexParser", + "-lswift_Backtracing", ++ "-lswift_Builtin_float", ++ "-lswift_math", + "-lswiftSynchronization", + "-lswiftGlibc", ++ "-lswiftAndroid", + "-lBlocksRuntime", + // Dispatch-specific Swift runtime libs + "-ldispatch", +diff --git a/swift/stdlib/cmake/modules/AddSwiftStdlib.cmake b/swift/stdlib/cmake/modules/AddSwiftStdlib.cmake +index 3784880bc63ed..a3912568f95a7 100644 +--- a/swift/stdlib/cmake/modules/AddSwiftStdlib.cmake ++++ b/swift/stdlib/cmake/modules/AddSwiftStdlib.cmake +@@ -557,7 +557,7 @@ function(_add_target_variant_link_flags) + # We need to add the math library, which is linked implicitly by libc++ + list(APPEND result "-lm") + if(NOT "${SWIFT_ANDROID_NDK_PATH}" STREQUAL "") +- if("${SWIFT_ANDROID_NDK_PATH}" MATCHES "r26") ++ if("${SWIFT_ANDROID_NDK_PATH}" MATCHES "r26|r27") + file(GLOB RESOURCE_DIR ${SWIFT_SDK_ANDROID_ARCH_${LFLAGS_ARCH}_PATH}/../lib/clang/*) + else() + file(GLOB RESOURCE_DIR ${SWIFT_SDK_ANDROID_ARCH_${LFLAGS_ARCH}_PATH}/../lib64/clang/*) +diff --git a/swift/stdlib/public/Platform/android.modulemap b/swift/stdlib/public/Platform/android.modulemap +index a1a9010c4a042..76da5f6bd5e59 100644 +--- a/swift/stdlib/public/Platform/android.modulemap ++++ b/swift/stdlib/public/Platform/android.modulemap +@@ -556,6 +556,14 @@ module _bits_sa_family_t [system] { + header "bits/sa_family_t.h" + export * + } ++ ++module _bits_sockaddr_storage [system] { ++ // Note: this module is not part of 'sys_socket' ++ // to prevent a circular modular dependency ++ header "bits/sockaddr_storage.h" ++ export * ++} ++ + module _bits_stdatomic [system] { + // Note: this module is not part of 'stdatomic' + // as it depends on libc++ and forcing it to diff --git a/packages/swift/swift-pure-bridging.patch b/packages/swift/swift-pure-bridging.patch deleted file mode 100644 index adef36d90d79e5..00000000000000 --- a/packages/swift/swift-pure-bridging.patch +++ /dev/null @@ -1,6451 +0,0 @@ -From 2dbd6cc56bb29db3d23dcd3c85d83f75ddc8bfab -From: Erik Eckstein -Date: Fri, 6 Oct 2023 20:19:24 +0200 -Subject: [PATCH] SwiftCompilerSources: rework bridging - -Introduce two modes of bridging: -* inline mode: this is basically how it worked so far. Using full C++ interop which allows bridging functions to be inlined. -* pure mode: bridging functions are not inlined but compiled in a cpp file. This allows to reduce the C++ interop requirements to a minimum. No std/llvm/swift headers are imported. - -This change requires a major refactoring of bridging sources. The implementation of bridging functions go to two separate files: SILBridgingImpl.h and OptimizerBridgingImpl.h. -Depending on the mode, those files are either included in the corresponding header files (inline mode), or included in the c++ file (pure mode). - -The mode can be selected with the BRIDGING_MODE cmake variable. By default it is set to the inline mode (= existing behavior). The pure mode is only selected in certain configurations to work around C++ interop issues: -* In debug builds, to workaround a problem with LLDB's `po` command (rdar://115770255). -* On windows to workaround a build problem. - -diff --git a/swift/CMakeLists.txt b/swift/CMakeLists.txt -index 294649a5ac0..027ca16521e 100644 ---- a/swift/CMakeLists.txt -+++ b/swift/CMakeLists.txt -@@ -346,6 +346,13 @@ How to build the swift compiler modules. Possible values are - compiler, provided in `SWIFT_NATIVE_SWIFT_TOOLS_PATH` - ]=] OFF) - -+option(BRIDGING_MODE [=[ -+How swift-C++ bridging code is compiled: -+ INLINE: uses full swift C++ interop and briding functions are inlined -+ PURE: uses limited C++ interp an bridging functions are not inlined -+ DEFAULT: based on the build configuration -+]=] DEFAULT) -+ - # 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.") -@@ -390,6 +397,17 @@ set(SWIFT_STDLIB_MSVC_RUNTIME_LIBRARY - ${SWIFT_STDLIB_MSVC_RUNTIME_LIBRARY_default} - CACHE STRING "MSVC Runtime Library for the standard library") - -+ -+if(BRIDGING_MODE STREQUAL "DEFAULT" OR NOT BRIDGING_MODE) -+ if(CMAKE_BUILD_TYPE STREQUAL "Debug" OR "${CMAKE_SYSTEM_NAME}" STREQUAL "Windows") -+ # In debug builds, to workaround a problem with LLDB's `po` command (rdar://115770255). -+ # On windows to workaround a build problem. -+ set(BRIDGING_MODE "PURE") -+ else() -+ set(BRIDGING_MODE "INLINE") -+ endif() -+endif() -+ - is_build_type_optimized("${SWIFT_STDLIB_BUILD_TYPE}" swift_optimized) - if(swift_optimized) - set(SWIFT_STDLIB_ASSERTIONS_default FALSE) -diff --git a/swift/SwiftCompilerSources/CMakeLists.txt b/swift/SwiftCompilerSources/CMakeLists.txt -index 138d208d9a3..e962132dec5 100644 ---- a/swift/SwiftCompilerSources/CMakeLists.txt -+++ b/swift/SwiftCompilerSources/CMakeLists.txt -@@ -76,6 +76,7 @@ function(add_swift_compiler_modules_library name) - "-Xfrontend" "-validate-tbd-against-ir=none" - "-Xfrontend" "-enable-experimental-cxx-interop" - "-Xcc" "-std=c++17" -+ "-Xcc" "-DCOMPILED_WITH_SWIFT" - "-Xcc" "-UIBOutlet" "-Xcc" "-UIBAction" "-Xcc" "-UIBInspectable") - if (NOT BOOTSTRAPPING_MODE STREQUAL "HOSTTOOLS") - list(APPEND swift_compile_options "-Xfrontend" "-disable-implicit-string-processing-module-import") -@@ -91,6 +92,10 @@ function(add_swift_compiler_modules_library name) - list(APPEND swift_compile_options "-Xcc" "-DNDEBUG") - endif() - -+ if("${BRIDGING_MODE}" STREQUAL "PURE") -+ list(APPEND swift_compile_options "-Xcc" "-DPURE_BRIDGING_MODE") -+ endif() -+ - if(NOT SWIFT_STDLIB_SUPPORT_BACK_DEPLOYMENT) - list(APPEND swift_compile_options "-Xfrontend" "-disable-legacy-type-info") - endif() -@@ -237,8 +242,8 @@ else() - # defined in include/swift/module.modulemap - file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/HeaderDependencies.cpp.tmp" - " --#include \"Basic/BridgedSwiftObject.h\" --#include \"Basic/BasicBridging.h\" -+#define COMPILED_WITH_SWIFT -+#include \"Basic/BasicBridging.h\" - #include \"SIL/SILBridging.h\" - - #include \"SILOptimizer/OptimizerBridging.h\" -diff --git a/swift/SwiftCompilerSources/Sources/Basic/SourceLoc.swift b/swift/SwiftCompilerSources/Sources/Basic/SourceLoc.swift -index aa1094dd786..a82baf8d2fc 100644 ---- a/swift/SwiftCompilerSources/Sources/Basic/SourceLoc.swift -+++ b/swift/SwiftCompilerSources/Sources/Basic/SourceLoc.swift -@@ -23,19 +23,15 @@ public struct SourceLoc { - self.locationInFile = locationInFile - } - -- public init?(bridged: swift.SourceLoc) { -+ public init?(bridged: BridgedSourceLoc) { - guard bridged.isValid() else { - return nil - } --#if $NewCxxMethodSafetyHeuristics -- self.locationInFile = bridged.getOpaquePointerValue().assumingMemoryBound(to: UInt8.self) --#else -- self.locationInFile = bridged.__getOpaquePointerValueUnsafe().assumingMemoryBound(to: UInt8.self) --#endif -+ self.locationInFile = bridged.uint8Pointer()! - } - -- public var bridged: swift.SourceLoc { -- .init(llvm.SMLoc.getFromPointer(locationInFile)) -+ public var bridged: BridgedSourceLoc { -+ .init(locationInFile) - } - } - -@@ -46,40 +42,24 @@ extension SourceLoc { - } - - extension Optional where Wrapped == SourceLoc { -- public var bridged: swift.SourceLoc { -+ public var bridged: BridgedSourceLoc { - self?.bridged ?? .init() - } - } - - public struct CharSourceRange { -- private let start: SourceLoc -- private let byteLength: UInt32 -+ public let start: SourceLoc -+ public let byteLength: UInt32 - - public init(start: SourceLoc, byteLength: UInt32) { - self.start = start - self.byteLength = byteLength - } - -- public init?(bridged: swift.CharSourceRange) { --#if $NewCxxMethodSafetyHeuristics -- guard let start = SourceLoc(bridged: bridged.getStart()) else { -+ public init?(bridgedStart: BridgedSourceLoc, byteLength: UInt32) { -+ guard let start = SourceLoc(bridged: bridgedStart) else { - return nil - } --#else -- guard let start = SourceLoc(bridged: bridged.__getStartUnsafe()) else { -- return nil -- } --#endif -- self.init(start: start, byteLength: bridged.getByteLength()) -- } -- -- public var bridged: swift.CharSourceRange { -- .init(start.bridged, byteLength) -- } --} -- --extension Optional where Wrapped == CharSourceRange { -- public var bridged: swift.CharSourceRange { -- self?.bridged ?? .init(.init(), 0) -+ self.init(start: start, byteLength: byteLength) - } - } -diff --git a/swift/SwiftCompilerSources/Sources/Basic/Utils.swift b/swift/SwiftCompilerSources/Sources/Basic/Utils.swift -index 853d3835faa..511fe58f00b 100644 ---- a/swift/SwiftCompilerSources/Sources/Basic/Utils.swift -+++ b/swift/SwiftCompilerSources/Sources/Basic/Utils.swift -@@ -58,42 +58,31 @@ public extension NoReflectionChildren { - //===----------------------------------------------------------------------===// - - public struct StringRef : CustomStringConvertible, NoReflectionChildren { -- let _bridged: llvm.StringRef -+ let _bridged: BridgedStringRef - -- public init(bridged: llvm.StringRef) { self._bridged = bridged } -+ public init(bridged: BridgedStringRef) { self._bridged = bridged } - -- public var string: String { _bridged.string } -+ public var string: String { String(_bridged) } - public var description: String { string } - - public var count: Int { --#if $NewCxxMethodSafetyHeuristics -- Int(_bridged.bytes_end() - _bridged.bytes_begin()) --#else -- Int(_bridged.__bytes_endUnsafe() - _bridged.__bytes_beginUnsafe()) --#endif -+ Int(_bridged.size()) - } - - public subscript(index: Int) -> UInt8 { --#if $NewCxxMethodSafetyHeuristics -- let buffer = UnsafeBufferPointer(start: _bridged.bytes_begin(), -- count: count) --#else -- let buffer = UnsafeBufferPointer(start: _bridged.__bytes_beginUnsafe(), -- count: count) --#endif -+ let buffer = UnsafeBufferPointer(start: _bridged.uintData(), count: count) - return buffer[index] - } - -+ public static func ==(lhs: StringRef, rhs: StringRef) -> Bool { -+ let lhsBuffer = UnsafeBufferPointer(start: lhs._bridged.uintData(), count: lhs.count) -+ let rhsBuffer = UnsafeBufferPointer(start: rhs._bridged.uintData(), count: rhs.count) -+ if lhsBuffer.count != rhsBuffer.count { return false } -+ return lhsBuffer.elementsEqual(rhsBuffer, by: ==) -+ } -+ - public static func ==(lhs: StringRef, rhs: StaticString) -> Bool { --#if $NewCxxMethodSafetyHeuristics -- let lhsBuffer = UnsafeBufferPointer( -- start: lhs._bridged.bytes_begin(), -- count: lhs.count) --#else -- let lhsBuffer = UnsafeBufferPointer( -- start: lhs._bridged.__bytes_beginUnsafe(), -- count: lhs.count) --#endif -+ let lhsBuffer = UnsafeBufferPointer(start: lhs._bridged.uintData(), count: lhs.count) - return rhs.withUTF8Buffer { (rhsBuffer: UnsafeBufferPointer) in - if lhsBuffer.count != rhsBuffer.count { return false } - return lhsBuffer.elementsEqual(rhsBuffer, by: ==) -@@ -101,6 +90,7 @@ public struct StringRef : CustomStringConvertible, NoReflectionChildren { - } - - public static func !=(lhs: StringRef, rhs: StaticString) -> Bool { !(lhs == rhs) } -+ public static func !=(lhs: StringRef, rhs: StringRef) -> Bool { !(lhs == rhs) } - - public static func ~=(pattern: StaticString, value: StringRef) -> Bool { value == pattern } - } -@@ -109,27 +99,23 @@ public struct StringRef : CustomStringConvertible, NoReflectionChildren { - // Bridging Utilities - //===----------------------------------------------------------------------===// - --extension llvm.StringRef { -- public var string: String { -- String(_cxxString: self.str()) -- } --} -- - extension String { -- /// Underscored to avoid name collision with Swift LLVM Bindings. -- /// To be replaced with a bindings call once bindings are a dependency. -- public func _withStringRef(_ c: (llvm.StringRef) -> T) -> T { -+ public func _withBridgedStringRef(_ c: (BridgedStringRef) -> T) -> T { - var str = self - return str.withUTF8 { buffer in -- return c(llvm.StringRef(buffer.baseAddress, buffer.count)) -+ return c(BridgedStringRef(buffer.baseAddress, buffer.count)) - } - } - -- /// Underscored to avoid name collision with the std overlay. -- /// To be replaced with an overlay call once the CI uses SDKs built with Swift 5.8. -- public init(_cxxString s: std.string) { -- self.init(cString: s.__c_strUnsafe()) -- withExtendedLifetime(s) {} -+ public init(_ s: BridgedStringRef) { -+ let buffer = UnsafeBufferPointer(start: s.uintData(), count: Int(s.size())) -+ self.init(decoding: buffer, as: UTF8.self) -+ } -+ -+ public init(taking s: BridgedOwnedString) { -+ let buffer = UnsafeBufferPointer(start: s.uintData(), count: s.size()) -+ self.init(decoding: buffer, as: UTF8.self) -+ s.destroy() - } - } - -diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/AliasAnalysis.swift b/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/AliasAnalysis.swift -index 21a0c2ce511..c2a880cd9b2 100644 ---- a/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/AliasAnalysis.swift -+++ b/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/AliasAnalysis.swift -@@ -36,7 +36,7 @@ struct AliasAnalysis { - static func register() { - BridgedAliasAnalysis.registerAnalysis( - // getMemEffectsFn -- { (bridgedCtxt: BridgedPassContext, bridgedVal: BridgedValue, bridgedInst: BridgedInstruction, complexityBudget: Int) -> swift.MemoryBehavior in -+ { (bridgedCtxt: BridgedPassContext, bridgedVal: BridgedValue, bridgedInst: BridgedInstruction, complexityBudget: Int) -> BridgedMemoryBehavior in - let context = FunctionPassContext(_bridged: bridgedCtxt) - let inst = bridgedInst.instruction - let val = bridgedVal.value -@@ -255,7 +255,7 @@ private struct IsIndirectResultWalker: AddressDefUseWalker { - } - - private extension SideEffects.Memory { -- var bridged: swift.MemoryBehavior { -+ var bridged: BridgedMemoryBehavior { - switch (read, write) { - case (false, false): return .None - case (true, false): return .MayRead -diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/CalleeAnalysis.swift b/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/CalleeAnalysis.swift -index 18f0640d4a9..fc55ceb9393 100644 ---- a/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/CalleeAnalysis.swift -+++ b/swift/SwiftCompilerSources/Sources/Optimizer/Analysis/CalleeAnalysis.swift -@@ -23,7 +23,7 @@ public struct CalleeAnalysis { - return inst.instruction.isDeinitBarrier(bca.analysis) - }, - // getMemBehaviorFn -- { (bridgedApply: BridgedInstruction, observeRetains: Bool, bca: BridgedCalleeAnalysis) -> swift.MemoryBehavior in -+ { (bridgedApply: BridgedInstruction, observeRetains: Bool, bca: BridgedCalleeAnalysis) -> BridgedMemoryBehavior in - let apply = bridgedApply.instruction as! ApplySite - let e = bca.analysis.getSideEffects(ofApply: apply) - return e.getMemBehavior(observeRetains: observeRetains) -@@ -126,13 +126,13 @@ extension Instruction { - } - - public struct FunctionArray : RandomAccessCollection, FormattedLikeArray { -- fileprivate let bridged: swift.CalleeList -+ fileprivate let bridged: BridgedCalleeAnalysis.CalleeList - - public var startIndex: Int { 0 } -- public var endIndex: Int { Int(bridged.getCount()) } -+ public var endIndex: Int { bridged.getCount() } - - public subscript(_ index: Int) -> Function { -- return BridgedCalleeAnalysis.getCallee(bridged, index).function -+ return bridged.getCallee(index).function - } - } - // Bridging utilities -diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/MergeCondFails.swift b/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/MergeCondFails.swift -index 7338d8f8650..64b0bfe1e66 100644 ---- a/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/MergeCondFails.swift -+++ b/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/MergeCondFails.swift -@@ -86,7 +86,7 @@ private func mergeCondFails(_ condFailToMerge: inout Stack, - - // Create a new cond_fail using the merged condition. - _ = builder.createCondFail(condition: mergedCond!, -- message: lastCFI.message) -+ message: lastCFI.message.string) - - while let cfi = condFailToMerge.pop() { - context.erase(instruction: cfi) -diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/ObjectOutliner.swift b/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/ObjectOutliner.swift -index 78f240c3e4a..0a97c61b24b 100644 ---- a/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/ObjectOutliner.swift -+++ b/swift/SwiftCompilerSources/Sources/Optimizer/FunctionPasses/ObjectOutliner.swift -@@ -161,10 +161,11 @@ private func findStores(toTailAddress tailAddr: Value, tailElementIndex: Int, st - for use in tailAddr.uses { - switch use.instruction { - case let indexAddr as IndexAddrInst: -- guard let indexLiteral = indexAddr.index as? IntegerLiteralInst else { -+ guard let indexLiteral = indexAddr.index as? IntegerLiteralInst, -+ let tailIdx = indexLiteral.value else -+ { - return false - } -- let tailIdx = Int(indexLiteral.value.getZExtValue()) - if !findStores(toTailAddress: indexAddr, tailElementIndex: tailElementIndex + tailIdx, stores: &stores) { - return false - } -@@ -381,11 +382,12 @@ private extension AllocRefInstBase { - } - - // The number of tail allocated elements must be constant. -- guard let tailCountLiteral = tailAllocatedCounts[0].value as? IntegerLiteralInst, -- tailCountLiteral.value.getActiveBits() <= 20 else { -- return nil -+ if let tailCountLiteral = tailAllocatedCounts[0].value as? IntegerLiteralInst, -+ let count = tailCountLiteral.value -+ { -+ return count - } -- return Int(tailCountLiteral.value.getZExtValue()); -+ return nil - } - - var numClassFields: Int { -diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondBranch.swift b/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondBranch.swift -index 69a799e9087..8b71648f1e0 100644 ---- a/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondBranch.swift -+++ b/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondBranch.swift -@@ -20,11 +20,13 @@ extension CondBranchInst : OnoneSimplifyable { - - private extension CondBranchInst { - func tryConstantFold(_ context: SimplifyContext) { -- guard let literal = condition as? IntegerLiteralInst else { -+ guard let literal = condition as? IntegerLiteralInst, -+ let conditionValue = literal.value else -+ { - return - } - let builder = Builder(before: self, context) -- if literal.value.isZero() { -+ if conditionValue == 0 { - builder.createBranch(to: falseBlock, arguments: Array(falseOperands.map { $0.value })) - } else { - builder.createBranch(to: trueBlock, arguments: Array(trueOperands.map { $0.value })) -diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondFail.swift b/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondFail.swift -index 9a423cae55b..b7ef2f29d30 100644 ---- a/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondFail.swift -+++ b/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyCondFail.swift -@@ -21,8 +21,9 @@ extension CondFailInst : OnoneSimplifyable { - /// cond_fail %0, "message" - /// ``` - if let literal = condition as? IntegerLiteralInst, -- literal.value.isZero() { -- -+ let value = literal.value, -+ value == 0 -+ { - context.erase(instruction: self) - } - } -diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyLoad.swift b/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyLoad.swift -index 0596b9402a0..8d61c21544e 100644 ---- a/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyLoad.swift -+++ b/swift/SwiftCompilerSources/Sources/Optimizer/InstructionSimplification/SimplifyLoad.swift -@@ -284,10 +284,11 @@ private extension Value { - func getBaseAddressAndOffset() -> (baseAddress: Value, offset: Int)? { - if let indexAddr = self as? IndexAddrInst { - guard let indexLiteral = indexAddr.index as? IntegerLiteralInst, -- indexLiteral.value.getActiveBits() <= 32 else { -+ let indexValue = indexLiteral.value else -+ { - return nil - } -- return (baseAddress: indexAddr.base, offset: Int(indexLiteral.value.getZExtValue())) -+ return (baseAddress: indexAddr.base, offset: indexValue) - } - return (baseAddress: self, offset: 0) - } -@@ -297,9 +298,11 @@ private extension Instruction { - var isShiftRightByAtLeastOne: Bool { - guard let bi = self as? BuiltinInst, - bi.id == .LShr, -- let shiftLiteral = bi.operands[1].value as? IntegerLiteralInst else { -+ let shiftLiteral = bi.operands[1].value as? IntegerLiteralInst, -+ let shiftValue = shiftLiteral.value else -+ { - return false - } -- return shiftLiteral.value.isStrictlyPositive() -+ return shiftValue > 0 - } - } -diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift b/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift -index 304fe88cacf..4ebec621530 100644 ---- a/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift -+++ b/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/Context.swift -@@ -204,7 +204,7 @@ struct FunctionPassContext : MutatingContext { - - func loadFunction(name: StaticString, loadCalleesRecursively: Bool) -> Function? { - return name.withUTF8Buffer { (nameBuffer: UnsafeBufferPointer) in -- let nameStr = llvm.StringRef(nameBuffer.baseAddress, nameBuffer.count) -+ let nameStr = BridgedStringRef(nameBuffer.baseAddress, nameBuffer.count) - return _bridged.loadFunction(nameStr, loadCalleesRecursively).function - } - } -@@ -222,7 +222,7 @@ struct FunctionPassContext : MutatingContext { - /// Returns nil if no such function or multiple matching functions are found. - func lookupStdlibFunction(name: StaticString) -> Function? { - return name.withUTF8Buffer { (nameBuffer: UnsafeBufferPointer) in -- let nameStr = llvm.StringRef(nameBuffer.baseAddress, nameBuffer.count) -+ let nameStr = BridgedStringRef(nameBuffer.baseAddress, nameBuffer.count) - return _bridged.lookupStdlibFunction(nameStr).function - } - } -@@ -241,7 +241,7 @@ struct FunctionPassContext : MutatingContext { - } - - func optimizeMemoryAccesses(in function: Function) -> Bool { -- if swift.optimizeMemoryAccesses(function.bridged.getFunction()) { -+ if BridgedPassContext.optimizeMemoryAccesses(function.bridged) { - notifyInstructionsChanged() - return true - } -@@ -249,7 +249,7 @@ struct FunctionPassContext : MutatingContext { - } - - func eliminateDeadAllocations(in function: Function) -> Bool { -- if swift.eliminateDeadAllocations(function.bridged.getFunction()) { -+ if BridgedPassContext.eliminateDeadAllocations(function.bridged) { - notifyInstructionsChanged() - return true - } -@@ -266,12 +266,11 @@ struct FunctionPassContext : MutatingContext { - } - - func mangleOutlinedVariable(from function: Function) -> String { -- let stdString = _bridged.mangleOutlinedVariable(function.bridged) -- return String(_cxxString: stdString) -+ return String(taking: _bridged.mangleOutlinedVariable(function.bridged)) - } - - func createGlobalVariable(name: String, type: Type, isPrivate: Bool) -> GlobalVariable { -- let gv = name._withStringRef { -+ let gv = name._withBridgedStringRef { - _bridged.createGlobalVariable($0, type.bridged, isPrivate) - } - return gv.globalVar -diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/ModulePassContext.swift b/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/ModulePassContext.swift -index 557ba9f8366..6ecd6dd740f 100644 ---- a/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/ModulePassContext.swift -+++ b/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/ModulePassContext.swift -@@ -22,8 +22,7 @@ struct ModulePassContext : Context, CustomStringConvertible { - let _bridged: BridgedPassContext - - public var description: String { -- let stdString = _bridged.getModuleDescription() -- return String(_cxxString: stdString) -+ return String(taking: _bridged.getModuleDescription()) - } - - struct FunctionList : CollectionLikeSequence, IteratorProtocol { -diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift b/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift -index 060adf01abf..00db3b95ec4 100644 ---- a/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift -+++ b/swift/SwiftCompilerSources/Sources/Optimizer/PassManager/PassRegistration.swift -@@ -25,7 +25,7 @@ public func initializeSwiftModules() { - private func registerPass( - _ pass: ModulePass, - _ runFn: @escaping (@convention(c) (BridgedPassContext) -> ())) { -- pass.name._withStringRef { nameStr in -+ pass.name._withBridgedStringRef { nameStr in - SILPassManager_registerModulePass(nameStr, runFn) - } - } -@@ -33,7 +33,7 @@ private func registerPass( - private func registerPass( - _ pass: FunctionPass, - _ runFn: @escaping (@convention(c) (BridgedFunctionPassCtxt) -> ())) { -- pass.name._withStringRef { nameStr in -+ pass.name._withBridgedStringRef { nameStr in - SILPassManager_registerFunctionPass(nameStr, runFn) - } - } -@@ -54,7 +54,7 @@ private func run(_ instType: InstType.Type, - private func registerForSILCombine( - _ instType: InstType.Type, - _ runFn: @escaping (@convention(c) (BridgedInstructionPassCtxt) -> ())) { -- String(describing: instType)._withStringRef { instClassStr in -+ String(describing: instType)._withBridgedStringRef { instClassStr in - SILCombine_registerInstructionPass(instClassStr, runFn) - } - } -diff --git a/swift/SwiftCompilerSources/Sources/Optimizer/Utilities/WalkUtils.swift b/swift/SwiftCompilerSources/Sources/Optimizer/Utilities/WalkUtils.swift -index b2133ff9224..011e5c73530 100644 ---- a/swift/SwiftCompilerSources/Sources/Optimizer/Utilities/WalkUtils.swift -+++ b/swift/SwiftCompilerSources/Sources/Optimizer/Utilities/WalkUtils.swift -@@ -485,7 +485,7 @@ extension AddressDefUseWalker { - } - case let ia as IndexAddrInst: - if let (pathIdx, subPath) = path.pop(kind: .indexedElement) { -- if let idx = ia.constantSmallIndex, -+ if let idx = ia.constantIndex, - idx == pathIdx { - return walkDownUses(ofAddress: ia, path: subPath) - } -@@ -746,7 +746,7 @@ extension AddressUseDefWalker { - case is BeginAccessInst, is MarkUnresolvedNonCopyableValueInst: - return walkUp(address: (def as! Instruction).operands[0].value, path: path) - case let ia as IndexAddrInst: -- if let idx = ia.constantSmallIndex { -+ if let idx = ia.constantIndex { - return walkUp(address: ia.base, path: path.push(.indexedElement, index: idx)) - } else { - return walkUp(address: ia.base, path: path.push(.anyIndexedElement, index: 0)) -@@ -760,13 +760,11 @@ extension AddressUseDefWalker { - } - - private extension IndexAddrInst { -- var constantSmallIndex: Int? { -- guard let literal = index as? IntegerLiteralInst else { -- return nil -- } -- let index = literal.value -- if index.isIntN(16) { -- return Int(index.getSExtValue()) -+ var constantIndex: Int? { -+ if let literal = index as? IntegerLiteralInst, -+ let indexValue = literal.value -+ { -+ return indexValue - } - return nil - } -diff --git a/swift/SwiftCompilerSources/Sources/SIL/BasicBlock.swift b/swift/SwiftCompilerSources/Sources/SIL/BasicBlock.swift -index 6854ac57c72..a2abd532502 100644 ---- a/swift/SwiftCompilerSources/Sources/SIL/BasicBlock.swift -+++ b/swift/SwiftCompilerSources/Sources/SIL/BasicBlock.swift -@@ -21,8 +21,7 @@ final public class BasicBlock : CustomStringConvertible, HasShortDescription, Eq - public var parentFunction: Function { bridged.getFunction().function } - - public var description: String { -- let stdString = bridged.getDebugDescription() -- return String(_cxxString: stdString) -+ return String(taking: bridged.getDebugDescription()) - } - public var shortDescription: String { name } - -diff --git a/swift/SwiftCompilerSources/Sources/SIL/Builder.swift b/swift/SwiftCompilerSources/Sources/SIL/Builder.swift -index aa6f0893381..a24d36ff527 100644 ---- a/swift/SwiftCompilerSources/Sources/SIL/Builder.swift -+++ b/swift/SwiftCompilerSources/Sources/SIL/Builder.swift -@@ -65,7 +65,7 @@ public struct Builder { - public func createBuiltinBinaryFunction(name: String, - operandType: Type, resultType: Type, arguments: [Value]) -> BuiltinInst { - return arguments.withBridgedValues { valuesRef in -- return name._withStringRef { nameStr in -+ return name._withBridgedStringRef { nameStr in - let bi = bridged.createBuiltinBinaryFunction( - nameStr, operandType.bridged, resultType.bridged, valuesRef) - return notifyNew(bi.getAs(BuiltinInst.self)) -@@ -74,7 +74,7 @@ public struct Builder { - } - - public func createCondFail(condition: Value, message: String) -> CondFailInst { -- return message._withStringRef { messageStr in -+ return message._withBridgedStringRef { messageStr in - let cf = bridged.createCondFail(condition.bridged, messageStr) - return notifyNew(cf.getAs(CondFailInst.self)) - } -@@ -195,7 +195,7 @@ public struct Builder { - arguments: [Value], - isNonThrowing: Bool = false, - isNonAsync: Bool = false, -- specializationInfo: ApplyInst.SpecializationInfo = nil -+ specializationInfo: ApplyInst.SpecializationInfo = ApplyInst.SpecializationInfo() - ) -> ApplyInst { - let apply = arguments.withBridgedValues { valuesRef in - bridged.createApply(function.bridged, substitutionMap.bridged, valuesRef, -diff --git a/swift/SwiftCompilerSources/Sources/SIL/Function.swift b/swift/SwiftCompilerSources/Sources/SIL/Function.swift -index 77fde8318c8..8002a0a8779 100644 ---- a/swift/SwiftCompilerSources/Sources/SIL/Function.swift -+++ b/swift/SwiftCompilerSources/Sources/SIL/Function.swift -@@ -22,8 +22,7 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash - } - - final public var description: String { -- let stdString = bridged.getDebugDescription() -- return String(_cxxString: stdString) -+ return String(taking: bridged.getDebugDescription()) - } - - public var shortDescription: String { name.string } -@@ -113,7 +112,7 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash - - public func hasSemanticsAttribute(_ attr: StaticString) -> Bool { - attr.withUTF8Buffer { (buffer: UnsafeBufferPointer) in -- bridged.hasSemanticsAttr(llvm.StringRef(buffer.baseAddress!, buffer.count)) -+ bridged.hasSemanticsAttr(BridgedStringRef(buffer.baseAddress!, buffer.count)) - } - } - -@@ -284,19 +283,19 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash - } else { - s = effects.description - } -- s._withStringRef { OStream_write(os, $0) } -+ s._withBridgedStringRef { $0.write(os) } - }, - // parseFn: -- { (f: BridgedFunction, str: llvm.StringRef, mode: BridgedFunction.ParseEffectsMode, argumentIndex: Int, paramNames: BridgedArrayRef) -> BridgedFunction.ParsingError in -+ { (f: BridgedFunction, str: BridgedStringRef, mode: BridgedFunction.ParseEffectsMode, argumentIndex: Int, paramNames: BridgedArrayRef) -> BridgedFunction.ParsingError in - do { -- var parser = StringParser(str.string) -+ var parser = StringParser(String(str)) - let function = f.function - - switch mode { - case .argumentEffectsFromSource: -- let paramToIdx = paramNames.withElements(ofType: llvm.StringRef.self) { -- (buffer: UnsafeBufferPointer) -> Dictionary in -- let keyValPairs = buffer.enumerated().lazy.map { ($0.1.string, $0.0) } -+ let paramToIdx = paramNames.withElements(ofType: BridgedStringRef.self) { -+ (buffer: UnsafeBufferPointer) -> Dictionary in -+ let keyValPairs = buffer.enumerated().lazy.map { (String($0.1), $0.0) } - return Dictionary(uniqueKeysWithValues: keyValPairs) - } - let effect = try parser.parseEffectFromSource(for: function, params: paramToIdx) -@@ -358,7 +357,7 @@ final public class Function : CustomStringConvertible, HasShortDescription, Hash - return BridgedFunction.EffectInfo(argumentIndex: -1, isDerived: false, isEmpty: true, isValid: false) - }, - // getMemBehaviorFn -- { (f: BridgedFunction, observeRetains: Bool) -> swift.MemoryBehavior in -+ { (f: BridgedFunction, observeRetains: Bool) -> BridgedMemoryBehavior in - let e = f.function.getSideEffects() - return e.getMemBehavior(observeRetains: observeRetains) - } -@@ -393,7 +392,7 @@ extension OptionalBridgedFunction { - } - - public extension SideEffects.GlobalEffects { -- func getMemBehavior(observeRetains: Bool) -> swift.MemoryBehavior { -+ func getMemBehavior(observeRetains: Bool) -> BridgedMemoryBehavior { - if allocates || ownership.destroy || (ownership.copy && observeRetains) { - return .MayHaveSideEffects - } -diff --git a/swift/SwiftCompilerSources/Sources/SIL/GlobalVariable.swift b/swift/SwiftCompilerSources/Sources/SIL/GlobalVariable.swift -index e231757bdf3..e30843b7cd5 100644 ---- a/swift/SwiftCompilerSources/Sources/SIL/GlobalVariable.swift -+++ b/swift/SwiftCompilerSources/Sources/SIL/GlobalVariable.swift -@@ -19,8 +19,7 @@ final public class GlobalVariable : CustomStringConvertible, HasShortDescription - } - - public var description: String { -- let stdString = bridged.getDebugDescription() -- return String(_cxxString: stdString) -+ return String(taking: bridged.getDebugDescription()) - } - - public var shortDescription: String { name.string } -@@ -163,8 +162,10 @@ private extension TupleExtractInst { - let bi = tuple as? BuiltinInst, - bi.id == .USubOver, - bi.operands[1].value is IntegerLiteralInst, -- let overFlowFlag = bi.operands[2].value as? IntegerLiteralInst, -- overFlowFlag.value.isNullValue() { -+ let overflowLiteral = bi.operands[2].value as? IntegerLiteralInst, -+ let overflowValue = overflowLiteral.value, -+ overflowValue == 0 -+ { - return true - } - return false -diff --git a/swift/SwiftCompilerSources/Sources/SIL/Instruction.swift b/swift/SwiftCompilerSources/Sources/SIL/Instruction.swift -index 7c68b270147..9e26e780e8f 100644 ---- a/swift/SwiftCompilerSources/Sources/SIL/Instruction.swift -+++ b/swift/SwiftCompilerSources/Sources/SIL/Instruction.swift -@@ -34,8 +34,7 @@ public class Instruction : CustomStringConvertible, Hashable { - final public var parentFunction: Function { parentBlock.parentFunction } - - final public var description: String { -- let stdString = bridged.getDebugDescription() -- return String(_cxxString: stdString) -+ return String(taking: bridged.getDebugDescription()) - } - - final public var isDeleted: Bool { -@@ -288,7 +287,7 @@ final public class CondFailInst : Instruction, UnaryInstruction { - public var condition: Value { operand.value } - public override var mayTrap: Bool { true } - -- public var message: String { bridged.CondFailInst_getMessage().string } -+ public var message: StringRef { StringRef(bridged: bridged.CondFailInst_getMessage()) } - } - - final public class FixLifetimeInst : Instruction, UnaryInstruction {} -@@ -408,7 +407,7 @@ final public class LoadUnownedInst : SingleValueInstruction, UnaryInstruction {} - final public class LoadBorrowInst : SingleValueInstruction, UnaryInstruction {} - - final public class BuiltinInst : SingleValueInstruction { -- public typealias ID = swift.BuiltinValueKind -+ public typealias ID = BridgedInstruction.BuiltinValueKind - - public var id: ID { - return bridged.BuiltinInst_getID() -@@ -552,11 +551,16 @@ final public class AllocGlobalInst : Instruction { - } - - final public class IntegerLiteralInst : SingleValueInstruction { -- public var value: llvm.APInt { bridged.IntegerLiteralInst_getValue() } -+ public var value: Int? { -+ let optionalInt = bridged.IntegerLiteralInst_getValue() -+ if optionalInt.hasValue { -+ return optionalInt.value -+ } -+ return nil -+ } - } - - final public class FloatLiteralInst : SingleValueInstruction { -- public var value: llvm.APFloat { bridged.FloatLiteralInst_getValue() } - } - - final public class StringLiteralInst : SingleValueInstruction { -@@ -702,7 +706,7 @@ final public class BridgeObjectToRefInst : SingleValueInstruction, - final public class BridgeObjectToWordInst : SingleValueInstruction, - UnaryInstruction {} - --public typealias AccessKind = swift.SILAccessKind -+public typealias AccessKind = BridgedInstruction.AccessKind - - - // TODO: add support for begin_unpaired_access -@@ -796,7 +800,7 @@ final public class ApplyInst : SingleValueInstruction, FullApplySite { - public var isNonThrowing: Bool { bridged.ApplyInst_getNonThrowing() } - public var isNonAsync: Bool { bridged.ApplyInst_getNonAsync() } - -- public typealias SpecializationInfo = UnsafePointer? -+ public typealias SpecializationInfo = BridgedGenericSpecializationInformation - - public var specializationInfo: SpecializationInfo { bridged.ApplyInst_getSpecializationInfo() } - } -diff --git a/swift/SwiftCompilerSources/Sources/SIL/Location.swift b/swift/SwiftCompilerSources/Sources/SIL/Location.swift -index 6940eb5b130..7b2553e053f 100644 ---- a/swift/SwiftCompilerSources/Sources/SIL/Location.swift -+++ b/swift/SwiftCompilerSources/Sources/SIL/Location.swift -@@ -13,11 +13,10 @@ - import SILBridging - - public struct Location: Equatable, CustomStringConvertible { -- let bridged: swift.SILDebugLocation -+ let bridged: BridgedLocation - - public var description: String { -- let stdString = bridged.getDebugDescription() -- return String(_cxxString: stdString) -+ return String(taking: bridged.getDebugDescription()) - } - - /// Keeps the debug scope but marks it as auto-generated. -@@ -39,6 +38,6 @@ public struct Location: Equatable, CustomStringConvertible { - } - - public static var artificialUnreachableLocation: Location { -- Location(bridged: swift.SILDebugLocation.getArtificialUnreachableLocation()) -+ Location(bridged: BridgedLocation.getArtificialUnreachableLocation()) - } - } -diff --git a/swift/SwiftCompilerSources/Sources/SIL/Registration.swift b/swift/SwiftCompilerSources/Sources/SIL/Registration.swift -index 2fa210ca99e..3d1fccd8c2f 100644 ---- a/swift/SwiftCompilerSources/Sources/SIL/Registration.swift -+++ b/swift/SwiftCompilerSources/Sources/SIL/Registration.swift -@@ -14,7 +14,7 @@ import Basic - import SILBridging - - private func register(_ cl: T.Type) { -- String(describing: cl)._withStringRef { nameStr in -+ String(describing: cl)._withBridgedStringRef { nameStr in - let metatype = unsafeBitCast(cl, to: SwiftMetatype.self) - registerBridgedClass(nameStr, metatype) - } -diff --git a/swift/SwiftCompilerSources/Sources/SIL/SubstitutionMap.swift b/swift/SwiftCompilerSources/Sources/SIL/SubstitutionMap.swift -index f618f31b8ff..4d62f6c081b 100644 ---- a/swift/SwiftCompilerSources/Sources/SIL/SubstitutionMap.swift -+++ b/swift/SwiftCompilerSources/Sources/SIL/SubstitutionMap.swift -@@ -13,17 +13,17 @@ - import SILBridging - - public struct SubstitutionMap { -- public let bridged: swift.SubstitutionMap -+ public let bridged: BridgedSubstitutionMap - -- public init(_ bridged: swift.SubstitutionMap) { -+ public init(_ bridged: BridgedSubstitutionMap) { - self.bridged = bridged - } - - public init() { -- self.bridged = swift.SubstitutionMap() -+ self.bridged = BridgedSubstitutionMap() - } - -- public var isEmpty: Bool { bridged.empty() } -+ public var isEmpty: Bool { bridged.isEmpty() } - - public var replacementTypes: OptionalTypeArray { - let types = BridgedTypeArray.fromReplacementTypes(bridged) -diff --git a/swift/SwiftCompilerSources/Sources/SIL/Type.swift b/swift/SwiftCompilerSources/Sources/SIL/Type.swift -index c7fdca56ee7..89bbad7cd30 100644 ---- a/swift/SwiftCompilerSources/Sources/SIL/Type.swift -+++ b/swift/SwiftCompilerSources/Sources/SIL/Type.swift -@@ -14,8 +14,8 @@ import Basic - import SILBridging - - public struct Type : CustomStringConvertible, NoReflectionChildren { -- public let bridged: swift.SILType -- -+ public let bridged: BridgedType -+ - public var isAddress: Bool { bridged.isAddress() } - public var isObject: Bool { !isAddress } - -@@ -23,12 +23,12 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { - public var objectType: Type { bridged.getObjectType().type } - - public func isTrivial(in function: Function) -> Bool { -- return bridged.isTrivial(function.bridged.getFunction()) -+ return bridged.isTrivial(function.bridged) - } - - /// Returns true if the type is a trivial type and is and does not contain a Builtin.RawPointer. - public func isTrivialNonPointer(in function: Function) -> Bool { -- return !bridged.isNonTrivialOrContainsRawPointer(function.bridged.getFunction()) -+ return !bridged.isNonTrivialOrContainsRawPointer(function.bridged) - } - - /// True if this type is a value type (struct/enum) that requires deinitialization beyond -@@ -36,11 +36,11 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { - public var isValueTypeWithDeinit: Bool { bridged.isValueTypeWithDeinit() } - - public func isLoadable(in function: Function) -> Bool { -- return bridged.isLoadable(function.bridged.getFunction()) -+ return bridged.isLoadable(function.bridged) - } - - public func isReferenceCounted(in function: Function) -> Bool { -- return bridged.isReferenceCounted(function.bridged.getFunction()) -+ return bridged.isReferenceCounted(function.bridged) - } - - public var isUnownedStorageType: Bool { -@@ -49,20 +49,20 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { - - public var hasArchetype: Bool { bridged.hasArchetype() } - -- public var isNominal: Bool { bridged.getNominalOrBoundGenericNominal() != nil } -- public var isClass: Bool { bridged.getClassOrBoundGenericClass() != nil } -- public var isStruct: Bool { bridged.getStructOrBoundGenericStruct() != nil } -+ public var isNominal: Bool { bridged.isNominalOrBoundGenericNominal() } -+ public var isClass: Bool { bridged.isClassOrBoundGenericClass() } -+ public var isStruct: Bool { bridged.isStructOrBoundGenericStruct() } - public var isTuple: Bool { bridged.isTuple() } -- public var isEnum: Bool { bridged.getEnumOrBoundGenericEnum() != nil } -+ public var isEnum: Bool { bridged.isEnumOrBoundGenericEnum() } - public var isFunction: Bool { bridged.isFunction() } - public var isMetatype: Bool { bridged.isMetatype() } - public var isNoEscapeFunction: Bool { bridged.isNoEscapeFunction() } - -- public var canBeClass: swift.TypeTraitResult { bridged.canBeClass() } -+ public var canBeClass: BridgedType.TraitResult { bridged.canBeClass() } - - /// Can only be used if the type is in fact a nominal type (`isNominal` is true). - public var nominal: NominalTypeDecl { -- NominalTypeDecl(_bridged: BridgedNominalTypeDecl(decl: bridged.getNominalOrBoundGenericNominal())) -+ NominalTypeDecl(_bridged: bridged.getNominalOrBoundGenericNominal()) - } - - public var isOrContainsObjectiveCClass: Bool { bridged.isOrContainsObjectiveCClass() } -@@ -73,7 +73,7 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { - public var builtinVectorElementType: Type { bridged.getBuiltinVectorElementType().type } - - public func isBuiltinInteger(withFixedWidth width: Int) -> Bool { -- bridged.isBuiltinFixedWidthInteger(UInt32(width)) -+ bridged.isBuiltinFixedWidthInteger(width) - } - - public func isExactSuperclass(of type: Type) -> Bool { -@@ -87,7 +87,7 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { - } - - public func instanceTypeOfMetatype(in function: Function) -> Type { -- bridged.getInstanceTypeOfMetatype(function.bridged.getFunction()).type -+ bridged.getInstanceTypeOfMetatype(function.bridged).type - } - - public var isCalleeConsumedFunction: Bool { bridged.isCalleeConsumedFunction() } -@@ -95,20 +95,20 @@ public struct Type : CustomStringConvertible, NoReflectionChildren { - public var isMarkedAsImmortal: Bool { bridged.isMarkedAsImmortal() } - - public func getIndexOfEnumCase(withName name: String) -> Int? { -- let idx = name._withStringRef { -+ let idx = name._withBridgedStringRef { - bridged.getCaseIdxOfEnumType($0) - } - return idx >= 0 ? idx : nil - } - - public var description: String { -- String(_cxxString: bridged.getDebugDescription()) -+ String(taking: bridged.getDebugDescription()) - } - } - - extension Type: Equatable { - public static func ==(lhs: Type, rhs: Type) -> Bool { -- lhs.bridged == rhs.bridged -+ lhs.bridged.opaqueValue == rhs.bridged.opaqueValue - } - } - -@@ -160,11 +160,11 @@ public struct NominalFieldsArray : RandomAccessCollection, FormattedLikeArray { - public var endIndex: Int { Int(type.bridged.getNumNominalFields()) } - - public subscript(_ index: Int) -> Type { -- type.bridged.getFieldType(index, function.bridged.getFunction()).type -+ type.bridged.getFieldType(index, function.bridged).type - } - - public func getIndexOfField(withName name: String) -> Int? { -- let idx = name._withStringRef { -+ let idx = name._withBridgedStringRef { - type.bridged.getFieldIdxOfNominalType($0) - } - return idx >= 0 ? idx : nil -@@ -186,7 +186,7 @@ public struct TupleElementArray : RandomAccessCollection, FormattedLikeArray { - } - } - --extension swift.SILType { -+extension BridgedType { - var type: Type { Type(bridged: self) } - var typeOrNil: Type? { isNull() ? nil : type } - } -diff --git a/swift/SwiftCompilerSources/Sources/SIL/VTable.swift b/swift/SwiftCompilerSources/Sources/SIL/VTable.swift -index 95a6da9d9d4..42e37b219d7 100644 ---- a/swift/SwiftCompilerSources/Sources/SIL/VTable.swift -+++ b/swift/SwiftCompilerSources/Sources/SIL/VTable.swift -@@ -23,8 +23,7 @@ public struct VTable : CustomStringConvertible, NoReflectionChildren { - public var function: Function { bridged.getImplementation().function } - - public var description: String { -- let stdString = bridged.getDebugDescription() -- return String(_cxxString: stdString) -+ return String(taking: bridged.getDebugDescription()) - } - } - -@@ -37,7 +36,7 @@ public struct VTable : CustomStringConvertible, NoReflectionChildren { - - public subscript(_ index: Int) -> Entry { - assert(index >= startIndex && index < endIndex) -- return Entry(bridged: BridgedVTableEntry(entry: base.entry + index)) -+ return Entry(bridged: base.advanceBy(index)) - } - } - -@@ -47,7 +46,6 @@ public struct VTable : CustomStringConvertible, NoReflectionChildren { - } - - public var description: String { -- let stdString = bridged.getDebugDescription() -- return String(_cxxString: stdString) -+ return String(taking: bridged.getDebugDescription()) - } - } -diff --git a/swift/SwiftCompilerSources/Sources/SIL/Value.swift b/swift/SwiftCompilerSources/Sources/SIL/Value.swift -index 320bfff10d3..f20c892fdfa 100644 ---- a/swift/SwiftCompilerSources/Sources/SIL/Value.swift -+++ b/swift/SwiftCompilerSources/Sources/SIL/Value.swift -@@ -88,8 +88,7 @@ public enum Ownership { - - extension Value { - public var description: String { -- let stdString = bridged.getDebugDescription() -- return String(_cxxString: stdString) -+ return String(taking: bridged.getDebugDescription()) - } - - public var uses: UseList { UseList(bridged.getFirstUse()) } -diff --git a/swift/SwiftCompilerSources/Sources/SIL/WitnessTable.swift b/swift/SwiftCompilerSources/Sources/SIL/WitnessTable.swift -index 4b4698f7618..f58277fb420 100644 ---- a/swift/SwiftCompilerSources/Sources/SIL/WitnessTable.swift -+++ b/swift/SwiftCompilerSources/Sources/SIL/WitnessTable.swift -@@ -20,8 +20,8 @@ public struct WitnessTable : CustomStringConvertible, NoReflectionChildren { - public struct Entry : CustomStringConvertible, NoReflectionChildren { - fileprivate let bridged: BridgedWitnessTableEntry - -- public typealias Kind = swift.SILWitnessTable.WitnessKind -- -+ public typealias Kind = BridgedWitnessTableEntry.Kind -+ - public var kind: Kind { - return bridged.getKind() - } -@@ -32,8 +32,7 @@ public struct WitnessTable : CustomStringConvertible, NoReflectionChildren { - } - - public var description: String { -- let stdString = bridged.getDebugDescription() -- return String(_cxxString: stdString) -+ return String(taking: bridged.getDebugDescription()) - } - } - -@@ -46,7 +45,7 @@ public struct WitnessTable : CustomStringConvertible, NoReflectionChildren { - - public subscript(_ index: Int) -> Entry { - assert(index >= startIndex && index < endIndex) -- return Entry(bridged: BridgedWitnessTableEntry(entry: base.entry + index)) -+ return Entry(bridged: base.advanceBy(index)) - } - } - -@@ -56,8 +55,7 @@ public struct WitnessTable : CustomStringConvertible, NoReflectionChildren { - } - - public var description: String { -- let stdString = bridged.getDebugDescription() -- return String(_cxxString: stdString) -+ return String(taking: bridged.getDebugDescription()) - } - } - -@@ -75,8 +73,7 @@ public struct DefaultWitnessTable : CustomStringConvertible, NoReflectionChildre - } - - public var description: String { -- let stdString = bridged.getDebugDescription() -- return String(_cxxString: stdString) -+ return String(taking: bridged.getDebugDescription()) - } - } - -diff --git a/swift/cmake/modules/SwiftSharedCMakeConfig.cmake b/swift/cmake/modules/SwiftSharedCMakeConfig.cmake -index 6679f404db2..4e7a033f40e 100644 ---- a/swift/cmake/modules/SwiftSharedCMakeConfig.cmake -+++ b/swift/cmake/modules/SwiftSharedCMakeConfig.cmake -@@ -351,6 +351,10 @@ macro(swift_common_cxx_warnings) - - # Disallow calls to objc_msgSend() with no function pointer cast. - set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DOBJC_OLD_DISPATCH_PROTOTYPES=0") -+ -+ if(BRIDGING_MODE STREQUAL "PURE") -+ set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -DPURE_BRIDGING_MODE") -+ endif() - endmacro() - - # Like 'llvm_config()', but uses libraries from the selected build -diff --git a/swift/include/module.modulemap b/swift/include/module.modulemap -index 2e421469dd1..78fe887a51e 100644 ---- a/swift/include/module.modulemap -+++ b/swift/include/module.modulemap -@@ -1,7 +1,5 @@ - module BasicBridging { -- header "swift/Basic/BridgedSwiftObject.h" - header "swift/Basic/BasicBridging.h" -- header "swift/Basic/SourceLoc.h" - requires cplusplus - export * - } -@@ -11,17 +9,7 @@ module CBasicBridging { - } - - module ASTBridging { -- header "swift/AST/AnyFunctionRef.h" - header "swift/AST/ASTBridging.h" -- header "swift/AST/Builtins.h" -- header "swift/AST/DiagnosticEngine.h" -- header "swift/AST/DiagnosticConsumer.h" -- header "swift/AST/ForeignAsyncConvention.h" -- header "swift/AST/ForeignErrorConvention.h" -- header "swift/AST/SubstitutionMap.h" -- -- textual header "swift/AST/Builtins.def" -- - requires cplusplus - export * - } -@@ -32,7 +20,6 @@ module CASTBridging { - - module SILBridging { - header "swift/SIL/SILBridging.h" -- header "swift/SIL/SILLocation.h" - requires cplusplus - export * - } -diff --git a/swift/include/swift/AST/ASTBridging.h b/swift/include/swift/AST/ASTBridging.h -index d02968cf85c..3d26622667e 100644 ---- a/swift/include/swift/AST/ASTBridging.h -+++ b/swift/include/swift/AST/ASTBridging.h -@@ -13,15 +13,22 @@ - #ifndef SWIFT_AST_ASTBRIDGING_H - #define SWIFT_AST_ASTBRIDGING_H - --#include "swift/AST/DiagnosticEngine.h" -+// Do not add other C++/llvm/swift header files here! -+// Function implementations should be placed into ASTBridging.cpp and required header files should be added there. -+// - #include "swift/Basic/BasicBridging.h" --#include "swift/Basic/Compiler.h" --#include "swift/Basic/Nullability.h" --#include --#include -+ -+#ifdef USED_IN_CPP_SOURCE -+#include "swift/AST/DiagnosticConsumer.h" -+#include "swift/AST/DiagnosticEngine.h" -+#endif - - SWIFT_BEGIN_NULLABILITY_ANNOTATIONS - -+namespace swift { -+ class DiagnosticArgument; -+} -+ - //===----------------------------------------------------------------------===// - // Diagnostic Engine - //===----------------------------------------------------------------------===// -@@ -33,24 +40,56 @@ typedef enum ENUM_EXTENSIBILITY_ATTR(open) BridgedDiagID : uint32_t { - #include "swift/AST/DiagnosticsAll.def" - } BridgedDiagID; - -+// Must match the definition of BridgedDiagnosticEngine in CASTBridging.h. - typedef struct { - void * _Nonnull object; - } BridgedDiagnosticEngine; - --typedef struct { -+struct BridgedOptionalDiagnosticEngine { - void *_Nullable object; --} BridgedOptionalDiagnosticEngine; -+}; -+ -+class BridgedDiagnosticArgument { -+ int64_t storage[3]; -+ -+public: -+#ifdef USED_IN_CPP_SOURCE -+ BridgedDiagnosticArgument(const swift::DiagnosticArgument &arg) { -+ *reinterpret_cast(&storage) = arg; -+ } -+ const swift::DiagnosticArgument &get() const { -+ return *reinterpret_cast(&storage); -+ } -+#endif -+ -+ BridgedDiagnosticArgument(SwiftInt i); -+ BridgedDiagnosticArgument(BridgedStringRef s); -+}; -+ -+class BridgedDiagnosticFixIt { -+ int64_t storage[7]; -+ -+public: -+#ifdef USED_IN_CPP_SOURCE -+ BridgedDiagnosticFixIt(const swift::DiagnosticInfo::FixIt &fixit){ -+ *reinterpret_cast(&storage) = fixit; -+ } -+ const swift::DiagnosticInfo::FixIt &get() const { -+ return *reinterpret_cast(&storage); -+ } -+#endif -+ -+ BridgedDiagnosticFixIt(BridgedSourceLoc start, uint32_t length, BridgedStringRef text); -+}; - - // FIXME: Can we bridge InFlightDiagnostic? --void DiagnosticEngine_diagnose(BridgedDiagnosticEngine, swift::SourceLoc loc, -+void DiagnosticEngine_diagnose(BridgedDiagnosticEngine, BridgedSourceLoc loc, - BridgedDiagID diagID, BridgedArrayRef arguments, -- swift::CharSourceRange highlight, -+ BridgedSourceLoc highlightStart, uint32_t hightlightLength, - BridgedArrayRef fixIts); - - bool DiagnosticEngine_hadAnyError(BridgedDiagnosticEngine); - --using ArrayRefOfDiagnosticArgument = llvm::ArrayRef; -- - SWIFT_END_NULLABILITY_ANNOTATIONS - - #endif // SWIFT_AST_ASTBRIDGING_H -diff --git a/swift/include/swift/AST/Decl.h b/swift/include/swift/AST/Decl.h -index 80330b15548..e6ba3651e6f 100644 ---- a/swift/include/swift/AST/Decl.h -+++ b/swift/include/swift/AST/Decl.h -@@ -26,6 +26,8 @@ - #include "swift/AST/DefaultArgumentKind.h" - #include "swift/AST/DiagnosticConsumer.h" - #include "swift/AST/DiagnosticEngine.h" -+#include "swift/AST/ForeignAsyncConvention.h" -+#include "swift/AST/ForeignErrorConvention.h" - #include "swift/AST/FreestandingMacroExpansion.h" - #include "swift/AST/GenericParamKey.h" - #include "swift/AST/IfConfigClause.h" -@@ -72,8 +74,6 @@ namespace swift { - struct ExternalSourceLocs; - class CaptureListExpr; - class DeclRefExpr; -- class ForeignAsyncConvention; -- class ForeignErrorConvention; - class LiteralExpr; - class BraceStmt; - class DeclAttributes; -diff --git a/swift/include/swift/Basic/BasicBridging.h b/swift/include/swift/Basic/BasicBridging.h -index f11083e83a0..8988bb75eb3 100644 ---- a/swift/include/swift/Basic/BasicBridging.h -+++ b/swift/include/swift/Basic/BasicBridging.h -@@ -13,31 +13,100 @@ - #ifndef SWIFT_BASIC_BASICBRIDGING_H - #define SWIFT_BASIC_BASICBRIDGING_H - -+#if !defined(COMPILED_WITH_SWIFT) || !defined(PURE_BRIDGING_MODE) -+#define USED_IN_CPP_SOURCE -+#endif -+ -+// Do not add other C++/llvm/swift header files here! -+// Function implementations should be placed into BasicBridging.cpp and required header files should be added there. -+// -+#include "swift/Basic/BridgedSwiftObject.h" -+#include "swift/Basic/Compiler.h" -+ -+#include -+#include -+#ifdef USED_IN_CPP_SOURCE - // Workaround to avoid a compiler error because `cas::ObjectRef` is not defined - // when including VirtualFileSystem.h - #include - #include "llvm/CAS/CASReference.h" - --#include "swift/Basic/BridgedSwiftObject.h" --#include "swift/Basic/Nullability.h" --#include "swift/Basic/SourceLoc.h" --#include -+#include "llvm/ADT/StringRef.h" -+#include -+#endif -+ -+#ifdef PURE_BRIDGING_MODE -+// In PURE_BRIDGING_MODE, briding functions are not inlined -+#define BRIDGED_INLINE -+#else -+#define BRIDGED_INLINE inline -+#endif - - SWIFT_BEGIN_NULLABILITY_ANNOTATIONS - - typedef intptr_t SwiftInt; - typedef uintptr_t SwiftUInt; - --typedef struct { -- const void * _Nullable data; -- size_t numElements; --} BridgedArrayRef; -- --typedef struct { -+struct BridgedOStream { - void * _Nonnull streamAddr; --} BridgedOStream; -+}; - --void OStream_write(BridgedOStream os, llvm::StringRef str); -+class BridgedStringRef { -+ const char * _Nonnull data; -+ size_t length; -+ -+public: -+#ifdef USED_IN_CPP_SOURCE -+ BridgedStringRef(llvm::StringRef sref) : data(sref.data()), length(sref.size()) {} -+ -+ llvm::StringRef get() const { return llvm::StringRef(data, length); } -+#endif -+ -+ BridgedStringRef(const char * _Nullable data, size_t length) -+ : data(data), length(length) {} -+ -+ SWIFT_IMPORT_UNSAFE const uint8_t * _Nonnull uintData() const { -+ return (const uint8_t * _Nonnull)data; -+ } -+ SwiftInt size() const { return (SwiftInt)length; } -+ void write(BridgedOStream os) const; -+}; -+ -+class BridgedOwnedString { -+ char * _Nonnull data; -+ size_t length; -+ -+public: -+#ifdef USED_IN_CPP_SOURCE -+ BridgedOwnedString(const std::string &stringToCopy); -+#endif -+ -+ SWIFT_IMPORT_UNSAFE const uint8_t * _Nonnull uintData() const { -+ return (const uint8_t * _Nonnull)(data ? data : ""); -+ } -+ SwiftInt size() const { return (SwiftInt)length; } -+ void destroy() const; -+}; -+ -+class BridgedSourceLoc { -+ const void * _Nullable opaquePointer; -+public: -+ BridgedSourceLoc() : opaquePointer(nullptr) {} -+ BridgedSourceLoc(const void * _Nullable loc) : opaquePointer(loc) {} -+ -+ bool isValid() const { return opaquePointer != nullptr; } -+ SWIFT_IMPORT_UNSAFE const uint8_t * _Nullable uint8Pointer() const { -+ return (const uint8_t * _Nullable)opaquePointer; -+ } -+ const char * _Nullable getLoc() const { -+ return (const char * _Nullable)opaquePointer; -+ } -+}; -+ -+struct BridgedArrayRef { -+ const void * _Nullable data; -+ size_t numElements; -+}; - - SWIFT_END_NULLABILITY_ANNOTATIONS - -diff --git a/swift/include/swift/SIL/SILBridging.h b/swift/include/swift/SIL/SILBridging.h -index f7492f25592..1dd794aeacd 100644 ---- a/swift/include/swift/SIL/SILBridging.h -+++ b/swift/include/swift/SIL/SILBridging.h -@@ -13,24 +13,18 @@ - #ifndef SWIFT_SIL_SILBRIDGING_H - #define SWIFT_SIL_SILBRIDGING_H - --#include "swift/AST/Builtins.h" --#include "swift/AST/Decl.h" --#include "swift/AST/SubstitutionMap.h" -+// Do not add other C++/llvm/swift header files here! -+// Function implementations should be placed into SILBridgingImpl.h or SILBridging.cpp and -+// required header files should be added there. -+// - #include "swift/Basic/BasicBridging.h" --#include "swift/Basic/BridgedSwiftObject.h" --#include "swift/Basic/Nullability.h" --#include "swift/SIL/ApplySite.h" -+ -+#ifdef USED_IN_CPP_SOURCE -+#include "llvm/ADT/ArrayRef.h" - #include "swift/SIL/SILBuilder.h" --#include "swift/SIL/SILDefaultWitnessTable.h" --#include "swift/SIL/SILFunctionConventions.h" - #include "swift/SIL/SILInstruction.h" --#include "swift/SIL/SILLocation.h" --#include "swift/SIL/SILModule.h" --#include "swift/SIL/SILVTable.h" - #include "swift/SIL/SILWitnessTable.h" --#include --#include --#include -+#endif - - SWIFT_BEGIN_NULLABILITY_ANNOTATIONS - -@@ -38,11 +32,100 @@ struct BridgedInstruction; - struct OptionalBridgedInstruction; - struct OptionalBridgedOperand; - struct OptionalBridgedSuccessor; -+struct BridgedFunction; - struct BridgedBasicBlock; - struct BridgedSuccessorArray; - struct OptionalBridgedBasicBlock; -+struct BridgedNominalTypeDecl; -+ -+namespace swift { -+class ValueBase; -+class Operand; -+class SILFunction; -+class SILBasicBlock; -+class SILSuccessor; -+class SILGlobalVariable; -+class SILInstruction; -+class SILArgument; -+class MultipleValueInstructionResult; -+class SILVTableEntry; -+class SILVTable; -+class SILWitnessTable; -+class SILDefaultWitnessTable; -+class NominalTypeDecl; -+class SwiftPassInvocation; -+class GenericSpecializationInformation; -+} -+ -+void registerBridgedClass(BridgedStringRef className, SwiftMetatype metatype); -+ -+struct BridgedType { -+ void * _Nullable opaqueValue; -+ -+ enum class MetatypeRepresentation { -+ Thin, -+ Thick, -+ ObjC -+ }; -+ -+ enum class TraitResult { -+ IsNot, -+ CanBe, -+ Is -+ }; -+ -+#ifdef USED_IN_CPP_SOURCE -+ BridgedType(swift::SILType t) : opaqueValue(t.getOpaqueValue()) {} -+ -+ swift::SILType get() const { -+ return swift::SILType::getFromOpaqueValue(opaqueValue); -+ } -+#endif - --void registerBridgedClass(llvm::StringRef className, SwiftMetatype metatype); -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedOwnedString getDebugDescription() const; -+ BRIDGED_INLINE bool isNull() const; -+ BRIDGED_INLINE bool isAddress() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getAddressType() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getObjectType() const; -+ BRIDGED_INLINE bool isTrivial(BridgedFunction f) const; -+ BRIDGED_INLINE bool isNonTrivialOrContainsRawPointer(BridgedFunction f) const; -+ BRIDGED_INLINE bool isValueTypeWithDeinit() const; -+ BRIDGED_INLINE bool isLoadable(BridgedFunction f) const; -+ BRIDGED_INLINE bool isReferenceCounted(BridgedFunction f) const; -+ BRIDGED_INLINE bool isUnownedStorageType() const; -+ BRIDGED_INLINE bool hasArchetype() const; -+ BRIDGED_INLINE bool isNominalOrBoundGenericNominal() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedNominalTypeDecl getNominalOrBoundGenericNominal() const; -+ BRIDGED_INLINE bool isClassOrBoundGenericClass() const; -+ BRIDGED_INLINE bool isStructOrBoundGenericStruct() const; -+ BRIDGED_INLINE bool isTuple() const; -+ BRIDGED_INLINE bool isEnumOrBoundGenericEnum() const; -+ BRIDGED_INLINE bool isFunction() const; -+ BRIDGED_INLINE bool isMetatype() const; -+ BRIDGED_INLINE bool isNoEscapeFunction() const; -+ // BRIDGED_INLINE bool isAsyncFunction() const; -+ BRIDGED_INLINE TraitResult canBeClass() const; -+ BRIDGED_INLINE bool isMoveOnly() const; -+ BRIDGED_INLINE bool isOrContainsObjectiveCClass() const; -+ BRIDGED_INLINE bool isBuiltinInteger() const; -+ BRIDGED_INLINE bool isBuiltinFloat() const; -+ BRIDGED_INLINE bool isBuiltinVector() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getBuiltinVectorElementType() const; -+ BRIDGED_INLINE bool isBuiltinFixedWidthInteger(SwiftInt width) const; -+ BRIDGED_INLINE bool isExactSuperclassOf(BridgedType t) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getInstanceTypeOfMetatype(BridgedFunction f) const; -+ BRIDGED_INLINE bool isDynamicSelfMetatype() const; -+ // BRIDGED_INLINE MetatypeRepresentation getRepresentationOfMetatype(BridgedFunction f) const; -+ BRIDGED_INLINE bool isCalleeConsumedFunction() const; -+ BRIDGED_INLINE bool isMarkedAsImmortal() const; -+ BRIDGED_INLINE SwiftInt getCaseIdxOfEnumType(BridgedStringRef name) const; -+ BRIDGED_INLINE SwiftInt getNumNominalFields() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getFieldType(SwiftInt idx, BridgedFunction f) const; -+ BRIDGED_INLINE SwiftInt getFieldIdxOfNominalType(BridgedStringRef name) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef getFieldName(SwiftInt idx) const; -+ BRIDGED_INLINE SwiftInt getNumTupleElements() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getTupleElementType(SwiftInt idx) const; -+}; - - struct BridgedValue { - SwiftObject obj; -@@ -63,49 +145,31 @@ struct BridgedValue { - None - }; - -- Kind getKind() const; -- -- swift::SILValue getSILValue() const { return static_cast(obj); } -- -- std::string getDebugDescription() const; -- -- SWIFT_IMPORT_UNSAFE -- inline OptionalBridgedOperand getFirstUse() const; -- -- SWIFT_IMPORT_UNSAFE -- swift::SILType getType() const { return getSILValue()->getType(); } -- -- Ownership getOwnership() const { -- switch (getSILValue()->getOwnershipKind()) { -- case swift::OwnershipKind::Any: -- llvm_unreachable("Invalid ownership for value"); -- case swift::OwnershipKind::Unowned: return Ownership::Unowned; -- case swift::OwnershipKind::Owned: return Ownership::Owned; -- case swift::OwnershipKind::Guaranteed: return Ownership::Guaranteed; -- case swift::OwnershipKind::None: return Ownership::None; -+#ifdef USED_IN_CPP_SOURCE -+ static swift::ValueOwnershipKind castToOwnership(BridgedValue::Ownership ownership) { -+ switch (ownership) { -+ case BridgedValue::Ownership::Unowned: return swift::OwnershipKind::Unowned; -+ case BridgedValue::Ownership::Owned: return swift::OwnershipKind::Owned; -+ case BridgedValue::Ownership::Guaranteed: return swift::OwnershipKind::Guaranteed; -+ case BridgedValue::Ownership::None: return swift::OwnershipKind::None; - } - } -+#endif -+ -+ Kind getKind() const; -+ BRIDGED_INLINE swift::ValueBase * _Nonnull getSILValue() const; -+ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedOperand getFirstUse() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getType() const; -+ BRIDGED_INLINE Ownership getOwnership() const; - }; - - struct OptionalBridgedValue { - OptionalSwiftObject obj; - -- swift::SILValue getSILValue() const { -- if (obj) -- return static_cast(obj); -- return swift::SILValue(); -- } -+ BRIDGED_INLINE swift::ValueBase * _Nullable getSILValue() const; - }; - --inline swift::ValueOwnershipKind castToOwnership(BridgedValue::Ownership ownership) { -- switch (ownership) { -- case BridgedValue::Ownership::Unowned: return swift::OwnershipKind::Unowned; -- case BridgedValue::Ownership::Owned: return swift::OwnershipKind::Owned; -- case BridgedValue::Ownership::Guaranteed: return swift::OwnershipKind::Guaranteed; -- case BridgedValue::Ownership::None: return swift::OwnershipKind::None; -- } --} -- - // This is the layout of a class existential. - struct BridgeValueExistential { - BridgedValue value; -@@ -116,33 +179,31 @@ struct BridgedValueArray { - const BridgeValueExistential * _Nullable base; - size_t count; - -+#ifdef USED_IN_CPP_SOURCE - llvm::ArrayRef getValues(llvm::SmallVectorImpl &storage); -+#endif - }; - - struct BridgedOperand { - swift::Operand * _Nonnull op; - -- bool isTypeDependent() const { return op->isTypeDependent(); } -- -- SWIFT_IMPORT_UNSAFE -- inline OptionalBridgedOperand getNextUse() const; -- -- SWIFT_IMPORT_UNSAFE -- BridgedValue getValue() const { return {op->get()}; } -- -- SWIFT_IMPORT_UNSAFE -- inline BridgedInstruction getUser() const; -+ BRIDGED_INLINE bool isTypeDependent() const; -+ BRIDGED_INLINE bool isLifetimeEnding() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedOperand getNextUse() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedValue getValue() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction getUser() const; -+ //BRIDGED_INLINE OperandOwnership getOperandOwnership() const; - }; - - struct OptionalBridgedOperand { - swift::Operand * _Nullable op; - - // Assumes that `op` is not null. -- SWIFT_IMPORT_UNSAFE -- BridgedOperand advancedBy(SwiftInt index) const { return {op + index}; } -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE -+ BridgedOperand advancedBy(SwiftInt index) const; - - // Assumes that `op` is not null. -- SwiftInt distanceTo(BridgedOperand element) const { return element.op - op; } -+ BRIDGED_INLINE SwiftInt distanceTo(BridgedOperand element) const; - }; - - struct BridgedOperandArray { -@@ -154,153 +215,81 @@ struct BridgedOperandArray { - // Currently it's not possible to switch over `SILArgumentConvention::ConventionType`, - // because it's not a class enum. - enum class BridgedArgumentConvention { -- Indirect_In = swift::SILArgumentConvention::Indirect_In, -- Indirect_In_Guaranteed = swift::SILArgumentConvention::Indirect_In_Guaranteed, -- Indirect_Inout = swift::SILArgumentConvention::Indirect_Inout, -- Indirect_InoutAliasable = swift::SILArgumentConvention::Indirect_InoutAliasable, -- Indirect_Out = swift::SILArgumentConvention::Indirect_Out, -- Direct_Owned = swift::SILArgumentConvention::Direct_Owned, -- Direct_Unowned = swift::SILArgumentConvention::Direct_Unowned, -- Direct_Guaranteed = swift::SILArgumentConvention::Direct_Guaranteed, -- Pack_Owned = swift::SILArgumentConvention::Pack_Owned, -- Pack_Inout = swift::SILArgumentConvention::Pack_Inout, -- Pack_Guaranteed = swift::SILArgumentConvention::Pack_Guaranteed, -- Pack_Out = swift::SILArgumentConvention::Pack_Out -+ Indirect_In, -+ Indirect_In_Guaranteed, -+ Indirect_Inout, -+ Indirect_InoutAliasable, -+ Indirect_Out, -+ Direct_Owned, -+ Direct_Unowned, -+ Direct_Guaranteed, -+ Pack_Owned, -+ Pack_Inout, -+ Pack_Guaranteed, -+ Pack_Out -+}; -+ -+enum class BridgedMemoryBehavior { -+ None, -+ MayRead, -+ MayWrite, -+ MayReadWrite, -+ MayHaveSideEffects - }; - --inline BridgedArgumentConvention castToArgumentConvention(swift::SILArgumentConvention convention) { -- return static_cast(convention.Value); --} -- - struct BridgedFunction { - SwiftObject obj; - -- SWIFT_IMPORT_UNSAFE -- swift::SILFunction * _Nonnull getFunction() const { -- return static_cast(obj); -- } -- -- SWIFT_IMPORT_UNSAFE -- llvm::StringRef getName() const { return getFunction()->getName(); } -- -- std::string getDebugDescription() const; -- -- bool hasOwnership() const { return getFunction()->hasOwnership(); } -- -- SWIFT_IMPORT_UNSAFE -- inline OptionalBridgedBasicBlock getFirstBlock() const; -- -- SWIFT_IMPORT_UNSAFE -- inline OptionalBridgedBasicBlock getLastBlock() const; -- -- SwiftInt getNumIndirectFormalResults() const { -- return (SwiftInt)getFunction()->getLoweredFunctionType()->getNumIndirectFormalResults(); -- } -- -- SwiftInt getNumParameters() const { -- return (SwiftInt)getFunction()->getLoweredFunctionType()->getNumParameters(); -- } -- -- SwiftInt getSelfArgumentIndex() const { -- swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); -- swift::CanSILFunctionType fTy = getFunction()->getLoweredFunctionType(); -- if (!fTy->hasSelfParam()) -- return -1; -- return conv.getNumParameters() + conv.getNumIndirectSILResults() - 1; -- } -- -- SwiftInt getNumSILArguments() const { -- return swift::SILFunctionConventions(getFunction()->getConventionsInContext()).getNumSILArguments(); -- } -- -- swift::SILType getSILArgumentType(SwiftInt idx) const { -- swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); -- return conv.getSILArgumentType(idx, getFunction()->getTypeExpansionContext()); -- } -- -- BridgedArgumentConvention getSILArgumentConvention(SwiftInt idx) const { -- swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); -- return castToArgumentConvention(conv.getSILArgumentConvention(idx)); -- } -- -- swift::SILType getSILResultType() const { -- swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); -- return conv.getSILResultType(getFunction()->getTypeExpansionContext()); -- } -- -- bool isSwift51RuntimeAvailable() const { -- if (getFunction()->getResilienceExpansion() != swift::ResilienceExpansion::Maximal) -- return false; -- -- swift::ASTContext &ctxt = getFunction()->getModule().getASTContext(); -- return swift::AvailabilityContext::forDeploymentTarget(ctxt).isContainedIn(ctxt.getSwift51Availability()); -- } -- -- bool isPossiblyUsedExternally() const { -- return getFunction()->isPossiblyUsedExternally(); -- } -- -- bool isAvailableExternally() const { -- return getFunction()->isAvailableExternally(); -- } -- -- bool isTransparent() const { -- return getFunction()->isTransparent() == swift::IsTransparent; -- } -- -- bool isAsync() const { -- return getFunction()->isAsync(); -- } -- -- bool isGlobalInitFunction() const { -- return getFunction()->isGlobalInit(); -- } -- -- bool isGlobalInitOnceFunction() const { -- return getFunction()->isGlobalInitOnceFunction(); -- } -- -- bool isGenericFunction() const { -- return getFunction()->getGenericSignature().isNull(); -- } -- -- bool hasSemanticsAttr(llvm::StringRef attrName) const { -- return getFunction()->hasSemanticsAttr(attrName); -- } -- -- swift::EffectsKind getEffectAttribute() const { -- return getFunction()->getEffectsKind(); -- } -+ enum class EffectsKind { -+ ReadNone, -+ ReadOnly, -+ ReleaseNone, -+ ReadWrite, -+ Unspecified, -+ Custom -+ }; - -- swift::PerformanceConstraints getPerformanceConstraints() const { -- return getFunction()->getPerfConstraints(); -- } -+ enum class PerformanceConstraints { -+ None = 0, -+ NoAllocation = 1, -+ NoLocks = 2 -+ }; - - enum class InlineStrategy { -- InlineDefault = swift::InlineDefault, -- NoInline = swift::NoInline, -- AlwaysInline = swift::AlwaysInline -+ InlineDefault, -+ NoInline, -+ AlwaysInline - }; - -- InlineStrategy getInlineStrategy() const { -- return (InlineStrategy)getFunction()->getInlineStrategy(); -- } -- -- bool isSerialized() const { -- return getFunction()->isSerialized(); -- } -- -- bool hasValidLinkageForFragileRef() const { -- return getFunction()->hasValidLinkageForFragileRef(); -- } -- -- bool needsStackProtection() const { -- return getFunction()->needsStackProtection(); -- } -- -- void setNeedStackProtection(bool needSP) const { -- getFunction()->setNeedStackProtection(needSP); -- } -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE swift::SILFunction * _Nonnull getFunction() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef getName() const; -+ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; -+ BRIDGED_INLINE bool hasOwnership() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedBasicBlock getFirstBlock() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedBasicBlock getLastBlock() const; -+ BRIDGED_INLINE SwiftInt getNumIndirectFormalResults() const; -+ BRIDGED_INLINE SwiftInt getNumParameters() const; -+ BRIDGED_INLINE SwiftInt getSelfArgumentIndex() const; -+ BRIDGED_INLINE SwiftInt getNumSILArguments() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getSILArgumentType(SwiftInt idx) const; -+ BRIDGED_INLINE BridgedArgumentConvention getSILArgumentConvention(SwiftInt idx) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedType getSILResultType() const; -+ BRIDGED_INLINE bool isSwift51RuntimeAvailable() const; -+ BRIDGED_INLINE bool isPossiblyUsedExternally() const; -+ BRIDGED_INLINE bool isAvailableExternally() const; -+ BRIDGED_INLINE bool isTransparent() const; -+ BRIDGED_INLINE bool isAsync() const; -+ BRIDGED_INLINE bool isGlobalInitFunction() const; -+ BRIDGED_INLINE bool isGlobalInitOnceFunction() const; -+ BRIDGED_INLINE bool isGenericFunction() const; -+ BRIDGED_INLINE bool hasSemanticsAttr(BridgedStringRef attrName) const; -+ BRIDGED_INLINE EffectsKind getEffectAttribute() const; -+ BRIDGED_INLINE PerformanceConstraints getPerformanceConstraints() const; -+ BRIDGED_INLINE InlineStrategy getInlineStrategy() const; -+ BRIDGED_INLINE bool isSerialized() const; -+ BRIDGED_INLINE bool hasValidLinkageForFragileRef() const; -+ BRIDGED_INLINE bool needsStackProtection() const; -+ BRIDGED_INLINE void setNeedStackProtection(bool needSP) const; - - enum class ParseEffectsMode { - argumentEffectsFromSource, -@@ -324,12 +313,12 @@ struct BridgedFunction { - typedef void (* _Nonnull RegisterFn)(BridgedFunction f, void * _Nonnull data, SwiftInt size); - typedef void (* _Nonnull WriteFn)(BridgedFunction, BridgedOStream, SwiftInt); - typedef ParsingError (*_Nonnull ParseFn)(BridgedFunction, -- llvm::StringRef, -+ BridgedStringRef, - ParseEffectsMode, SwiftInt, - BridgedArrayRef); - typedef SwiftInt (* _Nonnull CopyEffectsFn)(BridgedFunction, BridgedFunction); - typedef EffectInfo (* _Nonnull GetEffectInfoFn)(BridgedFunction, SwiftInt); -- typedef swift::MemoryBehavior (* _Nonnull GetMemBehaviorFn)(BridgedFunction, bool); -+ typedef BridgedMemoryBehavior (* _Nonnull GetMemBehaviorFn)(BridgedFunction, bool); - - static void registerBridging(SwiftMetatype metatype, - RegisterFn initFn, RegisterFn destroyFn, -@@ -347,34 +336,15 @@ struct BridgedGlobalVar { - SwiftObject obj; - - BridgedGlobalVar(SwiftObject obj) : obj(obj) {} -- -- SWIFT_IMPORT_UNSAFE -- swift::SILGlobalVariable * _Nonnull getGlobal() const { -- return static_cast(obj); -- } -- -- std::string getDebugDescription() const; -- -- SWIFT_IMPORT_UNSAFE -- llvm::StringRef getName() const { return getGlobal()->getName(); } -- -- bool isLet() const { return getGlobal()->isLet(); } -- -- void setLet(bool value) const { getGlobal()->setLet(value); } -- -- bool isPossiblyUsedExternally() const { -- return getGlobal()->isPossiblyUsedExternally(); -- } -- -- bool isAvailableExternally() const { -- return swift::isAvailableExternally(getGlobal()->getLinkage()); -- } -- -- SWIFT_IMPORT_UNSAFE -- inline OptionalBridgedInstruction getFirstStaticInitInst() const; -- -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE swift::SILGlobalVariable * _Nonnull getGlobal() const; -+ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef getName() const; -+ BRIDGED_INLINE bool isLet() const; -+ BRIDGED_INLINE void setLet(bool value) const; -+ BRIDGED_INLINE bool isPossiblyUsedExternally() const; -+ BRIDGED_INLINE bool isAvailableExternally() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedInstruction getFirstStaticInitInst() const; - bool canBeInitializedStatically() const; -- - bool mustBeInitializedStatically() const; - }; - -@@ -385,410 +355,137 @@ struct OptionalBridgedGlobalVar { - struct BridgedMultiValueResult { - SwiftObject obj; - -- swift::MultipleValueInstructionResult * _Nonnull getMVResult() const { -+#ifdef USED_IN_CPP_SOURCE -+ swift::MultipleValueInstructionResult * _Nonnull get() const { - return static_cast(obj); - } -+#endif - -- SWIFT_IMPORT_UNSAFE -- inline BridgedInstruction getParent() const; -- -- SwiftInt getIndex() const { -- return (SwiftInt)getMVResult()->getIndex(); -- } -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction getParent() const; -+ BRIDGED_INLINE SwiftInt getIndex() const; - }; - --struct OptionalBridgedInstruction { -- OptionalSwiftObject obj; -- -- OptionalBridgedInstruction() : obj(nullptr) {} -+struct BridgedSubstitutionMap { -+ uint64_t storage[1]; - -- OptionalBridgedInstruction(OptionalSwiftObject obj) : obj(obj) {} -- -- swift::SILInstruction * _Nullable getInst() const { -- if (!obj) -- return nullptr; -- return llvm::cast(static_cast(obj)->castToInstruction()); -+#ifdef USED_IN_CPP_SOURCE -+ BridgedSubstitutionMap(swift::SubstitutionMap map) { -+ *reinterpret_cast(&storage) = map; -+ } -+ swift::SubstitutionMap get() const { -+ return *reinterpret_cast(&storage); - } -+#endif -+ -+ BRIDGED_INLINE BridgedSubstitutionMap(); -+ BRIDGED_INLINE bool isEmpty() const; - }; - - struct BridgedTypeArray { -- llvm::ArrayRef typeArray; -+ BridgedArrayRef typeArray; - -- SWIFT_IMPORT_UNSAFE -- static BridgedTypeArray fromReplacementTypes(swift::SubstitutionMap substMap) { -- return {substMap.getReplacementTypes()}; -- } -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE -+ static BridgedTypeArray fromReplacementTypes(BridgedSubstitutionMap substMap); - -- SwiftInt getCount() const { return SwiftInt(typeArray.size()); } -+ SwiftInt getCount() const { return SwiftInt(typeArray.numElements); } - -- SWIFT_IMPORT_UNSAFE -- swift::SILType getAt(SwiftInt index) const { -- auto ty = typeArray[index]->getCanonicalType(); -- if (ty->isLegalSILType()) -- return swift::SILType::getPrimitiveObjectType(ty); -- return swift::SILType(); -- } -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE -+ BridgedType getAt(SwiftInt index) const; - }; - - struct BridgedSILTypeArray { -- llvm::ArrayRef typeArray; -+ BridgedArrayRef typeArray; - -- SwiftInt getCount() const { return SwiftInt(typeArray.size()); } -+ SwiftInt getCount() const { return SwiftInt(typeArray.numElements); } - -- SWIFT_IMPORT_UNSAFE -- swift::SILType getAt(SwiftInt index) const { return typeArray[index]; } -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE -+ BridgedType getAt(SwiftInt index) const; - }; - --struct BridgedInstruction { -- SwiftObject obj; -- -- BridgedInstruction(SwiftObject obj) : obj(obj) {} -- -- template I *_Nonnull getAs() const { -- return llvm::cast(static_cast(obj)->castToInstruction()); -- } -- -- swift::SILInstruction * _Nonnull getInst() const { return getAs(); } -- -- std::string getDebugDescription() const; -- -- SWIFT_IMPORT_UNSAFE -- OptionalBridgedInstruction getNext() const { -- auto iter = std::next(getInst()->getIterator()); -- if (iter == getInst()->getParent()->end()) -- return {nullptr}; -- return {iter->asSILNode()}; -- } -- -- SWIFT_IMPORT_UNSAFE -- OptionalBridgedInstruction getPrevious() const { -- auto iter = std::next(getInst()->getReverseIterator()); -- if (iter == getInst()->getParent()->rend()) -- return {nullptr}; -- return {iter->asSILNode()}; -- } -- -- SWIFT_IMPORT_UNSAFE -- inline BridgedBasicBlock getParent() const; -- -- SWIFT_IMPORT_UNSAFE -- inline BridgedInstruction getLastInstOfParent() const; -+struct BridgedLocation { -+ uint64_t storage[3]; - -- bool isDeleted() const { -- return getInst()->isDeleted(); -+#ifdef USED_IN_CPP_SOURCE -+ BridgedLocation(const swift::SILDebugLocation &loc) { -+ *reinterpret_cast(&storage) = loc; - } - -- SWIFT_IMPORT_UNSAFE -- BridgedOperandArray getOperands() const { -- auto operands = getInst()->getAllOperands(); -- return {{operands.data()}, (SwiftInt)operands.size()}; -+ const swift::SILDebugLocation &getLoc() const { -+ return *reinterpret_cast(&storage); - } -+#endif - -- void setOperand(SwiftInt index, BridgedValue value) const { -- getInst()->setOperand((unsigned)index, value.getSILValue()); -- } -+ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedLocation getAutogeneratedLocation() const; -+ BRIDGED_INLINE bool hasValidLineNumber() const; -+ BRIDGED_INLINE bool isAutoGenerated() const; -+ BRIDGED_INLINE bool isEqualTo(BridgedLocation rhs) const; -+ BRIDGED_INLINE bool hasSameSourceLocation(BridgedLocation rhs) const; -+ static BRIDGED_INLINE BridgedLocation getArtificialUnreachableLocation(); -+}; - -- SWIFT_IMPORT_UNSAFE -- swift::SILDebugLocation getLocation() const { -- return getInst()->getDebugLocation(); -- } -+struct BridgedGenericSpecializationInformation { -+ const swift::GenericSpecializationInformation * _Nullable data = nullptr; -+}; - -- swift::MemoryBehavior getMemBehavior() const { -- return getInst()->getMemoryBehavior(); -- } -+struct BridgedInstruction { -+ SwiftObject obj; - -- bool mayRelease() const { -- return getInst()->mayRelease(); -+#ifdef USED_IN_CPP_SOURCE -+ template I *_Nonnull getAs() const { -+ return llvm::cast(static_cast(obj)->castToInstruction()); - } -- -- bool mayHaveSideEffects() const { -- return getInst()->mayHaveSideEffects(); -+ swift::SILInstruction * _Nonnull get() const { -+ return getAs(); - } -+#endif - -+ BridgedInstruction(SwiftObject obj) : obj(obj) {} -+ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedInstruction getNext() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedInstruction getPrevious() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock getParent() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction getLastInstOfParent() const; -+ BRIDGED_INLINE bool isDeleted() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedOperandArray getOperands() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedOperandArray getTypeDependentOperands() const; -+ BRIDGED_INLINE void setOperand(SwiftInt index, BridgedValue value) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedLocation getLocation() const; -+ BRIDGED_INLINE BridgedMemoryBehavior getMemBehavior() const; -+ BRIDGED_INLINE bool mayRelease() const; -+ BRIDGED_INLINE bool mayHaveSideEffects() const; -+ BRIDGED_INLINE bool maySuspend() const; - bool mayAccessPointer() const; - bool mayLoadWeakOrUnowned() const; - bool maySynchronizeNotConsideringSideEffects() const; - bool mayBeDeinitBarrierNotConsideringSideEffects() const; - -- SwiftInt MultipleValueInstruction_getNumResults() const { -- return getAs()->getNumResults(); -- } -+ BRIDGED_INLINE SwiftInt MultipleValueInstruction_getNumResults() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedMultiValueResult MultipleValueInstruction_getResult(SwiftInt index) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSuccessorArray TermInst_getSuccessors() const; - -- SWIFT_IMPORT_UNSAFE -- BridgedMultiValueResult MultipleValueInstruction_getResult(SwiftInt index) const { -- return {getAs()->getResult(index)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- inline BridgedSuccessorArray TermInst_getSuccessors() const; -- -- SWIFT_IMPORT_UNSAFE -- llvm::StringRef CondFailInst_getMessage() const { -- return getAs()->getMessage(); -- } -- -- SwiftInt LoadInst_getLoadOwnership() const { -- return (SwiftInt)getAs()->getOwnershipQualifier(); -- } -- -- swift::BuiltinValueKind BuiltinInst_getID() const { -- return getAs()->getBuiltinInfo().ID; -- } -+ enum class BuiltinValueKind { -+ None = 0, -+#define BUILTIN(Id, Name, Attrs) Id, -+#include "swift/AST/Builtins.def" -+ }; - - enum class IntrinsicID { - memcpy, memmove, - unknown - }; - -- IntrinsicID BuiltinInst_getIntrinsicID() const { -- switch (getAs()->getIntrinsicInfo().ID) { -- case llvm::Intrinsic::memcpy: return IntrinsicID::memcpy; -- case llvm::Intrinsic::memmove: return IntrinsicID::memmove; -- default: return IntrinsicID::unknown; -- } -- } -- -- SWIFT_IMPORT_UNSAFE -- swift::SubstitutionMap BuiltinInst_getSubstitutionMap() const { -- return getAs()->getSubstitutions(); -- } -- -- bool PointerToAddressInst_isStrict() const { -- return getAs()->isStrict(); -- } -- -- bool AddressToPointerInst_needsStackProtection() const { -- return getAs()->needsStackProtection(); -- } -- -- bool IndexAddrInst_needsStackProtection() const { -- return getAs()->needsStackProtection(); -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedGlobalVar GlobalAccessInst_getGlobal() const { -- return {getAs()->getReferencedGlobal()}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedGlobalVar AllocGlobalInst_getGlobal() const { -- return {getAs()->getReferencedGlobal()}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedFunction FunctionRefBaseInst_getReferencedFunction() const { -- return {getAs()->getInitiallyReferencedFunction()}; -- } -- -- SWIFT_IMPORT_UNSAFE -- llvm::APInt IntegerLiteralInst_getValue() const { -- return getAs()->getValue(); -- } -- -- SWIFT_IMPORT_UNSAFE -- llvm::APFloat FloatLiteralInst_getValue() const { -- return getAs()->getValue(); -- } -- -- SWIFT_IMPORT_UNSAFE -- llvm::StringRef StringLiteralInst_getValue() const { -- return getAs()->getValue(); -- } -- -- int StringLiteralInst_getEncoding() const { -- return (int)getAs()->getEncoding(); -- } -- -- SwiftInt TupleExtractInst_fieldIndex() const { -- return getAs()->getFieldIndex(); -- } -- -- SwiftInt TupleElementAddrInst_fieldIndex() const { -- return getAs()->getFieldIndex(); -- } -- -- SwiftInt StructExtractInst_fieldIndex() const { -- return getAs()->getFieldIndex(); -- } -- -- OptionalBridgedValue StructInst_getUniqueNonTrivialFieldValue() const { -- return {getAs()->getUniqueNonTrivialFieldValue()}; -- } -- -- SwiftInt StructElementAddrInst_fieldIndex() const { -- return getAs()->getFieldIndex(); -- } -- -- SwiftInt ProjectBoxInst_fieldIndex() const { -- return getAs()->getFieldIndex(); -- } -- -- bool EndCOWMutationInst_doKeepUnique() const { -- return getAs()->doKeepUnique(); -- } -- -- SwiftInt EnumInst_caseIndex() const { -- return getAs()->getCaseIndex(); -- } -- -- SwiftInt UncheckedEnumDataInst_caseIndex() const { -- return getAs()->getCaseIndex(); -- } -- -- SwiftInt InitEnumDataAddrInst_caseIndex() const { -- return getAs()->getCaseIndex(); -- } -- -- SwiftInt UncheckedTakeEnumDataAddrInst_caseIndex() const { -- return getAs()->getCaseIndex(); -- } -- -- SwiftInt InjectEnumAddrInst_caseIndex() const { -- return getAs()->getCaseIndex(); -- } -- -- SwiftInt RefElementAddrInst_fieldIndex() const { -- return getAs()->getFieldIndex(); -- } -- -- bool RefElementAddrInst_fieldIsLet() const { -- return getAs()->getField()->isLet(); -- } -- -- SwiftInt PartialApplyInst_numArguments() const { -- return getAs()->getNumArguments(); -- } -- -- SwiftInt ApplyInst_numArguments() const { -- return getAs()->getNumArguments(); -- } -- -- bool ApplyInst_getNonThrowing() const { -- return getAs()->isNonThrowing(); -- } -- -- bool ApplyInst_getNonAsync() const { -- return getAs()->isNonAsync(); -- } -- -- const swift::GenericSpecializationInformation * _Nullable -- -- SWIFT_IMPORT_UNSAFE -- ApplyInst_getSpecializationInfo() const { -- return getAs()->getSpecializationInfo(); -- } -- -- SwiftInt ObjectInst_getNumBaseElements() const { -- return getAs()->getNumBaseElements(); -- } -- -- SwiftInt PartialApply_getCalleeArgIndexOfFirstAppliedArg() const { -- return swift::ApplySite(getInst()).getCalleeArgIndexOfFirstAppliedArg(); -- } -- -- bool PartialApplyInst_isOnStack() const { -- return getAs()->isOnStack(); -- } -- -- bool AllocStackInst_hasDynamicLifetime() const { -- return getAs()->hasDynamicLifetime(); -- } -- -- bool AllocRefInstBase_isObjc() const { -- return getAs()->isObjC(); -- } -- -- bool AllocRefInstBase_canAllocOnStack() const { -- return getAs()->canAllocOnStack(); -- } -- -- SwiftInt AllocRefInstBase_getNumTailTypes() const { -- return getAs()->getNumTailTypes(); -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedSILTypeArray AllocRefInstBase_getTailAllocatedTypes() const { -- return {getAs()->getTailAllocatedTypes()}; -- } -- -- bool AllocRefDynamicInst_isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType() const { -- return getAs()->isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType(); -- } -- -- SwiftInt BeginApplyInst_numArguments() const { -- return getAs()->getNumArguments(); -- } -- -- SwiftInt TryApplyInst_numArguments() const { -- return getAs()->getNumArguments(); -- } -- -- SWIFT_IMPORT_UNSAFE -- inline BridgedBasicBlock BranchInst_getTargetBlock() const; -- -- SwiftInt SwitchEnumInst_getNumCases() const { -- return getAs()->getNumCases(); -- } -- -- SwiftInt SwitchEnumInst_getCaseIndex(SwiftInt idx) const { -- auto *seInst = getAs(); -- return seInst->getModule().getCaseIndex(seInst->getCase(idx).first); -- } -- -- SwiftInt StoreInst_getStoreOwnership() const { -- return (SwiftInt)getAs()->getOwnershipQualifier(); -- } -- -- swift::SILAccessKind BeginAccessInst_getAccessKind() const { -- return getAs()->getAccessKind(); -- } -- -- bool BeginAccessInst_isStatic() const { -- return getAs()->getEnforcement() == swift::SILAccessEnforcement::Static; -- } -- -- bool CopyAddrInst_isTakeOfSrc() const { -- return getAs()->isTakeOfSrc(); -- } -- -- bool CopyAddrInst_isInitializationOfDest() const { -- return getAs()->isInitializationOfDest(); -- } -- -- void RefCountingInst_setIsAtomic(bool isAtomic) const { -- getAs()->setAtomicity( -- isAtomic ? swift::RefCountingInst::Atomicity::Atomic -- : swift::RefCountingInst::Atomicity::NonAtomic); -- } -- -- bool RefCountingInst_getIsAtomic() const { -- return getAs()->getAtomicity() == swift::RefCountingInst::Atomicity::Atomic; -- } -- -- SwiftInt CondBranchInst_getNumTrueArgs() const { -- return getAs()->getNumTrueArgs(); -- } -- -- void AllocRefInstBase_setIsStackAllocatable() const { -- getAs()->setStackAllocatable(); -- } -- -- bool AllocRefInst_isBare() const { -- return getAs()->isBare(); -- } -- -- void AllocRefInst_setIsBare() const { -- getAs()->setBare(true); -- } -- -- inline void TermInst_replaceBranchTarget(BridgedBasicBlock from, BridgedBasicBlock to) const; -+ struct OptionalInt { -+ SwiftInt value; -+ bool hasValue; -+ }; - -- SwiftInt KeyPathInst_getNumComponents() const { -- if (swift::KeyPathPattern *pattern = getAs()->getPattern()) { -- return (SwiftInt)pattern->getComponents().size(); -- } -- return 0; -- } -+ enum class AccessKind { -+ Init, -+ Read, -+ Modify, -+ Deinit -+ }; - - struct KeyPathFunctionResults { - enum { maxFunctions = 5 }; -@@ -796,71 +493,99 @@ struct BridgedInstruction { - SwiftInt numFunctions; - }; - -- void KeyPathInst_getReferencedFunctions(SwiftInt componentIdx, KeyPathFunctionResults * _Nonnull results) const { -- swift::KeyPathPattern *pattern = getAs()->getPattern(); -- const swift::KeyPathPatternComponent &comp = pattern->getComponents()[componentIdx]; -- results->numFunctions = 0; -- -- comp.visitReferencedFunctionsAndMethods([results](swift::SILFunction *func) { -- assert(results->numFunctions < KeyPathFunctionResults::maxFunctions); -- results->functions[results->numFunctions++] = {func}; -- }, [](swift::SILDeclRef) {}); -- } -- -- bool GlobalValueInst_isBare() const { -- return getAs()->isBare(); -- } -- -- void GlobalValueInst_setIsBare() const { -- getAs()->setBare(true); -- } -- -- void LoadInst_setOwnership(SwiftInt ownership) const { -- getAs()->setOwnershipQualifier((swift::LoadOwnershipQualifier)ownership); -- } -- -- SWIFT_IMPORT_UNSAFE -- inline BridgedBasicBlock CheckedCastBranch_getSuccessBlock() const; -- -- SWIFT_IMPORT_UNSAFE -- inline BridgedBasicBlock CheckedCastBranch_getFailureBlock() const; -- -- SWIFT_IMPORT_UNSAFE -- swift::SubstitutionMap ApplySite_getSubstitutionMap() const { -- auto as = swift::ApplySite(getInst()); -- return as.getSubstitutionMap(); -- } -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef CondFailInst_getMessage() const; -+ BRIDGED_INLINE SwiftInt LoadInst_getLoadOwnership() const ; -+ BRIDGED_INLINE BuiltinValueKind BuiltinInst_getID() const; -+ BRIDGED_INLINE IntrinsicID BuiltinInst_getIntrinsicID() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSubstitutionMap BuiltinInst_getSubstitutionMap() const; -+ BRIDGED_INLINE bool PointerToAddressInst_isStrict() const; -+ BRIDGED_INLINE bool AddressToPointerInst_needsStackProtection() const; -+ BRIDGED_INLINE bool IndexAddrInst_needsStackProtection() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedGlobalVar GlobalAccessInst_getGlobal() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedGlobalVar AllocGlobalInst_getGlobal() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction FunctionRefBaseInst_getReferencedFunction() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalInt IntegerLiteralInst_getValue() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef StringLiteralInst_getValue() const; -+ BRIDGED_INLINE int StringLiteralInst_getEncoding() const; -+ BRIDGED_INLINE SwiftInt TupleExtractInst_fieldIndex() const; -+ BRIDGED_INLINE SwiftInt TupleElementAddrInst_fieldIndex() const; -+ BRIDGED_INLINE SwiftInt StructExtractInst_fieldIndex() const; -+ BRIDGED_INLINE OptionalBridgedValue StructInst_getUniqueNonTrivialFieldValue() const; -+ BRIDGED_INLINE SwiftInt StructElementAddrInst_fieldIndex() const; -+ BRIDGED_INLINE SwiftInt ProjectBoxInst_fieldIndex() const; -+ BRIDGED_INLINE bool EndCOWMutationInst_doKeepUnique() const; -+ BRIDGED_INLINE SwiftInt EnumInst_caseIndex() const; -+ BRIDGED_INLINE SwiftInt UncheckedEnumDataInst_caseIndex() const; -+ BRIDGED_INLINE SwiftInt InitEnumDataAddrInst_caseIndex() const; -+ BRIDGED_INLINE SwiftInt UncheckedTakeEnumDataAddrInst_caseIndex() const; -+ BRIDGED_INLINE SwiftInt InjectEnumAddrInst_caseIndex() const; -+ BRIDGED_INLINE SwiftInt RefElementAddrInst_fieldIndex() const; -+ BRIDGED_INLINE bool RefElementAddrInst_fieldIsLet() const; -+ BRIDGED_INLINE SwiftInt PartialApplyInst_numArguments() const; -+ BRIDGED_INLINE SwiftInt ApplyInst_numArguments() const; -+ BRIDGED_INLINE bool ApplyInst_getNonThrowing() const; -+ BRIDGED_INLINE bool ApplyInst_getNonAsync() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedGenericSpecializationInformation ApplyInst_getSpecializationInfo() const; -+ BRIDGED_INLINE SwiftInt ObjectInst_getNumBaseElements() const; -+ BRIDGED_INLINE SwiftInt PartialApply_getCalleeArgIndexOfFirstAppliedArg() const; -+ BRIDGED_INLINE bool PartialApplyInst_isOnStack() const; -+ BRIDGED_INLINE bool AllocStackInst_hasDynamicLifetime() const; -+ BRIDGED_INLINE bool AllocRefInstBase_isObjc() const; -+ BRIDGED_INLINE bool AllocRefInstBase_canAllocOnStack() const; -+ BRIDGED_INLINE SwiftInt AllocRefInstBase_getNumTailTypes() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSILTypeArray AllocRefInstBase_getTailAllocatedTypes() const; -+ BRIDGED_INLINE bool AllocRefDynamicInst_isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType() const; -+ BRIDGED_INLINE SwiftInt BeginApplyInst_numArguments() const; -+ BRIDGED_INLINE SwiftInt TryApplyInst_numArguments() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock BranchInst_getTargetBlock() const; -+ BRIDGED_INLINE SwiftInt SwitchEnumInst_getNumCases() const; -+ BRIDGED_INLINE SwiftInt SwitchEnumInst_getCaseIndex(SwiftInt idx) const; -+ BRIDGED_INLINE SwiftInt StoreInst_getStoreOwnership() const; -+ BRIDGED_INLINE AccessKind BeginAccessInst_getAccessKind() const; -+ BRIDGED_INLINE bool BeginAccessInst_isStatic() const; -+ BRIDGED_INLINE bool CopyAddrInst_isTakeOfSrc() const; -+ BRIDGED_INLINE bool CopyAddrInst_isInitializationOfDest() const; -+ BRIDGED_INLINE void RefCountingInst_setIsAtomic(bool isAtomic) const; -+ BRIDGED_INLINE bool RefCountingInst_getIsAtomic() const; -+ BRIDGED_INLINE SwiftInt CondBranchInst_getNumTrueArgs() const; -+ BRIDGED_INLINE void AllocRefInstBase_setIsStackAllocatable() const; -+ BRIDGED_INLINE bool AllocRefInst_isBare() const; -+ BRIDGED_INLINE void AllocRefInst_setIsBare() const; -+ BRIDGED_INLINE void TermInst_replaceBranchTarget(BridgedBasicBlock from, BridgedBasicBlock to) const; -+ BRIDGED_INLINE SwiftInt KeyPathInst_getNumComponents() const; -+ BRIDGED_INLINE void KeyPathInst_getReferencedFunctions(SwiftInt componentIdx, KeyPathFunctionResults * _Nonnull results) const; -+ BRIDGED_INLINE bool GlobalValueInst_isBare() const; -+ BRIDGED_INLINE void GlobalValueInst_setIsBare() const; -+ BRIDGED_INLINE void LoadInst_setOwnership(SwiftInt ownership) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock CheckedCastBranch_getSuccessBlock() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock CheckedCastBranch_getFailureBlock() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSubstitutionMap ApplySite_getSubstitutionMap() const; -+ BRIDGED_INLINE BridgedArgumentConvention ApplySite_getArgumentConvention(SwiftInt calleeArgIdx) const; -+ BRIDGED_INLINE SwiftInt ApplySite_getNumArguments() const; -+ BRIDGED_INLINE SwiftInt FullApplySite_numIndirectResultArguments() const; -+}; - -- BridgedArgumentConvention ApplySite_getArgumentConvention(SwiftInt calleeArgIdx) const { -- auto as = swift::ApplySite(getInst()); -- auto conv = as.getSubstCalleeConv().getSILArgumentConvention(calleeArgIdx); -- return castToArgumentConvention(conv.Value); -- } -+struct OptionalBridgedInstruction { -+ OptionalSwiftObject obj; - -- SwiftInt ApplySite_getNumArguments() const { -- return swift::ApplySite(getInst()).getNumArguments(); -+#ifdef USED_IN_CPP_SOURCE -+ swift::SILInstruction * _Nullable get() const { -+ if (!obj) -+ return nullptr; -+ return llvm::cast(static_cast(obj)->castToInstruction()); - } -+#endif - -- SwiftInt FullApplySite_numIndirectResultArguments() const { -- auto fas = swift::FullApplySite(getInst()); -- return fas.getNumIndirectSILResults(); -- } -+ OptionalBridgedInstruction() : obj(nullptr) {} -+ OptionalBridgedInstruction(OptionalSwiftObject obj) : obj(obj) {} - }; - - struct BridgedArgument { - SwiftObject obj; - -- swift::SILArgument * _Nonnull getArgument() const { -- return static_cast(obj); -- } -- -- SWIFT_IMPORT_UNSAFE -- inline BridgedBasicBlock getParent() const; -- -- BridgedArgumentConvention getConvention() const { -- auto *fArg = llvm::cast(getArgument()); -- return castToArgumentConvention(fArg->getArgumentConvention()); -- } -+ BRIDGED_INLINE swift::SILArgument * _Nonnull getArgument() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock getParent() const; -+ BRIDGED_INLINE BridgedArgumentConvention getConvention() const; - }; - - struct OptionalBridgedArgument { -@@ -870,112 +595,56 @@ struct OptionalBridgedArgument { - struct OptionalBridgedBasicBlock { - OptionalSwiftObject obj; - -- swift::SILBasicBlock * _Nullable getBlock() const { -+#ifdef USED_IN_CPP_SOURCE -+ swift::SILBasicBlock * _Nullable get() const { - return obj ? static_cast(obj) : nullptr; - } -+#endif - }; - - struct BridgedBasicBlock { - SwiftObject obj; - -- BridgedBasicBlock(SwiftObject obj) : obj(obj) {} -- -- swift::SILBasicBlock * _Nonnull getBlock() const { -- return static_cast(obj); -- } -- -- std::string getDebugDescription() const; -- -- SWIFT_IMPORT_UNSAFE -- OptionalBridgedBasicBlock getNext() const { -- auto iter = std::next(getBlock()->getIterator()); -- if (iter == getBlock()->getParent()->end()) -- return {nullptr}; -- return {&*iter}; -- } -- -- SWIFT_IMPORT_UNSAFE -- OptionalBridgedBasicBlock getPrevious() const { -- auto iter = std::next(getBlock()->getReverseIterator()); -- if (iter == getBlock()->getParent()->rend()) -- return {nullptr}; -- return {&*iter}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedFunction getFunction() const { -- return {getBlock()->getParent()}; -+ BridgedBasicBlock(SwiftObject obj) : obj(obj) { - } - -- SWIFT_IMPORT_UNSAFE -- OptionalBridgedInstruction getFirstInst() const { -- if (getBlock()->empty()) -- return {nullptr}; -- return {getBlock()->front().asSILNode()}; -+#ifdef USED_IN_CPP_SOURCE -+ BridgedBasicBlock(swift::SILBasicBlock * _Nonnull block) : obj(block) { - } -- -- SWIFT_IMPORT_UNSAFE -- OptionalBridgedInstruction getLastInst() const { -- if (getBlock()->empty()) -- return {nullptr}; -- return {getBlock()->back().asSILNode()}; -- } -- -- SwiftInt getNumArguments() const { -- return getBlock()->getNumArguments(); -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedArgument getArgument(SwiftInt index) const { -- return {getBlock()->getArgument(index)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedArgument addBlockArgument(swift::SILType type, BridgedValue::Ownership ownership) const { -- return {getBlock()->createPhiArgument(type, castToOwnership(ownership))}; -- } -- -- void eraseArgument(SwiftInt index) const { -- getBlock()->eraseArgument(index); -- } -- -- void moveAllInstructionsToBegin(BridgedBasicBlock dest) const { -- dest.getBlock()->spliceAtBegin(getBlock()); -- } -- -- void moveAllInstructionsToEnd(BridgedBasicBlock dest) const { -- dest.getBlock()->spliceAtEnd(getBlock()); -- } -- -- void moveArgumentsTo(BridgedBasicBlock dest) const { -- dest.getBlock()->moveArgumentList(getBlock()); -+ swift::SILBasicBlock * _Nonnull get() const { -+ return static_cast(obj); - } -+#endif - -- SWIFT_IMPORT_UNSAFE -- inline OptionalBridgedSuccessor getFirstPred() const; -+ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedBasicBlock getNext() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedBasicBlock getPrevious() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getFunction() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedInstruction getFirstInst() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedInstruction getLastInst() const; -+ BRIDGED_INLINE SwiftInt getNumArguments() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedArgument getArgument(SwiftInt index) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedArgument addBlockArgument(BridgedType type, BridgedValue::Ownership ownership) const; -+ BRIDGED_INLINE void eraseArgument(SwiftInt index) const; -+ BRIDGED_INLINE void moveAllInstructionsToBegin(BridgedBasicBlock dest) const; -+ BRIDGED_INLINE void moveAllInstructionsToEnd(BridgedBasicBlock dest) const; -+ BRIDGED_INLINE void moveArgumentsTo(BridgedBasicBlock dest) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedSuccessor getFirstPred() const; - }; - - struct BridgedSuccessor { - const swift::SILSuccessor * _Nonnull succ; - -- SWIFT_IMPORT_UNSAFE -- inline OptionalBridgedSuccessor getNext() const; -- -- SWIFT_IMPORT_UNSAFE -- BridgedBasicBlock getTargetBlock() const { -- return {succ->getBB()}; -- } -- -- SWIFT_IMPORT_UNSAFE -- inline BridgedInstruction getContainingInst() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedSuccessor getNext() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock getTargetBlock() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction getContainingInst() const; - }; - - struct OptionalBridgedSuccessor { - const swift::SILSuccessor * _Nullable succ; - - // Assumes that `succ` is not null. -- SWIFT_IMPORT_UNSAFE -- BridgedSuccessor advancedBy(SwiftInt index) const { return {succ + index}; } -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSuccessor advancedBy(SwiftInt index) const; - }; - - struct BridgedSuccessorArray { -@@ -986,12 +655,9 @@ struct BridgedSuccessorArray { - struct BridgedVTableEntry { - const swift::SILVTableEntry * _Nonnull entry; - -- std::string getDebugDescription() const; -- -- SWIFT_IMPORT_UNSAFE -- BridgedFunction getImplementation() const { -- return {entry->getImplementation()}; -- } -+ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getImplementation() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedVTableEntry advanceBy(SwiftInt index) const; - }; - - struct BridgedVTableEntryArray { -@@ -1002,29 +668,31 @@ struct BridgedVTableEntryArray { - struct BridgedVTable { - const swift::SILVTable * _Nonnull vTable; - -- std::string getDebugDescription() const; -- -- SWIFT_IMPORT_UNSAFE -- BridgedVTableEntryArray getEntries() const { -- auto entries = vTable->getEntries(); -- return {{entries.data()}, (SwiftInt)entries.size()}; -- } -+ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedVTableEntryArray getEntries() const; - }; - - struct BridgedWitnessTableEntry { -- const swift::SILWitnessTable::Entry * _Nonnull entry; -+ const void * _Nonnull entry; - -- SWIFT_IMPORT_UNSAFE -- std::string getDebugDescription() const; -+ enum class Kind { -+ Invalid, -+ Method, -+ AssociatedType, -+ AssociatedTypeProtocol, -+ BaseProtocol -+ }; - -- swift::SILWitnessTable::WitnessKind getKind() const { -- return entry->getKind(); -+#ifdef USED_IN_CPP_SOURCE -+ const swift::SILWitnessTable::Entry * _Nonnull getEntry() const { -+ return (const swift::SILWitnessTable::Entry * _Nonnull)entry; - } -+#endif - -- SWIFT_IMPORT_UNSAFE -- OptionalBridgedFunction getMethodFunction() const { -- return {entry->getMethodWitness().Witness}; -- } -+ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; -+ BRIDGED_INLINE Kind getKind() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedFunction getMethodFunction() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedWitnessTableEntry advanceBy(SwiftInt index) const; - }; - - struct BridgedWitnessTableEntryArray { -@@ -1035,13 +703,8 @@ struct BridgedWitnessTableEntryArray { - struct BridgedWitnessTable { - const swift::SILWitnessTable * _Nonnull table; - -- std::string getDebugDescription() const; -- -- SWIFT_IMPORT_UNSAFE -- BridgedWitnessTableEntryArray getEntries() const { -- auto entries = table->getEntries(); -- return {{entries.data()}, (SwiftInt)entries.size()}; -- } -+ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedWitnessTableEntryArray getEntries() const; - }; - - struct OptionalBridgedWitnessTable { -@@ -1051,13 +714,8 @@ struct OptionalBridgedWitnessTable { - struct BridgedDefaultWitnessTable { - const swift::SILDefaultWitnessTable * _Nonnull table; - -- std::string getDebugDescription() const; -- -- SWIFT_IMPORT_UNSAFE -- BridgedWitnessTableEntryArray getEntries() const { -- auto entries = table->getEntries(); -- return {{entries.data()}, (SwiftInt)entries.size()}; -- } -+ SWIFT_IMPORT_UNSAFE BridgedOwnedString getDebugDescription() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedWitnessTableEntryArray getEntries() const; - }; - - struct OptionalBridgedDefaultWitnessTable { -@@ -1071,292 +729,99 @@ struct BridgedBuilder{ - } insertAt; - - SwiftObject insertionObj; -- swift::SILDebugLocation loc; -+ BridgedLocation loc; - -- swift::SILBuilder builder() const { -+#ifdef USED_IN_CPP_SOURCE -+ swift::SILBuilder get() const { - switch (insertAt) { -- case InsertAt::beforeInst: -- return swift::SILBuilder(BridgedInstruction(insertionObj).getInst(), loc.getScope()); -- case InsertAt::endOfBlock: -- return swift::SILBuilder(BridgedBasicBlock(insertionObj).getBlock(), loc.getScope()); -- case InsertAt::intoGlobal: -+ case BridgedBuilder::InsertAt::beforeInst: -+ return swift::SILBuilder(BridgedInstruction(insertionObj).get(), loc.getLoc().getScope()); -+ case BridgedBuilder::InsertAt::endOfBlock: -+ return swift::SILBuilder(BridgedBasicBlock(insertionObj).get(), loc.getLoc().getScope()); -+ case BridgedBuilder::InsertAt::intoGlobal: - return swift::SILBuilder(BridgedGlobalVar(insertionObj).getGlobal()); - } - } -- -- swift::SILLocation regularLoc() const { return swift::RegularLocation(loc.getLocation()); } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createBuiltinBinaryFunction(llvm::StringRef name, -- swift::SILType operandType, swift::SILType resultType, -- BridgedValueArray arguments) const { -- llvm::SmallVector argValues; -- return {builder().createBuiltinBinaryFunction(regularLoc(), -- name, operandType, resultType, -- arguments.getValues(argValues))}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createCondFail(BridgedValue condition, llvm::StringRef message) const { -- return {builder().createCondFail(regularLoc(), condition.getSILValue(), message)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createIntegerLiteral(swift::SILType type, SwiftInt value) const { -- return {builder().createIntegerLiteral(regularLoc(), type, value)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createAllocStack(swift::SILType type, -- bool hasDynamicLifetime, bool isLexical, bool wasMoved) const { -- return {builder().createAllocStack(regularLoc(), type, llvm::None, hasDynamicLifetime, isLexical, wasMoved)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createDeallocStack(BridgedValue operand) const { -- return {builder().createDeallocStack(regularLoc(), operand.getSILValue())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createDeallocStackRef(BridgedValue operand) const { -- return {builder().createDeallocStackRef(regularLoc(), operand.getSILValue())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createUncheckedRefCast(BridgedValue op, swift::SILType type) const { -- return {builder().createUncheckedRefCast(regularLoc(), op.getSILValue(), type)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createUpcast(BridgedValue op, swift::SILType type) const { -- return {builder().createUpcast(regularLoc(), op.getSILValue(), type)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createLoad(BridgedValue op, SwiftInt ownership) const { -- return {builder().createLoad(regularLoc(), op.getSILValue(), (swift::LoadOwnershipQualifier)ownership)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createSetDeallocating(BridgedValue op, bool isAtomic) const { -- return {builder().createSetDeallocating(regularLoc(), -- op.getSILValue(), -- isAtomic ? swift::RefCountingInst::Atomicity::Atomic -- : swift::RefCountingInst::Atomicity::NonAtomic)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createStrongRetain(BridgedValue op) const { -- auto b = builder(); -- return {b.createStrongRetain(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createStrongRelease(BridgedValue op) const { -- auto b = builder(); -- return {b.createStrongRelease(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createUnownedRetain(BridgedValue op) const { -- auto b = builder(); -- return {b.createUnownedRetain(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createUnownedRelease(BridgedValue op) const { -- auto b = builder(); -- return {b.createUnownedRelease(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createFunctionRef(BridgedFunction function) const { -- return {builder().createFunctionRef(regularLoc(), function.getFunction())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createCopyValue(BridgedValue op) const { -- return {builder().createCopyValue(regularLoc(), op.getSILValue())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createBeginBorrow(BridgedValue op) const { -- return {builder().createBeginBorrow(regularLoc(), op.getSILValue())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createEndBorrow(BridgedValue op) const { -- return {builder().createEndBorrow(regularLoc(), op.getSILValue())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createCopyAddr(BridgedValue from, BridgedValue to, -- bool takeSource, bool initializeDest) const { -- return {builder().createCopyAddr(regularLoc(), -- from.getSILValue(), to.getSILValue(), -- swift::IsTake_t(takeSource), -- swift::IsInitialization_t(initializeDest))}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createDestroyValue(BridgedValue op) const { -- return {builder().createDestroyValue(regularLoc(), op.getSILValue())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createDestroyAddr(BridgedValue op) const { -- return {builder().createDestroyAddr(regularLoc(), op.getSILValue())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createDebugStep() const { -- return {builder().createDebugStep(regularLoc())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createApply(BridgedValue function, swift::SubstitutionMap subMap, -- BridgedValueArray arguments, bool isNonThrowing, bool isNonAsync, -- const swift::GenericSpecializationInformation * _Nullable specInfo) const { -- llvm::SmallVector argValues; -- swift::ApplyOptions applyOpts; -- if (isNonThrowing) { applyOpts |= swift::ApplyFlags::DoesNotThrow; } -- if (isNonAsync) { applyOpts |= swift::ApplyFlags::DoesNotAwait; } -- -- return {builder().createApply(regularLoc(), -- function.getSILValue(), subMap, -- arguments.getValues(argValues), -- applyOpts, specInfo)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createSwitchEnumInst(BridgedValue enumVal, OptionalBridgedBasicBlock defaultBlock, -- const void * _Nullable enumCases, SwiftInt numEnumCases) const { -- using BridgedCase = const std::pair; -- llvm::ArrayRef cases(static_cast(enumCases), -- (unsigned)numEnumCases); -- llvm::SmallDenseMap mappedElements; -- swift::SILValue en = enumVal.getSILValue(); -- swift::EnumDecl *enumDecl = en->getType().getEnumOrBoundGenericEnum(); -- for (auto elemWithIndex : llvm::enumerate(enumDecl->getAllElements())) { -- mappedElements[elemWithIndex.index()] = elemWithIndex.value(); -- } -- llvm::SmallVector, 16> convertedCases; -- for (auto c : cases) { -- assert(mappedElements.count(c.first) && "wrong enum element index"); -- convertedCases.push_back({mappedElements[c.first], c.second.getBlock()}); -- } -- return {builder().createSwitchEnum(regularLoc(), -- enumVal.getSILValue(), -- defaultBlock.getBlock(), convertedCases)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createUncheckedEnumData(BridgedValue enumVal, SwiftInt caseIdx, -- swift::SILType resultType) const { -- swift::SILValue en = enumVal.getSILValue(); -- return {builder().createUncheckedEnumData(regularLoc(), enumVal.getSILValue(), -- en->getType().getEnumElement(caseIdx), resultType)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createEnum(SwiftInt caseIdx, OptionalBridgedValue payload, -- swift::SILType resultType) const { -- swift::EnumElementDecl *caseDecl = resultType.getEnumElement(caseIdx); -- swift::SILValue pl = payload.getSILValue(); -- return {builder().createEnum(regularLoc(), pl, caseDecl, resultType)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createBranch(BridgedBasicBlock destBlock, BridgedValueArray arguments) const { -- llvm::SmallVector argValues; -- return {builder().createBranch(regularLoc(), destBlock.getBlock(), arguments.getValues(argValues))}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createUnreachable() const { -- return {builder().createUnreachable(regularLoc())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createObject(swift::SILType type, BridgedValueArray arguments, SwiftInt numBaseElements) const { -- llvm::SmallVector argValues; -- return {builder().createObject(swift::ArtificialUnreachableLocation(), -- type, arguments.getValues(argValues), numBaseElements)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createGlobalAddr(BridgedGlobalVar global) const { -- return {builder().createGlobalAddr(regularLoc(), global.getGlobal())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createGlobalValue(BridgedGlobalVar global, bool isBare) const { -- return {builder().createGlobalValue(regularLoc(), global.getGlobal(), isBare)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createStruct(swift::SILType type, BridgedValueArray elements) const { -- llvm::SmallVector elementValues; -- return {builder().createStruct(regularLoc(), type, elements.getValues(elementValues))}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createStructExtract(BridgedValue str, SwiftInt fieldIndex) const { -- swift::SILValue v = str.getSILValue(); -- return {builder().createStructExtract(regularLoc(), v, v->getType().getFieldDecl(fieldIndex))}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createStructElementAddr(BridgedValue addr, SwiftInt fieldIndex) const { -- swift::SILValue v = addr.getSILValue(); -- return {builder().createStructElementAddr(regularLoc(), v, v->getType().getFieldDecl(fieldIndex))}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createDestructureStruct(BridgedValue str) const { -- return {builder().createDestructureStruct(regularLoc(), str.getSILValue())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createTuple(swift::SILType type, BridgedValueArray elements) const { -- llvm::SmallVector elementValues; -- return {builder().createTuple(regularLoc(), type, elements.getValues(elementValues))}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createTupleExtract(BridgedValue str, SwiftInt elementIndex) const { -- swift::SILValue v = str.getSILValue(); -- return {builder().createTupleExtract(regularLoc(), v, elementIndex)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createTupleElementAddr(BridgedValue addr, SwiftInt elementIndex) const { -- swift::SILValue v = addr.getSILValue(); -- return {builder().createTupleElementAddr(regularLoc(), v, elementIndex)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createDestructureTuple(BridgedValue str) const { -- return {builder().createDestructureTuple(regularLoc(), str.getSILValue())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createStore(BridgedValue src, BridgedValue dst, -- SwiftInt ownership) const { -- return {builder().createStore(regularLoc(), src.getSILValue(), dst.getSILValue(), -- (swift::StoreOwnershipQualifier)ownership)}; -+ swift::SILLocation regularLoc() const { -+ return swift::RegularLocation(loc.getLoc().getLocation()); - } -+#endif - -- SWIFT_IMPORT_UNSAFE -- BridgedInstruction createInitExistentialRef(BridgedValue instance, -- swift::SILType type, -- BridgedInstruction useConformancesOf) const { -- auto *src = useConformancesOf.getAs(); -- return {builder().createInitExistentialRef(regularLoc(), type, -- src->getFormalConcreteType(), -- instance.getSILValue(), -- src->getConformances())}; -- } -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createBuiltinBinaryFunction(BridgedStringRef name, -+ BridgedType operandType, BridgedType resultType, -+ BridgedValueArray arguments) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createCondFail(BridgedValue condition, -+ BridgedStringRef message) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createIntegerLiteral(BridgedType type, SwiftInt value) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createAllocStack(BridgedType type, -+ bool hasDynamicLifetime, bool isLexical, bool wasMoved) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDeallocStack(BridgedValue operand) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDeallocStackRef(BridgedValue operand) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUncheckedRefCast(BridgedValue op, -+ BridgedType type) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUpcast(BridgedValue op, BridgedType type) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createLoad(BridgedValue op, SwiftInt ownership) const; -+ /*SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createBeginDeallocRef(BridgedValue reference, -+ BridgedValue allocation) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createEndInitLetRef(BridgedValue op) const;*/ -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStrongRetain(BridgedValue op) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStrongRelease(BridgedValue op) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUnownedRetain(BridgedValue op) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUnownedRelease(BridgedValue op) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createFunctionRef(BridgedFunction function) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createCopyValue(BridgedValue op) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createBeginBorrow(BridgedValue op) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createEndBorrow(BridgedValue op) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createCopyAddr(BridgedValue from, BridgedValue to, -+ bool takeSource, bool initializeDest) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDestroyValue(BridgedValue op) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDestroyAddr(BridgedValue op) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDebugStep() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createApply(BridgedValue function, -+ BridgedSubstitutionMap subMap, -+ BridgedValueArray arguments, bool isNonThrowing, bool isNonAsync, -+ BridgedGenericSpecializationInformation specInfo) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createSwitchEnumInst(BridgedValue enumVal, -+ OptionalBridgedBasicBlock defaultBlock, -+ const void * _Nullable enumCases, SwiftInt numEnumCases) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUncheckedEnumData(BridgedValue enumVal, -+ SwiftInt caseIdx, BridgedType resultType) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createEnum(SwiftInt caseIdx, OptionalBridgedValue payload, -+ BridgedType resultType) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createBranch(BridgedBasicBlock destBlock, -+ BridgedValueArray arguments) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createUnreachable() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createObject(BridgedType type, BridgedValueArray arguments, -+ SwiftInt numBaseElements) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createGlobalAddr(BridgedGlobalVar global) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createGlobalValue(BridgedGlobalVar global, -+ bool isBare) const; -+ -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createSetDeallocating(BridgedValue op, bool isAtomic) const; -+ -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStruct(BridgedType type, -+ BridgedValueArray elements) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStructExtract(BridgedValue str, -+ SwiftInt fieldIndex) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStructElementAddr(BridgedValue addr, -+ SwiftInt fieldIndex) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDestructureStruct(BridgedValue str) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createTuple(BridgedType type, -+ BridgedValueArray elements) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createTupleExtract(BridgedValue str, -+ SwiftInt elementIndex) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createTupleElementAddr(BridgedValue addr, -+ SwiftInt elementIndex) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createDestructureTuple(BridgedValue str) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createStore(BridgedValue src, BridgedValue dst, -+ SwiftInt ownership) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createInitExistentialRef(BridgedValue instance, -+ BridgedType type, -+ BridgedInstruction useConformancesOf) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createMetatype(BridgedType type, -+ BridgedType::MetatypeRepresentation representation) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedInstruction createEndCOWMutation(BridgedValue instance, -+ bool keepUnique) const; - }; - - // AST bridging -@@ -1364,20 +826,11 @@ struct BridgedBuilder{ - struct BridgedNominalTypeDecl { - swift::NominalTypeDecl * _Nonnull decl; - -- SWIFT_IMPORT_UNSAFE -- llvm::StringRef getName() const { -- return decl->getName().str(); -- } -- -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedStringRef getName() const; - bool isStructWithUnreferenceableStorage() const; -+ BRIDGED_INLINE bool isGlobalActor() const; - }; - --// Passmanager and Context -- --namespace swift { -- class SwiftPassInvocation; --} -- - struct BridgedChangeNotificationHandler { - swift::SwiftPassInvocation * _Nonnull invocation; - -@@ -1391,89 +844,7 @@ struct BridgedChangeNotificationHandler { - void notifyChanges(Kind changeKind) const; - }; - --//===----------------------------------------------------------------------===// --// Inline functions --//===----------------------------------------------------------------------===// -- --OptionalBridgedOperand BridgedOperand::getNextUse() const { -- return {op->getNextUse()}; --} -- --BridgedInstruction BridgedOperand::getUser() const { -- return {op->getUser()->asSILNode()}; --} -- --OptionalBridgedOperand BridgedValue::getFirstUse() const { -- return {*getSILValue()->use_begin()}; --} -- --OptionalBridgedSuccessor BridgedSuccessor::getNext() const { -- return {succ->getNext()}; --} -- --BridgedInstruction BridgedSuccessor::getContainingInst() const { -- return {succ->getContainingInst()}; --} -- --OptionalBridgedBasicBlock BridgedFunction::getFirstBlock() const { -- return {getFunction()->empty() ? nullptr : getFunction()->getEntryBlock()}; --} -- --OptionalBridgedBasicBlock BridgedFunction::getLastBlock() const { -- return {getFunction()->empty() ? nullptr : &*getFunction()->rbegin()}; --} -- --OptionalBridgedInstruction BridgedGlobalVar::getFirstStaticInitInst() const { -- if (getGlobal()->begin() == getGlobal()->end()) { -- return {nullptr}; -- } -- swift::SILInstruction *firstInst = &*getGlobal()->begin(); -- return {firstInst->asSILNode()}; --} -- --BridgedInstruction BridgedMultiValueResult::getParent() const { -- return {getMVResult()->getParent()}; --} -- --BridgedBasicBlock BridgedInstruction::getParent() const { -- assert(!getInst()->isStaticInitializerInst() && -- "cannot get the parent of a static initializer instruction"); -- return {getInst()->getParent()}; --} -- --inline BridgedInstruction BridgedInstruction::getLastInstOfParent() const { -- return {getInst()->getParent()->back().asSILNode()}; --} -- --BridgedSuccessorArray BridgedInstruction::TermInst_getSuccessors() const { -- auto successors = getAs()->getSuccessors(); -- return {{successors.data()}, (SwiftInt)successors.size()}; --} -- --BridgedBasicBlock BridgedInstruction::BranchInst_getTargetBlock() const { -- return {getAs()->getDestBB()}; --} -- --void BridgedInstruction::TermInst_replaceBranchTarget(BridgedBasicBlock from, BridgedBasicBlock to) const { -- getAs()->replaceBranchTarget(from.getBlock(), to.getBlock()); --} -- --BridgedBasicBlock BridgedInstruction::CheckedCastBranch_getSuccessBlock() const { -- return {getAs()->getSuccessBB()}; --} -- --inline BridgedBasicBlock BridgedInstruction::CheckedCastBranch_getFailureBlock() const { -- return {getAs()->getFailureBB()}; --} -- --OptionalBridgedSuccessor BridgedBasicBlock::getFirstPred() const { -- return {getBlock()->pred_begin().getSuccessorRef()}; --} -- --BridgedBasicBlock BridgedArgument::getParent() const { -- return {getArgument()->getParent()}; --} -- -+void writeCharToStderr(int c); - - SWIFT_END_NULLABILITY_ANNOTATIONS - -diff --git a/swift/include/swift/SIL/SILBridgingImpl.h b/swift/include/swift/SIL/SILBridgingImpl.h -new file mode 100644 -index 00000000000..d195ffb9bf1 ---- /dev/null -+++ b/swift/include/swift/SIL/SILBridgingImpl.h -@@ -0,0 +1,1353 @@ -+//===--- SILBridgingImpl.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 contains the implementation of bridging functions, which are either -+// - depending on if PURE_BRIDGING_MODE is set - included in the cpp file or -+// in the header file. -+// -+//===----------------------------------------------------------------------===// -+ -+#ifndef SWIFT_SIL_SILBRIDGING_IMPL_H -+#define SWIFT_SIL_SILBRIDGING_IMPL_H -+ -+#include "swift/AST/Builtins.h" -+#include "swift/AST/Decl.h" -+#include "swift/AST/SubstitutionMap.h" -+#include "swift/Basic/BasicBridging.h" -+#include "swift/Basic/Nullability.h" -+#include "swift/SIL/ApplySite.h" -+#include "swift/SIL/InstWrappers.h" -+#include "swift/SIL/SILBuilder.h" -+#include "swift/SIL/SILDefaultWitnessTable.h" -+#include "swift/SIL/SILFunctionConventions.h" -+#include "swift/SIL/SILInstruction.h" -+#include "swift/SIL/SILLocation.h" -+#include "swift/SIL/SILModule.h" -+#include "swift/SIL/SILVTable.h" -+#include "swift/SIL/SILWitnessTable.h" -+#include -+#include -+#include -+ -+SWIFT_BEGIN_NULLABILITY_ANNOTATIONS -+ -+//===----------------------------------------------------------------------===// -+// BridgedType -+//===----------------------------------------------------------------------===// -+ -+BridgedOwnedString BridgedType::getDebugDescription() const { -+ return BridgedOwnedString(get().getDebugDescription()); -+} -+ -+bool BridgedType::isNull() const { -+ return get().isNull(); -+} -+ -+bool BridgedType::isAddress() const { -+ return get().isAddress(); -+} -+ -+BridgedType BridgedType::getAddressType() const { -+ return get().getAddressType(); -+} -+ -+BridgedType BridgedType::getObjectType() const { -+ return get().getObjectType(); -+} -+ -+bool BridgedType::isTrivial(BridgedFunction f) const { -+ return get().isTrivial(f.getFunction()); -+} -+ -+bool BridgedType::isNonTrivialOrContainsRawPointer(BridgedFunction f) const { -+ return get().isNonTrivialOrContainsRawPointer(f.getFunction()); -+} -+ -+bool BridgedType::isValueTypeWithDeinit() const { -+ return get().isValueTypeWithDeinit(); -+} -+ -+bool BridgedType::isLoadable(BridgedFunction f) const { -+ return get().isLoadable(f.getFunction()); -+} -+ -+bool BridgedType::isReferenceCounted(BridgedFunction f) const { -+ return get().isReferenceCounted(f.getFunction()); -+} -+ -+bool BridgedType::isUnownedStorageType() const { -+ return get().isUnownedStorageType(); -+} -+ -+bool BridgedType::hasArchetype() const { -+ return get().hasArchetype(); -+} -+ -+bool BridgedType::isNominalOrBoundGenericNominal() const { -+ return get().getNominalOrBoundGenericNominal() != nullptr; -+} -+ -+BridgedNominalTypeDecl BridgedType::getNominalOrBoundGenericNominal() const { -+ return {get().getNominalOrBoundGenericNominal()}; -+} -+ -+bool BridgedType::isClassOrBoundGenericClass() const { -+ return get().getClassOrBoundGenericClass() != 0; -+} -+ -+bool BridgedType::isStructOrBoundGenericStruct() const { -+ return get().getStructOrBoundGenericStruct() != nullptr; -+} -+ -+bool BridgedType::isTuple() const { -+ return get().isTuple(); -+} -+ -+bool BridgedType::isEnumOrBoundGenericEnum() const { -+ return get().getEnumOrBoundGenericEnum() != nullptr; -+} -+ -+bool BridgedType::isFunction() const { -+ return get().isFunction(); -+} -+ -+bool BridgedType::isMetatype() const { -+ return get().isMetatype(); -+} -+ -+bool BridgedType::isNoEscapeFunction() const { -+ return get().isNoEscapeFunction(); -+} -+ -+/*bool BridgedType::isAsyncFunction() const { -+ return get().isAsyncFunction(); -+}*/ -+ -+BridgedType::TraitResult BridgedType::canBeClass() const { -+ return (TraitResult)get().canBeClass(); -+} -+ -+bool BridgedType::isMoveOnly() const { -+ return get().isMoveOnly(); -+} -+ -+bool BridgedType::isOrContainsObjectiveCClass() const { -+ return get().isOrContainsObjectiveCClass(); -+} -+ -+bool BridgedType::isBuiltinInteger() const { -+ return get().isBuiltinInteger(); -+} -+ -+bool BridgedType::isBuiltinFloat() const { -+ return get().isBuiltinFloat(); -+} -+ -+bool BridgedType::isBuiltinVector() const { -+ return get().isBuiltinVector(); -+} -+ -+BridgedType BridgedType::getBuiltinVectorElementType() const { -+ return get().getBuiltinVectorElementType(); -+} -+ -+bool BridgedType::isBuiltinFixedWidthInteger(SwiftInt width) const { -+ return get().isBuiltinFixedWidthInteger((unsigned)width); -+} -+ -+bool BridgedType::isExactSuperclassOf(BridgedType t) const { -+ return get().isExactSuperclassOf(t.get()); -+} -+ -+BridgedType BridgedType::getInstanceTypeOfMetatype(BridgedFunction f) const { -+ return get().getInstanceTypeOfMetatype(f.getFunction()); -+} -+ -+bool BridgedType::isDynamicSelfMetatype() const { -+ auto metaType = get().castTo(); -+ swift::Type instTy = metaType->getInstanceType(); -+ return instTy->is(); -+} -+ -+/*BridgedType::MetatypeRepresentation BridgedType::getRepresentationOfMetatype(BridgedFunction f) const { -+ return BridgedType::MetatypeRepresentation(get().getRepresentationOfMetatype(f.getFunction())); -+}*/ -+ -+bool BridgedType::isCalleeConsumedFunction() const { -+ return get().isCalleeConsumedFunction(); -+} -+ -+bool BridgedType::isMarkedAsImmortal() const { -+ return get().isMarkedAsImmortal(); -+} -+ -+SwiftInt BridgedType::getCaseIdxOfEnumType(BridgedStringRef name) const { -+ return get().getCaseIdxOfEnumType(name.get()); -+} -+ -+SwiftInt BridgedType::getNumNominalFields() const { -+ return get().getNumNominalFields(); -+} -+ -+ -+BridgedType BridgedType::getFieldType(SwiftInt idx, BridgedFunction f) const { -+ return get().getFieldType(idx, f.getFunction()); -+} -+ -+SwiftInt BridgedType::getFieldIdxOfNominalType(BridgedStringRef name) const { -+ return get().getFieldIdxOfNominalType(name.get()); -+} -+ -+BridgedStringRef BridgedType::getFieldName(SwiftInt idx) const { -+ return get().getFieldName(idx); -+} -+ -+SwiftInt BridgedType::getNumTupleElements() const { -+ return get().getNumTupleElements(); -+} -+ -+BridgedType BridgedType::getTupleElementType(SwiftInt idx) const { -+ return get().getTupleElementType(idx); -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedValue -+//===----------------------------------------------------------------------===// -+ -+inline BridgedValue::Ownership castOwnership(swift::OwnershipKind ownership) { -+ switch (ownership) { -+ case swift::OwnershipKind::Any: -+ llvm_unreachable("Invalid ownership for value"); -+ case swift::OwnershipKind::Unowned: return BridgedValue::Ownership::Unowned; -+ case swift::OwnershipKind::Owned: return BridgedValue::Ownership::Owned; -+ case swift::OwnershipKind::Guaranteed: return BridgedValue::Ownership::Guaranteed; -+ case swift::OwnershipKind::None: return BridgedValue::Ownership::None; -+ } -+} -+ -+swift::ValueBase * _Nonnull BridgedValue::getSILValue() const { -+ return static_cast(obj); -+} -+ -+swift::ValueBase * _Nullable OptionalBridgedValue::getSILValue() const { -+ if (obj) -+ return static_cast(obj); -+ return nullptr; -+} -+ -+OptionalBridgedOperand BridgedValue::getFirstUse() const { -+ return {*getSILValue()->use_begin()}; -+} -+ -+BridgedType BridgedValue::getType() const { -+ return getSILValue()->getType(); -+} -+ -+BridgedValue::Ownership BridgedValue::getOwnership() const { -+ return castOwnership(getSILValue()->getOwnershipKind()); -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedOperand -+//===----------------------------------------------------------------------===// -+ -+bool BridgedOperand::isTypeDependent() const { return op->isTypeDependent(); } -+ -+bool BridgedOperand::isLifetimeEnding() const { return op->isLifetimeEnding(); } -+ -+OptionalBridgedOperand BridgedOperand::getNextUse() const { -+ return {op->getNextUse()}; -+} -+ -+BridgedValue BridgedOperand::getValue() const { return {op->get()}; } -+ -+BridgedInstruction BridgedOperand::getUser() const { -+ return {op->getUser()->asSILNode()}; -+} -+ -+/*BridgedOperand::OperandOwnership BridgedOperand::getOperandOwnership() const { -+ switch (op->getOperandOwnership()) { -+ case swift::OperandOwnership::NonUse: -+ return OperandOwnership::NonUse; -+ case swift::OperandOwnership::TrivialUse: -+ return OperandOwnership::TrivialUse; -+ case swift::OperandOwnership::InstantaneousUse: -+ return OperandOwnership::InstantaneousUse; -+ case swift::OperandOwnership::UnownedInstantaneousUse: -+ return OperandOwnership::UnownedInstantaneousUse; -+ case swift::OperandOwnership::ForwardingUnowned: -+ return OperandOwnership::ForwardingUnowned; -+ case swift::OperandOwnership::PointerEscape: -+ return OperandOwnership::PointerEscape; -+ case swift::OperandOwnership::BitwiseEscape: -+ return OperandOwnership::BitwiseEscape; -+ case swift::OperandOwnership::Borrow: -+ return OperandOwnership::Borrow; -+ case swift::OperandOwnership::DestroyingConsume: -+ return OperandOwnership::DestroyingConsume; -+ case swift::OperandOwnership::ForwardingConsume: -+ return OperandOwnership::ForwardingConsume; -+ case swift::OperandOwnership::InteriorPointer: -+ return OperandOwnership::InteriorPointer; -+ case swift::OperandOwnership::GuaranteedForwarding: -+ return OperandOwnership::GuaranteedForwarding; -+ case swift::OperandOwnership::EndBorrow: -+ return OperandOwnership::EndBorrow; -+ case swift::OperandOwnership::Reborrow: -+ return OperandOwnership::Reborrow; -+ } -+}*/ -+ -+BridgedOperand OptionalBridgedOperand::advancedBy(SwiftInt index) const { return {op + index}; } -+ -+// Assumes that `op` is not null. -+SwiftInt OptionalBridgedOperand::distanceTo(BridgedOperand element) const { return element.op - op; } -+ -+//===----------------------------------------------------------------------===// -+// BridgedArgument -+//===----------------------------------------------------------------------===// -+ -+inline BridgedArgumentConvention castToArgumentConvention(swift::SILArgumentConvention convention) { -+ return static_cast(convention.Value); -+} -+ -+swift::SILArgument * _Nonnull BridgedArgument::getArgument() const { -+ return static_cast(obj); -+} -+ -+BridgedBasicBlock BridgedArgument::getParent() const { -+ return {getArgument()->getParent()}; -+} -+ -+BridgedArgumentConvention BridgedArgument::getConvention() const { -+ auto *fArg = llvm::cast(getArgument()); -+ return castToArgumentConvention(fArg->getArgumentConvention()); -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedSubstitutionMap -+//===----------------------------------------------------------------------===// -+ -+BridgedSubstitutionMap::BridgedSubstitutionMap() : BridgedSubstitutionMap(swift::SubstitutionMap()) { -+} -+ -+bool BridgedSubstitutionMap::isEmpty() const { -+ return get().empty(); -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedLocation -+//===----------------------------------------------------------------------===// -+ -+BridgedLocation BridgedLocation::getAutogeneratedLocation() const { -+ return getLoc().getAutogeneratedLocation(); -+} -+bool BridgedLocation::hasValidLineNumber() const { -+ return getLoc().hasValidLineNumber(); -+} -+bool BridgedLocation::isAutoGenerated() const { -+ return getLoc().isAutoGenerated(); -+} -+bool BridgedLocation::isEqualTo(BridgedLocation rhs) const { -+ return getLoc().isEqualTo(rhs.getLoc()); -+} -+bool BridgedLocation::hasSameSourceLocation(BridgedLocation rhs) const { -+ return getLoc().hasSameSourceLocation(rhs.getLoc()); -+} -+BridgedLocation BridgedLocation::getArtificialUnreachableLocation() { -+ return swift::SILDebugLocation::getArtificialUnreachableLocation(); -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedFunction -+//===----------------------------------------------------------------------===// -+ -+swift::SILFunction * _Nonnull BridgedFunction::getFunction() const { -+ return static_cast(obj); -+} -+ -+BridgedStringRef BridgedFunction::getName() const { -+ return getFunction()->getName(); -+} -+ -+bool BridgedFunction::hasOwnership() const { return getFunction()->hasOwnership(); } -+ -+OptionalBridgedBasicBlock BridgedFunction::getFirstBlock() const { -+ return {getFunction()->empty() ? nullptr : getFunction()->getEntryBlock()}; -+} -+ -+OptionalBridgedBasicBlock BridgedFunction::getLastBlock() const { -+ return {getFunction()->empty() ? nullptr : &*getFunction()->rbegin()}; -+} -+ -+SwiftInt BridgedFunction::getNumIndirectFormalResults() const { -+ return (SwiftInt)getFunction()->getLoweredFunctionType()->getNumIndirectFormalResults(); -+} -+ -+SwiftInt BridgedFunction::getNumParameters() const { -+ return (SwiftInt)getFunction()->getLoweredFunctionType()->getNumParameters(); -+} -+ -+SwiftInt BridgedFunction::getSelfArgumentIndex() const { -+ swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); -+ swift::CanSILFunctionType fTy = getFunction()->getLoweredFunctionType(); -+ if (!fTy->hasSelfParam()) -+ return -1; -+ return conv.getNumParameters() + conv.getNumIndirectSILResults() - 1; -+} -+ -+SwiftInt BridgedFunction::getNumSILArguments() const { -+ return swift::SILFunctionConventions(getFunction()->getConventionsInContext()).getNumSILArguments(); -+} -+ -+BridgedType BridgedFunction::getSILArgumentType(SwiftInt idx) const { -+ swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); -+ return conv.getSILArgumentType(idx, getFunction()->getTypeExpansionContext()); -+} -+ -+BridgedArgumentConvention BridgedFunction::getSILArgumentConvention(SwiftInt idx) const { -+ swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); -+ return castToArgumentConvention(conv.getSILArgumentConvention(idx)); -+} -+ -+BridgedType BridgedFunction::getSILResultType() const { -+ swift::SILFunctionConventions conv(getFunction()->getConventionsInContext()); -+ return conv.getSILResultType(getFunction()->getTypeExpansionContext()); -+} -+ -+bool BridgedFunction::isSwift51RuntimeAvailable() const { -+ if (getFunction()->getResilienceExpansion() != swift::ResilienceExpansion::Maximal) -+ return false; -+ -+ swift::ASTContext &ctxt = getFunction()->getModule().getASTContext(); -+ return swift::AvailabilityContext::forDeploymentTarget(ctxt).isContainedIn(ctxt.getSwift51Availability()); -+} -+ -+bool BridgedFunction::isPossiblyUsedExternally() const { -+ return getFunction()->isPossiblyUsedExternally(); -+} -+ -+bool BridgedFunction::isAvailableExternally() const { -+ return getFunction()->isAvailableExternally(); -+} -+ -+bool BridgedFunction::isTransparent() const { -+ return getFunction()->isTransparent() == swift::IsTransparent; -+} -+ -+bool BridgedFunction::isAsync() const { -+ return getFunction()->isAsync(); -+} -+ -+bool BridgedFunction::isGlobalInitFunction() const { -+ return getFunction()->isGlobalInit(); -+} -+ -+bool BridgedFunction::isGlobalInitOnceFunction() const { -+ return getFunction()->isGlobalInitOnceFunction(); -+} -+ -+bool BridgedFunction::isGenericFunction() const { -+ return !getFunction()->getGenericSignature().isNull(); -+} -+ -+bool BridgedFunction::hasSemanticsAttr(BridgedStringRef attrName) const { -+ return getFunction()->hasSemanticsAttr(attrName.get()); -+} -+ -+BridgedFunction::EffectsKind BridgedFunction::getEffectAttribute() const { -+ return (EffectsKind)getFunction()->getEffectsKind(); -+} -+ -+BridgedFunction::PerformanceConstraints BridgedFunction::getPerformanceConstraints() const { -+ return (PerformanceConstraints)getFunction()->getPerfConstraints(); -+} -+ -+BridgedFunction::InlineStrategy BridgedFunction::getInlineStrategy() const { -+ return (InlineStrategy)getFunction()->getInlineStrategy(); -+} -+ -+bool BridgedFunction::isSerialized() const { -+ return getFunction()->isSerialized(); -+} -+ -+bool BridgedFunction::hasValidLinkageForFragileRef() const { -+ return getFunction()->hasValidLinkageForFragileRef(); -+} -+ -+bool BridgedFunction::needsStackProtection() const { -+ return getFunction()->needsStackProtection(); -+} -+ -+void BridgedFunction::setNeedStackProtection(bool needSP) const { -+ getFunction()->setNeedStackProtection(needSP); -+} -+ -+ -+//===----------------------------------------------------------------------===// -+// BridgedGlobalVar -+//===----------------------------------------------------------------------===// -+ -+swift::SILGlobalVariable * _Nonnull BridgedGlobalVar::getGlobal() const { -+ return static_cast(obj); -+} -+ -+BridgedStringRef BridgedGlobalVar::getName() const { -+ return getGlobal()->getName(); -+} -+ -+bool BridgedGlobalVar::isLet() const { return getGlobal()->isLet(); } -+ -+void BridgedGlobalVar::setLet(bool value) const { getGlobal()->setLet(value); } -+ -+bool BridgedGlobalVar::isPossiblyUsedExternally() const { -+ return getGlobal()->isPossiblyUsedExternally(); -+} -+ -+bool BridgedGlobalVar::isAvailableExternally() const { -+ return swift::isAvailableExternally(getGlobal()->getLinkage()); -+} -+ -+OptionalBridgedInstruction BridgedGlobalVar::getFirstStaticInitInst() const { -+ if (getGlobal()->begin() == getGlobal()->end()) { -+ return {nullptr}; -+ } -+ swift::SILInstruction *firstInst = &*getGlobal()->begin(); -+ return {firstInst->asSILNode()}; -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedMultiValueResult -+//===----------------------------------------------------------------------===// -+ -+BridgedInstruction BridgedMultiValueResult::getParent() const { -+ return {get()->getParent()}; -+} -+ -+SwiftInt BridgedMultiValueResult::getIndex() const { -+ return (SwiftInt)get()->getIndex(); -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedTypeArray -+//===----------------------------------------------------------------------===// -+ -+BridgedTypeArray BridgedTypeArray::fromReplacementTypes(BridgedSubstitutionMap substMap) { -+ swift::ArrayRef replTypes = substMap.get().getReplacementTypes(); -+ return {replTypes.data(), replTypes.size()}; -+} -+ -+BridgedType BridgedTypeArray::getAt(SwiftInt index) const { -+ assert((size_t)index < typeArray.numElements); -+ swift::Type origTy = ((const swift::Type *)typeArray.data)[index]; -+ auto ty = origTy->getCanonicalType(); -+ if (ty->isLegalSILType()) -+ return swift::SILType::getPrimitiveObjectType(ty); -+ return swift::SILType(); -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedTypeArray -+//===----------------------------------------------------------------------===// -+ -+BridgedType BridgedSILTypeArray::getAt(SwiftInt index) const { -+ assert((size_t)index < typeArray.numElements); -+ return ((const swift::SILType *)typeArray.data)[index]; -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedInstruction -+//===----------------------------------------------------------------------===// -+ -+OptionalBridgedInstruction BridgedInstruction::getNext() const { -+ auto iter = std::next(get()->getIterator()); -+ if (iter == get()->getParent()->end()) -+ return {nullptr}; -+ return {iter->asSILNode()}; -+} -+ -+OptionalBridgedInstruction BridgedInstruction::getPrevious() const { -+ auto iter = std::next(get()->getReverseIterator()); -+ if (iter == get()->getParent()->rend()) -+ return {nullptr}; -+ return {iter->asSILNode()}; -+} -+ -+BridgedBasicBlock BridgedInstruction::getParent() const { -+ assert(!get()->isStaticInitializerInst() && -+ "cannot get the parent of a static initializer instruction"); -+ return {get()->getParent()}; -+} -+ -+BridgedInstruction BridgedInstruction::getLastInstOfParent() const { -+ return {get()->getParent()->back().asSILNode()}; -+} -+ -+bool BridgedInstruction::isDeleted() const { -+ return get()->isDeleted(); -+} -+ -+BridgedOperandArray BridgedInstruction::getOperands() const { -+ auto operands = get()->getAllOperands(); -+ return {{operands.data()}, (SwiftInt)operands.size()}; -+} -+ -+BridgedOperandArray BridgedInstruction::getTypeDependentOperands() const { -+ auto typeOperands = get()->getTypeDependentOperands(); -+ return {{typeOperands.data()}, (SwiftInt)typeOperands.size()}; -+} -+ -+void BridgedInstruction::setOperand(SwiftInt index, BridgedValue value) const { -+ get()->setOperand((unsigned)index, value.getSILValue()); -+} -+ -+BridgedLocation BridgedInstruction::getLocation() const { -+ return get()->getDebugLocation(); -+} -+ -+BridgedMemoryBehavior BridgedInstruction::getMemBehavior() const { -+ return (BridgedMemoryBehavior)get()->getMemoryBehavior(); -+} -+ -+bool BridgedInstruction::mayRelease() const { -+ return get()->mayRelease(); -+} -+ -+bool BridgedInstruction::mayHaveSideEffects() const { -+ return get()->mayHaveSideEffects(); -+} -+ -+bool BridgedInstruction::maySuspend() const { -+ return get()->maySuspend(); -+} -+ -+SwiftInt BridgedInstruction::MultipleValueInstruction_getNumResults() const { -+ return getAs()->getNumResults(); -+} -+ -+BridgedMultiValueResult BridgedInstruction::MultipleValueInstruction_getResult(SwiftInt index) const { -+ return {getAs()->getResult(index)}; -+} -+ -+BridgedSuccessorArray BridgedInstruction::TermInst_getSuccessors() const { -+ auto successors = getAs()->getSuccessors(); -+ return {{successors.data()}, (SwiftInt)successors.size()}; -+} -+ -+BridgedStringRef BridgedInstruction::CondFailInst_getMessage() const { -+ return getAs()->getMessage(); -+} -+ -+SwiftInt BridgedInstruction::LoadInst_getLoadOwnership() const { -+ return (SwiftInt)getAs()->getOwnershipQualifier(); -+} -+ -+BridgedInstruction::BuiltinValueKind BridgedInstruction::BuiltinInst_getID() const { -+ return (BuiltinValueKind)getAs()->getBuiltinInfo().ID; -+} -+ -+BridgedInstruction::IntrinsicID BridgedInstruction::BuiltinInst_getIntrinsicID() const { -+ switch (getAs()->getIntrinsicInfo().ID) { -+ case llvm::Intrinsic::memcpy: return IntrinsicID::memcpy; -+ case llvm::Intrinsic::memmove: return IntrinsicID::memmove; -+ default: return IntrinsicID::unknown; -+ } -+} -+ -+BridgedSubstitutionMap BridgedInstruction::BuiltinInst_getSubstitutionMap() const { -+ return getAs()->getSubstitutions(); -+} -+ -+bool BridgedInstruction::PointerToAddressInst_isStrict() const { -+ return getAs()->isStrict(); -+} -+ -+bool BridgedInstruction::AddressToPointerInst_needsStackProtection() const { -+ return getAs()->needsStackProtection(); -+} -+ -+bool BridgedInstruction::IndexAddrInst_needsStackProtection() const { -+ return getAs()->needsStackProtection(); -+} -+ -+BridgedGlobalVar BridgedInstruction::GlobalAccessInst_getGlobal() const { -+ return {getAs()->getReferencedGlobal()}; -+} -+ -+BridgedGlobalVar BridgedInstruction::AllocGlobalInst_getGlobal() const { -+ return {getAs()->getReferencedGlobal()}; -+} -+ -+BridgedFunction BridgedInstruction::FunctionRefBaseInst_getReferencedFunction() const { -+ return {getAs()->getInitiallyReferencedFunction()}; -+} -+ -+BridgedInstruction::OptionalInt BridgedInstruction::IntegerLiteralInst_getValue() const { -+ llvm::APInt result = getAs()->getValue(); -+ if (result.getSignificantBits() <= std::min(std::numeric_limits::digits, 64)) { -+ return {(SwiftInt)result.getSExtValue(), true}; -+ } -+ return {0, false}; -+} -+ -+BridgedStringRef BridgedInstruction::StringLiteralInst_getValue() const { -+ return getAs()->getValue(); -+} -+ -+int BridgedInstruction::StringLiteralInst_getEncoding() const { -+ return (int)getAs()->getEncoding(); -+} -+ -+SwiftInt BridgedInstruction::TupleExtractInst_fieldIndex() const { -+ return getAs()->getFieldIndex(); -+} -+ -+SwiftInt BridgedInstruction::TupleElementAddrInst_fieldIndex() const { -+ return getAs()->getFieldIndex(); -+} -+ -+SwiftInt BridgedInstruction::StructExtractInst_fieldIndex() const { -+ return getAs()->getFieldIndex(); -+} -+ -+OptionalBridgedValue BridgedInstruction::StructInst_getUniqueNonTrivialFieldValue() const { -+ return {getAs()->getUniqueNonTrivialFieldValue()}; -+} -+ -+SwiftInt BridgedInstruction::StructElementAddrInst_fieldIndex() const { -+ return getAs()->getFieldIndex(); -+} -+ -+SwiftInt BridgedInstruction::ProjectBoxInst_fieldIndex() const { -+ return getAs()->getFieldIndex(); -+} -+ -+bool BridgedInstruction::EndCOWMutationInst_doKeepUnique() const { -+ return getAs()->doKeepUnique(); -+} -+ -+SwiftInt BridgedInstruction::EnumInst_caseIndex() const { -+ return getAs()->getCaseIndex(); -+} -+ -+SwiftInt BridgedInstruction::UncheckedEnumDataInst_caseIndex() const { -+ return getAs()->getCaseIndex(); -+} -+ -+SwiftInt BridgedInstruction::InitEnumDataAddrInst_caseIndex() const { -+ return getAs()->getCaseIndex(); -+} -+ -+SwiftInt BridgedInstruction::UncheckedTakeEnumDataAddrInst_caseIndex() const { -+ return getAs()->getCaseIndex(); -+} -+ -+SwiftInt BridgedInstruction::InjectEnumAddrInst_caseIndex() const { -+ return getAs()->getCaseIndex(); -+} -+ -+SwiftInt BridgedInstruction::RefElementAddrInst_fieldIndex() const { -+ return getAs()->getFieldIndex(); -+} -+ -+bool BridgedInstruction::RefElementAddrInst_fieldIsLet() const { -+ return getAs()->getField()->isLet(); -+} -+ -+SwiftInt BridgedInstruction::PartialApplyInst_numArguments() const { -+ return getAs()->getNumArguments(); -+} -+ -+SwiftInt BridgedInstruction::ApplyInst_numArguments() const { -+ return getAs()->getNumArguments(); -+} -+ -+bool BridgedInstruction::ApplyInst_getNonThrowing() const { -+ return getAs()->isNonThrowing(); -+} -+ -+bool BridgedInstruction::ApplyInst_getNonAsync() const { -+ return getAs()->isNonAsync(); -+} -+ -+BridgedGenericSpecializationInformation BridgedInstruction::ApplyInst_getSpecializationInfo() const { -+ return {getAs()->getSpecializationInfo()}; -+} -+ -+SwiftInt BridgedInstruction::ObjectInst_getNumBaseElements() const { -+ return getAs()->getNumBaseElements(); -+} -+ -+SwiftInt BridgedInstruction::PartialApply_getCalleeArgIndexOfFirstAppliedArg() const { -+ return swift::ApplySite(get()).getCalleeArgIndexOfFirstAppliedArg(); -+} -+ -+bool BridgedInstruction::PartialApplyInst_isOnStack() const { -+ return getAs()->isOnStack(); -+} -+ -+bool BridgedInstruction::AllocStackInst_hasDynamicLifetime() const { -+ return getAs()->hasDynamicLifetime(); -+} -+ -+bool BridgedInstruction::AllocRefInstBase_isObjc() const { -+ return getAs()->isObjC(); -+} -+ -+bool BridgedInstruction::AllocRefInstBase_canAllocOnStack() const { -+ return getAs()->canAllocOnStack(); -+} -+ -+SwiftInt BridgedInstruction::AllocRefInstBase_getNumTailTypes() const { -+ return getAs()->getNumTailTypes(); -+} -+ -+BridgedSILTypeArray BridgedInstruction::AllocRefInstBase_getTailAllocatedTypes() const { -+ llvm::ArrayRef types = getAs()->getTailAllocatedTypes(); -+ return {types.data(), types.size()}; -+} -+ -+bool BridgedInstruction::AllocRefDynamicInst_isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType() const { -+ return getAs()->isDynamicTypeDeinitAndSizeKnownEquivalentToBaseType(); -+} -+ -+SwiftInt BridgedInstruction::BeginApplyInst_numArguments() const { -+ return getAs()->getNumArguments(); -+} -+ -+SwiftInt BridgedInstruction::TryApplyInst_numArguments() const { -+ return getAs()->getNumArguments(); -+} -+ -+BridgedBasicBlock BridgedInstruction::BranchInst_getTargetBlock() const { -+ return {getAs()->getDestBB()}; -+} -+ -+SwiftInt BridgedInstruction::SwitchEnumInst_getNumCases() const { -+ return getAs()->getNumCases(); -+} -+ -+SwiftInt BridgedInstruction::SwitchEnumInst_getCaseIndex(SwiftInt idx) const { -+ auto *seInst = getAs(); -+ return seInst->getModule().getCaseIndex(seInst->getCase(idx).first); -+} -+ -+SwiftInt BridgedInstruction::StoreInst_getStoreOwnership() const { -+ return (SwiftInt)getAs()->getOwnershipQualifier(); -+} -+ -+BridgedInstruction::AccessKind BridgedInstruction::BeginAccessInst_getAccessKind() const { -+ return (AccessKind)getAs()->getAccessKind(); -+} -+ -+bool BridgedInstruction::BeginAccessInst_isStatic() const { -+ return getAs()->getEnforcement() == swift::SILAccessEnforcement::Static; -+} -+ -+bool BridgedInstruction::CopyAddrInst_isTakeOfSrc() const { -+ return getAs()->isTakeOfSrc(); -+} -+ -+bool BridgedInstruction::CopyAddrInst_isInitializationOfDest() const { -+ return getAs()->isInitializationOfDest(); -+} -+ -+void BridgedInstruction::RefCountingInst_setIsAtomic(bool isAtomic) const { -+ getAs()->setAtomicity( -+ isAtomic ? swift::RefCountingInst::Atomicity::Atomic -+ : swift::RefCountingInst::Atomicity::NonAtomic); -+} -+ -+bool BridgedInstruction::RefCountingInst_getIsAtomic() const { -+ return getAs()->getAtomicity() == swift::RefCountingInst::Atomicity::Atomic; -+} -+ -+SwiftInt BridgedInstruction::CondBranchInst_getNumTrueArgs() const { -+ return getAs()->getNumTrueArgs(); -+} -+ -+void BridgedInstruction::AllocRefInstBase_setIsStackAllocatable() const { -+ getAs()->setStackAllocatable(); -+} -+ -+bool BridgedInstruction::AllocRefInst_isBare() const { -+ return getAs()->isBare(); -+} -+ -+void BridgedInstruction::AllocRefInst_setIsBare() const { -+ getAs()->setBare(true); -+} -+ -+void BridgedInstruction::TermInst_replaceBranchTarget(BridgedBasicBlock from, BridgedBasicBlock to) const { -+ getAs()->replaceBranchTarget(from.get(), to.get()); -+} -+ -+SwiftInt BridgedInstruction::KeyPathInst_getNumComponents() const { -+ if (swift::KeyPathPattern *pattern = getAs()->getPattern()) { -+ return (SwiftInt)pattern->getComponents().size(); -+ } -+ return 0; -+} -+ -+void BridgedInstruction::KeyPathInst_getReferencedFunctions(SwiftInt componentIdx, -+ KeyPathFunctionResults * _Nonnull results) const { -+ swift::KeyPathPattern *pattern = getAs()->getPattern(); -+ const swift::KeyPathPatternComponent &comp = pattern->getComponents()[componentIdx]; -+ results->numFunctions = 0; -+ -+ comp.visitReferencedFunctionsAndMethods([results](swift::SILFunction *func) { -+ assert(results->numFunctions < KeyPathFunctionResults::maxFunctions); -+ results->functions[results->numFunctions++] = {func}; -+ }, [](swift::SILDeclRef) {}); -+} -+ -+bool BridgedInstruction::GlobalValueInst_isBare() const { -+ return getAs()->isBare(); -+} -+ -+void BridgedInstruction::GlobalValueInst_setIsBare() const { -+ getAs()->setBare(true); -+} -+ -+void BridgedInstruction::LoadInst_setOwnership(SwiftInt ownership) const { -+ getAs()->setOwnershipQualifier((swift::LoadOwnershipQualifier)ownership); -+} -+ -+BridgedBasicBlock BridgedInstruction::CheckedCastBranch_getSuccessBlock() const { -+ return {getAs()->getSuccessBB()}; -+} -+ -+BridgedBasicBlock BridgedInstruction::CheckedCastBranch_getFailureBlock() const { -+ return {getAs()->getFailureBB()}; -+} -+ -+BridgedSubstitutionMap BridgedInstruction::ApplySite_getSubstitutionMap() const { -+ auto as = swift::ApplySite(get()); -+ return as.getSubstitutionMap(); -+} -+ -+BridgedArgumentConvention BridgedInstruction::ApplySite_getArgumentConvention(SwiftInt calleeArgIdx) const { -+ auto as = swift::ApplySite(get()); -+ auto conv = as.getSubstCalleeConv().getSILArgumentConvention(calleeArgIdx); -+ return castToArgumentConvention(conv.Value); -+} -+ -+SwiftInt BridgedInstruction::ApplySite_getNumArguments() const { -+ return swift::ApplySite(get()).getNumArguments(); -+} -+ -+SwiftInt BridgedInstruction::FullApplySite_numIndirectResultArguments() const { -+ auto fas = swift::FullApplySite(get()); -+ return fas.getNumIndirectSILResults(); -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedBasicBlock -+//===----------------------------------------------------------------------===// -+ -+OptionalBridgedBasicBlock BridgedBasicBlock::getNext() const { -+ auto iter = std::next(get()->getIterator()); -+ if (iter == get()->getParent()->end()) -+ return {nullptr}; -+ return {&*iter}; -+} -+ -+OptionalBridgedBasicBlock BridgedBasicBlock::getPrevious() const { -+ auto iter = std::next(get()->getReverseIterator()); -+ if (iter == get()->getParent()->rend()) -+ return {nullptr}; -+ return {&*iter}; -+} -+ -+BridgedFunction BridgedBasicBlock::getFunction() const { -+ return {get()->getParent()}; -+} -+ -+OptionalBridgedInstruction BridgedBasicBlock::getFirstInst() const { -+ if (get()->empty()) -+ return {nullptr}; -+ return {get()->front().asSILNode()}; -+} -+ -+OptionalBridgedInstruction BridgedBasicBlock::getLastInst() const { -+ if (get()->empty()) -+ return {nullptr}; -+ return {get()->back().asSILNode()}; -+} -+ -+SwiftInt BridgedBasicBlock::getNumArguments() const { -+ return get()->getNumArguments(); -+} -+ -+BridgedArgument BridgedBasicBlock::getArgument(SwiftInt index) const { -+ return {get()->getArgument(index)}; -+} -+ -+BridgedArgument BridgedBasicBlock::addBlockArgument(BridgedType type, BridgedValue::Ownership ownership) const { -+ return {get()->createPhiArgument(type.get(), BridgedValue::castToOwnership(ownership))}; -+} -+ -+void BridgedBasicBlock::eraseArgument(SwiftInt index) const { -+ get()->eraseArgument(index); -+} -+ -+void BridgedBasicBlock::moveAllInstructionsToBegin(BridgedBasicBlock dest) const { -+ dest.get()->spliceAtBegin(get()); -+} -+ -+void BridgedBasicBlock::moveAllInstructionsToEnd(BridgedBasicBlock dest) const { -+ dest.get()->spliceAtEnd(get()); -+} -+ -+void BridgedBasicBlock::moveArgumentsTo(BridgedBasicBlock dest) const { -+ dest.get()->moveArgumentList(get()); -+} -+ -+OptionalBridgedSuccessor BridgedBasicBlock::getFirstPred() const { -+ return {get()->pred_begin().getSuccessorRef()}; -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedSuccessor -+//===----------------------------------------------------------------------===// -+ -+OptionalBridgedSuccessor BridgedSuccessor::getNext() const { -+ return {succ->getNext()}; -+} -+ -+BridgedBasicBlock BridgedSuccessor::getTargetBlock() const { -+ return succ->getBB(); -+} -+ -+BridgedInstruction BridgedSuccessor::getContainingInst() const { -+ return {succ->getContainingInst()}; -+} -+ -+BridgedSuccessor OptionalBridgedSuccessor::advancedBy(SwiftInt index) const { -+ return {succ + index}; -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedVTable -+//===----------------------------------------------------------------------===// -+ -+BridgedFunction BridgedVTableEntry::getImplementation() const { -+ return {entry->getImplementation()}; -+} -+ -+BridgedVTableEntry BridgedVTableEntry::advanceBy(SwiftInt index) const { -+ return {entry + index}; -+} -+ -+BridgedVTableEntryArray BridgedVTable::getEntries() const { -+ auto entries = vTable->getEntries(); -+ return {{entries.data()}, (SwiftInt)entries.size()}; -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedWitnessTable, BridgedDefaultWitnessTable -+//===----------------------------------------------------------------------===// -+ -+BridgedWitnessTableEntry::Kind BridgedWitnessTableEntry::getKind() const { -+ return (Kind)getEntry()->getKind(); -+} -+ -+OptionalBridgedFunction BridgedWitnessTableEntry::getMethodFunction() const { -+ return {getEntry()->getMethodWitness().Witness}; -+} -+ -+BridgedWitnessTableEntry BridgedWitnessTableEntry::advanceBy(SwiftInt index) const { -+ return {getEntry() + index}; -+} -+ -+BridgedWitnessTableEntryArray BridgedWitnessTable::getEntries() const { -+ auto entries = table->getEntries(); -+ return {{entries.data()}, (SwiftInt)entries.size()}; -+} -+ -+BridgedWitnessTableEntryArray BridgedDefaultWitnessTable::getEntries() const { -+ auto entries = table->getEntries(); -+ return {{entries.data()}, (SwiftInt)entries.size()}; -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedBuilder -+//===----------------------------------------------------------------------===// -+ -+BridgedInstruction BridgedBuilder::createBuiltinBinaryFunction(BridgedStringRef name, -+ BridgedType operandType, BridgedType resultType, -+ BridgedValueArray arguments) const { -+ llvm::SmallVector argValues; -+ return {get().createBuiltinBinaryFunction(regularLoc(), -+ name.get(), -+ operandType.get(), resultType.get(), -+ arguments.getValues(argValues))}; -+} -+ -+BridgedInstruction BridgedBuilder::createCondFail(BridgedValue condition, BridgedStringRef message) const { -+ return {get().createCondFail(regularLoc(), condition.getSILValue(), message.get())}; -+} -+ -+BridgedInstruction BridgedBuilder::createIntegerLiteral(BridgedType type, SwiftInt value) const { -+ return {get().createIntegerLiteral(regularLoc(), type.get(), value)}; -+} -+ -+BridgedInstruction BridgedBuilder::createAllocStack(BridgedType type, -+ bool hasDynamicLifetime, bool isLexical, bool wasMoved) const { -+ return {get().createAllocStack(regularLoc(), type.get(), llvm::None, -+ hasDynamicLifetime, isLexical, wasMoved)}; -+} -+ -+BridgedInstruction BridgedBuilder::createDeallocStack(BridgedValue operand) const { -+ return {get().createDeallocStack(regularLoc(), operand.getSILValue())}; -+} -+ -+BridgedInstruction BridgedBuilder::createDeallocStackRef(BridgedValue operand) const { -+ return {get().createDeallocStackRef(regularLoc(), operand.getSILValue())}; -+} -+ -+BridgedInstruction BridgedBuilder::createUncheckedRefCast(BridgedValue op, BridgedType type) const { -+ return {get().createUncheckedRefCast(regularLoc(), op.getSILValue(), type.get())}; -+} -+ -+BridgedInstruction BridgedBuilder::createUpcast(BridgedValue op, BridgedType type) const { -+ return {get().createUpcast(regularLoc(), op.getSILValue(), type.get())}; -+} -+ -+BridgedInstruction BridgedBuilder::createLoad(BridgedValue op, SwiftInt ownership) const { -+ return {get().createLoad(regularLoc(), op.getSILValue(), (swift::LoadOwnershipQualifier)ownership)}; -+} -+ -+/*BridgedInstruction BridgedBuilder::createBeginDeallocRef(BridgedValue reference, BridgedValue allocation) const { -+ return {get().createBeginDeallocRef(regularLoc(), reference.getSILValue(), allocation.getSILValue())}; -+} -+ -+BridgedInstruction BridgedBuilder::createEndInitLetRef(BridgedValue op) const { -+ return {get().createEndInitLetRef(regularLoc(), op.getSILValue())}; -+}*/ -+ -+BridgedInstruction BridgedBuilder::createStrongRetain(BridgedValue op) const { -+ auto b = get(); -+ return {b.createStrongRetain(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; -+} -+ -+BridgedInstruction BridgedBuilder::createStrongRelease(BridgedValue op) const { -+ auto b = get(); -+ return {b.createStrongRelease(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; -+} -+ -+BridgedInstruction BridgedBuilder::createUnownedRetain(BridgedValue op) const { -+ auto b = get(); -+ return {b.createUnownedRetain(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; -+} -+ -+BridgedInstruction BridgedBuilder::createUnownedRelease(BridgedValue op) const { -+ auto b = get(); -+ return {b.createUnownedRelease(regularLoc(), op.getSILValue(), b.getDefaultAtomicity())}; -+} -+ -+BridgedInstruction BridgedBuilder::createFunctionRef(BridgedFunction function) const { -+ return {get().createFunctionRef(regularLoc(), function.getFunction())}; -+} -+ -+BridgedInstruction BridgedBuilder::createCopyValue(BridgedValue op) const { -+ return {get().createCopyValue(regularLoc(), op.getSILValue())}; -+} -+ -+BridgedInstruction BridgedBuilder::createBeginBorrow(BridgedValue op) const { -+ return {get().createBeginBorrow(regularLoc(), op.getSILValue())}; -+} -+ -+BridgedInstruction BridgedBuilder::createEndBorrow(BridgedValue op) const { -+ return {get().createEndBorrow(regularLoc(), op.getSILValue())}; -+} -+ -+BridgedInstruction BridgedBuilder::createCopyAddr(BridgedValue from, BridgedValue to, -+ bool takeSource, bool initializeDest) const { -+ return {get().createCopyAddr(regularLoc(), -+ from.getSILValue(), to.getSILValue(), -+ swift::IsTake_t(takeSource), -+ swift::IsInitialization_t(initializeDest))}; -+} -+ -+BridgedInstruction BridgedBuilder::createDestroyValue(BridgedValue op) const { -+ return {get().createDestroyValue(regularLoc(), op.getSILValue())}; -+} -+ -+BridgedInstruction BridgedBuilder::createDestroyAddr(BridgedValue op) const { -+ return {get().createDestroyAddr(regularLoc(), op.getSILValue())}; -+} -+ -+BridgedInstruction BridgedBuilder::createDebugStep() const { -+ return {get().createDebugStep(regularLoc())}; -+} -+ -+BridgedInstruction BridgedBuilder::createApply(BridgedValue function, BridgedSubstitutionMap subMap, -+ BridgedValueArray arguments, bool isNonThrowing, bool isNonAsync, -+ BridgedGenericSpecializationInformation specInfo) const { -+ llvm::SmallVector argValues; -+ swift::ApplyOptions applyOpts; -+ if (isNonThrowing) { applyOpts |= swift::ApplyFlags::DoesNotThrow; } -+ if (isNonAsync) { applyOpts |= swift::ApplyFlags::DoesNotAwait; } -+ -+ return {get().createApply(regularLoc(), -+ function.getSILValue(), subMap.get(), -+ arguments.getValues(argValues), -+ applyOpts, specInfo.data)}; -+} -+ -+BridgedInstruction BridgedBuilder::createSwitchEnumInst(BridgedValue enumVal, OptionalBridgedBasicBlock defaultBlock, -+ const void * _Nullable enumCases, SwiftInt numEnumCases) const { -+ using BridgedCase = const std::pair; -+ llvm::ArrayRef cases(static_cast(enumCases), -+ (unsigned)numEnumCases); -+ llvm::SmallDenseMap mappedElements; -+ swift::SILValue en = enumVal.getSILValue(); -+ swift::EnumDecl *enumDecl = en->getType().getEnumOrBoundGenericEnum(); -+ for (auto elemWithIndex : llvm::enumerate(enumDecl->getAllElements())) { -+ mappedElements[elemWithIndex.index()] = elemWithIndex.value(); -+ } -+ llvm::SmallVector, 16> convertedCases; -+ for (auto c : cases) { -+ assert(mappedElements.count(c.first) && "wrong enum element index"); -+ convertedCases.push_back({mappedElements[c.first], c.second.get()}); -+ } -+ return {get().createSwitchEnum(regularLoc(), -+ enumVal.getSILValue(), -+ defaultBlock.get(), convertedCases)}; -+} -+ -+BridgedInstruction BridgedBuilder::createUncheckedEnumData(BridgedValue enumVal, SwiftInt caseIdx, -+ BridgedType resultType) const { -+ swift::SILValue en = enumVal.getSILValue(); -+ return {get().createUncheckedEnumData(regularLoc(), enumVal.getSILValue(), -+ en->getType().getEnumElement(caseIdx), resultType.get())}; -+} -+ -+BridgedInstruction BridgedBuilder::createEnum(SwiftInt caseIdx, OptionalBridgedValue payload, -+ BridgedType resultType) const { -+ swift::EnumElementDecl *caseDecl = resultType.get().getEnumElement(caseIdx); -+ swift::SILValue pl = payload.getSILValue(); -+ return {get().createEnum(regularLoc(), pl, caseDecl, resultType.get())}; -+} -+ -+BridgedInstruction BridgedBuilder::createBranch(BridgedBasicBlock destBlock, BridgedValueArray arguments) const { -+ llvm::SmallVector argValues; -+ return {get().createBranch(regularLoc(), destBlock.get(), arguments.getValues(argValues))}; -+} -+ -+BridgedInstruction BridgedBuilder::createUnreachable() const { -+ return {get().createUnreachable(regularLoc())}; -+} -+ -+BridgedInstruction BridgedBuilder::createObject(BridgedType type, -+ BridgedValueArray arguments, -+ SwiftInt numBaseElements) const { -+ llvm::SmallVector argValues; -+ return {get().createObject(swift::ArtificialUnreachableLocation(), -+ type.get(), arguments.getValues(argValues), numBaseElements)}; -+} -+ -+BridgedInstruction BridgedBuilder::createGlobalAddr(BridgedGlobalVar global) const { -+ return {get().createGlobalAddr(regularLoc(), global.getGlobal())}; -+} -+ -+BridgedInstruction BridgedBuilder::createGlobalValue(BridgedGlobalVar global, bool isBare) const { -+ return {get().createGlobalValue(regularLoc(), global.getGlobal(), isBare)}; -+} -+ -+BridgedInstruction BridgedBuilder::createSetDeallocating(BridgedValue op, bool isAtomic) const { -+ return {get().createSetDeallocating(regularLoc(), -+ op.getSILValue(), -+ isAtomic ? swift::RefCountingInst::Atomicity::Atomic -+ : swift::RefCountingInst::Atomicity::NonAtomic)}; -+} -+ -+BridgedInstruction BridgedBuilder::createStruct(BridgedType type, BridgedValueArray elements) const { -+ llvm::SmallVector elementValues; -+ return {get().createStruct(regularLoc(), type.get(), elements.getValues(elementValues))}; -+} -+ -+BridgedInstruction BridgedBuilder::createStructExtract(BridgedValue str, SwiftInt fieldIndex) const { -+ swift::SILValue v = str.getSILValue(); -+ return {get().createStructExtract(regularLoc(), v, v->getType().getFieldDecl(fieldIndex))}; -+} -+ -+BridgedInstruction BridgedBuilder::createStructElementAddr(BridgedValue addr, SwiftInt fieldIndex) const { -+ swift::SILValue v = addr.getSILValue(); -+ return {get().createStructElementAddr(regularLoc(), v, v->getType().getFieldDecl(fieldIndex))}; -+} -+ -+BridgedInstruction BridgedBuilder::createDestructureStruct(BridgedValue str) const { -+ return {get().createDestructureStruct(regularLoc(), str.getSILValue())}; -+} -+ -+BridgedInstruction BridgedBuilder::createTuple(BridgedType type, BridgedValueArray elements) const { -+ llvm::SmallVector elementValues; -+ return {get().createTuple(regularLoc(), type.get(), elements.getValues(elementValues))}; -+} -+ -+BridgedInstruction BridgedBuilder::createTupleExtract(BridgedValue str, SwiftInt elementIndex) const { -+ swift::SILValue v = str.getSILValue(); -+ return {get().createTupleExtract(regularLoc(), v, elementIndex)}; -+} -+ -+BridgedInstruction BridgedBuilder::createTupleElementAddr(BridgedValue addr, SwiftInt elementIndex) const { -+ swift::SILValue v = addr.getSILValue(); -+ return {get().createTupleElementAddr(regularLoc(), v, elementIndex)}; -+} -+ -+BridgedInstruction BridgedBuilder::createDestructureTuple(BridgedValue str) const { -+ return {get().createDestructureTuple(regularLoc(), str.getSILValue())}; -+} -+ -+BridgedInstruction BridgedBuilder::createStore(BridgedValue src, BridgedValue dst, -+ SwiftInt ownership) const { -+ return {get().createStore(regularLoc(), src.getSILValue(), dst.getSILValue(), -+ (swift::StoreOwnershipQualifier)ownership)}; -+} -+ -+BridgedInstruction BridgedBuilder::createInitExistentialRef(BridgedValue instance, -+ BridgedType type, -+ BridgedInstruction useConformancesOf) const { -+ auto *src = useConformancesOf.getAs(); -+ return {get().createInitExistentialRef(regularLoc(), type.get(), -+ src->getFormalConcreteType(), -+ instance.getSILValue(), -+ src->getConformances())}; -+} -+ -+BridgedInstruction BridgedBuilder::createMetatype(BridgedType type, -+ BridgedType::MetatypeRepresentation representation) const { -+ auto *mt = swift::MetatypeType::get(type.get().getASTType(), (swift::MetatypeRepresentation)representation); -+ auto t = swift::SILType::getPrimitiveObjectType(swift::CanType(mt)); -+ return {get().createMetatype(regularLoc(), t)}; -+} -+ -+BridgedInstruction BridgedBuilder::createEndCOWMutation(BridgedValue instance, bool keepUnique) const { -+ return {get().createEndCOWMutation(regularLoc(), instance.getSILValue(), keepUnique)}; -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedNominalTypeDecl -+//===----------------------------------------------------------------------===// -+ -+BridgedStringRef BridgedNominalTypeDecl::getName() const { -+ return decl->getName().str(); -+} -+ -+bool BridgedNominalTypeDecl::isGlobalActor() const { return decl->isGlobalActor(); } -+ -+ -+SWIFT_END_NULLABILITY_ANNOTATIONS -+ -+#endif -diff --git a/swift/include/swift/SIL/SILLocation.h b/swift/include/swift/SIL/SILLocation.h -index 671eb25443d..1e18af386ed 100644 ---- a/swift/include/swift/SIL/SILLocation.h -+++ b/swift/include/swift/SIL/SILLocation.h -@@ -730,8 +730,6 @@ public: - bool isAutoGenerated() const { return location.isAutoGenerated(); } - operator bool() const { return bool(location) && debugScope; } - -- std::string getDebugDescription() const; -- - SWIFT_IMPORT_UNSAFE - SILDebugLocation getAutogeneratedLocation() const { - SILDebugLocation autoGenLoc(RegularLocation::getAutoGeneratedLocation(), getScope()); -diff --git a/swift/include/swift/SILOptimizer/OptimizerBridging.h b/swift/include/swift/SILOptimizer/OptimizerBridging.h -index 54312f2b204..ecb7b846263 100644 ---- a/swift/include/swift/SILOptimizer/OptimizerBridging.h -+++ b/swift/include/swift/SILOptimizer/OptimizerBridging.h -@@ -13,27 +13,52 @@ - #ifndef SWIFT_SILOPTIMIZER_OPTIMIZERBRIDGING_H - #define SWIFT_SILOPTIMIZER_OPTIMIZERBRIDGING_H - --#include "swift/Basic/Nullability.h" -+// Do not add other C++/llvm/swift header files here! -+// Function implementations should be placed into OptimizerBridgingImpl.h or PassManager.cpp -+// (under OptimizerBridging) andrequired header files should be added there. -+// - #include "swift/SIL/SILBridging.h" --#include "swift/SILOptimizer/Analysis/AliasAnalysis.h" -+ -+#ifdef USED_IN_CPP_SOURCE -+ - #include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h" --#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h" --#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h" --#include "swift/SILOptimizer/PassManager/PassManager.h" --#include "swift/SILOptimizer/Utils/InstOptUtils.h" -+ -+#else // USED_IN_CPP_SOURCE -+ -+#ifdef SWIFT_SIL_SILVALUE_H -+#error "should not include swift headers into bridging header" -+#endif -+#ifdef LLVM_SUPPORT_COMPILER_H -+#error "should not include llvm headers into bridging header" -+#endif -+ -+#endif // USED_IN_CPP_SOURCE - - SWIFT_BEGIN_NULLABILITY_ANNOTATIONS - -+namespace swift { -+class AliasAnalysis; -+class BasicCalleeAnalysis; -+class DeadEndBlocks; -+class DominanceInfo; -+class PostDominanceInfo; -+class BasicBlockSet; -+class NodeSet; -+class ClonerWithFixedLocation; -+class SwiftPassInvocation; -+class FixedSizeSlabPayload; -+class FixedSizeSlab; -+class SILVTable; -+} -+ - struct BridgedPassContext; - - struct BridgedAliasAnalysis { - swift::AliasAnalysis * _Nonnull aa; - -- swift::MemoryBehavior getMemBehavior(BridgedInstruction inst, BridgedValue addr) const { -- return aa->computeMemoryBehavior(inst.getInst(), addr.getSILValue()); -- } -+ BRIDGED_INLINE BridgedMemoryBehavior getMemBehavior(BridgedInstruction inst, BridgedValue addr) const; - -- typedef swift::MemoryBehavior (* _Nonnull GetMemEffectFn)( -+ typedef BridgedMemoryBehavior (* _Nonnull GetMemEffectFn)( - BridgedPassContext context, BridgedValue, BridgedInstruction, SwiftInt); - typedef bool (* _Nonnull Escaping2InstFn)( - BridgedPassContext context, BridgedValue, BridgedInstruction, SwiftInt); -@@ -51,19 +76,28 @@ struct BridgedAliasAnalysis { - struct BridgedCalleeAnalysis { - swift::BasicCalleeAnalysis * _Nonnull ca; - -- SWIFT_IMPORT_UNSAFE -- swift::CalleeList getCallees(BridgedValue callee) const; -+ struct CalleeList { -+ uint64_t storage[3]; - -- SWIFT_IMPORT_UNSAFE -- swift::CalleeList getDestructors(swift::SILType type, bool isExactType) const; -+#ifdef USED_IN_CPP_SOURCE -+ CalleeList(swift::CalleeList list) { -+ *reinterpret_cast(&storage) = list; -+ } -+ swift::CalleeList get() const { -+ return *reinterpret_cast(&storage); -+ } -+#endif - -- SWIFT_IMPORT_UNSAFE -- static BridgedFunction getCallee(swift::CalleeList cl, SwiftInt index) { -- return {cl.get(index)}; -- } -+ BRIDGED_INLINE bool isIncomplete() const; -+ BRIDGED_INLINE SwiftInt getCount() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getCallee(SwiftInt index) const; -+ }; -+ -+ SWIFT_IMPORT_UNSAFE CalleeList getCallees(BridgedValue callee) const; -+ SWIFT_IMPORT_UNSAFE CalleeList getDestructors(BridgedType type, bool isExactType) const; - - typedef bool (* _Nonnull IsDeinitBarrierFn)(BridgedInstruction, BridgedCalleeAnalysis bca); -- typedef swift::MemoryBehavior (* _Nonnull GetMemBehvaiorFn)( -+ typedef BridgedMemoryBehavior (* _Nonnull GetMemBehvaiorFn)( - BridgedInstruction apply, bool observeRetains, BridgedCalleeAnalysis bca); - - static void registerAnalysis(IsDeinitBarrierFn isDeinitBarrierFn, -@@ -73,231 +107,114 @@ struct BridgedCalleeAnalysis { - struct BridgedDeadEndBlocksAnalysis { - swift::DeadEndBlocks * _Nonnull deb; - -- bool isDeadEnd(BridgedBasicBlock block) const { -- return deb->isDeadEnd(block.getBlock()); -- } -+ BRIDGED_INLINE bool isDeadEnd(BridgedBasicBlock block) const; - }; - - struct BridgedDomTree { - swift::DominanceInfo * _Nonnull di; - -- bool dominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const { -- return di->dominates(dominating.getBlock(), dominated.getBlock()); -- } -+ BRIDGED_INLINE bool dominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const; - }; - --struct BridgedBasicBlockSet { -- swift::BasicBlockSet * _Nonnull set; -- -- bool contains(BridgedBasicBlock block) const { -- return set->contains(block.getBlock()); -- } -+struct BridgedPostDomTree { -+ swift::PostDominanceInfo * _Nonnull pdi; - -- bool insert(BridgedBasicBlock block) const { -- return set->insert(block.getBlock()); -- } -+ BRIDGED_INLINE bool postDominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const; -+}; - -- void erase(BridgedBasicBlock block) const { -- set->erase(block.getBlock()); -- } -+struct BridgedBasicBlockSet { -+ swift::BasicBlockSet * _Nonnull set; - -- SWIFT_IMPORT_UNSAFE -- BridgedFunction getFunction() const { -- return {set->getFunction()}; -- } -+ BRIDGED_INLINE bool contains(BridgedBasicBlock block) const; -+ BRIDGED_INLINE bool insert(BridgedBasicBlock block) const; -+ BRIDGED_INLINE void erase(BridgedBasicBlock block) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getFunction() const; - }; - - struct BridgedNodeSet { - swift::NodeSet * _Nonnull set; - -- bool containsValue(BridgedValue value) const { -- return set->contains(value.getSILValue()); -- } -- -- bool insertValue(BridgedValue value) const { -- return set->insert(value.getSILValue()); -- } -- -- void eraseValue(BridgedValue value) const { -- set->erase(value.getSILValue()); -- } -- -- bool containsInstruction(BridgedInstruction inst) const { -- return set->contains(inst.getInst()->asSILNode()); -- } -- -- bool insertInstruction(BridgedInstruction inst) const { -- return set->insert(inst.getInst()->asSILNode()); -- } -- -- void eraseInstruction(BridgedInstruction inst) const { -- set->erase(inst.getInst()->asSILNode()); -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedFunction getFunction() const { -- return {set->getFunction()}; -- } -+ BRIDGED_INLINE bool containsValue(BridgedValue value) const; -+ BRIDGED_INLINE bool insertValue(BridgedValue value) const; -+ BRIDGED_INLINE void eraseValue(BridgedValue value) const; -+ BRIDGED_INLINE bool containsInstruction(BridgedInstruction inst) const; -+ BRIDGED_INLINE bool insertInstruction(BridgedInstruction inst) const; -+ BRIDGED_INLINE void eraseInstruction(BridgedInstruction inst) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedFunction getFunction() const; - }; - --namespace swift { --class ClonerWithFixedLocation; --} -- - struct BridgedCloner { - swift::ClonerWithFixedLocation * _Nonnull cloner; - - BridgedCloner(BridgedGlobalVar var, BridgedPassContext context); -- - BridgedCloner(BridgedInstruction inst, BridgedPassContext context); -- - void destroy(BridgedPassContext context); -- -- SWIFT_IMPORT_UNSAFE -- BridgedValue getClonedValue(BridgedValue v); -- -+ SWIFT_IMPORT_UNSAFE BridgedValue getClonedValue(BridgedValue v); - bool isValueCloned(BridgedValue v) const; -- - void clone(BridgedInstruction inst); - }; - --struct BridgedPostDomTree { -- swift::PostDominanceInfo * _Nonnull pdi; -- -- bool postDominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const { -- return pdi->dominates(dominating.getBlock(), dominated.getBlock()); -- } --}; -- - struct BridgedPassContext { - swift::SwiftPassInvocation * _Nonnull invocation; - -- std::string getModuleDescription() const; -+ enum class SILStage { -+ Raw, -+ Canonical, -+ Lowered -+ }; -+ -+ SWIFT_IMPORT_UNSAFE BridgedOwnedString getModuleDescription() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedChangeNotificationHandler asNotificationHandler() const; - -- SWIFT_IMPORT_UNSAFE -- BridgedChangeNotificationHandler asNotificationHandler() const { -- return {invocation}; -- } - // Analysis - -- SWIFT_IMPORT_UNSAFE -- BridgedAliasAnalysis getAliasAnalysis() const { -- return {invocation->getPassManager()->getAnalysis(invocation->getFunction())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedCalleeAnalysis getCalleeAnalysis() const { -- return {invocation->getPassManager()->getAnalysis()}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedDeadEndBlocksAnalysis getDeadEndBlocksAnalysis() const { -- auto *dba = invocation->getPassManager()->getAnalysis(); -- return {dba->get(invocation->getFunction())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedDomTree getDomTree() const { -- auto *da = invocation->getPassManager()->getAnalysis(); -- return {da->get(invocation->getFunction())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedPostDomTree getPostDomTree() const { -- auto *pda = invocation->getPassManager()->getAnalysis(); -- return {pda->get(invocation->getFunction())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedNominalTypeDecl getSwiftArrayDecl() const { -- swift::SILModule *mod = invocation->getPassManager()->getModule(); -- return {mod->getASTContext().getArrayDecl()}; -- } -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedAliasAnalysis getAliasAnalysis() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedCalleeAnalysis getCalleeAnalysis() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDeadEndBlocksAnalysis getDeadEndBlocksAnalysis() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedDomTree getDomTree() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedPostDomTree getPostDomTree() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedNominalTypeDecl getSwiftArrayDecl() const; - - // SIL modifications - -- SWIFT_IMPORT_UNSAFE -- BridgedBasicBlock splitBlock(BridgedInstruction bridgedInst) const { -- auto *inst = bridgedInst.getInst(); -- auto *block = inst->getParent(); -- return {block->split(inst->getIterator())}; -- } -- -- void eraseInstruction(BridgedInstruction inst) const { -- invocation->eraseInstruction(inst.getInst()); -- } -- -- void eraseBlock(BridgedBasicBlock block) const { -- block.getBlock()->eraseFromParent(); -- } -- -- bool tryOptimizeApplyOfPartialApply(BridgedInstruction closure) const; -- -- bool tryDeleteDeadClosure(BridgedInstruction closure, bool needKeepArgsAlive) const; -- - struct DevirtResult { - OptionalBridgedInstruction newApply; - bool cfgChanged; - }; - -- SWIFT_IMPORT_UNSAFE -- DevirtResult tryDevirtualizeApply(BridgedInstruction apply, bool isMandatory) const; -- -- SWIFT_IMPORT_UNSAFE -- OptionalBridgedValue constantFoldBuiltin(BridgedInstruction builtin) const; -- -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlock splitBlock(BridgedInstruction bridgedInst) const; -+ BRIDGED_INLINE void eraseInstruction(BridgedInstruction inst) const; -+ BRIDGED_INLINE void eraseBlock(BridgedBasicBlock block) const; -+ bool tryOptimizeApplyOfPartialApply(BridgedInstruction closure) const; -+ bool tryDeleteDeadClosure(BridgedInstruction closure, bool needKeepArgsAlive) const; -+ SWIFT_IMPORT_UNSAFE DevirtResult tryDevirtualizeApply(BridgedInstruction apply, bool isMandatory) const; -+ SWIFT_IMPORT_UNSAFE OptionalBridgedValue constantFoldBuiltin(BridgedInstruction builtin) const; - bool specializeAppliesInFunction(BridgedFunction function, bool isMandatory) const; -- -- std::string mangleOutlinedVariable(BridgedFunction function) const; -- -- SWIFT_IMPORT_UNSAFE -- BridgedGlobalVar createGlobalVariable(llvm::StringRef name, swift::SILType type, bool isPrivate) const; -- -+ SWIFT_IMPORT_UNSAFE BridgedOwnedString mangleOutlinedVariable(BridgedFunction function) const; -+ SWIFT_IMPORT_UNSAFE BridgedGlobalVar createGlobalVariable(BridgedStringRef name, BridgedType type, -+ bool isPrivate) const; - void inlineFunction(BridgedInstruction apply, bool mandatoryInline) const; -- -- SWIFT_IMPORT_UNSAFE -- BridgedValue getSILUndef(swift::SILType type) const { -- return {swift::SILUndef::get(type, *invocation->getFunction())}; -- } -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedValue getSILUndef(BridgedType type) const; -+ BRIDGED_INLINE static bool optimizeMemoryAccesses(BridgedFunction f); -+ BRIDGED_INLINE static bool eliminateDeadAllocations(BridgedFunction f); - - // IRGen - -- SwiftInt getStaticSize(swift::SILType type) const; -- -- SwiftInt getStaticAlignment(swift::SILType type) const; -- -- SwiftInt getStaticStride(swift::SILType type) const; -+ SwiftInt getStaticSize(BridgedType type) const; -+ SwiftInt getStaticAlignment(BridgedType type) const; -+ SwiftInt getStaticStride(BridgedType type) const; - - // Sets - -- SWIFT_IMPORT_UNSAFE -- BridgedBasicBlockSet allocBasicBlockSet() const { -- return {invocation->allocBlockSet()}; -- } -- -- void freeBasicBlockSet(BridgedBasicBlockSet set) const { -- invocation->freeBlockSet(set.set); -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedNodeSet allocNodeSet() const { -- return {invocation->allocNodeSet()}; -- } -- -- void freeNodeSet(BridgedNodeSet set) const { -- invocation->freeNodeSet(set.set); -- } -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedBasicBlockSet allocBasicBlockSet() const; -+ BRIDGED_INLINE void freeBasicBlockSet(BridgedBasicBlockSet set) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedNodeSet allocNodeSet() const; -+ BRIDGED_INLINE void freeNodeSet(BridgedNodeSet set) const; - - // Stack nesting - -- void notifyInvalidatedStackNesting() const { -- invocation->setNeedFixStackNesting(true); -- } -- -- bool getNeedFixStackNesting() const { -- return invocation->getNeedFixStackNesting(); -- } -- -+ BRIDGED_INLINE void notifyInvalidatedStackNesting() const; -+ BRIDGED_INLINE bool getNeedFixStackNesting() const; - void fixStackNesting(BridgedFunction function) const; - - // Slabs -@@ -305,216 +222,65 @@ struct BridgedPassContext { - struct Slab { - swift::FixedSizeSlabPayload * _Nullable data = nullptr; - -- static SwiftInt getCapacity() { -- return (SwiftInt)swift::FixedSizeSlabPayload::capacity; -- } -- -- Slab(swift::FixedSizeSlab * _Nullable slab) { -- if (slab) { -- data = slab; -- assert((void *)data == slab->dataFor()); -- } -- } -- -- swift::FixedSizeSlab * _Nullable getSlab() const { -- if (data) -- return static_cast(data); -- return nullptr; -- } -- -- SWIFT_IMPORT_UNSAFE -- Slab getNext() const { -- return &*std::next(getSlab()->getIterator()); -- } -- -- SWIFT_IMPORT_UNSAFE -- Slab getPrevious() const { -- return &*std::prev(getSlab()->getIterator()); -- } -+ BRIDGED_INLINE static SwiftInt getCapacity(); -+ BRIDGED_INLINE Slab(swift::FixedSizeSlab * _Nullable slab); -+ BRIDGED_INLINE swift::FixedSizeSlab * _Nullable getSlab() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE Slab getNext() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE Slab getPrevious() const; - }; - -- SWIFT_IMPORT_UNSAFE -- Slab allocSlab(Slab afterSlab) const { -- return invocation->allocSlab(afterSlab.getSlab()); -- } -- -- SWIFT_IMPORT_UNSAFE -- Slab freeSlab(Slab slab) const { -- return invocation->freeSlab(slab.getSlab()); -- } -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE Slab allocSlab(Slab afterSlab) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE Slab freeSlab(Slab slab) const; - - // Access SIL module data structures - -- SWIFT_IMPORT_UNSAFE -- OptionalBridgedFunction getFirstFunctionInModule() const { -- swift::SILModule *mod = invocation->getPassManager()->getModule(); -- if (mod->getFunctions().empty()) -- return {nullptr}; -- return {&*mod->getFunctions().begin()}; -- } -- -- SWIFT_IMPORT_UNSAFE -- static OptionalBridgedFunction getNextFunctionInModule(BridgedFunction function) { -- auto *f = function.getFunction(); -- auto nextIter = std::next(f->getIterator()); -- if (nextIter == f->getModule().getFunctions().end()) -- return {nullptr}; -- return {&*nextIter}; -- } -- -- SWIFT_IMPORT_UNSAFE -- OptionalBridgedGlobalVar getFirstGlobalInModule() const { -- swift::SILModule *mod = invocation->getPassManager()->getModule(); -- if (mod->getSILGlobals().empty()) -- return {nullptr}; -- return {&*mod->getSILGlobals().begin()}; -- } -- -- SWIFT_IMPORT_UNSAFE -- static OptionalBridgedGlobalVar getNextGlobalInModule(BridgedGlobalVar global) { -- auto *g = global.getGlobal(); -- auto nextIter = std::next(g->getIterator()); -- if (nextIter == g->getModule().getSILGlobals().end()) -- return {nullptr}; -- return {&*nextIter}; -- } -- - struct VTableArray { - swift::SILVTable * const _Nonnull * _Nullable base; - SwiftInt count; - }; - -- SWIFT_IMPORT_UNSAFE -- VTableArray getVTables() const { -- swift::SILModule *mod = invocation->getPassManager()->getModule(); -- auto vTables = mod->getVTables(); -- return {vTables.data(), (SwiftInt)vTables.size()}; -- } -- -- SWIFT_IMPORT_UNSAFE -- OptionalBridgedWitnessTable getFirstWitnessTableInModule() const { -- swift::SILModule *mod = invocation->getPassManager()->getModule(); -- if (mod->getWitnessTables().empty()) -- return {nullptr}; -- return {&*mod->getWitnessTables().begin()}; -- } -- -- SWIFT_IMPORT_UNSAFE -- static OptionalBridgedWitnessTable getNextWitnessTableInModule(BridgedWitnessTable table) { -- auto *t = table.table; -- auto nextIter = std::next(t->getIterator()); -- if (nextIter == t->getModule().getWitnessTables().end()) -- return {nullptr}; -- return {&*nextIter}; -- } -- -- SWIFT_IMPORT_UNSAFE -- OptionalBridgedDefaultWitnessTable getFirstDefaultWitnessTableInModule() const { -- swift::SILModule *mod = invocation->getPassManager()->getModule(); -- if (mod->getDefaultWitnessTables().empty()) -- return {nullptr}; -- return {&*mod->getDefaultWitnessTables().begin()}; -- } -- -- SWIFT_IMPORT_UNSAFE -- static OptionalBridgedDefaultWitnessTable getNextDefaultWitnessTableInModule(BridgedDefaultWitnessTable table) { -- auto *t = table.table; -- auto nextIter = std::next(t->getIterator()); -- if (nextIter == t->getModule().getDefaultWitnessTables().end()) -- return {nullptr}; -- return {&*nextIter}; -- } -- -- SWIFT_IMPORT_UNSAFE -- OptionalBridgedFunction loadFunction(llvm::StringRef name, bool loadCalleesRecursively) const { -- swift::SILModule *mod = invocation->getPassManager()->getModule(); -- return {mod->loadFunction(name, loadCalleesRecursively ? swift::SILModule::LinkingMode::LinkAll -- : swift::SILModule::LinkingMode::LinkNormal)}; -- } -- -- SWIFT_IMPORT_UNSAFE -- void loadFunction(BridgedFunction function, bool loadCalleesRecursively) const { -- swift::SILModule *mod = invocation->getPassManager()->getModule(); -- mod->loadFunction(function.getFunction(), -- loadCalleesRecursively ? swift::SILModule::LinkingMode::LinkAll -- : swift::SILModule::LinkingMode::LinkNormal); -- } -- -- SWIFT_IMPORT_UNSAFE -- OptionalBridgedFunction lookupStdlibFunction(llvm::StringRef name) const; -- -- SWIFT_IMPORT_UNSAFE -- swift::SubstitutionMap getContextSubstitutionMap(swift::SILType type) const { -- auto *ntd = type.getASTType()->getAnyNominal(); -- auto *mod = invocation->getPassManager()->getModule()->getSwiftModule(); -- return type.getASTType()->getContextSubstitutionMap(mod, ntd); -- } -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedFunction getFirstFunctionInModule() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedFunction getNextFunctionInModule(BridgedFunction function); -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedGlobalVar getFirstGlobalInModule() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedGlobalVar getNextGlobalInModule(BridgedGlobalVar global); -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE VTableArray getVTables() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedWitnessTable getFirstWitnessTableInModule() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedWitnessTable getNextWitnessTableInModule( -+ BridgedWitnessTable table); -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedDefaultWitnessTable getFirstDefaultWitnessTableInModule() const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE static OptionalBridgedDefaultWitnessTable getNextDefaultWitnessTableInModule( -+ BridgedDefaultWitnessTable table); -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE OptionalBridgedFunction loadFunction(BridgedStringRef name, -+ bool loadCalleesRecursively) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE void loadFunction(BridgedFunction function, bool loadCalleesRecursively) const; -+ SWIFT_IMPORT_UNSAFE OptionalBridgedFunction lookupStdlibFunction(BridgedStringRef name) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedSubstitutionMap getContextSubstitutionMap(BridgedType type) const; - - // Passmanager housekeeping - -- void beginTransformFunction(BridgedFunction function) const { -- invocation->beginTransformFunction(function.getFunction()); -- } -- -- void endTransformFunction() const { -- invocation->endTransformFunction(); -- } -- -- bool continueWithNextSubpassRun(OptionalBridgedInstruction inst) const { -- swift::SILPassManager *pm = invocation->getPassManager(); -- return pm->continueWithNextSubpassRun(inst.getInst(), -- invocation->getFunction(), -- invocation->getTransform()); -- } -+ BRIDGED_INLINE void beginTransformFunction(BridgedFunction function) const; -+ BRIDGED_INLINE void endTransformFunction() const; -+ BRIDGED_INLINE bool continueWithNextSubpassRun(OptionalBridgedInstruction inst) const; - - // SSAUpdater - -- void SSAUpdater_initialize(swift::SILType type, BridgedValue::Ownership ownership) const { -- invocation->initializeSSAUpdater(type, castToOwnership(ownership)); -- } -- -- void SSAUpdater_addAvailableValue(BridgedBasicBlock block, BridgedValue value) const { -- invocation->getSSAUpdater()->addAvailableValue(block.getBlock(), value.getSILValue()); -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedValue SSAUpdater_getValueAtEndOfBlock(BridgedBasicBlock block) const { -- return {invocation->getSSAUpdater()->getValueAtEndOfBlock(block.getBlock())}; -- } -- -- SWIFT_IMPORT_UNSAFE -- BridgedValue SSAUpdater_getValueInMiddleOfBlock(BridgedBasicBlock block) const { -- return {invocation->getSSAUpdater()->getValueInMiddleOfBlock(block.getBlock())}; -- } -+ BRIDGED_INLINE void SSAUpdater_initialize(BridgedType type, BridgedValue::Ownership ownership) const; -+ BRIDGED_INLINE void SSAUpdater_addAvailableValue(BridgedBasicBlock block, BridgedValue value) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedValue SSAUpdater_getValueAtEndOfBlock(BridgedBasicBlock block) const; -+ SWIFT_IMPORT_UNSAFE BRIDGED_INLINE BridgedValue SSAUpdater_getValueInMiddleOfBlock(BridgedBasicBlock block) const; - - // Options - -- bool enableStackProtection() const { -- swift::SILModule *mod = invocation->getPassManager()->getModule(); -- return mod->getOptions().EnableStackProtection; -- } -- -- bool enableEmbeddedSwift() const { -- swift::SILModule *mod = invocation->getPassManager()->getModule(); -- return mod->getASTContext().LangOpts.hasFeature(swift::Feature::Embedded); -- } -- -- bool enableMoveInoutStackProtection() const { -- swift::SILModule *mod = invocation->getPassManager()->getModule(); -- return mod->getOptions().EnableMoveInoutStackProtection; -- } -- - enum class AssertConfiguration { -- Debug = swift::SILOptions::Debug, -- Release = swift::SILOptions::Release, -- Unchecked = swift::SILOptions::Unchecked -+ Debug = 0, -+ Release = 1, -+ Unchecked = 2 - }; - -- AssertConfiguration getAssertConfiguration() const { -- swift::SILModule *mod = invocation->getPassManager()->getModule(); -- return (AssertConfiguration)mod->getOptions().AssertConfig; -- } -- -+ BRIDGED_INLINE bool enableStackProtection() const; -+ BRIDGED_INLINE bool enableEmbeddedSwift() const; -+ BRIDGED_INLINE bool enableMoveInoutStackProtection() const; -+ BRIDGED_INLINE AssertConfiguration getAssertConfiguration() const; - bool enableSimplificationFor(BridgedInstruction inst) const; - }; - -@@ -538,13 +304,18 @@ typedef void (* _Nonnull BridgedModulePassRunFn)(BridgedPassContext); - typedef void (* _Nonnull BridgedFunctionPassRunFn)(BridgedFunctionPassCtxt); - typedef void (* _Nonnull BridgedInstructionPassRunFn)(BridgedInstructionPassCtxt); - --void SILPassManager_registerModulePass(llvm::StringRef name, -+void SILPassManager_registerModulePass(BridgedStringRef name, - BridgedModulePassRunFn runFn); --void SILPassManager_registerFunctionPass(llvm::StringRef name, -+void SILPassManager_registerFunctionPass(BridgedStringRef name, - BridgedFunctionPassRunFn runFn); --void SILCombine_registerInstructionPass(llvm::StringRef instClassName, -+void SILCombine_registerInstructionPass(BridgedStringRef instClassName, - BridgedInstructionPassRunFn runFn); - -+#ifndef PURE_BRIDGING_MODE -+// In _not_ PURE_BRIDGING_MODE, briding functions are inlined and therefore inluded in the header file. -+#include "OptimizerBridgingImpl.h" -+#endif -+ - SWIFT_END_NULLABILITY_ANNOTATIONS - - #endif -diff --git a/swift/include/swift/SILOptimizer/OptimizerBridgingImpl.h b/swift/include/swift/SILOptimizer/OptimizerBridgingImpl.h -new file mode 100644 -index 00000000000..798efc6ec57 ---- /dev/null -+++ b/swift/include/swift/SILOptimizer/OptimizerBridgingImpl.h -@@ -0,0 +1,397 @@ -+//===--- OptimizerBridgingImpl.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 contains the implementation of bridging functions, which are either -+// - depending on if PURE_BRIDGING_MODE is set - included in the cpp file or -+// in the header file. -+// -+//===----------------------------------------------------------------------===// -+ -+#ifndef SWIFT_SILOPTIMIZER_OPTIMIZERBRIDGING_IMPL_H -+#define SWIFT_SILOPTIMIZER_OPTIMIZERBRIDGING_IMPL_H -+ -+#include "swift/SILOptimizer/OptimizerBridging.h" -+#include "swift/SILOptimizer/Analysis/AliasAnalysis.h" -+#include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h" -+#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h" -+#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h" -+#include "swift/SILOptimizer/PassManager/PassManager.h" -+#include "swift/SILOptimizer/Utils/InstOptUtils.h" -+ -+SWIFT_BEGIN_NULLABILITY_ANNOTATIONS -+ -+//===----------------------------------------------------------------------===// -+// BridgedAliasAnalysis -+//===----------------------------------------------------------------------===// -+ -+BridgedMemoryBehavior BridgedAliasAnalysis::getMemBehavior(BridgedInstruction inst, BridgedValue addr) const { -+ return (BridgedMemoryBehavior)aa->computeMemoryBehavior(inst.get(), addr.getSILValue()); -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedCalleeAnalysis -+//===----------------------------------------------------------------------===// -+ -+static_assert(sizeof(BridgedCalleeAnalysis::CalleeList) >= sizeof(swift::CalleeList), -+ "BridgedCalleeAnalysis::CalleeList has wrong size"); -+ -+bool BridgedCalleeAnalysis::CalleeList::isIncomplete() const { -+ return get().isIncomplete(); -+} -+ -+SwiftInt BridgedCalleeAnalysis::CalleeList::getCount() const { -+ return get().getCount(); -+} -+ -+BridgedFunction BridgedCalleeAnalysis::CalleeList::getCallee(SwiftInt index) const { -+ return {get().get((unsigned)index)}; -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedDeadEndBlocksAnalysis -+//===----------------------------------------------------------------------===// -+ -+bool BridgedDeadEndBlocksAnalysis::isDeadEnd(BridgedBasicBlock block) const { -+ return deb->isDeadEnd(block.get()); -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedDomTree, BridgedPostDomTree -+//===----------------------------------------------------------------------===// -+ -+bool BridgedDomTree::dominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const { -+ return di->dominates(dominating.get(), dominated.get()); -+} -+ -+bool BridgedPostDomTree::postDominates(BridgedBasicBlock dominating, BridgedBasicBlock dominated) const { -+ return pdi->dominates(dominating.get(), dominated.get()); -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedBasicBlockSet -+//===----------------------------------------------------------------------===// -+ -+bool BridgedBasicBlockSet::contains(BridgedBasicBlock block) const { -+ return set->contains(block.get()); -+} -+ -+bool BridgedBasicBlockSet::insert(BridgedBasicBlock block) const { -+ return set->insert(block.get()); -+} -+ -+void BridgedBasicBlockSet::erase(BridgedBasicBlock block) const { -+ set->erase(block.get()); -+} -+ -+BridgedFunction BridgedBasicBlockSet::getFunction() const { -+ return {set->getFunction()}; -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedNodeSet -+//===----------------------------------------------------------------------===// -+ -+bool BridgedNodeSet::containsValue(BridgedValue value) const { -+ return set->contains(value.getSILValue()); -+} -+ -+bool BridgedNodeSet::insertValue(BridgedValue value) const { -+ return set->insert(value.getSILValue()); -+} -+ -+void BridgedNodeSet::eraseValue(BridgedValue value) const { -+ set->erase(value.getSILValue()); -+} -+ -+bool BridgedNodeSet::containsInstruction(BridgedInstruction inst) const { -+ return set->contains(inst.get()->asSILNode()); -+} -+ -+bool BridgedNodeSet::insertInstruction(BridgedInstruction inst) const { -+ return set->insert(inst.get()->asSILNode()); -+} -+ -+void BridgedNodeSet::eraseInstruction(BridgedInstruction inst) const { -+ set->erase(inst.get()->asSILNode()); -+} -+ -+BridgedFunction BridgedNodeSet::getFunction() const { -+ return {set->getFunction()}; -+} -+ -+//===----------------------------------------------------------------------===// -+// BridgedPassContext -+//===----------------------------------------------------------------------===// -+ -+BridgedChangeNotificationHandler BridgedPassContext::asNotificationHandler() const { -+ return {invocation}; -+} -+ -+BridgedAliasAnalysis BridgedPassContext::getAliasAnalysis() const { -+ return {invocation->getPassManager()->getAnalysis(invocation->getFunction())}; -+} -+ -+BridgedCalleeAnalysis BridgedPassContext::getCalleeAnalysis() const { -+ return {invocation->getPassManager()->getAnalysis()}; -+} -+ -+BridgedDeadEndBlocksAnalysis BridgedPassContext::getDeadEndBlocksAnalysis() const { -+ auto *dba = invocation->getPassManager()->getAnalysis(); -+ return {dba->get(invocation->getFunction())}; -+} -+ -+BridgedDomTree BridgedPassContext::getDomTree() const { -+ auto *da = invocation->getPassManager()->getAnalysis(); -+ return {da->get(invocation->getFunction())}; -+} -+ -+BridgedPostDomTree BridgedPassContext::getPostDomTree() const { -+ auto *pda = invocation->getPassManager()->getAnalysis(); -+ return {pda->get(invocation->getFunction())}; -+} -+ -+BridgedNominalTypeDecl BridgedPassContext::getSwiftArrayDecl() const { -+ swift::SILModule *mod = invocation->getPassManager()->getModule(); -+ return {mod->getASTContext().getArrayDecl()}; -+} -+ -+// SIL modifications -+ -+BridgedBasicBlock BridgedPassContext::splitBlock(BridgedInstruction bridgedInst) const { -+ auto *block = bridgedInst.get()->getParent(); -+ return {block->split(bridgedInst.get()->getIterator())}; -+} -+ -+void BridgedPassContext::eraseInstruction(BridgedInstruction inst) const { -+ invocation->eraseInstruction(inst.get()); -+} -+ -+void BridgedPassContext::eraseBlock(BridgedBasicBlock block) const { -+ block.get()->eraseFromParent(); -+} -+ -+BridgedValue BridgedPassContext::getSILUndef(BridgedType type) const { -+ return {swift::SILUndef::get(type.get(), *invocation->getFunction())}; -+} -+ -+bool BridgedPassContext::optimizeMemoryAccesses(BridgedFunction f) { -+ return swift::optimizeMemoryAccesses(f.getFunction()); -+} -+bool BridgedPassContext::eliminateDeadAllocations(BridgedFunction f) { -+ return swift::eliminateDeadAllocations(f.getFunction()); -+} -+ -+BridgedBasicBlockSet BridgedPassContext::allocBasicBlockSet() const { -+ return {invocation->allocBlockSet()}; -+} -+ -+void BridgedPassContext::freeBasicBlockSet(BridgedBasicBlockSet set) const { -+ invocation->freeBlockSet(set.set); -+} -+ -+BridgedNodeSet BridgedPassContext::allocNodeSet() const { -+ return {invocation->allocNodeSet()}; -+} -+ -+void BridgedPassContext::freeNodeSet(BridgedNodeSet set) const { -+ invocation->freeNodeSet(set.set); -+} -+ -+void BridgedPassContext::notifyInvalidatedStackNesting() const { -+ invocation->setNeedFixStackNesting(true); -+} -+ -+bool BridgedPassContext::getNeedFixStackNesting() const { -+ return invocation->getNeedFixStackNesting(); -+} -+ -+SwiftInt BridgedPassContext::Slab::getCapacity() { -+ return (SwiftInt)swift::FixedSizeSlabPayload::capacity; -+} -+ -+BridgedPassContext::Slab::Slab(swift::FixedSizeSlab * _Nullable slab) { -+ if (slab) { -+ data = slab; -+ assert((void *)data == slab->dataFor()); -+ } -+} -+ -+swift::FixedSizeSlab * _Nullable BridgedPassContext::Slab::getSlab() const { -+ if (data) -+ return static_cast(data); -+ return nullptr; -+} -+ -+BridgedPassContext::Slab BridgedPassContext::Slab::getNext() const { -+ return &*std::next(getSlab()->getIterator()); -+} -+ -+BridgedPassContext::Slab BridgedPassContext::Slab::getPrevious() const { -+ return &*std::prev(getSlab()->getIterator()); -+} -+ -+BridgedPassContext::Slab BridgedPassContext::allocSlab(Slab afterSlab) const { -+ return invocation->allocSlab(afterSlab.getSlab()); -+} -+ -+BridgedPassContext::Slab BridgedPassContext::freeSlab(Slab slab) const { -+ return invocation->freeSlab(slab.getSlab()); -+} -+ -+OptionalBridgedFunction BridgedPassContext::getFirstFunctionInModule() const { -+ swift::SILModule *mod = invocation->getPassManager()->getModule(); -+ if (mod->getFunctions().empty()) -+ return {nullptr}; -+ return {&*mod->getFunctions().begin()}; -+} -+ -+OptionalBridgedFunction BridgedPassContext::getNextFunctionInModule(BridgedFunction function) { -+ auto *f = function.getFunction(); -+ auto nextIter = std::next(f->getIterator()); -+ if (nextIter == f->getModule().getFunctions().end()) -+ return {nullptr}; -+ return {&*nextIter}; -+} -+ -+OptionalBridgedGlobalVar BridgedPassContext::getFirstGlobalInModule() const { -+ swift::SILModule *mod = invocation->getPassManager()->getModule(); -+ if (mod->getSILGlobals().empty()) -+ return {nullptr}; -+ return {&*mod->getSILGlobals().begin()}; -+} -+ -+OptionalBridgedGlobalVar BridgedPassContext::getNextGlobalInModule(BridgedGlobalVar global) { -+ auto *g = global.getGlobal(); -+ auto nextIter = std::next(g->getIterator()); -+ if (nextIter == g->getModule().getSILGlobals().end()) -+ return {nullptr}; -+ return {&*nextIter}; -+} -+ -+BridgedPassContext::VTableArray BridgedPassContext::getVTables() const { -+ swift::SILModule *mod = invocation->getPassManager()->getModule(); -+ auto vTables = mod->getVTables(); -+ return {vTables.data(), (SwiftInt)vTables.size()}; -+} -+ -+OptionalBridgedWitnessTable BridgedPassContext::getFirstWitnessTableInModule() const { -+ swift::SILModule *mod = invocation->getPassManager()->getModule(); -+ if (mod->getWitnessTables().empty()) -+ return {nullptr}; -+ return {&*mod->getWitnessTables().begin()}; -+} -+ -+OptionalBridgedWitnessTable BridgedPassContext::getNextWitnessTableInModule(BridgedWitnessTable table) { -+ auto *t = table.table; -+ auto nextIter = std::next(t->getIterator()); -+ if (nextIter == t->getModule().getWitnessTables().end()) -+ return {nullptr}; -+ return {&*nextIter}; -+} -+ -+OptionalBridgedDefaultWitnessTable BridgedPassContext::getFirstDefaultWitnessTableInModule() const { -+ swift::SILModule *mod = invocation->getPassManager()->getModule(); -+ if (mod->getDefaultWitnessTables().empty()) -+ return {nullptr}; -+ return {&*mod->getDefaultWitnessTables().begin()}; -+} -+ -+OptionalBridgedDefaultWitnessTable BridgedPassContext:: -+getNextDefaultWitnessTableInModule(BridgedDefaultWitnessTable table) { -+ auto *t = table.table; -+ auto nextIter = std::next(t->getIterator()); -+ if (nextIter == t->getModule().getDefaultWitnessTables().end()) -+ return {nullptr}; -+ return {&*nextIter}; -+} -+ -+OptionalBridgedFunction BridgedPassContext::loadFunction(BridgedStringRef name, bool loadCalleesRecursively) const { -+ swift::SILModule *mod = invocation->getPassManager()->getModule(); -+ return {mod->loadFunction(name.get(), -+ loadCalleesRecursively ? swift::SILModule::LinkingMode::LinkAll -+ : swift::SILModule::LinkingMode::LinkNormal)}; -+} -+ -+void BridgedPassContext::loadFunction(BridgedFunction function, bool loadCalleesRecursively) const { -+ swift::SILModule *mod = invocation->getPassManager()->getModule(); -+ mod->loadFunction(function.getFunction(), -+ loadCalleesRecursively ? swift::SILModule::LinkingMode::LinkAll -+ : swift::SILModule::LinkingMode::LinkNormal); -+} -+ -+BridgedSubstitutionMap BridgedPassContext::getContextSubstitutionMap(BridgedType type) const { -+ swift::SILType ty = type.get(); -+ auto *ntd = ty.getASTType()->getAnyNominal(); -+ auto *mod = invocation->getPassManager()->getModule()->getSwiftModule(); -+ return ty.getASTType()->getContextSubstitutionMap(mod, ntd); -+} -+ -+void BridgedPassContext::beginTransformFunction(BridgedFunction function) const { -+ invocation->beginTransformFunction(function.getFunction()); -+} -+ -+void BridgedPassContext::endTransformFunction() const { -+ invocation->endTransformFunction(); -+} -+ -+bool BridgedPassContext::continueWithNextSubpassRun(OptionalBridgedInstruction inst) const { -+ swift::SILPassManager *pm = invocation->getPassManager(); -+ return pm->continueWithNextSubpassRun(inst.get(), invocation->getFunction(), invocation->getTransform()); -+} -+ -+void BridgedPassContext::SSAUpdater_initialize(BridgedType type, BridgedValue::Ownership ownership) const { -+ invocation->initializeSSAUpdater(type.get(), BridgedValue::castToOwnership(ownership)); -+} -+ -+void BridgedPassContext::SSAUpdater_addAvailableValue(BridgedBasicBlock block, BridgedValue value) const { -+ invocation->getSSAUpdater()->addAvailableValue(block.get(), value.getSILValue()); -+} -+ -+BridgedValue BridgedPassContext::SSAUpdater_getValueAtEndOfBlock(BridgedBasicBlock block) const { -+ return {invocation->getSSAUpdater()->getValueAtEndOfBlock(block.get())}; -+} -+ -+BridgedValue BridgedPassContext::SSAUpdater_getValueInMiddleOfBlock(BridgedBasicBlock block) const { -+ return {invocation->getSSAUpdater()->getValueInMiddleOfBlock(block.get())}; -+} -+ -+bool BridgedPassContext::enableStackProtection() const { -+ swift::SILModule *mod = invocation->getPassManager()->getModule(); -+ return mod->getOptions().EnableStackProtection; -+} -+ -+bool BridgedPassContext::enableEmbeddedSwift() const { -+ swift::SILModule *mod = invocation->getPassManager()->getModule(); -+ return mod->getASTContext().LangOpts.hasFeature(swift::Feature::Embedded); -+} -+ -+bool BridgedPassContext::enableMoveInoutStackProtection() const { -+ swift::SILModule *mod = invocation->getPassManager()->getModule(); -+ return mod->getOptions().EnableMoveInoutStackProtection; -+} -+ -+BridgedPassContext::AssertConfiguration BridgedPassContext::getAssertConfiguration() const { -+ swift::SILModule *mod = invocation->getPassManager()->getModule(); -+ return (AssertConfiguration)mod->getOptions().AssertConfig; -+} -+ -+static_assert((int)BridgedPassContext::SILStage::Raw == (int)swift::SILStage::Raw); -+static_assert((int)BridgedPassContext::SILStage::Canonical == (int)swift::SILStage::Canonical); -+static_assert((int)BridgedPassContext::SILStage::Lowered == (int)swift::SILStage::Lowered); -+ -+static_assert((int)BridgedPassContext::AssertConfiguration::Debug == (int)swift::SILOptions::Debug); -+static_assert((int)BridgedPassContext::AssertConfiguration::Release == (int)swift::SILOptions::Release); -+static_assert((int)BridgedPassContext::AssertConfiguration::Unchecked == (int)swift::SILOptions::Unchecked); -+ -+SWIFT_END_NULLABILITY_ANNOTATIONS -+ -+#endif -diff --git a/swift/lib/AST/ASTBridging.cpp b/swift/lib/AST/ASTBridging.cpp -index 4b924f80163..db58aaa98fe 100644 ---- a/swift/lib/AST/ASTBridging.cpp -+++ b/swift/lib/AST/ASTBridging.cpp -@@ -25,30 +25,53 @@ DiagnosticEngine *getDiagnosticEngine(const BridgedDiagnosticEngine &bridged) { - - } // namespace - -+static_assert(sizeof(BridgedDiagnosticArgument) >= sizeof(DiagnosticArgument), -+ "BridgedDiagnosticArgument has wrong size"); -+ -+BridgedDiagnosticArgument::BridgedDiagnosticArgument(SwiftInt i) -+ : BridgedDiagnosticArgument(DiagnosticArgument((int)i)) {} -+ -+BridgedDiagnosticArgument::BridgedDiagnosticArgument(BridgedStringRef s) -+ : BridgedDiagnosticArgument(DiagnosticArgument(s.get())) {} -+ -+static_assert(sizeof(BridgedDiagnosticFixIt) >= sizeof(DiagnosticInfo::FixIt), -+ "BridgedDiagnosticFixIt has wrong size"); -+ -+static SourceLoc getSourceLoc(BridgedSourceLoc bridgedLoc) { -+ return SourceLoc(llvm::SMLoc::getFromPointer(bridgedLoc.getLoc())); -+} -+ -+BridgedDiagnosticFixIt::BridgedDiagnosticFixIt(BridgedSourceLoc start, uint32_t length, BridgedStringRef text) -+ : BridgedDiagnosticFixIt(DiagnosticInfo::FixIt( -+ CharSourceRange(getSourceLoc(start), length), -+ text.get(), -+ llvm::ArrayRef())) {} -+ - void DiagnosticEngine_diagnose( -- BridgedDiagnosticEngine bridgedEngine, SourceLoc loc, -+ BridgedDiagnosticEngine bridgedEngine, BridgedSourceLoc loc, - BridgedDiagID bridgedDiagID, -- BridgedArrayRef /*DiagnosticArgument*/ bridgedArguments, -- CharSourceRange highlight, -- BridgedArrayRef /*DiagnosticInfo::FixIt*/ bridgedFixIts) { -+ BridgedArrayRef /*BridgedDiagnosticArgument*/ bridgedArguments, -+ BridgedSourceLoc highlightStart, uint32_t hightlightLength, -+ BridgedArrayRef /*BridgedDiagnosticFixIt*/ bridgedFixIts) { - auto *D = getDiagnosticEngine(bridgedEngine); - - auto diagID = static_cast(bridgedDiagID); - SmallVector arguments; -- for (auto arg : getArrayRef(bridgedArguments)) { -- arguments.push_back(arg); -+ for (auto arg : getArrayRef(bridgedArguments)) { -+ arguments.push_back(arg.get()); - } -- auto inflight = D->diagnose(loc, diagID, arguments); -+ auto inflight = D->diagnose(SourceLoc(llvm::SMLoc::getFromPointer(loc.getLoc())), diagID, arguments); - - // Add highlight. -- if (highlight.isValid()) { -+ if (highlightStart.isValid()) { -+ CharSourceRange highlight(getSourceLoc(highlightStart), (unsigned)hightlightLength); - inflight.highlightChars(highlight.getStart(), highlight.getEnd()); - } - - // Add fix-its. -- for (auto fixIt : getArrayRef(bridgedFixIts)) { -- auto range = fixIt.getRange(); -- auto text = fixIt.getText(); -+ for (const BridgedDiagnosticFixIt &fixIt : getArrayRef(bridgedFixIts)) { -+ auto range = fixIt.get().getRange(); -+ auto text = fixIt.get().getText(); - inflight.fixItReplaceChars(range.getStart(), range.getEnd(), text); - } - } -diff --git a/swift/lib/AST/Decl.cpp b/swift/lib/AST/Decl.cpp -index 8fd0134e9dc..f68e0ebf885 100644 ---- a/swift/lib/AST/Decl.cpp -+++ b/swift/lib/AST/Decl.cpp -@@ -27,8 +27,6 @@ - #include "swift/AST/DiagnosticsSema.h" - #include "swift/AST/ExistentialLayout.h" - #include "swift/AST/Expr.h" --#include "swift/AST/ForeignAsyncConvention.h" --#include "swift/AST/ForeignErrorConvention.h" - #include "swift/AST/GenericEnvironment.h" - #include "swift/AST/GenericSignature.h" - #include "swift/AST/Initializer.h" -diff --git a/swift/lib/Basic/BasicBridging.cpp b/swift/lib/Basic/BasicBridging.cpp -index 9f9e9e03e13..b9b9fe76717 100644 ---- a/swift/lib/Basic/BasicBridging.cpp -+++ b/swift/lib/Basic/BasicBridging.cpp -@@ -16,10 +16,27 @@ - using namespace swift; - - //===----------------------------------------------------------------------===// --// Bridging C functions -+// BridgedStringRef - //===----------------------------------------------------------------------===// - --void OStream_write(BridgedOStream os, StringRef str) { -- static_cast(os.streamAddr) -- ->write(str.data(), str.size()); -+void BridgedStringRef::write(BridgedOStream os) const { -+ static_cast(os.streamAddr)->write(data, length); - } -+ -+//===----------------------------------------------------------------------===// -+// BridgedOwnedString -+//===----------------------------------------------------------------------===// -+ -+BridgedOwnedString::BridgedOwnedString(const std::string &stringToCopy) -+ : data(nullptr), length(stringToCopy.size()) { -+ if (length != 0) { -+ data = new char[length]; -+ std::memcpy(data, stringToCopy.data(), length); -+ } -+} -+ -+void BridgedOwnedString::destroy() const { -+ if (data) -+ delete [] data; -+} -+ -diff --git a/swift/lib/Parse/ParseRegex.cpp b/swift/lib/Parse/ParseRegex.cpp -index 5ed804653d3..2b680142487 100644 ---- a/swift/lib/Parse/ParseRegex.cpp -+++ b/swift/lib/Parse/ParseRegex.cpp -@@ -44,7 +44,7 @@ ParserResult Parser::parseExprRegexLiteral() { - /*versionOut=*/&version, - /*captureStructureOut=*/capturesBuf.data(), - /*captureStructureSize=*/capturesBuf.size(), -- /*diagBaseLoc=*/{Tok.getLoc().getOpaquePointerValue()}, &Diags); -+ /*diagBaseLoc=*/{(const uint8_t *)(Tok.getLoc().getOpaquePointerValue())}, &Diags); - auto loc = consumeToken(); - SourceMgr.recordRegexLiteralStartLoc(loc); - -diff --git a/swift/lib/SIL/IR/SILBasicBlock.cpp b/swift/lib/SIL/IR/SILBasicBlock.cpp -index b94fcc7f376..2810e8331b4 100644 ---- a/swift/lib/SIL/IR/SILBasicBlock.cpp -+++ b/swift/lib/SIL/IR/SILBasicBlock.cpp -@@ -19,7 +19,6 @@ - #include "swift/SIL/DebugUtils.h" - #include "swift/SIL/SILBasicBlock.h" - #include "swift/SIL/SILBuilder.h" --#include "swift/SIL/SILBridging.h" - #include "swift/SIL/SILArgument.h" - #include "swift/SIL/SILDebugScope.h" - #include "swift/SIL/SILFunction.h" -diff --git a/swift/lib/SIL/IR/SILFunction.cpp b/swift/lib/SIL/IR/SILFunction.cpp -index 5c97ac25581..201b27edf7f 100644 ---- a/swift/lib/SIL/IR/SILFunction.cpp -+++ b/swift/lib/SIL/IR/SILFunction.cpp -@@ -985,9 +985,14 @@ void BridgedFunction::registerBridging(SwiftMetatype metatype, - std::pair SILFunction:: - parseArgumentEffectsFromSource(StringRef effectStr, ArrayRef paramNames) { - if (parseFunction) { -+ llvm::SmallVector bridgedParamNames; -+ for (StringRef paramName : paramNames) { -+ bridgedParamNames.push_back(paramName); -+ } -+ ArrayRef bridgedParamNameArray = bridgedParamNames; - auto error = parseFunction( - {this}, effectStr, BridgedFunction::ParseEffectsMode::argumentEffectsFromSource, -1, -- {(const unsigned char *)paramNames.data(), paramNames.size()}); -+ {(const unsigned char *)bridgedParamNameArray.data(), bridgedParamNameArray.size()}); - return {(const char *)error.message, (int)error.position}; - } - return {nullptr, 0}; -diff --git a/swift/lib/SIL/IR/SILLocation.cpp b/swift/lib/SIL/IR/SILLocation.cpp -index ad6feba56f5..cfaa9880382 100644 ---- a/swift/lib/SIL/IR/SILLocation.cpp -+++ b/swift/lib/SIL/IR/SILLocation.cpp -@@ -337,21 +337,3 @@ ImplicitReturnLocation::ImplicitReturnLocation(SILLocation L) - L.isASTNode() || - L.isNull()); - } -- --std::string SILDebugLocation::getDebugDescription() const { -- std::string str; -- llvm::raw_string_ostream os(str); -- SILLocation loc = getLocation(); -- loc.print(os); --#ifndef NDEBUG -- if (const SILDebugScope *scope = getScope()) { -- if (DeclContext *dc = loc.getAsDeclContext()) { -- os << ", scope="; -- scope->print(dc->getASTContext().SourceMgr, os, /*indent*/ 2); -- } else { -- os << ", scope=?"; -- } -- } --#endif -- return str; --} -diff --git a/swift/lib/SIL/Utils/SILBridging.cpp b/swift/lib/SIL/Utils/SILBridging.cpp -index 0aa1baaa36e..2c1c1e0179a 100644 ---- a/swift/lib/SIL/Utils/SILBridging.cpp -+++ b/swift/lib/SIL/Utils/SILBridging.cpp -@@ -1,8 +1,8 @@ --//===--- SILBridgingUtils.cpp - Utilities for swift bridging --------------===// -+//===--- SILBridging.cpp --------------------------------------------------===// - // - // This source file is part of the Swift.org open source project - // --// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors -+// 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 -@@ -10,16 +10,22 @@ - // - //===----------------------------------------------------------------------===// - -+#include "swift/SIL/SILBridging.h" -+#ifdef PURE_BRIDGING_MODE -+// In PURE_BRIDGING_MODE, briding functions are not inlined and therefore inluded in the cpp file. -+#include "swift/SIL/SILBridgingImpl.h" -+#endif -+ - #include "swift/Basic/BridgingUtils.h" - #include "swift/AST/Attr.h" - #include "swift/AST/SemanticAttrs.h" - #include "swift/SIL/SILNode.h" --#include "swift/SIL/ApplySite.h" --#include "swift/SIL/SILBridging.h" - #include "swift/SIL/SILGlobalVariable.h" - #include "swift/SIL/SILBuilder.h" - #include "swift/SIL/MemAccessUtils.h" - #include -+#include -+#include - - using namespace swift; - -@@ -61,7 +67,8 @@ static void setUnimplementedRange(SwiftMetatype metatype, - - /// Registers the metatype of a swift SIL class. - /// Called by initializeSwiftModules(). --void registerBridgedClass(StringRef className, SwiftMetatype metatype) { -+void registerBridgedClass(BridgedStringRef bridgedClassName, SwiftMetatype metatype) { -+ StringRef className = bridgedClassName.get(); - nodeMetatypesInitialized = true; - - // Handle the important non Node classes. -@@ -127,11 +134,39 @@ void registerBridgedClass(StringRef className, SwiftMetatype metatype) { - nodeMetatypes[(unsigned)kind] = metatype; - } - -+//===----------------------------------------------------------------------===// -+// SILType -+//===----------------------------------------------------------------------===// -+ -+static_assert((int)BridgedType::MetatypeRepresentation::Thin == (int)swift::MetatypeRepresentation::Thin); -+static_assert((int)BridgedType::MetatypeRepresentation::Thick == (int)swift::MetatypeRepresentation::Thick); -+static_assert((int)BridgedType::MetatypeRepresentation::ObjC == (int)swift::MetatypeRepresentation::ObjC); -+ -+static_assert((int)BridgedType::TraitResult::IsNot == (int)swift::TypeTraitResult::IsNot); -+static_assert((int)BridgedType::TraitResult::CanBe == (int)swift::TypeTraitResult::CanBe); -+static_assert((int)BridgedType::TraitResult::Is == (int)swift::TypeTraitResult::Is); -+ -+ - //===----------------------------------------------------------------------===// - // SILFunction - //===----------------------------------------------------------------------===// - --std::string BridgedFunction::getDebugDescription() const { -+static_assert((int)BridgedFunction::EffectsKind::ReadNone == (int)swift::EffectsKind::ReadNone); -+static_assert((int)BridgedFunction::EffectsKind::ReadOnly == (int)swift::EffectsKind::ReadOnly); -+static_assert((int)BridgedFunction::EffectsKind::ReleaseNone == (int)swift::EffectsKind::ReleaseNone); -+static_assert((int)BridgedFunction::EffectsKind::ReadWrite == (int)swift::EffectsKind::ReadWrite); -+static_assert((int)BridgedFunction::EffectsKind::Unspecified == (int)swift::EffectsKind::Unspecified); -+static_assert((int)BridgedFunction::EffectsKind::Custom == (int)swift::EffectsKind::Custom); -+ -+static_assert((int)BridgedFunction::PerformanceConstraints::None == (int)swift::PerformanceConstraints::None); -+static_assert((int)BridgedFunction::PerformanceConstraints::NoAllocation == (int)swift::PerformanceConstraints::NoAllocation); -+static_assert((int)BridgedFunction::PerformanceConstraints::NoLocks == (int)swift::PerformanceConstraints::NoLocks); -+ -+static_assert((int)BridgedFunction::InlineStrategy::InlineDefault == (int)swift::InlineDefault); -+static_assert((int)BridgedFunction::InlineStrategy::NoInline == (int)swift::NoInline); -+static_assert((int)BridgedFunction::InlineStrategy::AlwaysInline == (int)swift::AlwaysInline); -+ -+BridgedOwnedString BridgedFunction::getDebugDescription() const { - std::string str; - llvm::raw_string_ostream os(str); - getFunction()->print(os); -@@ -143,10 +178,10 @@ std::string BridgedFunction::getDebugDescription() const { - // SILBasicBlock - //===----------------------------------------------------------------------===// - --std::string BridgedBasicBlock::getDebugDescription() const { -+BridgedOwnedString BridgedBasicBlock::getDebugDescription() const { - std::string str; - llvm::raw_string_ostream os(str); -- getBlock()->print(os); -+ get()->print(os); - str.pop_back(); // Remove trailing newline. - return str; - } -@@ -155,7 +190,7 @@ std::string BridgedBasicBlock::getDebugDescription() const { - // SILValue - //===----------------------------------------------------------------------===// - --std::string BridgedValue::getDebugDescription() const { -+BridgedOwnedString BridgedValue::getDebugDescription() const { - std::string str; - llvm::raw_string_ostream os(str); - getSILValue()->print(os); -@@ -184,11 +219,30 @@ ArrayRef BridgedValueArray::getValues(SmallVectorImpl &stora - return storage; - } - -+ -+//===----------------------------------------------------------------------===// -+// SILArgument -+//===----------------------------------------------------------------------===// -+ -+static_assert((int)BridgedArgumentConvention::Indirect_In == (int)swift::SILArgumentConvention::Indirect_In); -+static_assert((int)BridgedArgumentConvention::Indirect_In_Guaranteed == (int)swift::SILArgumentConvention::Indirect_In_Guaranteed); -+static_assert((int)BridgedArgumentConvention::Indirect_Inout == (int)swift::SILArgumentConvention::Indirect_Inout); -+static_assert((int)BridgedArgumentConvention::Indirect_InoutAliasable == (int)swift::SILArgumentConvention::Indirect_InoutAliasable); -+static_assert((int)BridgedArgumentConvention::Indirect_Out == (int)swift::SILArgumentConvention::Indirect_Out); -+static_assert((int)BridgedArgumentConvention::Direct_Owned == (int)swift::SILArgumentConvention::Direct_Owned); -+static_assert((int)BridgedArgumentConvention::Direct_Unowned == (int)swift::SILArgumentConvention::Direct_Unowned); -+static_assert((int)BridgedArgumentConvention::Direct_Guaranteed == (int)swift::SILArgumentConvention::Direct_Guaranteed); -+static_assert((int)BridgedArgumentConvention::Pack_Owned == (int)swift::SILArgumentConvention::Pack_Owned); -+static_assert((int)BridgedArgumentConvention::Pack_Inout == (int)swift::SILArgumentConvention::Pack_Inout); -+static_assert((int)BridgedArgumentConvention::Pack_Guaranteed == (int)swift::SILArgumentConvention::Pack_Guaranteed); -+static_assert((int)BridgedArgumentConvention::Pack_Out == (int)swift::SILArgumentConvention::Pack_Out); -+ -+ - //===----------------------------------------------------------------------===// - // SILGlobalVariable - //===----------------------------------------------------------------------===// - --std::string BridgedGlobalVar::getDebugDescription() const { -+BridgedOwnedString BridgedGlobalVar::getDebugDescription() const { - std::string str; - llvm::raw_string_ostream os(str); - getGlobal()->print(os); -@@ -217,7 +271,7 @@ bool BridgedGlobalVar::mustBeInitializedStatically() const { - // SILVTable - //===----------------------------------------------------------------------===// - --std::string BridgedVTable::getDebugDescription() const { -+BridgedOwnedString BridgedVTable::getDebugDescription() const { - std::string str; - llvm::raw_string_ostream os(str); - vTable->print(os); -@@ -225,7 +279,7 @@ std::string BridgedVTable::getDebugDescription() const { - return str; - } - --std::string BridgedVTableEntry::getDebugDescription() const { -+BridgedOwnedString BridgedVTableEntry::getDebugDescription() const { - std::string str; - llvm::raw_string_ostream os(str); - entry->print(os); -@@ -237,15 +291,21 @@ std::string BridgedVTableEntry::getDebugDescription() const { - // SILVWitnessTable, SILDefaultWitnessTable - //===----------------------------------------------------------------------===// - --std::string BridgedWitnessTableEntry::getDebugDescription() const { -+static_assert((int)BridgedWitnessTableEntry::Kind::Invalid == (int)swift::SILWitnessTable::WitnessKind::Invalid); -+static_assert((int)BridgedWitnessTableEntry::Kind::Method == (int)swift::SILWitnessTable::WitnessKind::Method); -+static_assert((int)BridgedWitnessTableEntry::Kind::AssociatedType == (int)swift::SILWitnessTable::WitnessKind::AssociatedType); -+static_assert((int)BridgedWitnessTableEntry::Kind::AssociatedTypeProtocol == (int)swift::SILWitnessTable::WitnessKind::AssociatedTypeProtocol); -+static_assert((int)BridgedWitnessTableEntry::Kind::BaseProtocol == (int)swift::SILWitnessTable::WitnessKind::BaseProtocol); -+ -+BridgedOwnedString BridgedWitnessTableEntry::getDebugDescription() const { - std::string str; - llvm::raw_string_ostream os(str); -- entry->print(os, /*verbose=*/ false, PrintOptions::printSIL()); -+ getEntry()->print(os, /*verbose=*/ false, PrintOptions::printSIL()); - str.pop_back(); // Remove trailing newline. - return str; - } - --std::string BridgedWitnessTable::getDebugDescription() const { -+BridgedOwnedString BridgedWitnessTable::getDebugDescription() const { - std::string str; - llvm::raw_string_ostream os(str); - table->print(os); -@@ -253,7 +313,7 @@ std::string BridgedWitnessTable::getDebugDescription() const { - return str; - } - --std::string BridgedDefaultWitnessTable::getDebugDescription() const { -+BridgedOwnedString BridgedDefaultWitnessTable::getDebugDescription() const { - std::string str; - llvm::raw_string_ostream os(str); - table->print(os); -@@ -261,32 +321,76 @@ std::string BridgedDefaultWitnessTable::getDebugDescription() const { - return str; - } - -+//===----------------------------------------------------------------------===// -+// SubstitutionMap -+//===----------------------------------------------------------------------===// -+ -+static_assert(sizeof(BridgedSubstitutionMap) >= sizeof(swift::SubstitutionMap), -+ "BridgedSubstitutionMap has wrong size"); -+ -+ -+//===----------------------------------------------------------------------===// -+// SILDebugLocation -+//===----------------------------------------------------------------------===// -+ -+static_assert(sizeof(BridgedLocation) >= sizeof(swift::SILDebugLocation), -+ "BridgedLocation has wrong size"); -+ -+BridgedOwnedString BridgedLocation::getDebugDescription() const { -+ std::string str; -+ llvm::raw_string_ostream os(str); -+ SILLocation loc = getLoc().getLocation(); -+ loc.print(os); -+#ifndef NDEBUG -+ if (const SILDebugScope *scope = getLoc().getScope()) { -+ if (DeclContext *dc = loc.getAsDeclContext()) { -+ os << ", scope="; -+ scope->print(dc->getASTContext().SourceMgr, os, /*indent*/ 2); -+ } else { -+ os << ", scope=?"; -+ } -+ } -+#endif -+ return str; -+} -+ - //===----------------------------------------------------------------------===// - // SILInstruction - //===----------------------------------------------------------------------===// - --std::string BridgedInstruction::getDebugDescription() const { -+static_assert((int)BridgedMemoryBehavior::None == (int)swift::MemoryBehavior::None); -+static_assert((int)BridgedMemoryBehavior::MayRead == (int)swift::MemoryBehavior::MayRead); -+static_assert((int)BridgedMemoryBehavior::MayWrite == (int)swift::MemoryBehavior::MayWrite); -+static_assert((int)BridgedMemoryBehavior::MayReadWrite == (int)swift::MemoryBehavior::MayReadWrite); -+static_assert((int)BridgedMemoryBehavior::MayHaveSideEffects == (int)swift::MemoryBehavior::MayHaveSideEffects); -+ -+static_assert((int)BridgedInstruction::AccessKind::Init == (int)swift::SILAccessKind::Init); -+static_assert((int)BridgedInstruction::AccessKind::Read == (int)swift::SILAccessKind::Read); -+static_assert((int)BridgedInstruction::AccessKind::Modify == (int)swift::SILAccessKind::Modify); -+static_assert((int)BridgedInstruction::AccessKind::Deinit == (int)swift::SILAccessKind::Deinit); -+ -+BridgedOwnedString BridgedInstruction::getDebugDescription() const { - std::string str; - llvm::raw_string_ostream os(str); -- getInst()->print(os); -+ get()->print(os); - str.pop_back(); // Remove trailing newline. - return str; - } - - bool BridgedInstruction::mayAccessPointer() const { -- return ::mayAccessPointer(getInst()); -+ return ::mayAccessPointer(get()); - } - - bool BridgedInstruction::mayLoadWeakOrUnowned() const { -- return ::mayLoadWeakOrUnowned(getInst()); -+ return ::mayLoadWeakOrUnowned(get()); - } - - bool BridgedInstruction::maySynchronizeNotConsideringSideEffects() const { -- return ::maySynchronizeNotConsideringSideEffects(getInst()); -+ return ::maySynchronizeNotConsideringSideEffects(get()); - } - - bool BridgedInstruction::mayBeDeinitBarrierNotConsideringSideEffects() const { -- return ::mayBeDeinitBarrierNotConsideringSideEffects(getInst()); -+ return ::mayBeDeinitBarrierNotConsideringSideEffects(get()); - } - - //===----------------------------------------------------------------------===// -@@ -299,3 +403,7 @@ bool BridgedNominalTypeDecl::isStructWithUnreferenceableStorage() const { - } - return false; - } -+ -+void writeCharToStderr(int c) { -+ putc(c, stderr); -+} -diff --git a/swift/lib/SILOptimizer/PassManager/PassManager.cpp b/swift/lib/SILOptimizer/PassManager/PassManager.cpp -index a130147a445..cfa1a3abb39 100644 ---- a/swift/lib/SILOptimizer/PassManager/PassManager.cpp -+++ b/swift/lib/SILOptimizer/PassManager/PassManager.cpp -@@ -22,23 +22,17 @@ - #include "swift/SIL/SILCloner.h" - #include "swift/SIL/SILFunction.h" - #include "swift/SIL/SILModule.h" --#include "swift/SILOptimizer/Analysis/AliasAnalysis.h" - #include "swift/SILOptimizer/Analysis/BasicCalleeAnalysis.h" --#include "swift/SILOptimizer/Analysis/DeadEndBlocksAnalysis.h" - #include "swift/SILOptimizer/Analysis/FunctionOrder.h" --#include "swift/SILOptimizer/Analysis/DominanceAnalysis.h" - #include "swift/SILOptimizer/OptimizerBridging.h" - #include "swift/SILOptimizer/PassManager/PrettyStackTrace.h" - #include "swift/SILOptimizer/PassManager/Transforms.h" --#include "swift/SILOptimizer/Utils/BasicBlockOptUtils.h" --#include "swift/SILOptimizer/Utils/ConstantFolding.h" --#include "swift/SILOptimizer/Utils/CFGOptUtils.h" - #include "swift/SILOptimizer/Utils/Devirtualize.h" -+#include "swift/SILOptimizer/Utils/ConstantFolding.h" - #include "swift/SILOptimizer/Utils/OptimizerStatsUtils.h" - #include "swift/SILOptimizer/Utils/SILInliner.h" - #include "swift/SILOptimizer/Utils/SILOptFunctionBuilder.h" - #include "swift/SILOptimizer/Utils/StackNesting.h" --#include "swift/SILOptimizer/Utils/InstOptUtils.h" - #include "llvm/ADT/DenseMap.h" - #include "llvm/ADT/Statistic.h" - #include "llvm/ADT/StringSwitch.h" -@@ -151,10 +145,6 @@ llvm::cl::opt SILForceVerifyAll( - llvm::cl::desc("For all passes, precompute analyses before the pass and " - "verify analyses after the pass")); - --llvm::cl::list -- SimplifyInstructionTest("simplify-instruction", llvm::cl::CommaSeparated, -- llvm::cl::desc("Simplify instruction of specified kind(s)")); -- - static llvm::ManagedStatic> DebugPassNumbers; - - namespace { -@@ -1440,9 +1430,18 @@ SwiftPassInvocation::~SwiftPassInvocation() { - } - - //===----------------------------------------------------------------------===// --// Swift Bridging -+// OptimizerBridging - //===----------------------------------------------------------------------===// - -+llvm::cl::list -+ SimplifyInstructionTest("simplify-instruction", llvm::cl::CommaSeparated, -+ llvm::cl::desc("Simplify instruction of specified kind(s)")); -+ -+#ifdef PURE_BRIDGING_MODE -+// In PURE_BRIDGING_MODE, briding functions are not inlined and therefore inluded in the cpp file. -+#include "swift/SILOptimizer/OptimizerBridgingImpl.h" -+#endif -+ - void BridgedChangeNotificationHandler::notifyChanges(Kind changeKind) const { - switch (changeKind) { - case Kind::instructionsChanged: -@@ -1460,7 +1459,7 @@ void BridgedChangeNotificationHandler::notifyChanges(Kind changeKind) const { - } - } - --std::string BridgedPassContext::getModuleDescription() const { -+BridgedOwnedString BridgedPassContext::getModuleDescription() const { - std::string str; - llvm::raw_string_ostream os(str); - invocation->getPassManager()->getModule()->print(os); -@@ -1481,7 +1480,7 @@ bool BridgedPassContext::tryDeleteDeadClosure(BridgedInstruction closure, bool n - BridgedPassContext::DevirtResult BridgedPassContext::tryDevirtualizeApply(BridgedInstruction apply, - bool isMandatory) const { - auto cha = invocation->getPassManager()->getAnalysis(); -- auto result = ::tryDevirtualizeApply(ApplySite(apply.getInst()), cha, nullptr, isMandatory); -+ auto result = ::tryDevirtualizeApply(ApplySite(apply.get()), cha, nullptr, isMandatory); - if (result.first) { - OptionalBridgedInstruction newApply(result.first.getInstruction()->asSILNode()); - return {newApply, result.second}; -@@ -1498,7 +1497,7 @@ OptionalBridgedValue BridgedPassContext::constantFoldBuiltin(BridgedInstruction - void BridgedPassContext::inlineFunction(BridgedInstruction apply, bool mandatoryInline) const { - SILOptFunctionBuilder funcBuilder(*invocation->getTransform()); - InstructionDeleter deleter; -- SILInliner::inlineFullApply(FullApplySite(apply.getInst()), -+ SILInliner::inlineFullApply(FullApplySite(apply.get()), - mandatoryInline ? SILInliner::InlineKind::MandatoryInline - : SILInliner::InlineKind::PerformanceInline, - funcBuilder, -@@ -1518,29 +1517,29 @@ static SwiftInt integerValueFromConstant(llvm::Constant *c, SwiftInt add = 0) { - return value.getLimitedValue() + add; - } - --SwiftInt BridgedPassContext::getStaticSize(swift::SILType type) const { -+SwiftInt BridgedPassContext::getStaticSize(BridgedType type) const { - irgen::IRGenModule *IGM = invocation->getIRGenModule(); - if (!IGM) - return -1; -- auto &ti = getTypeInfoOfBuiltin(type, *IGM); -+ auto &ti = getTypeInfoOfBuiltin(type.get(), *IGM); - llvm::Constant *c = ti.getStaticSize(*IGM); - return integerValueFromConstant(c); - } - --SwiftInt BridgedPassContext::getStaticAlignment(swift::SILType type) const { -+SwiftInt BridgedPassContext::getStaticAlignment(BridgedType type) const { - irgen::IRGenModule *IGM = invocation->getIRGenModule(); - if (!IGM) - return -1; -- auto &ti = getTypeInfoOfBuiltin(type, *IGM); -+ auto &ti = getTypeInfoOfBuiltin(type.get(), *IGM); - llvm::Constant *c = ti.getStaticAlignmentMask(*IGM); - return integerValueFromConstant(c, 1); - } - --SwiftInt BridgedPassContext::getStaticStride(swift::SILType type) const { -+SwiftInt BridgedPassContext::getStaticStride(BridgedType type) const { - irgen::IRGenModule *IGM = invocation->getIRGenModule(); - if (!IGM) - return -1; -- auto &ti = getTypeInfoOfBuiltin(type, *IGM); -+ auto &ti = getTypeInfoOfBuiltin(type.get(), *IGM); - llvm::Constant *c = ti.getStaticStride(*IGM); - return integerValueFromConstant(c); - } -@@ -1566,7 +1565,7 @@ public: - }; - } // namespace - --std::string BridgedPassContext::mangleOutlinedVariable(BridgedFunction function) const { -+BridgedOwnedString BridgedPassContext::mangleOutlinedVariable(BridgedFunction function) const { - int idx = 0; - SILFunction *f = function.getFunction(); - SILModule &mod = f->getModule(); -@@ -1579,11 +1578,11 @@ std::string BridgedPassContext::mangleOutlinedVariable(BridgedFunction function) - } - } - --BridgedGlobalVar BridgedPassContext::createGlobalVariable(StringRef name, SILType type, bool isPrivate) const { -+BridgedGlobalVar BridgedPassContext::createGlobalVariable(BridgedStringRef name, BridgedType type, bool isPrivate) const { - return {SILGlobalVariable::create(*invocation->getPassManager()->getModule(), - isPrivate ? SILLinkage::Private : SILLinkage::Public, - IsNotSerialized, -- name, type)}; -+ name.get(), type.get())}; - } - - void BridgedPassContext::fixStackNesting(BridgedFunction function) const { -@@ -1600,10 +1599,10 @@ void BridgedPassContext::fixStackNesting(BridgedFunction function) const { - invocation->setNeedFixStackNesting(false); - } - --OptionalBridgedFunction BridgedPassContext::lookupStdlibFunction(llvm::StringRef name) const { -+OptionalBridgedFunction BridgedPassContext::lookupStdlibFunction(BridgedStringRef name) const { - swift::SILModule *mod = invocation->getPassManager()->getModule(); - SmallVector results; -- mod->getASTContext().lookupInSwiftModule(name, results); -+ mod->getASTContext().lookupInSwiftModule(name.get(), results); - if (results.size() != 1) - return {nullptr}; - -@@ -1621,7 +1620,7 @@ bool BridgedPassContext::enableSimplificationFor(BridgedInstruction inst) const - if (SimplifyInstructionTest.empty() && SILDisablePass.empty()) - return true; - -- StringRef instName = getSILInstructionName(inst.getInst()->getKind()); -+ StringRef instName = getSILInstructionName(inst.get()->getKind()); - - if (SILPassManager::isInstructionPassDisabled(instName)) - return false; -@@ -1637,17 +1636,17 @@ bool BridgedPassContext::enableSimplificationFor(BridgedInstruction inst) const - } - - bool FullApplySite_canInline(BridgedInstruction apply) { -- return swift::SILInliner::canInlineApplySite(swift::FullApplySite(apply.getInst())); -+ return swift::SILInliner::canInlineApplySite(swift::FullApplySite(apply.get())); - } - - // TODO: can't be inlined to work around https://github.com/apple/swift/issues/64502 --CalleeList BridgedCalleeAnalysis::getCallees(BridgedValue callee) const { -+BridgedCalleeAnalysis::CalleeList BridgedCalleeAnalysis::getCallees(BridgedValue callee) const { - return ca->getCalleeListOfValue(callee.getSILValue()); - } - - // TODO: can't be inlined to work around https://github.com/apple/swift/issues/64502 --CalleeList BridgedCalleeAnalysis::getDestructors(SILType type, bool isExactType) const { -- return ca->getDestructors(type, isExactType); -+BridgedCalleeAnalysis::CalleeList BridgedCalleeAnalysis::getDestructors(BridgedType type, bool isExactType) const { -+ return ca->getDestructors(type.get(), isExactType); - } - - // Need to put ClonerWithFixedLocation into namespace swift to forward reference -@@ -1698,7 +1697,7 @@ BridgedCloner::BridgedCloner(BridgedGlobalVar var, BridgedPassContext context) - } - - BridgedCloner::BridgedCloner(BridgedInstruction inst, BridgedPassContext context) -- : cloner(new ClonerWithFixedLocation(inst.getInst())) { -+ : cloner(new ClonerWithFixedLocation(inst.get())) { - context.invocation->notifyNewCloner(); - } - -@@ -1717,5 +1716,6 @@ bool BridgedCloner::isValueCloned(BridgedValue v) const { - } - - void BridgedCloner::clone(BridgedInstruction inst) { -- cloner->cloneInst(inst.getInst()); -+ cloner->cloneInst(inst.get()); - } -+ -diff --git a/swift/lib/SILOptimizer/PassManager/Passes.cpp b/swift/lib/SILOptimizer/PassManager/Passes.cpp -index 7f04f625a47..e28b6bbb6d8 100644 ---- a/swift/lib/SILOptimizer/PassManager/Passes.cpp -+++ b/swift/lib/SILOptimizer/PassManager/Passes.cpp -@@ -274,15 +274,15 @@ static void runBridgedFunctionPass(BridgedFunctionPassRunFn &runFunction, - } - - // Called from initializeSwiftModules(). --void SILPassManager_registerModulePass(llvm::StringRef name, -+void SILPassManager_registerModulePass(BridgedStringRef name, - BridgedModulePassRunFn runFn) { -- bridgedModulePassRunFunctions[name] = runFn; -+ bridgedModulePassRunFunctions[name.get()] = runFn; - passesRegistered = true; - } - --void SILPassManager_registerFunctionPass(llvm::StringRef name, -+void SILPassManager_registerFunctionPass(BridgedStringRef name, - BridgedFunctionPassRunFn runFn) { -- bridgedFunctionPassRunFunctions[name] = runFn; -+ bridgedFunctionPassRunFunctions[name.get()] = runFn; - passesRegistered = true; - } - -diff --git a/swift/lib/SILOptimizer/SILCombiner/SILCombine.cpp b/swift/lib/SILOptimizer/SILCombiner/SILCombine.cpp -index 599855125c9..0959b8733a9 100644 ---- a/swift/lib/SILOptimizer/SILCombiner/SILCombine.cpp -+++ b/swift/lib/SILOptimizer/SILCombiner/SILCombine.cpp -@@ -540,9 +540,9 @@ static llvm::StringMap swiftInstPasses; - static bool passesRegistered = false; - - // Called from initializeSwiftModules(). --void SILCombine_registerInstructionPass(llvm::StringRef instClassName, -+void SILCombine_registerInstructionPass(BridgedStringRef instClassName, - BridgedInstructionPassRunFn runFn) { -- swiftInstPasses[instClassName] = runFn; -+ swiftInstPasses[instClassName.get()] = runFn; - passesRegistered = true; - } - diff --git a/packages/swift/swift-remove-relative-rpaths.patch b/packages/swift/swift-remove-relative-rpaths.patch index f363ceddcb26c7..194ebee39ea470 100644 --- a/packages/swift/swift-remove-relative-rpaths.patch +++ b/packages/swift/swift-remove-relative-rpaths.patch @@ -26,19 +26,6 @@ index bd31bec..737c8c3 100755 # SwiftPM will otherwise try to compile against GNU strerror_r on # Android and fail. '-Xswiftc', '-Xcc', '-Xswiftc', '-U_GNU_SOURCE', -diff --git a/swift/CMakeLists.txt b/swift/CMakeLists.txt -index 93096ad07b9..27b7fe4b98d 100644 ---- a/swift/CMakeLists.txt -+++ b/swift/CMakeLists.txt -@@ -1366,7 +1368,7 @@ if(SWIFT_INCLUDE_TOOLS) - set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${SWIFT_HOST_LIBRARIES_DEST_DIR}") - set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${SWIFT_HOST_LIBRARIES_DEST_DIR}") - if(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD|FREEBSD") -- set(SWIFT_HOST_LIBRARIES_RPATH "$ORIGIN;$ORIGIN/../${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}") -+ set(SWIFT_HOST_LIBRARIES_RPATH "$ORIGIN;$ORIGIN/../..") - endif() - # Add unique ABI prefix to swift-syntax libraries so that compiler libraries (e.g. sourcekitdInProc) - # can be used from tools that has its own swift-syntax libraries as SwiftPM dependencies. diff --git a/swift/cmake/modules/AddPureSwift.cmake b/swift/cmake/modules/AddPureSwift.cmake index ee668f96903..61397d3910e 100644 --- a/swift/cmake/modules/AddPureSwift.cmake @@ -52,27 +39,42 @@ index ee668f96903..61397d3910e 100644 ) # NOTE: At this point we don't have any pure swift executables/shared # libraries required for building runtime/stdlib. So we don't need to add -diff --git a/swift-corelibs-foundation/Sources/Tools/plutil/CMakeLists.txt b/swift-corelibs-foundation/Sources/Tools/plutil/CMakeLists.txt -index b1c84350..35413f0b 100644 ---- a/swift-corelibs-foundation/Sources/Tools/plutil/CMakeLists.txt -+++ b/swift-corelibs-foundation/Sources/Tools/plutil/CMakeLists.txt -@@ -27,8 +27,8 @@ if(NOT CMAKE_SYSTEM_NAME MATCHES "Darwin|Windows") - set_target_properties(plutil PROPERTIES BUILD_RPATH ${CMAKE_MATCH_1}) +diff --git a/swift/lib/SwiftSyntax/CMakeLists.txt b/swift/lib/SwiftSyntax/CMakeLists.txt +index b39061073c9..a295f397d72 100644 +--- a/swift/lib/SwiftSyntax/CMakeLists.txt ++++ b/swift/lib/SwiftSyntax/CMakeLists.txt +@@ -13,7 +13,7 @@ set(BUILD_SHARED_LIBS ON) + set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${SWIFT_HOST_LIBRARIES_DEST_DIR}") + set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${SWIFT_HOST_LIBRARIES_DEST_DIR}") + if(SWIFT_HOST_VARIANT_SDK MATCHES "LINUX|ANDROID|OPENBSD|FREEBSD") +- set(SWIFT_HOST_LIBRARIES_RPATH "$ORIGIN;$ORIGIN/../${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}") ++ set(SWIFT_HOST_LIBRARIES_RPATH "$ORIGIN;$ORIGIN/../..") endif() + # Add unique ABI prefix to swift-syntax libraries so that compiler libraries (e.g. sourcekitdInProc) + # can be used from tools that has its own swift-syntax libraries as SwiftPM dependencies. +diff --git a/swift-corelibs-foundation/Sources/plutil/CMakeLists.txt b/swift-corelibs-foundation/Sources/plutil/CMakeLists.txt +index b1c84350..35413f0b 100644 +--- a/swift-corelibs-foundation/Sources/plutil/CMakeLists.txt ++++ b/swift-corelibs-foundation/Sources/plutil/CMakeLists.txt +@@ -27,9 +27,9 @@ if(NOT CMAKE_SYSTEM_NAME MATCHES "Darwin|Windows") + target_link_libraries(plutil PRIVATE + Foundation) -set_target_properties(plutil PROPERTIES -- INSTALL_RPATH "$ORIGIN/../lib/swift/$") -+#set_target_properties(plutil PROPERTIES -+ # INSTALL_RPATH "$ORIGIN/../lib/swift/$") - +- INSTALL_RPATH "$ORIGIN/../lib/swift/${SWIFT_SYSTEM_NAME}" +- INSTALL_REMOVE_ENVIRONMENT_RPATH ON) ++# set_target_properties(plutil PROPERTIES ++# INSTALL_RPATH "$ORIGIN/../lib/swift/${SWIFT_SYSTEM_NAME}" ++# INSTALL_REMOVE_ENVIRONMENT_RPATH ON) set_property(GLOBAL APPEND PROPERTY Foundation_EXPORTS plutil) + install(TARGETS plutil diff --git a/swift-driver/Utilities/build-script-helper.py b/swift-driver/Utilities/build-script-helper.py index ce6523d5..e8d63bdd 100755 --- a/swift-driver/Utilities/build-script-helper.py +++ b/swift-driver/Utilities/build-script-helper.py @@ -101,7 +101,7 @@ def get_swiftpm_options(args): - 'android-', args.cross_compile_hosts[0])): + if '-android' in args.build_target: swiftpm_args += [ '-Xlinker', '-landroid-spawn', - '-Xlinker', '-rpath', '-Xlinker', '$ORIGIN/../lib/swift/android', diff --git a/packages/swift/swift-runtime-aarch64.subpackage.sh b/packages/swift/swift-runtime-aarch64.subpackage.sh index d1bc8fa73cfa1c..c075cdb007eaae 100644 --- a/packages/swift/swift-runtime-aarch64.subpackage.sh +++ b/packages/swift/swift-runtime-aarch64.subpackage.sh @@ -1,5 +1,5 @@ TERMUX_SUBPKG_DESCRIPTION="Swift runtime libraries for Android AArch64" -TERMUX_SUBPKG_INCLUDE="opt/ndk-multilib/aarch64-linux-android/lib/lib[FXs]*.so" +TERMUX_SUBPKG_INCLUDE="opt/ndk-multilib/aarch64-linux-android/lib/lib[_FXs]*.so" TERMUX_SUBPKG_PLATFORM_INDEPENDENT=true TERMUX_SUBPKG_DEPEND_ON_PARENT=false TERMUX_SUBPKG_DEPENDS="ndk-multilib" diff --git a/packages/swift/swift-runtime-arm.subpackage.sh b/packages/swift/swift-runtime-arm.subpackage.sh index ceea74817497cd..feb8a6fef39e7e 100644 --- a/packages/swift/swift-runtime-arm.subpackage.sh +++ b/packages/swift/swift-runtime-arm.subpackage.sh @@ -1,5 +1,5 @@ TERMUX_SUBPKG_DESCRIPTION="Swift runtime libraries for Android armv7" -TERMUX_SUBPKG_INCLUDE="opt/ndk-multilib/arm-linux-androideabi/lib/lib[FXs]*.so" +TERMUX_SUBPKG_INCLUDE="opt/ndk-multilib/arm-linux-androideabi/lib/lib[_FXs]*.so" TERMUX_SUBPKG_PLATFORM_INDEPENDENT=true TERMUX_SUBPKG_DEPEND_ON_PARENT=false TERMUX_SUBPKG_DEPENDS="ndk-multilib" diff --git a/packages/swift/swift-runtime-x86-64.subpackage.sh b/packages/swift/swift-runtime-x86-64.subpackage.sh index d4b7f9ffe26615..29ac7e8d09ba01 100644 --- a/packages/swift/swift-runtime-x86-64.subpackage.sh +++ b/packages/swift/swift-runtime-x86-64.subpackage.sh @@ -1,5 +1,5 @@ TERMUX_SUBPKG_DESCRIPTION="Swift runtime libraries for Android x86_64" -TERMUX_SUBPKG_INCLUDE="opt/ndk-multilib/x86_64-linux-android/lib/lib[FXs]*.so" +TERMUX_SUBPKG_INCLUDE="opt/ndk-multilib/x86_64-linux-android/lib/lib[_FXs]*.so" TERMUX_SUBPKG_PLATFORM_INDEPENDENT=true TERMUX_SUBPKG_DEPEND_ON_PARENT=false TERMUX_SUBPKG_DEPENDS="ndk-multilib" diff --git a/packages/swift/swift-sdk-aarch64.subpackage.sh b/packages/swift/swift-sdk-aarch64.subpackage.sh index 7cae4747b789e8..92b9efc966c5e6 100644 --- a/packages/swift/swift-sdk-aarch64.subpackage.sh +++ b/packages/swift/swift-sdk-aarch64.subpackage.sh @@ -2,13 +2,15 @@ TERMUX_SUBPKG_DESCRIPTION="Swift SDK for Android AArch64" TERMUX_SUBPKG_INCLUDE=" lib/swift/android/aarch64/*.swiftdoc lib/swift/android/aarch64/*.swiftmodule -lib/swift/android/aarch64/glibc.modulemap +lib/swift/android/aarch64/android.modulemap lib/swift/android/aarch64/libswiftCxx.a -lib/swift/android/aarch64/SwiftGlibc.h +lib/swift/android/aarch64/libswiftCxxStdlib.a +lib/swift/android/aarch64/SwiftAndroidNDK.h +lib/swift/android/aarch64/SwiftBionic.h lib/swift/android/aarch64/swiftrt.o -lib/swift/android/*.swiftmodule/aarch64-* +lib/swift/android/*.swiftmodule/aarch64* lib/swift_static/android/aarch64/ -lib/swift_static/android/*.swiftmodule/aarch64-* +lib/swift_static/android/*.swiftmodule/aarch64* " TERMUX_SUBPKG_PLATFORM_INDEPENDENT=true TERMUX_SUBPKG_DEPENDS="swift-runtime-aarch64" diff --git a/packages/swift/swift-sdk-arm.subpackage.sh b/packages/swift/swift-sdk-arm.subpackage.sh index fbd81c05d64bb2..2da6ba016ac105 100644 --- a/packages/swift/swift-sdk-arm.subpackage.sh +++ b/packages/swift/swift-sdk-arm.subpackage.sh @@ -2,13 +2,15 @@ TERMUX_SUBPKG_DESCRIPTION="Swift SDK for Android armv7" TERMUX_SUBPKG_INCLUDE=" lib/swift/android/armv7/*.swiftdoc lib/swift/android/armv7/*.swiftmodule -lib/swift/android/armv7/glibc.modulemap +lib/swift/android/armv7/android.modulemap lib/swift/android/armv7/libswiftCxx.a -lib/swift/android/armv7/SwiftGlibc.h +lib/swift/android/armv7/libswiftCxxStdlib.a +lib/swift/android/armv7/SwiftAndroidNDK.h +lib/swift/android/armv7/SwiftBionic.h lib/swift/android/armv7/swiftrt.o -lib/swift/android/*.swiftmodule/armv7-* +lib/swift/android/*.swiftmodule/armv7* lib/swift_static/android/armv7/ -lib/swift_static/android/*.swiftmodule/armv7-* +lib/swift_static/android/*.swiftmodule/armv7* " TERMUX_SUBPKG_PLATFORM_INDEPENDENT=true TERMUX_SUBPKG_DEPENDS="swift-runtime-arm" diff --git a/packages/swift/swift-sdk-x86-64.subpackage.sh b/packages/swift/swift-sdk-x86-64.subpackage.sh index 92bf84091f5b45..84b74507377339 100644 --- a/packages/swift/swift-sdk-x86-64.subpackage.sh +++ b/packages/swift/swift-sdk-x86-64.subpackage.sh @@ -2,13 +2,15 @@ TERMUX_SUBPKG_DESCRIPTION="Swift SDK for Android x86_64" TERMUX_SUBPKG_INCLUDE=" lib/swift/android/x86_64/*.swiftdoc lib/swift/android/x86_64/*.swiftmodule -lib/swift/android/x86_64/glibc.modulemap +lib/swift/android/x86_64/android.modulemap lib/swift/android/x86_64/libswiftCxx.a -lib/swift/android/x86_64/SwiftGlibc.h +lib/swift/android/x86_64/libswiftCxxStdlib.a +lib/swift/android/x86_64/SwiftAndroidNDK.h +lib/swift/android/x86_64/SwiftBionic.h lib/swift/android/x86_64/swiftrt.o -lib/swift/android/*.swiftmodule/x86_64-* +lib/swift/android/*.swiftmodule/x86_64* lib/swift_static/android/x86_64/ -lib/swift_static/android/*.swiftmodule/x86_64-* +lib/swift_static/android/*.swiftmodule/x86_64* " TERMUX_SUBPKG_PLATFORM_INDEPENDENT=true TERMUX_SUBPKG_DEPENDS="swift-runtime-x86-64" diff --git a/packages/swift/swift-syntax.patch b/packages/swift/swift-syntax.patch new file mode 100644 index 00000000000000..f131bd5c363434 --- /dev/null +++ b/packages/swift/swift-syntax.patch @@ -0,0 +1,77 @@ +commit 031e9eddc214ac4b4b34e88013dc8fe2e6c150c2 +Date: Tue Aug 6 13:52:27 2024 +0530 + + [Android] Use the new overlay and Bionic module from Swift 6 + + The new overlay was merged into Swift 6 in swiftlang/swift#74758. + +diff --git a/swift-syntax/Sources/SwiftLibraryPluginProvider/LibraryPluginProvider.swift b/swift-syntax/Sources/SwiftLibraryPluginProvider/LibraryPluginProvider.swift +index eb06cca2..44be07e2 100644 +--- a/swift-syntax/Sources/SwiftLibraryPluginProvider/LibraryPluginProvider.swift ++++ b/swift-syntax/Sources/SwiftLibraryPluginProvider/LibraryPluginProvider.swift +@@ -22,6 +22,8 @@ private import Darwin + private import Glibc + #elseif canImport(Musl) + private import Musl ++#elseif canImport(Android) ++private import Android + #endif + #else + import SwiftSyntaxMacros +@@ -137,7 +139,7 @@ private func _loadLibrary(_ path: String) throws -> UnsafeMutableRawPointer { + #else + private func _loadLibrary(_ path: String) throws -> UnsafeMutableRawPointer { + guard let dlHandle = dlopen(path, RTLD_LAZY | RTLD_LOCAL) else { +- throw LibraryPluginError(message: "loader error: \(String(cString: dlerror()))") ++ throw LibraryPluginError(message: "loader error: \(String(cString: dlerror()!))") + } + return dlHandle + } +diff --git a/swift-syntax/Sources/SwiftSyntax/SyntaxText.swift b/swift-syntax/Sources/SwiftSyntax/SyntaxText.swift +index 574a67fc..4d877962 100644 +--- a/swift-syntax/Sources/SwiftSyntax/SyntaxText.swift ++++ b/swift-syntax/Sources/SwiftSyntax/SyntaxText.swift +@@ -15,6 +15,8 @@ + private import Darwin + #elseif canImport(Glibc) + private import Glibc ++#elseif canImport(Bionic) ++private import Bionic + #elseif canImport(Musl) + private import Musl + #endif +@@ -281,6 +283,8 @@ private func compareMemory( + return Darwin.memcmp(s1, s2, count) == 0 + #elseif canImport(Glibc) + return Glibc.memcmp(s1, s2, count) == 0 ++ #elseif canImport(Bionic) ++ return Bionic.memcmp(s1, s2, count) == 0 + #else + return UnsafeBufferPointer(start: s1, count: count) + .elementsEqual(UnsafeBufferPointer(start: s2, count: count)) +diff --git a/swift-syntax/SwiftParserCLI/Sources/swift-parser-cli/TerminalUtils.swift b/swift-syntax/SwiftParserCLI/Sources/swift-parser-cli/TerminalUtils.swift +index cb905a27..841e529b 100644 +--- a/swift-syntax/SwiftParserCLI/Sources/swift-parser-cli/TerminalUtils.swift ++++ b/swift-syntax/SwiftParserCLI/Sources/swift-parser-cli/TerminalUtils.swift +@@ -14,6 +14,8 @@ + import Glibc + #elseif canImport(Musl) + import Musl ++#elseif canImport(Android) ++import Android + #elseif os(Windows) + import CRT + #else +diff --git a/swift-syntax/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/ProcessRunner.swift b/swift-syntax/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/ProcessRunner.swift +index 526f4a2f..e88611cb 100644 +--- a/swift-syntax/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/ProcessRunner.swift ++++ b/swift-syntax/SwiftSyntaxDevUtils/Sources/swift-syntax-dev-utils/common/ProcessRunner.swift +@@ -24,7 +24,7 @@ class SigIntListener { + /// Registers a `SIGINT` signal handler that forwards `SIGINT` to all + /// subprocesses that are registered in `runningSubprocesses` + static func registerSigIntSubprocessTerminationHandler() { +- #if canImport(Darwin) || canImport(Glibc) ++ #if canImport(Darwin) || canImport(Glibc) || canImport(Bionic) + signal(SIGINT) { _ in + SigIntListener.hasReceivedSigInt = true + for process in SigIntListener.runningSubprocesses { diff --git a/packages/swift/swift-utils-build-script-impl-flags.patch b/packages/swift/swift-utils-build-script-impl-flags.patch index 3b3633d58ff1f4..ebc7659383a6c1 100644 --- a/packages/swift/swift-utils-build-script-impl-flags.patch +++ b/packages/swift/swift-utils-build-script-impl-flags.patch @@ -10,11 +10,9 @@ index b1d060328bc..218c9215260 100755 if [[ ! "${SKIP_BUILD_ANDROID}" ]] || [[ $(is_cross_tools_host ${host}) && "${host}" == "android-"* ]]; then cmake_options=( -@@ -1733,7 +1734,9 @@ - -DSWIFT_ANDROID_NDK_PATH:STRING="${ANDROID_NDK}" +@@ -1733,6 +1734,7 @@ -DSWIFT_ANDROID_DEPLOY_DEVICE_PATH:STRING="${ANDROID_DEPLOY_DEVICE_PATH}" -DSWIFT_SDK_ANDROID_ARCHITECTURES:STRING="${ANDROID_ARCH}" -+ -DBRIDGING_MODE:STRING="PURE" ) + cross_c_flags="$CFLAGS --target=$CCTERMUX_HOST_PLATFORM" fi @@ -82,7 +80,16 @@ index b1d060328bc..218c9215260 100755 fi ;; esac -@@ -2537,6 +2554,9 @@ +@@ -2412,7 +2412,7 @@ for host in "${ALL_HOSTS[@]}"; do + + ;; + foundation_macros) +- if [[ ${host} == "macosx"* ]]; then ++ if [[ ${host} == "macosx"* ]] || [[ "${host}" == "android-"* ]]; then + echo "Skipping Foundation Macros on OS X -- Foundation is part of the OS on this platform" + continue + fi +@@ -2537,11 +2554,15 @@ # https://cmake.org/cmake/help/latest/command/find_package.html cmake_options+=( -DCMAKE_FIND_ROOT_PATH:PATH="${CROSS_COMPILE_DEPS_PATH}" @@ -92,6 +99,12 @@ index b1d060328bc..218c9215260 100755 ) fi if [[ "${host}" == "android-"* ]]; then + cmake_options+=( + -DCMAKE_HAVE_LIBC_PTHREAD=True ++ -DSwiftFoundation_MODULE_TRIPLE:STRING="${ANDROID_ARCH}-unknown-linux-android" + ) + fi + ;; @@ -2583,6 +2603,11 @@ ) if [[ $(is_cross_tools_host ${host}) ]] ; then @@ -104,26 +117,28 @@ index b1d060328bc..218c9215260 100755 fi ;; esac -@@ -2929,7 +2999,20 @@ for host in "${ALL_HOSTS[@]}"; do +@@ -3106,7 +3131,14 @@ for host in "${ALL_HOSTS[@]}"; do if [[ -z "${INSTALL_LLBUILD}" ]] ; then continue fi - INSTALL_TARGETS="install-swift-build-tool install-libllbuildSwift" + INSTALL_TARGETS="install-libllbuildSwift" -+ # Remove most libdispatch products before building the package manager. -+ rm -rf @TERMUX_PREFIX@/lib/swift{,_static}/{Block,os} -+ rm @TERMUX_PREFIX@/lib/swift{,_static}/dispatch/*.h ++ # Use the system libdispatch headers instead. + sed -i -e "s%dispatch\.h%@TERMUX_PREFIX@/include/dispatch/dispatch.h%" \ + -e "s%introspection\.h%@TERMUX_PREFIX@/include/dispatch/introspection.h%" \ + @TERMUX_PREFIX@/lib/swift/dispatch/module.modulemap + sed -i -e "s%dispatch\.h%@TERMUX_PREFIX@/include/dispatch/dispatch.h%" \ + -e "s%introspection\.h%@TERMUX_PREFIX@/include/dispatch/introspection.h%" \ + @TERMUX_PREFIX@/lib/swift_static/dispatch/module.modulemap -+ if [[ -z "${ANDROID_DATA}" ]] ; then -+ mv @TERMUX_PREFIX@/lib/swift/${host/-//}/glibc.modulemap @TERMUX_PREFIX@/glibc-native.modulemap -+ cp $(build_directory ${host} swift)/lib/swift/${host/-//}/glibc.modulemap @TERMUX_PREFIX@/lib/swift/${host/-//}/glibc.modulemap -+ fi ;; # Products from this here install themselves; they don't fall-through. lldb) - if [[ -z "${INSTALL_LLDB}" ]] ; then +@@ -3131,7 +3163,7 @@ for host in "${ALL_HOSTS[@]}"; do + ;; + foundation|foundation_static|foundation_macros) + # FIXME: Foundation doesn't build from the script on OS X +- if [[ ${host} == "macosx"* ]]; then ++ if [[ ${host} == "macosx"* ]] || [[ "${host}" == "android-"* && "${product}" == "foundation_macros" ]]; then + echo "Skipping Foundation on OS X -- Foundation does not build for this platform" + continue + fi diff --git a/packages/swift/trigger-command b/packages/swift/trigger-command index 570d2b68c8dba1..7824998cbf41e7 100644 --- a/packages/swift/trigger-command +++ b/packages/swift/trigger-command @@ -4,9 +4,11 @@ if [ x"$native_triple" != x"$swift_runtime_triple" ]; then fi install_path=$install_path/lib -for so in Foundation FoundationNetworking FoundationXML XCTest swiftCore swiftDispatch \ - swiftDistributed swiftGlibc swiftObservation swiftRegexBuilder swiftRemoteMirror \ - swiftSwiftOnoneSupport swift_Concurrency swift_Differentiation swift_RegexParser swift_StringProcessing +for so in _FoundationICU Foundation FoundationEssentials FoundationInternationalization \ + FoundationNetworking FoundationXML XCTest swiftCore swiftDispatch \ + swiftDistributed swiftAndroid swiftObservation swiftRegexBuilder swiftRemoteMirror \ + swiftSwiftOnoneSupport swiftSynchronization swift_Builtin_float swift_Concurrency \ + swift_Differentiation swift_math swift_RegexParser swift_StringProcessing do @COMMAND@ done diff --git a/scripts/build/setup/termux_setup_swift.sh b/scripts/build/setup/termux_setup_swift.sh index 33a4e632515202..abef1c7dcd5212 100644 --- a/scripts/build/setup/termux_setup_swift.sh +++ b/scripts/build/setup/termux_setup_swift.sh @@ -19,7 +19,7 @@ termux_setup_swift() { termux_download \ https://download.swift.org/swift-$TERMUX_SWIFT_VERSION-release/ubuntu2404/swift-$TERMUX_SWIFT_VERSION-$SWIFT_RELEASE/$SWIFT_BIN.tar.gz \ $SWIFT_TAR \ - e1a56752d80b2b759d9ccceae548bd8bdf21674c2b807b0a2738fdb0ba7034ef + 711d1d9e81c6d0dbc36202d9bc9bd491cc5fa79854fd0205ba27f40122b6ad5f (cd $TERMUX_PKG_TMPDIR ; tar xf $SWIFT_TAR ; mv $SWIFT_BIN $SWIFT_FOLDER; rm $SWIFT_TAR) fi