swiftlang / swift

The Swift Programming Language
https://swift.org
Apache License 2.0
67.29k stars 10.34k forks source link

Assertion failed: (isa<To>(Val) && "cast<Ty>() argument of incompatible type!") #75774

Open JaapWijnen opened 1 month ago

JaapWijnen commented 1 month ago

Description

The following code fails to compile in release mode. (Debug mode works!) The crash only happens when the code is in a separate module and called from a second module, executable.

swift build -c release

Reproduction

Package.swift

// swift-tools-version: 5.9

import PackageDescription

let package = Package(
    name: "release-build-crash",
    products: [
        .executable(name: "Executable", targets: ["Executable"]),
        .library(name: "Library", targets: ["Library"]),
    ],
    targets: [
        .target(name: "Library"),
        .executableTarget(
            name: "Executable",
            dependencies: [
                "Library",
            ]
        ),
    ]
)

Sources/Executable/Executable.swift

import Library

let optimizedInitialWaterLevelArray2D = Solution<Array2D>.optimization()

Sources/Library/Library.swift

import Foundation
import _Differentiation

public struct Solution<Storage: Storage2D<Float>>: Differentiable {
    public var currentWaterLevel: Storage
    public var previousWaterLevel: Storage

    @noDerivative public var time: Float

    @inlinable // removing this inlinable makes it build
    public static func optimization() -> Storage {
        var initialWaterLevel = Storage(repeating: 0)

        let (_, delta) = valueWithGradient(at: initialWaterLevel, of: simulationWithLoss)

        initialWaterLevel.move(by: delta)

        return initialWaterLevel
    }
}

@inlinable // removing this @inlinable makes it build
@differentiable(reverse)
public func simulationWithLoss<Storage>(input: Storage) -> Float where Storage: Storage2D<Float> {
    return input.read(0, 0)
}

public protocol Storage2D<Element>: Differentiable where Element: Differentiable {
    associatedtype Element

    @differentiable(reverse)
    func read(_ x: Int, _ y: Int) -> Element

    init(repeating: Element)
}

public struct Array2D: Storage2D, Equatable, AdditiveArithmetic {
    public var values: [Float]

    public init(repeating element: Float) {
        self.values = .init(repeating: element, count: 1)
    }

    public static var zero: Array2D {
        fatalError()
    }

    public static func +(lhs: Array2D, rhs: Array2D) -> Array2D {
        fatalError()
    }

    public static func -(lhs: Array2D, rhs: Array2D) -> Array2D {
        fatalError()
    }

    public mutating func move(by offset: TangentVector) {
        fatalError()
    }

    @differentiable(reverse)
    public func read(_ x: Int, _ y: Int) -> Float {
        values[x + y]
    }

    @derivative(of: read)
    public func readVJP(x: Int, y: Int) -> (value: Float, pullback: (Float.TangentVector) -> TangentVector) {
        func pullback(_ v: Float.TangentVector) -> TangentVector {
            fatalError()
        }
        return (value: self.read(x, y), pullback: pullback)
    }
}

Stack dump

