diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 385e71c53f8..317862aa516 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -613,12 +613,13 @@ pub struct NbaSite { /// Two-state staging object holding a bit offset added to `lsb`, for an /// assignment whose position is computed at run time. pub offset: Option, - /// One-bit flag of a site whose destination receives no other - /// nonblocking assignment: a variable of the module with no other - /// nonblocking site in the module and no writer outside it (not a port, - /// not bound to a package variable, not the target of a hierarchical - /// reference). A frontend that cannot tell leaves it `None`, so the - /// assignment goes through the ordered queue. + /// One-bit flag of a site whose destination has no other writer in the + /// design (no other nonblocking site, no store of any unit, not a + /// top-level port) and whose update order nothing observes (no wait, + /// counter, event domain or combinational observer reads it, directly + /// or through combinational logic): publication places flagged updates + /// after the queued ones. Without the flag the assignment goes through + /// the ordered queue. /// /// The kernel stages the value and sets the flag without returning; /// publication commits flagged sites and clears the flags. A kernel diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs index 4c9fa3cfe8e..a34363cb372 100644 --- a/crates/celox-frontend-core/src/process.rs +++ b/crates/celox-frontend-core/src/process.rs @@ -287,6 +287,55 @@ impl ProcessKernelBuilder { Ok(()) } + /// A nonblocking update of `site` with two paths that a load of the + /// one-bit variable `switch` selects. With the switch set, the value + /// `lower` computes is staged as [`Self::nonblocking`] does for a site + /// with a `pending` flag. Otherwise the kernel returns + /// [`ProcessStatus::Nba`] at once, for a site whose value object already + /// holds the value. A frontend emits both before the whole design shows + /// which one may be used; assembly keeps one + /// (`crate::symbolic::artifact::NbaSwitch`). + pub fn nonblocking_switched>( + &mut self, + index: u32, + site: &NbaSite, + switch: SourceVarId, + lower: impl FnOnce( + &mut SIRBuilder, + ) -> Result<(RegisterId, Option), E>, + ) -> Result<(), E> { + assert!( + site.pending.is_some(), + "a switched nonblocking site has a pending flag" + ); + let on = self.builder.alloc_bit(1, false); + self.builder.emit(SIRInstruction::Load( + on, + stable(switch), + SIROffset::Static(0), + 1, + )); + let staged = self.builder.new_block(); + let queued = self.builder.new_block(); + let join = self.builder.new_block(); + self.builder.seal_block(SIRTerminator::Branch { + cond: on, + true_block: (staged, Vec::new()), + false_block: (queued, Vec::new()), + }); + self.builder.switch_to_block(staged); + self.nonblocking(index, site, lower)?; + self.builder + .seal_block(SIRTerminator::Jump(join, Vec::new())); + self.builder.switch_to_block(queued); + self.store_delay_constant(u64::from(index)); + self.suspend(ProcessStatus::Nba)?; + self.builder + .seal_block(SIRTerminator::Jump(join, Vec::new())); + self.builder.switch_to_block(join); + Ok(()) + } + /// End the simulation. No block is open afterwards. pub fn finish(&mut self) { self.wait_site = None; diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs index 6c6f6e61d6a..6b78ba0c17c 100644 --- a/crates/celox-frontend-core/src/sdk.rs +++ b/crates/celox-frontend-core/src/sdk.rs @@ -1936,6 +1936,7 @@ pub fn lower_frontend_artifact( counter_slots, wait_sites, nba_sites, + nba_switches: Vec::new(), host_request_sites: Vec::new(), time_slot: None, }; diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs index d190ccf2758..d1e7231593b 100644 --- a/crates/celox-frontend-core/src/symbolic/artifact.rs +++ b/crates/celox-frontend-core/src/symbolic/artifact.rs @@ -122,6 +122,8 @@ pub struct SimModule { /// Nonblocking sites of the module's processes; `process` indexes /// [`Self::processes`]. pub nba_sites: Vec>, + /// Nonblocking sites whose kernel has both a staged and a queued path. + pub nba_switches: Vec>, /// Synchronous host operations of the module processes. pub host_request_sites: Vec>, /// The variable through which the module's code reads the simulation @@ -129,6 +131,34 @@ pub struct SimModule { pub time_slot: Option, } +/// A nonblocking site whose kernel has two paths, as +/// `ProcessKernelBuilder::nonblocking_switched` builds them. The staged path +/// stages the value in the site's `value` and sets its `pending` flag; the +/// queued path leaves the value in `queued` and returns to the runtime. +/// Assembly keeps one path: the staged one only if nothing else writes the +/// site's target and nothing can observe when the target is updated. For the +/// queued path it makes `queued` the site's value and drops the flag. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct NbaSwitch { + /// The site's `value` object, which identifies the site. + pub value: A, + /// The one-bit variable whose load selects the path. It holds no state: + /// assembly replaces the selection by a jump. + pub switch: A, + /// The value object of the queued path. + pub queued: A, +} + +impl NbaSwitch { + pub fn map(&self, mut map: impl FnMut(&A) -> B) -> NbaSwitch { + NbaSwitch { + value: map(&self.value), + switch: map(&self.switch), + queued: map(&self.queued), + } + } +} + /// The package variable a module variable denotes. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct PackageBinding { diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 450145040e9..c851603fe8c 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2,7 +2,8 @@ use num_bigint::BigUint; use std::collections::{BTreeMap, BTreeSet}; use crate::symbolic::artifact::{ - FfPart, RelocationModule, SimModule, SplitCommit, SymbolicGlueAddr as GlueAddr, SymbolicRtl, + FfPart, NbaSwitch, RelocationModule, SimModule, SplitCommit, SymbolicGlueAddr as GlueAddr, + SymbolicRtl, }; use crate::{ FrontendLookup, FrontendTrace, FrontendTraceOptions, FusedSirOptimizationHints, HashMap, @@ -18,8 +19,8 @@ use celox_design::{ VariableMetadata, WaitSite, }; use celox_sir::{ - BasicBlock, ExecutionUnit, LaneUnit, ParallelSirProgram, SIRInstruction, SIRTerminator, - SirProgram, + BasicBlock, ExecutionUnit, LaneUnit, ParallelSirProgram, SIRInstruction, SIROffset, + SIRTerminator, SirProgram, }; use celox_slt::{ CombObserver, FfAccessSummary, LogicPath, LogicPathId, LogicPathTarget, NodeId, SLTNodeArena, @@ -680,7 +681,7 @@ pub fn schedule_symbolic_rtl( &mut trace, ) )?; - let timing = relocate_timing(bindings, &instance_modules, &modules, &processes); + let mut timing = relocate_timing(bindings, &instance_modules, &modules, &processes); let variables: HashMap = instance_modules .iter() .flat_map(|(&instance, module)| { @@ -1575,6 +1576,73 @@ pub fn schedule_symbolic_rtl( written_inputs: observer.written_inputs.clone(), }) .collect(); + // Nonblocking sites that can stage their value instead of queueing it + // (`NbaSite::pending`). Staged values are published after the queue, + // so a staged target must be one whose update order nothing observes: + // no wait, counter, event domain or comb observer reads it, directly or + // through combinational logic. + if !timing.nba_switches.is_empty() { + let observed = { + let mut observed: HashSet = timing + .wait_sites + .iter() + .flat_map(|site| site.terms.iter().map(|(signal, _)| *signal)) + .chain(timing.counter_slots.iter().map(|slots| slots.signal)) + .chain( + clock_domains + .iter() + .flat_map(|(&alias, &canonical)| [alias, canonical]), + ) + .chain(topological_clocks.iter().copied()) + .chain( + runtime_comb_observers + .iter() + .flat_map(|observer| observer.sensitivity.iter().map(|atom| atom.id)), + ) + .collect(); + for ffs in [ + &eval_apply_ffs, + &eval_comb_apply_ffs, + &eval_only_ffs, + &apply_ffs, + ] { + observed.extend(ffs.keys().copied()); + } + through_comb(observed, &comb_sources) + }; + // The ports of the top module, which the host drives. + let top_ports: HashSet = expanded + .get(&InstancePath(Vec::new())) + .map(|&root| { + modules[&instance_modules[&root]] + .variables + .iter() + .filter(|(_, variable)| { + matches!( + variable.kind, + crate::VariableKind::Input + | crate::VariableKind::Output + | crate::VariableKind::Inout + ) + }) + .map(|(&var_id, _)| bindings.locate(root, var_id)) + .collect() + }) + .unwrap_or_default(); + let staged = staged_nba_sites( + &timing, + eval_comb + .iter() + .chain(eval_apply_ffs.values().flatten()) + .chain(eval_comb_apply_ffs.values().flatten()) + .chain(eval_only_ffs.values().flatten()) + .chain(apply_ffs.values().flatten()) + .chain(processes.iter().map(|process| &process.kernel)), + &top_ports, + &observed, + ); + select_nba_paths(&mut timing, &staged, &mut processes); + } let (process_kernels, process_slots): (Vec<_>, Vec<_>) = processes .into_iter() .map(|process| (process.kernel, process.slots)) @@ -3104,6 +3172,7 @@ struct TimingMetadata { nba_sites: Vec>, host_request_sites: Vec>, time_slots: Vec, + nba_switches: Vec>, } /// For every combinational value, the variables it is computed from. @@ -3239,6 +3308,156 @@ fn split_observed_commits<'k>( split } +/// The switches of the switched nonblocking sites that may stage their +/// value: the site's target has no other writer (no store or commit of any +/// unit, no other nonblocking site, not a top-level port the host drives) +/// and is not in `observed`. +fn staged_nba_sites<'u>( + timing: &TimingMetadata, + units: impl Iterator>, + top_ports: &HashSet, + observed: &HashSet, +) -> HashSet { + let mut written = HashSet::default(); + for unit in units { + for block in unit.blocks.values() { + for instruction in &block.instructions { + match instruction { + SIRInstruction::Store(dst, ..) | SIRInstruction::Commit(_, dst, ..) => { + written.insert(dst.absolute_addr()); + } + _ => {} + } + } + } + } + let mut sites_per_target: HashMap = HashMap::default(); + for site in &timing.nba_sites { + *sites_per_target.entry(site.target).or_default() += 1; + } + let targets: HashMap = timing + .nba_sites + .iter() + .map(|site| (site.value, site.target)) + .collect(); + timing + .nba_switches + .iter() + .filter(|switch| { + let target = targets[&switch.value]; + sites_per_target[&target] == 1 + && !written.contains(&target) + && !top_ports.contains(&target) + && !observed.contains(&target) + }) + .map(|switch| switch.switch) + .collect() +} + +/// Keep one path of every switched nonblocking site: the staged one if its +/// switch is in `staged`, otherwise the queued one, whose value object +/// becomes the site's and which has no `pending` flag. The kernels select +/// the path by a jump; the other path is removed. +fn select_nba_paths( + timing: &mut TimingMetadata, + staged: &HashSet, + processes: &mut [RelocatedProcess], +) { + let switches: HashMap> = timing + .nba_switches + .iter() + .map(|switch| (switch.value, *switch)) + .collect(); + for site in &mut timing.nba_sites { + let Some(switch) = switches.get(&site.value) else { + continue; + }; + if !staged.contains(&switch.switch) { + site.value = switch.queued; + site.pending = None; + } + } + let selections: HashMap = switches + .values() + .map(|switch| (switch.switch, staged.contains(&switch.switch))) + .collect(); + let mut folded = 0; + for process in processes { + folded += fold_nba_switches(&mut process.kernel, &selections); + } + assert_eq!( + folded, + selections.len(), + "every nonblocking switch selects its path once" + ); +} + +/// Replace each branch on a load of a switch in `selections` by a jump to +/// the selected path and remove the blocks no longer reachable. Returns the +/// number of branches replaced. +fn fold_nba_switches( + unit: &mut ExecutionUnit, + selections: &HashMap, +) -> usize { + let mut folded = 0; + for block in unit.blocks.values_mut() { + let SIRTerminator::Branch { + cond, + true_block, + false_block, + } = &block.terminator + else { + continue; + }; + let Some((position, staged)) = + block + .instructions + .iter() + .enumerate() + .find_map(|(position, instruction)| match instruction { + SIRInstruction::Load(register, addr, SIROffset::Static(0), 1) + if register == cond => + { + selections + .get(&addr.absolute_addr()) + .map(|&staged| (position, staged)) + } + _ => None, + }) + else { + continue; + }; + let (target, args) = if staged { true_block } else { false_block }; + block.terminator = SIRTerminator::Jump(*target, args.clone()); + block.instructions.remove(position); + folded += 1; + } + if folded > 0 { + let mut reachable = HashSet::default(); + let mut pending = vec![unit.entry_block_id]; + while let Some(id) = pending.pop() { + if !reachable.insert(id) { + continue; + } + match &unit.blocks[&id].terminator { + SIRTerminator::Jump(next, _) => pending.push(*next), + SIRTerminator::Branch { + true_block, + false_block, + .. + } => pending.extend([true_block.0, false_block.0]), + SIRTerminator::Switch { cases, default, .. } => { + pending.extend(cases.iter().map(|case| case.target)); + pending.push(*default); + } + SIRTerminator::Return | SIRTerminator::Error(_) => {} + } + } + unit.blocks.retain(|id, _| reachable.contains(id)); + } + folded +} + /// Place the timing metadata of every instance. Sites name the global index /// of their process; a kernel numbers its sites in the order they appear /// here, which is the module's order. @@ -3261,6 +3480,7 @@ fn relocate_timing( nba_sites: Vec::new(), host_request_sites: Vec::new(), time_slots: Vec::new(), + nba_switches: Vec::new(), }; for (&instance, module) in instances { let module = &modules[module]; @@ -3292,6 +3512,12 @@ fn relocate_timing( }), ); metadata.time_slots.extend(module.time_slot.map(locate)); + metadata.nba_switches.extend( + module + .nba_switches + .iter() + .map(|switch| switch.map(|&var| locate(var))), + ); } metadata } diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 908fa9d4863..a110471a6e4 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -18,8 +18,8 @@ use celox_design::{ }; use celox_frontend_core::process::PROCESS_RESUME_WIDTH; use celox_frontend_core::symbolic::artifact::{ - ExternalHierarchy, ExternalModule, PackageBinding, SimModule, SymbolicGlueAddr as GlueAddr, - SymbolicProcess, SymbolicRtl, SymbolicVariable, + ExternalHierarchy, ExternalModule, NbaSwitch, PackageBinding, SimModule, + SymbolicGlueAddr as GlueAddr, SymbolicProcess, SymbolicRtl, SymbolicVariable, }; use celox_frontend_core::{ FrontendTrace, FrontendTraceOptions, LoweringPhase, ParserError, ScheduledRtlOutput, @@ -2892,6 +2892,7 @@ fn lower_module_with_overrides( processes, wait_sites, nba_sites, + nba_switches, host_request_sites, event_assignments, ) = lower_initial_processes( @@ -3010,6 +3011,7 @@ fn lower_module_with_overrides( counter_slots: Vec::new(), wait_sites, nba_sites, + nba_switches, host_request_sites, time_slot: name_to_id.get(TIME_SLOT).copied(), }, @@ -3751,6 +3753,7 @@ fn lower_initial_processes( Vec, Vec>, Vec>, + Vec>, Vec>, Vec<(SourceVarId, Vec)>, ), @@ -3826,6 +3829,7 @@ fn lower_initial_processes( Vec::new(), Vec::new(), Vec::new(), + Vec::new(), )); } @@ -3890,6 +3894,7 @@ fn lower_initial_processes( pm.extern_functions = std::mem::take(extern_functions); let mut wait_sites = Vec::new(); let mut nba_sites = Vec::new(); + let mut nba_switches = Vec::new(); let mut host_request_sites = Vec::new(); let processes = runtime .into_iter() @@ -3903,6 +3908,7 @@ fn lower_initial_processes( )?; wait_sites.extend(kernel.wait_sites); nba_sites.extend(kernel.nba_sites); + nba_switches.extend(kernel.nba_switches); host_request_sites.extend(kernel.host_request_sites.into_iter().map(|mut site| { site.process = index; // Repeating ordinary always processes also execute only in @@ -3927,6 +3933,7 @@ fn lower_initial_processes( processes?, wait_sites, nba_sites, + nba_switches, host_request_sites, std::mem::take(&mut pm.event_assignments), )) diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 860fdbc1da6..6acbee996e1 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -72,6 +72,8 @@ pub(super) struct Ff<'p, 'a> { /// The nonblocking assignment sites of the process, by local index. nba_sites: Vec>, host_request_sites: Vec>, + /// The nonblocking sites with a staged and a queued path. + nba_switches: Vec>, direct: bool, } @@ -122,6 +124,7 @@ impl<'p, 'a> Ff<'p, 'a> { wait_sites: Vec::new(), nba_sites: Vec::new(), host_request_sites: Vec::new(), + nba_switches: Vec::new(), } } @@ -4239,6 +4242,7 @@ impl Ff<'_, '_> { wait_sites: self.wait_sites, nba_sites: self.nba_sites, host_request_sites: self.host_request_sites, + nba_switches: self.nba_switches, }) } @@ -4276,19 +4280,25 @@ impl Ff<'_, '_> { }, )?; high = low; + // The staged value has an object of its own: a value still + // staged from earlier in the time slot is queued before it is + // replaced. Assembly keeps the staged or the queued path. + let staged_four_state = self.m.var(staged).is_4state; + let (value, _) = self.m.temp("nba_value", width, false, staged_four_state); + let (pending, _) = self.m.temp("nba_pending", 1, false, false); + let (switch, _) = self.m.temp("nba_staged", 1, false, false); let site = NbaSite { process: self.process, target: id, lsb, width, - value: staged, + value, offset: None, - pending: None, + pending: Some(pending), }; let index = self.nba_sites.len() as u32; - let staged_four_state = self.m.var(staged).is_4state; self.with_kernel(|kernel| { - kernel.nonblocking(index, &site, |builder| { + kernel.nonblocking_switched(index, &site, switch, |builder| { let value = if staged_four_state { builder.alloc_logic(width) } else { @@ -4304,6 +4314,11 @@ impl Ff<'_, '_> { }) }) .map_err(kernel_error)?; + self.nba_switches.push(NbaSwitch { + value, + switch, + queued: staged, + }); self.nba_sites.push(site); } Ok(()) @@ -4738,6 +4753,7 @@ pub(super) struct KernelUnit { pub wait_sites: Vec>, pub nba_sites: Vec>, pub host_request_sites: Vec>, + pub nba_switches: Vec>, } /// Iterations, as a power of two, between the yields of a kernel loop that diff --git a/crates/celox-frontend-veryl/src/artifact.rs b/crates/celox-frontend-veryl/src/artifact.rs index 216018f79ad..f4fce2b13c3 100644 --- a/crates/celox-frontend-veryl/src/artifact.rs +++ b/crates/celox-frontend-veryl/src/artifact.rs @@ -666,6 +666,7 @@ pub(crate) fn project_module_with_ids( counter_slots: Vec::new(), wait_sites: Vec::new(), nba_sites: Vec::new(), + nba_switches: Vec::new(), host_request_sites: Vec::new(), time_slot: None, }, diff --git a/crates/celox-runtime/src/simulation/nba.rs b/crates/celox-runtime/src/simulation/nba.rs index 5db8c839eda..7110263524e 100644 --- a/crates/celox-runtime/src/simulation/nba.rs +++ b/crates/celox-runtime/src/simulation/nba.rs @@ -42,7 +42,8 @@ impl SimulationState { } /// Publish the queued and flagged nonblocking assignments of process - /// kernels (the NBA region, IEEE 1800-2023 4.5). + /// kernels (the NBA region, IEEE 1800-2023 4.5): the queued ones in + /// issue order, then the flagged ones. pub(super) fn publish_nba(&mut self, executor: &mut E, round: &mut Round) -> bool where E: SimulationExecutor, @@ -51,15 +52,44 @@ impl SimulationState { return false; } round.nba_published = true; - let flagged = round.kernels_ran && self.model.has_pending_nba_sites; - if self.process_state.nba_queue.is_empty() && !flagged { + let flagged = if round.kernels_ran && self.model.has_pending_nba_sites { + let backend = executor.backend(); + self.model + .processes + .iter() + .flat_map(|process| &process.nba_sites) + .filter_map(|site| site.pending) + .filter(|&pending| backend.get_as::(pending) != 0) + .count() + } else { + 0 + }; + let mut queued = std::mem::take(&mut self.process_state.nba_queue); + if queued.is_empty() && flagged == 0 { + self.process_state.nba_queue = queued; return false; } - let mut updates = std::mem::take(&mut self.process_state.nba_queue); - if flagged { - let backend = executor.backend_mut(); - for process in &self.model.processes { - for site in &process.nba_sites { + // Several updates may pulse an event signal: each is an update the + // event domains see, not only the final value. + let several = queued.len() + flagged > 1; + if several { + self.event_values(executor.backend(), &mut round.before); + round.transitions.clear(); + } + for update in queued.drain(..) { + let new = NbaValue::Queued(&update.value); + self.publish_update(executor.backend_mut(), &update, new); + if several { + self.record_transitions(executor.backend(), round); + } + } + // Keep the queue's storage for the next time slot. + self.process_state.nba_queue = queued; + if flagged > 0 { + for process in 0..self.model.processes.len() { + for site in 0..self.model.processes[process].nba_sites.len() { + let site = self.model.processes[process].nba_sites[site]; + let backend = executor.backend_mut(); let Some(pending) = site.pending else { continue; }; @@ -70,40 +100,19 @@ impl SimulationState { let offset = site .offset .map_or(0, |offset| backend.get_as::(offset) as usize); - updates.push(NbaUpdate { + let update = NbaUpdate { target: site.target, lsb: site.lsb + offset, width: site.width, - value: read(backend, site.value), - }); + value: Value::default(), + }; + self.publish_update(backend, &update, NbaValue::Staged(site.value)); + if several { + self.record_transitions(executor.backend(), round); + } } } } - if updates.is_empty() { - return false; - } - // Several updates may pulse an event signal: each is an update the - // event domains see, not only the final value. - let several = updates.len() > 1; - if several { - self.event_values(executor.backend(), &mut round.before); - round.transitions.clear(); - } - for update in updates { - let backend = executor.backend_mut(); - let merged = update.merge_into(&read(backend, update.target)); - let target = update.target; - self.write_signal(backend, target, |backend| { - if target.is_4state { - backend.set_four_state(target, merged.0, merged.1); - } else { - backend.set_wide(target, merged.0); - } - }); - if several { - self.record_transitions(executor.backend(), round); - } - } if several { let transitions = std::mem::take(&mut round.transitions); self.mark_occurrences(executor.backend_mut(), round, &transitions); @@ -113,6 +122,55 @@ impl SimulationState { round.track_stable_edges = true; true } + + /// Write `update`, whose value is `new`, into its target. An update + /// inside a target of at most 64 bits with one state plane is merged as + /// `u64`; any other as [`Value`]. + fn publish_update(&mut self, backend: &mut B, update: &NbaUpdate, new: NbaValue<'_>) { + let target = update.target; + let narrow = |signal: SignalRef| { + signal.width <= 64 + && signal.array_layout.is_none() + && !(self.four_state && signal.is_4state) + }; + let inside = update.lsb + update.width <= target.width && narrow(target); + let new = match new { + NbaValue::Queued(value) if inside => Ok(value.0.iter_u64_digits().next().unwrap_or(0)), + NbaValue::Staged(value) if inside && narrow(value) => Ok(backend.get_as::(value)), + NbaValue::Queued(value) => Err(value.clone()), + NbaValue::Staged(value) => Err(read(backend, value)), + }; + match new { + Ok(new) => { + let all = low_bits(target.width); + let old = backend.get_as::(target) & all; + let merged = update.merge_narrow(old, new); + self.write_signal(backend, target, |backend| backend.set(target, merged)); + } + Err(value) => { + let merged = NbaUpdate { value, ..*update }.merge_into(&read(backend, target)); + self.write_signal(backend, target, |backend| { + if target.is_4state { + backend.set_four_state(target, merged.0, merged.1); + } else { + backend.set_wide(target, merged.0); + } + }); + } + } + } +} + +/// The value of a nonblocking update: queued, or staged in a site's value +/// object. +enum NbaValue<'a> { + Queued(&'a Value), + Staged(SignalRef), +} + +/// The low `width` bits of a `u64`, for `width` up to 64. +fn low_bits(width: usize) -> u64 { + u64::MAX >> (64 - width) } /// The working and sparse working state: the next-state values of @@ -156,4 +214,49 @@ impl NbaUpdate { place(&target.1, &self.value.1), ) } + + /// [`Self::merge_into`] for a target of at most 64 bits with one state + /// plane: the bits of the target's value `old` with `new` written in. + fn merge_narrow(&self, old: u64, new: u64) -> u64 { + let all = low_bits(self.target.width); + let range = (low_bits(self.width) << self.lsb) & all; + ((old & !range) | ((new << self.lsb) & range)) & all + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn narrow_merges_match_wide_merges() { + let patterns = [0u64, u64::MAX, 0xa5a5_5a5a_0f0f_f0f0, 0x8000_0000_0000_0001]; + for target_width in [1, 7, 8, 9, 16, 33, 63, 64] { + for lsb in 0..target_width { + for width in 1..=target_width - lsb { + for (old, new) in patterns.iter().zip(patterns.iter().rev()) { + let all = low_bits(target_width); + let update = NbaUpdate { + target: SignalRef { + offset: 0, + width: target_width, + is_4state: false, + array_layout: None, + }, + lsb, + width, + value: (BigUint::from(new & low_bits(width)), BigUint::default()), + }; + let wide = + update.merge_into(&(BigUint::from(old & all), BigUint::default())); + assert_eq!( + BigUint::from(update.merge_narrow(old & all, *new)), + wide.0, + "target {target_width}, lsb {lsb}, width {width}" + ); + } + } + } + } + } } diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index c6c9106baca..a1e41211fcd 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -496,6 +496,98 @@ (assert_eq d 3) (assert_eq sampled 2 "the register samples the value before the edge's update")) +(case staged_nonblocking_updates_keep_their_order + (source "staged_nba.sv" #" + module Top(output logic [7:0] last, count, early, two_sites, stim_seen, sampled); + logic [7:0] x = 8'd0, n = 8'd0, y = 8'd0, stim = 8'd0, r = 8'd0; + logic clk = 1'b0; + always #5 clk = ~clk; + initial begin + #1; + for (int i = 0; i < 3; i++) x <= 8'(i + 4); + repeat (2) n <= n + 8'd1; + for (int i = 0; i < 2; i++) + if (i == 1) y <= 8'd1; + else y <= 8'd2; + #0 early = x; + end + initial forever @(posedge clk) stim <= stim + 8'd3; + always_ff @(posedge clk) r <= stim; + assign last = x; + assign count = n; + assign two_sites = y; + assign stim_seen = stim; + assign sampled = r; + endmodule"#) + (top Top) + (run_until 1) + (assert_eq early 0 "a staged update lands after the inactive region") + (assert_eq last 6 "the last update of one site in a time slot wins") + (assert_eq count 1 "each update reads the value before the slot's updates") + (assert_eq two_sites 1 "updates of two sites land in the order they were issued") + (run_until 26) + (assert_eq stim_seen 9) + (assert_eq sampled 6 "the register samples the value before the edge's update")) + +(case narrow_nonblocking_updates_keep_the_other_bits + (source "narrow_nba.sv" #" + module Top(output logic [16:0] ps, pq, output logic [64:0] ws, wq, + output logic [65:0] xs, xq); + logic [15:0] p = 16'hffff, q = 16'hffff; + logic [63:0] w = 64'd0, v = 64'd0; + logic [64:0] x = 65'd0, y = 65'd0; + initial begin + #1; + p[11:4] <= 8'ha5; + q[11:4] <= 8'h5a; + q[3:0] <= 4'h0; + w <= 64'hfedc_ba98_7654_3210; + v <= 64'h0123_4567_89ab_cdef; + v[63:60] <= 4'h8; + x <= {1'b1, 64'h8000_0000_0000_0001}; + y[64:1] <= 64'hffff_ffff_ffff_ffff; + y[0] <= 1'b0; + end + // Extended, so that no target becomes a port. + assign ps = {1'b0, p}; + assign pq = {1'b0, q}; + assign ws = {1'b0, w}; + assign wq = {1'b0, v}; + assign xs = {1'b0, x}; + assign xq = {1'b0, y}; + endmodule"#) + (top Top) + (run_until 1) + (assert_eq ps 0xfa5f "a part select across a byte boundary keeps the other bits") + (assert_eq pq 0xf5a0) + (assert_eq ws 0xfedcba9876543210 "a 64-bit target takes all its bits") + (assert_eq wq 0x8123456789abcdef) + (assert_eq xs 0x18000000000000001 "a 65-bit target takes all its bits") + (assert_eq xq 0x1fffffffffffffffe)) + +(case four_state_nonblocking_updates_keep_unknown_bits + (source "four_state_nba.sv" #" + module Top(output bit staged, queued, wide); + logic [15:0] p = 16'bx, q = 16'bx; + logic [64:0] x = 65'bx; + initial begin + #1; + p[11:4] <= 8'ha5; + q[11:4] <= 8'h5z; + q[3:0] <= 4'h1; + x[32:1] <= 32'h8000_0001; + end + assign staged = p === 16'bxxxx_1010_0101_xxxx; + assign queued = q === 16'bxxxx_0101_zzzz_0001; + assign wide = x === {32'bx, 32'h8000_0001, 1'bx}; + endmodule"#) + (top Top) + (four_state) + (run_until 1) + (assert_eq staged 1 "an update keeps the unknown bits around it") + (assert_eq queued 1) + (assert_eq wide 1)) + (case nonblocking_ff_stores_remain_pending_during_inactive_work (source "nonblocking.sv" #"module Top(output bit [7:0] q, observed, derived_seen); bit clk; wire [7:0] derived=q+1; diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 70aabb29492..b941eeed532 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -80,6 +80,9 @@ timed_cases! { fn blocking_ff_stores_are_visible_before_inactive_work = "timing::blocking_ff_stores_are_visible_before_inactive_work"; fn blocking_ff_clock_edges_trigger_their_domains_before_inactive_work = "timing::blocking_ff_clock_edges_trigger_their_domains_before_inactive_work"; fn nonblocking_assignments_in_processes_update_in_the_nba_region = "timing::nonblocking_assignments_in_processes_update_in_the_nba_region"; + fn staged_nonblocking_updates_keep_their_order = "timing::staged_nonblocking_updates_keep_their_order"; + fn narrow_nonblocking_updates_keep_the_other_bits = "timing::narrow_nonblocking_updates_keep_the_other_bits"; + fn four_state_nonblocking_updates_keep_unknown_bits = "timing::four_state_nonblocking_updates_keep_unknown_bits"; fn nonblocking_ff_stores_remain_pending_during_inactive_work = "timing::nonblocking_ff_stores_remain_pending_during_inactive_work"; fn mixed_ff_stores_keep_their_active_and_nba_values = "timing::mixed_ff_stores_keep_their_active_and_nba_values"; fn printed_finish_notice_is_design_output = "timing::printed_finish_notice_is_design_output"; @@ -483,3 +486,105 @@ fn timing_controls_outside_suspendable_processes_are_rejected() { assert!(error.contains(construct), "{body}: {error}"); } } + +/// A nonblocking site stages its value (`NbaSite::pending`) only if its +/// target has no other writer and nothing observes the order of the +/// updates in the NBA region: no wait reads the target, directly or through +/// combinational logic, including the `$event` variable of an expression +/// event. Every other site keeps the ordered queue. +#[test] +fn nonblocking_sites_stage_only_unobserved_targets_with_one_writer() { + let source = r#" + module Top(output logic [7:0] q, output bit seen_wait, seen_comb); + timeunit 1ps / 1ps; + logic [7:0] stim = 8'd0, blocking = 8'd0, r = 8'd0; + logic a = 1'b0, b = 1'b0, d = 1'b0, e = 1'b0, s = 1'b0, en = 1'b1, clk = 1'b0; + logic [7:0] hits = 8'd0; + wire c = d & ~e; + always #5 clk = ~clk; + initial forever @(posedge clk) stim <= stim + 8'd3; + always_ff @(posedge clk) r <= stim; + initial begin #2; a <= 1'b1; b <= 1'b1; d <= 1'b1; e <= 1'b1; end + initial begin #10; b <= 1'b1; e <= 1'b1; end + initial begin wait (a && !b); seen_wait = 1'b1; end + initial begin @(posedge c); seen_comb = 1'b1; end + initial forever @(posedge clk) s <= ~s; + initial forever @(posedge (s & en)) hits = hits + 8'd1; + initial begin #1; blocking <= 8'd1; #1 blocking = 8'd2; end + initial begin #1; q <= stim; end + endmodule + "#; + let simulator = celox::Simulator::from_sv_sources( + vec![(source, std::path::Path::new("staged_sites.sv"))], + "Top", + ) + .build() + .unwrap(); + let program = simulator.program(); + let mut staged: Vec<_> = ["stim", "blocking", "a", "b", "d", "e", "s", "q"] + .into_iter() + .filter(|name| { + let target = program.get_addr(&[], &[name]).unwrap(); + program + .runtime_schema + .nba_sites + .iter() + .filter(|site| site.target == target) + .all(|site| site.pending.is_some()) + }) + .collect(); + staged.sort_unstable(); + assert_eq!(staged, ["stim"]); + + // The observed sites keep the ordered queue, and behave as before any + // site could stage: Celox evaluates the waits after the region's + // updates, so neither sees `a && !b` or `c` hold between two of them. + let mut sim = celox::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("staged_sites.sv"))], + "Top", + ) + .build() + .unwrap(); + sim.run_until(26).unwrap(); + assert_eq!(sim.get(sim.signal("seen_wait")), 0u8.into()); + assert_eq!(sim.get(sim.signal("seen_comb")), 0u8.into()); + assert_eq!(sim.get(sim.signal("q")), 0u8.into()); + assert_eq!(sim.get(sim.signal("stim")), 9u8.into()); + assert_eq!(sim.get(sim.signal("r")), 6u8.into()); + assert_eq!(sim.get(sim.signal("hits")), 2u8.into()); +} + +/// The narrow updates case covers staged and queued sites alike. +#[test] +fn narrow_nonblocking_updates_cover_staged_and_queued_sites() { + let design = celox_test_suite::sv::cases() + .find(|case| case.name == "timing::narrow_nonblocking_updates_keep_the_other_bits") + .unwrap() + .design(); + let sources = design + .sources + .iter() + .map(|source| (source.text.as_str(), source.path.as_path())) + .collect::>(); + let simulator = celox::Simulator::from_sv_sources(sources, &design.top) + .build() + .unwrap(); + let program = simulator.program(); + let staged = |name: &str| { + let target = program.get_addr(&[], &[name]).unwrap(); + let sites = program + .runtime_schema + .nba_sites + .iter() + .filter(|site| site.target == target) + .collect::>(); + assert!(!sites.is_empty(), "{name}"); + sites.iter().all(|site| site.pending.is_some()) + }; + for name in ["p", "w", "x"] { + assert!(staged(name), "{name} stages its update"); + } + for name in ["q", "v", "y"] { + assert!(!staged(name), "{name} queues its updates"); + } +}