diff --git a/Cargo.lock b/Cargo.lock index 9638a70c314..ea0809aa7ab 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -617,6 +617,7 @@ version = "0.11.0" dependencies = [ "celox-design", "celox-frontend-core", + "celox-heap", "celox-sir", "celox-slt", "celox-sv-analyzer", @@ -701,6 +702,7 @@ version = "0.11.0" dependencies = [ "bit-set", "celox-design", + "celox-heap", "celox-state-layout", "celox-testbench", "chrono", diff --git a/conformance/sv-tests/README.md b/conformance/sv-tests/README.md index 2964661cb26..2b9a23feef3 100644 --- a/conformance/sv-tests/README.md +++ b/conformance/sv-tests/README.md @@ -123,6 +123,17 @@ in both state modes, updating twelve more expectation rows. The scanner probes retain failures caused by unsupported `final` constructs or internal data types; no scanner expectation is changed. +The `string` implementation updates forty-two reviewed expectation rows: both +state modes for `5.13-builtin-methods-strings`, `6.16--string`, the sixteen +`6.16.*` method cases, `6.20.4--localparam_string`, +`11.4.12.2--string_concat_op` and `11.4.12.2--string_repl_op` change from fail +to pass. Each was simulated and its values checked, not only elaborated. Full +official runs at the pinned revision report 507 passing cases in 2state and 509 +in 4state. No passing case regresses. The `12.7.3--foreach`, `12.7.4--while` and +`12.7.5--dowhile` cases keep failing: they use an unpacked array of strings, +which is rejected because its element and character selects are not yet told +apart. + The report contains each case’s state mode, verdict, selected execution mode, tags, tool return code and path to the official log. The output directory retains both the official log and runner diagnostics for each case and state mode. diff --git a/conformance/sv-tests/expected.tsv b/conformance/sv-tests/expected.tsv index 01dce0b551b..a7ecf3e2733 100644 --- a/conformance/sv-tests/expected.tsv +++ b/conformance/sv-tests/expected.tsv @@ -89,10 +89,10 @@ chapter-11/11.4.12.1--repl_op-sim.sv 2state pass chapter-11/11.4.12.1--repl_op-sim.sv 4state pass chapter-11/11.4.12.1--repl_op.sv 2state pass chapter-11/11.4.12.1--repl_op.sv 4state pass -chapter-11/11.4.12.2--string_concat_op.sv 2state fail -chapter-11/11.4.12.2--string_concat_op.sv 4state fail -chapter-11/11.4.12.2--string_repl_op.sv 2state fail -chapter-11/11.4.12.2--string_repl_op.sv 4state fail +chapter-11/11.4.12.2--string_concat_op.sv 2state pass +chapter-11/11.4.12.2--string_concat_op.sv 4state pass +chapter-11/11.4.12.2--string_repl_op.sv 2state pass +chapter-11/11.4.12.2--string_repl_op.sv 4state pass chapter-11/11.4.13--set_member-sim.sv 2state pass chapter-11/11.4.13--set_member-sim.sv 4state pass chapter-11/11.4.13--set_member.sv 2state pass @@ -1011,8 +1011,8 @@ chapter-5/5.12-attributes-operator.sv 2state pass chapter-5/5.12-attributes-operator.sv 4state pass chapter-5/5.12-attributes-variable.sv 2state pass chapter-5/5.12-attributes-variable.sv 4state pass -chapter-5/5.13-builtin-methods-strings.sv 2state fail -chapter-5/5.13-builtin-methods-strings.sv 4state fail +chapter-5/5.13-builtin-methods-strings.sv 2state pass +chapter-5/5.13-builtin-methods-strings.sv 4state pass chapter-5/5.4--coments.sv 2state pass chapter-5/5.4--coments.sv 4state pass chapter-5/5.6--identifiers.sv 2state pass @@ -1109,44 +1109,44 @@ chapter-6/6.13--void.sv 2state pass chapter-6/6.13--void.sv 4state pass chapter-6/6.14--chandle.sv 2state fail chapter-6/6.14--chandle.sv 4state fail -chapter-6/6.16--string.sv 2state fail -chapter-6/6.16--string.sv 4state fail -chapter-6/6.16.1--string_len.sv 2state fail -chapter-6/6.16.1--string_len.sv 4state fail +chapter-6/6.16--string.sv 2state pass +chapter-6/6.16--string.sv 4state pass +chapter-6/6.16.1--string_len.sv 2state pass +chapter-6/6.16.1--string_len.sv 4state pass chapter-6/6.16.10--string_atoreal.sv 2state fail chapter-6/6.16.10--string_atoreal.sv 4state fail -chapter-6/6.16.11--string_itoa.sv 2state fail -chapter-6/6.16.11--string_itoa.sv 4state fail -chapter-6/6.16.12--string_hextoa.sv 2state fail -chapter-6/6.16.12--string_hextoa.sv 4state fail -chapter-6/6.16.13--string_octtoa.sv 2state fail -chapter-6/6.16.13--string_octtoa.sv 4state fail -chapter-6/6.16.14--string_bintoa.sv 2state fail -chapter-6/6.16.14--string_bintoa.sv 4state fail +chapter-6/6.16.11--string_itoa.sv 2state pass +chapter-6/6.16.11--string_itoa.sv 4state pass +chapter-6/6.16.12--string_hextoa.sv 2state pass +chapter-6/6.16.12--string_hextoa.sv 4state pass +chapter-6/6.16.13--string_octtoa.sv 2state pass +chapter-6/6.16.13--string_octtoa.sv 4state pass +chapter-6/6.16.14--string_bintoa.sv 2state pass +chapter-6/6.16.14--string_bintoa.sv 4state pass chapter-6/6.16.15--string_realtoa.sv 2state fail chapter-6/6.16.15--string_realtoa.sv 4state fail -chapter-6/6.16.2--string_putc.sv 2state fail -chapter-6/6.16.2--string_putc.sv 4state fail -chapter-6/6.16.3--string_getc.sv 2state fail -chapter-6/6.16.3--string_getc.sv 4state fail -chapter-6/6.16.4--string_toupper.sv 2state fail -chapter-6/6.16.4--string_toupper.sv 4state fail -chapter-6/6.16.5--string_tolower.sv 2state fail -chapter-6/6.16.5--string_tolower.sv 4state fail -chapter-6/6.16.6--string_compare.sv 2state fail -chapter-6/6.16.6--string_compare.sv 4state fail -chapter-6/6.16.7--string_icompare.sv 2state fail -chapter-6/6.16.7--string_icompare.sv 4state fail -chapter-6/6.16.8--string_substr.sv 2state fail -chapter-6/6.16.8--string_substr.sv 4state fail -chapter-6/6.16.9--string_atobin.sv 2state fail -chapter-6/6.16.9--string_atobin.sv 4state fail -chapter-6/6.16.9--string_atohex.sv 2state fail -chapter-6/6.16.9--string_atohex.sv 4state fail -chapter-6/6.16.9--string_atoi.sv 2state fail -chapter-6/6.16.9--string_atoi.sv 4state fail -chapter-6/6.16.9--string_atooct.sv 2state fail -chapter-6/6.16.9--string_atooct.sv 4state fail +chapter-6/6.16.2--string_putc.sv 2state pass +chapter-6/6.16.2--string_putc.sv 4state pass +chapter-6/6.16.3--string_getc.sv 2state pass +chapter-6/6.16.3--string_getc.sv 4state pass +chapter-6/6.16.4--string_toupper.sv 2state pass +chapter-6/6.16.4--string_toupper.sv 4state pass +chapter-6/6.16.5--string_tolower.sv 2state pass +chapter-6/6.16.5--string_tolower.sv 4state pass +chapter-6/6.16.6--string_compare.sv 2state pass +chapter-6/6.16.6--string_compare.sv 4state pass +chapter-6/6.16.7--string_icompare.sv 2state pass +chapter-6/6.16.7--string_icompare.sv 4state pass +chapter-6/6.16.8--string_substr.sv 2state pass +chapter-6/6.16.8--string_substr.sv 4state pass +chapter-6/6.16.9--string_atobin.sv 2state pass +chapter-6/6.16.9--string_atobin.sv 4state pass +chapter-6/6.16.9--string_atohex.sv 2state pass +chapter-6/6.16.9--string_atohex.sv 4state pass +chapter-6/6.16.9--string_atoi.sv 2state pass +chapter-6/6.16.9--string_atoi.sv 4state pass +chapter-6/6.16.9--string_atooct.sv 2state pass +chapter-6/6.16.9--string_atooct.sv 4state pass chapter-6/6.17--event.sv 2state fail chapter-6/6.17--event.sv 4state fail chapter-6/6.18--typedef.sv 2state pass @@ -1209,8 +1209,8 @@ chapter-6/6.20.4--localparam_int.sv 2state pass chapter-6/6.20.4--localparam_int.sv 4state pass chapter-6/6.20.4--localparam_logic.sv 2state pass chapter-6/6.20.4--localparam_logic.sv 4state pass -chapter-6/6.20.4--localparam_string.sv 2state fail -chapter-6/6.20.4--localparam_string.sv 4state fail +chapter-6/6.20.4--localparam_string.sv 2state pass +chapter-6/6.20.4--localparam_string.sv 4state pass chapter-6/6.20.4--localparam_unsigned_int.sv 2state pass chapter-6/6.20.4--localparam_unsigned_int.sv 4state pass chapter-6/6.20.5--specparam.sv 2state pass diff --git a/crates/celox-backend-arm64/src/scalar/extern_call.rs b/crates/celox-backend-arm64/src/scalar/extern_call.rs index 0ecf279451f..d2224389445 100644 --- a/crates/celox-backend-arm64/src/scalar/extern_call.rs +++ b/crates/celox-backend-arm64/src/scalar/extern_call.rs @@ -54,10 +54,15 @@ pub(super) fn emit_call_extern( saved: &[u8], pinned_fp: &[u8], ) -> Result<(), EmitError> { - let register_args = args.len().min(REGISTER_ARGS); + // The heap helper takes the state pointer before the arguments, so C + // argument `position` is `args[position - leading]`. + let heap = func == celox_sir::extern_abi::HEAP_HELPER_ID; + let leading = usize::from(heap); + let positions = args.len() + leading; + let register_args = positions.min(REGISTER_ARGS); // Outgoing stack arguments sit at SP, followed by the staged register // arguments and the save areas. - let staging = args.len().saturating_sub(REGISTER_ARGS) * 8; + let staging = positions.saturating_sub(REGISTER_ARGS) * 8; let gpr_save = staging + register_args * 8; let fp_save = gpr_save + saved.len() * 8; let frame = (fp_save + pinned_fp.len() * 8 + 15) & !15; @@ -80,10 +85,11 @@ pub(super) fn emit_call_extern( // Write every argument before overwriting any argument register, so // the moves into x0-x7 cannot clobber a source. for (index, &value) in args.iter().enumerate() { - let offset = if index < REGISTER_ARGS { - staging + index * 8 + let position = index + leading; + let offset = if position < REGISTER_ARGS { + staging + position * 8 } else { - (index - REGISTER_ARGS) * 8 + (position - REGISTER_ARGS) * 8 }; emit_store_at( ops, @@ -93,7 +99,7 @@ pub(super) fn emit_call_extern( OpSize::S64, ); } - for index in 0..register_args { + for index in leading..register_args { emit_load_at( ops, index as u8, @@ -102,6 +108,10 @@ pub(super) fn emit_call_extern( OpSize::S64, ); } + if heap { + // The state pointer is the saved x0. + emit_load_at(ops, 0, 31, gpr_save as i64, OpSize::S64); + } // The state pointer is the saved x0. emit_load_at(ops, SCRATCH1, 31, gpr_save as i64, OpSize::S64); @@ -114,6 +124,8 @@ pub(super) fn emit_call_extern( ); let offset = if func == celox_sir::float::FLOAT_HELPER_ID { -8 + } else if heap { + -16 } else { i64::from(func) * 8 }; diff --git a/crates/celox-backend-cranelift/src/translator/core.rs b/crates/celox-backend-cranelift/src/translator/core.rs index 9b475b61111..bc7af45163d 100644 --- a/crates/celox-backend-cranelift/src/translator/core.rs +++ b/crates/celox-backend-cranelift/src/translator/core.rs @@ -489,23 +489,35 @@ impl SIRTranslator { state.mem_ptr, celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET as i32, ); + // The heap helper sits two slots before the user table and takes the + // state pointer before its arguments. + let heap = func == celox_sir::extern_abi::HEAP_HELPER_ID; let function = state.builder.ins().load( types::I64, MemFlags::trusted(), table, - i32::try_from(func as u64 * 8).expect("extern function index fits the table"), + if heap { + -16 + } else { + i32::try_from(func as u64 * 8).expect("extern function index fits the table") + }, ); let mut signature = Signature::new(self.target_config.default_call_conv); signature .params - .extend(args.iter().map(|_| AbiParam::new(types::I64))); + .extend((0..args.len() + usize::from(heap)).map(|_| AbiParam::new(types::I64))); signature.returns.push(AbiParam::new(types::I64)); let signature = state.builder.import_signature(signature); - let arguments = args - .iter() - .map(|arg| self.extern_call_argument(state, *arg)) + let arguments = heap + .then_some(state.mem_ptr) + .into_iter() + .chain( + args.iter() + .map(|arg| self.extern_call_argument(state, *arg)) + .collect::>(), + ) .collect::>(); let call = state .builder diff --git a/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs b/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs index a35ed57289a..3c40c1e1030 100644 --- a/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs +++ b/crates/celox-backend-x86/src/backend/native/emit/extern_call.rs @@ -124,21 +124,30 @@ pub(super) fn emit_call_extern( } else { (&[rdi, rsi, rdx, rcx, r8, r9], 0) }; - let arg_count = usize::from(arg_count); + // The heap helper takes the state pointer before the staged arguments. + let heap = func == celox_sir::extern_abi::HEAP_HELPER_ID; + let leading = usize::from(heap); + let arg_count = usize::from(arg_count) + leading; let stack_args = arg_count.saturating_sub(registers.len()) as i32; // Generated code is entered with RSP = 8 (mod 16) and never moves it. let frame = ((shadow + 8 * stack_args + 15) & !15) + 8; asm.sub(rsp, frame)?; - for slot in registers.len()..arg_count { - let slot = slot as i32; + // C argument `position` comes from call-area slot `position - leading`. + for position in registers.len()..arg_count { + let slot = (position - leading) as i32; asm.mov(rax, qword_ptr(rbx + (area + 8 * slot)))?; asm.mov( - qword_ptr(rsp + (shadow + 8 * (slot - registers.len() as i32))), + qword_ptr(rsp + (shadow + 8 * (position - registers.len()) as i32)), rax, )?; } - for (slot, ®ister) in registers.iter().enumerate().take(arg_count) { - asm.mov(register, qword_ptr(rbx + (area + 8 * slot as i32)))?; + for (position, ®ister) in registers.iter().enumerate().take(arg_count) { + if position < leading { + asm.mov(register, rbx)?; + } else { + let slot = (position - leading) as i32; + asm.mov(register, qword_ptr(rbx + (area + 8 * slot)))?; + } } asm.mov( rax, @@ -146,6 +155,8 @@ pub(super) fn emit_call_extern( )?; let offset = if func == celox_sir::float::FLOAT_HELPER_ID { -8 + } else if heap { + -16 } else { i32::try_from(u64::from(func) * 8).expect("extern function index") }; diff --git a/crates/celox-backend-x86/src/lib.rs b/crates/celox-backend-x86/src/lib.rs index 0a0c7d7f230..6d35faf9394 100644 --- a/crates/celox-backend-x86/src/lib.rs +++ b/crates/celox-backend-x86/src/lib.rs @@ -111,6 +111,10 @@ const _: () = { ); assert!( celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET + 8 + <= celox_state_layout::STATE_HEADER_HEAP_ADDR_OFFSET + ); + assert!( + celox_state_layout::STATE_HEADER_HEAP_ADDR_OFFSET + 8 <= celox_state_layout::STATE_HEADER_SIZE ); }; diff --git a/crates/celox-design/src/lib.rs b/crates/celox-design/src/lib.rs index 385e71c53f8..5a008661a65 100644 --- a/crates/celox-design/src/lib.rs +++ b/crates/celox-design/src/lib.rs @@ -121,6 +121,10 @@ pub struct RuntimeEventSite { pub arg_is_string: Vec, #[serde(default)] pub arg_float_precision: Vec>, + /// Arguments that are heap handles of strings, formatted as their + /// contents. Missing entries are not handles. + #[serde(default)] + pub arg_is_handle: Vec, } /// A function in the host's C ABI that the design calls, such as a @@ -1598,6 +1602,7 @@ mod tests { arg_signed: Vec::new(), arg_is_string: Vec::new(), arg_float_precision: Vec::new(), + arg_is_handle: Vec::new(), }); runtime.comb_observers.push(RuntimeCombObserver { site_id: 0, diff --git a/crates/celox-frontend-core/src/symbolic/assembly.rs b/crates/celox-frontend-core/src/symbolic/assembly.rs index 450145040e9..22268c8a63a 100644 --- a/crates/celox-frontend-core/src/symbolic/assembly.rs +++ b/crates/celox-frontend-core/src/symbolic/assembly.rs @@ -2233,7 +2233,13 @@ fn relocate_executation_unit_with_errors( SIRInstruction::ExternCall { dst, func, args } => { SIRInstruction::ExternCall { dst: *dst, - func: extern_functions[func], + // The heap helper is outside every + // module's extern function table. + func: if *func == celox_sir::extern_abi::HEAP_HELPER_ID { + *func + } else { + extern_functions[func] + }, args: args.clone(), } } diff --git a/crates/celox-frontend-sv/Cargo.toml b/crates/celox-frontend-sv/Cargo.toml index 4597d98a0db..a51b484247d 100644 --- a/crates/celox-frontend-sv/Cargo.toml +++ b/crates/celox-frontend-sv/Cargo.toml @@ -12,6 +12,7 @@ rust-version.workspace = true [dependencies] celox-design = { workspace = true } celox-frontend-core = { workspace = true } +celox-heap = { workspace = true } celox-sir = { workspace = true } celox-slt = { workspace = true } celox-sv-analyzer = { workspace = true } diff --git a/crates/celox-frontend-sv/src/lowering.rs b/crates/celox-frontend-sv/src/lowering.rs index 908fa9d4863..b38e77bf898 100644 --- a/crates/celox-frontend-sv/src/lowering.rs +++ b/crates/celox-frontend-sv/src/lowering.rs @@ -68,6 +68,8 @@ const EVENT_PREFIX: &str = "$event["; #[derive(Clone)] struct SvVariable { float: Option, + /// A `string`: each element is a heap handle. + string: bool, path: Vec, width: usize, signed: bool, @@ -85,6 +87,17 @@ struct SvVariable { force_control: Option<(SourceVarId, bool)>, } +/// Whether `expr` reads a string variable: after its calls are hoisted, a +/// string-valued argument is the identifier of a variable or temporary. +fn reads_string_variable( + expr: &sv::ir::Expr, + variables: &HashMap, + names: &HashMap, +) -> bool { + matches!(expr, sv::ir::Expr::Ident(name) + if names.get(name).and_then(|id| variables.get(id)).is_some_and(|v| v.string)) +} + impl SvVariable { fn to_symbolic_variable(&self) -> SymbolicVariable { SymbolicVariable { @@ -97,7 +110,11 @@ impl SvVariable { kind: self.domain_kind, type_kind: self.type_kind, array_dims: self.array_dims.clone(), - value_kind: Default::default(), + value_kind: if self.string { + celox_design::ValueKind::StrRef + } else { + celox_design::ValueKind::Bits + }, }, unpacked_ranges: self.unpacked_ranges.clone(), packed_dims: self @@ -1129,6 +1146,7 @@ impl DriverScan<'_> { } continue; } + sv::ir::Callee::String(_) => continue, sv::ir::Callee::Subroutine(name) => name, }; let Some(subroutine) = self @@ -1511,6 +1529,8 @@ fn prepare_external_hierarchy_collecting( id, SvVariable { float: None, + + string: false, path: vec![variable.path.join("$")], width: variable.metadata.width, signed: variable.signed, @@ -2619,6 +2639,8 @@ fn lower_module_with_overrides( let kind = signal_kind_from_port_direction(port.direction())?; let variable = SvVariable { float: type_info.float, + + string: type_info.string, path, width: type_info.width, signed: type_info.signed, @@ -2701,6 +2723,8 @@ fn lower_module_with_overrides( } let variable = SvVariable { float: type_info.float, + + string: type_info.string, path, width: type_info.width, signed: type_info.signed, @@ -2775,6 +2799,8 @@ fn lower_module_with_overrides( id, SvVariable { float: None, + + string: false, path: vec![parameter.name().to_string()], width, signed, @@ -3846,6 +3872,8 @@ fn lower_initial_processes( id, SvVariable { float: None, + + string: false, path: vec![format!("$initial[{index}]"), slot.to_string()], width, signed: false, @@ -4246,6 +4274,8 @@ fn ensure_parent_output_signals( implicit_output_signals.insert(actual.to_string()); let variable = SvVariable { float: None, + + string: false, path: vec![actual.to_string()], width: 1, signed: false, @@ -5553,6 +5583,7 @@ fn signal_kind_from_port_direction( struct SvSignalType { float: Option, + string: bool, width: usize, signed: bool, is_4state: bool, @@ -5641,7 +5672,8 @@ fn signal_type_from_sv( sv::ir::TypeKind::Shortreal => Some(celox_sir::FloatPrecision::F32), _ => None, }; - let is_4state = float.is_none() && !matches!(typ.kind(), sv::ir::TypeKind::Bit); + let is_4state = + float.is_none() && !matches!(typ.kind(), sv::ir::TypeKind::Bit | sv::ir::TypeKind::String); let packed_ranges = typ .packed_ranges() .iter() @@ -5666,9 +5698,19 @@ fn signal_type_from_sv( sv::ir::TypeKind::Logic | sv::ir::TypeKind::Reg | sv::ir::TypeKind::Implicit => { PortTypeKind::Logic } + sv::ir::TypeKind::String => PortTypeKind::Other, }; + let string = typ.kind() == sv::ir::TypeKind::String; + if string && !array_dims.is_empty() { + // Selects of such an array would need to tell element selects from + // character selects. + return Err(sv::AnalyzerError::Unsupported( + "unpacked array of strings".into(), + )); + } Ok(SvSignalType { float, + string, width, signed, is_4state, diff --git a/crates/celox-frontend-sv/src/lowering/comb.rs b/crates/celox-frontend-sv/src/lowering/comb.rs index d5402df3c22..071c7ce59c0 100644 --- a/crates/celox-frontend-sv/src/lowering/comb.rs +++ b/crates/celox-frontend-sv/src/lowering/comb.rs @@ -3446,6 +3446,7 @@ impl<'p, 'a> Comb<'p, 'a> { let mut arg_signed = Vec::with_capacity(values.len()); let mut arg_is_string = Vec::with_capacity(values.len()); let mut arg_float_precision = Vec::with_capacity(values.len()); + let mut arg_is_handle = Vec::with_capacity(values.len()); for value in &values { let node = match value { sv::ir::SystemTaskArg::Expr(expr) => { @@ -3455,6 +3456,11 @@ impl<'p, 'a> Comb<'p, 'a> { expr.clone() }; let signed = self.expr_signed(&expr); + arg_is_handle.push(reads_string_variable( + &expr, + self.m.variables, + self.m.name_to_id, + )); arg_float_precision.push(floating::precision( &expr, self.m.variables, @@ -3475,6 +3481,7 @@ impl<'p, 'a> Comb<'p, 'a> { arg_signed.push(false); arg_is_string.push(true); arg_float_precision.push(None); + arg_is_handle.push(false); slt_constant(self.arena, value, width, false)? } sv::ir::SystemTaskArg::Empty => { @@ -3553,6 +3560,7 @@ impl<'p, 'a> Comb<'p, 'a> { arg_signed, arg_is_string, arg_float_precision, + arg_is_handle, }); let mut preceding_writes = Vec::new(); for (id, range) in store.iter() { diff --git a/crates/celox-frontend-sv/src/lowering/ff.rs b/crates/celox-frontend-sv/src/lowering/ff.rs index 860fdbc1da6..1ad5bb823c1 100644 --- a/crates/celox-frontend-sv/src/lowering/ff.rs +++ b/crates/celox-frontend-sv/src/lowering/ff.rs @@ -12,6 +12,7 @@ mod file_io; mod fread; mod scan; +mod strings; use super::procedural::*; use super::*; @@ -263,6 +264,7 @@ impl<'p, 'a> Ff<'p, 'a> { } continue; } + sv::ir::Callee::String(_) => continue, sv::ir::Callee::Subroutine(name) => name, }; let Some(subroutine) = self.m.subroutine(&name).cloned() else { @@ -864,6 +866,11 @@ impl<'p, 'a> Ff<'p, 'a> { args, .. } => self.scan_function(*function, args)?, + Expr::Call { + callee: sv::ir::Callee::String(op), + args, + .. + } => self.string_call(*op, args)?, Expr::Call { callee: sv::ir::Callee::System(sv::ir::SystemFunction::Fopen), args, @@ -997,6 +1004,8 @@ impl<'p, 'a> Ff<'p, 'a> { sv::ir::TypeKind::Shortreal => Some(celox_sir::FloatPrecision::F32), _ => None, }; + self.m.variables.get_mut(&temp).unwrap().string = + r#type.kind() == sv::ir::TypeKind::String; let Some(result) = result else { return Err(unsupported(format!( "void function `{name}` used as a value" @@ -2070,6 +2079,13 @@ impl<'p, 'a> Ff<'p, 'a> { ) -> Result<(), sv::AnalyzerError> { let lhs = self.propagate_lvalue(lhs); let lhs = self.hoist_lvalue(&lhs)?; + let converted = match self.m.id(lhs.name()) { + Some(id) if matches!(lhs, sv::ir::LValue::Ident(_)) => { + self.string_conversion(id, rhs.clone()) + } + _ => rhs.clone(), + }; + let rhs = &converted; let owned_rhs = if self.m.calls(rhs) { self.hoist(rhs)? } else { @@ -2832,6 +2848,7 @@ impl<'p, 'a> Ff<'p, 'a> { let mut arg_signed = Vec::with_capacity(values.len()); let mut arg_is_string = Vec::with_capacity(values.len()); let mut arg_float_precision = Vec::with_capacity(values.len()); + let mut arg_is_handle = Vec::with_capacity(values.len()); for value in &values { match value { sv::ir::SystemTaskArg::Expr(expr) => { @@ -2841,6 +2858,11 @@ impl<'p, 'a> Ff<'p, 'a> { expr.clone() }; let signed = self.expr_signed(&expr); + arg_is_handle.push(reads_string_variable( + &expr, + self.m.variables, + self.m.name_to_id, + )); arg_float_precision.push(floating::precision( &expr, self.m.variables, @@ -2864,6 +2886,7 @@ impl<'p, 'a> Ff<'p, 'a> { arg_signed.push(false); arg_is_string.push(true); arg_float_precision.push(None); + arg_is_handle.push(false); regs.push(reg); } sv::ir::SystemTaskArg::Empty => { @@ -2904,6 +2927,7 @@ impl<'p, 'a> Ff<'p, 'a> { arg_signed, arg_is_string, arg_float_precision, + arg_is_handle, }); self.b.emit(SIRInstruction::RuntimeEvent { site_id, @@ -3435,6 +3459,7 @@ impl<'p, 'a> Ff<'p, 'a> { param.source_name )) })?; + let actual = self.string_conversion(id, actual); let actual = if self.m.calls(&actual) { self.hoist(&actual)? } else { @@ -4586,6 +4611,7 @@ impl Ff<'_, '_> { source: None, hidden: true, force_control: None, + string: false, }, ); let mut renames = HashMap::default(); @@ -4811,6 +4837,8 @@ fn impure_call(pm: &ProcModule<'_>, expr: &sv::ir::Expr) -> Option { } continue; } + // A string operation is a value of its operands. + sv::ir::Callee::String(_) => continue, sv::ir::Callee::Subroutine(name) => name, }; if !visited.insert(name.clone()) { diff --git a/crates/celox-frontend-sv/src/lowering/ff/strings.rs b/crates/celox-frontend-sv/src/lowering/ff/strings.rs new file mode 100644 index 00000000000..48fdf000cb5 --- /dev/null +++ b/crates/celox-frontend-sv/src/lowering/ff/strings.rs @@ -0,0 +1,235 @@ +//! String operations (IEEE 1800-2023 6.16), lowered to calls of the heap +//! helper. +//! +//! A string value is a 32-bit heap handle. Each operation evaluates its +//! operands, calls the helper with a `celox_heap::ops` opcode, and leaves +//! its result in a temporary that the expression then reads. Operations +//! that build a string fill a heap buffer and intern it at the end. + +use super::*; +use celox_heap::ops; +use sv::ir::{Radix, StringOp}; + +impl Ff<'_, '_> { + /// The value of string operation `op`, as a temporary. + pub(super) fn string_call( + &mut self, + op: StringOp, + args: &[Option], + ) -> Result { + let args = args + .iter() + .map(|arg| { + arg.clone() + .ok_or_else(|| unsupported(format!("omitted argument of `{op}`"))) + }) + .collect::, _>>()?; + let result = match op { + StringOp::FromBits => { + let buffer = self.heap_call(ops::NEW, &[]); + let buffer = self.append_bits(buffer, &args[0])?; + self.heap_call(ops::FREEZE, &[buffer]) + } + StringOp::Concat => { + let mut buffer = self.heap_call(ops::NEW, &[]); + for arg in &args { + buffer = if self.m.expr_is_string(arg) { + let string = self.handle(arg)?; + self.heap_call(ops::APPEND, &[buffer, string]) + } else { + self.append_bits(buffer, arg)? + }; + } + self.heap_call(ops::FREEZE, &[buffer]) + } + StringOp::Replicate => { + let string = self.handle(&args[0])?; + let count = self.integer(&args[1], true)?; + let buffer = self.heap_call(ops::REPLICATE, &[string, count]); + self.heap_call(ops::FREEZE, &[buffer]) + } + StringOp::Compare | StringOp::ICompare => { + let left = self.handle(&args[0])?; + let right = self.handle(&args[1])?; + let code = if op == StringOp::Compare { + ops::COMPARE + } else { + ops::ICOMPARE + }; + self.heap_call(code, &[left, right]) + } + StringOp::Len => { + let string = self.handle(&args[0])?; + self.heap_call(ops::LEN, &[string]) + } + StringOp::Getc => { + let string = self.handle(&args[0])?; + let index = self.integer(&args[1], true)?; + self.heap_call(ops::GETC, &[string, index]) + } + StringOp::Putc => { + let string = self.handle(&args[0])?; + let index = self.integer(&args[1], true)?; + let character = self.integer(&args[2], false)?; + let buffer = self.heap_call(ops::COPY, &[string]); + let buffer = self.heap_call(ops::PUTC, &[buffer, index, character]); + self.heap_call(ops::FREEZE, &[buffer]) + } + StringOp::Substr => { + let string = self.handle(&args[0])?; + let first = self.integer(&args[1], true)?; + let last = self.integer(&args[2], true)?; + let buffer = self.heap_call(ops::SUBSTR, &[string, first, last]); + self.heap_call(ops::FREEZE, &[buffer]) + } + StringOp::ToUpper | StringOp::ToLower => { + let string = self.handle(&args[0])?; + let code = if op == StringOp::ToUpper { + ops::TO_UPPER + } else { + ops::TO_LOWER + }; + let buffer = self.heap_call(code, &[string]); + self.heap_call(ops::FREEZE, &[buffer]) + } + StringOp::Atoi(radix) => { + let string = self.handle(&args[0])?; + let parameter = ops::radix_parameter(radix_value(radix), 0, false); + self.heap_call(ops::encode(ops::ATOI, parameter), &[string]) + } + StringOp::Itoa(radix) => { + // The argument is an `integer` (6.16.11). + let value = self.integer_of_width(&args[0], 32, true)?; + let parameter = ops::radix_parameter(radix_value(radix), 32, true); + let buffer = self.heap_call(ops::encode(ops::ITOA, parameter), &[value]); + self.heap_call(ops::FREEZE, &[buffer]) + } + }; + let (width, signed) = op.result_type(); + let value = self.b.alloc_bit(width, false); + self.b.emit(SIRInstruction::Slice(value, result, 0, width)); + let (temp, name) = self.m.temp("string", width, signed, false); + self.m.variables.get_mut(&temp).unwrap().string = op.returns_string(); + self.store(temp, SIROffset::Static(0), width, value); + Ok(sv::ir::Expr::Ident(name)) + } + + /// `value` as the value of string variable `target`: an integral value + /// such as a string literal becomes its bytes (IEEE 1800-2023 6.16). + pub(super) fn string_conversion( + &self, + target: SourceVarId, + value: sv::ir::Expr, + ) -> sv::ir::Expr { + if self.m.var(target).string && !self.m.expr_is_string(&value) { + sv::ir::Expr::Call { + callee: sv::ir::Callee::String(StringOp::FromBits), + args: vec![Some(value)], + arg_order: Vec::new(), + } + } else { + value + } + } + + /// Call the heap helper with `code` and up to three operands; the result + /// is a 64-bit register. + fn heap_call(&mut self, code: u64, operands: &[RegisterId]) -> RegisterId { + let mut args = vec![self.constant64(code)]; + args.extend_from_slice(operands); + while args.len() < celox_sir::extern_abi::HEAP_HELPER_ARGUMENTS { + args.push(self.constant64(0)); + } + let dst = self.b.alloc_bit(64, false); + self.b.emit(SIRInstruction::ExternCall { + dst: Some(dst), + func: celox_sir::extern_abi::HEAP_HELPER_ID, + args, + }); + dst + } + + fn constant64(&mut self, value: u64) -> RegisterId { + let register = self.b.alloc_bit(64, false); + self.b.emit(SIRInstruction::Imm( + register, + SIRValue::new(BigUint::from(value)), + )); + register + } + + /// The handle of string `expr`, as a 64-bit operand. + fn handle(&mut self, expr: &sv::ir::Expr) -> Result { + self.integer_of_width(expr, celox_design::HANDLE_WIDTH, false) + } + + /// Integral `expr` as a 64-bit operand, sign-extended if `signed`. + fn integer( + &mut self, + expr: &sv::ir::Expr, + signed: bool, + ) -> Result { + self.integer_of_width(expr, 64, signed) + } + + /// `expr` converted to `width` bits, then extended to a 64-bit operand. + /// Unknown bits read as zero. + fn integer_of_width( + &mut self, + expr: &sv::ir::Expr, + width: usize, + signed: bool, + ) -> Result { + let expr = self.hoist(expr)?; + let value = self.eval(&expr, Some((width, signed)))?; + let known = self.b.alloc_bit(width, signed); + self.b + .emit(SIRInstruction::Unary(known, UnaryOp::ToTwoState, value)); + // An identity cast widens with the operand's signedness. + let operand = self.b.alloc_bit(64, false); + self.b + .emit(SIRInstruction::Unary(operand, UnaryOp::Ident, known)); + Ok(operand) + } + + /// `buffer` extended by the bytes of integral `expr`, most significant + /// first. + fn append_bits( + &mut self, + mut buffer: RegisterId, + expr: &sv::ir::Expr, + ) -> Result { + let expr = self.hoist(expr)?; + let natural = self.eval(&expr, None)?; + let width = self.b.register(&natural).width(); + let bytes = width.div_ceil(8); + let value = self.eval(&expr, Some((bytes * 8, false)))?; + let known = self.b.alloc_bit(bytes * 8, false); + self.b + .emit(SIRInstruction::Unary(known, UnaryOp::ToTwoState, value)); + let mut first = 0; + while first < bytes { + let count = (bytes - first).min(8); + let lsb = (bytes - first - count) * 8; + let chunk = self.b.alloc_bit(count * 8, false); + self.b + .emit(SIRInstruction::Slice(chunk, known, lsb, count * 8)); + let operand = self.b.alloc_bit(64, false); + self.b + .emit(SIRInstruction::Unary(operand, UnaryOp::Ident, chunk)); + let count_register = self.constant64(count as u64); + buffer = self.heap_call(ops::APPEND_BYTES, &[buffer, operand, count_register]); + first += count; + } + Ok(buffer) + } +} + +fn radix_value(radix: Radix) -> u32 { + match radix { + Radix::Binary => 2, + Radix::Octal => 8, + Radix::Decimal => 10, + Radix::Hexadecimal => 16, + } +} diff --git a/crates/celox-frontend-sv/src/lowering/procedural.rs b/crates/celox-frontend-sv/src/lowering/procedural.rs index 68eec7b2149..ab666eb9b0e 100644 --- a/crates/celox-frontend-sv/src/lowering/procedural.rs +++ b/crates/celox-frontend-sv/src/lowering/procedural.rs @@ -62,6 +62,37 @@ pub(super) struct MemoryWord { } impl<'a> ProcModule<'a> { + /// Whether `expr` has type `string`: a string variable, or an operation + /// or function that returns one. + pub fn expr_is_string(&self, expr: &sv::ir::Expr) -> bool { + match expr { + sv::ir::Expr::Ident(name) => self + .name_to_id + .get(name) + .and_then(|id| self.variables.get(id)) + .is_some_and(|variable| variable.string), + sv::ir::Expr::Call { + callee: sv::ir::Callee::String(op), + .. + } => op.returns_string(), + sv::ir::Expr::Call { + callee: sv::ir::Callee::Subroutine(name), + .. + } => self.subroutines.get(name).is_some_and(|subroutine| { + subroutine + .return_type + .as_ref() + .is_some_and(|ty| ty.kind() == sv::ir::TypeKind::String) + }), + sv::ir::Expr::Mux { + then_expr, + else_expr, + .. + } => self.expr_is_string(then_expr) || self.expr_is_string(else_expr), + _ => false, + } + } + pub fn expr_float_precision(&self, expr: &sv::ir::Expr) -> Option { use celox_sir::FloatPrecision as P; use sv::ir::{BinaryOp, Expr}; @@ -216,6 +247,8 @@ impl<'a> ProcModule<'a> { } continue; } + // String operations use the simulator's heap. + sv::ir::Callee::String(_) => return true, sv::ir::Callee::Subroutine(name) => name, }; if let Some(subroutine) = self.subroutine(&name) { @@ -645,6 +678,8 @@ impl<'a> ProcModule<'a> { id, SvVariable { float: None, + + string: false, path: vec![name.clone()], width: width.max(1), signed, @@ -713,6 +748,8 @@ impl<'a> ProcModule<'a> { } let variable = SvVariable { float: None, + + string: false, path, width: 1, signed: false, @@ -783,6 +820,7 @@ impl<'a> ProcModule<'a> { pub fn is_callee(&self, callee: &sv::ir::Callee) -> bool { match callee { sv::ir::Callee::System(function) => function.reads_simulation_state(), + sv::ir::Callee::String(_) => true, sv::ir::Callee::Subroutine(name) => { self.subroutines.contains_key(name) || self.dpi_imports.contains_key(name) } @@ -1119,11 +1157,12 @@ pub(super) fn system_task_template( { text.push_str("#g"); } else { - text.push(if matches!(value, sv::ir::SystemTaskArg::Str(_)) { - 's' - } else { - *radix - }); + let string = match value { + sv::ir::SystemTaskArg::Str(_) => true, + sv::ir::SystemTaskArg::Expr(expr) => module.expr_is_string(expr), + sv::ir::SystemTaskArg::Empty => false, + }; + text.push(if string { 's' } else { *radix }); } } template = Some(text); @@ -1172,6 +1211,8 @@ pub(super) fn register_locals( id, SvVariable { float: type_info.float, + + string: type_info.string, path: vec![local.source_name.clone()], width: type_info.width, signed: type_info.signed, diff --git a/crates/celox-frontend-veryl/src/lowering/ff.rs b/crates/celox-frontend-veryl/src/lowering/ff.rs index 490449601cb..f6a42d62974 100644 --- a/crates/celox-frontend-veryl/src/lowering/ff.rs +++ b/crates/celox-frontend-veryl/src/lowering/ff.rs @@ -568,6 +568,7 @@ impl<'a> FfParser<'a> { .iter() .map(|arg| arg.0.comptime().r#type.is_string()) .collect(), + arg_is_handle: Vec::new(), }; let id = self .runtime_event_site_base diff --git a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs index 56227bf5699..94cfa90963d 100644 --- a/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs +++ b/crates/celox-frontend-veryl/src/lowering/logic_tree/effect.rs @@ -116,6 +116,7 @@ fn register_comb_runtime_event_site<'a>( .iter() .map(|arg| arg.0.comptime().r#type.is_string()) .collect(), + arg_is_handle: Vec::new(), }; let id = collector.sites.len() as u32; collector.sites.push(site); diff --git a/crates/celox-frontend-veryl/src/testbench.rs b/crates/celox-frontend-veryl/src/testbench.rs index 11a0b377b6e..3f90788ba56 100644 --- a/crates/celox-frontend-veryl/src/testbench.rs +++ b/crates/celox-frontend-veryl/src/testbench.rs @@ -122,6 +122,7 @@ fn runtime_event_site_for_assert( .iter() .map(|arg| arg.0.comptime().r#type.is_string()) .collect(), + arg_is_handle: Vec::new(), } } diff --git a/crates/celox-heap/src/lib.rs b/crates/celox-heap/src/lib.rs index d52b3b146d9..8185824690a 100644 --- a/crates/celox-heap/src/lib.rs +++ b/crates/celox-heap/src/lib.rs @@ -7,12 +7,16 @@ //! //! References from state memory are not counted. A collection marks the //! entries reachable from the handles the caller passes as roots and frees -//! the rest; callers collect only where every copy of a handle is in a place -//! they can enumerate. +//! the rest; callers collect only where every copy of a handle that may still +//! be read is in a place they can enumerate. Handles are never reused, so a +//! stale copy that is only compared, such as the value a wait started from, +//! cannot equal a later string. use std::sync::Arc; -use fxhash::FxHashMap as HashMap; +use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; + +pub mod ops; /// A reference to a heap entry, as stored in state memory. pub type Handle = u32; @@ -30,11 +34,15 @@ const MIN_COLLECTION_INTERVAL: usize = 1024; /// Dynamic strings referenced by [`Handle`]. #[derive(Clone, Debug)] pub struct Heap { - strings: Vec>>, + strings: HashMap>, lookup: HashMap, Handle>, - free: Vec, + /// The handle the next string gets. + next: Handle, + /// Mutable strings under construction, see [`ops`]. + buffers: Vec>>, + free_buffers: Vec, /// Entries below this handle are never collected. - pinned: usize, + pinned: Handle, created: usize, live_after_collection: usize, } @@ -50,10 +58,14 @@ impl Heap { let empty: Arc<[u8]> = Arc::from(&[][..]); let mut lookup = HashMap::default(); lookup.insert(empty.clone(), EMPTY_STRING); + let mut strings = HashMap::default(); + strings.insert(EMPTY_STRING, empty); Self { - strings: vec![Some(empty)], + strings, lookup, - free: Vec::new(), + next: EMPTY_STRING + 1, + buffers: Vec::new(), + free_buffers: Vec::new(), pinned: 1, created: 0, live_after_collection: 1, @@ -76,18 +88,11 @@ impl Heap { return handle; } let value: Arc<[u8]> = Arc::from(bytes); - let handle = match self.free.pop() { - Some(handle) => { - self.strings[handle as usize] = Some(value.clone()); - handle - } - None => { - let handle = Handle::try_from(self.strings.len()) - .expect("the heap has more strings than handles can name"); - self.strings.push(Some(value.clone())); - handle - } - }; + let handle = self.next; + self.next = handle + .checked_add(1) + .expect("the heap created more strings than handles can name"); + self.strings.insert(handle, value.clone()); self.lookup.insert(value, handle); self.created += 1; handle @@ -96,22 +101,17 @@ impl Heap { /// The contents of `handle`. A handle that names no string reads as `""`, /// so a value written into a handle slot by the host cannot crash a read. pub fn string(&self, handle: Handle) -> &[u8] { - self.strings - .get(handle as usize) - .and_then(Option::as_deref) - .unwrap_or_default() + self.strings.get(&handle).map_or(&[], |value| value) } /// Whether `handle` names a live string. pub fn contains(&self, handle: Handle) -> bool { - self.strings - .get(handle as usize) - .is_some_and(Option::is_some) + self.strings.contains_key(&handle) } /// The number of live strings, including `""`. pub fn len(&self) -> usize { - self.strings.len() - self.free.len() + self.strings.len() } pub fn is_empty(&self) -> bool { @@ -120,7 +120,7 @@ impl Heap { /// Bytes of string contents, excluding allocator overhead. pub fn content_size(&self) -> usize { - self.strings.iter().flatten().map(|value| value.len()).sum() + self.strings.values().map(|value| value.len()).sum() } /// Whether enough entries were created since the last collection to make @@ -133,24 +133,48 @@ impl Heap { /// Free every unpinned entry that no handle in `roots` refers to. Roots /// that name no entry are ignored. pub fn collect(&mut self, roots: impl IntoIterator) { - let mut marked = vec![false; self.strings.len()]; - marked[..self.pinned].fill(true); - for root in roots { - if let Some(mark) = marked.get_mut(root as usize) { - *mark = true; + let marked: HashSet = roots.into_iter().collect(); + let pinned = self.pinned; + let lookup = &mut self.lookup; + self.strings.retain(|handle, value| { + let live = *handle < pinned || marked.contains(handle); + if !live { + lookup.remove(value); } - } - for (handle, live) in marked.into_iter().enumerate() { - if live { - continue; + live + }); + // No buffer outlives the kernel that built it. + self.buffers.clear(); + self.free_buffers.clear(); + self.created = 0; + self.live_after_collection = self.len(); + } + + fn new_buffer(&mut self, bytes: Vec) -> u64 { + match self.free_buffers.pop() { + Some(buffer) => { + self.buffers[buffer as usize] = Some(bytes); + buffer } - if let Some(value) = self.strings[handle].take() { - self.lookup.remove(&value); - self.free.push(handle as Handle); + None => { + self.buffers.push(Some(bytes)); + (self.buffers.len() - 1) as u64 } } - self.created = 0; - self.live_after_collection = self.len(); + } + + fn buffer(&mut self, buffer: u64) -> &mut Vec { + self.buffers + .get_mut(buffer as usize) + .and_then(Option::as_mut) + .unwrap_or_else(|| panic!("heap buffer {buffer} is not live")) + } + + fn take_buffer(&mut self, buffer: u64) -> Vec { + let bytes = std::mem::take(self.buffer(buffer)); + self.buffers[buffer as usize] = None; + self.free_buffers.push(buffer); + bytes } } @@ -185,7 +209,7 @@ mod tests { } #[test] - fn collection_frees_unreachable_strings_and_reuses_handles() { + fn collection_frees_unreachable_strings_without_reusing_handles() { let mut heap = Heap::new(); let kept = heap.intern(b"kept"); let dropped = heap.intern(b"dropped"); @@ -193,12 +217,12 @@ mod tests { assert_eq!(heap.string(kept), b"kept"); assert!(!heap.contains(dropped)); assert!(heap.contains(EMPTY_STRING)); - // A freed handle is reused, and its old contents are gone from the - // intern table. - let again = heap.intern(b"new"); - assert_eq!(again, dropped); - assert_eq!(heap.string(again), b"new"); - assert_ne!(heap.intern(b"dropped"), kept); + // A later string never takes a freed handle, and the freed contents + // are gone from the intern table. + let again = heap.intern(b"dropped"); + assert_ne!(again, dropped); + assert_eq!(heap.string(again), b"dropped"); + assert_eq!(heap.string(dropped), b""); } #[test] diff --git a/crates/celox-heap/src/ops.rs b/crates/celox-heap/src/ops.rs new file mode 100644 index 00000000000..80097bb14b0 --- /dev/null +++ b/crates/celox-heap/src/ops.rs @@ -0,0 +1,302 @@ +//! Heap operations that compiled code calls through one helper. +//! +//! An operation takes an opcode word and up to three 64-bit arguments and +//! returns a 64-bit result, so every backend calls it like a C function. The +//! low byte of the opcode word selects the operation; higher bits carry its +//! immediate parameters. +//! +//! String arguments are [`Handle`]s of interned strings. Operations that +//! build a string return a buffer: a mutable string outside the intern table +//! that later operations extend in place and [`FREEZE`] interns. A buffer is +//! consumed by the operation it is passed to, and none outlives the kernel +//! that created it, so a collection discards every buffer. + +use crate::{Handle, Heap}; + +/// `compare(a, b)`: -1, 0 or 1 as `strcmp` orders strings `a` and `b`. +pub const COMPARE: u64 = 0; +/// `icompare(a, b)`: [`COMPARE`] ignoring ASCII case. +pub const ICOMPARE: u64 = 1; +/// `len(a)`: the length of string `a` in bytes. +pub const LEN: u64 = 2; +/// `getc(a, i)`: byte `i` of string `a`, or 0 out of range. `i` is signed. +pub const GETC: u64 = 3; +/// `atoi(a)`: the leading digits of string `a` in the radix of the +/// parameter, as a 32-bit integer. +pub const ATOI: u64 = 4; +/// `new()`: an empty buffer. +pub const NEW: u64 = 16; +/// `copy(a)`: a buffer holding string `a`. +pub const COPY: u64 = 17; +/// `append(buffer, a)`: `buffer` extended by string `a`. +pub const APPEND: u64 = 18; +/// `append_bytes(buffer, value, count)`: `buffer` extended by the low `count` +/// bytes of `value`, most significant first. `count` is at most 8. +pub const APPEND_BYTES: u64 = 19; +/// `putc(buffer, i, c)`: `buffer` with byte `i` replaced by `c`, unless `i` +/// is out of range or `c` is 0. `i` is signed. +pub const PUTC: u64 = 20; +/// `substr(a, i, j)`: a buffer with bytes `i..=j` of string `a`, or empty if +/// `i < 0`, `j < i` or `j >= len`. `i` and `j` are signed. +pub const SUBSTR: u64 = 21; +/// `toupper(a)`: a buffer with string `a` in ASCII upper case. +pub const TO_UPPER: u64 = 22; +/// `tolower(a)`: a buffer with string `a` in ASCII lower case. +pub const TO_LOWER: u64 = 23; +/// `replicate(a, n)`: a buffer with `n` copies of string `a`. +pub const REPLICATE: u64 = 24; +/// `itoa(value)`: a buffer with `value` in the radix of the parameter. +pub const ITOA: u64 = 25; +/// `freeze(buffer)`: the interned string holding `buffer`, which is freed. +pub const FREEZE: u64 = 32; + +/// The opcode word of `op` with parameter `parameter`. +pub const fn encode(op: u64, parameter: u64) -> u64 { + op | parameter << 8 +} + +/// The parameter of [`ATOI`] and [`ITOA`]: the radix, and for [`ITOA`] the +/// width of `value` in bits and whether it is signed. +pub const fn radix_parameter(radix: u32, width: u32, signed: bool) -> u64 { + radix as u64 | (width as u64) << 8 | (signed as u64) << 16 +} + +/// The most copies [`REPLICATE`] makes, so a runaway count fails loudly +/// instead of exhausting memory. +const MAX_REPLICATE_BYTES: usize = 1 << 30; + +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 { + let parameter = code >> 8; + match code & 0xff { + COMPARE => ordering(self.string(a as Handle).cmp(self.string(b as Handle))), + ICOMPARE => { + let lower = |handle| { + self.string(handle as Handle) + .iter() + .map(u8::to_ascii_lowercase) + }; + ordering(lower(a).cmp(lower(b))) + } + LEN => self.string(a as Handle).len() as u64, + GETC => usize::try_from(b as i64) + .ok() + .and_then(|index| self.string(a as Handle).get(index)) + .map_or(0, |&byte| byte.into()), + ATOI => atoi(self.string(a as Handle), parameter as u32 & 0xff), + NEW => self.new_buffer(Vec::new()), + COPY => self.new_buffer(self.string(a as Handle).to_vec()), + APPEND => { + let tail = self.string(b as Handle).to_vec(); + self.buffer(a).extend_from_slice(&tail); + a + } + APPEND_BYTES => { + let count = (c as usize).min(8); + let bytes = b.to_be_bytes(); + self.buffer(a).extend_from_slice(&bytes[8 - count..]); + a + } + PUTC => { + let buffer = self.buffer(a); + if let Ok(index) = usize::try_from(b as i64) + && c as u8 != 0 + && let Some(byte) = buffer.get_mut(index) + { + *byte = c as u8; + } + a + } + SUBSTR => { + let string = self.string(a as Handle); + let (i, j) = (b as i64, c as i64); + let bytes = if i < 0 || j < i || j >= string.len() as i64 { + Vec::new() + } else { + string[i as usize..=j as usize].to_vec() + }; + self.new_buffer(bytes) + } + TO_UPPER => self.new_buffer(self.string(a as Handle).to_ascii_uppercase()), + TO_LOWER => self.new_buffer(self.string(a as Handle).to_ascii_lowercase()), + REPLICATE => { + let string = self.string(a as Handle); + let count = usize::try_from(b as i64).unwrap_or(0); + assert!( + string.len().saturating_mul(count) <= MAX_REPLICATE_BYTES, + "string replication of {} bytes {count} times is too large", + string.len() + ); + self.new_buffer(string.repeat(count)) + } + ITOA => self.new_buffer(itoa( + a, + parameter as u32 & 0xff, + (parameter >> 8) as u32 & 0xff, + parameter >> 16 & 1 != 0, + )), + FREEZE => { + let bytes = self.take_buffer(a); + self.intern(&bytes).into() + } + other => panic!("unknown heap operation {other}"), + } + } +} + +fn ordering(order: std::cmp::Ordering) -> u64 { + order as i64 as u64 +} + +/// IEEE 1800-2023 6.16.9: leading digits and underscores, wrapping to 32 bits. +fn atoi(string: &[u8], radix: u32) -> u64 { + let mut value: u32 = 0; + for &byte in string { + if byte == b'_' { + continue; + } + let Some(digit) = char::from(byte).to_digit(radix) else { + break; + }; + value = value.wrapping_mul(radix).wrapping_add(digit); + } + value.into() +} + +/// `value`, the low `width` bits of which are significant, in `radix`. +fn itoa(value: u64, radix: u32, width: u32, signed: bool) -> Vec { + let width = width.clamp(1, 64); + let unsigned = if width == 64 { + value + } else { + value & ((1 << width) - 1) + }; + let negative = signed && radix == 10 && unsigned >> (width - 1) & 1 != 0; + let mut magnitude = if negative { + // Two's complement magnitude of the sign-extended value. + (unsigned | !0 << (width - 1)).wrapping_neg() + } else { + unsigned + }; + let mut digits = Vec::new(); + loop { + let digit = (magnitude % u64::from(radix)) as u32; + digits.push(char::from_digit(digit, radix).unwrap() as u8); + magnitude /= u64::from(radix); + if magnitude == 0 { + break; + } + } + if negative { + digits.push(b'-'); + } + digits.reverse(); + digits +} + +#[cfg(test)] +mod tests { + use super::*; + + fn string(heap: &mut Heap, text: &str) -> u64 { + heap.intern(text.as_bytes()).into() + } + + fn frozen(heap: &mut Heap, buffer: u64) -> Vec { + let handle = heap.call(FREEZE, buffer, 0, 0); + heap.string(handle as Handle).to_vec() + } + + #[test] + fn comparisons_order_like_strcmp() { + let mut heap = Heap::new(); + let (abc, abd, upper) = ( + string(&mut heap, "abc"), + string(&mut heap, "abd"), + string(&mut heap, "ABC"), + ); + assert_eq!(heap.call(COMPARE, abc, abd, 0) as i64, -1); + assert_eq!(heap.call(COMPARE, abd, abc, 0) as i64, 1); + assert_eq!(heap.call(COMPARE, abc, abc, 0), 0); + assert_eq!(heap.call(COMPARE, 0, abc, 0) as i64, -1); + assert_eq!(heap.call(ICOMPARE, abc, upper, 0), 0); + } + + #[test] + fn character_access_ignores_out_of_range_indices() { + let mut heap = Heap::new(); + let abc = string(&mut heap, "abc"); + assert_eq!(heap.call(LEN, abc, 0, 0), 3); + assert_eq!(heap.call(GETC, abc, 1, 0), u64::from(b'b')); + assert_eq!(heap.call(GETC, abc, 3, 0), 0); + assert_eq!(heap.call(GETC, abc, -1i64 as u64, 0), 0); + let buffer = heap.call(COPY, abc, 0, 0); + let buffer = heap.call(PUTC, buffer, 0, u64::from(b'x')); + let buffer = heap.call(PUTC, buffer, 1, 0); + let buffer = heap.call(PUTC, buffer, 3, u64::from(b'y')); + assert_eq!(frozen(&mut heap, buffer), b"xbc"); + } + + #[test] + fn substrings_follow_the_lrm_bounds() { + let mut heap = Heap::new(); + let text = string(&mut heap, "hello"); + let cases = [ + (1, 3, "ell"), + (0, 4, "hello"), + (-1, 2, ""), + (3, 2, ""), + (2, 5, ""), + ]; + for (i, j, expected) in cases { + let buffer = heap.call(SUBSTR, text, i as u64, j as u64); + assert_eq!(frozen(&mut heap, buffer), expected.as_bytes(), "{i}..={j}"); + } + } + + #[test] + fn buffers_build_concatenations_and_replications() { + let mut heap = Heap::new(); + let (a, b) = (string(&mut heap, "ab"), string(&mut heap, "cd")); + let buffer = heap.call(COPY, a, 0, 0); + let buffer = heap.call(APPEND, buffer, b, 0); + let buffer = heap.call(APPEND_BYTES, buffer, 0x0065_6667, 3); + let joined = heap.call(FREEZE, buffer, 0, 0); + assert_eq!(heap.string(joined as Handle), b"abcdefg"); + // A literal assembled from bytes interns to the same handle. + let buffer = heap.call(NEW, 0, 0, 0); + let buffer = heap.call(APPEND_BYTES, buffer, u64::from_be_bytes(*b"\0abcdefg"), 7); + assert_eq!(heap.call(FREEZE, buffer, 0, 0), joined); + let buffer = heap.call(REPLICATE, a, 3, 0); + assert_eq!(frozen(&mut heap, buffer), b"ababab"); + let buffer = heap.call(TO_UPPER, a, 0, 0); + assert_eq!(frozen(&mut heap, buffer), b"AB"); + } + + #[test] + fn numeric_conversions_follow_the_lrm() { + let mut heap = Heap::new(); + let atoi_of = |heap: &mut Heap, text: &str, radix| { + let handle = string(heap, text); + heap.call(encode(ATOI, radix_parameter(radix, 0, false)), handle, 0, 0) + }; + assert_eq!(atoi_of(&mut heap, "1_234x5", 10), 1234); + assert_eq!(atoi_of(&mut heap, "-12", 10), 0); + assert_eq!(atoi_of(&mut heap, "fF", 16), 255); + assert_eq!(atoi_of(&mut heap, "4294967297", 10), 1); + let itoa_of = |heap: &mut Heap, value: i64, radix, width, signed| { + let code = encode(ITOA, radix_parameter(radix, width, signed)); + let buffer = heap.call(code, value as u64, 0, 0); + String::from_utf8(frozen(heap, buffer)).unwrap() + }; + assert_eq!(itoa_of(&mut heap, -42, 10, 32, true), "-42"); + assert_eq!(itoa_of(&mut heap, -1, 10, 32, false), "4294967295"); + assert_eq!(itoa_of(&mut heap, -1, 16, 32, true), "ffffffff"); + assert_eq!(itoa_of(&mut heap, 0, 2, 32, true), "0"); + assert_eq!( + itoa_of(&mut heap, i64::MIN, 10, 64, true), + "-9223372036854775808" + ); + } +} diff --git a/crates/celox-runtime/Cargo.toml b/crates/celox-runtime/Cargo.toml index 31f3ec4226b..501dd774136 100644 --- a/crates/celox-runtime/Cargo.toml +++ b/crates/celox-runtime/Cargo.toml @@ -11,6 +11,7 @@ rust-version.workspace = true [dependencies] celox-design = { workspace = true } +celox-heap = { workspace = true } celox-state-layout = { workspace = true } celox-testbench = { workspace = true } bit-set = { workspace = true } diff --git a/crates/celox-runtime/src/backend.rs b/crates/celox-runtime/src/backend.rs index fa03abdd57a..be3477e7562 100644 --- a/crates/celox-runtime/src/backend.rs +++ b/crates/celox-runtime/src/backend.rs @@ -139,6 +139,10 @@ pub trait SimBackend { fn set_comb_capture_event_enabled(&mut self, _active_sites: &[bool]) {} fn stable_region_size(&self) -> usize; fn layout(&self) -> &MemoryLayout; + /// The heap that handle slots in this backend's state refer to. + fn heap(&self) -> &celox_heap::Heap; + /// The heap, for changes made while no compiled code runs. + fn heap_mut(&mut self) -> &mut celox_heap::Heap; // ── event enumeration ─────────────────────────────────────── fn id_to_addr_slice(&self) -> &[AbsoluteAddr]; diff --git a/crates/celox-sir/src/extern_abi.rs b/crates/celox-sir/src/extern_abi.rs index 9e958255e8f..8956d1f4b86 100644 --- a/crates/celox-sir/src/extern_abi.rs +++ b/crates/celox-sir/src/extern_abi.rs @@ -8,6 +8,18 @@ use crate::RegisterType; +/// The `func` of an extern call to the heap helper. +/// +/// Its four arguments are an opcode word and three operands of a +/// `celox_heap::ops` operation. Unlike a user function, backends pass the +/// state pointer before them, and the helper finds the simulator's heap +/// through the state header. The helper's address sits two slots before the +/// user extern function table. +pub const HEAP_HELPER_ID: u32 = u32::MAX - 1; + +/// The number of arguments of an extern call to [`HEAP_HELPER_ID`]. +pub const HEAP_HELPER_ARGUMENTS: usize = 4; + /// The bit of an `svLogic` that holds the mask: `value | mask << 1`. pub const SV_LOGIC_MASK_SHIFT: u32 = 1; diff --git a/crates/celox-sir/src/verify.rs b/crates/celox-sir/src/verify.rs index 8e2515d2b23..b5d4acd8c0d 100644 --- a/crates/celox-sir/src/verify.rs +++ b/crates/celox-sir/src/verify.rs @@ -631,7 +631,21 @@ fn verify_instruction_types( SIRInstruction::CombCaptureEnableIfChanged { old, new, .. } => { same_width(*old, *new, "TYPE.CAPTURE_COMPARE_OPERANDS")?; } - SIRInstruction::ExternCall { dst, args, .. } => { + SIRInstruction::ExternCall { dst, func, args } => { + if *func == crate::extern_abi::HEAP_HELPER_ID + && args.len() != crate::extern_abi::HEAP_HELPER_ARGUMENTS + { + return Err(SirVerifyError::instruction( + "TYPE.HEAP_CALL_ARGUMENT_COUNT", + block, + index, + format!( + "a heap call takes {} arguments, not {}", + crate::extern_abi::HEAP_HELPER_ARGUMENTS, + args.len() + ), + )); + } if args.len() > crate::MAX_EXTERN_CALL_ARGUMENTS { return Err(SirVerifyError::instruction( "TYPE.EXTERN_CALL_ARGUMENT_COUNT", diff --git a/crates/celox-state-layout/src/lib.rs b/crates/celox-state-layout/src/lib.rs index 7cb9b3b63a3..ff2fbef6463 100644 --- a/crates/celox-state-layout/src/lib.rs +++ b/crates/celox-state-layout/src/lib.rs @@ -16,7 +16,7 @@ pub use trace::{TRACE_GROUP_BYTES, TraceLayout}; pub const RUNTIME_EVENT_CAPACITY: usize = 1024; pub const RUNTIME_EVENT_WRITING: u64 = u64::MAX; -pub const STATE_HEADER_SIZE: usize = 40; +pub const STATE_HEADER_SIZE: usize = 48; pub const STATE_HEADER_RUNTIME_EVENT_ADDR_OFFSET: usize = 0; /// Remaining iterations for an in-function native tick loop. #[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))] @@ -27,6 +27,8 @@ pub const STATE_HEADER_NATIVE_LOOP_EVENT_SEQ_OFFSET: usize = 24; pub const STATE_HEADER_COMB_CAPTURE_ENABLED_ADDR_OFFSET: usize = 16; /// Address of the table of extern function pointers called by `ExternCall`. pub const STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET: usize = 32; +/// Address of the simulator's heap, which the heap helper operates on. +pub const STATE_HEADER_HEAP_ADDR_OFFSET: usize = 40; /// Runtime-event write sequence observed when a native tick batch starts. pub const RUNTIME_EVENT_HEADER_SIZE: usize = 8; pub const RUNTIME_EVENT_SLOT_SEQ_OFFSET: usize = 0; @@ -1018,7 +1020,8 @@ mod tests { STATE_HEADER_NATIVE_LOOP_EVENT_SEQ_OFFSET + 8 <= STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET ); - assert!(STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET + 8 <= STATE_HEADER_SIZE); + assert!(STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET + 8 <= STATE_HEADER_HEAP_ADDR_OFFSET); + assert!(STATE_HEADER_HEAP_ADDR_OFFSET + 8 <= STATE_HEADER_SIZE); } } } diff --git a/crates/celox-sv-analyzer/src/ast.rs b/crates/celox-sv-analyzer/src/ast.rs index ae0157581ec..cf131498124 100644 --- a/crates/celox-sv-analyzer/src/ast.rs +++ b/crates/celox-sv-analyzer/src/ast.rs @@ -90,7 +90,7 @@ impl Deref for AnalysisContext<'_> { } } -pub use crate::system_functions::{ArrayQuery, Callee, SystemFunction, SystemTask}; +pub use crate::system_functions::{ArrayQuery, Callee, StringOp, SystemFunction, SystemTask}; use crate::{AnalyzerError, system_functions, typecheck}; mod array_compatibility; @@ -1934,6 +1934,8 @@ impl Type { pub enum TypeKind { Real, Shortreal, + /// IEEE 1800-2023 6.16: a dynamically sized string, held as a heap handle. + String, Bit, Logic, Reg, @@ -2362,6 +2364,8 @@ impl ConditionalAssignment { #[derive(Debug, Clone, PartialEq, Eq)] struct Function { return_real: bool, + /// Whether the function returns a `string`. + return_string: bool, name: String, params: Vec, /// The function's value as one expression of its arguments, or `None` @@ -2602,6 +2606,8 @@ struct UnpackedDimension { struct VariableDimensions { randomizable: bool, real: bool, + /// A `string`: each element is a heap handle, not packed bits. + string: bool, packed: Vec, unpacked: Vec, signed: bool, diff --git a/crates/celox-sv-analyzer/src/ast/array_compatibility.rs b/crates/celox-sv-analyzer/src/ast/array_compatibility.rs index 97333bf8978..ad2ce5624af 100644 --- a/crates/celox-sv-analyzer/src/ast/array_compatibility.rs +++ b/crates/celox-sv-analyzer/src/ast/array_compatibility.rs @@ -52,6 +52,7 @@ pub(super) fn selected_unpacked_shape( .filter(|rest| !rest.is_empty())?; Some(VariableDimensions { real: false, + string: false, unpacked: unpacked.to_vec(), ..shape.clone() }) diff --git a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs index c2bfcb3f450..94f167ee27b 100644 --- a/crates/celox-sv-analyzer/src/ast/bound_patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/bound_patterns.rs @@ -141,6 +141,7 @@ impl Value { .ok_or_else(|| unsupported("pattern target array size"))?; let shape = VariableDimensions { real: false, + string: false, unpacked: rest.to_vec(), ..shape.clone() }; @@ -191,6 +192,7 @@ impl BoundPattern { shapes = vec![ VariableDimensions { real: false, + string: false, unpacked: rest.to_vec(), ..shape.clone() }; @@ -230,6 +232,7 @@ impl BoundPattern { shapes = vec![ VariableDimensions { real: false, + string: false, packed: rest.to_vec(), signed: shape.signed_element_depth == Some(1), signed_element_depth: shape @@ -255,6 +258,7 @@ impl BoundPattern { shapes = vec![ VariableDimensions { real: false, + string: false, packed: Vec::new(), signed: false, signed_element_depth: None, diff --git a/crates/celox-sv-analyzer/src/ast/case.rs b/crates/celox-sv-analyzer/src/ast/case.rs index 1ec8ce1677e..b5cfa3255c1 100644 --- a/crates/celox-sv-analyzer/src/ast/case.rs +++ b/crates/celox-sv-analyzer/src/ast/case.rs @@ -60,6 +60,10 @@ pub(super) fn expr_is_two_state( callee: Callee::System(function), .. } => function.result_type().is_some(), + Expr::Call { + callee: Callee::String(op), + .. + } => !matches!(op, crate::system_functions::StringOp::Atoi(_)), Expr::Call { callee: Callee::Subroutine(name), .. diff --git a/crates/celox-sv-analyzer/src/ast/casts.rs b/crates/celox-sv-analyzer/src/ast/casts.rs index 5158f7e926a..d502d991290 100644 --- a/crates/celox-sv-analyzer/src/ast/casts.rs +++ b/crates/celox-sv-analyzer/src/ast/casts.rs @@ -29,6 +29,8 @@ pub(super) enum RuntimeCastTarget { Real { short: bool, }, + /// `string'(x)` (IEEE 1800-2023 6.24.1). + String, Zero(ExprType), Signing(bool), Integral { @@ -53,6 +55,9 @@ pub(super) fn runtime_cast_target_expr( ) -> Converted { let const_env = &packed_dimensions.const_env; let (target, numeric_size, two_state) = match target { + RuntimeCastTarget::String => { + return Ok(expression_binding::string_operand(expr, packed_dimensions)); + } RuntimeCastTarget::Real { short } => { let call = |function, value| Expr::Call { callee: Callee::System(function), @@ -163,7 +168,9 @@ pub(super) fn cast_constant_target( .. } => (target.width, numeric_size || target.signed), RuntimeCastTarget::Zero(target) => (target.width, target.signed), - RuntimeCastTarget::Signing(_) | RuntimeCastTarget::Real { .. } => return None, + RuntimeCastTarget::Signing(_) + | RuntimeCastTarget::Real { .. } + | RuntimeCastTarget::String => return None, }; if width == 0 || width > 128 { return None; @@ -211,7 +218,7 @@ pub(super) fn cast_constant_target( })? }; let (target_type, numeric_size, two_state) = match target { - RuntimeCastTarget::Real { .. } => return None, + RuntimeCastTarget::Real { .. } | RuntimeCastTarget::String => return None, RuntimeCastTarget::Signing(signed) => ( ExprType { width: literal.width, diff --git a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs index cdc60296bdd..e5310d1e48b 100644 --- a/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs +++ b/crates/celox-sv-analyzer/src/ast/comb_rewrite.rs @@ -99,6 +99,10 @@ pub(super) fn expr_static_width( callee: Callee::System(function), .. } => function.result_type().map(|(width, _)| width), + Expr::Call { + callee: Callee::String(op), + .. + } => Some(op.result_type().0), Expr::Call { callee: Callee::Subroutine(name), .. diff --git a/crates/celox-sv-analyzer/src/ast/const_functions.rs b/crates/celox-sv-analyzer/src/ast/const_functions.rs index 9216fbbc5d2..8d31d1bdda6 100644 --- a/crates/celox-sv-analyzer/src/ast/const_functions.rs +++ b/crates/celox-sv-analyzer/src/ast/const_functions.rs @@ -610,7 +610,7 @@ fn simulation_state_readers(functions: &[Subroutine]) -> HashMap { reads.get_or_insert(*system); } - Callee::System(_) => {} + Callee::System(_) | Callee::String(_) => {} Callee::Subroutine(callee) => calls.push(callee.as_str()), } } diff --git a/crates/celox-sv-analyzer/src/ast/dimensions.rs b/crates/celox-sv-analyzer/src/ast/dimensions.rs index 4427db6f394..80f2c03c262 100644 --- a/crates/celox-sv-analyzer/src/ast/dimensions.rs +++ b/crates/celox-sv-analyzer/src/ast/dimensions.rs @@ -133,12 +133,13 @@ pub(super) fn packed_dimensions_from_ports_and_signals( VariableDimensions { randomizable: !port.r#type().is_enum && port.randomizable, real: matches!(port.r#type().kind(), TypeKind::Real | TypeKind::Shortreal), + string: matches!(port.r#type().kind(), TypeKind::String), packed: signal_packed_dimension_widths(port.r#type().packed_ranges()), unpacked: unpacked_dimension_widths(port.r#type().unpacked_ranges()), signed: port.r#type().is_signed(), is_2state: matches!( port.r#type().kind(), - TypeKind::Bit | TypeKind::Real | TypeKind::Shortreal + TypeKind::Bit | TypeKind::Real | TypeKind::Shortreal | TypeKind::String ), members: port.r#type().members.clone(), signed_element_depth: port.r#type().signed_element_depth, @@ -151,12 +152,13 @@ pub(super) fn packed_dimensions_from_ports_and_signals( VariableDimensions { randomizable: !signal.r#type().is_enum && !signal.is_net() && !signal.is_const, real: matches!(signal.r#type().kind(), TypeKind::Real | TypeKind::Shortreal), + string: matches!(signal.r#type().kind(), TypeKind::String), packed: signal_packed_dimension_widths(signal.r#type().packed_ranges()), unpacked: unpacked_dimension_widths(signal.r#type().unpacked_ranges()), signed: signal.r#type().is_signed(), is_2state: matches!( signal.r#type().kind(), - TypeKind::Bit | TypeKind::Real | TypeKind::Shortreal + TypeKind::Bit | TypeKind::Real | TypeKind::Shortreal | TypeKind::String ), members: signal.r#type().members.clone(), signed_element_depth: signal.r#type().signed_element_depth, @@ -519,6 +521,7 @@ pub(super) fn parameter_packed_dimensions(parameters: &[Parameter]) -> VariableP VariableDimensions { randomizable: true, real: false, + string: false, packed: function_packed_dimension_widths(¶meter.packed_ranges), unpacked: Vec::new(), signed: parameter.declared_signed.unwrap_or(false), diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding.rs b/crates/celox-sv-analyzer/src/ast/expression_binding.rs index 87a9c131b7b..87798b461f4 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding.rs @@ -6,12 +6,16 @@ mod direct; mod lvalues; #[cfg(test)] mod selected; +mod strings; pub(super) use calls::{statement as call_statement, statement_root as call_statement_root}; pub(super) use direct::{ arguments, bind_value, call_name as native_name, callable_name, cast_target_native, real_value, remove_real_division_guards, ungroup, }; pub(super) use lvalues::{net_lvalue, variable_lvalue}; +pub(super) use strings::{ + call as string_call, method as string_method, native_string, to_string as string_operand, +}; fn disagreement() -> AnalyzerError { AnalyzerError::Parse("invalid native expression ownership".into()) } @@ -33,7 +37,14 @@ pub(super) fn expression( LValue::Ident(name) => dimensions.get(name), _ => None, }; - bind_value(root, native, tree, dimensions, shape) + let value = bind_value(root, native, tree, dimensions, shape)?; + // A string literal or integral value assigned to a string becomes its + // bytes (IEEE 1800-2023 6.16). + Ok(if shape.is_some_and(|shape| shape.string) { + string_operand(value, dimensions) + } else { + value + }) } pub(super) fn value( root: ExprId, diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs index 22a1180b48f..d91a27319b0 100644 --- a/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/direct.rs @@ -135,6 +135,11 @@ pub(in crate::ast) fn cast_target_native( dimensions: &PackedDimensions, ) -> Converted { let target = ungroup(target, native); + if let ExprKind::Type(id) = native.expression(target).kind + && matches!(&native.data_type(id).kind, celox_sv_syntax::DataTypeKind::Builtin(name) if name == "string") + { + return Ok(casts::RuntimeCastTarget::String); + } if let ExprKind::Type(id) = native.expression(target).kind && let Some(ty) = type_binding::binding::bind_in(id, native, tree, dimensions)? && matches!(ty.kind(), TypeKind::Real | TypeKind::Shortreal) @@ -225,6 +230,8 @@ enum Finish { Cast(casts::RuntimeCastTarget), Repeat, Inside(Vec), + /// A string operation on the bound children, see [`strings`]. + StringCall(StringOp), } enum Job { @@ -374,6 +381,34 @@ pub(in crate::ast) fn bind_value( )?), vec![(*expression, None)], ), + ExprKind::Call { + expression, + arguments: args, + } if strings::method(*expression, native, dimensions).is_some() => { + let (op, base) = strings::method(*expression, native, dimensions) + .expect("checked by the guard"); + if op.updates_receiver() { + return Err(unsupported(format!( + "string method `{op}` used as a value" + ))); + } + let (_, count) = StringOp::method(&op.to_string()).expect("a method name"); + let values = args + .iter() + .map(|arg| arg.value.filter(|_| arg.name.is_none())) + .collect::>>() + .filter(|values| values.len() == count) + .ok_or_else(|| { + unsupported(format!("arguments of string method `{op}`")) + })?; + ( + Finish::StringCall(op), + std::iter::once(base) + .chain(values) + .map(|id| (id, None)) + .collect(), + ) + } ExprKind::Call { expression, arguments: args, @@ -608,6 +643,18 @@ pub(in crate::ast) fn bind_value( Vec::new(), ) } + ExprKind::Select { + expression, + dimension, + } if strings::native_string(*expression, native, dimensions) => { + let celox_sv_syntax::DimensionKind::Index(index) = dimension.kind else { + return Err(unsupported("part-select of a string")); + }; + ( + Finish::StringCall(StringOp::Getc), + vec![(*expression, None), (index, None)], + ) + } ExprKind::Member { .. } | ExprKind::Select { .. } => { values.push(selected_value(id, native, tree, dimensions)?); continue; @@ -678,6 +725,11 @@ pub(in crate::ast) fn bind_value( let value = match finish { Finish::Unary(op) => { let operand = operands.pop().ok_or_else(disagreement)?; + if strings::string_value(&operand, dimensions) { + return Err(unsupported(format!( + "operator `{op}` on a string operand" + ))); + } if real_value(&operand, dimensions) && !matches!(op.as_str(), "+" | "-" | "!") { @@ -689,6 +741,12 @@ pub(in crate::ast) fn bind_value( Finish::Binary(op) => { let right = operands.pop().ok_or_else(disagreement)?; let left = operands.pop().ok_or_else(disagreement)?; + if strings::string_value(&left, dimensions) + || strings::string_value(&right, dimensions) + { + values.push(strings::binary(&op, left, right, dimensions)?); + continue; + } if (real_value(&left, dimensions) || real_value(&right, dimensions)) && !matches!( op.as_str(), @@ -735,16 +793,32 @@ pub(in crate::ast) fn bind_value( Expr::Literal(ty.width.to_string()) } Finish::Mux => { - let else_expr = operands.pop().ok_or_else(disagreement)?; - let then_expr = operands.pop().ok_or_else(disagreement)?; + let mut else_expr = operands.pop().ok_or_else(disagreement)?; + let mut then_expr = operands.pop().ok_or_else(disagreement)?; let condition = operands.pop().ok_or_else(disagreement)?; + if strings::string_value(&then_expr, dimensions) + || strings::string_value(&else_expr, dimensions) + { + then_expr = strings::to_string(then_expr, dimensions); + else_expr = strings::to_string(else_expr, dimensions); + } Expr::Mux { condition: Box::new(condition), then_expr: Box::new(then_expr), else_expr: Box::new(else_expr), } } + Finish::Concat + if operands + .iter() + .any(|operand| strings::string_value(operand, dimensions)) => + { + strings::call(StringOp::Concat, operands) + } Finish::Concat => Expr::Concat(operands), + Finish::StringCall(op) => { + strings::call(op, strings::operands(op, operands, dimensions)) + } Finish::Cast(target) => { let operand = remove_real_division_guards( guard_zero_divisions( @@ -775,6 +849,21 @@ pub(in crate::ast) fn bind_value( )? } } + Finish::Repeat + if operands[1..] + .iter() + .any(|operand| strings::string_value(operand, dimensions)) => + { + // A string replication count need not be constant + // (11.4.12.2). + let count = operands.remove(0); + let string = if operands.len() == 1 { + strings::to_string(operands.remove(0), dimensions) + } else { + strings::call(StringOp::Concat, operands) + }; + strings::call(StringOp::Replicate, vec![string, count]) + } Finish::Repeat => { let count = operands.remove(0); let count = expr_to_const(&tree.state, count.clone()) diff --git a/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs b/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs new file mode 100644 index 00000000000..101a8b4b0ab --- /dev/null +++ b/crates/celox-sv-analyzer/src/ast/expression_binding/strings.rs @@ -0,0 +1,152 @@ +//! `string` operands (IEEE 1800-2023 6.16). +//! +//! A string variable holds a heap handle, so the integral operators would +//! act on handles. Expressions with a string operand are rewritten into +//! [`Callee::String`] calls instead, which the frontend lowers to heap +//! operations. Equality stays an integral comparison of handles: equal +//! strings have equal handles. + +use super::*; + +/// Whether `expr` has type `string`. +pub(in crate::ast) fn string_value(expr: &Expr, dimensions: &PackedDimensions) -> bool { + match expr { + Expr::Ident(name) => dimensions.get(name).is_some_and(|ty| ty.string), + Expr::Call { + callee: Callee::String(op), + .. + } => op.returns_string(), + Expr::Call { + callee: Callee::Subroutine(name), + .. + } => dimensions + .functions + .get(name) + .is_some_and(|function| function.return_string), + Expr::Mux { + then_expr, + else_expr, + .. + } => string_value(then_expr, dimensions) || string_value(else_expr, dimensions), + _ => false, + } +} + +/// A call of string operation `op`. +pub(in crate::ast) fn call(op: StringOp, args: Vec) -> Expr { + Expr::Call { + callee: Callee::String(op), + args: args.into_iter().map(Some).collect(), + arg_order: Vec::new(), + } +} + +/// `expr` as a string: a string unchanged, or the bytes of an integral +/// value, as a string literal or a cast to `string` gives them. +pub(in crate::ast) fn to_string(expr: Expr, dimensions: &PackedDimensions) -> Expr { + if string_value(&expr, dimensions) { + expr + } else { + call(StringOp::FromBits, vec![expr]) + } +} + +/// A binary operator with a string operand (11.4.4, 11.4.5, Table 6-9). +pub(in crate::ast) fn binary( + op: &str, + left: Expr, + right: Expr, + dimensions: &PackedDimensions, +) -> Converted { + let left = to_string(left, dimensions); + let right = to_string(right, dimensions); + let compare = |op| Expr::Binary { + left: Box::new(call(StringOp::Compare, vec![left.clone(), right.clone()])), + op, + right: Box::new(Expr::Literal("0".into())), + }; + Ok(match op { + "==" | "===" => Expr::Binary { + left: Box::new(left), + op: BinaryOp::Eq, + right: Box::new(right), + }, + "!=" | "!==" => Expr::Binary { + left: Box::new(left), + op: BinaryOp::Ne, + right: Box::new(right), + }, + "<" => compare(BinaryOp::Lt), + "<=" => compare(BinaryOp::Le), + ">" => compare(BinaryOp::Gt), + ">=" => compare(BinaryOp::Ge), + _ => return Err(unsupported(format!("operator `{op}` on a string operand"))), + }) +} + +/// The arguments of string operation `op` after binding: the operands it +/// reads as strings are converted to strings. +pub(in crate::ast) fn operands( + op: StringOp, + operands: Vec, + dimensions: &PackedDimensions, +) -> Vec { + let strings = match op { + StringOp::FromBits | StringOp::Itoa(_) => 0, + StringOp::Concat => usize::MAX, + StringOp::Compare | StringOp::ICompare => 2, + _ => 1, + }; + operands + .into_iter() + .enumerate() + .map(|(index, operand)| { + // A concatenation converts each integral operand to its bytes. + if index < strings { + to_string(operand, dimensions) + } else { + operand + } + }) + .collect() +} + +/// Whether native expression `id` has type `string`, judged before it is +/// bound: a string variable, or a method of a string value that returns one. +pub(in crate::ast) fn native_string( + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> bool { + match &native.expression(ungroup(id, native)).kind { + ExprKind::Name(name) => dimensions + .get(&instances::normalize_identifier(&name.spelling)) + .is_some_and(|ty| ty.string), + ExprKind::Call { expression, .. } => { + method(*expression, native, dimensions).is_some_and(|(op, _)| op.returns_string()) + } + _ => false, + } +} + +/// The string method that native callee expression `id` names, with the +/// expression it is called on. +pub(in crate::ast) fn method( + id: ExprId, + native: &Declarations, + dimensions: &PackedDimensions, +) -> Option<(StringOp, ExprId)> { + let ExprKind::Member { + expression, + separator, + name, + } = &native.expression(ungroup(id, native)).kind + else { + return None; + }; + if separator != "." || !native_string(*expression, native, dimensions) { + return None; + } + let (op, _) = StringOp::method(&name.spelling)?; + Some((op, *expression)) +} diff --git a/crates/celox-sv-analyzer/src/ast/functions.rs b/crates/celox-sv-analyzer/src/ast/functions.rs index ba3ca88c3c2..9fd06946100 100644 --- a/crates/celox-sv-analyzer/src/ast/functions.rs +++ b/crates/celox-sv-analyzer/src/ast/functions.rs @@ -247,6 +247,7 @@ fn native_signature( return_real: ty .as_ref() .is_some_and(|ty| matches!(ty.kind(), TypeKind::Real | TypeKind::Shortreal)), + return_string: ty.as_ref().is_some_and(|ty| ty.kind() == TypeKind::String), name: instances::normalize_identifier(&native.name.spelling), params, body: None, diff --git a/crates/celox-sv-analyzer/src/ast/inlining.rs b/crates/celox-sv-analyzer/src/ast/inlining.rs index a3ffacb93da..418ab612044 100644 --- a/crates/celox-sv-analyzer/src/ast/inlining.rs +++ b/crates/celox-sv-analyzer/src/ast/inlining.rs @@ -105,6 +105,10 @@ pub(super) fn expr_signedness_with_return_types( callee: Callee::System(function), .. } => function.result_type().map(|(_, signed)| signed), + Expr::Call { + callee: Callee::String(op), + .. + } => Some(op.result_type().1), Expr::Call { callee: Callee::Subroutine(name), .. diff --git a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs index cb08b492dc7..4839d928e56 100644 --- a/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs +++ b/crates/celox-sv-analyzer/src/ast/packed_structs/selects.rs @@ -58,6 +58,7 @@ fn member_dimensions(name: &str, r#type: &Type, dimensions: &PackedDimensions) - VariableDimensions { randomizable: true, real: false, + string: false, packed: function_packed_dimension_widths(&r#type.packed_ranges), unpacked: Vec::new(), signed: r#type.is_signed, diff --git a/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs b/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs index c52377b5ca4..08bf3f49f05 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/declaration_types.rs @@ -23,6 +23,9 @@ pub(super) fn prefix<'a>( let data = tree.declarations().data_type(data_type); let (alias, primitive) = match &data.kind { DataTypeKind::Implicit => (None, None), + // A string parameter is a constant, which keeps the packed value of + // its literal like an untyped one (IEEE 1800-2023 6.20.2). + DataTypeKind::Builtin(name) if name == "string" => (None, None), DataTypeKind::Builtin(name) => ( None, Some( diff --git a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs index eabfe9df54a..65a8d898fc9 100644 --- a/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs +++ b/crates/celox-sv-analyzer/src/ast/parameters/skipped.rs @@ -279,7 +279,9 @@ pub(in crate::ast) fn validate( let width = match cast { casts::RuntimeCastTarget::Integral { target, .. } | casts::RuntimeCastTarget::Zero(target) => Some(target.width), - casts::RuntimeCastTarget::Signing(_) => None, + casts::RuntimeCastTarget::Signing(_) | casts::RuntimeCastTarget::String => { + None + } casts::RuntimeCastTarget::Real { short } => { Some(if short { 32 } else { 64 }) } @@ -463,6 +465,7 @@ fn pattern_items( left.max(right), VariableDimensions { real: false, + string: false, unpacked: rest.to_vec(), ..shape.clone() }, @@ -484,6 +487,7 @@ fn pattern_items( left.max(right), VariableDimensions { real: false, + string: false, packed: rest.to_vec(), ..shape.clone() }, @@ -497,6 +501,7 @@ fn pattern_items( VariableDimensions { randomizable: true, real: false, + string: false, packed: Vec::new(), unpacked: Vec::new(), members: Vec::new(), diff --git a/crates/celox-sv-analyzer/src/ast/patterns.rs b/crates/celox-sv-analyzer/src/ast/patterns.rs index a6fe8ab168f..f6dffb8f3d8 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns.rs @@ -65,6 +65,7 @@ fn pattern_value( let (_, _, count) = dimension_bounds(state, &dimension.left, &dimension.right, dims)?; let element = VariableDimensions { real: false, + string: false, unpacked: rest.to_vec(), ..shape.clone() }; diff --git a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs index 4dd43345df1..4a07987a791 100644 --- a/crates/celox-sv-analyzer/src/ast/patterns/binding.rs +++ b/crates/celox-sv-analyzer/src/ast/patterns/binding.rs @@ -106,6 +106,7 @@ fn select<'a>( let (left, right, count) = dimension_bounds(state, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { real: false, + string: false, unpacked: rest.to_vec(), ..(*shape).clone() })); @@ -206,6 +207,7 @@ fn select<'a>( let sub = Shape::Owned(Rc::new(VariableDimensions { randomizable: true, real: false, + string: false, packed: rest.to_vec(), unpacked: Vec::new(), signed: shape.signed_element_depth == Some(1), @@ -241,6 +243,7 @@ fn select<'a>( let bit = Shape::Owned(Rc::new(VariableDimensions { randomizable: true, real: false, + string: false, packed: Vec::new(), unpacked: Vec::new(), signed: false, @@ -382,6 +385,7 @@ pub(in crate::ast) fn bind_native( let (_, _, count) = dimension_bounds(&tree.state, &dim.left, &dim.right, dims)?; let sub = Shape::Owned(Rc::new(VariableDimensions { real: false, + string: false, unpacked: rest.to_vec(), ..(*shape).clone() })); diff --git a/crates/celox-sv-analyzer/src/ast/procedural.rs b/crates/celox-sv-analyzer/src/ast/procedural.rs index d7143eee62b..f89edc1b21d 100644 --- a/crates/celox-sv-analyzer/src/ast/procedural.rs +++ b/crates/celox-sv-analyzer/src/ast/procedural.rs @@ -70,12 +70,13 @@ pub(super) fn dimensions_from_type(r#type: &Type) -> VariableDimensions { VariableDimensions { randomizable: !r#type.is_enum, real: matches!(r#type.kind(), TypeKind::Real | TypeKind::Shortreal), + string: matches!(r#type.kind(), TypeKind::String), packed: dimensions::signal_packed_dimension_widths(r#type.packed_ranges()), unpacked: unpacked_dimension_widths(r#type.unpacked_ranges()), signed: r#type.is_signed(), is_2state: matches!( r#type.kind(), - TypeKind::Bit | TypeKind::Real | TypeKind::Shortreal + TypeKind::Bit | TypeKind::Real | TypeKind::Shortreal | TypeKind::String ), members: r#type.members.clone(), signed_element_depth: r#type.signed_element_depth, @@ -465,7 +466,15 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { &self.dims, )?; } + if let Some(stmt) = self.string_character_assignment(op, nonblocking, left, right)? { + return Ok(stmt); + } let (written, lhs) = self.native_lvalue(left)?; + if op != "=" + && expression_binding::native_string(left, self.tree.declarations(), &self.dims) + { + return Err(unsupported(format!("operator `{op}` on a string"))); + } let mut rhs = if op == "=" { expression_binding::expression( right, @@ -497,6 +506,73 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { }) } + /// `str[i] = c`, which replaces one character like `str.putc(i, c)` + /// (IEEE 1800-2023 6.16.2). + fn string_character_assignment( + &self, + op: &str, + nonblocking: bool, + left: celox_sv_syntax::ExprId, + right: celox_sv_syntax::ExprId, + ) -> Result, AnalyzerError> { + let native = self.tree.declarations(); + let celox_sv_syntax::ExprKind::Select { + expression, + dimension, + } = &native + .expression(expression_binding::ungroup(left, native)) + .kind + else { + return Ok(None); + }; + if !expression_binding::native_string(*expression, native, &self.dims) { + return Ok(None); + } + let celox_sv_syntax::DimensionKind::Index(index) = dimension.kind else { + return Err(unsupported("part-select of a string")); + }; + if op != "=" { + return Err(unsupported(format!( + "operator `{op}` on a string character" + ))); + } + let index = expression_binding::value(index, native, self.tree, &self.dims)?; + let character = expression_binding::value(right, native, self.tree, &self.dims)?; + self.string_update( + *expression, + StringOp::Putc, + vec![index, character], + nonblocking, + ) + .map(Some) + } + + /// `string = op(string, args)`: a method that updates the string it is + /// called on. + fn string_update( + &self, + string: celox_sv_syntax::ExprId, + op: StringOp, + args: Vec, + nonblocking: bool, + ) -> Result { + let (written, lhs) = self.native_lvalue(string)?; + let LValue::Ident(name) = &written else { + return Err(unsupported(format!( + "string method `{op}` on an array element" + ))); + }; + let receiver = (op == StringOp::Putc).then(|| Expr::Ident(name.clone())); + let mut rhs = + expression_binding::string_call(op, receiver.into_iter().chain(args).collect()); + self.rename_expr(&mut rhs); + Ok(Stmt::Assign { + lhs, + rhs, + nonblocking, + }) + } + fn inc_or_dec(&self, root: celox_sv_syntax::ExprId) -> Result { let celox_sv_syntax::ExprKind::Unary { operator, @@ -750,6 +826,33 @@ impl<'s, 't, 'a> BodyBuilder<'s, 't, 'a> { &mut self, root: celox_sv_syntax::ExprId, ) -> Result, AnalyzerError> { + let native = self.tree.declarations(); + if let celox_sv_syntax::ExprKind::Call { + expression, + arguments, + } = &native + .expression(expression_binding::ungroup(root, native)) + .kind + && let Some((op, string)) = + expression_binding::string_method(*expression, native, &self.dims) + { + let (_, count) = StringOp::method(&op.to_string()).expect("a method name"); + let args = arguments + .iter() + .map(|arg| arg.value.filter(|_| arg.name.is_none())) + .collect::>>() + .filter(|args| args.len() == count) + .ok_or_else(|| unsupported(format!("arguments of string method `{op}`")))? + .into_iter() + .map(|arg| expression_binding::value(arg, native, self.tree, &self.dims)) + .collect::, _>>()?; + // A method that returns a value has no effect as a statement. + return if op.updates_receiver() { + Ok(vec![self.string_update(string, op, args, false)?]) + } else { + Ok(Vec::new()) + }; + } let discarded = matches!( self.tree.declarations().expression(root).kind, celox_sv_syntax::ExprKind::Cast { .. } diff --git a/crates/celox-sv-analyzer/src/ast/type_binding.rs b/crates/celox-sv-analyzer/src/ast/type_binding.rs index e61f1390b46..eb8fb0acd63 100644 --- a/crates/celox-sv-analyzer/src/ast/type_binding.rs +++ b/crates/celox-sv-analyzer/src/ast/type_binding.rs @@ -231,6 +231,8 @@ pub(super) fn builtin_type(name: &str, signing: Option) -> Option { let (kind, width, signed) = match name { "real" | "realtime" => (TypeKind::Real, Some(64), true), "shortreal" => (TypeKind::Shortreal, Some(32), true), + // A heap handle; see `celox_design::HANDLE_WIDTH`. + "string" => (TypeKind::String, Some(32), false), "bit" => (TypeKind::Bit, None, false), "logic" => (TypeKind::Logic, None, false), "reg" => (TypeKind::Reg, None, false), diff --git a/crates/celox-sv-analyzer/src/ir.rs b/crates/celox-sv-analyzer/src/ir.rs index 8dd8ac14472..75bbc02b0c7 100644 --- a/crates/celox-sv-analyzer/src/ir.rs +++ b/crates/celox-sv-analyzer/src/ir.rs @@ -7,7 +7,8 @@ pub use crate::procedural::{ CaseKind, CaseLabel, EventEdge, LoopKind, ParamDirection, SourceSpan, StmtBase, SystemTaskArg, }; pub use crate::system_functions::{ - ArrayQuery, Callee, MemoryFormat, Radix, Severity, SystemFunction, SystemTask, VcdTask, + ArrayQuery, Callee, MemoryFormat, Radix, Severity, StringOp, SystemFunction, SystemTask, + VcdTask, }; /// A procedural statement of the analyzed IR. @@ -652,6 +653,8 @@ impl Type { pub enum TypeKind { Real, Shortreal, + /// IEEE 1800-2023 6.16: a dynamically sized string, held as a heap handle. + String, Bit, Logic, Reg, @@ -715,6 +718,7 @@ impl From for TypeKind { match kind { ast::TypeKind::Real => TypeKind::Real, ast::TypeKind::Shortreal => TypeKind::Shortreal, + ast::TypeKind::String => TypeKind::String, ast::TypeKind::Bit => TypeKind::Bit, ast::TypeKind::Logic => TypeKind::Logic, ast::TypeKind::Reg => TypeKind::Reg, diff --git a/crates/celox-sv-analyzer/src/system_functions.rs b/crates/celox-sv-analyzer/src/system_functions.rs index 80f13c40ff6..504c9854eb5 100644 --- a/crates/celox-sv-analyzer/src/system_functions.rs +++ b/crates/celox-sv-analyzer/src/system_functions.rs @@ -498,12 +498,134 @@ impl fmt::Display for SystemTask { } } +/// An operation on `string` values (IEEE 1800-2023 6.16, 11.4). +/// +/// The analyzer rewrites string operators, methods and conversions into +/// calls of these, so the frontend dispatches on them instead of on the +/// integral operators that a string handle would otherwise reach. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum StringOp { + /// A string holding the bytes of an integral operand, most significant + /// first, without NUL bytes: a cast to `string` (6.24.1), or a string + /// literal or integral value assigned to a string. + FromBits, + /// `{a, b, ...}` (11.4.12.2). Integral operands contribute their bytes. + Concat, + /// `{n{s}}` (11.4.12.2), with the arguments `s` and `n`. + Replicate, + /// `str.compare(s)` (6.16.6), and the ordering of relational operators. + Compare, + /// `str.icompare(s)` (6.16.7). + ICompare, + /// `str.len()` (6.16.1). + Len, + /// `str.getc(i)` and `str[i]` (6.16.3). + Getc, + /// `str.putc(i, c)` and `str[i] = c` (6.16.2), as the updated string. + Putc, + /// `str.substr(i, j)` (6.16.8). + Substr, + /// `str.toupper()` (6.16.4). + ToUpper, + /// `str.tolower()` (6.16.5). + ToLower, + /// `str.atoi()` and its radix variants (6.16.9). + Atoi(Radix), + /// `str.itoa(i)` and its radix variants (6.16.11-14), as the new string. + Itoa(Radix), +} + +impl StringOp { + /// Whether the result is a string rather than an integral value. + pub fn returns_string(self) -> bool { + matches!( + self, + Self::FromBits + | Self::Concat + | Self::Replicate + | Self::Putc + | Self::Substr + | Self::ToUpper + | Self::ToLower + | Self::Itoa(_) + ) + } + + /// The width and signedness of the result; a string is a 32-bit handle. + pub fn result_type(self) -> (usize, bool) { + match self { + Self::Compare | Self::ICompare | Self::Len | Self::Atoi(_) => (32, true), + Self::Getc => (8, false), + _ => (32, false), + } + } + + /// The method a call names on a string value, and its number of + /// arguments. + pub fn method(name: &str) -> Option<(Self, usize)> { + Some(match name { + "len" => (Self::Len, 0), + "getc" => (Self::Getc, 1), + "putc" => (Self::Putc, 2), + "toupper" => (Self::ToUpper, 0), + "tolower" => (Self::ToLower, 0), + "compare" => (Self::Compare, 1), + "icompare" => (Self::ICompare, 1), + "substr" => (Self::Substr, 2), + "atoi" => (Self::Atoi(Radix::Decimal), 0), + "atohex" => (Self::Atoi(Radix::Hexadecimal), 0), + "atooct" => (Self::Atoi(Radix::Octal), 0), + "atobin" => (Self::Atoi(Radix::Binary), 0), + "itoa" => (Self::Itoa(Radix::Decimal), 1), + "hextoa" => (Self::Itoa(Radix::Hexadecimal), 1), + "octtoa" => (Self::Itoa(Radix::Octal), 1), + "bintoa" => (Self::Itoa(Radix::Binary), 1), + _ => return None, + }) + } + + /// Whether the method updates the string it is called on instead of + /// returning a value (`putc` and the `itoa` family). + pub fn updates_receiver(self) -> bool { + matches!(self, Self::Putc | Self::Itoa(_)) + } +} + +impl fmt::Display for StringOp { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let name = match self { + Self::FromBits => "string cast", + Self::Concat => "string concatenation", + Self::Replicate => "string replication", + Self::Compare => "compare", + Self::ICompare => "icompare", + Self::Len => "len", + Self::Getc => "getc", + Self::Putc => "putc", + Self::Substr => "substr", + Self::ToUpper => "toupper", + Self::ToLower => "tolower", + Self::Atoi(Radix::Decimal) => "atoi", + Self::Atoi(Radix::Hexadecimal) => "atohex", + Self::Atoi(Radix::Octal) => "atooct", + Self::Atoi(Radix::Binary) => "atobin", + Self::Itoa(Radix::Decimal) => "itoa", + Self::Itoa(Radix::Hexadecimal) => "hextoa", + Self::Itoa(Radix::Octal) => "octtoa", + Self::Itoa(Radix::Binary) => "bintoa", + }; + f.write_str(name) + } +} + /// The subroutine a call expression calls. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum Callee { /// A user function or a DPI import, by its resolved name. Subroutine(String), System(SystemFunction), + /// A string operation, see [`StringOp`]. + String(StringOp), } impl Callee { @@ -511,14 +633,14 @@ impl Callee { pub fn subroutine(&self) -> Option<&str> { match self { Self::Subroutine(name) => Some(name), - Self::System(_) => None, + Self::System(_) | Self::String(_) => None, } } /// The system function, if this is one. pub fn system(&self) -> Option { match self { - Self::Subroutine(_) => None, + Self::Subroutine(_) | Self::String(_) => None, Self::System(function) => Some(*function), } } @@ -526,7 +648,10 @@ impl Callee { /// The width and signedness of a call of a system function that is /// lowered as an integral operation; see [`SystemFunction::result_type`]. pub fn result_type(&self) -> Option<(usize, bool)> { - self.system()?.result_type() + match self { + Self::String(op) => Some(op.result_type()), + _ => self.system()?.result_type(), + } } /// Rename a user subroutine with `rename`. @@ -534,6 +659,7 @@ impl Callee { match self { Self::Subroutine(name) => Self::Subroutine(rename(name)), Self::System(function) => Self::System(function), + Self::String(op) => Self::String(op), } } @@ -550,6 +676,7 @@ impl fmt::Display for Callee { match self { Self::Subroutine(name) => f.write_str(name), Self::System(function) => f.write_str(function.name()), + Self::String(op) => op.fmt(f), } } } diff --git a/crates/celox-sv-analyzer/src/typecheck.rs b/crates/celox-sv-analyzer/src/typecheck.rs index ae2df0d402f..cdbd0ae14e7 100644 --- a/crates/celox-sv-analyzer/src/typecheck.rs +++ b/crates/celox-sv-analyzer/src/typecheck.rs @@ -199,6 +199,7 @@ pub(crate) fn eval_const_expr_in_env( crate::ast::const_functions::eval_call(name, args, constants) } Callee::System(function) => eval_system_function(*function, args, constants), + Callee::String(_) => None, }, ConstExpr::Unary { op, expr: operand } => { if let Some(result) = integral_literal_from_const_expr(expr) diff --git a/crates/celox-test-suite/LIMITATIONS.md b/crates/celox-test-suite/LIMITATIONS.md index 20c306de17f..0324915b5fc 100644 --- a/crates/celox-test-suite/LIMITATIONS.md +++ b/crates/celox-test-suite/LIMITATIONS.md @@ -459,6 +459,7 @@ four-state expectations; the assertions remain enabled on all Celox variants. | `sv_icarus_interface_array_connections` | compile | icarus | 3 | Icarus 13.0 rejects distributed unpacked actuals and multidimensional instances, and aborts on interface array ports. See the focused interface-array evidence above. | | `sv_icarus_interfaces` | compile | icarus | 15 | Icarus 13.0 rejects interface port declarations (syntax error in port declarations), modport function imports ("sorry: modport task/function ports are not yet supported") and multidimensional interface instance arrays ("sorry: Multi-dimensional arrays of instances are not yet supported"). Verilator passes these cases. The implicit named interface cases have [focused pre-exclusion evidence](verification/sv/limitations/implicit-interface-ports-icarus.json). The mixed module-contract/local-interface case retains its [port-declaration diagnostics](verification/repros/sv_mixed_interface_connections_icarus.json). | | `sv_icarus_packed_inner_index_range` | execute | icarus | 1 | Icarus 13.0 flattens an out-of-range inner index of a multidimensional packed array into the neighbouring element: a read gives a known value instead of X, and a write lands in that element; IEEE 1800-2023 7.4.6 and 11.5.1 make the select out of range. Verilator cannot check four-state values, and it truncates out-of-range packed indices. | +| `sv_icarus_string_methods` | compile | icarus | 3 | Icarus 13.0 does not implement the string methods getc, putc, compare, icompare, toupper, tolower, substr, atoi/atohex/atooct/atobin and itoa/hextoa/octtoa/bintoa ("Method getc is not a string method"), and requires a constant replication count for a string ("A reference to a net or variable is not allowed in a constant expression"). IEEE 1800-2023 6.16 defines the methods and 11.4.12.2 permits a non-constant count for a string replication. Verilator passes the cases. | | `sv_icarus_unpacked_subroutine_ports` | compile | icarus | 2 | Icarus 13.0 reports that subroutine ports with unpacked dimensions are not yet supported. Verilator passes the valid case. | | `sv_icarus_unpacked_array_patterns` | compile | icarus | 1 | Icarus 13.0 reports that an assignment pattern with unpacked array items assigned to a multidimensional unpacked array is not yet supported ("Procedural assignment of array or array slice"), so the run cannot count it as a language rejection. The design is invalid (IEEE 1800-2023 7.6, 10.8). | | `sv_icarus_display_field_width` | execute | icarus | 1 | Icarus 13.0 zero-pads a value wider than an explicit field width of %h or %o to the argument's full width (%3h of 32'h1234 prints 00001234); IEEE 1800-2023 21.2.1.2 expands the field to the value without leading zeros (1234). Verilator agrees with the expected value. | diff --git a/crates/celox-test-suite/src/sv/cases/mod.rs b/crates/celox-test-suite/src/sv/cases/mod.rs index 6e73b02bedf..44c5b90d678 100644 --- a/crates/celox-test-suite/src/sv/cases/mod.rs +++ b/crates/celox-test-suite/src/sv/cases/mod.rs @@ -27,6 +27,10 @@ pub(super) const GROUPS: &[Group] = &[ file: "src/sv/cases/distributions.vtest", text: include_str!("distributions.vtest"), }, + Group { + file: "src/sv/cases/string.vtest", + text: include_str!("string.vtest"), + }, Group { file: "src/sv/cases/random_plusargs.vtest", text: include_str!("random_plusargs.vtest"), diff --git a/crates/celox-test-suite/src/sv/cases/string.vtest b/crates/celox-test-suite/src/sv/cases/string.vtest new file mode 100644 index 00000000000..b784c73f0de --- /dev/null +++ b/crates/celox-test-suite/src/sv/cases/string.vtest @@ -0,0 +1,173 @@ +(group string (category types)) + +(case assignment_and_display + (source "string.sv" #" +module Top(output bit done); + string s, t, empty; + initial begin + s = "hello"; + t = s; + s = "bye"; + $display("s=[%s] t=[%s] empty=[%s]", s, t, empty); + $display(t); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "s=[bye] t=[hello] empty=[]\nhello\n")) + +(case comparisons + (source "string.sv" #" +module Top(output bit [7:0] flags); + string a, b; + initial begin + a = "apple"; + b = "banana"; + flags = {a == b, a != b, a < b, a <= b, a > b, a >= b, a == "apple", "apple" == a}; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq flags 0x73)) + +(case concatenation_and_replication + (source "string.sv" #" +module Top(output bit done); + string a, b, joined, twice; + int n; + initial begin + a = "ab"; + b = "cd"; + joined = {a, "-", b}; + n = 3; + twice = {n{a}}; + $display("joined=[%s] repeated=[%s] len=%0d", joined, twice, joined.len()); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "joined=[ab-cd] repeated=[ababab] len=5\n")) + +(case character_access + (source "string.sv" #" +module Top(output bit [7:0] first, out_of_range, output bit done); + string s; + initial begin + s = "cat"; + first = s[0]; + out_of_range = s.getc(3); + s[0] = "b"; + s.putc(2, "r"); + s[1] = 0; + $display("s=[%s]", s); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (assert_eq first 0x63) (assert_eq out_of_range 0) + (expect_output "s=[bar]\n")) + +(case methods + (source "string.sv" #" +module Top(output bit done); + string s, sub; + int cmp, icmp, value, hex; + initial begin + s = "Hello World"; + sub = s.substr(6, 10); + cmp = s.compare("Hello"); + icmp = s.icompare("HELLO WORLD"); + $display("upper=[%s] lower=[%s] sub=[%s] cmp=%0d icmp=%0d bad=[%s]", + s.toupper(), s.tolower(), sub, cmp > 0, icmp, s.substr(5, 2)); + s = "12_34x"; + value = s.atoi(); + s = "fF"; + hex = s.atohex(); + $display("atoi=%0d atohex=%0d", value, hex); + s.itoa(-42); + $display("itoa=[%s]", s); + s.hextoa(255); + $display("hextoa=[%s]", s); + s.bintoa(5); + $display("bintoa=[%s]", s); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "upper=[HELLO WORLD] lower=[hello world] sub=[World] cmp=1 icmp=0 bad=[]\natoi=1234 atohex=255\nitoa=[-42]\nhextoa=[ff]\nbintoa=[101]\n")) + +(case casts_from_integral_values + (source "string.sv" #" +module Top(output bit done); + string s; + bit [31:0] word; + initial begin + word = 32'h00414243; + s = string'(word); + $display("cast=[%s] len=%0d", s, s.len()); + s = "x\0y"; + $display("nul=[%s] len=%0d", s, s.len()); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) + (expect_output "cast=[ABC] len=3\nnul=[xy] len=2\n")) + +(case strings_across_clock_edges + (source "string.sv" #" +module Top(output int count); + string history; + logic clk = 0; + always #5 clk = ~clk; + initial history = ""; + always @(posedge clk) begin + history = {history, "x"}; + count = history.len(); + $display("[%s]", history); + end +endmodule +"#) + (top Top) + (run_until 30) + (assert_eq count 3) + (expect_output "[x]\n[xx]\n[xxx]\n")) + +(case strings_survive_heap_collections + (source "string.sv" #" +module Top(output int n); + logic clk = 0; + always #1 clk = ~clk; + string kept, last; + initial kept = {"ke", "pt"}; + always @(posedge clk) begin + last.itoa(n); + last = {"value ", last}; + n = n + 1; + end + initial #6000 $display("[%s] [%s] %0d", kept, last, n); +endmodule +"#) + (top Top) + (run_until 6000) + (expect_output "[kept] [value 2999] 3000\n")) + +(case string_parameters_keep_their_text + (source "string.sv" #" +module Top(output bit same, output bit done); + localparam string NAME = "a longer name"; + localparam string SHORT = "ab"; + string copy; + initial begin + copy = NAME; + same = NAME == "a longer name"; + $display("[%s] [%s] [%s] %0d", NAME, SHORT, copy, copy.len()); + done = 1; + end +endmodule +"#) + (top Top) (run_until 0) (assert_eq done 1) (assert_eq same 1) + (expect_output "[a longer name] [ab] [a longer name] 13\n")) diff --git a/crates/celox-test-suite/verification/sv/icarus.json b/crates/celox-test-suite/verification/sv/icarus.json index c92647951db..66f057ba71e 100644 --- a/crates/celox-test-suite/verification/sv/icarus.json +++ b/crates/celox-test-suite/verification/sv/icarus.json @@ -12,6 +12,7 @@ "icarus/procedural.json", "icarus/random_plusargs.json", "icarus/review_regressions.json", + "icarus/string.json", "icarus/synthesizable.json", "icarus/system_functions.json", "icarus/timing.json", diff --git a/crates/celox-test-suite/verification/sv/icarus/string.json b/crates/celox-test-suite/verification/sv/icarus/string.json new file mode 100644 index 00000000000..6960ae9cd9e --- /dev/null +++ b/crates/celox-test-suite/verification/sv/icarus/string.json @@ -0,0 +1,139 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::assignment_and_display", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::casts_from_integral_values", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not implement the string methods getc, putc, compare, icompare, toupper, tolower, substr, atoi/atohex/atooct/atobin and itoa/hextoa/octtoa/bintoa (\"Method getc is not a string method\"), and requires a constant replication count for a string (\"A reference to a net or variable is not allowed in a constant expression\"). IEEE 1800-2023 6.16 defines the methods and 11.4.12.2 permits a non-constant count for a string replication. Verilator passes the cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_string_methods", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not implement the string methods getc, putc, compare, icompare, toupper, tolower, substr, atoi/atohex/atooct/atobin and itoa/hextoa/octtoa/bintoa (\"Method getc is not a string method\"), and requires a constant replication count for a string (\"A reference to a net or variable is not allowed in a constant expression\"). IEEE 1800-2023 6.16 defines the methods and 11.4.12.2 permits a non-constant count for a string replication. Verilator passes the cases.", + "upstream": [] + }, + "name": "string::character_access", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::comparisons", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not implement the string methods getc, putc, compare, icompare, toupper, tolower, substr, atoi/atohex/atooct/atobin and itoa/hextoa/octtoa/bintoa (\"Method getc is not a string method\"), and requires a constant replication count for a string (\"A reference to a net or variable is not allowed in a constant expression\"). IEEE 1800-2023 6.16 defines the methods and 11.4.12.2 permits a non-constant count for a string replication. Verilator passes the cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_string_methods", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not implement the string methods getc, putc, compare, icompare, toupper, tolower, substr, atoi/atohex/atooct/atobin and itoa/hextoa/octtoa/bintoa (\"Method getc is not a string method\"), and requires a constant replication count for a string (\"A reference to a net or variable is not allowed in a constant expression\"). IEEE 1800-2023 6.16 defines the methods and 11.4.12.2 permits a non-constant count for a string replication. Verilator passes the cases.", + "upstream": [] + }, + "name": "string::concatenation_and_replication", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "Icarus 13.0 does not implement the string methods getc, putc, compare, icompare, toupper, tolower, substr, atoi/atohex/atooct/atobin and itoa/hextoa/octtoa/bintoa (\"Method getc is not a string method\"), and requires a constant replication count for a string (\"A reference to a net or variable is not allowed in a constant expression\"). IEEE 1800-2023 6.16 defines the methods and 11.4.12.2 permits a non-constant count for a string replication. Verilator passes the cases.", + "expectation": "Simulation", + "known_issue": { + "category": "simulator_disagreement", + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "id": "sv_icarus_string_methods", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "phase": "compile", + "reason": "Icarus 13.0 does not implement the string methods getc, putc, compare, icompare, toupper, tolower, substr, atoi/atohex/atooct/atobin and itoa/hextoa/octtoa/bintoa (\"Method getc is not a string method\"), and requires a constant replication count for a string (\"A reference to a net or variable is not allowed in a constant expression\"). IEEE 1800-2023 6.16 defines the methods and 11.4.12.2 permits a non-constant count for a string replication. Verilator passes the cases.", + "upstream": [] + }, + "name": "string::methods", + "phase": "skip", + "status": "ignored", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::string_parameters_keep_their_text", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::strings_across_clock_edges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::strings_survive_heap_collections", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox-test-suite/verification/sv/limitations.json b/crates/celox-test-suite/verification/sv/limitations.json index 49ce5c92e65..9fcd0f1feb8 100644 --- a/crates/celox-test-suite/verification/sv/limitations.json +++ b/crates/celox-test-suite/verification/sv/limitations.json @@ -1654,5 +1654,24 @@ "latch::task_call_sensitivity" ] } + }, + { + "id": "sv_icarus_string_methods", + "category": "simulator_disagreement", + "phase": "compile", + "observed_version": "Celox SV frontend; Verilator 5.052 / Icarus 13.0", + "reason": "Icarus 13.0 does not implement the string methods getc, putc, compare, icompare, toupper, tolower, substr, atoi/atohex/atooct/atobin and itoa/hextoa/octtoa/bintoa (\"Method getc is not a string method\"), and requires a constant replication count for a string (\"A reference to a net or variable is not allowed in a constant expression\"). IEEE 1800-2023 6.16 defines the methods and 11.4.12.2 permits a non-constant count for a string replication. Verilator passes the cases.", + "upstream": [], + "evidence": [ + "verification/sv/limitations/icarus.json", + "LIMITATIONS.md#systemverilog-suite" + ], + "cases": { + "icarus": [ + "string::character_access", + "string::concatenation_and_replication", + "string::methods" + ] + } } ] diff --git a/crates/celox-test-suite/verification/sv/limitations/icarus.json b/crates/celox-test-suite/verification/sv/limitations/icarus.json index 318590cf075..3656017a5ed 100644 --- a/crates/celox-test-suite/verification/sv/limitations/icarus.json +++ b/crates/celox-test-suite/verification/sv/limitations/icarus.json @@ -9,7 +9,7 @@ "unexpected_accept": 1, "mismatch": 14, "emission_error": 0, - "compile_error": 104, + "compile_error": 107, "runtime_error": 7, "unsupported": 0, "ignored": 0 @@ -1199,6 +1199,30 @@ "stronger_than_sv": false, "tag_reasons": {}, "tags": [] + }, + { + "category": "Types", + "detail": "Icarus build exit status: 2; see /build.log\n/source_0.sv:7: error: Method getc is not a string method.\n/source_0.sv:7: error: Object celox_suite_tb.dut.s has no method \"getc(...)\".\n/source_0.sv:9: error: Enable of unknown task ``s.putc''.\n2 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "string::character_access", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 1; see /build.log\n/source_0.sv:10: error: A reference to a net or variable (`n') is not allowed in a constant expression.\n1 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "string::concatenation_and_replication", + "phase": "compile", + "status": "compile_error" + }, + { + "category": "Types", + "detail": "Icarus build exit status: 4; see /build.log\n/source_0.sv:8: error: Method compare is not a string method.\n/source_0.sv:8: error: Object celox_suite_tb.dut.s has no method \"compare(...)\".\n/source_0.sv:9: error: Method icompare is not a string method.\n/source_0.sv:9: error: Object celox_suite_tb.dut.s has no method \"icompare(...)\".\n/source_0.sv:11: error: Method toupper is not a string method.\n/source_0.sv:11: error: Object celox_suite_tb.dut.s has no method \"toupper(...)\".\n/source_0.sv:11: error: Method tolower is not a string method.\n/source_0.sv:11: error: Object celox_suite_tb.dut.s has no method \"tolower(...)\".\n4 error(s) during elaboration.\n", + "expectation": "Simulation", + "name": "string::methods", + "phase": "compile", + "status": "compile_error" } ] } diff --git a/crates/celox-test-suite/verification/sv/verilator.json b/crates/celox-test-suite/verification/sv/verilator.json index 6175b0c6ee5..8e66059cf84 100644 --- a/crates/celox-test-suite/verification/sv/verilator.json +++ b/crates/celox-test-suite/verification/sv/verilator.json @@ -12,6 +12,7 @@ "verilator/procedural.json", "verilator/random_plusargs.json", "verilator/review_regressions.json", + "verilator/string.json", "verilator/synthesizable.json", "verilator/system_functions.json", "verilator/timing.json", diff --git a/crates/celox-test-suite/verification/sv/verilator/string.json b/crates/celox-test-suite/verification/sv/verilator/string.json new file mode 100644 index 00000000000..2d9d77227a6 --- /dev/null +++ b/crates/celox-test-suite/verification/sv/verilator/string.json @@ -0,0 +1,103 @@ +{ + "cases": [ + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::assignment_and_display", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::casts_from_integral_values", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::character_access", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::comparisons", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::concatenation_and_replication", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::methods", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::string_parameters_keep_their_text", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::strings_across_clock_edges", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + }, + { + "category": "Types", + "detail": "", + "expectation": "Simulation", + "name": "string::strings_survive_heap_collections", + "phase": "execute", + "status": "passed", + "stronger_than_sv": false, + "tag_reasons": {}, + "tags": [] + } + ] +} diff --git a/crates/celox/src/backend/interp.rs b/crates/celox/src/backend/interp.rs index 800b6911d7b..3f7165c53e9 100644 --- a/crates/celox/src/backend/interp.rs +++ b/crates/celox/src/backend/interp.rs @@ -180,6 +180,8 @@ struct Machine<'a> { four_state: bool, /// Per-site enable bytes for comb capture events. comb_capture_enabled: &'a mut [u8], + /// The heap that heap helper calls operate on. + heap: &'a mut celox_heap::Heap, /// First-word snapshots of trigger-bearing objects taken at group entry, /// used by per-kind trigger edge detection. trigger_snapshots: &'a [((AbsoluteAddr, u32), u64)], @@ -999,6 +1001,12 @@ impl InterpMachine for Machine<'_> { } fn call_extern(&mut self, func: u32, args: &[u64]) -> Result { + if func == celox_sir::extern_abi::HEAP_HELPER_ID { + let &[code, a, b, c] = args else { + unreachable!("the SIR verifier checks heap call arguments") + }; + return Ok(self.heap.call(code, a, b, c)); + } // SAFETY: the frontend gives each call the argument count of the // DPI-C import it links to. Ok(unsafe { self.extern_functions.call(func, args) }) @@ -1115,6 +1123,7 @@ fn run_units( extern_functions: &ExternFunctionTable, four_state: bool, comb_capture_enabled: &mut [u8], + heap: &mut celox_heap::Heap, units: &mut [PreparedUnit], trigger_addrs: &[(AbsoluteAddr, u32)], trigger_snapshots: &mut Vec<((AbsoluteAddr, u32), u64)>, @@ -1135,6 +1144,7 @@ fn run_units( extern_functions, four_state, comb_capture_enabled: &mut *comb_capture_enabled, + heap: &mut *heap, trigger_snapshots, emit_triggers, }; @@ -1156,6 +1166,7 @@ fn run_units( extern_functions, four_state, comb_capture_enabled: &mut *comb_capture_enabled, + heap: &mut *heap, trigger_snapshots, emit_triggers, }; @@ -1205,6 +1216,8 @@ pub struct InterpBackend { memory: MemoryImage, runtime_event_buffer: Arc, comb_capture_enabled: Vec, + /// Boxed so the address in the state header survives moves. + heap: Box, event_map: HashMap, eval_only_event_map: HashMap, apply_event_map: HashMap, @@ -1416,6 +1429,7 @@ impl InterpBackend { memory, runtime_event_buffer, comb_capture_enabled, + heap: Default::default(), event_map, eval_only_event_map, apply_event_map, @@ -1454,6 +1468,10 @@ impl InterpBackend { celox_state_layout::STATE_HEADER_EXTERN_FUNCTIONS_ADDR_OFFSET, self.extern_functions.as_ptr() as u64, ); + self.memory.write_header_word( + celox_state_layout::STATE_HEADER_HEAP_ADDR_OFFSET, + std::ptr::from_mut(&mut *self.heap) as u64, + ); } /// Returns the pre-computed 4-state initialization regions @@ -1466,11 +1484,19 @@ impl InterpBackend { /// promotion. The returned memory image is byte-compatible with the /// compiled backends (same packed layout), and the event buffer `Arc` /// keeps its allocation so state-header pointers stay valid. - pub(crate) fn tier_transfer(&mut self) -> (MemoryImage, Arc, Vec) { + pub(crate) fn tier_transfer( + &mut self, + ) -> ( + MemoryImage, + Arc, + Vec, + Box, + ) { ( std::mem::take(&mut self.memory), Arc::clone(&self.runtime_event_buffer), std::mem::take(&mut self.comb_capture_enabled), + std::mem::take(&mut self.heap), ) } @@ -1502,6 +1528,7 @@ impl SimBackend for InterpBackend { &self.extern_functions, self.four_state, &mut self.comb_capture_enabled, + &mut self.heap, &mut self.eval_comb_units, &self.comb_trigger_addrs, &mut self.trigger_snapshots, @@ -1516,6 +1543,7 @@ impl SimBackend for InterpBackend { &self.extern_functions, self.four_state, &mut self.comb_capture_enabled, + &mut self.heap, self.eval_apply_units .get_mut(&event.addr()) .expect("scheduled event missing from SIR program"), @@ -1539,6 +1567,7 @@ impl SimBackend for InterpBackend { &self.extern_functions, self.four_state, &mut self.comb_capture_enabled, + &mut self.heap, units, &self.event_trigger_addrs[&event.addr()], &mut self.trigger_snapshots, @@ -1553,6 +1582,7 @@ impl SimBackend for InterpBackend { &self.extern_functions, self.four_state, &mut self.comb_capture_enabled, + &mut self.heap, self.eval_only_units .get_mut(&event.addr()) .expect("scheduled event missing from SIR program"), @@ -1571,6 +1601,7 @@ impl SimBackend for InterpBackend { &self.extern_functions, self.four_state, &mut self.comb_capture_enabled, + &mut self.heap, self.apply_units .get_mut(&event.addr()) .expect("scheduled event missing from SIR program"), @@ -1595,6 +1626,7 @@ impl SimBackend for InterpBackend { &self.extern_functions, self.four_state, &mut self.comb_capture_enabled, + &mut self.heap, std::slice::from_mut(unit), &[], &mut self.trigger_snapshots, @@ -1935,6 +1967,14 @@ impl SimBackend for InterpBackend { &self.layout } + fn heap(&self) -> &celox_heap::Heap { + &self.heap + } + + fn heap_mut(&mut self) -> &mut celox_heap::Heap { + &mut self.heap + } + fn id_to_addr_slice(&self) -> &[AbsoluteAddr] { &self.id_to_addr } diff --git a/crates/celox/src/backend/native/backend.rs b/crates/celox/src/backend/native/backend.rs index 429bcd23b58..62d2ebb11a7 100644 --- a/crates/celox/src/backend/native/backend.rs +++ b/crates/celox/src/backend/native/backend.rs @@ -2441,6 +2441,8 @@ pub struct NativeBackend { memory: MemoryImage, runtime_event_buffer: Arc, comb_capture_enabled: Vec, + /// Boxed so the address in the state header survives moves. + heap: Box, execution_timing: Option, /// Worker threads for lane-partitioned kernels, started on first use. lane_pool: Option, @@ -2665,6 +2667,7 @@ impl NativeBackend { memory, runtime_event_buffer, comb_capture_enabled, + heap: Default::default(), execution_timing: None, lane_pool: None, lane_selectors: Default::default(), @@ -2686,12 +2689,14 @@ impl NativeBackend { memory: MemoryImage, runtime_event_buffer: Arc, comb_capture_enabled: Vec, + heap: Box, ) -> Self { let mut backend = Self { compiled: shared, memory, runtime_event_buffer, comb_capture_enabled, + heap, execution_timing: None, lane_pool: None, lane_selectors: Default::default(), @@ -2699,6 +2704,7 @@ impl NativeBackend { // The state names the previous tier's extern function table; point it // at the one this code owns. backend.install_extern_functions(); + backend.install_heap(); backend } @@ -2822,6 +2828,14 @@ impl NativeBackend { self.comb_capture_enabled.as_ptr() as u64, ); self.install_extern_functions(); + self.install_heap(); + } + + fn install_heap(&mut self) { + self.memory.write_header_word( + celox_state_layout::STATE_HEADER_HEAP_ADDR_OFFSET, + std::ptr::from_mut(&mut *self.heap) as u64, + ); } fn install_extern_functions(&mut self) { @@ -3389,6 +3403,14 @@ impl super::super::SimBackend for NativeBackend { &self.compiled.layout } + fn heap(&self) -> &celox_heap::Heap { + &self.heap + } + + fn heap_mut(&mut self) -> &mut celox_heap::Heap { + &mut self.heap + } + fn id_to_addr_slice(&self) -> &[AbsoluteAddr] { &self.compiled.id_to_addr } diff --git a/crates/celox/src/backend/runtime.rs b/crates/celox/src/backend/runtime.rs index a45b48d4e81..e8f5ba4a1db 100644 --- a/crates/celox/src/backend/runtime.rs +++ b/crates/celox/src/backend/runtime.rs @@ -124,6 +124,8 @@ pub struct JitBackend { memory: MemoryImage, runtime_event_buffer: Arc, comb_capture_enabled: Vec, + /// Boxed so the address in the state header survives moves. + heap: Box, /// Cached from `shared.comb_func` to avoid Arc dereference on the hot path. comb_func: SimFunc, /// Worker threads for lane-partitioned kernels, started on first use. @@ -738,6 +740,7 @@ impl JitBackend { memory, runtime_event_buffer, comb_capture_enabled, + heap: Default::default(), comb_func, lane_pool: None, lane_selectors: Default::default(), @@ -758,6 +761,7 @@ impl JitBackend { memory: MemoryImage, runtime_event_buffer: Arc, comb_capture_enabled: Vec, + heap: Box, ) -> Self { // A MemorySpilled compile plan extends the compiled layout with // backend scratch beyond the semantic state the interpreter owned. @@ -774,6 +778,7 @@ impl JitBackend { memory, runtime_event_buffer, comb_capture_enabled, + heap, comb_func, lane_pool: None, lane_selectors: Default::default(), @@ -781,6 +786,7 @@ impl JitBackend { // The state names the previous tier's extern function table; point it // at the one this code owns. backend.install_extern_functions(); + backend.install_heap(); backend } @@ -798,6 +804,14 @@ impl JitBackend { self.comb_capture_enabled.as_ptr() as u64, ); self.install_extern_functions(); + self.install_heap(); + } + + fn install_heap(&mut self) { + self.memory.write_header_word( + celox_state_layout::STATE_HEADER_HEAP_ADDR_OFFSET, + std::ptr::from_mut(&mut *self.heap) as u64, + ); } fn install_extern_functions(&mut self) { @@ -1416,6 +1430,14 @@ impl super::SimBackend for JitBackend { self.layout() } + fn heap(&self) -> &celox_heap::Heap { + &self.heap + } + + fn heap_mut(&mut self) -> &mut celox_heap::Heap { + &mut self.heap + } + fn id_to_addr_slice(&self) -> &[AbsoluteAddr] { self.id_to_addr_slice() } diff --git a/crates/celox/src/backend/tiered.rs b/crates/celox/src/backend/tiered.rs index 26d36a20078..006d0ee904b 100644 --- a/crates/celox/src/backend/tiered.rs +++ b/crates/celox/src/backend/tiered.rs @@ -151,6 +151,7 @@ impl CompiledTier { mut memory: MemoryImage, runtime_event_buffer: Arc, comb_capture_enabled: Vec, + heap: Box, ) -> Self { debug_assert!(memory.capacity_words() >= code.required_image_words()); if memory.len_words() < code.required_image_words() { @@ -163,6 +164,7 @@ impl CompiledTier { memory, runtime_event_buffer, comb_capture_enabled, + heap, ))) } #[cfg(any( @@ -176,6 +178,7 @@ impl CompiledTier { memory, runtime_event_buffer, comb_capture_enabled, + heap, ), )), } @@ -1094,13 +1097,15 @@ impl TieredBackend { let mut adopted = None; if let Phase::Interpreting(slot) = &mut self.phase { if let Some(mut interp) = slot.take() { - let (memory, runtime_event_buffer, comb_capture_enabled) = interp.tier_transfer(); + let (memory, runtime_event_buffer, comb_capture_enabled, heap) = + interp.tier_transfer(); drop(interp); adopted = Some(CompiledTier::adopt( code, memory, runtime_event_buffer, comb_capture_enabled, + heap, )); } } @@ -1696,6 +1701,34 @@ impl SimBackend for TieredBackend { } } + fn heap(&self) -> &celox_heap::Heap { + match &self.phase { + Phase::Interpreting(Some(interp)) => interp.heap(), + Phase::Compiled(CompiledTier::Jit(jit)) => jit.heap(), + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + Phase::Compiled(CompiledTier::Native(native)) => native.heap(), + Phase::Interpreting(None) => unreachable!("promoted backend left no interpreter"), + } + } + + fn heap_mut(&mut self) -> &mut celox_heap::Heap { + match &mut self.phase { + Phase::Interpreting(Some(interp)) => interp.heap_mut(), + Phase::Compiled(CompiledTier::Jit(jit)) => jit.heap_mut(), + #[cfg(any( + target_arch = "x86_64", + feature = "arm64-codegen", + target_arch = "aarch64" + ))] + Phase::Compiled(CompiledTier::Native(native)) => native.heap_mut(), + Phase::Interpreting(None) => unreachable!("promoted backend left no interpreter"), + } + } + fn id_to_addr_slice(&self) -> &[AbsoluteAddr] { match &self.phase { Phase::Interpreting(Some(interp)) => interp.id_to_addr_slice(), diff --git a/crates/celox/src/backend/wasm_runtime.rs b/crates/celox/src/backend/wasm_runtime.rs index 14a41ed3f98..4dceda752f0 100644 --- a/crates/celox/src/backend/wasm_runtime.rs +++ b/crates/celox/src/backend/wasm_runtime.rs @@ -127,6 +127,14 @@ impl super::traits::SimBackend for WasmBackend { fn layout(&self) -> &super::MemoryLayout { WasmBackend::layout(self) } + + fn heap(&self) -> &celox_heap::Heap { + self.store.data() + } + + fn heap_mut(&mut self) -> &mut celox_heap::Heap { + self.store.data_mut() + } fn id_to_addr_slice(&self) -> &[AbsoluteAddr] { WasmBackend::id_to_addr_slice(self) } @@ -149,7 +157,7 @@ impl super::traits::SimBackend for WasmBackend { /// The runtime WASM backend. pub struct WasmBackend { - store: Store<()>, + store: Store, memory: Memory, raw_view_exposed: bool, comb_func: TypedFunc<(), i64>, @@ -306,7 +314,7 @@ impl WasmBackend { } // Create store and shared memory - let mut store = Store::new(&engine, ()); + let mut store = Store::new(&engine, celox_heap::Heap::new()); let runtime_event_base = layout.merged_total_size; let comb_capture_enabled_base = runtime_event_base + layout.runtime_event_buffer_size; let comb_capture_enabled_size = layout.runtime_event_site_layouts.len().max(1); @@ -347,7 +355,7 @@ impl WasmBackend { // extern functions it imports. fn instantiate_module( engine: &Engine, - store: &mut Store<()>, + store: &mut Store, module: &Module, memory: &Memory, extern_functions: &crate::dpi::ExternFunctionTable, @@ -369,23 +377,30 @@ impl WasmBackend { }; let extern_functions = extern_functions.clone(); linker - .func_new("env", import.name(), ty, move |_, params, results| { - // The SIR verifier bounds the argument count. - let mut args = [0; celox_sir::MAX_EXTERN_CALL_ARGUMENTS]; - let args = &mut args[..params.len()]; - for (arg, param) in args.iter_mut().zip(params) { - *arg = param.unwrap_i64() as u64; - } - // SAFETY: the module calls each import with the - // argument count of the DPI-C import it links to. - let result = if func == u32::MAX { - celox_sir::float::evaluate(args[0], args[1], args[2]) - } else { - unsafe { extern_functions.call(func, args) } - }; - results[0] = wasmtime::Val::I64(result as i64); - Ok(()) - }) + .func_new( + "env", + import.name(), + ty, + move |mut caller, params, results| { + // The SIR verifier bounds the argument count. + let mut args = [0; celox_sir::MAX_EXTERN_CALL_ARGUMENTS]; + let args = &mut args[..params.len()]; + for (arg, param) in args.iter_mut().zip(params) { + *arg = param.unwrap_i64() as u64; + } + // SAFETY: the module calls each import with the + // argument count of the DPI-C import it links to. + let result = if func == u32::MAX { + celox_sir::float::evaluate(args[0], args[1], args[2]) + } else if func == celox_sir::extern_abi::HEAP_HELPER_ID { + caller.data_mut().call(args[0], args[1], args[2], args[3]) + } else { + unsafe { extern_functions.call(func, args) } + }; + results[0] = wasmtime::Val::I64(result as i64); + Ok(()) + }, + ) .map_err(|source| wasm_codegen_error("linking", source))?; } let instance = linker diff --git a/crates/celox/src/dpi.rs b/crates/celox/src/dpi.rs index fc7e8cbe9da..06ab57898db 100644 --- a/crates/celox/src/dpi.rs +++ b/crates/celox/src/dpi.rs @@ -83,7 +83,7 @@ impl DpiSymbols { } // Internal helpers precede the user table so persisted machine code // resolves them in the loading process instead of embedding addresses. - let mut addresses = vec![celox_sir::float::evaluate as *const () as usize]; + let mut addresses = internal_helpers(); addresses.extend( functions .iter() @@ -170,16 +170,17 @@ pub(crate) struct ExternFunctionTable { impl Default for ExternFunctionTable { fn default() -> Self { Self { - addresses: vec![celox_sir::float::evaluate as *const () as usize].into(), + addresses: internal_helpers().into(), } } } impl ExternFunctionTable { /// The user table's address, which the state header holds. The internal - /// floating-point helper occupies the immediately preceding slot. + /// floating-point helper occupies the immediately preceding slot, and the + /// heap helper the one before it. pub(crate) fn as_ptr(&self) -> *const usize { - self.addresses.as_ptr().wrapping_add(1) + self.addresses.as_ptr().wrapping_add(INTERNAL_HELPERS) } /// Call function `func` with C integer arguments and return its C integer @@ -191,10 +192,37 @@ impl ExternFunctionTable { /// integer or nothing, as its DPI-C import declares. pub(crate) unsafe fn call(&self, func: u32, args: &[u64]) -> u64 { // SAFETY: forwarded from the caller. - unsafe { call_c(self.addresses[func as usize + 1], args) } + unsafe { call_c(self.addresses[func as usize + INTERNAL_HELPERS], args) } } } +/// The number of internal helpers in front of the user extern function table. +const INTERNAL_HELPERS: usize = 2; + +/// The internal helpers, in table order: the heap helper, then the +/// floating-point helper. +fn internal_helpers() -> Vec { + vec![ + heap_helper as *const () as usize, + celox_sir::float::evaluate as *const () as usize, + ] +} + +/// The heap helper that compiled code calls for +/// [`celox_sir::extern_abi::HEAP_HELPER_ID`], with the state pointer first. +pub(crate) extern "C" fn heap_helper(state: *mut u8, code: u64, a: u64, b: u64, c: u64) -> u64 { + // SAFETY: compiled code passes the state pointer of an image whose + // header holds the address of its backend's live heap, and the backend + // runs no other code on that heap during the call. + let heap = unsafe { + &mut *state + .add(celox_state_layout::STATE_HEADER_HEAP_ADDR_OFFSET) + .cast::<*mut celox_heap::Heap>() + .read() + }; + heap.call(code, a, b, c) +} + /// Call the C function at `address` with integer arguments. /// /// Every argument is passed and the result read as a 64-bit integer. On the diff --git a/crates/celox/src/simulation.rs b/crates/celox/src/simulation.rs index 4d0022f33ef..4a6c96beffd 100644 --- a/crates/celox/src/simulation.rs +++ b/crates/celox/src/simulation.rs @@ -216,6 +216,9 @@ impl HostBoundary for Simulator { } fn try_finish_timed_step(&mut self, timestamp: u64) -> Result<(), Halt> { + // The time slot is over: no kernel runs, and its updates are in + // state memory. + self.heap_safepoint(); self.start_sv_vcd(timestamp).map_err(|error| { Halt::Error(RuntimeErrorCode::Runtime { message: format!("VCD setup failed: {error}"), diff --git a/crates/celox/src/simulator.rs b/crates/celox/src/simulator.rs index e8d0992c26a..07e2c81f497 100644 --- a/crates/celox/src/simulator.rs +++ b/crates/celox/src/simulator.rs @@ -123,10 +123,11 @@ mod host { /// cross-codegen builds or unsupported hosts. pub struct Simulator { pub(crate) backend: B, - /// Dynamic values that handle slots in state memory refer to. - pub(crate) heap: celox_heap::Heap, /// Byte offsets of every handle slot in state memory. pub(super) handle_slots: std::sync::OnceLock>, + /// Set while handles live outside state memory, where no collection + /// may run: between the polls of concurrent testbench processes. + pub(crate) heap_safepoints_blocked: bool, file_io: celox_runtime::file_io::FileIo, pending_host_events: Arc>, pub(crate) program: RuntimeProgram, @@ -270,6 +271,36 @@ mod host { signed: bool, is_string: bool, float_precision: Option, + /// A string handle not yet replaced by its contents. + handle: bool, + } + + impl RuntimeEventArgValue { + /// Replace a string handle by the bytes of its string, which the + /// formatter prints as text. + fn resolve_handle(&mut self, heap: &celox_heap::Heap) { + if !std::mem::take(&mut self.handle) { + return; + } + let handle = self.values.first().copied().unwrap_or(0) as celox_heap::Handle; + let bytes = heap.string(handle); + self.values = BigUint::from_bytes_be(bytes).to_u64_digits(); + self.masks = vec![0; self.values.len()]; + self.width = bytes.len() * 8; + self.signed = false; + self.is_string = true; + } + } + + impl RawRuntimeEvent { + fn resolve_handles(&mut self, heap: &celox_heap::Heap) { + let (Self::Host { args, .. } | Self::Event { args, .. }) = self else { + return; + }; + for arg in args { + arg.resolve_handle(heap); + } + } } #[derive(Clone)] @@ -672,6 +703,9 @@ mod host { is_string: site .and_then(|site| site.arg_is_string.get(idx).copied()) .unwrap_or(false), + handle: site + .and_then(|site| site.arg_is_handle.get(idx).copied()) + .unwrap_or(false), }); } } @@ -756,7 +790,10 @@ mod host { collect_runtime_events(layout, sites, read_seq, size, read_u64, read_u64) }; raw.into_iter() - .filter_map(|event| render_raw_runtime_event(event, sites, context)) + .filter_map(|mut event| { + event.resolve_handles(backend.heap()); + render_raw_runtime_event(event, sites, context) + }) .collect() } @@ -834,8 +871,8 @@ mod host { dirty: false, declaration_phase: false, warnings, - heap: Default::default(), handle_slots: Default::default(), + heap_safepoints_blocked: false, file_io: Default::default(), pending_host_events: Default::default(), components: Default::default(), @@ -1152,7 +1189,27 @@ mod host { ); } + /// Move the events in the backend's buffer to the queue that + /// [`Self::drain_runtime_events`] reads. + pub(crate) fn stash_runtime_events(&mut self) { + let events = self.collect_backend_runtime_events(); + let capacity = self.backend.layout().runtime_event_capacity; + self.pending_host_events + .lock() + .unwrap() + .extend(events, capacity); + } + fn collect_backend_runtime_events(&mut self) -> Vec { + // String arguments are read now, while the heap still holds them. + let mut events = self.collect_backend_raw_runtime_events(); + for event in &mut events { + event.resolve_handles(self.backend.heap()); + } + events + } + + fn collect_backend_raw_runtime_events(&mut self) -> Vec { let layout = self.backend.layout(); let mut read_seq = self.runtime_event_read_seq.load(Ordering::Acquire); if let Some(buffer) = self.backend.runtime_event_buffer() { @@ -1620,6 +1677,12 @@ mod host { /// do not run; drive the signal's levels with the timed /// [`crate::Simulation`] for them. pub fn tick(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { + let result = self.tick_unit(event); + self.heap_safepoint(); + result + } + + fn tick_unit(&mut self, event: B::Event) -> Result<(), RuntimeErrorCode> { if let Some(Some(_)) = self.derived_ticks.get(event.id()) { return self.tick_derived(event); } @@ -1927,6 +1990,12 @@ mod host { /// gated clocks with the ticked domains, state-derived ones after /// all of them commit. pub fn tick_events(&mut self, events: &[B::Event]) -> Result<(), RuntimeErrorCode> { + let result = self.tick_events_unit(events); + self.heap_safepoint(); + result + } + + fn tick_events_unit(&mut self, events: &[B::Event]) -> Result<(), RuntimeErrorCode> { use celox_runtime::backend::EventHandle; // Deduplicate domains before requiring split kernels: a design // with a single domain has no split kernels, and aliases of one diff --git a/crates/celox/src/simulator/checkpoint.rs b/crates/celox/src/simulator/checkpoint.rs index 772c839cada..569d454a274 100644 --- a/crates/celox/src/simulator/checkpoint.rs +++ b/crates/celox/src/simulator/checkpoint.rs @@ -5,8 +5,8 @@ //! stable region, and the sparse, triggered-bit and scratch regions are //! cleared before control returns to the host. A checkpoint therefore copies //! only the stable region, which is laid out identically in every tier of a -//! tiered simulation. The state header in front of it holds host pointers and -//! is never copied. +//! tiered simulation, together with the heap its handle slots refer to. The +//! state header in front of it holds host pointers and is never copied. use celox_state_layout::STATE_HEADER_SIZE; use num_bigint::BigUint; @@ -15,7 +15,8 @@ use super::host::Simulator; use crate::backend::SimBackend; /// The design state of a memory image: the stable region after the state -/// header, tagged with the layout fingerprint it belongs to. +/// header and the heap it refers to, tagged with the layout fingerprint it +/// belongs to. /// /// This is the backend-level building block of [`Checkpoint`]. Hosts that /// drive a bare backend use it directly. @@ -23,6 +24,8 @@ use crate::backend::SimBackend; pub struct StateImage { fingerprint: u64, bytes: Box<[u8]>, + /// Strings are immutable and shared, so this copies only the tables. + heap: celox_heap::Heap, } impl StateImage { @@ -37,6 +40,7 @@ impl StateImage { Self { fingerprint, bytes: memory[range].into(), + heap: backend.heap().clone(), } } @@ -60,12 +64,14 @@ impl StateImage { let range = state_range(backend); assert_eq!(range.len(), self.bytes.len()); backend.write_memory(range.start, &self.bytes); + backend.heap_mut().clone_from(&self.heap); Ok(()) } - /// Size of the saved design state in bytes. + /// Size of the saved design state in bytes, including string contents + /// and excluding allocator overhead. pub fn len(&self) -> usize { - self.bytes.len() + self.bytes.len() + self.heap.content_size() } pub fn is_empty(&self) -> bool { @@ -92,7 +98,6 @@ fn state_range(backend: &B) -> std::ops::Range { #[derive(Clone)] pub struct Checkpoint { image: StateImage, - heap: celox_heap::Heap, comb_observer_snapshots: Vec>, comb_observer_initial_eval: bool, /// Whether the design had finished a timed simulation. @@ -102,7 +107,7 @@ pub struct Checkpoint { impl Checkpoint { /// Bytes in the saved memory image and string contents, excluding allocator overhead. pub fn state_size(&self) -> usize { - self.image.len() + self.heap.content_size() + self.image.len() } } @@ -159,7 +164,6 @@ impl Simulator { } Ok(Checkpoint { image: StateImage::capture(&self.backend, self.state_fingerprint()), - heap: self.heap.clone(), comb_observer_snapshots: self.comb_observer_snapshots.clone(), comb_observer_initial_eval: self.comb_observer_initial_eval, frozen: self.frozen, @@ -179,7 +183,6 @@ impl Simulator { checkpoint .image .restore_into(&mut self.backend, fingerprint)?; - self.heap.clone_from(&checkpoint.heap); self.comb_observer_snapshots .clone_from(&checkpoint.comb_observer_snapshots); self.comb_observer_initial_eval = checkpoint.comb_observer_initial_eval; diff --git a/crates/celox/src/simulator/heap.rs b/crates/celox/src/simulator/heap.rs index accc54b560d..47342e5f9fb 100644 --- a/crates/celox/src/simulator/heap.rs +++ b/crates/celox/src/simulator/heap.rs @@ -60,14 +60,27 @@ impl Simulator { .collect() } + /// Collect the heap between time slots, if enough was allocated. Runtime + /// events still in the backend's buffer are taken first, which reads + /// their string arguments. + pub(crate) fn heap_safepoint(&mut self) { + if self.heap_safepoints_blocked || !self.backend.heap().should_collect() { + return; + } + self.stash_runtime_events(); + self.maybe_collect_heap([]); + } + /// Collect the heap if enough was allocated since the last collection. /// State memory and `extra_roots` must hold every live handle: the /// caller runs this only where no copy of a handle is anywhere else. pub(crate) fn maybe_collect_heap(&mut self, extra_roots: impl IntoIterator) { - if !self.heap.should_collect() { + if !self.backend.heap().should_collect() { return; } let roots = self.handle_roots(); - self.heap.collect(roots.into_iter().chain(extra_roots)); + self.backend + .heap_mut() + .collect(roots.into_iter().chain(extra_roots)); } } diff --git a/crates/celox/src/simulator/host/file_io.rs b/crates/celox/src/simulator/host/file_io.rs index 31f0dcb65b7..ef6689303c9 100644 --- a/crates/celox/src/simulator/host/file_io.rs +++ b/crates/celox/src/simulator/host/file_io.rs @@ -75,6 +75,7 @@ impl Simulator { signed: arg.signed, is_string: arg.is_string, float_precision: arg.float_precision, + handle: false, }) .collect(); let process = &self.program.runtime_schema.processes[site.process]; @@ -104,6 +105,7 @@ impl Simulator { arg_signed: Vec::new(), arg_is_string: Vec::new(), arg_float_precision: Vec::new(), + arg_is_handle: Vec::new(), }; let mut message = render_runtime_event_message( &format, diff --git a/crates/celox/src/simulator/state_file.rs b/crates/celox/src/simulator/state_file.rs index 96f30a45e94..706e8dbf34a 100644 --- a/crates/celox/src/simulator/state_file.rs +++ b/crates/celox/src/simulator/state_file.rs @@ -126,19 +126,8 @@ pub struct StateSchema { impl StateSchema { /// Save the value of every state object of `backend` as last evaluated. - /// String objects read as `""`; use [`Self::capture_with_heap`] for a - /// backend whose strings live in a heap. pub fn capture(&self, backend: &B) -> StateFile { - self.capture_with_heap(backend, &celox_heap::Heap::new()) - } - - /// Save the value of every state object of `backend`, with the contents - /// of its strings from `heap`. - pub fn capture_with_heap( - &self, - backend: &B, - heap: &celox_heap::Heap, - ) -> StateFile { + let heap = backend.heap(); let mut strings = Vec::new(); let mut file_ids: HashMap = HashMap::default(); let mut objects: Vec = self @@ -211,16 +200,6 @@ impl StateSchema { &self, backend: &mut B, file: &StateFile, - ) -> Result<(), StateMismatch> { - self.load_with_heap(backend, &mut celox_heap::Heap::new(), file) - } - - /// Like [`Self::load`], creating the file's strings in `heap`. - pub fn load_with_heap( - &self, - backend: &mut B, - heap: &mut celox_heap::Heap, - file: &StateFile, ) -> Result<(), StateMismatch> { let saved: BTreeMap<&str, &StateObject> = file .objects @@ -278,7 +257,7 @@ impl StateSchema { .checked_sub(1) .and_then(|index| file.strings.get(index)) .map_or(&[][..], Vec::as_slice); - element.copy_from_slice(&heap.intern(contents).to_le_bytes()); + element.copy_from_slice(&backend.heap_mut().intern(contents).to_le_bytes()); } BigUint::from_bytes_le(&value) } else { @@ -322,9 +301,7 @@ impl Simulator { self.eval_comb_checked().map_err(StateError::Runtime)?; self.dirty = false; } - Ok(self - .state_schema() - .capture_with_heap(&self.backend, &self.heap)) + Ok(self.state_schema().capture(&self.backend)) } /// Load the state saved in `file`, matching objects by path. @@ -354,7 +331,7 @@ impl Simulator { // combinational loop), so keep the current state to return to. let previous = self.checkpoint()?; self.state_schema() - .load_with_heap(&mut self.backend, &mut self.heap, file) + .load(&mut self.backend, file) .map_err(StateError::Mismatch)?; for address in &self.program.runtime_schema.time_slots { self.backend.set( diff --git a/crates/celox/src/testbench.rs b/crates/celox/src/testbench.rs index 23fb0943e78..68c261446c6 100644 --- a/crates/celox/src/testbench.rs +++ b/crates/celox/src/testbench.rs @@ -97,16 +97,7 @@ fn eval_expr( sim: &mut Simulator, expr: &celox_testbench::CompiledExpr, ) -> TbValue { - let (memory, _) = sim.backend.memory_as_ptr(); - let trace = sim.backend.layout().trace.as_ref(); - expr.eval_with_heap(memory.cast_mut(), Some(&mut sim.heap), |offset, len| { - if let Some(trace) = trace { - // SAFETY: bytecode is bound to this simulator's memory layout. - unsafe { - trace.mark_range(memory.cast_mut(), offset, len); - } - } - }) + eval_backend_expr(&mut sim.backend, expr) } pub(crate) fn eval_backend_expr( @@ -114,18 +105,25 @@ pub(crate) fn eval_backend_expr( expr: &celox_testbench::CompiledExpr, ) -> TbValue { // This pointer is used only during evaluation, never exposed to a host. - // Observe VM stores explicitly instead of disabling tracking for reads. + // Observe VM stores explicitly instead of disabling tracking for reads; + // they are marked once the heap is no longer borrowed. let (memory, _) = backend.memory_as_ptr(); - let trace = backend.layout().trace.as_ref(); - expr.eval_value_with_write_observer(memory.cast_mut(), |offset, len| { - if let Some(trace) = trace { + let mut writes = Vec::new(); + let value = expr.eval_with_heap( + memory.cast_mut(), + Some(backend.heap_mut()), + |offset, len| writes.push((offset, len)), + ); + if let Some(trace) = backend.layout().trace.as_ref() { + for (offset, len) in writes { // SAFETY: bound bytecode writes valid locations in this image, and // the simulator cannot execute concurrently with this evaluation. unsafe { trace.mark_range(memory.cast_mut(), offset, len); } } - }) + } + value } fn format_assert_arg( @@ -254,7 +252,7 @@ fn sim_set_target( eval_expr(sim, &selection.offset).to_u64() as usize / celox_design::HANDLE_WIDTH }); if index < target.signal.width / celox_design::HANDLE_WIDTH { - let handle = sim.heap.intern(&bytes); + let handle = sim.backend.heap_mut().intern(&bytes); let element = SignalRef { offset: target.signal.offset + index * celox_heap::HANDLE_BYTES, width: celox_design::HANDLE_WIDTH, @@ -300,7 +298,7 @@ fn collect_testbench_heap( private_signals: &[SignalRef], locals: &[Vec<(BigUint, BigUint)>], ) { - if !sim.heap.should_collect() { + if !sim.backend.heap().should_collect() { return; } let slots = sim.handle_slots(); @@ -1716,6 +1714,20 @@ fn exec_testbench( if blocks.len() <= 1 { return exec_detailed(sim, testbench.statements(), ctx); } + // Suspended processes keep their temporaries outside state memory, so + // only the poll loop collects, with those temporaries as roots. + let blocked = std::mem::replace(&mut sim.heap_safepoints_blocked, true); + let result = exec_processes(sim, testbench, ctx, &blocks); + sim.heap_safepoints_blocked = blocked; + result +} + +fn exec_processes( + sim: &mut Simulator, + testbench: &CompiledTestbench, + ctx: &mut DetailedExecContext, + blocks: &[&[TestbenchStatement]], +) -> ExecResult { initialize_process_clocks(sim, testbench.statements()); // The compiler's function slots are shared by inline call sites. Keep // only these temporaries private; design variables remain shared between diff --git a/crates/celox/tests/frontends/systemverilog/review_regressions.rs b/crates/celox/tests/frontends/systemverilog/review_regressions.rs index deb4f74ebd1..29c87ced2f5 100644 --- a/crates/celox/tests/frontends/systemverilog/review_regressions.rs +++ b/crates/celox/tests/frontends/systemverilog/review_regressions.rs @@ -239,7 +239,7 @@ fn rejects_inline_enum_ports_instead_of_scalarizing_them() { fn rejects_non_integral_ports_instead_of_scalarizing_them() { let error = cranelift_build_error( r#" - module Top(input string value, output logic y); + module Top(input chandle value, output logic y); assign y = 1'b0; endmodule "#, @@ -6416,7 +6416,7 @@ fn rejects_unsupported_internal_data_types() { let error = cranelift_build_error( r#" module Top(output logic y); - string value; + chandle value; assign y = 1'b0; endmodule "#, diff --git a/crates/celox/tests/frontends/systemverilog/string.rs b/crates/celox/tests/frontends/systemverilog/string.rs new file mode 100644 index 00000000000..a1a23e71533 --- /dev/null +++ b/crates/celox/tests/frontends/systemverilog/string.rs @@ -0,0 +1,36 @@ +use super::*; + +sv_backends! { + fn string_assignment_and_display(sim) { @case "string::assignment_and_display"; } + fn string_comparisons(sim) { @case "string::comparisons"; } + fn string_concatenation_and_replication(sim) { @case "string::concatenation_and_replication"; } + fn string_character_access(sim) { @case "string::character_access"; } + fn string_methods(sim) { @case "string::methods"; } + fn string_casts_from_integral_values(sim) { @case "string::casts_from_integral_values"; } + fn strings_across_clock_edges(sim) { @case "string::strings_across_clock_edges"; } +} + +sv_backends! { + fn strings_survive_heap_collections(sim) { @case "string::strings_survive_heap_collections"; } +} + +sv_backends! { + fn string_parameters_keep_their_text(sim) { @case "string::string_parameters_keep_their_text"; } +} + +#[test] +fn unpacked_arrays_of_strings_are_rejected() { + let source = r#" + module Top; + string names [2]; + initial names[0] = "a"; + endmodule + "#; + let Err(error) = Simulator::from_sv_sources(vec![(source, Path::new("strings.sv"))], "Top") + .build_cranelift() + else { + panic!("an unpacked array of strings is unsupported"); + }; + let error = error.to_string(); + assert!(error.contains("unpacked array of strings"), "{error}"); +} diff --git a/crates/celox/tests/snapshots/native_mir__ff_branch_mir.snap b/crates/celox/tests/snapshots/native_mir__ff_branch_mir.snap index f82db7279e0..6e361d268e7 100644 --- a/crates/celox/tests/snapshots/native_mir__ff_branch_mir.snap +++ b/crates/celox/tests/snapshots/native_mir__ff_branch_mir.snap @@ -35,23 +35,23 @@ Bindings: apply_ff trigger=rst --- MIR after main optimization, before regalloc-owned late folds --- bb0: - v0 = load.i8 [sim + 48] - store.i8 [sim + 41], v0 + v0 = load.i8 [sim + 56] + store.i8 [sim + 49], v0 ret --- MIR after late memory folds, before allocation-owned scheduling --- bb0: - v0 = load.i8 [sim + 48] - store.i8 [sim + 41], v0 + v0 = load.i8 [sim + 56] + store.i8 [sim + 49], v0 ret --- MIR after allocation-owned scheduling, before spill reconstruction --- bb0: - v0 = load.i8 [sim + 48] - store.i8 [sim + 41], v0 + v0 = load.i8 [sim + 56] + store.i8 [sim + 49], v0 ret --- MIR after register allocation and post-RA peepholes --- bb0: - v0 = load.i8 [sim + 48] - store.i8 [sim + 41], v0 + v0 = load.i8 [sim + 56] + store.i8 [sim + 49], v0 ret Spill frame: 0 bytes Register assignment: @@ -61,8 +61,8 @@ x86-64 disassembly of emitted function: 0x00000005 movq xmm15,rax 0x0000000a wrgsbase rdi bb0: - 0x0000000f movzx eax,byte [gs:30h] - 0x00000018 mov [gs:29h],al + 0x0000000f movzx eax,byte [gs:38h] + 0x00000018 mov [gs:31h],al 0x00000021 xor eax,eax 0x00000023 jmp short 0000000000000025h 0x00000025 movq r11,xmm15 @@ -75,66 +75,66 @@ Bindings: eval_apply_ff trigger=rst --- MIR after main optimization, before regalloc-owned late folds --- bb0: - v0 = load.i8 [sim + 40] + v0 = load.i8 [sim + 48] v1 = cmp.Eq v0, 0 br v1, bb1, bb2 bb1: v2 = imm 0x0 - store.i8 [sim + 41], v2 + store.i8 [sim + 49], v2 jmp bb3 bb2: - v3 = load.i8 [sim + 42] - store.i8 [sim + 41], v3 + v3 = load.i8 [sim + 50] + store.i8 [sim + 49], v3 jmp bb3 bb3: ret --- MIR after late memory folds, before allocation-owned scheduling --- bb0: - v0 = load.i8 [sim + 40] + v0 = load.i8 [sim + 48] br_pred CompareImm { lhs: v0, imm: 0, kind: Eq }, bb4, bb5 bb4: jmp bb1 bb1: v2 = imm 0x0 - store.i8 [sim + 41], v2 + store.i8 [sim + 49], v2 jmp bb3 bb5: jmp bb2 bb2: - v3 = load.i8 [sim + 42] - store.i8 [sim + 41], v3 + v3 = load.i8 [sim + 50] + store.i8 [sim + 49], v3 jmp bb3 bb3: ret --- MIR after allocation-owned scheduling, before spill reconstruction --- bb0: - v0 = load.i8 [sim + 40] + v0 = load.i8 [sim + 48] br_pred CompareImm { lhs: v0, imm: 0, kind: Eq }, bb4, bb5 bb4: jmp bb1 bb1: v2 = imm 0x0 - store.i8 [sim + 41], v2 + store.i8 [sim + 49], v2 jmp bb3 bb5: jmp bb2 bb2: - v3 = load.i8 [sim + 42] - store.i8 [sim + 41], v3 + v3 = load.i8 [sim + 50] + store.i8 [sim + 49], v3 jmp bb3 bb3: ret --- MIR after register allocation and post-RA peepholes --- bb0: - v0 = load.i8 [sim + 40] + v0 = load.i8 [sim + 48] br_pred CompareImm { lhs: v0, imm: 0, kind: Eq }, bb1, bb2 bb1: v2 = imm 0x0 - store.i8 [sim + 41], v2 + store.i8 [sim + 49], v2 jmp bb3 bb2: - v3 = load.i8 [sim + 42] - store.i8 [sim + 41], v3 + v3 = load.i8 [sim + 50] + store.i8 [sim + 49], v3 jmp bb3 bb3: ret @@ -148,16 +148,16 @@ x86-64 disassembly of emitted function: 0x00000005 movq xmm15,rax 0x0000000a wrgsbase rdi bb0: - 0x0000000f movzx eax,byte [gs:28h] + 0x0000000f movzx eax,byte [gs:30h] 0x00000018 test rax,rax 0x0000001b je short 0000000000000031h bb2: - 0x0000001d movzx eax,byte [gs:2Ah] - 0x00000026 mov [gs:29h],al + 0x0000001d movzx eax,byte [gs:32h] + 0x00000026 mov [gs:31h],al 0x0000002f jmp short 000000000000003Ch bb1: 0x00000031 xor eax,eax - 0x00000033 mov [gs:29h],al + 0x00000033 mov [gs:31h],al bb3: 0x0000003c xor eax,eax 0x0000003e jmp short 0000000000000040h @@ -171,66 +171,66 @@ Bindings: eval_comb_apply_ff trigger=rst --- MIR after main optimization, before regalloc-owned late folds --- bb0: - v0 = load.i8 [sim + 40] + v0 = load.i8 [sim + 48] v1 = cmp.Eq v0, 0 br v1, bb1, bb2 bb1: v2 = imm 0x0 - store.i8 [sim + 41], v2 + store.i8 [sim + 49], v2 jmp bb3 bb2: - v3 = load.i8 [sim + 42] - store.i8 [sim + 41], v3 + v3 = load.i8 [sim + 50] + store.i8 [sim + 49], v3 jmp bb3 bb3: ret --- MIR after late memory folds, before allocation-owned scheduling --- bb0: - v0 = load.i8 [sim + 40] + v0 = load.i8 [sim + 48] br_pred CompareImm { lhs: v0, imm: 0, kind: Eq }, bb4, bb5 bb4: jmp bb1 bb1: v2 = imm 0x0 - store.i8 [sim + 41], v2 + store.i8 [sim + 49], v2 jmp bb3 bb5: jmp bb2 bb2: - v3 = load.i8 [sim + 42] - store.i8 [sim + 41], v3 + v3 = load.i8 [sim + 50] + store.i8 [sim + 49], v3 jmp bb3 bb3: ret --- MIR after allocation-owned scheduling, before spill reconstruction --- bb0: - v0 = load.i8 [sim + 40] + v0 = load.i8 [sim + 48] br_pred CompareImm { lhs: v0, imm: 0, kind: Eq }, bb4, bb5 bb4: jmp bb1 bb1: v2 = imm 0x0 - store.i8 [sim + 41], v2 + store.i8 [sim + 49], v2 jmp bb3 bb5: jmp bb2 bb2: - v3 = load.i8 [sim + 42] - store.i8 [sim + 41], v3 + v3 = load.i8 [sim + 50] + store.i8 [sim + 49], v3 jmp bb3 bb3: ret --- MIR after register allocation and post-RA peepholes --- bb0: - v0 = load.i8 [sim + 40] + v0 = load.i8 [sim + 48] br_pred CompareImm { lhs: v0, imm: 0, kind: Eq }, bb1, bb2 bb1: v2 = imm 0x0 - store.i8 [sim + 41], v2 + store.i8 [sim + 49], v2 jmp bb3 bb2: - v3 = load.i8 [sim + 42] - store.i8 [sim + 41], v3 + v3 = load.i8 [sim + 50] + store.i8 [sim + 49], v3 jmp bb3 bb3: ret @@ -250,16 +250,16 @@ x86-64 disassembly of emitted function: 0x00000022 movq xmm15,rax 0x00000027 nop bb0: - 0x00000028 movzx eax,byte [gs:28h] + 0x00000028 movzx eax,byte [gs:30h] 0x00000031 test rax,rax 0x00000034 je short 000000000000004Ah bb2: - 0x00000036 movzx eax,byte [gs:2Ah] - 0x0000003f mov [gs:29h],al + 0x00000036 movzx eax,byte [gs:32h] + 0x0000003f mov [gs:31h],al 0x00000048 jmp short 0000000000000055h bb1: 0x0000004a xor eax,eax - 0x0000004c mov [gs:29h],al + 0x0000004c mov [gs:31h],al bb3: 0x00000055 movq rax,xmm15 0x0000005a dec rax @@ -279,74 +279,74 @@ Bindings: eval_only_ff trigger=rst --- MIR after main optimization, before regalloc-owned late folds --- bb0: - v4 = load.i8 [sim + 41] - store.i8 [sim + 48], v4 - v0 = load.i8 [sim + 40] + v4 = load.i8 [sim + 49] + store.i8 [sim + 56], v4 + v0 = load.i8 [sim + 48] v1 = cmp.Eq v0, 0 br v1, bb1, bb2 bb1: v2 = imm 0x0 - store.i8 [sim + 48], v2 + store.i8 [sim + 56], v2 jmp bb3 bb2: - v3 = load.i8 [sim + 42] - store.i8 [sim + 48], v3 + v3 = load.i8 [sim + 50] + store.i8 [sim + 56], v3 jmp bb3 bb3: ret --- MIR after late memory folds, before allocation-owned scheduling --- bb0: - v4 = load.i8 [sim + 41] - store.i8 [sim + 48], v4 - v0 = load.i8 [sim + 40] + v4 = load.i8 [sim + 49] + store.i8 [sim + 56], v4 + v0 = load.i8 [sim + 48] br_pred CompareImm { lhs: v0, imm: 0, kind: Eq }, bb4, bb5 bb4: jmp bb1 bb1: v2 = imm 0x0 - store.i8 [sim + 48], v2 + store.i8 [sim + 56], v2 jmp bb3 bb5: jmp bb2 bb2: - v3 = load.i8 [sim + 42] - store.i8 [sim + 48], v3 + v3 = load.i8 [sim + 50] + store.i8 [sim + 56], v3 jmp bb3 bb3: ret --- MIR after allocation-owned scheduling, before spill reconstruction --- bb0: - v4 = load.i8 [sim + 41] - store.i8 [sim + 48], v4 - v0 = load.i8 [sim + 40] + v4 = load.i8 [sim + 49] + store.i8 [sim + 56], v4 + v0 = load.i8 [sim + 48] br_pred CompareImm { lhs: v0, imm: 0, kind: Eq }, bb4, bb5 bb4: jmp bb1 bb1: v2 = imm 0x0 - store.i8 [sim + 48], v2 + store.i8 [sim + 56], v2 jmp bb3 bb5: jmp bb2 bb2: - v3 = load.i8 [sim + 42] - store.i8 [sim + 48], v3 + v3 = load.i8 [sim + 50] + store.i8 [sim + 56], v3 jmp bb3 bb3: ret --- MIR after register allocation and post-RA peepholes --- bb0: - v4 = load.i8 [sim + 41] - store.i8 [sim + 48], v4 - v0 = load.i8 [sim + 40] + v4 = load.i8 [sim + 49] + store.i8 [sim + 56], v4 + v0 = load.i8 [sim + 48] br_pred CompareImm { lhs: v0, imm: 0, kind: Eq }, bb1, bb2 bb1: v2 = imm 0x0 - store.i8 [sim + 48], v2 + store.i8 [sim + 56], v2 jmp bb3 bb2: - v3 = load.i8 [sim + 42] - store.i8 [sim + 48], v3 + v3 = load.i8 [sim + 50] + store.i8 [sim + 56], v3 jmp bb3 bb3: ret @@ -361,18 +361,18 @@ x86-64 disassembly of emitted function: 0x00000005 movq xmm15,rax 0x0000000a wrgsbase rdi bb0: - 0x0000000f movzx eax,byte [gs:29h] - 0x00000018 mov [gs:30h],al - 0x00000021 movzx eax,byte [gs:28h] + 0x0000000f movzx eax,byte [gs:31h] + 0x00000018 mov [gs:38h],al + 0x00000021 movzx eax,byte [gs:30h] 0x0000002a test rax,rax 0x0000002d je short 0000000000000043h bb2: - 0x0000002f movzx eax,byte [gs:2Ah] - 0x00000038 mov [gs:30h],al + 0x0000002f movzx eax,byte [gs:32h] + 0x00000038 mov [gs:38h],al 0x00000041 jmp short 000000000000004Eh bb1: 0x00000043 xor eax,eax - 0x00000045 mov [gs:30h],al + 0x00000045 mov [gs:38h],al bb3: 0x0000004e xor eax,eax 0x00000050 jmp short 0000000000000052h diff --git a/crates/celox/tests/snapshots/native_mir__high_pressure_comb_mir.snap b/crates/celox/tests/snapshots/native_mir__high_pressure_comb_mir.snap index 604258b2507..707a4df3037 100644 --- a/crates/celox/tests/snapshots/native_mir__high_pressure_comb_mir.snap +++ b/crates/celox/tests/snapshots/native_mir__high_pressure_comb_mir.snap @@ -6,29 +6,29 @@ expression: output === Native function eval_comb === --- MIR after main optimization, before regalloc-owned late folds --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] - v2 = load.i32 [sim + 48] - v3 = load.i32 [sim + 52] - v4 = load.i32 [sim + 56] - v5 = load.i32 [sim + 60] - v6 = load.i32 [sim + 64] - v7 = load.i32 [sim + 68] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] + v2 = load.i32 [sim + 56] + v3 = load.i32 [sim + 60] + v4 = load.i32 [sim + 64] + v5 = load.i32 [sim + 68] + v6 = load.i32 [sim + 72] + v7 = load.i32 [sim + 76] v16 = add.w32 v0, v1 - v8 = load.i32 [sim + 72] - v9 = load.i32 [sim + 76] + v8 = load.i32 [sim + 80] + v9 = load.i32 [sim + 84] v17 = add.w32 v16, v2 - v10 = load.i32 [sim + 80] + v10 = load.i32 [sim + 88] v18 = add.w32 v17, v3 - v11 = load.i32 [sim + 84] + v11 = load.i32 [sim + 92] v19 = add.w32 v18, v4 - v12 = load.i32 [sim + 88] + v12 = load.i32 [sim + 96] v20 = add.w32 v19, v5 - v13 = load.i32 [sim + 92] + v13 = load.i32 [sim + 100] v21 = add.w32 v20, v6 - v14 = load.i32 [sim + 96] + v14 = load.i32 [sim + 104] v22 = add.w32 v21, v7 - v15 = load.i32 [sim + 100] + v15 = load.i32 [sim + 108] v23 = add.w32 v22, v8 v24 = add.w32 v23, v9 v25 = add.w32 v24, v10 @@ -37,33 +37,33 @@ bb0: v28 = add.w32 v27, v13 v29 = add.w32 v28, v14 v30 = add.w32 v29, v15 - store.i32 [sim + 104], v30 + store.i32 [sim + 112], v30 ret --- MIR after late memory folds, before allocation-owned scheduling --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] - v2 = load.i32 [sim + 48] - v3 = load.i32 [sim + 52] - v4 = load.i32 [sim + 56] - v5 = load.i32 [sim + 60] - v6 = load.i32 [sim + 64] - v7 = load.i32 [sim + 68] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] + v2 = load.i32 [sim + 56] + v3 = load.i32 [sim + 60] + v4 = load.i32 [sim + 64] + v5 = load.i32 [sim + 68] + v6 = load.i32 [sim + 72] + v7 = load.i32 [sim + 76] v16 = add.w32 v0, v1 - v8 = load.i32 [sim + 72] - v9 = load.i32 [sim + 76] + v8 = load.i32 [sim + 80] + v9 = load.i32 [sim + 84] v17 = add.w32 v16, v2 - v10 = load.i32 [sim + 80] + v10 = load.i32 [sim + 88] v18 = add.w32 v17, v3 - v11 = load.i32 [sim + 84] + v11 = load.i32 [sim + 92] v19 = add.w32 v18, v4 - v12 = load.i32 [sim + 88] + v12 = load.i32 [sim + 96] v20 = add.w32 v19, v5 - v13 = load.i32 [sim + 92] + v13 = load.i32 [sim + 100] v21 = add.w32 v20, v6 - v14 = load.i32 [sim + 96] + v14 = load.i32 [sim + 104] v22 = add.w32 v21, v7 - v15 = load.i32 [sim + 100] + v15 = load.i32 [sim + 108] v23 = add.w32 v22, v8 v24 = add.w32 v23, v9 v25 = add.w32 v24, v10 @@ -72,77 +72,77 @@ bb0: v28 = add.w32 v27, v13 v29 = add.w32 v28, v14 v30 = add.w32 v29, v15 - store.i32 [sim + 104], v30 + store.i32 [sim + 112], v30 ret --- MIR after allocation-owned scheduling, before spill reconstruction --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] v16 = add.w32 v0, v1 - v2 = load.i32 [sim + 48] + v2 = load.i32 [sim + 56] v17 = add.w32 v16, v2 - v3 = load.i32 [sim + 52] + v3 = load.i32 [sim + 60] v18 = add.w32 v17, v3 - v4 = load.i32 [sim + 56] + v4 = load.i32 [sim + 64] v19 = add.w32 v18, v4 - v5 = load.i32 [sim + 60] + v5 = load.i32 [sim + 68] v20 = add.w32 v19, v5 - v6 = load.i32 [sim + 64] + v6 = load.i32 [sim + 72] v21 = add.w32 v20, v6 - v7 = load.i32 [sim + 68] + v7 = load.i32 [sim + 76] v22 = add.w32 v21, v7 - v8 = load.i32 [sim + 72] + v8 = load.i32 [sim + 80] v23 = add.w32 v22, v8 - v9 = load.i32 [sim + 76] + v9 = load.i32 [sim + 84] v24 = add.w32 v23, v9 - v10 = load.i32 [sim + 80] + v10 = load.i32 [sim + 88] v25 = add.w32 v24, v10 - v11 = load.i32 [sim + 84] + v11 = load.i32 [sim + 92] v26 = add.w32 v25, v11 - v12 = load.i32 [sim + 88] + v12 = load.i32 [sim + 96] v27 = add.w32 v26, v12 - v13 = load.i32 [sim + 92] + v13 = load.i32 [sim + 100] v28 = add.w32 v27, v13 - v14 = load.i32 [sim + 96] + v14 = load.i32 [sim + 104] v29 = add.w32 v28, v14 - v15 = load.i32 [sim + 100] + v15 = load.i32 [sim + 108] v30 = add.w32 v29, v15 - store.i32 [sim + 104], v30 + store.i32 [sim + 112], v30 ret --- MIR after register allocation and post-RA peepholes --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] v16 = add.w32 v0, v1 - v2 = load.i32 [sim + 48] + v2 = load.i32 [sim + 56] v17 = add.w32 v16, v2 - v3 = load.i32 [sim + 52] + v3 = load.i32 [sim + 60] v18 = add.w32 v17, v3 - v4 = load.i32 [sim + 56] + v4 = load.i32 [sim + 64] v19 = add.w32 v18, v4 - v5 = load.i32 [sim + 60] + v5 = load.i32 [sim + 68] v20 = add.w32 v19, v5 - v6 = load.i32 [sim + 64] + v6 = load.i32 [sim + 72] v21 = add.w32 v20, v6 - v7 = load.i32 [sim + 68] + v7 = load.i32 [sim + 76] v22 = add.w32 v21, v7 - v8 = load.i32 [sim + 72] + v8 = load.i32 [sim + 80] v23 = add.w32 v22, v8 - v9 = load.i32 [sim + 76] + v9 = load.i32 [sim + 84] v24 = add.w32 v23, v9 - v10 = load.i32 [sim + 80] + v10 = load.i32 [sim + 88] v25 = add.w32 v24, v10 - v11 = load.i32 [sim + 84] + v11 = load.i32 [sim + 92] v26 = add.w32 v25, v11 - v12 = load.i32 [sim + 88] + v12 = load.i32 [sim + 96] v27 = add.w32 v26, v12 - v13 = load.i32 [sim + 92] + v13 = load.i32 [sim + 100] v28 = add.w32 v27, v13 - v14 = load.i32 [sim + 96] + v14 = load.i32 [sim + 104] v29 = add.w32 v28, v14 - v15 = load.i32 [sim + 100] + v15 = load.i32 [sim + 108] v30 = add.w32 v29, v15 - store.i32 [sim + 104], v30 + store.i32 [sim + 112], v30 ret Spill frame: 0 bytes Register assignment: @@ -182,38 +182,38 @@ x86-64 disassembly of emitted function: 0x00000005 movq xmm15,rax 0x0000000a wrgsbase rdi bb0: - 0x0000000f mov eax,[gs:28h] - 0x00000018 mov edx,[gs:2Ch] + 0x0000000f mov eax,[gs:30h] + 0x00000018 mov edx,[gs:34h] 0x00000020 add eax,edx - 0x00000022 mov edx,[gs:30h] + 0x00000022 mov edx,[gs:38h] 0x0000002a add eax,edx - 0x0000002c mov edx,[gs:34h] + 0x0000002c mov edx,[gs:3Ch] 0x00000034 add eax,edx - 0x00000036 mov edx,[gs:38h] + 0x00000036 mov edx,[gs:40h] 0x0000003e add eax,edx - 0x00000040 mov edx,[gs:3Ch] + 0x00000040 mov edx,[gs:44h] 0x00000048 add eax,edx - 0x0000004a mov edx,[gs:40h] + 0x0000004a mov edx,[gs:48h] 0x00000052 add eax,edx - 0x00000054 mov edx,[gs:44h] + 0x00000054 mov edx,[gs:4Ch] 0x0000005c add eax,edx - 0x0000005e mov edx,[gs:48h] + 0x0000005e mov edx,[gs:50h] 0x00000066 add eax,edx - 0x00000068 mov edx,[gs:4Ch] + 0x00000068 mov edx,[gs:54h] 0x00000070 add eax,edx - 0x00000072 mov edx,[gs:50h] + 0x00000072 mov edx,[gs:58h] 0x0000007a add eax,edx - 0x0000007c mov edx,[gs:54h] + 0x0000007c mov edx,[gs:5Ch] 0x00000084 add eax,edx - 0x00000086 mov edx,[gs:58h] + 0x00000086 mov edx,[gs:60h] 0x0000008e add eax,edx - 0x00000090 mov edx,[gs:5Ch] + 0x00000090 mov edx,[gs:64h] 0x00000098 add eax,edx - 0x0000009a mov edx,[gs:60h] + 0x0000009a mov edx,[gs:68h] 0x000000a2 add eax,edx - 0x000000a4 mov edx,[gs:64h] + 0x000000a4 mov edx,[gs:6Ch] 0x000000ac add eax,edx - 0x000000ae mov [gs:68h],eax + 0x000000ae mov [gs:70h],eax 0x000000b7 xor eax,eax 0x000000b9 jmp short 00000000000000BBh 0x000000bb movq r11,xmm15 diff --git a/crates/celox/tests/snapshots/native_mir__large_comb_pressure_mir.snap b/crates/celox/tests/snapshots/native_mir__large_comb_pressure_mir.snap index dae839024ea..f2b69780892 100644 --- a/crates/celox/tests/snapshots/native_mir__large_comb_pressure_mir.snap +++ b/crates/celox/tests/snapshots/native_mir__large_comb_pressure_mir.snap @@ -6,37 +6,37 @@ expression: output === Native function eval_comb === --- MIR after main optimization, before regalloc-owned late folds --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] - v3 = load.i32 [sim + 48] - v5 = load.i32 [sim + 52] - v7 = load.i32 [sim + 56] - v9 = load.i32 [sim + 60] - v11 = load.i32 [sim + 64] - v13 = load.i32 [sim + 68] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] + v3 = load.i32 [sim + 56] + v5 = load.i32 [sim + 60] + v7 = load.i32 [sim + 64] + v9 = load.i32 [sim + 68] + v11 = load.i32 [sim + 72] + v13 = load.i32 [sim + 76] v2 = xor.w32 v0, v1 - v15 = load.i32 [sim + 72] - v17 = load.i32 [sim + 76] + v15 = load.i32 [sim + 80] + v17 = load.i32 [sim + 84] v4 = xor.w32 v2, v3 - v19 = load.i32 [sim + 80] + v19 = load.i32 [sim + 88] v6 = xor.w32 v4, v5 - v21 = load.i32 [sim + 84] + v21 = load.i32 [sim + 92] v8 = xor.w32 v6, v7 - v23 = load.i32 [sim + 88] + v23 = load.i32 [sim + 96] v10 = xor.w32 v8, v9 - v25 = load.i32 [sim + 92] + v25 = load.i32 [sim + 100] v12 = xor.w32 v10, v11 - v27 = load.i32 [sim + 96] + v27 = load.i32 [sim + 104] v14 = xor.w32 v12, v13 - v29 = load.i32 [sim + 100] + v29 = load.i32 [sim + 108] v16 = xor.w32 v14, v15 - v31 = load.i32 [sim + 104] + v31 = load.i32 [sim + 112] v18 = xor.w32 v16, v17 - v33 = load.i32 [sim + 108] + v33 = load.i32 [sim + 116] v20 = xor.w32 v18, v19 - v35 = load.i32 [sim + 112] + v35 = load.i32 [sim + 120] v22 = xor.w32 v20, v21 - v37 = load.i32 [sim + 116] + v37 = load.i32 [sim + 124] v24 = xor.w32 v22, v23 v26 = xor.w32 v24, v25 v28 = xor.w32 v26, v27 @@ -45,81 +45,81 @@ bb0: v34 = xor.w32 v32, v33 v36 = xor.w32 v34, v35 v38 = xor.w32 v36, v37 - store.i32 [sim + 120], v38 + store.i32 [sim + 128], v38 v39 = add.w32 v38, v0 - store.i32 [sim + 124], v39 + store.i32 [sim + 132], v39 v40 = add.w32 v38, v1 - store.i32 [sim + 128], v40 + store.i32 [sim + 136], v40 v41 = add.w32 v38, v3 - store.i32 [sim + 132], v41 + store.i32 [sim + 140], v41 v42 = add.w32 v38, v5 - store.i32 [sim + 136], v42 + store.i32 [sim + 144], v42 v43 = add.w32 v38, v7 - store.i32 [sim + 140], v43 + store.i32 [sim + 148], v43 v44 = add.w32 v38, v9 - store.i32 [sim + 144], v44 + store.i32 [sim + 152], v44 v45 = add.w32 v38, v11 - store.i32 [sim + 148], v45 + store.i32 [sim + 156], v45 v46 = add.w32 v38, v13 - store.i32 [sim + 152], v46 + store.i32 [sim + 160], v46 v47 = add.w32 v38, v15 - store.i32 [sim + 156], v47 + store.i32 [sim + 164], v47 v48 = add.w32 v38, v17 - store.i32 [sim + 160], v48 + store.i32 [sim + 168], v48 v49 = add.w32 v38, v19 - store.i32 [sim + 164], v49 + store.i32 [sim + 172], v49 v50 = add.w32 v38, v21 - store.i32 [sim + 168], v50 + store.i32 [sim + 176], v50 v51 = add.w32 v38, v23 - store.i32 [sim + 172], v51 + store.i32 [sim + 180], v51 v52 = add.w32 v38, v25 - store.i32 [sim + 176], v52 + store.i32 [sim + 184], v52 v53 = add.w32 v38, v27 - store.i32 [sim + 180], v53 + store.i32 [sim + 188], v53 v54 = add.w32 v38, v29 - store.i32 [sim + 184], v54 + store.i32 [sim + 192], v54 v55 = add.w32 v38, v31 - store.i32 [sim + 188], v55 + store.i32 [sim + 196], v55 v56 = add.w32 v38, v33 - store.i32 [sim + 192], v56 + store.i32 [sim + 200], v56 v57 = add.w32 v38, v35 - store.i32 [sim + 196], v57 + store.i32 [sim + 204], v57 v58 = add.w32 v38, v37 - store.i32 [sim + 200], v58 + store.i32 [sim + 208], v58 ret --- MIR after late memory folds, before allocation-owned scheduling --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] - v3 = load.i32 [sim + 48] - v5 = load.i32 [sim + 52] - v7 = load.i32 [sim + 56] - v9 = load.i32 [sim + 60] - v11 = load.i32 [sim + 64] - v13 = load.i32 [sim + 68] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] + v3 = load.i32 [sim + 56] + v5 = load.i32 [sim + 60] + v7 = load.i32 [sim + 64] + v9 = load.i32 [sim + 68] + v11 = load.i32 [sim + 72] + v13 = load.i32 [sim + 76] v2 = xor.w32 v0, v1 - v15 = load.i32 [sim + 72] - v17 = load.i32 [sim + 76] + v15 = load.i32 [sim + 80] + v17 = load.i32 [sim + 84] v4 = xor.w32 v2, v3 - v19 = load.i32 [sim + 80] + v19 = load.i32 [sim + 88] v6 = xor.w32 v4, v5 - v21 = load.i32 [sim + 84] + v21 = load.i32 [sim + 92] v8 = xor.w32 v6, v7 - v23 = load.i32 [sim + 88] + v23 = load.i32 [sim + 96] v10 = xor.w32 v8, v9 - v25 = load.i32 [sim + 92] + v25 = load.i32 [sim + 100] v12 = xor.w32 v10, v11 - v27 = load.i32 [sim + 96] + v27 = load.i32 [sim + 104] v14 = xor.w32 v12, v13 - v29 = load.i32 [sim + 100] + v29 = load.i32 [sim + 108] v16 = xor.w32 v14, v15 - v31 = load.i32 [sim + 104] + v31 = load.i32 [sim + 112] v18 = xor.w32 v16, v17 - v33 = load.i32 [sim + 108] + v33 = load.i32 [sim + 116] v20 = xor.w32 v18, v19 - v35 = load.i32 [sim + 112] + v35 = load.i32 [sim + 120] v22 = xor.w32 v20, v21 - v37 = load.i32 [sim + 116] + v37 = load.i32 [sim + 124] v24 = xor.w32 v22, v23 v26 = xor.w32 v24, v25 v28 = xor.w32 v26, v27 @@ -128,220 +128,220 @@ bb0: v34 = xor.w32 v32, v33 v36 = xor.w32 v34, v35 v38 = xor.w32 v36, v37 - store.i32 [sim + 120], v38 + store.i32 [sim + 128], v38 v39 = add.w32 v38, v0 - store.i32 [sim + 124], v39 + store.i32 [sim + 132], v39 v40 = add.w32 v38, v1 - store.i32 [sim + 128], v40 + store.i32 [sim + 136], v40 v41 = add.w32 v38, v3 - store.i32 [sim + 132], v41 + store.i32 [sim + 140], v41 v42 = add.w32 v38, v5 - store.i32 [sim + 136], v42 + store.i32 [sim + 144], v42 v43 = add.w32 v38, v7 - store.i32 [sim + 140], v43 + store.i32 [sim + 148], v43 v44 = add.w32 v38, v9 - store.i32 [sim + 144], v44 + store.i32 [sim + 152], v44 v45 = add.w32 v38, v11 - store.i32 [sim + 148], v45 + store.i32 [sim + 156], v45 v46 = add.w32 v38, v13 - store.i32 [sim + 152], v46 + store.i32 [sim + 160], v46 v47 = add.w32 v38, v15 - store.i32 [sim + 156], v47 + store.i32 [sim + 164], v47 v48 = add.w32 v38, v17 - store.i32 [sim + 160], v48 + store.i32 [sim + 168], v48 v49 = add.w32 v38, v19 - store.i32 [sim + 164], v49 + store.i32 [sim + 172], v49 v50 = add.w32 v38, v21 - store.i32 [sim + 168], v50 + store.i32 [sim + 176], v50 v51 = add.w32 v38, v23 - store.i32 [sim + 172], v51 + store.i32 [sim + 180], v51 v52 = add.w32 v38, v25 - store.i32 [sim + 176], v52 + store.i32 [sim + 184], v52 v53 = add.w32 v38, v27 - store.i32 [sim + 180], v53 + store.i32 [sim + 188], v53 v54 = add.w32 v38, v29 - store.i32 [sim + 184], v54 + store.i32 [sim + 192], v54 v55 = add.w32 v38, v31 - store.i32 [sim + 188], v55 + store.i32 [sim + 196], v55 v56 = add.w32 v38, v33 - store.i32 [sim + 192], v56 + store.i32 [sim + 200], v56 v57 = add.w32 v38, v35 - store.i32 [sim + 196], v57 + store.i32 [sim + 204], v57 v58 = add.w32 v38, v37 - store.i32 [sim + 200], v58 + store.i32 [sim + 208], v58 ret --- MIR after allocation-owned scheduling, before spill reconstruction --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] v2 = xor.w32 v0, v1 - v3 = load.i32 [sim + 48] + v3 = load.i32 [sim + 56] v4 = xor.w32 v2, v3 - v5 = load.i32 [sim + 52] + v5 = load.i32 [sim + 60] v6 = xor.w32 v4, v5 - v7 = load.i32 [sim + 56] + v7 = load.i32 [sim + 64] v8 = xor.w32 v6, v7 - v9 = load.i32 [sim + 60] + v9 = load.i32 [sim + 68] v10 = xor.w32 v8, v9 - v11 = load.i32 [sim + 64] + v11 = load.i32 [sim + 72] v12 = xor.w32 v10, v11 - v13 = load.i32 [sim + 68] + v13 = load.i32 [sim + 76] v14 = xor.w32 v12, v13 - v15 = load.i32 [sim + 72] + v15 = load.i32 [sim + 80] v16 = xor.w32 v14, v15 - v17 = load.i32 [sim + 76] + v17 = load.i32 [sim + 84] v18 = xor.w32 v16, v17 - v19 = load.i32 [sim + 80] + v19 = load.i32 [sim + 88] v20 = xor.w32 v18, v19 - v21 = load.i32 [sim + 84] + v21 = load.i32 [sim + 92] v22 = xor.w32 v20, v21 - v23 = load.i32 [sim + 88] + v23 = load.i32 [sim + 96] v24 = xor.w32 v22, v23 - v25 = load.i32 [sim + 92] + v25 = load.i32 [sim + 100] v26 = xor.w32 v24, v25 - v27 = load.i32 [sim + 96] + v27 = load.i32 [sim + 104] v28 = xor.w32 v26, v27 - v29 = load.i32 [sim + 100] + v29 = load.i32 [sim + 108] v30 = xor.w32 v28, v29 - v31 = load.i32 [sim + 104] + v31 = load.i32 [sim + 112] v32 = xor.w32 v30, v31 - v33 = load.i32 [sim + 108] + v33 = load.i32 [sim + 116] v34 = xor.w32 v32, v33 - v35 = load.i32 [sim + 112] + v35 = load.i32 [sim + 120] v36 = xor.w32 v34, v35 - v37 = load.i32 [sim + 116] + v37 = load.i32 [sim + 124] v38 = xor.w32 v36, v37 - store.i32 [sim + 120], v38 + store.i32 [sim + 128], v38 v39 = add.w32 v38, v0 - store.i32 [sim + 124], v39 + store.i32 [sim + 132], v39 v40 = add.w32 v38, v1 - store.i32 [sim + 128], v40 + store.i32 [sim + 136], v40 v41 = add.w32 v38, v3 - store.i32 [sim + 132], v41 + store.i32 [sim + 140], v41 v42 = add.w32 v38, v5 - store.i32 [sim + 136], v42 + store.i32 [sim + 144], v42 v43 = add.w32 v38, v7 - store.i32 [sim + 140], v43 + store.i32 [sim + 148], v43 v44 = add.w32 v38, v9 - store.i32 [sim + 144], v44 + store.i32 [sim + 152], v44 v45 = add.w32 v38, v11 - store.i32 [sim + 148], v45 + store.i32 [sim + 156], v45 v46 = add.w32 v38, v13 - store.i32 [sim + 152], v46 + store.i32 [sim + 160], v46 v47 = add.w32 v38, v15 - store.i32 [sim + 156], v47 + store.i32 [sim + 164], v47 v48 = add.w32 v38, v17 - store.i32 [sim + 160], v48 + store.i32 [sim + 168], v48 v49 = add.w32 v38, v19 - store.i32 [sim + 164], v49 + store.i32 [sim + 172], v49 v50 = add.w32 v38, v21 - store.i32 [sim + 168], v50 + store.i32 [sim + 176], v50 v51 = add.w32 v38, v23 - store.i32 [sim + 172], v51 + store.i32 [sim + 180], v51 v52 = add.w32 v38, v25 - store.i32 [sim + 176], v52 + store.i32 [sim + 184], v52 v53 = add.w32 v38, v27 - store.i32 [sim + 180], v53 + store.i32 [sim + 188], v53 v54 = add.w32 v38, v29 - store.i32 [sim + 184], v54 + store.i32 [sim + 192], v54 v55 = add.w32 v38, v31 - store.i32 [sim + 188], v55 + store.i32 [sim + 196], v55 v56 = add.w32 v38, v33 - store.i32 [sim + 192], v56 + store.i32 [sim + 200], v56 v57 = add.w32 v38, v35 - store.i32 [sim + 196], v57 + store.i32 [sim + 204], v57 v58 = add.w32 v38, v37 - store.i32 [sim + 200], v58 + store.i32 [sim + 208], v58 ret --- MIR after register allocation and post-RA peepholes --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] v2 = xor.w32 v0, v1 - v3 = load.i32 [sim + 48] + v3 = load.i32 [sim + 56] v4 = xor.w32 v2, v3 - v5 = load.i32 [sim + 52] + v5 = load.i32 [sim + 60] v6 = xor.w32 v4, v5 - v7 = load.i32 [sim + 56] + v7 = load.i32 [sim + 64] v8 = xor.w32 v6, v7 - v9 = load.i32 [sim + 60] + v9 = load.i32 [sim + 68] v10 = xor.w32 v8, v9 - v11 = load.i32 [sim + 64] + v11 = load.i32 [sim + 72] v12 = xor.w32 v10, v11 - v13 = load.i32 [sim + 68] + v13 = load.i32 [sim + 76] v14 = xor.w32 v12, v13 - v15 = load.i32 [sim + 72] + v15 = load.i32 [sim + 80] v16 = xor.w32 v14, v15 - v17 = load.i32 [sim + 76] + v17 = load.i32 [sim + 84] v18 = xor.w32 v16, v17 - v19 = load.i32 [sim + 80] + v19 = load.i32 [sim + 88] v20 = xor.w32 v18, v19 - v21 = load.i32 [sim + 84] + v21 = load.i32 [sim + 92] v22 = xor.w32 v20, v21 - v23 = load.i32 [sim + 88] + v23 = load.i32 [sim + 96] v24 = xor.w32 v22, v23 - v25 = load.i32 [sim + 92] + v25 = load.i32 [sim + 100] v26 = xor.w32 v24, v25 - v27 = load.i32 [sim + 96] + v27 = load.i32 [sim + 104] v28 = xor.w32 v26, v27 - v29 = load.i32 [sim + 100] + v29 = load.i32 [sim + 108] v30 = xor.w32 v28, v29 - v31 = load.i32 [sim + 104] + v31 = load.i32 [sim + 112] v32 = xor.w32 v30, v31 - v33 = load.i32 [sim + 108] + v33 = load.i32 [sim + 116] v34 = xor.w32 v32, v33 - v35 = load.i32 [sim + 112] + v35 = load.i32 [sim + 120] v36 = xor.w32 v34, v35 - v37 = load.i32 [sim + 116] + v37 = load.i32 [sim + 124] v38 = xor.w32 v36, v37 - store.i32 [sim + 120], v38 + store.i32 [sim + 128], v38 v39 = add.w32 v38, v0 - store.i32 [sim + 124], v39 + store.i32 [sim + 132], v39 v40 = add.w32 v38, v1 - store.i32 [sim + 128], v40 + store.i32 [sim + 136], v40 v41 = add.w32 v38, v3 - store.i32 [sim + 132], v41 + store.i32 [sim + 140], v41 v42 = add.w32 v38, v5 - store.i32 [sim + 136], v42 + store.i32 [sim + 144], v42 v43 = add.w32 v38, v7 - store.i32 [sim + 140], v43 + store.i32 [sim + 148], v43 v44 = add.w32 v38, v9 - store.i32 [sim + 144], v44 + store.i32 [sim + 152], v44 v45 = add.w32 v38, v11 - store.i32 [sim + 148], v45 + store.i32 [sim + 156], v45 v46 = add.w32 v38, v13 - store.i32 [sim + 152], v46 + store.i32 [sim + 160], v46 v47 = add.w32 v38, v15 - store.i32 [sim + 156], v47 + store.i32 [sim + 164], v47 v48 = add.w32 v38, v17 - store.i32 [sim + 160], v48 + store.i32 [sim + 168], v48 v49 = add.w32 v38, v19 - store.i32 [sim + 164], v49 + store.i32 [sim + 172], v49 v50 = add.w32 v38, v21 - store.i32 [sim + 168], v50 - v59 = load.i32 [sim + 88] + store.i32 [sim + 176], v50 + v59 = load.i32 [sim + 96] v51 = add.w32 v38, v59 - store.i32 [sim + 172], v51 - v60 = load.i32 [sim + 92] + store.i32 [sim + 180], v51 + v60 = load.i32 [sim + 100] v52 = add.w32 v38, v60 - store.i32 [sim + 176], v52 - v61 = load.i32 [sim + 96] + store.i32 [sim + 184], v52 + v61 = load.i32 [sim + 104] v53 = add.w32 v38, v61 - store.i32 [sim + 180], v53 - v62 = load.i32 [sim + 100] + store.i32 [sim + 188], v53 + v62 = load.i32 [sim + 108] v54 = add.w32 v38, v62 - store.i32 [sim + 184], v54 - v63 = load.i32 [sim + 104] + store.i32 [sim + 192], v54 + v63 = load.i32 [sim + 112] v55 = add.w32 v38, v63 - store.i32 [sim + 188], v55 - v64 = load.i32 [sim + 108] + store.i32 [sim + 196], v55 + v64 = load.i32 [sim + 116] v56 = add.w32 v38, v64 - store.i32 [sim + 192], v56 - v65 = load.i32 [sim + 112] + store.i32 [sim + 200], v56 + v65 = load.i32 [sim + 120] v57 = add.w32 v38, v65 - store.i32 [sim + 196], v57 + store.i32 [sim + 204], v57 v58 = add.w32 v38, v37 - store.i32 [sim + 200], v58 + store.i32 [sim + 208], v58 ret Spill frame: 0 bytes Register assignment: @@ -421,94 +421,94 @@ x86-64 disassembly of emitted function: 0x0000001e movq xmm13,r14 0x00000023 wrgsbase rdi bb0: - 0x00000028 mov eax,[gs:28h] - 0x00000031 mov edx,[gs:2Ch] + 0x00000028 mov eax,[gs:30h] + 0x00000031 mov edx,[gs:34h] 0x00000039 mov esi,eax 0x0000003b xor esi,edx - 0x0000003d mov edi,[gs:30h] + 0x0000003d mov edi,[gs:38h] 0x00000045 xor esi,edi - 0x00000047 mov r8d,[gs:34h] + 0x00000047 mov r8d,[gs:3Ch] 0x00000050 xor esi,r8d - 0x00000053 mov r9d,[gs:38h] + 0x00000053 mov r9d,[gs:40h] 0x0000005c xor esi,r9d - 0x0000005f mov r10d,[gs:3Ch] + 0x0000005f mov r10d,[gs:44h] 0x00000068 xor esi,r10d - 0x0000006b mov r11d,[gs:40h] + 0x0000006b mov r11d,[gs:48h] 0x00000074 xor esi,r11d - 0x00000077 mov ecx,[gs:44h] + 0x00000077 mov ecx,[gs:4Ch] 0x0000007f xor esi,ecx - 0x00000081 mov ebx,[gs:48h] + 0x00000081 mov ebx,[gs:50h] 0x00000089 xor esi,ebx - 0x0000008b mov ebp,[gs:4Ch] + 0x0000008b mov ebp,[gs:54h] 0x00000093 xor esi,ebp - 0x00000095 mov r12d,[gs:50h] + 0x00000095 mov r12d,[gs:58h] 0x0000009e xor esi,r12d - 0x000000a1 mov r13d,[gs:54h] + 0x000000a1 mov r13d,[gs:5Ch] 0x000000aa xor esi,r13d - 0x000000ad mov r14d,[gs:58h] + 0x000000ad mov r14d,[gs:60h] 0x000000b6 xor esi,r14d - 0x000000b9 mov r14d,[gs:5Ch] + 0x000000b9 mov r14d,[gs:64h] 0x000000c2 xor esi,r14d - 0x000000c5 mov r14d,[gs:60h] + 0x000000c5 mov r14d,[gs:68h] 0x000000ce xor esi,r14d - 0x000000d1 mov r14d,[gs:64h] + 0x000000d1 mov r14d,[gs:6Ch] 0x000000da xor esi,r14d - 0x000000dd mov r14d,[gs:68h] + 0x000000dd mov r14d,[gs:70h] 0x000000e6 xor esi,r14d - 0x000000e9 mov r14d,[gs:6Ch] + 0x000000e9 mov r14d,[gs:74h] 0x000000f2 xor esi,r14d - 0x000000f5 mov r14d,[gs:70h] + 0x000000f5 mov r14d,[gs:78h] 0x000000fe xor esi,r14d - 0x00000101 mov r14d,[gs:74h] + 0x00000101 mov r14d,[gs:7Ch] 0x0000010a xor esi,r14d - 0x0000010d mov [gs:78h],esi + 0x0000010d mov [gs:80h],esi 0x00000115 add eax,esi - 0x00000117 mov [gs:7Ch],eax + 0x00000117 mov [gs:84h],eax 0x00000120 add edx,esi - 0x00000122 mov [gs:80h],edx + 0x00000122 mov [gs:88h],edx 0x0000012a add edi,esi - 0x0000012c mov [gs:84h],edi + 0x0000012c mov [gs:8Ch],edi 0x00000134 add r8d,esi - 0x00000137 mov [gs:88h],r8d + 0x00000137 mov [gs:90h],r8d 0x00000140 add r9d,esi - 0x00000143 mov [gs:8Ch],r9d + 0x00000143 mov [gs:94h],r9d 0x0000014c add r10d,esi - 0x0000014f mov [gs:90h],r10d + 0x0000014f mov [gs:98h],r10d 0x00000158 add r11d,esi - 0x0000015b mov [gs:94h],r11d + 0x0000015b mov [gs:9Ch],r11d 0x00000164 add ecx,esi - 0x00000166 mov [gs:98h],ecx + 0x00000166 mov [gs:0A0h],ecx 0x0000016e add ebx,esi - 0x00000170 mov [gs:9Ch],ebx + 0x00000170 mov [gs:0A4h],ebx 0x00000178 add ebp,esi - 0x0000017a mov [gs:0A0h],ebp + 0x0000017a mov [gs:0A8h],ebp 0x00000182 add r12d,esi - 0x00000185 mov [gs:0A4h],r12d + 0x00000185 mov [gs:0ACh],r12d 0x0000018e add r13d,esi - 0x00000191 mov [gs:0A8h],r13d - 0x0000019a mov eax,[gs:58h] + 0x00000191 mov [gs:0B0h],r13d + 0x0000019a mov eax,[gs:60h] 0x000001a3 add eax,esi - 0x000001a5 mov [gs:0ACh],eax - 0x000001ae mov eax,[gs:5Ch] + 0x000001a5 mov [gs:0B4h],eax + 0x000001ae mov eax,[gs:64h] 0x000001b7 add eax,esi - 0x000001b9 mov [gs:0B0h],eax - 0x000001c2 mov eax,[gs:60h] + 0x000001b9 mov [gs:0B8h],eax + 0x000001c2 mov eax,[gs:68h] 0x000001cb add eax,esi - 0x000001cd mov [gs:0B4h],eax - 0x000001d6 mov eax,[gs:64h] + 0x000001cd mov [gs:0BCh],eax + 0x000001d6 mov eax,[gs:6Ch] 0x000001df add eax,esi - 0x000001e1 mov [gs:0B8h],eax - 0x000001ea mov eax,[gs:68h] + 0x000001e1 mov [gs:0C0h],eax + 0x000001ea mov eax,[gs:70h] 0x000001f3 add eax,esi - 0x000001f5 mov [gs:0BCh],eax - 0x000001fe mov eax,[gs:6Ch] + 0x000001f5 mov [gs:0C4h],eax + 0x000001fe mov eax,[gs:74h] 0x00000207 add eax,esi - 0x00000209 mov [gs:0C0h],eax - 0x00000212 mov eax,[gs:70h] + 0x00000209 mov [gs:0C8h],eax + 0x00000212 mov eax,[gs:78h] 0x0000021b add eax,esi - 0x0000021d mov [gs:0C4h],eax + 0x0000021d mov [gs:0CCh],eax 0x00000226 add esi,r14d - 0x00000229 mov [gs:0C8h],esi + 0x00000229 mov [gs:0D0h],esi 0x00000231 xor eax,eax 0x00000233 jmp short 0000000000000235h 0x00000235 movq r14,xmm13 diff --git a/crates/celox/tests/snapshots/native_mir__rle_comb_mir.snap b/crates/celox/tests/snapshots/native_mir__rle_comb_mir.snap index 8b80d115462..9306dd4a241 100644 --- a/crates/celox/tests/snapshots/native_mir__rle_comb_mir.snap +++ b/crates/celox/tests/snapshots/native_mir__rle_comb_mir.snap @@ -6,31 +6,31 @@ expression: output === Native function eval_comb === --- MIR after main optimization, before regalloc-owned late folds --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] v2 = add.w32 v0, v1 - store.i32 [sim + 48], v2 + store.i32 [sim + 56], v2 ret --- MIR after late memory folds, before allocation-owned scheduling --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] v2 = add.w32 v0, v1 - store.i32 [sim + 48], v2 + store.i32 [sim + 56], v2 ret --- MIR after allocation-owned scheduling, before spill reconstruction --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] v2 = add.w32 v0, v1 - store.i32 [sim + 48], v2 + store.i32 [sim + 56], v2 ret --- MIR after register allocation and post-RA peepholes --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] v2 = add.w32 v0, v1 - store.i32 [sim + 48], v2 + store.i32 [sim + 56], v2 ret Spill frame: 0 bytes Register assignment: @@ -42,10 +42,10 @@ x86-64 disassembly of emitted function: 0x00000005 movq xmm15,rax 0x0000000a wrgsbase rdi bb0: - 0x0000000f mov eax,[gs:28h] - 0x00000018 mov edx,[gs:2Ch] + 0x0000000f mov eax,[gs:30h] + 0x00000018 mov edx,[gs:34h] 0x00000020 add eax,edx - 0x00000022 mov [gs:30h],eax + 0x00000022 mov [gs:38h],eax 0x0000002b xor eax,eax 0x0000002d jmp short 000000000000002Fh 0x0000002f movq r11,xmm15 diff --git a/crates/celox/tests/snapshots/native_mir__shared_expression_mir.snap b/crates/celox/tests/snapshots/native_mir__shared_expression_mir.snap index 1fb36fdfc4f..424acd78208 100644 --- a/crates/celox/tests/snapshots/native_mir__shared_expression_mir.snap +++ b/crates/celox/tests/snapshots/native_mir__shared_expression_mir.snap @@ -6,47 +6,47 @@ expression: output === Native function eval_comb === --- MIR after main optimization, before regalloc-owned late folds --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] v5 = add.w32 v0, v1 v2 = and.w32 v5, 0x1 - store.i32 [sim + 48], v2 + store.i32 [sim + 56], v2 v3 = imm 0x2 v4 = or.w32 v5, v3 - store.i32 [sim + 52], v4 + store.i32 [sim + 60], v4 ret --- MIR after late memory folds, before allocation-owned scheduling --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] v5 = add.w32 v0, v1 v2 = and.w32 v5, 0x1 - store.i32 [sim + 48], v2 + store.i32 [sim + 56], v2 v3 = imm 0x2 v4 = or.w32 v5, v3 - store.i32 [sim + 52], v4 + store.i32 [sim + 60], v4 ret --- MIR after allocation-owned scheduling, before spill reconstruction --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] v5 = add.w32 v0, v1 v2 = and.w32 v5, 0x1 - store.i32 [sim + 48], v2 + store.i32 [sim + 56], v2 v3 = imm 0x2 v4 = or.w32 v5, v3 - store.i32 [sim + 52], v4 + store.i32 [sim + 60], v4 ret --- MIR after register allocation and post-RA peepholes --- bb0: - v0 = load.i32 [sim + 40] - v1 = load.i32 [sim + 44] + v0 = load.i32 [sim + 48] + v1 = load.i32 [sim + 52] v5 = add.w32 v0, v1 v2 = and.w32 v5, 0x1 - store.i32 [sim + 48], v2 + store.i32 [sim + 56], v2 v3 = imm 0x2 v4 = or.w32 v5, v3 - store.i32 [sim + 52], v4 + store.i32 [sim + 60], v4 ret Spill frame: 0 bytes Register assignment: @@ -61,15 +61,15 @@ x86-64 disassembly of emitted function: 0x00000005 movq xmm15,rax 0x0000000a wrgsbase rdi bb0: - 0x0000000f mov eax,[gs:28h] - 0x00000018 mov edx,[gs:2Ch] + 0x0000000f mov eax,[gs:30h] + 0x00000018 mov edx,[gs:34h] 0x00000020 add eax,edx 0x00000022 mov edx,eax 0x00000024 and edx,1 - 0x00000027 mov [gs:30h],edx + 0x00000027 mov [gs:38h],edx 0x0000002f mov edx,2 0x00000034 or eax,edx - 0x00000036 mov [gs:34h],eax + 0x00000036 mov [gs:3Ch],eax 0x0000003f xor eax,eax 0x00000041 jmp short 0000000000000043h 0x00000043 movq r11,xmm15 diff --git a/crates/celox/tests/systemverilog.rs b/crates/celox/tests/systemverilog.rs index c1b830eb36c..ae514a65adc 100644 --- a/crates/celox/tests/systemverilog.rs +++ b/crates/celox/tests/systemverilog.rs @@ -132,6 +132,8 @@ mod procedural; mod review_regressions; #[path = "frontends/systemverilog/scan.rs"] mod scan; +#[path = "frontends/systemverilog/string.rs"] +mod string; #[path = "frontends/systemverilog/suite.rs"] mod suite; #[path = "frontends/systemverilog/synthesizable.rs"] diff --git a/docs/guide/systemverilog-reference.md b/docs/guide/systemverilog-reference.md index cbe8d605be0..8cddc4eb621 100644 --- a/docs/guide/systemverilog-reference.md +++ b/docs/guide/systemverilog-reference.md @@ -29,6 +29,7 @@ synthesis and is tested at the design level. | Expressions | arithmetic including `**`, logic, shift, comparison, reduction, concatenation and replication, `?:`, `inside`, `==?` / `!=?`, casts (`N'(x)`, `signed'(x)`, `T'(x)`), `$signed` / `$unsigned` | | Selects | constant and run-time bit selects and indexed part-selects (`[i]`, `[i +: W]`, `[i -: W]`), in reads and writes, in either declaration direction | | Patterns | assignment patterns for packed structs, packed arrays and unpacked arrays (`'{a, b}`, `'{x: a, default: 0}`, `'{n{a}}`, `T'{...}`) | +| Strings | `string` variables, function arguments and results: assignment of strings, string literals and casts (`string'(x)`), `==`, `!=` and ordering comparisons, concatenation and replication (with a run-time count), character reads and writes (`s[i]`), and the methods `len`, `getc`, `putc`, `toupper`, `tolower`, `compare`, `icompare`, `substr`, `atoi` / `atohex` / `atooct` / `atobin` and `itoa` / `hextoa` / `octtoa` / `bintoa`; `%s` and format-less display of string values. See [strings](#strings) | | Parameters | integral parameters and overrides preserving widths beyond 128 bits and X/Z values, and parameters of unpacked array or packed struct type given by an assignment pattern (constant tables), including unpacked-array pattern overrides | ### Processes and control flow @@ -136,7 +137,7 @@ constructs without a dedicated issue point to the frontend roadmap, [#88](https: `bind`. - Declarations: variable declaration initializers of members of an interface array, ANSI port default values, tagged unions, soft packed unions, packed union assignment patterns, internal nets without a driver ([#460](https://github.com/celox-sim/celox/issues/460)), - unpacked structs, strings and `real`. + unpacked structs and `real`. - Sequential processes: `iff` qualifiers ([#452](https://github.com/celox-sim/celox/issues/452)) and edge operands other than a plain signal ([#464](https://github.com/celox-sim/celox/issues/464)) in event lists. A plain `always` with such an edge, a multi-bit edge signal, or several edges without a reset is @@ -196,6 +197,20 @@ index: `child_signal(&[("u", 3)], "y")` and `dut.u[3]` reach `u[3]` of `Child u[3:2](...)`, and `InstanceHierarchy::index` holds the index. Arrays with a negative bound are rejected. +### Strings {#strings} + +A `string` variable holds a reference to text in the simulator's heap, so +assigning, comparing for equality and detecting a change of a string cost the +same as for a 32-bit integer; operations that read or build text call into the +runtime. Strings are collected between time slots and after each `tick`. +As IEEE 1800-2023 6.16 requires, NUL bytes are removed when text becomes a +string, and an integral value assigned or cast to a string contributes its +bytes from the most significant one. + +Not yet supported: `$sformat` / `$sformatf`, `atoreal` / `realtoa`, string +arguments of `$value$plusargs`, file I/O and DPI-C, and string values in VPI, +VCD output and the TypeScript API. + ### Out-of-range selects A run-time select that reaches past either end of a diff --git a/docs/guide/systemverilog.md b/docs/guide/systemverilog.md index 7623b7ee719..f3c531789ca 100644 --- a/docs/guide/systemverilog.md +++ b/docs/guide/systemverilog.md @@ -97,7 +97,7 @@ Common reasons a design needs changes are: ([#1707](https://github.com/celox-sim/celox/issues/1707)). - Nonblocking latch assignments, multiple drivers and tri-state buses. Inferred latches in `always_comb` require `inferred_latch = "warn"` or `"allow"` in the common `[diagnostics]` configuration. - Non-ANSI module ports, wildcard `.*` connections, gate primitives and `bind`. -- Strings, `real`, unpacked structs and several interface features. +- `real`, unpacked structs and several interface features. The [complete limitations list](./systemverilog-reference#what-is-not-supported) includes narrower restrictions and tracking issues. Unsupported constructs diff --git a/docs/ja/guide/systemverilog-reference.md b/docs/ja/guide/systemverilog-reference.md index 50ec446cad0..a4e93bf411c 100644 --- a/docs/ja/guide/systemverilog-reference.md +++ b/docs/ja/guide/systemverilog-reference.md @@ -28,6 +28,7 @@ outline: [2, 3] | 式 | `**` を含む算術、論理、シフト、比較、リダクション、連結・複製、`?:`、`inside`、`==?` / `!=?`、キャスト(`N'(x)`、`signed'(x)`、`T'(x)`)、`$signed` / `$unsigned` | | 選択 | 定数・実行時のビット選択と indexed part-select(`[i]`、`[i +: W]`、`[i -: W]`)。読み書きの両方、宣言の向きによらず | | パターン | packed 構造体・packed 配列・unpacked 配列の assignment pattern(`'{a, b}`、`'{x: a, default: 0}`、`'{n{a}}`、`T'{...}`) | +| 文字列 | `string` 型の変数、関数の引数と戻り値。文字列・文字列リテラル・キャスト(`string'(x)`)の代入、`==` / `!=` と大小比較、連結と複製(実行時の回数も可)、文字の読み書き(`s[i]`)、メソッド `len`、`getc`、`putc`、`toupper`、`tolower`、`compare`、`icompare`、`substr`、`atoi` / `atohex` / `atooct` / `atobin`、`itoa` / `hextoa` / `octtoa` / `bintoa`。`%s` と書式なしの表示。[文字列](#strings)を参照 | | パラメータ | 整数のパラメータ、128ビットを超える幅と X/Z を保持するパラメータ上書き、assignment pattern で与える unpacked 配列型・packed 構造体型のパラメータ(定数テーブル)と unpacked 配列のパターンによる上書き | ### プロセスと制御 @@ -126,7 +127,7 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 - `always_comb` の暗黙のラッチ推論はデフォルトで拒否します。`celox.toml` の `[diagnostics]` で `inferred_latch = "warn"` または `"allow"` を指定すると許可できます。通常の `always @*` と明示的な `always_latch` にはこの設定は不要です。 - ポートとインスタンス:non-ANSI 形式のポート宣言([#426](https://github.com/celox-sim/celox/issues/426))、`ref` ポート([#427](https://github.com/celox-sim/celox/issues/427))、 ワイルドカード接続 `.*`([#442](https://github.com/celox-sim/celox/issues/442))、ゲートプリミティブ([#457](https://github.com/celox-sim/celox/issues/457))、`bind`。 -- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、soft packed union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、unpacked 構造体、文字列、`real`。 +- 宣言:interface 配列のメンバーの変数宣言の初期化子、ANSI ポートの既定値、tagged union、soft packed union、packed union の assignment pattern、ドライバを持たない内部ネット([#460](https://github.com/celox-sim/celox/issues/460))、unpacked 構造体、`real`。 - 順序回路のプロセス:イベントリストの `iff` 修飾([#452](https://github.com/celox-sim/celox/issues/452))と単純な信号以外のエッジ オペランド([#464](https://github.com/celox-sim/celox/issues/464))。このようなエッジ、複数ビットのエッジ信号、リセットを持たない 複数のエッジを持つ通常の `always` も、プロセスとして実行できるようになるまで拒否します @@ -151,6 +152,12 @@ SystemVerilog に対しても、共有の Veryl 適合性スイートを実行 `$isunbounded(P)` は、値パラメータが `$` の場合に1、それ以外では0を1ビットの符号なし値として返します。`$` は別のパラメータへの代入やインスタンスのパラメータ上書きでも保持されます(IEEE 1800-2023 6.20.7、20.6.3)。 +### 文字列 {#strings} + +`string` 型の変数はシミュレータのヒープ上の文字列への参照を持ちます。代入、等値比較、値の変化の検出は 32 ビット整数と同じコストで、文字列の中身を読む・作る演算だけがランタイムを呼び出します。文字列はタイムスロットの間と各 `tick` の後に回収されます。IEEE 1800-2023 6.16 のとおり、文字列にするときに NUL バイトは取り除かれ、文字列へ代入・キャストした整数値は最上位のバイトから並びます。 + +未対応:`$sformat` / `$sformatf`、`atoreal` / `realtoa`、`$value$plusargs`・ファイル I/O・DPI-C の文字列引数、VPI・VCD 出力・TypeScript API での文字列値。 + ### インスタンス配列の要素 要素は宣言どおりの添字で参照します。`Child u[3:2](...)` の diff --git a/docs/ja/guide/systemverilog.md b/docs/ja/guide/systemverilog.md index c341643e4eb..8d0bec47655 100644 --- a/docs/ja/guide/systemverilog.md +++ b/docs/ja/guide/systemverilog.md @@ -91,7 +91,7 @@ X/Z を扱う場合は builder に `.four_state(true)` を指定します。 イベント制御の `iff`([#1444](https://github.com/celox-sim/celox/issues/1444))、実数の遅延([#1707](https://github.com/celox-sim/celox/issues/1707))。 - ラッチ内のノンブロッキング代入、複数ドライバ、トライステートバス。`always_comb` の暗黙のラッチ推論は 共通の `[diagnostics]` 設定で `inferred_latch = "warn"` または `"allow"` を指定して許可します。 - 非 ANSI モジュールポート、ワイルドカード `.*` 接続、ゲートプリミティブ、`bind`。 -- 文字列、`real`、unpacked 構造体、interface の一部の機能。 +- `real`、unpacked 構造体、interface の一部の機能。 [制約の一覧](./systemverilog-reference#what-is-not-supported)に、より細かな条件と追跡 issue をまとめています。 未対応の構文は、構文名と追跡 issue を含む診断を返します。