Skip to content

WASM: Runtime Library Experiment #1425

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions build1.sh
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,5 @@ cmake \
-DCMAKE_INSTALL_PREFIX=`pwd`/inst \
.
cmake --build . -j16 --target install

emcc -DWASM_RT_LIB src/libasr/runtime/lfortran_intrinsics.c -o src/libasr/runtime/rt_lib.wasm -s WASM=1 --no-entry
64 changes: 40 additions & 24 deletions src/libasr/codegen/asr_to_wasm.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,8 @@ class ASRToWASMVisitor : public ASR::BaseVisitor<ASRToWASMVisitor> {
no_of_imports = 0;
no_of_data_segments = 0;

min_no_pages = 100; // fixed 6.4 Mb memory currently
max_no_pages = 100; // fixed 6.4 Mb memory currently
min_no_pages = 256; // fixed 16.384 Mb memory currently
max_no_pages = 256; // fixed 16.384 Mb memory currently

m_type_section.reserve(m_al, 1024 * 128);
m_import_section.reserve(m_al, 1024 * 128);
Expand Down Expand Up @@ -224,6 +224,22 @@ class ASRToWASMVisitor : public ASR::BaseVisitor<ASRToWASMVisitor> {
}
}
}
} else if (ASR::is_a<ASR::Module_t>(*item.second)) {
ASR::Module_t *m = ASR::down_cast<ASR::Module_t>(item.second);
for (auto &item : m->m_symtab->get_scope()) {
if (ASR::is_a<ASR::Function_t>(*item.second)) {
ASR::Function_t *fn =
ASR::down_cast<ASR::Function_t>(item.second);
if (fn->m_abi == ASR::abiType::BindC &&
fn->m_deftype == ASR::deftypeType::Interface &&
!ASRUtils::is_intrinsic_function2(fn)) {
wasm::emit_import_fn(m_import_section, m_al, "js",
fn->m_name, no_of_types);
no_of_imports++;
emit_function_prototype(*fn);
}
}
}
} else if (ASR::is_a<ASR::Function_t>(*item.second)) {
ASR::Function_t *fn =
ASR::down_cast<ASR::Function_t>(item.second);
Expand Down Expand Up @@ -627,30 +643,30 @@ class ASRToWASMVisitor : public ASR::BaseVisitor<ASRToWASMVisitor> {
}
if (x.m_abi == ASR::abiType::BindC &&
x.m_deftype == ASR::deftypeType::Interface) {
if (ASRUtils::is_intrinsic_function2(&x)) {
diag.codegen_warning_label(
"WASM: C Intrinsic Functions not yet spported",
{x.base.base.loc}, std::string(x.m_name));
}
// if (ASRUtils::is_intrinsic_function2(&x)) {
// diag.codegen_warning_label(
// "WASM: C Intrinsic Functions not yet spported",
// {x.base.base.loc}, std::string(x.m_name));
// }
return true;
}
for (size_t i = 0; i < x.n_body; i++) {
if (x.m_body[i]->type == ASR::stmtType::SubroutineCall) {
auto sub_call = (const ASR::SubroutineCall_t &)(*x.m_body[i]);
ASR::Function_t *s = ASR::down_cast<ASR::Function_t>(
ASRUtils::symbol_get_past_external(sub_call.m_name));
if (s->m_abi == ASR::abiType::BindC &&
s->m_deftype == ASR::deftypeType::Interface &&
ASRUtils::is_intrinsic_function2(s)) {
diag.codegen_warning_label(
"WASM: Calls to C Intrinsic Functions are not yet "
"supported",
{x.m_body[i]->base.loc},
"Function: calls " + std::string(s->m_name));
return true;
}
}
}
// for (size_t i = 0; i < x.n_body; i++) {
// if (x.m_body[i]->type == ASR::stmtType::SubroutineCall) {
// auto sub_call = (const ASR::SubroutineCall_t &)(*x.m_body[i]);
// ASR::Function_t *s = ASR::down_cast<ASR::Function_t>(
// ASRUtils::symbol_get_past_external(sub_call.m_name));
// if (s->m_abi == ASR::abiType::BindC &&
// s->m_deftype == ASR::deftypeType::Interface &&
// ASRUtils::is_intrinsic_function2(s)) {
// diag.codegen_warning_label(
// "WASM: Calls to C Intrinsic Functions are not yet "
// "supported",
// {x.m_body[i]->base.loc},
// "Function: calls " + std::string(s->m_name));
// return true;
// }
// }
// }
return false;
}

