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/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/packages.rs b/crates/celox-frontend-sv/src/lowering/packages.rs index b4d21ad650..820728b624 100644 --- a/crates/celox-frontend-sv/src/lowering/packages.rs +++ b/crates/celox-frontend-sv/src/lowering/packages.rs @@ -91,6 +91,15 @@ 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>, +} + pub(super) fn lower_package_states( states: PackageStates, first: usize, @@ -105,99 +114,150 @@ 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. + let order = (0..states.len()).collect::>(); + let lowerings = celox_frontend_core::tasks::run_owned::<_, _, std::convert::Infallible>( + states, + &order, + 1, + |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 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/src/backend/native/compile_resources.rs b/crates/celox/src/backend/native/compile_resources.rs index ee34a74506..0f97bef9e8 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