From 3ad74a1a34e993da3b7e46f61cd541029ae75c59 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 20 Oct 2026 20:16:33 +0900 Subject: [PATCH] feat(sv)!: add source-driven VCD controls Support $dumpfile/$dumpvars/$dumpon/$dumpoff/$dumpall/$dumplimit/$dumpflush with source hierarchy and depth selection. Preserve waveform signals through optimization, propagate output errors and flush at simulation completion, including direct host API finishes. Enforce dump limits between complete header commands and value records, resume partially emitted headers before values, and rescan when limits relax. Flush old streams before reopening paths, report timed write failures, retain authored names, and apply source selections to component traces. Preserve on/off state changes while output is limited, resolve absolute $root selections, and keep package state outside module-recursive selections. Resolve escaped names, constant indexed hierarchy and explicit package-variable selections; reject source VCD tasks in untimed Simulator builds. Resolve imported package aliases, preserve source controls across output-file switches, retain terminal finish state on output failure, and publish pending diagnostic waveforms before returning fatal errors, including final run-until evaluation. Keep lexically resolved local dump targets distinct from same-named top modules. Accept omitted dump levels while retaining explicit selections, and decode dumpfile names through the shared packed-string binder. Focused VCD and mixed-family regressions pass, including error propagation, hierarchy selection and clocked processes. The completed tree also passes the recorded full unit/system-function, native image/checkpoint, Clippy, JavaScript and documentation checks. Regressions cover each reviewed output/selection failure, including deterministic activity-based limit resumption and injected traces, limited-output suspension, absolute hierarchy names, escaped/indexed hierarchy, explicit package selection and untimed-build rejection. Finish-output errors, fatal diagnostic output, restarted control state and imported-name shadowing have dedicated regressions. Header-command limit boundaries, omitted-depth package filtering and octal/multiline filenames have regressions. SV-only test helpers are gated so default-feature builds remain supported. Update the two newly passing dumpfile conformance rows from CI run 39413853030 (artifact 12262168735). BREAKING CHANGE: The public system-task catalog gains VCD variants; update exhaustive matches. Native images use format 19 for component-aware and lexically bound VCD selections and must be rebuilt. Designs with VCD system tasks cannot be checkpointed. Change-Id: Id407bf67945978820cbb54624814a47d2b66a8f1 --- conformance/sv-tests/expected.tsv | 4 +- crates/celox-frontend-sv/src/lowering/ff.rs | 80 ++ .../src/lowering/procedural.rs | 3 +- crates/celox-runtime/src/simulation/host.rs | 19 + crates/celox-runtime/src/simulation/mod.rs | 66 +- crates/celox-runtime/src/simulation/time.rs | 2 +- crates/celox-runtime/src/vcd.rs | 430 ++++++++- crates/celox-runtime/src/vcd/plan.rs | 17 + crates/celox-sv-analyzer/src/ast/packages.rs | 5 +- .../celox-sv-analyzer/src/ast/procedural.rs | 144 ++- crates/celox-sv-analyzer/src/ir.rs | 2 +- .../celox-sv-analyzer/src/system_functions.rs | 72 +- crates/celox/src/backend/native/image_file.rs | 2 +- crates/celox/src/component.rs | 86 ++ crates/celox/src/ir.rs | 6 + crates/celox/src/simulation.rs | 90 +- crates/celox/src/simulation/vcd_tasks.rs | 532 +++++++++++ crates/celox/src/simulator.rs | 30 +- crates/celox/src/simulator/builder.rs | 127 ++- crates/celox/src/simulator/checkpoint.rs | 11 +- .../systemverilog/system_functions.rs | 4 +- crates/celox/tests/sv_host_requests.rs | 52 +- crates/celox/tests/sv_vcd.rs | 902 ++++++++++++++++++ docs/guide/systemverilog-reference.md | 7 +- docs/guide/vcd.md | 27 + docs/ja/guide/systemverilog-reference.md | 5 +- docs/ja/guide/vcd.md | 26 + 27 files changed, 2636 insertions(+), 115 deletions(-) create mode 100644 crates/celox/src/simulation/vcd_tasks.rs create mode 100644 crates/celox/tests/sv_vcd.rs diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index b6bbf98b178..4e44a96be83 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -819,8 +819,8 @@ chapter-21/21.6--test.sv 2state pass chapter-21/21.6--test.sv 4state pass chapter-21/21.6--value.sv 2state pass chapter-21/21.6--value.sv 4state pass -chapter-21/21.7--dumpfile.sv 2state fail -chapter-21/21.7--dumpfile.sv 4state fail +chapter-21/21.7--dumpfile.sv 2state pass +chapter-21/21.7--dumpfile.sv 4state pass chapter-21/21.7--dumpports.sv 2state fail chapter-21/21.7--dumpports.sv 4state fail chapter-22/22.10--celldefine-basic-1.sv 2state skip diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 94bdcb8efe0..64b54726a4a 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -1130,6 +1130,82 @@ impl<'p, 'a> Ff<'p, 'a> { self.random.clone().expect("a process RNG") } + fn vcd_task( + &mut self, + operation: sv::ir::VcdTask, + args: &[sv::ir::SystemTaskArg], + ) -> Result<(), sv::AnalyzerError> { + use celox_design::{HostRequestKind, HostRequestSite, HostRequestValue}; + use sv::ir::VcdTask; + if self.kernel.is_none() { + return Err(unsupported("VCD tasks require a timed process")); + } + let mut values = Vec::new(); + let mut strings = Vec::new(); + for (index, arg) in args.iter().enumerate() { + if operation == VcdTask::Vars + && index == 0 + && matches!(arg, sv::ir::SystemTaskArg::Empty) + { + continue; + } + if operation == VcdTask::Vars && index > 0 { + let sv::ir::SystemTaskArg::Str(name) = arg else { + return Err(unsupported("$dumpvars module or variable selection")); + }; + strings.push(name.clone()); + continue; + } + let (reg, signed, is_string) = match arg { + sv::ir::SystemTaskArg::Expr(expr) => { + (self.eval(expr, None)?, self.expr_signed(expr), false) + } + sv::ir::SystemTaskArg::Str(text) if operation == VcdTask::File => { + let bytes = unescape(text).into_bytes(); + let width = (bytes.len() * 8).max(8); + let value = bytes.iter().fold(BigUint::zero(), |value, byte| { + (value << 8u32) | BigUint::from(*byte) + }); + let reg = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Imm(reg, SIRValue::new(value))); + (reg, false, true) + } + _ => { + return Err(unsupported( + "VCD argument must be an integral value or filename string", + )); + } + }; + let width = self.b.register(®).width(); + let is_4state = matches!(self.b.register(®), RegisterType::Logic { .. }); + let (id, _) = self.m.temp("vcd_argument", width, signed, is_4state); + self.store(id, SIROffset::Static(0), width, reg); + values.push(HostRequestValue { + id, + width, + signed, + is_string, + }); + } + let local_site = self + .host_request_sites + .iter() + .filter(|site| site.kind == HostRequestKind::Vcd) + .count() as u32; + self.host_request_sites.push(HostRequestSite { + process: self.process, + kind: HostRequestKind::Vcd, + requires_timed_simulation: false, + operation: operation as u32, + args: values, + results: Vec::new(), + strings, + }); + self.with_kernel(|kernel| kernel.host_request(HostRequestKind::Vcd, local_site)) + .map_err(|error| unsupported(error.to_string()))?; + Ok(()) + } + /// The seed of this process's `$random` calls without a seed argument. /// It starts at 0, as the seed variable of `$random(seed)` typically /// does, so a design whose one process calls `$random` gets the same @@ -2408,6 +2484,10 @@ impl<'p, 'a> Ff<'p, 'a> { args: &[sv::ir::SystemTaskArg], site: Option<&sv::ir::SourceSpan>, ) -> Result { + if let sv::ir::SystemTask::Vcd(operation) = task { + self.vcd_task(operation, args)?; + return Ok(true); + } if matches!( task, sv::ir::SystemTask::Fclose diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index bf02ad0e9f6..64778f14ca0 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -931,7 +931,8 @@ pub(super) fn system_task_kind(task: sv::ir::SystemTask) -> Option return None, + | SystemTask::Exit + | SystemTask::Vcd(_) => return None, }) } diff --git a/crates/celox-runtime/src/simulation/host.rs b/crates/celox-runtime/src/simulation/host.rs index d583777dca6..37a7f4aa3a7 100644 --- a/crates/celox-runtime/src/simulation/host.rs +++ b/crates/celox-runtime/src/simulation/host.rs @@ -56,6 +56,18 @@ pub trait HostBoundary: UnitExecutor { /// change its state. fn freeze(&mut self) {} + /// Publish buffered diagnostic output without ending or freezing execution. + fn flush_output(&mut self) -> Result<(), SimulatorErrorCode> { + Ok(()) + } + + /// Freeze after a design-requested finish, reporting output failures. + fn try_freeze(&mut self) -> Result<(), SimulatorErrorCode> { + let output = self.flush_output(); + self.freeze(); + output + } + /// Snapshot external-component inputs immediately before an event domain /// evaluates its sequential logic. fn stage_external_event( @@ -78,6 +90,13 @@ pub trait HostBoundary: UnitExecutor { /// Called after the state for a simulation timestamp has stabilized. fn finish_timed_step(&mut self, _timestamp: u64) {} + + /// Fallible timestamp boundary. The default preserves the original + /// infallible hook for existing executor implementations. + fn try_finish_timed_step(&mut self, timestamp: u64) -> Result<(), Halt> { + self.finish_timed_step(timestamp); + Ok(()) + } } /// Backend execution hooks needed by the timed simulation engine: its diff --git a/crates/celox-runtime/src/simulation/mod.rs b/crates/celox-runtime/src/simulation/mod.rs index 3c14ffee561..3fadd223888 100644 --- a/crates/celox-runtime/src/simulation/mod.rs +++ b/crates/celox-runtime/src/simulation/mod.rs @@ -189,17 +189,64 @@ impl SimulationState { match self.step_time(executor, limit) { Ok(time) => Ok(time), Err(Halt::Finish) => { - // The waveform records the state at the finish. - executor.finish_timed_step(self.scheduler.time); - self.finish(executor); + self.finalize_terminal(executor)?; Ok(Some(self.scheduler.time)) } // The time slot goes on when the simulation continues. Err(Halt::Stop) => Ok(Some(self.scheduler.time)), + Err(Halt::Error(error)) => { + // Preserve the primary runtime failure even if diagnostic + // waveform output also fails. This does not resume processes. + let _ = self.finish_timed_boundary(executor, self.scheduler.time); + let _ = executor.flush_output(); + Err(error) + } + } + } + + /// Complete a boundary reached from an entry point that returns runtime + /// errors rather than scheduler control halts. + fn finish_timed_boundary( + &mut self, + executor: &mut E, + time: u64, + ) -> Result<(), SimulatorErrorCode> + where + E: SimulationExecutor, + { + match executor.try_finish_timed_step(time) { + Ok(()) => Ok(()), Err(Halt::Error(error)) => Err(error), + Err(Halt::Finish) => { + self.finish_checked(executor)?; + Ok(()) + } + Err(Halt::Stop) => { + self.stopped = true; + Ok(()) + } } } + fn finish_checked(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> + where + E: SimulationExecutor, + { + self.finished = true; + executor.try_freeze() + } + + /// Once $finish is consumed, output errors must not make execution resumable. + pub fn finalize_terminal(&mut self, executor: &mut E) -> Result<(), SimulatorErrorCode> + where + E: SimulationExecutor, + { + self.finished = true; + let output = self.finish_timed_boundary(executor, self.scheduler.time); + let frozen = executor.try_freeze(); + output.and(frozen) + } + /// End the simulation where it is. pub fn finish(&mut self, executor: &mut E) where @@ -241,16 +288,21 @@ impl SimulationState { self.slot_passes = 0; match self.step_round(executor, time, Vec::new(), Vec::new(), true) { Ok(()) => { - executor.finish_timed_step(time); + self.finish_timed_boundary(executor, time)?; Ok(Some(time)) } Err(Halt::Finish) => { - executor.finish_timed_step(time); - self.finish(executor); + self.finalize_terminal(executor)?; Ok(Some(self.scheduler.time)) } Err(Halt::Stop) => Ok(Some(self.scheduler.time)), - Err(Halt::Error(error)) => Err(error), + Err(Halt::Error(error)) => { + // Preserve the primary runtime failure even if diagnostic + // waveform output also fails. This does not resume processes. + let _ = self.finish_timed_boundary(executor, self.scheduler.time); + let _ = executor.flush_output(); + Err(error) + } } } diff --git a/crates/celox-runtime/src/simulation/time.rs b/crates/celox-runtime/src/simulation/time.rs index 3b4a5bec296..1d8657ff8f1 100644 --- a/crates/celox-runtime/src/simulation/time.rs +++ b/crates/celox-runtime/src/simulation/time.rs @@ -183,7 +183,7 @@ impl SimulationState { self.charge_pass()?; self.step_round(executor, current_time, Vec::new(), ready, false)?; } - executor.finish_timed_step(current_time); + executor.try_finish_timed_step(current_time)?; Ok(()) } diff --git a/crates/celox-runtime/src/vcd.rs b/crates/celox-runtime/src/vcd.rs index e79e493bc1b..1747c6eb6b0 100644 --- a/crates/celox-runtime/src/vcd.rs +++ b/crates/celox-runtime/src/vcd.rs @@ -119,8 +119,11 @@ pub struct VcdWriter { timestamp: u64, time_precision: celox_design::TimePrecision, header_written: bool, + /// Complete header commands awaiting emission after a byte-limit pause. + header_records: Option>>, initial_values_written: bool, external_count: usize, + suspended: bool, } struct VcdOutput { @@ -133,6 +136,9 @@ struct VcdOutput { /// Bytes already accepted by BufWriter, including short writes before an error. written: usize, encoded_changes: u64, + accepted_bytes: u64, + byte_limit: Option, + limit_comment_written: bool, stats: VcdStatistics, } @@ -158,9 +164,11 @@ impl VcdWriter { /// signals, in a new file at `path`. The first dump there records every /// value, and its timestamps start over. pub fn restart>(&mut self, path: P) -> std::io::Result<()> { + self.flush()?; let mut next = Self::new_with_time_precision(path, &self.descs, self.time_precision)?; next.add_external_signals(&self.external_descs)?; - self.flush()?; + next.suspended = self.suspended; + next.output.byte_limit = self.output.byte_limit; *self = next; Ok(()) } @@ -199,6 +207,9 @@ impl VcdWriter { encoded: Vec::new(), written: 0, encoded_changes: 0, + accepted_bytes: 0, + byte_limit: None, + limit_comment_written: false, stats: VcdStatistics::default(), }, headers, @@ -212,8 +223,10 @@ impl VcdWriter { timestamp: 0, time_precision, header_written: false, + header_records: None, initial_values_written: false, external_count: 0, + suspended: false, } } @@ -243,6 +256,110 @@ impl VcdWriter { self.rescan_pending = true; } + /// Set the maximum output size requested by `$dumplimit`. Zero removes + /// the limit. Complete records may take the file beyond the limit. + pub fn set_byte_limit(&mut self, limit: u64) { + if self.output.limit_reached() { + // Skipped output may have consumed the backend's activity flags, + // and a partial initial snapshot has not initialized every value. + self.rescan_pending = true; + self.initial_values_written = false; + } + self.output.byte_limit = (limit != 0).then_some(limit); + self.output.limit_comment_written = false; + } + + fn limit_reached(&mut self) -> bool { + let reached = self.output.limit_reached(); + if reached { + self.output.note_limit(); + } + reached + } + + /// Emit a SystemVerilog VCD checkpoint. `off` writes unknowns and + /// suspends changes; `on` writes current values and resumes; `all` + /// writes current values without changing suspension (21.7.1.3–4). + pub fn checkpoint( + &mut self, + command: &str, + timestamp: u64, + memory: &[u8], + external: &[(BigUint, BigUint)], + ) -> std::io::Result<()> { + if !matches!(command, "dumpoff" | "dumpon" | "dumpall") { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + "invalid VCD checkpoint", + )); + } + self.validate_external_count(external.len())?; + // Suppressing header or value records must not suppress controls. + match command { + "dumpoff" => self.suspended = true, + "dumpon" => self.suspended = false, + _ => {} + } + if self.limit_reached() || !self.begin_timestamp(timestamp)? { + return Ok(()); + } + writeln!(self.output.encoded, "${command}")?; + if command == "dumpoff" { + for index in 0..self.headers.len() { + if self.output.limit_reached() { + break; + } + let width = self.headers[index].width; + let size = width.div_ceil(8); + self.output.encoded.reserve(width + 16); + let len = encode_value( + self.output.encoded.spare_capacity_mut(), + width, + &vec![255; size], + &vec![255; size], + ); + self.output.finish_record(len, self.plan.suffix(index))?; + } + self.suspended = true; + } else { + self.plan + .dump::(memory, external, None, &mut self.output)?; + self.initial_values_written = true; + if command == "dumpon" { + self.suspended = false; + } + } + writeln!(self.output.encoded, "$end")?; + self.output.note_limit(); + self.rescan_pending = true; + Ok(()) + } + + fn begin_timestamp(&mut self, timestamp: u64) -> std::io::Result { + if self.header_written && timestamp < self.timestamp { + return Err(std::io::Error::new( + std::io::ErrorKind::InvalidInput, + format!( + "VCD timestamp {timestamp} is earlier than the last dumped timestamp {}; start a new file to record a rewound simulation", + self.timestamp + ), + )); + } + self.output.write_encoded()?; + if !self.header_written && !self.write_header()? { + return Ok(false); + } + if self.limit_reached() { + return Ok(false); + } + if timestamp > self.timestamp || timestamp == 0 { + writeln!(self.output.encoded, "#{timestamp}")?; + self.timestamp = timestamp; + self.output.write_encoded()?; + } + Ok(true) + } + /// Dump as the backend's sole incremental waveform observer. Multiple /// writers must consume activity once and share it through /// `dump_with_activity`, since each consumption clears the pending flags. @@ -309,7 +426,7 @@ impl VcdWriter { return Ok(()); } } - if self.header_written { + if self.header_written || self.header_records.is_some() { return Err(std::io::Error::new( std::io::ErrorKind::InvalidInput, "cannot add external VCD signals after the first dump", @@ -330,20 +447,18 @@ impl VcdWriter { } #[cold] - fn write_header(&mut self) -> std::io::Result<()> { - writeln!(self.output.encoded, "$date")?; - writeln!( - self.output.encoded, - " {}", - chrono::Local::now().format("%Y-%m-%d %H:%M:%S") - )?; - writeln!(self.output.encoded, "$end")?; - writeln!(self.output.encoded, "$version")?; - writeln!(self.output.encoded, " celox")?; - writeln!(self.output.encoded, "$end")?; + fn prepare_header(&mut self) -> std::collections::VecDeque> { + let mut records = std::collections::VecDeque::new(); + records.push_back( + format!( + "$date\n {}\n$end\n", + chrono::Local::now().format("%Y-%m-%d %H:%M:%S") + ) + .into_bytes(), + ); + records.push_back(b"$version\n celox\n$end\n".to_vec()); let (magnitude, unit) = self.time_precision.vcd_timescale(); - writeln!(self.output.encoded, "$timescale {magnitude}{unit} $end")?; - + records.push_back(format!("$timescale {magnitude}{unit} $end\n").into_bytes()); let mut scope_order = Vec::::new(); let mut scope_groups = Vec::>::new(); let mut scope_idx = fxhash::FxHashMap::::default(); @@ -359,23 +474,42 @@ impl VcdWriter { } let mut next_id = 0; for (scope, group) in scope_order.iter().zip(scope_groups) { - writeln!(self.output.encoded, "$scope module {} $end", scope)?; + records.push_back(format!("$scope module {scope} $end\n").into_bytes()); for signal_index in group { let signal = &mut self.headers[signal_index]; let id = Self::generate_vcd_id(next_id); *self.plan.suffix(signal_index) = VcdRecordSuffix::new(signal.width, &id); next_id += 1; - writeln!( - self.output.encoded, - "$var wire {} {} {} $end", - signal.width, id, signal.name - )?; + records.push_back( + format!("$var wire {} {} {} $end\n", signal.width, id, signal.name) + .into_bytes(), + ); } - writeln!(self.output.encoded, "$upscope $end")?; + records.push_back(b"$upscope $end\n".to_vec()); } - writeln!(self.output.encoded, "$enddefinitions $end")?; - writeln!(self.output.encoded, "$dumpvars")?; - writeln!(self.output.encoded, "$end")?; + records.push_back(b"$enddefinitions $end\n".to_vec()); + records.push_back(b"$dumpvars\n$end\n".to_vec()); + records + } + + #[cold] + fn write_header(&mut self) -> std::io::Result { + if self.header_records.is_none() { + self.header_records = Some(self.prepare_header()); + } + while self + .header_records + .as_ref() + .is_some_and(|records| !records.is_empty()) + { + if self.limit_reached() { + return Ok(false); + } + let record = self.header_records.as_mut().unwrap().pop_front().unwrap(); + self.output.encoded.extend_from_slice(&record); + self.output.write_encoded()?; + } + self.header_records = None; let record_capacity = self .headers .iter() @@ -402,7 +536,7 @@ impl VcdWriter { // A large header must not permanently enlarge the value buffer. self.output.encoded.shrink_to(capacity); } - Ok(()) + Ok(true) } fn generate_vcd_id(num: usize) -> String { @@ -457,27 +591,12 @@ impl VcdWriter { activity: Option<&[usize]>, ) -> std::io::Result<()> { self.validate_external_count(external.len())?; - if self.header_written && timestamp < self.timestamp { - return Err(std::io::Error::new( - std::io::ErrorKind::InvalidInput, - format!( - "VCD timestamp {timestamp} is earlier than the last dumped timestamp {}; \ - start a new file to record a rewound simulation", - self.timestamp - ), - )); + if self.suspended || self.limit_reached() { + return Ok(()); } - // Finish the previous attempt before starting a new timestamp or - // consulting caches that include its queued value records. - self.output.write_encoded()?; let first_dump = !self.initial_values_written; - if !self.header_written { - self.write_header()?; - } - if timestamp > self.timestamp || timestamp == 0 { - writeln!(self.output.encoded, "#{}", timestamp)?; - self.timestamp = timestamp; - self.output.write_encoded()?; + if !self.begin_timestamp(timestamp)? { + return Ok(()); } self.selected.clear(); // Dense activity is cheaper to walk directly in registration order. @@ -510,11 +629,26 @@ impl VcdWriter { &mut self.output, )?; } + self.output.note_limit(); Ok(()) } } impl VcdOutput { + #[inline] + fn limit_reached(&self) -> bool { + self.byte_limit + .is_some_and(|limit| self.accepted_bytes + self.encoded.len() as u64 >= limit) + } + + fn note_limit(&mut self) { + if self.limit_reached() && !self.limit_comment_written { + self.encoded + .extend_from_slice(b"$comment VCD dump limit reached $end\n"); + self.limit_comment_written = true; + } + } + // Keep suffix publication with the value encoder so SIMD constants and // output state can stay in registers between records. #[inline(always)] @@ -548,6 +682,7 @@ impl VcdOutput { self.stats.changes += self.encoded_changes; self.stats.value_bytes += self.encoded.len() as u64; } + self.accepted_bytes += self.encoded.len() as u64; self.encoded.clear(); self.written = 0; self.encoded_changes = 0; @@ -736,6 +871,211 @@ const BINARY: [[u8; 8]; 256] = { mod tests { use super::*; + #[test] + fn limited_checkpoints_preserve_on_off_state_when_recording_resumes() { + for command in ["dumpoff", "dumpon"] { + let descs = [VcdSignalDesc { + scope: "Top".into(), + name: "value".into(), + offset: 0, + width: 1, + is_4state: false, + }]; + let mut writer = VcdWriter::from_writer(Vec::new(), &descs); + writer.dump(0, &[0]).unwrap(); + if command == "dumpon" { + writer.checkpoint("dumpoff", 1, &[0], &[]).unwrap(); + } + writer.set_byte_limit(1); + writer.checkpoint(command, 2, &[1], &[]).unwrap(); + writer.set_byte_limit(0); + writer.dump(3, &[1]).unwrap(); + let output = String::from_utf8(writer.into_inner().unwrap()).unwrap(); + assert_eq!( + output.contains("#3\n1"), + command == "dumpon", + "{command}: {output}" + ); + if command == "dumpoff" { + assert!( + !output.contains("#3"), + "off under the limit must remain suspended: {output}" + ); + } + } + } + + #[test] + fn byte_limit_pauses_header_at_command_boundaries_and_resumes_once() { + let descs = (0..100) + .map(|index| VcdSignalDesc { + scope: "Top".into(), + name: format!("signal_{index}"), + offset: index, + width: 1, + is_4state: false, + }) + .collect::>(); + let mut reference = VcdWriter::from_writer(Vec::new(), &descs); + let records = reference.prepare_header(); + let max_record = records.iter().map(Vec::len).max().unwrap(); + let header_size = records.iter().map(Vec::len).sum::(); + let mut boundary = 0; + let mut limits = vec![1]; + for record in &records { + boundary += record.len(); + limits.extend([boundary.saturating_sub(1), boundary]); + } + for limit in limits { + let mut writer = VcdWriter::from_writer(Vec::new(), &descs); + writer.set_byte_limit(limit as u64); + writer.dump(0, &[0; 100]).unwrap(); + writer.flush().unwrap(); + let paused = String::from_utf8(writer.get_ref().clone()).unwrap(); + assert!( + paused.len() <= limit + max_record + 36, + "{limit}/{header_size}: {paused}" + ); + assert!( + paused.contains("VCD dump limit reached"), + "{limit}: {paused}" + ); + assert!(!paused.contains("#0"), "{limit}: {paused}"); + assert_eq!(writer.statistics().changes, 0); + writer.set_byte_limit(0); + writer.dump(5, &[1; 100]).unwrap(); + let output = String::from_utf8(writer.into_inner().unwrap()).unwrap(); + assert_eq!(output.matches("$date\n").count(), 1, "{limit}: {output}"); + assert_eq!( + output.matches("$var wire ").count(), + 100, + "{limit}: {output}" + ); + assert_eq!( + output.matches("$enddefinitions $end").count(), + 1, + "{limit}: {output}" + ); + let (_, values) = output.split_once("#5\n").unwrap(); + assert_eq!( + values.lines().filter(|line| line.starts_with('1')).count(), + 100, + "{limit}: {output}" + ); + } + } + + #[test] + fn header_limit_keeps_checkpoint_suspension_and_external_registration() { + let descs = [VcdSignalDesc { + scope: "Top".into(), + name: "state".into(), + offset: 0, + width: 1, + is_4state: false, + }]; + let mut writer = VcdWriter::from_writer(Vec::new(), &descs); + writer.set_byte_limit(1); + writer.dump(0, &[0]).unwrap(); + assert!( + writer + .add_external_signals(&[VcdExternalSignalDesc { + scope: "Top".into(), + name: "late".into(), + width: 1 + }]) + .is_err() + ); + writer.checkpoint("dumpoff", 1, &[1], &[]).unwrap(); + writer.set_byte_limit(0); + writer.dump(2, &[1]).unwrap(); + writer.checkpoint("dumpon", 3, &[1], &[]).unwrap(); + let output = String::from_utf8(writer.into_inner().unwrap()).unwrap(); + assert!(!output.contains("#2"), "{output}"); + assert!(output.contains("#3\n$dumpon\n1!\n$end"), "{output}"); + } + + #[test] + fn byte_limit_stops_initial_changes_and_checkpoint_at_one_record() { + for width in [1usize, 4, 64] { + let bytes = width.div_ceil(8); + let descs = (0..100) + .map(|i| VcdSignalDesc { + scope: "Top".into(), + name: format!("s{i}"), + offset: i * bytes, + width, + is_4state: false, + }) + .collect::>(); + for command in ["initial", "changes", "dumpall", "dumpoff", "dumpon"] { + let mut writer = VcdWriter::from_writer(Vec::new(), &descs); + let mut memory = vec![0u8; bytes * descs.len()]; + writer.write_header().unwrap(); + if command != "initial" { + writer.dump(0, &memory).unwrap(); + } + let before = writer.statistics().changes; + writer.output.write_encoded().unwrap(); + // Leave room for the timestamp/command and one record, but not + // for the complete hundred-signal snapshot or checkpoint. + let allowance = if command.starts_with("dump") { 22 } else { 6 }; + let limit = writer.output.accepted_bytes + allowance; + writer.set_byte_limit(limit); + memory.fill(255); + if command.starts_with("dump") { + writer.checkpoint(command, 1, &memory, &[]).unwrap(); + } else { + writer.dump(1, &memory).unwrap(); + } + writer.flush().unwrap(); + let records = writer.statistics().changes - before; + assert!( + records < 10, + "{command}/{width}: emitted {records} records past a small limit" + ); + let output = String::from_utf8(writer.into_inner().unwrap()).unwrap(); + assert!( + output.contains("VCD dump limit reached"), + "{command}/{width}: {output}" + ); + let max_record = width.max(1) as u64 + 5; + assert!( + output.len() as u64 <= limit + max_record + 5 + 36, + "{command}/{width}: {} exceeds bound {limit}", + output.len() + ); + } + } + } + + #[test] + fn system_task_checkpoints_and_limit() { + let descs = [VcdSignalDesc { + scope: "Top".into(), + name: "value".into(), + offset: 0, + width: 4, + is_4state: true, + }]; + let mut writer = VcdWriter::from_writer(Vec::new(), &descs); + writer.dump(0, &[0b1011, 0b0011]).unwrap(); + writer.checkpoint("dumpoff", 1, &[15, 0], &[]).unwrap(); + writer.dump(2, &[0, 0]).unwrap(); + writer.checkpoint("dumpon", 3, &[15, 0], &[]).unwrap(); + writer.checkpoint("dumpall", 4, &[15, 0], &[]).unwrap(); + writer.set_byte_limit(1); + writer.dump(5, &[0, 0]).unwrap(); + let output = String::from_utf8(writer.into_inner().unwrap()).unwrap(); + assert!(output.contains("b10xx ")); + assert!(output.contains("$dumpoff\nbxxxx ")); + assert!(!output.contains("#2")); + assert!(output.contains("$dumpon\nb1111 ")); + assert!(output.contains("$dumpall\nb1111 ")); + assert!(!output.contains("#5")); + assert!(output.contains("VCD dump limit reached")); + } + #[test] fn headers_encode_supported_time_precisions() { for (exponent, expected) in [ diff --git a/crates/celox-runtime/src/vcd/plan.rs b/crates/celox-runtime/src/vcd/plan.rs index e29499de9e0..660586741db 100644 --- a/crates/celox-runtime/src/vcd/plan.rs +++ b/crates/celox-runtime/src/vcd/plan.rs @@ -184,6 +184,9 @@ impl TracePlan { // Sparse indices can break a long typed run into many short ones. // Visit each entry once instead of first rebuilding those runs. for &index in selected { + if output.limit_reached() { + break; + } let entry = self.entries[index]; let run = Run { kind: entry.kind, @@ -199,6 +202,9 @@ impl TracePlan { // Alternating types form many tiny runs. Visit their entries // directly so each specialized loop has a known length of one. for index in 0..self.entries.len() { + if output.limit_reached() { + break; + } let entry = self.entries[index]; let run = Run { kind: entry.kind, @@ -212,6 +218,9 @@ impl TracePlan { } } else { for index in 0..self.runs.len() { + if output.limit_reached() { + break; + } // SAFETY: the complete memory range was validated above. unsafe { self.write_run::(self.runs[index], memory, external, output)?; @@ -248,6 +257,10 @@ impl TracePlan { Kind::Generic => { let signals = &self.generic[run.start..run.end]; for (index, signal) in signals.iter().enumerate() { + if output.limit_reached() { + output.stats.comparisons += index as u64; + return Ok(()); + } let size = signal.width.div_ceil(8); let external_bytes; let (value, mask, track_mask): (&[u8], &[u8], bool) = match signal.source { @@ -306,6 +319,10 @@ unsafe fn write_fixed( output: &mut VcdOutput, ) -> std::io::Result<()> { for (index, signal) in signals.iter_mut().enumerate() { + if output.limit_reached() { + output.stats.comparisons += index as u64; + return Ok(()); + } let value = if BIT { // SAFETY: the plan validated this one-byte range for this dump. u64::from(unsafe { *memory.as_ptr().add(signal.offset) } & 1) diff --git a/crates/celox-sv-analyzer/src/ast/packages.rs b/crates/celox-sv-analyzer/src/ast/packages.rs index 397455ff256..42278e04dc2 100644 --- a/crates/celox-sv-analyzer/src/ast/packages.rs +++ b/crates/celox-sv-analyzer/src/ast/packages.rs @@ -357,7 +357,10 @@ impl Packages { /// The variables package `name` declares: each is one object, shared by /// every module that uses it (IEEE 1800-2023 26.2). Constant variables are /// left out; they are copied like parameters. Package nets are rejected. -fn package_variables(name: &str, tree: &SyntaxTree) -> Result, AnalyzerError> { +pub(super) fn package_variables( + name: &str, + tree: &SyntaxTree, +) -> Result, AnalyzerError> { use celox_sv_syntax::{BodyItemKind, DataDeclaration}; let native = tree.declarations(); let mut variables = HashSet::default(); diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index 6668b2960b0..1ce0ac90e77 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -843,11 +843,30 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { }; let args = arguments .iter() - .map(|arg| { + .enumerate() + .map(|(index, arg)| { let Some(id) = arg.value else { return Ok(SystemTaskArg::Empty); }; - if let celox_sv_syntax::ExprKind::Literal(text) = &declarations.expression(id).kind + if matches!(task, SystemTask::Vcd(system_functions::VcdTask::Vars)) && index > 0 { + let text = dump_selection_name( + id, + self.tree, + &self.dims, + &|value| self.rename_const(value), + &|name| { + self.scopes + .iter() + .any(|scope| scope.entries.iter().any(|entry| entry.source == name)) + }, + )?; + return Ok(SystemTaskArg::Str(text)); + } + // Filenames use the normal packed-string expression binder, + // including octal/hex escapes and multiline literal delimiters. + if !matches!(task, SystemTask::Vcd(system_functions::VcdTask::File)) + && let celox_sv_syntax::ExprKind::Literal(text) = + &declarations.expression(id).kind && let Some(text) = text .strip_prefix('"') .and_then(|text| text.strip_suffix('"')) @@ -1674,3 +1693,124 @@ pub(super) fn source_span( } result } + +fn dump_selection_name( + id: celox_sv_syntax::ExprId, + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + rename: &dyn Fn(&mut ConstExpr), + is_local: &dyn Fn(&str) -> bool, +) -> Result { + // Preserve identifier/index boundaries in host metadata. A normalized + // escaped identifier can itself contain '.', '::', or '[0]'. NUL cannot + // occur in an authored identifier, so it separates these components. + fn append( + id: celox_sv_syntax::ExprId, + tree: &AnalysisContext<'_>, + dimensions: &PackedDimensions, + rename: &dyn Fn(&mut ConstExpr), + kind: &mut &'static str, + fields: &mut Vec, + ) -> Result<(), AnalyzerError> { + use celox_sv_syntax::{DimensionKind, ExprKind}; + match &tree.declarations().expression(id).kind { + ExprKind::Name(name) if name.spelling == "$root" => { + *kind = "absolute"; + } + ExprKind::Name(name) => { + fields.extend([ + "name".into(), + instances::normalize_identifier(&name.spelling), + ]); + } + ExprKind::Member { + expression, + separator, + name, + } if separator == "." || separator == "::" => { + append(*expression, tree, dimensions, rename, kind, fields)?; + if separator == "::" { + *kind = "package"; + } + fields.extend([ + "name".into(), + instances::normalize_identifier(&name.spelling), + ]); + } + ExprKind::Select { + expression, + dimension, + } => { + let DimensionKind::Index(index) = &dimension.kind else { + return Err(unsupported( + "$dumpvars hierarchy selection requires a single constant index", + )); + }; + append(*expression, tree, dimensions, rename, kind, fields)?; + let mut value = constant_binding::bind(*index, tree, dimensions)? + .ok_or_else(|| unsupported("$dumpvars hierarchy index must be constant"))?; + rename(&mut value); + let index = eval_ast_const_expr(&tree.state, &value, &dimensions.const_env) + .ok_or_else(|| { + unsupported("$dumpvars hierarchy index must be a known constant integer") + })?; + fields.extend(["index".into(), index.to_string()]); + } + _ => { + return Err(unsupported( + "$dumpvars selection must be a module or variable name", + )); + } + } + Ok(()) + } + let mut kind = "relative"; + let mut fields = Vec::new(); + append(id, tree, dimensions, rename, &mut kind, &mut fields)?; + // Imports bind declarations, not a module-local spelling. Nested procedural + // declarations shadow these aliases just as they do for value expressions. + if kind == "relative" && fields.len() == 2 && !is_local(&fields[1]) { + let symbols = scope::imported(&tree.state); + if let Some(target) = symbols.aliases.get(&fields[1]) + && let Some((package, name)) = symbols + .state_signals + .iter() + .find(|signal| signal.name() == target) + .and_then(|signal| signal.package_variable()) + { + kind = "package"; + fields = vec!["name".into(), package.into(), "name".into(), name.into()]; + } else if let Ok(unit) = tree.root_unit() + && unit.kind == celox_sv_syntax::UnitKind::Package + && packages::package_variables(&unit.name.spelling, tree)?.contains(&fields[1]) + { + // A package subroutine is later instantiated at its caller, but + // its unqualified package references retain their lexical owner. + kind = "package"; + fields = vec![ + "name".into(), + instances::normalize_identifier(&unit.name.spelling), + "name".into(), + fields[1].clone(), + ]; + } + } + if fields.is_empty() { + return Err(unsupported( + "$dumpvars selection must name a module or variable", + )); + } + // A lexical declaration wins over a root module with the same spelling. + // Keep that decision in metadata: the runtime cannot recover lexical + // binding from an already flattened path or the top module's name. + if kind == "relative" + && (is_local(&fields[1]) || imports::scope_names(tree)?.contains(&fields[1])) + { + kind = "local"; + } + Ok(std::iter::once("celox.dump.path.v1".to_string()) + .chain(std::iter::once(kind.to_string())) + .chain(fields) + .collect::>() + .join("\0")) +} diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 6ebeb00ea0a..43c2066a3d7 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -7,7 +7,7 @@ pub use crate::procedural::{ CaseKind, CaseLabel, EventEdge, LoopKind, ParamDirection, SourceSpan, StmtBase, SystemTaskArg, }; pub use crate::system_functions::{ - ArrayQuery, Callee, MemoryFormat, Radix, Severity, SystemFunction, SystemTask, + ArrayQuery, Callee, MemoryFormat, Radix, Severity, SystemFunction, SystemTask, VcdTask, }; /// A procedural statement of the analyzed IR. diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 064b943d65e..5ded0654667 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -229,6 +229,8 @@ pub enum SystemTask { Write(Radix), /// `$readmemb` and `$readmemh` (21.4). Readmem(MemoryFormat), + /// Value change dump controls (21.7.1). + Vcd(VcdTask), /// File output tasks (21.3). Fclose, Fdisplay(Radix), @@ -242,6 +244,18 @@ pub enum SystemTask { AssertContinue, } +/// Four-state VCD control system tasks (IEEE 1800-2023 21.7.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum VcdTask { + File, + Vars, + Flush, + On, + Off, + All, + Limit, +} + /// The severity of `$error`, `$warning` and `$info`. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Severity { @@ -293,7 +307,7 @@ impl SystemTask { pub fn is_host_request(self) -> bool { matches!( self, - Self::Fclose | Self::Fdisplay(_) | Self::Fwrite(_) | Self::Writemem(_) + Self::Fclose | Self::Fdisplay(_) | Self::Fwrite(_) | Self::Writemem(_) | Self::Vcd(_) ) } @@ -330,6 +344,13 @@ impl SystemTask { Self::Writemem(MemoryFormat::Hexadecimal) => "$writememh", Self::Readmem(MemoryFormat::Binary) => "$readmemb", Self::Readmem(MemoryFormat::Hexadecimal) => "$readmemh", + Self::Vcd(VcdTask::File) => "$dumpfile", + Self::Vcd(VcdTask::Vars) => "$dumpvars", + Self::Vcd(VcdTask::Flush) => "$dumpflush", + Self::Vcd(VcdTask::On) => "$dumpon", + Self::Vcd(VcdTask::Off) => "$dumpoff", + Self::Vcd(VcdTask::All) => "$dumpall", + Self::Vcd(VcdTask::Limit) => "$dumplimit", Self::Assert => "$assert", Self::AssertContinue => "$assert_continue", } @@ -839,13 +860,48 @@ pub const SYSTEM_TFS: &[SystemTf] = &[ function(SystemFunction::TestPlusargs, 1, Some(1)), function(SystemFunction::ValuePlusargs, 2, Some(2)), // 21.7 Value change dump (VCD) files - unsupported("$dumpfile", Task), - unsupported("$dumpvars", Task), - unsupported("$dumpoff", Task), - unsupported("$dumpon", Task), - unsupported("$dumpall", Task), - unsupported("$dumplimit", Task), - unsupported("$dumpflush", Task), + task( + SystemTask::Vcd(VcdTask::File), + ProceduralAndInitial, + 0, + Some(1), + ), + task( + SystemTask::Vcd(VcdTask::Vars), + ProceduralAndInitial, + 0, + None, + ), + task( + SystemTask::Vcd(VcdTask::Off), + ProceduralAndInitial, + 0, + Some(0), + ), + task( + SystemTask::Vcd(VcdTask::On), + ProceduralAndInitial, + 0, + Some(0), + ), + task( + SystemTask::Vcd(VcdTask::All), + ProceduralAndInitial, + 0, + Some(0), + ), + task( + SystemTask::Vcd(VcdTask::Limit), + ProceduralAndInitial, + 1, + Some(1), + ), + task( + SystemTask::Vcd(VcdTask::Flush), + ProceduralAndInitial, + 0, + Some(0), + ), unsupported("$dumpports", Task), unsupported("$dumpportsoff", Task), unsupported("$dumpportson", Task), diff --git a/crates/celox/src/backend/native/image_file.rs b/crates/celox/src/backend/native/image_file.rs index 9b88368edf0..608c8c4bc75 100644 --- a/crates/celox/src/backend/native/image_file.rs +++ b/crates/celox/src/backend/native/image_file.rs @@ -6,7 +6,7 @@ use std::{fmt, path::Path}; use super::backend::NativeProgramImage; const TRAILER_MAGIC: &[u8; 8] = b"CELOXNPI"; -const CONTAINER_VERSION: u16 = 18; +const CONTAINER_VERSION: u16 = 19; const TRAILER_SIZE: usize = 32; const FNV_OFFSET_BASIS: u64 = 0xcbf2_9ce4_8422_2325; const FNV_PRIME: u64 = 0x0000_0100_0000_01b3; diff --git a/crates/celox/src/component.rs b/crates/celox/src/component.rs index be5f2b0a622..9091f8e1f52 100644 --- a/crates/celox/src/component.rs +++ b/crates/celox/src/component.rs @@ -920,6 +920,92 @@ pub(crate) fn host_bits(value: &HostValue) -> Option<(num_bigint::BigUint, u32)> mod tests { use super::*; + #[cfg(feature = "systemverilog")] + #[test] + fn source_vcd_filters_injected_component_trace_descriptors_and_values() { + use std::sync::Arc; + struct EmptyModel; + impl InjectedComponentHandler for EmptyModel { + fn call(&self, _: InjectedCall) -> Result { + Ok(InjectedResult::default()) + } + } + for (levels, target, expected_model, expected_other) in [ + (0, "Top.value", false, false), + (0, "Top.other.state", false, true), + (1, "Top", false, false), + (0, "Top", true, true), + (1, "Top.other", false, true), + ] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("component.vcd"); + let source = format!( + r#"module Top(output logic value); + timeunit 1ps; timeprecision 1ps; + initial begin $dumpfile("{}"); $dumpvars({levels}, {target}); value=1; + #1 $dumpall; #1 $dumpoff; #1 $dumpon; end + endmodule"#, + path.display() + ); + let mut simulation = crate::Simulation::from_sv_sources( + vec![(&source, std::path::Path::new("vcd.sv"))], + "Top", + ) + .build_interpreter() + .unwrap(); + let mut definitions = InjectedComponents::new(); + definitions + .insert("model", r#"{"kind":"method_only"}"#, Arc::new(EmptyModel)) + .unwrap(); + for (name, value) in [("model", 1u64), ("other", 42u64)] { + let mut host = HostContext::new(); + host.label = name.into(); + let instance = ExternalInstance::create_injected( + definitions.get("model").unwrap().clone(), + &mut host, + ) + .unwrap(); + host.trace_vars.push(host::HostTraceVar { + name: "state".into(), + width: 8, + words: vec![value], + }); + simulation + .simulator + .components + .components + .push(LiveComponent { + name: name.into(), + instance, + host, + inputs: Vec::new(), + outputs: Vec::new(), + events: Vec::new(), + fire_count: 0, + }); + } + simulation.run_until(4).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!( + text.contains("$scope module Top.model $end"), + expected_model, + "{target}: {text}" + ); + assert_eq!( + text.contains("$scope module Top.other $end"), + expected_other, + "{target}: {text}" + ); + if expected_other { + assert!( + text.contains("b101010 "), + "wrong external value subset for {target}: {text}" + ); + } + } + } + #[test] fn manifest_without_parameters_rejects_supplied_parameter() { let manifest = veryl_metadata::ComponentManifest::parse(r#"{"kind":"method_only"}"#) diff --git a/crates/celox/src/ir.rs b/crates/celox/src/ir.rs index 563b6ad66c4..89dd6f342ef 100644 --- a/crates/celox/src/ir.rs +++ b/crates/celox/src/ir.rs @@ -207,6 +207,12 @@ impl RuntimeDesign { self.instances.values() } + /// Package state has its own scope and is not a child of the top module. + #[cfg(feature = "host-runtime")] + pub(crate) fn is_package_instance(&self, id: InstanceId) -> bool { + self.package_instances.contains(&id) + } + pub fn instance(&self, id: InstanceId) -> Option<&RuntimeInstance> { self.instances.get(&id) } diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index a1dabb941c0..498bf262948 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -11,6 +11,8 @@ use celox_runtime::{ UnitExecutor, host_watch, }; +mod vcd_tasks; + /// Saved state of a [`Simulation`], created by [`Simulation::checkpoint`]: /// the design state together with simulation time, clocks and pending events. pub struct SimulationCheckpoint { @@ -124,9 +126,7 @@ impl UnitExecutor for Simulator { self.run_plusargs_request(request, timestamp) } celox_design::HostRequestKind::FileIo => self.run_file_io_request(request, timestamp), - celox_design::HostRequestKind::Vcd => { - Err(celox_runtime::SimulatorErrorCode::InternalError.into()) - } + celox_design::HostRequestKind::Vcd => self.run_vcd_request(request, timestamp), } } } @@ -148,6 +148,23 @@ impl HostBoundary for Simulator { self.frozen = true; } + fn flush_output(&mut self) -> Result<(), RuntimeErrorCode> { + if self.sv_vcd.started.is_some() { + self.flush_vcd() + .map_err(|error| RuntimeErrorCode::Runtime { + message: format!("VCD flush at finish failed: {error}"), + signals: Vec::new(), + })?; + } + Ok(()) + } + + fn try_freeze(&mut self) -> Result<(), RuntimeErrorCode> { + let output = self.flush_output(); + self.freeze(); + output + } + fn stage_external_event( &mut self, event: B::Event, @@ -180,6 +197,28 @@ impl HostBoundary for Simulator { self.dirty = false; self.dump_unless_rewound(timestamp); } + + fn try_finish_timed_step(&mut self, timestamp: u64) -> Result<(), Halt> { + self.start_sv_vcd(timestamp).map_err(|error| { + Halt::Error(RuntimeErrorCode::Runtime { + message: format!("VCD setup failed: {error}"), + signals: Vec::new(), + }) + })?; + self.dirty = false; + self.try_dump_unless_rewound(timestamp) + .map_err(|error| Halt::Error(vcd_dump_runtime_error(error))) + } +} + +fn vcd_dump_runtime_error(error: crate::simulator::DumpError) -> RuntimeErrorCode { + match error { + crate::simulator::DumpError::Runtime(error) => error, + crate::simulator::DumpError::Io(error) => RuntimeErrorCode::Runtime { + message: format!("VCD dump failed: {error}"), + signals: Vec::new(), + }, + } } impl Simulator { @@ -278,7 +317,7 @@ impl Simulation { } let mut file = self.simulator.save_state()?; // Settling for the file may have executed a `$finish`. - self.sync_finish(); + self.sync_finish_checked().map_err(StateError::Runtime)?; let parts = self.state.export_schedule(&self.simulator.backend); let mut record = self.simulator.name_schedule(parts); record.processes.host_writes = self.simulator.name_host_writes(); @@ -333,10 +372,23 @@ impl Simulation { /// A `$finish` that flip-flop or combinational code executed outside a /// step, during a direct settle, read or dump, ends the simulation too. - fn sync_finish(&mut self) { + fn sync_finish_checked(&mut self) -> Result<(), RuntimeErrorCode> { if !self.state.is_finished() && self.simulator.take_runtime_finish() { - self.state.finish(&mut self.simulator); + self.state.finalize_terminal(&mut self.simulator)?; } + Ok(()) + } + + /// Publish diagnostic state without replacing a primary evaluation error + /// or freezing a simulation whose caller may recover. + fn flush_error_output(&mut self) { + let _ = self.simulator.try_finish_timed_step(self.state.time()); + let _ = self.simulator.flush_output(); + } + + fn sync_finish(&mut self) { + self.sync_finish_checked() + .unwrap_or_else(|error| panic!("simulation finish failed: {error}")); } /// Captures the current state of all signals and writes them to the VCD file. @@ -348,8 +400,12 @@ impl Simulation { /// See [`Simulator::try_dump`]. pub fn try_dump(&mut self, timestamp: u64) -> Result<(), crate::simulator::DumpError> { let result = self.simulator.try_dump(timestamp); - self.sync_finish(); - result + let finished = self.sync_finish_checked(); + if matches!(&result, Err(crate::simulator::DumpError::Runtime(_))) { + self.flush_error_output(); + } + result?; + finished.map_err(crate::simulator::DumpError::Runtime) } /// See [`Simulator::switch_vcd`]. @@ -396,8 +452,9 @@ impl Simulation { F: FnOnce(&mut crate::IOContext), { let result = self.simulator.modify(f); - self.sync_finish(); + let finished = self.sync_finish_checked(); result?; + finished?; let logged = self.simulator.host_watch.has_log(); self.state.note_host_writes(&self.simulator.backend, logged); Ok(()) @@ -470,7 +527,12 @@ impl Simulation { } self.state .advance_time(&mut self.simulator.backend, end_time); - self.simulator.dump_unless_rewound(end_time); + if let Err(error) = self.simulator.try_dump_unless_rewound(end_time) { + if matches!(&error, crate::simulator::DumpError::Runtime(_)) { + self.flush_error_output(); + } + return Err(vcd_dump_runtime_error(error)); + } Ok(()) } @@ -545,8 +607,12 @@ impl Simulation { /// Directly execute combinational logic evaluation. pub fn eval_comb(&mut self) -> Result<(), RuntimeErrorCode> { let result = self.simulator.eval_comb(); - self.sync_finish(); - result + let finished = self.sync_finish_checked(); + if result.is_err() { + self.flush_error_output(); + } + result?; + finished } /// Returns a raw pointer to the backend memory and its total size in bytes. diff --git a/crates/celox/src/simulation/vcd_tasks.rs b/crates/celox/src/simulation/vcd_tasks.rs new file mode 100644 index 00000000000..3700f2439ef --- /dev/null +++ b/crates/celox/src/simulation/vcd_tasks.rs @@ -0,0 +1,532 @@ +//! Host-side execution of IEEE 1800-2023 21.7.1 VCD tasks. +use crate::ir::SignalRef; +use crate::{Simulator, backend::SimBackend}; +use celox_design::HostRequestSite; +use celox_runtime::Halt; +use num_traits::{ToPrimitive, Zero}; + +impl Simulator { + pub(crate) fn run_vcd_request( + &mut self, + site: &HostRequestSite, + timestamp: u64, + ) -> Result<(), Halt> { + // VcdTask discriminants are stable within one compiled artifact. + let result = self.vcd_request(site, timestamp); + result.map_err(|message| { + Halt::Error(crate::RuntimeErrorCode::Runtime { + message, + signals: Vec::new(), + }) + }) + } + + fn vcd_request( + &mut self, + site: &HostRequestSite, + timestamp: u64, + ) -> Result<(), String> { + let mut args = Vec::new(); + for arg in &site.args { + let (value, mask) = self.backend.get_four_state(arg.id); + if !mask.is_zero() { + return Err("VCD task argument contains x or z".into()); + } + if matches!(site.operation, 1 | 6) + && arg.signed + && arg.width > 0 + && value.bit((arg.width - 1) as u64) + { + return Err("VCD depth and size arguments must be nonnegative".into()); + } + args.push(value); + } + let io_error = |error: std::io::Error| format!("VCD task failed: {error}"); + match site.operation { + 0 => { + if self.sv_vcd.started.is_some() { + return Err("$dumpfile must execute before $dumpvars".into()); + } + let path = args + .first() + .map(|arg| { + let bytes = arg + .to_bytes_be() + .into_iter() + .skip_while(|byte| *byte == 0) + .collect::>(); + if bytes.contains(&0) { + return Err("$dumpfile filename contains a NUL byte".to_string()); + } + String::from_utf8(bytes) + .map_err(|_| "$dumpfile filename is not UTF-8".to_string()) + }) + .transpose()? + .unwrap_or_else(|| "dump.vcd".into()); + self.sv_vcd.path = Some(path.into()); + } + 1 => { + if self.sv_vcd.started.is_some_and(|time| time != timestamp) { + return Err( + "all $dumpvars calls must execute at the same simulation time".into(), + ); + } + let levels = args + .first() + .map(|value| { + value + .to_usize() + .ok_or("$dumpvars levels exceeds host range".to_string()) + }) + .transpose()? + .unwrap_or(0); + let owner = self + .program + .runtime_schema + .processes + .get(site.process) + .and_then(|slots| { + self.program + .design + .instances() + .find(|instance| instance.state_addresses().contains(&slots.resume)) + }) + .ok_or("$dumpvars process has no owning instance")?; + let top_name = self + .program + .design + .instances() + .find(|instance| instance.path.0.is_empty()) + .map(|instance| instance.module_name.clone()) + .unwrap_or_else(|| "top".into()); + let top = DumpComponent::name(top_name.clone()); + let owner_components = instance_dump_components(owner, &top); + let targets = if site.strings.is_empty() { + vec![DumpTarget { + package: false, + components: if args.is_empty() { + vec![top.clone()] + } else { + owner_components.clone() + }, + }] + } else { + site.strings + .iter() + .map(|name| decode_dump_target(name, &top, &owner_components)) + .collect::, _>>()? + }; + let mut descs = Vec::new(); + for instance in self.program.design.instances() { + let package = self.program.design.is_package_instance(instance.id); + let path = instance.display_path.join("."); + let scope = if package { + path.clone() + } else if path.is_empty() { + top_name.clone() + } else { + format!("{top_name}.{path}") + }; + let scope_components = if package { + vec![DumpComponent::name( + path.strip_suffix("::").unwrap_or(&path).to_string(), + )] + } else { + instance_dump_components(instance, &top) + }; + for address in instance.state_addresses() { + let Some(variable) = self.program.design.variable(address) else { + continue; + }; + if !instance.resolves_path_to(&variable.path, variable.address) { + continue; + } + let name = variable.path.join("."); + // resolves_path_to above uses the frontend's module-affiliation + // metadata; hidden compiler slots are absent from that index. + let variable_components = variable + .path + .iter() + .flat_map(|part| generated_dump_components(part)) + .collect::>(); + let selected = if package && args.is_empty() && site.strings.is_empty() { + true + } else { + dump_target_matches( + &scope_components, + &variable_components, + package, + &targets, + levels, + ) + }; + if !selected { + continue; + } + let signal = self.backend.resolve_signal(address); + if signal + .array_layout + .is_some_and(|array| array.element_stride * 8 != array.element_width) + { + return Err("$dumpvars requires packed array storage".into()); + } + descs.push(crate::VcdSignalDesc { + scope: scope.clone(), + name, + offset: signal.offset, + width: signal.width, + is_4state: self.backend.layout().four_state && signal.is_4state, + }); + } + } + let mut external = Vec::new(); + for (index, mut desc) in self.components.trace_descriptors().into_iter().enumerate() + { + if desc.scope != top_name && !desc.scope.starts_with(&format!("{top_name}.")) { + desc.scope = format!("{top_name}.{}", desc.scope); + } + if dump_target_matches( + &generated_dump_components(&desc.scope), + &generated_dump_components(&desc.name), + false, + &targets, + levels, + ) { + external.push((index, desc)); + } + } + if descs.is_empty() && external.is_empty() { + return Err("$dumpvars selection matches no dumpable variables".into()); + } + for desc in descs { + if !self + .sv_vcd + .selections + .iter() + .any(|old| old.scope == desc.scope && old.name == desc.name) + { + self.sv_vcd.selections.push(desc); + } + } + for (index, desc) in external { + if !self + .sv_vcd + .external_selections + .iter() + .any(|(old, _)| *old == index) + { + self.sv_vcd.external_selections.push((index, desc)); + } + } + self.sv_vcd.started = Some(timestamp); + self.sv_vcd.pending = true; + } + 2 => self.flush_vcd().map_err(io_error)?, + 3..=5 => { + let command = match site.operation { + 3 => "dumpon", + 4 => "dumpoff", + _ => "dumpall", + }; + self.sv_vcd.suspended = + site.operation == 4 || (site.operation == 5 && self.sv_vcd.suspended); + let external = self.vcd_external_values(); + let (ptr, size) = self.backend.memory_as_ptr(); + // SAFETY: backend execution is suspended at this host boundary. + let memory = unsafe { std::slice::from_raw_parts(ptr, size) }; + if let Some(writer) = self.vcd_writer.as_mut() { + writer + .checkpoint(command, timestamp, memory, &external) + .map_err(io_error)?; + } + } + 6 => { + self.sv_vcd.limit = args + .first() + .and_then(ToPrimitive::to_u64) + .ok_or("$dumplimit requires a nonnegative 64-bit size")?; + if let Some(writer) = self.vcd_writer.as_mut() { + writer.set_byte_limit(self.sv_vcd.limit); + } + } + _ => return Err("unknown VCD task operation".into()), + } + Ok(()) + } + + fn source_vcd_external_values(&self) -> Vec<(num_bigint::BigUint, num_bigint::BigUint)> { + let values = self.components.trace_values(); + self.sv_vcd + .external_selections + .iter() + .map(|(index, _)| values[*index].clone()) + .collect() + } + + pub(crate) fn vcd_external_values(&self) -> Vec<(num_bigint::BigUint, num_bigint::BigUint)> { + if self.sv_vcd.source_writer { + let values = self.components.trace_values(); + self.sv_vcd + .active_external_indices + .iter() + .map(|index| values[*index].clone()) + .collect() + } else { + self.components.trace_values() + } + } + + pub(crate) fn start_sv_vcd(&mut self, timestamp: u64) -> std::io::Result<()> { + if !self.sv_vcd.pending { + return Ok(()); + } + let path = self + .sv_vcd + .path + .as_deref() + .unwrap_or_else(|| std::path::Path::new("dump.vcd")); + // Retire the buffered stream before File::create can truncate the + // same path. Dropping the old handle later must not publish stale bytes. + if let Some(old) = self.vcd_writer.as_mut() { + old.flush()?; + } + self.vcd_writer = None; + let mut writer = crate::VcdWriter::new_with_time_precision( + path, + &self.sv_vcd.selections, + self.program.design.time_precision, + )?; + writer.set_byte_limit(self.sv_vcd.limit); + let external_descs = self + .sv_vcd + .external_selections + .iter() + .map(|(_, desc)| desc.clone()) + .collect::>(); + writer.add_external_signals(&external_descs)?; + if self.sv_vcd.suspended { + let (ptr, size) = self.backend.memory_as_ptr(); + let memory = unsafe { std::slice::from_raw_parts(ptr, size) }; + writer.checkpoint( + "dumpoff", + timestamp, + memory, + &self.source_vcd_external_values(), + )?; + } + self.vcd_writer = Some(writer); + self.sv_vcd.source_writer = true; + self.sv_vcd.active_external_indices = self + .sv_vcd + .external_selections + .iter() + .map(|(index, _)| *index) + .collect(); + self.sv_vcd.pending = false; + Ok(()) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +struct DumpComponent { + name: String, + indices: Vec, +} + +impl DumpComponent { + fn name(name: String) -> Self { + Self { + name, + indices: Vec::new(), + } + } +} + +struct DumpTarget { + package: bool, + components: Vec, +} + +// Generated hierarchy names may combine scopes (g[0].u). Escaped authored +// names remain one component, including any punctuation in their spelling. +fn generated_dump_components(text: &str) -> Vec { + let mut components = Vec::new(); + let mut rest = text; + while !rest.is_empty() { + if rest.starts_with('\\') { + components.push(DumpComponent::name(rest.to_string())); + break; + } + let end = rest.find(['.', '[']).unwrap_or(rest.len()); + if end == 0 { + return vec![DumpComponent::name(text.to_string())]; + } + let mut component = DumpComponent::name(rest[..end].to_string()); + rest = &rest[end..]; + while let Some(indexed) = rest.strip_prefix('[') { + let Some(end) = indexed.find(']') else { + return vec![DumpComponent::name(text.to_string())]; + }; + let Ok(index) = indexed[..end].parse::() else { + return vec![DumpComponent::name(text.to_string())]; + }; + component.indices.push(index); + rest = &indexed[end + 1..]; + } + components.push(component); + if let Some(next) = rest.strip_prefix('.') { + rest = next; + } else if !rest.is_empty() { + return vec![DumpComponent::name(text.to_string())]; + } + } + components +} + +fn instance_dump_components( + instance: &crate::ir::RuntimeInstance, + top: &DumpComponent, +) -> Vec { + let mut components = vec![top.clone()]; + for ((name, _), display) in instance.path.0.iter().zip(&instance.display_path) { + let mut part = generated_dump_components(name); + // The authored name and its indexed display name are separate in + // metadata, so an escaped literal bracket cannot become an index. + if let Some(suffix) = display + .strip_prefix(name) + .filter(|suffix| !suffix.is_empty()) + { + let indexed = generated_dump_components(&format!("instance{suffix}")); + if let (Some(last), Some(indices)) = (part.last_mut(), indexed.first()) { + last.indices.extend_from_slice(&indices.indices); + } + } + components.extend(part); + } + components +} + +fn decode_dump_target( + text: &str, + top: &DumpComponent, + owner: &[DumpComponent], +) -> Result { + let mut fields = text.split('\0'); + let (kind, mut components) = if fields.next() == Some("celox.dump.path.v1") { + let kind = fields.next().ok_or("invalid $dumpvars path metadata")?; + let mut components: Vec = Vec::new(); + while let Some(tag) = fields.next() { + let value = fields.next().ok_or("invalid $dumpvars path metadata")?; + match tag { + "name" => components.push(DumpComponent::name(value.to_string())), + "index" => components + .last_mut() + .ok_or("invalid $dumpvars index metadata")? + .indices + .push( + value + .parse() + .map_err(|_| "invalid $dumpvars index metadata")?, + ), + _ => return Err("invalid $dumpvars path metadata".into()), + } + } + (kind, components) + } else { + // Existing plain site metadata remains readable by this runtime. + if let Some(absolute) = text.strip_prefix("$root.") { + ("absolute", generated_dump_components(absolute)) + } else if let Some((package, variable)) = text.split_once("::") { + let mut components = vec![DumpComponent::name(package.to_string())]; + components.extend(generated_dump_components(variable)); + ("package", components) + } else { + ("relative", generated_dump_components(text)) + } + }; + if !matches!(kind, "relative" | "local" | "absolute" | "package") { + return Err("invalid $dumpvars path kind metadata".into()); + } + if components.is_empty() { + return Err("$dumpvars selection is empty".into()); + } + if kind == "local" || (kind == "relative" && components.first() != Some(top)) { + let mut qualified = owner.to_vec(); + qualified.extend(components); + components = qualified; + } + Ok(DumpTarget { + package: kind == "package", + components, + }) +} + +fn dump_target_matches( + scope: &[DumpComponent], + variable: &[DumpComponent], + package: bool, + targets: &[DumpTarget], + levels: usize, +) -> bool { + let full = scope.iter().chain(variable).cloned().collect::>(); + targets.iter().any(|target| { + if target.package != package { + return false; + } + if full == target.components { + return true; + } + if package { + return false; + } + if scope.starts_with(&target.components) { + return levels == 0 || scope.len() - target.components.len() < levels; + } + // A named generate scope may own variables without a child module. + let variable_scope = &full[..full.len().saturating_sub(1)]; + target.components.len() > scope.len() + && variable_scope.starts_with(&target.components) + && (levels == 0 || variable_scope.len() - target.components.len() < levels) + }) +} + +#[cfg(all(test, feature = "systemverilog"))] +mod tests { + #[test] + fn relaxed_limit_rescans_consumed_backend_writes() { + for new_limit in [0, 1_000_000] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("resume.vcd"); + let source = "module Top(output logic [3:0] value); initial value=0; endmodule"; + let mut simulation = crate::Simulation::from_sv_sources( + vec![(source, std::path::Path::new("vcd.sv"))], + "Top", + ) + .vcd(&path) + .build() + .unwrap(); + simulation.run_until(0).unwrap(); + simulation + .simulator + .vcd_writer + .as_mut() + .unwrap() + .set_byte_limit(1); + let value = simulation.signal("value"); + simulation.modify(|io| io.set(value, 3u8)).unwrap(); + simulation.run_until(1).unwrap(); + // Limit changes made by the host do not themselves dirty a group, + // so this exercises the empty activity list on resumption. + simulation + .simulator + .vcd_writer + .as_mut() + .unwrap() + .set_byte_limit(new_limit); + simulation.run_until(2).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert!(text.contains("#2\nb11 "), "limit {new_limit}: {text}"); + } + } +} diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index a7636bdcf46..dceaed1f6bc 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -59,6 +59,19 @@ mod host { }; use num_bigint::BigUint; + #[derive(Default)] + pub(crate) struct SvVcdControl { + pub path: Option, + pub started: Option, + pub pending: bool, + pub selections: Vec, + pub external_selections: Vec<(usize, celox_runtime::VcdExternalSignalDesc)>, + pub source_writer: bool, + pub active_external_indices: Vec, + pub limit: u64, + pub suspended: bool, + } + /// Hierarchical instance tree with resolved signals. #[derive(Debug, Clone)] pub struct InstanceHierarchy { @@ -109,6 +122,7 @@ mod host { /// The program's scheduling facts. pub(crate) schedule: celox_design::schedule::ScheduleModel, pub(crate) vcd_writer: Option, + pub(crate) sv_vcd: SvVcdControl, pub(crate) dirty: bool, pub(crate) warnings: Vec, pub(crate) components: crate::component::ComponentRuntime, @@ -788,6 +802,7 @@ mod host { program, schedule, vcd_writer: None, + sv_vcd: SvVcdControl::default(), dirty: false, warnings, testbench_strings: Default::default(), @@ -1266,7 +1281,7 @@ mod host { self.eval_comb_checked().map_err(DumpError::Runtime)?; self.dirty = false; } - let component_traces = self.components.trace_values(); + let component_traces = self.vcd_external_values(); if let Some(ref mut writer) = self.vcd_writer { writer .dump_backend(timestamp, &mut self.backend, &component_traces) @@ -1288,6 +1303,19 @@ mod host { } } + pub(crate) fn try_dump_unless_rewound(&mut self, timestamp: u64) -> Result<(), DumpError> { + let rewound = self + .vcd_writer + .as_ref() + .and_then(|writer| writer.last_timestamp()) + .is_some_and(|last| timestamp < last); + if rewound { + Ok(()) + } else { + self.try_dump(timestamp) + } + } + /// Reject a return to `time` if the VCD file has already passed it. pub(crate) fn check_vcd_rewind(&self, time: u64) -> Result<(), CheckpointError> { match self diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index a545b696018..a1690891b03 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1553,6 +1553,17 @@ mod host { fn validate_untimed_host_requests( program: &crate::ir::RuntimeProgram, ) -> Result<(), SimulatorError> { + if program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Vcd) + { + return Err(SimulatorError::from(crate::RuntimeErrorCode::Runtime { + message: "source VCD controls require Simulation; Simulator does not execute initial process kernels".into(), + signals: Vec::new(), + })); + } if program .runtime_schema .processes @@ -1565,7 +1576,7 @@ mod host { .any(|site| site.requires_timed_simulation) { return Err(SimulatorError::from(crate::RuntimeErrorCode::Runtime { - message: "edge procedures using system file I/O or plusargs require Simulation; Simulator does not execute scheduled process kernels".into(), + message: "edge procedures using system file I/O, plusargs, or VCD controls require Simulation; Simulator does not execute scheduled process kernels".into(), signals: Vec::new(), })); } @@ -1590,7 +1601,13 @@ mod host { sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); - if vcd_path.is_some() { + let source_vcd = sim + .program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Vcd); + if vcd_path.is_some() || source_vcd { if sim.layout().unpacked_arrays.values().any(|array| { !array.element_width.is_multiple_of(8) || array.element_stride != array.element_width / 8 @@ -2549,11 +2566,24 @@ mod host { tracing::debug!("[phase-timing] compile_to_sir: {:?}", start.elapsed()); } + // A source request can originate in an include or mixed-language + // child. Decide from the elaborated schema before physical layout. + let vcd_recording = self.vcd_path.is_some() + || program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Vcd); + let layout_mode = if vcd_recording { + crate::backend::memory_layout::MemoryLayoutMode::Packed + } else { + layout_mode + }; // Build memory layout (consumes semantic layout requirements). let layout_start = phase_timing.then(crate::timing::now); let mut laid_out = program.into_laid_out_with_mode(self.options.four_state, layout_mode); - if self.vcd_path.is_some() { + if vcd_recording { laid_out.enable_vcd_tracking(); } if let Some(start) = layout_start { @@ -3187,10 +3217,21 @@ mod host { .map_err(|error| error.apply_diagnostic_policy(&self.options.diagnostic_policy)); let sim_res = program_res.and_then(|(program, mut warnings)| { self.options.diagnostic_policy.apply(&mut warnings)?; + let vcd_recording = self.vcd_path.is_some() + || program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Vcd); + let layout_mode = if vcd_recording { + crate::backend::memory_layout::MemoryLayoutMode::Packed + } else { + layout_mode + }; let mut laid_out = program.into_laid_out_with_mode(self.options.four_state, layout_mode); validate_untimed_host_requests(laid_out.runtime())?; - if self.vcd_path.is_some() { + if vcd_recording { laid_out.enable_vcd_tracking(); } @@ -3468,6 +3509,69 @@ mod host { Ok(()) } + #[cfg(all( + test, + feature = "systemverilog", + any( + all(target_arch = "x86_64", not(feature = "arm64-codegen")), + all(target_arch = "aarch64", not(feature = "x86_64-codegen")) + ) + ))] + #[test] + fn typed_vcd_selections_survive_native_image_roundtrip() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("native.vcd"); + let source = format!( + r#" + package p; logic state=1; endpackage + module Child(output logic \state.value ); initial \state.value = 1; endmodule + module Top #(parameter int INDEX=1) (output logic [1:0] bus, output logic \literal[0] ); + Child u[0:1](bus); + logic package_use; + assign package_use=p::state; + assign \literal[0] = 0; + initial begin $dumpfile("{}"); + $dumpvars(0, Top.u[INDEX].\state.value , p::state, \literal[0] ); + end + endmodule"#, + path.display() + ); + let (program, warnings, options, _, _) = crate::Simulation::from_sv_sources( + vec![(&source, std::path::Path::new("native-vcd.sv"))], + "Top", + ) + .into_laid_out_program(crate::MemoryLayoutMode::Packed) + .unwrap(); + let image = + crate::backend::native::NativeBackend::compile_image(&program, &options).unwrap(); + let image = + crate::NativeProgramImage::from_container_bytes(&image.to_container_bytes().unwrap()) + .unwrap(); + let runtime = image.runtime_program(); + assert!( + runtime + .runtime_schema + .host_request_sites + .iter() + .flat_map(|site| &site.strings) + .any(|path| path.contains("\0local\0")) + ); + // SAFETY: the image was compiled from this test's trusted source. + let backend = unsafe { crate::backend::native::NativeBackend::from_image(image) }.unwrap(); + let mut simulator = + crate::Simulator::with_backend_and_program_for_simulation(backend, runtime, warnings); + simulator.apply_initial_values(); + simulator.modify(|_| {}).unwrap(); + let mut simulation = crate::Simulation::new(simulator); + simulation.run_until(1).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!(text.matches("$var wire ").count(), 3, "{text}"); + assert!(text.contains("Top.u[1]"), "{text}"); + assert!(text.contains("\\state.value"), "{text}"); + assert!(text.contains("\\literal[0]"), "{text}"); + } + /// Resolve user-specified `(instance_path, var_path)` to `AbsoluteAddr` and run DSE. fn run_dead_store_elimination( program: &mut LaidOutProgram, @@ -3476,6 +3580,21 @@ mod host { ) { use crate::HashSet; let mut externally_live = HashSet::default(); + if program + .runtime_schema + .host_request_sites + .iter() + .any(|site| site.kind == celox_design::HostRequestKind::Vcd) + { + // A runtime hierarchy selection may observe every authored object. + externally_live.extend( + program + .design + .instances() + .flat_map(|instance| instance.state_addresses().iter().copied()), + ); + } + // Native testbench expressions bypass SIR and read simulator memory // directly. Their inputs are therefore external DSE roots just like // signals named with `live_signal()`. diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index 203cca1ce9e..b5a16a235a5 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -123,10 +123,10 @@ pub enum CheckpointError { "checkpoints are not supported for designs with external components, whose state Celox cannot capture" )] ExternalComponents, - /// Source-driven files have host state that is + /// Source-driven files and waveform controls have host state that is /// not represented in the saved HDL memory image. #[error( - "checkpoints and state files are not supported for designs with SystemVerilog file I/O" + "checkpoints and state files are not supported for designs with SystemVerilog file I/O or VCD control tasks" )] ExternalSystemTasks, #[error("the checkpoint was taken from a different design")] @@ -210,7 +210,12 @@ impl Simulator { .runtime_schema .host_request_sites .iter() - .any(|site| matches!(site.kind, celox_design::HostRequestKind::FileIo)) + .any(|site| { + matches!( + site.kind, + celox_design::HostRequestKind::FileIo | celox_design::HostRequestKind::Vcd + ) + }) { return Err(CheckpointError::ExternalSystemTasks); } diff --git a/crates/celox/tests/frontends/systemverilog/system_functions.rs b/crates/celox/tests/frontends/systemverilog/system_functions.rs index 86bbbee169b..4a0960a7a7c 100644 --- a/crates/celox/tests/frontends/systemverilog/system_functions.rs +++ b/crates/celox/tests/frontends/systemverilog/system_functions.rs @@ -1810,8 +1810,8 @@ fn reports_where_a_known_system_function_is_not_supported() { endmodule", ), ( - "system task `$dumpvars`", - "module Top(output logic y); initial $dumpvars; assign y = 0; endmodule", + "system task `$dumpports`", + "module Top(output logic y); initial $dumpports; assign y = 0; endmodule", ), ( "system task `$stacktrace`", diff --git a/crates/celox/tests/sv_host_requests.rs b/crates/celox/tests/sv_host_requests.rs index ed74e5e2ef5..9c0263d47b7 100644 --- a/crates/celox/tests/sv_host_requests.rs +++ b/crates/celox/tests/sv_host_requests.rs @@ -11,7 +11,8 @@ macro_rules! mixed_requests { let directory = tempfile::tempdir().unwrap(); let first = directory.path().join("first.txt"); let second = directory.path().join("second.txt"); - let source = String::from( + let waveform = directory.path().join("trace.vcd"); + let source = format!( r#" module Child #(parameter int ID = 0) (output logic [7:0] value, output logic ok); @@ -38,8 +39,14 @@ macro_rules! mixed_requests { timeunit 1ps; timeprecision 1ps; Child a(a_value, a_ok); Child #(.ID(1)) b(b_value, b_ok); + initial begin + $dumpfile("{}"); + $dumpvars(0, Top); + #2 $dumpflush; + end endmodule "#, + waveform.display() ); let mut simulation = celox::Simulation::from_sv_sources( vec![(&source, Path::new("mixed_host_requests.sv"))], @@ -55,12 +62,16 @@ macro_rules! mixed_requests { .$backend() .unwrap(); simulation.run_until(2).unwrap(); + simulation.flush_vcd().unwrap(); assert_eq!(simulation.get(simulation.signal("a_ok")), 1u8.into()); assert_eq!(simulation.get(simulation.signal("b_ok")), 1u8.into()); assert_eq!(simulation.get(simulation.signal("a_value")), 12u8.into()); assert_eq!(simulation.get(simulation.signal("b_value")), 30u8.into()); assert_eq!(std::fs::read_to_string(first).unwrap(), "Top.a:11\n"); assert_eq!(std::fs::read_to_string(second).unwrap(), "Top.b:29\n"); + let trace = std::fs::read_to_string(waveform).unwrap(); + assert!(trace.contains("$dumpvars")); + assert!(trace.contains("#1\n")); } }; } @@ -73,22 +84,25 @@ mixed_requests!(native, build_native); #[test] fn external_host_state_rejects_checkpoints_and_state_files() { - let statement = r#"$fwrite(1, "output");"#; - let source = - format!("module Top(output bit q); initial begin {statement} q = 1; end endmodule"); - let mut simulation = - celox::Simulation::from_sv_sources(vec![(&source, Path::new("external_state.sv"))], "Top") - .build_interpreter() - .unwrap(); - assert!(matches!( - simulation.checkpoint(), - Err(celox::CheckpointError::ExternalSystemTasks) - )); - assert!( - simulation - .save_state() - .unwrap_err() - .to_string() - .contains("SystemVerilog file I/O") - ); + for statement in ["$fwrite(1, \"output\");", "$dumpvars;"] { + let source = + format!("module Top(output bit q); initial begin {statement} q = 1; end endmodule"); + let mut simulation = celox::Simulation::from_sv_sources( + vec![(&source, Path::new("external_state.sv"))], + "Top", + ) + .build_interpreter() + .unwrap(); + assert!(matches!( + simulation.checkpoint(), + Err(celox::CheckpointError::ExternalSystemTasks) + )); + assert!( + simulation + .save_state() + .unwrap_err() + .to_string() + .contains("SystemVerilog file I/O or VCD") + ); + } } diff --git a/crates/celox/tests/sv_vcd.rs b/crates/celox/tests/sv_vcd.rs new file mode 100644 index 00000000000..0927f6e1097 --- /dev/null +++ b/crates/celox/tests/sv_vcd.rs @@ -0,0 +1,902 @@ +#![cfg(feature = "systemverilog")] +//! Source-driven VCD controls exercise host requests and trace observation. +use celox::{SimBackend, Simulation}; +use std::path::Path; + +fn capture(mut simulation: Simulation, path: &Path) -> String { + simulation.run_until(4).unwrap(); + simulation.flush_vcd().unwrap(); + std::fs::read_to_string(path).unwrap() +} + +macro_rules! backends { + ($name:ident, $body:expr) => { + mod $name { + use super::*; + #[test] + fn interpreter() { + ($body)("interpreter", 0); + } + #[test] + fn cranelift() { + ($body)("cranelift", 1); + } + #[test] + fn wasm() { + ($body)("wasm", 2); + } + #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] + #[test] + fn native() { + ($body)("native", 3); + } + } + }; +} + +backends!(controls, |backend: &str, number: usize| { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join(format!("{backend}.vcd")); + let source = format!( + r#" + module Top(output logic [3:0] value); + timeunit 1ps; timeprecision 1ps; + initial begin + $dumpfile("{}"); + $dumpvars(0, Top.value); + value = 4'b10xz; + #1 $dumpoff; value = 4'b1111; + #1 $dumpon; + #1 $dumpall; $dumpflush; + end + endmodule + "#, + path.display() + ); + let build = || { + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top").four_state(true) + }; + let text = match number { + 0 => capture(build().build_interpreter().unwrap(), &path), + 1 => capture(build().build_cranelift().unwrap(), &path), + 2 => capture(build().build_wasm().unwrap(), &path), + _ => capture(build().build_native().unwrap(), &path), + }; + assert!(text.contains("$var wire 4"), "{text}"); + assert!(text.contains("b10xz "), "{text}"); + assert!(text.contains("$dumpoff\nbxxxx "), "{text}"); + assert!(text.contains("$dumpon\nb1111 "), "{text}"); + assert!(text.contains("$dumpall\nb1111 "), "{text}"); + assert!(!text.contains("vcd_argument"), "{text}"); +}); + +#[test] +fn depth_and_multiple_selections() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("hierarchy.vcd"); + let source = format!( + r#" + module Child(output logic child_value); + timeunit 1ps; timeprecision 1ps; + initial child_value = 1; + endmodule + module Top(output logic own_value, output logic child_wire); + timeunit 1ps; timeprecision 1ps; + Child child(.child_value(child_wire)); + initial begin + $dumpfile("{}"); + $dumpvars(1, Top); + $dumpvars(0, Top.child.child_value); + own_value = 1; + end + endmodule + "#, + path.display() + ); + let sim = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let text = capture(sim, &path); + assert!(text.contains("own_value"), "{text}"); + assert!(text.contains("child_value"), "{text}"); +} + +#[test] +fn later_dumpvars_reports_runtime_error() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("late.vcd"); + let source = format!( + r#"module Top(output logic value); + timeunit 1ps; timeprecision 1ps; + initial begin $dumpfile("{}"); $dumpvars; #1 $dumpvars; end + endmodule"#, + path.display() + ); + let mut sim = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let error = sim.run_until(2).unwrap_err(); + assert!(format!("{error:?}").contains("same simulation time")); +} + +#[test] +fn source_controls_keep_packed_array_storage_native() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("array.vcd"); + let source = format!( + r#"module Top(output logic done); + timeunit 1ps; timeprecision 1ps; + logic [4:0] memory [0:1]; + initial begin + $dumpfile("{}"); $dumpvars(0, Top.memory); + memory[0] = 5'h03; memory[1] = 5'h15; done = 1; + end + endmodule"#, + path.display() + ); + let sim = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build() + .unwrap(); + let text = capture(sim, &path); + assert!(text.contains("$var wire 10"), "{text}"); + assert!(text.contains("memory"), "{text}"); + assert!(!text.contains(" done "), "{text}"); +} + +#[test] +fn finish_flushes_source_waveform() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("finish.vcd"); + let source = format!( + r#"module Top(output logic value); + timeunit 1ps; timeprecision 1ps; + initial begin $dumpfile("{}"); $dumpvars; value = 1; $finish; end + endmodule"#, + path.display() + ); + let mut sim = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + sim.run_until(1).unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("value"), "{text}"); + assert!(text.contains("#0\n1"), "{text}"); +} + +#[test] +fn unwritable_source_path_returns_runtime_error() { + let dir = tempfile::tempdir().unwrap(); + // Opening a directory as an output file fails regardless of user privileges. + let source = format!( + r#"module Top(output logic value); + initial begin $dumpfile("{}"); $dumpvars; value = 1; end + endmodule"#, + dir.path().display() + ); + let mut sim = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let error = sim.run_until(1).unwrap_err(); + assert!(format!("{error:?}").contains("VCD setup failed")); +} + +#[test] +fn embedded_filename_nul_is_rejected() { + let source = r#"module Top(output logic value); + initial begin $dumpfile(32'h61006200); $dumpvars; value = 1; end + endmodule"#; + let mut sim = Simulation::from_sv_sources(vec![(source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let error = sim.run_until(1).unwrap_err(); + assert!(format!("{error:?}").contains("NUL byte")); +} + +#[test] +fn authored_internal_looking_names_are_selected() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("authored.vcd"); + let source = format!( + r#"module Top(output logic __celox_user); + initial begin $dumpfile("{}"); $dumpvars(0, Top.__celox_user); __celox_user=1; end + endmodule"#, + path.display() + ); + let simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let text = capture(simulation, &path); + assert!(text.contains(" __celox_user $end"), "{text}"); + assert!(!text.contains("vcd_argument"), "{text}"); +} + +#[test] +fn removing_reached_limit_rescans_stable_values() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("resumed.vcd"); + let source = format!( + r#"module Top(output logic [3:0] value); + timeunit 1ps; timeprecision 1ps; + initial begin + $dumpfile("{}"); $dumpvars; value=0; + #1 $dumplimit(1); value=3; + #1 value=5; + #1 $dumplimit(0); + end endmodule"#, + path.display() + ); + let simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build() + .unwrap(); + let text = capture(simulation, &path); + assert!(text.contains("VCD dump limit reached"), "{text}"); + assert!(text.contains("#3\nb101 "), "{text}"); +} + +#[test] +fn source_replacement_flushes_old_writer_before_truncation() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("same.vcd"); + let source = format!( + r#"module Top(output logic value); + timeunit 1ps; timeprecision 1ps; + initial begin + value=0; + #1 $dumpfile("{}"); $dumpvars(0, Top.value); value=1; + end endmodule"#, + path.display() + ); + let mut simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .vcd(&path) + .build_interpreter() + .unwrap(); + // Populate the old writer's buffer with more bytes than the replacement. + for _ in 0..1000 { + simulation.dump(0); + } + let text = { + simulation.run_until(2).unwrap(); + simulation.flush_vcd().unwrap(); + std::fs::read_to_string(path).unwrap() + }; + assert_eq!(text.matches("$enddefinitions").count(), 1, "{text}"); + assert!( + !text.contains("#0"), + "old buffered timestamps survived replacement: {text}" + ); +} + +#[cfg(target_os = "linux")] +#[test] +fn ordinary_timed_write_failure_is_returned() { + let source = r#"module Top(output logic [2097151:0] value); + initial begin $dumpfile("/dev/full"); $dumpvars; value='1; end + endmodule"#; + let mut simulation = Simulation::from_sv_sources(vec![(source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| simulation.run_until(1))); + let error = result + .expect("a timed waveform failure must not panic") + .unwrap_err(); + assert!( + format!("{error:?}").contains("VCD dump failed"), + "{error:?}" + ); +} + +#[test] +fn direct_finish_finalizes_source_waveform() { + for action in ["get", "get_four_state", "eval_comb", "dump"] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("direct.vcd"); + let source = format!( + r#"module Top(input logic stop_now, output logic value); + initial begin $dumpfile("{}"); $dumpvars; end + always_comb begin value=stop_now; if (stop_now) $finish; end + endmodule"#, + path.display() + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + let stop = simulation.signal("stop_now"); + let value = simulation.signal("value"); + simulation.modify(|io| io.set(stop, 1u8)).unwrap(); + match action { + "get" => { + simulation.get(value); + } + "get_four_state" => { + simulation.get_four_state(value); + } + "eval_comb" => simulation.eval_comb().unwrap(), + _ => simulation.try_dump(1).unwrap(), + } + // Read with the simulator alive: finish must flush, independently of Drop. + let text = std::fs::read_to_string(&path).unwrap(); + let last = text.rsplit("#1\n").next().unwrap(); + assert!( + last.lines().any(|line| line.starts_with('1')), + "{action}: {text}" + ); + assert!(simulation.is_finished()); + } +} + +#[test] +fn absolute_root_dump_targets_resolve_from_child_scope() { + for target in ["$root.Top.value", "$root.Top"] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("root.vcd"); + let source = format!( + r#" + module Recorder; + initial begin $dumpfile("{}"); $dumpvars(0, {target}); end + endmodule + module Top(output logic value); + Recorder recorder(); + initial value=1; + endmodule"#, + path.display() + ); + let simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let text = capture(simulation, &path); + assert!(text.contains(" value $end"), "{target}: {text}"); + assert!( + !text.contains("$root"), + "the pseudo-root must not become a VCD scope: {text}" + ); + } +} + +#[test] +fn module_recursive_dump_excludes_package_state() { + for selection in ["$dumpvars(0, Top);", "$dumpvars(0);", "$dumpvars;"] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("package.vcd"); + let source = format!( + r#" + package p; logic [7:0] package_only = 8'd7; endpackage + module Child(output logic [7:0] child_value); + import p::*; + assign child_value=package_only; + endmodule + module Top(output logic [7:0] value, child_value); + import p::*; + Child child(child_value); + assign value=package_only; + initial begin $dumpfile("{}"); {selection} end + endmodule"#, + path.display() + ); + let simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let text = capture(simulation, &path); + assert!(text.contains(" value $end"), "{selection}: {text}"); + assert!(text.contains(" child_value $end"), "{selection}: {text}"); + let package_count = text.matches(" package_only $end").count(); + assert_eq!( + package_count, + usize::from(selection == "$dumpvars;"), + "{selection}: {text}" + ); + assert!( + !text.contains("Top.p::"), + "packages must not appear beneath the top module: {text}" + ); + } +} + +#[test] +fn escaped_dump_identifiers_keep_literal_delimiters() { + for target in [ + r"Top.\a.b ", + r"Top.\array[0] ", + r"Top.\u.x .\state.value ", + r"$root.Top.\u.x .\state.value ", + r"\$root.Top.value ", + ] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("escaped.vcd"); + let source = format!( + r#"module Child(output logic \state.value ); + initial \state.value = 1; + endmodule + module Top(output logic \a.b , \array[0] , \$root.Top.value , child_value); + Child \u.x (child_value); + initial begin \a.b = 1; \array[0] = 0; \$root.Top.value = 1; + $dumpfile("{}"); $dumpvars(0, {target}); end + endmodule"#, + path.display() + ); + let simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let text = capture(simulation, &path); + assert_eq!(text.matches("$var wire ").count(), 1, "{target}: {text}"); + } +} + +#[test] +fn constant_indexed_instance_and_generate_selections() { + for target in [ + "Top.u[INDEX + 0]", + "Top.g[INDEX + 0]", + "Top.g[INDEX].nested.value", + "$root.Top.g[INDEX]", + ] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("indexed.vcd"); + let source = format!( + r#"module Child(output logic value); initial value=1; endmodule + module Top #(parameter int INDEX=1) (output logic [1:0] bus); + Child u[0:1](bus); + for (genvar i=0; i<2; i++) begin:g + logic generated; + initial generated=1; + Child nested(); + end + initial begin $dumpfile("{}"); $dumpvars(0, {target}); end + endmodule"#, + path.display() + ); + let simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let text = capture(simulation, &path); + assert!(text.contains("[1]"), "{target}: {text}"); + assert!(!text.contains("[0]"), "{target}: {text}"); + } +} + +#[test] +fn explicit_package_dump_selects_only_requested_variable() { + for target in ["p::state", r"\p.q ::\state.value "] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("package-select.vcd"); + let source = format!( + r#"package p; logic [7:0] state=7; logic [7:0] other=9; endpackage + package \p.q ; logic \state.value = 1; endpackage + module Recorder; + initial begin $dumpfile("{}"); $dumpvars(0, {target}); end + endmodule + module Top(output logic [7:0] value, output logic escaped_value); + assign value=p::other; + assign escaped_value=\p.q ::\state.value ; + Recorder recorder(); + endmodule"#, + path.display() + ); + let simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let text = capture(simulation, &path); + assert_eq!(text.matches("$var wire ").count(), 1, "{target}: {text}"); + assert!(!text.contains(" other $end"), "{target}: {text}"); + assert!(!text.contains("$scope module Top"), "{target}: {text}"); + } +} + +#[test] +fn initial_vcd_tasks_require_timed_simulation_on_every_backend() { + for task in ["$dumpvars;", "$dumpflush;"] { + let source = format!("module Top; initial begin {task} end endmodule"); + let build = + || celox::Simulator::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top"); + let errors = [ + build().build_interpreter().unwrap_err(), + build().build_cranelift().unwrap_err(), + build().build_wasm().unwrap_err(), + build().build().unwrap_err(), + ]; + for error in errors { + assert!( + format!("{error:?}").contains("source VCD controls require Simulation"), + "{error:?}" + ); + } + } +} + +#[cfg(target_os = "linux")] +#[test] +fn finish_stays_terminal_when_final_waveform_output_fails() { + for width in [1, 2097152] { + let source = format!( + r#"module Top(output logic [{high}:0] value); + initial begin $dumpfile("/dev/full"); $dumpvars; value='1; $finish; end + initial begin #1 value='0; end + endmodule"#, + high = width - 1 + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + assert!(simulation.run_until(2).is_err()); + assert!(simulation.is_finished(), "width={width}"); + let time = simulation.time(); + assert_eq!(simulation.step().unwrap(), None); + simulation.run_until(10).unwrap(); + assert_eq!(simulation.time(), time); + } +} + +#[test] +fn pending_source_waveform_is_finalized_on_fatal_error() { + let dir = tempfile::tempdir().unwrap(); + for path in [ + dir.path().join("fatal.vcd"), + dir.path().join("absent/fatal.vcd"), + ] { + let source = format!( + r#"module Top(output logic value); + initial begin $dumpfile("{}"); $dumpvars; value=1; $fatal(1,"primary failure"); end + endmodule"#, + path.display() + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let error = simulation.run_until(1).unwrap_err(); + assert!( + format!("{error:?}").contains("primary failure"), + "{error:?}" + ); + if path.parent() == Some(dir.path()) { + let text = std::fs::read_to_string(path).unwrap(); + assert!(text.contains("$enddefinitions"), "{text}"); + assert!(text.contains("1!"), "{text}"); + } + } +} + +#[test] +fn host_waveform_switch_keeps_source_suspension_and_limit() { + for control in ["$dumpoff", "$dumplimit(1)"] { + let dir = tempfile::tempdir().unwrap(); + let first = dir.path().join("first.vcd"); + let second = dir.path().join("second.vcd"); + let source = format!( + r#"module Top(output logic value); + timeunit 1ps; timeprecision 1ps; + initial begin $dumpfile("{}"); $dumpvars; value=0; + #1 {}; #1 value=1; #1 $dumpon; $dumplimit(0); #1 value=0; + end endmodule"#, + first.display(), + control + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + simulation.switch_vcd(&second).unwrap(); + simulation.run_until(2).unwrap(); + simulation.flush_vcd().unwrap(); + let paused = std::fs::read_to_string(&second).unwrap(); + if control == "$dumpoff" { + assert!(!paused.contains("#2"), "{control}: {paused}"); + } else { + assert!(paused.contains("VCD dump limit reached"), "{paused}"); + assert!(!paused.contains("1!"), "{paused}"); + } + simulation.run_until(4).unwrap(); + simulation.flush_vcd().unwrap(); + let resumed = std::fs::read_to_string(second).unwrap(); + assert!(resumed.contains("#3"), "{control}: {resumed}"); + assert!(resumed.contains("#4"), "{control}: {resumed}"); + } +} + +#[test] +fn imported_dump_target_follows_package_declaration_and_local_shadowing() { + for (declaration, package) in [ + ("import p::*;", true), + ("import p::state;", true), + ("import p::*; logic state;", false), + ] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("import.vcd"); + let source = format!( + r#"package p; logic state=1; logic other=0; endpackage + module Top; {} initial begin $dumpfile("{}"); $dumpvars(0,state); end endmodule"#, + declaration, + path.display() + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!(text.matches("$var ").count(), 1, "{text}"); + assert_eq!(text.contains("$scope module p::"), package, "{text}"); + assert!(!text.contains(" other "), "{text}"); + } +} + +#[cfg(target_os = "linux")] +#[test] +fn direct_finish_error_stays_terminal() { + let source = r#"module Top(input logic stop_now, output logic value); + initial begin $dumpfile("/dev/full"); $dumpvars; end + always_comb begin value=stop_now; if(stop_now) $finish; end + endmodule"#; + let mut simulation = Simulation::from_sv_sources(vec![(source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(0).unwrap(); + let stop = simulation.signal("stop_now"); + simulation.modify(|io| io.set(stop, 1u8)).unwrap(); + assert!(simulation.eval_comb().is_err()); + assert!(simulation.is_finished()); + assert_eq!(simulation.step().unwrap(), None); +} + +#[test] +fn imported_escaped_package_delimiters_remain_literal() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("escaped-import.vcd"); + let source = format!( + r#"package \p::q ; logic \state::value =1; endpackage + module Top; import \p::q ::*; + initial begin $dumpfile("{}"); $dumpvars(0,\state::value ); end endmodule"#, + path.display() + ); + let mut simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!(text.matches("$var ").count(), 1, "{text}"); + assert!(text.contains("\\state::value"), "{text}"); +} + +#[test] +fn scoped_parameter_dump_does_not_select_imported_state() { + let source = r#"package p; logic state=1; endpackage + module Top; import p::*; + initial begin localparam int state=0; $dumpvars(0,state); end endmodule"#; + let mut simulation = Simulation::from_sv_sources(vec![(source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + let error = simulation.run_until(1).unwrap_err(); + assert!( + format!("{error:?}").contains("selection matches no dumpable variables"), + "{error:?}" + ); +} + +#[test] +fn direct_fatal_errors_publish_waveform_without_freezing_recovery() { + for action in ["eval_comb", "try_dump"] { + check_direct_fatal_waveform(action); + } +} + +#[test] +fn final_run_until_fatal_publishes_waveform() { + check_direct_fatal_waveform("run_until"); +} + +#[test] +fn final_bounded_run_fatal_publishes_waveform() { + check_direct_fatal_waveform("run_until_bounded"); +} + +fn check_direct_fatal_waveform(action: &str) { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("direct-fatal.vcd"); + let source = format!( + r#"module Top(input logic fail_now, output logic value); + initial begin $dumpfile("{}"); $dumpvars(0,Top.value); end + always_comb begin value=fail_now; if(fail_now) $fatal(1,"direct primary"); end + endmodule"#, + path.display() + ); + let mut simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(0).unwrap(); + let fail = simulation.signal("fail_now"); + simulation.modify(|io| io.set(fail, 1u8)).unwrap(); + let error = match action { + "eval_comb" => format!("{:?}", simulation.eval_comb().unwrap_err()), + "try_dump" => format!("{:?}", simulation.try_dump(0).unwrap_err()), + "run_until" => format!("{:?}", simulation.run_until(1).unwrap_err()), + "run_until_bounded" => format!("{:?}", simulation.run_until_bounded(1, 10).unwrap_err()), + _ => unreachable!(), + }; + assert!(error.contains("direct primary"), "{action}: {error}"); + let text = std::fs::read_to_string(path).unwrap(); + assert!(text.contains("1!"), "{action}: {text}"); + simulation.modify(|io| io.set(fail, 0u8)).unwrap(); + simulation.eval_comb().unwrap(); + let value = simulation.signal("value"); + assert_eq!(simulation.get(value), 0u8.into()); + assert!(!simulation.is_finished()); +} + +#[test] +fn package_task_dump_target_keeps_lexical_package_owner() { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("package-task.vcd"); + let source = format!( + r#"package p; logic state=1; + task automatic trace(); $dumpvars(0,state); endtask endpackage + module Top; logic state=0; + initial begin $dumpfile("{}"); p::trace(); end endmodule"#, + path.display() + ); + let mut simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!(text.matches("$var ").count(), 1, "{text}"); + assert!(text.contains("$scope module p::"), "{text}"); + assert!(text.contains("1!"), "{text}"); +} + +#[test] +fn lexical_dump_target_shadows_top_module_name_in_child() { + for declaration in ["logic Top=1;", "Leaf Top();"] { + for selection in ["Top", "$root.Top.root_value"] { + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("lexical.vcd"); + let source = format!( + r#"module Leaf; logic value=1; endmodule + module Child; {} + initial begin $dumpfile("{}"); $dumpvars(0,{}); end endmodule + module Top; logic root_value=0; Child child(); endmodule"#, + declaration, + path.display(), + selection + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!( + text.matches("$var ").count(), + 1, + "{declaration}, {selection}: {text}" + ); + if selection == "Top" { + assert!(!text.contains(" root_value "), "{text}"); + assert!(text.contains("1!"), "{text}"); + } else { + assert!(text.contains(" root_value "), "{text}"); + assert!(text.contains("0!"), "{text}"); + } + } + } +} + +#[test] +fn initial_dump_limit_bounds_header_and_resumes_current_snapshot() { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("header-limit.vcd"); + let declarations = (0..100) + .map(|i| format!("logic signal_{i}=1;\n")) + .collect::(); + let source = format!( + r#"module Top; timeunit 1ps; timeprecision 1ps; {} + initial begin $dumpfile("{}"); $dumplimit(1); $dumpvars; + #1 $dumpoff; #1 $dumplimit(0); #1 $dumpon; end endmodule"#, + declarations, + path.display() + ); + let mut simulation = Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(0).unwrap(); + simulation.flush_vcd().unwrap(); + let paused = std::fs::read_to_string(&path).unwrap(); + assert!( + paused.len() < 128, + "header ignored limit: {} bytes", + paused.len() + ); + assert!(paused.contains("VCD dump limit reached"), "{paused}"); + assert!(!paused.contains("$var "), "{paused}"); + simulation.run_until(2).unwrap(); + simulation.flush_vcd().unwrap(); + assert_eq!(std::fs::read_to_string(&path).unwrap(), paused); + simulation.run_until(3).unwrap(); + simulation.flush_vcd().unwrap(); + let resumed = std::fs::read_to_string(path).unwrap(); + assert_eq!(resumed.matches("$date\n").count(), 1, "{resumed}"); + assert_eq!(resumed.matches("$var wire ").count(), 100, "{resumed}"); + assert!(resumed.contains("#3\n$dumpon\n"), "{resumed}"); +} + +#[test] +fn omitted_dump_depth_preserves_explicit_recursive_selections() { + for (selection, count) in [("Top.value", 1), ("Top.child", 2), ("p::state", 1)] { + let directory = tempfile::tempdir().unwrap(); + let path = directory.path().join("omitted-depth.vcd"); + let source = format!( + r#"package p; logic state=1; logic other=0; endpackage + module Grandchild; logic grand_value=1; endmodule + module Child; logic child_value=1; Grandchild grand(); endmodule + module Top; logic value=1; logic package_use; Child child(); + assign package_use=p::other; + initial begin $dumpfile("{}"); $dumpvars(,{}); end endmodule"#, + path.display(), + selection + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + simulation.flush_vcd().unwrap(); + let text = std::fs::read_to_string(path).unwrap(); + assert_eq!( + text.matches("$var wire ").count(), + count, + "{selection}: {text}" + ); + assert!(!text.contains(" other "), "{text}"); + if selection == "Top.child" { + assert!(text.contains(" grand_value "), "{text}"); + } + assert_eq!( + text.contains("$scope module p::"), + selection == "p::state", + "{text}" + ); + } +} + +#[test] +fn dumpfile_uses_shared_string_literal_escape_decoding() { + for kind in ["ordinary", "triple", "lf", "crlf", "triple-crlf"] { + let directory = tempfile::tempdir().unwrap(); + let base = directory.path().join("wave"); + let (delimiter, continuation) = match kind { + "triple" => ("\"\"\"", ""), + "lf" => ("\"", "\\\n"), + "crlf" => ("\"", "\\\r\n"), + "triple-crlf" => ("\"\"\"", "\\\r\n"), + _ => ("\"", ""), + }; + let literal = format!( + "{delimiter}{}{continuation}\\056vcd{delimiter}", + base.display() + ); + let source = format!( + "module Top; logic value=1; initial begin $dumpfile({literal}); $dumpvars(0,Top.value); end endmodule" + ); + let mut simulation = + Simulation::from_sv_sources(vec![(&source, Path::new("vcd.sv"))], "Top") + .build_interpreter() + .unwrap(); + simulation.run_until(1).unwrap(); + simulation.flush_vcd().unwrap(); + let path = directory.path().join("wave.vcd"); + let text = std::fs::read_to_string(&path) + .unwrap_or_else(|error| panic!("{kind}: {error}, literal={literal:?}")); + assert!(text.contains("1!"), "{kind}: {text}"); + assert_eq!( + std::fs::read_dir(directory.path()).unwrap().count(), + 1, + "{kind}" + ); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 6ebeb90dbc5..10cb245e6b0 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -69,7 +69,7 @@ as waits written directly in a process. | Random numbers | `$urandom`, `$urandom_range`, `$random` and `$dist_uniform` in clocked processes, `always_comb`, `always @*`, `initial` blocks and their subroutines; an optional integral seed of `$urandom`, a seed variable of `$random`, and a separate stream per process | | Simulation time | `$time` and `$stime` in clocked and combinational processes, continuous assignments, `initial` blocks and their subroutines | | System tasks | `$printtimescale`, `$display`, `$write` and their `b` / `o` / `h` forms, `$error`, `$warning`, `$info`, `$fatal`, `$finish`, `$stop`, `$exit` in `always` processes, subroutines and `initial` blocks; `$readmemh` / `$readmemb` there and in `initial` blocks; Veryl's `$assert` and `$assert_continue` | -| Runtime I/O | `$test$plusargs`, `$value$plusargs`, `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and radix variants, `$writememh` / `$writememb` in timed processes | +| Runtime I/O | `$test$plusargs`, `$value$plusargs`, `$fopen`, `$fclose`, `$fdisplay` / `$fwrite` and radix variants, `$writememh` / `$writememb`, and [VCD controls](./vcd#systemverilog-source-controls) in timed processes | | State | two-state and four-state simulation | Every construct above is covered by tests that compare the result with a @@ -367,8 +367,9 @@ strings are unsupported. See [runtime file output](#runtime-file-output) for file descriptors and memory snapshots. -Checkpoints and state files reject designs with file I/O, whose host state they -cannot capture. +[Source VCD controls](./vcd#systemverilog-source-controls) start recording after +the current timestamp settles. Checkpoints and state files reject designs with +file I/O or source VCD controls, whose host state they cannot capture. ## Time and precision {#time-and-precision} diff --git a/docs/guide/vcd.md b/docs/guide/vcd.md index 7a7ec0549a9..e9d66783d0e 100644 --- a/docs/guide/vcd.md +++ b/docs/guide/vcd.md @@ -59,3 +59,30 @@ sim.dispose(); ## Further Reading - [Writing Tests](./writing-tests.md) -- Simulator and Simulation patterns. + +## SystemVerilog controls {#systemverilog-source-controls} + +A timed SystemVerilog simulation can select and control tracing from HDL: + +```systemverilog +initial begin + $dumpfile("waves.vcd"); + $dumpvars(0, Top); +end +``` + +`$dumpvars` starts recording after the current simulation timestamp settles. +All calls must execute at the same simulation time. A level of `0` includes +all descendants; `1` includes only the named module's own variables. Individual +variables and multiple module or variable selections are supported. + +`$dumpoff` records unknown values and suspends tracing. `$dumpon` records current +values and resumes it. `$dumpall` records every selected value without changing +that state. `$dumpflush` publishes buffered output, and `$dumplimit(bytes)` stops +recording at the size limit with a comment in the file. Complete records may +extend past the limit. A zero limit removes the bound. + +`$dumpfile` accepts a string literal or an integral expression containing the +filename and must run before `$dumpvars`. The default filename is `dump.vcd`. +Source controls enable the necessary trace storage automatically; a host VCD +path is optional. Host waveform methods remain available. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index de6bab59b87..9cb190ed084 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -64,7 +64,7 @@ package/`$unit` の static 引数を持つ時間待ち task と、static task | 乱数 | `$urandom`、`$urandom_range`、`$random`、`$dist_uniform` はクロックで起動するプロセス、`always_comb`、`always @*`、`initial` とそれらから呼ぶサブルーチンで使用可能。`$urandom` の任意の整数式によるシード、`$random` のシード変数、プロセスごとに独立した乱数列 | | シミュレーション時刻 | `$time` と `$stime` はクロックで起動するプロセス、組合せプロセス、継続代入、`initial` とそれらから呼ぶサブルーチンで使用可能 | | システムタスク | `always` 系のプロセスとサブルーチンの `$printtimescale`、`$display`、`$write` とその `b` / `o` / `h` 形、`$error`、`$warning`、`$info`、`$fatal`、`$finish`、`$stop`、`$exit`。`initial` ブロックでも使えます。`$readmemh` / `$readmemb` はそれらと `initial` ブロック。Veryl の `$assert` と `$assert_continue` | -| 実行時 I/O | `$test$plusargs`、`$value$plusargs`、`$fopen`、`$fclose`、`$fdisplay` / `$fwrite` と基数指定形、`$writememh` / `$writememb`。時間を持つプロセスで実行 | +| 実行時 I/O | `$test$plusargs`、`$value$plusargs`、`$fopen`、`$fclose`、`$fdisplay` / `$fwrite` と基数指定形、`$writememh` / `$writememb`、[VCD 制御](./vcd#systemverilog-source-controls)。時間を持つプロセスで実行 | | 状態 | 2 値・4 値シミュレーション | 上記の各構文は、ソフトウェアモデルと結果を比較するテストで確認しています。Veryl が出力する @@ -267,7 +267,8 @@ real 変換と動的 string は未対応です。 ファイル descriptor とメモリ書き出しは[実行時のファイル出力](#実行時のファイル出力)を参照してください。 -ファイル I/O を含むデザインでは、ホスト側の状態を保存できないため、 +[VCD 制御](./vcd#systemverilog-source-controls)の記録開始は、その時刻の状態が確定した後です。 +ファイル I/O または SV からの VCD 制御を含むデザインでは、ホスト側の状態を保存できないため、 checkpoint と状態ファイルの保存・復元はエラーになります。 `$dist_uniform(seed, start, end)` は Annex N の一様分布を使い、整数の seed 変数を更新します。 diff --git a/docs/ja/guide/vcd.md b/docs/ja/guide/vcd.md index 9a890c5038f..1a211d75ed4 100644 --- a/docs/ja/guide/vcd.md +++ b/docs/ja/guide/vcd.md @@ -56,3 +56,29 @@ sim.dispose(); ## 関連資料 - [テストの書き方](./writing-tests.md) -- Simulator・Simulation のパターン。 + +## SystemVerilog からの制御 {#systemverilog-source-controls} + +時刻付きシミュレーションでは HDL から波形を指定できます。 + +```systemverilog +initial begin + $dumpfile("waves.vcd"); + $dumpvars(0, Top); +end +``` + +`$dumpvars` は現在時刻の処理が収束してから記録を開始します。すべての呼び出しを +同じシミュレーション時刻に実行してください。深さ `0` は子階層をすべて含み、 +`1` は指定モジュール自身の変数だけを含みます。個別変数や複数の選択も指定できます。 + +`$dumpoff` は不定値を記録して停止し、`$dumpon` は現在値を記録して再開します。 +`$dumpall` は記録の停止状態を変えずに選択変数の現在値をすべて記録します。 +`$dumpflush` はバッファを出力します。`$dumplimit(bytes)` はサイズ上限に達すると +コメントを出力して記録を停止します。完全なレコードを出力するため上限を多少超える +場合があります。上限 `0` はサイズ制限を解除します。 + +`$dumpfile` は文字列リテラルまたはファイル名を格納した整数式を受け取り、 +`$dumpvars` より前に実行する必要があります。既定のファイル名は `dump.vcd` です。 +必要なトレース用ストレージは自動で有効になるため、ホスト側での VCD パス指定は +省略できます。既存のホスト側の波形 API も引き続き使用できます。