Expand Down
30 changes: 20 additions & 10 deletions src/libasr/codegen/wasm_assembler.h
Original file line number Diff line number Diff line change
Expand Up @@ -777,10 +777,10 @@ void emit_branch_if(Vec<uint8_t> &code, Allocator &al, uint32_t label_idx) {

void save_js_glue(std::string filename) {
std::string js_glue =
R"(function define_imports(memory, outputBuffer, exit_code, stdout_print) {
R"(function define_imports(exports, outputBuffer, exit_code, stdout_print) {
const printNum = (num) => outputBuffer.push(num.toString());
const printStr = (startIdx, strSize) => outputBuffer.push(
new TextDecoder("utf8").decode(new Uint8Array(memory.buffer, startIdx, strSize)));
new TextDecoder("utf8").decode(new Uint8Array(exports.memory.buffer, startIdx, strSize)));
const flushBuffer = () => {
stdout_print(outputBuffer.join(" ") + "\n");
outputBuffer.length = 0;
Expand All @@ -789,7 +789,6 @@ void save_js_glue(std::string filename) {
const cpu_time = (time) => (Date.now() / 1000); // Date.now() returns milliseconds, so divide by 1000
var imports = {
js: {
memory: memory,
/* functions */
print_i32: printNum,
print_i64: printNum,
Expand All @@ -798,7 +797,8 @@ void save_js_glue(std::string filename) {
print_str: printStr,
flush_buf: flushBuffer,
set_exit_code: set_exit_code,
cpu_time: cpu_time
cpu_time: cpu_time,
...exports
},
};
return imports;
Expand All @@ -812,27 +812,37 @@ async function run_wasm(bytes, imports) {
} catch(e) { console.log(e); }
}

async function execute_code(bytes, stdout_print) {
async function execute_code(bytes, exports, stdout_print) {
var exit_code = {val: 1}; /* non-zero exit code */
var outputBuffer = [];
var memory = new WebAssembly.Memory({ initial: 100, maximum: 100 }); // fixed 6.4 Mb memory currently
var imports = define_imports(memory, outputBuffer, exit_code, stdout_print);
// var memory = new WebAssembly.Memory({ initial: 100, maximum: 100 }); // fixed 6.4 Mb memory currently
var imports = define_imports(exports, outputBuffer, exit_code, stdout_print);
await run_wasm(bytes, imports);
return exit_code.val;
}

function main() {
function main(functionExports) {
const fs = require("fs");
const wasmBuffer = fs.readFileSync(")" +
filename + R"(");
execute_code(wasmBuffer, (text) => process.stdout.write(text))
execute_code(wasmBuffer, functionExports, (text) => process.stdout.write(text))
.then((exit_code) => {
process.exit(exit_code);
})
.catch((e) => console.log(e))
}

main();
async function main2() {
const fs = require("fs");
const wasi = require('wasi');
const importOjbect = {wasi_snapshot_preview1: (new wasi.WASI()).wasiImport}
const wasmBuffer = fs.readFileSync("src/libasr/runtime/rt_lib.wasm");
var res = await WebAssembly.instantiate(wasmBuffer, importOjbect);
const exports = res.instance.exports;
main(exports);
}

main2().then().catch((e) => console.log(e));
)";
filename += ".js";
std::ofstream out(filename);
Expand Down
9 changes: 9 additions & 0 deletions src/libasr/runtime/lfortran_intrinsics.h
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
#include <inttypes.h>
#include <stdbool.h>

#ifdef WASM_RT_LIB
#include <emscripten.h>
#endif

#ifdef __cplusplus
extern "C" {
#endif
Expand Down Expand Up @@ -34,6 +38,11 @@ typedef double _Complex double_complex_t;
#define LFORTRAN_API /* Nothing */
#endif

#ifdef WASM_RT_LIB
#undef LFORTRAN_API
#define LFORTRAN_API EMSCRIPTEN_KEEPALIVE
#endif

LFORTRAN_API double _lfortran_sum(int n, double *v);
LFORTRAN_API void _lfortran_random_number(int n, double *v);
LFORTRAN_API double _lfortran_random();
Expand Down