Truly independent web browser
LibJS: Resolve sloppy global assignment targets before the value
Shannon Booth891b7b7fe4fe
diff --git a/Libraries/LibJS/JIT/Rust/src/builder/globals.rs b/Libraries/LibJS/JIT/Rust/src/builder/globals.rsindex a2030ec126f..ca7b86a61ea 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/globals.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/globals.rs@@ -52,6 +52,7 @@ use crate::ir::NodeId;use crate::ir::Op;use crate::ir::ShapeCheck;use crate::ir::value::OBJECT_TAG;+use crate::ir::value::TRUE;use crate::ir::value::UNDEFINED;use crate::ir::value::tag;use crate::snapshot::CellId;@@ -197,6 +198,40 @@ impl GraphBuilder<'_> {Ok(true)}+ /// Builds `dst = ResolveGlobalBinding` as true when the instruction's+ /// global variable cache found the variable, which stays: a binding of+ /// the global declarative environment for good, and a property of the+ /// global object while the object keeps its shape. Returns false, having+ /// built nothing, if it cannot speculate.+ pub(super) fn try_build_resolve_global_binding(+ &mut self,+ dst: Operand,+ cache: u32,+ ) -> Result<bool, CompileFailure> {+ let Some((globals, global)) = self.global_cache(cache) else {+ return Ok(false);+ };+ if let GlobalCacheSnapshot::Property {+ shape,+ dictionary_generation,+ ..+ } = global+ {+ if !self.may_speculate(ExitKind::BadShape) {+ return Ok(false);+ }+ let object = self.global_object(globals);+ let shape = ShapeCheck {+ shape,+ dictionary_generation,+ };+ self.check_shapes(object, &[shape]);+ }+ let found = self.constant(TRUE);+ self.write(dst, found)?;+ Ok(true)+ }+/// Builds `GetGlobal` (`Handling::Expanded`): the global variable that/// the instruction's global variable cache finds, like the interpreter.pub(super) fn build_get_global(&mut self, instruction: &Instruction) -> Result<Flow, CompileFailure> {diff --git a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs b/Libraries/LibJS/JIT/Rust/src/builder/mod.rsindex b8ba9a1f728..d985197e805 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/mod.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/mod.rs@@ -1737,6 +1737,11 @@ impl<'a> GraphBuilder<'a> {return Ok(None);}}+ Instruction::ResolveGlobalBinding { dst, cache, .. } => {+ if !self.try_build_resolve_global_binding(dst, cache)? {+ return Ok(None);+ }+ }Instruction::GetById { dst, base, cache, .. } => {if self.try_build_cached_getter(dst, base, cache)? {return Ok(Some(Flow::Continue));diff --git a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs b/Libraries/LibJS/JIT/Rust/src/builder/tests.rsindex 2d517bade4e..ee7fe013cb5 100644--- a/Libraries/LibJS/JIT/Rust/src/builder/tests.rs+++ b/Libraries/LibJS/JIT/Rust/src/builder/tests.rs@@ -2853,3 +2853,71 @@ fn array_length_specialization_requires_monomorphic_receivers_and_exit_gates() {assert!(text.contains("CallSlowPath"), "{text}");}}++mod globals {+ use super::*;+ use crate::snapshot::CellId;+ use crate::snapshot::GlobalCacheSnapshot;+ use crate::snapshot::GlobalValueSnapshot;+ use crate::snapshot::GlobalsSnapshot;++ #[test]+ fn global_variables_the_cache_found_resolve_without_the_interpreter() {+ let program = assemble(|_| {+ vec![+ Instruction::Enter,+ Instruction::ResolveGlobalBinding {+ dst: r(5),+ identifier: crate::bytecode::IdentifierTableIndex(0),+ cache: 0,+ },+ Instruction::Return { value: r(5) },+ ]+ });+ let build = |cache: Option<GlobalCacheSnapshot>| {+ let mut snapshot = snapshot_for(&program, test_layout());+ snapshot.runtime.heap_region_offset_mask = (1 << 48) - 1;+ snapshot.executables[0].globals = Some(GlobalsSnapshot {+ object: CellId(0x1000),+ declarative_environment: CellId(0x2000),+ environment_serial: 1,+ caches: vec![cache],+ });+ dump(&optimized_graph(&snapshot), &test_layout())+ };++ // A binding of the global declarative environment stays.+ let binding = GlobalCacheSnapshot::Binding {+ index: 0,+ mutable: true,+ assigned: true,+ value: None,+ };+ let text = build(Some(binding));+ assert!(!text.contains("ResolveGlobalBinding"), "{text}");+ assert!(!text.contains("CheckShape"), "{text}");++ // A property of the global object stays while the object keeps its shape.+ let property = GlobalCacheSnapshot::Property {+ shape: CellId(0x3000),+ dictionary_generation: None,+ offset: 0,+ writes_data_property: true,+ assigned: true,+ value: GlobalValueSnapshot {+ bits: crate::ir::value::UNDEFINED,+ cell: None,+ intrinsic: None,+ has_instance: None,+ typed_array: None,+ },+ };+ let text = build(Some(property));+ assert!(text.contains("CheckShape"), "{text}");+ assert!(!text.contains("ResolveGlobalBinding"), "{text}");++ // A variable the cache did not find is the interpreter's to resolve.+ let text = build(None);+ assert!(text.contains("CallSlowPath ResolveGlobalBinding"), "{text}");+ }+}diff --git a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rsindex 762499ac6a6..00a0985a5aa 100644--- a/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs+++ b/Libraries/LibJS/JIT/Rust/src/codegen/tests/lowerings.rs@@ -2506,6 +2506,20 @@ fn global_variables_the_snapshot_knows() {globals.named_properties[2] = value::NULL;let result = run_with_global_cache(&globals, &get, &[], unassigned, 99);assert_eq!((result.status, result.value), (RETURNED, object));++ // A variable the cache found resolves, even a binding that is still+ // uninitialized, and a property while the global object keeps its shape.+ let resolve = Instruction::ResolveGlobalBinding {+ dst: r(5),+ identifier: crate::bytecode::IdentifierTableIndex(0),+ cache: 1,+ };+ let result = run_with_global_cache(&globals, &resolve, &[], binding(1, true, None), 99);+ assert_eq!((result.status, result.value), (RETURNED, value::TRUE));+ let result = run_with_global_cache(&globals, &resolve, &[], property(shape, 2, value::int32(12)), 99);+ assert_eq!((result.status, result.value), (RETURNED, value::TRUE));+ let result = run_with_global_cache(&globals, &resolve, &[], property(shape + 8, 2, value::int32(12)), 99);+ assert_eq!(result.status, EXITED);}#[test]diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/constructs.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/constructs.rsindex 2e3f7539e7e..72760e0e6ba 100644--- a/Libraries/LibJS/Rust/src/bytecode/codegen/constructs.rs+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/constructs.rs@@ -47,6 +47,7 @@ use super::stream::Handler;use super::stream::LoopKind;use super::stream::OpenIterator;use super::stream::ScopeEnvironment;+use super::stream::TargetBinding;use super::stream::ValKind;use super::sweep::declaration_kind_of_mark;use super::sweep::is_anonymous_function_definition;@@ -1580,7 +1581,7 @@ impl Generator<'_> {}target_tag if target_tag == tag::IDENT || (tag::IDENT_MARKED..tag::MEMBER_MARKED).contains(&target_tag) => {let ident = self.identifier_of(Name(tree.node_a(target)));- self.target_of_identifier(ident);+ self.target_of_identifier(ident, TargetBinding::MightAppear);}_ => {self.sweep_rows(first_row, target.index() + 1)?;diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rsindex b166bd6aa71..16270d633c9 100644--- a/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rs+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/stream.rs@@ -88,6 +88,15 @@ pub enum ValKind {BuiltinCallee,}+/// Whether the binding of an identifier that gets written can come into being after the reference to it is made.+#[derive(Clone, Copy, PartialEq, Eq)]+pub(super) enum TargetBinding {+ /// Code that can make one runs in between, as for `x = value`.+ MightAppear,+ /// It is read or declared first, as for `x += value` and `var x = value`.+ Known,+}+/// An entry of the stack of evaluated expressions.#[derive(Clone, Copy)]pub struct Val {@@ -2538,7 +2547,8 @@ impl Generator<'_> {// --- Targets ---- pub(super) fn target_of_identifier(&mut self, ident: Identifier) {+ /// `ident` as a reference that gets written.+ pub(super) fn target_of_identifier(&mut self, ident: Identifier, binding: TargetBinding) {let first_temporary = self.next_temporary();let is_const = ident.declaration_kind == Some(DeclarationKind::Const);if ident.is_local() {@@ -2560,7 +2570,7 @@ impl Generator<'_> {// NB: Unless it is known where the binding is, the reference is what it is before the value gets evaluated.let mut resolved = Operand::invalid();let mut cache = u32::MAX;- if !ident.is_global || self.strict {+ if !ident.is_global || self.strict || binding == TargetBinding::MightAppear {let identifier = self.intern_identifier(ident.name);if self.environment_coordinate_for_identifier(identifier).is_none() {resolved = self.temporary();@@ -3589,16 +3599,19 @@ impl Generator<'_> {pub(super) fn target_of_declaration(&mut self, ident: Identifier) {// NB: The object of a `with` can have a property of the name of a `var`, which is what gets written then.if self.context.scope.is_in_with() && ident.declaration_kind == Some(DeclarationKind::Var) {- self.target_of_identifier(Identifier {- is_global: false,- ..ident- });+ self.target_of_identifier(+ Identifier {+ is_global: false,+ ..ident+ },+ TargetBinding::Known,+ );return;}// NB: What a `var` of a program is, is as open as for any other reference.if self.context.scope.is_program() && ident.declaration_kind == Some(DeclarationKind::Var) && !ident.is_local(){- self.target_of_identifier(ident);+ self.target_of_identifier(ident, TargetBinding::Known);return;}let first_temporary = self.next_temporary();diff --git a/Libraries/LibJS/Rust/src/bytecode/codegen/sweep.rs b/Libraries/LibJS/Rust/src/bytecode/codegen/sweep.rsindex e8025816b0b..46b2420f759 100644--- a/Libraries/LibJS/Rust/src/bytecode/codegen/sweep.rs+++ b/Libraries/LibJS/Rust/src/bytecode/codegen/sweep.rs@@ -31,6 +31,7 @@ use crate::parser::token::N_PROTO;use super::context::Generator;use super::nodes::*;+use super::stream::TargetBinding;use super::stream::ValKind;use crate::bytecode::constant_fold::ascii_code_units_to_string;@@ -141,11 +142,11 @@ impl Generator<'_> {}tag::IDENT_TARGET => {let ident = self.identifier_of(Name(a));- self.target_of_identifier(ident);+ self.target_of_identifier(ident, TargetBinding::MightAppear);}tag::IDENT_READ_TARGET => {let ident = self.identifier_of(Name(a));- self.target_of_identifier(ident);+ self.target_of_identifier(ident, TargetBinding::Known);self.read_target(Some(ident));}tag::IDENT_DECLARATION => {diff --git a/Tests/LibJS/Bytecode/expected/named-function-expression.txt b/Tests/LibJS/Bytecode/expected/named-function-expression.txtindex 3301e67802c..5460a729946 100644--- a/Tests/LibJS/Bytecode/expected/named-function-expression.txt+++ b/Tests/LibJS/Bytecode/expected/named-function-expression.txt@@ -1,20 +1,32 @@-$12b60500 named-function-expression.js:4:1- Registers: 8- Blocks: 1+$72cc050b named-function-expression.js:4:1+ Registers: 9+ Blocks: 4Constants:[0] = Undefined+ [1] = Nullblock0:[ 0] Enter[ 8] GetLexicalEnvironment dst:reg4[ 10] Mov dst:reg5, src:Undefined- [ 20] CreateLexicalEnvironment dst:reg7, parent:reg4, capacity:1, is_catch_environment:false- [ 38] CreateVariable `Oops`, is_immutable:true, is_global:false, is_strict:false- [ 48] NewFunction dst:reg6, shared_function_data_index:0- [ 60] InitializeLexicalBinding `Oops`, src:reg6- [ 78] SetLexicalEnvironment environment:reg4- [ 80] SetGlobal `Oops`, src:reg6- [ 90] Mov dst:reg5, src:reg6- [ a0] GetGlobal value_feedback:0, dst:reg6, `Oops`- [ b0] GetById value_feedback:1, dst:reg5, base:reg6, `x`- [ c8] End value:reg5+ [ 20] ResolveGlobalBinding dst:reg6, `Oops`+ [ 30] CreateLexicalEnvironment dst:reg8, parent:reg4, capacity:1, is_catch_environment:false+ [ 48] CreateVariable `Oops`, is_immutable:true, is_global:false, is_strict:false+ [ 58] NewFunction dst:reg7, shared_function_data_index:0+ [ 70] InitializeLexicalBinding `Oops`, src:reg7+ [ 88] SetLexicalEnvironment environment:reg4+ [ 90] JumpIf condition:reg6, true_target:block1, false_target:block2++block1:+ [ a0] SetGlobal `Oops`, src:reg7+ [ b0] Jump target:block3++block2:+ [ b8] SetResolvedBinding environment:Null, `Oops`, src:reg7+ [ c8] Jump target:block3++block3:+ [ d0] Mov dst:reg5, src:reg7+ [ e0] GetGlobal value_feedback:0, dst:reg6, `Oops`+ [ f0] GetById value_feedback:1, dst:reg5, base:reg6, `x`+ [ 108] End value:reg5diff --git a/Tests/LibJS/JIT/ir/named-access.js b/Tests/LibJS/JIT/ir/named-access.jsindex db3bf452ef5..3cbcc014dfa 100644--- a/Tests/LibJS/JIT/ir/named-access.js+++ b/Tests/LibJS/JIT/ir/named-access.js@@ -48,7 +48,8 @@ jit.compile(getY);// CHECK-NEXT: LoadNamed {{.*}}([[REFINED]], [[CASE_ADDRESS]])// Global variables whose caches found nothing to speculate on, like these-// accessors, probe the global variable caches like the interpreter does.+// accessors, probe the global variable caches like the interpreter does. The+// assignment resolves its target before the value, which the interpreter does.let reads = 0;Object.defineProperty(globalThis, "tick", {@@ -69,9 +70,10 @@ jit.compile(readAndWrite);// CHECK-FUNCTION: readAndWrite// CHECK-PASS: frame initialization-// CHECK: [[REALM:v[0-9]+]]:pointer = LoadFrameField Realm+// CHECK: CallSlowPath ResolveGlobalBinding+// CHECK-NEXT: [[REALM:v[0-9]+]]:pointer = LoadFrameField Realm// CHECK-NEXT: [[EXECUTABLE:v[0-9]+]]:pointer = LoadFrameField Executable-// CHECK-NEXT: [[VALUE:v[0-9]+]] = ProbeGlobalCache cache 0 ([[REALM]], [[EXECUTABLE]])+// CHECK-NEXT: [[VALUE:v[0-9]+]] = ProbeGlobalCache cache 1 ([[REALM]], [[EXECUTABLE]])// CHECK-NEXT: BranchTaggedEquals ([[VALUE]], #empty)-// CHECK: ProbeGlobalStore cache 1 ({{v[0-9]+}}, [[REALM]], [[EXECUTABLE]])+// CHECK: ProbeGlobalStore cache 0 ({{v[0-9]+}}, [[REALM]], [[EXECUTABLE]])// CHECK-NEXT: BranchBooldiff --git a/Tests/LibWeb/Text/expected/sloppy-global-assignment-resolves-target-first.txt b/Tests/LibWeb/Text/expected/sloppy-global-assignment-resolves-target-first.txtnew file mode 100644index 00000000000..4937d795831--- /dev/null+++ b/Tests/LibWeb/Text/expected/sloppy-global-assignment-resolves-target-first.txt@@ -0,0 +1,4 @@+assignment, let: 1 2+assignment, const: 1 2+object pattern: 1 2+array pattern: 1 2diff --git a/Tests/LibWeb/Text/input/sloppy-global-assignment-resolves-target-first.html b/Tests/LibWeb/Text/input/sloppy-global-assignment-resolves-target-first.htmlnew file mode 100644index 00000000000..907f912e673--- /dev/null+++ b/Tests/LibWeb/Text/input/sloppy-global-assignment-resolves-target-first.html@@ -0,0 +1,41 @@+<!DOCTYPE html>+<script src="include.js"></script>+<script>+ function runScript(source) {+ const script = document.createElement("script");+ script.textContent = source;+ document.head.append(script);+ }++ test(() => {+ assignedLet = (runScript("let assignedLet = 1;"), 2);+ println(`assignment, let: ${assignedLet} ${globalThis.assignedLet}`);++ try {+ assignedConst = (runScript("const assignedConst = 1;"), 2);+ println(`assignment, const: ${assignedConst} ${globalThis.assignedConst}`);+ } catch (error) {+ println(`assignment, const: ${error.name}`);+ }++ ({ a: objectPatternTarget } = {+ get a() {+ runScript("let objectPatternTarget = 1;");+ return 2;+ },+ });+ println(`object pattern: ${objectPatternTarget} ${globalThis.objectPatternTarget}`);++ [arrayPatternTarget] = {+ [Symbol.iterator]() {+ return {+ next() {+ runScript("let arrayPatternTarget = 1;");+ return { value: 2, done: false };+ },+ };+ },+ };+ println(`array pattern: ${arrayPatternTarget} ${globalThis.arrayPatternTarget}`);+ });+</script>