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
51 changes: 46 additions & 5 deletions crates/celox-frontend-sv/src/lowering/ff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2263,6 +2263,25 @@ impl<'p, 'a> Ff<'p, 'a> {
Ok(Expr::Ident(ret_name))
}

/// The value of `expr` now, in a temporary of its type.
fn keep_argument(&mut self, expr: &sv::ir::Expr) -> Result<sv::ir::Expr, sv::AnalyzerError> {
let signed = self.expr_signed(expr);
let float = floating::precision(expr, self.m.variables, self.m.name_to_id);
let handle = reads_string_variable(expr, self.m.variables, self.m.name_to_id);
let value = self.eval(expr, None)?;
let register = self.b.register(&value).clone();
let width = register.width();
let four_state = matches!(register, celox_sir::RegisterType::Logic { .. });
let (temp, name) = self.m.temp("task_argument", width, signed, four_state);
let variable = self.m.variables.get_mut(&temp).unwrap();
variable.float = float;
if handle {
variable.value_kind = celox_design::ValueKind::StrRef;
}
self.store(temp, SIROffset::Static(0), width, value);
Ok(sv::ir::Expr::Ident(name))
}

fn plusargs(
&mut self,
function: sv::ir::SystemFunction,
Expand Down Expand Up @@ -3216,6 +3235,32 @@ impl<'p, 'a> Ff<'p, 'a> {
};
let (template, mut values) = system_task_template(self.m, &kind, args);
prepare_time_operands(self.m, template.as_deref(), &mut values)?;
// Arguments are evaluated left to right. A later argument's call can
// change what an earlier one reads, or suspend the process (a host
// request) so that a value read before it would not survive the
// resume. So every argument before the last one with a call is
// evaluated whole into a temporary at its place; that one only has
// its calls run before its own reads, as any expression does.
let last_call = values.iter().rposition(
|value| matches!(value, sv::ir::SystemTaskArg::Expr(expr) if self.m.calls(expr)),
);
if let Some(last_call) = last_call {
for (index, value) in values[..=last_call].iter_mut().enumerate() {
let sv::ir::SystemTaskArg::Expr(expr) = value else {
continue;
};
let hoisted = if self.m.calls(expr) {
self.hoist(expr)?
} else {
expr.clone()
};
*expr = if index == last_call || matches!(hoisted, sv::ir::Expr::Literal(_)) {
hoisted
} else {
self.keep_argument(&hoisted)?
};
}
}
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 All @@ -3225,11 +3270,7 @@ impl<'p, 'a> Ff<'p, 'a> {
for value in &values {
match value {
sv::ir::SystemTaskArg::Expr(expr) => {
let expr = if self.m.calls(expr) {
self.hoist(expr)?
} else {
expr.clone()
};
let expr = expr.clone();
let signed = self.expr_signed(&expr);
arg_is_handle.push(reads_string_variable(
&expr,
Expand Down
164 changes: 155 additions & 9 deletions crates/celox-frontend-sv/src/lowering/procedural.rs
Original file line number Diff line number Diff line change
Expand Up @@ -373,26 +373,116 @@ impl<'a> ProcModule<'a> {
names.iter().filter_map(|name| self.id(name)).collect()
}

/// Whether `always @(items) body` is `always @* body`: no item has an edge
/// or a select, the items name exactly the variables the implicit event
/// expression of `body` has (IEEE 1800-2023 9.4.2.2), and the body neither
/// suspends nor makes a nonblocking assignment, directly or in a call.
/// Whether `always @(items) body` simulates like `always @* body`. The
/// body must neither suspend nor make a nonblocking assignment, directly
/// or in a call. Then either
/// - the items name exactly the variables the implicit event expression
/// of `body` has (IEEE 1800-2023 9.4.2.2), a part-select of a whole
/// variable naming it, or
/// - the items cover every bit `body` reads, and running `body` when
/// none of those bits changed is unobservable: it has no side effects,
/// reads no variable it writes, and stores each variable at most once
/// per run, so it writes the values it wrote last time without
/// pulsing a variable for the waiters on it (4.3, 9.4.2).
pub fn is_implicit_event_list(
&self,
items: &[sv::ir::EventItem],
body: &[sv::ir::Stmt],
) -> bool {
let mut listed = HashSet::default();
if self.suspends_or_defers(body) {
return false;
}
let mut listed: HashSet<VarAtomBase<SourceVarId>> = HashSet::default();
let mut exact = true;
for item in items {
let sv::ir::Expr::Ident(name) = &item.expr else {
return false;
let (name, range) = match &item.expr {
sv::ir::Expr::Ident(name) => (name, None),
sv::ir::Expr::Select {
expr: base,
msb,
lsb,
..
} => {
let sv::ir::Expr::Ident(name) = &**base else {
return false;
};
let Some(range) = sv::typecheck::eval_const_expr_with_types(
msb,
self.constants,
self.parameter_types,
)
.zip(sv::typecheck::eval_const_expr_with_types(
lsb,
self.constants,
self.parameter_types,
))
.and_then(|(msb, lsb)| {
packed_expr_select_offsets(base, msb, lsb, self.variables, self.name_to_id)
}) else {
return false;
};
(name, Some((range.0.min(range.1), range.0.max(range.1))))
}
_ => return false,
};
let Some(id) = self.id(name).filter(|id| !self.is_hidden(*id)) else {
return false;
};
listed.insert(VarAtomBase::new(id, 0, self.var(id).width - 1));
let width = self.var(id).width;
let (lsb, msb) = range.unwrap_or((0, width - 1));
exact &= lsb == 0 && msb == width - 1;
listed.insert(VarAtomBase::new(id, lsb, msb));
}
let reads = self.implicit_reads(body, false);
if exact && listed == reads {
return true;
}
if !self.is_pure(body) {
return false;
}
!self.suspends_or_defers(body) && listed == self.implicit_reads(body, false)
let mut written = HashSet::default();
written_names(body, &mut written);
let written: HashSet<_> = written
.iter()
.filter_map(|name| self.id(name))
.filter(|id| !self.is_hidden(*id))
.collect();
if reads.iter().any(|read| written.contains(&read.id)) {
return false;
}
if stores_twice(body, &mut HashSet::default()) {
return false;
}
// Longest static prefixes: constant selects keep their bits.
self.implicit_reads(body, true).iter().all(|read| {
(read.access.lsb..=read.access.msb).all(|bit| {
listed.iter().any(|item| {
item.id == read.id && item.access.lsb <= bit && bit <= item.access.msb
})
})
})
}

/// Whether `body` has no effect but its writes: no system task, no
/// subroutine call, no system function that reads the simulation.
fn is_pure(&self, body: &[sv::ir::Stmt]) -> bool {
let mut pure = true;
let mut calls = Vec::new();
for stmt in body {
stmt.walk(&mut |stmt| {
pure &= !matches!(
stmt,
sv::ir::Stmt::SystemTask { .. }
| sv::ir::Stmt::Eval(_)
| sv::ir::Stmt::Call { .. }
| sv::ir::Stmt::Return(_)
);
stmt_calls(stmt, &mut calls);
});
}
pure && calls.iter().all(|(callee, _)| {
matches!(callee, sv::ir::Callee::System(function) if !function.reads_simulation_state())
})
}

fn suspends_or_defers(&self, body: &[sv::ir::Stmt]) -> bool {
Expand Down Expand Up @@ -2606,6 +2696,62 @@ pub(super) fn expr_calls(expr: &sv::ir::Expr, is_callee: &dyn Fn(&sv::ir::Callee
}

/// The names written by the assignments (and through call arguments) of a
/// Whether a run of `stmts` may store a variable twice, given the variables
/// `written` on some path before them. Locals are not variables of the
/// design, and a loop counts as storing twice.
fn stores_twice(stmts: &[sv::ir::Stmt], written: &mut HashSet<String>) -> bool {
let mut locals = HashSet::default();
stores_twice_in(stmts, written, &mut locals)
}

fn stores_twice_in(
stmts: &[sv::ir::Stmt],
written: &mut HashSet<String>,
locals: &mut HashSet<String>,
) -> bool {
for stmt in stmts {
match stmt {
sv::ir::Stmt::Local { name, .. } => {
locals.insert(name.clone());
}
sv::ir::Stmt::Assign { .. } | sv::ir::Stmt::AssignConcat { .. } => {
let mut names = HashSet::default();
written_names(std::slice::from_ref(stmt), &mut names);
for name in names {
if !locals.contains(&name) && !written.insert(name) {
return true;
}
}
}
sv::ir::Stmt::If {
then_body,
else_body,
..
} => {
let mut other = written.clone();
if stores_twice_in(then_body, written, locals)
|| stores_twice_in(else_body, &mut other, locals)
{
return true;
}
written.extend(other);
}
sv::ir::Stmt::Case { items, default, .. } => {
let before = written.clone();
for body in items.iter().map(|item| &item.body).chain(default.iter()) {
let mut branch = before.clone();
if stores_twice_in(body, &mut branch, locals) {
return true;
}
written.extend(branch);
}
}
_ => return true,
}
}
false
}

/// statement list.
pub(super) fn written_names(stmts: &[sv::ir::Stmt], names: &mut HashSet<String>) {
for stmt in stmts {
Expand Down
78 changes: 78 additions & 0 deletions crates/celox-test-suite/src/sv/cases/always_comb.vtest
Original file line number Diff line number Diff line change
Expand Up @@ -168,3 +168,81 @@
(run_to_finish)
(expect_output "1 7\n"))

; A sensitivity list that covers every bit its statement reads, through
; part-selects narrower than the variables, simulates like `always @*` when
; running the statement more often is unobservable: no side effects, no
; feedback, and each variable stored at most once per run (#2079). The
; untimed harness builds a `Simulator`, which runs no processes.
(case covering_sensitivity_lists_settle_like_a_wildcard
(source "covering_lists.sv" #"
module Top(input logic [7:0] x, input logic [3:0] s,
output logic [2:0] y, output logic [3:0] z);
always @(x[2:0]) y = x[2:0] + 3'd1;
always @(x[7:4] or s) begin
case (s)
4'd0: z = x[7:4];
default: z = ~x[7:4];
endcase
end
endmodule
"#)
(top Top)
(modify (set x 0x15) (set s 0))
(assert_eq y 6) (assert_eq z 1)
(modify (set x 0x35))
(assert_eq y 6) (assert_eq z 3)
(modify (set x 0x36) (set s 1))
(assert_eq y 7) (assert_eq z 0xc))

(case covering_sensitivity_lists_settle_like_a_wildcard_in_four_state
(source "covering_lists.sv" #"
module Top(input logic [7:0] x, input logic [3:0] s,
output logic [2:0] y, output logic [3:0] z);
always @(x[2:0]) y = x[2:0] + 3'd1;
always @(x[7:4] or s) begin
case (s)
4'd0: z = x[7:4];
default: z = ~x[7:4];
endcase
end
endmodule
"#)
(top Top)
(four_state)
(modify (set x 0x15) (set s 0))
(assert_eq y 6) (assert_eq z 1)
(modify (set x 0x35))
(assert_eq y 6) (assert_eq z 3)
(modify (set x 0x36) (set s 1))
(assert_eq y 7) (assert_eq z 0xc))

; A block with a covering list that stores a variable twice per run stays a
; process: run on a change of an unlisted bit, it would pulse `p` and wake
; the edge waiter (4.3, 9.4.2).
(case multi_store_blocks_with_covering_lists_stay_processes
(source "multi_store_list.sv" #"
module Top;
logic [7:0] x;
logic p;
int n;
always @(x[0]) begin
p = 1'b0;
if (x[0]) p = 1'b1;
end
initial n = 0;
always @(posedge p) n = n + 1;
initial begin
x = 8'h15;
#1 $display("%b %0d", p, n);
x = 8'h35;
#1 $display("%b %0d", p, n);
x = 8'h36;
#1 $display("%b %0d", p, n);
$finish;
end
endmodule
"#)
(top Top)
(run_to_finish)
(expect_output "1 1\n1 1\n0 1\n"))

12 changes: 12 additions & 0 deletions crates/celox/tests/frontends/systemverilog/always_comb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,15 @@ sv_backends! {
@case "always_comb::two_state_other_sensitivity_lists_run_at_time_zero";
}
}

sv_backends! {
fn covering_sensitivity_lists_settle_like_a_wildcard(sim) {
@case "always_comb::covering_sensitivity_lists_settle_like_a_wildcard";
}
fn covering_sensitivity_lists_settle_like_a_wildcard_in_four_state(sim) {
@case "always_comb::covering_sensitivity_lists_settle_like_a_wildcard_in_four_state";
}
fn multi_store_blocks_with_covering_lists_stay_processes(sim) {
@case "always_comb::multi_store_blocks_with_covering_lists_stay_processes";
}
}
Loading
Loading