From b291fe81c5be157941669c56de715b9f0033daf0 Mon Sep 17 00:00:00 2001 From: tignear Date: Tue, 20 Oct 2026 07:08:08 +0900 Subject: [PATCH] feat(cli)!: configure optimization and explicit signal access `celox run` and `celox vpi build` now share optimization and hierarchical signal-access settings in celox.toml and CLI options. VPI builds default to O1 with no implicit force permission; users explicitly list observation roots and force targets. Common settings are overridden by the selected target and then the CLI, with complete-list replacement and explicit clearing options. Force targets imply liveness and receive override controls before symbolic evaluation and SIR optimization. This preserves blocking-assignment reads, signed and four-state values, declaration initializers, and sequential release behavior without globally switching to O0. Force uses the ordinary optimized native kernel, including parallel kernels. Permissions and control addresses survive native-image serialization, and undeclared force requests are rejected. Explicit force currently supports whole packed variables in pure SystemVerilog designs. Unpacked arrays, clock/reset event objects, structured port aliases, and Veryl/mixed-language force targets fail explicitly. Interface members must be selected at their owning declaration. Observation roots support both source languages. These manifest settings apply to the CLI; JavaScript project constructors do not consume them. Validation: - 14 signal-access regressions, including O0/O1/O2 loop force, O2 DSE retention, parallel execution, initial values, signed/wide/four-state values, and rejected targets. - 2944 SystemVerilog backend regressions, 234 interface regressions, 24 native-image regressions, and the VPI/CLI suites. - Two real cocotb end-to-end tests, including optimized force/release; the CI step now runs both. - NAPI build and 201 JS integration tests; 44 CI workflow/classifier tests. - Clippy with warnings denied, formatting, no-host SystemVerilog check, and doctests. BREAKING CHANGE: VPI CLI builds now require explicit force_signals/--force-signal declarations and default to O1 instead of implicit unrestricted O0 force support. SimulatorOptions adds signal_access, and native image container version 16 requires rebuilding attached images and using a matching runtime. Depends-On: https://github.com/celox-sim/celox/pull/1576 Change-Id: I3121ddcc187baaec143bdd0fe64d832d87e90a3e --- .github/workflows/ci.yml | 4 +- crates/celox-frontend-sv/src/lib.rs | 2 + crates/celox-frontend-sv/src/lowering.rs | 146 ++++++- crates/celox-frontend-sv/src/lowering/comb.rs | 84 +++- crates/celox-frontend-sv/src/lowering/ff.rs | 111 +++++- .../src/lowering/procedural.rs | 21 + crates/celox-vpi/src/bin/celox.rs | 21 +- crates/celox-vpi/src/bin/celox/project.rs | 47 +++ crates/celox-vpi/src/driver.rs | 39 +- crates/celox-vpi/tests/cocotb_e2e.rs | 41 ++ .../tests/fixtures/cocotb/force_profile.sv | 9 + .../fixtures/cocotb/test_force_profile.py | 18 + crates/celox-vpi/tests/project_cli.rs | 99 +++++ crates/celox-vpi/tests/signal_access.rs | 377 ++++++++++++++++++ crates/celox/src/backend/native/backend.rs | 122 +++++- crates/celox/src/backend/native/image_file.rs | 2 +- .../celox/src/backend/native/runtime_image.rs | 37 +- crates/celox/src/ir.rs | 28 ++ crates/celox/src/lib.rs | 3 + crates/celox/src/parser.rs | 4 +- crates/celox/src/signal_access.rs | 10 + crates/celox/src/simulator/builder.rs | 56 ++- docs/guide/celox-toml.md | 46 +++ docs/ja/guide/celox-toml.md | 28 ++ scripts/ci-workflow.test.mjs | 4 +- 25 files changed, 1322 insertions(+), 37 deletions(-) create mode 100644 crates/celox-vpi/tests/fixtures/cocotb/force_profile.sv create mode 100644 crates/celox-vpi/tests/fixtures/cocotb/test_force_profile.py create mode 100644 crates/celox-vpi/tests/signal_access.rs create mode 100644 crates/celox/src/signal_access.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 7f46105596e..542433183c0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -293,8 +293,8 @@ jobs: case "$feature" in celox/*) args+=(--features "$feature");; esac done CELOX_COCOTB_PYTHON="$(command -v python)" \ - cargo test --locked -p celox-vpi "${args[@]}" --test cocotb_e2e \ - cocotb_drives_an_attached_native_flip_flop -- --exact --ignored + cargo test --locked -p celox-vpi --features systemverilog "${args[@]}" --test cocotb_e2e \ + cocotb_ -- --ignored external-suites: name: External suite (${{ matrix.suite }}, ${{ matrix.tool }}) diff --git a/crates/celox-frontend-sv/src/lib.rs b/crates/celox-frontend-sv/src/lib.rs index ec528a33eac..bc6ad7f6c91 100644 --- a/crates/celox-frontend-sv/src/lib.rs +++ b/crates/celox-frontend-sv/src/lib.rs @@ -53,3 +53,5 @@ pub use lowering::{ interface_signatures_for_with_options, prepare_external_hierarchy_with_foreign_resolver_with_options, schedule_sources_with_options, }; + +pub use lowering::schedule_sources_with_force_signals; diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index d815098a48e..2d33bb4fec5 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -55,6 +55,11 @@ pub enum FrontendError { Lowering(#[from] ParserError), } +// These names cannot be authored as unescaped SV identifiers and are hidden +// from the source-facing hierarchy. The runtime image records their addresses. +const FORCE_ENABLE: &str = "@force-enable:"; +const FORCE_VALUE: &str = "@force-value:"; + #[derive(Clone)] struct SvVariable { path: Vec, @@ -69,6 +74,8 @@ struct SvVariable { source: Option, /// A procedural local or a lowering temporary: not addressable by name. hidden: bool, + /// Compiler-generated external override slot: (target, is_enable). + force_control: Option<(SourceVarId, bool)>, } impl SvVariable { @@ -97,7 +104,7 @@ impl SvVariable { /// A hidden variable other than the time slot, whose value the lowered /// code computes. The time slot is state the scheduler writes. fn is_scratch(&self) -> bool { - self.hidden && self.path != [TIME_SLOT] + self.hidden && self.path != [TIME_SLOT] && self.force_control.is_none() } } @@ -135,6 +142,7 @@ struct AnalyzedSvModule { pub(crate) struct LoweredSvInstance { pub module_name: String, pub instance_name: String, + pub force_signals: Vec, pub parameter_overrides: Vec, pub port_connections: Vec, /// For an element of an instance array: its position in declaration order @@ -163,6 +171,7 @@ pub(crate) struct LoweredSvPortConnection { #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub(crate) struct LoweredSvModuleKey { pub name: String, + pub force_signals: Vec, pub parameter_overrides: Vec, } @@ -170,6 +179,7 @@ impl LoweredSvModuleKey { pub fn base(name: String) -> Self { Self { name, + force_signals: Vec::new(), parameter_overrides: Vec::new(), } } @@ -179,6 +189,7 @@ impl LoweredSvModuleKey { parameter_overrides.sort_by(|left, right| left.name.cmp(&right.name)); Self { name: instance.module_name.clone(), + force_signals: instance.force_signals.clone(), parameter_overrides, } } @@ -267,7 +278,7 @@ fn interface_signatures_collecting( .into_iter() .map(|prototype| { warnings.extend(crate::warning::analyzer_warnings(&prototype.warnings)); - let lowered = lower_module(&prototype.module, false, true, false, warnings)?; + let lowered = lower_module(&prototype.module, false, true, false, warnings, &[])?; Ok(InterfaceSignature { name: prototype.name, module: lowered.source, @@ -774,7 +785,7 @@ fn lower_package_states( .into_iter() .enumerate() .map(|(index, module)| { - let mut lowered = lower_module(module, four_state, true, ff_parts, warnings)?; + let mut lowered = lower_module(module, four_state, true, ff_parts, warnings, &[])?; lowered.sim_module.time_precision = Some( celox_design::TimePrecision::try_from(packages.global_time_precision()) .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))?, @@ -1360,6 +1371,7 @@ fn prepare_external_hierarchy_collecting( type_kind: variable.metadata.type_kind, source: variable.source.clone(), hidden: !variable.module_affiliated, + force_control: None, }, ) }) @@ -1725,6 +1737,46 @@ pub fn schedule_sources_with_options( trace: Option<&mut FrontendTrace>, warnings: &mut Vec, analysis_options: sv::AnalysisOptions, +) -> Result { + schedule_sources_with_force_signals( + sources, + top, + parameter_overrides, + ignored_loops, + true_loops, + four_state, + parallel, + trace_options, + trace, + warnings, + analysis_options, + &[], + ) +} + +/// Schedule with explicitly forceable signal names. Only these objects receive +/// external override inputs; unrelated logic retains its normal optimization. +#[allow(clippy::too_many_arguments)] +pub fn schedule_sources_with_force_signals( + sources: &[(&str, &Path)], + top: &str, + parameter_overrides: &[(String, u64)], + ignored_loops: &[( + (Vec<(String, usize)>, Vec), + (Vec<(String, usize)>, Vec), + )], + true_loops: &[( + (Vec<(String, usize)>, Vec), + (Vec<(String, usize)>, Vec), + usize, + )], + four_state: bool, + parallel: &celox_frontend_core::ParallelScheduleOptions, + trace_options: &FrontendTraceOptions, + trace: Option<&mut FrontendTrace>, + warnings: &mut Vec, + analysis_options: sv::AnalysisOptions, + force_signals: &[String], ) -> Result { let mut found = Vec::new(); let scheduled = schedule_sources_collecting( @@ -1739,6 +1791,7 @@ pub fn schedule_sources_with_options( trace, &mut found, analysis_options, + force_signals, ); append_error_warnings(&scheduled, &mut found); crate::warning::append_unique_warnings(sources, warnings, found); @@ -1765,12 +1818,18 @@ fn schedule_sources_collecting( trace: Option<&mut FrontendTrace>, warnings: &mut Vec, analysis_options: sv::AnalysisOptions, + force_signals: &[String], ) -> Result { let analyzed = analyze_sources(sources, &[top], analysis_options)?; package_warnings(&analyzed, warnings); let top = top.to_string(); let root_key = LoweredSvModuleKey { name: top.clone(), + force_signals: force_signals + .iter() + .filter_map(|path| path.strip_prefix(&format!("{top}."))) + .map(str::to_string) + .collect(), parameter_overrides: parameter_overrides .iter() .map(|(name, value)| LoweredSvParameterOverride { @@ -2014,13 +2073,42 @@ fn specialize_module( .iter() .find(|candidate| candidate.name() == module.name) .ok_or_else(|| sv::AnalyzerError::Unsupported(format!("module `{}`", module.name)))?; + let local_forces = key + .force_signals + .iter() + .map(|path| { + module + .interface_member_paths + .iter() + .find(|(_, segments)| segments.join(".") == *path) + .map_or_else(|| path.clone(), |(flat, _)| flat.clone()) + }) + .collect::>(); let mut lowered = lower_module( specialized, four_state, module.implicit_nets_allowed, ff_parts, warnings, + &local_forces, )?; + for instance in &mut lowered.instances { + let name = if let Some((index, _)) = instance.array_element { + format!( + "{}[{}]", + instance.instance_name, + instance.array_index_base + index + ) + } else { + instance.instance_name.clone() + }; + let prefix = format!("{name}."); + instance.force_signals = key + .force_signals + .iter() + .filter_map(|path| path.strip_prefix(&prefix).map(str::to_string)) + .collect(); + } lowered.sim_module.time_precision = Some( celox_design::TimePrecision::try_from(module.packages.global_time_precision()) .map_err(|reason| sv::AnalyzerError::Unsupported(reason.to_string()))?, @@ -2052,6 +2140,7 @@ fn lower_module( implicit_nets_allowed: bool, ff_parts: bool, warnings: &mut Vec, + force_signals: &[String], ) -> Result { lower_module_with_overrides( module, @@ -2060,6 +2149,7 @@ fn lower_module( implicit_nets_allowed, ff_parts, warnings, + force_signals, ) } @@ -2072,6 +2162,7 @@ fn lower_module_with_overrides( implicit_nets_allowed: bool, ff_parts: bool, warnings: &mut Vec, + force_signals: &[String], ) -> Result { let mut package_variables = Vec::new(); let name = module.name().to_string(); @@ -2120,6 +2211,7 @@ fn lower_module_with_overrides( type_kind: type_info.type_kind, source: None, hidden: false, + force_control: None, }; name_to_id.insert(port.name().to_string(), id); port_order.push(id); @@ -2168,6 +2260,7 @@ fn lower_module_with_overrides( type_kind: type_info.type_kind, source: None, hidden: false, + force_control: None, }; name_to_id.insert(signal.name().to_string(), id); // The package's object has its own default value. @@ -2190,6 +2283,50 @@ fn lower_module_with_overrides( variables.insert(id, variable); } + let forceable = variables + .iter() + .filter_map(|(&id, var)| { + let name = &var.path[0]; + force_signals.iter().any(|path| name == path).then_some(id) + }) + .collect::>(); + for id in forceable { + let target = variables[&id].clone(); + // Whole packed variables only. Array elements require a separately + // specified addressing contract rather than a guessed flat offset. + if !target.array_dims.is_empty() { + continue; + } + for (prefix, width, is_4state) in [ + (FORCE_ENABLE, 1, false), + (FORCE_VALUE, target.width, target.is_4state), + ] { + let control_name = format!("{prefix}{}", target.path[0]); + if name_to_id.contains_key(&control_name) { + return Err(sv::AnalyzerError::Unsupported(format!( + "signal `{control_name}` conflicts with a compiler force control" + ))); + } + let mut control = target.clone(); + control.force_control = Some((id, prefix == FORCE_ENABLE)); + control.path = vec![control_name.clone()]; + control.width = width; + control.signed = false; + control.is_4state = is_4state; + control.kind = VariableKind::Variable; + control.hidden = true; + control.packed_ranges = vec![(width as i128 - 1, 0)]; + control.type_kind = if is_4state { + PortTypeKind::Logic + } else { + PortTypeKind::Bit + }; + let control_id = next_var_id(&mut next_id); + variables.insert(control_id, control); + name_to_id.insert(control_name, control_id); + } + } + if !cfg!(feature = "dpi") && !module.dpi_imports().is_empty() { return Err(sv::AnalyzerError::Unsupported( "DPI-C import (enable the `sv-dpi` feature of `celox`)".to_string(), @@ -2295,6 +2432,7 @@ fn lower_module_with_overrides( instances.push(LoweredSvInstance { module_name: instance.module_name().to_string(), instance_name: instance.name().to_string(), + force_signals: Vec::new(), parameter_overrides: lower_parameter_overrides( instance, &constants, @@ -3166,6 +3304,7 @@ fn lower_initial_processes( source: None, // Control slots are not signals of the design. hidden: true, + force_control: None, }, ); id @@ -3497,6 +3636,7 @@ fn ensure_parent_output_signals( type_kind: PortTypeKind::Logic, source: None, hidden: false, + force_control: None, }; parent .variables diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index e1fc10b2161..633ef544b4a 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -136,6 +136,43 @@ impl<'p, 'a> Comb<'p, 'a> { store: &Store, id: SourceVarId, access: BitAccess, + ) -> Result { + let mut value = self.read_unforced(store, id, access)?; + // Initial-state folding runs before a foreign caller can apply force. + // Runtime initial processes are lowered separately through Ff. + if !self.initial + && let Some((enabled, forced)) = self.m.force_controls(id) + { + let cond = self.alloc(SLTNode::Input { + variable: enabled, + signed: false, + index: vec![], + access: full(1), + })?; + let replacement = self.alloc(SLTNode::Input { + variable: forced, + signed: false, + index: vec![], + access, + })?; + value.0 = self.alloc(SLTNode::Mux { + cond, + then_expr: replacement, + else_expr: value.0, + })?; + value.1.insert(VarAtomBase::new(enabled, 0, 0)); + value + .1 + .insert(VarAtomBase::new(forced, access.lsb, access.msb)); + } + Ok(value) + } + + fn read_unforced( + &mut self, + store: &Store, + id: SourceVarId, + access: BitAccess, ) -> Result { let signed = self.m.var(id).signed && access.lsb == 0 && access.msb + 1 == self.m.var(id).width; @@ -189,6 +226,34 @@ impl<'p, 'a> Comb<'p, 'a> { value: Value, ) -> Result<(), sv::AnalyzerError> { let width = self.m.var(id).width; + let mut value = value; + // Initial-state folding runs before a foreign caller can apply force. + // Runtime initial processes are lowered separately through Ff. + if !self.initial + && let Some((enabled, forced)) = self.m.force_controls(id) + { + let condition = self.alloc(SLTNode::Input { + variable: enabled, + signed: false, + index: vec![], + access: full(1), + })?; + let replacement = self.alloc(SLTNode::Input { + variable: forced, + signed: false, + index: vec![], + access, + })?; + value.0 = self.alloc(SLTNode::Mux { + cond: condition, + then_expr: replacement, + else_expr: value.0, + })?; + value.1.insert(VarAtomBase::new(enabled, 0, 0)); + value + .1 + .insert(VarAtomBase::new(forced, access.lsb, access.msb)); + } debug_assert_eq!(self.width(value.0), access.msb - access.lsb + 1); store .entry(id) @@ -563,11 +628,13 @@ impl<'p, 'a> Comb<'p, 'a> { access, } => { if index.is_empty() { - if store.get(&variable).is_some_and(|range| { - range - .get_parts_ref(access) - .is_ok_and(|parts| parts.iter().any(|(value, _)| value.is_some())) - }) { + if self.m.force_controls(variable).is_some() + || store.get(&variable).is_some_and(|range| { + range + .get_parts_ref(access) + .is_ok_and(|parts| parts.iter().any(|(value, _)| value.is_some())) + }) + { let (value, sources) = self.read(store, variable, access)?; let _ = signed; (value, sources) @@ -592,9 +659,10 @@ impl<'p, 'a> Comb<'p, 'a> { }); } let var_width = self.m.var(variable).width; - let written = store.get(&variable).is_some_and(|range| { - range.ranges.values().any(|(value, _, _)| value.is_some()) - }); + let written = self.m.force_controls(variable).is_some() + || store.get(&variable).is_some_and(|range| { + range.ranges.values().any(|(value, _, _)| value.is_some()) + }); if written { // Read the selected bits out of the current value. let (whole, whole_sources) = self.read(store, variable, full(var_width))?; diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index bebcdf9317a..10ebf538941 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -344,7 +344,7 @@ impl<'p, 'a> Ff<'p, 'a> { } else { expr }; - let expr = self.propagate(&expr); + let expr = force_reads(&self.propagate(&expr), self.m); if let (sv::ir::Expr::Literal(literal), Some((width, _))) = (&expr, context) && let Some(fill) = unbased_fill_literal(literal) { @@ -1391,6 +1391,28 @@ impl<'p, 'a> Ff<'p, 'a> { } fn store(&mut self, id: SourceVarId, offset: SIROffset, width: usize, value: RegisterId) { + let value = if let Some((enabled, forced)) = self.m.force_controls(id) { + let condition = self.b.alloc_bit(1, false); + self.b.emit(SIRInstruction::Load( + condition, + stable(enabled), + SIROffset::Static(0), + 1, + )); + let replacement = self.b.alloc_reg(self.b.register(&value).clone()); + self.b.emit(SIRInstruction::Load( + replacement, + stable(forced), + offset.clone(), + width, + )); + let selected = self.b.alloc_reg(self.b.register(&value).clone()); + self.b + .emit(SIRInstruction::Mux(selected, condition, replacement, value)); + selected + } else { + value + }; let target = self.target(id); self.b.emit(SIRInstruction::Store( target, @@ -3908,3 +3930,90 @@ fn substitute_overlay( }, } } + +fn force_reads(expr: &sv::ir::Expr, m: &ProcModule<'_>) -> sv::ir::Expr { + if m.forceable.is_empty() { + return expr.clone(); + } + use sv::ir::Expr; + let go = |expr: &Expr| force_reads(expr, m); + match expr { + Expr::Ident(name) => { + if let Some(id) = m.id(name) + && let Some((enabled, forced)) = m.force_controls(id) + { + Expr::Resize { + width: m.var(id).width, + signed: m.var(id).signed, + expr: Box::new(Expr::Mux { + condition: Box::new(Expr::Ident(m.var(enabled).path[0].clone())), + then_expr: Box::new(Expr::Ident(m.var(forced).path[0].clone())), + else_expr: Box::new(expr.clone()), + }), + } + } else { + expr.clone() + } + } + Expr::Literal(_) => expr.clone(), + Expr::Select { + expr, + msb, + lsb, + signed, + } => Expr::Select { + expr: Box::new(go(expr)), + msb: msb.clone(), + lsb: lsb.clone(), + signed: *signed, + }, + Expr::Concat(parts) => Expr::Concat(parts.iter().map(go).collect()), + Expr::RepeatConcat { count, parts } => Expr::RepeatConcat { + count: count.clone(), + parts: parts.iter().map(go).collect(), + }, + Expr::Resize { + expr, + width, + signed, + } => Expr::Resize { + expr: Box::new(go(expr)), + width: *width, + signed: *signed, + }, + Expr::Unary { op, expr } => Expr::Unary { + op: *op, + expr: Box::new(go(expr)), + }, + Expr::Binary { left, op, right } => Expr::Binary { + left: Box::new(go(left)), + op: *op, + right: Box::new(go(right)), + }, + Expr::Mux { + condition, + then_expr, + else_expr, + } => Expr::Mux { + condition: Box::new(go(condition)), + then_expr: Box::new(go(then_expr)), + else_expr: Box::new(go(else_expr)), + }, + Expr::Call { + callee, + args, + arg_order, + } => Expr::Call { + arg_order: arg_order.clone(), + callee: callee.clone(), + args: args.iter().map(|arg| arg.as_ref().map(go)).collect(), + }, + Expr::Inside { expr, items } => Expr::Inside { + expr: Box::new(go(expr)), + items: items + .iter() + .map(|item| item.map(&mut |operand| go(operand))) + .collect(), + }, + } +} diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index b931cb20de6..56ef6cc6520 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -33,6 +33,7 @@ pub(super) struct ProcModule<'a> { /// Number of extern calls lowered so far. pub extern_calls: usize, pub four_state: bool, + pub forceable: HashMap, /// Hidden variables created while lowering, for the caller to publish. pub created: Vec, temp_counter: usize, @@ -127,7 +128,20 @@ impl<'a> ProcModule<'a> { unpacked_bounds.insert(id, bounds); } } + let forceable = variables + .iter() + .filter_map(|(&enabled, var)| { + let (target, true) = var.force_control? else { + return None; + }; + let value = variables.iter().find_map(|(&id, var)| { + (var.force_control == Some((target, false))).then_some(id) + })?; + Some((target, (enabled, value))) + }) + .collect(); Self { + forceable, variables, name_to_id, next_id, @@ -498,6 +512,10 @@ impl<'a> ProcModule<'a> { self.name_to_id.get(name).copied() } + pub fn force_controls(&self, id: SourceVarId) -> Option<(SourceVarId, SourceVarId)> { + self.forceable.get(&id).copied() + } + pub fn var(&self, id: SourceVarId) -> &SvVariable { &self.variables[&id] } @@ -552,6 +570,7 @@ impl<'a> ProcModule<'a> { }, source: None, hidden: true, + force_control: None, }, ); self.name_to_id.insert(name, id); @@ -613,6 +632,7 @@ impl<'a> ProcModule<'a> { type_kind: source.type_kind, source: None, hidden: true, + force_control: None, }; let id = next_var_id(&mut self.next_id); self.variables.insert(id, variable); @@ -1007,6 +1027,7 @@ pub(super) fn register_locals( type_kind: type_info.type_kind, source: None, hidden: true, + force_control: None, }, ); name_to_id.insert(local.name.clone(), id); diff --git a/crates/celox-vpi/src/bin/celox.rs b/crates/celox-vpi/src/bin/celox.rs index 79e26769689..82497626db9 100644 --- a/crates/celox-vpi/src/bin/celox.rs +++ b/crates/celox-vpi/src/bin/celox.rs @@ -44,10 +44,6 @@ struct RunArgs { #[command(flatten)] design: DesignArgs, - /// Compiler optimization level: O0, O1, O2 (default: project setting or O2). - #[arg(short = 'O', long, value_parser = parse_opt_level)] - opt_level: Option, - /// Maximum SV scheduler steps or Veryl ticks (default: project setting or 1000000). /// Does not bound compilation or work within a single step/tick. #[arg(long, value_parser = clap::value_parser!(u64).range(1..))] @@ -98,10 +94,7 @@ fn parse_opt_level(value: &str) -> Result { fn resolve_run_config(arguments: RunArgs) -> RunConfig { let design = resolve_design(arguments.design); RunConfig { - opt_level: arguments - .opt_level - .or(design.opt_level) - .unwrap_or(celox::OptLevel::O2), + opt_level: design.opt_level.unwrap_or(celox::OptLevel::O2), max_steps: arguments .max_steps .or(design.max_steps) @@ -169,7 +162,8 @@ fn run_testbench(arguments: RunArgs) -> Result<(), String> { ) .four_state(true) .opt_level(arguments.opt_level) - .diagnostic_policy(arguments.design.diagnostics.clone()); + .diagnostic_policy(arguments.design.diagnostics.clone()) + .signal_access(arguments.design.signal_access.clone()); if let Some(metadata) = metadata { builder = builder.with_metadata(metadata); } @@ -208,6 +202,7 @@ fn run_sv(arguments: RunConfig) -> Result<(), String> { .four_state(true) .opt_level(arguments.opt_level) .diagnostic_policy(arguments.design.diagnostics.clone()) + .signal_access(arguments.design.signal_access.clone()) .build() .map_err(|error| format!("compilation failed:\n{error}"))?; report_warnings(simulation.warnings())?; @@ -438,8 +433,8 @@ fn compile_native_design(design: &Design) -> Result let simulator = celox::Simulator::from_sv_sources(refs, &design.top) .four_state(true) .diagnostic_policy(design.diagnostics.clone()) - .native_force_support(true) - .opt_level(celox::OptLevel::O0) + .signal_access(design.signal_access.clone()) + .opt_level(design.opt_level.unwrap_or(celox::OptLevel::O1)) .build() .map_err(|error| format!("compilation failed:\n{error}"))?; report_warnings(simulator.warnings())?; @@ -458,10 +453,12 @@ fn compile_native_design(design: &Design) -> Result { return Err("pass .sv/.v sources, or one .veryl project entry file".to_string()); } - let (image, warnings) = celox_vpi::driver::compile_native_image_with_diagnostics( + let (image, warnings) = celox_vpi::driver::compile_native_image_with_options( &design.sources[0], &design.top, design.diagnostics.clone(), + design.opt_level.unwrap_or(celox::OptLevel::O1), + design.signal_access.clone(), )?; report_warnings(&warnings)?; Ok(image) diff --git a/crates/celox-vpi/src/bin/celox/project.rs b/crates/celox-vpi/src/bin/celox/project.rs index c017ca30528..7dee4979c58 100644 --- a/crates/celox-vpi/src/bin/celox/project.rs +++ b/crates/celox-vpi/src/bin/celox/project.rs @@ -15,6 +15,29 @@ pub(super) struct DesignArgs { /// Override a compilation diagnostic: CODE=allow|warn|error (repeatable). #[arg(long = "diagnostic", value_name = "CODE=LEVEL")] diagnostics: Vec, + /// Optimization level: O0, O1, O2 (default: project setting or O2 for run, O1 for vpi build). + #[arg(short = 'O', long, value_parser = super::parse_opt_level)] + opt_level: Option, + /// Preserve a hierarchical signal for observation (repeatable; replaces project list). + #[arg( + long = "live-signal", + value_name = "PATH", + conflicts_with = "no_live_signals" + )] + live_signals: Vec, + /// Permit force/release on a packed SV signal (repeatable; replaces project list). + #[arg( + long = "force-signal", + value_name = "PATH", + conflicts_with = "no_force_signals" + )] + force_signals: Vec, + /// Clear the project's live_signals list. + #[arg(long)] + no_live_signals: bool, + /// Clear the project's force_signals list. + #[arg(long)] + no_force_signals: bool, /// Project manifest (otherwise discover celox.toml when no inputs are given). #[arg(long, value_name = "FILE")] project: Option, @@ -52,6 +75,8 @@ struct Manifest { defines: BTreeMap, top: Option, opt_level: Option, + live_signals: Option>, + force_signals: Option>, max_steps: Option, default_target: Option, targets: BTreeMap, @@ -67,6 +92,8 @@ struct Target { defines: BTreeMap, top: Option, opt_level: Option, + live_signals: Option>, + force_signals: Option>, max_steps: Option, } @@ -78,6 +105,7 @@ pub(super) struct Design { pub defines: BTreeMap, pub top: String, pub opt_level: Option, + pub signal_access: celox::SignalAccessOptions, pub max_steps: Option, } @@ -169,6 +197,8 @@ impl DesignArgs { design.diagnostics = config.diagnostics.clone(); design.top = config.top.clone().unwrap_or_default(); let mut opt_level = config.opt_level.as_deref(); + design.signal_access.live_signals = config.live_signals.clone().unwrap_or_default(); + design.signal_access.force_signals = config.force_signals.clone().unwrap_or_default(); design.max_steps = config.max_steps; if let Some(target) = selected { design.diagnostics.0.extend(target.diagnostics.0.clone()); @@ -183,6 +213,12 @@ impl DesignArgs { design.top.clone_from(top); } opt_level = target.opt_level.as_deref().or(opt_level); + if let Some(paths) = &target.live_signals { + design.signal_access.live_signals.clone_from(paths); + } + if let Some(paths) = &target.force_signals { + design.signal_access.force_signals.clone_from(paths); + } design.max_steps = target.max_steps.or(design.max_steps); } design.opt_level = opt_level @@ -196,6 +232,17 @@ impl DesignArgs { return Err("max_steps must be positive".to_string()); } } + design.opt_level = self.opt_level.or(design.opt_level); + if self.no_live_signals { + design.signal_access.live_signals.clear(); + } else if !self.live_signals.is_empty() { + design.signal_access.live_signals = self.live_signals; + } + if self.no_force_signals { + design.signal_access.force_signals.clear(); + } else if !self.force_signals.is_empty() { + design.signal_access.force_signals = self.force_signals; + } let inputs = if self.input_order.is_empty() { (0..self.sources.len()) .map(Input::Source) diff --git a/crates/celox-vpi/src/driver.rs b/crates/celox-vpi/src/driver.rs index 2f00c6cfac7..442a5c2b154 100644 --- a/crates/celox-vpi/src/driver.rs +++ b/crates/celox-vpi/src/driver.rs @@ -53,6 +53,35 @@ pub fn compile_native_image_with_diagnostics( source: &Path, top: &str, policy: DiagnosticPolicy, +) -> Result<(NativeProgramImage, Vec), String> { + compile_native_image_configured( + source, + top, + policy, + celox::OptLevel::O0, + celox::SignalAccessOptions::default(), + true, + ) +} + +/// Compile with an explicit observation/force contract, retaining optimization. +pub fn compile_native_image_with_options( + source: &Path, + top: &str, + policy: DiagnosticPolicy, + level: celox::OptLevel, + access: celox::SignalAccessOptions, +) -> Result<(NativeProgramImage, Vec), String> { + compile_native_image_configured(source, top, policy, level, access, false) +} + +fn compile_native_image_configured( + source: &Path, + top: &str, + policy: DiagnosticPolicy, + level: celox::OptLevel, + access: celox::SignalAccessOptions, + legacy_force: bool, ) -> Result<(NativeProgramImage, Vec), String> { let simulator = if let Ok(metadata_path) = Metadata::search_from(source) { let mut metadata = Metadata::load(&metadata_path) @@ -76,8 +105,9 @@ pub fn compile_native_image_with_diagnostics( .with_metadata(metadata) .diagnostic_policy(policy.clone()) .four_state(true) - .native_force_support(true) - .opt_level(celox::OptLevel::O0) + .native_force_support(legacy_force) + .signal_access(access.clone()) + .opt_level(level) .build() } else { let contents = std::fs::read_to_string(source) @@ -85,8 +115,9 @@ pub fn compile_native_image_with_diagnostics( Simulator::from_sources(vec![(contents.as_str(), source)], top) .diagnostic_policy(policy.clone()) .four_state(true) - .native_force_support(true) - .opt_level(celox::OptLevel::O0) + .native_force_support(legacy_force) + .signal_access(access.clone()) + .opt_level(level) .build() } .map_err(|error| format!("compilation failed: {error}"))?; diff --git a/crates/celox-vpi/tests/cocotb_e2e.rs b/crates/celox-vpi/tests/cocotb_e2e.rs index 0163ad031b8..3b4b66860d9 100644 --- a/crates/celox-vpi/tests/cocotb_e2e.rs +++ b/crates/celox-vpi/tests/cocotb_e2e.rs @@ -489,3 +489,44 @@ fn compile_reports_a_missing_additional_source() { "{error}" ); } + +#[cfg(feature = "systemverilog")] +#[test] +#[ignore = "requires a cocotb installation"] +fn cocotb_uses_declared_force_targets_in_an_optimized_native_image() { + let python = env::var("CELOX_COCOTB_PYTHON").expect("set CELOX_COCOTB_PYTHON"); + let fixture = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/cocotb"); + let temporary = tempfile::tempdir().unwrap(); + let executable = temporary.path().join("force-sim"); + let results = temporary.path().join("results.xml"); + let compile = Command::new(env!("CARGO_BIN_EXE_celox")) + .args(["vpi", "build"]) + .arg(fixture.join("force_profile.sv")) + .args(["--top", "Top", "-O", "O2", "--force-signal", "Top.x", "-o"]) + .arg(&executable) + .output() + .unwrap(); + assert!(compile.status.success(), "{compile:?}"); + let site = python_output( + &python, + &["-c", "import site; print(':'.join(site.getsitepackages()))"], + ); + let runtime = Command::new(&executable) + .args([ + "--test-module", + "test_force_profile", + "--python", + &python, + "--results-file", + ]) + .arg(&results) + .current_dir(&fixture) + .env("PYTHONPATH", format!("{}:{site}", fixture.display())) + .output() + .unwrap(); + assert!(runtime.status.success(), "cocotb force failed: {runtime:?}"); + let xml = fs::read_to_string(results).unwrap(); + assert_eq!(xml.matches("