Add i64 support #1

Merged
nandi merged 4 commits from geordi/add-i64-support into main 2026-11-23 05:42:56 +00:00
6 changed files with 292 additions and 124 deletions
Showing only changes of commit 4c4fa91dc9 - Show all commits

No files matched your search

+5 -4
View File
@@ -29,8 +29,9 @@ can build the example.
## Supported subset ## Supported subset
i32 only; locals, params, calls, block/loop/if/else/br/br_if/return, select/drop, i32 i32 and i64; locals, params, calls, block/loop/if/else/br/br_if/return, select/drop,
arithmetic/comparison/shift/rotate, one fixed-size linear memory (i32 loads/stores with integer arithmetic/comparison/shift/rotate (i64 add/sub/mul/div/rem/and/or/xor/shifts/
bounds checks, `memory.size`; `memory.grow` always returns -1), i32 globals, active data comparisons, wrap/extend, sign-extension ops), one fixed-size linear memory (i32/i64 loads/stores incl. narrow
segments. Not supported: i64/floats, tables/`call_indirect`, `br_table`, start function, forms, with bounds checks, `memory.size`; `memory.grow` always returns -1), i32/i64 globals, active data
segments. Not supported: clz/ctz/popcnt, floats, tables/`call_indirect`, `br_table`, start function,
non-function imports. Input is assumed valid (`wasm-tools validate` it first). non-function imports. Input is assumed valid (`wasm-tools validate` it first).
+15 -8
View File
@@ -6,28 +6,28 @@ priv struct Asm {
///| ///|
fn Asm::new() -> Asm { fn Asm::new() -> Asm {
{ code: [] } { code: [], }
} }
///| ///|
fn Asm::here(self : Asm) -> Int { fn Asm::here(self : Asm) -> Int32 {
self.code.length() self.code.length()
} }
///| ///|
fn Asm::b(self : Asm, x : Int) -> Unit { fn Asm::b(self : Asm, x : Int32) -> Unit {
self.code.push((x & 0xFF).to_byte()) self.code.push((x & 0xFF).to_byte())
} }
///| ///|
fn Asm::bs(self : Asm, xs : Array[Int]) -> Unit { fn Asm::bs(self : Asm, xs : Array[Int32]) -> Unit {
for x in xs { for x in xs {
self.b(x) self.b(x)
} }
} }
///| ///|
fn Asm::i32(self : Asm, x : Int) -> Unit { fn Asm::i32(self : Asm, x : Int32) -> Unit {
self.b(x) self.b(x)
self.b(x >> 8) self.b(x >> 8)
self.b(x >> 16) self.b(x >> 16)
@@ -36,7 +36,7 @@ fn Asm::i32(self : Asm, x : Int) -> Unit {
///| ///|
/// Emit opcode bytes followed by a rel32 placeholder; returns the placeholder's position. /// Emit opcode bytes followed by a rel32 placeholder; returns the placeholder's position.
fn Asm::rel(self : Asm, op : Array[Int]) -> Int { fn Asm::rel(self : Asm, op : Array[Int32]) -> Int32 {
self.bs(op) self.bs(op)
let at = self.here() let at = self.here()
self.i32(0) self.i32(0)
@@ -45,7 +45,7 @@ fn Asm::rel(self : Asm, op : Array[Int]) -> Int {
///| ///|
/// Point the rel32 placeholder at `at` to `target`. /// Point the rel32 placeholder at `at` to `target`.
fn Asm::patch(self : Asm, at : Int, target : Int) -> Unit { fn Asm::patch(self : Asm, at : Int32, target : Int32) -> Unit {
let v = target - (at + 4) let v = target - (at + 4)
self.code[at] = (v & 0xFF).to_byte() self.code[at] = (v & 0xFF).to_byte()
self.code[at + 1] = ((v >> 8) & 0xFF).to_byte() self.code[at + 1] = ((v >> 8) & 0xFF).to_byte()
@@ -54,6 +54,13 @@ fn Asm::patch(self : Asm, at : Int, target : Int) -> Unit {
} }
///| ///|
fn Asm::patch_here(self : Asm, at : Int) -> Unit { fn Asm::patch_here(self : Asm, at : Int32) -> Unit {
self.patch(at, self.here()) self.patch(at, self.here())
} }
///|
fn Asm::i64(self : Asm, x : Int64) -> Unit {
for k in 0..<8 {
self.b((x >> (8 * k)).to_int())
}
}
+158 -74
View File
@@ -1,45 +1,45 @@
///| ///|
priv struct FuncType { priv struct FuncType {
nparams : Int nparams : Int32
nresults : Int nresults : Int32
} }
///| ///|
priv struct Frame { priv struct Frame {
kind : Int // 0 = block, 1 = loop, 2 = if kind : Int32 // 0 = block, 1 = loop, 2 = if
base : Int base : Int32
arity : Int arity : Int32
skip : Bool // opened while unreachable: emits nothing skip : Bool // opened while unreachable: emits nothing
loop_start : Int loop_start : Int32
ends : Array[Int] ends : Array[Int32]
mut else_patch : Int mut else_patch : Int32
} }
///| ///|
priv struct Fn { priv struct Fn {
code : Asm code : Asm
ft : FuncType ft : FuncType
nlocals : Int // total locals including params nlocals : Int32 // total locals including params
mem_bytes : Int mem_bytes : Int32
nglobals : Int nglobals : Int32
frames : Array[Frame] frames : Array[Frame]
calls : Array[(Int, Int)] // (rel32 position, callee function index) calls : Array[(Int32, Int32)] // (rel32 position, callee function index)
traps : Array[(Int, Int)] // (rel32 position, trap kind) traps : Array[(Int32, Int32)] // (rel32 position, trap kind)
mut height : Int mut height : Int32
mut dead : Bool mut dead : Bool
} }
///| ///|
const TRAP_UNREACHABLE : Int = 0 const TRAP_UNREACHABLE : Int32 = 0
///| ///|
const TRAP_DIV_ZERO : Int = 1 const TRAP_DIV_ZERO : Int32 = 1
///| ///|
const TRAP_OVERFLOW : Int = 2 const TRAP_OVERFLOW : Int32 = 2
///| ///|
const TRAP_OOB : Int = 3 const TRAP_OOB : Int32 = 3
///| ///|
fn Fn::push_rax(self : Fn) -> Unit { fn Fn::push_rax(self : Fn) -> Unit {
@@ -48,14 +48,14 @@ fn Fn::push_rax(self : Fn) -> Unit {
} }
///| ///|
fn Fn::pop(self : Fn, reg : Int) -> Unit { fn Fn::pop(self : Fn, reg : Int32) -> Unit {
// reg: 0 = rax, 1 = rcx, 2 = rdx // reg: 0 = rax, 1 = rcx, 2 = rdx
self.code.b(0x58 + reg) self.code.b(0x58 + reg)
self.height -= 1 self.height -= 1
} }
///| ///|
fn Fn::add_rsp(self : Fn, slots : Int) -> Unit { fn Fn::add_rsp(self : Fn, slots : Int32) -> Unit {
if slots > 0 { if slots > 0 {
self.code.bs([0x48, 0x81, 0xC4]) self.code.bs([0x48, 0x81, 0xC4])
self.code.i32(slots * 8) self.code.i32(slots * 8)
@@ -63,7 +63,7 @@ fn Fn::add_rsp(self : Fn, slots : Int) -> Unit {
} }
///| ///|
fn Fn::local_disp(self : Fn, idx : Int) -> Int raise CompileError { fn Fn::local_disp(self : Fn, idx : Int32) -> Int32 raise CompileError {
if idx < 0 || idx >= self.nlocals { if idx < 0 || idx >= self.nlocals {
raise CompileError("local index out of range") raise CompileError("local index out of range")
} }
@@ -76,13 +76,13 @@ fn Fn::local_disp(self : Fn, idx : Int) -> Int raise CompileError {
} }
///| ///|
fn Fn::trap_jmp(self : Fn, kind : Int, cond : Array[Int]) -> Unit { fn Fn::trap_jmp(self : Fn, kind : Int32, cond : Array[Int32]) -> Unit {
let at = self.code.rel(cond) let at = self.code.rel(cond)
self.traps.push((at, kind)) self.traps.push((at, kind))
} }
///| ///|
fn Fn::emit_br(self : Fn, depth : Int, h : Int) -> Unit raise CompileError { fn Fn::emit_br(self : Fn, depth : Int32, h : Int32) -> Unit raise CompileError {
if depth >= self.frames.length() { if depth >= self.frames.length() {
raise CompileError("branch depth out of range") raise CompileError("branch depth out of range")
} }
@@ -104,21 +104,16 @@ fn Fn::emit_br(self : Fn, depth : Int, h : Int) -> Unit raise CompileError {
} }
///| ///|
fn Fn::block_type(r : Reader) -> Int raise CompileError { fn Fn::block_type(r : Reader) -> Int32 raise CompileError {
match r.byte() { match r.byte() {
0x40 => 0 0x40 => 0
0x7F => 1 0x7F | 0x7E => 1
b => raise CompileError("unsupported block type 0x\{b.to_string(radix=16)}") b => raise CompileError("unsupported block type 0x\{b.to_string(radix=16)}")
} }
} }
///| ///|
fn Fn::open( fn Fn::open(self : Fn, kind : Int32, arity : Int32, skip : Bool) -> Unit {
self : Fn,
kind : Int,
arity : Int,
skip : Bool,
) -> Unit {
self.frames.push({ self.frames.push({
kind, kind,
base: self.height, base: self.height,
@@ -131,7 +126,7 @@ fn Fn::open(
} }
///| ///|
fn Fn::binop(self : Fn, op : Array[Int]) -> Unit { fn Fn::binop(self : Fn, op : Array[Int32]) -> Unit {
self.pop(1) self.pop(1)
self.pop(0) self.pop(0)
self.code.bs(op) self.code.bs(op)
@@ -139,41 +134,79 @@ fn Fn::binop(self : Fn, op : Array[Int]) -> Unit {
} }
///| ///|
fn Fn::cmp(self : Fn, setcc : Int) -> Unit { fn Fn::unop(self : Fn, op : Array[Int32]) -> Unit {
self.pop(0)
self.code.bs(op)
self.push_rax()
}
///|
fn Fn::cmp(self : Fn, setcc : Int32, wide : Bool) -> Unit {
self.pop(1) self.pop(1)
self.pop(0) self.pop(0)
if wide {
self.code.b(0x48)
}
self.code.bs([0x39, 0xC8, 0x0F, setcc, 0xC0, 0x0F, 0xB6, 0xC0]) self.code.bs([0x39, 0xC8, 0x0F, setcc, 0xC0, 0x0F, 0xB6, 0xC0])
self.push_rax() self.push_rax()
} }
///| ///|
fn Fn::divrem(self : Fn, op : Int) -> Unit { fn Fn::divrem(self : Fn, op : Int32, wide : Bool) -> Unit {
// op: 0x6D div_s, 0x6E div_u, 0x6F rem_s, 0x70 rem_u // op: 0x6D div_s, 0x6E div_u, 0x6F rem_s, 0x70 rem_u (i64 ops are mapped down by 0x12)
self.pop(1) self.pop(1)
self.pop(0) self.pop(0)
self.trap_jmp(TRAP_DIV_ZERO, [0x85, 0xC9, 0x0F, 0x84]) // test ecx,ecx ; jz let w = if wide { [0x48] } else { [] }
self.code.bs(w)
self.trap_jmp(TRAP_DIV_ZERO, [0x85, 0xC9, 0x0F, 0x84]) // test rcx,rcx ; jz
match op { match op {
0x6D => { 0x6D => {
if wide {
self.code.bs([0x48, 0x83, 0xF9, 0xFF, 0x75, 0x13]) // cmp rcx,-1 ; jne L
self.code.bs([0x48, 0xBA]) // mov rdx, INT64_MIN
self.code.i64(-9223372036854775808L)
self.code.bs([0x48, 0x39, 0xD0]) // cmp rax,rdx
} else {
self.code.bs([0x83, 0xF9, 0xFF, 0x75, 0x0B]) // cmp ecx,-1 ; jne L self.code.bs([0x83, 0xF9, 0xFF, 0x75, 0x0B]) // cmp ecx,-1 ; jne L
self.code.bs([0x3D, 0x00, 0x00, 0x00, 0x80]) // cmp eax,INT_MIN self.code.bs([0x3D, 0x00, 0x00, 0x00, 0x80]) // cmp eax,INT_MIN
}
let at = self.code.rel([0x0F, 0x84]) let at = self.code.rel([0x0F, 0x84])
self.traps.push((at, TRAP_OVERFLOW)) self.traps.push((at, TRAP_OVERFLOW))
self.code.bs([0x99, 0xF7, 0xF9]) // L: cdq ; idiv ecx self.code.bs(w)
self.code.bs([0x99]) // L: cdq / cqo
self.code.bs(w)
self.code.bs([0xF7, 0xF9]) // idiv
}
0x6E => {
self.code.bs([0x31, 0xD2]) // xor edx,edx
self.code.bs(w)
self.code.bs([0xF7, 0xF1]) // div
} }
0x6E => self.code.bs([0x31, 0xD2, 0xF7, 0xF1]) // xor edx,edx ; div ecx
0x6F => { 0x6F => {
self.code.bs([0x83, 0xF9, 0xFF, 0x75, 0x04]) // cmp ecx,-1 ; jne L self.code.bs(w)
self.code.bs([0x31, 0xC0, 0xEB, 0x05]) // xor eax,eax ; jmp done self.code.bs([0x83, 0xF9, 0xFF, 0x75, 0x04]) // cmp rcx,-1 ; jne L
self.code.bs([0x99, 0xF7, 0xF9, 0x89, 0xD0]) // L: cdq ; idiv ecx ; mov eax,edx self.code.bs([0x31, 0xC0, 0xEB, if wide { 0x08 } else { 0x05 }]) // xor eax,eax ; jmp done
self.code.bs(w)
self.code.bs([0x99]) // L: cdq / cqo
self.code.bs(w)
self.code.bs([0xF7, 0xF9])
self.code.bs(w)
self.code.bs([0x89, 0xD0]) // mov rax,rdx
}
_ => {
self.code.bs([0x31, 0xD2])
self.code.bs(w)
self.code.bs([0xF7, 0xF1])
self.code.bs(w)
self.code.bs([0x89, 0xD0])
} }
_ => self.code.bs([0x31, 0xD2, 0xF7, 0xF1, 0x89, 0xD0]) // xor edx,edx ; div ecx ; mov eax,edx
} }
self.push_rax() self.push_rax()
} }
///| ///|
/// Linear-memory load/store: bounds check, then access at MEM_BASE + addr + offset. /// Linear-memory load/store: bounds check, then access at MEM_BASE + addr + offset.
fn Fn::mem_access(self : Fn, r : Reader, op : Int) -> Unit raise CompileError { fn Fn::mem_access(self : Fn, r : Reader, op : Int32) -> Unit raise CompileError {
ignore(r.u32()) // alignment hint ignore(r.u32()) // alignment hint
let offset = r.u32() let offset = r.u32()
if self.mem_bytes == 0 { if self.mem_bytes == 0 {
@@ -183,8 +216,9 @@ fn Fn::mem_access(self : Fn, r : Reader, op : Int) -> Unit raise CompileError {
raise CompileError("memory offset too large") raise CompileError("memory offset too large")
} }
let size = match op { let size = match op {
0x28 | 0x36 => 4 0x29 | 0x37 => 8
0x2C | 0x2D | 0x3A => 1 0x28 | 0x34 | 0x35 | 0x36 | 0x3E => 4
0x2C | 0x2D | 0x30 | 0x31 | 0x3A | 0x3C => 1
_ => 2 _ => 2
} }
let is_store = op >= 0x36 let is_store = op >= 0x36
@@ -199,14 +233,19 @@ fn Fn::mem_access(self : Fn, r : Reader, op : Int) -> Unit raise CompileError {
self.code.i32(self.mem_bytes - size) self.code.i32(self.mem_bytes - size)
self.trap_jmp(TRAP_OOB, [0x0F, 0x87]) // ja trap self.trap_jmp(TRAP_OOB, [0x0F, 0x87]) // ja trap
match op { match op {
0x28 => self.code.bs([0x8B, 0x80]) 0x28 | 0x35 => self.code.bs([0x8B, 0x80])
0x29 => self.code.bs([0x48, 0x8B, 0x80])
0x2C => self.code.bs([0x0F, 0xBE, 0x80]) 0x2C => self.code.bs([0x0F, 0xBE, 0x80])
0x2D => self.code.bs([0x0F, 0xB6, 0x80]) 0x2D | 0x31 => self.code.bs([0x0F, 0xB6, 0x80])
0x2E => self.code.bs([0x0F, 0xBF, 0x80]) 0x2E => self.code.bs([0x0F, 0xBF, 0x80])
0x2F => self.code.bs([0x0F, 0xB7, 0x80]) 0x2F | 0x33 => self.code.bs([0x0F, 0xB7, 0x80])
0x36 => self.code.bs([0x89, 0x88]) 0x30 => self.code.bs([0x48, 0x0F, 0xBE, 0x80])
0x3A => self.code.bs([0x88, 0x88]) 0x32 => self.code.bs([0x48, 0x0F, 0xBF, 0x80])
_ => self.code.bs([0x66, 0x89, 0x88]) 0x34 => self.code.bs([0x48, 0x63, 0x80])
0x36 | 0x3E => self.code.bs([0x89, 0x88])
0x37 => self.code.bs([0x48, 0x89, 0x88])
0x3A | 0x3C => self.code.bs([0x88, 0x88])
_ => self.code.bs([0x66, 0x89, 0x88]) // 0x3B, 0x3D
} }
self.code.i32(MEM_BASE) self.code.i32(MEM_BASE)
if !is_store { if !is_store {
@@ -215,7 +254,7 @@ fn Fn::mem_access(self : Fn, r : Reader, op : Int) -> Unit raise CompileError {
} }
///| ///|
fn Fn::global_addr(self : Fn, idx : Int) -> Int raise CompileError { fn Fn::global_addr(self : Fn, idx : Int32) -> Int32 raise CompileError {
if idx < 0 || idx >= self.nglobals { if idx < 0 || idx >= self.nglobals {
raise CompileError("global index out of range") raise CompileError("global index out of range")
} }
@@ -226,13 +265,13 @@ fn Fn::global_addr(self : Fn, idx : Int) -> Int raise CompileError {
/// Compile one function body. Returns the generated Fn (machine code + patch lists). /// Compile one function body. Returns the generated Fn (machine code + patch lists).
fn compile_body( fn compile_body(
r : Reader, r : Reader,
body_end : Int, body_end : Int32,
ft : FuncType, ft : FuncType,
nlocals : Int, nlocals : Int32,
all_types : Array[FuncType], all_types : Array[FuncType],
func_types : Array[Int], func_types : Array[Int32],
mem_bytes : Int, mem_bytes : Int32,
nglobals : Int, nglobals : Int32,
) -> Fn raise CompileError { ) -> Fn raise CompileError {
let f : Fn = { let f : Fn = {
code: Asm::new(), code: Asm::new(),
@@ -265,9 +304,19 @@ fn compile_body(
match op { match op {
0x02 | 0x03 | 0x04 => { 0x02 | 0x03 | 0x04 => {
let a = Fn::block_type(r) let a = Fn::block_type(r)
f.open(if op == 0x03 { 1 } else if op == 0x04 { 2 } else { 0 }, a, true) f.open(
if op == 0x03 {
1
} else if op == 0x04 {
2
} else {
0
},
a,
true,
)
} }
0x05 => { 0x05 =>
if !skipping { if !skipping {
let fr = f.frames[f.frames.length() - 1] let fr = f.frames[f.frames.length() - 1]
if fr.else_patch >= 0 { if fr.else_patch >= 0 {
@@ -277,7 +326,6 @@ fn compile_body(
f.height = fr.base f.height = fr.base
f.dead = false f.dead = false
} }
}
0x0B => { 0x0B => {
let fr = f.frames.pop().unwrap() let fr = f.frames.pop().unwrap()
if !fr.skip { if !fr.skip {
@@ -300,6 +348,7 @@ fn compile_body(
} }
0x0C | 0x0D | 0x10 | 0x20 | 0x21 | 0x22 | 0x23 | 0x24 => ignore(r.u32()) 0x0C | 0x0D | 0x10 | 0x20 | 0x21 | 0x22 | 0x23 | 0x24 => ignore(r.u32())
0x41 => ignore(r.s32()) 0x41 => ignore(r.s32())
0x42 => ignore(r.s64())
0x3F | 0x40 => ignore(r.byte()) 0x3F | 0x40 => ignore(r.byte())
n if n >= 0x28 && n <= 0x3E => { n if n >= 0x28 && n <= 0x3E => {
ignore(r.u32()) ignore(r.u32())
@@ -409,17 +458,22 @@ fn compile_body(
} }
0x23 => { 0x23 => {
let a = f.global_addr(r.u32()) let a = f.global_addr(r.u32())
f.code.bs([0x8B, 0x04, 0x25]) // mov eax,[abs] f.code.bs([0x48, 0x8B, 0x04, 0x25]) // mov rax,[abs]
f.code.i32(a) f.code.i32(a)
f.push_rax() f.push_rax()
} }
0x24 => { 0x24 => {
let a = f.global_addr(r.u32()) let a = f.global_addr(r.u32())
f.pop(0) f.pop(0)
f.code.bs([0x89, 0x04, 0x25]) // mov [abs],eax f.code.bs([0x48, 0x89, 0x04, 0x25]) // mov [abs],rax
f.code.i32(a) f.code.i32(a)
} }
0x28 | 0x2C | 0x2D | 0x2E | 0x2F | 0x36 | 0x3A | 0x3B => f.mem_access(r, op) n if n >= 0x28 &&
n <= 0x3E &&
n != 0x2A &&
n != 0x2B &&
n != 0x38 &&
n != 0x39 => f.mem_access(r, op)
0x3F => { 0x3F => {
ignore(r.byte()) ignore(r.byte())
f.code.b(0x68) f.code.b(0x68)
@@ -443,20 +497,25 @@ fn compile_body(
f.code.bs([0x85, 0xC0, 0x0F, 0x94, 0xC0, 0x0F, 0xB6, 0xC0]) f.code.bs([0x85, 0xC0, 0x0F, 0x94, 0xC0, 0x0F, 0xB6, 0xC0])
f.push_rax() f.push_rax()
} }
0x46 => f.cmp(0x94) 0x42 => {
0x47 => f.cmp(0x95) let v = r.s64()
0x48 => f.cmp(0x9C) if v.to_int().to_int64() == v {
0x49 => f.cmp(0x92) f.code.b(0x68) // push imm32 (sign-extended)
0x4A => f.cmp(0x9F) f.code.i32(v.to_int())
0x4B => f.cmp(0x97) } else {
0x4C => f.cmp(0x9E) f.code.bs([0x48, 0xB8]) // mov rax, imm64
0x4D => f.cmp(0x96) f.code.i64(v)
0x4E => f.cmp(0x9D) f.code.b(0x50)
0x4F => f.cmp(0x93) }
f.height += 1
}
0x46..<=0x4F => f.cmp(setcc_of(op - 0x46), false)
0x50 => f.unop([0x48, 0x85, 0xC0, 0x0F, 0x94, 0xC0, 0x0F, 0xB6, 0xC0])
0x51..<=0x5A => f.cmp(setcc_of(op - 0x51), true)
0x6A => f.binop([0x01, 0xC8]) 0x6A => f.binop([0x01, 0xC8])
0x6B => f.binop([0x29, 0xC8]) 0x6B => f.binop([0x29, 0xC8])
0x6C => f.binop([0x0F, 0xAF, 0xC1]) 0x6C => f.binop([0x0F, 0xAF, 0xC1])
0x6D | 0x6E | 0x6F | 0x70 => f.divrem(op) 0x6D | 0x6E | 0x6F | 0x70 => f.divrem(op, false)
0x71 => f.binop([0x21, 0xC8]) 0x71 => f.binop([0x21, 0xC8])
0x72 => f.binop([0x09, 0xC8]) 0x72 => f.binop([0x09, 0xC8])
0x73 => f.binop([0x31, 0xC8]) 0x73 => f.binop([0x31, 0xC8])
@@ -465,8 +524,33 @@ fn compile_body(
0x76 => f.binop([0xD3, 0xE8]) 0x76 => f.binop([0xD3, 0xE8])
0x77 => f.binop([0xD3, 0xC0]) 0x77 => f.binop([0xD3, 0xC0])
0x78 => f.binop([0xD3, 0xC8]) 0x78 => f.binop([0xD3, 0xC8])
0x7C => f.binop([0x48, 0x01, 0xC8])
0x7D => f.binop([0x48, 0x29, 0xC8])
0x7E => f.binop([0x48, 0x0F, 0xAF, 0xC1])
0x7F..<=0x82 => f.divrem(op - 0x12, true)
0x83 => f.binop([0x48, 0x21, 0xC8])
0x84 => f.binop([0x48, 0x09, 0xC8])
0x85 => f.binop([0x48, 0x31, 0xC8])
0x86 => f.binop([0x48, 0xD3, 0xE0])
0x87 => f.binop([0x48, 0xD3, 0xF8])
0x88 => f.binop([0x48, 0xD3, 0xE8])
0x89 => f.binop([0x48, 0xD3, 0xC0])
0x8A => f.binop([0x48, 0xD3, 0xC8])
0xA7 | 0xAD => f.unop([0x89, 0xC0]) // i32.wrap_i64 / i64.extend_i32_u
0xAC => f.unop([0x48, 0x63, 0xC0]) // i64.extend_i32_s
0xC0 => f.unop([0x0F, 0xBE, 0xC0]) // i32.extend8_s
0xC1 => f.unop([0x0F, 0xBF, 0xC0]) // i32.extend16_s
0xC2 => f.unop([0x48, 0x0F, 0xBE, 0xC0]) // i64.extend8_s
0xC3 => f.unop([0x48, 0x0F, 0xBF, 0xC0]) // i64.extend16_s
0xC4 => f.unop([0x48, 0x63, 0xC0]) // i64.extend32_s
_ => raise CompileError("unsupported opcode 0x\{op.to_string(radix=16)}") _ => raise CompileError("unsupported opcode 0x\{op.to_string(radix=16)}")
} }
} }
f f
} }
///|
/// setcc opcode for comparison index eq, ne, lt_s, lt_u, gt_s, gt_u, le_s, le_u, ge_s, ge_u.
fn setcc_of(i : Int32) -> Int32 {
[0x94, 0x95, 0x9C, 0x92, 0x9F, 0x97, 0x9E, 0x96, 0x9D, 0x93][i]
}
+50
View File
@@ -0,0 +1,50 @@
;; i64 arithmetic, comparisons, conversions, memory and globals. Exits 0 if all checks pass,
;; otherwise with the number of the first failing check.
(module
(memory 1)
(global $g (mut i64) (i64.const 0x123456789abcdef0))
(func $fib (param $n i64) (result i64)
(if (result i64) (i64.lt_s (local.get $n) (i64.const 2))
(then (local.get $n))
(else (i64.add
(call $fib (i64.sub (local.get $n) (i64.const 1)))
(call $fib (i64.sub (local.get $n) (i64.const 2)))))))
(func (export "main") (result i32)
(local $x i64)
;; 1: fib(40) needs more than 32 bits of intermediate range
(if (i64.ne (call $fib (i64.const 40)) (i64.const 102334155)) (then (return (i32.const 1))))
;; 2: 64-bit multiply overflows i32
(if (i64.ne (i64.mul (i64.const 4294967296) (i64.const 3)) (i64.const 12884901888)) (then (return (i32.const 2))))
;; 3: signed division / remainder
(if (i64.ne (i64.div_s (i64.const -9000000000) (i64.const 7)) (i64.const -1285714285)) (then (return (i32.const 3))))
(if (i64.ne (i64.rem_s (i64.const -9000000000) (i64.const 7)) (i64.const -5)) (then (return (i32.const 4))))
;; 5: unsigned division treats -1 as 2^64-1
(if (i64.ne (i64.div_u (i64.const -1) (i64.const 2)) (i64.const 0x7fffffffffffffff)) (then (return (i32.const 5))))
;; 6: INT64_MIN rem_s -1 is 0 (no trap)
(if (i64.ne (i64.rem_s (i64.const 0x8000000000000000) (i64.const -1)) (i64.const 0)) (then (return (i32.const 6))))
;; 7: unsigned vs signed comparison
(if (i32.eqz (i64.lt_u (i64.const 1) (i64.const -1))) (then (return (i32.const 7))))
(if (i32.eqz (i64.gt_s (i64.const 1) (i64.const -1))) (then (return (i32.const 8))))
;; 9: shifts / rotates use 6-bit counts
(if (i64.ne (i64.shl (i64.const 1) (i64.const 40)) (i64.const 1099511627776)) (then (return (i32.const 9))))
(if (i64.ne (i64.shr_s (i64.const -1099511627776) (i64.const 40)) (i64.const -1)) (then (return (i32.const 10))))
(if (i64.ne (i64.shr_u (i64.const -1) (i64.const 60)) (i64.const 15)) (then (return (i32.const 11))))
(if (i64.ne (i64.rotl (i64.const 0x8000000000000001) (i64.const 1)) (i64.const 3)) (then (return (i32.const 12))))
;; 13: conversions
(if (i64.ne (i64.extend_i32_s (i32.const -1)) (i64.const -1)) (then (return (i32.const 13))))
(if (i64.ne (i64.extend_i32_u (i32.const -1)) (i64.const 0xffffffff)) (then (return (i32.const 14))))
(if (i32.ne (i32.wrap_i64 (i64.const 0x1ffffffff)) (i32.const -1)) (then (return (i32.const 15))))
;; 16: memory round trip, plus narrow loads
(i64.store (i32.const 8) (i64.const 0x8877665544332211))
(if (i64.ne (i64.load (i32.const 8)) (i64.const 0x8877665544332211)) (then (return (i32.const 16))))
(if (i64.ne (i64.load8_s (i32.const 15)) (i64.const -0x78)) (then (return (i32.const 17))))
(if (i64.ne (i64.load32_u (i32.const 12)) (i64.const 0x88776655)) (then (return (i32.const 18))))
(if (i64.ne (i64.load32_s (i32.const 12)) (i64.const -0x778899ab)) (then (return (i32.const 19))))
;; 20: i64 global
(global.set $g (i64.add (global.get $g) (i64.const 1)))
(if (i64.ne (global.get $g) (i64.const 0x123456789abcdef1)) (then (return (i32.const 20))))
;; 21: i64 local, select, eqz
(local.set $x (select (i64.const 5000000000) (i64.const 1) (i32.const 1)))
(if (i64.ne (local.get $x) (i64.const 5000000000)) (then (return (i32.const 21))))
(if (i32.eqz (i64.eqz (i64.const 0))) (then (return (i32.const 22))))
(i32.const 0)))
+36 -32
View File
@@ -1,15 +1,15 @@
///| ///|
fn expect_i32(r : Reader) -> Unit raise CompileError { fn expect_int(r : Reader) -> Unit raise CompileError {
let t = r.byte() let t = r.byte()
if t != 0x7F { if t != 0x7F && t != 0x7E {
raise CompileError( raise CompileError(
"only i32 value types are supported (got 0x\{t.to_string(radix=16)})", "only i32/i64 value types are supported (got 0x\{t.to_string(radix=16)})",
) )
} }
} }
///| ///|
fn le(out : Array[Byte], v : Int, n : Int) -> Unit { fn le(out : Array[Byte], v : Int32, n : Int32) -> Unit {
// little-endian, zero-extended past 32 bits (Int shifts wrap mod 32) // little-endian, zero-extended past 32 bits (Int shifts wrap mod 32)
for i in 0..<n { for i in 0..<n {
out.push(if i < 4 { ((v >> (8 * i)) & 0xFF).to_byte() } else { b'\x00' }) out.push(if i < 4 { ((v >> (8 * i)) & 0xFF).to_byte() } else { b'\x00' })
@@ -17,17 +17,17 @@ fn le(out : Array[Byte], v : Int, n : Int) -> Unit {
} }
///| ///|
const BASE : Int = 0x400000 const BASE : Int32 = 0x400000
///| ///|
/// Read/write data segment: one page of globals, then linear memory. /// Read/write data segment: one page of globals, then linear memory.
const SEG_BASE : Int = 0x10000000 const SEG_BASE : Int32 = 0x10000000
///| ///|
const GLOB_BASE : Int = 0x10000000 const GLOB_BASE : Int32 = 0x10000000
///| ///|
const MEM_BASE : Int = 0x10001000 const MEM_BASE : Int32 = 0x10001000
///| ///|
let messages : Array[String] = [ let messages : Array[String] = [
@@ -75,10 +75,7 @@ fn import_stub(m : String, name : String) -> Asm? {
"wasi:cli/exit::exit" => "wasi:cli/exit::exit" =>
// (status: result) -> () ; 0 = ok, 1 = err // (status: result) -> () ; 0 = ok, 1 = err
s.bs([0x8B, 0x7D, 0x10, 0xB8, 0xE7, 0x00, 0x00, 0x00, 0x0F, 0x05]) s.bs([0x8B, 0x7D, 0x10, 0xB8, 0xE7, 0x00, 0x00, 0x00, 0x0F, 0x05])
_ => _ => if !name.has_prefix("[resource-drop]") { return None }
if !name.has_prefix("[resource-drop]") {
return None
}
} }
s.bs([0x5D, 0xC3]) // pop rbp ; ret s.bs([0x5D, 0xC3]) // pop rbp ; ret
Some(s) Some(s)
@@ -107,7 +104,7 @@ fn module_exports_prefix(m : Bytes, prefix : String) -> Bool raise CompileError
} }
///| ///|
/// Compile a WebAssembly core module (i32-only subset) or a component whose /// Compile a WebAssembly core module (i32/i64 subset) or a component whose
/// core module targets `wasi:cli` to a static x86-64 Linux ELF executable. /// core module targets `wasi:cli` to a static x86-64 Linux ELF executable.
/// The entry export is called from `_start` and its i32 result becomes the /// The entry export is called from `_start` and its i32 result becomes the
/// process exit code. /// process exit code.
@@ -149,11 +146,11 @@ fn compile_core(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
} }
let r = Reader::new(wasm, 8) let r = Reader::new(wasm, 8)
let types : Array[FuncType] = [] let types : Array[FuncType] = []
let func_types : Array[Int] = [] // function index space: imports first let func_types : Array[Int32] = [] // function index space: imports first
let imports : Array[(String, String)] = [] let imports : Array[(String, String)] = []
let exports : Array[(String, Int)] = [] let exports : Array[(String, Int32)] = []
let bodies : Array[(Int, Int)] = [] // (start of locals, end) let bodies : Array[(Int32, Int32)] = [] // (start of locals, end)
let globals : Array[Int] = [] let globals : Array[Int64] = []
let mut mem_bytes = 0 let mut mem_bytes = 0
let image : Array[Byte] = [] // initial contents of the RW segment (after globals page) let image : Array[Byte] = [] // initial contents of the RW segment (after globals page)
while r.pos < wasm.length() { while r.pos < wasm.length() {
@@ -169,16 +166,16 @@ fn compile_core(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
} }
let np = r.u32() let np = r.u32()
for _ in 0..<np { for _ in 0..<np {
expect_i32(r) expect_int(r)
} }
let nr = r.u32() let nr = r.u32()
if nr > 1 { if nr > 1 {
raise CompileError("multi-value results are not supported") raise CompileError("multi-value results are not supported")
} }
for _ in 0..<nr { for _ in 0..<nr {
expect_i32(r) expect_int(r)
} }
types.push({ nparams: np, nresults: nr }) types.push({ nparams: np, nresults: nr, })
} }
2 => 2 =>
for _ in 0..<r.u32() { for _ in 0..<r.u32() {
@@ -212,12 +209,16 @@ fn compile_core(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
} }
6 => 6 =>
for _ in 0..<r.u32() { for _ in 0..<r.u32() {
expect_i32(r) expect_int(r)
ignore(r.byte()) // mutability ignore(r.byte()) // mutability
if r.byte() != 0x41 { match r.byte() {
raise CompileError("global initializers must be i32.const") 0x41 => globals.push(r.s32().to_int64())
0x42 => globals.push(r.s64())
_ =>
raise CompileError(
"global initializers must be i32.const or i64.const",
)
} }
globals.push(r.s32())
if r.byte() != 0x0B { if r.byte() != 0x0B {
raise CompileError("bad global initializer") raise CompileError("bad global initializer")
} }
@@ -240,7 +241,9 @@ fn compile_core(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
11 => 11 =>
for _ in 0..<r.u32() { for _ in 0..<r.u32() {
if r.u32() != 0 { if r.u32() != 0 {
raise CompileError("only active data segments on memory 0 are supported") raise CompileError(
"only active data segments on memory 0 are supported",
)
} }
if r.byte() != 0x41 { if r.byte() != 0x41 {
raise CompileError("data offsets must be i32.const") raise CompileError("data offsets must be i32.const")
@@ -286,7 +289,8 @@ fn compile_core(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
match find("main") { match find("main") {
Some(i) => exports[i].1 Some(i) => exports[i].1
None => None =>
match exports.search_by(fn(e) { e.0.has_prefix("wasi:cli/run@") }) { match
exports.search_by(fn(e) { e.0.has_prefix("wasi:cli/run@") }) {
Some(i) => exports[i].1 Some(i) => exports[i].1
None => None =>
if exports.length() > 0 { if exports.length() > 0 {
@@ -311,7 +315,7 @@ fn compile_core(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
let mut nlocals = ft.nparams let mut nlocals = ft.nparams
for _ in 0..<br.u32() { for _ in 0..<br.u32() {
let count = br.u32() let count = br.u32()
expect_i32(br) expect_int(br)
nlocals += count nlocals += count
} }
fns.push( fns.push(
@@ -338,8 +342,8 @@ fn compile_core(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
a.bs([0x31, 0xFF]) // xor edi,edi a.bs([0x31, 0xFF]) // xor edi,edi
} }
a.bs([0xB8, 0xE7, 0x00, 0x00, 0x00, 0x0F, 0x05]) // exit_group a.bs([0xB8, 0xE7, 0x00, 0x00, 0x00, 0x0F, 0x05]) // exit_group
let stub_at : Array[Int] = [] let stub_at : Array[Int32] = []
let lea_at : Array[Int] = [] let lea_at : Array[Int32] = []
for _ in 0..<messages.length() { for _ in 0..<messages.length() {
stub_at.push(a.here()) stub_at.push(a.here())
lea_at.push(a.rel([0x48, 0x8D, 0x35])) // lea rsi,[rip+msg] lea_at.push(a.rel([0x48, 0x8D, 0x35])) // lea rsi,[rip+msg]
@@ -350,7 +354,7 @@ fn compile_core(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
a.bs([0xBF, 0x86, 0x00, 0x00, 0x00]) // mov edi,134 a.bs([0xBF, 0x86, 0x00, 0x00, 0x00]) // mov edi,134
a.bs([0xB8, 0xE7, 0x00, 0x00, 0x00, 0x0F, 0x05]) // exit_group a.bs([0xB8, 0xE7, 0x00, 0x00, 0x00, 0x0F, 0x05]) // exit_group
} }
let fn_at : Array[Int] = [] let fn_at : Array[Int32] = []
for (m, n) in imports { for (m, n) in imports {
fn_at.push(a.here()) fn_at.push(a.here())
match import_stub(m, n) { match import_stub(m, n) {
@@ -428,8 +432,8 @@ fn compile_core(wasm : Bytes, entry : String?) -> Bytes raise CompileError {
seg.push(b'\x00') seg.push(b'\x00')
} }
for i in 0..<globals.length() { for i in 0..<globals.length() {
for k in 0..<4 { for k in 0..<8 {
seg[8 * i + k] = ((globals[i] >> (8 * k)) & 0xFF).to_byte() seg[8 * i + k] = ((globals[i] >> (8 * k)) & 0xFFL).to_int().to_byte()
} }
} }
for c in image { for c in image {
+28 -6
View File
@@ -6,16 +6,16 @@ pub suberror CompileError {
///| ///|
priv struct Reader { priv struct Reader {
data : Bytes data : Bytes
mut pos : Int mut pos : Int32
} }
///| ///|
fn Reader::new(data : Bytes, pos : Int) -> Reader { fn Reader::new(data : Bytes, pos : Int32) -> Reader {
{ data, pos } { data, pos, }
} }
///| ///|
fn Reader::byte(self : Reader) -> Int raise CompileError { fn Reader::byte(self : Reader) -> Int32 raise CompileError {
if self.pos >= self.data.length() { if self.pos >= self.data.length() {
raise CompileError("unexpected end of input") raise CompileError("unexpected end of input")
} }
@@ -25,7 +25,7 @@ fn Reader::byte(self : Reader) -> Int raise CompileError {
} }
///| ///|
fn Reader::u32(self : Reader) -> Int raise CompileError { fn Reader::u32(self : Reader) -> Int32 raise CompileError {
let mut result = 0 let mut result = 0
let mut shift = 0 let mut shift = 0
while true { while true {
@@ -43,7 +43,7 @@ fn Reader::u32(self : Reader) -> Int raise CompileError {
} }
///| ///|
fn Reader::s32(self : Reader) -> Int raise CompileError { fn Reader::s32(self : Reader) -> Int32 raise CompileError {
let mut result = 0 let mut result = 0
let mut shift = 0 let mut shift = 0
let mut b = 0 let mut b = 0
@@ -73,3 +73,25 @@ fn Reader::name(self : Reader) -> String raise CompileError {
} }
sb.to_string() sb.to_string()
} }
///|
fn Reader::s64(self : Reader) -> Int64 raise CompileError {
let mut result = 0L
let mut shift = 0
let mut b = 0
while true {
b = self.byte()
result = result | ((b & 0x7F).to_int64() << shift)
shift += 7
if (b & 0x80) == 0 {
break
}
if shift > 63 {
raise CompileError("LEB128 too long")
}
}
if shift < 64 && (b & 0x40) != 0 {
result = result | (-1L << shift)
}
result
}