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))` のような入れ子の呼び出し、 +アンパック配列を読む被演算子は拒否します。 ### 遅延付きアサーション