Skip to content
Merged
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
31 changes: 31 additions & 0 deletions changelog.d/6850-native-imul-typed-array-param.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
### Changed

- Lower two integer-math JS primitives that were compiled as runtime function
calls to native machine ops, closing an ~9x AOT-vs-JIT gap on hot integer
kernels (hashes/PRNGs/mixers/ciphers):
- **`Math.imul(a, b)`** now lowers to a single native `mul i32` whenever both
operands are provably in-range i32 (multiplication mod 2^32 has identical
low 32 bits for signed and unsigned operands, so this is exact).
Non-finite / fractional / `>2^32` operands keep the `js_math_imul` runtime
helper so JS `ToUint32`/`ToInt32` semantics (`NaN`/`±Infinity` -> 0) are
preserved. This also fixes the accumulator case `a = Math.imul(a, K)` where
the constant `K` exceeds `i32::MAX` (e.g. the golden-ratio mixer constant
`0x9e3779b1` = 2654435761): the i32 fast path now accepts integer literals
representable in 32 bits under either a signed or unsigned interpretation.
- **Reading a typed-array element through a parameter** (`S[i]` where
`S: Int32Array` etc. is a function parameter, in an i32/`ToInt32` context)
now lowers to a checked inline native load — a runtime guard (pointer +
inline-storage `PERRY_TA_VIEW_GUARD` + kind-cache) and a header-length
bounds check gate a bare width-correct load, an in-kind out-of-bounds read
yields `0` (`== ToInt32(undefined)`, the only observable value in that
context), and every rejected shape (view/detached/resizable backing, wrong
runtime kind) defers to the new `js_typed_array_read_int32` runtime
fallback. Perry already emitted bare loads for typed-array *locals* with
proven bounds (#6750); this extends the recognition to *parameters*, whose
length and storage are unknown at compile time. Plain-value parameter reads
still observe `undefined` out of bounds.
- On a 40M-iteration `Int32Array`-parameter bit-mixer that combines both
primitives, the two fallbacks previously cascaded the whole hot loop into
slow f64 `ToInt32` towers (`js_math_imul` x3, `js_typed_array_get` x3,
~60 `sitofp`/`fptosi`/`select`); both runtime-call families now reach zero
and the read/multiply chain stays in native i32.
302 changes: 273 additions & 29 deletions crates/perry-codegen/src/expr/i32_fast_path.rs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion crates/perry-codegen/src/expr/index_get.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ fn is_uint8array_receiver(ctx: &FnCtx<'_>, object: &Expr) -> bool {
)
}

