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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions conformance/sv-tests/expected.tsv
Original file line number Diff line number Diff line change
Expand Up @@ -1607,8 +1607,8 @@ chapter-9/9.4.1--delay_control-two-blocks-sim.sv 2state pass
chapter-9/9.4.1--delay_control-two-blocks-sim.sv 4state pass
chapter-9/9.4.1--delay_control.sv 2state pass
chapter-9/9.4.1--delay_control.sv 4state pass
chapter-9/9.4.2--event_control_edge.sv 2state fail
chapter-9/9.4.2--event_control_edge.sv 4state fail
chapter-9/9.4.2--event_control_edge.sv 2state pass
chapter-9/9.4.2--event_control_edge.sv 4state pass
chapter-9/9.4.2--event_control_negedge.sv 2state pass
chapter-9/9.4.2--event_control_negedge.sv 4state pass
chapter-9/9.4.2--event_control_posedge.sv 2state pass
Expand Down
74 changes: 59 additions & 15 deletions crates/celox-frontend-sv/src/lowering.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2712,6 +2712,31 @@ fn lower_module_with_overrides(
force_signals: &[String],
level_lists: LevelLists<'_>,
) -> Result<LoweredSvModule, sv::AnalyzerError> {
let parameter_types = module
.imported_parameters()
.iter()
.chain(module.parameters())
.filter_map(|parameter| {
Some((
parameter.name().to_string(),
(
parameter.resolved_width()?,
parameter.resolved_signed().unwrap_or(false),
),
))
})
.collect();
let constants = module_constants_with_overrides(module, parameter_overrides);
let fallbacks = module
.ff_processes()
.iter()
.any(|process| runs_as_process(module, process, &constants, &parameter_types))
.then(|| {
module.clone().run_edge_processes_as_processes(|process| {
runs_as_process(module, process, &constants, &parameter_types)
})
});
let module = fallbacks.as_ref().unwrap_or(module);
let mut ff_event_roles = Vec::new();
for process in module.ff_processes() {
let clock = clock_event_from_ff_process(process)
Expand All @@ -2734,21 +2759,6 @@ fn lower_module_with_overrides(
});
}
}
let parameter_types = module
.imported_parameters()
.iter()
.chain(module.parameters())
.filter_map(|parameter| {
Some((
parameter.name().to_string(),
(
parameter.resolved_width()?,
parameter.resolved_signed().unwrap_or(false),
),
))
})
.collect();
let constants = module_constants_with_overrides(module, parameter_overrides);
let shared_memories = shared_edge_memories(module, &constants, &parameter_types, warnings);
validate_variable_driver_ranges(module, &constants, &parameter_types, &shared_memories)?;
let scheduled = module
Expand Down Expand Up @@ -8482,6 +8492,40 @@ fn insert_or_merge_ff_unit(
}
}

