Skip to content

Truly independent web browser

LibJS/JIT: Build the text of dumps and of verifiers without the heap

Andreas Kling6eae257cc3eb
diff --git a/Libraries/LibJS/JIT/Rust/build.rs b/Libraries/LibJS/JIT/Rust/build.rs
index fec4f0284ec..77da6f525fd 100644
--- a/Libraries/LibJS/JIT/Rust/build.rs
+++ b/Libraries/LibJS/JIT/Rust/build.rs
@@ -12,7 +12,7 @@
//! `Libraries/LibJS/Rust/build.rs` through `flapc::rust_bytecode`.
// NB: The rule against containers of the heap (see clippy.toml) is for the compiler. This script runs at build time.
-#![allow(clippy::disallowed_types, clippy::disallowed_macros)]
+#![allow(clippy::disallowed_types, clippy::disallowed_macros, clippy::disallowed_methods)]
use flapc::metadata::Field;
use flapc::metadata::InstructionDefinition;
diff --git a/Libraries/LibJS/JIT/Rust/clippy.toml b/Libraries/LibJS/JIT/Rust/clippy.toml
index 6af6d1e76b2..a5b32f55582 100644
--- a/Libraries/LibJS/JIT/Rust/clippy.toml
+++ b/Libraries/LibJS/JIT/Rust/clippy.toml
@@ -56,6 +56,9 @@ disallowed-methods = [
{ path = "slice::sort_by", reason = "a stable sort makes a block in the heap: use sort_unstable_by, with a key that has no ties" },
{ path = "slice::sort_by_key", reason = "a stable sort makes a block in the heap: use sort_unstable_by_key, with a key that has no ties" },
{ path = "slice::sort_by_cached_key", reason = "this sort makes a block in the heap: use sort_unstable_by_key, with a key that has no ties" },
+ { path = "slice::to_vec", reason = "the compiler makes no block in the heap: use Zone::alloc_slice_copy, or ak::ZoneVec::from_slice_in" },
+ { path = "std::string::ToString::to_string", reason = "the compiler makes no block in the heap: show the value with Display, or write it into a crate::debug_text::DebugText" },
+ { path = "std::borrow::ToOwned::to_owned", reason = "the compiler makes no block in the heap: keep the reference, or copy into a zone" },
]
# The compiler keeps its data in zones (see ak::Zone), so that all the memory of a compile can go back to the system.
@@ -72,7 +75,9 @@ disallowed-types = [
{ path = "std::boxed::Box", reason = "the compiler makes no block in the heap: use Zone::alloc" },
{ path = "std::rc::Rc", reason = "the compiler makes no block in the heap: share a reference into a zone" },
{ path = "std::sync::Arc", reason = "the compiler makes no block in the heap: share a reference into a zone" },
+ { path = "std::string::String", reason = "the compiler makes no block in the heap: text is a Display value, or a crate::debug_text::DebugText in a zone" },
]
disallowed-macros = [
{ path = "std::vec", reason = "the compiler makes no block in the heap: use a slice, or ak::ZoneVec" },
+ { path = "std::format", reason = "the compiler makes no block in the heap: write! into a Formatter or into a crate::debug_text::DebugText" },
]
diff --git a/Libraries/LibJS/JIT/Rust/src/asm/disassembler.rs b/Libraries/LibJS/JIT/Rust/src/asm/disassembler.rs
index 2a4c4586c73..e4925763aea 100644
--- a/Libraries/LibJS/JIT/Rust/src/asm/disassembler.rs
+++ b/Libraries/LibJS/JIT/Rust/src/asm/disassembler.rs
@@ -10,14 +10,17 @@
//! the decoder of the host architecture; code for the other one is listed as
//! raw bytes.
+use core::fmt;
+use core::fmt::Write;
+
use super::Architecture;
/// One instruction of a listing, at `offset` from the start of the code.
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct DisassembledInstruction {
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct DisassembledInstruction<'a> {
pub offset: usize,
pub length: usize,
- pub text: String,
+ pub text: &'a str,
/// The 64-bit constant the instruction materializes, if any (an
/// immediate move, or the last `movz`/`movk` of a sequence on AArch64,
/// or a load from the constant pool).
@@ -33,13 +36,13 @@ pub fn for_each_instruction(
architecture: Architecture,
code: &[u8],
data_offset: usize,
- mut visit: impl FnMut(&DisassembledInstruction),
+ mut visit: impl FnMut(&DisassembledInstruction<'_>),
) {
let constant_at = |target: usize| {
let bytes = code.get(target..target + 8)?;
(target >= data_offset).then(|| u64::from_le_bytes(bytes.try_into().expect("eight bytes")))
};
- let mut visit_instruction = |mut instruction: DisassembledInstruction| {
+ let mut visit_instruction = |mut instruction: DisassembledInstruction<'_>| {
if let Some(target) = instruction.pc_relative_target {
instruction.constant = instruction.constant.or_else(|| constant_at(target));
}
@@ -50,32 +53,116 @@ pub fn for_each_instruction(
Architecture::AArch64 => aarch64_instructions(&code[..data_offset], &mut visit_instruction),
}
let first_constant = data_offset.next_multiple_of(8);
+ let mut text = InstructionText::new();
for offset in (first_constant..code.len()).step_by(8) {
let value = constant_at(offset).expect("constants fill the data");
+ text.clear();
+ let _ = write!(text, ".quad {value:#x}");
visit_instruction(DisassembledInstruction {
offset,
length: 8,
- text: format!(".quad {value:#x}"),
+ text: text.as_str(),
constant: Some(value),
pc_relative_target: None,
});
}
}
+/// The text of one instruction. It is cut at the boundary of a character if it is longer than the room for it, which
+/// is far more than the longest instruction needs.
+struct InstructionText {
+ bytes: [u8; Self::ROOM],
+ len: usize,
+ /// Whether runs of white space become one space, and white space at the start and at the end goes away.
+ single_spaced: bool,
+ /// Whether white space came after the last character that was not.
+ space: bool,
+}
+
+impl InstructionText {
+ // NB: The longest instruction text of the tests of the JIT has 41 bytes.
+ const ROOM: usize = 256;
+
+ fn new() -> Self {
+ Self {
+ bytes: [0; Self::ROOM],
+ len: 0,
+ single_spaced: false,
+ space: false,
+ }
+ }
+
+ /// A text with one space between each two words.
+ #[cfg(any(test, target_arch = "aarch64"))]
+ fn single_spaced() -> Self {
+ Self {
+ single_spaced: true,
+ ..Self::new()
+ }
+ }
+
+ fn clear(&mut self) {
+ self.len = 0;
+ self.space = false;
+ }
+
+ fn as_str(&self) -> &str {
+ // NB: Text goes in at the boundaries of characters only, so this never fails.
+ core::str::from_utf8(&self.bytes[..self.len]).unwrap_or_default()
+ }
+
+ fn push_str(&mut self, text: &str) {
+ let mut end = text.len().min(Self::ROOM - self.len);
+ while !text.is_char_boundary(end) {
+ end -= 1;
+ }
+ self.bytes[self.len..self.len + end].copy_from_slice(&text.as_bytes()[..end]);
+ self.len += end;
+ }
+}
+
+impl fmt::Write for InstructionText {
+ fn write_str(&mut self, text: &str) -> fmt::Result {
+ if !self.single_spaced {
+ self.push_str(text);
+ return Ok(());
+ }
+ for (index, character) in text.char_indices() {
+ if character.is_whitespace() {
+ self.space = self.len != 0;
+ continue;
+ }
+ if self.space {
+ self.push_str(" ");
+ self.space = false;
+ }
+ self.push_str(&text[index..index + character.len_utf8()]);
+ }
+ Ok(())
+ }
+}
+
+#[cfg(any(test, target_arch = "x86_64"))]
+impl iced_x86::FormatterOutput for InstructionText {
+ fn write(&mut self, text: &str, _kind: iced_x86::FormatterTextKind) {
+ let _ = fmt::Write::write_str(self, text);
+ }
+}
+
/// The bytes of code that no decoder in this build understands.
#[cfg(not(test))]
-fn raw_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction)) {
- use std::fmt::Write;
-
+fn raw_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction<'_>)) {
+ let mut text = InstructionText::new();
for (index, chunk) in code.chunks(8).enumerate() {
- let mut text = String::from(".byte");
+ text.clear();
+ text.push_str(".byte");
for byte in chunk {
- write!(text, " {byte:02x}").unwrap();
+ let _ = write!(text, " {byte:02x}");
}
visit(DisassembledInstruction {
offset: 8 * index,
length: chunk.len(),
- text,
+ text: text.as_str(),
constant: None,
pc_relative_target: None,
});
@@ -83,12 +170,12 @@ fn raw_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction)
}
#[cfg(not(any(test, target_arch = "x86_64")))]
-fn x86_64_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction)) {
+fn x86_64_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction<'_>)) {
raw_instructions(code, visit);
}
#[cfg(not(any(test, target_arch = "aarch64")))]
-fn aarch64_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction)) {
+fn aarch64_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction<'_>)) {
raw_instructions(code, visit);
}
@@ -109,7 +196,7 @@ fn x86_64_formatter() -> iced_x86::IntelFormatter {
}
#[cfg(any(test, target_arch = "x86_64"))]
-fn x86_64_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction)) {
+fn x86_64_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction<'_>)) {
use iced_x86::Decoder;
use iced_x86::DecoderOptions;
use iced_x86::Formatter;
@@ -117,12 +204,13 @@ fn x86_64_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstructi
let mut decoder = Decoder::with_ip(64, code, 0, DecoderOptions::NONE);
let mut formatter = x86_64_formatter();
+ let mut text = InstructionText::new();
while decoder.can_decode() {
let instruction = decoder.decode();
let offset = instruction.ip() as usize;
- let mut text = String::new();
+ text.clear();
if instruction.is_invalid() {
- text = format!(".byte {:02x}", code[offset]);
+ let _ = write!(text, ".byte {:02x}", code[offset]);
} else {
formatter.format(&instruction, &mut text);
}
@@ -135,44 +223,33 @@ fn x86_64_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstructi
visit(DisassembledInstruction {
offset,
length: instruction.len(),
- text,
+ text: text.as_str(),
constant,
pc_relative_target,
});
}
}
-/// The words of `text`, with one space between each two.
#[cfg(any(test, target_arch = "aarch64"))]
-fn single_spaced(text: &str) -> String {
- let mut spaced = String::with_capacity(text.len());
- for word in text.split_whitespace() {
- if !spaced.is_empty() {
- spaced.push(' ');
- }
- spaced.push_str(word);
- }
- spaced
-}
-
-#[cfg(any(test, target_arch = "aarch64"))]
-fn aarch64_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction)) {
+fn aarch64_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruction<'_>)) {
use farm64::format::FmtFormatter;
- use farm64::format::format_to_string;
+ use farm64::format::Formatter;
let mut decoder = farm64::Decoder::new(code, 0, farm64::DecoderOptions::default());
let formatter = FmtFormatter::new();
+ let mut text = InstructionText::single_spaced();
// The value each register holds after a `movz`/`movk` sequence.
let mut register_values = [None::<u64>; 32];
while decoder.can_decode() {
let offset = decoder.position();
let instruction = decoder.decode();
let word = u32::from_le_bytes(code[offset..offset + 4].try_into().unwrap());
- let text = if instruction.is_invalid() {
- format!(".word {word:#010x}")
+ text.clear();
+ if instruction.is_invalid() {
+ let _ = write!(text, ".word {word:#010x}");
} else {
- single_spaced(&format_to_string(&formatter, &instruction))
- };
+ formatter.format(&instruction, &mut text);
+ }
let register = (word & 0x1f) as usize;
let shift = 16 * ((word >> 21) & 3);
let immediate = u64::from((word >> 5) & 0xffff) << shift;
@@ -198,7 +275,7 @@ fn aarch64_instructions(code: &[u8], visit: &mut impl FnMut(DisassembledInstruct
visit(DisassembledInstruction {
offset,
length: 4,
- text,
+ text: text.as_str(),
constant,
pc_relative_target,
});
@@ -223,21 +300,33 @@ pub(crate) use listings::x86_64;
pub(crate) mod listings {
use super::*;
+ /// A `DisassembledInstruction` that keeps its text.
+ #[derive(Debug, Clone, PartialEq, Eq)]
+ pub struct ListedInstruction {
+ pub offset: usize,
+ pub length: usize,
+ pub text: String,
+ pub constant: Option<u64>,
+ pub pc_relative_target: Option<usize>,
+ }
+
/// The instructions of `code` (assumed to start at offset 0, so branch targets are code offsets) for
/// `architecture`.
- pub fn listing(architecture: Architecture, code: &[u8]) -> Vec<DisassembledInstruction> {
+ pub fn listing(architecture: Architecture, code: &[u8]) -> Vec<ListedInstruction> {
listing_with_data(architecture, code, code.len())
}
/// Like `listing()`, for instructions up to `data_offset` followed by the 64-bit constants they load.
- pub fn listing_with_data(
- architecture: Architecture,
- code: &[u8],
- data_offset: usize,
- ) -> Vec<DisassembledInstruction> {
+ pub fn listing_with_data(architecture: Architecture, code: &[u8], data_offset: usize) -> Vec<ListedInstruction> {
let mut instructions = Vec::new();
for_each_instruction(architecture, code, data_offset, |instruction| {
- instructions.push(instruction.clone())
+ instructions.push(ListedInstruction {
+ offset: instruction.offset,
+ length: instruction.length,
+ text: instruction.text.to_string(),
+ constant: instruction.constant,
+ pc_relative_target: instruction.pc_relative_target,
+ })
});
instructions
}
@@ -264,7 +353,7 @@ pub(crate) mod listings {
/// Disassembles `code[start..end]`, with addresses relative to `code`.
pub fn aarch64_range(code: &[u8], start: usize, end: usize) -> Vec<String> {
use farm64::format::FmtFormatter;
- use farm64::format::format_to_string;
+ use farm64::format::Formatter;
let code_start = start;
let code = &code[start..end];
@@ -277,8 +366,9 @@ pub(crate) mod listings {
let instruction = decoder.decode();
let word = u32::from_le_bytes(code[offset..offset + 4].try_into().unwrap());
assert!(!instruction.is_invalid(), "invalid AArch64 encoding {word:#010x}");
- let text = format_to_string(&formatter, &instruction);
- lines.push(single_spaced(&text));
+ let mut text = InstructionText::single_spaced();
+ formatter.format(&instruction, &mut text);
+ lines.push(text.as_str().to_string());
}
lines
}
@@ -332,6 +422,32 @@ mod tests {
use super::super::aarch64;
use super::*;
+ #[test]
+ fn instruction_text_is_cut_at_the_boundary_of_a_character() {
+ let mut text = InstructionText::new();
+ let _ = write!(text, "{}", "ä".repeat(InstructionText::ROOM));
+ assert_eq!(text.as_str(), "ä".repeat(InstructionText::ROOM / 2));
+ let _ = write!(text, "a");
+ assert_eq!(text.as_str().len(), InstructionText::ROOM);
+ text.clear();
+ let _ = write!(text, "x{}", "€".repeat(InstructionText::ROOM));
+ assert_eq!(
+ text.as_str(),
+ format!("x{}", "€".repeat((InstructionText::ROOM - 1) / 3))
+ );
+ }
+
+ #[test]
+ fn single_spaced_text_has_one_space_between_words() {
+ let mut text = InstructionText::single_spaced();
+ let _ = write!(text, " mov x0,");
+ let _ = write!(text, " x1 \t");
+ assert_eq!(text.as_str(), "mov x0, x1");
+ text.clear();
+ let _ = write!(text, " ret ");
+ assert_eq!(text.as_str(), "ret");
+ }
+
#[test]
fn lists_x86_64_code_with_constants() {
// mov r11, 0x123456789abcdef0; call r11; ret
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
index a1ac778eb52..b923820fb3e 100644
--- a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs
@@ -6,10 +6,14 @@
use super::*;
use crate::bytecode::test_support::*;
-use crate::ir::dump;
use crate::snapshot::ExecutableSnapshot;
use crate::snapshot::List;
+/// `graph` as text (see `crate::ir::dump()`).
+fn dump(graph: &Graph, layout: &crate::bytecode::FrameLayout) -> String {
+ crate::ir::dump(graph, layout).to_string()
+}
+
/// The constants of `test_layout()`: c0 is 0 and c1 is 10.
pub(crate) fn test_constants() -> Vec<u64> {
vec![value::int32(0), value::int32(10)]
diff --git a/Libraries/LibJS/JIT/Rust/src/code.rs b/Libraries/LibJS/JIT/Rust/src/code.rs
index 12f86907370..5f931152456 100644
--- a/Libraries/LibJS/JIT/Rust/src/code.rs
+++ b/Libraries/LibJS/JIT/Rust/src/code.rs
@@ -7,6 +7,8 @@
//! The output of a compile job: machine code and the metadata the runtime
//! needs to install it and to exit from it into the interpreter.
+use core::fmt;
+
use ak::Column;
use crate::artifact::Artifact;
@@ -39,11 +41,10 @@ pub struct CompiledCode {
/// The tables of the code (see `artifact()`), which have `layout`.
pub words: Column<u32>,
pub layout: Layout,
- /// The debug dumps `CompileOptions` asked for, as text to print.
- pub dump: Option<String>,
- /// With `CompileOptions::coverage`, what the code contains (see
- /// `coverage::coverage_keys()`).
- pub coverage: Vec<String>,
+ /// The debug dumps `CompileOptions` asked for, as UTF-8 text to print (see `dump()`).
+ pub(crate) dump: Option<Column<u8>>,
+ /// With `CompileOptions::coverage`, what the code contains, one key on each line (see `coverage()`).
+ pub(crate) coverage: Option<Column<u8>>,
}
impl Default for CompiledCode {
@@ -67,24 +68,57 @@ impl CompiledCode {
words: Column::new(MAX_WORDS, c"JIT compiled tables"),
layout: Layout::default(),
dump: None,
- coverage: Vec::new(),
+ coverage: None,
}
}
+ /// The most bytes of text the debug dumps of one compile, or its coverage keys, can have. A dump that does not
+ /// fit is cut.
+ const MAX_TEXT_BYTES: usize = 1 << 30;
+
/// Drops the code. This keeps its memory for the next compile.
pub fn clear(&mut self) {
self.code.clear();
self.words.clear();
self.layout = Layout::default();
- self.dump = None;
- self.coverage = Vec::new();
+ for text in [&mut self.dump, &mut self.coverage].into_iter().flatten() {
+ text.clear();
+ }
+ }
+
+ /// Makes room for the texts that a compile with these options writes, and drops the others. A column for text
+ /// takes no memory before it gets text (see `Column`).
+ pub(crate) fn keep_texts(&mut self, dump: bool, coverage: bool) {
+ for (text, wanted, name) in [
+ (&mut self.dump, dump, c"JIT dump"),
+ (&mut self.coverage, coverage, c"JIT coverage keys"),
+ ] {
+ if !wanted {
+ *text = None;
+ } else if text.is_none() {
+ *text = Some(Column::new(Self::MAX_TEXT_BYTES, name));
+ }
+ }
+ }
+
+ /// The debug dumps `CompileOptions` asked for, as text to print, or `None` if it asked for none.
+ pub fn dump(&self) -> Option<&str> {
+ self.dump.as_deref().map(text_of)
+ }
+
+ /// With `CompileOptions::coverage`, what the code contains (see `coverage::write_coverage_keys()`).
+ pub fn coverage(&self) -> impl Iterator<Item = &str> {
+ self.coverage.as_deref().map_or("", text_of).lines()
}
/// Gives memory back to the system: all that is past the code and its tables, and past the room for
- /// `code_bytes` bytes of code and for `words` words of tables.
+ /// `code_bytes` bytes of code and for `words` words of tables, and all that is past the texts.
pub fn trim(&mut self, code_bytes: usize, words: usize) {
self.code.trim(code_bytes);
self.words.trim(words);
+ for text in [&mut self.dump, &mut self.coverage].into_iter().flatten() {
+ text.trim(0);
+ }
}
/// What the runtime reads to install the code, to enter it, and to translate its state into interpreter frames.
@@ -93,6 +127,80 @@ impl CompiledCode {
}
}
+/// The text in the bytes of a column of `CompiledCode`, which a `TextWriter` wrote.
+fn text_of(bytes: &[u8]) -> &str {
+ core::str::from_utf8(bytes).expect("a text writer writes UTF-8 and cuts it at the boundaries of characters")
+}
+
+/// Writes text into a column of `CompiledCode`: a debug dump, or coverage keys. When the column has no room for more,
+/// a dump keeps what fits and ends with a line that says so, and a list of keys keeps the keys that fit. Writes fail
+/// from then on.
+pub(crate) struct TextWriter<'a> {
+ column: &'a mut Column<u8>,
+ /// Whether the text is a list of lines, of which only whole ones are kept.
+ whole_lines: bool,
+ full: bool,
+}
+
+impl<'a> TextWriter<'a> {
+ /// The line that ends a dump that did not fit.
+ const CUT: &'static str = "[the dump goes on, but there is no room for more of it]\n";
+
+ /// A writer of a debug dump.
+ pub(crate) fn dump(column: &'a mut Column<u8>) -> Self {
+ Self {
+ column,
+ whole_lines: false,
+ full: false,
+ }
+ }
+
+ /// A writer of coverage keys, one on each line.
+ pub(crate) fn lines(column: &'a mut Column<u8>) -> Self {
+ Self {
+ column,
+ whole_lines: true,
+ full: false,
+ }
+ }
+}
+
+impl fmt::Write for TextWriter<'_> {
+ fn write_str(&mut self, text: &str) -> fmt::Result {
+ if self.full {
+ return Err(fmt::Error);
+ }
+ // NB: The room for the last line of a dump that does not fit stays free.
+ let room = (self.column.limit() - self.column.len()).saturating_sub(Self::CUT.len() + 1);
+ if text.len() <= room {
+ return self
+ .column
+ .try_extend_from_slice(text.as_bytes())
+ .map_err(|_| fmt::Error);
+ }
+ self.full = true;
+ if self.whole_lines {
+ let end = self
+ .column
+ .iter()
+ .rposition(|byte| *byte == b'\n')
+ .map_or(0, |index| index + 1);
+ self.column.truncate(end);
+ return Err(fmt::Error);
+ }
+ let mut end = room;
+ while !text.is_char_boundary(end) {
+ end -= 1;
+ }
+ let _ = self.column.try_extend_from_slice(&text.as_bytes()[..end]);
+ if self.column.last().is_some_and(|byte| *byte != b'\n') {
+ let _ = self.column.try_push(b'\n');
+ }
+ let _ = self.column.try_extend_from_slice(Self::CUT.as_bytes());
+ Err(fmt::Error)
+ }
+}
+
/// The status word of `JitResult { u64 value; u64 status; }`, returned by
/// compiled code in the second return register.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -350,3 +458,52 @@ const _: () = {
index += 1;
}
};
+
+#[cfg(test)]
+mod tests {
+ use core::fmt::Write;
+
+ use super::*;
+
+ #[test]
+ fn a_dump_that_does_not_fit_is_cut_with_a_last_line_that_says_so() {
+ let mut column = Column::new(100, c"test");
+ let mut writer = TextWriter::dump(&mut column);
+ assert!(write!(writer, "b0:\n").is_ok());
+ assert!(write!(writer, "{}", "ä".repeat(100)).is_err());
+ assert!(write!(writer, "more").is_err());
+ let text = text_of(&column);
+ assert!(text.len() <= 100);
+ assert!(text.starts_with("b0:\nää"), "{text}");
+ assert!(text.ends_with(&format!("ä\n{}", TextWriter::CUT)), "{text}");
+ }
+
+ #[test]
+ fn coverage_keys_that_do_not_fit_are_left_out() {
+ let mut column = Column::new(100, c"test");
+ let mut writer = TextWriter::lines(&mut column);
+ assert!(writeln!(writer, "Phi").is_ok());
+ assert!(writeln!(writer, "Return").is_ok());
+ assert!(write!(writer, "Exit.").is_ok());
+ assert!(writeln!(writer, "{}", "x".repeat(100)).is_err());
+ assert!(writeln!(writer, "Jump").is_err());
+ assert_eq!(text_of(&column), "Phi\nReturn\n");
+ }
+
+ #[test]
+ fn texts_are_kept_only_for_the_options_that_ask_for_them() {
+ let mut compiled = CompiledCode::new();
+ assert_eq!(compiled.dump(), None);
+ compiled.keep_texts(true, true);
+ let _ = write!(TextWriter::dump(compiled.dump.as_mut().unwrap()), "dump");
+ let _ = write!(TextWriter::lines(compiled.coverage.as_mut().unwrap()), "Phi\nJump\n");
+ assert_eq!(compiled.dump(), Some("dump"));
+ assert_eq!(compiled.coverage().collect::<Vec<_>>(), ["Phi", "Jump"]);
+ compiled.clear();
+ assert_eq!(compiled.dump(), Some(""));
+ assert_eq!(compiled.coverage().count(), 0);
+ compiled.keep_texts(false, false);
+ assert_eq!(compiled.dump(), None);
+ assert!(compiled.coverage.is_none());
+ }
+}
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs b/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs
index e6b40e842bd..22e91de7169 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/lowering_info.rs
@@ -18,6 +18,7 @@ use super::slow_path_call;
use crate::asm::Gpr;
use crate::asm::PortableMacroAssembler;
use crate::code::Repr;
+use crate::debug_text::DebugText;
use crate::ir::BinaryOp;
use crate::ir::BlockId;
use crate::ir::BranchCondition;
@@ -589,7 +590,7 @@ fn slow_path_record(opcode: crate::bytecode::OpCode, on_values: bool) -> Record
}
}
-impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {
+impl<'a, M: PortableMacroAssembler> Codegen<'a, '_, 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 {
@@ -610,20 +611,20 @@ impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {
/// 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 = String::new();
- let mut report = |error: String| {
+ pub(super) fn verify_lowerings(&self) -> Result<(), DebugText<'a>> {
+ let mut errors = DebugText::new_in(self.work);
+ let mut report = |error: core::fmt::Arguments<'_>| {
if !errors.is_empty() {
errors.push('\n');
}
- errors.push_str(&error);
+ errors.write_fmt(error);
};
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 {
- report(format!(
+ report(format_args!(
"v{} ({}) takes {requested} temps, but declares {declared}",
node.0,
self.graph.node(node).op.name()
@@ -637,7 +638,7 @@ impl<M: PortableMacroAssembler> Codegen<'_, '_, M> {
continue;
}
previous = Some(node);
- report(format!(
+ report(format_args!(
"v{} ({}) uses the saves area, but does not declare it",
node.0,
self.graph.node(node).op.name()
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
index 87eb7b7c10c..f70a068edf4 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/mod.rs
@@ -58,6 +58,7 @@ mod strings;
mod values;
pub use slow_path::SlowPathCall;
+pub use slow_path::SlowPathSymbol;
pub use slow_path::ValueSource;
pub use slow_path::binary_operands;
pub use slow_path::jump_operands;
@@ -606,101 +607,154 @@ fn assembly_failure(error: crate::asm::AsmError) -> CompileFailure {
/// The machine code `code` as disassembly, under headers naming the block, IR node
/// or tail each run of instructions was generated for. Calls of runtime
/// helpers and well-known values are named.
-pub fn dump_code(
- graph: &Graph,
- executable: &ExecutableSnapshot,
- runtime: &RuntimeInfo,
+pub fn dump_code<'a>(
+ graph: &'a Graph<'a>,
+ executable: &'a ExecutableSnapshot,
+ runtime: &'a RuntimeInfo,
architecture: Architecture,
- code: &[u8],
- generated: &GeneratedCode,
- artifact: Artifact<'_>,
-) -> String {
- use std::fmt::Write;
-
- let helpers = [
- (runtime.jit_call, "libjs_jit_call"),
- (runtime.jit_exit, "libjs_jit_exit"),
- (runtime.finish_direct_call, "libjs_jit_finish_direct_call"),
- (runtime.to_boolean, "asm_helper_to_boolean"),
- (runtime.heap_region_base, "js_heap_region_base"),
- ];
- let symbol = |bits: u64| {
- if bits == 0 {
- return None;
- }
- if let Some((_, symbol)) = helpers.iter().find(|(address, _)| *address == bits) {
- return Some(symbol.to_string());
+ code: &'a [u8],
+ generated: &'a GeneratedCode<'a>,
+ artifact: Artifact<'a>,
+) -> CodeDump<'a> {
+ CodeDump {
+ graph,
+ executable,
+ runtime,
+ architecture,
+ code,
+ generated,
+ artifact,
+ }
+}
+
+/// The text of `dump_code()`.
+pub struct CodeDump<'a> {
+ graph: &'a Graph<'a>,
+ executable: &'a ExecutableSnapshot,
+ runtime: &'a RuntimeInfo,
+ architecture: Architecture,
+ code: &'a [u8],
+ generated: &'a GeneratedCode<'a>,
+ artifact: Artifact<'a>,
+}
+
+/// What a constant in code is, if the dump of the code names it.
+enum ConstantName {
+ Helper(&'static str),
+ SlowPath(SlowPathSymbol),
+ /// An address in the bytecode of the executable, at this offset.
+ Bytecode(u64),
+ Value(value::Description),
+}
+
+impl core::fmt::Display for ConstantName {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ match self {
+ Self::Helper(symbol) => f.write_str(symbol),
+ Self::SlowPath(symbol) => write!(f, "{symbol}"),
+ Self::Bytecode(offset) => write!(f, "bytecode @{offset}"),
+ Self::Value(description) => write!(f, "{description}"),
}
- runtime
- .slow_paths
- .iter()
- .enumerate()
- .filter(|(_, address)| **address == bits)
- .find_map(|(index, _)| {
- u8::try_from(index)
- .ok()
- .and_then(OpCode::from_u8)
- .and_then(slow_path_symbol)
- })
- };
- let describe_constant = |bits: u64| {
- if let Some(symbol) = symbol(bits) {
- return Some(symbol);
+ }
+}
+
+impl CodeDump<'_> {
+ fn name_constant(&self, bits: u64) -> Option<ConstantName> {
+ let (runtime, executable) = (self.runtime, self.executable);
+ if bits != 0 {
+ let helpers = [
+ (runtime.jit_call, "libjs_jit_call"),
+ (runtime.jit_exit, "libjs_jit_exit"),
+ (runtime.finish_direct_call, "libjs_jit_finish_direct_call"),
+ (runtime.to_boolean, "asm_helper_to_boolean"),
+ (runtime.heap_region_base, "js_heap_region_base"),
+ ];
+ if let Some((_, symbol)) = helpers.iter().find(|(address, _)| *address == bits) {
+ return Some(ConstantName::Helper(symbol));
+ }
+ let slow_path = runtime
+ .slow_paths
+ .iter()
+ .enumerate()
+ .filter(|(_, address)| **address == bits)
+ .find_map(|(index, _)| {
+ u8::try_from(index)
+ .ok()
+ .and_then(OpCode::from_u8)
+ .and_then(slow_path_symbol)
+ });
+ if let Some(symbol) = slow_path {
+ return Some(ConstantName::SlowPath(symbol));
+ }
}
let bytecode_end = executable.bytecode_address + executable.bytecode.len() as u64;
if (executable.bytecode_address..bytecode_end).contains(&bits) {
- return Some(format!("bytecode @{}", bits - executable.bytecode_address));
+ return Some(ConstantName::Bytecode(bits - executable.bytecode_address));
}
let description = value::describe(bits);
- (!description.starts_with("0x")).then_some(description)
- };
+ description.is_known_value().then_some(ConstantName::Value(description))
+ }
+
+ fn write_annotation(&self, f: &mut core::fmt::Formatter<'_>, annotation: &CodeAnnotation) -> core::fmt::Result {
+ let (graph, layout) = (self.graph, &self.executable.layout);
+ match annotation {
+ CodeAnnotation::Prologue => f.write_str("prologue:\n"),
+ CodeAnnotation::Block(block) => writeln!(f, "b{}:", block.0),
+ CodeAnnotation::Node(node) => writeln!(f, " {}", ir::node_text(graph, layout, *node)),
+ CodeAnnotation::BlockEndMoves => f.write_str(" block end moves\n"),
+ CodeAnnotation::Deferred(node) => writeln!(f, "deferred code of {}", ir::node_text(graph, layout, *node)),
+ CodeAnnotation::Tail(name) => writeln!(f, "{name}:"),
+ CodeAnnotation::Exit { index, node } => match self.artifact.site(*index).kind() {
+ SiteKind::Exit(kind) => writeln!(f, " exit #{index} ({kind:?}) of v{}:", node.0),
+ kind => writeln!(f, " exit #{index} ({kind:?}) of v{}:", node.0),
+ },
+ }
+ }
+}
- let mut annotations = generated.annotations.iter().peekable();
- let layout = &executable.layout;
- let mut out = String::new();
- let mut instruction_count = 0;
- disassembler::for_each_instruction(architecture, code, generated.data_offset as usize, |instruction| {
- instruction_count += 1;
- while let Some((_, annotation)) = annotations.next_if(|(offset, _)| *offset as usize <= instruction.offset) {
- match annotation {
- CodeAnnotation::Prologue => out.push_str("prologue:\n"),
- CodeAnnotation::Block(block) => writeln!(out, "b{}:", block.0).unwrap(),
- CodeAnnotation::Node(node) => {
- writeln!(out, " {}", ir::node_text(graph, layout, *node)).unwrap();
+impl core::fmt::Display for CodeDump<'_> {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ let generated = self.generated;
+ let mut annotations = generated.annotations.iter().peekable();
+ let mut instruction_count = 0;
+ let mut result = Ok(());
+ disassembler::for_each_instruction(
+ self.architecture,
+ self.code,
+ generated.data_offset as usize,
+ |instruction| {
+ instruction_count += 1;
+ if result.is_err() {
+ return;
}
- CodeAnnotation::BlockEndMoves => out.push_str(" block end moves\n"),
- CodeAnnotation::Deferred(node) => {
- writeln!(out, "deferred code of {}", ir::node_text(graph, layout, *node)).unwrap();
- }
- CodeAnnotation::Tail(name) => writeln!(out, "{name}:").unwrap(),
- CodeAnnotation::Exit { index, node } => {
- let kind = match artifact.site(*index).kind() {
- SiteKind::Exit(kind) => format!("{kind:?}"),
- kind => format!("{kind:?}"),
- };
- writeln!(out, " exit #{index} ({kind}) of v{}:", node.0).unwrap();
- }
- }
- }
- write!(out, " {:06x} {}", instruction.offset, instruction.text).unwrap();
- if let Some(description) = instruction.constant.and_then(describe_constant) {
- write!(out, " ; {description}").unwrap();
- }
- out.push('\n');
- });
- let count = |kind: fn(SiteKind) -> bool| artifact.sites().filter(|site| kind(site.kind())).count();
- writeln!(
- out,
- "{} instructions, {} bytes, {} exits, {} leaves, {} publish sites, {} call sites",
- instruction_count,
- code.len(),
- count(|kind| matches!(kind, SiteKind::Exit(_))),
- count(|kind| kind == SiteKind::Leave),
- count(|kind| kind == SiteKind::Publish),
- count(|kind| kind == SiteKind::Call),
- )
- .unwrap();
- out
+ result = (|| {
+ while let Some((_, annotation)) =
+ annotations.next_if(|(offset, _)| *offset as usize <= instruction.offset)
+ {
+ self.write_annotation(f, annotation)?;
+ }
+ write!(f, " {:06x} {}", instruction.offset, instruction.text)?;
+ if let Some(name) = instruction.constant.and_then(|bits| self.name_constant(bits)) {
+ write!(f, " ; {name}")?;
+ }
+ f.write_str("\n")
+ })();
+ },
+ );
+ result?;
+ let artifact = self.artifact;
+ let count = |kind: fn(SiteKind) -> bool| artifact.sites().filter(|site| kind(site.kind())).count();
+ writeln!(
+ f,
+ "{} instructions, {} bytes, {} exits, {} leaves, {} publish sites, {} call sites",
+ instruction_count,
+ self.code.len(),
+ count(|kind| matches!(kind, SiteKind::Exit(_))),
+ count(|kind| kind == SiteKind::Leave),
+ count(|kind| kind == SiteKind::Publish),
+ count(|kind| kind == SiteKind::Call),
+ )
+ }
}
/// For a block that ends in a cache probe and a branch on its result, where
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path.rs b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path.rs
index 5b42e9e99ec..2af45cbbb28 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/slow_path.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/slow_path.rs
@@ -11,6 +11,9 @@
//! holds their addresses, indexed by opcode; `slow_path_symbol()` names the
//! function the runtime must put there for each opcode.
+use core::fmt;
+use core::fmt::Write;
+
use crate::builder::handling;
use crate::bytecode::Instruction;
use crate::bytecode::OpCode;
@@ -104,20 +107,9 @@ fn is_binary_values_opcode(opcode: OpCode) -> bool {
)
}
-fn snake_case(name: &str) -> String {
- let mut result = String::new();
- for (index, character) in name.chars().enumerate() {
- if character.is_ascii_uppercase() && index != 0 {
- result.push('_');
- }
- result.push(character.to_ascii_lowercase());
- }
- result
-}
-
/// The C function the runtime must store in `RuntimeInfo::slow_paths` for
/// `opcode`, or `None` if JIT code never calls one for it.
-pub fn slow_path_symbol(opcode: OpCode) -> Option<String> {
+pub fn slow_path_symbol(opcode: OpCode) -> Option<SlowPathSymbol> {
let name = opcode.name();
let base = name
.strip_suffix("RhsInt32")
@@ -127,21 +119,71 @@ pub fn slow_path_symbol(opcode: OpCode) -> Option<String> {
let base = base.strip_suffix("Loop").unwrap_or(base);
Some(match slow_path_call(opcode)? {
SlowPathCall::JitCall => return None,
- SlowPathCall::JumpValues => format!("asm_slow_path_{}_values", snake_case(base)),
- SlowPathCall::BinaryValues => format!("asm_slow_path_{}_values", snake_case(base)),
+ SlowPathCall::JumpValues | SlowPathCall::BinaryValues => SlowPathSymbol::Values(base),
SlowPathCall::Record => match opcode {
- OpCode::ThrowIfTDZ => "asm_slow_path_throw_if_tdz".to_string(),
- OpCode::GetCalleeAndThisFromEnvironment => "asm_slow_path_get_callee_and_this".to_string(),
- OpCode::DynamicGetCalleeAndThisFromEnvironment => "asm_slow_path_dynamic_get_callee_and_this".to_string(),
- OpCode::NewRegExp => "asm_slow_path_new_regexp".to_string(),
- OpCode::GetById => "asm_slow_path_get_by_id_from_jit".to_string(),
- OpCode::GetByValue => "asm_slow_path_get_by_value_from_jit".to_string(),
- OpCode::PutByValue => "asm_slow_path_put_by_value_from_jit".to_string(),
- _ => format!("asm_slow_path_{}", snake_case(name)).replace("_reg_exp_", "_regexp_"),
+ OpCode::ThrowIfTDZ => SlowPathSymbol::Named("asm_slow_path_throw_if_tdz"),
+ OpCode::GetCalleeAndThisFromEnvironment => SlowPathSymbol::Named("asm_slow_path_get_callee_and_this"),
+ OpCode::DynamicGetCalleeAndThisFromEnvironment => {
+ SlowPathSymbol::Named("asm_slow_path_dynamic_get_callee_and_this")
+ }
+ OpCode::NewRegExp => SlowPathSymbol::Named("asm_slow_path_new_regexp"),
+ OpCode::GetById => SlowPathSymbol::Named("asm_slow_path_get_by_id_from_jit"),
+ OpCode::GetByValue => SlowPathSymbol::Named("asm_slow_path_get_by_value_from_jit"),
+ OpCode::PutByValue => SlowPathSymbol::Named("asm_slow_path_put_by_value_from_jit"),
+ _ => SlowPathSymbol::Record(name),
},
})
}
+/// The name of the C function of a slow path (see `slow_path_symbol()`).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum SlowPathSymbol {
+ /// The slow path that takes the values of the instructions named `base` in its operands.
+ Values(&'static str),
+ /// The slow path that takes the record of the instruction named so.
+ Record(&'static str),
+ Named(&'static str),
+}
+
+impl fmt::Display for SlowPathSymbol {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match *self {
+ Self::Values(base) => {
+ f.write_str("asm_slow_path_")?;
+ write_snake_case(f, base, false)?;
+ f.write_str("_values")
+ }
+ Self::Record(name) => {
+ f.write_str("asm_slow_path_")?;
+ write_snake_case(f, name, true)
+ }
+ Self::Named(symbol) => f.write_str(symbol),
+ }
+ }
+}
+
+/// Writes `name`, which is in CamelCase, in snake_case. With `regexp_as_one_word`, "RegExp" followed by another word
+/// is one word: "regexp".
+fn write_snake_case(f: &mut fmt::Formatter<'_>, name: &str, regexp_as_one_word: bool) -> fmt::Result {
+ let mut rest = name;
+ while let Some(character) = rest.chars().next() {
+ if character.is_ascii_uppercase() && rest.len() != name.len() {
+ f.write_char('_')?;
+ }
+ if let Some(after) = rest.strip_prefix("RegExp")
+ && regexp_as_one_word
+ && after.starts_with(|next: char| next.is_ascii_uppercase())
+ {
+ f.write_str("regexp")?;
+ rest = after;
+ continue;
+ }
+ f.write_char(character.to_ascii_lowercase())?;
+ rest = &rest[character.len_utf8()..];
+ }
+ Ok(())
+}
+
/// The destination and operands of a binary slow path call.
pub fn binary_operands(instruction: &Instruction) -> Option<(Operand, ValueSource, ValueSource)> {
use Instruction as I;
@@ -432,6 +474,31 @@ mod tests {
use super::*;
use crate::bytecode::NUM_OPCODES;
+ /// The symbol of the slow path of `opcode`, made from its name with string operations.
+ fn symbol_by_strings(opcode: OpCode) -> String {
+ let snake_case = |name: &str| {
+ let mut result = String::new();
+ for (index, character) in name.chars().enumerate() {
+ if character.is_ascii_uppercase() && index != 0 {
+ result.push('_');
+ }
+ result.push(character.to_ascii_lowercase());
+ }
+ result
+ };
+ let name = opcode.name();
+ let base = name
+ .strip_suffix("RhsInt32")
+ .or_else(|| name.strip_suffix("LhsInt32"))
+ .unwrap_or(name);
+ let base = base.strip_suffix("Loop").unwrap_or(base);
+ match slow_path_symbol(opcode).unwrap() {
+ SlowPathSymbol::Values(_) => format!("asm_slow_path_{}_values", snake_case(base)),
+ SlowPathSymbol::Record(_) => format!("asm_slow_path_{}", snake_case(name)).replace("_reg_exp_", "_regexp_"),
+ SlowPathSymbol::Named(symbol) => symbol.to_string(),
+ }
+ }
+
#[test]
fn every_generic_opcode_has_a_slow_path() {
for value in 0..NUM_OPCODES {
@@ -441,25 +508,32 @@ mod tests {
};
let symbol = slow_path_symbol(opcode);
assert_eq!(symbol.is_none(), call == SlowPathCall::JitCall, "{}", opcode.name());
+ if let Some(symbol) = symbol {
+ assert_eq!(symbol.to_string(), symbol_by_strings(opcode), "{}", opcode.name());
+ }
}
assert_eq!(
- slow_path_symbol(OpCode::JumpLessThanEqualsRhsInt32).unwrap(),
+ slow_path_symbol(OpCode::JumpLessThanEqualsRhsInt32)
+ .unwrap()
+ .to_string(),
"asm_slow_path_jump_less_than_equals_values"
);
assert_eq!(
- slow_path_symbol(OpCode::JumpLessThanEqualsLoopRhsInt32).unwrap(),
+ slow_path_symbol(OpCode::JumpLessThanEqualsLoopRhsInt32)
+ .unwrap()
+ .to_string(),
"asm_slow_path_jump_less_than_equals_values"
);
assert_eq!(
- slow_path_symbol(OpCode::AddLhsInt32).unwrap(),
+ slow_path_symbol(OpCode::AddLhsInt32).unwrap().to_string(),
"asm_slow_path_add_values"
);
assert_eq!(
- slow_path_symbol(OpCode::GetById).unwrap(),
+ slow_path_symbol(OpCode::GetById).unwrap().to_string(),
"asm_slow_path_get_by_id_from_jit"
);
assert_eq!(
- slow_path_symbol(OpCode::ThrowIfTDZ).unwrap(),
+ slow_path_symbol(OpCode::ThrowIfTDZ).unwrap().to_string(),
"asm_slow_path_throw_if_tdz"
);
}
diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
index c381b501812..cd424403dcd 100644
--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests.rs
@@ -2461,7 +2461,7 @@ fn aarch64_code_disassembles() {
&mut crate::scratch::Scratch::new(),
)
.unwrap();
- for dump in [x86_64.dump.unwrap(), aarch64.dump.unwrap()] {
+ for dump in [x86_64.dump().unwrap(), aarch64.dump().unwrap()] {
assert!(dump.contains("Exit NoFeedback [fs"), "{dump}");
assert!(dump.contains("exit #0 (NoFeedback) of v"), "{dump}");
assert!(dump.contains("exit stub (shared by all exits):\n"), "{dump}");
@@ -2524,7 +2524,7 @@ fn slow_paths_share_initialization_of_large_frames() {
);
assert_eq!(
compiled
- .dump
+ .dump()
.unwrap()
.matches("frame initialization (shared by slow paths):\n")
.count(),
@@ -2597,7 +2597,7 @@ fn dumps_ir_and_code_on_request() {
snapshot.options.dump_asm = true;
let compiled =
compile_for::<crate::asm::MacroAssembler>(&snapshot, &|_| true, &mut crate::scratch::Scratch::new()).unwrap();
- let dump = compiled.dump.unwrap();
+ let dump = compiled.dump().unwrap();
assert!(dump.contains("LoadSlot a0"), "{dump}");
assert!(dump.contains("prologue:"), "{dump}");
assert!(dump.contains("Return (v"), "{dump}");
diff --git a/Libraries/LibJS/JIT/Rust/src/coverage.rs b/Libraries/LibJS/JIT/Rust/src/coverage.rs
index 5e158a44112..70b97cb1ee2 100644
--- a/Libraries/LibJS/JIT/Rust/src/coverage.rs
+++ b/Libraries/LibJS/JIT/Rust/src/coverage.rs
@@ -10,27 +10,28 @@
//! "Int32Binary.Add", "LoadElementAt.TypedArray(Int8)" or "CallSlowPath.GetById",
//! and one key per place compiled code may exit, like "exit-site.BadShape".
+use core::fmt;
+
use crate::ir::BranchCondition;
use crate::ir::Graph;
use crate::ir::Op;
-/// The coverage keys of the nodes of `graph` that made it into the code.
-pub fn coverage_keys(graph: &Graph) -> Vec<String> {
- let mut keys = Vec::new();
+/// Writes the coverage keys of the nodes of `graph` that made it into the code to `out`, one on each line.
+pub fn write_coverage_keys(graph: &Graph, out: &mut dyn fmt::Write) -> fmt::Result {
for block in &graph.blocks {
for node in block.nodes() {
let op = &graph.node(node).op;
- keys.push(op_key(op));
+ writeln!(out, "{}", OpKey(op))?;
if let Some(kind) = op.exit_kind() {
- keys.push(format!("exit-site.{kind:?}"));
+ writeln!(out, "exit-site.{kind:?}")?;
}
}
}
if graph.blocks.iter().any(|block| block.is_loop_header) {
- keys.push("graph.loop".to_string());
+ writeln!(out, "graph.loop")?;
}
if !graph.osr_entries.is_empty() {
- keys.push("graph.osr-entry".to_string());
+ writeln!(out, "graph.osr-entry")?;
}
let inlined_depth = graph
.frame_states
@@ -40,39 +41,67 @@ pub fn coverage_keys(graph: &Graph) -> Vec<String> {
.max()
.unwrap_or(0);
if inlined_depth > 1 {
- keys.push(format!("graph.inlined-depth.{}", (inlined_depth - 1).min(5)));
+ writeln!(out, "graph.inlined-depth.{}", (inlined_depth - 1).min(5))?;
}
- keys
+ Ok(())
}
-fn op_key(op: &Op) -> String {
- let name = op.name();
- match op {
- Op::Int32Binary { op } | Op::Int32WrappingBinary { op } => format!("{name}.{op:?}"),
- Op::Int32Compare { comparison } => format!("{name}.{comparison:?}"),
- Op::CheckElements { kind } | Op::LoadElementAt { kind } | Op::StoreElementAt { kind } => {
- format!("{name}.{kind:?}")
+/// The coverage key of an op.
+struct OpKey<'a, 'z>(&'a Op<'z>);
+
+impl fmt::Display for OpKey<'_, '_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let op = self.0;
+ let name = op.name();
+ match op {
+ Op::Int32Binary { op } | Op::Int32WrappingBinary { op } => write!(f, "{name}.{op:?}"),
+ Op::Int32Compare { comparison } => write!(f, "{name}.{comparison:?}"),
+ Op::CheckElements { kind } | Op::LoadElementAt { kind } | Op::StoreElementAt { kind } => {
+ write!(f, "{name}.{kind:?}")
+ }
+ Op::Generic { opcode, .. } | Op::CallSlowPath { opcode, .. } => {
+ write!(f, "{name}.{}", opcode.name())
+ }
+ Op::Exit { kind } | Op::CheckValue { kind, .. } => write!(f, "{name}.{kind:?}"),
+ Op::TypeofIs { kind, .. } => write!(f, "{name}.{kind:?}"),
+ Op::Branch { condition, .. } => match condition {
+ BranchCondition::Int32(comparison) => write!(f, "{name}.Int32.{comparison:?}"),
+ // NB: The key names the condition, not what else it holds
+ // (like identifiers or binding indices).
+ other => {
+ write!(f, "{name}.")?;
+ let mut first_word = FirstWord { out: f, done: false };
+ fmt::Write::write_fmt(&mut first_word, format_args!("{other:?}"))
+ }
+ },
+ Op::TaggedEquals { equal } => write!(f, "{name}.{}", if *equal { "Equal" } else { "NotEqual" }),
+ Op::CheckShape { shapes } => write!(
+ f,
+ "{name}.{}",
+ if shapes.len() > 1 { "Polymorphic" } else { "Monomorphic" }
+ ),
+ _ => f.write_str(name),
}
- Op::Generic { opcode, .. } | Op::CallSlowPath { opcode, .. } => {
- format!("{name}.{}", opcode.name())
+ }
+}
+
+/// Passes text on up to the first `(`, ` ` or `{`, and drops the rest.
+struct FirstWord<'a, 'b> {
+ out: &'a mut fmt::Formatter<'b>,
+ done: bool,
+}
+
+impl fmt::Write for FirstWord<'_, '_> {
+ fn write_str(&mut self, text: &str) -> fmt::Result {
+ if self.done {
+ return Ok(());
}
- Op::Exit { kind } | Op::CheckValue { kind, .. } => format!("{name}.{kind:?}"),
- Op::TypeofIs { kind, .. } => format!("{name}.{kind:?}"),
- Op::Branch { condition, .. } => match condition {
- BranchCondition::Int32(comparison) => format!("{name}.Int32.{comparison:?}"),
- // NB: The key names the condition, not what else it holds
- // (like identifiers or binding indices).
- other => {
- let condition = format!("{other:?}");
- let kind = condition.split(['(', ' ', '{']).next().unwrap_or_default();
- format!("{name}.{kind}")
+ match text.find(['(', ' ', '{']) {
+ Some(end) => {
+ self.done = true;
+ self.out.write_str(&text[..end])
}
- },
- Op::TaggedEquals { equal } => format!("{name}.{}", if *equal { "Equal" } else { "NotEqual" }),
- Op::CheckShape { shapes } => format!(
- "{name}.{}",
- if shapes.len() > 1 { "Polymorphic" } else { "Monomorphic" }
- ),
- _ => name.to_string(),
+ None => self.out.write_str(text),
+ }
}
}
diff --git a/Libraries/LibJS/JIT/Rust/src/debug_text.rs b/Libraries/LibJS/JIT/Rust/src/debug_text.rs
new file mode 100644
index 00000000000..e1e5d1ef7e9
--- /dev/null
+++ b/Libraries/LibJS/JIT/Rust/src/debug_text.rs
@@ -0,0 +1,242 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The text of a debug dump or of an error that a verifier found, with its bytes in a zone.
+
+use core::fmt;
+use core::ops::Deref;
+
+use ak::Zone;
+use ak::ZoneVec;
+
+/// Text for a person to read: a debug dump, or what a verifier found. It grows in a zone (see `ak::Zone`), so it makes
+/// no block of the heap.
+///
+/// NB: This is not a string of the engine, and no string of a script is kept in one. It is UTF-8 because its text
+/// comes from the formatting of Rust (`write!`, `Display`, `Debug`), which gives UTF-8, and goes to the terminal.
+///
+/// `write!` and `writeln!` add formatted text to it and give no result to check, because adding to it cannot fail:
+///
+/// ```ignore
+/// let mut text = DebugText::new_in(&zone);
+/// write!(text, "v{} = {}", 1, "Add");
+/// ```
+pub struct DebugText<'zone> {
+ // NB: The bytes are UTF-8 at all times: text goes in as whole `str`s and `char`s, and comes out at the
+ // boundaries of characters only.
+ bytes: ZoneVec<'zone, u8>,
+}
+
+impl<'zone> DebugText<'zone> {
+ /// A text with no characters, which takes no memory of the zone before it gets one.
+ pub fn new_in(zone: &'zone Zone) -> Self {
+ Self {
+ bytes: ZoneVec::new_in(zone),
+ }
+ }
+
+ /// A text with no characters and room for `capacity` bytes.
+ pub fn with_capacity_in(capacity: usize, zone: &'zone Zone) -> Self {
+ Self {
+ bytes: ZoneVec::with_capacity_in(capacity, zone),
+ }
+ }
+
+ /// A copy of `text`.
+ pub fn from_str_in(text: &str, zone: &'zone Zone) -> Self {
+ Self {
+ bytes: ZoneVec::from_slice_in(text.as_bytes(), zone),
+ }
+ }
+
+ pub fn zone(&self) -> &'zone Zone {
+ self.bytes.zone()
+ }
+
+ /// The length in bytes.
+ pub fn len(&self) -> usize {
+ self.bytes.len()
+ }
+
+ pub fn is_empty(&self) -> bool {
+ self.bytes.is_empty()
+ }
+
+ pub fn as_str(&self) -> &str {
+ // SAFETY: The bytes are UTF-8 (see the field).
+ unsafe { core::str::from_utf8_unchecked(&self.bytes) }
+ }
+
+ /// The text as it is now, for as long as the zone holds it. This copies nothing.
+ pub fn into_str(self) -> &'zone str {
+ // SAFETY: The bytes are UTF-8 (see the field).
+ unsafe { core::str::from_utf8_unchecked(self.bytes.into_slice()) }
+ }
+
+ pub fn push(&mut self, character: char) {
+ self.push_str(character.encode_utf8(&mut [0; 4]));
+ }
+
+ pub fn push_str(&mut self, text: &str) {
+ self.bytes.extend_from_slice(text.as_bytes());
+ }
+
+ /// Adds formatted text. This is what `write!` and `writeln!` call.
+ pub fn write_fmt(&mut self, arguments: fmt::Arguments<'_>) {
+ // NB: `write_str()` does not fail, so this fails only if a `Display` or `Debug` implementation reports an
+ // error of its own, which is a bug of that implementation, as it is for `format!`.
+ fmt::Write::write_fmt(self, arguments).expect("a formatting trait implementation returned an error");
+ }
+
+ /// Removes the last character and returns it.
+ pub fn pop(&mut self) -> Option<char> {
+ let character = self.as_str().chars().next_back()?;
+ self.bytes.truncate(self.len() - character.len_utf8());
+ Some(character)
+ }
+
+ /// Keeps the first `len` bytes, which must end at the boundary of a character. Does nothing if the text is not
+ /// longer than that.
+ pub fn truncate(&mut self, len: usize) {
+ if len < self.len() {
+ assert!(
+ self.as_str().is_char_boundary(len),
+ "a text ends at the boundary of a character"
+ );
+ self.bytes.truncate(len);
+ }
+ }
+
+ /// Removes all characters and keeps the memory.
+ pub fn clear(&mut self) {
+ self.bytes.clear();
+ }
+}
+
+impl fmt::Write for DebugText<'_> {
+ fn write_str(&mut self, text: &str) -> fmt::Result {
+ self.push_str(text);
+ Ok(())
+ }
+
+ fn write_char(&mut self, character: char) -> fmt::Result {
+ self.push(character);
+ Ok(())
+ }
+}
+
+impl Deref for DebugText<'_> {
+ type Target = str;
+
+ fn deref(&self) -> &str {
+ self.as_str()
+ }
+}
+
+impl AsRef<str> for DebugText<'_> {
+ fn as_ref(&self) -> &str {
+ self.as_str()
+ }
+}
+
+impl fmt::Display for DebugText<'_> {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ fmt::Display::fmt(self.as_str(), formatter)
+ }
+}
+
+impl fmt::Debug for DebugText<'_> {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ fmt::Debug::fmt(self.as_str(), formatter)
+ }
+}
+
+impl PartialEq for DebugText<'_> {
+ fn eq(&self, other: &Self) -> bool {
+ self.as_str() == other.as_str()
+ }
+}
+
+impl Eq for DebugText<'_> {}
+
+impl PartialEq<str> for DebugText<'_> {
+ fn eq(&self, other: &str) -> bool {
+ self.as_str() == other
+ }
+}
+
+impl PartialEq<&str> for DebugText<'_> {
+ fn eq(&self, other: &&str) -> bool {
+ self.as_str() == *other
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn text_grows_by_characters_strings_and_formatted_values() {
+ let zone = Zone::new(1 << 20, c"test");
+ let mut text = DebugText::new_in(&zone);
+ assert!(text.is_empty());
+ assert_eq!(zone.used(), 0);
+ text.push('v');
+ text.push_str("1 = ");
+ let name = "Add";
+ write!(text, "{name} ({:>4}, {:#x})", 7, 255);
+ writeln!(text);
+ assert_eq!(text, "v1 = Add ( 7, 0xff)\n");
+ assert_eq!(text.len(), 22);
+ assert_eq!(text.lines().next(), Some("v1 = Add ( 7, 0xff)"));
+ assert_eq!(
+ format!("{text}{text:?}"),
+ "v1 = Add ( 7, 0xff)\n\"v1 = Add ( 7, 0xff)\\n\""
+ );
+ }
+
+ #[test]
+ fn text_ends_at_the_boundaries_of_characters() {
+ let zone = Zone::new(1 << 20, c"test");
+ let mut text = DebugText::from_str_in("aä€😀", &zone);
+ assert_eq!(text.len(), 10);
+ assert_eq!(text.pop(), Some('😀'));
+ assert_eq!(text.pop(), Some('€'));
+ assert_eq!(text, "aä");
+ text.truncate(8);
+ assert_eq!(text, "aä");
+ text.truncate(1);
+ assert_eq!(text, "a");
+ text.clear();
+ assert_eq!(text.pop(), None);
+ assert_eq!(text, "");
+ }
+
+ #[test]
+ #[should_panic(expected = "boundary of a character")]
+ fn text_cannot_end_inside_a_character() {
+ let zone = Zone::new(1 << 20, c"test");
+ let mut text = DebugText::from_str_in("ä", &zone);
+ text.truncate(1);
+ }
+
+ #[test]
+ fn text_keeps_its_bytes_when_it_moves_in_the_zone() {
+ let zone = Zone::new(1 << 20, c"test");
+ let mut text = DebugText::with_capacity_in(4, &zone);
+ text.push_str("abcd");
+ // NB: Something else is now the last thing that the zone gave out, so the text must move to grow.
+ let other = zone.alloc(7u64);
+ for index in 0..100 {
+ write!(text, "{index},");
+ }
+ assert_eq!(*other, 7);
+ assert!(text.starts_with("abcd0,1,2,"));
+ assert!(text.ends_with(",98,99,"));
+ let frozen: &str = text.into_str();
+ assert_eq!(frozen.len(), 4 + 2 * 10 + 3 * 90);
+ }
+}
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
index aed167c37fa..ebfd93a3cda 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/dump.rs
@@ -20,39 +20,72 @@ use crate::bytecode::Operand;
use crate::bytecode::SlotKind;
use crate::code::Repr;
use crate::code::ResumeMode;
-use std::fmt::Write;
+use core::fmt;
/// The name of a frame slot, like the bytecode disassembler prints operands.
-pub fn slot_name(layout: &FrameLayout, slot: u32) -> String {
- match layout.slot_kind(Operand::from_raw(slot)) {
- SlotKind::Register(index) => format!("r{index}"),
- SlotKind::Local(index) => format!("l{index}"),
- SlotKind::Constant(index) => format!("c{index}"),
- SlotKind::Argument(index) => format!("a{index}"),
+pub fn slot_name(layout: &FrameLayout, slot: u32) -> SlotName {
+ SlotName(layout.slot_kind(Operand::from_raw(slot)))
+}
+
+/// The text of `slot_name()`.
+#[derive(Clone, Copy)]
+pub struct SlotName(SlotKind);
+
+impl fmt::Display for SlotName {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self.0 {
+ SlotKind::Register(index) => write!(f, "r{index}"),
+ SlotKind::Local(index) => write!(f, "l{index}"),
+ SlotKind::Constant(index) => write!(f, "c{index}"),
+ SlotKind::Argument(index) => write!(f, "a{index}"),
+ }
}
}
-/// `text` with `item` after it, and a comma between the two if `text` is not empty.
-fn join(mut text: String, item: String) -> String {
- if !text.is_empty() {
- text.push_str(", ");
+/// Writes the text of each item, with ", " between them.
+fn write_joined<T>(
+ f: &mut fmt::Formatter<'_>,
+ items: impl IntoIterator<Item = T>,
+ mut write_item: impl FnMut(&mut fmt::Formatter<'_>, T) -> fmt::Result,
+) -> fmt::Result {
+ for (index, item) in items.into_iter().enumerate() {
+ if index != 0 {
+ f.write_str(", ")?;
+ }
+ write_item(f, item)?;
}
- text.push_str(&item);
- text
+ Ok(())
}
-fn value_name(graph: &Graph, id: NodeId) -> String {
- match (graph.constant_value(id), graph.node(id).repr) {
- (Some(bits), Some(Repr::Int32)) => format!("#i32:{}", (bits as u32).cast_signed()),
- (Some(bits), Some(Repr::Bool)) => format!("#bool:{}", bits != 0),
- (Some(bits), Some(Repr::Pointer)) => format!("#pointer:{bits:#x}"),
- (Some(bits), _) => format!("#{}", value::describe(bits)),
- (None, _) => format!("v{}", id.0),
+/// The name of a value: its node, or the constant it is.
+struct ValueName<'a, 'z> {
+ graph: &'a Graph<'z>,
+ id: NodeId,
+}
+
+fn value_name<'a, 'z>(graph: &'a Graph<'z>, id: NodeId) -> ValueName<'a, 'z> {
+ ValueName { graph, id }
+}
+
+impl fmt::Display for ValueName<'_, '_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let (graph, id) = (self.graph, self.id);
+ match (graph.constant_value(id), graph.node(id).repr) {
+ (Some(bits), Some(Repr::Int32)) => write!(f, "#i32:{}", (bits as u32).cast_signed()),
+ (Some(bits), Some(Repr::Bool)) => write!(f, "#bool:{}", bits != 0),
+ (Some(bits), Some(Repr::Pointer)) => write!(f, "#pointer:{bits:#x}"),
+ (Some(bits), _) => write!(f, "#{}", value::describe(bits)),
+ (None, _) => write!(f, "v{}", id.0),
+ }
}
}
-fn block_name(block: BlockId) -> String {
- format!("b{}", block.0)
+struct BlockName(BlockId);
+
+impl fmt::Display for BlockName {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(f, "b{}", self.0.0)
+ }
}
fn repr_name(repr: Repr) -> &'static str {
@@ -65,120 +98,180 @@ fn repr_name(repr: Repr) -> &'static str {
}
}
-fn shapes_text<'a>(shapes: impl Iterator<Item = &'a ShapeCheck>) -> String {
- shapes
- .map(|shape| match shape.dictionary_generation {
- Some(generation) => format!("{:#x}@{generation}", shape.shape.0),
- None => format!("{:#x}", shape.shape.0),
- })
- .fold(String::new(), join)
+fn write_shapes(f: &mut fmt::Formatter<'_>, shapes: &[ShapeCheck]) -> fmt::Result {
+ write_joined(f, shapes, |f, shape| match shape.dictionary_generation {
+ Some(generation) => write!(f, "{:#x}@{generation}", shape.shape.0),
+ None => write!(f, "{:#x}", shape.shape.0),
+ })
}
-fn condition_text(condition: BranchCondition) -> String {
- match condition {
- BranchCondition::Bool => "Bool".to_string(),
- BranchCondition::Nullish => "Nullish".to_string(),
- BranchCondition::Undefined => "Undefined".to_string(),
- BranchCondition::Object => "Object".to_string(),
- BranchCondition::ElementsKind(kind) => format!("ElementsKind {kind:?}"),
- BranchCondition::IndexInBounds => "IndexInBounds".to_string(),
- BranchCondition::MagicalLength => "MagicalLength".to_string(),
- BranchCondition::Extensible => "Extensible".to_string(),
- BranchCondition::HoleFillableArray => "HoleFillableArray".to_string(),
- BranchCondition::ArrayIterator => "ArrayIterator".to_string(),
- BranchCondition::GeneratorObject => "GeneratorObject".to_string(),
- BranchCondition::PlainArrayPrototypeChain => "PlainArrayPrototypeChain".to_string(),
- BranchCondition::ArrayWithRealmArrayPrototypeAndNoNamedProperties => {
- "ArrayWithRealmArrayPrototypeAndNoNamedProperties".to_string()
- }
- BranchCondition::HoldsValidWatchpointSet => "HoldsValidWatchpointSet".to_string(),
- BranchCondition::Shape(shape) => format!("Shape {}", shapes_text(std::iter::once(&shape))),
- BranchCondition::NonNegativeInt32 => "NonNegativeInt32".to_string(),
- BranchCondition::Int32(comparison) => format!("Int32{comparison:?}"),
- BranchCondition::Float64(comparison) => format!("Float64{comparison:?}"),
- BranchCondition::TaggedEquals { equal: true } => "TaggedEquals".to_string(),
- BranchCondition::TaggedEquals { equal: false } => "TaggedNotEquals".to_string(),
- BranchCondition::Int32Value => "Int32Value".to_string(),
- BranchCondition::Int32OrBoolean => "Int32OrBoolean".to_string(),
- BranchCondition::Double => "Double".to_string(),
- BranchCondition::String => "String".to_string(),
- BranchCondition::ResolvedString => "ResolvedString".to_string(),
- BranchCondition::Builtin(id) => format!("Builtin {id}"),
- BranchCondition::PropertyIteratorCacheValid => "PropertyIteratorCacheValid".to_string(),
- BranchCondition::BindingMutable { index } => format!("BindingMutable {index}"),
- BranchCondition::NextBindingOfShape { name, flags } => format!("NextBindingOfShape {name:#x} {flags}"),
+struct ConditionText(BranchCondition);
+
+impl fmt::Display for ConditionText {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let name = match self.0 {
+ BranchCondition::Bool => "Bool",
+ BranchCondition::Nullish => "Nullish",
+ BranchCondition::Undefined => "Undefined",
+ BranchCondition::Object => "Object",
+ BranchCondition::ElementsKind(kind) => return write!(f, "ElementsKind {kind:?}"),
+ BranchCondition::IndexInBounds => "IndexInBounds",
+ BranchCondition::MagicalLength => "MagicalLength",
+ BranchCondition::Extensible => "Extensible",
+ BranchCondition::HoleFillableArray => "HoleFillableArray",
+ BranchCondition::ArrayIterator => "ArrayIterator",
+ BranchCondition::GeneratorObject => "GeneratorObject",
+ BranchCondition::PlainArrayPrototypeChain => "PlainArrayPrototypeChain",
+ BranchCondition::ArrayWithRealmArrayPrototypeAndNoNamedProperties => {
+ "ArrayWithRealmArrayPrototypeAndNoNamedProperties"
+ }
+ BranchCondition::HoldsValidWatchpointSet => "HoldsValidWatchpointSet",
+ BranchCondition::Shape(shape) => {
+ f.write_str("Shape ")?;
+ return write_shapes(f, core::slice::from_ref(&shape));
+ }
+ BranchCondition::NonNegativeInt32 => "NonNegativeInt32",
+ BranchCondition::Int32(comparison) => return write!(f, "Int32{comparison:?}"),
+ BranchCondition::Float64(comparison) => return write!(f, "Float64{comparison:?}"),
+ BranchCondition::TaggedEquals { equal: true } => "TaggedEquals",
+ BranchCondition::TaggedEquals { equal: false } => "TaggedNotEquals",
+ BranchCondition::Int32Value => "Int32Value",
+ BranchCondition::Int32OrBoolean => "Int32OrBoolean",
+ BranchCondition::Double => "Double",
+ BranchCondition::String => "String",
+ BranchCondition::ResolvedString => "ResolvedString",
+ BranchCondition::Builtin(id) => return write!(f, "Builtin {id}"),
+ BranchCondition::PropertyIteratorCacheValid => "PropertyIteratorCacheValid",
+ BranchCondition::BindingMutable { index } => return write!(f, "BindingMutable {index}"),
+ BranchCondition::NextBindingOfShape { name, flags } => {
+ return write!(f, "NextBindingOfShape {name:#x} {flags}");
+ }
+ };
+ f.write_str(name)
}
}
-/// The text of a node's op, with `inputs` (already formatted) in place.
-fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {
- let with_inputs = |name: &str| {
- if inputs.is_empty() {
- name.to_string()
+/// Where a call or a slow path call is in the bytecode: `@pc`, or `@e<executable>:pc` in an inlined executable.
+struct Site {
+ executable: u32,
+ pc: u32,
+}
+
+impl fmt::Display for Site {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ if self.executable == 0 {
+ write!(f, "@{}", self.pc)
} else {
- format!("{name} {inputs}")
+ write!(f, "@e{}:{}", self.executable, self.pc)
+ }
+ }
+}
+
+/// The text of " without inlined frames (<bytes> bytes)", or of nothing for none.
+struct InlinedFrames(u32);
+
+impl fmt::Display for InlinedFrames {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ if self.0 == 0 {
+ return Ok(());
+ }
+ write!(f, " without inlined frames ({} bytes)", self.0)
+ }
+}
+
+/// The inputs of a node, like `(v1, #i32:2)`, or nothing if it has none.
+struct Inputs<'a, 'z> {
+ graph: &'a Graph<'z>,
+ inputs: &'a [NodeId],
+}
+
+impl Inputs<'_, '_> {
+ /// Writes `head`, and the inputs after it with a space between.
+ fn after(&self, f: &mut fmt::Formatter<'_>, head: fmt::Arguments<'_>) -> fmt::Result {
+ f.write_fmt(head)?;
+ if self.inputs.is_empty() {
+ return Ok(());
}
- };
+ write!(f, " {self}")
+ }
+}
+
+impl fmt::Display for Inputs<'_, '_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ if self.inputs.is_empty() {
+ return Ok(());
+ }
+ f.write_str("(")?;
+ write_joined(f, self.inputs, |f, input| {
+ write!(f, "{}", value_name(self.graph, *input))
+ })?;
+ f.write_str(")")
+ }
+}
+
+/// Writes the text of a node's op, with `inputs` in place.
+fn write_op(f: &mut fmt::Formatter<'_>, layout: &FrameLayout, op: &Op, inputs: &Inputs<'_, '_>) -> fmt::Result {
+ let name = op.name();
match op {
- Op::Constant(bits) => format!("Constant {}", value::describe(*bits)),
- 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::PublishFrame => with_inputs("PublishFrame"),
+ Op::Constant(bits) => write!(f, "Constant {}", value::describe(*bits)),
+ Op::LoadSlot { slot } => inputs.after(f, format_args!("LoadSlot {}", slot_name(layout, *slot))),
+ Op::StoreSlot { slot } => inputs.after(f, format_args!("StoreSlot {}", slot_name(layout, *slot))),
+ Op::Phi => inputs.after(f, format_args!("Phi")),
+ Op::InitializeFrame => inputs.after(f, format_args!("InitializeFrame")),
+ Op::EnsureFrameInitialized => inputs.after(f, format_args!("EnsureFrameInitialized")),
+ Op::PublishFrame => inputs.after(f, format_args!("PublishFrame")),
Op::Suspend { continuation, kind } => {
- let continuation = continuation.map_or("completed".to_string(), |pc| format!("pc {pc}"));
let kind = match kind {
SuspendKind::Yield => "",
SuspendKind::YieldIteratorResult => " iterator-result",
SuspendKind::Await => " await",
};
- with_inputs(&format!("Suspend {continuation}{kind}"))
- }
- Op::BoxCell => with_inputs("BoxCell"),
- Op::LoadOuterEnvironment => with_inputs("LoadOuterEnvironment"),
- Op::LoadEnvironmentBinding { index } => with_inputs(&format!("LoadEnvironmentBinding {index}")),
- Op::StoreEnvironmentBinding { index } => with_inputs(&format!("StoreEnvironmentBinding {index}")),
- Op::AppendEnvironmentBinding => with_inputs("AppendEnvironmentBinding"),
- Op::SetLexicalEnvironment => with_inputs("SetLexicalEnvironment"),
- Op::LeavePrivateEnvironment => with_inputs("LeavePrivateEnvironment"),
- Op::IsCallable => with_inputs("IsCallable"),
- Op::CheckInt32 => with_inputs("CheckInt32"),
- Op::CheckNumber => with_inputs("CheckNumber"),
- Op::CheckIdentityComparable => with_inputs("CheckIdentityComparable"),
- Op::BoxInt32 => with_inputs("BoxInt32"),
- Op::BoxBool => with_inputs("BoxBool"),
- Op::CellAddress => with_inputs("CellAddress"),
- Op::Int32Binary { op } => with_inputs(&format!("Int32{op:?}")),
- Op::Int32WrappingBinary { op } => with_inputs(&format!("Int32Wrapping{op:?}")),
- Op::Int32Compare { comparison } => with_inputs(&format!("Int32{comparison:?}")),
- Op::CheckElements { kind } => with_inputs(&format!("CheckElements {kind:?}")),
- Op::LoadElementAt { kind } | Op::StoreElementAt { kind } => with_inputs(&format!("{} {kind:?}", op.name())),
- Op::TaggedEquals { equal: true } => with_inputs("TaggedEquals"),
- Op::TaggedEquals { equal: false } => with_inputs("TaggedNotEquals"),
- Op::ToBoolean => with_inputs("ToBoolean"),
- Op::PrimitiveToString | Op::ToObject | Op::ArrayCreate => with_inputs(op.name()),
- Op::CallIntrinsic { intrinsic } => with_inputs(&format!("CallIntrinsic {intrinsic:?}")),
+ match continuation {
+ Some(pc) => inputs.after(f, format_args!("Suspend pc {pc}{kind}")),
+ None => inputs.after(f, format_args!("Suspend completed{kind}")),
+ }
+ }
+ Op::BoxCell => inputs.after(f, format_args!("BoxCell")),
+ Op::LoadOuterEnvironment => inputs.after(f, format_args!("LoadOuterEnvironment")),
+ Op::LoadEnvironmentBinding { index } => inputs.after(f, format_args!("LoadEnvironmentBinding {index}")),
+ Op::StoreEnvironmentBinding { index } => inputs.after(f, format_args!("StoreEnvironmentBinding {index}")),
+ Op::AppendEnvironmentBinding => inputs.after(f, format_args!("AppendEnvironmentBinding")),
+ Op::SetLexicalEnvironment => inputs.after(f, format_args!("SetLexicalEnvironment")),
+ Op::LeavePrivateEnvironment => inputs.after(f, format_args!("LeavePrivateEnvironment")),
+ Op::IsCallable => inputs.after(f, format_args!("IsCallable")),
+ Op::CheckInt32 => inputs.after(f, format_args!("CheckInt32")),
+ Op::CheckNumber => inputs.after(f, format_args!("CheckNumber")),
+ Op::CheckIdentityComparable => inputs.after(f, format_args!("CheckIdentityComparable")),
+ Op::BoxInt32 => inputs.after(f, format_args!("BoxInt32")),
+ Op::BoxBool => inputs.after(f, format_args!("BoxBool")),
+ Op::CellAddress => inputs.after(f, format_args!("CellAddress")),
+ Op::Int32Binary { op } => inputs.after(f, format_args!("Int32{op:?}")),
+ Op::Int32WrappingBinary { op } => inputs.after(f, format_args!("Int32Wrapping{op:?}")),
+ Op::Int32Compare { comparison } => inputs.after(f, format_args!("Int32{comparison:?}")),
+ Op::CheckElements { kind } => inputs.after(f, format_args!("CheckElements {kind:?}")),
+ Op::LoadElementAt { kind } | Op::StoreElementAt { kind } => inputs.after(f, format_args!("{name} {kind:?}")),
+ Op::TaggedEquals { equal: true } => inputs.after(f, format_args!("TaggedEquals")),
+ Op::TaggedEquals { equal: false } => inputs.after(f, format_args!("TaggedNotEquals")),
+ Op::ToBoolean => inputs.after(f, format_args!("ToBoolean")),
+ Op::PrimitiveToString | Op::ToObject | Op::ArrayCreate => inputs.after(f, format_args!("{name}")),
+ Op::CallIntrinsic { intrinsic } => inputs.after(f, format_args!("CallIntrinsic {intrinsic:?}")),
Op::Generic { opcode, executable, pc } => {
- let location = if *executable == 0 {
- format!("@{pc}")
- } else {
- format!("@e{executable}:{pc}")
+ let site = Site {
+ executable: *executable,
+ pc: *pc,
};
- with_inputs(&format!("Generic {} {location}", opcode.name()))
+ inputs.after(f, format_args!("Generic {} {site}", opcode.name()))
}
- Op::ArgumentCount => with_inputs("ArgumentCount"),
- Op::SliceArguments => with_inputs("SliceArguments"),
- Op::LoadFrameField { field } => with_inputs(&format!("LoadFrameField {field:?}")),
- Op::LoadArgument { .. } => with_inputs("LoadArgument"),
+ Op::ArgumentCount => inputs.after(f, format_args!("ArgumentCount")),
+ Op::SliceArguments => inputs.after(f, format_args!("SliceArguments")),
+ Op::LoadFrameField { field } => inputs.after(f, format_args!("LoadFrameField {field:?}")),
+ Op::LoadArgument { .. } => inputs.after(f, format_args!("LoadArgument")),
Op::CallForwardingArguments { executable, pc } => {
- let location = if *executable == 0 {
- format!("@{pc}")
- } else {
- format!("@e{executable}:{pc}")
+ let site = Site {
+ executable: *executable,
+ pc: *pc,
};
- with_inputs(&format!("CallForwardingArguments {location}"))
+ inputs.after(f, format_args!("CallForwardingArguments {site}"))
}
Op::CallDirect {
executable,
@@ -187,19 +280,19 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {
stores_operands,
target,
} => {
- let location = if *executable == 0 {
- format!("@{pc}")
- } else {
- format!("@e{executable}:{pc}")
- };
- let frames = if *inlined_frame_bytes == 0 {
- String::new()
- } else {
- format!(" without inlined frames ({inlined_frame_bytes} bytes)")
+ let site = Site {
+ executable: *executable,
+ pc: *pc,
};
+ let frames = InlinedFrames(*inlined_frame_bytes);
let stores = if *stores_operands { " storing operands" } else { "" };
- let target = target.map_or(String::new(), |target| format!(" of constant target {target}"));
- with_inputs(&format!("CallDirect {location}{frames}{stores}{target}"))
+ match target {
+ Some(target) => inputs.after(
+ f,
+ format_args!("CallDirect {site}{frames}{stores} of constant target {target}"),
+ ),
+ None => inputs.after(f, format_args!("CallDirect {site}{frames}{stores}")),
+ }
}
Op::CallNative {
executable,
@@ -207,114 +300,126 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {
inlined_frame_bytes,
stores_operands,
} => {
- let location = if *executable == 0 {
- format!("@{pc}")
- } else {
- format!("@e{executable}:{pc}")
- };
- let frames = if *inlined_frame_bytes == 0 {
- String::new()
- } else {
- format!(" without inlined frames ({inlined_frame_bytes} bytes)")
+ let site = Site {
+ executable: *executable,
+ pc: *pc,
};
+ let frames = InlinedFrames(*inlined_frame_bytes);
let stores = if *stores_operands { " storing operands" } else { "" };
- with_inputs(&format!("CallNative {location}{frames}{stores}"))
+ inputs.after(f, format_args!("CallNative {site}{frames}{stores}"))
}
Op::CallNativeAccessor { pc, part, target } => {
let direct = if target.direct_getter.is_some() { " direct" } else { "" };
- with_inputs(&format!(
- "CallNativeAccessor @{pc} {part:?} {:#x}{direct}",
- target.function.0
- ))
+ inputs.after(
+ f,
+ format_args!("CallNativeAccessor @{pc} {part:?} {:#x}{direct}", target.function.0),
+ )
}
Op::AllocateObject {
shape,
property_count,
reserve,
} => {
- format!(
+ write!(
+ f,
"AllocateObject {:#x} with {property_count} properties, room for {reserve}",
shape.0
)
}
- Op::InitializeNamed { offset } => with_inputs(&format!("InitializeNamed +{offset}")),
- Op::AllocateArray { count } => format!("AllocateArray with {count} elements"),
+ Op::InitializeNamed { offset } => inputs.after(f, format_args!("InitializeNamed +{offset}")),
+ Op::AllocateArray { count } => write!(f, "AllocateArray with {count} elements"),
Op::VirtualObject {
kind: VirtualObjectKind::Object { shape },
..
- } => with_inputs(&format!("VirtualObject {:#x}", shape.0)),
+ } => inputs.after(f, format_args!("VirtualObject {:#x}", shape.0)),
Op::VirtualObject {
kind: VirtualObjectKind::Closure { sample },
..
- } => with_inputs(&format!("VirtualObject closure {:#x}", sample.0)),
+ } => inputs.after(f, format_args!("VirtualObject closure {:#x}", sample.0)),
Op::AllocateEnvironment { shape_cache, capacity } => {
- with_inputs(&format!("AllocateEnvironment {shape_cache} capacity {capacity}"))
+ inputs.after(f, format_args!("AllocateEnvironment {shape_cache} capacity {capacity}"))
}
Op::AllocateFunction {
executable,
shared_function_data_index,
..
- } => with_inputs(&format!("AllocateFunction e{executable}:{shared_function_data_index}")),
- Op::InitializeElement { index } => with_inputs(&format!("InitializeElement [{index}]")),
- Op::CheckObject => with_inputs("CheckObject"),
- Op::CheckValue { expected, .. } => with_inputs(&format!("CheckValue {expected:#x}")),
- Op::CheckClosure { shared_data } => with_inputs(&format!("CheckClosure {:#x}", shared_data.0)),
- Op::LoadFunctionEnvironment { private } => with_inputs(if *private {
- "LoadFunctionEnvironment private"
- } else {
- "LoadFunctionEnvironment"
- }),
- Op::EmptyToUndefined => with_inputs("EmptyToUndefined"),
- Op::Typeof => with_inputs("Typeof"),
- Op::TypeofIs { kind, equal } => with_inputs(&format!("TypeofIs{} {kind:?}", if *equal { "" } else { "Not" })),
- Op::CheckShape { shapes } => with_inputs(&format!("CheckShape [{}]", shapes_text(shapes.iter()))),
- Op::CheckPrototypeChainValid { validity } => format!("CheckPrototypeChainValid {:#x}", validity.0),
- Op::AssumeValid => "AssumeValid".to_string(),
- Op::CheckInterrupt => "CheckInterrupt".to_string(),
- Op::AssumeLegacyArgumentsUnread => "AssumeLegacyArgumentsUnread".to_string(),
- Op::HasInPrototypeChain => with_inputs("HasInPrototypeChain"),
- Op::LoadGlobalBinding { environment, index } => format!("LoadGlobalBinding {:#x}[{index}]", environment.0),
+ } => inputs.after(
+ f,
+ format_args!("AllocateFunction e{executable}:{shared_function_data_index}"),
+ ),
+ Op::InitializeElement { index } => inputs.after(f, format_args!("InitializeElement [{index}]")),
+ Op::CheckObject => inputs.after(f, format_args!("CheckObject")),
+ Op::CheckValue { expected, .. } => inputs.after(f, format_args!("CheckValue {expected:#x}")),
+ Op::CheckClosure { shared_data } => inputs.after(f, format_args!("CheckClosure {:#x}", shared_data.0)),
+ Op::LoadFunctionEnvironment { private: true } => {
+ inputs.after(f, format_args!("LoadFunctionEnvironment private"))
+ }
+ Op::LoadFunctionEnvironment { private: false } => inputs.after(f, format_args!("LoadFunctionEnvironment")),
+ Op::EmptyToUndefined => inputs.after(f, format_args!("EmptyToUndefined")),
+ Op::Typeof => inputs.after(f, format_args!("Typeof")),
+ Op::TypeofIs { kind, equal } => {
+ let negation = if *equal { "" } else { "Not" };
+ inputs.after(f, format_args!("TypeofIs{negation} {kind:?}"))
+ }
+ Op::CheckShape { shapes } => {
+ f.write_str("CheckShape [")?;
+ write_shapes(f, shapes)?;
+ inputs.after(f, format_args!("]"))
+ }
+ Op::CheckPrototypeChainValid { validity } => write!(f, "CheckPrototypeChainValid {:#x}", validity.0),
+ Op::AssumeValid => f.write_str("AssumeValid"),
+ Op::CheckInterrupt => f.write_str("CheckInterrupt"),
+ Op::AssumeLegacyArgumentsUnread => f.write_str("AssumeLegacyArgumentsUnread"),
+ Op::HasInPrototypeChain => inputs.after(f, format_args!("HasInPrototypeChain")),
+ Op::LoadGlobalBinding { environment, index } => {
+ write!(f, "LoadGlobalBinding {:#x}[{index}]", environment.0)
+ }
Op::StoreGlobalBinding { environment, index } => {
- with_inputs(&format!("StoreGlobalBinding {:#x}[{index}]", environment.0))
+ inputs.after(f, format_args!("StoreGlobalBinding {:#x}[{index}]", environment.0))
}
- Op::LoadAccessorFunction { offset, part } => with_inputs(&format!("LoadAccessorFunction +{offset} {part:?}")),
- Op::CheckAccessorFunction { offset, part, function } => {
- with_inputs(&format!("CheckAccessorFunction +{offset} {part:?} {:#x}", function.0))
+ Op::LoadAccessorFunction { offset, part } => {
+ inputs.after(f, format_args!("LoadAccessorFunction +{offset} {part:?}"))
}
+ Op::CheckAccessorFunction { offset, part, function } => inputs.after(
+ f,
+ format_args!("CheckAccessorFunction +{offset} {part:?} {:#x}", function.0),
+ ),
Op::LoadNamed { offset, holds_data } => {
- with_inputs(&format!("LoadNamed +{offset}")) + if *holds_data { " data" } else { "" }
+ inputs.after(f, format_args!("LoadNamed +{offset}"))?;
+ f.write_str(if *holds_data { " data" } else { "" })
}
Op::StoreNamed { offset, holds_data } => {
- with_inputs(&format!("StoreNamed +{offset}")) + if *holds_data { " data" } else { "" }
+ inputs.after(f, format_args!("StoreNamed +{offset}"))?;
+ f.write_str(if *holds_data { " data" } else { "" })
}
- Op::AddNamed { offset, shape, .. } => with_inputs(&format!("AddNamed +{offset} to {:#x}", shape.0)),
+ Op::AddNamed { offset, shape, .. } => inputs.after(f, format_args!("AddNamed +{offset} to {:#x}", shape.0)),
Op::ShapeSwitch { shapes, targets } => {
- let cases = shapes
- .iter()
- .zip(*targets)
- .map(|(shape, block)| format!("{} -> {}", shapes_text(std::iter::once(shape)), block_name(*block)))
- .fold(String::new(), join);
- format!("{} [{}]", with_inputs("ShapeSwitch"), cases)
+ inputs.after(f, format_args!("ShapeSwitch"))?;
+ f.write_str(" [")?;
+ write_joined(f, shapes.iter().zip(*targets), |f, (shape, block)| {
+ write_shapes(f, core::slice::from_ref(shape))?;
+ write!(f, " -> {}", BlockName(*block))
+ })?;
+ f.write_str("]")
}
Op::CallSlowPath {
opcode, executable, pc, ..
} => {
- let location = if *executable == 0 {
- format!("@{pc}")
- } else {
- format!("@e{executable}:{pc}")
+ let site = Site {
+ executable: *executable,
+ pc: *pc,
};
- with_inputs(&format!("{} {} {location}", op.name(), opcode.name()))
+ inputs.after(f, format_args!("{name} {} {site}", opcode.name()))
}
- Op::Float64Unary { op } => with_inputs(&format!("Float64{}", op.name())),
- Op::CallFloat64Function { function } => with_inputs(&format!("CallFloat64{}", function.name())),
- Op::Float64Binary { op } => with_inputs(&format!("Float64{op:?}")),
- Op::Float64Compare { comparison } => with_inputs(&format!("Float64{comparison:?}")),
+ Op::Float64Unary { op } => inputs.after(f, format_args!("Float64{}", op.name())),
+ Op::CallFloat64Function { function } => inputs.after(f, format_args!("CallFloat64{}", function.name())),
+ Op::Float64Binary { op } => inputs.after(f, format_args!("Float64{op:?}")),
+ Op::Float64Compare { comparison } => inputs.after(f, format_args!("Float64{comparison:?}")),
Op::Refine { condition, holds } => {
let negation = if *holds { "" } else { "Not" };
- with_inputs(&format!("Refine{negation}{}", condition_text(*condition)))
+ inputs.after(f, format_args!("Refine{negation}{}", ConditionText(*condition)))
}
- Op::SlowPathOutput { index } => with_inputs(&format!("SlowPathOutput {index}")),
+ Op::SlowPathOutput { index } => inputs.after(f, format_args!("SlowPathOutput {index}")),
Op::UnboxInt32
| Op::Int32Abs
| Op::Int32Min
@@ -352,7 +457,7 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {
| Op::LoadGeneratorCompletionType
| Op::LoadGeneratorCompletionValue
| Op::LoadPropertyIteratorKeyCount
- | Op::LoadPropertyIteratorKey => with_inputs(op.name()),
+ | Op::LoadPropertyIteratorKey => inputs.after(f, format_args!("{name}")),
Op::CheckBounds
| Op::CheckNotHole
| Op::CheckInitialized
@@ -363,155 +468,160 @@ fn op_text(layout: &FrameLayout, op: &Op, inputs: &str) -> String {
| Op::LoadTypedArrayLength
| Op::LoadTypedArrayDataOffset
| Op::TypedArrayDataAddress
- | Op::CheckTypedArrayStorage => with_inputs(op.name()),
- Op::ConcatenateStrings { key: false } => with_inputs("ConcatenateStrings"),
- Op::ConcatenateStrings { key: true } => with_inputs("ConcatenateKeyStrings"),
- Op::ProbeHasProperty { own: true } => with_inputs("ProbeHasOwnProperty"),
- Op::ProbeHasProperty { own: false } => with_inputs("ProbeHasProperty"),
+ | Op::CheckTypedArrayStorage => inputs.after(f, format_args!("{name}")),
+ Op::ConcatenateStrings { key: false } => inputs.after(f, format_args!("ConcatenateStrings")),
+ Op::ConcatenateStrings { key: true } => inputs.after(f, format_args!("ConcatenateKeyStrings")),
+ Op::ProbeHasProperty { own: true } => inputs.after(f, format_args!("ProbeHasOwnProperty")),
+ Op::ProbeHasProperty { own: false } => inputs.after(f, format_args!("ProbeHasProperty")),
Op::ProbeGlobalCache { cache } | Op::ProbeGlobalStore { cache } => {
- with_inputs(&format!("{} cache {cache}", op.name()))
+ inputs.after(f, format_args!("{name} cache {cache}"))
}
Op::ProbePropertyCache { executable, cache, .. }
| Op::ProbeKeyedCache { executable, cache }
| Op::ProbeKeyedStore { executable, cache }
| Op::ProbePropertyStore { executable, cache, .. } => {
- let cache = if *executable == 0 {
- format!("cache {cache}")
+ if *executable == 0 {
+ inputs.after(f, format_args!("{name} cache {cache}"))
} else {
- format!("cache e{executable}:{cache}")
- };
- with_inputs(&format!("{} {cache}", op.name()))
+ inputs.after(f, format_args!("{name} cache e{executable}:{cache}"))
+ }
}
- Op::Jump { target } => format!("Jump {}", block_name(*target)),
+ Op::Jump { target } => write!(f, "Jump {}", BlockName(*target)),
Op::Branch {
condition,
if_true,
if_false,
} => {
- let condition = condition_text(*condition);
- format!(
- "{} -> {}, {}",
- with_inputs(&format!("Branch{condition}")),
- block_name(*if_true),
- block_name(*if_false)
- )
+ inputs.after(f, format_args!("Branch{}", ConditionText(*condition)))?;
+ write!(f, " -> {}, {}", BlockName(*if_true), BlockName(*if_false))
}
Op::BranchTruthy {
if_true,
if_false,
fallback,
- } => format!(
- "{} -> {}, {}, fallback {}",
- with_inputs("BranchTruthy"),
- block_name(*if_true),
- block_name(*if_false),
- block_name(*fallback)
- ),
- Op::BranchOnPc { pc, if_true, if_false } => format!(
- "{} -> {}, {}",
- with_inputs(&format!("BranchOnPc @{pc}")),
- block_name(*if_true),
- block_name(*if_false)
- ),
- Op::Return => with_inputs("Return"),
- Op::Exit { kind } => with_inputs(&format!("Exit {kind:?}")),
- Op::Unreachable => with_inputs("Unreachable"),
+ } => {
+ inputs.after(f, format_args!("BranchTruthy"))?;
+ write!(
+ f,
+ " -> {}, {}, fallback {}",
+ BlockName(*if_true),
+ BlockName(*if_false),
+ BlockName(*fallback)
+ )
+ }
+ Op::BranchOnPc { pc, if_true, if_false } => {
+ inputs.after(f, format_args!("BranchOnPc @{pc}"))?;
+ write!(f, " -> {}, {}", BlockName(*if_true), BlockName(*if_false))
+ }
+ Op::Return => inputs.after(f, format_args!("Return")),
+ Op::Exit { kind } => inputs.after(f, format_args!("Exit {kind:?}")),
+ Op::Unreachable => inputs.after(f, format_args!("Unreachable")),
}
}
+/// One node as text, like `v3 = Generic GetById @12 (v1) [fs2]` (see `node_text()`).
+pub struct NodeText<'a, 'z> {
+ graph: &'a Graph<'z>,
+ layout: &'a FrameLayout,
+ node_id: NodeId,
+}
+
/// One node as text, like `v3 = Generic GetById @12 (v1) [fs2]`.
-pub fn node_text(graph: &Graph, layout: &FrameLayout, node_id: NodeId) -> String {
- let node = graph.node(node_id);
- let mut out = String::new();
- if let Some(repr) = node.repr {
- write!(out, "v{}", node_id.0).unwrap();
- if repr != Repr::Tagged {
- write!(out, ":{}", repr_name(repr)).unwrap();
- }
- out.push_str(" = ");
- }
- let inputs = if node.inputs.is_empty() {
- String::new()
- } else {
- let inputs = node
- .inputs
- .iter()
- .map(|input| value_name(graph, *input))
- .fold(String::new(), join);
- format!("({inputs})")
- };
- out.push_str(&op_text(layout, &node.op, &inputs));
- if let Some(frame_state) = node.frame_state {
- write!(out, " [fs{}]", frame_state.0).unwrap();
+pub fn node_text<'a, 'z>(graph: &'a Graph<'z>, layout: &'a FrameLayout, node_id: NodeId) -> NodeText<'a, 'z> {
+ NodeText { graph, layout, node_id }
+}
+
+impl fmt::Display for NodeText<'_, '_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let node = self.graph.node(self.node_id);
+ if let Some(repr) = node.repr {
+ write!(f, "v{}", self.node_id.0)?;
+ if repr != Repr::Tagged {
+ write!(f, ":{}", repr_name(repr))?;
+ }
+ f.write_str(" = ")?;
+ }
+ let inputs = Inputs {
+ graph: self.graph,
+ inputs: &node.inputs,
+ };
+ write_op(f, self.layout, &node.op, &inputs)?;
+ if let Some(frame_state) = node.frame_state {
+ write!(f, " [fs{}]", frame_state.0)?;
+ }
+ Ok(())
}
- out
+}
+
+/// `graph` as text, with frame slots named according to `layout` (see `dump()`).
+pub struct Dump<'a, 'z> {
+ graph: &'a Graph<'z>,
+ layout: &'a FrameLayout,
}
/// Prints `graph` as text, naming frame slots according to `layout`.
-pub fn dump(graph: &Graph, layout: &FrameLayout) -> String {
- let mut out = String::new();
- for (index, block) in graph.blocks.iter().enumerate() {
- let id = BlockId::from_index(index);
- write!(out, "{}", block_name(id)).unwrap();
- if let Some(pc) = block.bytecode_start {
- write!(out, " (pc {pc})").unwrap();
- }
- if !block.predecessors.is_empty() {
- let predecessors = block
- .predecessors
- .iter()
- .map(|block| block_name(*block))
- .fold(String::new(), join);
- write!(out, " <- {predecessors}").unwrap();
- }
- if block.is_loop_header {
- out.push_str(" loop");
- }
- if block.is_cold {
- out.push_str(" cold");
- }
- out.push_str(":\n");
- for node_id in graph.block_nodes(id) {
- out.push_str(" ");
- out.push_str(&node_text(graph, layout, node_id));
- out.push('\n');
+pub fn dump<'a, 'z>(graph: &'a Graph<'z>, layout: &'a FrameLayout) -> Dump<'a, 'z> {
+ Dump { graph, layout }
+}
+
+impl fmt::Display for Dump<'_, '_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let (graph, layout) = (self.graph, self.layout);
+ for (index, block) in graph.blocks.iter().enumerate() {
+ let id = BlockId::from_index(index);
+ write!(f, "{}", BlockName(id))?;
+ if let Some(pc) = block.bytecode_start {
+ write!(f, " (pc {pc})")?;
+ }
+ if !block.predecessors.is_empty() {
+ f.write_str(" <- ")?;
+ write_joined(f, &block.predecessors, |f, block| write!(f, "{}", BlockName(*block)))?;
+ }
+ if block.is_loop_header {
+ f.write_str(" loop")?;
+ }
+ if block.is_cold {
+ f.write_str(" cold")?;
+ }
+ f.write_str(":\n")?;
+ for node_id in graph.block_nodes(id) {
+ writeln!(f, " {}", node_text(graph, layout, node_id))?;
+ }
}
+ for (pc, block) in &graph.osr_entries {
+ writeln!(f, "osr entry at pc {pc}: b{}", block.0)?;
+ }
+ if !graph.frame_states.is_empty() {
+ f.write_str("frame states:\n")?;
+ }
+ for (index, frame_state) in graph.frame_states.iter().enumerate() {
+ write!(f, " fs{index}: ")?;
+ if frame_state.executable != 0 {
+ write!(f, "e{} ", frame_state.executable)?;
+ }
+ write!(f, "pc {}", frame_state.pc)?;
+ match frame_state.mode {
+ ResumeMode::ResumeAt => f.write_str(" at")?,
+ ResumeMode::ResumeAfter { dst } if dst == Operand::INVALID => f.write_str(" after")?,
+ ResumeMode::ResumeAfter { dst } => write!(f, " after -> {}", slot_name(layout, dst))?,
+ }
+ f.write_str(" {")?;
+ write_joined(f, &frame_state.values, |f, (slot, value)| {
+ write!(f, "{}={}", slot_name(layout, *slot), value_name(graph, *value))
+ })?;
+ f.write_str("}")?;
+ if !frame_state.in_frame.is_empty() {
+ f.write_str(" frame [")?;
+ write_joined(f, &frame_state.in_frame, |f, slot| {
+ write!(f, "{}", slot_name(layout, *slot))
+ })?;
+ f.write_str("]")?;
+ }
+ if let Some(parent) = frame_state.parent {
+ write!(f, " in fs{}", parent.0)?;
+ }
+ f.write_str("\n")?;
+ }
+ Ok(())
}
- for (pc, block) in &graph.osr_entries {
- writeln!(out, "osr entry at pc {pc}: b{}", block.0).unwrap();
- }
- if !graph.frame_states.is_empty() {
- out.push_str("frame states:\n");
- }
- for (index, frame_state) in graph.frame_states.iter().enumerate() {
- write!(out, " fs{index}: ").unwrap();
- if frame_state.executable != 0 {
- write!(out, "e{} ", frame_state.executable).unwrap();
- }
- write!(out, "pc {}", frame_state.pc).unwrap();
- match frame_state.mode {
- ResumeMode::ResumeAt => out.push_str(" at"),
- ResumeMode::ResumeAfter { dst } if dst == Operand::INVALID => out.push_str(" after"),
- ResumeMode::ResumeAfter { dst } => write!(out, " after -> {}", slot_name(layout, dst)).unwrap(),
- }
- let values = frame_state
- .values
- .iter()
- .map(|(slot, value)| format!("{}={}", slot_name(layout, *slot), value_name(graph, *value)))
- .fold(String::new(), join);
- write!(out, " {{{values}}}").unwrap();
- if !frame_state.in_frame.is_empty() {
- let in_frame = frame_state
- .in_frame
- .iter()
- .map(|slot| slot_name(layout, *slot))
- .fold(String::new(), join);
- write!(out, " frame [{in_frame}]").unwrap();
- }
- if let Some(parent) = frame_state.parent {
- write!(out, " in fs{}", parent.0).unwrap();
- }
- out.push('\n');
- }
- out
}
diff --git a/Libraries/LibJS/JIT/Rust/src/ir/value.rs b/Libraries/LibJS/JIT/Rust/src/ir/value.rs
index 63d3a6bdedf..4e2d928108e 100644
--- a/Libraries/LibJS/JIT/Rust/src/ir/value.rs
+++ b/Libraries/LibJS/JIT/Rust/src/ir/value.rs
@@ -108,17 +108,47 @@ pub fn number(number: f64) -> u64 {
}
/// A short human readable description of a NaN-boxed value, for IR dumps.
-pub fn describe(bits: u64) -> String {
- match bits {
- EMPTY => "empty".to_string(),
- VIRTUAL_UNMAPPED_ARGUMENTS => "arguments".to_string(),
- VIRTUAL_MAPPED_ARGUMENTS => "mapped arguments".to_string(),
- UNDEFINED => "undefined".to_string(),
- NULL => "null".to_string(),
- FALSE => "false".to_string(),
- TRUE => "true".to_string(),
- _ if bits >> TAG_SHIFT == u64::from(INT32_TAG) => format!("{}", (bits as u32).cast_signed()),
- _ => format!("{bits:#018x}"),
+pub fn describe(bits: u64) -> Description {
+ Description(bits)
+}
+
+/// The text of `describe()`.
+#[derive(Debug, Clone, Copy)]
+pub struct Description(u64);
+
+impl Description {
+ /// The name of the value, if it has one rather than its bits in hex.
+ fn name(self) -> Option<&'static str> {
+ match self.0 {
+ EMPTY => Some("empty"),
+ VIRTUAL_UNMAPPED_ARGUMENTS => Some("arguments"),
+ VIRTUAL_MAPPED_ARGUMENTS => Some("mapped arguments"),
+ UNDEFINED => Some("undefined"),
+ NULL => Some("null"),
+ FALSE => Some("false"),
+ TRUE => Some("true"),
+ _ => None,
+ }
+ }
+
+ fn is_int32(self) -> bool {
+ self.0 >> TAG_SHIFT == u64::from(INT32_TAG)
+ }
+
+ /// Whether the text tells what the value is, rather than only giving its bits in hex.
+ pub fn is_known_value(self) -> bool {
+ self.name().is_some() || self.is_int32()
+ }
+}
+
+impl core::fmt::Display for Description {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ let bits = self.0;
+ match self.name() {
+ Some(name) => f.write_str(name),
+ None if self.is_int32() => write!(f, "{}", (bits as u32).cast_signed()),
+ None => write!(f, "{bits:#018x}"),
+ }
}
}
@@ -128,10 +158,12 @@ mod tests {
#[test]
fn describes_known_values() {
- assert_eq!(describe(EMPTY), "empty");
- assert_eq!(describe(TRUE), "true");
- assert_eq!(describe(int32(-5)), "-5");
- assert_eq!(describe(int32(7)), "7");
- assert_eq!(describe(0x4000_0000_0000_0000), "0x4000000000000000");
+ assert_eq!(describe(EMPTY).to_string(), "empty");
+ assert_eq!(describe(TRUE).to_string(), "true");
+ assert_eq!(describe(int32(-5)).to_string(), "-5");
+ assert_eq!(describe(int32(7)).to_string(), "7");
+ assert_eq!(describe(0x4000_0000_0000_0000).to_string(), "0x4000000000000000");
+ assert!(describe(int32(-5)).is_known_value());
+ assert!(!describe(0x4000_0000_0000_0000).is_known_value());
}
}
diff --git a/Libraries/LibJS/JIT/Rust/src/lib.rs b/Libraries/LibJS/JIT/Rust/src/lib.rs
index 77bf5ac61ab..47216536eb5 100644
--- a/Libraries/LibJS/JIT/Rust/src/lib.rs
+++ b/Libraries/LibJS/JIT/Rust/src/lib.rs
@@ -12,7 +12,10 @@
//! it can run on a worker thread.
// NB: The tests keep their own data in the heap.
-#![cfg_attr(test, allow(clippy::disallowed_types, clippy::disallowed_macros))]
+#![cfg_attr(
+ test,
+ allow(clippy::disallowed_types, clippy::disallowed_macros, clippy::disallowed_methods)
+)]
// NB: A module with `allow(clippy::disallowed_types)` still uses containers of the heap (see clippy.toml). It loses
// the `allow` when its data is in zones.
@@ -20,20 +23,19 @@ pub mod artifact;
pub mod asm;
pub mod builder;
pub mod bytecode;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
pub mod code;
pub mod codegen;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
+#[allow(clippy::disallowed_types, clippy::disallowed_macros, clippy::disallowed_methods)]
pub mod compile_pool;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
pub mod coverage;
+pub mod debug_text;
pub mod ir;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
+#[allow(clippy::disallowed_types, clippy::disallowed_macros, clippy::disallowed_methods)]
pub mod options;
pub mod passes;
pub mod regalloc;
pub mod scratch;
-#[allow(clippy::disallowed_types, clippy::disallowed_macros)]
+#[allow(clippy::disallowed_types, clippy::disallowed_macros, clippy::disallowed_methods)]
pub mod snapshot;
pub mod tables;
@@ -47,6 +49,8 @@ use artifact::ArtifactWriter;
use artifact::Tail;
use bytecode::OpCode;
use code::CompiledCode;
+use code::TextWriter;
+use core::fmt::Write;
use scratch::Scratch;
use snapshot::Snapshot;
@@ -143,8 +147,6 @@ fn compile_into<M: asm::PortableMacroAssembler>(
}
/// The stages of `compile_into()`, which leave their data in `scratch`.
-// NB: The coverage keys of a compile are still a list in the heap.
-#[allow(clippy::disallowed_types)]
fn run_stages<M: asm::PortableMacroAssembler>(
snapshot: &Snapshot,
has_run: &dyn Fn(u32) -> bool,
@@ -152,6 +154,11 @@ fn run_stages<M: asm::PortableMacroAssembler>(
compiled: &mut CompiledCode,
) -> Result<(), CompileFailure> {
compiled.clear();
+ let options = &snapshot.options;
+ compiled.keep_texts(
+ options.dump_ir || options.dump_asm || options.dump_passes,
+ options.coverage,
+ );
if !snapshot.is_complete() {
return Err(CompileFailure::TooLarge);
}
@@ -171,18 +178,14 @@ fn run_stages<M: asm::PortableMacroAssembler>(
// NB: The builder is done, and nothing of the graph is in its work data.
work.reset();
let executable = &snapshot.executables[0];
- let pass_dumps = if snapshot.options.dump_passes {
- Some(passes::optimize_with_dumps(
- &mut graph,
- &executable.layout,
- snapshot.options.verify_ir,
- work,
- steps,
- )?)
- } else {
- passes::optimize(&mut graph, &executable.layout, snapshot.options.verify_ir, work, steps)?;
- None
- };
+ // NB: The text of a dump that does not fit is cut (see `TextWriter`), so a failed write needs nothing more.
+ let mut dump = compiled.dump.as_mut().map(TextWriter::dump);
+ match &mut dump {
+ Some(dump) if options.dump_passes => {
+ passes::optimize_with_dumps(&mut graph, &executable.layout, options.verify_ir, work, steps, dump)?;
+ }
+ _ => passes::optimize(&mut graph, &executable.layout, options.verify_ir, work, steps)?,
+ }
let (mut registers, _) = codegen::target_registers::<M>();
if snapshot.options.stress.few_registers {
registers.allocatable_gprs = registers.few_registers(STRESS_EXTRA_REGISTERS);
@@ -223,37 +226,40 @@ fn run_stages<M: asm::PortableMacroAssembler>(
&mut compiled.words,
)?;
- let mut dump = None;
- if snapshot.options.dump_ir || snapshot.options.dump_asm || pass_dumps.is_some() {
- let mut text = pass_dumps.unwrap_or_default();
- if snapshot.options.dump_ir {
- text.push_str(&ir::dump(&graph, &executable.layout));
- text.push_str(&regalloc::dump_allocation(&graph, &allocation));
+ if let Some(dump) = &mut dump {
+ if options.dump_ir {
+ let _ = write!(
+ dump,
+ "{}{}",
+ ir::dump(&graph, &executable.layout),
+ regalloc::dump_allocation(&graph, &allocation)
+ );
}
- if snapshot.options.dump_asm {
- text.push_str(&codegen::dump_code(
- &graph,
- executable,
- &snapshot.runtime,
- M::ARCHITECTURE,
- &compiled.code,
- &generated,
- Artifact::new(&compiled.words, &layout),
- ));
+ if options.dump_asm {
+ let _ = write!(
+ dump,
+ "{}",
+ codegen::dump_code(
+ &graph,
+ executable,
+ &snapshot.runtime,
+ M::ARCHITECTURE,
+ &compiled.code,
+ &generated,
+ Artifact::new(&compiled.words, &layout),
+ )
+ );
}
- dump = Some(text);
+ }
+ if let Some(coverage) = &mut compiled.coverage {
+ // NB: The keys that do not fit are left out (see `TextWriter`).
+ let _ = coverage::write_coverage_keys(&graph, &mut TextWriter::lines(coverage));
}
compiled.data_offset = generated.data_offset;
compiled.entry_offset = generated.entry_offset;
compiled.site_index_frame_offset = generated.site_index_frame_offset;
compiled.register_dump_frame_offset = generated.register_dump_frame_offset;
compiled.layout = layout;
- compiled.dump = dump;
- compiled.coverage = if snapshot.options.coverage {
- coverage::coverage_keys(&graph)
- } else {
- Vec::new()
- };
Ok(())
}
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs b/Libraries/LibJS/JIT/Rust/src/passes/mod.rs
index beca81a8c2f..21110d4a422 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/mod.rs
@@ -39,6 +39,7 @@ pub mod verify;
mod tests;
use ak::Zone;
+use core::fmt;
use crate::CompileFailure;
use crate::bytecode::FrameLayout;
@@ -197,21 +198,21 @@ pub fn optimize(
run_passes(graph, layout, verify, work, steps, &mut |_, _| {})
}
-/// `optimize()`, returning the graph as text after building it and after
-/// every pass, each headed by "=== after <pass>" (for tests of passes).
+/// `optimize()`, writing the graph as text to `dumps` after building it and
+/// after every pass, each headed by "=== after <pass>" (for tests of passes).
+/// Text that `dumps` has no room for is left out.
pub fn optimize_with_dumps(
graph: &mut Graph,
layout: &FrameLayout,
verify: bool,
work: &mut Zone,
steps: &mut [Zone; 2],
-) -> Result<String, CompileFailure> {
- let mut text = String::new();
+ dumps: &mut dyn fmt::Write,
+) -> Result<(), CompileFailure> {
run_passes(graph, layout, verify, work, steps, &mut |graph, after| {
- text.push_str(&format!("=== after {after}\n"));
- text.push_str(&crate::ir::dump(graph, layout));
- })?;
- Ok(text)
+ // NB: A write fails only when `dumps` has no room for more text.
+ let _ = write!(dumps, "=== after {after}\n{}", crate::ir::dump(graph, layout));
+ })
}
fn run_passes(
@@ -264,12 +265,13 @@ fn check(graph: &Graph, layout: &FrameLayout, verify: bool, work: &mut Zone, aft
if !verify {
return;
}
- let result =
- work.scope(|work| verify::verify_with(graph, work).and(verify::verify_frame_writes(graph, layout, work)));
- if let Err(errors) = result {
- panic!(
- "invalid graph after {after}:\n{errors}\n{}",
- crate::ir::dump(graph, layout)
- );
- }
+ // NB: The errors are in the work zone, so the panic happens while it holds them.
+ work.scope(|work| {
+ if let Err(errors) = verify::verify_with(graph, work).and(verify::verify_frame_writes(graph, layout, work)) {
+ panic!(
+ "invalid graph after {after}:\n{errors}\n{}",
+ crate::ir::dump(graph, layout)
+ );
+ }
+ });
}
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/tests.rs b/Libraries/LibJS/JIT/Rust/src/passes/tests.rs
index 63d456350c1..30ce675f574 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/tests.rs
@@ -5,7 +5,7 @@
*/
use super::dominators::Dominators;
-use super::verify::verify;
+use super::verify::verify_with;
use crate::code::Repr;
use crate::ir::Block;
use crate::ir::BlockId;
@@ -15,6 +15,11 @@ use crate::ir::Node;
use crate::ir::NodeId;
use crate::ir::Op;
+/// The violated invariants of `graph`, one on each line (see `verify_with()`).
+fn verify(graph: &Graph) -> Result<(), String> {
+ verify_with(graph, &crate::test_work()).map_err(|errors| errors.to_string())
+}
+
fn node<'z>(graph: &mut Graph<'z>, op: Op<'z>, inputs: Vec<NodeId>, repr: Option<Repr>) -> NodeId {
graph.add_node(Node {
op,
diff --git a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
index b4ccad2f843..646c021cc1c 100644
--- a/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/passes/verify.rs
@@ -36,12 +36,14 @@
use ak::Zone;
use ak::ZoneVec;
+use core::fmt;
use super::dominators::Dominators;
use crate::bytecode::FrameLayout;
use crate::bytecode::Operand;
use crate::bytecode::RESERVED_REGISTER_COUNT;
use crate::code::Repr;
+use crate::debug_text::DebugText;
use crate::ir::BlockId;
use crate::ir::ElementsKind;
use crate::ir::Graph;
@@ -50,18 +52,22 @@ use crate::ir::NodeId;
use crate::ir::Op;
/// The descriptions of the violated invariants, one on each line.
-#[derive(Default)]
-struct Errors(String);
+struct Errors<'w>(DebugText<'w>);
-impl Errors {
- fn push(&mut self, message: String) {
+impl<'w> Errors<'w> {
+ fn new_in(work: &'w Zone) -> Self {
+ Self(DebugText::new_in(work))
+ }
+
+ /// Adds the description of a violated invariant. This is what `write!` calls.
+ fn write_fmt(&mut self, message: fmt::Arguments<'_>) {
if !self.0.is_empty() {
self.0.push('\n');
}
- self.0.push_str(&message);
+ self.0.write_fmt(message);
}
- fn finish(self) -> Result<(), String> {
+ fn finish(self) -> Result<(), DebugText<'w>> {
if self.0.is_empty() { Ok(()) } else { Err(self.0) }
}
}
@@ -77,8 +83,8 @@ struct Place {
/// Checks that `StoreSlot` writes frame memory only where something reads it: written constants, which live there,
/// the arguments the compiled function's legacy `arguments` shows, and the slots a node that reads the frame reads,
/// right before it. Merges and back edges never write frame memory: slots that differ get phis.
-pub fn verify_frame_writes(graph: &Graph, layout: &FrameLayout, work: &Zone) -> Result<(), String> {
- let mut errors = Errors::default();
+pub fn verify_frame_writes<'w>(graph: &Graph, layout: &FrameLayout, work: &'w Zone) -> Result<(), DebugText<'w>> {
+ let mut errors = Errors::new_in(work);
let mut nodes = ZoneVec::new_in(work);
for (index, block) in graph.blocks.iter().enumerate() {
nodes.assign(&block.body);
@@ -89,10 +95,11 @@ pub fn verify_frame_writes(graph: &Graph, layout: &FrameLayout, work: &Zone) ->
};
let operand = Operand::from_raw(slot).raw();
if graph.is_unwritten_slot(operand) {
- errors.push(format!(
+ write!(
+ errors,
"StoreSlot v{} in b{index} writes slot {operand}, which nothing writes (see `Graph::unwritten_slots`)",
node.0
- ));
+ );
}
let is_constant = operand >= layout.registers_and_locals_count && operand < layout.arguments_base();
if is_constant || graph.legacy_arguments.contains(&operand) {
@@ -119,64 +126,62 @@ pub fn verify_frame_writes(graph: &Graph, layout: &FrameLayout, work: &Zone) ->
|| matches!(op, Op::Suspend { .. })
});
if !reads_frame {
- errors.push(format!(
+ write!(
+ errors,
"StoreSlot v{} in b{index} writes a slot that no node reading the frame reads next",
node.0
- ));
+ );
}
}
}
errors.finish()
}
-/// Returns a description of every violated invariant, or `Ok` if there is none.
-pub fn verify(graph: &Graph) -> Result<(), String> {
- verify_with(graph, &Zone::new(1 << 30, c"JIT verifier"))
-}
-
-/// `verify()`, with `work` for its lists.
-pub fn verify_with(graph: &Graph, work: &Zone) -> Result<(), String> {
+/// Returns a description of every violated invariant, one on each line, or `Ok` if there is none. The description and
+/// the lists of the checks are in `work`.
+pub fn verify_with<'w>(graph: &Graph, work: &'w Zone) -> Result<(), DebugText<'w>> {
let places = verify_blocks(graph, work)?;
- verify_edges(graph)?;
+ verify_edges(graph, work)?;
verify_nodes(graph, &places, work)?;
verify_frame_states(graph, work)
}
/// Checks what each block holds, and returns where each node is.
-fn verify_blocks<'w>(graph: &Graph, work: &'w Zone) -> Result<ZoneVec<'w, Option<Place>>, String> {
- let mut errors = Errors::default();
+fn verify_blocks<'w>(graph: &Graph, work: &'w Zone) -> Result<ZoneVec<'w, Option<Place>>, DebugText<'w>> {
+ let mut errors = Errors::new_in(work);
let mut places: ZoneVec<Option<Place>> = ZoneVec::from_elem_in(None, graph.nodes.len(), work);
for (index, block) in graph.blocks.iter().enumerate() {
let block_id = BlockId::from_index(index);
let Some(control) = block.control else {
- errors.push(format!("b{index} has no control node"));
+ write!(errors, "b{index} has no control node");
continue;
};
if !graph.node(control).op.is_control() {
- errors.push(format!("b{index} ends in v{}, which is not a control node", control.0));
+ write!(errors, "b{index} ends in v{}, which is not a control node", control.0);
}
for phi in &block.phis {
if graph.node(*phi).op != Op::Phi {
- errors.push(format!("b{index} has v{} among its phis", phi.0));
+ write!(errors, "b{index} has v{} among its phis", phi.0);
}
if graph.node(*phi).inputs.len() != block.predecessors.len() {
- errors.push(format!(
+ write!(
+ errors,
"phi v{} of b{index} has {} inputs for {} predecessors",
phi.0,
graph.node(*phi).inputs.len(),
block.predecessors.len()
- ));
+ );
}
}
for node in &block.body {
let op = &graph.node(*node).op;
if *op == Op::Phi || op.is_control() || matches!(op, Op::Constant(_)) {
- errors.push(format!("b{index} has {} v{} in its body", op.name(), node.0));
+ write!(errors, "b{index} has {} v{} in its body", op.name(), node.0);
}
}
for (position, node) in graph.block_nodes(block_id).enumerate() {
match places[node.index()] {
- Some(other) => errors.push(format!("v{} is in b{} and in b{index}", node.0, other.block.0)),
+ Some(other) => write!(errors, "v{} is in b{} and in b{index}", node.0, other.block.0),
None => {
places[node.index()] = Some(Place {
block: block_id,
@@ -190,8 +195,8 @@ fn verify_blocks<'w>(graph: &Graph, work: &'w Zone) -> Result<ZoneVec<'w, Option
}
/// Checks the edges between blocks and their order.
-fn verify_edges(graph: &Graph) -> Result<(), String> {
- let mut errors = Errors::default();
+fn verify_edges<'w>(graph: &Graph, work: &'w Zone) -> Result<(), DebugText<'w>> {
+ let mut errors = Errors::new_in(work);
for (index, block) in graph.blocks.iter().enumerate() {
let block_id = BlockId::from_index(index);
for successor in graph.successors(block_id) {
@@ -203,38 +208,42 @@ fn verify_edges(graph: &Graph) -> Result<(), String> {
.filter(|predecessor| **predecessor == block_id)
.count();
if edges_out != edges_in {
- errors.push(format!(
+ write!(
+ errors,
"b{index} has {edges_out} edges to b{}, which lists it {edges_in} times",
successor.0
- ));
+ );
}
}
if !block.phis.is_empty() {
for predecessor in &block.predecessors {
if graph.successors(*predecessor).len() != 1 {
- errors.push(format!(
+ write!(
+ errors,
"b{index} has phis, but its predecessor b{} also leads elsewhere",
predecessor.0
- ));
+ );
}
}
}
for predecessor in &block.predecessors {
if !graph.successors(*predecessor).contains(&block_id) {
- errors.push(format!(
+ write!(
+ errors,
"b{index} lists b{} as a predecessor, which does not branch to it",
predecessor.0
- ));
+ );
}
// NB: Cold code comes after the code it rejoins.
if predecessor.index() >= index
&& !block.is_loop_header
&& !(graph.block(*predecessor).is_cold && !block.is_cold)
{
- errors.push(format!(
+ write!(
+ errors,
"b{index} is reached from the later b{} but is no loop header",
predecessor.0
- ));
+ );
}
}
}
@@ -243,10 +252,14 @@ fn verify_edges(graph: &Graph) -> Result<(), String> {
/// Checks that values are defined before their uses, and the rules of each
/// kind of node.
-fn verify_nodes(graph: &Graph, places: &[Option<Place>], work: &Zone) -> Result<(), String> {
- let mut errors = Errors::default();
+fn verify_nodes<'w>(graph: &Graph, places: &[Option<Place>], work: &'w Zone) -> Result<(), DebugText<'w>> {
+ let mut errors = Errors::new_in(work);
if graph.blocks.len() > Dominators::MAX_BLOCKS {
- return Err("the graph has more blocks than the tables of the dominators hold".to_string());
+ write!(
+ errors,
+ "the graph has more blocks than the tables of the dominators hold"
+ );
+ return errors.finish();
}
let dominators = &Dominators::of(graph, work);
let is_defined_before = |value: NodeId, block: BlockId, index: usize| -> bool {
@@ -267,33 +280,36 @@ fn verify_nodes(graph: &Graph, places: &[Option<Place>], work: &Zone) -> Result<
let block_id = BlockId::from_index(index);
let is_entry = graph.entries().any(|entry| entry == block_id);
if block.predecessors.is_empty() != is_entry {
- errors.push(format!(
+ write!(
+ errors,
"b{index} has {} predecessors, but is {}",
block.predecessors.len(),
if is_entry { "an entry" } else { "no entry" }
- ));
+ );
}
if !dominators.is_reachable(block_id) {
- errors.push(format!("b{index} is reachable from no entry"));
+ write!(errors, "b{index} is reachable from no entry");
continue;
}
for phi in &block.phis {
for (input, predecessor) in graph.node(*phi).inputs.iter().zip(&block.predecessors) {
if graph.node(*input).repr != graph.node(*phi).repr {
- errors.push(format!(
+ write!(
+ errors,
"phi v{} of b{index} is {:?}, but its input v{} is {:?}",
phi.0,
graph.node(*phi).repr,
input.0,
graph.node(*input).repr
- ));
+ );
}
let end = graph.block_nodes(*predecessor).count();
if !is_defined_before(*input, *predecessor, end) {
- errors.push(format!(
+ write!(
+ errors,
"phi v{} of b{index} uses v{} from b{}, where it is not defined",
phi.0, input.0, predecessor.0
- ));
+ );
}
}
}
@@ -304,19 +320,21 @@ fn verify_nodes(graph: &Graph, places: &[Option<Place>], work: &Zone) -> Result<
}
for input in &node.inputs {
if !is_defined_before(*input, block_id, position) {
- errors.push(format!(
+ write!(
+ errors,
"v{} ({}) in b{index} uses v{}, which is not defined before it",
node_id.0,
node.op.name(),
input.0
- ));
+ );
} else if graph.node(*input).repr.is_none() {
- errors.push(format!(
+ write!(
+ errors,
"v{} ({}) uses v{}, which has no value",
node_id.0,
node.op.name(),
input.0
- ));
+ );
}
}
// NB: Lazy exits of calls find their values after the call, but
@@ -324,51 +342,53 @@ fn verify_nodes(graph: &Graph, places: &[Option<Place>], work: &Zone) -> Result<
if let Some(frame_state) = node.frame_state {
for (slot, value) in graph.frame_state_values(frame_state, work) {
if graph.node(value).repr.is_none() && !matches!(graph.node(value).op, Op::VirtualObject { .. }) {
- errors.push(format!(
+ write!(
+ errors,
"the frame state of v{} has v{} for slot {slot}, which has no value",
node_id.0, value.0
- ));
+ );
}
// NB: Only the environments of virtual closures are cell addresses (see `VirtualObjectKind`).
if graph.node(value).repr == Some(Repr::Pointer) && slot != crate::ir::VIRTUAL_OBJECT_PROPERTY {
- errors.push(format!(
+ write!(
+ errors,
"the frame state of v{} has the cell address v{} for slot {slot}",
node_id.0, value.0
- ));
+ );
}
if !is_defined_before(value, block_id, position) {
- errors.push(format!(
+ write!(
+ errors,
"the frame state of v{} ({}) in b{index} has v{} for slot {slot}, which is not defined before it",
node_id.0,
node.op.name(),
value.0
- ));
+ );
}
}
}
- if let Some(message) = check_input_reprs(graph, node_id) {
- errors.push(message);
- }
+ check_input_reprs(graph, node_id, &mut errors);
if (node.op.can_eager_exit() || node.op.properties().can_lazy_exit) && node.frame_state.is_none() {
- errors.push(format!(
+ write!(
+ errors,
"v{} ({}) can exit, but has no frame state",
node_id.0,
node.op.name()
- ));
+ );
}
match node.op {
Op::Jump { .. } if !node.inputs.is_empty() => {
- errors.push(format!("v{} (Jump) has inputs", node_id.0));
+ write!(errors, "v{} (Jump) has inputs", node_id.0);
}
Op::Branch {
condition: crate::ir::BranchCondition::Shape(_),
..
- } => errors.push(format!("v{} branches on a shape", node_id.0)),
+ } => write!(errors, "v{} branches on a shape", node_id.0),
_ => {}
}
if let Op::CallSlowPath { .. } = node.op {
if node.frame_state.is_none() {
- errors.push(format!("v{} (CallSlowPath) has no frame state", node_id.0));
+ write!(errors, "v{} (CallSlowPath) has no frame state", node_id.0);
}
if matches!(
node.op,
@@ -378,10 +398,11 @@ fn verify_nodes(graph: &Graph, places: &[Option<Place>], work: &Zone) -> Result<
}
) && !block.is_cold
{
- errors.push(format!(
+ write!(
+ errors,
"v{} (CallSlowPath) is in b{index}, which is not cold",
node_id.0
- ));
+ );
}
}
if let Op::Refine { .. } = node.op {
@@ -389,21 +410,23 @@ fn verify_nodes(graph: &Graph, places: &[Option<Place>], work: &Zone) -> Result<
.iter()
.all(|other| matches!(graph.node(*other).op, Op::Refine { .. }));
if !at_head || block.predecessors.len() != 1 {
- errors.push(format!(
+ write!(
+ errors,
"v{} (Refine) is not at the head of b{index}, a block with one predecessor",
node_id.0
- ));
+ );
}
}
if let Some(index) = node.op.refined_input()
&& node.repr.is_some()
&& node.repr != graph.node(node.inputs[index]).repr
{
- errors.push(format!(
+ write!(
+ errors,
"v{} ({}) changes the representation of the value it refines",
node_id.0,
node.op.name()
- ));
+ );
}
// NB: Typed-array element accesses take the storage offset from
// its load or the check that it is valid, which they rely on.
@@ -415,11 +438,12 @@ fn verify_nodes(graph: &Graph, places: &[Option<Place>], work: &Zone) -> Result<
} = node.op
&& graph.node(node.inputs[0]).op != Op::TypedArrayDataAddress
{
- errors.push(format!(
+ write!(
+ errors,
"v{} ({}) takes no typed array data address",
node_id.0,
node.op.name()
- ));
+ );
}
if node.op == Op::TypedArrayDataAddress
&& !matches!(
@@ -427,10 +451,7 @@ fn verify_nodes(graph: &Graph, places: &[Option<Place>], work: &Zone) -> Result<
Op::LoadTypedArrayDataOffset | Op::CheckTypedArrayStorage
)
{
- errors.push(format!(
- "v{} (TypedArrayDataAddress) takes no storage offset",
- node_id.0
- ));
+ write!(errors, "v{} (TypedArrayDataAddress) takes no storage offset", node_id.0);
}
// A slow path's further outputs are where its call left them only
// until anything else runs.
@@ -444,10 +465,11 @@ fn verify_nodes(graph: &Graph, places: &[Option<Place>], work: &Zone) -> Result<
.all(|other| matches!(graph.node(other).op, Op::SlowPathOutput { .. }))
});
if !follows_call {
- errors.push(format!(
+ write!(
+ errors,
"v{} (SlowPathOutput) does not follow its slow path call v{} directly",
node_id.0, call.0
- ));
+ );
}
}
}
@@ -456,8 +478,8 @@ fn verify_nodes(graph: &Graph, places: &[Option<Place>], work: &Zone) -> Result<
}
/// Checks that frame states list each slot once.
-fn verify_frame_states(graph: &Graph, work: &Zone) -> Result<(), String> {
- let mut errors = Errors::default();
+fn verify_frame_states<'w>(graph: &Graph, work: &'w Zone) -> Result<(), DebugText<'w>> {
+ let mut errors = Errors::new_in(work);
let mut slots = ZoneVec::new_in(work);
for (index, frame_state) in graph.frame_states.iter().enumerate() {
slots.clear();
@@ -465,35 +487,42 @@ fn verify_frame_states(graph: &Graph, work: &Zone) -> Result<(), String> {
slots.extend_from_slice(&frame_state.in_frame);
slots.sort_unstable();
if slots.windows(2).any(|pair| pair[0] == pair[1]) {
- errors.push(format!("fs{index} lists a slot more than once"));
+ write!(errors, "fs{index} lists a slot more than once");
}
}
errors.finish()
}
-fn check_input_reprs(graph: &Graph, node_id: NodeId) -> Option<String> {
+/// Reports the first input of `node_id` that does not have the representation its op takes, or a wrong count of inputs.
+fn check_input_reprs(graph: &Graph, node_id: NodeId, errors: &mut Errors<'_>) {
let node = graph.node(node_id);
let expected = match node.op.info().inputs.reprs(node.inputs.len()) {
- Ok(expected) => expected?,
+ Ok(Some(expected)) => expected,
+ Ok(None) => return,
Err(count) => {
- return Some(format!(
+ write!(
+ errors,
"v{} ({}) has {} inputs, but takes {count}",
node_id.0,
node.op.name(),
node.inputs.len(),
- ));
+ );
+ return;
}
};
for (input, repr) in node.inputs.iter().zip(expected) {
- let actual = graph.node(*input).repr?;
+ let Some(actual) = graph.node(*input).repr else {
+ return;
+ };
if actual != repr {
- return Some(format!(
+ write!(
+ errors,
"v{} ({}) takes v{} as {repr:?}, but it is {actual:?}",
node_id.0,
node.op.name(),
input.0
- ));
+ );
+ return;
}
}
- None
}
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
index 468095be711..96f5cf421c3 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/mod.rs
@@ -75,6 +75,7 @@ use crate::tables::Run;
use ak::Zone;
use ak::ZoneVec;
use coalescing::Coalescing;
+use core::fmt;
use liveness::ValueLiveness;
use liveness::is_allocated_value;
use liveness::state_predecessor;
@@ -1134,71 +1135,95 @@ pub fn phi_spill_store(graph: &Graph, allocation: &Allocation, phi: NodeId) -> O
/// Prints the allocation of `graph` as text: every node with the moves
/// before it, the locations of its inputs and output, and its spill slot.
-pub fn dump_allocation(graph: &Graph, allocation: &Allocation) -> String {
- use std::fmt::Write;
- let location_name = |location: &Location| match location {
- Location::Register(register) if *register >= FPR_BASE => format!("f{}", register - FPR_BASE),
- Location::Register(register) => format!("r{register}"),
- Location::Stack(slot) => format!("s{slot}"),
- Location::Constant(bits) => format!("#{}", crate::ir::value::describe(*bits)),
- Location::Frame(slot) => format!("frame{slot}"),
- };
- /// Writes the text of each item to `out`, with ", " between them.
- fn write_list<T>(out: &mut String, items: &[T], text: impl Fn(&T) -> String) {
- for (index, item) in items.iter().enumerate() {
- if index != 0 {
- out.push_str(", ");
- }
- out.push_str(&text(item));
+pub fn dump_allocation<'a, 'z, 'w>(graph: &'a Graph<'z>, allocation: &'a Allocation<'w>) -> AllocationDump<'a, 'z, 'w> {
+ AllocationDump { graph, allocation }
+}
+
+/// The text of `dump_allocation()`.
+pub struct AllocationDump<'a, 'z, 'w> {
+ graph: &'a Graph<'z>,
+ allocation: &'a Allocation<'w>,
+}
+
+struct LocationName(Location);
+
+impl fmt::Display for LocationName {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self.0 {
+ Location::Register(register) if register >= FPR_BASE => write!(f, "f{}", register - FPR_BASE),
+ Location::Register(register) => write!(f, "r{register}"),
+ Location::Stack(slot) => write!(f, "s{slot}"),
+ Location::Constant(bits) => write!(f, "#{}", crate::ir::value::describe(bits)),
+ Location::Frame(slot) => write!(f, "frame{slot}"),
}
}
- let move_name = |m: &Move| format!("{} -> {}", location_name(&m.from), location_name(&m.to));
- let mut out = String::new();
- for index in 0..graph.blocks.len() {
- let block = BlockId::from_index(index);
- writeln!(out, "b{index}:").unwrap();
- for node_id in graph.block_nodes(block) {
- let node = allocation.node(node_id);
- if Some(node_id) == graph.block(block).control && !allocation.block_end_moves(block).is_empty() {
- out.push_str(" moves ");
- write_list(&mut out, allocation.block_end_moves(block), move_name);
- out.push('\n');
- }
- if !node.moves_before.is_empty() {
- out.push_str(" moves ");
- write_list(&mut out, node.moves_before, move_name);
- out.push('\n');
- }
- write!(out, " v{} {}", node_id.0, graph.node(node_id).op.name()).unwrap();
- if !node.inputs.is_empty() {
- out.push_str(" (");
- write_list(&mut out, node.inputs, location_name);
- out.push(')');
- }
- if let Some(output) = &node.output {
- write!(out, " -> {}", location_name(output)).unwrap();
- }
- if !node.temps.is_empty() {
- out.push_str(" temps ");
- write_list(&mut out, node.temps, |register| format!("r{register}"));
- }
- if let Some(slot) = node.spill_slot
- && graph.node(node_id).op != Op::Phi
- {
- write!(out, " spill s{slot}").unwrap();
+}
+
+impl fmt::Display for AllocationDump<'_, '_, '_> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ /// Writes the text of each item, with ", " between them.
+ fn write_list<T>(
+ f: &mut fmt::Formatter<'_>,
+ items: &[T],
+ write_item: impl Fn(&mut fmt::Formatter<'_>, &T) -> fmt::Result,
+ ) -> fmt::Result {
+ for (index, item) in items.iter().enumerate() {
+ if index != 0 {
+ f.write_str(", ")?;
+ }
+ write_item(f, item)?;
}
- if !node.exit_values.is_empty() {
- out.push_str(" exit {");
- write_list(&mut out, node.exit_values, |(slot, location)| {
- format!("{slot}={}", location_name(location))
- });
- out.push('}');
+ Ok(())
+ }
+ let write_move =
+ |f: &mut fmt::Formatter<'_>, m: &Move| write!(f, "{} -> {}", LocationName(m.from), LocationName(m.to));
+ let write_location = |f: &mut fmt::Formatter<'_>, location: &Location| write!(f, "{}", LocationName(*location));
+ let (graph, allocation) = (self.graph, self.allocation);
+ for index in 0..graph.blocks.len() {
+ let block = BlockId::from_index(index);
+ writeln!(f, "b{index}:")?;
+ for node_id in graph.block_nodes(block) {
+ let node = allocation.node(node_id);
+ if Some(node_id) == graph.block(block).control && !allocation.block_end_moves(block).is_empty() {
+ f.write_str(" moves ")?;
+ write_list(f, allocation.block_end_moves(block), write_move)?;
+ f.write_str("\n")?;
+ }
+ if !node.moves_before.is_empty() {
+ f.write_str(" moves ")?;
+ write_list(f, node.moves_before, write_move)?;
+ f.write_str("\n")?;
+ }
+ write!(f, " v{} {}", node_id.0, graph.node(node_id).op.name())?;
+ if !node.inputs.is_empty() {
+ f.write_str(" (")?;
+ write_list(f, node.inputs, write_location)?;
+ f.write_str(")")?;
+ }
+ if let Some(output) = &node.output {
+ write!(f, " -> {}", LocationName(*output))?;
+ }
+ if !node.temps.is_empty() {
+ f.write_str(" temps ")?;
+ write_list(f, node.temps, |f, register| write!(f, "r{register}"))?;
+ }
+ if let Some(slot) = node.spill_slot
+ && graph.node(node_id).op != Op::Phi
+ {
+ write!(f, " spill s{slot}")?;
+ }
+ if !node.exit_values.is_empty() {
+ f.write_str(" exit {")?;
+ write_list(f, node.exit_values, |f, (slot, location)| {
+ write!(f, "{slot}={}", LocationName(*location))
+ })?;
+ f.write_str("}")?;
+ }
+ f.write_str("\n")?;
}
- out.push('\n');
}
+ writeln!(f, "spill slots: {}", allocation.spill_slot_count)
}
- writeln!(out, "spill slots: {}", allocation.spill_slot_count).unwrap();
- out
}
#[cfg(test)]
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
index 70acc323ebe..a2a1a4102ae 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/tests.rs
@@ -72,7 +72,7 @@ fn straight_line_code() {
let graph = build(&program);
let allocation = allocate_and_verify(&graph);
assert_text(
- &dump_allocation(&graph, &allocation),
+ &dump_allocation(&graph, &allocation).to_string(),
"
b0:
v6 LoadSlot -> r0
@@ -112,7 +112,7 @@ fn values_live_across_calls_are_spilled_at_their_definition() {
assert_eq!(frame_home(&graph, argument), None);
assert!(allocation.node(argument).spill_slot.is_some());
assert_text(
- &dump_allocation(&graph, &allocation),
+ &dump_allocation(&graph, &allocation).to_string(),
"
b0:
v6 LoadSlot -> r0
@@ -149,7 +149,7 @@ fn values_loaded_from_unwritten_slots_are_reloaded_from_the_frame() {
assert_eq!(frame_home(&graph, argument), Some(a(0).raw()));
assert_eq!(allocation.node(argument).spill_slot, None);
assert_text(
- &dump_allocation(&graph, &allocation),
+ &dump_allocation(&graph, &allocation).to_string(),
"
b0:
v6 LoadSlot -> r0
@@ -293,7 +293,7 @@ fn swapping_loop_phis_go_through_a_temp_slot() {
// The loop header starts with the registers of the block entering the
// loop: the condition, a phi, stays in r0, with no reload in the loop.
assert_text(
- &dump_allocation(&graph, &allocation),
+ &dump_allocation(&graph, &allocation).to_string(),
"
b0:
v6 Jump
@@ -1087,7 +1087,7 @@ fn make_cold(graph: &mut Graph, blocks: &[BlockId]) {
graph.blocks[block.index()].is_cold = true;
}
crate::passes::edit::move_cold_blocks_last(graph, crate::test_zone());
- if let Err(errors) = crate::passes::verify::verify(graph) {
+ if let Err(errors) = crate::passes::verify::verify_with(graph, &crate::test_work()) {
panic!("{errors}\n{}", crate::ir::dump(graph, &test_layout()));
}
}
@@ -1159,7 +1159,7 @@ fn random_structured_programs_with_cold_blocks_allocate_correctly() {
graph.blocks[block.index()].is_cold = true;
}
crate::passes::edit::move_cold_blocks_last(&mut graph, crate::test_zone());
- if let Err(errors) = crate::passes::verify::verify(&graph) {
+ if let Err(errors) = crate::passes::verify::verify_with(&graph, &crate::test_work()) {
panic!("seed {seed}: {errors}\n{}", crate::ir::dump(&graph, &layout));
}
let registers = RegisterSet::test_configuration();
diff --git a/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs b/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs
index 6b3cf4e0f7b..300b8d486a7 100644
--- a/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs
+++ b/Libraries/LibJS/JIT/Rust/src/regalloc/verify.rs
@@ -18,6 +18,7 @@
use ak::Zone;
use ak::ZoneVec;
+use core::fmt;
use super::Allocation;
use super::Location;
@@ -27,6 +28,7 @@ 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::debug_text::DebugText;
use crate::ir::BlockId;
use crate::ir::Graph;
use crate::ir::NodeId;
@@ -199,7 +201,29 @@ fn stack_slot_count(allocation: &Allocation) -> usize {
count
}
-struct Verifier<'a> {
+/// What an error is about.
+#[derive(Clone, Copy)]
+enum Context {
+ Node(NodeId),
+ Input(NodeId, usize),
+ /// The exit value of a node for a slot.
+ ExitValue(NodeId, u32),
+ /// The moves at the end of a block.
+ EndOfBlock(BlockId),
+}
+
+impl fmt::Display for Context {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match *self {
+ Self::Node(node) => write!(f, "v{}", node.0),
+ Self::Input(node, index) => write!(f, "v{}, input {index}", node.0),
+ Self::ExitValue(node, slot) => write!(f, "v{}, exit value for slot {slot}", node.0),
+ Self::EndOfBlock(block) => write!(f, "end of b{}", block.0),
+ }
+ }
+}
+
+struct Verifier<'a, 'w> {
graph: &'a Graph<'a>,
registers: &'a RegisterSet,
allocation: &'a Allocation<'a>,
@@ -207,19 +231,24 @@ struct Verifier<'a> {
/// being computed.
checking: bool,
/// The errors, one on each line.
- errors: String,
- work: &'a Zone,
+ errors: DebugText<'w>,
+ work: &'w Zone,
}
/// Checks `allocation` against `graph`, returning a description of every
/// problem found.
-pub fn verify(graph: &Graph, registers: &RegisterSet, allocation: &Allocation, work: &Zone) -> Result<(), String> {
+pub fn verify<'w>(
+ graph: &Graph,
+ registers: &RegisterSet,
+ allocation: &Allocation,
+ work: &'w Zone,
+) -> Result<(), DebugText<'w>> {
let mut verifier = Verifier {
graph,
registers,
allocation,
checking: false,
- errors: String::new(),
+ errors: DebugText::new_in(work),
work,
};
let block_count = graph.blocks.len();
@@ -256,7 +285,7 @@ pub fn verify(graph: &Graph, registers: &RegisterSet, allocation: &Allocation, w
verifier.check_phi_inputs(block, &exit_states);
verifier.simulate_block(block, entry, &mut state, &mut exit);
}
- None => verifier.error(format!("b{} is unreachable", block.0)),
+ None => verifier.error(format_args!("b{} is unreachable", block.0)),
}
}
@@ -267,13 +296,13 @@ pub fn verify(graph: &Graph, registers: &RegisterSet, allocation: &Allocation, w
}
}
-impl Verifier<'_> {
- fn error(&mut self, message: String) {
+impl Verifier<'_, '_> {
+ fn error(&mut self, message: fmt::Arguments<'_>) {
if self.checking {
if !self.errors.is_empty() {
self.errors.push('\n');
}
- self.errors.push_str(&message);
+ self.errors.write_fmt(message);
}
}
@@ -353,7 +382,7 @@ impl Verifier<'_> {
for location in std::iter::once(output).chain(self.filled_slot(phi)) {
let found = self.read(exit, location);
if found != Some(self.content_of_value(input)) {
- self.error(format!(
+ self.error(format_args!(
"phi v{} in b{}: input from b{} should be {:?} in {location:?}, found {found:?}",
phi.0,
block.0,
@@ -380,10 +409,10 @@ impl Verifier<'_> {
}
}
- fn apply_moves(&mut self, state: &mut State, moves: &[Move], context: &str) {
+ fn apply_moves(&mut self, state: &mut State, moves: &[Move], context: Context) {
for m in moves {
if matches!(m.to, Location::Constant(_) | Location::Frame(_)) {
- self.error(format!("{context}: move into {:?}", m.to));
+ self.error(format_args!("{context}: move into {:?}", m.to));
continue;
}
self.check_location(m.to, context);
@@ -392,14 +421,14 @@ impl Verifier<'_> {
state.insert(m.to, content);
}
None => {
- self.error(format!("{context}: move reads {:?}, which holds nothing", m.from));
+ self.error(format_args!("{context}: move reads {:?}, which holds nothing", m.from));
state.remove(m.to);
}
}
}
}
- fn check_location(&mut self, location: Location, context: &str) {
+ fn check_location(&mut self, location: Location, context: Context) {
if let Location::Register(register) = location
&& !self
.registers
@@ -410,28 +439,28 @@ impl Verifier<'_> {
.allocatable(super::RegisterClass::Float)
.contains(register)
{
- self.error(format!("{context}: r{register} is not allocatable"));
+ self.error(format_args!("{context}: r{register} is not allocatable"));
}
}
- fn expect(&mut self, state: &State, location: Location, value: NodeId, context: &str) {
+ fn expect(&mut self, state: &State, location: Location, value: NodeId, context: Context) {
let expected = self.content_of_value(value);
let found = self.read(state, location);
if found != Some(expected) {
- self.error(format!(
+ self.error(format_args!(
"{context}: expected {expected:?} in {location:?}, found {found:?}"
));
}
}
- fn check_exit_values(&mut self, state: &State, node: NodeId, context: &str) {
+ fn check_exit_values(&mut self, state: &State, node: NodeId, context: Context) {
let Some(frame_state) = self.graph.node(node).frame_state else {
return;
};
let expected_count = self.graph.frame_state_values(frame_state, self.work).count();
let exit_values = self.allocation.node(node).exit_values;
if expected_count != exit_values.len() {
- self.error(format!(
+ self.error(format_args!(
"{context}: exit has {} values, frame state {}",
exit_values.len(),
expected_count
@@ -442,16 +471,11 @@ impl Verifier<'_> {
self.graph.frame_state_values(frame_state, self.work).zip(exit_values)
{
if slot != *exit_slot {
- self.error(format!(
+ self.error(format_args!(
"{context}: exit value for slot {exit_slot}, frame state slot {slot}"
));
}
- self.expect(
- state,
- *location,
- value,
- &format!("{context}, exit value for slot {slot}"),
- );
+ self.expect(state, *location, value, Context::ExitValue(node, slot));
}
}
@@ -476,7 +500,7 @@ impl Verifier<'_> {
self.simulate_node(state, *node);
}
let end_moves = self.allocation.block_end_moves(block);
- self.apply_moves(state, end_moves, &format!("end of b{}", block.0));
+ self.apply_moves(state, end_moves, Context::EndOfBlock(block));
self.simulate_node(state, self.graph.control_id(block));
state.store(out);
}
@@ -484,22 +508,22 @@ impl Verifier<'_> {
fn simulate_node(&mut self, state: &mut State, node_id: NodeId) {
let node = self.graph.node(node_id);
let allocation = self.allocation.node(node_id);
- let context = format!("v{}", node_id.0);
+ let context = Context::Node(node_id);
debug_assert!(node.op != Op::Phi);
- self.apply_moves(state, allocation.moves_before, &context);
+ self.apply_moves(state, allocation.moves_before, context);
if let Op::StoreSlot { slot } = node.op
&& self.graph.is_unwritten_slot(slot)
{
- self.error(format!("{context}: stores to slot {slot}, which nothing writes"));
+ self.error(format_args!("{context}: stores to slot {slot}, which nothing writes"));
}
if allocation.inputs.len() != node.inputs.len() {
- self.error(format!("{context}: wrong number of input locations"));
+ self.error(format_args!("{context}: wrong number of input locations"));
return;
}
let lowering = lowering_info(node);
if allocation.temps.len() != usize::from(lowering.temps) {
- self.error(format!(
+ self.error(format_args!(
"{context}: {} temps, but its lowering takes {}",
allocation.temps.len(),
lowering.temps
@@ -508,7 +532,7 @@ impl Verifier<'_> {
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) {
- self.error(format!("{context}: input {index} is not the constant {bits:#x}"));
+ self.error(format_args!("{context}: input {index} is not the constant {bits:#x}"));
}
continue;
}
@@ -516,23 +540,23 @@ impl Verifier<'_> {
// them from where they are.
let reads_input_anywhere = lowering.inputs.get(index) == InputConstraint::Anywhere;
if !matches!(location, Location::Register(_)) && !reads_input_anywhere {
- self.error(format!("{context}: input {index} is not in a register"));
+ self.error(format_args!("{context}: input {index} is not in a register"));
}
if let InputConstraint::Fixed(register) = self.registers.resolve(lowering.inputs.get(index), false)
&& *location != Location::Register(self.registers.fixed(register))
{
- self.error(format!("{context}: input {index} is not in its fixed register"));
+ self.error(format_args!("{context}: input {index} is not in its fixed register"));
}
- self.check_location(*location, &context);
- self.expect(state, *location, *input, &format!("{context}, input {index}"));
+ self.check_location(*location, context);
+ self.expect(state, *location, *input, Context::Input(node_id, index));
}
// 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.
for temp in allocation.temps {
- self.check_location(Location::Register(*temp), &context);
+ self.check_location(Location::Register(*temp), context);
if allocation.inputs.contains(&Location::Register(*temp)) {
- self.error(format!("{context}: temp r{temp} is also an input"));
+ self.error(format_args!("{context}: temp r{temp} is also an input"));
}
state.remove(Location::Register(*temp));
}
@@ -548,19 +572,21 @@ impl Verifier<'_> {
// NB: Cloning the state instead would take time quadratic in the size of code that keeps many values in
// their stack slots past many nodes.
let previous = state.remove(output);
- self.check_exit_values(state, node_id, &context);
+ self.check_exit_values(state, node_id, context);
if let Some(previous) = previous {
state.insert(output, previous);
}
} else {
- self.check_exit_values(state, node_id, &context);
+ self.check_exit_values(state, node_id, context);
}
match (node.repr.is_some(), allocation.output) {
(true, Some(Location::Register(register))) => {
- self.check_location(Location::Register(register), &context);
+ self.check_location(Location::Register(register), context);
if super::RegisterClass::of_register(register) != super::RegisterClass::of(node.repr) {
- self.error(format!("{context}: the output is in a register of the other class"));
+ self.error(format_args!(
+ "{context}: the output is in a register of the other class"
+ ));
}
state.insert(Location::Register(register), self.content_of_value(node_id));
if let Some(slot) = allocation.spill_slot {
@@ -568,7 +594,7 @@ impl Verifier<'_> {
}
}
(false, None) => {}
- (_, output) => self.error(format!("{context}: unexpected output location {output:?}")),
+ (_, output) => self.error(format_args!("{context}: unexpected output location {output:?}")),
}
}
}
diff --git a/Libraries/LibJS/Rust/src/jit/runtime_info.rs b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
index bdd4e269d02..dfc4f25aff7 100644
--- a/Libraries/LibJS/Rust/src/jit/runtime_info.rs
+++ b/Libraries/LibJS/Rust/src/jit/runtime_info.rs
@@ -104,7 +104,7 @@ impl RuntimeFunctionAddresses {
Self {
slow_paths: (0..=u8::MAX)
.map_while(OpCode::from_u8)
- .map(|opcode| slow_path_symbol(opcode).map_or(0, |symbol| address(&symbol)))
+ .map(|opcode| slow_path_symbol(opcode).map_or(0, |symbol| address(&symbol.to_string())))
.collect(),
try_get_by_id_cache: address("asm_try_get_by_id_cache"),
try_put_by_id_cache: address("asm_try_put_by_id_cache"),
diff --git a/Libraries/LibJS/Rust/src/jit/tier_up.rs b/Libraries/LibJS/Rust/src/jit/tier_up.rs
index a24fd0d622b..663b8f0dfec 100644
--- a/Libraries/LibJS/Rust/src/jit/tier_up.rs
+++ b/Libraries/LibJS/Rust/src/jit/tier_up.rs
@@ -425,10 +425,10 @@ fn finish_compile(
}
};
vm.jit.count_coverage("compile");
- for key in &compiled.coverage {
+ for key in compiled.coverage() {
vm.jit.count_coverage(key);
}
- if let Some(dump) = &compiled.dump {
+ if let Some(dump) = compiled.dump() {
eprintln!("JIT code for {}:\n{dump}", super::describe_executable(&executable));
}
if let Some(memory) = memory {