diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 339d3836e6b..66a502bdcb3 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -11,9 +11,10 @@ use std::path::Path; use celox_design::{ BinaryOp, BitAccess, DisplaySizing, DomainKind, ExternFunction, ExternSignature, ExternType, - InitialStateData, InitialStateValue, ModuleId, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, - PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo, RuntimeEventKind, - RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, WORKING_REGION, WaitSite, + InitialStateData, InitialStateValue, ModuleId, NbaSite, PROCESS_DELAY_WIDTH, + PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo, + RuntimeEventKind, RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, + WORKING_REGION, WaitSite, }; use celox_frontend_core::process::PROCESS_RESUME_WIDTH; use celox_frontend_core::symbolic::artifact::{ @@ -2004,7 +2005,7 @@ fn lower_module_with_overrides( ) }; mark_ff_event_domains(&event_vars, &mut variables); - let (initial_values, processes, wait_sites) = lower_initial_processes( + let (initial_values, processes, wait_sites, nba_sites) = lower_initial_processes( module, &mut variables, &mut name_to_id, @@ -2113,7 +2114,7 @@ fn lower_module_with_overrides( package_bindings: HashMap::default(), counter_slots: Vec::new(), wait_sites, - nba_sites: Vec::new(), + nba_sites, }, variables, port_order, @@ -2775,11 +2776,12 @@ fn lower_initial_processes( Vec>, Vec, Vec>, + Vec>, ), sv::AnalyzerError, > { if module.initial_processes().is_empty() { - return Ok((Vec::new(), Vec::new(), Vec::new())); + return Ok((Vec::new(), Vec::new(), Vec::new(), Vec::new())); } let mut values = Vec::new(); let mut runtime = Vec::new(); @@ -2833,7 +2835,7 @@ fn lower_initial_processes( } } if runtime.is_empty() { - return Ok((values, Vec::new(), Vec::new())); + return Ok((values, Vec::new(), Vec::new(), Vec::new())); } let mut next_id = SourceVarId( @@ -2888,24 +2890,29 @@ fn lower_initial_processes( pm.runtime_errors = std::mem::take(runtime_errors); pm.extern_functions = std::mem::take(extern_functions); let mut wait_sites = Vec::new(); + let mut nba_sites = Vec::new(); let processes = runtime .into_iter() .zip(slots) .enumerate() .map(|(index, ((process, random_seed), slots))| { - let (kernel, sites) = ff::Ff::new(&mut pm, random_seed).lower_initial_kernel( + let kernel = ff::Ff::new(&mut pm, random_seed).lower_initial_kernel( process.body(), slots, index, )?; - wait_sites.extend(sites); - Ok(SymbolicProcess { kernel, slots }) + wait_sites.extend(kernel.wait_sites); + nba_sites.extend(kernel.nba_sites); + Ok(SymbolicProcess { + kernel: kernel.unit, + slots, + }) }) .collect::, sv::AnalyzerError>>(); *runtime_event_sites = std::mem::take(&mut pm.runtime_event_sites); *runtime_errors = std::mem::take(&mut pm.runtime_errors); *extern_functions = std::mem::take(&mut pm.extern_functions); - Ok((values, processes?, wait_sites)) + Ok((values, processes?, wait_sites, nba_sites)) } fn lower_comb_processes( diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 431ca8eea0f..88cb0546d24 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -11,7 +11,7 @@ use super::procedural::*; use super::*; -use celox_design::{CounterKind, WaitSite}; +use celox_design::{CounterKind, NbaSite, WaitSite}; use celox_frontend_core::process::{ProcessKernelBuilder, ProcessKernelError}; use celox_sir::{RegisterId, RegisterType}; use celox_slt::SLTToSIRLowerer; @@ -64,6 +64,8 @@ pub(super) struct Ff<'p, 'a> { process: usize, /// The wait sites of the process, by local index. wait_sites: Vec>, + /// The nonblocking assignment sites of the process, by local index. + nba_sites: Vec>, direct: bool, } @@ -111,6 +113,7 @@ impl<'p, 'a> Ff<'p, 'a> { direct: false, process: 0, wait_sites: Vec::new(), + nba_sites: Vec::new(), } } @@ -1815,6 +1818,22 @@ impl<'p, 'a> Ff<'p, 'a> { fn exec(&mut self, stmt: &sv::ir::Stmt) -> Result { match stmt { + sv::ir::Stmt::Assign { + lhs, + rhs, + nonblocking: true, + } if self.kernel.is_some() => { + self.nonblocking(std::slice::from_ref(lhs), rhs)?; + Ok(true) + } + sv::ir::Stmt::AssignConcat { + parts, + rhs, + nonblocking: true, + } if self.kernel.is_some() => { + self.nonblocking(parts, rhs)?; + Ok(true) + } sv::ir::Stmt::Assign { lhs, rhs, .. } => { self.assign(lhs, rhs)?; Ok(true) @@ -3172,30 +3191,8 @@ impl Ff<'_, '_> { body: &[sv::ir::Stmt], slots: ProcessSlots, process: usize, - ) -> Result<(ExecutionUnit, Vec>), sv::AnalyzerError> { + ) -> Result { self.process = process; - // A nonblocking update would take effect in a later region of the - // time step, after the process has run on. - for stmt in body { - let mut nonblocking = false; - stmt.walk(&mut |stmt| { - nonblocking |= matches!( - stmt, - sv::ir::Stmt::Assign { - nonblocking: true, - .. - } | sv::ir::Stmt::AssignConcat { - nonblocking: true, - .. - } - ); - }); - if nonblocking { - return Err(unsupported( - "nonblocking assignment in an initial block that runs as a process", - )); - } - } let mut kernel = ProcessKernelBuilder::new(slots); std::mem::swap(&mut self.b, kernel.builder()); self.kernel = Some(kernel); @@ -3204,7 +3201,125 @@ impl Ff<'_, '_> { std::mem::swap(&mut self.b, kernel.builder()); let mut unit = kernel.build(); prune_unreachable_blocks(&mut unit); - Ok((unit, self.wait_sites)) + Ok(KernelUnit { + unit, + wait_sites: self.wait_sites, + nba_sites: self.nba_sites, + }) + } + + /// A nonblocking assignment in a process (IEEE 1800-2023 10.4.2): the + /// right-hand side is evaluated now, once, and each target part becomes + /// an update the runtime queues for the NBA region. + fn nonblocking( + &mut self, + parts: &[sv::ir::LValue], + rhs: &sv::ir::Expr, + ) -> Result<(), sv::AnalyzerError> { + let mut targets = Vec::with_capacity(parts.len()); + for part in parts { + targets.push(self.nba_target(part)?); + } + let total: usize = targets.iter().map(|(_, _, width)| width).sum(); + let four_state = targets.iter().any(|(id, _, _)| self.m.var(*id).is_4state); + let (_, value_name) = self.m.temp("nba", total, false, four_state); + self.assign(&sv::ir::LValue::Ident(value_name.clone()), rhs)?; + // The parts, most significant first, take consecutive bits of the + // value. + let mut high = total; + for (id, lsb, width) in targets { + let low = high - width; + let (staged, staged_name) = + self.m + .temp("nba_part", width, false, self.m.var(id).is_4state); + self.assign( + &sv::ir::LValue::Ident(staged_name), + &sv::ir::Expr::Select { + expr: Box::new(sv::ir::Expr::Ident(value_name.clone())), + msb: sv::ir::ConstExpr::Literal((high - 1).to_string()), + lsb: sv::ir::ConstExpr::Literal(low.to_string()), + signed: false, + }, + )?; + high = low; + let site = NbaSite { + process: self.process, + target: id, + lsb, + width, + value: staged, + offset: None, + pending: None, + }; + let index = self.nba_sites.len() as u32; + let staged_four_state = self.m.var(staged).is_4state; + self.with_kernel(|kernel| { + kernel.nonblocking(index, &site, |builder| { + let value = if staged_four_state { + builder.alloc_logic(width) + } else { + builder.alloc_bit(width, false) + }; + builder.emit(SIRInstruction::Load( + value, + stable(staged), + SIROffset::Static(0), + width, + )); + Ok::<_, ProcessKernelError>((value, None)) + }) + }) + .map_err(kernel_error)?; + self.nba_sites.push(site); + } + Ok(()) + } + + /// The variable and the constant bit range a nonblocking assignment in + /// a process writes. + fn nba_target( + &self, + lvalue: &sv::ir::LValue, + ) -> Result<(SourceVarId, usize, usize), sv::AnalyzerError> { + let id = self + .m + .id(lvalue.name()) + .ok_or_else(|| unsupported(format!("assignment target `{}`", lvalue.name())))?; + let variable = self.m.var(id); + if !variable.array_dims.is_empty() { + return Err(unsupported( + "nonblocking assignment to an unpacked array in a process", + )); + } + match lvalue { + sv::ir::LValue::Ident(_) => Ok((id, 0, variable.width)), + sv::ir::LValue::Select { msb, lsb, .. } => { + let constant = |expr| { + sv::typecheck::eval_const_expr_with_types( + expr, + self.m.constants, + self.m.parameter_types, + ) + }; + let (Some(msb), Some(lsb)) = (constant(msb), constant(lsb)) else { + return Err(unsupported( + "nonblocking assignment with a run-time position in a process", + )); + }; + let (Some(msb), Some(lsb)) = ( + packed_index_offset(variable, msb), + packed_index_offset(variable, lsb), + ) else { + return Err(unsupported("nonblocking assignment outside its target")); + }; + if msb < lsb { + return Err(unsupported( + "nonblocking assignment to a reversed part select in a process", + )); + } + Ok((id, lsb, msb - lsb + 1)) + } + } } /// `#amount` (IEEE 1800-2023 9.4.1). The amount is self-determined and @@ -3401,6 +3516,13 @@ impl Ff<'_, '_> { } } +/// The kernel of a process and its wait and nonblocking assignment sites. +pub(super) struct KernelUnit { + pub unit: ExecutionUnit, + pub wait_sites: Vec>, + pub nba_sites: Vec>, +} + /// Iterations, as a power of two, between the yields of a kernel loop that /// may not suspend. const LOOP_YIELD_BITS: usize = 16; diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 305f45fabc3..3d2faf5c327 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -429,6 +429,42 @@ (assert_eq cnt_gated 3 "so does a clock computed from it") (assert_eq cnt_derived 3 "and a falling one through an inverter")) +(case nonblocking_assignments_in_processes_update_in_the_nba_region + (source "process_nba.sv" #" + module Top(output logic [7:0] q, early, late, bus, hi, lo, d, sampled); + logic clk = 1'b0; + always #5 clk = ~clk; + initial begin + q = 8'd0; + bus = 8'd0; + #1; + q <= 8'd1; + q <= 8'd2; + #0 early = q; + bus[7:4] <= 4'ha; + {hi, lo} <= 16'h1234; + #1 late = q; + end + // A stimulus process and a register sampling it at the same edge. + initial begin + d = 8'd0; + forever @(posedge clk) d <= d + 8'd1; + end + always_ff @(posedge clk) sampled <= d; + endmodule"#) + (top Top) + (run_until 1) + (assert_eq early 0 "a nonblocking update lands after the inactive region") + (assert_eq q 2 "the last update of a time slot wins") + (assert_eq bus 0xa0) + (assert_eq hi 0x12) + (assert_eq lo 0x34) + (run_until 2) + (assert_eq late 2) + (run_until 26) + (assert_eq d 3) + (assert_eq sampled 2 "the register samples the value before the edge's update")) + (case nonblocking_ff_stores_remain_pending_during_inactive_work (source "nonblocking.sv" #"module Top(output bit [7:0] q, observed, derived_seen); bit clk; wire [7:0] derived=q+1; diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 9421f957be7..f67bd607e48 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -899,6 +899,26 @@ fn applies_unsigned_coercion_to_typed_parameter_comparisons() { assert_eq!(sim.get(sim.signal("all_ones")), 1u8.into()); } +/// Nonblocking assignments in processes whose target bits are not known at +/// compile time are not lowered yet; they are rejected by name. +#[test] +fn rejects_process_nonblocking_assignments_without_a_constant_target() { + for (body, construct) in [ + ( + "logic [7:0] q; logic [2:0] i; initial #1 q[i] <= 1'b1;", + "nonblocking assignment with a run-time position in a process", + ), + ( + "logic [7:0] mem [4]; initial #1 mem[1] <= 8'd1;", + "nonblocking assignment to an unpacked array in a process", + ), + ] { + let source = format!("module Top; {body} endmodule"); + let error = cranelift_build_error(&source); + assert!(error.contains(construct), "`{body}`: {error}"); + } +} + #[test] fn compile_sv_to_sir_forwards_parameter_overrides() { let source = r#" diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 9db62d543e1..136d95263b0 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -1795,18 +1795,27 @@ fn initial_blocks_that_read_design_state_run_at_time_zero() { assert_eq!(sim.get(y), 1u8.into()); } +/// A nonblocking assignment in an `initial` process updates its target in +/// the NBA region: a `$display` in the same time slot sees the old value. #[test] -fn rejects_nonblocking_assignments_in_initial_processes() { - let error = build_error( - r#"module Top(output logic y); - logic v; +fn nonblocking_assignments_in_initial_processes_update_after_the_display() { + let source = r#"module Top(output logic y); + logic v = 1'b0; initial begin v <= 1'b1; $display("%0d", v); end assign y = v; - endmodule"#, - ); - assert!( - error.contains("nonblocking assignment in an initial block that runs as a process"), - "{error}" + endmodule"#; + let mut sim = + celox::Simulation::from_sv_sources(vec![(source, Path::new("system_functions.sv"))], "Top") + .build() + .unwrap(); + sim.run_until(0).unwrap(); + let y = sim.signal("y"); + assert_eq!(sim.get(y), 1u8.into()); + assert_eq!( + sim.drain_runtime_events(), + vec![celox::RuntimeEvent::Display { + message: b"0".to_vec() + }] ); } diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 8832b5aca5b..a5389bd703f 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -70,6 +70,7 @@ timed_cases! { fn run_to_finish_has_no_simulated_time_deadline = "timing::run_to_finish_has_no_simulated_time_deadline"; fn blocking_ff_stores_are_visible_before_inactive_work = "timing::blocking_ff_stores_are_visible_before_inactive_work"; fn blocking_ff_clock_edges_trigger_their_domains_before_inactive_work = "timing::blocking_ff_clock_edges_trigger_their_domains_before_inactive_work"; + fn nonblocking_assignments_in_processes_update_in_the_nba_region = "timing::nonblocking_assignments_in_processes_update_in_the_nba_region"; fn nonblocking_ff_stores_remain_pending_during_inactive_work = "timing::nonblocking_ff_stores_remain_pending_during_inactive_work"; fn mixed_ff_stores_keep_their_active_and_nba_values = "timing::mixed_ff_stores_keep_their_active_and_nba_values"; fn printed_finish_notice_is_design_output = "timing::printed_finish_notice_is_design_output";