fn numeric_index_has_integer_array_index_proof(ctx: &FnCtx<'_>, index: &Expr) -> bool {
pub(crate) fn numeric_index_has_integer_array_index_proof(ctx: &FnCtx<'_>, index: &Expr) -> bool {
fn range_is_nonnegative_i32(ctx: &FnCtx<'_>, index: &Expr) -> bool {
int_range_expr(ctx, index)
.is_some_and(|range| range.min >= 0 && range.max <= i32::MAX as i64)
Expand Down
21 changes: 17 additions & 4 deletions crates/perry-codegen/src/expr/math_simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ use crate::type_analysis::{is_definitely_string_expr, is_numeric_expr, map_stati
use crate::types::{DOUBLE, F32, I1, I32, I64};

use super::{
can_lower_expr_as_i32, lower_expr, lower_expr_native, lower_math_operand,
nanbox_pointer_inline, nanbox_string_inline, record_collection_number_key_fallback,
can_lower_expr_as_i32, imul_operand_i32_lowerable_in_current_region, lower_expr,
lower_expr_native, lower_imul_operand_i32, lower_math_operand, nanbox_pointer_inline,
nanbox_string_inline, record_collection_number_key_fallback,
record_collection_number_key_selected, record_collection_string_key_fallback,
record_collection_string_key_selected, record_collection_string_key_value_selected,
record_collection_typed_value_fallback, record_collection_typed_value_selected,
Expand Down Expand Up @@ -416,9 +417,21 @@ pub(crate) fn lower(ctx: &mut FnCtx<'_>, expr: &Expr) -> Result<String> {
}

// -------- Math.imul — 32-bit wrapping integer multiply --------
// Route through the runtime helper so non-finite inputs use JS
// ToInt32 semantics (`NaN`/±Infinity -> 0) instead of LLVM fptosi.
// Lower to a single native `mul i32` when BOTH operands are provably
// in-range i32: multiplication mod 2^32 has identical low 32 bits for
// signed and unsigned operands, so `mul i32(ToInt32(a), ToInt32(b))`
// is exact. Arbitrary operands (`NaN`/±Infinity/fractional/`>2^32`)
// MUST keep the runtime helper — a bare `fptosi` would violate JS
// ToUint32/ToInt32 semantics (`NaN`->0, `Inf`->0, truncation).
Expr::MathImul(a, b) => {
if imul_operand_i32_lowerable_in_current_region(ctx, a)
&& imul_operand_i32_lowerable_in_current_region(ctx, b)
{
let a_i32 = lower_imul_operand_i32(ctx, a)?;
let b_i32 = lower_imul_operand_i32(ctx, b)?;
let r = ctx.block().mul(I32, &a_i32, &b_i32);
return Ok(ctx.block().sitofp(I32, &r, DOUBLE));
}
let av = lower_expr(ctx, a)?;
let bv = lower_expr(ctx, b)?;
Ok(ctx
Expand Down
7 changes: 4 additions & 3 deletions crates/perry-codegen/src/expr/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,10 @@ pub(crate) use helpers::{
unbox_to_i64,
};
pub(crate) use i32_fast_path::{
can_lower_expr_as_i32, can_lower_expr_as_i32_in_current_region, is_known_finite,
lower_expr_as_i32, lower_expr_native, lower_packed_u32_loop_index_get, try_flat_const_2d_int,
try_lower_flat_const_index_get,
can_lower_expr_as_i32, can_lower_expr_as_i32_in_current_region,
imul_operand_i32_lowerable_in_current_region, is_known_finite, lower_expr_as_i32,
lower_expr_native, lower_imul_operand_i32, lower_packed_u32_loop_index_get,
try_flat_const_2d_int, try_lower_flat_const_index_get,
};
pub(crate) use index::lower_index_set_fast;
pub(crate) use nanbox_inline::{
Expand Down
3 changes: 3 additions & 0 deletions crates/perry-codegen/src/runtime_decls/strings_part2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,9 @@ pub(crate) fn declare_phase_b_strings_part2(module: &mut LlModule) {
module.declare_function("js_typed_array_view", I64, &[I32, DOUBLE, DOUBLE, DOUBLE]);
module.declare_function("js_typed_array_length", I32, &[I64]);
module.declare_function("js_typed_array_get", DOUBLE, &[I64, I32]);
// Cold fallback for the inline checked-i32 typed-array element read
// (returns ToInt32 of the element, or 0 for OOB / view / wrong-kind).
module.declare_function("js_typed_array_read_int32", I32, &[I64, I32]);
// #2063: string / dynamic-key `ta[key]` [[Get]] dispatcher (canonical
// numeric index → element, else ordinary named-property [[Get]]).
module.declare_function("js_typed_array_index_get_dynamic", DOUBLE, &[I64, DOUBLE]);
Expand Down
48 changes: 48 additions & 0 deletions crates/perry-runtime/src/typedarray/access.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,54 @@ pub extern "C" fn js_typed_array_get(ta: *const TypedArrayHeader, index: i32) ->
}
}

/// Cold fallback for the codegen inline **checked i32** typed-array element read
/// (integer-kind receivers reached through an erased / typed parameter — e.g.
/// `function f(S: Int32Array){ return S[i] | 0 }`). The inline path serves the
/// overwhelmingly common inline-storage, correct-kind, in-bounds case with a
/// bare native load, and yields `0` directly for a genuine in-kind out-of-bounds
/// read (`== ToInt32(undefined)`, the only observable value in the i32/ToInt32
/// consumer context that path serves). It routes here only when its guard
/// rejects the access — a view/detached/resizable backing
/// (`PERRY_TA_VIEW_GUARD != 0`), a kind-cache miss, or a receiver that is not the
/// statically-expected kind. This helper performs the full ECMAScript
/// IntegerIndexedExotic `[[Get]]` (bounds-checked, view-aware, detach-safe) and
/// applies `ToInt32` to the result (`undefined` / non-finite -> `0`). Because it
/// is only ever consumed where the surrounding expression `ToInt32`s the value,
/// returning the i32 directly is exact.
#[no_mangle]
pub extern "C" fn js_typed_array_read_int32(ta: *const TypedArrayHeader, index: i32) -> i32 {
// Memory safety: this cold fallback is entered on a kind-cache miss / wrong
// runtime kind, which INCLUDES a receiver that is not actually a typed array
// — TS types are erased, so `function f(S: Int32Array){ S[i] }` compiles the
// statically-emitted checked path but may be called with an arbitrary value.
// `js_typed_array_get` would read `(*ta).length` (a `TypedArrayHeader` field)
// before classifying the pointer, type-confusing the first GC-header read.
// Validate the raw pointer is a registered typed array first (the same gate
// `strict_typed_array_from_raw` uses — it covers native/inline views); a
// non-typed-array receiver has no element to read, and
// `ToInt32(undefined) == 0` in this i32 consumer context.
let ta = clean_ta_ptr(ta);
if ta.is_null() || lookup_typed_array_kind(ta as usize).is_none() {
return 0;
}
let v = js_typed_array_get(ta, index);
// `js_typed_array_get` returns a plain finite f64 element for an in-bounds
// read and TAG_UNDEFINED (a NaN) for OOB. `ToInt32` maps NaN / ±Inf -> 0.
if !v.is_finite() {
return 0;
}
const TWO_32: f64 = 4_294_967_296.0;
(v.trunc().rem_euclid(TWO_32) as u32) as i32
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

// Codegen-only export: the inline checked-i32 read emits the call in
// `perry-codegen/src/expr/i32_fast_path.rs`; a whole-program bitcode link is
// otherwise free to internalize and dead-strip it (it has no internal Rust
// caller). The `#[used]` anchor pins it, mirroring the getter above.
#[used]
static KEEP_JS_TYPED_ARRAY_READ_INT32: extern "C" fn(*const TypedArrayHeader, i32) -> i32 =
js_typed_array_read_int32;

/// #2063 — dynamic / string-key `[[Get]]` on a TypedArray (`ta[key]`).
///
/// The codegen element-read fast path only fires for statically-proven
Expand Down
76 changes: 76 additions & 0 deletions test-files/test_gap_math_imul_native.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Math.imul lowering to a native `mul i32` when both operands are provably
// in-range i32 (perry-codegen expr/math_simple.rs generic arm +
// expr/i32_fast_path.rs i32-native / accumulator path). Multiplication mod 2^32
// has identical low 32 bits for signed and unsigned operands, so the native
// path is exact — but only for provable i32 operands. Non-finite / fractional /
// >2^32 operands MUST keep JS ToUint32/ToInt32 semantics via the runtime
// helper. Every result must match `node --experimental-strip-types` exactly.

// --- Edge cases the native path must NOT take (kept on the runtime helper) ---
console.log(Math.imul(NaN, 5)); // 0 (NaN -> ToInt32 -> 0)
console.log(Math.imul(Infinity, 5)); // 0
console.log(Math.imul(-Infinity, 3)); // 0
console.log(Math.imul(1.9, 2)); // 2 (1.9 -> ToInt32 -> 1)
console.log(Math.imul(2 ** 32 + 3, 1)); // 3 (ToUint32(2^32+3) = 3)

// --- Boundary / >i32::MAX constants the native path handles exactly ---
console.log(Math.imul(0x7fffffff, 2)); // -2 (wraps at i32 boundary)
console.log(Math.imul(0xffffffff, 5)); // -5 (0xffffffff -> -1 as i32)
console.log(Math.imul(-5, -3)); // 15
console.log(Math.imul(0x9e3779b1, 3)); // multiplier > i32::MAX
console.log(Math.imul(0x9e3779b1 | 0, 0x85ebca6b | 0));

// --- Nested native imul (result of imul is itself a provable i32) ---
console.log(Math.imul(Math.imul(3, 7), 5)); // 105

// --- Variable i32 operands ---
let p = 123456789 | 0;
let q = -987654321 | 0;
console.log(Math.imul(p, q));

// --- The i32-accumulator chain: `a = Math.imul(a, K)` on a local with an i32
// slot, whose constant K exceeds i32::MAX — the exact shape that failed to
// lower before the Integer-gate fix (0x9e3779b1 = 2654435761 > i32::MAX). ---
function mix(x: number): number {
let a = x | 0;
a = Math.imul(a, 0x9e3779b1);
a = (a ^ (a >>> 15)) | 0;
a = Math.imul(a, 0x85ebca6b);
a = (a ^ (a >>> 13)) | 0;
a = Math.imul(a, 0xc2b2ae35);
a = (a ^ (a >>> 16)) | 0;
return a | 0;
}
let acc = 0 | 0;
for (let i = 0; i < 5000; i++) acc = (acc ^ mix(acc ^ i)) | 0;
console.log(acc);

// --- imul feeding `| 0` and arithmetic, in a tight loop (hash-like) ---
function fnv1aish(seed: number): number {
let h = seed | 0;
for (let i = 0; i < 32; i++) {
h = (h ^ i) | 0;
h = Math.imul(h, 0x01000193); // 16777619, a prime > i16 but < i32
}
return h | 0;
}
console.log(fnv1aish(0x811c9dc5 | 0));
console.log(fnv1aish(1), fnv1aish(-1), fnv1aish(0));

// --- Scoping guard: the 32-bit-literal relaxation is confined to Math.imul.
// A plain `*` computes its product in f64 (precision loss above 2^53), so
// `x * BIGLIT | 0` must NOT be lowered to an exact `mul i32` — it must stay
// `ToInt32(f64_product)`, matching Node. `+`/`-`/bitwise with a >i32::MAX
// literal stay f64-exact too. ---
let g = 5 | 0;
g = (g + 3000000000) | 0;
console.log(g); // Add: sum < 2^53, exact
g = (g * 2654435761) | 0;
console.log(g); // Mul: product > 2^53 -> f64 rounding, NOT exact mul i32
g = (g ^ 0x9e3779b1) | 0;
console.log(g); // bitwise with >i32::MAX literal
console.log((123456789 * 2654435761) | 0); // large product | 0
console.log((0xffffffff * 0xffffffff) | 0); // 2^64-ish product | 0
console.log((2000000000 * 2000000000) | 0); // two large i32 values
console.log((1000003 * 1000033) | 0); // product < 2^53 (exact either way)

153 changes: 153 additions & 0 deletions test-files/test_gap_typedarray_param_read.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
// Reading a typed-array element through a *parameter* (erased length / storage).
// perry-codegen expr/i32_fast_path.rs lowers an i32/ToInt32-context read of a
// typed-array PARAM to a checked inline native load (runtime guard: pointer +
// inline-storage PERRY_TA_VIEW_GUARD + kind-cache; header-length bounds check;
// bare load; 0 on in-kind OOB == ToInt32(undefined); slow fallback
// js_typed_array_read_int32 for view/detached/wrong-kind). A plain-value read
// still observes `undefined` OOB. Every line must match
// `node --experimental-strip-types` exactly.

// ---- i32-context (bitwise) reads, one per integer kind, in a loop ----
function xorI32(S: Int32Array, n: number): number {
let a = 0 | 0;
for (let i = 0; i < n; i++) a = (a ^ S[i & 7]) | 0;
return a | 0;
}
function xorI8(S: Int8Array, n: number): number {
let a = 0 | 0;
for (let i = 0; i < n; i++) a = (a ^ S[i & 7]) | 0;
return a | 0;
}
function xorU8(S: Uint8Array, n: number): number {
let a = 0 | 0;
for (let i = 0; i < n; i++) a = (a ^ S[i & 7]) | 0;
return a | 0;
}
function xorU8C(S: Uint8ClampedArray, n: number): number {
let a = 0 | 0;
for (let i = 0; i < n; i++) a = (a ^ S[i & 7]) | 0;
return a | 0;
}
function xorI16(S: Int16Array, n: number): number {
let a = 0 | 0;
for (let i = 0; i < n; i++) a = (a ^ S[i & 7]) | 0;
return a | 0;
}
function xorU16(S: Uint16Array, n: number): number {
let a = 0 | 0;
for (let i = 0; i < n; i++) a = (a ^ S[i & 7]) | 0;
return a | 0;
}
function xorU32(S: Uint32Array, n: number): number {
let a = 0 | 0;
for (let i = 0; i < n; i++) a = (a ^ S[i & 7]) | 0;
return a | 0;
}

const i32 = Int32Array.from([-5, 100000, -2000000000, 7, 0x7fffffff, -1, 42, 999]);
const i8 = Int8Array.from([-5, 100, -128, 7, 127, -1, 42, 99]);
const u8 = Uint8Array.from([1, 200, 255, 7, 128, 0, 42, 99]);
const u8c = Uint8ClampedArray.from([1, 200, 255, 7, 128, 0, 42, 99]);
const i16 = Int16Array.from([-5, 30000, -32768, 7, 32767, -1, 42, 999]);
const u16 = Uint16Array.from([1, 60000, 65535, 7, 32768, 0, 42, 999]);
const u32 = Uint32Array.from([1, 4000000000, 0xffffffff, 7, 0x80000000, 0, 42, 999]);

console.log("i32", xorI32(i32, 8));
console.log("i8", xorI8(i8, 8));
console.log("u8", xorU8(u8, 8));
console.log("u8c", xorU8C(u8c, 8));
console.log("i16", xorI16(i16, 8));
console.log("u16", xorU16(u16, 8));
console.log("u32", xorU32(u32, 8));

// ---- OOB in i32-context: reads past length contribute 0 (ToInt32(undefined)) ----
function xorOob(S: Int32Array): number {
let a = 12345 | 0;
for (let i = 0; i < 16; i++) a = (a ^ S[i]) | 0; // i = 8..15 are OOB
return a | 0;
}
console.log("oob", xorOob(i32));

// A negative & fractional index in i32-context also read as 0.
function readMasked(S: Int32Array, i: number): number {
return (99 ^ S[i]) | 0;
}
console.log("neg", readMasked(i32, -1)); // S[-1] -> undefined -> 0 -> 99 ^ 0
console.log("frac", readMasked(i32, 3.9)); // fractional -> undefined -> 0
console.log("in", readMasked(i32, 3)); // in-bounds element 7

// ---- plain-value reads: OOB / negative / fractional must be `undefined` ----
function readAt(S: Int32Array, i: number): number | undefined {
return S[i];
}
console.log("v0", readAt(i32, 0), "v7", readAt(i32, 7));
console.log("voob", readAt(i32, 8)); // undefined
console.log("vneg", readAt(i32, -1)); // undefined
console.log("vfrac", readAt(i32, 1.5)); // undefined
console.log("vstr", String(readAt(i32, 8))); // "undefined"
console.log("veq", readAt(i32, 8) === undefined); // true

// ---- Float64Array param (element width != 4) ----
function sumF64(S: Float64Array, n: number): number {
let s = 0;
for (let i = 0; i < n; i++) s += S[i];
return s;
}
function readF64(S: Float64Array, i: number): number | undefined {
return S[i];
}
function truncF64(S: Float64Array, i: number): number {
return S[i] | 0; // i32-context: float -> ToInt32
}
const f64 = Float64Array.from([1.5, 2.25, -3.75, 100.125, 1e12 + 0.5]);
console.log("f64sum", sumF64(f64, 5));
console.log("f64read", readF64(f64, 1), readF64(f64, 10));
console.log("f64trunc", truncF64(f64, 0), truncF64(f64, 2), truncF64(f64, 4), truncF64(f64, 99));

// ---- Float32Array param (width 4, but float kind — stays on runtime read) ----
function readF32(S: Float32Array, i: number): number | undefined {
return S[i];
}
const f32 = Float32Array.from([0.5, -1.5, 2.5]);
console.log("f32", readF32(f32, 0), readF32(f32, 2), readF32(f32, 9));

// ---- view over an ArrayBuffer (non-inline storage -> slow fallback path) ----
function viewXor(S: Int32Array, n: number): number {
let a = 0 | 0;
for (let i = 0; i < n; i++) a = (a ^ S[i]) | 0;
return a | 0;
}
function viewRead(S: Int32Array, i: number): number | undefined {
return S[i];
}
const ab = new ArrayBuffer(16);
const view = new Int32Array(ab);
view[0] = 111;
view[1] = -222;
view[2] = 333;
view[3] = -444;
console.log("view", viewXor(view, 4), viewRead(view, 1), viewRead(view, 8));

// ---- detached buffer: reads are undefined (plain) / 0 (i32-context) ----
const ab2 = new ArrayBuffer(16);
const det = new Int32Array(ab2);
det[0] = 7;
det[1] = 9;
console.log("predetach", viewRead(det, 0), viewXor(det, 4));
ab2.transfer(); // detach ab2 (and its view `det`)
console.log("postdetach-plain", viewRead(det, 0)); // undefined
console.log("postdetach-i32", viewXor(det, 4)); // 0 (all OOB after detach)

// ---- fractional index in i32 context must NOT take the checked native path ----
// (regression: the fast path lowers the index via ToInt32, so `S[3.9]` would
// read element 3; JS reads a fractional typed-array index as undefined -> 0.)
function fracI32(S: Int32Array): number {
return S[3.9] | 0;
}
function fracVar(S: Int32Array, i: number): number {
return S[i] | 0;
}
const fr = new Int32Array([10, 20, 30, 40, 50]);
console.log("frac-lit", fracI32(fr)); // 0 (not 40)
console.log("frac-var", fracVar(fr, 2.5)); // 0 (not 30)
console.log("int-var", fracVar(fr, 3)); // 40 (integer var still fast+correct)
Loading