error: compile command failed due to signal 6 (use -v to see invocation)
Assertion failed: (isa<To>(Val) && "cast<Ty>() argument of incompatible type!"), function cast, file Casting.h, line 578.
Please submit a bug report (https://swift.org/contributing/#reporting-bugs) and include the crash backtrace.
Stack dump:
0.  Program arguments: /Users/jaap/Developer/swift-project/build/Ninja-RelWithDebInfoAssert/toolchain-macosx-arm64/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift-frontend -frontend -c /Users/jaap/Developer/PassiveLogic/autodiff-release-crasher/Sources/Executable/main.swift -emit-module-path /Users/jaap/Developer/PassiveLogic/autodiff-release-crasher/.build/arm64-apple-macosx/release/Modules/Executable.swiftmodule -emit-module-doc-path /Users/jaap/Developer/PassiveLogic/autodiff-release-crasher/.build/arm64-apple-macosx/release/Modules/Executable.swiftdoc -emit-module-source-info-path /Users/jaap/Developer/PassiveLogic/autodiff-release-crasher/.build/arm64-apple-macosx/release/Modules/Executable.swiftsourceinfo -emit-dependencies-path /Users/jaap/Developer/PassiveLogic/autodiff-release-crasher/.build/arm64-apple-macosx/release/Executable.build/Executable.d -emit-abi-descriptor-path /Users/jaap/Developer/PassiveLogic/autodiff-release-crasher/.build/arm64-apple-macosx/release/Modules/Executable.abi.json -target arm64-apple-macosx10.13 -Xllvm -aarch64-use-tbi -enable-objc-interop -sdk /Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX15.0.sdk -I /Users/jaap/Developer/PassiveLogic/autodiff-release-crasher/.build/arm64-apple-macosx/release/Modules -I /Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/usr/lib -F /Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks -color-diagnostics -g -debug-info-format=dwarf -dwarf-version=4 -module-cache-path /Users/jaap/Developer/PassiveLogic/autodiff-release-crasher/.build/arm64-apple-macosx/release/ModuleCache -swift-version 5 -O -D SWIFT_PACKAGE -entry-point-function-name Executable_main -empty-abi-descriptor -resource-dir /Users/jaap/Developer/swift-project/build/Ninja-RelWithDebInfoAssert/toolchain-macosx-arm64/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift -file-compilation-dir /Users/jaap/Developer/PassiveLogic/autodiff-release-crasher -Xcc -isysroot -Xcc /Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX15.0.sdk -Xcc -F -Xcc /Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks -Xcc -fPIC -Xcc -g -module-name Executable -package-name autodiff_release_crasher -plugin-path /Users/jaap/Developer/swift-project/build/Ninja-RelWithDebInfoAssert/toolchain-macosx-arm64/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/host/plugins -plugin-path /Users/jaap/Developer/swift-project/build/Ninja-RelWithDebInfoAssert/toolchain-macosx-arm64/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/local/lib/swift/host/plugins -target-sdk-version 15.0 -target-sdk-name macosx15.0 -external-plugin-path /Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/usr/lib/swift/host/plugins#/Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/usr/bin/swift-plugin-server -external-plugin-path /Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/usr/local/lib/swift/host/plugins#/Applications/Xcode-beta.app/Contents/Developer/Platforms/MacOSX.platform/Developer/usr/bin/swift-plugin-server -enable-default-cmo -num-threads 12 -o /Users/jaap/Developer/PassiveLogic/autodiff-release-crasher/.build/arm64-apple-macosx/release/Executable.build/main.swift.o
1.  Swift version 6.0-dev (LLVM d83ae228657c9e1, Swift 7441cef1010fbc7)
2.  Compiling with effective version 5.10
3.  While evaluating request ExecuteSILPipelineRequest(Run pipelines { PrepareOptimizationPasses, EarlyModulePasses, HighLevel,Function+EarlyLoopOpt, HighLevel,Module+StackPromote, MidLevel,Function, ClosureSpecialize, LowLevel,Function, LateLoopOpt, SIL Debug Info Generator } on SIL for Executable)
4.  While running pass #2654 SILFunctionTransform "CSE" on SILFunction "@$s7Library18simulationWithLoss5inputSfx_tAA9Storage2DRzSf7ElementRtzlFAaDRzSfAFRSlTJrSpSrAA7Array2DV_Tg5".
 for <<debugloc at "<compiler-generated>":0:0>>Stack dump without symbol names (ensure you have llvm-symbolizer in your PATH or set the environment var `LLVM_SYMBOLIZER_PATH` to point to it):
0  swift-frontend           0x0000000107858b84 llvm::sys::PrintStackTrace(llvm::raw_ostream&, int) + 56
1  swift-frontend           0x000000010785723c llvm::sys::RunSignalHandlers() + 112
2  swift-frontend           0x00000001078591b4 SignalHandler(int) + 292
3  libsystem_platform.dylib 0x00000001828e3584 _sigtramp + 56
4  libsystem_pthread.dylib  0x00000001828b2c20 pthread_kill + 288
5  libsystem_c.dylib        0x00000001827bfa30 abort + 180
6  libsystem_c.dylib        0x00000001827bed20 err + 0
7  swift-frontend           0x000000010785b094 (anonymous namespace)::TypeMemberDiffFinder::visit(swift::ide::api::SDKNode*) (.cold.2) + 0
8  swift-frontend           0x0000000102c9689c (anonymous namespace)::loadTupleOffsetFromMetadata(swift::irgen::IRGenFunction&, llvm::Value*, llvm::Value*) + 0
9  swift-frontend           0x00000001035603f8 swift::SILInstruction::hasIdenticalState(swift::SILInstruction const*) const + 860
10 swift-frontend           0x000000010302084c swift::SILInstruction::isIdenticalTo(swift::SILInstruction const*, llvm::function_ref<bool (swift::SILValue, swift::SILValue)>) const + 280
11 swift-frontend           0x00000001031f6158 swift::CSE::processNode(llvm::DomTreeNodeBase<swift::SILBasicBlock>*) + 580
12 swift-frontend           0x00000001031f5cd4 swift::CSE::processFunction(swift::SILFunction&, swift::DominanceInfo*) + 200
13 swift-frontend           0x0000000103207a60 (anonymous namespace)::SILCSE::run() + 668
14 swift-frontend           0x000000010316c2c8 swift::SILPassManager::runPassOnFunction(unsigned int, swift::SILFunction*) + 1428
15 swift-frontend           0x000000010316d154 swift::SILPassManager::runFunctionPasses(unsigned int, unsigned int) + 1044
16 swift-frontend           0x000000010316a1d8 swift::SILPassManager::executePassPipelinePlan(swift::SILPassPipelinePlan const&) + 72
17 swift-frontend           0x000000010316a174 swift::ExecuteSILPipelineRequest::evaluate(swift::Evaluator&, swift::SILPipelineExecutionDescriptor) const + 52
18 swift-frontend           0x00000001031a8b70 swift::SimpleRequest<swift::ExecuteSILPipelineRequest, std::__1::tuple<> (swift::SILPipelineExecutionDescriptor), (swift::RequestFlags)1>::evaluateRequest(swift::ExecuteSILPipelineRequest const&, swift::Evaluator&) + 28
19 swift-frontend           0x0000000103187ce4 swift::ExecuteSILPipelineRequest::OutputType swift::Evaluator::getResultUncached<swift::ExecuteSILPipelineRequest, swift::ExecuteSILPipelineRequest::OutputType swift::evaluateOrFatal<swift::ExecuteSILPipelineRequest>(swift::Evaluator&, swift::ExecuteSILPipelineRequest)::'lambda'()>(swift::ExecuteSILPipelineRequest const&, swift::ExecuteSILPipelineRequest::OutputType swift::evaluateOrFatal<swift::ExecuteSILPipelineRequest>(swift::Evaluator&, swift::ExecuteSILPipelineRequest)::'lambda'()) + 188
20 swift-frontend           0x000000010316a3c8 swift::executePassPipelinePlan(swift::SILModule*, swift::SILPassPipelinePlan const&, bool, swift::irgen::IRGenModule*) + 64
21 swift-frontend           0x0000000103189a14 swift::runSILOptimizationPasses(swift::SILModule&) + 156
22 swift-frontend           0x0000000102a8b558 swift::CompilerInstance::performSILProcessing(swift::SILModule*) + 636
23 swift-frontend           0x0000000102802978 performCompileStepsPostSILGen(swift::CompilerInstance&, std::__1::unique_ptr<swift::SILModule, std::__1::default_delete<swift::SILModule>>, llvm::PointerUnion<swift::ModuleDecl*, swift::SourceFile*>, swift::PrimarySpecificPaths const&, int&, swift::FrontendObserver*) + 756
24 swift-frontend           0x00000001028023b8 swift::performCompileStepsPostSema(swift::CompilerInstance&, int&, swift::FrontendObserver*) + 1296
25 swift-frontend           0x000000010280ddf8 withSemanticAnalysis(swift::CompilerInstance&, swift::FrontendObserver*, llvm::function_ref<bool (swift::CompilerInstance&)>, bool) + 164
26 swift-frontend           0x0000000102803f18 performCompile(swift::CompilerInstance&, int&, swift::FrontendObserver*) + 692
27 swift-frontend           0x0000000102803640 swift::performFrontend(llvm::ArrayRef<char const*>, char const*, void*, swift::FrontendObserver*) + 2412
28 swift-frontend           0x000000010261bee0 swift::mainEntry(int, char const**) + 3132
29 dyld                     0x000000018252a0e0 start + 2360

Expected behavior

Compile both in debug and release mode

Environment

Swift version 6.0-dev (LLVM d83ae228657c9e1, Swift 7441cef1010fbc7) Target: arm64-apple-macosx14.0

Additional information

No response

JaapWijnen commented 1 month ago

taggin @asl