diff --git a/CLAUDE.md b/CLAUDE.md index 65c5bff5124..4b006d7bd54 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -100,6 +100,7 @@ GCC-style optimization level presets with per-pass overrides. | `PartialForward` | Partial store-load forwarding in combinational blocks | | `IdentityStoreBypass` | Detects identity copies and registers address aliases | | `TailCallSplit` | Splits large functions into tail-call chains (enabled even at O0) | +| `DerivedEdgeUnits` | Runs edges of gated/divided clocks in generated units instead of the Rust plan walk (not a SIR transform; costs build time, `-sir:derived_edge_units` to opt out) | ### Cranelift Backend Optimization diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index db823a8e54f..5e45cf13916 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -876,6 +876,22 @@ pub struct RuntimeSchema { /// scheduler itself once one is generated. Present when the design has /// process kernels. pub scheduler: Option>, + /// Generated units that run an edge of an event with every derived + /// clock domain it reaches, for the events that have them. + pub derived_edges: Vec>, +} + +/// The process units that run the edges of one event together with its +/// derived clock domains, the signal having already moved. Each reads +/// [`SchedulerSlots::dirty`] to know whether combinational logic must +/// settle before the domains evaluate. +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub struct DerivedEdgeUnits { + /// The canonical event. + pub event: A, + /// Indices among the process units of the rising and the falling edge. + pub rising: usize, + pub falling: usize, } /// Width of [`SchedulerSlots::limit`], [`SchedulerSlots::now`], @@ -1084,6 +1100,7 @@ impl Default for RuntimeSchema { active_commits: Vec::new(), time_slots: Vec::new(), scheduler: None, + derived_edges: Vec::new(), } } } diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index bfb7ab5f61a..7682ec5627d 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2201,6 +2201,7 @@ pub fn schedule_symbolic_rtl_reporting_loops( active_commits, time_slots, scheduler, + derived_edges: Vec::new(), }, }; diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index 511a3310d32..19ffd8e1567 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -151,6 +151,13 @@ pub trait SimBackend { true } + /// Whether the code now running has the generated derived-edge units + /// (`RuntimeSchema::derived_edges`); otherwise a host walks the + /// derived-tick plans. + fn runs_derived_edge_units(&self) -> bool { + true + } + // ── event enumeration ─────────────────────────────────────── fn id_to_addr_slice(&self) -> &[AbsoluteAddr]; fn id_to_event_slice(&self) -> &[Self::Event]; diff --git a/crates/celox-sir-opt/src/policy.rs b/crates/celox-sir-opt/src/policy.rs index fbb387bf896..90c1664ed84 100644 --- a/crates/celox-sir-opt/src/policy.rs +++ b/crates/celox-sir-opt/src/policy.rs @@ -116,6 +116,12 @@ define_sir_passes! { /// Compatibility selector for Cranelift oversized-function planning. /// This is not a SIR transform and is consumed at the backend boundary. TailCallSplit => "tail_call_split", + /// Run the edges of events with derived clock domains (gated clocks, + /// dividers) in generated units instead of walking their plans in Rust. + /// Not a SIR transform: the builder consumes it. The units compile the + /// clock's domain once more, so disabling it trades tick speed for build + /// time. + DerivedEdgeUnits => "derived_edge_units", } /// Diagnostics and additional verification for the SIR optimizer. /// @@ -278,11 +284,12 @@ impl OptimizeOptions { self.opt_level.default_enabled(pass) } - /// Returns true if any pass other than TailCallSplit is enabled. + /// Returns true if any SIR transform is enabled: any pass other than + /// the TailCallSplit and DerivedEdgeUnits selectors. pub fn any_enabled(&self) -> bool { - SirPass::ALL - .iter() - .any(|&p| p != SirPass::TailCallSplit && self.is_enabled(p)) + SirPass::ALL.iter().any(|&p| { + !matches!(p, SirPass::TailCallSplit | SirPass::DerivedEdgeUnits) && self.is_enabled(p) + }) } /// The base optimization level. diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index cb7cff24b0f..28811acbea5 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -410,6 +410,7 @@ pub(crate) struct NativeRuntimeSchema { pub(crate) active_commits: Vec, pub(crate) time_slots: Vec, pub(crate) scheduler: Option>, + pub(crate) derived_edges: Vec>, } /// Pointer-free native compiler artifact which can be attached to the @@ -526,6 +527,7 @@ impl NativeProgramImage { active_commits: self.runtime_schema.active_commits.clone(), time_slots: self.runtime_schema.time_slots.clone(), scheduler: self.runtime_schema.scheduler.clone(), + derived_edges: self.runtime_schema.derived_edges.clone(), }, testbench: self.testbench.clone(), } @@ -621,12 +623,19 @@ impl NativeProgramImage { usize::MAX } }); - if self.process_offsets.len() - != self - .runtime_schema - .processes - .len() - .saturating_add(scheduler_units) + // The derived-edge units follow the kernels and the scheduler. + let derived_units = 2 * self.runtime_schema.derived_edges.len(); + let derived_in_range = self.runtime_schema.derived_edges.iter().all(|units| { + units.rising < self.process_offsets.len() && units.falling < self.process_offsets.len() + }); + if !derived_in_range + || self.process_offsets.len() + != self + .runtime_schema + .processes + .len() + .saturating_add(scheduler_units) + .saturating_add(derived_units) { return Err("process kernels and their control slots disagree".into()); } @@ -2443,6 +2452,7 @@ fn compile_program( active_commits: sir.runtime().runtime_schema.active_commits.clone(), time_slots: sir.runtime().runtime_schema.time_slots.clone(), scheduler: sir.runtime().runtime_schema.scheduler.clone(), + derived_edges: sir.runtime().runtime_schema.derived_edges.clone(), }, layout: layout.clone(), native_memory_size, diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index f587c107ec1..0c95b249cc8 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 33; +const CONTAINER_VERSION: u16 = 34; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/backend/tiered.rs b/crates/celox/src/backend/tiered.rs index 38c5e94aefc..bff1dcf143e 100644 --- a/crates/celox/src/backend/tiered.rs +++ b/crates/celox/src/backend/tiered.rs @@ -540,6 +540,10 @@ pub struct TieredBackend { /// first stage adopts a low-latency baseline image, this receiver yields /// the optimizing image for an in-place shared-code replacement. upgrade_receiver: Option>>, + /// The adopted code has the generated derived-edge units: a single-stage + /// image or the optimizing one. The baseline image leaves them out, so + /// their build cost lands in the optimizing tier. + derived_edges_live: bool, /// Evaluate-only events whose apply phase has not run yet. Promotion is /// deferred while this is non-zero so the compiled apply phase always /// observes the interpreted evaluate-only results through an intact @@ -799,6 +803,7 @@ impl TieredBackend { cancel, compiler_worker, upgrade_receiver: None, + derived_edges_live: false, pending_split_applies: 0, promotion_threshold, interpreted_steps: 0, @@ -859,6 +864,8 @@ impl TieredBackend { let (baseline_sender, baseline_receiver) = mpsc::channel(); let (upgrade_sender, upgrade_receiver) = mpsc::channel(); let background_laid_out = laid_out.clone(); + // The baseline image runs derived edges by walking their plans. + let baseline_laid_out = crate::derived_edge::without_units(laid_out); let worker_baseline_options = baseline_options.clone(); // A failed spawn keeps the interpreter as the permanent tier with the // reason recorded, matching the single-stage background-failure policy. @@ -868,11 +875,7 @@ impl TieredBackend { let span = tracing::info_span!("celox.tiered.compile", target = "native"); span.in_scope(|| { let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - compile( - &background_laid_out, - &worker_baseline_options, - &worker_cancel, - ) + compile(&baseline_laid_out, &worker_baseline_options, &worker_cancel) })) .unwrap_or_else(|_| { Err(SimulatorError::from(crate::RuntimeErrorCode::InternalError)) @@ -929,6 +932,7 @@ impl TieredBackend { cancel, compiler_worker, upgrade_receiver: Some(upgrade_receiver), + derived_edges_live: false, pending_split_applies: 0, promotion_threshold, interpreted_steps: 0, @@ -1141,6 +1145,8 @@ impl TieredBackend { } } self.phase = Phase::Compiled(compiled); + // A second stage still to come means this is the baseline image. + self.derived_edges_live = self.upgrade_receiver.is_none(); self.promotion = Promotion::Promoted; self.promoted_after_interpreted_steps = Some(self.interpreted_steps); if let Some(timing) = &mut self.execution_timing @@ -1205,6 +1211,7 @@ impl TieredBackend { && compiled.replace_native_code(code) { tracing::info!("tiered backend adopted optimizing native code"); + self.derived_edges_live = true; } } } @@ -1225,6 +1232,10 @@ impl SimBackend for TieredBackend { matches!(self.phase, Phase::Compiled(_)) } + fn runs_derived_edge_units(&self) -> bool { + matches!(self.phase, Phase::Compiled(_)) && self.derived_edges_live + } + type Event = TieredEventRef; fn eval_comb(&mut self) -> Result<(), SimulatorErrorCode> { diff --git a/crates/celox/src/derived_edge.rs b/crates/celox/src/derived_edge.rs index 2debba1c98c..32c2c0ae4f9 100644 --- a/crates/celox/src/derived_edge.rs +++ b/crates/celox/src/derived_edge.rs @@ -14,7 +14,10 @@ //! without settling for gates: two-state designs whose gated clocks all have //! gate programs. -use celox_design::{DomainKind, GateOp, STABLE_REGION, schedule::ScheduleModel}; +use celox_design::{ + DomainKind, GateOp, SCHEDULER_FLAG_WIDTH, STABLE_REGION, edges::active_level, + schedule::ScheduleModel, +}; use celox_sir::{BinaryOp, BlockId, SIRBuilder, SIRTerminator, SIRValue, UnaryOp}; use crate::ir::{ @@ -114,6 +117,28 @@ impl EdgePlan { if layout.four_state { return Err("the design is four-state"); } + // A host checks these after each unit it runs; a generated edge runs + // its units without returning in between. + if !program.runtime.runtime_schema.comb_observers.is_empty() { + return Err("the design observes combinational processes"); + } + let comb_fatal = program.sir.eval_comb.iter().any(|unit| { + unit.blocks + .values() + .flat_map(|block| &block.instructions) + .any(|inst| { + matches!( + inst, + SIRInstruction::CombCaptureEvent { + fatal_error_code: Some(_), + .. + } + ) + }) + }); + 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"); } @@ -183,6 +208,20 @@ impl EdgePlan { 1 + self.domains.len() + index } + /// Whether entry `entry` can fire together with another: the event's own + /// domain with gated clocks that are not independent, the derived ones + /// in a round with another derived one or at the edge with the event's + /// own. + fn fires_with_others(&self, entry: usize) -> bool { + let derived = self.domains.len() + self.gated.len(); + let gated_together = !self.gated.is_empty() && !self.independent; + if entry == 0 { + gated_together + } else { + derived > 1 || (entry > self.domains.len() && gated_together) + } + } + /// Emit one edge of the event's signal, which has already moved from /// level `from` to `to` (one-bit registers). `fires` says whether the /// event's own domain sees its active edge, `settle` whether @@ -270,23 +309,47 @@ impl EdgePlan { let gated_ready = e.binary(MAX_ENTRIES, 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); - let one_at_a_time = e.b.new_block(); + // 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 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 next_turn = e.b.new_block_with(vec![rest]); let together = e.b.new_block(); e.b.seal_block(SIRTerminator::Branch { cond: in_turn, - true_block: (one_at_a_time, Vec::new()), + true_block: (next_turn, vec![mask]), false_block: (together, Vec::new()), }); - // Independent gated domains, then the event's own, each fused. - e.b.switch_to_block(one_at_a_time); + // Independent gated domains, then the event's own, each fused, one + // at a time (`fire_with_gated`). + e.b.switch_to_block(next_turn); let order: Vec = (0..self.gated.len()) .map(|index| self.gated_bit(index)) .chain(std::iter::once(0)) .collect(); for entry in order { - let units = self.entries().nth(entry).expect("an entry of the mask"); - e.if_bit(mask, entry, |e| e.inline_all(&units.eval_apply)); + let bit = e.constant(1 << entry, MAX_ENTRIES); + let selected = e.binary(MAX_ENTRIES, 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(); + e.b.seal_block(SIRTerminator::Branch { + cond: set, + true_block: (take, Vec::new()), + 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 yes = e.constant(1, 1); + e.b.seal_block(SIRTerminator::Jump(one_domain, vec![bit, left, yes])); + e.b.switch_to_block(skip); } e.b.seal_block(SIRTerminator::Jump(fire_end, Vec::new())); @@ -297,27 +360,37 @@ impl EdgePlan { let lower = e.binary(MAX_ENTRIES, mask, BinaryOp::Sub, one); let others = e.binary(MAX_ENTRIES, mask, BinaryOp::And, lower); let single = e.binary(1, others, BinaryOp::Eq, zero); - let one_domain = e.b.new_block(); let several = e.b.new_block(); + let no = e.constant(0, 1); + let none_left = e.constant(0, MAX_ENTRIES); e.b.seal_block(SIRTerminator::Branch { cond: single, - true_block: (one_domain, Vec::new()), + true_block: (one_domain, vec![mask, none_left, no]), false_block: (several, Vec::new()), }); e.b.switch_to_block(one_domain); for (entry, units) in self.entries().enumerate() { - e.if_bit(mask, entry, |e| e.inline_all(&units.eval_apply)); + e.if_bit(one_mask, entry, |e| e.inline_all(&units.eval_apply)); } - e.b.seal_block(SIRTerminator::Jump(fire_end, Vec::new())); + e.b.seal_block(SIRTerminator::Branch { + cond: turn, + true_block: (next_turn, vec![remaining]), + false_block: (fire_end, Vec::new()), + }); e.b.switch_to_block(several); + let joint: Vec = (0..self.domains.len() + self.gated.len() + 1) + .map(|entry| self.fires_with_others(entry)) + .collect(); for (entry, units) in self.entries().enumerate() { - e.if_bit(mask, entry, |e| match &units.eval_only { - Some(eval_only) => e.inline_all(eval_only), - None => e.inline_all(&units.eval_apply), - }); + if joint[entry] { + e.if_bit(mask, entry, |e| match &units.eval_only { + Some(eval_only) => e.inline_all(eval_only), + None => e.inline_all(&units.eval_apply), + }); + } } for (entry, units) in self.entries().enumerate() { - if let Some(apply) = &units.apply { + if let (true, Some(apply)) = (joint[entry], &units.apply) { e.if_bit(mask, entry, |e| e.inline_all(apply)); } } @@ -640,26 +713,63 @@ impl Emitter<'_> { } } +/// Where a generated edge unit learns whether combinational logic must +/// settle before the domains evaluate. +#[derive(Clone, Copy, Debug)] +enum Settle { + #[cfg_attr(not(all(test, feature = "systemverilog")), allow(dead_code))] + Fixed(bool), + /// A flag object, not zero when it must. + Flag(AbsoluteAddr), +} + impl EdgePlan { /// A unit that runs one edge of the event whose signal its caller - /// already moved, rising or falling, with `settle` and `fires` fixed. - #[cfg(all(test, feature = "systemverilog"))] - fn unit(&self, comb: &[Unit], rising: bool, settle: bool, fires: bool) -> Unit { + /// already moved, rising or falling; `fires` says whether the event's own + /// domain sees its active edge. + fn unit(&self, comb: &[Unit], rising: bool, fires: bool, settle: Settle) -> Unit { let mut b = Builder::new(); - let constant = |b: &mut Builder, value: bool| { - let register = b.alloc_bit(1, false); - b.emit(SIRInstruction::Imm( - register, - SIRValue::new(u64::from(value)), - )); + let constant = |b: &mut Builder, value: u64, width: usize| { + let register = b.alloc_bit(width, false); + b.emit(SIRInstruction::Imm(register, SIRValue::new(value))); register }; - let from = constant(&mut b, !rising); - let to = constant(&mut b, rising); - let fires = constant(&mut b, fires); - let settle = constant(&mut b, settle); + let from = constant(&mut b, u64::from(!rising), 1); + let to = constant(&mut b, u64::from(rising), 1); + let source_fires = fires; + let fires = constant(&mut b, u64::from(fires), 1); + let settle = match settle { + Settle::Fixed(value) => constant(&mut b, u64::from(value), 1), + Settle::Flag(flag) => { + let value = b.alloc_bit(SCHEDULER_FLAG_WIDTH, false); + b.emit(SIRInstruction::Load( + value, + RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, flag), + SIROffset::Static(0), + SCHEDULER_FLAG_WIDTH, + )); + let zero = constant(&mut b, 0, SCHEDULER_FLAG_WIDTH); + let set = b.alloc_bit(1, false); + b.emit(SIRInstruction::Binary(set, value, BinaryOp::Ne, zero)); + set + } + }; let done = b.new_block(); - self.emit(&mut b, comb, from, to, fires, settle, done, done); + // An edge that never fires the event's own domain leaves its units + // out of the unit. + let plan = if source_fires { + std::borrow::Cow::Borrowed(self) + } else { + std::borrow::Cow::Owned(EdgePlan { + source: DomainUnits { + eval_apply: Vec::new(), + eval_only: None, + apply: None, + }, + ..self.clone() + }) + }; + plan.emit(&mut b, comb, from, to, fires, settle, done, done); b.switch_to_block(done); b.seal_block(SIRTerminator::Return); let (blocks, register_map, _) = b.drain(); @@ -671,6 +781,75 @@ impl EdgePlan { } } +/// Generate the edge units of every event whose plan this module emits and +/// record them in [`celox_design::RuntimeSchema::derived_edges`]. A unit +/// reads the scheduler's dirty flag to know whether to settle first. +pub(crate) fn attach(program: &mut LaidOutProgram) { + let schema = &program.runtime.runtime_schema; + let Some(flag) = schema + .scheduler + .as_ref() + .map(|scheduler| scheduler.slots.dirty) + else { + return; + }; + let model = ScheduleModel::derive(&program.design, schema); + let mut edges = Vec::new(); + for event in crate::edge_plans::event_addresses(program) { + let Ok(Some(plan)) = EdgePlan::new(program, &model, event) else { + continue; + }; + // An edge of a clock or reset fires its domain when it is the active + // one; any other moved two-state signal always does. + let kind = model.kind(&event); + let fires = |rising: bool| match kind { + Some( + DomainKind::ClockPosedge + | DomainKind::ClockNegedge + | DomainKind::ResetAsyncHigh + | DomainKind::ResetAsyncLow, + ) => rising == (active_level(kind) == 1), + _ => true, + }; + let mut indices = [0usize; 2]; + for (index, rising) in [true, false].into_iter().enumerate() { + let unit = plan.unit( + &program.sir.eval_comb, + rising, + fires(rising), + Settle::Flag(flag), + ); + indices[index] = program.sir.processes.len(); + program.sir.processes.push(unit); + } + edges.push(celox_design::DerivedEdgeUnits { + event, + rising: indices[0], + falling: indices[1], + }); + } + program.runtime.runtime_schema.derived_edges = edges; +} + +/// `program` without its derived-edge units, for a tier whose host walks +/// the derived-tick plans instead. The units follow every other process +/// unit, so the others keep their indices. +pub(crate) fn without_units(program: &LaidOutProgram) -> LaidOutProgram { + let mut program = program.clone(); + let first = program + .runtime + .runtime_schema + .derived_edges + .iter() + .map(|units| units.rising.min(units.falling)) + .min(); + if let Some(first) = first { + program.sir.processes.truncate(first); + program.runtime.runtime_schema.derived_edges.clear(); + } + program +} + /// A generated edge unit and the edge it runs, for the tests. #[cfg(all(test, feature = "systemverilog"))] #[derive(Clone, Copy, Debug)] @@ -697,7 +876,8 @@ pub(crate) fn attach_test_units(program: &mut LaidOutProgram, sink: &TestEdgeUni for rising in [false, true] { for settle in [false, true] { for fires in [false, true] { - let unit = plan.unit(&program.sir.eval_comb, rising, settle, fires); + let unit = + plan.unit(&program.sir.eval_comb, rising, fires, Settle::Fixed(settle)); let index = program.sir.processes.len(); program.sir.processes.push(unit); sink.lock().expect("unpoisoned").push(TestEdgeUnit { @@ -727,6 +907,66 @@ mod tests { backend::{EventHandle, SimBackend}, }; + const GATED: &str = "module Top(input logic clk, input logic en, output logic [7:0] q); + logic gclk; + logic [7:0] r = 0; + logic [7:0] g = 0; + logic [7:0] w; + assign gclk = clk & en; + // A value the host's writes of `en` change through logic. + assign w = en ? 8'd3 : 8'd1; + always_ff @(posedge clk) r <= r + w; + always_ff @(posedge gclk) g <= g + r; + assign q = g; + endmodule"; + + const INVERTED: &str = "module Top(input logic clk, input logic en, output logic [7:0] q); + logic nclk; + logic gclk; + logic [7:0] r = 0; + logic [7:0] n = 0; + logic [7:0] g = 0; + assign nclk = ~clk; + assign gclk = clk & en; + always_ff @(posedge clk) r <= r + 8'd1; + always_ff @(posedge nclk) n <= n + r; + always_ff @(negedge gclk) g <= g ^ n; + assign q = n + g; + endmodule"; + + const DIVIDERS: &str = "module Top(input logic clk, output logic [7:0] q); + logic half = 0; + logic quarter = 0; + logic [7:0] h = 0; + logic [7:0] w = 0; + always_ff @(posedge clk) half <= ~half; + always_ff @(posedge half) quarter <= ~quarter; + always_ff @(posedge half) h <= h + 8'd1; + always_ff @(posedge quarter) w <= w + h; + assign q = h + w; + endmodule"; + + const RAISED_ENABLE: &str = "module Top(input logic clk, output logic [7:0] q); + logic en = 0; + logic gclk; + logic [7:0] g = 0; + assign gclk = clk & en; + always_ff @(posedge clk) en <= ~en; + always_ff @(posedge gclk) g <= g + 8'd1; + assign q = g; + endmodule"; + + const INDEPENDENT: &str = + "module Top(input logic clk, input logic en, input logic [7:0] d, output logic [7:0] q); + logic gclk; + logic [7:0] r = 0; + logic [7:0] g = 0; + assign gclk = clk & en; + always_ff @(posedge clk) r <= r + d; + always_ff @(posedge gclk) g <= g + 8'd3; + assign q = r ^ g; + endmodule"; + /// The design state: the stable region after its header. fn state(backend: &B) -> Vec { let (ptr, len) = backend.memory_as_ptr(); @@ -851,84 +1091,80 @@ mod tests { } } + /// Drive `source` through the `Simulator` API, with derived domains run + /// by the generated edge units and by the plan walk, and compare every + /// named signal after each operation: ticks of `clk`, single and + /// 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(); + assert!( + !generated.program.runtime_schema.derived_edges.is_empty(), + "no edge unit was generated" + ); + assert!(walked.program.runtime_schema.derived_edges.is_empty()); + let clk = generated.event("clk"); + let en = generated.try_signal("en").ok(); + let names: Vec<_> = walked.named_signals(); + for step in 0..80usize { + for sim in [&mut generated, &mut walked] { + if let Some(en) = en + && step % 7 < 2 + { + sim.modify(|io| io.set(en, u8::from(step % 3 != 0))) + .unwrap(); + } + match step % 5 { + 0 | 1 => sim.tick(clk).unwrap(), + 2 => sim.edge(clk, Edge::Rising).unwrap(), + 3 => sim.edge(clk, Edge::Rising).unwrap(), + _ => sim.edge(clk, Edge::Falling).unwrap(), + } + } + for named in &names { + assert_eq!( + generated.get(named.signal), + walked.get(named.signal), + "step {step}: {}", + named.name + ); + } + } + } + + #[test] + fn simulator_ticks_run_generated_edges_as_the_plan_walk() { + for source in [GATED, INVERTED, DIVIDERS, RAISED_ENABLE, INDEPENDENT] { + ticks_agree(source); + } + } + #[test] fn gated_clocks_run_as_the_plan_walk() { - agrees( - "module Top(input logic clk, input logic en, output logic [7:0] q); - logic gclk; - logic [7:0] r = 0; - logic [7:0] g = 0; - assign gclk = clk & en; - always_ff @(posedge clk) r <= r + 8'd1; - always_ff @(posedge gclk) g <= g + r; - assign q = g; - endmodule", - ); + agrees(GATED); } #[test] fn inverted_and_falling_gated_clocks_run_as_the_plan_walk() { - agrees( - "module Top(input logic clk, input logic en, output logic [7:0] q); - logic nclk; - logic gclk; - logic [7:0] r = 0; - logic [7:0] n = 0; - logic [7:0] g = 0; - assign nclk = ~clk; - assign gclk = clk & en; - always_ff @(posedge clk) r <= r + 8'd1; - always_ff @(posedge nclk) n <= n + r; - always_ff @(negedge gclk) g <= g ^ n; - assign q = n + g; - endmodule", - ); + agrees(INVERTED); } #[test] fn dividers_run_as_the_plan_walk() { - agrees( - "module Top(input logic clk, output logic [7:0] q); - logic half = 0; - logic quarter = 0; - logic [7:0] h = 0; - logic [7:0] w = 0; - always_ff @(posedge clk) half <= ~half; - always_ff @(posedge half) quarter <= ~quarter; - always_ff @(posedge half) h <= h + 8'd1; - always_ff @(posedge quarter) w <= w + h; - assign q = h + w; - endmodule", - ); + agrees(DIVIDERS); } #[test] fn enables_the_commit_raises_run_as_the_plan_walk() { - agrees( - "module Top(input logic clk, output logic [7:0] q); - logic en = 0; - logic gclk; - logic [7:0] g = 0; - assign gclk = clk & en; - always_ff @(posedge clk) en <= ~en; - always_ff @(posedge gclk) g <= g + 8'd1; - assign q = g; - endmodule", - ); + agrees(RAISED_ENABLE); } #[test] fn independent_gated_domains_run_as_the_plan_walk() { - agrees( - "module Top(input logic clk, input logic en, input logic [7:0] d, output logic [7:0] q); - logic gclk; - logic [7:0] r = 0; - logic [7:0] g = 0; - assign gclk = clk & en; - always_ff @(posedge clk) r <= r + d; - always_ff @(posedge gclk) g <= g + 8'd3; - assign q = r ^ g; - endmodule", - ); + agrees(INDEPENDENT); } } diff --git a/crates/celox/src/lib.rs b/crates/celox/src/lib.rs index ae4fb81ffe3..28c216b193e 100644 --- a/crates/celox/src/lib.rs +++ b/crates/celox/src/lib.rs @@ -19,9 +19,7 @@ pub use component::{ register_static_component_manifest, }; mod debug; -// Only its tests run the generator until a host does. #[cfg(feature = "host-runtime")] -#[cfg_attr(not(all(test, feature = "systemverilog")), allow(dead_code))] mod derived_edge; mod edge_plans; pub use edge_plans::{ diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index 2ce6b6afe92..ffccc1394d2 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -163,6 +163,12 @@ mod host { derived_ticks: celox_runtime::DerivedTickPlans, /// Boxed, so that taking it out for a tick moves one pointer. derived_scratch: Option>, + /// Per event ID, the generated units that run an edge of the event + /// with its derived domains. Empty without them. + derived_units: Arc<[Option]>, + /// The flag a derived-edge unit reads to settle combinational logic + /// before the domains evaluate. + derived_settle: Option, /// The design finished a timed simulation (`$finish`). Evaluation, /// host writes and waveform dumps no longer change anything. pub(crate) frozen: bool, @@ -850,6 +856,8 @@ mod host { celox_runtime::build_derived_tick_plans(&backend, &schedule); let event_edges = celox_runtime::build_event_edges(&backend, &schedule.events, &schedule.kinds); + let (derived_units, derived_settle) = + derived_edge_units(&backend, &program.runtime_schema, &derived_ticks); let comb_observer_reads = crate::comb_activation::ObserverReads::new( &backend, &program.runtime_schema.comb_observers, @@ -884,6 +892,8 @@ mod host { tick_timing_eval_comb_ns: 0, derived_ticks, derived_scratch: Some(Box::new(derived_scratch)), + derived_units, + derived_settle, frozen: false, host_watch: Default::default(), finish_scan_seq: 0, @@ -1848,6 +1858,12 @@ mod host { } return Ok(()); } + if let Some(Some(unit)) = self.derived_units.get(event.id()).copied() + && !self.finish_sites + && self.backend.runs_derived_edge_units() + { + return self.edge_unit(info, edge, unit); + } let plans = std::sync::Arc::clone(&self.derived_ticks); let plan = plans.get(event.id()).and_then(Option::as_ref); let mut scratch = self.derived_scratch.take().unwrap_or_default(); @@ -1861,6 +1877,53 @@ mod host { self.note_edge(result) } + /// [`Self::edge`] of an event with a generated derived-edge unit: + /// move the signal, then run the unit of the edge, which judges the + /// gated clocks, runs the domains and the cascade rounds, as the plan + /// walk does. + #[inline(never)] + fn edge_unit( + &mut self, + info: celox_runtime::EventEdge, + edge: celox_runtime::Edge, + unit: DerivedEdgeUnit, + ) -> Result<(), RuntimeErrorCode> { + let mut watch = std::mem::take(&mut self.host_watch); + let moved = celox_runtime::move_signal( + &mut self.backend, + &info, + edge, + watched_write(&mut watch), + ); + self.host_watch = watch; + let Some(old) = moved else { + return Ok(()); + }; + let fires = info.fires(old, edge); + if let Some(flag) = self.derived_settle { + self.backend + .set(flag, u8::from(self.dirty || info.comb_read)); + } + let index = match edge { + celox_runtime::Edge::Rising => unit.rising, + celox_runtime::Edge::Falling => unit.falling, + }; + if let Err(error) = self.backend.run_process(index) { + self.dirty = true; + return Err(self.decorate_runtime_error(error)); + } + // Without a gated clock and the event's own edge nothing ran, as + // in the plan walk. + let outcome = if unit.gated || fires { + celox_runtime::EdgeOutcome::Settled + } else if info.comb_read { + celox_runtime::EdgeOutcome::Moved + } else { + celox_runtime::EdgeOutcome::Stored + }; + self.note_edge(Ok(outcome)) + } + fn note_edge( &mut self, outcome: Result, @@ -2830,6 +2893,46 @@ mod host { } } + /// The generated units of one event's edges with its derived domains. + #[derive(Clone, Copy, Debug)] + struct DerivedEdgeUnit { + rising: usize, + falling: usize, + /// The event gates derived clocks, so an edge always runs domains. + gated: bool, + } + + /// Per event ID, the generated derived-edge units of `schema`, and the flag + /// they read to settle first. + fn derived_edge_units( + backend: &B, + schema: &celox_design::RuntimeSchema, + plans: &celox_runtime::DerivedTickPlans, + ) -> (Arc<[Option]>, Option) { + if schema.derived_edges.is_empty() { + return (Arc::from([]), None); + } + let mut units = vec![None; backend.num_events()]; + for edges in &schema.derived_edges { + let Some(event) = backend.resolve_event_opt(&edges.event) else { + continue; + }; + let Some(Some(plan)) = plans.get(event.id()) else { + continue; + }; + units[event.id()] = Some(DerivedEdgeUnit { + rising: edges.rising, + falling: edges.falling, + gated: plan.lever_signals().next().is_some(), + }); + } + let flag = schema + .scheduler + .as_ref() + .map(|scheduler| backend.resolve_signal(&scheduler.slots.dirty)); + (units.into(), flag) + } + /// The host's write of an event signal's level, observed by a timed /// simulation's waits and counters as [`IOContext`] writes are. fn watched_write( diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 68400436bc8..7f8b600c462 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -2848,6 +2848,14 @@ mod host { { crate::scheduler::attach(&mut laid_out); } + #[cfg(feature = "host-runtime")] + if self + .options + .optimize_options + .is_enabled(crate::optimizer::SirPass::DerivedEdgeUnits) + { + crate::derived_edge::attach(&mut laid_out); + } #[cfg(all(test, feature = "host-runtime", feature = "systemverilog"))] if let Some(sink) = &self.options.derived_edge_units { crate::derived_edge::attach_test_units(&mut laid_out, sink); diff --git a/crates/celox/tests/tick_semantics.rs b/crates/celox/tests/tick_semantics.rs index 78ebf514fac..e25afb59e0f 100644 --- a/crates/celox/tests/tick_semantics.rs +++ b/crates/celox/tests/tick_semantics.rs @@ -31,10 +31,22 @@ module Dut ( output logic [7:0] r, output logic [7:0] c2, output logic [7:0] s, + output logic [7:0] d, + output logic [7:0] e, output logic lvl ); logic gclk; + logic half = 1'b0; + logic ren = 1'b0; + logic rclk; assign gclk = clk & en; + // A clock divided from `clk`, and a gate whose enable `clk`'s own domain + // toggles. + always_ff @(posedge clk) half <= ~half; + always_ff @(posedge half) d <= d + 8'd1; + always_ff @(posedge clk) ren <= ~ren; + assign rclk = clk & ren; + always_ff @(posedge rclk) e <= e + 8'd1; always_ff @(posedge clk) p <= p + 8'd1; always_ff @(negedge clk) n <= n + 8'd1; always_ff @(posedge gclk) g <= g + 8'd1; @@ -48,7 +60,7 @@ module Dut ( endmodule "#; -const OUTPUTS: [&str; 8] = ["p", "n", "g", "ng", "r", "c2", "s", "lvl"]; +const OUTPUTS: [&str; 10] = ["p", "n", "g", "ng", "r", "c2", "s", "d", "e", "lvl"]; /// Event signals with their active levels. const EVENTS: [(&str, u8); 3] = [("clk", 1), ("clk2", 1), ("rst_n", 0)]; @@ -93,10 +105,10 @@ fn reference(ops: &[Op]) -> Vec> { `timescale 1ns/1ns module Top; logic clk, clk2, en, rst_n; - wire [7:0] p, n, g, ng, r, c2, s; + wire [7:0] p, n, g, ng, r, c2, s, d, e; wire lvl; Dut u ( - .clk, .clk2, .en, .rst_n, .p, .n, .g, .ng, .r, .c2, .s, .lvl + .clk, .clk2, .en, .rst_n, .p, .n, .g, .ng, .r, .c2, .s, .d, .e, .lvl ); initial begin {body} end @@ -124,11 +136,18 @@ endmodule .collect() } -fn hosted(ops: &[Op]) -> Vec> { - let mut sim = Simulator::from_sv_sources(vec![(DUT, Path::new("dut.sv"))], "Dut") - .four_state(false) - .build() - .unwrap(); +/// The values of `OUTPUTS` after each operation through the `Simulator` +/// API, with derived clock domains run by their generated edge units, or by +/// walking their plans when `walk`. +fn hosted(ops: &[Op], walk: bool) -> Vec> { + let builder = + Simulator::from_sv_sources(vec![(DUT, Path::new("dut.sv"))], "Dut").four_state(false); + let builder = if walk { + builder.disable_pass(celox::SirPass::DerivedEdgeUnits) + } else { + builder + }; + let mut sim = builder.build().unwrap(); ops.iter() .map(|&op| { match op { @@ -166,14 +185,26 @@ fn hosted(ops: &[Op]) -> Vec> { } fn check(ops: &[Op]) { + check_except(ops, &[]); +} + +/// [`check`] of every output but `skipped`. +fn check_except(ops: &[Op], skipped: &[&str]) { + let kept: Vec = (0..OUTPUTS.len()) + .filter(|&index| !skipped.contains(&OUTPUTS[index])) + .collect(); + let select = |values: &Vec| kept.iter().map(|&index| values[index]).collect::>(); let expected = reference(ops); - let actual = hosted(ops); - for (k, (expected, actual)) in expected.iter().zip(&actual).enumerate() { - assert_eq!( - actual, expected, - "after {:?} (operation {k}), outputs {OUTPUTS:?}", - ops[k] - ); + for walk in [false, true] { + let actual = hosted(ops, walk); + for (k, (expected, actual)) in expected.iter().zip(&actual).enumerate() { + assert_eq!( + select(actual), + select(expected), + "after {:?} (operation {k}, walk {walk}), outputs {OUTPUTS:?} without {skipped:?}", + ops[k] + ); + } } } @@ -207,14 +238,38 @@ fn a_tick_from_the_active_level_takes_only_the_inactive_edge() { ]); } -/// Coincident ticks sample each other's values from before the edge. +const COINCIDENT: [Op; 5] = [ + Op::Edge("rst_n", 1), + Op::Tick(&["clk2"]), + Op::Tick(&["clk", "clk2"]), + Op::Tick(&["clk", "clk2"]), + Op::Tick(&["clk"]), +]; + +/// Coincident ticks sample each other's values from before the edge. The +/// commit-raised gate's domain (`e`) is checked against Icarus below until +/// the timed reference sees its edge in a coincident batch (#1860). #[test] fn ticks_of_several_events_are_coincident() { - check(&[ - Op::Edge("rst_n", 1), - Op::Tick(&["clk2"]), - Op::Tick(&["clk", "clk2"]), - Op::Tick(&["clk", "clk2"]), - Op::Tick(&["clk"]), - ]); + check_except(&COINCIDENT, &["e"]); +} + +/// At the second coincident tick `clk` rises while `ren` is already high, so +/// `rclk` rises in the active region and `e` counts: Icarus 13.0 gives +/// `e` = 0 0 1 2 3 after the operations. The timed reference gives 0 0 1 1 2 +/// (#1860); both `Simulator` paths agree with Icarus. +#[test] +#[ignore = "#1860"] +fn coincident_ticks_run_the_domain_of_a_gate_the_commit_raised() { + let e = OUTPUTS.iter().position(|name| *name == "e").unwrap(); + let values = |rows: Vec>| rows.iter().map(|row| row[e]).collect::>(); + let icarus = vec![0, 0, 1, 2, 3]; + assert_eq!( + values(reference(&COINCIDENT)), + icarus, + "the timed reference" + ); + for walk in [false, true] { + assert_eq!(values(hosted(&COINCIDENT, walk)), icarus, "walk {walk}"); + } } diff --git a/crates/celox/tests/tiered.rs b/crates/celox/tests/tiered.rs index 894bec229a6..8873c86fe5d 100644 --- a/crates/celox/tests/tiered.rs +++ b/crates/celox/tests/tiered.rs @@ -394,3 +394,96 @@ endmodule assert!(sim.promotion_error().is_none()); assert_eq!(sim.get_four_state(neq), expected); } + +const DERIVED: &str = r#" +module Top ( + clk: input clock, + rst: input reset, + en: input logic, + cnt: output logic<8>, + extra: output logic<8>, + more: output logic<8>, +) { + var c: logic<8>; + var e: logic<8>; + var m: logic<8>; + var half: logic; + let gated: '_ clock = clk & en; + let divided: '_ clock = half; + always_ff (clk, rst) { + if_reset { + c = 0; + half = 0; + } else { + c += 1; + half = ~half; + } + } + always_ff (gated) { + e += c; + } + always_ff (divided) { + m += 1; + } + assign cnt = c; + assign extra = e; + assign more = m; +} +"#; + +/// Derived clock edges walk their plans until the tier with the generated +/// derived-edge units runs (the optimizing image of a two-stage build), then +/// run the units, matching the plan walk throughout. +#[test] +fn tiered_derived_edges_switch_to_generated_units() { + use celox::SimBackend as _; + let mut tiered: Simulator = SimulatorBuilder::new(DERIVED, "Top") + .build_tiered() + .unwrap(); + let mut walked = Simulator::builder(DERIVED, "Top") + .disable_pass(celox::SirPass::DerivedEdgeUnits) + .build() + .unwrap(); + let outputs = ["cnt", "extra", "more"]; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120); + let mut live_ticks = 0u32; + let mut step = 0u32; + while live_ticks < 32 { + assert!( + std::time::Instant::now() < deadline, + "the generated derived-edge units never became live" + ); + let (rst, en) = (u8::from(step > 1), u8::from(!step.is_multiple_of(5))); + let reset = tiered.signal("rst"); + let enable = tiered.signal("en"); + tiered + .modify(|io| { + io.set(reset, rst); + io.set(enable, en); + }) + .unwrap(); + let reset = walked.signal("rst"); + let enable = walked.signal("en"); + walked + .modify(|io| { + io.set(reset, rst); + io.set(enable, en); + }) + .unwrap(); + let clk = tiered.event("clk"); + tiered.tick(clk).unwrap(); + let clk = walked.event("clk"); + walked.tick(clk).unwrap(); + for name in outputs { + let left = tiered.get_as::(tiered.signal(name)); + let right = walked.get_as::(walked.signal(name)); + assert_eq!(left, right, "step {step}: {name}"); + } + if tiered.backend_ref().runs_derived_edge_units() { + live_ticks += 1; + } else { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + step += 1; + } +} diff --git a/docs/internals/optimizations.md b/docs/internals/optimizations.md index 2359f540469..7ecea17951a 100644 --- a/docs/internals/optimizations.md +++ b/docs/internals/optimizations.md @@ -95,6 +95,12 @@ unnecessary: - an event that does not match the required edge does not evaluate its domain; - a non-cascaded single domain may use a combined evaluate-and-commit kernel; - cascaded evaluation continues only while newly triggered domains exist. +- an edge of an event with derived clock domains (gated clocks, dividers) runs + as generated units, which judge the gated clocks, run the domains and the + cascade rounds, instead of a walk of the derived-tick plan in Rust. These units + compile the clock's domain once more; the `derived_edge_units` selector + (`-sir:derived_edge_units`, `SirPass::DerivedEdgeUnits`) turns them off to + trade tick speed for build time. These choices preserve the ordering model defined in [Runtime Semantics](./cascade-limitations.md). They do not change signal values or diff --git a/packages/celox/src/types.ts b/packages/celox/src/types.ts index e151864feb8..7dfee70b78f 100644 --- a/packages/celox/src/types.ts +++ b/packages/celox/src/types.ts @@ -346,7 +346,10 @@ export interface SimulatorOptions { * bit_extract_peephole, optimize_blocks, split_wide_commits, commit_sinking, * inline_commit_forwarding, eliminate_dead_working_stores, reschedule, * coalesce_stores, gvn, concat_folding, xor_chain_folding, vectorize_concat, - * split_coalesced_stores, partial_forward, identity_store_bypass, tail_call_split + * split_coalesced_stores, partial_forward, identity_store_bypass, tail_call_split, + * derived_edge_units (generated units for the edges of gated and divided + * clocks; "-sir:derived_edge_units" walks their plans instead, which + * builds faster and ticks slower) * * @example ["-sir:reschedule", "+sir:gvn"] */