Skip to content

Ternary operator/if-expression not differentiable #79052

@loonatick-src

Description

@loonatick-src

Description

Closely related to #54195: the following throws a compilation error on Swift 6.0.3.

import _Differentiation

@differentiable(reverse)
func TF_966(_ x: Float, _ bool: Bool) -> Float {
  let tuple = (x, 1)
  let result = bool ? tuple : tuple
  return result.0
}
<source>:3:2: error: function is not differentiable
1 | import _Differentiation
2 | 
3 | @differentiable(reverse)
  |  `- error: function is not differentiable
4 | func TF_966(_ x: Float, _ bool: Bool) -> Float {
  |      `- note: when differentiating this function definition
5 |   let tuple = (x, 1)
6 |   let result = bool ? tuple : tuple
  |                       `- note: expression is not differentiable
7 |   return result.0
8 | }

But, the following semantically equivalent function compiles successfully.

import _Differentiation

@differentiable(reverse)
func TF_966(_ x: Float, _ bool: Bool) -> Float {
  let tuple = (x, 1)
  return bool ? tuple.0 : tuple.0
}

Compiler explorer link

Reproduction

In a single file

// main.swift
import _Differentiation

@differentiable(reverse)
func TF_966(_ x: Float, _ bool: Bool) -> Float {
  let tuple = (x, 1)
  let result = bool ? tuple : tuple
  return result.0
}

Run swiftc main.swift.

Expected behavior

Should compile successfully.

Environment

Swift version 6.0.3 (swift-6.0.3-RELEASE)
Target: x86_64-unknown-linux-gnu

Additional information

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    AutoDiffbugA deviation from expected or documented behavior. Also: expected but undesirable behavior.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions