Truly independent web browser
LibJS: Let specializations cover only one instruction
Andreas Klinga8c043ebc5e9
diff --git a/Libraries/LibJS/Flap/src/bytecode.rs b/Libraries/LibJS/Flap/src/bytecode.rsindex 9d5c6d23505..00d0b578ba9 100644--- a/Libraries/LibJS/Flap/src/bytecode.rs+++ b/Libraries/LibJS/Flap/src/bytecode.rs@@ -101,39 +101,34 @@ pub(crate) fn validate_specializations(let ops = ops.iter().map(|op| (op.name.as_str(), op)).collect::<HashMap<_, _>>();let mut names = ops.keys().copied().map(str::to_string).collect::<HashSet<_>>();for specialization in specializations {- for (component_index, component) in specialization.components.iter().enumerate() {- let op = ops- .get(component.bytecode.as_str())- .ok_or_else(|| format!("specialization references unknown bytecode '{}'", component.bytecode))?;- if component_index + 1 != specialization.components.len() && op.is_terminator {+ let op = ops.get(specialization.bytecode.as_str()).ok_or_else(|| {+ format!(+ "specialization references unknown bytecode '{}'",+ specialization.bytecode+ )+ })?;+ let mut parameters = HashSet::new();+ for parameter in &specialization.parameters {+ if !parameters.insert(parameter.name.as_str()) {return Err(format!(- "terminating bytecode '{}' may only be the final specialization component",- component.bytecode+ "specialization repeats parameter '{}.{}'",+ specialization.bytecode, parameter.name));}- let mut parameters = HashSet::new();- for parameter in &component.parameters {- if !parameters.insert(parameter.name.as_str()) {- return Err(format!(- "specialization repeats parameter '{}.{}'",- component.bytecode, parameter.name- ));- }- let field_name = format!("m_{}", parameter.name);- let field = op.fields.iter().find(|field| field.name == field_name).ok_or_else(|| {- format!(- "specialization parameter '{}.{}' does not name a bytecode field",- component.bytecode, parameter.name- )- })?;- match parameter.constraint {- SpecializationConstraint::Int32 | SpecializationConstraint::Undefined => {- if field.ty != "Operand" || field.is_array {- return Err(format!(- "constant constraint requires an Operand field, but '{}.{}' is {}",- component.bytecode, parameter.name, field.ty- ));- }+ let field_name = format!("m_{}", parameter.name);+ let field = op.fields.iter().find(|field| field.name == field_name).ok_or_else(|| {+ format!(+ "specialization parameter '{}.{}' does not name a bytecode field",+ specialization.bytecode, parameter.name+ )+ })?;+ match parameter.constraint {+ SpecializationConstraint::Int32 | SpecializationConstraint::Undefined => {+ if field.ty != "Operand" || field.is_array {+ return Err(format!(+ "constant constraint requires an Operand field, but '{}.{}' is {}",+ specialization.bytecode, parameter.name, field.ty+ ));}}}@@ -291,19 +286,6 @@ mod tests {assert_eq!(error, "handler 'Put' has 2 parameter names but 1 parameter types");}- #[test]- fn validates_pair_specialization_constraints() {- let source = r#"-handler Increment(dst: inout Operand) { dispatch_next; }-handler JumpLessThan(lhs: Operand, rhs: Operand) @terminator { exit; }-specialize Increment() + JumpLessThan(rhs: Int32);-"#;- let ops = crate::metadata::parse_flap_metadata("test.flap", source).unwrap();- let specializations = crate::metadata::parse_specializations("test.flap", source).unwrap();-- validate_specializations(&ops, &specializations).unwrap();- }-#[test]fn rejects_duplicate_derived_specialization_names() {let source = r#"diff --git a/Libraries/LibJS/Flap/src/frontend/parser.rs b/Libraries/LibJS/Flap/src/frontend/parser.rsindex b9b66cce4fe..4662c01c909 100644--- a/Libraries/LibJS/Flap/src/frontend/parser.rs+++ b/Libraries/LibJS/Flap/src/frontend/parser.rs@@ -1803,7 +1803,7 @@ handler Mod(lhs: Value, rhs: Value) {let program = parse("test.flap","-specialize Increment() + JumpLessThan(rhs: Int32);+specialize JumpLessThan(rhs: Int32);handler Increment(dst: inout Operand) { dispatch_next; }",)diff --git a/Libraries/LibJS/Flap/src/frontend/specialize.rs b/Libraries/LibJS/Flap/src/frontend/specialize.rsindex ea3edceb9ee..6ffa1096d63 100644--- a/Libraries/LibJS/Flap/src/frontend/specialize.rs+++ b/Libraries/LibJS/Flap/src/frontend/specialize.rs@@ -8,12 +8,12 @@use super::ast::{Block, Declaration, ElseContinuation, Expression, ExpressionKind, HandlerDeclaration, Parameter, Pattern, Program,- ScalarMatchArm, Statement, StatementKind, ValueMatchArm,+ ScalarMatchArm, StatementKind, ValueMatchArm,};use super::diagnostic::{Diagnostic, SourceLocation, SourceSpan};use crate::hash::HashMap;use crate::metadata::{SpecializedInstruction, SpecializedParameterBinding};-use crate::types::{BlockTemperature, ParameterMode, Type};+use crate::types::{ParameterMode, Type};pub(crate) fn expand_declarative_specializations(filename: &str,@@ -58,9 +58,8 @@ pub(crate) fn expand_declarative_specializations(let mut parameters = Vec::<Parameter>::new();for field in &specialization.definition.fields {let field_name = field.name.strip_prefix("m_").unwrap_or(&field.name);- let source_parameter = specialization.components.iter().find_map(|component| {- let handler = handlers.get(&component.bytecode)?;- component.parameters.iter().find_map(|(source_name, binding)| {+ let source_parameter = handlers.get(&specialization.bytecode).and_then(|handler| {+ specialization.parameters.iter().find_map(|(source_name, binding)| {if binding != &SpecializedParameterBinding::Field(field_name.to_string()) {return None;}@@ -93,105 +92,64 @@ pub(crate) fn expand_declarative_specializations(});}- let mut component_bodies = Vec::with_capacity(specialization.components.len());- for component in &specialization.components {- let handler = handlers.get(&component.bytecode).ok_or_else(|| {- Diagnostic::new(- filename,- fallback_span,- format!("specialization references unknown handler '{}'", component.bytecode),- )- })?;- for (source_name, binding) in &component.parameters {- if binding != &SpecializedParameterBinding::Undefined {- continue;- }- let source_parameter = handler- .parameters- .iter()- .find(|parameter| parameter.name == *source_name)- .ok_or_else(|| {- Diagnostic::new(- filename,- handler.span,- format!(- "specialization parameter '{}.{source_name}' has no source parameter",- component.bytecode- ),- )- })?;- if source_parameter.mode != ParameterMode::In {- return Err(Diagnostic::new(- filename,- source_parameter.span,- format!(- "cannot constrain output parameter '{}.{source_name}' to Undefined",- component.bytecode- ),- ));- }+ let handler = handlers.get(&specialization.bytecode).ok_or_else(|| {+ Diagnostic::new(+ filename,+ fallback_span,+ format!(+ "specialization references unknown handler '{}'",+ specialization.bytecode+ ),+ )+ })?;+ for (source_name, binding) in &specialization.parameters {+ if binding != &SpecializedParameterBinding::Undefined {+ continue;}- let substitutions = component+ let source_parameter = handler.parameters.iter()- .map(|(source_name, binding)| {- let expression = match binding {- SpecializedParameterBinding::Field(name) => ExpressionKind::Name(name.clone()),- SpecializedParameterBinding::Undefined => ExpressionKind::Name("Value<Undefined>".to_string()),- };- (source_name.clone(), expression)- })- .collect::<HashMap<_, _>>();- let mut body = handler.body.clone();- substitute_block_parameters(&mut body, &substitutions);- component_bodies.push(body);- }-- let span = component_bodies.first().map(|body| body.span).unwrap_or(fallback_span);- let body = if component_bodies.len() == 1 {- component_bodies.pop().unwrap()- } else {- let continuation_names = (0..component_bodies.len())- .map(|index| format!("__specialization_component_{index}"))- .collect::<Vec<_>>();- let mut statements = Vec::with_capacity(component_bodies.len() + 1);- for (index, mut body) in component_bodies.into_iter().enumerate() {- if let Some(next) = continuation_names.get(index + 1) {- replace_dispatch_next(&mut body, next);- }- statements.push(Statement::new(- StatementKind::Continuation {- name: continuation_names[index].clone(),- temperature: BlockTemperature::Default,- parameters: Vec::new(),- body,- },- span,+ .find(|parameter| parameter.name == *source_name)+ .ok_or_else(|| {+ Diagnostic::new(+ filename,+ handler.span,+ format!(+ "specialization parameter '{}.{source_name}' has no source parameter",+ specialization.bytecode+ ),+ )+ })?;+ if source_parameter.mode != ParameterMode::In {+ return Err(Diagnostic::new(+ filename,+ source_parameter.span,+ format!(+ "cannot constrain output parameter '{}.{source_name}' to Undefined",+ specialization.bytecode+ ),));}- statements.push(Statement::new(- StatementKind::ContinuationJump {- target: continuation_names[0].clone(),- arguments: Vec::new(),- },- span,- ));- Block {- statements,- value: None,- span,- }- };- let temperature = match specialization.components.as_slice() {- [component] => handlers[&component.bytecode].temperature,- _ => BlockTemperature::Default,- };+ }+ let substitutions = specialization+ .parameters+ .iter()+ .map(|(source_name, binding)| {+ let expression = match binding {+ SpecializedParameterBinding::Field(name) => ExpressionKind::Name(name.clone()),+ SpecializedParameterBinding::Undefined => ExpressionKind::Name("Value<Undefined>".to_string()),+ };+ (source_name.clone(), expression)+ })+ .collect::<HashMap<_, _>>();+ let mut body = handler.body.clone();+ substitute_block_parameters(&mut body, &substitutions);program.declarations.push(Declaration::Handler(HandlerDeclaration {name: specialization.definition.name.clone(),parameters,- temperature,+ temperature: handler.temperature,+ span: body.span,body,- span,}));}Ok(())@@ -356,71 +314,13 @@ fn substitute_block_parameters(block: &mut Block, substitutions: &HashMap<String}}-fn replace_dispatch_next(block: &mut Block, next: &str) {- for statement in &mut block.statements {- if matches!(- &statement.kind,- StatementKind::Expression(Expression {- kind: ExpressionKind::Name(name),- ..- }) if name == "dispatch_next"- ) || matches!(- &statement.kind,- StatementKind::Expression(Expression {- kind: ExpressionKind::Call { callee, arguments },- ..- }) if callee == "dispatch_next" && arguments.is_empty()- ) {- statement.kind = StatementKind::ContinuationJump {- target: next.to_string(),- arguments: Vec::new(),- };- continue;- }- match &mut statement.kind {- StatementKind::GuardLet { failure, .. }- | StatementKind::FallibleCall { failure, .. }- | StatementKind::Guard { failure, .. } => replace_dispatch_in_else(failure, next),- StatementKind::ValueMatch { arms, fallback, .. } => {- for arm in arms {- replace_dispatch_next(&mut arm.body, next);- }- replace_dispatch_next(&mut fallback.body, next);- }- StatementKind::ScalarMatch { arms, fallback, .. } => {- for arm in arms {- replace_dispatch_next(&mut arm.body, next);- }- replace_dispatch_next(fallback, next);- }- StatementKind::Continuation { body, .. } | StatementKind::While { body, .. } => {- replace_dispatch_next(body, next);- }- StatementKind::If {- then_body, else_body, ..- } => {- replace_dispatch_next(then_body, next);- if let Some(else_body) = else_body {- replace_dispatch_next(else_body, next);- }- }- _ => {}- }- }-}--fn replace_dispatch_in_else(continuation: &mut ElseContinuation, next: &str) {- if let ElseContinuation::Block { body, .. } = continuation {- replace_dispatch_next(body, next);- }-}-#[cfg(test)]mod tests {use super::*;+ use crate::types::BlockTemperature;#[test]- fn preserves_single_component_handler_temperature() {+ fn preserves_handler_temperature() {let source = "handler Source(src: Operand) @cold { dispatch_next; }";let mut program = super::super::parser::parse("test.flap", source).unwrap();let operations = crate::metadata::parse_flap_metadata("test.flap", source).unwrap();@@ -463,7 +363,8 @@ mod tests {opcode: None,is_fallback: false,},- components: Vec::new(),+ bytecode: String::new(),+ parameters: std::collections::HashMap::new(),}];let error = expand_declarative_specializations("test.flap", &mut program, &specializations).unwrap_err();@@ -494,13 +395,11 @@ mod tests {opcode: None,is_fallback: false,},- components: vec![crate::metadata::SpecializedComponentLayout {- bytecode: "Source".to_string(),- parameters: std::collections::HashMap::from([(- "missing".to_string(),- SpecializedParameterBinding::Field("field".to_string()),- )]),- }],+ bytecode: "Source".to_string(),+ parameters: std::collections::HashMap::from([(+ "missing".to_string(),+ SpecializedParameterBinding::Field("field".to_string()),+ )]),}];let error = expand_declarative_specializations("test.flap", &mut program, &specializations).unwrap_err();diff --git a/Libraries/LibJS/Flap/src/lib.rs b/Libraries/LibJS/Flap/src/lib.rsindex 86ccecc9b8c..e3fc32624a9 100644--- a/Libraries/LibJS/Flap/src/lib.rs+++ b/Libraries/LibJS/Flap/src/lib.rs@@ -996,20 +996,13 @@ handler Outer() {}#[test]- fn compiles_declarative_single_and_fused_specializations() {+ fn compiles_declarative_specializations() {let source = r#"handler Copy(dst: out Operand, src: in Operand) {store(dst, load(src));dispatch_next;}-handler Touch(src: in Operand) {- let value = load(src);- assert(extract_tag(value) != 0);- dispatch_next;-}specialize Copy(src: Int32);-specialize Copy() + Touch();-specialize Copy() + Touch() + Touch();"#;for architecture in [Architecture::X86_64, Architecture::Aarch64] {@@ -1027,13 +1020,6 @@ specialize Copy() + Touch() + Touch();}).expect("declarative specializations should prepare");assert!(prepared.handlers.iter().any(|handler| handler.name() == "CopySrcInt32"));- assert!(prepared.handlers.iter().any(|handler| handler.name() == "CopyTouch"));- assert!(- prepared- .handlers- .iter()- .any(|handler| { handler.name() == "CopyTouchTouch" })- );compiler.lower(&prepared)diff --git a/Libraries/LibJS/Flap/src/metadata.rs b/Libraries/LibJS/Flap/src/metadata.rsindex 61f619229c5..d19059565d4 100644--- a/Libraries/LibJS/Flap/src/metadata.rs+++ b/Libraries/LibJS/Flap/src/metadata.rs@@ -147,14 +147,9 @@ pub struct SpecializationParameter {}#[derive(Debug, Clone, PartialEq, Eq)]-pub struct SpecializationComponent {+pub struct Specialization {pub bytecode: String,pub parameters: Vec<SpecializationParameter>,-}--#[derive(Debug, Clone, PartialEq, Eq)]-pub struct Specialization {- pub components: Vec<SpecializationComponent>,pub name: Option<String>,}@@ -164,32 +159,24 @@ pub enum SpecializedParameterBinding {Undefined,}-#[derive(Debug, Clone)]-pub struct SpecializedComponentLayout {- pub bytecode: String,- pub parameters: HashMap<String, SpecializedParameterBinding>,-}-#[derive(Debug, Clone)]pub struct SpecializedInstruction {pub definition: InstructionDefinition,- pub components: Vec<SpecializedComponentLayout>,+ pub bytecode: String,+ pub parameters: HashMap<String, SpecializedParameterBinding>,}pub fn specialization_name(specialization: &Specialization) -> String {if let Some(name) = &specialization.name {return name.clone();}- let mut name = String::new();- for component in &specialization.components {- name.push_str(&component.bytecode);- for parameter in &component.parameters {- name.push_str(¶meter.name[..1].to_ascii_uppercase());- name.push_str(¶meter.name[1..]);- match parameter.constraint {- SpecializationConstraint::Int32 => name.push_str("Int32"),- SpecializationConstraint::Undefined => name.push_str("Undefined"),- }+ let mut name = specialization.bytecode.clone();+ for parameter in &specialization.parameters {+ name.push_str(¶meter.name[..1].to_ascii_uppercase());+ name.push_str(¶meter.name[1..]);+ match parameter.constraint {+ SpecializationConstraint::Int32 => name.push_str("Int32"),+ SpecializationConstraint::Undefined => name.push_str("Undefined"),}}name@@ -559,10 +546,8 @@ fn parse_specialization(source_name: &str, line: usize, source: &str) -> Result<index: 0,};parser.expect("specialize")?;- let mut components = vec![parser.parse_component()?];- while parser.consume("+") {- components.push(parser.parse_component()?);- }+ let bytecode = parser.identifier("bytecode name")?.to_string();+ let parameters = parser.parse_parameters()?;let name = if parser.consume("as") {Some(parser.identifier("specialization name")?.to_string())} else {@@ -572,7 +557,11 @@ fn parse_specialization(source_name: &str, line: usize, source: &str) -> Result<if parser.index != tokens.len() {return Err(parser.error("unexpected token after specialization declaration"));}- Ok(Specialization { components, name })+ Ok(Specialization {+ bytecode,+ parameters,+ name,+ })}fn tokenize_specialization(source_name: &str, line: usize, source: &str) -> Result<Vec<String>, ParseError> {@@ -589,7 +578,7 @@ fn tokenize_specialization(source_name: &str, line: usize, source: &str) -> Resuif character.is_whitespace() {continue;}- if matches!(character, '(' | ')' | ',' | ':' | '+' | ';') {+ if matches!(character, '(' | ')' | ',' | ':' | ';') {tokens.push(character.to_string());} else {return Err(ParseError::new(@@ -648,8 +637,7 @@ impl SpecializationParser<'_> {Ok(&self.tokens[self.index - 1])}- fn parse_component(&mut self) -> Result<SpecializationComponent, ParseError> {- let bytecode = self.identifier("bytecode name")?.to_string();+ fn parse_parameters(&mut self) -> Result<Vec<SpecializationParameter>, ParseError> {self.expect("(")?;let mut parameters = Vec::new();while !self.consume(")") {@@ -662,7 +650,7 @@ impl SpecializationParser<'_> {}self.expect(",")?;}- Ok(SpecializationComponent { bytecode, parameters })+ Ok(parameters)}fn parse_constraint(&mut self) -> Result<SpecializationConstraint, ParseError> {@@ -872,69 +860,59 @@ pub fn derive_specialized_instructions(for specialization in specializations {let name = specialization_name(specialization);+ let op = ops_by_name.get(specialization.bytecode.as_str()).ok_or_else(|| {+ format!(+ "specialization references unknown bytecode '{}'",+ specialization.bytecode+ )+ })?;+ let constraints = specialization+ .parameters+ .iter()+ .map(|parameter| (parameter.name.as_str(), ¶meter.constraint))+ .collect::<HashMap<_, _>>();let mut fields = Vec::new();- let mut components = Vec::with_capacity(specialization.components.len());- let is_fused = specialization.components.len() > 1;- for (component_index, component) in specialization.components.iter().enumerate() {- let op = ops_by_name- .get(component.bytecode.as_str())- .ok_or_else(|| format!("specialization references unknown bytecode '{}'", component.bytecode))?;- let constraints = component- .parameters- .iter()- .map(|parameter| (parameter.name.as_str(), ¶meter.constraint))- .collect::<HashMap<_, _>>();- let mut parameters = HashMap::new();-- for field in user_fields(op) {- let source_name = field.name.strip_prefix("m_").unwrap_or(&field.name);- let constraint = constraints.get(source_name).copied();- let binding = match constraint {- Some(SpecializationConstraint::Undefined) => SpecializedParameterBinding::Undefined,- constraint => {- let specialized_name = if is_fused {- format!("c{component_index}_{source_name}")- } else {- source_name.to_string()- };- let ty = match constraint {- Some(SpecializationConstraint::Int32) => "i32",- _ => field.ty.as_str(),- };- fields.push(Field {- name: format!("m_{specialized_name}"),- ty: ty.to_string(),- is_array: field.is_array,- mode: field.mode,- });- SpecializedParameterBinding::Field(specialized_name)- }- };- parameters.insert(source_name.to_string(), binding);- }- components.push(SpecializedComponentLayout {- bytecode: component.bytecode.clone(),- parameters,- });+ let mut parameters = HashMap::new();++ for field in user_fields(op) {+ let source_name = field.name.strip_prefix("m_").unwrap_or(&field.name);+ let constraint = constraints.get(source_name).copied();+ let binding = match constraint {+ Some(SpecializationConstraint::Undefined) => SpecializedParameterBinding::Undefined,+ constraint => {+ let ty = match constraint {+ Some(SpecializationConstraint::Int32) => "i32",+ _ => field.ty.as_str(),+ };+ fields.push(Field {+ name: format!("m_{source_name}"),+ ty: ty.to_string(),+ is_array: field.is_array,+ mode: field.mode,+ });+ SpecializedParameterBinding::Field(source_name.to_string())+ }+ };+ parameters.insert(source_name.to_string(), binding);}- let last_component = specialization- .components- .last()- .expect("specializations contain at least one component");let mut definition = InstructionDefinition {name,parent: "Instruction".to_string(),fields,- is_terminator: ops_by_name[last_component.bytecode.as_str()].is_terminator,- falls_through: ops_by_name[last_component.bytecode.as_str()].falls_through,+ is_terminator: op.is_terminator,+ falls_through: op.falls_through,layout: OpLayout::default(),array: None,opcode: None,is_fallback: false,};validate_op(&mut definition)?;- derived.push(SpecializedInstruction { definition, components });+ derived.push(SpecializedInstruction {+ definition,+ bytecode: specialization.bytecode.clone(),+ parameters,+ });}Ok(derived)@@ -1058,29 +1036,24 @@ handler Second() { dispatch_next; }}#[test]- fn parses_specializations_of_arbitrary_length() {+ fn parses_specializations() {let specializations = parse_specializations("test.flap",r#"specialize Add(rhs: Int32);-specialize Increment()- + JumpLessThan(rhs: Int32);-specialize Mov() + Add(rhs: Undefined)- + JumpIf(condition: Int32) as HotLoop;-specialize A() + B() + C() + D();+specialize JumpIf(+ condition: Int32) as HotLoop;"#,).unwrap();- assert_eq!(specializations.len(), 4);- assert_eq!(specializations[1].components.len(), 2);+ assert_eq!(specializations.len(), 2);+ assert_eq!(specializations[0].bytecode, "Add");assert_eq!(- specializations[1].components[1].parameters[0].constraint,+ specializations[0].parameters[0].constraint,SpecializationConstraint::Int32);- assert_eq!(specializations[2].components.len(), 3);- assert_eq!(specializations[2].name.as_deref(), Some("HotLoop"));- assert_eq!(specializations[3].components.len(), 4);+ assert_eq!(specializations[1].name.as_deref(), Some("HotLoop"));}#[test]@@ -1088,26 +1061,22 @@ specialize A() + B() + C() + D();let specializations = parse_specializations("test.flap",r#"-specialize Increment() # Continue with the comparison.- + JumpLessThan( # Only the right-hand side is constant.- rhs: Int32); # End the declaration.+specialize JumpLessThan( # Only the right-hand side is constant.+ rhs: Int32); # End the declaration."#,).unwrap();assert_eq!(specializations.len(), 1);- assert_eq!(specializations[0].components.len(), 2);+ assert_eq!(specializations[0].parameters.len(), 1);}#[test]- fn derives_compact_single_and_fused_instruction_layouts() {+ fn derives_compact_instruction_layouts() {let source = r#"handler Add(dst: out Operand, lhs: in Operand, rhs: in Operand) {dispatch_next;}-handler Increment(dst: inout Operand) {- dispatch_next;-}handler Mov(dst: out Operand, src: in Operand) {dispatch_next;}@@ -1116,7 +1085,7 @@ handler JumpLessThan(lhs: in Operand, rhs: in Operand, target: Label) @terminato}specialize Add(rhs: Int32);specialize Mov(src: Undefined);-specialize Increment() + JumpLessThan(rhs: Int32);+specialize JumpLessThan(rhs: Int32);"#;let ops = parse_flap_metadata("test.flap", source).unwrap();let specializations = parse_specializations("test.flap", source).unwrap();@@ -1142,11 +1111,8 @@ specialize Increment() + JumpLessThan(rhs: Int32);.collect::<Vec<_>>(),[("m_dst", "Operand")]);- assert_eq!(- derived[1].components[0].parameters["src"],- SpecializedParameterBinding::Undefined- );- assert_eq!(derived[2].definition.name, "IncrementJumpLessThanRhsInt32");+ assert_eq!(derived[1].parameters["src"], SpecializedParameterBinding::Undefined);+ assert_eq!(derived[2].definition.name, "JumpLessThanRhsInt32");assert_eq!(derived[2].definition@@ -1154,44 +1120,12 @@ specialize Increment() + JumpLessThan(rhs: Int32);.iter().map(|field| (field.name.as_str(), field.ty.as_str())).collect::<Vec<_>>(),- [- ("m_c0_dst", "Operand"),- ("m_c1_lhs", "Operand"),- ("m_c1_rhs", "i32"),- ("m_c1_target", "Label"),- ]+ [("m_lhs", "Operand"), ("m_rhs", "i32"), ("m_target", "Label")]);assert!(derived[2].definition.is_terminator);assert_eq!(- derived[2].components[1].parameters["lhs"],- SpecializedParameterBinding::Field("c1_lhs".to_string())- );- }-- #[test]- fn qualifies_field_names_across_fused_components() {- let source = r#"-handler Copy(dst: out Operand) { dispatch_next; }-handler Convert(dst: out Operand) { dispatch_next; }-handler Use(dst1: in Operand) { dispatch_next; }-specialize Copy() + Convert() + Use();-"#;- let ops = parse_flap_metadata("test.flap", source).unwrap();- let specializations = parse_specializations("test.flap", source).unwrap();- let derived = derive_specialized_instructions(&ops, &specializations).unwrap();-- assert_eq!(- derived[0]- .definition- .fields- .iter()- .map(|field| field.name.as_str())- .collect::<Vec<_>>(),- ["m_c0_dst", "m_c1_dst", "m_c2_dst1"]- );- assert_eq!(- derived[0].components[2].parameters["dst1"],- SpecializedParameterBinding::Field("c2_dst1".to_string())+ derived[2].parameters["lhs"],+ SpecializedParameterBinding::Field("lhs".to_string()));}diff --git a/Libraries/LibJS/Rust/generate/instructions.rs b/Libraries/LibJS/Rust/generate/instructions.rsindex 58b4a775118..1bebc33b270 100644--- a/Libraries/LibJS/Rust/generate/instructions.rs+++ b/Libraries/LibJS/Rust/generate/instructions.rs@@ -71,21 +71,12 @@ fn generate_rust_code(Ok(())}-/// The operands of the instruction called `name` that a specialization looks at. The emitter only-/// holds back `Mov` for specializations of several instructions, which this makes sure stays all it has to do.+/// The operands of the instruction called `name` that a specialization looks at.fn specializable_operands(name: &str, specializations: &[Specialization]) -> Vec<String> {let mut operands = Vec::new();for specialization in specializations {- assert!(- specialization.components.len() == 1- || specialization- .components- .iter()- .all(|component| component.bytecode == "Mov"),- "only Mov may specialize as part of a sequence"- );- if name != "Mov" && specialization.components[0].bytecode == name {- for parameter in &specialization.components[0].parameters {+ if name != "Mov" && specialization.bytecode == name {+ for parameter in &specialization.parameters {let operand = rust_field_name(¶meter.name);if !operands.contains(&operand) {operands.push(operand);@@ -149,15 +140,7 @@ fn generate_specialization_selector(specialized_ops: &[SpecializedInstruction],) -> Result<(), Box<dyn std::error::Error>> {let mut order = (0..specializations.len()).collect::<Vec<_>>();- order.sort_by_key(|index| {- let specialization = &specializations[*index];- let constraint_count = specialization- .components- .iter()- .map(|component| component.parameters.len())- .sum::<usize>();- std::cmp::Reverse((specialization.components.len(), constraint_count))- });+ order.sort_by_key(|index| std::cmp::Reverse(specializations[*index].parameters.len()));writeln!(w, "#[allow(unused_variables)]")?;writeln!(w, "#[allow(clippy::clone_on_copy)]")?;@@ -166,71 +149,50 @@ fn generate_specialization_selector(writeln!(w, "#[allow(clippy::unnecessary_unwrap)]")?;writeln!(w,- "pub fn specialize_instruction_sequence<'a>(instructions: impl Iterator<Item = &'a Instruction> + Clone, constants: &[super::executable_data::ConstantValue]) -> Option<(Instruction, usize)> {{"- )?;- // Most instructions start no sequence at all, which one look at the first of them tells.- let mut first_ops = specializations- .iter()- .map(|specialization| format!("Instruction::{} {{ .. }}", specialization.components[0].bytecode))- .collect::<Vec<_>>();- first_ops.sort();- first_ops.dedup();- writeln!(- w,- " if !matches!(instructions.clone().next(), Some({})) {{ return None; }}",- first_ops.join(" | ")+ "pub fn specialize_instruction(instruction: &Instruction, constants: &[super::executable_data::ConstantValue]) -> Option<Instruction> {{")?;for index in order {let specialization = &specializations[index];let specialized_op = &specialized_ops[index];- let component_count = specialization.components.len();- writeln!(w, " let mut candidate = instructions.clone();")?;- writeln!(w, " if let (")?;- for (component_index, component) in specialization.components.iter().enumerate() {- let op = &component.bytecode;- let base_op = ops- .iter()- .find(|definition| definition.name == *op)- .expect("specialization bytecodes are validated");- let bindings = user_fields(base_op)- .iter()- .map(|field| rust_field_name(&field.name))- .map(|name| format!("{name}: c{component_index}_{name}"))- .collect::<Vec<_>>();- writeln!(w, " Some(Instruction::{op} {{ {} }}),", bindings.join(", "))?;- }- writeln!(w, " ) = (")?;- for _ in &specialization.components {- writeln!(w, " candidate.next(),")?;- }- writeln!(w, " ) {{")?;+ let op = &specialization.bytecode;+ let base_op = ops+ .iter()+ .find(|definition| definition.name == *op)+ .expect("specialization bytecodes are validated");+ let bindings = user_fields(base_op)+ .iter()+ .map(|field| rust_field_name(&field.name))+ .collect::<Vec<_>>();+ writeln!(+ w,+ " if let Instruction::{op} {{ {} }} = instruction {{",+ bindings.join(", ")+ )?;let mut conditions = Vec::new();let mut extracted_values = Vec::new();- for (component_index, component) in specialization.components.iter().enumerate() {- for parameter in &component.parameters {- let operand = format!("c{component_index}_{}", parameter.name);- match ¶meter.constraint {- SpecializationConstraint::Int32 => {- let value = format!("specialized_c{component_index}_{}", parameter.name);- writeln!(- w,- " let {value} = constants.get({operand}.index() as usize).and_then(|constant| match constant {{"- )?;- writeln!(- w,- " super::executable_data::ConstantValue::Number(number) if number.fract() == 0.0 && *number >= i32::MIN as f64 && *number <= i32::MAX as f64 && number.to_bits() != (-0.0_f64).to_bits() => Some(*number as i32),"- )?;- writeln!(w, " _ => None,")?;- writeln!(w, " }});")?;- conditions.push(format!("{operand}.is_constant() && {value}.is_some()"));- extracted_values.push(value);- }- SpecializationConstraint::Undefined => {- conditions.push(format!(- "{operand}.is_constant() && matches!(constants.get({operand}.index() as usize), Some(super::executable_data::ConstantValue::Undefined))"- ));- }+ for parameter in &specialization.parameters {+ let operand = ¶meter.name;+ match ¶meter.constraint {+ SpecializationConstraint::Int32 => {+ let value = format!("specialized_{operand}");+ writeln!(+ w,+ " let {value} = constants.get({operand}.index() as usize).and_then(|constant| match constant {{"+ )?;+ writeln!(+ w,+ " super::executable_data::ConstantValue::Number(number) if number.fract() == 0.0 && *number >= i32::MIN as f64 && *number <= i32::MAX as f64 && number.to_bits() != (-0.0_f64).to_bits() => Some(*number as i32),"+ )?;+ writeln!(w, " _ => None,")?;+ writeln!(w, " }});")?;+ conditions.push(format!("{operand}.is_constant() && {value}.is_some()"));+ extracted_values.push(value);+ }+ SpecializationConstraint::Undefined => {+ conditions.push(format!(+ "{operand}.is_constant() && matches!(constants.get({operand}.index() as usize), Some(super::executable_data::ConstantValue::Undefined))"+ ));}}}@@ -243,34 +205,29 @@ fn generate_specialization_selector(}writeln!(w,- " return Some((Instruction::{} {{",+ " return Some(Instruction::{} {{",specialized_op.definition.name)?;for field in &specialized_op.definition.fields {let field_name = rust_field_name(&field.name);- let mut source = None;- for (component_index, component) in specialized_op.components.iter().enumerate() {- for (parameter, binding) in &component.parameters {- if binding == &SpecializedParameterBinding::Field(field_name.clone()) {- source = Some(if field.ty == "i32" {- format!("specialized_c{component_index}_{parameter}")- } else {- format!("(*c{component_index}_{parameter}).clone()")- });- break;- }- }- if source.is_some() {- break;- }- }- writeln!(- w,- " {field_name}: {},",- source.expect("every specialized field has a source")- )?;+ let parameter = specialized_op+ .parameters+ .iter()+ .find_map(|(parameter, binding)| {+ (binding == &SpecializedParameterBinding::Field(field_name.clone())).then_some(parameter)+ })+ .expect("every specialized field has a source");+ let is_int32 = specialization.parameters.iter().any(|specialized| {+ &specialized.name == parameter && matches!(specialized.constraint, SpecializationConstraint::Int32)+ });+ let source = if is_int32 {+ format!("specialized_{parameter}")+ } else {+ format!("(*{parameter}).clone()")+ };+ writeln!(w, " {field_name}: {source},")?;}- writeln!(w, " }}, {component_count}));")?;+ writeln!(w, " }});")?;if !conditions.is_empty() {writeln!(w, " }}")?;}diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rsindex c77e266106d..942d16e421d 100644--- a/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rs+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rs@@ -28,7 +28,7 @@ use crate::bytecode::constant_fold::try_constant_fold_unary;use crate::bytecode::executable_data::ConstantValue;use crate::bytecode::executable_data::ExceptionHandler;use crate::bytecode::instruction::Instruction;-use crate::bytecode::instruction::specialize_instruction_sequence;+use crate::bytecode::instruction::specialize_instruction;use crate::bytecode::instruction::typed as op;use crate::bytecode::instruction::typed::TypedInstruction;use crate::bytecode::operand::*;@@ -583,11 +583,8 @@ impl Generator<'_> {#[inline(never)]fn put_specialized(&mut self, instruction: &Instruction, watched: Operand) -> u32 {- let specialized = specialize_instruction_sequence([instruction].into_iter(), &self.context.constants.values);- let instruction = match &specialized {- Some((specialized, _)) => specialized,- None => instruction,- };+ let specialized = specialize_instruction(instruction, &self.context.constants.values);+ let instruction = specialized.as_ref().unwrap_or(instruction);self.encode_into_stream(|strict, encoder| instruction.encode_into_block(strict, encoder),watched,diff --git a/Libraries/LibJS/Rust/src/bytecode/instruction.rs b/Libraries/LibJS/Rust/src/bytecode/instruction.rsindex 54f75017194..7e572c46313 100644--- a/Libraries/LibJS/Rust/src/bytecode/instruction.rs+++ b/Libraries/LibJS/Rust/src/bytecode/instruction.rs@@ -27,10 +27,8 @@ mod tests {};let constants = [ConstantValue::Number(42.0)];- let (specialized, component_count) =- specialize_instruction_sequence([&instruction].into_iter(), &constants).expect("Add should specialize");+ let specialized = specialize_instruction(&instruction, &constants).expect("Add should specialize");- assert_eq!(component_count, 1);assert!(matches!(specialized,Instruction::AddRhsInt32 {@@ -49,9 +47,7 @@ mod tests {};let constants = [ConstantValue::Undefined];- let (specialized, component_count) =- specialize_instruction_sequence([&instruction].into_iter(), &constants).expect("Mov should specialize");- assert_eq!(component_count, 1);+ let specialized = specialize_instruction(&instruction, &constants).expect("Mov should specialize");assert!(matches!(specialized, Instruction::MovSrcUndefined { .. }));}}