From b10ec209a8a6a0e95b1189b7a9c26b185b0a21c1 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 17:32:47 +0900 Subject: [PATCH 1/4] feat(sv): run always @* calls of timed tasks as processes and accept package delays A plain always @* that calls a task containing a timing control was rejected. It is an ordinary always procedure (IEEE 1800-2023 9.2.2.2.2), so it now runs as a process that waits on its implicit event list, the variables the statement reads with the task's arguments but not its body (9.4.2.2), before each run, like an always @* with a direct timing control. always_comb and always_latch may not suspend (9.2.2.2): a timed task call there is now the same language error as a direct timing control, instead of an unsupported construct. A package-scoped delay value such as #pkg::D is a ps_identifier delay_value (A.6.5); it is now bound like the parenthesized #(pkg::D). Verilator 5.052 schedules the always @* case differently and Icarus 13.0 cannot parse #pkg::D; both cases are excluded with retained evidence. The wait of an @* now keeps the statements it covers, folded branches included (Stmt::WaitImplicit), and the frontend reads them with the analysis that gives a combinational always @* its sensitivity: the defaults of omitted arguments, of nested calls too, and constant-false branches count (9.4.2.2), and timing-control expressions do not. Direct @* waits in processes use the same analysis. Icarus prunes folded branches and Verilator leaves defaults out; both are excluded. Fixes #1710 Change-Id: I187e0c26549e9aca2eda399699c24ddbc8de24bf --- crates/celox-frontend-sv/src/lowering/comb.rs | 7 +- crates/celox-frontend-sv/src/lowering/ff.rs | 140 ++++++++++++++- .../src/lowering/procedural.rs | 1 + crates/celox-sv-analyzer/src/ast.rs | 7 +- .../celox-sv-analyzer/src/ast/comb_process.rs | 7 +- .../src/ast/const_functions.rs | 4 +- crates/celox-sv-analyzer/src/ast/constants.rs | 2 + crates/celox-sv-analyzer/src/ast/lifetimes.rs | 14 +- .../src/ast/procedural/timed_tasks.rs | 79 +++++++- .../src/ast/procedural/timing.rs | 169 +----------------- .../celox-sv-analyzer/src/ast/validation.rs | 5 +- crates/celox-sv-analyzer/src/procedural.rs | 8 + crates/celox-sv-analyzer/src/tests.rs | 43 +++-- crates/celox-test-suite/LIMITATIONS.md | 26 +++ .../src/sv/cases/timing.vtest | 122 +++++++++++++ .../verification/sv/icarus/timing.json | 79 ++++++++ .../verification/sv/limitations.json | 70 ++++++++ .../verification/sv/limitations/icarus.json | 20 ++- .../sv/limitations/verilator.json | 34 +++- .../verification/sv/verilator/timing.json | 103 +++++++++++ .../frontends/systemverilog/synthesizable.rs | 6 +- .../tests/frontends/systemverilog/timing.rs | 89 ++++++++- 22 files changed, 829 insertions(+), 206 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index cc10985fc16..921f9972b72 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -2049,9 +2049,10 @@ impl<'p, 'a> Comb<'p, 'a> { Ok(store) } // A timing control suspends a process; this lowering has none. - sv::ir::Stmt::Delay { .. } | sv::ir::Stmt::WaitEvent(_) | sv::ir::Stmt::Wait(_) => { - Err(unsupported("procedural timing control")) - } + sv::ir::Stmt::Delay { .. } + | sv::ir::Stmt::WaitEvent(_) + | sv::ir::Stmt::WaitImplicit(_) + | sv::ir::Stmt::Wait(_) => Err(unsupported("procedural timing control")), sv::ir::Stmt::Local { name, init } => { let id = self .m diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index ad0ca48546b..3d57c5e018e 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -2629,7 +2629,10 @@ impl<'p, 'a> Ff<'p, 'a> { fn exec(&mut self, stmt: &sv::ir::Stmt) -> Result { if matches!( stmt, - sv::ir::Stmt::Delay { .. } | sv::ir::Stmt::WaitEvent(_) | sv::ir::Stmt::Wait(_) + sv::ir::Stmt::Delay { .. } + | sv::ir::Stmt::WaitEvent(_) + | sv::ir::Stmt::WaitImplicit(_) + | sv::ir::Stmt::Wait(_) ) && (self.kernel.is_none() || self.active_calls.iter().any(|name| { self.m @@ -2676,6 +2679,10 @@ impl<'p, 'a> Ff<'p, 'a> { self.wait_event(items)?; Ok(true) } + sv::ir::Stmt::WaitImplicit(reads) => { + self.wait_implicit(reads)?; + Ok(true) + } sv::ir::Stmt::Wait(condition) => { self.wait_level(condition)?; Ok(true) @@ -4937,6 +4944,65 @@ impl Ff<'_, '_> { fn wait_event(&mut self, items: &[sv::ir::EventItem]) -> Result<(), sv::AnalyzerError> { let mut terms = Vec::new(); let mut samples = Vec::new(); + self.event_terms(items, &mut terms, &mut samples)?; + self.suspend_on(terms, samples) + } + + /// `@*` (IEEE 1800-2023 9.4.2.2): wait for a change of a variable that + /// `reads` read. The module variables are those a combinational + /// `always @*` is sensitive to, from the same analysis, so folded + /// branches and the defaults of omitted subroutine arguments count. A + /// process-local variable it reads is sampled like an operand of an + /// event expression. + fn wait_implicit(&mut self, reads: &[sv::ir::Stmt]) -> Result<(), sv::AnalyzerError> { + // The expressions of timing controls are not part of the event list. + let reads = without_timing_controls(reads); + let reads = reads.as_slice(); + let mut ids: Vec = self + .m + .implicit_reads(reads, false) + .into_iter() + .map(|atom| atom.id) + .collect(); + ids.sort_unstable(); + ids.dedup(); + let mut terms: Vec<_> = ids + .into_iter() + .map(|id| (id, CounterKind::Changes)) + .collect(); + let mut names = HashSet::default(); + for stmt in reads { + stmt.clone().visit_mut( + &mut |expr: &mut sv::ir::Expr| expr_idents(expr, &mut names), + &mut |_: &mut sv::ir::LValue| {}, + &mut |_: &mut String| {}, + ); + } + let mut locals: Vec = names + .into_iter() + .filter(|name| self.m.id(name).is_some_and(|id| self.m.is_hidden(id))) + .collect(); + locals.sort_unstable(); + let locals: Vec<_> = locals + .into_iter() + .map(|name| sv::ir::EventItem { + edge: sv::ir::EventEdge::Any, + expr: sv::ir::Expr::Ident(name), + }) + .collect(); + let mut samples = Vec::new(); + self.event_terms(&locals, &mut terms, &mut samples)?; + self.suspend_on(terms, samples) + } + + /// The counter terms of `items` and the samples the process takes of + /// their expressions before it suspends. + fn event_terms( + &mut self, + items: &[sv::ir::EventItem], + terms: &mut Vec<(SourceVarId, CounterKind)>, + samples: &mut Vec<(String, sv::ir::Expr)>, + ) -> Result<(), sv::AnalyzerError> { for item in items { let expr = self.propagate(&item.expr); let edge = match item.edge { @@ -4953,12 +5019,12 @@ impl Ff<'_, '_> { let id = match &expr { sv::ir::Expr::Ident(name) => match self.m.id(name) { Some(id) if !self.m.is_hidden(id) => id, - Some(_) => self.event_expression(&expr, &mut samples)?, + Some(_) => self.event_expression(&expr, samples)?, // A constant never changes. None if self.m.constants.contains_key(name) => continue, None => return Err(unsupported(format!("event expression `{name}`"))), }, - _ => self.event_expression(&expr, &mut samples)?, + _ => self.event_expression(&expr, samples)?, }; match item.edge { sv::ir::EventEdge::Any => terms.push((id, CounterKind::Changes)), @@ -4970,6 +5036,15 @@ impl Ff<'_, '_> { } } } + Ok(()) + } + + /// Suspend until one of `terms` counts, after taking `samples`. + fn suspend_on( + &mut self, + terms: Vec<(SourceVarId, CounterKind)>, + samples: Vec<(String, sv::ir::Expr)>, + ) -> Result<(), sv::AnalyzerError> { for (target, value) in samples { self.assign(&sv::ir::LValue::Ident(target), &value)?; } @@ -5217,12 +5292,68 @@ pub(super) struct KernelUnit { /// may not suspend. const LOOP_YIELD_BITS: usize = 16; +/// `stmts` without their delays, event controls and waits, at any depth. +fn without_timing_controls(stmts: &[sv::ir::Stmt]) -> Vec { + use sv::ir::Stmt; + stmts + .iter() + .filter(|stmt| { + !matches!( + stmt, + Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::WaitImplicit(_) | Stmt::Wait(_) + ) + }) + .map(|stmt| match stmt { + Stmt::If { + condition, + then_body, + else_body, + } => Stmt::If { + condition: condition.clone(), + then_body: without_timing_controls(then_body), + else_body: without_timing_controls(else_body), + }, + Stmt::Case { + kind, + selector, + items, + default, + } => Stmt::Case { + kind: *kind, + selector: selector.clone(), + items: items + .iter() + .map(|item| sv::ir::CaseItem { + labels: item.labels.clone(), + body: without_timing_controls(&item.body), + }) + .collect(), + default: default.as_deref().map(without_timing_controls), + }, + Stmt::Loop { + kind, + init, + condition, + step, + body, + } => Stmt::Loop { + kind: kind.clone(), + init: without_timing_controls(init), + condition: condition.clone(), + step: without_timing_controls(step), + body: without_timing_controls(body), + }, + stmt => stmt.clone(), + }) + .collect() +} + /// Whether every pass through `stmts` suspends the process. fn always_suspends(stmts: &[sv::ir::Stmt]) -> bool { stmts.iter().any(|stmt| { matches!( stmt, - sv::ir::Stmt::Delay { .. } | sv::ir::Stmt::WaitEvent(_) + sv::ir::Stmt::Delay { .. } | sv::ir::Stmt::WaitEvent(_) | sv::ir::Stmt::WaitImplicit(_) ) }) } @@ -5336,6 +5467,7 @@ fn impure_call(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option { sv::ir::Stmt::SystemTask { .. } | sv::ir::Stmt::Delay { .. } | sv::ir::Stmt::WaitEvent(_) + | sv::ir::Stmt::WaitImplicit(_) | sv::ir::Stmt::Wait(_) => effect = true, _ => {} }); diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 54a49321b97..71ab51281e9 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -349,6 +349,7 @@ impl<'a> ProcModule<'a> { stmt, sv::ir::Stmt::Delay { .. } | sv::ir::Stmt::WaitEvent(_) + | sv::ir::Stmt::WaitImplicit(_) | sv::ir::Stmt::Wait(_) | sv::ir::Stmt::Assign { nonblocking: true, diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 3d026b99fd7..7b61af634ae 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1300,7 +1300,7 @@ impl Module { } procedural::timed_tasks::classify( subroutines.iter().chain(imported.subroutines.iter()), - &comb_processes, + &mut comb_processes, &mut ff_processes, &mut initial_processes, )?; @@ -2254,6 +2254,9 @@ impl LValue { pub struct CombProcess { creation_order: usize, site: Option, + /// Where the procedure is written, for an `always @*` that becomes a + /// process when it calls a timed task. + process_site: Option, kind: CombProcessKind, condition: Option, assignments: Vec, @@ -2292,6 +2295,7 @@ impl CombProcess { Self { creation_order: 0, site: None, + process_site: None, sensitivity_body: Vec::new(), kind, condition, @@ -2304,6 +2308,7 @@ impl CombProcess { Self { creation_order: 0, site: None, + process_site: None, sensitivity_body: Vec::new(), kind, condition, diff --git a/crates/celox-sv-analyzer/src/ast/comb_process.rs b/crates/celox-sv-analyzer/src/ast/comb_process.rs index 23ac807196a..d958288a35a 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_process.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_process.rs @@ -38,10 +38,9 @@ pub(super) fn comb_processes_from_scope( )?; for process in &mut processes[start..] { process.creation_order = creation_order; - process.site = procedural::source_span( - syntax_tree.declarations().body_item(item.id).tokens, - syntax_tree, - ); + let tokens = syntax_tree.declarations().body_item(item.id).tokens; + process.site = procedural::source_span(tokens, syntax_tree); + process.process_site = procedural::process_site("always", tokens, syntax_tree); for assignment in &mut process.assignments { item.assignment(assignment); } diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 66c9f602e7e..0ddd4912b4f 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -1345,7 +1345,9 @@ impl Frame<'_> { // diagnostic belongs to the declaration, not to evaluation. Stmt::SystemTask { .. } => {} // A function has no timing controls (IEEE 1800-2023 13.4). - Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::Wait(_) => return None, + Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::WaitImplicit(_) | Stmt::Wait(_) => { + return None; + } Stmt::AssignConcat { .. } | Stmt::Call { .. } => return None, } Some(Flow::Next) diff --git a/crates/celox-sv-analyzer/src/ast/constants.rs b/crates/celox-sv-analyzer/src/ast/constants.rs index d78ed34fa7c..f915a50fdf3 100644 --- a/crates/celox-sv-analyzer/src/ast/constants.rs +++ b/crates/celox-sv-analyzer/src/ast/constants.rs @@ -118,6 +118,7 @@ pub(super) fn substitute_process_constants_with_parameter_literals( return CombProcess { creation_order: process.creation_order, site: process.site, + process_site: process.process_site, sensitivity_body, ..CombProcess::procedural(process.kind, condition, body) }; @@ -140,6 +141,7 @@ pub(super) fn substitute_process_constants_with_parameter_literals( ); result.creation_order = process.creation_order; result.site = process.site; + result.process_site = process.process_site; result.sensitivity_body = sensitivity_body; result } diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index dae02b92839..884c9ebcffe 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -611,6 +611,17 @@ impl Flow<'_> { } Ok(Exits::next(written)) } + // An `@*` samples what its statements read; they do not run. + Stmt::WaitImplicit(reads) => { + let mut exprs = Vec::new(); + for stmt in reads { + stmt.walk(&mut |stmt| exprs.extend(stmt_exprs(stmt))); + } + for expr in exprs { + self.read(expr, written)?; + } + Ok(Exits::next(written)) + } } } @@ -749,7 +760,8 @@ pub(super) fn stmt_exprs(stmt: &Stmt) -> Vec<&Expr> { Stmt::Local { init, .. } => init.iter().collect(), Stmt::Delay { amount: expr, .. } | Stmt::Wait(expr) => vec![expr], Stmt::WaitEvent(items) => items.iter().map(|item| &item.expr).collect(), - Stmt::Break | Stmt::Continue => Vec::new(), + // The statements of an `@*` describe its reads and do not run. + Stmt::WaitImplicit(_) | Stmt::Break | Stmt::Continue => Vec::new(), } } diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs b/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs index 58bfe2b180a..76e37f3c563 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs @@ -3,7 +3,7 @@ use super::*; pub(in crate::ast) fn classify<'a>( subroutines: impl Iterator, - comb: &[CombProcess], + comb: &mut Vec, ff: &mut Vec, processes: &mut Vec, ) -> Result<(), AnalyzerError> { @@ -86,11 +86,59 @@ pub(in crate::ast) fn classify<'a>( )); } } - if comb.iter().any(|process| suspends(&process.body, &timed)) { - return Err(unsupported("timed task call in a combinational process")); - } let initial_count = processes.len(); let mut retained = Vec::new(); + for process in std::mem::take(comb) { + if !suspends(&process.body, &timed) { + if process.kind == CombProcessKind::AlwaysStar && assigns_nonblocking(&process.body) { + return Err(unsupported("nonblocking assignment inside always_comb")); + } + retained.push(process); + continue; + } + // An `always @*` is an ordinary `always` procedure (IEEE 1800-2023 + // 9.2.2.2.2): calling a timed task makes it a process that waits on + // its implicit event list before each run of its statement. + // `always_comb` and `always_latch` may not suspend (9.2.2.2). + let context = match process.kind { + CombProcessKind::AlwaysStar => None, + CombProcessKind::AlwaysLatch => Some("an always_latch body"), + CombProcessKind::AlwaysComb | CombProcessKind::ContinuousAssign => { + Some("an always_comb body") + } + }; + if let Some(context) = context { + return Err(AnalyzerError::TimingControlOutsideProcess { + construct: "timed task call", + context, + }); + } + // The frontend reads the wait's statements as it reads those of a + // combinational `always @*`, folded branches and the defaults of + // omitted arguments included. + let mut body = vec![timing::implicit_event( + &process.body, + &process.sensitivity_body, + )]; + body.extend(process.body); + processes.push(InitialProcess { + creation_order: process.creation_order, + site: process.process_site, + condition: process.condition, + body: vec![Stmt::Loop { + kind: LoopKind::Forever, + init: Vec::new(), + condition: None, + step: Vec::new(), + body, + }], + initializer: false, + synthetic: false, + repeats: true, + }); + } + *comb = retained; + let mut retained = Vec::new(); for process in std::mem::take(ff) { if !suspends(&process.body, &timed) { retained.push(process); @@ -141,7 +189,9 @@ fn suspends(body: &[Stmt], timed: &HashSet) -> bool { for statement in body { statement.walk(&mut |statement| { result |= match statement { - Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::Wait(_) => true, + Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::WaitImplicit(_) | Stmt::Wait(_) => { + true + } Stmt::Call { name, .. } => timed.contains(name), _ => false, }; @@ -149,3 +199,22 @@ fn suspends(body: &[Stmt], timed: &HashSet) -> bool { } result } + +fn assigns_nonblocking(body: &[Stmt]) -> bool { + let mut result = false; + for statement in body { + statement.walk(&mut |statement| { + result |= matches!( + statement, + Stmt::Assign { + nonblocking: true, + .. + } | Stmt::AssignConcat { + nonblocking: true, + .. + } + ); + }); + } + result +} diff --git a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs index 1389fa550f7..6820026a578 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timing.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timing.rs @@ -102,6 +102,7 @@ impl BodyBuilder<'_, '_, '_> { Ok(result) } ExprKind::Member { .. } => { + let delay = value; let mut parts = Vec::new(); loop { match &native.expression(value).kind { @@ -113,8 +114,10 @@ impl BodyBuilder<'_, '_, '_> { parts.push(instances::normalize_identifier(&name.spelling)); value = *expression; } + // A package-scoped identifier (A.6.5 delay_value, + // ps_identifier) is bound like any other value. ExprKind::Member { separator, .. } if separator == "::" => { - return Err(unsupported("package-scoped delay value")); + return self.native_value(delay); } ExprKind::Name(name) => { parts.push(instances::normalize_identifier(&name.spelling)); @@ -136,165 +139,9 @@ impl BodyBuilder<'_, '_, '_> { /// The wait of an `@*` that controls the statement lowered to `body`, with /// the branches constant folding removed from it in `removed`: an event of /// any change of each variable the statement reads (IEEE 1800-2023 -/// 9.4.2.2). That is every identifier in an expression, a subroutine -/// argument or a left-hand-side index, but not in a timing control (a -/// delay, wait or event control) and not an assignment target itself. Names that turn out not to -/// denote a variable, such as parameters, never change. +/// 9.4.2.2). The frontend reads the statements with the analysis that gives +/// a combinational `always @*` its sensitivity, so both count the same +/// reads, the defaults of omitted subroutine arguments included. pub(super) fn implicit_event(body: &[Stmt], removed: &[Stmt]) -> Stmt { - fn constant(expr: &ConstExpr, names: &mut Vec) { - match expr { - ConstExpr::Ident(name) => push(name, names), - ConstExpr::Literal(_) => {} - ConstExpr::Select { expr, bit } => { - constant(expr, names); - constant(bit, names); - } - ConstExpr::SelectRange { expr, msb, lsb, .. } => { - constant(expr, names); - constant(msb, names); - constant(lsb, names); - } - ConstExpr::Resize { expr, .. } | ConstExpr::Unary { expr, .. } => constant(expr, names), - ConstExpr::Function { args, .. } => args.iter().for_each(|arg| constant(arg, names)), - ConstExpr::Binary { left, right, .. } => { - constant(left, names); - constant(right, names); - } - ConstExpr::Mux { - condition, - then_expr, - else_expr, - } => { - constant(condition, names); - constant(then_expr, names); - constant(else_expr, names); - } - } - } - fn expression(expr: &Expr, names: &mut Vec) { - match expr { - Expr::Ident(name) => push(name, names), - Expr::Literal(_) => {} - Expr::Select { expr, msb, lsb, .. } => { - expression(expr, names); - constant(msb, names); - constant(lsb, names); - } - Expr::Concat(parts) => parts.iter().for_each(|part| expression(part, names)), - Expr::RepeatConcat { count, parts } => { - constant(count, names); - parts.iter().for_each(|part| expression(part, names)); - } - Expr::Resize { expr, .. } | Expr::Unary { expr, .. } => expression(expr, names), - Expr::Binary { left, right, .. } => { - expression(left, names); - expression(right, names); - } - Expr::Mux { - condition, - then_expr, - else_expr, - } => { - expression(condition, names); - expression(then_expr, names); - expression(else_expr, names); - } - // A function's own reads are not part of the event expression. - Expr::Call { args, .. } => args.iter().flatten().for_each(|arg| expression(arg, names)), - Expr::Inside { expr, items } => { - expression(expr, names); - for item in items { - item.exprs() - .into_iter() - .for_each(|operand| expression(operand, names)); - } - } - } - } - fn target(lvalue: &LValue, names: &mut Vec) { - if let LValue::Select { - msb, - lsb, - array_slice_width, - .. - } = lvalue - { - constant(msb, names); - constant(lsb, names); - if let Some(width) = array_slice_width { - constant(width, names); - } - } - } - fn push(name: &str, names: &mut Vec) { - if !names.iter().any(|known| known == name) { - names.push(name.to_string()); - } - } - let mut names = Vec::new(); - for stmt in body.iter().chain(removed) { - stmt.walk(&mut |stmt| match stmt { - Stmt::Assign { lhs, rhs, .. } => { - target(lhs, &mut names); - expression(rhs, &mut names); - } - Stmt::AssignConcat { parts, rhs, .. } => { - parts.iter().for_each(|part| target(part, &mut names)); - expression(rhs, &mut names); - } - Stmt::If { condition, .. } => expression(condition, &mut names), - Stmt::Case { - selector, items, .. - } => { - expression(selector, &mut names); - for label in items.iter().flat_map(|item| &item.labels) { - match label { - CaseLabel::Value(value) => expression(value, &mut names), - CaseLabel::Range { low, high } => { - expression(low, &mut names); - expression(high, &mut names); - } - } - } - } - Stmt::Loop { - kind, condition, .. - } => { - if let LoopKind::Repeat(count) = kind { - expression(count, &mut names); - } - if let Some(condition) = condition { - expression(condition, &mut names); - } - } - Stmt::Return(value) => value.iter().for_each(|value| expression(value, &mut names)), - Stmt::Call { args, .. } => args - .iter() - .flatten() - .for_each(|arg| expression(arg, &mut names)), - Stmt::Eval(expr) => expression(expr, &mut names), - Stmt::SystemTask { args, .. } => { - for arg in args { - if let SystemTaskArg::Expr(expr) = arg { - expression(expr, &mut names); - } - } - } - Stmt::Local { init, .. } => init.iter().for_each(|init| expression(init, &mut names)), - Stmt::Break - | Stmt::Continue - | Stmt::Delay { .. } - | Stmt::WaitEvent(_) - | Stmt::Wait(_) => {} - }); - } - Stmt::WaitEvent( - names - .into_iter() - .map(|name| EventItemBase { - edge: EventEdge::Any, - expr: Expr::Ident(name), - }) - .collect(), - ) + Stmt::WaitImplicit(body.iter().chain(removed).cloned().collect()) } diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 1ccf521aeb4..629730d0fc0 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -131,9 +131,12 @@ fn validate_procedure( while let Some(id) = pending.pop() { let statement = native.statement(id); match &statement.kind { + // A plain `always @*` that calls a timed task runs as a process, + // which may assign nonblocking; timed task classification + // rejects the assignment in one that stays combinational. StatementKind::Assignment { nonblocking: true, .. - } if kind == AlwaysKind::Comb => { + } if kind == AlwaysKind::Comb && procedure.kind != ProcedureKind::Always => { return Err(unsupported( if procedure.kind == ProcedureKind::AlwaysLatch { "nonblocking assignment inside always_latch" diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index b9822da6e37..16d579a9d31 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -114,6 +114,12 @@ pub enum StmtBase { /// `@(items)`: suspend the process until one of the events occurs /// (9.4.2). WaitEvent(Vec>), + /// `@*` (9.4.2.2): suspend the process until a variable that the + /// statements read changes. They are the statements the control covers, + /// branches that constant folding removed included, and only describe + /// the reads: they do not execute here, and [`StmtBase::walk`] does not + /// visit them. + WaitImplicit(Vec>), /// `wait (condition)`: suspend the process until the condition is true /// (9.4.3). Wait(E), @@ -343,6 +349,7 @@ impl StmtBase { .collect(), ), StmtBase::Wait(condition) => StmtBase::Wait(fe(condition)), + StmtBase::WaitImplicit(reads) => StmtBase::WaitImplicit(body(reads, fe, fl)), } } @@ -455,6 +462,7 @@ impl StmtBase { } } StmtBase::Wait(condition) => fe(condition), + StmtBase::WaitImplicit(reads) => body(reads, fe, fl, fname), } } diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index dcc648cb2c5..94015a571ce 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -3591,25 +3591,30 @@ fn implicit_event_controls_wait_on_the_reads_of_their_statement() { initial forever @* begin if (c > 0) y = a; else y = b; z[i] = 1; @(d); #(d); end\n\ endmodule"; let ir = analyze_source(code, Path::new("implicit.sv")).expect("`@*` in a process"); - let mut waits = Vec::new(); + // The frontend reads the statements of an `@*` with the analysis that + // gives a combinational `always @*` its sensitivity; the analyzer keeps + // the statements the control covers. + let mut implicit = Vec::new(); + let mut explicit = Vec::new(); for process in ir.modules()[0].initial_processes() { for stmt in process.body() { - stmt.walk(&mut |stmt| { - if let ir::Stmt::WaitEvent(items) = stmt { - waits.push( - items - .iter() - .map(|item| match &item.expr { - ir::Expr::Ident(name) => name.clone(), - expr => panic!("unexpected event expression {expr:?}"), - }) - .collect::>(), - ); - } + stmt.walk(&mut |stmt| match stmt { + ir::Stmt::WaitImplicit(reads) => implicit.push(!reads.is_empty()), + ir::Stmt::WaitEvent(items) => explicit.push( + items + .iter() + .map(|item| match &item.expr { + ir::Expr::Ident(name) => name.clone(), + expr => panic!("unexpected event expression {expr:?}"), + }) + .collect::>(), + ), + _ => {} }); } } - assert_eq!(waits, [vec!["c", "a", "b", "i"], vec!["d"]]); + assert_eq!(implicit, [true], "one @* over the statements of the block"); + assert_eq!(explicit, [vec!["d"]]); } #[test] @@ -6070,7 +6075,6 @@ fn native_system_task_arguments_preserve_strings_omissions_and_query_operands() fn timed_task_calls_require_a_suspendable_context() { for caller in [ "always_comb outer();", - "always @* outer();", "always_ff @(posedge clk) outer();", "function void f(); outer(); endfunction initial f();", ] { @@ -6084,6 +6088,15 @@ fn timed_task_calls_require_a_suspendable_context() { "{caller}: {error}" ); } + // A plain `always @*` is an ordinary always procedure: the call makes it + // a process (IEEE 1800-2023 9.2.2.2.2). + let ir = analyze_source( + "module Top; task automatic pause(); #1; endtask task automatic outer(); pause(); endtask always @* outer(); endmodule", + Path::new("timed_task_star.sv"), + ) + .unwrap(); + assert!(ir.modules()[0].comb_processes().is_empty()); + assert_eq!(ir.modules()[0].initial_processes().len(), 1); } #[test] diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 51e04377b4c..518436a082f 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -407,6 +407,32 @@ both checks in Verilator and passes in Icarus 13.0, which also passes the unchanged shared assertions. The [retained observation](verification/repros/process_nba_positions_verilator.json) records both failures; `--include-ignored` retains their assertions. +Verilator 5.052 schedules an `always @*` that calls a timed task differently +from its event control in `timing::always_star_timed_task_calls_run_as_processes`: +the call for `a = 5` at 3 ns writes `y` at 6 ns instead of 5 ns, and in +`timing::always_star_timed_task_calls_assign_nonblocking` a nonblocking update +after the task's 1 ns delay lands at 2 ns instead of 3 ns. A standalone +probe also shows it rerunning the call for a change made while the task was +suspended and for variables only the task body reads. IEEE 1800-2023 9.4.2.2 +makes the implicit event list the variables the statement reads, and 9.4.2 +waits only for changes after the event control is reached. Icarus 13.0 passes +the unchanged shared assertions. + +IEEE 1800-2023 9.4.2.2 defines the event list of an `always @*` by the +identifiers that appear in its statement, so a branch that constant folding +removes still contributes, and Celox's combinational and process `always @*` +count it, with the reads of the defaults of omitted arguments. Icarus 13.0 +leaves the folded branch out in +`timing::always_star_timed_task_calls_wait_on_folded_branch_reads`. Verilator +5.052 leaves out both the folded branch and the default of a nested call in +`timing::always_star_timed_task_calls_wait_on_nested_call_defaults`, and runs +the process at time zero; Icarus passes the nested-default case. + +Icarus 13.0 reports a syntax error for an unparenthesized package-scoped delay +value (`#delays::D;`) in `timing::package_scoped_delay_values_wait_their_value`; +IEEE 1800-2023 A.6.5 permits a `ps_identifier` as a `delay_value`. Verilator +passes the case. + Verilator 5.052 repeats activation of the self-reading latch in `latch::guarded_activation`, producing 3 where one `seed`/`en` change should produce 1. The [adapter-free reproduction](verification/repros/latch_activation.sv) diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 6700235ed25..500208661ae 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -1211,6 +1211,128 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev (run_until 7) (assert_eq count 1) (run_until 8) (assert_eq count 2)) +; A plain `always @*` that calls a timed task runs as a process (IEEE +; 1800-2023 9.2.2.2.2): its event list is the variables its statement +; reads, including the task's arguments but not what the task body reads +; (9.4.2.2), and it waits for one of them to change before each run. +(case always_star_timed_task_calls_run_as_processes + (source "star_tasks.sv" #" + module Top(output logic [7:0] y, z, w); + logic [7:0] a = 8'd0, b = 8'd0; + logic [7:0] y_r = 8'd0, z_r = 8'd0, w_r = 8'd0; + task automatic delayed(input logic [7:0] v); + #2 y_r = v; + endtask + task automatic mark(input logic [7:0] v); + #1 w_r = v; + endtask + always @* delayed(a); + always @* begin z_r = b; mark(b); end + initial begin + #3 a = 8'd5; + b = 8'd1; + #3 a = 8'd7; + end + assign y = y_r; + assign z = z_r; + assign w = w_r; + endmodule + "#) + (top Top) + (run_until 3) (assert_eq y 0) (assert_eq z 1) (assert_eq w 0) + (run_until 4) (assert_eq w 1) (assert_eq y 0) + (run_until 5) (assert_eq y 5 "the task resumes two units after a changed") + (run_until 7) (assert_eq y 5) + (run_until 8) (assert_eq y 7)) + +; Such a process may assign nonblocking, as any `always` process may. +(case always_star_timed_task_calls_assign_nonblocking + (source "star_task_nba.sv" #" + module Top(output logic [7:0] q); + logic [7:0] d = 8'd0, q_r = 8'd0; + task automatic pause(); + #1; + endtask + always @* begin + pause(); + q_r <= d; + end + initial #2 d = 8'd5; + assign q = q_r; + endmodule + "#) + (top Top) + (run_until 2) (assert_eq q 0) + (run_until 3) (assert_eq q 5 "the update follows the task's delay")) + +; The event list of such a process comes from the analysis that gives a +; combinational `always @*` its sensitivity: it counts what the defaults of +; omitted arguments read, of calls nested in arguments too. +(case always_star_timed_task_calls_wait_on_nested_call_defaults + (source "star_nested_default.sv" #" + module Top(output logic [7:0] y); + logic [7:0] a = 8'd0, y_r = 8'd0; + function automatic logic [7:0] pick(input logic [7:0] v = a); + return v; + endfunction + task automatic delayed(input logic [7:0] v); + #1 y_r = v; + endtask + always @* delayed(pick()); + initial #2 a = 8'd5; + assign y = y_r; + endmodule + "#) + (top Top) + (run_until 2) (assert_eq y 0) + (run_until 3) (assert_eq y 5 "a change of what pick's default reads wakes the process")) + +; It counts the reads of branches that constant folding removed, as the +; syntactic event list does (IEEE 1800-2023 9.4.2.2). +(case always_star_timed_task_calls_wait_on_folded_branch_reads + (source "star_folded_default.sv" #" + module Top(output logic [7:0] y); + logic [7:0] a = 8'd0, b = 8'd1, y_r = 8'd0; + task automatic delayed(input logic [7:0] v = a); + #1 y_r = v; + endtask + always @* begin + if (0) delayed(); + delayed(b); + end + initial #2 a = 8'd5; + assign y = y_r; + endmodule + "#) + (top Top) + (run_until 2) (assert_eq y 0) + (run_until 3) (assert_eq y 1 "a change of what a folded call's default reads wakes the process")) + +; A package-scoped identifier is a delay value (IEEE 1800-2023 A.6.5, +; ps_identifier), with or without parentheses. +(case package_scoped_delay_values_wait_their_value + (source "package_delays.sv" #" + package delays; + parameter int D = 3; + localparam int E = 2; + endpackage + module Top(output int at_d, at_e, at_paren); + initial begin + at_d = 0; at_e = 0; at_paren = 0; + #delays::D; + at_d = 1; + #delays::E; + at_e = 1; + #(delays::D) at_paren = 1; + end + endmodule + "#) + (top Top) + (run_until 2) (assert_eq at_d 0) + (run_until 3) (assert_eq at_d 1) (assert_eq at_e 0) + (run_until 5) (assert_eq at_e 1) (assert_eq at_paren 0) + (run_until 8) (assert_eq at_paren 1)) + (case timed_task_four_state_storage_survives_suspension (four_state) diff --git a/crates/celox-test-suite/verification/sv/icarus/timing.json b/crates/celox-test-suite/verification/sv/icarus/timing.json index ebe8418ed61..0a0b6efdeb2 100644 --- a/crates/celox-test-suite/verification/sv/icarus/timing.json +++ b/crates/celox-test-suite/verification/sv/icarus/timing.json @@ -1333,6 +1333,85 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_run_as_processes", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_assign_nonblocking", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_wait_on_nested_call_defaults", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 leaves the reads of a branch that constant folding removes out of the event list of an always @*: a change of a, which the default of the call in `if (0) delayed();` reads, does not wake the process. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, so a constant-false branch still contributes. Celox's combinational and process always @* both count it.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_always_star_folded_branches", + "observed_version": "Icarus 13.0", + "phase": "execute", + "reason": "Icarus 13.0 leaves the reads of a branch that constant folding removes out of the event list of an always @*: a change of a, which the default of the call in `if (0) delayed();` reads, does not wake the process. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, so a constant-false branch still contributes. Celox's combinational and process always @* both count it.", + "upstream": [] + }, + "name": "timing::always_star_timed_task_calls_wait_on_folded_branch_reads", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Icarus 13.0 reports a syntax error for an unparenthesized package-scoped delay value such as #delays::D. IEEE 1800-2023 A.6.5 permits a ps_identifier as a delay_value. Verilator passes the case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_compile_limitation", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_package_delay_value", + "observed_version": "Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 reports a syntax error for an unparenthesized package-scoped delay value such as #delays::D. IEEE 1800-2023 A.6.5 permits a ps_identifier as a delay_value. Verilator passes the case.", + "upstream": [] + }, + "name": "timing::package_scoped_delay_values_wait_their_value", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index b9acfdf7286..a026da63bf5 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -2140,5 +2140,75 @@ "class::randomization_mode_bit_argument" ] } + }, + { + "id": "sv_verilator_always_star_timed_task", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052; Icarus 13.0", + "reason": "Verilator 5.052 schedules an always @* that calls a timed task differently from its event control: the task called for a = 5 at 3 ns writes y at 6 ns instead of 5 ns, a nonblocking update after the task's 1 ns delay lands at 2 ns instead of 3 ns, and a standalone probe shows it rerunning the call for a change made while the task was suspended and for variables only the task body reads. IEEE 1800-2023 9.4.2.2 makes the implicit event list the variables the statement reads, the task's arguments but not its body, and 9.4.2 waits only for changes after the event control is reached. Icarus passes the unchanged shared assertions.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "timing::always_star_timed_task_calls_run_as_processes", + "timing::always_star_timed_task_calls_assign_nonblocking" + ] + } + }, + { + "id": "sv_icarus_package_delay_value", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 reports a syntax error for an unparenthesized package-scoped delay value such as #delays::D. IEEE 1800-2023 A.6.5 permits a ps_identifier as a delay_value. Verilator passes the case.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "timing::package_scoped_delay_values_wait_their_value" + ] + } + }, + { + "id": "sv_icarus_always_star_folded_branches", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Icarus 13.0", + "reason": "Icarus 13.0 leaves the reads of a branch that constant folding removes out of the event list of an always @*: a change of a, which the default of the call in `if (0) delayed();` reads, does not wake the process. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, so a constant-false branch still contributes. Celox's combinational and process always @* both count it.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "timing::always_star_timed_task_calls_wait_on_folded_branch_reads" + ] + } + }, + { + "id": "sv_verilator_always_star_implicit_reads", + "category": "simulator_disagreement", + "phase": "execute", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "reason": "Verilator 5.052 builds the event list of an always @* that calls a timed task without the reads of the defaults of omitted arguments of nested calls, so a change of a does not wake `always @* delayed(pick())` with `pick(input v = a)`, and without the reads of a branch that constant folding removes; it also runs the process at time zero. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, a constant-false branch included, and 9.4.2 waits for a change. Icarus passes the nested-default case.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "verilator": [ + "timing::always_star_timed_task_calls_wait_on_nested_call_defaults", + "timing::always_star_timed_task_calls_wait_on_folded_branch_reads" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index 52658fffaa6..fd6bb918a35 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -7,9 +7,9 @@ "passed": 0, "rejected": 0, "unexpected_accept": 1, - "mismatch": 16, + "mismatch": 17, "emission_error": 0, - "compile_error": 119, + "compile_error": 120, "runtime_error": 8, "unsupported": 0, "ignored": 0 @@ -1343,6 +1343,22 @@ "name": "class::methods_called_through_interface_class_handles", "phase": "compile", "status": "compile_error" + }, + { + "category": "Sequential", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:9: syntax error\n/source_0.sv:9: error: Malformed statement\n/source_0.sv:11: syntax error\n/source_0.sv:11: error: Malformed statement\n", + "expectation": "Simulation", + "name": "timing::package_scoped_delay_values_wait_their_value", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Sequential", + "detail": "timing::always_star_timed_task_calls_wait_on_folded_branch_reads at 1309:17: assert_eq y: expected 0x1, got 0x0 (a change of what a folded call's default reads wakes the process)", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_wait_on_folded_branch_reads", + "phase": "execute", + "status": "mismatch" } ] } diff --git a/crates/celox-test-suite/verification/sv/limitations/verilator.json b/crates/celox-test-suite/verification/sv/limitations/verilator.json index a18b6d80f40..baf0c215a6a 100644 --- a/crates/celox-test-suite/verification/sv/limitations/verilator.json +++ b/crates/celox-test-suite/verification/sv/limitations/verilator.json @@ -7,7 +7,7 @@ "passed": 0, "rejected": 0, "unexpected_accept": 0, - "mismatch": 24, + "mismatch": 28, "emission_error": 0, "compile_error": 18, "runtime_error": 2, @@ -450,6 +450,38 @@ "name": "indexed_select::known_run_time_selects_stay_within_their_element", "phase": "execute", "status": "mismatch" + }, + { + "category": "Sequential", + "detail": "timing::always_star_timed_task_calls_run_as_processes at 1244:17: assert_eq y: expected 0x5, got 0x0 (the task resumes two units after a changed)", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_run_as_processes", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "Sequential", + "detail": "timing::always_star_timed_task_calls_assign_nonblocking at 1265:17: assert_eq q: expected 0x0, got 0x5", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_assign_nonblocking", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "Sequential", + "detail": "timing::always_star_timed_task_calls_wait_on_nested_call_defaults at 1288:17: assert_eq y: expected 0x5, got 0x0 (a change of what pick's default reads wakes the process)", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_wait_on_nested_call_defaults", + "phase": "execute", + "status": "mismatch" + }, + { + "category": "Sequential", + "detail": "timing::always_star_timed_task_calls_wait_on_folded_branch_reads at 1308:17: assert_eq y: expected 0x0, got 0x1", + "expectation": "Simulation", + "name": "timing::always_star_timed_task_calls_wait_on_folded_branch_reads", + "phase": "execute", + "status": "mismatch" } ] } diff --git a/crates/celox-test-suite/verification/sv/verilator/timing.json b/crates/celox-test-suite/verification/sv/verilator/timing.json index 35f824e434c..7c115851699 100644 --- a/crates/celox-test-suite/verification/sv/verilator/timing.json +++ b/crates/celox-test-suite/verification/sv/verilator/timing.json @@ -1469,6 +1469,109 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator 5.052 schedules an always @* that calls a timed task differently from its event control: the task called for a = 5 at 3 ns writes y at 6 ns instead of 5 ns, a nonblocking update after the task's 1 ns delay lands at 2 ns instead of 3 ns, and a standalone probe shows it rerunning the call for a change made while the task was suspended and for variables only the task body reads. IEEE 1800-2023 9.4.2.2 makes the implicit event list the variables the statement reads, the task's arguments but not its body, and 9.4.2 waits only for changes after the event control is reached. Icarus passes the unchanged shared assertions.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_always_star_timed_task", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052; Icarus 13.0", + "phase": "execute", + "reason": "Verilator 5.052 schedules an always @* that calls a timed task differently from its event control: the task called for a = 5 at 3 ns writes y at 6 ns instead of 5 ns, a nonblocking update after the task's 1 ns delay lands at 2 ns instead of 3 ns, and a standalone probe shows it rerunning the call for a change made while the task was suspended and for variables only the task body reads. IEEE 1800-2023 9.4.2.2 makes the implicit event list the variables the statement reads, the task's arguments but not its body, and 9.4.2 waits only for changes after the event control is reached. Icarus passes the unchanged shared assertions.", + "upstream": [] + }, + "name": "timing::always_star_timed_task_calls_run_as_processes", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator 5.052 schedules an always @* that calls a timed task differently from its event control: the task called for a = 5 at 3 ns writes y at 6 ns instead of 5 ns, a nonblocking update after the task's 1 ns delay lands at 2 ns instead of 3 ns, and a standalone probe shows it rerunning the call for a change made while the task was suspended and for variables only the task body reads. IEEE 1800-2023 9.4.2.2 makes the implicit event list the variables the statement reads, the task's arguments but not its body, and 9.4.2 waits only for changes after the event control is reached. Icarus passes the unchanged shared assertions.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_always_star_timed_task", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052; Icarus 13.0", + "phase": "execute", + "reason": "Verilator 5.052 schedules an always @* that calls a timed task differently from its event control: the task called for a = 5 at 3 ns writes y at 6 ns instead of 5 ns, a nonblocking update after the task's 1 ns delay lands at 2 ns instead of 3 ns, and a standalone probe shows it rerunning the call for a change made while the task was suspended and for variables only the task body reads. IEEE 1800-2023 9.4.2.2 makes the implicit event list the variables the statement reads, the task's arguments but not its body, and 9.4.2 waits only for changes after the event control is reached. Icarus passes the unchanged shared assertions.", + "upstream": [] + }, + "name": "timing::always_star_timed_task_calls_assign_nonblocking", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator 5.052 builds the event list of an always @* that calls a timed task without the reads of the defaults of omitted arguments of nested calls, so a change of a does not wake `always @* delayed(pick())` with `pick(input v = a)`, and without the reads of a branch that constant folding removes; it also runs the process at time zero. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, a constant-false branch included, and 9.4.2 waits for a change. Icarus passes the nested-default case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_always_star_implicit_reads", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "phase": "execute", + "reason": "Verilator 5.052 builds the event list of an always @* that calls a timed task without the reads of the defaults of omitted arguments of nested calls, so a change of a does not wake `always @* delayed(pick())` with `pick(input v = a)`, and without the reads of a branch that constant folding removes; it also runs the process at time zero. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, a constant-false branch included, and 9.4.2 waits for a change. Icarus passes the nested-default case.", + "upstream": [] + }, + "name": "timing::always_star_timed_task_calls_wait_on_nested_call_defaults", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "Verilator 5.052 builds the event list of an always @* that calls a timed task without the reads of the defaults of omitted arguments of nested calls, so a change of a does not wake `always @* delayed(pick())` with `pick(input v = a)`, and without the reads of a branch that constant folding removes; it also runs the process at time zero. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, a constant-false branch included, and 9.4.2 waits for a change. Icarus passes the nested-default case.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/verilator.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_verilator_always_star_implicit_reads", + "observed_version": "Verilator 5.052 2026-09-05 rev v5.052", + "phase": "execute", + "reason": "Verilator 5.052 builds the event list of an always @* that calls a timed task without the reads of the defaults of omitted arguments of nested calls, so a change of a does not wake `always @* delayed(pick())` with `pick(input v = a)`, and without the reads of a branch that constant folding removes; it also runs the process at time zero. IEEE 1800-2023 9.4.2.2 defines the implicit event list by the identifiers that appear in the statement, a constant-false branch included, and 9.4.2 waits for a change. Icarus passes the nested-default case.", + "upstream": [] + }, + "name": "timing::always_star_timed_task_calls_wait_on_folded_branch_reads", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Sequential", + "detail": "", + "expectation": "Simulation", + "name": "timing::package_scoped_delay_values_wait_their_value", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox/tests/frontends/systemverilog/synthesizable.rs b/crates/celox/tests/frontends/systemverilog/synthesizable.rs index b80ee583c0a..db5c6a7c056 100644 --- a/crates/celox/tests/frontends/systemverilog/synthesizable.rs +++ b/crates/celox/tests/frontends/systemverilog/synthesizable.rs @@ -171,7 +171,11 @@ fn task_timing_control_is_rejected() { .build_cranelift() .expect_err("a task with a delay must be rejected") .to_string(); - assert!(error.contains("Unsupported"), "{error}"); + // IEEE 1800-2023 9.2.2.2: always_comb may not suspend. + assert!( + error.contains("timed task call in an always_comb body"), + "{error}" + ); } #[test] diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index b3916379346..83bcaca0f58 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -55,6 +55,11 @@ timed_cases! { fn timed_task_nested_copyback_wait_and_return = "timing::timed_task_nested_copyback_wait_and_return"; fn timed_task_static_formals_remain_shared = "timing::timed_task_static_formals_remain_shared"; fn timed_task_in_edge_always_rearms_after_return = "timing::timed_task_in_edge_always_rearms_after_return"; + fn always_star_timed_task_calls_run_as_processes = "timing::always_star_timed_task_calls_run_as_processes"; + fn always_star_timed_task_calls_assign_nonblocking = "timing::always_star_timed_task_calls_assign_nonblocking"; + fn always_star_timed_task_calls_wait_on_nested_call_defaults = "timing::always_star_timed_task_calls_wait_on_nested_call_defaults"; + fn always_star_timed_task_calls_wait_on_folded_branch_reads = "timing::always_star_timed_task_calls_wait_on_folded_branch_reads"; + fn package_scoped_delay_values_wait_their_value = "timing::package_scoped_delay_values_wait_their_value"; fn time_calls_in_child_port_subroutines = "timing::time_calls_in_child_port_subroutines"; fn time_calls_in_child_port_actuals = "timing::time_calls_in_child_port_actuals"; fn time_literal_delays_accept_all_units = "timing::time_literal_delays_accept_all_units"; @@ -491,12 +496,6 @@ fn unimplemented_timing_features_are_rejected() { "always_ff event control", 88, ), - // #1710 - ( - "bit q; task t(); #1 q = 1; endtask always @* t();", - "timed task call in a combinational process", - 88, - ), ] { let source = format!("module Top; {body} endmodule"); let error = celox::Simulation::from_sv_sources( @@ -571,6 +570,14 @@ fn timing_controls_outside_suspendable_processes_are_rejected() { "bit a; function automatic bit f(); #1; return a; endfunction", "delay control in a function", ), + ( + "bit q; task t(); #1 q = 1; endtask always_comb t();", + "timed task call in an always_comb body", + ), + ( + "bit q, e; task t(); #1 q = 1; endtask always_latch if (e) t();", + "timed task call in an always_latch body", + ), ] { let source = format!("module Top; {body} endmodule"); let error = celox::Simulation::from_sv_sources( @@ -585,6 +592,76 @@ fn timing_controls_outside_suspendable_processes_are_rejected() { } } +/// The default of an omitted task argument is read by the call, so an +/// `always @*` that calls the task waits on what the default reads, as for a +/// combinational `always @*`. Icarus 13.0 agrees; Verilator 5.052 does not +/// wake the process. +#[test] +fn always_star_timed_task_calls_wait_on_omitted_argument_defaults() { + let source = r#" + module Top(output logic [7:0] y); + timeunit 1ns / 1ns; + logic [7:0] a = 8'd0; + logic [7:0] y_r = 8'd0; + task automatic delayed(input logic [7:0] v = a); + #1 y_r = v; + endtask + always @* delayed(); + initial #2 a = 8'd5; + assign y = y_r; + endmodule + "#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("star_default.sv"))], + "Top", + ) + .build() + .unwrap(); + sim.run_until(2).unwrap(); + assert_eq!(sim.get(sim.signal("y")), 0u8.into()); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(sim.signal("y")), 5u8.into()); +} + +/// An `always @*` that is still in a timed task when a variable of its event +/// list changes misses the change: its event control waits only for changes +/// after it is reached again (IEEE 1800-2023 9.4.2). Icarus 13.0 agrees; +/// Verilator 5.052 reruns the call for the missed change. +#[test] +fn always_star_timed_task_calls_miss_changes_while_suspended() { + let source = r#" + module Top(output logic [7:0] y); + timeunit 1ns / 1ns; + logic [7:0] a = 8'd0; + logic [7:0] y_r = 8'd0; + task automatic delayed(input logic [7:0] v); + #2 y_r = v + 8'd1; + endtask + always @* delayed(a); + initial begin + #1 a = 8'd5; + #1 a = 8'd6; + #5 a = 8'd7; + end + assign y = y_r; + endmodule + "#; + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("star_missed.sv"))], + "Top", + ) + .build() + .unwrap(); + sim.run_until(6).unwrap(); + assert_eq!( + sim.get(sim.signal("y")), + 6u8.into(), + "a = 6 came while suspended" + ); + sim.run_until(10).unwrap(); + assert_eq!(sim.get(sim.signal("y")), 8u8.into()); +} + /// A nonblocking site stages its value (`NbaSite::pending`) only if its /// target has no other writer and nothing observes the order of the /// updates in the NBA region: no wait reads the target, directly or through From 88acb3b350663791fcc0ef7763da1671d3826ac5 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 17:32:47 +0900 Subject: [PATCH 2/4] docs(sv): describe always @* timed task calls and package delay values Change-Id: I63e21eb628046b097fc69220dc1a63f1e148b286 --- docs/guide/systemverilog-reference.md | 12 +++++++----- docs/ja/guide/systemverilog-reference.md | 10 +++++----- 2 files changed, 12 insertions(+), 10 deletions(-) diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index af7fea78edf..c4f7756f189 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -50,7 +50,7 @@ In a timed `Simulation`, `initial` and plain `always` processes can suspend: | Control | Supported | | --- | --- | -| `#delay` | integral and real delays, `#(min:typ:max)` (the typical value) and [time literals](#time-literal-delays); an X or Z delay counts as zero | +| `#delay` | integral and real delays, `#(min:typ:max)` (the typical value), package-scoped values such as `#pkg::D`, and [time literals](#time-literal-delays); an X or Z delay counts as zero | | `@(...)` | variables, `posedge` / `negedge` / `edge`, items joined by `or` or `,`, bit, part and run-time index selects, any expression including calls of pure functions, and `@*` / `@(*)`, which waits on the variables its statement reads | | `wait (condition)` | any condition; an X or Z condition counts as false | | Assignments | blocking and nonblocking, to any target a blocking assignment takes, including unpacked array elements and run-time positions; nonblocking updates take effect in the NBA region of the time slot, at the position evaluated when the assignment executes, and bits outside the target or at a position with an X or Z bit are not written | @@ -78,8 +78,11 @@ An `initial` or ordinary `always` process can call tasks containing `#delay`, `@(event)` and `wait (condition)`, including through nested tasks. Calls are inlined into the caller's resumable state machine. A normal edge-sensitive `always` that calls a timed task waits for that task to return before rearming -its event control. Functions, `always_comb` and `always_ff` cannot call a timed -task, and `always @*` cannot yet ([#1710](https://github.com/celox-sim/celox/issues/1710)). +its event control. An `always @*` that calls a timed task runs as a process +too: it waits for a change of a variable its statement reads, the task's +arguments among them but not what the task body reads, and misses changes +while the task is suspended. Functions, `always_comb`, `always_latch` and +`always_ff` cannot call a timed task. Automatic task arguments and locals have separate storage for each activation and survive suspension. Module-local static task arguments remain shared. Inputs and inouts @@ -173,8 +176,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), named events and `->`, `fork` / `join`, `wait fork` / `disable fork`, concurrent assertions, `force` / `release`. - Timing controls in processes: `iff` qualifiers ([#1444](https://github.com/celox-sim/celox/issues/1444)), - package-scoped delay values - ([#1710](https://github.com/celox-sim/celox/issues/1710)), impure function calls in event expressions, and + impure function calls in event expressions, and `wait` or event expressions reading a static task argument. - Nonblocking assignments inside `always_latch` ([#431](https://github.com/celox-sim/celox/issues/431)); use blocking assignments for the supported latch subset. - Inferred latches inside `always_comb` are rejected by default. Set `inferred_latch = "warn"` or `"allow"` in `celox.toml` under `[diagnostics]` to permit retained blocking assignments. Ordinary `always @*` and explicit `always_latch` do not require this option. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index c10c355185b..187b9710432 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -49,7 +49,7 @@ outline: [2, 3] | 制御 | 対応範囲 | | --- | --- | -| `#delay` | 整数と実数の遅延、`#(min:typ:max)`(typ の値)、[時間リテラル](#time-literal-delays)。X / Z の遅延は 0 として扱う | +| `#delay` | 整数と実数の遅延、`#(min:typ:max)`(typ の値)、`#pkg::D` のような package スコープの値、[時間リテラル](#time-literal-delays)。X / Z の遅延は 0 として扱う | | `@(...)` | 変数、`posedge` / `negedge` / `edge`、`or` または `,` で並べた項目、ビット選択・部分選択・実行時添字の選択、pure な関数呼び出しを含む任意の式、文が読む変数を待つ `@*` / `@(*)` | | `wait (condition)` | 任意の条件。X / Z の条件は偽として扱う | | 代入 | ブロッキング代入とノンブロッキング代入。代入先はブロッキング代入と同じで、unpacked 配列の要素や実行時に決まる位置も使えます。ノンブロッキング代入は代入を実行した時点で評価した位置に、そのタイムスロットの NBA 領域で反映します。代入先の範囲外のビットと、X や Z のビットを含む位置には書き込みません | @@ -73,8 +73,9 @@ outline: [2, 3] `initial` と通常の `always` から、`#delay`・`@(event)`・`wait (condition)` を 含む task を呼び出せます。task のネストも可能です。呼び出しは呼び出し元の状態機械に インライン展開されます。エッジ待ちの `always` は task の完了後に次のエッジを待ちます。 -function・`always_comb`・`always_ff` からの時間待ち task 呼び出しは拒否します。 -`always @*` からの呼び出しも現在は拒否します([#1710](https://github.com/celox-sim/celox/issues/1710))。 +時間待ち task を呼ぶ `always @*` もプロセスとして実行します。文が読む変数(task の引数を含み、 +task 本体が読む変数は含まない)の変化を待ち、task の実行中に起きた変化は見送ります。 +function・`always_comb`・`always_latch`・`always_ff` からの時間待ち task 呼び出しは拒否します。 automatic な引数とローカル変数は呼び出しごとに独立し、中断中も保持されます。 module 内の static task の引数は共有されます。input/inout は呼び出し時にコピーされ、output/inout は @@ -157,8 +158,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 - 振る舞い記述・検証向けの構文:`final`、代入内のタイミング制御(`a = #1 b`)、遅延付き継続代入([#444](https://github.com/celox-sim/celox/issues/444))、 named event と `->`、`fork` / `join`、`wait fork` / `disable fork`、並行アサーション、`force` / `release`。 - プロセス内のタイミング制御:`iff` 修飾([#1444](https://github.com/celox-sim/celox/issues/1444))、 - package スコープの遅延値 - ([#1710](https://github.com/celox-sim/celox/issues/1710))、イベント式内の impure な関数呼び出し、 + イベント式内の impure な関数呼び出し、 static task 引数を読む `wait` 条件とイベント式。 - `always_latch` 内のノンブロッキング代入([#431](https://github.com/celox-sim/celox/issues/431))。対応するラッチではブロッキング代入を使用してください。 - `always_comb` の暗黙のラッチ推論はデフォルトで拒否します。`celox.toml` の `[diagnostics]` で `inferred_latch = "warn"` または `"allow"` を指定すると許可できます。通常の `always @*` と明示的な `always_latch` にはこの設定は不要です。 From 6b4296a8adcf05262d2ec941e5355d4c5010c973 Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 19:34:56 +0900 Subject: [PATCH 3/4] fix(sv): report %t in the smallest time precision of the design %t printed its value in the time unit of the calling scope. Without $timeformat, IEEE 1800-2023 20.4.3 (Table 20-3) reports it in the smallest time precision of the design, in which the simulation counts its time. The analyzer now scales each value a %t of a display, file output or severity task converts by its scope's ticks per time unit, as it does for $time; a scope whose unit is the global precision is unchanged. `#1.5` under `timescale 1ns/1ps then $display("%0t", $realtime) prints 1500, as Icarus and Verilator do, instead of 2. A string literal converts as its packed bytes and keeps any literal form; a signed value keeps its sign. A string variable has no time to report and is rejected instead of printing its storage handle. Fixes #1821 Change-Id: Ied354a869434803679f082169c0fdca8028a653f --- crates/celox-frontend-sv/src/lowering/comb.rs | 3 +- crates/celox-frontend-sv/src/lowering/ff.rs | 3 +- .../src/lowering/ff/file_io.rs | 3 +- .../src/lowering/procedural.rs | 73 +++++++++++++++ .../celox-sv-analyzer/src/ast/procedural.rs | 90 ++++++++++++++++++ .../src/sv/cases/system_functions.vtest | 67 ++++++++++++++ .../sv/icarus/system_functions.json | 44 +++++++++ .../sv/verilator/system_functions.json | 44 +++++++++ .../systemverilog/system_functions.rs | 92 +++++++++++++++++++ 9 files changed, 416 insertions(+), 3 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index cc10985fc16..1bafc3c0126 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3469,7 +3469,8 @@ impl<'p, 'a> Comb<'p, 'a> { } else { None }; - let (template, values) = system_task_template(self.m, &kind, args); + let (template, mut values) = system_task_template(self.m, &kind, args); + prepare_time_operands(self.m, template.as_deref(), &mut values)?; let mut captured = Vec::with_capacity(values.len()); let mut arg_widths = Vec::with_capacity(values.len()); let mut arg_signed = Vec::with_capacity(values.len()); diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index ad0ca48546b..b0c45b5c12a 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -2894,7 +2894,8 @@ impl<'p, 'a> Ff<'p, 'a> { } else { None }; - let (template, values) = system_task_template(self.m, &kind, args); + let (template, mut values) = system_task_template(self.m, &kind, args); + prepare_time_operands(self.m, template.as_deref(), &mut values)?; let mut regs = Vec::with_capacity(values.len()); let mut arg_widths = Vec::with_capacity(values.len()); let mut arg_signed = Vec::with_capacity(values.len()); diff --git a/crates/celox-frontend-sv/src/lowering/ff/file_io.rs b/crates/celox-frontend-sv/src/lowering/ff/file_io.rs index a84aed372a4..5cfba9fda9b 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/file_io.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/file_io.rs @@ -186,7 +186,8 @@ impl Ff<'_, '_> { SystemTask::Fdisplay(radix) | SystemTask::Fwrite(radix) => { let descriptor = self.file_io_arg(&args[0])?; let kind = SystemTaskKind::Print(RuntimeEventKind::Write, radix.letter()); - let (template, args) = system_task_template(self.m, &kind, &args[1..]); + let (template, mut args) = system_task_template(self.m, &kind, &args[1..]); + prepare_time_operands(self.m, template.as_deref(), &mut args)?; let mut values = vec![descriptor]; for arg in &args { values.push(self.file_io_arg(arg)?); diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 54a49321b97..bdaaeac36df 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -1250,6 +1250,79 @@ fn template_arguments(template: &str) -> usize { count } +/// Prepare each value that a `%t` of `template` converts. A system task +/// argument is self-determined (IEEE 1800-2023 11.6.1, 21.2.1), so the +/// operand of the analyzer's scaling `value * factor` keeps its own width +/// and signedness. A `string` value has no time value, and Celox would print +/// its storage handle: it is rejected, as Verilator rejects it, while Icarus +/// prints the conversion unformatted. +pub(super) fn prepare_time_operands( + module: &ProcModule<'_>, + template: Option<&str>, + values: &mut [sv::ir::SystemTaskArg], +) -> Result<(), sv::AnalyzerError> { + let Some(template) = template else { + return Ok(()); + }; + let mut chars = template.chars().peekable(); + let mut index = 0; + while let Some(ch) = chars.next() { + if ch != '%' { + continue; + } + while chars + .next_if(|ch| matches!(ch, '-' | '+' | ' ' | '#' | '0')) + .is_some() + {} + while chars.next_if(char::is_ascii_digit).is_some() {} + if chars.next_if_eq(&'.').is_some() { + while chars.next_if(char::is_ascii_digit).is_some() {} + } + let Some(spec) = chars.next() else { + break; + }; + if !"bBoOhHxXdDiIcCsStTeEfFgG".contains(spec) { + continue; + } + if matches!(spec, 't' | 'T') + && let Some(sv::ir::SystemTaskArg::Expr(expr)) = values.get_mut(index) + { + if module.expr_is_string(expr) { + return Err(unsupported("string operand of a %t conversion")); + } + // The analyzer scales a %t value as `value * factor`. + if let sv::ir::Expr::Binary { + left, + op: sv::ir::BinaryOp::Mul, + .. + } = expr + { + if module.expr_is_string(left) { + return Err(unsupported("string operand of a %t conversion")); + } + if module.expr_float_precision(left).is_none() + && let Some(width) = sv_expr_natural_width( + &module.typed_calls(left), + module.variables, + module.name_to_id, + module.constants, + module.parameter_types, + ) + { + let signed = module.expr_signed(left); + **left = sv::ir::Expr::Resize { + expr: left.clone(), + width, + signed, + }; + } + } + } + index += 1; + } + Ok(()) +} + /// The message template and value arguments of a system task: a leading /// string literal is the template. `$fatal` first takes a finish number. /// A `$display` or `$write` argument without a conversion of its own is diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 47c102a0582..f3eee42895d 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -1327,6 +1327,24 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { Ok(SystemTaskArg::Expr(value)) }) .collect::, AnalyzerError>>()?; + let mut args = args; + // A string literal that %t converts is bound as a value: the binder + // handles every literal form, triple quotes and escapes included. + let mut bind = |index: usize| -> Result, AnalyzerError> { + let Some(id) = arguments.get(index).and_then(|arg| arg.value) else { + return Ok(None); + }; + let mut value = + expression_binding::bind_value(id, declarations, self.tree, &self.dims, None)?; + self.rename_expr(&mut value); + Ok(Some(value)) + }; + scale_time_conversions( + task, + &mut args, + timescales::time_divisor(root, self.tree)?, + &mut bind, + )?; // Keep Veryl's assertion calls as calls: their message arguments // execute even on success, unlike an SV assertion's fail action. Ok(vec![Stmt::SystemTask { @@ -2866,6 +2884,78 @@ pub(super) fn process_site( }) } +/// `%t` reports a time value in the units of `$timeformat`, by default the +/// smallest time precision of the design (IEEE 1800-2023 20.4.3, Table 20-3), +/// in which the simulation counts its time. The value is in the time unit of +/// the calling scope, of which `ticks_per_unit` simulation time units make +/// one, so each value a `%t` of the template converts is scaled by it. +fn scale_time_conversions( + task: SystemTask, + args: &mut [SystemTaskArg], + ticks_per_unit: u64, + bind: &mut impl FnMut(usize) -> Result, AnalyzerError>, +) -> Result<(), AnalyzerError> { + if ticks_per_unit == 1 { + return Ok(()); + } + let template = match task { + SystemTask::Display(_) | SystemTask::Write(_) | SystemTask::Severity(_) => 0, + SystemTask::Fatal => usize::from(matches!(args.first(), Some(SystemTaskArg::Expr(_)))), + SystemTask::Fdisplay(_) + | SystemTask::Fwrite(_) + | SystemTask::Assert + | SystemTask::AssertContinue => 1, + _ => return Ok(()), + }; + let Some(SystemTaskArg::Str(text)) = args.get(template) else { + return Ok(()); + }; + // The conversions of the template, in the order they take arguments + // (21.2.1.2): flags, a width and a precision may precede each. + let mut conversions = Vec::new(); + let mut chars = text.chars().peekable(); + while let Some(ch) = chars.next() { + if ch != '%' { + continue; + } + while chars + .next_if(|ch| matches!(ch, '-' | '+' | ' ' | '#' | '0')) + .is_some() + {} + while chars.next_if(char::is_ascii_digit).is_some() {} + if chars.next_if_eq(&'.').is_some() { + while chars.next_if(char::is_ascii_digit).is_some() {} + } + if let Some(spec) = chars.next() + && "bBoOhHxXdDiIcCsStTeEfFgG".contains(spec) + { + conversions.push(spec); + } + } + for (offset, spec) in conversions.into_iter().enumerate() { + if !matches!(spec, 't' | 'T') { + continue; + } + let index = template + 1 + offset; + // A string literal converts as its packed bytes (5.9). The factor is + // signed, so the product keeps the signedness of the value (11.8.1). + let value = match args.get(index) { + Some(SystemTaskArg::Expr(value)) => value.clone(), + Some(SystemTaskArg::Str(_)) => match bind(index)? { + Some(value) => value, + None => continue, + }, + Some(SystemTaskArg::Empty) | None => continue, + }; + args[index] = SystemTaskArg::Expr(Expr::Binary { + left: Box::new(value), + op: BinaryOp::Mul, + right: Box::new(Expr::Literal(format!("64'sd{ticks_per_unit}"))), + }); + } + Ok(()) +} + /// Original invocation span of a native token range, when it belongs to one file. pub(super) fn source_span( tokens: celox_sv_syntax::TokenRange, diff --git a/crates/celox-test-suite/src/sv/cases/system_functions.vtest b/crates/celox-test-suite/src/sv/cases/system_functions.vtest index 961efccc184..0990ccf7e9f 100644 --- a/crates/celox-test-suite/src/sv/cases/system_functions.vtest +++ b/crates/celox-test-suite/src/sv/cases/system_functions.vtest @@ -2386,6 +2386,7 @@ endmodule (case time_format_consumes_its_expression_argument (source "time_format.sv" #" +`timescale 1ns/1ns module Top(input logic clk); always_ff @(posedge clk) begin $display("t:[%t] d:[%d]", 32'd7, 8'shfe); @@ -2397,6 +2398,72 @@ endmodule (tick clk) (expect_output "t:[ 7] d:[ -2]\nsmall:[17] padded:[ 9] next:[af] %t\n")) +; Without `$timeformat`, %t reports a time in the smallest time precision of +; the design, in a field of 20 columns (IEEE 1800-2023 20.4.3, Table 20-3): +; a value in the time unit of its scope is scaled to it. Timed cases run at +; 1 ns / 1 ps. +(case time_format_defaults_to_the_smallest_precision + (source "time_format_default.sv" #" +module Top; + int n = 7; + initial begin + #1.5; + $display("[%t] [%0t] [%0t] [%0t] [%0d]", $time, $time, $realtime, n, $time); + $write("w=%0t\n", $realtime); + $finish; + end +endmodule +"#) + (top Top) + (run_to_finish) + (expect_output "[ 2000] [2000] [1500] [7000] [2]\nw=1500\n")) + +; The smallest precision of all the design's time scales sets the unit of +; %t in every scope. +(case time_format_scales_each_scope_to_the_smallest_precision + (source "time_format_scopes.sv" #" +`timescale 1ns/1ps +module Top(input logic clk); + Child child(.clk); + always_ff @(posedge clk) $display("top [%0t] [%t]", 32'd7, 8'd3); +endmodule +`timescale 1us/1us +module Child(input logic clk); + always_ff @(posedge clk) $display("child [%0t]", 32'd2); +endmodule +"#) + (top Top) + (tick clk) + (expect_output "top [7000] [ 3000]\nchild [2000000]\n")) + +; A string literal that %t converts is its packed bytes (IEEE 1800-2023 5.9), +; scaled like any other value. +(case time_format_scales_string_literals + (source "time_format_strings.sv" #" +`timescale 1ns/1ps +module Top(input logic clk); + always_ff @(posedge clk) $display("[%0t] [%t]", "A", "AB"); +endmodule +"#) + (top Top) + (tick clk) + (expect_output "[65000] [ 16706000]\n")) + +; A value that %t converts is self-determined (IEEE 1800-2023 11.6.1, 21.2.1): +; it is evaluated at its own width before it is scaled. +(case time_format_values_are_self_determined + (source "time_format_self_determined.sv" #" +`timescale 1ns/1ps +module Top(input logic clk); + logic [7:0] a = 8'hff; + logic [3:0] b = 4'd9, c = 4'd8; + always_ff @(posedge clk) $display("[%0t] [%0t] [%0t]", a + 8'd1, b + c, {b, c}); +endmodule +"#) + (top Top) + (tick clk) + (expect_output "[0] [1000] [152000]\n")) + (case string_literals_follow_numeric_format_specifiers (source "string_format.sv" #" module Top(input logic clk); diff --git a/crates/celox-test-suite/verification/sv/icarus/system_functions.json b/crates/celox-test-suite/verification/sv/icarus/system_functions.json index 341ab3ef479..eacfdc15b69 100644 --- a/crates/celox-test-suite/verification/sv/icarus/system_functions.json +++ b/crates/celox-test-suite/verification/sv/icarus/system_functions.json @@ -1575,6 +1575,50 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_defaults_to_the_smallest_precision", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_scales_each_scope_to_the_smallest_precision", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_scales_string_literals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_values_are_self_determined", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox-test-suite/verification/sv/verilator/system_functions.json b/crates/celox-test-suite/verification/sv/verilator/system_functions.json index 5f54ad2fe17..697545e7c70 100644 --- a/crates/celox-test-suite/verification/sv/verilator/system_functions.json +++ b/crates/celox-test-suite/verification/sv/verilator/system_functions.json @@ -876,6 +876,50 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_defaults_to_the_smallest_precision", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_scales_each_scope_to_the_smallest_precision", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_scales_string_literals", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Functions", + "detail": "", + "expectation": "Simulation", + "name": "system_functions::time_format_values_are_self_determined", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] } ] } diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index d7f08c6624c..280d9aebc2f 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -513,6 +513,10 @@ sv_backends! { fn character_formats_preserve_non_utf8_bytes(sim) { @case "system_functions::character_formats_preserve_non_utf8_bytes"; } fn time_format_consumes_its_expression_argument(sim) { @case "system_functions::time_format_consumes_its_expression_argument"; } + fn time_format_defaults_to_the_smallest_precision(sim) { @case "system_functions::time_format_defaults_to_the_smallest_precision"; } + fn time_format_scales_each_scope_to_the_smallest_precision(sim) { @case "system_functions::time_format_scales_each_scope_to_the_smallest_precision"; } + fn time_format_scales_string_literals(sim) { @case "system_functions::time_format_scales_string_literals"; } + fn time_format_values_are_self_determined(sim) { @case "system_functions::time_format_values_are_self_determined"; } fn string_literals_follow_numeric_format_specifiers(sim) { @case "system_functions::string_literals_follow_numeric_format_specifiers"; } // Veryl extension calls emitted unchanged into SV, not SV assert statements. fn veryl_assert_continue_ff_captures_arguments_before_reporting(sim) { @@ -3134,3 +3138,91 @@ fn scope_randomize_survives_all_optimization_levels() { } } } + +/// A signed value that %t converts keeps its sign when it is scaled to the +/// smallest time precision, as Icarus 13.0 prints it. Verilator 5.052 prints +/// the 32-bit pattern of an `int` as unsigned (4294967294000 for -2), so +/// this is no suite case. +#[test] +fn time_format_keeps_the_sign_of_signed_values() { + let source = r#" + `timescale 1ns/1ps + module Top(input logic go); + int n; + logic signed [7:0] s; + always_comb begin + n = -2; + s = -8'sd3; + if (go) $display("[%0t] [%0t]", n, s); + end + endmodule + "#; + let mut sim = Simulator::from_sv_sources(vec![(source, Path::new("signed_time.sv"))], "Top") + .build_cranelift() + .unwrap(); + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 0u8)).unwrap(); + sim.drain_runtime_events(); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + let messages: Vec<_> = sim + .drain_runtime_events() + .into_iter() + .map(|event| match event { + celox::RuntimeEvent::Display { message } => message, + event => panic!("unexpected event: {event:?}"), + }) + .collect(); + assert_eq!(messages, vec![b"[-2000] [-3000]".to_vec()]); +} + +/// A triple-quoted string literal that %t converts is its packed bytes too +/// (IEEE 1800-2023 5.9), scaled like any other value. Verilator 5.052 prints +/// 65000; Icarus 13.0 cannot parse triple-quoted literals, so this is no +/// suite case. +#[test] +fn time_format_scales_triple_quoted_literals() { + let source = r#" + `timescale 1ns/1ps + module Top(input logic go); + always_comb if (go) $display("[%0t]", """A"""); + endmodule + "#; + let mut sim = Simulator::from_sv_sources(vec![(source, Path::new("triple_time.sv"))], "Top") + .build_cranelift() + .unwrap(); + let go = sim.signal("go"); + sim.modify(|io| io.set(go, 0u8)).unwrap(); + sim.drain_runtime_events(); + sim.modify(|io| io.set(go, 1u8)).unwrap(); + let messages: Vec<_> = sim + .drain_runtime_events() + .into_iter() + .map(|event| match event { + celox::RuntimeEvent::Display { message } => message, + event => panic!("unexpected event: {event:?}"), + }) + .collect(); + assert_eq!(messages, vec![b"[65000]".to_vec()]); +} + +/// A `string` value has no time to report: %t of one is rejected rather than +/// printing its storage handle. Verilator 5.052 rejects it too ("format of +/// '%t' illegal with non-numeric argument"); Icarus 13.0 prints the +/// conversion unformatted. +#[test] +fn time_format_rejects_string_operands() { + for timescale in ["`timescale 1ns/1ps", "`timescale 1ns/1ns"] { + let source = format!( + "{timescale}\nmodule Top(input logic go); string s = \"A\"; always_comb if (go) $display(\"[%0t]\", s); endmodule" + ); + let error = + Simulator::from_sv_sources(vec![(source.as_str(), Path::new("string_time.sv"))], "Top") + .build_cranelift() + .expect_err("a string %t operand must be rejected") + .to_string(); + assert!( + error.contains("string operand of a %t conversion"), + "{timescale}: {error}" + ); + } +} From f2c286d00341195c9b2da8f84247b0e7abc19eae Mon Sep 17 00:00:00 2001 From: tignear Date: Fri, 23 Oct 2026 19:34:56 +0900 Subject: [PATCH 4/4] docs(sv): describe the default %t unit Change-Id: Ia98f17bfaa1c302d8af5cbe9a143c2c42990face --- docs/guide/systemverilog-reference.md | 7 +++++++ docs/ja/guide/systemverilog-reference.md | 5 +++++ 2 files changed, 12 insertions(+) diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index af7fea78edf..f97975a8043 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -646,6 +646,13 @@ precision includes all declared precisions and directive precisions, even in uninstantiated definitions (3.14.3). Selected instance arrays and generate paths require elaborated hierarchy lookup and are currently rejected. +`%t` reports a time in the smallest time precision of the design, in a field +of 20 columns (IEEE 1800-2023 20.4.3): `$display("%0t", $realtime)` after +`#1.5` under `` `timescale 1ns/1ps`` prints `1500`. A design without time scales +uses the 1 ns / 1 ps defaults, so `%t` reports picoseconds there too. +`%t` of a `string` value, which has no time to report, is rejected, and +`$timeformat` is not supported. + `$printtimescale` displays the selected time scope in the IEEE 1800-2023 20.4.2 form, for example `Time scale of (Top.child) is 100ns / 10ps`. It accepts the current scope, a design-element argument, `$unit`, or `$root`, diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index c10c355185b..73c64b82611 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -520,6 +520,11 @@ interface型から解決します。generic interfaceポートとgenerate内の 変換時に精度を失う場合があります。checkpoint の復元後は復元した時刻を参照します。 +`%t` は時刻を設計全体で最も細かい時間精度の単位で、20 桁の欄に表示します(IEEE 1800-2023 20.4.3)。 +`` `timescale 1ns/1ps`` のもとで `#1.5` の後に `$display("%0t", $realtime)` を実行すると `1500` を表示します。 +時間スケールのない設計は既定の 1 ns / 1 ps を使うため、`%t` はやはりピコ秒で表示します。 +報告する時刻を持たない `string` の値に対する `%t` は拒否します。`$timeformat` には対応していません。 + `$printtimescale` は IEEE1800-2023 20.4.2 の形式で時刻スコープを表示します。 例: `Time scale of (Top.child) is 100ns / 10ps`。 引数なしの現在スコープ、design element、`$unit`、`$root` を指定でき、