diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs
index ad65391ccce..1de57c16f22 100644
--- a/crates/celox-design/src/lib.rs
+++ b/crates/celox-design/src/lib.rs
@@ -230,6 +230,13 @@ pub enum ProcessStatus {
/// It ran no statement, so no state other than its own wait bookkeeping
/// changed.
Pending,
+ /// Resume after the number of rising edges stored in
+ /// [`ProcessSlots::delay`] of the process clock whose index is stored in
+ /// [`ProcessSlots::clock`]. The runtime generates those edges: the clock
+ /// toggles every half period from the first wait on it, and the process
+ /// resumes one period after the last counted edge, before the edge that
+ /// follows.
+ WaitClock,
/// An event occurred while sampling queued drives; resume its body after the batch.
Ready,
/// Resume this process immediately, charging the current time-slot budget.
@@ -247,6 +254,7 @@ impl ProcessStatus {
Self::Finish => 3,
Self::Wait => 4,
Self::Pending => 5,
+ Self::WaitClock => 6,
Self::Ready => 11,
Self::Yield => 10,
}
@@ -260,6 +268,7 @@ impl ProcessStatus {
3 => Some(Self::Finish),
4 => Some(Self::Wait),
5 => Some(Self::Pending),
+ 6 => Some(Self::WaitClock),
11 => Some(Self::Ready),
10 => Some(Self::Yield),
_ => None,
@@ -267,18 +276,42 @@ impl ProcessStatus {
}
}
+/// A clock a process waits on with [`ProcessStatus::WaitClock`]: the clock
+/// signal of a sequential domain, and the period of the edges the runtime
+/// generates for it (at least two time units).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+pub struct ProcessClock {
+ pub signal: A,
+ pub period: u64,
+}
+
+impl ProcessClock {
+ pub fn map(self, map: impl FnOnce(A) -> B) -> ProcessClock {
+ ProcessClock {
+ signal: map(self.signal),
+ period: self.period,
+ }
+ }
+}
+
/// State through which one process kernel exchanges control with the runtime.
///
/// A process kernel is a resumable function. On entry it reads `resume` to
/// find where it stopped; before returning it stores the next resume point,
-/// a [`ProcessStatus`] code in `status` and, for a delay, the number of time
-/// units in `delay`. All three are ordinary two-state state objects, so
-/// checkpoints capture a suspended process.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
+/// a [`ProcessStatus`] code in `status` and, for a delay or a clock wait, the
+/// number of time units or edges in `delay`; a clock wait also stores the
+/// index into `clocks` in `clock`. The slots are ordinary two-state state
+/// objects, so checkpoints capture a suspended process.
+#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ProcessSlots {
pub resume: A,
pub status: A,
pub delay: A,
+ pub clock: A,
+ /// The clocks the process may wait on, in the order its kernel numbers
+ /// them.
+ #[serde(default = "Vec::new")]
+ pub clocks: Vec>,
}
impl ProcessSlots {
@@ -287,11 +320,18 @@ impl ProcessSlots {
resume: map(self.resume),
status: map(self.status),
delay: map(self.delay),
+ clock: map(self.clock),
+ clocks: self
+ .clocks
+ .into_iter()
+ .map(|clock| clock.map(&mut map))
+ .collect(),
}
}
+ /// The control slots, without the clock signals.
pub fn iter(&self) -> impl Iterator- {
- [&self.resume, &self.status, &self.delay].into_iter()
+ [&self.resume, &self.status, &self.delay, &self.clock].into_iter()
}
}
@@ -299,6 +339,8 @@ impl ProcessSlots {
pub const PROCESS_STATUS_WIDTH: usize = 8;
/// Width of [`ProcessSlots::delay`].
pub const PROCESS_DELAY_WIDTH: usize = 64;
+/// Width of [`ProcessSlots::clock`].
+pub const PROCESS_CLOCK_WIDTH: usize = 32;
pub const PROCESS_EVENT_COUNTER_WIDTH: usize = 32;
@@ -348,6 +390,8 @@ pub struct RuntimeSchema {
/// derived from the other state, so state files recompute rather than
/// compare them.
pub comb_writes: HashSet,
+ /// Combinational execution reads a clock, so both phases must settle.
+ pub clock_phase_sensitive_comb: bool,
/// Dead store elimination policy the program was compiled with. Together
/// with `live_signals` and the design it decides which combinationally
/// written state the host may observe.
@@ -357,7 +401,7 @@ pub struct RuntimeSchema {
/// Control slots of the process kernels, in kernel order.
pub processes: Vec>,
pub process_event_counters: Vec>,
- /// FF evaluation domains that publish blocking stores into active state.
+ /// FF domains with blocking stores or finish effects in the active region.
pub active_ff_events: HashSet,
}
@@ -371,6 +415,7 @@ impl Default for RuntimeSchema {
testbench_read_roots: HashSet::default(),
rtl_writes: HashSet::default(),
comb_writes: HashSet::default(),
+ clock_phase_sensitive_comb: false,
dead_store_policy: DeadStorePolicy::Off,
live_signals: HashSet::default(),
processes: Vec::new(),
diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs
index fa6aa699207..5f10bab6c9f 100644
--- a/crates/celox-frontend-core/src/process.rs
+++ b/crates/celox-frontend-core/src/process.rs
@@ -16,8 +16,8 @@
//! suspension methods where the source suspends.
use celox_design::{
- PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, ProcessStatus, RegionedVarAddrBase,
- STABLE_REGION,
+ PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, ProcessStatus,
+ RegionedVarAddrBase, STABLE_REGION,
};
use celox_sir::{
BinaryOp, BlockId, ExecutionUnit, RegisterId, SIRBuilder, SIRInstruction, SIROffset,
@@ -43,6 +43,8 @@ pub const MAX_PROCESS_SUSPENSIONS: usize = (1 << PROCESS_RESUME_WIDTH) - 1;
pub enum ProcessKernelError {
#[error("a process has more than {MAX_PROCESS_SUSPENSIONS} suspension points")]
TooManySuspensions,
+ #[error("a process waits on clock {0}, which its slots do not list")]
+ UnknownClock(u32),
}
/// Builder of one process kernel.
@@ -140,6 +142,29 @@ impl ProcessKernelBuilder {
Ok(())
}
+ /// Suspend until `count` rising edges of the process clock `clock` (an
+ /// index into the slots' clock list) have passed, and continue at a new
+ /// resume point one period after the last of them. `count` is an
+ /// unsigned two-state register of [`PROCESS_DELAY_WIDTH`] bits; a count
+ /// of zero continues at once.
+ pub fn wait_clock(&mut self, clock: u32, count: RegisterId) -> Result<(), ProcessKernelError> {
+ if clock as usize >= self.slots.clocks.len() {
+ return Err(ProcessKernelError::UnknownClock(clock));
+ }
+ let point = self.resume_blocks.len();
+ if point > MAX_PROCESS_SUSPENSIONS {
+ return Err(ProcessKernelError::TooManySuspensions);
+ }
+ self.store(self.slots.delay, PROCESS_DELAY_WIDTH, count);
+ self.store_constant(self.slots.clock, PROCESS_CLOCK_WIDTH, u64::from(clock));
+ self.store_constant(self.slots.resume, PROCESS_RESUME_WIDTH, point as u64);
+ self.end(ProcessStatus::WaitClock);
+ let resume = self.builder.new_block();
+ self.resume_blocks.push(resume);
+ self.builder.switch_to_block(resume);
+ Ok(())
+ }
+
/// Suspend until a condition the kernel evaluates holds, and continue at
/// a new resume point. The caller lowers the condition at that point
/// and ends it with [`Self::wake_if`]; the runtime resumes the process
diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs
index b6c5231d2e3..187743ff56a 100644
--- a/crates/celox-frontend-core/src/sdk.rs
+++ b/crates/celox-frontend-core/src/sdk.rs
@@ -2,8 +2,9 @@
use celox_design::{
BinaryOp, BitAccess, DomainKind, InitialStateData, InitialStateValue, ModuleId,
- PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, RegionedVarAddrBase,
- STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, VariableMetadata, WORKING_REGION,
+ PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessClock,
+ ProcessSlots, RegionedVarAddrBase, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase,
+ VariableMetadata, WORKING_REGION,
};
use celox_frontend_sdk::{
ActiveLevel, Direction, Edge, ExprId, ExprNode, FrontendArtifact, SignalId, SignalSlice,
@@ -1034,6 +1035,7 @@ fn lower_registers(
fn lower_statements(
artifact: &FrontendArtifact,
kernel: &mut ProcessKernelBuilder,
+ clocks: &[SignalId],
statements: &[Statement],
) -> Result {
for statement in statements {
@@ -1075,7 +1077,7 @@ fn lower_statements(
let mut join = None;
for (block, body) in [(then_block, then_body), (else_block, else_body)] {
kernel.builder().switch_to_block(block);
- if lower_statements(artifact, kernel, body)? {
+ if lower_statements(artifact, kernel, clocks, body)? {
let builder = kernel.builder();
let target = *join.get_or_insert_with(|| builder.new_block());
builder.seal_block(SIRTerminator::Jump(target, Vec::new()));
@@ -1100,7 +1102,7 @@ fn lower_statements(
false_block: (exit, Vec::new()),
});
builder.switch_to_block(body_block);
- if lower_statements(artifact, kernel, body)? {
+ if lower_statements(artifact, kernel, clocks, body)? {
kernel
.builder()
.seal_block(SIRTerminator::Jump(header, Vec::new()));
@@ -1112,7 +1114,7 @@ fn lower_statements(
let header = builder.new_block();
builder.seal_block(SIRTerminator::Jump(header, Vec::new()));
builder.switch_to_block(header);
- if lower_statements(artifact, kernel, body)? {
+ if lower_statements(artifact, kernel, clocks, body)? {
kernel
.builder()
.seal_block(SIRTerminator::Jump(header, Vec::new()));
@@ -1129,6 +1131,20 @@ fn lower_statements(
)?;
kernel.delay(amount)?;
}
+ Statement::ClockCycles { clock, count } => {
+ let index = clocks
+ .iter()
+ .position(|c| c == clock)
+ .ok_or(FrontendArtifactError::UnknownSignal(clock.index()))?;
+ let count = coerce_sir_expression(
+ artifact,
+ *count,
+ ValueType::bits(PROCESS_DELAY_WIDTH)?,
+ kernel.builder(),
+ &mut cache,
+ )?;
+ kernel.wait_clock(index as u32, count)?;
+ }
Statement::Finish => {
kernel.finish();
return Ok(false);
@@ -1176,13 +1192,28 @@ fn lower_processes(
.enumerate()
.map(|(index, process)| {
let name = |slot: &str| vec![format!("$process[{index}]"), slot.to_string()];
+ let mut clocks = Vec::new();
+ celox_frontend_sdk::collect_process_clocks(process.body(), &mut clocks);
let slots = ProcessSlots {
resume: declare(name("resume"), PROCESS_RESUME_WIDTH),
status: declare(name("status"), PROCESS_STATUS_WIDTH),
delay: declare(name("delay"), PROCESS_DELAY_WIDTH),
+ clock: declare(name("clock"), PROCESS_CLOCK_WIDTH),
+ clocks: clocks
+ .iter()
+ .map(|clock| {
+ Ok(ProcessClock {
+ signal: source_id(*clock),
+ period: artifact
+ .clock_period(*clock)
+ .ok_or(FrontendArtifactError::UnknownSignal(clock.index()))?
+ .max(2),
+ })
+ })
+ .collect::, FrontendArtifactError>>()?,
};
- let mut kernel = ProcessKernelBuilder::new(slots);
- lower_statements(artifact, &mut kernel, process.body())?;
+ let mut kernel = ProcessKernelBuilder::new(slots.clone());
+ lower_statements(artifact, &mut kernel, &clocks, process.body())?;
Ok(SymbolicProcess {
kernel: kernel.build(),
slots,
diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs
index f9e88f448e8..56ca734f8bd 100644
--- a/crates/celox-frontend-core/src/symbolic/assembly.rs
+++ b/crates/celox-frontend-core/src/symbolic/assembly.rs
@@ -1440,6 +1440,7 @@ pub fn schedule_symbolic_rtl(
testbench_read_roots: process_read_roots,
rtl_writes,
comb_writes: Default::default(),
+ clock_phase_sensitive_comb: false,
dead_store_policy: Default::default(),
live_signals: Default::default(),
processes: process_slots,
@@ -2273,7 +2274,10 @@ fn relocate_units(
&runtime_event_site_map,
&extern_function_map,
),
- slots: process.slots.map(|var_id| bindings.locate(*id, var_id)),
+ slots: process
+ .slots
+ .clone()
+ .map(|var_id| bindings.locate(*id, var_id)),
},
));
}
diff --git a/crates/celox-frontend-sdk/src/lib.rs b/crates/celox-frontend-sdk/src/lib.rs
index 8b83123dc8d..7788bf5a355 100644
--- a/crates/celox-frontend-sdk/src/lib.rs
+++ b/crates/celox-frontend-sdk/src/lib.rs
@@ -13,9 +13,9 @@ use thiserror::Error;
/// Current JSON interchange version of [`FrontendArtifact`].
///
-/// Version 2 adds [`Process`]es. An artifact without processes is still
-/// written as version 1, so older consumers keep accepting it.
-pub const ARTIFACT_FORMAT_VERSION: u32 = 2;
+/// Version 2 adds [`Process`]es; version 3 adds [`Statement::ClockCycles`].
+/// Artifacts use the oldest version that can represent their statements.
+pub const ARTIFACT_FORMAT_VERSION: u32 = 3;
/// Oldest JSON interchange version [`FrontendArtifact::from_json`] accepts.
pub const MIN_ARTIFACT_FORMAT_VERSION: u32 = 1;
@@ -474,6 +474,13 @@ pub enum Statement {
/// amount count as zero; a zero delay resumes at the same time, after
/// the other processes and the registers their edges trigger.
Delay { amount: ExprId },
+ /// Suspend the process until `count` rising edges of `clock` have
+ /// passed. The runtime generates the edges of a clock from the first
+ /// wait on it, with the period set by [`ModuleBuilder::clock_period`],
+ /// and resumes the process one period after the last counted edge,
+ /// before the edge that follows. Unknown bits of the count count as
+ /// zero; a zero count continues at once.
+ ClockCycles { clock: SignalId, count: ExprId },
/// End the simulation.
Finish,
}
@@ -509,6 +516,9 @@ pub struct FrontendArtifact {
port_order: Vec,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
processes: Vec,
+ /// Periods of the clocks processes wait on, in time units.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ clock_periods: Vec<(SignalId, u64)>,
}
impl FrontendArtifact {
@@ -523,10 +533,25 @@ impl FrontendArtifact {
/// Decode and version-check an artifact produced by an external frontend.
pub fn from_json(json: &str) -> Result {
+ #[derive(Deserialize)]
+ struct Header {
+ format_version: u32,
+ }
+ let header: Header = serde_json::from_str(json)?;
+ if !(MIN_ARTIFACT_FORMAT_VERSION..=ARTIFACT_FORMAT_VERSION).contains(&header.format_version)
+ {
+ return Err(ArtifactJsonError::UnsupportedVersion {
+ expected: ARTIFACT_FORMAT_VERSION,
+ actual: header.format_version,
+ });
+ }
let artifact: Self = serde_json::from_str(json)?;
- if !(MIN_ARTIFACT_FORMAT_VERSION..=ARTIFACT_FORMAT_VERSION)
- .contains(&artifact.format_version)
- || (artifact.format_version < 2 && !artifact.processes.is_empty())
+ let mut clocks = Vec::new();
+ for process in &artifact.processes {
+ collect_process_clocks(&process.body, &mut clocks);
+ }
+ if (artifact.format_version < 2 && !artifact.processes.is_empty())
+ || (artifact.format_version < 3 && !clocks.is_empty())
{
return Err(ArtifactJsonError::UnsupportedVersion {
expected: ARTIFACT_FORMAT_VERSION,
@@ -850,6 +875,67 @@ impl FrontendArtifact {
for process in &self.processes {
self.validate_statements(&process.body, &driver_ranges)?;
}
+ // The same requirements as `ModuleBuilder::clock_period` and
+ // `ModuleBuilder::process` put on the clocks processes wait on.
+ let mut declared_clocks = std::collections::BTreeSet::new();
+ for (clock, period) in &self.clock_periods {
+ if !declared_clocks.insert(clock.index()) {
+ let name = self
+ .signal(*clock)
+ .ok_or(BuildError::UnknownSignal(clock.index()))?
+ .name
+ .clone();
+ return Err(BuildError::DuplicateClockPeriod { name });
+ }
+ let signal = self
+ .signal(*clock)
+ .ok_or(BuildError::UnknownSignal(clock.index()))?;
+ if signal.value_type.width() != 1 {
+ return Err(BuildError::InvalidControlWidth {
+ name: signal.name.clone(),
+ });
+ }
+ if *period < 2 {
+ return Err(BuildError::InvalidClockPeriod { period: *period });
+ }
+ }
+ for process in &self.processes {
+ let mut clocks = Vec::new();
+ collect_process_clocks(&process.body, &mut clocks);
+ for clock in clocks {
+ let mut targets = Vec::new();
+ for process in &self.processes {
+ collect_process_targets(&process.body, &mut targets);
+ }
+ if driver_ranges.contains_key(&clock)
+ || targets.iter().any(|target| target.signal == clock)
+ {
+ return Err(BuildError::DrivenProcessClock {
+ name: self
+ .signal(clock)
+ .ok_or(BuildError::UnknownSignal(clock.index()))?
+ .name
+ .clone(),
+ });
+ }
+ let known = self
+ .clock_periods
+ .iter()
+ .any(|(signal, _)| *signal == clock)
+ && self
+ .registers
+ .iter()
+ .any(|register| register.clock == clock);
+ if !known {
+ let name = self
+ .signal(clock)
+ .ok_or(BuildError::UnknownSignal(clock.index()))?
+ .name
+ .clone();
+ return Err(BuildError::UnknownProcessClock { name });
+ }
+ }
+ }
let mut ordered_ports = FxHashMap::default();
for signal in &self.port_order {
let signal = self
@@ -906,6 +992,14 @@ impl FrontendArtifact {
&self.processes
}
+ /// The period of `clock` for [`Statement::ClockCycles`], if set.
+ pub fn clock_period(&self, clock: SignalId) -> Option {
+ self.clock_periods
+ .iter()
+ .find(|(signal, _)| *signal == clock)
+ .map(|(_, period)| *period)
+ }
+
fn validate_statements(
&self,
statements: &[Statement],
@@ -955,6 +1049,14 @@ pub enum BuildError {
},
#[error("control signal `{name}` must be one bit wide")]
InvalidControlWidth { name: String },
+ #[error("a clock period must be at least two time units, not {period}")]
+ InvalidClockPeriod { period: u64 },
+ #[error("duplicate process-clock period for `{name}`")]
+ DuplicateClockPeriod { name: String },
+ #[error("clock `{name}` needs a period and a register it clocks before a process waits on it")]
+ UnknownProcessClock { name: String },
+ #[error("process clock `{name}` also has a continuous, register or process driver")]
+ DrivenProcessClock { name: String },
#[error("register target `{name}` must cover the complete signal")]
PartialRegisterTarget { name: String },
#[error("module name must not be empty")]
@@ -1014,6 +1116,7 @@ pub struct ModuleBuilder {
driver_ranges: FxHashMap>,
port_order: Vec,
processes: Vec,
+ clock_periods: Vec<(SignalId, u64)>,
}
impl ModuleBuilder {
@@ -1033,6 +1136,7 @@ impl ModuleBuilder {
driver_ranges: FxHashMap::default(),
port_order: Vec::new(),
processes: Vec::new(),
+ clock_periods: Vec::new(),
})
}
@@ -1366,6 +1470,36 @@ impl ModuleBuilder {
&|expression| self.expressions.get(expression.index() as usize),
&self.driver_ranges,
)?;
+ let mut clocks = Vec::new();
+ collect_process_clocks(&body, &mut clocks);
+ let mut targets = Vec::new();
+ collect_process_targets(&body, &mut targets);
+ for process in &self.processes {
+ collect_process_targets(&process.body, &mut targets);
+ collect_process_clocks(&process.body, &mut clocks);
+ }
+ for clock in clocks {
+ if self.driver_ranges.contains_key(&clock)
+ || targets.iter().any(|target| target.signal == clock)
+ {
+ return Err(BuildError::DrivenProcessClock {
+ name: self.signal_info(clock)?.name.clone(),
+ });
+ }
+ let known = self
+ .clock_periods
+ .iter()
+ .any(|(signal, _)| *signal == clock)
+ && self
+ .registers
+ .iter()
+ .any(|register| register.clock == clock);
+ if !known {
+ return Err(BuildError::UnknownProcessClock {
+ name: self.signal_info(clock)?.name.clone(),
+ });
+ }
+ }
self.processes.push(Process { body });
Ok(())
}
@@ -1375,7 +1509,15 @@ impl ModuleBuilder {
format_version: if self.processes.is_empty() {
MIN_ARTIFACT_FORMAT_VERSION
} else {
- ARTIFACT_FORMAT_VERSION
+ let mut clocks = Vec::new();
+ for process in &self.processes {
+ collect_process_clocks(&process.body, &mut clocks);
+ }
+ if clocks.is_empty() {
+ 2
+ } else {
+ ARTIFACT_FORMAT_VERSION
+ }
},
module_name: self.name,
signals: self.signals,
@@ -1384,9 +1526,31 @@ impl ModuleBuilder {
registers: self.registers,
port_order: self.port_order,
processes: self.processes,
+ clock_periods: self.clock_periods,
}
}
+ /// Set the period, in time units, of the edges the runtime generates
+ /// for `clock` when a process waits on it with
+ /// [`Statement::ClockCycles`]. The clock must clock a register, and
+ /// the period is at least two.
+ pub fn clock_period(&mut self, clock: SignalId, period: u64) -> Result<(), BuildError> {
+ let signal = self.signal_info(clock)?;
+ if signal.value_type.width() != 1 {
+ return Err(BuildError::InvalidControlWidth {
+ name: signal.name.clone(),
+ });
+ }
+ if period < 2 {
+ return Err(BuildError::InvalidClockPeriod { period });
+ }
+ match self.clock_periods.iter_mut().find(|(s, _)| *s == clock) {
+ Some(entry) => entry.1 = period,
+ None => self.clock_periods.push((clock, period)),
+ }
+ Ok(())
+ }
+
fn signal_info(&self, signal: SignalId) -> Result<&Signal, BuildError> {
self.signals
.get(signal.index() as usize)
@@ -1430,6 +1594,13 @@ impl ModuleBuilder {
fn record_driver_target(&mut self, target: SignalSlice) -> Result<(), BuildError> {
let signal_name = self.signal_info(target.signal)?.name.clone();
+ let mut process_clocks = Vec::new();
+ for process in &self.processes {
+ collect_process_clocks(&process.body, &mut process_clocks);
+ }
+ if process_clocks.contains(&target.signal) {
+ return Err(BuildError::DrivenProcessClock { name: signal_name });
+ }
let mut process_targets = Vec::new();
for process in &self.processes {
collect_process_targets(&process.body, &mut process_targets);
@@ -1473,7 +1644,32 @@ fn collect_process_targets(statements: &[Statement], targets: &mut Vec {
collect_process_targets(body, targets);
}
- Statement::Delay { .. } | Statement::Finish => {}
+ Statement::Delay { .. } | Statement::ClockCycles { .. } | Statement::Finish => {}
+ }
+ }
+}
+
+/// The clocks the statements wait on, in order of first use.
+pub fn collect_process_clocks(statements: &[Statement], clocks: &mut Vec) {
+ for statement in statements {
+ match statement {
+ Statement::ClockCycles { clock, .. } => {
+ if !clocks.contains(clock) {
+ clocks.push(*clock);
+ }
+ }
+ Statement::If {
+ then_body,
+ else_body,
+ ..
+ } => {
+ collect_process_clocks(then_body, clocks);
+ collect_process_clocks(else_body, clocks);
+ }
+ Statement::While { body, .. } | Statement::Forever { body } => {
+ collect_process_clocks(body, clocks);
+ }
+ Statement::Assign { .. } | Statement::Delay { .. } | Statement::Finish => {}
}
}
}
@@ -1552,6 +1748,13 @@ fn validate_statements<'a>(
return Err(BuildError::DelayTooWide { width });
}
}
+ Statement::ClockCycles { clock, count } => {
+ signal(*clock).ok_or(BuildError::UnknownSignal(clock.index()))?;
+ let width = expression_type(*count)?.width();
+ if width > MAX_DELAY_WIDTH {
+ return Err(BuildError::DelayTooWide { width });
+ }
+ }
Statement::Finish => {}
}
}
@@ -1899,6 +2102,113 @@ mod tests {
));
}
+ fn module_for_driven_clock() -> Result<(), BuildError> {
+ let bit = ValueType::bits(1)?;
+ let mut module = ModuleBuilder::new("Driven")?;
+ let clk = module.internal("clk", bit)?;
+ let q = module.output("q", bit)?;
+ let one = module.constant(Constant::two_state(1u8, 1)?);
+ let target = module.whole(q)?;
+ module.register(target, one, clk, Edge::Posedge, None, None)?;
+ module.clock_period(clk, 4)?;
+ let target = module.whole(clk)?;
+ module.assign(target, one)?;
+ module.process(vec![Statement::ClockCycles {
+ clock: clk,
+ count: one,
+ }])
+ }
+
+ #[test]
+ fn revalidates_process_clocks_from_json() {
+ let bit = ValueType::bits(1).unwrap();
+ let mut module = ModuleBuilder::new("ProcessClocks").unwrap();
+ let clock = module.internal("clock", bit).unwrap();
+ let count = module.output("count", bit).unwrap();
+ let toggled = module.read(count).unwrap();
+ let toggled = module.unary(UnaryOp::BitNot, toggled, bit).unwrap();
+ let target = module.whole(count).unwrap();
+ module
+ .register(target, toggled, clock, Edge::Posedge, None, None)
+ .unwrap();
+ module.clock_period(clock, 4).unwrap();
+ let one = module.constant(Constant::two_state(1u8, 8).unwrap());
+ module
+ .process(vec![Statement::ClockCycles { clock, count: one }])
+ .unwrap();
+ let artifact = module.finish();
+ assert_eq!(artifact.format_version(), 3);
+ let json = serde_json::to_value(&artifact).unwrap();
+ let mut old_version = json.clone();
+ old_version["format_version"] = 2.into();
+ assert!(matches!(
+ FrontendArtifact::from_json(&old_version.to_string()),
+ Err(ArtifactJsonError::UnsupportedVersion { actual: 2, .. })
+ ));
+ let mut future = json.clone();
+ future["format_version"] = 4.into();
+ future["processes"][0]["body"][0] = serde_json::json!({"FutureStatement": {}});
+ assert!(matches!(
+ FrontendArtifact::from_json(&future.to_string()),
+ Err(ArtifactJsonError::UnsupportedVersion { actual: 4, .. })
+ ));
+ // Validate both builder orderings and the deserialization trust boundary.
+ let driven = module_for_driven_clock();
+ assert!(matches!(driven, Err(BuildError::DrivenProcessClock { .. })));
+ let mut late_driver = json.clone();
+ late_driver["assignments"] = serde_json::json!([{ "target": {"signal": clock, "lsb": 0, "width": 1}, "value": toggled }]);
+ assert!(matches!(
+ FrontendArtifact::from_json(&late_driver.to_string()),
+ Err(ArtifactJsonError::InvalidArtifact(
+ BuildError::DrivenProcessClock { .. }
+ ))
+ ));
+ let mut later = ModuleBuilder::new("LaterDriver").unwrap();
+ let clk = later.internal("clk", bit).unwrap();
+ let q = later.output("q", bit).unwrap();
+ let one = later.constant(Constant::two_state(1u8, 1).unwrap());
+ let target = later.whole(q).unwrap();
+ later
+ .register(target, one, clk, Edge::Posedge, None, None)
+ .unwrap();
+ later.clock_period(clk, 4).unwrap();
+ later
+ .process(vec![Statement::ClockCycles {
+ clock: clk,
+ count: one,
+ }])
+ .unwrap();
+ let target = later.whole(clk).unwrap();
+ assert!(matches!(
+ later.assign(target, one),
+ Err(BuildError::DrivenProcessClock { .. })
+ ));
+
+ // Without its period, the clock clocks nothing.
+ let mut unknown = json.clone();
+ unknown["clock_periods"] = serde_json::json!([]);
+ let error = FrontendArtifact::from_json(&unknown.to_string()).unwrap_err();
+ assert!(
+ matches!(
+ error,
+ ArtifactJsonError::InvalidArtifact(BuildError::UnknownProcessClock { .. })
+ ),
+ "{error:?}"
+ );
+
+ // A period below two cannot have distinct edges.
+ let mut short = json.clone();
+ short["clock_periods"][0][1] = 1.into();
+ let error = FrontendArtifact::from_json(&short.to_string()).unwrap_err();
+ assert!(
+ matches!(
+ error,
+ ArtifactJsonError::InvalidArtifact(BuildError::InvalidClockPeriod { period: 1 })
+ ),
+ "{error:?}"
+ );
+ }
+
#[test]
fn rejects_input_driver_targets_in_builder_and_json() {
let bit = ValueType::bits(1).unwrap();
diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs
index 2070a5892e5..bb5d5179bd4 100644
--- a/crates/celox-frontend-sv/src/lowering.rs
+++ b/crates/celox-frontend-sv/src/lowering.rs
@@ -11,9 +11,10 @@ use std::path::Path;
use celox_design::{
BinaryOp, BitAccess, DisplaySizing, DomainKind, ExternFunction, ExternSignature, ExternType,
- InitialStateData, InitialStateValue, ModuleId, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH,
- PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo, RuntimeEventKind,
- RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, WORKING_REGION,
+ InitialStateData, InitialStateValue, ModuleId, PROCESS_CLOCK_WIDTH, PROCESS_DELAY_WIDTH,
+ PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots, RegionedVarAddrBase, RuntimeErrorInfo,
+ RuntimeEventKind, RuntimeEventSite, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase,
+ WORKING_REGION,
};
use celox_frontend_core::process::PROCESS_RESUME_WIDTH;
use celox_frontend_core::symbolic::artifact::{
@@ -3660,6 +3661,8 @@ fn lower_initial_processes(
resume: declare("resume", PROCESS_RESUME_WIDTH),
status: declare("status", PROCESS_STATUS_WIDTH),
delay: declare("delay", PROCESS_DELAY_WIDTH),
+ clock: declare("clock", PROCESS_CLOCK_WIDTH),
+ clocks: Vec::new(),
}
})
.collect();
@@ -3708,7 +3711,7 @@ fn lower_initial_processes(
Ok(SymbolicProcess {
kernel: ff::Ff::new(&mut pm).lower_initial_kernel(
process.body(),
- slots,
+ slots.clone(),
activation,
)?,
slots,
diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs
index fb82fb3e8b0..67c22bc7753 100644
--- a/crates/celox-runtime/src/backend.rs
+++ b/crates/celox-runtime/src/backend.rs
@@ -53,7 +53,13 @@ pub trait SimBackend {
if count == 0 {
return (0, Ok(()));
}
- (1, self.eval_comb_apply_ff_at(event))
+ if let Err(error) = self.eval_comb() {
+ return (0, Err(error));
+ }
+ {
+ let result = self.eval_apply_ff_at(event);
+ (u64::from(result.is_ok()), result)
+ }
}
/// Evaluate FF domain without applying (for cascaded clocks).
diff --git a/crates/celox-runtime/src/lib.rs b/crates/celox-runtime/src/lib.rs
index 616e4ddd1f2..d34c3ab9d33 100644
--- a/crates/celox-runtime/src/lib.rs
+++ b/crates/celox-runtime/src/lib.rs
@@ -18,7 +18,8 @@ pub use reflection::{
SignalDirection,
};
pub use simulation::{
- EventInfo, ProcessRefs, ScheduleParts, SimulationExecutor, SimulationSnapshot, SimulationState,
+ EventInfo, ProcessClockRef, ProcessClockState, ProcessRefs, ScheduleParts, SimulationExecutor,
+ SimulationSnapshot, SimulationState,
};
pub use state_file::{
ScheduleRecord, ScheduledEvent, StateDifference, StateFile, StateFileError, StateObject,
diff --git a/crates/celox-runtime/src/simulation.rs b/crates/celox-runtime/src/simulation.rs
index 805a5d38a00..089b675d6d6 100644
--- a/crates/celox-runtime/src/simulation.rs
+++ b/crates/celox-runtime/src/simulation.rs
@@ -62,6 +62,33 @@ pub trait SimulationExecutor {
self.backend_mut().run_process(index)
}
+ /// Run up to `count` rising edges of `event` as fused ticks: each one
+ /// evaluates the combinational logic and then the sequential domain,
+ /// without toggling the clock signal. Returns how many completed before
+ /// a runtime event or an error forced a return to the host.
+ fn tick_many(
+ &mut self,
+ event: ::Event,
+ count: u64,
+ ) -> (u64, Result<(), SimulatorErrorCode>) {
+ if count == 0 {
+ return (0, Ok(()));
+ }
+ if let Err(error) = self.eval_comb() {
+ return (0, Err(error));
+ }
+ {
+ let result = self.eval_apply_ff_at(event);
+ (u64::from(result.is_ok()), result)
+ }
+ }
+
+ /// Whether clock waits may be served by fused ticks, which skip the
+ /// clock signal's own edges and the host's per-edge hooks.
+ fn fused_ticks_allowed(&self) -> bool {
+ false
+ }
+
/// Snapshot external-component inputs immediately before an event domain
/// evaluates its sequential logic.
fn stage_external_event(
@@ -86,11 +113,92 @@ pub trait SimulationExecutor {
fn finish_timed_step(&mut self, _timestamp: u64) {}
}
+/// A clock a process may wait on, resolved to the backend.
+#[derive(Debug)]
+pub struct ProcessClockRef {
+ pub event: B::Event,
+ pub signal: SignalRef,
+ pub period: u64,
+}
+
+impl Clone for ProcessClockRef {
+ fn clone(&self) -> Self {
+ Self {
+ event: self.event,
+ signal: self.signal,
+ period: self.period,
+ }
+ }
+}
+
/// Control slots of one process kernel, resolved to signals of the backend.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct ProcessRefs {
+#[derive(Debug)]
+pub struct ProcessRefs {
pub status: SignalRef,
pub delay: SignalRef,
+ pub clock: SignalRef,
+ pub clocks: Vec>,
+}
+
+impl Clone for ProcessRefs {
+ fn clone(&self) -> Self {
+ Self {
+ status: self.status,
+ delay: self.delay,
+ clock: self.clock,
+ clocks: self.clocks.clone(),
+ }
+ }
+}
+
+/// A process clock some process has waited on: the runtime generates its
+/// edges from then on. A rising edge is due at `next_edge` while a process
+/// waits; the falling edge of the last rising edge that was applied to the
+/// signal is pending at `falling_edge`.
+#[derive(Debug)]
+struct TickClock {
+ event: B::Event,
+ signal: SignalRef,
+ period: u64,
+ next_edge: u64,
+ falling_edge: Option,
+ /// Last level actually driven by this generator, independent of the
+ /// edge-detection baseline retained until publication succeeds.
+ driven_value: Option,
+}
+
+impl Clone for TickClock {
+ fn clone(&self) -> Self {
+ Self {
+ event: self.event,
+ signal: self.signal,
+ period: self.period,
+ next_edge: self.next_edge,
+ falling_edge: self.falling_edge,
+ driven_value: self.driven_value,
+ }
+ }
+}
+
+/// A process waiting for `remaining` more rising edges of the process clock
+/// with event id `clock`.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+struct ClockWait {
+ clock: usize,
+ remaining: u64,
+}
+
+/// The state of one process clock, for schedules expressed by name.
+#[derive(Debug)]
+pub struct ProcessClockState {
+ pub event: B::Event,
+ pub signal: SignalRef,
+ pub period: u64,
+ pub next_edge: u64,
+ pub falling_edge: Option,
+ /// Last generator drive; `None` before its first drive. Retain this
+ /// across failed rounds independently of the sampled event baseline.
+ pub driven_value: Option,
}
/// A process waiting for simulation time to reach `time`. Ordered so that a
@@ -151,6 +259,12 @@ impl PeriodicEventKey {
/// Backend-independent state and execution rules for timed simulation.
pub struct SimulationState {
scheduler: Scheduler,
+ round_published_domains: BitSet,
+ round_triggered_domains: BitSet,
+ scheduled_clock_drives: BitSet,
+ scheduled_clock_time: u64,
+ round_triggers_discovered: bool,
+ round_new_rising: BitSet,
periodic_events: FxHashMap,
last_clock_values: BitSet,
pending_host_edges: BTreeMap,
@@ -160,13 +274,21 @@ pub struct SimulationState {
event_info: Vec>,
signal_to_id: FxHashMap,
signal_index_by_id: Vec,
- processes: Vec,
+ processes: Vec>,
process_event_counters: Vec<(usize, SignalRef, SignalRef)>,
active_ff_domains: BitSet,
process_wakeups: BinaryHeap,
/// Processes suspended at an event or level wait, which their kernels
/// re-check whenever the state may have changed.
waiting: BTreeSet,
+ /// Process clocks that have been waited on, by event id.
+ tick_clocks: BTreeMap>,
+ /// Processes waiting for rising edges of a process clock.
+ clock_waits: BTreeMap,
+ /// Processes that ran to their end.
+ done: BTreeSet,
+ /// Rising edges of process clocks so far.
+ ticks: u64,
sampled_ready: BTreeSet,
inactive: BTreeSet,
/// A process requested the end of the simulation.
@@ -196,11 +318,22 @@ fn sample_event_signal(backend: &B, signal: SignalRef) -> (bool,
}
}
+/// The error of a process clock whose next edge lies beyond simulation time.
+fn clock_overflow(clock: usize) -> SimulatorErrorCode {
+ SimulatorErrorCode::Runtime {
+ message: format!("process clock {clock} overflows simulation time"),
+ signals: Vec::new(),
+ }
+}
+
impl SimulationState {
/// Rebase edge detection after state was advanced outside this scheduler.
pub fn synchronize_event_values(&mut self, backend: &B) {
self.pending_host_edges.clear();
self.sample_event_values(backend);
+ for clock in self.tick_clocks.values_mut() {
+ clock.driven_value = None;
+ }
}
fn sample_event_values(&mut self, backend: &B) {
@@ -220,13 +353,29 @@ impl SimulationState {
}
}
+ fn pending_generated_baseline(&self, id: usize) -> Option<(bool, bool)> {
+ let driven = self.tick_clocks.get(&id)?.driven_value?;
+ let baseline = (
+ self.last_clock_values.contains(id),
+ self.unknown_clock_values.contains(id),
+ );
+ (baseline != (driven, false)).then_some(baseline)
+ }
+
/// Retain FF occurrences observed by a host evaluation until the scheduler runs.
pub fn capture_host_edges(&mut self, backend: &B) {
if self.finished {
return;
}
+ // A failed generated round owns its unpublished source edge. Host
+ // settling must neither dispatch it nor consume its retry baseline.
+ let generated_baselines: Vec<_> = self
+ .tick_clocks
+ .keys()
+ .filter_map(|&id| self.pending_generated_baseline(id).map(|value| (id, value)))
+ .collect();
for (_, id, _) in &self.topo_signals {
- if *id == usize::MAX {
+ if *id == usize::MAX || self.pending_generated_baseline(*id).is_some() {
continue;
}
let info = &self.event_info[*id];
@@ -239,6 +388,18 @@ impl SimulationState {
}
}
self.sample_event_values(backend);
+ for (id, (value, unknown)) in generated_baselines {
+ if value {
+ self.last_clock_values.insert(id);
+ } else {
+ self.last_clock_values.remove(id);
+ }
+ if unknown {
+ self.unknown_clock_values.insert(id);
+ } else {
+ self.unknown_clock_values.remove(id);
+ }
+ }
}
fn stable_edge_triggered(&self, backend: &B, id: usize) -> bool {
@@ -290,7 +451,7 @@ impl SimulationState {
topo_signals: Vec<(SignalRef, usize, usize)>,
domain_kinds: Vec