diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs
index 412ab44f11a..a7c52360619 100644
--- a/crates/celox-design/src/lib.rs
+++ b/crates/celox-design/src/lib.rs
@@ -216,11 +216,31 @@ pub struct RuntimeErrorInfo {
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ProcessStatus {
/// Resume after the number of time units stored in [`ProcessSlots::delay`].
+ /// A zero delay resumes at the same time after the nonblocking
+ /// assignments of that time are published.
Delay,
/// The process ran to the end of its body.
Done,
/// The process requested the end of the simulation.
Finish,
+ /// Like [`Self::Delay`], but a zero delay resumes in the inactive region
+ /// of the same time, before nonblocking assignments are published (IEEE
+ /// 1800-2023 4.4.2.3).
+ InactiveDelay,
+ /// The process suspended at an event or level wait. The delay slot holds
+ /// the index of its [`WaitSite`]. The runtime resumes the process when a
+ /// counter of that site moves; the kernel then checks the wait itself.
+ Wait,
+ /// The process was resumed at a wait whose condition does not hold. It
+ /// ran no statement and waits at the same site.
+ Pending,
+ /// The process staged one nonblocking assignment. The delay slot holds
+ /// the index of its [`NbaSite`]. The runtime queues the staged value and
+ /// resumes the process at once.
+ Nba,
+ /// The process returned so the runtime can charge its time-slot budget.
+ /// It resumes at once.
+ Yield,
}
impl ProcessStatus {
@@ -231,6 +251,11 @@ impl ProcessStatus {
Self::Delay => 1,
Self::Done => 2,
Self::Finish => 3,
+ Self::InactiveDelay => 4,
+ Self::Wait => 5,
+ Self::Pending => 6,
+ Self::Nba => 7,
+ Self::Yield => 8,
}
}
@@ -239,6 +264,11 @@ impl ProcessStatus {
1 => Some(Self::Delay),
2 => Some(Self::Done),
3 => Some(Self::Finish),
+ 4 => Some(Self::InactiveDelay),
+ 5 => Some(Self::Wait),
+ 6 => Some(Self::Pending),
+ 7 => Some(Self::Nba),
+ 8 => Some(Self::Yield),
_ => None,
}
}
@@ -277,6 +307,191 @@ pub const PROCESS_STATUS_WIDTH: usize = 8;
/// Width of [`ProcessSlots::delay`].
pub const PROCESS_DELAY_WIDTH: usize = 64;
+/// Width of every occurrence counter of an [`EventWatch`]. Counters wrap;
+/// only their inequality is meaningful.
+pub const EVENT_COUNTER_WIDTH: usize = 32;
+
+/// The occurrences an event counter counts on its watched signal (IEEE
+/// 1800-2023 9.4.2, Table 9-2).
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
+pub enum CounterKind {
+ /// Any change of the value, including the unknown bits.
+ Changes,
+ /// A positive edge of the least significant bit.
+ Rises,
+ /// A negative edge of the least significant bit.
+ Falls,
+}
+
+impl CounterKind {
+ pub const ALL: [Self; 3] = [Self::Changes, Self::Rises, Self::Falls];
+
+ /// The counter kind that wakes an event domain of `kind`.
+ pub const fn for_domain(kind: DomainKind) -> Self {
+ match kind {
+ DomainKind::ClockPosedge | DomainKind::ResetAsyncHigh => Self::Rises,
+ DomainKind::ClockNegedge | DomainKind::ResetAsyncLow => Self::Falls,
+ DomainKind::Other => Self::Changes,
+ }
+ }
+}
+
+/// A counted signal: a signal that an event control or flip-flop domain
+/// watches and that one unit may store twice without the runtime checking
+/// in between. Its occurrences are counted in two-state counter objects.
+///
+/// Generated code bumps the counters around each such store (see
+/// `celox_frontend_core::watch`) and the host and the scheduler bump them on
+/// their writes. Every other watched signal is checked by value. The
+/// counters are ordinary state.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct EventWatch {
+ pub signal: A,
+ pub width: usize,
+ pub four_state: bool,
+ pub changes: Option,
+ pub rises: Option,
+ pub falls: Option,
+ /// Canonical event domains that the counter of the given kind triggers
+ /// instead of edge detection by value.
+ pub domains: Vec<(A, CounterKind)>,
+}
+
+impl EventWatch {
+ pub fn counter(&self, kind: CounterKind) -> Option {
+ match kind {
+ CounterKind::Changes => self.changes,
+ CounterKind::Rises => self.rises,
+ CounterKind::Falls => self.falls,
+ }
+ }
+
+ /// The present counters and their kinds.
+ pub fn counters(&self) -> impl Iterator- + '_ {
+ CounterKind::ALL
+ .into_iter()
+ .filter_map(|kind| Some((kind, self.counter(kind)?)))
+ }
+
+ pub fn map(&self, mut map: impl FnMut(A) -> B) -> EventWatch {
+ EventWatch {
+ signal: map(self.signal),
+ width: self.width,
+ four_state: self.four_state,
+ changes: self.changes.map(&mut map),
+ rises: self.rises.map(&mut map),
+ falls: self.falls.map(&mut map),
+ domains: self
+ .domains
+ .iter()
+ .map(|&(event, kind)| (map(event), kind))
+ .collect(),
+ }
+ }
+}
+
+/// Counter objects a frontend declares for a signal that one of its units
+/// may store twice between two runtime checks. Assembly turns them into an
+/// [`EventWatch`] only if something watches the signal.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct CounterSlots {
+ pub signal: A,
+ pub changes: A,
+ pub rises: A,
+ pub falls: A,
+}
+
+impl CounterSlots {
+ pub fn counter(&self, kind: CounterKind) -> A {
+ match kind {
+ CounterKind::Changes => self.changes,
+ CounterKind::Rises => self.rises,
+ CounterKind::Falls => self.falls,
+ }
+ }
+
+ pub fn map(self, mut map: impl FnMut(A) -> B) -> CounterSlots {
+ CounterSlots {
+ signal: map(self.signal),
+ changes: map(self.changes),
+ rises: map(self.rises),
+ falls: map(self.falls),
+ }
+ }
+}
+
+/// An event or level wait of a process kernel. A kernel suspended with
+/// [`ProcessStatus::Wait`] stores the index of the site among its process's
+/// sites in its delay slot.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct WaitSite {
+ /// Index of the process in [`RuntimeSchema::processes`].
+ pub process: usize,
+ /// Occurrences that may satisfy the wait. The runtime resumes the
+ /// process at the first one after the wait began; a site whose kernel
+ /// checks a condition at its resume point decides itself whether it
+ /// continues.
+ pub terms: Vec<(A, CounterKind)>,
+}
+
+impl WaitSite {
+ pub fn map(&self, mut map: impl FnMut(A) -> B) -> WaitSite {
+ WaitSite {
+ process: self.process,
+ terms: self
+ .terms
+ .iter()
+ .map(|&(signal, kind)| (map(signal), kind))
+ .collect(),
+ }
+ }
+}
+
+/// A nonblocking assignment of a process kernel. A kernel that returns
+/// [`ProcessStatus::Nba`] stores the index of the site among its process's
+/// sites in its delay slot.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+pub struct NbaSite {
+ /// Index of the process in [`RuntimeSchema::processes`].
+ pub process: usize,
+ /// The assigned object and the static part of the assigned bit range.
+ pub target: A,
+ pub lsb: usize,
+ pub width: usize,
+ /// Staging object of `width` bits holding the assigned value, with the
+ /// target's state representation.
+ pub value: A,
+ /// Two-state staging object holding a bit offset added to `lsb`, for an
+ /// assignment whose position is computed at run time.
+ pub offset: Option,
+ /// One-bit flag of a site whose destination receives no other
+ /// nonblocking assignment: a variable of the module with no other
+ /// nonblocking site in the module and no writer outside it (not a port,
+ /// not bound to a package variable, not the target of a hierarchical
+ /// reference). A frontend that cannot tell leaves it `None`, so the
+ /// assignment goes through the ordered queue.
+ ///
+ /// The kernel stages the value and sets the flag without returning;
+ /// publication commits flagged sites and clears the flags. A kernel
+ /// reaching the site again while the flag is set returns
+ /// [`ProcessStatus::Nba`] first, so the runtime queues the staged value.
+ pub pending: Option,
+}
+
+impl NbaSite {
+ pub fn map(&self, mut map: impl FnMut(A) -> B) -> NbaSite {
+ NbaSite {
+ process: self.process,
+ target: map(self.target),
+ lsb: self.lsb,
+ width: self.width,
+ value: map(self.value),
+ offset: self.offset.map(&mut map),
+ pending: self.pending.map(&mut map),
+ }
+ }
+}
+
/// Controls which combinational stores dead store elimination preserves.
///
/// The policy is part of the runtime contract: host-side handles resolve
@@ -325,6 +540,14 @@ pub struct RuntimeSchema {
pub live_signals: HashSet,
/// Control slots of the process kernels, in kernel order.
pub processes: Vec>,
+ /// Counted signals and their occurrence counters.
+ pub watches: Vec>,
+ /// Wait sites of the process kernels. A process's sites appear in the
+ /// order of its local site indices.
+ pub wait_sites: Vec>,
+ /// Nonblocking assignment sites of the process kernels, ordered like
+ /// `wait_sites`.
+ pub nba_sites: Vec>,
}
impl Default for RuntimeSchema {
@@ -341,6 +564,9 @@ impl Default for RuntimeSchema {
dead_store_policy: DeadStorePolicy::Off,
live_signals: HashSet::default(),
processes: Vec::new(),
+ watches: Vec::new(),
+ wait_sites: Vec::new(),
+ nba_sites: Vec::new(),
}
}
}
diff --git a/crates/celox-frontend-core/src/lib.rs b/crates/celox-frontend-core/src/lib.rs
index 0594d9fe192..05e833c6575 100644
--- a/crates/celox-frontend-core/src/lib.rs
+++ b/crates/celox-frontend-core/src/lib.rs
@@ -7,6 +7,7 @@ mod sdk;
pub mod shared;
pub mod symbolic;
mod trace;
+pub mod watch;
pub use error::{LoweringPhase, ParserError, SourceLocation};
pub use sdk::{FrontendArtifactError, LoweredFrontendArtifact, lower_frontend_artifact};
diff --git a/crates/celox-frontend-core/src/process.rs b/crates/celox-frontend-core/src/process.rs
index 4dd6aac955a..8b7b42e9480 100644
--- a/crates/celox-frontend-core/src/process.rs
+++ b/crates/celox-frontend-core/src/process.rs
@@ -6,13 +6,23 @@
//! suspension stores the next resume point, a [`ProcessStatus`] and its wait
//! amount into the process's control slots and returns to the runtime.
//!
+//! A delay resumes after a time. An event or level wait resumes at the first
+//! occurrence of one of the terms of its [`WaitSite`] after the wait began.
+//! A level wait, or an event control on an expression, checks its condition
+//! at the resume point and either continues or reports
+//! [`ProcessStatus::Pending`].
+//!
//! The builder is source-independent: a frontend lowers statements and
//! expressions into [`ProcessKernelBuilder::builder`] and calls the
-//! suspension methods where the source suspends.
+//! suspension methods where the source suspends. Wait and nonblocking
+//! sites are numbered per process, in the order the frontend lists them in
+//! the module's metadata.
+//!
+//! [`WaitSite`]: celox_design::WaitSite
use celox_design::{
- PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, ProcessStatus, RegionedVarAddrBase,
- STABLE_REGION,
+ NbaSite, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, ProcessSlots, ProcessStatus,
+ RegionedVarAddrBase, STABLE_REGION,
};
use celox_sir::{
BlockId, ExecutionUnit, RegisterId, SIRBuilder, SIRInstruction, SIROffset, SIRSwitchCase,
@@ -40,12 +50,18 @@ pub enum ProcessKernelError {
TooManySuspensions,
}
+/// Width of the bit offset staged by a nonblocking assignment whose position
+/// is computed at run time ([`NbaSite::offset`]).
+pub const NBA_OFFSET_WIDTH: usize = 64;
+
/// Builder of one process kernel.
pub struct ProcessKernelBuilder {
builder: SIRBuilder,
slots: ProcessSlots,
/// The block each resume point continues in; point 0 is the start.
resume_blocks: Vec,
+ /// The wait site whose resume point is being lowered.
+ wait_site: Option,
}
impl ProcessKernelBuilder {
@@ -58,6 +74,7 @@ impl ProcessKernelBuilder {
builder,
slots,
resume_blocks: vec![start],
+ wait_site: None,
}
}
@@ -95,25 +112,167 @@ impl ProcessKernelBuilder {
self.builder.seal_block(SIRTerminator::Return);
}
- /// Suspend for the number of time units in `amount`, an unsigned
- /// two-state register of [`PROCESS_DELAY_WIDTH`] bits, and continue at
- /// a new resume point.
- pub fn delay(&mut self, amount: RegisterId) -> Result<(), ProcessKernelError> {
+ /// Store `value` into the delay slot.
+ fn store_delay_constant(&mut self, value: u64) {
+ self.store_constant(self.slots.delay, PROCESS_DELAY_WIDTH, value);
+ }
+
+ /// Store the next resume point, return with `status` and continue in a
+ /// new block at that point.
+ fn suspend(&mut self, status: ProcessStatus) -> Result<(), ProcessKernelError> {
let point = self.resume_blocks.len();
if point > MAX_PROCESS_SUSPENSIONS {
return Err(ProcessKernelError::TooManySuspensions);
}
- self.store(self.slots.delay, PROCESS_DELAY_WIDTH, amount);
self.store_constant(self.slots.resume, PROCESS_RESUME_WIDTH, point as u64);
- self.end(ProcessStatus::Delay);
+ self.end(status);
let resume = self.builder.new_block();
self.resume_blocks.push(resume);
self.builder.switch_to_block(resume);
Ok(())
}
+ /// Suspend for the number of time units in `amount`, an unsigned
+ /// two-state register of [`PROCESS_DELAY_WIDTH`] bits, and continue at
+ /// a new resume point. A zero delay resumes after the nonblocking
+ /// assignments of the time are published.
+ pub fn delay(&mut self, amount: RegisterId) -> Result<(), ProcessKernelError> {
+ self.store(self.slots.delay, PROCESS_DELAY_WIDTH, amount);
+ self.suspend(ProcessStatus::Delay)
+ }
+
+ /// A delay with the scheduling of IEEE 1800-2023: a zero delay resumes
+ /// in the inactive region of the same time (4.4.2.3), before
+ /// nonblocking assignments are published.
+ pub fn inactive_delay(&mut self, amount: RegisterId) -> Result<(), ProcessKernelError> {
+ self.store(self.slots.delay, PROCESS_DELAY_WIDTH, amount);
+ self.suspend(ProcessStatus::InactiveDelay)
+ }
+
+ /// Return to the runtime, which charges its time-slot budget and
+ /// resumes the process at once. Frontends place this in loops without
+ /// timing controls so that a runaway process is reported, not hung in.
+ pub fn yield_now(&mut self) -> Result<(), ProcessKernelError> {
+ self.suspend(ProcessStatus::Yield)
+ }
+
+ /// Suspend at wait site `site` of this process. The open block
+ /// afterwards is the site's resume point: the caller lowers the wait's
+ /// condition there and ends it with [`Self::wake_if`].
+ 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);
+ Ok(())
+ }
+
+ /// At the resume point of a [`Self::suspend_wait`]: continue when
+ /// `condition`, a one-bit two-state register, holds; otherwise report
+ /// 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 woken = self.builder.new_block();
+ let pending = self.builder.new_block();
+ self.builder.seal_block(SIRTerminator::Branch {
+ cond: condition,
+ true_block: (woken, Vec::new()),
+ false_block: (pending, Vec::new()),
+ });
+ self.builder.switch_to_block(pending);
+ self.store_delay_constant(u64::from(site));
+ self.end(ProcessStatus::Pending);
+ self.builder.switch_to_block(woken);
+ }
+
+ /// `wait (condition)` (IEEE 1800-2023 9.4.3) at wait site `site`:
+ /// `predicate` lowers the condition to a one-bit two-state register at
+ /// the open block. It is evaluated once before suspending, so a
+ /// condition that already holds does not suspend, and again whenever
+ /// the process is resumed.
+ pub fn wait_level(
+ &mut self,
+ site: u32,
+ mut predicate: impl FnMut(&mut SIRBuilder) -> RegisterId,
+ ) -> Result<(), ProcessKernelError> {
+ let holds = predicate(&mut self.builder);
+ let join = self.builder.new_block();
+ let wait = self.builder.new_block();
+ self.builder.seal_block(SIRTerminator::Branch {
+ cond: holds,
+ true_block: (join, Vec::new()),
+ false_block: (wait, Vec::new()),
+ });
+ self.builder.switch_to_block(wait);
+ self.suspend_wait(site)?;
+ let holds = predicate(&mut self.builder);
+ self.wake_if(holds);
+ self.builder
+ .seal_block(SIRTerminator::Jump(join, Vec::new()));
+ self.builder.switch_to_block(join);
+ Ok(())
+ }
+
+ /// The nonblocking assignment of nonblocking site `index` of this
+ /// process, described by `site`: schedule a value for the NBA region of
+ /// the current time (IEEE 1800-2023 10.4.2). `lower` lowers the
+ /// right-hand side at the open block and returns the value, a register
+ /// of `site.width` bits, and for a site with a run-time position the
+ /// bit offset, an unsigned two-state register of [`NBA_OFFSET_WIDTH`]
+ /// bits.
+ ///
+ /// A site with a `pending` flag stages the value without returning. If
+ /// the flag is still set from an earlier execution in the same time
+ /// slot, the kernel first returns [`ProcessStatus::Nba`] so the runtime
+ /// queues the earlier value, and evaluates the right-hand side only
+ /// after that.
+ pub fn nonblocking>(
+ &mut self,
+ index: u32,
+ site: &NbaSite,
+ lower: impl FnOnce(
+ &mut SIRBuilder,
+ ) -> Result<(RegisterId, Option), E>,
+ ) -> Result<(), E> {
+ if let Some(pending) = site.pending {
+ let flag = self.builder.alloc_bit(1, false);
+ self.builder.emit(SIRInstruction::Load(
+ flag,
+ stable(pending),
+ SIROffset::Static(0),
+ 1,
+ ));
+ let flush = self.builder.new_block();
+ let stage = self.builder.new_block();
+ self.builder.seal_block(SIRTerminator::Branch {
+ cond: flag,
+ true_block: (flush, Vec::new()),
+ false_block: (stage, Vec::new()),
+ });
+ self.builder.switch_to_block(flush);
+ self.store_delay_constant(u64::from(index));
+ self.suspend(ProcessStatus::Nba)?;
+ self.builder
+ .seal_block(SIRTerminator::Jump(stage, Vec::new()));
+ self.builder.switch_to_block(stage);
+ }
+ let (value, offset) = lower(&mut self.builder)?;
+ self.store(site.value, site.width, value);
+ if let (Some(slot), Some(offset)) = (site.offset, offset) {
+ self.store(slot, NBA_OFFSET_WIDTH, offset);
+ }
+ if let Some(pending) = site.pending {
+ self.store_constant(pending, 1, 1);
+ return Ok(());
+ }
+ self.store_delay_constant(u64::from(index));
+ self.suspend(ProcessStatus::Nba)?;
+ Ok(())
+ }
+
/// End the simulation. No block is open afterwards.
pub fn finish(&mut self) {
+ self.wait_site = None;
self.end(ProcessStatus::Finish);
}
diff --git a/crates/celox-frontend-core/src/sdk.rs b/crates/celox-frontend-core/src/sdk.rs
index 9ee5423d4bf..a73e773440e 100644
--- a/crates/celox-frontend-core/src/sdk.rs
+++ b/crates/celox-frontend-core/src/sdk.rs
@@ -1,13 +1,14 @@
//! Projection from the stable frontend SDK into Celox symbolic internals.
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,
+ BinaryOp, BitAccess, CounterKind, DomainKind, InitialStateData, InitialStateValue, ModuleId,
+ NbaSite, PROCESS_DELAY_WIDTH, PROCESS_STATUS_WIDTH, PortTypeKind, ProcessSlots,
+ RegionedVarAddrBase, STABLE_REGION, TriggerSet, UnaryOp, VarAtomBase, VariableMetadata,
+ WORKING_REGION, WaitSite,
};
use celox_frontend_sdk::{
- ActiveLevel, Direction, Edge, ExprId, ExprNode, FrontendArtifact, SignalId, SignalSlice,
- Statement, ValueType,
+ ActiveLevel, Direction, Edge, EventEdge, ExprId, ExprNode, FrontendArtifact, SignalId,
+ SignalSlice, Statement, ValueType,
};
use celox_sir::{
BlockId, ExecutionUnit, RegisterId, SIRBuilder, SIRInstruction, SIROffset, SIRTerminator,
@@ -1029,34 +1030,222 @@ fn lower_registers(
Ok(())
}
+/// Hidden state objects the lowering declares after the artifact's signals:
+/// process control slots, counters, staging and gate objects. None of them
+/// is a signal of the design.
+struct HiddenObjects<'a> {
+ next_id: u32,
+ variables: &'a mut HashMap,
+}
+
+impl HiddenObjects<'_> {
+ fn declare(&mut self, path: Vec, width: usize, four_state: bool) -> SourceVarId {
+ let id = SourceVarId(self.next_id);
+ self.next_id += 1;
+ self.variables.insert(
+ id,
+ SymbolicVariable {
+ path,
+ kind: VariableKind::Variable,
+ signed: false,
+ metadata: VariableMetadata {
+ width,
+ is_4state: four_state,
+ kind: DomainKind::Other,
+ type_kind: if four_state {
+ PortTypeKind::Logic
+ } else {
+ PortTypeKind::Bit
+ },
+ array_dims: Vec::new(),
+ },
+ packed_dims: vec![width],
+ source: None,
+ module_affiliated: false,
+ },
+ );
+ id
+ }
+}
+
+/// Timing metadata collected while lowering the processes of an artifact.
+struct ProcessLowering<'a, 'h> {
+ artifact: &'a FrontendArtifact,
+ hidden: &'a mut HiddenObjects<'h>,
+ wait_sites: Vec>,
+ nba_sites: Vec>,
+ /// Signals that exactly one nonblocking statement of the artifact
+ /// assigns. An artifact is one flat module whose processes never run
+ /// inside another design, so nothing outside it writes its signals and
+ /// these sites stage a single pending value.
+ single_nba_targets: HashSet,
+ process: usize,
+ process_wait_sites: u32,
+ process_nba_sites: u32,
+ /// Loops given an iteration counter so far.
+ counted_loops: usize,
+}
+
+fn collect_nonblocking_targets(statements: &[Statement], targets: &mut Vec) {
+ for statement in statements {
+ match statement {
+ Statement::Nonblocking { target, .. } => targets.push(target.signal()),
+ Statement::If {
+ then_body,
+ else_body,
+ ..
+ } => {
+ collect_nonblocking_targets(then_body, targets);
+ collect_nonblocking_targets(else_body, targets);
+ }
+ Statement::While { body, .. } | Statement::Forever { body } => {
+ collect_nonblocking_targets(body, targets);
+ }
+ _ => {}
+ }
+ }
+}
+
+/// A one-bit two-state register that holds when `condition` is nonzero: some
+/// bit is a known one.
+fn truth(
+ artifact: &FrontendArtifact,
+ condition: ExprId,
+ builder: &mut SIRBuilder,
+) -> Result {
+ let value_type = artifact
+ .expression(condition)
+ .ok_or(FrontendArtifactError::UnknownExpression(condition.index()))?
+ .value_type();
+ let value = lower_sir_expression(artifact, condition, builder, &mut HashMap::default())?;
+ let any = alloc_register(
+ builder,
+ ValueType::new(1, false, value_type.is_four_state())?,
+ );
+ builder.emit(SIRInstruction::Unary(any, UnaryOp::Or, value));
+ if !value_type.is_four_state() {
+ return Ok(any);
+ }
+ let known = builder.alloc_bit(1, false);
+ builder.emit(SIRInstruction::Unary(known, UnaryOp::ToTwoState, any));
+ Ok(known)
+}
+
+fn store_assignment(
+ artifact: &FrontendArtifact,
+ builder: &mut SIRBuilder,
+ target: SignalSlice,
+ value: ExprId,
+ cache: &mut HashMap,
+) -> Result<(), FrontendArtifactError> {
+ let target_type = signal_slice_type(artifact, target)?;
+ let value = coerce_sir_expression(artifact, value, target_type, builder, cache)?;
+ builder.emit(SIRInstruction::Store(
+ RegionedSourceAddr {
+ region: STABLE_REGION,
+ var_id: source_id(target.signal()),
+ },
+ SIROffset::Static(target.lsb()),
+ target.width(),
+ value,
+ Vec::new(),
+ Vec::new(),
+ ));
+ Ok(())
+}
+
/// Lower `statements` at the kernel's open block. Returns whether control
/// can continue after them; if not, no block is left open.
+/// Whether `statements` always suspend the process: a loop around them
+/// returns to the runtime in each iteration. A level wait whose condition
+/// holds does not suspend.
+fn always_suspends(statements: &[Statement]) -> bool {
+ statements.iter().any(|statement| {
+ matches!(
+ statement,
+ Statement::Delay { .. } | Statement::InactiveDelay { .. } | Statement::WaitEvent { .. }
+ )
+ })
+}
+
+/// Iterations, as a power of two, between the yields of a loop that may not
+/// suspend. A finite loop pays one counter update per iteration, and only a
+/// loop of about 2^40 iterations in one time slot exhausts the runtime's
+/// return budget.
+const LOOP_YIELD_BITS: usize = 16;
+
+/// Close a loop iteration that may not suspend: count it, yield every
+/// 2^[`LOOP_YIELD_BITS`] iterations, and continue at `header`. The count
+/// lives in a hidden object, so it survives the yield.
+fn yield_now_and_then(
+ lowering: &mut ProcessLowering<'_, '_>,
+ kernel: &mut ProcessKernelBuilder,
+ header: BlockId,
+) -> Result<(), FrontendArtifactError> {
+ let counter = stable(lowering.hidden.declare(
+ vec![
+ format!("$loop[{}]", lowering.counted_loops),
+ "iterations".to_string(),
+ ],
+ LOOP_YIELD_BITS,
+ false,
+ ));
+ lowering.counted_loops += 1;
+ let builder = kernel.builder();
+ let count = builder.alloc_bit(LOOP_YIELD_BITS, false);
+ builder.emit(SIRInstruction::Load(
+ count,
+ counter,
+ SIROffset::Static(0),
+ LOOP_YIELD_BITS,
+ ));
+ let one = builder.alloc_bit(LOOP_YIELD_BITS, false);
+ builder.emit(SIRInstruction::Imm(one, SIRValue::new(1u8)));
+ let next = builder.alloc_bit(LOOP_YIELD_BITS, false);
+ builder.emit(SIRInstruction::Binary(next, count, BinaryOp::Add, one));
+ builder.emit(SIRInstruction::Store(
+ counter,
+ SIROffset::Static(0),
+ LOOP_YIELD_BITS,
+ next,
+ Vec::new(),
+ Vec::new(),
+ ));
+ let zero = builder.alloc_bit(LOOP_YIELD_BITS, false);
+ builder.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8)));
+ let wrapped = builder.alloc_bit(1, false);
+ builder.emit(SIRInstruction::Binary(wrapped, next, BinaryOp::Eq, zero));
+ let yield_block = builder.new_block();
+ builder.seal_block(SIRTerminator::Branch {
+ cond: wrapped,
+ true_block: (yield_block, Vec::new()),
+ false_block: (header, Vec::new()),
+ });
+ builder.switch_to_block(yield_block);
+ kernel.yield_now()?;
+ kernel
+ .builder()
+ .seal_block(SIRTerminator::Jump(header, Vec::new()));
+ Ok(())
+}
+
+/// Lower `statements` into `kernel`. A loop whose body may not suspend
+/// yields every 2^[`LOOP_YIELD_BITS`] iterations, so that the runtime
+/// charges it against the time slot's budget instead of spinning in the
+/// kernel.
fn lower_statements(
- artifact: &FrontendArtifact,
+ lowering: &mut ProcessLowering<'_, '_>,
kernel: &mut ProcessKernelBuilder,
statements: &[Statement],
) -> Result {
+ let artifact = lowering.artifact;
for statement in statements {
// Registers do not live across statements: a suspension in between
// returns to the runtime, and each read must see the current state.
let mut cache = HashMap::default();
match statement {
Statement::Assign { target, value } => {
- let target_type = signal_slice_type(artifact, *target)?;
- let builder = kernel.builder();
- let value =
- coerce_sir_expression(artifact, *value, target_type, builder, &mut cache)?;
- builder.emit(SIRInstruction::Store(
- RegionedSourceAddr {
- region: STABLE_REGION,
- var_id: source_id(target.signal()),
- },
- SIROffset::Static(target.lsb()),
- target.width(),
- value,
- Vec::new(),
- Vec::new(),
- ));
+ store_assignment(artifact, kernel.builder(), *target, *value, &mut cache)?;
}
Statement::If {
condition,
@@ -1075,7 +1264,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(lowering, kernel, body)? {
let builder = kernel.builder();
let target = *join.get_or_insert_with(|| builder.new_block());
builder.seal_block(SIRTerminator::Jump(target, Vec::new()));
@@ -1100,10 +1289,14 @@ fn lower_statements(
false_block: (exit, Vec::new()),
});
builder.switch_to_block(body_block);
- if lower_statements(artifact, kernel, body)? {
- kernel
- .builder()
- .seal_block(SIRTerminator::Jump(header, Vec::new()));
+ if lower_statements(lowering, kernel, body)? {
+ if always_suspends(body) {
+ kernel
+ .builder()
+ .seal_block(SIRTerminator::Jump(header, Vec::new()));
+ } else {
+ yield_now_and_then(lowering, kernel, header)?;
+ }
}
kernel.builder().switch_to_block(exit);
}
@@ -1112,14 +1305,18 @@ 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)? {
- kernel
- .builder()
- .seal_block(SIRTerminator::Jump(header, Vec::new()));
+ if lower_statements(lowering, kernel, body)? {
+ if always_suspends(body) {
+ kernel
+ .builder()
+ .seal_block(SIRTerminator::Jump(header, Vec::new()));
+ } else {
+ yield_now_and_then(lowering, kernel, header)?;
+ }
}
return Ok(false);
}
- Statement::Delay { amount } => {
+ Statement::Delay { amount } | Statement::InactiveDelay { amount } => {
let amount = coerce_sir_expression(
artifact,
*amount,
@@ -1127,7 +1324,101 @@ fn lower_statements(
kernel.builder(),
&mut cache,
)?;
- kernel.delay(amount)?;
+ if matches!(statement, Statement::Delay { .. }) {
+ kernel.delay(amount)?;
+ } else {
+ kernel.inactive_delay(amount)?;
+ }
+ }
+ Statement::WaitEvent { terms } => {
+ let index = lowering.process_wait_sites;
+ lowering.process_wait_sites += 1;
+ lowering.wait_sites.push(WaitSite {
+ process: lowering.process,
+ terms: terms
+ .iter()
+ .map(|term| {
+ let kind = match term.edge {
+ EventEdge::Change => CounterKind::Changes,
+ EventEdge::Posedge => CounterKind::Rises,
+ EventEdge::Negedge => CounterKind::Falls,
+ };
+ (source_id(term.signal), kind)
+ })
+ .collect(),
+ });
+ // The runtime resumes the process at the first occurrence
+ // after the wait began; no condition is left to check.
+ kernel.suspend_wait(index)?;
+ let woken = kernel.builder().alloc_bit(1, false);
+ kernel
+ .builder()
+ .emit(SIRInstruction::Imm(woken, SIRValue::new(1u8)));
+ kernel.wake_if(woken);
+ }
+ Statement::WaitLevel { condition } => {
+ let index = lowering.process_wait_sites;
+ lowering.process_wait_sites += 1;
+ let mut sources = HashSet::default();
+ expression_sources(artifact, *condition, &mut sources, &mut HashSet::default())?;
+ let mut signals = sources.into_iter().map(|atom| atom.id).collect::>();
+ signals.sort_unstable();
+ signals.dedup();
+ lowering.wait_sites.push(WaitSite {
+ process: lowering.process,
+ terms: signals
+ .into_iter()
+ .map(|signal| (signal, CounterKind::Changes))
+ .collect(),
+ });
+ let mut error = None;
+ kernel.wait_level(index, |builder| {
+ truth(artifact, *condition, builder).unwrap_or_else(|e| {
+ error = Some(e);
+ let never = builder.alloc_bit(1, false);
+ builder.emit(SIRInstruction::Imm(never, SIRValue::new(0u8)));
+ never
+ })
+ })?;
+ if let Some(error) = error {
+ return Err(error);
+ }
+ }
+ Statement::Nonblocking { target, value } => {
+ let index = lowering.process_nba_sites;
+ lowering.process_nba_sites += 1;
+ let target_type = signal_slice_type(artifact, *target)?;
+ let site_index = lowering.nba_sites.len();
+ let name = |slot: &str| vec![format!("$nba[{site_index}]"), slot.to_string()];
+ let staged = lowering.hidden.declare(
+ name("value"),
+ target.width(),
+ target_type.is_four_state(),
+ );
+ let pending = lowering
+ .single_nba_targets
+ .contains(&target.signal())
+ .then(|| lowering.hidden.declare(name("pending"), 1, false));
+ let site = NbaSite {
+ process: lowering.process,
+ target: source_id(target.signal()),
+ lsb: target.lsb(),
+ width: target.width(),
+ value: staged,
+ offset: None,
+ pending,
+ };
+ kernel.nonblocking(index, &site, |builder| {
+ let value = coerce_sir_expression(
+ artifact,
+ *value,
+ target_type,
+ builder,
+ &mut HashMap::default(),
+ )?;
+ Ok::<_, FrontendArtifactError>((value, None))
+ })?;
+ lowering.nba_sites.push(site);
}
Statement::Finish => {
kernel.finish();
@@ -1139,56 +1430,308 @@ fn lower_statements(
Ok(true)
}
+/// Lower the statements of a combinational process: assignments and
+/// conditionals, writing stable state as they execute.
+fn lower_comb_statements(
+ artifact: &FrontendArtifact,
+ builder: &mut SIRBuilder,
+ statements: &[Statement],
+) -> Result<(), FrontendArtifactError> {
+ for statement in statements {
+ let mut cache = HashMap::default();
+ match statement {
+ Statement::Assign { target, value } => {
+ store_assignment(artifact, builder, *target, *value, &mut cache)?;
+ }
+ Statement::If {
+ condition,
+ then_body,
+ else_body,
+ } => {
+ let condition = lower_sir_expression(artifact, *condition, builder, &mut cache)?;
+ let then_block = builder.new_block();
+ let else_block = builder.new_block();
+ let join = builder.new_block();
+ builder.seal_block(SIRTerminator::Branch {
+ cond: condition,
+ true_block: (then_block, Vec::new()),
+ false_block: (else_block, Vec::new()),
+ });
+ for (block, body) in [(then_block, then_body), (else_block, else_body)] {
+ builder.switch_to_block(block);
+ lower_comb_statements(artifact, builder, body)?;
+ builder.seal_block(SIRTerminator::Jump(join, Vec::new()));
+ }
+ builder.switch_to_block(join);
+ }
+ _ => return Err(FrontendArtifactError::UnsupportedOperation),
+ }
+ }
+ Ok(())
+}
+
+/// The bits of `atom` outside every range of `written`.
+fn unwritten_bits(
+ atom: VarAtomBase,
+ written: &[VarAtomBase],
+) -> Vec> {
+ let mut ranges = vec![(atom.access.lsb, atom.access.msb)];
+ for written in written.iter().filter(|written| written.id == atom.id) {
+ ranges = ranges
+ .into_iter()
+ .flat_map(|(lsb, msb)| {
+ if written.access.msb < lsb || written.access.lsb > msb {
+ return vec![(lsb, msb)];
+ }
+ let mut kept = Vec::new();
+ if lsb < written.access.lsb {
+ kept.push((lsb, written.access.lsb - 1));
+ }
+ if written.access.msb < msb {
+ kept.push((written.access.msb + 1, msb));
+ }
+ kept
+ })
+ .collect();
+ }
+ ranges
+ .into_iter()
+ .map(|(lsb, msb)| VarAtomBase::new(atom.id, lsb, msb))
+ .collect()
+}
+
+fn statement_sources(
+ artifact: &FrontendArtifact,
+ statements: &[Statement],
+ sources: &mut HashSet>,
+) -> Result<(), FrontendArtifactError> {
+ for statement in statements {
+ let mut visited = HashSet::default();
+ match statement {
+ Statement::Assign { value, .. } => {
+ expression_sources(artifact, *value, sources, &mut visited)?
+ }
+ Statement::If {
+ condition,
+ then_body,
+ else_body,
+ } => {
+ expression_sources(artifact, *condition, sources, &mut visited)?;
+ statement_sources(artifact, then_body, sources)?;
+ statement_sources(artifact, else_body, sources)?;
+ }
+ _ => return Err(FrontendArtifactError::UnsupportedOperation),
+ }
+ }
+ Ok(())
+}
+
+fn stable(var_id: SourceVarId) -> RegionedSourceAddr {
+ RegionedSourceAddr {
+ region: STABLE_REGION,
+ var_id,
+ }
+}
+
+fn stable_signal(address: &RegionedSourceAddr, signals: usize) -> Option {
+ (address.region == STABLE_REGION && (address.var_id.0 as usize) < signals)
+ .then_some(address.var_id)
+}
+
+/// Lower each combinational process to one unit that runs only when it has
+/// not run yet or bits it reads and does not write changed (IEEE 1800-2023
+/// 9.2.2.2, 9.2.2.2.1), and to a path for each slice it assigns.
+fn lower_comb_processes(
+ artifact: &FrontendArtifact,
+ hidden: &mut HiddenObjects<'_>,
+ arena: &mut SLTNodeArena,
+ candidates: &mut Vec,
+) -> Result>, FrontendArtifactError> {
+ let mut paths = Vec::new();
+ for (index, process) in artifact.comb_processes().iter().enumerate() {
+ let mut builder = SIRBuilder::new();
+ lower_comb_statements(artifact, &mut builder, process.body())?;
+ let body = seal_builder(builder);
+ candidates.extend(crate::watch::multi_store_candidates(&body, |address| {
+ stable_signal(address, artifact.signals().len())
+ }));
+
+ let mut targets = Vec::new();
+ for block in body.blocks.values() {
+ for instruction in &block.instructions {
+ if let SIRInstruction::Store(address, SIROffset::Static(lsb), width, ..) =
+ instruction
+ {
+ let atom = VarAtomBase::new(address.var_id, *lsb, lsb + width - 1);
+ if !targets.contains(&atom) {
+ targets.push(atom);
+ }
+ }
+ }
+ }
+ targets.sort_unstable_by_key(|atom| (atom.id, atom.access.lsb, atom.access.msb));
+ // One path per range the process drives, however often it writes it.
+ let mut merged: Vec> = Vec::new();
+ for target in targets {
+ match merged.last_mut() {
+ Some(last) if last.id == target.id && target.access.lsb <= last.access.msb + 1 => {
+ last.access.msb = last.access.msb.max(target.access.msb);
+ }
+ _ => merged.push(target),
+ }
+ }
+ let targets = merged;
+ // A process is not sensitive to what it writes (IEEE 1800-2023
+ // 9.2.2.2.1): its inputs are the bits it reads outside its targets.
+ let mut reads = HashSet::default();
+ statement_sources(artifact, process.body(), &mut reads)?;
+ let mut sources: Vec> = reads
+ .into_iter()
+ .flat_map(|atom| unwritten_bits(atom, &targets))
+ .collect();
+ sources.sort_unstable_by_key(|atom| (atom.id, atom.access.lsb, atom.access.msb));
+ let mut merged: Vec> = Vec::new();
+ for source in sources {
+ match merged.last_mut() {
+ Some(last) if last.id == source.id && source.access.lsb <= last.access.msb + 1 => {
+ last.access.msb = last.access.msb.max(source.access.msb);
+ }
+ _ => merged.push(source),
+ }
+ }
+ let sources = merged;
+ let name = |slot: String| vec![format!("$comb[{index}]"), slot];
+ let gate_inputs = sources
+ .iter()
+ .map(|atom| {
+ let value_type = artifact
+ .signals()
+ .get(atom.id.0 as usize)
+ .ok_or(FrontendArtifactError::UnknownSignal(atom.id.0))?
+ .value_type();
+ let width = atom.access.msb - atom.access.lsb + 1;
+ Ok(crate::watch::GateInput {
+ input: stable(atom.id),
+ lsb: atom.access.lsb,
+ shadow: stable(hidden.declare(
+ name(format!(
+ "input[{}][{}:{}]",
+ atom.id.0, atom.access.msb, atom.access.lsb
+ )),
+ width,
+ value_type.is_four_state(),
+ )),
+ width,
+ four_state: value_type.is_four_state(),
+ })
+ })
+ .collect::, FrontendArtifactError>>()?;
+ let ran = hidden.declare(name("ran".to_string()), 1, false);
+ let unit = crate::watch::gate_on_input_change(&body, &gate_inputs, &stable(ran))
+ .into_map_addr(&mut |address| address.var_id);
+ let sources: HashSet<_> = sources.into_iter().collect();
+ for target in targets {
+ let expr = arena.alloc(SLTNode::Input {
+ variable: target.id,
+ signed: false,
+ index: Vec::new(),
+ access: target.access,
+ })?;
+ paths.push(LogicPath {
+ target: LogicPathTarget::Process {
+ process: ran,
+ after_initials: true,
+ target,
+ unit: Box::new(unit.clone()),
+ },
+ sources: sources.clone(),
+ previous_sources: HashSet::default(),
+ address_sources: HashSet::default(),
+ local_inputs: Vec::new(),
+ order_before: HashSet::default(),
+ comb_capture_enable_sites: Vec::new(),
+ comb_capture_enable_always: false,
+ pre_lower_nodes: Vec::new(),
+ expr,
+ });
+ }
+ }
+ Ok(paths)
+}
+
+/// Lowered processes of an artifact and their timing metadata.
+struct LoweredProcesses {
+ processes: Vec,
+ wait_sites: Vec>,
+ nba_sites: Vec>,
+}
+
/// Declare the control slots of every process after the artifact's signals
/// and lower each process body to a kernel.
fn lower_processes(
artifact: &FrontendArtifact,
- variables: &mut HashMap,
-) -> Result, FrontendArtifactError> {
- let mut next_id = artifact.signals().len() as u32;
- let mut declare = |path: Vec, width: usize| {
- let id = SourceVarId(next_id);
- next_id += 1;
- variables.insert(
- id,
- SymbolicVariable {
- path,
- kind: VariableKind::Variable,
- signed: false,
- metadata: VariableMetadata {
- width,
- is_4state: false,
- kind: DomainKind::Other,
- type_kind: PortTypeKind::Bit,
- array_dims: Vec::new(),
- },
- packed_dims: vec![width],
- source: None,
- // Control slots are not signals of the design.
- module_affiliated: false,
- },
- );
- id
- };
- artifact
- .processes()
- .iter()
- .enumerate()
- .map(|(index, process)| {
- let name = |slot: &str| vec![format!("$process[{index}]"), slot.to_string()];
- let slots = ProcessSlots {
- resume: declare(name("resume"), PROCESS_RESUME_WIDTH),
- status: declare(name("status"), PROCESS_STATUS_WIDTH),
- delay: declare(name("delay"), PROCESS_DELAY_WIDTH),
- };
- let mut kernel = ProcessKernelBuilder::new(slots);
- lower_statements(artifact, &mut kernel, process.body())?;
- Ok(SymbolicProcess {
- kernel: kernel.build(),
- slots,
+ hidden: &mut HiddenObjects<'_>,
+ candidates: &mut Vec,
+) -> Result {
+ let mut nonblocking_targets = Vec::new();
+ for process in artifact.processes() {
+ collect_nonblocking_targets(process.body(), &mut nonblocking_targets);
+ }
+ let mut counts: HashMap = HashMap::default();
+ for target in nonblocking_targets {
+ *counts.entry(target).or_default() += 1;
+ }
+ let mut lowering = ProcessLowering {
+ artifact,
+ hidden,
+ wait_sites: Vec::new(),
+ nba_sites: Vec::new(),
+ // A port may have writers outside the module (`NbaSite::pending`).
+ single_nba_targets: counts
+ .into_iter()
+ .filter(|&(target, count)| {
+ count == 1
+ && artifact
+ .signal(target)
+ .is_some_and(|signal| signal.direction() == Direction::Internal)
})
- })
- .collect()
+ .map(|(target, _)| target)
+ .collect(),
+ process: 0,
+ process_wait_sites: 0,
+ process_nba_sites: 0,
+ counted_loops: 0,
+ };
+ let mut processes = Vec::new();
+ for (index, process) in artifact.processes().iter().enumerate() {
+ let name = |slot: &str| vec![format!("$process[{index}]"), slot.to_string()];
+ let slots = ProcessSlots {
+ resume: lowering
+ .hidden
+ .declare(name("resume"), PROCESS_RESUME_WIDTH, false),
+ status: lowering
+ .hidden
+ .declare(name("status"), PROCESS_STATUS_WIDTH, false),
+ delay: lowering
+ .hidden
+ .declare(name("delay"), PROCESS_DELAY_WIDTH, false),
+ };
+ lowering.process = index;
+ lowering.process_wait_sites = 0;
+ lowering.process_nba_sites = 0;
+ let mut kernel = ProcessKernelBuilder::new(slots);
+ lower_statements(&mut lowering, &mut kernel, process.body())?;
+ let kernel = kernel.build();
+ candidates.extend(crate::watch::multi_store_candidates(&kernel, |address| {
+ stable_signal(address, artifact.signals().len())
+ }));
+ processes.push(SymbolicProcess { kernel, slots });
+ }
+ Ok(LoweredProcesses {
+ processes,
+ wait_sites: lowering.wait_sites,
+ nba_sites: lowering.nba_sites,
+ })
}
fn set_role(
@@ -1281,9 +1824,21 @@ pub fn lower_frontend_artifact(
})
.collect();
- let processes = lower_processes(artifact, &mut variables)?;
-
+ let mut hidden = HiddenObjects {
+ next_id: artifact.signals().len() as u32,
+ variables: &mut variables,
+ };
+ let mut candidates = Vec::new();
+ let LoweredProcesses {
+ processes,
+ wait_sites,
+ nba_sites,
+ } = lower_processes(artifact, &mut hidden, &mut candidates)?;
let mut arena = SLTNodeArena::new();
+ let comb_process_paths =
+ lower_comb_processes(artifact, &mut hidden, &mut arena, &mut candidates)?;
+ let counter_slots = crate::watch::declare_counter_slots(hidden.variables, candidates);
+
let mut node_cache = HashMap::default();
let mut comb_blocks = Vec::new();
for assignment in artifact.assignments() {
@@ -1310,6 +1865,7 @@ pub fn lower_frontend_artifact(
)?,
});
}
+ comb_blocks.extend(comb_process_paths);
let mut eval_only_ff_blocks = HashMap::default();
let mut apply_ff_blocks = HashMap::default();
@@ -1362,6 +1918,9 @@ pub fn lower_frontend_artifact(
reset_clock_map,
processes,
package_bindings: HashMap::default(),
+ counter_slots,
+ wait_sites,
+ nba_sites,
};
let symbolic = SymbolicRtl {
modules: [(module_id, sim_module.clone())].into_iter().collect(),
diff --git a/crates/celox-frontend-core/src/symbolic/artifact.rs b/crates/celox-frontend-core/src/symbolic/artifact.rs
index fb7b4fa02a6..2916167c90b 100644
--- a/crates/celox-frontend-core/src/symbolic/artifact.rs
+++ b/crates/celox-frontend-core/src/symbolic/artifact.rs
@@ -1,8 +1,9 @@
use std::{collections::BTreeSet, fmt};
use celox_design::{
- ExternFunction, InitialStateValue, ModuleId, ProcessSlots, RegionedAbsoluteAddrBase,
- RegionedVarAddrBase, RuntimeErrorInfo, RuntimeEventSite, TriggerSet, VariableMetadata,
+ CounterSlots, ExternFunction, InitialStateValue, ModuleId, NbaSite, ProcessSlots,
+ RegionedAbsoluteAddrBase, RegionedVarAddrBase, RuntimeErrorInfo, RuntimeEventSite, TriggerSet,
+ VariableMetadata, WaitSite,
};
use celox_sir::ExecutionUnit;
use celox_slt::{CombObserver, FfAccessSummary, GlueBlockBase, LogicPath, SLTNodeArena};
@@ -87,6 +88,17 @@ pub struct SimModule {
/// 1800-2023 26.2). Every instance of the module refers to that one
/// object instead of a state object of its own.
pub package_bindings: HashMap,
+ /// Counter objects of the signals that a unit of the module may store
+ /// twice between two runtime checks (see
+ /// `crate::watch::multi_store_candidates`). Assembly counts a signal's
+ /// occurrences only if a flip-flop domain or a wait watches it.
+ pub counter_slots: Vec>,
+ /// Wait sites of the module's processes; `process` indexes
+ /// [`Self::processes`].
+ pub wait_sites: Vec>,
+ /// Nonblocking sites of the module's processes; `process` indexes
+ /// [`Self::processes`].
+ pub nba_sites: Vec>,
}
/// The package variable a module variable denotes.
diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs
index 44298ea22e2..ee3b11c38f8 100644
--- a/crates/celox-frontend-core/src/symbolic/assembly.rs
+++ b/crates/celox-frontend-core/src/symbolic/assembly.rs
@@ -9,11 +9,11 @@ use crate::{
SourceAddr, SourceLocation, SourceVarId, VariableInfo, flattening,
};
use celox_design::{
- BitAccess, CombDerivedClock, DomainKind, ElaboratedDesign, EventTopology, ExternFunction,
- GateOp, InitialStateValue, InstanceId, ModuleId, ProcessSlots, RegionedAbsoluteAddrBase,
- RegionedStateAddr, RuntimeCombObserver, RuntimeErrorInfo, RuntimeEventKind, RuntimeEventSite,
- RuntimeSchema, STABLE_REGION, StateAddr, StateObjectId, TriggerSet, VarAtomBase,
- VariableMetadata,
+ BitAccess, CombDerivedClock, CounterKind, CounterSlots, DomainKind, ElaboratedDesign,
+ EventTopology, EventWatch, ExternFunction, GateOp, InitialStateValue, InstanceId, ModuleId,
+ NbaSite, ProcessSlots, RegionedAbsoluteAddrBase, RegionedStateAddr, RuntimeCombObserver,
+ RuntimeErrorInfo, RuntimeEventKind, RuntimeEventSite, RuntimeSchema, STABLE_REGION, StateAddr,
+ StateObjectId, TriggerSet, VarAtomBase, VariableMetadata, WaitSite,
};
use celox_sir::{
BasicBlock, ExecutionUnit, LaneUnit, ParallelSirProgram, SIRInstruction, SIRTerminator,
@@ -645,7 +645,7 @@ pub fn schedule_symbolic_rtl(
runtime_event_sites,
extern_functions,
next_runtime_error_code,
- processes,
+ mut processes,
) = timed_sub!(
"relocate_units",
relocate_units(
@@ -663,6 +663,39 @@ pub fn schedule_symbolic_rtl(
&mut trace,
)
)?;
+ let timing = relocate_timing(bindings, &instance_modules, &modules, &processes);
+ let counted = {
+ // Flip-flop event domains and the aliases that resolve to them.
+ let event_addresses: HashSet = eval_apply_ffs
+ .keys()
+ .copied()
+ .chain(
+ clock_domains
+ .iter()
+ .filter(|(_, canonical)| eval_apply_ffs.contains_key(canonical))
+ .map(|(alias, _)| *alias),
+ )
+ .collect();
+ let variables: HashMap = instance_modules
+ .iter()
+ .flat_map(|(&instance, module)| {
+ modules[module].variables.iter().map(move |(&var_id, var)| {
+ (
+ bindings.locate(instance, var_id),
+ (var.metadata.width, var.metadata.is_4state),
+ )
+ })
+ })
+ .collect();
+ instrument_counted_signals(
+ &timing,
+ &event_addresses,
+ &variables,
+ four_state,
+ &mut processes,
+ &mut comb_blocks,
+ )
+ };
check_package_variable_drivers(
bindings,
&instance_modules,
@@ -1145,7 +1178,12 @@ pub fn schedule_symbolic_rtl(
.values()
.filter(|units| !units.is_empty())
.count();
- let needs_split_path = active_ff_domains > 1 || !cascaded_clocks.is_empty();
+ // With process kernels, a round in which a zero delay is pending after
+ // domains triggered evaluates them before the inactive region and
+ // publishes them in the NBA region (IEEE 1800-2023 4.5). Only those
+ // rounds use the split units; the fused units stay the default.
+ let needs_split_path =
+ active_ff_domains > 1 || !cascaded_clocks.is_empty() || !processes.is_empty();
let parallel_sir = parallel.enabled().then(|| {
let mut events = eval_apply_ffs
.iter()
@@ -1238,6 +1276,11 @@ pub fn schedule_symbolic_rtl(
.into_iter()
.map(|process| (process.kernel, process.slots))
.unzip();
+ let TimingMetadata {
+ wait_sites,
+ nba_sites,
+ ..
+ } = timing;
let source_sir = SirProgram {
eval_apply_ffs,
eval_comb_apply_ffs,
@@ -1432,6 +1475,63 @@ pub fn schedule_symbolic_rtl(
.into_iter()
.map(|slots| slots.map(project))
.collect();
+ let watches: Vec> = {
+ let event_kinds = ElaboratedDesign {
+ state_objects: state_objects.clone(),
+ events: events.clone(),
+ initial_state: Vec::new(),
+ }
+ .event_kinds();
+ counted
+ .values()
+ .map(|slots| {
+ let signal = project(slots.signal);
+ let object = &state_objects[&signal];
+ let canonical = events.canonical(signal);
+ let domains = event_kinds
+ .get(&canonical)
+ .filter(|_| events.ordered_events.contains(&signal) || canonical != signal)
+ .map(|&kind| (canonical, CounterKind::for_domain(kind)))
+ .into_iter()
+ .collect();
+ EventWatch {
+ signal,
+ width: object.width,
+ four_state: object.is_4state,
+ changes: Some(project(slots.changes)),
+ rises: Some(project(slots.rises)),
+ falls: Some(project(slots.falls)),
+ domains,
+ }
+ })
+ .collect()
+ };
+ let wait_sites: Vec> =
+ wait_sites.iter().map(|site| site.map(project)).collect();
+ let nba_sites: Vec> =
+ nba_sites.iter().map(|site| site.map(project)).collect();
+ // The runtime reads counters, the signals waits watch and staged
+ // nonblocking values directly; no unit loads a wait's signal.
+ let timing_read_roots = watches
+ .iter()
+ .flat_map(|watch| {
+ watch
+ .counters()
+ .map(|(_, counter)| counter)
+ .collect::>()
+ })
+ .chain(
+ wait_sites
+ .iter()
+ .flat_map(|site| site.terms.iter().map(|(signal, _)| *signal)),
+ )
+ .chain(
+ nba_sites
+ .iter()
+ .flat_map(|site| [Some(site.value), site.offset, site.pending])
+ .flatten(),
+ )
+ .collect();
// A package variable's state object maps back to the package's own
// variable, not to one of its aliases.
let state_to_source = source_to_state
@@ -1465,13 +1565,16 @@ pub fn schedule_symbolic_rtl(
runtime_event_sites,
extern_functions,
comb_observers,
- testbench_read_roots: Default::default(),
+ testbench_read_roots: timing_read_roots,
rtl_writes,
comb_writes: Default::default(),
persistent_comb_state,
dead_store_policy: Default::default(),
live_signals: Default::default(),
processes: process_slots,
+ watches,
+ wait_sites,
+ nba_sites,
},
};
@@ -2516,6 +2619,7 @@ fn relocate_units(
&extern_function_map,
),
slots: process.slots.map(|var_id| bindings.locate(*id, var_id)),
+ key: (*id, index),
},
));
}
@@ -2606,6 +2710,128 @@ fn relocate_units(
struct RelocatedProcess {
kernel: ExecutionUnit,
slots: ProcessSlots,
+ /// The instance and the module-local index of the process.
+ key: (InstanceId, usize),
+}
+
+/// Counter slots, wait sites and nonblocking sites of the whole design.
+struct TimingMetadata {
+ counter_slots: Vec>,
+ wait_sites: Vec>,
+ nba_sites: Vec>,
+}
+
+/// Place the timing metadata of every instance. Sites name the global index
+/// of their process; a kernel numbers its sites in the order they appear
+/// here, which is the module's order.
+fn relocate_timing(
+ bindings: &PackageBindings,
+ instance_modules: &HashMap,
+ modules: &HashMap,
+ processes: &[RelocatedProcess],
+) -> TimingMetadata {
+ let process_index: HashMap<(InstanceId, usize), usize> = processes
+ .iter()
+ .enumerate()
+ .map(|(index, process)| (process.key, index))
+ .collect();
+ let mut instances = instance_modules.iter().collect::>();
+ instances.sort_unstable_by_key(|(instance, _)| **instance);
+ let mut metadata = TimingMetadata {
+ counter_slots: Vec::new(),
+ wait_sites: Vec::new(),
+ nba_sites: Vec::new(),
+ };
+ for (&instance, module) in instances {
+ let module = &modules[module];
+ let locate = |var_id| bindings.locate(instance, var_id);
+ metadata
+ .counter_slots
+ .extend(module.counter_slots.iter().map(|slots| slots.map(locate)));
+ metadata
+ .wait_sites
+ .extend(module.wait_sites.iter().map(|site| WaitSite {
+ process: process_index[&(instance, site.process)],
+ ..site.map(locate)
+ }));
+ metadata
+ .nba_sites
+ .extend(module.nba_sites.iter().map(|site| NbaSite {
+ process: process_index[&(instance, site.process)],
+ ..site.map(locate)
+ }));
+ }
+ metadata
+}
+
+/// Counted signals: those a unit may store twice between two runtime checks
+/// (a frontend declared counters for them) and that a flip-flop domain or a
+/// wait watches. Returns their counters by signal and instruments the
+/// process kernels and combinational process units that write them; no
+/// other unit changes.
+fn instrument_counted_signals(
+ timing: &TimingMetadata,
+ event_addresses: &HashSet,
+ variables: &HashMap,
+ four_state: bool,
+ processes: &mut [RelocatedProcess],
+ comb_blocks: &mut [LogicPath],
+) -> BTreeMap> {
+ let waited: HashSet = timing
+ .wait_sites
+ .iter()
+ .flat_map(|site| site.terms.iter().map(|(signal, _)| *signal))
+ .collect();
+ let counted: BTreeMap> = timing
+ .counter_slots
+ .iter()
+ .filter(|slots| event_addresses.contains(&slots.signal) || waited.contains(&slots.signal))
+ .map(|slots| (slots.signal, *slots))
+ .collect();
+ if counted.is_empty() {
+ return counted;
+ }
+ let code = |signal: AbsoluteAddr| {
+ let slots = counted.get(&signal)?;
+ let (width, is_4state) = variables[&signal];
+ Some((slots, width, four_state && is_4state))
+ };
+ for process in processes {
+ crate::watch::instrument_unit(&mut process.kernel, |address| {
+ if address.region != STABLE_REGION {
+ return None;
+ }
+ let (slots, width, four_state) = code(address.absolute_addr())?;
+ let stable =
+ |var: AbsoluteAddr| RegionedAbsoluteAddr::from_absolute_addr(STABLE_REGION, var);
+ Some(crate::watch::WatchCode {
+ signal: stable(slots.signal),
+ width,
+ four_state,
+ counters: CounterKind::ALL
+ .into_iter()
+ .map(|kind| (kind, stable(slots.counter(kind))))
+ .collect(),
+ })
+ });
+ }
+ for path in comb_blocks {
+ if let LogicPathTarget::Process { unit, .. } = &mut path.target {
+ crate::watch::instrument_unit(unit, |address| {
+ let (slots, width, four_state) = code(*address)?;
+ Some(crate::watch::WatchCode {
+ signal: slots.signal,
+ width,
+ four_state,
+ counters: CounterKind::ALL
+ .into_iter()
+ .map(|kind| (kind, slots.counter(kind)))
+ .collect(),
+ })
+ });
+ }
+ }
+ counted
}
fn build_comb_observer_capture_paths(
diff --git a/crates/celox-frontend-core/src/watch.rs b/crates/celox-frontend-core/src/watch.rs
new file mode 100644
index 00000000000..3d9b80a809e
--- /dev/null
+++ b/crates/celox-frontend-core/src/watch.rs
@@ -0,0 +1,590 @@
+//! SIR for watched signals and change-gated combinational units.
+//!
+//! A watched signal ([`EventWatch`]) counts its occurrences in counter
+//! objects. [`emit_watched`] surrounds one store or commit to the signal
+//! with the code that bumps those counters, so an occurrence is counted even
+//! when a later store of the same execution overwrites it. Frontends use it
+//! on every path that writes a watched signal: process kernels, flip-flop
+//! evaluation and publication, and imperative combinational units. The code
+//! is ordinary SIR, so every backend runs it unchanged.
+//!
+//! An instrumented combinational unit must only run when one of its inputs
+//! changed (IEEE 1800-2023 9.2.2.2); otherwise re-running it, for example
+//! `y = 0; if (a) y = 1;` with a steady `a`, would count a pulse on `y` at
+//! every settle. [`gate_on_input_change`] adds that gate.
+
+use celox_design::{BinaryOp, CounterKind, EVENT_COUNTER_WIDTH, EventWatch};
+use celox_sir::{
+ ExecutionUnit, RegisterId, SIRBuilder, SIRInstruction, SIROffset, SIRTerminator, SIRValue,
+};
+
+/// A watched signal and its counters, addressed in the code being built.
+#[derive(Clone, Debug)]
+pub struct WatchCode {
+ /// The signal's stable state.
+ pub signal: A,
+ pub width: usize,
+ /// Whether the signal is held in four-state form.
+ pub four_state: bool,
+ pub counters: Vec<(CounterKind, A)>,
+}
+
+impl WatchCode {
+ /// The code view of `watch`, addressing each object through `address`.
+ /// `four_state` is whether the build keeps the signal in four-state form.
+ pub fn new(watch: &EventWatch, four_state: bool, address: impl Fn(V) -> A) -> Self {
+ Self {
+ signal: address(watch.signal),
+ width: watch.width,
+ four_state: four_state && watch.four_state,
+ counters: watch
+ .counters()
+ .map(|(kind, counter)| (kind, address(counter)))
+ .collect(),
+ }
+ }
+}
+
+fn load(
+ b: &mut SIRBuilder,
+ address: &A,
+ width: usize,
+ four_state: bool,
+) -> RegisterId {
+ load_bits(b, address, 0, width, four_state)
+}
+
+/// Load bits `lsb..lsb + width` of `address`.
+fn load_bits(
+ b: &mut SIRBuilder,
+ address: &A,
+ lsb: usize,
+ width: usize,
+ four_state: bool,
+) -> RegisterId {
+ let register = if four_state {
+ b.alloc_logic(width)
+ } else {
+ b.alloc_bit(width, false)
+ };
+ b.emit(SIRInstruction::Load(
+ register,
+ address.clone(),
+ SIROffset::Static(lsb),
+ width,
+ ));
+ register
+}
+
+fn binary(
+ b: &mut SIRBuilder,
+ lhs: RegisterId,
+ op: BinaryOp,
+ rhs: RegisterId,
+) -> RegisterId {
+ let result = b.alloc_bit(1, false);
+ b.emit(SIRInstruction::Binary(result, lhs, op, rhs));
+ result
+}
+
+/// Emit `write`, a store or commit that may change `watch.signal`, and
+/// count the occurrence it causes. `value_type` is the type of a store's
+/// source register.
+pub fn emit_watched(
+ b: &mut SIRBuilder,
+ watch: &WatchCode,
+ write: SIRInstruction,
+ value_type: Option<&celox_sir::RegisterType>,
+) {
+ let old = load(b, &watch.signal, watch.width, watch.four_state);
+ // A store of the whole signal stores the new value itself; any other
+ // write is read back.
+ let stored = match &write {
+ SIRInstruction::Store(_, SIROffset::Static(0), width, value, ..)
+ if *width == watch.width
+ && value_type
+ == Some(&if watch.four_state {
+ celox_sir::RegisterType::Logic { width: *width }
+ } else {
+ celox_sir::RegisterType::Bit {
+ width: *width,
+ signed: false,
+ }
+ }) =>
+ {
+ Some(*value)
+ }
+ _ => None,
+ };
+ // Everything derived from the old value is computed before the write,
+ // so no backend can re-read the written state for it.
+ let old_lsb = lsb(b, old, watch.width, watch.four_state);
+ b.emit(write);
+ if watch.counters.is_empty() {
+ return;
+ }
+ let new = match stored {
+ Some(value) => value,
+ None => load(b, &watch.signal, watch.width, watch.four_state),
+ };
+ let new_lsb = lsb(b, new, watch.width, watch.four_state);
+ for &(kind, ref counter) in &watch.counters {
+ let occurred = occurrence(
+ b,
+ kind,
+ (old, old_lsb),
+ (new, new_lsb),
+ watch.width,
+ watch.four_state,
+ );
+ bump(b, counter, occurred);
+ }
+}
+
+/// The least significant bit of `value`, kept at the signal's width: the
+/// value masked with one. A `Slice` would do, but the native backends may
+/// re-read a sliced load from state, which the write has changed.
+fn lsb(b: &mut SIRBuilder, value: RegisterId, width: usize, four_state: bool) -> RegisterId {
+ let one = constant(b, 1, width, four_state);
+ let bit = if four_state {
+ b.alloc_logic(width)
+ } else {
+ b.alloc_bit(width, false)
+ };
+ b.emit(SIRInstruction::Binary(bit, value, BinaryOp::And, one));
+ bit
+}
+
+fn constant(b: &mut SIRBuilder, value: u8, width: usize, four_state: bool) -> RegisterId {
+ let register = if four_state {
+ b.alloc_logic(width)
+ } else {
+ b.alloc_bit(width, false)
+ };
+ b.emit(SIRInstruction::Imm(register, SIRValue::new(value)));
+ register
+}
+
+/// Whether the change from `old` to `new`, each a value and its least
+/// significant bit, is an occurrence of `kind`.
+fn occurrence(
+ b: &mut SIRBuilder,
+ kind: CounterKind,
+ (old, old_lsb): (RegisterId, RegisterId),
+ (new, new_lsb): (RegisterId, RegisterId),
+ width: usize,
+ four_state: bool,
+) -> RegisterId {
+ if kind == CounterKind::Changes {
+ // Case inequality distinguishes every unknown bit as well.
+ return binary(b, old, BinaryOp::NeCase, new);
+ }
+ // IEEE 1800-2023 Table 9-2: a positive edge leaves 0 or reaches 1, a
+ // negative edge leaves 1 or reaches 0, and either changes the bit. In
+ // two-state form this is `old == 0 && new == 1` for a positive edge.
+ let (from, to) = if kind == CounterKind::Rises {
+ (0, 1)
+ } else {
+ (1, 0)
+ };
+ let from = constant(b, from, width, four_state);
+ let to = constant(b, to, width, four_state);
+ let changed = binary(b, old_lsb, BinaryOp::NeCase, new_lsb);
+ let left = binary(b, old_lsb, BinaryOp::EqCase, from);
+ let reached = binary(b, new_lsb, BinaryOp::EqCase, to);
+ let either = binary(b, left, BinaryOp::Or, reached);
+ binary(b, changed, BinaryOp::And, either)
+}
+
+/// Add `occurred`, a one-bit two-state register, to the counter at
+/// `counter`.
+fn bump(b: &mut SIRBuilder, counter: &A, occurred: RegisterId) {
+ let value = load(b, counter, EVENT_COUNTER_WIDTH, false);
+ let one = b.alloc_bit(EVENT_COUNTER_WIDTH, false);
+ b.emit(SIRInstruction::Imm(one, SIRValue::new(1u8)));
+ let incremented = b.alloc_bit(EVENT_COUNTER_WIDTH, false);
+ b.emit(SIRInstruction::Binary(
+ incremented,
+ value,
+ BinaryOp::Add,
+ one,
+ ));
+ let next = b.alloc_bit(EVENT_COUNTER_WIDTH, false);
+ b.emit(SIRInstruction::Mux(next, occurred, incremented, value));
+ b.emit(SIRInstruction::Store(
+ counter.clone(),
+ SIROffset::Static(0),
+ EVENT_COUNTER_WIDTH,
+ next,
+ Vec::new(),
+ Vec::new(),
+ ));
+}
+
+/// One input of a change-gated unit: bits `lsb..lsb + width` of the input's
+/// stable state and a private object of that width and representation that
+/// remembers their value.
+#[derive(Clone, Debug)]
+pub struct GateInput {
+ pub input: A,
+ pub lsb: usize,
+ pub shadow: A,
+ pub width: usize,
+ pub four_state: bool,
+}
+
+/// Wrap `unit` so that it runs on its first execution and afterwards only
+/// when an input differs from its value at the previous run. `ran` is a
+/// private one-bit two-state object, zero before the first run.
+///
+/// Inputs are remembered before the body runs, so the unit's own writes do
+/// not re-trigger it; a frontend excludes the variables the unit writes from
+/// `inputs` (IEEE 1800-2023 9.2.2.2.1).
+pub fn gate_on_input_change(
+ unit: &ExecutionUnit,
+ inputs: &[GateInput],
+ ran: &A,
+) -> ExecutionUnit {
+ let mut b = SIRBuilder::new();
+ let has_run = load(&mut b, ran, 1, false);
+ let first = b.alloc_bit(1, false);
+ b.emit(SIRInstruction::Unary(
+ first,
+ celox_design::UnaryOp::LogicNot,
+ has_run,
+ ));
+ let mut run = first;
+ let mut currents = Vec::with_capacity(inputs.len());
+ for input in inputs {
+ let current = load_bits(
+ &mut b,
+ &input.input,
+ input.lsb,
+ input.width,
+ input.four_state,
+ );
+ let previous = load(&mut b, &input.shadow, input.width, input.four_state);
+ let differs = binary(&mut b, current, BinaryOp::NeCase, previous);
+ run = binary(&mut b, run, BinaryOp::Or, differs);
+ currents.push(current);
+ }
+ let execute = b.new_block();
+ let done = b.new_block();
+ b.seal_block(SIRTerminator::Branch {
+ cond: run,
+ true_block: (execute, Vec::new()),
+ false_block: (done, Vec::new()),
+ });
+ b.switch_to_block(execute);
+ for (input, current) in inputs.iter().zip(currents) {
+ b.emit(SIRInstruction::Store(
+ input.shadow.clone(),
+ SIROffset::Static(0),
+ input.width,
+ current,
+ Vec::new(),
+ Vec::new(),
+ ));
+ }
+ let one = b.alloc_bit(1, false);
+ b.emit(SIRInstruction::Imm(one, SIRValue::new(1u8)));
+ b.emit(SIRInstruction::Store(
+ ran.clone(),
+ SIROffset::Static(0),
+ 1,
+ one,
+ Vec::new(),
+ Vec::new(),
+ ));
+ b.inline_execution_unit(unit);
+ b.seal_block(SIRTerminator::Jump(done, Vec::new()));
+ b.switch_to_block(done);
+ b.flush_eu().expect("a gated unit has instructions")
+}
+
+fn successors(terminator: &SIRTerminator) -> Vec {
+ match terminator {
+ SIRTerminator::Jump(target, _) => vec![*target],
+ SIRTerminator::Branch {
+ true_block,
+ false_block,
+ ..
+ } => vec![true_block.0, false_block.0],
+ SIRTerminator::Switch { cases, default, .. } => cases
+ .iter()
+ .map(|case| case.target)
+ .chain(std::iter::once(*default))
+ .collect(),
+ SIRTerminator::Return | SIRTerminator::Error(_) => Vec::new(),
+ }
+}
+
+/// The destination of a store or commit.
+pub fn write_destination(instruction: &SIRInstruction) -> Option<&A> {
+ match instruction {
+ SIRInstruction::Store(address, ..) | SIRInstruction::Commit(_, address, ..) => {
+ Some(address)
+ }
+ _ => None,
+ }
+}
+
+/// Destinations, by `key`, that one execution of `unit` may write twice
+/// without returning in between: a write from which another write of the
+/// same destination is reachable, including itself around a loop. A
+/// process kernel returns at every suspension, so for a kernel this is
+/// "twice between two suspensions"; a write in one branch and another in
+/// the other branch is not.
+///
+/// The result is a syntactic superset; a candidate costs only counter
+/// objects unless something watches it.
+pub fn multi_store_candidates(
+ unit: &ExecutionUnit,
+ key: impl Fn(&A) -> Option,
+) -> Vec {
+ let writes = |block: &celox_sir::BasicBlock| -> Vec