Truly independent web browser
/*
* Copyright (c) 2026-present, the Ladybird developers.
*
* SPDX-License-Identifier: BSD-2-Clause
*/
//! Selection of legal target instructions from target-independent LowIR.
use super::ir::{Function, Instruction, Operand, Program};
use crate::Architecture;
use crate::low_ir::preallocate::{
materialize_program_counter_reads, orient_commutative_updates, schedule_x86_relational_operand_loads,
split_rematerializable_live_ranges_across_calls,
};
use crate::low_ir::{self, AddressDisplacement, Operand as LowOperand};
use crate::target::description::{IntegerWidth, Operation};
use crate::{CompileError, CompileStage};
pub(crate) fn select_program(
mut program: low_ir::Program,
architecture: Architecture,
) -> Result<Program, CompileError> {
let functions = std::mem::take(&mut program.handlers)
.into_iter()
.map(|mut handler| -> Result<_, CompileError> {
materialize_program_counter_reads(&mut handler.instructions)
.map_err(|message| selection_error(&handler.name, message))?;
if architecture == Architecture::X86_64 {
schedule_x86_relational_operand_loads(&mut handler.instructions);
}
orient_commutative_updates(&mut handler.instructions);
split_rematerializable_live_ranges_across_calls(&mut handler.instructions);
materialize_constant_register_inputs(&mut handler.instructions);
if architecture == Architecture::X86_64 {
materialize_wide_immediates(&mut handler.instructions);
}
// Splitting and constant materialization create new virtual registers, so interning must follow them.
let virtual_registers = low_ir::intern_virtual_registers(handler.id, &mut handler.instructions);
let mut instructions = Vec::with_capacity(handler.instructions.len());
for mut instruction in handler.instructions {
let operation = instruction.opcode;
for (index, operand) in instruction.operands.iter_mut().enumerate() {
legalize_operand(operand, operation, index, architecture, &handler.name)?;
}
let mut operands = instruction.operands;
if operation == Operation::Move(IntegerWidth::U32)
&& let Some(Operand::Immediate(value)) = operands.get_mut(1)
{
*value = (*value as u64 & 0xffff_ffff) as i64;
}
let opcode = instruction.opcode.select_for_operands(architecture, &operands);
debug_assert_eq!(opcode.architecture(), architecture);
if architecture == Architecture::Aarch64
&& matches!(
operation,
Operation::IntegerBinary {
operation: crate::intrinsic::IntegerBinaryOperation::Binary(
crate::target::description::BinaryOperation::Add
),
width: IntegerWidth::U64,
}
)
&& let Some(Operand::Immediate(value)) = operands.get_mut(1)
{
match opcode.aarch64() {
crate::target::aarch64::Opcode::AddSubtractImmediate {
operation: crate::target::aarch64::AddSubtractOperation::Subtract,
..
} => {
*value = value.checked_neg().ok_or_else(|| {
CompileError::new(
CompileStage::Selection,
Some(&handler.name),
"AArch64 add immediate cannot be negated",
)
})?;
}
crate::target::aarch64::Opcode::AddSubtractImmediate {
shift: crate::target::aarch64::ImmediateShift::Twelve,
..
} => {
*value >>= 12;
}
_ => {}
}
}
opcode.add_contract_operands(&mut operands);
instructions.push(Instruction { opcode, operands });
}
Ok(Function {
id: handler.id,
name: handler.name,
size: handler.size,
is_cold: handler.is_cold,
architecture,
virtual_registers,
instructions,
})
})
.collect::<Result<_, _>>()?;
Ok(Program {
runtime: program.runtime,
dispatch_handlers: program.dispatch_handlers,
dispatch: program.dispatch,
architecture,
functions,
})
}
fn materialize_constant_register_inputs(instructions: &mut Vec<low_ir::Instruction>) {
let mut materialized = Vec::with_capacity(instructions.len());
for (instruction_index, mut instruction) in std::mem::take(instructions).into_iter().enumerate() {
let description = instruction.opcode.description();
let operand_count = instruction.operands.len();
for (operand_index, operand) in instruction.operands.iter_mut().enumerate() {
if description.operand_kind(operand_index, operand_count) != Some(super::description::OperandKind::GprIn)
|| !matches!(operand, LowOperand::Immediate(_) | LowOperand::ValueConstant(_))
{
continue;
}
let register = LowOperand::VirtualRegister(low_ir::VirtualRegister::new(format!(
"constant_{instruction_index}_{operand_index}"
)));
materialized.push(low_ir::Instruction {
opcode: Operation::Move(IntegerWidth::U64),
operands: vec![register.clone(), std::mem::replace(operand, register)],
});
}
materialized.push(instruction);
}
*instructions = materialized;
}
/// x86-64 compares, combines, and multiplies 64-bit registers only with sign-extended 32-bit immediates, so other
/// immediates go into a register first, which also spares the operations scratch registers of their own.
fn materialize_wide_immediates(instructions: &mut Vec<low_ir::Instruction>) {
let mut materialized = Vec::with_capacity(instructions.len());
for (instruction_index, mut instruction) in std::mem::take(instructions).into_iter().enumerate() {
let compares_64_bits = matches!(
instruction.opcode,
Operation::Branch(
crate::intrinsic::BranchOperation::Equality {
width: IntegerWidth::U64,
..
} | crate::intrinsic::BranchOperation::Ordered {
width: IntegerWidth::U64,
..
}
) | Operation::AssertBranch(
crate::intrinsic::BranchOperation::Equality {
width: IntegerWidth::U64,
..
} | crate::intrinsic::BranchOperation::Ordered {
width: IntegerWidth::U64,
..
}
)
);
let combines_64_bits = matches!(
instruction.opcode,
Operation::IntegerBinary {
operation: crate::intrinsic::IntegerBinaryOperation::Binary(
crate::target::description::BinaryOperation::Add
| crate::target::description::BinaryOperation::Subtract
| crate::target::description::BinaryOperation::And
| crate::target::description::BinaryOperation::Or
| crate::target::description::BinaryOperation::Xor
),
width: IntegerWidth::U64,
}
);
// Masking with 0xffffffff is a 32-bit move, which needs no immediate.
let is_low_half_mask = matches!(
instruction.opcode,
Operation::IntegerBinary {
operation: crate::intrinsic::IntegerBinaryOperation::Binary(
crate::target::description::BinaryOperation::And
),
..
}
) && matches!(instruction.operands.get(1), Some(LowOperand::Immediate(value)) if *value as u64 == 0xffff_ffff);
let multiplies_64_bits = matches!(
instruction.opcode,
Operation::IntegerBinary {
operation: crate::intrinsic::IntegerBinaryOperation::Binary(
crate::target::description::BinaryOperation::Multiply
),
width: IntegerWidth::U64,
}
);
// A multiplication can take its immediate in any input position, the others take it second.
let candidates = if multiplies_64_bits {
1..instruction.operands.len()
} else if compares_64_bits || combines_64_bits {
1..instruction.operands.len().min(2)
} else {
0..0
};
for position in candidates {
if is_low_half_mask {
break;
}
let operand = &mut instruction.operands[position];
if !matches!(operand, LowOperand::Immediate(value) if i32::try_from(*value).is_err()) {
continue;
}
let register = LowOperand::VirtualRegister(low_ir::VirtualRegister::new(format!(
"wide_immediate_{instruction_index}_{position}"
)));
materialized.push(low_ir::Instruction {
opcode: Operation::Move(IntegerWidth::U64),
operands: vec![register.clone(), std::mem::replace(operand, register)],
});
}
materialized.push(instruction);
}
*instructions = materialized;
}
fn legalize_operand(
operand: &mut LowOperand,
operation: Operation,
operand_index: usize,
architecture: Architecture,
handler: &str,
) -> Result<(), CompileError> {
let operation = match operation {
Operation::AssertBranch(branch) => Operation::Branch(branch),
operation => operation,
};
match operand {
LowOperand::VirtualRegister(register) => {
debug_assert!(register.id().is_some());
}
LowOperand::ValueConstant(value) => {
let compares_value_tag = operand_index == 1
&& (matches!(operation, Operation::Branch(crate::intrinsic::BranchOperation::Tag(_)))
|| (matches!(
operation,
Operation::Branch(crate::intrinsic::BranchOperation::Singleton(_))
) && architecture == Architecture::X86_64));
*operand = LowOperand::Immediate(if compares_value_tag {
((*value as u64) >> 48) as i64
} else {
*value
});
}
LowOperand::LayoutConstant(constant) => {
return Err(selection_error(
handler,
format!("unresolved layout constant #{}", constant.id().index()),
));
}
LowOperand::BytecodeField(field) => {
return Err(selection_error(
handler,
format!("unresolved bytecode field #{}", field.index()),
));
}
LowOperand::Address(address) => {
for register in std::iter::once(&address.base).chain(address.index.iter()) {
if let low_ir::AddressRegister::Virtual(register) = register {
debug_assert!(register.id().is_some());
}
}
if let Some(crate::low_ir::AddressScale::LayoutConstant(constant)) = &address.scale {
return Err(selection_error(
handler,
format!("unresolved address scale layout constant #{}", constant.id().index()),
));
}
if let Some(AddressDisplacement::LayoutConstant(constant)) = &address.displacement {
return Err(selection_error(
handler,
format!(
"unresolved address displacement layout constant #{}",
constant.id().index()
),
));
}
if let Some(AddressDisplacement::BytecodeField(field)) = &address.displacement {
return Err(selection_error(
handler,
format!("unresolved bytecode field #{}", field.index()),
));
}
}
_ => {}
}
Ok(())
}
fn selection_error(handler: &str, message: impl Into<String>) -> CompileError {
CompileError::new(CompileStage::Selection, Some(handler), message)
}