diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index f03fd8c924f..0f272283820 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -328,6 +328,7 @@ fn interface_signatures_collecting( &[], LevelLists::Processes, &HashMap::default(), + SharedAlways::default(), )?; Ok(InterfaceSignature { name: prototype.name, @@ -940,6 +941,7 @@ fn lower_package_states( &[], LevelLists::Processes, &HashMap::default(), + SharedAlways::default(), )?; lowered.sim_module.time_precision = Some( celox_design::TimePrecision::try_from(packages.global_time_precision()) @@ -1211,6 +1213,297 @@ fn shared_edge_memories( memories } +/// How `always @*` blocks that write a common variable run. +#[derive(Clone, Copy)] +struct SharedAlways<'a> { + /// Make a variable a temporary of each block when that is unobservable + /// within the module (the `shared_always_temporary` diagnostic; see + /// [`share_always_variables`]). + temporaries: bool, + /// The module's signals that hierarchical names in other modules denote. + foreign_references: &'a HashSet, +} + +impl Default for SharedAlways<'_> { + fn default() -> Self { + static EMPTY: std::sync::LazyLock> = + std::sync::LazyLock::new(HashSet::default); + Self { + temporaries: false, + foreign_references: &EMPTY, + } + } +} + +/// `module` with its `always @*` blocks that write a common variable +/// rearranged, and the variables they write together as processes, or +/// `None` when no blocks write a common variable. +/// +/// Several plain `always` processes may write one variable (IEEE 1800-2023 +/// 6.5, 9.2.2), such as a loop index, and each block waits on the variables +/// it reads, a shared one included (9.4.2.2). So the blocks run as +/// processes, whose writes wake the other blocks as the standard requires: +/// a block that keeps waking another never settles, and the simulation +/// reports the time and the processes. +/// +/// With `shared.temporaries`, a variable becomes a temporary of each block +/// instead when only such blocks write it, each writes it before it reads +/// it on every path, and nothing else reads it: no other process, +/// continuous assignment, subroutine, port, instance connection or +/// hierarchical name. Its writes then wake no other block, unlike in the +/// standard, and the variable itself keeps its initial value. +fn share_always_variables( + module: &sv::ir::Module, + constants: &HashMap, + parameter_types: &HashMap, + shared: SharedAlways<'_>, + warnings: &mut Vec, +) -> Option<(sv::ir::Module, HashSet)> { + let comb = module.comb_processes(); + let mut shared_names = HashSet::default(); + let drivers = ModuleDrivers::new(module, constants, parameter_types); + let mut processes = HashSet::default(); + let mut temporaries: Vec<(&sv::ir::Signal, Vec)> = Vec::new(); + for signal in module.signals().iter().filter(|signal| !signal.is_net()) { + let mut writers: Vec = drivers + .local(signal.name()) + .iter() + .map(|(driver, _)| *driver) + .collect(); + writers.sort_unstable(); + writers.dedup(); + if writers.len() < 2 + || !writers.iter().all(|&driver| { + comb.get(driver) + .is_some_and(|process| process.kind() == sv::ir::CombProcessKind::AlwaysStar) + }) + { + continue; + } + if shared.temporaries + && !shared.foreign_references.contains(signal.name()) + && !read_outside(module, signal.name(), &writers) + && writers.iter().all(|&driver| { + written_before_read(comb[driver].body(), signal.name(), false) == Some(true) + }) + { + temporaries.push((signal, writers)); + } else { + processes.extend(writers); + shared_names.insert(signal.name().to_string()); + } + } + if processes.is_empty() && temporaries.is_empty() { + return None; + } + let mut module = module.clone(); + let mut renames: HashMap> = HashMap::default(); + for (signal, writers) in &temporaries { + let mut sites: Vec = writers + .iter() + .filter_map(|&driver| driver_site(&module, driver)) + .collect(); + sites.sort_unstable(); + warnings.push(( + crate::FrontendWarningKind::SharedAlwaysTemporary { + module: module.name().into(), + signal: signal.name().into(), + blocks: sites.join(", "), + }, + comb[writers[0]].site().cloned(), + )); + for &driver in writers { + let local = format!("{}$always{driver}", signal.name()); + module = module.add_local(sv::ir::LocalVariable { + name: local.clone(), + source_name: signal.name().into(), + r#type: signal.r#type().clone(), + }); + renames + .entry(driver) + .or_default() + .insert(signal.name().into(), local); + } + } + let module = module.map_comb_process_bodies(|index, body, sensitivity| { + let Some(renames) = renames.get(&index) else { + return body; + }; + let mut renamed: Vec = Vec::new(); + if !sensitivity { + // Each run starts a new temporary. + let mut locals: Vec<&String> = renames.values().collect(); + locals.sort_unstable(); + renamed.extend(locals.into_iter().map(|name| sv::ir::Stmt::Local { + name: name.clone(), + init: None, + })); + } + renamed.extend(body.into_iter().map(|stmt| { + stmt.map( + &mut |expr| ff::rename_idents(&expr, renames), + &mut |lvalue| rename_lvalue(lvalue, renames), + ) + })); + renamed + }); + Some(( + module.run_comb_processes_as_processes(|index, _| processes.contains(&index)), + shared_names, + )) +} + +/// `lvalue` with the identifiers in `renames` replaced. +fn rename_lvalue(lvalue: sv::ir::LValue, renames: &HashMap) -> sv::ir::LValue { + match lvalue { + sv::ir::LValue::Ident(name) => { + sv::ir::LValue::Ident(renames.get(&name).cloned().unwrap_or(name)) + } + sv::ir::LValue::Select { + name, + msb, + lsb, + array_slice_width, + array_slice_reversed, + } => sv::ir::LValue::Select { + name: renames.get(&name).cloned().unwrap_or(name), + msb: ff::rename_const_idents(&msb, renames), + lsb: ff::rename_const_idents(&lsb, renames), + array_slice_width: array_slice_width + .map(|width| ff::rename_const_idents(&width, renames)), + array_slice_reversed, + }, + } +} + +/// Whether `stmts` mention `name`, read or written. +fn stmts_mention(stmts: &[sv::ir::Stmt], name: &str) -> bool { + let renames: HashMap = + std::iter::once((name.to_string(), format!("{name}$"))).collect(); + stmts.iter().any(|stmt| { + let found = std::cell::Cell::new(false); + stmt.clone().map( + &mut |expr| { + found.set(found.get() || ff::rename_idents(&expr, &renames) != expr); + expr + }, + &mut |lvalue| { + found.set(found.get() || rename_lvalue(lvalue.clone(), &renames) != lvalue); + lvalue + }, + ); + found.get() + }) +} + +/// Whether something other than the processes `writers` (indices among the +/// combinational processes) of `module` reads or writes `name`. +fn read_outside(module: &sv::ir::Module, name: &str, writers: &[usize]) -> bool { + let renames: HashMap = + std::iter::once((name.to_string(), format!("{name}$"))).collect(); + let mentions = |expr: &sv::ir::Expr| ff::rename_idents(expr, &renames) != *expr; + module.ports().iter().any(|port| port.name() == name) + || module + .comb_processes() + .iter() + .enumerate() + .filter(|(index, _)| !writers.contains(index)) + .any(|(_, process)| { + stmts_mention(process.body(), name) + || stmts_mention(process.sensitivity_body(), name) + }) + || module + .ff_processes() + .iter() + .any(|process| stmts_mention(process.body(), name)) + || module + .initial_processes() + .iter() + .any(|process| stmts_mention(process.body(), name)) + || module + .subroutines() + .iter() + .any(|subroutine| stmts_mention(&subroutine.body, name)) + || module + .assignments() + .iter() + .any(|assignment| assignment.lhs() == name || mentions(assignment.rhs())) + || module.instances().iter().any(|instance| { + instance.port_connections().iter().any(|connection| { + connection.actual() == name || connection.actual_expr().is_some_and(mentions) + }) + }) +} + +/// Whether every path through `stmts` writes the whole of `name` before it +/// reads it: `Some` with whether `name` is written when they end, or `None` +/// when a read may come before the write. `assigned` says whether it is +/// written when they start. +fn written_before_read(stmts: &[sv::ir::Stmt], name: &str, mut assigned: bool) -> Option { + use sv::ir::Stmt; + let reads = |stmt: &Stmt| stmts_mention(std::slice::from_ref(stmt), name); + for stmt in stmts { + assigned = match stmt { + Stmt::Assign { lhs, rhs, .. } => { + let whole = matches!(lhs, sv::ir::LValue::Ident(target) if target == name); + let probe = Stmt::Eval(rhs.clone()); + let index_reads = !whole + && matches!(lhs, sv::ir::LValue::Select { .. }) + && lhs.name() != name + && reads(stmt); + if !assigned && (reads(&probe) || index_reads) { + return None; + } + assigned || whole + } + Stmt::If { + condition, + then_body, + else_body, + } => { + if !assigned && reads(&Stmt::Eval(condition.clone())) { + return None; + } + let then_assigned = written_before_read(then_body, name, assigned)?; + let else_assigned = written_before_read(else_body, name, assigned)?; + then_assigned && else_assigned + } + Stmt::Loop { + kind, + init, + condition, + step, + body, + } => { + let initialized = written_before_read(init, name, assigned)?; + let header = Stmt::Loop { + kind: kind.clone(), + init: Vec::new(), + condition: condition.clone(), + step: Vec::new(), + body: Vec::new(), + }; + if !initialized && reads(&header) { + return None; + } + // The body and the step may not run. + let after_body = written_before_read(body, name, initialized)?; + written_before_read(step, name, after_body)?; + initialized + } + Stmt::Break | Stmt::Continue => assigned, + // Other statements, case statements included, only read here. + _ => { + if !assigned && reads(stmt) { + return None; + } + assigned + } + }; + } + Some(assigned) +} + /// Variables, other than unpacked arrays, that several plain edge-triggered /// `always` processes write only by blocking assignments, such as a loop /// index they share. A variable may have several procedural writers, and the @@ -1594,8 +1887,19 @@ fn validate_variable_driver_ranges( }) }); if overlapping_continuous || (has_overlap && !shared.contains(signal_name)) { + let mut sites: Vec = local + .iter() + .filter_map(|(driver, _)| driver_site(module, *driver)) + .collect(); + sites.sort_unstable(); + sites.dedup(); + let at = if sites.is_empty() { + String::new() + } else { + format!(", written at {}", sites.join(", ")) + }; return Err(sv::AnalyzerError::Unsupported(format!( - "multiple variable drivers for `{signal_name}`" + "multiple variable drivers for `{signal_name}`{at}" ))); } } @@ -1855,6 +2159,30 @@ impl ModuleDrivers { } } +/// Where process `driver` of [`ModuleDrivers::local`] is written, as +/// `path:line` or `path:line:column`. +fn driver_site(module: &sv::ir::Module, driver: usize) -> Option { + let combinational = module.comb_processes().len(); + let edge = combinational + module.ff_processes().len(); + if let Some(process) = module.comb_processes().get(driver) { + return process + .site() + .map(|site| format!("{}:{}", site.logical_path.display(), site.line)); + } + if driver < edge { + return module.ff_processes()[driver - combinational] + .site() + .map(ToString::to_string); + } + module + .initial_processes() + .iter() + .filter(|process| process.repeats()) + .nth(driver - edge) + .and_then(|process| process.site()) + .map(ToString::to_string) +} + /// Whether process `driver` of [`ModuleDrivers::local`] must be the only writer of /// the variables it writes: an `always_comb` or continuous assignment, an /// edge procedure, or an `always_ff` run as a process, but not another @@ -2878,6 +3206,7 @@ fn schedule_sources_collecting( // the order the modules are lowered in. let mut references = HashMap::default(); let mut analyses = HashMap::default(); + let mut foreign_references: HashMap> = HashMap::default(); let mut foreign_writes: HashMap> = HashMap::default(); for &module_id in &hierarchical_modules { @@ -2907,6 +3236,14 @@ fn schedule_sources_collecting( if let Some(module) = ir.modules().iter().find(|module| module.name() == key.name) { hierarchy::collect_foreign_writes(module, &resolved, &mut foreign_writes); } + for reference in &resolved { + for (target_module, target) in &reference.targets { + foreign_references + .entry(*target_module) + .or_default() + .insert(target.clone()); + } + } references.insert(module_id, resolved); analyses.insert(module_id, ir); } @@ -2921,6 +3258,7 @@ fn schedule_sources_collecting( let mut demoted: HashMap> = HashMap::default(); let mut trace = trace; let no_foreign_writes = HashMap::default(); + let no_foreign_references = HashSet::default(); loop { let mut specialize = |key: &LoweredSvModuleKey, module_id: ModuleId| @@ -2947,6 +3285,12 @@ fn schedule_sources_collecting( HierarchicalNames { signals: &signals, foreign_writes: foreign_writes.get(&module_id).unwrap_or(&no_foreign_writes), + shared: SharedAlways { + temporaries: analysis_options.shared_always_temporaries, + foreign_references: foreign_references + .get(&module_id) + .unwrap_or(&no_foreign_references), + }, analyzed: analyses.get(&module_id), }, )?) @@ -3286,6 +3630,7 @@ fn specialize_module( &local_forces, level_lists, hierarchical.foreign_writes, + hierarchical.shared, )?; propagate_force_signals(&mut lowered.instances, &key.force_signals); lowered.sim_module.time_precision = Some( @@ -3304,6 +3649,8 @@ struct HierarchicalNames<'a> { signals: &'a [sv::ast::HierarchicalSignal], /// The module's signals that names in other modules write. foreign_writes: &'a HashMap, + /// How `always @*` blocks that write a common variable run. + shared: SharedAlways<'a>, /// The analysis of the module with `signals`, if it is done already. analyzed: Option<&'a sv::Ir>, } @@ -3315,6 +3662,7 @@ impl Default for HierarchicalNames<'_> { Self { signals: &[], foreign_writes: &EMPTY, + shared: SharedAlways::default(), analyzed: None, } } @@ -3399,6 +3747,7 @@ fn lower_module( force_signals: &[String], level_lists: LevelLists<'_>, foreign_writes: &HashMap, + shared: SharedAlways<'_>, ) -> Result { lower_module_with_overrides( module, @@ -3410,6 +3759,7 @@ fn lower_module( force_signals, level_lists, foreign_writes, + shared, ) } @@ -3492,9 +3842,13 @@ fn lower_module_with_overrides( force_signals: &[String], level_lists: LevelLists<'_>, foreign_writes: &HashMap, + shared: SharedAlways<'_>, ) -> Result { let parameter_types = module_parameter_types(module); let constants = module_constants_with_overrides(module, parameter_overrides); + let sharing = share_always_variables(module, &constants, ¶meter_types, shared, warnings); + let module = sharing.as_ref().map_or(module, |(module, _)| module); + let shared_process_variables = sharing.as_ref().map(|(_, names)| names); let fallbacks = module .ff_processes() .iter() @@ -3530,7 +3884,11 @@ fn lower_module_with_overrides( let drivers = ModuleDrivers::new(module, &constants, ¶meter_types); let shared_memories = shared_edge_memories(module, &drivers, foreign_writes, warnings); let shared_variables = shared_edge_variables(module, &drivers); - let shared_all = shared_memories.union(&shared_variables).cloned().collect(); + let shared_all = shared_memories + .union(&shared_variables) + .chain(shared_process_variables.into_iter().flatten()) + .cloned() + .collect(); validate_variable_driver_ranges(module, &drivers, &shared_all)?; validate_foreign_drivers(module, &drivers, &shared_memories, foreign_writes)?; let scheduled = module diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 26ef54d8fb1..3b2ce8ff325 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -6433,62 +6433,73 @@ fn impure_call(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option { } /// `expr` with the identifiers in `renames` replaced. -fn rename_idents(expr: &sv::ir::Expr, renames: &HashMap) -> sv::ir::Expr { - fn constant(expr: &sv::ir::ConstExpr, renames: &HashMap) -> sv::ir::ConstExpr { - use sv::ir::ConstExpr; - let go = |expr: &ConstExpr| Box::new(constant(expr, renames)); - match expr { - ConstExpr::Ident(name) => ConstExpr::Ident(renames.get(name).unwrap_or(name).clone()), - ConstExpr::Literal(_) => expr.clone(), - ConstExpr::SelectRange { - expr, - msb, - lsb, - signed, - } => ConstExpr::SelectRange { - expr: go(expr), - msb: go(msb), - lsb: go(lsb), - signed: *signed, - }, - ConstExpr::Select { expr, bit } => ConstExpr::Select { - expr: go(expr), - bit: go(bit), - }, - ConstExpr::Function { callee, args, site } => ConstExpr::Function { - callee: callee.clone(), - site: *site, - args: args.iter().map(|arg| constant(arg, renames)).collect(), - }, - ConstExpr::Resize { - expr, - width, - signed, - } => ConstExpr::Resize { - expr: go(expr), - width: *width, - signed: *signed, - }, - ConstExpr::Unary { op, expr } => ConstExpr::Unary { - op: *op, - expr: go(expr), - }, - ConstExpr::Binary { left, op, right } => ConstExpr::Binary { - left: go(left), - op: *op, - right: go(right), - }, - ConstExpr::Mux { - condition, - then_expr, - else_expr, - } => ConstExpr::Mux { - condition: go(condition), - then_expr: go(then_expr), - else_expr: go(else_expr), - }, - } +pub(super) fn rename_const_idents( + expr: &sv::ir::ConstExpr, + renames: &HashMap, +) -> sv::ir::ConstExpr { + use sv::ir::ConstExpr; + let go = |expr: &ConstExpr| Box::new(rename_const_idents(expr, renames)); + match expr { + ConstExpr::Ident(name) => ConstExpr::Ident(renames.get(name).unwrap_or(name).clone()), + ConstExpr::Literal(_) => expr.clone(), + ConstExpr::SelectRange { + expr, + msb, + lsb, + signed, + } => ConstExpr::SelectRange { + expr: go(expr), + msb: go(msb), + lsb: go(lsb), + signed: *signed, + }, + ConstExpr::Select { expr, bit } => ConstExpr::Select { + expr: go(expr), + bit: go(bit), + }, + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee: callee.clone(), + site: *site, + args: args + .iter() + .map(|arg| rename_const_idents(arg, renames)) + .collect(), + }, + ConstExpr::Resize { + expr, + width, + signed, + } => ConstExpr::Resize { + expr: go(expr), + width: *width, + signed: *signed, + }, + ConstExpr::Unary { op, expr } => ConstExpr::Unary { + op: *op, + expr: go(expr), + }, + ConstExpr::Binary { left, op, right } => ConstExpr::Binary { + left: go(left), + op: *op, + right: go(right), + }, + ConstExpr::Mux { + condition, + then_expr, + else_expr, + } => ConstExpr::Mux { + condition: go(condition), + then_expr: go(then_expr), + else_expr: go(else_expr), + }, } +} + +/// `expr` with the identifiers in `renames` replaced. +pub(super) fn rename_idents( + expr: &sv::ir::Expr, + renames: &HashMap, +) -> sv::ir::Expr { use sv::ir::Expr; let go = |expr: &Expr| Box::new(rename_idents(expr, renames)); match expr { @@ -6501,8 +6512,8 @@ fn rename_idents(expr: &sv::ir::Expr, renames: &HashMap) -> sv:: signed, } => Expr::Select { expr: go(expr), - msb: constant(msb, renames), - lsb: constant(lsb, renames), + msb: rename_const_idents(msb, renames), + lsb: rename_const_idents(lsb, renames), signed: *signed, }, Expr::Concat(parts) => Expr::Concat( @@ -6512,7 +6523,7 @@ fn rename_idents(expr: &sv::ir::Expr, renames: &HashMap) -> sv:: .collect(), ), Expr::RepeatConcat { count, parts } => Expr::RepeatConcat { - count: constant(count, renames), + count: rename_const_idents(count, renames), parts: parts .iter() .map(|part| rename_idents(part, renames)) diff --git a/crates/celox-frontend-sv/src/warning.rs b/crates/celox-frontend-sv/src/warning.rs index 4d5752d35ce..3229df12676 100644 --- a/crates/celox-frontend-sv/src/warning.rs +++ b/crates/celox-frontend-sv/src/warning.rs @@ -61,6 +61,18 @@ pub enum FrontendWarningKind { /// IEEE 1800-2023 24.7 ignores. #[error("`$exit` outside a program block is ignored")] ExitOutsideProgram, + /// A variable that only several `always @*` blocks write is a temporary + /// of each block, so its writes do not wake the other blocks as IEEE + /// 1800-2023 9.4.2.2 requires. Applied only when the diagnostic is not + /// an error. + #[error( + "`{signal}` in `{module}` is treated as a temporary of each `always @*` block that writes it ({blocks}): its writes do not wake the other blocks" + )] + SharedAlwaysTemporary { + module: String, + signal: String, + blocks: String, + }, } /// Where a warning is in the source. @@ -160,6 +172,7 @@ impl miette::Diagnostic for FrontendWarning { FrontendWarningKind::InferredLatch => "inferred_latch", FrontendWarningKind::MemoryFileWordCount { .. } => "memory_file_word_count", FrontendWarningKind::ExitOutsideProgram => "exit_outside_program", + FrontendWarningKind::SharedAlwaysTemporary { .. } => "shared_always_temporary", })) } @@ -190,6 +203,9 @@ impl miette::Diagnostic for FrontendWarning { FrontendWarningKind::ExitOutsideProgram => { "end the simulation with `$finish`, or remove the call" } + FrontendWarningKind::SharedAlwaysTemporary { .. } => { + "a language deviation enabled by shared_always_temporary=warn or allow; declare the variable inside each block to keep IEEE 1800-2023 semantics" + } })) } diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 0a57c8a08b0..449e3d88d70 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -165,6 +165,11 @@ pub struct SimulationState { return_budget: u64, /// Rounds and process-phase passes the current time slot has run. slot_passes: u64, + /// The processes the current time slot ran, most recent last, up to + /// [`RESUMED_PROCESSES`]: the ones a slot that does not settle reports. + slot_resumed: std::collections::VecDeque, + /// Names of the processes for diagnostics, by index. + process_names: Vec, /// The loop that runs time slots, and the slots each loop ran. stats: SchedulerStats, /// The bits of the compiled scheduler's events whose changes the host @@ -173,6 +178,10 @@ pub struct SimulationState { observed_events: u64, } +/// The most recent processes of a time slot that a slot that does not +/// settle reports. +const RESUMED_PROCESSES: usize = 64; + impl SimulationState { /// Bound the work of one time slot: `rounds` rounds and passes of the /// process phase, and `returns` kernel returns per round, before a step @@ -183,6 +192,12 @@ impl SimulationState { self.return_budget = returns; } + /// Name the processes, by index, in diagnostics such as a time slot + /// that does not settle. + pub fn set_process_names(&mut self, names: Vec) { + self.process_names = names; + } + /// Every process of `model` starts at time zero, in list order. pub fn new(backend: &B, model: ResolvedSchedule) -> Self { let process_state = ProcessState { @@ -227,6 +242,8 @@ impl SimulationState { round_budget: SLOT_ROUND_BUDGET, return_budget: SLOT_RETURN_BUDGET, slot_passes: 0, + slot_resumed: std::collections::VecDeque::new(), + process_names: Vec::new(), stats: SchedulerStats::default(), observed_events: 0, }; @@ -484,6 +501,7 @@ impl SimulationState { E: SimulationExecutor, { self.slot_passes = 0; + self.slot_resumed.clear(); match self.step_round(executor, time, Vec::new(), Vec::new(), true, false) { Ok(()) => { self.finish_timed_boundary(executor, time)?; diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index 3716a3a3721..d169a133db1 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -5,10 +5,10 @@ use std::collections::BTreeSet; use celox_design::{HostRequestKind, ProcessStatus}; -use super::SimulationState; use super::host::SimulationExecutor; use super::round::Round; use super::wait::wake_in_region; +use super::{RESUMED_PROCESSES, SimulationState}; use crate::{ SimulatorErrorCode, backend::SimBackend, @@ -127,6 +127,10 @@ impl SimulationState { where E: SimulationExecutor, { + if self.slot_resumed.len() == RESUMED_PROCESSES { + self.slot_resumed.pop_front(); + } + self.slot_resumed.push_back(process); let kernel = self.restore_activation(executor.backend_mut(), process); let result = self.run_activation(executor, current_time, process, kernel, returns); self.save_activation(executor.backend(), process); diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index a48ba7bd963..03cce208edc 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -146,6 +146,7 @@ impl SimulationState { { self.host_pending = false; self.slot_passes = 0; + self.slot_resumed.clear(); let events_to_process = if self.scheduler.next_event_time() == Some(current_time) { self.scheduler .pop_all_at_next_time() @@ -245,15 +246,32 @@ impl SimulationState { if returns <= budget { return Ok(()); } + let name = |process: usize| { + self.process_names + .get(process) + .cloned() + .unwrap_or_else(|| format!("process {process}")) + }; Err(Halt::Error(SimulatorErrorCode::Runtime { message: match process { Some(process) => { - format!("process {process} does not suspend within one time slot") + format!("{} does not suspend within one time slot", name(process)) + } + None => { + let mut resumed: Vec = self.slot_resumed.iter().copied().collect(); + resumed.sort_unstable(); + resumed.dedup(); + let resumed: Vec = resumed.into_iter().map(name).collect(); + format!( + "time {} does not settle: processes keep resuming{}", + self.scheduler.time, + if resumed.is_empty() { + String::new() + } else { + format!(": {}", resumed.join(", ")) + } + ) } - None => format!( - "time {} does not settle: processes keep resuming", - self.scheduler.time - ), }, signals: Vec::new(), })) diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 9472313a755..2633aecc25f 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2416,6 +2416,12 @@ pub struct CombProcess { } impl CombProcess { + /// Where an `always` procedure is written, for diagnostics about it as + /// a process. + pub fn process_site(&self) -> Option<&crate::procedural::ProcessSite> { + self.process_site.as_ref() + } + pub fn site(&self) -> Option<&crate::procedural::SourceSpan> { self.site.as_ref() } diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index f094e067c62..2e3d545c248 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -136,6 +136,77 @@ impl Module { self } + /// Run selected `always @*` processes, by index among + /// [`Self::comb_processes`], as ordinary processes that wait on their + /// implicit event expression (IEEE 1800-2023 9.4.2.2) before each run of + /// their statement. + pub fn run_comb_processes_as_processes( + mut self, + mut select: impl FnMut(usize, &CombProcess) -> bool, + ) -> Self { + let mut retained = Vec::new(); + for (index, process) in std::mem::take(&mut self.comb_processes) + .into_iter() + .enumerate() + { + if process.kind != CombProcessKind::AlwaysStar || !select(index, &process) { + retained.push(process); + continue; + } + // The reads of branches that constant folding removed count too. + let reads = process + .body + .iter() + .chain(&process.sensitivity_body) + .cloned() + .collect(); + let mut body = vec![Stmt::WaitImplicit(reads)]; + body.extend(process.body); + self.initial_processes.push(InitialProcess { + creation_order: process.creation_order, + site: process.process_site, + scheduled_edge: false, + condition: process.condition, + body: vec![Stmt::Loop { + kind: LoopKind::Forever, + init: Vec::new(), + condition: None, + step: Vec::new(), + body, + }], + kind: celox_design::ProcessKind::Regular, + synthetic: false, + repeats: true, + }); + } + self.comb_processes = retained; + self.initial_processes + .sort_by_key(|process| (!process.is_initializer(), process.creation_order)); + self + } + + /// Rewrite the statements of the combinational processes, by index + /// among [`Self::comb_processes`]: their bodies, and the statements that + /// only describe their implicit sensitivity (`true`; see + /// [`CombProcess::sensitivity_body`]). + pub fn map_comb_process_bodies( + mut self, + mut rewrite: impl FnMut(usize, Vec, bool) -> Vec, + ) -> Self { + for (index, process) in self.comb_processes.iter_mut().enumerate() { + process.body = rewrite(index, std::mem::take(&mut process.body), false); + process.sensitivity_body = + rewrite(index, std::mem::take(&mut process.sensitivity_body), true); + } + self + } + + /// Declare a variable local to a procedural block (see [`Self::locals`]). + pub fn add_local(mut self, local: LocalVariable) -> Self { + self.locals.push(local); + self + } + /// Represent selected [`InitialProcess::level_sensitive`] processes as /// `always @*`. The caller selects a process only when its list is the /// implicit event expression of its statement (IEEE 1800-2023 9.4.2.2). @@ -1036,6 +1107,9 @@ impl LValue { pub struct CombProcess { creation_order: usize, site: Option, + /// Where an `always` procedure is written, for diagnostics about it as + /// a process. + process_site: Option, kind: CombProcessKind, condition: Option, assignments: Vec, @@ -1048,6 +1122,11 @@ impl CombProcess { self.site.as_ref() } + /// Where an `always` procedure is written, as a process. + pub fn process_site(&self) -> Option<&ProcessSite> { + self.process_site.as_ref() + } + /// Reads removed from executable branches still affect implicit sensitivity. pub fn sensitivity_body(&self) -> &[Stmt] { &self.sensitivity_body @@ -1067,6 +1146,7 @@ impl CombProcess { Self { creation_order: 0, site: None, + process_site: None, sensitivity_body: Vec::new(), kind, condition, @@ -1567,6 +1647,7 @@ impl From for CombProcess { ); result.creation_order = process.creation_order(); result.site = process.site().cloned(); + result.process_site = process.process_site().cloned(); result.sensitivity_body = process .sensitivity_body() .iter() diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 07f42be06d6..272ca8701c9 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -48,6 +48,12 @@ pub const DIV_ZERO_UNKNOWN_LITERAL: &str = "$celox_div_zero_unknown"; #[derive(Debug, Clone, Copy, Default)] pub struct AnalysisOptions { pub allow_mixed_timescales: bool, + /// Treat a variable that only several `always @*` blocks write, each + /// before it reads it, and that nothing else reads, as a temporary of + /// each block, instead of a variable whose writes wake the other blocks + /// (IEEE 1800-2023 9.4.2.2). Off by default; see the + /// `shared_always_temporary` diagnostic. + pub shared_always_temporaries: bool, /// Default unit/precision exponents; precision also bounds global resolution. pub default_timescale: Option<(i32, i32)>, } diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index 0485e6b8ab0..c1363dfc0ff 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -123,9 +123,45 @@ (assert_eq prev 8) (assert_eq i_q 8)) +; Level-sensitive always processes may share a variable as well (IEEE +; 1800-2023 6.5, 9.2.2), and each waits on the variables it reads (9.4.2.2): +; here the second block's writes to `j` wake the first one, which reads it, +; while the first block's loop writes wake nothing. Which block writes `j` +; last is not defined, so the output leaves it out. +(case level_processes_share_a_written_variable + (source "shared_level.sv" #" + module Top; + logic [3:0] a, b; + logic any_a, any_b; + integer j; + always @(*) begin + any_a = 1'b0; + for (j = 0; j < 4; j = j + 1) any_a = any_a | a[j]; + end + always @(*) begin + j = 0; + any_b = b[1]; + end + initial begin + a = 4'b0000; + b = 4'b0000; + #1 $display("%b %b", any_a, any_b); + a = 4'b0100; + #1 $display("%b %b", any_a, any_b); + b = 4'b0010; + #1 $display("%b %b", any_a, any_b); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "0 0\n1 0\n1 1\n")) + ; Processes of different clocks share a variable. A write at one edge is ; visible to a process of a later edge, and survives a coincident edge whose ; process does not write the variable. + (case edge_processes_of_two_clocks_share_a_blocking_variable (source "shared_clocks.sv" #" module Top(input logic ca, input logic cb, input logic en, diff --git a/crates/celox/src/diagnostic_policy.rs b/crates/celox/src/diagnostic_policy.rs index dc58a639307..da074f8c789 100644 --- a/crates/celox/src/diagnostic_policy.rs +++ b/crates/celox/src/diagnostic_policy.rs @@ -85,6 +85,7 @@ impl DiagnosticPolicy { if matches!( code, "mixed_timescale" + | "shared_always_temporary" | "interface_array_query" | "unpacked_port_default" | "multiple_always_ff_drivers" @@ -104,6 +105,8 @@ impl DiagnosticPolicy { ) -> celox_frontend_sv::AnalysisOptions { celox_frontend_sv::AnalysisOptions { allow_mixed_timescales: self.level("mixed_timescale") != DiagnosticLevel::Error, + shared_always_temporaries: self.level("shared_always_temporary") + != DiagnosticLevel::Error, default_timescale: timescale.map(|scale| (scale.unit, scale.precision)), } } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index dfc7e05abd1..0cd6e820705 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -437,10 +437,20 @@ impl Simulation { // ── Generic methods available for any backend ─────────────────────── pub(crate) fn simulation_state(simulator: &Simulator) -> SimulationState { - SimulationState::new( + let mut state = SimulationState::new( &simulator.backend, ResolvedSchedule::resolve(&simulator.backend, &simulator.schedule), - ) + ); + state.set_process_names( + simulator + .program + .runtime_schema + .process_origins + .iter() + .map(ToString::to_string) + .collect(), + ); + state } impl Simulation { diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index b2a107ed0f8..fea304effca 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -270,3 +270,135 @@ sv_backends! { @case "procedural::initial_while_loops_define_the_state"; } } + +/// Two `always @*` blocks that use a module-level variable as their loop +/// index (#2129). Each block's writes to `j` wake the other, which reads it +/// (IEEE 1800-2023 9.4.2.2), so the blocks never settle. +const SHARED_INDEX: &str = r#"`timescale 1ns/1ns +module top; + reg [3:0] a = 4'b0000; + reg [3:0] b = 4'b0000; + reg any_a, any_b; + integer j; + always @(*) begin + any_a = 1'b0; + for (j = 0; j < 4; j = j + 1) any_a = any_a | a[j]; + end + always @(*) begin + any_b = 1'b0; + for (j = 0; j < 4; j = j + 1) any_b = any_b | b[j]; + end + initial begin + #1 a = 4'b0100; + #1 b = 4'b0010; + #1 $display("%b %b", any_a, any_b); + $finish; + end +endmodule +"#; + +fn shared_index( + source: &str, + level: Option, +) -> Result { + let mut policy = celox::DiagnosticPolicy::default(); + if let Some(level) = level { + policy.set("shared_always_temporary", level); + } + celox::Simulation::from_sv_sources(vec![(source, Path::new("shared.sv"))], "top") + .diagnostic_policy(policy) + .build() +} + +fn display_lines(sim: &mut celox::Simulation) -> Vec { + sim.drain_runtime_events() + .into_iter() + .filter_map(|event| match event { + celox::RuntimeEvent::Display { message } => { + Some(String::from_utf8_lossy(&message).into_owned()) + } + _ => None, + }) + .collect() +} + +/// The time the blocks keep waking each other, and both blocks. +fn assert_does_not_settle(mut sim: celox::Simulation) { + let error = sim.run_until(10).unwrap_err().to_string(); + assert!(error.contains("does not settle"), "{error}"); + assert!(error.contains("shared.sv:7:"), "{error}"); + assert!(error.contains("shared.sv:11:"), "{error}"); +} + +#[test] +fn level_blocks_sharing_a_loop_index_do_not_settle() { + assert_does_not_settle(shared_index(SHARED_INDEX, None).unwrap()); +} + +#[test] +fn shared_always_temporary_runs_each_block_with_its_own_index() { + // Icarus 13 prints `1 1`: it does not wake a block on the other's writes. + for four_state in [false, true] { + let mut policy = celox::DiagnosticPolicy::default(); + policy.set("shared_always_temporary", celox::DiagnosticLevel::Allow); + let mut sim = + celox::Simulation::from_sv_sources(vec![(SHARED_INDEX, Path::new("shared.sv"))], "top") + .four_state(four_state) + .diagnostic_policy(policy) + .build() + .unwrap(); + assert!(sim.warnings().is_empty()); + sim.run_until(10).unwrap(); + assert_eq!(display_lines(&mut sim), ["1 1"], "four_state={four_state}"); + } + let sim = shared_index(SHARED_INDEX, Some(celox::DiagnosticLevel::Warn)).unwrap(); + let warnings: Vec = sim.warnings().iter().map(ToString::to_string).collect(); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert!(warnings[0].contains("`j`"), "{warnings:?}"); + assert!(warnings[0].contains("shared.sv:7"), "{warnings:?}"); + assert!(warnings[0].contains("shared.sv:11"), "{warnings:?}"); +} + +#[test] +fn shared_always_temporary_keeps_the_standard_when_it_would_show() { + let allow = Some(celox::DiagnosticLevel::Allow); + for (what, source) in [ + ( + "another reader", + SHARED_INDEX.replace(" initial begin\n", " wire [31:0] q = j;\n initial begin\n"), + ), + ( + "a read before the write", + SHARED_INDEX.replace( + " any_b = 1'b0;\n", + " any_b = j[0];\n", + ), + ), + ( + "a hierarchical reader", + SHARED_INDEX.replace("module top;", "module dut;").replace( + "endmodule\n", + "endmodule\nmodule top;\n dut d();\n initial #5 $display(\"%0d\", d.j);\nendmodule\n", + ), + ), + ] { + let sim = shared_index(&source, allow).unwrap(); + assert!(sim.warnings().is_empty(), "{what}"); + assert_does_not_settle(sim); + } +} + +#[test] +fn always_comb_blocks_may_not_share_a_variable() { + let source = SHARED_INDEX.replace("always @(*)", "always_comb"); + let error = match shared_index(&source, Some(celox::DiagnosticLevel::Allow)) { + Ok(_) => panic!("always_comb restricts a variable to one process"), + Err(error) => error.to_string(), + }; + assert!( + error.contains("multiple variable drivers for `j`"), + "{error}" + ); + assert!(error.contains("shared.sv:7"), "{error}"); + assert!(error.contains("shared.sv:11"), "{error}"); +} diff --git a/docs/guide/celox-toml.md b/docs/guide/celox-toml.md index 3b54313138e..c39e6f22d20 100644 --- a/docs/guide/celox-toml.md +++ b/docs/guide/celox-toml.md @@ -199,6 +199,20 @@ The Rust `.allow_inferred_latches(true)` and JavaScript `allowInferredLatches: t options provide `allow` only when this diagnostic has no explicit setting; an explicit `error`, `warn` or `allow` takes precedence. +`shared_always_temporary` defaults to `error`, which keeps IEEE 1800-2023 +semantics for a variable that several `always @*` blocks write, such as a loop +index they share: each block waits on the variables it reads, the shared one +included (§9.4.2.2), so its writes wake the other blocks. Blocks that keep waking +each other end the run with `time T does not settle`, which names the blocks. +With `warn` or `allow`, Celox instead makes such a variable a temporary of each +block, when only `always @*` blocks write it, each writes it before it reads it +on every path, and nothing else reads it: no other process, continuous +assignment, subroutine, port, instance connection or hierarchical name. Its +writes then wake no other block, as in Icarus Verilog, and the variable itself +keeps its initial value. This deviates from the standard, so it is not the +default; `warn` reports each variable and its blocks. Declaring the variable +inside each block keeps the standard semantics without it. + Project simulator constructors load this table alongside `Veryl.toml`. Native compilation also supports standalone SystemVerilog projects: diff --git a/docs/ja/guide/celox-toml.md b/docs/ja/guide/celox-toml.md index 6443f46cdad..dd57539ea23 100644 --- a/docs/ja/guide/celox-toml.md +++ b/docs/ja/guide/celox-toml.md @@ -155,6 +155,10 @@ memory_file_word_count = "error" Rust の `.allow_inferred_latches(true)` と JavaScript の `allowInferredLatches: true` は、 この診断の明示設定がない場合だけ `allow` を補います。明示した `error`・`warn`・`allow` が優先されます。 +`shared_always_temporary` の既定値は `error` で、共有するループ変数のように複数の `always @*` ブロックが書き込む変数に IEEE 1800-2023 の意味論を適用します。各ブロックは自身が読む変数(共有変数を含む)の変化を待つため(§9.4.2.2)、あるブロックの書き込みは他のブロックを起動します。互いに起動し続けるブロックは `time T does not settle` で実行を終了し、そのメッセージに該当ブロックが示されます。 +`warn` または `allow` を選ぶと、Celox はそのような変数を各ブロックの一時変数として扱います。対象は、`always @*` ブロックだけが書き込み、各ブロックがすべての経路で読む前に書き込み、ほかに読むもの(他のプロセス、継続的代入、サブルーチン、ポート、インスタンス接続、階層名)がない変数です。その書き込みは Icarus Verilog と同様に他のブロックを起動せず、変数自体は初期値のままになります。 +これは規格からの逸脱なので既定では無効です。`warn` は対象の変数とブロックを報告します。変数を各ブロックの中で宣言すれば、この緩和なしで規格どおりの意味論を保てます。 + `interface_array_query` の既定値は `error` です。`warn` または `allow` で、固定長の interface 配列と添字で選択した部分配列に対する `$size` を互換拡張として許可します。IEEE 1800-2023 §20.7 の対象はデータ配列であり、interface インスタンスはデータオブジェクトではありません。省略可能な次元引数は既知の整数定数に限ります。この拡張によって interface ハンドルに packed 幅が付いたり、他の配列クエリが使えるようになったりすることはありません。 ```toml