From eef1fe65381bd397cfc0587ef182686d486e517d Mon Sep 17 00:00:00 2001 From: tignear Date: Sun, 25 Oct 2026 22:57:36 +0900 Subject: [PATCH] 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を呼びます。