-
Notifications
You must be signed in to change notification settings - Fork 1
/
wasm-inline.js
47 lines (41 loc) · 1.41 KB
/
wasm-inline.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/* eslint-env node */
import wabt from 'wabt';
import binaryen from 'binaryen';
import fs from 'fs';
import {fileURLToPath} from 'url';
export {wasmInline as default};
const isMain = process.argv[1] === fileURLToPath(import.meta.url);
if (isMain) {
wasmInline(process.argv[2]);
}
async function wasmInline(wasmPath, doWrite = true) {
// can be called with either .wat or .wasm path
// creates or overwrites the .wasm with functions inlined
let isWasm = wasmPath.indexOf('.wasm') !== -1;
let isWat = wasmPath.indexOf('.wat') !== -1;
if (!isWat && !isWasm) {
console.error('ERROR: must provide .wasm or .wat file as first argument');
process.exit(1);
}
let wasmBinary;
if (isWat) {
let watText = fs.readFileSync(wasmPath, {encoding: 'utf8'});
let wabtModule = (await wabt()).parseWat(wasmPath, watText, {simd: true});
wasmPath = wasmPath.replace('wat/', 'wasm/').replace('.wat', '.wasm');
wasmBinary = wabtModule.toBinary({}).buffer;
} else {
wasmBinary = fs.readFileSync(wasmPath);
}
let module = binaryen.readBinary(wasmBinary);
// force function inlining
binaryen.setOptimizeLevel(3);
binaryen.setShrinkLevel(0);
binaryen.setFlexibleInlineMaxSize(1000000000);
module.runPasses(['inlining-optimizing']);
// module.optimize();
wasmBinary = module.emitBinary();
if (doWrite) {
fs.writeFileSync(wasmPath, wasmBinary);
}
return {bytes: wasmBinary, path: wasmPath};
}