diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index c24b1699178..204e1520b64 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -16,7 +16,7 @@ chapter-11/11.10.1--string_concat.sv fail chapter-11/11.10.1--string_copy.sv fail chapter-11/11.10.3--empty_string-sim.sv fail chapter-11/11.10.3--empty_string.sv fail -chapter-11/11.11--min_max_avg_delay.sv fail +chapter-11/11.11--min_max_avg_delay.sv pass chapter-11/11.12--let_construct.sv fail chapter-11/11.3.5--expr_short_circuit.sv pass chapter-11/11.3.6--assign_in_exp-sim.sv fail @@ -726,7 +726,7 @@ chapter-9/9.3.5--statement_labels_par.sv fail chapter-9/9.3.5--statement_labels_seq.sv pass chapter-9/9.4.1--delay_control-sim.sv fail chapter-9/9.4.1--delay_control-two-blocks-sim.sv fail -chapter-9/9.4.1--delay_control.sv fail +chapter-9/9.4.1--delay_control.sv pass chapter-9/9.4.2--event_control_edge.sv fail chapter-9/9.4.2--event_control_negedge.sv pass chapter-9/9.4.2--event_control_posedge.sv pass @@ -737,7 +737,7 @@ chapter-9/9.4.2.1--event_or_op.sv fail chapter-9/9.4.2.2--event_implicit.sv pass chapter-9/9.4.2.3--event_conditional.sv fail chapter-9/9.4.2.4--event_sequence.sv fail -chapter-9/9.4.3--event_sequence_controls.sv fail +chapter-9/9.4.3--event_sequence_controls.sv pass chapter-9/9.4.5--event_blocking_assignment_delay.sv fail chapter-9/9.4.5--event_nonblocking_assignment_delay.sv fail chapter-9/9.4.5--event_nonblocking_assignment_event.sv fail diff --git a/crates/celox-design/src/edges.rs b/crates/celox-design/src/edges.rs index fa3209c1f78..510b012f28d 100644 --- a/crates/celox-design/src/edges.rs +++ b/crates/celox-design/src/edges.rs @@ -14,26 +14,58 @@ pub const fn polarity(kind: DomainKind) -> Option { } } -/// Whether a level change from `was` to `is` that the scheduler applies to -/// an event signal, or that a process drives, is an active edge of a domain -/// of `kind`. A domain of unknown kind reacts to a rising edge. +/// The bit of an edge level that marks an unknown (x or z) value; the value +/// bit then tells x (1) from z (0), as in the state image. An edge level is +/// 0, 1, x (`LEVEL_UNKNOWN | 1`) or z (`LEVEL_UNKNOWN`). +pub const LEVEL_UNKNOWN: u8 = 2; + +/// Whether a change between the edge levels `was` and `is` is a rising +/// (`rising`) or a falling edge (IEEE 1800-2023 9.4.2, Table 9-2): a posedge +/// leaves 0 or reaches 1, a negedge leaves 1 or reaches 0, and a change +/// between x and z is neither. With `FOUR_STATE` false the levels are 0 or +/// 1 and this is a rise or a fall. +#[inline] +pub const fn level_edge(rising: bool, was: u8, is: u8) -> bool { + let between_unknowns = FOUR_STATE && was & is & LEVEL_UNKNOWN != 0; + let (from, to) = if rising { (0, 1) } else { (1, 0) }; + was != to && is != from && !between_unknowns +} + +/// Whether a change from edge level `was` to `is` that the scheduler +/// applies to an event signal, or that a process drives, is an active edge +/// of a domain of `kind`. A domain of unknown kind reacts to a rising edge. /// /// This differs from [`settled_edge`] for domains of unknown kind; the two /// rules stay separate. -pub const fn scheduled_edge(kind: Option, was: bool, is: bool) -> bool { +#[inline] +pub const fn scheduled_edge( + kind: Option, + was: u8, + is: u8, +) -> bool { match kind { - Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => !was && is, - Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => was && !is, - _ => !was && is, + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { + level_edge::(false, was, is) + } + _ => level_edge::(true, was, is), } } -/// Whether a settled level change from `was` to `is` is an active edge of a -/// domain of `kind`. A domain of unknown kind reacts to any change. -pub const fn settled_edge(kind: Option, was: bool, is: bool) -> bool { +/// Whether a settled change from edge level `was` to `is` is an active edge +/// of a domain of `kind`. A domain of unknown kind reacts to any change. +#[inline] +pub const fn settled_edge( + kind: Option, + was: u8, + is: u8, +) -> bool { match kind { - Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => !was && is, - Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => was && !is, + Some(DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh) => { + level_edge::(true, was, is) + } + Some(DomainKind::ClockNegedge | DomainKind::ResetAsyncLow) => { + level_edge::(false, was, is) + } _ => was != is, } } @@ -54,10 +86,32 @@ mod tests { #[test] fn domains_of_unknown_kind_differ_between_the_rules() { for kind in [None, Some(DomainKind::Other)] { - assert!(scheduled_edge(kind, false, true)); - assert!(!scheduled_edge(kind, true, false)); - assert!(settled_edge(kind, false, true)); - assert!(settled_edge(kind, true, false)); + assert!(scheduled_edge::(kind, 0, 1)); + assert!(!scheduled_edge::(kind, 1, 0)); + assert!(settled_edge::(kind, 0, 1)); + assert!(settled_edge::(kind, 1, 0)); + } + } + + /// IEEE 1800-2023 Table 9-2, rows `from` and columns `to` in the order + /// 0, 1, x, z: `P` posedge, `N` negedge, `-` no edge. + #[test] + fn four_state_levels_follow_table_9_2() { + const LEVELS: [u8; 4] = [0, 1, LEVEL_UNKNOWN | 1, LEVEL_UNKNOWN]; + const TABLE: [&str; 4] = ["-PPP", "N-NN", "NP--", "NP--"]; + for (from, row) in LEVELS.iter().zip(TABLE) { + for (to, cell) in LEVELS.iter().zip(row.chars()) { + for (kind, mark) in [ + (DomainKind::ClockPosedge, 'P'), + (DomainKind::ResetAsyncHigh, 'P'), + (DomainKind::ClockNegedge, 'N'), + (DomainKind::ResetAsyncLow, 'N'), + ] { + let edge = cell == mark; + assert_eq!(settled_edge::(Some(kind), *from, *to), edge); + assert_eq!(scheduled_edge::(Some(kind), *from, *to), edge); + } + } } } @@ -70,10 +124,16 @@ mod tests { DomainKind::ResetAsyncLow, ] { let rising = polarity(kind) == Some(true); - for (was, is) in [(false, true), (true, false), (false, false), (true, true)] { - let edge = if rising { !was && is } else { was && !is }; - assert_eq!(scheduled_edge(Some(kind), was, is), edge); - assert_eq!(settled_edge(Some(kind), was, is), edge); + for (was, is) in [(0, 1), (1, 0), (0, 0), (1, 1)] { + let edge = if rising { + was == 0 && is == 1 + } else { + was == 1 && is == 0 + }; + assert_eq!(scheduled_edge::(Some(kind), was, is), edge); + assert_eq!(settled_edge::(Some(kind), was, is), edge); + assert_eq!(scheduled_edge::(Some(kind), was, is), edge); + assert_eq!(settled_edge::(Some(kind), was, is), edge); } assert_eq!(active_level(Some(kind)), u8::from(rising)); } diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 2982ce71c1d..c3ff7ae31c5 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -522,6 +522,49 @@ pub enum DeadStorePolicy { PreserveAllPorts, } +/// One simulation tick, expressed as a power of ten seconds. +/// Valid SystemVerilog/VCD scales range from 1 fs (-15) to 100 s (2). +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)] +#[serde(try_from = "i32", into = "i32")] +pub struct TimePrecision(i32); + +impl TimePrecision { + pub fn exponent(self) -> i32 { + self.0 + } + + /// The magnitude and physical unit used by a VCD `$timescale` header. + pub fn vcd_timescale(self) -> (u8, &'static str) { + let magnitude = 10u8.pow(self.0.rem_euclid(3) as u32); + let unit = ["s", "ms", "us", "ns", "ps", "fs"][(-self.0.div_euclid(3)) as usize]; + (magnitude, unit) + } +} + +impl Default for TimePrecision { + /// Scale-free frontends use the same 1ps tick as the SV implementation default. + fn default() -> Self { + Self(-12) + } +} + +impl TryFrom for TimePrecision { + type Error = &'static str; + fn try_from(exponent: i32) -> Result { + if (-15..=2).contains(&exponent) { + Ok(Self(exponent)) + } else { + Err("time precision must be between 1fs and 100s") + } + } +} + +impl From for i32 { + fn from(precision: TimePrecision) -> Self { + precision.0 + } +} + /// Source-independent runtime diagnostics and observable event descriptions. #[derive(Clone, Debug)] pub struct RuntimeSchema { @@ -740,6 +783,13 @@ impl EventTopology { } } +/// Time unit and rounding precision of one source scope, in powers of ten seconds. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct TimeScale { + pub unit: TimePrecision, + pub precision: TimePrecision, +} + /// Backend-neutral semantic design data after hierarchy flattening. /// /// This is intentionally not a frontend lookup table: every state object is @@ -751,6 +801,11 @@ impl EventTopology { deserialize = "A: Deserialize<'de> + Eq + std::hash::Hash + Ord" ))] pub struct ElaboratedDesign { + /// Physical duration of one global simulation tick. + #[serde(default)] + pub time_precision: TimePrecision, + /// Local time units and precisions retained for reflected instance queries. + pub instance_time_scales: HashMap, pub state_objects: HashMap, pub events: EventTopology, pub initial_state: Vec>, @@ -759,6 +814,8 @@ pub struct ElaboratedDesign { impl Default for ElaboratedDesign { fn default() -> Self { Self { + time_precision: TimePrecision::default(), + instance_time_scales: HashMap::default(), state_objects: HashMap::default(), events: EventTopology::default(), initial_state: Vec::new(), diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index a73e773440e..aa42635fc38 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1897,6 +1897,8 @@ pub fn lower_frontend_artifact( let module_id = ModuleId(0); let sim_module = SimModule { + time_precision: None, + time_scale: celox_design::TimeScale::default(), name: artifact.module_name().to_string(), variables, ff_access_summaries: HashMap::default(), diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index 2916167c90b..2baccec6144 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -56,6 +56,10 @@ pub struct SymbolicProcess { #[derive(Clone)] pub struct SimModule { + /// A frontend's global tick precision; absent for scale-free frontends. + pub time_precision: Option, + /// Local unit and precision; scale-free frontends use the 1ps default. + pub time_scale: celox_design::TimeScale, pub name: String, pub variables: HashMap, pub ff_access_summaries: diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index a4742149e02..7581c99d08f 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -572,6 +572,11 @@ pub fn schedule_symbolic_rtl( root_id, packages, } = symbolic; + let time_precision = modules + .values() + .filter_map(|module| module.time_precision) + .min() + .unwrap_or_default(); let flatten_timing = trace_opts.phase_timing; macro_rules! timed_sub { ($label:expr, $body:expr) => {{ @@ -603,6 +608,10 @@ pub fn schedule_symbolic_rtl( instance_modules.insert(id, *module_id); package_instances.insert(*module_id, id); } + let instance_time_scales = instance_modules + .iter() + .map(|(&instance, module)| (instance, modules[module].time_scale)) + .collect::>(); let bindings = &PackageBindings::new(&instance_modules, &modules, &package_instances)?; let global_boundaries = timed_sub!( "propagate_boundaries", @@ -1479,6 +1488,8 @@ pub fn schedule_symbolic_rtl( .collect(); let watches: Vec> = { let event_kinds = ElaboratedDesign { + time_precision, + instance_time_scales: HashMap::default(), state_objects: state_objects.clone(), events: events.clone(), initial_state: Vec::new(), @@ -1546,6 +1557,8 @@ pub fn schedule_symbolic_rtl( let scheduled = ScheduledRtl { sir, design: ElaboratedDesign { + time_precision, + instance_time_scales, state_objects, events, initial_state, diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 10a5f1f5b66..c177953bfcb 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -13,7 +13,7 @@ use celox_design::{ BinaryOp, BitAccess, DisplaySizing, DomainKind, ExternFunction, ExternSignature, ExternType, InitialStateData, InitialStateValue, ModuleId, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo, RuntimeEventKind, - RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, WORKING_REGION, + RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, WORKING_REGION, WaitSite, }; use celox_frontend_core::process::PROCESS_RESUME_WIDTH; use celox_frontend_core::symbolic::artifact::{ @@ -141,7 +141,7 @@ pub(crate) struct LoweredSvParameterOverride { pub value: Option, /// The data type resolved in the instantiating scope. pub bound_type: Option, - pub pattern_text: Option, + pub bound_pattern: Option, } #[derive(Clone)] @@ -723,7 +723,12 @@ fn lower_package_states( .into_iter() .enumerate() .map(|(index, module)| { - let lowered = lower_module(module, four_state, true, ff_parts)?; + let mut lowered = lower_module(module, four_state, true, ff_parts)?; + lowered.sim_module.time_precision = Some( + celox_design::TimePrecision::try_from(packages.global_time_precision()) + .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))?, + ); + lowered.sim_module.time_scale = scope_time_scale(packages, module.name())?; // Declaration initializers run before every `initial` block // (IEEE 1800-2023 10.5); one that is not folded into an initial // value would run among them. @@ -1208,6 +1213,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( "__celox_foreign", &HashMap::default(), &[], + &[], &sv::ModuleInterfaces::default(), &sv::Packages::default(), )?; @@ -1295,7 +1301,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( name: name.clone(), value: Some(value.expression()), bound_type: None, - pattern_text: None, + bound_pattern: None, }) .collect(); requested_roots.insert(name.clone(), key.clone()); @@ -1310,7 +1316,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( name: name.clone(), value: Some(sv::ir::ConstExpr::Literal(value.to_string())), bound_type: None, - pattern_text: None, + bound_pattern: None, }) .collect(); } @@ -1371,7 +1377,7 @@ pub fn prepare_external_hierarchy_with_foreign_resolver( name: name.clone(), value: Some(value.expression()), bound_type: None, - pattern_text: None, + bound_pattern: None, }) .collect(); requested_roots.insert(name.clone(), dependency.clone()); @@ -1580,7 +1586,7 @@ pub fn schedule_sources( name: name.clone(), value: Some(sv::ir::ConstExpr::Literal(value.to_string())), bound_type: None, - pattern_text: None, + bound_pattern: None, }) .collect(), }; @@ -1773,16 +1779,13 @@ fn specialize_module( let pattern_overrides: Vec<_> = key .parameter_overrides .iter() - .filter_map(|parameter| Some((parameter.name.clone(), parameter.pattern_text.clone()?))) + .filter_map(|parameter| Some((parameter.name.clone(), parameter.bound_pattern.clone()?))) .collect(); - let pattern_source = module - .source - .with_pattern_parameter_overrides(&module.name, &pattern_overrides)?; - let source = pattern_source.as_ref().unwrap_or(&module.source); - let ir = source.analyze_module( + let ir = module.source.analyze_module( &module.name, &overrides, &type_overrides, + &pattern_overrides, &module.interfaces, &module.packages, )?; @@ -1791,12 +1794,35 @@ fn specialize_module( .iter() .find(|candidate| candidate.name() == module.name) .ok_or_else(|| sv::AnalyzerError::Unsupported(format!("module `{}`", module.name)))?; - lower_module( + let mut lowered = lower_module( specialized, four_state, module.implicit_nets_allowed, ff_parts, - ) + )?; + lowered.sim_module.time_precision = Some( + celox_design::TimePrecision::try_from(module.packages.global_time_precision()) + .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))?, + ); + lowered.sim_module.time_scale = scope_time_scale(&module.packages, &module.name)?; + Ok(lowered) +} + +fn scope_time_scale( + packages: &sv::Packages, + name: &str, +) -> Result { + let Some((unit, precision)) = packages.scope_time_scale(name) else { + return Ok(celox_design::TimeScale::default()); + }; + let convert = |exponent: i32| { + celox_design::TimePrecision::try_from(exponent) + .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string())) + }; + Ok(celox_design::TimeScale { + unit: convert(unit)?, + precision: convert(precision)?, + }) } fn lower_module( @@ -1977,7 +2003,7 @@ fn lower_module_with_overrides( ) }; mark_ff_event_domains(&event_vars, &mut variables); - let (initial_values, processes) = lower_initial_processes( + let (initial_values, processes, wait_sites) = lower_initial_processes( module, &mut variables, &mut name_to_id, @@ -2060,6 +2086,8 @@ fn lower_module_with_overrides( source: module.clone(), implicit_nets_allowed, sim_module: SimModule { + time_precision: None, + time_scale: celox_design::TimeScale::default(), name, variables: shared_variables, ff_access_summaries: HashMap::default(), @@ -2082,7 +2110,7 @@ fn lower_module_with_overrides( processes, package_bindings: HashMap::default(), counter_slots: Vec::new(), - wait_sites: Vec::new(), + wait_sites, nba_sites: Vec::new(), }, variables, @@ -2158,7 +2186,7 @@ fn lower_parameter_overrides( name: parameter.name().to_string(), value, bound_type: parameter.bound_type().cloned(), - pattern_text: parameter.pattern_text().map(str::to_string), + bound_pattern: parameter.bound_pattern().cloned(), } }) .collect() @@ -2740,9 +2768,16 @@ fn lower_initial_processes( runtime_event_sites: &mut Vec, runtime_errors: &mut HashMap>, extern_functions: &mut Vec, -) -> Result<(Vec>, Vec), sv::AnalyzerError> { +) -> Result< + ( + Vec>, + Vec, + Vec>, + ), + sv::AnalyzerError, +> { if module.initial_processes().is_empty() { - return Ok((Vec::new(), Vec::new())); + return Ok((Vec::new(), Vec::new(), Vec::new())); } let mut values = Vec::new(); let mut runtime = Vec::new(); @@ -2790,7 +2825,7 @@ fn lower_initial_processes( } } if runtime.is_empty() { - return Ok((values, Vec::new())); + return Ok((values, Vec::new(), Vec::new())); } let mut next_id = SourceVarId( @@ -2844,21 +2879,25 @@ fn lower_initial_processes( pm.runtime_event_sites = std::mem::take(runtime_event_sites); pm.runtime_errors = std::mem::take(runtime_errors); pm.extern_functions = std::mem::take(extern_functions); + let mut wait_sites = Vec::new(); let processes = runtime .into_iter() .zip(slots) - .map(|((process, random_seed), slots)| { - Ok(SymbolicProcess { - kernel: ff::Ff::new(&mut pm, random_seed) - .lower_initial_kernel(process.body(), slots)?, + .enumerate() + .map(|(index, ((process, random_seed), slots))| { + let (kernel, sites) = ff::Ff::new(&mut pm, random_seed).lower_initial_kernel( + process.body(), slots, - }) + index, + )?; + wait_sites.extend(sites); + Ok(SymbolicProcess { kernel, slots }) }) .collect::, sv::AnalyzerError>>(); *runtime_event_sites = std::mem::take(&mut pm.runtime_event_sites); *runtime_errors = std::mem::take(&mut pm.runtime_errors); *extern_functions = std::mem::take(&mut pm.extern_functions); - Ok((values, processes?)) + Ok((values, processes?, wait_sites)) } fn lower_comb_processes( diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index a6a2b8cfbe7..dfcbac62065 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -1788,6 +1788,10 @@ impl<'p, 'a> Comb<'p, 'a> { self.assign_concat(&mut store, frames, parts, rhs)?; Ok(store) } + // A timing control suspends a process; this lowering has none. + sv::ir::Stmt::Delay(_) | sv::ir::Stmt::WaitEvent(_) | sv::ir::Stmt::Wait(_) => { + Err(unsupported("procedural timing control")) + } sv::ir::Stmt::Local { name, init } => { let id = self .m diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 1e727f1ea7d..3c8947420e5 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -11,7 +11,8 @@ use super::procedural::*; use super::*; -use celox_frontend_core::process::ProcessKernelBuilder; +use celox_design::{CounterKind, WaitSite}; +use celox_frontend_core::process::{ProcessKernelBuilder, ProcessKernelError}; use celox_sir::{RegisterId, RegisterType}; use celox_slt::SLTToSIRLowerer; use num_traits::{ToPrimitive, Zero}; @@ -57,6 +58,10 @@ pub(super) struct Ff<'p, 'a> { /// body is lowered, and the process reads and writes stable state /// directly. kernel: Option, + /// The index of the process being lowered among the module's kernels. + process: usize, + /// The wait sites of the process, by local index. + wait_sites: Vec>, direct: bool, } @@ -101,6 +106,8 @@ impl<'p, 'a> Ff<'p, 'a> { dist_seed: None, kernel: None, direct: false, + process: 0, + wait_sites: Vec::new(), } } @@ -1811,6 +1818,18 @@ impl<'p, 'a> Ff<'p, 'a> { self.assign_concat(parts, rhs)?; Ok(true) } + sv::ir::Stmt::Delay(amount) => { + self.delay(amount)?; + Ok(true) + } + sv::ir::Stmt::WaitEvent(items) => { + self.wait_event(items)?; + Ok(true) + } + sv::ir::Stmt::Wait(condition) => { + self.wait_level(condition)?; + Ok(true) + } sv::ir::Stmt::Local { name, init } => { let id = self .m @@ -2366,7 +2385,32 @@ impl<'p, 'a> Ff<'p, 'a> { sv::ir::LoopKind::Repeat(count) => { let signed = self.expr_signed(count); let (id, name) = self.m.temp("repeat", 64, false, false); - let value = self.eval(count, Some((64, signed)))?; + let value = if self.kernel.is_some() { + // A count with an unknown bit, or a negative one, runs + // the body zero times (IEEE 1800-2023 12.7.2). + let count = if signed { + sv::ir::Expr::Mux { + condition: Box::new(sv::ir::Expr::Binary { + left: Box::new(count.clone()), + op: sv::ir::BinaryOp::Lt, + right: Box::new(sv::ir::Expr::Literal("0".to_string())), + }), + then_expr: Box::new(sv::ir::Expr::Literal("0".to_string())), + else_expr: Box::new(count.clone()), + } + } else { + count.clone() + }; + let mut arena = SLTNodeArena::new(); + let node = self.expr_slt(&count, None, &mut arena)?; + let original = self.lower_slt(&arena, node)?; + let node = + coerce_node_width(&mut arena, node, Some(64), signed).map_err(slt_error)?; + let value = self.lower_slt(&arena, node)?; + self.zero_if_unknown(value, original) + } else { + self.eval(count, Some((64, signed)))? + }; self.store(id, SIROffset::Static(0), 64, value); Some(name) } @@ -2422,6 +2466,14 @@ impl<'p, 'a> Ff<'p, 'a> { if falls? { self.jump(latch); } + // A kernel loop that may not suspend yields now and then, so the + // runtime charges it against the time slot's budget instead of + // spinning in the kernel. + let header = if self.kernel.is_some() && !always_suspends(body) { + self.yielding_back_edge(header)? + } else { + header + }; // Latch: the step, then the condition again. A counted loop whose // step leaves its variable unchanged would never end; it stops the // simulation with an error instead. @@ -2860,7 +2912,9 @@ impl Ff<'_, '_> { mut self, body: &[sv::ir::Stmt], slots: ProcessSlots, - ) -> Result, sv::AnalyzerError> { + process: usize, + ) -> Result<(ExecutionUnit, Vec>), sv::AnalyzerError> { + self.process = process; // A nonblocking update would take effect in a later region of the // time step, after the process has run on. for stmt in body { @@ -2891,10 +2945,267 @@ impl Ff<'_, '_> { std::mem::swap(&mut self.b, kernel.builder()); let mut unit = kernel.build(); prune_unreachable_blocks(&mut unit); - Ok(unit) + Ok((unit, self.wait_sites)) + } + + /// `#amount` (IEEE 1800-2023 9.4.1). The amount is self-determined and + /// read as an unsigned 64-bit time: a negative value as its two's + /// complement, and a value with an unknown bit as zero. `#0` resumes in + /// the inactive region. + fn delay(&mut self, amount: &sv::ir::Expr) -> Result<(), sv::AnalyzerError> { + let signed = self.expr_signed(amount); + let mut arena = SLTNodeArena::new(); + let node = self.expr_slt(amount, None, &mut arena)?; + let original = self.lower_slt(&arena, node)?; + let node = coerce_node_width(&mut arena, node, Some(PROCESS_DELAY_WIDTH), signed) + .map_err(slt_error)?; + let delay = self.lower_slt(&arena, node)?; + let delay = self.zero_if_unknown(delay, original); + self.with_kernel(|kernel| kernel.inactive_delay(delay)) + .map_err(kernel_error) + } + + /// `value` as a two-state register that is zero when `source` has an + /// unknown bit. + fn zero_if_unknown(&mut self, value: RegisterId, source: RegisterId) -> RegisterId { + let width = self.b.register(&value).width(); + if !matches!(self.b.register(&source), RegisterType::Logic { .. }) { + return value; + } + // The reduction XOR of a value is unknown exactly when a bit is. + let reduced = self.b.alloc_logic(1); + self.b + .emit(SIRInstruction::Unary(reduced, UnaryOp::Xor, source)); + let zero = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); + let one = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); + let is_zero = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Binary( + is_zero, + reduced, + BinaryOp::EqCase, + zero, + )); + let is_one = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Binary( + is_one, + reduced, + BinaryOp::EqCase, + one, + )); + let known = self.b.alloc_bit(1, false); + self.b + .emit(SIRInstruction::Binary(known, is_zero, BinaryOp::Or, is_one)); + let value = match *self.b.register(&value) { + RegisterType::Logic { width } => { + let two_state = self.b.alloc_bit(width, false); + self.b + .emit(SIRInstruction::Unary(two_state, UnaryOp::ToTwoState, value)); + two_state + } + _ => value, + }; + let zero = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); + let result = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Mux(result, known, value, zero)); + result + } + + /// `@(items)` (IEEE 1800-2023 9.4.2): the process waits for an + /// occurrence of any item, which the runtime detects on the watched + /// signals themselves, so nothing is left to check when it resumes. + fn wait_event(&mut self, items: &[sv::ir::EventItem]) -> Result<(), sv::AnalyzerError> { + let mut terms = Vec::new(); + for item in items { + let id = match &item.expr { + sv::ir::Expr::Ident(name) => self.m.id(name).filter(|&id| !self.m.is_hidden(id)), + _ => None, + } + .ok_or_else(|| unsupported("event expression other than a variable"))?; + match item.edge { + sv::ir::EventEdge::Any => terms.push((id, CounterKind::Changes)), + sv::ir::EventEdge::Pos => terms.push((id, CounterKind::Rises)), + sv::ir::EventEdge::Neg => terms.push((id, CounterKind::Falls)), + sv::ir::EventEdge::Both => { + terms.push((id, CounterKind::Rises)); + terms.push((id, CounterKind::Falls)); + } + } + } + let site = self.wait_site(terms); + self.with_kernel(|kernel| -> Result<(), ProcessKernelError> { + kernel.suspend_wait(site)?; + let woken = kernel.builder().alloc_bit(1, false); + kernel + .builder() + .emit(SIRInstruction::Imm(woken, SIRValue::new(1u8))); + kernel.wake_if(woken); + Ok(()) + }) + .map_err(kernel_error) + } + + /// `wait (condition)` (IEEE 1800-2023 9.4.3): the process goes on at once + /// if the condition holds, and otherwise checks it again whenever a + /// variable it reads changes. + fn wait_level(&mut self, condition: &sv::ir::Expr) -> Result<(), sv::AnalyzerError> { + let mut names = HashSet::default(); + expr_idents(condition, &mut names); + subroutine_reads(self.m, condition, &mut names); + let mut ids: Vec<_> = names + .iter() + .filter_map(|name| self.m.id(name)) + .filter(|&id| !self.m.is_hidden(id)) + .collect(); + ids.sort_unstable(); + ids.dedup(); + let site = self.wait_site( + ids.into_iter() + .map(|id| (id, CounterKind::Changes)) + .collect(), + ); + // The condition is lowered once per check: before the process + // suspends and at every resume. + let mut error = None; + let mut kernel = self.kernel.take().expect("lowering a process kernel"); + std::mem::swap(&mut self.b, kernel.builder()); + // The kernel is out of `self` while it builds the checks; reads go + // to stable state all the same. + let direct = std::mem::replace(&mut self.direct, true); + let result = kernel.wait_level(site, |builder| { + std::mem::swap(&mut self.b, builder); + let truth = self.eval_truth(condition).map(|(truth, _)| truth); + std::mem::swap(&mut self.b, builder); + truth.unwrap_or_else(|e| { + error = Some(e); + let never = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Imm(never, SIRValue::new(0u8))); + never + }) + }); + self.direct = direct; + std::mem::swap(&mut self.b, kernel.builder()); + self.kernel = Some(kernel); + result.map_err(kernel_error)?; + error.map_or(Ok(()), Err) + } + + /// Declare a wait site of the process with the given terms and return + /// its local index. + fn wait_site(&mut self, terms: Vec<(SourceVarId, CounterKind)>) -> u32 { + let index = self.wait_sites.len() as u32; + self.wait_sites.push(WaitSite { + process: self.process, + terms, + }); + index + } + + /// The back edge of a kernel loop that may not suspend: count the + /// iteration, yield every 2^[`LOOP_YIELD_BITS`] of them, and continue at + /// `header`. Returns the block the loop's back edges jump to. + fn yielding_back_edge(&mut self, header: BlockId) -> Result { + let back = self.b.new_block(); + let (counter, _) = self.m.temp("loop", LOOP_YIELD_BITS, false, false); + self.b.switch_to_block(back); + let count = self.b.alloc_bit(LOOP_YIELD_BITS, false); + self.b.emit(SIRInstruction::Load( + count, + stable(counter), + SIROffset::Static(0), + LOOP_YIELD_BITS, + )); + let one = self.b.alloc_bit(LOOP_YIELD_BITS, false); + self.b.emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); + let next = self.b.alloc_bit(LOOP_YIELD_BITS, false); + self.b + .emit(SIRInstruction::Binary(next, count, BinaryOp::Add, one)); + self.store(counter, SIROffset::Static(0), LOOP_YIELD_BITS, next); + let zero = self.b.alloc_bit(LOOP_YIELD_BITS, false); + self.b.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); + let wrapped = self.b.alloc_bit(1, false); + self.b + .emit(SIRInstruction::Binary(wrapped, next, BinaryOp::Eq, zero)); + let yield_block = self.b.new_block(); + self.b.seal_block(SIRTerminator::Branch { + cond: wrapped, + true_block: (yield_block, Vec::new()), + false_block: (header, Vec::new()), + }); + self.b.switch_to_block(yield_block); + self.with_kernel(ProcessKernelBuilder::yield_now) + .map_err(kernel_error)?; + self.jump(header); + Ok(back) } } +/// Iterations, as a power of two, between the yields of a kernel loop that +/// may not suspend. +const LOOP_YIELD_BITS: usize = 16; + +/// Whether every pass through `stmts` suspends the process. +fn always_suspends(stmts: &[sv::ir::Stmt]) -> bool { + stmts + .iter() + .any(|stmt| matches!(stmt, sv::ir::Stmt::Delay(_) | sv::ir::Stmt::WaitEvent(_))) +} + +/// The module variables the subroutines `expr` calls read, directly or +/// through further calls, besides their own formals and locals. +fn subroutine_reads(pm: &ProcModule<'_>, expr: &sv::ir::Expr, names: &mut HashSet) { + let mut pending = Vec::new(); + collect_call_names(expr, &mut pending); + let mut visited = HashSet::default(); + while let Some(name) = pending.pop() { + if !visited.insert(name.clone()) { + continue; + } + let Some(subroutine) = pm.subroutine(&name) else { + continue; + }; + for param in &subroutine.params { + if let Some(default) = ¶m.default { + expr_idents(default, names); + } + } + for stmt in &subroutine.body { + let mut stmt = stmt.clone(); + stmt.visit_mut( + &mut |expr| { + expr_idents(expr, names); + collect_call_names(expr, &mut pending); + }, + &mut |_| {}, + &mut |_| {}, + ); + stmt.walk(&mut |stmt| { + if let sv::ir::Stmt::Call { name, .. } = stmt { + pending.push(name.clone()); + } + }); + } + } +} + +/// The names of the user subroutines `expr` calls. +fn collect_call_names(expr: &sv::ir::Expr, names: &mut Vec) { + let called = std::cell::RefCell::new(Vec::new()); + expr_calls(expr, &|callee| { + if let Some(name) = callee.subroutine() { + called.borrow_mut().push(name.to_string()); + } + false + }); + names.extend(called.into_inner()); +} + +fn kernel_error(error: ProcessKernelError) -> sv::AnalyzerError { + unsupported(error.to_string()) +} + fn seal_drained(mut builder: SIRBuilder) -> ExecutionUnit { let (blocks, register_map, _) = builder.drain(); let mut unit = ExecutionUnit { diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 597abeb4e3d..728194843a8 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -449,6 +449,8 @@ pub(crate) fn project_module_with_ids( Ok(( crate::symbolic::artifact::SimModule { + time_precision: None, + time_scale: celox_design::TimeScale::default(), name: veryl_parser::resource_table::get_str_value(module.name).unwrap_or_default(), variables, ff_access_summaries: module diff --git a/crates/celox-napi/src/lib.rs b/crates/celox-napi/src/lib.rs index a07a0fcd5b0..4db8c62de46 100644 --- a/crates/celox-napi/src/lib.rs +++ b/crates/celox-napi/src/lib.rs @@ -684,6 +684,7 @@ struct CachedBuild { state_schema: Arc, /// Pre-computed VCD signal descriptors so VCD works on cache hits. vcd_descs: Vec, + time_precision: celox_design::TimePrecision, /// Derived clock domains per event, valid for every backend sharing /// `shared_code`. derived_ticks: celox::DerivedTickPlans, @@ -1127,6 +1128,7 @@ impl NativeSimulatorHandle { let state_fingerprint = sim.state_fingerprint(); let state_schema = sim.state_schema(); let vcd_descs = sim.build_vcd_descs(four_state); + let time_precision = sim.program().design.time_precision; let runtime_errors = runtime_errors_by_name(sim.program()); let derived_ticks = sim.derived_tick_plans(); let event_edges = sim.event_edges(); @@ -1156,6 +1158,7 @@ impl NativeSimulatorHandle { state_fingerprint, state_schema: Arc::clone(&state_schema), vcd_descs: vcd_descs.clone(), + time_precision, derived_ticks: Arc::clone(&derived_ticks), event_edges: Arc::clone(&event_edges), }); @@ -1166,7 +1169,7 @@ impl NativeSimulatorHandle { // Create VcdWriter if requested let vcd_writer = if let Some(path) = vcd_path { Some( - celox::VcdWriter::new(path, &vcd_descs) + celox::VcdWriter::new_with_time_precision(path, &vcd_descs, time_precision) .map_err(|e| Error::from_reason(format!("Failed to create VCD: {}", e)))?, ) } else { @@ -1262,8 +1265,12 @@ impl NativeSimulatorHandle { ))); let vcd_writer = if let Some(path) = vcd_path { Some( - celox::VcdWriter::new(path, &cached.vcd_descs) - .map_err(|e| Error::from_reason(format!("Failed to create VCD: {}", e)))?, + celox::VcdWriter::new_with_time_precision( + path, + &cached.vcd_descs, + cached.time_precision, + ) + .map_err(|e| Error::from_reason(format!("Failed to create VCD: {}", e)))?, ) } else { None @@ -4344,6 +4351,35 @@ mod tests { ); } + #[test] + fn cached_waveforms_retain_explicit_time_precision() { + let dir = tempfile::tempdir().unwrap(); + let source = "module CachedPrecision(y: output logic) {}"; + let sources = make_sources(&[(source, "cached_precision.veryl")]); + let key = build_cache_key(&sources, "CachedPrecision", &default_opts(), None); + let sim = celox::Simulator::builder(source, "CachedPrecision") + .vcd(dir.path().join("initial.vcd")) + .build() + .unwrap(); + let handle = NativeSimulatorHandle::build_and_cache(sim, None, Some(key.clone())).unwrap(); + drop(handle); + let mut cached = JIT_CACHE + .lock() + .unwrap_or_else(|e| e.into_inner()) + .remove(&key) + .unwrap(); + // A frontend with a non-default scale supplies this cached metadata. + Arc::get_mut(&mut cached).unwrap().time_precision = + celox_design::TimePrecision::try_from(-15).unwrap(); + let path = dir.path().join("cached.vcd"); + let mut handle = NativeSimulatorHandle::from_cached(&cached, path.to_str()).unwrap(); + handle.dump(123.0).unwrap(); + handle.vcd_writer.as_mut().unwrap().flush().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert!(text.contains("$timescale 1fs $end"), "{text}"); + assert!(text.contains("#123\n")); + } + #[test] fn vcd_paths_share_compiled_code_but_tracing_modes_do_not() { let src = make_sources(&[("module Top {}", "a.veryl")]); diff --git a/crates/celox-runtime/src/derived_tick.rs b/crates/celox-runtime/src/derived_tick.rs index 902b8ccaf08..19b35c1d783 100644 --- a/crates/celox-runtime/src/derived_tick.rs +++ b/crates/celox-runtime/src/derived_tick.rs @@ -30,14 +30,14 @@ use celox_design::{ DomainKind, GateOp, - edges::{active_level, settled_edge}, + edges::{LEVEL_UNKNOWN, active_level, settled_edge}, schedule::ScheduleModel, }; use crate::{ AbsoluteAddr, SignalRef, SimulatorErrorCode, backend::{EventHandle, SimBackend}, - simulation::{HostBoundary, UnitExecutor, event_level}, + simulation::{HostBoundary, UnitExecutor, edge_level}, timing::Halt, }; @@ -279,6 +279,9 @@ pub struct DerivedTickPlan { /// Every gate has a program over two-state values, so gates are judged /// without settling the design. fast: bool, + /// The design keeps unknown bits: levels are read with their masks and + /// edges follow the four-state rows of IEEE 1800-2023 Table 9-2. + four_state: bool, /// The gated domains read and write no state the ticked domain writes, /// nor one another's, so they may run before it, one at a time, with the /// result of evaluating them together. @@ -296,10 +299,11 @@ pub struct DerivedTickScratch { ready: Vec, } -/// The entry's level at the start of the current phase. -const WAS: u8 = 1; +/// The entry's edge level (see [`edge_level`]) at the start of the +/// current phase. +const WAS: u8 = 1 | LEVEL_UNKNOWN; /// The entry's domain already ran in the current phase. -const FIRED: u8 = 2; +const FIRED: u8 = 4; impl DerivedTickScratch { #[inline] @@ -391,6 +395,7 @@ pub fn build_derived_tick_plans( domains, levers, fast, + four_state: !two_state, independent, })); } @@ -419,8 +424,10 @@ impl DerivedTickPlan { let mut domains: Vec> = Vec::new(); let mut levers: Vec<(SignalRef, u8)> = Vec::new(); let mut fast = true; + let mut four_state = false; for plan in plans { fast &= plan.fast; + four_state |= plan.four_state; for domain in &plan.gated { let id = domain.derived.domain.eval_apply.id(); if ticked(&domain.derived.domain) @@ -461,6 +468,7 @@ impl DerivedTickPlan { domains: domains.into(), levers: levers.into(), fast, + four_state, independent: false, } } @@ -513,6 +521,9 @@ impl DerivedTickPlan { /// `run.fire_sources`, every gated clock that sees its active edge in /// `run.transitions`, then the cascade rounds. Returns whether /// combinational logic is settled afterwards; it is not when nothing ran. + /// + /// The levels of [`EdgeRun::transitions`] are edge levels (see + /// [`celox_design::edges`]): a lever may leave x or z. pub fn run( &self, executor: &mut X, @@ -520,6 +531,25 @@ impl DerivedTickPlan { settle: bool, run: EdgeRun<'_>, ) -> Result + where + X: TickExecutor, + X::Backend: SimBackend, + { + if self.four_state { + self.run_in::(executor, scratch, settle, run) + } else { + self.run_in::(executor, scratch, settle, run) + } + } + + /// [`Self::run`] with levels read in the design's state mode. + fn run_in( + &self, + executor: &mut X, + scratch: &mut DerivedTickScratch, + settle: bool, + run: EdgeRun<'_>, + ) -> Result where X: TickExecutor, X::Backend: SimBackend, @@ -527,7 +557,7 @@ impl DerivedTickPlan { scratch.prepare(self.domains.len() + self.gated.len(), self.levers.len()); // The baseline is the state settled after the previous operation, // as the timed scheduler keeps it between steps. - self.sample_domains(executor.backend(), scratch); + self.sample_domains::(executor.backend(), scratch); let sources: &[EventDomain] = if run.fire_sources { &self.sources } else { &[] }; if self.gated.is_empty() { if sources.is_empty() { @@ -535,19 +565,25 @@ impl DerivedTickPlan { } fire(executor, settle, sources.iter())?; executor.eval_comb()?; - self.rounds(executor, scratch, run.transitions)?; + self.rounds::(executor, scratch, run.transitions)?; return Ok(true); } if self.fast { - self.run_gated_fast(executor, scratch, settle, sources, run.transitions)?; + self.run_gated_fast::( + executor, + scratch, + settle, + sources, + run.transitions, + )?; } else { - self.run_gated_settled(executor, scratch, settle, sources, &run)?; + self.run_gated_settled::(executor, scratch, settle, sources, &run)?; } Ok(true) } /// Gates judged by their programs: no settle beyond the ticked domains'. - fn run_gated_fast( + fn run_gated_fast( &self, executor: &mut X, scratch: &mut DerivedTickScratch, @@ -565,9 +601,9 @@ impl DerivedTickPlan { for (index, domain) in self.gated.iter().enumerate() { let (from, to) = transitions[domain.lever]; let backend = executor.backend(); - let before = self.gate_level(backend, domain, from); - let after = self.gate_level(backend, domain, to); - let fired = settled_edge(domain.derived.kind, before, after); + let before = self.gate_level::(backend, domain, from); + let after = self.gate_level::(backend, domain, to); + let fired = settled_edge::(domain.derived.kind, before, after); if fired { scratch.ready.push(index); } @@ -577,12 +613,12 @@ impl DerivedTickPlan { executor.eval_comb()?; // The commit may move a gate, as the nonblocking updates after the // edge do; that is a further edge of the gated clock. - self.rounds(executor, scratch, transitions) + self.rounds::(executor, scratch, transitions) } /// Gates without programs: settle the design with the levers at each /// level, as the timed scheduler does at the edge. - fn run_gated_settled( + fn run_gated_settled( &self, executor: &mut X, scratch: &mut DerivedTickScratch, @@ -604,8 +640,17 @@ impl DerivedTickPlan { scratch.flags[saved + 2 * index] = u8::try_from(&value).unwrap_or(0); scratch.flags[saved + 2 * index + 1] = u8::try_from(&mask).unwrap_or(0); } - if event_level(executor.backend(), signal) != from { - executor.backend_mut().set(signal, from); + if edge_level::(executor.backend(), signal) != from { + if FOUR_STATE && from & LEVEL_UNKNOWN != 0 { + // The lever leaves x or z. + executor.backend_mut().set_four_state( + signal, + num_bigint::BigUint::from(from & 1), + num_bigint::BigUint::from(1u8), + ); + } else { + executor.backend_mut().set(signal, from); + } moved = true; } } @@ -613,7 +658,7 @@ impl DerivedTickPlan { executor.eval_comb()?; } for (index, domain) in self.gated.iter().enumerate() { - let level = event_level(executor.backend(), domain.derived.signal) != 0; + let level = edge_level::(executor.backend(), domain.derived.signal); scratch.flags[base + index] = flags(level, false); } for (index, &(signal, _)) in self.levers.iter().enumerate() { @@ -622,9 +667,9 @@ impl DerivedTickPlan { executor.eval_comb()?; scratch.ready.clear(); for (index, domain) in self.gated.iter().enumerate() { - let before = scratch.flags[base + index] & WAS != 0; - let after = event_level(executor.backend(), domain.derived.signal) != 0; - let fired = settled_edge(domain.derived.kind, before, after); + let before = scratch.flags[base + index] & WAS; + let after = edge_level::(executor.backend(), domain.derived.signal); + let fired = settled_edge::(domain.derived.kind, before, after); if fired { scratch.ready.push(index); } @@ -632,7 +677,7 @@ impl DerivedTickPlan { } self.fire_with_gated(executor, false, sources, &scratch.ready)?; executor.eval_comb()?; - self.rounds(executor, scratch, run.transitions)?; + self.rounds::(executor, scratch, run.transitions)?; if run.persist { return Ok(()); } @@ -684,24 +729,34 @@ impl DerivedTickPlan { /// A gated clock's level with its lever at `level`, from its program in /// the fast path and from the settled design otherwise. #[inline] - fn gate_level(&self, backend: &B, domain: &GatedDomain, level: u8) -> bool { + fn gate_level( + &self, + backend: &B, + domain: &GatedDomain, + level: u8, + ) -> u8 { match &domain.gate { - Some(gate) if self.fast => gate.level(backend, level), - _ => event_level(backend, domain.derived.signal) != 0, + Some(gate) if self.fast => u8::from(gate.level(backend, level)), + _ => edge_level::(backend, domain.derived.signal), } } #[inline] - fn sample_domains(&self, backend: &B, scratch: &mut DerivedTickScratch) { + fn sample_domains( + &self, + backend: &B, + scratch: &mut DerivedTickScratch, + ) { for (index, domain) in self.domains.iter().enumerate() { - scratch.flags[index] = flags(event_level(backend, domain.signal) != 0, false); + let level = edge_level::(backend, domain.signal); + scratch.flags[index] = flags(level, false); } } /// Cascade rounds over the state-derived and gated domains: each round /// runs together every domain whose clock moved to its active edge since /// the phase began, then settles, until no further edge appears. - fn rounds( + fn rounds( &self, executor: &mut X, scratch: &mut DerivedTickScratch, @@ -719,8 +774,8 @@ impl DerivedTickPlan { if state & FIRED != 0 { continue; } - let is = event_level(executor.backend(), domain.signal) != 0; - if settled_edge(domain.kind, state & WAS != 0, is) { + let is = edge_level::(executor.backend(), domain.signal); + if settled_edge::(domain.kind, state & WAS, is) { scratch.ready.push(index); } } @@ -729,8 +784,12 @@ impl DerivedTickPlan { if state & FIRED != 0 { continue; } - let is = self.gate_level(executor.backend(), domain, transitions[domain.lever].1); - if settled_edge(domain.derived.kind, state & WAS != 0, is) { + let is = self.gate_level::( + executor.backend(), + domain, + transitions[domain.lever].1, + ); + if settled_edge::(domain.derived.kind, state & WAS, is) { scratch.ready.push(base + index); } } @@ -759,8 +818,8 @@ impl DerivedTickPlan { /// How an edge moves the signals that gate a plan's derived clocks. #[derive(Clone, Copy, Debug)] pub struct EdgeRun<'a> { - /// Per lever ([`DerivedTickPlan::lever_signals`]), its level before and - /// after the edge. + /// Per lever ([`DerivedTickPlan::lever_signals`]), its edge level (see + /// [`celox_design::edges`]) before and after the edge. pub transitions: &'a [(u8, u8)], /// The levers stay at their new level; otherwise they are left as they /// were before the edge. @@ -770,12 +829,15 @@ pub struct EdgeRun<'a> { } #[inline] -fn flags(level: bool, fired: bool) -> u8 { - (u8::from(level) * WAS) | (u8::from(fired) * FIRED) +fn flags(level: u8, fired: bool) -> u8 { + level | (u8::from(fired) * FIRED) } /// Evaluate and commit `domains` as one coincident edge: each of them /// samples the same state, then all of them commit. +// Instantiated for each state mode, it would otherwise stay out of line, +// which costs two-state ticks the call. +#[inline(always)] fn fire<'a, X, E>( executor: &mut X, settle: bool, diff --git a/crates/celox-runtime/src/edge.rs b/crates/celox-runtime/src/edge.rs index 721da594786..3d404e53dfe 100644 --- a/crates/celox-runtime/src/edge.rs +++ b/crates/celox-runtime/src/edge.rs @@ -13,7 +13,7 @@ //! so the inactive edge of a clock that only clocks flip-flops costs no //! settle on the next active edge. -use celox_design::{DomainKind, EventTopology}; +use celox_design::{DomainKind, EventTopology, edges::LEVEL_UNKNOWN}; use crate::{ AbsoluteAddr, SignalRef, @@ -21,7 +21,7 @@ use crate::{ derived_tick::{ DerivedTickPlan, DerivedTickPlans, DerivedTickScratch, EdgeRun, EventDomain, TickExecutor, }, - simulation::event_level, + simulation::{edge_level, event_level}, timing::Halt, }; @@ -133,16 +133,19 @@ fn moved_only(comb_read: bool) -> EdgeOutcome { } } -/// The level of `signal`, or `None` while it is unknown. -fn level(backend: &B, signal: SignalRef) -> Option { +/// The edge level of `signal` (see [`celox_design::edges`]): 0, 1, or, in a +/// four-state design, x or z. +fn level(backend: &B, signal: SignalRef) -> u8 { if signal.is_4state && backend.layout().four_state { - let (value, mask) = backend.get_four_state(signal); - if mask.bit(0) { - return None; - } - return Some(value.bit(0)); + edge_level::(backend, signal) + } else { + u8::from(event_level(backend, signal) != 0) } - Some(event_level(backend, signal) != 0) +} + +/// The known value of an edge level, or `None` for x and z. +fn known(level: u8) -> Option { + (level & LEVEL_UNKNOWN == 0).then_some(level != 0) } /// Writes an event signal's new level: the host's own write of the signal, @@ -170,11 +173,22 @@ pub fn move_signal( backend: &mut B, info: &EventEdge, edge: Edge, - mut write: impl SignalWrite, + write: impl SignalWrite, ) -> Option> { + move_level(backend, info, edge, write).map(known) +} + +/// [`move_signal`], returning the edge level the signal had: x or z leave +/// for 1 or 0 like 0 or 1 do (IEEE 1800-2023 Table 9-2). +fn move_level( + backend: &mut B, + info: &EventEdge, + edge: Edge, + mut write: impl SignalWrite, +) -> Option { let old = level(backend, info.signal); let new = edge.level(); - if old == Some(new != 0) { + if old == new { return None; } write.write(backend, info.signal, new); @@ -201,14 +215,15 @@ where X::Backend: SimBackend, E: EventHandle, { - let Some(old) = move_signal(executor.backend_mut(), &info, edge, write) else { + let Some(from) = move_level(executor.backend_mut(), &info, edge, write) else { return Ok(EdgeOutcome::Unchanged); }; let new = edge.level(); - let fires = info.fires(old, edge); + let fires = info.fires(known(from), edge); let settle = dirty || info.comb_read; if let Some(plan) = plan { - let from = old.map_or(new ^ 1, u8::from); + // A gated clock is judged from the lever's real level before the + // edge, x and z included. let transition = [(from, new)]; let transitions: &[(u8, u8)] = if plan.lever_signals().next().is_some() { &transition @@ -283,14 +298,14 @@ where let info = &edges[id]; let old = level(executor.backend(), info.signal); let new = edge.level(); - if old == Some(new != 0) || transitions.iter().any(|(signal, _)| *signal == info.signal) { + if old == new || transitions.iter().any(|(signal, _)| *signal == info.signal) { continue; } any_moved = true; write.write(executor.backend_mut(), info.signal, new); - transitions.push((info.signal, (old.map_or(new ^ 1, u8::from), new))); + transitions.push((info.signal, (old, new))); comb_read |= info.comb_read; - if info.fires(old, edge) { + if info.fires(known(old), edge) { let address = executor.backend().id_to_addr_slice()[id]; sources.push(EventDomain { eval_apply: event, diff --git a/crates/celox-runtime/src/reflection.rs b/crates/celox-runtime/src/reflection.rs index d29ea346a56..272f81c49b3 100644 --- a/crates/celox-runtime/src/reflection.rs +++ b/crates/celox-runtime/src/reflection.rs @@ -24,6 +24,7 @@ pub struct ReflectionScope { pub name: String, pub full_name: String, pub module_name: String, + pub time_scale: celox_design::TimeScale, pub parent: Option, pub children: Vec, pub signals: Vec, diff --git a/crates/celox-runtime/src/simulation/batch.rs b/crates/celox-runtime/src/simulation/batch.rs index 4fe08593259..0972bd60d3a 100644 --- a/crates/celox-runtime/src/simulation/batch.rs +++ b/crates/celox-runtime/src/simulation/batch.rs @@ -2,7 +2,7 @@ //! stable-edge helpers it calls, kept in one module. use bit_set::BitSet; -use celox_design::edges::{scheduled_edge, settled_edge}; +use celox_design::edges::{LEVEL_UNKNOWN, settled_edge}; use super::SimulationState; use super::host::SimulationExecutor; @@ -20,8 +20,53 @@ pub(crate) fn event_level(backend: &B, signal: SignalRef) -> u8 { } } +/// The edge level (see [`celox_design::edges`]) of an event signal: 0, 1, +/// or, in a four-state design, [`LEVEL_UNKNOWN`] with the value bit for x +/// and z. `FOUR_STATE` is the design's state mode; a two-state design reads +/// only the value bits, as [`event_level`] does. +#[inline] +pub(crate) fn edge_level( + backend: &B, + signal: SignalRef, +) -> u8 { + let value = u8::from(event_level(backend, signal) != 0); + if FOUR_STATE && signal.is_4state && event_unknown(backend, signal) { + value | LEVEL_UNKNOWN + } else { + value + } +} + +/// Whether a four-state event signal has unknown bits. Its mask plane +/// follows its value bytes in the state image. +#[inline] +fn event_unknown(backend: &B, signal: SignalRef) -> bool { + let mask = SignalRef { + offset: signal.offset + celox_state_layout::get_byte_size(signal.width), + width: signal.width, + is_4state: false, + array_layout: None, + }; + event_level(backend, mask) != 0 +} + impl SimulationState { + #[inline(always)] pub(super) fn stable_edge_triggered(&self, backend: &B, id: usize) -> bool { + if self.four_state { + self.stable_edge_triggered_four_state(backend, id) + } else { + self.stable_edge_triggered_in::(backend, id) + } + } + + #[inline(never)] + fn stable_edge_triggered_four_state(&self, backend: &B, id: usize) -> bool { + self.stable_edge_triggered_in::(backend, id) + } + + #[inline(always)] + fn stable_edge_triggered_in(&self, backend: &B, id: usize) -> bool { let Some((signal, _)) = self .model .topo_signals @@ -29,20 +74,28 @@ impl SimulationState { else { return true; }; - let was_nonzero = self.last_clock_values.contains(id); - let is_nonzero = event_level(backend, *signal) != 0; - settled_edge(self.model.domain_kinds[id], was_nonzero, is_nonzero) + let was = self.last_level_in::(id); + let is = edge_level::(backend, *signal); + settled_edge::(self.model.domain_kinds[id], was, is) } pub(super) fn replace_triggers_with_stable_edges(&self, backend: &mut B) { + if self.four_state { + self.replace_triggers_in::(backend); + } else { + self.replace_triggers_in::(backend); + } + } + + fn replace_triggers_in(&self, backend: &mut B) { backend.clear_triggered_bits(); for (signal, id) in &self.model.topo_signals { if *id == usize::MAX { continue; } - let was_nonzero = self.last_clock_values.contains(*id); - let is_nonzero = event_level(backend, *signal) != 0; - if settled_edge(self.model.domain_kinds[*id], was_nonzero, is_nonzero) { + let was = self.last_level_in::(*id); + let is = edge_level::(backend, *signal); + if settled_edge::(self.model.domain_kinds[*id], was, is) { backend.mark_triggered_bit(*id); } } @@ -80,14 +133,14 @@ impl SimulationState { self.model .signal_to_id .get(&event.signal) - .map(|&id| (id, event.next_val != 0)) + .map(|&id| (id, u8::from(event.next_val != 0))) }); // Scheduled signals that changed level and gate derived clocks. let mut gating_sources = Vec::new(); - for (id, is_nonzero) in scheduled { + for (id, is) in scheduled { track_stable_edges = true; - let was_nonzero = self.last_clock_values.contains(id); - if was_nonzero != is_nonzero + let was = self.last_level(id); + if was != is && self .model .combinational_derived @@ -96,8 +149,7 @@ impl SimulationState { { gating_sources.push(id); } - let triggered = scheduled_edge(self.model.domain_kinds[id], was_nonzero, is_nonzero); - if triggered { + if self.scheduled_edge(id, was, is) { scheduled_trigger_ids.insert(id); executor.backend_mut().mark_triggered_bit(id); } @@ -130,25 +182,23 @@ impl SimulationState { // NBA region do. let mut edge_approved: Option = None; for &source in &gating_sources { - for &id in self.model.combinational_derived[source].iter() { + for index in 0..self.model.combinational_derived[source].len() { + let id = self.model.combinational_derived[source][index]; if self.stable_edge_triggered(executor.backend(), id) { executor.backend_mut().mark_triggered_bit(id); edge_approved .get_or_insert_with(|| BitSet::with_capacity(num_events)) .insert(id); } - let Some((signal, _)) = self + let Some(&(signal, _)) = self .model .topo_signals .get(self.model.signal_index_by_id[id]) else { continue; }; - if event_level(executor.backend(), *signal) != 0 { - self.last_clock_values.insert(id); - } else { - self.last_clock_values.remove(id); - } + let level = self.level(executor.backend(), signal); + self.record_level(id, level); } } diff --git a/crates/celox-runtime/src/simulation/edges.rs b/crates/celox-runtime/src/simulation/edges.rs index 20ecd99b1a9..25d14024a09 100644 --- a/crates/celox-runtime/src/simulation/edges.rs +++ b/crates/celox-runtime/src/simulation/edges.rs @@ -1,38 +1,137 @@ //! Edges of event signals: marking the domains that scheduled values, //! process writes, publications and counters trigger. -use celox_design::edges::{scheduled_edge, settled_edge}; +use celox_design::edges::{LEVEL_UNKNOWN, scheduled_edge, settled_edge}; use super::round::Round; -use super::{SimulationState, event_level}; -use crate::{backend::SimBackend, timing::kind_index}; +use super::{SimulationState, edge_level}; +use crate::{SignalRef, backend::SimBackend, timing::kind_index}; impl SimulationState { /// Take the levels of the event signals as the baseline that edge /// detection compares against. + #[inline(always)] pub(super) fn resample_clock_values(&mut self, backend: &B) { - for (signal, id) in &self.model.topo_signals { - if *id == usize::MAX { - continue; - } - if event_level(backend, *signal) != 0 { - self.last_clock_values.insert(*id); - } else { - self.last_clock_values.remove(*id); - } - } + self.record_all_levels(backend); } /// Rebase edge detection after state was advanced outside this scheduler. pub fn synchronize_event_values(&mut self, backend: &B) { self.last_clock_values.make_empty(); - for (signal, id) in &self.model.topo_signals { - if *id == usize::MAX { - continue; + self.last_clock_unknown.make_empty(); + self.record_all_levels(backend); + } + + // The four-state paths of the level helpers stay out of line, so that a + // two-state design's callers keep the size and inlining they had before. + + /// The current edge level of an event signal (see [`edge_level`]). + #[inline] + pub(super) fn level(&self, backend: &B, signal: SignalRef) -> u8 { + if self.four_state { + self.level_four_state(backend, signal) + } else { + edge_level::(backend, signal) + } + } + + #[inline(never)] + fn level_four_state(&self, backend: &B, signal: SignalRef) -> u8 { + edge_level::(backend, signal) + } + + /// The edge level of event `id` when edge detection last sampled it. + #[inline] + pub(super) fn last_level_in(&self, id: usize) -> u8 { + let value = u8::from(self.last_clock_values.contains(id)); + if FOUR_STATE && self.last_clock_unknown.contains(id) { + value | LEVEL_UNKNOWN + } else { + value + } + } + + #[inline] + pub(super) fn last_level(&self, id: usize) -> u8 { + if self.four_state { + self.last_level_four_state(id) + } else { + self.last_level_in::(id) + } + } + + #[inline(never)] + fn last_level_four_state(&self, id: usize) -> u8 { + self.last_level_in::(id) + } + + /// Make `level` the baseline of event `id`'s next edge. + #[inline] + fn record_level_in(&mut self, id: usize, level: u8) { + if level & 1 != 0 { + self.last_clock_values.insert(id); + } else { + self.last_clock_values.remove(id); + } + if FOUR_STATE { + if level & LEVEL_UNKNOWN != 0 { + self.last_clock_unknown.insert(id); + } else { + self.last_clock_unknown.remove(id); } - if event_level(backend, *signal) != 0 { - self.last_clock_values.insert(*id); + } + } + + #[inline] + pub(super) fn record_level(&mut self, id: usize, level: u8) { + if self.four_state { + self.record_level_four_state(id, level); + } else { + self.record_level_in::(id, level); + } + } + + #[inline(never)] + fn record_level_four_state(&mut self, id: usize, level: u8) { + self.record_level_in::(id, level); + } + + /// Make every event's current level the baseline of its next edge. + #[inline(always)] + pub(super) fn record_all_levels(&mut self, backend: &B) { + if self.four_state { + self.record_levels_four_state(backend); + } else { + self.record_levels::(backend); + } + } + + #[inline(never)] + fn record_levels_four_state(&mut self, backend: &B) { + self.record_levels::(backend); + } + + #[inline(always)] + fn record_levels(&mut self, backend: &B) { + for index in 0..self.model.topo_signals.len() { + let (signal, id) = self.model.topo_signals[index]; + if id == usize::MAX { + continue; } + let level = edge_level::(backend, signal); + self.record_level_in::(id, level); + } + } + + /// Whether a scheduled or process-driven change of event `id` from level + /// `was` to `is` triggers its domain. + #[inline] + pub(super) fn scheduled_edge(&self, id: usize, was: u8, is: u8) -> bool { + let kind = self.model.domain_kinds[id]; + if self.four_state { + scheduled_edge::(kind, was, is) + } else { + scheduled_edge::(kind, was, is) } } @@ -60,14 +159,13 @@ impl SimulationState { &self, backend: &mut B, round: &mut Round, - values: &[(usize, bool)], + values: &[(usize, u8)], ) { - for &(id, is_nonzero) in values { + for &(id, is) in values { round.track_stable_edges = true; - // A signal written again compares with its preceding value. - let was_nonzero = - round.previous(id, is_nonzero, || self.last_clock_values.contains(id)); - if was_nonzero != is_nonzero + // A signal written again compares with its preceding level. + let was = round.previous(id, is, || self.last_level(id)); + if was != is && self .model .combinational_derived @@ -76,21 +174,21 @@ impl SimulationState { { round.gating_sources.push(id); } - let triggered = scheduled_edge(self.model.domain_kinds[id], was_nonzero, is_nonzero); - if triggered { + if self.scheduled_edge(id, was, is) { round.scheduled_trigger_ids.insert(id); backend.mark_triggered_bit(id); } } } + /// The edge level (see [`edge_level`]) of every event signal. pub(super) fn event_values(&self, backend: &B, values: &mut Vec) { values.clear(); values.extend( self.model .topo_signals .iter() - .map(|(signal, _)| event_level(backend, *signal)), + .map(|(signal, _)| self.level(backend, *signal)), ); } @@ -105,7 +203,7 @@ impl SimulationState { .zip(&round.after) { if *id != usize::MAX && old != new { - round.transitions.push((*id, new != 0)); + round.transitions.push((*id, new)); } } std::mem::swap(&mut round.before, &mut round.after); @@ -118,12 +216,16 @@ impl SimulationState { &self, backend: &mut B, round: &mut Round, - transitions: &[(usize, bool)], + transitions: &[(usize, u8)], ) { - for &(id, is_nonzero) in transitions { - let was_nonzero = - round.previous(id, is_nonzero, || self.last_clock_values.contains(id)); - let triggered = settled_edge(self.model.domain_kinds[id], was_nonzero, is_nonzero); + for &(id, is) in transitions { + let was = round.previous(id, is, || self.last_level(id)); + let kind = self.model.domain_kinds[id]; + let triggered = if self.four_state { + settled_edge::(kind, was, is) + } else { + settled_edge::(kind, was, is) + }; if triggered { round.occurrences.insert(id); round.scheduled_trigger_ids.insert(id); diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 1e9708c0f61..2c09657edd9 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -16,7 +16,7 @@ use std::{cmp::Reverse, collections::BinaryHeap}; use bit_set::BitSet; use celox_design::CounterKind; -pub(crate) use batch::event_level; +pub(crate) use batch::{edge_level, event_level}; pub use host::{HostBoundary, HostWatch, SimulationExecutor, UnitExecutor}; pub use nba::NbaUpdate; pub use persist::{ScheduleParts, SimulationSnapshot}; @@ -83,7 +83,15 @@ struct Suspended { /// Backend-independent state and execution rules for timed simulation. pub struct SimulationState { scheduler: Scheduler, + /// Events whose signal was high (value bit set) when edge detection last + /// sampled it. last_clock_values: BitSet, + /// Events whose signal was x or z when edge detection last sampled it. + /// Empty unless the design is four-state. + last_clock_unknown: BitSet, + /// The design keeps unknown bits, so edges follow the four-state rows + /// of IEEE 1800-2023 Table 9-2. + four_state: bool, /// The design's scheduling facts, which never change. model: ResolvedSchedule, process_wakeups: BinaryHeap, @@ -120,12 +128,6 @@ impl SimulationState { /// Every process of `model` starts at time zero, in list order. pub fn new(backend: &B, model: ResolvedSchedule) -> Self { - let mut last_clock_values = BitSet::with_capacity(backend.num_events()); - for (signal, id) in model.topo_signals.iter().copied() { - if id != usize::MAX && event_level(backend, signal) != 0 { - last_clock_values.insert(id); - } - } let process_state = ProcessState { domain_counters: model .counted @@ -136,9 +138,11 @@ impl SimulationState { .collect(), ..ProcessState::default() }; - Self { + let mut state = Self { scheduler: Scheduler::new(), - last_clock_values, + last_clock_values: BitSet::with_capacity(backend.num_events()), + last_clock_unknown: BitSet::new(), + four_state: backend.layout().four_state, process_wakeups: (0..model.processes.len()) .map(|process| Reverse((0, process))) .collect(), @@ -152,7 +156,9 @@ impl SimulationState { round_budget: SLOT_ROUND_BUDGET, return_budget: SLOT_RETURN_BUDGET, slot_passes: 0, - } + }; + state.synchronize_event_values(backend); + state } /// Settle host writes at the current time, then advance to the next time @@ -263,9 +269,7 @@ impl SimulationState { } // Otherwise only an event signal's change needs the current time. for (signal, id) in &self.model.topo_signals { - if *id != usize::MAX - && (event_level(backend, *signal) != 0) != self.last_clock_values.contains(*id) - { + if *id != usize::MAX && self.level(backend, *signal) != self.last_level(*id) { self.host_pending = true; return; } diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index 3006c553a39..5a568466011 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -20,6 +20,7 @@ impl SimulationState { clocks: self.scheduler.clocks.clone(), event_queue: self.scheduler.event_queue.clone(), last_clock_values: self.last_clock_values.clone(), + last_clock_unknown: self.last_clock_unknown.clone(), process_wakeups: self.process_wakeups.clone(), process_state: self.process_state.clone(), host_pending: self.host_pending, @@ -54,6 +55,8 @@ impl SimulationState { self.scheduler.event_queue = event_queue; self.last_clock_values .clone_from(&snapshot.last_clock_values); + self.last_clock_unknown + .clone_from(&snapshot.last_clock_unknown); self.process_wakeups.clone_from(&snapshot.process_wakeups); self.process_state.clone_from(&snapshot.process_state); self.host_pending = snapshot.host_pending; @@ -76,7 +79,10 @@ pub struct ScheduleParts { /// the number of identical such events. pub periodic: Vec<(SimEvent, u64)>, /// Events whose signal was high when edge detection last sampled it. + /// An x counts as high. pub high_events: Vec, + /// Events whose signal was x or z when edge detection last sampled it. + pub unknown_events: Vec, /// Suspended processes and the time each resumes at. pub process_wakeups: Vec<(usize, u64)>, /// Waiting and ready processes, queued nonblocking assignments and the @@ -115,6 +121,11 @@ impl SimulationState { periodic }, high_events: self.last_clock_values.iter().map(|id| events[id]).collect(), + unknown_events: self + .last_clock_unknown + .iter() + .map(|id| events[id]) + .collect(), process_wakeups: { let mut wakeups = self .process_wakeups @@ -162,6 +173,12 @@ impl SimulationState { for event in parts.high_events { self.last_clock_values.insert(event.id()); } + self.last_clock_unknown.make_empty(); + if self.four_state { + for event in parts.unknown_events { + self.last_clock_unknown.insert(event.id()); + } + } self.process_wakeups = parts .process_wakeups .into_iter() @@ -181,6 +198,7 @@ pub struct SimulationSnapshot { clocks: Vec>, event_queue: std::collections::BinaryHeap>, last_clock_values: BitSet, + last_clock_unknown: BitSet, process_wakeups: BinaryHeap, process_state: ProcessState, host_pending: bool, @@ -194,6 +212,7 @@ impl Clone for SimulationSnapshot { clocks: self.clocks.clone(), event_queue: self.event_queue.clone(), last_clock_values: self.last_clock_values.clone(), + last_clock_unknown: self.last_clock_unknown.clone(), process_wakeups: self.process_wakeups.clone(), process_state: self.process_state.clone(), host_pending: self.host_pending, diff --git a/crates/celox-runtime/src/simulation/round.rs b/crates/celox-runtime/src/simulation/round.rs index e30bb87f56e..6ffae56c3a8 100644 --- a/crates/celox-runtime/src/simulation/round.rs +++ b/crates/celox-runtime/src/simulation/round.rs @@ -6,7 +6,7 @@ use bit_set::BitSet; use super::host::SimulationExecutor; use super::nba::{restore_working_image, working_image}; -use super::{EventInfo, SimulationState, Suspended, event_level}; +use super::{EventInfo, SimulationState, Suspended}; use crate::{ SimulatorErrorCode, backend::SimBackend, @@ -31,10 +31,10 @@ pub(super) struct Round { /// Kernels ran in this round, so pending nonblocking flags may be set. pub(super) kernels_ran: bool, pub(super) nba_published: bool, - /// Event-signal values scheduled or written by processes, not yet - /// marked. - pub(super) transitions: Vec<(usize, bool)>, - /// Event-signal values before and after a process run. + /// Event-signal levels (see [`super::edge_level`]) scheduled or written + /// by processes, not yet marked. + pub(super) transitions: Vec<(usize, u8)>, + /// Event-signal levels before and after a process run. pub(super) before: Vec, pub(super) after: Vec, /// Event ids a pulse of several publications triggered; like counted @@ -53,7 +53,7 @@ pub(super) struct Round { /// since the baseline (`last_clock_values`) was last taken, valid where /// the stamp equals `generation`: a value written in one wave of the /// active region is the previous value of the next wave's write. - latest: Vec<(u32, bool)>, + latest: Vec<(u32, u8)>, generation: u32, } @@ -62,24 +62,19 @@ impl Round { /// baseline. fn begin_scan(&mut self, events: usize) { if self.latest.len() < events { - self.latest.resize(events, (0, false)); + self.latest.resize(events, (0, 0)); } self.generation = self.generation.wrapping_add(1); if self.generation == 0 { // Stamps of an earlier wrap must not match. - self.latest.fill((0, false)); + self.latest.fill((0, 0)); self.generation = 1; } } - /// The value event `id` had before this transition: its latest value in + /// The level event `id` had before this transition: its latest level in /// the scan, or `baseline`; records `value` as its latest. - pub(super) fn previous( - &mut self, - id: usize, - value: bool, - baseline: impl FnOnce() -> bool, - ) -> bool { + pub(super) fn previous(&mut self, id: usize, value: u8, baseline: impl FnOnce() -> u8) -> u8 { let (stamp, latest) = std::mem::replace(&mut self.latest[id], (self.generation, value)); if stamp == self.generation { latest @@ -159,23 +154,21 @@ impl SimulationState { /// edge) gives a further edge, as the update events of the NBA region do. fn judge_derived_edges(&mut self, backend: &mut B, round: &mut Round) { for source in std::mem::take(&mut round.gating_sources) { - for &id in self.model.combinational_derived[source].iter() { + for index in 0..self.model.combinational_derived[source].len() { + let id = self.model.combinational_derived[source][index]; if self.stable_edge_triggered(backend, id) { backend.mark_triggered_bit(id); round.edge_approved.insert(id); } - let Some((signal, _)) = self + let Some(&(signal, _)) = self .model .topo_signals .get(self.model.signal_index_by_id[id]) else { continue; }; - if event_level(backend, *signal) != 0 { - self.last_clock_values.insert(id); - } else { - self.last_clock_values.remove(id); - } + let level = self.level(backend, signal); + self.record_level(id, level); } } } @@ -396,7 +389,7 @@ impl SimulationState { self.model .signal_to_id .get(&event.signal) - .map(|&id| (id, event.next_val != 0)) + .map(|&id| (id, u8::from(event.next_val != 0))) })); // The check after the batch already saw every signal. diff --git a/crates/celox-runtime/src/state_file.rs b/crates/celox-runtime/src/state_file.rs index 0a7b177353f..a377679d3ba 100644 --- a/crates/celox-runtime/src/state_file.rs +++ b/crates/celox-runtime/src/state_file.rs @@ -19,6 +19,8 @@ //! event count u32, then per event: scheduled event //! periodic count u32, then per marker: scheduled event | count u64 //! high count u32, then per event: event str +//! (only with FLAG_UNKNOWN_EVENTS) unknown count u32, then per event: +//! event str //! processes (version 2): //! wakeup count u32, then per wakeup: process str | time u64 //! waiter count u32, then per waiter: @@ -47,6 +49,9 @@ const MAGIC: &[u8; 8] = b"CXSTATE\0"; const VERSION: u16 = 2; const FLAG_FOUR_STATE: u16 = 1 << 0; const FLAG_SCHEDULE: u16 = 1 << 1; +/// The schedule lists events whose signal was x or z. Set only when there are +/// any, so other files keep their earlier encoding. +const FLAG_UNKNOWN_EVENTS: u16 = 1 << 2; /// How a state object gets its value. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -94,7 +99,11 @@ pub struct ScheduleRecord { /// the number of identical such events. pub periodic: Vec<(ScheduledEvent, u64)>, /// Event paths whose signal was high when edge detection last sampled it. + /// An x counts as high. pub high_events: Vec, + /// Event paths whose signal was x or z when edge detection last sampled + /// it. + pub unknown_events: Vec, /// Scheduling state of the design's processes. pub processes: ProcessRecord, } @@ -210,8 +219,11 @@ impl StateFile { if self.four_state { flags |= FLAG_FOUR_STATE; } - if self.schedule.is_some() { + if let Some(schedule) = &self.schedule { flags |= FLAG_SCHEDULE; + if !schedule.unknown_events.is_empty() { + flags |= FLAG_UNKNOWN_EVENTS; + } } put_u16(w, flags)?; put_len(w, self.objects.len())?; @@ -254,6 +266,12 @@ impl StateFile { for event in &schedule.high_events { put_str(w, event)?; } + if !schedule.unknown_events.is_empty() { + put_len(w, schedule.unknown_events.len())?; + for event in &schedule.unknown_events { + put_str(w, event)?; + } + } if let Some(processes) = processes { put_processes(w, processes)?; } @@ -322,6 +340,13 @@ impl StateFile { let high_events = (0..get_u32(r)?) .map(|_| get_str(r)) .collect::>()?; + let unknown_events = if flags & FLAG_UNKNOWN_EVENTS != 0 { + (0..get_u32(r)?) + .map(|_| get_str(r)) + .collect::>()? + } else { + Vec::new() + }; let processes = if version >= 2 { get_processes(r)? } else { @@ -333,6 +358,7 @@ impl StateFile { events, periodic, high_events, + unknown_events, processes, }) } else { @@ -682,6 +708,7 @@ mod tests { events: vec![event.clone()], periodic: vec![(event, 1)], high_events: vec!["clk".into()], + unknown_events: vec!["rst".into()], processes: ProcessRecord { wakeups: vec![("$process[0].status".into(), 20)], waiters: vec![WaiterRecord { diff --git a/crates/celox-runtime/src/vcd.rs b/crates/celox-runtime/src/vcd.rs index 3046e51329e..e79e493bc1b 100644 --- a/crates/celox-runtime/src/vcd.rs +++ b/crates/celox-runtime/src/vcd.rs @@ -117,6 +117,7 @@ pub struct VcdWriter { descs: Vec, external_descs: Vec, timestamp: u64, + time_precision: celox_design::TimePrecision, header_written: bool, initial_values_written: bool, external_count: usize, @@ -137,14 +138,27 @@ struct VcdOutput { impl VcdWriter { pub fn new>(path: P, descs: &[VcdSignalDesc]) -> std::io::Result { - Ok(Self::from_writer(File::create(path)?, descs)) + Self::new_with_time_precision(path, descs, celox_design::TimePrecision::default()) + } + + /// Create a waveform whose timestamps use the design's global tick precision. + pub fn new_with_time_precision>( + path: P, + descs: &[VcdSignalDesc], + time_precision: celox_design::TimePrecision, + ) -> std::io::Result { + Ok(Self::from_writer_with_time_precision( + File::create(path)?, + descs, + time_precision, + )) } /// Finish the current file and continue the waveform, with the same /// signals, in a new file at `path`. The first dump there records every /// value, and its timestamps start over. pub fn restart>(&mut self, path: P) -> std::io::Result<()> { - let mut next = Self::new(path, &self.descs)?; + let mut next = Self::new_with_time_precision(path, &self.descs, self.time_precision)?; next.add_external_signals(&self.external_descs)?; self.flush()?; *self = next; @@ -154,6 +168,15 @@ impl VcdWriter { impl VcdWriter { pub fn from_writer(writer: W, descs: &[VcdSignalDesc]) -> Self { + Self::from_writer_with_time_precision(writer, descs, celox_design::TimePrecision::default()) + } + + /// Create a writer with an explicit physical duration for each timestamp tick. + pub fn from_writer_with_time_precision( + writer: W, + descs: &[VcdSignalDesc], + time_precision: celox_design::TimePrecision, + ) -> Self { let mut plan = TracePlan::default(); let mut groups: fxhash::FxHashMap> = Default::default(); let headers = descs @@ -187,6 +210,7 @@ impl VcdWriter { descs: descs.to_vec(), external_descs: Vec::new(), timestamp: 0, + time_precision, header_written: false, initial_values_written: false, external_count: 0, @@ -317,7 +341,8 @@ impl VcdWriter { writeln!(self.output.encoded, "$version")?; writeln!(self.output.encoded, " celox")?; writeln!(self.output.encoded, "$end")?; - writeln!(self.output.encoded, "$timescale 1ns $end")?; + let (magnitude, unit) = self.time_precision.vcd_timescale(); + writeln!(self.output.encoded, "$timescale {magnitude}{unit} $end")?; let mut scope_order = Vec::::new(); let mut scope_groups = Vec::>::new(); @@ -711,6 +736,33 @@ const BINARY: [[u8; 8]; 256] = { mod tests { use super::*; + #[test] + fn headers_encode_supported_time_precisions() { + for (exponent, expected) in [ + (2, "100s"), + (0, "1s"), + (-1, "100ms"), + (-5, "10us"), + (-9, "1ns"), + (-12, "1ps"), + (-14, "10fs"), + (-15, "1fs"), + ] { + let precision = celox_design::TimePrecision::try_from(exponent).unwrap(); + let mut writer = VcdWriter::from_writer_with_time_precision(Vec::new(), &[], precision); + writer.dump_with_external(123, &[], &[]).unwrap(); + writer.flush().unwrap(); + let output = std::str::from_utf8(writer.get_ref()).unwrap(); + assert!( + output.contains(&format!("$timescale {expected} $end")), + "{output}" + ); + assert!(output.contains("#123\n")); + } + assert!(celox_design::TimePrecision::try_from(-16).is_err()); + assert!(celox_design::TimePrecision::try_from(3).is_err()); + } + #[test] fn appended_external_signals_survive_restart() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/celox-sv-analyzer/src/analyze.rs b/crates/celox-sv-analyzer/src/analyze.rs index f09c9a3f7f8..4cebe51c5e7 100644 --- a/crates/celox-sv-analyzer/src/analyze.rs +++ b/crates/celox-sv-analyzer/src/analyze.rs @@ -135,7 +135,7 @@ pub fn analyze_source(source: ast::Source) -> Result { parameter.name().to_string(), parameter.value().cloned().map(Into::into), parameter.bound_type().cloned(), - parameter.pattern_text().map(str::to_string), + parameter.bound_pattern().cloned(), ) }) .collect(), diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 404a9527c75..1cc7da990b6 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -25,9 +25,11 @@ use crate::{AnalyzerError, system_functions, typecheck}; mod array_compatibility; mod array_parameters; mod assignment_analysis; +mod bound_patterns; mod case; mod casts; mod comb_process; +pub use bound_patterns::BoundPattern; mod comb_rewrite; pub(crate) mod const_functions; mod constant_folding; @@ -205,6 +207,7 @@ pub struct Source { pub(crate) struct ModuleParameterBindings<'a> { pub values: &'a HashMap, pub types: &'a [(String, Type)], + pub patterns: &'a [(String, BoundPattern)], } impl Source { @@ -293,6 +296,7 @@ impl Source { ModuleParameterBindings { values: parameter_overrides, types: &[], + patterns: &[], }, extra_interfaces, &packages, @@ -329,6 +333,11 @@ impl Source { )?; imported.type_parameter_bindings = type_parameters::bind(node.clone(), syntax_tree, bindings.types)?; + imported.pattern_parameter_bindings = type_parameters::bind_patterns( + node.clone(), + syntax_tree, + bindings.patterns, + )?; modules.push(Module::from_module_node_with_parameter_overrides( node, syntax_tree, @@ -1070,6 +1079,7 @@ impl Module { // A package keeps its symbols for the scopes that use it. let symbols = is_package.then(|| scope::ScopeSymbols { type_parameter_bindings: HashMap::default(), + pattern_parameter_bindings: HashMap::default(), const_env: const_env.clone(), parameter_values: parameter_values.clone(), parameters: parameters.clone(), @@ -1579,7 +1589,7 @@ pub struct ParameterOverride { value: Option, /// The data type resolved in the instantiating scope. bound_type: Option, - pattern_text: Option, + bound_pattern: Option, } impl ParameterOverride { @@ -1588,7 +1598,7 @@ impl ParameterOverride { name, value, bound_type: None, - pattern_text: None, + bound_pattern: None, } } @@ -1597,13 +1607,13 @@ impl ParameterOverride { name, value: None, bound_type: Some(bound_type), - pattern_text: None, + bound_pattern: None, } } /// A constant assignment pattern, evaluated in the caller scope. - pub fn pattern_text(&self) -> Option<&str> { - self.pattern_text.as_deref() + pub fn bound_pattern(&self) -> Option<&BoundPattern> { + self.bound_pattern.as_ref() } pub fn name(&self) -> &str { @@ -2214,7 +2224,7 @@ struct FunctionLocalType { is_2state: bool, } -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Expr { Ident(String), Literal(String), @@ -2263,7 +2273,7 @@ pub enum Expr { } /// One item of an `inside` set. -#[derive(Debug, Clone, PartialEq, Eq)] +#[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum InsideItem { /// A value matched with wildcard equality (`==?`). Value(Expr), diff --git a/crates/celox-sv-analyzer/src/ast/array_parameters.rs b/crates/celox-sv-analyzer/src/ast/array_parameters.rs index ba8232a9b9f..75afe95e93d 100644 --- a/crates/celox-sv-analyzer/src/ast/array_parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/array_parameters.rs @@ -10,13 +10,20 @@ use super::*; /// A parameter of unpacked array type, as the variable that holds it. pub(super) struct ArrayParameter<'a> { pub signal: Signal, - pattern: &'a sv_parser::AssignmentPatternExpression, + pattern: Option<&'a sv_parser::AssignmentPatternExpression>, + bound: Option, } /// Whether a parameter assignment declares an unpacked array, or a value /// given by an assignment pattern (a packed structure or array). pub(super) fn is_array_parameter(param: &sv_parser::ParamAssignment) -> bool { - !param.nodes.1.is_empty() || value_pattern(param).is_some() + !param.nodes.1.is_empty() + || value_pattern(param).is_some() + || identifier_locate(RefNode::ParameterIdentifier(¶m.nodes.0)).is_some_and(|loc| { + scope::imported() + .pattern_parameter_bindings + .contains_key(&loc.offset) + }) } fn declared_type( @@ -152,7 +159,14 @@ pub(super) fn array_parameters_from_declaration<'a>( let RefNode::ParamAssignment(param) = child else { continue; }; - if !is_array_parameter(param) { + let bound = + identifier_locate(RefNode::ParameterIdentifier(¶m.nodes.0)).and_then(|loc| { + scope::imported() + .pattern_parameter_bindings + .get(&loc.offset) + .cloned() + }); + if !is_array_parameter(param) && bound.is_none() { continue; } let name = parameter_name(RefNode::ParameterIdentifier(¶m.nodes.0), tree)?; @@ -166,12 +180,16 @@ pub(super) fn array_parameters_from_declaration<'a>( const_env, type_aliases, )?; - let pattern = value_pattern(param).ok_or_else(|| { - AnalyzerError::Unsupported(format!("value of array parameter `{name}`")) - })?; + let pattern = value_pattern(param); + if pattern.is_none() && bound.is_none() { + return Err(AnalyzerError::Unsupported(format!( + "value of array parameter `{name}`" + ))); + } let parameter = ArrayParameter { signal: Signal::new(name, type_with_unpacked_ranges(element, ranges)), pattern, + bound, }; // Publish before the next declarator can query this array's shape. publish(¶meter); @@ -189,11 +207,18 @@ impl ArrayParameter<'_> { ) -> Result { let name = self.signal.name().to_string(); let shape = procedural::dimensions_from_type(self.signal.r#type()); - let value = if self.pattern.nodes.0.is_some() { - patterns::typed_pattern(self.pattern, tree, dims) + let value = if let Some(bound) = &self.bound { + bound.lower(&shape, dims)? } else { - patterns::expr_from_pattern(&self.pattern.nodes.1, &shape, tree, dims) - }?; + let pattern = self + .pattern + .ok_or_else(|| unsupported("array parameter value"))?; + if pattern.nodes.0.is_some() { + patterns::typed_pattern(pattern, tree, dims)? + } else { + patterns::expr_from_pattern(&pattern.nodes.1, &shape, tree, dims)? + } + }; Ok(InitialProcess { creation_order: 0, condition: None, diff --git a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs new file mode 100644 index 00000000000..d79739839f0 --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs @@ -0,0 +1,412 @@ +//! Assignment-pattern bindings retain structure, not generated source. Names, +//! keys and repetition counts bind in the caller; element sizing happens in +//! the receiving declaration's assignment context (IEEE 1800-2023 10.9). +use super::*; + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub struct BoundPattern { + items: Items, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Items { + Value(Expr), + List(Vec), + Repeat(usize, Vec), + Keyed(Vec<(Key, Value)>), +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +enum Key { + Index(i128), + Member(String), + Default, +} + +#[derive(Debug, Clone, PartialEq, Eq, Hash)] +pub(super) enum Value { + Expression(Expr), + Pattern(BoundPattern), +} + +pub(super) fn from_param( + expression: &sv_parser::ParamExpression, + tree: &SyntaxTree, + dims: &PackedDimensions, +) -> Converted { + let sv_parser::ParamExpression::MintypmaxExpression(expression) = expression else { + return Err(unsupported("parameter assignment pattern")); + }; + let sv_parser::MintypmaxExpression::Expression(expression) = expression.as_ref() else { + return Err(unsupported("parameter pattern mintypmax expression")); + }; + match value(expression, tree, dims)? { + Value::Pattern(pattern) => Ok(pattern), + Value::Expression(value) => Ok(BoundPattern { + items: Items::Value(value), + }), + } +} + +fn frozen(expr: Expr, dims: &PackedDimensions) -> Converted { + let freeze = |expr| frozen(expr, dims).map(Box::new); + Ok(match expr { + Expr::Literal(_) => expr, + Expr::Unary { op, expr } => Expr::Unary { + op, + expr: freeze(*expr)?, + }, + Expr::Binary { left, op, right } => Expr::Binary { + left: freeze(*left)?, + op, + right: freeze(*right)?, + }, + Expr::Mux { + condition, + then_expr, + else_expr, + } => Expr::Mux { + condition: freeze(*condition)?, + then_expr: freeze(*then_expr)?, + else_expr: freeze(*else_expr)?, + }, + Expr::Call { + callee: Callee::Subroutine(name), + args, + arg_order, + } if arg_order.is_empty() => { + let args = args + .into_iter() + .map(|arg| { + let expr = frozen( + arg.ok_or_else(|| { + unsupported("default constant function argument in pattern") + })?, + dims, + )?; + expr_to_const(expr) + .map(Into::into) + .ok_or_else(|| unsupported("constant pattern function argument")) + }) + .collect::>>()?; + let literal = const_functions::eval_call_literal(&name, &args, &dims.const_env) + .ok_or_else(|| unsupported("constant parameter pattern function"))?; + Expr::Literal(typecheck::format_integral_literal_binary(&literal)) + } + value => { + let values = dims + .parameter_values + .iter() + .map(|(n, v)| (n.clone(), v.clone())) + .collect(); + let value = + substitute_expr_constants_with_parameter_literals(value, &dims.const_env, &values); + let folded = fold_const_integral_expr_preserving_mask(value, &dims.const_env); + if !matches!(folded, Expr::Literal(_)) { + return Err(unsupported("nonconstant parameter pattern element")); + } + folded + } + }) +} + +fn value( + expr: &sv_parser::Expression, + tree: &SyntaxTree, + dims: &PackedDimensions, +) -> Converted { + if let Some(pattern) = patterns::pattern_expression(expr) { + value_pattern(pattern, tree, dims) + } else { + Ok(Value::Expression(frozen( + expr_from_expression_with_types(expr, tree, dims)?, + dims, + )?)) + } +} + +fn value_pattern( + pattern: &sv_parser::AssignmentPatternExpression, + tree: &SyntaxTree, + dims: &PackedDimensions, +) -> Converted { + if pattern.nodes.0.is_some() { + return patterns::constant_typed_pattern_value(pattern, tree, dims); + } + let integer = |expr: &sv_parser::ConstantExpression| { + const_expr_from_ref_node_with_env( + RefNode::ConstantExpression(expr), + tree, + &dims.const_env, + &dims.type_aliases, + )? + .and_then(|expr| eval_ast_const_expr(&expr, &dims.const_env)) + .ok_or_else(|| unsupported("nonconstant assignment pattern key or count")) + }; + let values = |items: Vec<&sv_parser::Expression>| { + items + .into_iter() + .map(|expr| value(expr, tree, dims)) + .collect::>>() + }; + let default_key = |key: &sv_parser::AssignmentPatternKey| match key { + sv_parser::AssignmentPatternKey::Default(_) => Ok(Key::Default), + _ => Err(unsupported("assignment pattern type key")), + }; + let items = match &pattern.nodes.1 { + sv_parser::AssignmentPattern::List(list) => { + Items::List(values(list.nodes.0.nodes.1.contents())?) + } + sv_parser::AssignmentPattern::Repeat(repeat) => { + let (count, items) = &repeat.nodes.0.nodes.1; + let count = usize::try_from(integer(count)?) + .map_err(|_| unsupported("assignment pattern repetition count"))?; + let values = values(items.nodes.1.contents())?; + Items::Repeat(count, values) + } + sv_parser::AssignmentPattern::Array(array) => Items::Keyed( + array + .nodes + .0 + .nodes + .1 + .contents() + .into_iter() + .map(|(key, _, expr)| { + let key = match key { + sv_parser::ArrayPatternKey::ConstantExpression(index) => { + Key::Index(integer(index)?) + } + sv_parser::ArrayPatternKey::AssignmentPatternKey(key) => default_key(key)?, + }; + Ok((key, value(expr, tree, dims)?)) + }) + .collect::>()?, + ), + sv_parser::AssignmentPattern::Structure(structure) => Items::Keyed( + structure + .nodes + .0 + .nodes + .1 + .contents() + .into_iter() + .map(|(key, _, expr)| { + let key = match key { + sv_parser::StructurePatternKey::MemberIdentifier(member) => Key::Member( + identifier_text(RefNode::MemberIdentifier(member), tree) + .ok_or_else(|| unsupported("assignment pattern member name"))?, + ), + sv_parser::StructurePatternKey::AssignmentPatternKey(key) => { + default_key(key)? + } + }; + Ok((key, value(expr, tree, dims)?)) + }) + .collect::>()?, + ), + }; + Ok(Value::Pattern(BoundPattern { items })) +} + +impl Value { + pub(super) fn list(values: Vec) -> Self { + Self::Pattern(BoundPattern { + items: Items::List(values), + }) + } + fn lower( + &self, + shape: &VariableDimensions, + dims: &PackedDimensions, + default: bool, + ) -> Converted { + if let Self::Pattern(pattern) = self { + return pattern.lower(shape, dims); + } + let Self::Expression(value) = self else { + unreachable!() + }; + if default && let Some((dimension, rest)) = shape.unpacked.split_first() { + let count = eval_ast_const_expr(&dimension.width, &dims.const_env) + .and_then(|n| usize::try_from(n).ok()) + .ok_or_else(|| unsupported("pattern target array size"))?; + let shape = VariableDimensions { + unpacked: rest.to_vec(), + ..shape.clone() + }; + return Ok(Expr::Concat(vec![self.lower(&shape, dims, true)?; count])); + } + if !shape.unpacked.is_empty() { + return Err(unsupported( + "scalar assignment pattern item for unpacked array", + )); + } + let width = patterns::shape_width(shape, dims) + .ok_or_else(|| unsupported("assignment pattern element width"))?; + let signed = + expr_signedness(value, &dims.expression_signedness, &dims.functions).unwrap_or(false); + Ok(Expr::Resize { + expr: Box::new(value.clone()), + width, + signed, + }) + } +} + +impl BoundPattern { + pub(super) fn lower( + &self, + shape: &VariableDimensions, + dims: &PackedDimensions, + ) -> Converted { + if let Items::Value(value) = &self.items { + return Ok(value.clone()); + } + let eval = |expr| { + eval_ast_const_expr(expr, &dims.const_env) + .ok_or_else(|| unsupported("assignment pattern target bounds")) + }; + let unpacked = !shape.unpacked.is_empty(); + let mut shapes = Vec::new(); + let keys; + if let Some((dim, rest)) = shape.unpacked.split_first() { + let left = eval(&dim.left)?; + let right = eval(&dim.right)?; + let count = usize::try_from(left.abs_diff(right) + 1) + .map_err(|_| unsupported("assignment pattern target size"))?; + shapes = vec![ + VariableDimensions { + unpacked: rest.to_vec(), + ..shape.clone() + }; + count + ]; + keys = (0..count) + .map(|i| { + Key::Index(if left <= right { + left + i as i128 + } else { + left - i as i128 + }) + }) + .collect::>(); + } else if !shape.members.is_empty() { + if shape.members.len() > 1 && shape.members.iter().all(|m| m.offset() == 0) { + return Err(unsupported("assignment pattern for a packed union")); + } + keys = shape + .members + .iter() + .map(|m| Key::Member(m.name().into())) + .collect(); + shapes.extend( + shape + .members + .iter() + .map(|m| procedural::dimensions_from_type(m.r#type())), + ); + } else if let Some((dim, rest)) = shape.packed.split_first() + && !rest.is_empty() + { + let left = eval(&dim.left)?; + let right = eval(&dim.right)?; + let count = usize::try_from(left.abs_diff(right) + 1) + .map_err(|_| unsupported("assignment pattern target size"))?; + shapes = vec![ + VariableDimensions { + packed: rest.to_vec(), + signed: shape.signed_element_depth == Some(1), + signed_element_depth: shape + .signed_element_depth + .and_then(|n| n.checked_sub(1)) + .filter(|n| *n > 0), + ..shape.clone() + }; + count + ]; + keys = (0..count) + .map(|i| { + Key::Index(if left <= right { + left + i as i128 + } else { + left - i as i128 + }) + }) + .collect(); + } else { + let width = patterns::shape_width(shape, dims) + .ok_or_else(|| unsupported("pattern target width"))?; + shapes = vec![ + VariableDimensions { + packed: Vec::new(), + signed: false, + signed_element_depth: None, + ..shape.clone() + }; + width + ]; + keys = (0..width).rev().map(|i| Key::Index(i as i128)).collect(); + } + let selected = match &self.items { + Items::Value(value) => return Ok(value.clone()), + Items::Repeat(count, values) => { + if count.checked_mul(values.len()) != Some(shapes.len()) { + return Err(unsupported( + "assignment pattern repetition size does not match target", + )); + } + (0..*count) + .flat_map(|_| values.iter().map(|v| (v, false))) + .collect() + } + Items::List(values) => { + if values.len() != shapes.len() { + return Err(unsupported(format!( + "assignment pattern with {} items for {} elements", + values.len(), + shapes.len() + ))); + } + values.iter().map(|v| (v, false)).collect::>() + } + Items::Keyed(items) => { + for (key, _) in items { + if *key != Key::Default && !keys.contains(key) { + return Err(unsupported("assignment pattern key outside target")); + } + } + keys.iter() + .map(|key| { + items + .iter() + .rev() + .find(|(k, _)| k == key) + .map(|(_, v)| (v, false)) + .or_else(|| { + items + .iter() + .rev() + .find(|(k, _)| *k == Key::Default) + .map(|(_, v)| (v, true)) + }) + .ok_or_else(|| unsupported("assignment pattern missing element")) + }) + .collect::>>()? + } + }; + let mut parts = selected + .into_iter() + .zip(shapes) + .map(|((v, default), shape)| v.lower(&shape, dims, default)) + .collect::>>()?; + if unpacked { + parts.reverse(); + } + Ok(if parts.len() == 1 { + parts.remove(0) + } else { + Expr::Concat(parts) + }) + } +} diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index d418d39f8ba..c380f993906 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -973,6 +973,8 @@ impl Frame<'_> { // Messages have no effect on the value. Unknown and unsupported // system tasks are rejected before elaboration. Stmt::SystemTask { .. } => {} + // A function has no timing controls (IEEE 1800-2023 13.4). + Stmt::Delay(_) | Stmt::WaitEvent(_) | Stmt::Wait(_) => return None, Stmt::AssignConcat { .. } | Stmt::Call { .. } => return None, } Some(Flow::Next) diff --git a/crates/celox-sv-analyzer/src/ast/instances.rs b/crates/celox-sv-analyzer/src/ast/instances.rs index aa2d08409df..1548d11804f 100644 --- a/crates/celox-sv-analyzer/src/ast/instances.rs +++ b/crates/celox-sv-analyzer/src/ast/instances.rs @@ -491,9 +491,9 @@ fn parameter_override( .into_iter() .any(|node| matches!(node, RefNode::AssignmentPatternExpression(_))) { - let text = constant_pattern_text(expr, syntax_tree, packed_dimensions)?; + let pattern = bound_patterns::from_param(expr, syntax_tree, packed_dimensions)?; let mut bound = ParameterOverride::new(name, None); - bound.pattern_text = Some(text); + bound.bound_pattern = Some(pattern); return Ok(bound); } // sv-parser accepts a single packed dimension on a named type as an @@ -552,186 +552,3 @@ fn parameter_override( } Ok(ParameterOverride::new(name, Some(value))) } - -fn constant_pattern_literal( - mut expression: ConstExpr, - dimensions: &PackedDimensions, - types: &HashMap, -) -> Converted { - fn freeze(expr: &mut ConstExpr, constants: &HashMap) { - match expr { - ConstExpr::Literal(_) | ConstExpr::Ident(_) => {} - ConstExpr::Unary { expr, .. } | ConstExpr::Resize { expr, .. } => { - freeze(expr, constants) - } - ConstExpr::Select { expr, bit } => { - freeze(expr, constants); - freeze(bit, constants); - } - ConstExpr::SelectRange { expr, msb, lsb, .. } => { - freeze(expr, constants); - freeze(msb, constants); - freeze(lsb, constants); - } - ConstExpr::Binary { left, right, .. } => { - freeze(left, constants); - freeze(right, constants); - } - ConstExpr::Mux { - condition, - then_expr, - else_expr, - } => { - freeze(condition, constants); - freeze(then_expr, constants); - freeze(else_expr, constants); - } - ConstExpr::Function { callee, args, .. } => { - for arg in args.iter_mut() { - freeze(arg, constants); - } - let lowered = args.iter().cloned().map(Into::into).collect::>(); - if let Callee::Subroutine(name) = callee - && let Some(literal) = - const_functions::eval_call_literal(name, &lowered, constants) - { - *expr = ConstExpr::Literal(typecheck::format_integral_literal_binary(&literal)); - } - } - } - } - // System/literal expressions retain their four-state masks. User functions - // run through the installed interpreter, with the caller's constant scope - // and their declared result widths, before the leaf is serialized. - freeze(&mut expression, &dimensions.const_env); - typecheck::eval_const_integral_literal_with_types( - &expression.into(), - &dimensions.const_env, - types, - ) - .ok_or_else(|| unsupported("nonconstant parameter pattern element")) -} - -/// Freeze pattern leaves in the instantiating module's constant environment. -/// Reparse in the callee to apply the target array/structure shape. -fn constant_pattern_text( - expression: &sv_parser::ParamExpression, - tree: &SyntaxTree, - dimensions: &PackedDimensions, -) -> Result { - let node = RefNode::ParamExpression(expression); - let tokens: Vec<_> = node - .clone() - .into_iter() - .filter_map(|node| { - if let RefNode::Locate(locate) = node { - Some(locate) - } else { - None - } - }) - .collect(); - let start = tokens - .iter() - .map(|locate| locate.offset) - .min() - .ok_or_else(|| unsupported("parameter pattern"))?; - let end = tokens - .iter() - .map(|locate| locate.offset + locate.len) - .max() - .unwrap(); - let original = tree - .get_str(&sv_parser::Locate { - offset: start, - line: 0, - len: end - start, - }) - .ok_or_else(|| unsupported("parameter pattern text"))?; - let types = parameter_types_from_const_env(&dimensions.const_env) - .into_iter() - .map(|(name, ty)| (name, (ty.width, ty.signed))) - .collect(); - let mut edits = Vec::new(); - for child in node { - let value = match child { - RefNode::AssignmentPatternExpression(pattern) if pattern.nodes.0.is_some() => Some( - patterns::constant_typed_pattern_text(pattern, tree, dimensions)?, - ), - RefNode::Primary(primary) - if !matches!( - primary, - sv_parser::Primary::PrimaryLiteral(_) - | sv_parser::Primary::MintypmaxExpression(_) - | sv_parser::Primary::AssignmentPatternExpression(_) - ) => - { - let expr = sv_parser::Expression::Primary(Box::new(primary.clone())); - let value = indexed_select_base(RefNode::Expression(&expr), tree, dimensions)?; - Some(format!( - "({})", - typecheck::format_integral_literal_binary(&constant_pattern_literal( - value, dimensions, &types - )?,) - )) - } - RefNode::ConstantPrimary(primary) - if !matches!( - primary, - sv_parser::ConstantPrimary::PrimaryLiteral(_) - | sv_parser::ConstantPrimary::MintypmaxExpression(_) - | sv_parser::ConstantPrimary::ConstantAssignmentPatternExpression(_) - ) => - { - let expr = - sv_parser::ConstantExpression::ConstantPrimary(Box::new(primary.clone())); - let value = - indexed_select_base(RefNode::ConstantExpression(&expr), tree, dimensions)?; - Some(format!( - "({})", - typecheck::format_integral_literal_binary(&constant_pattern_literal( - value, dimensions, &types - )?,) - )) - } - // Retain literals, operators and parentheses for the callee's - // assignment context, including unbased fills and wider arithmetic. - // Descendant primary references still bind in the caller, also - // inside constant-expression repetition counts and index keys. - _ => None, - }; - let Some(replacement) = value else { - continue; - }; - let tokens: Vec<_> = child - .into_iter() - .filter_map(|node| { - if let RefNode::Locate(locate) = node { - Some(locate) - } else { - None - } - }) - .collect(); - let low = tokens.iter().map(|locate| locate.offset).min().unwrap(); - let high = tokens - .iter() - .map(|locate| locate.offset + locate.len) - .max() - .unwrap(); - edits.push((low, high, replacement)); - } - edits.sort_by_key(|(low, high, _)| (*low, std::cmp::Reverse(*high))); - let mut result = String::new(); - let mut cursor = start; - for (low, high, replacement) in edits { - if low < cursor { - continue; - } - result.push_str(&original[cursor - start..low - start]); - result.push_str(&replacement); - cursor = high; - } - result.push_str(&original[cursor - start..]); - Ok(result) -} diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index 84b66629b3a..d468b131f69 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -527,6 +527,16 @@ impl Flow<'_> { } Ok(Exits::next(written)) } + Stmt::Delay(expr) | Stmt::Wait(expr) => { + self.read(expr, written)?; + Ok(Exits::next(written)) + } + Stmt::WaitEvent(items) => { + for item in items { + self.read(&item.expr, written)?; + } + Ok(Exits::next(written)) + } } } @@ -660,6 +670,8 @@ fn stmt_exprs(stmt: &Stmt) -> Vec<&Expr> { }) .collect(), Stmt::Local { init, .. } => init.iter().collect(), + Stmt::Delay(expr) | Stmt::Wait(expr) => vec![expr], + Stmt::WaitEvent(items) => items.iter().map(|item| &item.expr).collect(), Stmt::Break | Stmt::Continue => Vec::new(), } } diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index b8fdd765396..028e6256092 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -102,6 +102,16 @@ impl Package { } impl Packages { + /// Global simulation precision, as a power of ten seconds (IEEE 1800-2023 3.14.3). + pub fn global_time_precision(&self) -> i32 { + self.timescales.global_precision() + } + + /// Resolved local time unit and precision of a module or package. + pub fn scope_time_scale(&self, name: &str) -> Option<(i32, i32)> { + self.timescales.scope_scale(name) + } + pub fn is_empty(&self) -> bool { self.packages.is_empty() } diff --git a/crates/celox-sv-analyzer/src/ast/patterns.rs b/crates/celox-sv-analyzer/src/ast/patterns.rs index f9f49f37ab0..f95528ec534 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns.rs @@ -91,11 +91,11 @@ fn typed_pattern_type( /// Serialize a typed constant pattern as positional values already converted /// to its caller-side type (IEEE 1800-2023 10.9). Packed values become /// literals; only unpacked dimensions need positional patterns. -pub(super) fn constant_typed_pattern_text( +pub(super) fn constant_typed_pattern_value( pattern: &sv_parser::AssignmentPatternExpression, tree: &SyntaxTree, dims: &PackedDimensions, -) -> Converted { +) -> Converted { let r#type = typed_pattern_type(pattern, tree, dims)?; let shape = procedural::dimensions_from_type(&r#type); let value = expr_from_pattern(&pattern.nodes.1, &shape, tree, dims)?; @@ -112,15 +112,15 @@ pub(super) fn constant_typed_pattern_text( }; let value = typecheck::parse_integral_literal(&value) .ok_or_else(|| unsupported("typed parameter pattern value"))?; - pattern_value_text(&value, &shape, 0, dims) + pattern_value(&value, &shape, 0, dims) } -fn pattern_value_text( +fn pattern_value( value: &typecheck::IntegralLiteral, shape: &VariableDimensions, offset: usize, dims: &PackedDimensions, -) -> Converted { +) -> Converted { let mut parts = Vec::new(); if let Some((dimension, rest)) = shape.unpacked.split_first() { let (_, _, count) = dimension_bounds(&dimension.left, &dimension.right, dims)?; @@ -131,7 +131,7 @@ fn pattern_value_text( let width = shape_width(&element, dims) .ok_or_else(|| unsupported("typed pattern element width"))?; for position in 0..count { - parts.push(pattern_value_text( + parts.push(pattern_value( value, &element, offset + position * width, @@ -152,9 +152,11 @@ fn pattern_value_text( literal.value ^= &literal.value & &literal.mask; literal.mask = num_bigint::BigUint::default(); } - return Ok(typecheck::format_integral_literal_binary(&literal)); + return Ok(bound_patterns::Value::Expression(Expr::Literal( + typecheck::format_integral_literal_binary(&literal), + ))); } - Ok(format!("'{{{}}}", parts.join(", "))) + Ok(bound_patterns::Value::list(parts)) } /// The value of one element of a pattern, as a `shape`. diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index c51fd75dc29..12a4ccdbfa5 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -8,7 +8,8 @@ use super::*; use crate::procedural::{ - CaseItemBase, CaseKind, CaseLabel, LoopKind, ParamDirection, SystemTaskArg, + CaseItemBase, CaseKind, CaseLabel, EventEdge, EventItemBase, LoopKind, ParamDirection, + SystemTaskArg, }; /// One lexical scope: the locals it declares and the bindings they shadow. @@ -569,11 +570,23 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { sv_parser::StatementItem::ProceduralAssertionStatement(assertion) => { self.assertion(assertion) } - sv_parser::StatementItem::ProceduralTimingControlStatement(_) - | sv_parser::StatementItem::WaitStatement(_) - | sv_parser::StatementItem::EventTrigger(_) => { - Err(unsupported("procedural timing control")) + sv_parser::StatementItem::ProceduralTimingControlStatement(timing) => { + let mut stmts = vec![self.timing_control(&timing.nodes.0)?]; + stmts.extend(self.statement_or_null(&timing.nodes.1)?); + Ok(stmts) } + sv_parser::StatementItem::WaitStatement(wait) => match &**wait { + sv_parser::WaitStatement::Wait(wait) => { + self.allow_timing("wait statement")?; + let condition = self.expr(&wait.nodes.1.nodes.1)?; + let mut stmts = vec![Stmt::Wait(condition)]; + stmts.extend(self.statement_or_null(&wait.nodes.2)?); + Ok(stmts) + } + sv_parser::WaitStatement::Fork(_) => Err(unsupported("wait fork statement")), + sv_parser::WaitStatement::Order(_) => Err(unsupported("wait order statement")), + }, + sv_parser::StatementItem::EventTrigger(_) => Err(unsupported("event trigger")), sv_parser::StatementItem::ProceduralContinuousAssignment(_) => { Err(unsupported("procedural continuous assignment")) } @@ -583,6 +596,137 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { } } + /// Timing controls suspend the process that executes them. An `initial` + /// body runs as a process; `always` bodies with timing controls and + /// subroutines with them are not lowered yet. + fn allow_timing(&self, construct: &str) -> Result<(), AnalyzerError> { + match self.body { + system_functions::Body::Initial => Ok(()), + system_functions::Body::Always => Err(unsupported(format!( + "always and always_latch processes with a {construct}" + ))), + system_functions::Body::Subroutine => { + Err(unsupported(format!("{construct} in a subroutine"))) + } + } + } + + /// The suspension a procedural timing control stands for: a delay or an + /// event control. + fn timing_control( + &self, + control: &sv_parser::ProceduralTimingControl, + ) -> Result { + match control { + sv_parser::ProceduralTimingControl::DelayControl(delay) => { + self.allow_timing("delay control")?; + self.delay_control(delay).map(Stmt::Delay) + } + sv_parser::ProceduralTimingControl::EventControl(control) => { + self.allow_timing("event control")?; + self.event_control(control).map(Stmt::WaitEvent) + } + sv_parser::ProceduralTimingControl::CycleDelay(_) => Err(unsupported("cycle delay")), + } + } + + /// The amount of a `#` delay control, in time units. Of a + /// `min:typ:max` delay the typical value is used, as simulators do by + /// default. + fn delay_control(&self, delay: &sv_parser::DelayControl) -> Result { + match delay { + sv_parser::DelayControl::Delay(delay) => match &delay.nodes.1 { + sv_parser::DelayValue::UnsignedNumber(number) => Ok(Expr::Literal( + self.tree + .get_str(&number.nodes.0) + .ok_or_else(|| unsupported("delay value"))? + .replace('_', ""), + )), + sv_parser::DelayValue::PsIdentifier(identifier) => { + if identifier.nodes.0.is_some() { + return Err(unsupported("package-scoped delay value")); + } + let name = identifier_text(RefNode::Identifier(&identifier.nodes.1), self.tree) + .ok_or_else(|| unsupported("delay value"))?; + let mut expr = Expr::Ident(name); + self.rename_expr(&mut expr); + Ok(expr) + } + sv_parser::DelayValue::HierarchicalIdentifier(identifier) => { + let name = + identifier_text(RefNode::HierarchicalIdentifier(identifier), self.tree) + .ok_or_else(|| unsupported("delay value"))?; + let mut expr = Expr::Ident(name); + self.rename_expr(&mut expr); + Ok(expr) + } + sv_parser::DelayValue::RealNumber(_) + | sv_parser::DelayValue::TimeLiteral(_) + | sv_parser::DelayValue::Step1(_) => Err(unsupported("delay value")), + }, + sv_parser::DelayControl::Mintypmax(delay) => match &delay.nodes.1.nodes.1 { + sv_parser::MintypmaxExpression::Expression(expr) => self.expr(expr), + sv_parser::MintypmaxExpression::Ternary(ternary) => self.expr(&ternary.nodes.2), + }, + } + } + + /// The items of an `@` event control. + fn event_control( + &self, + control: &sv_parser::EventControl, + ) -> Result>, AnalyzerError> { + match control { + sv_parser::EventControl::EventExpression(control) => { + let mut items = Vec::new(); + self.event_items(&control.nodes.1.nodes.1, &mut items)?; + Ok(items) + } + sv_parser::EventControl::EventIdentifier(_) => Err(unsupported("named event")), + sv_parser::EventControl::Asterisk(_) | sv_parser::EventControl::ParenAsterisk(_) => { + Err(unsupported("`@*` event control in a process")) + } + sv_parser::EventControl::SequenceIdentifier(_) => { + Err(unsupported("sequence event control")) + } + } + } + + fn event_items( + &self, + expr: &sv_parser::EventExpression, + items: &mut Vec>, + ) -> Result<(), AnalyzerError> { + match expr { + sv_parser::EventExpression::Expression(expr) => { + if expr.nodes.2.is_some() { + return Err(unsupported("iff-qualified event")); + } + let edge = match &expr.nodes.0 { + None => EventEdge::Any, + Some(sv_parser::EdgeIdentifier::Posedge(_)) => EventEdge::Pos, + Some(sv_parser::EdgeIdentifier::Negedge(_)) => EventEdge::Neg, + Some(sv_parser::EdgeIdentifier::Edge(_)) => EventEdge::Both, + }; + let expr = self.expr(&expr.nodes.1)?; + items.push(EventItemBase { edge, expr }); + Ok(()) + } + sv_parser::EventExpression::Or(expr) => { + self.event_items(&expr.nodes.0, items)?; + self.event_items(&expr.nodes.2, items) + } + sv_parser::EventExpression::Comma(expr) => { + self.event_items(&expr.nodes.0, items)?; + self.event_items(&expr.nodes.2, items) + } + sv_parser::EventExpression::Paren(expr) => { + self.event_items(&expr.nodes.0.nodes.1, items) + } + sv_parser::EventExpression::Sequence(_) => Err(unsupported("sequence event")), + } + } + fn seq_block(&mut self, block: &sv_parser::SeqBlock) -> Result, AnalyzerError> { let mut stmts = Vec::new(); for item in &block.nodes.2 { diff --git a/crates/celox-sv-analyzer/src/ast/scope.rs b/crates/celox-sv-analyzer/src/ast/scope.rs index f6b51f36e3e..0987ddfbabd 100644 --- a/crates/celox-sv-analyzer/src/ast/scope.rs +++ b/crates/celox-sv-analyzer/src/ast/scope.rs @@ -24,6 +24,7 @@ pub(super) struct ScopeSymbols { pub type_aliases: HashMap, /// Bound type parameters, keyed by their declaration offset in this tree. pub type_parameter_bindings: HashMap, + pub pattern_parameter_bindings: HashMap, pub enum_constants: EnumMemberConstants, pub functions: HashMap, pub function_return_types: HashMap, @@ -376,6 +377,7 @@ impl ScopeSymbols { .collect(); ScopeSymbols { type_parameter_bindings: self.type_parameter_bindings.clone(), + pattern_parameter_bindings: self.pattern_parameter_bindings.clone(), const_env, parameter_values: self .parameter_values diff --git a/crates/celox-sv-analyzer/src/ast/timescales.rs b/crates/celox-sv-analyzer/src/ast/timescales.rs index 86daae84697..921e99983d2 100644 --- a/crates/celox-sv-analyzer/src/ast/timescales.rs +++ b/crates/celox-sv-analyzer/src/ast/timescales.rs @@ -523,6 +523,17 @@ pub(crate) fn generated_source_declarations( } impl Timescales { + pub(super) fn scope_scale(&self, name: &str) -> Option<(i32, i32)> { + let scope = self + .definitions + .get(name) + .or_else(|| self.packages.get(name))?; + Some((scope.scale.unit, scope.scale.precision)) + } + + pub(super) fn global_precision(&self) -> i32 { + self.precision.unwrap_or(DEFAULT.precision) + } fn including_tree(&self, tree: &SyntaxTree) -> Converted { let local = Self::collect(&[(tree, Path::new(""))])?; let specified = [ @@ -1222,6 +1233,7 @@ mod tests { "Top", &HashMap::default(), &[], + &[], &ModuleInterfaces::default(), &packages, ) @@ -1468,6 +1480,7 @@ mod tests { "Child", &HashMap::default(), &[], + &[], &ModuleInterfaces::default(), &packages, ) @@ -1495,6 +1508,7 @@ mod tests { "Child", &HashMap::default(), &[], + &[], &ModuleInterfaces::default(), &packages ) @@ -1643,6 +1657,7 @@ mod tests { "Child", &HashMap::default(), &[("T".into(), ty)], + &[], &ModuleInterfaces::default(), &packages, ) diff --git a/crates/celox-sv-analyzer/src/ast/type_parameters.rs b/crates/celox-sv-analyzer/src/ast/type_parameters.rs index 9667f335858..536d748e5c4 100644 --- a/crates/celox-sv-analyzer/src/ast/type_parameters.rs +++ b/crates/celox-sv-analyzer/src/ast/type_parameters.rs @@ -1,4 +1,4 @@ -//! Type parameter bindings and the remaining value-pattern source edits. +//! Declaration-scoped parameter bindings. use super::*; @@ -100,13 +100,6 @@ pub(super) fn resolve(mut ty: Type, env: &HashMap) -> Option Some(ty) } -/// A source text edit: replace `start..end` with `replacement`. -struct Edit { - start: usize, - end: usize, - replacement: String, -} - /// The span of `node` in the original source text. Token offsets refer to /// the preprocessed text, which can differ from the source (the preprocessor /// widens the space after `"DPI-C"`), so each token is mapped back and text @@ -136,54 +129,20 @@ pub(super) fn node_span(node: RefNode<'_>, syntax_tree: &SyntaxTree) -> Option<( range } -/// Apply the edits that fall inside `text[range]`, dropping any edit nested in -/// an earlier (outer) one. -fn apply_edits(text: &str, range: (usize, usize), mut edits: Vec) -> String { - edits.retain(|edit| edit.start >= range.0 && edit.end <= range.1); - edits.sort_by_key(|edit| (edit.start, std::cmp::Reverse(edit.end))); - let mut result = String::new(); - let mut cursor = range.0; - for edit in edits { - if edit.start < cursor { - continue; - } - result.push_str(&text[cursor..edit.start]); - result.push_str(&edit.replacement); - cursor = edit.end; - } - result.push_str(&text[cursor..range.1]); - result -} - -/// Override array/structure value parameters before their target shapes are -/// lowered. Only overridable module parameters may be rebound, never locals. -pub(crate) fn apply_pattern_parameter_overrides( - code: &str, +/// Locate value-pattern bindings by declaration, so nested names stay local. +pub(super) fn bind_patterns( + node: RefNode<'_>, tree: &SyntaxTree, - module_name: &str, - overrides: &[(String, String)], -) -> Result, AnalyzerError> { - if overrides.is_empty() { - return Ok(None); - } - for node in tree { - if !matches!( - node, - RefNode::ModuleDeclarationAnsi(_) | RefNode::ModuleDeclarationNonansi(_) - ) { - continue; - } - if module_name_from_node(node.clone(), tree)? != module_name { - continue; - } - let allowed = declarations::module_interface_from_node(node.clone(), tree)?.parameters; - let mut edits = Vec::new(); - let mut found = HashSet::default(); - let mut declarations = module_parameter_port_list(node.clone()) + overrides: &[(String, BoundPattern)], +) -> Converted> { + let allowed = declarations::module_interface_from_node(node.clone(), tree)?.parameters; + let mut declarations = module_parameter_port_list(node.clone()) + .into_iter() + .collect::>(); + declarations.extend( + scope_declarations(node) .into_iter() - .collect::>(); - declarations.extend(scope_declarations(node.clone()).into_iter().filter_map( - |declaration| { + .filter_map(|declaration| { if let sv_parser::PackageOrGenerateItemDeclaration::ParameterDeclaration( declaration, ) = declaration @@ -192,42 +151,39 @@ pub(crate) fn apply_pattern_parameter_overrides( } else { None } - }, - )); - for child in declarations.into_iter().flat_map(|node| node.into_iter()) { - let RefNode::ParamAssignment(param) = child else { - continue; - }; - let name = parameter_name(RefNode::ParameterIdentifier(¶m.nodes.0), tree)?; - let Some((_, bound)) = overrides.iter().find(|(candidate, _)| *candidate == name) - else { - continue; - }; - if !allowed.contains(&name) { - return Err(unsupported(format!( - "pattern override of non-overridable parameter `{name}`" - ))); - } - let Some((_, value)) = ¶m.nodes.2 else { - return Err(unsupported(format!( - "array parameter `{name}` without a default" - ))); - }; - let (start, end) = node_span(RefNode::ConstantParamExpression(value), tree) - .ok_or_else(|| unsupported("array parameter source span"))?; - edits.push(Edit { - start, - end, - replacement: bound.clone(), - }); - found.insert(name); + }), + ); + let mut bindings = HashMap::default(); + for (name, value) in overrides { + if !allowed.contains(name) { + return Err(unsupported(format!( + "pattern override of non-overridable parameter `{name}`" + ))); } - for (name, _) in overrides { - if !found.contains(name) { - return Err(unsupported(format!("unknown array parameter `{name}`"))); - } + let param = declarations + .iter() + .flat_map(|node| node.clone().into_iter()) + .find_map(|child| { + if let RefNode::ParamAssignment(param) = child + && parameter_name(RefNode::ParameterIdentifier(¶m.nodes.0), tree) + .ok() + .as_ref() + == Some(name) + { + Some(param) + } else { + None + } + }) + .ok_or_else(|| unsupported(format!("unknown array parameter `{name}`")))?; + let offset = identifier_locate(RefNode::ParameterIdentifier(¶m.nodes.0)) + .ok_or_else(|| unsupported("parameter location"))? + .offset; + if bindings.insert(offset, value.clone()).is_some() { + return Err(unsupported(format!( + "duplicate parameter override `{name}`" + ))); } - return Ok(Some(apply_edits(code, (0, code.len()), edits))); } - Err(unsupported(format!("module `{module_name}`"))) + Ok(bindings) } diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index 10bdcdf8c7e..ef9e6402a03 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -353,6 +353,20 @@ fn reject_silently_ignored_constructs_with_dimensions( .flat_map(|root| root.into_iter()) .filter(|child| matches!(child, RefNode::Cast(_))) .collect(); + // The `min:typ:max` value of a procedural delay control is lowered as its + // typical value; any other one is not supported. + let delay_mintypmax: Vec<_> = validation_nodes(node.clone(), is_module) + .flat_map(|root| root.into_iter()) + .filter_map(|child| match child { + RefNode::DelayControlMintypmax(delay) => Some(delay), + _ => None, + }) + .flat_map(|delay| RefNode::DelayControlMintypmax(delay).into_iter()) + .filter_map(|child| match child { + RefNode::MintypmaxExpressionTernary(ternary) => Some(ternary), + _ => None, + }) + .collect(); // Procedure locals, parameters and loop indices are installed by // BodyBuilder. Validate their queries while lowering that scoped body. let procedural_queries: Vec<_> = validation_nodes(node.clone(), is_module) @@ -587,6 +601,8 @@ fn reject_silently_ignored_constructs_with_dimensions( RefNode::SpecifyBlock(_) => { return Err(AnalyzerError::Unsupported("specify block".to_string())); } + RefNode::MintypmaxExpressionTernary(ternary) + if delay_mintypmax.iter().any(|delay| std::ptr::eq(*delay, ternary)) => {} RefNode::MintypmaxExpressionTernary(_) | RefNode::ConstantMintypmaxExpressionTernary(_) => { return Err(AnalyzerError::Unsupported( diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 715559ec782..2a6252fef15 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -3,7 +3,7 @@ use crate::{ast, symbol::ModuleId, typecheck}; pub use crate::procedural::{ - CaseKind, CaseLabel, LoopKind, ParamDirection, StmtBase, SystemTaskArg, + CaseKind, CaseLabel, EventEdge, LoopKind, ParamDirection, StmtBase, SystemTaskArg, }; pub use crate::system_functions::{ ArrayQuery, Callee, MemoryFormat, Radix, Severity, SystemFunction, SystemTask, @@ -12,6 +12,7 @@ pub use crate::system_functions::{ /// A procedural statement of the analyzed IR. pub type Stmt = StmtBase; pub type CaseItem = crate::procedural::CaseItemBase; +pub type EventItem = crate::procedural::EventItemBase; pub type LocalVariable = crate::procedural::LocalVariableBase; pub type Subroutine = crate::procedural::SubroutineBase; pub type SubroutineParam = crate::procedural::SubroutineParamBase; @@ -418,7 +419,7 @@ pub struct ParameterOverride { name: String, value: Option, bound_type: Option, - pattern_text: Option, + bound_pattern: Option, } impl ParameterOverride { @@ -426,19 +427,19 @@ impl ParameterOverride { name: String, value: Option, bound_type: Option, - pattern_text: Option, + bound_pattern: Option, ) -> Self { Self { name, value, bound_type, - pattern_text, + bound_pattern, } } /// A constant assignment pattern, evaluated in the caller scope. - pub fn pattern_text(&self) -> Option<&str> { - self.pattern_text.as_deref() + pub fn bound_pattern(&self) -> Option<&crate::ast::BoundPattern> { + self.bound_pattern.as_ref() } pub fn name(&self) -> &str { diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 2ad5920849f..23613967ae5 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -142,6 +142,7 @@ const UNSUPPORTED_CONSTRUCT_ISSUES: &[(&str, u32)] = &[ ("streaming concatenation", 447), ("loop-generate unroll limit exceeded", 448), ("iff-qualified always_ff event", 452), + ("iff-qualified event", 1444), ("nonblocking assignment inside always_comb", 453), ("genvar update operator", 455), ("reduction operator in parameter expression", 456), @@ -327,6 +328,7 @@ pub fn analyze_source_module_with_packages( module_name, &overrides, &[], + &[], &ModuleInterfaces::default(), packages, ) diff --git a/crates/celox-sv-analyzer/src/parsed.rs b/crates/celox-sv-analyzer/src/parsed.rs index 86d87a19cff..052fe3b0658 100644 --- a/crates/celox-sv-analyzer/src/parsed.rs +++ b/crates/celox-sv-analyzer/src/parsed.rs @@ -14,7 +14,6 @@ use crate::{AnalyzerError, Ir, ModuleInterfaces, Packages, analyze, ast, ir, syn /// remain local to each analysis. Like `sv-parser`'s tree, this value is confined /// to the parsing thread; consumers can share it there with [`std::rc::Rc`]. pub struct ParsedSource { - code: String, path: PathBuf, tree: sv_parser::SyntaxTree, index: ast::module_index::ModuleIndex, @@ -25,30 +24,12 @@ impl ParsedSource { let tree = syntax::parse_source(code, path)?; let index = ast::with_call_sites(|| ast::module_index::ModuleIndex::new(&tree))?; Ok(Self { - code: code.to_string(), path: path.to_path_buf(), tree, index, }) } - /// Bind assignment-pattern parameters with values frozen in the caller. - pub fn with_pattern_parameter_overrides( - &self, - module_name: &str, - overrides: &[(String, String)], - ) -> Result, AnalyzerError> { - ast::type_parameters::apply_pattern_parameter_overrides( - &self.code, - &self.tree, - module_name, - overrides, - )? - .as_deref() - .map(|code| Self::parse(code, &self.path)) - .transpose() - } - pub fn module_names(&self) -> &[String] { self.index.names() } @@ -119,6 +100,7 @@ impl ParsedSource { module_name: &str, overrides: &HashMap, type_overrides: &[(String, ast::Type)], + pattern_overrides: &[(String, ast::BoundPattern)], interfaces: &ModuleInterfaces, packages: &Packages, ) -> Result { @@ -126,6 +108,7 @@ impl ParsedSource { module_name, overrides, type_overrides, + pattern_overrides, interfaces, packages, ) @@ -140,7 +123,7 @@ impl ParsedSource { interfaces: &ModuleInterfaces, ) -> Result { let packages = Self::analyze_packages(&[self])?; - self.analyze_module_with_packages(module_name, overrides, &[], interfaces, &packages) + self.analyze_module_with_packages(module_name, overrides, &[], &[], interfaces, &packages) } fn analyze_module_with_packages( @@ -148,6 +131,7 @@ impl ParsedSource { module_name: &str, overrides: &HashMap, type_overrides: &[(String, ast::Type)], + pattern_overrides: &[(String, ast::BoundPattern)], interfaces: &ModuleInterfaces, packages: &Packages, ) -> Result { @@ -164,6 +148,7 @@ impl ParsedSource { ast::ModuleParameterBindings { values: &overrides, types: type_overrides, + patterns: pattern_overrides, }, interfaces, packages, @@ -316,6 +301,7 @@ mod tests { "Top", &HashMap::default(), &types, + &[], &ModuleInterfaces::default(), &packages, ) @@ -361,6 +347,7 @@ mod tests { "Child", &HashMap::default(), &bindings, + &[], &ModuleInterfaces::default(), &packages, ) @@ -392,6 +379,7 @@ mod tests { "Child", &HashMap::default(), &[("T".into(), type_binding("bit signed [7:0]"))], + &[], &ModuleInterfaces::default(), &packages, ) @@ -426,6 +414,7 @@ mod tests { "Child", &HashMap::default(), &bindings, + &[], &ModuleInterfaces::default(), &packages ) @@ -437,6 +426,7 @@ mod tests { "Child", &HashMap::default(), &[], + &[], &ModuleInterfaces::default(), &packages, ) @@ -531,16 +521,24 @@ mod pattern_override_tests { Path::new("pattern_scope.sv"), ) .unwrap(); - let rebound = source - .with_pattern_parameter_overrides("Top", &[("Q".into(), "'{-3, -5}".into())]) + let caller = crate::analyze_source( + "module Caller; Top #(.Q('{-3, -5})) t(); endmodule", + Path::new("caller.sv"), + ) + .unwrap(); + let bound = caller.modules()[0].instances()[0].parameter_overrides()[0] + .bound_pattern() .unwrap() - .unwrap(); - assert!(rebound.code.contains("localparam int Q = 9;")); - let ir = rebound - .analyze_module_with_parameter_expr_overrides( + .clone(); + let packages = ParsedSource::analyze_packages(&[&source]).unwrap(); + let ir = source + .analyze_module( "Top", &HashMap::default(), + &[], + &[("Q".into(), bound)], &ModuleInterfaces::default(), + &packages, ) .unwrap(); assert_eq!(ir.modules()[0].initial_processes().len(), 1); @@ -570,22 +568,21 @@ mod pattern_override_tests { .find(|module| module.name() == "Top") .unwrap(); for instance in top.instances() { - let pattern = instance.parameter_overrides()[0].pattern_text().unwrap(); - assert!(!pattern.contains('N'), "{pattern}"); + let pattern = instance.parameter_overrides()[0].bound_pattern().unwrap(); let child = ParsedSource::parse( "module Child #(parameter int N = 1, parameter byte Q [2] = '{1, 2}); endmodule", Path::new("child.sv"), ) .unwrap(); - let rebound = child - .with_pattern_parameter_overrides("Child", &[("Q".into(), pattern.into())]) - .unwrap() - .unwrap(); - rebound - .analyze_module_with_parameter_expr_overrides( + let packages = ParsedSource::analyze_packages(&[&child]).unwrap(); + child + .analyze_module( "Child", &HashMap::default(), + &[], + &[("Q".into(), pattern.clone())], &ModuleInterfaces::default(), + &packages, ) .unwrap(); } diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index f832b8def25..991b1f790ac 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -70,6 +70,36 @@ pub enum StmtBase { name: String, init: Option, }, + /// `#amount`: suspend the process for `amount` time units (IEEE + /// 1800-2023 9.4.1). + Delay(E), + /// `@(items)`: suspend the process until one of the events occurs + /// (9.4.2). + WaitEvent(Vec>), + /// `wait (condition)`: suspend the process until the condition is true + /// (9.4.3). + Wait(E), +} + +/// One item of an event control, `[edge] expr`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EventItemBase { + pub edge: EventEdge, + pub expr: E, +} + +/// Which transitions of an event expression are events (IEEE 1800-2023 +/// 9.4.2, Table 9-2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EventEdge { + /// Any change of the value. + Any, + /// `posedge`: the least significant bit rises. + Pos, + /// `negedge`: the least significant bit falls. + Neg, + /// `edge`: the least significant bit rises or falls. + Both, } /// How a case statement compares its selector with the item labels. @@ -255,6 +285,17 @@ impl StmtBase { name, init: init.map(fe), }, + StmtBase::Delay(amount) => StmtBase::Delay(fe(amount)), + StmtBase::WaitEvent(items) => StmtBase::WaitEvent( + items + .into_iter() + .map(|item| EventItemBase { + edge: item.edge, + expr: fe(item.expr), + }) + .collect(), + ), + StmtBase::Wait(condition) => StmtBase::Wait(fe(condition)), } } @@ -360,6 +401,13 @@ impl StmtBase { fe(init); } } + StmtBase::Delay(amount) => fe(amount), + StmtBase::WaitEvent(items) => { + for item in items { + fe(&mut item.expr); + } + } + StmtBase::Wait(condition) => fe(condition), } } diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index b7f22392912..468d13d2ecb 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -1406,6 +1406,7 @@ fn resolves_imported_constant_parameter_part_selects() { "Top", &HashMap::default(), &[], + &[], &ModuleInterfaces::default(), &packages, ) @@ -3485,6 +3486,67 @@ fn rejects_unlowered_constructs() { assert!(matches!(error, AnalyzerError::Unsupported(_)), "{error:?}"); } +/// Timing constructs that remain unimplemented are rejected with their +/// own construct names, not as a generic timing control. +#[test] +fn rejects_unimplemented_timing_constructs() { + for (body, construct) in [ + ("initial begin fork #1; join end", "fork-join block"), + ("initial wait fork;", "wait fork statement"), + // The `event` data type is rejected before its uses. + ("event e; initial @e;", "unsupported internal data type"), + ("event e; initial ->e;", "unsupported internal data type"), + ( + "logic clk, en; initial @(posedge clk iff en);", + "iff-qualified event", + ), + ( + "logic a, b; initial a = #1 b;", + "intra-assignment timing control", + ), + ( + "logic a, b; initial a <= #1 b;", + "intra-assignment timing control", + ), + ("initial begin : b disable b; end", "disable statement"), + ("initial #1.5;", "delay value"), + ( + "logic a; initial @* a = 1;", + "`@*` event control in a process", + ), + ( + "logic clk; always @(posedge clk) #1;", + "always and always_latch processes", + ), + ( + "task automatic t; #1; endtask", + "delay control in a subroutine", + ), + ] { + let code = format!("module Top; {body} endmodule"); + let error = analyze_source(&code, Path::new("timing.sv")) + .expect_err(&format!("`{body}` must be rejected")); + assert!( + matches!(&error, AnalyzerError::Unsupported(text) if text.starts_with(construct)), + "`{body}`: {error:?}" + ); + } + assert_eq!( + AnalyzerError::Unsupported("iff-qualified event".to_string()).tracking_issue(), + 1444 + ); +} + +/// Delays, event controls and waits in an `initial` block keep their +/// statement structure in the IR. +#[test] +fn analyzes_timing_controls_in_initial_blocks() { + let code = "module Top(input logic clk, output logic [7:0] y);\n\ + initial begin #3; @(posedge clk or negedge clk, y); @(edge clk); #(1:2:3); wait (y > 1); end\n\ + endmodule"; + analyze_source(code, Path::new("timing.sv")).expect("timing controls in an initial block"); +} + #[test] fn analyzes_veryl_emitted_fifo_with_runtime_casts() { analyze_source( diff --git a/crates/celox-test-suite/src/sv/cases/edges.vtest b/crates/celox-test-suite/src/sv/cases/edges.vtest new file mode 100644 index 00000000000..1d1bb80a3ac --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/edges.vtest @@ -0,0 +1,186 @@ +(group edges (category sequential)) + +; IEEE 1800-2023 9.4.2, Table 9-2 for clocks and resets the design drives +; itself. A posedge leaves 0 or reaches 1, a negedge leaves 1 or reaches 0, +; and a change between x and z is neither. Each design walks its clock or +; reset through all twelve changes between 0, 1, x and z (an Euler circuit), +; one change per tick. Rising and falling edges are sensed on two copies of +; the clock. + +(case register_clock_edges_follow_table_9_2 + (four_state) + (source "register_clock.sv" #" +module Top(input logic clk, input logic d, + output logic [7:0] pos, output logic [7:0] neg); + logic cp; + logic cn; + logic [7:0] p = 8'd0; + logic [7:0] n = 8'd0; + always_ff @(posedge clk) begin + cp <= d; + cn <= d; + end + always_ff @(posedge cp) p <= p + 8'd1; + always_ff @(negedge cn) n <= n + 8'd1; + assign pos = p; + assign neg = n; +endmodule +"#) + (top Top) + (set clk 0) + ; x -> 0 is a negedge. + (set d 0) + (tick clk) + (assert_eq pos 0) + (assert_eq neg 1) + (for (value pos_count neg_count) + (list (1 1 1) (0 1 2) (1'bx 2 2) (0 2 3) (1'bz 3 3) (1 4 3) + (1'bx 4 4) (1 5 4) (1'bz 5 5) (1'bx 5 5) (1'bz 5 5) (0 5 6)) + (set d value) + (tick clk) + (assert_eq pos pos_count) + (assert_eq neg neg_count))) + +; A clock computed by continuous assignments from a register. The register +; changes as a whole, so the clock changes once per tick without a glitch. +(case comb_clock_edges_follow_table_9_2 + (four_state) + (source "comb_clock.sv" #" +module Top(input logic clk, input logic [2:0] d, + output logic [7:0] pos, output logic [7:0] neg); + logic [2:0] r; + logic a; + logic cp; + logic cn; + logic [7:0] p = 8'd0; + logic [7:0] n = 8'd0; + always_ff @(posedge clk) r <= d; + assign a = r[1] & r[0]; + assign cp = r[2] ? a : 1'bz; + assign cn = r[2] ? r[1] & r[0] : 1'bz; + always_ff @(posedge cp) p <= p + 8'd1; + always_ff @(negedge cn) n <= n + 8'd1; + assign pos = p; + assign neg = n; +endmodule +"#) + (top Top) + (set clk 0) + ; x -> 0 is a negedge. + (set d 3'b101) + (tick clk) + (assert_eq pos 0) + (assert_eq neg 1) + ; Clock levels: 1, 0, x, 0, z, 1, x, 1, z, x, z, 0. + (for (value pos_count neg_count) + (list (3'b111 1 1) (3'b100 1 2) (3'b11z 2 2) (3'b110 2 3) (3'b011 3 3) + (3'b111 4 3) (3'b1x1 4 4) (3'b111 5 4) (3'b000 5 5) (3'bx11 5 5) + (3'b0z1 5 5) (3'b101 5 6)) + (set d value) + (tick clk) + (assert_eq pos pos_count) + (assert_eq neg neg_count))) + +; Asynchronous resets driven by registers. A reset's edge runs its register, +; which takes the reset branch only at the known active level: an edge to x +; or z increments the counter, and an edge to the active level clears it. The +; path puts an increment before every clear, and an edge that should not fire +; would increment the counter. +(case internal_async_reset_edges_follow_table_9_2 + (four_state) + (source "async_reset.sv" #" +module Top(input logic clk, input logic k, input logic dh, input logic dl, + output logic [7:0] hits_h, output logic [7:0] hits_l); + logic rh; + logic rl; + logic [7:0] h = 8'h80; + logic [7:0] l = 8'h80; + always_ff @(posedge clk) begin + rh <= dh; + rl <= dl; + end + always_ff @(posedge k or posedge rh) + if (rh) h <= 8'd0; + else h <= h + 8'd1; + always_ff @(posedge k or negedge rl) + if (!rl) l <= 8'd0; + else l <= l + 8'd1; + assign hits_h = h; + assign hits_l = l; +endmodule +"#) + (top Top) + (set clk 0) + (set k 0) + ; x -> 0 is not a posedge, and x -> 1 is not a negedge. + (set dh 0) + (set dl 1) + (tick clk) + (assert_eq hits_h 0x80) + (assert_eq hits_l 0x80) + ; Reset levels 1, 0, x, 1, x, 0, z, 1, z, x, z, 0 for `rh`; `rl` has 0 and + ; 1 swapped. + (for (high low hits) + (list (1 0 0) (0 1 0) (1'bx 1'bx 1) (1 0 0) (1'bx 1'bx 0) (0 1 0) + (1'bz 1'bz 1) (1 0 0) (1'bz 1'bz 0) (1'bx 1'bx 0) (1'bz 1'bz 0) + (0 1 0)) + (set dh high) + (set dl low) + (tick clk) + (assert_eq hits_h hits) + (assert_eq hits_l hits))) + +; A clock gated by the ticked clock, `clk & en`, rises to 1 or x with the +; tick. A tick drives `clk` from its inactive level, so an x or z `clk` goes to +; 0 first. No write between ticks raises the gated clock. +(case gated_clock_edges_from_unknown_levels + (four_state) + (source "gated_clock.sv" #" +module Top(input logic clk, input logic en, output logic [7:0] pos, + output logic [7:0] ticks); + logic g; + logic [7:0] p = 8'd0; + logic [7:0] t = 8'd0; + assign g = clk & en; + always_ff @(posedge clk) t <= t + 8'd1; + always_ff @(posedge g) p <= p + 8'd1; + assign pos = p; + assign ticks = t; +endmodule +"#) + (top Top) + (for (clock enable count) + (list (1'bx 1 1) (1'bz 1'bx 2) (1'bx 1 3) (0 1'bz 4) (1'bz 0 4) (0 1 5)) + (set clk clock) + (set en enable) + (tick clk) + (assert_eq pos count))) + +; The register clock of `register_clock_edges_follow_table_9_2` in two-state +; simulation, where only 0 and 1 occur. +(case register_clock_two_state_edges + (source "register_clock.sv" #" +module Top(input bit clk, input bit d, + output bit [7:0] pos, output bit [7:0] neg); + bit cp; + bit cn; + bit [7:0] p; + bit [7:0] n; + always_ff @(posedge clk) begin + cp <= d; + cn <= d; + end + always_ff @(posedge cp) p <= p + 8'd1; + always_ff @(negedge cn) n <= n + 8'd1; + assign pos = p; + assign neg = n; +endmodule +"#) + (top Top) + (set clk 0) + (for (value pos_count neg_count) + (list (0 0 0) (1 1 0) (1 1 0) (0 1 1) (1 2 1) (0 2 2)) + (set d value) + (tick clk) + (assert_eq pos pos_count) + (assert_eq neg neg_count))) diff --git a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest index 9f02025d908..9349c2ffe17 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchy.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchy.vtest @@ -469,3 +469,46 @@ (eval) (assert_eq value 9) (assert_eq raw (fourstate 13 6))) + +(case parameter_patterns_keep_original_declarations_and_isolated_bindings + (source "pattern_binding_isolation.sv" #" + `define ORIGINAL_VALUES '{1, 2} + module Child #(parameter int N = 9, parameter byte Q [2] = `ORIGINAL_VALUES) + (output logic [15:0] y, output logic [7:0] local_y); + assign y = {Q[0], Q[1]}; + always_comb begin + localparam byte Q = 7; + local_y = Q; + end + endmodule + module Top(output logic [15:0] defaults, repeated, keyed, + output logic [7:0] local_default, local_repeated, local_keyed); + localparam N = 2; + Child a(defaults, local_default); + Child #(.Q('{N{-N}})) b(repeated, local_repeated); + Child #(.Q('{N-2: -N, default: N+1})) c(keyed, local_keyed); + endmodule + `undef ORIGINAL_VALUES + "#) + (top Top) + (assert_eq defaults 0x0102) + (assert_eq repeated 0xfefe) + (assert_eq keyed 0xfe03) + (assert_eq local_default 7) + (assert_eq local_repeated 7) + (assert_eq local_keyed 7)) + +(case parameter_patterns_preserve_enclosing_expressions + (source "pattern_expressions.sv" #" + module Child #(parameter logic [15:0] P = 0)(output logic [15:0] y); + assign y = P; + endmodule + module Top(output logic [15:0] added, negated); + typedef logic [7:0] byte_t; + Child #(.P(byte_t'{default: 1} + 16'd1)) a(added); + Child #(.P(~(byte_t'{default: 0} | 16'd0))) b(negated); + endmodule + "#) + (top Top) + (assert_eq added 256) + (assert_eq negated 65535)) diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index 8f88d2cba33..d6dbc7e3d4a 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -11,6 +11,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/always_comb.vtest", text: include_str!("always_comb.vtest"), }, + Group { + file: "src/sv/cases/edges.vtest", + text: include_str!("edges.vtest"), + }, Group { file: "src/sv/cases/generate.vtest", text: include_str!("generate.vtest"), diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index e441ec138e7..a4a71ae644b 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -684,6 +684,62 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev module Top(output wire[7:0]qualified,imported);Qualified a(qualified);Imported b(imported);initial #2 $finish;endmodule "#)(top Top)(run_until 0)(assert_eq qualified 0)(assert_eq imported 0)(run_until 1)(assert_eq qualified 0)(assert_eq imported 0)(run_to_finish)) +(case edge_waits_wake_on_rising_and_falling_edges + (source "edge.sv" #" + module Top(output logic [7:0] seen); + logic clk = 1'b0; + initial begin + #3 clk = 1'b1; + #3 clk = 1'b0; + #3 clk = 1'b1; + end + initial begin + seen = 8'd0; + forever @(edge clk) seen = seen + 8'd1; + end + endmodule + "#) + (top Top) + (run_until 2) + (assert_eq seen 0) + (run_until 3) + (assert_eq seen 1) + (run_until 6) + (assert_eq seen 2 "a falling edge is an edge") + (run_until 9) + (assert_eq seen 3)) + +(case min_typ_max_delays_wait_the_typical_value + (source "mintypmax.sv" #" + module Top(output logic [7:0] a); + initial begin + a = 8'd1; + #(2:5:9) a = 8'd2; + end + endmodule + "#) + (top Top) + (run_until 4) + (assert_eq a 1) + (run_until 5) + (assert_eq a 2)) + +(case long_process_loops_finish_within_one_time_slot + (source "long_loop.sv" #" + module Top(output logic [31:0] count); + initial begin + count = 32'd0; + for (int i = 0; i < 200000; i++) count = count + 32'd1; + #1 count = count + 32'd1; + end + endmodule + "#) + (top Top) + (run_until 0) + (assert_eq count 200000) + (run_until 1) + (assert_eq count 200001)) + (case initial_blocks_run_at_time_zero (source "time_zero.sv" #" module Top(output bit [7:0] y); diff --git a/crates/celox-test-suite/src/veryl/cases/four_state.vtest b/crates/celox-test-suite/src/veryl/cases/four_state.vtest index 8c7d2c71ef0..341eb6366d5 100644 --- a/crates/celox-test-suite/src/veryl/cases/four_state.vtest +++ b/crates/celox-test-suite/src/veryl/cases/four_state.vtest @@ -2393,3 +2393,196 @@ assign narrow_256 = a_256 >> sh; (assert_eq shr_{width} (fourstate limit limit) "unknown count width={width}") (assert_eq shl_{width} (fourstate limit limit) "unknown count width={width}") (assert_eq narrow_{width} (fourstate 15 15)))))) + +; IEEE 1800-2023 9.4.2, Table 9-2: a posedge leaves 0 or reaches 1, a negedge +; leaves 1 or reaches 0, and a change between x and z is neither. The clock +; below is a register, so each of its twelve changes (an Euler circuit over +; 0, 1, x, z) is an edge of an internally driven clock. +(case test_four_state_register_clock_edges_follow_table_9_2 + (four_state) + (source "test.veryl" #" +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + d : input logic, + pos: output logic<8>, + neg: output logic<8>, +) { + var c: logic; + always_ff (clk) { + c = d; + } + let cp: '_ clock = c; + let cn: '_ clock_negedge = c; + var p : logic<8>; + var n : logic<8>; + always_ff (cp, rst) { + if_reset { + p = 0; + } else { + p = p + 8'd1; + } + } + always_ff (cn, rst) { + if_reset { + n = 0; + } else { + n = n + 8'd1; + } + } + assign pos = p; + assign neg = n; +} +"#) + (top Top) + (set clk 0) + (set rst 0) + (tick rst) + (set rst 1) + (assert_eq pos 0) + (assert_eq neg 0) + ; x -> 0 is a negedge. + (set d 0) + (tick clk) + (assert_eq pos 0) + (assert_eq neg 1) + (for (value pos_count neg_count) + (list (1 1 1) (0 1 2) (1'bx 2 2) (0 2 3) (1'bz 3 3) (1 4 3) + (1'bx 4 4) (1 5 4) (1'bz 5 5) (1'bx 5 5) (1'bz 5 5) (0 5 6)) + (set d value) + (tick clk) + (assert_eq pos pos_count) + (assert_eq neg neg_count))) + +; The same transitions on a clock computed combinationally from a register, +; `e ? a & b : 'z`. The register changes as a whole, so the clock changes once +; per tick without a glitch. +(case test_four_state_comb_clock_edges_follow_table_9_2 + (four_state) + (source "test.veryl" #" +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + d : input logic<3>, + pos: output logic<8>, + neg: output logic<8>, +) { + var r: logic<3>; + always_ff (clk) { + r = d; + } + let cp: '_ clock = if r[2] ? r[1] & r[0] : 1'bz; + let cn: '_ clock_negedge = if r[2] ? r[1] & r[0] : 1'bz; + var p : logic<8>; + var n : logic<8>; + always_ff (cp, rst) { + if_reset { + p = 0; + } else { + p = p + 8'd1; + } + } + always_ff (cn, rst) { + if_reset { + n = 0; + } else { + n = n + 8'd1; + } + } + assign pos = p; + assign neg = n; +} +"#) + (top Top) + (set clk 0) + (set rst 0) + (tick rst) + (set rst 1) + ; x -> 0 is a negedge. + (set d 3'b101) + (tick clk) + (assert_eq pos 0) + (assert_eq neg 1) + ; Clock levels: 1, 0, x, 0, z, 1, x, 1, z, x, z, 0. + (for (value pos_count neg_count) + (list (3'b111 1 1) (3'b100 1 2) (3'b11z 2 2) (3'b110 2 3) (3'b011 3 3) + (3'b111 4 3) (3'b1x1 4 4) (3'b111 5 4) (3'b000 5 5) (3'bx11 5 5) + (3'b0z1 5 5) (3'b101 5 6)) + (set d value) + (tick clk) + (assert_eq pos pos_count) + (assert_eq neg neg_count))) + +; Asynchronous resets driven by registers. A reset domain runs on every +; Table 9-2 edge of its reset and takes the reset branch only at the known +; active level, so an edge to x or z increments the counter and an edge to +; the active level clears it. The path through the twelve changes puts an +; increment before every clear, and any edge that should not fire would +; increment the counter. +(case test_four_state_internal_async_reset_edges_follow_table_9_2 + (four_state) + (source "test.veryl" #" +module Top ( + clk : input '_ clock, + k : input '_ clock, + clr : input logic, + dh : input logic, + dl : input logic, + hits_h: output logic<8>, + hits_l: output logic<8>, +) { + var qh: logic; + var ql: logic; + always_ff (clk) { + qh = dh; + ql = dl; + } + let rh: '_ reset_async_high = qh; + let rl: '_ reset_async_low = ql; + var h : logic<8>; + var l : logic<8>; + always_ff (k, rh) { + if_reset { + h = 0; + } else if clr { + h = 8'h80; + } else { + h = h + 8'h01; + } + } + always_ff (k, rl) { + if_reset { + l = 0; + } else if clr { + l = 8'h80; + } else { + l = l + 8'h01; + } + } + assign hits_h = h; + assign hits_l = l; +} +"#) + (top Top) + (set clk 0) + (set k 0) + ; x -> 0 is not a posedge, and x -> 1 is not a negedge. + (set dh 0) + (set dl 1) + (tick clk) + (set clr 1) + (tick k) + (set clr 0) + (assert_eq hits_h 0x80) + (assert_eq hits_l 0x80) + ; Reset levels 1, 0, x, 1, x, 0, z, 1, z, x, z, 0 for `rh`; `rl` has 0 and + ; 1 swapped. + (for (high low hits) + (list (1 0 0) (0 1 0) (1'bx 1'bx 1) (1 0 0) (1'bx 1'bx 0) (0 1 0) + (1'bz 1'bz 1) (1 0 0) (1'bz 1'bz 0) (1'bx 1'bx 0) (1'bz 1'bz 0) + (0 1 0)) + (set dh high) + (set dl low) + (tick clk) + (assert_eq hits_h hits) + (assert_eq hits_l hits))) diff --git a/crates/celox-test-suite/tests/external_adapter.rs b/crates/celox-test-suite/tests/external_adapter.rs index 6f25ed0416c..5a0b362488a 100644 --- a/crates/celox-test-suite/tests/external_adapter.rs +++ b/crates/celox-test-suite/tests/external_adapter.rs @@ -93,7 +93,7 @@ fn catalogue_has_unique_stable_names_and_categories() { assert!(names.insert(case.name), "duplicate {}", case.name); assert!(case.name.contains("::")); } - assert_eq!(names.len(), 762); + assert_eq!(names.len(), 765); assert_eq!( case("operators::test_bitwise_operations").unwrap().category, Category::Operators diff --git a/crates/celox-test-suite/verification/sv/icarus/generate.json b/crates/celox-test-suite/verification/sv/icarus/generate.json index 8e62f79fb18..d04abdd4415 100644 --- a/crates/celox-test-suite/verification/sv/icarus/generate.json +++ b/crates/celox-test-suite/verification/sv/icarus/generate.json @@ -181,6 +181,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, diff --git a/crates/celox-test-suite/verification/sv/icarus/hierarchy.json b/crates/celox-test-suite/verification/sv/icarus/hierarchy.json index 15a70b06b1a..ee5f58bdfcb 100644 --- a/crates/celox-test-suite/verification/sv/icarus/hierarchy.json +++ b/crates/celox-test-suite/verification/sv/icarus/hierarchy.json @@ -19,6 +19,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -42,6 +43,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -65,6 +67,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -88,6 +91,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -215,6 +219,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, @@ -238,6 +243,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, @@ -267,6 +273,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] } @@ -290,6 +297,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] } @@ -313,9 +321,58 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] } + }, + { + "name": "hierarchy::parameter_patterns_preserve_enclosing_expressions", + "category": "Hierarchy", + "expectation": "Simulation", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "known_issue": { + "id": "sv_icarus_syntax", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 rejects syntax used by these designs: selects of concatenations and replications (IEEE 1800-2023 A.8.4, primary), keyed and typed assignment patterns, packed-structure parameter declarations, and parameter type declarations in generate blocks.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" + }, + { + "name": "hierarchy::parameter_patterns_keep_original_declarations_and_isolated_bindings", + "category": "Hierarchy", + "expectation": "Simulation", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "detail": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "known_issue": { + "id": "sv_icarus_unpacked_array_parameters", + "category": "simulator_compile_limitation", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 reports that unpacked array parameters are not supported (IEEE 1800-2023 6.20.2) and rejects the typed assignment pattern of a struct parameter. Verilator passes the struct-parameter case; its internal error on the $isunbounded array query is recorded separately.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ] + }, + "phase": "skip", + "status": "ignored" } ] } diff --git a/crates/celox-test-suite/verification/sv/icarus/indexed_select.json b/crates/celox-test-suite/verification/sv/icarus/indexed_select.json index 0ca89492be7..1811d025379 100644 --- a/crates/celox-test-suite/verification/sv/icarus/indexed_select.json +++ b/crates/celox-test-suite/verification/sv/icarus/indexed_select.json @@ -36,6 +36,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, @@ -81,6 +82,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, @@ -115,6 +117,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, @@ -226,6 +229,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, @@ -249,6 +253,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, diff --git a/crates/celox-test-suite/verification/sv/icarus/procedural.json b/crates/celox-test-suite/verification/sv/icarus/procedural.json index eb4a98cbe32..dd1f06d9948 100644 --- a/crates/celox-test-suite/verification/sv/icarus/procedural.json +++ b/crates/celox-test-suite/verification/sv/icarus/procedural.json @@ -8,6 +8,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", diff --git a/crates/celox-test-suite/verification/sv/icarus/review_regressions.json b/crates/celox-test-suite/verification/sv/icarus/review_regressions.json index c75b20bbe78..c820979706a 100644 --- a/crates/celox-test-suite/verification/sv/icarus/review_regressions.json +++ b/crates/celox-test-suite/verification/sv/icarus/review_regressions.json @@ -35,6 +35,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, @@ -180,6 +181,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, diff --git a/crates/celox-test-suite/verification/sv/icarus/synthesizable.json b/crates/celox-test-suite/verification/sv/icarus/synthesizable.json index 1a4adf0dcf3..d93d7be4c81 100644 --- a/crates/celox-test-suite/verification/sv/icarus/synthesizable.json +++ b/crates/celox-test-suite/verification/sv/icarus/synthesizable.json @@ -328,6 +328,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ] }, diff --git a/crates/celox-test-suite/verification/sv/icarus/system_functions.json b/crates/celox-test-suite/verification/sv/icarus/system_functions.json index a99b8693025..a37381f1e66 100644 --- a/crates/celox-test-suite/verification/sv/icarus/system_functions.json +++ b/crates/celox-test-suite/verification/sv/icarus/system_functions.json @@ -279,6 +279,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -622,6 +623,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -1233,6 +1235,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -1256,6 +1259,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -1302,6 +1306,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", @@ -1417,6 +1422,7 @@ "category": "simulator_compile_limitation", "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "id": "sv_icarus_unpacked_array_parameters", diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index cabc838a58e..cd555abd3a4 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -96,6 +96,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "cases": { @@ -111,7 +112,8 @@ "review_regressions::default_pattern_fills_each_element_of_unpacked_subarrays", "hierarchy::parameter_patterns_transfer_packed_values", "hierarchy::parameter_patterns_override_scalar_defaults", - "hierarchy::parameter_patterns_preserve_packed_member_states" + "hierarchy::parameter_patterns_preserve_packed_member_states", + "hierarchy::parameter_patterns_preserve_enclosing_expressions" ] } }, @@ -145,6 +147,7 @@ "upstream": [], "evidence": [ "verification/sv/limitations/icarus.json", + "verification/sv/limitations/pattern-bindings-icarus.json", "LIMITATIONS.md#systemverilog-suite" ], "cases": { @@ -158,6 +161,7 @@ "system_functions::isunbounded_reports_bounded_array_parameters", "hierarchy::parameter_patterns_evaluate_caller_constant_functions", "hierarchy::parameter_patterns_override_body_declarations", + "hierarchy::parameter_patterns_keep_original_declarations_and_isolated_bindings", "system_functions::unpacked_dimensions_publishes_array_parameters_before_declarations", "system_functions::unpacked_dimensions_resolves_package_array_constants", "system_functions::unpacked_dimensions_resolves_types_and_constant_scopes", diff --git a/crates/celox-test-suite/verification/sv/limitations/pattern-bindings-icarus.json b/crates/celox-test-suite/verification/sv/limitations/pattern-bindings-icarus.json new file mode 100644 index 00000000000..6d86e8f383b --- /dev/null +++ b/crates/celox-test-suite/verification/sv/limitations/pattern-bindings-icarus.json @@ -0,0 +1,57 @@ +{ + "cases": [ + { + "case_fingerprint": "46e32699a44c76e09e170464362d07224abb6770e1a7e061babfe855a66dfbf4", + "category": "Hierarchy", + "detail": "Icarus build exit status: 7; see /build.log\n/source_0.sv:3: sorry: unpacked array parameters are not supported yet.\n/source_0.sv:15: syntax error\n/source_0.sv:15: error: Syntax error in parameter value assignment list.\n/source_0.sv:15: error: Invalid module instantiation\n/source_0.sv:16: syntax error\n/source_0.sv:16: error: Syntax error in parameter value assignment list.\n/source_0.sv:16: error: Invalid module instantiation\n", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_keep_original_declarations_and_isolated_bindings", + "phase": "compile", + "reused": false, + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792281566 + }, + { + "case_fingerprint": "b0224fd8ab450a706e01b2fb34f41f5218e61c9d7f04558216838fb4ecad6270", + "category": "Hierarchy", + "detail": "Icarus build exit status: 6; see /build.log\n/source_0.sv:7: syntax error\n/source_0.sv:7: error: Syntax error in parameter value assignment list.\n/source_0.sv:7: error: Invalid module instantiation\n/source_0.sv:8: syntax error\n/source_0.sv:8: error: Syntax error in parameter value assignment list.\n/source_0.sv:8: error: Invalid module instantiation\n", + "expectation": "Simulation", + "name": "hierarchy::parameter_patterns_preserve_enclosing_expressions", + "phase": "compile", + "reused": false, + "status": "compile_error", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [], + "verified_at_unix": 1792281566 + } + ], + "context_fingerprint": "210520fad7d12ef78257b83bd11d81ddda693f68bfdae0ee9de0cae78a0ab483", + "counts": { + "compile_error": 2, + "emission_error": 0, + "ignored": 0, + "mismatch": 0, + "passed": 0, + "rejected": 0, + "runtime_error": 0, + "unexpected_accept": 0, + "unsupported": 0 + }, + "exclude_stronger_than_sv": false, + "include_ignored": false, + "incremental": true, + "run_counts": { + "fresh": 2, + "reused": 0 + }, + "schema_version": 3, + "suite": "sv", + "suite_version": "0.11.0", + "tool": "icarus", + "version": "Icarus Verilog version 13.0 (stable) (v13_0)", + "retained_selection": "The two newly added parameter-pattern regressions from the local parameter_patterns run; existing ignored cases are omitted." +} diff --git a/crates/celox-vpi/Cargo.toml b/crates/celox-vpi/Cargo.toml index df83e9a7ca9..b4ac5a08050 100644 --- a/crates/celox-vpi/Cargo.toml +++ b/crates/celox-vpi/Cargo.toml @@ -8,6 +8,9 @@ license.workspace = true description.workspace = true edition.workspace = true +[features] +systemverilog = ["celox/systemverilog"] + [lib] crate-type = ["rlib", "cdylib"] diff --git a/crates/celox-vpi/src/lib.rs b/crates/celox-vpi/src/lib.rs index 73fd74ae014..eab9d9d92de 100644 --- a/crates/celox-vpi/src/lib.rs +++ b/crates/celox-vpi/src/lib.rs @@ -190,20 +190,26 @@ fn logic_level(value: &BigUint, mask: &BigUint) -> LogicLevel { } } -fn is_active_edge(kind: DomainKind, old: LogicLevel, new: LogicLevel) -> bool { - match celox_design::edges::polarity(kind) { - Some(true) => { - matches!(old, LogicLevel::Zero) && !matches!(new, LogicLevel::Zero) - || matches!(old, LogicLevel::X | LogicLevel::Z) && matches!(new, LogicLevel::One) - } - Some(false) => { - matches!(old, LogicLevel::One) && !matches!(new, LogicLevel::One) - || matches!(old, LogicLevel::X | LogicLevel::Z) && matches!(new, LogicLevel::Zero) +impl LogicLevel { + /// The edge level of [`celox_design::edges`]. + fn edge_level(self) -> u8 { + use celox_design::edges::LEVEL_UNKNOWN; + match self { + LogicLevel::Zero => 0, + LogicLevel::One => 1, + LogicLevel::X => LEVEL_UNKNOWN | 1, + LogicLevel::Z => LEVEL_UNKNOWN, } - None => false, } } +/// Whether a write from `old` to `new` is an active edge of a domain of +/// `kind` (IEEE 1800-2023 Table 9-2). A domain without an edge has none. +fn is_active_edge(kind: DomainKind, old: LogicLevel, new: LogicLevel) -> bool { + celox_design::edges::polarity(kind).is_some() + && celox_design::edges::settled_edge::(Some(kind), old.edge_level(), new.edge_level()) +} + fn record_pending_write( pending: &mut PendingWrites, id: ReflectionSignalId, @@ -609,8 +615,9 @@ fn object_type(object: ObjectRef) -> i32 { /// /// `reference` must be a live handle returned by this library. pub unsafe extern "C" fn vpi_get(property: i32, reference: VpiHandle) -> i32 { - if matches!(property, VPI_TIME_UNIT | VPI_TIME_PRECISION) { - return -12; + if reference.is_null() && matches!(property, VPI_TIME_UNIT | VPI_TIME_PRECISION) { + return with_runtime(|runtime| runtime.time_precision().exponent()) + .unwrap_or_else(|| celox_design::TimePrecision::default().exponent()); } if reference.is_null() { return 0; @@ -631,6 +638,23 @@ pub unsafe extern "C" fn vpi_get(property: i32, reference: VpiHandle) -> i32 { return 0; }; match property { + VPI_TIME_UNIT | VPI_TIME_PRECISION => with_runtime(|runtime| { + let reflection = runtime.reflection(); + let scope = match object { + ObjectRef::Scope(id) => reflection.scope(id), + ObjectRef::Signal(id) => reflection + .signal(id) + .and_then(|signal| reflection.scope(signal.parent)), + }; + scope.map_or(0, |scope| { + if property == VPI_TIME_UNIT { + scope.time_scale.unit.exponent() + } else { + scope.time_scale.precision.exponent() + } + }) + }) + .unwrap_or(0), VPI_TYPE => object_type(object), VPI_TOP_MODULE => i32::from(object == ObjectRef::Scope(ReflectionScopeId(0))), VPI_SIZE | VPI_SCALAR | VPI_VECTOR | VPI_DIRECTION | VPI_SIGNED => { diff --git a/crates/celox-vpi/tests/basic_vpi.rs b/crates/celox-vpi/tests/basic_vpi.rs index cdd09849e68..7f9935e3042 100644 --- a/crates/celox-vpi/tests/basic_vpi.rs +++ b/crates/celox-vpi/tests/basic_vpi.rs @@ -2292,3 +2292,81 @@ fn finish_during_queued_edge_replay_stops_remaining_callbacks_and_edges() { } clear_runtime(); } + +#[cfg(feature = "systemverilog")] +#[test] +fn vpi_time_properties_follow_the_attached_design_precision() { + for (declarations, unit, expected) in [ + ("", -9, -12), + ("timeunit 1ns; timeprecision 1fs;", -9, -15), + ("timeunit 1us; timeprecision 100ns;", -6, -7), + ] { + let source = format!("module Top(output logic y); {declarations} endmodule"); + let sim = + Simulator::from_sv_sources(vec![(&source, std::path::Path::new("time.sv"))], "Top") + .build_native() + .unwrap(); + let bytes = sim + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let image = celox::NativeProgramImage::from_container_bytes(&bytes).unwrap(); + install_runtime(trusted_instance(image)); + unsafe { + let top = vpi_handle_by_name(c"Top".as_ptr(), ptr::null_mut()); + assert_eq!(vpi_get(VPI_TIME_UNIT, ptr::null_mut()), expected); + assert_eq!(vpi_get(VPI_TIME_PRECISION, ptr::null_mut()), expected); + assert_eq!(vpi_get(VPI_TIME_UNIT, top), unit); + assert_eq!(vpi_get(VPI_TIME_PRECISION, top), expected); + vpi_free_object(top); + } + clear_runtime(); + } +} + +#[cfg(feature = "systemverilog")] +#[test] +fn vpi_time_properties_preserve_module_scales_in_native_images() { + let source = r#" + `timescale 10ns / 1ps + module Top(output logic y); + Coarse coarse(); + Fine fine(); + endmodule + module Coarse(output logic value); + timeunit 1us; timeprecision 100ns; + endmodule + module Fine(output logic value); + timeunit 1ns; timeprecision 1fs; + endmodule + "#; + let sim = Simulator::from_sv_sources(vec![(source, std::path::Path::new("scales.sv"))], "Top") + .build_native() + .unwrap(); + let bytes = sim + .shared_code() + .program_image() + .to_container_bytes() + .unwrap(); + let image = celox::NativeProgramImage::from_container_bytes(&bytes).unwrap(); + install_runtime(trusted_instance(image)); + unsafe { + assert_eq!(vpi_get(VPI_TIME_UNIT, ptr::null_mut()), -15); + assert_eq!(vpi_get(VPI_TIME_PRECISION, ptr::null_mut()), -15); + for (name, unit, precision) in [ + (c"Top", -8, -12), + (c"Top.coarse", -6, -7), + (c"Top.coarse.value", -6, -7), + (c"Top.fine", -9, -15), + (c"Top.fine.value", -9, -15), + ] { + let handle = vpi_handle_by_name(name.as_ptr(), ptr::null_mut()); + assert!(!handle.is_null(), "{name:?}"); + assert_eq!(vpi_get(VPI_TIME_UNIT, handle), unit, "{name:?}"); + assert_eq!(vpi_get(VPI_TIME_PRECISION, handle), precision, "{name:?}"); + vpi_free_object(handle); + } + } + clear_runtime(); +} diff --git a/crates/celox/benches/overhead.rs b/crates/celox/benches/overhead.rs index 23839ecada6..9bafc8fe723 100644 --- a/crates/celox/benches/overhead.rs +++ b/crates/celox/benches/overhead.rs @@ -59,71 +59,80 @@ fn benchmark_simulation_overhead(c: &mut Criterion) { } // Benchmark 1b/1c: Simulator::tick with a derived clock domain: a gated - // clock (`clk & en`) and a register-driven divider. - for (name, derived) in [ - ( - "simulator_tick_gated_x10000", - "let gated: '_ clock = clk & en; always_ff (gated) { extra += 1; }", - ), - ( - "simulator_tick_divided_x10000", - "var half: logic; always_ff (clk) { half = ~half; } - let divided: '_ clock = half; always_ff (divided) { extra += 1; }", - ), - ] { - let code = CODE.replace( - "cnt: output logic<32>[N],\n ) {", - &format!( - "cnt: output logic<32>[N],\n en: input logic,\n extra: output logic<32>,\n ) {{\n {derived}" - ), - ); - let mut sim = Simulator::builder(&code, "Top").build().unwrap(); - let clk = sim.event("clk"); - let rst = sim.signal("rst"); - let en = sim.signal("en"); - sim.modify(|io| { - io.set(rst, 0u8); - io.set(en, 1u8); - }) - .unwrap(); - sim.tick(clk).unwrap(); - sim.modify(|io| io.set(rst, 1u8)).unwrap(); - - c.bench_function(name, |b| { - b.iter(|| { - for _ in 0..10000 { - sim.tick(clk).unwrap(); - } - }) - }); - let cycle_name = name.replace("tick", "cycle"); - c.bench_function(&cycle_name, |b| { - b.iter(|| { - for _ in 0..10000 { - sim.cycle(clk).unwrap(); + // clock (`clk & en`) and a register-driven divider. The `_4state` + // variants build the same designs in four-state mode, where edges of + // derived clocks also read their unknown masks (IEEE 1800-2023 + // Table 9-2). + for four_state in [false, true] { + let suffix = if four_state { "_4state" } else { "" }; + for (name, derived) in DERIVED { + let mut sim = Simulator::builder(&derived_code(derived), "Top") + .four_state(four_state) + .build() + .unwrap(); + let clk = sim.event("clk"); + let rst = sim.signal("rst"); + let en = sim.signal("en"); + let half = (name == "divided").then(|| sim.signal("half")); + sim.modify(|io| { + io.set(rst, 0u8); + io.set(en, 1u8); + // A four-state divider starts at x and would never toggle. + if let Some(half) = half { + io.set(half, 0u8); } }) - }); + .unwrap(); + sim.tick(clk).unwrap(); + sim.modify(|io| io.set(rst, 1u8)).unwrap(); + + c.bench_function(&format!("simulator_tick_{name}{suffix}_x10000"), |b| { + b.iter(|| { + for _ in 0..10000 { + sim.tick(clk).unwrap(); + } + }) + }); + c.bench_function(&format!("simulator_cycle_{name}{suffix}_x10000"), |b| { + b.iter(|| { + for _ in 0..10000 { + sim.cycle(clk).unwrap(); + } + }) + }); + } } - // Benchmark 2: Simulation::step - { - let mut sim = Simulation::builder(CODE, "Top").build().unwrap(); - sim.add_clock("clk", 10, 10); + // Benchmark 2: Simulation::step, plain and with a register-driven + // divider, in both state modes. + for four_state in [false, true] { + let suffix = if four_state { "_4state" } else { "" }; + let divided = derived_code(DERIVED[1].1); + for (name, code) in [("", CODE), ("_divided", divided.as_str())] { + let mut sim = Simulation::builder(code, "Top") + .four_state(four_state) + .build() + .unwrap(); + if !name.is_empty() { + let half = sim.signal("half"); + sim.modify(|io| io.set(half, 0u8)).unwrap(); + } + sim.add_clock("clk", 10, 10); - // Reset - // simulation currently doesn't have a direct reset method, - // but we can schedule events or just let it run. - // For this benchmark, we just want to measure the steady state overhead. + // Reset + // simulation currently doesn't have a direct reset method, + // but we can schedule events or just let it run. + // For this benchmark, we just want to measure the steady state overhead. - c.bench_function("simulation_step_x20000", |b| { - b.iter(|| { - // 20000 steps = 10000 cycles (rising + falling) - for _ in 0..20000 { - sim.step().unwrap(); - } - }) - }); + c.bench_function(&format!("simulation_step{name}{suffix}_x20000"), |b| { + b.iter(|| { + // 20000 steps = 10000 cycles (rising + falling) + for _ in 0..20000 { + sim.step().unwrap(); + } + }) + }); + } } // Benchmark 3: Simulation::step of SystemVerilog counters at the rising @@ -171,5 +180,27 @@ fn benchmark_simulation_overhead(c: &mut Criterion) { } } +/// Derived clock domains added to [`CODE`] by [`derived_code`]. +const DERIVED: [(&str, &str); 2] = [ + ( + "gated", + "let gated: '_ clock = clk & en; always_ff (gated) { extra += 1; }", + ), + ( + "divided", + "var half: logic; always_ff (clk) { half = ~half; } + let divided: '_ clock = half; always_ff (divided) { extra += 1; }", + ), +]; + +fn derived_code(derived: &str) -> String { + CODE.replace( + "cnt: output logic<32>[N],\n ) {", + &format!( + "cnt: output logic<32>[N],\n en: input logic,\n extra: output logic<32>,\n ) {{\n {derived}" + ), + ) +} + criterion_group!(benches, benchmark_simulation_overhead); criterion_main!(benches); diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 2267bf7793f..e336bfe84e9 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -427,6 +427,11 @@ pub struct NativeProgramImage { } impl NativeProgramImage { + /// Physical duration of one tick, retained in serialized native images. + pub fn time_precision(&self) -> celox_design::TimePrecision { + self.design.time_precision + } + /// Remap filesystem paths in the image's runtime and diagnostic metadata. /// This permits relative paths in stored artifacts and rebinding on load. /// Machine code and design-authored literal strings are not modified. diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index f68a8012e79..c2808088fe9 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 13; +const CONTAINER_VERSION: u16 = 14; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/backend/native/runtime_image.rs b/crates/celox/src/backend/native/runtime_image.rs index c22fc1f196b..2ce9ad8aee0 100644 --- a/crates/celox/src/backend/native/runtime_image.rs +++ b/crates/celox/src/backend/native/runtime_image.rs @@ -103,6 +103,11 @@ impl NativeProgramInstance { unsafe { Self::from_image(appended.image) } } + /// Physical duration of one tick in the attached design. + pub fn time_precision(&self) -> celox_design::TimePrecision { + self.shared.program_image().time_precision() + } + /// Elaborated hierarchy and signal metadata embedded by the compiler. pub fn reflection(&self) -> &DesignReflection { self.shared.program_image().reflection() diff --git a/crates/celox/src/edge_plans.rs b/crates/celox/src/edge_plans.rs index 61c75ff3261..18c73387801 100644 --- a/crates/celox/src/edge_plans.rs +++ b/crates/celox/src/edge_plans.rs @@ -21,6 +21,10 @@ pub struct EdgePlanSignal { /// it in the next byte. pub offset: usize, pub width: usize, + /// The signal keeps unknown bits: its edges follow the four-state rows + /// of IEEE 1800-2023 Table 9-2. + #[serde(rename = "fourState")] + pub four_state: bool, } /// A derived event domain. @@ -96,6 +100,7 @@ pub fn edge_plans(program: &LaidOutProgram) -> EdgePlans { let signal = |address: &AbsoluteAddr| EdgePlanSignal { offset: layout.offsets.get(address).copied().unwrap_or_default(), width: layout.widths.get(address).copied().unwrap_or(1), + four_state: layout.four_state && layout.is_4states.get(address).copied().unwrap_or(false), }; let domain = |address: &AbsoluteAddr| EdgePlanDomain { event: program.get_path(address), diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index 3f2b06e1fe5..5f93ce300f2 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -913,6 +913,12 @@ impl RuntimeProgram { name: scope.name.clone(), full_name: scope.full_name.clone(), module_name: scope.module_name.clone(), + time_scale: self + .design + .instance_time_scales + .get(&scope.instance_id) + .copied() + .unwrap_or_default(), parent: scope.parent_name.as_ref().map(|parent| scope_ids[parent]), children: Vec::new(), signals: Vec::new(), diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 1e2b7536e32..ba25492c9fd 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -1254,3 +1254,475 @@ endmodule #[cfg(all(test, feature = "host-runtime"))] mod runtime_core_tests; + +/// Edges of clocks and resets the design drives itself follow IEEE 1800-2023 +/// 9.4.2, Table 9-2 in a four-state timed simulation, on every backend: a +/// posedge leaves 0 or reaches 1, a negedge leaves 1 or reaches 0, and a +/// change between x and z is neither. +#[cfg(all(test, feature = "host-runtime"))] +mod four_state_edge_tests { + use celox_frontend_sdk::{ + BinaryOp, Constant, Edge, EventEdge, EventTerm, ExprId, FrontendArtifact, ModuleBuilder, + Statement, ValueType, + }; + use num_bigint::BigUint; + + use super::Simulation; + use crate::{SimBackend, Simulator}; + + /// 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 + /// negedges counted after each change. + const WALK: [((u8, u8), u8, u8); 12] = [ + ((1, 0), 1, 0), + ((0, 0), 1, 1), + ((1, 1), 2, 1), + ((0, 0), 2, 2), + ((0, 1), 3, 2), + ((1, 0), 4, 2), + ((1, 1), 4, 3), + ((1, 0), 5, 3), + ((0, 1), 5, 4), + ((1, 1), 5, 4), + ((0, 1), 5, 4), + ((0, 0), 5, 5), + ]; + + /// Build `$check` against a timed simulation of each backend. + 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())); + #[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())); + }}; + } + + fn set(sim: &mut Simulation, name: &str, (value, mask): (u8, u8)) { + let signal = sim.signal(name); + sim.modify(|io| io.set_four_state(signal, value.into(), mask.into())) + .unwrap(); + } + + fn get(sim: &mut Simulation, name: &str) -> BigUint { + let signal = sim.signal(name); + sim.get(signal) + } + + /// Two processes drive `cp` and `cn` through [`WALK`], one change per + /// time unit; registers count the posedges of `cp` and the negedges of + /// `cn`. + fn process_design() -> FrontendArtifact { + let bit = ValueType::new(1, false, true).unwrap(); + let word = ValueType::new(8, false, true).unwrap(); + let mut module = ModuleBuilder::new("Top").unwrap(); + let cp = module.internal("cp", bit).unwrap(); + let cn = module.internal("cn", bit).unwrap(); + let pos = module.output("pos", word).unwrap(); + let neg = module.output("neg", word).unwrap(); + for (signal, width) in [(cp, 1), (cn, 1), (pos, 8), (neg, 8)] { + module + .set_initial(signal, Constant::two_state(0u8, width).unwrap()) + .unwrap(); + } + let one = module.constant(Constant::two_state(1u8, 8).unwrap()); + for (counter, clock, edge) in [(pos, cp, Edge::Posedge), (neg, cn, Edge::Negedge)] { + let read = module.read(counter).unwrap(); + let next = module.binary(BinaryOp::Add, read, one, word).unwrap(); + let target = module.whole(counter).unwrap(); + module + .register(target, next, clock, edge, None, None) + .unwrap(); + } + let delay = module.constant(Constant::two_state(1u8, 8).unwrap()); + for clock in [cp, cn] { + let target = module.whole(clock).unwrap(); + let mut body = Vec::new(); + for ((value, mask), _, _) in WALK { + let level: ExprId = module.constant(Constant::four_state(value, mask, 1).unwrap()); + body.push(Statement::Delay { amount: delay }); + body.push(Statement::Assign { + target, + value: level, + }); + } + module.process(body).unwrap(); + } + module.finish() + } + + /// A process drives `d` through [`WALK`] and pulses `clk` after each + /// change; registers `c` and `c2` follow `d` on the rising edges of + /// `clk`. Event-control waits `@(posedge c)` and `@(negedge c)` and + /// registers on the posedges of `c` and the negedges of `c2` count the + /// edges of the register clock. + fn wait_design() -> FrontendArtifact { + let bit = ValueType::new(1, false, true).unwrap(); + let word = ValueType::new(8, false, true).unwrap(); + let mut module = ModuleBuilder::new("Top").unwrap(); + let clk = module.internal("clk", bit).unwrap(); + let d = module.internal("d", bit).unwrap(); + let c = module.internal("c", bit).unwrap(); + let c2 = module.internal("c2", bit).unwrap(); + let counters = ["wait_pos", "wait_neg", "ff_pos", "ff_neg"] + .map(|name| module.output(name, word).unwrap()); + for signal in [clk, d, c, c2] { + module + .set_initial(signal, Constant::two_state(0u8, 1).unwrap()) + .unwrap(); + } + for counter in counters { + module + .set_initial(counter, Constant::two_state(0u8, 8).unwrap()) + .unwrap(); + } + let d_expr = module.read(d).unwrap(); + for register in [c, c2] { + let target = module.whole(register).unwrap(); + module + .register(target, d_expr, clk, Edge::Posedge, None, None) + .unwrap(); + } + let one = module.constant(Constant::two_state(1u8, 8).unwrap()); + let increment = |module: &mut ModuleBuilder, counter| { + let read = module.read(counter).unwrap(); + let next = module.binary(BinaryOp::Add, read, one, word).unwrap(); + (module.whole(counter).unwrap(), next) + }; + let [wait_pos, wait_neg, ff_pos, ff_neg] = counters; + for (counter, clock, edge) in [(ff_pos, c, Edge::Posedge), (ff_neg, c2, Edge::Negedge)] { + let (target, next) = increment(&mut module, counter); + module + .register(target, next, clock, edge, None, None) + .unwrap(); + } + for (counter, edge) in [ + (wait_pos, EventEdge::Posedge), + (wait_neg, EventEdge::Negedge), + ] { + let (target, value) = increment(&mut module, counter); + module + .process(vec![Statement::Forever { + body: vec![ + Statement::WaitEvent { + terms: vec![EventTerm { signal: c, edge }], + }, + Statement::Assign { target, value }, + ], + }]) + .unwrap(); + } + let delay = module.constant(Constant::two_state(1u8, 8).unwrap()); + let high = module.constant(Constant::two_state(1u8, 1).unwrap()); + let low = module.constant(Constant::two_state(0u8, 1).unwrap()); + let d_target = module.whole(d).unwrap(); + let clk_target = module.whole(clk).unwrap(); + let mut body = Vec::new(); + for ((value, mask), _, _) in WALK { + let level = module.constant(Constant::four_state(value, mask, 1).unwrap()); + body.push(Statement::Assign { + target: d_target, + value: level, + }); + body.push(Statement::Delay { amount: delay }); + body.push(Statement::Assign { + target: clk_target, + value: high, + }); + body.push(Statement::Delay { amount: delay }); + body.push(Statement::Assign { + target: clk_target, + value: low, + }); + } + module.process(body).unwrap(); + module.finish() + } + + /// Event-control waits and flip-flop domains see the same Table 9-2 + /// edges of a register clock. + #[test] + fn waits_on_register_clocks_follow_table_9_2() { + fn check(mut sim: Simulation) { + for (step, (_, pos, neg)) in (0u64..).zip(WALK) { + let time = 2 * step + 1; + sim.run_until(time).unwrap(); + let counts = + ["wait_pos", "wait_neg", "ff_pos", "ff_neg"].map(|name| get(&mut sim, name)); + assert_eq!( + counts, + [pos, neg, pos, neg].map(BigUint::from), + "wait_pos, wait_neg, ff_pos, ff_neg at {time}" + ); + } + } + on_every_backend!(Simulator::from_frontend(wait_design()), check); + } + + #[test] + fn process_driven_clocks_follow_table_9_2() { + fn check(mut sim: Simulation) { + for (time, (_, pos, neg)) in (1..).zip(WALK) { + sim.run_until(time).unwrap(); + assert_eq!(get(&mut sim, "pos"), pos.into(), "posedges at {time}"); + assert_eq!(get(&mut sim, "neg"), neg.into(), "negedges at {time}"); + } + } + on_every_backend!(Simulator::from_frontend(process_design()), check); + } + + const REGISTER_CLOCK: &str = r#" +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + d : input logic, + pos: output logic<8>, + neg: output logic<8>, +) { + var c: logic; + always_ff (clk) { + c = d; + } + let cp: '_ clock = c; + let cn: '_ clock_negedge = c; + var p : logic<8>; + var n : logic<8>; + always_ff (cp, rst) { + if_reset { + p = 0; + } else { + p = p + 8'd1; + } + } + always_ff (cn, rst) { + if_reset { + n = 0; + } else { + n = n + 8'd1; + } + } + assign pos = p; + assign neg = n; +} +"#; + + /// A clock that is a register follows `d` through [`WALK`], one change + /// per rising edge of `clk`. `clk` starts at x, so its first rise, x to + /// 1, is a posedge too. + #[test] + fn register_clocks_follow_table_9_2() { + fn check(mut sim: Simulation) { + // x -> 0 asserts the reset. + sim.schedule("rst", 0, 0).unwrap(); + sim.schedule("rst", 1, 1).unwrap(); + set(&mut sim, "d", (0, 0)); + sim.add_clock("clk", 10, 5); + // The register leaves x for 0: a negedge. + sim.run_until(5).unwrap(); + assert_eq!(get(&mut sim, "pos"), 0u8.into()); + assert_eq!(get(&mut sim, "neg"), 1u8.into()); + for (time, (level, pos, neg)) in (15..).step_by(10).zip(WALK) { + set(&mut sim, "d", level); + sim.run_until(time).unwrap(); + assert_eq!(get(&mut sim, "pos"), pos.into(), "posedges at {time}"); + assert_eq!(get(&mut sim, "neg"), (neg + 1).into(), "negedges at {time}"); + } + } + on_every_backend!(Simulator::builder(REGISTER_CLOCK, "Top"), check); + } + + /// A clock computed combinationally from a register, `e ? a & b : 'z`, + /// with the register written whole so the clock changes once per edge. + #[test] + fn combinational_clocks_follow_table_9_2() { + const SOURCE: &str = r#" +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + d : input logic<3>, + pos: output logic<8>, + neg: output logic<8>, +) { + var r: logic<3>; + always_ff (clk) { + r = d; + } + let cp: '_ clock = if r[2] ? r[1] & r[0] : 1'bz; + let cn: '_ clock_negedge = if r[2] ? r[1] & r[0] : 1'bz; + var p : logic<8>; + var n : logic<8>; + always_ff (cp, rst) { + if_reset { + p = 0; + } else { + p = p + 8'd1; + } + } + always_ff (cn, rst) { + if_reset { + n = 0; + } else { + n = n + 8'd1; + } + } + assign pos = p; + assign neg = n; +} +"#; + /// `{e, a, b}` for each level of [`WALK`], as (value, mask). + const INPUTS: [(u8, u8); 12] = [ + (0b111, 0), + (0b100, 0), + (0b110, 0b001), // 1 & z + (0b110, 0), + (0b011, 0), // e = 0 + (0b111, 0), + (0b111, 0b010), // 1 & x + (0b111, 0), + (0b000, 0), // e = 0 + (0b111, 0b100), // e = x + (0b001, 0b010), // e = 0 + (0b101, 0), + ]; + fn check(mut sim: Simulation) { + sim.schedule("rst", 0, 0).unwrap(); + sim.schedule("rst", 1, 1).unwrap(); + set(&mut sim, "d", (0b101, 0)); + sim.add_clock("clk", 10, 5); + sim.run_until(5).unwrap(); + assert_eq!(get(&mut sim, "pos"), 0u8.into()); + assert_eq!(get(&mut sim, "neg"), 1u8.into()); + for (time, (input, (_, pos, neg))) in + (15..).step_by(10).zip(INPUTS.into_iter().zip(WALK)) + { + set(&mut sim, "d", input); + sim.run_until(time).unwrap(); + assert_eq!(get(&mut sim, "pos"), pos.into(), "posedges at {time}"); + assert_eq!(get(&mut sim, "neg"), (neg + 1).into(), "negedges at {time}"); + } + } + on_every_backend!(Simulator::builder(SOURCE, "Top"), check); + } + + /// Asynchronous resets that are registers. An edge to x or z runs the + /// register's clocked branch (+1), an edge to the active level clears + /// it, and every clear follows an increment. + #[test] + fn register_async_resets_follow_table_9_2() { + const SOURCE: &str = r#" +module Top ( + clk : input '_ clock, + k : input '_ clock, + clr : input logic, + dh : input logic, + dl : input logic, + hits_h: output logic<8>, + hits_l: output logic<8>, +) { + var qh: logic; + var ql: logic; + always_ff (clk) { + qh = dh; + ql = dl; + } + let rh: '_ reset_async_high = qh; + let rl: '_ reset_async_low = ql; + var h : logic<8>; + var l : logic<8>; + always_ff (k, rh) { + if_reset { + h = 0; + } else if clr { + h = 8'h80; + } else { + h = h + 8'h01; + } + } + always_ff (k, rl) { + if_reset { + l = 0; + } else if clr { + l = 8'h80; + } else { + l = l + 8'h01; + } + } + assign hits_h = h; + assign hits_l = l; +} +"#; + /// `rh` levels 1, 0, x, 1, x, 0, z, 1, z, x, z, 0 (`rl` has 0 and 1 + /// swapped), and the counter after each change. + const STEPS: [((u8, u8), u8); 12] = [ + ((1, 0), 0), + ((0, 0), 0), + ((1, 1), 1), + ((1, 0), 0), + ((1, 1), 0), + ((0, 0), 0), + ((0, 1), 1), + ((1, 0), 0), + ((0, 1), 0), + ((1, 1), 0), + ((0, 1), 0), + ((0, 0), 0), + ]; + fn check(mut sim: Simulation) { + set(&mut sim, "dh", (0, 0)); + set(&mut sim, "dl", (1, 0)); + set(&mut sim, "clr", (1, 0)); + sim.schedule("k", 0, 0).unwrap(); + sim.add_clock("clk", 10, 5); + // x -> 0 is no posedge of `rh`, x -> 1 no negedge of `rl`. + sim.schedule("k", 7, 1).unwrap(); + sim.run_until(7).unwrap(); + set(&mut sim, "clr", (0, 0)); + assert_eq!(get(&mut sim, "hits_h"), 0x80u8.into()); + assert_eq!(get(&mut sim, "hits_l"), 0x80u8.into()); + for (time, ((value, mask), hits)) in (15..).step_by(10).zip(STEPS) { + let low = if mask == 0 { value ^ 1 } else { value }; + set(&mut sim, "dh", (value, mask)); + set(&mut sim, "dl", (low, mask)); + sim.run_until(time).unwrap(); + assert_eq!(get(&mut sim, "hits_h"), hits.into(), "rh at {time}"); + assert_eq!(get(&mut sim, "hits_l"), hits.into(), "rl at {time}"); + } + } + on_every_backend!(Simulator::builder(SOURCE, "Top"), check); + } + + /// The edge baseline of a clock left at x survives a checkpoint: the + /// following rise, x to 1, is a posedge. + #[test] + fn unknown_edge_baselines_survive_checkpoints() { + fn check(mut sim: Simulation) { + sim.schedule("rst", 0, 0).unwrap(); + sim.schedule("rst", 1, 1).unwrap(); + set(&mut sim, "d", (1, 1)); + sim.add_clock("clk", 10, 5); + // The register leaves x for x: no edge. + sim.run_until(5).unwrap(); + assert_eq!(get(&mut sim, "pos"), 0u8.into()); + let saved = sim.checkpoint().unwrap(); + let state = sim.save_state().unwrap(); + set(&mut sim, "d", (1, 0)); + sim.run_until(15).unwrap(); + assert_eq!(get(&mut sim, "pos"), 1u8.into()); + sim.restore(&saved).unwrap(); + set(&mut sim, "d", (1, 0)); + sim.run_until(15).unwrap(); + assert_eq!(get(&mut sim, "pos"), 1u8.into(), "after a restore"); + sim.load_state(&state).unwrap(); + set(&mut sim, "d", (1, 0)); + 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); + } +} diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 80b636b6991..f924bbcab9a 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1347,8 +1347,12 @@ mod host { ))); } let descs = sim.build_vcd_descs(options.four_state); - let vcd_writer = crate::VcdWriter::new(path, &descs) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + let vcd_writer = crate::VcdWriter::new_with_time_precision( + path, + &descs, + sim.program.design.time_precision, + ) + .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; sim.vcd_writer = Some(vcd_writer); } let apply_initial_start = options.diagnostics.phase_timing.then(crate::timing::now); @@ -2332,8 +2336,12 @@ mod host { sim.diagnostics = options.diagnostics.clone(); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); - let vcd_writer = crate::VcdWriter::new(path, &descs) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + let vcd_writer = crate::VcdWriter::new_with_time_precision( + path, + &descs, + sim.program.design.time_precision, + ) + .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); @@ -2374,8 +2382,12 @@ mod host { sim.diagnostics = options.diagnostics.clone(); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); - let vcd_writer = crate::VcdWriter::new(path, &descs) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + let vcd_writer = crate::VcdWriter::new_with_time_precision( + path, + &descs, + sim.program.design.time_precision, + ) + .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); @@ -2420,8 +2432,12 @@ mod host { sim.diagnostics = options.diagnostics.clone(); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); - let vcd_writer = crate::VcdWriter::new(path, &descs) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + let vcd_writer = crate::VcdWriter::new_with_time_precision( + path, + &descs, + sim.program.design.time_precision, + ) + .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); @@ -2480,8 +2496,12 @@ mod host { sim.diagnostics = options.diagnostics.clone(); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); - let vcd_writer = crate::VcdWriter::new(path, &descs) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + let vcd_writer = crate::VcdWriter::new_with_time_precision( + path, + &descs, + sim.program.design.time_precision, + ) + .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); @@ -2675,8 +2695,12 @@ mod host { sim.diagnostics = options.diagnostics.clone(); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); - let vcd_writer = crate::VcdWriter::new(path, &descs) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + let vcd_writer = crate::VcdWriter::new_with_time_precision( + path, + &descs, + sim.program.design.time_precision, + ) + .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); @@ -3031,8 +3055,12 @@ mod host { sim.diagnostics = options.diagnostics.clone(); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); - let vcd_writer = crate::VcdWriter::new(path, &descs) - .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; + let vcd_writer = crate::VcdWriter::new_with_time_precision( + path, + &descs, + sim.program.design.time_precision, + ) + .map_err(|_| SimulatorError::from(crate::RuntimeErrorCode::InternalError))?; sim.vcd_writer = Some(vcd_writer); } sim.apply_initial_values(); diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index f31475354ac..6c281ce7961 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -384,6 +384,7 @@ impl Simulator { .map(|(event, count)| (named(event), *count)) .collect(), high_events: parts.high_events.into_iter().map(event_path).collect(), + unknown_events: parts.unknown_events.into_iter().map(event_path).collect(), processes, } } @@ -750,6 +751,7 @@ impl Simulator { .iter() .map(|(name, _)| name) .chain(&record.high_events) + .chain(&record.unknown_events) .chain(scheduled.clone().map(|event| &event.event)) .filter(|name| !events.contains_key(*name)) .chain( @@ -794,6 +796,11 @@ impl Simulator { .map(|(event, count)| (resolve(event), *count)) .collect(), high_events: record.high_events.iter().map(|name| events[name]).collect(), + unknown_events: record + .unknown_events + .iter() + .map(|name| events[name]) + .collect(), process_wakeups, process_state, host_pending: record.processes.host_pending, diff --git a/crates/celox/tests/both_clock_edges.rs b/crates/celox/tests/both_clock_edges.rs index 2e14eda8b01..f662b5924fd 100644 --- a/crates/celox/tests/both_clock_edges.rs +++ b/crates/celox/tests/both_clock_edges.rs @@ -166,6 +166,7 @@ fn a_reset_at_both_edges() { endmodule"; for four_state in [false, true] { let mut sim = build(source, four_state); + let initial_low = get(&mut sim, "low"); let mut observed = Vec::new(); let mut time = 0; let mut edge = |sim: &mut Simulation, port: &str, level: u64| { @@ -189,12 +190,14 @@ fn a_reset_at_both_edges() { observed.push(edge(&mut sim, "rst", 1)); observed.push(edge(&mut sim, "clk", 1)); // Before `rst` first falls, `low` is unknown, and stays unknown when - // incremented. + // incremented. In four-state, `rst` rises from its initial unknown + // level, a posedge but no negedge (IEEE 1800-2023 Table 9-2), so + // `low` keeps its initial value until the first clock edge. let low = |count: u64| if four_state { 0xff } else { count }; assert_eq!( observed, vec![ - (0, low(0)), + (0, if four_state { initial_low } else { 0 }), (0, low(1)), (0, low(2)), (0, 0), diff --git a/crates/celox/tests/four_state.rs b/crates/celox/tests/four_state.rs index e0111a4e7f3..fd59bc7a47d 100644 --- a/crates/celox/tests/four_state.rs +++ b/crates/celox/tests/four_state.rs @@ -503,4 +503,25 @@ fn test_x_literal_encoding(sim) { @case "four_state::test_x_literal_encoding"; } +// ========================================================================== +// Edges of internally driven clocks and resets (IEEE 1800-2023 Table 9-2) +// ========================================================================== + +fn test_four_state_register_clock_edges_follow_table_9_2(sim) { + // Veryl 0.22.0's simulator misses edges through x and z, such as x -> 0. + @ignore_on(veryl); + @case "four_state::test_four_state_register_clock_edges_follow_table_9_2"; +} + +fn test_four_state_comb_clock_edges_follow_table_9_2(sim) { + // Veryl 0.22.0's simulator misses edges through x and z, such as x -> 0. + @ignore_on(veryl); + @case "four_state::test_four_state_comb_clock_edges_follow_table_9_2"; +} + +fn test_four_state_internal_async_reset_edges_follow_table_9_2(sim) { + // Veryl 0.22.0's simulator misses edges through x and z, such as x -> 0. + @ignore_on(veryl); + @case "four_state::test_four_state_internal_async_reset_edges_follow_table_9_2"; +} } diff --git a/crates/celox/tests/four_state_explicit_edges.rs b/crates/celox/tests/four_state_explicit_edges.rs new file mode 100644 index 00000000000..7bb97553b85 --- /dev/null +++ b/crates/celox/tests/four_state_explicit_edges.rs @@ -0,0 +1,136 @@ +#![cfg(feature = "systemverilog")] +//! Explicit edges of four-state clocks that are x or z follow IEEE +//! 1800-2023 9.4.2, Table 9-2: a rising edge from x or z is a posedge, a +//! falling one a negedge, and a gated clock is judged from the clock's real +//! level before the edge. On plain events, gated clocks and register +//! clocks, on every backend. + +use celox::{BigUint, Edge, SimBackend, Simulator}; + +/// `clkp` and `clkn` clock plain posedge and negedge counters; `clkg` gates +/// `gc = clkg & en`; `clkd` clocks a register `r` whose posedges are +/// counted. +const SOURCE: &str = "module Top(input logic clkp, input logic clkn, input logic clkg, + input logic clkd, input logic en, input logic d, + output logic [7:0] pos, output logic [7:0] neg, output logic [7:0] gpos, + output logic [7:0] dpos); + logic [7:0] p = 8'd0; + logic [7:0] n = 8'd0; + logic [7:0] g = 8'd0; + logic [7:0] t = 8'd0; + logic [7:0] q = 8'd0; + logic r = 1'b0; + logic gc; + assign gc = clkg & en; + always_ff @(posedge clkp) p <= p + 8'd1; + always_ff @(negedge clkn) n <= n + 8'd1; + always_ff @(posedge clkg) t <= t + 8'd1; + always_ff @(posedge gc) g <= g + 8'd1; + always_ff @(posedge clkd) r <= d; + always_ff @(posedge r) q <= q + 8'd1; + assign pos = p; + assign neg = n; + assign gpos = g; + assign dpos = q; +endmodule"; + +const X: (u8, u8) = (1, 1); +const Z: (u8, u8) = (0, 1); +const ZERO: (u8, u8) = (0, 0); +const ONE: (u8, u8) = (1, 0); + +fn set(sim: &mut Simulator, name: &str, (value, mask): (u8, u8)) { + let signal = sim.signal(name); + sim.modify(|io| io.set_four_state(signal, BigUint::from(value), BigUint::from(mask))) + .unwrap(); +} + +fn get(sim: &mut Simulator, name: &str) -> u64 { + let signal = sim.signal(name); + sim.get(signal).try_into().unwrap() +} + +fn edge(sim: &mut Simulator, event: &str, edge: Edge) { + let event = sim.event(event); + sim.edge(event, edge).unwrap(); +} + +fn check(mut sim: Simulator, backend: &str) { + let counts = |sim: &mut Simulator| ["pos", "neg", "gpos", "dpos"].map(|name| get(sim, name)); + + // Plain events: x -> 1 is a posedge, z -> 0 a negedge, and the + // inactive x -> 0 runs nothing. + set(&mut sim, "clkp", X); + edge(&mut sim, "clkp", Edge::Rising); + set(&mut sim, "clkn", Z); + edge(&mut sim, "clkn", Edge::Falling); + assert_eq!(counts(&mut sim), [1, 1, 0, 0], "{backend}: plain from x/z"); + set(&mut sim, "clkp", X); + edge(&mut sim, "clkp", Edge::Falling); + set(&mut sim, "clkn", X); + edge(&mut sim, "clkn", Edge::Rising); + assert_eq!(counts(&mut sim), [1, 1, 0, 0], "{backend}: inactive from x"); + sim.cycle(sim.event("clkp")).unwrap(); + assert_eq!(counts(&mut sim), [2, 1, 0, 0], "{backend}: cycle after x"); + + // A gated clock: `x & 1` -> `1 & 1` rises; `x & x` -> `1 & x` stays x. + set(&mut sim, "en", ONE); + set(&mut sim, "clkg", X); + edge(&mut sim, "clkg", Edge::Rising); + assert_eq!(counts(&mut sim)[2], 1, "{backend}: gated x -> 1"); + set(&mut sim, "en", X); + set(&mut sim, "clkg", X); + edge(&mut sim, "clkg", Edge::Rising); + assert_eq!(counts(&mut sim)[2], 1, "{backend}: gated x -> x is no edge"); + // `z & 1` is x: z -> 1 of the clock is x -> 1 of the gated clock. + set(&mut sim, "en", ONE); + set(&mut sim, "clkg", Z); + edge(&mut sim, "clkg", Edge::Rising); + assert_eq!(counts(&mut sim)[2], 2, "{backend}: gated z -> 1"); + // `0 & 1` -> `1 & 1`, with the clock coming from 0. + edge(&mut sim, "clkg", Edge::Falling); + edge(&mut sim, "clkg", Edge::Rising); + assert_eq!(counts(&mut sim)[2], 3, "{backend}: gated 0 -> 1"); + + // A register clock: `r` goes 0 -> x -> 1, two posedges, through edges + // of a clock that starts at z. + set(&mut sim, "clkd", Z); + set(&mut sim, "d", X); + edge(&mut sim, "clkd", Edge::Rising); + assert_eq!(counts(&mut sim)[3], 1, "{backend}: register 0 -> x"); + set(&mut sim, "d", ONE); + edge(&mut sim, "clkd", Edge::Falling); + edge(&mut sim, "clkd", Edge::Rising); + assert_eq!(counts(&mut sim)[3], 2, "{backend}: register x -> 1"); + set(&mut sim, "d", ZERO); + sim.cycle(sim.event("clkd")).unwrap(); + assert_eq!(counts(&mut sim)[3], 2, "{backend}: register 1 -> 0"); + + // Coincident edges from x judge the gated clock from x too. + set(&mut sim, "en", X); + set(&mut sim, "clkg", X); + set(&mut sim, "clkp", X); + let moves = [ + (sim.event("clkg"), Edge::Rising), + (sim.event("clkp"), Edge::Rising), + ]; + sim.edges(&moves).unwrap(); + assert_eq!(counts(&mut sim)[..3], [3, 1, 3], "{backend}: coincident"); +} + +#[test] +fn explicit_edges_from_unknown_levels_follow_table_9_2() { + let build = || { + Simulator::from_sv_sources( + vec![(SOURCE, std::path::Path::new("four_state_explicit_edges.sv"))], + "Top", + ) + .four_state(true) + }; + check(build().build_interpreter().unwrap(), "interp"); + check(build().build_cranelift().unwrap(), "cranelift"); + check(build().build_wasm().unwrap(), "wasm"); + check(build().build_tiered().unwrap(), "tiered"); + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + check(build().build_native().unwrap(), "native"); +} diff --git a/crates/celox/tests/frontends/systemverilog/edges.rs b/crates/celox/tests/frontends/systemverilog/edges.rs new file mode 100644 index 00000000000..893e189ed7c --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/edges.rs @@ -0,0 +1,24 @@ +//! Edges of clocks and resets the design drives itself, in four-state +//! simulation (IEEE 1800-2023 9.4.2, Table 9-2). + +sv_backends! { + fn register_clock_edges_follow_table_9_2(sim) { + @case "edges::register_clock_edges_follow_table_9_2"; + } + + fn comb_clock_edges_follow_table_9_2(sim) { + @case "edges::comb_clock_edges_follow_table_9_2"; + } + + fn internal_async_reset_edges_follow_table_9_2(sim) { + @case "edges::internal_async_reset_edges_follow_table_9_2"; + } + + fn gated_clock_edges_from_unknown_levels(sim) { + @case "edges::gated_clock_edges_from_unknown_levels"; + } + + fn register_clock_two_state_edges(sim) { + @case "edges::register_clock_two_state_edges"; + } +} diff --git a/crates/celox/tests/frontends/systemverilog/hierarchy.rs b/crates/celox/tests/frontends/systemverilog/hierarchy.rs index 5367c930e02..1c98894e89e 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchy.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchy.rs @@ -1,6 +1,8 @@ use super::*; sv_backends! { + fn parameter_patterns_keep_original_declarations_and_isolated_bindings(sim) { @case "hierarchy::parameter_patterns_keep_original_declarations_and_isolated_bindings"; } + fn parameter_patterns_preserve_enclosing_expressions(sim) { @case "hierarchy::parameter_patterns_preserve_enclosing_expressions"; } fn widens_small_parameters_preserving_four_state_bits(sim) { @case "hierarchy::widens_small_parameters_preserving_four_state_bits"; } diff --git a/crates/celox/tests/frontends/systemverilog/suite.rs b/crates/celox/tests/frontends/systemverilog/suite.rs index f4126b657a6..e5d20fd137c 100644 --- a/crates/celox/tests/frontends/systemverilog/suite.rs +++ b/crates/celox/tests/frontends/systemverilog/suite.rs @@ -7,7 +7,7 @@ struct CeloxBackend(Simulator); /// A timed case: the design's own processes and clocks run in a /// [`Simulation`]. A host write is settled at the current time by the next -/// run operation. +/// run operation, read, eval or output collection. struct TimedBackend { sim: Simulation, /// Runtime events not yet taken as output. @@ -60,6 +60,20 @@ impl TimedBackend { } } + /// Settle host writes and the work they wake at the current time, as + /// the reference simulators do before a read, then capture events. + fn settled(&mut self, operation: &str) -> Result<()> { + let finished = self.finished; + if !finished { + self.sim.run_until(self.sim.time())?; + } + self.capture_events()?; + if !finished && self.finished { + return Err(format!("the design finished during {operation}").into()); + } + Ok(()) + } + /// Capture events after an operation that does not advance time. fn checked(&mut self, operation: &str) -> Result<()> { let finished = self.finished; @@ -104,14 +118,14 @@ impl Backend for TimedBackend { } fn read(&mut self, path: &SignalPath) -> Result<(BigUint, BigUint)> { - self.checked("a read")?; + self.settled("a read")?; let signal = self.signal(path); Ok(self.sim.get_four_state(signal)) } fn eval_comb(&mut self) -> Result<()> { self.sim.eval_comb()?; - self.checked("eval") + self.settled("eval") } fn tick(&mut self, _event: &str) -> Result<()> { @@ -119,7 +133,7 @@ impl Backend for TimedBackend { } fn take_output(&mut self) -> Result> { - self.checked("output collection")?; + self.settled("output collection")?; collect_output(std::mem::take(&mut self.events)) } diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 291bb088484..27dfb7c846c 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -49,112 +49,86 @@ macro_rules! timed_cases { } timed_cases! { - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn delays_resume_initial_blocks_at_later_times = "timing::delays_resume_initial_blocks_at_later_times"; #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn always_with_a_delay_generates_a_clock = "timing::always_with_a_delay_generates_a_clock"; #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn edge_waits_resume_before_the_registers_of_that_edge_update = "timing::edge_waits_resume_before_the_registers_of_that_edge_update"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn any_change_waits_wake_on_every_value_change = "timing::any_change_waits_wake_on_every_value_change"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn wait_statements_block_until_their_condition_holds = "timing::wait_statements_block_until_their_condition_holds"; #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn level_sensitive_always_runs_as_a_process = "timing::level_sensitive_always_runs_as_a_process"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn processes_wake_each_other_at_the_same_time = "timing::processes_wake_each_other_at_the_same_time"; #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn tasks_with_timing_controls_run_in_processes = "timing::tasks_with_timing_controls_run_in_processes"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn edge_waits_see_the_signals_the_script_drives = "timing::edge_waits_see_the_signals_the_script_drives"; #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn finish_in_an_always_process_ends_the_simulation = "timing::finish_in_an_always_process_ends_the_simulation"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn waiting_processes_do_not_keep_an_idle_simulation_running = "timing::waiting_processes_do_not_keep_an_idle_simulation_running"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "flip-flop domains miss edges to and from z on a four-state clock (#1472)"] fn four_state_edges_count_transitions_through_unknown = "timing::four_state_edges_count_transitions_through_unknown"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn unknown_delays_and_conditions_count_as_zero_and_false = "timing::unknown_delays_and_conditions_count_as_zero_and_false"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn direct_reads_settle_waiting_processes = "timing::direct_reads_settle_waiting_processes"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn output_reads_settle_waiting_processes = "timing::output_reads_settle_waiting_processes"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn run_until_drains_target_time_before_later_writes = "timing::run_until_drains_target_time_before_later_writes"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn repeated_settles_do_not_advance_design_time = "timing::repeated_settles_do_not_advance_design_time"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn run_to_finish_has_no_simulated_time_deadline = "timing::run_to_finish_has_no_simulated_time_deadline"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "blocking stores of an edge-triggered always are not visible before the inactive region (#1123)"] fn blocking_ff_stores_are_visible_before_inactive_work = "timing::blocking_ff_stores_are_visible_before_inactive_work"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn nonblocking_ff_stores_remain_pending_during_inactive_work = "timing::nonblocking_ff_stores_remain_pending_during_inactive_work"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "blocking stores of an edge-triggered always are not visible before the inactive region (#1123)"] fn mixed_ff_stores_keep_their_active_and_nba_values = "timing::mixed_ff_stores_keep_their_active_and_nba_values"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn printed_finish_notice_is_design_output = "timing::printed_finish_notice_is_design_output"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn combinational_finish_ends_timed_execution = "timing::combinational_finish_ends_timed_execution"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn inactive_time_directives_do_not_change_scheduler_units = "timing::inactive_time_directives_do_not_change_scheduler_units"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn blocking_concatenation_publishes_one_event_update = "timing::blocking_concatenation_publishes_one_event_update"; #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn finite_active_feedback_preserves_convergence = "timing::finite_active_feedback_preserves_convergence"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn pure_function_rhs_preserves_distinct_write_times = "timing::pure_function_rhs_preserves_distinct_write_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn conditional_writes_preserve_distinct_activation_times = "timing::conditional_writes_preserve_distinct_activation_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn case_writes_preserve_distinct_activation_times = "timing::case_writes_preserve_distinct_activation_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn constant_repeat_writes_preserve_distinct_activation_times = "timing::constant_repeat_writes_preserve_distinct_activation_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn separate_comb_assignments_preserve_selected_dependencies = "timing::separate_comb_assignments_preserve_selected_dependencies"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn constant_for_writes_preserve_distinct_activation_times = "timing::constant_for_writes_preserve_distinct_activation_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn untimed_tasks_preserve_distinct_activation_times = "timing::untimed_tasks_preserve_distinct_activation_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn untimed_task_copyback_preserves_distinct_activation_times = "timing::untimed_task_copyback_preserves_distinct_activation_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn statically_satisfied_waits_preserve_distinct_activation_times = "timing::statically_satisfied_waits_preserve_distinct_activation_times"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn nba_woken_waiters_sample_before_continuations = "timing::nba_woken_waiters_sample_before_continuations"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn negative_repeat_counts_do_not_run_the_body = "timing::negative_repeat_counts_do_not_run_the_body"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn blocking_ff_woken_waiters_sample_before_continuations = "timing::blocking_ff_woken_waiters_sample_before_continuations"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn direct_blocking_ff_woken_waiters_sample_before_continuations = "timing::direct_blocking_ff_woken_waiters_sample_before_continuations"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn constant_variable_initializers_do_not_invent_clock_edges = "timing::constant_variable_initializers_do_not_invent_clock_edges"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn repeated_active_edges_share_one_nba_batch = "timing::repeated_active_edges_share_one_nba_batch"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] + #[ignore = "the SV frontend lowers only variables as event expressions (#1123)"] fn false_wait_preserves_separate_hierarchical_write_times = "timing::false_wait_preserves_separate_hierarchical_write_times"; #[ignore = "the SV analyzer rejects plain always processes (#431)"] fn always_timed_task_without_inline_timing_executes = "timing::always_timed_task_without_inline_timing_executes"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn constant_comb_if_discards_unreachable_pulse_branch = "timing::constant_comb_if_discards_unreachable_pulse_branch"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn constant_child_ff_case_discards_unreachable_pulse_arm = "timing::constant_child_ff_case_discards_unreachable_pulse_arm"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn constant_child_loop_exit_keeps_one_write = "timing::constant_child_loop_exit_keeps_one_write"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn constant_child_case_exit_keeps_one_write = "timing::constant_child_case_exit_keeps_one_write"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn four_state_child_if_keeps_one_write = "timing::four_state_child_if_keeps_one_write"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn selected_child_dependency_ignores_unreachable_reads = "timing::selected_child_dependency_ignores_unreachable_reads"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn selected_child_loop_exit_ignores_unreachable_suffix = "timing::selected_child_loop_exit_ignores_unreachable_suffix"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn finite_process_loop_preserves_continuation_values = "timing::finite_process_loop_preserves_continuation_values"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn zero_trip_child_dependencies_ignore_body_and_step = "timing::zero_trip_child_dependencies_ignore_body_and_step"; - #[ignore = "the SV analyzer rejects procedural timing controls (#88)"] fn cross_file_package_initializers_keep_static_clock_baseline = "timing::cross_file_package_initializers_keep_static_clock_baseline"; + fn edge_waits_wake_on_rising_and_falling_edges = "timing::edge_waits_wake_on_rising_and_falling_edges"; + fn min_typ_max_delays_wait_the_typical_value = "timing::min_typ_max_delays_wait_the_typical_value"; + fn long_process_loops_finish_within_one_time_slot = "timing::long_process_loops_finish_within_one_time_slot"; fn initial_blocks_run_at_time_zero = "timing::initial_blocks_run_at_time_zero"; fn host_edges_after_time_zero_clock_flip_flops = "timing::host_edges_after_time_zero_clock_flip_flops"; } diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index a033aa691ff..51d09dd85f4 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -100,6 +100,8 @@ macro_rules! sv_backends { #[path = "frontends/systemverilog/always_comb.rs"] mod always_comb; +#[path = "frontends/systemverilog/edges.rs"] +mod edges; #[path = "frontends/systemverilog/generate.rs"] mod generate; #[path = "frontends/systemverilog/hierarchy.rs"] diff --git a/crates/celox/tests/time_precision.rs b/crates/celox/tests/time_precision.rs new file mode 100644 index 00000000000..15280c2b3d8 --- /dev/null +++ b/crates/celox/tests/time_precision.rs @@ -0,0 +1,127 @@ +#![cfg(feature = "systemverilog")] + +use std::path::Path; + +use celox::{SimBackend, Simulator, SimulatorBuilder}; + +fn check_vcd(mut sim: Simulator, path: &Path, expected: &str) { + let signal = sim.signal("y"); + sim.modify(|io| io.set(signal, 1u8)).unwrap(); + sim.dump(123); + sim.flush_vcd().unwrap(); + let first = std::fs::read_to_string(path).unwrap(); + assert!( + first.contains(&format!("$timescale {expected} $end")), + "{first}" + ); + assert!( + first.contains("#123\n"), + "timestamps must remain global ticks" + ); + let next = path.with_extension("next.vcd"); + sim.switch_vcd(&next).unwrap(); + sim.dump(130); + sim.flush_vcd().unwrap(); + assert!( + std::fs::read_to_string(next) + .unwrap() + .contains(&format!("$timescale {expected} $end")) + ); +} + +fn check_backends<'source>( + build: impl Fn(&Path) -> SimulatorBuilder<'source, Simulator>, + expected: &str, +) { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("wave.vcd"); + check_vcd(build(&path).build_native().unwrap(), &path, expected); + check_vcd(build(&path).build_cranelift().unwrap(), &path, expected); + check_vcd(build(&path).build_wasm().unwrap(), &path, expected); + check_vcd(build(&path).build_interpreter().unwrap(), &path, expected); + check_vcd(build(&path).build_tiered().unwrap(), &path, expected); + check_vcd( + build(&path) + .threads(4) + .parallel_partition(celox::ParallelPartition::Always) + .build_native() + .unwrap(), + &path, + expected, + ); + check_vcd( + build(&path) + .threads(4) + .parallel_partition(celox::ParallelPartition::Always) + .build_cranelift() + .unwrap(), + &path, + expected, + ); +} + +#[test] +fn sv_waveforms_use_global_precision_across_backends() { + for (declarations, expected) in [ + ("", "1ps"), + ("timeunit 1ns; timeprecision 1fs;", "1fs"), + ("timeunit 1us; timeprecision 100ns;", "100ns"), + ] { + let source = format!("module Top(output logic y); {declarations} endmodule"); + check_backends( + |path| { + Simulator::from_sv_sources(vec![(&source, Path::new("top.sv"))], "Top").vcd(path) + }, + expected, + ); + } +} + +#[test] +fn package_precision_is_retained_by_native_images() { + let source = "package P; timeunit 1ns; timeprecision 10fs; endpackage + module Top(output logic y); timeunit 1ns; timeprecision 1ps; endmodule"; + let build = |path: &Path| { + Simulator::from_sv_sources(vec![(source, Path::new("packages.sv"))], "Top").vcd(path) + }; + check_backends(build, "10fs"); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("image.vcd"); + let image = build(&path).compile_native().unwrap().into_program_image(); + let image = + celox::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + assert_eq!(image.time_precision().exponent(), -14); + let sim = Simulator::from_sources(Vec::new(), "Top") + .vcd(&path) + .build_native_from_image(image) + .unwrap(); + check_vcd(sim, &path, "10fs"); +} + +#[test] +fn veryl_waveforms_use_the_default_picosecond_tick() { + let source = "module Top(y: output logic) {}"; + check_backends(|path| Simulator::builder(source, "Top").vcd(path), "1ps"); +} + +#[test] +fn mixed_designs_keep_sv_precision_through_the_veryl_frontend() { + let veryl = "module Top(y: output logic) { inst child: $sv::Child (y); }"; + for (precision, expected) in [("1fs", "1fs"), ("100ns", "100ns")] { + let sv = format!( + "module Child(output logic y); timeunit 1us; timeprecision {precision}; assign y = 1; endmodule" + ); + check_backends( + |path| { + Simulator::from_mixed_sources( + vec![(veryl, Path::new("top.veryl"))], + vec![(&sv, Path::new("child.sv"))], + "Top", + ) + .vcd(path) + }, + expected, + ); + } +} diff --git a/docs/guide/writing-tests.md b/docs/guide/writing-tests.md index 986ac088860..ea59203ad16 100644 --- a/docs/guide/writing-tests.md +++ b/docs/guide/writing-tests.md @@ -100,6 +100,15 @@ and a falling one. ## Time-Based Simulation +Simulation timestamps and clock periods count global-precision ticks. Veryl +uses 1ps per tick. SystemVerilog uses the design's global time precision +(default 1ps). VCD headers and VPI time properties queried with a NULL handle +use that global precision. VPI queries on a module or its signals return the +module's own time unit and precision. +Existing Veryl VCD exports now declare 1ps instead of 1ns; their numeric +timestamps are unchanged. Native images compiled before this change must be +recompiled for the updated container format. + `Simulation` manages clock generation for you. This is the natural choice for sequential logic with clocked flip-flops. ```typescript diff --git a/docs/ja/guide/writing-tests.md b/docs/ja/guide/writing-tests.md index 08e05c0c2c2..23152ebf14b 100644 --- a/docs/ja/guide/writing-tests.md +++ b/docs/ja/guide/writing-tests.md @@ -61,6 +61,15 @@ module Reg ( ## タイムベースシミュレーション +時刻やクロック周期は global precision の tick 数です。Veryl は 1 tick = 1ps、 +SystemVerilog は設計の global time precision(既定は 1ps)を使用します。 +VCD のヘッダーと NULL ハンドルで問い合わせた VPI の時刻プロパティは、 +この全体の精度を示します。モジュールや信号のハンドルを指定した VPI の問い合わせは、 +そのモジュール自身の時間単位と精度を返します。 +Veryl の既存 VCD 出力は数値のタイムスタンプを保ったまま、宣言を 1ns から +1ps に変更します。ネイティブイメージの形式も更新するため、既存イメージは +再コンパイルしてください。 + `Simulation` はクロック生成を自動的に管理します。クロック付きフリップフロップを持つ順序回路に適しています。 ```typescript diff --git a/packages/celox/src/simulation.test.ts b/packages/celox/src/simulation.test.ts index 5432fcf232e..9e0d355822b 100644 --- a/packages/celox/src/simulation.test.ts +++ b/packages/celox/src/simulation.test.ts @@ -35,12 +35,19 @@ function createMockNative(opts?: { resetTypeKind?: string; associatedClock?: string; emptyEventQueue?: boolean; + /** Four-state `clk` that starts at x; its mask plane is at offset 7. */ + unknownClock?: boolean; }): { create: NativeCreateSimulationFn; handle: NativeSimulationHandle; buffer: SharedArrayBuffer; } { const buffer = new SharedArrayBuffer(64); + if (opts?.unknownClock) { + const view = new DataView(buffer); + view.setUint8(6, 1); + view.setUint8(7, 1); + } let currentTime = 0; let nextScheduledTime: number | null = opts?.emptyEventQueue ? null : 5; const processNextEvent = (): number | null => { @@ -49,8 +56,14 @@ function createMockNative(opts?: { nextScheduledTime += 5; const view = new DataView(buffer); view.setUint8(4, view.getUint8(2)); - // Toggle clock (offset 6) on each step to simulate half-period=5 - view.setUint8(6, view.getUint8(6) === 0 ? 1 : 0); + // Toggle clock (offset 6) on each step to simulate half-period=5. An + // unknown clock rises to 1 first. + if (opts?.unknownClock && view.getUint8(7) !== 0) { + view.setUint8(7, 0); + view.setUint8(6, 1); + } else { + view.setUint8(6, view.getUint8(6) === 0 ? 1 : 0); + } return currentTime; }; @@ -99,7 +112,7 @@ function createMockNative(opts?: { offset: 6, width: 1, byteSize: 1, - is4state: false, + is4state: opts?.unknownClock ?? false, direction: "input", typeKind: "clock", }, @@ -583,6 +596,19 @@ describe("Simulation", () => { expect(t).toBe(25); }); + test("waitForCycles: x -> 1 is a rising edge (IEEE 1800-2023 Table 9-2)", () => { + const mock = createMockNative({ unknownClock: true }); + const sim = Simulation.create(TopModule, { + __nativeCreate: mock.create, + }); + + sim.addClock("clk", { period: 10 }); + const t = sim.waitForCycles("clk", 3); + // clk: x→1→0→1→0→1 (5 steps for 3 rising edges) + expect(mock.handle.step).toHaveBeenCalledTimes(5); + expect(t).toBe(25); + }); + test("waitForCycles: throws without addClock", () => { const mock = createMockNative(); const sim = Simulation.create(TopModule, { diff --git a/packages/celox/src/simulation.ts b/packages/celox/src/simulation.ts index 454a9e31565..56fd3e998f1 100644 --- a/packages/celox/src/simulation.ts +++ b/packages/celox/src/simulation.ts @@ -556,8 +556,10 @@ export class Simulation

