diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 3c4c5a0d7d4..7306b081347 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -7244,6 +7244,11 @@ impl Ff<'_, '_> { }) { return Err(unsupported("wait condition reading a static task argument")); } + // A write of a class property does not wake a waiting process yet, so + // a condition that reads one would never be checked again. + if let Some(op) = heap_read(self.m, condition) { + return Err(unsupported(format!("{op} in a wait condition"))); + } let mut ids: Vec<_> = names .iter() .filter_map(|name| self.m.id(name)) @@ -7471,6 +7476,66 @@ fn subroutine_reads(pm: &ProcModule<'_>, expr: &sv::ir::Expr, names: &mut HashSe } } +/// The name of an operation in `expr` that reads the class object heap, +/// directly or through the functions it calls: a class property, or the +/// random mode of one. Container contents are values of their handles. The +/// default of an argument counts only where a call omits the argument. +fn heap_read(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option { + let mut pending = vec![expr.clone()]; + let mut calls = Vec::new(); + let mut visited = HashSet::default(); + let mut defaults = HashSet::default(); + loop { + while let Some(expr) = pending.pop() { + let found = std::cell::RefCell::new(None); + expr_calls(&expr, &|callee| { + if let sv::ir::Callee::Object(op) = callee + && matches!( + **op, + sv::ir::ObjectOp::Load(_) + | sv::ir::ObjectOp::ModeGet(..) + | sv::ir::ObjectOp::ConstraintModeGet(_) + ) + { + found.borrow_mut().get_or_insert(op.to_string()); + } + false + }); + if let Some(op) = found.into_inner() { + return Some(op); + } + collect_calls(&expr, &mut calls); + } + let (callee, args) = calls.pop()?; + let sv::ir::Callee::Subroutine(name) = callee else { + continue; + }; + let Some(subroutine) = pm.subroutine(&name) else { + continue; + }; + for (position, param) in subroutine.params.iter().enumerate() { + if matches!(args.get(position), None | Some(None)) + && let Some(default) = ¶m.default + && defaults.insert((name.clone(), position)) + { + pending.push(default.clone()); + } + } + if !visited.insert(name) { + continue; + } + for stmt in &subroutine.body { + let mut stmt = stmt.clone(); + stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); + stmt.visit_mut( + &mut |expr| pending.push(expr.clone()), + &mut |_| {}, + &mut |_| {}, + ); + } + } +} + /// The name of a call in `expr` that has an effect or reads the state of the /// simulation, directly or through the functions it calls: an event /// expression must be a value of the variables it reads. diff --git a/crates/celox-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index 2f439a631e1..5910e061df0 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -4343,8 +4343,12 @@ mod tests { } #[test] - fn native_handle_edges_of_clocks_comb_logic_does_not_read_stay_settled() { - for (seen, comb_read) in [("1'b1", false), ("clk", true)] { + fn native_handle_edges_preserve_settledness_for_unused_clocks_and_wiring() { + for (seen, settled, value) in [ + ("1'b1", true, Some(1)), + ("clk", true, Some(0)), + ("~clk", false, None), + ] { let source = format!( "module Top (clk: input clock, count: output logic<8>, seen: output logic) {{ always_ff (clk) {{ count += 1; }} @@ -4356,13 +4360,22 @@ mod tests { let events: HashMap = serde_json::from_str(&handle.events_json()).unwrap(); let clk = events["clk"]; assert!(handle.edges(vec![clk], vec![true], None).unwrap()); - // Moving `clk` without running a domain leaves combinational - // logic stale only when it reads `clk`, or already was. + // Unused clocks and direct wiring remain settled after an + // inactive edge. Other clock-dependent logic still needs a settle. assert_eq!( handle.edges(vec![clk], vec![false], Some(false)).unwrap(), - !comb_read, + settled, "{seen}" ); + if let Some(value) = value { + let layout: serde_json::Value = + serde_json::from_str(&handle.layout_json()).unwrap(); + let offset = layout["seen"]["offset"].as_u64().unwrap() as usize; + let (memory, len) = handle.backend.as_mut().unwrap().memory_as_mut_ptr(); + assert!(offset < len); + // Read the stored result without implicitly evaluating comb. + assert_eq!(unsafe { *memory.add(offset) }, value, "{seen}"); + } assert!(handle.edges(vec![clk], vec![true], Some(true)).unwrap()); assert!(!handle.edges(vec![clk], vec![false], Some(true)).unwrap()); handle.dispose().unwrap(); diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index 05bb918ca1e..2cef0230087 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -47,6 +47,14 @@ pub trait SimBackend { // ── evaluation ────────────────────────────────────────────── fn eval_comb(&mut self) -> Result<(), SimulatorErrorCode>; + /// Publish all combinational effects of a single clock-level change when + /// its cone is proven to contain only wiring. Called only from a settled + /// state, immediately after the host writes the clock. `false` must leave + /// state unchanged and requests the normal full settle. + fn eval_clock_aliases(&mut self, _event: Self::Event) -> Result { + Ok(false) + } + /// Evaluate and apply a flip-flop domain for the given event. fn eval_apply_ff_at(&mut self, event: Self::Event) -> Result<(), SimulatorErrorCode>; diff --git a/crates/celox-runtime/src/edge.rs b/crates/celox-runtime/src/edge.rs index be49d6dc281..44b22c6a96e 100644 --- a/crates/celox-runtime/src/edge.rs +++ b/crates/celox-runtime/src/edge.rs @@ -358,7 +358,9 @@ where }; let new = edge.level(); let fires = info.fires(known(from), edge); - let settle = dirty || info.comb_read; + let comb_read = + info.comb_read && (dirty || !executor.backend_mut().eval_clock_aliases(event)?); + let settle = dirty || comb_read; if let Some(plan) = plan { // A gated clock is judged from the lever's real level before the // edge, x and z included. @@ -381,11 +383,11 @@ where return Ok(if settled { EdgeOutcome::Settled } else { - moved_only(info.comb_read) + moved_only(comb_read) }); } if !fires { - return Ok(moved_only(info.comb_read)); + return Ok(moved_only(comb_read)); } if settle { executor.eval_comb_apply_ff_at(event)?; @@ -552,7 +554,8 @@ where any_moved = true; write.write(executor.backend_mut(), info.signal, new); transitions.push((info.signal, (old, new))); - comb_read |= info.comb_read; + comb_read |= + info.comb_read && (dirty || !executor.backend_mut().eval_clock_aliases(event)?); let fires = info.fires(known(old), edge); if cached { changed.push((event, fires)); diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 3774d7cd147..323381f68bb 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -619,6 +619,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_verilator_program_exit` | execute | verilator | 1 | Verilator 5.052 continues after `$exit` and keeps the program's other `initial` procedures (24.7). Icarus does not run the case; xezim 0.11.3 agrees with the expected output. | | `sv_verilator_program_items` | compile | verilator | 2 | Verilator 5.052 rejects an `always` procedure and a module instance in a program with syntax errors, which the run cannot count as language rejections. Both are illegal (IEEE 1800-2023 24.3); Icarus 13.0 rejects them with diagnostics that name the rule. | | `sv_icarus_iff_event_controls` | compile | icarus | 15 | Icarus 13.0 rejects `iff` in an event control with "syntax error" and "Malformed event control expression." IEEE 1800-2023 9.4.2.3 and A.6.5 permit `@(posedge clk iff en)`; [Standalone probe](verification/repros/sv_iff_event_controls_icarus.json); Verilator 5.052 runs the cases and gives the asserted counts. | +| `sv_icarus_static_property_wait` | execute | icarus | 1 | Icarus 13.0 compiles a `wait` on a static class property in a class task but vvp cannot load the result ("unresolved vvp_net reference", "Program not runnable"); IEEE 1800-2023 8.9 and 9.4.3 make the property one variable that the wait watches. [Standalone probe](verification/repros/sv_static_property_wait_icarus.json); Verilator 5.052 and xezim 0.11.3 pass the case. | | `sv_verilator_iff_late_conditions` | execute | verilator | 4 | Verilator 5.052 judges an `iff` condition after the process that writes the event signal suspends, not at the write: with `clk = 1; en = 0;` from en = 1 it counts no event, with nonblocking updates `clk <= 1; en <= 0;` from en = 1 it counts none either, and an always_comb that writes `en = a; clk = a; en = 0;` gives no event of its `clk` write while `en` is 1. IEEE 1800-2023 9.4.2.3 judges the condition when the event occurs, and 10.4.2 applies nonblocking updates in issue order, so all three are events. [Standalone probes](verification/repros/sv_iff_late_conditions_verilator.json) print n=0, n=1 and n=0 in Verilator where the spec gives 1, 2 and 1; Icarus 13.0 rejects `iff` in event controls. | The [system-function edge-case evidence](verification/repros/system_function_edge_cases.json) diff --git a/crates/celox-test-suite/src/sv/cases/class.vtest b/crates/celox-test-suite/src/sv/cases/class.vtest index 32147016334..88e604db58c 100644 --- a/crates/celox-test-suite/src/sv/cases/class.vtest +++ b/crates/celox-test-suite/src/sv/cases/class.vtest @@ -2806,3 +2806,28 @@ module Top(output int a, output int b); endmodule "#) (top Top) (run_until 0) (assert_eq a 8) (assert_eq b 8)) + +(case waits_on_static_properties + ; A static property is a variable of the declaring scope, so a wait in a + ; method wakes when another process writes it (IEEE 1800-2023 8.9, 9.4.3). + (source "class.sv" #" +class C; + static int s_state; + task wait_for(int s); + wait (s_state >= s); + $display("reached %0d at %0d", s, $time); + endtask +endclass +module Top; + C c; + initial begin + c = new; + fork + c.wait_for(2); + begin #1 c.s_state = 1; #1 c.s_state = 2; end + join + end +endmodule +"#) + (top Top) (run_until 5) + (expect_output "reached 2 at 2\n")) diff --git a/crates/celox-test-suite/verification/repros/sv_static_property_wait_icarus.json b/crates/celox-test-suite/verification/repros/sv_static_property_wait_icarus.json new file mode 100644 index 00000000000..a2f10b87245 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_static_property_wait_icarus.json @@ -0,0 +1,16 @@ +{ + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "source": "sv_static_property_wait_icarus.sv", + "standard": "IEEE 1800-2023 8.9, 9.4.3", + "command": "iverilog -g2012 -s Top -o sp.vvp sv_static_property_wait_icarus.sv && vvp sp.vvp", + "expected_output": "reached 2 at 2", + "observations": [ + { + "build_exit_code": 0, + "exit_code": 2, + "output": "unresolved vvp_net reference: v0x5555558f2f70_0\nunresolved vvp_net reference: v0x5555558f3050_0\ncompile_cleanup: 2 unresolved items\nsp.vvp: Program not runnable, 2 errors.\n" + } + ], + "note": "A task of a class waits on a static property of the class, which another process writes through a handle. Icarus 13.0 compiles the design but vvp cannot load it (unresolved nets). Verilator 5.052, xezim 0.11.3 and Celox print reached 2 at 2." +} diff --git a/crates/celox-test-suite/verification/repros/sv_static_property_wait_icarus.sv b/crates/celox-test-suite/verification/repros/sv_static_property_wait_icarus.sv new file mode 100644 index 00000000000..f32aec9dad8 --- /dev/null +++ b/crates/celox-test-suite/verification/repros/sv_static_property_wait_icarus.sv @@ -0,0 +1,17 @@ +class C; + static int s_state; + task wait_for(int s); + wait (s_state >= s); + $display("reached %0d at %0d", s, $time); + endtask +endclass +module Top; + C c; + initial begin + c = new; + fork + c.wait_for(2); + begin #1 c.s_state = 1; #1 c.s_state = 2; end + join + end +endmodule diff --git a/crates/celox-test-suite/verification/sv/icarus/class.json b/crates/celox-test-suite/verification/sv/icarus/class.json index 798ee76f9f8..5b45280df28 100644 --- a/crates/celox-test-suite/verification/sv/icarus/class.json +++ b/crates/celox-test-suite/verification/sv/icarus/class.json @@ -1692,6 +1692,29 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 compiles a `wait` on a static class property in a class task but vvp cannot load the result (\"unresolved vvp_net reference\", \"Program not runnable\"). IEEE 1800-2023 8.9 and 9.4.3 make the property one variable that the wait watches. Verilator 5.052 and xezim 0.11.3 pass the case.", + "expectation": "Simulation", + "known_issue": { + "id": "sv_icarus_static_property_wait", + "category": "simulator_runtime_limitation", + "phase": "execute", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 compiles a `wait` on a static class property in a class task but vvp cannot load the result (\"unresolved vvp_net reference\", \"Program not runnable\"). IEEE 1800-2023 8.9 and 9.4.3 make the property one variable that the wait watches. Verilator 5.052 and xezim 0.11.3 pass the case.", + "upstream": [], + "evidence": [ + "verification/repros/sv_static_property_wait_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "name": "class::waits_on_static_properties", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 9e3d93bcf81..1ed492b94c2 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2769,6 +2769,23 @@ ] } }, + { + "id": "sv_icarus_static_property_wait", + "category": "simulator_runtime_limitation", + "phase": "execute", + "observed_version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "reason": "Icarus 13.0 compiles a `wait` on a static class property in a class task but vvp cannot load the result (\"unresolved vvp_net reference\", \"Program not runnable\"). IEEE 1800-2023 8.9 and 9.4.3 make the property one variable that the wait watches. Verilator 5.052 and xezim 0.11.3 pass the case.", + "upstream": [], + "evidence": [ + "verification/repros/sv_static_property_wait_icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "class::waits_on_static_properties" + ] + } + }, { "id": "sv_verilator_iff_late_conditions", "category": "simulator_disagreement", diff --git a/crates/celox-test-suite/verification/sv/verilator/class.json b/crates/celox-test-suite/verification/sv/verilator/class.json index 07fbee05dad..42f2fc7c4d9 100644 --- a/crates/celox-test-suite/verification/sv/verilator/class.json +++ b/crates/celox-test-suite/verification/sv/verilator/class.json @@ -831,6 +831,17 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::waits_on_static_properties", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox-test-suite/verification/sv/xezim/class.json b/crates/celox-test-suite/verification/sv/xezim/class.json index 239b5e1837a..6ad38174bf9 100644 --- a/crates/celox-test-suite/verification/sv/xezim/class.json +++ b/crates/celox-test-suite/verification/sv/xezim/class.json @@ -648,6 +648,17 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "class::waits_on_static_properties", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 7e13bd35dba..ae3d4b70502 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -166,6 +166,7 @@ impl super::super::EventHandle for NativeEventRef { /// that share the same compiled machine code. pub struct SharedNativeCode { comb_func: NativeSimFunc, + clock_alias_funcs: Vec>, comb_unit_funcs: Vec, /// One function per process kernel. process_funcs: Vec, @@ -308,8 +309,25 @@ impl SharedNativeCode { .map(materialize) .collect::, _>>()?; + // Optional named exports keep older images usable: absence requests a + // full settle. Export names are part of the native runtime contract. + let mut clock_alias_funcs = vec![None; id_to_event.len()]; + for entry in &program_image.code_entries { + if let Some(id) = entry.name.strip_prefix(super::clock_aliases::EXPORT_PREFIX) { + let id = id + .strip_suffix(']') + .and_then(|id| id.parse::().ok()) + .filter(|&id| id < clock_alias_funcs.len()) + .ok_or_else(|| codegen_message("invalid clock alias export"))?; + if clock_alias_funcs[id].is_some() { + return Err(codegen_message("duplicate clock alias export")); + } + clock_alias_funcs[id] = Some(native_function_at(&jit_image, entry.offset)?); + } + } Ok(Self { comb_func, + clock_alias_funcs, comb_unit_funcs, process_funcs, lane_kernels, @@ -359,7 +377,8 @@ impl SharedNativeCode { /// One callable function in a packed native code image. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct NativeCodeEntry { - /// Stable diagnostic name for the emitted function. + /// Stable name for the emitted function. `clock_alias_update[N]` names + /// an optional clock-wiring update entry for event N; other names are diagnostic. pub name: String, /// Byte offset from the start of the native image. pub offset: usize, @@ -2656,6 +2675,26 @@ fn compile_program_with_outlining_threshold( .into_iter() .collect::, _>>()?; let lane_kernels = super::lanes::compile_lane_kernels(sir, options, cancel)?; + let mut clock_alias_jits = Vec::new(); + if !options.four_state && !options.native_force_support && force_bindings.is_empty() { + let (_, clocks) = crate::backend::event_ids(sir); + for (id, clock) in clocks.into_iter().enumerate() { + if let Some(units) = super::clock_aliases::extract(sir, clock) { + let name = format!("{}{}]", super::clock_aliases::EXPORT_PREFIX, id); + let compiled = compile_units( + &units, + layout, + false, + &name, + &options.x86_options, + false, + &options.optimize_options.diagnostics, + cancel, + )?; + clock_alias_jits.push((name, compiled)); + } + } + } let codegen_trace = capture_trace .then(|| format_native_codegen_trace(&comb_jit, &compiled_ff_codes, &compile_tasks)); let semantic_memory_size = layout @@ -2663,6 +2702,11 @@ fn compile_program_with_outlining_threshold( .checked_add(layout.triggered_bits_total_size) .expect("native semantic-memory size overflow"); let native_memory_size = std::iter::once(comb_jit.required_state_size) + .chain( + clock_alias_jits + .iter() + .map(|(_, code)| code.required_state_size), + ) .chain(comb_chunk_jits.iter().map(|code| code.required_state_size)) .chain( compiled_ff_codes @@ -2683,6 +2727,11 @@ fn compile_program_with_outlining_threshold( ) .fold(semantic_memory_size, usize::max); let required_native_features = std::iter::once(comb_jit.required_native_features) + .chain( + clock_alias_jits + .iter() + .map(|(_, code)| code.required_native_features), + ) .chain( comb_chunk_jits .iter() @@ -2768,6 +2817,15 @@ fn compile_program_with_outlining_threshold( )?; task_offsets.insert(task_id, offset); } + for (name, compiled) in &clock_alias_jits { + append_native_code( + &mut packed_image, + &mut code_entries, + &mut image_symbols, + name.clone(), + compiled, + )?; + } let lane_image = lane_kernels .map(|kernels| kernels.pack(&mut packed_image, &mut code_entries, &mut image_symbols)) .transpose()?; @@ -3695,6 +3753,14 @@ impl super::super::SimBackend for NativeBackend { self.call_func_timed(func) } + fn eval_clock_aliases(&mut self, event: NativeEventRef) -> Result { + let Some(func) = self.compiled.clock_alias_funcs[event.id] else { + return Ok(false); + }; + self.call_func_timed(func)?; + Ok(true) + } + fn eval_apply_ff_at(&mut self, event: NativeEventRef) -> Result<(), SimulatorErrorCode> { if self.lane_event_kernel(event) { let compiled = Arc::clone(&self.compiled); @@ -4085,6 +4151,45 @@ mod tests { BasicBlock, BlockId, RegisterId, RegisterType, SIRInstruction, SIRTerminator, SIRValue, }; + #[test] + fn image_without_clock_alias_exports_uses_full_settle() { + let source = r#" + module Child (clk: input clock, d: input bit<8>, q: output bit<8>) { + always_ff (clk) { q = d; } + } + module Top (clk: input clock, d: input bit<8>, q: output bit<8>) { + inst child: Child (clk, d, q); + } + "#; + let mut image = crate::Simulator::builder(source, "Top") + .four_state(false) + .compile_native() + .unwrap() + .into_program_image(); + let previous = image.code_entries.len(); + image.code_entries.retain(|entry| { + !entry + .name + .starts_with(super::super::clock_aliases::EXPORT_PREFIX) + }); + assert_eq!(previous, image.code_entries.len() + 1); + let image = + NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()).unwrap(); + let mut sim = crate::Simulator::from_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(); + let event = sim.event("clk"); + let d = sim.signal("d"); + sim.set(d, 42u8); + sim.active_edge(event).unwrap(); + sim.inactive_edge(event).unwrap(); + assert_eq!(sim.get(sim.signal("q")), 42u8.into()); + assert_eq!( + sim.get(sim.child_signal(&[("child", 0)], "clk")), + 0u8.into() + ); + } + /// A unit of `blocks` blocks loading `value`, with its maps filled in /// forward or reverse order. fn unit(blocks: usize, value: u8, width: usize, reverse: bool) -> NativeUnit { diff --git a/crates/celox/src/backend/native/clock_aliases.rs b/crates/celox/src/backend/native/clock_aliases.rs new file mode 100644 index 00000000000..8478e3a50b1 --- /dev/null +++ b/crates/celox/src/backend/native/clock_aliases.rs @@ -0,0 +1,146 @@ +//! A clock move whose entire combinational cone is wiring needs only these +//! stores, not another evaluation of the datapath. Keep the original stores +//! (including trigger bookkeeping) and leave the full comb function unchanged. + +use crate::HashMap; +use crate::ir::{ + AbsoluteAddr, BlockId, ExecutionUnit, LaidOutProgram, RegionedAbsoluteAddr, RegisterId, + SIRInstruction, SIROffset, SIRTerminator, +}; +use celox_sir::BasicBlock; + +pub(super) const EXPORT_PREFIX: &str = "clock_alias_update["; + +pub(super) fn extract( + program: &LaidOutProgram, + clock: AbsoluteAddr, +) -> Option>> { + let events = &program.design.events; + if events.reset_clocks.contains_key(&clock) + || !events.combinationally_read.contains(&clock) + || !program + .runtime() + .runtime_schema + .persistent_comb_state + .is_empty() + || !program.runtime().runtime_schema.comb_observers.is_empty() + { + return None; + } + let is_alias = + |address: RegionedAbsoluteAddr| events.canonical(address.absolute_addr()) == clock; + let mut result = Vec::new(); + for unit in &program.sir.eval_comb { + let cfg = celox_sir::cfg::SirCfg::analyze_forward(unit).ok()?; + // A copy must execute exactly once on every successful evaluation. + // Exclude error exits rather than hoisting through them. Other logic + // may contain loops; only the copied stores must be outside cycles. + if unit + .blocks + .values() + .any(|block| matches!(block.terminator, SIRTerminator::Error(_))) + { + return None; + } + let exits: Vec<_> = unit + .blocks + .values() + .filter(|block| matches!(block.terminator, SIRTerminator::Return)) + .map(|block| cfg.index[&block.id]) + .collect(); + let mut loads = HashMap::default(); + for block in unit.blocks.values() { + for instruction in &block.instructions { + if matches!( + instruction, + SIRInstruction::ExternCall { .. } + | SIRInstruction::RuntimeEvent { .. } + | SIRInstruction::CombCaptureEvent { .. } + | SIRInstruction::CombCaptureEnableIfChanged { .. } + ) { + return None; + } + if let Some(read) = instruction.memory_read() { + if is_alias(*read.addr) { + // Only direct root loads: alias chains and working-state + // loads require a more general dependency proof. + match instruction { + SIRInstruction::Load(reg, addr, SIROffset::Static(0), 1) + if addr.region == 0 && addr.absolute_addr() == clock => + { + loads.insert(*reg, instruction.clone()); + } + _ => return None, + } + } + } + } + } + let mut stores = Vec::new(); + for id in &cfg.block_ids { + let block = &unit.blocks[id]; + let mut used = false; + block + .terminator + .for_each_use(|reg| used |= loads.contains_key(®)); + if used { + return None; + } + for instruction in &block.instructions { + let mut uses_clock = false; + instruction.for_each_use(|reg| uses_clock |= loads.contains_key(®)); + let writes_alias = instruction + .memory_write() + .is_some_and(|write| is_alias(*write.addr)); + if !uses_clock && !writes_alias { + continue; + } + match instruction { + SIRInstruction::Store(addr, SIROffset::Static(0), 1, source, _, captures) + if addr.region == 0 + && addr.absolute_addr() != clock + && is_alias(*addr) + && loads.contains_key(source) + && captures.is_empty() + && !cfg.sccs[cfg.scc_for_block[cfg.index[id]]].cyclic + && exits + .iter() + .all(|&exit| cfg.dominators.dominates(cfg.index[id], exit)) => + { + stores.push(instruction.clone()); + } + _ => return None, + } + } + } + if stores.is_empty() { + continue; + } + let mut registers: Vec = loads.keys().copied().collect(); + registers.sort_unstable(); + let register_map = registers + .iter() + .map(|reg| (*reg, unit.register_map[reg].clone())) + .collect(); + let mut instructions: Vec<_> = registers.iter().map(|reg| loads[reg].clone()).collect(); + instructions.extend(stores); + let id = BlockId(0); + result.push(ExecutionUnit { + entry_block_id: id, + blocks: [( + id, + BasicBlock { + id, + params: Vec::new(), + instructions, + terminator: SIRTerminator::Return, + }, + )] + .into_iter() + .collect(), + register_map, + }); + } + // No exports for unused clocks: their ordinary topology already avoids settling. + (!result.is_empty()).then_some(result) +} diff --git a/crates/celox/src/backend/native/mod.rs b/crates/celox/src/backend/native/mod.rs index 3a41492b801..0b0e613dca3 100644 --- a/crates/celox/src/backend/native/mod.rs +++ b/crates/celox/src/backend/native/mod.rs @@ -1,4 +1,5 @@ pub mod backend; +mod clock_aliases; mod compile_resources; mod image_file; mod lanes; diff --git a/crates/celox/src/backend/tiered.rs b/crates/celox/src/backend/tiered.rs index bf76d552d4c..fdb70cbee83 100644 --- a/crates/celox/src/backend/tiered.rs +++ b/crates/celox/src/backend/tiered.rs @@ -1391,6 +1391,23 @@ impl SimBackend for TieredBackend { } } + fn eval_clock_aliases(&mut self, event: TieredEventRef) -> Result { + // Do not promote during a partial settle: normal evaluation boundaries + // continue to own tier changes and their accounting. + match &mut self.phase { + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + Phase::Compiled(CompiledTier::Native(native)) => { + let event = native.id_to_event_slice()[event.id()]; + native.eval_clock_aliases(event) + } + _ => Ok(false), + } + } + fn eval_apply_ff_at(&mut self, event: TieredEventRef) -> Result<(), SimulatorErrorCode> { self.maybe_promote(); self.maybe_upgrade(); diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 1e4653b2e21..ca90b98db52 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -2394,7 +2394,7 @@ mod host { celox_runtime::set_level, ); if let Some(old) = moved { - if info.comb_read { + if self.clock_move_needs_settle(event, info.comb_read)? { self.dirty = true; } if info.fires(old, active) { @@ -2402,7 +2402,7 @@ mod host { } } self.backend.set(info.signal, inactive.level()); - if info.comb_read || observers { + if self.clock_move_needs_settle(event, info.comb_read)? || observers { self.dirty = true; } Ok(()) @@ -2421,12 +2421,24 @@ mod host { } self.backend .set(info.signal, info.active_edge().opposite().level()); - if info.comb_read || !self.program.runtime_schema.comb_observers.is_empty() { + if self.clock_move_needs_settle(event, info.comb_read)? + || !self.program.runtime_schema.comb_observers.is_empty() + { self.dirty = true; } Ok(()) } + /// Publish wiring immediately when the previous state was settled; + /// otherwise leave the entire pending evaluation to the normal path. + fn clock_move_needs_settle( + &mut self, + event: B::Event, + comb_read: bool, + ) -> Result { + Ok(comb_read && (self.dirty || !self.backend.eval_clock_aliases(event)?)) + } + /// Run the event's domain as its active edge does, with the signal /// left as it is: the unit of the edge APIs. fn fire(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { @@ -2522,7 +2534,9 @@ mod host { // wait behind the kernel's stores (4 KiB aliasing), // which made a period cost almost two domain runs. self.backend.set(info.signal, edge.level()); - if info.comb_read || !self.program.runtime_schema.comb_observers.is_empty() { + if self.clock_move_needs_settle(event, info.comb_read)? + || !self.program.runtime_schema.comb_observers.is_empty() + { self.dirty = true; } return Ok(()); @@ -2539,7 +2553,7 @@ mod host { else { return Ok(()); }; - if info.comb_read { + if self.clock_move_needs_settle(event, info.comb_read)? { self.dirty = true; } if info.fires(old, edge) { @@ -2559,7 +2573,7 @@ mod host { && !self.finish_sites && self.backend.runs_derived_edge_units() { - return self.edge_unit(info, edge, unit); + return self.edge_unit(event, info, edge, unit); } let plans = std::sync::Arc::clone(&self.derived_ticks); let plan = plans.get(event.id()).and_then(Option::as_ref); @@ -2581,6 +2595,7 @@ mod host { #[inline(never)] fn edge_unit( &mut self, + event: B::Event, info: celox_runtime::EventEdge, edge: celox_runtime::Edge, unit: DerivedEdgeUnit, @@ -2597,9 +2612,9 @@ mod host { return Ok(()); }; let fires = info.fires(old, edge); + let comb_read = self.clock_move_needs_settle(event, info.comb_read)?; if let Some(flag) = self.derived_settle { - self.backend - .set(flag, u8::from(self.dirty || info.comb_read)); + self.backend.set(flag, u8::from(self.dirty || comb_read)); } let index = match edge { celox_runtime::Edge::Rising => unit.rising, @@ -2613,7 +2628,7 @@ mod host { // in the plan walk. let outcome = if unit.gated || fires { celox_runtime::EdgeOutcome::Settled - } else if info.comb_read { + } else if comb_read { celox_runtime::EdgeOutcome::Moved } else { celox_runtime::EdgeOutcome::Stored @@ -3930,7 +3945,11 @@ mod host { assign seen = {seen}; }}" ); - let mut sim = Simulator::builder(&source, "Top").build().unwrap(); + // The interpreter requests the generic full-settle fallback. + // Native wiring-only cones are checked in native_clock_aliases. + let mut sim = Simulator::builder(&source, "Top") + .build_interpreter() + .unwrap(); let clk = sim.event("clk"); sim.posedge(clk).unwrap(); assert!(!sim.dirty); diff --git a/crates/celox/tests/frontends/systemverilog/class.rs b/crates/celox/tests/frontends/systemverilog/class.rs index c7d1a3e9e7c..d17b3770a43 100644 --- a/crates/celox/tests/frontends/systemverilog/class.rs +++ b/crates/celox/tests/frontends/systemverilog/class.rs @@ -6,6 +6,7 @@ sv_backends! { fn class_imported_member_type_dimensions(sim) { @case "class::imported_member_type_dimensions"; } fn class_imported_member_type_inheritance(sim) { @case "class::imported_member_type_inheritance"; } fn class_package_constant_class_defaults(sim) { @case "class::package_constant_class_defaults"; } + fn class_waits_on_static_properties(sim) { @case "class::waits_on_static_properties"; } fn class_package_constant_type_arguments(sim) { @case "class::package_constant_type_arguments"; } fn class_named_aggregate_type_arguments(sim) { @case "class::named_aggregate_type_arguments"; } fn class_generate_scope_enum_type_arguments(sim) { @case "class::generate_scope_enum_type_arguments"; } @@ -211,6 +212,103 @@ sv_backends! { } } +/// A write of a class property does not wake a process waiting on it, so a +/// wait whose condition reads one is rejected instead of never waking. The +/// condition reads it in a method through `this`, through a handle, through +/// a queue held in a property and through a function. +#[test] +fn waits_on_class_properties_are_unsupported() { + let waits = [ + "wait (m_state >= s);", + "wait (other.m_state >= s);", + "wait (q.size() != 0);", + "wait (reached(s));", + ]; + for wait in waits { + let source = format!( + "class C; + int m_state; + int q[$]; + C other; + function bit reached(int s); return m_state >= s; endfunction + task wait_for(int s); {wait} $display(\"reached %0d at %0d\", s, $time); endtask + endclass + module Top; + initial begin + automatic C c = new; + c.other = c; + fork + c.wait_for(2); + begin #1 c.m_state = 1; #1 c.m_state = 2; c.q.push_back(1); end + join + end + endmodule" + ); + for four_state in [false, true] { + let builder = || { + celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("class.sv"))], + "Top", + ) + .four_state(four_state) + }; + let errors = [ + builder().build_native().err(), + builder().build_cranelift().err(), + builder().build_wasm().err(), + builder().build_interpreter().err(), + ]; + for error in errors { + let error = error + .unwrap_or_else(|| panic!("{wait} must be rejected")) + .to_string(); + assert!(error.contains("in a wait condition"), "{wait}: {error}"); + } + } + } +} + +/// The default of an argument is read only where a call omits the argument, +/// so a property-reading default does not reject a wait that supplies it. +#[test] +fn waits_read_property_defaults_only_when_omitted() { + let source = |call: &str| { + format!( + "`timescale 1ns/1ns + class C; int state; endclass + module Top(output int seen); + C c; + int signal; + function automatic bit ready(int x = c.state); return x != 0; endfunction + initial begin + c = new; + fork + begin wait ({call}); seen = $time; end + begin #2 signal = 1; end + join + end + endmodule" + ) + }; + let supplied = source("ready(signal)"); + let mut sim = + celox::Simulation::from_sv_sources(vec![(supplied.as_str(), Path::new("class.sv"))], "Top") + .build_interpreter() + .unwrap(); + sim.run_until(5).unwrap(); + let seen = sim.signal("seen"); + assert_eq!(sim.get(seen), BigUint::from(2u8)); + let omitted = source("ready()"); + let Err(error) = + celox::Simulation::from_sv_sources(vec![(omitted.as_str(), Path::new("class.sv"))], "Top") + .build_interpreter() + else { + panic!("a wait reading a property through a default is rejected"); + }; + let error = error.to_string(); + assert!(error.contains("in a wait condition"), "{error}"); +} + #[test] fn randomizing_four_state_properties_is_rejected() { for (body, want) in [ diff --git a/crates/celox/tests/native_clock_aliases.rs b/crates/celox/tests/native_clock_aliases.rs new file mode 100644 index 00000000000..5135b786858 --- /dev/null +++ b/crates/celox/tests/native_clock_aliases.rs @@ -0,0 +1,170 @@ +//! Native clock-cone specialization, including its optional image exports. +#![cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + +use celox::{NativeBackend, SharedNativeCode}; +use celox::{NativeProgramImage, SimBackend, Simulator}; +use std::sync::Arc; + +const SOURCE: &str = r#" +module Child (clk: input clock, d: input bit<8>, q: output bit<8>) { + always_ff (clk) { q = d; } +} +module Top (clk: input clock, d: input bit<8>, q: output bit<8>) { + inst child: Child (clk, d, q); +} +"#; + +fn image(source: &str, four_state: bool) -> NativeProgramImage { + Simulator::builder(source, "Top") + .four_state(four_state) + .compile_native() + .unwrap() + .into_program_image() +} + +fn exports(image: &NativeProgramImage) -> usize { + image + .code_entries() + .iter() + .filter(|entry| entry.name.starts_with("clock_alias_update[")) + .count() +} + +#[test] +fn clock_wiring_projection_matches_full_settle_after_image_roundtrip() { + let image = image(SOURCE, false); + assert_eq!(exports(&image), 1); + let image = + NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()).unwrap(); + // SAFETY: this test just compiled and serialized the image. + let shared = Arc::new(unsafe { SharedNativeCode::from_image(image) }.unwrap()); + let mut fast = NativeBackend::from_shared(shared.clone()); + let mut full = NativeBackend::from_shared(shared); + let event = fast.id_to_event_slice()[0]; + use celox::EventHandle; + let clock = fast.resolve_signal(&event.addr()); + fast.eval_comb().unwrap(); + full.eval_comb().unwrap(); + for value in [1u8, 0, 1, 0] { + fast.clear_triggered_bits(); + full.clear_triggered_bits(); + fast.set(clock, value); + full.set(clock, value); + assert!(fast.eval_clock_aliases(event).unwrap()); + full.eval_comb().unwrap(); + assert_eq!(fast.get_triggered_bits(), full.get_triggered_bits()); + for (addr, &offset) in &fast.layout().offsets { + let width = fast.layout().plane_size(addr); + let bytes = |backend: &NativeBackend| { + let (ptr, _) = backend.memory_as_ptr(); + // SAFETY: layout ranges describe live signal storage. Exclude + // host pointers and scratch memory, which differ per instance. + unsafe { std::slice::from_raw_parts(ptr.add(offset), width) }.to_vec() + }; + assert_eq!(bytes(&fast), bytes(&full), "{addr:?}"); + } + } +} + +#[test] +fn falling_edges_publish_aliases_and_dirty_inputs_still_settle() { + let mut sim = Simulator::builder(SOURCE, "Top") + .four_state(false) + .build_native() + .unwrap(); + let clk = sim.event("clk"); + let d = sim.signal("d"); + let q = sim.signal("q"); + let child_clk = sim.child_signal(&[("child", 0)], "clk"); + for value in [17u8, 29, 255] { + // Leave this data write dirty: the projection must not suppress it. + sim.set(d, value); + sim.active_edge(clk).unwrap(); + assert_eq!(sim.get(q), value.into()); + assert_eq!(sim.get(child_clk), 1u8.into()); + sim.inactive_edge(clk).unwrap(); + // Inspect the backend directly so this assertion cannot cause a + // deferred full settle and hide a missing alias publication. + assert_eq!(sim.backend_ref().get(child_clk), 0u8.into()); + // Already settled rising edge takes the specialized path. + sim.active_edge(clk).unwrap(); + assert_eq!(sim.get(q), value.into()); + sim.inactive_edge(clk).unwrap(); + } +} + +#[test] +fn clock_data_dependencies_and_four_state_keep_full_settle() { + assert_eq!(exports(&image(SOURCE, true)), 0); + let source = SOURCE.replace( + "inst child: Child (clk, d, q);", + "var data: bit<8>; assign data = if (clk as u8) != 0 ? d : 0; inst child: Child (clk, d: data, q);" + ); + assert_eq!(exports(&image(&source, false)), 0); +} + +#[test] +fn coincident_clock_moves_publish_both_wiring_cones() { + let source = r#" + module Counter (clk: input clock, q: output bit<8>) { + always_ff (clk) { q += 1; } + } + module Top ( + clk_a: input 'fast clock, clk_b: input 'slow clock, + a: output 'fast bit<8>, b: output 'slow bit<8>, + ) { + inst first: Counter (clk: clk_a, q: a); + inst second: Counter (clk: clk_b, q: b); + } + "#; + let compiled = Simulator::builder(source, "Top") + .four_state(false) + .compile_native() + .unwrap(); + assert_eq!(exports(compiled.program_image()), 2); + let mut sim = compiled.initialize().unwrap(); + let a = sim.event("clk_a"); + let b = sim.event("clk_b"); + use celox_runtime::Edge::{Falling, Rising}; + for expected in 1..=4u8 { + sim.edges(&[(a, Rising), (b, Rising)]).unwrap(); + assert_eq!(sim.get(sim.signal("a")), expected.into()); + assert_eq!(sim.get(sim.signal("b")), expected.into()); + sim.edges(&[(b, Falling), (a, Falling)]).unwrap(); + for child in ["first", "second"] { + let clk = sim.child_signal(&[(child, 0)], "clk"); + assert_eq!(sim.backend_ref().get(clk), 0u8.into()); + } + } +} + +#[test] +fn unrelated_combinational_loop_does_not_prevent_clock_specialization() { + let source = SOURCE.replace( + "always_ff (clk) { q = d; }", + r#" + var sum: bit<8>; + always_comb { + sum = 0; + for i in 0..1024 { + if i <: (d as u32) { sum += 1; } + } + } + always_ff (clk) { q = sum; } + "#, + ); + let compiled = Simulator::builder(&source, "Top") + .four_state(false) + .compile_native() + .unwrap(); + assert_eq!(exports(compiled.program_image()), 1); + let mut sim = compiled.initialize().unwrap(); + let clk = sim.event("clk"); + let d = sim.signal("d"); + for expected in [3u8, 99, 255] { + sim.modify(|io| io.set(d, expected)).unwrap(); + sim.active_edge(clk).unwrap(); + assert_eq!(sim.get(sim.signal("q")), expected.into()); + sim.inactive_edge(clk).unwrap(); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index ea203f1ba21..46cb4c3a12c 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -335,8 +335,12 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: - Behavioral and verification constructs: intra-assignment timing controls (`a = #1 b`), delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), named events and `->`, `wait fork` / `disable fork`, temporal concurrent assertions beyond the Boolean subset below, `force` / `release`. -- Timing controls in processes: impure function calls in event expressions, and - `wait` or event expressions reading a static task argument. +- Timing controls in processes: impure function calls in event expressions, + `wait` or event expressions reading a static task argument, and `wait` + conditions or event expressions reading a class property (directly, through + a handle or a function, or a container held in one), since a write of the + property does not wake the waiting process. Static class properties are + module variables and may be waited on. - Nonblocking assignments inside `always_latch` ([#431](https://github.com/celox-sim/celox/issues/431)); use blocking assignments for the supported latch subset. - Inferred latches inside `always_comb` are rejected by default. Set `inferred_latch = "warn"` or `"allow"` in `celox.toml` under `[diagnostics]` to permit retained blocking assignments. Ordinary `always @*` and explicit `always_latch` do not require this option. - Ports and instances: non-ANSI port expressions such as `module m({a, b}, c[3:0], .p(d))` ([#1953](https://github.com/celox-sim/celox/issues/1953)), `ref` ports diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 12758812b52..f540ad6bb28 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -218,7 +218,9 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 - 振る舞い記述・検証向けの構文:`final`、代入内のタイミング制御(`a = #1 b`)、遅延付き継続代入([#444](https://github.com/celox-sim/celox/issues/444))、 named event と `->`、`fork` / `join`、`wait fork` / `disable fork`、下記のBoolean部分集合を超える並行アサーション、`force` / `release`。 - プロセス内のタイミング制御:イベント式と `iff` 条件内の impure な関数呼び出し、 - static task 引数を読む `wait` 条件、イベント式、`iff` 条件。 + static task 引数を読む `wait` 条件、イベント式、`iff` 条件。クラスのプロパティを(直接、ハンドルや関数を通じて、 + またはプロパティが持つコンテナとして)読む `wait` 条件とイベント式。プロパティへの書き込みで待機中のプロセスが + 起きないためです。static プロパティはモジュールの変数なので待機できます。 - `always_latch` 内のノンブロッキング代入([#431](https://github.com/celox-sim/celox/issues/431))。対応するラッチではブロッキング代入を使用してください。 - `always_comb` の暗黙のラッチ推論はデフォルトで拒否します。`celox.toml` の `[diagnostics]` で `inferred_latch = "warn"` または `"allow"` を指定すると許可できます。通常の `always @*` と明示的な `always_latch` にはこの設定は不要です。 - ポートとインスタンス:non-ANSI 形式のポート式(`module m({a, b}, c[3:0], .p(d))` など、[#1953](https://github.com/celox-sim/celox/issues/1953))、`ref` ポート([#427](https://github.com/celox-sim/celox/issues/427))、