Truly independent web browser
LibJS/JIT: Call the runtime's functions of doubles for Math functions
Andreas Kling6e287d8139d9
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.mdindex 18d74f4980f..e633f668775 100644--- a/Libraries/LibJS/JIT/ARCHITECTURE.md+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md@@ -143,6 +143,7 @@ Exits: E = eager, L = lazy. Every node that can exit has a frame state. "Call" m| IsCallable | Whether input 0 is a function object. | | | | cse || Typeof, TypeofIs | `typeof` of input 0, or whether it is one kind. | | | | cse || ToBoolean | Truthiness through the runtime's `to_boolean`; the slow path of `BranchTruthy`. | | | | call, cse |+| CallFloat64Function | `Math.exp`, `log`, `sin`, `cos`, `tan` and `pow` of float64 values, through the runtime's function of doubles for each, which only computes. | | | | call, cse || PrimitiveToString, ToObject | ToString of a primitive, and ToObject of a primitive (but undefined and null) as a builtin of the running realm makes it (else the empty value), through the runtime. | | | | call, allocates || CallIntrinsic | A builtin of a `this` value and arguments of the kinds its `HelperCall` lists (like a string and an int32 position for `String.prototype.indexOf`), through its runtime helper, without a native frame; the helper runs in the realm of the calling code. Helpers that return any value return the empty value where they decline, having done nothing observable. | | Per `HelperCall` | Per `HelperCall` | call, allocates || ArrayCreate | `new Array(length)` as the running realm's `Array` constructor makes it, through the runtime. | | | | call, allocates |diff --git a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs b/Libraries/LibJS/JIT/Rust/src/builder/checks.rsindex 662a8caa2e4..384fc0a198e 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/checks.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/checks.rs@@ -26,6 +26,7 @@ use crate::code::ExitKind;use crate::code::Repr;use crate::ir::BlockId;use crate::ir::BranchCondition;+use crate::ir::Float64Function;use crate::ir::Float64UnaryOp;use crate::ir::FrameStateId;use crate::ir::NodeId;@@ -104,6 +105,55 @@ impl GraphBuilder<'_> {call_feedback,..} => self.build_math_function(Float64UnaryOp::Sqrt, dst, callee, argument, call_feedback),+ Instruction::CallBuiltinMathExp {+ dst,+ callee,+ argument,+ call_feedback,+ ..+ } => self.build_math_call(Float64Function::Exp, dst, callee, &[argument], call_feedback),+ Instruction::CallBuiltinMathLog {+ dst,+ callee,+ argument,+ call_feedback,+ ..+ } => self.build_math_call(Float64Function::Log, dst, callee, &[argument], call_feedback),+ Instruction::CallBuiltinMathSin {+ dst,+ callee,+ argument,+ call_feedback,+ ..+ } => self.build_math_call(Float64Function::Sin, dst, callee, &[argument], call_feedback),+ Instruction::CallBuiltinMathCos {+ dst,+ callee,+ argument,+ call_feedback,+ ..+ } => self.build_math_call(Float64Function::Cos, dst, callee, &[argument], call_feedback),+ Instruction::CallBuiltinMathTan {+ dst,+ callee,+ argument,+ call_feedback,+ ..+ } => self.build_math_call(Float64Function::Tan, dst, callee, &[argument], call_feedback),+ Instruction::CallBuiltinMathPow {+ dst,+ callee,+ argument0,+ argument1,+ call_feedback,+ ..+ } => self.build_math_call(+ Float64Function::Pow,+ dst,+ callee,+ &[argument0, argument1],+ call_feedback,+ ),Instruction::GetIterator {dst_iterator_object,dst_iterator_next,diff --git a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs b/Libraries/LibJS/JIT/Rust/src/builder/handling.rsindex 4ade0adda1e..21bc51b78d6 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/handling.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/handling.rs@@ -136,14 +136,8 @@ pub fn handling(opcode: OpCode) -> Handling {// The builtin slow paths call the builtin directly, and any other// callee through the generic call machinery, without leaving the// caller's frame.- O::CallBuiltinMathExp- | O::CallBuiltinMathLog- | O::CallBuiltinMathPow- | O::CallBuiltinMathImul+ O::CallBuiltinMathImul| O::CallBuiltinMathRandom- | O::CallBuiltinMathSin- | O::CallBuiltinMathCos- | O::CallBuiltinMathTan| O::CallBuiltinRegExpPrototypeExec| O::CallBuiltinRegExpPrototypeReplace| O::CallBuiltinRegExpPrototypeSplit@@ -161,6 +155,14 @@ pub fn handling(opcode: OpCode) -> Handling {| O::CallBuiltinMathCeil| O::CallBuiltinMathRound| O::CallBuiltinMathSqrt => EXPANDED,+ // Math functions the runtime computes, built as calls of its+ // functions of doubles for numbers.+ O::CallBuiltinMathExp+ | O::CallBuiltinMathLog+ | O::CallBuiltinMathSin+ | O::CallBuiltinMathCos+ | O::CallBuiltinMathTan+ | O::CallBuiltinMathPow => EXPANDED,O::CreateArguments | O::CreateRestParams | O::Debugger => GENERIC_READS_WHOLE_FRAME,diff --git a/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs b/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rsindex dbffec9f7a0..ce464c0fe1a 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/intrinsics.rs@@ -19,6 +19,7 @@ use crate::ir::BinaryOp;use crate::ir::BranchCondition;use crate::ir::Comparison;use crate::ir::ElementsKind;+use crate::ir::Float64Function;use crate::ir::Float64UnaryOp;use crate::ir::NodeId;use crate::ir::Op;@@ -108,6 +109,57 @@ impl GraphBuilder<'_> {Ok(Flow::Continue)}+ /// Builds `Math.<function>(arguments...)`, a `CallBuiltinMath*`+ /// instruction, for numbers, like `build_math_function()`: the code+ /// calls the runtime's function of doubles for it, which only computes,+ /// so nothing after the call forgets what it knew.+ pub(super) fn build_math_call(+ &mut self,+ function: Float64Function,+ dst: Operand,+ callee: Operand,+ arguments: &[Operand],+ call_feedback: u16,+ ) -> Result<Flow, CompileFailure> {+ let layout = &self.runtime.layout;+ let builtin = match function {+ Float64Function::Exp => layout.builtin_math_exp,+ Float64Function::Log => layout.builtin_math_log,+ Float64Function::Sin => layout.builtin_math_sin,+ Float64Function::Cos => layout.builtin_math_cos,+ Float64Function::Tan => layout.builtin_math_tan,+ Float64Function::Pow => layout.builtin_math_pow,+ };+ let target = self+ .call_feedback(call_feedback)+ .and_then(|feedback| feedback.monomorphic_builtin(builtin))+ .filter(|_| self.may_speculate(ExitKind::BadCallTarget));+ if let Some(target) = target {+ self.check_callee(callee, target)?;+ }+ let callee = self.read(callee)?;+ let arguments = arguments+ .iter()+ .map(|argument| self.read(*argument))+ .collect::<Result<Vec<_>, _>>()?;+ let mut slow_paths = self.start_slow_paths(Some(Repr::Tagged))?;+ self.exit_instead_of_slow_path(&mut slow_paths);+ if target.is_none() {+ self.branch_to_slow_path(&mut slow_paths, BranchCondition::Builtin(builtin), vec![callee], true);+ }+ let numbers = arguments+ .into_iter()+ .map(|argument| self.float64_of_number(&mut slow_paths, argument))+ .collect();+ let result = self.emit(Op::CallFloat64Function { function }, numbers, Some(Repr::Float64));+ let result = self.emit(Op::BoxFloat64, vec![result], Some(Repr::Tagged));+ let result = self+ .join_slow_paths(slow_paths, Some(result))+ .expect("the instruction has a value");+ self.write(dst, result)?;+ Ok(Flow::Continue)+ }+/// The `Repr::Int32` value of `value`, if it is known to be an int32:/// itself, or what it boxes.pub(super) fn int32_value_of(&self, value: NodeId) -> Option<NodeId> {diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/float64.rs b/Libraries/LibJS/JIT/Rust/src/codegen/float64.rsindex d7e8d02faac..e5146d25f9a 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/float64.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/float64.rs@@ -5,9 +5,10 @@*///! Lowering of number ops: unboxing and boxing of numbers, double-//! arithmetic and comparisons, conversions, and `Math` functions of one-//! double. `Repr::Float64` values are in floating point registers.+//! arithmetic and comparisons, conversions, and `Math` functions of+//! doubles. `Repr::Float64` values are in floating point registers.+use crate::CompileFailure;use crate::asm::Condition;use crate::asm::DoubleCondition;use crate::asm::Gpr;@@ -17,6 +18,7 @@ use crate::codegen::Codegen;use crate::codegen::InputValue;use crate::ir::BinaryOp;use crate::ir::Comparison;+use crate::ir::Float64Function;use crate::ir::Float64UnaryOp;use crate::ir::NodeId;use crate::ir::value;@@ -103,6 +105,30 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}}+ /// `CallFloat64Function`: calls the runtime's function of doubles. The+ /// registers C calls take doubles in (and return the first in) are+ /// lowering registers, which hold no values.+ pub(in crate::codegen) fn emit_call_float64_function(+ &mut self,+ node: NodeId,+ function: Float64Function,+ ) -> Result<(), CompileFailure> {+ let address = (self.runtime.float64_functions.0)(function);+ if address == 0 {+ return Err(CompileFailure::MissingRuntimeHelper { opcode: None });+ }+ for index in 0..function.argument_count() {+ let argument = M::ARGUMENT_FPRS[index];+ assert_eq!(argument, Self::lowering_fpr(index));+ let input = self.float_input(node, index);+ self.masm.move_double(argument, input);+ }+ self.masm.call_absolute(address);+ let output = self.float_output(node);+ self.masm.move_double(output, M::ARGUMENT_FPRS[0]);+ Ok(())+ }+/// `Float64Binary`: `op` of two doubles.pub(in crate::codegen) fn emit_float64_binary(&mut self, node: NodeId, op: BinaryOp) {let (lhs, rhs, output) = (diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rsindex cdd3e446e71..6b6545d2020 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs@@ -1664,6 +1664,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {}Op::BoxFloat64 => self.emit_box_float64(node_id),Op::Float64Unary { op } => self.emit_float64_unary(node_id, *op),+ Op::CallFloat64Function { function } => self.emit_call_float64_function(node_id, *function)?,Op::Float64Binary { op } => self.emit_float64_binary(node_id, *op),Op::Float64Min | Op::Float64Max => {let (lhs, rhs, output) = (diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rsindex aa4bcab5b90..cb2ba0cf5f5 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs@@ -13,6 +13,7 @@ use crate::builder::OperationInput;use crate::bytecode::EnvironmentCoordinate;use crate::ir::BinaryOp;use crate::ir::Comparison;+use crate::ir::Float64Function;use crate::snapshot::KeyedFeedbackSnapshot;use crate::snapshot::keyed_feedback_bits;@@ -265,9 +266,16 @@ fn marker_runtime() -> RuntimeInfo {O::CallBuiltinMathCeil,O::CallBuiltinMathRound,O::CallBuiltinMathSqrt,+ O::CallBuiltinMathExp,+ O::CallBuiltinMathLog,+ O::CallBuiltinMathSin,+ O::CallBuiltinMathCos,+ O::CallBuiltinMathTan,+ O::CallBuiltinMathPow,] {set(opcode, marker_scalar as *const () as u64);}+ runtime.float64_functions = crate::snapshot::Float64FunctionAddresses(fake_float64_function);for opcode in [O::ObjectPropertyIteratorNext, O::ResolveThisBinding, O::CreateVariable] {set(opcode, marker_put as *const () as u64);}@@ -1216,6 +1224,12 @@ fn fake_object_layout() -> RuntimeLayout {builtin_math_ceil: 11,builtin_math_round: 12,builtin_math_sqrt: 13,+ builtin_math_exp: 14,+ builtin_math_log: 15,+ builtin_math_sin: 16,+ builtin_math_cos: 17,+ builtin_math_tan: 18,+ builtin_math_pow: 19,typeof_strings: crate::snapshot::TypeofStrings::default(),fly_string_cache: 0,fly_string_cache_mask: 0,@@ -3398,6 +3412,191 @@ fn math_builtin_calls() {}}+extern "C" fn fake_exp(number: f64) -> f64 {+ number.exp()+}++extern "C" fn fake_log(number: f64) -> f64 {+ number.ln()+}++extern "C" fn fake_sin(number: f64) -> f64 {+ number.sin()+}++extern "C" fn fake_cos(number: f64) -> f64 {+ number.cos()+}++extern "C" fn fake_tan(number: f64) -> f64 {+ number.tan()+}++extern "C" fn fake_pow(base: f64, exponent: f64) -> f64 {+ base.powf(exponent)+}++fn fake_float64_function(function: Float64Function) -> u64 {+ let function: *const () = match function {+ Float64Function::Exp => fake_exp as *const (),+ Float64Function::Log => fake_log as *const (),+ Float64Function::Sin => fake_sin as *const (),+ Float64Function::Cos => fake_cos as *const (),+ Float64Function::Tan => fake_tan as *const (),+ Float64Function::Pow => fake_pow as *const (),+ };+ function as u64+}++#[test]+fn math_function_calls() {+ type Reference = fn(f64, f64) -> f64;+ let functions: [(u8, Reference); 6] = [+ (14, |number, _| number.exp()),+ (15, |number, _| number.ln()),+ (16, |number, _| number.sin()),+ (17, |number, _| number.cos()),+ (18, |number, _| number.tan()),+ (19, f64::powf),+ ];+ // NB: Where the code exited before, it calls the slow path instead.+ let call_with = |builtin: u8, callee: u64, argument0: u64, argument1: u64, exited: bool| {+ let instruction = match builtin {+ 14 => Instruction::CallBuiltinMathExp {+ call_feedback: 0,+ dst: r(5),+ callee: argument(0),+ this_value: argument(0),+ argument: argument(1),+ expression_string: None,+ },+ 15 => Instruction::CallBuiltinMathLog {+ call_feedback: 0,+ dst: r(5),+ callee: argument(0),+ this_value: argument(0),+ argument: argument(1),+ expression_string: None,+ },+ 16 => Instruction::CallBuiltinMathSin {+ call_feedback: 0,+ dst: r(5),+ callee: argument(0),+ this_value: argument(0),+ argument: argument(1),+ expression_string: None,+ },+ 17 => Instruction::CallBuiltinMathCos {+ call_feedback: 0,+ dst: r(5),+ callee: argument(0),+ this_value: argument(0),+ argument: argument(1),+ expression_string: None,+ },+ 18 => Instruction::CallBuiltinMathTan {+ call_feedback: 0,+ dst: r(5),+ callee: argument(0),+ this_value: argument(0),+ argument: argument(1),+ expression_string: None,+ },+ _ => Instruction::CallBuiltinMathPow {+ call_feedback: 0,+ dst: r(5),+ callee: argument(0),+ this_value: argument(0),+ argument0: argument(1),+ argument1: argument(2),+ expression_string: None,+ },+ };+ let program = assemble(|_| {+ vec![+ Instruction::Enter,+ instruction.clone(),+ Instruction::Return { value: r(5) },+ ]+ });+ let pc = program.offsets[1];+ let (result, _) = run_program_with_snapshot(+ &program,+ &[callee, argument0, argument1],+ |snapshot| {+ if exited {+ snapshot.executables[0].exit_sites = vec![(pc, ExitKind::SlowPath)];+ }+ },+ |_| {},+ );+ if result.status == crate::code::JitStatus::Resume as u64 {+ return EXITED;+ }+ assert_eq!(result.status, RETURNED);+ result.value+ };+ let numbers = [+ 0.0,+ -0.0,+ 0.5,+ -0.5,+ 2.0,+ 10.0,+ -3.25,+ 1e300,+ f64::INFINITY,+ f64::NEG_INFINITY,+ f64::NAN,+ ];+ for (builtin, reference) in functions {+ let callee = fake_function(Some(builtin));+ // NB: Before any exit at the site, the cases the slow path handles+ // exit instead.+ for exited in [true, false] {+ let slow = if exited { MARKER } else { EXITED };+ for number in numbers {+ for exponent in [3.0, -0.5] {+ let expected = box_number(reference(number, exponent));+ assert_eq!(+ call_with(builtin, callee, number.to_bits(), exponent.to_bits(), exited),+ expected,+ "builtin {builtin} of {number:?} and {exponent:?}"+ );+ }+ }+ for integer in [0, 1, -1, 7, i32::MAX, i32::MIN] {+ let expected = box_number(reference(f64::from(integer), 2.0));+ assert_eq!(+ call_with(builtin, callee, value::int32(integer), value::int32(2), exited),+ expected,+ "builtin {builtin} of {integer}"+ );+ }+ // Other callees and arguments take the slow path.+ let one = value::int32(1);+ assert_eq!(+ call_with(builtin, fake_function(Some(builtin - 1)), one, one, exited),+ slow+ );+ assert_eq!(call_with(builtin, fake_function(None), one, one, exited), slow);+ assert_eq!(call_with(builtin, value::UNDEFINED, one, one, exited), slow);+ assert_eq!(call_with(builtin, callee, value::UNDEFINED, one, exited), slow);+ assert_eq!(call_with(builtin, callee, value::TRUE, one, exited), slow);+ }+ }+ // So does an exponent that is no number.+ let one = value::int32(1);+ assert_eq!(+ call_with(19, fake_function(Some(19)), one, value::UNDEFINED, false),+ EXITED+ );+ assert_eq!(+ call_with(19, fake_function(Some(19)), one, value::UNDEFINED, true),+ MARKER+ );+}+/// The fake string `string`, with its length set to `length`.fn with_length(string: u64, length: u32) -> u64 {let address = (string & 0xFFFF_FFFF_FFFF) as *mut u64;diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rsindex c28bb0ad081..456dea1ca4f 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs@@ -270,6 +270,7 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {with_inputs(&format!("{} {} {location}", op.name(), opcode.name()))}Op::Float64Unary { op } => with_inputs(&format!("Float64{}", op.name())),+ Op::CallFloat64Function { function } => with_inputs(&format!("CallFloat64{}", function.name())),Op::Float64Binary { op } => with_inputs(&format!("Float64{op:?}")),Op::Float64Compare { comparison } => with_inputs(&format!("Float64{comparison:?}")),Op::Refine { condition, holds } => {diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rsindex 1ac8b067def..09651f651bb 100644--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs@@ -963,6 +963,13 @@ pub enum Op {/// `Repr::Float64`: NaN if either is NaN, and -0 below +0.Float64Min,Float64Max,+ /// `Math.<function>` of the `Repr::Float64` inputs (two for Pow, one for+ /// the others), as a `Repr::Float64`, through the runtime's function of+ /// doubles for it (see `RuntimeInfo::float64_functions`), which only+ /// computes.+ CallFloat64Function {+ function: Float64Function,+ },/// `input 0 comparison input 1` of two `Repr::Float64` inputs, as a/// `Repr::Bool`: false if either is NaN, but for the inequalities./// Equalities are strict and loose alike.@@ -1179,6 +1186,39 @@ impl Float64UnaryOp {}}+/// What `Op::CallFloat64Function` computes: the `Math` function of that+/// name, of numbers.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum Float64Function {+ Exp,+ Log,+ Sin,+ Cos,+ Tan,+ Pow,+}++impl Float64Function {+ pub fn name(self) -> &'static str {+ match self {+ Float64Function::Exp => "Exp",+ Float64Function::Log => "Log",+ Float64Function::Sin => "Sin",+ Float64Function::Cos => "Cos",+ Float64Function::Tan => "Tan",+ Float64Function::Pow => "Pow",+ }+ }++ /// How many numbers the function takes.+ pub fn argument_count(self) -> usize {+ match self {+ Float64Function::Pow => 2,+ _ => 1,+ }+ }+}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct NodeProperties {/// May need to exit to the interpreter after it returns, resuming after@@ -1245,7 +1285,7 @@ impl Op {..P::PURE},Op::IsCallable => P::PURE,- Op::ToBoolean => P {+ Op::ToBoolean | Op::CallFloat64Function { .. } => P {is_call: true,..P::PURE},@@ -1633,6 +1673,7 @@ impl Op {Op::Float64Binary { .. } => "Float64Binary",Op::Float64Min => "Float64Min",Op::Float64Max => "Float64Max",+ Op::CallFloat64Function { .. } => "CallFloat64Function",Op::Float64Compare { .. } => "Float64Compare",Op::Float64ToInt32 => "Float64ToInt32",Op::Float64ToUint8Clamped => "Float64ToUint8Clamped",diff --git a/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rs b/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rsindex af9d7c974ca..0db9e22a9e6 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rs@@ -129,8 +129,8 @@ fn need(node: &Node, layout: &FrameLayout) -> Need {// those frames, whose full translation initializes it.Op::CallSlowPath { .. } => Need::Published,Op::CallDirect { executable, .. } | Op::CallNative { executable, .. } if *executable != 0 => Need::Published,- // NB: The helper only looks at its argument.- Op::ToBoolean => Need::Nothing,+ // NB: The helpers only look at their arguments.+ Op::ToBoolean | Op::CallFloat64Function { .. } => Need::Nothing,// NB: The generator resumes in the frame, where the interpreter// needs the constants too.Op::Suspend { .. } => Need::Initialized,diff --git a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs b/Libraries/LibJS/JIT/Rust/src/passes/verify.rsindex cf80255c575..eacc8e28cbe 100644--- a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs+++ b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs@@ -89,9 +89,7 @@ pub fn verify_frame_writes(graph: &Graph, layout: &FrameLayout) -> Result<(), Stmatches!(op, Op::InitializeFrame | Op::EnsureFrameInitialized | Op::PublishFrame);!matches!(op, Op::StoreSlot { .. })&& !(is_argument && initializes_frame)- && (properties.is_call- || properties.reads != Locations::NONE- || properties.writes != Locations::NONE)+ && (properties.reads != Locations::NONE || properties.writes != Locations::NONE)});let reads_frame = reader.is_some_and(|reader| {let op = &graph.node(*reader).op;@@ -512,6 +510,7 @@ fn expected_input_reprs(graph: &Graph, node: NodeId) -> Option<Vec<Repr>> {Op::Float64Binary { .. } | Op::Float64Min | Op::Float64Max | Op::Float64Compare { .. } => {Some(vec![Repr::Float64, Repr::Float64])}+ Op::CallFloat64Function { function } => Some(vec![Repr::Float64; function.argument_count()]),Op::Int32Min | Op::Int32Max | Op::Uint32Min => Some(vec![Repr::Int32, Repr::Int32]),Op::Uint32ShiftRight => Some(vec![Repr::Int32, Repr::Int32]),Op::Uint32ToFloat64 | Op::IntegerToString => Some(vec![Repr::Int32]),diff --git a/Libraries/LibJS/JIT/Rust/src/snapshot.rs b/Libraries/LibJS/JIT/Rust/src/snapshot.rsindex c447fd45177..af244880171 100644--- a/Libraries/LibJS/JIT/Rust/src/snapshot.rs+++ b/Libraries/LibJS/JIT/Rust/src/snapshot.rs@@ -13,6 +13,7 @@use std::sync::Arc;+use crate::ir::Float64Function;use crate::ir::Locations;use crate::bytecode::EnvironmentCoordinate;@@ -823,6 +824,17 @@ impl Default for HelperCallAddresses {}}+/// `u64 (Float64Function)`: the address of the runtime's `double+/// (double...)` function that computes a `Float64Function`, or 0.+#[derive(Debug, Clone, Copy)]+pub struct Float64FunctionAddresses(pub fn(Float64Function) -> u64);++impl Default for Float64FunctionAddresses {+ fn default() -> Self {+ Self(|_| 0)+ }+}+impl Intrinsic {/// How JIT code calls the builtin through its runtime helper, if it/// does.@@ -943,6 +955,9 @@ pub struct RuntimeInfo {/// The runtime helpers of the intrinsics JIT code calls through them/// (see `Intrinsic::helper_call()`).pub helper_calls: HelperCallAddresses,+ /// The runtime's functions of doubles that `Op::CallFloat64Function`+ /// calls.+ pub float64_functions: Float64FunctionAddresses,/// `u64 libjs_jit_to_object(VM*, u64 primitive, u64 function)`: ToObject/// of a primitive other than undefined and null, as the builtin/// `function` makes it, or the empty value if that function is of@@ -1628,13 +1643,20 @@ pub struct RuntimeLayout {/// `Builtin` values.pub builtin_string_prototype_char_code_at: u8,pub builtin_string_prototype_char_at: u8,- /// `JS::Builtin::MathAbs`, `MathFloor`, `MathCeil`, `MathRound` and- /// `MathSqrt`.+ /// `JS::Builtin::MathAbs`, `MathFloor`, `MathCeil`, `MathRound`,+ /// `MathSqrt`, `MathExp`, `MathLog`, `MathSin`, `MathCos`, `MathTan` and+ /// `MathPow`.pub builtin_math_abs: u8,pub builtin_math_floor: u8,pub builtin_math_ceil: u8,pub builtin_math_round: u8,pub builtin_math_sqrt: u8,+ pub builtin_math_exp: u8,+ pub builtin_math_log: u8,+ pub builtin_math_sin: u8,+ pub builtin_math_cos: u8,+ pub builtin_math_tan: u8,+ pub builtin_math_pow: u8,/// The strings `typeof` results in, as values, or all 0 for code/// without them.pub typeof_strings: TypeofStrings,diff --git a/Libraries/LibJS/Rust/src/jit/calls.rs b/Libraries/LibJS/Rust/src/jit/calls.rsindex 14dc7a9b0e5..b00ceb16f53 100644--- a/Libraries/LibJS/Rust/src/jit/calls.rs+++ b/Libraries/LibJS/Rust/src/jit/calls.rs@@ -10,6 +10,7 @@use core::ptr::NonNull;use libjs_abi::register;+use libjs_jit::ir::Float64Function;use super::code::EntryStatus;use super::entry_exit::{can_enter_jit_code, enter_jit_code};@@ -45,11 +46,13 @@ use crate::runtime::error_types::ErrorType;use crate::runtime::function_prototype::FunctionPrototype;use crate::runtime::intrinsics::Intrinsics;use crate::runtime::iterator::get_iterator_values;+use crate::runtime::math_object;use crate::runtime::native_javascript_backed_function::NativeJavaScriptBackedFunction;use crate::runtime::primitive_string::PrimitiveString;use crate::runtime::property_attributes::DEFAULT_ATTRIBUTES;use crate::runtime::property_key::PropertyKey;use crate::runtime::shared_function_instance_data::{ConstructorKind, FunctionKind, ThisMode};+use crate::runtime::value_conversions;/// Calls through Function.prototype.call/apply and bound functions are unwrapped this many times before the generic/// call machinery takes over.@@ -933,6 +936,44 @@ pub extern "C" fn libjs_jit_primitive_to_string(vm: &Vm, primitive: u64) -> u64Value::from_string(primitive.to_primitive_string(vm).must()).0}+/// The address of the runtime's `double (double...)` function that computes `function`, which JIT code calls with+/// numbers (see `Op::CallFloat64Function`).+pub fn float64_function_address(function: Float64Function) -> u64 {+ let function: *const () = match function {+ Float64Function::Exp => libjs_jit_math_exp as *const (),+ Float64Function::Log => libjs_jit_math_log as *const (),+ Float64Function::Sin => libjs_jit_math_sin as *const (),+ Float64Function::Cos => libjs_jit_math_cos as *const (),+ Float64Function::Tan => libjs_jit_math_tan as *const (),+ Float64Function::Pow => libjs_jit_math_pow as *const (),+ };+ function as u64+}++extern "C" fn libjs_jit_math_exp(number: f64) -> f64 {+ math_object::exp_of_number(number)+}++extern "C" fn libjs_jit_math_log(number: f64) -> f64 {+ math_object::log_of_number(number)+}++extern "C" fn libjs_jit_math_sin(number: f64) -> f64 {+ math_object::sin_of_number(number)+}++extern "C" fn libjs_jit_math_cos(number: f64) -> f64 {+ math_object::cos_of_number(number)+}++extern "C" fn libjs_jit_math_tan(number: f64) -> f64 {+ math_object::tan_of_number(number)+}++extern "C" fn libjs_jit_math_pow(base: f64, exponent: f64) -> f64 {+ value_conversions::exp_double(base, exponent)+}+/// `u64 libjs_jit_to_object(VM*, u64 primitive, u64 function)`: ToObject of a primitive other than undefined and/// null, as the builtin function `function` makes it, or the empty value if that function is of another realm.///diff --git a/Libraries/LibJS/Rust/src/jit/runtime_info.rs b/Libraries/LibJS/Rust/src/jit/runtime_info.rsindex cb31c3856bd..be2d9f5689a 100644--- a/Libraries/LibJS/Rust/src/jit/runtime_info.rs+++ b/Libraries/LibJS/Rust/src/jit/runtime_info.rs@@ -15,8 +15,8 @@ use libjs_abi::value as nan_box;use libjs_jit::bytecode::OpCode;use libjs_jit::codegen::slow_path_symbol;use libjs_jit::snapshot::{- CellId, DynamicCallLayout, HelperCallAddresses, IntrinsicHelpers, RuntimeInfo, RuntimeLayout, RuntimeOffsets,- TypeofStrings,+ CellId, DynamicCallLayout, Float64FunctionAddresses, HelperCallAddresses, IntrinsicHelpers, RuntimeInfo,+ RuntimeLayout, RuntimeOffsets, TypeofStrings,};use super::allocation::{AllocationInfos, FUNCTION_ENVIRONMENT_FREE_LIST_COUNT};@@ -221,6 +221,12 @@ fn runtime_layout() -> RuntimeLayout {builtin_math_ceil: Builtin::MathCeil as u8,builtin_math_round: Builtin::MathRound as u8,builtin_math_sqrt: Builtin::MathSqrt as u8,+ builtin_math_exp: Builtin::MathExp as u8,+ builtin_math_log: Builtin::MathLog as u8,+ builtin_math_sin: Builtin::MathSin as u8,+ builtin_math_cos: Builtin::MathCos as u8,+ builtin_math_tan: Builtin::MathTan as u8,+ builtin_math_pow: Builtin::MathPow as u8,// NB: Filled in by runtime_info().typeof_strings: TypeofStrings::default(),fly_string_cache: 0,@@ -471,6 +477,7 @@ pub fn runtime_info(vm: &Vm, realm: Gc<Realm>, allocation: AllocationInfos) -> Rto_boolean: addresses.to_boolean,primitive_to_string: super::calls::libjs_jit_primitive_to_string as *const () as u64,helper_calls: HelperCallAddresses(super::helper_calls::address),+ float64_functions: Float64FunctionAddresses(super::calls::float64_function_address),to_object: super::calls::libjs_jit_to_object as *const () as u64,array_create: super::calls::libjs_jit_array_create as *const () as u64,intrinsic_helpers: IntrinsicHelpers {diff --git a/Libraries/LibJS/Rust/src/runtime/math_object.rs b/Libraries/LibJS/Rust/src/runtime/math_object.rsindex a79bbc824e9..5a8ae1b5727 100644--- a/Libraries/LibJS/Rust/src/runtime/math_object.rs+++ b/Libraries/LibJS/Rust/src/runtime/math_object.rs@@ -1230,18 +1230,23 @@ pub fn cos_impl(vm: &Vm, value: Value) -> ThrowCompletionOr<Value> {// 1. Let n be ? ToNumber(x).let number = value.to_number(vm)?;+ Ok(Value::from_f64(cos_of_number(number.as_f64())))+}++/// The steps of Math.cos after ToNumber, which JIT code also calls.+pub fn cos_of_number(number: f64) -> f64 {// 2. If n is NaN, n is +∞𝔽, or n is -∞𝔽, return NaN.- if number.is_nan() || number.is_infinity() {- return Ok(js_nan());+ if number.is_nan() || number.is_infinite() {+ return f64::NAN;}// 3. If n is +0𝔽 or n is -0𝔽, return 1𝔽.- if number.is_positive_zero() || number.is_negative_zero() {- return Ok(Value::from_i32(1));+ if number == 0.0 {+ return 1.0;}// 4. Return an implementation-approximated Number value representing the result of the cosine of ℝ(n).- Ok(Value::from_f64(number.as_f64().cos()))+ number.cos()}// 21.3.2.14 Math.exp ( x ), https://tc39.es/ecma262/#sec-math.exp@@ -1249,23 +1254,28 @@ pub fn exp_impl(vm: &Vm, x: Value) -> ThrowCompletionOr<Value> {// 1. Let n be ? ToNumber(x).let number = x.to_number(vm)?;+ Ok(Value::from_f64(exp_of_number(number.as_f64())))+}++/// The steps of Math.exp after ToNumber, which JIT code also calls.+pub fn exp_of_number(number: f64) -> f64 {// 2. If n is either NaN or +∞𝔽, return n.- if number.is_nan() || number.is_positive_infinity() {- return Ok(number);+ if number.is_nan() || number == f64::INFINITY {+ return number;}// 3. If n is either +0𝔽 or -0𝔽, return 1𝔽.- if number.as_f64() == 0.0 {- return Ok(Value::from_i32(1));+ if number == 0.0 {+ return 1.0;}// 4. If n is -∞𝔽, return +0𝔽.- if number.is_negative_infinity() {- return Ok(Value::from_i32(0));+ if number == f64::NEG_INFINITY {+ return 0.0;}// 5. Return an implementation-approximated Number value representing the result of the exponential function of ℝ(n).- Ok(Value::from_f64(number.as_f64().exp()))+ number.exp()}// 21.3.2.16 Math.floor ( x ), https://tc39.es/ecma262/#sec-math.floor@@ -1302,28 +1312,33 @@ pub fn log_impl(vm: &Vm, x: Value) -> ThrowCompletionOr<Value> {// 1. Let n be ? ToNumber(x).let number = x.to_number(vm)?;+ Ok(Value::from_f64(log_of_number(number.as_f64())))+}++/// The steps of Math.log after ToNumber, which JIT code also calls.+pub fn log_of_number(number: f64) -> f64 {// 2. If n is NaN or n is +∞𝔽, return n.- if number.is_nan() || number.is_positive_infinity() {- return Ok(number);+ if number.is_nan() || number == f64::INFINITY {+ return number;}// 3. If n is 1𝔽, return +0𝔽.- if number.as_f64() == 1.0 {- return Ok(Value::from_i32(0));+ if number == 1.0 {+ return 0.0;}// 4. If n is +0𝔽 or n is -0𝔽, return -∞𝔽.- if number.is_positive_zero() || number.is_negative_zero() {- return Ok(js_negative_infinity());+ if number == 0.0 {+ return f64::NEG_INFINITY;}// 5. If n < -0𝔽, return NaN.- if number.as_f64() < -0.0 {- return Ok(js_nan());+ if number < -0.0 {+ return f64::NAN;}// 6. Return an implementation-approximated Number value representing the result of the natural logarithm of ℝ(n).- Ok(Value::from_f64(number.as_f64().ln()))+ number.ln()}// 21.3.2.27 Math.pow ( base, exponent ), https://tc39.es/ecma262/#sec-math.pow@@ -1378,18 +1393,23 @@ pub fn sin_impl(vm: &Vm, value: Value) -> ThrowCompletionOr<Value> {// 1. Let n be ? ToNumber(x).let number = value.to_number(vm)?;+ Ok(Value::from_f64(sin_of_number(number.as_f64())))+}++/// The steps of Math.sin after ToNumber, which JIT code also calls.+pub fn sin_of_number(number: f64) -> f64 {// 2. If n is NaN, n is +0𝔽, or n is -0𝔽, return n.- if number.is_nan() || number.is_positive_zero() || number.is_negative_zero() {- return Ok(number);+ if number.is_nan() || number == 0.0 {+ return number;}// 3. If n is +∞𝔽 or n is -∞𝔽, return NaN.- if number.is_infinity() {- return Ok(js_nan());+ if number.is_infinite() {+ return f64::NAN;}// 4. Return an implementation-approximated Number value representing the result of the sine of ℝ(n).- Ok(Value::from_f64(number.as_f64().sin()))+ number.sin()}// 21.3.2.33 Math.sqrt ( x ), https://tc39.es/ecma262/#sec-math.sqrt@@ -1427,16 +1447,21 @@ pub fn tan_impl(vm: &Vm, value: Value) -> ThrowCompletionOr<Value> {// Let n be ? ToNumber(x).let number = value.to_number(vm)?;+ Ok(Value::from_f64(tan_of_number(number.as_f64())))+}++/// The steps of Math.tan after ToNumber, which JIT code also calls.+pub fn tan_of_number(number: f64) -> f64 {// 2. If n is NaN, n is +0𝔽, or n is -0𝔽, return n.- if number.is_nan() || number.is_positive_zero() || number.is_negative_zero() {- return Ok(number);+ if number.is_nan() || number == 0.0 {+ return number;}// 3. If n is +∞𝔽, or n is -∞𝔽, return NaN.- if number.is_infinity() {- return Ok(js_nan());+ if number.is_infinite() {+ return f64::NAN;}// 4. Return an implementation-approximated Number value representing the result of the tangent of ℝ(n).- Ok(Value::from_f64(number.as_f64().tan()))+ number.tan()}diff --git a/Tests/LibJS/JIT/ir/math-and-string-builtins.js b/Tests/LibJS/JIT/ir/math-and-string-builtins.jsindex 92d2734ba1a..d542a169976 100644--- a/Tests/LibJS/JIT/ir/math-and-string-builtins.js+++ b/Tests/LibJS/JIT/ir/math-and-string-builtins.js@@ -101,3 +101,38 @@ jit.compile(absAndSqrt);// CHECK: Float64Roundconsole.log(absAndSqrt(-9), absAndSqrt(16));++// Math.exp, log, sin, cos, tan and pow of numbers call the runtime's functions+// of doubles, which only compute: the code after them keeps what it knew.++function bias(base, values) {+ let sum = 0;+ for (let i = 0; i < values.length; ++i) sum += Math.pow(values[i], Math.log(1 - base * 0.5) / Math.LN2);+ return sum;+}+jit.prepare(bias);+for (let i = 0; i < 10; ++i) bias(0.25, [0.5, 0.75]);+jit.compile(bias);++// CHECK-FUNCTION: bias+// CHECK-PASS: graph building+// CHECK: CallFloat64Log+// CHECK: CallFloat64Pow+// CHECK-NOT: CallSlowPath CallBuiltinMath++function trigonometry(x) {+ return Math.sin(x) + Math.cos(x) + Math.tan(x) + Math.exp(x);+}+jit.prepare(trigonometry);+for (let i = 0; i < 10; ++i) trigonometry(i * 0.5);+jit.compile(trigonometry);++// CHECK-FUNCTION: trigonometry+// CHECK-PASS: dead code elimination+// CHECK: CallFloat64Sin+// CHECK: CallFloat64Cos+// CHECK: CallFloat64Tan+// CHECK: CallFloat64Exp+// CHECK-NOT: CallSlowPath++console.log(bias(0.25, [0.5, 0.75]), trigonometry(0.5), trigonometry(2));diff --git a/Tests/LibJS/Runtime/jit/math-functions.js b/Tests/LibJS/Runtime/jit/math-functions.jsindex 64f6f9cd542..f5faac7c6e1 100644--- a/Tests/LibJS/Runtime/jit/math-functions.js+++ b/Tests/LibJS/Runtime/jit/math-functions.js@@ -1,7 +1,9 @@// JIT code computes Math.abs, Math.floor, Math.ceil, Math.round and-// Math.sqrt of numbers inline. These tests run every function many times,-// so that with a low JIT threshold they are compiled, and compare its results-// with the expected ones, -0 and the int32 range boundaries included.+// Math.sqrt of numbers inline, and calls the runtime's functions of doubles for+// Math.exp, Math.log, Math.sin, Math.cos, Math.tan and Math.pow. These tests+// run every function many times, so that with a low JIT threshold they are+// compiled, and compare its results with the expected ones, -0, the+// infinities and the int32 range boundaries included.const iterations = 100;@@ -74,3 +76,92 @@ describe("Math functions of one number in JIT code", () => {expect(functions.abs(-1)).toBe(1);});});++const computedFunctions = {+ exp: value => Math.exp(value),+ log: value => Math.log(value),+ sin: value => Math.sin(value),+ cos: value => Math.cos(value),+ tan: value => Math.tan(value),+};++// [argument, exp, log, sin, cos, tan]+const computedCases = [+ [0, 1, -Infinity, 0, 1, 0],+ [-0, 1, -Infinity, -0, 1, -0],+ [1, Math.E, 0, Math.sin(1), Math.cos(1), Math.tan(1)],+ [-1, 1 / Math.E, NaN, -Math.sin(1), Math.cos(1), -Math.tan(1)],+ [Infinity, Infinity, Infinity, NaN, NaN, NaN],+ [-Infinity, 0, NaN, NaN, NaN, NaN],+ [NaN, NaN, NaN, NaN, NaN, NaN],+];++// [base, exponent, power]+const powers = [+ [2, 10, 1024],+ [4, 0.5, 2],+ [-2, 3, -8],+ [3, -1, 1 / 3],+ [NaN, 0, 1],+ [NaN, -0, 1],+ [1, NaN, NaN],+ [1, Infinity, NaN],+ [-8, 1 / 3, NaN],+ [0, -1, Infinity],+ [-0, -1, -Infinity],+ [-0, -2, Infinity],+ [-0, 3, -0],+ [-Infinity, 3, -Infinity],+ [-Infinity, -3, -0],+ [0.5, -Infinity, Infinity],+ [2147483647, 1, 2147483647],+ [-2147483648, 1, -2147483648],+];++const pow = (base, exponent) => Math.pow(base, exponent);++describe("Math functions the runtime computes in JIT code", () => {+ test("numbers", () => {+ const names = Object.keys(computedFunctions);+ const show = value => (Object.is(value, -0) ? "-0" : `${value}`);+ const mismatches = [];+ for (let i = 0; i < iterations; ++i) {+ for (const [argument, ...expected] of computedCases) {+ names.forEach((name, index) => {+ const result = computedFunctions[name](argument);+ if (!Object.is(result, expected[index]))+ mismatches.push(`${name}(${show(argument)}) = ${show(result)}, not ${show(expected[index])}`);+ });+ }+ for (const [base, exponent, expected] of powers) {+ const result = pow(base, exponent);+ if (!Object.is(result, expected))+ mismatches.push(`pow(${show(base)}, ${show(exponent)}) = ${show(result)}, not ${show(expected)}`);+ }+ }+ expect(mismatches).toEqual([]);+ });++ test("values that are not numbers", () => {+ for (let i = 0; i < iterations; ++i) {+ expect(computedFunctions.exp("0")).toBe(1);+ expect(computedFunctions.log({ valueOf: () => 1 })).toBe(0);+ expect(computedFunctions.sin(null)).toBe(0);+ expect(computedFunctions.cos(undefined)).toBeNaN();+ expect(pow(true, "3")).toBe(1);+ expect(pow(2, { valueOf: () => 3 })).toBe(8);+ }+ });++ test("replaced functions", () => {+ for (let i = 0; i < iterations; ++i) expect(pow(i, 1)).toBe(i);+ const original = Math.pow;+ try {+ Math.pow = () => "replaced";+ expect(pow(2, 2)).toBe("replaced");+ } finally {+ Math.pow = original;+ }+ expect(pow(2, 2)).toBe(4);+ });+});