import WordIR /-! # Forth.Double IR code for the double-cell words. `UM*` and `UM/MOD` are loops over the `n` bits of a word, built from single-word instructions only (shifts, `ADD`, `SUB`, `MUL`, `CMP`, `OR`) and the IR's virtual registers, with `countedLoop` running the body `n` times. `Forth.DoubleCorrect` proves that they compute `Op.sem`. `UM* ( a b -- lo hi )`, shift-and-add from the top bit of `b` down. Registers: `0` = `a`, `1` = `b` shifted left by the bits done so far, `2` = `lo`, `3` = `hi`, `4` = the loop counter. Each round doubles `(hi, lo)` and adds `a` times the top bit of register `1`: ``` hi := (hi << 1) + (lo >> (n-1)); lo := lo << 1 x := a * (b >> (n-1)); lo := x + lo; hi := (lo > (n-1); r2 := (r << 1) + (lo >> (n-1)); lo := lo << 1 c := t | (r2 >=u u); q := (q << 1) + c; r := r2 - c * u ``` -/ namespace WordDialect namespace Forth open IR /-- `UM*` before the loop: `b` and `a` into registers 1 and 0, `lo = hi = 0`. -/ def umStarPre {n : Nat} : List (Instr n) := [.pop 1, .pop 0, .word 0#n, .pop 2, .word 0#n, .pop 3] /-- One round of `UM*`. -/ def umStarBody {n : Nat} : List (Instr n) := [.push 3, .word 1#n, .shl, .push 2, .word (BitVec.ofNat n (n - 1)), .shr, .add, .pop 3, .push 2, .word 1#n, .shl, .pop 2, .push 0, .push 1, .word (BitVec.ofNat n (n - 1)), .shr, .mul, .dup, .push 2, .add, .dup, .pop 2, .swap, .cmp .ult, .push 3, .add, .pop 3, .push 1, .word 1#n, .shl, .pop 1] /-- `UM*` after the loop: push `lo`, then `hi`. -/ def umStarPost {n : Nat} : List (Instr n) := [.push 2, .push 3] def umStarFrag {n : Nat} : Frag n := (Frag.ofCode umStarPre).seq ((countedLoop 4 n (Frag.ofCode umStarBody)).seq (Frag.ofCode umStarPost)) /-- `UM/MOD` before the loop: `u`, `hi`, `lo` into registers 0, 1, 2; trap unless `hi