diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 768418755b4..4a5081ba774 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -224,7 +224,9 @@ jobs: bash scripts/tests/run-heliodor-bench-results.sh bash scripts/tests/run-heliodor-bench-gate.sh python3 -m unittest discover -s .updatecli/tests -v - PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover -s scripts/tests -p test_rtlmeter_bench.py -v + python3 -m venv "$RUNNER_TEMP/rtlmeter-tests" + "$RUNNER_TEMP/rtlmeter-tests/bin/python" -m pip install -r benchmarks/rtlmeter/requirements.txt + PYTHONDONTWRITEBYTECODE=1 "$RUNNER_TEMP/rtlmeter-tests/bin/python" -m unittest discover -s scripts/tests -p test_rtlmeter_bench.py -v # A new dependency edge can invalidate the NAPI exclusions or the # backend and frontend variants that pull requests narrow celox to. diff --git a/.github/workflows/rtlmeter-bench.yml b/.github/workflows/rtlmeter-bench.yml index 31b7201da1b..54f16ade5f3 100644 --- a/.github/workflows/rtlmeter-bench.yml +++ b/.github/workflows/rtlmeter-bench.yml @@ -39,7 +39,7 @@ jobs: strategy: fail-fast: false matrix: - case: [e902, e906] + case: [e902, e906, e203] steps: - uses: actions/checkout@v7 - uses: actions/setup-python@v7 @@ -109,9 +109,9 @@ jobs: path: artifacts - name: Validate every report before publishing run: | - for case in e902 e906; do + for case in e902 e906 e203; do node scripts/publish-rtlmeter-bench.mjs "artifacts/rtlmeter-$case/result/results.json" "artifacts/rtlmeter-$case/host.txt" --validate-only done - for case in e902 e906; do + for case in e902 e906 e203; do node scripts/publish-rtlmeter-bench.mjs "artifacts/rtlmeter-$case/result/results.json" "artifacts/rtlmeter-$case/host.txt" done diff --git a/benchmarks/rtlmeter/manifest.json b/benchmarks/rtlmeter/manifest.json index 91f25586722..9e3d22d52ab 100644 --- a/benchmarks/rtlmeter/manifest.json +++ b/benchmarks/rtlmeter/manifest.json @@ -6,7 +6,28 @@ "samples": 3, "verilatorVersion": "5.052", "cases": { - "e902": { "design": "XuanTie-E902", "test": "hello", "payload": "Hello Friend!", "maxCycles": 16384 }, - "e906": { "design": "XuanTie-E906", "test": "hello", "payload": "Hello Friend!", "maxCycles": 32768 } + "e902": { + "design": "XuanTie-E902", + "test": "hello", + "payload": "Hello Friend!", + "maxCycles": 16384 + }, + "e906": { + "design": "XuanTie-E906", + "test": "hello", + "payload": "Hello Friend!", + "maxCycles": 32768 + }, + "e203": { + "design": "HummingbirdV2-E203", + "test": "hello", + "payload": "Hello World from HummingbirdV2 E203", + "maxCycles": 16384, + "configuration": "default", + "successMarker": "TEST_PASSED", + "inputFiles": [ + "tests/hello/program.hex" + ] + } } } diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index d762f1cd301..faa0384b5a0 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -1633,8 +1633,8 @@ chapter-9/9.4.3--event_sequence_controls.sv 2state pass chapter-9/9.4.3--event_sequence_controls.sv 4state pass chapter-9/9.4.5--event_blocking_assignment_delay.sv 2state pass chapter-9/9.4.5--event_blocking_assignment_delay.sv 4state pass -chapter-9/9.4.5--event_nonblocking_assignment_delay.sv 2state fail -chapter-9/9.4.5--event_nonblocking_assignment_delay.sv 4state fail +chapter-9/9.4.5--event_nonblocking_assignment_delay.sv 2state pass +chapter-9/9.4.5--event_nonblocking_assignment_delay.sv 4state pass chapter-9/9.4.5--event_nonblocking_assignment_event.sv 2state pass chapter-9/9.4.5--event_nonblocking_assignment_event.sv 4state pass chapter-9/9.4.5--event_nonblocking_assignment_repeat.sv 2state pass diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 754464d521b..f2ca44864b7 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -452,7 +452,8 @@ pub enum ProcessStatus { /// ran no statement and waits at the same site. Pending, /// The process staged one nonblocking assignment. The delay slot holds - /// the index of its [`NbaSite`]. The runtime queues the staged value and + /// the index of its [`NbaSite`]. The runtime queues the staged value for + /// the site's update time and /// resumes the process at once. Nba, /// The process returned so the runtime can charge its time-slot budget. @@ -482,6 +483,9 @@ pub enum ProcessStatus { AssertionObserved, /// Resume an assertion action in Reactive after every Observed predicate. AssertionReactive, + /// Continue in the same Active/Reactive region after other runnable work. + /// This is an implementation scheduling boundary, not an HDL wait (4.7). + DeferActive, } impl ProcessStatus { @@ -507,6 +511,7 @@ impl ProcessStatus { Self::EventProbe => 16, Self::AssertionObserved => 17, Self::AssertionReactive => 18, + Self::DeferActive => 19, } } @@ -530,6 +535,7 @@ impl ProcessStatus { 16 => Some(Self::EventProbe), 17 => Some(Self::AssertionObserved), 18 => Some(Self::AssertionReactive), + 19 => Some(Self::DeferActive), _ => None, } } @@ -1117,6 +1123,9 @@ impl WaitSite { /// sites in its delay slot. #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] pub struct NbaSite { + /// Global precision ticks from evaluation to the NBA update. + #[serde(default)] + pub delay: u64, /// Index of the process in [`RuntimeSchema::processes`]. pub process: usize, /// The assigned object and the static part of the assigned bit range. @@ -1147,6 +1156,7 @@ pub struct NbaSite { impl NbaSite { pub fn map(&self, mut map: impl FnMut(A) -> B) -> NbaSite { NbaSite { + delay: self.delay, process: self.process, target: map(self.target), lsb: self.lsb, diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index 980d1953c86..d41a22f7430 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -229,6 +229,13 @@ impl ProcessKernelBuilder { self.suspend(ProcessStatus::Yield) } + /// Give other runnable work priority before the next statement, without + /// leaving the current Active/Reactive region (IEEE 1800-2023 4.7). + pub fn defer_active(&mut self) -> Result<(), ProcessKernelError> { + self.slots.const_delays = false; + self.suspend(ProcessStatus::DeferActive) + } + /// Reserve one entry point for each child, then return to the runtime to spawn them. /// The caller lowers each child into its entry block and ends it with `complete`. pub fn fork( @@ -364,8 +371,8 @@ impl ProcessKernelBuilder { } /// The nonblocking assignment of nonblocking site `index` of this - /// process, described by `site`: schedule a value for the NBA region of - /// the current time (IEEE 1800-2023 10.4.2). `lower` lowers the + /// process, described by `site`: schedule a value for the NBA region at + /// the current time plus `site.delay` (IEEE 1800-2023 10.4.2). `lower` lowers the /// right-hand side at the open block and returns the value, a register /// of `site.width` bits, and for a site with a run-time position the bit /// offset and the number of bits written, unsigned two-state registers diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 2321410fa29..242c7dd6531 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1422,6 +1422,7 @@ fn lower_statements( .contains(&target.signal()) .then(|| lowering.hidden.declare(name("pending"), 1, false)); let site = NbaSite { + delay: 0, process: lowering.process, target: source_id(target.signal()), lsb: target.lsb(), diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 58fc59e4196..696973588d5 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -4442,10 +4442,12 @@ fn select_nba_paths( processes: &mut [RelocatedProcess], ) { let mut staged = staged.clone(); - // Fork activations can reach one NBA site concurrently. Always queue its + // Future updates must be queued at issue time rather than staged for + // publication in the current slot. Fork activations can reach one NBA site + // concurrently. Always queue its // captured value, rather than leaving one shared pending slot per kernel. for site in &timing.nba_sites { - if processes[site.process].frame.is_some() { + if site.delay > 0 || processes[site.process].frame.is_some() { for switch in &timing.nba_switches { if switch.value == site.value { staged.remove(&switch.switch); diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 59cc2285d77..a559eb85955 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -155,9 +155,6 @@ pub(crate) struct LoweredSvModule { /// The continuous assignments of the event expressions the processes /// wait on, by their hidden target `$event[k]`. event_assignments: Vec<(SourceVarId, Vec)>, - /// The creation orders of the `always @(list)` processes lowered like - /// `always @*`. - level_lists_lowered: Vec, /// The write streams one flip-flop evaluation may write twice. repeated_ff_writes: Vec, /// The `inout` ports whose net has its driver in this module or below it, @@ -329,6 +326,7 @@ fn interface_signatures_collecting( LevelLists::Processes, &HashMap::default(), &HashMap::default(), + SharedAlways::default(), )?; Ok(InterfaceSignature { name: prototype.name, @@ -1017,6 +1015,7 @@ fn lower_package_states( LevelLists::Processes, &HashMap::default(), &HashMap::default(), + SharedAlways::default(), )?; lowered.sim_module.time_precision = Some( celox_design::TimePrecision::try_from(packages.global_time_precision()) @@ -1294,6 +1293,338 @@ fn shared_edge_memories( memories } +/// How `always @*` blocks that write a common variable run. +#[derive(Clone, Copy)] +struct SharedAlways<'a> { + /// Make a variable a temporary of each block when that is unobservable + /// within the module (the `shared_always_temporary` diagnostic; see + /// [`share_always_variables`]). + temporaries: bool, + /// The module's signals that hierarchical names in other modules denote. + foreign_references: &'a HashSet, +} + +impl Default for SharedAlways<'_> { + fn default() -> Self { + static EMPTY: std::sync::LazyLock> = + std::sync::LazyLock::new(HashSet::default); + Self { + temporaries: false, + foreign_references: &EMPTY, + } + } +} + +/// `module` with its `always @*` blocks that write a common variable +/// rearranged, and the variables they write together as processes, or +/// `None` when no blocks write a common variable. +/// +/// Several plain `always` processes may write one variable (IEEE 1800-2023 +/// 6.5, 9.2.2), such as a loop index, and each block waits on the variables +/// it reads, a shared one included (9.4.2.2). So the blocks run as +/// processes, whose writes notify other blocks that are waiting. For isolated +/// indices written before reads, let other Active work run after the body but +/// before its next implicit wait, as 4.7 and 4.9.3 permit. The shared variable's +/// writes and event notifications remain; no private copy is substituted. +/// Blocks that still keep waking each other report the time and processes. +/// +/// With `shared.temporaries`, a variable becomes a temporary of each block +/// instead when only such blocks write it, each writes it before it reads +/// it on every path, and nothing else reads it: no other process, +/// continuous assignment, subroutine, port, instance connection or +/// hierarchical name. Its writes then wake no other block, unlike in the +/// standard, and the variable itself keeps its initial value. +fn share_always_variables( + module: &sv::ir::Module, + constants: &HashMap, + parameter_types: &HashMap, + shared: SharedAlways<'_>, + warnings: &mut Vec, +) -> Option<(sv::ir::Module, HashSet)> { + let comb = module.comb_processes(); + let mut shared_names = HashSet::default(); + let drivers = ModuleDrivers::new(module, constants, parameter_types); + let mut processes = HashSet::default(); + let mut deferred_rearm = HashSet::default(); + let mut temporaries: Vec<(&sv::ir::Signal, Vec)> = Vec::new(); + for signal in module.signals().iter().filter(|signal| !signal.is_net()) { + let mut writers: Vec = drivers + .local(signal.name()) + .iter() + .map(|(driver, _)| *driver) + .collect(); + writers.sort_unstable(); + writers.dedup(); + if writers.len() < 2 + || !writers.iter().all(|&driver| { + comb.get(driver) + .is_some_and(|process| process.kind() == sv::ir::CombProcessKind::AlwaysStar) + }) + { + continue; + } + let isolated = !shared.foreign_references.contains(signal.name()) + && !read_outside(module, signal.name(), &writers) + && writers.iter().all(|&driver| { + let body = comb[driver].body(); + !has_nonblocking_write(body, signal.name()) + && written_before_read(body, signal.name(), false) == Some(true) + }); + if shared.temporaries && isolated { + temporaries.push((signal, writers)); + } else { + if isolated { + deferred_rearm.extend(writers.iter().copied()); + } + processes.extend(writers); + shared_names.insert(signal.name().to_string()); + } + } + if processes.is_empty() && temporaries.is_empty() { + return None; + } + let mut module = module.clone(); + let mut renames: HashMap> = HashMap::default(); + for (signal, writers) in &temporaries { + let mut sites: Vec = writers + .iter() + .filter_map(|&driver| driver_site(&module, driver)) + .collect(); + sites.sort_unstable(); + warnings.push(( + crate::FrontendWarningKind::SharedAlwaysTemporary { + module: module.name().into(), + signal: signal.name().into(), + blocks: sites.join(", "), + }, + comb[writers[0]].site().cloned(), + )); + for &driver in writers { + let local = format!("{}$always{driver}", signal.name()); + module = module.add_local(sv::ir::LocalVariable { + name: local.clone(), + source_name: signal.name().into(), + r#type: signal.r#type().clone(), + }); + renames + .entry(driver) + .or_default() + .insert(signal.name().into(), local); + } + } + let module = module.map_comb_process_bodies(|index, body, sensitivity| { + let Some(renames) = renames.get(&index) else { + return body; + }; + let mut renamed: Vec = Vec::new(); + if !sensitivity { + // Each run starts a new temporary. + let mut locals: Vec<&String> = renames.values().collect(); + locals.sort_unstable(); + renamed.extend(locals.into_iter().map(|name| sv::ir::Stmt::Local { + name: name.clone(), + init: None, + })); + } + renamed.extend(body.into_iter().map(|stmt| { + stmt.map( + &mut |expr| ff::rename_idents(&expr, renames), + &mut |lvalue| rename_lvalue(lvalue, renames), + ) + })); + renamed + }); + Some(( + module.run_comb_processes_with_deferred_rearm(|index, _| { + processes + .contains(&index) + .then_some(deferred_rearm.contains(&index)) + }), + shared_names, + )) +} + +/// `lvalue` with the identifiers in `renames` replaced. +fn rename_lvalue(lvalue: sv::ir::LValue, renames: &HashMap) -> sv::ir::LValue { + match lvalue { + sv::ir::LValue::Ident(name) => { + sv::ir::LValue::Ident(renames.get(&name).cloned().unwrap_or(name)) + } + sv::ir::LValue::Select { + name, + msb, + lsb, + array_slice_width, + array_slice_reversed, + } => sv::ir::LValue::Select { + name: renames.get(&name).cloned().unwrap_or(name), + msb: ff::rename_const_idents(&msb, renames), + lsb: ff::rename_const_idents(&lsb, renames), + array_slice_width: array_slice_width + .map(|width| ff::rename_const_idents(&width, renames)), + array_slice_reversed, + }, + } +} + +/// Whether `stmts` mention `name`, read or written. +fn stmts_mention(stmts: &[sv::ir::Stmt], name: &str) -> bool { + let renames: HashMap = + std::iter::once((name.to_string(), format!("{name}$"))).collect(); + stmts.iter().any(|stmt| { + let mut expression_found = false; + let mut target_found = false; + stmt.clone().map( + &mut |expr| { + expression_found |= ff::rename_idents(&expr, &renames) != expr; + expr + }, + &mut |lvalue| { + target_found |= rename_lvalue(lvalue.clone(), &renames) != lvalue; + lvalue + }, + ); + expression_found || target_found + }) +} + +/// Whether something other than the processes `writers` (indices among the +/// combinational processes) of `module` reads or writes `name`. +fn read_outside(module: &sv::ir::Module, name: &str, writers: &[usize]) -> bool { + let renames: HashMap = + std::iter::once((name.to_string(), format!("{name}$"))).collect(); + let mentions = |expr: &sv::ir::Expr| ff::rename_idents(expr, &renames) != *expr; + module.ports().iter().any(|port| port.name() == name) + || module + .comb_processes() + .iter() + .enumerate() + .filter(|(index, _)| !writers.contains(index)) + .any(|(_, process)| { + stmts_mention(process.body(), name) + || stmts_mention(process.sensitivity_body(), name) + }) + || module + .ff_processes() + .iter() + .any(|process| stmts_mention(process.body(), name)) + || module + .initial_processes() + .iter() + .any(|process| stmts_mention(process.body(), name)) + || module + .subroutines() + .iter() + .any(|subroutine| stmts_mention(&subroutine.body, name)) + || module + .assignments() + .iter() + .any(|assignment| assignment.lhs() == name || mentions(assignment.rhs())) + || module.instances().iter().any(|instance| { + instance.port_connections().iter().any(|connection| { + connection.actual() == name || connection.actual_expr().is_some_and(mentions) + }) + }) +} + +/// A queued write cannot initialize a temporary or remain combinational +/// after privatization, even if a blocking assignment precedes it. +fn has_nonblocking_write(stmts: &[sv::ir::Stmt], name: &str) -> bool { + use sv::ir::Stmt; + stmts.iter().any(|stmt| { + let mut found = false; + stmt.walk(&mut |stmt| { + found |= match stmt { + Stmt::Assign { + lhs, + nonblocking: true, + .. + } => lhs.name() == name, + Stmt::AssignConcat { + parts, + nonblocking: true, + .. + } => parts.iter().any(|part| part.name() == name), + _ => false, + }; + }); + found + }) +} + +/// Whether every path through `stmts` writes the whole of `name` before it +/// reads it: `Some` with whether `name` is written when they end, or `None` +/// when a read may come before the write. `assigned` says whether it is +/// written when they start. +fn written_before_read(stmts: &[sv::ir::Stmt], name: &str, mut assigned: bool) -> Option { + use sv::ir::Stmt; + let reads = |stmt: &Stmt| stmts_mention(std::slice::from_ref(stmt), name); + for stmt in stmts { + assigned = match stmt { + Stmt::Assign { + lhs, + rhs, + nonblocking: false, + } => { + let whole = matches!(lhs, sv::ir::LValue::Ident(target) if target == name); + let probe = Stmt::Eval(rhs.clone()); + let index_reads = !whole + && matches!(lhs, sv::ir::LValue::Select { .. }) + && lhs.name() != name + && reads(stmt); + if !assigned && (reads(&probe) || index_reads) { + return None; + } + assigned || whole + } + Stmt::If { + condition, + then_body, + else_body, + } => { + if !assigned && reads(&Stmt::Eval(condition.clone())) { + return None; + } + let then_assigned = written_before_read(then_body, name, assigned)?; + let else_assigned = written_before_read(else_body, name, assigned)?; + then_assigned && else_assigned + } + Stmt::Loop { + kind, + init, + condition, + step, + body, + } => { + let initialized = written_before_read(init, name, assigned)?; + let header = Stmt::Loop { + kind: kind.clone(), + init: Vec::new(), + condition: condition.clone(), + step: Vec::new(), + body: Vec::new(), + }; + if !initialized && reads(&header) { + return None; + } + // The body and the step may not run. + let after_body = written_before_read(body, name, initialized)?; + written_before_read(step, name, after_body)?; + initialized + } + Stmt::Break | Stmt::Continue => assigned, + // Other statements, case statements included, only read here. + _ => { + if !assigned && reads(stmt) { + return None; + } + assigned + } + }; + } + Some(assigned) +} + /// Variables, other than unpacked arrays, that several plain edge-triggered /// `always` processes write only by blocking assignments, such as a loop /// index they share. A variable may have several procedural writers, and the @@ -1696,8 +2027,19 @@ fn validate_variable_driver_ranges( }) }); if overlapping_continuous || (has_overlap && !shared.contains(signal_name)) { + let mut sites: Vec = local + .iter() + .filter_map(|(driver, _)| driver_site(module, *driver)) + .collect(); + sites.sort_unstable(); + sites.dedup(); + let at = if sites.is_empty() { + String::new() + } else { + format!(", written at {}", sites.join(", ")) + }; return Err(sv::AnalyzerError::Unsupported(format!( - "multiple variable drivers for `{signal_name}`" + "multiple variable drivers for `{signal_name}`{at}" ))); } } @@ -2038,6 +2380,30 @@ impl ModuleDrivers { } } +/// Where process `driver` of [`ModuleDrivers::local`] is written, as +/// `path:line` or `path:line:column`. +fn driver_site(module: &sv::ir::Module, driver: usize) -> Option { + let combinational = module.comb_processes().len(); + let edge = combinational + module.ff_processes().len(); + if let Some(process) = module.comb_processes().get(driver) { + return process + .site() + .map(|site| format!("{}:{}", site.logical_path.display(), site.line)); + } + if driver < edge { + return module.ff_processes()[driver - combinational] + .site() + .map(ToString::to_string); + } + module + .initial_processes() + .iter() + .filter(|process| process.repeats()) + .nth(driver - edge) + .and_then(|process| process.site()) + .map(ToString::to_string) +} + /// Whether process `driver` of [`ModuleDrivers::local`] must be the only writer of /// the variables it writes: an `always_comb` or continuous assignment, an /// edge procedure, or an `always_ff` run as a process, but not another @@ -2361,7 +2727,6 @@ fn prepare_external_hierarchy_collecting( // The foreign module's own combinational blocks carry its copies. event_copies: Vec::new(), event_assignments: Vec::new(), - level_lists_lowered: Vec::new(), repeated_ff_writes: Vec::new(), inout_driven_inside: HashSet::default(), } @@ -3128,6 +3493,7 @@ fn schedule_sources_collecting( // the order the modules are lowered in. let mut references = HashMap::default(); let mut analyses = HashMap::default(); + let mut foreign_references: HashMap> = HashMap::default(); let mut foreign_writes: HashMap> = HashMap::default(); for &module_id in &hierarchical_modules { @@ -3163,6 +3529,14 @@ fn schedule_sources_collecting( if let Some(module) = ir.modules().iter().find(|module| module.name() == key.name) { hierarchy::collect_foreign_writes(module, &resolved, &mut foreign_writes); } + for reference in &resolved { + for (target_module, target) in &reference.targets { + foreign_references + .entry(*target_module) + .or_default() + .insert(target.clone()); + } + } references.insert(module_id, resolved); analyses.insert(module_id, ir); } @@ -3197,9 +3571,9 @@ fn schedule_sources_collecting( } drop(virtual_sources); - // A combinational loop through an `always @(list)` lowered like - // `always @*` may converge as a process: demote the lists in the loop - // and schedule again, until no lowered list takes part in it. + // Level-sensitive always blocks in a static combinational loop may + // converge as event processes. Demote the participating blocks and retry; + // the runtime then evaluates convergence using their authored sensitivity. let no_demotions = HashSet::default(); let mut demoted: HashMap> = HashMap::default(); let mut trace = trace; @@ -3208,6 +3582,7 @@ fn schedule_sources_collecting( // fixed above. A retry changes only the demoted level lists of the modules // reported by `demote_level_lists`; retain every other lowered module. let mut lowered_modules = HashMap::default(); + let no_foreign_references = HashSet::default(); loop { let mut specialize = |key: &LoweredSvModuleKey, module_id: ModuleId| @@ -3239,6 +3614,12 @@ fn schedule_sources_collecting( signals: &signals, foreign_writes: foreign_writes.get(&module_id).unwrap_or(&no_foreign_writes), analyzed: analyses.get(&module_id).or(discovery_analysis.as_ref()), + shared: SharedAlways { + temporaries: analysis_options.shared_always_temporaries, + foreign_references: foreign_references + .get(&module_id) + .unwrap_or(&no_foreign_references), + }, }, )?) }; @@ -3379,8 +3760,8 @@ fn schedule_sources_collecting( } } -/// Demote the `always @(list)` processes lowered like `always @*` which -/// drive a range of a combinational loop. Return the changed modules so only +/// Demote `always @*` and equivalent explicit-list processes which drive +/// a range of a combinational loop. Return the changed modules so only /// their lowering is invalidated before scheduling again. fn demote_level_lists( loop_members: &[celox_frontend_core::symbolic::assembly::LoopMember], @@ -3403,7 +3784,6 @@ fn demote_level_lists( for process in lowered.source.comb_processes() { let creation_order = process.creation_order(); if process.kind() != sv::ir::CombProcessKind::AlwaysStar - || !lowered.level_lists_lowered.contains(&creation_order) || demoted .get(module_id) .is_some_and(|demoted| demoted.contains(&creation_order)) @@ -3651,6 +4031,7 @@ fn specialize_module( level_lists, hierarchical.foreign_writes, &module.interface_member_paths, + hierarchical.shared, )?; propagate_force_signals(&mut lowered.instances, &key.force_signals); lowered.sim_module.time_precision = Some( @@ -3669,6 +4050,8 @@ struct HierarchicalNames<'a> { signals: &'a [sv::ast::HierarchicalSignal], /// The module's signals that names in other modules write. foreign_writes: &'a HashMap, + /// How `always @*` blocks that write a common variable run. + shared: SharedAlways<'a>, /// The analysis of the module with `signals`, if it is done already. analyzed: Option<&'a sv::Ir>, } @@ -3680,6 +4063,7 @@ impl Default for HierarchicalNames<'_> { Self { signals: &[], foreign_writes: &EMPTY, + shared: SharedAlways::default(), analyzed: None, } } @@ -3767,6 +4151,7 @@ fn lower_module( level_lists: LevelLists<'_>, foreign_writes: &HashMap, reflected_paths: &HashMap, + shared: SharedAlways<'_>, ) -> Result { lower_module_with_overrides( module, @@ -3779,6 +4164,7 @@ fn lower_module( level_lists, foreign_writes, reflected_paths, + shared, ) } @@ -3863,9 +4249,31 @@ fn lower_module_with_overrides( level_lists: LevelLists<'_>, foreign_writes: &HashMap, reflected_paths: &HashMap, + shared: SharedAlways<'_>, ) -> Result { let parameter_types = module_parameter_types(module); let constants = module_constants_with_overrides(module, parameter_overrides); + let demoted_stars = match level_lists { + LevelLists::Lowered { demoted } + if module.comb_processes().iter().any(|process| { + process.kind() == sv::ir::CombProcessKind::AlwaysStar + && demoted.contains(&process.creation_order()) + }) => + { + Some( + module + .clone() + .run_comb_processes_as_processes(|_, process| { + demoted.contains(&process.creation_order()) + }), + ) + } + _ => None, + }; + let module = demoted_stars.as_ref().unwrap_or(module); + let sharing = share_always_variables(module, &constants, ¶meter_types, shared, warnings); + let module = sharing.as_ref().map_or(module, |(module, _)| module); + let shared_process_variables = sharing.as_ref().map(|(_, names)| names); let fallbacks = module .ff_processes() .iter() @@ -3901,7 +4309,11 @@ fn lower_module_with_overrides( let drivers = ModuleDrivers::new(module, &constants, ¶meter_types); let shared_memories = shared_edge_memories(module, &drivers, foreign_writes, warnings); let shared_variables = shared_edge_variables(module, &drivers); - let shared_all = shared_memories.union(&shared_variables).cloned().collect(); + let shared_all = shared_memories + .union(&shared_variables) + .chain(shared_process_variables.into_iter().flatten()) + .cloned() + .collect(); validate_variable_driver_ranges(module, &drivers, &shared_all)?; validate_foreign_drivers(module, &drivers, &shared_memories, foreign_writes)?; let scheduled = module @@ -4222,7 +4634,6 @@ fn lower_module_with_overrides( )?; // `always @(list)` naming exactly the reads of its statement is // `always @*` (IEEE 1800-2023 9.4.2.2), which needs no process. - let mut level_lists_lowered = Vec::new(); let level_sensitive = match level_lists { LevelLists::Processes => None, LevelLists::Lowered { demoted } => Some(demoted), @@ -4244,14 +4655,10 @@ fn lower_module_with_overrides( warnings, ); module.clone().lower_level_sensitive_processes(|process| { - let selected = !demoted.contains(&process.creation_order()) + !demoted.contains(&process.creation_order()) && process .level_sensitive() - .is_some_and(|(items, body)| pm.is_implicit_event_list(items, body)); - if selected { - level_lists_lowered.push(process.creation_order()); - } - selected + .is_some_and(|(items, body)| pm.is_implicit_event_list(items, body)) }) }); let module = level_sensitive.as_ref().unwrap_or(module); @@ -4380,7 +4787,6 @@ fn lower_module_with_overrides( package_variables, event_copies: event_vars.copies, event_assignments, - level_lists_lowered, repeated_ff_writes, inout_driven_inside: HashSet::default(), }) @@ -11410,6 +11816,66 @@ fn inferred_clock( mod tests { use super::*; + #[test] + fn shared_always_temporaries_exclude_queued_writes() { + // The syntax frontend currently rejects untimed wildcard NBAs before + // lowering. Exercise the IR transformation directly so it remains safe + // when such a process reaches this pass. + for (left, right) in [ + ("j=a; x=j;", "j=b; y=j;"), + ("{j}=a; x=j;", "{j}=b; y=j;"), + ( + "j=0; case(a) default:j=a; endcase x=j;", + "j=0; case(b) default:{j}=b; endcase y=j;", + ), + ] { + let source = format!( + "module Top(input bit a,b, output bit x,y); bit j; \ + always @* begin {left} end always @* begin {right} end endmodule" + ); + let ir = sv::analyze_source(&source, Path::new("shared_nba.sv")).unwrap(); + let module = + ir.modules()[0] + .clone() + .map_comb_process_bodies(|_, mut body, sensitivity| { + if !sensitivity { + for stmt in &mut body { + stmt.walk_mut(&mut |stmt| match stmt { + sv::ir::Stmt::Assign { + lhs, + rhs: sv::ir::Expr::Ident(_), + nonblocking, + } if lhs.name() == "j" => *nonblocking = true, + sv::ir::Stmt::AssignConcat { + parts, nonblocking, .. + } if parts.iter().any(|part| part.name() == "j") => { + *nonblocking = true + } + _ => {} + }); + } + } + body + }); + let mut warnings = Vec::new(); + let (converted, shared) = share_always_variables( + &module, + &module_constants_with_overrides(&module, &[]), + &module_parameter_types(&module), + SharedAlways { + temporaries: true, + foreign_references: &HashSet::default(), + }, + &mut warnings, + ) + .unwrap(); + assert!(shared.contains("j"), "{source}"); + assert!(warnings.is_empty(), "{source}"); + assert!(converted.comb_processes().is_empty(), "{source}"); + assert_eq!(converted.initial_processes().len(), 2, "{source}"); + } + } + std::thread_local! { // Observe the real compilation path without sharing counters between // concurrently running tests or adding instrumentation to release builds. diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index 34d1634119f..63b38440ff6 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -2069,7 +2069,9 @@ impl<'p, 'a> Comb<'p, 'a> { Ok(store) } // A timing control suspends a process; this lowering has none. - sv::ir::Stmt::Delay { .. } + sv::ir::Stmt::DeferActive + | sv::ir::Stmt::DelayedNonblocking { .. } + | sv::ir::Stmt::Delay { .. } | sv::ir::Stmt::WaitEvent(_) | sv::ir::Stmt::WaitImplicit(_) | sv::ir::Stmt::Wait(_) => Err(unsupported("procedural timing control")), diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index eebe16f11de..5354f607cfc 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -1125,10 +1125,19 @@ impl<'p, 'a> Ff<'p, 'a> { fn eval_const( &mut self, expr: &sv::ir::Expr, + ) -> Result, sv::AnalyzerError> { + self.eval_const_with_width(expr, None) + } + + fn eval_const_with_width( + &mut self, + expr: &sv::ir::Expr, + width: Option, ) -> Result, sv::AnalyzerError> { if self.m.calls(expr) { return Ok(None); } + let signed = width.map(|_| self.expr_signed(expr)); let expr = self.propagate(&expr_for_state_mode(expr, self.m.four_state)); let mut arena = SLTNodeArena::new(); let Some((node, _)) = lower_expr_with_context( @@ -1143,6 +1152,11 @@ impl<'p, 'a> Ff<'p, 'a> { ) else { return Ok(None); }; + let node = if let Some(signed) = signed { + coerce_node_width(&mut arena, node, width, signed).map_err(slt_error)? + } else { + node + }; Ok(slt_const(&arena, &mut ConstCache::default(), node)) } @@ -3720,6 +3734,45 @@ impl<'p, 'a> Ff<'p, 'a> { return Err(unsupported("timed task call outside a suspendable process")); } match stmt { + sv::ir::Stmt::DeferActive => { + self.with_kernel(ProcessKernelBuilder::defer_active) + .map_err(kernel_error)?; + Ok(true) + } + sv::ir::Stmt::DelayedNonblocking { + control, + assignment, + } => { + let sv::ir::Stmt::Delay { + amount, + ticks_per_unit, + .. + } = control.as_ref() + else { + return Err(unsupported("nonblocking intra-assignment event control")); + }; + let delay = self + .eval_const_with_width(amount, Some(PROCESS_DELAY_WIDTH))? + .and_then(|(value, _)| u64::try_from(value).ok()) + .and_then(|value| value.checked_mul(*ticks_per_unit)) + .ok_or_else(|| { + unsupported("nonconstant or overflowing nonblocking assignment delay") + })?; + match assignment.as_ref() { + sv::ir::Stmt::Assign { + lhs, + rhs, + nonblocking: true, + } => self.nonblocking_delayed(std::slice::from_ref(lhs), rhs, delay)?, + sv::ir::Stmt::AssignConcat { + parts, + rhs, + nonblocking: true, + } => self.nonblocking_delayed(parts, rhs, delay)?, + _ => return Err(unsupported("nonblocking delayed assignment target")), + } + Ok(true) + } sv::ir::Stmt::Assign { lhs, rhs, @@ -6596,6 +6649,15 @@ impl Ff<'_, '_> { &mut self, parts: &[sv::ir::LValue], rhs: &sv::ir::Expr, + ) -> Result<(), sv::AnalyzerError> { + self.nonblocking_delayed(parts, rhs, 0) + } + + fn nonblocking_delayed( + &mut self, + parts: &[sv::ir::LValue], + rhs: &sv::ir::Expr, + delay: u64, ) -> Result<(), sv::AnalyzerError> { let mut targets = Vec::with_capacity(parts.len()); for part in parts { @@ -6683,6 +6745,7 @@ impl Ff<'_, '_> { width: self.m.temp("nba_width", NBA_POSITION_WIDTH, false, false).0, }); let site = NbaSite { + delay, process: self.process, target: id, lsb, @@ -8142,7 +8205,87 @@ fn concurrent_monitor_clock(body: &[sv::ir::Stmt]) -> Option { } /// `expr` with the identifiers in `renames` replaced. -fn rename_idents(expr: &sv::ir::Expr, renames: &HashMap) -> sv::ir::Expr { +pub(super) fn rename_const_idents( + expr: &sv::ir::ConstExpr, + renames: &HashMap, +) -> sv::ir::ConstExpr { + rename_const_idents_with_sampling(expr, renames, false) +} + +fn rename_const_idents_with_sampling( + expr: &sv::ir::ConstExpr, + renames: &HashMap, + sampling: bool, +) -> sv::ir::ConstExpr { + if sampling + && matches!(expr, sv::ir::ConstExpr::Function { callee: sv::ir::Callee::System(function), .. } if function.reads_sampled_values()) + { + return expr.clone(); + } + use sv::ir::ConstExpr; + let go = + |expr: &ConstExpr| Box::new(rename_const_idents_with_sampling(expr, renames, sampling)); + match expr { + ConstExpr::Ident(name) => ConstExpr::Ident(renames.get(name).unwrap_or(name).clone()), + ConstExpr::Literal(_) => expr.clone(), + ConstExpr::SelectRange { + expr, + msb, + lsb, + signed, + } => ConstExpr::SelectRange { + expr: go(expr), + msb: go(msb), + lsb: go(lsb), + signed: *signed, + }, + ConstExpr::Select { expr, bit } => ConstExpr::Select { + expr: go(expr), + bit: go(bit), + }, + ConstExpr::Function { callee, args, site } => ConstExpr::Function { + callee: callee.clone(), + site: *site, + args: args + .iter() + .map(|arg| rename_const_idents_with_sampling(arg, renames, sampling)) + .collect(), + }, + ConstExpr::Resize { + expr, + width, + signed, + } => ConstExpr::Resize { + expr: go(expr), + width: *width, + signed: *signed, + }, + ConstExpr::Unary { op, expr } => ConstExpr::Unary { + op: *op, + expr: go(expr), + }, + ConstExpr::Binary { left, op, right } => ConstExpr::Binary { + left: go(left), + op: *op, + right: go(right), + }, + ConstExpr::Mux { + condition, + then_expr, + else_expr, + } => ConstExpr::Mux { + condition: go(condition), + then_expr: go(then_expr), + else_expr: go(else_expr), + }, + } +} + +/// `expr` with the identifiers in `renames` replaced. +pub(super) fn rename_idents( + expr: &sv::ir::Expr, + renames: &HashMap, +) -> sv::ir::Expr { rename_idents_with_sampling(expr, renames, false) } @@ -8153,73 +8296,6 @@ fn rename_idents_with_sampling( renames: &HashMap, sampling: bool, ) -> sv::ir::Expr { - fn constant( - expr: &sv::ir::ConstExpr, - renames: &HashMap, - sampling: bool, - ) -> sv::ir::ConstExpr { - if sampling - && matches!(expr, sv::ir::ConstExpr::Function { callee: sv::ir::Callee::System(function), .. } if function.reads_sampled_values()) - { - return expr.clone(); - } - use sv::ir::ConstExpr; - let go = |expr: &ConstExpr| Box::new(constant(expr, renames, sampling)); - match expr { - ConstExpr::Ident(name) => ConstExpr::Ident(renames.get(name).unwrap_or(name).clone()), - ConstExpr::Literal(_) => expr.clone(), - ConstExpr::SelectRange { - expr, - msb, - lsb, - signed, - } => ConstExpr::SelectRange { - expr: go(expr), - msb: go(msb), - lsb: go(lsb), - signed: *signed, - }, - ConstExpr::Select { expr, bit } => ConstExpr::Select { - expr: go(expr), - bit: go(bit), - }, - ConstExpr::Function { callee, args, site } => ConstExpr::Function { - callee: callee.clone(), - site: *site, - args: args - .iter() - .map(|arg| constant(arg, renames, sampling)) - .collect(), - }, - ConstExpr::Resize { - expr, - width, - signed, - } => ConstExpr::Resize { - expr: go(expr), - width: *width, - signed: *signed, - }, - ConstExpr::Unary { op, expr } => ConstExpr::Unary { - op: *op, - expr: go(expr), - }, - ConstExpr::Binary { left, op, right } => ConstExpr::Binary { - left: go(left), - op: *op, - right: go(right), - }, - ConstExpr::Mux { - condition, - then_expr, - else_expr, - } => ConstExpr::Mux { - condition: go(condition), - then_expr: go(then_expr), - else_expr: go(else_expr), - }, - } - } if sampling && matches!(expr, sv::ir::Expr::Call { callee: sv::ir::Callee::System(function), .. } if function.reads_sampled_values()) { @@ -8237,8 +8313,8 @@ fn rename_idents_with_sampling( signed, } => Expr::Select { expr: go(expr), - msb: constant(msb, renames, sampling), - lsb: constant(lsb, renames, sampling), + msb: rename_const_idents_with_sampling(msb, renames, sampling), + lsb: rename_const_idents_with_sampling(lsb, renames, sampling), signed: *signed, }, Expr::Concat(parts) => Expr::Concat( @@ -8248,7 +8324,7 @@ fn rename_idents_with_sampling( .collect(), ), Expr::RepeatConcat { count, parts } => Expr::RepeatConcat { - count: constant(count, renames, sampling), + count: rename_const_idents_with_sampling(count, renames, sampling), parts: parts .iter() .map(|part| rename_idents_with_sampling(part, renames, sampling)) diff --git a/crates/celox-frontend-sv/src/warning.rs b/crates/celox-frontend-sv/src/warning.rs index 9bdc2f46418..57724ab35a6 100644 --- a/crates/celox-frontend-sv/src/warning.rs +++ b/crates/celox-frontend-sv/src/warning.rs @@ -65,6 +65,18 @@ pub enum FrontendWarningKind { /// IEEE 1800-2023 24.7 ignores. #[error("`$exit` outside a program block is ignored")] ExitOutsideProgram, + /// A variable that only several `always @*` blocks write is a temporary + /// of each block, so its writes do not wake the other blocks as IEEE + /// 1800-2023 9.4.2.2 requires. Applied only when the diagnostic is not + /// an error. + #[error( + "`{signal}` in `{module}` is treated as a temporary of each `always @*` block that writes it ({blocks}): its writes do not wake the other blocks" + )] + SharedAlwaysTemporary { + module: String, + signal: String, + blocks: String, + }, } /// Where a warning is in the source. @@ -176,6 +188,7 @@ impl miette::Diagnostic for FrontendWarning { FrontendWarningKind::InferredLatch => "inferred_latch", FrontendWarningKind::MemoryFileWordCount { .. } => "memory_file_word_count", FrontendWarningKind::ExitOutsideProgram => "exit_outside_program", + FrontendWarningKind::SharedAlwaysTemporary { .. } => "shared_always_temporary", })) } @@ -209,6 +222,9 @@ impl miette::Diagnostic for FrontendWarning { FrontendWarningKind::ExitOutsideProgram => { "end the simulation with `$finish`, or remove the call" } + FrontendWarningKind::SharedAlwaysTemporary { .. } => { + "a language deviation enabled by shared_always_temporary=warn or allow; declare the variable inside each block to keep IEEE 1800-2023 semantics" + } })) } diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index d6867741ca8..3160165aeb3 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -374,6 +374,7 @@ impl ResolvedSchedule { .nbas .iter() .map(|site| NbaSiteRefs { + delay: site.delay, target: resolve(&site.target), lsb: site.lsb, width: site.width, diff --git a/crates/celox-runtime/src/simulation/activation.rs b/crates/celox-runtime/src/simulation/activation.rs index 48b7eff94b0..3e0da6abfa0 100644 --- a/crates/celox-runtime/src/simulation/activation.rs +++ b/crates/celox-runtime/src/simulation/activation.rs @@ -285,6 +285,7 @@ impl SimulationState { activation.join = None; state.waiters.remove(id); state.ready.remove(&id); + state.deferred_ready.remove(&id); state.reactive.remove(&id); state.observed.remove(&id); state.inactive.remove(&id); diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index 402e5060ebb..cb4d1f54e21 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -74,8 +74,10 @@ impl SimulationState { || self.host_pending || !pending.observed.is_empty() || !pending.ready.is_empty() + || !pending.deferred_ready.is_empty() || !pending.inactive.is_empty() || !pending.nba_queue.is_empty() + || !pending.delayed_nba.is_empty() || !pending.nba_events.is_empty() // A derived clock changes with the slots of its sources, which // the scheduler does not tell apart. diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index d5e9ca58ef8..dc7af106a4b 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -176,6 +176,11 @@ pub struct SimulationState { return_budget: u64, /// Rounds and process-phase passes the current time slot has run. slot_passes: u64, + /// The processes the current time slot ran, most recent last, up to + /// [`RESUMED_PROCESSES`]: the ones a slot that does not settle reports. + slot_resumed: std::collections::VecDeque, + /// Names of the processes for diagnostics, by index. + process_names: Vec, /// The loop that runs time slots, and the slots each loop ran. stats: SchedulerStats, /// The bits of the compiled scheduler's events whose changes the host @@ -184,6 +189,10 @@ pub struct SimulationState { observed_events: crate::schedule::EventMask, } +/// The most recent processes of a time slot that a slot that does not +/// settle reports. +const RESUMED_PROCESSES: usize = 64; + impl SimulationState { /// Bound the work of one time slot: `rounds` rounds and passes of the /// process phase, and `returns` kernel returns per round, before a step @@ -194,6 +203,12 @@ impl SimulationState { self.return_budget = returns; } + /// Name the processes, by index, in diagnostics such as a time slot + /// that does not settle. + pub fn set_process_names(&mut self, names: Vec) { + self.process_names = names; + } + /// Every process of `model` starts at time zero, in list order. pub fn new(backend: &B, model: ResolvedSchedule) -> Self { let process_state = ProcessState { @@ -243,6 +258,8 @@ impl SimulationState { round_budget: SLOT_ROUND_BUDGET, return_budget: SLOT_RETURN_BUDGET, slot_passes: 0, + slot_resumed: std::collections::VecDeque::new(), + process_names: Vec::new(), stats: SchedulerStats::default(), observed_events: Default::default(), }; @@ -585,6 +602,7 @@ impl SimulationState { E: SimulationExecutor, { self.slot_passes = 0; + self.slot_resumed.clear(); match self.step_round(executor, time, Vec::new(), Vec::new(), true, false) { Ok(()) => { self.finish_timed_boundary(executor, time)?; diff --git a/crates/celox-runtime/src/simulation/nba.rs b/crates/celox-runtime/src/simulation/nba.rs index f5f15c8a826..c79dbe36c74 100644 --- a/crates/celox-runtime/src/simulation/nba.rs +++ b/crates/celox-runtime/src/simulation/nba.rs @@ -32,19 +32,30 @@ impl SimulationState { let Some((lsb, width)) = refs.range(backend) else { return Ok(()); }; - // A program process's update waits for the Re-NBA region (IEEE - // 1800-2023 24.3.1). - let queue = if self.model.processes[process].program.is_some() { - &mut self.process_state.re_nba_queue - } else { - &mut self.process_state.nba_queue - }; - queue.push(NbaUpdate { + let program = self.model.processes[process].program.is_some(); + let update = NbaUpdate { target: refs.target, lsb, width, value: read(backend, refs.value), - }); + }; + if refs.delay > 0 { + let time = self.scheduler.time.checked_add(refs.delay).ok_or_else(|| { + Halt::Error(crate::SimulatorErrorCode::Runtime { + message: "nonblocking assignment delay overflows simulation time".into(), + signals: Vec::new(), + }) + })?; + self.process_state + .delayed_nba + .entry(time) + .or_default() + .push((program, update)); + } else if program { + self.process_state.re_nba_queue.push(update); + } else { + self.process_state.nba_queue.push(update); + } Ok(()) } diff --git a/crates/celox-runtime/src/simulation/persist.rs b/crates/celox-runtime/src/simulation/persist.rs index fff40333975..744ef1ce361 100644 --- a/crates/celox-runtime/src/simulation/persist.rs +++ b/crates/celox-runtime/src/simulation/persist.rs @@ -294,8 +294,10 @@ impl SimulationState { .map(|(process, waiter)| (process, waiter.clone())) .collect(), ready: state.ready.iter().copied().collect(), + deferred_ready: state.deferred_ready.iter().copied().collect(), inactive: state.inactive.iter().copied().collect(), nba_queue: state.nba_queue.clone(), + delayed_nba: state.delayed_nba.clone(), reactive: state.reactive.iter().copied().collect(), observed: state.observed.iter().copied().collect(), re_inactive: state.re_inactive.iter().copied().collect(), @@ -327,8 +329,10 @@ pub struct ScheduleKey { pub process_wakeups: Vec<(u64, usize)>, pub waiters: Vec<(usize, super::Waiter)>, pub ready: Vec, + pub deferred_ready: Vec, pub inactive: Vec, pub nba_queue: Vec, + pub delayed_nba: std::collections::BTreeMap>, pub reactive: Vec, pub observed: Vec, pub re_inactive: Vec, diff --git a/crates/celox-runtime/src/simulation/process.rs b/crates/celox-runtime/src/simulation/process.rs index e0845eaa12f..d3726063910 100644 --- a/crates/celox-runtime/src/simulation/process.rs +++ b/crates/celox-runtime/src/simulation/process.rs @@ -5,10 +5,10 @@ use std::collections::BTreeSet; use celox_design::{HostRequestKind, ProcessStatus}; -use super::SimulationState; use super::host::SimulationExecutor; use super::round::Round; use super::wait::wake_in_region; +use super::{RESUMED_PROCESSES, SimulationState}; use crate::{ SimulatorErrorCode, backend::SimBackend, @@ -127,6 +127,10 @@ impl SimulationState { where E: SimulationExecutor, { + if self.slot_resumed.len() == RESUMED_PROCESSES { + self.slot_resumed.pop_front(); + } + self.slot_resumed.push_back(process); let kernel = self.restore_activation(executor.backend_mut(), process); if let Some(activation) = self.process_state.activations.get_mut(process) { activation.control.level_wait = false; @@ -281,6 +285,12 @@ impl SimulationState { wake_in_region(&self.model.processes, ready, reactive, process); return Err(Halt::Stop); } + Some(ProcessStatus::DeferActive) => { + *returns += 1; + self.charge(*returns, Some(process))?; + self.process_state.deferred_ready.insert(process); + return Ok(false); + } Some(ProcessStatus::Yield) => { *returns += 1; self.charge(*returns, Some(process))?; @@ -384,6 +394,23 @@ impl SimulationState { } } + /// Choose these runnable Active/Reactive continuations after the ordinary + /// ready work, while still preceding the Inactive and NBA regions (4.7). + fn promote_deferred_ready(&mut self, reactive: bool) -> bool { + let continuations: Vec<_> = self + .process_state + .deferred_ready + .iter() + .copied() + .filter(|&index| self.model.processes[index].program.is_some() == reactive) + .collect(); + for &index in &continuations { + self.process_state.deferred_ready.remove(&index); + self.region_ready(reactive).insert(index); + } + !continuations.is_empty() + } + /// `$exit` of program kernel `process` (IEEE 1800-2023 24.7): every /// kernel of its program instance ends, as if it had run to its end. fn exit_program(&mut self, backend: &mut B, process: usize) -> Result<(), Halt> { @@ -413,6 +440,7 @@ impl SimulationState { let state = &mut self.process_state; state.waiters.remove(index); state.ready.remove(&index); + state.deferred_ready.remove(&index); state.reactive.remove(&index); state.re_inactive.remove(&index); } @@ -512,6 +540,9 @@ impl SimulationState { if !self.process_state.reactive.is_empty() { continue; } + if self.promote_deferred_ready(true) { + continue; + } if !self.process_state.re_inactive.is_empty() { let inactive = std::mem::take(&mut self.process_state.re_inactive); self.process_state.reactive.extend(inactive); @@ -527,6 +558,9 @@ impl SimulationState { if !self.process_state.ready.is_empty() { continue; } + if self.promote_deferred_ready(false) { + continue; + } if self.process_state.inactive.is_empty() { // A domain whose blocking results are observed commits them // in the active region: the processes they wake run before diff --git a/crates/celox-runtime/src/simulation/process_control.rs b/crates/celox-runtime/src/simulation/process_control.rs index 930173577ce..c5ef795a2de 100644 --- a/crates/celox-runtime/src/simulation/process_control.rs +++ b/crates/celox-runtime/src/simulation/process_control.rs @@ -107,8 +107,9 @@ impl SimulationState { backend: &B, ) -> SuspendedProcess { let state = &self.process_state; - let runnable = - target == current || state.ready.contains(&target) || state.reactive.contains(&target); + let runnable = target == current + || (state.ready.contains(&target) || state.deferred_ready.contains(&target)) + || state.reactive.contains(&target); let wake_time = self .process_wakeups .iter() @@ -121,6 +122,7 @@ impl SimulationState { self.process_slot(backend, current, target, self.model.processes[target].delay) }); self.process_state.ready.remove(&target); + self.process_state.deferred_ready.remove(&target); self.process_state.reactive.remove(&target); self.process_state.inactive.remove(&target); self.process_state.re_inactive.remove(&target); @@ -235,7 +237,8 @@ impl SimulationState { 3 } else if target == current || Some(target) == final_identity - || self.process_state.ready.contains(&target) + || (self.process_state.ready.contains(&target) + || self.process_state.deferred_ready.contains(&target)) || self.process_state.reactive.contains(&target) { 1 diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index db0756e15eb..e2775463b6b 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -149,6 +149,16 @@ impl SimulationState { { self.host_pending = false; self.slot_passes = 0; + self.slot_resumed.clear(); + if let Some(updates) = self.process_state.delayed_nba.remove(¤t_time) { + for (program, update) in updates { + if program { + self.process_state.re_nba_queue.push(update); + } else { + self.process_state.nba_queue.push(update); + } + } + } let events_to_process = if self.scheduler.next_event_time() == Some(current_time) { self.scheduler .pop_all_at_next_time() @@ -266,15 +276,32 @@ impl SimulationState { if returns <= budget { return Ok(()); } + let name = |process: usize| { + self.process_names + .get(process) + .cloned() + .unwrap_or_else(|| format!("process {process}")) + }; Err(Halt::Error(SimulatorErrorCode::Runtime { message: match process { Some(process) => { - format!("process {process} does not suspend within one time slot") + format!("{} does not suspend within one time slot", name(process)) + } + None => { + let mut resumed: Vec = self.slot_resumed.iter().copied().collect(); + resumed.sort_unstable(); + resumed.dedup(); + let resumed: Vec = resumed.into_iter().map(name).collect(); + format!( + "time {} does not settle: processes keep resuming{}", + self.scheduler.time, + if resumed.is_empty() { + String::new() + } else { + format!(": {}", resumed.join(", ")) + } + ) } - None => format!( - "time {} does not settle: processes keep resuming", - self.scheduler.time - ), }, signals: Vec::new(), })) @@ -324,11 +351,21 @@ impl SimulationState { if self.finalizing.is_some() || !self.process_state.observed.is_empty() || !self.process_state.ready.is_empty() + || !self.process_state.deferred_ready.is_empty() || !self.process_state.reactive.is_empty() { return Some(self.scheduler.time); } let process = self.process_wakeups.peek().map(|&Reverse((time, _))| time); + let delayed_nba = self + .process_state + .delayed_nba + .first_key_value() + .map(|(&time, _)| time); + let process = match (process, delayed_nba) { + (Some(process), Some(nba)) => Some(process.min(nba)), + (process, nba) => process.or(nba), + }; match (self.scheduler.next_event_time(), process) { (Some(event), Some(process)) => Some(event.min(process)), (event, process) => event.or(process), diff --git a/crates/celox-runtime/src/state_file.rs b/crates/celox-runtime/src/state_file.rs index 42facd57959..00adae0ea22 100644 --- a/crates/celox-runtime/src/state_file.rs +++ b/crates/celox-runtime/src/state_file.rs @@ -54,12 +54,13 @@ //! builds read too. Static-only process schedules retain version 2; graphs //! and reactive queues require version 3. Pending Observed assertion evaluations //! require version 4, and a heap section version 5. Versions 1 through 4 -//! remain readable. +//! remain readable. Version 6 adds future NBA updates after the Observed queue; +//! older versions remain readable and are still written when sufficient. use std::io::{self, Read, Write}; const MAGIC: &[u8; 8] = b"CXSTATE\0"; -const VERSION: u16 = 5; +const VERSION: u16 = 6; mod activations; use activations::*; @@ -148,10 +149,13 @@ pub struct ProcessRecord { pub waiters: Vec, /// Processes ready in the active region of the current time. pub ready: Vec, + pub deferred_ready: Vec, /// Processes resuming in the inactive region of the current time. pub inactive: Vec, /// Queued nonblocking assignments, in issue order. pub nba_queue: Vec, + /// Future updates: due time, Re-NBA region, captured assignment. + pub delayed_nba: Vec<(u64, bool, NbaRecord)>, /// Counter values each counted domain last triggered on, by counted /// signal, in changes/rises/falls order. pub domain_counters: Vec<(String, [u32; 3])>, @@ -259,7 +263,9 @@ impl StateFile { .map(|schedule| &schedule.processes) .filter(|processes| **processes != ProcessRecord::default()); let version = processes.map_or(1, |p| { - if !p.observed.is_empty() { + if !p.delayed_nba.is_empty() || !p.deferred_ready.is_empty() { + 6 + } else if !p.observed.is_empty() { 4 } else if needs_v3(p) { 3 @@ -270,7 +276,7 @@ impl StateFile { // A heap section needs version 5, which always lists processes. let empty = ProcessRecord::default(); let (version, processes) = match (self.next_object, &self.schedule) { - (Some(_), Some(_)) => (5, Some(processes.unwrap_or(&empty))), + (Some(_), Some(_)) => (version.max(5), Some(processes.unwrap_or(&empty))), (Some(_), None) => (5, processes), (None, _) => (version, processes), }; @@ -633,6 +639,19 @@ fn put_processes(w: &mut impl Write, processes: &ProcessRecord, version: u16) -> if version >= 4 { put_process_list(w, &processes.observed, version)?; } + if version >= 6 { + put_len(w, processes.delayed_nba.len())?; + for (time, program, update) in &processes.delayed_nba { + put_u64(w, *time)?; + w.write_all(&[u8::from(*program)])?; + put_str(w, &update.target)?; + put_u64(w, update.lsb)?; + put_u64(w, update.width)?; + put_bytes(w, &update.value)?; + put_bytes(w, &update.mask)?; + } + put_process_list(w, &processes.deferred_ready, version)?; + } Ok(()) } @@ -727,6 +746,24 @@ fn get_processes(r: &mut impl Read, version: u16) -> Result= 4 { result.observed = get_process_list(r, version)?; } + if version >= 6 { + result.delayed_nba = (0..get_u32(r)?) + .map(|_| { + Ok(( + get_u64(r)?, + get_flag(r)?, + NbaRecord { + target: get_str(r)?, + lsb: get_u64(r)?, + width: get_u64(r)?, + value: get_len_bytes(r)?, + mask: get_len_bytes(r)?, + }, + )) + }) + .collect::>()?; + result.deferred_ready = get_process_list(r, version)?; + } Ok(result) } @@ -879,6 +916,17 @@ mod tests { assert_eq!(StateFile::read_from(bytes.as_slice()).unwrap(), file); } + #[test] + fn deferred_active_continuations_keep_their_queue_in_version_six() { + let mut file = sample(); + file.schedule.as_mut().unwrap().processes.deferred_ready = + vec!["$process[4].status".into()]; + let mut bytes = Vec::new(); + file.write_to(&mut bytes).unwrap(); + assert_eq!(bytes[8..10], 6u16.to_le_bytes()); + assert_eq!(StateFile::read_from(bytes.as_slice()).unwrap(), file); + } + #[test] fn files_without_process_state_are_version_1() { let mut file = sample(); diff --git a/crates/celox-runtime/src/timing.rs b/crates/celox-runtime/src/timing.rs index d67858af177..276d2210fde 100644 --- a/crates/celox-runtime/src/timing.rs +++ b/crates/celox-runtime/src/timing.rs @@ -227,6 +227,7 @@ pub struct TermRefs { /// A nonblocking assignment site. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct NbaSiteRefs { + pub delay: u64, pub target: SignalRef, pub lsb: usize, pub width: usize, @@ -436,10 +437,16 @@ pub struct ProcessState { pub waiters: Waiters, /// Processes ready to run in the active region of the current time. pub ready: std::collections::BTreeSet, + /// Runnable continuations placed after other work of their current region. + #[serde(default)] + pub deferred_ready: std::collections::BTreeSet, /// Processes that resume in the inactive region (`#0`). pub inactive: std::collections::BTreeSet, /// Queued nonblocking assignments, in issue order. pub nba_queue: Vec, + /// Future NBA and Re-NBA updates, in issue order at each time. + #[serde(default)] + pub delayed_nba: std::collections::BTreeMap>, /// Program processes ready to run in the Reactive region of the current /// time (IEEE 1800-2023 4.4.2.6). pub reactive: std::collections::BTreeSet, diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index 1e2fa6d2445..d2982f82485 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -2959,6 +2959,12 @@ pub struct CombProcess { } impl CombProcess { + /// Where an `always` procedure is written, for diagnostics about it as + /// a process. + pub fn process_site(&self) -> Option<&crate::procedural::ProcessSite> { + self.process_site.as_ref() + } + pub fn site(&self) -> Option<&crate::procedural::SourceSpan> { self.site.as_ref() } diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 2378a33b2c9..a4c51a4614c 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -1803,10 +1803,15 @@ impl<'a> Frame<'a> { // diagnostic belongs to the declaration, not to evaluation. Stmt::SystemTask { .. } => {} // A function has no timing controls (IEEE 1800-2023 13.4). - Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::WaitImplicit(_) | Stmt::Wait(_) => { + Stmt::DelayedNonblocking { .. } + | Stmt::Delay { .. } + | Stmt::WaitEvent(_) + | Stmt::WaitImplicit(_) + | Stmt::Wait(_) => { return None; } Stmt::Fork { .. } + | Stmt::DeferActive | Stmt::AssertionRegion { .. } | Stmt::WaitFork | Stmt::DisableFork diff --git a/crates/celox-sv-analyzer/src/ast/lifetimes.rs b/crates/celox-sv-analyzer/src/ast/lifetimes.rs index f558f699d08..a408fe2fadd 100644 --- a/crates/celox-sv-analyzer/src/ast/lifetimes.rs +++ b/crates/celox-sv-analyzer/src/ast/lifetimes.rs @@ -640,6 +640,13 @@ impl Flow<'_> { fn stmt(&self, stmt: &Stmt, written: bool) -> Result { match stmt { + Stmt::DelayedNonblocking { + control, + assignment, + } => { + self.stmt(control, written)?; + self.stmt(assignment, written) + } Stmt::Assign { lhs, rhs, @@ -815,9 +822,10 @@ impl Flow<'_> { self.read(expr, written)?; Ok(Exits::next(written)) } - Stmt::AssertionRegion { .. } | Stmt::WaitFork | Stmt::DisableFork => { - Ok(Exits::next(written)) - } + Stmt::DeferActive + | Stmt::AssertionRegion { .. } + | Stmt::WaitFork + | Stmt::DisableFork => Ok(Exits::next(written)), Stmt::WaitEvent(items) => { for item in items { self.read(&item.expr, written)?; @@ -976,7 +984,9 @@ pub(super) fn stmt_exprs(stmt: &Stmt) -> Vec<&Expr> { .flat_map(|item| std::iter::once(&item.expr).chain(&item.iff)) .collect(), // The statements of an `@*` describe its reads and do not run. - Stmt::Fork { .. } + Stmt::DelayedNonblocking { .. } + | Stmt::Fork { .. } + | Stmt::DeferActive | Stmt::AssertionRegion { .. } | Stmt::WaitFork | Stmt::DisableFork diff --git a/crates/celox-sv-analyzer/src/ast/procedural/intra_assignment.rs b/crates/celox-sv-analyzer/src/ast/procedural/intra_assignment.rs index 94693a88388..9a6ca1ca7a3 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural/intra_assignment.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural/intra_assignment.rs @@ -1,4 +1,4 @@ -//! Blocking intra-assignment controls (IEEE 1800-2023 9.4.5, 10.4.1). +//! Intra-assignment controls (IEEE 1800-2023 9.4.5, 10.4.1, 10.4.2). use super::*; use celox_sv_syntax::{ExprId, TimingControlId}; @@ -12,10 +12,7 @@ impl BodyBuilder<'_, '_, '_> { control: Option, repeat_count: Option, ) -> Converted> { - if nonblocking { - return Err(unsupported("nonblocking intra-assignment timing control")); - } - if operator != "=" { + if operator != "=" && !nonblocking { return Err(unsupported("compound assignment with a timing control")); } self.allow_timing("intra-assignment timing control")?; @@ -40,6 +37,19 @@ impl BodyBuilder<'_, '_, '_> { { return Err(unsupported("nonintegral intra-assignment target")); } + if nonblocking { + let delay = self.native_timing_control(control)?; + if repeat_count.is_some() || !matches!(delay, Stmt::Delay { .. }) { + return Err(unsupported("nonblocking intra-assignment event control")); + } + output.extend(target_effects); + let assignment = self.assignment_value("=", true, (left, right))?; + output.push(Stmt::DelayedNonblocking { + control: Box::new(delay), + assignment: Box::new(assignment), + }); + return Ok(output); + } let ty = shape .pattern_type(&self.tree.functions, &self.dims) .ok_or_else(|| unsupported("intra-assignment target type"))?; @@ -130,15 +140,10 @@ mod tests { #[test] fn keeps_unimplemented_assignment_controls_explicit() { for (declarations, statement, diagnostic) in [ - ( - "bit a,b,clk;", - "a <= #1 b;", - "nonblocking intra-assignment timing control", - ), ( "bit a,b,clk;", "a <= repeat(2) @(posedge clk) b;", - "nonblocking intra-assignment timing control", + "nonblocking intra-assignment event control", ), ( "bit a,b,clk; logic [128:0] n=1;", diff --git a/crates/celox-sv-analyzer/src/ast/validation.rs b/crates/celox-sv-analyzer/src/ast/validation.rs index f5323941352..12aa47a1cd9 100644 --- a/crates/celox-sv-analyzer/src/ast/validation.rs +++ b/crates/celox-sv-analyzer/src/ast/validation.rs @@ -65,9 +65,8 @@ pub(super) fn always_kind( }) } -/// Native statement traversal excludes intra-assignment controls, matching the -/// existing process-classification contract. Typed leaf restrictions remain in -/// their semantic binders. +/// Timing controls, including delayed assignments, require process kernels. +/// Typed leaf restrictions remain in their semantic binders. fn has_timing_control( root: celox_sv_syntax::StatementId, native: &celox_sv_syntax::Declarations, @@ -78,7 +77,10 @@ fn has_timing_control( let statement = native.statement(id); if matches!( statement.kind, - StatementKind::Timing { .. } + StatementKind::Assignment { + timing: Some(_), + .. + } | StatementKind::Timing { .. } | StatementKind::Assertion { header: celox_sv_syntax::AssertionHeader::Concurrent { .. }, .. diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 517e50e2b90..40781d1f469 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -154,6 +154,95 @@ impl Module { self } + /// Run selected `always @*` processes, by index among + /// [`Self::comb_processes`], as ordinary processes that wait on their + /// implicit event expression (IEEE 1800-2023 9.4.2.2) before each run of + /// their statement. + pub fn run_comb_processes_as_processes( + self, + mut select: impl FnMut(usize, &CombProcess) -> bool, + ) -> Self { + self.run_comb_processes_with_deferred_rearm(|index, process| { + select(index, process).then_some(false) + }) + } + + /// Like `run_comb_processes_as_processes`: `None` keeps a combinational + /// process, `Some(false)` converts it, and `Some(true)` additionally lets + /// other Active work run between its body and its next implicit wait (4.7). + pub fn run_comb_processes_with_deferred_rearm( + mut self, + mut select: impl FnMut(usize, &CombProcess) -> Option, + ) -> Self { + let mut retained = Vec::new(); + for (index, process) in std::mem::take(&mut self.comb_processes) + .into_iter() + .enumerate() + { + let selection = (process.kind == CombProcessKind::AlwaysStar) + .then(|| select(index, &process)) + .flatten(); + let Some(defer_rearm) = selection else { + retained.push(process); + continue; + }; + // The reads of branches that constant folding removed count too. + let reads = process + .body + .iter() + .chain(&process.sensitivity_body) + .cloned() + .collect(); + let mut body = vec![Stmt::WaitImplicit(reads)]; + body.extend(process.body); + if defer_rearm { + body.push(Stmt::DeferActive); + } + self.initial_processes.push(InitialProcess { + creation_order: process.creation_order, + site: process.process_site, + scheduled_edge: false, + condition: process.condition, + body: vec![Stmt::Loop { + kind: LoopKind::Forever, + init: Vec::new(), + condition: None, + step: Vec::new(), + body, + }], + kind: celox_design::ProcessKind::Regular, + synthetic: false, + repeats: true, + }); + } + self.comb_processes = retained; + self.initial_processes + .sort_by_key(|process| (!process.is_initializer(), process.creation_order)); + self + } + + /// Rewrite the statements of the combinational processes, by index + /// among [`Self::comb_processes`]: their bodies, and the statements that + /// only describe their implicit sensitivity (`true`; see + /// [`CombProcess::sensitivity_body`]). + pub fn map_comb_process_bodies( + mut self, + mut rewrite: impl FnMut(usize, Vec, bool) -> Vec, + ) -> Self { + for (index, process) in self.comb_processes.iter_mut().enumerate() { + process.body = rewrite(index, std::mem::take(&mut process.body), false); + process.sensitivity_body = + rewrite(index, std::mem::take(&mut process.sensitivity_body), true); + } + self + } + + /// Declare a variable local to a procedural block (see [`Self::locals`]). + pub fn add_local(mut self, local: LocalVariable) -> Self { + self.locals.push(local); + self + } + /// Represent selected [`InitialProcess::level_sensitive`] processes as /// `always @*`. The caller selects a process only when its list is the /// implicit event expression of its statement (IEEE 1800-2023 9.4.2.2). @@ -1162,6 +1251,9 @@ impl LValue { pub struct CombProcess { creation_order: usize, site: Option, + /// Where an `always` procedure is written, for diagnostics about it as + /// a process. + process_site: Option, kind: CombProcessKind, condition: Option, assignments: Vec, @@ -1174,6 +1266,11 @@ impl CombProcess { self.site.as_ref() } + /// Where an `always` procedure is written, as a process. + pub fn process_site(&self) -> Option<&ProcessSite> { + self.process_site.as_ref() + } + /// Reads removed from executable branches still affect implicit sensitivity. pub fn sensitivity_body(&self) -> &[Stmt] { &self.sensitivity_body @@ -1193,6 +1290,7 @@ impl CombProcess { Self { creation_order: 0, site: None, + process_site: None, sensitivity_body: Vec::new(), kind, condition, @@ -1695,6 +1793,7 @@ impl From for CombProcess { ); result.creation_order = process.creation_order(); result.site = process.site().cloned(); + result.process_site = process.process_site().cloned(); result.sensitivity_body = process .sensitivity_body() .iter() diff --git a/crates/celox-sv-analyzer/src/lib.rs b/crates/celox-sv-analyzer/src/lib.rs index 26ba12f41de..ec3c4371b1c 100644 --- a/crates/celox-sv-analyzer/src/lib.rs +++ b/crates/celox-sv-analyzer/src/lib.rs @@ -57,6 +57,12 @@ pub struct AnalysisOptions { /// Compatibility mode: return zero for every empty array reduction, /// rather than the product/bitwise-AND identity. Disabled by default. pub legacy_empty_reductions: bool, + /// Treat a variable that only several `always @*` blocks write, each + /// before it reads it, and that nothing else reads, as a temporary of + /// each block, instead of a variable whose writes wake the other blocks + /// (IEEE 1800-2023 9.4.2.2). Off by default; see the + /// `shared_always_temporary` diagnostic. + pub shared_always_temporaries: bool, /// Default unit/precision exponents; precision also bounds global resolution. pub default_timescale: Option<(i32, i32)>, /// The virtual interfaces of the design (IEEE 1800-2023 25.9), which the diff --git a/crates/celox-sv-analyzer/src/procedural.rs b/crates/celox-sv-analyzer/src/procedural.rs index 18d1e32321b..ffb1a5263f7 100644 --- a/crates/celox-sv-analyzer/src/procedural.rs +++ b/crates/celox-sv-analyzer/src/procedural.rs @@ -59,6 +59,12 @@ pub enum StmtBase { rhs: E, nonblocking: bool, }, + /// A nonblocking assignment scheduled by an intra-assignment delay. + /// The control describes the delay; it does not suspend the caller. + DelayedNonblocking { + control: Box>, + assignment: Box>, + }, If { condition: E, then_body: Vec>, @@ -135,6 +141,8 @@ pub enum StmtBase { WaitImplicit(Vec>), WaitFork, DisableFork, + /// An internal scheduling boundary in the current Active region (4.7). + DeferActive, /// Internal region boundary of a concurrent assertion monitor. AssertionRegion { reactive: bool, @@ -273,6 +281,13 @@ impl StmtBase { stmts.into_iter().map(|stmt| stmt.map(fe, fl)).collect() } match self { + StmtBase::DelayedNonblocking { + control, + assignment, + } => StmtBase::DelayedNonblocking { + control: Box::new(control.map(fe, fl)), + assignment: Box::new(assignment.map(fe, fl)), + }, StmtBase::Assign { lhs, rhs, @@ -405,6 +420,7 @@ impl StmtBase { .collect(), ), StmtBase::AssertionRegion { reactive } => StmtBase::AssertionRegion { reactive }, + StmtBase::DeferActive => StmtBase::DeferActive, StmtBase::WaitFork => StmtBase::WaitFork, StmtBase::DisableFork => StmtBase::DisableFork, StmtBase::Wait(condition) => StmtBase::Wait(fe(condition)), @@ -431,6 +447,13 @@ impl StmtBase { } } match self { + StmtBase::DelayedNonblocking { + control, + assignment, + } => { + control.visit_mut(fe, fl, fname); + assignment.visit_mut(fe, fl, fname); + } StmtBase::Assign { lhs, rhs, .. } => { fl(lhs); fe(rhs); @@ -528,7 +551,10 @@ impl StmtBase { } } } - StmtBase::WaitFork | StmtBase::DisableFork | StmtBase::AssertionRegion { .. } => {} + StmtBase::DeferActive + | StmtBase::WaitFork + | StmtBase::DisableFork + | StmtBase::AssertionRegion { .. } => {} StmtBase::Wait(condition) => fe(condition), StmtBase::WaitImplicit(reads) => body(reads, fe, fl, fname), } @@ -543,6 +569,13 @@ impl StmtBase { } }; match self { + StmtBase::DelayedNonblocking { + control, + assignment, + } => { + control.walk_mut(f); + assignment.walk_mut(f); + } StmtBase::If { then_body, else_body, @@ -596,6 +629,13 @@ impl StmtBase { } }; match self { + StmtBase::DelayedNonblocking { + control, + assignment, + } => { + control.walk_scoped(f, detached); + assignment.walk_scoped(f, detached); + } StmtBase::If { then_body, else_body, diff --git a/crates/celox-sv-analyzer/src/tests.rs b/crates/celox-sv-analyzer/src/tests.rs index 0d08f13b494..8006e069371 100644 --- a/crates/celox-sv-analyzer/src/tests.rs +++ b/crates/celox-sv-analyzer/src/tests.rs @@ -3563,10 +3563,6 @@ fn rejects_unimplemented_timing_constructs() { "event e; logic c; initial @(e or posedge c);", "event control mixing named events with other events", ), - ( - "logic a, b; initial a <= #1 b;", - "nonblocking intra-assignment timing control", - ), ("initial begin : b disable b; end", "disable statement"), ( "logic a, y; always_latch y <= a;", diff --git a/crates/celox-test-suite/src/sv/cases/procedural.vtest b/crates/celox-test-suite/src/sv/cases/procedural.vtest index 8820469d8f8..32f8bbb78d8 100644 --- a/crates/celox-test-suite/src/sv/cases/procedural.vtest +++ b/crates/celox-test-suite/src/sv/cases/procedural.vtest @@ -123,9 +123,45 @@ (assert_eq prev 8) (assert_eq i_q 8)) +; Level-sensitive always processes may share a variable as well (IEEE +; 1800-2023 6.5, 9.2.2), and each waits on the variables it reads (9.4.2.2): +; here the second block's writes to `j` wake the first one, which reads it, +; while the first block's loop writes wake nothing. Which block writes `j` +; last is not defined, so the output leaves it out. +(case level_processes_share_a_written_variable + (source "shared_level.sv" #" + module Top; + logic [3:0] a, b; + logic any_a, any_b; + integer j; + always @(*) begin + any_a = 1'b0; + for (j = 0; j < 4; j = j + 1) any_a = any_a | a[j]; + end + always @(*) begin + j = 0; + any_b = b[1]; + end + initial begin + a = 4'b0000; + b = 4'b0000; + #1 $display("%b %b", any_a, any_b); + a = 4'b0100; + #1 $display("%b %b", any_a, any_b); + b = 4'b0010; + #1 $display("%b %b", any_a, any_b); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "0 0\n1 0\n1 1\n")) + ; Processes of different clocks share a variable. A write at one edge is ; visible to a process of a later edge, and survives a coincident edge whose ; process does not write the variable. + (case edge_processes_of_two_clocks_share_a_blocking_variable (source "shared_clocks.sv" #" module Top(input logic ca, input logic cb, input logic en, diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 7265940ccf1..d9d77c60423 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -3256,6 +3256,145 @@ endmodule (run_to_finish) (expect_output "final value=31\n")) +; IEEE 1800-2023 10.4.2: delayed NBA updates capture values and positions +; immediately, preserve issue order, and do not suspend the caller. +(case wildcard_blocks_with_crossing_output_dependencies + (source "crossing_outputs.sv" #" +module Top; + reg [7:0] s=0, t=0, a, b, x, y; + always @* begin a=s; x=b+1; end + always @* begin b=t; y=a+1; end + initial begin + #1 s=3; t=5; + #1 $display("%0d %0d %0d %0d", a, b, x, y); + $finish; + end +endmodule +"#) + (top Top) + (run_to_finish) + (expect_output "3 5 6 4\n")) + +(case wildcard_blocks_in_a_converging_feedback_loop + (source "converging_wildcards.sv" #" +module Top; + reg [7:0] a, b; + always @* b=(a<4) ? a : 8'd3; + always @* a=(b<4) ? b+8'd1 : b; + initial begin + #1 a=1; + #1 $display("%0d %0d", a, b); + $finish; + end +endmodule +"#) + (top Top) + (run_to_finish) + (expect_output "4 3\n")) + +(case nonblocking_intra_assignment_delays + (source "delayed_nba.sv" #" +module Top; + reg [7:0] q=0, rhs=8'h11, zero=0; + initial begin + q <= #3 rhs; + rhs=8'h22; + q <= #5 rhs; + #1 q <= #2 8'h33; + #1 $display("before %h", q); + #2 $display("ordered %h", q); + zero <= #0 rhs; + rhs=8'h44; + #2 $display("after %h zero %h", q, zero); + $finish; + end +endmodule +"#) + (top Top) + (run_to_finish) + (expect_output "before 00\nordered 33\nafter 22 zero 22\n")) + +(case nonblocking_intra_assignment_positions + (source "delayed_position.sv" #" +module Top; + reg [15:0] q=0; + integer index=0, bit_index=0; + reg [7:0] bits=0; + reg [3:0] rhs=1; + initial begin + bits[bit_index++] <= #2 1'b1; + bits[bit_index++] <= #2 1'b0; + $display("positions %0d", bit_index); + q[index +: 4] <= #2 rhs; + index=4; rhs=2; + q[index +: 4] <= #2 rhs; + index=8; rhs=3; + #3 $display("%h", q); + $display("%h %0d", bits, bit_index); + $finish; + end +endmodule +"#) + (top Top) + (run_to_finish) + (expect_output "positions 2\n0021\n01 2\n")) + +(case nonblocking_intra_assignment_four_state + (source "delayed_four_state.sv" #" +module Top; + reg [3:0] q=0, rhs=4'bxz01; + initial begin + q <= #2 rhs; + rhs='1; + #1 $display("%b", q); + #2 $display("%b", q); + $finish; + end +endmodule +"#) + (top Top) + (four_state) + (run_to_finish) + (expect_output "0000\nxz01\n")) + +(case nonblocking_intra_assignment_flip_flop + (source "delayed_flop.sv" #" +module Top; + reg clk=0, rst_n=1, d=0; + reg q; + always @(posedge clk or negedge rst_n) + if (!rst_n) q <= #1 0; + else q <= #1 d; + initial begin + #1 rst_n=0; + #2 $display("reset %b", q); + rst_n=1; d=1; + #1 clk=1; + #1 d=0; + #1 $display("data %b", q); + $finish; + end +endmodule +"#) + (top Top) + (run_to_finish) + (expect_output "reset 0\ndata 1\n")) + +(case nonblocking_intra_assignment_outlives_caller + (source "delayed_done.sv" #" +module Top; + reg q=0; + initial q <= #2 1; + always @(q) if (q) begin + $display("updated"); + $finish; + end +endmodule +"#) + (top Top) + (run_to_finish) + (expect_output "updated\n")) + ; IEEE 1800-2023 9.4.5/10.4.1: snapshot and convert the RHS before waiting; ; evaluate the destination, including its effects, after the wait. (case blocking_intra_assignment_delays diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 0c1979652e2..af065a1b347 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -10,8 +10,8 @@ use std::{ use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -// Images retain the scheduler's slots and the reads of TB settle requests. -const CONTAINER_VERSION: u16 = 56; +// Nonblocking sites retain their update delay in global precision ticks. +const CONTAINER_VERSION: u16 = 57; const TRAILER_SIZE: usize = 32; // This optional prefix descriptor does not change the Postcard payload. Older // readers ignore framing flags and continue to locate the payload at EOF. diff --git a/crates/celox/src/diagnostic_policy.rs b/crates/celox/src/diagnostic_policy.rs index b500344115d..7a771a40e71 100644 --- a/crates/celox/src/diagnostic_policy.rs +++ b/crates/celox/src/diagnostic_policy.rs @@ -85,6 +85,7 @@ impl DiagnosticPolicy { if matches!( code, "mixed_timescale" + | "shared_always_temporary" | "interface_array_query" | "interface_array_parameter" | "unpacked_port_default" @@ -106,6 +107,8 @@ impl DiagnosticPolicy { ) -> celox_frontend_sv::AnalysisOptions { celox_frontend_sv::AnalysisOptions { allow_mixed_timescales: self.level("mixed_timescale") != DiagnosticLevel::Error, + shared_always_temporaries: self.level("shared_always_temporary") + != DiagnosticLevel::Error, default_timescale: timescale.map(|scale| (scale.unit, scale.precision)), legacy_empty_reductions, ..Default::default() diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index e3fd77ba219..ae5e4ed98d8 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -477,10 +477,20 @@ impl Simulation { // ── Generic methods available for any backend ─────────────────────── pub(crate) fn simulation_state(simulator: &Simulator) -> SimulationState { - SimulationState::new( + let mut state = SimulationState::new( &simulator.backend, ResolvedSchedule::resolve(&simulator.backend, &simulator.schedule), - ) + ); + state.set_process_names( + simulator + .program + .runtime_schema + .process_origins + .iter() + .map(ToString::to_string) + .collect(), + ); + state } impl Simulation { diff --git a/crates/celox/src/simulation/checkpoint_file.rs b/crates/celox/src/simulation/checkpoint_file.rs index be5fafaf83c..e287b90f3be 100644 --- a/crates/celox/src/simulation/checkpoint_file.rs +++ b/crates/celox/src/simulation/checkpoint_file.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; const MAGIC: &[u8; 8] = b"CELOXCP1"; // Bump whenever a serialized core-state schema or its interpretation changes. -const VERSION: u32 = 2; +const VERSION: u32 = 3; #[derive(Debug, thiserror::Error)] pub enum CheckpointFileError { diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 7ee2f360a54..5a3dfa7763d 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -664,7 +664,34 @@ impl Simulator { }) .collect(), ready: state.ready.iter().map(|&index| process(index)).collect(), + deferred_ready: state + .deferred_ready + .iter() + .map(|&index| process(index)) + .collect(), inactive: state.inactive.iter().map(|&index| process(index)).collect(), + delayed_nba: state + .delayed_nba + .iter() + .flat_map(|(&time, updates)| { + updates + .iter() + .map(|(program, update)| { + ( + time, + *program, + NbaRecord { + target: path(update.target), + lsb: update.lsb as u64, + width: update.width as u64, + value: update.value.0.to_bytes_le(), + mask: update.value.1.to_bytes_le(), + }, + ) + }) + .collect::>() + }) + .collect(), nba_queue: state .nba_queue .iter() @@ -800,6 +827,7 @@ impl Simulator { .filter_map(|(name, time)| Some((process(name)?, *time))) .collect(); let ready = record.ready.iter().filter_map(process).collect(); + let deferred_ready = record.deferred_ready.iter().filter_map(process).collect(); let inactive = record.inactive.iter().filter_map(process).collect(); let reactive = record.reactive.iter().filter_map(process).collect(); let observed = record.observed.iter().filter_map(process).collect(); @@ -927,7 +955,12 @@ impl Simulator { ); } let mut nba_queue = Vec::new(); - for update in record.nba_queue.iter().chain(&record.re_nba_queue) { + for update in record + .nba_queue + .iter() + .chain(&record.re_nba_queue) + .chain(record.delayed_nba.iter().map(|(_, _, update)| update)) + { match signals.get(&update.target) { // A queued assignment covers a nonempty range of its target. Some(&target) @@ -954,7 +987,18 @@ impl Simulator { None => unknown.push(update.target.clone()), } } - let re_nba_queue = nba_queue.split_off(record.nba_queue.len().min(nba_queue.len())); + let mut re_nba_queue = nba_queue.split_off(record.nba_queue.len().min(nba_queue.len())); + let delayed = re_nba_queue.split_off(record.re_nba_queue.len().min(re_nba_queue.len())); + let mut delayed_nba = BTreeMap::<_, Vec<_>>::new(); + for ((time, program, _), update) in record.delayed_nba.iter().zip(delayed) { + if *time <= file.schedule.as_ref().map_or(0, |schedule| schedule.time) { + unknown.push("nonblocking assignment is not in the future".into()); + } + delayed_nba + .entry(*time) + .or_default() + .push((*program, update)); + } let counted = self.counted_signals(); let mut domain_counters = vec![[0; 3]; counted.len()]; for (name, counters) in &record.domain_counters { @@ -1025,8 +1069,10 @@ impl Simulator { cells, waiters, ready, + deferred_ready, inactive, nba_queue, + delayed_nba, reactive, observed, re_inactive, diff --git a/crates/celox/src/simulator/state_file/activations.rs b/crates/celox/src/simulator/state_file/activations.rs index 44fba57c4d4..c2d9e77ba17 100644 --- a/crates/celox/src/simulator/state_file/activations.rs +++ b/crates/celox/src/simulator/state_file/activations.rs @@ -629,6 +629,7 @@ impl Simulator { .map(|(id, _)| id) .chain(record.waiters.iter().map(|w| &w.process)) .chain(&record.ready) + .chain(&record.deferred_ready) .chain(&record.inactive) .chain(&record.reactive) .chain(&record.observed) diff --git a/crates/celox/tests/frontends/systemverilog/procedural.rs b/crates/celox/tests/frontends/systemverilog/procedural.rs index 0c1eaee2b1d..34183a9fd45 100644 --- a/crates/celox/tests/frontends/systemverilog/procedural.rs +++ b/crates/celox/tests/frontends/systemverilog/procedural.rs @@ -50,6 +50,9 @@ fn native_merged_optimization_preserves_large_and_wide_array_boundaries() { } sv_backends! { + fn level_processes_share_a_written_variable(sim) { + @case "procedural::level_processes_share_a_written_variable"; + } fn constant_functions_evaluate_wide_address_tables(sim) { @case "procedural::constant_functions_evaluate_wide_address_tables"; } @@ -295,3 +298,188 @@ sv_backends! { @case "procedural::dpi_exports_leave_subroutines_unchanged"; } } + +/// Two `always @*` blocks that use a module-level variable as their loop +/// index (#2129). Each block's writes to `j` wake the other, which reads it +/// (IEEE 1800-2023 9.4.2.2); whether they settle depends on the permitted +/// Active-region interleaving (4.7). +const SHARED_INDEX: &str = r#"`timescale 1ns/1ns +module top; + reg [3:0] a = 4'b0000; + reg [3:0] b = 4'b0000; + reg any_a, any_b; + integer j; + always @(*) begin + any_a = 1'b0; + for (j = 0; j < 4; j = j + 1) any_a = any_a | a[j]; + end + always @(*) begin + any_b = 1'b0; + for (j = 0; j < 4; j = j + 1) any_b = any_b | b[j]; + end + initial begin + #1 a = 4'b0100; + #1 b = 4'b0010; + #1 $display("%b %b", any_a, any_b); + $finish; + end +endmodule +"#; + +fn shared_index( + source: &str, + level: Option, +) -> Result { + let mut policy = celox::DiagnosticPolicy::default(); + if let Some(level) = level { + policy.set("shared_always_temporary", level); + } + celox::Simulation::from_sv_sources(vec![(source, Path::new("shared.sv"))], "top") + .diagnostic_policy(policy) + .build() +} + +fn display_lines(sim: &mut celox::Simulation) -> Vec { + sim.drain_runtime_events() + .into_iter() + .filter_map(|event| match event { + celox::RuntimeEvent::Display { message } => { + Some(String::from_utf8_lossy(&message).into_owned()) + } + _ => None, + }) + .collect() +} + +/// The time the blocks keep waking each other, and both blocks. +fn assert_does_not_settle(mut sim: celox::Simulation) { + let error = sim.run_until(10).unwrap_err().to_string(); + assert!(error.contains("does not settle"), "{error}"); + assert!(error.contains("shared.sv:7:"), "{error}"); + assert!(error.contains("shared.sv:11:"), "{error}"); +} + +#[test] +fn level_blocks_sharing_an_isolated_loop_index_can_settle() { + // 4.7 permits other Active work between the body and the next @* wait. + // Shared storage and event notifications remain; this is not privatization. + for four_state in [false, true] { + let mut sim = + celox::Simulation::from_sv_sources(vec![(SHARED_INDEX, Path::new("shared.sv"))], "top") + .four_state(four_state) + .build() + .unwrap(); + assert!(sim.warnings().is_empty()); + sim.run_until(10).unwrap(); + assert_eq!(display_lines(&mut sim), ["1 1"]); + let j = sim.signal("j"); + assert_eq!(sim.get(j), BigUint::from(4u8)); + } +} + +#[test] +fn shared_always_rearms_before_flip_flop_nba_updates() { + let source = SHARED_INDEX + .replace("reg any_a, any_b;", "reg any_a, any_b; reg clk=0;") + .replace("#1 a = 4'b0100;", "#1 a = 4'b0100; clk=1;") + .replace("#1 b = 4'b0010;", "") + .replace( + " initial begin", + " always @(posedge clk) b <= 4'b0010;\n initial begin", + ); + for four_state in [false, true] { + let mut sim = + celox::Simulation::from_sv_sources(vec![(&source, Path::new("shared-nba.sv"))], "top") + .four_state(four_state) + .build() + .unwrap(); + sim.run_until(10).unwrap(); + assert_eq!(display_lines(&mut sim), ["1 1"]); + } +} + +#[test] +fn shared_always_active_continuations_survive_stop() { + let source = SHARED_INDEX.replace("endmodule", "initial #1 $stop;\nendmodule"); + for four_state in [false, true] { + let build = || { + celox::Simulation::from_sv_sources(vec![(&source, Path::new("shared-stop.sv"))], "top") + .four_state(four_state) + .build() + .unwrap() + }; + let mut sim = build(); + sim.run_until(10).unwrap(); + assert!(sim.is_stopped()); + sim.run_until(10).unwrap(); + assert_eq!(display_lines(&mut sim), ["1 1"]); + } +} + +#[test] +fn shared_always_temporary_runs_each_block_with_its_own_index() { + // Icarus 13 prints `1 1`: it does not wake a block on the other's writes. + for four_state in [false, true] { + let mut policy = celox::DiagnosticPolicy::default(); + policy.set("shared_always_temporary", celox::DiagnosticLevel::Allow); + let mut sim = + celox::Simulation::from_sv_sources(vec![(SHARED_INDEX, Path::new("shared.sv"))], "top") + .four_state(four_state) + .diagnostic_policy(policy) + .build() + .unwrap(); + assert!(sim.warnings().is_empty()); + sim.run_until(10).unwrap(); + assert_eq!(display_lines(&mut sim), ["1 1"], "four_state={four_state}"); + } + let sim = shared_index(SHARED_INDEX, Some(celox::DiagnosticLevel::Warn)).unwrap(); + let warnings: Vec = sim.warnings().iter().map(ToString::to_string).collect(); + assert_eq!(warnings.len(), 1, "{warnings:?}"); + assert!(warnings[0].contains("`j`"), "{warnings:?}"); + assert!(warnings[0].contains("shared.sv:7"), "{warnings:?}"); + assert!(warnings[0].contains("shared.sv:11"), "{warnings:?}"); +} + +#[test] +fn shared_always_temporary_keeps_the_standard_when_it_would_show() { + let allow = Some(celox::DiagnosticLevel::Allow); + for (what, source) in [ + ( + "another reader", + SHARED_INDEX.replace(" initial begin\n", " wire [31:0] q = j;\n initial begin\n"), + ), + ( + "a read before the write", + SHARED_INDEX.replace( + " any_b = 1'b0;\n", + " any_b = j[0];\n", + ), + ), + ( + "a hierarchical reader", + SHARED_INDEX.replace("module top;", "module dut;").replace( + "endmodule\n", + "endmodule\nmodule top;\n dut d();\n initial #5 $display(\"%0d\", d.j);\nendmodule\n", + ), + ), + ] { + let sim = shared_index(&source, allow).unwrap(); + assert!(sim.warnings().is_empty(), "{what}"); + assert_does_not_settle(sim); + } +} + +#[test] +fn always_comb_blocks_may_not_share_a_variable() { + let source = SHARED_INDEX.replace("always @(*)", "always_comb"); + let error = match shared_index(&source, Some(celox::DiagnosticLevel::Allow)) { + Ok(_) => panic!("always_comb restricts a variable to one process"), + Err(error) => error.to_string(), + }; + assert!( + error.contains("multiple variable drivers for `j`"), + "{error}" + ); + assert!(error.contains("shared.sv:7"), "{error}"); + assert!(error.contains("shared.sv:11"), "{error}"); +} diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 278834cab27..5959ab64aef 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -5,6 +5,8 @@ //! adds it removes the exclusion. Supported cases run on every backend, //! and natively also from a serialized native image. +use num_bigint::BigUint; + macro_rules! timed_cases { () => {}; ( @@ -57,6 +59,13 @@ macro_rules! timed_cases { } timed_cases! { + fn wildcard_blocks_with_crossing_output_dependencies = "timing::wildcard_blocks_with_crossing_output_dependencies"; + fn wildcard_blocks_in_a_converging_feedback_loop = "timing::wildcard_blocks_in_a_converging_feedback_loop"; + fn nonblocking_intra_assignment_delays = "timing::nonblocking_intra_assignment_delays"; + fn nonblocking_intra_assignment_positions = "timing::nonblocking_intra_assignment_positions"; + fn nonblocking_intra_assignment_four_state = "timing::nonblocking_intra_assignment_four_state"; + fn nonblocking_intra_assignment_flip_flop = "timing::nonblocking_intra_assignment_flip_flop"; + fn nonblocking_intra_assignment_outlives_caller = "timing::nonblocking_intra_assignment_outlives_caller"; fn blocking_intra_assignment_tag_checks = "timing::blocking_intra_assignment_tag_checks"; fn blocking_intra_assignment_rejects_net = "timing::blocking_intra_assignment_rejects_net"; fn blocking_intra_assignment_rejects_net_port_select = "timing::blocking_intra_assignment_rejects_net_port_select"; @@ -523,8 +532,8 @@ fn unimplemented_timing_features_are_rejected() { 88, ), ( - "bit a, b; initial a <= #1 b;", - "nonblocking intra-assignment timing control", + "bit a, b; int d; initial a <= #(d) b;", + "nonconstant or overflowing nonblocking assignment delay", 88, ), ( @@ -924,6 +933,56 @@ fn runtime_error_before_a_commit_leaves_no_held_writes() { } } +#[test] +fn delayed_nonblocking_updates_survive_checkpoint_and_state_file() { + let source = r#" + module Top(output logic [7:0] q); + timeunit 1ns / 1ns; + initial begin + q=0; q <= #3 8'h11; q <= #6 8'h22; + // IEEE 1800-2023 9.4.1: negative delays use the time width. + q <= #(4'shf) 8'hee; + q <= #(-1) 8'hff; + end + endmodule + "#; + for four_state in [false, true] { + let build = || { + celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("delayed_state.sv"))], + "Top", + ) + .four_state(four_state) + .build() + .unwrap() + }; + let mut sim = build(); + let q = sim.signal("q"); + sim.run_until(1).unwrap(); + let saved = sim.checkpoint().unwrap(); + let mut bytes = Vec::new(); + sim.save_state().unwrap().write_to(&mut bytes).unwrap(); + let file = celox::StateFile::read_from(bytes.as_slice()).unwrap(); + let pending = &file.schedule.as_ref().unwrap().processes.delayed_nba; + assert_eq!( + pending.iter().map(|(time, _, _)| *time).collect::>(), + [3, 6, u64::MAX, u64::MAX] + ); + let mut loaded = build(); + loaded.load_state(&file).unwrap(); + let loaded_q = loaded.signal("q"); + for (time, expected) in [(4, 0x11u8), (7, 0x22)] { + sim.run_until(time).unwrap(); + loaded.run_until(time).unwrap(); + assert_eq!(sim.get(q), BigUint::from(expected)); + assert_eq!(loaded.get(loaded_q), BigUint::from(expected)); + } + sim.restore(&saved).unwrap(); + sim.run_until(4).unwrap(); + assert_eq!(sim.get(q), BigUint::from(0x11u8)); + } +} + /// The baselines of waits on a counted variable survive a state file: a /// simulation loaded between two pulses of `y` wakes the waiters as the /// uninterrupted one does, and saves the same baselines again. diff --git a/docs/.vitepress/components/BenchmarkDashboard.vue b/docs/.vitepress/components/BenchmarkDashboard.vue index b506426242d..84dead3d1b9 100644 --- a/docs/.vitepress/components/BenchmarkDashboard.vue +++ b/docs/.vitepress/components/BenchmarkDashboard.vue @@ -428,10 +428,14 @@ function shortDate(epoch: number): string { return `${d.getMonth() + 1}/${d.getDate()}`; } +function rtlmeterDesignName(name: string): string { + return name === "e203" ? "HummingbirdV2-E203" : `XuanTie-${name.toUpperCase()}`; +} + /** Format chart title from benchName */ function formatChartTitle(benchName: string): string { - const rtlmeter = benchName.match(/^rtlmeter_(e902|e906)_hello_v1_x64_(two-state|four-state)_total$/); - if (rtlmeter) return `XuanTie-${rtlmeter[1].toUpperCase()} hello · cold source-to-finish`; + const rtlmeter = benchName.match(/^rtlmeter_(e902|e906|e203)_hello_v1_x64_(two-state|four-state)_total$/); + if (rtlmeter) return `${rtlmeterDesignName(rtlmeter[1])} hello · cold source-to-finish`; let s = benchName; const rica = s.match(/^collection_rica_(kernel-[a-z-]+)_([a-f0-9]+)_(x64|arm64)_total$/); if (rica) return `rica ${rica[1]} · total · ${rica[3]} · workload ${rica[2]}`; @@ -902,7 +906,7 @@ onBeforeUnmount(() => { Measurement details.

