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
3 changes: 2 additions & 1 deletion crates/celox-frontend-sv/src/lowering/comb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3469,7 +3469,8 @@ impl<'p, 'a> Comb<'p, 'a> {
} else {
None
};
let (template, values) = system_task_template(self.m, &kind, args);
let (template, mut values) = system_task_template(self.m, &kind, args);
prepare_time_operands(self.m, template.as_deref(), &mut values)?;
let mut captured = Vec::with_capacity(values.len());
let mut arg_widths = Vec::with_capacity(values.len());
let mut arg_signed = Vec::with_capacity(values.len());
Expand Down
3 changes: 2 additions & 1 deletion crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2894,7 +2894,8 @@ impl<'p, 'a> Ff<'p, 'a> {
} else {
None
};
let (template, values) = system_task_template(self.m, &kind, args);
let (template, mut values) = system_task_template(self.m, &kind, args);
prepare_time_operands(self.m, template.as_deref(), &mut values)?;
let mut regs = Vec::with_capacity(values.len());
let mut arg_widths = Vec::with_capacity(values.len());
let mut arg_signed = Vec::with_capacity(values.len());
Expand Down
3 changes: 2 additions & 1 deletion crates/celox-frontend-sv/src/lowering/ff/file_io.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,8 @@ impl Ff<'_, '_> {
SystemTask::Fdisplay(radix) | SystemTask::Fwrite(radix) => {
let descriptor = self.file_io_arg(&args[0])?;
let kind = SystemTaskKind::Print(RuntimeEventKind::Write, radix.letter());
let (template, args) = system_task_template(self.m, &kind, &args[1..]);
let (template, mut args) = system_task_template(self.m, &kind, &args[1..]);
prepare_time_operands(self.m, template.as_deref(), &mut args)?;
let mut values = vec![descriptor];
for arg in &args {
values.push(self.file_io_arg(arg)?);
Expand Down
73 changes: 73 additions & 0 deletions crates/celox-frontend-sv/src/lowering/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1250,6 +1250,79 @@ fn template_arguments(template: &str) -> usize {
count
}

/// Prepare each value that a `%t` of `template` converts. A system task
/// argument is self-determined (IEEE 1800-2023 11.6.1, 21.2.1), so the
/// operand of the analyzer's scaling `value * factor` keeps its own width
/// and signedness. A `string` value has no time value, and Celox would print
/// its storage handle: it is rejected, as Verilator rejects it, while Icarus
/// prints the conversion unformatted.
pub(super) fn prepare_time_operands(
module: &ProcModule<'_>,
template: Option<&str>,
values: &mut [sv::ir::SystemTaskArg<sv::ir::Expr>],
) -> Result<(), sv::AnalyzerError> {
let Some(template) = template else {
return Ok(());
};
let mut chars = template.chars().peekable();
let mut index = 0;
while let Some(ch) = chars.next() {
if ch != '%' {
continue;
}
while chars
.next_if(|ch| matches!(ch, '-' | '+' | ' ' | '#' | '0'))
.is_some()
{}
while chars.next_if(char::is_ascii_digit).is_some() {}
if chars.next_if_eq(&'.').is_some() {
while chars.next_if(char::is_ascii_digit).is_some() {}
}
let Some(spec) = chars.next() else {
break;
};
if !"bBoOhHxXdDiIcCsStTeEfFgG".contains(spec) {
continue;
}
if matches!(spec, 't' | 'T')
&& let Some(sv::ir::SystemTaskArg::Expr(expr)) = values.get_mut(index)
{
if module.expr_is_string(expr) {
return Err(unsupported("string operand of a %t conversion"));
}
// The analyzer scales a %t value as `value * factor`.
if let sv::ir::Expr::Binary {
left,
op: sv::ir::BinaryOp::Mul,
..
} = expr
{
if module.expr_is_string(left) {
return Err(unsupported("string operand of a %t conversion"));
}
if module.expr_float_precision(left).is_none()
&& let Some(width) = sv_expr_natural_width(
&module.typed_calls(left),
module.variables,
module.name_to_id,
module.constants,
module.parameter_types,
)
{
let signed = module.expr_signed(left);
**left = sv::ir::Expr::Resize {
expr: left.clone(),
width,
signed,
};
}
}
}
index += 1;
}
Ok(())
}

/// The message template and value arguments of a system task: a leading
/// string literal is the template. `$fatal` first takes a finish number.
/// A `$display` or `$write` argument without a conversion of its own is
Expand Down
90 changes: 90 additions & 0 deletions crates/celox-sv-analyzer/src/ast/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1327,6 +1327,24 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> {
Ok(SystemTaskArg::Expr(value))
})
.collect::<Result<Vec<_>, AnalyzerError>>()?;
let mut args = args;
// A string literal that %t converts is bound as a value: the binder
// handles every literal form, triple quotes and escapes included.
let mut bind = |index: usize| -> Result<Option<Expr>, AnalyzerError> {
let Some(id) = arguments.get(index).and_then(|arg| arg.value) else {
return Ok(None);
};
let mut value =
expression_binding::bind_value(id, declarations, self.tree, &self.dims, None)?;
self.rename_expr(&mut value);
Ok(Some(value))
};
scale_time_conversions(
task,
&mut args,
timescales::time_divisor(root, self.tree)?,
&mut bind,
)?;
// Keep Veryl's assertion calls as calls: their message arguments
// execute even on success, unlike an SV assertion's fail action.
Ok(vec![Stmt::SystemTask {
Expand Down Expand Up @@ -2866,6 +2884,78 @@ pub(super) fn process_site(
})
}

/// `%t` reports a time value in the units of `$timeformat`, by default the
/// smallest time precision of the design (IEEE 1800-2023 20.4.3, Table 20-3),
/// in which the simulation counts its time. The value is in the time unit of
/// the calling scope, of which `ticks_per_unit` simulation time units make
/// one, so each value a `%t` of the template converts is scaled by it.
fn scale_time_conversions(
task: SystemTask,
args: &mut [SystemTaskArg<Expr>],
ticks_per_unit: u64,
bind: &mut impl FnMut(usize) -> Result<Option<Expr>, AnalyzerError>,
) -> Result<(), AnalyzerError> {
if ticks_per_unit == 1 {
return Ok(());
}
let template = match task {
SystemTask::Display(_) | SystemTask::Write(_) | SystemTask::Severity(_) => 0,
SystemTask::Fatal => usize::from(matches!(args.first(), Some(SystemTaskArg::Expr(_)))),
SystemTask::Fdisplay(_)
| SystemTask::Fwrite(_)
| SystemTask::Assert
| SystemTask::AssertContinue => 1,
_ => return Ok(()),
};
let Some(SystemTaskArg::Str(text)) = args.get(template) else {
return Ok(());
};
// The conversions of the template, in the order they take arguments
// (21.2.1.2): flags, a width and a precision may precede each.
let mut conversions = Vec::new();
let mut chars = text.chars().peekable();
while let Some(ch) = chars.next() {
if ch != '%' {
continue;
}
while chars
.next_if(|ch| matches!(ch, '-' | '+' | ' ' | '#' | '0'))
.is_some()
{}
while chars.next_if(char::is_ascii_digit).is_some() {}
if chars.next_if_eq(&'.').is_some() {
while chars.next_if(char::is_ascii_digit).is_some() {}
}
if let Some(spec) = chars.next()
&& "bBoOhHxXdDiIcCsStTeEfFgG".contains(spec)
{
conversions.push(spec);
}
}
for (offset, spec) in conversions.into_iter().enumerate() {
if !matches!(spec, 't' | 'T') {
continue;
}
let index = template + 1 + offset;
// A string literal converts as its packed bytes (5.9). The factor is
// signed, so the product keeps the signedness of the value (11.8.1).
let value = match args.get(index) {
Some(SystemTaskArg::Expr(value)) => value.clone(),
Some(SystemTaskArg::Str(_)) => match bind(index)? {
Some(value) => value,
None => continue,
},
Some(SystemTaskArg::Empty) | None => continue,
};
args[index] = SystemTaskArg::Expr(Expr::Binary {
left: Box::new(value),
op: BinaryOp::Mul,
right: Box::new(Expr::Literal(format!("64'sd{ticks_per_unit}"))),
Comment thread
tignear marked this conversation as resolved.
Resolved
});
}
Ok(())
}

/// Original invocation span of a native token range, when it belongs to one file.
pub(super) fn source_span(
tokens: celox_sv_syntax::TokenRange,
Expand Down
67 changes: 67 additions & 0 deletions crates/celox-test-suite/src/sv/cases/system_functions.vtest
Original file line number Diff line number Diff line change
Expand Up @@ -2386,6 +2386,7 @@ endmodule

(case time_format_consumes_its_expression_argument
(source "time_format.sv" #"
`timescale 1ns/1ns
module Top(input logic clk);
always_ff @(posedge clk) begin
$display("t:[%t] d:[%d]", 32'd7, 8'shfe);
Expand All @@ -2397,6 +2398,72 @@ endmodule
(tick clk)
(expect_output "t:[ 7] d:[ -2]\nsmall:[17] padded:[ 9] next:[af] %t\n"))

; Without `$timeformat`, %t reports a time in the smallest time precision of
; the design, in a field of 20 columns (IEEE 1800-2023 20.4.3, Table 20-3):
; a value in the time unit of its scope is scaled to it. Timed cases run at
; 1 ns / 1 ps.
(case time_format_defaults_to_the_smallest_precision
(source "time_format_default.sv" #"
module Top;
int n = 7;
initial begin
#1.5;
$display("[%t] [%0t] [%0t] [%0t] [%0d]", $time, $time, $realtime, n, $time);
$write("w=%0t\n", $realtime);
$finish;
end
endmodule
"#)
(top Top)
(run_to_finish)
(expect_output "[ 2000] [2000] [1500] [7000] [2]\nw=1500\n"))

; The smallest precision of all the design's time scales sets the unit of
; %t in every scope.
(case time_format_scales_each_scope_to_the_smallest_precision
(source "time_format_scopes.sv" #"
`timescale 1ns/1ps
module Top(input logic clk);
Child child(.clk);
always_ff @(posedge clk) $display("top [%0t] [%t]", 32'd7, 8'd3);
endmodule
`timescale 1us/1us
module Child(input logic clk);
always_ff @(posedge clk) $display("child [%0t]", 32'd2);
endmodule
"#)
(top Top)
(tick clk)
(expect_output "top [7000] [ 3000]\nchild [2000000]\n"))

; A string literal that %t converts is its packed bytes (IEEE 1800-2023 5.9),
; scaled like any other value.
(case time_format_scales_string_literals
(source "time_format_strings.sv" #"
`timescale 1ns/1ps
module Top(input logic clk);
always_ff @(posedge clk) $display("[%0t] [%t]", "A", "AB");
endmodule
"#)
(top Top)
(tick clk)
(expect_output "[65000] [ 16706000]\n"))

; A value that %t converts is self-determined (IEEE 1800-2023 11.6.1, 21.2.1):
; it is evaluated at its own width before it is scaled.
(case time_format_values_are_self_determined
(source "time_format_self_determined.sv" #"
`timescale 1ns/1ps
module Top(input logic clk);
logic [7:0] a = 8'hff;
logic [3:0] b = 4'd9, c = 4'd8;
always_ff @(posedge clk) $display("[%0t] [%0t] [%0t]", a + 8'd1, b + c, {b, c});
endmodule
"#)
(top Top)
(tick clk)
(expect_output "[0] [1000] [152000]\n"))

(case string_literals_follow_numeric_format_specifiers
(source "string_format.sv" #"
module Top(input logic clk);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1575,6 +1575,50 @@
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
},
{
"category": "Functions",
"detail": "",
"expectation": "Simulation",
"name": "system_functions::time_format_defaults_to_the_smallest_precision",
"phase": "execute",
"status": "passed",
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
},
{
"category": "Functions",
"detail": "",
"expectation": "Simulation",
"name": "system_functions::time_format_scales_each_scope_to_the_smallest_precision",
"phase": "execute",
"status": "passed",
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
},
{
"category": "Functions",
"detail": "",
"expectation": "Simulation",
"name": "system_functions::time_format_scales_string_literals",
"phase": "execute",
"status": "passed",
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
},
{
"category": "Functions",
"detail": "",
"expectation": "Simulation",
"name": "system_functions::time_format_values_are_self_determined",
"phase": "execute",
"status": "passed",
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -876,6 +876,50 @@
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
},
{
"category": "Functions",
"detail": "",
"expectation": "Simulation",
"name": "system_functions::time_format_defaults_to_the_smallest_precision",
"phase": "execute",
"status": "passed",
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
},
{
"category": "Functions",
"detail": "",
"expectation": "Simulation",
"name": "system_functions::time_format_scales_each_scope_to_the_smallest_precision",
"phase": "execute",
"status": "passed",
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
},
{
"category": "Functions",
"detail": "",
"expectation": "Simulation",
"name": "system_functions::time_format_scales_string_literals",
"phase": "execute",
"status": "passed",
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
},
{
"category": "Functions",
"detail": "",
"expectation": "Simulation",
"name": "system_functions::time_format_values_are_self_determined",
"phase": "execute",
"status": "passed",
"stronger_than_sv": false,
"tag_reasons": {},
"tags": []
}
]
}
Loading
Loading