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
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 @@ -8392,6 +8402,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 @@ -4626,6 +4626,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
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
77 changes: 77 additions & 0 deletions crates/celox-test-suite/src/sv/cases/timing.vtest
Original file line number Diff line number Diff line change
Expand Up @@ -2082,3 +2082,80 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev
(top Top)
(run_to_finish)
(expect_output "q=2 r=1 s=1\n"))

(case plain_always_expression_edges_run_as_processes
; IEEE 1800-2023 9.2.2.4 restricts only always_ff to the flip-flop shape.
; A plain always waits on its event control like any other process: an
; edge of a select or an expression, or `edge` (9.4.2).
(source "always_expression_edges.sv" #"
module Top(output bit [7:0] selected, both, any);
bit [3:0] v;
bit a, b;
always @(posedge v[1]) selected = selected + 8'd1;
always @(posedge (a & b)) both = both + 8'd1;
always @(edge a) any = any + 8'd1;
initial begin
#1; v = 4'b0010; a = 1;
#1; b = 1;
#1; v = 4'b0000; a = 0;
#1; v = 4'b0010; a = 1;
end
endmodule
"#)
(top Top)
(run_until 1)
(assert_eq selected 1)
(assert_eq both 0)
(assert_eq any 1)
(run_until 2)
(assert_eq both 1 "a & b rose")
(run_until 4)
(assert_eq selected 2)
(assert_eq both 2)
(assert_eq any 3 "a rose, fell and rose"))

(case plain_always_multi_bit_edges_follow_the_lsb
; Table 9-2 judges the edge of a multi-bit expression on its least
; significant bit.
(source "always_multi_bit_edge.sv" #"
module Top(output bit [7:0] count);
bit [3:0] bus;
always @(posedge bus) count = count + 8'd1;
initial begin
#1; bus = 4'b0010;
#1; bus = 4'b0011;
#1; bus = 4'b0000;
#1; bus = 4'b0001;
end
endmodule
"#)
(top Top)
(run_until 1)
(assert_eq count 0 "the least significant bit stayed 0")
(run_until 2)
(assert_eq count 1)
(run_until 4)
(assert_eq count 2))

(case plain_always_edges_without_a_reset_run_as_processes
; Neither edge is tested in the body, so neither is an asynchronous
; reset: the process wakes on each of them.
(source "always_two_edges.sv" #"
module Top(output bit [7:0] count);
bit c, d;
always @(posedge c or posedge d) count <= count + 8'd1;
initial begin
#1; c = 1;
#1; d = 1;
#1; c = 0; d = 0;
#1; c = 1;
end
endmodule
"#)
(top Top)
(run_until 1)
(assert_eq count 1)
(run_until 2)
(assert_eq count 2)
(run_until 4)
(assert_eq count 3))
33 changes: 33 additions & 0 deletions crates/celox-test-suite/verification/sv/icarus/timing.json
Original file line number Diff line number Diff line change
Expand Up @@ -673,6 +673,39 @@
"tag_reasons": {},
"tags": []
},
{
"category": "Sequential",
"detail": "",
"expectation": "Simulation",
"name": "timing::plain_always_edges_without_a_reset_run_as_processes",
"phase": "execute",
"status": "passed",
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
},
{
"category": "Sequential",
"detail": "",
"expectation": "Simulation",
"name": "timing::plain_always_expression_edges_run_as_processes",
"phase": "execute",
"status": "passed",
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
},
{
"category": "Sequential",
"detail": "",
"expectation": "Simulation",
"name": "timing::plain_always_multi_bit_edges_follow_the_lsb",
"phase": "execute",
"status": "passed",
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
},
{
"category": "Sequential",
"detail": "",
Expand Down
Loading
Loading