plum
git clone https://git.pyrossh.dev/plum
A statically typed, imperative programming language inspired by rust, python
77ca54d
— Peter John
2026-11-16T22:15:01+05:30
U4e: inline small functions that cannot trap
- compiler/cli/tests/cli/crash_test.rs +17 -0
- compiler/test-support/src/lib.rs +12 -0
- compiler/wasm-codegen/src/intrinsics.rs +1 -1
- compiler/wasm-codegen/src/lib.rs +6 -3
- compiler/wasm-codegen/src/matching.rs +1 -1
- compiler/wasm-codegen/src/module.rs +13 -2
- compiler/wasm-codegen/src/optimize.rs +401 -0
- compiler/wasm-codegen/src/traits.rs +2 -2
- compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs +2 -2
- compiler/wasm-codegen/tests/wasm_codegen/dispatch_test.rs +2 -0
- compiler/wasm-codegen/tests/wasm_codegen/e2e_mem/reuse.rs +1 -0
- compiler/wasm-codegen/tests/wasm_codegen/e2e_records/inline_value_fields.rs +1 -1
- compiler/wasm-codegen/tests/wasm_codegen/e2e_tail/tail.rs +1 -1
- compiler/wasm-codegen/tests/wasm_codegen/fusion_alloc_test.rs +4 -0
- compiler/wasm-codegen/tests/wasm_codegen/optimize_test.rs +76 -8
- docs/backlog.md +3 -2
compiler/cli/tests/cli/crash_test.rs
CHANGED
|
@@ -100,3 +100,20 @@ fn aTrapIsOneCleanLine() {
|
|
|
100
100
|
assert_eq!(boom.lines().count(), 1, "{boom}");
|
|
101
101
|
assert!(boom.starts_with("crash: boom at "), "{boom}");
|
|
102
102
|
}
|
|
103
|
+
|
|
104
|
+
/// Small functions are copied into their callers only when they cannot trap, so a trap
|
|
105
|
+
/// still names every function on the stack: `half` (a division) and `scaled` (which calls
|
|
106
|
+
/// it) stay functions.
|
|
107
|
+
#[test]
|
|
108
|
+
fn aTrapNamesEverySmallFunctionOnTheStack() {
|
|
109
|
+
let dir = crate::common::Scratch::new("trap_small");
|
|
110
|
+
std::fs::write(
|
|
111
|
+
dir.join("small.plum"),
|
|
112
|
+
"import std/Int\nimport std/Io\nimport std/Str\nimport std/App\nstruct T(mut n: Int)\n\nprimitive Main[App] =\n fun half(t: T, k: Int) -> Int =\n d := k * 2\n if d > 4 then d else t.n / {k - 1}\n\n fun scaled(t: T, k: Int) -> Int =\n e := k + 1\n if e > 100 then e else Main.half(t, k) + 1\n\n fun main(io: Io) =\n t := T(n: 5)\n io.printLn(\"{Main.scaled(t, 1)}\")\n",
|
|
113
|
+
)
|
|
114
|
+
.unwrap();
|
|
115
|
+
let out = Command::new(plumBin()).current_dir(crate::common::root()).arg("run").arg(dir.join("small.plum")).output().unwrap();
|
|
116
|
+
let stderr = String::from_utf8_lossy(&out.stderr);
|
|
117
|
+
assert!(!out.status.success(), "stderr: {stderr}");
|
|
118
|
+
assert_eq!(stderr.trim(), "crash: division by zero in Main.half (called from Main.scaled, main)");
|
|
119
|
+
}
|
compiler/test-support/src/lib.rs
CHANGED
|
@@ -125,6 +125,18 @@ pub fn compile(name: &str, src: &str) -> Vec<u8> {
|
|
|
125
125
|
bytes
|
|
126
126
|
}
|
|
127
127
|
|
|
128
|
+
/// `compile`, but small functions stay functions (no `inlineSmall`): for tests that read a
|
|
129
|
+
/// function's own body by name.
|
|
130
|
+
pub fn compileKeepingFns(name: &str, src: &str) -> Vec<u8> {
|
|
131
|
+
let source = load(name, src).unwrap_or_else(|e| panic!("load failed: {e}"));
|
|
132
|
+
let opts = plum_wasm_codegen::CompileOptions { inlineSmall: false, ..Default::default() };
|
|
133
|
+
let bytes = plum_wasm_codegen::compile(&source, &opts)
|
|
134
|
+
.map(|o| o.wasm)
|
|
135
|
+
.unwrap_or_else(|ds| panic!("compile failed: {}", ds.iter().map(|d| d.to_string()).collect::<Vec<_>>().join("\n")));
|
|
136
|
+
wasmparser::validate(&bytes).expect("valid wasm");
|
|
137
|
+
bytes
|
|
138
|
+
}
|
|
139
|
+
|
|
128
140
|
pub fn engine() -> wasmtime::Engine {
|
|
129
141
|
let mut config = wasmtime::Config::new();
|
|
130
142
|
config.wasm_gc(true);
|
compiler/wasm-codegen/src/intrinsics.rs
CHANGED
|
@@ -508,7 +508,7 @@ pub(crate) fn compileArrayIntrinsicFnBody(f: &ast::Fn, subst: &Subst) -> Option<
|
|
|
508
508
|
Instruction::LocalSet(5).encode(&mut body);
|
|
509
509
|
Instruction::Br(0).encode(&mut body);
|
|
510
510
|
Instruction::End.encode(&mut body); // loop
|
|
511
|
-
|
|
511
|
+
crate::optimize::emitImpossible(&mut body);
|
|
512
512
|
Instruction::End.encode(&mut body); // block
|
|
513
513
|
Instruction::End.encode(&mut body); // function
|
|
514
514
|
Some(body)
|
compiler/wasm-codegen/src/lib.rs
CHANGED
|
@@ -67,11 +67,14 @@ pub struct CompileOptions {
|
|
|
67
67
|
/// see `optimize::removeDeadFunctions`): for tests that read a fn's body by name after
|
|
68
68
|
/// the passes inlined every call to it.
|
|
69
69
|
pub keepDeadFns: bool,
|
|
70
|
+
/// Copy small functions that cannot trap into their callers (`optimize::inlineSmall`).
|
|
71
|
+
/// Off for tests that read a function's own body by name.
|
|
72
|
+
pub inlineSmall: bool,
|
|
70
73
|
}
|
|
71
74
|
|
|
72
75
|
impl Default for CompileOptions {
|
|
73
76
|
fn default() -> Self {
|
|
74
|
-
CompileOptions { tests: false, passes: plum_driver::PassOptions::default(), keepDeadFns: false }
|
|
77
|
+
CompileOptions { tests: false, passes: plum_driver::PassOptions::default(), keepDeadFns: false, inlineSmall: true }
|
|
75
78
|
}
|
|
76
79
|
}
|
|
77
80
|
|
|
@@ -118,12 +121,12 @@ pub fn compile(source: &ast::Source, opts: &CompileOptions) -> Result<Output, Ve
|
|
|
118
121
|
let mut extra = prog.extraExports.clone();
|
|
119
122
|
extra.extend(gameExports(game));
|
|
120
123
|
let (mut module, fn_keys) = compileSourceInner(&prog.source, &extra, typed).map_err(codegenDiag)?;
|
|
121
|
-
let wasm = module.finishOptimized(opts.keepDeadFns);
|
|
124
|
+
let wasm = module.finishOptimized(opts.keepDeadFns, opts.inlineSmall);
|
|
122
125
|
Ok(Output { wasm, fn_keys, test_names: prog.names, isGame: game })
|
|
123
126
|
} else {
|
|
124
127
|
let typed = plum_core::timing::time("check + passes", || plum_driver::check(source, &opts.passes))?;
|
|
125
128
|
let (mut module, fn_keys) = plum_core::timing::time("codegen", || compileSourceInner(source, &gameExports(game), typed)).map_err(codegenDiag)?;
|
|
126
|
-
let wasm = plum_core::timing::time("wasm passes", || module.finishOptimized(opts.keepDeadFns));
|
|
129
|
+
let wasm = plum_core::timing::time("wasm passes", || module.finishOptimized(opts.keepDeadFns, opts.inlineSmall));
|
|
127
130
|
Ok(Output { wasm, fn_keys, test_names: Vec::new(), isGame: game })
|
|
128
131
|
}
|
|
129
132
|
}
|
compiler/wasm-codegen/src/matching.rs
CHANGED
|
@@ -266,7 +266,7 @@ pub(crate) fn compileMatchArmsMulti(
|
|
|
266
266
|
// match" error), also one whose coverage `exhaustive_fallback` can't see from
|
|
267
267
|
// the tags (`_, R` arms across two subjects): no value gets here.
|
|
268
268
|
if result_vt.is_some() {
|
|
269
|
-
|
|
269
|
+
crate::optimize::emitImpossible(body);
|
|
270
270
|
}
|
|
271
271
|
return Ok(());
|
|
272
272
|
}
|
compiler/wasm-codegen/src/module.rs
CHANGED
|
@@ -190,13 +190,14 @@ impl WasmModule {
|
|
|
190
190
|
}
|
|
191
191
|
|
|
192
192
|
/// The module's bytes after the passes in `optimize` (with `keepDeadFns`, functions
|
|
193
|
-
/// nothing reaches stay, for tests that read a fn the passes inlined everywhere
|
|
193
|
+
/// nothing reaches stay, for tests that read a fn the passes inlined everywhere; without
|
|
194
|
+
/// `inlineSmall`, `optimize::inlineSmall` does not run). With
|
|
194
195
|
/// `PLUM_NO_WASM_OPT` set in the environment no pass runs (to compare a program's
|
|
195
196
|
/// behaviour with and without them). When the module as built does not validate, it is
|
|
196
197
|
/// returned as it is, so the engine reports the error. A pass that breaks a valid
|
|
197
198
|
/// module is a compiler bug: a panic in debug builds; otherwise a warning on stderr,
|
|
198
199
|
/// a count in `optimizerFallbacks`, and the unoptimised module.
|
|
199
|
-
pub fn finishOptimized(&mut self, keepDeadFns: bool) -> Vec<u8> {
|
|
200
|
+
pub fn finishOptimized(&mut self, keepDeadFns: bool, inlineSmall: bool) -> Vec<u8> {
|
|
200
201
|
if std::env::var_os(NO_WASM_OPT_ENV).is_some() || crate::optimize::validates(self).is_err() {
|
|
201
202
|
return self.encode();
|
|
202
203
|
}
|
|
@@ -205,6 +206,16 @@ impl WasmModule {
|
|
|
205
206
|
.and_then(|_| crate::optimize::inlineLeaves(self))
|
|
206
207
|
// Again, for the calls inside what the first round copied (`Int.compare` in a small fn).
|
|
207
208
|
.and_then(|_| crate::optimize::inlineLeaves(self))
|
|
209
|
+
// Rounds, for the calls inside what a round copied, until one copies nothing.
|
|
210
|
+
.and_then(|_| {
|
|
211
|
+
let rounds = if inlineSmall { crate::optimize::SMALL_INLINE_ROUNDS } else { 0 };
|
|
212
|
+
for _ in 0..rounds {
|
|
213
|
+
if crate::optimize::inlineSmall(self)? == 0 {
|
|
214
|
+
break;
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
Ok(0)
|
|
218
|
+
})
|
|
208
219
|
.and_then(|_| crate::optimize::removeRedundantCasts(self))
|
|
209
220
|
.and_then(|_| if keepDeadFns { Ok(0) } else { crate::optimize::removeDeadFunctions(self) })
|
|
210
221
|
.and_then(|_| crate::optimize::validates(self));
|
compiler/wasm-codegen/src/optimize.rs
CHANGED
|
@@ -489,3 +489,404 @@ pub(crate) fn inlineLeaves(module: &mut WasmModule) -> Result<usize, String> {
|
|
|
489
489
|
}
|
|
490
490
|
Ok(count)
|
|
491
491
|
}
|
|
492
|
+
|
|
493
|
+
/// Largest body (bytes of code after its local declarations) `inlineSmall` copies into a
|
|
494
|
+
/// caller. Measured on Orbit Runner, Clockwork and the scale benchmark (instructions
|
|
495
|
+
/// retired): 60 bytes took 2/3 of the gain, 100 nearly all of it for +20% of wasm; 150 and
|
|
496
|
+
/// 250 a few percent more of paint for +27% and +46%.
|
|
497
|
+
pub(crate) const SMALL_INLINE_LIMIT: usize = 100;
|
|
498
|
+
|
|
499
|
+
/// Largest body `inlineSmall` copies into the one place that calls it (nothing else names
|
|
500
|
+
/// it, so its own copy then goes): the wasm hardly grows.
|
|
501
|
+
pub(crate) const ONE_CALL_INLINE_LIMIT: usize = 400;
|
|
502
|
+
|
|
503
|
+
/// How many times `finishOptimized` runs `inlineSmall` at most.
|
|
504
|
+
pub(crate) const SMALL_INLINE_ROUNDS: usize = 3;
|
|
505
|
+
|
|
506
|
+
/// Writes the trap of a path no value takes (an exhaustive match's fall-through, a trait
|
|
507
|
+
/// call's unknown tag): `nop` then `unreachable`. The `nop` tells `inlineSmall` that this
|
|
508
|
+
/// `unreachable` is no `crash`, `assert` or range check a program can reach.
|
|
509
|
+
pub(crate) fn emitImpossible(body: &mut Vec<u8>) {
|
|
510
|
+
body.extend_from_slice(&[0x01, 0x00]);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/// Can `op` trap? A division or remainder, a float-to-integer conversion, an array access or
|
|
514
|
+
/// an allocation of a computed length (`at`, a checked index), `unreachable` (after a `crash`,
|
|
515
|
+
/// an `assert`, a host range check), memory and table access, an indirect call (whose callee
|
|
516
|
+
/// is unknown, so may trap) and the exception instructions. (`inlineSmall` looks at the
|
|
517
|
+
/// instruction before for two exceptions: `unreachable` written by `emitImpossible`, and a
|
|
518
|
+
/// division by a constant other than 0 and -1.) `array.new_data` is codegen's string literal, of a
|
|
519
|
+
/// constant range of its segment. A failed `ref.cast` or a `struct.get` on null
|
|
520
|
+
/// would trap too, but Plum has no null and its casts follow its own tests: those only
|
|
521
|
+
/// trap on a compiler bug.
|
|
522
|
+
fn mayTrap(op: &Operator) -> bool {
|
|
523
|
+
use Operator::*;
|
|
524
|
+
match op {
|
|
525
|
+
Unreachable | I32DivS | I32DivU | I32RemS | I32RemU | I64DivS | I64DivU | I64RemS | I64RemU | I32TruncF32S
|
|
526
|
+
| I32TruncF32U | I32TruncF64S | I32TruncF64U | I64TruncF32S | I64TruncF32U | I64TruncF64S | I64TruncF64U
|
|
527
|
+
| ArrayGet { .. } | ArrayGetS { .. } | ArrayGetU { .. } | ArraySet { .. } | ArrayFill { .. } | ArrayCopy { .. }
|
|
528
|
+
| ArrayInitData { .. } | ArrayInitElem { .. } | ArrayNew { .. } | ArrayNewDefault { .. }
|
|
529
|
+
| ArrayNewElem { .. } | CallIndirect { .. } | CallRef { .. } | ReturnCallIndirect { .. } | ReturnCallRef { .. }
|
|
530
|
+
| Throw { .. } | ThrowRef | Rethrow { .. } | Try { .. } | TryTable { .. } | Catch { .. } | CatchAll | Delegate { .. } => true,
|
|
531
|
+
I32Const { .. } | I64Const { .. } | F32Const { .. } | F64Const { .. } | LocalGet { .. } | LocalSet { .. } | LocalTee { .. }
|
|
532
|
+
| GlobalGet { .. } | GlobalSet { .. } | Call { .. } | ReturnCall { .. } | Block { .. } | Loop { .. } | If { .. } | Else
|
|
533
|
+
| End | Br { .. } | BrIf { .. } | BrTable { .. } | Return | Drop | Select | TypedSelect { .. } | Nop | StructGet { .. }
|
|
534
|
+
| StructGetS { .. } | StructGetU { .. } | StructSet { .. } | StructNew { .. } | StructNewDefault { .. }
|
|
535
|
+
| ArrayNewFixed { .. } | ArrayNewData { .. } | ArrayLen | RefTestNonNull { .. } | RefTestNullable { .. } | RefCastNonNull { .. }
|
|
536
|
+
| RefCastNullable { .. } | RefNull { .. } | RefIsNull | RefFunc { .. } | RefAsNonNull | RefEq | RefI31 | I31GetS
|
|
537
|
+
| I31GetU | BrOnNull { .. } | BrOnNonNull { .. } | BrOnCast { .. } | BrOnCastFail { .. } | AnyConvertExtern
|
|
538
|
+
| ExternConvertAny => false,
|
|
539
|
+
_ => {
|
|
540
|
+
let s = format!("{op:?}");
|
|
541
|
+
["Load", "Store", "Memory", "Table", "Atomic", "Data", "Elem", "V128", "Throw", "Catch", "Resume", "Suspend", "Switch", "Cont"]
|
|
542
|
+
.iter()
|
|
543
|
+
.any(|p| s.contains(p))
|
|
544
|
+
}
|
|
545
|
+
}
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
/// The local declarations of a function body: `(count, encoded type)` per group, and where
|
|
549
|
+
/// the code after them starts.
|
|
550
|
+
fn localGroups(body: &[u8]) -> Result<(Vec<(u32, Vec<u8>)>, usize), String> {
|
|
551
|
+
let mut r = wasmparser::BinaryReader::new(body, 0);
|
|
552
|
+
let groups = r.read_var_u32().map_err(|e| e.to_string())?;
|
|
553
|
+
let mut out = Vec::new();
|
|
554
|
+
for _ in 0..groups {
|
|
555
|
+
let n = r.read_var_u32().map_err(|e| e.to_string())?;
|
|
556
|
+
let at = r.original_position();
|
|
557
|
+
r.read::<wasmparser::ValType>().map_err(|e| e.to_string())?;
|
|
558
|
+
out.push((n, body[at..r.original_position()].to_vec()));
|
|
559
|
+
}
|
|
560
|
+
Ok((out, r.original_position()))
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
/// The bytes that set local `idx` of encoded type `ty` to its default value; `None` for a
|
|
564
|
+
/// type with no default (a non-null reference: the copy sets it before it reads it, as the
|
|
565
|
+
/// validator checked in the callee) or none written here (`v128`).
|
|
566
|
+
fn resetLocal(ty: &[u8], idx: u32) -> Option<Option<Vec<u8>>> {
|
|
567
|
+
let mut out = match ty.first()? {
|
|
568
|
+
0x7F => vec![0x41, 0],
|
|
569
|
+
0x7E => vec![0x42, 0],
|
|
570
|
+
0x7D => vec![0x43, 0, 0, 0, 0],
|
|
571
|
+
0x7C => vec![0x44, 0, 0, 0, 0, 0, 0, 0, 0],
|
|
572
|
+
0x7B => return None,
|
|
573
|
+
0x64 => return Some(None),
|
|
574
|
+
0x63 => [&[0xD0][..], &ty[1..]].concat(),
|
|
575
|
+
// A shorthand nullable reference type (`anyref`) is its heap type's byte.
|
|
576
|
+
b => vec![0xD0, *b],
|
|
577
|
+
};
|
|
578
|
+
wasm_encoder::Encode::encode(&wasm_encoder::Instruction::LocalSet(idx), &mut out);
|
|
579
|
+
Some(Some(out))
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/// Copies the body of every small function that cannot trap into each place that calls it
|
|
583
|
+
/// directly (`call`, or `return_call` followed by a `return`). Unlike `inlineLeaves`, the
|
|
584
|
+
/// callee may have locals and control flow: the copy is a block of the callee's type, so the
|
|
585
|
+
/// arguments flow into it as they would into the call; it first stores them in locals the
|
|
586
|
+
/// caller adds for the callee's parameters and locals (one set per caller and callee),
|
|
587
|
+
/// sets the callee's own locals to their defaults, and runs the callee's code with every
|
|
588
|
+
/// local renumbered, every `return` a branch out of the block and a `return_call` a call and
|
|
589
|
+
/// that branch.
|
|
590
|
+
///
|
|
591
|
+
/// A candidate holds at most `SMALL_INLINE_LIMIT` bytes of code (`ONE_CALL_INLINE_LIMIT` when
|
|
592
|
+
/// one call is all that names it), no instruction that can trap
|
|
593
|
+
/// (`mayTrap`: no division, no array index, no `crash` or `assert`, no indirect call), calls only
|
|
594
|
+
/// imports other than `crash` and functions that are candidates by the same rule apart from
|
|
595
|
+
/// their size, holds no loop (a call costs little next to a loop, and Cranelift kept a loop
|
|
596
|
+
/// copied into its caller worse: benchmarks/master_vs_simpler `loop` ran 10% more
|
|
597
|
+
/// instructions), and is not recursive: as nothing in it can trap, no crash report ever needs
|
|
598
|
+
/// its name, and every frame a report names is still there. A call on the way to a trap (the
|
|
599
|
+
/// message of a `crash`) stays a call. Returns the number of call sites inlined.
|
|
600
|
+
pub(crate) fn inlineSmall(module: &mut WasmModule) -> Result<usize, String> {
|
|
601
|
+
#[derive(Clone, Copy)]
|
|
602
|
+
enum Fix {
|
|
603
|
+
Local(u8, u32),
|
|
604
|
+
Return(u32),
|
|
605
|
+
ReturnCall(u32, u32),
|
|
606
|
+
}
|
|
607
|
+
struct Fx {
|
|
608
|
+
first: usize,
|
|
609
|
+
end: usize,
|
|
610
|
+
depth: u32,
|
|
611
|
+
safe: bool,
|
|
612
|
+
looped: bool,
|
|
613
|
+
/// Ends in `unreachable`, with no branch or return before it: it only traps (a
|
|
614
|
+
/// `crash`'s message built and handed over, `Slice.outOfRange`).
|
|
615
|
+
trapsOnly: bool,
|
|
616
|
+
/// The op before the current one was `unreachable`.
|
|
617
|
+
lastTrap: bool,
|
|
618
|
+
callees: Vec<u32>,
|
|
619
|
+
fixes: Vec<(usize, usize, Fix)>,
|
|
620
|
+
}
|
|
621
|
+
let bytes = module.encode();
|
|
622
|
+
let imports = module.func_import_count;
|
|
623
|
+
let n = module.functions.len();
|
|
624
|
+
let crash: Vec<u32> = module
|
|
625
|
+
.imports
|
|
626
|
+
.iter()
|
|
627
|
+
.enumerate()
|
|
628
|
+
.filter(|(_, (m, name, _))| m == "plum" && name == "crash")
|
|
629
|
+
.map(|(i, _)| i as u32)
|
|
630
|
+
.collect();
|
|
631
|
+
let mut fx: Vec<Fx> = (0..n).map(|_| Fx { first: 0, end: 0, depth: 0, safe: true, looped: false, trapsOnly: true, lastTrap: false, callees: vec![], fixes: vec![] }).collect();
|
|
632
|
+
let mut localCount: Vec<u32> = vec![0; n];
|
|
633
|
+
// Per caller: (callee, op start, op end, is a return_call, on the way to a trap).
|
|
634
|
+
let mut calls: Vec<Vec<(u32, usize, usize, bool, bool)>> = vec![Vec::new(); n];
|
|
635
|
+
// Per caller: the straight-line run of code each call is in.
|
|
636
|
+
let mut runOf: Vec<Vec<usize>> = vec![Vec::new(); n];
|
|
637
|
+
let mut runs = 0;
|
|
638
|
+
// The first call of the straight-line run of code the walk is in.
|
|
639
|
+
let mut run = 0;
|
|
640
|
+
let mut cur = usize::MAX;
|
|
641
|
+
let mut afterNop = false;
|
|
642
|
+
let mut divisor: Option<i64> = None;
|
|
643
|
+
let mut refFuncs: Vec<u32> = Vec::new();
|
|
644
|
+
walk(&bytes, |fn_i, v, op, start, end| {
|
|
645
|
+
let f = &mut fx[fn_i];
|
|
646
|
+
if cur != fn_i {
|
|
647
|
+
cur = fn_i;
|
|
648
|
+
localCount[fn_i] = v.len_locals();
|
|
649
|
+
f.first = start;
|
|
650
|
+
afterNop = false;
|
|
651
|
+
divisor = None;
|
|
652
|
+
run = 0;
|
|
653
|
+
}
|
|
654
|
+
// The calls that lead straight to an `unreachable` build a crash's message: a cold
|
|
655
|
+
// path, where a copy only costs the hot path registers (`Slice.at` took 2.8% more
|
|
656
|
+
// instructions on benchmarks/master_vs_simpler `array` with its message's `Str` copied).
|
|
657
|
+
match op {
|
|
658
|
+
Operator::Unreachable => {
|
|
659
|
+
for c in &mut calls[fn_i][run..] {
|
|
660
|
+
c.4 = true;
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
Operator::End if f.depth == 0 => {}
|
|
664
|
+
Operator::Br { .. }
|
|
665
|
+
| Operator::BrIf { .. }
|
|
666
|
+
| Operator::BrTable { .. }
|
|
667
|
+
| Operator::BrOnNull { .. }
|
|
668
|
+
| Operator::BrOnNonNull { .. }
|
|
669
|
+
| Operator::BrOnCast { .. }
|
|
670
|
+
| Operator::BrOnCastFail { .. }
|
|
671
|
+
| Operator::Return
|
|
672
|
+
| Operator::ReturnCall { .. }
|
|
673
|
+
| Operator::ReturnCallRef { .. }
|
|
674
|
+
| Operator::ReturnCallIndirect { .. } => f.trapsOnly = false,
|
|
675
|
+
_ => {}
|
|
676
|
+
}
|
|
677
|
+
match op {
|
|
678
|
+
Operator::Block { .. }
|
|
679
|
+
| Operator::Loop { .. }
|
|
680
|
+
| Operator::If { .. }
|
|
681
|
+
| Operator::Else
|
|
682
|
+
| Operator::End
|
|
683
|
+
| Operator::Br { .. }
|
|
684
|
+
| Operator::BrIf { .. }
|
|
685
|
+
| Operator::BrTable { .. }
|
|
686
|
+
| Operator::BrOnNull { .. }
|
|
687
|
+
| Operator::BrOnNonNull { .. }
|
|
688
|
+
| Operator::BrOnCast { .. }
|
|
689
|
+
| Operator::BrOnCastFail { .. }
|
|
690
|
+
| Operator::Return => {
|
|
691
|
+
run = calls[fn_i].len();
|
|
692
|
+
runs += 1;
|
|
693
|
+
}
|
|
694
|
+
_ => {}
|
|
695
|
+
}
|
|
696
|
+
if matches!(op, Operator::End) && f.depth == 0 {
|
|
697
|
+
f.trapsOnly &= f.lastTrap;
|
|
698
|
+
}
|
|
699
|
+
f.lastTrap = matches!(op, Operator::Unreachable);
|
|
700
|
+
let impossible = afterNop && matches!(op, Operator::Unreachable);
|
|
701
|
+
afterNop = matches!(op, Operator::Nop);
|
|
702
|
+
// A division by a constant that is neither 0 nor -1 cannot trap.
|
|
703
|
+
let byConstant = match (op, divisor) {
|
|
704
|
+
(Operator::I32DivS | Operator::I64DivS, Some(c)) => c != 0 && c != -1,
|
|
705
|
+
(Operator::I32DivU | Operator::I64DivU | Operator::I32RemS | Operator::I64RemS | Operator::I32RemU | Operator::I64RemU, Some(c)) => c != 0,
|
|
706
|
+
_ => false,
|
|
707
|
+
};
|
|
708
|
+
divisor = match op {
|
|
709
|
+
Operator::I32Const { value } => Some(*value as i64),
|
|
710
|
+
Operator::I64Const { value } => Some(*value),
|
|
711
|
+
_ => None,
|
|
712
|
+
};
|
|
713
|
+
if f.safe && !impossible && !byConstant && mayTrap(op) {
|
|
714
|
+
f.safe = false;
|
|
715
|
+
}
|
|
716
|
+
match op {
|
|
717
|
+
Operator::Call { function_index } | Operator::ReturnCall { function_index } => {
|
|
718
|
+
let tail = matches!(op, Operator::ReturnCall { .. });
|
|
719
|
+
calls[fn_i].push((*function_index, start, end, tail, false));
|
|
720
|
+
runOf[fn_i].push(runs);
|
|
721
|
+
if crash.contains(function_index) {
|
|
722
|
+
f.safe = false;
|
|
723
|
+
}
|
|
724
|
+
if *function_index >= imports {
|
|
725
|
+
f.callees.push(*function_index - imports);
|
|
726
|
+
}
|
|
727
|
+
if tail {
|
|
728
|
+
f.fixes.push((start, end, Fix::ReturnCall(*function_index, f.depth)));
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
Operator::LocalGet { local_index } => f.fixes.push((start, end, Fix::Local(0x20, *local_index))),
|
|
732
|
+
Operator::LocalSet { local_index } => f.fixes.push((start, end, Fix::Local(0x21, *local_index))),
|
|
733
|
+
Operator::LocalTee { local_index } => f.fixes.push((start, end, Fix::Local(0x22, *local_index))),
|
|
734
|
+
Operator::Return => f.fixes.push((start, end, Fix::Return(f.depth))),
|
|
735
|
+
Operator::RefFunc { function_index } => refFuncs.push(*function_index),
|
|
736
|
+
Operator::Loop { .. } => {
|
|
737
|
+
f.looped = true;
|
|
738
|
+
f.depth += 1;
|
|
739
|
+
}
|
|
740
|
+
Operator::Block { .. } | Operator::If { .. } | Operator::Try { .. } | Operator::TryTable { .. } => f.depth += 1,
|
|
741
|
+
Operator::End if f.depth == 0 => f.end = start,
|
|
742
|
+
Operator::End => f.depth -= 1,
|
|
743
|
+
_ => {}
|
|
744
|
+
}
|
|
745
|
+
})?;
|
|
746
|
+
// A call followed, in the same run, by a call of a function that only traps is cold too.
|
|
747
|
+
for (d, cs) in calls.iter_mut().enumerate() {
|
|
748
|
+
for k in (0..cs.len()).rev() {
|
|
749
|
+
let traps = cs[k].0.checked_sub(imports).is_some_and(|c| fx[c as usize].trapsOnly);
|
|
750
|
+
if traps || cs[k].4 {
|
|
751
|
+
for j in (0..k).rev().take_while(|&j| runOf[d][j] == runOf[d][k]) {
|
|
752
|
+
cs[j].4 = true;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
// The safe ones: no trapping instruction, calling only safe functions (the largest set
|
|
758
|
+
// closed under that rule).
|
|
759
|
+
let mut safe: Vec<bool> = fx.iter().map(|f| f.safe).collect();
|
|
760
|
+
loop {
|
|
761
|
+
let mut changed = false;
|
|
762
|
+
for d in 0..n {
|
|
763
|
+
if safe[d] && fx[d].callees.iter().any(|&c| !safe[c as usize]) {
|
|
764
|
+
safe[d] = false;
|
|
765
|
+
changed = true;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
if !changed {
|
|
769
|
+
break;
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
let reaches = |from: usize, to: usize| {
|
|
773
|
+
let mut seen = vec![false; n];
|
|
774
|
+
let mut stack: Vec<usize> = fx[from].callees.iter().map(|&c| c as usize).collect();
|
|
775
|
+
while let Some(c) = stack.pop() {
|
|
776
|
+
if c == to {
|
|
777
|
+
return true;
|
|
778
|
+
}
|
|
779
|
+
if !std::mem::replace(&mut seen[c], true) {
|
|
780
|
+
stack.extend(fx[c].callees.iter().map(|&c| c as usize));
|
|
781
|
+
}
|
|
782
|
+
}
|
|
783
|
+
false
|
|
784
|
+
};
|
|
785
|
+
// How many direct calls name each function, and whether anything else does (an export,
|
|
786
|
+
// the start function, the table, a `ref.func`): then it stays whatever is inlined.
|
|
787
|
+
let mut sites = vec![0usize; n];
|
|
788
|
+
for cs in &calls {
|
|
789
|
+
for &(f, ..) in cs {
|
|
790
|
+
if let Some(c) = f.checked_sub(imports) {
|
|
791
|
+
sites[c as usize] += 1;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
let mut rooted = vec![false; n];
|
|
796
|
+
for f in module.exports.iter().filter(|(_, k, _)| *k == wasm_encoder::ExportKind::Func).map(|(_, _, i)| *i).chain(module.start_function).chain(module.table_elements.iter().copied()).chain(refFuncs.iter().copied()) {
|
|
797
|
+
if let Some(c) = f.checked_sub(imports) {
|
|
798
|
+
rooted[c as usize] = true;
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
let declared = paramTypes(module);
|
|
802
|
+
struct Copy {
|
|
803
|
+
ty: u32,
|
|
804
|
+
/// The callee's parameter types, then its declared locals', one per local.
|
|
805
|
+
locals: Vec<Vec<u8>>,
|
|
806
|
+
code: Vec<u8>,
|
|
807
|
+
fixes: Vec<(usize, usize, Fix)>,
|
|
808
|
+
}
|
|
809
|
+
let mut copies: Vec<Option<Copy>> = Vec::with_capacity(n);
|
|
810
|
+
for d in 0..n {
|
|
811
|
+
let f = &fx[d];
|
|
812
|
+
let body = &module.functions[d].1;
|
|
813
|
+
let limit = if sites[d] == 1 && !rooted[d] { ONE_CALL_INLINE_LIMIT } else { SMALL_INLINE_LIMIT };
|
|
814
|
+
if !safe[d] || f.looped || f.end < f.first || f.end - f.first > limit || reaches(d, d) {
|
|
815
|
+
copies.push(None);
|
|
816
|
+
continue;
|
|
817
|
+
}
|
|
818
|
+
let (groups, _) = localGroups(body)?;
|
|
819
|
+
let mut locals = declared[d].clone();
|
|
820
|
+
for (k, t) in groups {
|
|
821
|
+
locals.extend(std::iter::repeat_n(t, k as usize));
|
|
822
|
+
}
|
|
823
|
+
if locals.len() as u32 != localCount[d] || locals.iter().any(|t| t.first() == Some(&0x7B)) {
|
|
824
|
+
copies.push(None);
|
|
825
|
+
continue;
|
|
826
|
+
}
|
|
827
|
+
copies.push(Some(Copy {
|
|
828
|
+
ty: module.functions[d].0,
|
|
829
|
+
locals,
|
|
830
|
+
code: body[f.first..f.end].to_vec(),
|
|
831
|
+
fixes: f.fixes.iter().map(|&(s, e, x)| (s - f.first, e - f.first, x)).collect(),
|
|
832
|
+
}));
|
|
833
|
+
}
|
|
834
|
+
let mut edits: Vec<Vec<Edit>> = (0..n).map(|_| Vec::new()).collect();
|
|
835
|
+
let mut added: Vec<Vec<Vec<u8>>> = vec![Vec::new(); n];
|
|
836
|
+
for (d, cs) in calls.iter().enumerate() {
|
|
837
|
+
let mut bases: HashMap<usize, u32> = HashMap::new();
|
|
838
|
+
for &(f, start, end, tail, cold) in cs {
|
|
839
|
+
let Some(callee) = f.checked_sub(imports).map(|c| c as usize) else { continue };
|
|
840
|
+
let Some(Some(copy)) = copies.get(callee) else { continue };
|
|
841
|
+
if callee == d || cold {
|
|
842
|
+
continue;
|
|
843
|
+
}
|
|
844
|
+
let base = *bases.entry(callee).or_insert_with(|| {
|
|
845
|
+
let b = localCount[d] + added[d].len() as u32;
|
|
846
|
+
added[d].extend_from_slice(©.locals);
|
|
847
|
+
b
|
|
848
|
+
});
|
|
849
|
+
let params = declared[callee].len() as u32;
|
|
850
|
+
let mut with = Vec::new();
|
|
851
|
+
use wasm_encoder::{Encode, Instruction as I};
|
|
852
|
+
I::Block(wasm_encoder::BlockType::FunctionType(copy.ty)).encode(&mut with);
|
|
853
|
+
for k in (0..params).rev() {
|
|
854
|
+
I::LocalSet(base + k).encode(&mut with);
|
|
855
|
+
}
|
|
856
|
+
for (k, t) in copy.locals.iter().enumerate().skip(params as usize) {
|
|
857
|
+
if let Some(Some(reset)) = resetLocal(t, base + k as u32) {
|
|
858
|
+
with.extend_from_slice(&reset);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
let mut at = 0;
|
|
862
|
+
for &(s, e, x) in ©.fixes {
|
|
863
|
+
with.extend_from_slice(©.code[at..s]);
|
|
864
|
+
match x {
|
|
865
|
+
Fix::Local(opcode, k) => {
|
|
866
|
+
with.push(opcode);
|
|
867
|
+
leb(base + k, &mut with);
|
|
868
|
+
}
|
|
869
|
+
Fix::Return(depth) => I::Br(depth).encode(&mut with),
|
|
870
|
+
Fix::ReturnCall(g, depth) => {
|
|
871
|
+
I::Call(g).encode(&mut with);
|
|
872
|
+
I::Br(depth).encode(&mut with);
|
|
873
|
+
}
|
|
874
|
+
}
|
|
875
|
+
at = e;
|
|
876
|
+
}
|
|
877
|
+
with.extend_from_slice(©.code[at..]);
|
|
878
|
+
with.push(0x0B);
|
|
879
|
+
if tail {
|
|
880
|
+
with.push(0x0F);
|
|
881
|
+
}
|
|
882
|
+
edits[d].push(Edit { start, end, with });
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
let count = applyAll(module, edits);
|
|
886
|
+
for (d, extra) in added.iter().enumerate() {
|
|
887
|
+
if !extra.is_empty() {
|
|
888
|
+
module.functions[d].1 = addLocals(&module.functions[d].1, extra)?;
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
Ok(count)
|
|
892
|
+
}
|
compiler/wasm-codegen/src/traits.rs
CHANGED
|
@@ -138,7 +138,7 @@ fn emitTagOf(l: u32, reg: &GcTypeRegistry, body: &mut Vec<u8>) {
|
|
|
138
138
|
fn emitTagSwitch(local: u32, reg: &GcTypeRegistry, arms: &[(Vec<i32>, Vec<u8>)], body: &mut Vec<u8>) {
|
|
139
139
|
let tags = || arms.iter().flat_map(|a| a.0.iter().copied());
|
|
140
140
|
if arms.is_empty() || tags().next().is_none() {
|
|
141
|
-
|
|
141
|
+
crate::optimize::emitImpossible(body);
|
|
142
142
|
return;
|
|
143
143
|
}
|
|
144
144
|
let lo = tags().min().unwrap();
|
|
@@ -163,7 +163,7 @@ fn emitTagSwitch(local: u32, reg: &GcTypeRegistry, arms: &[(Vec<i32>, Vec<u8>)],
|
|
|
163
163
|
body.extend_from_slice(code);
|
|
164
164
|
}
|
|
165
165
|
Instruction::End.encode(body);
|
|
166
|
-
|
|
166
|
+
crate::optimize::emitImpossible(body);
|
|
167
167
|
}
|
|
168
168
|
|
|
169
169
|
/// The signature of the dispatcher of `obj.method`: `self` as the trait object, then the trait's
|
compiler/wasm-codegen/tests/wasm_codegen/codegen_tests.rs
CHANGED
|
@@ -248,7 +248,7 @@ fn lastCaseOfAnExhaustiveMatchIsNotTested() {
|
|
|
248
248
|
let src = "import std/Int\nimport std/App\nenum Shape =\n | Circle(r: Int)\n | Rect(w: Int, h: Int)\n\nprimitive Main[App] =\n fun areaOf(s: Shape) -> Int =\n match s\n Circle(r) => r * r * 3\n Rect(w, h) => w * h\n\n fun main() -> Int =\n Main.areaOf(Rect(w: 2, h: 5)) + Main.areaOf(Circle(r: 1))\n";
|
|
249
249
|
// Without fusion, which may fold the two calls of constants into `main`.
|
|
250
250
|
let source = plum_test_support::load("lastcase", src).expect("loads");
|
|
251
|
-
let opts = CompileOptions { passes: plum_driver::PassOptions { fusion: false, ..Default::default() }, ..Default::default() };
|
|
251
|
+
let opts = CompileOptions { passes: plum_driver::PassOptions { fusion: false, ..Default::default() }, inlineSmall: false, ..Default::default() };
|
|
252
252
|
let bytes = compile(&source, &opts).expect("compiles").wasm;
|
|
253
253
|
let ops = namedBodies(&bytes).into_iter().find(|(n, _)| n == "Main.areaOf").expect("areaOf").1;
|
|
254
254
|
assert_eq!(ops.iter().filter(|o| o.starts_with("RefTest")).count(), 1, "{ops:?}");
|
|
@@ -1075,7 +1075,7 @@ fn compiledKeys(name: &str, src: &str) -> (Vec<u8>, Vec<String>) {
|
|
|
1075
1075
|
let path = dir.join("main.plum");
|
|
1076
1076
|
std::fs::write(&path, src).unwrap();
|
|
1077
1077
|
let source = plum_core::loadAndMergeDiag(&path, &repoRoot()).expect("load");
|
|
1078
|
-
let o = compile(&source, &CompileOptions::default()).expect("compile");
|
|
1078
|
+
let o = compile(&source, &CompileOptions { inlineSmall: false, ..Default::default() }).expect("compile");
|
|
1079
1079
|
let r = (o.wasm, o.fn_keys);
|
|
1080
1080
|
let _ = std::fs::remove_dir_all(&dir);
|
|
1081
1081
|
wasmparser::validate(&r.0).expect("valid wasm");
|
compiler/wasm-codegen/tests/wasm_codegen/dispatch_test.rs
CHANGED
|
@@ -52,6 +52,8 @@ fn compile(name: &str, src: &str, fbip: bool) -> Vec<u8> {
|
|
|
52
52
|
let source = plum_test_support::load(name, src).unwrap_or_else(|e| panic!("load: {e}"));
|
|
53
53
|
let opts = plum_wasm_codegen::CompileOptions {
|
|
54
54
|
passes: plum_driver::PassOptions { fbip, explain: false, ..plum_driver::PassOptions::default() },
|
|
55
|
+
// Small functions stay functions: the test reads their bodies.
|
|
56
|
+
inlineSmall: false,
|
|
55
57
|
..Default::default()
|
|
56
58
|
};
|
|
57
59
|
let bytes = plum_wasm_codegen::compile(&source, &opts)
|
compiler/wasm-codegen/tests/wasm_codegen/e2e_mem/reuse.rs
CHANGED
|
@@ -39,6 +39,7 @@ fn structNewCountWith(name: &str, src: &str, reuse: bool, fusion: bool) -> usize
|
|
|
39
39
|
passes: plum_driver::PassOptions { fusion: fusion, explain: false, ..plum_driver::PassOptions::default() },
|
|
40
40
|
// `main2`'s rebuild is counted though nothing calls it.
|
|
41
41
|
keepDeadFns: true,
|
|
42
|
+
inlineSmall: false,
|
|
42
43
|
..Default::default()
|
|
43
44
|
};
|
|
44
45
|
let bytes = plum_wasm_codegen::compile(&source, &opts)
|
compiler/wasm-codegen/tests/wasm_codegen/e2e_records/inline_value_fields.rs
CHANGED
|
@@ -14,7 +14,7 @@ import std/App
|
|
|
14
14
|
/// away and leave nothing to look at).
|
|
15
15
|
fn bodies(name: &str, src: &str) -> Vec<(String, Vec<String>)> {
|
|
16
16
|
let source = load(name, src).expect("loads");
|
|
17
|
-
let opts = plum_wasm_codegen::CompileOptions { passes: plum_driver::PassOptions { fusion: false, ..Default::default() }, ..Default::default() };
|
|
17
|
+
let opts = plum_wasm_codegen::CompileOptions { passes: plum_driver::PassOptions { fusion: false, ..Default::default() }, inlineSmall: false, ..Default::default() };
|
|
18
18
|
let bytes = plum_wasm_codegen::compile(&source, &opts).expect("compiles").wasm;
|
|
19
19
|
let mut names: std::collections::HashMap<u32, String> = Default::default();
|
|
20
20
|
let mut imports = 0u32;
|
compiler/wasm-codegen/tests/wasm_codegen/e2e_tail/tail.rs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
use plum_test_support::{compile, PRE};
|
|
1
|
+
use plum_test_support::{compileKeepingFns as compile, PRE};
|
|
2
2
|
|
|
3
3
|
fn prog(body: &str) -> String {
|
|
4
4
|
format!("{PRE}{body}")
|
compiler/wasm-codegen/tests/wasm_codegen/fusion_alloc_test.rs
CHANGED
|
@@ -11,6 +11,8 @@ fn load(name: &str, src: &str) -> plum_core::ast::Source {
|
|
|
11
11
|
fn compile(source: &plum_core::ast::Source, fusion: bool) -> Vec<u8> {
|
|
12
12
|
let opts = plum_wasm_codegen::CompileOptions {
|
|
13
13
|
passes: plum_driver::PassOptions { fusion: fusion, explain: false, ..plum_driver::PassOptions::default() },
|
|
14
|
+
// Small functions stay functions: the test reads their bodies.
|
|
15
|
+
inlineSmall: false,
|
|
14
16
|
..Default::default()
|
|
15
17
|
};
|
|
16
18
|
let bytes = plum_wasm_codegen::compile(source, &opts).map(|o| o.wasm).unwrap_or_else(|e| panic!("compile failed: {}", e.iter().map(|d| d.to_string()).collect::<Vec<_>>().join("\n")));
|
|
@@ -642,6 +644,8 @@ fn self_spread_hazard_stays_a_copy() {
|
|
|
642
644
|
fn compileFbip(source: &plum_core::ast::Source, fbip: bool) -> Vec<u8> {
|
|
643
645
|
let opts = plum_wasm_codegen::CompileOptions {
|
|
644
646
|
passes: plum_driver::PassOptions { fbip, explain: false, ..plum_driver::PassOptions::default() },
|
|
647
|
+
// Small functions stay functions: the test reads their bodies.
|
|
648
|
+
inlineSmall: false,
|
|
645
649
|
..Default::default()
|
|
646
650
|
};
|
|
647
651
|
let bytes = plum_wasm_codegen::compile(source, &opts)
|
compiler/wasm-codegen/tests/wasm_codegen/optimize_test.rs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
//! The module-level passes in `src/optimize.rs`: what they take out, and that what is
|
|
2
2
|
//! left still runs.
|
|
3
3
|
|
|
4
|
-
use plum_test_support::{compile, runInt};
|
|
4
|
+
use plum_test_support::{compile, compileKeepingFns, runInt};
|
|
5
5
|
|
|
6
6
|
/// Every operator of every function body, as debug strings, with the function's name.
|
|
7
7
|
fn bodies(bytes: &[u8]) -> Vec<(String, Vec<String>)> {
|
|
@@ -51,7 +51,7 @@ fun main() -> Int =\n PointFns.total(Point(x: 3, y: 4, label: \"p\"), 3)\n";
|
|
|
51
51
|
/// the struct's type.
|
|
52
52
|
#[test]
|
|
53
53
|
fn fieldOfAStructParameterIsNotCast() {
|
|
54
|
-
let all = bodies(&
|
|
54
|
+
let all = bodies(&compileKeepingFns("nocast", POINT));
|
|
55
55
|
let ops = body(&all, "PointFns.total");
|
|
56
56
|
assert!(!ops.iter().any(|o| o.starts_with("RefCast")), "{ops:?}");
|
|
57
57
|
assert!(ops.iter().any(|o| o.starts_with("StructGet")), "{ops:?}");
|
|
@@ -67,7 +67,7 @@ primitive Main[App] =\n fun areaOf(s: Shape) -> Int =\n match s\n Circl
|
|
|
67
67
|
fun main() -> Int =\n Main.areaOf(Rect(w: 2, h: 5)) + Main.areaOf(Circle(r: 1))\n";
|
|
68
68
|
// Without fusion, which may fold the two calls of constants into `main`.
|
|
69
69
|
let source = plum_test_support::load("variantcast", src).expect("loads");
|
|
70
|
-
let opts = plum_wasm_codegen::CompileOptions { passes: plum_driver::PassOptions { fusion: false, ..Default::default() }, ..Default::default() };
|
|
70
|
+
let opts = plum_wasm_codegen::CompileOptions { passes: plum_driver::PassOptions { fusion: false, ..Default::default() }, inlineSmall: false, ..Default::default() };
|
|
71
71
|
let all = bodies(&plum_wasm_codegen::compile(&source, &opts).expect("compiles").wasm);
|
|
72
72
|
let ops = body(&all, "Main.areaOf");
|
|
73
73
|
assert!(ops.iter().any(|o| o.starts_with("RefCast") || o.starts_with("BrOnCast")), "{ops:?}");
|
|
@@ -81,7 +81,7 @@ fn unreachableFunctionsAreDropped() {
|
|
|
81
81
|
let src = "import std/Int\nimport std/App\n\
|
|
82
82
|
primitive Main[App] =\n fun neverCalled(n: Int) -> Int =\n n * 1000\n\n fun twice(f: fn(Int) -> Int, n: Int) -> Int =\n f(f(n))\n\n fun bump(n: Int) -> Int =\n n + 1\n\n \
|
|
83
83
|
fun main() -> Int =\n k := 10\n Main.twice(|n| n + k, 1) + Main.twice(Main.bump, 0)\n";
|
|
84
|
-
let all = bodies(&
|
|
84
|
+
let all = bodies(&compileKeepingFns("deadfns", src));
|
|
85
85
|
let names: Vec<&str> = all.iter().map(|b| b.0.as_str()).collect();
|
|
86
86
|
assert!(!names.contains(&"Main.neverCalled"), "{names:?}");
|
|
87
87
|
assert!(names.iter().any(|n| n.starts_with("Main.twice")), "{names:?}");
|
|
@@ -151,7 +151,7 @@ struct Big(a: Int, b: Int, c: Int, d: Int, e: Int)\nstruct P2(x: Int, y: Int)\n\
|
|
|
151
151
|
struct Hold(big: Big, at: P2, label: Str)\n\n\
|
|
152
152
|
primitive Main[App] =\n fun spot(h: Hold, n: Int) -> Int = if n == 0 then h.at.x * 10 + h.at.y else spot(h, n - 1)\n\n \
|
|
153
153
|
fun main() -> Int =\n Main.spot(Hold(big: Big(a: 1, b: 2, c: 3, d: 4, e: 5), at: P2(x: 6, y: 7), label: \"h\"), 2)\n";
|
|
154
|
-
let all = bodies(&
|
|
154
|
+
let all = bodies(&compileKeepingFns("unboxcopy", src));
|
|
155
155
|
let names: Vec<&str> = all.iter().map(|b| b.0.as_str()).collect();
|
|
156
156
|
assert!(!names.iter().any(|n| n.starts_with("unbox.P2")), "{names:?}");
|
|
157
157
|
let spot = body(&all, "Main.spot");
|
|
@@ -191,7 +191,7 @@ struct Tool(x: Int) =\n fun digitsValue(ds: Str, i: Int, j: Int, acc: Int) -> I
|
|
|
191
191
|
struct Pair2(a: Int, b: Int, c: Str) =\n fun twice(n: Int) -> Int = if n > 100 then n else Pair2.twice(n * 2)\n\n\
|
|
192
192
|
primitive Main[App] =\n fun digitsValue(ds: Str, i: Int, j: Int, acc: Int) -> Int =\n if i >= j then acc else digitsValue(ds, i + 1, j, acc * 10 + digit(ds, i))\n\n fun digit(ds: Str, i: Int) -> Int = ds.byteAtUnchecked(i) - 48\n\n \
|
|
193
193
|
fun main() -> Int =\n Tool.digitsValue(\"1234\", 0, 4, 0) * 10000 + Main.digitsValue(\"5678\", 0, 4, 0) + Pair2.twice(3)\n";
|
|
194
|
-
let all = bodies(&
|
|
194
|
+
let all = bodies(&compileKeepingFns("statics", src));
|
|
195
195
|
let names: Vec<&str> = all.iter().map(|b| b.0.as_str()).collect();
|
|
196
196
|
assert!(!names.contains(&"Tool.digit") && !names.contains(&"Main.digit"), "{names:?}");
|
|
197
197
|
assert_eq!(body(&all, "Tool.digitsValue"), body(&all, "Main.digitsValue"));
|
|
@@ -298,7 +298,7 @@ fn optimizerNeverFallsBackOnTheRepo() {
|
|
|
298
298
|
/// `PLUM_NO_WASM_OPT` turns the passes off: the casts the first pass drops are back.
|
|
299
299
|
#[test]
|
|
300
300
|
fn noWasmOptEnvKeepsTheModuleAsBuilt() {
|
|
301
|
-
let opt =
|
|
301
|
+
let opt = compileKeepingFns("noopt_on", POINT);
|
|
302
302
|
let out = std::process::Command::new(std::env::current_exe().unwrap())
|
|
303
303
|
.args(["--exact", "optimize_test::noWasmOptChild", "--nocapture", "--include-ignored"])
|
|
304
304
|
.env(plum_wasm_codegen::NO_WASM_OPT_ENV, "1")
|
|
@@ -315,7 +315,75 @@ fn noWasmOptEnvKeepsTheModuleAsBuilt() {
|
|
|
315
315
|
#[ignore]
|
|
316
316
|
fn noWasmOptChild() {
|
|
317
317
|
assert!(std::env::var_os(plum_wasm_codegen::NO_WASM_OPT_ENV).is_some(), "run by noWasmOptEnvKeepsTheModuleAsBuilt");
|
|
318
|
-
let all = bodies(&
|
|
318
|
+
let all = bodies(&compileKeepingFns("noopt_off", POINT));
|
|
319
319
|
assert!(body(&all, "PointFns.total").iter().any(|o| o.starts_with("RefCast")), "{:?}", body(&all, "PointFns.total"));
|
|
320
320
|
println!("unoptimised total has a cast");
|
|
321
321
|
}
|
|
322
|
+
|
|
323
|
+
/// Does `caller`'s body call `callee` (`call` or `return_call`)?
|
|
324
|
+
fn callsOf(bytes: &[u8], caller: &str, callee: &str) -> bool {
|
|
325
|
+
let all = bodies(bytes);
|
|
326
|
+
let imports = {
|
|
327
|
+
let mut n = 0u32;
|
|
328
|
+
for payload in wasmparser::Parser::new(0).parse_all(bytes) {
|
|
329
|
+
if let wasmparser::Payload::ImportSection(s) = payload.unwrap() {
|
|
330
|
+
n = s.count();
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
n
|
|
334
|
+
};
|
|
335
|
+
let Some(i) = all.iter().position(|(n, _)| n == callee) else { return false };
|
|
336
|
+
let idx = imports + i as u32;
|
|
337
|
+
body(&all, caller).iter().any(|op| *op == format!("Call {{ function_index: {idx} }}") || *op == format!("ReturnCall {{ function_index: {idx} }}"))
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/// `bump` with what each test puts in its body, called from the loop `run`.
|
|
341
|
+
fn bumpSrc(step: &str) -> String {
|
|
342
|
+
format!(
|
|
343
|
+
"import std/Int\nimport std/App\n\
|
|
344
|
+
struct T(mut n: Int)\n\n\
|
|
345
|
+
primitive Main[App] =\n fun bump(t: T, k: Int) -> Int =\n d := k * 3\n if d > 10\n t.n = t.n + d\n else\n {step}\n t.n\n\n \
|
|
346
|
+
fun run(t: T, i: Int, acc: Int) -> Int = if i == 0 then acc else run(t, i - 1, acc + Main.bump(t, i))\n\n \
|
|
347
|
+
fun main() -> Int = Main.run(T(n: 0), 5, 0)\n"
|
|
348
|
+
)
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/// A small function with a local and branches, that cannot trap, is copied into its caller
|
|
352
|
+
/// (`inlineSmall`): its own copy is gone, and the result is the same.
|
|
353
|
+
#[test]
|
|
354
|
+
fn aSmallFnWithLocalsAndBranchesIsInlined() {
|
|
355
|
+
let src = bumpSrc("t.n = t.n - 1");
|
|
356
|
+
let all = bodies(&compile("small_inline", &src));
|
|
357
|
+
let names: Vec<&str> = all.iter().map(|b| b.0.as_str()).collect();
|
|
358
|
+
assert!(!names.contains(&"Main.bump"), "{names:?}");
|
|
359
|
+
assert_eq!(runInt("small_inline", &src), 117);
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/// A function that can trap stays a function, so a crash report names it: a division, a
|
|
363
|
+
/// checked index, a `crash`, an `assert`.
|
|
364
|
+
#[test]
|
|
365
|
+
fn aFnThatCanTrapIsNotInlined() {
|
|
366
|
+
for (name, step) in [
|
|
367
|
+
("small_div", "t.n = t.n / k"),
|
|
368
|
+
("small_at", "t.n = [1, 2, 3].at(k)"),
|
|
369
|
+
("small_crash", "crash \"no\""),
|
|
370
|
+
("small_assert", "assert k > 0"),
|
|
371
|
+
] {
|
|
372
|
+
let src = bumpSrc(step).replace("import std/Int\n", "import std/Int\nimport std/Str\nimport std/collections/List\n");
|
|
373
|
+
let bytes = compile(name, &src);
|
|
374
|
+
assert!(callsOf(&bytes, "Main.run", "Main.bump"), "{name}: {:?}", bodies(&bytes).iter().map(|b| &b.0).collect::<Vec<_>>());
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/// A recursive function is not copied into itself or its callers (mutual recursion as well).
|
|
379
|
+
#[test]
|
|
380
|
+
fn aRecursiveFnIsNotInlined() {
|
|
381
|
+
let src = "import std/Int\nimport std/App\n\
|
|
382
|
+
primitive Main[App] =\n fun ev(n: Int) -> Int = if n == 0 then 1 else 1 + Main.od(n - 1)\n\n \
|
|
383
|
+
fun od(n: Int) -> Int = if n == 0 then 0 else 1 + Main.ev(n - 1)\n\n \
|
|
384
|
+
fun main() -> Int = Main.ev(7) * 10 + Main.od(4)\n";
|
|
385
|
+
let all = bodies(&compile("small_rec", src));
|
|
386
|
+
let names: Vec<&str> = all.iter().map(|b| b.0.as_str()).collect();
|
|
387
|
+
assert!(names.contains(&"Main.ev") && names.contains(&"Main.od"), "{names:?}");
|
|
388
|
+
assert_eq!(runInt("small_rec", src), 7 * 10 + 4);
|
|
389
|
+
}
|
docs/backlog.md
CHANGED
|
@@ -28,10 +28,11 @@ The retained scene tree was replaced by master's screen view in functional form:
|
|
|
28
28
|
- **Closure calls go through the table** (since U4a, 2026-11-16). A `fn(..)` value is a `ref null $Closure` (`struct {i32 table index}`), and a closure that captures values is its own final subtype with the captures as fields: one allocation (none for a closure that captures nothing: a global built at start), no cast at the call (`struct.get` then `call_indirect`), one cast to a final type in the body. Not `call_ref` on a typed funcref field: wasmtime 47 reads and writes a funcref inside a GC object through a host call (`get_interned_func_ref`), which made Orbit Runner's update 2-3x slower when tried, and a cast to a non-final type that the value only subtypes is a host call too (`is_subtype`), so a `fn` read out of a `Slice` (an `anyref` array) still pays one. Release, interleaved, min of 9 (the machine was loaded): orbit update 13.4 to 12.2 ms, Orb Run 40.7 to 38.2, `benchmarks/closures/calls` 179 to 165; orbit paint, Clockwork, Balloon Pop, `cons`, `cons_rec` within noise (their closures are inlined by closure specialisation or not hot). Left: the table bounds and signature check of `call_indirect`, and the env cast in each capturing body.
|
|
29
29
|
- **A value struct inside an enum payload is boxed twice** (`Some(Pos)` allocates two objects). No measurement yet.
|
|
30
30
|
- **In-place updates still miss** (recounted 2026-11-16 after U4c, `--explain-fusion`, each "not in place" line by its innermost reason): Orb Run 36 in place, 39 not (10 a value still used after the update, all the time travel's `rewindTo`/`undo`/`redo` from a fold; 8 bound to a shared value; 6 rebound by a pattern, `match self.history / Some(h)` and `Shift.after`; 5 a shared value; 3 taken out of `List.head`; 2 fields out of declaration order; 2 a receiver read again; 1 each other). Orbit Runner 31 in place of 96, Clockwork 26 of 88, Menu 20 of 86, Balloon Pop 23 of 86; the biggest reason in the four games is a receiver kept or read again after a method call (19-22, mostly the time travel and `Looping`). No closure reason is left (Balloon Pop's 5 "an argument is passed from inside a closure" went with U4c: its fold's closures are copies now), but the counts are the same as before U4c: each fix moved a spread's reason one step down. U4c added three proofs, each with a test in `uniqueness_fold_test.rs`: a field moved in one arm of a whole-body `match` (`moveRegions`: `Steer` in `PlayingScreen.update` is now a move of `self.ship`), a variable handed over through an inline `if` (`sized := if c then self.resized(p) else self`), and a field read into a local that is only read (`aliasReads`: `ship := self.ship` then `ship.body.pos`); and a pattern binder handed to a read-only parameter counts as a read. What blocks the hot ones now: `PlayingScreen.ship` is shared because the view holds the ship (`if !self.over then self.ship`), so `Ship.steer`/`step`/`hurtFor` copy; `List.head` is shared because `List.find` returns the head and `List.next` pairs it (a field's uniqueness is one fact for every element type), so the actors' steps copy; `Game.run`'s `sized` needs `Game.resized` to return its `self` in place, which `Game.remake` (shared) blocks. The Elm-style `update` regression (Orbit Runner's update 7-10% slower after the Elm screens) was not found in instructions retired here (`screen_views/orbit.plum update` 283M before U4c, 280M after).
|
|
31
|
-
- **Paint** (U4b, 2026-11-16, `sl/paint-direct`): each kind of view has its own copy of the draw's step (`View.paintAt`, `paintCulledAt`, `@final`), so an item costs one trait call in place of four; the walks recurse over the list with no closure (`List.each` with a capturing closure cost about 15% of a paint), skip the walk under an empty view, and an unturned `Place.under`, `Affine.scaleX`/`scaleY`/`rotation`, `Views.through` and a `Left` label skip the matrix product, `hypot`, `atan2` and the text width. `PLUM_NULL_GFX`'s stubs are raw host functions (a typed `Func::new` loaded every argument as a `Val`: a quarter of a timed paint). Instructions retired by the paint (paint run minus update run): Orbit Runner 2,659M to 1,087M, Clockwork (`benchmarks/screen_views/clockwork.plum`, new) 1,394M to 692M, `scale.plum` 7,750M to 2,740M; about a third of each drop is the null host. Open: wasmtime's `compiler_inlining`
|
|
31
|
+
- **Paint** (U4b, 2026-11-16, `sl/paint-direct`): each kind of view has its own copy of the draw's step (`View.paintAt`, `paintCulledAt`, `@final`), so an item costs one trait call in place of four; the walks recurse over the list with no closure (`List.each` with a capturing closure cost about 15% of a paint), skip the walk under an empty view, and an unturned `Place.under`, `Affine.scaleX`/`scaleY`/`rotation`, `Views.through` and a `Left` label skip the matrix product, `hypot`, `atan2` and the text width. `PLUM_NULL_GFX`'s stubs are raw host functions (a typed `Func::new` loaded every argument as a `Val`: a quarter of a timed paint). Instructions retired by the paint (paint run minus update run): Orbit Runner 2,659M to 1,087M, Clockwork (`benchmarks/screen_views/clockwork.plum`, new) 1,394M to 692M, `scale.plum` 7,750M to 2,740M; about a third of each drop is the null host. Open: wasmtime's `compiler_inlining` stays off (inlined frames drop out of a crash's `in f (called from g)`); Plum's own inliner (U4e, below) takes about half of what it took; still made each frame: the view's list (spreads upcast and copied) and each item's own list; `List.each`/`map` with a capturing closure is still slow everywhere else (`Views.stepIn`, `drawnIn`).
|
|
32
|
+
- **Small functions inlined when they cannot trap** (U4e, 2026-11-16, `optimize::inlineSmall`): a function of at most 100 bytes of wasm code (400 when one call is all that names it) is copied into each direct caller, locals and branches included (a block of the callee's type, its locals renumbered, `return` a branch), when nothing in it can trap: no division or remainder (by a constant other than 0 and -1 is fine), no array access or computed-length allocation (`at`, an index), no `crash`, `assert` or host range check (`unreachable`; an exhaustive match's or a trait call's impossible fall-through is written `nop; unreachable` and does not count), no indirect call, and every function it calls the same; not recursive, no loop (a loop copied into `main` ran 10% more instructions on `loop`), and not a call on the way to a crash (its message's `Str` copied into `Slice.at` cost `array` 2.8%). So no trap ever needs an inlined name. Instructions retired, one run of each (in-process, `(REPS=6 - REPS=1) / 5`, min of 3): Orbit Runner update 199M to 164M (-18%), paint 1,285M to 1,104M (-14%); Clockwork update 550M to 503M (-9%), paint 1,235M to 1,103M (-11%); `scale.plum` update 632M to 557M (-12%), paint 3,354M to 2,776M (-17%); `map` -7%, `trig` -9%, `str` -3%, `particles` -3%, `cons`/`fib`/`loop`/`array` unchanged; the run.py drivers Orb Run 742M to 646M (-13%), Balloon Pop 7,261M to 6,765M (-7%); checksums unchanged. Cost: Orbit Runner's .wasm 84,313 to 98,146 bytes (+16%; Clockwork +12%, scale +14%), `plum compile` +2% instructions (6.40G to 6.53G), `plum build` (with Cranelift) +2.5% (7.84G to 8.03G). Left (wasmtime's inliner took 27% of paint): everything that reaches a trap stays a call: `Place.under` (through `Math.cos`'s reduction tables), the `Gfx.*` wrappers (their `Int`-to-`i32` range check), `List.at`, the kinds' `paintAt` (172 bytes); `Views.blendOf` on a kind that is never a `Blend` is copied but still tests (the argument goes through a local of the callee's parameter type, so the static type that would fold the `ref.test` is lost).
|
|
32
33
|
- **Static functions are slower than free functions** (0.78 s against 0.57 s on `benchmarks/static_calls`).
|
|
33
34
|
- **Closures inlined by size** (U4c, 2026-11-16): a callee of at most 64 expression nodes (`closure_spec::SMALL_CALLEE`; std's closure-taking fns are 3-59, `List.map` 3, `fold` 8, `Range.fold` 33, `Slice.mergeRun` 59, the biggest in the repository 68) gets a copy for every closure handed to it; a bigger one keeps a cap of 8 (`MAX_BIG_COPIES`) per callee, in the order its calls are met, so which of its calls are inlined still depends on the rest of the program. Copies made inside copies stop at 4 levels (`MAX_DEPTH`), and 256 copies of one small callee is a safety net. The escape analysis now resolves `x.m(..)` by the checker's receiver type (`FnCall.recv`, stamped before closure specialisation): `List.all` had never been specialised, as `t.all(keep)` resolved to every `all` and `Set.all` captures its closure. Cost: Orbit Runner compiles in 2.7% more instructions (8,722M to 8,957M), its .wasm is 352 bytes bigger (112,515 to 112,867). Run time within 1% in instructions retired on every benchmark (Orb Run 839M to 845M, Orbit Runner update 283M to 280M, Clockwork update 639M to 643M, `closures/calls` 3,084M to 3,083M; whole process, wasmtime's compile included).
|
|
34
|
-
- **Smaller codegen items**: match arms test then cast (`br_on_cast` would do one check);
|
|
35
|
+
- **Smaller codegen items**: match arms test then cast (`br_on_cast` would do one check); every struct has its own empty supertype; purity treats every closure-taking function as impure, so pipelines fuse only after closure specialisation.
|
|
35
36
|
- No evidence either way, so not planned: unchecked reads in `for` over a `Slice` (checked `at` showed no cost).
|
|
36
37
|
|
|
37
38
|
## Bugs
|