From eef1fe65381bd397cfc0587ef182686d486e517d Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 22:57:36 +0900 Subject: [PATCH 1/2] feat(cli): save state files at chosen cycles or times of a SystemVerilog run Refs #2025 Change-Id: Ib71719ee9f5f4d322b2b673915f907156e26e1a0 --- crates/celox-vpi/src/bin/celox.rs | 230 +++++++++++++++++++++++++++++- crates/celox-vpi/tests/run_cli.rs | 74 ++++++++++ crates/celox/src/simulation.rs | 10 ++ docs/guide/checkpoints.md | 4 + docs/guide/cocotb.md | 20 +++ docs/ja/guide/checkpoints.md | 2 + docs/ja/guide/cocotb.md | 14 ++ 7 files changed, 350 insertions(+), 4 deletions(-) diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index dce33a96a11..0f04453b598 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -32,6 +32,8 @@ struct Cli { } #[derive(Subcommand)] +// Parsed once per process; boxing would only complicate the matches. +#[allow(clippy::large_enum_variant)] enum CliCommand { /// Run a SystemVerilog or Veryl native testbench. Run(RunArgs), @@ -53,6 +55,41 @@ struct RunArgs { /// Does not bound compilation or work within a single step/tick. #[arg(long, value_parser = clap::value_parser!(u64).range(1..))] max_steps: Option, + + #[command(flatten)] + save_state: SaveStateArgs, +} + +/// When `celox run` saves state files for `celox state dump/diff`. +#[derive(Args, Clone, Default)] +struct SaveStateArgs { + /// Count the cycles of this signal for --save-state-at, such as + /// `tb.clk`: a cycle is a change of the signal to 1. + #[arg(long, value_name = "SIGNAL", requires = "save_state_at")] + save_state_on: Option, + /// Save the state after these cycles of --save-state-on, counted from 1. + #[arg( + long, + value_name = "N", + value_delimiter = ',', + requires = "save_state_on", + value_parser = clap::value_parser!(u64).range(1..) + )] + save_state_at: Vec, + /// Save the state at these simulation times (SystemVerilog), in units of + /// the design's global time precision. + #[arg(long, value_name = "T", value_delimiter = ',')] + save_state_at_time: Vec, + /// The directory of the saved files, `-.state` and + /// `time-.state` (default: the current directory). + #[arg(long, value_name = "DIR")] + save_state_dir: Option, +} + +impl SaveStateArgs { + fn is_empty(&self) -> bool { + self.save_state_on.is_none() && self.save_state_at_time.is_empty() + } } struct RunConfig { @@ -60,6 +97,7 @@ struct RunConfig { design: Design, opt_level: celox::OptLevel, max_steps: u64, + save_state: SaveStateArgs, } fn resolve_design(arguments: DesignArgs) -> Design { @@ -114,6 +152,7 @@ fn resolve_run_config(arguments: RunArgs) -> RunConfig { .or(design.max_steps) .unwrap_or(1_000_000), design, + save_state: arguments.save_state, } } @@ -137,6 +176,12 @@ fn run_testbench(arguments: RunArgs) -> Result<(), String> { { return Err("pass .sv/.v sources, or Veryl project sources".into()); } + if !arguments.save_state.is_empty() { + return Err( + "--save-state-on and --save-state-at-time currently require a SystemVerilog testbench" + .into(), + ); + } runner::run(arguments.execution, arguments.design, arguments.max_steps).map_err(|error| { if let runner::RunError::InvalidConfiguration { .. } = &error { clap::Error::raw(clap::error::ErrorKind::ArgumentConflict, error.to_string()).exit(); @@ -174,7 +219,8 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { .$build() .map_err(|error| format!("compilation failed:\n{error}"))?; report_warnings(simulation.warnings())?; - simulate_sv(simulation, max_steps, &mut std::io::stdout().lock()) + let saves = StateSaves::new(&simulation, &arguments.design.top, &arguments.save_state)?; + simulate_sv(simulation, max_steps, saves, &mut std::io::stdout().lock()) }}; } match arguments.execution.backend() { @@ -192,30 +238,206 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { fn simulate_sv( mut simulation: celox::Simulation, max_steps: u64, + mut saves: StateSaves, output: &mut impl Write, ) -> Result<(), String> { let mut failed = false; let initial = simulation.eval_comb(); drain_sv_output(&mut simulation, output, &mut failed)?; initial.map_err(|error| error.to_string())?; + saves.start(&mut simulation); let mut steps = 0; - while !simulation.is_finished() && simulation.next_event_time().is_some() { + while !simulation.is_finished() + && let Some(next) = simulation.next_event_time() + { if steps == max_steps { return Err(format!("simulation exceeded --max-steps {}", max_steps)); } + saves.before(&mut simulation, next)?; let step = simulation.step(); drain_sv_output(&mut simulation, output, &mut failed)?; if step.map_err(|error| error.to_string())?.is_none() { break; } + saves.after_step(&mut simulation)?; steps += 1; } + saves.finish(&mut simulation)?; if failed { return Err("SystemVerilog testbench reported an assertion failure or $error".to_string()); } Ok(()) } +/// The state files a SystemVerilog run saves (`--save-state-*`). +/// +/// A cycle of the counted signal is a time step at whose end the signal is +/// 1 while it was not at the end of the previous one (or after the initial +/// settle). Its file is saved right after that time step, with every region +/// of the time done. A file for time `T` holds the state after everything +/// due at times up to `T`, saved before the run advances past `T`. +#[cfg(feature = "systemverilog")] +#[derive(Default)] +struct StateSaves { + counted: Option<(String, celox::SignalRef)>, + /// The cycles still to save, in descending order. + cycles: Vec, + count: u64, + high: bool, + /// The times still to save, in descending order. + times: Vec, + directory: PathBuf, +} + +#[cfg(feature = "systemverilog")] +impl StateSaves { + fn new( + simulation: &celox::Simulation, + top: &str, + arguments: &SaveStateArgs, + ) -> Result { + let counted = match &arguments.save_state_on { + Some(path) => Some((path.clone(), resolve_signal_path(simulation, top, path)?)), + None => None, + }; + let descending = |values: &[u64]| { + let mut values = values.to_vec(); + values.sort_unstable_by(|a, b| b.cmp(a)); + values.dedup(); + values + }; + let directory = arguments + .save_state_dir + .clone() + .unwrap_or_else(|| PathBuf::from(".")); + if !arguments.is_empty() { + std::fs::create_dir_all(&directory) + .map_err(|error| format!("cannot create {}: {error}", directory.display()))?; + } + Ok(Self { + counted, + cycles: descending(&arguments.save_state_at), + count: 0, + high: false, + times: descending(&arguments.save_state_at_time), + directory, + }) + } + + fn level( + simulation: &mut celox::Simulation, + signal: celox::SignalRef, + ) -> bool { + let (value, mask) = simulation.get_four_state(signal); + value == 1u8.into() && mask == 0u8.into() + } + + fn start(&mut self, simulation: &mut celox::Simulation) { + if let Some((_, signal)) = self.counted { + self.high = Self::level(simulation, signal); + } + } + + /// Save the times before `next`, the time the next step runs. + fn before( + &mut self, + simulation: &mut celox::Simulation, + next: u64, + ) -> Result<(), String> { + while let Some(&time) = self.times.last() + && time < next + { + self.times.pop(); + self.save(simulation, format!("time-{time}.state"))?; + } + Ok(()) + } + + fn after_step( + &mut self, + simulation: &mut celox::Simulation, + ) -> Result<(), String> { + let Some((name, signal)) = &self.counted else { + return Ok(()); + }; + let (name, signal) = (name.clone(), *signal); + let high = Self::level(simulation, signal); + let rose = high && !self.high; + self.high = high; + if rose { + self.count += 1; + if self.cycles.last() == Some(&self.count) { + self.cycles.pop(); + self.save(simulation, format!("{name}-{}.state", self.count))?; + } + } + Ok(()) + } + + /// After the run: nothing changes any more, so the state at a later + /// time is the final one; a cycle not reached is an error. + fn finish( + &mut self, + simulation: &mut celox::Simulation, + ) -> Result<(), String> { + self.before(simulation, u64::MAX)?; + if let Some(cycle) = self.cycles.last() { + let (name, _) = self.counted.as_ref().expect("cycles count a signal"); + return Err(format!( + "the run ended after {} cycles of {name}, before cycle {cycle} of --save-state-at", + self.count + )); + } + Ok(()) + } + + fn save( + &self, + simulation: &mut celox::Simulation, + name: String, + ) -> Result<(), String> { + let path = self.directory.join(name); + let state = simulation + .save_state() + .map_err(|error| format!("cannot save {}: {error}", path.display()))?; + let mut bytes = Vec::new(); + state + .write_to(&mut bytes) + .and_then(|()| std::fs::write(&path, bytes)) + .map_err(|error| format!("cannot write {}: {error}", path.display())) + } +} + +/// Resolve `path`, a hierarchical signal name such as `tb.cpu.clk` or +/// `cpu[1].clk`, which may start with the top module's name. +#[cfg(feature = "systemverilog")] +fn resolve_signal_path( + simulation: &celox::Simulation, + top: &str, + path: &str, +) -> Result { + let mut segments: Vec<&str> = path.split('.').collect(); + if segments.len() > 1 && segments[0] == top { + segments.remove(0); + } + let var = segments.pop().unwrap_or_default(); + let instances = segments + .iter() + .map( + |segment| match segment.strip_suffix(']').and_then(|s| s.split_once('[')) { + Some((name, index)) => index + .parse() + .map(|index| (name, index)) + .map_err(|_| format!("invalid instance index in `{path}`")), + None => Ok((*segment, 0)), + }, + ) + .collect::, _>>()?; + simulation + .try_child_signal(&instances, var) + .map_err(|error| format!("--save-state-on {path}: {error}")) +} + #[cfg(feature = "systemverilog")] fn drain_sv_output( simulation: &mut celox::Simulation, @@ -924,7 +1146,7 @@ mod tests { .unwrap(); simulation.add_clock("clk", 2, 1); let mut output = Vec::new(); - let error = simulate_sv(simulation, 3, &mut output).unwrap_err(); + let error = simulate_sv(simulation, 3, StateSaves::default(), &mut output).unwrap_err(); assert!(error.contains("exceeded --max-steps 3")); assert!(String::from_utf8(output).unwrap().contains("tick")); } @@ -943,7 +1165,7 @@ mod tests { .build() .unwrap(); let mut output = Vec::new(); - let result = simulate_sv(simulation, 10, &mut output); + let result = simulate_sv(simulation, 10, StateSaves::default(), &mut output); (result, String::from_utf8(output).unwrap()) }; let (result, output) = run("$info"); diff --git a/crates/celox-vpi/tests/run_cli.rs b/crates/celox-vpi/tests/run_cli.rs index 9947d41f80c..1c7365115b8 100644 --- a/crates/celox-vpi/tests/run_cli.rs +++ b/crates/celox-vpi/tests/run_cli.rs @@ -636,3 +636,77 @@ fn interface_array_query_policy_flows_through_manifest_and_cli_overrides() { } } } + +#[cfg(feature = "systemverilog")] +#[test] +fn sv_saves_state_files_at_cycles_and_times() { + let source = "`timescale 1ns/1ns +module Top; + logic clk = 0; + logic [7:0] count = 0; + always #5 clk = ~clk; + always_ff @(posedge clk) count <= count + 8'd1; + initial #100 $finish; +endmodule +"; + let states = tempfile::tempdir().unwrap(); + let directory = states.path().to_str().unwrap(); + for backend in ["tiered", "interpreter", "native"] { + let output = run( + &[("top.sv", source)], + &[ + "--backend", + backend, + "--save-state-on", + "Top.clk", + "--save-state-at", + "2,5", + "--save-state-at-time", + "32", + "--save-state-dir", + directory, + ], + ); + assert!(output.status.success(), "{backend}: {output:?}"); + // Cycle N is the N-th rising edge of clk, at 10N - 5; the file holds + // the state after that time step, its nonblocking updates included. + for (file, time, count) in [ + ("Top.clk-2.state", 15, 2), + ("Top.clk-5.state", 45, 5), + // Time 32 has no activity; the state is that after time 30. + ("time-32.state", 30, 3), + ] { + let dump = std::process::Command::new(env!("CARGO_BIN_EXE_celox")) + .args(["state", "dump"]) + .arg(states.path().join(file)) + .output() + .unwrap(); + assert!(dump.status.success(), "{backend} {file}: {dump:?}"); + let text = String::from_utf8_lossy(&dump.stdout); + assert!( + text.contains(&format!("count[8] = {count:02x}\n")), + "{backend} {file}:\n{text}" + ); + assert!( + text.contains(&format!("time: {time}\n")), + "{backend} {file}:\n{text}" + ); + } + } + let output = run( + &[("top.sv", source)], + &[ + "--save-state-on", + "clk", + "--save-state-at", + "50", + "--save-state-dir", + directory, + ], + ); + assert_eq!(output.status.code(), Some(1), "{output:?}"); + assert!( + String::from_utf8_lossy(&output.stderr).contains("before cycle 50"), + "{output:?}" + ); +} diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 2bcd39299f2..967e6da71b4 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -1103,6 +1103,16 @@ impl Simulation { self.simulator.child_signal(instance_path, var) } + /// Like [`Self::child_signal`], returning an error for a path that does + /// not resolve. + pub fn try_child_signal( + &self, + instance_path: &[(&str, usize)], + var: &str, + ) -> Result { + self.simulator.try_child_signal(instance_path, var) + } + /// Registers a clock signal by event ID. /// /// Invalid IDs and IDs that do not resolve to events are ignored for diff --git a/docs/guide/checkpoints.md b/docs/guide/checkpoints.md index e1b762c5d19..36a22fb532d 100644 --- a/docs/guide/checkpoints.md +++ b/docs/guide/checkpoints.md @@ -141,6 +141,10 @@ celox state dump before_failure.state celox state diff native.state interpreter.state ``` +`celox run` saves state files at chosen cycles or times of a SystemVerilog run +with `--save-state-on`, `--save-state-at` and `--save-state-at-time` (see +[the command line](cocotb.md#save-state-files-during-a-systemverilog-run)). + `diff` exits with status 1 when the files differ. Both commands skip combinational signals unless you pass `--comb`. Dead store elimination at `O2` leaves unread combinational signals unwritten, so their saved values are diff --git a/docs/guide/cocotb.md b/docs/guide/cocotb.md index ba8bae593a9..713f6c42825 100644 --- a/docs/guide/cocotb.md +++ b/docs/guide/cocotb.md @@ -72,6 +72,26 @@ safe point while preserving pending events. For example: celox run test/Top.sv --top Top --backend tiered --threads 4 ``` +### Save state files during a SystemVerilog run + +To compare two runs or two simulators, `celox run` can save +[state files](checkpoints.md#state-files) for `celox state dump` and `celox state diff`: + +| Options | Purpose | +| --- | --- | +| `--save-state-on SIGNAL` | Count the cycles of `SIGNAL`, a hierarchical path such as `tb.clk` (the top module's name may be left out). A cycle is a time step at whose end the signal is 1 while it was not at the end of the previous time step. | +| `--save-state-at N[,M...]` | Save the state after cycles N, M, ... of `--save-state-on`, counted from 1, as `-.state`. The file is written right after that time step, with every region of the time done, so its nonblocking updates are included. | +| `--save-state-at-time T[,U...]` | Save the state after everything due at times up to T, before the run advances past T, as `time-.state`. T is in units of the design's global time precision. | +| `--save-state-dir DIR` | Write the files to `DIR` (default: the current directory). | + +A cycle that the run never reaches is an error. These options are available for +SystemVerilog testbenches on every backend. + +```sh +celox run c906.v --top tb --save-state-on tb.clk --save-state-at 1000,2000 --save-state-dir states +celox state diff states/tb.clk-1000.state other/tb.clk-1000.state +``` + For Veryl native testbenches it also provides: | Options | Purpose | diff --git a/docs/ja/guide/checkpoints.md b/docs/ja/guide/checkpoints.md index addac63cba6..3da2f5e7098 100644 --- a/docs/ja/guide/checkpoints.md +++ b/docs/ja/guide/checkpoints.md @@ -125,6 +125,8 @@ celox state dump before_failure.state celox state diff native.state interpreter.state ``` +SystemVerilog の実行中に、指定したサイクルや時刻で状態ファイルを保存するには `celox run` の `--save-state-on`、`--save-state-at`、`--save-state-at-time` を使います([コマンドライン](cocotb.md)を参照)。 + `diff` は、ファイルに差があると終了コード 1 で終わります。 どちらのコマンドも、`--comb` を付けない限り組み合わせ回路の信号を表示しません。 `O2` の dead store elimination は、どこからも読まれない組み合わせ回路の信号を書かないので、その信号の保存値は古いままになっているためです。 diff --git a/docs/ja/guide/cocotb.md b/docs/ja/guide/cocotb.md index c06aefbe3c4..b2318bdef50 100644 --- a/docs/ja/guide/cocotb.md +++ b/docs/ja/guide/cocotb.md @@ -66,6 +66,20 @@ celox run test/Top.veryl --top Top --four-state celox run --project /path/to/veryl-project --top smoke --report --unlimited ``` +SVのtestbenchでは、実行中に[状態ファイル](checkpoints.md#状態ファイル)を保存して +`celox state dump`/`celox state diff`で2つの実行やシミュレーターを比較できます(全バックエンド対応)。 +`--save-state-on SIGNAL`で数える信号(`tb.clk`のような階層パス、トップモジュール名は省略可)を指定し、 +`--save-state-at N[,M...]`で保存するサイクル(1から数える)を指定します。 +サイクルは、終了時に信号が1で、直前のタイムステップの終了時には1でなかったタイムステップです。 +ファイル`-.state`はそのタイムステップの全リージョンが終わった直後に書くので、ノンブロッキング代入の更新も含みます。 +`--save-state-at-time T[,U...]`は時刻T以前の処理をすべて終え、Tを越えて進む前の状態を`time-.state`に保存します(単位はデザインのグローバル時間精度)。 +`--save-state-dir DIR`で出力先を指定します(既定はカレントディレクトリ)。 +実行が指定のサイクルに達しなかった場合はエラーです。 + +```sh +celox run c906.v --top tb --save-state-on tb.clk --save-state-at 1000,2000 --save-state-dir states +``` + Veryl用の`--report`は設定・コンパイル時間・実行時間・tiered昇格統計・結果を 機械可読な`CELOX_*`レコードとして標準出力に出します。通常実行では出しません。 Heliodorベンチも専用Celoxバイナリではなく、このCLIを呼びます。 From 6db33adff2feab12482a768e923e4e864abbba09 Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 22:30:50 +0900 Subject: [PATCH 2/2] perf(sv): publish only the written elements of an array another process writes A process's nonblocking writes to an unpacked array that another process also writes, such as a testbench loading a RAM through hierarchical references, are staged in a value and a mask plane so that the other process's writes in between survive (IEEE 1800-2023 10.4.2). Their merge looped over every element on every edge, and every evaluation reset the whole mask plane. On rtlmeter C906 that is 16 x 524288 element merges per clock edge, 4.6 s per edge on the interpreter. When each nonblocking write of such an array is a select that runs at most once an evaluation (none is in a loop, a concatenation, a whole-array or a slice write), each write now also records the bit range it wrote and that it ran. The merge publishes only the elements those ranges cover and clears their mask bits, so an edge costs its writes. Elements another write already merged find their mask clear, and an out-of-range write marked no mask bits. Other arrays merge every element as before. Closes #2020 Change-Id: Iaa55fbe4ea0ab9588872ac23384812d151dba56a --- crates/celox-frontend-sv/src/lowering/ff.rs | 325 ++++++++++++++++-- .../sv/cases/hierarchical_references.vtest | 56 +++ .../systemverilog/hierarchical_references.rs | 3 + 3 files changed, 360 insertions(+), 24 deletions(-) diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index d399b4a9628..7c9c153da7c 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -4362,13 +4362,43 @@ impl<'p, 'a> Ff<'p, 'a> { value_name, mask, mask_name, + sites: None, } }) .collect(); + // Publish only the elements an array's nonblocking writes wrote, so + // an edge costs its writes rather than the whole array. + let mut staged = staged; + if self.kernel.is_none() && !self.direct { + for stage in &mut staged { + if self.m.var(stage.id).array_dims.is_empty() { + continue; + } + let Some(count) = array_nba_site_count(body, stage.id, self.m) else { + continue; + }; + let sites = (0..count) + .map(|_| { + let (lsb, lsb_name) = self.m.temp("nba_lsb", 64, false, false); + let (msb, msb_name) = self.m.temp("nba_msb", 64, false, false); + let (hit, hit_name) = self.m.temp("nba_hit", 1, false, false); + NbaArraySite { + lsb, + lsb_name, + msb, + msb_name, + hit, + hit_name, + } + }) + .collect(); + stage.sites = Some(sites); + } + } let body = if staged.is_empty() { body.to_vec() } else { - stage_nonblocking(body, &staged, self.m) + stage_nonblocking(body, &staged, self.m, &mut HashMap::default()) }; // A variable staged for an exact publication has no next state of // its own: only its merge publishes it. A shared variable is written @@ -4390,6 +4420,8 @@ impl<'p, 'a> Ff<'p, 'a> { 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 if stage.sites.is_some() { + // The merge clears the mask bits it published. } else { // Nothing writes the mask's stable state, which stays zero; // a store may not span the elements of an array. @@ -4552,6 +4584,87 @@ struct NbaStage { value_name: String, mask: SourceVarId, mask_name: String, + /// For an unpacked array, the sites of its nonblocking writes, when each + /// runs at most once an evaluation: the merge then publishes only the + /// elements they wrote. Without them every element is merged. + sites: Option>, +} + +/// A nonblocking write of a staged unpacked array: the bit range it wrote, +/// in the array's flattened bits, and whether it ran. +struct NbaArraySite { + lsb: SourceVarId, + lsb_name: String, + msb: SourceVarId, + msb_name: String, + hit: SourceVarId, + hit_name: String, +} + +/// The number of nonblocking writes of the unpacked array `id` in `stmts`, +/// when each is a select [`stage_nonblocking`] stages and none is in a loop, +/// so that each runs at most once an evaluation. +fn array_nba_site_count( + stmts: &[sv::ir::Stmt], + id: SourceVarId, + pm: &ProcModule<'_>, +) -> Option { + let writes = |stmt: &sv::ir::Stmt| { + let mut found = false; + stmt.walk(&mut |stmt| match stmt { + sv::ir::Stmt::Assign { + lhs, + nonblocking: true, + .. + } => found |= pm.id(lhs.name()) == Some(id), + sv::ir::Stmt::AssignConcat { + parts, + nonblocking: true, + .. + } => found |= parts.iter().any(|part| pm.id(part.name()) == Some(id)), + _ => {} + }); + found + }; + let mut count = 0; + for stmt in stmts { + match stmt { + sv::ir::Stmt::Assign { + lhs, + nonblocking: true, + .. + } if pm.id(lhs.name()) == Some(id) => match lhs { + sv::ir::LValue::Select { + msb, + lsb, + array_slice_width: None, + .. + } if expr_from_const_expr(msb).is_some() && expr_from_const_expr(lsb).is_some() => { + count += 1; + } + _ => return None, + }, + sv::ir::Stmt::If { + then_body, + else_body, + .. + } => { + count += array_nba_site_count(then_body, id, pm)?; + count += array_nba_site_count(else_body, id, pm)?; + } + sv::ir::Stmt::Case { items, default, .. } => { + for item in items { + count += array_nba_site_count(&item.body, id, pm)?; + } + if let Some(default) = default { + count += array_nba_site_count(default, id, pm)?; + } + } + other if writes(other) => return None, + _ => {} + } + } + Some(count) } /// `stmts` with every nonblocking assignment to a staged variable writing @@ -4560,6 +4673,7 @@ fn stage_nonblocking( stmts: &[sv::ir::Stmt], staged: &[NbaStage], pm: &ProcModule<'_>, + next_site: &mut HashMap, ) -> Vec { let stage_of = |lvalue: &sv::ir::LValue| { staged @@ -4596,6 +4710,29 @@ fn stage_nonblocking( nonblocking: true, } if stage_of(lhs).is_some() => { let stage = stage_of(lhs).unwrap(); + if let (Some(sites), sv::ir::LValue::Select { msb, lsb, .. }) = (&stage.sites, lhs) + { + let index = next_site.entry(stage.id).or_default(); + let site = &sites[*index]; + *index += 1; + let record = |name: &str, rhs: sv::ir::Expr| sv::ir::Stmt::Assign { + lhs: sv::ir::LValue::Ident(name.to_string()), + rhs, + nonblocking: false, + }; + out.push(record( + &site.lsb_name, + expr_from_const_expr(lsb).expect("a staged site's bounds are expressions"), + )); + out.push(record( + &site.msb_name, + expr_from_const_expr(msb).expect("a staged site's bounds are expressions"), + )); + out.push(record( + &site.hit_name, + sv::ir::Expr::Literal("1'b1".to_string()), + )); + } out.push(sv::ir::Stmt::Assign { lhs: renamed(lhs, &stage.value_name), rhs: rhs.clone(), @@ -4631,8 +4768,8 @@ fn stage_nonblocking( else_body, } => out.push(sv::ir::Stmt::If { condition: condition.clone(), - then_body: stage_nonblocking(then_body, staged, pm), - else_body: stage_nonblocking(else_body, staged, pm), + then_body: stage_nonblocking(then_body, staged, pm, next_site), + else_body: stage_nonblocking(else_body, staged, pm, next_site), }), sv::ir::Stmt::Case { kind, @@ -4646,12 +4783,12 @@ fn stage_nonblocking( .iter() .map(|item| sv::ir::CaseItem { labels: item.labels.clone(), - body: stage_nonblocking(&item.body, staged, pm), + body: stage_nonblocking(&item.body, staged, pm, next_site), }) .collect(), default: default .as_ref() - .map(|body| stage_nonblocking(body, staged, pm)), + .map(|body| stage_nonblocking(body, staged, pm, next_site)), }), sv::ir::Stmt::Loop { kind, @@ -4664,7 +4801,7 @@ fn stage_nonblocking( init: init.clone(), condition: condition.clone(), step: step.clone(), - body: stage_nonblocking(body, staged, pm), + body: stage_nonblocking(body, staged, pm, next_site), }), other => out.push(other.clone()), } @@ -4682,7 +4819,14 @@ fn emit_nba_merges(builder: &mut SIRBuilder, staged: &[NbaStage], pm: &Pro if let Some(element_width) = unpacked_element_width(variable).filter(|_| !variable.array_dims.is_empty()) { - emit_array_nba_merge(builder, stage, variable, element_width); + match &stage.sites { + Some(sites) => { + for site in sites { + emit_array_site_merge(builder, stage, site, variable, element_width); + } + } + None => emit_array_nba_merge(builder, stage, variable, element_width), + } continue; } let width = variable.width; @@ -4746,41 +4890,81 @@ 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( +/// [`emit_nba_merges`] for one write site of an unpacked array: when it ran, +/// a loop merges the elements its bit range covers, and clears their mask +/// bits and its hit for the next evaluation. Another site that wrote the +/// same element merged it already, and then finds its mask clear. +fn emit_array_site_merge( builder: &mut SIRBuilder, stage: &NbaStage, + site: &NbaArraySite, 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 hit = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Load( + hit, + working(site.hit), + SIROffset::Static(0), + 1, + )); + let first = builder.new_block(); + let done = builder.new_block(); + let next = builder.new_block(); + builder.seal_block(SIRTerminator::Branch { + cond: hit, + true_block: (first, Vec::new()), + false_block: (next, Vec::new()), + }); + + builder.switch_to_block(first); + let load = |builder: &mut SIRBuilder, id| { + let value = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Load( + value, + working(id), + SIROffset::Static(0), + 64, + )); + value }; - let first = builder.alloc_bit(64, false); - builder.emit(SIRInstruction::Imm(first, SIRValue::new(0u8))); + let lsb = load(builder, site.lsb); + let msb = load(builder, site.msb); + let reversed = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(reversed, msb, BinaryOp::LtU, lsb)); + let low = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Mux(low, reversed, msb, lsb)); + let high = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Mux(high, reversed, lsb, msb)); + let width = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Imm( + width, + SIRValue::new(element_width as u64), + )); + let start = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Binary(start, low, BinaryOp::DivU, width)); + let end = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Binary(end, high, BinaryOp::DivU, width)); 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.seal_block(SIRTerminator::Jump(header, vec![start])); builder.switch_to_block(header); let limit = builder.alloc_bit(64, false); builder.emit(SIRInstruction::Imm(limit, SIRValue::new(count as u64))); + let inside = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(inside, index, BinaryOp::LtU, limit)); + let covered = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Binary(covered, index, BinaryOp::LeU, end)); let more = builder.alloc_bit(1, false); - builder.emit(SIRInstruction::Binary(more, index, BinaryOp::LtU, limit)); + builder.emit(SIRInstruction::Binary(more, inside, BinaryOp::And, covered)); builder.seal_block(SIRTerminator::Branch { cond: more, true_block: (body, vec![index]), - false_block: (exit, Vec::new()), + false_block: (done, Vec::new()), }); builder.switch_to_block(body); @@ -4790,6 +4974,60 @@ fn emit_array_nba_merge( bit_offset: 0, dynamic_bit_offset: None, }; + emit_element_merge(builder, stage, variable, element_width, &offset); + let clear = builder.alloc_bit(element_width, false); + builder.emit(SIRInstruction::Imm(clear, SIRValue::new(0u8))); + builder.emit(SIRInstruction::Store( + working(stage.mask), + offset, + element_width, + clear, + Vec::new(), + Vec::new(), + )); + let one = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); + let following = builder.alloc_bit(64, false); + builder.emit(SIRInstruction::Binary( + following, + body_index, + BinaryOp::Add, + one, + )); + builder.seal_block(SIRTerminator::Jump(header, vec![following])); + + builder.switch_to_block(done); + let unset = builder.alloc_bit(1, false); + builder.emit(SIRInstruction::Imm(unset, SIRValue::new(0u8))); + builder.emit(SIRInstruction::Store( + working(site.hit), + SIROffset::Static(0), + 1, + unset, + Vec::new(), + Vec::new(), + )); + builder.seal_block(SIRTerminator::Jump(next, Vec::new())); + + builder.switch_to_block(next); +} + +/// Merge the staged nonblocking value of one element of an unpacked array +/// into its stable state, in the bits its mask marks. +fn emit_element_merge( + builder: &mut SIRBuilder, + stage: &NbaStage, + variable: &SvVariable, + element_width: usize, + offset: &SIROffset, +) { + let alloc = |builder: &mut SIRBuilder| { + if variable.is_4state { + builder.alloc_logic(element_width) + } else { + builder.alloc_bit(element_width, false) + } + }; let current = alloc(builder); builder.emit(SIRInstruction::Load( current, @@ -4821,12 +5059,51 @@ fn emit_array_nba_merge( builder.emit(SIRInstruction::Binary(merged, kept, BinaryOp::Or, taken)); builder.emit(SIRInstruction::Store( stable(stage.id), - offset, + offset.clone(), element_width, merged, Vec::new(), Vec::new(), )); +} + +/// [`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 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, + }; + emit_element_merge(builder, stage, variable, element_width, &offset); let one = builder.alloc_bit(64, false); builder.emit(SIRInstruction::Imm(one, SIRValue::new(1u8))); let next = builder.alloc_bit(64, false); diff --git a/crates/celox-test-suite/src/sv/cases/hierarchical_references.vtest b/crates/celox-test-suite/src/sv/cases/hierarchical_references.vtest index 6f9d257fce0..a37ebc973b3 100644 --- a/crates/celox-test-suite/src/sv/cases/hierarchical_references.vtest +++ b/crates/celox-test-suite/src/sv/cases/hierarchical_references.vtest @@ -83,6 +83,62 @@ (run_to_finish) (expect_output "q=8616\nlo2=ef hi2=be hi7=80\nq=be5a\n")) +; An array a process writes by nonblocking element writes and another +; process writes through hierarchical names publishes only the elements +; written: in the same step, the other process's writes stay in the bits a +; nonblocking write did not write, and a nonblocking write to the same bits +; lands after them; an out-of-range write writes nothing (IEEE 1800-2023 +; 7.4.5, 10.4.2). +(case nonblocking_element_writes_keep_hierarchical_writes_of_the_same_step + (source "site_merge.sv" #" + module Ram(input logic clk, input logic [1:0] op, input logic [4:0] addr, + input logic [7:0] d, output logic [7:0] q); + logic [7:0] mem [15:0]; + always @(posedge clk) begin + case (op) + 2'd1: mem[addr] <= d; + 2'd2: mem[addr][3:0] <= d[3:0]; + default: q <= mem[addr]; + endcase + end + endmodule + module Top; + logic clk = 0; + logic [1:0] op = 0; + logic [4:0] addr = 0; + logic [7:0] d = 0; + logic [7:0] q; + integer i; + Ram ram(.clk(clk), .op(op), .addr(addr), .d(d), .q(q)); + task automatic step; + #5 clk = 1; + #5 clk = 0; + endtask + initial begin + for (i = 0; i < 16; i = i + 1) ram.mem[i] = 8'hb0 + i; + op = 1; addr = 2; d = 8'h5a; + #5 clk = 1; ram.mem[3] = 8'hc3; #5 clk = 0; + op = 2; addr = 4; d = 8'h0e; + #5 clk = 1; ram.mem[4][7:4] = 4'h9; #5 clk = 0; + op = 1; addr = 7; d = 8'h77; + #5 clk = 1; ram.mem[7] = 8'h11; #5 clk = 0; + op = 1; addr = 20; d = 8'hee; + step(); + op = 0; + for (i = 0; i < 9; i = i + 1) begin + addr = i; + step(); + $display("%0d=%h", i, q); + end + $display("15=%h", ram.mem[15]); + $finish; + end + endmodule + "#) + (top Top) + (run_to_finish) + (expect_output "0=b0\n1=b1\n2=5a\n3=c3\n4=9e\n5=b5\n6=b6\n7=77\n8=b8\n15=bf\n")) + ; A component may name an element of an instance array or an instance of a ; generate block. (case names_instance_array_elements_and_generated_instances diff --git a/crates/celox/tests/frontends/systemverilog/hierarchical_references.rs b/crates/celox/tests/frontends/systemverilog/hierarchical_references.rs index 828aca9bfa2..aefd0000696 100644 --- a/crates/celox/tests/frontends/systemverilog/hierarchical_references.rs +++ b/crates/celox/tests/frontends/systemverilog/hierarchical_references.rs @@ -7,6 +7,9 @@ sv_backends! { fn writes_memory_elements_of_instances_below(sim) { @case "hierarchical_references::writes_memory_elements_of_instances_below"; } + fn nonblocking_element_writes_keep_hierarchical_writes_of_the_same_step(sim) { + @case "hierarchical_references::nonblocking_element_writes_keep_hierarchical_writes_of_the_same_step"; + } fn names_instance_array_elements_and_generated_instances(sim) { @case "hierarchical_references::names_instance_array_elements_and_generated_instances"; }