diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index c5e36c0a10e..ed9a71b7f0d 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -349,30 +349,30 @@ chapter-16/16.17--expect.sv 2state fail chapter-16/16.17--expect.sv 4state fail chapter-16/16.2--assert-final-uvm.sv 2state fail chapter-16/16.2--assert-final-uvm.sv 4state fail -chapter-16/16.2--assert-final.sv 2state fail -chapter-16/16.2--assert-final.sv 4state fail +chapter-16/16.2--assert-final.sv 2state pass +chapter-16/16.2--assert-final.sv 4state pass chapter-16/16.2--assert-uvm.sv 2state fail chapter-16/16.2--assert-uvm.sv 4state fail chapter-16/16.2--assert.sv 2state pass chapter-16/16.2--assert.sv 4state pass chapter-16/16.2--assert0-uvm.sv 2state fail chapter-16/16.2--assert0-uvm.sv 4state fail -chapter-16/16.2--assert0.sv 2state fail -chapter-16/16.2--assert0.sv 4state fail -chapter-16/16.2--assume-final.sv 2state fail -chapter-16/16.2--assume-final.sv 4state fail +chapter-16/16.2--assert0.sv 2state pass +chapter-16/16.2--assert0.sv 4state pass +chapter-16/16.2--assume-final.sv 2state pass +chapter-16/16.2--assume-final.sv 4state pass chapter-16/16.2--assume-uvm.sv 2state fail chapter-16/16.2--assume-uvm.sv 4state fail chapter-16/16.2--assume.sv 2state pass chapter-16/16.2--assume.sv 4state pass -chapter-16/16.2--assume0.sv 2state fail -chapter-16/16.2--assume0.sv 4state fail -chapter-16/16.2--cover-final.sv 2state fail -chapter-16/16.2--cover-final.sv 4state fail +chapter-16/16.2--assume0.sv 2state pass +chapter-16/16.2--assume0.sv 4state pass +chapter-16/16.2--cover-final.sv 2state pass +chapter-16/16.2--cover-final.sv 4state pass chapter-16/16.2--cover.sv 2state pass chapter-16/16.2--cover.sv 4state pass -chapter-16/16.2--cover0.sv 2state fail -chapter-16/16.2--cover0.sv 4state fail +chapter-16/16.2--cover0.sv 2state pass +chapter-16/16.2--cover0.sv 4state pass chapter-16/16.7--sequence-and-range-uvm.sv 2state fail chapter-16/16.7--sequence-and-range-uvm.sv 4state fail chapter-16/16.7--sequence-and-uvm.sv 2state fail diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index e96f8bbb7fb..f53a2af7176 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -4393,10 +4393,10 @@ fn build_comb_observer_capture_paths( | RuntimeEventKind::Finish | RuntimeEventKind::Stop ); - let fatal_error_code = sites[observer.site_id as usize] - .kind - .is_fatal() - .then_some(observer.site_id as i64); + // A deferred `$fatal` ends the simulation when it matures. + let fatal_error_code = (sites[observer.site_id as usize].kind.is_fatal() + && sites[observer.site_id as usize].deferred.is_none()) + .then_some(observer.site_id as i64); let pre_lower_nodes = observer_pre_lower_nodes(observer, arena); for idx in &order_after { comb_blocks[idx.0] @@ -4449,10 +4449,10 @@ fn build_comb_observer_capture_paths( | RuntimeEventKind::Finish | RuntimeEventKind::Stop ); - let member_fatal_error_code = sites[member.site_id as usize] - .kind - .is_fatal() - .then_some(member.site_id as i64); + // A deferred `$fatal` ends the simulation when it matures. + let member_fatal_error_code = (sites[member.site_id as usize].kind.is_fatal() + && sites[member.site_id as usize].deferred.is_none()) + .then_some(member.site_id as i64); let member_expr = match member .loop_runner .or(member.guard) diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 0202c7f5c14..f19eef919c5 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -4504,7 +4504,14 @@ pub(crate) fn attach_instance_glue( observer.activation_group += site_base; module.comb_observers.push(observer); } - module.runtime_event_sites.extend(comb_sites); + module + .runtime_event_sites + .extend(comb_sites.into_iter().map(|mut site| { + if let Some(celox_design::DeferredSite::Action { queue, .. }) = &mut site.deferred { + *queue += site_base; + } + site + })); for id in created { module .variables @@ -5219,6 +5226,12 @@ fn lower_comb_processes( .expect("a counter for every sensitivity atom") }) .collect(); + // A deferred action waits in the queue of its process. + if let Some(celox_design::DeferredSite::Action { queue, .. }) = + &mut comb.sites[(observer.site_id - base) as usize].deferred + { + *queue = base; + } observers.push(observer); } sites.append(&mut comb.sites); diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 9a4c532d84d..27fabd04104 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3581,6 +3581,15 @@ impl<'p, 'a> Comb<'p, 'a> { } self.effect_sensitivity.extend(observed.iter().copied()); let site_id = self.site_base + self.sites.len() as u32; + // The action of a deferred assertion waits in the queue of its + // process, which lowering names by the process's activation group + // (IEEE 1800-2023 16.4). A deferred `$fatal` ends the simulation + // when it matures, not while combinational logic settles. + let deferred = assertion_site + .map(|assertion| assertion.deferral) + .filter(|®ion| region != celox_design::AssertionDeferral::None) + .map(|region| celox_design::DeferredSite::Action { queue: 0, region }); + let fatal = kind.is_fatal() && deferred.is_none(); // Inside a run-time loop the event is emitted once per iteration by // the loop's runner (see `fold_loop`). let captured_in_loop = if let Some(effects) = &mut self.loop_effects { @@ -3592,7 +3601,7 @@ impl<'p, 'a> Comb<'p, 'a> { SystemTaskKind::Print(..) | SystemTaskKind::Control(_) ), args: captured.clone(), - fatal_error_code: kind.is_fatal().then_some(i64::from(site_id)), + fatal_error_code: fatal.then_some(i64::from(site_id)), }); true } else { @@ -3605,7 +3614,7 @@ impl<'p, 'a> Comb<'p, 'a> { scope: None, location: report_location(site), assertion: assertion_site.cloned(), - deferred: None, + deferred, 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 6058fabcc4a..692f14c3ff0 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -3951,6 +3951,7 @@ impl<'p, 'a> Ff<'p, 'a> { let width = self.m.var(id).width; self.targets.push((id, BitAccess::new(0, width - 1))); } + let flush_site = self.deferred_flush_site(body); if self.exec_block(body)? { self.b.seal_block(SIRTerminator::Return); } @@ -4112,6 +4113,13 @@ impl<'p, 'a> Ff<'p, 'a> { false_block: (done, vec![]), }); self.b.switch_to_block(execute); + // Each run is a resume of the process (IEEE 1800-2023 16.4.2). + if let Some(site_id) = flush_site { + self.b.emit(SIRInstruction::RuntimeEvent { + site_id, + args: Vec::new(), + }); + } self.b.inline_execution_unit(&body_unit); if !always_comb { // @* is not waiting during its body. Its own writes cannot wake diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index 19ffd8e1567..94ba20cf12e 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -137,6 +137,12 @@ pub trait SimBackend { None } fn set_comb_capture_event_enabled(&mut self, _active_sites: &[bool]) {} + /// Which runtime event sites are enabled for combinational capture, by + /// the host before an evaluation or by the evaluation for observers + /// whose inputs it changed. Empty for a backend without capture. + fn comb_capture_event_enabled(&self) -> Vec { + Vec::new() + } fn stable_region_size(&self) -> usize; fn layout(&self) -> &MemoryLayout; /// The heap that handle slots in this backend's state refer to. diff --git a/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs b/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs index d01cd58a92e..b149afc12cd 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/assertions.rs @@ -8,17 +8,9 @@ impl BodyBuilder<'_, '_, '_> { keyword: &str, header: &AssertionHeader, ) -> Result { - let AssertionHeader::Immediate { - condition, - deferred, - .. - } = header - else { + let AssertionHeader::Immediate { condition, .. } = header else { return Err(unsupported("concurrent assertion")); }; - if keyword == "cover" && deferred.is_some() { - return Err(unsupported("deferred immediate cover")); - } if !matches!(keyword, "assert" | "assume" | "cover") { return Err(unsupported("immediate assertion keyword")); } 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 f7af1518363..8475ff2012a 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 @@ -199,7 +199,7 @@ fn native_assertion_action_scopes_and_unsupported_classes_keep_existing_behavior }; assert_ne!(pass, fail); for (statement, diagnostic) in [ - ("cover #0(a);", "deferred immediate cover"), + ("cover #0(a) y=1;", "deferred assertion action"), ("assert property(a);", "concurrent assertion"), ] { let tree = parsed(statement); diff --git a/crates/celox-sv-analyzer/src/syntax.rs b/crates/celox-sv-analyzer/src/syntax.rs index c3607469349..9fde61ea7ba 100644 --- a/crates/celox-sv-analyzer/src/syntax.rs +++ b/crates/celox-sv-analyzer/src/syntax.rs @@ -172,17 +172,19 @@ mod tests { } #[test] - fn module_deferred_assertions_parse_but_require_execution_support() { + /// A deferred assertion as a module item is the same assertion in an + /// `always_comb` (IEEE 1800-2023 16.4.3), labeled or not. + fn module_deferred_assertions_are_always_comb_processes() { for keyword in ["assert", "assume", "cover"] { for deferral in ["#0", "final"] { - let code = format!("module M; logic a=1; {keyword} {deferral} (a!=0); endmodule"); - let path = Path::new("module-deferred.sv"); - parse_source(&code, path).unwrap(); - let error = crate::analyze_source(&code, path).unwrap_err(); - assert!( - matches!(error, AnalyzerError::Unsupported(ref reason) if reason == "module deferred immediate assertion"), - "{error}" - ); + for label in ["", "a1: "] { + let code = format!( + "module M; logic a=1; {label}{keyword} {deferral} (a!=0); endmodule" + ); + let path = Path::new("module-deferred.sv"); + parse_source(&code, path).unwrap(); + crate::analyze_source(&code, path).unwrap(); + } } } } diff --git a/crates/celox-sv-syntax/src/parser/declarations.rs b/crates/celox-sv-syntax/src/parser/declarations.rs index 9b16ce4c5fa..bdb35072461 100644 --- a/crates/celox-sv-syntax/src/parser/declarations.rs +++ b/crates/celox-sv-syntax/src/parser/declarations.rs @@ -781,16 +781,36 @@ impl Parser<'_> { frames.push(frame); continue; } + // A deferred immediate assertion as a module item is the same + // assertion in an `always_comb` (IEEE 1800-2023 16.4.3). + let deferred_assertion = |at: usize| { + matches!(self.nth(at), "assert" | "assume" | "cover") + && matches!(self.nth(at + 1), "#" | "final") + }; + // A module item, also in a generate region or block. + let static_deferred = frame.item_start + && frame.delimiters.is_empty() + && frame + .scopes + .iter() + .all(|scope| matches!(*scope, "endgenerate" | "end" | "endcase")) + && (deferred_assertion(0) || self.nth(1) == ":" && deferred_assertion(2)); if frame.item_start && frame.delimiters.is_empty() && !frame .scopes .iter() .any(|scope| matches!(*scope, "endproperty" | "endsequence")) - && matches!( - self.peek(), - "initial" | "always" | "always_comb" | "always_latch" | "always_ff" | "final" - ) + && (static_deferred + || matches!( + self.peek(), + "initial" + | "always" + | "always_comb" + | "always_latch" + | "always_ff" + | "final" + )) { let parameters = self.parameter_declarations.len(); let aliases = self.type_aliases.len(); @@ -798,7 +818,11 @@ impl Parser<'_> { let times = self.time_declarations.len(); let assigns = self.assign_statements.len(); let start = self.at; - let id = self.procedure()?; + let id = if static_deferred { + self.static_deferred_assertion()? + } else { + self.procedure()? + }; frame.unit.procedures.push(id); frame.record(self, start, BodyItemKind::Procedure(id))?; frame.unit.parameter_declarations.extend( diff --git a/crates/celox-sv-syntax/src/parser/procedures.rs b/crates/celox-sv-syntax/src/parser/procedures.rs index 7d872398e62..bd513df2ce0 100644 --- a/crates/celox-sv-syntax/src/parser/procedures.rs +++ b/crates/celox-sv-syntax/src/parser/procedures.rs @@ -137,6 +137,22 @@ impl Parser<'_> { Ok(id) } + /// A deferred immediate assertion as a module item: an `always_comb` + /// procedure whose body is the assertion (IEEE 1800-2023 16.4.3). + pub(super) fn static_deferred_assertion(&mut self) -> Result { + let start = self.at; + let body = self.statement_machine()?; + let id = ProcedureId(self.procedures.len()); + let authored_statements = self.body_membership(&[body]); + self.procedures.push(Procedure { + kind: ProcedureKind::AlwaysComb, + body, + authored_statements, + tokens: self.range(start), + }); + Ok(id) + } + /// Capture syntax ownership before execution graph transformations. This /// flat membership also keeps deeply nested scopes independent of Rust's /// call stack; opaque statement children remain their own captured scope. diff --git a/crates/celox-sv-syntax/src/parser/tests.rs b/crates/celox-sv-syntax/src/parser/tests.rs index 7372cf06afb..981c37f09f1 100644 --- a/crates/celox-sv-syntax/src/parser/tests.rs +++ b/crates/celox-sv-syntax/src/parser/tests.rs @@ -2799,14 +2799,20 @@ fn specparam_retains_its_body_item_boundary() { } #[test] -fn module_deferred_assertions_do_not_become_final_procedures() { +/// A deferred assertion as a module item is an `always_comb` procedure +/// (IEEE 1800-2023 16.4.3), never a `final` one. +fn module_deferred_assertions_become_always_comb_procedures() { for keyword in ["assert", "assume", "cover"] { for deferral in ["#0", "final"] { let native = parse(&format!("module M; {keyword} {deferral} (1); endmodule")); - assert!(native.procedures.is_empty()); - assert!( - matches!(&native.body_item(native.units[0].items[0]).kind, BodyItemKind::Unconverted { category, .. } if category == keyword) - ); + let [procedure] = &native.procedures[..] else { + panic!("{:?}", native.procedures) + }; + assert_eq!(procedure.kind, ProcedureKind::AlwaysComb); + assert!(matches!( + &native.statement(procedure.body).kind, + StatementKind::Assertion { keyword: k, .. } if k == keyword + )); } } } diff --git a/crates/celox/src/backend/interp.rs b/crates/celox/src/backend/interp.rs index 1101a082e15..d3651da5bc6 100644 --- a/crates/celox/src/backend/interp.rs +++ b/crates/celox/src/backend/interp.rs @@ -1965,6 +1965,13 @@ impl SimBackend for InterpBackend { } } + fn comb_capture_event_enabled(&self) -> Vec { + self.comb_capture_enabled + .iter() + .map(|&enabled| enabled != 0) + .collect() + } + fn stable_region_size(&self) -> usize { self.layout.total_size } diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 28811acbea5..5df523898e5 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -3433,6 +3433,13 @@ impl super::super::SimBackend for NativeBackend { } } + fn comb_capture_event_enabled(&self) -> Vec { + self.comb_capture_enabled + .iter() + .map(|&enabled| enabled != 0) + .collect() + } + fn stable_region_size(&self) -> usize { self.compiled.layout.total_size } diff --git a/crates/celox/src/backend/runtime.rs b/crates/celox/src/backend/runtime.rs index e8f5ba4a1db..87b312090ad 100644 --- a/crates/celox/src/backend/runtime.rs +++ b/crates/celox/src/backend/runtime.rs @@ -1422,6 +1422,13 @@ impl super::SimBackend for JitBackend { self.set_comb_capture_event_enabled(active_sites); } + fn comb_capture_event_enabled(&self) -> Vec { + self.comb_capture_enabled + .iter() + .map(|&enabled| enabled != 0) + .collect() + } + fn stable_region_size(&self) -> usize { self.stable_region_size() } diff --git a/crates/celox/src/backend/tiered.rs b/crates/celox/src/backend/tiered.rs index bff1dcf143e..ef541fac47e 100644 --- a/crates/celox/src/backend/tiered.rs +++ b/crates/celox/src/backend/tiered.rs @@ -1690,6 +1690,20 @@ impl SimBackend for TieredBackend { } } + fn comb_capture_event_enabled(&self) -> Vec { + match &self.phase { + Phase::Interpreting(Some(interp)) => interp.comb_capture_event_enabled(), + Phase::Compiled(CompiledTier::Jit(jit)) => jit.comb_capture_event_enabled(), + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + Phase::Compiled(CompiledTier::Native(native)) => native.comb_capture_event_enabled(), + Phase::Interpreting(None) => unreachable!("promoted backend left no interpreter"), + } + } + fn stable_region_size(&self) -> usize { match &self.phase { Phase::Interpreting(Some(interp)) => interp.stable_region_size(), diff --git a/crates/celox/src/backend/wasm_runtime.rs b/crates/celox/src/backend/wasm_runtime.rs index 4dceda752f0..26e5c70b1a2 100644 --- a/crates/celox/src/backend/wasm_runtime.rs +++ b/crates/celox/src/backend/wasm_runtime.rs @@ -121,6 +121,9 @@ impl super::traits::SimBackend for WasmBackend { fn set_comb_capture_event_enabled(&mut self, active_sites: &[bool]) { WasmBackend::set_comb_capture_event_enabled(self, active_sites) } + fn comb_capture_event_enabled(&self) -> Vec { + WasmBackend::comb_capture_event_enabled(self) + } fn stable_region_size(&self) -> usize { WasmBackend::stable_region_size(self) } @@ -705,6 +708,16 @@ impl WasmBackend { } } + pub fn comb_capture_event_enabled(&self) -> Vec { + let enabled_base = self.layout.merged_total_size + self.layout.runtime_event_buffer_size; + let enabled_len = self.layout.runtime_event_site_layouts.len(); + let mem = self.memory.data(&self.store); + mem[enabled_base..enabled_base + enabled_len] + .iter() + .map(|&enabled| enabled != 0) + .collect() + } + pub fn stable_region_size(&self) -> usize { self.layout.total_size } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 59740d44036..9ff42deb8cc 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -433,6 +433,7 @@ impl Simulation { // Only a timed simulation ends at an RTL `$finish`; a bare // `Simulator`, ticks included, leaves that to the host. simulator.finish_sites = simulator.schedule.finish_sites; + simulator.timed = true; simulator.skip_runtime_finish(); state.initialize_declarations(&mut simulator)?; Ok(Self { @@ -683,9 +684,44 @@ impl Simulation { if self.reports.fail_on.is_some() { return self.watched_step(); } + // With nothing scheduled, the step ends the slot too. + self.end_idle_slot(self.state.next_event_time().unwrap_or(u64::MAX))?; self.step_until(u64::MAX) } + /// A slot with nothing due is over when a run leaves its time. In a + /// design with deferred assertions, logic that host writes or the + /// initial settle left dirty settles there, and the actions waiting from + /// any settle at that time mature, so that a deferred `$fatal` ends the + /// run at that time. + #[inline] + fn end_idle_slot(&mut self, end_time: u64) -> Result<(), RuntimeErrorCode> { + if !self.simulator.deferred_assertions + || end_time <= self.state.time() + || self.state.next_event_time() == Some(self.state.time()) + { + return Ok(()); + } + self.settle_idle_slot() + } + + #[cold] + #[inline(never)] + fn settle_idle_slot(&mut self) -> Result<(), RuntimeErrorCode> { + let result = if self.simulator.dirty { + let result = self.simulator.eval_comb_checked(); + self.simulator.dirty = false; + result + } else { + Ok(()) + }; + if let Err(error) = result.and_then(|()| self.simulator.mature_deferred_assertions()) { + self.flush_error_output(); + return Err(error); + } + Ok(()) + } + /// [`Self::step`] while [`Self::set_fail_on`] is set: a slot that only /// settles host writes is watched before the step goes on to the next /// time. @@ -765,15 +801,31 @@ impl Simulation { /// that wake no process, at the current time, and watch its reports. A /// watched run does this before it moves to a later time. fn watch_settle(&mut self) -> Result<(), RuntimeErrorCode> { - if !self.simulator.dirty { + // The run leaves the time or ends at it: the slot is over, and the + // deferred actions waiting from any settle at that time mature + // before the reports are watched. + let mature = self.simulator.deferred_assertions + && self.state.next_event_time() != Some(self.state.time()); + if !self.simulator.dirty && !mature { return Ok(()); } - if let Err(error) = self.simulator.eval_comb_checked() { + if self.simulator.dirty { + if let Err(error) = self.simulator.eval_comb_checked() { + self.flush_error_output(); + return Err(error); + } + self.simulator.dirty = false; + } + let matured = if mature { + self.simulator.mature_deferred_assertions() + } else { + Ok(()) + }; + self.watch_reports(); + if let Err(error) = matured { self.flush_error_output(); return Err(error); } - self.simulator.dirty = false; - self.watch_reports(); Ok(()) } @@ -831,8 +883,12 @@ impl Simulation { self.reports.failure = None; // With reports to watch, step one slot at a time; the run below // then only advances the time. - if self.reports.fail_on.is_some() && !self.watched_steps(end_time, u64::MAX)? { - return Ok(()); + if self.reports.fail_on.is_some() { + if !self.watched_steps(end_time, u64::MAX)? { + return Ok(()); + } + } else { + self.end_idle_slot(end_time)?; } let reached = match self.shadow.take() { None => self.state.run_until(&mut self.simulator, end_time)?, @@ -871,6 +927,15 @@ impl Simulation { if self.time() != last || self.is_finished() || self.is_stopped() { return Ok(()); } + // Leaving `last` ends its slot. + if self.reports.fail_on.is_some() { + self.watch_settle()?; + if self.reports.failure.is_some() { + return Ok(()); + } + } else { + self.end_idle_slot(time)?; + } self.state.advance_time(&mut self.simulator.backend, time); if let Some(shadow) = &mut self.shadow { shadow @@ -900,6 +965,7 @@ impl Simulation { self.run_until(end_time)?; return Ok(!self.state.is_stopped()); } + self.end_idle_slot(end_time)?; let mut steps = 0; while let Some(next_time) = self.state.next_event_time() { if next_time > end_time { @@ -948,6 +1014,16 @@ impl Simulation { /// Takes the runtime events (`$display`, messages, `$finish`, ...) the /// design emitted since the last call, in emission order. pub fn drain_runtime_events(&mut self) -> Vec { + // A slot with nothing more due is over, also before the first step: + // the initial settle of combinational logic belongs to time zero. + // A fatal action is drained as a fatal report. + if self.simulator.deferred_assertions + && self.state.next_event_time() != Some(self.state.time()) + { + // Lazily settled logic runs in the slot too. + self.simulator.settle_for_runtime_event_drain(); + let _ = self.simulator.mature_deferred_assertions(); + } let mut events = std::mem::take(&mut self.reports.events); events.extend(self.simulator.drain_runtime_events()); events diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index d70605ce91b..abae66ea6c2 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -153,6 +153,13 @@ mod host { /// The design has deferred assertions, whose actions mature at the /// end of each time slot. pub(crate) deferred_assertions: bool, + /// The activation groups of combinational processes with deferred + /// assertions, with a site of each: running the process again + /// flushes its queue (IEEE 1800-2023 16.4.2). + comb_deferred_groups: Vec<(u32, usize)>, + /// A timed simulation owns this simulator: a time slot ends when its + /// scheduler says so, not when combinational logic settles. + pub(crate) timed: 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. @@ -430,9 +437,7 @@ mod host { { let site = *site_id as u32; match *deferred { - celox_design::DeferredSite::FlushPoint => { - self.deferred.waiting.retain(|&(queue, ..)| queue != site); - } + celox_design::DeferredSite::FlushPoint => self.flush(site), celox_design::DeferredSite::Action { queue, region } => { self.deferred.waiting.push((queue, region, event)); } @@ -452,6 +457,13 @@ mod host { self.push_ready(event, capacity); } + /// Discard the actions waiting in queue `queue`. + fn flush(&mut self, queue: u32) { + self.deferred + .waiting + .retain(|&(waiting, ..)| waiting != queue); + } + /// 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 @@ -1017,6 +1029,19 @@ mod host { } else { Vec::new() }; + let mut comb_deferred_groups: Vec<(u32, usize)> = Vec::new(); + for observer in &program.runtime_schema.comb_observers { + if matches!( + sites[observer.site_id as usize].deferred, + Some(celox_design::DeferredSite::Action { .. }) + ) && !comb_deferred_groups + .iter() + .any(|&(group, _)| group == observer.activation_group) + { + comb_deferred_groups + .push((observer.activation_group, observer.site_id as usize)); + } + } let mut sim = Self { backend, program, @@ -1037,6 +1062,8 @@ mod host { ..Default::default() })), deferred_assertions: !deferred_sites.is_empty(), + comb_deferred_groups, + timed: false, components: Default::default(), component_simulation: None, runtime_event_read_seq: Arc::new(AtomicU64::new(0)), @@ -1263,10 +1290,26 @@ mod host { !self.runtime_event_drain_active.load(Ordering::Acquire), "cannot use Simulator::drain_runtime_events while a RuntimeEventDrain is active", ); + self.settle_for_runtime_event_drain(); + // A fatal action is drained as a fatal report. + let _ = self.end_untimed_slot(); + self.collect_formatted_runtime_events(ctx) + } + + /// Settle dirty combinational logic before its events are drained. + pub(crate) fn settle_for_runtime_event_drain(&mut self) { if self.dirty { self.eval_comb_for_runtime_event_drain().unwrap(); } - self.collect_formatted_runtime_events(ctx) + } + + /// Without a scheduler, a host call is a time slot: mature the + /// deferred assertions it ran. + fn end_untimed_slot(&mut self) -> Result<(), RuntimeErrorCode> { + if self.timed { + return Ok(()); + } + self.mature_deferred_assertions() } pub(crate) fn drain_runtime_events_deferred_with_context( @@ -1735,6 +1778,7 @@ mod host { self.dirty = true; if self.runtime_event_drain_active.load(Ordering::Acquire) { self.eval_comb_for_runtime_event_drain()?; + self.end_untimed_slot()?; } Ok(()) } @@ -1742,6 +1786,8 @@ mod host { pub(super) fn settle_dirty_for_runtime_event_drain(&mut self) { if self.runtime_event_drain_active.load(Ordering::Acquire) { self.eval_comb_for_runtime_event_drain().unwrap(); + // A fatal action is drained as a fatal report. + let _ = self.end_untimed_slot(); } } @@ -1798,8 +1844,14 @@ mod host { &self.comb_observer_snapshots, self.comb_observer_initial_eval, ); + if !self.comb_deferred_groups.is_empty() { + self.flush_comb_deferred(&active_sites); + } self.backend.set_comb_capture_event_enabled(&active_sites); let eval_result = self.backend.eval_comb(); + if !self.comb_deferred_groups.is_empty() { + self.flush_comb_rerun_deferred(&active_sites); + } self.comb_observer_reads .snapshot(&self.backend, &mut snapshots); let runtime_events = self.peek_backend_runtime_events_from(runtime_event_start_seq); @@ -1816,6 +1868,34 @@ mod host { (eval_result, runtime_events) } + /// The combinational processes that run again flush the actions of + /// their deferred assertions, after the events issued before. + #[cold] + fn flush_comb_deferred(&mut self, active_sites: &[bool]) { + self.stash_runtime_events(); + let mut pending = self.pending_host_events.lock().unwrap(); + for &(group, site) in &self.comb_deferred_groups { + if active_sites[site] { + pending.flush(group); + } + } + } + + /// A combinational process that runs again because the evaluation + /// changed its inputs, which the backend enables it for, flushes the + /// actions waiting from before the evaluation. Its new actions are + /// still in the backend's buffer. + #[cold] + fn flush_comb_rerun_deferred(&mut self, active_sites: &[bool]) { + let enabled = self.backend.comb_capture_event_enabled(); + let mut pending = self.pending_host_events.lock().unwrap(); + for &(group, site) in &self.comb_deferred_groups { + if !active_sites[site] && enabled.get(site).copied().unwrap_or(false) { + pending.flush(group); + } + } + } + pub(super) fn snapshot_all_comb_observers( &self, ) -> Vec { @@ -1832,7 +1912,8 @@ mod host { .runtime_schema .runtime_event_sites .get(*site_id)?; - if !site.kind.is_fatal() { + // A deferred `$fatal` ends the simulation when it matures. + if !site.kind.is_fatal() || site.deferred.is_some() { return None; } Some(RuntimeErrorCode::Runtime { @@ -2586,7 +2667,7 @@ mod host { pub fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { self.eval_comb_checked()?; self.dirty = false; - Ok(()) + self.end_untimed_slot() } /// Returns a raw pointer to the backend memory and its total size in bytes. diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 28c62e18b39..e56ff78d97a 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -1404,12 +1404,14 @@ fn readmem_diagnostics_identify_task_and_requested_range() { } } +/// The action of a deferred cover, like that of a deferred assertion, is +/// one subroutine call (IEEE 1800-2023 16.4). #[test] -fn rejects_deferred_cover_instead_of_discarding_its_semantics() { +fn rejects_deferred_cover_actions_other_than_a_task_call() { for timing in ["#0", "final"] { let source = format!("module Top(output logic y); initial cover {timing} (1) y = 1; endmodule"); - assert!(build_error(&source).contains("deferred immediate cover")); + assert!(build_error(&source).contains("deferred assertion action")); } } diff --git a/crates/celox/tests/sv_deferred_assertions.rs b/crates/celox/tests/sv_deferred_assertions.rs index a92d9a44e6f..bffd145a554 100644 --- a/crates/celox/tests/sv_deferred_assertions.rs +++ b/crates/celox/tests/sv_deferred_assertions.rs @@ -1,6 +1,6 @@ #![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 +//! The actions of deferred immediate assertions wait in the deferred +//! assertion report queue of their process: `#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}; @@ -124,6 +124,160 @@ macro_rules! deferred { ); } + /// Combinational processes run again when a source changes; the + /// second run flushes the failure of the first (IEEE 1800-2023 + /// 16.4.2). A module item is the same assertion in an + /// `always_comb` (16.4.3). + #[test] + fn rerunning_a_combinational_process_flushes_waiting_actions() { + let glitch = "initial begin #1 a = 1; #0 b = 1; end"; + for assertion in [ + "always_comb d: assert #0 (a == b) else $error(\"d\");", + "always_comb d: assert final (a == b) else $error(\"d\");", + "always @(a or b) d: assert #0 (a == b) else $error(\"d\");", + "d: assert #0 (a == b) else $error(\"d\");", + "d: assume final (a == b) else $error(\"d\");", + ] { + assert_eq!(run(&format!(" {assertion}\n {glitch}"), 1), vec![], "{assertion}"); + let mut reports = run(&format!(" {assertion}\n initial #1 a = 1;"), 1); + assert_eq!(reports.len(), 1, "{assertion}: {reports:?}"); + assert_eq!(reports.remove(0).0, "d", "{assertion}"); + } + } + + /// A process also runs again when the evaluation itself changes + /// one of its inputs, here `y` through the continuous assignment + /// from `x`, and that run flushes the earlier failure too. + #[test] + fn reruns_from_changes_within_an_evaluation_flush_waiting_actions() { + let body = " bit y;\n assign y = ~x;\n \ + always_comb d: assert #0 (a == y) else $error(\"d\");\n \ + initial begin x = 1; #1 a = 1; #0 x = 0; end"; + assert_eq!(run(body, 1), vec![]); + } + + /// A module item in a generate region or a generate block is a + /// deferred assertion as well. + #[test] + fn module_assertions_in_generate_scopes_are_deferred() { + for item in [ + "generate d: assert #0 (a == b) else $error(\"d\"); endgenerate", + "if (1) begin : g d: assert #0 (a == b) else $error(\"d\"); end", + "for (genvar i = 0; i < 1; i++) begin : g\n d: assert #0 (a == b) else $error(\"d\");\n end", + "case (1) 1: begin : g d: assert #0 (a == b) else $error(\"d\"); end endcase", + ] { + assert_eq!( + run(&format!(" {item}\n initial begin #1 a = 1; #0 b = 1; end"), 1), + vec![], + "{item}" + ); + let reports = run(&format!(" {item}\n initial #1 a = 1;"), 1); + assert_eq!(reports.len(), 1, "{item}: {reports:?}"); + } + } + + /// A run watching reports matures the actions of a settle that + /// no step ran before it checks them, and stops there. + #[test] + fn fail_on_sees_actions_of_settles_without_steps() { + let mut sim = simulation(" always_comb d: assert #0 (a) else $error(\"d\");"); + sim.set_fail_on(Some(Severity::Error)); + sim.run_until(10).unwrap(); + assert_eq!(sim.time(), 0); + assert_eq!(sim.failure().map(|report| report.message.clone()), Some(b"d".to_vec())); + } + + /// A run leaving a slot with nothing due ends it, so a deferred + /// `$fatal` of its settle ends the run there, also without + /// `set_fail_on`, by `run_until` or by `step`. + #[test] + fn a_deferred_fatal_of_an_idle_slot_ends_the_run() { + for (body, step) in [ + (" always_comb assert #0 (a) else $fatal(1, \"failed\");", false), + (" always_comb assert #0 (a) else $fatal(1, \"failed\");\n initial #5 $display(\"later\");", true), + ] { + let mut sim = simulation(body); + let result = if step { sim.step().map(|_| ()) } else { sim.run_until(10) }; + assert!(result.is_err(), "{body}"); + assert_eq!(sim.time(), 0, "{body}"); + } + // Also when a settle at that time already ran, by + // `eval_comb` or by a run to the current time. + let body = " always_comb assert #0 (a) else $fatal(1, \"failed\");"; + for settle in [false, true] { + let mut sim = simulation(body); + if settle { + sim.eval_comb().unwrap(); + } else { + sim.run_until(0).unwrap(); + } + assert!(sim.run_until(10).is_err(), "eval_comb: {settle}"); + assert_eq!(sim.time(), 0, "eval_comb: {settle}"); + } + // `advance_to` leaves the slot too. + let mut sim = simulation(body); + assert!(sim.advance_to(1).is_err()); + assert_eq!(sim.time(), 0); + // A step with nothing scheduled, after a settle or not. + for settle in [false, true] { + let mut sim = simulation(body); + if settle { + sim.eval_comb().unwrap(); + } + assert!(sim.step().is_err(), "step after eval_comb: {settle}"); + } + } + + /// A run watching reports also checks the actions of a settle + /// that already ran at the time it leaves. + #[test] + fn fail_on_sees_actions_of_earlier_settles() { + let mut sim = simulation(" always_comb d: assert #0 (a) else $error(\"d\");"); + sim.eval_comb().unwrap(); + sim.set_fail_on(Some(Severity::Error)); + sim.run_until(10).unwrap(); + assert_eq!(sim.time(), 0); + assert_eq!(sim.failure().map(|report| report.message.clone()), Some(b"d".to_vec())); + } + + /// A design without events may never step; the initial settle + /// of combinational logic belongs to time zero, whose slot is + /// over once nothing more is due. + #[test] + fn actions_of_the_initial_settle_mature_without_a_step() { + let mut sim = simulation(" d: assume #0 (a) else $error(\"d\");"); + sim.run_until(0).unwrap(); + assert_eq!( + summary(sim.drain_runtime_events()), + vec![("d".to_owned(), Some(AssertionDeferral::Observed))] + ); + } + + /// A deferred cover reports its pass action when it matures. + #[test] + fn deferred_cover_reports_when_it_matures() { + let cover = " c: cover #0 (a != b) $info(\"c\");\n "; + assert_eq!(run(&format!("{cover}initial begin #1 a = 1; #0 b = 1; end"), 1), vec![]); + assert_eq!( + run(&format!("{cover}initial #1 a = 1;"), 1), + vec![("c".to_owned(), Some(AssertionDeferral::Observed))] + ); + } + + /// A deferred `$fatal` of a combinational process ends the + /// simulation when it matures, not while combinational logic + /// settles. + #[test] + fn a_combinational_deferred_fatal_ends_the_simulation_when_it_matures() { + let mut sim = simulation( + " always_comb f: assert final (a == b) else $fatal(1, \"boom\");\n \ + initial begin #1 a = 1; #0 b = 1; #1 a = 0; end", + ); + sim.run_until(1).unwrap(); + assert!(sim.run_until(5).is_err()); + assert_eq!(sim.time(), 2); + } + /// A deferred `$fatal` ends the simulation when it matures, at /// the end of its time slot. #[test] @@ -289,6 +443,87 @@ fn deferred_actions_mature_at_the_end_of_edges_and_derived_ticks() { assert_eq!(labels, ["o", "d", "o", "o", "d", "o", "o", "d", "o"]); } +/// Without a scheduler, a settle of combinational logic ends the host +/// call's time slot. +#[test] +fn combinational_deferred_actions_mature_when_logic_settles() { + let source = "module Top(input bit a);\n \ + always_comb d: assert #0 (a) else $error(\"d\");\n\ + endmodule"; + let mut sim = + celox::Simulator::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top") + .build() + .unwrap(); + assert_eq!( + summary(sim.drain_runtime_events()), + vec![("d".to_owned(), Some(AssertionDeferral::Observed))] + ); + let a = sim.signal("a"); + sim.modify(|io| io.set(a, 1u8)).unwrap(); + assert_eq!(summary(sim.drain_runtime_events()), vec![]); +} + +/// A drain returns a deferred `$fatal` of combinational logic as a fatal +/// report. +#[test] +fn draining_a_combinational_deferred_fatal_returns_its_report() { + let source = "module Top(input bit a);\n \ + always_comb assert #0 (a) else $fatal(1, \"failed\");\n\ + endmodule"; + let mut sim = + celox::Simulator::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top") + .build() + .unwrap(); + let events = sim.drain_runtime_events(); + assert!( + matches!( + events.as_slice(), + [RuntimeEvent::Report(Report { severity: Severity::Fatal, message, .. })] + if message == b"failed" + ), + "{events:?}" + ); +} + +/// A tick is one time slot: the settle before its flip-flops does not end +/// it, so the settle after them flushes what failed in between. +#[test] +fn a_tick_flushes_actions_of_the_settle_before_its_flip_flops() { + let source = "module Top(input bit clk);\n \ + bit q;\n \ + always_ff @(posedge clk) q <= 1'b1;\n \ + always_comb assert #0 (!clk || q) else $error(\"failed\");\n\ + endmodule"; + let mut sim = + celox::Simulator::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top") + .build() + .unwrap(); + assert_eq!(summary(sim.drain_runtime_events()), vec![]); + // The host write leaves the logic to settle before the flip-flops. + let q = sim.signal("q"); + sim.set(q, 0u8); + let clk = sim.event("clk"); + sim.tick(clk).unwrap(); + assert_eq!(summary(sim.drain_runtime_events()), vec![]); +} + +/// The first drain of a simulation settles its combinational logic before +/// the slot matures, and returns what failed. +#[test] +fn a_first_drain_returns_actions_of_the_initial_settle() { + let source = "module Top;\n bit a;\n \ + d: assert #0 (a) else $error(\"d\");\n\ + endmodule"; + let mut sim = + celox::Simulation::from_sv_sources(vec![(source, Path::new("deferred.sv"))], "Top") + .build() + .unwrap(); + assert_eq!( + summary(sim.drain_runtime_events()), + vec![("d".to_owned(), Some(AssertionDeferral::Observed))] + ); +} + #[test] fn deferred_actions_are_one_display_or_severity_task_call() { let source = "module Top; bit a;\n \ diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 79e3ef8a4a5..2f8c528f43d 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -43,7 +43,7 @@ synthesis and is tested at the design level. | Combinational processes | `always_comb`, `always @*`, blocking `always_latch`, block-local variables, sequential and dependent blocking assignments, reads of a variable before the process writes it (its previous value) | | Sequential processes | `always_ff @(posedge clk)`, `always @(posedge clk or negedge rst_n)` and the like, blocking and nonblocking assignments, concatenated targets, four-state clock and reset signals, one asynchronous reset shared by several clock domains, processes at both edges of one clock or reset, and one signal as the clock of some processes and the asynchronous reset of others (a timed `Simulation` runs every edge; `Simulator::tick` is the rising edge of its event only) | | Initial blocks | `initial` blocks and variable declaration initializers (`logic [7:0] v = 8'h5a;`, also of interface members); initializers take effect before the `initial` blocks. One whose writes have constant values, with constant `if` / `for` and `$readmemh` / `$readmemb`, defines the initial state. Any other, such as one that reads design state or calls a system task, runs as a process from time zero in a timed `Simulation`; a `Simulator` does not run processes, so building one for such a design fails with `SimulatorErrorKind::ProcessRequiresSimulation` | -| Statements | `if` / `else`, `case`, `casez`, `casex`, `case ... inside`, `unique` / `priority`, `for`, `while`, `do ... while`, `repeat`, `forever` and `foreach` (unrolled when the trip count is constant, otherwise executed at run time), `break` / `continue` / `return`, immediate assertions | +| Statements | `if` / `else`, `case`, `casez`, `casex`, `case ... inside`, `unique` / `priority`, `for`, `while`, `do ... while`, `repeat`, `forever` and `foreach` (unrolled when the trip count is constant, otherwise executed at run time), `break` / `continue` / `return`, immediate and deferred immediate assertions | | Functions | `function` and `task` with `input`, `output` and `inout` arguments, `return` or assignment to the function name, local variables and `localparam`s, selected and composite assignments; calls are inlined. Calls with constant arguments in constant expressions (parameters, ranges) are evaluated during elaboration | ### Timing controls {#timing-controls} @@ -601,12 +601,6 @@ ignored, as 24.7 specifies, with a compilation warning function of a module. Calls in function declarations are diagnosed even when the function is unused; the diagnostic does not depend on constant evaluation executing it. -### Immediate cover - -Immediate cover executes its pass statement when the condition is true. -Coverage counters and reports are not exposed. Deferred cover (`#0` / `final`) -is rejected because its scheduling is not modeled. - ### Severity tasks and reports `$info`, `$warning`, `$error` and `$fatal`, including the default `$error` of @@ -625,22 +619,29 @@ 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. +The action of `assert #0`, `assume #0`, `cover #0` and their `final` forms +waits in the deferred assertion report queue of its process (IEEE 1800-2023 +16.4). Its arguments are evaluated when the assertion executes. The process +flushes the queue at its flush points (16.4.2): +- a process with timing controls, each time it resumes from an event control + or a wait; a resume after a delay is no flush point; +- an edge-triggered `always` or `always_ff` process, each time it runs; +- `always_comb`, `always_latch` and an `always` lowered as combinational logic + (one whose only timing control is its leading event control), each time it + runs again. + +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. A deferred assertion as a module item is the same assertion +in an `always_comb` (16.4.3). An action is one display or severity task +call; a user subroutine, or more than one statement, is rejected. A +`Simulator` call is a time slot: there, actions mature when the call settles +combinational logic or runs a domain. + +### Immediate cover + +Immediate cover executes its pass statement when the condition is true. +Coverage counters and reports are not exposed. ### Constant functions diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 49f40d7e00d..952eb064d73 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -84,7 +84,7 @@ The main supported areas are: | RTL processes | `assign`, `always_comb`, `always @*`, blocking `always_latch`, edge-triggered `always` and `always_ff` | | Timed processes | `initial` and `always` with `#delay` (also time literals such as `#5ns`), `@(...)` on variables, edges, selects, expressions and `@*`, `wait (...)`, nonblocking assignments and task calls with timing controls | | Computation | Arithmetic, selects, assignment patterns, branches, loops and functions | -| Simulation helpers | Immediate assertions, display tasks, `$readmemh` / `$readmemb`, time queries and random numbers | +| Simulation helpers | Immediate and deferred immediate assertions, display tasks, `$readmemh` / `$readmemb`, time queries and random numbers | Each area has restrictions. Use the [detailed support list](./systemverilog-reference#what-is-supported) to check diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index fec9ec48260..66ef02a138c 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -41,7 +41,7 @@ outline: [2, 3] | 組み合わせプロセス | `always_comb`、`always @*`、ブロッキング代入の `always_latch`、ブロックローカル変数、逐次・依存するブロッキング代入、プロセスが書き込む前の変数の読み出し(直前の値) | | 順序プロセス | `always_ff @(posedge clk)`、`always @(posedge clk or negedge rst_n)` など。ブロッキング・ノンブロッキング代入、連結を代入先とする代入、4 値のクロック・リセット信号、複数のクロックドメインで共有する非同期リセット、同一クロック・同一リセットの両エッジを使うプロセス、あるプロセスのクロックを別のプロセスの非同期リセットとして使う信号(時間付きの `Simulation` はすべてのエッジを実行します。`Simulator::tick` はイベントの立ち上がりエッジだけです) | | initial ブロック | `initial` ブロックと変数宣言の初期化子(`logic [7:0] v = 8'h5a;`、interface のメンバーを含む)。初期化子は `initial` ブロックより先に適用。書き込む値が定数のもの(定数の `if` / `for`、`$readmemh` / `$readmemb` を含む)は初期状態を定める。デザインの状態を読むものやシステムタスクを呼ぶものなどそれ以外は、時間を持つ `Simulation` で時刻 0 からプロセスとして実行(`Simulator` はプロセスを実行しないため、このようなデザインでは `SimulatorErrorKind::ProcessRequiresSimulation` でビルドに失敗) | -| 文 | `if` / `else`、`case`、`casez`、`casex`、`case ... inside`、`unique` / `priority`、`for`、`while`、`do ... while`、`repeat`、`forever`、`foreach`(反復回数が定数なら展開し、そうでなければ実行時に実行)、`break` / `continue` / `return`、即時アサーション | +| 文 | `if` / `else`、`case`、`casez`、`casex`、`case ... inside`、`unique` / `priority`、`for`、`while`、`do ... while`、`repeat`、`forever`、`foreach`(反復回数が定数なら展開し、そうでなければ実行時に実行)、`break` / `continue` / `return`、即時アサーションと遅延付き即時アサーション | | 関数 | `input` / `output` / `inout` 引数を持てる `function` と、`task`。`return`、または関数名への代入で値を返す。ローカル変数と `localparam`、部分選択や複合的な代入先への代入。呼び出しはインライン展開。定数式(パラメータ、範囲)の中の定数引数による呼び出しはエラボレーション時に評価 | ### タイミング制御 {#timing-controls} @@ -401,19 +401,20 @@ VPI ホストと `celox` コマンドが表示する形に整形します。`cel ### 遅延付きアサーション -タイミング制御を含む `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 は拒否します。 +`assert #0`、`assume #0`、`cover #0` とそれぞれの `final` 形のアクションは、プロセスの遅延 +アサーション報告キューで待ちます(IEEE 1800-2023 16.4)。引数はアサーションを実行した時点で +評価します。プロセスはフラッシュ点でキューを空にします(16.4.2)。 +- タイミング制御を含むプロセスは、イベント制御や wait から再開するたびに。遅延からの再開は + フラッシュ点ではありません。 +- エッジで起動する `always` / `always_ff` プロセスは、実行するたびに。 +- `always_comb`、`always_latch`、組み合わせ回路として扱う `always`(タイミング制御が先頭の + イベント制御だけのもの)は、再実行するたびに。 + +タイムスロットが終わると、まだ待っているアクションを `#0` のもの、`final` のものの順に実行します。 +遅延付きの `$fatal` はそこでシミュレーションを終了します。モジュール直下の遅延付きアサーションは、 +`always_comb` に入れた同じアサーションです(16.4.3)。アクションは表示タスクか重大度タスクの +呼び出し 1 つで、ユーザーのサブルーチンや複数の文は拒否します。`Simulator` では呼び出し 1 回が +タイムスロットで、組み合わせ回路が落ち着いたときやドメインを実行したときにアクションが成熟します。 ### 定数関数 diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 947852c6397..4c8a4face3e 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -80,7 +80,7 @@ X/Z を扱う場合は builder に `.four_state(true)` を指定します。 | RTL のプロセス | `assign`、`always_comb`、`always @*`、ブロッキング代入の `always_latch`、エッジで起動する `always` と `always_ff` | | 時間を持つプロセス | `#delay`(`#5ns` などの時間リテラルを含む)、変数・エッジ・選択・式・`@*` に対する `@(...)`、`wait (...)`、ノンブロッキング代入、タイミング制御を持つ task 呼び出しを使う `initial` と `always` | | 演算と制御 | 算術、部分選択、assignment pattern、分岐、ループ、関数 | -| シミュレーション補助 | 即時アサーション、表示タスク、`$readmemh` / `$readmemb`、時刻の取得、乱数 | +| シミュレーション補助 | 即時アサーションと遅延付き即時アサーション、表示タスク、`$readmemh` / `$readmemb`、時刻の取得、乱数 | 各領域には制約があります。デザインを移植する際は、 [詳しい対応一覧](./systemverilog-reference#what-is-supported)でポート、型、文、システム関数を確認してください。