Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion crates/celox-design/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1354,7 +1354,8 @@ pub struct SchedulerSlots<A> {
/// Where a shared combinational settle continues.
pub cont: A,
/// Set when state combinational logic reads may have changed since its
/// last settle.
/// last settle. The caller initializes this before every scheduler run;
/// timed runs set it even after a checkpoint restore or partial-slot exit.
pub dirty: A,
/// The number of time slots the run ran.
pub count: A,
Expand Down
2 changes: 2 additions & 0 deletions crates/celox-runtime/src/schedule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ pub(crate) struct SchedulerRefs {
pub(crate) exit: SignalRef,
pub(crate) exit_arg: SignalRef,
pub(crate) finish: SignalRef,
pub(crate) dirty: SignalRef,
pub(crate) count: SignalRef,
pub(crate) current: SignalRef,
pub(crate) levels: SignalRef,
Expand Down Expand Up @@ -426,6 +427,7 @@ impl<B: SimBackend> ResolvedSchedule<B> {
exit: resolve(&slots.exit),
exit_arg: resolve(&slots.exit_arg),
finish: resolve(&slots.finish),
dirty: resolve(&slots.dirty),
count: resolve(&slots.count),
current: resolve(&slots.current),
levels: resolve(&slots.levels),
Expand Down
3 changes: 3 additions & 0 deletions crates/celox-runtime/src/simulation/compiled.rs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,9 @@ impl<B: SimBackend> SimulationState<B> {
backend.set(scheduler.limit, limit);
backend.set(scheduler.exit, 0u8);
backend.set(scheduler.finish, 0u8);
// State may have been restored or a prior slot may have exited early.
// Only hosts that prove their input state settled may enter clean.
backend.set(scheduler.dirty, 1u8);
backend.set(scheduler.count, 0u64);
for &(_, waiting) in scheduler.wake.iter().flatten() {
backend.set(waiting, 0u8);
Expand Down
8 changes: 8 additions & 0 deletions crates/celox-runtime/src/simulation/edges.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,14 @@ impl<B: SimBackend> SimulationState<B> {
self.record_all_levels(backend);
}

/// Restore samples saved by a generated scheduler before it ran a slot.
/// This preserves pending asynchronous edges when execution returns to the queue.
pub fn restore_event_baselines(&mut self, levels: impl IntoIterator<Item = (usize, u8)>) {
for (event, level) in levels {
self.record_level(event, level);
}
}

/// Whether an event signal changed outside the queue since its last sample.
/// Callers must settle pending combinational writes before treating `false`
/// as permission to bypass the queue's transition detection.
Expand Down
5 changes: 5 additions & 0 deletions crates/celox-runtime/src/testbench.rs
Original file line number Diff line number Diff line change
Expand Up @@ -476,6 +476,10 @@ pub fn bind_testbench_program<B: SimBackend>(
.into_iter()
.map(|component| bind_component(backend, component, rtl_writes))
.collect::<Option<Vec<_>>>()?;
let scheduler = program
.scheduler()
.cloned()
.map(|s| s.map(|a| backend.resolve_signal(&a)));
let statements = program
.into_statements()
.into_iter()
Expand All @@ -489,6 +493,7 @@ pub fn bind_testbench_program<B: SimBackend>(
Some(
ExecutableTestbench::from_processes(processes, random_seed)
.with_kernels(kernels)
.with_scheduler(scheduler)
.with_clocks(clocks)
.with_private_signals(private_signals)
.with_component_runtime(
Expand Down
21 changes: 21 additions & 0 deletions crates/celox-testbench/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
//! execution. No Veryl AST, parser ID, simulator backend, or runtime handle is
//! part of the bytecode representation.

mod scheduler;
pub use scheduler::*;

use num_bigint::BigUint;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
Expand Down Expand Up @@ -305,6 +308,7 @@ pub struct TestbenchKernel<A> {
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TestbenchProgram<A> {
kernels: Vec<TestbenchKernel<A>>,
scheduler: Option<TestbenchScheduler<A>>,
statements: Vec<SemanticStatement<A>>,
process_lengths: Vec<usize>,
clocks: Vec<TestbenchClock<A>>,
Expand All @@ -320,6 +324,7 @@ impl<A> Default for TestbenchProgram<A> {
fn default() -> Self {
Self {
kernels: Vec::new(),
scheduler: None,
statements: Vec::new(),
process_lengths: Vec::new(),
clocks: Vec::new(),
Expand All @@ -334,6 +339,12 @@ impl<A> Default for TestbenchProgram<A> {
}

impl<A> TestbenchProgram<A> {
pub fn scheduler(&self) -> Option<&TestbenchScheduler<A>> {
self.scheduler.as_ref()
}
pub fn set_scheduler(&mut self, scheduler: TestbenchScheduler<A>) {
self.scheduler = Some(scheduler);
}
pub fn kernels(&self) -> &[TestbenchKernel<A>] {
&self.kernels
}
Expand All @@ -344,6 +355,7 @@ impl<A> TestbenchProgram<A> {
pub fn new(statements: Vec<SemanticStatement<A>>) -> Self {
Self {
kernels: Vec::new(),
scheduler: None,
process_lengths: vec![statements.len()],
clocks: Vec::new(),
private_variables: Vec::new(),
Expand Down Expand Up @@ -708,6 +720,7 @@ pub type ExecutableComponentBinding<Event, Signal> = ComponentBinding<Event, Sig

pub struct ExecutableTestbench<Event, Signal> {
kernels: Vec<TestbenchKernel<Signal>>,
scheduler: Option<TestbenchScheduler<Signal>>,
statements: Vec<ExecutableStatement<Event, Signal>>,
process_lengths: Vec<usize>,
clocks: Vec<TestbenchClock<Event>>,
Expand All @@ -720,6 +733,13 @@ pub struct ExecutableTestbench<Event, Signal> {
}

impl<Event, Signal> ExecutableTestbench<Event, Signal> {
pub fn scheduler(&self) -> Option<&TestbenchScheduler<Signal>> {
self.scheduler.as_ref()
}
pub fn with_scheduler(mut self, scheduler: Option<TestbenchScheduler<Signal>>) -> Self {
self.scheduler = scheduler;
self
}
pub fn kernels(&self) -> &[TestbenchKernel<Signal>] {
&self.kernels
}
Expand All @@ -738,6 +758,7 @@ impl<Event, Signal> ExecutableTestbench<Event, Signal> {
) -> Self {
Self {
kernels: Vec::new(),
scheduler: None,
process_lengths: vec![statements.len()],
clocks: Vec::new(),
private_signals: Vec::new(),
Expand Down
68 changes: 68 additions & 0 deletions crates/celox-testbench/src/scheduler.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
//! Persistent state of the generated Veryl testbench scheduler.
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct TestbenchScheduler<A> {
pub entry: Option<usize>,
/// Continuation, exit, simulation time, elapsed ticks, tick limit,
/// remaining slots before a runtime safe point, current process, edge-path
/// permission, finish state, settle-path permission, event reporting time, and settle continuation.
/// Indices are the `TB_*` constants below.
pub control: [A; 12],
/// State (ready/waiting/done/releasing), remaining cycles, clock, wake time, reset request.
pub processes: Vec<[A; 5]>,
/// Next rising edge, next falling edge, falling armed, generator enabled.
pub clocks: Vec<[A; 4]>,
pub events: Vec<A>,
pub periods: Vec<u64>,
pub declared: usize,
/// Per-process homes for function temporaries; design variables stay shared.
pub locals: Vec<Vec<(A, A)>>,
pub baselines: Vec<(A, A)>,
}

impl<A: Clone> TestbenchScheduler<A> {
pub fn map<B>(self, mut f: impl FnMut(A) -> B) -> TestbenchScheduler<B> {
TestbenchScheduler {
entry: self.entry,
control: self.control.map(&mut f),
processes: self.processes.into_iter().map(|v| v.map(&mut f)).collect(),
clocks: self.clocks.into_iter().map(|v| v.map(&mut f)).collect(),
events: self.events.into_iter().map(&mut f).collect(),
periods: self.periods,
declared: self.declared,
baselines: self
.baselines
.into_iter()
.map(|(a, b)| (f(a), f(b)))
.collect(),
locals: self
.locals
.into_iter()
.map(|v| v.into_iter().map(|(a, b)| (f(a), f(b))).collect())
.collect(),
}
}
}

pub const TB_PHASE: usize = 0;
pub const TB_EXIT: usize = 1;
pub const TB_NOW: usize = 2;
pub const TB_TICKS: usize = 3;
pub const TB_LIMIT: usize = 4;
pub const TB_BUDGET: usize = 5;
pub const TB_CURRENT: usize = 6;
pub const TB_HOST: u64 = 1;
pub const TB_EDGES: u64 = 2;
pub const TB_SAFEPOINT: u64 = 3;
pub const TB_DONE: u64 = 4;
pub const TB_LIMITED: u64 = 5;
pub const TB_OVERFLOW: u64 = 6;

pub const TB_RESET: u64 = 7;
pub const TB_NATIVE_EDGES: usize = 7;
pub const TB_STOPPED: usize = 8;
pub const TB_NATIVE_SETTLE: usize = 9;
pub const TB_FINISHED: u64 = 8;
pub const TB_REPORT_TIME: usize = 10;
pub const TB_SETTLE_CONT: usize = 11;
80 changes: 71 additions & 9 deletions crates/celox/src/backend/native/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ impl SharedNativeCode {
// full settle. Export names are part of the native runtime contract.
let mut clock_alias_funcs = vec![None; id_to_event.len()];
for entry in &program_image.code_entries {
if let Some(id) = entry.name.strip_prefix(super::clock_aliases::EXPORT_PREFIX) {
if let Some(id) = entry.name.strip_prefix(crate::clock_aliases::EXPORT_PREFIX) {
let id = id
.strip_suffix(']')
.and_then(|id| id.parse::<usize>().ok())
Expand Down Expand Up @@ -787,7 +787,25 @@ impl NativeProgramImage {
usize::MAX
}
});
// The derived-edge units follow the kernels and the scheduler.
let testbench_units = self
.testbench
.as_ref()
.and_then(|tb| tb.scheduler())
.and_then(|scheduler| scheduler.entry)
.map_or(0, |unit| {
if unit
== self
.runtime_schema
.processes
.len()
.saturating_add(scheduler_units)
{
1
} else {
usize::MAX
}
});
// Derived-edge units follow process and scheduler entries.
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()
Expand All @@ -799,10 +817,56 @@ impl NativeProgramImage {
.processes
.len()
.saturating_add(scheduler_units)
.saturating_add(testbench_units)
.saturating_add(derived_units)
{
return Err("process kernels and their control slots disagree".into());
}
if let Some(tb) = &self.testbench
&& let Some(scheduler) = tb.scheduler()
{
let valid_slot = |a: &AbsoluteAddr| {
self.design
.state_objects
.get(a)
.is_some_and(|info| info.width == 64 && !info.is_4state)
};
if scheduler.processes.len() != tb.kernels().len()
|| scheduler.locals.len() != tb.kernels().len()
|| scheduler.clocks.len() != scheduler.events.len()
|| scheduler.clocks.len() != scheduler.periods.len()
|| scheduler.declared > scheduler.clocks.len()
|| scheduler.periods.iter().any(|&period| period < 2)
|| !scheduler
.control
.iter()
.chain(scheduler.processes.iter().flatten())
.chain(scheduler.clocks.iter().flatten())
.all(valid_slot)
|| scheduler
.events
.iter()
.any(|a| !self.design.state_objects.contains_key(a))
|| scheduler
.locals
.iter()
.flatten()
.chain(&scheduler.baselines)
.any(|(a, b)| {
let Some(a) = self.design.state_objects.get(a) else {
return true;
};
let Some(b) = self.design.state_objects.get(b) else {
return true;
};
a.width != b.width
|| a.array_dims != b.array_dims
|| a.is_4state != b.is_4state
})
{
return Err("invalid testbench scheduler storage".into());
}
}
if self.runtime_schema.process_frames.len() != self.runtime_schema.processes.len() {
return Err("process kernels and their activation frames disagree".into());
}
Expand Down Expand Up @@ -2742,8 +2806,8 @@ fn compile_program_with_outlining_threshold(
if !options.four_state && !options.native_force_support && force_bindings.is_empty() {
let (_, clocks) = crate::backend::event_ids(sir);
for (id, clock) in clocks.into_iter().enumerate() {
if let Some(units) = super::clock_aliases::extract(sir, clock) {
let name = format!("{}{}]", super::clock_aliases::EXPORT_PREFIX, id);
if let Some(units) = crate::clock_aliases::extract(sir, clock) {
let name = format!("{}{}]", crate::clock_aliases::EXPORT_PREFIX, id);
let compiled = compile_units(
&units,
layout,
Expand Down Expand Up @@ -4257,11 +4321,9 @@ mod tests {
.unwrap()
.into_program_image();
let previous = image.code_entries.len();
image.code_entries.retain(|entry| {
!entry
.name
.starts_with(super::super::clock_aliases::EXPORT_PREFIX)
});
image
.code_entries
.retain(|entry| !entry.name.starts_with(crate::clock_aliases::EXPORT_PREFIX));
assert_eq!(previous, image.code_entries.len() + 1);
let image =
NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()).unwrap();
Expand Down
4 changes: 2 additions & 2 deletions crates/celox/src/backend/native/image_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ use std::{
use super::backend::NativeProgramImage;

const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI";
// Concurrent assertion kernels suspend into Observed and Reactive regions.
const CONTAINER_VERSION: u16 = 53;
// Images retain generated TB scheduler continuations and clock state.
const CONTAINER_VERSION: u16 = 55;
const TRAILER_SIZE: usize = 32;
const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325;
const FNV_PRIME: u64 = 0x0000_0100_0000_01b3;
Expand Down
1 change: 0 additions & 1 deletion crates/celox/src/backend/native/mod.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
pub mod backend;
mod clock_aliases;
mod compile_resources;
#[cfg(target_os = "linux")]
mod executable_mapping;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ use crate::ir::{
};
use celox_sir::BasicBlock;

pub(super) const EXPORT_PREFIX: &str = "clock_alias_update[";
pub(crate) const EXPORT_PREFIX: &str = "clock_alias_update[";

pub(super) fn extract(
pub(crate) fn extract(
program: &LaidOutProgram,
clock: AbsoluteAddr,
) -> Option<Vec<ExecutionUnit<RegionedAbsoluteAddr>>> {
Expand Down
7 changes: 7 additions & 0 deletions crates/celox/src/ir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,13 @@ impl RuntimeDesign {
address
}

pub(crate) fn allocate_testbench_copy(&mut self, source: AbsoluteAddr) -> AbsoluteAddr {
let info = self.semantic.state_objects[&source].clone();
let address = self.allocate_testbench_slot(info.width, false);
self.semantic.state_objects.insert(address, info);
address
}

fn from_projection(
semantic: celox_design::ElaboratedDesign<AbsoluteAddr>,
frontend: FrontendLookup,
Expand Down
2 changes: 2 additions & 0 deletions crates/celox/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ mod parser;
pub(crate) mod portable;
// Builds without the host runtime run every slot in the reference loop.
#[cfg(feature = "host-runtime")]
mod clock_aliases;
#[cfg(feature = "host-runtime")]
mod scheduler;
mod settle;
#[cfg(feature = "host-runtime")]
Expand Down
Loading
Loading