From 903b7899fc733746b0e9bcf59a26d4212d845586 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 18:41:46 +0900 Subject: [PATCH 1/4] feat(sv): support $sampled in processes Implement sampled values for static variables using copies captured before advancing to a later timestamp (IEEE 1800-2023 16.5.1 and 16.9.3). Initialize from declarations, preserve automatic variables, and copy strided arrays through their layouts. Same-timestamp host resumptions and writes retain the Preponed baseline; untimed Simulator calls each form a slot. Resolve sampled select operands before hoisting nested calls, including calls with side effects. Cover timed host-only writes, repeated run_until calls, bounded runs, step, advance_to, and report watching. Verify that the compiled scheduler actually executes in the regression. The runtime schema gains sample_shadows; native image version is 42. Combinational $sampled and handle operands remain unsupported in this stack member. Validation: - sv_sampled: 35 passed across interpreter, native, actual Cranelift and WASM. - Celox/runtime unit tests: 309 passed. - Time, stop, state-file, runtime API, clock and image consumers: 110 passed, 2 ignored. - Formatting and affected-crate Clippy with -D warnings. Change-Id: I764da6c419a54df2ca88f784d797f22e5c8520eb --- crates/celox-design/src/lib.rs | 6 + crates/celox-design/src/schedule.rs | 4 + crates/celox-frontend-core/src/sdk.rs | 1 + .../src/symbolic/artifact.rs | 3 + .../src/symbolic/assembly.rs | 20 ++ crates/celox-frontend-sv/src/lowering.rs | 59 +++- crates/celox-frontend-sv/src/lowering/ff.rs | 76 ++++- .../src/lowering/procedural.rs | 22 ++ crates/celox-frontend-veryl/src/artifact.rs | 1 + crates/celox-runtime/src/lib.rs | 23 ++ crates/celox-runtime/src/schedule.rs | 7 + crates/celox-runtime/src/simulation/batch.rs | 2 - .../celox-runtime/src/simulation/compiled.rs | 20 +- crates/celox-runtime/src/simulation/mod.rs | 14 + crates/celox-runtime/src/simulation/round.rs | 4 +- crates/celox-runtime/src/simulation/time.rs | 15 +- .../src/ast/expression_binding/direct.rs | 6 + .../celox-sv-analyzer/src/ast/expressions.rs | 28 ++ .../celox-sv-analyzer/src/system_functions.rs | 13 +- crates/celox/src/backend/native/backend.rs | 4 + crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulation.rs | 20 +- crates/celox/src/simulator.rs | 169 ++++++++++- crates/celox/tests/sv_sampled.rs | 264 ++++++++++++++++++ docs/guide/systemverilog-reference.md | 16 ++ docs/ja/guide/systemverilog-reference.md | 13 + 26 files changed, 760 insertions(+), 52 deletions(-) create mode 100644 crates/celox/tests/sv_sampled.rs diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 3f34f2b61fc..a85be9c3be6 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -1105,6 +1105,11 @@ pub struct RuntimeSchema { /// most one per module instance. Before each round a timed scheduler /// stores the current time into each, as [`TIME_SLOT_WIDTH`] bits. pub time_slots: Vec, + /// Variables of `$sampled` operands and their copies, which hold the + /// value of the variable in the Preponed region (IEEE 1800-2023 + /// 16.5.1): a host copies each variable into its copy when a time slot + /// is over, and once before the first. + pub sample_shadows: Vec<(A, A)>, /// The state a compiled scheduler exchanges with the runtime, and the /// scheduler itself once one is generated. Present when the design has /// process kernels. @@ -1359,6 +1364,7 @@ impl Default for RuntimeSchema { host_request_sites: Vec::new(), active_commits: Vec::new(), time_slots: Vec::new(), + sample_shadows: Vec::new(), scheduler: None, derived_edges: Vec::new(), settle_partitions: None, diff --git a/crates/celox-design/src/schedule.rs b/crates/celox-design/src/schedule.rs index bbe9a4a74fe..a8b28da4739 100644 --- a/crates/celox-design/src/schedule.rs +++ b/crates/celox-design/src/schedule.rs @@ -46,6 +46,9 @@ pub struct ScheduleModel { /// Objects the scheduler stores the current time into /// ([`RuntimeSchema::time_slots`]). pub time_slots: Vec, + /// Sampled variables and their copies + /// ([`RuntimeSchema::sample_shadows`]). + pub sample_shadows: Vec<(A, A)>, /// The compiled scheduler, if one was generated /// ([`RuntimeSchema::scheduler`]). pub scheduler: Option>, @@ -152,6 +155,7 @@ impl ScheduleModel { .any(|site| matches!(site.kind, RuntimeEventKind::Finish)), active_commits: schema.active_commits.clone(), time_slots: schema.time_slots.clone(), + sample_shadows: schema.sample_shadows.clone(), scheduler: schema.scheduler.clone(), } } diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 978966f9d2f..b17909e54cd 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1972,6 +1972,7 @@ pub fn lower_frontend_artifact( nba_switches: Vec::new(), host_request_sites: Vec::new(), time_slot: None, + sample_shadows: Vec::new(), }; let symbolic = SymbolicRtl { modules: [(module_id, sim_module.clone())].into_iter().collect(), diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index 13d9d614ced..6f6acef4356 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -159,6 +159,9 @@ pub struct SimModule { /// The variable through which the module's code reads the simulation /// time; see `RuntimeSchema::time_slots`. pub time_slot: Option, + /// Variables and their sampled copies; see + /// `RuntimeSchema::sample_shadows`. + pub sample_shadows: Vec<(SourceVarId, SourceVarId)>, } /// A nonblocking site whose kernel has two paths, as diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 288fda6029b..766715c6749 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2135,6 +2135,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( nba_sites, host_request_sites, time_slots, + sample_shadows, .. } = timing; let source_sir = SirProgram { @@ -2386,6 +2387,10 @@ pub fn schedule_symbolic_rtl_reporting_loops( .collect(); let active_commits: Vec = active_commits.into_iter().map(project).collect(); let time_slots: Vec = time_slots.into_iter().map(project).collect(); + let sample_shadows: Vec<(StateAddr, StateAddr)> = sample_shadows + .into_iter() + .map(|(variable, copy)| (project(variable), project(copy))) + .collect(); let root_instance = expanded[&InstancePath(Vec::new())]; let settle_partitions = settle_flags.map(|settle| { let mut marks: HashMap> = HashMap::default(); @@ -2509,6 +2514,12 @@ pub fn schedule_symbolic_rtl_reporting_loops( .flat_map(|(source, counter)| [source.id, *counter]), ); } + // The host copies each sampled variable into its copy. + timing_read_roots.extend( + sample_shadows + .iter() + .flat_map(|&(variable, copy)| [variable, copy]), + ); // A package variable's state object maps back to the package's own // variable, not to one of its aliases. let state_to_source = source_to_state @@ -2561,6 +2572,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( host_request_sites, active_commits, time_slots, + sample_shadows, scheduler, derived_edges: Vec::new(), settle_partitions, @@ -4113,6 +4125,7 @@ struct TimingMetadata { nba_sites: Vec>, host_request_sites: Vec>, time_slots: Vec, + sample_shadows: Vec<(AbsoluteAddr, AbsoluteAddr)>, nba_switches: Vec>, } @@ -4435,6 +4448,7 @@ fn relocate_timing( nba_sites: Vec::new(), host_request_sites: Vec::new(), time_slots: Vec::new(), + sample_shadows: Vec::new(), nba_switches: Vec::new(), }; for (&instance, module) in instances { @@ -4470,6 +4484,12 @@ fn relocate_timing( }), ); metadata.time_slots.extend(module.time_slot.map(locate)); + metadata.sample_shadows.extend( + module + .sample_shadows + .iter() + .map(|&(variable, copy)| (locate(variable), locate(copy))), + ); metadata.nba_switches.extend( module .nba_switches diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 763987247b7..98a11f435f2 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -87,6 +87,9 @@ struct SvVariable { hidden: bool, /// Compiler-generated external override slot: (target, is_enable). force_control: Option<(SourceVarId, bool)>, + /// The variable whose sampled value this hidden copy holds + /// (`SimModule::sample_shadows`). + sampled_from: Option, } /// Whether `expr` reads a string variable: after its calls are hoisted, a @@ -126,13 +129,14 @@ impl SvVariable { } /// A hidden variable other than the time slot, whose value the lowered - /// code computes. The time slot is state the scheduler writes, and an - /// event expression's variables are state its process and its - /// continuous assignment share. + /// code computes. The time slot and the sampled copies are state the + /// scheduler writes, and an event expression's variables are state its + /// process and its continuous assignment share. fn is_scratch(&self) -> bool { self.hidden && self.path != [TIME_SLOT] && self.force_control.is_none() + && self.sampled_from.is_none() && !self.path[0].starts_with(EVENT_PREFIX) } } @@ -2198,6 +2202,7 @@ fn prepare_external_hierarchy_collecting( source: variable.source.clone(), hidden: !variable.module_affiliated, force_control: None, + sampled_from: None, }, ) }) @@ -3629,6 +3634,7 @@ fn lower_module_with_overrides( source: None, hidden: false, force_control: None, + sampled_from: None, }; name_to_id.insert(port.name().to_string(), id); port_order.push(id); @@ -3713,6 +3719,7 @@ fn lower_module_with_overrides( source: None, hidden: false, force_control: None, + sampled_from: None, }; name_to_id.insert(signal.name().to_string(), id); // The package's object, or the other instance's, has its own @@ -3793,6 +3800,7 @@ fn lower_module_with_overrides( source: None, hidden: false, force_control: None, + sampled_from: None, }, ); } @@ -4005,6 +4013,7 @@ fn lower_module_with_overrides( nba_switches, host_request_sites, time_slot: name_to_id.get(TIME_SLOT).copied(), + sample_shadows: Vec::new(), }, variables, port_order, @@ -4793,6 +4802,12 @@ pub(crate) fn attach_instance_glue( } // Combinational processes may read the time too. module.time_slot = signal_names.get(TIME_SLOT).copied(); + let mut sample_shadows: Vec<_> = parent_variables + .iter() + .filter_map(|(©, variable)| variable.sampled_from.map(|variable| (variable, copy))) + .collect(); + sample_shadows.sort_by_key(|&(variable, copy)| (variable.0, copy.0)); + module.sample_shadows = sample_shadows; for (instance, child_id, child, connections) in resolved_instances { let glue = build_instance_glue( &parent_variables, @@ -5187,6 +5202,7 @@ fn lower_initial_processes( // Control slots are not signals of the design. hidden: true, force_control: None, + sampled_from: None, }, ); id @@ -5831,6 +5847,7 @@ fn ensure_parent_output_signals( source: None, hidden: false, force_control: None, + sampled_from: None, }; parent .variables @@ -7713,6 +7730,7 @@ fn lower_bit_vector_function_slt( | SystemFunction::Isunbounded | SystemFunction::Signed | SystemFunction::Unsigned + | SystemFunction::Sampled | SystemFunction::Bits | SystemFunction::Size | SystemFunction::Dimensions @@ -9077,6 +9095,15 @@ fn runtime_select_as_shift( } fn expr_from_const_expr(expr: &sv::ir::ConstExpr) -> Option { + expr_from_const_expr_with_calls(expr, false) +} + +/// Reconstruct a select operand, optionally retaining nested runtime calls. +fn expr_from_const_expr_with_calls( + expr: &sv::ir::ConstExpr, + allow_calls: bool, +) -> Option { + let convert = |expr| expr_from_const_expr_with_calls(expr, allow_calls); Some(match expr { sv::ir::ConstExpr::Literal(value) => sv::ir::Expr::Literal(value.clone()), sv::ir::ConstExpr::Ident(name) => sv::ir::Expr::Ident(name.clone()), @@ -9086,13 +9113,13 @@ fn expr_from_const_expr(expr: &sv::ir::ConstExpr) -> Option { lsb, signed, } => sv::ir::Expr::Select { - expr: Box::new(expr_from_const_expr(expr)?), + expr: Box::new(convert(expr)?), msb: (**msb).clone(), lsb: (**lsb).clone(), signed: *signed, }, sv::ir::ConstExpr::Select { expr, bit } => sv::ir::Expr::Select { - expr: Box::new(expr_from_const_expr(expr)?), + expr: Box::new(convert(expr)?), msb: (**bit).clone(), lsb: (**bit).clone(), signed: false, @@ -9102,28 +9129,36 @@ fn expr_from_const_expr(expr: &sv::ir::ConstExpr) -> Option { width, signed, } => sv::ir::Expr::Resize { - expr: Box::new(expr_from_const_expr(expr)?), + expr: Box::new(convert(expr)?), width: *width, signed: *signed, }, + sv::ir::ConstExpr::Function { callee, args, .. } if allow_calls => sv::ir::Expr::Call { + callee: callee.clone(), + arg_order: Vec::new(), + args: args + .iter() + .map(|arg| convert(arg).map(Some)) + .collect::>()?, + }, sv::ir::ConstExpr::Function { .. } => return None, sv::ir::ConstExpr::Unary { op, expr } => sv::ir::Expr::Unary { op: *op, - expr: Box::new(expr_from_const_expr(expr)?), + expr: Box::new(convert(expr)?), }, sv::ir::ConstExpr::Binary { left, op, right } => sv::ir::Expr::Binary { - left: Box::new(expr_from_const_expr(left)?), + left: Box::new(convert(left)?), op: *op, - right: Box::new(expr_from_const_expr(right)?), + right: Box::new(convert(right)?), }, sv::ir::ConstExpr::Mux { condition, then_expr, else_expr, } => sv::ir::Expr::Mux { - condition: Box::new(expr_from_const_expr(condition)?), - then_expr: Box::new(expr_from_const_expr(then_expr)?), - else_expr: Box::new(expr_from_const_expr(else_expr)?), + condition: Box::new(convert(condition)?), + then_expr: Box::new(convert(then_expr)?), + else_expr: Box::new(convert(else_expr)?), }, }) } diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 26ef54d8fb1..7a1bbbff731 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -102,6 +102,8 @@ pub(super) struct Ff<'p, 'a> { /// The flush-point site of a process with deferred assertions, whose /// queue their actions wait in. flush_site: Option, + /// A combinational process is being lowered. + combinational: bool, } fn stable(var_id: SourceVarId) -> Addr { @@ -161,9 +163,44 @@ impl<'p, 'a> Ff<'p, 'a> { host_request_sites: Vec::new(), nba_switches: Vec::new(), flush_site: None, + combinational: false, } } + /// The operand of `$sampled` (IEEE 1800-2023 16.9.3) with each static + /// variable read through its sampled copy. Automatic variables and the + /// lowering's own temporaries keep their current value (16.5.1). A + /// combinational process reruns when its inputs change, not when their + /// sampled values do, so it cannot read them. + fn sampled( + &mut self, + args: &[Option], + ) -> Result { + if self.combinational { + return Err(unsupported("$sampled in combinational logic")); + } + let [Some(operand)] = args else { + return Err(unsupported("operand of `$sampled`")); + }; + let operand = self.propagate(operand); + let mut names = HashSet::default(); + expr_idents(&operand, &mut names); + let mut renames = HashMap::default(); + for name in names { + let Some(id) = self.m.id(&name) else { + continue; + }; + if self.m.is_hidden(id) { + continue; + } + if self.m.var(id).value_kind.is_handle() { + return Err(unsupported("$sampled of a string or class handle")); + } + renames.insert(name, self.m.sampled_copy(id)); + } + Ok(rename_idents(&operand, &renames)) + } + /// Whether `stmts`, or a subroutine they call, including in timing /// controls and the defaults of omitted arguments, hold a deferred /// assertion. @@ -779,8 +816,18 @@ impl<'p, 'a> Ff<'p, 'a> { } let mut lowered = Vec::with_capacity(args.len()); for arg in args { - let arg = self.hoist_const(arg, calls)?; - lowered.push(expr_from_const_expr(&arg).ok_or_else(|| { + // $sampled must rewrite its operand before any nested + // call reads it. Hoisting first hides the original inputs + // behind a temporary holding their current-slot value. + let arg = if matches!( + callee, + sv::ir::Callee::System(sv::ir::SystemFunction::Sampled) + ) { + arg.clone() + } else { + self.hoist_const(arg, calls)? + }; + lowered.push(expr_from_const_expr_with_calls(&arg, true).ok_or_else(|| { unsupported(format!("argument of `{callee}` in a select")) })?); } @@ -789,8 +836,19 @@ impl<'p, 'a> Ff<'p, 'a> { callee: callee.clone(), args: lowered.into_iter().map(Some).collect(), }; - let sv::ir::Expr::Ident(result) = self.hoist(&call)? else { - return Err(unsupported(format!("call of `{callee}` in a select"))); + let result = match self.hoist(&call)? { + sv::ir::Expr::Ident(result) => result, + // A sampled operand, as `$sampled(i + 1)`: its value at + // this point is the select's. + hoisted @ sv::ir::Expr::Binary { .. } + | hoisted @ sv::ir::Expr::Unary { .. } => { + let value = self.eval(&hoisted, None)?; + let width = self.b.register(&value).width(); + let (temp, name) = self.m.temp("select", width, false, true); + self.store(temp, SIROffset::Static(0), width, value); + name + } + _ => return Err(unsupported(format!("call of `{callee}` in a select"))), }; let result = ConstExpr::Ident(result); calls.push((expr.clone(), result.clone())); @@ -1074,6 +1132,14 @@ impl<'p, 'a> Ff<'p, 'a> { self.assign(&sv::ir::LValue::Ident(name.clone()), value)?; Expr::Ident(name) } + Expr::Call { + callee: sv::ir::Callee::System(sv::ir::SystemFunction::Sampled), + args, + .. + } => { + let operand = self.sampled(args)?; + self.hoist(&operand)? + } Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::Fread), args, @@ -4064,6 +4130,7 @@ impl<'p, 'a> Ff<'p, 'a> { // `initial` blocks, like `always_comb`, as Verilator settles them. let runs_at_time_zero = always_comb || !self.m.four_state; self.direct = true; + self.combinational = true; let mut reads = self.m.implicit_reads(body, always_comb); reads.extend(self.m.implicit_reads(sensitivity_body, always_comb)); for stmt in body { @@ -6076,6 +6143,7 @@ impl Ff<'_, '_> { source: None, hidden: true, force_control: None, + sampled_from: None, value_kind: Default::default(), }, ); diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 37095d43ae5..404fb18d038 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -974,6 +974,7 @@ impl<'a> ProcModule<'a> { source: None, hidden: true, force_control: None, + sampled_from: None, }, ); self.name_to_id.insert(name, id); @@ -982,6 +983,24 @@ impl<'a> ProcModule<'a> { } /// A hidden variable with the shape of `id`, two-state when `two_state`. + /// The hidden copy that holds the sampled value of variable `id` + /// (IEEE 1800-2023 16.5.1), created on first use. + pub fn sampled_copy(&mut self, id: SourceVarId) -> String { + if let Some((name, _)) = self + .name_to_id + .iter() + .find(|(_, copy)| self.variables[copy].sampled_from == Some(id)) + { + return name.clone(); + } + let (copy, name) = self.shadow(id, "sampled", false); + self.variables + .get_mut(©) + .expect("a new copy") + .sampled_from = Some(id); + name + } + pub fn shadow( &mut self, id: SourceVarId, @@ -1040,6 +1059,7 @@ impl<'a> ProcModule<'a> { source: None, hidden: true, force_control: None, + sampled_from: None, }; let id = next_var_id(&mut self.next_id); self.variables.insert(id, variable); @@ -1070,6 +1090,7 @@ impl<'a> ProcModule<'a> { source: None, hidden: true, force_control: None, + sampled_from: None, ..variable }, ); @@ -1597,6 +1618,7 @@ pub(super) fn register_locals( source: None, hidden: true, force_control: None, + sampled_from: None, }, ); name_to_id.insert(local.name.clone(), id); diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 49fdb07fc6b..526b5b7dbf0 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -682,6 +682,7 @@ pub(crate) fn project_module_with_ids( nba_switches: Vec::new(), host_request_sites: Vec::new(), time_slot: None, + sample_shadows: Vec::new(), }, ids, inferred_latch_diagnostics, diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs index 2a07d54399b..71aaa07ba01 100644 --- a/crates/celox-runtime/src/lib.rs +++ b/crates/celox-runtime/src/lib.rs @@ -142,6 +142,29 @@ pub struct SignalRef { pub array_layout: Option, } +/// Copy the value of `from`, with its unknown bits, into `to`, a signal of +/// the same width and state form. +pub fn copy_signal(backend: &mut B, from: SignalRef, to: SignalRef) { + if from.array_layout.is_some() || to.array_layout.is_some() { + // Each array has its own layout, packed or with strided elements: + // the backend gathers and scatters the elements. + let (value, mask) = backend.get_four_state(from); + backend.set_four_state(to, value, mask); + return; + } + let planes = if backend.layout().four_state && from.is_4state { + 2 + } else { + 1 + }; + let bytes = celox_state_layout::get_byte_size(from.width) * planes; + let (memory, size) = backend.memory_as_mut_ptr(); + assert!(from.offset + bytes <= size && to.offset + bytes <= size); + // SAFETY: both ranges are in the backend's memory. Signal views can + // alias, so use the copy operation that permits overlapping ranges. + unsafe { std::ptr::copy(memory.add(from.offset), memory.add(to.offset), bytes) }; +} + #[cfg(test)] mod array_layout_tests { use super::SignalArrayLayout; diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index 436f3c1fc08..7ec03666d06 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -43,6 +43,8 @@ pub struct ResolvedSchedule { pub(crate) active_commits: bit_set::BitSet, /// Signals the current time is stored into before each round. pub(crate) time_slots: Vec, + /// Sampled variables and their copies, captured before entering a later timestamp. + pub(crate) sample_shadows: Vec<(SignalRef, SignalRef)>, /// The compiled scheduler, when one was generated. pub(crate) scheduler: Option, /// Per process kernel, why the compiled scheduler does not run it, or @@ -336,6 +338,11 @@ impl ResolvedSchedule { timed: model.timed, active_commits, time_slots: model.time_slots.iter().map(resolve).collect(), + sample_shadows: model + .sample_shadows + .iter() + .map(|(variable, copy)| (resolve(variable), resolve(copy))) + .collect(), scheduler: model.scheduler.as_ref().and_then(|scheduler| { let slots = &scheduler.slots; let mut refs = SchedulerRefs { diff --git a/crates/celox-runtime/src/simulation/batch.rs b/crates/celox-runtime/src/simulation/batch.rs index 449175c28cc..6b6eeea398b 100644 --- a/crates/celox-runtime/src/simulation/batch.rs +++ b/crates/celox-runtime/src/simulation/batch.rs @@ -119,8 +119,6 @@ impl SimulationState { where E: SimulationExecutor, { - self.scheduler.time = current_time; - let num_events = executor.backend().num_events(); let counted = !self.model.counted.is_empty(); for event in &events_to_process { diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index df6c6b04732..0b3133476a8 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -124,7 +124,7 @@ impl SimulationState { let one_slot = match executor.compiled_slots() { CompiledSlots::None => return None, CompiledSlots::One => true, - CompiledSlots::Any => one_slot, + CompiledSlots::Any => one_slot || self.one_slot_runs(), }; Some(if one_slot { first @@ -176,6 +176,11 @@ impl SimulationState { where E: SimulationExecutor, { + // Designs with sampled values are limited to one slot, so `limit` + // is that slot's timestamp. Keep its baseline on same-time reentry. + if self.one_slot_runs() && limit > self.scheduler.time { + self.sample_values(executor.backend_mut()); + } let scheduler = self .model .scheduler @@ -418,6 +423,19 @@ impl SimulationState { if executor.take_slot_writes() { self.host_pending = true; } + // A run of one slot ends it unless work is left at its time. + if (self.one_slot_runs() || executor.compiled_slots() == CompiledSlots::One) + && !self.host_pending + && self.next_work_time() != Some(now) + { + self.end_time_slot(executor, now)?; + } Ok(now) } + + /// Whether every run of the compiled scheduler takes one slot: the + /// sampled copies are made before entering each later timestamp. + fn one_slot_runs(&self) -> bool { + !self.model.sample_shadows.is_empty() + } } diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 0a57c8a08b0..bc1af0b2da8 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -552,9 +552,23 @@ impl SimulationState { /// Move to `time` without running anything there, as the end of a run /// to a time without work does. Design code reads the new time. pub fn advance_time(&mut self, backend: &mut B, time: u64) { + if time > self.scheduler.time { + self.sample_values(backend); + } self.set_time(backend, time); } + /// Copy each sampled variable into its copy, which then holds the value + /// the variable has in the Preponed region of the next time slot (IEEE + /// 1800-2023 4.4.2.1, 16.5.1). A timed simulation does it before + /// advancing to a later timestamp and once before the first slot. + /// Returning to the host at the same timestamp must retain the copy. + pub fn sample_values(&self, backend: &mut B) { + for &(variable, copy) in &self.model.sample_shadows { + crate::copy_signal(backend, variable, copy); + } + } + /// Store `time` where design code reads the simulation time (`$time`). fn publish_time(&self, backend: &mut B, time: u64) { for &slot in &self.model.time_slots { diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index 881f1d146e6..5ab9a9d3a57 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -441,12 +441,10 @@ impl SimulationState { where E: SimulationExecutor, { - self.publish_time(executor.backend_mut(), current_time); + self.advance_time(executor.backend_mut(), current_time); if !self.model.timed { return self.batch_round(executor, current_time, events_to_process); } - self.scheduler.time = current_time; - // Host writes the waits must see one at a time. for (signal, value) in executor.take_host_writes() { self.observe_host_write(signal, &value); diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index a48ba7bd963..cad499b6469 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -214,7 +214,7 @@ impl SimulationState { // The slot is over when nothing more is due at its time, host // writes included. if !self.host_pending && self.next_work_time() != Some(current_time) { - executor.try_end_time_slot(current_time)?; + self.end_time_slot(executor, current_time)?; } Ok(()) } @@ -228,6 +228,19 @@ impl SimulationState { || !state.re_nba_queue.is_empty() } + /// Run the host's Observed and Postponed work after quiescence. + /// The host may resume this timestamp, so sampling waits for time advance. + pub(super) fn end_time_slot( + &mut self, + executor: &mut E, + current_time: u64, + ) -> Result<(), Halt> + where + E: SimulationExecutor, + { + executor.try_end_time_slot(current_time) + } + /// Count a round or a pass of the process phase against the slot's /// budget, so that processes resuming at one time forever end the step /// with an error instead of hanging it. diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index 41d24194d86..d769b5e4a65 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -1787,6 +1787,12 @@ pub(in crate::ast) fn real_value(expr: &Expr, dimensions: &PackedDimensions) -> .functions .get(name) .is_some_and(|function| function.return_real), + // A sampled value has the type of its operand. + Expr::Call { + callee: Callee::System(SystemFunction::Sampled), + args, + .. + } => matches!(args.first(), Some(Some(operand)) if real_value(operand, dimensions)), Expr::Unary { op: UnaryOp::Plus | UnaryOp::Minus | UnaryOp::ToTwoState, expr, diff --git a/crates/celox-sv-analyzer/src/ast/expressions.rs b/crates/celox-sv-analyzer/src/ast/expressions.rs index c19568558e4..8b451cf93d7 100644 --- a/crates/celox-sv-analyzer/src/ast/expressions.rs +++ b/crates/celox-sv-analyzer/src/ast/expressions.rs @@ -139,6 +139,34 @@ pub(super) fn numeric_system_function( signed: function == SystemFunction::Signed, }) } + // The sampled value has the type of its operand; the frontend reads + // it from the operand's sampled copy (IEEE 1800-2023 16.9.3). + SystemFunction::Sampled => { + let argument = arguments.pop().ok_or_else(operand_error)?; + // A real operand keeps its type: an integral resize would + // round it. + if expression_binding::real_value(&argument, dimensions) { + return Ok(Expr::Call { + callee: Callee::System(function), + args: vec![Some(argument)], + arg_order: Vec::new(), + }); + } + let width = + expr_static_width(state, &argument, dimensions).ok_or_else(operand_error)?; + let signed = + dimensions::expression_signedness(&argument, dimensions, &dimensions.const_env) + .ok_or_else(operand_error)?; + Ok(Expr::Resize { + expr: Box::new(Expr::Call { + callee: Callee::System(function), + args: vec![Some(argument)], + arg_order: Vec::new(), + }), + width, + signed, + }) + } SystemFunction::Ln | SystemFunction::Log10 | SystemFunction::Exp diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index f6e85cb53f9..3b541bf184e 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -60,6 +60,9 @@ pub enum SystemFunction { Signed, /// `$unsigned` (11.7). Unsigned, + /// `$sampled` (IEEE 1800-2023 16.9.3): the value of its operand in the + /// Preponed region of the time slot. + Sampled, /// `$bits` (20.6.2). Bits, /// `$isunbounded` (20.6.3). @@ -253,6 +256,7 @@ impl SystemFunction { Self::Timeprecision => "$timeprecision", Self::Signed => "$signed", Self::Unsigned => "$unsigned", + Self::Sampled => "$sampled", Self::Bits => "$bits", Self::Isunbounded => "$isunbounded", Self::Dimensions => "$dimensions", @@ -354,7 +358,11 @@ impl SystemFunction { /// or it returns the simulation time. Such a call is not a constant /// expression, and a process evaluates it where it runs. pub fn reads_simulation_state(self) -> bool { - self.is_effectful() || matches!(self, Self::Time | Self::Stime | Self::Realtime) + self.is_effectful() + || matches!( + self, + Self::Time | Self::Stime | Self::Realtime | Self::Sampled + ) } /// Whether the call writes argument `position` back, as `$random(seed)` @@ -440,6 +448,7 @@ impl SystemFunction { Self::Time => Some((64, false)), Self::Signed | Self::Unsigned + | Self::Sampled | Self::Bits | Self::Dimensions | Self::UnpackedDimensions @@ -1141,7 +1150,7 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$assertvacuousoff", Task), unsupported("$assertcontrol", Task), // 20.12 Sampled value system functions - unsupported("$sampled", Function), + function(SystemFunction::Sampled, 1, Some(1)), unsupported("$rose", Function), unsupported("$fell", Function), unsupported("$stable", Function), diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index b605d44113b..e050bed0c41 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -418,6 +418,8 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) host_request_sites: Vec>, pub(crate) active_commits: Vec, pub(crate) time_slots: Vec, + #[serde(default)] + pub(crate) sample_shadows: Vec<(AbsoluteAddr, AbsoluteAddr)>, pub(crate) scheduler: Option>, pub(crate) derived_edges: Vec>, } @@ -591,6 +593,7 @@ impl NativeProgramImage { host_request_sites: self.runtime_schema.host_request_sites.clone(), active_commits: self.runtime_schema.active_commits.clone(), time_slots: self.runtime_schema.time_slots.clone(), + sample_shadows: self.runtime_schema.sample_shadows.clone(), scheduler: self.runtime_schema.scheduler.clone(), derived_edges: self.runtime_schema.derived_edges.clone(), settle_partitions: None, @@ -2640,6 +2643,7 @@ fn compile_program( declaration_startup: sir.runtime().runtime_schema.declaration_startup.clone(), active_commits: sir.runtime().runtime_schema.active_commits.clone(), time_slots: sir.runtime().runtime_schema.time_slots.clone(), + sample_shadows: sir.runtime().runtime_schema.sample_shadows.clone(), scheduler: sir.runtime().runtime_schema.scheduler.clone(), derived_edges: sir.runtime().runtime_schema.derived_edges.clone(), }, diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index a697a472d00..1b329072c48 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 41; +const CONTAINER_VERSION: u16 = 42; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index dfc7e05abd1..8e8137bd495 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -271,19 +271,14 @@ impl HostBoundary for Simulator { fn compiled_slots(&self) -> celox_runtime::CompiledSlots { use celox_runtime::CompiledSlots; - // Deferred assertions mature when a slot is over, which the - // runtime's loop tells apart from the end of a step. - if self.frozen - || !self.components.is_empty() - || self.deferred_assertions - || !self.backend.runs_compiled_scheduler() - { + if self.frozen || !self.components.is_empty() || !self.backend.runs_compiled_scheduler() { return CompiledSlots::None; } - // Waveforms record, the heap collects and a slot observer looks at - // every slot boundary. + // Waveforms record, the heap collects, deferred assertions mature + // and a slot observer looks at every slot boundary. let vcd = &self.sv_vcd; - if self.slot_observer.is_some() + if self.deferred_assertions + || self.slot_observer.is_some() || self.vcd_writer.is_some() || vcd.path.is_some() || vcd.started.is_some() @@ -458,6 +453,9 @@ impl Simulation { simulator.timed = true; simulator.skip_runtime_finish(); state.initialize_declarations(&mut simulator)?; + // Before the first slot, a sampled value is the declared or default + // value (IEEE 1800-2023 16.5.1). + state.sample_values(&mut simulator.backend); Ok(Self { simulator, state, @@ -761,7 +759,7 @@ impl Simulation { /// run at that time. #[inline] fn end_idle_slot(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { - if !self.simulator.deferred_assertions + if !self.simulator.host_slot_work || end_time <= self.state.time() || self.state.next_event_time() == Some(self.state.time()) { diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index d0e1e8c7398..0db616ec3fe 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -161,6 +161,12 @@ mod host { /// A timed simulation owns this simulator: a time slot ends when its /// scheduler says so, not when combinational logic settles. pub(crate) timed: bool, + /// Sampled variables and their copies + /// (`RuntimeSchema::sample_shadows`). + sample_shadows: Vec<(SignalRef, SignalRef)>, + /// Deferred assertions or sampled copies have work when a host + /// call's time slot is over. + pub(crate) host_slot_work: bool, /// Identity of the state layout, computed on first checkpoint use. pub(super) checkpoint_fingerprint: std::sync::OnceLock, /// State objects as state files name them, built on first use. @@ -1030,6 +1036,17 @@ mod host { } else { Vec::new() }; + let sample_shadows: Vec<(SignalRef, SignalRef)> = program + .runtime_schema + .sample_shadows + .iter() + .map(|(variable, copy)| { + ( + backend.resolve_signal(variable), + backend.resolve_signal(copy), + ) + }) + .collect(); let mut comb_deferred_groups: Vec<(u32, usize)> = Vec::new(); for observer in &program.runtime_schema.comb_observers { if matches!( @@ -1066,6 +1083,8 @@ mod host { deferred_assertions: !deferred_sites.is_empty(), comb_deferred_groups, timed: false, + host_slot_work: !deferred_sites.is_empty() || !sample_shadows.is_empty(), + sample_shadows, components: Default::default(), component_simulation: None, runtime_event_read_seq: Arc::new(AtomicU64::new(0)), @@ -1321,13 +1340,12 @@ mod host { } } - /// Without a scheduler, a host call is a time slot: mature the - /// deferred assertions it ran. + /// Without a scheduler, a host call is a time slot: end it. fn end_untimed_slot(&mut self) -> Result<(), RuntimeErrorCode> { if self.timed { return Ok(()); } - self.mature_deferred_assertions() + self.end_host_slot() } pub(crate) fn drain_runtime_events_deferred_with_context( @@ -1469,6 +1487,53 @@ mod host { self.host_watch.set_log(other.host_watch.log().to_vec()); } + /// A host call without a scheduler is a time slot, which is over: + /// deferred assertions mature, then the sampled copies are made. + #[inline] + fn end_host_slot(&mut self) -> Result<(), RuntimeErrorCode> { + if !self.host_slot_work { + return Ok(()); + } + self.finish_host_slot() + } + + /// A host call without a scheduler begins a time slot. Logic that + /// host writes since the previous call left dirty settles first, in + /// the previous slot, which then ends: the call's domains sample the + /// values it settled to, and settles within the call do not change + /// them. + #[inline] + fn begin_host_slot(&mut self) -> Result<(), RuntimeErrorCode> { + if !self.host_slot_work || !self.dirty || self.timed { + return Ok(()); + } + self.settle_host_slot() + } + + #[cold] + #[inline(never)] + fn settle_host_slot(&mut self) -> Result<(), RuntimeErrorCode> { + self.eval_comb_checked()?; + self.dirty = false; + self.finish_host_slot() + } + + #[cold] + #[inline(never)] + fn finish_host_slot(&mut self) -> Result<(), RuntimeErrorCode> { + self.mature_deferred_assertions()?; + self.sample_values(); + Ok(()) + } + + /// Copy each sampled variable into its copy (IEEE 1800-2023 + /// 16.5.1). + pub(crate) fn sample_values(&mut self) { + for &(variable, copy) in &self.sample_shadows { + celox_runtime::copy_signal(&mut self.backend, variable, copy); + } + } + /// The time slot ends: the actions of deferred assertions that their /// process did not flush mature, `#0` before `final` (IEEE 1800-2023 /// 16.4). A fatal one ends the simulation with an error. @@ -2054,8 +2119,10 @@ mod host { // Nothing the domain runs reads the level, which is the // inactive one before and after the period: both stores are // unobservable, and the period is one run of the domain. - return self.fire(event); + // The call begins its slot in the domain's run. + return self.fire_from::(event); } + self.begin_host_slot()?; let moved = celox_runtime::move_signal( &mut self.backend, &info, @@ -2099,13 +2166,27 @@ mod host { /// 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> { - let result = self.fire_unit(event); + self.fire_from::(event) + } + + /// [`Self::fire`]; with `BEGIN`, also the start of the host call, + /// whose slot [`Self::begin_host_slot`] begins in the domain's run, + /// where the clock that nothing reads has already moved. + #[inline] + fn fire_from( + &mut self, + event: B::Event, + ) -> Result<(), RuntimeErrorCode> { + let result = self.fire_unit::(event); self.heap_safepoint(); result.and(self.take_heap_fault())?; - self.mature_deferred_assertions() + self.end_host_slot() } - fn fire_unit(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + fn fire_unit( + &mut self, + event: B::Event, + ) -> Result<(), RuntimeErrorCode> { if let Some(Some(_)) = self.derived_ticks.get(event.id()) { return self.tick_derived(event); } @@ -2113,7 +2194,10 @@ mod host { let mut eval_comb_ns = 0u64; let mut eval_apply_ns = 0u64; if self.dirty { - if timing_enabled { + if BEGIN && self.host_slot_work && !self.timed { + self.settle_host_slot()?; + self.eval_apply_ff_at_checked(event)?; + } else if timing_enabled { let start = crate::timing::now(); self.eval_comb_checked()?; eval_comb_ns = eval_comb_ns.saturating_add(start.elapsed().as_nanos() as u64); @@ -2180,7 +2264,12 @@ mod host { return Ok(()); } // No derived domains: move the signal, then run the event's - // domain. + // domain. Logic that reads the signal settles before it + // moves; otherwise the call begins its slot in the domain's + // run. + if info.comb_read { + self.begin_host_slot()?; + } let write = watched_write(&mut self.host_watch); let Some(old) = celox_runtime::move_signal(&mut self.backend, &info, edge, write) else { @@ -2190,13 +2279,18 @@ mod host { self.dirty = true; } if info.fires(old, edge) { - return self.fire(event); + return if info.comb_read { + self.fire(event) + } else { + self.fire_from::(event) + }; } if !self.program.runtime_schema.comb_observers.is_empty() { self.dirty = true; } return Ok(()); } + self.begin_host_slot()?; if let Some(Some(unit)) = self.derived_units.get(event.id()).copied() && !self.finish_sites && self.backend.runs_derived_edge_units() @@ -2264,8 +2358,7 @@ mod host { } /// Settle the outcome of [`celox_runtime::run_edge`] or - /// [`celox_runtime::run_edges`], and mature the deferred assertions - /// they ran. + /// [`celox_runtime::run_edges`], and end the time slot they ran. fn note_edge( &mut self, outcome: Result, @@ -2288,7 +2381,7 @@ mod host { Err(celox_runtime::Halt::Error(error)) => return Err(error), } // The edges are a time slot, as a tick is. - self.mature_deferred_assertions() + self.end_host_slot() } /// A rising edge of `event`'s signal; see [`Self::edge`]. @@ -2328,6 +2421,7 @@ mod host { if self.frozen { return Ok(()); } + self.begin_host_slot()?; let plans = std::sync::Arc::clone(&self.derived_ticks); let edges = std::sync::Arc::clone(&self.event_edges); let mut scratch = self.derived_scratch.take().unwrap_or_default(); @@ -2432,6 +2526,7 @@ mod host { if self.frozen { return Ok(()); } + self.begin_host_slot()?; if let [event] = events { return self.tick(*event); } @@ -2492,7 +2587,7 @@ mod host { let result = self.tick_events_unit(&fired); self.heap_safepoint(); result.and(self.take_heap_fault())?; - self.mature_deferred_assertions()?; + self.end_host_slot()?; for &event in events { let info = self.event_edges[event.id()]; self.backend @@ -2594,8 +2689,11 @@ mod host { ) -> Result<(), RuntimeErrorCode> { if !self.program.runtime_schema.comb_observers.is_empty() || matches!(self.derived_ticks.get(event.id()), Some(Some(_))) + || self.host_slot_work { - // Derived domains need the settled state to see their edges. + // Derived domains need the settled state to see their edges, + // and each tick of a design with slot work is a host call. + self.begin_host_slot()?; return self.fire(event); } if self.dirty { @@ -2634,6 +2732,7 @@ mod host { if !self.program.runtime_schema.comb_observers.is_empty() || !self.dirty || matches!(self.derived_ticks.get(event.id()), Some(Some(_))) + || self.host_slot_work { return (1, self.tick_deferred_comb(event)); } @@ -3380,6 +3479,46 @@ mod host { } } + #[test] + fn signal_copy_accepts_an_aliased_four_state_view() { + let mut sim = Simulator::builder("module Top (data: input logic<32>) {}", "Top") + .four_state(true) + .build_interpreter() + .unwrap(); + let signal = sim.try_child_signal(&[], "data").unwrap(); + let value = BigUint::from(0x1234u32); + let mask = BigUint::from(0x00ffu32); + sim.backend + .set_four_state(signal, value.clone(), mask.clone()); + celox_runtime::copy_signal(&mut sim.backend, signal, signal); + assert_eq!(sim.backend.get_four_state(signal), (value, mask)); + } + + /// Batched testbench ticks end each tick's slot in a design with + /// sampled values: a register capturing `$sampled(count)` follows + /// the preceding tick. + #[cfg(feature = "systemverilog")] + #[test] + fn batched_testbench_ticks_end_each_slot() { + let source = "module Top(input bit clk, output bit [7:0] count, output bit [7:0] seen);\n \ + always_ff @(posedge clk) begin count <= count + 1; seen <= $sampled(count); end\n\ + endmodule"; + let mut sim = + Simulator::from_sv_sources(vec![(source, std::path::Path::new("t.sv"))], "Top") + .build() + .unwrap(); + let clk = sim.event("clk"); + sim.dirty = true; + let mut done = 0; + while done < 3 { + let (ran, result) = sim.tick_deferred_comb_many(clk, 3 - done); + result.unwrap(); + done += ran; + } + let seen = sim.signal("seen"); + assert_eq!(sim.get(seen), BigUint::from(2u8)); + } + #[test] fn edges_leave_a_finished_simulation_unchanged() { let mut sim = Simulator::builder(GATED_COUNTER, "Top").build().unwrap(); diff --git a/crates/celox/tests/sv_sampled.rs b/crates/celox/tests/sv_sampled.rs new file mode 100644 index 00000000000..756fb132c5f --- /dev/null +++ b/crates/celox/tests/sv_sampled.rs @@ -0,0 +1,264 @@ +#![cfg(feature = "systemverilog")] +//! `$sampled(e)` is the value of `e` in the Preponed region of the time +//! slot, the value at the end of the previous slot, and before the first +//! slot the declared or default value (IEEE 1800-2023 4.4.2.1, 16.5.1, +//! 16.9.3). +use std::path::Path; + +macro_rules! sampled { + ($module:ident, $backend:ident) => { + mod $module { + use super::*; + + fn simulation(body: &str) -> celox::Simulation { + let source = format!( + "`timescale 1ns/1ns\nmodule Top;\n bit clk, a, b, r, s, x, y, z;\n int v;\n{body}\nendmodule" + ); + celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("sampled.sv"))], + "Top", + ) + .$backend() + .unwrap() + } + + fn value(sim: &mut celox::Simulation, name: &str) -> u64 { + let signal = sim.signal(name); + sim.get(signal).try_into().unwrap() + } + + /// A clock edge and a blocking write in one slot: the register + /// sees the new value, `$sampled` the value from before the slot. + #[test] + fn a_flip_flop_samples_the_value_before_the_slot() { + let mut sim = simulation( + " always @(posedge clk) begin r <= $sampled(a); s <= a; end\n \ + initial begin #1 a = 1; clk = 1; #1 clk = 0; #1 clk = 1; end", + ); + sim.run_until(1).unwrap(); + assert_eq!((value(&mut sim, "r"), value(&mut sim, "s")), (0, 1)); + sim.run_until(3).unwrap(); + assert_eq!((value(&mut sim, "r"), value(&mut sim, "s")), (1, 1)); + } + + /// Returning to the host does not advance the Preponed baseline: + /// the host may schedule more work at the same timestamp. + #[test] + fn host_resumptions_keep_the_current_timestamp_sample() { + for mode in [celox::SchedulerMode::Reference, celox::SchedulerMode::Compiled] { + for watch in [false, true] { + for entry in 0..4 { + let source = r#"`timescale 1ns/1ns +module Top(input bit clk, input bit [7:0] host); + bit [7:0] a, r; + always @(posedge clk) r <= $sampled(a + host); + initial #1 a = 1; +endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("sampled.sv"))], "Top", + ).scheduler_mode(mode).$backend().unwrap(); + if watch { sim.set_fail_on(Some(celox::Severity::Error)); } + sim.run_until(0).unwrap(); + match entry { + 0 => sim.run_until(1).unwrap(), + 1 => { sim.run_until_bounded(1, 10).unwrap(); } + 2 => { assert_eq!(sim.step().unwrap(), Some(1)); } + _ => { sim.advance_to(1).unwrap(); sim.run_until(1).unwrap(); } + } + assert_eq!(value(&mut sim, "a"), 1); + sim.schedule("clk", 1, 1).unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "r"), 0, "{mode:?}, watch={watch}, entry={entry}"); + + // Host writes also belong to time 1, not a new slot. + let host = sim.signal("host"); + sim.modify(|io| io.set(host, 2u8)).unwrap(); + sim.schedule("clk", 1, 0).unwrap(); + sim.run_until(1).unwrap(); + sim.schedule("clk", 1, 1).unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "r"), 0); + + // Once time advances, the updated values are sampled. + sim.schedule("clk", 2, 0).unwrap(); + sim.schedule("clk", 3, 1).unwrap(); + sim.run_until(3).unwrap(); + assert_eq!(value(&mut sim, "r"), 3); + if matches!(mode, celox::SchedulerMode::Compiled) + && !watch && entry == 0 + && matches!(stringify!($backend), "build" | "build_cranelift") { + assert!(sim.scheduler_stats().compiled_slots > 0); + } + } + } + } + } + + /// In the first slot the sampled value is the declared value, + /// in a later slot the value at the end of the previous one. + #[test] + fn time_zero_samples_the_declared_value() { + let mut sim = simulation( + " bit d = 1;\n \ + initial begin\n \ + x = $sampled(b) ^ $sampled(d); b = 1; d = 0; #0 y = $sampled(b) ^ $sampled(d);\n \ + #1 z = $sampled(b) ^ $sampled(d);\n \ + end", + ); + sim.run_until(1).unwrap(); + assert_eq!( + (value(&mut sim, "x"), value(&mut sim, "y"), value(&mut sim, "z")), + (1, 1, 1) + ); + } + + /// A real operand keeps its type. + #[test] + fn real_operands_keep_their_type() { + let mut sim = simulation( + " real d = 1.25;\n real rr;\n initial begin rr = $sampled(d); $display(\"%0.2f\", rr); end", + ); + sim.run_until(0).unwrap(); + assert!(matches!( + sim.drain_runtime_events().as_slice(), + [celox::RuntimeEvent::Display { message }] if message == b"1.25" + )); + } + + /// A sampled expression selects, as `$sampled(i + 1)`. + #[test] + fn sampled_expressions_select() { + let mut sim = simulation( + " bit [7:0] data [0:3] = '{10, 11, 12, 13};\n bit [1:0] i = 1;\n bit [7:0] q;\n \ + always @(posedge clk) q <= data[$sampled(i + 1)];\n \ + initial begin #1 clk = 1; i = 0; end", + ); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "q"), 12); + } + + /// A call in a sampled select index reads the sampled values too. + #[test] + fn sampled_calls_select() { + let mut sim = simulation( + " int calls; function automatic bit [1:0] f(bit [1:0] k); calls++; return k; endfunction\n \ + bit [7:0] data [0:3] = '{10, 11, 12, 13};\n bit [1:0] i = 2;\n bit [7:0] q;\n bit [3:0] w;\n \ + always @(posedge clk) begin q <= data[$sampled(f(i))]; w[$sampled(f(i))] <= 1; end\n \ + initial begin #1 clk = 1; i = 0; end", + ); + sim.run_until(1).unwrap(); + assert_eq!((value(&mut sim, "q"), value(&mut sim, "w")), (12, 4)); + } + + /// Automatic variables keep their current value; the operand may + /// be any expression. + #[test] + fn automatic_variables_and_expressions() { + let mut sim = simulation( + " initial begin\n \ + automatic int k = 5;\n \ + #1 a = 1; b = 1;\n \ + v = $sampled(k + a + {31'b0, b});\n \ + end", + ); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "v"), 5); + } + + #[test] + fn combinational_logic_cannot_read_sampled_values() { + for item in [ + "always_comb y = $sampled(a);", + "always @(a) y = $sampled(a);", + "assign y = $sampled(a);", + ] { + let source = format!("module Top; bit a, y; {item} endmodule"); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("sampled.sv"))], + "Top", + ) + .$backend() + .err() + .expect("rejected"); + assert!( + error.to_string().contains("$sampled in combinational logic"), + "{item}: {error}" + ); + } + } + } + }; +} + +sampled!(interpreter, build_interpreter); +#[cfg(feature = "cranelift")] +sampled!(cranelift, build_cranelift); +#[cfg(target_arch = "x86_64")] +sampled!(native, build_native); +#[cfg(feature = "wasm-runtime")] +sampled!(wasm, build_wasm); + +/// A `Simulator` call is a time slot: a domain reads the values its +/// inputs had when the previous call ended. +#[test] +fn a_tick_samples_the_value_of_the_previous_call() { + let source = "module Top(input bit clk, input bit a, output bit r, output bit s);\n \ + always_ff @(posedge clk) begin r <= $sampled(a); s <= a; end\n\ + endmodule"; + let mut sim = celox::Simulator::from_sv_sources(vec![(source, Path::new("sampled.sv"))], "Top") + .build() + .unwrap(); + let (a, r, s, clk) = ( + sim.signal("a"), + sim.signal("r"), + sim.signal("s"), + sim.event("clk"), + ); + sim.modify(|io| io.set(a, 1u8)).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!((sim.get_as::(r), sim.get_as::(s)), (1, 1)); +} + +/// A domain of a derived clock samples the values from before the call, not +/// those the source domain committed in it. +#[test] +fn derived_domains_sample_the_values_from_before_the_call() { + let source = "module Top(input bit clk, output bit [7:0] r);\n \ + bit div;\n bit [7:0] a;\n \ + always_ff @(posedge clk) begin div <= !div; a <= a + 1; end\n \ + always_ff @(posedge div) r <= $sampled(a);\n\ + endmodule"; + // With the edges in generated units and through the plan walk. + for units in [true, false] { + let mut builder = + celox::Simulator::from_sv_sources(vec![(source, Path::new("sampled.sv"))], "Top"); + if !units { + builder = builder.disable_pass(celox::SirPass::DerivedEdgeUnits); + } + let mut sim = builder.build().unwrap(); + let (r, clk) = (sim.signal("r"), sim.event("clk")); + sim.tick(clk).unwrap(); + assert_eq!(sim.get_as::(r), 0, "units: {units}"); + sim.tick(clk).unwrap(); + sim.tick(clk).unwrap(); + assert_eq!(sim.get_as::(r), 2, "units: {units}"); + } +} + +/// A host write in a slot with nothing to run is what the next slot +/// samples. +#[test] +fn host_writes_of_idle_slots_are_sampled() { + let source = "`timescale 1ns/1ns\nmodule Top(input bit clk, input bit a, output bit r);\n \ + always_ff @(posedge clk) r <= $sampled(a);\nendmodule"; + let mut sim = + celox::Simulation::from_sv_sources(vec![(source, Path::new("sampled.sv"))], "Top") + .build() + .unwrap(); + sim.add_clock("clk", 2, 1); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 1u8)).unwrap(); + sim.run_until(1).unwrap(); + let r = sim.signal("r"); + assert_eq!(sim.get(r), 1u8.into()); +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index b74b6f5a4b7..ae258e91cbb 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -210,6 +210,7 @@ waits zero. | System functions | `$timeunit`, `$timeprecision`, `$bits`, `$size`, `$left`, `$right`, `$low`, `$high`, `$increment`, `$dimensions`, `$unpacked_dimensions`, `$clog2`, `$countbits`, `$countones`, `$onehot`, `$onehot0`, `$isunknown`, `$isunbounded` in expressions, constant expressions and as statements; `$signed`, `$unsigned` in expressions, constant expressions and as statements | | Random numbers | `$urandom`, `$urandom_range`, `$random` and `$dist_uniform` in clocked processes, `always_comb`, `always @*`, `initial` blocks and their subroutines; an optional integral seed of `$urandom`, a seed variable of `$random`, and a separate stream per process | | Simulation time | `$time`, `$stime` and `$realtime` in clocked and combinational processes, continuous assignments, `initial` blocks and their subroutines | +| Sampled values | `$sampled` in edge-triggered processes, processes with timing controls, `initial` blocks and the subroutines they call; see [Sampled values](#sampled-values) | | System tasks | `$printtimescale`, `$display`, `$write` and their `b` / `o` / `h` forms, `$error`, `$warning`, `$info`, `$fatal`, `$finish`, `$stop`, `$exit` in `always` processes, subroutines and `initial` blocks; `$readmemh` / `$readmemb` there and in `initial` blocks; Veryl's `$assert` and `$assert_continue` | | Runtime I/O | `$test$plusargs`, `$value$plusargs`, `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and radix variants, `$writememh` / `$writememb`, and [VCD controls](./vcd#systemverilog-source-controls) in timed processes | | State | two-state and four-state simulation | @@ -709,6 +710,21 @@ host does at each callback, or the time step of the report while and the `celox` command print it. Only `$error` and `$fatal` fail a `celox` run; `$fatal` also ends the simulation with an error. +### Sampled values {#sampled-values} + +`$sampled(e)` is the value `e` has in the Preponed region of the time slot: +the value at the end of the previous slot, and in the first slot the declared +or default value (IEEE 1800-2023 4.4.2.1, 16.5.1). Each static variable the +operand reads, the indices of its selects and the arguments of its calls +included, is read from a copy that the timed simulation updates before advancing +to a later timestamp. Returning to the host and resuming at the same timestamp +retains that copy, including across host writes. Automatic variables keep their current value. A `Simulator` call is a +time slot. `$sampled` in combinational logic (`always_comb`, `always_latch`, +an `always` lowered as combinational logic, a continuous assignment) is +rejected: such a process reruns when its inputs change, not when their sampled +values do. A design that uses `$sampled` runs the compiled scheduler one slot +at a time. + ### Deferred assertions The action of `assert #0`, `assume #0`, `cover #0` and their `final` forms diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index ff7e7377ff9..2839b045e40 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -154,6 +154,7 @@ enumは宣言された値だけから均等に抽選し、飛び飛びの値や | システム関数 | `$timeunit`、`$timeprecision`、`$bits`、`$size`、`$clog2`、`$countbits`、`$countones`、`$onehot`、`$onehot0`、`$isunknown`、`$isunbounded` は式・定数式の中と文として。`$signed`、`$unsigned` は式の中と文として | | 乱数 | `$urandom`、`$urandom_range`、`$random`、`$dist_uniform` はクロックで起動するプロセス、`always_comb`、`always @*`、`initial` とそれらから呼ぶサブルーチンで使用可能。`$urandom` の任意の整数式によるシード、`$random` のシード変数、プロセスごとに独立した乱数列 | | シミュレーション時刻 | `$time`、`$stime`、`$realtime` はクロックで起動するプロセス、組合せプロセス、継続代入、`initial` とそれらから呼ぶサブルーチンで使用可能 | +| サンプル値 | `$sampled` はエッジで起動するプロセス、タイミング制御を含むプロセス、`initial` とそれらから呼ぶサブルーチンで使用可能。[サンプル値](#sampled-values) を参照 | | システムタスク | `always` 系のプロセスとサブルーチンの `$printtimescale`、`$display`、`$write` とその `b` / `o` / `h` 形、`$error`、`$warning`、`$info`、`$fatal`、`$finish`、`$stop`、`$exit`。`initial` ブロックでも使えます。`$readmemh` / `$readmemb` はそれらと `initial` ブロック。Veryl の `$assert` と `$assert_continue` | | 実行時 I/O | `$test$plusargs`、`$value$plusargs`、`$fopen`、`$fclose`、`$fdisplay` / `$fwrite` と基数指定形、`$writememh` / `$writememb`、[VCD 制御](./vcd#systemverilog-source-controls)。時間を持つプロセスで実行 | | 状態 | 2 値・4 値シミュレーション | @@ -408,6 +409,18 @@ drain のコンテキストが与える時刻で、VPI ホストはコールバ VPI ホストと `celox` コマンドが表示する形に整形します。`celox` の実行を失敗にするのは `$error` と `$fatal` だけで、`$fatal` はさらにシミュレーションをエラーで終了します。 +### サンプル値 {#sampled-values} + +`$sampled(e)` は、タイムスロットの Preponed region での `e` の値です。前のスロットの終わりの値で、 +最初のスロットでは宣言の初期値か既定値です(IEEE 1800-2023 4.4.2.1、16.5.1)。被演算子が読む +静的変数は、選択のインデックスや呼び出しの引数の中のものも含めて、時刻を先へ進める直前に +更新するコピーから読みます。同じ時刻にホストへ戻って再開しても、ホストからの書き込みを含め、 +コピーは更新しません。automatic 変数は現在の値のままです。`Simulator` では呼び出し 1 回が +タイムスロットです。組み合わせ回路(`always_comb`、`always_latch`、組み合わせ回路として扱う +`always`、継続代入)の中の `$sampled` は拒否します。こうしたプロセスは入力が変わったときに +再実行するもので、入力のサンプル値が変わったときではないためです。`$sampled` を使う設計では、 +コンパイル済みスケジューラを 1 スロットずつ実行します。 + ### 遅延付きアサーション `assert #0`、`assume #0`、`cover #0` とそれぞれの `final` 形のアクションは、プロセスの遅延 From f1a6efbb8e239ab42aac364a80e6947b14b8c558 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 17:46:55 +0900 Subject: [PATCH 2/4] feat(sv): support $past and the value change functions in clocked processes Implement $past, $rose, $fell, $stable and $changed using per-process sampled histories and an inferred clock. Initialize history from declared/default values, support constant history depth and gated ticks, and compare four-state values using case equality where required. Reject history operands whose semantics cannot yet be represented. NativeProgramInstance rejects images requiring sampled/history slot boundaries; Simulator and Simulation retain the metadata and initialization copies. Rebase that check onto the current native image API and bump the image container to version 43. Preserve nested sampled operands both during call discovery and when lowering select indices; resolve their histories before evaluation. Support numeric stability/change comparisons for real and shortreal, including signed zero and nested sampled expressions. Validation on this stack member: sv_past, sv_sampled and native_simulation_image across interpreter, native, actual Cranelift and WASM, 96 passed; frontend unit tests, 7 passed; formatting and affected-crate Clippy with -D warnings. Both newly added regressions failed on all four backends before the fixes. Change-Id: I8980d66c6a630a5297ed41429c982e3b02a62f9b --- crates/celox-design/src/lib.rs | 5 + crates/celox-frontend-core/src/sdk.rs | 1 + .../src/symbolic/artifact.rs | 3 + .../src/symbolic/assembly.rs | 15 + crates/celox-frontend-sv/src/lowering.rs | 28 +- crates/celox-frontend-sv/src/lowering/ff.rs | 380 +++++++++++++++++- .../src/lowering/procedural.rs | 21 +- crates/celox-frontend-veryl/src/artifact.rs | 1 + .../src/ast/expression_binding/direct.rs | 11 +- .../celox-sv-analyzer/src/ast/expressions.rs | 29 +- .../celox-sv-analyzer/src/system_functions.rs | 48 ++- crates/celox/src/backend/native/backend.rs | 4 + crates/celox/src/backend/native/image_file.rs | 2 +- .../celox/src/backend/native/runtime_image.rs | 22 +- crates/celox/src/simulation.rs | 4 +- crates/celox/src/simulator.rs | 16 + crates/celox/tests/native_simulation_image.rs | 20 + crates/celox/tests/sv_past.rs | 339 ++++++++++++++++ crates/celox/tests/sv_sampled.rs | 16 + docs/guide/systemverilog-reference.md | 17 +- docs/ja/guide/systemverilog-reference.md | 12 +- 21 files changed, 959 insertions(+), 35 deletions(-) create mode 100644 crates/celox/tests/sv_past.rs diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index a85be9c3be6..9ff485fbf42 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -1110,6 +1110,10 @@ pub struct RuntimeSchema { /// 16.5.1): a host copies each variable into its copy when a time slot /// is over, and once before the first. pub sample_shadows: Vec<(A, A)>, + /// Variables and copies that start with the variable's value, such as + /// the `$past` histories (IEEE 1800-2023 16.9.3): a host copies each + /// once before the first time slot. + pub initial_copies: Vec<(A, A)>, /// The state a compiled scheduler exchanges with the runtime, and the /// scheduler itself once one is generated. Present when the design has /// process kernels. @@ -1365,6 +1369,7 @@ impl Default for RuntimeSchema { active_commits: Vec::new(), time_slots: Vec::new(), sample_shadows: Vec::new(), + initial_copies: Vec::new(), scheduler: None, derived_edges: Vec::new(), settle_partitions: None, diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index b17909e54cd..a691ceaff01 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1973,6 +1973,7 @@ pub fn lower_frontend_artifact( host_request_sites: Vec::new(), time_slot: None, sample_shadows: Vec::new(), + initial_copies: Vec::new(), }; let symbolic = SymbolicRtl { modules: [(module_id, sim_module.clone())].into_iter().collect(), diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index 6f6acef4356..20938dc8163 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -162,6 +162,9 @@ pub struct SimModule { /// Variables and their sampled copies; see /// `RuntimeSchema::sample_shadows`. pub sample_shadows: Vec<(SourceVarId, SourceVarId)>, + /// Variables and copies that start with their value; see + /// `RuntimeSchema::initial_copies`. + pub initial_copies: Vec<(SourceVarId, SourceVarId)>, } /// A nonblocking site whose kernel has two paths, as diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 766715c6749..88712b02971 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2136,6 +2136,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( host_request_sites, time_slots, sample_shadows, + initial_copies, .. } = timing; let source_sir = SirProgram { @@ -2391,6 +2392,10 @@ pub fn schedule_symbolic_rtl_reporting_loops( .into_iter() .map(|(variable, copy)| (project(variable), project(copy))) .collect(); + let initial_copies: Vec<(StateAddr, StateAddr)> = initial_copies + .into_iter() + .map(|(variable, copy)| (project(variable), project(copy))) + .collect(); let root_instance = expanded[&InstancePath(Vec::new())]; let settle_partitions = settle_flags.map(|settle| { let mut marks: HashMap> = HashMap::default(); @@ -2518,6 +2523,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( timing_read_roots.extend( sample_shadows .iter() + .chain(&initial_copies) .flat_map(|&(variable, copy)| [variable, copy]), ); // A package variable's state object maps back to the package's own @@ -2573,6 +2579,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( active_commits, time_slots, sample_shadows, + initial_copies, scheduler, derived_edges: Vec::new(), settle_partitions, @@ -4126,6 +4133,7 @@ struct TimingMetadata { host_request_sites: Vec>, time_slots: Vec, sample_shadows: Vec<(AbsoluteAddr, AbsoluteAddr)>, + initial_copies: Vec<(AbsoluteAddr, AbsoluteAddr)>, nba_switches: Vec>, } @@ -4449,6 +4457,7 @@ fn relocate_timing( host_request_sites: Vec::new(), time_slots: Vec::new(), sample_shadows: Vec::new(), + initial_copies: Vec::new(), nba_switches: Vec::new(), }; for (&instance, module) in instances { @@ -4490,6 +4499,12 @@ fn relocate_timing( .iter() .map(|&(variable, copy)| (locate(variable), locate(copy))), ); + metadata.initial_copies.extend( + module + .initial_copies + .iter() + .map(|&(variable, copy)| (locate(variable), locate(copy))), + ); metadata.nba_switches.extend( module .nba_switches diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 98a11f435f2..45adbe3c2ae 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -90,6 +90,9 @@ struct SvVariable { /// The variable whose sampled value this hidden copy holds /// (`SimModule::sample_shadows`). sampled_from: Option, + /// The variable whose past sampled values this hidden register holds; + /// it starts with the variable's value (`SimModule::initial_copies`). + history_of: Option, } /// Whether `expr` reads a string variable: after its calls are hoisted, a @@ -130,13 +133,15 @@ impl SvVariable { /// A hidden variable other than the time slot, whose value the lowered /// code computes. The time slot and the sampled copies are state the - /// scheduler writes, and an event expression's variables are state its - /// process and its continuous assignment share. + /// scheduler writes, `$past` histories are state their process keeps, + /// and an event expression's variables are state its process and its + /// continuous assignment share. fn is_scratch(&self) -> bool { self.hidden && self.path != [TIME_SLOT] && self.force_control.is_none() && self.sampled_from.is_none() + && self.history_of.is_none() && !self.path[0].starts_with(EVENT_PREFIX) } } @@ -2203,6 +2208,7 @@ fn prepare_external_hierarchy_collecting( hidden: !variable.module_affiliated, force_control: None, sampled_from: None, + history_of: None, }, ) }) @@ -3635,6 +3641,7 @@ fn lower_module_with_overrides( hidden: false, force_control: None, sampled_from: None, + history_of: None, }; name_to_id.insert(port.name().to_string(), id); port_order.push(id); @@ -3720,6 +3727,7 @@ fn lower_module_with_overrides( hidden: false, force_control: None, sampled_from: None, + history_of: None, }; name_to_id.insert(signal.name().to_string(), id); // The package's object, or the other instance's, has its own @@ -3801,6 +3809,7 @@ fn lower_module_with_overrides( hidden: false, force_control: None, sampled_from: None, + history_of: None, }, ); } @@ -4014,6 +4023,7 @@ fn lower_module_with_overrides( host_request_sites, time_slot: name_to_id.get(TIME_SLOT).copied(), sample_shadows: Vec::new(), + initial_copies: Vec::new(), }, variables, port_order, @@ -4808,6 +4818,12 @@ pub(crate) fn attach_instance_glue( .collect(); sample_shadows.sort_by_key(|&(variable, copy)| (variable.0, copy.0)); module.sample_shadows = sample_shadows; + let mut initial_copies: Vec<_> = parent_variables + .iter() + .filter_map(|(©, variable)| variable.history_of.map(|variable| (variable, copy))) + .collect(); + initial_copies.sort_by_key(|&(variable, copy)| (variable.0, copy.0)); + module.initial_copies = initial_copies; for (instance, child_id, child, connections) in resolved_instances { let glue = build_instance_glue( &parent_variables, @@ -5203,6 +5219,7 @@ fn lower_initial_processes( hidden: true, force_control: None, sampled_from: None, + history_of: None, }, ); id @@ -5848,6 +5865,7 @@ fn ensure_parent_output_signals( hidden: false, force_control: None, sampled_from: None, + history_of: None, }; parent .variables @@ -7731,6 +7749,11 @@ fn lower_bit_vector_function_slt( | SystemFunction::Signed | SystemFunction::Unsigned | SystemFunction::Sampled + | SystemFunction::Past + | SystemFunction::Rose + | SystemFunction::Fell + | SystemFunction::Stable + | SystemFunction::Changed | SystemFunction::Bits | SystemFunction::Size | SystemFunction::Dimensions @@ -9721,6 +9744,7 @@ fn lower_ff_processes( .with_shared_variables(shared_variables) .with_sparse_candidates(&edge_memories) .with_window_writes(&window_writes) + .with_inferred_clock(trigger_set.resets.is_empty()) .lower_process(process.body())?; repeated_writes.extend(repeated_ff_writes(&eval_only, &staged)); // A process without writes still runs for its runtime events and diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 7a1bbbff731..93ed22832e2 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -104,6 +104,24 @@ pub(super) struct Ff<'p, 'a> { flush_site: Option, /// A combinational process is being lowered. combinational: bool, + /// The process has the one clock that sampled value functions infer + /// (IEEE 1800-2023 16.14.6): an edge-triggered process with a single + /// event, which runs at each tick of it. + inferred_clock: bool, + /// The `$past` histories of the process. + history: Vec, +} + +/// The sampled values of variable `name` at the previous ticks of the clock +/// of a process: `chain[k - 1]` holds the value `k` ticks ago, counting +/// only the ticks at which the gate held. +struct History { + name: String, + gate: Option, + /// The hidden variable that holds the gate's value at the tick, before + /// the body runs. + gate_value: Option, + chain: Vec, } fn stable(var_id: SourceVarId) -> Addr { @@ -164,9 +182,18 @@ impl<'p, 'a> Ff<'p, 'a> { nba_switches: Vec::new(), flush_site: None, combinational: false, + inferred_clock: false, + history: Vec::new(), } } + /// Lower an edge-triggered process whose single event is the clock of + /// its sampled value functions. + pub fn with_inferred_clock(mut self, inferred: bool) -> Self { + self.inferred_clock = inferred; + self + } + /// The operand of `$sampled` (IEEE 1800-2023 16.9.3) with each static /// variable read through its sampled copy. Automatic variables and the /// lowering's own temporaries keep their current value (16.5.1). A @@ -182,6 +209,26 @@ impl<'p, 'a> Ff<'p, 'a> { let [Some(operand)] = args else { return Err(unsupported("operand of `$sampled`")); }; + // A sampled value function in the operand would read the sampled + // copies instead of its history. + let mut nested = Vec::new(); + collect_calls(operand, &mut nested); + if nested.iter().any(|(callee, _)| { + matches!( + callee, + sv::ir::Callee::System( + sv::ir::SystemFunction::Past + | sv::ir::SystemFunction::Rose + | sv::ir::SystemFunction::Fell + | sv::ir::SystemFunction::Stable + | sv::ir::SystemFunction::Changed + ) + ) + }) { + return Err(unsupported( + "`$sampled` of an operand that calls a sampled value function", + )); + } let operand = self.propagate(operand); let mut names = HashSet::default(); expr_idents(&operand, &mut names); @@ -201,6 +248,262 @@ impl<'p, 'a> Ff<'p, 'a> { Ok(rename_idents(&operand, &renames)) } + /// Declare the `$past` histories that the sampled value functions of + /// `body` read, as nonblocking targets of the process. + fn declare_history(&mut self, body: &[sv::ir::Stmt]) -> Result<(), sv::AnalyzerError> { + use sv::ir::SystemFunction; + let mut calls = Vec::new(); + for stmt in body { + stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); + } + for (callee, args) in calls { + let sv::ir::Callee::System( + function @ (SystemFunction::Past + | SystemFunction::Rose + | SystemFunction::Fell + | SystemFunction::Stable + | SystemFunction::Changed), + ) = callee + else { + continue; + }; + if !self.inferred_clock { + return Err(unsupported(format!( + "`{function}` outside an edge-triggered process with one event, whose clock it infers" + ))); + } + let (depth, gate) = past_depth_and_gate(function, &args)?; + let Some(Some(operand)) = args.first() else { + return Err(unsupported(format!("operand of `{function}`"))); + }; + // The history of a nested call would need its own chain. + let mut nested = Vec::new(); + collect_calls(operand, &mut nested); + if nested.iter().any(|(callee, _)| { + matches!( + callee, + sv::ir::Callee::System( + SystemFunction::Past + | SystemFunction::Rose + | SystemFunction::Fell + | SystemFunction::Stable + | SystemFunction::Changed + ) + ) + }) { + return Err(unsupported(format!( + "`{function}` of an operand that calls a sampled value function other than `$sampled`" + ))); + } + // The histories hold variables: the result of a call, which can + // read the time or state the operand does not name, has none. + if nested.iter().any(|(callee, _)| { + !matches!(callee, sv::ir::Callee::System(SystemFunction::Sampled)) + }) { + return Err(unsupported(format!( + "`{function}` of an operand that calls a function" + ))); + } + let mut names = HashSet::default(); + expr_idents(operand, &mut names); + let mut names: Vec<_> = names.into_iter().collect(); + names.sort(); + for name in names { + let Some(id) = self.m.id(&name) else { + continue; + }; + if self.m.is_hidden(id) { + continue; + } + if self.m.var(id).value_kind.is_handle() { + return Err(unsupported(format!( + "`{function}` of a string or class handle" + ))); + } + // A history moves one tick back with one nonblocking copy + // of the variable, which an unpacked array has no form of. + if !self.m.var(id).array_dims.is_empty() { + return Err(unsupported(format!("`{function}` of an unpacked array"))); + } + let index = match self + .history + .iter() + .position(|history| history.name == name && history.gate == gate) + { + Some(index) => index, + None => { + self.history.push(History { + name: name.clone(), + gate: gate.clone(), + gate_value: None, + chain: Vec::new(), + }); + self.history.len() - 1 + } + }; + while self.history[index].chain.len() < depth { + let register = self.m.history_copy(id); + // A hidden variable is no target of its own: the + // history is state the process commits at each tick. + self.record_target(&sv::ir::LValue::Ident(register.clone()), false); + let copy = self.m.id(®ister).expect("a new history register"); + let width = self.m.var(copy).width; + self.targets.push((copy, BitAccess::new(0, width - 1))); + self.history[index].chain.push(register); + } + } + } + Ok(()) + } + + /// The operand of `$past` (IEEE 1800-2023 16.9.3) evaluated over the + /// sampled values of its variables `depth` ticks ago. + fn past( + &self, + function: sv::ir::SystemFunction, + args: &[Option], + ) -> Result { + let (depth, gate) = past_depth_and_gate(function, args)?; + let Some(Some(operand)) = args.first() else { + return Err(unsupported(format!("operand of `{function}`"))); + }; + let operand = self.propagate(operand); + let mut names = HashSet::default(); + expr_idents(&operand, &mut names); + let mut renames = HashMap::default(); + for name in names { + if self.m.id(&name).is_none_or(|id| self.m.is_hidden(id)) { + continue; + } + // `declare_history` declared the histories of the process body; + // a call elsewhere, as in a subroutine, has no clock. + let history = self + .history + .iter() + .find(|history| { + history.name == name && history.gate == gate && history.chain.len() >= depth + }) + .ok_or_else(|| { + unsupported(format!( + "`{function}` outside an edge-triggered process with one event, whose clock it infers" + )) + })?; + renames.insert(name, history.chain[depth - 1].clone()); + } + Ok(rename_idents(&operand, &renames)) + } + + /// `$rose`, `$fell`, `$stable` or `$changed` (IEEE 1800-2023 16.9.3): the + /// sampled value of the operand against its value at the previous tick, + /// with case equality for integral values and numeric equality for reals. + /// A change from or to X counts. `$rose` and + /// `$fell` look at the least significant bit. + fn value_change( + &mut self, + function: sv::ir::SystemFunction, + args: &[Option], + ) -> Result { + use sv::ir::{BinaryOp, Expr, SystemFunction}; + let current = self.sampled(args)?; + let past = self.past(function, args)?; + // Resolve nested $sampled calls before inspecting the operand's type. + let current = self.hoist(¤t)?; + let past = self.hoist(&past)?; + let real = floating::precision(¤t, self.m.variables, self.m.name_to_id).is_some(); + let binary = |left: Expr, op, right: Expr| Expr::Binary { + left: Box::new(left), + op, + right: Box::new(right), + }; + let bit = |value: Expr| binary(value, BinaryOp::BitAnd, Expr::Literal("1'b1".into())); + let literal = |text: &str| Expr::Literal(text.into()); + Ok(match function { + SystemFunction::Rose | SystemFunction::Fell => { + let level = if function == SystemFunction::Rose { + "1'b1" + } else { + "1'b0" + }; + binary( + binary(bit(past), BinaryOp::NeCase, literal(level)), + BinaryOp::LogicAnd, + binary(bit(current), BinaryOp::EqCase, literal(level)), + ) + } + SystemFunction::Stable => binary( + current, + if real { BinaryOp::Eq } else { BinaryOp::EqCase }, + past, + ), + _ => binary( + current, + if real { BinaryOp::Ne } else { BinaryOp::NeCase }, + past, + ), + }) + } + + /// The `$past` updates at the end of an evaluation, a tick of the + /// process's clock: each history moves one tick back and takes the + /// sampled value, where its gate holds at the tick. + fn update_history(&mut self) -> Result { + use sv::ir::{Expr, LValue, Stmt}; + let sampled = |expr: Expr| Expr::Call { + callee: sv::ir::Callee::System(sv::ir::SystemFunction::Sampled), + args: vec![Some(expr)], + arg_order: Vec::new(), + }; + let mut stmts = Vec::new(); + for history in &self.history { + let mut updates: Vec = history + .chain + .windows(2) + .map(|pair| Stmt::Assign { + lhs: LValue::Ident(pair[1].clone()), + rhs: Expr::Ident(pair[0].clone()), + nonblocking: true, + }) + .collect(); + updates.push(Stmt::Assign { + lhs: LValue::Ident(history.chain[0].clone()), + rhs: sampled(Expr::Ident(history.name.clone())), + nonblocking: true, + }); + match &history.gate_value { + None => stmts.extend(updates), + Some(gate) => stmts.push(Stmt::If { + condition: Expr::Ident(gate.clone()), + then_body: updates, + else_body: Vec::new(), + }), + } + } + self.exec_block(&stmts) + } + + /// Evaluate the gate of each `$past` history before the body runs. The + /// gate is the `iff` of the clocking event, which is evaluated at the + /// tick (IEEE 1800-2023 9.4.2.3), not after the body's assignments. + fn capture_history_gates(&mut self) -> Result<(), sv::AnalyzerError> { + use sv::ir::{BinaryOp, Expr}; + for index in 0..self.history.len() { + let Some(gate) = self.history[index].gate.clone() else { + continue; + }; + // Its truth, which keeps an unknown gate unknown, as `if` reads it. + let truth = Expr::Binary { + left: Box::new(gate), + op: BinaryOp::Ne, + right: Box::new(Expr::Literal("1'b0".into())), + }; + let value = self.eval(&truth, Some((1, false)))?; + let (temp, name) = self.m.temp("gate", 1, false, true); + self.store(temp, SIROffset::Static(0), 1, value); + self.history[index].gate_value = Some(name); + } + Ok(()) + } + /// Whether `stmts`, or a subroutine they call, including in timing /// controls and the defaults of omitted arguments, hold a deferred /// assertion. @@ -816,12 +1119,19 @@ impl<'p, 'a> Ff<'p, 'a> { } let mut lowered = Vec::with_capacity(args.len()); for arg in args { - // $sampled must rewrite its operand before any nested - // call reads it. Hoisting first hides the original inputs - // behind a temporary holding their current-slot value. + // Sampled/history functions must resolve their operands + // before nested calls hide the original inputs behind + // temporaries holding current-slot values. let arg = if matches!( callee, - sv::ir::Callee::System(sv::ir::SystemFunction::Sampled) + sv::ir::Callee::System( + sv::ir::SystemFunction::Sampled + | sv::ir::SystemFunction::Past + | sv::ir::SystemFunction::Rose + | sv::ir::SystemFunction::Fell + | sv::ir::SystemFunction::Stable + | sv::ir::SystemFunction::Changed + ) ) { arg.clone() } else { @@ -838,17 +1148,16 @@ impl<'p, 'a> Ff<'p, 'a> { }; let result = match self.hoist(&call)? { sv::ir::Expr::Ident(result) => result, - // A sampled operand, as `$sampled(i + 1)`: its value at - // this point is the select's. - hoisted @ sv::ir::Expr::Binary { .. } - | hoisted @ sv::ir::Expr::Unary { .. } => { + // A sampled/history operand can retain any expression + // shape (including a resize inserted for the index). + // Evaluate it only after its references are resolved. + hoisted => { let value = self.eval(&hoisted, None)?; let width = self.b.register(&value).width(); let (temp, name) = self.m.temp("select", width, false, true); self.store(temp, SIROffset::Static(0), width, value); name } - _ => return Err(unsupported(format!("call of `{callee}` in a select"))), }; let result = ConstExpr::Ident(result); calls.push((expr.clone(), result.clone())); @@ -1140,6 +1449,28 @@ impl<'p, 'a> Ff<'p, 'a> { let operand = self.sampled(args)?; self.hoist(&operand)? } + Expr::Call { + callee: sv::ir::Callee::System(function @ sv::ir::SystemFunction::Past), + args, + .. + } => { + let operand = self.past(*function, args)?; + self.hoist(&operand)? + } + Expr::Call { + callee: + sv::ir::Callee::System( + function @ (sv::ir::SystemFunction::Rose + | sv::ir::SystemFunction::Fell + | sv::ir::SystemFunction::Stable + | sv::ir::SystemFunction::Changed), + ), + args, + .. + } => { + let change = self.value_change(*function, args)?; + self.hoist(&change)? + } Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::Fread), args, @@ -4443,6 +4774,7 @@ impl<'p, 'a> Ff<'p, 'a> { mut self, body: &[sv::ir::Stmt], ) -> Result { + self.declare_history(body)?; let mut visited = HashSet::default(); self.scan(body, &mut visited); // A variable only this process's nonblocking assignments write here, @@ -4622,7 +4954,8 @@ impl<'p, 'a> Ff<'p, 'a> { args: Vec::new(), }); } - if self.exec_block(&body)? { + self.capture_history_gates()?; + if self.exec_block(&body)? && self.update_history()? { self.b.seal_block(SIRTerminator::Return); } let mut eval = seal_drained(self.b); @@ -6144,6 +6477,7 @@ impl Ff<'_, '_> { hidden: true, force_control: None, sampled_from: None, + history_of: None, value_kind: Default::default(), }, ); @@ -6923,3 +7257,29 @@ fn force_reads(expr: &sv::ir::Expr, m: &ProcModule<'_>) -> sv::ir::Expr { }, } } + +/// The depth and the gate of a `$past` call, or of the comparison a +/// value change function makes with the previous tick. +fn past_depth_and_gate( + function: sv::ir::SystemFunction, + args: &[Option], +) -> Result<(usize, Option), sv::AnalyzerError> { + if function != sv::ir::SystemFunction::Past { + return Ok((1, None)); + } + let depth = match args.get(1) { + None | Some(None) => 1, + Some(Some(depth)) => { + let mut depth = depth; + while let sv::ir::Expr::Resize { expr, .. } = depth { + depth = expr; + } + literal_usize(depth) + .filter(|&depth| depth >= 1) + .ok_or_else(|| { + unsupported("number of ticks of `$past` other than a positive constant") + })? + } + }; + Ok((depth, args.get(2).cloned().flatten())) +} diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 404fb18d038..8db1571dae6 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -975,6 +975,7 @@ impl<'a> ProcModule<'a> { hidden: true, force_control: None, sampled_from: None, + history_of: None, }, ); self.name_to_id.insert(name, id); @@ -1001,6 +1002,17 @@ impl<'a> ProcModule<'a> { name } + /// A new hidden register of `$past` history for variable `id`, which + /// starts with the variable's value. + pub fn history_copy(&mut self, id: SourceVarId) -> String { + let (copy, name) = self.shadow(id, "past", false); + self.variables + .get_mut(©) + .expect("a new copy") + .history_of = Some(id); + name + } + pub fn shadow( &mut self, id: SourceVarId, @@ -1060,6 +1072,7 @@ impl<'a> ProcModule<'a> { hidden: true, force_control: None, sampled_from: None, + history_of: None, }; let id = next_var_id(&mut self.next_id); self.variables.insert(id, variable); @@ -1091,6 +1104,7 @@ impl<'a> ProcModule<'a> { hidden: true, force_control: None, sampled_from: None, + history_of: None, ..variable }, ); @@ -1619,6 +1633,7 @@ pub(super) fn register_locals( hidden: true, force_control: None, sampled_from: None, + history_of: None, }, ); name_to_id.insert(local.name.clone(), id); @@ -2333,7 +2348,7 @@ pub(super) struct CanonicalLoop { pub decreasing: bool, } -fn literal_usize(expr: &sv::ir::Expr) -> Option { +pub(super) fn literal_usize(expr: &sv::ir::Expr) -> Option { let sv::ir::Expr::Literal(text) = expr else { return None; }; @@ -2975,7 +2990,9 @@ fn collect_const_calls( ConstExpr::Function { callee, args, .. } => { calls.push(( callee.clone(), - args.iter().map(expr_from_const_expr).collect(), + args.iter() + .map(|arg| expr_from_const_expr_with_calls(arg, true)) + .collect(), )); args.iter().for_each(|arg| collect_const_calls(arg, calls)); } diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 526b5b7dbf0..9293057ddb2 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -683,6 +683,7 @@ pub(crate) fn project_module_with_ids( host_request_sites: Vec::new(), time_slot: None, sample_shadows: Vec::new(), + initial_copies: Vec::new(), }, ids, inferred_latch_diagnostics, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index d769b5e4a65..33887ffd798 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -1265,6 +1265,15 @@ pub(in crate::ast) fn bind_value( arg_order: Vec::new(), } } else { + let mut operands = operands; + // An omitted number of ticks of `$past` is + // one (IEEE 1800-2023 16.9.3); the gate stays + // the third argument. + if function == SystemFunction::Past + && args.get(1).is_some_and(Option::is_none) + { + operands.insert(1, Expr::Literal("1".into())); + } expressions::numeric_system_function( &tree.state, function, @@ -1789,7 +1798,7 @@ pub(in crate::ast) fn real_value(expr: &Expr, dimensions: &PackedDimensions) -> .is_some_and(|function| function.return_real), // A sampled value has the type of its operand. Expr::Call { - callee: Callee::System(SystemFunction::Sampled), + callee: Callee::System(SystemFunction::Sampled | SystemFunction::Past), args, .. } => matches!(args.first(), Some(Some(operand)) if real_value(operand, dimensions)), diff --git a/crates/celox-sv-analyzer/src/ast/expressions.rs b/crates/celox-sv-analyzer/src/ast/expressions.rs index 8b451cf93d7..26524a5f22a 100644 --- a/crates/celox-sv-analyzer/src/ast/expressions.rs +++ b/crates/celox-sv-analyzer/src/ast/expressions.rs @@ -139,16 +139,16 @@ pub(super) fn numeric_system_function( signed: function == SystemFunction::Signed, }) } - // The sampled value has the type of its operand; the frontend reads - // it from the operand's sampled copy (IEEE 1800-2023 16.9.3). - SystemFunction::Sampled => { - let argument = arguments.pop().ok_or_else(operand_error)?; + // A sampled value has the type of its operand; the frontend reads + // it from copies of the operand's variables (IEEE 1800-2023 16.9.3). + SystemFunction::Sampled | SystemFunction::Past => { + let argument = arguments.first().cloned().ok_or_else(operand_error)?; // A real operand keeps its type: an integral resize would // round it. if expression_binding::real_value(&argument, dimensions) { return Ok(Expr::Call { callee: Callee::System(function), - args: vec![Some(argument)], + args: arguments.into_iter().map(Some).collect(), arg_order: Vec::new(), }); } @@ -157,16 +157,33 @@ pub(super) fn numeric_system_function( let signed = dimensions::expression_signedness(&argument, dimensions, &dimensions.const_env) .ok_or_else(operand_error)?; + // The number of ticks is a constant expression, which the frontend + // reads as a literal. + if function == SystemFunction::Past + && let Some(ticks) = arguments.get_mut(1) + && let Some(constant) = expr_to_const(state, ticks.clone()) + && let Some(value) = eval_ast_const_expr(state, &constant, &dimensions.const_env) + { + *ticks = Expr::Literal(value.to_string()); + } Ok(Expr::Resize { expr: Box::new(Expr::Call { callee: Callee::System(function), - args: vec![Some(argument)], + args: arguments.into_iter().map(Some).collect(), arg_order: Vec::new(), }), width, signed, }) } + SystemFunction::Rose + | SystemFunction::Fell + | SystemFunction::Stable + | SystemFunction::Changed => Ok(Expr::Call { + callee: Callee::System(function), + args: arguments.into_iter().map(Some).collect(), + arg_order: Vec::new(), + }), SystemFunction::Ln | SystemFunction::Log10 | SystemFunction::Exp diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 3b541bf184e..0a9507f995f 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -63,6 +63,15 @@ pub enum SystemFunction { /// `$sampled` (IEEE 1800-2023 16.9.3): the value of its operand in the /// Preponed region of the time slot. Sampled, + /// `$past` (16.9.3): the sampled value of its operand at an earlier tick + /// of the clock. + Past, + /// `$rose`, `$fell`, `$stable` and `$changed` (16.9.3): the sampled value + /// of the operand against its sampled value at the previous tick. + Rose, + Fell, + Stable, + Changed, /// `$bits` (20.6.2). Bits, /// `$isunbounded` (20.6.3). @@ -257,6 +266,11 @@ impl SystemFunction { Self::Signed => "$signed", Self::Unsigned => "$unsigned", Self::Sampled => "$sampled", + Self::Past => "$past", + Self::Rose => "$rose", + Self::Fell => "$fell", + Self::Stable => "$stable", + Self::Changed => "$changed", Self::Bits => "$bits", Self::Isunbounded => "$isunbounded", Self::Dimensions => "$dimensions", @@ -361,7 +375,15 @@ impl SystemFunction { self.is_effectful() || matches!( self, - Self::Time | Self::Stime | Self::Realtime | Self::Sampled + Self::Time + | Self::Stime + | Self::Realtime + | Self::Sampled + | Self::Past + | Self::Rose + | Self::Fell + | Self::Stable + | Self::Changed ) } @@ -421,7 +443,14 @@ impl SystemFunction { | Self::Countones | Self::ScopeRandomize | Self::ScopeRandomizeEnum => Some((32, true)), - Self::Onehot | Self::Onehot0 | Self::Isunknown | Self::Isunbounded => Some((1, false)), + Self::Onehot + | Self::Onehot0 + | Self::Isunknown + | Self::Isunbounded + | Self::Rose + | Self::Fell + | Self::Stable + | Self::Changed => Some((1, false)), Self::Random | Self::DistUniform | Self::DistNormal @@ -449,6 +478,7 @@ impl SystemFunction { Self::Signed | Self::Unsigned | Self::Sampled + | Self::Past | Self::Bits | Self::Dimensions | Self::UnpackedDimensions @@ -1151,11 +1181,11 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ unsupported("$assertcontrol", Task), // 20.12 Sampled value system functions function(SystemFunction::Sampled, 1, Some(1)), - unsupported("$rose", Function), - unsupported("$fell", Function), - unsupported("$stable", Function), - unsupported("$changed", Function), - unsupported("$past", Function), + function(SystemFunction::Rose, 1, Some(1)), + function(SystemFunction::Fell, 1, Some(1)), + function(SystemFunction::Stable, 1, Some(1)), + function(SystemFunction::Changed, 1, Some(1)), + function(SystemFunction::Past, 1, Some(3)), unsupported("$past_gclk", Function), unsupported("$rose_gclk", Function), unsupported("$fell_gclk", Function), @@ -1563,11 +1593,13 @@ pub fn check_call( }); } // Functions require values, except the optional addressing operands of - // `$fread` (21.3.4.4). Tasks such as `$display(a,,b)` may omit operands. + // `$fread` (21.3.4.4) and the number of ticks of `$past` (16.9.3). Tasks + // such as `$display(a,,b)` may omit operands. if tf.kind != Task && let Some(position) = args.iter().enumerate().position(|(position, arg)| { *arg == Arg::Omitted && !(checked == SystemCall::Function(SystemFunction::Fread) && position >= 2) + && !(checked == SystemCall::Function(SystemFunction::Past) && position == 1) }) { return Err(AnalyzerError::InvalidSystemTfCall { diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index e050bed0c41..dba4b92e934 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -420,6 +420,8 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) time_slots: Vec, #[serde(default)] pub(crate) sample_shadows: Vec<(AbsoluteAddr, AbsoluteAddr)>, + #[serde(default)] + pub(crate) initial_copies: Vec<(AbsoluteAddr, AbsoluteAddr)>, pub(crate) scheduler: Option>, pub(crate) derived_edges: Vec>, } @@ -594,6 +596,7 @@ impl NativeProgramImage { active_commits: self.runtime_schema.active_commits.clone(), time_slots: self.runtime_schema.time_slots.clone(), sample_shadows: self.runtime_schema.sample_shadows.clone(), + initial_copies: self.runtime_schema.initial_copies.clone(), scheduler: self.runtime_schema.scheduler.clone(), derived_edges: self.runtime_schema.derived_edges.clone(), settle_partitions: None, @@ -2644,6 +2647,7 @@ fn compile_program( active_commits: sir.runtime().runtime_schema.active_commits.clone(), time_slots: sir.runtime().runtime_schema.time_slots.clone(), sample_shadows: sir.runtime().runtime_schema.sample_shadows.clone(), + initial_copies: sir.runtime().runtime_schema.initial_copies.clone(), scheduler: sir.runtime().runtime_schema.scheduler.clone(), derived_edges: sir.runtime().runtime_schema.derived_edges.clone(), }, diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 1b329072c48..03eac608b15 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 42; +const CONTAINER_VERSION: u16 = 43; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index c13435839e2..229eae17a9d 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -61,7 +61,9 @@ impl NativeProgramInstance { /// validation is structural and does not authenticate executable code. /// /// An image with process kernels, which only a timed - /// [`crate::Simulation`] runs, fails to attach. + /// [`crate::Simulation`] runs, fails to attach. So does one with sampled + /// value copies, `$past` histories or deferred assertions, whose time + /// slots a [`crate::Simulator`] or [`crate::Simulation`] ends. pub unsafe fn from_image(image: NativeProgramImage) -> Result { if image.has_processes() { let origin = image @@ -74,6 +76,24 @@ impl NativeProgramInstance { crate::SimulatorErrorKind::ProcessRequiresSimulation(origin), ))); } + let schema = image.runtime_schema(); + if !schema.sample_shadows.is_empty() + || !schema.initial_copies.is_empty() + || schema + .runtime_event_sites + .iter() + .any(|site| site.deferred.is_some()) + { + return Err(NativeProgramLoadError::Attach(SimulatorError::new( + crate::SimulatorErrorKind::Runtime(crate::RuntimeErrorCode::Runtime { + message: "a native program instance does not end time slots: sampled \ + values, `$past` and deferred assertions need a `Simulator` or \ + `Simulation`" + .to_string(), + signals: Vec::new(), + }), + ))); + } // Safety: upheld by this constructor's caller. let shared = Arc::new( unsafe { SharedNativeCode::from_image(image) } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 8e8137bd495..eed84eed802 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -454,8 +454,8 @@ impl Simulation { simulator.skip_runtime_finish(); state.initialize_declarations(&mut simulator)?; // Before the first slot, a sampled value is the declared or default - // value (IEEE 1800-2023 16.5.1). - state.sample_values(&mut simulator.backend); + // value (IEEE 1800-2023 16.5.1), which declarations may have set. + simulator.initialize_copies(); Ok(Self { simulator, state, diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 0db616ec3fe..5eb290bfa55 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -1112,6 +1112,7 @@ mod host { finish_sites: false, event_edges, }; + sim.initialize_copies(); sim.comb_observer_snapshots = sim.snapshot_all_comb_observers(); sim } @@ -1526,6 +1527,21 @@ mod host { Ok(()) } + /// Before the first time slot, start the `$past` histories and the + /// sampled copies with the values of their variables, the default + /// sampled values (IEEE 1800-2023 16.5.1). + pub(crate) fn initialize_copies(&mut self) { + if !self.host_slot_work && self.program.runtime_schema.initial_copies.is_empty() { + return; + } + for (variable, copy) in self.program.runtime_schema.initial_copies.clone() { + let variable = self.backend.resolve_signal(&variable); + let copy = self.backend.resolve_signal(©); + celox_runtime::copy_signal(&mut self.backend, variable, copy); + } + self.sample_values(); + } + /// Copy each sampled variable into its copy (IEEE 1800-2023 /// 16.5.1). pub(crate) fn sample_values(&mut self) { diff --git a/crates/celox/tests/native_simulation_image.rs b/crates/celox/tests/native_simulation_image.rs index 491590fff87..38ecdd403e0 100644 --- a/crates/celox/tests/native_simulation_image.rs +++ b/crates/celox/tests/native_simulation_image.rs @@ -284,3 +284,23 @@ endmodule .unwrap(); assert_eq!(run(&mut sim), expected); } + +/// A native program instance ends no time slots, so an image with sampled +/// values or histories fails to attach. +#[test] +fn a_native_program_instance_rejects_sampled_values() { + let source = "module Top(input bit clk, input bit a, output bit r);\n \ + always_ff @(posedge clk) r <= $past(a);\nendmodule"; + let image = celox::Simulator::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top") + .compile_native() + .unwrap() + .into_program_image(); + // SAFETY: the image was compiled from the trusted source above. + let Err(error) = (unsafe { NativeProgramInstance::from_image(image) }) else { + panic!("a native program instance ends no slots"); + }; + assert!( + error.to_string().contains("does not end time slots"), + "{error}" + ); +} diff --git a/crates/celox/tests/sv_past.rs b/crates/celox/tests/sv_past.rs new file mode 100644 index 00000000000..b3d246b356a --- /dev/null +++ b/crates/celox/tests/sv_past.rs @@ -0,0 +1,339 @@ +#![cfg(feature = "systemverilog")] +//! `$past(e, k, gate)` is the sampled value of `e` at the `k`-th previous +//! tick of its clock at which `gate` held, and `$rose`, `$fell`, `$stable` +//! and `$changed` compare the sampled value with the one at the previous +//! tick. Before enough ticks, the past value is the default sampled value +//! (IEEE 1800-2023 16.9.3). The clock is inferred from an edge-triggered +//! process with one event (16.14.6). +use std::path::Path; + +/// A clock rising at 1, 3, 5, 7, ... and the declarations of the tests. +const HEADER: &str = "`timescale 1ns/1ns\nmodule Top;\n bit clk, en;\n bit [7:0] a, p1, p2, g;\n \ + bit b; logic l; int rn, fn_, sn, cn, lr, ls;\n always #1 clk = ~clk;\n"; + +macro_rules! past { + ($module:ident, $backend:ident) => { + mod $module { + use super::*; + + fn simulation(body: &str) -> celox::Simulation { + let source = format!("{HEADER}{body}\nendmodule"); + celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("past.sv"))], + "Top", + ) + .$backend() + .unwrap() + } + + fn value(sim: &mut celox::Simulation, name: &str) -> u64 { + let signal = sim.signal(name); + sim.get(signal).try_into().unwrap() + } + + /// `a` is 0, 1, 2, 3 at the ticks 1, 3, 5, 7. + #[test] + fn past_values_are_sampled_at_earlier_ticks() { + let mut sim = simulation( + " always @(posedge clk) begin p1 <= $past(a); p2 <= $past(a, 2); end\n \ + initial begin #2 a = 1; #2 a = 2; #2 a = 3; end", + ); + sim.run_until(5).unwrap(); + assert_eq!((value(&mut sim, "p1"), value(&mut sim, "p2")), (1, 0)); + sim.run_until(7).unwrap(); + assert_eq!((value(&mut sim, "p1"), value(&mut sim, "p2")), (2, 1)); + } + + #[test] + fn sampled_history_in_selects_uses_previous_ticks() { + let mut sim = simulation(r#" + bit i; + bit [1:0] data = 2'b10; + bit p, r, f, s, c; + always @(posedge clk) begin + p <= data[$past($sampled(i))]; + r <= data[$rose($sampled(i))]; + f <= data[$fell($sampled(i))]; + s <= data[$stable($sampled(i))]; + c <= data[$changed($sampled(i))]; + end + initial begin #2 i = 1; #4 i = 0; end +"#); + for (time, expected) in [ + (1, [0, 0, 0, 1, 0]), + (3, [0, 1, 0, 0, 1]), + (5, [1, 0, 0, 1, 0]), + (7, [1, 0, 1, 0, 1]), + ] { + sim.run_until(time).unwrap(); + assert_eq!(["p", "r", "f", "s", "c"].map(|n| value(&mut sim, n)), expected, "time={time}"); + } + } + + #[test] + fn real_stability_uses_numeric_equality() { + let mut sim = simulation(r#" + real d; + shortreal e; + bit ds, dc, es, ec, nested; + always @(posedge clk) begin + ds <= $stable(d); dc <= $changed(d); + es <= $stable(e); ec <= $changed(e); + nested <= $stable($sampled(d + 0.0)); + end + initial begin + #2 d = 1.5; e = 1.5; + #4 d = 0.0; e = 0.0; + #2 d = -0.0; e = -0.0; + end +"#); + for (time, expected) in [(1, [1, 0]), (3, [0, 1]), (5, [1, 0]), (7, [0, 1]), (9, [1, 0])] { + sim.run_until(time).unwrap(); + assert_eq!(["ds", "dc"].map(|n| value(&mut sim, n)), expected, "real time={time}"); + assert_eq!(["es", "ec"].map(|n| value(&mut sim, n)), expected, "shortreal time={time}"); + assert_eq!(value(&mut sim, "nested"), expected[0]); + } + } + + /// The gate's ticks: with `en` low at the tick of 5, `$past(a, 1, + /// en)` at 7 is the value at 3. + #[test] + fn a_gate_skips_ticks() { + let mut sim = simulation( + " always @(posedge clk) g <= $past(a, 1, en);\n \ + initial begin en = 1; #2 a = 1; #2 a = 2; en = 0; #2 a = 3; en = 1; end", + ); + sim.run_until(7).unwrap(); + assert_eq!(value(&mut sim, "g"), 1); + } + + /// An omitted number of ticks is one. + #[test] + fn an_omitted_number_of_ticks_is_one() { + let mut sim = simulation( + " always @(posedge clk) g <= $past(a, , en);\n \ + initial begin en = 1; #2 a = 1; #2 a = 2; en = 0; #2 a = 3; en = 1; end", + ); + sim.run_until(7).unwrap(); + assert_eq!(value(&mut sim, "g"), 1); + } + + /// The gate is evaluated at the tick, before the body clears it: + /// the tick of 3 takes `a` = 1 into the history. + #[test] + fn a_gate_is_evaluated_before_the_body() { + let mut sim = simulation( + " always @(posedge clk) begin g <= $past(a, 1, en); en = 0; end\n \ + initial begin #2 en = 1; a = 1; #2 en = 1; a = 2; end", + ); + sim.run_until(5).unwrap(); + assert_eq!(value(&mut sim, "g"), 1); + } + + /// The number of ticks is a constant expression. + #[test] + fn the_number_of_ticks_is_a_constant_expression() { + let mut sim = simulation( + " localparam int K = 1;\n \ + always @(posedge clk) begin p1 <= $past(a, K); p2 <= $past(a, K + 1); end\n \ + initial begin #2 a = 1; #2 a = 2; #2 a = 3; end", + ); + sim.run_until(7).unwrap(); + assert_eq!((value(&mut sim, "p1"), value(&mut sim, "p2")), (2, 1)); + } + + + /// `b` is 0, 1, 1, 0 at the ticks 1, 3, 5, 7; its value before + /// the first tick is 0. + #[test] + fn value_changes_compare_with_the_previous_tick() { + let mut sim = simulation( + " always @(posedge clk) begin\n \ + if ($rose(b)) rn <= rn + 1;\n \ + if ($fell(b)) fn_ <= fn_ + 1;\n \ + if ($stable(b)) sn <= sn + 1;\n \ + if ($changed(b)) cn <= cn + 1;\n \ + end\n \ + initial begin #2 b = 1; #4 b = 0; end", + ); + sim.run_until(7).unwrap(); + assert_eq!( + ["rn", "fn_", "sn", "cn"].map(|name| value(&mut sim, name)), + [1, 1, 2, 2] + ); + } + + /// Case equality: in four-state simulation `l` is X before the + /// first tick and at it, which is stable, and X to 1 is a rise. + #[test] + fn unknown_values_compare_with_case_equality() { + let body = " always @(posedge clk) begin\n \ + if ($stable(l)) ls <= ls + 1;\n \ + if ($rose(l)) lr <= lr + 1;\n \ + end\n \ + initial #2 l = 1;"; + let source = format!("{HEADER}{body}\nendmodule"); + let mut sim = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("past.sv"))], + "Top", + ) + .four_state(true) + .$backend() + .unwrap(); + sim.run_until(1).unwrap(); + assert_eq!((value(&mut sim, "ls"), value(&mut sim, "lr")), (1, 0)); + sim.run_until(3).unwrap(); + assert_eq!((value(&mut sim, "ls"), value(&mut sim, "lr")), (1, 1)); + } + + /// Before the first tick the past value is the declared value. + #[test] + fn the_first_tick_sees_the_declared_value() { + let mut sim = simulation( + " bit [7:0] d = 5;\n \ + always @(posedge clk) p1 <= $past(d);\n \ + initial #0 d = 6;", + ); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "p1"), 5); + } + + /// Without one clock to infer, the functions are rejected. + #[test] + fn a_clock_must_be_inferable() { + for item in [ + "initial #1 p1 = $past(a);", + "always_comb p1 = $past(a);", + "always @(posedge clk or posedge en) p1 <= $past(a);", + "always @(posedge clk) begin #1; p1 = $past(a); end", + ] { + let source = format!("{HEADER} {item}\nendmodule"); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("past.sv"))], + "Top", + ) + .$backend() + .err() + .expect("rejected"); + let text = error.to_string(); + assert!( + text.contains("whose clock it infers") + || text.contains("$sampled in combinational logic"), + "{item}: {text}" + ); + } + } + } + }; +} + +past!(interpreter, build_interpreter); +#[cfg(feature = "cranelift")] +past!(cranelift, build_cranelift); +#[cfg(target_arch = "x86_64")] +past!(native, build_native); +#[cfg(feature = "wasm-runtime")] +past!(wasm, build_wasm); + +/// A `Simulator` tick is a tick of the clock. +#[test] +fn simulator_ticks_are_clock_ticks() { + let source = "module Top(input bit clk, input bit [7:0] a, output bit [7:0] p);\n \ + always_ff @(posedge clk) p <= $past(a);\n\ + endmodule"; + let mut sim = celox::Simulator::from_sv_sources(vec![(source, Path::new("past.sv"))], "Top") + .build() + .unwrap(); + let (a, p, clk) = (sim.signal("a"), sim.signal("p"), sim.event("clk")); + for value in 1..=3u8 { + sim.modify(|io| io.set(a, value)).unwrap(); + sim.tick(clk).unwrap(); + } + assert_eq!(sim.get_as::(p), 2); +} + +/// Before the first tick, a past value is the declared value. +#[test] +fn a_first_simulator_tick_sees_the_declared_value() { + let source = "module Top(input bit clk, output bit r);\n \ + bit d = 1;\n \ + always_ff @(posedge clk) begin r <= $past(d); d <= 0; end\n\ + endmodule"; + let mut sim = celox::Simulator::from_sv_sources(vec![(source, Path::new("past.sv"))], "Top") + .build() + .unwrap(); + let (r, clk) = (sim.signal("r"), sim.event("clk")); + sim.tick(clk).unwrap(); + assert_eq!(sim.get_as::(r), 1); + sim.tick(clk).unwrap(); + assert_eq!(sim.get_as::(r), 1); + sim.tick(clk).unwrap(); + assert_eq!(sim.get_as::(r), 0); +} + +/// A nested `$past` would need a history of its own. +#[test] +fn nested_past_calls_are_rejected() { + let source = "module Top(input bit clk, input bit a, output bit r);\n \ + always_ff @(posedge clk) r <= $past($past(a));\n\ + endmodule"; + let error = celox::Simulator::from_sv_sources(vec![(source, Path::new("past.sv"))], "Top") + .build() + .unwrap_err(); + assert!( + error.to_string().contains("calls a sampled value function"), + "{error}" + ); +} + +/// Operands whose value a history of their variables cannot hold, and +/// sampled value functions inside `$sampled`, are rejected; so is a call in +/// a subroutine that needs more history than its caller declared. +#[test] +fn operands_histories_cannot_hold_are_rejected() { + for (body, message) in [ + ( + "always_ff @(posedge clk) t <= $past($time);", + "calls a function", + ), + ( + "function bit f(); return a; endfunction\n always_ff @(posedge clk) r <= $past(f());", + "calls a function", + ), + ( + "always_ff @(posedge clk) r <= $sampled($past(a));", + "`$sampled` of an operand that calls a sampled value function", + ), + ( + "function bit deeper(); return $past(a, 2); endfunction\n \ + always_ff @(posedge clk) begin r <= $past(a); s <= deeper(); end", + "whose clock it infers", + ), + ] { + let source = format!( + "module Top(input bit clk, input bit a, output bit r, output bit s, output time t);\n {body}\nendmodule" + ); + let error = + celox::Simulator::from_sv_sources(vec![(source.as_str(), Path::new("past.sv"))], "Top") + .build() + .unwrap_err(); + assert!(error.to_string().contains(message), "{body}: {error}"); + } +} + +/// A history moves with a copy of the whole variable, which an unpacked +/// array has no form of. +#[test] +fn past_values_of_unpacked_arrays_are_rejected() { + let source = "module Top(input bit clk, output bit [2:0] r);\n \ + bit [2:0] mem [0:3];\n \ + always_ff @(posedge clk) r <= $past(mem[3]);\n\ + endmodule"; + let error = celox::Simulator::from_sv_sources(vec![(source, Path::new("past.sv"))], "Top") + .build() + .unwrap_err(); + assert!( + error.to_string().contains("of an unpacked array"), + "{error}" + ); +} diff --git a/crates/celox/tests/sv_sampled.rs b/crates/celox/tests/sv_sampled.rs index 756fb132c5f..30366cc5364 100644 --- a/crates/celox/tests/sv_sampled.rs +++ b/crates/celox/tests/sv_sampled.rs @@ -150,6 +150,22 @@ endmodule"#; assert_eq!((value(&mut sim, "q"), value(&mut sim, "w")), (12, 4)); } + /// The copy of an array holds all of it. + #[test] + fn arrays_are_sampled_whole() { + let mut sim = simulation( + " bit [2:0] mem [0:3];\n bit [1:0] i;\n \ + int u;\n \ + always_ff @(posedge clk) mem[i] <= 3'd5;\n \ + always_ff @(posedge clk) u <= $sampled(mem[i]);\n \ + initial begin i = 3; #1 clk = 1; #1 clk = 0; #1 clk = 1; end", + ); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "u"), 0); + sim.run_until(3).unwrap(); + assert_eq!(value(&mut sim, "u"), 5); + } + /// Automatic variables keep their current value; the operand may /// be any expression. #[test] diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index ae258e91cbb..36732b073f3 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -210,7 +210,7 @@ waits zero. | System functions | `$timeunit`, `$timeprecision`, `$bits`, `$size`, `$left`, `$right`, `$low`, `$high`, `$increment`, `$dimensions`, `$unpacked_dimensions`, `$clog2`, `$countbits`, `$countones`, `$onehot`, `$onehot0`, `$isunknown`, `$isunbounded` in expressions, constant expressions and as statements; `$signed`, `$unsigned` in expressions, constant expressions and as statements | | Random numbers | `$urandom`, `$urandom_range`, `$random` and `$dist_uniform` in clocked processes, `always_comb`, `always @*`, `initial` blocks and their subroutines; an optional integral seed of `$urandom`, a seed variable of `$random`, and a separate stream per process | | Simulation time | `$time`, `$stime` and `$realtime` in clocked and combinational processes, continuous assignments, `initial` blocks and their subroutines | -| Sampled values | `$sampled` in edge-triggered processes, processes with timing controls, `initial` blocks and the subroutines they call; see [Sampled values](#sampled-values) | +| Sampled values | `$sampled` in edge-triggered processes, processes with timing controls, `initial` blocks and the subroutines they call; `$past`, `$rose`, `$fell`, `$stable` and `$changed` in edge-triggered processes with one event; see [Sampled values](#sampled-values) | | System tasks | `$printtimescale`, `$display`, `$write` and their `b` / `o` / `h` forms, `$error`, `$warning`, `$info`, `$fatal`, `$finish`, `$stop`, `$exit` in `always` processes, subroutines and `initial` blocks; `$readmemh` / `$readmemb` there and in `initial` blocks; Veryl's `$assert` and `$assert_continue` | | Runtime I/O | `$test$plusargs`, `$value$plusargs`, `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and radix variants, `$writememh` / `$writememb`, and [VCD controls](./vcd#systemverilog-source-controls) in timed processes | | State | two-state and four-state simulation | @@ -725,6 +725,21 @@ rejected: such a process reruns when its inputs change, not when their sampled values do. A design that uses `$sampled` runs the compiled scheduler one slot at a time. +`$past(e, k, gate)` is the sampled value of `e` at the `k`-th previous tick of +its clock at which `gate` held, the `iff` of the clock (9.4.2.3), and `$rose`, `$fell`, `$stable` +and `$changed` compare the sampled value of their operand with the one at the +previous tick, with case equality for integral values and numeric equality for +`real`/`shortreal` (`$rose` and `$fell` look at the least +significant bit). Before enough ticks, the past value is the declared or +default value (16.9.3). `k` is a positive constant. The clock is inferred +(16.14.6): the functions are supported in an `always_ff` or `always` process +whose only timing control is one edge event, such as `@(posedge clk)`, and +which therefore runs at each tick. The process keeps a history register for +each variable of the operand and updates it with nonblocking assignments at +the end of each run. An explicit clocking event argument, processes with +more than one event (such as an asynchronous reset) and calls in subroutines +are rejected. + ### Deferred assertions The action of `assert #0`, `assume #0`, `cover #0` and their `final` forms diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 2839b045e40..f904894e6f7 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -154,7 +154,7 @@ enumは宣言された値だけから均等に抽選し、飛び飛びの値や | システム関数 | `$timeunit`、`$timeprecision`、`$bits`、`$size`、`$clog2`、`$countbits`、`$countones`、`$onehot`、`$onehot0`、`$isunknown`、`$isunbounded` は式・定数式の中と文として。`$signed`、`$unsigned` は式の中と文として | | 乱数 | `$urandom`、`$urandom_range`、`$random`、`$dist_uniform` はクロックで起動するプロセス、`always_comb`、`always @*`、`initial` とそれらから呼ぶサブルーチンで使用可能。`$urandom` の任意の整数式によるシード、`$random` のシード変数、プロセスごとに独立した乱数列 | | シミュレーション時刻 | `$time`、`$stime`、`$realtime` はクロックで起動するプロセス、組合せプロセス、継続代入、`initial` とそれらから呼ぶサブルーチンで使用可能 | -| サンプル値 | `$sampled` はエッジで起動するプロセス、タイミング制御を含むプロセス、`initial` とそれらから呼ぶサブルーチンで使用可能。[サンプル値](#sampled-values) を参照 | +| サンプル値 | `$sampled` はエッジで起動するプロセス、タイミング制御を含むプロセス、`initial` とそれらから呼ぶサブルーチンで使用可能。`$past`、`$rose`、`$fell`、`$stable`、`$changed` はイベントが 1 つのエッジで起動するプロセスで使用可能。[サンプル値](#sampled-values) を参照 | | システムタスク | `always` 系のプロセスとサブルーチンの `$printtimescale`、`$display`、`$write` とその `b` / `o` / `h` 形、`$error`、`$warning`、`$info`、`$fatal`、`$finish`、`$stop`、`$exit`。`initial` ブロックでも使えます。`$readmemh` / `$readmemb` はそれらと `initial` ブロック。Veryl の `$assert` と `$assert_continue` | | 実行時 I/O | `$test$plusargs`、`$value$plusargs`、`$fopen`、`$fclose`、`$fdisplay` / `$fwrite` と基数指定形、`$writememh` / `$writememb`、[VCD 制御](./vcd#systemverilog-source-controls)。時間を持つプロセスで実行 | | 状態 | 2 値・4 値シミュレーション | @@ -421,6 +421,16 @@ VPI ホストと `celox` コマンドが表示する形に整形します。`cel 再実行するもので、入力のサンプル値が変わったときではないためです。`$sampled` を使う設計では、 コンパイル済みスケジューラを 1 スロットずつ実行します。 +`$past(e, k, gate)` は、クロックの `iff` である `gate`(9.4.2.3)が成り立っていたティックのうち +`k` 個前のものでの `e` のサンプル値です。`$rose`、`$fell`、`$stable`、`$changed` は、被演算子のサンプル値を +前のティックでのものと、整数型なら case 等価、`real` / `shortreal` なら数値の等価で比べます(`$rose` と `$fell` は最下位ビットを見ます)。ティックが +足りないうちは、過去の値は宣言の初期値か既定値です(16.9.3)。`k` は正の定数です。クロックは +推論します(16.14.6)。これらの関数は、タイミング制御が `@(posedge clk)` のようなエッジイベント +1 つだけで、そのためティックごとに実行する `always_ff` / `always` プロセスで使えます。プロセスは +被演算子の変数ごとに履歴レジスタを持ち、実行の最後にノンブロッキング代入で更新します。明示した +クロッキングイベント引数、イベントが複数あるプロセス(非同期リセットなど)、サブルーチン内の +呼び出しは拒否します。 + ### 遅延付きアサーション `assert #0`、`assume #0`、`cover #0` とそれぞれの `final` 形のアクションは、プロセスの遅延 From 3837df45d9e5b57551948db6e96bc9101b2417a8 Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 15:57:06 +0900 Subject: [PATCH 3/4] fix(sv)!: give reports the time they are issued at Store the issuing simulation time in severity report records, so draining several slots together preserves each report's original time. Keep timestamp arguments out of formatted messages and combinational sensitivity. RuntimeEventSite gains timestamp_arg; the native image container version is 44. Settle pending combinational reports before leaving their time, including when no event is scheduled. A $finish or $fatal during that settle runs final procedures and leaves the simulation at its termination time. Propagate terminal halts through the host boundary, preserve the original fatal diagnostic, and allow a $stop in a final procedure to suspend and resume without advancing time. Regression coverage exercises run_until, step, advance_to and bounded runs, with and without later clocks/report watching, across interpreter, native, Cranelift and WASM. The new regressions reproduced missing termination/finalization before the review fix. Validation: report, VCD, stop/resume and deferred-assertion integration tests (181 passed); celox/runtime unit tests (308 passed); formatting and affected-crate all-targets Clippy with -D warnings. Change-Id: I865a9dced4edb57838192ef0ed22fc22618d835a --- crates/celox-design/src/lib.rs | 6 + crates/celox-frontend-sv/src/lowering/comb.rs | 14 ++ crates/celox-frontend-sv/src/lowering/ff.rs | 14 ++ .../celox-frontend-veryl/src/lowering/ff.rs | 1 + .../src/lowering/logic_tree/effect.rs | 1 + crates/celox-frontend-veryl/src/testbench.rs | 1 + crates/celox-runtime/src/simulation/host.rs | 8 + crates/celox-runtime/src/simulation/mod.rs | 43 +++- crates/celox-runtime/src/simulation/time.rs | 3 + crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/simulation.rs | 43 +++- crates/celox/src/simulator.rs | 46 ++++ crates/celox/src/simulator/host/file_io.rs | 1 + crates/celox/tests/sv_reports.rs | 208 ++++++++++++++++-- docs/guide/systemverilog-reference.md | 8 +- docs/ja/guide/systemverilog-reference.md | 5 +- 16 files changed, 374 insertions(+), 30 deletions(-) diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 9ff485fbf42..cc67b04a278 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -211,6 +211,11 @@ pub struct RuntimeEventSite { /// deferred assertions. #[serde(default)] pub deferred: Option, + /// The last argument is the simulation time at which the site issued + /// the event, which a report carries (IEEE 1800-2023 20.10). It is not + /// formatted. + #[serde(default)] + pub timestamp_arg: bool, pub arg_widths: Vec, pub arg_signed: Vec, pub arg_is_string: Vec, @@ -2226,6 +2231,7 @@ mod tests { location: None, assertion: None, deferred: None, + timestamp_arg: false, arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 06233d06023..246447ad5c8 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3578,6 +3578,19 @@ impl<'p, 'a> Comb<'p, 'a> { arg_widths.push(self.width(node)); captured.push(self.capture(node)?); } + // A report carries the time it is issued at (IEEE 1800-2023 20.10). + // The time does not run the process. + let timestamp_arg = matches!(kind, SystemTaskKind::Message(_) | SystemTaskKind::Fatal); + if timestamp_arg { + let time = sv::ir::Expr::Ident(self.m.time_slot()); + let (node, _) = self.eval(store, frames, &time, None)?; + arg_signed.push(false); + arg_is_string.push(false); + arg_float_precision.push(None); + arg_is_handle.push(false); + arg_widths.push(self.width(node)); + captured.push(self.capture(node)?); + } let event_kind = kind.event_kind(); let condition = self.path_condition()?; let guard = if let Some(passed) = assertion { @@ -3649,6 +3662,7 @@ impl<'p, 'a> Comb<'p, 'a> { location: report_location(site), assertion: assertion_site.cloned(), deferred, + timestamp_arg, arg_widths, arg_signed, arg_is_string, diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 93ed22832e2..6f23db2d86c 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -570,6 +570,7 @@ impl<'p, 'a> Ff<'p, 'a> { location: None, assertion: None, deferred: Some(DeferredSite::FlushPoint), + timestamp_arg: false, arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), @@ -3761,6 +3762,18 @@ impl<'p, 'a> Ff<'p, 'a> { } } } + // A report carries the time it is issued at (IEEE 1800-2023 20.10). + let timestamp_arg = matches!(kind, SystemTaskKind::Message(_) | SystemTaskKind::Fatal); + if timestamp_arg { + let time = sv::ir::Expr::Ident(self.m.time_slot()); + let reg = self.eval(&time, None)?; + arg_widths.push(self.b.register(®).width()); + arg_signed.push(false); + arg_is_string.push(false); + arg_float_precision.push(None); + arg_is_handle.push(false); + regs.push(reg); + } // Argument effects happen before branching, and the condition register // retains the value it had before those effects. let resume = match assertion { @@ -3794,6 +3807,7 @@ impl<'p, 'a> Ff<'p, 'a> { location: report_location(site), assertion: assertion_site.cloned(), deferred, + timestamp_arg, arg_widths, arg_signed, arg_is_string, diff --git a/crates/celox-frontend-veryl/src/lowering/ff.rs b/crates/celox-frontend-veryl/src/lowering/ff.rs index 474841588f8..09a556a434a 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff.rs @@ -556,6 +556,7 @@ impl<'a> FfParser<'a> { location: None, assertion: None, deferred: None, + timestamp_arg: false, arg_widths: value_args .iter() .map(|arg| self.get_expression_width(&arg.0)) diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs index f3c50003647..c6164737f68 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs @@ -104,6 +104,7 @@ fn register_comb_runtime_event_site<'a>( location: None, assertion: None, deferred: None, + timestamp_arg: false, arg_widths: value_args .iter() .map(|arg| arg.0.comptime().r#type.total_width().unwrap_or(1)) diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index e94a57e8747..25089bcc76e 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -112,6 +112,7 @@ fn runtime_event_site_for_assert( location: None, assertion: None, deferred: None, + timestamp_arg: false, arg_widths: value_args.iter().map(assert_arg_width).collect(), arg_signed: value_args .iter() diff --git a/crates/celox-runtime/src/simulation/host.rs b/crates/celox-runtime/src/simulation/host.rs index e2c753c4181..146bc75484b 100644 --- a/crates/celox-runtime/src/simulation/host.rs +++ b/crates/celox-runtime/src/simulation/host.rs @@ -146,6 +146,14 @@ pub trait HostBoundary: UnitExecutor { fn try_end_time_slot(&mut self, _timestamp: u64) -> Result<(), Halt> { Ok(()) } + + /// Called before a run or a step moves from `timestamp` to a later time: + /// before the step of a later slot, and at the end of a run to a time + /// without work. An error ends the run there, as an error of a step + /// does, and so does a `$finish` the host ran there. + fn try_leave_time(&mut self, _timestamp: u64) -> Result<(), Halt> { + Ok(()) + } } /// How many time slots a compiled scheduler may run at once (see diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index bc1af0b2da8..4d469da3cad 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -278,7 +278,10 @@ impl SimulationState { Ok(Some(self.scheduler.time)) } // The time slot goes on when the simulation continues. - Err(Halt::Stop) => Ok(Some(self.scheduler.time)), + Err(Halt::Stop) => { + self.stopped = true; + Ok(Some(self.scheduler.time)) + } Err(Halt::Error(error)) => { if matches!(&error, SimulatorErrorCode::Fatal { .. }) { let _ = self.finalize_terminal(executor); @@ -342,6 +345,12 @@ impl SimulationState { } else { None }; + if compiled.is_some() + && next_time > self.scheduler.time + && !self.leave_time(executor)? + { + return Ok(false); + } observer.before_step(self, executor); let result = match compiled { Some(limit) => self.run_compiled(executor, limit), @@ -356,10 +365,42 @@ impl SimulationState { if self.finished { return Ok(false); } + if end > self.scheduler.time && !self.leave_time(executor)? { + return Ok(false); + } self.advance_time(executor.backend_mut(), end); Ok(true) } + /// The host's work before a run leaves the current time + /// ([`HostBoundary::try_leave_time`]). Returns `false` when it stopped + /// or finished the simulation. + fn leave_time(&mut self, executor: &mut E) -> Result + where + E: SimulationExecutor, + { + match executor.try_leave_time(self.scheduler.time) { + Ok(()) => Ok(true), + Err(Halt::Stop) => { + self.stopped = true; + Ok(false) + } + Err(Halt::Finish) => { + self.finalize_terminal(executor)?; + Ok(false) + } + Err(Halt::Error(error)) => { + if matches!(&error, SimulatorErrorCode::Fatal { .. }) { + let _ = self.finalize_terminal(executor); + return Err(error); + } + let _ = self.finish_timed_boundary(executor, self.scheduler.time); + let _ = executor.flush_output(); + Err(error) + } + } + } + /// Select the loop that runs time slots. pub fn set_scheduler_mode(&mut self, mode: SchedulerMode) { self.stats.mode = mode; diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index cad499b6469..e48d6ce660d 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -128,6 +128,9 @@ impl SimulationState { if current_time > limit { return Ok(settled); } + if current_time > self.scheduler.time { + executor.try_leave_time(self.scheduler.time)?; + } // Host writes alone: settle them, then go on to the next time. let host_only = self.host_pending && self.next_work_time() != Some(current_time); self.run_time(executor, current_time)?; diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 03eac608b15..71fc64b00c4 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 43; +const CONTAINER_VERSION: u16 = 44; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index eed84eed802..f189a1c3170 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -314,6 +314,17 @@ impl HostBoundary for Simulator { self.dump_unless_rewound(timestamp); } + /// Combinational logic still to settle belongs to `timestamp`, so its + /// reports read that time: settle it before the run moves on. + fn try_leave_time(&mut self, _timestamp: u64) -> Result<(), Halt> { + if self.timestamped_reports && self.dirty { + self.eval_comb_checked().map_err(Halt::Error)?; + self.dirty = false; + self.runtime_finish()?; + } + Ok(()) + } + /// Deferred assertions mature in the Observed and Postponed regions of /// the slot (IEEE 1800-2023 16.4). fn try_end_time_slot(&mut self, _timestamp: u64) -> Result<(), Halt> { @@ -748,7 +759,11 @@ impl Simulation { return self.watched_step(); } // With nothing scheduled, the step ends the slot too. + let was_stopped = self.is_stopped(); self.end_idle_slot(self.state.next_event_time().unwrap_or(u64::MAX))?; + if !was_stopped && self.is_stopped() { + return Ok(Some(self.time())); + } self.step_until(u64::MAX) } @@ -759,7 +774,7 @@ impl Simulation { /// run at that time. #[inline] fn end_idle_slot(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { - if !self.simulator.host_slot_work + if (!self.simulator.host_slot_work && !self.simulator.timestamped_reports) || end_time <= self.state.time() || self.state.next_event_time() == Some(self.state.time()) { @@ -774,7 +789,8 @@ impl Simulation { let result = if self.simulator.dirty { let result = self.simulator.eval_comb_checked(); self.simulator.dirty = false; - result + // A `$finish` of the settle finishes the simulation here. + result.and_then(|()| self.sync_finish_checked()) } else { Ok(()) }; @@ -796,7 +812,7 @@ impl Simulation { while let Some(next_time) = self.state.next_event_time() { if next_time > self.state.time() { self.watch_settle()?; - if self.reports.failure.is_some() { + if self.is_finished() || self.is_stopped() || self.reports.failure.is_some() { return Ok(Some(self.state.time())); } } @@ -844,7 +860,7 @@ impl Simulation { } if next_time > self.state.time() { self.watch_settle()?; - if self.reports.failure.is_some() { + if self.is_finished() || self.is_stopped() || self.reports.failure.is_some() { return Ok(false); } } @@ -858,7 +874,7 @@ impl Simulation { } } self.watch_settle()?; - Ok(self.reports.failure.is_none()) + Ok(!self.is_stopped() && self.reports.failure.is_none()) } /// Settle combinational logic that no step settled, as after host writes @@ -877,7 +893,11 @@ impl Simulation { return Ok(()); } if self.simulator.dirty { - if let Err(error) = self.simulator.eval_comb_checked() { + if let Err(error) = self + .simulator + .eval_comb_checked() + .and_then(|()| self.sync_finish_checked()) + { self.finalize_fatal(&error); self.flush_error_output(); return Err(error); @@ -959,7 +979,11 @@ impl Simulation { return Ok(()); } } else { + let was_stopped = self.is_stopped(); self.end_idle_slot(end_time)?; + if !was_stopped && self.is_stopped() { + return Ok(()); + } } let reached = match self.shadow.take() { None => self.state.run_until(&mut self.simulator, end_time)?, @@ -1008,6 +1032,9 @@ impl Simulation { } else { self.end_idle_slot(time)?; } + if self.is_finished() || self.is_stopped() { + return Ok(()); + } self.state.advance_time(&mut self.simulator.backend, time); if let Some(shadow) = &mut self.shadow { shadow @@ -1037,7 +1064,11 @@ impl Simulation { self.run_until(end_time)?; return Ok(!self.state.is_stopped()); } + let was_stopped = self.is_stopped(); self.end_idle_slot(end_time)?; + if !was_stopped && self.is_stopped() { + return Ok(false); + } let mut steps = 0; while let Some(next_time) = self.state.next_event_time() { if next_time > end_time { diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 5eb290bfa55..15e9737d7ac 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -167,6 +167,8 @@ mod host { /// Deferred assertions or sampled copies have work when a host /// call's time slot is over. pub(crate) host_slot_work: bool, + /// Some report site reads the time it issues its report at. + pub(crate) timestamped_reports: bool, /// Identity of the state layout, computed on first checkpoint use. pub(super) checkpoint_fingerprint: std::sync::OnceLock, /// State objects as state files name them, built on first use. @@ -304,6 +306,7 @@ mod host { } pub struct RuntimeEventDrain { + timed: bool, buffer: Arc, layout: MemoryLayout, sites: Vec, @@ -334,6 +337,7 @@ mod host { events .into_iter() .filter_map(|raw| render_raw_runtime_event(raw, &self.sites, ctx)) + .map(|event| untimed_report(event, self.timed, ctx)) .collect() } } @@ -631,6 +635,7 @@ mod host { args: &[RuntimeEventArgValue], ctx: RuntimeFormatContext<'_>, ) -> Vec { + let args = formatted_args(site, args); let Some(template) = site.template.as_deref() else { let default_spec = match site.kind { // Veryl prints arguments without a format string in hexadecimal. @@ -751,11 +756,48 @@ mod host { } } + /// Without a scheduler the simulation has no time: a report has the + /// time the host gives, not the one its site read. + fn untimed_report( + event: RuntimeEvent, + timed: bool, + ctx: RuntimeFormatContext<'_>, + ) -> RuntimeEvent { + match event { + RuntimeEvent::Report(report) if !timed => RuntimeEvent::Report(Report { + time: ctx.tb_time, + ..report + }), + event => event, + } + } + + /// The arguments of an event that its message formats: all but the + /// time of a timestamped site. + fn formatted_args<'a>( + site: &RuntimeEventSite, + args: &'a [RuntimeEventArgValue], + ) -> &'a [RuntimeEventArgValue] { + match (site.timestamp_arg, args.split_last()) { + (true, Some((_, args))) => args, + _ => args, + } + } + fn render_runtime_event( site: &RuntimeEventSite, args: &[RuntimeEventArgValue], ctx: RuntimeFormatContext<'_>, ) -> RuntimeEvent { + // The time the site issued the event, unless the host gives one. + let issued = site + .timestamp_arg + .then(|| args.last().and_then(|time| time.values.first().copied())) + .flatten(); + let ctx = RuntimeFormatContext { + tb_time: ctx.tb_time.or(issued), + ..ctx + }; let message = render_runtime_event_message(site, args, ctx); match site.kind { RuntimeEventKind::Display => RuntimeEvent::Display { message }, @@ -1025,6 +1067,7 @@ mod host { &program.runtime_schema.comb_observers, ); let sites = &program.runtime_schema.runtime_event_sites; + let timestamped_reports = sites.iter().any(|site| site.timestamp_arg); let deferred_sites = if sites.iter().any(|site| site.deferred.is_some()) { sites .iter() @@ -1084,6 +1127,7 @@ mod host { comb_deferred_groups, timed: false, host_slot_work: !deferred_sites.is_empty() || !sample_shadows.is_empty(), + timestamped_reports, sample_shadows, components: Default::default(), component_simulation: None, @@ -1429,6 +1473,7 @@ mod host { ctx, ) }) + .map(|event| untimed_report(event, self.timed, ctx)) .collect() } @@ -1715,6 +1760,7 @@ mod host { .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire) .ok()?; Some(RuntimeEventDrain { + timed: self.timed, buffer, layout: self.backend.layout().clone(), sites: self.program.runtime_schema.runtime_event_sites.clone(), diff --git a/crates/celox/src/simulator/host/file_io.rs b/crates/celox/src/simulator/host/file_io.rs index 1420c5d1975..90c2d98d1da 100644 --- a/crates/celox/src/simulator/host/file_io.rs +++ b/crates/celox/src/simulator/host/file_io.rs @@ -104,6 +104,7 @@ impl Simulator { location: None, assertion: None, deferred: None, + timestamp_arg: false, arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), diff --git a/crates/celox/tests/sv_reports.rs b/crates/celox/tests/sv_reports.rs index cceecc58a08..d7554e6b140 100644 --- a/crates/celox/tests/sv_reports.rs +++ b/crates/celox/tests/sv_reports.rs @@ -33,12 +33,24 @@ fn report( } } +/// `reports`, issued at `time`. +fn at(time: u64, reports: Vec) -> Vec { + reports + .into_iter() + .map(|report| Report { + time: Some(time), + ..report + }) + .collect() +} + macro_rules! reports { ($module:ident, $backend:ident) => { mod $module { use super::*; - /// The reports of `body` in `module Top` until time 1. + /// The reports of `body` in `module Top` until time 10, drained + /// after the run. fn reports(body: &str) -> Vec { let source = format!("`timescale 1ns/1ns\nmodule Top;\n{body}\nendmodule"); let mut sim = celox::Simulation::from_sv_sources( @@ -47,7 +59,7 @@ macro_rules! reports { ) .$backend() .unwrap(); - sim.run_until(1).unwrap(); + sim.run_until(10).unwrap(); sim.drain_runtime_events() .into_iter() .filter_map(|event| match event { @@ -68,11 +80,14 @@ macro_rules! reports { $error(\"e\");\n \ end" ), - vec![ - report(Severity::Info, "i 1", 5, None), - report(Severity::Warning, "w", 6, None), - report(Severity::Error, "e", 7, None), - ] + at( + 1, + vec![ + report(Severity::Info, "i 1", 5, None), + report(Severity::Warning, "w", 6, None), + report(Severity::Error, "e", 7, None), + ] + ) ); } @@ -91,7 +106,7 @@ macro_rules! reports { assume (!a) $info(\"assumed\");\n \ end" ), - vec![ + at(1, vec![ report( Severity::Warning, "a low", @@ -111,7 +126,7 @@ macro_rules! reports { Some((Some("c1"), Cover, Pass)) ), report(Severity::Info, "assumed", 9, Some((None, Assume, Pass))), - ] + ]) ); } @@ -131,12 +146,15 @@ macro_rules! reports { end\n \ end" ), - vec![report( - Severity::Error, - "assert failed", - 7, - Some((Some("inner"), Assert, Fail)) - )] + at( + 1, + vec![report( + Severity::Error, + "assert failed", + 7, + Some((Some("inner"), Assert, Fail)) + )] + ) ); } @@ -144,10 +162,26 @@ macro_rules! reports { fn always_comb_reports_keep_their_location() { assert_eq!( reports(" bit a;\n always_comb if (!a) $warning(\"low\");"), - vec![report(Severity::Warning, "low", 4, None)] + at(0, vec![report(Severity::Warning, "low", 4, None)]) ); } + /// A report keeps the time of its step however late the host + /// drains it (IEEE 1800-2023 20.10). + #[test] + fn reports_keep_their_time_when_drained_late() { + let times: Vec<_> = reports( + " initial begin\n \ + #1 $warning(\"w\");\n \ + #3 $error(\"e\");\n \ + end", + ) + .into_iter() + .map(|report| report.time) + .collect(); + assert_eq!(times, vec![Some(1), Some(4)]); + } + /// With `failOn`, a run stops after the time step of the first /// report of at least that severity, the next run continues, /// and every report keeps the time it was issued at. @@ -284,6 +318,145 @@ macro_rules! reports { assert!(failure.message.starts_with(b"missed "), "{failure:?}"); } + /// The initial settle of combinational logic is at time zero, + /// also when the first work is a clock edge at a later time, + /// reached by `run_until` or by `step`. + #[test] + fn initial_reports_before_a_later_first_slot_are_at_time_zero() { + let source = "`timescale 1ns/1ns\nmodule Top(input bit clk);\n \ + bit q, a;\n \ + always_ff @(posedge clk) q <= !q;\n \ + always_comb if (!a) $warning(\"low\");\nendmodule"; + for (step, watch) in [(false, false), (true, false), (false, true), (true, true)] { + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], + "Top", + ) + .$backend() + .unwrap(); + sim.add_clock("clk", 2, 5); + // Watching reports keeps the issued time too. + if watch { + sim.set_fail_on(Some(Severity::Warning)); + } + if step { + sim.step().unwrap(); + } else { + sim.run_until(10).unwrap(); + } + let times: Vec<_> = sim + .drain_runtime_events() + .into_iter() + .map(|event| match event { + celox::RuntimeEvent::Report(report) => report.time, + event => panic!("unexpected event {event:?}"), + }) + .collect(); + assert_eq!(times, vec![Some(0)], "step: {step}, watch: {watch}"); + if watch { + assert_eq!(sim.failure().and_then(|report| report.time), Some(0)); + } + } + } + + /// A leave-time settle can terminate before any scheduled slot. + /// Exercise the host entry points, report watching, and final blocks. + #[test] + fn initial_report_finish_preserves_time_and_runs_final() { + for clock in [false, true] { + for watch in [false, true] { + for entry in 0..4 { + let source = r#"`timescale 1ns/1ns +module Top(input bit clk); + bit a; + int ticks, final_calls; + always_ff @(posedge clk) ticks <= ticks + 1; + always_comb if (!a) begin $warning("initial"); $finish; end + final final_calls++; +endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], "Top", + ).$backend().unwrap(); + if clock { sim.add_clock("clk", 2, 5); } + if watch { sim.set_fail_on(Some(Severity::Error)); } + match entry { + 0 => sim.run_until(10).unwrap(), + 1 => { sim.step().unwrap(); } + 2 => sim.advance_to(10).unwrap(), + _ => { sim.run_until_bounded(10, 10).unwrap(); } + } + assert_eq!(sim.time(), 0, "clock={clock}, watch={watch}, entry={entry}"); + assert!(sim.is_finished(), "clock={clock}, watch={watch}, entry={entry}"); + let final_calls = sim.signal("final_calls"); + let ticks = sim.signal("ticks"); + assert_eq!(sim.get(final_calls), 1u32.into()); + assert_eq!(sim.get(ticks), 0u32.into()); + let times: Vec<_> = sim.drain_runtime_events().into_iter() + .filter_map(|event| match event { + celox::RuntimeEvent::Report(report) => Some(report.time), + _ => None, + }).collect(); + assert_eq!(times, vec![Some(0)]); + } + } + } + } + + #[test] + fn leave_time_final_can_stop_and_resume_at_the_same_time() { + for watch in [false, true] { + for entry in 0..4 { + let source = r#"`timescale 1ns/1ns +module Top; + bit a; + int final_calls; + always_comb if (!a) begin $warning("initial"); $finish; end + final begin final_calls++; $stop; final_calls++; end +endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], "Top", + ).$backend().unwrap(); + if watch { sim.set_fail_on(Some(Severity::Error)); } + for resumed in [false, true] { + match entry { + 0 => sim.run_until(10).unwrap(), + 1 => { sim.step().unwrap(); } + 2 => sim.advance_to(10).unwrap(), + _ => { sim.run_until_bounded(10, 10).unwrap(); } + } + assert_eq!(sim.time(), 0); + assert_eq!(sim.is_stopped(), !resumed, "watch={watch}, entry={entry}"); + assert_eq!(sim.is_finished(), resumed); + let final_calls = sim.signal("final_calls"); + assert_eq!(sim.get(final_calls), (if resumed { 2u32 } else { 1u32 }).into()); + } + } + } + } + + #[test] + fn initial_fatal_runs_final_before_returning_the_error() { + for clock in [false, true] { + let source = r#"`timescale 1ns/1ns +module Top(input bit clk); + bit a, q; + int final_calls; + always_ff @(posedge clk) q <= !q; + always_comb if (!a) $fatal(1, "initial"); + final final_calls++; +endmodule"#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, Path::new("reports.sv"))], "Top", + ).$backend().unwrap(); + if clock { sim.add_clock("clk", 2, 5); } + assert!(matches!(sim.run_until(10), Err(celox::RuntimeErrorCode::Fatal { .. }))); + assert_eq!(sim.time(), 0); + assert!(sim.is_finished()); + let final_calls = sim.signal("final_calls"); + assert_eq!(sim.get(final_calls), 1u32.into()); + } + } + #[test] fn line_directives_set_the_reported_location() { let reports = reports("`line 40 \"other.sv\" 0\n initial $info(\"moved\");"); @@ -300,7 +473,8 @@ macro_rules! reports { } reports!(interpreter, build_interpreter); -reports!(cranelift, build); +#[cfg(feature = "cranelift")] +reports!(cranelift, build_cranelift); #[cfg(target_arch = "x86_64")] reports!(native, build_native); reports!(wasm, build_wasm); diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 36732b073f3..46d41f1b895 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -704,9 +704,11 @@ severity, its message, the file and line of the call as `` `__FILE__ `` and action block of an immediate assertion also names that assertion: its statement label, `assert`, `assume` or `cover`, and whether the pass or the fail action issued it. Severity tasks in subroutines the action block calls -are not attributed. `time` is the time the drain's context gives, as the VPI -host does at each callback, or the time step of the report while -`Simulation::set_fail_on` is set. `Report::render` formats a report as the VPI host +are not attributed. `time` is the simulation time at which the report was +issued, however late the host drains it, unless the drain's context gives a +time, as the VPI host does at each callback; a `Simulator` has no time and +uses only the context's. +`Report::render` formats a report as the VPI host and the `celox` command print it. Only `$error` and `$fatal` fail a `celox` run; `$fatal` also ends the simulation with an error. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index f904894e6f7..95b86fd8b90 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -404,8 +404,9 @@ static な output 引数も、代入しない経路では以前の値を保持 スコープを持ちます。即時アサーションのアクションブロックからの報告は、そのアサーションも示します。 文ラベル、`assert` / `assume` / `cover` の別、pass と fail のどちらのアクションから出たかです。 アクションブロックが呼ぶサブルーチン内の重大度タスクは、アサーションに結び付けません。`time` は -drain のコンテキストが与える時刻で、VPI ホストはコールバックごとに与えます。`Simulation::set_fail_on` -の設定中は、報告が出たタイムステップの時刻です。`Report::render` は、 +報告を出したシミュレーション時刻で、ホストがいつ drain しても変わりません。ただし drain の +コンテキストが時刻を与える場合はそれを使います。VPI ホストはコールバックごとに与えます。 +`Simulator` は時刻を持たないので、コンテキストの時刻だけを使います。`Report::render` は、 VPI ホストと `celox` コマンドが表示する形に整形します。`celox` の実行を失敗にするのは `$error` と `$fatal` だけで、`$fatal` はさらにシミュレーションをエラーで終了します。 From 1a36881d200495eed6cb592fbb5fddb25ee26dfb Mon Sep 17 00:00:00 2001 From: tignear Date: Sat, 24 Oct 2026 16:40:36 +0900 Subject: [PATCH 4/4] feat(sv): extend sampled values and inferred history clocks Sample static locals and permit $sampled in combinational logic, while retaining the process's ordinary sensitivity. Infer the history clock in asynchronous-reset processes and called subroutines, including omitted-argument defaults. Reject nested sampled history and gates depending on unsupported subroutine arguments explicitly. For multi-event processes, advance history on every four-state edge in IEEE 1800-2023 Table 9-2. Compare the clock's least significant bit with case equality so 0-to-X/Z rising edges and 1-to-X/Z falling edges count too. The regression covers all ten positive/negative transitions on all four backends and failed before the fix. The documented limitation remains: a clock that returns to its pre-slot level within the same slot cannot yet be distinguished from another triggering event by the history guard. The regression registrations explicitly select build_cranelift; the default build() method selects native. Optional backends are feature-gated. Validation: - Sampled/history/deferred-assertion and native-image regressions: 187 passed. - SV analyzer/frontend, simulator and runtime units: 1,142 passed, 3 ignored. - Common SV timing suite including fork/process control: 1,057 passed; final procedures: 18 passed. - Affected-crate all-targets Clippy with -D warnings and formatting. - Debug NAPI build and timing/cascaded-clock/runtime-event JS integration: 9 passed. Change-Id: I964607db06fbe5e75728e0b7f4cfd935c303e332 --- crates/celox-frontend-sv/src/lowering.rs | 34 ++++- crates/celox-frontend-sv/src/lowering/ff.rs | 132 +++++++++++++++--- crates/celox-sv-analyzer/src/ast/lifetimes.rs | 22 +++ .../src/ast/procedural/control.rs | 14 ++ .../celox-sv-analyzer/src/system_functions.rs | 9 ++ crates/celox/tests/sv_deferred_assertions.rs | 27 ++-- crates/celox/tests/sv_past.rs | 117 +++++++++++++++- crates/celox/tests/sv_sampled.rs | 47 +++++-- docs/guide/systemverilog-reference.md | 34 +++-- docs/ja/guide/systemverilog-reference.md | 27 ++-- 10 files changed, 388 insertions(+), 75 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 45adbe3c2ae..9997aab84cf 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -9732,6 +9732,7 @@ fn lower_ff_processes( } let sites_before = pm.runtime_event_sites.len(); let extern_calls_before = pm.extern_calls; + let clock = inferred_clock(pm, process); let ff::FfProcessUnits { eval: eval_only, apply, @@ -9744,7 +9745,7 @@ fn lower_ff_processes( .with_shared_variables(shared_variables) .with_sparse_candidates(&edge_memories) .with_window_writes(&window_writes) - .with_inferred_clock(trigger_set.resets.is_empty()) + .with_inferred_clock(clock) .lower_process(process.body())?; repeated_writes.extend(repeated_ff_writes(&eval_only, &staged)); // A process without writes still runs for its runtime events and @@ -10462,6 +10463,37 @@ pub(crate) fn unsupported_sv_inout(path: String) -> ParserError { ) } +/// The clock that the sampled value functions of an edge-triggered process +/// infer (IEEE 1800-2023 16.14.6): its event expression of the clock, when +/// it is the only one whose signal the body reads nowhere else. With an +/// asynchronous reset the body reads the reset, so the clock remains. +fn inferred_clock( + pm: &procedural::ProcModule<'_>, + process: &sv::ir::FfProcess, +) -> Option { + let clock = clock_event_from_ff_process(process)?; + let reads: HashSet = pm + .implicit_reads(process.body(), true) + .into_iter() + .map(|atom| atom.id) + .collect(); + let unread: Vec<_> = process + .events() + .iter() + .filter(|event| pm.id(event.signal()).is_none_or(|id| !reads.contains(&id))) + .collect(); + match unread.as_slice() { + [only] if only.signal() == clock.signal() && only.edge() == clock.edge() => { + Some(ff::Clock { + signal: clock.signal().to_owned(), + rising: clock.edge() == sv::ir::FfEdge::Pos, + alone: process.events().len() == 1, + }) + } + _ => None, + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 6f23db2d86c..bdc54ff5324 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -102,16 +102,23 @@ pub(super) struct Ff<'p, 'a> { /// The flush-point site of a process with deferred assertions, whose /// queue their actions wait in. flush_site: Option, - /// A combinational process is being lowered. - combinational: bool, - /// The process has the one clock that sampled value functions infer - /// (IEEE 1800-2023 16.14.6): an edge-triggered process with a single - /// event, which runs at each tick of it. - inferred_clock: bool, + /// The clock that the sampled value functions of the process infer + /// (IEEE 1800-2023 16.14.6). + inferred_clock: Option, /// The `$past` histories of the process. history: Vec, } +/// The clock of an edge-triggered process. +pub(super) struct Clock { + /// The clock signal. + pub signal: String, + /// Whether a tick is a rising edge. + pub rising: bool, + /// The clock is the only event of the process, so every run is a tick. + pub alone: bool, +} + /// The sampled values of variable `name` at the previous ticks of the clock /// of a process: `chain[k - 1]` holds the value `k` ticks ago, counting /// only the ticks at which the gate held. @@ -181,31 +188,28 @@ impl<'p, 'a> Ff<'p, 'a> { host_request_sites: Vec::new(), nba_switches: Vec::new(), flush_site: None, - combinational: false, - inferred_clock: false, + inferred_clock: None, history: Vec::new(), } } - /// Lower an edge-triggered process whose single event is the clock of - /// its sampled value functions. - pub fn with_inferred_clock(mut self, inferred: bool) -> Self { - self.inferred_clock = inferred; + /// Lower an edge-triggered process with the clock its sampled value + /// functions infer, if any. + pub fn with_inferred_clock(mut self, clock: Option) -> Self { + self.inferred_clock = clock; self } /// The operand of `$sampled` (IEEE 1800-2023 16.9.3) with each static /// variable read through its sampled copy. Automatic variables and the /// lowering's own temporaries keep their current value (16.5.1). A - /// combinational process reruns when its inputs change, not when their - /// sampled values do, so it cannot read them. + /// combinational process stays sensitive to the variables themselves, + /// whose changes run it, not to their copies: it is lowered as a gated + /// unit that keeps the value it last computed. fn sampled( &mut self, args: &[Option], ) -> Result { - if self.combinational { - return Err(unsupported("$sampled in combinational logic")); - } let [Some(operand)] = args else { return Err(unsupported("operand of `$sampled`")); }; @@ -249,14 +253,34 @@ impl<'p, 'a> Ff<'p, 'a> { } /// Declare the `$past` histories that the sampled value functions of - /// `body` read, as nonblocking targets of the process. + /// `body`, and of the subroutines it calls, read, as nonblocking targets + /// of the process. A subroutine's calls infer the clock of the process + /// that calls it. fn declare_history(&mut self, body: &[sv::ir::Stmt]) -> Result<(), sv::AnalyzerError> { use sv::ir::SystemFunction; let mut calls = Vec::new(); for stmt in body { stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); } - for (callee, args) in calls { + // The calls after these are in subroutines the body calls. + let body_calls = calls.len(); + let mut visited = HashSet::default(); + let mut index = 0; + while index < calls.len() { + if let (sv::ir::Callee::Subroutine(name), args) = calls[index].clone() + && let Some(subroutine) = self.m.subroutine(&name).cloned() + { + // The defaults of omitted arguments run at the call. + default_calls(&subroutine, &args, &mut calls); + if visited.insert(name) { + for stmt in &subroutine.body { + stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); + } + } + } + index += 1; + } + for (position, (callee, args)) in calls.into_iter().enumerate() { let sv::ir::Callee::System( function @ (SystemFunction::Past | SystemFunction::Rose @@ -267,15 +291,32 @@ impl<'p, 'a> Ff<'p, 'a> { else { continue; }; - if !self.inferred_clock { + if self.inferred_clock.is_none() { return Err(unsupported(format!( - "`{function}` outside an edge-triggered process with one event, whose clock it infers" + "`{function}` outside an edge-triggered process whose clock it infers" ))); } let (depth, gate) = past_depth_and_gate(function, &args)?; let Some(Some(operand)) = args.first() else { return Err(unsupported(format!("operand of `{function}`"))); }; + // The process evaluates the gate before its body runs, outside + // the subroutine: there the gate can read only module variables, + // not the subroutine's arguments or locals. + if position >= body_calls + && let Some(gate) = &gate + { + let mut names = HashSet::default(); + expr_idents(gate, &mut names); + if names + .iter() + .any(|name| self.m.id(name).is_none_or(|id| self.m.is_hidden(id))) + { + return Err(unsupported(format!( + "`{function}` in a subroutine with a gate that reads the subroutine's arguments or locals" + ))); + } + } // The history of a nested call would need its own chain. let mut nested = Vec::new(); collect_calls(operand, &mut nested); @@ -385,7 +426,7 @@ impl<'p, 'a> Ff<'p, 'a> { }) .ok_or_else(|| { unsupported(format!( - "`{function}` outside an edge-triggered process with one event, whose clock it infers" + "`{function}` outside an edge-triggered process whose clock it infers" )) })?; renames.insert(name, history.chain[depth - 1].clone()); @@ -454,6 +495,9 @@ impl<'p, 'a> Ff<'p, 'a> { arg_order: Vec::new(), }; let mut stmts = Vec::new(); + if self.history.is_empty() { + return Ok(true); + } for history in &self.history { let mut updates: Vec = history .chain @@ -478,6 +522,49 @@ impl<'p, 'a> Ff<'p, 'a> { }), } } + // A run for another event, such as an asynchronous reset, is no + // tick: the clock has kept the level it had before the slot. + let clock = self + .inferred_clock + .as_ref() + .expect("histories have a clock"); + if !clock.alone { + use sv::ir::BinaryOp::{EqCase, LogicAnd, LogicOr, NeCase}; + let to = Expr::Literal(if clock.rising { "1'b1" } else { "1'b0" }.into()); + let from = Expr::Literal(if clock.rising { "1'b0" } else { "1'b1" }.into()); + // Edge events inspect only the least significant bit (9.4.2). + let signal = Expr::Resize { + expr: Box::new(Expr::Ident(clock.signal.clone())), + width: 1, + signed: false, + }; + let old = sampled(signal.clone()); + let compare = |left: Expr, op, right: Expr| Expr::Binary { + left: Box::new(left), + op, + right: Box::new(right), + }; + // Table 9-2: leaving the opposite known level for X/Z is an + // edge too, as is arriving at the target level from X/Z. + let tick = compare( + compare( + compare(old.clone(), EqCase, from.clone()), + LogicAnd, + compare(signal.clone(), NeCase, from), + ), + LogicOr, + compare( + compare(old, NeCase, to.clone()), + LogicAnd, + compare(signal, EqCase, to), + ), + ); + stmts = vec![Stmt::If { + condition: tick, + then_body: stmts, + else_body: Vec::new(), + }]; + } self.exec_block(&stmts) } @@ -4475,7 +4562,6 @@ impl<'p, 'a> Ff<'p, 'a> { // `initial` blocks, like `always_comb`, as Verilator settles them. let runs_at_time_zero = always_comb || !self.m.four_state; self.direct = true; - self.combinational = true; let mut reads = self.m.implicit_reads(body, always_comb); reads.extend(self.m.implicit_reads(sensitivity_body, always_comb)); for stmt in body { diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index da8e1a27b8b..dfae6dedfab 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -71,9 +71,12 @@ fn keep_in( ) -> Result<(), AnalyzerError> { let mut index = 0; while index < stmts.len() { + // A sampled value of a static local is its value from an earlier + // time slot (IEEE 1800-2023 16.5.1), which the local keeps. if let Stmt::Local { name, init } = &stmts[index] && statics.contains_key(name) && (concurrent + || sampled_reads(&stmts[index + 1..], name) || entry( state, name, @@ -839,6 +842,25 @@ pub(super) fn stmt_exprs(stmt: &Stmt) -> Vec<&Expr> { } } +/// Whether a sampled value function in `stmts` reads `name`. +fn sampled_reads(stmts: &[Stmt], name: &str) -> bool { + let mut found = false; + for stmt in stmts { + stmt.walk(&mut |stmt| { + for expr in stmt_exprs(stmt) { + visit_calls(expr, &mut |callee, args| { + if let Callee::System(function) = callee + && function.reads_sampled_values() + { + found |= args.iter().flatten().any(|arg| expr_reads(arg, name)); + } + }); + } + }); + } + found +} + /// Call `f` with the callee and arguments of every call in `expr`. pub(super) fn visit_calls<'e>(expr: &'e Expr, f: &mut impl FnMut(&'e Callee, &'e [Option])) { match expr { diff --git a/crates/celox-sv-analyzer/src/ast/procedural/control.rs b/crates/celox-sv-analyzer/src/ast/procedural/control.rs index 4b9619346cd..e9807660083 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/control.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/control.rs @@ -329,6 +329,20 @@ impl BodyBuilder<'_, '_, '_> { unreachable!("matched an immediate header"); }; let statement = native.statement(id); + // The action of a deferred assertion is one + // subroutine call (IEEE 1800-2023 16.4), not a block. + if deferred.is_some() + && success.iter().chain(failure).any(|&action| { + !matches!( + native.statement(action).kind, + StatementKind::Empty | StatementKind::Expression(_) + ) + }) + { + return Err(unsupported( + "deferred assertion action other than one display or severity task call", + )); + } jobs.push(Job::AssertionThen { condition, keyword: keyword.clone(), diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 0a9507f995f..9a1ce737663 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -371,6 +371,15 @@ impl SystemFunction { /// Whether a call reads the state of the simulation: it has an effect, /// or it returns the simulation time. Such a call is not a constant /// expression, and a process evaluates it where it runs. + /// Whether the function reads the sampled values of its operand + /// (IEEE 1800-2023 16.9.3), which are those of earlier time slots. + pub fn reads_sampled_values(self) -> bool { + matches!( + self, + Self::Sampled | Self::Past | Self::Rose | Self::Fell | Self::Stable | Self::Changed + ) + } + pub fn reads_simulation_state(self) -> bool { self.is_effectful() || matches!( diff --git a/crates/celox/tests/sv_deferred_assertions.rs b/crates/celox/tests/sv_deferred_assertions.rs index bffd145a554..6cc9c7493a3 100644 --- a/crates/celox/tests/sv_deferred_assertions.rs +++ b/crates/celox/tests/sv_deferred_assertions.rs @@ -390,7 +390,8 @@ macro_rules! deferred { } deferred!(interpreter, build_interpreter); -deferred!(cranelift, build); +#[cfg(feature = "cranelift")] +deferred!(cranelift, build_cranelift); #[cfg(target_arch = "x86_64")] deferred!(native, build_native); deferred!(wasm, build_wasm); @@ -526,14 +527,22 @@ fn a_first_drain_returns_actions_of_the_initial_settle() { #[test] fn deferred_actions_are_one_display_or_severity_task_call() { - let source = "module Top; bit a;\n \ - initial assert #0 (a) else begin $error(\"x\"); $error(\"y\"); end\n\ - endmodule"; - let error = celox::Simulation::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top") + for action in [ + "begin $error(\"x\"); $error(\"y\"); end", + "begin $error(\"x\"); end", + "a = 1;", + ] { + let source = + format!("module Top; bit a;\n initial assert #0 (a) else {action}\nendmodule"); + let error = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("deferred.sv"))], + "Top", + ) .build() .unwrap_err(); - assert!( - error.to_string().contains("deferred assertion action"), - "{error}" - ); + assert!( + error.to_string().contains("deferred assertion action"), + "{action}: {error}" + ); + } } diff --git a/crates/celox/tests/sv_past.rs b/crates/celox/tests/sv_past.rs index b3d246b356a..8172d6a0066 100644 --- a/crates/celox/tests/sv_past.rs +++ b/crates/celox/tests/sv_past.rs @@ -198,6 +198,106 @@ macro_rules! past { assert_eq!(value(&mut sim, "p1"), 5); } + /// With an asynchronous reset the body reads the reset, so the + /// clock is inferred (IEEE 1800-2023 16.14.6); a run for the + /// reset is no tick. `a` is 0, 1, 2 at the ticks 1, 3, 5, and the + /// reset pulses low at 4: had that run shifted the history, + /// `$past(a, 2)` would be 1 at 5. + #[test] + fn an_asynchronous_reset_is_no_tick() { + let mut sim = simulation( + " bit rst = 1;\n \ + always_ff @(posedge clk or negedge rst)\n \ + if (!rst) p2 <= p2 + 1; else p1 <= $past(a, 2);\n \ + initial begin #2 a = 1; #2 a = 2; rst = 0; #0 rst = 1; end", + ); + sim.run_until(5).unwrap(); + assert_eq!((value(&mut sim, "p1"), value(&mut sim, "p2")), (0, 1)); + sim.run_until(7).unwrap(); + assert_eq!(value(&mut sim, "p1"), 1); + } + + /// Multi-event processes count all four-state clock edges + /// (IEEE 1800-2023 Table 9-2), including transitions into X/Z. + #[test] + fn four_state_clock_edges_advance_history() { + for (edge, old, new) in [ + ("posedge", "0", "1"), + ("posedge", "0", "x"), + ("posedge", "0", "z"), + ("posedge", "x", "1"), + ("posedge", "z", "1"), + ("negedge", "1", "0"), + ("negedge", "1", "x"), + ("negedge", "1", "z"), + ("negedge", "x", "0"), + ("negedge", "z", "0"), + ] { + let source = format!(r#"`timescale 1ns/1ns +module Top; + logic clk = 1'b{old}; + bit rst = 1; + bit [7:0] a, p; + always_ff @({edge} clk or negedge rst) + if (!rst) p <= 0; else p <= $past(a); + initial begin + a = 11; + #1 clk = 1'b{new}; + #1 a = 22; clk = 1'b{old}; + #1 clk = 1'b{new}; + end +endmodule"#); + let mut sim = celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("past.sv"))], "Top", + ).four_state(true).$backend().unwrap(); + sim.run_until(3).unwrap(); + assert_eq!(value(&mut sim, "p"), 11, "{edge} {old}->{new}"); + } + } + + /// A function called by a clocked process infers its clock. + #[test] + fn subroutines_infer_the_clock_of_their_caller() { + let mut sim = simulation( + " function bit [7:0] previous();\n \ + return $past(a);\n \ + endfunction\n \ + always @(posedge clk) p1 <= previous();\n \ + initial begin #2 a = 1; #2 a = 2; #2 a = 3; end", + ); + sim.run_until(7).unwrap(); + assert_eq!(value(&mut sim, "p1"), 2); + } + + /// So does the default of an omitted argument. + #[test] + fn argument_defaults_infer_the_clock_of_their_caller() { + let mut sim = simulation( + " function bit [7:0] pass(bit [7:0] v = $past(a));\n \ + return v;\n \ + endfunction\n \ + always @(posedge clk) p1 <= pass();\n \ + initial begin #2 a = 1; #2 a = 2; #2 a = 3; end", + ); + sim.run_until(7).unwrap(); + assert_eq!(value(&mut sim, "p1"), 2); + } + + /// A subroutine's history is as deep as its own calls need, also + /// beyond the caller's. + #[test] + fn subroutines_declare_their_own_history() { + let mut sim = simulation( + " function bit [7:0] deeper();\n \ + return $past(a, 2);\n \ + endfunction\n \ + always @(posedge clk) begin p1 <= $past(a); p2 <= deeper(); end\n \ + initial begin #2 a = 1; #2 a = 2; #2 a = 3; end", + ); + sim.run_until(7).unwrap(); + assert_eq!((value(&mut sim, "p1"), value(&mut sim, "p2")), (2, 1)); + } + /// Without one clock to infer, the functions are rejected. #[test] fn a_clock_must_be_inferable() { @@ -305,18 +405,25 @@ fn operands_histories_cannot_hold_are_rejected() { "`$sampled` of an operand that calls a sampled value function", ), ( - "function bit deeper(); return $past(a, 2); endfunction\n \ - always_ff @(posedge clk) begin r <= $past(a); s <= deeper(); end", - "whose clock it infers", + "function automatic bit gated(bit enable); return $past(a, 1, enable); endfunction\n \ + always_ff @(posedge clk) r <= gated(1'b1);", + "gate that reads the subroutine's arguments", + ), + ( + "function bit [7:0] previous(); return $past(a); endfunction\n \ + always_ff @(posedge clk) r <= $past(previous());", + "calls a function", ), ] { let source = format!( "module Top(input bit clk, input bit a, output bit r, output bit s, output time t);\n {body}\nendmodule" ); - let error = + let Err(error) = celox::Simulator::from_sv_sources(vec![(source.as_str(), Path::new("past.sv"))], "Top") .build() - .unwrap_err(); + else { + panic!("{body} builds"); + }; assert!(error.to_string().contains(message), "{body}: {error}"); } } diff --git a/crates/celox/tests/sv_sampled.rs b/crates/celox/tests/sv_sampled.rs index 30366cc5364..9e7346959ea 100644 --- a/crates/celox/tests/sv_sampled.rs +++ b/crates/celox/tests/sv_sampled.rs @@ -181,25 +181,48 @@ endmodule"#; assert_eq!(value(&mut sim, "v"), 5); } + /// A static local keeps its value between runs, so its sampled + /// value is the one the previous run left; an automatic one is + /// read as it is (IEEE 1800-2023 16.5.1). `a` is 0, 1, 2, 3 at + /// the edges 1, 3, 5, 7. #[test] - fn combinational_logic_cannot_read_sampled_values() { + fn static_locals_are_sampled_and_automatic_ones_are_not() { + let mut sim = simulation( + " bit [7:0] p, q, w;\n \ + always #1 clk = ~clk;\n \ + always @(posedge clk) begin\n \ + bit [7:0] t;\n \ + automatic bit [7:0] u;\n \ + t = w; u = w;\n \ + p <= $sampled(t); q <= $sampled(u);\n \ + end\n \ + initial begin #2 w = 1; #2 w = 2; #2 w = 3; end", + ); + sim.run_until(7).unwrap(); + assert_eq!((value(&mut sim, "p"), value(&mut sim, "q")), (2, 3)); + } + + /// A combinational process runs when its inputs change, not + /// when their sampled values do, so it keeps the sampled value + /// it read (IEEE 1800-2023 4.5, 16.9.3). `a` becomes 1 at 1 and + /// 2 at 3. + #[test] + fn combinational_logic_reads_sampled_values_when_it_runs() { for item in [ "always_comb y = $sampled(a);", "always @(a) y = $sampled(a);", "assign y = $sampled(a);", ] { - let source = format!("module Top; bit a, y; {item} endmodule"); - let error = celox::Simulation::from_sv_sources( - vec![(source.as_str(), Path::new("sampled.sv"))], - "Top", - ) - .$backend() - .err() - .expect("rejected"); - assert!( - error.to_string().contains("$sampled in combinational logic"), - "{item}: {error}" + let body = format!( + " {item}\n initial begin #1 a = 1; #2 a = 0; end" ); + let mut sim = simulation(&body); + let mut values = Vec::new(); + for time in [0, 1, 2, 3, 4] { + sim.run_until(time).unwrap(); + values.push(value(&mut sim, "y")); + } + assert_eq!(values, vec![0, 0, 0, 1, 1], "{item}"); } } } diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 46d41f1b895..1884b55f280 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -210,7 +210,7 @@ waits zero. | System functions | `$timeunit`, `$timeprecision`, `$bits`, `$size`, `$left`, `$right`, `$low`, `$high`, `$increment`, `$dimensions`, `$unpacked_dimensions`, `$clog2`, `$countbits`, `$countones`, `$onehot`, `$onehot0`, `$isunknown`, `$isunbounded` in expressions, constant expressions and as statements; `$signed`, `$unsigned` in expressions, constant expressions and as statements | | Random numbers | `$urandom`, `$urandom_range`, `$random` and `$dist_uniform` in clocked processes, `always_comb`, `always @*`, `initial` blocks and their subroutines; an optional integral seed of `$urandom`, a seed variable of `$random`, and a separate stream per process | | Simulation time | `$time`, `$stime` and `$realtime` in clocked and combinational processes, continuous assignments, `initial` blocks and their subroutines | -| Sampled values | `$sampled` in edge-triggered processes, processes with timing controls, `initial` blocks and the subroutines they call; `$past`, `$rose`, `$fell`, `$stable` and `$changed` in edge-triggered processes with one event; see [Sampled values](#sampled-values) | +| Sampled values | `$sampled` in processes, combinational logic and the subroutines they call; `$past`, `$rose`, `$fell`, `$stable` and `$changed` in edge-triggered processes whose clock they infer and the subroutines those call; see [Sampled values](#sampled-values) | | System tasks | `$printtimescale`, `$display`, `$write` and their `b` / `o` / `h` forms, `$error`, `$warning`, `$info`, `$fatal`, `$finish`, `$stop`, `$exit` in `always` processes, subroutines and `initial` blocks; `$readmemh` / `$readmemb` there and in `initial` blocks; Veryl's `$assert` and `$assert_continue` | | Runtime I/O | `$test$plusargs`, `$value$plusargs`, `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and radix variants, `$writememh` / `$writememb`, and [VCD controls](./vcd#systemverilog-source-controls) in timed processes | | State | two-state and four-state simulation | @@ -720,12 +720,13 @@ or default value (IEEE 1800-2023 4.4.2.1, 16.5.1). Each static variable the operand reads, the indices of its selects and the arguments of its calls included, is read from a copy that the timed simulation updates before advancing to a later timestamp. Returning to the host and resuming at the same timestamp -retains that copy, including across host writes. Automatic variables keep their current value. A `Simulator` call is a -time slot. `$sampled` in combinational logic (`always_comb`, `always_latch`, -an `always` lowered as combinational logic, a continuous assignment) is -rejected: such a process reruns when its inputs change, not when their sampled -values do. A design that uses `$sampled` runs the compiled scheduler one slot -at a time. +retains that copy, including across host writes. Automatic variables keep their current value; a static local is +sampled like a module variable. A `Simulator` call is a time slot. In +combinational logic (`always_comb`, `always_latch`, an `always` lowered as +combinational logic, a continuous assignment) the process reruns when the +operand's variables change, not when their sampled values do, and keeps the +sampled value it read until then (4.5). A design that uses `$sampled` runs the +compiled scheduler one slot at a time. `$past(e, k, gate)` is the sampled value of `e` at the `k`-th previous tick of its clock at which `gate` held, the `iff` of the clock (9.4.2.3), and `$rose`, `$fell`, `$stable` @@ -734,13 +735,18 @@ previous tick, with case equality for integral values and numeric equality for `real`/`shortreal` (`$rose` and `$fell` look at the least significant bit). Before enough ticks, the past value is the declared or default value (16.9.3). `k` is a positive constant. The clock is inferred -(16.14.6): the functions are supported in an `always_ff` or `always` process -whose only timing control is one edge event, such as `@(posedge clk)`, and -which therefore runs at each tick. The process keeps a history register for -each variable of the operand and updates it with nonblocking assignments at -the end of each run. An explicit clocking event argument, processes with -more than one event (such as an asynchronous reset) and calls in subroutines -are rejected. +(16.14.6): in an `always_ff` or `always` process whose only timing control is +its event control, it is the clock edge when that is the only event whose +signal the body reads nowhere else, as with an asynchronous reset that the +body tests. A subroutine the process calls, also from the default of an +omitted argument, infers the same clock. The process keeps a history register +for each variable of the operand and updates it with nonblocking assignments at +the end of each run that is a tick of the clock. With an asynchronous reset, a +run is a tick when the clock has left the level it had before the time slot: a +clock that returns to that level within the slot, as `clk = 0; #0 clk = 1;` +from 1, does not move the history. An explicit clocking event argument, calls +without a clock to infer, nested calls such as `$past($past(a))` and operands +that read an unpacked array are rejected. ### Deferred assertions diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 95b86fd8b90..439ea865291 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -154,7 +154,7 @@ enumは宣言された値だけから均等に抽選し、飛び飛びの値や | システム関数 | `$timeunit`、`$timeprecision`、`$bits`、`$size`、`$clog2`、`$countbits`、`$countones`、`$onehot`、`$onehot0`、`$isunknown`、`$isunbounded` は式・定数式の中と文として。`$signed`、`$unsigned` は式の中と文として | | 乱数 | `$urandom`、`$urandom_range`、`$random`、`$dist_uniform` はクロックで起動するプロセス、`always_comb`、`always @*`、`initial` とそれらから呼ぶサブルーチンで使用可能。`$urandom` の任意の整数式によるシード、`$random` のシード変数、プロセスごとに独立した乱数列 | | シミュレーション時刻 | `$time`、`$stime`、`$realtime` はクロックで起動するプロセス、組合せプロセス、継続代入、`initial` とそれらから呼ぶサブルーチンで使用可能 | -| サンプル値 | `$sampled` はエッジで起動するプロセス、タイミング制御を含むプロセス、`initial` とそれらから呼ぶサブルーチンで使用可能。`$past`、`$rose`、`$fell`、`$stable`、`$changed` はイベントが 1 つのエッジで起動するプロセスで使用可能。[サンプル値](#sampled-values) を参照 | +| サンプル値 | `$sampled` はプロセス、組み合わせ回路とそれらから呼ぶサブルーチンで使用可能。`$past`、`$rose`、`$fell`、`$stable`、`$changed` はクロックを推論できるエッジで起動するプロセスと、そこから呼ぶサブルーチンで使用可能。[サンプル値](#sampled-values) を参照 | | システムタスク | `always` 系のプロセスとサブルーチンの `$printtimescale`、`$display`、`$write` とその `b` / `o` / `h` 形、`$error`、`$warning`、`$info`、`$fatal`、`$finish`、`$stop`、`$exit`。`initial` ブロックでも使えます。`$readmemh` / `$readmemb` はそれらと `initial` ブロック。Veryl の `$assert` と `$assert_continue` | | 実行時 I/O | `$test$plusargs`、`$value$plusargs`、`$fopen`、`$fclose`、`$fdisplay` / `$fwrite` と基数指定形、`$writememh` / `$writememb`、[VCD 制御](./vcd#systemverilog-source-controls)。時間を持つプロセスで実行 | | 状態 | 2 値・4 値シミュレーション | @@ -416,21 +416,26 @@ VPI ホストと `celox` コマンドが表示する形に整形します。`cel 最初のスロットでは宣言の初期値か既定値です(IEEE 1800-2023 4.4.2.1、16.5.1)。被演算子が読む 静的変数は、選択のインデックスや呼び出しの引数の中のものも含めて、時刻を先へ進める直前に 更新するコピーから読みます。同じ時刻にホストへ戻って再開しても、ホストからの書き込みを含め、 -コピーは更新しません。automatic 変数は現在の値のままです。`Simulator` では呼び出し 1 回が -タイムスロットです。組み合わせ回路(`always_comb`、`always_latch`、組み合わせ回路として扱う -`always`、継続代入)の中の `$sampled` は拒否します。こうしたプロセスは入力が変わったときに -再実行するもので、入力のサンプル値が変わったときではないためです。`$sampled` を使う設計では、 -コンパイル済みスケジューラを 1 スロットずつ実行します。 +コピーは更新しません。automatic 変数は現在の値のままで、静的なローカル変数はモジュールの +変数と同じくサンプルします。`Simulator` では呼び出し 1 回がタイムスロットです。組み合わせ回路 +(`always_comb`、`always_latch`、組み合わせ回路として扱う `always`、継続代入)では、プロセスは +被演算子の変数が変わったときに再実行し、サンプル値が変わったときには再実行しません。それまでは +読んだサンプル値を保ちます(4.5)。`$sampled` を使う設計では、コンパイル済みスケジューラを +1 スロットずつ実行します。 `$past(e, k, gate)` は、クロックの `iff` である `gate`(9.4.2.3)が成り立っていたティックのうち `k` 個前のものでの `e` のサンプル値です。`$rose`、`$fell`、`$stable`、`$changed` は、被演算子のサンプル値を 前のティックでのものと、整数型なら case 等価、`real` / `shortreal` なら数値の等価で比べます(`$rose` と `$fell` は最下位ビットを見ます)。ティックが 足りないうちは、過去の値は宣言の初期値か既定値です(16.9.3)。`k` は正の定数です。クロックは -推論します(16.14.6)。これらの関数は、タイミング制御が `@(posedge clk)` のようなエッジイベント -1 つだけで、そのためティックごとに実行する `always_ff` / `always` プロセスで使えます。プロセスは -被演算子の変数ごとに履歴レジスタを持ち、実行の最後にノンブロッキング代入で更新します。明示した -クロッキングイベント引数、イベントが複数あるプロセス(非同期リセットなど)、サブルーチン内の -呼び出しは拒否します。 +推論します(16.14.6)。タイミング制御がイベント制御だけの `always_ff` / `always` プロセスでは、 +本体がほかで読まない信号のイベントがクロックのエッジだけのとき、それがクロックです。本体が +判定する非同期リセットがこれに当たります。プロセスが呼ぶサブルーチンも、省略した引数の既定値から +呼ぶものを含めて、同じクロックを推論します。プロセスは被演算子の変数ごとに履歴レジスタを持ち、 +クロックのティックである実行の最後にノンブロッキング代入で更新します。非同期リセットがあるときは、 +クロックがタイムスロット前のレベルから変わっている実行をティックとします。1 から `clk = 0; #0 clk = 1;` +のように同じスロット内で元のレベルに戻ったクロックでは、履歴は進みません。明示したクロッキング +イベント引数、推論できるクロックのない呼び出し、`$past($past(a))` のような入れ子の呼び出し、 +アンパック配列を読む被演算子は拒否します。 ### 遅延付きアサーション