# Exact overflow-checked multiplication for metadata. Zero factors return zero. # Other bounded products use 32 Horner steps, each below the native Nat cap. import Base import ./machine_limits.bend as Machine def bounded_result(valid: Bool,value: Nat) -> Maybe<&2,Nat>: match valid: case False{}: None{} case True{}: Some{value} def bounded(+value: Nat,limit: Nat) -> Maybe<&2,Nat>: bounded_result(Nat.is_le(value,limit),value) def multiply_step(bit: Bool,right: Nat,previous: Maybe<&2,Nat>,limit: Nat) -> Maybe<&2,Nat>: match previous: case None{}: None{} case Some{value}: bounded(Nat.add(Nat.double(value),Bool.pick(Nat,bit,right,0n)),limit) def multiply_bits(width: Nat,bits: Word(width),+right: Nat,+limit: Nat) -> Maybe<&2,Nat>: match width bits: case 0n WNil{}: Some{0n} case 1n+rest WCon{bit,tail}: multiply_step(bit,right,multiply_bits(rest,tail,right,limit),limit) def encoded(result: Maybe<&2,Nat>) -> Maybe<&2,U32>: match result: case None{}: None{} case Some{value}: Some{U32.from_nat(value)} def multiply_bounded_when(left_zero: Bool,right_zero: Bool,left: U32,right: U32,limit: U32) -> Maybe<&2,U32>: match left_zero right_zero: case True{} right_zero: Some{0} case False{} True{}: Some{0} case False{} False{}: U32{bits} = left encoded(multiply_bits(32n,bits,U32.to_nat(right),U32.to_nat(limit))) def multiply_bounded(+left: U32,+right: U32,limit: U32) -> Maybe<&2,U32>: multiply_bounded_when(U32.is_zero(left),U32.is_zero(right),left,right,limit) # A left operand at most 2^31 divided by a right operand of at most 2^30 # gives a product of at most 2^31, which the native product holds. Other # products take the exact bit traversal. def multiply_small(fits: Bool,+left: U32,+right: U32) -> Maybe<&2,U32>: match fits: case True{}: Some{(left * right : U32)} case False{}: multiply_bounded(left,right,Machine.word_max()) def multiply_divided(large: Bool,+left: U32,+right: U32) -> Maybe<&2,U32>: match large: case True{}: multiply_bounded(left,right,Machine.word_max()) case False{}: multiply_small(U32.is_le(left,(2147483648 / right : U32)),left,right) # Unit products already fit a word; shapes and contiguous strides frequently # use them. def multiply_right(unit: Bool,+left: U32,+right: U32) -> Maybe<&2,U32>: match unit: case True{}: Some{left} case False{}: multiply_divided(U32.is_zero(right) || U32.is_lt(1073741824,right),left,right) def multiply_left(unit: Bool,+left: U32,+right: U32) -> Maybe<&2,U32>: match unit: case True{}: Some{right} case False{}: multiply_right(U32.is_eq(right,1),left,right) def multiply(+left: U32,+right: U32) -> Maybe<&2,U32>: multiply_left(U32.is_eq(left,1),left,right)