diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index ac20aebb6cb..8e9f73a561d 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -157,6 +157,22 @@ pub enum AssertionDeferral { Final, } +/// How the host defers the events of a site (IEEE 1800-2023 16.4). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum DeferredSite { + /// A flush point of a process with deferred assertions (16.4.2): the + /// actions its queue holds are discarded. The events of this site are + /// not shown. + FlushPoint, + /// The action of a deferred assertion: its event waits in the queue of + /// the flush-point site `queue` of the same instance, numbered like the + /// sites of its module, until `region` of the time slot. + Action { + queue: u32, + region: AssertionDeferral, + }, +} + /// Which action block of an assertion issues a report. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] pub enum AssertionOutcome { @@ -191,6 +207,10 @@ pub struct RuntimeEventSite { /// The assertion whose action issues this report. #[serde(default)] pub assertion: Option, + /// How the host defers the events of this site, for the processes of + /// deferred assertions. + #[serde(default)] + pub deferred: Option, pub arg_widths: Vec, pub arg_signed: Vec, pub arg_is_string: Vec, @@ -1979,6 +1999,7 @@ mod tests { scope: None, location: None, assertion: None, + deferred: None, arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index b141ad8d532..a67dbcf8eb8 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -62,6 +62,9 @@ pub struct ProcessKernelBuilder { resume_blocks: Vec, /// The wait site whose resume point is being lowered. wait_site: Option, + /// The runtime event site the process reports at its flush points + /// (see [`Self::flush_deferred_at`]). + flush_site: Option, } impl ProcessKernelBuilder { @@ -78,9 +81,17 @@ impl ProcessKernelBuilder { }, resume_blocks: vec![start], wait_site: None, + flush_site: None, } } + /// Report runtime event site `site` whenever the process resumes from + /// an event control or a wait: a flush point of its deferred + /// assertions (IEEE 1800-2023 16.4.2). A resume after a delay is not. + pub fn flush_deferred_at(&mut self, site: u32) { + self.flush_site = Some(site); + } + /// The kernel's control slots, with [`ProcessSlots::const_delays`] set /// for the delays lowered so far. pub fn slots(&self) -> ProcessSlots { @@ -225,6 +236,12 @@ impl ProcessKernelBuilder { self.store_delay_constant(u64::from(site)); self.end(ProcessStatus::Pending); self.builder.switch_to_block(woken); + if let Some(site_id) = self.flush_site { + self.builder.emit(SIRInstruction::RuntimeEvent { + site_id, + args: Vec::new(), + }); + } } /// `wait (condition)` (IEEE 1800-2023 9.4.3) at wait site `site`: diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index aff5ec85d2c..258e3beaf76 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -3257,11 +3257,17 @@ fn relocate_units( } let mut runtime_event_site_map = HashMap::default(); let scope = elaborated_scope_name(root_name, path, expanded, indexed_instances); + let site_base = runtime_event_sites.len() as u32; for (local_site, site) in sim_module.runtime_event_sites.iter().enumerate() { let global_site = runtime_event_sites.len() as u32; runtime_event_site_map.insert(local_site as u32, global_site); let mut site = site.clone(); site.scope = Some(scope.clone()); + // A deferred action names the flush point of its process in the + // same instance. + if let Some(celox_design::DeferredSite::Action { queue, .. }) = &mut site.deferred { + *queue += site_base; + } runtime_event_sites.push(site); } diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index ecaee3626b9..9a4c532d84d 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3605,6 +3605,7 @@ impl<'p, 'a> Comb<'p, 'a> { scope: None, location: report_location(site), assertion: assertion_site.cloned(), + deferred: None, arg_widths, arg_signed, arg_is_string, diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 649d4c6c6a1..6058fabcc4a 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -17,7 +17,9 @@ mod strings; use super::procedural::*; use super::*; -use celox_design::{CounterKind, NbaPosition, NbaSite, SPARSE_WORKING_REGION, WaitSite}; +use celox_design::{ + CounterKind, DeferredSite, NbaPosition, NbaSite, SPARSE_WORKING_REGION, WaitSite, +}; use celox_frontend_core::process::{NBA_POSITION_WIDTH, ProcessKernelBuilder, ProcessKernelError}; use celox_sir::{RegisterId, RegisterType}; use celox_slt::SLTToSIRLowerer; @@ -92,6 +94,9 @@ pub(super) struct Ff<'p, 'a> { /// Whether a combinational process also reruns for occurrences of its /// inputs that left their value unchanged. input_occurrences: bool, + /// The flush-point site of a process with deferred assertions, whose + /// queue their actions wait in. + flush_site: Option, } fn stable(var_id: SourceVarId) -> Addr { @@ -147,9 +152,86 @@ impl<'p, 'a> Ff<'p, 'a> { nba_sites: Vec::new(), host_request_sites: Vec::new(), nba_switches: Vec::new(), + flush_site: None, } } + /// Whether `stmts`, or a subroutine they call, including in timing + /// controls and the defaults of omitted arguments, hold a deferred + /// assertion. + fn has_deferred_assertions( + &self, + stmts: &[sv::ir::Stmt], + visited: &mut HashSet, + ) -> bool { + let mut found = false; + let mut calls = Vec::new(); + for stmt in stmts { + stmt.walk(&mut |stmt| { + if let sv::ir::Stmt::SystemTask { + assertion: Some(assertion), + .. + } = stmt + && assertion.deferral != celox_design::AssertionDeferral::None + { + found = true; + } + stmt_calls(stmt, &mut calls); + // Timing controls evaluate their expressions too. + match stmt { + sv::ir::Stmt::Wait(condition) => collect_calls(condition, &mut calls), + sv::ir::Stmt::WaitEvent(items) => { + for item in items { + collect_calls(&item.expr, &mut calls); + } + } + sv::ir::Stmt::Delay { amount, .. } => collect_calls(amount, &mut calls), + _ => {} + } + }); + } + if found { + return true; + } + while let Some((callee, args)) = calls.pop() { + let sv::ir::Callee::Subroutine(name) = callee else { + continue; + }; + let Some(subroutine) = self.m.subroutine(&name).cloned() else { + continue; + }; + default_calls(&subroutine, &args, &mut calls); + if visited.insert(name) && self.has_deferred_assertions(&subroutine.body, visited) { + return true; + } + } + false + } + + /// For a process with deferred assertions, its flush-point site (IEEE + /// 1800-2023 16.4.2), whose queue their actions wait in. + fn deferred_flush_site(&mut self, body: &[sv::ir::Stmt]) -> Option { + if !self.has_deferred_assertions(body, &mut HashSet::default()) { + return None; + } + let site = self.m.event_site(RuntimeEventSite { + kind: RuntimeEventKind::Write, + template: None, + sizing: DisplaySizing::Ieee, + scope: None, + location: None, + assertion: None, + deferred: Some(DeferredSite::FlushPoint), + arg_widths: Vec::new(), + arg_signed: Vec::new(), + arg_is_string: Vec::new(), + arg_float_precision: Vec::new(), + arg_is_handle: Vec::new(), + }); + self.flush_site = Some(site); + Some(site) + } + /// Lower a combinational process that reruns only when an input value /// changed. Its inputs then need no occurrence counters, so the units /// that write them stay unchanged. @@ -3173,6 +3255,13 @@ impl<'p, 'a> Ff<'p, 'a> { _ => None, }; let event_kind = kind.event_kind(); + // The action of a deferred assertion waits in its process's queue + // until the assertion matures (IEEE 1800-2023 16.4.1). + let deferred = assertion_site + .map(|assertion| assertion.deferral) + .filter(|®ion| region != celox_design::AssertionDeferral::None) + .zip(self.flush_site) + .map(|(region, queue)| DeferredSite::Action { queue, region }); let site_id = self.m.event_site(RuntimeEventSite { kind: event_kind, template: template.clone(), @@ -3180,6 +3269,7 @@ impl<'p, 'a> Ff<'p, 'a> { scope: None, location: report_location(site), assertion: assertion_site.cloned(), + deferred, arg_widths, arg_signed, arg_is_string, @@ -3190,7 +3280,8 @@ impl<'p, 'a> Ff<'p, 'a> { site_id, args: regs, }); - if kind.is_fatal() { + // A deferred `$fatal` ends the simulation when it matures. + if kind.is_fatal() && deferred.is_none() { let code = self .m .runtime_error(template.unwrap_or_else(|| sv::ir::SystemTask::Fatal.to_string())); @@ -4272,6 +4363,13 @@ impl<'p, 'a> Ff<'p, 'a> { )); } } + // Each evaluation resumes the process from its event control. + if let Some(site_id) = self.deferred_flush_site(&body) { + self.b.emit(SIRInstruction::RuntimeEvent { + site_id, + args: Vec::new(), + }); + } if self.exec_block(&body)? { self.b.seal_block(SIRTerminator::Return); } @@ -4710,6 +4808,9 @@ impl Ff<'_, '_> { ) -> Result { self.process = process; let mut kernel = ProcessKernelBuilder::new(slots); + if let Some(site) = self.deferred_flush_site(body) { + kernel.flush_deferred_at(site); + } std::mem::swap(&mut self.b, kernel.builder()); self.kernel = Some(kernel); self.exec_block(body)?; diff --git a/crates/celox-frontend-veryl/src/lowering/ff.rs b/crates/celox-frontend-veryl/src/lowering/ff.rs index 4570dde39a2..474841588f8 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff.rs @@ -555,6 +555,7 @@ impl<'a> FfParser<'a> { scope: None, location: None, assertion: None, + deferred: None, arg_widths: value_args .iter() .map(|arg| self.get_expression_width(&arg.0)) diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs index f77095b9bd8..f3c50003647 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs @@ -103,6 +103,7 @@ fn register_comb_runtime_event_site<'a>( scope: None, location: None, assertion: None, + deferred: None, arg_widths: value_args .iter() .map(|arg| arg.0.comptime().r#type.total_width().unwrap_or(1)) diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index e0a5971e020..e94a57e8747 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -111,6 +111,7 @@ fn runtime_event_site_for_assert( scope: None, location: None, assertion: None, + deferred: None, arg_widths: value_args.iter().map(assert_arg_width).collect(), arg_signed: value_args .iter() diff --git a/crates/celox-runtime/src/simulation/host.rs b/crates/celox-runtime/src/simulation/host.rs index 206b2f1cdd0..5e31cbfa1c6 100644 --- a/crates/celox-runtime/src/simulation/host.rs +++ b/crates/celox-runtime/src/simulation/host.rs @@ -134,6 +134,15 @@ pub trait HostBoundary: UnitExecutor { self.finish_timed_step(timestamp); Ok(()) } + + /// Called after [`Self::try_finish_timed_step`] when the time slot + /// `timestamp` is over: no more work is due at that time. A step ends + /// before its slot does when a process waits for zero time. The + /// runtime's loop calls it; a host that has work here returns + /// [`CompiledSlots::None`] from [`Self::compiled_slots`]. + fn try_end_time_slot(&mut self, _timestamp: u64) -> Result<(), Halt> { + Ok(()) + } } /// How many time slots a compiled scheduler may run at once (see diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index 32c77cebfb0..e25822ae243 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -210,6 +210,11 @@ impl SimulationState { if executor.take_slot_writes() { self.host_pending = true; } + // The slot is over when nothing more is due at its time, host + // writes included. + if !self.host_pending && self.next_work_time() != Some(current_time) { + executor.try_end_time_slot(current_time)?; + } Ok(()) } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index adbf305d7f8..17604d9017c 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -1623,9 +1623,33 @@ fn assertion_failure(keyword: &str, site: Option) }] } -/// Attribute the severity tasks of an assertion's action block to it. Tasks -/// in subroutines the block calls are not attributed, and the tasks of a -/// nested assertion keep its own attribution. +/// Check the action of a deferred assertion: one subroutine call (IEEE +/// 1800-2023 16.4). Only display and severity tasks are supported, since +/// a user subroutine would run in the Reactive region and could wake +/// processes there. +fn deferred_action(body: &[Stmt]) -> Result<(), AnalyzerError> { + match body { + [] => Ok(()), + [ + Stmt::SystemTask { + task: + SystemTask::Display(_) + | SystemTask::Write(_) + | SystemTask::Severity(_) + | SystemTask::Fatal, + .. + }, + ] => Ok(()), + _ => Err(unsupported( + "deferred assertion action other than one display or severity task call", + )), + } +} + +/// Attribute the severity tasks of an assertion's action block to it, and +/// for a deferred assertion its display tasks, which wait in the same +/// queue. Tasks in subroutines the block calls are not attributed, and the +/// tasks of a nested assertion keep its own attribution. fn attribute_reports( body: &mut [Stmt], assertion: &celox_design::AssertionSite, @@ -1633,11 +1657,14 @@ fn attribute_reports( ) { for stmt in body { stmt.walk_mut(&mut |stmt| { + let deferred = assertion.deferral != celox_design::AssertionDeferral::None; if let Stmt::SystemTask { - task: SystemTask::Severity(_) | SystemTask::Fatal, + task, assertion: attributed @ None, .. } = stmt + && (matches!(task, SystemTask::Severity(_) | SystemTask::Fatal) + || deferred && matches!(task, SystemTask::Display(_) | SystemTask::Write(_))) { *attributed = Some(celox_design::AssertionSite { outcome, diff --git a/crates/celox-sv-analyzer/src/ast/procedural/control.rs b/crates/celox-sv-analyzer/src/ast/procedural/control.rs index a2f7748bf8b..a5d8c5c49c5 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/control.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/control.rs @@ -241,6 +241,10 @@ impl BodyBuilder<'_, '_, '_> { failure, } => { let condition = self.native_assertion_condition(keyword, header)?; + let celox_sv_syntax::AssertionHeader::Immediate { deferred, .. } = header + else { + unreachable!("matched an immediate header"); + }; let statement = native.statement(id); jobs.push(Job::AssertionThen { condition, @@ -255,7 +259,15 @@ impl BodyBuilder<'_, '_, '_> { "cover" => celox_design::AssertionDirective::Cover, _ => celox_design::AssertionDirective::Assert, }, - deferral: celox_design::AssertionDeferral::None, + deferral: match deferred { + None => celox_design::AssertionDeferral::None, + Some(celox_sv_syntax::AssertionDeferral::Zero) => { + celox_design::AssertionDeferral::Observed + } + Some(celox_sv_syntax::AssertionDeferral::Final) => { + celox_design::AssertionDeferral::Final + } + }, outcome: celox_design::AssertionOutcome::Fail, }, span: super::source_span(statement.tokens, self.tree), @@ -329,6 +341,10 @@ impl BodyBuilder<'_, '_, '_> { if let Some((keyword, span)) = default_failure { else_body = assertion_failure(&keyword, span); } + if assertion.deferral != celox_design::AssertionDeferral::None { + deferred_action(&then_body)?; + deferred_action(&else_body)?; + } attribute_reports( &mut then_body, &assertion, diff --git a/crates/celox-sv-analyzer/src/source_tree/tests/immediate_assertions.rs b/crates/celox-sv-analyzer/src/source_tree/tests/immediate_assertions.rs index d74fb4fa2f9..f7af1518363 100644 --- a/crates/celox-sv-analyzer/src/source_tree/tests/immediate_assertions.rs +++ b/crates/celox-sv-analyzer/src/source_tree/tests/immediate_assertions.rs @@ -37,8 +37,15 @@ fn assigned_literal(statements: &[Stmt]) -> &str { } #[test] fn native_immediate_and_deferred_predicate_operators_drive_real_conditions() { - for keyword in ["assert", "assume", "cover", "assert #0", "assume final"] { - let mut tree = parsed(&format!("{keyword}(a+1) y=1;")); + for (keyword, action) in [ + ("assert", "y=1;"), + ("assume", "y=1;"), + ("cover", "y=1;"), + // A deferred action is one subroutine call (IEEE 1800-2023 16.4). + ("assert #0", "$info(\"p\");"), + ("assume final", "$info(\"p\");"), + ] { + let mut tree = parsed(&format!("{keyword}(a+1) {action}")); subtract(&mut tree); let source = Source::from_syntax(&tree).unwrap(); let Stmt::If { condition, .. } = &source.modules()[0].initial_processes()[0].body()[0] @@ -132,7 +139,7 @@ fn native_assertion_default_failure_cover_and_else_only_actions_keep_contracts() #[test] fn native_assertion_header_and_action_roles_are_authoritative() { for change_deferral in [false, true] { - let mut tree = parsed("assert #0(a) y=1; else y=2;"); + let mut tree = parsed("assert(a) y=1; else y=2;"); for statement in &mut tree.declarations.statements { if let StatementKind::Assertion { header, success, .. @@ -148,6 +155,16 @@ fn native_assertion_header_and_action_roles_are_authoritative() { } } } + // The native header decides the deferral: a deferred action must be + // one subroutine call (IEEE 1800-2023 16.4). + if change_deferral { + let error = Source::from_syntax(&tree).unwrap_err(); + assert!( + error.to_string().contains("deferred assertion action"), + "{error}" + ); + continue; + } let source = Source::from_syntax(&tree).unwrap(); let Stmt::If { then_body, @@ -157,11 +174,7 @@ fn native_assertion_header_and_action_roles_are_authoritative() { else { panic!() }; - if change_deferral { - assert_eq!(assigned_literal(then_body), "1"); - } else { - assert!(then_body.is_empty()); - } + assert!(then_body.is_empty()); assert_eq!(assigned_literal(else_body), "2"); } } diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 7278978181c..7adfec4e3b5 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 35; +const CONTAINER_VERSION: u16 = 36; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index d176c7dc1e8..59740d44036 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -271,7 +271,13 @@ impl HostBoundary for Simulator { fn compiled_slots(&self) -> celox_runtime::CompiledSlots { use celox_runtime::CompiledSlots; - if self.frozen || !self.components.is_empty() || !self.backend.runs_compiled_scheduler() { + // Deferred assertions mature when a slot is over, which the + // runtime's loop tells apart from the end of a step. + if self.frozen + || !self.components.is_empty() + || self.deferred_assertions + || !self.backend.runs_compiled_scheduler() + { return CompiledSlots::None; } // Waveforms record, the heap collects and a slot observer looks at @@ -294,6 +300,12 @@ impl HostBoundary for Simulator { self.dump_unless_rewound(timestamp); } + /// Deferred assertions mature in the Observed and Postponed regions of + /// the slot (IEEE 1800-2023 16.4). + fn try_end_time_slot(&mut self, _timestamp: u64) -> Result<(), Halt> { + self.mature_deferred_assertions().map_err(Halt::Error) + } + fn try_finish_timed_step(&mut self, timestamp: u64) -> Result<(), Halt> { // The time slot is over: no kernel runs, and its updates are in // state memory. diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index dc7af3cc618..d70605ce91b 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -150,6 +150,9 @@ mod host { comb_observer_scratch: Vec, comb_observer_reads: crate::comb_activation::ObserverReads, pub(super) comb_observer_initial_eval: bool, + /// The design has deferred assertions, whose actions mature at the + /// end of each time slot. + pub(crate) deferred_assertions: bool, /// Identity of the state layout, computed on first checkpoint use. pub(super) checkpoint_fingerprint: std::sync::OnceLock, /// State objects as state files name them, built on first use. @@ -394,6 +397,21 @@ mod host { struct PendingRuntimeEvents { events: std::collections::VecDeque, missed: u64, + deferred: DeferredQueues, + } + + /// The actions of deferred assertions that wait in the queue of their + /// process until they mature (IEEE 1800-2023 16.4.1). + #[derive(Clone, Default)] + struct DeferredQueues { + /// How the events of each site are deferred, and whether the site is + /// fatal, by site id. Empty without deferred assertions. + sites: Vec>, + /// Waiting actions in issue order, with their queue and region. + waiting: Vec<(u32, celox_design::AssertionDeferral, RawRuntimeEvent)>, + /// Events lost to the ring since the last maturity, in a design with + /// fatal deferred actions: they may have held one. + missed: u64, } impl PendingRuntimeEvents { @@ -403,7 +421,65 @@ mod host { } } + /// Queue the event, unless it is the action of a deferred assertion, + /// which waits, or a flush point, which discards the actions waiting + /// in its queue (16.4.2). fn push(&mut self, event: RawRuntimeEvent, capacity: usize) { + if let RawRuntimeEvent::Event { site_id, .. } = &event + && let Some(Some((deferred, _))) = self.deferred.sites.get(*site_id) + { + let site = *site_id as u32; + match *deferred { + celox_design::DeferredSite::FlushPoint => { + self.deferred.waiting.retain(|&(queue, ..)| queue != site); + } + celox_design::DeferredSite::Action { queue, region } => { + self.deferred.waiting.push((queue, region, event)); + } + } + return; + } + if let RawRuntimeEvent::Missed { count } = event + && self + .deferred + .sites + .iter() + .flatten() + .any(|&(_, fatal)| fatal) + { + self.deferred.missed += count; + } + self.push_ready(event, capacity); + } + + /// The time slot ends: queue the waiting actions, those of the + /// Observed region (`#0`) before those of the Postponed region + /// (`final`), up to the first fatal one, which it returns, or + /// [`RawRuntimeEvent::Missed`] when events that may have been one were + /// lost. + fn mature(&mut self, capacity: usize) -> Option { + let waiting = std::mem::take(&mut self.deferred.waiting); + let missed = std::mem::take(&mut self.deferred.missed); + let fatal = (missed > 0).then_some(RawRuntimeEvent::Missed { count: missed }); + for region in [ + celox_design::AssertionDeferral::Observed, + celox_design::AssertionDeferral::Final, + ] { + for (_, _, event) in waiting.iter().filter(|(_, r, _)| *r == region) { + self.push_ready(event.clone(), capacity); + // The simulation ends at a fatal action: the actions + // after it do not run. + if let RawRuntimeEvent::Event { site_id, .. } = event + && let Some(Some((_, true))) = self.deferred.sites.get(*site_id) + { + return fatal.or_else(|| Some(event.clone())); + } + } + } + fatal + } + + fn push_ready(&mut self, event: RawRuntimeEvent, capacity: usize) { if let RawRuntimeEvent::Missed { count } = event { // Ring overwrite means every older pending record also lies // outside the latest `capacity` records of the combined stream. @@ -929,6 +1005,18 @@ mod host { &backend, &program.runtime_schema.comb_observers, ); + let sites = &program.runtime_schema.runtime_event_sites; + let deferred_sites = if sites.iter().any(|site| site.deferred.is_some()) { + sites + .iter() + .map(|site| { + site.deferred + .map(|deferred| (deferred, site.kind.is_fatal())) + }) + .collect() + } else { + Vec::new() + }; let mut sim = Self { backend, program, @@ -941,7 +1029,14 @@ mod host { handle_slots: Default::default(), heap_safepoints_blocked: false, file_io: Default::default(), - pending_host_events: Default::default(), + pending_host_events: Arc::new(std::sync::Mutex::new(PendingRuntimeEvents { + deferred: DeferredQueues { + sites: deferred_sites.clone(), + ..Default::default() + }, + ..Default::default() + })), + deferred_assertions: !deferred_sites.is_empty(), components: Default::default(), component_simulation: None, runtime_event_read_seq: Arc::new(AtomicU64::new(0)), @@ -1313,6 +1408,39 @@ mod host { self.host_watch.set_log(other.host_watch.log().to_vec()); } + /// The time slot ends: the actions of deferred assertions that their + /// process did not flush mature, `#0` before `final` (IEEE 1800-2023 + /// 16.4). A fatal one ends the simulation with an error. + pub(crate) fn mature_deferred_assertions(&mut self) -> Result<(), RuntimeErrorCode> { + if !self.deferred_assertions { + return Ok(()); + } + self.stash_runtime_events(); + let capacity = self.backend.layout().runtime_event_capacity; + let fatal = self.pending_host_events.lock().unwrap().mature(capacity); + if let Some(RawRuntimeEvent::Missed { count }) = fatal { + return Err(RuntimeErrorCode::Runtime { + message: format!( + "missed {count} runtime events, which may have held a deferred $fatal" + ), + signals: Vec::new(), + }); + } + let Some(RuntimeEvent::Report(report)) = fatal.and_then(|raw| { + render_raw_runtime_event( + raw, + &self.program.runtime_schema.runtime_event_sites, + RuntimeFormatContext::default(), + ) + }) else { + return Ok(()); + }; + Err(RuntimeErrorCode::Runtime { + message: message_diagnostic(&report.message), + signals: Vec::new(), + }) + } + /// Move the events in the backend's buffer to the queue that /// [`Self::drain_runtime_events`] reads. pub(crate) fn stash_runtime_events(&mut self) { @@ -1845,7 +1973,8 @@ mod host { fn fire(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { let result = self.fire_unit(event); self.heap_safepoint(); - result.and(self.take_heap_fault()) + result.and(self.take_heap_fault())?; + self.mature_deferred_assertions() } fn fire_unit(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { @@ -2006,6 +2135,9 @@ mod host { self.note_edge(Ok(outcome)) } + /// Settle the outcome of [`celox_runtime::run_edge`] or + /// [`celox_runtime::run_edges`], and mature the deferred assertions + /// they ran. fn note_edge( &mut self, outcome: Result, @@ -2027,7 +2159,8 @@ mod host { Err(celox_runtime::Halt::Finish | celox_runtime::Halt::Stop) => self.dirty = true, Err(celox_runtime::Halt::Error(error)) => return Err(error), } - Ok(()) + // The edges are a time slot, as a tick is. + self.mature_deferred_assertions() } /// A rising edge of `event`'s signal; see [`Self::edge`]. @@ -2231,6 +2364,7 @@ mod host { let result = self.tick_events_unit(&fired); self.heap_safepoint(); result.and(self.take_heap_fault())?; + self.mature_deferred_assertions()?; for &event in events { let info = self.event_edges[event.id()]; self.backend diff --git a/crates/celox/src/simulator/host/file_io.rs b/crates/celox/src/simulator/host/file_io.rs index 25d04c5ec96..55d2078f84c 100644 --- a/crates/celox/src/simulator/host/file_io.rs +++ b/crates/celox/src/simulator/host/file_io.rs @@ -103,6 +103,7 @@ impl Simulator { scope, location: None, assertion: None, + deferred: None, arg_widths: Vec::new(), arg_signed: Vec::new(), arg_is_string: Vec::new(), diff --git a/crates/celox/tests/native_simulation_image.rs b/crates/celox/tests/native_simulation_image.rs index aab956b1f94..491590fff87 100644 --- a/crates/celox/tests/native_simulation_image.rs +++ b/crates/celox/tests/native_simulation_image.rs @@ -241,3 +241,46 @@ endmodule let vcd = std::fs::read_to_string(&path).unwrap(); assert!(vcd.contains("b101"), "{vcd}"); } + +/// Deferred assertions keep their queue through the image: a glitch is +/// flushed, a lasting failure reports at the end of its slot. +#[test] +fn deferred_assertions_run_from_the_image() { + const DEFERRED: &str = r#"`timescale 1ns/1ns +module Top; + bit a, b; + initial forever begin + @(a or b); + d: assert #0 (a == b) else $error("d"); + end + initial begin + #1 a = 1; #0 b = 1; + #1 a = 0; + #1 $display("done"); + end +endmodule +"#; + let run = |sim: &mut Simulation<_>| { + sim.run_until(5).unwrap(); + sim.drain_runtime_events() + .into_iter() + .map(|event| match event { + RuntimeEvent::Report(report) => report.message, + RuntimeEvent::Display { message } => message, + event => panic!("unexpected event {event:?}"), + }) + .collect::>() + }; + let expected = run(&mut builder(DEFERRED).build_native().unwrap()); + assert_eq!(expected, vec![b"d".to_vec(), b"done".to_vec()]); + let image = reloaded( + &builder(DEFERRED) + .compile_native() + .unwrap() + .into_program_image(), + ); + let mut sim = Simulation::from_sv_sources(Vec::new(), "Top") + .build_native_from_image(image) + .unwrap(); + assert_eq!(run(&mut sim), expected); +} diff --git a/crates/celox/tests/sv_deferred_assertions.rs b/crates/celox/tests/sv_deferred_assertions.rs new file mode 100644 index 00000000000..a92d9a44e6f --- /dev/null +++ b/crates/celox/tests/sv_deferred_assertions.rs @@ -0,0 +1,304 @@ +#![cfg(feature = "systemverilog")] +//! The actions of deferred immediate assertions in processes wait in the +//! process's deferred assertion report queue: `#0` ones mature in the +//! Observed region, `final` ones in the Postponed region, and a flush point +//! of the process discards those still waiting (IEEE 1800-2023 16.4). +use celox::{AssertionDeferral, Report, RuntimeEvent, Severity}; +use std::path::Path; + +/// The reports and displays of `events`, as (label or message, deferral). +fn summary(events: Vec) -> Vec<(String, Option)> { + events + .into_iter() + .filter_map(|event| match event { + RuntimeEvent::Report(Report { + message, assertion, .. + }) => Some(( + String::from_utf8(message).unwrap(), + assertion.map(|assertion| assertion.deferral), + )), + RuntimeEvent::Display { message } => Some((String::from_utf8(message).unwrap(), None)), + _ => None, + }) + .collect() +} + +macro_rules! deferred { + ($module:ident, $backend:ident) => { + mod $module { + use super::*; + + fn simulation(body: &str) -> celox::Simulation { + let source = format!( + "`timescale 1ns/1ns\nmodule Top;\n bit a, b, c, x;\n{body}\nendmodule" + ); + celox::Simulation::from_sv_sources( + vec![(source.as_str(), Path::new("deferred.sv"))], + "Top", + ) + .$backend() + .unwrap() + } + + fn run(body: &str, time: u64) -> Vec<(String, Option)> { + let mut sim = simulation(body); + sim.run_until(time).unwrap(); + summary(sim.drain_runtime_events()) + } + + /// The first execution fails while `b` lags `a`; the process + /// resumes from its event control when `b` follows, which + /// flushes the failure. The immediate assertion reports it. + #[test] + fn an_event_control_resume_flushes_waiting_actions() { + assert_eq!( + run( + " initial forever begin\n \ + @(a or b);\n \ + i: assert (a == b) else $error(\"i\");\n \ + d: assert #0 (a == b) else $error(\"d\");\n \ + end\n \ + initial begin #1 a = 1; #0 b = 1; end", + 1 + ), + vec![("i".to_owned(), Some(AssertionDeferral::None))] + ); + } + + /// IEEE 1800-2023 16.4.2: an Observed region is reached after + /// `a3` and before the next flush point, so `a3` reports; `a4` + /// is flushed when `b` changes after it ran. + #[test] + fn a_delay_resume_is_no_flush_point() { + assert_eq!( + run( + " always @(a or b) begin\n \ + a3: assert #0 (a == b) else $error(\"a3\");\n \ + #1;\n \ + a4: assert #0 (a == b) else $error(\"a4\");\n \ + end\n \ + initial begin #1 a = 1; #1; #0 b = 1; end", + 3 + ), + vec![("a3".to_owned(), Some(AssertionDeferral::Observed))] + ); + } + + /// In one time slot, `$display` output comes first, then the + /// `#0` actions, then the `final` ones. + #[test] + fn observed_actions_mature_before_postponed_ones() { + assert_eq!( + run( + " initial begin\n \ + #1;\n \ + f: assert final (0) else $error(\"f\");\n \ + o: assert #0 (0) else $error(\"o\");\n \ + p: assert #0 (1) $display(\"p\");\n \ + $display(\"d\");\n \ + end", + 1 + ), + vec![ + ("d".to_owned(), None), + ("o".to_owned(), Some(AssertionDeferral::Observed)), + ("p".to_owned(), None), + ("f".to_owned(), Some(AssertionDeferral::Final)), + ] + ); + } + + /// Each evaluation of an edge-triggered process resumes it from + /// its event control: the second edge of a time slot flushes the + /// failure of the first. + #[test] + fn a_second_edge_flushes_a_flip_flop_process() { + let body = " always @(posedge c) o: assert #0 (x) else $error(\"o\");\n "; + assert_eq!( + run(&format!("{body}initial #1 c = 1;"), 1), + vec![("o".to_owned(), Some(AssertionDeferral::Observed))] + ); + assert_eq!( + run(&format!("{body}initial begin #1 c = 1; #0 c = 0; x = 1; #0 c = 1; end"), 1), + vec![] + ); + } + + /// A deferred `$fatal` ends the simulation when it matures, at + /// the end of its time slot. + #[test] + fn a_deferred_fatal_ends_the_simulation_when_it_matures() { + let mut sim = simulation( + " initial begin\n \ + #1;\n \ + f: assert final (0) else $fatal(1, \"boom\");\n \ + $display(\"after\");\n \ + end", + ); + assert!(sim.run_until(5).is_err()); + assert_eq!(sim.time(), 1); + let events = sim.drain_runtime_events(); + assert!(events.iter().any(|event| matches!( + event, + RuntimeEvent::Report(Report { severity: Severity::Fatal, message, .. }) + if message == b"boom" + )), "{events:?}"); + } + + /// A deferred assertion that only a `wait` condition reaches + /// still waits for the end of the slot. + #[test] + fn assertions_in_wait_conditions_are_deferred() { + assert_eq!( + run( + " function automatic bit check();\n \ + d: assert #0 (0) else $error(\"d\");\n \ + return 1;\n \ + endfunction\n \ + initial begin\n \ + #1;\n \ + wait (check());\n \ + $display(\"after\");\n \ + end", + 5 + ), + vec![ + ("after".to_owned(), None), + ("d".to_owned(), Some(AssertionDeferral::Observed)), + ] + ); + } + + /// The simulation ends at a deferred `$fatal`: the actions that + /// would mature after it, here in the Postponed region, do not + /// run. + #[test] + fn actions_after_a_deferred_fatal_do_not_mature() { + let mut sim = simulation( + " initial begin\n \ + #1;\n \ + assert #0 (0) else $fatal(1, \"boom\");\n \ + assert final (1) $display(\"after fatal\");\n \ + end", + ); + assert!(sim.run_until(5).is_err()); + assert_eq!( + summary(sim.drain_runtime_events()), + vec![("boom".to_owned(), Some(AssertionDeferral::Observed))] + ); + } + + /// A deferred assertion that only the default of an omitted + /// argument reaches still waits for the end of the slot. + #[test] + fn assertions_in_argument_defaults_are_deferred() { + assert_eq!( + run( + " function automatic bit check();\n \ + d: assert #0 (0) else $error(\"d\");\n \ + return 1;\n \ + endfunction\n \ + function automatic bit f(bit v = check());\n \ + return v;\n \ + endfunction\n \ + initial begin\n \ + #1;\n \ + x = f();\n \ + $display(\"after\");\n \ + end", + 5 + ), + vec![ + ("after".to_owned(), None), + ("d".to_owned(), Some(AssertionDeferral::Observed)), + ] + ); + } + + /// Events lost to a full event buffer may have held a deferred + /// `$fatal`, which then still ends the simulation. + #[test] + fn a_deferred_fatal_lost_to_the_event_buffer_ends_the_simulation() { + let mut sim = simulation( + " initial begin\n \ + #1;\n \ + f: assert final (0) else $fatal(1, \"boom\");\n \ + repeat (2000) $display(\"x\");\n \ + #1 $display(\"after\");\n \ + end", + ); + let error = sim.run_until(5).unwrap_err(); + assert!(error.to_string().contains("missed"), "{error}"); + assert_eq!(sim.time(), 1); + } + } + }; +} + +deferred!(interpreter, build_interpreter); +deferred!(cranelift, build); +#[cfg(target_arch = "x86_64")] +deferred!(native, build_native); +deferred!(wasm, build_wasm); + +/// A `Simulator` call is a time slot: a deferred assertion of a flip-flop +/// domain matures at the end of the tick that ran it. +#[test] +fn deferred_actions_mature_at_the_end_of_a_tick() { + let source = "module Top(input bit clk, input bit x);\n \ + always_ff @(posedge clk) o: assert #0 (x) else $error(\"o\");\n\ + endmodule"; + let mut sim = + celox::Simulator::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top") + .build() + .unwrap(); + let clk = sim.event("clk"); + sim.tick(clk).unwrap(); + assert_eq!( + summary(sim.drain_runtime_events()), + vec![("o".to_owned(), Some(AssertionDeferral::Observed))] + ); +} + +/// So is a call of the edge APIs that run derived domains, and of +/// `edges`: a later edge does not flush the actions of an earlier one. +#[test] +fn deferred_actions_mature_at_the_end_of_edges_and_derived_ticks() { + let source = "module Top(input bit clk, input bit x);\n \ + bit div;\n \ + always_ff @(posedge clk) div <= !div;\n \ + always_ff @(posedge clk) o: assert #0 (x) else $error(\"o\");\n \ + always_ff @(posedge div) d: assert #0 (x) else $error(\"d\");\n\ + endmodule"; + let mut sim = + celox::Simulator::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top") + .build() + .unwrap(); + let clk = sim.event("clk"); + for _ in 0..2 { + sim.edges(&[(clk, celox::Edge::Rising)]).unwrap(); + sim.edges(&[(clk, celox::Edge::Falling)]).unwrap(); + } + for _ in 0..4 { + sim.tick(clk).unwrap(); + } + let labels: Vec<_> = summary(sim.drain_runtime_events()) + .into_iter() + .map(|(label, _)| label) + .collect(); + assert_eq!(labels, ["o", "d", "o", "o", "d", "o", "o", "d", "o"]); +} + +#[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") + .build() + .unwrap_err(); + assert!( + error.to_string().contains("deferred assertion action"), + "{error}" + ); +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index d3c04e955ab..79e3ef8a4a5 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -623,6 +623,25 @@ host does at each callback, or the time step of the report while and the `celox` command print it. Only `$error` and `$fatal` fail a `celox` run; `$fatal` also ends the simulation with an error. +### Deferred assertions + +In an `initial` or `always` process with a timing control, and in an +edge-triggered `always` or `always_ff` process, the action of `assert #0`, +`assume #0`, `assert final` and `assume final` waits in the process's +deferred assertion report queue (IEEE 1800-2023 16.4). Its arguments are +evaluated when the assertion executes. The process flushes the queue each +time it resumes from an event control or a wait, and an edge-triggered +process each time it runs; a resume after a delay is no flush point +(16.4.2). When the time slot is over, the actions still waiting are +executed: those of `#0` ones first, then those of `final` ones. A deferred +`$fatal` ends the simulation then. An action is one display or severity +task call; a user subroutine, or more than one statement, is rejected. + +The same assertions in `always_comb`, `always_latch` or a process lowered as +combinational logic (an `always` whose only timing control is its leading +event control) still report at once, like simple immediate assertions. +Deferred assertions as module items and deferred cover are rejected. + ### Constant functions Constant functions ignore the display and severity tasks they call. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 7cd330ff86b..fec9ec48260 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -399,6 +399,22 @@ drain のコンテキストが与える時刻で、VPI ホストはコールバ VPI ホストと `celox` コマンドが表示する形に整形します。`celox` の実行を失敗にするのは `$error` と `$fatal` だけで、`$fatal` はさらにシミュレーションをエラーで終了します。 +### 遅延付きアサーション + +タイミング制御を含む `initial` / `always` プロセスと、エッジで起動する `always` / +`always_ff` プロセスでは、`assert #0`、`assume #0`、`assert final`、`assume final` の +アクションはプロセスの遅延アサーション報告キューで待ちます(IEEE 1800-2023 16.4)。 +引数はアサーションを実行した時点で評価します。プロセスはイベント制御や wait から再開する +たびに、エッジで起動するプロセスは実行するたびにキューをフラッシュします。遅延からの再開は +フラッシュ点ではありません(16.4.2)。タイムスロットが終わると、まだ待っているアクションを +`#0` のもの、`final` のものの順に実行します。遅延付きの `$fatal` はそこでシミュレーションを +終了します。アクションは表示タスクか重大度タスクの呼び出し 1 つで、ユーザーのサブルーチンや +複数の文は拒否します。 + +`always_comb`、`always_latch`、組み合わせ回路として扱うプロセス(タイミング制御が先頭の +イベント制御だけの `always`)の同じアサーションは、まだ単純な即時アサーションと同じく +その場で報告します。モジュール直下の遅延付きアサーションと遅延付きの cover は拒否します。 + ### 定数関数 定数関数は、呼び出す表示タスクと重大度タスクを無視します。