diff --git a/src/vm/aot/compile.rs b/src/vm/aot/compile.rs index 739674e7..99570cf8 100644 --- a/src/vm/aot/compile.rs +++ b/src/vm/aot/compile.rs @@ -1132,8 +1132,8 @@ fn lower_aot_ssa_inst( AotSsaInstKind::IntAdd { lhs, rhs } => b.ins().iadd(values[lhs], values[rhs]), AotSsaInstKind::TaggedNumberSub { lhs, rhs } | AotSsaInstKind::TaggedNumberMul { lhs, rhs } => { - let lhs = aot_box_numeric_operand(b, ctx, values[lhs], value_reprs[lhs])?; - let rhs = aot_box_numeric_operand(b, ctx, values[rhs], value_reprs[rhs])?; + let lhs = aot_box_scalar_operand(b, ctx, values[lhs], value_reprs[lhs])?; + let rhs = aot_box_scalar_operand(b, ctx, values[rhs], value_reprs[rhs])?; aot_lower_tagged_number_arithmetic( b, ctx, @@ -1167,6 +1167,10 @@ fn lower_aot_ssa_inst( }, true, ), + AotSsaInstKind::ShlGuard { stack, locals } => { + aot_lower_shl_guard(b, ctx, inst.ip, stack, locals, values)?; + b.ins().iconst(types::I8, 0) + } AotSsaInstKind::IntShl { lhs, rhs } => b.ins().ishl(values[lhs], values[rhs]), AotSsaInstKind::IntShr { lhs, rhs } => b.ins().sshr(values[lhs], values[rhs]), AotSsaInstKind::IntLshr { lhs, rhs } => b.ins().ushr(values[lhs], values[rhs]), @@ -1226,8 +1230,8 @@ fn lower_aot_ssa_inst( } AotSsaInstKind::TaggedNumberCmpLt { lhs, rhs } | AotSsaInstKind::TaggedNumberCmpGt { lhs, rhs } => { - let lhs = aot_box_numeric_operand(b, ctx, values[lhs], value_reprs[lhs])?; - let rhs = aot_box_numeric_operand(b, ctx, values[rhs], value_reprs[rhs])?; + let lhs = aot_box_scalar_operand(b, ctx, values[lhs], value_reprs[lhs])?; + let rhs = aot_box_scalar_operand(b, ctx, values[rhs], value_reprs[rhs])?; aot_lower_tagged_number_compare( b, ctx, @@ -1239,15 +1243,19 @@ fn lower_aot_ssa_inst( matches!(inst.kind, AotSsaInstKind::TaggedNumberCmpLt { .. }), )? } - AotSsaInstKind::TaggedCmpEq { lhs, rhs } => aot_lower_tagged_eq( - b, - ctx, - AotBinaryOp { - ip: inst.ip, - lhs: values[lhs], - rhs: values[rhs], - }, - )?, + AotSsaInstKind::TaggedCmpEq { lhs, rhs } => { + let lhs = aot_box_scalar_operand(b, ctx, values[lhs], value_reprs[lhs])?; + let rhs = aot_box_scalar_operand(b, ctx, values[rhs], value_reprs[rhs])?; + aot_lower_tagged_eq( + b, + ctx, + AotBinaryOp { + ip: inst.ip, + lhs, + rhs, + }, + )? + } AotSsaInstKind::StringCmpEq { lhs, rhs } => aot_lower_tagged_bytes_eq( b, ctx, @@ -1963,6 +1971,82 @@ fn aot_lower_tagged_to_bool( Ok(b.block_params(cont)[0]) } +#[cfg(feature = "cranelift-jit")] +fn aot_lower_shl_guard( + b: &mut FunctionBuilder, + ctx: AotLowerCtx<'_>, + ip: usize, + stack: &[AotSsaMaterialization], + locals: &[AotSsaMaterialization], + values: &HashMap, +) -> Result<(), AotCompileError> { + let [.., lhs, rhs] = stack else { + return Err(AotCompileError::Codegen( + "Shl guard needs two operands".into(), + )); + }; + let error = b.create_block(); + b.set_cold_block(error); + let layout = ctx.layout.value; + let check = |b: &mut FunctionBuilder, cond| { + let ok = b.create_block(); + b.ins().brif(cond, ok, &[], error, &[]); + b.switch_to_block(ok); + }; + let check_int_tag = |b: &mut FunctionBuilder, value| { + let tag = ssa_load_tag_i32(b, layout, value); + let is_int = b + .ins() + .icmp_imm(IntCC::Equal, tag, i64::from(layout.int_tag)); + check(b, is_int); + }; + let count = match rhs { + AotSsaMaterialization::BoxInt(id) => values[id], + AotSsaMaterialization::Value(id) => { + let value = values[id]; + check_int_tag(b, value); + b.ins().load( + types::I64, + MemFlags::new(), + value, + layout.int_payload_offset, + ) + } + _ => { + return Err(AotCompileError::Codegen( + "Shl guard needs an integer count".into(), + )); + } + }; + let valid_count = b.ins().icmp_imm(IntCC::UnsignedLessThanOrEqual, count, 63); + check(b, valid_count); + if let AotSsaMaterialization::Value(id) = lhs { + check_int_tag(b, values[id]); + } + + let ok = b.current_block().expect("Shl guard continuation"); + b.switch_to_block(error); + // Only invalid operands take this exit. Resume at Shl with its original + // operands so the interpreter reports the exact error in operand-pop order. + materialize_state_to_vm( + b, + ctx.vm_ptr, + ctx.exit_block, + ctx.pointer_type, + ctx.layout, + ctx.helper_refs, + ctx.helper_addrs, + stack, + locals, + values, + ip, + )?; + let status = b.ins().iconst(types::I32, i64::from(STATUS_TRACE_EXIT)); + jump_with_status(b, ctx.exit_block, status); + b.switch_to_block(ok); + Ok(()) +} + #[cfg(feature = "cranelift-jit")] fn aot_lower_tagged_to_int( b: &mut FunctionBuilder, @@ -2285,7 +2369,7 @@ fn aot_lower_int_divrem( } #[cfg(feature = "cranelift-jit")] -fn aot_box_numeric_operand( +fn aot_box_scalar_operand( b: &mut FunctionBuilder, ctx: AotLowerCtx<'_>, value: cranelift_codegen::ir::Value, @@ -2298,9 +2382,10 @@ fn aot_box_numeric_operand( match repr { AotSsaValueRepr::I64 => ssa_store_int_in_value(b, ctx.layout.value, slot, value), AotSsaValueRepr::F64 => ssa_store_float_in_value(b, ctx.layout.value, slot, value), + AotSsaValueRepr::Bool => ssa_store_bool_in_value(b, ctx.layout.value, slot, value), _ => { return Err(AotCompileError::Codegen( - "non-numeric operand representation".into(), + "non-scalar operand representation".into(), )); } } diff --git a/src/vm/aot/runtime.rs b/src/vm/aot/runtime.rs index 2c643428..a9678b7f 100644 --- a/src/vm/aot/runtime.rs +++ b/src/vm/aot/runtime.rs @@ -26,6 +26,11 @@ impl Vm { self.engine.aot_exec_count } + /// Reports whether AOT execution has handed control back to the interpreter. + pub fn aot_interpreter_boundary_hit(&self) -> bool { + self.engine.aot_interpreter_boundary_hit + } + pub fn aot_resume_ips(&self) -> Option<&[usize]> { self.engine .aot_program diff --git a/src/vm/aot/ssa.rs b/src/vm/aot/ssa.rs index e367fa73..c65a31f5 100644 --- a/src/vm/aot/ssa.rs +++ b/src/vm/aot/ssa.rs @@ -202,6 +202,10 @@ pub(crate) enum AotSsaInstKind { lhs: AotSsaValueId, rhs: AotSsaValueId, }, + ShlGuard { + stack: Vec, + locals: Vec, + }, IntShl { lhs: AotSsaValueId, rhs: AotSsaValueId, @@ -321,6 +325,7 @@ impl AotSsaInstKind { fn inputs(&self) -> Vec { match self { Self::LocalWrite { .. } + | Self::ShlGuard { .. } // Verified by checking the materializations. | Self::IntConst(_) | Self::FloatConst(_) | Self::BoolConst(_) @@ -589,6 +594,11 @@ impl AotSsaProgram { }); } } + if let AotSsaInstKind::ShlGuard { stack, locals } = &inst.kind { + for materialization in stack.iter().chain(locals) { + verify_materialization(materialization, &available_values)?; + } + } available_values.insert(inst.output.id, inst.output.repr); value_reprs.insert(inst.output.id, inst.output.repr); } @@ -1915,14 +1925,7 @@ fn apply_direct_instruction( AotInstruction::IMul => emit_typed_int_binary(frame, emitter, ip, "imul", |lhs, rhs| { AotSsaInstKind::IntMul { lhs, rhs } }), - AotInstruction::Shl => emit_binary( - frame, - emitter, - ip, - "shl", - AotSsaValueRepr::I64, - |lhs, rhs| AotSsaInstKind::IntShl { lhs, rhs }, - ), + AotInstruction::Shl => emit_shl(frame, emitter, ip), AotInstruction::Shr => emit_binary( frame, emitter, @@ -2133,22 +2136,24 @@ fn apply_direct_instruction( AotSsaInstKind::FloatMod { lhs, rhs } }), AotInstruction::Ceq => { + use AotSsaValueRepr::{Bool, F64, I64, Tagged}; + let rhs = frame.pop(ip, "ceq")?; let lhs = frame.pop(ip, "ceq")?; let kind = match (lhs.value.repr, rhs.value.repr) { - (AotSsaValueRepr::I64, AotSsaValueRepr::I64) => Some(AotSsaInstKind::IntCmpEq { + (I64, I64) => Some(AotSsaInstKind::IntCmpEq { lhs: lhs.value.id, rhs: rhs.value.id, }), - (AotSsaValueRepr::Bool, AotSsaValueRepr::Bool) => Some(AotSsaInstKind::BoolCmpEq { + (Bool, Bool) => Some(AotSsaInstKind::BoolCmpEq { lhs: lhs.value.id, rhs: rhs.value.id, }), - (AotSsaValueRepr::F64, AotSsaValueRepr::F64) => Some(AotSsaInstKind::FloatCmpEq { + (F64, F64) => Some(AotSsaInstKind::FloatCmpEq { lhs: lhs.value.id, rhs: rhs.value.id, }), - (AotSsaValueRepr::Tagged, AotSsaValueRepr::Tagged) => { + (Tagged, Tagged) => { let tagged_kind = match operand_types_at(program, ip) { (ValueType::String, ValueType::String) => AotSsaInstKind::StringCmpEq { lhs: lhs.value.id, @@ -2169,7 +2174,7 @@ fn apply_direct_instruction( }; Some(tagged_kind) } - (AotSsaValueRepr::Tagged, AotSsaValueRepr::I64) + (Tagged, I64) if operand_types_at(program, ip) == (ValueType::Int, ValueType::Int) => { let lhs_int = emitter.emit( @@ -2184,7 +2189,7 @@ fn apply_direct_instruction( rhs: rhs.value.id, }) } - (AotSsaValueRepr::I64, AotSsaValueRepr::Tagged) + (I64, Tagged) if operand_types_at(program, ip) == (ValueType::Int, ValueType::Int) => { let rhs_int = emitter.emit( @@ -2199,6 +2204,15 @@ fn apply_direct_instruction( rhs: rhs_int.id, }) } + (Tagged, I64 | F64 | Bool) | (I64 | F64 | Bool, Tagged) => { + Some(AotSsaInstKind::TaggedCmpEq { + lhs: lhs.value.id, + rhs: rhs.value.id, + }) + } + // Same-representation scalar pairs were handled above. Value::eq + // compares different scalar variants as unequal without coercion. + (I64 | F64 | Bool, I64 | F64 | Bool) => Some(AotSsaInstKind::BoolConst(false)), _ => None, }; if let Some(kind) = kind { @@ -2329,6 +2343,50 @@ fn emit_unary( Ok(true) } +fn emit_shl( + frame: &mut Frame, + emitter: &mut E, + ip: usize, +) -> Result { + let [lhs, rhs] = *frame + .stack + .last_chunk() + .ok_or(AotSsaBuildError::StackUnderflow { + ip, + instruction: "shl", + })?; + if ![lhs, rhs].iter().all(|operand| { + matches!( + operand.value.repr, + AotSsaValueRepr::I64 | AotSsaValueRepr::Tagged + ) + }) { + return Ok(false); + } + emitter.emit( + ip, + AotSsaInstKind::ShlGuard { + stack: materialize_values(&frame.stack), + locals: materialize_values(&frame.locals), + }, + AotSsaValueRepr::Bool, + ); + frame.stack.truncate(frame.stack.len() - 2); + let lhs = coerce_numeric_to_int(emitter, ip, lhs.value); + let rhs = coerce_numeric_to_int(emitter, ip, rhs.value); + frame.stack.push(FrameValue { + value: emitter.emit( + ip, + AotSsaInstKind::IntShl { + lhs: lhs.id, + rhs: rhs.id, + }, + AotSsaValueRepr::I64, + ), + }); + Ok(true) +} + fn emit_typed_int_binary( frame: &mut Frame, emitter: &mut E, @@ -2960,6 +3018,44 @@ mod tests { use super::*; use crate::{BytecodeBuilder, HostImport, Value}; + #[cfg(feature = "cranelift-jit")] + #[test] + fn aot_ssa_tagged_mul_shl_and_ceq_complete_without_interpreter_boundary() { + let mut code = BytecodeBuilder::new(); + code.ldloc(0); + code.ldc(0); + code.mul(); + code.ldc(1); + code.shl(); + code.ldloc(1); + code.ldc(2); + code.ceq(); + code.ret(); + + let program = Program::new( + vec![Value::Int(2), Value::Int(3), Value::Float(2.0)], + code.finish(), + ) + .with_local_count(2); + let mut vm = crate::Vm::new_with_jit_config( + program, + crate::JitConfig { + enabled: false, + ..crate::JitConfig::default() + }, + ); + vm.set_local(0, Value::Int(9_007_199_254_740_993)).unwrap(); + vm.set_local(1, Value::Int(2)).unwrap(); + vm.compile_aot().unwrap(); + assert_eq!(vm.run().unwrap(), crate::VmStatus::Halted); + assert_eq!( + vm.stack(), + &[Value::Int(144_115_188_075_855_888), Value::Bool(false)] + ); + assert_eq!(vm.aot_exec_count(), 1); + assert!(!vm.engine.aot_interpreter_boundary_hit); + } + fn compile_legacy(source: &str) -> crate::CompiledProgram { crate::compile_source_with_flavor_and_options( source, diff --git a/tests/aot_tagged_number_tests.rs b/tests/aot_tagged_number_tests.rs index 3465b951..5ba27cef 100644 --- a/tests/aot_tagged_number_tests.rs +++ b/tests/aot_tagged_number_tests.rs @@ -199,6 +199,250 @@ fn dynamic_program(op: &str) -> Program { Program::new(vec![], code.finish()).with_local_count(2) } +fn binary_program( + [lhs, rhs]: [Option; 2], + emit: impl FnOnce(&mut BytecodeBuilder), +) -> Program { + let mut code = BytecodeBuilder::new(); + let mut constants = Vec::new(); + for (index, operand) in [lhs, rhs].into_iter().enumerate() { + if let Some(operand) = operand { + code.ldc(constants.len() as u32); + constants.push(operand); + } else { + code.ldloc(index as u8); + } + } + emit(&mut code); + code.ret(); + Program::new(constants, code.finish()).with_local_count(2) +} + +fn binary_machine(program: Program, lhs: Value, rhs: Value, native: bool) -> Vm { + let mut machine = Vm::new_with_jit_config( + program, + JitConfig { + enabled: false, + ..JitConfig::default() + }, + ); + machine.set_fuel(100_000); + machine.set_local(0, lhs).unwrap(); + machine.set_local(1, rhs).unwrap(); + if native { + machine + .compile_aot() + .expect("compile tagged operands natively"); + assert_ssa(&machine); + } + machine +} + +#[test] +fn shl_with_tagged_operands_preserves_full_width_and_wraps() { + for (lhs, rhs, expected) in [ + (1, 0, 1), + (1, 63, i64::MIN), + (2, 63, 0), + (16, 2, 64), + (-3, 1, -6), + (9_007_199_254_740_993, 1, 18_014_398_509_481_986), + ] { + for (lhs_const, rhs_const) in [(None, Some(rhs)), (Some(lhs), None), (None, None)] { + let operands = [lhs_const.map(Value::Int), rhs_const.map(Value::Int)]; + for native in [false, true] { + let mut machine = binary_machine( + binary_program(operands.clone(), |code| { + code.shl(); + }), + Value::Int(lhs), + Value::Int(rhs), + native, + ); + assert_eq!(machine.run().unwrap(), VmStatus::Halted); + assert_eq!(machine.stack(), &[Value::Int(expected)]); + assert_eq!(machine.aot_exec_count(), u64::from(native)); + assert!( + !machine.aot_interpreter_boundary_hit(), + "{lhs} << {rhs}, constants={operands:?}, native={native}" + ); + } + } + } +} + +#[test] +fn shl_rejects_invalid_counts_and_tags_in_vm_order() { + for (lhs, rhs, expected) in [ + (Value::Int(1), Value::Int(-1), VmError::InvalidShift(-1)), + (Value::Int(1), Value::Int(64), VmError::InvalidShift(64)), + ( + Value::Int(1), + Value::Int(1 << 32), + VmError::InvalidShift(1 << 32), + ), + ( + Value::Int(1), + Value::Float(1.0), + VmError::TypeMismatch("int"), + ), + ( + Value::Bool(true), + Value::Int(1), + VmError::TypeMismatch("int"), + ), + (Value::Bool(true), Value::Int(64), VmError::InvalidShift(64)), + ] { + let int_constant = |value: &Value| match value { + Value::Int(value) => Some(*value), + _ => None, + }; + let lhs_const = int_constant(&lhs); + let rhs_const = int_constant(&rhs); + for (lhs_const, rhs_const) in [(None, None), (lhs_const, rhs_const)] { + let operands = [lhs_const.map(Value::Int), rhs_const.map(Value::Int)]; + for native in [false, true] { + let mut machine = binary_machine( + binary_program(operands.clone(), |code| { + code.shl(); + }), + lhs.clone(), + rhs.clone(), + native, + ); + let actual = machine.run().unwrap_err(); + match (&actual, &expected) { + (VmError::InvalidShift(actual), VmError::InvalidShift(expected)) => { + assert_eq!(actual, expected); + } + (VmError::TypeMismatch("int"), VmError::TypeMismatch("int")) => {} + _ => panic!("{lhs:?} << {rhs:?}: expected {expected:?}, got {actual:?}"), + } + assert_eq!(machine.aot_exec_count(), u64::from(native)); + // The native guard intentionally hands invalid shifts back to the interpreter. + assert_eq!(machine.aot_interpreter_boundary_hit(), native); + } + } + } +} + +#[test] +fn ceq_with_tagged_operands_preserves_value_equality() { + for (tagged, scalar, expected) in [ + (Value::Int(2), 2.0, false), + (Value::Float(2.0), 2.0, true), + (Value::Float(2.0), 3.0, false), + (Value::Float(0.0), -0.0, true), + (Value::Float(f64::NAN), f64::NAN, false), + ( + Value::Int(9_007_199_254_740_993), + 9_007_199_254_740_992.0, + false, + ), + ] { + for (operands, lhs, rhs) in [ + ( + [None, Some(Value::Float(scalar))], + tagged.clone(), + Value::Null, + ), + ( + [Some(Value::Float(scalar)), None], + Value::Null, + tagged.clone(), + ), + ([None, None], tagged, Value::Float(scalar)), + ] { + for native in [false, true] { + let program = binary_program(operands.clone(), |code| { + code.ceq(); + }); + let mut machine = binary_machine(program, lhs.clone(), rhs.clone(), native); + assert_eq!(machine.run().unwrap(), VmStatus::Halted); + assert_eq!( + machine.stack(), + &[Value::Bool(expected)], + "{lhs:?}, {rhs:?}, scalar={scalar:?}" + ); + assert_eq!(machine.aot_exec_count(), u64::from(native)); + assert!( + !machine.aot_interpreter_boundary_hit(), + "{lhs:?} == {rhs:?}, constants={operands:?}, native={native}" + ); + } + } + } +} + +fn assert_ceq(operands: [Option; 2], locals: [Value; 2], expected: bool) { + for native in [false, true] { + let program = binary_program(operands.clone(), |code| { + code.ceq(); + }); + let mut machine = binary_machine(program, locals[0].clone(), locals[1].clone(), native); + assert_eq!(machine.run().unwrap(), VmStatus::Halted); + assert_eq!( + machine.stack(), + &[Value::Bool(expected)], + "constants={operands:?}, locals={locals:?}, native={native}" + ); + assert_eq!(machine.aot_exec_count(), u64::from(native)); + assert!(!machine.aot_interpreter_boundary_hit()); + } +} + +#[test] +fn ceq_with_tagged_and_scalar_int_preserves_value_equality() { + const WIDE: i64 = 9_007_199_254_740_993; + for (tagged, scalar, expected) in [ + (Value::Int(WIDE), Value::Int(WIDE), true), + (Value::Int(WIDE - 1), Value::Int(WIDE), false), + (Value::Float(1.0), Value::Int(1), false), + (Value::Bool(true), Value::Int(1), false), + ] { + assert_ceq( + [None, Some(scalar.clone())], + [tagged.clone(), Value::Null], + expected, + ); + assert_ceq([Some(scalar), None], [Value::Null, tagged], expected); + } +} + +#[test] +fn ceq_with_tagged_and_scalar_bool_preserves_value_equality() { + for (tagged, scalar, expected) in [ + (Value::Bool(true), Value::Bool(true), true), + (Value::Bool(false), Value::Bool(false), true), + (Value::Bool(false), Value::Bool(true), false), + (Value::Int(1), Value::Bool(true), false), + (Value::Null, Value::Bool(false), false), + ] { + assert_ceq( + [None, Some(scalar.clone())], + [tagged.clone(), Value::Null], + expected, + ); + assert_ceq([Some(scalar), None], [Value::Null, tagged], expected); + } +} + +#[test] +fn ceq_with_mixed_scalar_types_does_not_coerce_values() { + for (lhs, rhs) in [ + (Value::Int(1), Value::Float(1.0)), + (Value::Bool(true), Value::Int(1)), + (Value::Bool(true), Value::Float(1.0)), + ] { + assert_ceq( + [Some(lhs.clone()), Some(rhs.clone())], + [Value::Null, Value::Null], + false, + ); + assert_ceq([Some(rhs), Some(lhs)], [Value::Null, Value::Null], false); + } +} + #[test] fn invalid_dynamic_tags_reject_safely_at_the_numeric_instruction() { for op in ["less", "greater", "subtract", "multiply"] {