Skip to content

Truly independent web browser

LibJS: Take variable shift amounts in RCX in the JIT on x86-64

Andreas Klinge9139d5b3ec7
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.md
index 29bbbc316c3..82158174587 100644
--- a/Libraries/LibJS/JIT/ARCHITECTURE.md
+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md
@@ -432,17 +432,20 @@ unreachable. Each one keeps the graph valid (`passes/verify.rs`), and IR tests i
Every node declares what its lowering needs in `codegen::lowering_info()`, one exhaustive match next
to the lowerings: where each input must be (a register, a register of the calling convention, a
-register or an immediate constant, or anywhere, its stack slot included), where its output goes (a
-register or the return register), how many temps it takes (with a comment saying what each is for),
-what its code clobbers beyond those (nothing; every floating point register, for nodes whose out of
-line code calls the runtime saving only the general purpose registers; or every caller-saved
-register, for calls), whether its output may take the register of its first input where that dies,
-and which parts of the JIT frame it uses (the saves area, the operand record). The register
-allocator, its verifier and the frame layout read it instead of keeping lists of ops of their own.
-In debug builds and with `verify-ir`, code generation checks the lowerings against it: each lowering
-takes exactly the temps it declares (through `Codegen::temp()`, also on paths that do not use them),
-and only nodes that declare it use the saves area. The verifier of the allocation checks that every
-node got the temps it declares, and that no value an exit needs is in the node's output register.
+register or an immediate constant, the register the target shifts by
+(`RegisterSet::shift_amount_gpr`, RCX on x86-64, any register on AArch64) or an immediate constant,
+or anywhere, its stack slot included), where its output goes (a register or the return register),
+how many temps it takes (with a comment saying what each is for), what its code clobbers beyond
+those (nothing; every floating point register, for nodes whose out of line code calls the runtime
+saving only the general purpose registers; or every caller-saved register, for calls), whether its
+output may take the register of its first input where that dies, and which parts of the JIT frame it
+uses (the saves area, the operand record). The register allocator, its verifier and the frame layout
+read it instead of keeping lists of ops of their own. In debug builds and with `verify-ir`, code
+generation checks the lowerings against it: each lowering takes exactly the temps it declares
+(through `Codegen::temp()`, also on paths that do not use them), and only nodes that declare it use
+the saves area. The verifier of the allocation checks that every node got the temps it declares,
+that inputs of a fixed register are in it, and that no value an exit needs is in the node's output
+register.
To be written: the forward walk, spills at definition, merges and their state predecessor, cold
blocks, the verifier.
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/aarch64/macro_assembler.rs b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/macro_assembler.rs
index e756381b657..5ee8591c8f4 100644
--- a/Libraries/LibJS/JIT/Rust/src/asm/aarch64/macro_assembler.rs
+++ b/Libraries/LibJS/JIT/Rust/src/asm/aarch64/macro_assembler.rs
@@ -463,6 +463,7 @@ impl PortableMacroAssembler for MacroAssembler {
/// x0-x15 and x19-x28.
const ALLOCATABLE_GPRS: GprSet = GprSet(0x1ff8_ffff);
const ALLOCATABLE_FPRS: FprSet = FprSet(0x7fff_ffff);
+ const SHIFT_AMOUNT_GPR: Option<Gpr> = None;
const STACK_POINTER: Gpr = SP;
const FRAME_POINTER: Gpr = FP;
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rs b/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rs
index 4bf8981a4e1..c0fa49daa8a 100644
--- a/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rs
+++ b/Libraries/LibJS/JIT/Rust/src/asm/macro_assembler.rs
@@ -75,6 +75,8 @@ pub trait PortableMacroAssembler: Sized {
/// What the register allocator may use.
const ALLOCATABLE_GPRS: GprSet;
const ALLOCATABLE_FPRS: FprSet;
+ /// The register shifts by a register amount take the amount in, on targets that shift by one register only.
+ const SHIFT_AMOUNT_GPR: Option<Gpr>;
const STACK_POINTER: Gpr;
const FRAME_POINTER: Gpr;
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs
index 8c9bb73f9c8..d0e003c6852 100644
--- a/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs
+++ b/Libraries/LibJS/JIT/Rust/src/asm/x86_64/macro_assembler.rs
@@ -214,7 +214,8 @@ impl MacroAssembler {
self.assembler.shift_ri(op, width, dst, amount);
}
- /// Shifts by a register amount, which x86 needs in CL.
+ /// Shifts by a register amount, which x86 needs in CL. The register allocator puts the amounts of shift nodes there
+ /// (see `SHIFT_AMOUNT_GPR`), and other amounts go through the scratch registers.
fn shift_register(&mut self, op: ShiftOp, width: Width, dst: Gpr, src: Gpr, amount: Gpr) {
if amount == RCX && dst != RCX {
self.mov_if_needed(width, dst, src);
@@ -362,6 +363,7 @@ impl PortableMacroAssembler for MacroAssembler {
const SCRATCH_FPRS: FprSet = FprSet::of(&[FP_SCRATCH]);
const ALLOCATABLE_GPRS: GprSet = GprSet::of(&[RAX, RCX, RDX, RBX, RSI, RDI, R8, R9, R12, R13, R14, R15]);
const ALLOCATABLE_FPRS: FprSet = FprSet(0x7fff);
+ const SHIFT_AMOUNT_GPR: Option<Gpr> = Some(RCX);
const STACK_POINTER: Gpr = RSP;
const FRAME_POINTER: Gpr = RBP;
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs b/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs
index 38b42c4534a..4bb67365bea 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs
@@ -35,6 +35,9 @@ pub enum FixedRegister {
Argument(u8),
/// The register calls return their (first) result in.
Return,
+ /// The register shifts by a register amount take the amount in, on targets that have one (see
+ /// `RegisterSet::shift_amount_gpr`).
+ ShiftAmount,
}
/// Where a node finds one of its inputs.
@@ -48,6 +51,10 @@ pub enum InputConstraint {
RegisterOrConstant,
/// Wherever the value is: a register, its stack slot or a constant.
Anywhere,
+ /// The amount of a shift: the constant itself if the input is one, which code generation uses as an immediate,
+ /// and otherwise the register the target shifts by, or any register on targets that shift by any (see
+ /// `RegisterSet::resolve()`).
+ ShiftAmount,
}
/// Where a node puts its value.
@@ -147,6 +154,12 @@ impl LoweringInfo {
self
}
+ /// Shifts by input `index`, which it takes as an immediate if it is a constant.
+ fn with_shift_amount(mut self, index: usize) -> Self {
+ self.inputs[index] = InputConstraint::ShiftAmount;
+ self
+ }
+
/// Calls a runtime function with the VM in the first argument register and its inputs in the next ones, returning
/// its value.
fn runtime_call(node: &Node) -> Self {
@@ -270,6 +283,15 @@ pub fn lowering_info(node: &Node) -> LoweringInfo {
reuses_first_input: true,
..plain.with_immediate(1).with_temps(1)
},
+ Op::Int32Binary {
+ op: BinaryOp::LeftShift | BinaryOp::RightShift | BinaryOp::UnsignedRightShift,
+ }
+ | Op::Int32WrappingBinary {
+ op: BinaryOp::UnsignedRightShift,
+ } => LoweringInfo {
+ reuses_first_input: true,
+ ..plain.with_shift_amount(1)
+ },
Op::Int32Binary { .. } | Op::Int32WrappingBinary { .. } => LoweringInfo {
reuses_first_input: true,
..plain.with_immediate(1)
@@ -389,7 +411,7 @@ pub fn lowering_info(node: &Node) -> LoweringInfo {
},
Op::Float64Min | Op::Float64Max | Op::CallFloat64Function { .. } | Op::Float64Compare { .. } => plain,
Op::Float64ToInt32 | Op::Float64ToUint8Clamped | Op::CheckFloat64Int32 => plain,
- Op::Uint32ShiftRight => plain.with_immediate(1),
+ Op::Uint32ShiftRight => plain.with_shift_amount(1),
Op::Uint32ToFloat64 | Op::StringAddress | Op::StringLength | Op::LoadStringCodeUnit => plain,
Op::SingleCharacterString => plain,
// The first string's address, then its length or its storage word.
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index cac12296326..5e6bcf48174 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -160,6 +160,7 @@ pub fn target_registers<M: PortableMacroAssembler>() -> (RegisterSet, PinnedRegi
caller_saved_fprs: RegisterMask(u64::from(M::CALLER_SAVED_FPRS.0)),
argument_gprs: M::ARGUMENT_GPRS.iter().map(|register| register.0).collect(),
return_gpr: M::RETURN_GPRS[0].0,
+ shift_amount_gpr: M::SHIFT_AMOUNT_GPR.map(|register| register.0),
scratch_gpr: pinned.scratch.0,
};
(registers, pinned)
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
index e8852d05d67..e1fd032f239 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
@@ -2446,6 +2446,36 @@ fn slow_paths_save_no_more_registers_than_the_saves_area_holds() {
check::<crate::asm::aarch64::MacroAssembler>();
}
+#[test]
+fn x86_64_shifts_find_their_amount_in_cl() {
+ let program = assemble(|_| {
+ vec![
+ Instruction::Enter,
+ Instruction::BitwiseXorRhsInt32 {
+ arith_feedback: 1,
+ dst: r(4),
+ lhs: a(0),
+ rhs: 5,
+ },
+ Instruction::LeftShift {
+ arith_feedback: 0,
+ dst: r(5),
+ lhs: a(0),
+ rhs: r(4),
+ },
+ Instruction::Return { value: r(5) },
+ ]
+ });
+ let mut snapshot = crate::builder::tests::snapshot_for(&program, test_layout());
+ snapshot.runtime = runtime();
+ snapshot.executables[0].feedback.arith = vec![crate::snapshot::arith_feedback::INT32; 2];
+ let compiled = compile_for::<crate::asm::x86_64::MacroAssembler>(&snapshot, &|_| true).unwrap();
+ let text = crate::asm::disassembler::x86_64(&compiled.code[..compiled.data_offset as usize]).join("\n");
+ // NB: The macro assembler shifts amounts in other registers in a scratch register, saving RCX in another.
+ assert!(text.contains(", cl"), "{text}");
+ assert!(!text.contains("r11d, cl") && !text.contains("mov r10, rcx"), "{text}");
+}
+
#[test]
fn dumps_ir_and_code_on_request() {
let program = assemble(|_| vec![Instruction::Enter, Instruction::Return { value: a(0) }]);
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
index 3ce4cf636e6..07361e4749a 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
@@ -137,6 +137,8 @@ pub struct RegisterSet {
pub argument_gprs: Vec<u8>,
/// Where calls return their (first) result.
pub return_gpr: u8,
+ /// Where shifts by a register amount take the amount, on targets that shift by one register only.
+ pub shift_amount_gpr: Option<u8>,
/// Never allocated. Moves between stack slots and of constants into stack
/// slots go through it, and node lowerings may clobber it.
pub scratch_gpr: u8,
@@ -156,6 +158,20 @@ impl RegisterSet {
match register {
FixedRegister::Argument(index) => self.argument_gprs[usize::from(index)],
FixedRegister::Return => self.return_gpr,
+ FixedRegister::ShiftAmount => self
+ .shift_amount_gpr
+ .expect("only targets with a shift amount register have fixed shift amounts"),
+ }
+ }
+
+ /// Where an input of `constraint` must be on this target, if it is a constant (`is_constant`) or not.
+ pub fn resolve(&self, constraint: InputConstraint, is_constant: bool) -> InputConstraint {
+ match constraint {
+ InputConstraint::ShiftAmount if is_constant || self.shift_amount_gpr.is_none() => {
+ InputConstraint::RegisterOrConstant
+ }
+ InputConstraint::ShiftAmount => InputConstraint::Fixed(FixedRegister::ShiftAmount),
+ constraint => constraint,
}
}
@@ -165,11 +181,11 @@ impl RegisterSet {
}
/// The fewest allocatable registers allocation works with: the ones
- /// calls take their arguments and return their results in, and
- /// `extra` more.
+ /// calls take their arguments and return their results in, the one
+ /// shifts take their amount in, and `extra` more.
pub fn few_registers(&self, extra: u32) -> RegisterMask {
let mut mask = RegisterMask(0).with(self.return_gpr);
- for register in &self.argument_gprs {
+ for register in self.argument_gprs.iter().chain(&self.shift_amount_gpr) {
mask = mask.with(*register);
}
let mut mask = RegisterMask(mask.0 & self.allocatable_gprs.0);
@@ -195,6 +211,7 @@ impl RegisterSet {
caller_saved_fprs: RegisterMask(0b1111_1111),
argument_gprs: vec![1, 2, 3],
return_gpr: 0,
+ shift_amount_gpr: None,
scratch_gpr: 7,
}
}
@@ -611,13 +628,22 @@ impl<'a> Allocator<'a> {
let node = self.graph.node(node_id);
self.position = self.liveness.positions[node_id.index()];
let constraints = lowering_info(node);
+ let input_constraints = constraints
+ .inputs
+ .iter()
+ .zip(&node.inputs)
+ .map(|(constraint, input)| {
+ self.registers
+ .resolve(*constraint, self.graph.constant_value(*input).is_some())
+ })
+ .collect::<InlineVec<_, 4>>();
let mut moves = Vec::new();
let mut blocked = RegisterMask::default();
let mut inputs = InlineVec::from_elem(Location::Register(0), node.inputs.len());
// Fixed register inputs first, so that inputs in any register do not
// take their registers.
- for (index, (input, constraint)) in node.inputs.iter().zip(&constraints.inputs).enumerate() {
+ for (index, (input, constraint)) in node.inputs.iter().zip(&input_constraints).enumerate() {
let InputConstraint::Fixed(register) = *constraint else {
continue;
};
@@ -645,7 +671,7 @@ impl<'a> Allocator<'a> {
blocked = blocked.with(register);
inputs[index] = Location::Register(register);
}
- for (index, (input, constraint)) in node.inputs.iter().zip(&constraints.inputs).enumerate() {
+ for (index, (input, constraint)) in node.inputs.iter().zip(&input_constraints).enumerate() {
if *constraint == InputConstraint::RegisterOrConstant
&& let Some(bits) = self.graph.constant_value(*input)
{
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
index 49e5ae3b9b9..2e4959d03bc 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
@@ -517,6 +517,62 @@ fn int32_operations_write_over_their_first_input_where_it_dies() {
);
}
+#[test]
+fn shift_amounts_are_in_the_targets_shift_register_or_immediates() {
+ let program = assemble(|_| {
+ vec![
+ Instruction::Enter,
+ Instruction::BitwiseXorRhsInt32 {
+ arith_feedback: 2,
+ dst: r(4),
+ lhs: a(0),
+ rhs: 5,
+ },
+ Instruction::LeftShift {
+ arith_feedback: 0,
+ dst: r(5),
+ lhs: a(0),
+ rhs: r(4),
+ },
+ Instruction::RightShiftRhsInt32 {
+ arith_feedback: 1,
+ dst: r(6),
+ lhs: r(5),
+ rhs: 3,
+ },
+ Instruction::Return { value: r(6) },
+ ]
+ });
+ let mut snapshot = crate::builder::tests::snapshot_for(&program, crate::bytecode::test_support::test_layout());
+ snapshot.executables[0].feedback.arith = vec![crate::snapshot::arith_feedback::INT32; 3];
+ let graph = crate::builder::tests::optimized_graph(&snapshot);
+ let shift = |op| find_node(&graph, |node| node.op == Op::Int32Binary { op });
+ let (variable, constant) = (
+ shift(crate::ir::BinaryOp::LeftShift),
+ shift(crate::ir::BinaryOp::RightShift),
+ );
+ for shift_amount_gpr in [None, Some(3), Some(4)] {
+ let registers = RegisterSet {
+ shift_amount_gpr,
+ ..RegisterSet::test_configuration()
+ };
+ let allocation = allocate(&graph, &registers);
+ if let Err(errors) = verify(&graph, &registers, &allocation) {
+ panic!("{errors}\n{}", dump_allocation(&graph, &allocation));
+ }
+ let dump = dump_allocation(&graph, &allocation);
+ let amount = allocation.node(variable).inputs[1];
+ match shift_amount_gpr {
+ Some(register) => assert_eq!(amount, Location::Register(register), "{dump}"),
+ None => assert!(matches!(amount, Location::Register(_)), "{dump}"),
+ }
+ assert!(
+ matches!(allocation.node(constant).inputs[1], Location::Constant(bits) if bits as u32 == 3),
+ "{dump}"
+ );
+ }
+}
+
#[test]
fn float64_operations_write_over_their_first_input_where_it_dies() {
// The first product dies at the second, whose output then takes its register, also for non-commutative
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs
index 8457e42e709..e474829cbd0 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs
@@ -317,6 +317,11 @@ impl Verifier<'_> {
if !matches!(location, Location::Register(_)) && !reads_input_anywhere {
self.error(format!("{context}: input {index} is not in a register"));
}
+ if let InputConstraint::Fixed(register) = self.registers.resolve(lowering.inputs[index], false)
+ && *location != Location::Register(self.registers.fixed(register))
+ {
+ self.error(format!("{context}: input {index} is not in its fixed register"));
+ }
self.check_location(*location, &context);
self.expect(state, *location, *input, &format!("{context}, input {index}"));
}