Skip to content

Truly independent web browser

LibJS: Declare what the JIT knows about each op in two tables

Andreas Klingb277da9bd85a
diff --git a/Libraries/LibJS/JIT/ARCHITECTURE.md b/Libraries/LibJS/JIT/ARCHITECTURE.md
index a8893d031df..9a43f4197ec 100644
--- a/Libraries/LibJS/JIT/ARCHITECTURE.md
+++ b/Libraries/LibJS/JIT/ARCHITECTURE.md
@@ -58,8 +58,10 @@ keep it there.
### 3.1 Effects
-`Op::properties()` describes every op's effects, and every pass decides what it may do with a node
-from them alone:
+`Op::info()` (`ir/info.rs`) decides, for every op in one exhaustive match, its effects
+(`NodeProperties`), its exit kind, the input it refines (section 3.2), whether it ends a block, and
+the inputs it takes (`Inputs`: how many, of which representations), which the verifier checks every
+node against. Every pass decides what it may do with a node from its effects alone:
- **Exits.** `Op::can_eager_exit()`, whether the op has an exit kind (`Op::exit_kind()`): may exit
before its side effects, resuming at the current bytecode (needs the eager frame state).
@@ -76,7 +78,7 @@ from them alone:
one question: whether one node's writes intersect another's reads. `runs_code`: may run other
code, which may write anything, or invalidate the compiled code. The op table below names the
locations coarsely (Named for slots and shapes, Elements for values and counts, Any for all);
- `Op::properties()` has the exact sets.
+ `Op::info()` has the exact sets.
- **Allocation.** `allocates`: may allocate, so may run the garbage collector.
Global value numbering shares nodes without effects that read no memory; check elimination reuses
@@ -425,8 +427,22 @@ unreachable. Each one keeps the graph valid (`passes/verify.rs`), and IR tests i
## 7. Register allocation
-To be written: the forward walk, node constraints, spills at definition, merges and their state
-predecessor, cold blocks, the verifier.
+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.
+
+To be written: the forward walk, spills at definition, merges and their state predecessor, cold
+blocks, the verifier.
## 8. Code generation and the runtime interface
@@ -455,8 +471,9 @@ explicitly:
stack pointer goes through `emit_prologue()` or `allocate_stack()`, which touch the pages on the
way down (with the stack probes in `asm::x86_64`, which the Wasm JIT shares). Code that moves it
any other way can skip the guard pages and fault. Compiled functions check the native stack limit
- before they touch their frames, with `emit_prologue_unprobed()` and `probe_frame()`, so that a
- frame that does not fit makes the code exit instead of touching past the end of the stack.
+ before their prologue moves the stack pointer (`Codegen::emit_prologue()` compares the lowest
+ address of the frame with `Vm::jit_native_stack_limit`), so that a frame that does not fit makes
+ the code exit instead of touching past the end of the stack.
## 9. Speculation and exits
@@ -609,7 +626,7 @@ Options for debugging the JIT:
| `dump-passes` | Print the IR after building it and after every pass. |
| `dump-asm` | Print the machine code of every compile. |
| `dump-feedback` | Print the interpreter feedback of each function the first time it gets hot. |
-| `verify-ir` | Check the invariants of the IR after building it and after every pass, also in release builds. |
+| `verify-ir` | Check the IR, the register allocation and the lowerings (sections 6 and 7), also in release builds.|
| `log-exits` | Print every exit from compiled code to the interpreter, and every discard of compiled code. |
| `perf-map` | Describe compiled code in `/tmp/perf-<pid>.map` for `perf`. |
| `coverage=DIRECTORY` | Write what compiled code contained and did into `DIRECTORY`, one JSON file per VM. |
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
index af9ead09daa..137f83f636a 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs
@@ -1415,7 +1415,7 @@ impl<'a> GraphBuilder<'a> {
Instruction::Enter => {
// NB: Inlined frames are set up by the caller.
if !self.function.is_virtual() {
- self.emit(Op::InitializeFrame { clobbers_floats: false }, Vec::new(), None);
+ self.emit(Op::InitializeFrame, Vec::new(), None);
let this_value = self.emit(
Op::LoadSlot {
slot: THIS_VALUE_REGISTER,
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs
index fbe21954201..4fadd56b749 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/allocation.rs
@@ -56,10 +56,6 @@ pub(super) struct DeferredAllocation {
}
impl<M: PortableMacroAssembler> Codegen<'_, M> {
- fn allocation_temp(&self, node: NodeId, index: usize) -> Gpr {
- Gpr(self.allocation.node(node).temps[index])
- }
-
/// `dst` = the value with tag `tag` of the cell pointer `src`, which is
/// `src` with what the two differ in flipped: cells are in the heap
/// region, which is aligned to its size, so a cell pointer is the
@@ -113,6 +109,8 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
) -> Result<(), CompileFailure> {
let info = &self.runtime.object_allocation;
let (entry, resume) = self.defer_allocation(node, AllocationCall::Object(shape, reserve));
+ // NB: The fallback to the runtime call takes no temps, but the lowering declares them for the fast path.
+ let (heap, next) = (self.temp(node, 0), self.temp(node, 1));
// NB: The cell's fields up to the inline storage come from the
// template, patched with the shape and the inline capacity.
let template_bytes = 8 * info.template.len() as u64;
@@ -128,11 +126,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
return Ok(());
};
- let (cell, heap, next) = (
- self.output(node),
- self.allocation_temp(node, 0),
- self.allocation_temp(node, 1),
- );
+ let cell = self.output(node);
let info = self.runtime.object_allocation.clone();
let at = |base: Gpr, offset: u32| Address::new(base, offset as i32);
@@ -306,11 +300,11 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
/// Stores into a named property of an object being initialized, which
/// is a plain data property (see `Op::InitializeNamed`).
pub(super) fn emit_initialize_named(&mut self, node: NodeId, offset: u32) -> Result<(), CompileFailure> {
+ let storage = self.temp(node, 0);
// NB: The allocation stored constants already.
if self.absorbed_initializations.contains(&node) {
return Ok(());
}
- let storage = self.allocation_temp(node, 0);
let object = self.input(node, 0);
// NB: Objects allocated in a size class keep their properties inline, until their first indexed property. A
// computed key of the literal can give them one, but only further down than right after the allocation.
@@ -435,6 +429,8 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
const MAX_INLINE_ELEMENTS: u32 = 64;
let info = self.runtime.array_allocation.clone();
let (entry, resume) = self.defer_allocation(node, AllocationCall::Array(count));
+ // NB: The fallback to the runtime call takes no temps, but the lowering declares them for the fast path.
+ let (storage, temp) = (self.temp(node, 0), self.temp(node, 1));
let storage_size_class = info
.storage_size_classes
.iter()
@@ -467,7 +463,6 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
}
let array = self.output(node);
- let (storage, temp) = (self.allocation_temp(node, 0), self.allocation_temp(node, 1));
let scratch = self.pinned.scratch;
let at = |base: Gpr, offset: u32| Address::new(base, offset as i32);
@@ -537,7 +532,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
/// Stores into an element of an array being initialized (see
/// `Op::InitializeElement`).
pub(super) fn emit_initialize_element(&mut self, node: NodeId, index: u32) -> Result<(), CompileFailure> {
- let elements = self.allocation_temp(node, 0);
+ let elements = self.temp(node, 0);
let slot = self.named_property_address(elements, index)?;
self.emit_unbox_cell(elements, self.input(node, 0));
let elements_field = Address::new(elements, self.runtime.layout.object_indexed_elements as i32);
@@ -562,6 +557,8 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
.cloned()
.ok_or(CompileFailure::CodeGeneration)?;
let (entry, resume) = self.defer_allocation(node, AllocationCall::Environment(shape_cache, capacity));
+ // NB: The fallback to the runtime call takes no temps, but the lowering declares them for the fast path.
+ let (environment, temp) = (self.temp(node, 0), self.temp(node, 1));
let template_bytes = 8 * template.words.len() as u64;
let stored = [(template.binding_values_offset, 8), (template.outer_offset, 4)];
let fits = template.allocator != 0
@@ -576,7 +573,6 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
// NB: The output may be in the register of the input.
let output = self.output(node);
let parent = self.input(node, 0);
- let (environment, temp) = (self.allocation_temp(node, 0), self.allocation_temp(node, 1));
let at = |base: Gpr, offset: u32| Address::new(base, offset as i32);
self.emit_check_heap_threshold(template.cell_size, environment, temp, entry);
@@ -618,6 +614,8 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
.cloned()
.ok_or(CompileFailure::CodeGeneration)?;
let (entry, resume) = self.defer_allocation(node, AllocationCall::Function(closure.sample));
+ // NB: The fallback to the runtime call takes no temps, but the lowering declares them for the fast path.
+ let (function, temp) = (self.temp(node, 0), self.temp(node, 1));
let objects = self.runtime.object_allocation.clone();
let offsets = self.runtime.offsets;
let stored = [
@@ -637,7 +635,6 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
// NB: The output may be in the register of an input.
let output = self.output(node);
let (environment, private_environment) = (self.input(node, 0), self.input(node, 1));
- let (function, temp) = (self.allocation_temp(node, 0), self.allocation_temp(node, 1));
let at = |base: Gpr, offset: u32| Address::new(base, offset as i32);
// NB: Functions with a private environment have rare data, unlike the template.
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs
index 0cde1181bbb..387d0299aeb 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/call_stub.rs
@@ -143,6 +143,11 @@ fn generate_stub<M: PortableMacroAssembler>(runtime: &RuntimeInfo, construct: bo
deferred_storage_growths: Vec::new(),
absorbed_initializations: Vec::new(),
inline_initializations: Default::default(),
+ // NB: The stub lowers no nodes.
+ verify: false,
+ emitting: None,
+ requested_temps: Vec::new(),
+ undeclared_saves_area_uses: Default::default(),
};
codegen.emit_call_stub(construct)?;
let (code, _) = codegen
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs b/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs
index cadb6a987f1..633c4c0d704 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/concatenation.rs
@@ -33,8 +33,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
/// value. Needs three temps.
pub(in crate::codegen) fn emit_concatenate_strings(&mut self, node: NodeId) {
let (lhs, rhs, output) = (self.input(node, 0), self.input(node, 1), self.output(node));
- let temps = &self.allocation.node(node).temps;
- let temps = [Gpr(temps[0]), Gpr(temps[1]), Gpr(temps[2])];
+ let temps = [self.temp(node, 0), self.temp(node, 1), self.temp(node, 2)];
let (slow, done) = (self.masm.new_label(), self.masm.new_label());
let mut resume = None;
if self.runtime.rope_allocation.allocator != 0 && self.rope_template_fits() {
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs b/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs
new file mode 100644
index 00000000000..8495315341b
--- /dev/null
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs
@@ -0,0 +1,531 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! What the lowering of each node needs from register allocation and the frame layout, declared next to the
+//! lowerings in one exhaustive match (`lowering_info()`): where its inputs and its output are, how many temps it
+//! takes, what it clobbers out of line, and which parts of the JIT frame it uses. The register allocator, its verifier
+//! and the frame layout read it from here, and code generation checks that each lowering takes exactly the temps it
+//! declares and uses the saves area only where it says so (see `Codegen::verify_lowerings()`).
+
+use super::Codegen;
+use super::DIRECT_CALL_TEMPS;
+use super::SlowPathCall;
+use super::probes::PUT_BY_ID_RECORD_BYTES;
+use super::slow_path_call;
+use crate::asm::Gpr;
+use crate::asm::PortableMacroAssembler;
+use crate::code::Repr;
+use crate::inline_vec::InlineVec;
+use crate::ir::BinaryOp;
+use crate::ir::BlockId;
+use crate::ir::BranchCondition;
+use crate::ir::Node;
+use crate::ir::NodeId;
+use crate::ir::Op;
+
+/// A register of the target's calling convention, which the register allocator resolves (see
+/// `RegisterSet::fixed()`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum FixedRegister {
+ /// Argument register `n` of calls.
+ Argument(u8),
+ /// The register calls return their (first) result in.
+ Return,
+}
+
+/// Where a node finds one of its inputs.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
+pub enum InputConstraint {
+ #[default]
+ Register,
+ Fixed(FixedRegister),
+ /// A register, or the constant itself if the input is one, which code
+ /// generation uses as an immediate.
+ RegisterOrConstant,
+ /// Wherever the value is: a register, its stack slot or a constant.
+ Anywhere,
+}
+
+/// Where a node puts its value.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum OutputConstraint {
+ None,
+ Register,
+ /// The register calls return their result in.
+ Return,
+}
+
+/// The registers a node's code clobbers, beyond its temps, its output and the scratch register.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Clobbers {
+ Nothing,
+ /// Every floating point register: its out of line code calls the runtime saving only the general purpose
+ /// registers that may hold values (see `slow_path_saved_registers()`). Float64 values live across it get stack
+ /// slots, like values live across a call.
+ Floats,
+ /// Every register a call clobbers: it is a call (`NodeProperties::is_call`).
+ CallerSaved,
+}
+
+/// The part of the operand record (see `Locals::record`) a node's code uses.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Record {
+ None,
+ Bytes(u32),
+ /// The operands of the slow path of its instruction, and the stack arguments of its call, which the frame layout
+ /// sizes from the bytecode (see `Codegen::lay_out_frame()`).
+ SlowPathOperands,
+}
+
+/// What the lowering of a node needs (see `lowering_info()`).
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct LoweringInfo {
+ pub inputs: InlineVec<InputConstraint, 4>,
+ pub output: OutputConstraint,
+ /// How many general purpose registers it computes with, besides its inputs and its output, which no input is in.
+ pub temps: u8,
+ pub clobbers: Clobbers,
+ /// Whether it computes its output from its first input as two-address instructions do, so that the output may take
+ /// the register of that input where it dies.
+ pub reuses_first_input: bool,
+ /// Whether its code uses the saves area (see `Locals::saves`), wherever it runs.
+ pub uses_saves_area: bool,
+ /// Whether, in an inlined callee, it runs in the published frames of the inlined calls it is in (see
+ /// `Codegen::emit_publish_frames()`), which also uses the saves area.
+ pub publishes_frames: bool,
+ /// Whether it runs a slow path or a call that may leave compiled code, so that in an inlined callee, its leave
+ /// writes its frame state (see `Codegen::leave_frame_of()`).
+ pub may_leave_from_inlined_callee: bool,
+ pub record: Record,
+}
+
+impl LoweringInfo {
+ /// Takes its inputs in registers, from which it computes its value (if it has one) in a register, and nothing else.
+ fn plain(node: &Node) -> Self {
+ Self {
+ inputs: InlineVec::from_elem(InputConstraint::Register, node.inputs.len()),
+ output: if node.repr.is_some() {
+ OutputConstraint::Register
+ } else {
+ OutputConstraint::None
+ },
+ temps: 0,
+ clobbers: if node.op.properties().is_call {
+ Clobbers::CallerSaved
+ } else {
+ Clobbers::Nothing
+ },
+ reuses_first_input: false,
+ uses_saves_area: false,
+ publishes_frames: false,
+ may_leave_from_inlined_callee: false,
+ record: Record::None,
+ }
+ }
+
+ fn with_temps(self, temps: u8) -> Self {
+ Self { temps, ..self }
+ }
+
+ /// Calls the runtime out of line saving only the general purpose registers, in the saves area.
+ fn saving_registers(self) -> Self {
+ debug_assert_eq!(self.clobbers, Clobbers::Nothing, "calls clobber more");
+ Self {
+ clobbers: Clobbers::Floats,
+ uses_saves_area: true,
+ ..self
+ }
+ }
+
+ /// Takes input `index` as an immediate if it is a constant.
+ fn with_immediate(mut self, index: usize) -> Self {
+ self.inputs[index] = InputConstraint::RegisterOrConstant;
+ 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 {
+ Self {
+ inputs: (0..node.inputs.len())
+ .map(|index| InputConstraint::Fixed(FixedRegister::Argument(index as u8 + 1)))
+ .collect(),
+ output: OutputConstraint::Return,
+ ..Self::plain(node)
+ }
+ }
+}
+
+/// What the lowering of `node` needs. Nodes without code (constants, phis, virtual objects, refinements and legacy
+/// arguments guards, which are gone before register allocation) need nothing but what every node does.
+pub fn lowering_info(node: &Node) -> LoweringInfo {
+ let plain = LoweringInfo::plain(node);
+ match &node.op {
+ Op::Constant(_) | Op::Phi | Op::VirtualObject { .. } | Op::Refine { .. } | Op::AssumeLegacyArgumentsUnread => {
+ plain
+ }
+ Op::LoadSlot { .. } | Op::StoreSlot { .. } | Op::PublishFrame | Op::Suspend { .. } => plain,
+ // A value and a cursor for filling the registers and locals.
+ Op::InitializeFrame | Op::EnsureFrameInitialized => plain.with_temps(2),
+ Op::LoadOuterEnvironment | Op::LoadEnvironmentBinding { .. } => plain,
+ // The environment's binding values.
+ Op::StoreEnvironmentBinding { .. } => plain.with_temps(1),
+ // The index of the appended binding.
+ Op::AppendEnvironmentBinding => plain.with_temps(1),
+ Op::BoxCell | Op::SetLexicalEnvironment | Op::LeavePrivateEnvironment | Op::IsCallable => plain,
+ Op::ToBoolean => LoweringInfo {
+ inputs: InlineVec::from_elem(InputConstraint::Fixed(FixedRegister::Argument(0)), 1),
+ output: OutputConstraint::Return,
+ ..plain
+ },
+ // NB: The VM is the first argument.
+ Op::PrimitiveToString | Op::CallIntrinsic { .. } | Op::ToObject | Op::ArrayCreate => {
+ LoweringInfo::runtime_call(node)
+ }
+ // NB: The inserted values go on the native stack.
+ Op::CallArraySplice => {
+ let mut info = LoweringInfo::runtime_call(node);
+ for input in info.inputs.iter_mut().skip(3) {
+ *input = InputConstraint::RegisterOrConstant;
+ }
+ info
+ }
+ Op::Generic { opcode, .. } => LoweringInfo {
+ output: if node.repr.is_some() {
+ OutputConstraint::Return
+ } else {
+ OutputConstraint::None
+ },
+ may_leave_from_inlined_callee: true,
+ record: slow_path_record(*opcode, false),
+ ..plain
+ },
+ // NB: The call stores its operands to the frame first.
+ Op::CallDirect {
+ stores_operands: true,
+ inlined_frame_bytes,
+ ..
+ }
+ | Op::CallNative {
+ stores_operands: true,
+ inlined_frame_bytes,
+ ..
+ } => LoweringInfo {
+ inputs: InlineVec::from_elem(InputConstraint::Anywhere, node.inputs.len()),
+ output: OutputConstraint::Return,
+ publishes_frames: *inlined_frame_bytes == 0,
+ may_leave_from_inlined_callee: true,
+ ..plain
+ },
+ // Direct and native calls with inputs build the callee's frame in
+ // temps.
+ Op::CallDirect {
+ inlined_frame_bytes, ..
+ }
+ | Op::CallNative {
+ inlined_frame_bytes, ..
+ } => {
+ let info = LoweringInfo {
+ publishes_frames: *inlined_frame_bytes == 0,
+ may_leave_from_inlined_callee: true,
+ ..plain
+ };
+ if node.inputs.is_empty() {
+ info
+ } else {
+ // NB: Calls in inlined callees return their result.
+ LoweringInfo {
+ output: if node.repr.is_some() {
+ OutputConstraint::Return
+ } else {
+ OutputConstraint::None
+ },
+ ..info.with_temps(DIRECT_CALL_TEMPS)
+ }
+ }
+ }
+ // Native accessor calls build the callee's frame in temps, and return
+ // the result.
+ Op::CallNativeAccessor { .. } => LoweringInfo {
+ output: OutputConstraint::Return,
+ ..plain.with_temps(DIRECT_CALL_TEMPS)
+ },
+ Op::ArgumentCount | Op::LoadFrameField { .. } | Op::LoadArgument { .. } => plain,
+ Op::CallForwardingArguments { .. } => LoweringInfo {
+ may_leave_from_inlined_callee: true,
+ ..plain
+ },
+ Op::CheckInt32 | Op::CheckNumber | Op::BoxInt32 | Op::BoxBool => plain,
+ // NB: Comparisons and int32 arithmetic take a constant right-hand side as an immediate.
+ Op::Int32Binary { op: BinaryOp::Mul } => LoweringInfo {
+ reuses_first_input: true,
+ ..plain
+ },
+ // The quotient of a remainder.
+ Op::Int32Binary { op: BinaryOp::Mod } => LoweringInfo {
+ reuses_first_input: true,
+ ..plain.with_immediate(1).with_temps(1)
+ },
+ Op::Int32Binary { .. } | Op::Int32WrappingBinary { .. } => LoweringInfo {
+ reuses_first_input: true,
+ ..plain.with_immediate(1)
+ },
+ Op::Int32Compare { .. } | Op::TaggedEquals { .. } => plain.with_immediate(1),
+ // The object's address.
+ Op::CheckElements { .. } | Op::CheckTypedArray | Op::CheckArray => plain.with_temps(1),
+ Op::CheckNonNegativeInt32 | Op::LoadTypedArrayLength | Op::LoadTypedArrayDataOffset => plain,
+ Op::TypedArrayDataAddress => LoweringInfo {
+ reuses_first_input: true,
+ ..plain
+ },
+ Op::CheckTypedArrayStorage => plain,
+ Op::CheckBounds => plain.with_immediate(0).with_immediate(1),
+ // The elements or the element address.
+ Op::LoadElementAt { .. } => plain.with_immediate(1).with_temps(1),
+ // The elements or the element address. Stores of integer and tagged constants store immediates.
+ Op::StoreElementAt { kind } => {
+ let info = plain.with_immediate(1).with_temps(1);
+ if kind.stored_repr() == Repr::Float64 {
+ info
+ } else {
+ info.with_immediate(2)
+ }
+ }
+ Op::CheckNotHole | Op::CheckInitialized | Op::CellAddress => plain,
+ // The heap and a value.
+ Op::AllocateObject { .. } => plain.with_temps(2).saving_registers(),
+ // The object's property storage.
+ Op::InitializeNamed { .. } => plain.with_temps(1),
+ // The element storage and a value.
+ Op::AllocateArray { .. } => plain.with_temps(2).saving_registers(),
+ // The array's elements.
+ Op::InitializeElement { .. } => plain.with_temps(1),
+ // The function and a value.
+ Op::AllocateFunction { .. } => plain.with_temps(2).saving_registers(),
+ // The environment and a value.
+ Op::AllocateEnvironment { .. } => plain.with_temps(2).saving_registers(),
+ Op::SliceArguments => LoweringInfo {
+ inputs: InlineVec::from_elem(InputConstraint::Fixed(FixedRegister::Argument(2)), 1),
+ output: OutputConstraint::Return,
+ ..plain
+ },
+ // The tag of an operand, with a bit that tells two of the tags apart set.
+ Op::CheckIdentityComparable => plain.with_temps(1),
+ Op::CheckObject => plain,
+ // The function object.
+ Op::CheckClosure { .. } => plain.with_temps(1),
+ Op::LoadFunctionEnvironment { .. } | Op::CheckValue { .. } => plain,
+ Op::EmptyToUndefined | Op::Typeof | Op::TypeofIs { .. } => plain,
+ Op::CheckShape { .. } | Op::CheckPrototypeChainValid { .. } => plain,
+ // The object whose prototype comes next.
+ Op::HasInPrototypeChain => plain.with_temps(1),
+ Op::AssumeValid | Op::CheckInterrupt | Op::LoadGlobalBinding { .. } => plain,
+ // The environment's binding values.
+ Op::StoreGlobalBinding { .. } => plain.with_temps(1),
+ // The object's property storage, then the accessor.
+ Op::CheckAccessorFunction { .. } => plain.with_temps(1),
+ Op::LoadAccessorFunction { .. } | Op::LoadNamed { .. } => plain,
+ // The object's property storage.
+ Op::AddNamed { .. } | Op::StoreNamed { .. } => plain.with_temps(1),
+ Op::Jump { .. } => plain,
+ Op::Branch { condition, .. } => branch_lowering_info(*condition, plain),
+ Op::BranchTruthy { .. } | Op::BranchOnPc { .. } | Op::ShapeSwitch { .. } => plain,
+ Op::Return => LoweringInfo {
+ inputs: InlineVec::from_elem(InputConstraint::Fixed(FixedRegister::Return), 1),
+ ..plain
+ },
+ Op::Exit { .. } | Op::Unreachable => plain,
+ // NB: Slow path calls read their operands from where they are.
+ Op::CallSlowPath {
+ saves_registers,
+ opcode,
+ ..
+ } => {
+ let info = LoweringInfo {
+ inputs: InlineVec::from_elem(InputConstraint::Anywhere, node.inputs.len()),
+ // NB: A call's value is moved into the return register once its
+ // slow path continued, where a conditional jump's control
+ // word is.
+ output: if !saves_registers && node.repr.is_some() {
+ OutputConstraint::Return
+ } else {
+ plain.output
+ },
+ uses_saves_area: true,
+ publishes_frames: true,
+ may_leave_from_inlined_callee: true,
+ record: slow_path_record(*opcode, true),
+ ..plain
+ };
+ if *saves_registers {
+ LoweringInfo {
+ clobbers: Clobbers::Floats,
+ ..info
+ }
+ } else {
+ info
+ }
+ }
+ Op::UnboxInt32 | Op::Int32Abs | Op::Int32Min | Op::Int32Max | Op::Uint32Min | Op::Int32ToFloat64 => plain,
+ Op::BoolToInt32 => LoweringInfo {
+ reuses_first_input: true,
+ ..plain
+ },
+ Op::UnboxDouble | Op::BoxFloat64 | Op::Float64Unary { .. } | Op::Float64Binary { .. } => plain,
+ Op::Float64Min | Op::Float64Max | Op::CallFloat64Function { .. } | Op::Float64Compare { .. } => plain,
+ Op::Float64ToInt32 | Op::Float64ToUint8Clamped | Op::CheckFloat64Int32 => plain,
+ Op::Uint32ShiftRight => plain.with_immediate(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.
+ Op::StringsEqual => plain.with_temps(1),
+ // The new rope string, its length and a temp.
+ Op::ConcatenateStrings => plain.with_temps(3).saving_registers(),
+ Op::IntegerToString => plain,
+ // The array, then its prototypes.
+ Op::CheckAppendableArray => plain.with_temps(2),
+ Op::LoadElementsLength => plain,
+ // The object's elements.
+ Op::LoadElementsCapacity | Op::AppendElement => plain.with_temps(1),
+ Op::CallArrayPush | Op::CallStoreHoleyElement | Op::OpenArrayIteration => plain.saving_registers(),
+ Op::LoadArrayIteratorArray | Op::LoadArrayIteratorIndex => plain,
+ Op::StoreArrayIteratorIndex | Op::FinishArrayIterator => plain,
+ Op::LoadGeneratorCompletionType | Op::LoadGeneratorCompletionValue => plain,
+ Op::LoadPropertyIteratorKeyCount | Op::LoadPropertyIteratorKey => plain,
+ // NB: The output comes from where the slow path call left it.
+ Op::SlowPathOutput { .. } => LoweringInfo {
+ inputs: InlineVec::from_elem(InputConstraint::Anywhere, 1),
+ ..plain
+ },
+ // The object, its shape and the cache entry.
+ Op::ProbePropertyCache { .. } => plain.with_temps(3).saving_registers(),
+ // The object, its shape and the cache entry.
+ Op::ProbeKeyedCache { .. } => plain.with_temps(3),
+ // The object, its shape, the cache entry and the named property storage of property additions.
+ // NB: It calls no runtime function: the subroutine that grows named property storage keeps every register
+ // but the scratch register, saving the ones it uses in the saves area.
+ Op::ProbeKeyedStore { .. } => LoweringInfo {
+ uses_saves_area: true,
+ ..plain.with_temps(4)
+ },
+ // The object, its shape, the cache entry and the named property storage of property additions.
+ Op::ProbePropertyStore { .. } => LoweringInfo {
+ record: Record::Bytes(PUT_BY_ID_RECORD_BYTES),
+ ..plain.with_temps(4).saving_registers()
+ },
+ // The cache, the global declarative environment, the global object
+ // and a temp.
+ Op::ProbeGlobalCache { .. } | Op::ProbeGlobalStore { .. } => plain.with_temps(4),
+ // The object or its elements, and the keyed cache's registers.
+ Op::ProbeHasProperty { .. } => plain.with_temps(3).saving_registers(),
+ }
+}
+
+/// What a branch on `condition` needs, beyond `plain`.
+fn branch_lowering_info(condition: BranchCondition, plain: LoweringInfo) -> LoweringInfo {
+ match condition {
+ BranchCondition::Bool
+ | BranchCondition::Nullish
+ | BranchCondition::Undefined
+ | BranchCondition::Object
+ | BranchCondition::NonNegativeInt32
+ | BranchCondition::IndexInBounds
+ | BranchCondition::MagicalLength
+ | BranchCondition::Extensible
+ | BranchCondition::ArrayIterator
+ | BranchCondition::GeneratorObject
+ | BranchCondition::HoldsValidWatchpointSet
+ | BranchCondition::Shape(_)
+ | BranchCondition::Float64(_)
+ | BranchCondition::Int32Value
+ | BranchCondition::Int32OrBoolean
+ | BranchCondition::Double
+ | BranchCondition::String
+ | BranchCondition::ResolvedString => plain,
+ // NB: Comparisons take a constant right-hand side as an immediate.
+ BranchCondition::Int32(_) | BranchCondition::TaggedEquals { .. } => plain.with_immediate(1),
+ // The address of the object.
+ BranchCondition::ElementsKind(_) => plain.with_temps(1),
+ // The array's prototypes.
+ BranchCondition::HoleFillableArray => plain.with_temps(1),
+ // The object's prototypes.
+ BranchCondition::PlainArrayPrototypeChain => plain.with_temps(1),
+ // The object's shape.
+ BranchCondition::ArrayWithRealmArrayPrototypeAndNoNamedProperties => plain.with_temps(1),
+ // The function object.
+ BranchCondition::Builtin(_) => plain.with_temps(1),
+ // The binding's index, and a temp.
+ BranchCondition::BindingMutable { .. } => plain.with_temps(2),
+ // The environment's shape and the binding's index.
+ BranchCondition::NextBindingOfShape { .. } => plain.with_temps(2),
+ // The object, the property iterator cache, and a temp.
+ BranchCondition::PropertyIteratorCacheValid => plain.with_temps(3),
+ }
+}
+
+/// The part of the operand record the slow path of `opcode` uses, called by a `CallSlowPath` node (`on_values`) or a
+/// `Generic` one.
+fn slow_path_record(opcode: crate::bytecode::OpCode, on_values: bool) -> Record {
+ match slow_path_call(opcode) {
+ Some(SlowPathCall::Record) => Record::SlowPathOperands,
+ // NB: Binary slow paths called on values write their result into the record.
+ Some(SlowPathCall::BinaryValues) if on_values => Record::Bytes(8),
+ Some(SlowPathCall::BinaryValues | SlowPathCall::JumpValues | SlowPathCall::JitCall) | None => Record::None,
+ }
+}
+
+impl<M: PortableMacroAssembler> Codegen<'_, M> {
+ /// Temp `index` of `node`, which its lowering declares (see `LoweringInfo::temps`). Lowerings take every temp
+ /// they declare through this, even on paths that do not use it, so that the declarations can be checked.
+ pub(super) fn temp(&self, node: NodeId, index: usize) -> Gpr {
+ let requested = &self.requested_temps[node.index()];
+ requested.set(requested.get().max(index as u8 + 1));
+ Gpr(self.allocation.node(node).temps[index])
+ }
+
+ /// Notes that the code being emitted uses the saves area.
+ pub(super) fn note_saves_area_use(&self) {
+ if self.verify
+ && let Some(node) = self.emitting
+ && !self.uses_saves_area(node)
+ {
+ self.undeclared_saves_area_uses.borrow_mut().push(node);
+ }
+ }
+
+ /// Checks that the lowering of every node took exactly the temps it declares, and that only nodes that declare
+ /// it used the saves area, whose size depends on that.
+ pub(super) fn verify_lowerings(&self) -> Result<(), String> {
+ let mut errors = Vec::new();
+ for block in 0..self.graph.blocks.len() {
+ for node in self.graph.block_nodes(BlockId::from_index(block)) {
+ let declared = lowering_info(self.graph.node(node)).temps;
+ let requested = self.requested_temps[node.index()].get();
+ if requested != declared {
+ errors.push(format!(
+ "v{} ({}) takes {requested} temps, but declares {declared}",
+ node.0,
+ self.graph.node(node).op.name()
+ ));
+ }
+ }
+ }
+ let mut undeclared = self.undeclared_saves_area_uses.borrow().clone();
+ undeclared.dedup();
+ for node in undeclared {
+ errors.push(format!(
+ "v{} ({}) uses the saves area, but does not declare it",
+ node.0,
+ self.graph.node(node).op.name()
+ ));
+ }
+ if errors.is_empty() {
+ Ok(())
+ } else {
+ Err(errors.join("\n"))
+ }
+ }
+}
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index 7f7072a052c..1afde74f2d3 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -28,6 +28,7 @@ mod allocation;
mod call;
mod call_stub;
mod entry;
+pub mod lowering_info;
pub use call::DIRECT_CALL_MAX_INPUTS;
pub use call::DIRECT_CALL_TEMPS;
@@ -330,6 +331,14 @@ struct Codegen<'a, M: PortableMacroAssembler> {
/// The no-ops of `AssumeValid` nodes, with the exits that the jumps
/// replacing them go to once the code is invalidated.
invalidation_points: Vec<(usize, Label)>,
+ /// Whether to check that the lowerings match what they declare (see `verify_lowerings()`).
+ verify: bool,
+ /// The node whose code (inline or out of line) is being emitted, if any.
+ emitting: Option<NodeId>,
+ /// How many temps each node's lowering took (see `temp()`).
+ requested_temps: Vec<std::cell::Cell<u8>>,
+ /// The nodes whose code used the saves area without declaring it.
+ undeclared_saves_area_uses: std::cell::RefCell<Vec<NodeId>>,
}
/// The operands of the slow path of a `CallSlowPath` node that is a call,
@@ -404,13 +413,15 @@ struct LeaveStub {
}
/// Generates code for `graph` with `allocation`, whose registers came from
-/// `target_registers::<M>()`.
+/// `target_registers::<M>()`. With `verify` (and in debug builds), checks
+/// that every lowering matches its `lowering_info()`.
pub fn generate<M: PortableMacroAssembler>(
graph: &Graph,
allocation: &Allocation,
executables: &[ExecutableSnapshot],
runtime: &RuntimeInfo,
stress: StressOptions,
+ verify: bool,
) -> Result<GeneratedCode, CompileFailure> {
let (_, pinned) = target_registers::<M>();
let (gpr_dump_count, fpr_dump_count) = register_dump_counts::<M>();
@@ -460,6 +471,10 @@ pub fn generate<M: PortableMacroAssembler>(
slow_path_values: None,
invalidation_points: Vec::new(),
fused_probe_failure: None,
+ verify: verify || cfg!(debug_assertions),
+ emitting: None,
+ requested_temps: vec![std::cell::Cell::new(0); graph.nodes.len()],
+ undeclared_saves_area_uses: std::cell::RefCell::new(Vec::new()),
};
codegen.lay_out_frame()?;
codegen.emit_prologue();
@@ -474,6 +489,11 @@ pub fn generate<M: PortableMacroAssembler>(
codegen.emit_tails();
codegen.emit_frame_initialization_stub()?;
let osr_entries = codegen.emit_osr_entries();
+ if codegen.verify
+ && let Err(errors) = codegen.verify_lowerings()
+ {
+ panic!("lowerings that do not match their declarations:\n{errors}");
+ }
let sites = codegen
.sites
@@ -702,23 +722,19 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let needs_saves_area = (0..self.graph.blocks.len())
.flat_map(|block| self.graph.block_nodes(BlockId::from_index(block)))
.any(|node| self.uses_saves_area(node));
+ // NB: This sizes the record for the nodes that are no longer in any block too.
for node in &self.graph.nodes {
- // NB: The runtime's PutById cache probe takes a record.
- if let Op::ProbePropertyStore { .. } = node.op {
- record_bytes = record_bytes.max(probes::PUT_BY_ID_RECORD_BYTES);
- }
- // NB: Binary slow paths called on values write their result into
- // the record.
- if let Op::CallSlowPath { opcode, .. } = node.op
- && slow_path_call(opcode) == Some(SlowPathCall::BinaryValues)
- {
- record_bytes = record_bytes.max(8);
- }
- match node.op {
- Op::Generic { opcode, executable, pc }
- | Op::CallSlowPath {
- opcode, executable, pc, ..
- } if slow_path_call(opcode) == Some(SlowPathCall::Record) => {
+ match lowering_info::lowering_info(node).record {
+ lowering_info::Record::None => {}
+ lowering_info::Record::Bytes(bytes) => record_bytes = record_bytes.max(bytes),
+ lowering_info::Record::SlowPathOperands => {
+ let (Op::Generic { opcode, executable, pc }
+ | Op::CallSlowPath {
+ opcode, executable, pc, ..
+ }) = node.op
+ else {
+ unreachable!("only slow path calls take their operands in the record");
+ };
let layout = slow_path_layout(opcode);
let (inputs, fixed_registers) = match layout.abi {
SlowPathAbi::Scalar => (
@@ -751,7 +767,6 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
};
record_bytes = record_bytes.max(8 * record);
}
- _ => {}
}
}
let record = outgoing_bytes.next_multiple_of(16);
@@ -949,6 +964,10 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
fn annotate(&mut self, annotation: CodeAnnotation) {
let offset = u32::try_from(self.masm.offset()).expect("code fits in 4 GiB");
self.annotations.push((offset, annotation));
+ self.emitting = match annotation {
+ CodeAnnotation::Node(node) | CodeAnnotation::Deferred(node) => Some(node),
+ _ => None,
+ };
}
fn emit_prologue(&mut self) {
@@ -1372,9 +1391,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.masm.load64(self.output(node_id), &address);
}
Op::StoreSlot { slot } => self.emit_store_slot(node_id, *slot)?,
- Op::InitializeFrame { clobbers_floats } => self.emit_initialize_frame(node_id, *clobbers_floats)?,
- Op::EnsureFrameInitialized { clobbers_floats } => {
- self.emit_ensure_frame_initialized(node_id, *clobbers_floats)?;
+ Op::InitializeFrame => self.emit_initialize_frame(node_id)?,
+ Op::EnsureFrameInitialized => {
+ self.emit_ensure_frame_initialized(node_id)?;
}
Op::PublishFrame => self.emit_publish_frame(),
Op::LoadOuterEnvironment => {
@@ -1707,7 +1726,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
}
Op::StoreGlobalBinding { environment, index } => {
let exit = self.exit_site(node_id);
- let values = Gpr(self.allocation.node(node_id).temps[0]);
+ let values = self.temp(node_id, 0);
let slot = self.global_binding_slot(values, *environment, *index)?;
self.masm
.branch64_memory_imm(Condition::Equal, &slot, value::EMPTY as i64, exit);
@@ -1722,7 +1741,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
}
Op::CheckAccessorFunction { offset, part, function } => {
let exit = self.exit_site(node_id);
- let accessor = Gpr(self.allocation.node(node_id).temps[0]);
+ let accessor = self.temp(node_id, 0);
let field = self.emit_load_accessor(node_id, accessor, *offset, *part, exit)?;
self.masm
.branch32_memory_imm(Condition::NotEqual, &field, function.compressed() as i32, exit);
@@ -1741,7 +1760,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
}
Op::StoreNamed { offset, holds_data } => {
let exit = (!holds_data).then(|| self.exit_site(node_id));
- let storage = Gpr(self.allocation.node(node_id).temps[0]);
+ let storage = self.temp(node_id, 0);
let slot = self.named_property_address(storage, *offset)?;
let cell = self.cell_address_of(node_id, storage, 2);
let storage_field = Address::new(cell, self.runtime.offsets.object_named_properties as i32);
@@ -1923,7 +1942,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let exit = self.exit_site(node);
let (value, prototype) = (self.input(node, 0), self.input(node, 1));
let output = self.output(node);
- let object = Gpr(self.allocation.node(node).temps[0]);
+ let object = self.temp(node, 0);
let scratch = self.pinned.scratch;
let layout = self.runtime.layout;
let offsets = self.runtime.offsets;
@@ -2103,7 +2122,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
fn emit_add_named(&mut self, node_id: NodeId, offset: u32, shape: CellId) -> Result<(), CompileFailure> {
// NB: Nothing can collect garbage between giving the object
// the shape with the property and storing its value.
- let storage = Gpr(self.allocation.node(node_id).temps[0]);
+ let storage = self.temp(node_id, 0);
let cell = self.cell_address_of(node_id, storage, 2);
let offsets = self.runtime.offsets;
self.masm
@@ -2261,19 +2280,17 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
/// The `Enter` bytecode: empty registers and locals, constants copied
/// into the frame, and the frame marked initialized (and published).
- fn emit_initialize_frame(&mut self, node: NodeId, clobbers_floats: bool) -> Result<(), CompileFailure> {
- let temps = &self.allocation.node(node).temps;
- let (value, cursor) = (Gpr(temps[0]), Gpr(temps[1]));
- self.emit_frame_initialization(value, cursor, clobbers_floats.then_some(M::ARGUMENT_FPRS[0]))
+ fn emit_initialize_frame(&mut self, node: NodeId) -> Result<(), CompileFailure> {
+ let (value, cursor) = (self.temp(node, 0), self.temp(node, 1));
+ self.emit_frame_initialization(value, cursor, Self::lowering_fpr(0))
}
/// `EnsureFrameInitialized`: initializes the frame unless it is.
- fn emit_ensure_frame_initialized(&mut self, node: NodeId, clobbers_floats: bool) -> Result<(), CompileFailure> {
- let temps = &self.allocation.node(node).temps;
- let (value, cursor) = (Gpr(temps[0]), Gpr(temps[1]));
+ fn emit_ensure_frame_initialized(&mut self, node: NodeId) -> Result<(), CompileFailure> {
+ let (value, cursor) = (self.temp(node, 0), self.temp(node, 1));
let done = self.masm.new_label();
self.branch_if_frame_initialized(done);
- self.emit_frame_initialization(value, cursor, clobbers_floats.then_some(M::ARGUMENT_FPRS[0]))?;
+ self.emit_frame_initialization(value, cursor, Self::lowering_fpr(0))?;
self.masm.bind(done);
Ok(())
}
@@ -2299,23 +2316,18 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
/// Publishes the frame and initializes it like `Enter`, with `value` for
/// the stored values, and with a loop using `cursor` for large frames.
- /// With a `vector` register, which it clobbers, it stores two slots at
- /// a time. Clobbers the scratch register.
- fn emit_frame_initialization(
- &mut self,
- value: Gpr,
- cursor: Gpr,
- vector: Option<Fpr>,
- ) -> Result<(), CompileFailure> {
+ /// Stores two slots at a time through `vector`, which it clobbers (and
+ /// which therefore holds no values: a lowering register, or any register
+ /// in the out of line stub). Clobbers the scratch register.
+ fn emit_frame_initialization(&mut self, value: Gpr, cursor: Gpr, vector: Fpr) -> Result<(), CompileFailure> {
self.emit_publish_frame();
- // Up to this many registers and locals are emptied with one store
- // each (or per two slots through a vector register), more in a loop.
- let unrolled_slots: u32 = if vector.is_some() { 64 } else { 32 };
+ // Up to this many registers and locals are emptied with one store per two slots, more in a loop.
+ const UNROLLED_SLOTS: u32 = 64;
let layout = self.executables[0].layout;
let slots = self.runtime.offsets.execution_context_slots;
let first = crate::bytecode::RESERVED_REGISTER_COUNT;
let mut fields: Vec<call::ConstantField> = Vec::new();
- let unrolled = layout.registers_and_locals_count.saturating_sub(first) <= unrolled_slots;
+ let unrolled = layout.registers_and_locals_count.saturating_sub(first) <= UNROLLED_SLOTS;
if !unrolled {
self.masm.move_imm64(value, value::EMPTY);
let start = self.slot_address(first)?;
@@ -2336,7 +2348,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
fields.push((slots + 8 * (layout.constants_base() + index), 8, *constant));
}
fields.push((self.runtime.offsets.execution_context_frame_initialized, 1, 1));
- self.emit_constant_fields_with_vector(self.pinned.frame, value, &mut fields, vector, &[])
+ self.emit_constant_fields_with_vector(self.pinned.frame, value, &mut fields, Some(vector), &[])
}
/// Initializes the frame for slow paths, whose caller-saved general
@@ -2350,7 +2362,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
};
self.annotate(CodeAnnotation::Tail("frame initialization (shared by slow paths)"));
self.masm.bind(label);
- self.emit_frame_initialization(M::ARGUMENT_GPRS[0], M::ARGUMENT_GPRS[1], Some(M::ARGUMENT_FPRS[0]))?;
+ self.emit_frame_initialization(M::ARGUMENT_GPRS[0], M::ARGUMENT_GPRS[1], M::ARGUMENT_FPRS[0])?;
self.masm.ret();
Ok(())
}
@@ -3148,15 +3160,9 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
// published frames, and an exception they throw may be caught
// further out, where the interpreter reads the frames. (The
// slow paths of fast paths run in frames written in full.)
- return matches!(
- self.graph.node(node).op,
- Op::Generic { .. }
- | Op::CallSlowPath { .. }
- | Op::CallDirect { .. }
- | Op::CallNative { .. }
- | Op::CallForwardingArguments { .. }
- )
- .then_some(node);
+ return lowering_info::lowering_info(self.graph.node(node))
+ .may_leave_from_inlined_callee
+ .then_some(node);
}
(frame_state.executable == 0 && !frame_state.values.is_empty()).then_some(node)
}
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rs b/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rs
index 07ea72c98e8..58f46756443 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/named_storage.rs
@@ -135,6 +135,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
/// runs with `return_address_bytes` more on the stack on some targets)
/// or its callers see it.
fn growth_save_address(&self, index: u32, return_address_bytes: u32) -> Address {
+ self.note_saves_area_use();
self.local_address(self.locals.saves + 8 * index + return_address_bytes)
}
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs b/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs
index 2c55b668c8a..f5b51e02fd9 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/probes/property.rs
@@ -591,6 +591,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
/// The runtime probes of the cache probe nodes, out of line.
pub(in crate::codegen) fn emit_deferred_cache_probes(&mut self) -> Result<(), CompileFailure> {
for deferred in std::mem::take(&mut self.deferred_cache_probes) {
+ self.emitting = Some(deferred.node);
self.masm.bind(deferred.entry);
let pc = self.graph.node(deferred.node).pc;
self.emit_cache_probe(
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs
index ff7f3410d78..684fb00bed6 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path_calls.rs
@@ -9,6 +9,7 @@
//! code of nodes.
use super::Codegen;
+use super::lowering_info::lowering_info;
use crate::CompileFailure;
use crate::asm::Address;
use crate::asm::Gpr;
@@ -130,23 +131,12 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
let in_inlined_callee = node
.frame_state
.is_some_and(|frame_state| self.graph.frame_state(frame_state).parent.is_some());
- in_inlined_callee
- && matches!(
- node.op,
- Op::CallSlowPath { .. }
- | Op::CallDirect {
- inlined_frame_bytes: 0,
- ..
- }
- | Op::CallNative {
- inlined_frame_bytes: 0,
- ..
- }
- )
+ in_inlined_callee && lowering_info(node).publishes_frames
}
/// The address of word `index` of the saves area.
pub(super) fn save_address(&self, index: usize) -> Address {
+ self.note_saves_area_use();
self.local_address(self.locals.saves + 8 * index as u32)
}
@@ -169,26 +159,10 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
}
}
- /// Whether the code of `node` uses the saves area: slow paths and the
- /// runtime calls that save registers like them, calls that publish
- /// frames, and stores that may grow named property storage.
+ /// Whether the code of `node` uses the saves area (see `LoweringInfo::uses_saves_area`), or publishes frames,
+ /// which uses it too.
pub(super) fn uses_saves_area(&self, node: NodeId) -> bool {
- match self.graph.node(node).op {
- Op::CallSlowPath { .. }
- | Op::ProbePropertyCache { .. }
- | Op::ProbeHasProperty { .. }
- | Op::ProbePropertyStore { .. }
- | Op::ProbeKeyedStore { .. }
- | Op::CallArrayPush
- | Op::CallStoreHoleyElement
- | Op::OpenArrayIteration
- | Op::AllocateObject { .. }
- | Op::AllocateArray { .. }
- | Op::AllocateFunction { .. }
- | Op::AllocateEnvironment { .. } => true,
- Op::CallDirect { .. } | Op::CallNative { .. } => self.publishes_frames(node),
- _ => false,
- }
+ lowering_info(self.graph.node(node)).uses_saves_area || self.publishes_frames(node)
}
/// A `SlowPathOutput` node: output `index` of the `CallSlowPath` node
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/speculation.rs b/Libraries/LibJS/JIT/Rust/src/codegen/speculation.rs
index 0021d6998f6..7046a3a7397 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/speculation.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/speculation.rs
@@ -56,7 +56,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
pub(super) fn emit_check_identity_comparable(&mut self, node: NodeId) {
let exit = self.exit_site(node);
let ok = self.masm.new_label();
- let (scratch, temp) = (self.pinned.scratch, Gpr(self.allocation.node(node).temps[0]));
+ let (scratch, temp) = (self.pinned.scratch, self.temp(node, 0));
for input in 0..2 {
let value = self.input(node, input);
self.masm.shr64_imm(scratch, value, 48);
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/values.rs b/Libraries/LibJS/JIT/Rust/src/codegen/values.rs
index df77a6e2632..f488a193ad1 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/values.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/values.rs
@@ -16,7 +16,6 @@ use crate::asm::Gpr;
use crate::asm::Label;
use crate::asm::NegativeZero;
use crate::asm::PortableMacroAssembler;
-use crate::ir::NodeId;
use crate::ir::value;
/// How many floating point registers lowerings compute with (see
@@ -138,8 +137,4 @@ impl<M: PortableMacroAssembler> Codegen<'_, M> {
self.branch_on_tag(Condition::NotEqual, value, value::OBJECT_TAG, scratch, fail);
self.emit_unbox_cell(dst, value);
}
-
- pub(super) fn temp(&self, node: NodeId, index: usize) -> Gpr {
- Gpr(self.allocation.node(node).temps[index])
- }
}
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
index f05915d18ed..2daf28b7b48 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
@@ -115,8 +115,8 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {
Op::LoadSlot { slot } => with_inputs(&format!("LoadSlot {}", slot_name(layout, *slot))),
Op::StoreSlot { slot } => with_inputs(&format!("StoreSlot {}", slot_name(layout, *slot))),
Op::Phi => with_inputs("Phi"),
- Op::InitializeFrame { .. } => with_inputs("InitializeFrame"),
- Op::EnsureFrameInitialized { .. } => with_inputs("EnsureFrameInitialized"),
+ Op::InitializeFrame => with_inputs("InitializeFrame"),
+ Op::EnsureFrameInitialized => with_inputs("EnsureFrameInitialized"),
Op::PublishFrame => with_inputs("PublishFrame"),
Op::Suspend { continuation, kind } => {
let continuation = continuation.map_or("completed".to_string(), |pc| format!("pc {pc}"));
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/info.rs b/Libraries/LibJS/JIT/Rust/src/ir/info.rs
new file mode 100644
index 00000000000..c1eebffe5eb
--- /dev/null
+++ b/Libraries/LibJS/JIT/Rust/src/ir/info.rs
@@ -0,0 +1,649 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! What the compiler knows about each op, apart from how code generation lowers it (see
+//! `codegen::lowering_info`): its effects, how it exits, which input it refines, whether it ends a block and which
+//! inputs it takes. `Op::info()` decides all of them for every op in one exhaustive match, so that a new op cannot
+//! be added without deciding each, and the passes and the verifier read them from there.
+
+use super::BranchCondition;
+use super::ElementsKind;
+use super::Locations;
+use super::Op;
+use crate::code::ExitKind;
+use crate::code::Repr;
+use crate::snapshot::HelperResult;
+use crate::snapshot::Intrinsic;
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct NodeProperties {
+ /// May need to exit to the interpreter after it returns, resuming after
+ /// the current bytecode.
+ pub can_lazy_exit: bool,
+ /// Calls out of JIT code; every caller-saved register is clobbered.
+ pub is_call: bool,
+ /// The locations it may read and write, beyond its inputs and outputs.
+ pub reads: Locations,
+ pub writes: Locations,
+ /// May run other code (which may write any location), or invalidate
+ /// the compiled code (see `Dependency`).
+ pub runs_code: bool,
+ pub allocates: bool,
+}
+
+impl NodeProperties {
+ pub(super) const PURE: Self = Self {
+ can_lazy_exit: false,
+ is_call: false,
+ reads: Locations::NONE,
+ writes: Locations::NONE,
+ runs_code: false,
+ allocates: false,
+ };
+
+ /// Reads `reads` and has no other effect.
+ const fn reading(reads: Locations) -> Self {
+ Self { reads, ..Self::PURE }
+ }
+
+ /// Writes `writes` and has no other effect.
+ const fn writing(writes: Locations) -> Self {
+ Self { writes, ..Self::PURE }
+ }
+
+ /// Calls out of JIT code and has no other effect: it only computes its value.
+ const CALL: Self = Self {
+ is_call: true,
+ ..Self::PURE
+ };
+
+ /// Calls out of JIT code, which may allocate.
+ const ALLOCATING_CALL: Self = Self {
+ is_call: true,
+ allocates: true,
+ ..Self::PURE
+ };
+
+ /// Stores or adds a named property through a cache.
+ const STORE_PROBE: Self = Self {
+ reads: Locations::NAMED,
+ writes: Locations::NAMED,
+ allocates: true,
+ ..Self::PURE
+ };
+
+ /// Runs code of the program: a call that may do anything and exit after it returns.
+ const RUNS_ANYTHING: Self = Self {
+ can_lazy_exit: true,
+ is_call: true,
+ reads: Locations::ALL,
+ writes: Locations::ALL,
+ runs_code: true,
+ allocates: true,
+ };
+}
+
+/// The inputs an op takes, which the verifier checks every node against.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Inputs {
+ /// Exactly these, in this order.
+ Exactly(&'static [Repr]),
+ /// These, then any number of `rest`.
+ AtLeast(&'static [Repr], Repr),
+ /// The receiver and the arguments of the intrinsic's `HelperCall`.
+ HelperCall(Intrinsic),
+ /// Not checked by their representations: phis take one input per predecessor, of their own representation (which
+ /// the verifier checks with the predecessors), constants take none, and `StoreSlot` stores any value.
+ Unchecked,
+}
+
+impl Inputs {
+ const NONE: Self = Self::Exactly(&[]);
+ const TAGGED: Self = Self::Exactly(&[Repr::Tagged]);
+ const TAGGED_2: Self = Self::Exactly(&[Repr::Tagged, Repr::Tagged]);
+ const TAGGED_3: Self = Self::Exactly(&[Repr::Tagged, Repr::Tagged, Repr::Tagged]);
+ const INT32: Self = Self::Exactly(&[Repr::Int32]);
+ const INT32_2: Self = Self::Exactly(&[Repr::Int32, Repr::Int32]);
+ const FLOAT64: Self = Self::Exactly(&[Repr::Float64]);
+ const FLOAT64_2: Self = Self::Exactly(&[Repr::Float64, Repr::Float64]);
+ const BOOL: Self = Self::Exactly(&[Repr::Bool]);
+ const POINTER: Self = Self::Exactly(&[Repr::Pointer]);
+ const POINTER_2: Self = Self::Exactly(&[Repr::Pointer, Repr::Pointer]);
+ const POINTER_INT32: Self = Self::Exactly(&[Repr::Pointer, Repr::Int32]);
+ /// An object and its `CellAddress`.
+ const OBJECT: Self = Self::Exactly(&[Repr::Tagged, Repr::Pointer]);
+ /// An object, a value and the object's `CellAddress`.
+ const OBJECT_VALUE: Self = Self::Exactly(&[Repr::Tagged, Repr::Tagged, Repr::Pointer]);
+ /// Any number of tagged values.
+ const TAGGED_ANY: Self = Self::AtLeast(&[], Repr::Tagged);
+
+ /// The representations of `count` inputs, if they are of this signature, or `None` if `count` is wrong. A
+ /// `HelperCall` of an intrinsic without one, and `Unchecked`, accept anything.
+ pub fn reprs(self, count: usize) -> Result<Option<Vec<Repr>>, usize> {
+ match self {
+ Inputs::Exactly(reprs) if reprs.len() == count => Ok(Some(reprs.to_vec())),
+ Inputs::Exactly(reprs) => Err(reprs.len()),
+ Inputs::AtLeast(first, rest) if count >= first.len() => Ok(Some(
+ first
+ .iter()
+ .copied()
+ .chain(std::iter::repeat_n(rest, count - first.len()))
+ .collect(),
+ )),
+ Inputs::AtLeast(first, _) => Err(first.len()),
+ Inputs::HelperCall(intrinsic) => {
+ let Some(call) = intrinsic.helper_call() else {
+ return Ok(None);
+ };
+ let reprs = std::iter::once(call.receiver)
+ .chain(call.arguments.iter().copied())
+ .map(|operand| operand.repr())
+ .collect::<Vec<_>>();
+ if reprs.len() == count {
+ Ok(Some(reprs))
+ } else {
+ Err(reprs.len())
+ }
+ }
+ Inputs::Unchecked => Ok(None),
+ }
+ }
+}
+
+/// What the compiler knows about an op (see `Op::info()`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct OpInfo {
+ pub properties: NodeProperties,
+ /// Why the node exits to the interpreter, if it can exit eagerly: before its side effects, resuming at the
+ /// current bytecode.
+ pub exit_kind: Option<ExitKind>,
+ /// For checks and refinements, whose value is an input known to pass them: which input that is (see
+ /// "Refinements" in `Op`).
+ pub refined_input: Option<usize>,
+ /// Whether it ends its block (see `Op::successors()`).
+ pub is_control: bool,
+ /// Whether its value is never the empty value (see `Graph::is_known_non_empty()`, which decides constants, slots
+ /// and phis itself). False is always safe.
+ pub never_empty: bool,
+ pub inputs: Inputs,
+}
+
+impl OpInfo {
+ /// An op without effects or exits, taking `inputs`.
+ const fn pure(inputs: Inputs) -> Self {
+ Self {
+ properties: NodeProperties::PURE,
+ exit_kind: None,
+ refined_input: None,
+ is_control: false,
+ never_empty: false,
+ inputs,
+ }
+ }
+
+ /// A check of input 0 that exits with `kind` where it fails, and has that input, refined, as its value.
+ const fn check(kind: ExitKind, inputs: Inputs) -> Self {
+ Self {
+ exit_kind: Some(kind),
+ refined_input: Some(0),
+ ..Self::pure(inputs)
+ }
+ }
+
+ /// A control node taking `inputs`.
+ const fn control(inputs: Inputs) -> Self {
+ Self {
+ is_control: true,
+ ..Self::pure(inputs)
+ }
+ }
+
+ const fn with_properties(self, properties: NodeProperties) -> Self {
+ Self { properties, ..self }
+ }
+
+ const fn exiting(self, kind: ExitKind) -> Self {
+ Self {
+ exit_kind: Some(kind),
+ ..self
+ }
+ }
+
+ const fn never_empty(self) -> Self {
+ Self {
+ never_empty: true,
+ ..self
+ }
+ }
+}
+
+impl Op {
+ /// What the compiler knows about the op.
+ pub fn info(&self) -> OpInfo {
+ use Inputs as I;
+ use NodeProperties as P;
+ match self {
+ Op::Constant(_) | Op::Phi => OpInfo::pure(I::Unchecked),
+ Op::LoadSlot { .. } => OpInfo::pure(I::NONE).with_properties(P::reading(Locations::FRAME)),
+ Op::StoreSlot { .. } => OpInfo::pure(I::Unchecked).with_properties(P::writing(Locations::FRAME)),
+ Op::InitializeFrame | Op::EnsureFrameInitialized | Op::PublishFrame => {
+ OpInfo::pure(I::NONE).with_properties(P::writing(Locations::FRAME))
+ }
+ // NB: It hands the frame's slots to the code that resumes it.
+ Op::Suspend { .. } => OpInfo::pure(I::NONE).with_properties(P {
+ reads: Locations::FRAME,
+ writes: Locations::FRAME,
+ ..P::PURE
+ }),
+ Op::LoadOuterEnvironment | Op::BoxCell => OpInfo::pure(I::POINTER),
+ Op::LoadEnvironmentBinding { .. } => OpInfo::pure(I::POINTER)
+ .with_properties(P::reading(Locations::BINDINGS.union(Locations::GLOBAL_BINDINGS))),
+ Op::StoreEnvironmentBinding { .. } => OpInfo::pure(I::Exactly(&[Repr::Pointer, Repr::Tagged]))
+ .with_properties(P::writing(Locations::BINDINGS.union(Locations::GLOBAL_BINDINGS))),
+ Op::AppendEnvironmentBinding => OpInfo::pure(I::POINTER)
+ .with_properties(P::writing(Locations::BINDINGS.union(Locations::GLOBAL_BINDINGS))),
+ Op::SetLexicalEnvironment => OpInfo::pure(I::TAGGED).with_properties(P {
+ reads: Locations::FRAME,
+ writes: Locations::FRAME,
+ ..P::PURE
+ }),
+ Op::LeavePrivateEnvironment => OpInfo::pure(I::NONE).with_properties(P {
+ reads: Locations::FRAME,
+ writes: Locations::FRAME,
+ ..P::PURE
+ }),
+ Op::IsCallable => OpInfo::pure(I::TAGGED).never_empty(),
+ Op::ToBoolean => OpInfo::pure(I::TAGGED).with_properties(P::CALL),
+ Op::PrimitiveToString => OpInfo::pure(I::TAGGED).with_properties(P::ALLOCATING_CALL),
+ Op::CallIntrinsic { intrinsic } => {
+ let call = intrinsic
+ .helper_call()
+ .expect("intrinsics called through a helper have one");
+ // NB: Helpers that answer with a number or a boolean make no
+ // cells.
+ OpInfo::pure(I::HelperCall(*intrinsic)).with_properties(P {
+ is_call: true,
+ allocates: matches!(call.result, HelperResult::String | HelperResult::Value),
+ reads: call.reads,
+ writes: call.writes,
+ ..P::PURE
+ })
+ }
+ Op::CallArraySplice => OpInfo::pure(I::AtLeast(&[Repr::Tagged, Repr::Int32, Repr::Int32], Repr::Tagged))
+ .with_properties(P {
+ is_call: true,
+ allocates: true,
+ reads: Locations::NAMED.union(Locations::ELEMENTS_AND_COUNTS),
+ writes: Locations::ELEMENTS_AND_COUNTS,
+ ..P::PURE
+ }),
+ Op::ToObject => OpInfo::pure(I::TAGGED_2).with_properties(P::ALLOCATING_CALL),
+ Op::ArrayCreate => {
+ OpInfo::pure(I::Exactly(&[Repr::Int32, Repr::Tagged])).with_properties(P::ALLOCATING_CALL)
+ }
+ Op::Generic { .. } => OpInfo::pure(I::NONE).with_properties(P::RUNS_ANYTHING),
+ // NB: Calls return values, never the empty value.
+ Op::CallDirect { .. } | Op::CallNative { .. } => OpInfo::pure(I::TAGGED_ANY)
+ .with_properties(P::RUNS_ANYTHING)
+ .never_empty(),
+ Op::CallNativeAccessor { part, .. } => {
+ let inputs = match part {
+ super::AccessorPart::Getter => I::TAGGED,
+ super::AccessorPart::Setter => I::TAGGED_2,
+ };
+ OpInfo::pure(inputs).with_properties(P::RUNS_ANYTHING)
+ }
+ Op::ArgumentCount => OpInfo::pure(I::NONE)
+ .with_properties(P::reading(Locations::FRAME))
+ .never_empty(),
+ Op::LoadFrameField { .. } => OpInfo::pure(I::NONE).with_properties(P::reading(Locations::FRAME)),
+ Op::LoadArgument { .. } => OpInfo::pure(I::TAGGED)
+ .with_properties(P::reading(Locations::FRAME))
+ .exiting(ExitKind::ArgumentsIndex)
+ .never_empty(),
+ Op::CallForwardingArguments { .. } => OpInfo::pure(I::NONE).with_properties(P::RUNS_ANYTHING),
+ Op::CheckInt32 => OpInfo::pure(I::TAGGED).exiting(ExitKind::NotInt32),
+ Op::CheckNumber => OpInfo::pure(I::TAGGED).exiting(ExitKind::BadType),
+ Op::BoxInt32 => OpInfo::pure(I::INT32).never_empty(),
+ Op::BoxBool => OpInfo::pure(I::BOOL).never_empty(),
+ Op::Int32Binary { op } => {
+ let info = OpInfo::pure(I::INT32_2);
+ if op.int32_can_overflow() {
+ info.exiting(ExitKind::Overflow)
+ } else {
+ info
+ }
+ }
+ Op::Int32WrappingBinary { .. } | Op::Int32Compare { .. } => OpInfo::pure(I::INT32_2),
+ Op::TaggedEquals { .. } => OpInfo::pure(I::TAGGED_2),
+ // NB: The elements kind of a typed array never changes.
+ Op::CheckElements {
+ kind: ElementsKind::TypedArray(_),
+ } => OpInfo::check(ExitKind::BadElements, I::TAGGED),
+ Op::CheckElements { .. } => {
+ OpInfo::check(ExitKind::BadElements, I::TAGGED).with_properties(P::reading(Locations::ELEMENT_COUNTS))
+ }
+ Op::CheckTypedArray => OpInfo::check(ExitKind::BadElements, I::TAGGED),
+ Op::CheckArray => OpInfo::check(ExitKind::BadType, I::TAGGED),
+ Op::CheckNonNegativeInt32 => OpInfo::check(ExitKind::Overflow, I::INT32),
+ Op::LoadTypedArrayLength | Op::LoadTypedArrayDataOffset => {
+ OpInfo::pure(I::POINTER).with_properties(P::reading(Locations::ELEMENT_COUNTS))
+ }
+ Op::TypedArrayDataAddress => OpInfo::pure(I::POINTER),
+ Op::CheckTypedArrayStorage => OpInfo::check(ExitKind::OutOfBounds, I::POINTER),
+ Op::CheckBounds => OpInfo::check(ExitKind::OutOfBounds, I::INT32_2),
+ Op::LoadElementAt { .. } => OpInfo::pure(I::POINTER_INT32).with_properties(P::reading(Locations::ELEMENTS)),
+ // NB: Stores within the bounds change no element count.
+ Op::StoreElementAt { kind } => {
+ let inputs = match kind.stored_repr() {
+ Repr::Float64 => I::Exactly(&[Repr::Pointer, Repr::Int32, Repr::Float64]),
+ Repr::Int32 => I::Exactly(&[Repr::Pointer, Repr::Int32, Repr::Int32]),
+ _ => I::Exactly(&[Repr::Pointer, Repr::Int32, Repr::Tagged]),
+ };
+ OpInfo::pure(inputs).with_properties(P::writing(Locations::ELEMENTS))
+ }
+ Op::CheckNotHole => OpInfo::check(ExitKind::OutOfBounds, I::TAGGED),
+ Op::CheckInitialized => OpInfo::check(ExitKind::Uninitialized, I::TAGGED),
+ Op::CellAddress => OpInfo::pure(I::TAGGED),
+ Op::AllocateObject { .. } => OpInfo::pure(I::NONE)
+ .with_properties(P {
+ allocates: true,
+ ..P::PURE
+ })
+ .never_empty(),
+ Op::InitializeNamed { .. } => OpInfo::pure(I::TAGGED_2).with_properties(P::writing(Locations::NAMED_SLOTS)),
+ // NB: Virtual objects are in no block, so the verifier sees no inputs of theirs.
+ Op::VirtualObject { .. } => OpInfo::pure(I::Unchecked),
+ Op::AllocateArray { .. } => OpInfo::pure(I::NONE)
+ .with_properties(P {
+ allocates: true,
+ ..P::PURE
+ })
+ .never_empty(),
+ Op::InitializeElement { .. } => OpInfo::pure(I::TAGGED_2).with_properties(P::writing(Locations::ELEMENTS)),
+ Op::AllocateFunction { .. } => OpInfo::pure(I::POINTER_2)
+ .with_properties(P {
+ allocates: true,
+ ..P::PURE
+ })
+ .never_empty(),
+ Op::AllocateEnvironment { .. } => OpInfo::pure(I::TAGGED)
+ .with_properties(P {
+ allocates: true,
+ ..P::PURE
+ })
+ .never_empty(),
+ Op::SliceArguments => OpInfo::pure(I::TAGGED)
+ .with_properties(P {
+ is_call: true,
+ reads: Locations::FRAME,
+ allocates: true,
+ ..P::PURE
+ })
+ .exiting(ExitKind::ArgumentsIndex)
+ .never_empty(),
+ Op::CheckIdentityComparable => OpInfo::check(ExitKind::BadType, I::TAGGED_2),
+ Op::CheckObject => OpInfo::check(ExitKind::NotObject, I::TAGGED),
+ Op::CheckClosure { .. } => OpInfo::check(ExitKind::BadCallTarget, I::TAGGED),
+ Op::LoadFunctionEnvironment { .. } => OpInfo::pure(I::POINTER),
+ Op::CheckValue { kind, .. } => OpInfo::check(*kind, I::TAGGED),
+ Op::EmptyToUndefined | Op::Typeof => OpInfo::pure(I::TAGGED).never_empty(),
+ Op::TypeofIs { .. } => OpInfo::pure(I::TAGGED),
+ Op::CheckShape { .. } => {
+ OpInfo::check(ExitKind::BadShape, I::OBJECT).with_properties(P::reading(Locations::SHAPES))
+ }
+ Op::CheckPrototypeChainValid { .. } => OpInfo::pure(I::NONE)
+ .with_properties(P::reading(Locations::SHAPES))
+ .exiting(ExitKind::BadShape),
+ Op::HasInPrototypeChain => OpInfo::pure(I::TAGGED_2)
+ .with_properties(P::reading(Locations::SHAPES))
+ .exiting(ExitKind::BadType),
+ // NB: Reading everything keeps loops whose code may invalidate
+ // the code from hoisting it.
+ Op::AssumeValid | Op::AssumeLegacyArgumentsUnread => OpInfo::pure(I::NONE)
+ .with_properties(P::reading(Locations::ALL))
+ .exiting(ExitKind::Invalidated),
+ Op::CheckInterrupt => OpInfo::pure(I::NONE)
+ .with_properties(P::writing(Locations::INTERRUPT))
+ .exiting(ExitKind::Interrupted),
+ Op::LoadGlobalBinding { .. } => OpInfo::pure(I::NONE)
+ .with_properties(P::reading(Locations::GLOBAL_BINDINGS))
+ .exiting(ExitKind::BadShape),
+ Op::StoreGlobalBinding { .. } => OpInfo::pure(I::TAGGED)
+ .with_properties(P {
+ reads: Locations::GLOBAL_BINDINGS,
+ writes: Locations::GLOBAL_BINDINGS,
+ ..P::PURE
+ })
+ .exiting(ExitKind::BadShape),
+ Op::CheckAccessorFunction { .. } => {
+ OpInfo::check(ExitKind::UnexpectedValue, I::OBJECT).with_properties(P::reading(Locations::NAMED_SLOTS))
+ }
+ Op::LoadAccessorFunction { .. } => OpInfo::pure(I::OBJECT)
+ .with_properties(P::reading(Locations::NAMED_SLOTS))
+ .exiting(ExitKind::BadCallTarget),
+ Op::LoadNamed { holds_data, .. } => {
+ let info = OpInfo::pure(I::OBJECT).with_properties(P::reading(Locations::NAMED_SLOTS));
+ if *holds_data {
+ info
+ } else {
+ info.exiting(ExitKind::BadShape)
+ }
+ }
+ Op::AddNamed { .. } => OpInfo::pure(I::OBJECT_VALUE).with_properties(P {
+ reads: Locations::NAMED,
+ writes: Locations::NAMED,
+ ..P::PURE
+ }),
+ // NB: Stores to a property an object has change no shape.
+ Op::StoreNamed { holds_data, .. } => {
+ let info = OpInfo::pure(I::OBJECT_VALUE).with_properties(P {
+ reads: Locations::NAMED_SLOTS,
+ writes: Locations::NAMED_SLOTS,
+ ..P::PURE
+ });
+ if *holds_data {
+ info
+ } else {
+ info.exiting(ExitKind::BadShape)
+ }
+ }
+ Op::Jump { .. } | Op::Unreachable => OpInfo::control(I::NONE),
+ Op::Branch { condition, .. } => OpInfo::control(I::Exactly(condition.input_reprs())),
+ Op::BranchTruthy { .. } | Op::Return => OpInfo::control(I::TAGGED),
+ Op::BranchOnPc { .. } => OpInfo::control(I::INT32),
+ Op::ShapeSwitch { .. } => OpInfo::control(I::OBJECT)
+ .with_properties(P::reading(Locations::SHAPES))
+ .exiting(ExitKind::BadShape),
+ Op::Exit { kind } => OpInfo::control(I::NONE).exiting(*kind),
+ Op::Refine { condition, .. } => OpInfo {
+ refined_input: Some(0),
+ ..OpInfo::pure(I::Exactly(condition.input_reprs()))
+ },
+ Op::CallSlowPath {
+ saves_registers: false,
+ opcode,
+ ..
+ } => OpInfo::pure(I::TAGGED_ANY).with_properties(
+ Op::Generic {
+ opcode: *opcode,
+ executable: 0,
+ pc: 0,
+ }
+ .properties(),
+ ),
+ // NB: The slow path saves the registers it clobbers, so the node
+ // is not a call for the register allocator.
+ Op::CallSlowPath { .. } => OpInfo::pure(I::TAGGED_ANY).with_properties(P {
+ reads: Locations::ALL,
+ writes: Locations::ALL,
+ runs_code: true,
+ allocates: true,
+ ..P::PURE
+ }),
+ Op::UnboxInt32 | Op::UnboxDouble => OpInfo::pure(I::TAGGED),
+ Op::Int32Abs | Op::Int32ToFloat64 => OpInfo::pure(I::INT32),
+ Op::Int32Min | Op::Int32Max | Op::Uint32Min | Op::Uint32ShiftRight => OpInfo::pure(I::INT32_2),
+ Op::BoolToInt32 => OpInfo::pure(I::BOOL),
+ Op::BoxFloat64 => OpInfo::pure(I::FLOAT64).never_empty(),
+ Op::Float64Unary { .. } | Op::Float64ToInt32 | Op::Float64ToUint8Clamped => OpInfo::pure(I::FLOAT64),
+ Op::Float64Binary { .. } | Op::Float64Min | Op::Float64Max | Op::Float64Compare { .. } => {
+ OpInfo::pure(I::FLOAT64_2)
+ }
+ Op::CallFloat64Function { function } => {
+ let inputs = match function.argument_count() {
+ 1 => I::FLOAT64,
+ _ => I::FLOAT64_2,
+ };
+ OpInfo::pure(inputs).with_properties(P::CALL)
+ }
+ Op::CheckFloat64Int32 => OpInfo::pure(I::FLOAT64).exiting(ExitKind::NotInt32),
+ Op::Uint32ToFloat64 => OpInfo::pure(I::INT32),
+ Op::StringAddress => OpInfo::pure(I::TAGGED),
+ // NB: Strings never change. These take the refinements of the
+ // checks they rely on as inputs.
+ Op::StringLength => OpInfo::pure(I::POINTER),
+ Op::LoadStringCodeUnit => OpInfo::pure(I::POINTER_INT32),
+ Op::SingleCharacterString => OpInfo::pure(I::INT32),
+ // NB: A cache miss and strings whose characters only the slow
+ // path reads stay that way until the slow path ran.
+ Op::StringsEqual => OpInfo::pure(I::TAGGED_2),
+ Op::ConcatenateStrings => OpInfo::pure(I::TAGGED_2).with_properties(P {
+ allocates: true,
+ ..P::PURE
+ }),
+ Op::IntegerToString => OpInfo::pure(I::INT32),
+ // NB: It reads the shapes and the indexed properties of the
+ // prototypes too.
+ Op::CheckAppendableArray => {
+ OpInfo::check(ExitKind::SlowPath, I::TAGGED).with_properties(P::reading(Locations::ALL))
+ }
+ Op::LoadElementsLength | Op::LoadElementsCapacity => {
+ OpInfo::pure(I::POINTER).with_properties(P::reading(Locations::ELEMENT_COUNTS))
+ }
+ Op::AppendElement => {
+ OpInfo::pure(I::Exactly(&[Repr::Pointer, Repr::Int32, Repr::Tagged])).with_properties(P {
+ reads: Locations::ELEMENTS_AND_COUNTS,
+ writes: Locations::ELEMENTS_AND_COUNTS,
+ ..P::PURE
+ })
+ }
+ Op::CallArrayPush => OpInfo::pure(I::TAGGED_2).with_properties(P {
+ reads: Locations::ELEMENTS_AND_COUNTS,
+ writes: Locations::ELEMENTS_AND_COUNTS,
+ allocates: true,
+ ..P::PURE
+ }),
+ Op::CallStoreHoleyElement => OpInfo::pure(I::Exactly(&[Repr::Pointer, Repr::Int32, Repr::Tagged]))
+ .with_properties(P {
+ reads: Locations::ELEMENTS_AND_COUNTS,
+ writes: Locations::ELEMENTS_AND_COUNTS,
+ allocates: true,
+ ..P::PURE
+ }),
+ // NB: The runtime watches the intrinsics anew with new watchpoint sets once the old ones fired.
+ Op::OpenArrayIteration => OpInfo::pure(I::TAGGED).with_properties(P {
+ reads: Locations::ALL,
+ allocates: true,
+ ..P::PURE
+ }),
+ Op::LoadArrayIteratorArray
+ | Op::LoadArrayIteratorIndex
+ | Op::LoadGeneratorCompletionType
+ | Op::LoadGeneratorCompletionValue => {
+ OpInfo::pure(I::POINTER).with_properties(P::reading(Locations::ITERATORS))
+ }
+ Op::StoreArrayIteratorIndex => {
+ OpInfo::pure(I::POINTER_INT32).with_properties(P::writing(Locations::ITERATORS))
+ }
+ Op::FinishArrayIterator => OpInfo::pure(I::POINTER).with_properties(P::writing(Locations::ITERATORS)),
+ // NB: The keys of a cache never change.
+ Op::LoadPropertyIteratorKeyCount => OpInfo::pure(I::TAGGED),
+ Op::LoadPropertyIteratorKey => OpInfo::pure(I::Exactly(&[Repr::Tagged, Repr::Int32])),
+ // NB: The slow path call leaves its outputs where the node reads
+ // them, so it stays right after the call (which the verifier
+ // checks). Its input, the call, ties it there.
+ Op::SlowPathOutput { .. } => OpInfo::pure(I::TAGGED),
+ Op::ProbePropertyCache { .. } => OpInfo::pure(I::TAGGED).with_properties(P::reading(Locations::NAMED)),
+ Op::ProbeKeyedCache { .. } => OpInfo::pure(I::TAGGED_2).with_properties(P::reading(Locations::NAMED)),
+ // NB: Additions may grow the object's storage.
+ Op::ProbePropertyStore { .. } => OpInfo::pure(I::TAGGED_2).with_properties(P::STORE_PROBE),
+ Op::ProbeKeyedStore { .. } => OpInfo::pure(I::TAGGED_3).with_properties(P::STORE_PROBE),
+ // NB: Global variables are properties of the global object and
+ // bindings of the global declarative environment.
+ Op::ProbeGlobalCache { .. } => OpInfo::pure(I::POINTER_2).with_properties(P::reading(Locations::ALL)),
+ Op::ProbeGlobalStore { .. } => OpInfo::pure(I::Exactly(&[Repr::Tagged, Repr::Pointer, Repr::Pointer]))
+ .with_properties(P {
+ reads: Locations::ALL,
+ writes: Locations::ALL,
+ runs_code: true,
+ ..P::PURE
+ }),
+ Op::ProbeHasProperty { .. } => OpInfo::pure(I::TAGGED_2).with_properties(P::reading(Locations::ALL)),
+ }
+ }
+
+ pub fn properties(&self) -> NodeProperties {
+ self.info().properties
+ }
+
+ /// Why this node exits to the interpreter, if it can exit eagerly.
+ pub fn exit_kind(&self) -> Option<ExitKind> {
+ self.info().exit_kind
+ }
+
+ /// Whether the node may exit to the interpreter before its side effects,
+ /// resuming at the current bytecode: whether it has an exit kind.
+ pub fn can_eager_exit(&self) -> bool {
+ self.exit_kind().is_some()
+ }
+
+ /// For checks and refinements, whose value is an input known to pass
+ /// them: which input that is (see "Refinements" in `Op`).
+ pub fn refined_input(&self) -> Option<usize> {
+ self.info().refined_input
+ }
+
+ pub fn is_control(&self) -> bool {
+ self.info().is_control
+ }
+}
+
+impl BranchCondition {
+ /// The representations of the inputs a branch on the condition (and a `Refine` of it) takes.
+ pub fn input_reprs(self) -> &'static [Repr] {
+ match self {
+ BranchCondition::Bool => &[Repr::Bool],
+ BranchCondition::Nullish
+ | BranchCondition::Undefined
+ | BranchCondition::Object
+ | BranchCondition::NonNegativeInt32
+ | BranchCondition::ElementsKind(_)
+ | BranchCondition::Int32Value
+ | BranchCondition::Int32OrBoolean
+ | BranchCondition::Double
+ | BranchCondition::String
+ | BranchCondition::Builtin(_) => &[Repr::Tagged],
+ BranchCondition::IndexInBounds | BranchCondition::Int32(_) => &[Repr::Int32, Repr::Int32],
+ BranchCondition::MagicalLength
+ | BranchCondition::Extensible
+ | BranchCondition::HoleFillableArray
+ | BranchCondition::ArrayIterator
+ | BranchCondition::GeneratorObject
+ | BranchCondition::PlainArrayPrototypeChain
+ | BranchCondition::ArrayWithRealmArrayPrototypeAndNoNamedProperties
+ | BranchCondition::HoldsValidWatchpointSet
+ | BranchCondition::ResolvedString
+ | BranchCondition::BindingMutable { .. }
+ | BranchCondition::NextBindingOfShape { .. } => &[Repr::Pointer],
+ BranchCondition::Shape(_) => &[Repr::Tagged, Repr::Pointer],
+ BranchCondition::Float64(_) => &[Repr::Float64, Repr::Float64],
+ BranchCondition::TaggedEquals { .. } | BranchCondition::PropertyIteratorCacheValid => {
+ &[Repr::Tagged, Repr::Tagged]
+ }
+ }
+ }
+}
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
index ec38bcb3d75..696bb3d58bf 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/mod.rs
@@ -17,9 +17,13 @@
mod dump;
mod effects;
+mod info;
pub mod value;
pub use effects::Locations;
+pub use info::Inputs;
+pub use info::NodeProperties;
+pub use info::OpInfo;
pub use dump::dump;
pub use dump::node_text;
@@ -29,7 +33,6 @@ use crate::code::ExitKind;
use crate::code::Repr;
use crate::code::ResumeMode;
use crate::snapshot::CellId;
-use crate::snapshot::HelperResult;
use crate::snapshot::Intrinsic;
use crate::snapshot::NativeCallTarget;
@@ -415,845 +418,874 @@ impl Comparison {
}
}
-/// What a node does.
-///
-/// Refinements: a check that exits unless its input 0 passes it (`CheckObject`,
-/// `CheckShape`, `CheckValue`, `CheckClosure`, `CheckAccessorFunction`,
-/// `CheckElements`, `CheckTypedArray`, `CheckArray`, `CheckNonNegativeInt32`,
-/// `CheckIdentityComparable`, `CheckAppendableArray`, `CheckBounds`,
-/// `CheckTypedArrayStorage`, `CheckNotHole`, `CheckInitialized`), and a
-/// `Refine` on the edge of a branch, has that input as its value, refined:
-/// known to pass. Nodes that rely on the check take the refined value as their
-/// input instead of the input itself, so that the check is a data dependency
-/// of theirs: passes move or share them exactly when they can move or share
-/// the check. Before register allocation, every use of a refined value
-/// becomes a use of the value it refines (see `edit::remove_refinements()`).
-/// `CheckInt32` refines and unboxes its input at once.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub enum Op {
- /// A NaN-boxed constant.
- Constant(u64),
- /// Reads frame slot `slot` (a flat operand index).
- LoadSlot {
- slot: u32,
- },
- /// Writes input 0 to frame slot `slot`.
- StoreSlot {
- slot: u32,
- },
- /// One input per block predecessor, in predecessor order.
- Phi,
- /// The `Enter` bytecode: fills the registers and locals with the empty
- /// value, copies the constants into the frame and marks it initialized.
- /// If `clobbers_floats`, the node it initializes the frame for clobbers
- /// the floating point registers anyway, so it stores through one of
- /// them, two slots at a time.
- InitializeFrame {
- clobbers_floats: bool,
- },
- /// Makes the frame the running execution context, where other code (the
- /// garbage collector, stack walks, runtime functions) sees it. Direct
- /// calls of compiled functions leave their frame unpublished until it
- /// is. `InitializeFrame` and `EnsureFrameInitialized` publish the frame
- /// too. See `passes::frame_initialization`.
- PublishFrame,
- /// Does what `InitializeFrame` does, unless the frame is initialized
- /// already. See `passes::frame_initialization`.
- EnsureFrameInitialized {
- clobbers_floats: bool,
- },
- /// The suspension of the `Yield`, `YieldIteratorResult` and `Await`
- /// bytecodes, right before the `Return` of the yielded or awaited value:
- /// records in the frame where its generator or async function resumes
- /// (`continuation`, or nowhere once it completes) and what the value is
- /// (`kind`). The `StoreSlot`s before it put every slot live at the
- /// continuation in frame memory, from where the runtime resumes the
- /// frame.
- Suspend {
- continuation: Option<u32>,
- kind: SuspendKind,
- },
- /// The environment the environment at the `Repr::Pointer` input 0 is in
- /// (its outer environment), as a `Repr::Pointer`. Environments keep
- /// their outer environment.
- LoadOuterEnvironment,
- /// Binding `index` of the declarative environment at the
- /// `Repr::Pointer` input 0: its value, or the empty value while it is
- /// uninitialized.
- LoadEnvironmentBinding {
- index: u32,
- },
- /// Stores input 1 into binding `index` of the declarative environment
- /// at the `Repr::Pointer` input 0.
- StoreEnvironmentBinding {
- index: u32,
- },
- /// Appends the binding the shape of the declarative environment at the
- /// `Repr::Pointer` input 0 has next to its bindings, uninitialized,
- /// where a branch on `BranchCondition::NextBindingOfShape` found room.
- AppendEnvironmentBinding,
- /// The tagged cell value of the cell at the `Repr::Pointer` input 0,
- /// which is no object: an environment, as bytecode registers hold it.
- BoxCell,
- /// The `SetLexicalEnvironment` bytecode: input 0, a cell value, becomes
- /// the frame's lexical environment. The node's value is its address, as
- /// a `Repr::Pointer` like `LoadFrameField` gives it.
- SetLexicalEnvironment,
- /// The `LeavePrivateEnvironment` bytecode.
- LeavePrivateEnvironment,
- /// The `IsCallable` bytecode: a boolean value telling whether input 0 is a function object.
- IsCallable,
- /// Truthiness of the tagged input 0 as a `Repr::Bool`, computed by the
- /// runtime's `to_boolean` helper. This is the slow path of `BranchTruthy`.
- ToBoolean,
- /// `String(value)` of the primitive input 0, through the runtime:
- /// ToString, but the descriptive string of a symbol.
- PrimitiveToString,
- /// The builtin `intrinsic` of the `this` value input 0 and the
- /// arguments in the other inputs, of the kinds and representations its
- /// `HelperCall` says, through its runtime helper.
- CallIntrinsic {
- intrinsic: Intrinsic,
- },
- /// Splices a plain packed array through the runtime, or returns the
- /// empty value without observable effects. Inputs: the tagged receiver,
- /// int32 start and delete count, and the tagged values to insert.
- CallArraySplice,
- /// ToObject of input 0, a primitive other than undefined and null, as
- /// the builtin function input 1 makes it (in its realm), through the
- /// runtime, or the empty value where that is not the running realm.
- ToObject,
- /// ArrayCreate of the length input 0, a non-negative `Repr::Int32`, as
- /// the Array constructor input 1 makes it (in its realm), through the
- /// runtime, or the empty value where that is not the running realm.
- ArrayCreate,
- /// Runs one bytecode instruction through the interpreter's slow path for
- /// its opcode. The frame is the only input: every slot the instruction
- /// reads is in frame memory, and slots it writes are read back from there.
- /// Conditional jumps produce the `Repr::Int32` offset of the next
- /// instruction to run.
- Generic {
- opcode: OpCode,
- /// The instruction's executable (an index into `Snapshot::executables`)
- /// and its offset there.
- executable: u32,
- pc: u32,
- },
- /// The `Call` instruction at `pc` of `executable`, like `Generic`, but
- /// calling its call feedback's `DirectCallTarget` directly: JIT code
- /// builds the callee's frame the way the interpreter's `Call` fast path
- /// does and enters the callee's JIT code (or the interpreter). Other
- /// callees, and calls the fast path cannot make, go through the
- /// `Generic` slow path.
- ///
- /// With `inlined_frame_bytes`, the call is in an inlined callee and runs
- /// without the frames of the inlined calls it is in: the node's value is
- /// the call's result, the callee's frame names the inlined call site for
- /// stack walks (see `SiteKind::Call`), and the call leaves room
- /// for those frames, of `inlined_frame_bytes`, below the callee's frame,
- /// where its slow paths materialize them.
- ///
- /// The node's inputs are the callee, the `this` value and the arguments,
- /// in registers (see `codegen::DIRECT_CALL_MAX_INPUTS`), or with
- /// `stores_operands`, all of the instruction's operands (callee, `this`,
- /// arguments) anywhere, which its code stores to their frame slots before
- /// it reads them from there.
- /// The node's value is the call's result. Without inputs (for operands
- /// holding an arguments object the code never created), the node reads
- /// its operands from the frame and writes the result there, like a
- /// `Generic` node.
- ///
- /// The callee it calls is its call feedback's `DirectCallTarget`, or
- /// with `target`, the graph's `direct_call_targets[target]`, a function
- /// the code holds as a constant.
- CallDirect {
- executable: u32,
- pc: u32,
- inlined_frame_bytes: u32,
- stores_operands: bool,
- target: Option<u32>,
- },
- /// The `Call` instruction at `pc` of `executable`, like `Generic`, but
- /// calling its call feedback's `NativeCallTarget` directly, in the
- /// lightweight frame the interpreter's `Call` fast path builds for raw
- /// native functions. Other callees go through the `Generic` slow path.
- /// `inlined_frame_bytes`, `stores_operands` and the inputs are like
- /// `CallDirect`'s, but always with the `this` value.
- CallNative {
- executable: u32,
- pc: u32,
- inlined_frame_bytes: u32,
- stores_operands: bool,
- },
- /// The `GetById` or `GetLength` (for the getter) or `PutById` (for the
- /// setter) at `pc` of the compiled function (never of an inlined call),
- /// whose checks established that the property is an accessor whose
- /// `part` is the raw native function `target`: calls it like
- /// `CallNative` calls its target, with input 0 as the `this` value and
- /// input 1 (for the setter) as the argument. The value is the getter's
- /// result (for the setter, its result too).
- CallNativeAccessor {
- pc: u32,
- part: AccessorPart,
- target: NativeCallTarget,
- },
- /// The running frame's passed argument count, as an int32 value.
- ArgumentCount,
- /// The raw pointer in `field` of the running frame's execution context,
- /// as a `Repr::Pointer`. Nodes take the parts of the execution context
- /// they need as inputs: in the compiled function, loaded with this once
- /// per path until an instruction may replace them (see
- /// `GraphBuilder::frame_field()`), and in inlined callees, whose
- /// execution contexts only exist as SSA values, constants.
- LoadFrameField {
- field: FrameField,
- },
- /// `arguments[i]` of the running frame's arguments object, which was
- /// never created, for the index value in input 0: the argument slot
- /// `arguments_base + i`. Exits unless the index is an int32 within the
- /// passed arguments.
- LoadArgument {
- arguments_base: u32,
- },
- /// The `Call` instruction at `pc` of `executable`, `f.apply(this_arg, arguments)`
- /// with `Function.prototype.apply` as its callee and the running frame's
- /// arguments object, which was never created, as its last argument: like
- /// a `Generic` call, but the runtime calls `f` with the frame's arguments.
- CallForwardingArguments {
- executable: u32,
- pc: u32,
- },
- /// Input 0 as a `Repr::Int32`. Exits with `ExitKind::NotInt32` unless
- /// it is an int32.
- CheckInt32,
- /// The number input 0 as a `Repr::Float64`. Exits with
- /// `ExitKind::BadType` unless it is a number.
- CheckNumber,
- /// The tagged value of the `Repr::Int32` input 0.
- BoxInt32,
- /// The tagged boolean of the `Repr::Bool` input 0.
- BoxBool,
- /// `input 0 op input 1` of two `Repr::Int32` inputs, as a `Repr::Int32`.
- /// Exits with `ExitKind::Overflow` where the result is not an int32:
- /// Add, Sub and Mul on overflow (Mul also on -0), Mod for a zero
- /// divisor and on -0, UnsignedRightShift for results above `i32::MAX`.
- /// Div is no int32 operation.
- Int32Binary {
- op: BinaryOp,
- },
- /// The low 32 bits of `input 0 op input 1` of two `Repr::Int32` inputs,
- /// as a `Repr::Int32`, for Add, Sub, Mul and UnsignedRightShift. Never
- /// exits: the truncation pass makes the int32 operations whose users only
- /// read the low 32 bits of their results these, and Mul is `Math.imul`.
- Int32WrappingBinary {
- op: BinaryOp,
- },
- /// `input 0 comparison input 1` of two `Repr::Int32` inputs, as a
- /// `Repr::Bool`. Equalities and inequalities are strict and loose alike.
- Int32Compare {
- comparison: Comparison,
- },
- /// Whether the tagged inputs 0 and 1 have the same bits (or different
- /// ones, if not `equal`), as a `Repr::Bool`. For values where that is
- /// strict equality: anything but numbers, strings and bigints.
- TaggedEquals {
- equal: bool,
- },
- /// Exits with `ExitKind::BadElements` unless input 0 is an object with
- /// elements of `kind`. For `ElementsKind::Holey`, packed ones qualify too.
- CheckElements {
- kind: ElementsKind,
- },
- /// Exits with `ExitKind::BadElements` unless input 0 is a typed array,
- /// of any kind.
- CheckTypedArray,
- /// Exits with `ExitKind::BadType` unless input 0 is an object with
- /// the magical length property of an array.
- CheckArray,
- /// The `Repr::Int32` input 0, checked to be nonnegative. Exits with
- /// `ExitKind::Overflow` for unsigned counts above i32::MAX.
- CheckNonNegativeInt32,
- /// The length of the typed array at the `Repr::Pointer` input 0, as a
- /// `Repr::Int32`, or 0 if its data is not cached (because its buffer is
- /// detached or resizable) or its length does not fit in 32 bits: how
- /// many elements `LoadElementAt` and `StoreElementAt` may access.
- LoadTypedArrayLength,
- /// The cached offset of the typed array at the `Repr::Pointer` input 0
- /// within the primitive storage cage, as a `Repr::Pointer`. It may be
- /// invalid: accesses must first check the index against
- /// `LoadTypedArrayLength`, which is zero without cached storage.
- LoadTypedArrayDataOffset,
- /// The address of the elements of a typed array whose storage offset is
- /// the `Repr::Pointer` input 0: the primitive storage cage base plus the
- /// offset masked into the cage, as a `Repr::Pointer`. Whatever the
- /// offset, accesses at a zero-extended 32-bit index scaled by at most 8
- /// from it stay within the cage or the guard region past it.
- TypedArrayDataAddress,
- /// The `Repr::Pointer` storage offset input 0, checked to be valid.
- /// Exits with `ExitKind::OutOfBounds` if it is invalid, so a captured
- /// typed array's fixed length can be used until its storage changes.
- CheckTypedArrayStorage,
- /// The `Repr::Int32` index input 0, which is known to be below the
- /// `Repr::Int32` count input 1 (as an unsigned number) from here on.
- /// Exits with `ExitKind::OutOfBounds` where it is not.
- CheckBounds,
- /// Element input 1 (a `Repr::Int32` index, which must be below the
- /// object's `LoadElementsLength` and `LoadElementsCapacity`, or its
- /// `LoadTypedArrayLength`) of the object at the `Repr::Pointer` input 0,
- /// whose elements are of `kind`, in `kind.loaded_repr()`. For typed
- /// arrays, input 0 is instead their `TypedArrayDataAddress`. A hole
- /// of holey elements is the empty value.
- LoadElementAt {
- kind: ElementsKind,
- },
- /// Stores input 2, in `kind.stored_repr()`, as the element at index
- /// input 1 (like for `LoadElementAt`) of the object at the
- /// `Repr::Pointer` input 0, whose elements are of `kind`. For typed
- /// arrays, input 0 is instead their `TypedArrayDataAddress`.
- StoreElementAt {
- kind: ElementsKind,
- },
- /// The tagged input 0, which is known to be no hole (the empty value
- /// `LoadElementAt` finds there) from here on. Exits with
- /// `ExitKind::OutOfBounds` where it is one.
- CheckNotHole,
- /// The tagged input 0, the value of a binding or local variable, which
- /// is known to be initialized (not the empty value) from here on. Exits
- /// with `ExitKind::Uninitialized` where it is not.
- CheckInitialized,
- /// The address of the cell in the tagged input 0, as a `Repr::Pointer`.
- /// Nodes accessing an object take it as an extra input, so that one
- /// decoding of the tagged value serves all of them.
- CellAddress,
- /// A new plain object of `shape` (see `ObjectAllocationInfo`), whose
- /// `property_count` named properties are all `undefined`, with room for
- /// `reserve` (at least `property_count`) properties inline, for the
- /// properties `AddNamed` nodes add to it. Allocates inline when the
- /// object fits a size class, and through the runtime otherwise. The node
- /// only allocates: nothing else happens, and nothing can see the object
- /// before it is stored somewhere.
- AllocateObject {
- shape: CellId,
- property_count: u32,
- reserve: u32,
- },
- /// Stores input 1 into named property `offset` of the object in input
- /// 0, made by an `AllocateObject` with a shape that has the property as
- /// a writable data property, and seen by nothing but the code
- /// initializing it (an object literal's own `InitObjectLiteralProperty`
- /// instructions), so its shape is still that one.
- InitializeNamed {
- offset: u32,
- },
- /// An object that escape analysis replaced by the values of its
- /// properties (the inputs, in offset order), as an exit needs it: the
- /// runtime creates it with `shape` when the exit is taken. Frame states
- /// refer to it; it is in no block and has no code. An input may be
- /// another virtual object. Every frame state refers to the object the
- /// `AllocateObject` node `allocation` made with a virtual object of its
- /// own, and `allocation` tells the runtime they are the same object.
- VirtualObject {
- shape: CellId,
- allocation: NodeId,
- },
- /// A new array of `count` packed elements, all `undefined`, of the
- /// realm of the compiled code (see `ArrayAllocationInfo`). Like
- /// `AllocateObject`, the node only allocates.
- AllocateArray {
- count: u32,
- },
- /// Stores input 1 into element `index` of the array in input 0, made by
- /// an `AllocateArray` with more elements, and seen by nothing but the
- /// code initializing it (an array literal's own instruction).
- InitializeElement {
- index: u32,
- },
- /// A new closure of the compiled function's `NewFunction` of
- /// `shared_function_data_index`, a copy of its closure template (see
- /// `FunctionAllocationInfo`) with the lexical environment (a cell
- /// pointer) in input 0 and the private environment in input 1. Like
- /// `AllocateObject`, the node only allocates.
- AllocateFunction {
- shared_function_data_index: u32,
- },
- /// A new lexical environment of the compiled function's
- /// `CreateLexicalEnvironment` with environment shape cache `shape_cache`
- /// and `capacity` bindings, from its template (see
- /// `LexicalEnvironmentTemplateSnapshot`), with the environment (a cell
- /// value) in input 0 as its parent. Like `AllocateObject`, the node only
- /// allocates.
- AllocateEnvironment {
- shape_cache: u32,
- capacity: u32,
- },
- /// `Array.prototype.slice.call(arguments, start)` with the running
- /// frame's arguments object, which was never created, and the start in
- /// input 0: an array of the passed arguments from `start` on, made by
- /// `RuntimeInfo::slice_arguments`. Exits unless the start is an int32.
- SliceArguments,
- /// Exits with `ExitKind::BadType` unless input 0 or input 1 is an
- /// object, a symbol, a boolean, undefined or null: a value strictly
- /// equal to exactly the values with the same bits.
- CheckIdentityComparable,
- /// Exits unless input 0 is an object.
- CheckObject,
- /// Exits with `ExitKind::BadCallTarget` unless input 0 is an ECMAScript
- /// function object with the `SharedFunctionInstanceData` `shared_data`:
- /// a closure of the function the code inlines.
- CheckClosure {
- shared_data: CellId,
- },
- /// The lexical environment (or with `private`, the private environment)
- /// of the ECMAScript function at the `CellAddress` input 0, which stays
- /// the same for the function's lifetime, as a `Repr::Pointer` like
- /// `LoadFrameField` gives it.
- LoadFunctionEnvironment {
- private: bool,
- },
- /// Exits with `kind` unless input 0 is the NaN-boxed value `expected`.
- CheckValue {
- expected: u64,
- kind: ExitKind,
- },
- /// Input 0, with the empty value replaced by `undefined`.
- EmptyToUndefined,
- /// `typeof` of input 0: one of the strings of `TypeofStrings`.
- Typeof,
- /// Whether `typeof` of input 0 is the string of `kind` (or not, if not
- /// `equal`), as a `Repr::Bool`.
- TypeofIs {
- kind: TypeofKind,
- equal: bool,
- },
- /// Exits unless the object in input 0 has one of `shapes`. An optional
- /// input 1 is the object's `CellAddress`.
- CheckShape {
- shapes: Vec<ShapeCheck>,
- },
- /// Exits unless the `WatchpointSet` cell `validity` is still valid.
- CheckPrototypeChainValid {
- validity: CellId,
- },
- /// Whether the `[[Prototype]]` chain of input 0 contains input 1, like
- /// the loop of OrdinaryHasInstance: false for values that are not
- /// objects, as a `Repr::Bool`. Exits with `ExitKind::BadType` unless
- /// input 1 is an object, and where an object of the chain does not have
- /// the ordinary `[[GetPrototypeOf]]`.
- HasInPrototypeChain,
- /// Exits with `ExitKind::Invalidated` if the code was invalidated
- /// because something it depends on (see `Graph::dependencies`) stopped
- /// holding. Costs nothing: it is a no-op that the runtime replaces with
- /// a jump to its exit when it invalidates the code. The code only needs
- /// one where it relies on its dependencies after other code ran, which
- /// is the only way they can stop holding.
- AssumeValid,
- /// An `AssumeValid` after an instruction whose calls run code that may
- /// read the legacy `arguments` of the frames of inlined calls the
- /// instruction is in. Where those arguments are objects the code never
- /// allocated, the runtime creates them for that code and invalidates the
- /// code, so that the frame exits here and continues with the very objects
- /// that code read. Escape analysis makes it an `AssumeValid` after calls
- /// whose frame states have such objects, and removes the others (see
- /// `Graph::legacy_arguments_guards`). Until then it is no `AssumeValid`,
- /// so that check elimination does not rely on it.
- AssumeLegacyArgumentsUnread,
- /// Exits with `ExitKind::Interrupted` if another thread interrupted the
- /// VM (`Vm::request_interrupt()`), which raised the native stack limit
- /// past the stack pointer. Every loop back edge has one, right before the
- /// instruction that jumps back, where the interpreter stops. Calls need
- /// none: the same limit sends every call and entry to the interpreter.
- CheckInterrupt,
- /// Loads binding `index` of the global declarative environment
- /// `environment`. Exits with `ExitKind::BadShape` if it is still
- /// uninitialized.
- LoadGlobalBinding {
- environment: CellId,
- index: u32,
- },
- /// Stores input 0 into the mutable binding `index` of the global
- /// declarative environment `environment`. Exits with
- /// `ExitKind::BadShape` if it is still uninitialized.
- StoreGlobalBinding {
- environment: CellId,
- index: u32,
- },
- /// Exits with `ExitKind::UnexpectedValue` unless the named property at
- /// `offset` of the object in input 0 is an accessor whose getter or
- /// setter (`part`) is the function `function`. Accessors can get other
- /// functions in place. Input 1 is the object's `CellAddress`.
- CheckAccessorFunction {
- offset: u32,
- part: AccessorPart,
- function: CellId,
- },
- /// The getter or setter (`part`) of the accessor in the named property
- /// at `offset` of the object in input 0, as an object value. Exits
- /// unless the property holds an accessor with that part. Input 1 is the
- /// object's `CellAddress`.
- LoadAccessorFunction {
- offset: u32,
- part: AccessorPart,
- },
- /// Loads the named property at `offset` of the object in input 0. Exits
- /// if the property holds an accessor, unless checks before it ensure
- /// that it `holds_data`. An optional input 1 is the object's
- /// `CellAddress`.
- LoadNamed {
- offset: u32,
- holds_data: bool,
- },
- /// Adds a property to the object in input 0 (whose `CellAddress` is
- /// input 2), made by an `AllocateObject` with room for it, which has the
- /// shape `shape` transitions from: stores input 1 into the property at
- /// `offset` (the shape's last one, of `property_count`), then gives the
- /// object `shape`. Checks before it ensure the object's old shape and
- /// that adding the property sets nothing in its prototype chain.
- AddNamed {
- offset: u32,
- shape: CellId,
- property_count: u32,
- },
- /// Stores input 1 into the named property at `offset` of the object in
- /// input 0, which already exists. Exits if the property holds an accessor,
- /// unless checks before it ensure that it `holds_data`. An optional input
- /// 2 is the object's `CellAddress`.
- StoreNamed {
- offset: u32,
- holds_data: bool,
- },
-
- // Control nodes. Each block ends with exactly one of these.
- Jump {
- target: BlockId,
- },
- /// Branches on input 0.
- Branch {
- condition: BranchCondition,
- if_true: BlockId,
- if_false: BlockId,
- },
- /// Branches on the truthiness of the tagged input 0. Booleans and int32
- /// values are tested inline; everything else continues at `fallback`.
- BranchTruthy {
- if_true: BlockId,
- if_false: BlockId,
- fallback: BlockId,
- },
- /// Continues at `if_true` if the `Repr::Int32` input 0 equals `pc`, and
- /// at `if_false` otherwise.
- BranchOnPc {
- pc: u32,
- if_true: BlockId,
- if_false: BlockId,
- },
- /// Continues at the block of the first case whose shape the object in
- /// input 0 has, or exits if there is none. An optional input 1 is the
- /// object's `CellAddress`.
- ShapeSwitch {
- cases: Vec<(ShapeCheck, BlockId)>,
- },
- /// Returns input 0 from the function, as is: the `End` bytecode, and the
- /// `Return` bytecode of a value whose empty value became `undefined`.
- Return,
- /// Unconditionally exits to the interpreter (eager exit).
- Exit {
- kind: ExitKind,
- },
- /// Control never reaches the end of this block, for example after a
- /// generic `Throw`.
- Unreachable,
-
- /// Input 0, refined: the same value, at the head of a block that only
- /// one edge reaches, the edge of a branch on `condition` of the inputs
- /// (the same as the branch's) where the condition is `holds`. Nodes that
- /// rely on the condition take the refinement as their input instead of
- /// input 0, which ties them to the branch as a data dependency: passes
- /// move or share them exactly when they can move or share the
- /// refinement, and refinements stay at the head of their block. Code
- /// generation sees none: refinements are removed after the passes.
- Refine {
- condition: BranchCondition,
- holds: bool,
- },
-
- /// Runs one bytecode instruction through the interpreter's slow path for
- /// its opcode, with the values of the operands the slow path reads as
- /// inputs, in the order of its layout (see `bytecode::slow_path_layout()`):
- /// the fields that are not outputs, then the array's elements. Its value
- /// is the instruction's first output (`SlowPathOutput` nodes right after
- /// it give the others), or for a conditional jump, the slow path's
- /// control word, which `BranchOnPc` tests.
- ///
- /// With `saves_registers`, the node is in a cold block that the code
- /// built for the instruction branches to where it does not handle the
- /// operands, with the instruction's eager frame state, and it keeps every
- /// value in its register: it saves the registers the call clobbers and
- /// restores them afterwards, so it is no call for the register
- /// allocator. In an inlined callee, its slow path runs in frames
- /// materialized from the frame state first.
+/// Defines `Op` and `Op::name()`, the name of each variant, so that names cannot drift from the variants. Everything
+/// else the compiler knows about an op is in `Op::info()` and `codegen::lowering_info()`.
+macro_rules! define_ops {
+ (
+ $(#[$attribute:meta])*
+ pub enum Op {
+ $(
+ $(#[$variant_attribute:meta])*
+ $variant:ident $(($($tuple:ty),* $(,)?))? $({
+ $($(#[$field_attribute:meta])* $field:ident: $field_type:ty),* $(,)?
+ })?
+ ),* $(,)?
+ }
+ ) => {
+ $(#[$attribute])*
+ pub enum Op {
+ $(
+ $(#[$variant_attribute])*
+ $variant $(($($tuple),*))? $({
+ $($(#[$field_attribute])* $field: $field_type),*
+ })?
+ ),*
+ }
+
+ impl Op {
+ pub fn name(&self) -> &'static str {
+ match self {
+ $(Op::$variant { .. } => stringify!($variant)),*
+ }
+ }
+ }
+ };
+}
+
+define_ops! {
+ /// What a node does.
///
- /// Otherwise it is a call, which runs the instruction in place of any
- /// code of the compiled function for it, with a frame state after the
- /// instruction like a `Generic` node's. Its outputs that live in frame
- /// memory (see `builder::is_ssa_slow_path_output()`) are stored there,
- /// and it has no value if the first one does.
- CallSlowPath {
- opcode: OpCode,
- /// The instruction's executable (an index into `Snapshot::executables`)
- /// and its offset there.
- executable: u32,
- pc: u32,
- saves_registers: bool,
- },
- // Numbers and strings.
- /// The `Repr::Int32` of the tagged input 0, which must be an int32: a
- /// branch on `BranchCondition::Int32Value` decides that first. Of a
- /// boolean (see `BranchCondition::Int32OrBoolean`), it is 0 or 1.
- UnboxInt32,
- /// The absolute value of the `Repr::Int32` input 0, which must not be
- /// `i32::MIN`, as a `Repr::Int32`.
- Int32Abs,
- /// The smaller and the larger of the `Repr::Int32` inputs 0 and 1, as a
- /// `Repr::Int32`.
- Int32Min,
- Int32Max,
- /// The smaller of the `Repr::Int32` inputs 0 and 1 as unsigned numbers,
- /// as a `Repr::Int32`.
- Uint32Min,
- /// The `Repr::Float64` of the `Repr::Int32` input 0.
- Int32ToFloat64,
- /// The `Repr::Int32` 0 or 1 of the `Repr::Bool` input 0, like ToInt32
- /// of a boolean.
- BoolToInt32,
- /// The `Repr::Float64` of the tagged input 0, which must be a double:
- /// the refinement of a branch on `BranchCondition::Double`.
- UnboxDouble,
- /// The tagged number of the `Repr::Float64` input 0, like
- /// `JS::Value(double)`: an int32 if it is one (but not -0), with NaN
- /// canonicalized.
- BoxFloat64,
- /// `op` of the `Repr::Float64` input 0, as a `Repr::Float64`.
- Float64Unary {
- op: Float64UnaryOp,
- },
- /// `input 0 op input 1` of two `Repr::Float64` inputs, as a
- /// `Repr::Float64`, for Add, Sub, Mul and Div.
- Float64Binary {
- op: BinaryOp,
- },
- /// `Math.min` and `Math.max` of the `Repr::Float64` inputs 0 and 1, as a
- /// `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.
- Float64Compare {
- comparison: Comparison,
- },
- /// ToInt32 of the `Repr::Float64` input 0, as a `Repr::Int32`: its
- /// integral part modulo 2^32, and 0 for NaN and the infinities.
- Float64ToInt32,
- /// ToUint8Clamp of the numeric `Repr::Float64` input 0, as a `Repr::Int32`.
- Float64ToUint8Clamped,
- /// The `Repr::Float64` input 0 as a `Repr::Int32`. Exits with
- /// `ExitKind::NotInt32` unless it is an int32 (and not -0): what a
- /// `CheckInt32` of its `BoxFloat64` does, without the boxing.
- CheckFloat64Int32,
- /// `input 0 >>> input 1` of two `Repr::Int32` inputs, as the
- /// `Repr::Int32` of the bits of the unsigned result.
- Uint32ShiftRight,
- /// The `Repr::Float64` of the bits of the `Repr::Int32` input 0, as an
- /// unsigned integer.
- Uint32ToFloat64,
- /// The address of the string input 0, as a `Repr::Pointer`, like
- /// `CellAddress` of objects.
- StringAddress,
- /// The length in code units of the string whose address is input 0, as
- /// a `Repr::Int32`.
- StringLength,
- /// The code unit at the `Repr::Int32` index input 1, which must be in
- /// bounds, of the string whose address is input 0 and whose characters
- /// must be readable (see `BranchCondition::ResolvedString`), as a
- /// `Repr::Int32`.
- LoadStringCodeUnit,
- /// The VM's string of the code unit input 0, a `Repr::Int32` below 128
- /// (see `RuntimeInfo::fast_paths.single_ascii_character_strings`).
- SingleCharacterString,
- /// Whether the strings 0 and 1 are equal, as a tagged boolean, or the
- /// empty value where only the slow path can tell: for strings with the
- /// same length whose characters are not in a word of their own.
- StringsEqual,
- /// The concatenation of the strings 0 and 1, or the empty value where
- /// only the slow path makes it. An empty string concatenates to the
- /// other one; a rope string is allocated inline, or by the runtime where
- /// there is no local free cell (see `RopeAllocationInfo`), but for
- /// results short enough to be short
- /// strings, which come from the VM's cache of fly strings (when both
- /// strings are short).
- ConcatenateStrings,
- /// The VM's string of the `Repr::Int32` input 0, from its caches of the
- /// strings of non-negative integers, or the empty value if they have
- /// none.
- IntegerToString,
-
- // Arrays.
- /// Exits with `ExitKind::SlowPath` unless input 0 is an array that
- /// `Array.prototype.push` appends to without any observable step: an
- /// extensible array with a writable length, no proxy target, with packed
- /// indexed storage or none yet, whose prototype chain is the realm's
- /// default one (`%Array.prototype%` and `%Object.prototype%`, without
- /// indexed properties). The node's value is input 0, refined.
- CheckAppendableArray,
- /// The number of indexed elements of the object at the `Repr::Pointer`
- /// input 0 (its array-like size), as a `Repr::Int32`.
- LoadElementsLength,
- /// How many elements the packed or holey indexed storage of the object
- /// at the `Repr::Pointer` input 0, which has such storage or none, has
- /// room for, as a `Repr::Int32`: 0 without storage, and at most
- /// `i32::MAX`.
- LoadElementsCapacity,
- /// Stores the tagged input 2 as the element of the object at the
- /// `Repr::Pointer` input 0 at the `Repr::Int32` index input 1, which is
- /// its number of elements and below their capacity, and counts the
- /// element. The node's value is the new number of elements, as a
- /// `Repr::Int32`.
- AppendElement,
- /// `Array.prototype.push` of the tagged input 1 to the array input 0, of
- /// a kind `CheckAppendableArray` accepts, through
- /// `RuntimeInfo::array_push`, which grows its elements. It saves the
- /// registers the call clobbers and restores them afterwards, so it is no
- /// call for the register allocator. The node's value is the new length.
- CallArrayPush,
- /// Stores the tagged input 2 at the `Repr::Int32` index input 1, below the
- /// length of the holey elements of the array at the `Repr::Pointer` input
- /// 0, through `RuntimeInfo::store_holey_element`, which grows the elements
- /// where they have no room for it (or makes them a dictionary, where the
- /// store is sparse), and makes them packed if it filled their last hole. A branch on `BranchCondition::HoleFillableArray`
- /// established that this runs no code. It saves the registers the call
- /// clobbers, like `CallArrayPush`.
- CallStoreHoleyElement,
-
- // For-of loops over arrays.
- /// `RuntimeInfo::open_array_iteration` of the tagged iterable input 0:
- /// the iterable, where `GetIterator` iterates it in fast array mode, or
- /// the empty value. It saves the registers the call clobbers and restores
- /// them afterwards, so it is no call for the register allocator.
- OpenArrayIteration,
- /// The `[[IteratedArrayLike]]` of the array iterator at the
- /// `Repr::Pointer` input 0, as a tagged value: the array, or `undefined`
- /// once the iterator is done.
- LoadArrayIteratorArray,
- /// The low 32 bits of the `[[ArrayLikeNextIndex]]` of the array iterator
- /// at the `Repr::Pointer` input 0, as a `Repr::Int32`. Iterators over
- /// arrays have indices below 2^32.
- LoadArrayIteratorIndex,
- /// Sets the `[[ArrayLikeNextIndex]]` of the array iterator at the
- /// `Repr::Pointer` input 0 to the non-negative `Repr::Int32` input 1.
- StoreArrayIteratorIndex,
- /// Sets the `[[IteratedArrayLike]]` of the array iterator at the
- /// `Repr::Pointer` input 0 to `undefined`, which makes it done.
- FinishArrayIterator,
- /// The type of the completion the generator object at the
- /// `Repr::Pointer` input 0 resumed with, as the `Repr::Int32` that
- /// `GetCompletionFields` writes.
- LoadGeneratorCompletionType,
- /// The value of the completion the generator object at the
- /// `Repr::Pointer` input 0 resumed with, as a tagged value.
- LoadGeneratorCompletionValue,
-
- // For-in loops.
- /// The number of keys of the property iterator cache input 0, as a
- /// `Repr::Int32` (at most `i32::MAX`).
- LoadPropertyIteratorKeyCount,
- /// The key at the `Repr::Int32` index input 1, below their number, of
- /// the property iterator cache input 0.
- LoadPropertyIteratorKey,
-
- // Slow paths.
- /// Output `index` of the `CallSlowPath` input 0, whose value is output
- /// 0: the operands its instruction writes, in the order of the slow
- /// path's layout (see `bytecode::slow_path_layout()`), operands it reads
- /// and writes included. It comes right after that node, in its block.
- SlowPathOutput {
- index: u8,
- },
-
- // Keyed access and `length`.
- /// The data property (own, or of an unchanged prototype chain), or
- /// `undefined` for a missing property, that property lookup cache
- /// `cache` of executable `executable` has for the tagged input 0, like
- /// the interpreter's `GetById` handler finds it: for objects, for their
- /// shape, and for strings, numbers and booleans, for the shape of their
- /// prototype. The empty value if the cache has none, or for other
- /// values. Probing the cache is one step: its entries change as the
- /// interpreter runs.
- ProbePropertyCache {
- executable: u32,
- cache: u32,
- },
- /// The value of the own data property (or, for a missing property,
- /// `undefined`) that the string or symbol input 1 names on the object in
- /// input 0, where keyed property lookup cache `cache` of executable
- /// `executable` or the VM's keyed lookup cache has it, or the empty
- /// value.
- ProbeKeyedCache {
- executable: u32,
- cache: u32,
- },
- /// Stores input 1 into the writable own data property of the object in
- /// input 0 (or adds it) that an entry of property lookup cache `cache`
- /// of executable `executable` has for the object's shape, like the
- /// interpreter's `PutById` handler, as a `Repr::Bool` telling whether it
- /// did. Other values than objects are not stored to.
- ProbePropertyStore {
- executable: u32,
- cache: u32,
- },
- /// Stores input 2 into the writable own data property that the string or
- /// symbol input 1 names on the object in input 0 (or adds it), where
- /// keyed property lookup cache `cache` of executable `executable` or the
- /// VM's keyed store cache has it, as a `Repr::Bool` telling whether it
- /// did.
- ProbeKeyedStore {
- executable: u32,
- cache: u32,
- },
- /// The global variable that global variable cache `cache` of the
- /// executable in input 1 is for, like the interpreter's `GetGlobal`
- /// handler finds it with the realm in input 0 (both `Repr::Pointer`
- /// frame fields): a data property of the
- /// global object of the cached shape, or an initialized binding of the
- /// global declarative environment, while the environment has the cached
- /// serial number. The empty value where the cache does not apply.
- ProbeGlobalCache {
- cache: u32,
- },
- /// Stores input 0 into the global variable that global variable cache
- /// `cache` of the executable in input 2 is for, with the realm in input
- /// 1 (both `Repr::Pointer` frame fields), like the interpreter's
- /// `SetGlobal` handler: a writable data
- /// property or an initialized mutable binding. A `Repr::Bool` telling
- /// whether it did.
- ProbeGlobalStore {
- cache: u32,
- },
- /// Whether the object in input 0 has the property that the key in input
- /// 1 names, as its own (`own`, like `Object.prototype.hasOwnProperty`)
- /// or in its prototype chain too (like `in`), as a tagged boolean, where
- /// the VM can tell without running code (from its keyed lookup cache,
- /// the elements, or the runtime's lookup of objects whose lookups run no
- /// code). The empty value otherwise, and for other values than objects.
- ProbeHasProperty {
- own: bool,
- },
+ /// Refinements: a check that exits unless its input 0 passes it (`CheckObject`,
+ /// `CheckShape`, `CheckValue`, `CheckClosure`, `CheckAccessorFunction`,
+ /// `CheckElements`, `CheckTypedArray`, `CheckArray`, `CheckNonNegativeInt32`,
+ /// `CheckIdentityComparable`, `CheckAppendableArray`, `CheckBounds`,
+ /// `CheckTypedArrayStorage`, `CheckNotHole`, `CheckInitialized`), and a
+ /// `Refine` on the edge of a branch, has that input as its value, refined:
+ /// known to pass. Nodes that rely on the check take the refined value as their
+ /// input instead of the input itself, so that the check is a data dependency
+ /// of theirs: passes move or share them exactly when they can move or share
+ /// the check. Before register allocation, every use of a refined value
+ /// becomes a use of the value it refines (see `edit::remove_refinements()`).
+ /// `CheckInt32` refines and unboxes its input at once.
+ #[derive(Debug, Clone, PartialEq, Eq)]
+ pub enum Op {
+ /// A NaN-boxed constant.
+ Constant(u64),
+ /// Reads frame slot `slot` (a flat operand index).
+ LoadSlot {
+ slot: u32,
+ },
+ /// Writes input 0 to frame slot `slot`.
+ StoreSlot {
+ slot: u32,
+ },
+ /// One input per block predecessor, in predecessor order.
+ Phi,
+ /// The `Enter` bytecode: fills the registers and locals with the empty
+ /// value, copies the constants into the frame and marks it initialized.
+ InitializeFrame,
+ /// Makes the frame the running execution context, where other code (the
+ /// garbage collector, stack walks, runtime functions) sees it. Direct
+ /// calls of compiled functions leave their frame unpublished until it
+ /// is. `InitializeFrame` and `EnsureFrameInitialized` publish the frame
+ /// too. See `passes::frame_initialization`.
+ PublishFrame,
+ /// Does what `InitializeFrame` does, unless the frame is initialized
+ /// already. See `passes::frame_initialization`.
+ EnsureFrameInitialized,
+ /// The suspension of the `Yield`, `YieldIteratorResult` and `Await`
+ /// bytecodes, right before the `Return` of the yielded or awaited value:
+ /// records in the frame where its generator or async function resumes
+ /// (`continuation`, or nowhere once it completes) and what the value is
+ /// (`kind`). The `StoreSlot`s before it put every slot live at the
+ /// continuation in frame memory, from where the runtime resumes the
+ /// frame.
+ Suspend {
+ continuation: Option<u32>,
+ kind: SuspendKind,
+ },
+ /// The environment the environment at the `Repr::Pointer` input 0 is in
+ /// (its outer environment), as a `Repr::Pointer`. Environments keep
+ /// their outer environment.
+ LoadOuterEnvironment,
+ /// Binding `index` of the declarative environment at the
+ /// `Repr::Pointer` input 0: its value, or the empty value while it is
+ /// uninitialized.
+ LoadEnvironmentBinding {
+ index: u32,
+ },
+ /// Stores input 1 into binding `index` of the declarative environment
+ /// at the `Repr::Pointer` input 0.
+ StoreEnvironmentBinding {
+ index: u32,
+ },
+ /// Appends the binding the shape of the declarative environment at the
+ /// `Repr::Pointer` input 0 has next to its bindings, uninitialized,
+ /// where a branch on `BranchCondition::NextBindingOfShape` found room.
+ AppendEnvironmentBinding,
+ /// The tagged cell value of the cell at the `Repr::Pointer` input 0,
+ /// which is no object: an environment, as bytecode registers hold it.
+ BoxCell,
+ /// The `SetLexicalEnvironment` bytecode: input 0, a cell value, becomes
+ /// the frame's lexical environment. The node's value is its address, as
+ /// a `Repr::Pointer` like `LoadFrameField` gives it.
+ SetLexicalEnvironment,
+ /// The `LeavePrivateEnvironment` bytecode.
+ LeavePrivateEnvironment,
+ /// The `IsCallable` bytecode: a boolean value telling whether input 0 is a function object.
+ IsCallable,
+ /// Truthiness of the tagged input 0 as a `Repr::Bool`, computed by the
+ /// runtime's `to_boolean` helper. This is the slow path of `BranchTruthy`.
+ ToBoolean,
+ /// `String(value)` of the primitive input 0, through the runtime:
+ /// ToString, but the descriptive string of a symbol.
+ PrimitiveToString,
+ /// The builtin `intrinsic` of the `this` value input 0 and the
+ /// arguments in the other inputs, of the kinds and representations its
+ /// `HelperCall` says, through its runtime helper.
+ CallIntrinsic {
+ intrinsic: Intrinsic,
+ },
+ /// Splices a plain packed array through the runtime, or returns the
+ /// empty value without observable effects. Inputs: the tagged receiver,
+ /// int32 start and delete count, and the tagged values to insert.
+ CallArraySplice,
+ /// ToObject of input 0, a primitive other than undefined and null, as
+ /// the builtin function input 1 makes it (in its realm), through the
+ /// runtime, or the empty value where that is not the running realm.
+ ToObject,
+ /// ArrayCreate of the length input 0, a non-negative `Repr::Int32`, as
+ /// the Array constructor input 1 makes it (in its realm), through the
+ /// runtime, or the empty value where that is not the running realm.
+ ArrayCreate,
+ /// Runs one bytecode instruction through the interpreter's slow path for
+ /// its opcode. The frame is the only input: every slot the instruction
+ /// reads is in frame memory, and slots it writes are read back from there.
+ /// Conditional jumps produce the `Repr::Int32` offset of the next
+ /// instruction to run.
+ Generic {
+ opcode: OpCode,
+ /// The instruction's executable (an index into `Snapshot::executables`)
+ /// and its offset there.
+ executable: u32,
+ pc: u32,
+ },
+ /// The `Call` instruction at `pc` of `executable`, like `Generic`, but
+ /// calling its call feedback's `DirectCallTarget` directly: JIT code
+ /// builds the callee's frame the way the interpreter's `Call` fast path
+ /// does and enters the callee's JIT code (or the interpreter). Other
+ /// callees, and calls the fast path cannot make, go through the
+ /// `Generic` slow path.
+ ///
+ /// With `inlined_frame_bytes`, the call is in an inlined callee and runs
+ /// without the frames of the inlined calls it is in: the node's value is
+ /// the call's result, the callee's frame names the inlined call site for
+ /// stack walks (see `SiteKind::Call`), and the call leaves room
+ /// for those frames, of `inlined_frame_bytes`, below the callee's frame,
+ /// where its slow paths materialize them.
+ ///
+ /// The node's inputs are the callee, the `this` value and the arguments,
+ /// in registers (see `codegen::DIRECT_CALL_MAX_INPUTS`), or with
+ /// `stores_operands`, all of the instruction's operands (callee, `this`,
+ /// arguments) anywhere, which its code stores to their frame slots before
+ /// it reads them from there.
+ /// The node's value is the call's result. Without inputs (for operands
+ /// holding an arguments object the code never created), the node reads
+ /// its operands from the frame and writes the result there, like a
+ /// `Generic` node.
+ ///
+ /// The callee it calls is its call feedback's `DirectCallTarget`, or
+ /// with `target`, the graph's `direct_call_targets[target]`, a function
+ /// the code holds as a constant.
+ CallDirect {
+ executable: u32,
+ pc: u32,
+ inlined_frame_bytes: u32,
+ stores_operands: bool,
+ target: Option<u32>,
+ },
+ /// The `Call` instruction at `pc` of `executable`, like `Generic`, but
+ /// calling its call feedback's `NativeCallTarget` directly, in the
+ /// lightweight frame the interpreter's `Call` fast path builds for raw
+ /// native functions. Other callees go through the `Generic` slow path.
+ /// `inlined_frame_bytes`, `stores_operands` and the inputs are like
+ /// `CallDirect`'s, but always with the `this` value.
+ CallNative {
+ executable: u32,
+ pc: u32,
+ inlined_frame_bytes: u32,
+ stores_operands: bool,
+ },
+ /// The `GetById` or `GetLength` (for the getter) or `PutById` (for the
+ /// setter) at `pc` of the compiled function (never of an inlined call),
+ /// whose checks established that the property is an accessor whose
+ /// `part` is the raw native function `target`: calls it like
+ /// `CallNative` calls its target, with input 0 as the `this` value and
+ /// input 1 (for the setter) as the argument. The value is the getter's
+ /// result (for the setter, its result too).
+ CallNativeAccessor {
+ pc: u32,
+ part: AccessorPart,
+ target: NativeCallTarget,
+ },
+ /// The running frame's passed argument count, as an int32 value.
+ ArgumentCount,
+ /// The raw pointer in `field` of the running frame's execution context,
+ /// as a `Repr::Pointer`. Nodes take the parts of the execution context
+ /// they need as inputs: in the compiled function, loaded with this once
+ /// per path until an instruction may replace them (see
+ /// `GraphBuilder::frame_field()`), and in inlined callees, whose
+ /// execution contexts only exist as SSA values, constants.
+ LoadFrameField {
+ field: FrameField,
+ },
+ /// `arguments[i]` of the running frame's arguments object, which was
+ /// never created, for the index value in input 0: the argument slot
+ /// `arguments_base + i`. Exits unless the index is an int32 within the
+ /// passed arguments.
+ LoadArgument {
+ arguments_base: u32,
+ },
+ /// The `Call` instruction at `pc` of `executable`, `f.apply(this_arg, arguments)`
+ /// with `Function.prototype.apply` as its callee and the running frame's
+ /// arguments object, which was never created, as its last argument: like
+ /// a `Generic` call, but the runtime calls `f` with the frame's arguments.
+ CallForwardingArguments {
+ executable: u32,
+ pc: u32,
+ },
+ /// Input 0 as a `Repr::Int32`. Exits with `ExitKind::NotInt32` unless
+ /// it is an int32.
+ CheckInt32,
+ /// The number input 0 as a `Repr::Float64`. Exits with
+ /// `ExitKind::BadType` unless it is a number.
+ CheckNumber,
+ /// The tagged value of the `Repr::Int32` input 0.
+ BoxInt32,
+ /// The tagged boolean of the `Repr::Bool` input 0.
+ BoxBool,
+ /// `input 0 op input 1` of two `Repr::Int32` inputs, as a `Repr::Int32`.
+ /// Exits with `ExitKind::Overflow` where the result is not an int32:
+ /// Add, Sub and Mul on overflow (Mul also on -0), Mod for a zero
+ /// divisor and on -0, UnsignedRightShift for results above `i32::MAX`.
+ /// Div is no int32 operation.
+ Int32Binary {
+ op: BinaryOp,
+ },
+ /// The low 32 bits of `input 0 op input 1` of two `Repr::Int32` inputs,
+ /// as a `Repr::Int32`, for Add, Sub, Mul and UnsignedRightShift. Never
+ /// exits: the truncation pass makes the int32 operations whose users only
+ /// read the low 32 bits of their results these, and Mul is `Math.imul`.
+ Int32WrappingBinary {
+ op: BinaryOp,
+ },
+ /// `input 0 comparison input 1` of two `Repr::Int32` inputs, as a
+ /// `Repr::Bool`. Equalities and inequalities are strict and loose alike.
+ Int32Compare {
+ comparison: Comparison,
+ },
+ /// Whether the tagged inputs 0 and 1 have the same bits (or different
+ /// ones, if not `equal`), as a `Repr::Bool`. For values where that is
+ /// strict equality: anything but numbers, strings and bigints.
+ TaggedEquals {
+ equal: bool,
+ },
+ /// Exits with `ExitKind::BadElements` unless input 0 is an object with
+ /// elements of `kind`. For `ElementsKind::Holey`, packed ones qualify too.
+ CheckElements {
+ kind: ElementsKind,
+ },
+ /// Exits with `ExitKind::BadElements` unless input 0 is a typed array,
+ /// of any kind.
+ CheckTypedArray,
+ /// Exits with `ExitKind::BadType` unless input 0 is an object with
+ /// the magical length property of an array.
+ CheckArray,
+ /// The `Repr::Int32` input 0, checked to be nonnegative. Exits with
+ /// `ExitKind::Overflow` for unsigned counts above i32::MAX.
+ CheckNonNegativeInt32,
+ /// The length of the typed array at the `Repr::Pointer` input 0, as a
+ /// `Repr::Int32`, or 0 if its data is not cached (because its buffer is
+ /// detached or resizable) or its length does not fit in 32 bits: how
+ /// many elements `LoadElementAt` and `StoreElementAt` may access.
+ LoadTypedArrayLength,
+ /// The cached offset of the typed array at the `Repr::Pointer` input 0
+ /// within the primitive storage cage, as a `Repr::Pointer`. It may be
+ /// invalid: accesses must first check the index against
+ /// `LoadTypedArrayLength`, which is zero without cached storage.
+ LoadTypedArrayDataOffset,
+ /// The address of the elements of a typed array whose storage offset is
+ /// the `Repr::Pointer` input 0: the primitive storage cage base plus the
+ /// offset masked into the cage, as a `Repr::Pointer`. Whatever the
+ /// offset, accesses at a zero-extended 32-bit index scaled by at most 8
+ /// from it stay within the cage or the guard region past it.
+ TypedArrayDataAddress,
+ /// The `Repr::Pointer` storage offset input 0, checked to be valid.
+ /// Exits with `ExitKind::OutOfBounds` if it is invalid, so a captured
+ /// typed array's fixed length can be used until its storage changes.
+ CheckTypedArrayStorage,
+ /// The `Repr::Int32` index input 0, which is known to be below the
+ /// `Repr::Int32` count input 1 (as an unsigned number) from here on.
+ /// Exits with `ExitKind::OutOfBounds` where it is not.
+ CheckBounds,
+ /// Element input 1 (a `Repr::Int32` index, which must be below the
+ /// object's `LoadElementsLength` and `LoadElementsCapacity`, or its
+ /// `LoadTypedArrayLength`) of the object at the `Repr::Pointer` input 0,
+ /// whose elements are of `kind`, in `kind.loaded_repr()`. For typed
+ /// arrays, input 0 is instead their `TypedArrayDataAddress`. A hole
+ /// of holey elements is the empty value.
+ LoadElementAt {
+ kind: ElementsKind,
+ },
+ /// Stores input 2, in `kind.stored_repr()`, as the element at index
+ /// input 1 (like for `LoadElementAt`) of the object at the
+ /// `Repr::Pointer` input 0, whose elements are of `kind`. For typed
+ /// arrays, input 0 is instead their `TypedArrayDataAddress`.
+ StoreElementAt {
+ kind: ElementsKind,
+ },
+ /// The tagged input 0, which is known to be no hole (the empty value
+ /// `LoadElementAt` finds there) from here on. Exits with
+ /// `ExitKind::OutOfBounds` where it is one.
+ CheckNotHole,
+ /// The tagged input 0, the value of a binding or local variable, which
+ /// is known to be initialized (not the empty value) from here on. Exits
+ /// with `ExitKind::Uninitialized` where it is not.
+ CheckInitialized,
+ /// The address of the cell in the tagged input 0, as a `Repr::Pointer`.
+ /// Nodes accessing an object take it as an extra input, so that one
+ /// decoding of the tagged value serves all of them.
+ CellAddress,
+ /// A new plain object of `shape` (see `ObjectAllocationInfo`), whose
+ /// `property_count` named properties are all `undefined`, with room for
+ /// `reserve` (at least `property_count`) properties inline, for the
+ /// properties `AddNamed` nodes add to it. Allocates inline when the
+ /// object fits a size class, and through the runtime otherwise. The node
+ /// only allocates: nothing else happens, and nothing can see the object
+ /// before it is stored somewhere.
+ AllocateObject {
+ shape: CellId,
+ property_count: u32,
+ reserve: u32,
+ },
+ /// Stores input 1 into named property `offset` of the object in input
+ /// 0, made by an `AllocateObject` with a shape that has the property as
+ /// a writable data property, and seen by nothing but the code
+ /// initializing it (an object literal's own `InitObjectLiteralProperty`
+ /// instructions), so its shape is still that one.
+ InitializeNamed {
+ offset: u32,
+ },
+ /// An object that escape analysis replaced by the values of its
+ /// properties (the inputs, in offset order), as an exit needs it: the
+ /// runtime creates it with `shape` when the exit is taken. Frame states
+ /// refer to it; it is in no block and has no code. An input may be
+ /// another virtual object. Every frame state refers to the object the
+ /// `AllocateObject` node `allocation` made with a virtual object of its
+ /// own, and `allocation` tells the runtime they are the same object.
+ VirtualObject {
+ shape: CellId,
+ allocation: NodeId,
+ },
+ /// A new array of `count` packed elements, all `undefined`, of the
+ /// realm of the compiled code (see `ArrayAllocationInfo`). Like
+ /// `AllocateObject`, the node only allocates.
+ AllocateArray {
+ count: u32,
+ },
+ /// Stores input 1 into element `index` of the array in input 0, made by
+ /// an `AllocateArray` with more elements, and seen by nothing but the
+ /// code initializing it (an array literal's own instruction).
+ InitializeElement {
+ index: u32,
+ },
+ /// A new closure of the compiled function's `NewFunction` of
+ /// `shared_function_data_index`, a copy of its closure template (see
+ /// `FunctionAllocationInfo`) with the lexical environment (a cell
+ /// pointer) in input 0 and the private environment in input 1. Like
+ /// `AllocateObject`, the node only allocates.
+ AllocateFunction {
+ shared_function_data_index: u32,
+ },
+ /// A new lexical environment of the compiled function's
+ /// `CreateLexicalEnvironment` with environment shape cache `shape_cache`
+ /// and `capacity` bindings, from its template (see
+ /// `LexicalEnvironmentTemplateSnapshot`), with the environment (a cell
+ /// value) in input 0 as its parent. Like `AllocateObject`, the node only
+ /// allocates.
+ AllocateEnvironment {
+ shape_cache: u32,
+ capacity: u32,
+ },
+ /// `Array.prototype.slice.call(arguments, start)` with the running
+ /// frame's arguments object, which was never created, and the start in
+ /// input 0: an array of the passed arguments from `start` on, made by
+ /// `RuntimeInfo::slice_arguments`. Exits unless the start is an int32.
+ SliceArguments,
+ /// Exits with `ExitKind::BadType` unless input 0 or input 1 is an
+ /// object, a symbol, a boolean, undefined or null: a value strictly
+ /// equal to exactly the values with the same bits.
+ CheckIdentityComparable,
+ /// Exits unless input 0 is an object.
+ CheckObject,
+ /// Exits with `ExitKind::BadCallTarget` unless input 0 is an ECMAScript
+ /// function object with the `SharedFunctionInstanceData` `shared_data`:
+ /// a closure of the function the code inlines.
+ CheckClosure {
+ shared_data: CellId,
+ },
+ /// The lexical environment (or with `private`, the private environment)
+ /// of the ECMAScript function at the `CellAddress` input 0, which stays
+ /// the same for the function's lifetime, as a `Repr::Pointer` like
+ /// `LoadFrameField` gives it.
+ LoadFunctionEnvironment {
+ private: bool,
+ },
+ /// Exits with `kind` unless input 0 is the NaN-boxed value `expected`.
+ CheckValue {
+ expected: u64,
+ kind: ExitKind,
+ },
+ /// Input 0, with the empty value replaced by `undefined`.
+ EmptyToUndefined,
+ /// `typeof` of input 0: one of the strings of `TypeofStrings`.
+ Typeof,
+ /// Whether `typeof` of input 0 is the string of `kind` (or not, if not
+ /// `equal`), as a `Repr::Bool`.
+ TypeofIs {
+ kind: TypeofKind,
+ equal: bool,
+ },
+ /// Exits unless the object in input 0 has one of `shapes`. An optional
+ /// input 1 is the object's `CellAddress`.
+ CheckShape {
+ shapes: Vec<ShapeCheck>,
+ },
+ /// Exits unless the `WatchpointSet` cell `validity` is still valid.
+ CheckPrototypeChainValid {
+ validity: CellId,
+ },
+ /// Whether the `[[Prototype]]` chain of input 0 contains input 1, like
+ /// the loop of OrdinaryHasInstance: false for values that are not
+ /// objects, as a `Repr::Bool`. Exits with `ExitKind::BadType` unless
+ /// input 1 is an object, and where an object of the chain does not have
+ /// the ordinary `[[GetPrototypeOf]]`.
+ HasInPrototypeChain,
+ /// Exits with `ExitKind::Invalidated` if the code was invalidated
+ /// because something it depends on (see `Graph::dependencies`) stopped
+ /// holding. Costs nothing: it is a no-op that the runtime replaces with
+ /// a jump to its exit when it invalidates the code. The code only needs
+ /// one where it relies on its dependencies after other code ran, which
+ /// is the only way they can stop holding.
+ AssumeValid,
+ /// An `AssumeValid` after an instruction whose calls run code that may
+ /// read the legacy `arguments` of the frames of inlined calls the
+ /// instruction is in. Where those arguments are objects the code never
+ /// allocated, the runtime creates them for that code and invalidates the
+ /// code, so that the frame exits here and continues with the very objects
+ /// that code read. Escape analysis makes it an `AssumeValid` after calls
+ /// whose frame states have such objects, and removes the others (see
+ /// `Graph::legacy_arguments_guards`). Until then it is no `AssumeValid`,
+ /// so that check elimination does not rely on it.
+ AssumeLegacyArgumentsUnread,
+ /// Exits with `ExitKind::Interrupted` if another thread interrupted the
+ /// VM (`Vm::request_interrupt()`), which raised the native stack limit
+ /// past the stack pointer. Every loop back edge has one, right before the
+ /// instruction that jumps back, where the interpreter stops. Calls need
+ /// none: the same limit sends every call and entry to the interpreter.
+ CheckInterrupt,
+ /// Loads binding `index` of the global declarative environment
+ /// `environment`. Exits with `ExitKind::BadShape` if it is still
+ /// uninitialized.
+ LoadGlobalBinding {
+ environment: CellId,
+ index: u32,
+ },
+ /// Stores input 0 into the mutable binding `index` of the global
+ /// declarative environment `environment`. Exits with
+ /// `ExitKind::BadShape` if it is still uninitialized.
+ StoreGlobalBinding {
+ environment: CellId,
+ index: u32,
+ },
+ /// Exits with `ExitKind::UnexpectedValue` unless the named property at
+ /// `offset` of the object in input 0 is an accessor whose getter or
+ /// setter (`part`) is the function `function`. Accessors can get other
+ /// functions in place. Input 1 is the object's `CellAddress`.
+ CheckAccessorFunction {
+ offset: u32,
+ part: AccessorPart,
+ function: CellId,
+ },
+ /// The getter or setter (`part`) of the accessor in the named property
+ /// at `offset` of the object in input 0, as an object value. Exits
+ /// unless the property holds an accessor with that part. Input 1 is the
+ /// object's `CellAddress`.
+ LoadAccessorFunction {
+ offset: u32,
+ part: AccessorPart,
+ },
+ /// Loads the named property at `offset` of the object in input 0. Exits
+ /// if the property holds an accessor, unless checks before it ensure
+ /// that it `holds_data`. An optional input 1 is the object's
+ /// `CellAddress`.
+ LoadNamed {
+ offset: u32,
+ holds_data: bool,
+ },
+ /// Adds a property to the object in input 0 (whose `CellAddress` is
+ /// input 2), made by an `AllocateObject` with room for it, which has the
+ /// shape `shape` transitions from: stores input 1 into the property at
+ /// `offset` (the shape's last one, of `property_count`), then gives the
+ /// object `shape`. Checks before it ensure the object's old shape and
+ /// that adding the property sets nothing in its prototype chain.
+ AddNamed {
+ offset: u32,
+ shape: CellId,
+ property_count: u32,
+ },
+ /// Stores input 1 into the named property at `offset` of the object in
+ /// input 0, which already exists. Exits if the property holds an accessor,
+ /// unless checks before it ensure that it `holds_data`. An optional input
+ /// 2 is the object's `CellAddress`.
+ StoreNamed {
+ offset: u32,
+ holds_data: bool,
+ },
+
+ // Control nodes. Each block ends with exactly one of these.
+ Jump {
+ target: BlockId,
+ },
+ /// Branches on input 0.
+ Branch {
+ condition: BranchCondition,
+ if_true: BlockId,
+ if_false: BlockId,
+ },
+ /// Branches on the truthiness of the tagged input 0. Booleans and int32
+ /// values are tested inline; everything else continues at `fallback`.
+ BranchTruthy {
+ if_true: BlockId,
+ if_false: BlockId,
+ fallback: BlockId,
+ },
+ /// Continues at `if_true` if the `Repr::Int32` input 0 equals `pc`, and
+ /// at `if_false` otherwise.
+ BranchOnPc {
+ pc: u32,
+ if_true: BlockId,
+ if_false: BlockId,
+ },
+ /// Continues at the block of the first case whose shape the object in
+ /// input 0 has, or exits if there is none. An optional input 1 is the
+ /// object's `CellAddress`.
+ ShapeSwitch {
+ cases: Vec<(ShapeCheck, BlockId)>,
+ },
+ /// Returns input 0 from the function, as is: the `End` bytecode, and the
+ /// `Return` bytecode of a value whose empty value became `undefined`.
+ Return,
+ /// Unconditionally exits to the interpreter (eager exit).
+ Exit {
+ kind: ExitKind,
+ },
+ /// Control never reaches the end of this block, for example after a
+ /// generic `Throw`.
+ Unreachable,
+
+ /// Input 0, refined: the same value, at the head of a block that only
+ /// one edge reaches, the edge of a branch on `condition` of the inputs
+ /// (the same as the branch's) where the condition is `holds`. Nodes that
+ /// rely on the condition take the refinement as their input instead of
+ /// input 0, which ties them to the branch as a data dependency: passes
+ /// move or share them exactly when they can move or share the
+ /// refinement, and refinements stay at the head of their block. Code
+ /// generation sees none: refinements are removed after the passes.
+ Refine {
+ condition: BranchCondition,
+ holds: bool,
+ },
+
+ /// Runs one bytecode instruction through the interpreter's slow path for
+ /// its opcode, with the values of the operands the slow path reads as
+ /// inputs, in the order of its layout (see `bytecode::slow_path_layout()`):
+ /// the fields that are not outputs, then the array's elements. Its value
+ /// is the instruction's first output (`SlowPathOutput` nodes right after
+ /// it give the others), or for a conditional jump, the slow path's
+ /// control word, which `BranchOnPc` tests.
+ ///
+ /// With `saves_registers`, the node is in a cold block that the code
+ /// built for the instruction branches to where it does not handle the
+ /// operands, with the instruction's eager frame state, and it keeps every
+ /// value in its register: it saves the registers the call clobbers and
+ /// restores them afterwards, so it is no call for the register
+ /// allocator. In an inlined callee, its slow path runs in frames
+ /// materialized from the frame state first.
+ ///
+ /// Otherwise it is a call, which runs the instruction in place of any
+ /// code of the compiled function for it, with a frame state after the
+ /// instruction like a `Generic` node's. Its outputs that live in frame
+ /// memory (see `builder::is_ssa_slow_path_output()`) are stored there,
+ /// and it has no value if the first one does.
+ CallSlowPath {
+ opcode: OpCode,
+ /// The instruction's executable (an index into `Snapshot::executables`)
+ /// and its offset there.
+ executable: u32,
+ pc: u32,
+ saves_registers: bool,
+ },
+ // Numbers and strings.
+ /// The `Repr::Int32` of the tagged input 0, which must be an int32: a
+ /// branch on `BranchCondition::Int32Value` decides that first. Of a
+ /// boolean (see `BranchCondition::Int32OrBoolean`), it is 0 or 1.
+ UnboxInt32,
+ /// The absolute value of the `Repr::Int32` input 0, which must not be
+ /// `i32::MIN`, as a `Repr::Int32`.
+ Int32Abs,
+ /// The smaller and the larger of the `Repr::Int32` inputs 0 and 1, as a
+ /// `Repr::Int32`.
+ Int32Min,
+ Int32Max,
+ /// The smaller of the `Repr::Int32` inputs 0 and 1 as unsigned numbers,
+ /// as a `Repr::Int32`.
+ Uint32Min,
+ /// The `Repr::Float64` of the `Repr::Int32` input 0.
+ Int32ToFloat64,
+ /// The `Repr::Int32` 0 or 1 of the `Repr::Bool` input 0, like ToInt32
+ /// of a boolean.
+ BoolToInt32,
+ /// The `Repr::Float64` of the tagged input 0, which must be a double:
+ /// the refinement of a branch on `BranchCondition::Double`.
+ UnboxDouble,
+ /// The tagged number of the `Repr::Float64` input 0, like
+ /// `JS::Value(double)`: an int32 if it is one (but not -0), with NaN
+ /// canonicalized.
+ BoxFloat64,
+ /// `op` of the `Repr::Float64` input 0, as a `Repr::Float64`.
+ Float64Unary {
+ op: Float64UnaryOp,
+ },
+ /// `input 0 op input 1` of two `Repr::Float64` inputs, as a
+ /// `Repr::Float64`, for Add, Sub, Mul and Div.
+ Float64Binary {
+ op: BinaryOp,
+ },
+ /// `Math.min` and `Math.max` of the `Repr::Float64` inputs 0 and 1, as a
+ /// `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.
+ Float64Compare {
+ comparison: Comparison,
+ },
+ /// ToInt32 of the `Repr::Float64` input 0, as a `Repr::Int32`: its
+ /// integral part modulo 2^32, and 0 for NaN and the infinities.
+ Float64ToInt32,
+ /// ToUint8Clamp of the numeric `Repr::Float64` input 0, as a `Repr::Int32`.
+ Float64ToUint8Clamped,
+ /// The `Repr::Float64` input 0 as a `Repr::Int32`. Exits with
+ /// `ExitKind::NotInt32` unless it is an int32 (and not -0): what a
+ /// `CheckInt32` of its `BoxFloat64` does, without the boxing.
+ CheckFloat64Int32,
+ /// `input 0 >>> input 1` of two `Repr::Int32` inputs, as the
+ /// `Repr::Int32` of the bits of the unsigned result.
+ Uint32ShiftRight,
+ /// The `Repr::Float64` of the bits of the `Repr::Int32` input 0, as an
+ /// unsigned integer.
+ Uint32ToFloat64,
+ /// The address of the string input 0, as a `Repr::Pointer`, like
+ /// `CellAddress` of objects.
+ StringAddress,
+ /// The length in code units of the string whose address is input 0, as
+ /// a `Repr::Int32`.
+ StringLength,
+ /// The code unit at the `Repr::Int32` index input 1, which must be in
+ /// bounds, of the string whose address is input 0 and whose characters
+ /// must be readable (see `BranchCondition::ResolvedString`), as a
+ /// `Repr::Int32`.
+ LoadStringCodeUnit,
+ /// The VM's string of the code unit input 0, a `Repr::Int32` below 128
+ /// (see `RuntimeInfo::fast_paths.single_ascii_character_strings`).
+ SingleCharacterString,
+ /// Whether the strings 0 and 1 are equal, as a tagged boolean, or the
+ /// empty value where only the slow path can tell: for strings with the
+ /// same length whose characters are not in a word of their own.
+ StringsEqual,
+ /// The concatenation of the strings 0 and 1, or the empty value where
+ /// only the slow path makes it. An empty string concatenates to the
+ /// other one; a rope string is allocated inline, or by the runtime where
+ /// there is no local free cell (see `RopeAllocationInfo`), but for
+ /// results short enough to be short
+ /// strings, which come from the VM's cache of fly strings (when both
+ /// strings are short).
+ ConcatenateStrings,
+ /// The VM's string of the `Repr::Int32` input 0, from its caches of the
+ /// strings of non-negative integers, or the empty value if they have
+ /// none.
+ IntegerToString,
+
+ // Arrays.
+ /// Exits with `ExitKind::SlowPath` unless input 0 is an array that
+ /// `Array.prototype.push` appends to without any observable step: an
+ /// extensible array with a writable length, no proxy target, with packed
+ /// indexed storage or none yet, whose prototype chain is the realm's
+ /// default one (`%Array.prototype%` and `%Object.prototype%`, without
+ /// indexed properties). The node's value is input 0, refined.
+ CheckAppendableArray,
+ /// The number of indexed elements of the object at the `Repr::Pointer`
+ /// input 0 (its array-like size), as a `Repr::Int32`.
+ LoadElementsLength,
+ /// How many elements the packed or holey indexed storage of the object
+ /// at the `Repr::Pointer` input 0, which has such storage or none, has
+ /// room for, as a `Repr::Int32`: 0 without storage, and at most
+ /// `i32::MAX`.
+ LoadElementsCapacity,
+ /// Stores the tagged input 2 as the element of the object at the
+ /// `Repr::Pointer` input 0 at the `Repr::Int32` index input 1, which is
+ /// its number of elements and below their capacity, and counts the
+ /// element. The node's value is the new number of elements, as a
+ /// `Repr::Int32`.
+ AppendElement,
+ /// `Array.prototype.push` of the tagged input 1 to the array input 0, of
+ /// a kind `CheckAppendableArray` accepts, through
+ /// `RuntimeInfo::array_push`, which grows its elements. It saves the
+ /// registers the call clobbers and restores them afterwards, so it is no
+ /// call for the register allocator. The node's value is the new length.
+ CallArrayPush,
+ /// Stores the tagged input 2 at the `Repr::Int32` index input 1, below the
+ /// length of the holey elements of the array at the `Repr::Pointer` input
+ /// 0, through `RuntimeInfo::store_holey_element`, which grows the elements
+ /// where they have no room for it (or makes them a dictionary, where the
+ /// store is sparse), and makes them packed if it filled their last hole. A branch on `BranchCondition::HoleFillableArray`
+ /// established that this runs no code. It saves the registers the call
+ /// clobbers, like `CallArrayPush`.
+ CallStoreHoleyElement,
+
+ // For-of loops over arrays.
+ /// `RuntimeInfo::open_array_iteration` of the tagged iterable input 0:
+ /// the iterable, where `GetIterator` iterates it in fast array mode, or
+ /// the empty value. It saves the registers the call clobbers and restores
+ /// them afterwards, so it is no call for the register allocator.
+ OpenArrayIteration,
+ /// The `[[IteratedArrayLike]]` of the array iterator at the
+ /// `Repr::Pointer` input 0, as a tagged value: the array, or `undefined`
+ /// once the iterator is done.
+ LoadArrayIteratorArray,
+ /// The low 32 bits of the `[[ArrayLikeNextIndex]]` of the array iterator
+ /// at the `Repr::Pointer` input 0, as a `Repr::Int32`. Iterators over
+ /// arrays have indices below 2^32.
+ LoadArrayIteratorIndex,
+ /// Sets the `[[ArrayLikeNextIndex]]` of the array iterator at the
+ /// `Repr::Pointer` input 0 to the non-negative `Repr::Int32` input 1.
+ StoreArrayIteratorIndex,
+ /// Sets the `[[IteratedArrayLike]]` of the array iterator at the
+ /// `Repr::Pointer` input 0 to `undefined`, which makes it done.
+ FinishArrayIterator,
+ /// The type of the completion the generator object at the
+ /// `Repr::Pointer` input 0 resumed with, as the `Repr::Int32` that
+ /// `GetCompletionFields` writes.
+ LoadGeneratorCompletionType,
+ /// The value of the completion the generator object at the
+ /// `Repr::Pointer` input 0 resumed with, as a tagged value.
+ LoadGeneratorCompletionValue,
+
+ // For-in loops.
+ /// The number of keys of the property iterator cache input 0, as a
+ /// `Repr::Int32` (at most `i32::MAX`).
+ LoadPropertyIteratorKeyCount,
+ /// The key at the `Repr::Int32` index input 1, below their number, of
+ /// the property iterator cache input 0.
+ LoadPropertyIteratorKey,
+
+ // Slow paths.
+ /// Output `index` of the `CallSlowPath` input 0, whose value is output
+ /// 0: the operands its instruction writes, in the order of the slow
+ /// path's layout (see `bytecode::slow_path_layout()`), operands it reads
+ /// and writes included. It comes right after that node, in its block.
+ SlowPathOutput {
+ index: u8,
+ },
+
+ // Keyed access and `length`.
+ /// The data property (own, or of an unchanged prototype chain), or
+ /// `undefined` for a missing property, that property lookup cache
+ /// `cache` of executable `executable` has for the tagged input 0, like
+ /// the interpreter's `GetById` handler finds it: for objects, for their
+ /// shape, and for strings, numbers and booleans, for the shape of their
+ /// prototype. The empty value if the cache has none, or for other
+ /// values. Probing the cache is one step: its entries change as the
+ /// interpreter runs.
+ ProbePropertyCache {
+ executable: u32,
+ cache: u32,
+ },
+ /// The value of the own data property (or, for a missing property,
+ /// `undefined`) that the string or symbol input 1 names on the object in
+ /// input 0, where keyed property lookup cache `cache` of executable
+ /// `executable` or the VM's keyed lookup cache has it, or the empty
+ /// value.
+ ProbeKeyedCache {
+ executable: u32,
+ cache: u32,
+ },
+ /// Stores input 1 into the writable own data property of the object in
+ /// input 0 (or adds it) that an entry of property lookup cache `cache`
+ /// of executable `executable` has for the object's shape, like the
+ /// interpreter's `PutById` handler, as a `Repr::Bool` telling whether it
+ /// did. Other values than objects are not stored to.
+ ProbePropertyStore {
+ executable: u32,
+ cache: u32,
+ },
+ /// Stores input 2 into the writable own data property that the string or
+ /// symbol input 1 names on the object in input 0 (or adds it), where
+ /// keyed property lookup cache `cache` of executable `executable` or the
+ /// VM's keyed store cache has it, as a `Repr::Bool` telling whether it
+ /// did.
+ ProbeKeyedStore {
+ executable: u32,
+ cache: u32,
+ },
+ /// The global variable that global variable cache `cache` of the
+ /// executable in input 1 is for, like the interpreter's `GetGlobal`
+ /// handler finds it with the realm in input 0 (both `Repr::Pointer`
+ /// frame fields): a data property of the
+ /// global object of the cached shape, or an initialized binding of the
+ /// global declarative environment, while the environment has the cached
+ /// serial number. The empty value where the cache does not apply.
+ ProbeGlobalCache {
+ cache: u32,
+ },
+ /// Stores input 0 into the global variable that global variable cache
+ /// `cache` of the executable in input 2 is for, with the realm in input
+ /// 1 (both `Repr::Pointer` frame fields), like the interpreter's
+ /// `SetGlobal` handler: a writable data
+ /// property or an initialized mutable binding. A `Repr::Bool` telling
+ /// whether it did.
+ ProbeGlobalStore {
+ cache: u32,
+ },
+ /// Whether the object in input 0 has the property that the key in input
+ /// 1 names, as its own (`own`, like `Object.prototype.hasOwnProperty`)
+ /// or in its prototype chain too (like `in`), as a tagged boolean, where
+ /// the VM can tell without running code (from its keyed lookup cache,
+ /// the elements, or the runtime's lookup of objects whose lookups run no
+ /// code). The empty value otherwise, and for other values than objects.
+ ProbeHasProperty {
+ own: bool,
+ },
+ }
}
/// What `Op::Float64Unary` computes. Floor, Ceil and Round are those of
@@ -1314,597 +1346,7 @@ impl Float64Function {
}
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub struct NodeProperties {
- /// May need to exit to the interpreter after it returns, resuming after
- /// the current bytecode.
- pub can_lazy_exit: bool,
- /// Calls out of JIT code; every caller-saved register is clobbered.
- pub is_call: bool,
- /// The locations it may read and write, beyond its inputs and outputs.
- pub reads: Locations,
- pub writes: Locations,
- /// May run other code (which may write any location), or invalidate
- /// the compiled code (see `Dependency`).
- pub runs_code: bool,
- pub allocates: bool,
-}
-
-impl NodeProperties {
- const PURE: Self = Self {
- can_lazy_exit: false,
- is_call: false,
- reads: Locations::NONE,
- writes: Locations::NONE,
- runs_code: false,
- allocates: false,
- };
-}
-
impl Op {
- pub fn properties(&self) -> NodeProperties {
- use NodeProperties as P;
- match self {
- Op::Constant(_) | Op::Refine { .. } => P::PURE,
- Op::LoadSlot { .. } => P {
- reads: Locations::FRAME,
- ..P::PURE
- },
- Op::StoreSlot { .. } => P {
- writes: Locations::FRAME,
- ..P::PURE
- },
- // NB: It hands the frame's slots to the code that resumes it.
- Op::Suspend { .. } => P {
- reads: Locations::FRAME,
- writes: Locations::FRAME,
- ..P::PURE
- },
- Op::Phi => P::PURE,
- Op::InitializeFrame { .. } | Op::EnsureFrameInitialized { .. } | Op::PublishFrame => P {
- writes: Locations::FRAME,
- ..P::PURE
- },
- Op::BoxCell | Op::LoadOuterEnvironment => P::PURE,
- Op::LoadEnvironmentBinding { .. } => P {
- reads: Locations::BINDINGS.union(Locations::GLOBAL_BINDINGS),
- ..P::PURE
- },
- Op::StoreEnvironmentBinding { .. } | Op::AppendEnvironmentBinding => P {
- writes: Locations::BINDINGS.union(Locations::GLOBAL_BINDINGS),
- ..P::PURE
- },
- Op::SetLexicalEnvironment | Op::LeavePrivateEnvironment => P {
- reads: Locations::FRAME,
- writes: Locations::FRAME,
- ..P::PURE
- },
- Op::IsCallable => P::PURE,
- Op::ToBoolean | Op::CallFloat64Function { .. } => P {
- is_call: true,
- ..P::PURE
- },
- Op::CallIntrinsic { intrinsic } => {
- let call = intrinsic
- .helper_call()
- .expect("intrinsics called through a helper have one");
- // NB: Helpers that answer with a number or a boolean make no
- // cells.
- P {
- is_call: true,
- allocates: matches!(call.result, HelperResult::String | HelperResult::Value),
- reads: call.reads,
- writes: call.writes,
- ..P::PURE
- }
- }
- Op::PrimitiveToString | Op::ToObject | Op::ArrayCreate => P {
- is_call: true,
- allocates: true,
- ..P::PURE
- },
- Op::CallArraySplice => P {
- is_call: true,
- allocates: true,
- reads: Locations::NAMED.union(Locations::ELEMENTS_AND_COUNTS),
- writes: Locations::ELEMENTS_AND_COUNTS,
- ..P::PURE
- },
- Op::CheckInt32
- | Op::CheckFloat64Int32
- | Op::CheckNumber
- | Op::CheckIdentityComparable
- | Op::CheckNonNegativeInt32 => P::PURE,
- Op::BoxInt32
- | Op::BoxBool
- | Op::Int32Binary { .. }
- | Op::Int32WrappingBinary { .. }
- | Op::Int32Compare { .. }
- | Op::TaggedEquals { .. }
- | Op::CellAddress => P::PURE,
- // NB: The elements kind of a typed array never changes.
- Op::CheckElements {
- kind: ElementsKind::TypedArray(_),
- }
- | Op::CheckTypedArray
- | Op::CheckArray => P::PURE,
- Op::CheckElements { .. } => P {
- reads: Locations::ELEMENT_COUNTS,
- ..P::PURE
- },
- Op::LoadTypedArrayLength | Op::LoadTypedArrayDataOffset => P {
- reads: Locations::ELEMENT_COUNTS,
- ..P::PURE
- },
- Op::LoadElementAt { .. } => P {
- reads: Locations::ELEMENTS,
- ..P::PURE
- },
- // NB: Stores within the bounds change no element count.
- Op::StoreElementAt { .. } => P {
- writes: Locations::ELEMENTS,
- ..P::PURE
- },
- Op::CheckBounds | Op::CheckNotHole | Op::CheckInitialized | Op::CheckTypedArrayStorage => P::PURE,
- Op::AllocateObject { .. } => P {
- allocates: true,
- ..P::PURE
- },
- Op::InitializeNamed { .. } => P {
- writes: Locations::NAMED_SLOTS,
- ..P::PURE
- },
- Op::SliceArguments => P {
- is_call: true,
- reads: Locations::FRAME,
- allocates: true,
- ..P::PURE
- },
- Op::AllocateFunction { .. } | Op::AllocateEnvironment { .. } => P {
- allocates: true,
- ..P::PURE
- },
- Op::VirtualObject { .. } => P::PURE,
- Op::AllocateArray { .. } => P {
- allocates: true,
- ..P::PURE
- },
- Op::InitializeElement { .. } => P {
- writes: Locations::ELEMENTS,
- ..P::PURE
- },
- Op::CheckObject | Op::CheckValue { .. } | Op::CheckClosure { .. } => P::PURE,
- Op::LoadFunctionEnvironment { .. } => P::PURE,
- Op::EmptyToUndefined | Op::Typeof | Op::TypeofIs { .. } => P::PURE,
- Op::CheckShape { .. } | Op::CheckPrototypeChainValid { .. } => P {
- reads: Locations::SHAPES,
- ..P::PURE
- },
- Op::CheckAccessorFunction { .. } => P {
- reads: Locations::NAMED_SLOTS,
- ..P::PURE
- },
- Op::LoadAccessorFunction { .. } => P {
- reads: Locations::NAMED_SLOTS,
- ..P::PURE
- },
- Op::LoadNamed { .. } => P {
- reads: Locations::NAMED_SLOTS,
- ..P::PURE
- },
- // NB: Reading everything keeps loops whose code may invalidate
- // the code from hoisting it.
- Op::AssumeValid | Op::AssumeLegacyArgumentsUnread => P {
- reads: Locations::ALL,
- ..P::PURE
- },
- Op::CheckInterrupt => P {
- writes: Locations::INTERRUPT,
- ..P::PURE
- },
- Op::HasInPrototypeChain => P {
- reads: Locations::SHAPES,
- ..P::PURE
- },
- Op::LoadGlobalBinding { .. } => P {
- reads: Locations::GLOBAL_BINDINGS,
- ..P::PURE
- },
- Op::StoreGlobalBinding { .. } => P {
- reads: Locations::GLOBAL_BINDINGS,
- writes: Locations::GLOBAL_BINDINGS,
- ..P::PURE
- },
- // NB: Stores to a property an object has change no shape.
- Op::StoreNamed { .. } => P {
- reads: Locations::NAMED_SLOTS,
- writes: Locations::NAMED_SLOTS,
- ..P::PURE
- },
- Op::AddNamed { .. } => P {
- reads: Locations::NAMED,
- writes: Locations::NAMED,
- ..P::PURE
- },
- Op::ArgumentCount => P {
- reads: Locations::FRAME,
- ..P::PURE
- },
- Op::LoadFrameField { .. } => P {
- reads: Locations::FRAME,
- ..P::PURE
- },
- Op::LoadArgument { .. } => P {
- reads: Locations::FRAME,
- ..P::PURE
- },
- Op::Generic { .. }
- | Op::CallDirect { .. }
- | Op::CallNative { .. }
- | Op::CallNativeAccessor { .. }
- | Op::CallForwardingArguments { .. } => P {
- can_lazy_exit: true,
- is_call: true,
- reads: Locations::ALL,
- writes: Locations::ALL,
- runs_code: true,
- allocates: true,
- },
- Op::Jump { .. }
- | Op::Branch { .. }
- | Op::BranchTruthy { .. }
- | Op::BranchOnPc { .. }
- | Op::Return
- | Op::Unreachable => P::PURE,
- Op::Exit { .. } => P { ..P::PURE },
- Op::ShapeSwitch { .. } => P {
- reads: Locations::SHAPES,
- ..P::PURE
- },
- Op::CallSlowPath {
- saves_registers: false,
- opcode,
- ..
- } => Op::Generic {
- opcode: *opcode,
- executable: 0,
- pc: 0,
- }
- .properties(),
- // NB: The slow path call leaves its outputs where the node reads
- // them, so it stays right after the call (which the verifier
- // checks). Its input, the call, ties it there.
- Op::SlowPathOutput { .. } => P::PURE,
- Op::ProbePropertyCache { .. } | Op::ProbeKeyedCache { .. } => P {
- reads: Locations::NAMED,
- ..P::PURE
- },
- Op::ProbeHasProperty { .. } => P {
- reads: Locations::ALL,
- ..P::PURE
- },
- // NB: Global variables are properties of the global object and
- // bindings of the global declarative environment.
- Op::ProbeGlobalCache { .. } => P {
- reads: Locations::ALL,
- ..P::PURE
- },
- Op::ProbeGlobalStore { .. } => P {
- reads: Locations::ALL,
- writes: Locations::ALL,
- runs_code: true,
- ..P::PURE
- },
- // NB: Additions may grow the object's storage.
- Op::ProbeKeyedStore { .. } | Op::ProbePropertyStore { .. } => P {
- reads: Locations::NAMED,
- writes: Locations::NAMED,
- allocates: true,
- ..P::PURE
- },
- // NB: The slow path saves the registers it clobbers, so the node
- // is not a call for the register allocator.
- Op::CallSlowPath { .. } => P {
- reads: Locations::ALL,
- writes: Locations::ALL,
- runs_code: true,
- allocates: true,
- ..P::PURE
- },
- Op::UnboxInt32
- | Op::UnboxDouble
- | Op::BoxFloat64
- | Op::Float64Unary { .. }
- | Op::Float64Binary { .. }
- | Op::Float64Min
- | Op::Float64Max
- | Op::Float64Compare { .. }
- | Op::Float64ToInt32
- | Op::Float64ToUint8Clamped
- | Op::Uint32ShiftRight
- | Op::Uint32ToFloat64
- | Op::Int32Abs
- | Op::Int32Min
- | Op::Int32Max
- | Op::Uint32Min
- | Op::Int32ToFloat64
- | Op::BoolToInt32
- | Op::TypedArrayDataAddress
- | Op::StringAddress => P::PURE,
- // NB: A cache miss and strings whose characters only the slow
- // path reads stay that way until the slow path ran.
- Op::StringsEqual | Op::IntegerToString => P::PURE,
- Op::ConcatenateStrings => P {
- allocates: true,
- ..P::PURE
- },
- // NB: Strings never change. These take the refinements of the
- // checks they rely on as inputs.
- Op::StringLength | Op::LoadStringCodeUnit | Op::SingleCharacterString => P::PURE,
- // NB: It reads the shapes and the indexed properties of the
- // prototypes too.
- Op::CheckAppendableArray => P {
- reads: Locations::ALL,
- ..P::PURE
- },
- Op::LoadElementsLength | Op::LoadElementsCapacity => P {
- reads: Locations::ELEMENT_COUNTS,
- ..P::PURE
- },
- Op::AppendElement => P {
- reads: Locations::ELEMENTS_AND_COUNTS,
- writes: Locations::ELEMENTS_AND_COUNTS,
- ..P::PURE
- },
- // NB: The keys of a cache never change.
- Op::LoadPropertyIteratorKeyCount | Op::LoadPropertyIteratorKey => P::PURE,
- Op::CallArrayPush | Op::CallStoreHoleyElement => P {
- reads: Locations::ELEMENTS_AND_COUNTS,
- writes: Locations::ELEMENTS_AND_COUNTS,
- allocates: true,
- ..P::PURE
- },
- // NB: The runtime watches the intrinsics anew with new watchpoint sets once the old ones fired.
- Op::OpenArrayIteration => P {
- reads: Locations::ALL,
- allocates: true,
- ..P::PURE
- },
- Op::LoadArrayIteratorArray
- | Op::LoadArrayIteratorIndex
- | Op::LoadGeneratorCompletionType
- | Op::LoadGeneratorCompletionValue => P {
- reads: Locations::ITERATORS,
- ..P::PURE
- },
- Op::StoreArrayIteratorIndex | Op::FinishArrayIterator => P {
- writes: Locations::ITERATORS,
- ..P::PURE
- },
- }
- }
-
- pub fn name(&self) -> &'static str {
- match self {
- Op::Constant(_) => "Constant",
- Op::LoadSlot { .. } => "LoadSlot",
- Op::StoreSlot { .. } => "StoreSlot",
- Op::Phi => "Phi",
- Op::InitializeFrame { .. } => "InitializeFrame",
- Op::EnsureFrameInitialized { .. } => "EnsureFrameInitialized",
- Op::Suspend { .. } => "Suspend",
- Op::PublishFrame => "PublishFrame",
- Op::BoxCell => "BoxCell",
- Op::LoadOuterEnvironment => "LoadOuterEnvironment",
- Op::LoadEnvironmentBinding { .. } => "LoadEnvironmentBinding",
- Op::StoreEnvironmentBinding { .. } => "StoreEnvironmentBinding",
- Op::AppendEnvironmentBinding => "AppendEnvironmentBinding",
- Op::SetLexicalEnvironment => "SetLexicalEnvironment",
- Op::LeavePrivateEnvironment => "LeavePrivateEnvironment",
- Op::IsCallable => "IsCallable",
- Op::ToBoolean => "ToBoolean",
- Op::PrimitiveToString => "PrimitiveToString",
- Op::CallIntrinsic { .. } => "CallIntrinsic",
- Op::CallArraySplice => "CallArraySplice",
- Op::ToObject => "ToObject",
- Op::ArrayCreate => "ArrayCreate",
- Op::Generic { .. } => "Generic",
- Op::CallDirect { .. } => "CallDirect",
- Op::CallNative { .. } => "CallNative",
- Op::CallNativeAccessor { .. } => "CallNativeAccessor",
- Op::ArgumentCount => "ArgumentCount",
- Op::LoadFrameField { .. } => "LoadFrameField",
- Op::LoadArgument { .. } => "LoadArgument",
- Op::CallForwardingArguments { .. } => "CallForwardingArguments",
- Op::CheckInt32 => "CheckInt32",
- Op::CheckFloat64Int32 => "CheckFloat64Int32",
- Op::CheckNumber => "CheckNumber",
- Op::BoxInt32 => "BoxInt32",
- Op::BoxBool => "BoxBool",
- Op::Int32Binary { .. } => "Int32Binary",
- Op::Int32WrappingBinary { .. } => "Int32WrappingBinary",
- Op::Int32Compare { .. } => "Int32Compare",
- Op::TaggedEquals { .. } => "TaggedEquals",
- Op::CheckElements { .. } => "CheckElements",
- Op::CheckTypedArray => "CheckTypedArray",
- Op::CheckArray => "CheckArray",
- Op::CheckNonNegativeInt32 => "CheckNonNegativeInt32",
- Op::LoadTypedArrayLength => "LoadTypedArrayLength",
- Op::LoadTypedArrayDataOffset => "LoadTypedArrayDataOffset",
- Op::TypedArrayDataAddress => "TypedArrayDataAddress",
- Op::CheckTypedArrayStorage => "CheckTypedArrayStorage",
- Op::CheckBounds => "CheckBounds",
- Op::LoadElementAt { .. } => "LoadElementAt",
- Op::StoreElementAt { .. } => "StoreElementAt",
- Op::CheckNotHole => "CheckNotHole",
- Op::CheckInitialized => "CheckInitialized",
- Op::CellAddress => "CellAddress",
- Op::AllocateObject { .. } => "AllocateObject",
- Op::InitializeNamed { .. } => "InitializeNamed",
- Op::AllocateArray { .. } => "AllocateArray",
- Op::VirtualObject { .. } => "VirtualObject",
- Op::AllocateFunction { .. } => "AllocateFunction",
- Op::AllocateEnvironment { .. } => "AllocateEnvironment",
- Op::SliceArguments => "SliceArguments",
- Op::InitializeElement { .. } => "InitializeElement",
- Op::CheckIdentityComparable => "CheckIdentityComparable",
- Op::CheckObject => "CheckObject",
- Op::CheckValue { .. } => "CheckValue",
- Op::CheckClosure { .. } => "CheckClosure",
- Op::LoadFunctionEnvironment { .. } => "LoadFunctionEnvironment",
- Op::EmptyToUndefined => "EmptyToUndefined",
- Op::Typeof => "Typeof",
- Op::TypeofIs { .. } => "TypeofIs",
- Op::CheckShape { .. } => "CheckShape",
- Op::CheckPrototypeChainValid { .. } => "CheckPrototypeChainValid",
- Op::AssumeValid => "AssumeValid",
- Op::CheckInterrupt => "CheckInterrupt",
- Op::AssumeLegacyArgumentsUnread => "AssumeLegacyArgumentsUnread",
- Op::HasInPrototypeChain => "HasInPrototypeChain",
- Op::LoadGlobalBinding { .. } => "LoadGlobalBinding",
- Op::StoreGlobalBinding { .. } => "StoreGlobalBinding",
- Op::CheckAccessorFunction { .. } => "CheckAccessorFunction",
- Op::LoadAccessorFunction { .. } => "LoadAccessorFunction",
- Op::LoadNamed { .. } => "LoadNamed",
- Op::StoreNamed { .. } => "StoreNamed",
- Op::AddNamed { .. } => "AddNamed",
- Op::ShapeSwitch { .. } => "ShapeSwitch",
- Op::Jump { .. } => "Jump",
- Op::Branch { .. } => "Branch",
- Op::BranchTruthy { .. } => "BranchTruthy",
- Op::BranchOnPc { .. } => "BranchOnPc",
- Op::Return => "Return",
- Op::Exit { .. } => "Exit",
- Op::Unreachable => "Unreachable",
- Op::Refine { .. } => "Refine",
- Op::CallSlowPath { .. } => "CallSlowPath",
- Op::UnboxInt32 => "UnboxInt32",
- Op::Int32Abs => "Int32Abs",
- Op::Int32Min => "Int32Min",
- Op::Uint32Min => "Uint32Min",
- Op::Int32Max => "Int32Max",
- Op::Int32ToFloat64 => "Int32ToFloat64",
- Op::BoolToInt32 => "BoolToInt32",
- Op::UnboxDouble => "UnboxDouble",
- Op::BoxFloat64 => "BoxFloat64",
- Op::Float64Unary { .. } => "Float64Unary",
- Op::Float64Binary { .. } => "Float64Binary",
- Op::Float64Min => "Float64Min",
- Op::Float64Max => "Float64Max",
- Op::CallFloat64Function { .. } => "CallFloat64Function",
- Op::Float64Compare { .. } => "Float64Compare",
- Op::Float64ToInt32 => "Float64ToInt32",
- Op::Float64ToUint8Clamped => "Float64ToUint8Clamped",
- Op::Uint32ShiftRight => "Uint32ShiftRight",
- Op::Uint32ToFloat64 => "Uint32ToFloat64",
- Op::StringsEqual => "StringsEqual",
- Op::ConcatenateStrings => "ConcatenateStrings",
- Op::IntegerToString => "IntegerToString",
- Op::StringAddress => "StringAddress",
- Op::StringLength => "StringLength",
- Op::LoadStringCodeUnit => "LoadStringCodeUnit",
- Op::SingleCharacterString => "SingleCharacterString",
- Op::CheckAppendableArray => "CheckAppendableArray",
- Op::LoadElementsLength => "LoadElementsLength",
- Op::LoadElementsCapacity => "LoadElementsCapacity",
- Op::AppendElement => "AppendElement",
- Op::CallArrayPush => "CallArrayPush",
- Op::CallStoreHoleyElement => "CallStoreHoleyElement",
- Op::OpenArrayIteration => "OpenArrayIteration",
- Op::LoadArrayIteratorArray => "LoadArrayIteratorArray",
- Op::LoadArrayIteratorIndex => "LoadArrayIteratorIndex",
- Op::LoadGeneratorCompletionType => "LoadGeneratorCompletionType",
- Op::LoadGeneratorCompletionValue => "LoadGeneratorCompletionValue",
- Op::StoreArrayIteratorIndex => "StoreArrayIteratorIndex",
- Op::FinishArrayIterator => "FinishArrayIterator",
- Op::SlowPathOutput { .. } => "SlowPathOutput",
- Op::LoadPropertyIteratorKeyCount => "LoadPropertyIteratorKeyCount",
- Op::LoadPropertyIteratorKey => "LoadPropertyIteratorKey",
- Op::ProbePropertyCache { .. } => "ProbePropertyCache",
- Op::ProbeKeyedCache { .. } => "ProbeKeyedCache",
- Op::ProbeKeyedStore { .. } => "ProbeKeyedStore",
- Op::ProbePropertyStore { .. } => "ProbePropertyStore",
- Op::ProbeGlobalCache { .. } => "ProbeGlobalCache",
- Op::ProbeGlobalStore { .. } => "ProbeGlobalStore",
- Op::ProbeHasProperty { .. } => "ProbeHasProperty",
- }
- }
-
- /// For checks and refinements, whose value is an input known to pass
- /// them: which input that is (see "Refinements" in `Op`).
- pub fn refined_input(&self) -> Option<usize> {
- match self {
- Op::Refine { .. }
- | Op::CheckObject
- | Op::CheckShape { .. }
- | Op::CheckValue { .. }
- | Op::CheckClosure { .. }
- | Op::CheckAccessorFunction { .. }
- | Op::CheckElements { .. }
- | Op::CheckTypedArray
- | Op::CheckArray
- | Op::CheckNonNegativeInt32
- | Op::CheckIdentityComparable
- | Op::CheckAppendableArray
- | Op::CheckBounds
- | Op::CheckTypedArrayStorage
- | Op::CheckNotHole
- | Op::CheckInitialized => Some(0),
- _ => None,
- }
- }
-
- pub fn is_control(&self) -> bool {
- matches!(
- self,
- Op::Jump { .. }
- | Op::Branch { .. }
- | Op::BranchTruthy { .. }
- | Op::BranchOnPc { .. }
- | Op::ShapeSwitch { .. }
- | Op::Return
- | Op::Exit { .. }
- | Op::Unreachable
- )
- }
-
- /// Why this node exits to the interpreter, if it can exit eagerly.
- /// Whether the node may exit to the interpreter before its side effects,
- /// resuming at the current bytecode: whether it has an exit kind.
- pub fn can_eager_exit(&self) -> bool {
- self.exit_kind().is_some()
- }
-
- pub fn exit_kind(&self) -> Option<ExitKind> {
- match self {
- Op::Exit { kind } => Some(*kind),
- Op::CheckObject => Some(ExitKind::NotObject),
- Op::CheckElements { .. } | Op::CheckTypedArray => Some(ExitKind::BadElements),
- Op::CheckBounds | Op::CheckNotHole | Op::CheckTypedArrayStorage => Some(ExitKind::OutOfBounds),
- Op::CheckInitialized => Some(ExitKind::Uninitialized),
- Op::CheckInt32 | Op::CheckFloat64Int32 => Some(ExitKind::NotInt32),
- Op::CheckArray => Some(ExitKind::BadType),
- Op::CheckNonNegativeInt32 => Some(ExitKind::Overflow),
- Op::CheckNumber | Op::CheckIdentityComparable | Op::HasInPrototypeChain => Some(ExitKind::BadType),
- Op::AssumeValid | Op::AssumeLegacyArgumentsUnread => Some(ExitKind::Invalidated),
- Op::CheckInterrupt => Some(ExitKind::Interrupted),
- Op::Int32Binary { op } if op.int32_can_overflow() => Some(ExitKind::Overflow),
- Op::CheckValue { kind, .. } => Some(*kind),
- Op::LoadArgument { .. } | Op::SliceArguments => Some(ExitKind::ArgumentsIndex),
- Op::CheckAppendableArray => Some(ExitKind::SlowPath),
- Op::LoadAccessorFunction { .. } | Op::CheckClosure { .. } => Some(ExitKind::BadCallTarget),
- Op::CheckAccessorFunction { .. } => Some(ExitKind::UnexpectedValue),
- Op::CheckShape { .. }
- | Op::CheckPrototypeChainValid { .. }
- | Op::LoadGlobalBinding { .. }
- | Op::StoreGlobalBinding { .. }
- | Op::LoadNamed { holds_data: false, .. }
- | Op::StoreNamed { holds_data: false, .. }
- | Op::ShapeSwitch { .. } => Some(ExitKind::BadShape),
- _ => None,
- }
- }
-
/// The blocks a control node can continue at.
pub fn successors(&self) -> Successors {
let inline = |blocks: &[BlockId]| {
@@ -2175,22 +1617,8 @@ impl Graph {
match &data.op {
Op::Constant(bits) if *bits != value::EMPTY => {}
Op::LoadSlot { slot } if arguments.contains(&crate::bytecode::Operand::from_raw(*slot).raw()) => {}
- // NB: Calls return values, never the empty value.
- Op::CallDirect { .. } | Op::CallNative { .. } => {}
- Op::ArgumentCount
- | Op::LoadArgument { .. }
- | Op::IsCallable
- | Op::EmptyToUndefined
- | Op::Typeof
- | Op::AllocateObject { .. }
- | Op::AllocateArray { .. }
- | Op::AllocateFunction { .. }
- | Op::AllocateEnvironment { .. }
- | Op::SliceArguments
- | Op::BoxInt32
- | Op::BoxBool
- | Op::BoxFloat64 => {}
Op::Phi => pending.extend(data.inputs.iter().copied()),
+ op if op.info().never_empty => {}
_ => return false,
}
}
diff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rs
index 11e869f104c..42a95f04148 100644
--- a/Libraries/LibJS/JIT/Rust/src/lib.rs
+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs
@@ -105,6 +105,7 @@ pub fn compile_for<M: asm::PortableMacroAssembler>(
&snapshot.executables,
&snapshot.runtime,
snapshot.options.stress,
+ snapshot.options.verify_ir,
)?;
let mut dump = None;
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rs b/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rs
index 280f49bb03b..aa9a920d63a 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/frame_initialization.rs
@@ -73,16 +73,15 @@ impl State {
}
/// The node to put before a node with `need`, if any, and the state
- /// after both. If `clobbers_floats`, that node clobbers the floating
- /// point registers anyway (see `Op::InitializeFrame`).
- fn satisfy(self, need: &Need, clobbers_floats: bool) -> (Option<Op>, State) {
+ /// after both.
+ fn satisfy(self, need: &Need) -> (Option<Op>, State) {
const INITIALIZED: State = State {
published: Holds::Yes,
initialized: Holds::Yes,
};
match (need, self.initialized, self.published) {
- (Need::Initialized, Holds::No, _) => (Some(Op::InitializeFrame { clobbers_floats }), INITIALIZED),
- (Need::Initialized, Holds::Maybe, _) => (Some(Op::EnsureFrameInitialized { clobbers_floats }), INITIALIZED),
+ (Need::Initialized, Holds::No, _) => (Some(Op::InitializeFrame), INITIALIZED),
+ (Need::Initialized, Holds::Maybe, _) => (Some(Op::EnsureFrameInitialized), INITIALIZED),
(Need::Published, _, Holds::No | Holds::Maybe) => (
Some(Op::PublishFrame),
State {
@@ -154,7 +153,7 @@ pub fn run(graph: &mut Graph, layout: &FrameLayout) {
block
.body
.iter()
- .find(|node| matches!(graph.node(**node).op, Op::InitializeFrame { .. }))
+ .find(|node| matches!(graph.node(**node).op, Op::InitializeFrame))
.map(|node| (index, *node))
}) else {
return;
@@ -216,9 +215,7 @@ pub fn run(graph: &mut Graph, layout: &FrameLayout) {
}
continue;
}
- let op = &graph.node(*node).op;
- let clobbers_floats = op.properties().is_call || crate::regalloc::saves_only_gprs(op);
- let (op, after) = current.satisfy(&need, clobbers_floats);
+ let (op, after) = current.satisfy(&need);
if let Some(op) = op {
insertions.push((block, index, op));
}
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/tests.rs b/Libraries/LibJS/JIT/Rust/src/passes/tests.rs
index 72f86226ed8..96950ce8b26 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/tests.rs
@@ -851,7 +851,7 @@ fn frame_writes_after_slow_paths_that_may_initialize_the_frame_check_first() {
};
let mut graph = Graph::default();
graph.add_block(Block::default());
- let initialize = node(&mut graph, Op::InitializeFrame { clobbers_floats: false }, vec![], None);
+ let initialize = node(&mut graph, Op::InitializeFrame, vec![], None);
let call = node(
&mut graph,
Op::CallSlowPath {
@@ -882,7 +882,7 @@ fn frame_writes_after_slow_paths_that_may_initialize_the_frame_check_first() {
ops.as_slice(),
[
Op::CallSlowPath { .. },
- Op::EnsureFrameInitialized { .. },
+ Op::EnsureFrameInitialized,
Op::StoreSlot { .. }
]
));
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
index 36a4100fd32..806f5134ab5 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
@@ -85,10 +85,8 @@ pub fn verify_frame_writes(graph: &Graph, layout: &FrameLayout) -> Result<(), St
let reader = nodes[position + 1..].iter().find(|next| {
let op = &graph.node(**next).op;
let properties = op.properties();
- let initializes_frame = matches!(
- op,
- Op::InitializeFrame { .. } | Op::EnsureFrameInitialized { .. } | Op::PublishFrame
- );
+ let initializes_frame =
+ matches!(op, Op::InitializeFrame | Op::EnsureFrameInitialized | Op::PublishFrame);
!matches!(op, Op::StoreSlot { .. })
&& !(is_argument && initializes_frame)
&& (properties.reads != Locations::NONE || properties.writes != Locations::NONE)
@@ -465,135 +463,19 @@ fn verify_frame_states(graph: &Graph) -> Result<(), String> {
}
}
-fn branch_input_reprs(condition: crate::ir::BranchCondition) -> Vec<Repr> {
- let tagged = |count: usize| vec![Repr::Tagged; count];
- match condition {
- crate::ir::BranchCondition::Bool => vec![Repr::Bool],
- crate::ir::BranchCondition::Int32(_) => vec![Repr::Int32, Repr::Int32],
- crate::ir::BranchCondition::Float64(_) => vec![Repr::Float64, Repr::Float64],
- crate::ir::BranchCondition::TaggedEquals { .. } => tagged(2),
- crate::ir::BranchCondition::Nullish
- | crate::ir::BranchCondition::Undefined
- | crate::ir::BranchCondition::Object
- | crate::ir::BranchCondition::NonNegativeInt32
- | crate::ir::BranchCondition::Int32Value
- | crate::ir::BranchCondition::Int32OrBoolean
- | crate::ir::BranchCondition::Double
- | crate::ir::BranchCondition::String
- | crate::ir::BranchCondition::ElementsKind(_)
- | crate::ir::BranchCondition::Builtin(_) => tagged(1),
- crate::ir::BranchCondition::ResolvedString
- | crate::ir::BranchCondition::MagicalLength
- | crate::ir::BranchCondition::Extensible
- | crate::ir::BranchCondition::HoleFillableArray
- | crate::ir::BranchCondition::ArrayIterator
- | crate::ir::BranchCondition::GeneratorObject
- | crate::ir::BranchCondition::PlainArrayPrototypeChain
- | crate::ir::BranchCondition::ArrayWithRealmArrayPrototypeAndNoNamedProperties
- | crate::ir::BranchCondition::HoldsValidWatchpointSet => vec![Repr::Pointer],
- crate::ir::BranchCondition::Shape(_) => vec![Repr::Tagged, Repr::Pointer],
- crate::ir::BranchCondition::PropertyIteratorCacheValid => tagged(2),
- crate::ir::BranchCondition::BindingMutable { .. } | crate::ir::BranchCondition::NextBindingOfShape { .. } => {
- vec![Repr::Pointer]
- }
- crate::ir::BranchCondition::IndexInBounds => vec![Repr::Int32, Repr::Int32],
- }
-}
-
-/// The representations a node requires of its inputs, if it requires any.
-fn expected_input_reprs(graph: &Graph, node: NodeId) -> Option<Vec<Repr>> {
- let node = graph.node(node);
- let tagged = |count: usize| vec![Repr::Tagged; count];
- match node.op {
- Op::Phi | Op::Constant(_) | Op::StoreSlot { .. } => None,
- Op::Branch { condition, .. } | Op::Refine { condition, .. } => Some(branch_input_reprs(condition)),
- Op::UnboxInt32 | Op::UnboxDouble | Op::CheckNumber | Op::StringAddress => Some(tagged(1)),
- Op::StringLength => Some(vec![Repr::Pointer]),
- Op::BoxFloat64
- | Op::Float64Unary { .. }
- | Op::Float64ToInt32
- | Op::Float64ToUint8Clamped
- | Op::CheckFloat64Int32 => Some(vec![Repr::Float64]),
- 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]),
- Op::StringsEqual | Op::ConcatenateStrings | Op::ToObject => Some(tagged(2)),
- Op::PrimitiveToString => Some(tagged(1)),
- Op::CallIntrinsic { intrinsic } => intrinsic.helper_call().map(|call| {
- std::iter::once(call.receiver)
- .chain(call.arguments.iter().copied())
- .map(|operand| operand.repr())
- .collect()
- }),
- Op::ArrayCreate => Some(vec![Repr::Int32, Repr::Tagged]),
- Op::CallArraySplice => {
- let mut inputs = tagged(node.inputs.len());
- if inputs.len() < 3 {
- return Some(vec![Repr::Tagged, Repr::Int32, Repr::Int32]);
- }
- inputs[1] = Repr::Int32;
- inputs[2] = Repr::Int32;
- Some(inputs)
- }
- Op::LoadStringCodeUnit => Some(vec![Repr::Pointer, Repr::Int32]),
- Op::SingleCharacterString | Op::Int32Abs | Op::Int32ToFloat64 => Some(vec![Repr::Int32]),
- Op::AppendElement | Op::CallStoreHoleyElement => Some(vec![Repr::Pointer, Repr::Int32, Repr::Tagged]),
- Op::LoadElementsLength | Op::LoadElementsCapacity => Some(vec![Repr::Pointer]),
- Op::LoadPropertyIteratorKey => Some(vec![Repr::Tagged, Repr::Int32]),
- Op::OpenArrayIteration => Some(tagged(1)),
- Op::LoadArrayIteratorArray
- | Op::LoadArrayIteratorIndex
- | Op::FinishArrayIterator
- | Op::LoadGeneratorCompletionType
- | Op::LoadGeneratorCompletionValue => Some(vec![Repr::Pointer]),
- Op::StoreArrayIteratorIndex => Some(vec![Repr::Pointer, Repr::Int32]),
- Op::BranchOnPc { .. } => Some(vec![Repr::Int32]),
- Op::BoxInt32 | Op::CheckNonNegativeInt32 => Some(vec![Repr::Int32]),
- Op::CheckShape { .. }
- | Op::LoadNamed { .. }
- | Op::ShapeSwitch { .. }
- | Op::CheckAccessorFunction { .. }
- | Op::LoadAccessorFunction { .. } => Some(vec![Repr::Tagged, Repr::Pointer]),
- Op::StoreNamed { .. } | Op::AddNamed { .. } => Some(vec![Repr::Tagged, Repr::Tagged, Repr::Pointer]),
- Op::LoadElementAt { .. } => Some(vec![Repr::Pointer, Repr::Int32]),
- Op::StoreElementAt { kind } => Some(vec![Repr::Pointer, Repr::Int32, kind.stored_repr()]),
- Op::CheckBounds => Some(vec![Repr::Int32, Repr::Int32]),
- Op::LoadTypedArrayLength
- | Op::LoadTypedArrayDataOffset
- | Op::TypedArrayDataAddress
- | Op::CheckTypedArrayStorage => Some(vec![Repr::Pointer]),
- Op::BoxBool | Op::BoolToInt32 => Some(vec![Repr::Bool]),
- Op::LoadFunctionEnvironment { .. }
- | Op::BoxCell
- | Op::LoadOuterEnvironment
- | Op::LoadEnvironmentBinding { .. }
- | Op::AppendEnvironmentBinding => Some(vec![Repr::Pointer]),
- Op::StoreEnvironmentBinding { .. } => Some(vec![Repr::Pointer, Repr::Tagged]),
- Op::AllocateFunction { .. } | Op::ProbeGlobalCache { .. } => Some(vec![Repr::Pointer, Repr::Pointer]),
- Op::ProbeGlobalStore { .. } => Some(vec![Repr::Tagged, Repr::Pointer, Repr::Pointer]),
- Op::Int32Binary { .. } | Op::Int32WrappingBinary { .. } | Op::Int32Compare { .. } => {
- Some(vec![Repr::Int32, Repr::Int32])
- }
- _ => Some(tagged(node.inputs.len())),
- }
-}
-
fn check_input_reprs(graph: &Graph, node_id: NodeId) -> Option<String> {
- let expected = expected_input_reprs(graph, node_id)?;
let node = graph.node(node_id);
- if node.inputs.len() != expected.len() {
- return Some(format!(
- "v{} ({}) has {} inputs, but takes {}",
- node_id.0,
- node.op.name(),
- node.inputs.len(),
- expected.len()
- ));
- }
+ let expected = match node.op.info().inputs.reprs(node.inputs.len()) {
+ Ok(expected) => expected?,
+ Err(count) => {
+ return Some(format!(
+ "v{} ({}) has {} inputs, but takes {count}",
+ node_id.0,
+ node.op.name(),
+ node.inputs.len(),
+ ));
+ }
+ };
for (input, repr) in node.inputs.iter().zip(expected) {
let actual = graph.node(*input).repr?;
if actual != repr {
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs
index 59a56d19075..ef4451506f7 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/liveness.rs
@@ -11,6 +11,8 @@
//! state uses happen after the call returns.
use crate::bitset::BitSet;
+use crate::codegen::lowering_info::Clobbers as LoweringClobbers;
+use crate::codegen::lowering_info::lowering_info;
use crate::ir::BlockId;
use crate::ir::Graph;
use crate::ir::NodeId;
@@ -248,10 +250,12 @@ impl ValueLiveness {
} else if is_allocated_value(graph, node) {
dead_outputs.insert(node.index());
}
- let op = &graph.node(node).op;
- let is_call = op.properties().is_call;
- // NB: Their slow paths clobber the floating point registers.
- let clobbers_floats = super::saves_only_gprs(op);
+ let (is_call, clobbers_floats) = match lowering_info(graph.node(node)).clobbers {
+ LoweringClobbers::CallerSaved => (true, false),
+ // NB: Their slow paths clobber the floating point registers.
+ LoweringClobbers::Floats => (false, true),
+ LoweringClobbers::Nothing => (false, false),
+ };
if is_call || clobbers_floats {
clobbers.float_clobbers += 1;
clobbers.calls += u32::from(is_call);
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
index e601b567c64..3ce4cf636e6 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
@@ -39,9 +39,13 @@
//! every value but `Repr::Float64` ones, which floating point registers hold.
//! Floating point registers are numbered from `FPR_BASE` on in `Location`s
//! and masks. Nodes whose slow paths save the general purpose registers
-//! around their calls (see `saves_only_gprs()`) clobber the floating point
+//! around their calls (see `Clobbers::Floats`) clobber the floating point
//! ones, so float64 values live across them get stack slots, like values
//! live across a call.
+//!
+//! What each node needs (where its inputs and its output are, its temps and
+//! what it clobbers) is declared next to its lowering, in
+//! `codegen::lowering_info()`.
mod coalescing;
mod liveness;
@@ -53,11 +57,14 @@ pub use moves::resolve_parallel_moves;
pub use verify::verify;
use crate::code::Repr;
+use crate::codegen::lowering_info::Clobbers;
+use crate::codegen::lowering_info::FixedRegister;
+use crate::codegen::lowering_info::InputConstraint;
+use crate::codegen::lowering_info::OutputConstraint;
+use crate::codegen::lowering_info::lowering_info;
use crate::inline_vec::InlineVec;
use crate::ir::BlockId;
-use crate::ir::BranchCondition;
use crate::ir::Graph;
-use crate::ir::Node;
use crate::ir::NodeId;
use crate::ir::Op;
use liveness::ValueLiveness;
@@ -98,45 +105,6 @@ impl RegisterClass {
}
}
-/// Whether the lowering of `op` calls out of line keeping only the general
-/// purpose registers (register-saving `CallSlowPath`s, the growth of arrays and named storage, the runtime's
-/// cache probes, and allocations that call the runtime), or stores constants
-/// through a floating point register (frame initialization for such nodes
-/// and calls): it clobbers every floating point register.
-pub fn saves_only_gprs(op: &Op) -> bool {
- matches!(
- op,
- Op::CallSlowPath {
- saves_registers: true,
- ..
- } | Op::InitializeFrame { clobbers_floats: true }
- | Op::EnsureFrameInitialized { clobbers_floats: true }
- | Op::CallArrayPush
- | Op::CallStoreHoleyElement
- | Op::OpenArrayIteration
- | Op::AddNamed { .. }
- | Op::ProbeKeyedStore { .. }
- | Op::ProbePropertyCache { .. }
- | Op::ProbePropertyStore { .. }
- | Op::ProbeHasProperty { .. }
- | Op::AllocateObject { .. }
- | Op::AllocateArray { .. }
- | Op::AllocateFunction { .. }
- | Op::AllocateEnvironment { .. }
- | Op::ConcatenateStrings
- )
-}
-
-/// Whether the lowering of `op` computes its output from its first input
-/// as two-address instructions do, so that the output may take the
-/// register of that input where it dies.
-fn reuses_first_input(op: &Op) -> bool {
- matches!(
- op,
- Op::Int32WrappingBinary { .. } | Op::Int32Binary { .. } | Op::BoolToInt32 | Op::TypedArrayDataAddress
- )
-}
-
/// A set of registers, as a bit mask of register numbers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RegisterMask(pub u64);
@@ -183,6 +151,14 @@ impl RegisterSet {
}
}
+ /// The number of the calling convention's register `register`.
+ pub fn fixed(&self, register: FixedRegister) -> u8 {
+ match register {
+ FixedRegister::Argument(index) => self.argument_gprs[usize::from(index)],
+ FixedRegister::Return => self.return_gpr,
+ }
+ }
+
/// The registers of both classes a call clobbers.
pub fn caller_saved(&self) -> RegisterMask {
RegisterMask(self.caller_saved_gprs.0 | (self.caller_saved_fprs.0 << FPR_BASE))
@@ -286,238 +262,6 @@ impl Allocation {
}
}
-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
-enum InputConstraint {
- #[default]
- Register,
- FixedRegister(u8),
- /// A register, or the constant itself if the input is one, which code
- /// generation uses as an immediate.
- RegisterOrConstant,
- /// Wherever the value is: a register, its stack slot or a constant.
- Anywhere,
-}
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum OutputConstraint {
- None,
- Register,
- FixedRegister(u8),
-}
-
-struct Constraints {
- inputs: InlineVec<InputConstraint, 4>,
- output: OutputConstraint,
- temps: u8,
- is_call: bool,
-}
-
-fn constraints(node: &Node, registers: &RegisterSet) -> Constraints {
- let register_inputs = || InlineVec::from_elem(InputConstraint::Register, node.inputs.len());
- let output = if node.repr.is_some() {
- OutputConstraint::Register
- } else {
- OutputConstraint::None
- };
- let mut constraints = Constraints {
- inputs: register_inputs(),
- output,
- temps: 0,
- is_call: node.op.properties().is_call,
- };
- match node.op {
- Op::Constant(_) | Op::Phi => unreachable!("constants and phis have no constraints"),
- Op::ToBoolean => {
- constraints.inputs = InlineVec::from_elem(InputConstraint::FixedRegister(registers.argument_gprs[0]), 1);
- constraints.output = OutputConstraint::FixedRegister(registers.return_gpr);
- }
- // NB: The VM is the first argument.
- Op::PrimitiveToString | Op::CallIntrinsic { .. } | Op::ToObject | Op::ArrayCreate => {
- constraints.inputs = (0..node.inputs.len())
- .map(|index| InputConstraint::FixedRegister(registers.argument_gprs[index + 1]))
- .collect();
- constraints.output = OutputConstraint::FixedRegister(registers.return_gpr);
- }
- Op::CallArraySplice => {
- constraints.inputs = (0..node.inputs.len())
- .map(|index| {
- if index < 3 {
- InputConstraint::FixedRegister(registers.argument_gprs[index + 1])
- } else {
- InputConstraint::RegisterOrConstant
- }
- })
- .collect();
- constraints.output = OutputConstraint::FixedRegister(registers.return_gpr);
- }
- Op::Generic { .. } => {
- if node.repr.is_some() {
- constraints.output = OutputConstraint::FixedRegister(registers.return_gpr);
- }
- }
- Op::SliceArguments => {
- constraints.inputs = InlineVec::from_elem(InputConstraint::FixedRegister(registers.argument_gprs[2]), 1);
- constraints.output = OutputConstraint::FixedRegister(registers.return_gpr);
- }
- Op::Return => {
- constraints.inputs = InlineVec::from_elem(InputConstraint::FixedRegister(registers.return_gpr), 1);
- }
- // Comparisons and int32 arithmetic take a constant right-hand side
- // as an immediate.
- Op::Int32Compare { .. }
- | Op::TaggedEquals { .. }
- | Op::Branch {
- condition: BranchCondition::Int32(_) | BranchCondition::TaggedEquals { .. },
- ..
- } => constraints.inputs[1] = InputConstraint::RegisterOrConstant,
- Op::Int32WrappingBinary { .. } => constraints.inputs[1] = InputConstraint::RegisterOrConstant,
- Op::Int32Binary { op } if op != crate::ir::BinaryOp::Mul => {
- constraints.inputs[1] = InputConstraint::RegisterOrConstant;
- // The quotient of a remainder.
- if op == crate::ir::BinaryOp::Mod {
- constraints.temps = 1;
- }
- }
- Op::Uint32ShiftRight => constraints.inputs[1] = InputConstraint::RegisterOrConstant,
- // The new rope string, its length and a temp.
- Op::ConcatenateStrings => constraints.temps = 3,
- Op::StringsEqual => constraints.temps = 1,
- // A value and a cursor for filling the registers and locals.
- Op::InitializeFrame { .. } | Op::EnsureFrameInitialized { .. } => constraints.temps = 2,
- // The object's property storage.
- Op::StoreNamed { .. } | Op::AddNamed { .. } | Op::CheckAccessorFunction { .. } => constraints.temps = 1,
- // The object whose prototype comes next.
- Op::HasInPrototypeChain => constraints.temps = 1,
- // The environment's binding values.
- Op::StoreGlobalBinding { .. } => constraints.temps = 1,
- // Direct and native calls with inputs build the callee's frame in
- // temps.
- Op::CallDirect {
- stores_operands: true, ..
- }
- | Op::CallNative {
- stores_operands: true, ..
- } => {
- // NB: The call stores its operands to the frame first.
- constraints.inputs = InlineVec::from_elem(InputConstraint::Anywhere, node.inputs.len());
- constraints.output = OutputConstraint::FixedRegister(registers.return_gpr);
- }
- Op::CallDirect { .. } | Op::CallNative { .. } if !node.inputs.is_empty() => {
- constraints.temps = crate::codegen::DIRECT_CALL_TEMPS;
- // NB: Calls in inlined callees return their result.
- if node.repr.is_some() {
- constraints.output = OutputConstraint::FixedRegister(registers.return_gpr);
- }
- }
- // Native accessor calls build the callee's frame in temps, and return
- // the result.
- Op::CallNativeAccessor { .. } => {
- constraints.temps = crate::codegen::DIRECT_CALL_TEMPS;
- constraints.output = OutputConstraint::FixedRegister(registers.return_gpr);
- }
- // The object, its shape and the cache entry.
- Op::ProbePropertyCache { .. } | Op::ProbeKeyedCache { .. } => constraints.temps = 3,
- // Those, and the named property storage of property additions.
- Op::ProbeKeyedStore { .. } | Op::ProbePropertyStore { .. } => constraints.temps = 4,
- // The cache, the global declarative environment, the global object
- // and a temp.
- Op::ProbeGlobalCache { .. } | Op::ProbeGlobalStore { .. } => constraints.temps = 4,
- // The object or its elements, and the keyed cache's registers.
- Op::ProbeHasProperty { .. } => constraints.temps = 3,
- // The address of the object.
- Op::Branch {
- condition: BranchCondition::ElementsKind(_),
- ..
- } => constraints.temps = 1,
- // NB: Slow path calls read their operands from where they are.
- Op::CallSlowPath { saves_registers, .. } => {
- constraints.inputs = InlineVec::from_elem(InputConstraint::Anywhere, node.inputs.len());
- // NB: A call's value is moved into the return register once its
- // slow path continued, where a conditional jump's control
- // word is.
- if !saves_registers && node.repr.is_some() {
- constraints.output = OutputConstraint::FixedRegister(registers.return_gpr);
- }
- }
- // NB: The output comes from where the slow path call left it.
- Op::SlowPathOutput { .. } => constraints.inputs = InlineVec::from_elem(InputConstraint::Anywhere, 1),
- // The object, the property iterator cache, and a temp.
- Op::Branch {
- condition: BranchCondition::PropertyIteratorCacheValid,
- ..
- } => constraints.temps = 3,
- // The binding's index, and a temp; the environment's shape and the
- // binding's index.
- Op::Branch {
- condition: BranchCondition::BindingMutable { .. } | BranchCondition::NextBindingOfShape { .. },
- ..
- } => constraints.temps = 2,
- // The array's prototypes.
- Op::Branch {
- condition: BranchCondition::HoleFillableArray,
- ..
- } => constraints.temps = 1,
- // The environment's binding values (and their count).
- Op::StoreEnvironmentBinding { .. } | Op::AppendEnvironmentBinding => constraints.temps = 1,
- // The array, then its prototypes.
- Op::CheckAppendableArray => constraints.temps = 2,
- // The object's prototypes.
- Op::Branch {
- condition: BranchCondition::PlainArrayPrototypeChain,
- ..
- } => constraints.temps = 1,
- // The object's shape.
- Op::Branch {
- condition: BranchCondition::ArrayWithRealmArrayPrototypeAndNoNamedProperties,
- ..
- } => constraints.temps = 1,
- // The object's elements.
- Op::LoadElementsCapacity | Op::AppendElement => constraints.temps = 1,
- // The object, then its elements or element address.
- Op::CheckElements { .. }
- | Op::CheckTypedArray
- | Op::CheckArray
- | Op::CheckIdentityComparable
- | Op::CheckClosure { .. } => {
- constraints.temps = 1;
- }
- // The elements or the element address.
- Op::LoadElementAt { .. } => {
- constraints.inputs[1] = InputConstraint::RegisterOrConstant;
- constraints.temps = 1;
- }
- // NB: Stores of integer and tagged constants store immediates.
- Op::StoreElementAt { kind } => {
- constraints.inputs[1] = InputConstraint::RegisterOrConstant;
- if kind.stored_repr() != Repr::Float64 {
- constraints.inputs[2] = InputConstraint::RegisterOrConstant;
- }
- constraints.temps = 1;
- }
- Op::CheckBounds => {
- constraints.inputs[0] = InputConstraint::RegisterOrConstant;
- constraints.inputs[1] = InputConstraint::RegisterOrConstant;
- }
- // The heap and a value.
- Op::AllocateObject { .. } => constraints.temps = 2,
- // The object's property storage.
- Op::InitializeNamed { .. } => constraints.temps = 1,
- // The element storage and a value.
- Op::AllocateArray { .. } => constraints.temps = 2,
- // The function and a value.
- Op::AllocateFunction { .. } | Op::AllocateEnvironment { .. } => constraints.temps = 2,
- // The array's elements.
- Op::InitializeElement { .. } => constraints.temps = 1,
- // The function object.
- Op::Branch {
- condition: BranchCondition::Builtin(_),
- ..
- } => constraints.temps = 1,
- _ => {}
- }
- constraints
-}
-
/// Assigns locations to the values of `graph`. The verifier checks the
/// result where the IR is verified (see `verify()`).
pub fn allocate(graph: &Graph, registers: &RegisterSet) -> Allocation {
@@ -866,7 +610,7 @@ impl<'a> Allocator<'a> {
fn allocate_node(&mut self, node_id: NodeId) {
let node = self.graph.node(node_id);
self.position = self.liveness.positions[node_id.index()];
- let constraints = constraints(node, self.registers);
+ let constraints = lowering_info(node);
let mut moves = Vec::new();
let mut blocked = RegisterMask::default();
let mut inputs = InlineVec::from_elem(Location::Register(0), node.inputs.len());
@@ -874,9 +618,10 @@ impl<'a> Allocator<'a> {
// 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() {
- let InputConstraint::FixedRegister(register) = *constraint else {
+ let InputConstraint::Fixed(register) = *constraint else {
continue;
};
+ let register = self.registers.fixed(register);
let is_value = is_allocated_value(self.graph, *input);
if !is_value || self.value_registers[input.index()] != Some(register) {
debug_assert!(!blocked.contains(register), "two inputs need the same register");
@@ -911,7 +656,7 @@ impl<'a> Allocator<'a> {
inputs[index] = self.current_location(*input);
continue;
}
- if matches!(constraint, InputConstraint::FixedRegister(_)) {
+ if matches!(constraint, InputConstraint::Fixed(_)) {
continue;
}
let register = match self.value_registers[input.index()] {
@@ -945,7 +690,7 @@ impl<'a> Allocator<'a> {
let first_input_register = match inputs.first() {
Some(Location::Register(register))
if node.frame_state.is_none()
- && reuses_first_input(&node.op)
+ && constraints.reuses_first_input
&& is_allocated_value(self.graph, node.inputs[0])
&& self.liveness.dies_at[node_id.index()].contains(&node.inputs[0])
&& RegisterClass::of_register(*register) == RegisterClass::of(node.repr)
@@ -964,18 +709,17 @@ impl<'a> Allocator<'a> {
OutputConstraint::Register => Some(
first_input_register.unwrap_or_else(|| allocator.pick_register(blocked, RegisterClass::of(node.repr))),
),
- OutputConstraint::FixedRegister(register) => {
- debug_assert!(constraints.is_call || !blocked.contains(register));
+ OutputConstraint::Return => {
+ let register = allocator.registers.return_gpr;
+ debug_assert!(constraints.clobbers == Clobbers::CallerSaved || !blocked.contains(register));
allocator.evict(register);
Some(register)
}
};
- let clobbered = if constraints.is_call {
- self.registers.caller_saved()
- } else if saves_only_gprs(&node.op) {
- self.registers.allocatable(RegisterClass::Float)
- } else {
- RegisterMask::default()
+ let clobbered = match constraints.clobbers {
+ Clobbers::CallerSaved => self.registers.caller_saved(),
+ Clobbers::Floats => self.registers.allocatable(RegisterClass::Float),
+ Clobbers::Nothing => RegisterMask::default(),
};
{
for register in clobbered.iter() {
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs
index c76064f89e1..8457e42e709 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs
@@ -16,6 +16,9 @@ use super::Location;
use super::Move;
use super::RegisterSet;
use super::liveness::phi_inputs_from;
+use crate::codegen::lowering_info::Clobbers;
+use crate::codegen::lowering_info::InputConstraint;
+use crate::codegen::lowering_info::lowering_info;
use crate::ir::BlockId;
use crate::ir::Graph;
use crate::ir::NodeId;
@@ -293,6 +296,14 @@ impl Verifier<'_> {
self.error(format!("{context}: wrong number of input locations"));
return;
}
+ let lowering = lowering_info(node);
+ if allocation.temps.len() != usize::from(lowering.temps) {
+ self.error(format!(
+ "{context}: {} temps, but its lowering takes {}",
+ allocation.temps.len(),
+ lowering.temps
+ ));
+ }
for (index, (input, location)) in node.inputs.iter().zip(&allocation.inputs).enumerate() {
if let Location::Constant(bits) = location {
if self.graph.constant_value(*input) != Some(*bits) {
@@ -302,20 +313,8 @@ impl Verifier<'_> {
}
// NB: Slow path calls, and calls that store their operands, read
// them from where they are.
- let reads_inputs_anywhere = matches!(
- node.op,
- Op::CallSlowPath { .. }
- | Op::CallDirect {
- stores_operands: true,
- ..
- }
- | Op::CallNative {
- stores_operands: true,
- ..
- }
- | Op::SlowPathOutput { .. }
- );
- if !matches!(location, Location::Register(_)) && !reads_inputs_anywhere {
+ let reads_input_anywhere = lowering.inputs[index] == InputConstraint::Anywhere;
+ if !matches!(location, Location::Register(_)) && !reads_input_anywhere {
self.error(format!("{context}: input {index} is not in a register"));
}
self.check_location(*location, &context);
@@ -324,7 +323,6 @@ impl Verifier<'_> {
// A node may exit at any point after reading its inputs, including
// after it wrote its temps and its output: exit values must survive both.
- let properties = node.op.properties();
for temp in &allocation.temps {
self.check_location(Location::Register(*temp), &context);
if allocation.inputs.contains(&Location::Register(*temp)) {
@@ -332,14 +330,13 @@ impl Verifier<'_> {
}
state.remove(&Location::Register(*temp));
}
- if properties.is_call {
- for register in self.registers.caller_saved().iter() {
- state.remove(&Location::Register(register));
- }
- } else if super::saves_only_gprs(&node.op) {
- for register in self.registers.allocatable(super::RegisterClass::Float).iter() {
- state.remove(&Location::Register(register));
- }
+ let clobbered = match lowering.clobbers {
+ Clobbers::CallerSaved => self.registers.caller_saved(),
+ Clobbers::Floats => self.registers.allocatable(super::RegisterClass::Float),
+ Clobbers::Nothing => super::RegisterMask::default(),
+ };
+ for register in clobbered.iter() {
+ state.remove(&Location::Register(register));
}
if let Some(output @ Location::Register(_)) = allocation.output {
// NB: Cloning the state instead would take time quadratic in the size of code that keeps many values in