diff --git a/crates/celox-frontend-core/src/lib.rs b/crates/celox-frontend-core/src/lib.rs index 99fd29d9ea..20b3ec0efc 100644 --- a/crates/celox-frontend-core/src/lib.rs +++ b/crates/celox-frontend-core/src/lib.rs @@ -6,6 +6,7 @@ pub mod process; mod sdk; pub mod shared; pub mod symbolic; +pub mod tasks; mod trace; pub mod watch; diff --git a/crates/celox-frontend-core/src/symbolic/parallel.rs b/crates/celox-frontend-core/src/symbolic/parallel.rs index 5949b85da2..41ecc890a0 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-core/src/tasks.rs b/crates/celox-frontend-core/src/tasks.rs new file mode 100644 index 0000000000..5e7caf4977 --- /dev/null +++ b/crates/celox-frontend-core/src/tasks.rs @@ -0,0 +1,192 @@ +//! Independent compile tasks on a few scoped threads, with results that do +//! not depend on how many threads run them. + +/// The stack of a task thread: what the main thread of a process has, since +/// lowering and compiling recurse over statements and expressions as they +/// do on it. +const STACK_SIZE: usize = 8 * 1024 * 1024; + +/// Run task `index` for each index of `order`, on up to `workers` threads. +/// The tasks are taken in the order of `order`, but the results come back by +/// task index. The first task that fails stops the others from taking more +/// tasks; of the tasks that failed, the error of the one with the lowest +/// index is returned. With one worker or one task, the tasks run in `order` +/// on the calling thread. +pub fn run_ordered( + order: &[usize], + workers: usize, + task: impl Fn(usize) -> Result + Sync, +) -> std::thread::Result, E>> { + run_ordered_with(order, workers, || (), |(), index| task(index)) +} + +/// [`run_ordered`], with state of each worker: `state` makes it in the +/// worker, once, and the worker passes it to each task it runs. +pub fn run_ordered_with( + order: &[usize], + workers: usize, + state: impl Fn() -> S + Sync, + task: impl Fn(&mut S, usize) -> Result + Sync, +) -> std::thread::Result, E>> { + use std::sync::atomic::Ordering; + use std::sync::atomic::{AtomicBool, AtomicUsize}; + let mut results = Vec::with_capacity(order.len()); + let mut failure = None; + if workers <= 1 || order.len() <= 1 { + let mut state = state(); + for &index in order { + match task(&mut state, index) { + Ok(result) => results.push((index, result)), + Err(error) => { + failure = Some((index, error)); + break; + } + } + } + } else { + #[expect( + clippy::disallowed_types, + reason = "cross-thread: scoped task threads claim the next task index from this shared counter" + )] + let next = AtomicUsize::new(0); + #[expect( + clippy::disallowed_types, + reason = "cross-thread: the first failing scoped task thread sets it and the other threads stop taking tasks" + )] + let stopped = AtomicBool::new(false); + // The tasks log as the calling thread does. + let dispatcher = tracing::dispatcher::get_default(Clone::clone); + std::thread::scope(|scope| { + let handles = (0..workers.min(order.len())) + .map(|_| { + let next = &next; + let stopped = &stopped; + let state = &state; + let task = &task; + let dispatcher = dispatcher.clone(); + std::thread::Builder::new() + .stack_size(STACK_SIZE) + .spawn_scoped(scope, move || { + let _logging = tracing::dispatcher::set_default(&dispatcher); + let mut state = state(); + let mut results = Vec::new(); + let mut failure = None; + while !stopped.load(Ordering::Relaxed) { + let position = next.fetch_add(1, Ordering::Relaxed); + let Some(&index) = order.get(position) else { + break; + }; + match task(&mut state, index) { + Ok(result) => results.push((index, result)), + Err(error) => { + stopped.store(true, Ordering::Relaxed); + failure = Some((index, error)); + break; + } + } + } + (results, failure) + }) + .expect("spawn a compile task thread") + }) + .collect::>(); + let mut panic = None; + for handle in handles { + match handle.join() { + Ok((completed, failed)) => { + results.extend(completed); + // Of the tasks that failed before the others + // stopped, the first by index. + if let Some(failed) = failed + && failure.as_ref().is_none_or(|(index, _)| failed.0 < *index) + { + failure = Some(failed); + } + } + Err(error) => { + if panic.is_none() { + panic = Some(error); + } + } + } + } + match panic { + Some(error) => Err(error), + None => Ok(()), + } + })?; + } + if let Some((_, error)) = failure { + return Ok(Err(error)); + } + results.sort_unstable_by_key(|(index, _)| *index); + Ok(Ok(results.into_iter().map(|(_, result)| result).collect())) +} + +/// [`run_ordered`] over tasks that each own their input: task `index` takes +/// `inputs[index]`. +pub fn run_owned( + inputs: Vec, + order: &[usize], + workers: usize, + task: impl Fn(usize, I) -> Result + Sync, +) -> std::thread::Result, E>> { + #[expect( + clippy::disallowed_types, + reason = "cross-thread: each scoped task thread takes the input of the task it claimed, once" + )] + let inputs = inputs + .into_iter() + .map(|input| std::sync::Mutex::new(Some(input))) + .collect::>(); + run_ordered(order, workers, |index| { + let input = inputs[index] + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take() + .expect("each task runs once"); + task(index, input) + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn results_come_back_by_index_for_every_worker_count() { + let order = [3, 0, 2, 1, 4]; + for workers in [1, 2, 8] { + let results = + run_ordered::<_, ()>(&order, workers, |index| Ok(index * 10)).expect("no panic"); + assert_eq!(results, Ok(vec![0, 10, 20, 30, 40]), "{workers} workers"); + } + } + + #[test] + fn the_failure_with_the_lowest_index_is_returned() { + // With one worker the tasks run in `order` and stop at the first + // failure taken, task 3. + let order = [3, 1, 0, 2]; + let result = run_ordered( + &order, + 1, + |index| if index % 2 == 1 { Err(index) } else { Ok(()) }, + ) + .expect("no panic"); + assert_eq!(result, Err(3)); + } + + #[test] + fn each_task_owns_its_input() { + let inputs = vec![String::from("a"), String::from("b"), String::from("c")]; + let results = run_owned::<_, _, ()>(inputs, &[2, 1, 0], 2, |index, input| { + Ok(format!("{index}{input}")) + }) + .expect("no panic"); + assert_eq!( + results, + Ok(vec!["0a".to_string(), "1b".to_string(), "2c".to_string()]) + ); + } +} diff --git a/crates/celox-frontend-sv/src/lowering/external_hierarchy.rs b/crates/celox-frontend-sv/src/lowering/external_hierarchy.rs index a104853937..f6d355980e 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 b4d21ad650..3a2724866b 100644 --- a/crates/celox-frontend-sv/src/lowering/packages.rs +++ b/crates/celox-frontend-sv/src/lowering/packages.rs @@ -91,8 +91,21 @@ pub(super) fn package_states( } } +/// What lowering one package state module made: the warnings and the +/// recursion report lines it gave, which [`lower_package_states`] passes on +/// in the order of the modules, and the module or the error. +struct PackageLowering { + warnings: Vec, + report: Option>, + 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, @@ -105,99 +118,152 @@ pub(super) fn lower_package_states( states, global_precision, } = states; - states - .into_iter() - .enumerate() - .map(|(index, (module, time_scale))| { - let name = module.name().to_string(); - // The subroutines that the package's initializers call go out of - // line as a module's do, recursive ones included. - let mut calls = Some(recursion::CallGraph::new( - force_out_of_line, - recursion_report.is_some(), - )); - // And call the root's functions instead where they serve (see - // `out_of_line::Home`), when the two keep time alike. - if let (Some(home), Ok(time_scale), Some(functions)) = ( - &home, - &time_scale, - calls.as_mut().and_then(|graph| graph.out_of_line.as_mut()), - ) && home.time_scale == *time_scale - { - functions.home = Some(out_of_line::HomeLink::new( - std::sync::Arc::clone(home), - &name, - )); - } - let report_source = recursion_report.map(|_| module.clone()); - let lowered = lower_module( - std::borrow::Cow::Owned(module), + // 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. 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, + workers, + |index, (module, time_scale)| { + let mut warnings = Vec::new(); + let mut report = None; + let lowered = lower_package_state( + module, + time_scale, + ModuleId(first + index), four_state, - true, ff_parts, - NextStateOptions::default(), - warnings, - &[], - LevelLists::Processes, - &HashMap::default(), - &HashMap::default(), - SharedAlways::default(), - &HashSet::default(), - &[], - calls.as_mut(), + global_precision, + &mut warnings, + force_out_of_line, + recursion_report.is_some().then_some(&mut report), + home.as_ref(), ); - if let (Some(graph), Some(path), Some(module)) = - (&calls, recursion_report, &report_source) - { - recursion::append(module, graph, path); - } - let mut lowered = lowered?; - if let Some(functions) = calls.as_ref().and_then(|graph| graph.out_of_line.as_ref()) { - out_of_line::attach_functions(&mut lowered.sim_module, functions); - // The variables that name those of the root's function - // sites (see `ProcModule::list_home_sites`). - if let Some(link) = &functions.home { - for (own, target) in &link.bound { - match target { - out_of_line::Mirror::Home(id) => { - lowered.sim_module.hierarchical_bindings.insert( - *own, - celox_frontend_core::symbolic::artifact::HierarchicalBinding { - start: celox_frontend_core::symbolic::artifact::HierarchicalStart::Root, - path: Vec::new(), - targets: vec![(link.home.module, *id)], - }, - ); - } - out_of_line::Mirror::Package(package, variable) => lowered - .package_variables - .push((*own, package.clone(), variable.clone())), - } + Ok(PackageLowering { + warnings, + report, + lowered, + }) + }, + ) + .unwrap_or_else(|panic| std::panic::resume_unwind(panic)); + let Ok(lowerings) = lowerings; + let mut lowered = Vec::with_capacity(lowerings.len()); + for lowering in lowerings { + warnings.extend(lowering.warnings); + if let (Some(lines), Some(path)) = (&lowering.report, recursion_report) { + recursion::append_lines(lines, path); + } + lowered.push(lowering.lowered?); + } + Ok(lowered) +} + +/// Lower the state `module` of a package as the module `id`, with the +/// recursion report lines of its call graph in `report` when one is asked +/// for. +#[allow(clippy::too_many_arguments)] +fn lower_package_state( + module: sv::ir::Module, + time_scale: Result, + id: ModuleId, + four_state: bool, + ff_parts: bool, + global_precision: i32, + warnings: &mut Vec, + force_out_of_line: bool, + report: Option<&mut Option>>, + home: Option<&std::sync::Arc>, +) -> Result<(String, ModuleId, LoweredSvModule), sv::AnalyzerError> { + let name = module.name().to_string(); + // The subroutines that the package's initializers call go out of + // line as a module's do, recursive ones included. + let mut calls = Some(recursion::CallGraph::new( + force_out_of_line, + report.is_some(), + )); + // And call the root's functions instead where they serve (see + // `out_of_line::Home`), when the two keep time alike. + if let (Some(home), Ok(time_scale), Some(functions)) = ( + home, + &time_scale, + calls.as_mut().and_then(|graph| graph.out_of_line.as_mut()), + ) && home.time_scale == *time_scale + { + functions.home = Some(out_of_line::HomeLink::new( + std::sync::Arc::clone(home), + &name, + )); + } + let report_source = report.is_some().then(|| module.clone()); + let lowered = lower_module( + std::borrow::Cow::Owned(module), + four_state, + true, + ff_parts, + NextStateOptions::default(), + warnings, + &[], + LevelLists::Processes, + &HashMap::default(), + &HashMap::default(), + SharedAlways::default(), + &HashSet::default(), + &[], + calls.as_mut(), + ); + if let (Some(graph), Some(report), Some(module)) = (&calls, report, &report_source) { + *report = Some(recursion::report(module, graph)); + } + let mut lowered = lowered?; + if let Some(functions) = calls.as_ref().and_then(|graph| graph.out_of_line.as_ref()) { + out_of_line::attach_functions(&mut lowered.sim_module, functions); + // The variables that name those of the root's function + // sites (see `ProcModule::list_home_sites`). + if let Some(link) = &functions.home { + for (own, target) in &link.bound { + match target { + out_of_line::Mirror::Home(id) => { + lowered.sim_module.hierarchical_bindings.insert( + *own, + celox_frontend_core::symbolic::artifact::HierarchicalBinding { + start: celox_frontend_core::symbolic::artifact::HierarchicalStart::Root, + path: Vec::new(), + targets: vec![(link.home.module, *id)], + }, + ); } + out_of_line::Mirror::Package(package, variable) => lowered + .package_variables + .push((*own, package.clone(), variable.clone())), } } - lowered.sim_module.time_precision = Some( - celox_design::TimePrecision::try_from(global_precision) - .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))?, - ); - lowered.sim_module.time_scale = time_scale?; - // Declaration initializers run before every `initial` block - // (IEEE 1800-2023 6.8, 10.5): one that is not folded into an - // initial value runs as a declaration initializer, and any other - // process would run among the `initial` blocks. - if lowered - .sim_module - .processes - .iter() - .any(|process| process.slots.kind != celox_design::ProcessKind::Initializer) - { - return Err(sv::AnalyzerError::Unsupported(format!( - "package variable initializer that is not constant in package `{name}`" - ))); - } - Ok((name, ModuleId(first + index), lowered)) - }) - .collect() + } + } + lowered.sim_module.time_precision = Some( + celox_design::TimePrecision::try_from(global_precision) + .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))?, + ); + lowered.sim_module.time_scale = time_scale?; + // Declaration initializers run before every `initial` block + // (IEEE 1800-2023 6.8, 10.5): one that is not folded into an + // initial value runs as a declaration initializer, and any other + // process would run among the `initial` blocks. + if lowered + .sim_module + .processes + .iter() + .any(|process| process.slots.kind != celox_design::ProcessKind::Initializer) + { + return Err(sv::AnalyzerError::Unsupported(format!( + "package variable initializer that is not constant in package `{name}`" + ))); + } + Ok((name, id, lowered)) } /// Add the keys of the class properties that the level waits of the state @@ -277,3 +343,102 @@ 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 specialized modules and 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 modules_and_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 Leaf #(parameter int W = 1)(input logic clk, output int count); + function automatic int step(int n); + if (n > 0) return step(n - 1) + W; + return 0; + endfunction + always_ff @(posedge clk) count <= count + step(2); + endmodule + module Top(input logic clk, output int sum); + int a, b, c, d; + Leaf #(1) l1(.clk(clk), .count(a)); + Leaf #(2) l2(.clk(clk), .count(b)); + Leaf #(3) l3(.clk(clk), .count(c)); + Leaf #(4) l4(.clk(clk), .count(d)); + assign sum = p0::start + p1::start + p2::start + p3::start + + p4::start + p5::start + a + b + c + d; + 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/recursion.rs b/crates/celox-frontend-sv/src/lowering/recursion.rs index 7b25cec1cc..532e95fc96 100644 --- a/crates/celox-frontend-sv/src/lowering/recursion.rs +++ b/crates/celox-frontend-sv/src/lowering/recursion.rs @@ -459,7 +459,11 @@ pub(super) fn report(module: &sv::ir::Module, graph: &CallGraph) -> Vec /// Append the report of `module` to `path`. pub(super) fn append(module: &sv::ir::Module, graph: &CallGraph, path: &Path) { - let lines = report(module, graph); + append_lines(&report(module, graph), path); +} + +/// Append the `lines` of a report (see [`report`]) to `path`. +pub(super) fn append_lines(lines: &[String], path: &Path) { if let Ok(mut file) = std::fs::OpenOptions::new() .create(true) .append(true) diff --git a/crates/celox-frontend-sv/src/lowering/schedule.rs b/crates/celox-frontend-sv/src/lowering/schedule.rs index ced51dacba..c75b3fbff3 100644 --- a/crates/celox-frontend-sv/src/lowering/schedule.rs +++ b/crates/celox-frontend-sv/src/lowering/schedule.rs @@ -933,70 +933,124 @@ fn schedule_sources_collecting( let no_foreign_references = HashSet::default(); let mut reported_forces = false; loop { - let mut specialize = |key: &LoweredSvModuleKey, - module_id: ModuleId| - -> Result { - let base = analyzed - .get(&key.name) - .ok_or_else(|| unsupported_sv_instance(key.name.clone()))?; - let level_lists = LevelLists::Lowered { - demoted: demoted.get(&module_id).unwrap_or(&no_demotions), - }; - let signals: Vec<_> = references - .get(&module_id) - .into_iter() - .flatten() - .map(|reference: &hierarchy::HierarchicalReference| reference.signal.clone()) - .collect(); - // Move out the discovery result: final lowering owns its source - // module, so keeping another complete IR through retries is needless. - let discovery_analysis = discovery_analyses.remove(&module_id); - Ok(specialize_module( - base, - &mut design, - key, - four_state, - parallel.enabled(), - warnings, - level_lists, - HierarchicalNames { - signals: &signals, - foreign_writes: foreign_writes.get(&module_id).unwrap_or(&no_foreign_writes), - forced: forced.get(&module_id).map_or(&[], Vec::as_slice), - analyzed: analyses.get(&module_id), - recursion_report: analysis_options.recursion_report.as_deref(), - force_out_of_line: analysis_options.force_out_of_line_calls, - home: module_id == root_id && !hidden_root, - next_state: NextStateOptions { - report: analysis_options.ff_next_state_report.as_deref(), - forms: analysis_options.ff_next_state, - }, - properties: &properties, - time_format, - instances: Instances::Known(&expansion), - shared: SharedAlways { - temporaries: analysis_options.shared_always_temporaries, - foreign_references: foreign_references + // Each specialization still to lower is prepared in the order of + // `module_ids`, which may analyze it, and then lowered on its own, + // on up to `compile_workers` threads, the largest first. What they + // give is passed on in that order, up to the first that fails, as + // lowering them one after another would. + let pending: Vec<(&LoweredSvModuleKey, ModuleId)> = module_ids + .iter() + .filter(|(_, module_id)| !lowered_modules.contains_key(*module_id)) + .map(|(key, &module_id)| (key, module_id)) + .collect(); + // The signals of other instances each one's names denote. + let signals: Vec> = pending + .iter() + .map(|(_, module_id)| { + references + .get(module_id) + .into_iter() + .flatten() + .map(|reference: &hierarchy::HierarchicalReference| reference.signal.clone()) + .collect() + }) + .collect(); + let mut prepared = Vec::with_capacity(pending.len()); + let mut failure = None; + for (&(key, module_id), signals) in pending.iter().zip(&signals) { + let mut prepare = || -> Result<_, FrontendError> { + let base = analyzed + .get(&key.name) + .ok_or_else(|| unsupported_sv_instance(key.name.clone()))?; + let level_lists = LevelLists::Lowered { + demoted: demoted.get(&module_id).unwrap_or(&no_demotions), + }; + // Move out the discovery result: final lowering owns its source + // module, so keeping another complete IR through retries is needless. + let discovery_analysis = discovery_analyses.remove(&module_id); + let mut warnings = Vec::new(); + let specialization = prepare_specialization( + base, + &mut design, + key, + four_state, + parallel.enabled(), + &mut warnings, + level_lists, + HierarchicalNames { + signals, + foreign_writes: foreign_writes + .get(&module_id) + .unwrap_or(&no_foreign_writes), + forced: forced.get(&module_id).map_or(&[], Vec::as_slice), + analyzed: analyses.get(&module_id), + recursion_report: analysis_options.recursion_report.as_deref(), + force_out_of_line: analysis_options.force_out_of_line_calls, + home: module_id == root_id && !hidden_root, + next_state: NextStateOptions { + report: analysis_options.ff_next_state_report.as_deref(), + forms: analysis_options.ff_next_state, + }, + properties: &properties, + time_format, + instances: Instances::Known(&expansion), + shared: SharedAlways { + temporaries: analysis_options.shared_always_temporaries, + foreign_references: foreign_references + .get(&module_id) + .unwrap_or(&no_foreign_references), + no_covergroups, + }, + same_instance_aliased: same_instance_aliased .get(&module_id) .unwrap_or(&no_foreign_references), - no_covergroups, + same_instance_alias_groups: same_instance_alias_groups + .get(&module_id) + .map_or(&[], Vec::as_slice), }, - same_instance_aliased: same_instance_aliased - .get(&module_id) - .unwrap_or(&no_foreign_references), - same_instance_alias_groups: same_instance_alias_groups - .get(&module_id) - .map_or(&[], Vec::as_slice), - }, - discovery_analysis, - )?) - }; - for (key, &module_id) in &module_ids { - if let std::collections::hash_map::Entry::Vacant(entry) = - lowered_modules.entry(module_id) + discovery_analysis, + ); + Ok((warnings, specialization)) + }; + match prepare() { + Ok((warnings, Ok(specialization))) => prepared.push((warnings, specialization)), + Ok((warnings, Err(error))) => { + failure = Some((warnings, FrontendError::from(error))); + break; + } + Err(error) => { + failure = Some((Vec::new(), error)); + break; + } + } + } + let mut order = (0..prepared.len()).collect::>(); + order.sort_by_key(|&index| std::cmp::Reverse(prepared[index].1.size())); + let lowerings = celox_frontend_core::tasks::run_owned::<_, _, std::convert::Infallible>( + prepared, + &order, + parallel.compile_workers, + |_, (mut warnings, specialization)| { + let mut report = None; + let lowered = lower_specialization(specialization, &mut warnings, &mut report); + Ok((warnings, report, lowered)) + }, + ) + .unwrap_or_else(|panic| std::panic::resume_unwind(panic)); + let Ok(lowerings) = lowerings; + for ((_, module_id), (lowering_warnings, report, lowered)) in pending.iter().zip(lowerings) + { + warnings.extend(lowering_warnings); + if let (Some(lines), Some(path)) = + (&report, analysis_options.recursion_report.as_deref()) { - entry.insert(specialize(key, module_id)?); + recursion::append_lines(lines, path); } + lowered_modules.insert(*module_id, lowered?); + } + if let Some((failure_warnings, error)) = failure { + warnings.extend(failure_warnings); + return Err(error); } // Every instance of a forced specialization carries its force // controls; report the specializations that more than one instance @@ -1227,6 +1281,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-frontend-sv/src/lowering/specialize.rs b/crates/celox-frontend-sv/src/lowering/specialize.rs index e0665b2a53..71e0e9daba 100644 --- a/crates/celox-frontend-sv/src/lowering/specialize.rs +++ b/crates/celox-frontend-sv/src/lowering/specialize.rs @@ -146,6 +146,90 @@ pub(super) fn specialize_module( hierarchical: HierarchicalNames<'_>, owned_analysis: Option, ) -> Result { + let prepared = prepare_specialization( + module, + design, + key, + four_state, + ff_parts, + warnings, + level_lists, + hierarchical, + owned_analysis, + )?; + let mut report = None; + let lowered = lower_specialization(prepared, warnings, &mut report); + if let (Some(lines), Some(path)) = (&report, hierarchical.recursion_report) { + recursion::append_lines(lines, path); + } + lowered +} + +/// The analysis a specialization is lowered from (see +/// [`PreparedSpecialization`]). +enum SpecializedSource<'a> { + /// The module of an analysis shared with other lowerings. + Shared(&'a sv::ir::Module), + /// An analysis of the module's own, kept whole for the recursion report + /// after a failed lowering. + Reported(sv::Ir), + /// The module of an analysis of its own. + Owned(Box), +} + +/// What [`lower_specialization`] lowers a specialization from: its analysis +/// and what lowering reads of the analyzed module and the packages, made by +/// [`prepare_specialization`] on the calling thread, which may analyze it. +/// Lowering needs nothing else of the analysis, so it can run on any +/// thread. +pub(super) struct PreparedSpecialization<'a> { + name: String, + source: SpecializedSource<'a>, + implicit_nets_allowed: bool, + interface_member_paths: &'a HashMap, + force_signals: &'a [String], + four_state: bool, + ff_parts: bool, + level_lists: LevelLists<'a>, + hierarchical: HierarchicalNames<'a>, + /// The packages whose state modules may call the root's units (see + /// `out_of_line::Home`), for the root. + scope_callers: Option>, + time_precision: Result, + time_scale: Result, +} + +impl PreparedSpecialization<'_> { + /// How large lowering the specialization is: the subroutines of its + /// module, which a class library brings by the thousand. + pub(super) fn size(&self) -> usize { + match &self.source { + SpecializedSource::Shared(module) => module.subroutines().len(), + SpecializedSource::Reported(ir) => ir + .modules() + .iter() + .find(|candidate| candidate.name() == self.name) + .map_or(0, |module| module.subroutines().len()), + SpecializedSource::Owned(module) => module.subroutines().len(), + } + } +} + +/// The analysis of specialization `key` of `module`, analyzing it now when +/// neither `hierarchical` nor `owned_analysis` has it, with what lowering it +/// reads of `module` and its packages (see [`lower_specialization`]). +#[allow(clippy::too_many_arguments)] +pub(super) fn prepare_specialization<'a>( + module: &'a AnalyzedSvModule, + design: &mut sv::Design, + key: &'a LoweredSvModuleKey, + four_state: bool, + ff_parts: bool, + warnings: &mut Vec, + level_lists: LevelLists<'a>, + hierarchical: HierarchicalNames<'a>, + owned_analysis: Option, +) -> Result, sv::AnalyzerError> { #[cfg(test)] tests::record_specialization(key, level_lists); let unsupported = || sv::AnalyzerError::Unsupported(format!("module `{}`", module.name)); @@ -154,23 +238,15 @@ pub(super) fn specialize_module( .iter() .find(|candidate| candidate.name() == name) } - // The module lowered, and the same module when the recursion report - // needs it after a failed lowering (it keeps the shared analysis then). - let owned; - let (specialized, reported): ( - std::borrow::Cow<'_, sv::ir::Module>, - Option<&sv::ir::Module>, - ) = match (hierarchical.analyzed, owned_analysis) { + let source = match (hierarchical.analyzed, owned_analysis) { (Some(ir), _) => { warnings.extend(crate::warning::analyzer_warnings(ir.warnings())); - let specialized = find(ir, &module.name).ok_or_else(unsupported)?; - (std::borrow::Cow::Borrowed(specialized), Some(specialized)) + SpecializedSource::Shared(find(ir, &module.name).ok_or_else(unsupported)?) } (None, Some(ir)) if hierarchical.recursion_report.is_some() => { - owned = ir; - warnings.extend(crate::warning::analyzer_warnings(owned.warnings())); - let specialized = find(&owned, &module.name).ok_or_else(unsupported)?; - (std::borrow::Cow::Borrowed(specialized), Some(specialized)) + warnings.extend(crate::warning::analyzer_warnings(ir.warnings())); + find(&ir, &module.name).ok_or_else(unsupported)?; + SpecializedSource::Reported(ir) } (None, owned_analysis) => { let ir = match owned_analysis { @@ -199,14 +275,146 @@ pub(super) fn specialize_module( } }; warnings.extend(crate::warning::analyzer_warnings(ir.warnings())); - let specialized = ir - .into_modules() - .into_iter() - .find(|candidate| candidate.name() == module.name) - .ok_or_else(unsupported)?; - (std::borrow::Cow::Owned(specialized), None) + SpecializedSource::Owned(Box::new( + ir.into_modules() + .into_iter() + .find(|candidate| candidate.name() == module.name) + .ok_or_else(unsupported)?, + )) } }; + // The packages whose state modules may call the root's units: those + // that keep time as the root does (see `out_of_line::Home`). + let scope_callers = hierarchical.home.then(|| { + let time_scale = scope_time_scale(&module.packages, &module.name).ok(); + let mut callers: Vec = module + .packages + .names() + .filter(|package| scope_time_scale(&module.packages, package).ok() == time_scale) + .map(str::to_string) + .collect(); + callers.sort_unstable(); + callers + }); + Ok(PreparedSpecialization { + name: module.name.clone(), + source, + implicit_nets_allowed: module.implicit_nets_allowed, + interface_member_paths: &module.interface_member_paths, + force_signals: &key.force_signals, + four_state, + ff_parts, + level_lists, + hierarchical, + scope_callers, + time_precision: celox_design::TimePrecision::try_from( + module.packages.global_time_precision(), + ) + .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string())), + time_scale: scope_time_scale(&module.packages, &module.name), + }) +} + +/// Lower a specialization [`prepare_specialization`] prepared. When the +/// lowering fails and a recursion report is asked for, `report` gets the +/// report lines of the graph recorded up to the error, for the caller to +/// append (see `recursion::append_lines`). +pub(super) fn lower_specialization( + prepared: PreparedSpecialization<'_>, + warnings: &mut Vec, + report: &mut Option>, +) -> Result { + let PreparedSpecialization { + name, + source, + implicit_nets_allowed, + interface_member_paths, + force_signals, + four_state, + ff_parts, + level_lists, + hierarchical, + scope_callers, + time_precision, + time_scale, + } = prepared; + // The module lowered, and the same module when the recursion report + // needs it after a failed lowering (it keeps the shared analysis then). + let (specialized, reported): ( + std::borrow::Cow<'_, sv::ir::Module>, + Option<&sv::ir::Module>, + ) = match &source { + SpecializedSource::Shared(module) => (std::borrow::Cow::Borrowed(*module), Some(*module)), + SpecializedSource::Reported(ir) => { + let module = ir + .modules() + .iter() + .find(|candidate| candidate.name() == name) + .expect("prepared with the module"); + (std::borrow::Cow::Borrowed(module), Some(module)) + } + SpecializedSource::Owned(_) => { + let SpecializedSource::Owned(module) = source else { + unreachable!() + }; + return lower_specialized( + std::borrow::Cow::Owned(*module), + None, + &name, + implicit_nets_allowed, + interface_member_paths, + force_signals, + four_state, + ff_parts, + level_lists, + hierarchical, + scope_callers, + time_precision, + time_scale, + warnings, + report, + ); + } + }; + lower_specialized( + specialized, + reported, + &name, + implicit_nets_allowed, + interface_member_paths, + force_signals, + four_state, + ff_parts, + level_lists, + hierarchical, + scope_callers, + time_precision, + time_scale, + warnings, + report, + ) +} + +/// [`lower_specialization`] of the module `specialized`, with `reported` +/// for the recursion report after a failed lowering. +#[allow(clippy::too_many_arguments)] +fn lower_specialized( + specialized: std::borrow::Cow<'_, sv::ir::Module>, + reported: Option<&sv::ir::Module>, + name: &str, + implicit_nets_allowed: bool, + interface_member_paths: &HashMap, + force_signals: &[String], + four_state: bool, + ff_parts: bool, + level_lists: LevelLists<'_>, + hierarchical: HierarchicalNames<'_>, + scope_callers: Option>, + time_precision: Result, + time_scale: Result, + warnings: &mut Vec, + report: &mut Option>, +) -> Result { // Each module may store or wait on a watched property. let own; let properties = if matches!(hierarchical.instances, Instances::Discovery) { @@ -240,12 +448,10 @@ pub(super) fn specialize_module( } else { specialized }; - let local_forces = key - .force_signals + let local_forces = force_signals .iter() .map(|path| { - module - .interface_member_paths + interface_member_paths .iter() .find(|(_, segments)| segments.segments.join(".") == *path) .map_or_else(|| path.clone(), |(flat, _)| flat.clone()) @@ -263,31 +469,21 @@ pub(super) fn specialize_module( )); if let Some(functions) = calls.as_mut().and_then(|graph| graph.out_of_line.as_mut()) { functions.foreign = hierarchical.shared.foreign_references.clone(); - // The packages whose state modules may call the root's units: those - // that keep time as the root does (see `out_of_line::Home`). - if hierarchical.home { - let time_scale = scope_time_scale(&module.packages, &module.name).ok(); - let mut callers: Vec = module - .packages - .names() - .filter(|package| scope_time_scale(&module.packages, package).ok() == time_scale) - .map(str::to_string) - .collect(); - callers.sort_unstable(); + if let Some(callers) = scope_callers { functions.scope_callers = callers; } } let lowered = lower_module( specialized, four_state, - module.implicit_nets_allowed, + implicit_nets_allowed, ff_parts, hierarchical.next_state, warnings, &local_forces, level_lists, hierarchical.foreign_writes, - &module.interface_member_paths, + interface_member_paths, hierarchical.shared, hierarchical.same_instance_aliased, hierarchical.same_instance_alias_groups, @@ -296,19 +492,17 @@ pub(super) fn specialize_module( let mut lowered = match (lowered, &calls, hierarchical.recursion_report, reported) { (Ok(lowered), _, _, _) => lowered, // Report the graph recorded up to the error. - (Err(error), Some(graph), Some(path), Some(specialized)) => { - recursion::append(specialized, graph, path); + (Err(error), Some(graph), Some(_), Some(specialized)) => { + *report = Some(recursion::report(specialized, graph)); return Err(error); } (Err(error), ..) => return Err(error), }; lowered.calls = calls; - propagate_force_signals(&mut lowered.instances, &key.force_signals); - lowered.sim_module.time_precision = Some( - celox_design::TimePrecision::try_from(module.packages.global_time_precision()) - .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))?, - ); - lowered.sim_module.time_scale = scope_time_scale(&module.packages, &module.name)?; + propagate_force_signals(&mut lowered.instances, force_signals); + let _ = name; + lowered.sim_module.time_precision = Some(time_precision?); + lowered.sim_module.time_scale = time_scale?; Ok(lowered) } diff --git a/crates/celox-napi/src/options.rs b/crates/celox-napi/src/options.rs index afe1e3ece8..db67d95835 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 60c3fb74ef..fa1430ea70 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 2546be28c2..7710a5842e 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 ee34a74506..662ab730ff 100644 --- a/crates/celox/src/backend/native/compile_resources.rs +++ b/crates/celox/src/backend/native/compile_resources.rs @@ -15,99 +15,15 @@ pub(super) fn compile_tasks( } /// [`compile_tasks`], with state of each worker: `state` makes it in the -/// worker, once, and the worker passes it to each task it compiles. +/// worker, once, and the worker passes it to each task it compiles (see +/// [`celox_frontend_core::tasks::run_ordered_with`]). pub(super) fn compile_tasks_with( order: &[usize], workers: usize, state: impl Fn() -> S + Sync, compile: impl Fn(&mut S, usize) -> Result + Sync, ) -> std::thread::Result, E>> { - use std::sync::atomic::Ordering; - use std::sync::atomic::{AtomicBool, AtomicUsize}; - let mut results = Vec::with_capacity(order.len()); - let mut failure = None; - if workers <= 1 || order.len() <= 1 { - let mut state = state(); - for &index in order { - match compile(&mut state, index) { - Ok(result) => results.push((index, result)), - Err(error) => { - failure = Some((index, error)); - break; - } - } - } - } else { - #[expect( - clippy::disallowed_types, - reason = "cross-thread: scoped compile worker threads claim the next task index from this shared counter" - )] - let next = AtomicUsize::new(0); - #[expect( - clippy::disallowed_types, - reason = "cross-thread: the first failing scoped compile worker sets it and the other workers stop taking tasks" - )] - let stopped = AtomicBool::new(false); - std::thread::scope(|scope| { - let handles = (0..workers.min(order.len())) - .map(|_| { - let next = &next; - let stopped = &stopped; - let state = &state; - let compile = &compile; - scope.spawn(move || { - let mut state = state(); - let mut results = Vec::new(); - let mut failure = None; - while !stopped.load(Ordering::Relaxed) { - let position = next.fetch_add(1, Ordering::Relaxed); - let Some(&index) = order.get(position) else { - break; - }; - match compile(&mut state, index) { - Ok(result) => results.push((index, result)), - Err(error) => { - stopped.store(true, Ordering::Relaxed); - failure = Some((index, error)); - break; - } - } - } - (results, failure) - }) - }) - .collect::>(); - let mut panic = None; - for handle in handles { - match handle.join() { - Ok((completed, failed)) => { - results.extend(completed); - // Of the tasks that failed before the others - // stopped, the first by index. - if let Some(failed) = failed - && failure.as_ref().is_none_or(|(index, _)| failed.0 < *index) - { - failure = Some(failed); - } - } - Err(error) => { - if panic.is_none() { - panic = Some(error); - } - } - } - } - match panic { - Some(error) => Err(error), - None => Ok(()), - } - })?; - } - if let Some((_, error)) = failure { - return Ok(Err(error)); - } - results.sort_unstable_by_key(|(index, _)| *index); - Ok(Ok(results.into_iter().map(|(_, result)| result).collect())) + celox_frontend_core::tasks::run_ordered_with(order, workers, state, compile) } /// What compiling a unit of `blocks` blocks and `instructions` instructions @@ -127,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, @@ -143,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 { @@ -175,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 997ac803ab..575b9e0458 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 adccadc3b2..9e1d4daeda 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 84b4aa9c2b..68145ac4d6 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 5887160334..e38962bc6e 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 ecd5a8cfab..5a03fc8d75 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 d67c828d72..40011e4b33 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 ad58b58f65..54cc7923b2 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 911be469ba..ed21cfde70 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 16e393fd2c..d6f8c5ed46 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