diff --git a/crates/celox-backend-cranelift/src/wide_ops.rs b/crates/celox-backend-cranelift/src/wide_ops.rs index dab790a1902..46dd3edeb3a 100644 --- a/crates/celox-backend-cranelift/src/wide_ops.rs +++ b/crates/celox-backend-cranelift/src/wide_ops.rs @@ -435,12 +435,14 @@ pub(crate) fn emit_wide_unsigned_cmp( for i in 0..num_chunks { let l = get_chunk_as_i64(builder, l_chunks, i); let r = get_chunk_as_i64(builder, r_chunks, i); - let eq = builder.ins().icmp(IntCC::Equal, l, r); + // Each comparison gives 0 or 1, which a branch may test + // directly: no bitwise complement of it. cond = if matches!(op, BinaryOp::Eq) { + let eq = builder.ins().icmp(IntCC::Equal, l, r); builder.ins().band(cond, eq) } else { - let neq = builder.ins().bnot(eq); - builder.ins().bor(cond, neq) + let ne = builder.ins().icmp(IntCC::NotEqual, l, r); + builder.ins().bor(cond, ne) }; } cond diff --git a/crates/celox-backend-cranelift/tests/wide_equality.rs b/crates/celox-backend-cranelift/tests/wide_equality.rs new file mode 100644 index 00000000000..56e5f144d46 --- /dev/null +++ b/crates/celox-backend-cranelift/tests/wide_equality.rs @@ -0,0 +1,146 @@ +//! A branch on the equality of operands wider than 64 bits takes the side +//! the comparison gives (#2102). +use celox_backend_cranelift::*; +use celox_design::StateObjectId; +use celox_state_layout::{LayoutInput, LayoutSource, MemoryLayoutMode, StateObjectLayout}; +use num_bigint::BigUint; + +struct Objects(Vec>); +impl LayoutSource for Objects { + fn layout_input(&self, _: MemoryLayoutMode) -> LayoutInput { + LayoutInput { + state_objects: self.0.clone(), + working_addresses: vec![], + sparse_addresses: vec![], + unpacked_arrays: HashMap::default(), + requirements: Default::default(), + ff_referenced_addresses: HashSet::default(), + num_events: 0, + runtime_event_sites: vec![], + lane_writers: Default::default(), + access_rank: Default::default(), + } + } +} + +/// Branch on `a op b` for 128-bit `a` and `b`, storing 1 when it holds and 2 +/// otherwise. +fn branch_on(op: BinaryOp, a: &BigUint, b: &BigUint) -> u8 { + let address = |id| AbsoluteAddr { + instance_id: InstanceId(0), + var_id: StateObjectId(id), + }; + let region = |id| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, address(id)); + let layout = MemoryLayout::build( + &Objects( + [(0, 128), (1, 128), (2, 8)] + .into_iter() + .map(|(id, width)| StateObjectLayout { + address: address(id), + width, + is_4state: false, + }) + .collect(), + ), + false, + MemoryLayoutMode::Packed, + ); + let store = |value: u8, register: usize| BasicBlock { + id: BlockId(value as usize), + params: vec![], + instructions: vec![ + SIRInstruction::Imm(RegisterId(register), SIRValue::new(value)), + SIRInstruction::Store( + region(2), + SIROffset::Static(0), + 8, + RegisterId(register), + vec![], + vec![], + ), + ], + terminator: SIRTerminator::Return, + }; + let unit = ExecutionUnit { + entry_block_id: BlockId(0), + blocks: [ + ( + BlockId(0), + BasicBlock { + id: BlockId(0), + params: vec![], + instructions: vec![ + SIRInstruction::Load(RegisterId(0), region(0), SIROffset::Static(0), 128), + SIRInstruction::Load(RegisterId(1), region(1), SIROffset::Static(0), 128), + SIRInstruction::Binary(RegisterId(2), RegisterId(0), op, RegisterId(1)), + ], + terminator: SIRTerminator::Branch { + cond: RegisterId(2), + true_block: (BlockId(1), vec![]), + false_block: (BlockId(2), vec![]), + }, + }, + ), + (BlockId(1), store(1, 3)), + (BlockId(2), store(2, 4)), + ] + .into_iter() + .collect(), + register_map: [(0, 128), (1, 128), (2, 1), (3, 8), (4, 8)] + .into_iter() + .map(|(id, width)| { + ( + RegisterId(id), + RegisterType::Bit { + width, + signed: false, + }, + ) + }) + .collect(), + }; + let mut jit = JitEngine::new( + layout.clone(), + &CompileOptions { + four_state: false, + emit_triggers: false, + cranelift: Default::default(), + }, + ) + .unwrap(); + let entry = jit.compile_units(&[unit], None, None, None).unwrap(); + // The JIT owns this function for the entire test; its ABI is (memory) -> u64. + let run: unsafe extern "C" fn(*mut u8) -> u64 = unsafe { std::mem::transmute(entry) }; + let mut memory = vec![0u8; layout.merged_total_size]; + for (id, value) in [(0, a), (1, b)] { + let offset = layout.offsets[&address(id)]; + let bytes = value.to_bytes_le(); + memory[offset..offset + bytes.len()].copy_from_slice(&bytes); + } + assert_eq!(unsafe { run(memory.as_mut_ptr()) }, 0); + memory[layout.offsets[&address(2)]] +} + +#[test] +fn branches_on_wide_equality_take_the_compared_side() { + let high: BigUint = BigUint::from(1u8) << 100usize; + for (a, b) in [ + (high.clone(), high.clone()), + (high.clone(), &high + 1u8), + (high.clone(), BigUint::from(0u8)), + (BigUint::from(5u8), BigUint::from(5u8)), + ] { + let equal = a == b; + let side = |holds: bool| if holds { 1 } else { 2 }; + assert_eq!( + branch_on(BinaryOp::Eq, &a, &b), + side(equal), + "{a:x} == {b:x}" + ); + assert_eq!( + branch_on(BinaryOp::Ne, &a, &b), + side(!equal), + "{a:x} != {b:x}" + ); + } +} diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index eb9860f1524..0fc8bbbe896 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -892,7 +892,25 @@ pub fn schedule_symbolic_rtl_reporting_loops( .values() .map(|module| modules[module].processes.len()) .sum(); - let scheduler_slots = declare_scheduler_slots(&mut modules, root_id, process_count); + // At most one event per trigger signal of each instance's domains; + // instances connected to one clock share its event. A design with more + // events than its slots hold runs without the compiled scheduler. + let expected_events = instance_modules + .values() + .map(|module| { + let module = &modules[module]; + module + .eval_apply_ff_blocks + .keys() + .chain(module.eval_only_ff_blocks.keys()) + .chain(module.apply_ff_blocks.keys()) + .flat_map(|triggers| std::iter::once(&triggers.clock).chain(&triggers.resets)) + .collect::>() + .len() + }) + .sum::(); + let scheduler_slots = + declare_scheduler_slots(&mut modules, root_id, process_count, expected_events); // Each package with variables is one instance outside the hierarchy, // named by a path segment no instance name can take. let mut package_instances = HashMap::default(); @@ -2754,12 +2772,15 @@ fn declare_settle_flags( /// Declare the hidden objects a compiled scheduler exchanges with the /// runtime (`RuntimeSchema::scheduler`) as variables of the top module, for -/// a design with `process_count` process kernels. A design without kernels -/// has them too: host clocks may run in a compiled scheduler. +/// a design with `process_count` process kernels and about +/// `expected_events` events, whose edge and level masks hold one bit per +/// event in whole 64-bit words. A design without kernels has them too: host +/// clocks may run in a compiled scheduler. fn declare_scheduler_slots( modules: &mut HashMap, root: ModuleId, process_count: usize, + expected_events: usize, ) -> Option> { let variables = &mut modules.get_mut(&root)?.variables; let mut next = variables.keys().map(|id| id.0 + 1).max().unwrap_or(0); @@ -2791,19 +2812,20 @@ fn declare_scheduler_slots( use celox_design::{ SCHEDULER_CLOCKS as CLOCKS, SCHEDULER_FLAG_WIDTH as FLAG, SCHEDULER_TIME_WIDTH as TIME, }; + let events = expected_events.next_multiple_of(TIME).max(TIME); Some(celox_design::SchedulerSlots { limit: declare("limit".into(), TIME), now: declare("now".into(), TIME), exit: declare("exit".into(), FLAG), - exit_arg: declare("exit_arg".into(), TIME), + exit_arg: declare("exit_arg".into(), events), finish: declare("finish".into(), FLAG), cont: declare("cont".into(), FLAG), dirty: declare("dirty".into(), FLAG), defer_limit_settle: declare("defer_limit_settle".into(), FLAG), count: declare("count".into(), TIME), current: declare("current".into(), TIME), - levels: declare("levels".into(), TIME), - unknown_levels: declare("unknown_levels".into(), TIME), + levels: declare("levels".into(), events), + unknown_levels: declare("unknown_levels".into(), events), ready: declare("ready".into(), TIME), wake: (0..process_count) .map(|index| declare(format!("wake[{index}]"), TIME)) diff --git a/crates/celox-runtime/src/schedule.rs b/crates/celox-runtime/src/schedule.rs index fa45770658c..43f2a440909 100644 --- a/crates/celox-runtime/src/schedule.rs +++ b/crates/celox-runtime/src/schedule.rs @@ -63,6 +63,52 @@ pub struct ResolvedSchedule { /// A design's compiled scheduler resolved against a backend: its process /// unit and the slots it exchanges a run with. +/// A set of the compiled scheduler's events, by their bit in `levels`: one +/// 64-bit word per 64 events. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub(crate) struct EventMask(Vec); + +impl EventMask { + /// The set of the events at `bits`. + pub(crate) fn of(bits: impl IntoIterator) -> Self { + let mut mask = Self::default(); + for bit in bits { + let word = bit / 64; + if mask.0.len() <= word { + mask.0.resize(word + 1, 0); + } + mask.0[word] |= 1 << (bit % 64); + } + mask + } + + pub(crate) fn union(&self, other: &Self) -> Self { + let (long, short) = if self.0.len() >= other.0.len() { + (self, other) + } else { + (other, self) + }; + let mut union = long.clone(); + for (word, other) in union.0.iter_mut().zip(&short.0) { + *word |= other; + } + union + } + + /// The events of `self` not in `other`. + pub(crate) fn difference(&self, other: &Self) -> Self { + let mut difference = self.clone(); + for (word, other) in difference.0.iter_mut().zip(&other.0) { + *word &= !other; + } + difference + } + + pub(crate) fn intersects(&self, other: &Self) -> bool { + self.0.iter().zip(&other.0).any(|(a, b)| a & b != 0) + } +} + pub(crate) struct SchedulerRefs { pub(crate) unit: usize, pub(crate) limit: SignalRef, @@ -93,12 +139,12 @@ pub(crate) struct SchedulerRefs { /// in the order of its clock slots. pub(crate) clocks: Vec<(usize, SignalRef)>, /// Per process kernel, the bits of `levels` of the events it writes. - pub(crate) kernel_events: Vec, + pub(crate) kernel_events: Vec, /// Per clock slot, the bit of `levels` of its event. - pub(crate) clock_events: Vec, + pub(crate) clock_events: Vec, /// The bits of `levels` of clocks derived from the others, which any /// slot may change. - pub(crate) derived_events: u64, + pub(crate) derived_events: EventMask, pub(crate) clock_next: SignalRef, pub(crate) clock_period: SignalRef, pub(crate) clock_value: SignalRef, @@ -106,6 +152,16 @@ pub(crate) struct SchedulerRefs { } impl SchedulerRefs { + /// The low word of `exit_arg`, where an exit that names a clock stores + /// its index. The slot is wider when it holds the edges of more than 64 + /// events. + pub(crate) fn exit_index(&self) -> SignalRef { + SignalRef { + width: self.exit_arg.width.min(celox_design::SCHEDULER_TIME_WIDTH), + ..self.exit_arg + } + } + /// Element `bit` of the per-clock slot `slots`. pub(crate) fn clock_element(slots: SignalRef, bit: usize) -> SignalRef { let width = celox_design::SCHEDULER_TIME_WIDTH; @@ -479,12 +535,14 @@ impl ResolvedSchedule { .collect::>()?, kernel_events: (0..scheduler.fallback.len()) .map(|index| { - scheduler - .kernel_events - .get(index) - .into_iter() - .flatten() - .fold(0, |mask, &bit| mask | 1 << bit) + EventMask::of( + scheduler + .kernel_events + .get(index) + .into_iter() + .flatten() + .copied(), + ) }) .collect(), clock_events: scheduler @@ -492,7 +550,7 @@ impl ResolvedSchedule { .iter() .map(|clock| { let bit = scheduler.events.iter().position(|event| event == clock)?; - Some(1 << bit) + Some(EventMask::of([bit])) }) .collect::>()?, clocks: scheduler @@ -507,18 +565,16 @@ impl ResolvedSchedule { clock_period: resolve(&slots.clock_period), clock_value: resolve(&slots.clock_value), clock_armed: resolve(&slots.clock_armed), - derived_events: 0, + derived_events: EventMask::default(), }; // What no kernel and no clock writes itself derives from them. - let all = 1u64 - .checked_shl(refs.events.len() as u32) - .map_or(u64::MAX, |bit| bit - 1); + let all = EventMask::of(0..refs.events.len()); let driven = refs .kernel_events .iter() .chain(&refs.clock_events) - .fold(0, |mask, &bits| mask | bits); - refs.derived_events = all & !driven; + .fold(EventMask::default(), |mask, bits| mask.union(bits)); + refs.derived_events = all.difference(&driven); Some(refs) }), kernel_fallback: model diff --git a/crates/celox-runtime/src/simulation/compiled.rs b/crates/celox-runtime/src/simulation/compiled.rs index 6f459a749d1..39d3529fddb 100644 --- a/crates/celox-runtime/src/simulation/compiled.rs +++ b/crates/celox-runtime/src/simulation/compiled.rs @@ -79,7 +79,7 @@ impl SimulationState { || !pending.nba_events.is_empty() // A derived clock changes with the slots of its sources, which // the scheduler does not tell apart. - || self.observed_events & scheduler.derived_events != 0 + || self.observed_events.intersects(&scheduler.derived_events) || pending.waiters.iter().any(|(process, _)| { scheduler.waits.get(process).is_none_or(Option::is_none) || self.writes_observed(scheduler, process) @@ -109,7 +109,7 @@ impl SimulationState { for event in queue { if clock_slot(scheduler, event, clocks).is_some_and(|bit| { compiled >> bit & 1 != 0 - && scheduler.clock_events[bit] & self.observed_events == 0 + && !scheduler.clock_events[bit].intersects(&self.observed_events) }) { first = first.min(event.time); } else { @@ -141,7 +141,7 @@ impl SimulationState { scheduler .kernel_events .get(process) - .is_some_and(|&events| events & self.observed_events != 0) + .is_some_and(|events| events.intersects(&self.observed_events)) } /// Run the compiled scheduler for the slots up to `limit`. Returns, like @@ -293,7 +293,7 @@ impl SimulationState { let slot_complete = complete || exit == Some(SchedulerExit::ClockOverflow); let overflowed = scheduler .clocks - .get(backend.get_as::(scheduler.exit_arg) as usize) + .get(backend.get_as::(scheduler.exit_index()) as usize) .map(|&(event, _)| event); // Armed clocks wait for their next edge in the event queue again; a // clock whose edge applied in a slot the run left unfinished is gone, @@ -393,12 +393,19 @@ impl SimulationState { } else if count > 0 { // The baseline is the levels slot `now` started from; events the // kernels do not write kept theirs. - let levels: u64 = executor.backend().get_as(scheduler.levels); - let unknown: u64 = if self.four_state { - executor.backend().get_as(scheduler.unknown_levels) - } else { - 0 + // The frontend sizes the slots from an estimate, so they can be + // wider than the events need. + let plane = |slot: crate::SignalRef| -> Box bool> { + if slot.width <= 64 { + let bits: u64 = executor.backend().get_as(slot); + Box::new(move |bit| bits >> bit & 1 != 0) + } else { + let bits = executor.backend().get(slot); + Box::new(move |bit| bits.bit(bit as u64)) + } }; + let level = plane(scheduler.levels); + let unknown = self.four_state.then(|| plane(scheduler.unknown_levels)); // A run without clocks records no level of their events, which // only the clocks change. let scheduler = self @@ -414,8 +421,11 @@ impl SimulationState { clocked || scheduler.clocks.iter().all(|&(clock, _)| clock != id) }) .map(|(bit, &id)| { - let level = (levels >> bit & 1) as u8; - (id, level | ((unknown >> bit & 1) as u8 * LEVEL_UNKNOWN)) + let unknown = unknown.as_ref().is_some_and(|unknown| unknown(bit)); + ( + id, + u8::from(level(bit)) | (u8::from(unknown) * LEVEL_UNKNOWN), + ) }) .collect(); for (id, level) in recorded { diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 17198395437..239dff9968c 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -171,7 +171,7 @@ pub struct SimulationState { /// The bits of the compiled scheduler's events whose changes the host /// observes inside a slot: the kernels and host clocks that write them /// run in the reference loop. - observed_events: u64, + observed_events: crate::schedule::EventMask, } impl SimulationState { @@ -234,7 +234,7 @@ impl SimulationState { return_budget: SLOT_RETURN_BUDGET, slot_passes: 0, stats: SchedulerStats::default(), - observed_events: 0, + observed_events: Default::default(), }; state.stats.kernels = (0..state.model.processes.len()) .map(|index| match state.model.kernel_fallback.get(index) { @@ -427,11 +427,12 @@ impl SimulationState { let Some(scheduler) = &self.model.scheduler else { return; }; - self.observed_events = signals - .into_iter() - .filter_map(|signal| self.model.signal_to_id.get(&signal)) - .filter_map(|event| scheduler.events.iter().position(|id| id == event)) - .fold(0, |mask, bit| mask | 1 << bit); + self.observed_events = crate::schedule::EventMask::of( + signals + .into_iter() + .filter_map(|signal| self.model.signal_to_id.get(&signal)) + .filter_map(|event| scheduler.events.iter().position(|id| id == event)), + ); } /// [`Self::step_until`], showing the step to `observer`. An error of diff --git a/crates/celox/src/derived_edge.rs b/crates/celox/src/derived_edge.rs index 183cb8cae95..d5e4a217b05 100644 --- a/crates/celox/src/derived_edge.rs +++ b/crates/celox/src/derived_edge.rs @@ -19,6 +19,7 @@ use celox_design::{ schedule::ScheduleModel, }; use celox_sir::{BinaryOp, BlockId, SIRBuilder, SIRTerminator, SIRValue, UnaryOp}; +use num_bigint::BigUint; use crate::ir::{ AbsoluteAddr, ExecutionUnit, LaidOutProgram, RegionedAbsoluteAddr, RegisterId, SIRInstruction, @@ -34,8 +35,10 @@ const GATE_WIDTH: usize = 64; /// The deepest stack a gate program may use, as the Rust walk allows. const GATE_STACK: usize = 16; -/// The most domains one edge can fire: one bit each in a fire mask. -const MAX_ENTRIES: usize = 64; +/// The narrowest fire mask, one bit per domain an edge can fire: one 64-bit +/// word, which every edge reaching at most 64 domains uses. An edge reaching +/// more uses as many words as its domains need. +const MIN_ENTRY_BITS: usize = 64; /// The units of one event domain. #[derive(Clone, Debug)] @@ -139,9 +142,6 @@ impl EdgePlan { if comb_fatal { return Err("combinational logic has fatal assertions"); } - if domains.len() + gated.len() + 1 > MAX_ENTRIES { - return Err("an edge reaches too many derived domains"); - } // A derived clock without a domain of its own is left out, as the // Rust walk leaves out a clock without an event. let derived = |address: AbsoluteAddr| -> Result, &'static str> { @@ -204,6 +204,14 @@ impl EdgePlan { .chain(self.gated.iter().map(|gated| &gated.derived.units)) } + /// The width of a fire mask: one bit per entry, at least + /// [`MIN_ENTRY_BITS`] and a whole number of words. + fn entry_bits(&self) -> usize { + (1 + self.domains.len() + self.gated.len()) + .next_multiple_of(64) + .max(MIN_ENTRY_BITS) + } + fn gated_bit(&self, index: usize) -> usize { 1 + self.domains.len() + index } @@ -240,9 +248,11 @@ impl EdgePlan { settled: BlockId, unsettled: BlockId, ) { + let bits = self.entry_bits(); let mut e = Emitter { b, after: Vec::new(), + entry_bits: bits, }; // The state-derived clocks' levels before the edge, the baseline of // their edges for the whole phase. @@ -254,14 +264,14 @@ impl EdgePlan { // The fire section's parameters: the domains to fire, those fired so // far, whether to settle first, and whether the gated domains run // first one at a time (`fire_with_gated`). - let mask = e.b.alloc_bit(MAX_ENTRIES, false); - let fired = e.b.alloc_bit(MAX_ENTRIES, false); + let mask = e.b.alloc_bit(bits, false); + let fired = e.b.alloc_bit(bits, false); let settle_first = e.b.alloc_bit(1, false); let alone = e.b.alloc_bit(1, false); let fire = e.b.new_block_with(vec![mask, fired, settle_first, alone]); let source = e.bit(fires, 0); if self.gated.is_empty() { - let zero = e.constant(0, MAX_ENTRIES); + let zero = e.constant(0, bits); let none = e.binary(1, source, BinaryOp::Eq, zero); let no = e.constant(0, 1); let start = e.b.new_block(); @@ -276,15 +286,15 @@ impl EdgePlan { // The edge: each gated clock judged from its gate program with // the signal at its old and new level. let mut ready = source; - let mut gated_fired = e.constant(0, MAX_ENTRIES); + let mut gated_fired = e.constant(0, bits); let mut after = Vec::with_capacity(self.gated.len()); for (index, gated) in self.gated.iter().enumerate() { let before = e.gate(&gated.gate, from); let level = e.gate(&gated.gate, to); let edge = e.edge(gated.derived.kind, before, level); let bit = e.bit(edge, self.gated_bit(index)); - ready = e.binary(MAX_ENTRIES, ready, BinaryOp::Or, bit); - gated_fired = e.binary(MAX_ENTRIES, gated_fired, BinaryOp::Or, bit); + ready = e.binary(bits, ready, BinaryOp::Or, bit); + gated_fired = e.binary(bits, gated_fired, BinaryOp::Or, bit); after.push(level); } let alone = e.constant(u64::from(self.independent), 1); @@ -299,24 +309,26 @@ impl EdgePlan { e.b.switch_to_block(fire); let fire_end = e.b.new_block(); e.settle_if(settle_first, comb); - let zero = e.constant(0, MAX_ENTRIES); + let zero = e.constant(0, bits); let gated_mask = self .gated .iter() .enumerate() - .fold(0u64, |mask, (index, _)| mask | 1 << self.gated_bit(index)); - let gated_bits = e.constant(gated_mask, MAX_ENTRIES); - let gated_ready = e.binary(MAX_ENTRIES, mask, BinaryOp::And, gated_bits); + .fold(BigUint::ZERO, |mask, (index, _)| { + mask | BigUint::from(1u8) << self.gated_bit(index) + }); + let gated_bits = e.wide_constant(gated_mask, bits); + let gated_ready = e.binary(bits, mask, BinaryOp::And, gated_bits); let any_gated = e.binary(1, gated_ready, BinaryOp::Ne, zero); let in_turn = e.binary(1, alone, BinaryOp::And, any_gated); // Each domain's units appear once in the unit: the one-domain path // also serves the independent gated domains one at a time, and only // domains that can fire with another get the several-domain path. - let one_mask = e.b.alloc_bit(MAX_ENTRIES, false); - let remaining = e.b.alloc_bit(MAX_ENTRIES, false); + let one_mask = e.b.alloc_bit(bits, false); + let remaining = e.b.alloc_bit(bits, false); let turn = e.b.alloc_bit(1, false); let one_domain = e.b.new_block_with(vec![one_mask, remaining, turn]); - let rest = e.b.alloc_bit(MAX_ENTRIES, false); + let rest = e.b.alloc_bit(bits, false); let next_turn = e.b.new_block_with(vec![rest]); let together = e.b.new_block(); e.b.seal_block(SIRTerminator::Branch { @@ -333,8 +345,8 @@ impl EdgePlan { .chain(std::iter::once(0)) .collect(); for entry in order { - let bit = e.constant(1 << entry, MAX_ENTRIES); - let selected = e.binary(MAX_ENTRIES, rest, BinaryOp::And, bit); + let bit = e.single(entry, bits); + let selected = e.binary(bits, rest, BinaryOp::And, bit); let set = e.binary(1, selected, BinaryOp::Ne, zero); let take = e.b.new_block(); let skip = e.b.new_block(); @@ -344,9 +356,9 @@ impl EdgePlan { false_block: (skip, Vec::new()), }); e.b.switch_to_block(take); - let all = e.constant(u64::MAX, MAX_ENTRIES); - let others = e.binary(MAX_ENTRIES, bit, BinaryOp::Xor, all); - let left = e.binary(MAX_ENTRIES, rest, BinaryOp::And, others); + let all = e.ones(bits); + let others = e.binary(bits, bit, BinaryOp::Xor, all); + let left = e.binary(bits, rest, BinaryOp::And, others); let yes = e.constant(1, 1); e.b.seal_block(SIRTerminator::Jump(one_domain, vec![bit, left, yes])); e.b.switch_to_block(skip); @@ -356,13 +368,13 @@ impl EdgePlan { // The domains together: one evaluates and commits at once, several // evaluate, then commit, in entry order. e.b.switch_to_block(together); - let one = e.constant(1, MAX_ENTRIES); - let lower = e.binary(MAX_ENTRIES, mask, BinaryOp::Sub, one); - let others = e.binary(MAX_ENTRIES, mask, BinaryOp::And, lower); + let one = e.constant(1, bits); + let lower = e.binary(bits, mask, BinaryOp::Sub, one); + let others = e.binary(bits, mask, BinaryOp::And, lower); let single = e.binary(1, others, BinaryOp::Eq, zero); let several = e.b.new_block(); let no = e.constant(0, 1); - let none_left = e.constant(0, MAX_ENTRIES); + let none_left = e.constant(0, bits); e.b.seal_block(SIRTerminator::Branch { cond: single, true_block: (one_domain, vec![mask, none_left, no]), @@ -400,23 +412,23 @@ impl EdgePlan { // domains not fired yet whose clocks moved to their active edge. e.b.switch_to_block(fire_end); e.inline_all(comb); - let mut ready = e.constant(0, MAX_ENTRIES); + let mut ready = e.constant(0, bits); for (index, domain) in self.domains.iter().enumerate() { let is = e.level(domain.signal, domain.width); let edge = e.edge(domain.kind, was[index], is); let bit = e.bit(edge, 1 + index); - ready = e.binary(MAX_ENTRIES, ready, BinaryOp::Or, bit); + ready = e.binary(bits, ready, BinaryOp::Or, bit); } let after = std::mem::take(&mut e.after); for (index, gated) in self.gated.iter().enumerate() { let is = e.gate(&gated.gate, to); let edge = e.edge(gated.derived.kind, after[index], is); let bit = e.bit(edge, self.gated_bit(index)); - ready = e.binary(MAX_ENTRIES, ready, BinaryOp::Or, bit); + ready = e.binary(bits, ready, BinaryOp::Or, bit); } - let all = e.constant(u64::MAX, MAX_ENTRIES); - let unfired = e.binary(MAX_ENTRIES, fired, BinaryOp::Xor, all); - let ready = e.binary(MAX_ENTRIES, ready, BinaryOp::And, unfired); + let all = e.ones(bits); + let unfired = e.binary(bits, fired, BinaryOp::Xor, all); + let ready = e.binary(bits, ready, BinaryOp::And, unfired); let quiet = e.binary(1, ready, BinaryOp::Eq, zero); let round = e.b.new_block(); e.b.seal_block(SIRTerminator::Branch { @@ -425,7 +437,7 @@ impl EdgePlan { false_block: (round, Vec::new()), }); e.b.switch_to_block(round); - let now_fired = e.binary(MAX_ENTRIES, fired, BinaryOp::Or, ready); + let now_fired = e.binary(bits, fired, BinaryOp::Or, ready); let no = e.constant(0, 1); e.b.seal_block(SIRTerminator::Jump(fire, vec![ready, now_fired, no, no])); } @@ -491,16 +503,32 @@ struct Emitter<'b> { /// The gated clocks' levels just after the edge, the baseline of their /// further edges in the rounds. after: Vec, + /// See [`EdgePlan::entry_bits`]. + entry_bits: usize, } impl Emitter<'_> { fn constant(&mut self, value: u64, width: usize) -> RegisterId { + self.wide_constant(BigUint::from(value), width) + } + + fn wide_constant(&mut self, value: BigUint, width: usize) -> RegisterId { let register = self.b.alloc_bit(width, false); self.b .emit(SIRInstruction::Imm(register, SIRValue::new(value))); register } + /// The `width`-bit value with only bit `bit` set. + fn single(&mut self, bit: usize, width: usize) -> RegisterId { + self.wide_constant(BigUint::from(1u8) << bit, width) + } + + /// The `width`-bit value with every bit set. + fn ones(&mut self, width: usize) -> RegisterId { + self.wide_constant((BigUint::from(1u8) << width) - 1u8, width) + } + fn binary( &mut self, width: usize, @@ -561,9 +589,9 @@ impl Emitter<'_> { /// Bit `index` of a fire mask, set when `condition` holds. fn bit(&mut self, condition: RegisterId, index: usize) -> RegisterId { - let set = self.constant(1 << index, MAX_ENTRIES); - let unset = self.constant(0, MAX_ENTRIES); - let bit = self.b.alloc_bit(MAX_ENTRIES, false); + let set = self.single(index, self.entry_bits); + let unset = self.constant(0, self.entry_bits); + let bit = self.b.alloc_bit(self.entry_bits, false); self.b.emit(SIRInstruction::Mux(bit, condition, set, unset)); bit } @@ -695,9 +723,9 @@ impl Emitter<'_> { /// Run `body` when bit `index` of `mask` is set. fn if_bit(&mut self, mask: RegisterId, index: usize, body: impl FnOnce(&mut Self)) { - let selector = self.constant(1 << index, MAX_ENTRIES); - let selected = self.binary(MAX_ENTRIES, mask, BinaryOp::And, selector); - let zero = self.constant(0, MAX_ENTRIES); + let selector = self.single(index, self.entry_bits); + let selected = self.binary(self.entry_bits, mask, BinaryOp::And, selector); + let zero = self.constant(0, self.entry_bits); let set = self.binary(1, selected, BinaryOp::Ne, zero); let run = self.b.new_block(); let next = self.b.new_block(); @@ -1227,11 +1255,17 @@ mod tests { /// repeated edges, and host writes of `en` when the design has it. fn ticks_agree(source: &str) { let build = || Simulator::from_sv_sources(vec![(source, Path::new("top.sv"))], "Top"); - let mut generated = build().build().unwrap(); - let mut walked = build() - .disable_pass(crate::SirPass::DerivedEdgeUnits) - .build() - .unwrap(); + ticks_agree_on( + build().build().unwrap(), + build() + .disable_pass(crate::SirPass::DerivedEdgeUnits) + .build() + .unwrap(), + ); + } + + /// [`ticks_agree`] for two simulators of one backend. + fn ticks_agree_on(mut generated: Simulator, mut walked: Simulator) { assert!( !generated.program.runtime_schema.derived_edges.is_empty(), "no edge unit was generated" @@ -1273,17 +1307,15 @@ mod tests { } } - /// An edge reaching 60 gated domains. - #[test] - fn an_edge_reaching_60_gated_domains_runs_as_the_plan_walk() { - const GATED_CLOCKS: usize = 60; + /// One `clk` gating `gated_clocks` clocks, each clocking a counter. + fn gated_domains_source(gated_clocks: usize) -> String { let mut source = String::from( "module Top(input logic clk, input logic en, output logic [7:0] q);\n \ logic [6:0] count = 0;\n logic [7:0] sum;\n \ always_ff @(posedge clk) count <= count + 7'd1;\n", ); let mut terms = Vec::new(); - for index in 0..GATED_CLOCKS { + for index in 0..gated_clocks { source += &format!( " logic g{index};\n logic [7:0] n{index} = 0;\n \ assign g{index} = clk & (en ^ (count[2:0] == 3'd{bits}) ^ (count[6:3] == 4'd{high}));\n \ @@ -1294,7 +1326,34 @@ mod tests { terms.push(format!("n{index}")); } source += &format!(" assign q = {};\nendmodule\n", terms.join(" ^ ")); - ticks_agree(&source); + source + } + + /// An edge reaching 60 gated domains. + #[test] + fn an_edge_reaching_60_gated_domains_runs_as_the_plan_walk() { + ticks_agree(&gated_domains_source(60)); + } + + /// An edge reaching more domains than one word of a fire mask holds. + #[test] + fn an_edge_reaching_more_than_64_domains_runs_as_the_plan_walk() { + ticks_agree(&gated_domains_source(70)); + } + + /// The same on Cranelift, whose wide comparisons once ran every domain. + #[test] + fn an_edge_reaching_more_than_64_domains_runs_on_cranelift_as_the_plan_walk() { + let source = gated_domains_source(70); + let build = + || Simulator::from_sv_sources(vec![(source.as_str(), Path::new("top.sv"))], "Top"); + ticks_agree_on( + build().build_cranelift().unwrap(), + build() + .disable_pass(crate::SirPass::DerivedEdgeUnits) + .build_cranelift() + .unwrap(), + ); } #[test] diff --git a/crates/celox/src/scheduler.rs b/crates/celox/src/scheduler.rs index e81311b3f10..4449ea6b5e4 100644 --- a/crates/celox/src/scheduler.rs +++ b/crates/celox/src/scheduler.rs @@ -41,6 +41,7 @@ use celox_design::{ TIME_SLOT_WIDTH, edges::LEVEL_UNKNOWN, schedule::ScheduleModel, }; use celox_sir::{BinaryOp, SIRBuilder, SIRSwitchCase, SIRValue}; +use num_bigint::BigUint; use std::collections::BTreeSet; use crate::{ @@ -54,8 +55,10 @@ use crate::{ type Unit = ExecutionUnit; type Builder = SIRBuilder; -/// The most events whose edges one slot can record. -const MAX_EVENTS: usize = 64; +/// The narrowest event mask: one 64-bit word, which every design with at +/// most 64 events uses. A design with more uses as many words as its events +/// need. +const MIN_EVENT_BITS: usize = 64; /// The most kernels the ready mask of a slot holds. const MAX_KERNELS: usize = 64; @@ -256,6 +259,9 @@ struct Plan { /// combinationally from them, with those clocks: their edges are judged /// when the source changes. gating: Vec<(usize, Vec)>, + /// The width of an event mask: one bit per event, at least + /// [`MIN_EVENT_BITS`] and a whole number of words. + event_bits: usize, } /// Deferred settles. The reference loop settles after every pass of the @@ -316,7 +322,6 @@ impl Plan { if !schema.comb_observers.is_empty() { return Err("the design observes combinational processes".into()); } - const _: () = assert!(MAX_EVENTS <= SCHEDULER_CLOCKS); if slots.wake.len() != schema.processes.len() { return Err("the scheduler slots do not match the kernels".into()); } @@ -339,8 +344,19 @@ impl Plan { let shared = program.shared_storage(); let storage = |address: AbsoluteAddr| shared.get(&address).copied().unwrap_or(address); let addresses = crate::edge_plans::event_addresses(program); - if addresses.len() > MAX_EVENTS { - return Err(format!("the design has more than {MAX_EVENTS} events")); + let event_bits = addresses.len().next_multiple_of(64).max(MIN_EVENT_BITS); + // The masks of the edges and levels of a slot live in these slots, + // which the frontend sized for the events it expected. + for (name, slot) in [ + ("levels", slots.levels), + ("unknown_levels", slots.unknown_levels), + ("exit_arg", slots.exit_arg), + ] { + if program.layout().widths.get(&slot).copied().unwrap_or(0) < event_bits { + return Err(format!( + "the design has more events than its scheduler's {name} slot holds" + )); + } } let mut events = Vec::with_capacity(addresses.len()); let mut event_storage = HashMap::default(); @@ -515,6 +531,11 @@ impl Plan { }) .map(|(index, _)| index) .collect(); + if clocks.len() > SCHEDULER_CLOCKS { + return Err(format!( + "the design has more than {SCHEDULER_CLOCKS} host clock events" + )); + } let mut kernels: Vec> = Vec::with_capacity(schema.processes.len()); let mut fallback = Vec::with_capacity(schema.processes.len()); @@ -865,6 +886,7 @@ impl Plan { lazy, derived: Vec::new(), gating: Vec::new(), + event_bits, }; let edged = plan.edged(); // The clocks derived from the events the slots change, transitively: @@ -1086,6 +1108,7 @@ impl Plan { .layout() .four_state .then_some(&program.layout().is_4states), + event_bits: self.event_bits, }; let waits: Vec<(usize, &Wait)> = self .kernels @@ -1267,8 +1290,8 @@ impl Plan { // any kernel runs; their edges start the slot's edges, which // collect in `exit_arg`. A clock whose edge applied waits for its // next edge until the slot ends. A run without clocks skips them. - let zero = g.constant(0, MAX_EVENTS); - g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, zero); + let zero = g.constant(0, self.event_bits); + g.store(slots.exit_arg, self.event_bits, zero); let finish_exit = g.exit_block(SchedulerExit::Finish); let internal_exit = g.exit_block(SchedulerExit::Internal); let pick = g.b.new_block(); @@ -1282,7 +1305,7 @@ impl Plan { g.b.switch_to_block(apply); let values = g.load(slots.clock_value, SCHEDULER_TIME_WIDTH); let mut fired = g.constant(0, SCHEDULER_CLOCKS); - let mut edges = g.constant(0, MAX_EVENTS); + let mut edges = g.constant(0, self.event_bits); let mut levels = g.load_levels(); for (bit, &index) in self.clocks.iter().enumerate() { let event = &self.events[index]; @@ -1333,13 +1356,13 @@ impl Plan { g.store(slots.dirty, SCHEDULER_FLAG_WIDTH, dirty); } let edge = g.edge(event, was, is); - let edge = g.bit(edge, index); - edges = g.binary(MAX_EVENTS, edges, BinaryOp::Or, edge); + let edge = g.event_bit(edge, index); + edges = g.binary(self.event_bits, edges, BinaryOp::Or, edge); let bit = g.bit(due, bit); fired = g.binary(SCHEDULER_CLOCKS, fired, BinaryOp::Or, bit); } g.store_levels(levels); - g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, edges); + g.store(slots.exit_arg, self.event_bits, edges); let all = g.constant(u64::MAX, SCHEDULER_CLOCKS); let unfired = g.binary(SCHEDULER_CLOCKS, fired, BinaryOp::Xor, all); let armed = g.binary(SCHEDULER_CLOCKS, armed, BinaryOp::And, unfired); @@ -1467,14 +1490,14 @@ impl Plan { // The edges of this run, against the levels before it. g.b.switch_to_block(resumed); - let mut edges = g.load(slots.exit_arg, MAX_EVENTS); + let mut edges = g.load(slots.exit_arg, self.event_bits); for (&event, &was) in kernel.writes.iter().zip(&before) { let is = g.level(&self.events[event]); let edge = g.edge(&self.events[event], was, is); - let bit = g.bit(edge, event); - edges = g.binary(MAX_EVENTS, edges, BinaryOp::Or, bit); + let bit = g.event_bit(edge, event); + edges = g.binary(self.event_bits, edges, BinaryOp::Or, bit); } - g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, edges); + g.store(slots.exit_arg, self.event_bits, edges); } Some(wait) => { // A kernel runs at most once a slot (see `Plan::new`), so @@ -1569,8 +1592,8 @@ impl Plan { self.batch(&mut g, &tracked, slot_end, finish_exit); } else { let staged: Vec<&Staged> = waits.iter().flat_map(|(_, wait)| &wait.sites).collect(); - let mask = g.load(slots.exit_arg, MAX_EVENTS); - let zero = g.constant(0, MAX_EVENTS); + let mask = g.load(slots.exit_arg, self.event_bits); + let zero = g.constant(0, self.event_bits); let quiet = g.binary(1, mask, BinaryOp::Eq, zero); let triggered = g.b.new_block(); let untriggered = g.b.new_block(); @@ -1610,9 +1633,9 @@ impl Plan { // No event can have an edge; the mask stays empty. g.b.seal_block(SIRTerminator::Jump(evaluated, Vec::new())); } else { - let one = g.constant(1, MAX_EVENTS); - let lower = g.binary(MAX_EVENTS, mask, BinaryOp::Sub, one); - let others = g.binary(MAX_EVENTS, mask, BinaryOp::And, lower); + let one = g.constant(1, self.event_bits); + let lower = g.binary(self.event_bits, mask, BinaryOp::Sub, one); + let others = g.binary(self.event_bits, mask, BinaryOp::And, lower); let single = g.binary(1, others, BinaryOp::Eq, zero); let one_domain = g.b.new_block(); let domains = g.b.new_block(); @@ -1629,7 +1652,7 @@ impl Plan { let written = self.written(); for &index in written.iter().chain(&self.clocks) { let event = &self.events[index]; - let bit = g.constant(1 << index, MAX_EVENTS); + let bit = g.single(index, self.event_bits); let this = g.binary(1, mask, BinaryOp::Eq, bit); let unit = g.b.new_block(); let next = g.b.new_block(); @@ -1687,14 +1710,14 @@ impl Plan { let evaluate = g.b.new_block(); g.settle_then(evaluate); g.b.switch_to_block(evaluate); - mask = g.load(slots.exit_arg, MAX_EVENTS); - zero = g.constant(0, MAX_EVENTS); + mask = g.load(slots.exit_arg, self.event_bits); + zero = g.constant(0, self.event_bits); } for phase in [Phase::Evaluate, Phase::Apply] { for &index in &edged { let event = &self.events[index]; - let bit = g.constant(1 << index, MAX_EVENTS); - let selected = g.binary(MAX_EVENTS, mask, BinaryOp::And, bit); + let bit = g.single(index, self.event_bits); + let selected = g.binary(self.event_bits, mask, BinaryOp::And, bit); let this = g.binary(1, selected, BinaryOp::Ne, zero); let unit = g.b.new_block(); let next = g.b.new_block(); @@ -1843,7 +1866,7 @@ impl Plan { ) { let slots = g.slots; let wave = g.b.new_block(); - let mask = g.b.alloc_bit(MAX_EVENTS, false); + let mask = g.b.alloc_bit(self.event_bits, false); let fire = g.b.new_block_with(vec![mask]); let judge = g.b.new_block(); // A pass of the process phase settles before the domains; a @@ -1856,10 +1879,10 @@ impl Plan { } g.b.switch_to_block(judge); - let active = g.load(slots.exit_arg, MAX_EVENTS); + let active = g.load(slots.exit_arg, self.event_bits); let levels = g.load_levels(); let stable = self.stable_edges(g, tracked, levels); - let mut gated_edges = g.constant(0, MAX_EVENTS); + let mut gated_edges = g.constant(0, self.event_bits); let mut judged = levels; for (source, gated) in &self.gating { let source_bit = position(tracked, *source); @@ -1872,8 +1895,8 @@ impl Plan { let is = g.level(&self.events[clock]); let edge = g.edge(&self.events[clock], was, is); let edge = g.binary(1, edge, BinaryOp::And, changed); - let bit = g.bit(edge, clock); - gated_edges = g.binary(MAX_EVENTS, gated_edges, BinaryOp::Or, bit); + let bit = g.event_bit(edge, clock); + gated_edges = g.binary(self.event_bits, gated_edges, BinaryOp::Or, bit); // The judged level is the clock's baseline from now on. let level = g.b.alloc_bit(g.level_width(), false); g.b.emit(SIRInstruction::Mux(level, changed, is, was)); @@ -1881,12 +1904,12 @@ impl Plan { } } g.store_levels(judged); - let zero = g.constant(0, MAX_EVENTS); + let zero = g.constant(0, self.event_bits); let edged = g.binary(1, active, BinaryOp::Ne, zero); - let sources = g.binary(MAX_EVENTS, active, BinaryOp::Or, gated_edges); - let triggers = g.b.alloc_bit(MAX_EVENTS, false); + let sources = g.binary(self.event_bits, active, BinaryOp::Or, gated_edges); + let triggers = g.b.alloc_bit(self.event_bits, false); g.b.emit(SIRInstruction::Mux(triggers, edged, sources, stable)); - g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, triggers); + g.store(slots.exit_arg, self.event_bits, triggers); let quiet = g.binary(1, triggers, BinaryOp::Eq, zero); let first = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { @@ -1899,13 +1922,13 @@ impl Plan { // A wave after a commit: the domains not run yet whose clocks moved. g.b.switch_to_block(wave); - let fired = g.load(slots.exit_arg, MAX_EVENTS); + let fired = g.load(slots.exit_arg, self.event_bits); let levels = g.load_levels(); let stable = self.stable_edges(g, tracked, levels); - let all = g.constant(u64::MAX, MAX_EVENTS); - let unfired = g.binary(MAX_EVENTS, fired, BinaryOp::Xor, all); - let ready = g.binary(MAX_EVENTS, stable, BinaryOp::And, unfired); - let zero = g.constant(0, MAX_EVENTS); + let all = g.ones(self.event_bits); + let unfired = g.binary(self.event_bits, fired, BinaryOp::Xor, all); + let ready = g.binary(self.event_bits, stable, BinaryOp::And, unfired); + let zero = g.constant(0, self.event_bits); let quiet = g.binary(1, ready, BinaryOp::Eq, zero); let next = g.b.new_block(); g.b.seal_block(SIRTerminator::Branch { @@ -1914,17 +1937,17 @@ impl Plan { false_block: (next, Vec::new()), }); g.b.switch_to_block(next); - let fired = g.binary(MAX_EVENTS, fired, BinaryOp::Or, ready); - g.store(slots.exit_arg, SCHEDULER_TIME_WIDTH, fired); + let fired = g.binary(self.event_bits, fired, BinaryOp::Or, ready); + g.store(slots.exit_arg, self.event_bits, fired); g.b.seal_block(SIRTerminator::Jump(fire, vec![ready])); // A wave: one domain evaluates and commits at once, several // evaluate, then commit, in event order; then logic settles. g.b.switch_to_block(fire); - let zero = g.constant(0, MAX_EVENTS); - let one = g.constant(1, MAX_EVENTS); - let lower = g.binary(MAX_EVENTS, mask, BinaryOp::Sub, one); - let others = g.binary(MAX_EVENTS, mask, BinaryOp::And, lower); + let zero = g.constant(0, self.event_bits); + let one = g.constant(1, self.event_bits); + let lower = g.binary(self.event_bits, mask, BinaryOp::Sub, one); + let others = g.binary(self.event_bits, mask, BinaryOp::And, lower); let single = g.binary(1, others, BinaryOp::Eq, zero); let alone = g.b.new_block(); let together = g.b.new_block(); @@ -1969,13 +1992,13 @@ impl Plan { /// The tracked events whose levels moved to their active edge against /// `levels`, their baselines, as bits by event index. fn stable_edges(&self, g: &mut Generator<'_>, tracked: &[usize], levels: Levels) -> RegisterId { - let mut edges = g.constant(0, MAX_EVENTS); + let mut edges = g.constant(0, self.event_bits); for (position, &index) in tracked.iter().enumerate() { let was = g.saved_level(levels, position); let is = g.level(&self.events[index]); let edge = g.edge(&self.events[index], was, is); - let bit = g.bit(edge, index); - edges = g.binary(MAX_EVENTS, edges, BinaryOp::Or, bit); + let bit = g.event_bit(edge, index); + edges = g.binary(self.event_bits, edges, BinaryOp::Or, bit); } edges } @@ -2023,16 +2046,38 @@ struct Generator<'a> { /// loads and stores move both planes, and edge levels are four-state /// (see [`Self::level_at`]). `None` in a two-state design. four_state: Option<&'a crate::HashMap>, + /// See [`Plan::event_bits`]. + event_bits: usize, } impl Generator<'_> { fn constant(&mut self, value: u64, width: usize) -> RegisterId { + self.wide_constant(BigUint::from(value), width) + } + + fn wide_constant(&mut self, value: BigUint, width: usize) -> RegisterId { let register = self.b.alloc_bit(width, false); self.b .emit(SIRInstruction::Imm(register, SIRValue::new(value))); register } + /// The `width`-bit value with only bit `bit` set. + fn single(&mut self, bit: usize, width: usize) -> RegisterId { + self.wide_constant(BigUint::from(1u8) << bit, width) + } + + /// The `width`-bit value with every bit but `bit` set. + fn all_but(&mut self, bit: usize, width: usize) -> RegisterId { + let ones = (BigUint::from(1u8) << width) - 1u8; + self.wide_constant(ones ^ (BigUint::from(1u8) << bit), width) + } + + /// The `width`-bit value with every bit set. + fn ones(&mut self, width: usize) -> RegisterId { + self.wide_constant((BigUint::from(1u8) << width) - 1u8, width) + } + fn binary( &mut self, width: usize, @@ -2100,7 +2145,7 @@ impl Generator<'_> { /// Whether bit `bit` of `mask` is set. fn mask_bit(&mut self, mask: RegisterId, bit: usize) -> RegisterId { let width = self.b.register(&mask).width(); - let selector = self.constant(1 << bit, width); + let selector = self.single(bit, width); let selected = self.binary(width, mask, BinaryOp::And, selector); let zero = self.constant(0, width); self.binary(1, selected, BinaryOp::Ne, zero) @@ -2270,22 +2315,22 @@ impl Generator<'_> { /// `levels` with `level` at bit `bit`, which was clear. fn with_level(&mut self, levels: Levels, level: RegisterId, bit: usize) -> Levels { let (value, unknown) = self.level_planes(level); - let set = self.bit(value, bit); - let values = self.binary(MAX_EVENTS, levels.values, BinaryOp::Or, set); + let set = self.event_bit(value, bit); + let values = self.binary(self.event_bits, levels.values, BinaryOp::Or, set); let unknown = levels.unknown.map(|levels| { - let set = self.bit(unknown.expect("a four-state level"), bit); - self.binary(MAX_EVENTS, levels, BinaryOp::Or, set) + let set = self.event_bit(unknown.expect("a four-state level"), bit); + self.binary(self.event_bits, levels, BinaryOp::Or, set) }); Levels { values, unknown } } /// `levels` with `level` in place of the one at bit `bit`. fn replace_level(&mut self, levels: Levels, level: RegisterId, bit: usize) -> Levels { - let keep = self.constant(!(1u64 << bit), MAX_EVENTS); - let values = self.binary(MAX_EVENTS, levels.values, BinaryOp::And, keep); + let keep = self.all_but(bit, self.event_bits); + let values = self.binary(self.event_bits, levels.values, BinaryOp::And, keep); let unknown = levels .unknown - .map(|unknown| self.binary(MAX_EVENTS, unknown, BinaryOp::And, keep)); + .map(|unknown| self.binary(self.event_bits, unknown, BinaryOp::And, keep)); self.with_level(Levels { values, unknown }, level, bit) } @@ -2305,32 +2350,32 @@ impl Generator<'_> { /// No saved levels: every event at 0. fn no_levels(&mut self) -> Levels { - let values = self.constant(0, MAX_EVENTS); + let values = self.constant(0, self.event_bits); let unknown = self .four_state .is_some() - .then(|| self.constant(0, MAX_EVENTS)); + .then(|| self.constant(0, self.event_bits)); Levels { values, unknown } } /// The levels of [`SchedulerSlots::levels`]. fn load_levels(&mut self) -> Levels { - let values = self.load(self.slots.levels, MAX_EVENTS); + let values = self.load(self.slots.levels, self.event_bits); let unknown = self .four_state .is_some() - .then(|| self.load(self.slots.unknown_levels, MAX_EVENTS)); + .then(|| self.load(self.slots.unknown_levels, self.event_bits)); Levels { values, unknown } } fn store_levels(&mut self, levels: Levels) { - self.store(self.slots.levels, SCHEDULER_TIME_WIDTH, levels.values); + self.store(self.slots.levels, self.event_bits, levels.values); if let Some(unknown) = levels.unknown { - self.store(self.slots.unknown_levels, SCHEDULER_TIME_WIDTH, unknown); + self.store(self.slots.unknown_levels, self.event_bits, unknown); } } - /// Run `body` when bit `index` of the 64-bit `mask` is set. + /// Run `body` when bit `index` of `mask` is set. fn if_bit(&mut self, mask: RegisterId, index: usize, body: impl FnOnce(&mut Self)) { let set = self.mask_bit(mask, index); let run = self.b.new_block(); @@ -2354,11 +2399,20 @@ impl Generator<'_> { block } - /// Bit `index` of a 64-bit mask, set when `condition` holds. + /// Bit `index` of a kernel or clock mask, set when `condition` holds. fn bit(&mut self, condition: RegisterId, index: usize) -> RegisterId { - let set = self.constant(1 << index, MAX_KERNELS); - let unset = self.constant(0, MAX_KERNELS); - let bit = self.b.alloc_bit(MAX_KERNELS, false); + self.bit_of(condition, index, MAX_KERNELS) + } + + /// Bit `index` of an event mask, set when `condition` holds. + fn event_bit(&mut self, condition: RegisterId, index: usize) -> RegisterId { + self.bit_of(condition, index, self.event_bits) + } + + fn bit_of(&mut self, condition: RegisterId, index: usize, width: usize) -> RegisterId { + let set = self.single(index, width); + let unset = self.constant(0, width); + let bit = self.b.alloc_bit(width, false); self.b.emit(SIRInstruction::Mux(bit, condition, set, unset)); bit } @@ -3195,3 +3249,141 @@ mod tests { } } } + +#[cfg(all(test, feature = "systemverilog"))] +mod wide_event_tests { + use num_bigint::BigUint; + + const CLOCKS: usize = 70; + const PERIODS: usize = 7; + const END: u64 = 100; + + /// 70 clocks, each clocking a counter. One process per period toggles + /// its clocks, so the events exceed a word while the kernels stay few. + fn more_than_64_events() -> String { + let mut source = String::from("`timescale 1ns/1ns\nmodule Top;\n"); + for index in 0..CLOCKS { + source += &format!( + " logic c{index} = 0;\n logic [7:0] n{index} = 0;\n \ + always_ff @(posedge c{index}) n{index} <= n{index} + 8'd1;\n" + ); + } + for period in 1..=PERIODS { + let toggles: String = (0..CLOCKS) + .filter(|index| index % PERIODS + 1 == period) + .map(|index| format!(" c{index} = ~c{index};")) + .collect(); + source += &format!(" always #{period} begin{toggles} end\n"); + } + source + "endmodule\n" + } + + fn builder(source: &str) -> crate::SimulatorBuilder<'_, crate::Simulation> { + crate::Simulation::from_sv_sources(vec![(source, std::path::Path::new("events.sv"))], "Top") + } + + /// Run to `END` and check every counter against its clock's edges; + /// returns the slots the compiled scheduler ran. + fn counts_every_edge( + backend: &str, + mut sim: crate::Simulation, + ) -> u64 { + sim.run_until(END).unwrap(); + for index in 0..CLOCKS { + // A clock with half period `p` rises at p, 3p, 5p, ... + let period = (index % PERIODS + 1) as u64; + let rises = (END / period).div_ceil(2); + let counter = sim.signal(&format!("n{index}")); + assert_eq!( + sim.get(counter), + BigUint::from(rises), + "{backend}: n{index}" + ); + } + sim.scheduler_stats().compiled_slots + } + + /// A design with more events than one word of a mask holds runs in + /// the compiled scheduler, and every domain sees each of its edges. + #[test] + fn more_than_64_events_run_in_the_compiled_scheduler() { + let source = more_than_64_events(); + let mut sim = builder(&source).build().unwrap(); + let scheduler = sim + .simulator + .program + .runtime_schema + .scheduler + .as_ref() + .unwrap(); + assert!(scheduler.unit.is_some(), "{:?}", scheduler.fallback); + assert!(scheduler.events.len() > 64); + assert!(scheduler.fallback.iter().all(Option::is_none)); + sim.run_until(1).unwrap(); + assert!(sim.scheduler_stats().compiled_slots > 0); + counts_every_edge("native", sim); + // Every step of the compiled scheduler agrees with the reference + // loop. + let mut checked = builder(&source) + .scheduler_mode(crate::SchedulerMode::Differential) + .build() + .unwrap(); + checked.run_until(END).unwrap(); + assert!(checked.scheduler_stats().checked_steps > 0); + } + + /// 70 instances on one clock: the frontend's estimate counts the clock + /// once per instance and widens the scheduler's slots, while the design + /// has few events. A `$finish` ends a compiled slot early. + #[test] + fn wide_slots_with_few_events_finish_on_every_backend() { + let mut source = String::from( + "`timescale 1ns/1ns\nmodule Counter(input logic clk, output logic [7:0] n);\n \ + initial n = 0;\n always_ff @(posedge clk) n <= n + 8'd1;\nendmodule\n\ + module Top;\n logic clk = 0;\n always #1 clk = ~clk;\n initial #20 $finish;\n", + ); + for index in 0..CLOCKS { + source += + &format!(" logic [7:0] n{index};\n Counter u{index}(.clk(clk), .n(n{index}));\n"); + } + source += "endmodule\n"; + fn finishes(backend: &str, mut sim: crate::Simulation) { + sim.run_until(100).unwrap(); + assert!(sim.is_finished(), "{backend}"); + for index in 0..CLOCKS { + let counter = sim.signal(&format!("n{index}")); + assert_eq!(sim.get(counter), BigUint::from(10u8), "{backend}: n{index}"); + } + } + let wide = builder(&source).build().unwrap(); + let scheduler = wide + .simulator + .program + .runtime_schema + .scheduler + .as_ref() + .unwrap(); + assert!(scheduler.events.len() <= 64); + assert!(wide.simulator.layout().widths[&scheduler.slots.levels] > 64); + finishes("native", wide); + finishes("interpreter", builder(&source).build_interpreter().unwrap()); + finishes("tiered", builder(&source).build_tiered().unwrap()); + #[cfg(feature = "cranelift")] + finishes("cranelift", builder(&source).build_cranelift().unwrap()); + #[cfg(feature = "wasm-runtime")] + finishes("wasm", builder(&source).build_wasm().unwrap()); + } + + /// The runtime reads the wide scheduler slots on every backend. + #[test] + fn more_than_64_events_run_on_every_backend() { + let source = more_than_64_events(); + counts_every_edge("interpreter", builder(&source).build_interpreter().unwrap()); + counts_every_edge("tiered", builder(&source).build_tiered().unwrap()); + // Cranelift's wide comparisons once ran every domain (#2102). + #[cfg(feature = "cranelift")] + assert!(counts_every_edge("cranelift", builder(&source).build_cranelift().unwrap()) > 0); + #[cfg(feature = "wasm-runtime")] + counts_every_edge("wasm", builder(&source).build_wasm().unwrap()); + } +} diff --git a/crates/celox/src/scheduler/testbench.rs b/crates/celox/src/scheduler/testbench.rs index 09373bddd6f..9e6371f73ad 100644 --- a/crates/celox/src/scheduler/testbench.rs +++ b/crates/celox/src/scheduler/testbench.rs @@ -544,6 +544,13 @@ fn generate( .layout() .four_state .then_some(&program.layout().is_4states), + // The unit judges no event masks; they keep the slot's width. + event_bits: program + .layout() + .widths + .get(&slots.levels) + .copied() + .unwrap_or(SCHEDULER_TIME_WIDTH), }; let initialize = g.b.new_block(); let start = g.b.new_block();