From f1a6efbb8e239ab42aac364a80e6947b14b8c558 Mon Sep 17 00:00:00 2001 From: tignear Date: Mon, 26 Oct 2026 17:46:55 +0900 Subject: [PATCH] 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` 形のアクションは、プロセスの遅延