diff --git a/CMakeLists.txt b/CMakeLists.txt index 18cf581a64f03..c8f9999c2a173 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -458,6 +458,12 @@ if(SWIFT_PATH_TO_CMARK_BUILD) endif() message(STATUS "") +if("${SWIFT_NATIVE_LLVM_TOOLS_PATH}" STREQUAL "") + set(SWIFT_CROSS_COMPILING FALSE) +else() + set(SWIFT_CROSS_COMPILING TRUE) +endif() + include(SwiftSharedCMakeConfig) # NOTE: We include this before SwiftComponents as it relies on some LLVM CMake @@ -487,16 +493,6 @@ if(NOT SWIFT_LIPO) find_toolchain_tool(SWIFT_LIPO "${SWIFT_DARWIN_XCRUN_TOOLCHAIN}" lipo) endif() -# Reset CMAKE_SYSTEM_PROCESSOR if not cross-compiling. -# CMake refuses to use `uname -m` on OS X -# http://public.kitware.com/Bug/view.php?id=10326 -if(NOT CMAKE_CROSSCOMPILING AND CMAKE_SYSTEM_PROCESSOR STREQUAL "i386") - execute_process( - COMMAND "uname" "-m" - OUTPUT_VARIABLE CMAKE_SYSTEM_PROCESSOR - OUTPUT_STRIP_TRAILING_WHITESPACE) -endif() - get_filename_component(SWIFT_SOURCE_DIR ${CMAKE_CURRENT_SOURCE_DIR} REALPATH) set(SWIFT_BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}") set(SWIFT_CMAKE_DIR "${CMAKE_CURRENT_SOURCE_DIR}/cmake/modules") diff --git a/README.md b/README.md index c219cecac3ab6..8b090a70578d4 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ Please make sure you use Python 2.x. Python 3.x is not supported currently. #### macOS -To build for macOS, you need [Xcode 11.4](https://developer.apple.com/xcode/resources/). +To build for macOS, you need [Xcode 12 beta](https://developer.apple.com/xcode/resources/). The required version of Xcode changes frequently, and is often a beta release. Check this document or the host information on for the current required version. @@ -241,7 +241,7 @@ various products. These incremental builds are a big timesaver when developing and debugging. cd ${SWIFT_BUILD_DIR} - ninja swift + ninja swift-frontend This will build the Swift compiler, but will not rebuild the standard library or any other target. Building the `swift-stdlib` target as an additional layer of @@ -258,7 +258,7 @@ To open the Swift project in Xcode, open `${SWIFT_BUILD_DIR}/Swift.xcodeproj`. It will auto-create a *lot* of schemes for all of the available targets. A common debug flow would involve: - - Select the 'swift' scheme. + - Select the 'swift-frontend' scheme. - Pull up the scheme editor (⌘⇧<). - Select the 'Arguments' tab and click the '+'. - Add the command line options. diff --git a/benchmark/cmake/modules/AddSwiftBenchmarkSuite.cmake b/benchmark/cmake/modules/AddSwiftBenchmarkSuite.cmake index fb20e12689359..ea36002f8eabe 100644 --- a/benchmark/cmake/modules/AddSwiftBenchmarkSuite.cmake +++ b/benchmark/cmake/modules/AddSwiftBenchmarkSuite.cmake @@ -105,7 +105,7 @@ macro(configure_build) endmacro() macro(configure_sdks_darwin) - set(macosx_arch "x86_64") + set(macosx_arch "x86_64" "arm64") set(iphoneos_arch "arm64" "arm64e" "armv7") set(appletvos_arch "arm64") set(watchos_arch "armv7k") @@ -609,11 +609,7 @@ function (swift_benchmark_compile_archopts) if(is_darwin) # If host == target. - if("${BENCH_COMPILE_ARCHOPTS_PLATFORM}" STREQUAL "macosx") - set(OUTPUT_EXEC "${benchmark-bin-dir}/Benchmark_${BENCH_COMPILE_ARCHOPTS_OPT}") - else() - set(OUTPUT_EXEC "${benchmark-bin-dir}/Benchmark_${BENCH_COMPILE_ARCHOPTS_OPT}-${target}") - endif() + set(OUTPUT_EXEC "${benchmark-bin-dir}/Benchmark_${BENCH_COMPILE_ARCHOPTS_OPT}-${target}") else() # If we are on Linux, we do not support cross compiling. set(OUTPUT_EXEC "${benchmark-bin-dir}/Benchmark_${BENCH_COMPILE_ARCHOPTS_OPT}") @@ -660,8 +656,11 @@ function (swift_benchmark_compile_archopts) "-m${triple_platform}-version-min=${ver}" "-lobjc" "-L${SWIFT_LIBRARY_PATH}/${BENCH_COMPILE_ARCHOPTS_PLATFORM}" + "-L${sdk}/usr/lib/swift" "-Xlinker" "-rpath" "-Xlinker" "${SWIFT_LINK_RPATH}" + "-Xlinker" "-rpath" + "-Xlinker" "/usr/lib/swift" ${bench_library_objects} ${bench_driver_objects} ${ld64_add_ast_path_opts} @@ -694,7 +693,7 @@ function(swift_benchmark_compile) cmake_parse_arguments(SWIFT_BENCHMARK_COMPILE "" "PLATFORM" "" ${ARGN}) if(NOT SWIFT_BENCHMARK_BUILT_STANDALONE) - set(stdlib_dependencies "swift") + set(stdlib_dependencies "swift-frontend") foreach(stdlib_dependency ${UNIVERSAL_LIBRARY_NAMES_${SWIFT_BENCHMARK_COMPILE_PLATFORM}}) string(FIND "${stdlib_dependency}" "Unittest" find_output) if("${find_output}" STREQUAL "-1") diff --git a/benchmark/single-source/FloatingPointParsing.swift b/benchmark/single-source/FloatingPointParsing.swift index 70aa335af544f..0b1f01186dd52 100644 --- a/benchmark/single-source/FloatingPointParsing.swift +++ b/benchmark/single-source/FloatingPointParsing.swift @@ -242,7 +242,7 @@ public func run_ParseDoubleExp(_ N: Int) { @inline(never) public func run_ParseFloat80Exp(_ N: Int) { - #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(Linux) +#if canImport(Darwin) || os(Linux) // On Darwin, long double is Float80 on x86, and Double otherwise. // On Linux, Float80 is at aleast available on x86. #if arch(x86_64) || arch(i386) @@ -263,7 +263,7 @@ public func run_ParseDoubleUniform(_ N: Int) { @inline(never) public func run_ParseFloat80Uniform(_ N: Int) { - #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(Linux) +#if canImport(Darwin) || os(Linux) // On Darwin, long double is Float80 on x86, and Double otherwise. // On Linux, Float80 is at aleast available on x86. #if arch(x86_64) || arch(i386) diff --git a/benchmark/single-source/FloatingPointPrinting.swift b/benchmark/single-source/FloatingPointPrinting.swift index 06f6c494f8c27..08961077c9bf2 100644 --- a/benchmark/single-source/FloatingPointPrinting.swift +++ b/benchmark/single-source/FloatingPointPrinting.swift @@ -106,7 +106,7 @@ public func run_FloatingPointPrinting_Double_description_small(_ N: Int) { @inline(never) public func run_FloatingPointPrinting_Float80_description_small(_ N: Int) { -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(Linux) +#if canImport(Darwin) || os(Linux) // On Darwin, long double is Float80 on x86, and Double otherwise. // On Linux, Float80 is at aleast available on x86. #if arch(x86_64) || arch(i386) @@ -152,7 +152,7 @@ public func run_FloatingPointPrinting_Double_description_uniform(_ N: Int) { @inline(never) public func run_FloatingPointPrinting_Float80_description_uniform(_ N: Int) { -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(Linux) +#if canImport(Darwin) || os(Linux) // On Darwin, long double is Float80 on x86, and Double otherwise. // On Linux, Float80 is at aleast available on x86. #if arch(x86_64) || arch(i386) @@ -202,7 +202,7 @@ public func run_FloatingPointPrinting_Double_interpolated(_ N: Int) { @inline(never) public func run_FloatingPointPrinting_Float80_interpolated(_ N: Int) { -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(Linux) +#if canImport(Darwin) || os(Linux) // On Darwin, long double is Float80 on x86, and Double otherwise. // On Linux, Float80 is at aleast available on x86. #if arch(x86_64) || arch(i386) diff --git a/benchmark/single-source/NSStringConversion.swift b/benchmark/single-source/NSStringConversion.swift index 9b51720861c3e..d57415e3498c8 100644 --- a/benchmark/single-source/NSStringConversion.swift +++ b/benchmark/single-source/NSStringConversion.swift @@ -11,7 +11,7 @@ //===----------------------------------------------------------------------===// // -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if canImport(Darwin) import TestsUtils import Foundation diff --git a/benchmark/single-source/Substring.swift b/benchmark/single-source/Substring.swift index 7d4c7a7906459..e6ccccd667b54 100644 --- a/benchmark/single-source/Substring.swift +++ b/benchmark/single-source/Substring.swift @@ -17,6 +17,8 @@ public let SubstringTest = [ BenchmarkInfo(name: "EqualSubstringString", runFunction: run_EqualSubstringString, tags: [.validation, .api, .String]), BenchmarkInfo(name: "EqualSubstringSubstring", runFunction: run_EqualSubstringSubstring, tags: [.validation, .api, .String]), BenchmarkInfo(name: "EqualSubstringSubstringGenericEquatable", runFunction: run_EqualSubstringSubstringGenericEquatable, tags: [.validation, .api, .String]), + BenchmarkInfo(name: "SubstringRemoveFirst1", runFunction: run_SubstringRemoveFirst1, tags: [.validation, .api, .String]), + BenchmarkInfo(name: "SubstringRemoveLast1", runFunction: run_SubstringRemoveLast1, tags: [.validation, .api, .String]), BenchmarkInfo(name: "LessSubstringSubstring", runFunction: run_LessSubstringSubstring, tags: [.validation, .api, .String]), BenchmarkInfo(name: "LessSubstringSubstringGenericComparable", runFunction: run_LessSubstringSubstringGenericComparable, tags: [.validation, .api, .String]), BenchmarkInfo(name: "StringFromLongWholeSubstring", runFunction: run_StringFromLongWholeSubstring, tags: [.validation, .api, .String]), @@ -34,6 +36,8 @@ let longWide = "fὢasὢodὢijὢadὢolὢsjὢalὢsdὢjlὢasὢdfὢijὢ let (s1, ss1) = equivalentWithDistinctBuffers() let (s2, ss2) = equivalentWithDistinctBuffers() +let quiteLong = String(repeating: "0", count: 10_000)[...] + @inline(never) public func run_SubstringFromLongString(_ N: Int) { var s = longWide @@ -126,6 +130,24 @@ public func run_EqualSubstringSubstringGenericEquatable(_ N: Int) { } } +@inline(never) +public func run_SubstringRemoveFirst1(_ N: Int) { + for _ in 1...N { + var s = quiteLong + s.removeFirst(1) + blackHole(s.first == "0") + } +} + +@inline(never) +public func run_SubstringRemoveLast1(_ N: Int) { + for _ in 1...N { + var s = quiteLong + s.removeLast(1) + blackHole(s.first == "0") + } +} + /* func checkEqual(_ x: T, _ y: U) where T : StringProtocol, U : StringProtocol { diff --git a/benchmark/utils/main.swift b/benchmark/utils/main.swift index cbf8aaedaa25c..b4791ad6208e7 100644 --- a/benchmark/utils/main.swift +++ b/benchmark/utils/main.swift @@ -103,12 +103,12 @@ import NibbleSort import NIOChannelPipeline import NSDictionaryCastToSwift import NSError -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if canImport(Darwin) import NSStringConversion #endif import NopDeinit import ObjectAllocation -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if canImport(Darwin) import ObjectiveCBridging import ObjectiveCBridgingStubs #if !(SWIFT_PACKAGE || Xcode) @@ -287,14 +287,14 @@ registerBenchmark(MonteCarloE) registerBenchmark(MonteCarloPi) registerBenchmark(NSDictionaryCastToSwift) registerBenchmark(NSErrorTest) -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if canImport(Darwin) registerBenchmark(NSStringConversion) #endif registerBenchmark(NibbleSort) registerBenchmark(NIOChannelPipeline) registerBenchmark(NopDeinit) registerBenchmark(ObjectAllocation) -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if canImport(Darwin) registerBenchmark(ObjectiveCBridging) registerBenchmark(ObjectiveCBridgingStubs) #if !(SWIFT_PACKAGE || Xcode) diff --git a/cmake/modules/AddSwift.cmake b/cmake/modules/AddSwift.cmake index cbef2b8534d4f..1d97caa2e09bd 100644 --- a/cmake/modules/AddSwift.cmake +++ b/cmake/modules/AddSwift.cmake @@ -23,7 +23,7 @@ function(_swift_gyb_target_sources target scope) add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/${generated} COMMAND - $ ${SWIFT_SOURCE_DIR}/utils/gyb -D CMAKE_SIZEOF_VOID_P=${CMAKE_SIZEOF_VOID_P} ${SWIFT_GYB_FLAGS} -o ${CMAKE_CURRENT_BINARY_DIR}/${generated}.tmp ${absolute} + $ ${SWIFT_SOURCE_DIR}/utils/gyb -D CMAKE_SIZEOF_VOID_P=${CMAKE_SIZEOF_VOID_P} ${SWIFT_GYB_FLAGS} -o ${CMAKE_CURRENT_BINARY_DIR}/${generated}.tmp ${absolute} COMMAND ${CMAKE_COMMAND} -E copy_if_different ${CMAKE_CURRENT_BINARY_DIR}/${generated}.tmp ${CMAKE_CURRENT_BINARY_DIR}/${generated} COMMAND @@ -88,6 +88,7 @@ function(_add_host_variant_c_compile_link_flags name) MACCATALYST_BUILD_FLAVOR "" DEPLOYMENT_VERSION "${DEPLOYMENT_VERSION}") target_compile_options(${name} PRIVATE -target;${target}) + target_link_options(${name} PRIVATE -target;${target}) endif() set(_sysroot @@ -120,6 +121,7 @@ function(_add_host_variant_c_compile_link_flags name) _compute_lto_flag("${SWIFT_TOOLS_ENABLE_LTO}" _lto_flag_out) if (_lto_flag_out) target_compile_options(${name} PRIVATE ${_lto_flag_out}) + target_link_options(${name} PRIVATE ${_lto_flag_out}) endif() endfunction() @@ -470,6 +472,7 @@ function(add_swift_host_library name) _add_host_variant_c_compile_flags(${name}) _add_host_variant_link_flags(${name}) + _add_host_variant_c_compile_link_flags(${name}) _set_target_prefix_and_suffix(${name} "${libkind}" "${SWIFT_HOST_VARIANT_SDK}") # Set compilation and link flags. @@ -526,11 +529,6 @@ function(add_swift_host_library name) target_link_options(${name} PRIVATE "LINKER:-current_version,${SWIFT_COMPILER_VERSION}") endif() - - get_target_triple(target target_variant "${SWIFT_HOST_VARIANT_SDK}" "${SWIFT_HOST_VARIANT_ARCH}" - MACCATALYST_BUILD_FLAVOR "" - DEPLOYMENT_VERSION "${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_DEPLOYMENT_VERSION}") - target_link_options(${name} PRIVATE -target;${target}) endif() add_dependencies(dev ${name}) @@ -575,6 +573,7 @@ function(add_swift_host_tool executable) add_executable(${executable} ${ASHT_UNPARSED_ARGUMENTS}) _add_host_variant_c_compile_flags(${executable}) _add_host_variant_link_flags(${executable}) + _add_host_variant_c_compile_link_flags(${executable}) target_link_directories(${executable} PRIVATE ${SWIFTLIB_DIR}/${SWIFT_SDK_${SWIFT_HOST_VARIANT_SDK}_LIB_SUBDIR}) add_dependencies(${executable} ${LLVM_COMMON_DEPENDS}) diff --git a/cmake/modules/AddSwiftUnittests.cmake b/cmake/modules/AddSwiftUnittests.cmake index 811b455bd3ed2..531916e071b79 100644 --- a/cmake/modules/AddSwiftUnittests.cmake +++ b/cmake/modules/AddSwiftUnittests.cmake @@ -57,9 +57,11 @@ function(add_swift_unittest test_dirname) _ENABLE_EXTENDED_ALIGNED_STORAGE) endif() - if(SWIFT_USE_LINKER) - set_property(TARGET "${test_dirname}" APPEND_STRING PROPERTY - LINK_FLAGS " -fuse-ld=${SWIFT_USE_LINKER}") + if(NOT SWIFT_COMPILER_IS_MSVC_LIKE) + if(SWIFT_USE_LINKER) + target_link_options(${test_dirname} PRIVATE + -fuse-ld=${SWIFT_USE_LINKER}$<$:.exe>) + endif() endif() if(SWIFT_ANALYZE_CODE_COVERAGE) diff --git a/cmake/modules/DarwinSDKs.cmake b/cmake/modules/DarwinSDKs.cmake index 23fa42a9bd43e..5ad1e32d1d8a1 100644 --- a/cmake/modules/DarwinSDKs.cmake +++ b/cmake/modules/DarwinSDKs.cmake @@ -4,17 +4,34 @@ option(SWIFT_ENABLE_IOS32 if(SWIFT_ENABLE_IOS32) set(SUPPORTED_IOS_ARCHS "armv7;armv7s;arm64;arm64e") -set(SUPPORTED_IOS_SIMULATOR_ARCHS "i386;x86_64") +set(SUPPORTED_IOS_SIMULATOR_ARCHS "i386;x86_64;arm64") else() set(SUPPORTED_IOS_ARCHS "arm64;arm64e") -set(SUPPORTED_IOS_SIMULATOR_ARCHS "x86_64") +set(SUPPORTED_IOS_SIMULATOR_ARCHS "x86_64;arm64") endif() set(SUPPORTED_TVOS_ARCHS "arm64") -set(SUPPORTED_TVOS_SIMULATOR_ARCHS "x86_64") +set(SUPPORTED_TVOS_SIMULATOR_ARCHS "x86_64;arm64") set(SUPPORTED_WATCHOS_ARCHS "armv7k") -set(SUPPORTED_WATCHOS_SIMULATOR_ARCHS "i386") -set(SUPPORTED_OSX_ARCHS "x86_64") +set(SUPPORTED_WATCHOS_SIMULATOR_ARCHS "i386;arm64") +set(SUPPORTED_OSX_ARCHS "x86_64;arm64;arm64e") + +# Get the SDK version from SDKSettings. +execute_process( + COMMAND "defaults" "read" "${CMAKE_OSX_SYSROOT}/SDKSettings.plist" "Version" + OUTPUT_VARIABLE SWIFT_OSX_SDK_VERSION + OUTPUT_STRIP_TRAILING_WHITESPACE) + +# Remove the last component, if any. e.g. 10.15.26 -> 10.15 +string(REGEX REPLACE "\([0-9]*[.][0-9]*\)[.][0-9]*" "\\1" + SWIFT_OSX_SDK_VERSION "${SWIFT_OSX_SDK_VERSION}") + +if (${SWIFT_OSX_SDK_VERSION} STREQUAL "10.14" OR + ${SWIFT_OSX_SDK_VERSION} STREQUAL "10.15") + set(SUPPORTED_OSX_ARCHS "x86_64") +else() + set(SUPPORTED_OSX_ARCHS "x86_64;arm64e") +endif() is_sdk_requested(OSX swift_build_osx) if(swift_build_osx) diff --git a/cmake/modules/SwiftConfigureSDK.cmake b/cmake/modules/SwiftConfigureSDK.cmake index 09d45cc3a34a3..52c08025e62a0 100644 --- a/cmake/modules/SwiftConfigureSDK.cmake +++ b/cmake/modules/SwiftConfigureSDK.cmake @@ -85,6 +85,38 @@ function(_report_sdk prefix) message(STATUS "") endfunction() +# Remove architectures not supported by the SDK from the given list. +function(remove_sdk_unsupported_archs name os sdk_path architectures_var) + execute_process(COMMAND + /usr/libexec/PlistBuddy -c "Print :SupportedTargets:${os}:Archs" ${sdk_path}/SDKSettings.plist + OUTPUT_VARIABLE sdk_supported_archs + RESULT_VARIABLE plist_error) + + if (NOT plist_error EQUAL 0) + message(STATUS "${os} SDK at ${sdk_path} does not publish its supported architectures") + return() + endif() + + set(architectures) + foreach(arch ${${architectures_var}}) + if(sdk_supported_archs MATCHES "${arch}\n") + list(APPEND architectures ${arch}) + elseif(arch MATCHES "^armv7(s)?$" AND os STREQUAL "iphoneos") + # 32-bit iOS is not listed explicitly in SDK settings. + message(STATUS "Assuming ${name} SDK at ${sdk_path} supports architecture ${arch}") + list(APPEND architectures ${arch}) + elseif(arch STREQUAL "i386" AND os STREQUAL "iphonesimulator") + # 32-bit iOS simulatoris not listed explicitly in SDK settings. + message(STATUS "Assuming ${name} SDK at ${sdk_path} supports architecture ${arch}") + list(APPEND architectures ${arch}) + else() + message(STATUS "${name} SDK at ${sdk_path} does not support architecture ${arch}") + endif() + endforeach() + + set("${architectures_var}" ${architectures} PARENT_SCOPE) +endfunction() + # Configure an SDK # # Usage: @@ -164,6 +196,9 @@ macro(configure_sdk_darwin SWIFT_SDK_${prefix}_ARCHITECTURES) # result endif() + # Remove any architectures not supported by the SDK. + remove_sdk_unsupported_archs(${name} ${xcrun_name} ${SWIFT_SDK_${prefix}_PATH} SWIFT_SDK_${prefix}_ARCHITECTURES) + list_intersect( "${SWIFT_DARWIN_MODULE_ARCHS}" # lhs "${architectures}" # rhs diff --git a/cmake/modules/SwiftHandleGybSources.cmake b/cmake/modules/SwiftHandleGybSources.cmake index f8dc984ea0c68..e74489f56989f 100644 --- a/cmake/modules/SwiftHandleGybSources.cmake +++ b/cmake/modules/SwiftHandleGybSources.cmake @@ -1,8 +1,6 @@ include(SwiftAddCustomCommandTarget) include(SwiftSetIfArchBitness) -find_package(Python2 COMPONENTS Interpreter REQUIRED) - # Create a target to process single gyb source with the 'gyb' tool. # # handle_gyb_source_single( @@ -60,7 +58,7 @@ function(handle_gyb_source_single dependency_out_var_name) COMMAND "${CMAKE_COMMAND}" -E make_directory "${dir}" COMMAND - "$" "${gyb_tool}" ${SWIFT_GYB_FLAGS} ${GYB_SINGLE_FLAGS} -o "${GYB_SINGLE_OUTPUT}.tmp" "${GYB_SINGLE_SOURCE}" + "$" "${gyb_tool}" ${SWIFT_GYB_FLAGS} ${GYB_SINGLE_FLAGS} -o "${GYB_SINGLE_OUTPUT}.tmp" "${GYB_SINGLE_SOURCE}" COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${GYB_SINGLE_OUTPUT}.tmp" "${GYB_SINGLE_OUTPUT}" COMMAND diff --git a/cmake/modules/SwiftSharedCMakeConfig.cmake b/cmake/modules/SwiftSharedCMakeConfig.cmake index 5bddf37d86816..c4c15084fe902 100644 --- a/cmake/modules/SwiftSharedCMakeConfig.cmake +++ b/cmake/modules/SwiftSharedCMakeConfig.cmake @@ -58,7 +58,7 @@ macro(swift_common_standalone_build_config_llvm product) fix_imported_targets_for_xcode("${LLVM_EXPORTED_TARGETS}") endif() - if(NOT CMAKE_CROSSCOMPILING) + if(NOT CMAKE_CROSSCOMPILING AND NOT SWIFT_CROSS_COMPILING) set(${product}_NATIVE_LLVM_TOOLS_PATH "${LLVM_TOOLS_BINARY_DIR}") endif() diff --git a/docs/ABI/TypeMetadata.rst b/docs/ABI/TypeMetadata.rst index a74ad24ec5899..533b387e51594 100644 --- a/docs/ABI/TypeMetadata.rst +++ b/docs/ABI/TypeMetadata.rst @@ -222,13 +222,18 @@ classes. record is stored at **offset 0**, in place of an integer kind discriminator. - The **super pointer** pointing to the metadata record for the superclass is stored at **offset 1**. If the class is a root class, it is null. -- Two words are reserved for use by the Objective-C runtime at **offset 2** - and **offset 3**. -- The **rodata pointer** is stored at **offset 4**; it points to an Objective-C - compatible rodata record for the class. This pointer value includes a tag. +- On platforms which support Objective-C interoperability, two words are + reserved for use by the Objective-C runtime at **offset 2** and **offset + 3**; on other platforms, nothing is reserved. +- On platforms which support Objective-C interoperability, the **rodata + pointer** is stored at **offset 4**; on other platforms, it is not present. + The rodata pointer points to an Objective-C compatible rodata record for the + class. This pointer value includes a tag. The **low bit is always set to 1** for Swift classes and always set to 0 for Objective-C classes. -- The **class flags** are a 32-bit field at **offset 5**. +- The **class flags** are a 32-bit field at **offset 5** on platforms which + support Objective-C interoperability; on other platforms, the field is at + **offset 2**. - The **instance address point** is a 32-bit field following the class flags. A pointer to an instance of this class points this number of bytes after the beginning of the instance. @@ -246,8 +251,11 @@ classes. object size. This is the number of bytes of storage in the class metadata object. - The `nominal type descriptor`_ for the most-derived class type is referenced - at an offset immediately following the class object address point. This is - **offset 8** on a 64-bit platform or **offset 11** on a 32-bit platform. + at an offset immediately following the class object address point. On 64-bit + and 32-bit platforms which support Objective-C interoperability, this is, + respectively, at **offset 8** and at **offset 11**; in platforms that do not + support Objective-C interoperability, this is, respectively, at **offset 5** + and at **offset 8**. - For each Swift class in the class's inheritance hierarchy, in order starting from the root class and working down to the most derived class, the following fields are present: diff --git a/docs/Android.md b/docs/Android.md index d0bbd19180910..77d6b46479d2d 100644 --- a/docs/Android.md +++ b/docs/Android.md @@ -103,10 +103,9 @@ $ NDK_PATH="path/to/android-ndk21" $ build/Ninja-ReleaseAssert/swift-linux-x86_64/bin/swiftc \ # The Swift compiler built in the previous step. # The location of the tools used to build Android binaries -tools-directory ${NDK_PATH}/toolchains/llvm/prebuilt/linux-x86_64/bin/ \ - -target armv7a-none-linux-androideabi \ # Targeting android-armv7. - -sdk ${NDK_PATH}/platforms/android-21/arch-arm \ # Use the same architecture and API version as you used to build the stdlib in the previous step. - -Xclang-linker -nostdlib++ \ # Don't link libc++, and supply the path to libgcc. + -target armv7a-none-linux-androideabi \ # Targeting android-armv7, and supply the path to libgcc. -L ${NDK_PATH}/toolchains/arm-linux-androideabi-4.9/prebuilt/linux-x86_64/lib/gcc/arm-linux-androideabi/4.9.x/armv7-a \ + -sdk ${NDK_PATH}/platforms/android-21/arch-arm \ # Use the same architecture and API version as you used to build the stdlib in the previous step. hello.swift ``` diff --git a/docs/DifferentiableProgramming.md b/docs/DifferentiableProgramming.md index 0cec90aa47712..91b396adada17 100644 --- a/docs/DifferentiableProgramming.md +++ b/docs/DifferentiableProgramming.md @@ -1,7 +1,7 @@ # Differentiable Programming Manifesto * Authors: [Richard Wei], [Dan Zheng], [Marc Rasi], [Bart Chrzaszcz] -* Status: Partially implemented +* Status: Partially implemented on master, feature gated under `import _Differentiation` ## Table of contents @@ -1949,7 +1949,7 @@ One concrete example is `sinf(_:)` from the C standard library. It can be made differentiable by defining a derivative retroactively. ```swift -#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) +#if canImport(Darwin) import func Darwin.sinf #else import func Glibc.sinf diff --git a/docs/ExternalResources.md b/docs/ExternalResources.md new file mode 100644 index 0000000000000..b8bf3849ee728 --- /dev/null +++ b/docs/ExternalResources.md @@ -0,0 +1,176 @@ +# External Resources + +The official [Swift blog](https://swift.org/blog/) has a lot of useful +information, such as [how runtime reflection works][mirror-post] and how the +compiler's [new diagnostic architecture][diagnostic-arch-post] is structured. + +[mirror-post]: https://swift.org/blog/how-mirror-works/ +[diagnostic-arch-post]: https://swift.org/blog/new-diagnostic-arch-overview/ + +This page lists some external resources apart from the Swift blog which may be +helpful for people interested in contributing to Swift. The resources are listed +in reverse-chronological order and organized by topic. + + + + + +## Contributing Guides and Tips + +- [Steps for first PR and asking questions][] by Varun Gandhi (Swift forum + comment, Dec 2019). +- [Contributing to Swift for the First Time][] by Robert Pieta (talk, Jun 2019): + This talk describes Robert's experience contributing to + `swift-corelibs-foundation` and later `swift`, providing a step-by-step guide + for new contributors to get their feet wet. +- [Contributing to Swift compiler][] by Yusuke Kita (lightning talk, Apr 2019). +- Contributing to Swift ([Part 1][Contributing to Swift - Part 1], + [Part 2][Contributing to Swift - Part 2]) by Suyash Srijan (blog post series, + Dec 2018). +- [Setting up a compile-edit-test cycle][] by Robert Widmann (Swift forum + comment, May 2018) +- [Becoming an Effective Contributor to Swift][] by Harlan Haskins and Robert + Widmann (talk, Apr 2018): Covers the following topics: + - The organization of different projects part of the Swift monorepo. + - How to set up an environment for building Swift. + - Common utilities and compiler flags for debugging different stages. + - Common build configurations. + - Tips and tricks for testing: early exiting, filtering tests, + testing Swift and Objective-C together, using `PrettyStackTrace`. + - A live demo fixing a crash: + - Copying program arguments into Xcode for debugging. + - Using `dump()` for print debugging. +- [Getting Started with Swift Compiler Development][] by Brian Gesiak (blog post + series, Aug 2017 - Jun 2018) +- [Contributing to Open Source Swift][] by Jesse Squires (talk, Mar 2016): + Covers the following topics: + - The overall compiler pipeline. + - The organization of different projects part of the Swift monorepo, + including some "difficulty levels" for different projects. + - Tips for contributing effectively. + +[Steps for first PR and asking questions]: +https://forums.swift.org/t/getting-started-with-swift-compiler-development/31502/2 +[Contributing to Swift for the First Time]: https://youtu.be/51j7TrFNKiA +[Contributing to Swift compiler]: https://youtu.be/HAXJsgYniqE +[Contributing to Swift - Part 1]: https://medium.com/kinandcartacreated/contributing-to-swift-part-1-ea19108a2a54 +[Contributing to Swift - Part 2]: +https://medium.com/kinandcartacreated/contributing-to-swift-part-2-efebcf7b6c93 +[Setting up a compile-edit-test cycle]: https://forums.swift.org/t/need-a-workflow-advice/12536/14 +[Becoming an Effective Contributor to Swift]: https://youtu.be/oGJKsp-pZPk +[Getting Started with Swift Compiler Development]: https://modocache.io/getting-started-with-swift-development +[Contributing to Open Source Swift]: https://youtu.be/Ysa2n8ZX-YY + +## AST + +- [The secret life of types in Swift][] by Slava Pestov (blog post, Jul 2016): + This blog post describes the representation of Swift types inside the compiler. + It covers many important concepts: `TypeLoc` vs `TypeRepr` vs `Type`, the + representation of generic types, substitutions and more. + + +[The secret life of types in Swift]: https://medium.com/@slavapestov/the-secret-life-of-types-in-swift-ff83c3c000a5 + +### libSyntax and SwiftSyntax + +- [An overview of SwiftSyntax][] by Luciano Almeida (blog post, Apr 2019): + This post provides a quick tour of libSyntax and SwiftSyntax. +- [Improving Swift Tools with libSyntax][] by Harlan Haskins (talk, Sep 2017): + This talk describes the design of libSyntax/SwiftSyntax and discusses some + useful APIs. It also describes how to write a simple Swift formatter using the + library. + +[An overview of SwiftSyntax]: https://medium.com/@lucianoalmeida1/an-overview-of-swiftsyntax-cf1ae6d53494 +[Improving Swift Tools with libSyntax]: https://youtu.be/5ivuYGxW_3M + +## Type checking and inference + +- [Implementing Swift Generics][] by Slava Pestov and John McCall (talk, Oct 2017): + This talk dives into how Swift's compilation scheme for generics balances + (a) modularity and separate compilation with (b) the ability to pass unboxed + values and (c) the flexibility to optionally generate fully specialized code. + It covers the following type-checking related topics: type-checking generic + contexts, requirement paths and canonicalized generic signatures. +- [A Type System from Scratch][] by Robert Widmann (talk, Apr 2017): + This talk covers several topics related to type-checking and inference in Swift: + - Understanding sequent notation which can be used to represent typing judgments. + - An overview of how bidirectional type-checking works. + - Examples of checking and inferring types for some Swift expressions. + - Interaction complexity of different type system features with type inference. + - Type variables and constraint graphs. + +[Implementing Swift Generics]: https://youtu.be/ctS8FzqcRug +[A Type System from Scratch]: https://youtu.be/IbjoA5xVUq0 + +## SIL + +- [Ownership SSA][] by Michael Gottesman (talk, Oct 2019): This talk describes + efficiency and correctness challenges with automatic reference counting and + how including ownership semantics in the compiler's intermediate representation + helps tackles those challenges. +- [How to talk to your kids about SIL type use][] by Slava Pestov (blog post, + Jul 2016): This blog post describes several important SIL concepts: object + vs address types, AST -> SIL type lowering, trivial vs loadable vs + address-only SIL types, abstraction patterns and more. +- [Swift's High-Level IR][] by Joe Groff and Chris Lattner (talk, Oct 2015): + This talk describes the goals and design of SIL. It covers the following: + - Some commonly used SIL instructions and how they are motivated by language + features. + - Some early passes in SIL processing, such as mandatory inlining, + box-to-stack promotion and definite initialization. + - Why SIL is useful as an intermediate representation between the AST and + LLVM IR. + +[Ownership SSA]: https://youtu.be/qy3iZPHZ88o +[How to talk to your kids about SIL type use]: https://medium.com/@slavapestov/how-to-talk-to-your-kids-about-sil-type-use-6b45f7595f43 +[Swift's High-Level IR]: https://youtu.be/Ntj8ab-5cvE + +## Code generation, runtime and ABI + +- [How Swift Achieved Dynamic Linking Where Rust Couldn't][] by Alexis + Beingessner (blog post, Nov 2019): This blog post describes Swift's approach + for compiling polymorphic functions, contrasting it with the strategy used by + Rust and C++ (monomorphization). It covers the following topics: ABI stability, + library evolution, resilient type layout, reabstraction, materialization, + ownership and calling conventions. +- [arm64e: An ABI for Pointer Authentication][] by Ahmed Bougacha and John McCall + (talk, Oct 2019): This talk does not mention Swift specifically, but provides a + good background on the arm64e ABI and pointer authentication. The ABI affects + parts of IR generation, the Swift runtime, and small parts of the standard + library using unsafe code. +- [Exploiting The Swift ABI][] by Robert Widmann (talk, July 2019): + This talk is a whirlwind tour of different aspects of the Swift ABI and runtime + touching the following topics: reflection, type layout, ABI entrypoints, + Swift's compilation model for generics and archetypes, witness tables, + relative references, context descriptors and more. +- [Efficiently Implementing Runtime Metadata][] by Joe Groff and Doug Gregor + (talk, Oct 2018): This talk covers the use of relative references in Swift's + runtime metadata structures. After describing some important metrics impacted + by the use of dynamic libraries, it goes through the different kinds of + relative references used in the Swift runtime and the resulting tooling and + performance benefits. +- [Coroutine Representations and ABIs in LLVM][] by John McCall (talk, Oct 2018): + This talk describes several points in the design space for coroutines, diving + into important implementation tradeoffs. It explains how different language + features can be built on top of coroutines and how they impose different + design requirements. It also contrasts C++20's coroutines feature with + Swift's accessors, describing the differences between the two as implemented + in LLVM. +- [Implementing Swift Generics][]: This talk is mentioned in the type-checking + section. It also covers the following code generation and runtime topics: + value witness tables, type metadata, abstraction patterns, reabstraction, + reabstraction thunks and protocol witness tables. + +[How Swift Achieved Dynamic Linking Where Rust Couldn't]: https://gankra.github.io/blah/swift-abi/ +[arm64e: An ABI for Pointer Authentication]: https://youtu.be/C1nZvpEBfYA +[Exploiting The Swift ABI]: https://youtu.be/0rHG_Pa86oA +[Efficiently Implementing Runtime Metadata]: https://youtu.be/G3bpj-4tWVU +[Coroutine Representations and ABIs in LLVM]: https://youtu.be/wyAbV8AM9PM diff --git a/docs/README.md b/docs/README.md index dceb55fa82bda..1492d1ef48430 100644 --- a/docs/README.md +++ b/docs/README.md @@ -252,12 +252,10 @@ They are preserved mostly for historical interest. ## External Resources -The official [Swift blog](https://swift.org/blog/) contains a lot of useful -information, such as how library evolution works and how the compiler's new -diagnostic architecture is structured, helping us provide more precise -diagnostics. - -TODO: Add a new document ExternalResources.md. +External resources are listed in [docs/ExternalResources.md](ExternalResources.md). +These cover a variety of topics, +such as the design of different aspects of the Swift compiler and runtime +and contributing to the project more effectively. ## Uncategorized diff --git a/docs/SIL.rst b/docs/SIL.rst index 947f166123d33..34143b4724f97 100644 --- a/docs/SIL.rst +++ b/docs/SIL.rst @@ -3573,6 +3573,20 @@ the encoding is ``objc_selector``, the string literal produces a reference to a UTF-8-encoded Objective-C selector in the Objective-C method name segment. +base_addr_for_offset +```````````````````` +:: + + sil-instruction ::= 'base_addr_for_offset' sil-type + + %1 = base_addr_for_offset $*S + // %1 has type $*S + +Creates a base address for offset calculations. The result can be used by +address projections, like ``struct_element_addr``, which themselves return the +offset of the projected fields. +IR generation simply creates a null pointer for ``base_addr_for_offset``. + Dynamic Dispatch ~~~~~~~~~~~~~~~~ diff --git a/docs/StandardLibraryProgrammersManual.md b/docs/StandardLibraryProgrammersManual.md index d3bf123d53d2c..67ded2ecb6613 100644 --- a/docs/StandardLibraryProgrammersManual.md +++ b/docs/StandardLibraryProgrammersManual.md @@ -98,7 +98,7 @@ On these platforms, the Swift Standard Library ships as an integrated part of th #### Unwrapping Optionals -Optionals can be unwrapped with `!`, which triggers a trap on nil. Alternatively, they can be `.unsafelyUnwrapped()`, which will check and trap in debug builds of user code. Internal to the standard library is `._unsafelyUnwrappedUnchecked()` which will only check and trap in debug builds of the standard library itself. These correspond directly with `_precondition`, `_debugPrecondition`, and `_sanityCheck`. See [that section](#precondition) for details. +Optionals can be unwrapped with `!`, which triggers a trap on nil. Alternatively, they can be `.unsafelyUnwrapped()`, which will check and trap in debug builds of user code. Internal to the standard library is `._unsafelyUnwrappedUnchecked()` which will only check and trap in debug builds of the standard library itself. These correspond directly with `_precondition`, `_debugPrecondition`, and `_internalInvariant`. See [that section](#precondition) for details. #### UnsafeBitCast and Casting References diff --git a/docs/StdlibRationales.rst b/docs/StdlibRationales.rst index 3b8503b5a92c8..1a13f5a8109c4 100644 --- a/docs/StdlibRationales.rst +++ b/docs/StdlibRationales.rst @@ -174,21 +174,6 @@ call an API with a different name, say ``lazyEnumerate()`` to opt into laziness. The problem is that the eager API, which would have a shorter and less obscure name, would be less efficient for the common case. -Use of ``BooleanType`` in library APIs --------------------------------------- - -Use ``Bool`` instead of a generic function over a ``BooleanType``, unless there -are special circumstances (for example, ``func &&`` is designed to work on all -boolean values so that ``&&`` feels like a part of the language). - -``BooleanType`` is a protocol to which only ``Bool`` and ``ObjCBool`` conform. -Users don't usually interact ``ObjCBool`` instances, except when using certain -specific APIs (for example, APIs that operate on pointers to ``BOOL``). If -someone already has an ``ObjCBool`` instance for whatever strange reason, they -can just convert it to ``Bool``. We think this is the right tradeoff: -simplifying function signatures is more important than making a marginal -usecase a bit more convenient. - Possible future directions ========================== diff --git a/include/swift/AST/ASTContext.h b/include/swift/AST/ASTContext.h index 4ff1060777427..44aff1b7cd009 100644 --- a/include/swift/AST/ASTContext.h +++ b/include/swift/AST/ASTContext.h @@ -254,11 +254,6 @@ class ASTContext final { /// The request-evaluator that is used to process various requests. Evaluator evaluator; - /// The set of top-level modules we have loaded. - /// This map is used for iteration, therefore it's a MapVector and not a - /// DenseMap. - llvm::MapVector LoadedModules; - /// The builtin module. ModuleDecl * const TheBuiltinModule; @@ -654,6 +649,15 @@ class ASTContext final { /// metadata. AvailabilityContext getPrespecializedGenericMetadataAvailability(); + /// Get the runtime availability of the swift_compareTypeContextDescriptors + /// for the target platform. + AvailabilityContext getCompareTypeContextDescriptorsAvailability(); + + /// Get the runtime availability of the + /// swift_compareProtocolConformanceDescriptors entry point for the target + /// platform. + AvailabilityContext getCompareProtocolConformanceDescriptorsAvailability(); + /// Get the runtime availability of features introduced in the Swift 5.2 /// compiler for the target platform. AvailabilityContext getSwift52Availability(); @@ -712,8 +716,11 @@ class ASTContext final { /// compiler. /// \param isDWARF \c true if this module loader can load Clang modules /// from DWARF. + /// \param IsInterface \c true if this module loader can load Swift textual + /// interface. void addModuleLoader(std::unique_ptr loader, - bool isClang = false, bool isDWARF = false); + bool isClang = false, bool isDWARF = false, + bool IsInterface = false); /// Retrieve the module dependencies for the module with the given name. /// @@ -787,8 +794,26 @@ class ASTContext final { /// The loader is owned by the AST context. ClangModuleLoader *getDWARFModuleLoader() const; + /// Retrieve the module interface loader for this ASTContext. + ModuleLoader *getModuleInterfaceLoader() const; +public: namelookup::ImportCache &getImportCache() const; + /// Returns an iterator over the modules that are known by this context + /// to be loaded. + /// + /// Iteration order is guaranteed to match the order in which + /// \c addLoadedModule was called to register the loaded module + /// with this context. + iterator_range::const_iterator> + getLoadedModules() const; + + /// Returns the number of loaded modules known by this context to be loaded. + unsigned getNumLoadedModules() const { + auto eltRange = getLoadedModules(); + return std::distance(eltRange.begin(), eltRange.end()); + } + /// Asks every module loader to verify the ASTs it has loaded. /// /// Does nothing in non-asserts (NDEBUG) builds. @@ -828,6 +853,11 @@ class ASTContext final { return const_cast(this)->getStdlibModule(false); } + /// Insert an externally-sourced module into the set of known loaded modules + /// in this context. + void addLoadedModule(ModuleDecl *M); + +public: /// Retrieve the current generation number, which reflects the /// number of times a module import has caused mass invalidation of /// lookup tables. diff --git a/include/swift/AST/ASTDemangler.h b/include/swift/AST/ASTDemangler.h index 02d8a479337eb..f8582c5e8c41b 100644 --- a/include/swift/AST/ASTDemangler.h +++ b/include/swift/AST/ASTDemangler.h @@ -26,6 +26,7 @@ #include "llvm/ADT/StringRef.h" #include "swift/AST/Types.h" #include "swift/Demangling/Demangler.h" +#include "swift/Demangling/NamespaceMacros.h" #include "swift/Demangling/TypeDecoder.h" namespace swift { @@ -33,6 +34,7 @@ namespace swift { class TypeDecl; namespace Demangle { +SWIFT_BEGIN_INLINE_NAMESPACE Type getTypeForMangling(ASTContext &ctx, llvm::StringRef mangling); @@ -178,6 +180,7 @@ class ASTBuilder { Demangle::Node::Kind kind); }; +SWIFT_END_INLINE_NAMESPACE } // namespace Demangle } // namespace swift diff --git a/include/swift/AST/ASTMangler.h b/include/swift/AST/ASTMangler.h index f6605561b4adb..d806bcc3fda0c 100644 --- a/include/swift/AST/ASTMangler.h +++ b/include/swift/AST/ASTMangler.h @@ -101,7 +101,8 @@ class ASTMangler : public Mangler { SymbolKind SKind = SymbolKind::Default); std::string mangleDestructorEntity(const DestructorDecl *decl, - bool isDeallocating, SymbolKind SKind); + bool isDeallocating, + SymbolKind SKind = SymbolKind::Default); std::string mangleConstructorEntity(const ConstructorDecl *ctor, bool isAllocating, @@ -120,11 +121,11 @@ class ASTMangler : public Mangler { std::string mangleDefaultArgumentEntity(const DeclContext *func, unsigned index, - SymbolKind SKind); + SymbolKind SKind = SymbolKind::Default); std::string mangleInitializerEntity(const VarDecl *var, SymbolKind SKind); std::string mangleBackingInitializerEntity(const VarDecl *var, - SymbolKind SKind); + SymbolKind SKind = SymbolKind::Default); std::string mangleNominalType(const NominalTypeDecl *decl); diff --git a/include/swift/AST/ASTPrinter.h b/include/swift/AST/ASTPrinter.h index 0e5a17c9dcef7..3c28d725ab6bb 100644 --- a/include/swift/AST/ASTPrinter.h +++ b/include/swift/AST/ASTPrinter.h @@ -204,7 +204,9 @@ class ASTPrinter { return *this << StringRef(&c, 1); } - void printKeyword(StringRef name, PrintOptions Opts, StringRef Suffix = "") { + void printKeyword(StringRef name, + const PrintOptions &Opts, + StringRef Suffix = "") { if (Opts.SkipUnderscoredKeywords && name.startswith("_")) return; assert(!name.empty() && "Tried to print empty keyword"); diff --git a/include/swift/AST/ASTTypeIDZone.def b/include/swift/AST/ASTTypeIDZone.def index 5c1eaa91fe286..daf638f797480 100644 --- a/include/swift/AST/ASTTypeIDZone.def +++ b/include/swift/AST/ASTTypeIDZone.def @@ -27,6 +27,7 @@ SWIFT_TYPEID(PropertyWrapperTypeInfo) SWIFT_TYPEID(Requirement) SWIFT_TYPEID(ResilienceExpansion) SWIFT_TYPEID(FragileFunctionKind) +SWIFT_TYPEID(TangentPropertyInfo) SWIFT_TYPEID(Type) SWIFT_TYPEID(TypePair) SWIFT_TYPEID(TypeWitnessAndDecl) diff --git a/include/swift/AST/ASTTypeIDs.h b/include/swift/AST/ASTTypeIDs.h index 9359f95427d0e..b81fdc686b9ac 100644 --- a/include/swift/AST/ASTTypeIDs.h +++ b/include/swift/AST/ASTTypeIDs.h @@ -19,6 +19,7 @@ #include "swift/Basic/LLVM.h" #include "swift/Basic/TypeID.h" + namespace swift { class AbstractFunctionDecl; @@ -58,14 +59,14 @@ class Requirement; enum class ResilienceExpansion : unsigned; struct FragileFunctionKind; class SourceFile; +struct TangentPropertyInfo; class Type; -class ValueDecl; -class VarDecl; -class Witness; class TypeAliasDecl; -class Type; struct TypePair; struct TypeWitnessAndDecl; +class ValueDecl; +class VarDecl; +class Witness; enum class AncestryFlags : uint8_t; enum class ImplicitMemberAction : uint8_t; struct FingerprintAndMembers; diff --git a/include/swift/AST/Attr.def b/include/swift/AST/Attr.def index 95504c3477426..fb1085509c8f3 100644 --- a/include/swift/AST/Attr.def +++ b/include/swift/AST/Attr.def @@ -494,7 +494,7 @@ SIMPLE_DECL_ATTR(_disfavoredOverload, DisfavoredOverload, ABIStableToAdd | ABIStableToRemove | APIStableToAdd | APIStableToRemove, 87) SIMPLE_DECL_ATTR(_functionBuilder, FunctionBuilder, - OnNominalType | + OnNominalType | UserInaccessible | ABIStableToAdd | ABIStableToRemove | APIStableToAdd | APIStableToRemove, 88) DECL_ATTR(_projectedValueProperty, ProjectedValueProperty, diff --git a/include/swift/AST/Attr.h b/include/swift/AST/Attr.h index d6482297d272f..98eb453af7a36 100644 --- a/include/swift/AST/Attr.h +++ b/include/swift/AST/Attr.h @@ -35,6 +35,7 @@ #include "swift/AST/Ownership.h" #include "swift/AST/PlatformKind.h" #include "swift/AST/Requirement.h" +#include "swift/AST/StorageImpl.h" #include "swift/AST/TrailingCallArguments.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" @@ -1718,6 +1719,7 @@ class OriginallyDefinedInAttr: public DeclAttribute { struct DeclNameRefWithLoc { DeclNameRef Name; DeclNameLoc Loc; + Optional AccessorKind; }; /// Attribute that marks a function as differentiable. diff --git a/include/swift/AST/AutoDiff.h b/include/swift/AST/AutoDiff.h index 5b447027b20c5..18524c9933e9e 100644 --- a/include/swift/AST/AutoDiff.h +++ b/include/swift/AST/AutoDiff.h @@ -35,6 +35,7 @@ class AnyFunctionType; class SourceFile; class SILFunctionType; class TupleType; +class VarDecl; /// A function type differentiability kind. enum class DifferentiabilityKind : uint8_t { @@ -459,6 +460,99 @@ class DerivativeFunctionTypeError } }; +/// Describes the "tangent stored property" corresponding to an original stored +/// property in a `Differentiable`-conforming type. +/// +/// The tangent stored property is the stored property in the `TangentVector` +/// struct of the `Differentiable`-conforming type, with the same name as the +/// original stored property and with the original stored property's +/// `TangentVector` type. +struct TangentPropertyInfo { + struct Error { + enum class Kind { + /// The original property is `@noDerivative`. + NoDerivativeOriginalProperty, + /// The nominal parent type does not conform to `Differentiable`. + NominalParentNotDifferentiable, + /// The original property's type does not conform to `Differentiable`. + OriginalPropertyNotDifferentiable, + /// The parent `TangentVector` type is not a struct. + ParentTangentVectorNotStruct, + /// The parent `TangentVector` struct does not declare a stored property + /// with the same name as the original property. + TangentPropertyNotFound, + /// The tangent property's type is not equal to the original property's + /// `TangentVector` type. + TangentPropertyWrongType, + /// The tangent property is not a stored property. + TangentPropertyNotStored + }; + + /// The error kind. + Kind kind; + + private: + union Value { + Type type; + Value(Type type) : type(type) {} + Value() {} + } value; + + public: + Error(Kind kind) : kind(kind), value() { + assert(kind == Kind::NoDerivativeOriginalProperty || + kind == Kind::NominalParentNotDifferentiable || + kind == Kind::OriginalPropertyNotDifferentiable || + kind == Kind::ParentTangentVectorNotStruct || + kind == Kind::TangentPropertyNotFound || + kind == Kind::TangentPropertyNotStored); + }; + + Error(Kind kind, Type type) : kind(kind), value(type) { + assert(kind == Kind::TangentPropertyWrongType); + }; + + Type getType() const { + assert(kind == Kind::TangentPropertyWrongType); + return value.type; + } + + friend bool operator==(const Error &lhs, const Error &rhs); + }; + + /// The tangent stored property. + VarDecl *tangentProperty = nullptr; + + /// An optional error. + Optional error = None; + +private: + TangentPropertyInfo(VarDecl *tangentProperty, Optional error) + : tangentProperty(tangentProperty), error(error) {} + +public: + TangentPropertyInfo(VarDecl *tangentProperty) + : TangentPropertyInfo(tangentProperty, None) {} + + TangentPropertyInfo(Error::Kind errorKind) + : TangentPropertyInfo(nullptr, Error(errorKind)) {} + + TangentPropertyInfo(Error::Kind errorKind, Type errorType) + : TangentPropertyInfo(nullptr, Error(errorKind, errorType)) {} + + /// Returns `true` iff this tangent property info is valid. + bool isValid() const { return tangentProperty && !error; } + + explicit operator bool() const { return isValid(); } + + friend bool operator==(const TangentPropertyInfo &lhs, + const TangentPropertyInfo &rhs) { + return lhs.tangentProperty == rhs.tangentProperty && lhs.error == rhs.error; + } +}; + +void simple_display(llvm::raw_ostream &OS, TangentPropertyInfo info); + /// The key type used for uniquing `SILDifferentiabilityWitness` in /// `SILModule`: original function name, parameter indices, result indices, and /// derivative generic signature. diff --git a/include/swift/AST/AvailabilitySpec.h b/include/swift/AST/AvailabilitySpec.h index 05c0752bffaab..86b0342419a1a 100644 --- a/include/swift/AST/AvailabilitySpec.h +++ b/include/swift/AST/AvailabilitySpec.h @@ -68,16 +68,33 @@ class PlatformVersionConstraintAvailabilitySpec : public AvailabilitySpec { SourceLoc PlatformLoc; llvm::VersionTuple Version; + + // For macOS Big Sur, we canonicalize 10.16 to 11.0 for compile-time + // checking since clang canonicalizes availability markup. However, to + // support Beta versions of macOS Big Sur where the OS + // reports 10.16 at run time, we need to compare against 10.16, + // + // This means for: + // + // if #available(macOS 10.16, *) { ... } + // + // we need to keep around both a canonical version for use in compile-time + // checks and an uncanonicalized version for the version to actually codegen + // with. + llvm::VersionTuple RuntimeVersion; + SourceRange VersionSrcRange; public: PlatformVersionConstraintAvailabilitySpec(PlatformKind Platform, SourceLoc PlatformLoc, llvm::VersionTuple Version, + llvm::VersionTuple RuntimeVersion, SourceRange VersionSrcRange) : AvailabilitySpec(AvailabilitySpecKind::PlatformVersionConstraint), Platform(Platform), PlatformLoc(PlatformLoc), Version(Version), + RuntimeVersion(RuntimeVersion), VersionSrcRange(VersionSrcRange) {} /// The required platform. @@ -93,6 +110,11 @@ class PlatformVersionConstraintAvailabilitySpec : public AvailabilitySpec { llvm::VersionTuple getVersion() const { return Version; } SourceRange getVersionSrcRange() const { return VersionSrcRange; } + // The version to be used in codegen for version comparisons at run time. + // This is required to support beta versions of macOS Big Sur that + // report 10.16 at run time. + llvm::VersionTuple getRuntimeVersion() const { return RuntimeVersion; } + SourceRange getSourceRange() const; void print(raw_ostream &OS, unsigned Indent) const; diff --git a/include/swift/AST/CMakeLists.txt b/include/swift/AST/CMakeLists.txt new file mode 100644 index 0000000000000..ebc60523cb0d8 --- /dev/null +++ b/include/swift/AST/CMakeLists.txt @@ -0,0 +1,3 @@ +swift_install_in_component(DIRECTORY diagnostics + DESTINATION "share/swift/" + COMPONENT compiler) diff --git a/include/swift/AST/Decl.h b/include/swift/AST/Decl.h index 8b372835d08b1..8848b5c2360a1 100644 --- a/include/swift/AST/Decl.h +++ b/include/swift/AST/Decl.h @@ -535,7 +535,7 @@ class alignas(1 << DeclAlignInBits) Decl { NumRequirementsInSignature : 16 ); - SWIFT_INLINE_BITFIELD(ClassDecl, NominalTypeDecl, 1+1+2+1+1+1+1+1+1, + SWIFT_INLINE_BITFIELD(ClassDecl, NominalTypeDecl, 1+1+2+1+1+1+1+1, /// Whether this class inherits its superclass's convenience initializers. InheritsSuperclassInits : 1, ComputedInheritsSuperclassInits : 1, @@ -543,9 +543,6 @@ class alignas(1 << DeclAlignInBits) Decl { /// \see ClassDecl::ForeignKind RawForeignKind : 2, - /// \see ClassDecl::getEmittedMembers() - HasForcedEmittedMembers : 1, - HasMissingDesignatedInitializers : 1, ComputedHasMissingDesignatedInitializers : 1, @@ -3856,14 +3853,6 @@ class ClassDecl final : public NominalTypeDecl { llvm::PointerIntPair SuperclassType; } LazySemanticInfo; - bool hasForcedEmittedMembers() const { - return Bits.ClassDecl.HasForcedEmittedMembers; - } - - void setHasForcedEmittedMembers() { - Bits.ClassDecl.HasForcedEmittedMembers = true; - } - Optional getCachedInheritsSuperclassInitializers() const { if (Bits.ClassDecl.ComputedInheritsSuperclassInits) return Bits.ClassDecl.InheritsSuperclassInits; @@ -4089,7 +4078,7 @@ class ClassDecl final : public NominalTypeDecl { /// Get all the members of this class, synthesizing any implicit members /// that appear in the vtable if needed. - DeclRange getEmittedMembers() const; + ArrayRef getEmittedMembers() const; // Implement isa/cast/dyncast/etc. static bool classof(const Decl *D) { @@ -5502,35 +5491,10 @@ class ParamDecl : public VarDecl { } /// Does this parameter reject temporary pointer conversions? - bool isNonEphemeral() const { - if (getAttrs().hasAttribute()) - return true; - - // Only pointer parameters can be non-ephemeral. - auto ty = getInterfaceType(); - if (!ty->lookThroughSingleOptionalType()->getAnyPointerElementType()) - return false; - - // Enum element pointer parameters are always non-ephemeral. - auto *parentDecl = getDeclContext()->getAsDecl(); - if (parentDecl && isa(parentDecl)) - return true; - - return false; - } + bool isNonEphemeral() const; /// Attempt to apply an implicit `@_nonEphemeral` attribute to this parameter. - void setNonEphemeralIfPossible() { - // Don't apply the attribute if this isn't a pointer param. - auto type = getInterfaceType(); - if (!type->lookThroughSingleOptionalType()->getAnyPointerElementType()) - return; - - if (!getAttrs().hasAttribute()) { - auto &ctx = getASTContext(); - getAttrs().add(new (ctx) NonEphemeralAttr(/*IsImplicit*/ true)); - } - } + void setNonEphemeralIfPossible(); /// Remove the type of this varargs element designator, without the array /// type wrapping it. A parameter like "Int..." will have formal parameter diff --git a/include/swift/AST/DiagnosticEngine.h b/include/swift/AST/DiagnosticEngine.h index 3abd15ea0f224..ef9160641981e 100644 --- a/include/swift/AST/DiagnosticEngine.h +++ b/include/swift/AST/DiagnosticEngine.h @@ -18,9 +18,10 @@ #ifndef SWIFT_BASIC_DIAGNOSTICENGINE_H #define SWIFT_BASIC_DIAGNOSTICENGINE_H -#include "swift/AST/TypeLoc.h" #include "swift/AST/DeclNameLoc.h" #include "swift/AST/DiagnosticConsumer.h" +#include "swift/AST/LocalizationFormat.h" +#include "swift/AST/TypeLoc.h" #include "llvm/ADT/StringSet.h" #include "llvm/Support/Allocator.h" #include "llvm/Support/VersionTuple.h" @@ -629,7 +630,7 @@ namespace swift { DiagnosticState(DiagnosticState &&) = default; DiagnosticState &operator=(DiagnosticState &&) = default; }; - + /// Class responsible for formatting diagnostics and presenting them /// to the user. class DiagnosticEngine { @@ -663,6 +664,10 @@ namespace swift { /// but rather stored until all transactions complete. llvm::StringSet TransactionStrings; + /// Diagnostic producer to handle the logic behind retrieving a localized + /// diagnostic message. + std::unique_ptr localization; + /// The number of open diagnostic transactions. Diagnostics are only /// emitted once all transactions have closed. unsigned TransactionCount = 0; @@ -734,6 +739,13 @@ namespace swift { return diagnosticDocumentationPath; } + void setLocalization(std::string locale, std::string path) { + assert(!locale.empty()); + assert(!path.empty()); + localization = + std::make_unique(locale, path); + } + void ignoreDiagnostic(DiagID id) { state.setDiagnosticBehavior(id, DiagnosticState::Behavior::Ignore); } @@ -955,8 +967,7 @@ namespace swift { void emitTentativeDiagnostics(); public: - static const char *diagnosticStringFor(const DiagID id, - bool printDiagnosticName); + const char *diagnosticStringFor(const DiagID id, bool printDiagnosticName); /// If there is no clear .dia file for a diagnostic, put it in the one /// corresponding to the SourceLoc given here. diff --git a/include/swift/AST/DiagnosticsFrontend.def b/include/swift/AST/DiagnosticsFrontend.def index 7aa018966646b..3557e0486cb58 100644 --- a/include/swift/AST/DiagnosticsFrontend.def +++ b/include/swift/AST/DiagnosticsFrontend.def @@ -76,6 +76,13 @@ ERROR(error_unknown_arg,none, "unknown argument: '%0'", (StringRef)) ERROR(error_invalid_arg_value,none, "invalid value '%1' in '%0'", (StringRef, StringRef)) +WARNING(warning_invalid_locale_code,none, + "unsupported locale code; supported locale codes are: '%0'", (StringRef)) +WARNING(warning_locale_path_not_found,none, + "specified localization directory '%0' does not exist, " + "translation is disabled", (StringRef)) +WARNING(warning_cannot_find_locale_file,none, + "cannot find translations for '%0' at '%1': no such file", (StringRef, StringRef)) WARNING(warning_cannot_multithread_batch_mode,none, "ignoring -num-threads argument; cannot multithread batch mode", ()) ERROR(error_unsupported_option_argument,none, @@ -251,6 +258,14 @@ ERROR(previous_installname_map_corrupted,none, "previous install name map from %0 is malformed", (StringRef)) +ERROR(explicit_swift_module_map_missing,none, + "cannot open explicit Swift module map from %0", + (StringRef)) + +ERROR(explicit_swift_module_map_corrupted,none, + "explicit Swift module map from %0 is malformed", + (StringRef)) + REMARK(default_previous_install_name, none, "default previous install name for %0 is %1", (StringRef, StringRef)) @@ -299,6 +314,9 @@ ERROR(error_optimization_remark_pattern, none, "%0 in '%1'", ERROR(error_invalid_debug_prefix_map, none, "invalid argument '%0' to -debug-prefix-map; it must be of the form " "'original=remapped'", (StringRef)) +ERROR(error_invalid_coverage_prefix_map, none, + "invalid argument '%0' to -coverage-prefix-map; it must be of the form " + "'original=remapped'", (StringRef)) ERROR(error_unable_to_write_swift_ranges_file, none, diff --git a/include/swift/AST/DiagnosticsSIL.def b/include/swift/AST/DiagnosticsSIL.def index 34ca3c7b08c86..047a9b3366fe0 100644 --- a/include/swift/AST/DiagnosticsSIL.def +++ b/include/swift/AST/DiagnosticsSIL.def @@ -496,17 +496,28 @@ NOTE(autodiff_cannot_differentiate_through_multiple_results,none, "cannot differentiate through multiple results", ()) NOTE(autodiff_cannot_differentiate_through_inout_arguments,none, "cannot differentiate through 'inout' arguments", ()) -// TODO(TF-1149): Remove this diagnostic. -NOTE(autodiff_loadable_value_addressonly_tangent_unsupported,none, - "cannot yet differentiate value whose type %0 has a compile-time known " - "size, but whose 'TangentVector' contains stored properties of unknown " - "size; consider modifying %1 to use fewer generic parameters in stored " - "properties", (Type, Type)) NOTE(autodiff_enums_unsupported,none, "differentiating enum values is not yet supported", ()) +NOTE(autodiff_stored_property_parent_not_differentiable,none, + "cannot differentiate access to property '%0.%1' because '%0' does not " + "conform to 'Differentiable'", (StringRef, StringRef)) +NOTE(autodiff_stored_property_not_differentiable,none, + "cannot differentiate access to property '%0.%1' because property type %2 " + "does not conform to 'Differentiable'", (StringRef, StringRef, Type)) +NOTE(autodiff_stored_property_tangent_not_struct,none, + "cannot differentiate access to property '%0.%1' because " + "'%0.TangentVector' is not a struct", (StringRef, StringRef)) NOTE(autodiff_stored_property_no_corresponding_tangent,none, - "property cannot be differentiated because '%0.TangentVector' does not " - "have a member named '%1'", (StringRef, StringRef)) + "cannot differentiate access to property '%0.%1' because " + "'%0.TangentVector' does not have a stored property named '%1'", + (StringRef, StringRef)) +NOTE(autodiff_tangent_property_wrong_type,none, + "cannot differentiate access to property '%0.%1' because " + "'%0.TangentVector.%1' does not have expected type %2", + (StringRef, StringRef, /*originalPropertyTanType*/ Type)) +NOTE(autodiff_tangent_property_not_stored,none, + "cannot differentiate access to property '%0.%1' because " + "'%0.TangentVector.%1' is not a stored property", (StringRef, StringRef)) NOTE(autodiff_coroutines_not_supported,none, "differentiation of coroutine calls is not yet supported", ()) NOTE(autodiff_cannot_differentiate_writes_to_global_variables,none, diff --git a/include/swift/AST/DiagnosticsSema.def b/include/swift/AST/DiagnosticsSema.def index 7467f35798830..f40b05ee93584 100644 --- a/include/swift/AST/DiagnosticsSema.def +++ b/include/swift/AST/DiagnosticsSema.def @@ -253,6 +253,10 @@ ERROR(no_candidates_match_result_type,none, "no '%0' candidates produce the expected contextual result type %1", (StringRef, Type)) +ERROR(no_candidates_match_argument_type,none, + "no '%0' candidates produce the expected type %1 for parameter #%2", + (StringRef, Type, unsigned)) + ERROR(cannot_infer_closure_parameter_type,none, "unable to infer type of a closure parameter %0 in the current context", (StringRef)) @@ -1071,6 +1075,9 @@ ERROR(optional_base_not_unwrapped,none, NOTE(optional_base_chain,none, "chain the optional using '?' to access member %0 only for non-'nil' " "base values", (DeclNameRef)) +NOTE(optional_base_remove_optional_for_keypath_root, none, + "use unwrapped type %0 as key path root", (Type)) + ERROR(missing_unwrap_optional_try,none, "value of optional type %0 not unwrapped; did you mean to use 'try!' " "or chain with '?'?", @@ -1794,11 +1801,11 @@ ERROR(type_cannot_conform_to_nsobject,none, ERROR(use_of_equal_instead_of_equality,none, "use of '=' in a boolean context, did you mean '=='?", ()) - ERROR(type_cannot_conform, none, - "%select{|value of protocol }0type %1 cannot conform to %2; " - "only struct/enum/class types can conform to protocols", - (bool, Type, Type)) + "%select{type %1|protocol %1 as a type}0 cannot conform to " + "%select{%3|the protocol itself}2; " + "only concrete types such as structs, enums and classes can conform to protocols", + (bool, Type, bool, Type)) NOTE(required_by_opaque_return,none, "required by opaque return type of %0 %1", (DescriptiveDeclKind, DeclName)) NOTE(required_by_decl,none, @@ -2685,7 +2692,8 @@ ERROR(decl_from_hidden_module,none, "in an extension with public or '@usableFromInline' members|" "in an extension with conditional conformances}2; " "%select{%3 has been imported as implementation-only|" - "it is an SPI imported from %3}4", + "it is an SPI imported from %3|" + "it is SPI}4", (DescriptiveDeclKind, DeclName, unsigned, Identifier, unsigned)) ERROR(conformance_from_implementation_only_module,none, "cannot use conformance of %0 to %1 %select{here|as property wrapper here|" @@ -3087,6 +3095,16 @@ ERROR(derivative_attr_class_member_dynamic_self_result_unsupported,none, ERROR(derivative_attr_nonfinal_class_init_unsupported,none, "cannot register derivative for 'init' in a non-final class; consider " "making %0 final", (Type)) +ERROR(derivative_attr_unsupported_accessor_kind,none, + "cannot register derivative for %0", (/*accessorKind*/ DescriptiveDeclKind)) +// TODO(SR-13096): Remove this temporary diagnostic. +ERROR(derivative_attr_class_setter_unsupported,none, + "cannot yet register derivative for class property or subscript setters", + ()) +// TODO(TF-982): Remove this temporary diagnostic. +NOTE(derivative_attr_protocol_requirement_unsupported,none, + "cannot yet register derivative default implementation for protocol " + "requirements", ()) ERROR(derivative_attr_original_already_has_derivative,none, "a derivative already exists for %0", (DeclName)) NOTE(derivative_attr_duplicate_note,none, @@ -3122,13 +3140,25 @@ NOTE(transpose_attr_wrt_self_self_type_mismatch_note,none, "%1", (Type, Type)) // Automatic differentiation attributes -ERROR(autodiff_attr_original_decl_invalid_kind,none, - "%0 is not a 'func', 'init', 'subscript', or 'var' computed property " - "declaration", (DeclNameRef)) -ERROR(autodiff_attr_original_decl_none_valid_found,none, - "could not find function %0 with expected type %1", (DeclNameRef, Type)) -ERROR(autodiff_attr_original_decl_not_same_type_context,none, - "%0 is not defined in the current type context", (DeclNameRef)) +ERROR(autodiff_attr_original_decl_ambiguous,none, + "referenced declaration %0 is ambiguous", (DeclNameRef)) +NOTE(autodiff_attr_original_decl_ambiguous_candidate,none, + "candidate %0 found here", (DescriptiveDeclKind)) +ERROR(autodiff_attr_original_decl_none_valid,none, + "referenced declaration %0 could not be resolved", (DeclNameRef)) +NOTE(autodiff_attr_original_decl_invalid_kind,none, + "candidate %0 is not a 'func', 'init', 'subscript', or 'var' computed " + "property declaration", (DescriptiveDeclKind)) +NOTE(autodiff_attr_original_decl_missing_accessor,none, + "candidate %0 does not have a %1", + (DescriptiveDeclKind, /*accessorDeclKind*/ DescriptiveDeclKind)) +NOTE(autodiff_attr_original_decl_type_mismatch,none, + "candidate %0 does not have " + "%select{expected type|type equal to or less constrained than}2 %1", + (DescriptiveDeclKind, Type, /*hasGenericSignature*/ bool)) +NOTE(autodiff_attr_original_decl_not_same_type_context,none, + "candidate %0 is not defined in the current type context", + (DescriptiveDeclKind)) ERROR(autodiff_attr_original_void_result,none, "cannot differentiate void function %0", (DeclName)) ERROR(autodiff_attr_original_multiple_semantic_results,none, @@ -3137,6 +3167,8 @@ ERROR(autodiff_attr_original_multiple_semantic_results,none, ERROR(autodiff_attr_result_not_differentiable,none, "can only differentiate functions with results that conform to " "'Differentiable', but %0 does not conform to 'Differentiable'", (Type)) +ERROR(autodiff_attr_opaque_result_type_unsupported,none, + "cannot differentiate functions returning opaque result types", ()) // differentiation `wrt` parameters clause ERROR(diff_function_no_parameters,none, @@ -4759,7 +4791,8 @@ WARNING(resilience_decl_unavailable_warn, ERROR(inlinable_decl_ref_from_hidden_module, none, "%0 %1 cannot be used in " FRAGILE_FUNC_KIND "2 " "because %select{%3 was imported implementation-only|" - "it is an SPI imported from %3}4", + "it is an SPI imported from %3|" + "it is SPI}4", (DescriptiveDeclKind, DeclName, unsigned, Identifier, unsigned)) #undef FRAGILE_FUNC_KIND diff --git a/include/swift/AST/EducationalNotes.def b/include/swift/AST/EducationalNotes.def index ca30032f17a5f..e4e0ec2a3bd89 100644 --- a/include/swift/AST/EducationalNotes.def +++ b/include/swift/AST/EducationalNotes.def @@ -59,11 +59,23 @@ EDUCATIONAL_NOTES(property_wrapper_failable_init, EDUCATIONAL_NOTES(property_wrapper_type_requirement_not_accessible, "property-wrapper-requirements.md") +EDUCATIONAL_NOTES(opaque_type_var_no_init, "opaque-type-inference.md") +EDUCATIONAL_NOTES(opaque_type_no_underlying_type_candidates, + "opaque-type-inference.md") +EDUCATIONAL_NOTES(opaque_type_mismatched_underlying_type_candidates, + "opaque-type-inference.md") +EDUCATIONAL_NOTES(opaque_type_self_referential_underlying_type, + "opaque-type-inference.md") +EDUCATIONAL_NOTES(opaque_type_var_no_underlying_type, + "opaque-type-inference.md") + + EDUCATIONAL_NOTES(missing_append_interpolation, "string-interpolation-conformance.md") EDUCATIONAL_NOTES(append_interpolation_static, "string-interpolation-conformance.md") EDUCATIONAL_NOTES(append_interpolation_void_or_discardable, "string-interpolation-conformance.md") +EDUCATIONAL_NOTES(type_cannot_conform, "protocol-type-non-conformance.md") #undef EDUCATIONAL_NOTES diff --git a/include/swift/AST/Expr.h b/include/swift/AST/Expr.h index 1cb0976cdfd5e..eaca55f951348 100644 --- a/include/swift/AST/Expr.h +++ b/include/swift/AST/Expr.h @@ -5380,6 +5380,13 @@ class KeyPathExpr : public Expr { return Loc; } + SourceRange getSourceRange() const { + if (auto *indexExpr = getIndexExpr()) { + return indexExpr->getSourceRange(); + } + return Loc; + } + Kind getKind() const { return KindValue; } diff --git a/include/swift/AST/FineGrainedDependencies.h b/include/swift/AST/FineGrainedDependencies.h index e904cf4fbe703..bd53f9492211a 100644 --- a/include/swift/AST/FineGrainedDependencies.h +++ b/include/swift/AST/FineGrainedDependencies.h @@ -19,6 +19,7 @@ #include "swift/Basic/Range.h" #include "swift/Basic/ReferenceDependencyKeys.h" #include "llvm/ADT/Hashing.h" +#include "llvm/ADT/SetVector.h" #include "llvm/Support/MD5.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/YAMLParser.h" @@ -684,7 +685,7 @@ class SourceFileDepGraphNode : public DepGraphNode { size_t sequenceNumber = ~0; /// Holds the sequence numbers of definitions I depend upon. - std::unordered_set defsIDependUpon; + llvm::SetVector defsIDependUpon; /// True iff a Decl exists for this node. /// If a provides and a depends in the existing system both have the same key, diff --git a/include/swift/AST/GenericSignature.h b/include/swift/AST/GenericSignature.h index 271e07899698f..68e13a83baa88 100644 --- a/include/swift/AST/GenericSignature.h +++ b/include/swift/AST/GenericSignature.h @@ -136,8 +136,10 @@ class GenericSignature { return hash_value(sig.getPointer()); } - void print(raw_ostream &OS, PrintOptions Options = PrintOptions()) const; - void print(ASTPrinter &Printer, PrintOptions Opts = PrintOptions()) const; + void print(raw_ostream &OS, + const PrintOptions &Options = PrintOptions()) const; + void print(ASTPrinter &Printer, + const PrintOptions &Opts = PrintOptions()) const; SWIFT_DEBUG_DUMP; std::string getAsString() const; diff --git a/include/swift/AST/IRGenOptions.h b/include/swift/AST/IRGenOptions.h index 279fdcefb3c4e..ef745ec6b3772 100644 --- a/include/swift/AST/IRGenOptions.h +++ b/include/swift/AST/IRGenOptions.h @@ -169,6 +169,9 @@ class IRGenOptions { /// Path prefixes that should be rewritten in debug info. PathRemapper DebugPrefixMap; + /// Path prefixes that should be rewritten in coverage info. + PathRemapper CoveragePrefixMap; + /// What level of debug info to generate. IRGenDebugInfoLevel DebugInfoLevel : 2; @@ -281,6 +284,9 @@ class IRGenOptions { /// Whether to disable using mangled names for accessing concrete type metadata. unsigned DisableConcreteTypeMetadataMangledNameAccessors : 1; + /// The number of threads for multi-threaded code generation. + unsigned NumThreads = 0; + /// Path to the profdata file to be used for PGO, or the empty string. std::string UseProfile = ""; @@ -380,6 +386,10 @@ class IRGenOptions { llvm::hash_code getPCHHashComponents() const { return llvm::hash_value(0); } + + bool hasMultipleIRGenThreads() const { return NumThreads > 1; } + bool shouldPerformIRGenerationInParallel() const { return NumThreads != 0; } + bool hasMultipleIGMs() const { return hasMultipleIRGenThreads(); } }; } // end namespace swift diff --git a/include/swift/AST/IRGenRequests.h b/include/swift/AST/IRGenRequests.h index 3cd8212176aee..3887d8f8dca7c 100644 --- a/include/swift/AST/IRGenRequests.h +++ b/include/swift/AST/IRGenRequests.h @@ -172,6 +172,13 @@ struct IRGenDescriptor { outModuleHash, LinkerDirectives}; } + + /// Retrieves the files to perform IR generation for. + TinyPtrVector getFiles() const; + + /// For a single file, returns its parent module, otherwise returns the module + /// itself. + ModuleDecl *getParentModule() const; }; /// Report that a request of the given kind is being evaluated, so it @@ -180,10 +187,10 @@ template void reportEvaluatedRequest(UnifiedStatsReporter &stats, const Request &request); -class IRGenSourceFileRequest - : public SimpleRequest { +class IRGenRequest + : public SimpleRequest { public: using SimpleRequest::SimpleRequest; @@ -194,33 +201,12 @@ class IRGenSourceFileRequest GeneratedModule evaluate(Evaluator &evaluator, IRGenDescriptor desc) const; -public: - bool isCached() const { return true; } - public: // Incremental dependencies. evaluator::DependencySource readDependencySource(const evaluator::DependencyRecorder &) const; }; -class IRGenWholeModuleRequest - : public SimpleRequest { -public: - using SimpleRequest::SimpleRequest; - -private: - friend SimpleRequest; - - // Evaluation. - GeneratedModule - evaluate(Evaluator &evaluator, IRGenDescriptor desc) const; - -public: - bool isCached() const { return true; } -}; - void simple_display(llvm::raw_ostream &out, const IRGenDescriptor &d); SourceLoc extractNearestSourceLoc(const IRGenDescriptor &desc); diff --git a/include/swift/AST/IRGenTypeIDZone.def b/include/swift/AST/IRGenTypeIDZone.def index d865c79247fb0..e3f2ff3fba08a 100644 --- a/include/swift/AST/IRGenTypeIDZone.def +++ b/include/swift/AST/IRGenTypeIDZone.def @@ -14,10 +14,6 @@ // //===----------------------------------------------------------------------===// -SWIFT_REQUEST(IRGen, IRGenSourceFileRequest, +SWIFT_REQUEST(IRGen, IRGenRequest, GeneratedModule(IRGenDescriptor), Uncached, NoLocationInfo) -SWIFT_REQUEST(IRGen, IRGenWholeModuleRequest, - GeneratedModule(IRGenDescriptor), - Uncached, NoLocationInfo) - diff --git a/include/swift/AST/LocalizationFormat.h b/include/swift/AST/LocalizationFormat.h new file mode 100644 index 0000000000000..a4205bb85be72 --- /dev/null +++ b/include/swift/AST/LocalizationFormat.h @@ -0,0 +1,69 @@ +//===--- LocalizationFormat.h - YAML format for Diagnostic Messages ---*- +// C++ -*-===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2020 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 the format for localized diagnostic messages. +// +//===----------------------------------------------------------------------===// + +#ifndef SWIFT_LOCALIZATIONFORMAT_H +#define SWIFT_LOCALIZATIONFORMAT_H + +#include "llvm/ADT/StringRef.h" +#include "llvm/Support/YAMLParser.h" +#include "llvm/Support/YAMLTraits.h" +#include +#include + +namespace swift { +enum class DiagID : uint32_t; + +namespace diag { +class LocalizationProducer { +public: + /// If the message isn't available/localized in the current `yaml` file, + /// return the fallback default message. + virtual llvm::StringRef getMessageOr(swift::DiagID id, + llvm::StringRef defaultMessage) const { + return defaultMessage; + } + + virtual ~LocalizationProducer() {} +}; + +class YAMLLocalizationProducer final : public LocalizationProducer { +public: + std::vector diagnostics; + explicit YAMLLocalizationProducer(std::string locale, std::string path); + llvm::StringRef getMessageOr(swift::DiagID id, + llvm::StringRef defaultMessage) const override; +}; + +class LocalizationInput : public llvm::yaml::Input { + using Input::Input; + + /// Read diagnostics in the YAML file iteratively + template + friend typename std::enable_if::value, + void>::type + readYAML(llvm::yaml::IO &io, T &Seq, bool, Context &Ctx); + + template + friend typename std::enable_if::value, + LocalizationInput &>::type + operator>>(LocalizationInput &yin, T &diagnostics); +}; + +} // namespace diag +} // namespace swift + +#endif diff --git a/include/swift/AST/LocalizationLanguages.def b/include/swift/AST/LocalizationLanguages.def new file mode 100644 index 0000000000000..98bae1c23f8e1 --- /dev/null +++ b/include/swift/AST/LocalizationLanguages.def @@ -0,0 +1,207 @@ +//===--- LocalizationLanguages.def - Localization Languages ----*- C++ -*-===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2020 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 has all language codes defined by ISO 639-1 for localization. +// +//===----------------------------------------------------------------------===// + +#ifndef SUPPORTED_LOCALE +#define SUPPORTED_LOCALE(Code, Language) +#endif + +SUPPORTED_LOCALE(ab, Abkhazian) +SUPPORTED_LOCALE(aa, Afar) +SUPPORTED_LOCALE(af, Afrikaans) +SUPPORTED_LOCALE(ak, Akan) +SUPPORTED_LOCALE(sq, Albanian) +SUPPORTED_LOCALE(am, Amharic) +SUPPORTED_LOCALE(ar, Arabic) +SUPPORTED_LOCALE(an, Aragonese) +SUPPORTED_LOCALE(hy, Armenian) +SUPPORTED_LOCALE(as, Assamese) +SUPPORTED_LOCALE(av, Avaric) +SUPPORTED_LOCALE(ae, Avestan) +SUPPORTED_LOCALE(ay, Aymara) +SUPPORTED_LOCALE(az, Azerbaijani) +SUPPORTED_LOCALE(bm, Bambara) +SUPPORTED_LOCALE(ba, Bashkir) +SUPPORTED_LOCALE(eu, Basque) +SUPPORTED_LOCALE(be, Belarusian) +SUPPORTED_LOCALE(bn, Bengali) +SUPPORTED_LOCALE(bh, Bihari languages) +SUPPORTED_LOCALE(bi, Bislama) +SUPPORTED_LOCALE(bs, Bosnian) +SUPPORTED_LOCALE(br, Breton) +SUPPORTED_LOCALE(bg, Bulgarian) +SUPPORTED_LOCALE(my, Burmese) +SUPPORTED_LOCALE(ca, Catalan) +SUPPORTED_LOCALE(km, Central Khmer) +SUPPORTED_LOCALE(ch, Chamorro) +SUPPORTED_LOCALE(ce, Chechen) +SUPPORTED_LOCALE(ny, Chichewa) +SUPPORTED_LOCALE(zh, Chinese) +SUPPORTED_LOCALE(cu, Church Slavonic) +SUPPORTED_LOCALE(cv, Chuvash) +SUPPORTED_LOCALE(kw, Cornish) +SUPPORTED_LOCALE(co, Corsican) +SUPPORTED_LOCALE(cr, Cree) +SUPPORTED_LOCALE(hr, Croatian) +SUPPORTED_LOCALE(cs, Czech) +SUPPORTED_LOCALE(da, Danish) +SUPPORTED_LOCALE(dv, Divehi) +SUPPORTED_LOCALE(nl, Dutch) +SUPPORTED_LOCALE(dz, Dzongkha) +SUPPORTED_LOCALE(en, English) +SUPPORTED_LOCALE(eo, Esperanto) +SUPPORTED_LOCALE(et, Estonian) +SUPPORTED_LOCALE(ee, Ewe) +SUPPORTED_LOCALE(fo, Faroese) +SUPPORTED_LOCALE(fj, Fijian) +SUPPORTED_LOCALE(fi, Finnish) +SUPPORTED_LOCALE(fr, French) +SUPPORTED_LOCALE(ff, Fulah) +SUPPORTED_LOCALE(gd, Gaelic) +SUPPORTED_LOCALE(gl, Galician) +SUPPORTED_LOCALE(lg, Ganda) +SUPPORTED_LOCALE(ka, Georgian) +SUPPORTED_LOCALE(de, German) +SUPPORTED_LOCALE(ki, Kikuyu) +SUPPORTED_LOCALE(el, Greek) +SUPPORTED_LOCALE(kl, Kalaallisut) +SUPPORTED_LOCALE(gn, Guarani) +SUPPORTED_LOCALE(gu, Gujarati) +SUPPORTED_LOCALE(ht, Haitian Creole) +SUPPORTED_LOCALE(ha, Hausa) +SUPPORTED_LOCALE(he, Hebrew) +SUPPORTED_LOCALE(hz, Herero) +SUPPORTED_LOCALE(hi, Hindi) +SUPPORTED_LOCALE(ho, Hiri Motu) +SUPPORTED_LOCALE(hu, Hungarian) +SUPPORTED_LOCALE(is, Icelandic) +SUPPORTED_LOCALE(io, Ido) +SUPPORTED_LOCALE(ig, Igbo) +SUPPORTED_LOCALE(id, Indonesian) +SUPPORTED_LOCALE(ia, Interlingua) +SUPPORTED_LOCALE(ie, Interlingue) +SUPPORTED_LOCALE(iu, Inuktitut) +SUPPORTED_LOCALE(ik, Inupiaq) +SUPPORTED_LOCALE(ga, Irish) +SUPPORTED_LOCALE(it, Italian) +SUPPORTED_LOCALE(ja, Japanese) +SUPPORTED_LOCALE(jv, Javanese) +SUPPORTED_LOCALE(kn, Kannada) +SUPPORTED_LOCALE(kr, Kanuri) +SUPPORTED_LOCALE(ks, Kashmiri) +SUPPORTED_LOCALE(kk, Kazakh) +SUPPORTED_LOCALE(rw, Kinyarwanda) +SUPPORTED_LOCALE(kv, Komi) +SUPPORTED_LOCALE(kg, Kongo) +SUPPORTED_LOCALE(ko, Korean) +SUPPORTED_LOCALE(kj, Kwanyama) +SUPPORTED_LOCALE(ku, Kurdish) +SUPPORTED_LOCALE(ky, Kyrgyz) +SUPPORTED_LOCALE(lo, Lao) +SUPPORTED_LOCALE(la, Latin) +SUPPORTED_LOCALE(lv, Latvian) +SUPPORTED_LOCALE(lb, Letzeburgesch) +SUPPORTED_LOCALE(li, Limburgish) +SUPPORTED_LOCALE(ln, Lingala) +SUPPORTED_LOCALE(lt, Lithuanian) +SUPPORTED_LOCALE(lu, Luba-Katanga) +SUPPORTED_LOCALE(mk, Macedonian) +SUPPORTED_LOCALE(mg, Malagasy) +SUPPORTED_LOCALE(ms, Malay) +SUPPORTED_LOCALE(ml, Malayalam) +SUPPORTED_LOCALE(mt, Maltese) +SUPPORTED_LOCALE(gv, Manx) +SUPPORTED_LOCALE(mi, Maori) +SUPPORTED_LOCALE(mr, Marathi) +SUPPORTED_LOCALE(mh, Marshallese) +SUPPORTED_LOCALE(ro, Romanian) +SUPPORTED_LOCALE(mn, Mongolian) +SUPPORTED_LOCALE(na, Nauru) +SUPPORTED_LOCALE(nv, Navajo) +SUPPORTED_LOCALE(nd, Northern Ndebele) +SUPPORTED_LOCALE(ng, Ndonga) +SUPPORTED_LOCALE(ne, Nepali) +SUPPORTED_LOCALE(se, Northern Sami) +SUPPORTED_LOCALE(no, Norwegian) +SUPPORTED_LOCALE(nb, Norwegian Bokmål) +SUPPORTED_LOCALE(nn, Norwegian Nynorsk) +SUPPORTED_LOCALE(ii, Nuosu Sichuan Yi) +SUPPORTED_LOCALE(oc, Occitan) +SUPPORTED_LOCALE(oj, Ojibwa) +SUPPORTED_LOCALE(or, Oriya) +SUPPORTED_LOCALE(om, Oromo) +SUPPORTED_LOCALE(os, Ossetian) +SUPPORTED_LOCALE(pi, Pali) +SUPPORTED_LOCALE(pa, Panjabi) +SUPPORTED_LOCALE(ps, Pashto) +SUPPORTED_LOCALE(fa, Persian) +SUPPORTED_LOCALE(pl, Polish) +SUPPORTED_LOCALE(pt, Portuguese) +SUPPORTED_LOCALE(qu, Quechua) +SUPPORTED_LOCALE(rm, Romansh) +SUPPORTED_LOCALE(rn, Rundi) +SUPPORTED_LOCALE(ru, Russian) +SUPPORTED_LOCALE(sm, Samoan) +SUPPORTED_LOCALE(sg, Sango) +SUPPORTED_LOCALE(sa, Sanskrit) +SUPPORTED_LOCALE(sc, Sardinian) +SUPPORTED_LOCALE(sr, Serbian) +SUPPORTED_LOCALE(sn, Shona) +SUPPORTED_LOCALE(sd, Sindhi) +SUPPORTED_LOCALE(si, Sinhala Sinhalese) +SUPPORTED_LOCALE(sk, Slovak) +SUPPORTED_LOCALE(sl, Slovenian) +SUPPORTED_LOCALE(so, Somali) +SUPPORTED_LOCALE(st, Sotho Southern) +SUPPORTED_LOCALE(nr, South Ndebele) +SUPPORTED_LOCALE(es, Spanish Castilian) +SUPPORTED_LOCALE(su, Sundanese) +SUPPORTED_LOCALE(sw, Swahili) +SUPPORTED_LOCALE(ss, Swati) +SUPPORTED_LOCALE(sv, Swedish) +SUPPORTED_LOCALE(tl, Tagalog) +SUPPORTED_LOCALE(ty, Tahitian) +SUPPORTED_LOCALE(tg, Tajik) +SUPPORTED_LOCALE(ta, Tamil) +SUPPORTED_LOCALE(tt, Tatar) +SUPPORTED_LOCALE(te, Telugu) +SUPPORTED_LOCALE(th, Thai) +SUPPORTED_LOCALE(bo, Tibetan) +SUPPORTED_LOCALE(ti, Tigrinya) +SUPPORTED_LOCALE(to, Tonga) +SUPPORTED_LOCALE(ts, Tsonga) +SUPPORTED_LOCALE(tn, Tswana) +SUPPORTED_LOCALE(tr, Turkish) +SUPPORTED_LOCALE(tk, Turkmen) +SUPPORTED_LOCALE(tw, Twi) +SUPPORTED_LOCALE(ug, Uighur) +SUPPORTED_LOCALE(uk, Ukrainian) +SUPPORTED_LOCALE(ur, Urdu) +SUPPORTED_LOCALE(uz, Uzbek) +SUPPORTED_LOCALE(ve, Venda) +SUPPORTED_LOCALE(vi, Vietnamese) +SUPPORTED_LOCALE(vo, Volap_k) +SUPPORTED_LOCALE(wa, Walloon) +SUPPORTED_LOCALE(cy, Welsh) +SUPPORTED_LOCALE(fy, Western Frisian) +SUPPORTED_LOCALE(wo, Wolof) +SUPPORTED_LOCALE(xh, Xhosa) +SUPPORTED_LOCALE(yi, Yiddish) +SUPPORTED_LOCALE(yo, Yoruba) +SUPPORTED_LOCALE(za, Zhuang Chuang) +SUPPORTED_LOCALE(zu, Zulu) + +#undef SUPPORTED_LOCALE + diff --git a/include/swift/AST/ModuleDependencies.h b/include/swift/AST/ModuleDependencies.h index 47ff92fa8f3e4..e948157c832ac 100644 --- a/include/swift/AST/ModuleDependencies.h +++ b/include/swift/AST/ModuleDependencies.h @@ -73,6 +73,11 @@ class SwiftModuleDependenciesStorage : public ModuleDependenciesStorageBase { /// interface. const std::vector buildCommandLine; + /// To build a PCM to be used by this Swift module, we need to append these + /// arguments to the generic PCM build arguments reported from the dependency + /// graph. + const std::vector extraPCMArgs; + /// The hash value that will be used for the generated module const std::string contextHash; @@ -92,10 +97,12 @@ class SwiftModuleDependenciesStorage : public ModuleDependenciesStorageBase { const std::string &compiledModulePath, const Optional &swiftInterfaceFile, ArrayRef buildCommandLine, + ArrayRef extraPCMArgs, StringRef contextHash ) : ModuleDependenciesStorageBase(/*isSwiftModule=*/true, compiledModulePath), swiftInterfaceFile(swiftInterfaceFile), buildCommandLine(buildCommandLine.begin(), buildCommandLine.end()), + extraPCMArgs(extraPCMArgs.begin(), extraPCMArgs.end()), contextHash(contextHash) { } ModuleDependenciesStorageBase *clone() const override { @@ -173,13 +180,15 @@ class ModuleDependencies { /// Describe the module dependencies for a Swift module that can be /// built from a Swift interface file (\c .swiftinterface). static ModuleDependencies forSwiftInterface( - const std::string &compiledModulePath, const std::string &swiftInterfaceFile, ArrayRef buildCommands, + ArrayRef extraPCMArgs, StringRef contextHash) { + std::string compiledModulePath; return ModuleDependencies( std::make_unique( - compiledModulePath, swiftInterfaceFile, buildCommands, contextHash)); + compiledModulePath, swiftInterfaceFile, buildCommands, + extraPCMArgs, contextHash)); } /// Describe the module dependencies for a serialized or parsed Swift module. @@ -187,7 +196,17 @@ class ModuleDependencies { const std::string &compiledModulePath) { return ModuleDependencies( std::make_unique( - compiledModulePath, None, ArrayRef(), StringRef())); + compiledModulePath, None, ArrayRef(), + ArrayRef(), StringRef())); + } + + /// Describe the main Swift module. + static ModuleDependencies forMainSwiftModule(ArrayRef extraPCMArgs) { + std::string compiledModulePath; + return ModuleDependencies( + std::make_unique( + compiledModulePath, None, ArrayRef(), extraPCMArgs, + StringRef())); } /// Describe the module dependencies for a Clang module that can be diff --git a/include/swift/AST/ModuleLoader.h b/include/swift/AST/ModuleLoader.h index 6abeebcb8b8ba..a1c91e205a981 100644 --- a/include/swift/AST/ModuleLoader.h +++ b/include/swift/AST/ModuleLoader.h @@ -60,13 +60,22 @@ enum class Bridgeability : unsigned { Full }; +/// Specifies which dependencies the intermodule dependency tracker records. +enum class IntermoduleDepTrackingMode { + /// Records both system and non-system dependencies. + IncludeSystem, + + /// Records only non-system dependencies. + ExcludeSystem, +}; + /// Records dependencies on files outside of the current module; /// implemented in terms of a wrapped clang::DependencyCollector. class DependencyTracker { std::shared_ptr clangCollector; public: explicit DependencyTracker( - bool TrackSystemDeps, + IntermoduleDepTrackingMode Mode, std::shared_ptr FileCollector = {}); /// Adds a file as a dependency. @@ -89,6 +98,7 @@ struct SubCompilerInstanceInfo { CompilerInstance* Instance; StringRef Hash; ArrayRef BuildArguments; + ArrayRef ExtraPCMArgs; }; /// Abstract interface to run an action in a sub ASTContext. @@ -97,7 +107,8 @@ struct InterfaceSubContextDelegate { StringRef interfacePath, StringRef outputPath, SourceLoc diagLoc, - llvm::function_ref, StringRef)> action) = 0; + llvm::function_ref, + ArrayRef, StringRef)> action) = 0; virtual bool runInSubCompilerInstance(StringRef moduleName, StringRef interfacePath, StringRef outputPath, diff --git a/include/swift/AST/PlatformKind.h b/include/swift/AST/PlatformKind.h index f03d5adc8f7bf..be687b449b403 100644 --- a/include/swift/AST/PlatformKind.h +++ b/include/swift/AST/PlatformKind.h @@ -20,6 +20,7 @@ #include "swift/Basic/LLVM.h" #include "swift/Config.h" #include "llvm/ADT/StringRef.h" +#include "llvm/Support/VersionTuple.h" namespace swift { @@ -65,6 +66,9 @@ PlatformKind targetPlatform(const LangOptions &LangOpts); /// an explicit attribute for the child. bool inheritsAvailabilityFromPlatform(PlatformKind Child, PlatformKind Parent); +llvm::VersionTuple canonicalizePlatformVersion( + PlatformKind platform, const llvm::VersionTuple &version); + } // end namespace swift #endif diff --git a/include/swift/AST/SILOptions.h b/include/swift/AST/SILOptions.h index ac41b9e6aac0f..1ff15e19922e2 100644 --- a/include/swift/AST/SILOptions.h +++ b/include/swift/AST/SILOptions.h @@ -40,9 +40,6 @@ class SILOptions { /// Controls the aggressiveness of the loop unroller. int UnrollThreshold = 250; - /// The number of threads for multi-threaded code generation. - int NumThreads = 0; - /// Controls whether to pull in SIL from partial modules during the /// merge modules step. Could perhaps be merged with the link mode /// above but the interactions between all the flags are tricky. @@ -161,10 +158,6 @@ class SILOptions { /// Enable large loadable types IRGen pass. bool EnableLargeLoadableTypes = true; - /// Should the default pass pipelines strip ownership during the diagnostic - /// pipeline or after serialization. - bool StripOwnershipAfterSerialization = true; - /// The name of the file to which the backend should save optimization /// records. std::string OptRecordFile; @@ -187,10 +180,6 @@ class SILOptions { bool shouldOptimize() const { return OptMode > OptimizationMode::NoOptimization; } - - bool hasMultipleIRGenThreads() const { return NumThreads > 1; } - bool shouldPerformIRGenerationInParallel() const { return NumThreads != 0; } - bool hasMultipleIGMs() const { return hasMultipleIRGenThreads(); } }; } // end namespace swift diff --git a/include/swift/AST/SearchPathOptions.h b/include/swift/AST/SearchPathOptions.h index 36fc930d589ef..cd65528e48f17 100644 --- a/include/swift/AST/SearchPathOptions.h +++ b/include/swift/AST/SearchPathOptions.h @@ -85,6 +85,8 @@ class SearchPathOptions { /// The paths to a set of explicitly built modules from interfaces. std::vector ExplicitSwiftModules; + /// A map of explict Swift module information. + std::string ExplicitSwiftModuleMap; private: static StringRef pathStringFromFrameworkSearchPath(const FrameworkSearchPath &next) { diff --git a/include/swift/AST/Stmt.h b/include/swift/AST/Stmt.h index 513be8e40d774..7c8e535efbb2d 100644 --- a/include/swift/AST/Stmt.h +++ b/include/swift/AST/Stmt.h @@ -39,6 +39,8 @@ class Pattern; class PatternBindingDecl; class VarDecl; class CaseStmt; +class DoCatchStmt; +class SwitchStmt; enum class StmtKind { #define STMT(ID, PARENT) ID, @@ -927,6 +929,7 @@ class CaseStmt final CaseLabelItem> { friend TrailingObjects; + Stmt *ParentStmt = nullptr; SourceLoc UnknownAttrLoc; SourceLoc ItemIntroducerLoc; SourceLoc ItemTerminatorLoc; @@ -954,6 +957,14 @@ class CaseStmt final CaseParentKind getParentKind() const { return ParentKind; } + Stmt *getParentStmt() const { return ParentStmt; } + void setParentStmt(Stmt *S) { + assert(S && "Parent statement must be SwitchStmt or DoCatchStmt"); + assert((ParentKind == CaseParentKind::Switch && isa(S)) || + (ParentKind == CaseParentKind::DoCatch && isa(S))); + ParentStmt = S; + } + ArrayRef getCaseLabelItems() const { return {getTrailingObjects(), Bits.CaseStmt.NumPatterns}; } @@ -1161,6 +1172,8 @@ class DoCatchStmt final Bits.DoCatchStmt.NumCatches = catches.size(); std::uninitialized_copy(catches.begin(), catches.end(), getTrailingObjects()); + for (auto *catchStmt : getCatches()) + catchStmt->setParentStmt(this); } public: diff --git a/include/swift/AST/SubstitutionMap.h b/include/swift/AST/SubstitutionMap.h index deb897f5053bb..2f3549fabf6ba 100644 --- a/include/swift/AST/SubstitutionMap.h +++ b/include/swift/AST/SubstitutionMap.h @@ -150,6 +150,10 @@ class SubstitutionMap { /// generic parameters. ArrayRef getReplacementTypes() const; + /// Retrieve the array of replacement types for the innermost generic + /// parameters. + ArrayRef getInnermostReplacementTypes() const; + /// Query whether any replacement types in the map contain archetypes. bool hasArchetypes() const; @@ -282,6 +286,12 @@ class SubstitutionMap { Type lookupSubstitution(CanSubstitutableType type) const; }; +inline llvm::raw_ostream &operator<<(llvm::raw_ostream &OS, + const SubstitutionMap &subs) { + subs.dump(OS); + return OS; +} + /// A function object suitable for use as a \c TypeSubstitutionFn that /// queries an underlying \c SubstitutionMap. struct QuerySubstitutionMap { diff --git a/include/swift/AST/TypeCheckRequests.h b/include/swift/AST/TypeCheckRequests.h index 46d6b5ae0810a..48dd1a5b58301 100644 --- a/include/swift/AST/TypeCheckRequests.h +++ b/include/swift/AST/TypeCheckRequests.h @@ -1064,8 +1064,8 @@ class SynthesizeAccessorRequest : class EmittedMembersRequest : public SimpleRequest { + ArrayRef(ClassDecl *), + RequestFlags::Cached> { public: using SimpleRequest::SimpleRequest; @@ -1073,14 +1073,11 @@ class EmittedMembersRequest : friend SimpleRequest; // Evaluation. - DeclRange + ArrayRef evaluate(Evaluator &evaluator, ClassDecl *classDecl) const; public: - // Separate caching. bool isCached() const { return true; } - Optional getCachedResult() const; - void cacheResult(DeclRange value) const; }; class IsImplicitlyUnwrappedOptionalRequest : @@ -2191,6 +2188,27 @@ class DerivativeAttrOriginalDeclRequest bool isCached() const { return true; } }; +/// Resolves the "tangent stored property" corresponding to an original stored +/// property in a `Differentiable`-conforming type. +class TangentStoredPropertyRequest + : public SimpleRequest { +public: + using SimpleRequest::SimpleRequest; + +private: + friend SimpleRequest; + + // Evaluation. + TangentPropertyInfo evaluate(Evaluator &evaluator, VarDecl *originalField, + CanType parentType) const; + +public: + // Caching. + bool isCached() const { return true; } +}; + /// Checks whether a type eraser has a viable initializer. class TypeEraserHasViableInitRequest : public SimpleRequest(ClassDecl *), + Cached, NoLocationInfo) SWIFT_REQUEST(TypeChecker, EnumRawValuesRequest, evaluator::SideEffect (EnumDecl *, TypeResolutionStage), SeparatelyCached, NoLocationInfo) @@ -203,6 +203,8 @@ SWIFT_REQUEST(TypeChecker, SuperclassTypeRequest, SWIFT_REQUEST(TypeChecker, SynthesizeAccessorRequest, AccessorDecl *(AbstractStorageDecl *, AccessorKind), SeparatelyCached, NoLocationInfo) +SWIFT_REQUEST(TypeChecker, TangentStoredPropertyRequest, + llvm::Expected(VarDecl *, CanType), Cached, NoLocationInfo) SWIFT_REQUEST(TypeChecker, TypeCheckFunctionBodyRequest, bool(AbstractFunctionDecl *), Cached, NoLocationInfo) SWIFT_REQUEST(TypeChecker, TypeCheckFunctionBodyAtLocRequest, diff --git a/include/swift/AST/Types.h b/include/swift/AST/Types.h index abe0baf5a6a08..34d48b6e27622 100644 --- a/include/swift/AST/Types.h +++ b/include/swift/AST/Types.h @@ -24,7 +24,6 @@ #include "swift/AST/Ownership.h" #include "swift/AST/ProtocolConformanceRef.h" #include "swift/AST/Requirement.h" -#include "swift/AST/SILLayout.h" #include "swift/AST/SubstitutionMap.h" #include "swift/AST/Type.h" #include "swift/AST/TypeAlignments.h" @@ -786,6 +785,10 @@ class alignas(1 << TypeAlignInBits) TypeBase { /// Check if this is a nominal type defined at the top level of the Swift module bool isStdlibType(); + + /// Check if this is either an Array, Set or Dictionary collection type defined + /// at the top level of the Swift module + bool isKnownStdlibCollectionType(); /// If this is a class type or a bound generic class type, returns the /// (possibly generic) class. @@ -1813,13 +1816,10 @@ class TypeAliasType final return *getTrailingObjects(); } - /// Get the innermost generic arguments, which correspond to the generic - /// arguments that are directly applied to the typealias declaration in - /// produced by \c getDecl(). - /// - /// The result can be empty, if the declaration itself is non-generic but - /// the parent is generic. - SmallVector getInnermostGenericArgs() const; + /// Get the direct generic arguments, which correspond to the generic + /// arguments that are directly applied to the typealias declaration + /// this type references. + ArrayRef getDirectGenericArgs() const; // Support for FoldingSet. void Profile(llvm::FoldingSetNodeID &id) const; @@ -2888,6 +2888,10 @@ class AnyFunctionType : public TypeBase { Param getWithoutLabel() const { return Param(Ty, Identifier(), Flags); } + Param withLabel(Identifier newLabel) const { + return Param(Ty, newLabel, Flags); + } + Param withType(Type newType) const { return Param(newType, Label, Flags); } Param withFlags(ParameterTypeFlags flags) const { @@ -3640,7 +3644,7 @@ inline CanGenericSignature CanAnyFunctionType::getOptGenericSignature() const { } /// Conventions for passing arguments as parameters. -enum class ParameterConvention { +enum class ParameterConvention : uint8_t { /// This argument is passed indirectly, i.e. by directly passing the address /// of an object in memory. The callee is responsible for destroying the /// object. The callee may assume that the address does not alias any valid @@ -3686,7 +3690,7 @@ enum class ParameterConvention { }; // Check that the enum values fit inside Bits.SILFunctionType. static_assert(unsigned(ParameterConvention::Direct_Guaranteed) < (1<<3), - "fits in Bits.SILFunctionType and SILParameterInfo"); + "fits in Bits.SILFunctionType"); // Does this parameter convention require indirect storage? This reflects a // SILFunctionType's formal (immutable) conventions, as opposed to the transient @@ -3745,7 +3749,7 @@ inline bool isGuaranteedParameter(ParameterConvention conv) { } /// The differentiability of a SIL function type parameter. -enum class SILParameterDifferentiability : unsigned { +enum class SILParameterDifferentiability : bool { /// Either differentiable or not applicable. /// /// - If the function type is not `@differentiable`, parameter @@ -3763,8 +3767,9 @@ enum class SILParameterDifferentiability : unsigned { /// A parameter type and the rules for passing it. class SILParameterInfo { - llvm::PointerIntPair TypeAndConvention; - SILParameterDifferentiability Differentiability : 1; + CanType Type; + ParameterConvention Convention; + SILParameterDifferentiability Differentiability; public: SILParameterInfo() = default;//: Ty(), Convention((ParameterConvention)0) {} @@ -3772,7 +3777,7 @@ class SILParameterInfo { CanType type, ParameterConvention conv, SILParameterDifferentiability differentiability = SILParameterDifferentiability::DifferentiableOrNotApplicable) - : TypeAndConvention(type, conv), Differentiability(differentiability) { + : Type(type), Convention(conv), Differentiability(differentiability) { assert(type->isLegalSILType() && "SILParameterInfo has illegal SIL type"); } @@ -3781,7 +3786,7 @@ class SILParameterInfo { /// /// For most purposes, you probably want \c getArgumentType . CanType getInterfaceType() const { - return TypeAndConvention.getPointer(); + return Type; } /// Return the type of a call argument matching this parameter. @@ -3789,7 +3794,7 @@ class SILParameterInfo { /// \c t must refer back to the function type this is a parameter for. CanType getArgumentType(SILModule &M, const SILFunctionType *t, TypeExpansionContext context) const; ParameterConvention getConvention() const { - return TypeAndConvention.getInt(); + return Convention; } // Does this parameter convention require indirect storage? This reflects a // SILFunctionType's formal (immutable) conventions, as opposed to the @@ -3908,7 +3913,7 @@ class SILParameterInfo { }; /// Conventions for returning values. -enum class ResultConvention { +enum class ResultConvention : uint8_t { /// This result is returned indirectly, i.e. by passing the address /// of an uninitialized object in memory. The callee is responsible /// for leaving an initialized object at this address. The callee @@ -3943,7 +3948,7 @@ inline bool isIndirectFormalResult(ResultConvention convention) { } /// The differentiability of a SIL function type result. -enum class SILResultDifferentiability : unsigned { +enum class SILResultDifferentiability : bool { /// Either differentiable or not applicable. /// /// - If the function type is not `@differentiable`, result @@ -3961,15 +3966,16 @@ enum class SILResultDifferentiability : unsigned { /// A result type and the rules for returning it. class SILResultInfo { - llvm::PointerIntPair TypeAndConvention; - SILResultDifferentiability Differentiability : 1; + CanType Type; + ResultConvention Convention; + SILResultDifferentiability Differentiability; public: SILResultInfo() = default; SILResultInfo(CanType type, ResultConvention conv, SILResultDifferentiability differentiability = SILResultDifferentiability::DifferentiableOrNotApplicable) - : TypeAndConvention(type, conv), Differentiability(differentiability) { + : Type(type), Convention(conv), Differentiability(differentiability) { assert(type->isLegalSILType() && "SILResultInfo has illegal SIL type"); } @@ -3978,7 +3984,7 @@ class SILResultInfo { /// /// For most purposes, you probably want \c getReturnValueType . CanType getInterfaceType() const { - return TypeAndConvention.getPointer(); + return Type; } /// The type of a return value corresponding to this result. @@ -3988,7 +3994,7 @@ class SILResultInfo { TypeExpansionContext context) const; ResultConvention getConvention() const { - return TypeAndConvention.getInt(); + return Convention; } SILResultDifferentiability getDifferentiability() const { @@ -4056,8 +4062,9 @@ class SILResultInfo { } void profile(llvm::FoldingSetNodeID &id) { - id.AddPointer(TypeAndConvention.getOpaqueValue()); - id.AddInteger((unsigned)getDifferentiability()); + id.AddPointer(Type.getPointer()); + id.AddInteger(unsigned(getConvention())); + id.AddInteger(unsigned(getDifferentiability())); } SWIFT_DEBUG_DUMP; @@ -4074,7 +4081,8 @@ class SILResultInfo { getOwnershipKind(SILFunction &, CanSILFunctionType fTy) const; // in SILType.cpp bool operator==(SILResultInfo rhs) const { - return TypeAndConvention == rhs.TypeAndConvention; + return Type == rhs.Type && Convention == rhs.Convention + && Differentiability == rhs.Differentiability; } bool operator!=(SILResultInfo rhs) const { return !(*this == rhs); @@ -5567,25 +5575,7 @@ class ArchetypeType : public SubstitutableType, /// find a particular nested type by name, directly, or look at the /// protocols to which this archetype conforms. ArrayRef> - getKnownNestedTypes(bool resolveTypes = true) const { - return getAllNestedTypes(/*resolveTypes=*/false); - } - - /// Retrieve the nested types of this archetype. - /// - /// \param resolveTypes Whether to eagerly resolve the nested types - /// (defaults to \c true). Otherwise, the nested types might be - /// null. - /// - /// FIXME: This operation should go away, because it breaks recursive - /// protocol constraints. - ArrayRef> - getAllNestedTypes(bool resolveTypes = true) const; - - /// Set the nested types to a copy of the given array of - /// archetypes. - void setNestedTypes(ASTContext &Ctx, - ArrayRef> Nested); + getKnownNestedTypes() const; /// Register a nested type with the given name. void registerNestedType(Identifier name, Type nested); diff --git a/include/swift/AST/diagnostics/en.yaml b/include/swift/AST/diagnostics/en.yaml new file mode 100644 index 0000000000000..561ed57dfff71 --- /dev/null +++ b/include/swift/AST/diagnostics/en.yaml @@ -0,0 +1,19 @@ +#===--- en.yaml - Localized diagnostic messages for English ---*- YAML -*-===# +# +# This source file is part of the Swift.org open source project +# +# Copyright (c) 2014 - 2020 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 the diagnostic messages for the English language. +# Each diagnostic is described in the following format: +# - id: "" +# msg: "" +# +#===----------------------------------------------------------------------===# + diff --git a/include/swift/Basic/DiagnosticOptions.h b/include/swift/Basic/DiagnosticOptions.h index 31e6149412692..e2f1c5ef22b71 100644 --- a/include/swift/Basic/DiagnosticOptions.h +++ b/include/swift/Basic/DiagnosticOptions.h @@ -67,6 +67,11 @@ class DiagnosticOptions { std::string DiagnosticDocumentationPath = ""; + std::string LocalizationCode = ""; + + // Diagnostic messages directory path. + std::string LocalizationPath = ""; + /// Return a hash code of any components from these options that should /// contribute to a Swift Bridging PCH hash. llvm::hash_code getPCHHashComponents() const { diff --git a/include/swift/Basic/Mangler.h b/include/swift/Basic/Mangler.h index 93c0875f52d0b..c14d78fac68ee 100644 --- a/include/swift/Basic/Mangler.h +++ b/include/swift/Basic/Mangler.h @@ -14,6 +14,7 @@ #define SWIFT_BASIC_MANGLER_H #include "swift/Demangling/ManglingUtils.h" +#include "swift/Demangling/NamespaceMacros.h" #include "swift/Basic/Debug.h" #include "swift/Basic/LLVM.h" #include "llvm/ADT/DenseMap.h" @@ -24,6 +25,7 @@ namespace swift { namespace Mangle { +SWIFT_BEGIN_INLINE_NAMESPACE void printManglingStats(); @@ -204,6 +206,7 @@ class Mangler { } }; +SWIFT_END_INLINE_NAMESPACE } // end namespace Mangle } // end namespace swift diff --git a/include/swift/Basic/OptionSet.h b/include/swift/Basic/OptionSet.h index a5e0d25aa00b6..c5758b250ca9c 100644 --- a/include/swift/Basic/OptionSet.h +++ b/include/swift/Basic/OptionSet.h @@ -21,6 +21,7 @@ #include #include +#include namespace swift { @@ -58,6 +59,10 @@ class OptionSet { /// Create an option set with only the given option set. constexpr OptionSet(Flags flag) : Storage(static_cast(flag)) {} + /// Create an option set containing the given options. + constexpr OptionSet(std::initializer_list flags) + : Storage(combineFlags(flags)) {} + /// Create an option set from raw storage. explicit constexpr OptionSet(StorageType storage) : Storage(storage) {} @@ -136,6 +141,14 @@ class OptionSet { static void _checkResultTypeOperatorOr(...) {} + static constexpr StorageType + combineFlags(const std::initializer_list &flags) { + OptionSet result; + for (Flags flag : flags) + result |= flag; + return result.Storage; + } + static_assert(!std::is_same::value, "operator| should produce an OptionSet"); diff --git a/include/swift/ClangImporter/ClangImporter.h b/include/swift/ClangImporter/ClangImporter.h index e894dd1855535..128886f6c0bed 100644 --- a/include/swift/ClangImporter/ClangImporter.h +++ b/include/swift/ClangImporter/ClangImporter.h @@ -175,7 +175,7 @@ class ClangImporter final : public ClangModuleLoader { /// Create a new clang::DependencyCollector customized to /// ClangImporter's specific uses. static std::shared_ptr - createDependencyCollector(bool TrackSystemDeps, + createDependencyCollector(IntermoduleDepTrackingMode Mode, std::shared_ptr FileCollector); /// Append visible module names to \p names. Note that names are possibly diff --git a/include/swift/Demangling/Demangle.h b/include/swift/Demangling/Demangle.h index 61934a820e357..bb1b286847f14 100644 --- a/include/swift/Demangling/Demangle.h +++ b/include/swift/Demangling/Demangle.h @@ -25,6 +25,7 @@ #include #include "llvm/ADT/StringRef.h" #include "swift/Runtime/Config.h" +#include "swift/Demangling/NamespaceMacros.h" namespace llvm { class raw_ostream; @@ -32,6 +33,7 @@ namespace llvm { namespace swift { namespace Demangle { +SWIFT_BEGIN_INLINE_NAMESPACE enum class SymbolicReferenceKind : uint8_t; @@ -621,6 +623,7 @@ bool isFunctionAttr(Node::Kind kind); /// contain symbolic references. llvm::StringRef makeSymbolicMangledNameStringRef(const char *base); +SWIFT_END_INLINE_NAMESPACE } // end namespace Demangle } // end namespace swift diff --git a/include/swift/Demangling/Demangler.h b/include/swift/Demangling/Demangler.h index 30da4d715c917..3616ff426af86 100644 --- a/include/swift/Demangling/Demangler.h +++ b/include/swift/Demangling/Demangler.h @@ -20,6 +20,7 @@ #define SWIFT_DEMANGLING_DEMANGLER_H #include "swift/Demangling/Demangle.h" +#include "swift/Demangling/NamespaceMacros.h" //#define NODE_FACTORY_DEBUGGING @@ -28,6 +29,7 @@ using llvm::StringRef; namespace swift { namespace Demangle { +SWIFT_BEGIN_INLINE_NAMESPACE class CharVector; @@ -622,6 +624,7 @@ template class StackAllocatedDemangler : public Demangler { NodePointer demangleOldSymbolAsNode(StringRef MangledName, NodeFactory &Factory); +SWIFT_END_INLINE_NAMESPACE } // end namespace Demangle } // end namespace swift diff --git a/include/swift/Demangling/ManglingUtils.h b/include/swift/Demangling/ManglingUtils.h index c1afbb4f0def3..e15872004ddab 100644 --- a/include/swift/Demangling/ManglingUtils.h +++ b/include/swift/Demangling/ManglingUtils.h @@ -14,10 +14,12 @@ #define SWIFT_DEMANGLING_MANGLINGUTILS_H #include "llvm/ADT/StringRef.h" +#include "swift/Demangling/NamespaceMacros.h" #include "swift/Demangling/Punycode.h" namespace swift { namespace Mangle { +SWIFT_BEGIN_INLINE_NAMESPACE using llvm::StringRef; @@ -190,9 +192,8 @@ void mangleIdentifier(Mangler &M, StringRef ident) { // Mangle the sub-string up to the next word substitution (or to the end // of the identifier - that's why we added the dummy-word). // The first thing: we add the encoded sub-string length. + bool first = true; M.Buffer << (Repl.StringPos - Pos); - assert(!isDigit(ident[Pos]) && - "first char of sub-string may not be a digit"); do { // Update the start position of new added words, so that they refer to // the begin of the whole mangled Buffer. @@ -201,9 +202,16 @@ void mangleIdentifier(Mangler &M, StringRef ident) { M.Words[WordsInBuffer].start = M.getBufferStr().size(); WordsInBuffer++; } + // Error recovery. We sometimes need to mangle identifiers coming + // from invalid code. + if (first && isDigit(ident[Pos])) + M.Buffer << 'X'; // Add a literal character of the sub-string. - M.Buffer << ident[Pos]; + else + M.Buffer << ident[Pos]; + Pos++; + first = false; } while (Pos < Repl.StringPos); } // Is it a "real" word substitution (and not the dummy-word)? @@ -311,6 +319,7 @@ class SubstitutionMerging { } }; +SWIFT_END_INLINE_NAMESPACE } // end namespace Mangle } // end namespace swift diff --git a/include/swift/Demangling/NamespaceMacros.h b/include/swift/Demangling/NamespaceMacros.h new file mode 100644 index 0000000000000..66c3d9ea87073 --- /dev/null +++ b/include/swift/Demangling/NamespaceMacros.h @@ -0,0 +1,35 @@ +//===--- NamespaceMacros.h - Macros for inline namespaces -------*- C++ -*-===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2020 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 +// +//===----------------------------------------------------------------------===// +// +// Macros that conditionally define an inline namespace so that symbols used in +// multiple places (such as in the compiler and in the runtime library) can be +// given distinct mangled names in different contexts without affecting client +// usage in source. +// +//===----------------------------------------------------------------------===// + +#ifndef SWIFT_DEMANGLING_NAMESPACE_MACROS_H +#define SWIFT_DEMANGLING_NAMESPACE_MACROS_H + +#if defined(__cplusplus) + +#if defined(SWIFT_INLINE_NAMESPACE) +#define SWIFT_BEGIN_INLINE_NAMESPACE inline namespace SWIFT_INLINE_NAMESPACE { +#define SWIFT_END_INLINE_NAMESPACE } +#else +#define SWIFT_BEGIN_INLINE_NAMESPACE +#define SWIFT_END_INLINE_NAMESPACE +#endif + +#endif + +#endif // SWIFT_DEMANGLING_NAMESPACE_MACROS_H diff --git a/include/swift/Demangling/Punycode.h b/include/swift/Demangling/Punycode.h index 8d32e53581c92..01eb08d593d7d 100644 --- a/include/swift/Demangling/Punycode.h +++ b/include/swift/Demangling/Punycode.h @@ -28,11 +28,13 @@ #define SWIFT_DEMANGLING_PUNYCODE_H #include "llvm/ADT/StringRef.h" +#include "swift/Demangling/NamespaceMacros.h" #include #include namespace swift { namespace Punycode { +SWIFT_BEGIN_INLINE_NAMESPACE using llvm::StringRef; @@ -58,6 +60,7 @@ bool encodePunycodeUTF8(StringRef InputUTF8, std::string &OutPunycode, bool decodePunycodeUTF8(StringRef InputPunycode, std::string &OutUTF8); +SWIFT_END_INLINE_NAMESPACE } // end namespace Punycode } // end namespace swift diff --git a/include/swift/Demangling/TypeDecoder.h b/include/swift/Demangling/TypeDecoder.h index 2e293989934ee..89631c291b36e 100644 --- a/include/swift/Demangling/TypeDecoder.h +++ b/include/swift/Demangling/TypeDecoder.h @@ -20,6 +20,7 @@ #include "swift/ABI/MetadataValues.h" #include "swift/Demangling/Demangler.h" +#include "swift/Demangling/NamespaceMacros.h" #include "swift/Basic/LLVM.h" #include "swift/Runtime/Unreachable.h" #include "swift/Strings.h" @@ -28,6 +29,7 @@ namespace swift { namespace Demangle { +SWIFT_BEGIN_INLINE_NAMESPACE enum class ImplMetatypeRepresentation { Thin, @@ -1152,6 +1154,7 @@ decodeMangledType(BuilderType &Builder, } +SWIFT_END_INLINE_NAMESPACE } // end namespace Demangle } // end namespace swift diff --git a/include/swift/Frontend/Frontend.h b/include/swift/Frontend/Frontend.h index f8cad378fc6ae..72555f19f02e0 100644 --- a/include/swift/Frontend/Frontend.h +++ b/include/swift/Frontend/Frontend.h @@ -498,10 +498,6 @@ class CompilerInstance { Diagnostics.removeConsumer(*DC); } - void createDependencyTracker(bool TrackSystemDeps) { - assert(!Context && "must be called before setup()"); - DepTracker = std::make_unique(TrackSystemDeps); - } DependencyTracker *getDependencyTracker() { return DepTracker.get(); } const DependencyTracker *getDependencyTracker() const { return DepTracker.get(); } @@ -582,6 +578,7 @@ class CompilerInstance { bool setUpASTContextIfNeeded(); void setupStatsReporter(); void setupDiagnosticVerifierIfNeeded(); + void setupDependencyTrackerIfNeeded(); Optional setUpCodeCompletionBuffer(); /// Set up all state in the CompilerInstance to process the given input file. diff --git a/include/swift/Frontend/FrontendOptions.h b/include/swift/Frontend/FrontendOptions.h index 201202cd983a1..306df2cb29719 100644 --- a/include/swift/Frontend/FrontendOptions.h +++ b/include/swift/Frontend/FrontendOptions.h @@ -27,7 +27,7 @@ namespace llvm { } namespace swift { - +enum class IntermoduleDepTrackingMode; /// Options for controlling the behavior of the frontend. class FrontendOptions { @@ -134,6 +134,7 @@ class FrontendOptions { DumpPCM, ///< Dump information about a precompiled Clang module ScanDependencies, ///< Scan dependencies of Swift source files + PrintVersion, ///< Print version information. }; /// Indicates the action the user requested that the frontend perform. @@ -236,9 +237,10 @@ class FrontendOptions { /// See the \ref SILOptions.EmitSortedSIL flag. bool EmitSortedSIL = false; - /// Indicates whether the dependency tracker should track system - /// dependencies as well. - bool TrackSystemDeps = false; + /// Specifies the collection mode for the intermodule dependency tracker. + /// Note that if set, the dependency tracker will be enabled even if no + /// output path is configured. + Optional IntermoduleDependencyTracking; /// Should we serialize the hashes of dependencies (vs. the modification /// times) when compiling a module interface? @@ -287,9 +289,6 @@ class FrontendOptions { /// -dump-scope-maps. SmallVector, 2> DumpScopeMapLocations; - /// Indicates whether the action will immediately run code. - static bool isActionImmediate(ActionType); - /// \return true if action only parses without doing other compilation steps. static bool shouldActionOnlyParse(ActionType); @@ -317,6 +316,9 @@ class FrontendOptions { return ImplicitImportModuleNames; } + /// Whether we're configured to track system intermodule dependencies. + bool shouldTrackSystemDependencies() const; + private: static bool canActionEmitDependencies(ActionType); static bool canActionEmitReferenceDependencies(ActionType); diff --git a/include/swift/Frontend/ModuleInterfaceLoader.h b/include/swift/Frontend/ModuleInterfaceLoader.h index 22c183beb2c69..edfd4c75e81be 100644 --- a/include/swift/Frontend/ModuleInterfaceLoader.h +++ b/include/swift/Frontend/ModuleInterfaceLoader.h @@ -150,6 +150,7 @@ class ExplicitSwiftModuleLoader: public SerializedModuleLoaderBase { create(ASTContext &ctx, DependencyTracker *tracker, ModuleLoadingMode loadMode, ArrayRef ExplicitModulePaths, + StringRef ExplicitSwiftModuleMap, bool IgnoreSwiftSourceInfoFile); /// Append visible module names to \p names. Note that names are possibly @@ -201,7 +202,6 @@ class ModuleInterfaceLoader : public SerializedModuleLoaderBase { std::unique_ptr *ModuleSourceInfoBuffer) override; bool isCached(StringRef DepPath) override; - public: static std::unique_ptr create(ASTContext &ctx, StringRef cacheDir, StringRef prebuiltCacheDir, @@ -234,6 +234,9 @@ class ModuleInterfaceLoader : public SerializedModuleLoaderBase { StringRef ModuleName, StringRef InPath, StringRef OutPath, bool SerializeDependencyHashes, bool TrackSystemDependencies, ModuleInterfaceLoaderOptions Opts); + + std::string getUpToDateCompiledModuleForInterface(StringRef moduleName, + StringRef interfacePath) override; }; struct InterfaceSubContextDelegateImpl: InterfaceSubContextDelegate { @@ -244,7 +247,6 @@ struct InterfaceSubContextDelegateImpl: InterfaceSubContextDelegate { llvm::StringSaver ArgSaver; std::vector GenericArgs; CompilerInvocation subInvocation; - std::vector ModuleOutputPaths; template InFlightDiagnostic diagnose(StringRef interfacePath, @@ -280,7 +282,8 @@ struct InterfaceSubContextDelegateImpl: InterfaceSubContextDelegate { StringRef interfacePath, StringRef outputPath, SourceLoc diagLoc, - llvm::function_ref, StringRef)> action) override; + llvm::function_ref, + ArrayRef, StringRef)> action) override; bool runInSubCompilerInstance(StringRef moduleName, StringRef interfacePath, StringRef outputPath, diff --git a/include/swift/IDE/ConformingMethodList.h b/include/swift/IDE/ConformingMethodList.h index 1dbe1c3770972..d755f080798ae 100644 --- a/include/swift/IDE/ConformingMethodList.h +++ b/include/swift/IDE/ConformingMethodList.h @@ -42,6 +42,7 @@ class ConformingMethodListConsumer { public: virtual ~ConformingMethodListConsumer() {} virtual void handleResult(const ConformingMethodListResult &result) = 0; + virtual void setReusingASTContext(bool flag) = 0; }; /// Printing consumer @@ -53,6 +54,7 @@ class PrintingConformingMethodListConsumer PrintingConformingMethodListConsumer(llvm::raw_ostream &OS) : OS(OS) {} void handleResult(const ConformingMethodListResult &result) override; + void setReusingASTContext(bool flag) override {} }; /// Create a factory for code completion callbacks. diff --git a/include/swift/IDE/TypeContextInfo.h b/include/swift/IDE/TypeContextInfo.h index 2bb8c95053710..ed12906edf303 100644 --- a/include/swift/IDE/TypeContextInfo.h +++ b/include/swift/IDE/TypeContextInfo.h @@ -38,6 +38,7 @@ class TypeContextInfoConsumer { public: virtual ~TypeContextInfoConsumer() {} virtual void handleResults(ArrayRef) = 0; + virtual void setReusingASTContext(bool flag) = 0; }; /// Printing consumer @@ -48,6 +49,7 @@ class PrintingTypeContextInfoConsumer : public TypeContextInfoConsumer { PrintingTypeContextInfoConsumer(llvm::raw_ostream &OS) : OS(OS) {} void handleResults(ArrayRef) override; + void setReusingASTContext(bool flag) override {} }; /// Create a factory for code completion callbacks. diff --git a/include/swift/Option/FrontendOptions.td b/include/swift/Option/FrontendOptions.td index 42b4e5db2974c..2da46f6f1c087 100644 --- a/include/swift/Option/FrontendOptions.td +++ b/include/swift/Option/FrontendOptions.td @@ -220,6 +220,10 @@ def disable_implicit_swift_modules: Flag<["-"], "disable-implicit-swift-modules" def swift_module_file : Separate<["-"], "swift-module-file">, MetaVarName<"">, HelpText<"Specify Swift module explicitly built from textual interface">; + +def explict_swift_module_map + : Separate<["-"], "explicit-swift-module-map-file">, MetaVarName<"">, + HelpText<"Specify a JSON file containing information of explict Swift modules">; } @@ -289,10 +293,6 @@ def disable_sil_partial_apply : Flag<["-"], "disable-sil-partial-apply">, def enable_spec_devirt : Flag<["-"], "enable-spec-devirt">, HelpText<"Enable speculative devirtualization pass.">; -def enable_ownership_stripping_after_serialization - : Flag<["-"], "enable-ownership-stripping-after-serialization">, - HelpText<"Strip ownership after serialization">; - def disable_access_control : Flag<["-"], "disable-access-control">, HelpText<"Don't respect access control restrictions">; def enable_access_control : Flag<["-"], "enable-access-control">, diff --git a/include/swift/Option/Options.td b/include/swift/Option/Options.td index edaf19bdc3559..226a26d64a367 100644 --- a/include/swift/Option/Options.td +++ b/include/swift/Option/Options.td @@ -213,7 +213,7 @@ def help_hidden : Flag<["-", "--"], "help-hidden">, def v : Flag<["-"], "v">, Flags<[DoesNotAffectIncrementalBuild]>, HelpText<"Show commands to run and use verbose output">; -def version : Flag<["-", "--"], "version">, +def version : Flag<["-", "--"], "version">, Flags<[FrontendOption]>, HelpText<"Print version information and exit">; def parseable_output : Flag<["-"], "parseable-output">, @@ -389,6 +389,14 @@ def diagnostic_style : Separate<["-"], "diagnostic-style">, def diagnostic_style_EQ : Joined<["-"], "diagnostic-style=">, Flags<[FrontendOption, DoesNotAffectIncrementalBuild]>, MetaVarName<"