(* Arith: the machine's arithmetic that raz has no operator for, which Math gives as sqrt, mul and divMod: an F64's square root, the 128-bit product of two U64s, and a 128-bit number divided by a U64. This file is arm64's, Arith.x86_64.raz x86-64's. The root is fsqrt, and a call of sqrt, an fsqrt and ret, is made in place (Gen.oneRealOp); the product is mul for its low half and umulh for its high. arm64 has no division of 128 bits by 64, only udiv of 64 by 64, so div128 is long division in raz, a bit of the quotient at each of 64 steps. Depends on Check, for its test. *) module Arith; import Check; import SYSTEM; (* The square root of x, exact to the last bit; NaN for x below 0. *) proc sqrt*(x: F64): F64; code fsqrt d0, d0; ret; end sqrt; (* a times b: the low 64 bits of the product, and the high, which come back in x0 and x1. *) proc mul*(a, b: U64): (U64, U64); code mul x2, x0, x1; umulh x1, x0, x1; mov x0, x2; ret; end mul; (* hi, lo divided by d, with hi < d, which the caller checks first: the quotient and the remainder. As by hand, in base 2: the remainder so far, hi, takes the next bit of lo at each step, and where it then holds d, d is taken from it and that bit of the quotient is 1. The remainder is below d before a step, so below 2d after the shift: it holds d once at most, and its bit shifted out, top, says it is more than 64 bits can hold, and so holds d too. *) proc div128*(hi, lo, d: U64): (U64, U64); var q: U64; i: INT; top: BOOL; begin q := 0; for i := 1 to 64 do top := hi shr 63 = 1; hi := hi shl 1 | lo shr 63; lo := lo shl 1; q := q shl 1; if top or (hi >= d) then hi := hi - d; q := q | 1; end; end; return q, hi; end; (* The module's test; Math's tests these more. *) proc main*; var lo, hi, q, r: U64; begin Check.ok(sqrt(2.0) = 1.4142135623730951, "Arith.sqrt"); lo, hi := mul(0FFFFFFFFFFFFFFFFH, 0FFFFFFFFFFFFFFFFH); Check.ok((lo = 1) and (hi = 0FFFFFFFFFFFFFFFEH), "Arith.mul"); q, r := div128(5, 9, 6); Check.ok((q = 0D555555555555556H) and (r = 5), "Arith.div128"); end; end Arith.