diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 765af0db277..c1972fb7545 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1112,6 +1112,144 @@ fn edge_only_memories( .collect() } +/// The variables a process kernel of `module` may write after it first +/// suspends. Such a write can land between the evaluation of an edge +/// process and the NBA region that publishes its nonblocking assignments: +/// an inactive-region resumption (`#0`), or a process a domain's observed +/// blocking result wakes (IEEE 1800-2023 4.4.2.4, 4.5). The code before the +/// first suspension of an `initial` runs at time zero before any domain +/// evaluates, so its writes, such as memory initialization, are not +/// included. +/// +/// These are the writers within `module`. A writer outside it (a +/// hierarchical reference) that can write after it suspends has to be added +/// here. +fn kernel_window_writes(module: &sv::ir::Module) -> HashSet { + let subroutines = module.subroutines(); + let mut names = HashSet::default(); + for process in module + .initial_processes() + .iter() + .filter(|process| !process.is_initializer()) + { + let body = process.body(); + let first = if process.repeats() { + 0 + } else { + body.iter() + .position(|stmt| stmt_may_suspend(subroutines, stmt)) + .unwrap_or(body.len()) + }; + kernel_written_names( + subroutines, + &body[first..], + &mut names, + &mut HashSet::default(), + 0, + ); + } + names +} + +/// Whether `stmt` may suspend its process: a timing control, or a call of a +/// task, in it or in a subroutine it calls. +fn stmt_may_suspend(subroutines: &[sv::ir::Subroutine], stmt: &sv::ir::Stmt) -> bool { + let mut found = false; + let mut calls = Vec::new(); + stmt.walk(&mut |stmt| { + found |= matches!( + stmt, + sv::ir::Stmt::Delay { .. } | sv::ir::Stmt::WaitEvent(_) | sv::ir::Stmt::Wait(_) + ); + procedural::stmt_calls(stmt, &mut calls); + }); + let mut visited = HashSet::default(); + while !found && let Some((callee, args)) = calls.pop() { + let sv::ir::Callee::Subroutine(name) = callee else { + continue; + }; + let Some(subroutine) = subroutines + .iter() + .find(|subroutine| subroutine.name == name) + else { + continue; + }; + found |= subroutine.is_task; + procedural::default_calls(subroutine, &args, &mut calls); + if visited.insert(name) { + for stmt in &subroutine.body { + stmt.walk(&mut |stmt| procedural::stmt_calls(stmt, &mut calls)); + } + } + } + found +} + +/// Adds the names of the variables `body` writes, directly or in the +/// subroutines it calls, to `names` (see [`DriverScan`]). +fn kernel_written_names( + subroutines: &[sv::ir::Subroutine], + body: &[sv::ir::Stmt], + names: &mut HashSet, + visited: &mut HashSet, + depth: usize, +) { + if depth > procedural::MAX_CALL_DEPTH { + return; + } + let mut calls = Vec::new(); + for stmt in body { + stmt.walk(&mut |stmt| { + match stmt { + sv::ir::Stmt::Assign { lhs, .. } => { + names.insert(lhs.name().to_string()); + } + sv::ir::Stmt::AssignConcat { parts, .. } => { + names.extend(parts.iter().map(|part| part.name().to_string())); + } + sv::ir::Stmt::SystemTask { task, args, .. } => { + if let Some(destination) = procedural::readmem_destination(*task, args) { + names.insert(destination.to_string()); + } + } + _ => {} + } + procedural::stmt_calls(stmt, &mut calls); + }); + } + while let Some((callee, args)) = calls.pop() { + let name = match callee { + sv::ir::Callee::System(function) => { + names.extend( + procedural::written_system_arguments(function, &args) + .iter() + .map(|lvalue| lvalue.name().to_string()), + ); + continue; + } + sv::ir::Callee::String(_) | sv::ir::Callee::Object(_) => continue, + sv::ir::Callee::Subroutine(name) => name, + }; + let Some(subroutine) = subroutines + .iter() + .find(|subroutine| subroutine.name == name) + else { + continue; + }; + procedural::default_calls(subroutine, &args, &mut calls); + for (param, arg) in subroutine.params.iter().zip(&args) { + if param.direction.is_written() + && let Some(lvalues) = arg.as_ref().and_then(procedural::lvalue_from_expr) + { + names.extend(lvalues.iter().map(|lvalue| lvalue.name().to_string())); + } + } + if visited.insert(name) { + kernel_written_names(subroutines, &subroutine.body, names, visited, depth + 1); + } + } +} + fn validate_variable_driver_ranges( module: &sv::ir::Module, constants: &HashMap, @@ -8490,6 +8628,7 @@ fn lower_ff_processes( } let edge_memories = edge_only_memories(module, pm.constants, pm.parameter_types); + let window_writes = kernel_window_writes(module); let random_seeds = process_random_seeds(module); for ((index, process), events) in module.ff_processes().iter().enumerate().zip(process_events) { let mut events = events @@ -8517,6 +8656,7 @@ fn lower_ff_processes( } = ff::Ff::new(pm, random_seeds[&(0, index)]) .with_sparse_memories(shared_memories) .with_sparse_candidates(&edge_memories) + .with_window_writes(&window_writes) .lower_process(process.body())?; repeated_writes.extend(repeated_ff_writes(&eval_only, &staged)); // A process without writes still runs for its runtime events and diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 61296800342..243ddfad3c1 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -48,6 +48,9 @@ pub(super) struct Ff<'p, 'a> { /// Variables written other than at a constant range or one element of /// an unpacked array, which a sparse publication does not support. other_writes: HashSet, + /// Variables a process kernel may write between the evaluation of this + /// process and the NBA region (see `kernel_window_writes`). + window_writes: HashSet, b: SIRBuilder, /// Variables read from the working region. working: HashSet, @@ -120,6 +123,7 @@ impl<'p, 'a> Ff<'p, 'a> { sparse_candidates: HashSet::default(), element_writes: HashSet::default(), other_writes: HashSet::default(), + window_writes: HashSet::default(), b: SIRBuilder::new(), working: HashSet::default(), nonblocking: HashSet::default(), @@ -164,6 +168,11 @@ impl<'p, 'a> Ff<'p, 'a> { self } + pub fn with_window_writes(mut self, names: &HashSet) -> Self { + self.window_writes = names.iter().filter_map(|name| self.m.id(name)).collect(); + self + } + /// Where a write of `id`, and a read of a value the process wrote, go: /// the working region, or stable state in a process kernel. fn target(&self, id: SourceVarId) -> Addr { @@ -251,6 +260,44 @@ impl<'p, 'a> Ff<'p, 'a> { self.targets.push((id, access)); } + /// The variables the subroutines `body` calls assign, directly or + /// through further calls. + fn subroutine_assignments(&self, body: &[sv::ir::Stmt]) -> HashSet { + let mut calls = Vec::new(); + for stmt in body { + stmt.walk(&mut |stmt| stmt_calls(stmt, &mut calls)); + } + let mut assigned = HashSet::default(); + let mut visited = HashSet::default(); + while let Some((callee, args)) = calls.pop() { + let sv::ir::Callee::Subroutine(name) = callee else { + continue; + }; + let Some(subroutine) = self.m.subroutine(&name) else { + continue; + }; + default_calls(subroutine, &args, &mut calls); + if !visited.insert(name) { + continue; + } + for stmt in &subroutine.body { + stmt.walk(&mut |stmt| { + match stmt { + sv::ir::Stmt::Assign { lhs, .. } => { + assigned.extend(self.m.id(lhs.name())); + } + sv::ir::Stmt::AssignConcat { parts, .. } => { + assigned.extend(parts.iter().filter_map(|part| self.m.id(part.name()))); + } + _ => {} + } + stmt_calls(stmt, &mut calls); + }); + } + } + assigned + } + /// Collect the variables a body writes, following calls into subroutines. fn scan(&mut self, stmts: &[sv::ir::Stmt], visited: &mut HashSet) { let mut writes: Vec<(sv::ir::LValue, bool)> = Vec::new(); @@ -3966,6 +4013,25 @@ impl<'p, 'a> Ff<'p, 'a> { ) -> Result { let mut visited = HashSet::default(); self.scan(body, &mut visited); + // A variable only this process's nonblocking assignments write here, + // and that a process kernel may write before they are published, + // takes only the bits they wrote: the kernel's write stays in the + // others, even when no assignment executed (IEEE 1800-2023 10.4.2). + // Staging rewrites the assignments of the body; a variable a called + // subroutine assigns keeps its whole next state. + let called = self.subroutine_assignments(body); + let exact: HashSet = self + .nonblocking + .iter() + .copied() + .filter(|id| { + self.window_writes.contains(id) + && !called.contains(id) + && !self.working.contains(id) + && !self.m.is_hidden(*id) + && !self.sparse_memories.contains(id) + }) + .collect(); // Publish only the written elements of an array this process alone // updates by nonblocking element writes, rather than seeding and // committing all of it on every edge. The element stores keep @@ -3977,6 +4043,7 @@ impl<'p, 'a> Ff<'p, 'a> { .copied() .filter(|id| { self.element_writes.contains(id) + && !exact.contains(id) && !self.working.contains(id) && !self.other_writes.contains(id) && !self.m.is_hidden(*id) @@ -4024,6 +4091,7 @@ impl<'p, 'a> Ff<'p, 'a> { .intersection(&self.working) .copied() .filter(|&id| !self.m.is_hidden(id) && self.m.var(id).array_dims.is_empty()) + .chain(exact.iter().copied()) .collect(); mixed.sort_by_key(|id| id.0); let staged: Vec = mixed @@ -4046,7 +4114,14 @@ impl<'p, 'a> Ff<'p, 'a> { } else { stage_nonblocking(body, &staged, self.m) }; - let ordinary_targets: Vec<_> = targets + // A variable staged for an exact publication has no next state of + // its own: only its merge publishes it. + let published: Vec<_> = targets + .iter() + .copied() + .filter(|target| !exact.contains(&target.id)) + .collect(); + let ordinary_targets: Vec<_> = published .iter() .copied() .filter(|target| !self.sparse_memories.contains(&target.id)) @@ -4054,9 +4129,21 @@ impl<'p, 'a> Ff<'p, 'a> { emit_ff_seeds(&mut self.b, &ordinary_targets); for stage in &staged { let width = self.m.var(stage.mask).width; - let zero = self.b.alloc_bit(width, false); - self.b.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); - self.store(stage.mask, SIROffset::Static(0), width, zero); + if self.m.var(stage.id).array_dims.is_empty() { + let zero = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Imm(zero, SIRValue::new(0u8))); + self.store(stage.mask, SIROffset::Static(0), width, zero); + } else { + // Nothing writes the mask's stable state, which stays zero; + // a store may not span the elements of an array. + self.b.emit(SIRInstruction::Commit( + stable(stage.mask), + working(stage.mask), + SIROffset::Static(0), + width, + Vec::new(), + )); + } } if self.exec_block(&body)? { self.b.seal_block(SIRTerminator::Return); @@ -4078,14 +4165,14 @@ impl<'p, 'a> Ff<'p, 'a> { } } } - let (active_targets, nba_targets): (Vec<_>, Vec<_>) = targets + let (active_targets, nba_targets): (Vec<_>, Vec<_>) = published .iter() .copied() .partition(|target| self.working.contains(&target.id)); let mut apply = SIRBuilder::new(); emit_sparse_memory_commits( &mut apply, - &targets, + &published, &self.sparse_memories, self.m.variables, ); @@ -4328,6 +4415,12 @@ fn emit_nba_merges(builder: &mut SIRBuilder, staged: &[NbaStage], pm: &Pro for stage in staged { let _ = &stage.name; let variable = pm.var(stage.id); + if let Some(element_width) = + unpacked_element_width(variable).filter(|_| !variable.array_dims.is_empty()) + { + emit_array_nba_merge(builder, stage, variable, element_width); + continue; + } let width = variable.width; let current = if variable.is_4state { builder.alloc_logic(width) @@ -4389,6 +4482,96 @@ fn emit_nba_merges(builder: &mut SIRBuilder, staged: &[NbaStage], pm: &Pro } } +/// [`emit_nba_merges`] for an unpacked array: a loop merges each element, +/// since an access may not span elements. +fn emit_array_nba_merge( + builder: &mut SIRBuilder, + stage: &NbaStage, + variable: &SvVariable, + element_width: usize, +) { + let count = variable.width / element_width; + let four_state = variable.is_4state; + let alloc = |builder: &mut SIRBuilder| { + if four_state { + builder.alloc_logic(element_width) + } else { + builder.alloc_bit(element_width, false) + } + }; + let first = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Imm(first, SIRValue::new(0u8))); + let index = builder.alloc_bit(64, false); + let header = builder.new_block_with(vec![index]); + let body_index = builder.alloc_bit(64, false); + let body = builder.new_block_with(vec![body_index]); + let exit = builder.new_block(); + builder.seal_block(SIRTerminator::Jump(header, vec![first])); + + builder.switch_to_block(header); + let limit = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Imm(limit, SIRValue::new(count as u64))); + let more = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(more, index, BinaryOp::LtU, limit)); + builder.seal_block(SIRTerminator::Branch { + cond: more, + true_block: (body, vec![index]), + false_block: (exit, Vec::new()), + }); + + builder.switch_to_block(body); + let offset = SIROffset::Element { + index: body_index, + element_width, + bit_offset: 0, + dynamic_bit_offset: None, + }; + let current = alloc(builder); + builder.emit(SIRInstruction::Load( + current, + stable(stage.id), + offset.clone(), + element_width, + )); + let value = alloc(builder); + builder.emit(SIRInstruction::Load( + value, + working(stage.value), + offset.clone(), + element_width, + )); + let mask = builder.alloc_bit(element_width, false); + builder.emit(SIRInstruction::Load( + mask, + working(stage.mask), + offset.clone(), + element_width, + )); + let keep = builder.alloc_bit(element_width, false); + builder.emit(SIRInstruction::Unary(keep, UnaryOp::BitNot, mask)); + let kept = alloc(builder); + builder.emit(SIRInstruction::Binary(kept, current, BinaryOp::And, keep)); + let taken = alloc(builder); + builder.emit(SIRInstruction::Binary(taken, value, BinaryOp::And, mask)); + let merged = alloc(builder); + builder.emit(SIRInstruction::Binary(merged, kept, BinaryOp::Or, taken)); + builder.emit(SIRInstruction::Store( + stable(stage.id), + offset, + element_width, + merged, + Vec::new(), + Vec::new(), + )); + let one = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); + let next = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Binary(next, body_index, BinaryOp::Add, one)); + builder.seal_block(SIRTerminator::Jump(header, vec![next])); + + builder.switch_to_block(exit); +} + impl Ff<'_, '_> { /// Lower an `initial` body into a process kernel that runs it from time /// zero, reading and writing stable state directly. diff --git a/crates/celox-test-suite/src/sv/cases/timing.vtest b/crates/celox-test-suite/src/sv/cases/timing.vtest index 500208661ae..9391d4b7673 100644 --- a/crates/celox-test-suite/src/sv/cases/timing.vtest +++ b/crates/celox-test-suite/src/sv/cases/timing.vtest @@ -2462,3 +2462,106 @@ module Top(input bit clk,output bit[7:0]seen);bit q;Child c(clk,q);initial forev (assert_eq q 0) (assert_eq m0 0) (assert_eq m1 0)) + +(case edge_nonblocking_updates_keep_later_writes_of_other_bits + ; An edge process evaluates, then a zero-delay resumption writes the same + ; variables before the NBA region (IEEE 1800-2023 4.4.2.4). The + ; nonblocking updates change only the bits they assign (10.4.2): the + ; resumption's writes to other bits, elements and variables stay, also + ; where no assignment executed, and an update of the same bits wins. + (source "nba_window.sv" #" + module Top(output logic [31:0] m0, m2, m3, m5, q, r); + bit clk = 1'b0; + bit en = 1'b0; + bit [3:0] i = 4'd0; + bit [4:0] k = 5'd3; + bit [31:0] mem [16]; + bit [31:0] q_, r_; + always #5 clk = ~clk; + always @(posedge clk) begin + mem[i][15:8] <= 8'h44; + mem[i + 2] <= 32'h11; + if (en) q_ <= 32'h11; + r_[k] <= 1'b1; + end + initial begin + for (int j = 0; j < 16; j++) mem[j] = 0; + q_ = 0; + r_ = 0; + @(posedge clk); + #0; + mem[0][7:0] = 8'h22; + mem[2][31:24] = 8'h77; + mem[3] = 32'h33; + mem[5][7:0] = 8'h55; + q_ = 32'h66; + r_[20] = 1'b1; + end + assign m0 = mem[0]; + assign m2 = mem[2]; + assign m3 = mem[3]; + assign m5 = mem[5]; + assign q = q_; + assign r = r_; + endmodule + "#) + (top Top) + (run_until 6) + (assert_eq m0 0x4422) + (assert_eq m2 0x11) + (assert_eq m3 0x33) + (assert_eq m5 0x55) + (assert_eq q 0x66 "no nonblocking assignment to q executed") + (assert_eq r 0x100008)) + +(case edge_nonblocking_updates_follow_writes_their_blocking_results_wake + ; The edge process's blocking result wakes a waiting process in the + ; active region, before the NBA region (IEEE 1800-2023 4.5). Its write + ; stays where no nonblocking assignment executed. + (source "nba_active_window.sv" #" + module Top(output logic [7:0] q, output logic [7:0] p); + bit clk = 1'b0; + bit flag = 1'b0; + bit en = 1'b0; + bit [7:0] q_ = 8'd0, p_ = 8'd0; + always #5 clk = ~clk; + always @(posedge clk) begin + flag = 1'b1; + if (en) q_ <= 8'h11; + p_ <= 8'h44; + end + initial begin + @(posedge flag); + q_ = 8'h22; + p_ = 8'h33; + end + assign q = q_; + assign p = p_; + endmodule + "#) + (top Top) + (run_until 6) + (assert_eq q 0x22) + (assert_eq p 0x44 "the nonblocking update is later")) + +(case edge_blocking_results_precede_later_process_writes + ; A blocking assignment of an edge process takes effect when it executes: + ; a zero-delay resumption that writes the variable afterwards, without + ; reading it, leaves its own value. + (source "blocking_window.sv" #" + module Top(output logic [7:0] t); + bit clk = 1'b0; + bit [7:0] t_ = 8'd0; + always #5 clk = ~clk; + always @(posedge clk) t_ = 8'h11; + initial begin + @(posedge clk); + #0; + t_ = 8'h22; + end + assign t = t_; + endmodule + "#) + (top Top) + (run_until 6) + (assert_eq t 0x22)) diff --git a/crates/celox/tests/frontends/systemverilog/timing.rs b/crates/celox/tests/frontends/systemverilog/timing.rs index 83bcaca0f58..2ab8a3bccde 100644 --- a/crates/celox/tests/frontends/systemverilog/timing.rs +++ b/crates/celox/tests/frontends/systemverilog/timing.rs @@ -776,6 +776,20 @@ sv_backends! { } } +sv_backends! { + fn edge_nonblocking_updates_keep_later_writes_of_other_bits(sim) { + @case "timing::edge_nonblocking_updates_keep_later_writes_of_other_bits"; + } + + fn edge_nonblocking_updates_follow_writes_their_blocking_results_wake(sim) { + @case "timing::edge_nonblocking_updates_follow_writes_their_blocking_results_wake"; + } + + fn edge_blocking_results_precede_later_process_writes(sim) { + @case "timing::edge_blocking_results_precede_later_process_writes"; + } +} + /// An edge whose evaluation a `$fatal` ends before its commit leaves no /// held write of a watched variable behind: when the host continues, the /// later edges rewrite `y[0]` to its own value and wake no waiter.