From 8372475b6a6b4f5f2be32206428cb2154eab3cdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Vouillon?= Date: Wed, 25 Nov 2026 09:32:29 +0100 Subject: [PATCH 1/2] Initialize each `VMFuncRef` once in the module startup function In the module startup function, each `ref.func` of a defined function writes the four fields of the function's `VMFuncRef`. Modules produced by wasm_of_ocaml reference the same functions from many global initializers. When calls separate these references, as the slow paths of GC allocations do, the same fields are written again for each reference. The optimizer also merges the repeated `func_addr` instructions, so the address of each of these functions stays live from its first `ref.func` to its last. In the startup function of one such module (a wasm_of_ocaml build of herd, with 24,560 globals), 287 function addresses were live across most of the function's 125,000 blocks. Register allocation then split 572 values at boundaries between hot and cold blocks. Now the startup function begins by initializing, once, the `VMFuncRef` of each defined function referenced by `ref.func` in a global initializer, an element segment or a table initializer. A `ref.func` of one of these functions then only computes the address of its `VMFuncRef`. Any other `ref.func` still initializes the `VMFuncRef` itself, as before. For herd, compiling the startup function now uses 2.2 GiB instead of 4.9 GiB, and compiling the whole module 3.3 GiB instead of 5.9 GiB. These numbers are with the regalloc2 fix from bytecodealliance/regalloc2#285; without it, the module does not compile within 12 GB. --- crates/cranelift/src/func_environ.rs | 76 +++++++++++++++++ tests/disas/elem-segment.wat | 44 +++++----- tests/disas/startup-ref-func-once.wat | 83 +++++++++++++++++++ .../startup-ref-func-shared.wast | 41 +++++++++ 4 files changed, 220 insertions(+), 24 deletions(-) create mode 100644 tests/disas/startup-ref-func-once.wat create mode 100644 tests/misc_testsuite/startup-ref-func-shared.wast diff --git a/crates/cranelift/src/func_environ.rs b/crates/cranelift/src/func_environ.rs index f5b12101899e..b2eca798c6a4 100644 --- a/crates/cranelift/src/func_environ.rs +++ b/crates/cranelift/src/func_environ.rs @@ -196,6 +196,10 @@ pub struct FuncEnvironment<'module_environment> { translation: &'module_environment ModuleTranslation<'module_environment>, + /// Defined functions whose `VMFuncRef` is initialized at the start of the + /// module startup function. Empty when compiling any other function. + func_refs_initialized_up_front: std::collections::BTreeSet, + /// Heaps implementing WebAssembly linear memories. heaps: PrimaryMap, @@ -318,6 +322,7 @@ impl<'module_environment> FuncEnvironment<'module_environment> { offsets, tunables, fuel_var: Variable::reserved_value(), + func_refs_initialized_up_front: Default::default(), epoch_deadline_var: Variable::reserved_value(), epoch_ptr_var: Variable::reserved_value(), @@ -3751,6 +3756,15 @@ impl FuncEnvironment<'_> { let func = &self.module.functions[func_index]; assert!(func.is_escaping()); let func_ref_offset = self.offsets.func_refs().at(func.func_ref); + + // If the `VMFuncRef` was initialized at the start of the module startup + // function, only its address is needed. Otherwise, it is initialized + // here; this is also correct in the startup function, only slower. + if self.func_refs_initialized_up_front.contains(&def_index) { + let vmctx = self.vmctx_val(pos); + return pos.ins().iadd_imm_s(vmctx, i64::from(func_ref_offset)); + } + let sig = func.signature.unwrap_module_type_index(); let wasm_func = self.get_or_create_defined_func_ref(pos.func, def_index); @@ -6490,6 +6504,7 @@ impl FuncEnvironment<'_> { /// module itself starts executing. This will, for example, execute all /// constant expressions for global initializers. pub fn translate_module_startup(&mut self, builder: &mut FunctionBuilder) -> WasmResult<()> { + self.initialize_func_refs_up_front(builder); for (i, expr) in self.translation.global_initializers.iter() { self.module_initialize_global(builder, *i, expr)?; } @@ -6521,6 +6536,67 @@ impl FuncEnvironment<'_> { Ok(()) } + /// Initializes, at the start of the module startup function, the + /// `VMFuncRef` of each defined function referenced by `ref.func` in a + /// global initializer, an element segment or a table initializer. + /// + /// Without this, each `ref.func` would initialize the `VMFuncRef` again, + /// and modules that reference the same functions from many constant + /// expressions would write the same fields many times. + fn initialize_func_refs_up_front(&mut self, builder: &mut FunctionBuilder) { + use std::collections::BTreeSet; + + fn add_expr(funcs: &mut BTreeSet, expr: &ConstExpr) { + for op in expr.ops() { + if let ConstOp::RefFunc(f) = op { + funcs.insert(*f); + } + } + } + fn add_elements(funcs: &mut BTreeSet, elements: &TableSegmentElements) { + match elements { + TableSegmentElements::Functions(indices) => { + // These segments are not expected to contain null + // elements (the reserved value), but skip them anyway. + funcs.extend(indices.iter().filter(|f| !f.is_reserved_value())); + } + TableSegmentElements::Expressions { exprs, .. } => { + for expr in exprs.iter() { + add_expr(funcs, expr); + } + } + } + } + + let translation = self.translation; + let mut funcs = BTreeSet::new(); + for (_, expr) in translation.global_initializers.iter() { + add_expr(&mut funcs, expr); + } + for (_, elements) in translation.passive_elements.iter() { + add_elements(&mut funcs, elements); + } + for (_, init) in translation.table_initialization.initial_values.iter() { + if let TableInitialValue::Expr(expr) = init { + add_expr(&mut funcs, expr); + } + } + for segment in translation.table_initialization.segments.iter() { + // The elements of staged segments are in `passive_elements`. + if let TableSegmentInit::Direct(elements) = &segment.init { + add_elements(&mut funcs, elements); + } + } + + for def_index in funcs + .into_iter() + .filter_map(|f| self.module.defined_func_index(f)) + { + self.translate_ref_defined_func(&mut builder.cursor(), def_index); + self.func_refs_initialized_up_front.insert(def_index); + } + } + /// Initializes all "complicated" globals in a module. /// /// This will translate the given constant expression and then initialize diff --git a/tests/disas/elem-segment.wat b/tests/disas/elem-segment.wat index 9e534c483ea6..dc77551f5cb5 100644 --- a/tests/disas/elem-segment.wat +++ b/tests/disas/elem-segment.wat @@ -54,32 +54,28 @@ ;; region4 = 100 "" ;; region5 = 160 "" ;; region6 = 116 "" -;; sig0 = (i64 vmctx, i32) -> i64 tail -;; sig1 = (i64 vmctx, i64) tail -;; sig2 = (i64 vmctx, i64, i64, i64) -> i8 system_v -;; sig3 = (i64 vmctx, i64, i64, i64) -> i8 system_v -;; sig4 = (i64 vmctx, i64, i64, i64) -> i8 system_v -;; fn0 = colocated u805306368:4 sig0 -;; fn1 = colocated u0:0 sig1 -;; fn2 = colocated u268435456:0 sig2 -;; fn3 = colocated u268435456:0 sig3 -;; fn4 = colocated u268435456:0 sig4 +;; sig0 = (i64 vmctx, i64) tail +;; sig1 = (i64 vmctx, i64, i64, i64) -> i8 system_v +;; sig2 = (i64 vmctx, i32) -> i64 tail +;; fn0 = colocated u0:0 sig0 +;; fn1 = colocated u268435456:0 sig1 +;; fn2 = colocated u805306368:4 sig2 ;; ;; block0(v0: i64, v1: i64): -;; v2 = iconst.i32 0 -;; v3 = call fn0(v0, v2) ; v2 = 0 -;; v8 = iconst.i64 48 -;; v9 = iadd v0, v8 ; v8 = 48 -;; store notrap aligned little region6 v9, v3 -;; store notrap aligned little region6 v9, v3+16 -;; v17 = func_addr.i64 fn4 -;; store notrap aligned region2 v17, v0+48 -;; v4 = func_addr.i64 fn1 -;; store notrap aligned region3 v4, v0+56 +;; v3 = func_addr.i64 fn1 +;; store notrap aligned region2 v3, v0+48 +;; v2 = func_addr.i64 fn0 +;; store notrap aligned region3 v2, v0+56 ;; store notrap aligned region4 v0, v0+72 -;; v6 = load.i64 notrap aligned readonly can_move region0 v0+40 -;; v7 = load.i32 notrap aligned readonly can_move region1 v6 -;; store notrap aligned region5 v7, v0+64 -;; store notrap aligned little region6 v9, v3+32 +;; v4 = load.i64 notrap aligned readonly can_move region0 v0+40 +;; v5 = load.i32 notrap aligned readonly can_move region1 v4 +;; store notrap aligned region5 v5, v0+64 +;; v8 = iconst.i32 0 +;; v9 = call fn2(v0, v8) ; v8 = 0 +;; v6 = iconst.i64 48 +;; v7 = iadd v0, v6 ; v6 = 48 +;; store notrap aligned little region6 v7, v9 +;; store notrap aligned little region6 v7, v9+16 +;; store notrap aligned little region6 v7, v9+32 ;; return ;; } diff --git a/tests/disas/startup-ref-func-once.wat b/tests/disas/startup-ref-func-once.wat new file mode 100644 index 000000000000..eafe863f58c8 --- /dev/null +++ b/tests/disas/startup-ref-func-once.wat @@ -0,0 +1,83 @@ +;;! target = 'x86_64' +;;! test = 'optimize' +;;! filter = 'module_start' + +;; `$f` is referenced by a global initializer and by a passive element +;; segment. Its `VMFuncRef` is written only once, at the start of the module +;; startup function, even though the call that sets up the passive segment +;; separates the two references. + +(module + (func $f) + (global funcref (ref.func $f)) + (elem func $f) +) +;; function u2415919104:1(i64 vmctx, i64, i64, i64) -> i8 system_v { +;; region0 = 123 "" +;; region1 = 243 "" +;; region2 = 72 "" +;; region3 = 231 "" +;; region4 = 112 "" +;; region5 = 34 "" +;; sig0 = (i64 vmctx, i64) tail +;; fn0 = colocated u2415919104:0 sig0 +;; +;; block0(v0: i64, v1: i64, v2: i64, v3: i64): +;; jump block1 +;; +;; block1: +;; v7 = get_frame_pointer.i64 +;; v6 = load.i64 notrap aligned readonly can_move region0 v0+8 +;; store notrap aligned region1 v7, v6+64 +;; v8 = get_stack_pointer.i64 +;; store notrap aligned region2 v8, v6+56 +;; v9 = get_exception_handler_address.i64 block1, 0 +;; store notrap aligned region3 v9, v6+72 +;; try_call fn0(v0, v1), sig0, block2, [ default: block3 ] +;; +;; block2: +;; v14 = iconst.i8 1 +;; return v14 ; v14 = 1 +;; +;; block3: +;; v11 = iconst.i64 1 +;; store notrap aligned region4 v11, v6+128 ; v11 = 1 +;; v4 = iconst.i64 0 +;; store notrap aligned region5 v4, v6+144 ; v4 = 0 +;; v13 = iconst.i8 0 +;; return v13 ; v13 = 0 +;; } +;; +;; function u2415919104:0(i64 vmctx, i64) tail { +;; region0 = 130 "" +;; region1 = 134 "" +;; region2 = 44 "" +;; region3 = 120 "" +;; region4 = 100 "" +;; region5 = 160 "" +;; region6 = 250 "" +;; region7 = 116 "" +;; sig0 = (i64 vmctx, i64) tail +;; sig1 = (i64 vmctx, i64, i64, i64) -> i8 system_v +;; sig2 = (i64 vmctx, i32) -> i64 tail +;; fn0 = colocated u0:0 sig0 +;; fn1 = colocated u268435456:0 sig1 +;; fn2 = colocated u805306368:4 sig2 +;; +;; block0(v0: i64, v1: i64): +;; v3 = func_addr.i64 fn1 +;; store notrap aligned region2 v3, v0+64 +;; v2 = func_addr.i64 fn0 +;; store notrap aligned region3 v2, v0+72 +;; store notrap aligned region4 v0, v0+88 +;; v4 = load.i64 notrap aligned readonly can_move region0 v0+40 +;; v5 = load.i32 notrap aligned readonly can_move region1 v4 +;; store notrap aligned region5 v5, v0+80 +;; v6 = iconst.i64 64 +;; v7 = iadd v0, v6 ; v6 = 64 +;; store notrap aligned region6 v7, v0+48 +;; v10 = iconst.i32 0 +;; v11 = call fn2(v0, v10) ; v10 = 0 +;; store notrap aligned little region7 v7, v11 +;; return +;; } diff --git a/tests/misc_testsuite/startup-ref-func-shared.wast b/tests/misc_testsuite/startup-ref-func-shared.wast new file mode 100644 index 000000000000..06c89d2971f1 --- /dev/null +++ b/tests/misc_testsuite/startup-ref-func-shared.wast @@ -0,0 +1,41 @@ +;;! reference_types = true +;;! bulk_memory = true + +;; Functions referenced several times from global initializers and element +;; segments can be called through each of these references. + +(module + (type $t (func (result i32))) + (func $f (type $t) (i32.const 1)) + (func $g (type $t) (i32.const 2)) + + (global $a funcref (ref.func $f)) + (global $b funcref (ref.func $f)) + (global $c funcref (ref.func $g)) + + (table $tab 6 funcref) + (elem (table $tab) (i32.const 0) func $f $g $f) + (elem $passive funcref (ref.func $g) (ref.func $f)) + + (func $call-at-5 (param funcref) (result i32) + (table.set $tab (i32.const 5) (local.get 0)) + (call_indirect $tab (type $t) (i32.const 5))) + (func (export "call-a") (result i32) (call $call-at-5 (global.get $a))) + (func (export "call-b") (result i32) (call $call-at-5 (global.get $b))) + (func (export "call-c") (result i32) (call $call-at-5 (global.get $c))) + + (func (export "call-table") (param i32) (result i32) + (call_indirect $tab (type $t) (local.get 0))) + (func (export "init-from-passive") + (table.init $tab $passive (i32.const 3) (i32.const 0) (i32.const 2))) +) + +(assert_return (invoke "call-a") (i32.const 1)) +(assert_return (invoke "call-b") (i32.const 1)) +(assert_return (invoke "call-c") (i32.const 2)) +(assert_return (invoke "call-table" (i32.const 0)) (i32.const 1)) +(assert_return (invoke "call-table" (i32.const 1)) (i32.const 2)) +(assert_return (invoke "call-table" (i32.const 2)) (i32.const 1)) +(invoke "init-from-passive") +(assert_return (invoke "call-table" (i32.const 3)) (i32.const 2)) +(assert_return (invoke "call-table" (i32.const 4)) (i32.const 1)) From 3a98586b4ee5eac64a66fca8552d987a7dba26d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=B4me=20Vouillon?= Date: Thu, 26 Nov 2026 10:53:46 +0100 Subject: [PATCH 2/2] Initialize each `VMFuncRef` at its first `ref.func` in the startup function Instead of collecting, before translating the module startup function, the functions referenced by `ref.func` in constant expressions and element segments, initialize the `VMFuncRef` of a function at its first `ref.func` in the startup function, and only compute its address at the later ones. This relies on the startup function evaluating constant expressions in order, never in conditional code, so that the first `ref.func` of a function comes before all the others. --- crates/cranelift/src/func_environ.rs | 82 ++++----------------------- tests/disas/elem-segment.wat | 40 ++++++------- tests/disas/startup-ref-func-once.wat | 12 ++-- 3 files changed, 38 insertions(+), 96 deletions(-) diff --git a/crates/cranelift/src/func_environ.rs b/crates/cranelift/src/func_environ.rs index b2eca798c6a4..33249ea6c906 100644 --- a/crates/cranelift/src/func_environ.rs +++ b/crates/cranelift/src/func_environ.rs @@ -196,9 +196,9 @@ pub struct FuncEnvironment<'module_environment> { translation: &'module_environment ModuleTranslation<'module_environment>, - /// Defined functions whose `VMFuncRef` is initialized at the start of the - /// module startup function. Empty when compiling any other function. - func_refs_initialized_up_front: std::collections::BTreeSet, + /// In the module startup function, the defined functions whose `VMFuncRef` + /// has already been initialized by an earlier `ref.func`. + func_refs_initialized: std::collections::HashSet, /// Heaps implementing WebAssembly linear memories. heaps: PrimaryMap, @@ -322,7 +322,7 @@ impl<'module_environment> FuncEnvironment<'module_environment> { offsets, tunables, fuel_var: Variable::reserved_value(), - func_refs_initialized_up_front: Default::default(), + func_refs_initialized: Default::default(), epoch_deadline_var: Variable::reserved_value(), epoch_ptr_var: Variable::reserved_value(), @@ -3757,10 +3757,14 @@ impl FuncEnvironment<'_> { assert!(func.is_escaping()); let func_ref_offset = self.offsets.func_refs().at(func.func_ref); - // If the `VMFuncRef` was initialized at the start of the module startup - // function, only its address is needed. Otherwise, it is initialized - // here; this is also correct in the startup function, only slower. - if self.func_refs_initialized_up_front.contains(&def_index) { + // In the module startup function, only the first `ref.func` of a + // function initializes its `VMFuncRef`; later ones only need its + // address. This relies on the startup function evaluating constant + // expressions in order, never in conditional code, so that the first + // `ref.func` of a function comes before all the others. + if matches!(self.key, FuncKey::ModuleStartup(..)) + && !self.func_refs_initialized.insert(def_index) + { let vmctx = self.vmctx_val(pos); return pos.ins().iadd_imm_s(vmctx, i64::from(func_ref_offset)); } @@ -6504,7 +6508,6 @@ impl FuncEnvironment<'_> { /// module itself starts executing. This will, for example, execute all /// constant expressions for global initializers. pub fn translate_module_startup(&mut self, builder: &mut FunctionBuilder) -> WasmResult<()> { - self.initialize_func_refs_up_front(builder); for (i, expr) in self.translation.global_initializers.iter() { self.module_initialize_global(builder, *i, expr)?; } @@ -6536,67 +6539,6 @@ impl FuncEnvironment<'_> { Ok(()) } - /// Initializes, at the start of the module startup function, the - /// `VMFuncRef` of each defined function referenced by `ref.func` in a - /// global initializer, an element segment or a table initializer. - /// - /// Without this, each `ref.func` would initialize the `VMFuncRef` again, - /// and modules that reference the same functions from many constant - /// expressions would write the same fields many times. - fn initialize_func_refs_up_front(&mut self, builder: &mut FunctionBuilder) { - use std::collections::BTreeSet; - - fn add_expr(funcs: &mut BTreeSet, expr: &ConstExpr) { - for op in expr.ops() { - if let ConstOp::RefFunc(f) = op { - funcs.insert(*f); - } - } - } - fn add_elements(funcs: &mut BTreeSet, elements: &TableSegmentElements) { - match elements { - TableSegmentElements::Functions(indices) => { - // These segments are not expected to contain null - // elements (the reserved value), but skip them anyway. - funcs.extend(indices.iter().filter(|f| !f.is_reserved_value())); - } - TableSegmentElements::Expressions { exprs, .. } => { - for expr in exprs.iter() { - add_expr(funcs, expr); - } - } - } - } - - let translation = self.translation; - let mut funcs = BTreeSet::new(); - for (_, expr) in translation.global_initializers.iter() { - add_expr(&mut funcs, expr); - } - for (_, elements) in translation.passive_elements.iter() { - add_elements(&mut funcs, elements); - } - for (_, init) in translation.table_initialization.initial_values.iter() { - if let TableInitialValue::Expr(expr) = init { - add_expr(&mut funcs, expr); - } - } - for segment in translation.table_initialization.segments.iter() { - // The elements of staged segments are in `passive_elements`. - if let TableSegmentInit::Direct(elements) = &segment.init { - add_elements(&mut funcs, elements); - } - } - - for def_index in funcs - .into_iter() - .filter_map(|f| self.module.defined_func_index(f)) - { - self.translate_ref_defined_func(&mut builder.cursor(), def_index); - self.func_refs_initialized_up_front.insert(def_index); - } - } - /// Initializes all "complicated" globals in a module. /// /// This will translate the given constant expression and then initialize diff --git a/tests/disas/elem-segment.wat b/tests/disas/elem-segment.wat index dc77551f5cb5..3f9e9fd2a5e2 100644 --- a/tests/disas/elem-segment.wat +++ b/tests/disas/elem-segment.wat @@ -54,28 +54,28 @@ ;; region4 = 100 "" ;; region5 = 160 "" ;; region6 = 116 "" -;; sig0 = (i64 vmctx, i64) tail -;; sig1 = (i64 vmctx, i64, i64, i64) -> i8 system_v -;; sig2 = (i64 vmctx, i32) -> i64 tail -;; fn0 = colocated u0:0 sig0 -;; fn1 = colocated u268435456:0 sig1 -;; fn2 = colocated u805306368:4 sig2 +;; sig0 = (i64 vmctx, i32) -> i64 tail +;; sig1 = (i64 vmctx, i64) tail +;; sig2 = (i64 vmctx, i64, i64, i64) -> i8 system_v +;; fn0 = colocated u805306368:4 sig0 +;; fn1 = colocated u0:0 sig1 +;; fn2 = colocated u268435456:0 sig2 ;; ;; block0(v0: i64, v1: i64): -;; v3 = func_addr.i64 fn1 -;; store notrap aligned region2 v3, v0+48 -;; v2 = func_addr.i64 fn0 -;; store notrap aligned region3 v2, v0+56 +;; v2 = iconst.i32 0 +;; v3 = call fn0(v0, v2) ; v2 = 0 +;; v5 = func_addr.i64 fn2 +;; store notrap aligned region2 v5, v0+48 +;; v4 = func_addr.i64 fn1 +;; store notrap aligned region3 v4, v0+56 ;; store notrap aligned region4 v0, v0+72 -;; v4 = load.i64 notrap aligned readonly can_move region0 v0+40 -;; v5 = load.i32 notrap aligned readonly can_move region1 v4 -;; store notrap aligned region5 v5, v0+64 -;; v8 = iconst.i32 0 -;; v9 = call fn2(v0, v8) ; v8 = 0 -;; v6 = iconst.i64 48 -;; v7 = iadd v0, v6 ; v6 = 48 -;; store notrap aligned little region6 v7, v9 -;; store notrap aligned little region6 v7, v9+16 -;; store notrap aligned little region6 v7, v9+32 +;; v6 = load.i64 notrap aligned readonly can_move region0 v0+40 +;; v7 = load.i32 notrap aligned readonly can_move region1 v6 +;; store notrap aligned region5 v7, v0+64 +;; v8 = iconst.i64 48 +;; v9 = iadd v0, v8 ; v8 = 48 +;; store notrap aligned little region6 v9, v3 +;; store notrap aligned little region6 v9, v3+16 +;; store notrap aligned little region6 v9, v3+32 ;; return ;; } diff --git a/tests/disas/startup-ref-func-once.wat b/tests/disas/startup-ref-func-once.wat index eafe863f58c8..de5b2a4493cd 100644 --- a/tests/disas/startup-ref-func-once.wat +++ b/tests/disas/startup-ref-func-once.wat @@ -3,9 +3,9 @@ ;;! filter = 'module_start' ;; `$f` is referenced by a global initializer and by a passive element -;; segment. Its `VMFuncRef` is written only once, at the start of the module -;; startup function, even though the call that sets up the passive segment -;; separates the two references. +;; segment. Its `VMFuncRef` is written only once, by the first reference, even +;; though the call that sets up the passive segment separates the two +;; references. (module (func $f) @@ -76,8 +76,8 @@ ;; v6 = iconst.i64 64 ;; v7 = iadd v0, v6 ; v6 = 64 ;; store notrap aligned region6 v7, v0+48 -;; v10 = iconst.i32 0 -;; v11 = call fn2(v0, v10) ; v10 = 0 -;; store notrap aligned little region7 v7, v11 +;; v8 = iconst.i32 0 +;; v9 = call fn2(v0, v8) ; v8 = 0 +;; store notrap aligned little region7 v7, v9 ;; return ;; }