From 5d7848ec26190e697adb7b7838fa8c1afbeb2a00 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 28 Nov 2026 21:19:04 +0900 Subject: [PATCH] perf(sv): lower the state modules of packages in parallel The state modules of the packages are lowered on up to `compile_workers` threads (`ParallelScheduleOptions`), the largest first, and what they give is passed on in their order as before, so the result is the same for every thread count. A UVM design has one per package, each with thousands of subroutines. The count comes from the new `compile_threads` option (`SimulatorBuilder::compile_threads`, NAPI/TS `compileThreads`, `celox run --compile-threads`), which defaults to the available parallelism and is not the simulation `threads`. It is one budget for compiling: native code generation takes its workers within it too (`compile_resources`, the lane kernels), still at most four and as its memory budget allows. One thread compiles everything on the calling thread. `opt_level`, `optimize` and `optimize_options` keep a count set before them, as they keep the lanes. A test lowers six packages and four module specializations at 1, 2, 4 and 16 threads and compares the SIR, the warnings and the recursion report. AVIP axi4_base_test (nocb copy, heliodor-dev, 16 cores, quiet lock), this commit alone at 16 threads: the `packages` phase 10.9 s -> 4.4 s, wall 1:22.9 -> 1:17.0. With the next commit, master -> tip, two runs each: - wall 1:24.6 / 1:24.1 -> 1:13.3 / 1:13.0 (-13%) - `packages` 11.8 / 11.8 s -> 4.2 / 4.5 s; `specialize_modules` 6.1 / 5.7 s -> 2.4 / 2.6 s; sv_frontend 63.7 / 63.3 s -> 53.1 / 53.7 s - CPU 129.5 / 128.4 s -> 137.2 / 137.0 s; instructions:u 988.7 / 992.4 G -> 1009.1 / 1018.4 G - peak RSS 10.90 / 10.96 GB -> 10.93 / 11.03 GB; 10.73 GB at 4 threads, 10.96 GB at 8, 9.05 GB at 1 (native code generation on one worker) - stdout identical to master at 1, 4, 8 and 16 threads Gates (heliodor-dev, master ee408c1950 -> the stack tip at the default 16 compile threads): - the UVM cases give output identical to master: 18.10 instructions:u 182.2 -> 182.6 G, 16.10 245.4 -> 247.1 G, uvm_scoreboard_env 287.2 -> 289.0 G; the 16.9 elaboration exits 0 (183.8 -> 185.5 G); - VeeR-EL2: compile 91.7 / 92.5 s -> 89.3 / 89.5 s; instructions:u 1197.11 / 1197.04 G -> 1198.64 / 1198.64 G (+0.13%, the thread overhead: 1197.02 G with --compile-threads 1). Its simulation executes 12740.84 M -> 12741.64 M instructions (+0.006%) at 1 and at 16 threads alike, from the first commit of the stack on, which only moves the task runner between crates: the layout of the host binary, not the generated code. Change-Id: I3c8a40603fbb829a8fcc81728424963c925d0efa --- .../src/symbolic/parallel.rs | 6 ++ .../src/lowering/external_hierarchy.rs | 2 + .../src/lowering/packages.rs | 99 ++++++++++++++++++- .../src/lowering/schedule.rs | 1 + crates/celox-napi/src/options.rs | 13 +++ crates/celox-napi/src/tests.rs | 2 + crates/celox-sir-opt/src/policy.rs | 32 ++++++ .../backend/native/backend/compile_program.rs | 5 + .../backend/native/backend/lazy_functions.rs | 1 + .../src/backend/native/compile_resources.rs | 27 +++-- crates/celox/src/backend/native/lanes.rs | 53 +++++----- crates/celox/src/bin/celox.rs | 4 + crates/celox/src/bin/celox/runner.rs | 11 +++ crates/celox/src/optimizer.rs | 1 + crates/celox/src/simulator/builder/host.rs | 26 +++++ docs/guide/parallel-simulation.md | 23 +++++ docs/ja/guide/parallel-simulation.md | 23 +++++ packages/celox/src/napi-helpers.ts | 5 + packages/celox/src/types.ts | 7 ++ 19 files changed, 305 insertions(+), 36 deletions(-) diff --git a/crates/celox-frontend-core/src/symbolic/parallel.rs b/crates/celox-frontend-core/src/symbolic/parallel.rs index 5949b85da2f..41ecc890a01 100644 --- a/crates/celox-frontend-core/src/symbolic/parallel.rs +++ b/crates/celox-frontend-core/src/symbolic/parallel.rs @@ -39,6 +39,11 @@ pub struct ParallelScheduleOptions { /// value between paths leave the program (`celox_slt::net_inline`). /// [`DeadStorePolicy::Off`] keeps every net. pub unobserved_nets: DeadStorePolicy, + /// The threads the frontend may lower independent modules on, at least + /// one: one lowers them in order on the calling thread. They are not + /// simulation lanes; what the frontend makes is the same for every + /// count. + pub compile_workers: usize, } /// Whether a settle is partitioned ([`ParallelScheduleOptions::settle`]). @@ -62,6 +67,7 @@ impl ParallelScheduleOptions { settle: SettlePartitionMode::Off, settle_profile: false, unobserved_nets: DeadStorePolicy::Off, + compile_workers: 1, }; /// Request `lanes` simulation lanes with the default cost model. diff --git a/crates/celox-frontend-sv/src/lowering/external_hierarchy.rs b/crates/celox-frontend-sv/src/lowering/external_hierarchy.rs index a1048539374..f6d355980e4 100644 --- a/crates/celox-frontend-sv/src/lowering/external_hierarchy.rs +++ b/crates/celox-frontend-sv/src/lowering/external_hierarchy.rs @@ -642,6 +642,8 @@ fn prepare_external_hierarchy_collecting( time_format, &expansion, ), + // A mixed-language hierarchy is lowered on the calling thread. + 1, module_ids.len(), four_state, false, diff --git a/crates/celox-frontend-sv/src/lowering/packages.rs b/crates/celox-frontend-sv/src/lowering/packages.rs index 820728b6245..7e73aa7a139 100644 --- a/crates/celox-frontend-sv/src/lowering/packages.rs +++ b/crates/celox-frontend-sv/src/lowering/packages.rs @@ -100,8 +100,12 @@ struct PackageLowering { lowered: Result<(String, ModuleId, LoweredSvModule), sv::AnalyzerError>, } +/// Each state module is lowered on its own, on up to `workers` threads, the +/// largest first. +#[allow(clippy::too_many_arguments)] pub(super) fn lower_package_states( states: PackageStates, + workers: usize, first: usize, four_state: bool, ff_parts: bool, @@ -116,12 +120,14 @@ pub(super) fn lower_package_states( } = states; // Each module is lowered on its own; what they give is passed on in // their order, up to the first that fails, as lowering them one after - // another would. - let order = (0..states.len()).collect::>(); + // another would. The largest start first: a package of a class library + // such as UVM carries thousands of subroutines. + let mut order = (0..states.len()).collect::>(); + order.sort_by_key(|&index| std::cmp::Reverse(states[index].0.subroutines().len())); let lowerings = celox_frontend_core::tasks::run_owned::<_, _, std::convert::Infallible>( states, &order, - 1, + workers, |index, (module, time_scale)| { let mut warnings = Vec::new(); let mut report = None; @@ -337,3 +343,90 @@ pub(super) fn bind_package_variables<'a>( } Ok(()) } + +#[cfg(test)] +mod tests { + use super::super::{FrontendTraceOptions, schedule_sources_with_options, sv}; + use std::sync::Arc; + + /// The SIR, or the error, and the warnings and recursion report lines of + /// scheduling `source` with `workers` compile threads. + fn schedule(source: &str, workers: usize, name: &str) -> (String, String, String) { + let report = std::env::temp_dir().join(format!( + "celox-package-states-{}-{name}-{workers}.txt", + std::process::id() + )); + let _ = std::fs::remove_file(&report); + let mut warnings = Vec::new(); + let scheduled = schedule_sources_with_options( + &[(source, std::path::Path::new("packages.sv"))], + "Top", + &[], + &[], + &[], + false, + &celox_frontend_core::ParallelScheduleOptions { + compile_workers: workers, + ..Default::default() + }, + &FrontendTraceOptions::default(), + None, + &mut warnings, + sv::AnalysisOptions { + recursion_report: Some(Arc::from(report.as_path())), + ..sv::AnalysisOptions::default() + }, + ); + let result = match scheduled { + Ok(output) => format!("{:?}", output.scheduled.sir), + Err(error) => format!("error {error:?}"), + }; + let lines = std::fs::read_to_string(&report).unwrap_or_default(); + let _ = std::fs::remove_file(&report); + (result, format!("{warnings:?}"), lines) + } + + /// Lowering the state modules of the packages on several threads makes + /// what lowering them one after another makes: the same SIR, warnings + /// and recursion report. + #[test] + fn package_states_lower_alike_on_any_number_of_threads() { + let packages = (0..6) + .map(|index| { + format!( + "package p{index}; + int counter = {index}; + class C{index}; + static int made = 0; + function new(); made = made + 1; endfunction + virtual function int value(int n); + if (n > 0) return value(n - 1) + {index}; + return counter; + endfunction + endclass + C{index} first = new(); + int start = first.value(2); + endpackage + " + ) + }) + .collect::(); + let source = format!( + "{packages} + module Top(output int sum); + assign sum = p0::start + p1::start + p2::start + p3::start + + p4::start + p5::start; + endmodule" + ); + let sequential = schedule(&source, 1, "ok"); + assert!(!sequential.0.starts_with("error "), "{}", sequential.0); + assert!(!sequential.2.is_empty(), "no recursion report"); + for workers in [2, 4, 16] { + assert_eq!( + schedule(&source, workers, "ok"), + sequential, + "{workers} threads" + ); + } + } +} diff --git a/crates/celox-frontend-sv/src/lowering/schedule.rs b/crates/celox-frontend-sv/src/lowering/schedule.rs index ced51dacbad..31b3da2d925 100644 --- a/crates/celox-frontend-sv/src/lowering/schedule.rs +++ b/crates/celox-frontend-sv/src/lowering/schedule.rs @@ -1227,6 +1227,7 @@ fn schedule_sources_collecting( } let package_states = lower_package_states( package_states, + parallel.compile_workers, module_ids.len(), four_state, parallel.enabled(), diff --git a/crates/celox-napi/src/options.rs b/crates/celox-napi/src/options.rs index afe1e3ece81..db67d95835f 100644 --- a/crates/celox-napi/src/options.rs +++ b/crates/celox-napi/src/options.rs @@ -109,6 +109,9 @@ pub struct NapiOptions { pub dead_store_policy: Option, /// Simulation threads, including the calling thread. Default: 1. pub threads: Option, + /// Compile threads (see `SimulatorBuilder::compile_threads`). Default: + /// the available parallelism of the host. + pub compile_threads: Option, /// Tiered handles compile hot execution groups incrementally (hotspot /// JIT). Default: true; `false` selects whole-image tiered compilation. pub hotspot_jit: Option, @@ -458,6 +461,16 @@ pub(super) fn parse_options(options: &Option) -> Result, max_native_memory_width: usize, parallel_lanes: u32, + /// See [`Self::compile_threads`]; `None` takes the available + /// parallelism. + compile_threads: Option, parallel_partition: ParallelPartition, settle_partition: SettlePartition, settle_profile: bool, @@ -241,6 +244,7 @@ impl OptimizeOptions { 64 }, parallel_lanes: 1, + compile_threads: None, parallel_partition: ParallelPartition::Estimated, settle_partition: SettlePartition::Estimated, settle_profile: false, @@ -309,6 +313,34 @@ impl OptimizeOptions { self.parallel_lanes.max(1) } + /// Compile with at most `threads` threads (at least one): the frontend + /// lowers independent modules on them, and native code generation + /// compiles independent units on as many of them as its memory budget + /// allows. One compiles everything on the calling thread. They are not + /// simulation lanes (see [`Self::set_parallel_lanes`]); the result is the + /// same for every count. The default is the available parallelism of + /// the host. + pub fn with_compile_threads(mut self, threads: usize) -> Self { + self.set_compile_threads(threads); + self + } + + pub fn set_compile_threads(&mut self, threads: usize) { + self.compile_threads = Some(threads.max(1)); + } + + /// The compile threads set with [`Self::with_compile_threads`], if any. + pub fn requested_compile_threads(&self) -> Option { + self.compile_threads + } + + /// The threads compiling may use (see [`Self::with_compile_threads`]). + pub fn compile_threads(&self) -> usize { + self.compile_threads.unwrap_or_else(|| { + std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get) + }) + } + pub fn with_parallel_partition(mut self, partition: ParallelPartition) -> Self { self.parallel_partition = partition; self diff --git a/crates/celox/src/backend/native/backend/compile_program.rs b/crates/celox/src/backend/native/backend/compile_program.rs index 60c3fb74ef9..fa1430ea707 100644 --- a/crates/celox/src/backend/native/backend/compile_program.rs +++ b/crates/celox/src/backend/native/backend/compile_program.rs @@ -307,6 +307,7 @@ pub(super) fn compile_program_with_outlining_threshold( 0 }); let workers = super::super::compile_resources::workers_with_primary( + options.optimize_options.compile_threads(), comb_size, (pool_blocks, pool_instructions), compile_tasks.len() + pooled, @@ -534,6 +535,7 @@ fn compile_scheduler_callees( let max_blocks = sizes.iter().map(|size| size.0).max().unwrap_or(0); let max_instructions = sizes.iter().map(|size| size.1).max().unwrap_or(0); let workers = super::super::compile_resources::workers_with_state( + options.optimize_options.compile_threads(), max_blocks, max_instructions, callees.len(), @@ -642,6 +644,7 @@ fn compile_function_units( let max_instructions = sizes.iter().map(|size| size.1).max().unwrap_or(0); // Each worker compiles with a copy of the layout (below). let workers = super::super::compile_resources::workers_with_state( + options.optimize_options.compile_threads(), max_blocks, max_instructions, functions.len(), @@ -807,6 +810,7 @@ fn compile_split_comb( let mut order = (0..sizes.len()).collect::>(); order.sort_by_key(|&index| std::cmp::Reverse(sizes[index])); let workers = super::super::compile_resources::workers( + options.optimize_options.compile_threads(), sizes.iter().map(|s| s.0).max().unwrap_or(0), sizes.iter().map(|s| s.1).max().unwrap_or(0), sizes.len(), @@ -1093,6 +1097,7 @@ fn compile_remaining_processes( ); } let process_workers = super::super::compile_resources::workers( + options.optimize_options.compile_threads(), max_process_blocks, max_process_instructions, process_sizes.len(), diff --git a/crates/celox/src/backend/native/backend/lazy_functions.rs b/crates/celox/src/backend/native/backend/lazy_functions.rs index 2546be28c2a..7710a5842ec 100644 --- a/crates/celox/src/backend/native/backend/lazy_functions.rs +++ b/crates/celox/src/backend/native/backend/lazy_functions.rs @@ -351,6 +351,7 @@ impl Compiler { (blocks.max(b), instructions.max(i)) }); super::super::compile_resources::workers_with_state( + self.options.optimize_options.compile_threads(), blocks, instructions, functions.len(), diff --git a/crates/celox/src/backend/native/compile_resources.rs b/crates/celox/src/backend/native/compile_resources.rs index 0f97bef9e8c..662ab730ff7 100644 --- a/crates/celox/src/backend/native/compile_resources.rs +++ b/crates/celox/src/backend/native/compile_resources.rs @@ -43,13 +43,17 @@ const MIN_TASK_MEMORY: u64 = 128 * 1024 * 1024; /// one worker. const ASSUMED_BUDGET: u64 = 2 * 1024 * 1024 * 1024; -pub(super) fn workers(blocks: usize, instructions: usize, tasks: usize) -> usize { - workers_with_state(blocks, instructions, tasks, 0) +/// How many of `threads` (the compile threads of the options, see +/// `OptimizeOptions::compile_threads`) compile `tasks` tasks of at most +/// `blocks` blocks and `instructions` instructions. +pub(super) fn workers(threads: usize, blocks: usize, instructions: usize, tasks: usize) -> usize { + workers_with_state(threads, blocks, instructions, tasks, 0) } /// [`workers`] for tasks that each worker compiles with state of its own, /// such as a copy of the layout, of `state` bytes. pub(super) fn workers_with_state( + threads: usize, blocks: usize, instructions: usize, tasks: usize, @@ -59,12 +63,20 @@ pub(super) fn workers_with_state( blocks, instructions, tasks, - std::thread::available_parallelism().map_or(1, usize::from), + cpus(threads), available_memory(), state, ) } +/// The host threads compiling may use: `threads` of the options, no more +/// than the host has. +fn cpus(threads: usize) -> usize { + std::thread::available_parallelism() + .map_or(1, usize::from) + .min(threads.max(1)) +} + /// About the heap a copy of `table` takes. A hash table holds a control byte /// besides each entry. fn table_bytes(table: &fxhash::FxHashMap) -> u64 { @@ -91,17 +103,12 @@ pub(super) fn layout_bytes(layout: &celox_state_layout::MemoryLayout) -> u /// One primary circuit and a queue of smaller independent event functions. /// Reserve the primary once, rather than charging its size to every worker. pub(super) fn workers_with_primary( + threads: usize, primary: (usize, usize), secondary: (usize, usize), tasks: usize, ) -> usize { - choose_workers_with_primary( - primary, - secondary, - tasks, - std::thread::available_parallelism().map_or(1, usize::from), - available_memory(), - ) + choose_workers_with_primary(primary, secondary, tasks, cpus(threads), available_memory()) } fn choose_workers_with_primary( diff --git a/crates/celox/src/backend/native/lanes.rs b/crates/celox/src/backend/native/lanes.rs index 997ac803ab7..575b9e0458e 100644 --- a/crates/celox/src/backend/native/lanes.rs +++ b/crates/celox/src/backend/native/lanes.rs @@ -239,31 +239,35 @@ pub(super) fn compile_lane_kernels( } let mut lane_options = options.x86_options.clone(); lane_options.arena_base = (lane > 0).then_some(arena_floor); - let compiled = compile_jobs(&jobs, |&(kernel, task)| { - let units = planned[kernel].task_units(task); - let mut footprint = None; - let function = compile_unit_refs_inspected( - &units, - layout, - options.four_state, - "lane_task", - NativeMergeKind::Partial, - &lane_options, - false, - &options.optimize_options.diagnostics, - cancel, - false, - &mut |prepared| { - footprint = Some(Footprint::of_unit(prepared, layout, codegen)); - tracing::trace!(target: "celox::parallel", event = "native_task_sir", + let compiled = compile_jobs( + &jobs, + options.optimize_options.compile_threads(), + |&(kernel, task)| { + let units = planned[kernel].task_units(task); + let mut footprint = None; + let function = compile_unit_refs_inspected( + &units, + layout, + options.four_state, + "lane_task", + NativeMergeKind::Partial, + &lane_options, + false, + &options.optimize_options.diagnostics, + cancel, + false, + &mut |prepared| { + footprint = Some(Footprint::of_unit(prepared, layout, codegen)); + tracing::trace!(target: "celox::parallel", event = "native_task_sir", schedule = planned[kernel].diagnostic_id.as_str(), program = planned[kernel].diagnostic_program.as_str(), kind = ?planned[kernel].kind, task, sir = ?prepared); - }, - )?; - let footprint = footprint.unwrap_or_else(Footprint::empty); - Ok((function, footprint)) - })?; + }, + )?; + let footprint = footprint.unwrap_or_else(Footprint::empty); + Ok((function, footprint)) + }, + )?; let lane_end = compiled .iter() .map(|(function, _)| function.required_state_size) @@ -334,14 +338,17 @@ pub(super) fn compile_lane_kernels( })) } -/// Compile independent jobs on up to four host threads, preserving order. +/// Compile independent jobs on up to four host threads, and no more than the +/// `threads` compiling may use, preserving order. fn compile_jobs( jobs: &[J], + threads: usize, compile: impl Fn(&J) -> Result + Sync, ) -> Result, SimulatorError> { let workers = std::thread::available_parallelism() .map_or(1, usize::from) .min(4) + .min(threads.max(1)) .min(jobs.len()); if workers <= 1 { return jobs.iter().map(&compile).collect(); diff --git a/crates/celox/src/bin/celox.rs b/crates/celox/src/bin/celox.rs index adccadc3b2a..9e1d4daeda0 100644 --- a/crates/celox/src/bin/celox.rs +++ b/crates/celox/src/bin/celox.rs @@ -295,6 +295,10 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { .signal_access(arguments.design.signal_access.clone()) .plusargs(arguments.plusargs.iter().cloned()) .defer_initialization(arguments.save_state.restore_checkpoint.is_some()); + let builder = match arguments.execution.compile_threads { + Some(threads) => builder.compile_threads(threads as usize), + None => builder, + }; // Live waveform reads need every signal store, including unused internal nets. let builder = if arguments.cdsp.is_some() { builder.dead_store_policy(celox::DeadStorePolicy::Off) diff --git a/crates/celox/src/bin/celox/runner.rs b/crates/celox/src/bin/celox/runner.rs index 84b4aa9c2bc..68145ac4d64 100644 --- a/crates/celox/src/bin/celox/runner.rs +++ b/crates/celox/src/bin/celox/runner.rs @@ -111,6 +111,12 @@ pub(super) struct ExecutionArgs { /// Simulation threads, including the calling thread. #[arg(long, default_value_t = 1, value_parser = clap::value_parser!(u32).range(1..=64))] pub threads: u32, + /// Compile threads: the SystemVerilog frontend and native code + /// generation compile independent modules and units on up to this many + /// threads. The compiled program is the same for every count. Default: + /// the available parallelism of the host. + #[arg(long, value_name = "N", value_parser = clap::value_parser!(u32).range(1..))] + pub compile_threads: Option, /// Emit machine-readable CELOX_* timing, configuration and result records. #[arg(long)] pub(super) report: bool, @@ -266,6 +272,7 @@ struct Options { native_memory_width: usize, x86_slp: bool, threads: u32, + compile_threads: Option, always_partition: bool, } @@ -458,6 +465,9 @@ pub(super) fn run( .hotspot_jit(opts.hotspot_jit) .threads(opts.threads as usize) .diagnostics_from_env(); + if let Some(threads) = opts.compile_threads { + builder = builder.compile_threads(threads as usize); + } if let Some(path) = &opts.dump_settle_plan { builder = builder.settle_plan_output(path); } @@ -653,6 +663,7 @@ fn resolve_options( all(target_arch = "x86_64", not(feature = "arm64-codegen")) ))), threads: cli.threads, + compile_threads: cli.compile_threads, always_partition: cli.always_partition, design, }) diff --git a/crates/celox/src/optimizer.rs b/crates/celox/src/optimizer.rs index 58871603349..e38962bc6e7 100644 --- a/crates/celox/src/optimizer.rs +++ b/crates/celox/src/optimizer.rs @@ -108,5 +108,6 @@ pub(crate) fn parallel_schedule_options( celox_frontend_core::SettlePartitionMode::Estimated }; parallel.settle_profile = options.settle_profile(); + parallel.compile_workers = options.compile_threads(); parallel } diff --git a/crates/celox/src/simulator/builder/host.rs b/crates/celox/src/simulator/builder/host.rs index ecd5a8cfabb..5a03fc8d756 100644 --- a/crates/celox/src/simulator/builder/host.rs +++ b/crates/celox/src/simulator/builder/host.rs @@ -339,11 +339,15 @@ impl<'a, Target> SimulatorBuilder<'a, Target> { let partition = self.options.optimize_options.parallel_partition(); let settle = self.options.optimize_options.settle_partition(); let watched = self.watched_objects(); + let compile_threads = self.options.optimize_options.requested_compile_threads(); self.options.optimize_options = crate::optimizer::OptimizeOptions::new(level) .with_parallel_lanes(lanes) .with_parallel_partition(partition) .with_settle_partition(settle) .with_value_change_objects(watched); + if let Some(threads) = compile_threads { + self.options.optimize_options.set_compile_threads(threads); + } self.options.cranelift_options = crate::backend::CraneliftOptions::for_speed_optimization( level != crate::optimizer::OptLevel::O0, ); @@ -379,6 +383,7 @@ impl<'a, Target> SimulatorBuilder<'a, Target> { let partition = self.options.optimize_options.parallel_partition(); let settle = self.options.optimize_options.settle_partition(); let watched = self.watched_objects(); + let compile_threads = self.options.optimize_options.requested_compile_threads(); self.options.optimize_options = if enable { crate::optimizer::OptimizeOptions::all() } else { @@ -388,6 +393,9 @@ impl<'a, Target> SimulatorBuilder<'a, Target> { .with_parallel_partition(partition) .with_settle_partition(settle) .with_value_change_objects(watched); + if let Some(threads) = compile_threads { + self.options.optimize_options.set_compile_threads(threads); + } self } @@ -427,11 +435,17 @@ impl<'a, Target> SimulatorBuilder<'a, Target> { } else { options.value_change_objects().to_vec() }; + let compile_threads = options + .requested_compile_threads() + .or_else(|| self.options.optimize_options.requested_compile_threads()); self.options.optimize_options = options .with_parallel_lanes(lanes) .with_parallel_partition(partition) .with_settle_partition(settle) .with_value_change_objects(watched); + if let Some(threads) = compile_threads { + self.options.optimize_options.set_compile_threads(threads); + } self } @@ -458,6 +472,18 @@ impl<'a, Target> SimulatorBuilder<'a, Target> { self } + /// Compile with at most `threads` host threads (at least one). The + /// SystemVerilog frontend lowers independent modules on them, and + /// native code generation compiles independent units on as many as its + /// memory budget allows. One compiles on the calling thread only. The + /// compiled program is the same for every count; these are not the + /// simulation threads of [`Self::threads`]. The default is the + /// available parallelism of the host. + pub fn compile_threads(mut self, threads: usize) -> Self { + self.options.optimize_options.set_compile_threads(threads); + self + } + /// Choose how [`Self::threads`] decides which phases to partition. /// /// The default partitions a phase only when its estimated speedup diff --git a/docs/guide/parallel-simulation.md b/docs/guide/parallel-simulation.md index d67c828d725..40011e4b333 100644 --- a/docs/guide/parallel-simulation.md +++ b/docs/guide/parallel-simulation.md @@ -63,6 +63,29 @@ result. Each measurement costs a few dozen calls of the slower version. Runtime events such as `$display` and assertions, and stores that can trigger clock events, stay ordered exactly as in sequential simulation. +## Compile threads + +Compilation has its own thread count, separate from the simulation threads +above. The SystemVerilog frontend lowers independent modules (such as the +state modules of packages) on these threads, and native code generation +compiles independent units on as many of them as its memory budget allows. +The compiled program is the same for every count. + +```rust +let mut sim = Simulator::builder(code, "Top") + .compile_threads(8) + .build()?; +``` + +```typescript +const sim = await Simulator.create(module, { compileThreads: 8 }); +``` + +On the command line it is `celox run --compile-threads 8`. The default is the +available parallelism of the host; `1` compiles everything on the calling +thread. Lower it when many simulators compile at the same time, as test +runners do. + ## Backends Parallel execution is available on the native x86-64 and AArch64 backends diff --git a/docs/ja/guide/parallel-simulation.md b/docs/ja/guide/parallel-simulation.md index ad58b58f658..54cc7923b20 100644 --- a/docs/ja/guide/parallel-simulation.md +++ b/docs/ja/guide/parallel-simulation.md @@ -60,6 +60,29 @@ Celox は次の 2 段階で、並列化によって遅くなることを防ぎ `$display` やアサーションなどのランタイムイベント、クロックイベントを発火しうる ストアの順序は、逐次シミュレーションとまったく同じに保たれます。 +## コンパイルスレッド + +コンパイルには、上記のシミュレーションスレッドとは別のスレッド数があります。 +SystemVerilog フロントエンドは独立したモジュール(パッケージの状態モジュール +など)をこれらのスレッドで変換し、ネイティブコード生成は独立したユニットを +メモリ予算の許す数のスレッドでコンパイルします。生成されるプログラムは +スレッド数によらず同じです。 + +```rust +let mut sim = Simulator::builder(code, "Top") + .compile_threads(8) + .build()?; +``` + +```typescript +const sim = await Simulator.create(module, { compileThreads: 8 }); +``` + +コマンドラインでは `celox run --compile-threads 8` です。既定値はホストで +利用可能な並列度で、`1` ではすべて呼び出し元スレッドでコンパイルします。 +テストランナーのように多数のシミュレーターを同時にコンパイルする場合は +小さくしてください。 + ## バックエンド 並列実行はネイティブの x86-64・AArch64 バックエンドと Cranelift で利用できます。 diff --git a/packages/celox/src/napi-helpers.ts b/packages/celox/src/napi-helpers.ts index 911be469bad..ed21cfde700 100644 --- a/packages/celox/src/napi-helpers.ts +++ b/packages/celox/src/napi-helpers.ts @@ -192,6 +192,7 @@ export interface NapiOptions { parameters?: NapiParamOverride[]; deadStorePolicy?: string; threads?: number; + compileThreads?: number; hotspotJit?: boolean; } @@ -563,6 +564,10 @@ export function buildNapiOpts( napiOpts.threads = options.threads; hasOpt = true; } + if (options.compileThreads != null) { + napiOpts.compileThreads = options.compileThreads; + hasOpt = true; + } if (options.hotspotJit === false) { napiOpts.hotspotJit = false; hasOpt = true; diff --git a/packages/celox/src/types.ts b/packages/celox/src/types.ts index 16e393fd2c5..d6f8c5ed46d 100644 --- a/packages/celox/src/types.ts +++ b/packages/celox/src/types.ts @@ -589,6 +589,13 @@ export interface SimulatorOptions { * cores. */ threads?: number; + /** + * Compile threads: the SystemVerilog frontend and native code generation + * compile independent modules and units on up to this many threads. + * The compiled program is the same for every count. These are not the + * simulation `threads`. Default: the available parallelism of the host. + */ + compileThreads?: number; /** * Run tiered: execution starts on the interpreter immediately while the * host's compiled tier is prepared on a background thread, and the