> { /** * Wait for `count` rising edges of the given clock. * - * Detects actual 0→1 transitions by reading the clock signal directly - * from the shared buffer (clock ports are excluded from the DUT proxy). + * Detects actual posedges by reading the clock signal directly from the + * shared buffer (clock ports are excluded from the DUT proxy). In a + * four-state simulation, a change from x or z to 1 and from 0 to x or z + * is a posedge too (IEEE 1800-2023 Table 9-2). * The clock must have been registered via `addClock`. * * @returns The simulation time after the edges are observed. @@ -579,12 +581,20 @@ export class Simulation

> { throw new Error(`No layout entry for clock '${clock}'.`); } const view = new DataView(this._buffer); - const readClk = () => view.getUint8(sig.offset); + // The level of the clock's LSB: 0, 1, or 2 plus the value bit for x + // and z, whose mask plane follows the value plane. + const maskOffset = sig.is4state ? sig.offset + sig.byteSize : -1; + const readClk = () => { + const value = view.getUint8(sig.offset) & 1; + return maskOffset < 0 + ? value + : value | ((view.getUint8(maskOffset) & 1) << 1); + }; let prev = readClk(); let remaining = count; return this.waitUntil(() => { const curr = readClk(); - if (prev === 0 && curr !== 0) remaining--; + if (prev !== 1 && curr !== 0 && (prev & curr & 2) === 0) remaining--; prev = curr; return remaining <= 0; }, opts); diff --git a/packages/celox/src/simulator-edges-addon.test.ts b/packages/celox/src/simulator-edges-addon.test.ts index 553bbe1df41..070265934d8 100644 --- a/packages/celox/src/simulator-edges-addon.test.ts +++ b/packages/celox/src/simulator-edges-addon.test.ts @@ -1,6 +1,7 @@ import { describe, expect, test } from "vitest"; import { Simulation } from "./simulation.js"; import { Simulator } from "./simulator.js"; +import { type FourStateSignalValue, X } from "./types.js"; const COUNTERS = ` module Top ( @@ -199,4 +200,50 @@ module Top ( sim.dispose(); } }); + + test("edges of a four-state clock follow IEEE 1800-2023 Table 9-2 from x", () => { + const source = ` +module Top ( + clk: input '_ clock, + rst: input '_ reset_async_low, + en: input logic, + rising: output logic<8>, + gated_rising: output logic<8>, +) { + var r: logic<8>; + var g: logic<8>; + always_ff (clk, rst) { if_reset { r = 0; } else { r = r + 8'd1; } } + let gated: '_ clock = clk & en; + always_ff (gated, rst) { if_reset { g = 0; } else { g = g + 8'd1; } } + assign rising = r; + assign gated_rising = g; +} +`; + type Ports = { + get en(): bigint; + set en(value: FourStateSignalValue); + readonly rising: bigint; + readonly gated_rising: bigint; + }; + const sim = Simulator.fromSource(source, "Top", { + fourState: true, + }); + try { + const clk = sim.event("clk"); + const counters = () => [sim.dut.rising, sim.dut.gated_rising]; + reset(sim); + expect(counters()).toEqual([0n, 0n]); + // The clock rises from x: a posedge of its own domain, while + // `x & x` stays x and the gated clock has no edge. + sim.dut.en = X; + sim.posedge(clk); + expect(counters()).toEqual([1n, 0n]); + sim.negedge(clk); + sim.dut.en = 1n; + sim.posedge(clk); + expect(counters()).toEqual([2n, 1n]); + } finally { + sim.dispose(); + } + }); }); diff --git a/packages/celox/src/wasm-edges.test.ts b/packages/celox/src/wasm-edges.test.ts index 3a1d25270a2..e82a48d3c38 100644 --- a/packages/celox/src/wasm-edges.test.ts +++ b/packages/celox/src/wasm-edges.test.ts @@ -3,7 +3,7 @@ import { createWasmSimulatorBridge, type RawWasmSimulatorHandle, } from "./wasm-bridge.js"; -import type { EdgePlans } from "./wasm-edges.js"; +import { type EdgePlans, WasmEdgeRunner } from "./wasm-edges.js"; // Memory map of a small design driven by hand-written WASM modules: // `gated = clk & en`, `inverted = ~clk`, and one counter per domain. @@ -187,3 +187,93 @@ test("edges of a clock combinational logic does not read keep it settled", () => expect(handle.edges?.([1], [true], true)).toBe(true); expect(sharedMemory[GATED_COUNT]).toBe(2); }); + +test("four-state edges judge a gated clock from x and z (IEEE 1800-2023 Table 9-2)", () => { + // Value bytes with their unknown masks in the following byte. + const clk = { offset: 0, width: 1 }; + const en = { offset: 2, width: 1 }; + const gated = { offset: 4, width: 1 }; + const COUNT = 8; + const plans: EdgePlans = { + fourState: true, + events: { + clk: { + signal: clk, + edge: "posedge", + combRead: true, + domains: [], + gated: [{ event: "gated", signal: gated, edge: "posedge" }], + }, + gated: { + signal: gated, + edge: "posedge", + combRead: false, + domains: [], + gated: [], + }, + }, + }; + const memory = { buffer: new ArrayBuffer(16) }; + const bytes = new Uint8Array(memory.buffer); + const set = (offset: number, level: "0" | "1" | "x" | "z") => { + bytes[offset] = level === "1" || level === "x" ? 1 : 0; + bytes[offset + 1] = level === "x" || level === "z" ? 1 : 0; + }; + // gated = clk & en, with four-state AND: a known 0 wins, then x. + const evalComb = () => { + const known0 = (offset: number) => + (bytes[offset + 1] ?? 0) === 0 && (bytes[offset] ?? 0) === 0; + const known1 = (offset: number) => + (bytes[offset + 1] ?? 0) === 0 && (bytes[offset] ?? 0) === 1; + if (known0(clk.offset) || known0(en.offset)) { + set(gated.offset, "0"); + } else if (known1(clk.offset) && known1(en.offset)) { + set(gated.offset, "1"); + } else { + set(gated.offset, "x"); + } + }; + const kernels = (name: string) => + name === "gated" + ? { + evalApply: () => { + bytes[COUNT] = (bytes[COUNT] ?? 0) + 1; + }, + } + : undefined; + const runner = new WasmEdgeRunner( + memory, + plans, + { clk: 0, gated: 1 }, + kernels, + evalComb, + ); + const rise = () => runner.edges([0], [true]); + const fall = () => runner.edges([0], [false]); + + // x & x stays x when the clock rises from x: no edge. + set(clk.offset, "x"); + set(en.offset, "x"); + evalComb(); + rise(); + expect(bytes[COUNT]).toBe(0); + // x & 1 -> 1 & 1: a posedge. + set(clk.offset, "x"); + set(en.offset, "1"); + evalComb(); + rise(); + expect(bytes[COUNT]).toBe(1); + // z & 1 is x: z -> 1 of the clock is x -> 1 of the gated clock. + set(clk.offset, "z"); + evalComb(); + rise(); + expect(bytes[COUNT]).toBe(2); + // A falling edge from x is no posedge, and the clock ends at a known 0. + set(clk.offset, "x"); + evalComb(); + fall(); + expect(bytes[COUNT]).toBe(2); + expect([bytes[clk.offset], bytes[clk.offset + 1]]).toEqual([0, 0]); + rise(); + expect(bytes[COUNT]).toBe(3); +}); diff --git a/packages/celox/src/wasm-edges.ts b/packages/celox/src/wasm-edges.ts index ee31deee116..9e4c1cc966a 100644 --- a/packages/celox/src/wasm-edges.ts +++ b/packages/celox/src/wasm-edges.ts @@ -18,6 +18,10 @@ * * Gates are judged by settling the design with the signal at each level. * + * In a four-state design, levels are 0, 1, x and z, and edges follow + * IEEE 1800-2023 Table 9-2: a posedge leaves 0 or reaches 1, a negedge + * leaves 1 or reaches 0, and a change between x and z is neither. + * * @module */ @@ -30,6 +34,11 @@ export interface EdgeMemory { export interface EdgePlanSignal { readonly offset: number; readonly width: number; + /** + * The signal keeps unknown bits; its mask follows the value byte. + * Defaults to the plans' `fourState`. + */ + readonly fourState?: boolean; } /** The active edge of a domain, or `"any"` for a domain of unknown kind. */ @@ -98,26 +107,37 @@ export function cachedEdgeKernels( }; } -/** One entry of a cascade round: a domain and the level it last had. */ +/** + * The bit of an edge level that marks an unknown value; the value bit then + * tells x (1) from z (0). An edge level is 0, 1, x (3) or z (2). + */ +const UNKNOWN = 2; + +/** One entry of a cascade round: a domain and the edge level it last had. */ interface RoundEntry { readonly domain: EdgePlanDomain; - was: boolean; + was: number; fired: boolean; } -/** A signal moved by an edge, with its level before and after. */ +/** A signal moved by an edge, with its edge level before and after. */ interface Lever { readonly signal: EdgePlanSignal; readonly from: number; readonly to: number; } -function stableEdge(edge: EdgePlanEdge, was: boolean, is: boolean): boolean { +/** + * Whether a change between the edge levels `was` and `is` is an active edge + * of a domain sensing `edge` (IEEE 1800-2023 Table 9-2). + */ +function stableEdge(edge: EdgePlanEdge, was: number, is: number): boolean { + const betweenUnknowns = (was & is & UNKNOWN) !== 0; switch (edge) { case "posedge": - return !was && is; + return was !== 1 && is !== 0 && !betweenUnknowns; case "negedge": - return was && !is; + return was !== 0 && is !== 1 && !betweenUnknowns; default: return was !== is; } @@ -212,7 +232,7 @@ export class WasmEdgeRunner { return; } const to = rising[index] ? 1 : 0; - const old = this.knownLevel(plan.signal); + const old = this.level(plan.signal); if ( old === to || levers.some((l) => l.signal.offset === plan.signal.offset) @@ -222,7 +242,9 @@ export class WasmEdgeRunner { moved = true; combRead ||= plan.combRead; this.setLevel(plan.signal, to); - const lever = { signal: plan.signal, from: old ?? to ^ 1, to }; + // A gated clock is judged from the lever's real level, x and z + // included. + const lever = { signal: plan.signal, from: old, to }; if (plan.edge === "any" || (plan.edge === "posedge") === (to === 1)) { sources.push(name); } @@ -281,7 +303,7 @@ export class WasmEdgeRunner { : levers.map((lever) => this.saveLevel(lever.signal)); let moved = false; for (const lever of levers) { - if (this.level(lever.signal) !== (lever.from === 1)) { + if (this.level(lever.signal) !== lever.from) { this.setLevel(lever.signal, lever.from); moved = true; } @@ -382,37 +404,40 @@ export class WasmEdgeRunner { return this.bytes()[offset] ?? 0; } - private level(signal: EdgePlanSignal): boolean { - return (this.byte(signal.offset) & 1) !== 0; + private fourState(signal: EdgePlanSignal): boolean { + return signal.fourState ?? this.plans.fourState; } - /** The signal's level, or `null` while it is unknown. */ - private knownLevel(signal: EdgePlanSignal): number | null { - if (this.plans.fourState && (this.byte(signal.offset + 1) & 1) !== 0) { - return null; + /** The signal's edge level: 0, 1, or x (3) and z (2) while unknown. */ + private level(signal: EdgePlanSignal): number { + const value = this.byte(signal.offset) & 1; + if (this.fourState(signal) && (this.byte(signal.offset + 1) & 1) !== 0) { + return UNKNOWN | value; } - return this.byte(signal.offset) & 1; + return value; } + /** Move the signal to the edge level `level`. */ private setLevel(signal: EdgePlanSignal, level: number): void { const bytes = this.bytes(); - bytes[signal.offset] = (this.byte(signal.offset) & ~1) | level; - if (this.plans.fourState) { - bytes[signal.offset + 1] = this.byte(signal.offset + 1) & ~1; + bytes[signal.offset] = (this.byte(signal.offset) & ~1) | (level & 1); + if (this.fourState(signal)) { + const unknown = (level & UNKNOWN) !== 0 ? 1 : 0; + bytes[signal.offset + 1] = (this.byte(signal.offset + 1) & ~1) | unknown; } } private saveLevel(signal: EdgePlanSignal): [number, number] { return [ this.byte(signal.offset), - this.plans.fourState ? this.byte(signal.offset + 1) : 0, + this.fourState(signal) ? this.byte(signal.offset + 1) : 0, ]; } private restoreLevel(signal: EdgePlanSignal, saved: [number, number]): void { const bytes = this.bytes(); bytes[signal.offset] = saved[0]; - if (this.plans.fourState) { + if (this.fourState(signal)) { bytes[signal.offset + 1] = saved[1]; } } diff --git a/packages/playground/src/waveform-viewer.ts b/packages/playground/src/waveform-viewer.ts index d7c192621f2..52421f42be2 100644 --- a/packages/playground/src/waveform-viewer.ts +++ b/packages/playground/src/waveform-viewer.ts @@ -51,7 +51,7 @@ export function generateVcdText(trace: VcdTrace): string { const L: string[] = []; L.push("$date", ` ${new Date().toISOString()}`, "$end"); L.push("$version celox-playground $end"); - L.push("$timescale 1ns $end"); + L.push("$timescale 1ps $end"); L.push("$scope module top $end"); const ids = trace.signals.map((_, i) => vcdId(i)); for (let i = 0; i < trace.signals.length; i++) { diff --git a/packages/playground/test/playground-simulator-wasm.test.ts b/packages/playground/test/playground-simulator-wasm.test.ts index 3e41fb8b612..985912eb06a 100644 --- a/packages/playground/test/playground-simulator-wasm.test.ts +++ b/packages/playground/test/playground-simulator-wasm.test.ts @@ -3,7 +3,7 @@ * explicit edges and timed steps fire derived and gated clocks as the * native simulator does. The expected counts are the native simulator's. */ -import { loadNativeAddon, Simulator } from "@celox-sim/celox"; +import { loadNativeAddon, Simulator, X } from "@celox-sim/celox"; import { describe, expect, test } from "vitest"; import { type CompilerHandle, @@ -52,15 +52,27 @@ type WasmAddon = { ) => CompilerHandle & { dispose(): void }; }; -function compile(source: string, top: string) { +// A gated clock with a reset, so that its counter is known in four-state +// simulation. +const GATED_RESET = `module GatedReset ( + clk: input clock, + rst: input reset_async_low, + en: input logic, + count: output logic<8>, +) { + let gated: '_ clock = clk & en; + always_ff (gated, rst) { if_reset { count = 0; } else { count += 1; } } +}`; + +function compile(source: string, top: string, fourState = false) { const addon = loadNativeAddon() as unknown as WasmAddon; const handle = new addon.NativeSimulatorHandle( [{ content: source, path: "top.veryl" }], top, - { fourState: false }, + { fourState }, ); try { - return compiledFromHandle(handle, false); + return compiledFromHandle(handle, fourState); } finally { handle.dispose(); } @@ -148,4 +160,25 @@ describe.skipIf(!isWasm)("playground runtime (WASM)", () => { expect(dumps[0]?.timestamp).toBe(7); expect(dumps[0]?.names).toEqual(expect.arrayContaining(["en", "count"])); }); + + test("four-state edges judge a gated clock from x (IEEE 1800-2023 Table 9-2)", () => { + const sim = createPlaygroundSimulator( + compile(GATED_RESET, "GatedReset", true), + ); + const clk = sim.event("clk"); + const rst = sim.event("rst"); + sim.negedge(rst); + sim.posedge(rst); + expect(sim.dut.count).toBe(0n); + // The clock rises from x with `en` at x: `x & x` stays x, no edge. + // The DUT is typed for two-state values; its setter takes X too. + (sim.dut as Record).en = X; + sim.posedge(clk); + expect(sim.dut.count).toBe(0n); + // From a known 0, `0 & 1` -> `1 & 1` rises. + sim.negedge(clk); + sim.dut.en = 1n; + sim.posedge(clk); + expect(sim.dut.count).toBe(1n); + }); }); diff --git a/packages/playground/test/waveform-viewer.test.ts b/packages/playground/test/waveform-viewer.test.ts new file mode 100644 index 00000000000..bb943165e74 --- /dev/null +++ b/packages/playground/test/waveform-viewer.test.ts @@ -0,0 +1,8 @@ +import { expect, test } from "vitest"; +import { generateVcdText } from "../src/waveform-viewer"; + +test("downloaded Veryl waveforms use picosecond simulation ticks", () => { + const text = generateVcdText({ signals: [{ name: "y", width: 1 }], snapshots: [{ timestamp: 123, values: [1n] }] }); + expect(text).toContain("$timescale 1ps $end"); + expect(text).toContain("#123\n"); +});