-

XuanTie-{{ entry.rtlmeter!.case.toUpperCase() }} · latest qualification

+

{{ rtlmeterDesignName(entry.rtlmeter!.case) }} · latest qualification

Raw logs and versions · {{ entry.cpu }} · {{ new Date(entry.date).toLocaleDateString() }}

diff --git a/docs/benchmarks/index.md b/docs/benchmarks/index.md index ae504185b2f..a78adaddb8c 100644 --- a/docs/benchmarks/index.md +++ b/docs/benchmarks/index.md @@ -29,7 +29,7 @@ Celox/Verilator results for five fixed configurations (472 tests per sample). Its tab separates test-body, whole-process and HDL compilation time. The [RTLMeter comparison](./rtlmeter.md) measures cold source-to-finish latency for -XuanTie-E902/E906 hello programs in separate 2-state and 4-state charts, with +XuanTie-E902/E906 and HummingbirdV2-E203 hello programs in separate 2-state and 4-state charts, with Verilator and the stable xezim release pinned by Nix. Unsupported modes and failed qualifications remain visible in its status tables. diff --git a/docs/benchmarks/rtlmeter.md b/docs/benchmarks/rtlmeter.md index bdc3296d7f3..3e85d1840ec 100644 --- a/docs/benchmarks/rtlmeter.md +++ b/docs/benchmarks/rtlmeter.md @@ -2,10 +2,13 @@ [Open the RTLMeter dashboard](./index.md?tab=rtlmeter). -The comparison runs the unmodified **XuanTie-E902** and **XuanTie-E906** `hello` -programs from [RTLMeter](https://github.com/verilator/rtlmeter), fixed at commit +The comparison runs the unmodified **XuanTie-E902**, **XuanTie-E906** and +**HummingbirdV2-E203** `hello` programs from [RTLMeter](https://github.com/verilator/rtlmeter), fixed at commit `4fdd6c3fd154e9b99d3a9d713cf3f4977e284f94`. All tools receive the same ordered -source list, headers, defines, testbench and `case.pat`. Input hashes, tool +source list, headers, defines, testbench and firmware (`case.pat` for E902/E906; +`program.hex` for E203). E203 uses the upstream `default` configuration, including +its `#1` flip-flop delays, with assertions enabled and standard shared-variable +semantics. Input hashes, tool versions, executable hashes and raw output are retained with each run. ## State models @@ -38,15 +41,16 @@ These short programs measure iteration latency, **not steady-state simulation throughput**. All configurations for one design run sequentially on the same VM and logical -CPU, with tool order rotated between repetitions. The two designs may run on +CPU, with tool order rotated between repetitions. Different designs may run on different hosts. Compare results within one design, state model and host. -A successful sample requires a zero exit status, exactly one `Hello Friend!` -and `TEST PASSED` line, no failure marker, and a positive final RTLMeter clock -count. Counts must be stable across repetitions and differ by at most one clock +A successful sample requires a zero exit status, the expected program output +and success marker exactly once, no failure marker, and a positive final +RTLMeter clock count. E902/E906 print `Hello Friend!` and `TEST PASSED`; E203 +prints `Hello World from HummingbirdV2 E203` and `TEST_PASSED`. Counts must be stable across repetitions and differ by at most one clock between tools, allowing for `$finish` and the counter on the same active edge. A separate one-cycle negative control must stop before program success. -All tools use the same upstream `+max_cycles` limit (16,384 for E902; 32,768 +All tools use the same upstream `+max_cycles` limit (16,384 for E902/E203; 32,768 for E906), so a stalled UART or CPU cannot count as a completed workload. Unsupported modes, probe failures, simulation failures, timeouts and clock mismatches appear in the table and contribute no performance points. @@ -69,5 +73,5 @@ work/rtlmeter-python/bin/python scripts/run-rtlmeter-bench.py prepare work/rtlme nix develop .#xezim --command work/rtlmeter-python/bin/python scripts/run-rtlmeter-bench.py run e902 work/rtlmeter-source work/rtlmeter-bin/celox work/rtlmeter-report ``` -Repeat with `e906` and a fresh output directory. Local dirty-checkout results +Repeat with `e906` or `e203` and a fresh output directory. Local dirty-checkout results are useful for investigation and cannot be published as release measurements. diff --git a/docs/guide/celox-toml.md b/docs/guide/celox-toml.md index 5a8c51d7b07..dfa0926a6ab 100644 --- a/docs/guide/celox-toml.md +++ b/docs/guide/celox-toml.md @@ -207,6 +207,23 @@ The Rust `.allow_inferred_latches(true)` and JavaScript `allowInferredLatches: t options provide `allow` only when this diagnostic has no explicit setting; an explicit `error`, `warn` or `allow` takes precedence. +`shared_always_temporary` defaults to `error`, which keeps IEEE 1800-2023 +semantics for a variable that several `always @*` blocks write, such as a loop +index they share: each block waits on the variables it reads, the shared one +included (§9.4.2.2), and writes notify other blocks that are waiting. For an +isolated index written before reads, Celox may run other Active work after the +body and before the next implicit wait (§4.7, §4.9.3). Shared storage and event +notifications remain; sharing alone does not require nonconvergence. Blocks that keep waking +each other end the run with `time T does not settle`, which names the blocks. +With `warn` or `allow`, Celox instead makes such a variable a temporary of each +block, when only `always @*` blocks write it, each writes it before it reads it +on every path, and nothing else reads it: no other process, continuous +assignment, subroutine, port, instance connection or hierarchical name. Its +writes then wake no other block, as in Icarus Verilog, and the variable itself +keeps its initial value. This deviates from the standard, so it is not the +default; `warn` reports each variable and its blocks. Declaring the variable +inside each block keeps the standard semantics without it. + Project simulator constructors load this table alongside `Veryl.toml`. Native compilation also supports standalone SystemVerilog projects: diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index b90081ad47b..aab1c2919d6 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -58,6 +58,7 @@ In a timed `Simulation`, `initial` and plain `always` processes can suspend: | `#delay` | integral and real delays, `#(min:typ:max)` (the typical value), package-scoped values such as `#pkg::D`, and [time literals](#time-literal-delays); an X or Z delay counts as zero | | `@(...)` | variables, `posedge` / `negedge` / `edge`, items joined by `or` or `,`, bit, part and run-time index selects, any expression including calls of pure functions, `iff` conditions on items (not in `always_ff`), and `@*` / `@(*)`, which waits on the variables its statement reads | | `wait (condition)` | any condition; an X or Z condition counts as false | +| Delayed nonblocking assignments | `lhs <= #constant rhs` in `initial` and ordinary `always`, for integral constant delays and time literals. The value and destination position are captured immediately; the update is queued in the NBA region of the target time without suspending the caller (IEEE 1800-2023 10.4.2). Pending updates survive checkpoints and state files. | | Assignments | blocking and nonblocking, to any target a blocking assignment takes, including unpacked array elements and run-time positions; nonblocking updates take effect in the NBA region of the time slot, at the position evaluated when the assignment executes, and bits outside the target or at a position with an X or Z bit are not written | An `always` whose sensitivity list names exactly the variables its statement @@ -361,7 +362,7 @@ it. The error carries the number of the issue that tracks the construct; constructs without a dedicated issue point to the frontend roadmap, [#88](https://github.com/celox-sim/celox/issues/88). - Class features beyond those [listed](#classes): `$cast` to a variable that is not a class handle, anonymous enumeration, struct and union types and named four-state or string constants of a module or package as class parameter values (a class passes its own such parameters on by name), module-local classes as type arguments to package-class specializations, properties that are `real` or arrays, reads of bit and part selects of a property not declared `[N-1:0]`, selects of a member of a property of unpacked structure type, packed structure members of a property, properties as `output` or `inout` arguments, and randomization or constraints over 4-state properties. Recursive calls remain unsupported. -- Behavioral and verification constructs: intra-assignment timing controls (`a = #1 b`), +- Behavioral and verification constructs: nonblocking intra-assignment event controls and nonconstant delays, delayed continuous assignments ([#444](https://github.com/celox-sim/celox/issues/444)), `wait fork` / `disable fork`, temporal concurrent assertions beyond the Boolean subset below, `force` / `release`. - Named events beyond those [listed](#named-events): arrays of events, event ports, diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 7ca5e547568..157e73f8106 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -103,7 +103,7 @@ ports, types, statements or system functions before porting a design. Common reasons a design needs changes are: - Class-based verification beyond [simple classes](./systemverilog-reference#classes) and concurrent assertions beyond the [single-cycle Boolean subset](./systemverilog-reference#concurrent-assertions). -- `fork` / `join`, intra-assignment timing such as `a = #1 b` +- `fork` / `join`, nonblocking intra-assignment event controls and nonconstant delays and `iff` in `always_ff` event controls ([#452](https://github.com/celox-sim/celox/issues/452)). - Nonblocking latch assignments, multiple drivers and tri-state buses. Inferred latches in `always_comb` require `inferred_latch = "warn"` or `"allow"` in the common `[diagnostics]` configuration. - Non-ANSI module ports, wildcard `.*` connections, gate primitives with delays, strengths or instance arrays, and `bind`. diff --git a/docs/ja/benchmarks/index.md b/docs/ja/benchmarks/index.md index d46f631bbaa..7e6be84d9c4 100644 --- a/docs/ja/benchmarks/index.md +++ b/docs/ja/benchmarks/index.md @@ -94,6 +94,6 @@ Issue には実行へのリンクと、性能低下の場合は比較結果と ローカル計測は、同じマシン上で 2 つのリビジョンを比較する場合に最も有効です。 CI 履歴は、単発の小さな差より長期的な傾向の確認に向いています。 -[RTLMeter 比較](./rtlmeter.md)では XuanTie-E902/E906 hello を用い、 +[RTLMeter 比較](./rtlmeter.md)では XuanTie-E902/E906 と HummingbirdV2-E203 の hello を用い、 2-state / 4-state を分けて Verilator・Nix 固定の安定版 xezim と比較します。 コンパイルから実行完了までを測り、未対応や失敗も表に表示します。 diff --git a/docs/ja/benchmarks/rtlmeter.md b/docs/ja/benchmarks/rtlmeter.md index 2c85ab46a33..cabf3213473 100644 --- a/docs/ja/benchmarks/rtlmeter.md +++ b/docs/ja/benchmarks/rtlmeter.md @@ -2,7 +2,9 @@ [RTLMeter ダッシュボード](./index.md?tab=rtlmeter)で、Celox・Verilator・xezim の 2-state / 4-state 比較を確認できます。対象は固定した RTLMeter の -XuanTie-E902 / E906 の `hello` です。 +XuanTie-E902 / E906 と HummingbirdV2-E203 の `hello` です。 +E203 は上流の `default` 構成(フリップフロップの `#1` 遅延を含む)を使用し、 +assertion を有効にした通常の共有変数の意味論で実行します。 測定値は、同じ VM・論理 CPU 上で順番を入れ替えて実行した 3 回の中央値です。 HDL の読み込みからコンパイル、起動、実行完了までを含みます。Verilator には diff --git a/docs/ja/guide/celox-toml.md b/docs/ja/guide/celox-toml.md index 6443f46cdad..243dbf44feb 100644 --- a/docs/ja/guide/celox-toml.md +++ b/docs/ja/guide/celox-toml.md @@ -155,6 +155,10 @@ memory_file_word_count = "error" Rust の `.allow_inferred_latches(true)` と JavaScript の `allowInferredLatches: true` は、 この診断の明示設定がない場合だけ `allow` を補います。明示した `error`・`warn`・`allow` が優先されます。 +`shared_always_temporary` の既定値は `error` で、共有するループ変数のように複数の `always @*` ブロックが書き込む変数に IEEE 1800-2023 の意味論を適用します。各ブロックは自身が読む変数(共有変数を含む)の変化を待つため(§9.4.2.2)、書き込みは待機中の他のブロックに通知されます。ほかから読まれず読む前に書かれる添字については、本体終了後、次の暗黙のイベント待ちに入る前に他の Active 領域の処理を実行できます(§4.7、§4.9.3)。共有変数の格納とイベント通知は保持し、共有だけを理由に非収束とはしません。互いに起動し続けるブロックは `time T does not settle` で実行を終了し、そのメッセージに該当ブロックが示されます。 +`warn` または `allow` を選ぶと、Celox はそのような変数を各ブロックの一時変数として扱います。対象は、`always @*` ブロックだけが書き込み、各ブロックがすべての経路で読む前に書き込み、ほかに読むもの(他のプロセス、継続的代入、サブルーチン、ポート、インスタンス接続、階層名)がない変数です。その書き込みは Icarus Verilog と同様に他のブロックを起動せず、変数自体は初期値のままになります。 +これは規格からの逸脱なので既定では無効です。`warn` は対象の変数とブロックを報告します。変数を各ブロックの中で宣言すれば、この緩和なしで規格どおりの意味論を保てます。 + `interface_array_query` の既定値は `error` です。`warn` または `allow` で、固定長の interface 配列と添字で選択した部分配列に対する `$size` を互換拡張として許可します。IEEE 1800-2023 §20.7 の対象はデータ配列であり、interface インスタンスはデータオブジェクトではありません。省略可能な次元引数は既知の整数定数に限ります。この拡張によって interface ハンドルに packed 幅が付いたり、他の配列クエリが使えるようになったりすることはありません。 ```toml diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 8db85ac8c33..b2885807b1c 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -55,6 +55,7 @@ outline: [2, 3] | `#delay` | 整数と実数の遅延、`#(min:typ:max)`(typ の値)、`#pkg::D` のような package スコープの値、[時間リテラル](#time-literal-delays)。X / Z の遅延は 0 として扱う | | `@(...)` | 変数、`posedge` / `negedge` / `edge`、`or` または `,` で並べた項目、ビット選択・部分選択・実行時添字の選択、pure な関数呼び出しを含む任意の式、項目の `iff` 条件(`always_ff` を除く)、文が読む変数を待つ `@*` / `@(*)` | | `wait (condition)` | 任意の条件。X / Z の条件は偽として扱う | +| 遅延付きノンブロッキング代入 | `initial` と通常の `always` での `lhs <= #constant rhs`。整数の定数遅延と時間リテラルに対応します。右辺と代入先の位置を即時に評価し、呼び出し元を中断せず指定時刻の NBA 領域で更新します(IEEE 1800-2023 10.4.2)。予約更新はチェックポイントと state file にも保持します。 | | 代入 | ブロッキング代入とノンブロッキング代入。代入先はブロッキング代入と同じで、unpacked 配列の要素や実行時に決まる位置も使えます。ノンブロッキング代入は代入を実行した時点で評価した位置に、そのタイムスロットの NBA 領域で反映します。代入先の範囲外のビットと、X や Z のビットを含む位置には書き込みません | 文が読む変数をちょうど並べたセンシティビティリスト(`@*` が求めるもの、IEEE 1800-2023 9.4.2.2)を持つ @@ -239,7 +240,7 @@ unpacked 構造体(IEEE 1800-2023 7.2)のメンバには、整数型、列 ANSI ヘッダーのポートは、クロック入力やパラメータ依存の幅も含めて modport 経由で渡せます。 interface 自体と入れ子の interface は対応しています。型パラメータはインスタンスごとに解決し、modport ポート経由でも伝搬します。 再帰する特殊化と64段を超える入れ子は拒否します。細かな制約は[英語版の一覧](/guide/systemverilog-reference#interface-restrictions)を参照してください。 -- 振る舞い記述・検証向けの構文:`final`、代入内のタイミング制御(`a = #1 b`)、遅延付き継続代入([#444](https://github.com/celox-sim/celox/issues/444))、 +- 振る舞い記述・検証向けの構文:`final`、ノンブロッキング代入内のイベント制御と定数でない遅延、遅延付き継続代入([#444](https://github.com/celox-sim/celox/issues/444))、 `fork` / `join`、`wait fork` / `disable fork`、下記のBoolean部分集合を超える並行アサーション、`force` / `release`。 - [対応範囲](#named-events)を超える named event:event の配列、event のポート、unpacked 構造体の event メンバ、event を返す関数、 `always_comb` / `always_latch` の中の trigger、 diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index cd64eb40245..6b38968a5b6 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -92,7 +92,7 @@ X/Z を扱う場合は builder に `.four_state(true)` を指定します。 デザインの変更が必要になりやすいのは、次の機能です。 - [単純なクラス](./systemverilog-reference#classes)を超えるクラスを使う検証、[単一サイクルBoolean部分集合](./systemverilog-reference#並行アサーション)を超える並行アサーション。 -- `fork` / `join`、`a = #1 b` のような代入内のタイミング制御、 +- `fork` / `join`、ノンブロッキング代入内のイベント制御と定数でない遅延、 `always_ff` のイベント制御の `iff`([#452](https://github.com/celox-sim/celox/issues/452))。 - ラッチ内のノンブロッキング代入、複数ドライバ、トライステートバス。`always_comb` の暗黙のラッチ推論は 共通の `[diagnostics]` 設定で `inferred_latch = "warn"` または `"allow"` を指定して許可します。 - 非 ANSI モジュールポート、ワイルドカード `.*` 接続、遅延・強度指定やインスタンス配列を持つゲートプリミティブ、`bind`。 diff --git a/scripts/publish-rtlmeter-bench.mjs b/scripts/publish-rtlmeter-bench.mjs index cca6dc9617d..c65f50a3d89 100644 --- a/scripts/publish-rtlmeter-bench.mjs +++ b/scripts/publish-rtlmeter-bench.mjs @@ -13,6 +13,8 @@ const positive = value => Number.isSafeInteger(value) && value > 0; export function rtlmeterMetrics(report, commit) { assert.ok(manifest.cases[report.case], "Unknown RTLMeter case"); + const spec = manifest.cases[report.case]; + assert.deepEqual(report.caseSpec, spec, "Workload options must match the manifest"); assert.equal(report.schemaVersion, 1); assert.equal(report.contract, manifest.contract); assert.equal(report.status, "completed"); @@ -42,7 +44,7 @@ export function rtlmeterMetrics(report, commit) { Object.fromEntries(Object.entries(report.inputSha256).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)), )).digest("hex")); const design = manifest.cases[report.case].design; - for (const path of [`designs/${design}/descriptor.yaml`, `designs/${design}/tests/hello/case.pat`, + for (const path of [`designs/${design}/descriptor.yaml`, ...((spec.inputFiles ?? ["tests/hello/case.pat"]).map(file => `designs/${design}/${file}`)), "rtl/__rtlmeter_utils.sv", "rtl/__rtlmeter_top_include.vh"]) { assert.ok(digest(report.inputSha256[path]), `Missing input identity: ${path}`); } @@ -84,7 +86,7 @@ export function rtlmeterMetrics(report, commit) { const times = row.samples.map(sample => sample.processNs).sort((a, b) => a - b); return { name: `rtlmeter-${row.engine}/rtlmeter_${report.case}_hello_v1_x64_${row.stateModel}_total`, unit: "us", value: times[Math.floor(times.length / 2)] / 1000, - extra: JSON.stringify({ contract: report.contract, rtlmeter: report.rtlmeterRevision, + extra: JSON.stringify({ caseSpec: report.caseSpec, contract: report.contract, rtlmeter: report.rtlmeterRevision, state: row.stateModel, cycles: row.samples[0].cycles, maxCycles: report.maxCycles, samples: times, configuration: report.configuration, versions: report.versions, binarySha256: report.binarySha256, sourceSha256: report.sourceSha256, run }) }; diff --git a/scripts/rtlmeter-benchmark.test.mjs b/scripts/rtlmeter-benchmark.test.mjs index 876d446e1a1..39ce3e8c3b5 100644 --- a/scripts/rtlmeter-benchmark.test.mjs +++ b/scripts/rtlmeter-benchmark.test.mjs @@ -7,15 +7,17 @@ import { rtlmeterMetrics } from "./publish-rtlmeter-bench.mjs"; const manifest = JSON.parse(readFileSync(new URL("../benchmarks/rtlmeter/manifest.json", import.meta.url))); const locked = JSON.parse(readFileSync(new URL("../flake.lock", import.meta.url))).nodes.xezim; const commit = 'a'.repeat(40); -function report() { +function report(name = "e902") { + const spec = manifest.cases[name]; const inputSha256 = Object.fromEntries([ - ...Array.from({ length: 110 }, (_, i) => `designs/XuanTie-E902/src/${i}.v`), - 'designs/XuanTie-E902/descriptor.yaml', 'designs/XuanTie-E902/tests/hello/case.pat', + ...Array.from({ length: 110 }, (_, i) => `designs/${spec.design}/src/${i}.v`), + `designs/${spec.design}/descriptor.yaml`, + ...(spec.inputFiles ?? ["tests/hello/case.pat"]).map(file => `designs/${spec.design}/${file}`), 'rtl/__rtlmeter_utils.sv', 'rtl/__rtlmeter_top_include.vh', ].sort().map(path => [path, 'b'.repeat(64)])); - return { schemaVersion: 1, contract: manifest.contract, case: 'e902', status: 'completed', + return { schemaVersion: 1, contract: manifest.contract, case: name, caseSpec: spec, status: 'completed', rtlmeterRevision: manifest.revision, celoxCommit: commit, dirty: false, - requestedSamples: 3, maxCycles: manifest.cases.e902.maxCycles, host: { architecture: 'x86_64', cpu: 'test CPU', affinityCpu: 0 }, + requestedSamples: 3, maxCycles: spec.maxCycles, host: { architecture: 'x86_64', cpu: 'test CPU', affinityCpu: 0 }, xezimRelease: locked.original.ref, xezimRevision: locked.locked.rev, versions: { celox: 'celox 0.12.0', verilator: 'Verilator 5.052', xezim: `xezim version ${locked.original.ref.replace(/^v/, '')}\ngit unknown` }, binarySha256: { celox: 'a'.repeat(64), verilator: 'b'.repeat(64), xezim: 'c'.repeat(64) }, @@ -73,7 +75,7 @@ test('RTLMeter runs daily/manual with locked tools, raw failures and master-only assert.doesNotMatch(workflow, /^\s+(pull_request|push|merge_group):/m); assert.match(workflow, /cancel-in-progress: false/); assert.match(workflow, /fail-fast: false/); - assert.match(workflow, /case: \[e902, e906\]/); + assert.match(workflow, /case: \[e902, e906, e203\]/); assert.match(workflow, /nix build --no-update-lock-file \.#xezim/); assert.match(workflow, /revision: ea338be98e1e838d3518809ce8899f85a009963c/); assert.match(workflow, /needs: comparison\n if: github.ref == 'refs\/heads\/master'/); @@ -81,3 +83,14 @@ test('RTLMeter runs daily/manual with locked tools, raw failures and master-only assert.match(workflow, /if: always\(\)[\s\S]+retention-days: 30/); assert.ok(workflow.indexOf('--validate-only') < workflow.lastIndexOf('node scripts/publish-rtlmeter-bench.mjs')); }); + +test('E203 publishes the default hello workload and rejects altered options or image identities', () => { + const r = report('e203'); + assert.ok(rtlmeterMetrics(r, commit).every(metric => metric.name.includes('rtlmeter_e203_hello_v1_'))); + const wrongOptions = structuredClone(r); + wrongOptions.caseSpec.configuration = 'nodelay'; + assert.throws(() => rtlmeterMetrics(wrongOptions, commit)); + delete r.inputSha256['designs/HummingbirdV2-E203/tests/hello/program.hex']; + r.sourceSha256 = createHash('sha256').update(JSON.stringify(r.inputSha256)).digest('hex'); + assert.throws(() => rtlmeterMetrics(r, commit), /Missing input identity:.*program\.hex/); +}); diff --git a/scripts/run-rtlmeter-bench.py b/scripts/run-rtlmeter-bench.py index a8ea09af146..57b3f727a01 100644 --- a/scripts/run-rtlmeter-bench.py +++ b/scripts/run-rtlmeter-bench.py @@ -54,10 +54,16 @@ def specification(name, source): descriptor = yaml.safe_load((design / 'descriptor.yaml').read_text()) compile_spec = descriptor['compile'] test = descriptor['execute']['tests'][spec['test']] + configurations = descriptor.get('configurations', {}) + configuration = configurations[spec['configuration']] if 'configuration' in spec else configurations.get('default', {}) + configured_compile = configuration.get('compile', {}) + configured_execute = configuration.get('execute', {}) + test = {**test, **configured_execute.get('tests', {}).get(spec['test'], {})} sources = [design / p for p in compile_spec['verilogSourceFiles']] sources.append(source / 'rtl/__rtlmeter_utils.sv') files = [design / p for p in test.get('files', [])] - defines = {**compile_spec.get('verilogDefines', {}), '__RTLMETER_MAIN_CLOCK': compile_spec['mainClock']} + defines = {**compile_spec.get('verilogDefines', {}), **configured_compile.get('verilogDefines', {}), + '__RTLMETER_MAIN_CLOCK': compile_spec['mainClock']} # Fingerprint all potential local headers, not only explicit compilation inputs. inputs = sorted(set([*sources, *files, design / 'descriptor.yaml', *design.joinpath('src').rglob('*'), source / 'rtl/__rtlmeter_top_include.vh'])) @@ -96,12 +102,12 @@ def execute(command, cwd, log, timeout, cpu): return {'exitCode': code, 'timedOut': code in (124, 137), 'elapsedNs': time.monotonic_ns() - start} -def accept(stdout, cycles, outcome, payload): +def accept(stdout, cycles, outcome, payload, success_marker='TEST PASSED'): if outcome['timedOut'] or outcome['exitCode'] != 0: raise ValueError('process failed or timed out') - if re.search(r'TEST\s+FAIL(?:ED)?|simulation finished with error|\$fatal|%Error:', stdout, re.I): + if re.search(r'TEST[\s_]+FAIL(?:ED)?|Time Out !!!|simulation finished with error|\$fatal|%Error:', stdout, re.I): raise ValueError('testbench reported failure') - if stdout.splitlines().count('TEST PASSED') != 1 or stdout.splitlines().count(payload) != 1: + if stdout.splitlines().count(success_marker) != 1 or stdout.splitlines().count(payload) != 1: raise ValueError('missing unique upstream success marker or expected program output') if not re.fullmatch(r'[1-9][0-9]*', cycles.strip()): raise ValueError('missing valid final RTLMeter clock count') @@ -168,7 +174,7 @@ def measure_case(name, source, celox, xezim, output, build_root, timeout=1800, s release = locked['original'].get('ref') if release is None or versions['xezim'].splitlines()[0] != f'xezim version {release.removeprefix("v")}': raise ValueError('xezim must be built from the release fixed by flake.lock') - report = {'schemaVersion': 1, 'contract': MANIFEST['contract'], 'case': name, + report = {'schemaVersion': 1, 'contract': MANIFEST['contract'], 'case': name, 'caseSpec': MANIFEST['cases'][name], 'rtlmeterRevision': MANIFEST['revision'], 'sourceSha256': spec['sourceSha256'], 'inputSha256': spec['inputSha256'], 'celoxCommit': git(ROOT, 'rev-parse', 'HEAD'), 'dirty': bool(git(ROOT, 'status', '--porcelain')), 'requestedSamples': samples, @@ -219,7 +225,7 @@ def save(): text = ''.join(p.read_text(errors='replace') for p in sorted((control / 'logs').glob('*.log'))) control_cycles = control / '_rtlmeter_cycles.txt' if (outcome['exitCode'] == 0 and not outcome['timedOut'] - and 'RTLMeter: +max_cycles reached, exiting' in text and 'TEST PASSED' not in text + and 'RTLMeter: +max_cycles reached, exiting' in text and spec.get('successMarker', 'TEST PASSED') not in text and control_cycles.exists() and control_cycles.read_text().strip() == '1'): row['negativeControl'] = 'passed' else: @@ -245,7 +251,7 @@ def save(): stdout = ''.join(p.read_text(errors='replace') for p in sorted((directory / 'logs').glob('*.log'))) cycles = directory / '_rtlmeter_cycles.txt' try: - count = accept(stdout, cycles.read_text() if cycles.exists() else '', outcome, spec['payload']) + count = accept(stdout, cycles.read_text() if cycles.exists() else '', outcome, spec['payload'], spec.get('successMarker', 'TEST PASSED')) if count >= spec['maxCycles']: raise ValueError('Workload reached the cycle limit instead of completing normally') row['samples'].append({'status': 'passed', 'processNs': outcome['elapsedNs'], 'cycles': count}) diff --git a/scripts/tests/test_rtlmeter_bench.py b/scripts/tests/test_rtlmeter_bench.py index 915fb738011..ba72f5d3d07 100644 --- a/scripts/tests/test_rtlmeter_bench.py +++ b/scripts/tests/test_rtlmeter_bench.py @@ -37,6 +37,58 @@ def test_verilator_times_build_and_run_in_both_modes(self): with self.assertRaisesRegex(ValueError, 'no global two-state'): bench.commands('xezim', 'two-state', spec, Path('/source/files.f'), Path('/build'), binaries, []) + def test_e203_uses_its_own_success_and_failure_markers(self): + outcome = {'exitCode': 0, 'timedOut': False} + text = 'Hello World from HummingbirdV2 E203\nTEST_PASSED\n' + payload = bench.MANIFEST['cases']['e203']['payload'] + self.assertEqual(bench.accept(text, '3000', outcome, payload, 'TEST_PASSED'), 3000) + for output in [text.replace('TEST_PASSED', 'TEST PASSED'), + text + 'TEST_FAILED\n', text + 'Time Out !!!\n', + text + 'TEST_PASSED\n', text.replace(payload, '')]: + with self.subTest(output=output), self.assertRaises(ValueError): + bench.accept(output, '3000', outcome, payload, 'TEST_PASSED') + + def test_descriptor_default_defines_reach_every_simulator(self): + # Like E203, this descriptor supplies FF delays via its default + # configuration. Keep the source unmodified and assertions enabled. + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + design = root / 'designs/HummingbirdV2-E203' + (design / 'src').mkdir(parents=True) + (design / 'tests/hello').mkdir(parents=True) + (root / 'rtl').mkdir() + for path in ['src/tb.v', 'tests/hello/program.hex']: + (design / path).write_text('test fixture') + for path in ['__rtlmeter_utils.sv', '__rtlmeter_top_include.vh']: + (root / 'rtl' / path).write_text('test fixture') + (design / 'descriptor.yaml').write_text(""" +compile: + verilogSourceFiles: [src/tb.v] + topModule: tb + mainClock: tb.clk +execute: + tests: + hello: + files: [tests/hello/program.hex] +configurations: + default: + compile: + verilogDefines: + RTLMETER_FF_DELAY: '#1' + nodelay: + compile: + verilogDefines: + RTLMETER_FF_DELAY: '' +""") + spec = bench.specification('e203', root) + self.assertEqual(spec['defines'], {'RTLMETER_FF_DELAY': '#1', '__RTLMETER_MAIN_CLOCK': 'tb.clk'}) + self.assertEqual(spec['files'], [design / 'tests/hello/program.hex']) + binaries = {engine: engine for engine in bench.ENGINES} + for engine in bench.ENGINES: + command = bench.commands(engine, 'four-state', spec, root / 'files.f', root / 'build', binaries, [])[0] + self.assertIn('-DRTLMETER_FF_DELAY=#1', command) + self.assertFalse(any('DISABLE_SV_ASSERTION' in arg or 'shared_always_temporary' in arg for arg in command if isinstance(arg, str))) + def test_cold_build_directory_cannot_be_reused(self): with tempfile.TemporaryDirectory() as directory: with bench.build_directory(Path(directory), 'sample') as first:
SimulatorStateStatusDetails