Skip to content

Native compiler: Bool.or(x, pick(Bool, cond, a, b)) returns the wrong value #1026

Closed

Description

@tsenart

The native compiler (bend file.bend -o out) computes Bool.or(x, pick(Bool, <computed condition>, a, b)) wrongly. The checker and the default lane (bend file.bend) get it right.

Reproduces on 2.0.25 and 2.0.27 (latest), macOS 14.5 arm64, Homebrew clang 23.1.1.

Repro

import Base

def pick(-A: Data, c: Bool, a: A, b: A) -> A:
  match c:
    case True{}:
      a
    case False{}:
      b

def lim(+m: Maybe<&2, Nat>) -> Nat:
  Maybe.default(&2, Nat, m, 0n)

# n bound once, used in the condition and in a branch
def f(+x: Bool, +m: Maybe<&2, Nat>) -> Bool:
  +n = lim(m)
  Bool.or(x, pick(Bool, Nat.is_lt(0n, n), False{}, Nat.is_eq(n, 0n)))

# same, n not reused
def g(+x: Bool, +m: Maybe<&2, Nat>) -> Bool:
  Bool.or(x, pick(Bool, Nat.is_lt(0n, lim(m)), False{}, Nat.is_eq(lim(m), 0n)))

# same, without Bool.or
def h(+m: Maybe<&2, Nat>) -> Bool:
  +n = lim(m)
  pick(Bool, Nat.is_lt(0n, n), False{}, Nat.is_eq(n, 0n))

def main() -> IO(Unit):
  do IO<Unit>:
    IO.print("f " ++ Bool.show(f(False{}, Some{0n})) ++ " g " ++ Bool.show(g(False{}, Some{0n})) ++ " h " ++ Bool.show(h(Some{0n})))

With m = Some{0n}, n = 0: the condition 0 < 0 is False, so pick returns Nat.is_eq(0, 0) = True, and Bool.or(False, True) = True.

f g h
bend canary.bend (default lane) True True True
bend canary.bend -o canary && ./canary False False True

h (the same pick without Bool.or) is right when compiled; f and g are wrong whether or not n is reused.

Workaround

Binding the pick to a def of its own (so Bool.or gets a call, not the inline pick) compiles correctly. We found this porting Vegeta to Bend, where the laws and proofs were fine but compiled code disagreed; the file above is kept as a canary test in https://github.com/tsenart/vegeta/blob/bend-port/bend/tests/compiler_canary.bend.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions