From 229f7a0e4956b67e7b9a1d2fa9c2bc64e39f3767 Mon Sep 17 00:00:00 2001 From: tignear Date: Thu, 29 Oct 2026 01:42:43 +0900 Subject: [PATCH] feat(sv): provide UVM's DPI-C functions sv-tests runs UVM without `UVM_NO_DPI` and without UVM's C library, so `uvm_pkg` imports 23 DPI-C functions that no library defines. Celox now provides them: an import with one of their C names and UVM's prototype binds to a builtin instead of a C function, needs no `sv-dpi` feature, and is lowered to heap operations on every backend. Other imports are unchanged. `uvm_re_comp`, `uvm_re_exec`, `uvm_re_free`, `uvm_re_compexec`, `uvm_re_compexecfree`, `uvm_re_buffer` and `uvm_re_deglobbed` follow UVM's `uvm_regex.cc`, including its glob translation and error buffer; expressions are compiled with the `regex` crate and their handles are chandles that survive checkpoints as patterns. `uvm_dpi_get_next_arg_c` returns `celox` followed by the simulation's plusargs, and the tool name and version are Celox's. The `uvm_hdl_*` and `uvm_polling_*` imports bind too, but return 0 or null and leave their outputs unchanged until they are implemented, so UVM reports them as unavailable. Change-Id: I2b0f2552448c89bc9e36059a003751df77a6a5f7 --- Cargo.lock | 1 + Cargo.toml | 1 + crates/celox-frontend-sv/src/lowering.rs | 54 ++- crates/celox-frontend-sv/src/lowering/ff.rs | 16 + .../src/lowering/ff/dpi_builtins.rs | 215 +++++++++++ .../src/lowering/procedural.rs | 25 +- crates/celox-heap/Cargo.toml | 1 + crates/celox-heap/src/lib.rs | 6 + crates/celox-heap/src/ops.rs | 32 ++ crates/celox-heap/src/uvm_dpi.rs | 339 +++++++++++++++++ crates/celox-sv-analyzer/src/ast.rs | 23 +- crates/celox-sv-analyzer/src/ast/dpi.rs | 258 ++++++++++++- crates/celox-sv-analyzer/src/ir.rs | 59 ++- crates/celox/Cargo.toml | 4 + crates/celox/src/simulator.rs | 20 + crates/celox/src/simulator/builder.rs | 16 +- crates/celox/tests/sv_uvm_dpi.rs | 345 ++++++++++++++++++ docs/guide/systemverilog-reference.md | 14 + docs/ja/guide/systemverilog-reference.md | 8 + 19 files changed, 1410 insertions(+), 27 deletions(-) create mode 100644 crates/celox-frontend-sv/src/lowering/ff/dpi_builtins.rs create mode 100644 crates/celox-heap/src/uvm_dpi.rs create mode 100644 crates/celox/tests/sv_uvm_dpi.rs diff --git a/Cargo.lock b/Cargo.lock index b19c8b33b93..7a0ca91cc22 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -660,6 +660,7 @@ version = "0.12.0" dependencies = [ "aplite", "fxhash", + "regex", "serde", "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 21f7f578215..9b136698f85 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -118,6 +118,7 @@ num-bigint = { version = "0.5", features = ["serde"] } num-traits = "0.2.19" rand = { version = "0.10", default-features = false } rand_pcg = "0.10" +regex = "1.13" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" tempfile = "3.26" diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 5a2798a5691..febb99aae9c 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -1372,6 +1372,7 @@ fn kernel_window_writes( foreign_writes: &HashMap, ) -> HashSet { let subroutines = module.subroutines(); + let scan = DriverScan::of(module); let mut names = HashSet::default(); for process in module .initial_processes() @@ -1387,7 +1388,7 @@ fn kernel_window_writes( .unwrap_or(body.len()) }; kernel_written_names( - subroutines, + &scan, &body[first..], &mut names, &mut HashSet::default(), @@ -1435,7 +1436,7 @@ fn stmt_may_suspend(subroutines: &[sv::ir::Subroutine], stmt: &sv::ir::Stmt) -> /// Adds the names of the variables `body` writes, directly or in the /// subroutines it calls, to `names` (see [`DriverScan`]). fn kernel_written_names( - subroutines: &[sv::ir::Subroutine], + scan: &DriverScan<'_>, body: &[sv::ir::Stmt], names: &mut HashSet, visited: &mut HashSet, @@ -1488,7 +1489,16 @@ fn kernel_written_names( | sv::ir::Callee::Stream(_) => continue, sv::ir::Callee::Subroutine(name) => name, }; - let Some(subroutine) = subroutines + if let Some(import) = scan.dpi_import(&name) { + names.extend( + procedural::written_dpi_arguments(import, &args) + .iter() + .map(|lvalue| lvalue.name().to_string()), + ); + continue; + } + let Some(subroutine) = scan + .subroutines .iter() .find(|subroutine| subroutine.name == name) else { @@ -1503,7 +1513,7 @@ fn kernel_written_names( } } if visited.insert(name) { - kernel_written_names(subroutines, &subroutine.body, names, visited, depth + 1); + kernel_written_names(scan, &subroutine.body, names, visited, depth + 1); } } } @@ -1644,9 +1654,21 @@ fn validate_variable_driver_ranges( /// the calling process (IEEE 1800-2023 9.2.2.2). struct DriverScan<'a> { subroutines: &'a [sv::ir::Subroutine], + dpi_imports: &'a [sv::ir::DpiImport], } -impl DriverScan<'_> { +impl<'a> DriverScan<'a> { + fn of(module: &'a sv::ir::Module) -> Self { + Self { + subroutines: module.subroutines(), + dpi_imports: module.dpi_imports(), + } + } + + fn dpi_import(&self, name: &str) -> Option<&sv::ir::DpiImport> { + self.dpi_imports.iter().find(|import| import.name() == name) + } + /// Calls `record` with each assignment target of `body`. fn body(&self, record: &mut dyn FnMut(&sv::ir::LValue), body: &[sv::ir::Stmt]) { self.body_at(record, body, &mut HashSet::default(), 0); @@ -1694,6 +1716,12 @@ impl DriverScan<'_> { | sv::ir::Callee::Stream(_) => continue, sv::ir::Callee::Subroutine(name) => name, }; + if let Some(import) = self.dpi_import(&name) { + for lvalue in procedural::written_dpi_arguments(import, &args) { + record(&lvalue); + } + continue; + } let Some(subroutine) = self .subroutines .iter() @@ -1822,9 +1850,7 @@ impl ModuleDrivers { // run-time element. let mut shapes: HashMap> = HashMap::default(); let mut writes: HashMap> = HashMap::default(); - let scan = DriverScan { - subroutines: module.subroutines(), - }; + let scan = DriverScan::of(module); let mut walk = |body: &[sv::ir::Stmt], local: Option, continuous: Option, @@ -3282,9 +3308,7 @@ fn demote_level_lists( else { continue; }; - let scan = DriverScan { - subroutines: lowered.source.subroutines(), - }; + let scan = DriverScan::of(&lowered.source); for process in lowered.source.comb_processes() { let creation_order = process.creation_order(); if process.kind() != sv::ir::CombProcessKind::AlwaysStar @@ -4065,7 +4089,13 @@ fn lower_module_with_overrides( } } - if !cfg!(feature = "dpi") && !module.dpi_imports().is_empty() { + // The functions Celox provides need no C library. + if !cfg!(feature = "dpi") + && module + .dpi_imports() + .iter() + .any(|import| import.builtin().is_none()) + { return Err(sv::AnalyzerError::Unsupported( "DPI-C import (enable the `sv-dpi` feature of `celox`)".to_string(), )); diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 1897c654e30..6af2bd810e3 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -10,6 +10,7 @@ //! four-state semantics identical to the combinational lowering. mod containers; +mod dpi_builtins; mod file_io; mod format; mod fread; @@ -941,6 +942,12 @@ impl<'p, 'a> Ff<'p, 'a> { | sv::ir::Callee::Stream(_) => continue, sv::ir::Callee::Subroutine(name) => name, }; + if let Some(import) = self.m.dpi_imports.get(&name) { + for lvalue in written_dpi_arguments(import, &args) { + self.record_target(&lvalue, true); + } + continue; + } let Some(subroutine) = self.m.subroutine(&name).cloned() else { continue; }; @@ -1825,6 +1832,10 @@ impl<'p, 'a> Ff<'p, 'a> { r#type.is_signed(), r#type.is_4state(), ); + if r#type == sv::ir::DpiType::String { + self.m.variables.get_mut(&temp).unwrap().value_kind = + celox_design::ValueKind::StrRef; + } self.store(temp, SIROffset::Static(0), r#type.width(), result); Expr::Ident(temp_name) } @@ -2005,6 +2016,11 @@ impl<'p, 'a> Ff<'p, 'a> { import.arguments().len() ))); } + if let Some(builtin) = import.builtin() { + // Keeps a process whose only effect is the call (see `extern_calls`). + self.m.extern_calls += 1; + return self.builtin_dpi_call(import, builtin, args, arg_order); + } let mut registers = vec![None; args.len()]; let positions: Vec<_> = if arg_order.is_empty() { (0..args.len()).collect() diff --git a/crates/celox-frontend-sv/src/lowering/ff/dpi_builtins.rs b/crates/celox-frontend-sv/src/lowering/ff/dpi_builtins.rs new file mode 100644 index 00000000000..16a7dce27af --- /dev/null +++ b/crates/celox-frontend-sv/src/lowering/ff/dpi_builtins.rs @@ -0,0 +1,215 @@ +//! Calls of the UVM DPI-C functions Celox provides (see +//! [`sv::ir::DpiBuiltin`]), lowered to heap operations instead of C calls. + +use super::*; +use celox_heap::ops; +use sv::ir::{DpiBuiltin, DpiType, StringOp}; + +impl Ff<'_, '_> { + /// Call builtin `builtin` of `import`, returning the register holding its + /// result. + pub(super) fn builtin_dpi_call( + &mut self, + import: &sv::ir::DpiImport, + builtin: DpiBuiltin, + args: &[Option], + arg_order: &[usize], + ) -> Result, sv::AnalyzerError> { + let name = import.name(); + let positions: Vec<_> = if arg_order.is_empty() { + (0..args.len()).collect() + } else { + arg_order.to_vec() + }; + // Inputs in source order, each kept in a temporary before any heap + // call (see `heap_operand`). + let mut inputs = vec![None; args.len()]; + for position in positions { + let argument = &import.arguments()[position]; + if argument.is_output() { + continue; + } + let arg = args[position].as_ref().ok_or_else(|| { + unsupported(format!("omitted argument of DPI-C function `{name}`")) + })?; + let arg = if argument.r#type() == DpiType::String { + self.string_argument(arg)? + } else { + let r#type = argument.r#type(); + self.heap_operand(arg, Some((r#type.width(), r#type.is_signed())), None)? + }; + inputs[position] = Some(arg); + } + let operand = |this: &mut Self, position: usize| -> Result { + let arg = inputs[position].as_ref().expect("an input argument"); + let r#type = import.arguments()[position].r#type(); + if r#type == DpiType::String { + this.handle(arg) + } else { + this.integer_of_width(arg, r#type.width(), r#type.is_signed()) + } + }; + let call = + |this: &mut Self, code: u64, operands: &[RegisterId]| this.heap_call(code, operands); + let result = match builtin { + DpiBuiltin::ReComp | DpiBuiltin::ReExec | DpiBuiltin::ReDeglobbed => { + let a = operand(self, 0)?; + let b = operand(self, 1)?; + let code = match builtin { + DpiBuiltin::ReComp => ops::UVM_RE_COMP, + DpiBuiltin::ReExec => ops::UVM_RE_EXEC, + _ => ops::UVM_RE_DEGLOBBED, + }; + Some(call(self, code, &[a, b])) + } + DpiBuiltin::ReFree => { + let a = operand(self, 0)?; + call(self, ops::UVM_RE_FREE, &[a]); + None + } + DpiBuiltin::ReCompExec | DpiBuiltin::ReCompExecFree => { + // Selectors of the output are evaluated before the call, so + // a host request they make cannot separate the result from + // its use. + let target = self.builtin_output_target(name, &args[3])?; + let re = operand(self, 0)?; + let string = operand(self, 1)?; + let deglob = operand(self, 2)?; + let code = if builtin == DpiBuiltin::ReCompExec { + ops::UVM_RE_COMPEXEC + } else { + ops::UVM_RE_COMPEXECFREE + }; + let result = call(self, code, &[re, string, deglob]); + // Publishing the output may suspend the process, which keeps + // no register: the result waits in a variable. + let (spilled, _) = self.m.temp("dpi_result", 64, false, false); + self.store(spilled, SIROffset::Static(0), 64, result); + let exec_ret = call(self, ops::UVM_RE_LAST_EXEC, &[]); + self.builtin_output(&target, exec_ret, 32, true)?; + let result = self.b.alloc_bit(64, false); + // From the region the store wrote. + self.b.emit(SIRInstruction::Load( + result, + self.target(spilled), + SIROffset::Static(0), + 64, + )); + Some(result) + } + DpiBuiltin::ReBuffer => Some(call(self, ops::UVM_RE_BUFFER, &[])), + DpiBuiltin::NextArg => { + let init = operand(self, 0)?; + Some(call(self, ops::UVM_NEXT_ARG, &[init])) + } + DpiBuiltin::ToolName => Some(call(self, ops::UVM_TOOL_NAME, &[])), + DpiBuiltin::ToolVersion => Some(call(self, ops::UVM_TOOL_VERSION, &[])), + // `null`, 0 or "" (an empty string has handle 0): the facility + // is unavailable; outputs keep their values, though their + // selectors are evaluated as for any call. + DpiBuiltin::Unavailable => { + for (argument, actual) in import.arguments().iter().zip(args) { + if argument.is_output() && actual.is_some() { + self.builtin_output_target(name, actual)?; + } + } + import.return_type().map(|_| self.constant64(0)) + } + }; + Ok(match (result, import.return_type()) { + (Some(result), Some(r#type)) => { + let width = r#type.width(); + let value = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Slice(value, result, 0, width)); + Some(value) + } + _ => None, + }) + } + + /// A string argument as a string: a string expression, or the bytes of + /// an integral one such as a literal (IEEE 1800-2023 6.16). + fn string_argument(&mut self, arg: &sv::ir::Expr) -> Result { + let arg = self.hoist(arg)?; + if self.m.expr_is_string(&arg) { + return self.heap_operand( + &arg, + Some((32, false)), + Some(celox_design::ValueKind::StrRef), + ); + } + self.string_call(StringOp::FromBits, &[Some(arg)]) + } + + /// The target of the output actual `actual` of builtin `name`. The + /// tagged union members it accesses are checked here, as for any output + /// actual; a builtin writes no variable that could change their tags. + fn builtin_output_target( + &mut self, + name: &str, + actual: &Option, + ) -> Result { + let actual = actual + .as_ref() + .ok_or_else(|| unsupported(format!("omitted output of DPI-C function `{name}`")))?; + // A reference formal bound to a class property, forwarded: its + // object was evaluated when the reference was made. + if forwarded_property(actual, sv::ir::Expr::Literal("0".into())).is_some() { + return Ok(BuiltinOutput::Property(actual.clone())); + } + let lvalues = lvalue_from_expr(actual) + .ok_or_else(|| unsupported(format!("output argument of DPI-C function `{name}`")))?; + self.check_tagged_guards(&tagged_actual_guards(actual))?; + let hoisted = lvalues + .iter() + .map(|lvalue| { + let lvalue = self.propagate_lvalue(lvalue); + self.hoist_lvalue(&lvalue) + }) + .collect::>()?; + Ok(BuiltinOutput::Variables { lvalues, hoisted }) + } + + /// Write `value` to output target `target` (see + /// [`Self::builtin_output_target`]). + fn builtin_output( + &mut self, + target: &BuiltinOutput, + value: RegisterId, + width: usize, + signed: bool, + ) -> Result<(), sv::AnalyzerError> { + let narrowed = self.b.alloc_bit(width, signed); + self.b + .emit(SIRInstruction::Slice(narrowed, value, 0, width)); + let (temp, temp_name) = self.m.temp("dpi_output", width, signed, false); + self.store(temp, SIROffset::Static(0), width, narrowed); + let value = sv::ir::Expr::Ident(temp_name); + match target { + BuiltinOutput::Variables { lvalues, hoisted } => { + match hoisted.as_slice() { + [lvalue] => self.assign(lvalue, &value)?, + parts => self.assign_concat(parts, &value)?, + } + self.observe_assignment(lvalues) + } + BuiltinOutput::Property(actual) => { + let store = forwarded_property(actual, value).expect("a forwarded property"); + self.exec_block(&[store]).map(drop) + } + } + } +} + +/// Where a builtin writes an output. +enum BuiltinOutput { + /// The targets of the actual, and those targets with their selectors + /// evaluated. + Variables { + lvalues: Vec, + hoisted: Vec, + }, + /// The class property a reference formal forwards (see + /// [`forwarded_property`]). + Property(sv::ir::Expr), +} diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 4b6487c9f58..8da35073b2c 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -109,6 +109,12 @@ impl<'a> ProcModule<'a> { callee: sv::ir::Callee::String(op), .. } => op.returns_string(), + sv::ir::Expr::Call { + callee: sv::ir::Callee::Subroutine(name), + .. + } if self.dpi_imports.contains_key(name) => { + self.dpi_imports[name].return_type() == Some(sv::ir::DpiType::String) + } sv::ir::Expr::Call { callee: sv::ir::Callee::Object(op), .. @@ -1288,6 +1294,7 @@ impl<'a> ProcModule<'a> { sv::ir::DpiType::Bit => ExternType::Bit, sv::ir::DpiType::Logic => ExternType::Logic, sv::ir::DpiType::Integer { width, signed } => ExternType::Integer { width, signed }, + sv::ir::DpiType::String => unreachable!("only a builtin passes a string"), // A pointer, 64 bits on the supported hosts. sv::ir::DpiType::Chandle => ExternType::Integer { width: 64, @@ -2940,7 +2947,7 @@ pub(super) fn written_names_with_calls( names: &mut HashSet, ) { super::kernel_written_names( - module.subroutines(), + &super::DriverScan::of(module), stmts, names, &mut HashSet::default(), @@ -2963,6 +2970,22 @@ pub(super) fn written_system_arguments( .collect() } +/// The variables a call of DPI-C import `import` writes through its output +/// arguments (IEEE 1800-2023 35.5.1.2). +pub(super) fn written_dpi_arguments( + import: &sv::ir::DpiImport, + args: &[Option], +) -> Vec { + import + .arguments() + .iter() + .zip(args) + .filter(|(argument, _)| argument.is_output()) + .filter_map(|(_, arg)| arg.as_ref().and_then(lvalue_from_expr)) + .flatten() + .collect() +} + /// State writes performed by heap container calls. pub(super) fn written_object_arguments( op: &sv::ir::ObjectOp, diff --git a/crates/celox-heap/Cargo.toml b/crates/celox-heap/Cargo.toml index e8223578ef6..a41385f6801 100644 --- a/crates/celox-heap/Cargo.toml +++ b/crates/celox-heap/Cargo.toml @@ -15,6 +15,7 @@ serde_json = { workspace = true } serde = { workspace = true, features = ["rc"] } fxhash = { workspace = true } +regex = { workspace = true } [lints] workspace = true diff --git a/crates/celox-heap/src/lib.rs b/crates/celox-heap/src/lib.rs index d474dc87068..f85261a6280 100644 --- a/crates/celox-heap/src/lib.rs +++ b/crates/celox-heap/src/lib.rs @@ -21,6 +21,8 @@ mod objects; pub mod ops; pub mod randomization; pub mod streams; +mod uvm_dpi; +pub use uvm_dpi::deglob as uvm_deglob; pub use objects::{Fault, NULL}; @@ -99,6 +101,8 @@ pub struct Heap { pinned: Handle, created: usize, live_after_collection: usize, + /// The state of UVM's C library functions, see [`uvm_dpi`]. + uvm: uvm_dpi::UvmDpi, } impl Default for Heap { @@ -132,6 +136,7 @@ impl Heap { pinned: 1, created: 0, live_after_collection: 1, + uvm: uvm_dpi::UvmDpi::default(), } } @@ -187,6 +192,7 @@ impl Heap { && self.next_object == other.next_object && self.events == other.events && self.containers == other.containers + && self.uvm == other.uvm } /// The number of live strings, including `""`. diff --git a/crates/celox-heap/src/ops.rs b/crates/celox-heap/src/ops.rs index 120b734f529..e729284857b 100644 --- a/crates/celox-heap/src/ops.rs +++ b/crates/celox-heap/src/ops.rs @@ -116,6 +116,37 @@ pub const fn radix_parameter(radix: u32, width: u32, signed: bool) -> u64 { /// instead of exhausting memory. const MAX_REPLICATE_BYTES: usize = 1 << 30; +/// UVM DPI-C functions (see `uvm_dpi`): `uvm_re_comp(re, deglob)`. +pub const UVM_RE_COMP: u64 = 128; +/// `uvm_re_exec(rexp, str)`. +pub const UVM_RE_EXEC: u64 = 129; +/// `uvm_re_free(rexp)`. +pub const UVM_RE_FREE: u64 = 130; +/// `uvm_re_compexec(re, str, deglob)`; [`UVM_RE_LAST_EXEC`] gives `exec_ret`. +pub const UVM_RE_COMPEXEC: u64 = 131; +/// `uvm_re_compexecfree(re, str, deglob)`; [`UVM_RE_LAST_EXEC`] gives +/// `exec_ret`. +pub const UVM_RE_COMPEXECFREE: u64 = 132; +/// The `exec_ret` of the last compile-and-execute operation. +pub const UVM_RE_LAST_EXEC: u64 = 133; +/// `uvm_re_buffer()`. +pub const UVM_RE_BUFFER: u64 = 134; +/// `uvm_re_deglobbed(glob, with_brackets)`. +pub const UVM_RE_DEGLOBBED: u64 = 135; +/// `uvm_dpi_get_next_arg_c(init)`. +pub const UVM_NEXT_ARG: u64 = 136; +/// `uvm_dpi_get_tool_name_c()`. +pub const UVM_TOOL_NAME: u64 = 137; +/// `uvm_dpi_get_tool_version_c()`. +pub const UVM_TOOL_VERSION: u64 = 138; +// `call` dispatches the low opcode byte by range, so the UVM range shares no +// operation with the container and stream ranges. +const _: () = assert!( + crate::containers::RSORT < UVM_RE_COMP + && crate::streams::TRUNCATE < UVM_RE_COMP + && UVM_TOOL_VERSION <= 0xff +); + impl Heap { /// Perform the operation selected by `code` on `a`, `b` and `c`. pub fn call(&mut self, code: u64, a: u64, b: u64, c: u64) -> u64 { @@ -135,6 +166,7 @@ impl Heap { crate::containers::HANDLE_PATTERN => { self.new_buffer(crate::containers::handle_pattern(a as u32 as u64)) } + op @ UVM_RE_COMP..=UVM_TOOL_VERSION => self.uvm_call(op, a, b, c), COMPARE => ordering(self.string(a as Handle).cmp(self.string(b as Handle))), ICOMPARE => { let lower = |handle| { diff --git a/crates/celox-heap/src/uvm_dpi.rs b/crates/celox-heap/src/uvm_dpi.rs new file mode 100644 index 00000000000..5b9a2cc17a9 --- /dev/null +++ b/crates/celox-heap/src/uvm_dpi.rs @@ -0,0 +1,339 @@ +//! The functions of UVM's C library (UVM `src/dpi`) that Celox provides as +//! heap operations: regular expressions (`uvm_regex.cc`) and the tool's +//! command line (`uvm_svcmd_dpi.c`). +//! +//! A regular expression handle (a `chandle`) is a positive number, never +//! reused, `0` (`null`) on failure. Compiled expressions are rebuilt from +//! their patterns after a checkpoint is restored. + +use super::*; +use std::collections::BTreeMap; +use std::collections::hash_map::Entry; + +/// `REG_NOMATCH` of the C library UVM uses: `uvm_re_exec` returns `0` on a +/// match and this otherwise. +const REG_NOMATCH: u64 = 1; + +/// `UVM_REGEX_MAX_LENGTH` of `uvm_regex.cc`. +const MAX_LENGTH: usize = 2048; + +/// The regular-expression and command-line state of UVM's C library. +#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize, PartialEq, Eq)] +pub(crate) struct UvmDpi { + /// The pattern of each live regular expression handle. + patterns: BTreeMap, + /// The last handle given out. + last_handle: u64, + #[serde(skip)] + compiled: CompiledCache, + /// `uvm_re_buffer()`: the last message or deglobbed expression. + buffer: Vec, + /// The `exec_ret` of the last `uvm_re_compexec`. + last_exec: u64, + /// The tool's arguments, which `uvm_dpi_get_next_arg_c` returns in turn. + arguments: Vec, + next_argument: usize, +} + +/// Compiled expressions, rebuilt on demand; not part of the heap's state. +#[derive(Clone, Debug, Default)] +struct CompiledCache(HashMap); + +impl PartialEq for CompiledCache { + fn eq(&self, _: &Self) -> bool { + true + } +} + +impl Eq for CompiledCache {} + +/// Compile `pattern` as a POSIX extended expression without `REG_NEWLINE` +/// in the C locale: `.` matches any byte, a newline included. +fn compile(pattern: &str) -> Result { + regex::bytes::RegexBuilder::new(pattern) + .dot_matches_new_line(true) + .unicode(false) + .build() +} + +/// The pattern text of expression bytes `re`, each byte that is not UTF-8 +/// written as an escape matching that byte. +fn pattern_text(re: &[u8]) -> String { + let mut text = String::with_capacity(re.len()); + for chunk in re.utf8_chunks() { + text.push_str(chunk.valid()); + for byte in chunk.invalid() { + text.push_str(&format!("\\x{byte:02X}")); + } + } + text +} + +/// The glob-to-ERE translation of `uvm_re_deglobbed`, or the message it +/// leaves in the buffer. +pub fn deglob(glob: &[u8], with_brackets: bool) -> Result, String> { + const BRACKET: u8 = b'/'; + if glob.is_empty() || glob == [BRACKET] { + return Ok(if with_brackets { + b"/^$/".to_vec() + } else { + b"^$".to_vec() + }); + } + if glob.len() > 1 && glob[0] == BRACKET && glob[glob.len() - 1] == BRACKET { + if glob.len() > MAX_LENGTH { + return Err(format!( + "uvm_glob_to_re() glob exceeds max length ({MAX_LENGTH})" + )); + } + return Ok(if with_brackets { + glob.to_vec() + } else { + glob[1..glob.len() - 1].to_vec() + }); + } + let mut out = Vec::with_capacity(glob.len() + 4); + if with_brackets { + out.push(BRACKET); + } + if glob[0] != b'^' { + out.push(b'^'); + } + for &byte in glob { + match byte { + b'*' | b'+' => out.extend([b'.', byte]), + b'.' | b'[' | b']' | b'(' | b')' => out.extend([b'\\', byte]), + b'?' => out.push(b'.'), + _ => out.push(byte), + } + } + if out.last() != Some(&b'$') { + out.push(b'$'); + } + if with_brackets { + out.push(BRACKET); + } + if out.len() > MAX_LENGTH { + return Err(format!( + "uvm_glob_to_re() expansion exceeds max length({MAX_LENGTH})" + )); + } + Ok(out) +} + +impl Heap { + /// Set the tool's command line: the program name, then its arguments. + pub fn set_tool_arguments(&mut self, arguments: Vec) { + self.uvm.arguments = arguments; + self.uvm.next_argument = 0; + } + + fn uvm_string(&mut self, bytes: &[u8]) -> u64 { + self.intern(bytes) as u64 + } + + /// `uvm_re_comp(re, deglob)`. + fn re_comp(&mut self, re: Handle, deglob: bool) -> u64 { + let re = self.string(re).to_vec(); + let pattern = if deglob { + match self::deglob(&re, false) { + Ok(pattern) => pattern, + Err(message) => { + self.uvm.buffer = message.into_bytes(); + return 0; + } + } + } else if re.len() > MAX_LENGTH { + self.uvm.buffer = + format!("uvm_re_comp() re exceeds max length ({MAX_LENGTH})").into_bytes(); + return 0; + } else if re.len() > 1 && re[0] == b'/' && re[re.len() - 1] == b'/' { + re[1..re.len() - 1].to_vec() + } else { + re + }; + let pattern = pattern_text(&pattern); + match compile(&pattern) { + Ok(compiled) => { + self.uvm.last_handle += 1; + let handle = self.uvm.last_handle; + self.uvm.patterns.insert(handle, pattern); + self.uvm.compiled.0.insert(handle, compiled); + handle + } + Err(error) => { + self.uvm.buffer = error.to_string().into_bytes(); + 0 + } + } + } + + /// The compiled expression of handle `rexp`, rebuilt if needed. + fn compiled(&mut self, rexp: u64) -> Option<®ex::bytes::Regex> { + let pattern = self.uvm.patterns.get(&rexp)?; + match self.uvm.compiled.0.entry(rexp) { + Entry::Occupied(entry) => Some(entry.into_mut()), + Entry::Vacant(entry) => compile(pattern).ok().map(|regex| &*entry.insert(regex)), + } + } + + /// `uvm_re_exec(rexp, str)`: `0` on a match. + fn re_exec(&mut self, rexp: u64, string: Handle) -> u64 { + let string = self.string(string).to_vec(); + match self.compiled(rexp) { + Some(regex) => u64::from(!regex.is_match(&string)) * REG_NOMATCH, + None => { + self.uvm.buffer = b"uvm_re_exec: NULL rexp".to_vec(); + REG_NOMATCH + } + } + } + + /// `uvm_re_free(rexp)`. + fn re_free(&mut self, rexp: u64) { + self.uvm.patterns.remove(&rexp); + self.uvm.compiled.0.remove(&rexp); + } + + /// Perform UVM DPI operation `op` on `a`, `b` and `c`. + pub(crate) fn uvm_call(&mut self, op: u64, a: u64, b: u64, c: u64) -> u64 { + match op { + ops::UVM_RE_COMP => self.re_comp(a as Handle, b & 1 != 0), + ops::UVM_RE_EXEC => self.re_exec(a, b as Handle), + ops::UVM_RE_FREE => { + self.re_free(a); + 0 + } + ops::UVM_RE_COMPEXEC => { + let rexp = self.re_comp(a as Handle, c & 1 != 0); + self.uvm.last_exec = if rexp == 0 { + REG_NOMATCH + } else { + self.re_exec(rexp, b as Handle) + }; + rexp + } + ops::UVM_RE_COMPEXECFREE => { + let rexp = self.re_comp(a as Handle, c & 1 != 0); + self.uvm.last_exec = if rexp == 0 { + REG_NOMATCH + } else { + self.re_exec(rexp, b as Handle) + }; + self.re_free(rexp); + u64::from(rexp != 0) + } + ops::UVM_RE_LAST_EXEC => self.uvm.last_exec, + ops::UVM_RE_BUFFER => { + let buffer = self.uvm.buffer.clone(); + self.uvm_string(&buffer) + } + ops::UVM_RE_DEGLOBBED => { + let glob = self.string(a as Handle).to_vec(); + match deglob(&glob, b & 1 != 0) { + Ok(regex) => { + self.uvm.buffer = regex.clone(); + self.uvm_string(®ex) + } + // The C function returns NULL, which is "" (35.5.6). + Err(message) => { + self.uvm.buffer = message.into_bytes(); + EMPTY_STRING as u64 + } + } + } + ops::UVM_NEXT_ARG => { + if a as i32 == 1 { + self.uvm.next_argument = 0; + } + match self.uvm.arguments.get(self.uvm.next_argument).cloned() { + Some(argument) => { + self.uvm.next_argument += 1; + self.uvm_string(argument.as_bytes()) + } + None => EMPTY_STRING as u64, + } + } + ops::UVM_TOOL_NAME => self.uvm_string(b"Celox"), + ops::UVM_TOOL_VERSION => self.uvm_string(env!("CARGO_PKG_VERSION").as_bytes()), + _ => unreachable!("UVM DPI operation {op}"), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn globs_translate_like_uvm_regex_cc() { + for (glob, brackets, expected) in [ + ("", false, "^$"), + ("/", true, "/^$/"), + ("*", false, "^.*$"), + ("top.u?.*", false, "^top\\.u.\\..*$"), + ("^a+[b]", false, "^a.+\\[b\\]$"), + ("ends$", true, "/^ends$/"), + ("/^x.y$/", false, "^x.y$"), + ("/^x.y$/", true, "/^x.y$/"), + ] { + assert_eq!( + String::from_utf8(deglob(glob.as_bytes(), brackets).unwrap()).unwrap(), + expected, + "{glob}" + ); + } + } + + #[test] + fn expressions_compile_match_and_free() { + let mut heap = Heap::new(); + let pattern = heap.intern(b"uvm_test_top.*") as u64; + let rexp = heap.call(ops::UVM_RE_COMP, pattern, 1, 0); + assert_ne!(rexp, 0); + let hit = heap.intern(b"uvm_test_top.env") as u64; + let miss = heap.intern(b"other") as u64; + assert_eq!(heap.call(ops::UVM_RE_EXEC, rexp, hit, 0), 0); + assert_eq!(heap.call(ops::UVM_RE_EXEC, rexp, miss, 0), REG_NOMATCH); + // A restored heap has no compiled expressions and rebuilds them. + let mut restored = heap.clone(); + restored.uvm.compiled = CompiledCache::default(); + assert!(restored.same_contents(&heap)); + assert_eq!(restored.call(ops::UVM_RE_EXEC, rexp, hit, 0), 0); + // `.` matches any byte, a newline included, as without `REG_NEWLINE` + // in the C locale. + let lines = heap.intern(b"uvm_test_top.a\nb\xff") as u64; + assert_eq!(heap.call(ops::UVM_RE_EXEC, rexp, lines, 0), 0); + let byte = heap.intern(b"^a\xffb$") as u64; + let byte = heap.call(ops::UVM_RE_COMP, byte, 0, 0); + let hit_byte = heap.intern(b"a\xffb") as u64; + assert_eq!(heap.call(ops::UVM_RE_EXEC, byte, hit_byte, 0), 0); + assert_eq!(heap.call(ops::UVM_RE_EXEC, byte, hit, 0), REG_NOMATCH); + heap.call(ops::UVM_RE_FREE, byte, 0, 0); + heap.call(ops::UVM_RE_FREE, rexp, 0, 0); + assert_eq!(heap.call(ops::UVM_RE_EXEC, rexp, hit, 0), REG_NOMATCH); + // Freed expressions leave nothing behind and handles are not reused. + assert!(heap.uvm.patterns.is_empty() && heap.uvm.compiled.0.is_empty()); + assert_ne!(heap.call(ops::UVM_RE_COMP, pattern, 1, 0), rexp); + let bad = heap.intern(b"(") as u64; + assert_eq!(heap.call(ops::UVM_RE_COMP, bad, 0, 0), 0); + let message = heap.call(ops::UVM_RE_BUFFER, 0, 0, 0); + assert!(!heap.string(message as Handle).is_empty()); + assert_eq!(heap.call(ops::UVM_RE_COMPEXECFREE, pattern, hit, 1), 1); + assert_eq!(heap.call(ops::UVM_RE_LAST_EXEC, 0, 0, 0), 0); + } + + #[test] + fn arguments_are_returned_in_turn() { + let mut heap = Heap::new(); + heap.set_tool_arguments(vec!["celox".into(), "+UVM_TESTNAME=t".into()]); + let next = |heap: &mut Heap, init| { + let handle = heap.call(ops::UVM_NEXT_ARG, init, 0, 0) as Handle; + String::from_utf8(heap.string(handle).to_vec()).unwrap() + }; + assert_eq!(next(&mut heap, 1), "celox"); + assert_eq!(next(&mut heap, 0), "+UVM_TESTNAME=t"); + assert_eq!(next(&mut heap, 0), ""); + assert_eq!(next(&mut heap, 1), "celox"); + } +} diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index b0c8e8101d1..72556af556b 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -1259,6 +1259,9 @@ impl Module { crate::ir::DpiType::Logic => { type_binding::builtin_type("logic", None) } + crate::ir::DpiType::String => { + type_binding::builtin_type("string", None) + } crate::ir::DpiType::Chandle => { type_binding::builtin_type("chandle", None) } @@ -1288,7 +1291,17 @@ impl Module { ); subroutine_directions.insert( import.name().to_string(), - vec![crate::procedural::ParamDirection::Input; import.arguments().len()], + import + .arguments() + .iter() + .map(|argument| { + if argument.is_output() { + crate::procedural::ParamDirection::Output + } else { + crate::procedural::ParamDirection::Input + } + }) + .collect(), ); } packed_dimensions.subroutine_param_shapes = Arc::new(subroutine_shapes.clone()); @@ -1494,7 +1507,7 @@ impl Module { )), signed: r#type.is_signed(), is_2state: !r#type.is_4state(), - string: false, + string: r#type == crate::ir::DpiType::String, chandle: r#type == crate::ir::DpiType::Chandle, pattern_type: None, enum_domain: None, @@ -3210,7 +3223,11 @@ fn dpi_argument_metadata(import: &crate::ir::DpiImport) -> Arc<[FunctionArgument .iter() .map(|argument| FunctionArgumentMetadata { name: argument.name().to_string(), - direction: ParamDirection::Input, + direction: if argument.is_output() { + ParamDirection::Output + } else { + ParamDirection::Input + }, has_default: false, }) .collect() diff --git a/crates/celox-sv-analyzer/src/ast/dpi.rs b/crates/celox-sv-analyzer/src/ast/dpi.rs index ada0717bd0c..ee8087c86a9 100644 --- a/crates/celox-sv-analyzer/src/ast/dpi.rs +++ b/crates/celox-sv-analyzer/src/ast/dpi.rs @@ -8,9 +8,13 @@ //! and does not change it (35.7). Only a `context` import may call an //! exported subroutine (35.5.3), so an accepted export is checked and has no //! further effect. +//! +//! The functions of UVM's C library (UVM `src/dpi`) are provided by Celox +//! instead: an import with one of their C names and UVM's prototype binds to +//! a [`DpiBuiltin`], so UVM runs without `UVM_NO_DPI` or a C library. use super::*; -use crate::ir::{DpiArgument, DpiImport, DpiType}; +use crate::ir::{DpiArgument, DpiBuiltin, DpiImport, DpiType}; /// The largest number of arguments an imported function may take; the /// limit of `celox_sir::MAX_EXTERN_CALL_ARGUMENTS`. @@ -150,6 +154,228 @@ pub(super) fn import( lower_native_dpi(syntax.dpi_declaration(id), syntax) } +/// A type in the prototype of a UVM DPI-C function. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + String, + Chandle, + Bit, + Int, + /// `uvm_hdl_data_t`, a `logic` vector. + HdlData, +} + +/// The UVM DPI-C functions Celox provides: C name, function, result (`None` +/// for `void`), and arguments with whether they are written. +const BUILTINS: &[(&str, DpiBuiltin, Option, &[(Kind, bool)])] = { + use DpiBuiltin::*; + use Kind::{Bit, Chandle, HdlData, Int, String}; + &[ + ( + "uvm_re_comp", + ReComp, + Some(Chandle), + &[(String, false), (Bit, false)], + ), + ( + "uvm_re_exec", + ReExec, + Some(Int), + &[(Chandle, false), (String, false)], + ), + ("uvm_re_free", ReFree, None, &[(Chandle, false)]), + ( + "uvm_re_compexec", + ReCompExec, + Some(Chandle), + &[(String, false), (String, false), (Bit, false), (Int, true)], + ), + ( + "uvm_re_compexecfree", + ReCompExecFree, + Some(Bit), + &[(String, false), (String, false), (Bit, false), (Int, true)], + ), + ("uvm_re_buffer", ReBuffer, Some(String), &[]), + ( + "uvm_re_deglobbed", + ReDeglobbed, + Some(String), + &[(String, false), (Bit, false)], + ), + ( + "uvm_dpi_get_next_arg_c", + NextArg, + Some(String), + &[(Int, false)], + ), + ("uvm_dpi_get_tool_name_c", ToolName, Some(String), &[]), + ("uvm_dpi_get_tool_version_c", ToolVersion, Some(String), &[]), + ( + "uvm_hdl_check_path", + Unavailable, + Some(Int), + &[(String, false)], + ), + ( + "uvm_hdl_deposit", + Unavailable, + Some(Int), + &[(String, false), (HdlData, false)], + ), + ( + "uvm_hdl_force", + Unavailable, + Some(Int), + &[(String, false), (HdlData, false)], + ), + ( + "uvm_hdl_read", + Unavailable, + Some(Int), + &[(String, false), (HdlData, true)], + ), + ( + "uvm_hdl_release", + Unavailable, + Some(Int), + &[(String, false)], + ), + ( + "uvm_hdl_release_and_read", + Unavailable, + Some(Int), + &[(String, false), (HdlData, true)], + ), + ( + "uvm_hdl_signal_size", + Unavailable, + Some(Int), + &[(String, false)], + ), + ( + "uvm_polling_create", + Unavailable, + Some(Chandle), + &[(String, false), (Int, false)], + ), + ( + "uvm_polling_get_callback_enable", + Unavailable, + Some(Int), + &[(Chandle, false)], + ), + ( + "uvm_polling_setup_notifier", + Unavailable, + Some(Int), + &[(String, false)], + ), + ("uvm_polling_process_changelist", Unavailable, None, &[]), + ( + "uvm_polling_set_enable_callback", + Unavailable, + None, + &[(Chandle, false), (Int, false)], + ), + ("uvm_polling_free_mem_structures", Unavailable, None, &[]), + ] +}; + +/// The kind of a prototype type, as UVM writes it. +fn kind(id: celox_sv_syntax::TypeId, syntax: &celox_sv_syntax::Declarations) -> Option { + use celox_sv_syntax::DataTypeKind; + let data = syntax.data_type(id); + match &data.kind { + DataTypeKind::Builtin(name) if data.packed_dimensions.is_empty() => match name.as_str() { + "string" => Some(Kind::String), + "chandle" => Some(Kind::Chandle), + "bit" if data.signed.is_none() => Some(Kind::Bit), + "int" if data.signed.is_none() => Some(Kind::Int), + _ => None, + }, + DataTypeKind::Builtin(name) if name == "logic" => Some(Kind::HdlData), + DataTypeKind::Named(path) + if path + .last() + .is_some_and(|part| part.name.spelling == "uvm_hdl_data_t") => + { + Some(Kind::HdlData) + } + _ => None, + } +} + +fn builtin_type(kind: Kind) -> DpiType { + match kind { + Kind::String => DpiType::String, + Kind::Chandle => DpiType::Chandle, + Kind::Bit => DpiType::Bit, + Kind::Int => DpiType::Integer { + width: 32, + signed: true, + }, + // `UVM_HDL_MAX_WIDTH` bits, written by no builtin yet. + Kind::HdlData => DpiType::Integer { + width: 64, + signed: false, + }, + } +} + +/// The builtin that a UVM import with C name `c_name` binds to, when it +/// declares UVM's prototype. +fn builtin( + declaration: &celox_sv_syntax::DpiDeclaration, + c_name: &str, + syntax: &celox_sv_syntax::Declarations, +) -> Option { + use celox_sv_syntax::{DataTypeKind, Direction, DpiKind}; + let &(_, builtin, result, arguments) = BUILTINS.iter().find(|(name, ..)| *name == c_name)?; + if !declaration.import || declaration.kind != DpiKind::Function { + return None; + } + let declared_result = declaration.return_type?; + let declared_result = match &syntax.data_type(declared_result).kind { + DataTypeKind::Builtin(name) if name == "void" => None, + _ => Some(kind(declared_result, syntax)?), + }; + if declared_result != result || declaration.ports.len() != arguments.len() { + return None; + } + let mut written = false; + let mut lowered = Vec::with_capacity(arguments.len()); + for (port, &(expected, output)) in declaration.ports.iter().zip(arguments) { + if let Some(direction) = port.direction { + written = direction != Direction::Input; + } + if written != output + || port.constant + || !port.dimensions.is_empty() + || port.default.is_some() + || kind(port.data_type, syntax) != Some(expected) + { + return None; + } + let name = port.name.as_ref()?.spelling.clone(); + lowered.push(if output { + DpiArgument::output(name, builtin_type(expected)) + } else { + DpiArgument::new(name, builtin_type(expected)) + }); + } + Some( + DpiImport::new( + declaration.name.spelling.clone(), + c_name.to_owned(), + false, + result.map(builtin_type), + lowered, + ) + .with_builtin(builtin), + ) +} + /// Bind an owned native body declaration to the existing C ABI/IR contract. /// No legacy declaration, prototype or type nodes participate in this conversion. fn lower_native_dpi( @@ -157,6 +383,16 @@ fn lower_native_dpi( syntax: &celox_sv_syntax::Declarations, ) -> Result { use celox_sv_syntax::{DataTypeKind, Direction, DpiKind, DpiProperty}; + { + let name = &declaration.name.spelling; + let c_name = declaration + .c_name + .as_ref() + .map_or(name, |name| &name.spelling); + if let Some(import) = builtin(declaration, c_name, syntax) { + return Ok(import); + } + } if !declaration.import { return Err(unsupported("DPI-C export")); } @@ -275,6 +511,26 @@ fn native_dpi_type( mod tests { use super::*; + #[test] + fn uvm_prototypes_bind_to_builtins_by_c_name() { + let code = "module M; + import \"DPI-C\" function chandle uvm_re_comp(string re, bit deglob); + import \"DPI-C\" function bit uvm_re_compexecfree(string re, string str, bit deglob, output int exec_ret); + import \"DPI-C\" context function int uvm_hdl_read(string path, output logic [1023:0] value); + import \"DPI-C\" mine = function void uvm_re_free(chandle rexp); + import \"DPI-C\" function int uvm_re_exec(int other); + endmodule"; + let source = crate::analyze_source(code, Path::new("uvm_dpi.sv")).unwrap(); + let imports = source.modules()[0].dpi_imports(); + assert_eq!(imports[0].builtin(), Some(DpiBuiltin::ReComp)); + assert_eq!(imports[1].builtin(), Some(DpiBuiltin::ReCompExecFree)); + assert!(imports[1].arguments()[3].is_output()); + assert_eq!(imports[2].builtin(), Some(DpiBuiltin::Unavailable)); + // Another C name, or another prototype, is an ordinary import. + assert_eq!(imports[3].builtin(), None); + assert_eq!(imports[4].builtin(), None); + } + #[test] fn native_body_prototypes_bind_linkage_signedness_and_empty_argument_lists() { let code = "`define ARG input byte unsigned value\nmodule M; import \"DPI-C\" pure c_add = function shortint add(`ARG, input logic flag); import \"DPI-C\" function void tick(); endmodule"; diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 0894a6185a4..f83c83dcb11 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -2002,6 +2002,8 @@ pub enum DpiType { /// `byte`, `shortint`, `int` or `longint`, passed as the C integer of /// that width. Integer { width: usize, signed: bool }, + /// `string`, only for a [`DpiBuiltin`]: a heap handle. + String, /// `chandle`, passed as a C pointer (IEEE 1800-2023 6.14). Chandle, } @@ -2011,6 +2013,7 @@ impl DpiType { match self { DpiType::Bit | DpiType::Logic => 1, DpiType::Integer { width, .. } => *width, + DpiType::String => celox_design::HANDLE_WIDTH, DpiType::Chandle => 64, } } @@ -2024,16 +2027,55 @@ impl DpiType { } } -/// An argument of a DPI-C import. Only `input` arguments are supported. +/// A UVM DPI-C function that Celox provides itself, so UVM runs without +/// its C library (UVM `src/dpi`). It binds by C name and UVM's prototype. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum DpiBuiltin { + ReComp, + ReExec, + ReFree, + ReCompExec, + ReCompExecFree, + ReBuffer, + ReDeglobbed, + NextArg, + ToolName, + ToolVersion, + /// A function of UVM's C library that Celox does not provide yet: it + /// returns 0 (`null`, failure) and writes no output, so UVM reports the + /// facility as unavailable. + Unavailable, +} + +/// An argument of a DPI-C import. Only `input` arguments are supported, +/// except by a [`DpiBuiltin`]. #[derive(Debug, Clone, PartialEq, Eq)] pub struct DpiArgument { name: String, r#type: DpiType, + output: bool, } impl DpiArgument { pub(crate) fn new(name: String, r#type: DpiType) -> Self { - Self { name, r#type } + Self { + name, + r#type, + output: false, + } + } + + pub(crate) fn output(name: String, r#type: DpiType) -> Self { + Self { + name, + r#type, + output: true, + } + } + + /// Whether the argument is an `output` (or `inout`), of a builtin. + pub fn is_output(&self) -> bool { + self.output } pub fn name(&self) -> &str { @@ -2053,6 +2095,7 @@ pub struct DpiImport { pure: bool, return_type: Option, arguments: Vec, + builtin: Option, } impl DpiImport { @@ -2077,9 +2120,21 @@ impl DpiImport { pure, return_type, arguments, + builtin: None, } } + /// This import bound to a function Celox provides. + pub(crate) fn with_builtin(mut self, builtin: DpiBuiltin) -> Self { + self.builtin = Some(builtin); + self + } + + /// The function Celox provides for this import, if any. + pub fn builtin(&self) -> Option { + self.builtin + } + /// The name SystemVerilog calls the function by. pub fn name(&self) -> &str { &self.name diff --git a/crates/celox/Cargo.toml b/crates/celox/Cargo.toml index 8591d88d79d..c7d0ecb382a 100644 --- a/crates/celox/Cargo.toml +++ b/crates/celox/Cargo.toml @@ -258,6 +258,10 @@ required-features = ["wasm-runtime"] name = "sv_plusargs" required-features = ["wasm-runtime"] +[[test]] +name = "sv_uvm_dpi" +required-features = ["wasm-runtime"] + [[test]] name = "sv_real_math" required-features = ["wasm-runtime"] diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index c10fdd1d9fb..0df960e5ae5 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -1403,6 +1403,26 @@ mod host { .restore_initial_state(initial_memory_values); } + /// Set the simulation's plusargs (IEEE 1800-2023 21.6). The tool's + /// command line, which UVM reads through `uvm_dpi_get_next_arg_c`, + /// is the program name followed by them, each with the leading `+` + /// that UVM recognizes plusargs by and that the builder lets callers + /// leave out. + pub(crate) fn set_plusargs(&mut self, plusargs: Vec) { + self.backend.heap_mut().set_tool_arguments( + std::iter::once("celox".to_owned()) + .chain(plusargs.iter().map(|argument| { + if argument.starts_with('+') { + argument.clone() + } else { + format!("+{argument}") + } + })) + .collect(), + ); + self.plusargs = celox_runtime::plusargs::Plusargs(plusargs); + } + pub(crate) fn run_plusargs_request( &mut self, site: &celox_design::HostRequestSite, diff --git a/crates/celox/src/simulator/builder.rs b/crates/celox/src/simulator/builder.rs index 22a1ece15d0..41c0ac09ce5 100644 --- a/crates/celox/src/simulator/builder.rs +++ b/crates/celox/src/simulator/builder.rs @@ -1839,7 +1839,7 @@ mod host { let mut sim = Simulator::with_backend_and_program(backend, program, warnings); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); - sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.set_plusargs(options.plusargs.clone()); sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Err(error) = validate_native_vcd_layout(sim.layout(), &sim.program, &vcd_path) { return Err(error.with_warnings(std::mem::take(&mut sim.warnings))); @@ -3164,7 +3164,7 @@ mod host { Simulator::with_backend_and_program(backend, laid_out.into_runtime(), warnings); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); - sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.set_plusargs(options.plusargs.clone()); sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); @@ -3222,7 +3222,7 @@ mod host { Simulator::with_backend_and_program(backend, laid_out.into_runtime(), warnings); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); - sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.set_plusargs(options.plusargs.clone()); sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); @@ -3281,7 +3281,7 @@ mod host { Simulator::with_backend_and_program(backend, laid_out.into_runtime(), warnings); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); - sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.set_plusargs(options.plusargs.clone()); sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); @@ -3354,7 +3354,7 @@ mod host { Simulator::with_backend_and_program(backend, laid_out.into_runtime(), warnings); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); - sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.set_plusargs(options.plusargs.clone()); sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); @@ -3574,7 +3574,7 @@ mod host { Simulator::with_backend_and_program(backend, laid_out.into_runtime(), warnings); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); - sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.set_plusargs(options.plusargs.clone()); sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); @@ -3795,7 +3795,7 @@ mod host { sim.components .set_injected(self.injected_components.clone()); sim.diagnostics = self.options.diagnostics.clone(); - sim.plusargs = celox_runtime::plusargs::Plusargs(self.options.plusargs.clone()); + sim.set_plusargs(self.options.plusargs.clone()); sim.file_io = celox_runtime::file_io::FileIo::new(self.options.file_system.create()); sim.apply_initial_values(); @@ -4224,7 +4224,7 @@ mod host { Simulator::with_backend_and_program_for_simulation(backend, program, warnings); sim.components.set_injected(injected_components); sim.diagnostics = options.diagnostics.clone(); - sim.plusargs = celox_runtime::plusargs::Plusargs(options.plusargs.clone()); + sim.set_plusargs(options.plusargs.clone()); sim.file_io = celox_runtime::file_io::FileIo::new(options.file_system.create()); if let Some(path) = vcd_path { let descs = sim.build_vcd_descs(options.four_state); diff --git a/crates/celox/tests/sv_uvm_dpi.rs b/crates/celox/tests/sv_uvm_dpi.rs new file mode 100644 index 00000000000..9b2ae95e98c --- /dev/null +++ b/crates/celox/tests/sv_uvm_dpi.rs @@ -0,0 +1,345 @@ +#![cfg(feature = "systemverilog")] +//! The functions of UVM's C library that Celox provides itself. +use std::path::Path; + +const SOURCE: &str = r#" +package dpi; + import "DPI-C" function chandle uvm_re_comp(string re, bit deglob); + import "DPI-C" function int uvm_re_exec(chandle rexp, string str); + import "DPI-C" function void uvm_re_free(chandle rexp); + import "DPI-C" function chandle uvm_re_compexec(string re, string str, bit deglob, output int exec_ret); + import "DPI-C" function bit uvm_re_compexecfree(string re, string str, bit deglob, output int exec_ret); + import "DPI-C" function string uvm_re_buffer(); + import "DPI-C" function string uvm_re_deglobbed(string glob, bit with_brackets); + import "DPI-C" function string uvm_dpi_get_next_arg_c (int init); + import "DPI-C" function string uvm_dpi_get_tool_name_c (); + import "DPI-C" function string uvm_dpi_get_tool_version_c (); + typedef logic [1023:0] uvm_hdl_data_t; + import "DPI-C" context function int uvm_hdl_read(string path, output uvm_hdl_data_t value); + import "DPI-C" context function chandle uvm_polling_create(input string name, input int sv_key); + + function automatic bit glob_hit(string re, string str); + chandle rexp = uvm_re_comp(re, 1); + bit hit; + if (rexp == null) return 0; + hit = uvm_re_exec(rexp, str) == 0; + uvm_re_free(rexp); + return hit; + endfunction +endpackage + +module Top(output int checks, output int failed); + import dpi::*; + int selections; + function automatic int next_slot(); + selections++; + return 1; + endfunction + initial begin + automatic chandle rexp; + automatic int ret = 7; + automatic string args[$]; + automatic string arg; + automatic uvm_hdl_data_t data = '0; + automatic uvm_hdl_data_t slots[2] = '{'0, '0}; + checks = 0; failed = 0; + if (glob_hit("uvm_test_top.*", "uvm_test_top.env.agent")) checks++; else failed |= 1; + if (!glob_hit("uvm_test_top.*", "top.env")) checks++; else failed |= 2; + if (glob_hit("/^a[0-9]+b$/", "a42b") && !glob_hit("/^a[0-9]+b$/", "ab")) checks++; else failed |= 4; + if (uvm_re_deglobbed("top.u?.*", 0) == "^top\\.u.\\..*$") checks++; else failed |= 8; + rexp = uvm_re_compexec("env*", "env_1", 1, ret); + if (rexp != null && ret == 0) checks++; else failed |= 16; + uvm_re_free(rexp); + if (uvm_re_compexecfree("x", "y", 0, ret) && ret == 1) checks++; else failed |= 32; + if (uvm_re_comp("(", 0) == null && uvm_re_buffer() != "") checks++; else failed |= 64; + arg = uvm_dpi_get_next_arg_c(1); + while (arg != "") begin args.push_back(arg); arg = uvm_dpi_get_next_arg_c(0); end + if (args.size() == 3 && args[1] == "+UVM_TESTNAME=smoke" && args[2] == "+UVM_VERBOSITY=LOW") checks++; else failed |= 128; + if (uvm_dpi_get_tool_name_c() == "Celox" && uvm_dpi_get_tool_version_c() != "") checks++; else failed |= 256; + // Not provided yet: failure, outputs unchanged. + if (uvm_hdl_read("Top.checks", data) == 0 && data == '0 && uvm_polling_create("x", 1) == null) checks++; else failed |= 512; + // The selector of the output is still evaluated. + if (uvm_hdl_read("Top.checks", slots[next_slot()]) == 0 && selections == 1 && slots[1] == '0) checks++; else failed |= 1024; + end +endmodule +"#; + +macro_rules! run_uvm_dpi { + ($name:ident, $backend:ident) => { + #[test] + fn $name() { + for four_state in [false, true] { + let mut sim = celox::Simulation::from_sv_sources( + vec![(SOURCE, Path::new("uvm_dpi.sv"))], + "Top", + ) + .four_state(four_state) + .plusargs(["+UVM_TESTNAME=smoke", "UVM_VERBOSITY=LOW"]) + .$backend() + .unwrap(); + sim.run_until(0).unwrap(); + assert_eq!( + sim.get(sim.signal("failed")), + 0u8.into(), + "four_state={four_state}" + ); + assert_eq!( + sim.get(sim.signal("checks")), + 11u8.into(), + "four_state={four_state}" + ); + } + } + }; +} +run_uvm_dpi!(uvm_dpi_interpreter, build_interpreter); +run_uvm_dpi!(uvm_dpi_cranelift, build); +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +run_uvm_dpi!(uvm_dpi_native, build_native); +run_uvm_dpi!(uvm_dpi_wasm, build_wasm); + +/// The traced builder seeds the arguments too. +#[test] +fn uvm_dpi_traced_builder_sees_arguments() { + let source = r#" +module Top(output bit ok); + import "DPI-C" function string uvm_dpi_get_next_arg_c (int init); + function automatic bit second_is_test(); + string arg = uvm_dpi_get_next_arg_c(1); + arg = uvm_dpi_get_next_arg_c(0); + return arg == "+UVM_TESTNAME=smoke"; + endfunction + assign ok = second_is_test(); +endmodule +"#; + let mut sim = celox::Simulator::from_sv_sources(vec![(source, Path::new("args.sv"))], "Top") + .plusargs(["+UVM_TESTNAME=smoke"]) + .build_with_trace() + .res + .unwrap(); + assert_eq!(sim.get(sim.signal("ok")), 1u8.into()); +} + +const CLOCKED: &str = r#" +`timescale 1ns/1ns +module Top(output int ret_seen, output bit skipped, output bit indexed, output bit hit, output bit freed); + import "DPI-C" function chandle uvm_re_compexec(string re, string str, bit deglob, output int exec_ret); + import "DPI-C" function bit uvm_re_compexecfree(string re, string str, bit deglob, output int exec_ret); + import "DPI-C" function string uvm_dpi_get_next_arg_c (int init); + bit clk = 0; + int ret = 7; + chandle rexp; + always #1 clk = ~clk; + // The output is written before the block reads it. + int free_ret; + always_ff @(posedge clk) begin + rexp = uvm_re_compexec("a*", "aa", 1, ret); + ret_seen <= ret; + hit <= rexp != null; + freed <= uvm_re_compexecfree("a*", "aa", 1, free_ret) && free_ret == 0; + end + // A process whose only effect is the call still runs. + always_ff @(posedge clk) void'(uvm_dpi_get_next_arg_c(0)); + initial begin + void'(uvm_dpi_get_next_arg_c(1)); + #2 skipped = uvm_dpi_get_next_arg_c(0) == "+B"; + end + // The output's selector makes a host request after the result exists. + int status[2] = '{7, 7}; + initial begin + automatic chandle r = uvm_re_compexec("a*", "aa", 1, status[$test$plusargs("B")]); + indexed = r != null && status[1] == 0 && status[0] == 7; + end +endmodule +"#; + +macro_rules! run_clocked { + ($name:ident, $backend:ident) => { + #[test] + fn $name() { + for four_state in [false, true] { + let mut sim = celox::Simulation::from_sv_sources( + vec![(CLOCKED, Path::new("clocked.sv"))], + "Top", + ) + .four_state(four_state) + .plusargs(["+A", "+B"]) + .$backend() + .unwrap(); + sim.run_until(3).unwrap(); + assert_eq!( + sim.get(sim.signal("ret_seen")), + 0u32.into(), + "four_state={four_state}" + ); + assert_eq!( + sim.get(sim.signal("skipped")), + 1u8.into(), + "four_state={four_state}" + ); + assert_eq!( + sim.get(sim.signal("indexed")), + 1u8.into(), + "four_state={four_state}" + ); + // The results of clocked calls, not only their outputs. + assert_eq!( + sim.get(sim.signal("hit")), + 1u8.into(), + "four_state={four_state}" + ); + assert_eq!( + sim.get(sim.signal("freed")), + 1u8.into(), + "four_state={four_state}" + ); + } + } + }; +} +run_clocked!(clocked_interpreter, build_interpreter); +run_clocked!(clocked_cranelift, build); +#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] +run_clocked!(clocked_native, build_native); +run_clocked!(clocked_wasm, build_wasm); + +/// A result outlives the publication of the output, which may suspend a +/// forked process waiting on a compound event. +#[test] +fn uvm_dpi_results_survive_output_publication() { + let source = r#" +`timescale 1ns/1ns +module Top(output bit ok, output bit freed); + import "DPI-C" function chandle uvm_re_compexec(string re, string str, bit deglob, output int exec_ret); + import "DPI-C" function bit uvm_re_compexecfree(string re, string str, bit deglob, output int exec_ret); + int value, ret; + initial begin + automatic chandle rexp; + fork #1 value = 1; join_none + rexp = uvm_re_compexec("env*", "env_1", 1, ret); + ok = rexp != null && ret == 0; + freed = uvm_re_compexecfree("x", "y", 0, ret) && ret == 1; + void'(uvm_re_compexec("env*", "env_2", 1, ret)); + uvm_re_compexecfree("a", "b", 0, ret); + @(value == 1); + end +endmodule +"#; + for four_state in [false, true] { + let mut sim = + celox::Simulation::from_sv_sources(vec![(source, Path::new("publish.sv"))], "Top") + .four_state(four_state) + .build() + .unwrap(); + sim.run_until(2).unwrap(); + assert_eq!( + sim.get(sim.signal("ok")), + 1u8.into(), + "four_state={four_state}" + ); + assert_eq!( + sim.get(sim.signal("freed")), + 1u8.into(), + "four_state={four_state}" + ); + } +} + +/// An output of a builtin forwarded from a reference formal bound to a class +/// property is written to the property (IEEE 1800-2023 13.5.2). +#[test] +fn uvm_dpi_outputs_reach_forwarded_class_properties() { + let source = r#" +module Top(output bit ok); + import "DPI-C" function chandle uvm_re_compexec(string re, string str, bit deglob, output int exec_ret); + import "DPI-C" function bit uvm_re_compexecfree(string re, string str, bit deglob, output int exec_ret); + class Holder; + int status = 7; + int freed = 7; + endclass + function automatic chandle match_into(ref int status); + return uvm_re_compexec("env*", "env_1", 1, status); + endfunction + function automatic bit miss_into(ref int status); + return uvm_re_compexecfree("x", "y", 0, status); + endfunction + initial begin + automatic Holder h = new; + automatic chandle rexp = match_into(h.status); + ok = rexp != null && h.status == 0 && miss_into(h.freed) && h.freed == 1; + end +endmodule +"#; + for four_state in [false, true] { + let mut sim = + celox::Simulation::from_sv_sources(vec![(source, Path::new("forward.sv"))], "Top") + .four_state(four_state) + .build() + .unwrap(); + sim.run_until(1).unwrap(); + assert_eq!( + sim.get(sim.signal("ok")), + 1u8.into(), + "four_state={four_state}" + ); + } +} + +/// An output that selects an inactive tagged union member is an invalid +/// access, as for any output actual (IEEE 1800-2023 7.3.2). +#[test] +fn uvm_dpi_outputs_check_tagged_members() { + let source = r#" +module Top(output int y); + import "DPI-C" function chandle uvm_re_compexec(string re, string str, bit deglob, output int exec_ret); + union tagged packed { void Empty; logic [31:0] Full; } status; + initial begin + status = tagged Empty; + void'(uvm_re_compexec("a", "a", 0, status.Full)); + y = 0; + end +endmodule +"#; + for four_state in [false, true] { + let mut sim = + celox::Simulation::from_sv_sources(vec![(source, Path::new("tagged.sv"))], "Top") + .four_state(four_state) + .build() + .unwrap(); + let error = sim.step().unwrap_err(); + assert!( + error.to_string().contains("tagged union member"), + "four_state={four_state}: {error}" + ); + } +} + +/// A variable that processes of one edge share through a builtin's output +/// is not overwritten by a process that leaves it unwritten. +#[test] +fn uvm_dpi_outputs_are_shared_edge_writes() { + let source = r#" +module Top(input bit clk, output int seen); + import "DPI-C" function chandle uvm_re_compexec(string re, string str, bit deglob, output int exec_ret); + bit set = 0; + int ret = 7; + always @(posedge clk) void'(uvm_re_compexec("a", "a", 0, ret)); + always @(posedge clk) if (set) ret = 5; + assign seen = ret; +endmodule +"#; + for four_state in [false, true] { + let mut sim = + celox::Simulator::from_sv_sources(vec![(source, Path::new("shared.sv"))], "Top") + .four_state(four_state) + .build() + .unwrap(); + let clk = sim.event("clk"); + sim.tick(clk).unwrap(); + assert_eq!( + sim.get(sim.signal("seen")), + 0u32.into(), + "four_state={four_state}" + ); + } +} diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index 8a52bb67ced..b9b31b884dc 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -1662,6 +1662,20 @@ C names are unique, and it takes no `ref` formals or class handles (35.7). An export does not change the subroutine (35.7), and only `context` imports may call exported subroutines (35.5.3), so no C code calls them. +The functions of UVM's C library (UVM `src/dpi`) are provided by Celox, so UVM +runs without `UVM_NO_DPI` or a C library, and without the `sv-dpi` feature: an +import with one of their C names and UVM's prototype binds to Celox's version +instead of a C function, and a user implementation under that name is not +called. `uvm_re_comp`, `uvm_re_exec`, `uvm_re_free`, `uvm_re_compexec`, +`uvm_re_compexecfree`, `uvm_re_buffer` and `uvm_re_deglobbed` behave like UVM's +`uvm_regex.cc`, except that expressions are compiled with the Rust `regex` +crate, whose syntax differs from POSIX extended regular expressions in some rare +constructs, and +`uvm_dpi_get_next_arg_c` returns `celox` followed by the plusargs, with +`uvm_dpi_get_tool_name_c` returning `Celox`. The `uvm_hdl_*` and +`uvm_polling_*` functions are not provided yet: they return 0 or `null` and +leave their outputs unchanged, so UVM reports the facility as unavailable. + ## SystemVerilog emitted by Veryl {#systemverilog-emitted-by-veryl} The Veryl conformance suite runs against the SystemVerilog that Veryl emits. diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 8425d3b6bae..ccfc86b6039 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -937,6 +937,14 @@ interface の既定値で呼び出す定数関数は、native analyzer が本体 組み合わせ回路からの呼び出し、`context`、task import、`output` / `inout`、packed vector、`real`、`string` などは未対応です。 同じモジュール・package で定義した関数・task の `export "DPI-C"` 宣言は受理して検査します(1 つのサブルーチンにつき 1 回、C 名の重複なし、`ref` 仮引数とクラスハンドルなし、35.7)。export はサブルーチンを変えず(35.7)、export したサブルーチンを呼べるのは `context` import だけなので(35.5.3)、C から呼ばれることはありません。 +UVM の C ライブラリ(UVM `src/dpi`)の関数は Celox が提供するため、UVM は `UVM_NO_DPI` も C ライブラリも +`sv-dpi` 機能もなしに動きます。それらの C 名と UVM のプロトタイプを持つ import は C 関数ではなく Celox の実装に +束縛され、同名のユーザー実装は呼ばれません。`uvm_re_comp`・`uvm_re_exec`・`uvm_re_free`・`uvm_re_compexec`・ +`uvm_re_compexecfree`・`uvm_re_buffer`・`uvm_re_deglobbed` は UVM の `uvm_regex.cc` と同じ動作です。ただし正規表現は +Rust の `regex` クレートでコンパイルするため、まれな構文で POSIX 拡張正規表現と異なる場合があります。`uvm_dpi_get_next_arg_c` は `celox` に続けて +plusargs を返し、`uvm_dpi_get_tool_name_c` は `Celox` を返します。`uvm_hdl_*` と `uvm_polling_*` は未提供で、0 または +`null` を返し出力を変更しないため、UVM はその機能が使えないと報告します。 + 登録のコード例と詳細は[英語版の DPI-C imports](/guide/systemverilog-reference#dpi-c-imports)を参照してください。 ## Veryl が出力する SystemVerilog {#systemverilog-emitted-by-veryl}