Restructure and compartmentalize the project
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "codegen-luajit"
|
||||
version = "0.8.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies.wasm-ast]
|
||||
path = "../../wasm-ast"
|
||||
|
||||
[dependencies.parity-wasm]
|
||||
git = "https://github.com/paritytech/parity-wasm.git"
|
||||
features = ["multi_value", "sign_ext"]
|
||||
|
||||
[[bin]]
|
||||
name = "wasm2luajit"
|
||||
@@ -0,0 +1,649 @@
|
||||
local module = {}
|
||||
|
||||
local bit = require("bit")
|
||||
local ffi = require("ffi")
|
||||
|
||||
local u32 = ffi.typeof("uint32_t")
|
||||
local u64 = ffi.typeof("uint64_t")
|
||||
local i64 = ffi.typeof("int64_t")
|
||||
|
||||
local math_ceil = math.ceil
|
||||
local math_floor = math.floor
|
||||
local to_number = tonumber
|
||||
|
||||
local ID_ZERO = i64(0)
|
||||
local ID_ONE = i64(1)
|
||||
|
||||
local function truncate(num)
|
||||
if num >= 0 then
|
||||
return (math_floor(num))
|
||||
else
|
||||
return (math_ceil(num))
|
||||
end
|
||||
end
|
||||
|
||||
do
|
||||
local add = {}
|
||||
local sub = {}
|
||||
local mul = {}
|
||||
local div = {}
|
||||
local rem = {}
|
||||
local neg = {}
|
||||
local copysign = {}
|
||||
local nearest = {}
|
||||
|
||||
local to_signed = bit.tobit
|
||||
local math_abs = math.abs
|
||||
|
||||
local RE_INSTANCE = ffi.new([[union {
|
||||
double f64;
|
||||
struct { int32_t a32, b32; };
|
||||
}]])
|
||||
|
||||
local function round(num)
|
||||
if num >= 0 then
|
||||
return (math_floor(num + 0.5))
|
||||
else
|
||||
return (math_ceil(num - 0.5))
|
||||
end
|
||||
end
|
||||
|
||||
function add.i32(a, b)
|
||||
return (to_signed(a + b))
|
||||
end
|
||||
|
||||
function sub.i32(a, b)
|
||||
return (to_signed(a - b))
|
||||
end
|
||||
|
||||
function mul.i32(a, b)
|
||||
return (to_signed(ID_ONE * a * b))
|
||||
end
|
||||
|
||||
function div.i32(lhs, rhs)
|
||||
assert(rhs ~= 0, "division by zero")
|
||||
|
||||
return (truncate(lhs / rhs))
|
||||
end
|
||||
|
||||
function div.u32(lhs, rhs)
|
||||
assert(rhs ~= 0, "division by zero")
|
||||
|
||||
lhs = to_number(u32(lhs))
|
||||
rhs = to_number(u32(rhs))
|
||||
|
||||
return (to_signed(math_floor(lhs / rhs)))
|
||||
end
|
||||
|
||||
function div.u64(lhs, rhs)
|
||||
assert(rhs ~= 0, "division by zero")
|
||||
|
||||
return (i64(u64(lhs) / u64(rhs)))
|
||||
end
|
||||
|
||||
function rem.u32(lhs, rhs)
|
||||
assert(rhs ~= 0, "division by zero")
|
||||
|
||||
lhs = to_number(u32(lhs))
|
||||
rhs = to_number(u32(rhs))
|
||||
|
||||
return (to_signed(lhs % rhs))
|
||||
end
|
||||
|
||||
function rem.u64(lhs, rhs)
|
||||
assert(rhs ~= 0, "division by zero")
|
||||
|
||||
return (i64(u64(lhs) % u64(rhs)))
|
||||
end
|
||||
|
||||
function neg.num(num)
|
||||
return -num
|
||||
end
|
||||
|
||||
function copysign.num(lhs, rhs)
|
||||
RE_INSTANCE.f64 = rhs
|
||||
|
||||
if RE_INSTANCE.b32 >= 0 then
|
||||
return (math_abs(lhs))
|
||||
else
|
||||
return -math_abs(lhs)
|
||||
end
|
||||
end
|
||||
|
||||
function nearest.num(num)
|
||||
local result = round(num)
|
||||
|
||||
if math_abs(num) % 1 == 0.5 and temp_2 % 2 == 1 then
|
||||
result = result - 1
|
||||
end
|
||||
|
||||
return result
|
||||
end
|
||||
|
||||
module.add = add
|
||||
module.sub = sub
|
||||
module.mul = mul
|
||||
module.div = div
|
||||
module.rem = rem
|
||||
module.neg = neg
|
||||
module.copysign = copysign
|
||||
module.nearest = nearest
|
||||
end
|
||||
|
||||
do
|
||||
local clz = {}
|
||||
local ctz = {}
|
||||
local popcnt = {}
|
||||
|
||||
local lj_band = bit.band
|
||||
local lj_lshift = bit.lshift
|
||||
|
||||
function clz.i32(num)
|
||||
for i = 0, 31 do
|
||||
local mask = lj_lshift(1, 31 - i)
|
||||
|
||||
if lj_band(num, mask) ~= 0 then
|
||||
return i
|
||||
end
|
||||
end
|
||||
|
||||
return 32
|
||||
end
|
||||
|
||||
function ctz.i32(num)
|
||||
for i = 0, 31 do
|
||||
local mask = lj_lshift(1, i)
|
||||
|
||||
if lj_band(num, mask) ~= 0 then
|
||||
return i
|
||||
end
|
||||
end
|
||||
|
||||
return 32
|
||||
end
|
||||
|
||||
function popcnt.i32(num)
|
||||
local count = 0
|
||||
|
||||
while num ~= 0 do
|
||||
num = lj_band(num, num - 1)
|
||||
count = count + 1
|
||||
end
|
||||
|
||||
return count
|
||||
end
|
||||
|
||||
function clz.i64(num)
|
||||
for i = 0, 63 do
|
||||
local mask = lj_lshift(ID_ONE, 63 - i)
|
||||
|
||||
if lj_band(num, mask) ~= ID_ZERO then
|
||||
return i * ID_ONE
|
||||
end
|
||||
end
|
||||
|
||||
return 64 * ID_ONE
|
||||
end
|
||||
|
||||
function ctz.i64(num)
|
||||
for i = 0, 63 do
|
||||
local mask = lj_lshift(ID_ONE, i)
|
||||
|
||||
if lj_band(num, mask) ~= ID_ZERO then
|
||||
return i * ID_ONE
|
||||
end
|
||||
end
|
||||
|
||||
return 64 * ID_ONE
|
||||
end
|
||||
|
||||
function popcnt.i64(num)
|
||||
local count = ID_ZERO
|
||||
|
||||
while num ~= ID_ZERO do
|
||||
num = lj_band(num, num - 1)
|
||||
count = count + ID_ONE
|
||||
end
|
||||
|
||||
return count
|
||||
end
|
||||
|
||||
module.clz = clz
|
||||
module.ctz = ctz
|
||||
module.popcnt = popcnt
|
||||
end
|
||||
|
||||
do
|
||||
local le = {}
|
||||
local lt = {}
|
||||
local ge = {}
|
||||
local gt = {}
|
||||
|
||||
function ge.u32(lhs, rhs)
|
||||
return u32(lhs) >= u32(rhs)
|
||||
end
|
||||
|
||||
function ge.u64(lhs, rhs)
|
||||
return u64(lhs) >= u64(rhs)
|
||||
end
|
||||
|
||||
function gt.u32(lhs, rhs)
|
||||
return u32(lhs) > u32(rhs)
|
||||
end
|
||||
|
||||
function gt.u64(lhs, rhs)
|
||||
return u64(lhs) > u64(rhs)
|
||||
end
|
||||
|
||||
function le.u32(lhs, rhs)
|
||||
return u32(lhs) <= u32(rhs)
|
||||
end
|
||||
|
||||
function le.u64(lhs, rhs)
|
||||
return u64(lhs) <= u64(rhs)
|
||||
end
|
||||
|
||||
function lt.u32(lhs, rhs)
|
||||
return u32(lhs) < u32(rhs)
|
||||
end
|
||||
|
||||
function lt.u64(lhs, rhs)
|
||||
return u64(lhs) < u64(rhs)
|
||||
end
|
||||
|
||||
module.le = le
|
||||
module.lt = lt
|
||||
module.ge = ge
|
||||
module.gt = gt
|
||||
end
|
||||
|
||||
do
|
||||
local bnot = {}
|
||||
|
||||
bnot.i32 = bit.bnot
|
||||
bnot.i64 = bit.bnot
|
||||
|
||||
module.bnot = bnot
|
||||
end
|
||||
|
||||
do
|
||||
local shl = {}
|
||||
local shr = {}
|
||||
local rotl = {}
|
||||
local rotr = {}
|
||||
|
||||
rotl.i32 = bit.rol
|
||||
rotl.i64 = bit.rol
|
||||
|
||||
rotr.i32 = bit.ror
|
||||
rotr.i64 = bit.ror
|
||||
|
||||
shl.i32 = bit.lshift
|
||||
shl.i64 = bit.lshift
|
||||
shl.u32 = bit.lshift
|
||||
shl.u64 = bit.lshift
|
||||
|
||||
shr.i32 = bit.arshift
|
||||
shr.i64 = bit.arshift
|
||||
shr.u32 = bit.rshift
|
||||
shr.u64 = bit.rshift
|
||||
|
||||
module.shl = shl
|
||||
module.shr = shr
|
||||
module.rotl = rotl
|
||||
module.rotr = rotr
|
||||
end
|
||||
|
||||
do
|
||||
local wrap = {}
|
||||
local trunc = {}
|
||||
local extend = {}
|
||||
local convert = {}
|
||||
local promote = {}
|
||||
local demote = {}
|
||||
local reinterpret = {}
|
||||
|
||||
local bit_band = bit.band
|
||||
|
||||
-- This would surely be an issue in a multi-thread environment...
|
||||
-- ... thankfully this isn't one.
|
||||
local RE_INSTANCE = ffi.new([[union {
|
||||
int32_t i32;
|
||||
int64_t i64;
|
||||
float f32;
|
||||
double f64;
|
||||
}]])
|
||||
|
||||
function wrap.i32_i64(num)
|
||||
RE_INSTANCE.i64 = num
|
||||
|
||||
return RE_INSTANCE.i32
|
||||
end
|
||||
|
||||
trunc.i32_f32 = truncate
|
||||
trunc.i32_f64 = truncate
|
||||
trunc.u32_f32 = math_floor
|
||||
trunc.u32_f64 = math_floor
|
||||
trunc.i64_f32 = i64
|
||||
trunc.i64_f64 = i64
|
||||
trunc.u64_f32 = i64
|
||||
trunc.u64_f64 = i64
|
||||
|
||||
function extend.i32_i8(num)
|
||||
num = bit_band(num, 0xFF)
|
||||
|
||||
if num >= 0x80 then
|
||||
return num - 0x100
|
||||
else
|
||||
return num
|
||||
end
|
||||
end
|
||||
|
||||
function extend.i32_i16(num)
|
||||
num = bit_band(num, 0xFFFF)
|
||||
|
||||
if num >= 0x8000 then
|
||||
return num - 0x10000
|
||||
else
|
||||
return num
|
||||
end
|
||||
end
|
||||
|
||||
function extend.i64_i8(num)
|
||||
num = bit_band(num, 0xFF)
|
||||
|
||||
if num >= 0x80 then
|
||||
return num - 0x100
|
||||
else
|
||||
return num
|
||||
end
|
||||
end
|
||||
|
||||
function extend.i64_i16(num)
|
||||
num = bit_band(num, 0xFFFF)
|
||||
|
||||
if num >= 0x8000 then
|
||||
return num - 0x10000
|
||||
else
|
||||
return num
|
||||
end
|
||||
end
|
||||
|
||||
function extend.i64_i32(num)
|
||||
num = bit_band(num, 0xFFFFFFFF)
|
||||
|
||||
if num >= 0x80000000 then
|
||||
return num - 0x100000000
|
||||
else
|
||||
return num
|
||||
end
|
||||
end
|
||||
|
||||
function extend.u64_i32(num)
|
||||
RE_INSTANCE.i64 = ID_ZERO
|
||||
RE_INSTANCE.i32 = num
|
||||
|
||||
return RE_INSTANCE.i64
|
||||
end
|
||||
|
||||
function convert.f32_i32(num)
|
||||
return num
|
||||
end
|
||||
|
||||
function convert.f32_u32(num)
|
||||
return (to_number(u32(num)))
|
||||
end
|
||||
|
||||
function convert.f32_i64(num)
|
||||
return (to_number(num))
|
||||
end
|
||||
|
||||
function convert.f32_u64(num)
|
||||
return (to_number(u64(num)))
|
||||
end
|
||||
|
||||
function convert.f64_i32(num)
|
||||
return num
|
||||
end
|
||||
|
||||
function convert.f64_u32(num)
|
||||
return (to_number(u32(num)))
|
||||
end
|
||||
|
||||
function convert.f64_i64(num)
|
||||
return (to_number(num))
|
||||
end
|
||||
|
||||
function convert.f64_u64(num)
|
||||
return (to_number(u64(num)))
|
||||
end
|
||||
|
||||
function demote.f32_f64(num)
|
||||
return num
|
||||
end
|
||||
|
||||
function promote.f64_f32(num)
|
||||
return num
|
||||
end
|
||||
|
||||
function reinterpret.i32_f32(num)
|
||||
RE_INSTANCE.f32 = num
|
||||
|
||||
return RE_INSTANCE.i32
|
||||
end
|
||||
|
||||
function reinterpret.i64_f64(num)
|
||||
RE_INSTANCE.f64 = num
|
||||
|
||||
return RE_INSTANCE.i64
|
||||
end
|
||||
|
||||
function reinterpret.f32_i32(num)
|
||||
RE_INSTANCE.i32 = num
|
||||
|
||||
return RE_INSTANCE.f32
|
||||
end
|
||||
|
||||
function reinterpret.f64_i64(num)
|
||||
RE_INSTANCE.i64 = num
|
||||
|
||||
return RE_INSTANCE.f64
|
||||
end
|
||||
|
||||
module.wrap = wrap
|
||||
module.trunc = trunc
|
||||
module.extend = extend
|
||||
module.convert = convert
|
||||
module.demote = demote
|
||||
module.promote = promote
|
||||
module.reinterpret = reinterpret
|
||||
end
|
||||
|
||||
do
|
||||
local load = {}
|
||||
local store = {}
|
||||
local allocator = {}
|
||||
|
||||
ffi.cdef([[
|
||||
union Any {
|
||||
int8_t i8;
|
||||
int16_t i16;
|
||||
int32_t i32;
|
||||
int64_t i64;
|
||||
|
||||
uint8_t u8;
|
||||
uint16_t u16;
|
||||
uint32_t u32;
|
||||
uint64_t u64;
|
||||
|
||||
float f32;
|
||||
double f64;
|
||||
};
|
||||
|
||||
struct Memory {
|
||||
uint32_t min;
|
||||
uint32_t max;
|
||||
union Any *data;
|
||||
};
|
||||
|
||||
void *calloc(size_t num, size_t size);
|
||||
void *realloc(void *ptr, size_t size);
|
||||
void free(void *ptr);
|
||||
]])
|
||||
|
||||
local alias_t = ffi.typeof("uint8_t *")
|
||||
local any_t = ffi.typeof("union Any *")
|
||||
local cast = ffi.cast
|
||||
|
||||
local function by_offset(pointer, offset)
|
||||
local aliased = cast(alias_t, pointer)
|
||||
|
||||
return cast(any_t, aliased + offset)
|
||||
end
|
||||
|
||||
function load.i32_i8(memory, addr)
|
||||
return by_offset(memory.data, addr).i8
|
||||
end
|
||||
|
||||
function load.i32_u8(memory, addr)
|
||||
return by_offset(memory.data, addr).u8
|
||||
end
|
||||
|
||||
function load.i32_i16(memory, addr)
|
||||
return by_offset(memory.data, addr).i16
|
||||
end
|
||||
|
||||
function load.i32_u16(memory, addr)
|
||||
return by_offset(memory.data, addr).u16
|
||||
end
|
||||
|
||||
function load.i32(memory, addr)
|
||||
return by_offset(memory.data, addr).i32
|
||||
end
|
||||
|
||||
function load.i64_i8(memory, addr)
|
||||
return (i64(by_offset(memory.data, addr).i8))
|
||||
end
|
||||
|
||||
function load.i64_u8(memory, addr)
|
||||
return (i64(by_offset(memory.data, addr).u8))
|
||||
end
|
||||
|
||||
function load.i64_i16(memory, addr)
|
||||
return (i64(by_offset(memory.data, addr).i16))
|
||||
end
|
||||
|
||||
function load.i64_u16(memory, addr)
|
||||
return (i64(by_offset(memory.data, addr).u16))
|
||||
end
|
||||
|
||||
function load.i64_i32(memory, addr)
|
||||
return (i64(by_offset(memory.data, addr).i32))
|
||||
end
|
||||
|
||||
function load.i64_u32(memory, addr)
|
||||
return (i64(by_offset(memory.data, addr).u32))
|
||||
end
|
||||
|
||||
function load.i64(memory, addr)
|
||||
return by_offset(memory.data, addr).i64
|
||||
end
|
||||
|
||||
function load.f32(memory, addr)
|
||||
return by_offset(memory.data, addr).f32
|
||||
end
|
||||
|
||||
function load.f64(memory, addr)
|
||||
return by_offset(memory.data, addr).f64
|
||||
end
|
||||
|
||||
function store.i32_n8(memory, addr, value)
|
||||
by_offset(memory.data, addr).i8 = value
|
||||
end
|
||||
|
||||
function store.i32_n16(memory, addr, value)
|
||||
by_offset(memory.data, addr).i16 = value
|
||||
end
|
||||
|
||||
function store.i32(memory, addr, value)
|
||||
by_offset(memory.data, addr).i32 = value
|
||||
end
|
||||
|
||||
function store.i64_n8(memory, addr, value)
|
||||
by_offset(memory.data, addr).i8 = value
|
||||
end
|
||||
|
||||
function store.i64_n16(memory, addr, value)
|
||||
by_offset(memory.data, addr).i16 = value
|
||||
end
|
||||
|
||||
function store.i64_n32(memory, addr, value)
|
||||
by_offset(memory.data, addr).i32 = value
|
||||
end
|
||||
|
||||
function store.i64(memory, addr, value)
|
||||
by_offset(memory.data, addr).i64 = value
|
||||
end
|
||||
|
||||
function store.f32(memory, addr, value)
|
||||
by_offset(memory.data, addr).f32 = value
|
||||
end
|
||||
|
||||
function store.f64(memory, addr, value)
|
||||
by_offset(memory.data, addr).f64 = value
|
||||
end
|
||||
|
||||
function store.string(memory, addr, data, len)
|
||||
local start = by_offset(memory.data, addr)
|
||||
|
||||
ffi.copy(start, data, len or #data)
|
||||
end
|
||||
|
||||
local WASM_PAGE_SIZE = 65536
|
||||
|
||||
local function finalizer(memory)
|
||||
ffi.C.free(memory.data)
|
||||
end
|
||||
|
||||
local function grow_unchecked(memory, old, new)
|
||||
memory.data = ffi.C.realloc(memory.data, new)
|
||||
|
||||
assert(memory.data ~= nil, "failed to reallocate")
|
||||
|
||||
ffi.fill(by_offset(memory.data, old), new - old, 0)
|
||||
end
|
||||
|
||||
function allocator.new(min, max)
|
||||
local data = ffi.C.calloc(max, WASM_PAGE_SIZE)
|
||||
|
||||
assert(data ~= nil, "failed to allocate")
|
||||
|
||||
local memory = ffi.new("struct Memory", min, max, data)
|
||||
|
||||
return ffi.gc(memory, finalizer)
|
||||
end
|
||||
|
||||
function allocator.grow(memory, num)
|
||||
if num == 0 then
|
||||
return memory.min
|
||||
end
|
||||
|
||||
local old = memory.min
|
||||
local new = old + num
|
||||
|
||||
if new > memory.max then
|
||||
return -1
|
||||
else
|
||||
grow_unchecked(memory, old * WASM_PAGE_SIZE, new * WASM_PAGE_SIZE)
|
||||
memory.min = new
|
||||
|
||||
return old
|
||||
end
|
||||
end
|
||||
|
||||
module.load = load
|
||||
module.store = store
|
||||
module.allocator = allocator
|
||||
end
|
||||
|
||||
return module
|
||||
@@ -0,0 +1,36 @@
|
||||
use wasm_ast::node::{BinOpType, CmpOpType};
|
||||
|
||||
pub trait AsSymbol {
|
||||
fn as_symbol(&self) -> Option<&'static str>;
|
||||
}
|
||||
|
||||
impl AsSymbol for BinOpType {
|
||||
fn as_symbol(&self) -> Option<&'static str> {
|
||||
let result = match self {
|
||||
Self::Add_I64 | Self::Add_FN => "+",
|
||||
Self::Sub_I64 | Self::Sub_FN => "-",
|
||||
Self::Mul_I64 | Self::Mul_FN => "*",
|
||||
Self::DivS_I64 | Self::Div_FN => "/",
|
||||
Self::RemS_I64 => "%",
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
Some(result)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsSymbol for CmpOpType {
|
||||
fn as_symbol(&self) -> Option<&'static str> {
|
||||
let result = match self {
|
||||
Self::Eq_I32 | Self::Eq_I64 | Self::Eq_FN => "==",
|
||||
Self::Ne_I32 | Self::Ne_I64 | Self::Ne_FN => "~=",
|
||||
Self::LtS_I32 | Self::LtS_I64 | Self::Lt_FN => "<",
|
||||
Self::GtS_I32 | Self::GtS_I64 | Self::Gt_FN => ">",
|
||||
Self::LeS_I32 | Self::LeS_I64 | Self::Le_FN => "<=",
|
||||
Self::GeS_I32 | Self::GeS_I64 | Self::Ge_FN => ">=",
|
||||
_ => return None,
|
||||
};
|
||||
|
||||
Some(result)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use wasm_ast::{
|
||||
node::{BrTable, FuncData},
|
||||
visit::{Driver, Visitor},
|
||||
};
|
||||
|
||||
struct Visit {
|
||||
id_map: HashMap<usize, usize>,
|
||||
}
|
||||
|
||||
impl Visitor for Visit {
|
||||
fn visit_br_table(&mut self, table: &BrTable) {
|
||||
let id = table as *const _ as usize;
|
||||
let len = self.id_map.len() + 1;
|
||||
|
||||
self.id_map.insert(id, len);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn visit(ast: &FuncData) -> HashMap<usize, usize> {
|
||||
let mut visit = Visit {
|
||||
id_map: HashMap::new(),
|
||||
};
|
||||
|
||||
ast.accept(&mut visit);
|
||||
|
||||
visit.id_map
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use wasm_ast::{
|
||||
node::{BinOp, CmpOp, FuncData, LoadAt, MemoryGrow, MemorySize, StoreAt, UnOp},
|
||||
visit::{Driver, Visitor},
|
||||
};
|
||||
|
||||
use super::as_symbol::AsSymbol;
|
||||
|
||||
struct Visit {
|
||||
local_set: BTreeSet<(&'static str, &'static str)>,
|
||||
memory_set: BTreeSet<usize>,
|
||||
}
|
||||
|
||||
impl Visitor for Visit {
|
||||
fn visit_load_at(&mut self, v: &LoadAt) {
|
||||
let name = v.load_type().as_name();
|
||||
|
||||
self.memory_set.insert(0);
|
||||
self.local_set.insert(("load", name));
|
||||
}
|
||||
|
||||
fn visit_store_at(&mut self, v: &StoreAt) {
|
||||
let name = v.store_type().as_name();
|
||||
|
||||
self.memory_set.insert(0);
|
||||
self.local_set.insert(("store", name));
|
||||
}
|
||||
|
||||
fn visit_un_op(&mut self, v: &UnOp) {
|
||||
let name = v.op_type().as_name();
|
||||
|
||||
self.local_set.insert(name);
|
||||
}
|
||||
|
||||
fn visit_bin_op(&mut self, v: &BinOp) {
|
||||
if v.op_type().as_symbol().is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let name = v.op_type().as_name();
|
||||
|
||||
self.local_set.insert(name);
|
||||
}
|
||||
|
||||
fn visit_cmp_op(&mut self, v: &CmpOp) {
|
||||
if v.op_type().as_symbol().is_some() {
|
||||
return;
|
||||
}
|
||||
|
||||
let name = v.op_type().as_name();
|
||||
|
||||
self.local_set.insert(name);
|
||||
}
|
||||
|
||||
fn visit_memory_size(&mut self, m: &MemorySize) {
|
||||
self.memory_set.insert(m.memory());
|
||||
}
|
||||
|
||||
fn visit_memory_grow(&mut self, m: &MemoryGrow) {
|
||||
self.memory_set.insert(m.memory());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn visit(ast: &FuncData) -> (BTreeSet<(&'static str, &'static str)>, BTreeSet<usize>) {
|
||||
let mut visit = Visit {
|
||||
local_set: BTreeSet::new(),
|
||||
memory_set: BTreeSet::new(),
|
||||
};
|
||||
|
||||
ast.accept(&mut visit);
|
||||
|
||||
(visit.local_set, visit.memory_set)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
pub mod as_symbol;
|
||||
pub mod br_table;
|
||||
pub mod localize;
|
||||
@@ -0,0 +1,153 @@
|
||||
use std::{
|
||||
io::{Result, Write},
|
||||
num::FpCategory,
|
||||
};
|
||||
|
||||
use wasm_ast::node::{
|
||||
BinOp, CmpOp, Expression, GetGlobal, GetLocal, GetTemporary, LoadAt, MemorySize, Select, UnOp,
|
||||
Value,
|
||||
};
|
||||
|
||||
use crate::analyzer::as_symbol::AsSymbol;
|
||||
|
||||
use super::manager::{
|
||||
write_cmp_op, write_condition, write_separated, write_variable, Driver, Manager,
|
||||
};
|
||||
|
||||
macro_rules! impl_write_number {
|
||||
($name:tt, $numeric:ty) => {
|
||||
fn $name(number: $numeric, w: &mut dyn Write) -> Result<()> {
|
||||
match (number.classify(), number.is_sign_negative()) {
|
||||
(FpCategory::Nan, true) => write!(w, "(0.0 / 0.0) "),
|
||||
(FpCategory::Nan, false) => write!(w, "-(0.0 / 0.0) "),
|
||||
(FpCategory::Infinite, true) => write!(w, "-math.huge "),
|
||||
(FpCategory::Infinite, false) => write!(w, "math.huge "),
|
||||
_ => write!(w, "{number:e} "),
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
impl Driver for Select {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write!(w, "(")?;
|
||||
write_condition(self.condition(), mng, w)?;
|
||||
write!(w, "and ")?;
|
||||
self.on_true().write(mng, w)?;
|
||||
write!(w, "or ")?;
|
||||
self.on_false().write(mng, w)?;
|
||||
write!(w, ")")
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for GetTemporary {
|
||||
fn write(&self, _: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write!(w, "reg_{} ", self.var())
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for GetLocal {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write_variable(self.var(), mng, w)
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for GetGlobal {
|
||||
fn write(&self, _: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write!(w, "GLOBAL_LIST[{}].value ", self.var())
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for LoadAt {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write!(w, "load_{}(memory_at_0, ", self.load_type().as_name())?;
|
||||
self.pointer().write(mng, w)?;
|
||||
|
||||
if self.offset() != 0 {
|
||||
write!(w, "+ {}", self.offset())?;
|
||||
}
|
||||
|
||||
write!(w, ")")
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for MemorySize {
|
||||
fn write(&self, _: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write!(w, "memory_at_{}.min ", self.memory())
|
||||
}
|
||||
}
|
||||
|
||||
impl_write_number!(write_f32, f32);
|
||||
impl_write_number!(write_f64, f64);
|
||||
|
||||
impl Driver for Value {
|
||||
fn write(&self, _: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
match self {
|
||||
Self::I32(i) => write!(w, "{i} "),
|
||||
Self::I64(i) => write!(w, "{i}LL "),
|
||||
Self::F32(f) => write_f32(*f, w),
|
||||
Self::F64(f) => write_f64(*f, w),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for UnOp {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
let (a, b) = self.op_type().as_name();
|
||||
|
||||
write!(w, "{a}_{b}(")?;
|
||||
self.rhs().write(mng, w)?;
|
||||
write!(w, ")")
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for BinOp {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
if let Some(symbol) = self.op_type().as_symbol() {
|
||||
write!(w, "(")?;
|
||||
self.lhs().write(mng, w)?;
|
||||
write!(w, "{symbol} ")?;
|
||||
self.rhs().write(mng, w)?;
|
||||
write!(w, ")")
|
||||
} else {
|
||||
let (head, tail) = self.op_type().as_name();
|
||||
|
||||
write!(w, "{head}_{tail}(")?;
|
||||
self.lhs().write(mng, w)?;
|
||||
write!(w, ", ")?;
|
||||
self.rhs().write(mng, w)?;
|
||||
write!(w, ")")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for CmpOp {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write!(w, "(")?;
|
||||
write_cmp_op(self, mng, w)?;
|
||||
write!(w, "and 1 or 0)")
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for Expression {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
match self {
|
||||
Self::Select(e) => e.write(mng, w),
|
||||
Self::GetTemporary(e) => e.write(mng, w),
|
||||
Self::GetLocal(e) => e.write(mng, w),
|
||||
Self::GetGlobal(e) => e.write(mng, w),
|
||||
Self::LoadAt(e) => e.write(mng, w),
|
||||
Self::MemorySize(e) => e.write(mng, w),
|
||||
Self::Value(e) => e.write(mng, w),
|
||||
Self::UnOp(e) => e.write(mng, w),
|
||||
Self::BinOp(e) => e.write(mng, w),
|
||||
Self::CmpOp(e) => e.write(mng, w),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for &[Expression] {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write_separated(self.iter(), |e, w| e.write(mng, w), w)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
io::{Result, Write},
|
||||
ops::Range,
|
||||
};
|
||||
|
||||
use wasm_ast::node::{BrTable, CmpOp, Expression};
|
||||
|
||||
use crate::analyzer::as_symbol::AsSymbol;
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct Manager {
|
||||
table_map: HashMap<usize, usize>,
|
||||
label_list: Vec<usize>,
|
||||
num_label: usize,
|
||||
num_param: usize,
|
||||
}
|
||||
|
||||
impl Manager {
|
||||
pub fn get_table_index(&self, table: &BrTable) -> usize {
|
||||
let id = table as *const _ as usize;
|
||||
|
||||
self.table_map[&id]
|
||||
}
|
||||
|
||||
pub fn set_table_map(&mut self, map: HashMap<usize, usize>) {
|
||||
self.table_map = map;
|
||||
}
|
||||
|
||||
pub fn set_num_param(&mut self, num: usize) {
|
||||
self.num_param = num;
|
||||
}
|
||||
|
||||
pub fn label_list(&self) -> &[usize] {
|
||||
&self.label_list
|
||||
}
|
||||
|
||||
pub fn push_label(&mut self) -> usize {
|
||||
self.label_list.push(self.num_label);
|
||||
self.num_label += 1;
|
||||
|
||||
self.num_label - 1
|
||||
}
|
||||
|
||||
pub fn pop_label(&mut self) {
|
||||
self.label_list.pop().unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Driver {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()>;
|
||||
}
|
||||
|
||||
pub fn write_separated<I, T, M>(mut iter: I, mut func: M, w: &mut dyn Write) -> Result<()>
|
||||
where
|
||||
M: FnMut(T, &mut dyn Write) -> Result<()>,
|
||||
I: Iterator<Item = T>,
|
||||
{
|
||||
match iter.next() {
|
||||
Some(first) => func(first, w)?,
|
||||
None => return Ok(()),
|
||||
}
|
||||
|
||||
iter.try_for_each(|v| {
|
||||
write!(w, ", ")?;
|
||||
func(v, w)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn write_ascending(prefix: &str, range: Range<usize>, w: &mut dyn Write) -> Result<()> {
|
||||
write_separated(range, |i, w| write!(w, "{prefix}_{i}"), w)
|
||||
}
|
||||
|
||||
pub fn write_variable(var: usize, mng: &Manager, w: &mut dyn Write) -> Result<()> {
|
||||
if let Some(rem) = var.checked_sub(mng.num_param) {
|
||||
write!(w, "loc_{rem} ")
|
||||
} else {
|
||||
write!(w, "param_{var} ")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_cmp_op(cmp: &CmpOp, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
if let Some(symbol) = cmp.op_type().as_symbol() {
|
||||
cmp.lhs().write(mng, w)?;
|
||||
write!(w, "{symbol} ")?;
|
||||
cmp.rhs().write(mng, w)
|
||||
} else {
|
||||
let (head, tail) = cmp.op_type().as_name();
|
||||
|
||||
write!(w, "{head}_{tail}(")?;
|
||||
cmp.lhs().write(mng, w)?;
|
||||
write!(w, ", ")?;
|
||||
cmp.rhs().write(mng, w)?;
|
||||
write!(w, ")")
|
||||
}
|
||||
}
|
||||
|
||||
pub fn write_condition(data: &Expression, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
if let Expression::CmpOp(node) = data {
|
||||
write_cmp_op(node, mng, w)
|
||||
} else {
|
||||
data.write(mng, w)?;
|
||||
write!(w, "~= 0 ")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub mod manager;
|
||||
|
||||
mod expression;
|
||||
mod statement;
|
||||
@@ -0,0 +1,345 @@
|
||||
use std::{
|
||||
io::{Result, Write},
|
||||
ops::Range,
|
||||
};
|
||||
|
||||
use parity_wasm::elements::ValueType;
|
||||
use wasm_ast::node::{
|
||||
Backward, Br, BrIf, BrTable, Call, CallIndirect, Forward, FuncData, If, MemoryGrow, SetGlobal,
|
||||
SetLocal, SetTemporary, Statement, StoreAt, Terminator,
|
||||
};
|
||||
|
||||
use crate::analyzer::br_table;
|
||||
|
||||
use super::manager::{
|
||||
write_ascending, write_condition, write_separated, write_variable, Driver, Manager,
|
||||
};
|
||||
|
||||
impl Driver for Br {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
let level = *mng.label_list().iter().nth_back(self.target()).unwrap();
|
||||
|
||||
if !self.align().is_aligned() {
|
||||
write_ascending("reg", self.align().new_range(), w)?;
|
||||
write!(w, " = ")?;
|
||||
write_ascending("reg", self.align().old_range(), w)?;
|
||||
write!(w, " ")?;
|
||||
}
|
||||
|
||||
write!(w, "goto continue_at_{level} ")
|
||||
}
|
||||
}
|
||||
|
||||
fn to_ordered_table<'a>(list: &'a [Br], default: &'a Br) -> Vec<&'a Br> {
|
||||
let mut data: Vec<_> = list.iter().chain(std::iter::once(default)).collect();
|
||||
|
||||
data.sort_by_key(|v| v.target());
|
||||
data.dedup_by_key(|v| v.target());
|
||||
|
||||
data
|
||||
}
|
||||
|
||||
fn write_search_layer(
|
||||
range: Range<usize>,
|
||||
list: &[&Br],
|
||||
mng: &mut Manager,
|
||||
w: &mut dyn Write,
|
||||
) -> Result<()> {
|
||||
if range.len() == 1 {
|
||||
return list[range.start].write(mng, w);
|
||||
}
|
||||
|
||||
let center = range.start + range.len() / 2;
|
||||
let br = list[center];
|
||||
|
||||
if range.start != center {
|
||||
write!(w, "if temp < {} then ", br.target())?;
|
||||
write_search_layer(range.start..center, list, mng, w)?;
|
||||
write!(w, "else")?;
|
||||
}
|
||||
|
||||
if range.end != center + 1 {
|
||||
write!(w, "if temp > {} then ", br.target())?;
|
||||
write_search_layer(center + 1..range.end, list, mng, w)?;
|
||||
write!(w, "else")?;
|
||||
}
|
||||
|
||||
write!(w, " ")?;
|
||||
br.write(mng, w)?;
|
||||
write!(w, "end ")
|
||||
}
|
||||
|
||||
fn write_table_setup(table: &BrTable, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
let id = mng.get_table_index(table);
|
||||
|
||||
write!(w, "if not br_map[{id}] then ")?;
|
||||
write!(w, "br_map[{id}] = (function() return {{[0] =")?;
|
||||
|
||||
table
|
||||
.data()
|
||||
.iter()
|
||||
.try_for_each(|v| write!(w, "{},", v.target()))?;
|
||||
|
||||
write!(w, "}} end)()")?;
|
||||
write!(w, "end ")?;
|
||||
|
||||
write!(w, "temp = br_map[{id}][")?;
|
||||
table.condition().write(mng, w)?;
|
||||
write!(w, "] or {} ", table.default().target())
|
||||
}
|
||||
|
||||
impl Driver for BrTable {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
if self.data().is_empty() {
|
||||
// Our condition should be pure so we probably don't need
|
||||
// to emit it in this case.
|
||||
return self.default().write(mng, w);
|
||||
}
|
||||
|
||||
// `BrTable` is optimized by first mapping all indices to targets through
|
||||
// a Lua table; this reduces the size of the code generated as duplicate entries
|
||||
// don't need checking. Then, for speed, a binary search is done for the target
|
||||
// and the appropriate jump is performed.
|
||||
let list = to_ordered_table(self.data(), self.default());
|
||||
|
||||
write_table_setup(self, mng, w)?;
|
||||
write_search_layer(0..list.len(), &list, mng, w)
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for Terminator {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
match self {
|
||||
Self::Unreachable => write!(w, "error(\"out of code bounds\")"),
|
||||
Self::Br(s) => s.write(mng, w),
|
||||
Self::BrTable(s) => s.write(mng, w),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for Forward {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
let label = mng.push_label();
|
||||
|
||||
self.code().iter().try_for_each(|s| s.write(mng, w))?;
|
||||
|
||||
if let Some(v) = self.last() {
|
||||
v.write(mng, w)?;
|
||||
}
|
||||
|
||||
write!(w, "::continue_at_{label}::")?;
|
||||
|
||||
mng.pop_label();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for Backward {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
let label = mng.push_label();
|
||||
|
||||
write!(w, "::continue_at_{label}::")?;
|
||||
write!(w, "while true do ")?;
|
||||
|
||||
self.code().iter().try_for_each(|s| s.write(mng, w))?;
|
||||
|
||||
if let Some(v) = self.last() {
|
||||
v.write(mng, w)?;
|
||||
} else {
|
||||
write!(w, "break ")?;
|
||||
}
|
||||
|
||||
write!(w, "end ")?;
|
||||
|
||||
mng.pop_label();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for BrIf {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write!(w, "if ")?;
|
||||
write_condition(self.condition(), mng, w)?;
|
||||
write!(w, "then ")?;
|
||||
self.target().write(mng, w)?;
|
||||
write!(w, "end ")
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for If {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write!(w, "if ")?;
|
||||
write_condition(self.condition(), mng, w)?;
|
||||
write!(w, "then ")?;
|
||||
|
||||
self.on_true().write(mng, w)?;
|
||||
|
||||
if let Some(v) = self.on_false() {
|
||||
write!(w, "else ")?;
|
||||
|
||||
v.write(mng, w)?;
|
||||
}
|
||||
|
||||
write!(w, "end ")
|
||||
}
|
||||
}
|
||||
|
||||
fn write_call_store(result: Range<usize>, w: &mut dyn Write) -> Result<()> {
|
||||
if result.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
write_ascending("reg", result, w)?;
|
||||
write!(w, " = ")
|
||||
}
|
||||
|
||||
impl Driver for Call {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write_call_store(self.result(), w)?;
|
||||
|
||||
write!(w, "FUNC_LIST[{}](", self.function())?;
|
||||
self.param_list().write(mng, w)?;
|
||||
write!(w, ")")
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for CallIndirect {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write_call_store(self.result(), w)?;
|
||||
|
||||
write!(w, "TABLE_LIST[{}].data[", self.table())?;
|
||||
self.index().write(mng, w)?;
|
||||
write!(w, "](")?;
|
||||
self.param_list().write(mng, w)?;
|
||||
write!(w, ")")
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for SetTemporary {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write!(w, "reg_{} = ", self.var())?;
|
||||
self.value().write(mng, w)
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for SetLocal {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write_variable(self.var(), mng, w)?;
|
||||
write!(w, "= ")?;
|
||||
self.value().write(mng, w)
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for SetGlobal {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write!(w, "GLOBAL_LIST[{}].value = ", self.var())?;
|
||||
self.value().write(mng, w)
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for StoreAt {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
write!(w, "store_{}(memory_at_0, ", self.store_type().as_name())?;
|
||||
self.pointer().write(mng, w)?;
|
||||
|
||||
if self.offset() != 0 {
|
||||
write!(w, "+ {}", self.offset())?;
|
||||
}
|
||||
|
||||
write!(w, ", ")?;
|
||||
self.value().write(mng, w)?;
|
||||
write!(w, ")")
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for MemoryGrow {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
let result = self.result();
|
||||
let memory = self.memory();
|
||||
|
||||
write!(w, "reg_{result} = rt.allocator.grow(memory_at_{memory}, ")?;
|
||||
self.size().write(mng, w)?;
|
||||
write!(w, ")")
|
||||
}
|
||||
}
|
||||
|
||||
impl Driver for Statement {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
match self {
|
||||
Self::Forward(s) => s.write(mng, w),
|
||||
Self::Backward(s) => s.write(mng, w),
|
||||
Self::BrIf(s) => s.write(mng, w),
|
||||
Self::If(s) => s.write(mng, w),
|
||||
Self::Call(s) => s.write(mng, w),
|
||||
Self::CallIndirect(s) => s.write(mng, w),
|
||||
Self::SetTemporary(s) => s.write(mng, w),
|
||||
Self::SetLocal(s) => s.write(mng, w),
|
||||
Self::SetGlobal(s) => s.write(mng, w),
|
||||
Self::StoreAt(s) => s.write(mng, w),
|
||||
Self::MemoryGrow(s) => s.write(mng, w),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_parameter_list(ast: &FuncData, w: &mut dyn Write) -> Result<()> {
|
||||
write!(w, "function(")?;
|
||||
write_ascending("param", 0..ast.num_param(), w)?;
|
||||
write!(w, ")")
|
||||
}
|
||||
|
||||
fn write_variable_list(ast: &FuncData, w: &mut dyn Write) -> Result<()> {
|
||||
let mut total = 0;
|
||||
|
||||
for data in ast.local_data().iter().filter(|v| v.count() != 0) {
|
||||
let range = total..total + usize::try_from(data.count()).unwrap();
|
||||
let typed = if data.value_type() == ValueType::I64 {
|
||||
"0LL"
|
||||
} else {
|
||||
"0"
|
||||
}
|
||||
.as_bytes();
|
||||
|
||||
total = range.end;
|
||||
|
||||
write!(w, "local ")?;
|
||||
write_ascending("loc", range.clone(), w)?;
|
||||
write!(w, " = ")?;
|
||||
write_separated(range, |_, w| w.write_all(typed), w)?;
|
||||
write!(w, " ")?;
|
||||
}
|
||||
|
||||
if ast.num_stack() != 0 {
|
||||
write!(w, "local ")?;
|
||||
write_ascending("reg", 0..ast.num_stack(), w)?;
|
||||
write!(w, " ")?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Driver for FuncData {
|
||||
fn write(&self, mng: &mut Manager, w: &mut dyn Write) -> Result<()> {
|
||||
let br_map = br_table::visit(self);
|
||||
|
||||
write_parameter_list(self, w)?;
|
||||
write_variable_list(self, w)?;
|
||||
|
||||
if !br_map.is_empty() {
|
||||
write!(w, "local br_map, temp = {{}}, nil ")?;
|
||||
}
|
||||
|
||||
mng.set_table_map(br_map);
|
||||
mng.set_num_param(self.num_param());
|
||||
self.code().write(mng, w)?;
|
||||
|
||||
if self.num_result() != 0 {
|
||||
write!(w, "return ")?;
|
||||
write_ascending("reg", 0..self.num_result(), w)?;
|
||||
write!(w, " ")?;
|
||||
}
|
||||
|
||||
write!(w, "end ")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
use std::io::{Result, Write};
|
||||
|
||||
use parity_wasm::{deserialize_file, elements::Module};
|
||||
|
||||
fn load_module(name: &str) -> Module {
|
||||
deserialize_file(name)
|
||||
.expect("Failed to parse WebAssembly file")
|
||||
.parse_names()
|
||||
.unwrap_or_else(|v| v.1)
|
||||
}
|
||||
|
||||
fn do_runtime(lock: &mut dyn Write) -> Result<()> {
|
||||
let runtime = codegen_luajit::RUNTIME;
|
||||
|
||||
writeln!(lock, "local rt = (function()")?;
|
||||
writeln!(lock, "{runtime}")?;
|
||||
writeln!(lock, "end)()")
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let wasm = match std::env::args().nth(1) {
|
||||
Some(name) => load_module(&name),
|
||||
None => {
|
||||
eprintln!("usage: wasm2luajit <file>");
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
|
||||
let lock = &mut std::io::stdout().lock();
|
||||
|
||||
do_runtime(lock)?;
|
||||
codegen_luajit::from_module_untyped(&wasm, lock)
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
pub static RUNTIME: &str = include_str!("../runtime/runtime.lua");
|
||||
|
||||
pub use translator::{from_inst_list, from_module_typed, from_module_untyped};
|
||||
|
||||
mod analyzer;
|
||||
mod backend;
|
||||
mod translator;
|
||||
@@ -0,0 +1,355 @@
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
io::{Result, Write},
|
||||
};
|
||||
|
||||
use parity_wasm::elements::{
|
||||
External, ImportCountType, Instruction, Internal, Module, NameSection, ResizableLimits,
|
||||
};
|
||||
|
||||
use wasm_ast::{
|
||||
builder::{Builder, TypeInfo},
|
||||
node::{FuncData, Statement},
|
||||
};
|
||||
|
||||
use crate::{
|
||||
analyzer::localize,
|
||||
backend::manager::{Driver, Manager},
|
||||
};
|
||||
|
||||
fn to_internal_index(internal: Internal) -> u32 {
|
||||
match internal {
|
||||
Internal::Function(v) | Internal::Table(v) | Internal::Memory(v) | Internal::Global(v) => v,
|
||||
}
|
||||
}
|
||||
|
||||
fn limit_data_of(limits: &ResizableLimits) -> (u32, u32) {
|
||||
let max = limits.maximum().unwrap_or(0xFFFF);
|
||||
|
||||
(limits.initial(), max)
|
||||
}
|
||||
|
||||
fn write_table_init(limit: &ResizableLimits, w: &mut dyn Write) -> Result<()> {
|
||||
let (a, b) = limit_data_of(limit);
|
||||
|
||||
write!(w, "{{ min = {a}, max = {b}, data = {{}} }}")
|
||||
}
|
||||
|
||||
fn write_memory_init(limit: &ResizableLimits, w: &mut dyn Write) -> Result<()> {
|
||||
let (a, b) = limit_data_of(limit);
|
||||
|
||||
write!(w, "rt.allocator.new({a}, {b})")
|
||||
}
|
||||
|
||||
fn write_named_array(name: &str, len: usize, w: &mut dyn Write) -> Result<()> {
|
||||
let hash = len.min(1);
|
||||
let len = len.saturating_sub(1);
|
||||
|
||||
write!(w, "local {name} = table_new({len}, {hash})")
|
||||
}
|
||||
|
||||
fn write_constant(code: &[Instruction], type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
|
||||
let func = Builder::from_type_info(type_info).build_anonymous(code);
|
||||
|
||||
if let Some(Statement::SetTemporary(stat)) = func.code().code().last() {
|
||||
stat.value().write(&mut Manager::default(), w)?;
|
||||
} else {
|
||||
panic!("Not a valid constant");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_import_of<T>(wasm: &Module, lower: &str, cond: T, w: &mut dyn Write) -> Result<()>
|
||||
where
|
||||
T: Fn(&External) -> bool,
|
||||
{
|
||||
let import = match wasm.import_section() {
|
||||
Some(v) => v.entries(),
|
||||
None => return Ok(()),
|
||||
};
|
||||
let upper = lower.to_uppercase();
|
||||
|
||||
for (i, v) in import.iter().filter(|v| cond(v.external())).enumerate() {
|
||||
let field = v.field();
|
||||
let module = v.module();
|
||||
|
||||
write!(w, r#"{upper}[{i}] = wasm["{module}"].{lower}["{field}"]"#)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_export_of<T>(wasm: &Module, lower: &str, cond: T, w: &mut dyn Write) -> Result<()>
|
||||
where
|
||||
T: Fn(&Internal) -> bool,
|
||||
{
|
||||
let export = match wasm.export_section() {
|
||||
Some(v) => v.entries(),
|
||||
None => return Ok(()),
|
||||
};
|
||||
let upper = lower.to_uppercase();
|
||||
|
||||
write!(w, "{lower} = {{")?;
|
||||
|
||||
for v in export.iter().filter(|v| cond(v.internal())) {
|
||||
let field = v.field();
|
||||
let index = to_internal_index(*v.internal());
|
||||
|
||||
write!(w, r#"["{field}"] = {upper}[{index}],"#)?;
|
||||
}
|
||||
|
||||
write!(w, "}},")
|
||||
}
|
||||
|
||||
fn write_import_list(wasm: &Module, w: &mut dyn Write) -> Result<()> {
|
||||
write_import_of(wasm, "func_list", |v| matches!(v, External::Function(_)), w)?;
|
||||
write_import_of(wasm, "table_list", |v| matches!(v, External::Table(_)), w)?;
|
||||
write_import_of(wasm, "memory_list", |v| matches!(v, External::Memory(_)), w)?;
|
||||
write_import_of(wasm, "global_list", |v| matches!(v, External::Global(_)), w)
|
||||
}
|
||||
|
||||
fn write_export_list(wasm: &Module, w: &mut dyn Write) -> Result<()> {
|
||||
write_export_of(wasm, "func_list", |v| matches!(v, Internal::Function(_)), w)?;
|
||||
write_export_of(wasm, "table_list", |v| matches!(v, Internal::Table(_)), w)?;
|
||||
write_export_of(wasm, "memory_list", |v| matches!(v, Internal::Memory(_)), w)?;
|
||||
write_export_of(wasm, "global_list", |v| matches!(v, Internal::Global(_)), w)
|
||||
}
|
||||
|
||||
fn write_table_list(wasm: &Module, w: &mut dyn Write) -> Result<()> {
|
||||
let table = match wasm.table_section() {
|
||||
Some(v) => v.entries(),
|
||||
None => return Ok(()),
|
||||
};
|
||||
let offset = wasm.import_count(ImportCountType::Table);
|
||||
|
||||
for (i, v) in table.iter().enumerate() {
|
||||
write!(w, "TABLE_LIST[{}] =", i + offset)?;
|
||||
write_table_init(v.limits(), w)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_memory_list(wasm: &Module, w: &mut dyn Write) -> Result<()> {
|
||||
let memory = match wasm.memory_section() {
|
||||
Some(v) => v.entries(),
|
||||
None => return Ok(()),
|
||||
};
|
||||
let offset = wasm.import_count(ImportCountType::Memory);
|
||||
|
||||
for (i, v) in memory.iter().enumerate() {
|
||||
write!(w, "MEMORY_LIST[{}] =", i + offset)?;
|
||||
write_memory_init(v.limits(), w)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_global_list(wasm: &Module, type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
|
||||
let global = match wasm.global_section() {
|
||||
Some(v) => v,
|
||||
None => return Ok(()),
|
||||
};
|
||||
let offset = wasm.import_count(ImportCountType::Global);
|
||||
|
||||
for (i, v) in global.entries().iter().enumerate() {
|
||||
write!(w, "GLOBAL_LIST[{}] = {{ value =", i + offset)?;
|
||||
write_constant(v.init_expr().code(), type_info, w)?;
|
||||
write!(w, "}}")?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_element_list(wasm: &Module, type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
|
||||
let element = match wasm.elements_section() {
|
||||
Some(v) => v.entries(),
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
for v in element {
|
||||
let code = v.offset().as_ref().unwrap().code();
|
||||
|
||||
write!(w, "do ")?;
|
||||
write!(w, "local target = TABLE_LIST[{}].data ", v.index())?;
|
||||
write!(w, "local offset =")?;
|
||||
|
||||
write_constant(code, type_info, w)?;
|
||||
|
||||
write!(w, "local data = {{")?;
|
||||
|
||||
v.members()
|
||||
.iter()
|
||||
.try_for_each(|v| write!(w, "FUNC_LIST[{v}],"))?;
|
||||
|
||||
write!(w, "}}")?;
|
||||
|
||||
write!(w, "table.move(data, 1, #data, offset, target)")?;
|
||||
|
||||
write!(w, "end ")?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_data_list(wasm: &Module, type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
|
||||
let data = match wasm.data_section() {
|
||||
Some(v) => v.entries(),
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
for v in data {
|
||||
let code = v.offset().as_ref().unwrap().code();
|
||||
let index = v.index();
|
||||
|
||||
write!(w, "rt.store.string(")?;
|
||||
write!(w, "MEMORY_LIST[{index}],")?;
|
||||
write_constant(code, type_info, w)?;
|
||||
write!(w, r#","{}")"#, v.value().escape_ascii())?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn build_func_list(wasm: &Module, type_info: &TypeInfo) -> Vec<FuncData> {
|
||||
let list = match wasm.code_section() {
|
||||
Some(v) => v.bodies(),
|
||||
None => return Vec::new(),
|
||||
};
|
||||
|
||||
let mut builder = Builder::from_type_info(type_info);
|
||||
|
||||
list.iter()
|
||||
.enumerate()
|
||||
.map(|f| builder.build_indexed(f.0, f.1))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn write_local_operation(head: &str, tail: &str, w: &mut dyn Write) -> Result<()> {
|
||||
match (head, tail) {
|
||||
("band" | "bor" | "bxor", _) => {
|
||||
write!(w, "local {head}_{tail} = bit.{head} ")
|
||||
}
|
||||
("abs" | "ceil" | "floor" | "sqrt" | "min" | "max", _) => {
|
||||
write!(w, "local {head}_{tail} = math.{head} ")
|
||||
}
|
||||
("rem", "i32") => {
|
||||
write!(w, "local {head}_{tail} = math.fmod ")
|
||||
}
|
||||
_ => write!(w, "local {head}_{tail} = rt.{head}.{tail} "),
|
||||
}
|
||||
}
|
||||
|
||||
fn write_localize_used(func_list: &[FuncData], w: &mut dyn Write) -> Result<BTreeSet<usize>> {
|
||||
let mut loc_set = BTreeSet::new();
|
||||
let mut mem_set = BTreeSet::new();
|
||||
|
||||
for (loc, mem) in func_list.iter().map(localize::visit) {
|
||||
loc_set.extend(loc);
|
||||
mem_set.extend(mem);
|
||||
}
|
||||
|
||||
for loc in loc_set {
|
||||
write_local_operation(loc.0, loc.1, w)?;
|
||||
}
|
||||
|
||||
for mem in &mem_set {
|
||||
write!(w, "local memory_at_{mem} ")?;
|
||||
}
|
||||
|
||||
Ok(mem_set)
|
||||
}
|
||||
|
||||
fn write_func_start(wasm: &Module, index: u32, w: &mut dyn Write) -> Result<()> {
|
||||
let opt = wasm
|
||||
.names_section()
|
||||
.and_then(NameSection::functions)
|
||||
.and_then(|v| v.names().get(index));
|
||||
|
||||
write!(w, "FUNC_LIST")?;
|
||||
|
||||
if let Some(name) = opt {
|
||||
write!(w, "--[[ {name} ]]")?;
|
||||
}
|
||||
|
||||
write!(w, "[{index}] =")
|
||||
}
|
||||
|
||||
fn write_func_list(
|
||||
wasm: &Module,
|
||||
type_info: &TypeInfo,
|
||||
func_list: &[FuncData],
|
||||
w: &mut dyn Write,
|
||||
) -> Result<()> {
|
||||
func_list.iter().enumerate().try_for_each(|(i, v)| {
|
||||
let index = (type_info.len_ex() + i).try_into().unwrap();
|
||||
|
||||
write_func_start(wasm, index, w)?;
|
||||
|
||||
v.write(&mut Manager::default(), w)
|
||||
})
|
||||
}
|
||||
|
||||
fn write_module_start(
|
||||
wasm: &Module,
|
||||
type_info: &TypeInfo,
|
||||
mem_set: &BTreeSet<usize>,
|
||||
w: &mut dyn Write,
|
||||
) -> Result<()> {
|
||||
write!(w, "local function run_init_code()")?;
|
||||
write_table_list(wasm, w)?;
|
||||
write_memory_list(wasm, w)?;
|
||||
write_global_list(wasm, type_info, w)?;
|
||||
write_element_list(wasm, type_info, w)?;
|
||||
write_data_list(wasm, type_info, w)?;
|
||||
write!(w, "end ")?;
|
||||
|
||||
write!(w, "return function(wasm)")?;
|
||||
write_import_list(wasm, w)?;
|
||||
write!(w, "run_init_code()")?;
|
||||
|
||||
for mem in mem_set {
|
||||
write!(w, "memory_at_{mem} = MEMORY_LIST[{mem}]")?;
|
||||
}
|
||||
|
||||
if let Some(start) = wasm.start_section() {
|
||||
write!(w, "FUNC_LIST[{start}]()")?;
|
||||
}
|
||||
|
||||
write!(w, "return {{")?;
|
||||
write_export_list(wasm, w)?;
|
||||
write!(w, "}} end ")
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Returns `Err` if writing to `Write` failed.
|
||||
pub fn from_inst_list(code: &[Instruction], type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
|
||||
Builder::from_type_info(type_info)
|
||||
.build_anonymous(code)
|
||||
.write(&mut Manager::default(), w)
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Returns `Err` if writing to `Write` failed.
|
||||
pub fn from_module_typed(wasm: &Module, type_info: &TypeInfo, w: &mut dyn Write) -> Result<()> {
|
||||
let func_list = build_func_list(wasm, type_info);
|
||||
let mem_set = write_localize_used(&func_list, w)?;
|
||||
|
||||
write!(w, "local table_new = require(\"table.new\")")?;
|
||||
write_named_array("FUNC_LIST", wasm.functions_space(), w)?;
|
||||
write_named_array("TABLE_LIST", wasm.table_space(), w)?;
|
||||
write_named_array("MEMORY_LIST", wasm.memory_space(), w)?;
|
||||
write_named_array("GLOBAL_LIST", wasm.globals_space(), w)?;
|
||||
|
||||
write_func_list(wasm, type_info, &func_list, w)?;
|
||||
write_module_start(wasm, type_info, &mem_set, w)
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
/// Returns `Err` if writing to `Write` failed.
|
||||
pub fn from_module_untyped(wasm: &Module, w: &mut dyn Write) -> Result<()> {
|
||||
let type_info = TypeInfo::from_module(wasm);
|
||||
|
||||
from_module_typed(wasm, &type_info, w)
|
||||
}
|
||||
Reference in New Issue
Block a user