Skip to content
Merged
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
280 changes: 140 additions & 140 deletions conformance/sv-tests/expected.tsv

Large diffs are not rendered by default.

19 changes: 15 additions & 4 deletions crates/celox-design/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -616,6 +616,17 @@ impl std::fmt::Display for ProcessOrigin {
}
}

/// When a procedural kernel is invoked by the runtime.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ProcessKind {
/// Static declarations run before ordinary HDL procedures.
Initializer,
#[default]
Regular,
/// A final procedure runs only when simulation ends (IEEE 1800-2023 9.2.3).
Final,
}

/// State through which one process kernel exchanges control with the runtime.
///
/// A process kernel is a resumable function. On entry it reads `resume` to
Expand All @@ -625,9 +636,9 @@ impl std::fmt::Display for ProcessOrigin {
/// checkpoints capture a suspended process.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ProcessSlots<A> {
/// A static declaration initializer, executed before all HDL procedures.
pub is_initializer: bool,
/// This kernel originated from an edge procedure and must execute in Simulation.
/// The phase in which the runtime invokes this kernel.
pub kind: ProcessKind,
/// This kernel requires Simulation's process scheduler rather than Simulator.
pub requires_timed_simulation: bool,
/// Every delay the kernel suspends for is a constant of at least one
/// time unit.
Expand All @@ -646,7 +657,7 @@ pub struct ProcessSlots<A> {
impl<A> ProcessSlots<A> {
pub fn map<B>(self, mut map: impl FnMut(A) -> B) -> ProcessSlots<B> {
ProcessSlots {
is_initializer: self.is_initializer,
kind: self.kind,
requires_timed_simulation: self.requires_timed_simulation,
const_delays: self.const_delays,
program: self.program.map(&mut map),
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-frontend-core/src/sdk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1729,7 +1729,7 @@ fn lower_processes(
for (index, process) in artifact.processes().iter().enumerate() {
let name = |slot: &str| vec![format!("$process[{index}]"), slot.to_string()];
let slots = ProcessSlots {
is_initializer: false,
kind: celox_design::ProcessKind::Regular,
requires_timed_simulation: false,
const_delays: false,
program: None,
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-frontend-core/src/symbolic/assembly.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1940,7 +1940,7 @@ pub fn schedule_symbolic_rtl_reporting_loops(
.collect();
let declaration_startup = processes
.iter()
.any(|process| process.slots.is_initializer)
.any(|process| process.slots.kind == celox_design::ProcessKind::Initializer)
.then(|| {
let targets: BTreeSet<_> = folded_initials.iter().map(|init| init.address).collect();
let mut reset = targets
Expand Down
24 changes: 14 additions & 10 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1348,7 +1348,7 @@ fn kernel_window_writes(
for process in module
.initial_processes()
.iter()
.filter(|process| !process.is_initializer())
.filter(|process| !process.is_initializer() && !process.is_final())
{
let body = process.body();
let first = if process.repeats() {
Expand Down Expand Up @@ -4978,6 +4978,7 @@ fn process_origin(process: &sv::ir::InitialProcess) -> celox_design::ProcessOrig
let construct = match process.site() {
Some(site) => site.construct,
None if process.is_initializer() => "declaration initializer",
None if process.is_final() => "final",
None if process.repeats() => "always",
None => "initial",
};
Expand All @@ -4988,9 +4989,9 @@ fn process_origin(process: &sv::ir::InitialProcess) -> celox_design::ProcessOrig
}
}

/// The `initial` blocks and declaration initializers (IEEE 1800-2023 9.2.1,
/// 10.5): the initial state they define, and the processes that run the
/// others from time zero.
/// Lower declaration initializers and procedural kernels. Final procedures
/// retain kernels but execute only at simulation termination (9.2.3); they
/// must never contribute folded initial state.
///
/// A block whose writes have constant values defines initial state, with
/// the hidden variables used while executing it discarded. Declaration
Expand Down Expand Up @@ -5062,7 +5063,10 @@ fn lower_initial_processes(
// initial state. A program's `initial` procedure runs in the reactive
// region set (IEEE 1800-2023 24.3.1), after the design's processes of
// time zero, so it is not folded either.
if process.repeats() || (module.is_program() && !process.is_initializer()) {
if process.is_final()
|| process.repeats()
|| (module.is_program() && !process.is_initializer())
{
runtime.push((process, random_seed));
continue;
}
Expand Down Expand Up @@ -5138,8 +5142,8 @@ fn lower_initial_processes(
id
};
ProcessSlots {
is_initializer: process.is_initializer(),
requires_timed_simulation: process.is_scheduled_edge(),
kind: process.kind(),
requires_timed_simulation: process.is_scheduled_edge() || process.is_final(),
const_delays: false,
program: None,
resume: declare("resume", PROCESS_RESUME_WIDTH),
Expand All @@ -5155,10 +5159,10 @@ fn lower_initial_processes(
let program = slots
.iter()
.zip(&runtime)
.find(|(_, (process, _))| !process.is_initializer())
.find(|(_, (process, _))| !process.is_initializer() && !process.is_final())
.map(|(slots, _)| slots.status);
for (slots, (process, _)) in slots.iter_mut().zip(&runtime) {
if !process.is_initializer() {
if !process.is_initializer() && !process.is_final() {
slots.program = program;
}
}
Expand Down Expand Up @@ -10725,7 +10729,7 @@ endmodule
.runtime_schema
.processes
.iter()
.filter(|process| !process.is_initializer)
.filter(|process| process.kind != celox_design::ProcessKind::Initializer)
.count()
}

Expand Down
23 changes: 21 additions & 2 deletions crates/celox-runtime/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,11 @@ pub enum SimulatorErrorCode {
DetectedTrueLoopAt {
signals: Vec<String>,
},
/// `$fatal` also implicitly requests simulation termination.
Fatal {
message: String,
signals: Vec<String>,
},
Runtime {
message: String,
signals: Vec<String>,
Expand Down Expand Up @@ -36,6 +41,16 @@ impl PartialEq for SimulatorErrorCode {
signals: sb,
},
) => a == b && sa == sb,
(
Self::Fatal {
message: a,
signals: sa,
},
Self::Fatal {
message: b,
signals: sb,
},
) => a == b && sa == sb,
(Self::NotAnEvent(a), Self::NotAnEvent(b)) => a == b,
_ => false,
}
Expand All @@ -54,8 +69,12 @@ impl std::fmt::Display for SimulatorErrorCode {
Self::DetectedTrueLoopAt { signals } => {
write!(f, "Detected True Loop: {}", signals.join(", "))
}
Self::Runtime { message, signals } if signals.is_empty() => write!(f, "{message}"),
Self::Runtime { message, signals } => {
Self::Fatal { message, signals } | Self::Runtime { message, signals }
if signals.is_empty() =>
{
write!(f, "{message}")
}
Self::Fatal { message, signals } | Self::Runtime { message, signals } => {
write!(f, "{}: {}", message, signals.join(", "))
}
Self::InternalError => write!(f, "Internal Error"),
Expand Down
6 changes: 4 additions & 2 deletions crates/celox-runtime/src/schedule.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ impl<B: SimBackend> ResolvedSchedule<B> {
.processes
.iter()
.map(|process| ProcessRefs {
is_initializer: process.slots.is_initializer,
kind: process.slots.kind,
program: process.slots.program.as_ref().map(resolve),
resume: resolve(&process.slots.resume),
starts_with_event_wait: process.slots.requires_timed_simulation,
Expand Down Expand Up @@ -312,7 +312,9 @@ impl<B: SimBackend> ResolvedSchedule<B> {
program_processes: processes
.iter()
.enumerate()
.filter(|(_, process)| process.program.is_some())
.filter(|(_, process)| {
process.kind == celox_design::ProcessKind::Regular && process.program.is_some()
})
.map(|(index, _)| index)
.collect(),
processes,
Expand Down
4 changes: 4 additions & 0 deletions crates/celox-runtime/src/simulation/compiled.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,10 @@ impl<B: SimBackend> SimulationState<B> {
}
Err(Halt::Stop) => Ok(Some(self.scheduler.time)),
Err(Halt::Error(error)) => {
if matches!(&error, SimulatorErrorCode::Fatal { .. }) {
let _ = self.finalize_terminal(executor);
return Err(error);
}
let _ = self.finish_timed_boundary(executor, self.scheduler.time);
let _ = executor.flush_output();
Err(error)
Expand Down
71 changes: 37 additions & 34 deletions crates/celox-runtime/src/simulation/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ mod persist;
mod process;
mod round;
mod stats;
mod terminal;
mod time;
mod wait;

Expand Down Expand Up @@ -146,6 +147,8 @@ pub struct SimulationState<B: SimBackend> {
host_pending: bool,
/// A process requested the end of the simulation.
finished: bool,
/// Next final procedure while terminal execution is suspended by `$stop`.
finalizing: Option<usize>,
/// A process suspended the simulation (`$stop`) in the last step.
stopped: bool,
/// The round a `$stop` suspended, which the next step continues.
Expand Down Expand Up @@ -193,7 +196,9 @@ impl<B: SimBackend> SimulationState<B> {
.processes
.iter()
.enumerate()
.filter_map(|(index, process)| process.is_initializer.then_some(index))
.filter_map(|(index, process)| {
(process.kind == celox_design::ProcessKind::Initializer).then_some(index)
})
.collect();
let declarations_pending = !declaration_processes.is_empty();
let mut state = Self {
Expand All @@ -202,6 +207,7 @@ impl<B: SimBackend> SimulationState<B> {
last_clock_unknown: BitSet::new(),
four_state: backend.layout().four_state,
process_wakeups: (0..model.processes.len())
.filter(|&index| model.processes[index].kind != celox_design::ProcessKind::Final)
.map(|process| Reverse((0, process)))
.collect(),
model,
Expand All @@ -210,6 +216,7 @@ impl<B: SimBackend> SimulationState<B> {
declarations_pending,
host_pending: false,
finished: false,
finalizing: None,
stopped: false,
suspended: None,
scratch: None,
Expand Down Expand Up @@ -253,6 +260,13 @@ impl<B: SimBackend> SimulationState<B> {
E: SimulationExecutor<Backend = B>,
{
self.stopped = false;
if self.finalizing.is_some() {
if self.scheduler.time > limit {
return Ok(None);
}
self.finalize_terminal(executor)?;
return Ok(Some(self.scheduler.time));
}
match self.step_time(executor, limit) {
Ok(time) => Ok(time),
Err(Halt::Finish) => {
Expand All @@ -262,6 +276,10 @@ impl<B: SimBackend> SimulationState<B> {
// The time slot goes on when the simulation continues.
Err(Halt::Stop) => Ok(Some(self.scheduler.time)),
Err(Halt::Error(error)) => {
if matches!(&error, SimulatorErrorCode::Fatal { .. }) {
let _ = self.finalize_terminal(executor);
return Err(error);
}
// Preserve the primary runtime failure even if diagnostic
// waveform output also fails. This does not resume processes.
let _ = self.finish_timed_boundary(executor, self.scheduler.time);
Expand Down Expand Up @@ -312,7 +330,10 @@ impl<B: SimBackend> SimulationState<B> {
// A process the scheduler does not run waits: the slot stays in
// the reference loop. Test that first, as designs with such
// processes fail it at every step.
let compiled = if compiles && self.process_state.waiters.len() <= waiting_kernels {
let compiled = if self.finalizing.is_none()
&& compiles
&& self.process_state.waiters.len() <= waiting_kernels
{
self.compiled_limit(executor, end, observer.one_slot())
} else {
None
Expand Down Expand Up @@ -405,9 +426,14 @@ impl<B: SimBackend> SimulationState<B> {
{
match executor.try_finish_timed_step(time) {
Ok(()) => Ok(()),
Err(Halt::Error(error)) => Err(error),
Err(Halt::Error(error)) => {
if matches!(&error, SimulatorErrorCode::Fatal { .. }) {
let _ = self.finalize_terminal(executor);
}
Err(error)
}
Err(Halt::Finish) => {
self.finish_checked(executor)?;
self.finalize_terminal(executor)?;
Ok(())
}
Err(Halt::Stop) => {
Expand All @@ -417,34 +443,6 @@ impl<B: SimBackend> SimulationState<B> {
}
}

fn finish_checked<E>(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode>
where
E: SimulationExecutor<Backend = B>,
{
self.finished = true;
executor.try_freeze()
}

/// Once $finish is consumed, output errors must not make execution resumable.
pub fn finalize_terminal<E>(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode>
where
E: SimulationExecutor<Backend = B>,
{
self.finished = true;
let output = self.finish_timed_boundary(executor, self.scheduler.time);
let frozen = executor.try_freeze();
output.and(frozen)
}

/// End the simulation where it is.
pub fn finish<E>(&mut self, executor: &mut E)
where
E: SimulationExecutor<Backend = B>,
{
self.finished = true;
executor.freeze();
}

/// Whether a process requested the end of the simulation.
pub fn is_finished(&self) -> bool {
self.finished
Expand All @@ -461,7 +459,8 @@ impl<B: SimBackend> SimulationState<B> {
/// Whether the simulation is suspended in the middle of a time slot, so
/// that its scheduling state cannot be captured.
pub fn is_suspended(&self) -> bool {
self.suspended.is_some() || (self.stopped && self.declarations_pending)
self.suspended.is_some()
|| (self.stopped && (self.declarations_pending || self.finalizing.is_some()))
}

/// Settle externally driven state against the previous edge baseline even
Expand All @@ -486,6 +485,10 @@ impl<B: SimBackend> SimulationState<B> {
}
Err(Halt::Stop) => Ok(Some(self.scheduler.time)),
Err(Halt::Error(error)) => {
if matches!(&error, SimulatorErrorCode::Fatal { .. }) {
let _ = self.finalize_terminal(executor);
return Err(error);
}
// Preserve the primary runtime failure even if diagnostic
// waveform output also fails. This does not resume processes.
let _ = self.finish_timed_boundary(executor, self.scheduler.time);
Expand Down Expand Up @@ -556,7 +559,7 @@ impl<B: SimBackend> SimulationState<B> {
return None;
}
// Host writes are work of the current time.
if self.host_pending {
if self.host_pending || self.finalizing.is_some() {
return Some(self.scheduler.time);
}
self.next_work_time()
Expand Down
Loading
Loading