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
8 changes: 4 additions & 4 deletions conformance/sv-tests/expected.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1645,14 +1645,14 @@ chapter-9/9.4.5--event_nonblocking_assignment_repeat_int_neg.sv 2state fail
chapter-9/9.4.5--event_nonblocking_assignment_repeat_int_neg.sv 4state fail
chapter-9/9.4.5--event_nonblocking_assignment_repeat_neg.sv 2state fail
chapter-9/9.4.5--event_nonblocking_assignment_repeat_neg.sv 4state fail
chapter-9/9.6.1--wait_fork.sv 2state fail
chapter-9/9.6.1--wait_fork.sv 4state fail
chapter-9/9.6.1--wait_fork.sv 2state pass
chapter-9/9.6.1--wait_fork.sv 4state pass
chapter-9/9.6.2--disable.sv 2state fail
chapter-9/9.6.2--disable.sv 4state fail
chapter-9/9.6.2--disable_other.sv 2state fail
chapter-9/9.6.2--disable_other.sv 4state fail
chapter-9/9.6.3--disable_fork.sv 2state fail
chapter-9/9.6.3--disable_fork.sv 4state fail
chapter-9/9.6.3--disable_fork.sv 2state pass
chapter-9/9.6.3--disable_fork.sv 4state pass
chapter-9/9.7--process_cls_await.sv 2state fail
chapter-9/9.7--process_cls_await.sv 4state fail
chapter-9/9.7--process_cls_kill.sv 2state fail
Expand Down
8 changes: 8 additions & 0 deletions crates/celox-design/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,10 @@ pub enum ProcessStatus {
Fork,
/// Allocate a fresh automatic local cell before its declaration initializer.
Local,
/// Wait for all live immediate child activations.
WaitFork,
/// Terminate all descendants of the calling activation.
DisableFork,
}

impl ProcessStatus {
Expand All @@ -484,6 +488,8 @@ impl ProcessStatus {
Self::Exit => 11,
Self::Fork => 12,
Self::Local => 13,
Self::WaitFork => 14,
Self::DisableFork => 15,
}
}

