diff --git a/quest/m2/README.md b/quest/m2/README.md index 367e30caa..640a83abf 100644 --- a/quest/m2/README.md +++ b/quest/m2/README.md @@ -21,7 +21,6 @@ The fork's feature quests folded into the [exporter](/quest/m1/ffi-export.md); ## Required -- [MIR's codec as fast as THIR's](/quest/m2/ts-mir-codec.md) - the codec from MIR no slower than from THIR in any engine - [Lower bodies from MIR](/quest/m2/ts-mir.md) - the MIR spike's prototype becomes the only lowering, and the THIR one goes - [Cheaper byte slices](/quest/m2/ts-byte-views.md) - splitting a `&[u8]` stops making a `Uint8Array` view per split - [Wide-integer fast paths](/quest/m2/ts-wide-fast.md) - a fused `from_halves` and an unboxed limb product, kept only if measured faster diff --git a/quest/m2/ts-mir-codec.md b/quest/m2/ts-mir-codec.md deleted file mode 100644 index 69614bd16..000000000 --- a/quest/m2/ts-mir-codec.md +++ /dev/null @@ -1,17 +0,0 @@ -# [M] MIR's codec as fast as THIR's - -## Goal - -Lowering moq-net's codec from MIR runs it no slower than THIR's lowering on -`just ts bench`, in Node, Bun, and Chromium, before MIR becomes the only lowering. - -## Plan - -Decided with the maintainer on 2026-10-24: this blocks making MIR the default. On -[#36](https://github.com/kixelated/rust2/pull/36)'s head, after its review fixes, the -codec's geometric mean from MIR was 1.10x THIR's in Node, 1.02x in Bun, and 1.12x in -Chromium, against A/A controls of 1.00. Group encode was 1.9-2.6x slower in every -engine, frames encode 1.3-1.4x in Chromium, and small varint encodes up to 1.6x in -Node (but 0.7x in Bun). An earlier run, before the review fixes and the bench's -random order, put the codec within 8% apart from group encode, so start by -separating what the review fixes' copies cost from what was always there. diff --git a/quest/m2/ts-mir.md b/quest/m2/ts-mir.md index bba9931ab..e19027571 100644 --- a/quest/m2/ts-mir.md +++ b/quest/m2/ts-mir.md @@ -26,8 +26,11 @@ still needs: copied out of a field and then passed on. - `?` on an `Option` returned through a `next` whose item can be `undefined`, and the other THIR special cases the prototype mirrors (`for` loops by the iterator protocol, - `from_be_bytes` of bytes made in place, ranges stepped in place): keep each only - where `just ts bench` measures it. + `from_be_bytes` of bytes made in place): keep each only where `just ts bench` + measures it. Ranges stepped in place stay: a `for` over `0..n` read through + `rt.Range.next` or as a number-or-`rt.DONE` was up to 1.3x slower in V8. +- A signed `%` by a constant leaves its overflow check's operands as statements + (`4 === -1;`), which `tsc` rejects. - Size: the task fixture's bundle is 35% larger gzipped than THIR's, the codec's 9%. Likely wins, each to measure: a coroutine resume function structured where the graph allows (a dispatch at each loop header the resume enters, rather than a @@ -44,7 +47,3 @@ take a raw pointer. A nightly bump that changes them should fail loudly, as each now. Public API: the translator's whole output, and the `--lower` option, which goes. - -## Required - -- [MIR's codec as fast as THIR's](/quest/m2/ts-mir-codec.md) - the codec from MIR no slower than from THIR in any engine diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index bdc0d6f52..1ec46deeb 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -378,16 +378,35 @@ export function loops(data: Uint8Array, out: rt.ByteVec): void { count = rt.u8.add(count, 1); } out.push(count); + const lo = rt.i32.neg(rt.usize.rem(data.length, 4) | 0); + let r: rt.Range = new rt.Range(lo, rt.i32.add(lo, 3)); + const first = rt.iter.toOption(r.next()); + r.end = r.start; + const second = rt.iter.toOption(r.next()); + if (first !== undefined) { + const x = first; + out.extendFromSlice(rt.i32.toBeBytes(x)); + } + if (second !== undefined) { + const x2 = second; + out.extendFromSlice(rt.i32.toBeBytes(x2)); + } + for (let k = lo; k < 2; k++) { + out.push(k & 0xff); + } + for (let k2 = rt.i8.sub(124, (lo << 24) >> 24); k2 < 127; k2++) { + out.push(k2 & 0xff); + } out.push(firstRepeat(data)); out.extendFromSlice(rt.u16.toBeBytes(tailBreak(data))); out.push(armLoop(data)); out.extendFromSlice(rt.u32.toBeBytes(position$u8(data, 0) as rt.u32)); - const settle = (x: rt.u8): rt.u8 => { + const settle = (x3: rt.u8): rt.u8 => { while (true) { - if (x < 10) { - return x; + if (x3 < 10) { + return x3; } - x = rt.u8.div(x, 3); + x3 = rt.u8.div(x3, 3); } }; out.push(settle(rt.u8.mul(data.length & 0xff, 7))); diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index bdbea9e32..236e5f1d6 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -493,6 +493,26 @@ pub fn loops(data: &[u8], out: &mut Vec) { } out.push(count); + // Ranges stepped by hand: signed across zero, up to the type's end, and an item read + // after the range changed. + let lo = -((data.len() % 4) as i32); + let mut r = lo..lo + 3; + let first = r.next(); + r.end = r.start; + let second = r.next(); + if let Some(x) = first { + out.extend_from_slice(&x.to_be_bytes()); + } + if let Some(x) = second { + out.extend_from_slice(&x.to_be_bytes()); + } + for k in lo..2 { + out.push(k as u8); + } + for k in 124 - lo as i8..i8::MAX { + out.push(k as u8); + } + out.push(first_repeat(data)); out.extend_from_slice(&tail_break(data).to_be_bytes()); out.push(arm_loop(data)); diff --git a/ts/src/lower/mir/call.rs b/ts/src/lower/mir/call.rs index 53524ccd1..1a41fdb91 100644 --- a/ts/src/lower/mir/call.rs +++ b/ts/src/lower/mir/call.rs @@ -34,6 +34,15 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { { let iter_ty = gargs.skip_binder().type_at(0); let recv = self.operand_frozen(&args[0].node, span, &mut pre); + if self.range_nexts.contains(&dest.local) + && let Some(name) = self.var(dest.local) + { + let name = name.to_string(); + self.assigned[dest.local] = true; + self.range_next(name, recv, &mut pre); + self.emit(pre, None, false, out); + return; + } if let Some(name) = self.var(dest.local) { let name = name.to_string(); self.next_names.insert(name); @@ -221,11 +230,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { done(Expr::undefined(), true) } // A range of numbers steps in place, with nothing between it and the loop. - ("Iterator", "next") - if let ty::Adt(adt, range_args) = targ(0)?.kind() - && Std::of(tcx, adt.did()) == Some(Std::Range) - && Int::of(range_args.type_at(0)).is_some_and(|i| !i.big()) => - { + ("Iterator", "next") if super::small_range(tcx, targ(0)?) => { let range = self.alias_place(&args[0].node)?; let start = range.clone().member("start"); let next = Expr::Cond( @@ -427,6 +432,28 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { } } + /// `name = recv.next()` of a range of numbers, stepped in place rather than through + /// `rt.Range`'s generic steps, into the item alone and a flag for whether there was + /// one: a number that is sometimes `rt.DONE` is slower in V8. Past the end, `name` is + /// left as it was, since only `Some` reads it. + fn range_next(&mut self, name: String, recv: Expr, out: &mut Vec) { + let range = self.path(recv, "range", out); + let start = range.clone().member("start"); + let flag = self.b.fresh(&format!("{name}Some")); + let more = start.clone().binary("<", range.member("end")); + out.push(StmtKind::Expr(Expr::ident(&flag).assign(more)).at(None)); + let step = Expr::ident(&name).assign(Expr::Postfix(Box::new(start), "++")); + out.push( + StmtKind::If { + cond: Expr::ident(&flag), + then: vec![StmtKind::Expr(step).at(None)], + els: Vec::new(), + } + .at(None), + ); + self.range_flags.insert(name, flag); + } + /// The value at `place`, after setting `place` to `value`. fn swap_out(&mut self, place: Expr, value: Expr, base: &str, out: &mut Vec) -> Expr { let name = self.b.fresh(base); diff --git a/ts/src/lower/mir/mod.rs b/ts/src/lower/mir/mod.rs index ea84a561d..d25714b27 100644 --- a/ts/src/lower/mir/mod.rs +++ b/ts/src/lower/mir/mod.rs @@ -179,6 +179,11 @@ pub struct Fx<'m, 'b, 'a, 'tcx> { next_results: FxHashSet, /// Their names, which a switch on their variant tests against `rt.DONE`. next_names: FxHashSet, + /// Next results of a range of numbers stepped in place: each holds only the item, so + /// JS keeps it a number, and a flag holds whether there was one. + range_nexts: FxHashSet, + /// Their names, and their flags' names, which a switch on their variant tests. + range_flags: FxHashMap, } impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { @@ -219,6 +224,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { var_parts: FxHashMap::default(), next_results: FxHashSet::default(), next_names: FxHashSet::default(), + range_nexts: FxHashSet::default(), + range_flags: FxHashMap::default(), }; fx.analyze(); fx @@ -576,14 +583,14 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { else { continue; }; - let ty::FnDef(def_id, _) = *func.ty(&mir.local_decls, tcx).kind() else { + let ty::FnDef(def_id, gargs) = *func.ty(&mir.local_decls, tcx).kind() else { continue; }; let Some(local) = destination.as_local() else { continue; }; if crate::lower::iter::is_next(tcx, def_id) && self.defs[local] == 1 { - nexts.push(local); + nexts.push((local, gargs.skip_binder().type_at(0))); } if crate::lower::library::key(tcx, def_id).is_some_and(|(o, n)| o == "Try" && n == "branch") && let [arg] = &**args @@ -597,7 +604,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { branches.insert(from, (at, local)); } } - for local in nexts { + for (local, iter_ty) in nexts { let branch = branches.get(&local).copied(); let mut uses = Uses { local, @@ -624,6 +631,8 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { continue; } self.next_results.insert(to); + } else if local != mir::RETURN_PLACE && small_range(tcx, iter_ty) { + self.range_nexts.insert(local); } self.next_results.insert(local); } @@ -761,6 +770,17 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { out.push(StmtKind::Declare { name, ty }.at(None)); } } + let mut flags: Vec = self.range_flags.values().cloned().collect(); + flags.sort(); + for name in flags { + out.push( + StmtKind::Declare { + name, + ty: Type::Builtin("boolean"), + } + .at(None), + ); + } out.extend(entry); out.extend(body); drop_self_assignments(&mut out); @@ -841,6 +861,9 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { _ => args.type_at(0), }; let item = self.b.t.ty(item, self.span); + if self.range_nexts.contains(&local) { + return item; + } return Type::Union(vec![item, Type::Rt("Done", Vec::new())]); } let ty = match (self.checked.contains(&local), ty.kind()) { @@ -2126,3 +2149,10 @@ fn inert(e: &Expr) -> bool { e => e.is_path(), } } + +/// Whether `ty` is a `Range` of numbers that fit a JS number, which steps in place. +pub(super) fn small_range<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> bool { + matches!(ty.kind(), ty::Adt(adt, args) + if crate::lower::library::Std::of(tcx, adt.did()) == Some(crate::lower::library::Std::Range) + && crate::lower::num::Int::of(args.type_at(0)).is_some_and(|i| !i.big())) +} diff --git a/ts/src/lower/mir/place.rs b/ts/src/lower/mir/place.rs index d23001ce1..e0d2a7405 100644 --- a/ts/src/lower/mir/place.rs +++ b/ts/src/lower/mir/place.rs @@ -369,6 +369,16 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { return self.err(span, format!("no variant of `{ty}` has discriminant {value}")); }; match Std::of(tcx, adt.did()) { + Some(Std::Option) + if let Expr::Ident(n) = scrut + && let Some(flag) = self.range_flags.get(n) => + { + let flag = Expr::ident(flag); + match index.index() { + 0 => flag.not(), + _ => flag, + } + } Some(Std::Option) if matches!(scrut, Expr::Ident(n) if self.next_names.contains(n)) => { match index.index() { 0 => scrut.clone().binary("===", Expr::Rt("DONE")), diff --git a/ts/src/lower/mir/rvalue.rs b/ts/src/lower/mir/rvalue.rs index 2a9901512..c7269cc31 100644 --- a/ts/src/lower/mir/rvalue.rs +++ b/ts/src/lower/mir/rvalue.rs @@ -131,7 +131,7 @@ impl<'m, 'b, 'a, 'tcx> Fx<'m, 'b, 'a, 'tcx> { let v = self.operand(op, span, out); match elem_ty.kind() { ty::Uint(ty::UintTy::U8) => { - let array = Expr::New(Box::new(Expr::ident("Uint8Array")), vec![Expr::lit(n.to_string())]); + let array = Expr::rt("bytes", vec![Expr::lit(n.to_string())]); match &v { Expr::Lit(text) if text == "0" => array, _ => array.member("fill").call(vec![v]),