diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index c93669c5ccb..b283788d24b 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -390,8 +390,6 @@ impl HostRequestValue { #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct HostRequestSite { pub process: usize, - /// This request belongs to an edge procedure lowered to a scheduled kernel. - pub requires_timed_simulation: bool, pub kind: HostRequestKind, pub operation: u32, pub args: Vec>, @@ -403,7 +401,6 @@ impl HostRequestSite { pub fn map(&self, mut map: impl FnMut(A) -> B) -> HostRequestSite { HostRequestSite { process: self.process, - requires_timed_simulation: self.requires_timed_simulation, kind: self.kind, operation: self.operation, args: self.args.iter().map(|value| value.map(&mut map)).collect(), @@ -421,6 +418,30 @@ impl HostRequestSite { } } +/// The source procedure a process kernel was lowered from, for diagnostics. +#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct ProcessOrigin { + /// The construct, such as `initial` or `always`. + pub construct: String, + /// `path:line:column` of the construct, when known. + pub location: Option, + /// Fully elaborated module-instance scope that owns the process. + pub scope: Option, +} + +impl std::fmt::Display for ProcessOrigin { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "`{}`", self.construct)?; + if let Some(location) = &self.location { + write!(f, " at {location}")?; + } + if let Some(scope) = &self.scope { + write!(f, " in `{scope}`")?; + } + Ok(()) + } +} + /// State through which one process kernel exchanges control with the runtime. /// /// A process kernel is a resumable function. On entry it reads `resume` to @@ -795,6 +816,8 @@ pub struct RuntimeSchema { pub live_signals: HashSet, /// Control slots of the process kernels, in kernel order. pub processes: Vec>, + /// Source procedures of the process kernels, in kernel order. + pub process_origins: Vec, /// Counted signals and their occurrence counters. pub watches: Vec>, /// Wait sites of the process kernels. A process's sites appear in the @@ -833,6 +856,7 @@ impl Default for RuntimeSchema { dead_store_policy: DeadStorePolicy::Off, live_signals: HashSet::default(), processes: Vec::new(), + process_origins: Vec::new(), watches: Vec::new(), wait_sites: Vec::new(), nba_sites: Vec::new(), @@ -1536,7 +1560,6 @@ mod tests { let site = HostRequestSite { process: 2, kind: HostRequestKind::Plusargs, - requires_timed_simulation: false, operation: 1, args: vec![value(3u32)], results: vec![value(5)], diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 6b78ba0c17c..2a5196e29ef 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1732,7 +1732,15 @@ fn lower_processes( candidates.extend(crate::watch::multi_store_candidates(&kernel, |address| { stable_signal(address, artifact.signals().len()) })); - processes.push(SymbolicProcess { kernel, slots }); + processes.push(SymbolicProcess { + kernel, + slots, + origin: celox_design::ProcessOrigin { + construct: "process".to_string(), + location: None, + scope: None, + }, + }); } Ok(LoweredProcesses { processes, diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index d1e7231593b..a505345d621 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -54,6 +54,7 @@ impl FfPart { pub struct SymbolicProcess { pub kernel: ExecutionUnit, pub slots: ProcessSlots, + pub origin: celox_design::ProcessOrigin, } /// The commit of a trigger group's results, split by region. diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 0d1d3315008..9e7edb1dc0c 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -1691,10 +1691,14 @@ pub fn schedule_symbolic_rtl_reporting_loops( ); select_nba_paths(&mut timing, &staged, &mut processes); } - let (process_kernels, process_slots): (Vec<_>, Vec<_>) = processes - .into_iter() - .map(|process| (process.kernel, process.slots)) - .unzip(); + let mut process_kernels = Vec::with_capacity(processes.len()); + let mut process_slots = Vec::with_capacity(processes.len()); + let mut process_origins = Vec::with_capacity(processes.len()); + for process in processes { + process_kernels.push(process.kernel); + process_slots.push(process.slots); + process_origins.push(process.origin); + } let TimingMetadata { wait_sites, nba_sites, @@ -2034,6 +2038,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( dead_store_policy: Default::default(), live_signals: Default::default(), processes: process_slots, + process_origins, watches, wait_sites, nba_sites, @@ -3087,6 +3092,10 @@ fn relocate_units( &extern_function_map, ), slots: process.slots.map(|var_id| bindings.locate(*id, var_id)), + origin: celox_design::ProcessOrigin { + scope: Some(scope.clone()), + ..process.origin.clone() + }, key: (*id, index), }, )); @@ -3214,6 +3223,7 @@ fn relocate_units( struct RelocatedProcess { kernel: ExecutionUnit, slots: ProcessSlots, + origin: celox_design::ProcessOrigin, /// The instance and the module-local index of the process. key: (InstanceId, usize), } diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 3efdbe94393..742b44be619 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -3918,6 +3918,21 @@ fn process_random_seeds(module: &sv::ir::Module) -> HashMap<(u8, usize), u32> { .collect() } +/// The source procedure of a process kernel, for diagnostics. +fn process_origin(process: &sv::ir::InitialProcess) -> celox_design::ProcessOrigin { + let construct = match process.site() { + Some(site) => site.construct, + None if process.is_initializer() => "declaration initializer", + None if process.repeats() => "always", + None => "initial", + }; + celox_design::ProcessOrigin { + construct: construct.to_string(), + location: process.site().map(ToString::to_string), + scope: None, + } +} + /// The `initial` blocks and declaration initializers (IEEE 1800-2023 9.2.1, /// 10.5): the initial state they define, and the processes that run the /// others from time zero. @@ -4108,15 +4123,12 @@ fn lower_initial_processes( nba_switches.extend(kernel.nba_switches); host_request_sites.extend(kernel.host_request_sites.into_iter().map(|mut site| { site.process = index; - // Repeating ordinary always processes also execute only in - // the timed scheduler. Keep this site requirement separate - // from the converted-FF startup marker on ProcessSlots. - site.requires_timed_simulation = process.repeats(); site })); Ok(SymbolicProcess { kernel: kernel.unit, slots, + origin: process_origin(process), }) }) .collect::, sv::AnalyzerError>>(); diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index f637b17630c..a6de1d2a32a 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -1298,7 +1298,6 @@ impl<'p, 'a> Ff<'p, 'a> { self.host_request_sites.push(HostRequestSite { process: self.process, kind: HostRequestKind::Vcd, - requires_timed_simulation: false, operation: operation as u32, args: values, results: Vec::new(), @@ -1923,7 +1922,6 @@ impl<'p, 'a> Ff<'p, 'a> { self.host_request_sites.push(HostRequestSite { process: 0, kind: HostRequestKind::Distribution, - requires_timed_simulation: false, operation, args: operands, results: vec![value(ret_id), value(seed_id)], @@ -2001,7 +1999,6 @@ impl<'p, 'a> Ff<'p, 'a> { self.host_request_sites.push(HostRequestSite { process: 0, kind: HostRequestKind::Plusargs, - requires_timed_simulation: false, operation: u32::from(value_query), args: vec![HostRequestValue { float_precision: None, 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 9116792f2d7..a84aed372a4 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/file_io.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/file_io.rs @@ -75,7 +75,6 @@ impl Ff<'_, '_> { .count() as u32; self.host_request_sites.push(HostRequestSite { process: 0, - requires_timed_simulation: false, kind: HostRequestKind::FileIo, operation, args, diff --git a/crates/celox-frontend-sv/src/lowering/ff/scan.rs b/crates/celox-frontend-sv/src/lowering/ff/scan.rs index 5388cf2f5c7..7a24f55f6b5 100644 --- a/crates/celox-frontend-sv/src/lowering/ff/scan.rs +++ b/crates/celox-frontend-sv/src/lowering/ff/scan.rs @@ -86,7 +86,6 @@ impl Ff<'_, '_> { self.host_request_sites.push(HostRequestSite { process: 0, kind: HostRequestKind::Scan, - requires_timed_simulation: false, operation: u32::from(function == sv::ir::SystemFunction::Fscanf), args: inputs, results, diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 306a1d59579..40da3a4c7ce 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1176,6 +1176,7 @@ impl Module { first_block, InitialProcess { creation_order: 0, + site: None, condition: None, body: static_initializers, initializer: true, @@ -2271,6 +2272,7 @@ pub struct FfProcess { always_ff: bool, suspendable: bool, creation_order: usize, + site: Option, events: Vec, body: Vec, } @@ -2285,11 +2287,16 @@ impl FfProcess { self.creation_order } + pub fn site(&self) -> Option<&crate::procedural::ProcessSite> { + self.site.as_ref() + } + fn new(events: Vec, body: Vec) -> Self { Self { always_ff: false, suspendable: false, creation_order: 0, + site: None, events, body, } @@ -2308,6 +2315,7 @@ impl FfProcess { #[derive(Debug, Clone, PartialEq, Eq)] pub struct InitialProcess { creation_order: usize, + site: Option, condition: Option, body: Vec, initializer: bool, @@ -2322,6 +2330,10 @@ impl InitialProcess { self.creation_order } + pub fn site(&self) -> Option<&crate::procedural::ProcessSite> { + self.site.as_ref() + } + pub fn condition(&self) -> Option<&ConstExpr> { self.condition.as_ref() } diff --git a/crates/celox-sv-analyzer/src/ast/array_parameters.rs b/crates/celox-sv-analyzer/src/ast/array_parameters.rs index b667ec8d4e6..e482af2e751 100644 --- a/crates/celox-sv-analyzer/src/ast/array_parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/array_parameters.rs @@ -190,6 +190,7 @@ impl ArrayParameter { }; Ok(InitialProcess { creation_order: 0, + site: None, condition: None, body: vec![Stmt::Assign { lhs: LValue::Ident(name), diff --git a/crates/celox-sv-analyzer/src/ast/ff_process.rs b/crates/celox-sv-analyzer/src/ast/ff_process.rs index 0b24fc075c2..944550c2926 100644 --- a/crates/celox-sv-analyzer/src/ast/ff_process.rs +++ b/crates/celox-sv-analyzer/src/ast/ff_process.rs @@ -32,6 +32,15 @@ pub(super) fn ff_processes_from_scope( } for process in &mut processes[start..] { process.creation_order = creation_order; + process.site = procedural::process_site( + if process.always_ff { + "always_ff" + } else { + "always" + }, + syntax_tree.declarations().body_item(item.id).tokens, + syntax_tree, + ); for event in &mut process.events { event.signal = item.name(&event.signal); } diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index f89edc1b21d..0f132d574b1 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -1722,6 +1722,11 @@ pub(super) fn initial_processes_from_scope( if !body.is_empty() { initializers.push(InitialProcess { creation_order, + site: process_site( + "declaration initializer", + tree.declarations().body_item(item.id).tokens, + tree, + ), condition: None, body, initializer: true, @@ -1734,6 +1739,10 @@ pub(super) fn initial_processes_from_scope( let Some(procedure) = item.procedure(tree.declarations())? else { continue; }; + let construct = match procedure.kind { + celox_sv_syntax::ProcedureKind::Initial => "initial", + _ => "always", + }; let repeats = match procedure.kind { celox_sv_syntax::ProcedureKind::Initial => false, celox_sv_syntax::ProcedureKind::Always @@ -1772,6 +1781,11 @@ pub(super) fn initial_processes_from_scope( } processes.push(InitialProcess { creation_order, + site: process_site( + construct, + tree.declarations().body_item(item.id).tokens, + tree, + ), condition: None, body, initializer: false, @@ -1800,6 +1814,29 @@ pub(super) fn written_names<'s>(stmts: impl IntoIterator) -> Ha names } +/// Where the first token of a native token range was invoked. +pub(super) fn process_site( + construct: &'static str, + tokens: celox_sv_syntax::TokenRange, + tree: &SyntaxTree, +) -> Option { + let native = tree.declarations(); + let token = native + .tokens + .get(tokens.start..tokens.end)? + .iter() + .find(|token| !token.is_trivia())?; + let span = native.sources.invocation(token.origin); + let file = native.sources.file(span.file); + let (line, column) = file.line_column(span.start); + Some(crate::procedural::ProcessSite { + construct, + path: file.path.clone(), + line, + column, + }) +} + /// 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-sv-analyzer/src/ast/procedural/timed_tasks.rs b/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs index 9c1b8aaa9d6..58bfe2b180a 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs @@ -115,6 +115,7 @@ pub(in crate::ast) fn classify<'a>( body.extend(process.body); processes.push(InitialProcess { creation_order: process.creation_order, + site: process.site.clone(), condition: None, body: vec![Stmt::Loop { kind: LoopKind::Forever, diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index 7bce362fd3d..2356aecfd89 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -328,6 +328,7 @@ impl ScopeSymbols { .filter(|process| initializes(process, target)) .map(|process| InitialProcess { creation_order: process.creation_order, + site: process.site.clone(), condition: process.condition.clone(), body: process .body @@ -562,6 +563,7 @@ impl ScopeSymbols { .iter() .map(|process| InitialProcess { creation_order: process.creation_order, + site: process.site.clone(), condition: process .condition .clone() diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index c2b3647396a..064c08f09a6 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -4,7 +4,8 @@ use crate::{ast, symbol::ModuleId, typecheck}; pub use crate::ast::warnings::AnalyzerWarning; pub use crate::procedural::{ - CaseKind, CaseLabel, EventEdge, LoopKind, ParamDirection, SourceSpan, StmtBase, SystemTaskArg, + CaseKind, CaseLabel, EventEdge, LoopKind, ParamDirection, ProcessSite, SourceSpan, StmtBase, + SystemTaskArg, }; pub use crate::system_functions::{ ArrayQuery, Callee, MemoryFormat, Radix, Severity, StringOp, SystemFunction, SystemTask, @@ -99,6 +100,7 @@ impl Module { body.extend(process.body); self.initial_processes.push(InitialProcess { creation_order: process.creation_order, + site: process.site, scheduled_edge: true, condition: None, body: vec![Stmt::Loop { @@ -1003,6 +1005,7 @@ pub enum CombProcessKind { pub struct FfProcess { always_ff: bool, creation_order: usize, + site: Option, events: Vec, body: Vec, } @@ -1018,10 +1021,16 @@ impl FfProcess { self.creation_order } + /// Where the procedure is written. + pub fn site(&self) -> Option<&ProcessSite> { + self.site.as_ref() + } + pub(crate) fn new(events: Vec, body: Vec) -> Self { Self { always_ff: false, creation_order: 0, + site: None, events, body, } @@ -1040,6 +1049,7 @@ impl FfProcess { #[derive(Debug, Clone, PartialEq, Eq)] pub struct InitialProcess { creation_order: usize, + site: Option, scheduled_edge: bool, condition: Option, body: Vec, @@ -1060,9 +1070,15 @@ impl InitialProcess { self.creation_order } + /// Where the procedure is written. + pub fn site(&self) -> Option<&ProcessSite> { + self.site.as_ref() + } + pub(crate) fn new(condition: Option, body: Vec, initializer: bool) -> Self { Self { creation_order: 0, + site: None, scheduled_edge: false, condition, body, @@ -1470,6 +1486,7 @@ impl From for FfProcess { ); result.always_ff = process.is_always_ff(); result.creation_order = process.creation_order(); + result.site = process.site().cloned(); result } } @@ -1487,6 +1504,7 @@ impl From for InitialProcess { process.is_initializer(), ); result.creation_order = process.creation_order(); + result.site = process.site().cloned(); result.synthetic = process.is_synthetic(); result.repeats = process.repeats(); result diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index a5940ca627c..8db2fbe4b9b 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -18,6 +18,26 @@ pub struct SourceSpan { pub end: usize, } +/// Where a process is written, for diagnostics about the process as a +/// whole. +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct ProcessSite { + /// The construct the process comes from: `initial`, `always`, + /// `always_ff`, or `declaration initializer`. + pub construct: &'static str, + pub path: std::path::PathBuf, + /// One-based physical line. + pub line: usize, + /// One-based byte column. + pub column: usize, +} + +impl std::fmt::Display for ProcessSite { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}:{}:{}", self.path.display(), self.line, self.column) + } +} + /// One procedural statement. #[derive(Debug, Clone, PartialEq, Eq)] pub enum StmtBase { diff --git a/crates/celox-vpi/tests/diagnostics.rs b/crates/celox-vpi/tests/diagnostics.rs index e05e3b59dba..3299cc6b8ea 100644 --- a/crates/celox-vpi/tests/diagnostics.rs +++ b/crates/celox-vpi/tests/diagnostics.rs @@ -34,9 +34,17 @@ fn run_and_build_share_project_target_and_cli_diagnostic_precedence() { "module Plain(output logic y); assign y = 1; endmodule", ) .unwrap(); - fs::write(project.path().join("top.sv"), "module Top(output logic y); timeunit 1ns / 1ps; Plain child(y); initial #1 $finish; endmodule").unwrap(); fs::write(&config, "sources = ['plain.sv', 'top.sv']\ntop = 'Top'\n[diagnostics]\nmixed_timescale = 'error'\n[targets.compat.diagnostics]\nmixed_timescale = 'warn'\n").unwrap(); for build in [false, true] { + // A VPI image runs no process. + let finish = if build { "" } else { "initial #1 $finish;" }; + fs::write( + project.path().join("top.sv"), + format!( + "module Top(output logic y); timeunit 1ns / 1ps; Plain child(y); {finish} endmodule" + ), + ) + .unwrap(); let compile = |target: bool, overrides: &[&str], discover: bool| { let mut command = Command::new(env!("CARGO_BIN_EXE_celox")); if build { @@ -151,9 +159,16 @@ fn aggregate_input_defaults_can_be_enabled_with_diagnostic_policy() { fn inferred_latch_uses_common_diagnostics_for_run_and_build() { let project = tempfile::tempdir().unwrap(); let config = project.path().join("celox.toml"); - fs::write( - project.path().join("top.sv"), - r#"module Top; + fs::write(&config, "sources = ['top.sv']\ntop = 'Top'\n[diagnostics]\ninferred_latch = 'error'\n[targets.compat.diagnostics]\ninferred_latch = 'warn'\n").unwrap(); + for build in [false, true] { + // A VPI image runs no process. + let source = if build { + r#"module Top(input logic en, input logic [7:0] d, output logic [7:0] q); + timeunit 1ns / 1ps; + always_comb if (en) q = d; + endmodule"# + } else { + r#"module Top; timeunit 1ns / 1ps; logic en; logic [7:0] d, q; always_comb if (en) q = d; @@ -164,11 +179,9 @@ fn inferred_latch_uses_common_diagnostics_for_run_and_build() { assert (q == 7) else $fatal(1, "closed latch"); $finish; end - endmodule"#, - ) - .unwrap(); - fs::write(&config, "sources = ['top.sv']\ntop = 'Top'\n[diagnostics]\ninferred_latch = 'error'\n[targets.compat.diagnostics]\ninferred_latch = 'warn'\n").unwrap(); - for build in [false, true] { + endmodule"# + }; + fs::write(project.path().join("top.sv"), source).unwrap(); let compile = |target: bool, overrides: &[&str]| { let mut command = Command::new(env!("CARGO_BIN_EXE_celox")); if build { diff --git a/crates/celox-vpi/tests/project_cli.rs b/crates/celox-vpi/tests/project_cli.rs index 43426385fbc..982b7261b75 100644 --- a/crates/celox-vpi/tests/project_cli.rs +++ b/crates/celox-vpi/tests/project_cli.rs @@ -491,6 +491,13 @@ fn top_parameters_merge_common_target_and_cli_without_editing_sv() { ); success(&output); assert_eq!(output.stdout, b"v=9 w=16\n"); + assert_eq!( + fs::read_to_string(root.path().join("top.sv")).unwrap(), + source + ); + // A VPI image runs no process. + let untimed = "module Top #(parameter W=8, parameter V=1, parameter NEXT=V+1) (output logic [W-1:0] y); assign y=NEXT; endmodule"; + fs::write(root.path().join("top.sv"), untimed).unwrap(); success(&invoke( root.path(), &[ @@ -516,8 +523,9 @@ fn top_parameters_merge_common_target_and_cli_without_editing_sv() { assert_eq!(celox::SimBackend::get_as::(sim.backend(), signal), 0); assert_eq!( fs::read_to_string(root.path().join("top.sv")).unwrap(), - source + untimed ); + fs::write(root.path().join("top.sv"), source).unwrap(); let output = invoke(root.path(), &["run", "--target", "wide", "-GMISSING=1"]); assert!(!output.status.success()); assert!( @@ -641,6 +649,14 @@ fn sv_parameter_literals_preserve_types_across_project_target_and_cli() { let output = invoke(root.path(), &[&["run"][..], &args].concat()); success(&output); assert_eq!(output.stdout, b"ok\n"); + assert_eq!( + fs::read_to_string(root.path().join("top.sv")).unwrap(), + source + ); + // A VPI image runs no process. + let (design, _) = source.split_once("initial").unwrap(); + let source = format!("{design}endmodule\n"); + fs::write(root.path().join("top.sv"), &source).unwrap(); success(&invoke( root.path(), &[&["vpi", "build"][..], &args, &["-o", "sim"]].concat(), @@ -667,17 +683,20 @@ fn sv_parameter_literals_preserve_types_across_project_target_and_cli() { #[test] fn state_mode_merges_project_target_and_cli_for_run_and_native_build() { let root = tempfile::tempdir().unwrap(); - fs::write( - root.path().join("top.sv"), - r#" + let timed = r#" module Top(output logic[3:0] y); logic[3:0] uninitialized; assign y=uninitialized; initial begin #1; $display("value=%b",y); $finish; end endmodule - "#, - ) - .unwrap(); + "#; + // A VPI image runs no process. + let untimed = r#" + module Top(output logic[3:0] y); + logic[3:0] uninitialized; + assign y=uninitialized; + endmodule + "#; fs::write( root.path().join("celox.toml"), "sources=['top.sv']\ntop='Top'\nfour_state=true\n[targets.two]\nfour_state=false\n", @@ -693,9 +712,11 @@ fn state_mode_merges_project_target_and_cli_for_run_and_native_build() { true, ), ] { + fs::write(root.path().join("top.sv"), timed).unwrap(); let run = invoke(root.path(), &[&["run"][..], &args].concat()); success(&run); assert_eq!(String::from_utf8(run.stdout).unwrap(), expected); + fs::write(root.path().join("top.sv"), untimed).unwrap(); success(&invoke( root.path(), &[&["vpi", "build"][..], &args, &["-o", "sim"]].concat(), @@ -798,6 +819,12 @@ fn sv_cli_defaults_to_two_state_for_run_and_native_images() { let run = invoke(root.path(), &["run", "top.sv", "--top", "Top"]); success(&run); assert_eq!(run.stdout, b"value=0000\n"); + // A VPI image runs no process. + fs::write( + root.path().join("top.sv"), + "module Top(output logic[3:0] y); logic[3:0] uninitialized; assign y=uninitialized; endmodule", + ) + .unwrap(); success(&invoke( root.path(), &["vpi", "build", "top.sv", "--top", "Top", "-o", "sim"], @@ -816,9 +843,7 @@ fn sv_cli_defaults_to_two_state_for_run_and_native_images() { #[test] fn timescale_reaches_run_and_native_images_with_target_and_cli_precedence() { let root = tempfile::tempdir().unwrap(); - fs::write( - root.path().join("top.sv"), - r#" + let timed = r#" `timescale 1ns/1ps module Top(input bit clk, output bit q); always_ff @(posedge clk) q <= !q; @@ -827,9 +852,14 @@ module Top(input bit clk, output bit q); #1ns $finish; end endmodule -"#, - ) - .unwrap(); +"#; + // A VPI image runs no process. + let untimed = r#" +`timescale 1ns/1ps +module Top(input bit clk, output bit q); + always_ff @(posedge clk) q <= !q; +endmodule +"#; fs::write( root.path().join("celox.toml"), r#" @@ -847,12 +877,14 @@ timescale = "1ns/1fs" (vec!["--target", "fine", "--timescale", "10ns/100fs"], -13), (vec!["--timescale", "1ns/10ps"], -12), ] { + fs::write(root.path().join("top.sv"), timed).unwrap(); let output = invoke(root.path(), &[vec!["run"], options.clone()].concat()); success(&output); assert!( String::from_utf8_lossy(&output.stdout).contains(&format!("SCALE -12 {precision}")), "{output:?}" ); + fs::write(root.path().join("top.sv"), untimed).unwrap(); success(&invoke( root.path(), &[vec!["vpi", "build", "-o", "sim"], options].concat(), @@ -863,6 +895,7 @@ timescale = "1ns/1fs" unsafe { celox::NativeProgramInstance::from_attached_bytes(&bytes) }.unwrap(); assert_eq!(instance.time_precision().exponent(), precision); } + fs::write(root.path().join("top.sv"), timed).unwrap(); rejected( &invoke(root.path(), &["run", "--timescale", "1ps/1ns"]), "invalid timescale", diff --git a/crates/celox/examples/sv_tests.rs b/crates/celox/examples/sv_tests.rs index 6f0f9f89a84..9d53159778a 100644 --- a/crates/celox/examples/sv_tests.rs +++ b/crates/celox/examples/sv_tests.rs @@ -165,7 +165,8 @@ fn run(options: &Options) -> Result<(), String> { let top = select_top(&parsed, options.top.as_deref())?; match options.mode { Mode::Parsing => unreachable!("parsing returned before root selection"), - Mode::Elaboration => celox::Simulator::from_sv_sources(sources, &top) + // A Simulator rejects designs with processes, which it does not run. + Mode::Elaboration => celox::Simulation::from_sv_sources(sources, &top) .four_state(options.four_state) .build() .map(|_| ()) diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 62d2ebb11a7..1d1990bb5a4 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -401,6 +401,7 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) live_signals: std::collections::BTreeSet, pub(crate) declaration_startup: Option>, pub(crate) processes: Vec>, + pub(crate) process_origins: Vec, pub(crate) watches: Vec>, pub(crate) wait_sites: Vec>, pub(crate) nba_sites: Vec>, @@ -514,6 +515,7 @@ impl NativeProgramImage { dead_store_policy: self.runtime_schema.dead_store_policy, live_signals: self.runtime_schema.live_signals.iter().copied().collect(), processes: self.runtime_schema.processes.clone(), + process_origins: self.runtime_schema.process_origins.clone(), watches: self.runtime_schema.watches.clone(), wait_sites: self.runtime_schema.wait_sites.clone(), nba_sites: self.runtime_schema.nba_sites.clone(), @@ -2408,6 +2410,7 @@ fn compile_program( .copied() .collect(), processes: sir.runtime().runtime_schema.processes.clone(), + process_origins: sir.runtime().runtime_schema.process_origins.clone(), watches: sir.runtime().runtime_schema.watches.clone(), wait_sites: sir.runtime().runtime_schema.wait_sites.clone(), nba_sites: sir.runtime().runtime_schema.nba_sites.clone(), diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index ccef7b3ce43..0eea3828822 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -41,7 +41,7 @@ pub use backend::SimulatorErrorCode as RuntimeErrorCode; pub use backend::{ EventHandle, LayoutRequirements, MemoryLayout, MemoryLayoutMode, SimBackend, get_byte_size, }; -pub use celox_design::{DomainKind, ElaboratedDesign, EventTopology, RuntimeSchema}; +pub use celox_design::{DomainKind, ElaboratedDesign, EventTopology, ProcessOrigin, RuntimeSchema}; pub use celox_frontend_core::FrontendArtifactError; pub use celox_frontend_sdk as frontend_sdk; pub use celox_frontend_sdk::FrontendArtifact; diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 4a6c96beffd..cef829cd455 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -323,6 +323,11 @@ impl Simulation { self.simulator.warnings() } + /// Returns a reference to the compiled SIR program. + pub fn program(&self) -> &crate::ir::RuntimeProgram { + self.simulator.program() + } + /// Save the design state, simulation time, clocks and pending events. pub fn checkpoint(&self) -> Result, CheckpointError> { if self.state.is_suspended() { @@ -897,23 +902,16 @@ mod process_tests { .unwrap(), steps as u64, ); - let image = builder(four_state, steps) + // A native image starts an untimed Simulator, which runs no + // process. + let error = builder(four_state, steps) .compile_native() - .unwrap() - .into_program_image(); - let image = crate::NativeProgramImage::from_container_bytes( - &image.to_container_bytes().unwrap(), - ) - .unwrap(); - check( - Simulation::new( - Simulator::from_sources(Vec::new(), "Processes") - .emit_triggers() - .build_native_from_image(image) - .unwrap(), - ), - steps as u64, - ); + .map(|_| ()) + .unwrap_err(); + assert!(matches!( + error.kind(), + crate::SimulatorErrorKind::ProcessRequiresSimulation(_) + )); } } @@ -1437,7 +1435,7 @@ mod four_state_edge_tests { use num_bigint::BigUint; use super::Simulation; - use crate::{SimBackend, Simulator}; + use crate::SimBackend; /// The levels of a clock walking all twelve changes between 0, 1, x and /// z (an Euler circuit from 0), as (value, mask), with the posedges and @@ -1461,15 +1459,15 @@ mod four_state_edge_tests { macro_rules! on_every_backend { ($builder:expr, $check:ident) => {{ let builder = || $builder.four_state(true).emit_triggers(); - $check(Simulation::new(builder().build_interpreter().unwrap())); - $check(Simulation::new(builder().build_cranelift().unwrap())); - $check(Simulation::new(builder().build_wasm().unwrap())); - $check(Simulation::new(builder().build_tiered().unwrap())); + $check(builder().build_interpreter().unwrap()); + $check(builder().build_cranelift().unwrap()); + $check(builder().build_wasm().unwrap()); + $check(builder().build_tiered().unwrap()); #[cfg(any( all(target_arch = "x86_64", not(feature = "arm64-codegen")), all(target_arch = "aarch64", not(feature = "x86_64-codegen")) ))] - $check(Simulation::new(builder().build_native().unwrap())); + $check(builder().build_native().unwrap()); }}; } @@ -1631,7 +1629,7 @@ mod four_state_edge_tests { ); } } - on_every_backend!(Simulator::from_frontend(wait_design()), check); + on_every_backend!(Simulation::from_frontend(wait_design()), check); } #[test] @@ -1643,7 +1641,7 @@ mod four_state_edge_tests { assert_eq!(get(&mut sim, "neg"), neg.into(), "negedges at {time}"); } } - on_every_backend!(Simulator::from_frontend(process_design()), check); + on_every_backend!(Simulation::from_frontend(process_design()), check); } const REGISTER_CLOCK: &str = r#" @@ -1703,7 +1701,7 @@ module Top ( assert_eq!(get(&mut sim, "neg"), (neg + 1).into(), "negedges at {time}"); } } - on_every_backend!(Simulator::builder(REGISTER_CLOCK, "Top"), check); + on_every_backend!(Simulation::builder(REGISTER_CLOCK, "Top"), check); } /// A clock computed combinationally from a register, `e ? a & b : 'z`, @@ -1776,7 +1774,7 @@ module Top ( assert_eq!(get(&mut sim, "neg"), (neg + 1).into(), "negedges at {time}"); } } - on_every_backend!(Simulator::builder(SOURCE, "Top"), check); + on_every_backend!(Simulation::builder(SOURCE, "Top"), check); } /// Asynchronous resets that are registers. An edge to x or z runs the @@ -1863,7 +1861,7 @@ module Top ( assert_eq!(get(&mut sim, "hits_l"), hits.into(), "rl at {time}"); } } - on_every_backend!(Simulator::builder(SOURCE, "Top"), check); + on_every_backend!(Simulation::builder(SOURCE, "Top"), check); } /// The edge baseline of a clock left at x survives a checkpoint: the @@ -1892,6 +1890,6 @@ module Top ( sim.run_until(15).unwrap(); assert_eq!(get(&mut sim, "pos"), 1u8.into(), "after a state load"); } - on_every_backend!(Simulator::builder(REGISTER_CLOCK, "Top"), check); + on_every_backend!(Simulation::builder(REGISTER_CLOCK, "Top"), check); } } diff --git a/crates/celox/src/simulation/runtime_core_tests.rs b/crates/celox/src/simulation/runtime_core_tests.rs index 722e68785bc..53e0d326276 100644 --- a/crates/celox/src/simulation/runtime_core_tests.rs +++ b/crates/celox/src/simulation/runtime_core_tests.rs @@ -13,33 +13,19 @@ use crate::{SimBackend, Simulator, SimulatorBuilder}; use celox_runtime::backend::EventHandle as _; /// Run `$body` with `$sim` bound to a timed simulation of `$builder` on -/// every backend, including a native program image that went through its -/// container. +/// every backend. macro_rules! on_every_backend { - ($builder:expr, $top:expr, |$sim:ident| $body:block) => {{ + ($builder:expr, |$sim:ident| $body:block) => {{ fn run(mut $sim: Simulation) $body - run(Simulation::new($builder.build_interpreter().unwrap())); - run(Simulation::new($builder.build_cranelift().unwrap())); - run(Simulation::new($builder.build_wasm().unwrap())); - run(Simulation::new($builder.build_tiered().unwrap())); + run($builder.build_interpreter().unwrap()); + run($builder.build_cranelift().unwrap()); + run($builder.build_wasm().unwrap()); + run($builder.build_tiered().unwrap()); #[cfg(any( all(target_arch = "x86_64", not(feature = "arm64-codegen")), all(target_arch = "aarch64", not(feature = "x86_64-codegen")) ))] - { - run(Simulation::new($builder.build_native().unwrap())); - let image = $builder.compile_native().unwrap().into_program_image(); - let image = crate::NativeProgramImage::from_container_bytes( - &image.to_container_bytes().unwrap(), - ) - .unwrap(); - run(Simulation::new( - Simulator::from_sources(Vec::new(), $top) - .emit_triggers() - .build_native_from_image(image) - .unwrap(), - )); - } + run($builder.build_native().unwrap()); }}; } @@ -174,8 +160,8 @@ fn wait(signal: SignalId, edge: EventEdge) -> Statement { } } -fn builder(artifact: &FrontendArtifact, four_state: bool) -> SimulatorBuilder<'static, Simulator> { - Simulator::from_frontend(artifact.clone()) +fn builder(artifact: &FrontendArtifact, four_state: bool) -> SimulatorBuilder<'static, Simulation> { + Simulation::from_frontend(artifact.clone()) .four_state(four_state) .emit_triggers() } @@ -216,24 +202,20 @@ fn process_optimization_preserves_state_changes_between_continuations() { crate::OptLevel::O1, crate::OptLevel::O2, ] { - on_every_backend!( - builder(&artifact, four_state).opt_level(level), - "OptimizedProcess", - |sim| { - sim.run_until(0).unwrap(); - assert_eq!(value(&mut sim, "result"), 5); - sim.run_until(1).unwrap(); - assert_eq!(value(&mut sim, "shared"), 9); - assert_eq!(value(&mut sim, "result"), 5); - sim.run_until(2).unwrap(); - assert_eq!(value(&mut sim, "result"), 9); - assert!(!sim.is_finished()); - sim.run_until(20).unwrap(); - assert!(sim.is_finished()); - assert_eq!(sim.time(), 3); - assert_eq!(value(&mut sim, "result"), 9); - } - ); + on_every_backend!(builder(&artifact, four_state).opt_level(level), |sim| { + sim.run_until(0).unwrap(); + assert_eq!(value(&mut sim, "result"), 5); + sim.run_until(1).unwrap(); + assert_eq!(value(&mut sim, "shared"), 9); + assert_eq!(value(&mut sim, "result"), 5); + sim.run_until(2).unwrap(); + assert_eq!(value(&mut sim, "result"), 9); + assert!(!sim.is_finished()); + sim.run_until(20).unwrap(); + assert!(sim.is_finished()); + assert_eq!(sim.time(), 3); + assert_eq!(value(&mut sim, "result"), 9); + }); } } } @@ -259,7 +241,7 @@ fn pulse(four_state: bool) -> FrontendArtifact { fn a_pulse_within_one_process_run_wakes_posedge_once() { for four_state in [false, true] { let artifact = pulse(four_state); - on_every_backend!(builder(&artifact, four_state), "Pulse", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { sim.run_until(0).unwrap(); assert_eq!(value(&mut sim, "waits"), 0); sim.run_until(5).unwrap(); @@ -309,7 +291,7 @@ fn repeated_edges(four_state: bool) -> FrontendArtifact { fn repeated_edges_in_one_slot_trigger_a_domain_repeatedly() { for four_state in [false, true] { let artifact = repeated_edges(four_state); - on_every_backend!(builder(&artifact, four_state), "Repeated", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { sim.run_until(1).unwrap(); assert_eq!(value(&mut sim, "wakes"), 2); // Both evaluations publish, the later one last. @@ -337,7 +319,7 @@ fn host_clock(four_state: bool) -> FrontendArtifact { fn host_writes_trigger_registers_and_wake_waits() { for four_state in [false, true] { let artifact = host_clock(four_state); - on_every_backend!(builder(&artifact, four_state), "HostClock", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { let clk = sim.signal("clk"); sim.modify(|io| io.set(clk, 0u8)).unwrap(); sim.run_until(0).unwrap(); @@ -387,7 +369,7 @@ fn level(four_state: bool) -> FrontendArtifact { fn level_waits_block_until_their_condition_holds() { for four_state in [false, true] { let artifact = level(four_state); - on_every_backend!(builder(&artifact, four_state), "Level", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { sim.run_until(2).unwrap(); assert_eq!(value(&mut sim, "first"), 0); sim.run_until(3).unwrap(); @@ -446,7 +428,7 @@ fn zero_delays(four_state: bool) -> FrontendArtifact { fn zero_delays_order_against_flip_flops_and_nonblocking_assignments() { for four_state in [false, true] { let artifact = zero_delays(four_state); - on_every_backend!(builder(&artifact, four_state), "ZeroDelays", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { sim.run_until(1).unwrap(); assert_eq!(value(&mut sim, "q"), 3, "the domain evaluated before #0"); assert_eq!( @@ -509,7 +491,7 @@ fn nonblocking(four_state: bool) -> FrontendArtifact { fn nonblocking_assignments_publish_in_order() { for four_state in [false, true] { let artifact = nonblocking(four_state); - on_every_backend!(builder(&artifact, four_state), "Nonblocking", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { sim.run_until(1).unwrap(); assert_eq!(value(&mut sim, "q"), 0); assert_eq!( @@ -541,7 +523,7 @@ fn finishing(four_state: bool) -> FrontendArtifact { fn finish_freezes_the_simulation() { for four_state in [false, true] { let artifact = finishing(four_state); - on_every_backend!(builder(&artifact, four_state), "Finishing", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { let clk = sim.signal("clk"); sim.modify(|io| io.set(clk, 0u8)).unwrap(); sim.add_clock("clk", 2, 1); @@ -578,7 +560,7 @@ fn waiting(four_state: bool) -> FrontendArtifact { fn checkpoints_restore_a_waiting_process() { for four_state in [false, true] { let artifact = waiting(four_state); - on_every_backend!(builder(&artifact, four_state), "Waiting", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { let go = sim.signal("go"); sim.modify(|io| io.set(go, 0u8)).unwrap(); sim.run_until(1).unwrap(); @@ -602,7 +584,7 @@ fn checkpoints_restore_a_waiting_process() { fn state_files_carry_waiting_processes_across_backends() { // Saved on the interpreter, loaded into every backend. let artifact = waiting(true); - let mut source = Simulation::new(builder(&artifact, true).build_interpreter().unwrap()); + let mut source = builder(&artifact, true).build_interpreter().unwrap(); let go = source.signal("go"); source.modify(|io| io.set(go, 0u8)).unwrap(); source.run_until(1).unwrap(); @@ -615,7 +597,7 @@ fn state_files_carry_waiting_processes_across_backends() { file.write_to(&mut bytes).unwrap(); let file = celox_runtime::StateFile::read_from(bytes.as_slice()).unwrap(); STATE.with(|state| *state.borrow_mut() = Some(file)); - on_every_backend!(builder(&artifact, true), "Waiting", |sim| { + on_every_backend!(builder(&artifact, true), |sim| { let file = STATE.with(|state| state.borrow().clone().unwrap()); sim.load_state(&file).unwrap(); assert_eq!(sim.time(), 3); @@ -659,7 +641,7 @@ fn edge_order(four_state: bool) -> FrontendArtifact { fn edge_woken_processes_read_flip_flops_before_the_edge_publishes() { for four_state in [false, true] { let artifact = edge_order(four_state); - on_every_backend!(builder(&artifact, four_state), "EdgeOrder", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { let clk = sim.signal("clk"); sim.modify(|io| io.set(clk, 0u8)).unwrap(); sim.add_clock("clk", 10, 5); @@ -708,7 +690,7 @@ fn comb_pulse(four_state: bool) -> FrontendArtifact { fn comb_processes_pulse_only_when_an_input_changes() { for four_state in [false, true] { let artifact = comb_pulse(four_state); - on_every_backend!(builder(&artifact, four_state), "CombPulse", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { let a = sim.signal("a"); let b = sim.signal("b"); sim.modify(|io| { @@ -762,14 +744,14 @@ endmodule fn imperative_comb_units_pulse_only_when_an_input_changes() { for four_state in [false, true] { let build = || { - Simulator::from_sv_sources( + Simulation::from_sv_sources( vec![(SOURCE, std::path::Path::new("comb_pulse.sv"))], "Top", ) .four_state(four_state) .emit_triggers() }; - on_every_backend!(build(), "Top", |sim| { + on_every_backend!(build(), |sim| { let a = sim.signal("a"); let b = sim.signal("b"); sim.modify(|io| { @@ -894,8 +876,8 @@ fn processes_leave_the_flip_flop_path_of_a_time_slot_unchanged() { .build_native() .unwrap() }; - let plain = recorded_steps(Simulation::new(build(false)), 4); - let timed = recorded_steps(Simulation::new(build(true)), 4); + let plain = recorded_steps(build(false), 4); + let timed = recorded_steps(build(true), 4); // Rising and falling edges of a plain design: one settle, the fused // evaluate-and-apply of the domain, and the settle after it. assert_eq!(plain[0], ["comb", "eval_apply", "comb"]); @@ -954,7 +936,7 @@ fn republished(four_state: bool) -> FrontendArtifact { fn every_publication_of_a_domain_is_an_update() { for four_state in [false, true] { let artifact = republished(four_state); - on_every_backend!(builder(&artifact, four_state), "Republished", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { sim.run_until(1).unwrap(); assert_eq!(value(&mut sim, "q"), 0); assert_eq!( @@ -997,7 +979,7 @@ fn pulse_around_nba(four_state: bool) -> FrontendArtifact { fn a_pulse_around_a_queued_nonblocking_assignment_is_an_edge() { for four_state in [false, true] { let artifact = pulse_around_nba(four_state); - on_every_backend!(builder(&artifact, four_state), "PulseAroundNba", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { sim.run_until(2).unwrap(); assert_eq!(value(&mut sim, "r"), 2); assert_eq!(value(&mut sim, "waits"), 1); @@ -1011,7 +993,7 @@ fn host_write_pulses_survive_checkpoints_and_state_files() { // A pulse written by the host and saved before the step that shows it // to the waits. let artifact = waiting(false); - on_every_backend!(builder(&artifact, false), "Waiting", |sim| { + on_every_backend!(builder(&artifact, false), |sim| { let go = sim.signal("go"); sim.modify(|io| io.set(go, 0u8)).unwrap(); sim.run_until(1).unwrap(); @@ -1041,7 +1023,7 @@ fn host_write_pulses_survive_checkpoints_and_state_files() { #[test] fn loading_a_finished_state_freezes_the_simulation() { let artifact = finishing(false); - on_every_backend!(builder(&artifact, false), "Finishing", |sim| { + on_every_backend!(builder(&artifact, false), |sim| { let clk = sim.signal("clk"); sim.modify(|io| io.set(clk, 0u8)).unwrap(); let start = sim.save_state().unwrap(); @@ -1076,10 +1058,10 @@ module Top(input logic go, output logic [7:0] y); endmodule "#; let build = || { - Simulator::from_sv_sources(vec![(SOURCE, std::path::Path::new("finish.sv"))], "Top") + Simulation::from_sv_sources(vec![(SOURCE, std::path::Path::new("finish.sv"))], "Top") .emit_triggers() }; - on_every_backend!(build(), "Top", |sim| { + on_every_backend!(build(), |sim| { let go = sim.signal("go"); sim.modify(|io| io.set(go, 0u8)).unwrap(); sim.eval_comb().unwrap(); @@ -1129,7 +1111,7 @@ fn interleaved(four_state: bool) -> FrontendArtifact { fn interleaved_publications_keep_each_signals_edges() { for four_state in [false, true] { let artifact = interleaved(four_state); - on_every_backend!(builder(&artifact, four_state), "Interleaved", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { sim.run_until(1).unwrap(); assert_eq!(value(&mut sim, "qa"), 0); assert_eq!(value(&mut sim, "rises"), 1); @@ -1141,7 +1123,7 @@ fn interleaved_publications_keep_each_signals_edges() { #[test] fn state_files_reject_queued_assignments_outside_their_target() { let artifact = nonblocking(false); - let mut sim = Simulation::new(builder(&artifact, false).build_interpreter().unwrap()); + let mut sim = builder(&artifact, false).build_interpreter().unwrap(); sim.run_until(0).unwrap(); let mut file = sim.save_state().unwrap(); file.schedule @@ -1181,7 +1163,7 @@ fn low_then_high(four_state: bool) -> FrontendArtifact { fn a_signal_written_again_compares_with_its_preceding_value() { for four_state in [false, true] { let artifact = low_then_high(four_state); - on_every_backend!(builder(&artifact, four_state), "LowThenHigh", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { sim.run_until(2).unwrap(); assert_eq!(value(&mut sim, "clk"), 1); assert_eq!(value(&mut sim, "ffs"), 1); @@ -1210,7 +1192,7 @@ fn nba_pulse(four_state: bool) -> FrontendArtifact { fn queued_nonblocking_pulses_trigger_flip_flops() { for four_state in [false, true] { let artifact = nba_pulse(four_state); - on_every_backend!(builder(&artifact, four_state), "NbaPulse", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { sim.run_until(2).unwrap(); assert_eq!(value(&mut sim, "clk"), 0); assert_eq!(value(&mut sim, "ffs"), 1); @@ -1242,7 +1224,7 @@ fn comb_override(four_state: bool) -> FrontendArtifact { fn comb_processes_may_overwrite_their_own_targets() { for four_state in [false, true] { let artifact = comb_override(four_state); - on_every_backend!(builder(&artifact, four_state), "CombOverride", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { let a = sim.signal("a"); let low = sim.signal("low"); sim.modify(|io| { @@ -1260,12 +1242,10 @@ fn comb_processes_may_overwrite_their_own_targets() { fn the_waveform_records_the_finish() { let artifact = finishing(false); let path = std::env::temp_dir().join(format!("celox-finish-{}.vcd", std::process::id())); - let mut sim = Simulation::new( - builder(&artifact, false) - .vcd(&path) - .build_interpreter() - .unwrap(), - ); + let mut sim = builder(&artifact, false) + .vcd(&path) + .build_interpreter() + .unwrap(); let clk = sim.signal("clk"); sim.modify(|io| io.set(clk, 0u8)).unwrap(); sim.add_clock("clk", 2, 1); @@ -1281,7 +1261,7 @@ fn the_waveform_records_the_finish() { #[test] fn state_files_reject_baselines_of_the_wrong_kind() { let artifact = waiting(false); - let mut sim = Simulation::new(builder(&artifact, false).build_interpreter().unwrap()); + let mut sim = builder(&artifact, false).build_interpreter().unwrap(); let go = sim.signal("go"); sim.modify(|io| io.set(go, 0u8)).unwrap(); sim.run_until(1).unwrap(); @@ -1311,12 +1291,11 @@ module Top(input logic go, output logic [7:0] y); end endmodule "#; - let mut sim = Simulation::new( - Simulator::from_sv_sources(vec![(SOURCE, std::path::Path::new("finish.sv"))], "Top") + let mut sim = + Simulation::from_sv_sources(vec![(SOURCE, std::path::Path::new("finish.sv"))], "Top") .emit_triggers() .build_interpreter() - .unwrap(), - ); + .unwrap(); let go = sim.signal("go"); sim.modify(|io| io.set(go, 0u8)).unwrap(); sim.run_until(0).unwrap(); @@ -1351,7 +1330,7 @@ fn dead_store_elimination_keeps_signals_a_wait_watches() { for four_state in [false, true] { let artifact = wait_on_comb(four_state); let optimized = || builder(&artifact, four_state).opt_level(crate::OptLevel::O2); - on_every_backend!(optimized(), "WaitOnComb", |sim| { + on_every_backend!(optimized(), |sim| { let (a, b) = (sim.signal("a"), sim.signal("b")); sim.modify(|io| { io.set(a, 0u8); @@ -1399,7 +1378,7 @@ fn nba_pulse_after_one_domain(four_state: bool) -> FrontendArtifact { fn nonblocking_pulses_after_a_single_domain_trigger_their_domain() { for four_state in [false, true] { let artifact = nba_pulse_after_one_domain(four_state); - on_every_backend!(builder(&artifact, four_state), "NbaPulseOneDomain", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { sim.schedule("clk", 0, 0).unwrap(); sim.run_until(0).unwrap(); for edge in 1..=3u64 { @@ -1434,7 +1413,7 @@ fn pulse_across_waves(four_state: bool) -> FrontendArtifact { fn a_pulse_across_two_waves_of_a_slot_is_an_edge() { for four_state in [false, true] { let artifact = pulse_across_waves(four_state); - on_every_backend!(builder(&artifact, four_state), "PulseAcrossWaves", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { sim.run_until(0).unwrap(); assert_eq!(value(&mut sim, "rises"), 0); sim.run_until(2).unwrap(); @@ -1492,12 +1471,8 @@ fn zero_time_loops(four_state: bool) -> [FrontendArtifact; 3] { #[test] fn zero_time_loops_exhaust_the_slot_budget() { for four_state in [false, true] { - for (artifact, top) in - zero_time_loops(four_state) - .into_iter() - .zip(["InactiveLoop", "PingPong", "Spin"]) - { - on_every_backend!(builder(&artifact, four_state), top, |sim| { + for artifact in zero_time_loops(four_state) { + on_every_backend!(builder(&artifact, four_state), |sim| { sim.state.set_slot_budgets(256, 2); sim.run_until(0).unwrap(); let error = sim.run_until(5).unwrap_err(); @@ -1547,7 +1522,7 @@ fn write_raw(sim: &mut Simulation, signal: crate::SignalRef, v fn raw_host_writes_wake_waits_at_the_current_time() { for four_state in [false, true] { let artifact = raw_go(four_state); - on_every_backend!(builder(&artifact, four_state), "RawGo", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { let go = sim.signal("go"); write_raw(&mut sim, go, 0); sim.note_raw_writes(); @@ -1593,7 +1568,7 @@ fn comb_reads_unwritten_bits(four_state: bool) -> FrontendArtifact { fn comb_processes_rerun_on_bits_they_do_not_write() { for four_state in [false, true] { let artifact = comb_reads_unwritten_bits(four_state); - on_every_backend!(builder(&artifact, four_state), "CombBits", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { let a = sim.signal("a"); for (time, input, expected) in [(1, 0u8, 0u64), (2, 1, 3), (3, 0, 0), (4, 1, 3)] { sim.modify(|io| io.set(a, input)).unwrap(); @@ -1640,7 +1615,7 @@ fn gated_clocks_see_their_edges_with_processes() { for four_state in [false, true] { for inactive in [false, true] { let artifact = gated_clock_with_process(four_state, inactive); - on_every_backend!(builder(&artifact, four_state), "GatedClock", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { let en = sim.signal("en"); sim.modify(|io| io.set(en, 1u8)).unwrap(); sim.schedule("clk", 0, 0).unwrap(); @@ -1689,7 +1664,7 @@ fn host_writes_do_not_hold_steps_at_the_current_time() { for four_state in [false, true] { for waiting in [false, true] { let artifact = host_writes_with_processes(four_state, waiting); - on_every_backend!(builder(&artifact, four_state), "HostSteps", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { for (time, level) in [(10, 1), (20, 0), (30, 1)] { sim.schedule("clk", time, level).unwrap(); } @@ -1742,7 +1717,7 @@ fn counted_with_comb_writer(four_state: bool) -> FrontendArtifact { fn waits_on_counted_signals_see_uncounted_writers() { for four_state in [false, true] { let artifact = counted_with_comb_writer(four_state); - on_every_backend!(builder(&artifact, four_state), "CountedComb", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { let a = sim.signal("a"); sim.modify(|io| io.set(a, 0u8)).unwrap(); sim.run_until(1).unwrap(); @@ -1796,7 +1771,7 @@ fn comb_pulse_between_waves(four_state: bool) -> FrontendArtifact { fn waits_see_combinational_pulses_between_flip_flop_waves() { for four_state in [false, true] { let artifact = comb_pulse_between_waves(four_state); - on_every_backend!(builder(&artifact, four_state), "CombPulse", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { sim.schedule("clk", 0, 0).unwrap(); for edge in 1..=4u64 { sim.schedule("clk", 2 * edge - 1, 1).unwrap(); @@ -1838,7 +1813,7 @@ fn long_loop(four_state: bool) -> FrontendArtifact { fn long_finite_loops_yield_rarely() { for four_state in [false, true] { let artifact = long_loop(four_state); - on_every_backend!(builder(&artifact, four_state), "LongLoop", |sim| { + on_every_backend!(builder(&artifact, four_state), |sim| { sim.state.set_slot_budgets(256, 2); sim.run_until(2).unwrap(); assert_eq!(value(&mut sim, "i"), 1 << 17); @@ -2182,11 +2157,7 @@ fn executor_call_traces_are_unchanged() { let suffix = if four_state { "_4state" } else { "" }; insta::assert_snapshot!( format!("trace_{name}{suffix}_interpreter"), - trace( - Simulation::new(builder().build_interpreter().unwrap()), - &ops, - observe - ) + trace(builder().build_interpreter().unwrap(), &ops, observe) ); #[cfg(any( all(target_arch = "x86_64", not(feature = "arm64-codegen")), @@ -2195,11 +2166,7 @@ fn executor_call_traces_are_unchanged() { { insta::assert_snapshot!( format!("trace_{name}{suffix}_native"), - trace( - Simulation::new(builder().build_native().unwrap()), - &ops, - observe - ) + trace(builder().build_native().unwrap(), &ops, observe) ); // Parallel flip-flop kernels; their calls are those of the // plain RTL design. @@ -2208,11 +2175,7 @@ fn executor_call_traces_are_unchanged() { } insta::assert_snapshot!( format!("trace_{name}{suffix}_native_threads"), - trace( - Simulation::new(builder().threads(4).build_native().unwrap()), - &ops, - observe - ) + trace(builder().threads(4).build_native().unwrap(), &ops, observe) ); } } @@ -2298,14 +2261,10 @@ module Top ( fn executor_call_traces_of_veryl_clock_domains_are_unchanged() { for &(name, source, inputs, observe) in VERYL_TRACE_DESIGNS { let ops = stimulus(inputs); - let builder = || Simulator::builder(source, "Top").emit_triggers(); + let builder = || Simulation::builder(source, "Top").emit_triggers(); insta::assert_snapshot!( format!("trace_{name}_interpreter"), - trace( - Simulation::new(builder().build_interpreter().unwrap()), - &ops, - observe - ) + trace(builder().build_interpreter().unwrap(), &ops, observe) ); insta::assert_snapshot!( format!("trace_{name}_default"), @@ -2472,12 +2431,10 @@ mod sv_traces { insta::assert_snapshot!( format!("trace_{name}_interpreter"), trace( - Simulation::new( - Simulator::from_sv_sources(sources(), "Top") - .emit_triggers() - .build_interpreter() - .unwrap() - ), + Simulation::from_sv_sources(sources(), "Top") + .emit_triggers() + .build_interpreter() + .unwrap(), &ops, observe ) @@ -2554,11 +2511,11 @@ fn public_time_setter_publishes_time_before_design_evaluation() { "#; for four_state in [false, true] { let build = || { - Simulator::from_sv_sources(vec![(source, std::path::Path::new("time.sv"))], "Top") + Simulation::from_sv_sources(vec![(source, std::path::Path::new("time.sv"))], "Top") .four_state(four_state) .emit_triggers() }; - on_every_backend!(build(), "Top", |sim| { + on_every_backend!(build(), |sim| { let a = sim.signal("a"); let y = sim.signal("y"); sim.state.set_time(&mut sim.simulator.backend, 5_000); diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index aacbfd00d4f..919968af2c9 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1720,58 +1720,19 @@ mod host { injected_components: crate::InjectedComponents, } - fn validate_untimed_host_requests( + /// `Simulator` runs no process kernel, so a design with one would + /// simulate wrongly without any error. + fn validate_untimed_processes( program: &crate::ir::RuntimeProgram, ) -> Result<(), SimulatorError> { - if program - .runtime_schema - .host_request_sites - .iter() - .any(|site| site.kind == celox_design::HostRequestKind::Distribution) - { - return Err(SimulatorError::from(crate::RuntimeErrorCode::Runtime { - message: "probabilistic distributions require Simulation; Simulator does not execute scheduled process kernels".into(), - signals: Vec::new(), - })); - } - if program - .runtime_schema - .host_request_sites - .iter() - .any(|site| site.kind == celox_design::HostRequestKind::Vcd) - { - return Err(SimulatorError::from(crate::RuntimeErrorCode::Runtime { - message: "source VCD controls require Simulation; Simulator does not execute initial process kernels".into(), - signals: Vec::new(), - })); - } - if program - .runtime_schema - .host_request_sites - .iter() - .any(|site| site.kind == celox_design::HostRequestKind::Scan) - { - return Err(SimulatorError::from(crate::RuntimeErrorCode::Runtime { - message:"formatted input requires Simulation; Simulator does not execute initial process kernels".into(),signals:Vec::new(), - })); - } - if program - .runtime_schema - .processes - .iter() - .any(|slots| slots.requires_timed_simulation) - || program - .runtime_schema - .host_request_sites - .iter() - .any(|site| site.requires_timed_simulation) - { - return Err(SimulatorError::from(crate::RuntimeErrorCode::Runtime { - message: "edge procedures using system file I/O, plusargs, or VCD controls require Simulation; Simulator does not execute scheduled process kernels".into(), - signals: Vec::new(), - })); - } - Ok(()) + let schema = &program.runtime_schema; + if schema.processes.is_empty() { + return Ok(()); + } + let origin = schema.process_origins.first().cloned().unwrap_or_default(); + Err(SimulatorError::new( + SimulatorErrorKind::ProcessRequiresSimulation(origin), + )) } #[cfg(any( @@ -1787,7 +1748,7 @@ mod host { vcd_path: Option, injected_components: crate::InjectedComponents, ) -> Result, SimulatorError> { - validate_untimed_host_requests(&program)?; + validate_untimed_processes(&program)?; let mut sim = Simulator::with_backend_and_program(backend, program, warnings); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); @@ -2906,7 +2867,7 @@ mod host { let (laid_out, mut warnings, options, vcd_path, injected_components) = self .into_laid_out_program(crate::backend::memory_layout::MemoryLayoutMode::Packed)?; - validate_untimed_host_requests(laid_out.runtime())?; + validate_untimed_processes(laid_out.runtime())?; if let Some(s) = phase_start { tracing::debug!( @@ -2975,7 +2936,7 @@ mod host { let (laid_out, mut warnings, options, vcd_path, injected_components) = self .into_laid_out_program(crate::backend::memory_layout::MemoryLayoutMode::Packed)?; - validate_untimed_host_requests(laid_out.runtime())?; + validate_untimed_processes(laid_out.runtime())?; if let Some(s) = phase_start { tracing::debug!( @@ -3033,7 +2994,7 @@ mod host { vcd_recording, ))? }; - validate_untimed_host_requests(laid_out.runtime())?; + validate_untimed_processes(laid_out.runtime())?; if let Some(s) = phase_start { tracing::debug!( @@ -3103,7 +3064,7 @@ mod host { vcd_recording, ))? }; - validate_untimed_host_requests(laid_out.runtime())?; + validate_untimed_processes(laid_out.runtime())?; if let Some(s) = phase_start { tracing::debug!( @@ -3153,7 +3114,7 @@ mod host { .into_laid_out_program( crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, )?; - validate_untimed_host_requests(laid_out.runtime())?; + validate_untimed_processes(laid_out.runtime())?; if let Some(start) = sir_start { tracing::debug!( "[phase-timing] into_laid_out_program total: {:?}", @@ -3197,7 +3158,7 @@ mod host { crate::backend::memory_layout::MemoryLayoutMode::ElementStrided, Some(&mut trace), )?; - validate_untimed_host_requests(laid_out.runtime())?; + validate_untimed_processes(laid_out.runtime())?; if let Some(start) = sir_start { tracing::debug!( "[phase-timing] into_laid_out_program total: {:?}", @@ -3323,7 +3284,7 @@ mod host { ) -> Result, SimulatorError> { let (laid_out, mut warnings, options, vcd_path, injected_components) = self .into_laid_out_program(crate::backend::memory_layout::MemoryLayoutMode::Packed)?; - validate_untimed_host_requests(laid_out.runtime())?; + validate_untimed_processes(laid_out.runtime())?; let backend = crate::backend::wasm_runtime::WasmBackend::new(&laid_out, &options) .map_err(|error| error.with_warnings(std::mem::take(&mut warnings)))?; let mut sim = @@ -3503,7 +3464,7 @@ mod host { }; let mut laid_out = program.into_laid_out_with_mode(self.options.four_state, layout_mode); - validate_untimed_host_requests(laid_out.runtime())?; + validate_untimed_processes(laid_out.runtime())?; if vcd_recording { laid_out.enable_vcd_tracking(); } diff --git a/crates/celox/src/simulator/error.rs b/crates/celox/src/simulator/error.rs index fa9e69fa1db..de6d0097ec0 100644 --- a/crates/celox/src/simulator/error.rs +++ b/crates/celox/src/simulator/error.rs @@ -158,6 +158,10 @@ pub enum SimulatorErrorKind { Codegen(CodegenError), /// The C functions of DPI-C imports could not be linked. Dpi(crate::DpiError), + /// The design has a process kernel, such as an `initial` block with + /// timing controls or an `always` process, which `Simulator` does not + /// run. `Simulation` runs it. + ProcessRequiresSimulation(crate::ProcessOrigin), } /// Structured failure while preparing executable simulator code. @@ -332,6 +336,10 @@ impl fmt::Display for SimulatorError { SimulatorErrorKind::Runtime(e) => write!(f, "Runtime error: {e}")?, SimulatorErrorKind::Codegen(error) => write!(f, "JIT Code generation error: {error}")?, SimulatorErrorKind::Dpi(error) => write!(f, "{error}")?, + SimulatorErrorKind::ProcessRequiresSimulation(origin) => write!( + f, + "{origin} is a process, which Simulator does not run; build a Simulation instead" + )?, } if !self.warnings.is_empty() { f.write_str("\n\n--- warnings ---\n\n")?; diff --git a/crates/celox/tests/frontends/systemverilog/file_io.rs b/crates/celox/tests/frontends/systemverilog/file_io.rs index 9dcf2bfff61..95f0067a08b 100644 --- a/crates/celox/tests/frontends/systemverilog/file_io.rs +++ b/crates/celox/tests/frontends/systemverilog/file_io.rs @@ -163,21 +163,26 @@ fn edge_host_requests_require_the_timed_api() { build().build_wasm().map(|_| ()), ]; for result in results { + let error = result.unwrap_err(); assert!( - result - .unwrap_err() - .to_string() - .contains("require Simulation") + matches!( + error.kind(), + celox::SimulatorErrorKind::ProcessRequiresSimulation(_) + ), + "{error}" ); } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] - assert!( - build() - .build_native() - .unwrap_err() - .to_string() - .contains("require Simulation") - ); + { + let error = build().build_native().map(|_| ()).unwrap_err(); + assert!( + matches!( + error.kind(), + celox::SimulatorErrorKind::ProcessRequiresSimulation(_) + ), + "{error}" + ); + } } #[test] diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index 29c87ced2f5..a605a4291a7 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -8615,7 +8615,7 @@ fn timed_task_edge_processes_allow_initialization_and_disjoint_drivers() { always @(negedge clk) begin pause(); q[1] = a; end endmodule "#; - Simulator::from_sv_sources( + celox::Simulation::from_sv_sources( vec![(source, Path::new("disjoint_timed_drivers.sv"))], "Top", ) @@ -8652,7 +8652,7 @@ fn waits_on_automatic_task_arguments_still_compile() { initial t(0); endmodule "#; - Simulator::from_sv_sources(vec![(source, Path::new("automatic_wait.sv"))], "Top") + celox::Simulation::from_sv_sources(vec![(source, Path::new("automatic_wait.sv"))], "Top") .build_cranelift() .expect("automatic arguments are private; visible go supplies the wakeup"); } diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index cd4b9642274..d7f08c6624c 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -60,33 +60,39 @@ fn veryl_assert_unknown_conditions_are_eager_on_interpreter() { } } -const URANDOM_SKIPPED_INITIAL_SOURCE: &str = r#" +const URANDOM_COMB_SOURCE: &str = r#" module Top(input int seed, output int unsigned value, reference); - initial $display("skipped initial"); always_comb value = $urandom(seed); always_comb reference = $urandom(17); endmodule "#; #[test] -fn urandom_comb_skipped_initials_work_on_interpreter_and_tiered() { - fn check(mut sim: Simulator) { +fn urandom_comb_runs_next_to_an_initial_process_on_interpreter_and_tiered() { + const SOURCE: &str = r#" + module Top(input int seed, output int unsigned value, reference); + initial $display("initial"); + always_comb value = $urandom(seed); + always_comb reference = $urandom(17); + endmodule + "#; + fn check(mut sim: celox::Simulation) { + sim.run_until(0).unwrap(); let value = sim.signal("value"); assert_ne!(sim.get(value), 0u8.into()); let seed = sim.signal("seed"); sim.modify(|io| io.set(seed, 17u8)).unwrap(); assert_eq!(sim.get(value), sim.get(sim.signal("reference"))); - assert!(sim.drain_runtime_events().is_empty()); + assert_eq!( + sim.drain_runtime_events(), + vec![celox::RuntimeEvent::Display { + message: b"initial".to_vec() + }] + ); } let builder = || { - Simulator::from_sv_sources( - vec![( - URANDOM_SKIPPED_INITIAL_SOURCE, - Path::new("random_skipped_initial.sv"), - )], - "Top", - ) - .four_state(true) + celox::Simulation::from_sv_sources(vec![(SOURCE, Path::new("random_initial.sv"))], "Top") + .four_state(true) }; check(builder().build_interpreter().unwrap()); check(builder().build_tiered().unwrap()); @@ -142,9 +148,9 @@ sv_backends! { assert_eq!(sim.get(b), second); } - fn urandom_comb_runs_when_untimed_initials_are_skipped(sim) { - @setup { let source = URANDOM_SKIPPED_INITIAL_SOURCE; } - @build Simulator::from_sv_sources(vec![(source, Path::new("random_skipped_initial.sv"))], "Top").four_state(true); + fn urandom_comb_runs_untimed(sim) { + @setup { let source = URANDOM_COMB_SOURCE; } + @build Simulator::from_sv_sources(vec![(source, Path::new("random_comb.sv"))], "Top").four_state(true); let value = sim.signal("value"); let seed = sim.signal("seed"); assert_ne!(sim.get(value), 0u8.into()); diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 43dd2f6e75d..a4b7900eef7 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -583,13 +583,13 @@ fn nonblocking_sites_stage_only_unobserved_targets_with_one_writer() { initial begin #1; q <= stim; end endmodule "#; - let simulator = celox::Simulator::from_sv_sources( + let simulation = celox::Simulation::from_sv_sources( vec![(source, std::path::Path::new("staged_sites.sv"))], "Top", ) .build() .unwrap(); - let program = simulator.program(); + let program = simulation.program(); let mut staged: Vec<_> = ["stim", "blocking", "a", "b", "d", "e", "s", "q"] .into_iter() .filter(|name| { @@ -635,10 +635,10 @@ fn narrow_nonblocking_updates_cover_staged_and_queued_sites() { .iter() .map(|source| (source.text.as_str(), source.path.as_path())) .collect::>(); - let simulator = celox::Simulator::from_sv_sources(sources, &design.top) + let simulation = celox::Simulation::from_sv_sources(sources, &design.top) .build() .unwrap(); - let program = simulator.program(); + let program = simulation.program(); let staged = |name: &str| { let target = program.get_addr(&[], &[name]).unwrap(); let sites = program diff --git a/crates/celox/tests/processes.rs b/crates/celox/tests/processes.rs index 42b300da623..6d45dc72af6 100644 --- a/crates/celox/tests/processes.rs +++ b/crates/celox/tests/processes.rs @@ -71,6 +71,21 @@ fn process_generated_clock_drives_registers() { assert_eq!(sim.time(), 100); } +#[test] +fn untimed_simulator_rejects_processes() { + let error = celox::Simulator::from_frontend(clocked_counter()) + .build() + .map(|_| ()) + .unwrap_err(); + let celox::SimulatorErrorKind::ProcessRequiresSimulation(origin) = error.kind() else { + panic!("{error}"); + }; + assert_eq!(origin.construct, "process"); + assert_eq!(origin.location, None); + assert_eq!(origin.scope.as_deref(), Some("ClockedCounter")); + assert!(error.to_string().contains("Simulation"), "{error}"); +} + #[test] fn process_suspends_and_finishes() { let byte = ValueType::bits(8).unwrap(); diff --git a/crates/celox/tests/sv_declaration_startup.rs b/crates/celox/tests/sv_declaration_startup.rs index 8a3fc4509a2..6bb88b8f387 100644 --- a/crates/celox/tests/sv_declaration_startup.rs +++ b/crates/celox/tests/sv_declaration_startup.rs @@ -441,8 +441,8 @@ fn native_runtime_declaration_startup_at_o0_and_o2() { } #[test] -fn plain_simulator_does_not_execute_initial_kernels() { - let mut simulator = celox::Simulator::from_sv_sources( +fn plain_simulator_rejects_initial_kernels() { + let error = celox::Simulator::from_sv_sources( vec![( HOST_DECLARATION, Path::new("declaration_plain_simulator.sv"), @@ -451,9 +451,15 @@ fn plain_simulator_does_not_execute_initial_kernels() { ) .plusargs(["+on"]) .build_interpreter() - .unwrap(); - let a = simulator.signal("a"); - let q = simulator.signal("q"); - assert_eq!(simulator.get(a), 0u8.into()); - assert_eq!(simulator.get(q), 0u8.into()); + .map(|_| ()) + .expect_err("Simulator accepted a design whose kernels it does not run"); + // Declaration initializers start before the initial block. + let celox::SimulatorErrorKind::ProcessRequiresSimulation(origin) = error.kind() else { + panic!("{error}"); + }; + assert_eq!(origin.construct, "declaration initializer"); + assert_eq!( + origin.location.as_deref(), + Some("declaration_plain_simulator.sv:3:3") + ); } diff --git a/crates/celox/tests/sv_distributions.rs b/crates/celox/tests/sv_distributions.rs index d9c00c69507..da3f19edc90 100644 --- a/crates/celox/tests/sv_distributions.rs +++ b/crates/celox/tests/sv_distributions.rs @@ -125,7 +125,7 @@ macro_rules! distribution_backends { let error = celox::Simulator::from_sv_sources( vec![(source, Path::new("distribution_initial.sv"))], "Top", ).$backend().err().expect("untimed initial distribution accepted"); - assert!(error.to_string().contains("distributions require Simulation")); + assert!(matches!(error.kind(), celox::SimulatorErrorKind::ProcessRequiresSimulation(_)), "{error}"); } #[test] @@ -137,7 +137,7 @@ macro_rules! distribution_backends { let error = celox::Simulator::from_sv_sources( vec![(source, Path::new("distribution_edge.sv"))], "Top", ).$backend().err().expect("untimed distribution accepted"); - assert!(error.to_string().contains("require Simulation")); + assert!(matches!(error.kind(), celox::SimulatorErrorKind::ProcessRequiresSimulation(_)), "{error}"); let mut sim = celox::Simulation::from_sv_sources( vec![(source, Path::new("distribution_edge.sv"))], "Top", ).$backend().unwrap(); diff --git a/crates/celox/tests/sv_ordinary_host_requests.rs b/crates/celox/tests/sv_ordinary_host_requests.rs index cae1da6492b..aae8463256d 100644 --- a/crates/celox/tests/sv_ordinary_host_requests.rs +++ b/crates/celox/tests/sv_ordinary_host_requests.rs @@ -20,7 +20,7 @@ macro_rules! ordinary_host_requests { let error = celox::Simulator::from_sv_sources( vec![(&source, Path::new("ordinary_host.sv"))], "Top", ).$backend().err().expect("untimed edge host process was accepted"); - assert!(error.to_string().contains("require Simulation"), "{error}"); + assert!(matches!(error.kind(), celox::SimulatorErrorKind::ProcessRequiresSimulation(_)), "{error}"); } } @@ -65,7 +65,7 @@ macro_rules! ordinary_host_requests { let error = celox::Simulator::from_sv_sources( vec![(source, Path::new("delayed_host.sv"))], "Top", ).$backend().err().expect("untimed repeating host process was accepted"); - assert!(error.to_string().contains("require Simulation"), "{error}"); + assert!(matches!(error.kind(), celox::SimulatorErrorKind::ProcessRequiresSimulation(_)), "{error}"); let mut sim = celox::Simulation::from_sv_sources( vec![(source, Path::new("delayed_host.sv"))], "Top", ).plusargs(["+ON"]).$backend().unwrap(); @@ -78,13 +78,14 @@ macro_rules! ordinary_host_requests { } #[test] - fn one_shot_initial_host_keeps_existing_untimed_builder_boundary() { + fn one_shot_initial_host_requires_simulation() { let source = r#"module Top(output int enabled); initial enabled = $test$plusargs("ON"); endmodule"#; - celox::Simulator::from_sv_sources( + let error = celox::Simulator::from_sv_sources( vec![(source, Path::new("initial_host.sv"))], "Top", - ).$backend().unwrap(); + ).$backend().err().expect("untimed initial host process was accepted"); + assert!(matches!(error.kind(), celox::SimulatorErrorKind::ProcessRequiresSimulation(_)), "{error}"); } } }; diff --git a/crates/celox/tests/sv_scan.rs b/crates/celox/tests/sv_scan.rs index a9ce1696a11..1a53f2b8501 100644 --- a/crates/celox/tests/sv_scan.rs +++ b/crates/celox/tests/sv_scan.rs @@ -122,7 +122,13 @@ fn pure_sscanf_allows_checkpoint_and_untimed_build_is_rejected() { let error = celox::Simulator::from_sv_sources(vec![(source, Path::new("scan.sv"))], "Top") .build_interpreter() .unwrap_err(); - assert!(format!("{error:?}").contains("formatted input requires Simulation")); + assert!( + matches!( + error.kind(), + celox::SimulatorErrorKind::ProcessRequiresSimulation(_) + ), + "{error}" + ); } #[test] fn rejected_formats_are_explicit() { diff --git a/crates/celox/tests/sv_scheduled_host_requests.rs b/crates/celox/tests/sv_scheduled_host_requests.rs index 7df1a9b7ff6..6d8768c56a2 100644 --- a/crates/celox/tests/sv_scheduled_host_requests.rs +++ b/crates/celox/tests/sv_scheduled_host_requests.rs @@ -236,17 +236,19 @@ macro_rules! scheduled_requests { end endmodule "#; - let result = celox::Simulator::from_sv_sources( + let error = celox::Simulator::from_sv_sources( vec![(source, Path::new("dead_host.sv"))], "Top", ) - .$backend(); + .$backend() + .err() + .unwrap(); assert!( - result - .err() - .unwrap() - .to_string() - .contains("require Simulation") + matches!( + error.kind(), + celox::SimulatorErrorKind::ProcessRequiresSimulation(_) + ), + "{error}" ); let mut sim = celox::Simulation::from_sv_sources( vec![(source, Path::new("dead_host.sv"))], diff --git a/crates/celox/tests/sv_untimed_processes.rs b/crates/celox/tests/sv_untimed_processes.rs new file mode 100644 index 00000000000..b9dc4f6fff1 --- /dev/null +++ b/crates/celox/tests/sv_untimed_processes.rs @@ -0,0 +1,213 @@ +//! An untimed `Simulator` runs no process kernel, so building one for a +//! design with a kernel is an error that names the process (#1712). +#![cfg(feature = "systemverilog")] + +use std::path::Path; + +use celox::{ProcessOrigin, Simulation, Simulator, SimulatorError, SimulatorErrorKind}; + +/// The build error of every untimed backend. +fn untimed_errors(sources: &[(&str, &str)], top: &str) -> Vec { + let build = || { + Simulator::from_sv_sources( + sources + .iter() + .map(|(source, path)| (*source, Path::new(path))) + .collect(), + top, + ) + }; + let mut errors = vec![ + build().build_interpreter().map(|_| ()).unwrap_err(), + build().build_cranelift().map(|_| ()).unwrap_err(), + build().build_wasm().map(|_| ()).unwrap_err(), + build().build_tiered().map(|_| ()).unwrap_err(), + ]; + #[cfg(any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ))] + errors.extend([ + build().build_native().map(|_| ()).unwrap_err(), + build().compile_native().map(|_| ()).unwrap_err(), + ]); + errors +} + +fn origin(error: &SimulatorError) -> &ProcessOrigin { + match error.kind() { + SimulatorErrorKind::ProcessRequiresSimulation(origin) => origin, + _ => panic!("{error}"), + } +} + +/// Every untimed backend rejects `source` and names the same process. +fn assert_rejected(source: &str, construct: &str, location: &str, scope: &str) { + for error in untimed_errors(&[(source, "processes.sv")], "Top") { + let origin = origin(&error); + assert_eq!(origin.construct, construct, "{error}"); + assert_eq!(origin.location.as_deref(), Some(location), "{error}"); + assert_eq!(origin.scope.as_deref(), Some(scope), "{error}"); + let message = error.to_string(); + assert!(message.contains(location), "{message}"); + assert!(message.contains("Simulation"), "{message}"); + } +} + +/// `always @(a)` does not list `b`, so it is not an implicit `always @*`. +const INCOMPLETE_LIST: &str = "module Top(input logic [7:0] a, b, output logic [7:0] y); + always @(a) y = a + b; +endmodule +"; + +#[test] +fn incomplete_event_list_is_rejected() { + assert_rejected(INCOMPLETE_LIST, "always", "processes.sv:2:3", "Top"); +} + +#[test] +fn incomplete_event_list_runs_in_a_simulation() { + let mut sim = Simulation::from_sv_sources(vec![(INCOMPLETE_LIST, Path::new("p.sv"))], "Top") + .build_interpreter() + .unwrap(); + let (a, b, y) = (sim.signal("a"), sim.signal("b"), sim.signal("y")); + sim.modify(|io| io.set(b, 5u8)).unwrap(); + sim.run_until(0).unwrap(); + sim.modify(|io| io.set(a, 3u8)).unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(sim.get(y), 8u8.into()); +} + +#[test] +fn delayed_initial_is_rejected() { + assert_rejected( + "module Top(output logic x); + initial #5 x = 1; +endmodule +", + "initial", + "processes.sv:2:3", + "Top", + ); +} + +#[test] +fn timed_task_in_an_edge_procedure_is_rejected() { + assert_rejected( + "module Top(input logic clk, a, output logic q); + task automatic pause; #1; endtask + always @(posedge clk) begin pause(); q = a; end +endmodule +", + "always", + "processes.sv:3:3", + "Top", + ); +} + +#[test] +fn always_ff_with_file_output_is_rejected() { + assert_rejected( + "module Top(input logic clk, d, output logic q); + always_ff @(posedge clk) begin + $fwrite(1, \"edge\"); + q <= d; + end +endmodule +", + "always_ff", + "processes.sv:2:3", + "Top", + ); +} + +#[test] +fn the_first_process_is_named() { + assert_rejected( + "module Top(output logic x, y); + initial x = 0; + initial #2 y = 1; + always #1 x = ~x; +endmodule +", + "initial", + "processes.sv:3:3", + "Top", + ); +} + +#[test] +fn processes_of_child_instances_are_rejected() { + let sources = [( + "module Child(input logic [7:0] a, b, output logic [7:0] y); + always @(a) y = a + b; +endmodule +module Top(input logic [7:0] a, b, output logic [7:0] y); + Child child(a, b, y); +endmodule +", + "child.sv", + )]; + for error in untimed_errors(&sources, "Top") { + let origin = origin(&error); + assert_eq!(origin.construct, "always"); + assert_eq!(origin.location.as_deref(), Some("child.sv:2:3")); + assert_eq!(origin.scope.as_deref(), Some("Top.child")); + } +} + +const VERYL_TOP: &str = "module Top(a: input logic<8>, b: input logic<8>, y: output logic<8>) { inst child: $sv::Child(a, b, y); }"; +const SV_CHILD: &str = "module Child(input logic [7:0] a, b, output logic [7:0] y); + always @(a) y = a + b; +endmodule +"; + +#[test] +fn processes_below_a_veryl_top_are_rejected() { + let error = Simulator::from_mixed_sources( + vec![(VERYL_TOP, Path::new("top.veryl"))], + vec![(SV_CHILD, Path::new("child.sv"))], + "Top", + ) + .build_interpreter() + .map(|_| ()) + .unwrap_err(); + let origin = origin(&error); + assert_eq!(origin.construct, "always"); + assert_eq!(origin.location.as_deref(), Some("child.sv:2:3")); + let mut sim = Simulation::from_sources(vec![(VERYL_TOP, Path::new("top.veryl"))], "Top") + .with_sv_sources(vec![(SV_CHILD, Path::new("child.sv"))]) + .build_interpreter() + .unwrap(); + let (a, b, y) = (sim.signal("a"), sim.signal("b"), sim.signal("y")); + sim.modify(|io| io.set(b, 5u8)).unwrap(); + sim.run_until(0).unwrap(); + sim.modify(|io| io.set(a, 3u8)).unwrap(); + sim.run_until(1).unwrap(); + assert_eq!(sim.get(y), 8u8.into()); +} + +/// Initial blocks and declaration initializers with constant results are +/// initial values, not processes, so an untimed `Simulator` keeps them. +#[test] +fn constant_initial_state_builds_an_untimed_simulator() { + let source = "module Top(input logic [7:0] a, output logic [7:0] y, z); + logic [7:0] base = 8'd3; + logic [7:0] mem [4]; + logic [7:0] offset; + initial begin + offset = 8'd10; + for (int i = 0; i < 4; i++) mem[i] = 8'(i * 2); + end + assign y = a + base + offset; + assign z = mem[a[1:0]]; +endmodule +"; + let mut sim = Simulator::from_sv_sources(vec![(source, Path::new("initial.sv"))], "Top") + .build_interpreter() + .unwrap(); + let (a, y, z) = (sim.signal("a"), sim.signal("y"), sim.signal("z")); + sim.modify(|io| io.set(a, 3u8)).unwrap(); + assert_eq!(sim.get(y), 16u8.into()); + assert_eq!(sim.get(z), 6u8.into()); +} diff --git a/crates/celox/tests/sv_vcd.rs b/crates/celox/tests/sv_vcd.rs index 0927f6e1097..c642322ee11 100644 --- a/crates/celox/tests/sv_vcd.rs +++ b/crates/celox/tests/sv_vcd.rs @@ -497,8 +497,11 @@ fn initial_vcd_tasks_require_timed_simulation_on_every_backend() { ]; for error in errors { assert!( - format!("{error:?}").contains("source VCD controls require Simulation"), - "{error:?}" + matches!( + error.kind(), + celox::SimulatorErrorKind::ProcessRequiresSimulation(_) + ), + "{error}" ); } } diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index 196f4527c89..65123edabbd 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -213,6 +213,12 @@ List package definitions before their consumers. It does not discover a must all be `.sv` files; for Veryl, pass one project entry file. The `celox-vpi-compile` binary accepts the same source list. +cocotb drives the design, so the compiled executable runs no HDL process. +Compilation fails for a design with an `initial` process, an ordinary `always` +process or another procedure Celox runs as a process, and names the first one; +constant `initial` blocks and declaration initializers still set initial +values. + ## Run cocotb Suppose `test/test_top.py` contains a cocotb test. Run the generated executable diff --git a/docs/guide/external-frontends.md b/docs/guide/external-frontends.md index c6a5b53dc4e..d3a9f60ee95 100644 --- a/docs/guide/external-frontends.md +++ b/docs/guide/external-frontends.md @@ -164,7 +164,9 @@ whenever a signal they read, and do not write, changes. Each write is visible as it happens, so `y = 0; if (a) y = 1;` pulses `y` when an input change re-runs the process; settling again with steady inputs does not re-run it. -Processes run only in a timed `Simulation`. Each one is compiled into a +Processes run only in a timed `Simulation`; building a `Simulator` for an +artifact with processes fails with `SimulatorErrorKind::ProcessRequiresSimulation`. +Each one is compiled into a resumable kernel that the simulation scheduler resumes when its delay expires or its wait is satisfied. Processes that resume at the same time run in declaration order. A time slot follows the regions of IEEE 1800-2023 4.5: diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 86daa04776e..46b06a9b95c 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -39,7 +39,7 @@ synthesis and is tested at the design level. | Continuous logic | `assign`, `wire w = expr;` | | 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 | +| 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 | | 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 | @@ -61,9 +61,9 @@ both `Simulator` and `Simulation`: `always @(a or b) y = a + b;` or or a nonblocking assignment. Any other sensitivity list without edges runs as a process: `always @(a) y = a + b;` leaves `y` unchanged when only `b` changes. So does a list that, as `always @*`, would close a combinational -loop with other logic. A `Simulator` runs no processes, so such a design simulates without them there; -use `Simulation`, or write `always @*` or `always_comb` -([#1712](https://github.com/celox-sim/celox/issues/1712)). +loop with other logic. A `Simulator` runs no processes, so building one for +such a design fails with `SimulatorErrorKind::ProcessRequiresSimulation`; use +`Simulation`, or write `always @*` or `always_comb`. ### Timed task calls diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 8292e7e53cb..d722a186482 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -63,8 +63,10 @@ tracks time and runs scheduled edges. Constant initialization applies to both. `initial` blocks that read design state or call system tasks, processes with timing controls and `always` blocks whose sensitivity list is neither `@*` nor [the variables they read](./systemverilog-reference#timing-controls) run as -processes and need `Simulation`; a `Simulator` does not run them -([#1712](https://github.com/celox-sim/celox/issues/1712)). +processes and need `Simulation`. A `Simulator` runs no process, so building +one for such a design fails with `SimulatorErrorKind::ProcessRequiresSimulation`, +which names the first process and its source location. For a mixed hierarchy, +build the `Simulation` with `Simulation::from_sources(veryl).with_sv_sources(sv)`. Use `.four_state(true)` on the builder when your test needs X/Z values. The [4-state guide](./four-state) explains the state model. For time units, diff --git a/docs/ja/guide/cocotb.md b/docs/ja/guide/cocotb.md index 0f37fae4f4b..c06aefbe3c4 100644 --- a/docs/ja/guide/cocotb.md +++ b/docs/ja/guide/cocotb.md @@ -188,6 +188,11 @@ package定義は利用側より先に指定してください。`Veryl.toml`や Verylではプロジェクトの入口となるファイルを1つ指定します。 `celox-vpi-compile`も同じソース一覧を受け付けます。 +設計はcocotbが駆動するため、生成した実行ファイルはHDLのプロセスを実行しません。 +`initial`プロセス、通常の`always`プロセスなど、Celoxがプロセスとして実行する +手続きを含む設計はコンパイルに失敗し、最初のプロセスを示します。定数の`initial` +ブロックと宣言初期化子は引き続き初期値を設定します。 + ## cocotbを実行する たとえば`test/test_top.py`にcocotbテストがある場合、そのモジュールをimportできる diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 18f18c73a24..54354ce4cbf 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -38,7 +38,7 @@ outline: [2, 3] | 連続論理 | `assign`、`wire w = expr;` | | 組み合わせプロセス | `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` はプロセスを実行しない) | +| 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`、即時アサーション | | 関数 | `input` / `output` / `inout` 引数を持てる `function` と、`task`。`return`、または関数名への代入で値を返す。ローカル変数と `localparam`、部分選択や複合的な代入先への代入。呼び出しはインライン展開。定数式(パラメータ、範囲)の中の定数引数による呼び出しはエラボレーション時に評価 | @@ -59,9 +59,9 @@ outline: [2, 3] 文にはタイミング制御とノンブロッキング代入を含められません。エッジを持たないそれ以外の センシティビティリストを持つ `always` はプロセスとして実行します。`always @(a) y = a + b;` は `b` だけが変化しても `y` を更新しません。`always @*` として扱うと他の論理と組み合わせループを作るリストも -プロセスとして実行します。`Simulator` はプロセスを実行しないため、そこではこのプロセス抜きで -シミュレーションされます。`Simulation` を使うか、`always @*` / `always_comb` で記述してください -([#1712](https://github.com/celox-sim/celox/issues/1712))。 +プロセスとして実行します。`Simulator` はプロセスを実行しないため、このようなデザインでは +`SimulatorErrorKind::ProcessRequiresSimulation` でビルドに失敗します。`Simulation` を使うか、 +`always @*` / `always_comb` で記述してください。 ### 時間待ちを含む task diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index 085c228482c..89ac71967e8 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -60,8 +60,10 @@ assert_eq!(sim.get(q), 1u8.into()); 定数による初期化はどちらにも適用されます。デザインの状態を読む、またはシステムタスクを呼ぶ `initial` ブロック、タイミング制御を持つプロセス、`@*` でも [文が読む変数](./systemverilog-reference#timing-controls)でもないセンシティビティリストを持つ -`always` はプロセスとして実行するため `Simulation` が必要です。`Simulator` はこれらを実行しません -([#1712](https://github.com/celox-sim/celox/issues/1712))。 +`always` はプロセスとして実行するため `Simulation` が必要です。`Simulator` はプロセスを実行しないため、 +このようなデザインでは `SimulatorErrorKind::ProcessRequiresSimulation` でビルドに失敗し、 +最初のプロセスとそのソース位置を示します。Veryl と混在する階層では +`Simulation::from_sources(veryl).with_sv_sources(sv)` で `Simulation` を作成します。 X/Z を扱う場合は builder に `.four_state(true)` を指定します。 状態モデルは [4 値シミュレーション](./four-state)、時刻、`$stop`、メモリの読み込みなどは diff --git a/packages/celox/src/e2e.test.ts b/packages/celox/src/e2e.test.ts index 08cbf81d425..08ff08aa5bb 100644 --- a/packages/celox/src/e2e.test.ts +++ b/packages/celox/src/e2e.test.ts @@ -353,6 +353,14 @@ describe("E2E: external frontend artifact", () => { sim.dispose(); }); + test("rejects a process in an untimed simulator", () => { + expect(() => + Simulator.fromFrontendArtifact(FRONTEND_FINISH_ARTIFACT), + ).toThrow( + /`process` in `Finisher` is a process, which Simulator does not run; build a Simulation instead/, + ); + }); + test("runs a Veryl native testbench against a frontend SDK design", () => { const result = runTestWithFrontendArtifact( FRONTEND_ADDER_ARTIFACT,