Expand All @@ -502,6 +508,8 @@ impl ProcessStatus {
11 => Some(Self::Exit),
12 => Some(Self::Fork),
13 => Some(Self::Local),
14 => Some(Self::WaitFork),
15 => Some(Self::DisableFork),
_ => None,
}
}
Expand Down
24 changes: 20 additions & 4 deletions crates/celox-frontend-core/src/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ pub struct ProcessKernelBuilder {
slots: ProcessSlots<SourceVarId>,
/// The block each resume point continues in; point 0 is the start.
resume_blocks: Vec<BlockId>,
/// The wait site whose resume point is being lowered.
wait_site: Option<u32>,
/// The wait site and predicate entry resume point being lowered.
wait_site: Option<(u32, usize)>,
/// The runtime event site the process reports at its flush points
/// (see [`Self::flush_deferred_at`]).
flush_site: Option<u32>,
Expand Down Expand Up @@ -217,6 +217,19 @@ impl ProcessKernelBuilder {
Ok((children, self.builder.current_block()))
}

/// Wait for the calling process's immediate children (IEEE 1800-2023 9.6.1).
pub fn wait_fork(&mut self) -> Result<(), ProcessKernelError> {
self.slots.const_delays = false;
self.slots.requires_timed_simulation = true;
self.suspend(ProcessStatus::WaitFork)
}

/// Cancel descendants without suspending HDL execution (9.6.3).
pub fn disable_fork(&mut self) -> Result<(), ProcessKernelError> {
self.slots.const_delays = false;
self.suspend(ProcessStatus::DisableFork)
}

pub fn local(&mut self, slot: usize) -> Result<(), ProcessKernelError> {
self.store_delay_constant(slot as u64);
self.suspend(ProcessStatus::Local)
Expand Down Expand Up @@ -245,7 +258,7 @@ impl ProcessKernelBuilder {
pub fn suspend_wait(&mut self, site: u32) -> Result<(), ProcessKernelError> {
self.store_delay_constant(u64::from(site));
self.suspend(ProcessStatus::Wait)?;
self.wait_site = Some(site);
self.wait_site = Some((site, self.resume_blocks.len() - 1));
Ok(())
}

Expand All @@ -254,7 +267,7 @@ impl ProcessKernelBuilder {
/// that the wait is still pending and return to the same resume point.
/// The continuation block is open afterwards.
pub fn wake_if(&mut self, condition: RegisterId) {
let site = self.wait_site.take().expect("wake_if follows suspend_wait");
let (site, resume) = self.wait_site.take().expect("wake_if follows suspend_wait");
let woken = self.builder.new_block();
let pending = self.builder.new_block();
self.builder.seal_block(SIRTerminator::Branch {
Expand All @@ -263,6 +276,9 @@ impl ProcessKernelBuilder {
false_block: (pending, Vec::new()),
});
self.builder.switch_to_block(pending);
// Predicate evaluation may itself yield to the runtime (for example,
// disable fork). A later wakeup must evaluate the whole predicate.
self.store_constant(self.slots.resume, PROCESS_RESUME_WIDTH, resume as u64);
self.store_delay_constant(u64::from(site));
self.end(ProcessStatus::Pending);
self.builder.switch_to_block(woken);
Expand Down
5 changes: 4 additions & 1 deletion crates/celox-frontend-sv/src/lowering/comb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2026,7 +2026,10 @@ impl<'p, 'a> Comb<'p, 'a> {
stmt: &sv::ir::Stmt,
) -> Result<Store, sv::AnalyzerError> {
match stmt {
sv::ir::Stmt::Fork { .. } => Err(unsupported("fork outside a timed process")),
sv::ir::Stmt::DisableFork => Ok(store),
sv::ir::Stmt::Fork { .. } | sv::ir::Stmt::WaitFork => {
Err(unsupported("fork control outside a timed process"))
}
sv::ir::Stmt::Assign {
lhs,
rhs,
Expand Down
65 changes: 41 additions & 24 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3014,6 +3014,23 @@ impl<'p, 'a> Ff<'p, 'a> {
self.wait_level(condition)?;
Ok(true)
}
sv::ir::Stmt::WaitFork | sv::ir::Stmt::DisableFork => {
if self.kernel.is_none() {
return if matches!(stmt, sv::ir::Stmt::DisableFork) {
Ok(true)
Comment on lines +3018 to +3020

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve cancellation when lowering a wait-condition function

When a function containing disable fork is called from a wait condition, this branch silently discards the cancellation. Ff::wait_level temporarily takes self.kernel out while lowering the predicate, so self.kernel.is_none() does not necessarily mean execution is outside a timed process. For example, after spawning a delayed child, wait(cancel()) with a function that executes disable fork and returns 1 continues without cancelling that child, allowing its later writes to occur. Preserve the caller's process-control effects while lowering these predicates, rather than treating this temporary builder state as a no-op context.

Useful? React with 👍 / 👎.

} else {
Err(unsupported("fork control outside a timed process"))
};
}
if matches!(stmt, sv::ir::Stmt::WaitFork) {
self.with_kernel(ProcessKernelBuilder::wait_fork)
.map_err(kernel_error)?;
} else {
self.with_kernel(ProcessKernelBuilder::disable_fork)
.map_err(kernel_error)?;
}
Ok(true)
}
sv::ir::Stmt::Fork { join, branches } => {
if self.kernel.is_none() {
return Err(unsupported("fork outside a timed process"));
Expand Down Expand Up @@ -5231,7 +5248,7 @@ impl Ff<'_, '_> {
let mut calls = Vec::new();
for stmt in body {
stmt.walk(&mut |stmt| match stmt {
sv::ir::Stmt::Fork { .. } => found = true,
sv::ir::Stmt::Fork { .. } | sv::ir::Stmt::WaitFork => found = true,
sv::ir::Stmt::Call { name, .. } => calls.push(name.clone()),
_ => {}
});
Expand Down Expand Up @@ -6130,30 +6147,29 @@ impl Ff<'_, '_> {
.map(|id| (id, CounterKind::Changes))
.collect(),
);
// The condition is lowered once per check: before the process
// suspends and at every resume.
let mut error = None;
let mut kernel = self.kernel.take().expect("lowering a process kernel");
std::mem::swap(&mut self.b, kernel.builder());
// The kernel is out of `self` while it builds the checks; reads go
// to stable state all the same.
// Keep the kernel available while evaluating the predicate: functions
// may perform synchronous process control such as disable fork.
let direct = std::mem::replace(&mut self.direct, true);
let result = kernel.wait_level(site, |builder| {
std::mem::swap(&mut self.b, builder);
let truth = self.eval_truth(condition).map(|(truth, _)| truth);
std::mem::swap(&mut self.b, builder);
truth.unwrap_or_else(|e| {
error = Some(e);
let never = builder.alloc_bit(1, false);
builder.emit(SIRInstruction::Imm(never, SIRValue::new(0u8)));
never
})
});
let result = (|| {
let (holds, _) = self.eval_truth(condition)?;
let join = self.b.new_block();
let wait = self.b.new_block();
self.b.seal_block(SIRTerminator::Branch {
cond: holds,
true_block: (join, Vec::new()),
false_block: (wait, Vec::new()),
});
self.b.switch_to_block(wait);
self.with_kernel(|kernel| kernel.suspend_wait(site))
.map_err(kernel_error)?;
let (holds, _) = self.eval_truth(condition)?;
self.with_kernel(|kernel| kernel.wake_if(holds));
self.b.seal_block(SIRTerminator::Jump(join, Vec::new()));
self.b.switch_to_block(join);
Ok(())
})();
self.direct = direct;
std::mem::swap(&mut self.b, kernel.builder());
self.kernel = Some(kernel);
result.map_err(kernel_error)?;
error.map_or(Ok(()), Err)
result
}

/// Declare a wait site of the process with the given terms and return
Expand Down Expand Up @@ -6394,7 +6410,8 @@ fn impure_call(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option<String> {
args: args.clone(),
arg_order: arg_order.clone(),
}),
sv::ir::Stmt::SystemTask { .. }
sv::ir::Stmt::DisableFork
| sv::ir::Stmt::SystemTask { .. }
| sv::ir::Stmt::Delay { .. }
| sv::ir::Stmt::WaitEvent(_)
| sv::ir::Stmt::WaitImplicit(_)
Expand Down
58 changes: 58 additions & 0 deletions crates/celox-runtime/src/simulation/activation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,64 @@ impl<B: SimBackend> SimulationState<B> {
}
}

/// Only immediate, still-live children participate, even when an already
/// completed child left running descendants (IEEE 1800-2023 9.6.1).
pub(super) fn wait_for_children(&mut self, process: usize) -> bool {
let children: Vec<_> = self
.process_state
.activations
.iter()
.enumerate()
.filter_map(|(id, activation)| {
(activation.live && activation.parent == Some(process)).then_some(id)
})
.collect();
if children.is_empty() {
return true;
}
self.process_state.activations[process].join = Some((ForkJoin::All, children));
false
}

/// Follow ancestry through completed parents too (IEEE 1800-2023 9.6.3).
/// Remove scheduler entries before releasing IDs for reuse.
pub(super) fn disable_children(&mut self, process: usize) {
if self.process_state.activations.is_empty() {
return;
}
let mut cancelled = vec![false; self.process_state.activations.len()];
let mut pending = vec![process];
while let Some(parent) = pending.pop() {
for (id, activation) in self.process_state.activations.iter().enumerate() {
if activation.parent == Some(parent) && !cancelled[id] {
cancelled[id] = true;
pending.push(id);
}
}
}
let state = &mut self.process_state;
for (id, activation) in state.activations.iter_mut().enumerate() {
activation.pending.retain(|&child| !cancelled[child]);
if cancelled[id] {
activation.live = false;
activation.join = None;
state.waiters.remove(id);
state.ready.remove(&id);
state.reactive.remove(&id);
state.inactive.remove(&id);
state.re_inactive.remove(&id);
}
}
self.process_wakeups
.retain(|std::cmp::Reverse((_, id))| !cancelled[*id]);
// Already captured NBA values are independent scheduler work.
for (id, &cancelled) in cancelled.iter().enumerate() {
if cancelled {
self.retire_activation(id);
}
}
}

pub(super) fn end_activation(&mut self, process: usize) {
if self.process_state.activations.is_empty()
|| self.model.processes[process].frame.is_none()
Expand Down
5 changes: 5 additions & 0 deletions crates/celox-runtime/src/simulation/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,11 @@ impl<B: SimBackend> SimulationState<B> {
self.charge(*returns, Some(process))?;
return self.fork_activation(executor.backend_mut(), process, encoded);
}
Some(ProcessStatus::WaitFork) => return Ok(self.wait_for_children(process)),
Some(ProcessStatus::DisableFork) => {
self.disable_children(process);
return Ok(true);
}
Some(ProcessStatus::Local) => {
let index = delay() as usize;
self.allocate_local(process, index)?;
Expand Down
7 changes: 6 additions & 1 deletion crates/celox-runtime/src/simulation/terminal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,12 @@ impl<B: SimBackend> SimulationState<B> {
}
// Yield is an implementation boundary, not an HDL timing control.
// NBA events created by a final never run after termination (9.2.3).
Some(ProcessStatus::Yield | ProcessStatus::Nba | ProcessStatus::Local) => {}
Some(
ProcessStatus::Yield
| ProcessStatus::Nba
| ProcessStatus::Local
| ProcessStatus::DisableFork,
) => {}
_ => {
return Err(SimulatorErrorCode::Runtime {
message: "final procedure cannot suspend for HDL timing".into(),
Expand Down
6 changes: 5 additions & 1 deletion crates/celox-sv-analyzer/src/ast/const_functions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1402,7 +1402,11 @@ impl Frame<'_> {
Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::WaitImplicit(_) | Stmt::Wait(_) => {
return None;
}
Stmt::Fork { .. } | Stmt::AssignConcat { .. } | Stmt::Call { .. } => return None,
Stmt::Fork { .. }
| Stmt::WaitFork
| Stmt::DisableFork
| Stmt::AssignConcat { .. }
| Stmt::Call { .. } => return None,
}
Some(Flow::Next)
}
Expand Down
8 changes: 7 additions & 1 deletion crates/celox-sv-analyzer/src/ast/lifetimes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,7 @@ impl Flow<'_> {
self.read(expr, written)?;
Ok(Exits::next(written))
}
Stmt::WaitFork | Stmt::DisableFork => Ok(Exits::next(written)),
Stmt::WaitEvent(items) => {
for item in items {
self.read(&item.expr, written)?;
Expand Down Expand Up @@ -829,7 +830,12 @@ pub(super) fn stmt_exprs(stmt: &Stmt) -> Vec<&Expr> {
Stmt::Delay { amount: expr, .. } | Stmt::Wait(expr) => vec![expr],
Stmt::WaitEvent(items) => items.iter().map(|item| &item.expr).collect(),
// The statements of an `@*` describe its reads and do not run.
Stmt::Fork { .. } | Stmt::WaitImplicit(_) | Stmt::Break | Stmt::Continue => Vec::new(),
Stmt::Fork { .. }
| Stmt::WaitFork
| Stmt::DisableFork
| Stmt::WaitImplicit(_)
| Stmt::Break
| Stmt::Continue => Vec::new(),
}
}

Expand Down
13 changes: 8 additions & 5 deletions crates/celox-sv-analyzer/src/ast/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -968,7 +968,10 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> {
_ => self.subroutine_call_statement(*id),
},
StatementKind::Assertion { .. } => Err(unsupported("concurrent assertion")),
StatementKind::WaitFork => Err(unsupported("wait fork statement")),
StatementKind::WaitFork => {
self.allow_timing("wait fork statement")?;
Ok(vec![Stmt::WaitFork])
Comment on lines +971 to +973

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include wait fork in timed-task classification

Tasks containing the newly accepted Stmt::WaitFork are not classified as suspendable: ast/procedural/timed_tasks.rs::suspends still recognizes only delays, event controls, level waits, and previously classified task calls. Consequently, a valid ordinary process such as always @(posedge clk) await_children();, where await_children contains wait fork, remains on the non-kernel FF lowering path and fails with fork control outside a timed process. Add this variant to suspension propagation so ordinary event-driven callers are promoted to process kernels, as they are for other blocking task statements.

Useful? React with 👍 / 👎.

}
StatementKind::WaitOrder { .. } => Err(unsupported("wait order statement")),
StatementKind::EventTrigger(_) => Err(unsupported("event trigger")),
StatementKind::ProceduralAssign(_) | StatementKind::ProceduralRelease(_) => {
Expand All @@ -985,11 +988,11 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> {
.filter(|token| !token.is_trivia())
.find(|token| token.text != "disable")
.is_some_and(|token| token.text == "fork");
Err(unsupported(if disables_fork {
"disable fork statement"
if disables_fork {
Ok(vec![Stmt::DisableFork])
} else {
"disable statement"
}))
Err(unsupported("disable statement"))
}
}
StatementKind::Parallel { .. } => Err(unsupported("fork-join block")),
_ => Err(unsupported("procedural statement")),
Expand Down
9 changes: 6 additions & 3 deletions crates/celox-sv-analyzer/src/ast/procedural/timed_tasks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -192,9 +192,12 @@ fn suspends(body: &[Stmt], timed: &HashSet<String>) -> bool {
for statement in body {
statement.walk(&mut |statement| {
result |= match statement {
Stmt::Delay { .. } | Stmt::WaitEvent(_) | Stmt::WaitImplicit(_) | Stmt::Wait(_) => {
true
}
Stmt::Delay { .. }
| Stmt::WaitEvent(_)
| Stmt::WaitImplicit(_)
| Stmt::Wait(_)
| Stmt::WaitFork
| Stmt::Fork { .. } => true,
Stmt::Call { name, .. } => timed.contains(name),
_ => false,
};
Expand Down
Loading
Loading