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
70 changes: 58 additions & 12 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2600,8 +2600,9 @@ impl<'p, 'a> Ff<'p, 'a> {
sv::ir::Stmt::Delay {
amount,
ticks_per_unit,
ticks_per_precision,
} => {
self.delay(amount, *ticks_per_unit)?;
self.delay(amount, *ticks_per_unit, *ticks_per_precision)?;
Ok(true)
}
sv::ir::Stmt::WaitEvent(items) => {
Expand Down Expand Up @@ -4364,21 +4365,30 @@ impl Ff<'_, '_> {
&mut self,
amount: &sv::ir::Expr,
ticks_per_unit: u64,
ticks_per_precision: u64,
) -> Result<(), sv::AnalyzerError> {
let signed = self.expr_signed(amount);
let mut arena = SLTNodeArena::new();
let node = self.expr_slt(amount, None, &mut arena)?;
let original = self.lower_slt(&arena, node)?;
let node = coerce_node_width(&mut arena, node, Some(PROCESS_DELAY_WIDTH), signed)
.map_err(slt_error)?;
let delay = self.lower_slt(&arena, node)?;
let mut delay = self.zero_if_unknown(delay, original);
if ticks_per_unit > 1 {
let (mut delay, ticks_per_step) = match self.m.expr_float_precision(amount) {
Some(precision) => (
self.real_delay(amount, precision, ticks_per_unit / ticks_per_precision)?,
ticks_per_precision,
),
None => {
let signed = self.expr_signed(amount);
let mut arena = SLTNodeArena::new();
let node = self.expr_slt(amount, None, &mut arena)?;
let original = self.lower_slt(&arena, node)?;
let node = coerce_node_width(&mut arena, node, Some(PROCESS_DELAY_WIDTH), signed)
.map_err(slt_error)?;
let delay = self.lower_slt(&arena, node)?;
(self.zero_if_unknown(delay, original), ticks_per_unit)
}
};
if ticks_per_step > 1 {
// Check before multiplying so the 64-bit delay slot cannot wrap.
let limit = self.b.alloc_bit(PROCESS_DELAY_WIDTH, false);
self.b.emit(SIRInstruction::Imm(
limit,
SIRValue::new(u64::MAX / ticks_per_unit),
SIRValue::new(u64::MAX / ticks_per_step),
));
let overflow = self.b.alloc_bit(1, false);
self.b.emit(SIRInstruction::Binary(
Expand All @@ -4402,7 +4412,7 @@ impl Ff<'_, '_> {
self.b.switch_to_block(scaled);
let factor = self.b.alloc_bit(PROCESS_DELAY_WIDTH, false);
self.b
.emit(SIRInstruction::Imm(factor, SIRValue::new(ticks_per_unit)));
.emit(SIRInstruction::Imm(factor, SIRValue::new(ticks_per_step)));
let product = self.b.alloc_bit(PROCESS_DELAY_WIDTH, false);
self.b.emit(SIRInstruction::Binary(
product,
Expand All @@ -4416,6 +4426,42 @@ impl Ff<'_, '_> {
.map_err(kernel_error)
}

/// A real delay `amount` in precision steps of the declaring scope:
/// scaled from time units by `steps_per_unit`, rounded to the nearest
/// step with ties away from zero (3.14.1, 6.12.1), and read as an
/// unsigned 64-bit time like an integral delay (9.4.1). A NaN or
/// infinite delay is zero, as an unknown integral one is.
fn real_delay(
&mut self,
amount: &sv::ir::Expr,
precision: celox_sir::FloatPrecision,
steps_per_unit: u64,
) -> Result<RegisterId, sv::AnalyzerError> {
let scaled = if steps_per_unit > 1 {
sv::ir::Expr::Binary {
left: Box::new(amount.clone()),
op: sv::ir::BinaryOp::Mul,
right: Box::new(sv::ir::Expr::Literal(format!("{steps_per_unit}.0"))),
}
} else {
amount.clone()
};
let precision = self.m.expr_float_precision(&scaled).unwrap_or(precision);
let mut arena = SLTNodeArena::new();
let node = self.expr_slt(&scaled, None, &mut arena)?;
let node = floating::convert(
&mut arena,
node,
Some(precision),
None,
PROCESS_DELAY_WIDTH,
true,
true,
)
.ok_or_else(|| unsupported("real delay conversion"))?;
self.lower_slt(&arena, node)
}

/// `value` as a two-state register that is zero when `source` has an
/// unknown bit.
fn zero_if_unknown(&mut self, value: RegisterId, source: RegisterId) -> RegisterId {
Expand Down
9 changes: 9 additions & 0 deletions crates/celox-sv-analyzer/src/ast/procedural/timing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,13 @@ impl BodyBuilder<'_, '_, '_> {
return Ok(Stmt::Delay {
amount: Expr::Literal(format!("64'd{ticks}")),
ticks_per_unit: 1,
ticks_per_precision: 1,
});
}
Ok(Stmt::Delay {
amount: self.native_delay(*value, *parenthesized)?,
ticks_per_unit: timescales::time_divisor(*value, self.tree)?,
ticks_per_precision: timescales::precision_divisor(*value, self.tree)?,
})
}
TimingControlKind::Event(event) => {
Expand Down Expand Up @@ -87,6 +89,13 @@ impl BodyBuilder<'_, '_, '_> {
ExprKind::Literal(text) if text.chars().all(|c| c.is_ascii_digit() || c == '_') => {
Ok(Expr::Literal(text.replace('_', "")))
}
// A real_number delay value such as `#1.5` (A.2.2.3).
ExprKind::Literal(text)
if text.contains(['.', 'e', 'E'])
&& text.replace('_', "").parse::<f64>().is_ok() =>
{
Ok(Expr::Literal(text.replace('_', "")))
}
ExprKind::Name(name) => {
let mut result = Expr::Ident(instances::normalize_identifier(&name.spelling));
self.rename_expr(&mut result);
Expand Down
62 changes: 42 additions & 20 deletions crates/celox-sv-analyzer/src/ast/timescales.rs
Original file line number Diff line number Diff line change
Expand Up @@ -794,12 +794,24 @@ impl Timescales {
/// The time units of the simulation, which counts the global time
/// precision (3.14.3), in one time unit of the scope of `node`.
fn time_divisor_in_unit(&self, at: usize, unit: &Unit) -> u64 {
self.ticks_in(at, unit, |scale| scale.unit)
}

/// The time units of the simulation in one time precision step of the
/// scope of `node` (3.14.1).
fn precision_divisor_in_unit(&self, at: usize, unit: &Unit) -> u64 {
self.ticks_in(at, unit, |scale| scale.precision)
}

/// The time units of the simulation in `10^exponent(scale)` seconds,
/// where `scale` is the time scale of the scope at `at`.
fn ticks_in(&self, at: usize, unit: &Unit, exponent: impl Fn(&Scale) -> i32) -> u64 {
let scale =
scope_at(&unit.scopes, &unit.parents, at).map_or(unit.scale, |i| unit.scopes[i].scale);
let precision = self.precision.unwrap_or(DEFAULT.precision);
// A scope's precision is not coarser than its unit, and no unit is
// longer than 100 s or precision finer than 1 fs.
10u64.pow((scale.unit - precision.min(scale.precision)) as u32)
10u64.pow((exponent(&scale) - precision.min(scale.precision)) as u32)
}

fn resolve(
Expand Down Expand Up @@ -1009,27 +1021,37 @@ pub(super) fn time_divisor(
node: celox_sv_syntax::ExprId,
tree: &AnalysisContext<'_>,
) -> Converted<u64> {
divisor(node, tree, Timescales::time_divisor_in_unit)
}

/// The simulation's time units in one time precision step of the scope of
/// `node`, at which a real delay is rounded (3.14.1).
pub(super) fn precision_divisor(
node: celox_sv_syntax::ExprId,
tree: &AnalysisContext<'_>,
) -> Converted<u64> {
divisor(node, tree, Timescales::precision_divisor_in_unit)
}

fn divisor(
node: celox_sv_syntax::ExprId,
tree: &AnalysisContext<'_>,
in_unit: fn(&Timescales, usize, &Unit) -> u64,
) -> Converted<u64> {
let context = tree.state.timescales.design.borrow();
let at = tree.declarations().expression(node).tokens.start;
if let Some(prepared) = &context.prepared
&& prepared.address == tree.syntax_tree as *const SyntaxTree as usize
{
let context = tree.state.timescales.design.borrow();
if let Some(prepared) = &context.prepared
&& prepared.address == tree.syntax_tree as *const SyntaxTree as usize
{
return Ok(context.design.time_divisor_in_unit(
tree.declarations().expression(node).tokens.start,
&prepared.unit,
));
}
let design = &context.design;
let source = key(tree);
let extended = (!design.units.contains_key(&source))
.then(|| design.including_tree(tree))
.transpose()?;
let design = extended.as_ref().unwrap_or(design);
Ok(design.time_divisor_in_unit(
tree.declarations().expression(node).tokens.start,
&design.units[&source],
))
return Ok(in_unit(&context.design, at, &prepared.unit));
}
let design = &context.design;
let source = key(tree);
let extended = (!design.units.contains_key(&source))
.then(|| design.including_tree(tree))
.transpose()?;
let design = extended.as_ref().unwrap_or(design);
Ok(in_unit(design, at, &design.units[&source]))
}

/// A standalone time literal used as a delay: round at the declaring
Expand Down
5 changes: 5 additions & 0 deletions crates/celox-sv-analyzer/src/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,9 @@ pub enum StmtBase<E, L> {
amount: E,
/// Global-precision ticks in one time unit of the declaring scope.
ticks_per_unit: u64,
/// Global-precision ticks in one time precision step of the
/// declaring scope, to which a real amount is rounded (3.14.1).
ticks_per_precision: u64,
},
/// `@(items)`: suspend the process until one of the events occurs
/// (9.4.2).
Expand Down Expand Up @@ -304,9 +307,11 @@ impl<E, L> StmtBase<E, L> {
StmtBase::Delay {
amount,
ticks_per_unit,
ticks_per_precision,
} => StmtBase::Delay {
amount: fe(amount),
ticks_per_unit,
ticks_per_precision,
},
StmtBase::WaitEvent(items) => StmtBase::WaitEvent(
items
Expand Down
2 changes: 1 addition & 1 deletion crates/celox-sv-analyzer/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3509,7 +3509,6 @@ fn rejects_unimplemented_timing_constructs() {
"intra-assignment timing control",
),
("initial begin : b disable b; end", "disable statement"),
("initial #1.5;", "delay value"),
(
"logic a, y; always_latch y <= a;",
"nonblocking assignment inside always_latch",
Expand Down Expand Up @@ -6316,6 +6315,7 @@ fn time_literal_delays_accept_numeric_separators() {
let ir::Stmt::Delay {
amount,
ticks_per_unit,
..
} = &ir.modules()[0].initial_processes()[0].body()[0]
else {
panic!("delay");
Expand Down
50 changes: 50 additions & 0 deletions crates/celox-test-suite/src/sv/cases/timing.vtest
Original file line number Diff line number Diff line change
Expand Up @@ -1057,6 +1057,56 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev
(run_to_finish)
(assert_eq count 8))

(case real_delays_round_at_the_scope_precision
; IEEE 1800-2023 3.14.1: a delay is rounded at the scope's precision, here
; the default 1 ps, and 6.12.1 rounds a real tie away from zero: 0.0625 ns
; waits 63 ps. A NaN delay counts as zero, as Icarus 13.0 and Verilator
; 5.052 do.
(source "real_delays.sv" #"
module Top(output bit a_before, a_after, b_before, b_after, c_before,
c_after, d_after, e_before, e_after);
real r = 2.75, tie = 0.0625, zero = 0.0, nan;
shortreal quarter = 0.25;
bit a, b, c, d, e;
initial begin #r a = 1; end
initial begin #2749ps a_before = a; #2ps a_after = a; end
initial begin #3; #tie b = 1; end
initial begin #3062ps b_before = b; #2ps b_after = b; end
initial begin #5; #quarter c = 1; end
initial begin #5249ps c_before = c; #2ps c_after = c; end
initial begin nan = zero / zero; #6; #nan d = 1; end
initial begin #6001ps d_after = d; end
initial begin #7; #(r * 2) e = 1; end
initial begin #12499ps e_before = e; #2ps e_after = e; end
initial #20 $finish;
endmodule
"#)
(top Top)
(run_to_finish)
(assert_eq a_before 0)
(assert_eq a_after 1 "2.75 waits 2750 ps")
(assert_eq b_before 0)
(assert_eq b_after 1 "0.0625 waits 63 ps")
(assert_eq c_before 0)
(assert_eq c_after 1 "shortreal 0.25 waits 250 ps")
(assert_eq d_after 1 "a NaN delay waits zero")
(assert_eq e_before 0)
(assert_eq e_after 1 "r * 2 waits 5.5 ns"))

(case negative_real_delays_wait_their_twos_complement
; IEEE 1800-2023 9.4.1: a negative delay is read as a two's-complement
; unsigned time, so -1.5 waits about 2^64 precision steps.
(source "negative_real_delay.sv" #"
module Top(output bit woke);
real r = -1.5;
initial begin #r woke = 1; end
initial #10 $finish;
endmodule
"#)
(top Top)
(run_to_finish)
(assert_eq woke 0))

(case expression_events_see_pulses_within_a_time_slot
; IEEE 1800-2023 9.4.2: each change of the expression's value is an
; event, also one the slot undoes before it ends. The waits begin after
Expand Down
22 changes: 22 additions & 0 deletions crates/celox-test-suite/verification/sv/icarus/timing.json
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,17 @@
"tag_reasons": {},
"tags": []
},
{
"category": "Sequential",
"detail": "",
"expectation": "Simulation",
"name": "timing::negative_real_delays_wait_their_twos_complement",
"phase": "execute",
"status": "passed",
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
},
{
"category": "Sequential",
"detail": "",
Expand Down Expand Up @@ -584,6 +595,17 @@
"tag_reasons": {},
"tags": []
},
{
"category": "Sequential",
"detail": "",
"expectation": "Simulation",
"name": "timing::real_delays_round_at_the_scope_precision",
"phase": "execute",
"status": "passed",
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
},
{
"category": "Sequential",
"detail": "",
Expand Down
22 changes: 22 additions & 0 deletions crates/celox-test-suite/verification/sv/verilator/timing.json
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,17 @@
"tag_reasons": {},
"tags": []
},
{
"category": "Sequential",
"detail": "",
"expectation": "Simulation",
"name": "timing::negative_real_delays_wait_their_twos_complement",
"phase": "execute",
"status": "passed",
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
},
{
"category": "Sequential",
"detail": "",
Expand Down Expand Up @@ -584,6 +595,17 @@
"tag_reasons": {},
"tags": []
},
{
"category": "Sequential",
"detail": "",
"expectation": "Simulation",
"name": "timing::real_delays_round_at_the_scope_precision",
"phase": "execute",
"status": "passed",
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
},
{
"category": "Sequential",
"detail": "",
Expand Down
Loading
Loading