/// A plain `always` sensitive to edges is a flip-flop only in the shape of
/// one: a clock and asynchronous resets, each a one-bit variable. Any other
/// edge-sensitive `always` runs as a process waiting on the same events.
fn runs_as_process(
module: &sv::ir::Module,
process: &sv::ir::FfProcess,
constants: &HashMap<String, i128>,
parameter_types: &HashMap<String, (usize, bool)>,
) -> bool {
let multi_bit = |name: &str| {
let r#type = module
.ports()
.iter()
.find(|port| port.name() == name)
.map(sv::ir::Port::r#type)
.or_else(|| {
module
.signals()
.iter()
.find(|signal| signal.name() == name)
.map(sv::ir::Signal::r#type)
});
r#type
.and_then(|r#type| signal_type_from_sv(r#type, constants, parameter_types).ok())
.is_some_and(|type_info| type_info.width != 1)
};
!process.is_always_ff()
&& (clock_event_from_ff_process(process).is_none()
|| process
.events()
.iter()
.any(|event| multi_bit(event.signal())))
}

fn clock_event_from_ff_process(process: &sv::ir::FfProcess) -> Option<&sv::ir::FfEvent> {
let clock = process.events().first()?;
if process.events().len() == 1 {
Expand Down
11 changes: 11 additions & 0 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4632,6 +4632,17 @@ impl Ff<'_, '_> {
let mut samples = Vec::new();
for item in items {
let expr = self.propagate(&item.expr);
let edge = match item.edge {
sv::ir::EventEdge::Any => None,
sv::ir::EventEdge::Pos => Some("posedge"),
sv::ir::EventEdge::Neg => Some("negedge"),
sv::ir::EventEdge::Both => Some("edge"),
};
if let Some(edge) = edge
&& self.m.expr_float_precision(&expr).is_some()
{
return Err(sv::AnalyzerError::RealEdgeEvent { edge });
}
let id = match &expr {
sv::ir::Expr::Ident(name) => match self.m.id(name) {
Some(id) if !self.m.is_hidden(id) => id,
Expand Down
68 changes: 53 additions & 15 deletions crates/celox-runtime/src/simulation/wait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,24 @@ impl<B: SimBackend> SimulationState<B> {
for (term, baseline) in terms.iter().zip(&mut waiter.baselines) {
match term.counter {
Some(counter) => {
*baseline = Baseline::Counter {
seen: backend.get_as(counter),
value: read(backend, term.signal),
let seen = backend.get_as(counter);
match planes(backend, term.signal) {
Some(image) => {
if let Baseline::RawCounter { seen: last, raw } = baseline {
*last = seen;
copy_planes(raw, image, term.signal.width);
} else {
let mut raw = Vec::with_capacity(image.len());
copy_planes(&mut raw, image, term.signal.width);
*baseline = Baseline::RawCounter { seen, raw };
}
}
None => {
*baseline = Baseline::Counter {
seen,
value: read(backend, term.signal),
}
}
}
}
None => match planes(backend, term.signal) {
Expand Down Expand Up @@ -128,20 +143,40 @@ impl<B: SimBackend> SimulationState<B> {
continue;
}
let baseline = &mut waiter.baselines[index];
// The common term: a plain signal no counter counts.
if let Baseline::Raw(last) = baseline {
let now = state.planes(term.signal).expect("a plain signal");
wake |= Self::advance(term.kind, last, now, term.signal.width);
continue;
}
let counted = |seen: u32| {
term.counter
.is_some_and(|counter| backend.get_as::<u32>(counter) != seen)
};
wake |= match baseline {
Baseline::Counter { seen, value } => {
let counted = term
.counter
.is_some_and(|counter| backend.get_as::<u32>(counter) != *seen);
let now = read(backend, term.signal);
let changed = occurs(term.kind, value, &now);
*value = now;
counted || changed
}
Baseline::Raw(last) => {
Baseline::RawCounter { seen, raw } => {
let now = state.planes(term.signal).expect("a plain signal");
Self::advance(term.kind, last, now, term.signal.width)
let changed = Self::advance(term.kind, raw, now, term.signal.width);
counted(*seen) || changed
}
Baseline::Counter { seen, value } => match state.planes(term.signal) {
// A baseline loaded from a state file.
Some(now) => {
let seen = *seen;
let mut raw = encode_planes(value, term.signal.width, now.len());
let changed =
Self::advance(term.kind, &mut raw, now, term.signal.width);
*baseline = Baseline::RawCounter { seen, raw };
counted(seen) || changed
}
None => {
let now = read(backend, term.signal);
let changed = occurs(term.kind, value, &now);
*value = now;
counted(*seen) || changed
}
},
Baseline::Raw(_) => unreachable!("tested above"),
Baseline::Value(last) => match state.planes(term.signal) {
// A baseline loaded from a state file.
Some(now) => {
Expand Down Expand Up @@ -191,7 +226,7 @@ impl<B: SimBackend> SimulationState<B> {
}
match baseline {
// Counters are bumped by the write itself.
Baseline::Counter { .. } => {}
Baseline::Counter { .. } | Baseline::RawCounter { .. } => {}
Baseline::Raw(last) => {
let now = encode_planes(value, signal.width, last.len());
wake |= Self::advance(term.kind, last, &now, signal.width);
Expand Down Expand Up @@ -224,6 +259,9 @@ pub enum Baseline {
/// (see [`planes`]) with the bits above its width cleared. Checks
/// compare it with the state in place.
Raw(Vec<u8>),
/// Like `Counter`, with the signal's state at the last check kept as
/// in [`Baseline::Raw`].
RawCounter { seen: u32, raw: Vec<u8> },
}

/// A process suspended at a wait.
Expand Down
34 changes: 27 additions & 7 deletions crates/celox-sv-analyzer/src/ast/ff_process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,12 @@ fn ff_process_from_procedure(
if always_kind(procedure, syntax_tree.declarations())? != AlwaysKind::Ff {
return Ok(None);
}
let root = procedure.body;
let (events, body) = ff_event_control_and_body(root, syntax_tree)?;
let Some((events, body)) = ff_event_control_and_body(procedure.body, syntax_tree)? else {
if procedure.kind == celox_sv_syntax::ProcedureKind::AlwaysFf {
return Err(unsupported("always_ff event expression"));
}
return Ok(None);
};
let mut local_dimensions = packed_dimensions.clone();
local_dimensions.const_env = const_env.clone().into();
let mut builder = procedural::BodyBuilder::new(
Expand All @@ -93,12 +97,26 @@ fn ff_process_from_procedure(
}))
}

/// A plain `always` sensitive to edges runs as a process when its events are
/// not all `posedge` or `negedge` of a variable, such as `@(posedge v[0])`,
/// `@(edge a)` or `@(posedge clk or a)`. Only `always_ff` must have this shape
/// (IEEE 1800-2023 9.2.2.4).
pub(super) fn always_falls_back_to_process(
procedure: &celox_sv_syntax::Procedure,
tree: &AnalysisContext<'_>,
) -> Result<bool, AnalyzerError> {
Ok(procedure.kind == celox_sv_syntax::ProcedureKind::Always
&& always_kind(procedure, tree.declarations())? == AlwaysKind::Ff
&& ff_event_control_and_body(procedure.body, tree)?.is_none())
}

/// The events of a flip-flop shaped event control and the body it controls,
/// or `None` when an event is not an edge of a variable.
fn ff_event_control_and_body(
root: celox_sv_syntax::StatementId,
tree: &AnalysisContext<'_>,
) -> Result<(Vec<FfEvent>, celox_sv_syntax::StatementId), AnalyzerError> {
) -> Result<Option<(Vec<FfEvent>, celox_sv_syntax::StatementId)>, AnalyzerError> {
use celox_sv_syntax::{EventControl, StatementKind, TimingControlKind, TimingEdge};
let unsupported_event = || unsupported("always_ff event expression");
let native = tree.declarations();
let StatementKind::Timing { control, body } = native.statement(root).kind else {
return Err(timing::disagreement());
Expand All @@ -115,12 +133,14 @@ fn ff_event_control_and_body(
let edge = match item.edge {
TimingEdge::Pos => FfEdge::Pos,
TimingEdge::Neg => FfEdge::Neg,
_ => return Err(unsupported_event()),
_ => return Ok(None),
};
let expression =
expression_binding::value(item.expression, native, tree, &PackedDimensions::default())?;
let signal = expr_ident_name(&expression).ok_or_else(unsupported_event)?;
let Some(signal) = expr_ident_name(&expression) else {
return Ok(None);
};
events.push(FfEvent::new(edge, signal));
}
Ok((events, body))
Ok(Some((events, body)))
}
3 changes: 2 additions & 1 deletion crates/celox-sv-analyzer/src/ast/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2701,7 +2701,8 @@ pub(super) fn initial_processes_from_scope(
celox_sv_syntax::ProcedureKind::Initial => false,
celox_sv_syntax::ProcedureKind::Always
if validation::always_kind(procedure, tree.declarations())?
== validation::AlwaysKind::Process =>
== validation::AlwaysKind::Process
|| ff_process::always_falls_back_to_process(procedure, tree)? =>
{
true
}
Expand Down
5 changes: 4 additions & 1 deletion crates/celox-sv-analyzer/src/ast/validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ pub(super) enum AlwaysKind {

/// `always_comb` and `always @*` are combinational; `always_ff` and an
/// `always` sensitive to clock edges are sequential, as long as their body
/// has no timing control of its own. Every other `always` is a process.
/// has no timing control of its own. Every other `always` is a process, and
/// so is an edge-sensitive `always` whose events are not edges of variables
/// (`ff_process::always_falls_back_to_process`). The frontend runs one whose
/// events are not a one-bit clock and resets as a process too.
/// `always_latch` has the execution and sensitivity rules of `always_comb`.
pub(super) fn always_kind(
procedure: &celox_sv_syntax::Procedure,
Expand Down
18 changes: 16 additions & 2 deletions crates/celox-sv-analyzer/src/ir.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,21 @@ pub struct Module {
impl Module {
/// Represent selected edge procedures as scheduled processes. A host
/// request must finish synchronously before the following statement runs.
pub fn schedule_edge_processes(mut self, mut select: impl FnMut(&FfProcess) -> bool) -> Self {
pub fn schedule_edge_processes(self, select: impl FnMut(&FfProcess) -> bool) -> Self {
self.edge_processes_as_processes(select, true)
}

/// Run selected plain `always` edge procedures as ordinary processes that
/// wait on the same events, for those that do not fit the flip-flop shape.
pub fn run_edge_processes_as_processes(self, select: impl FnMut(&FfProcess) -> bool) -> Self {
self.edge_processes_as_processes(select, false)
}

fn edge_processes_as_processes(
mut self,
mut select: impl FnMut(&FfProcess) -> bool,
scheduled_edge: bool,
) -> Self {
let mut retained = Vec::new();
for process in std::mem::take(&mut self.ff_processes) {
if !select(&process) {
Expand All @@ -101,7 +115,7 @@ impl Module {
self.initial_processes.push(InitialProcess {
creation_order: process.creation_order,
site: process.site,
scheduled_edge: true,
scheduled_edge,
condition: None,
body: vec![Stmt::Loop {
kind: LoopKind::Forever,
Expand Down
4 changes: 4 additions & 0 deletions crates/celox-sv-analyzer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,10 @@ pub enum AnalyzerError {
actual: String,
target: String,
},
/// `posedge`, `negedge` or `edge` of a real expression, which has no
/// least significant bit to judge the edge on (IEEE 1800-2023 6.12).
#[error("`{edge}` of a real expression: edge event controls do not apply to reals")]
RealEdgeEvent { edge: &'static str },
}

impl miette::Diagnostic for AnalyzerError {}
Expand Down
Loading
Loading