From 247a1709e5ab363fb3359db6204af20a4fbecfe8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E7=82=B9?= <467490186@qq.com> Date: Fri, 13 Nov 2026 15:46:34 +0800 Subject: [PATCH 1/5] perf(compiler): read declared scalar properties through typed offsets Property reads of declared int/float scalars were lowered to attr(offset, AttrMode::Get), which materializes a Variant on every read and adds refcount traffic plus a temporary that the following conversion has to unwrap. Read the zval slot directly through attrInt/attrFloat instead when the property is stored as a native scalar. The receiver must be an exact class so the persistent property offset cannot drift when a subclass redeclares the property: `$this` in a final class, or a typed object variable whose declared class is final. Readonly properties keep the Zend initialization check, nullable properties may hold null (which the typed accessors reject), and properties with hooks keep the existing lowering, so all of those stay on the Variant path. The probe under probes/typed_property_read measures 20M reads of two declared scalars at 1169ms before and 125ms after on this machine, with identical output; generated code confirms attr(get_persistent_prop(...)) drops to zero and typed offset reads appear instead. --- .../declared-scalar-property-read-final.php | 17 ++++ ...declared-scalar-property-read-nullable.php | 11 +++ .../declared-scalar-property-read-open.php | 11 +++ ...declared-scalar-property-read-readonly.php | 13 +++ .../src/DeclaredScalarPropertyReadTest.php | 87 +++++++++++++++++++ src/Parser/PropertyAccessTrait.php | 75 ++++++++++++++++ ...ed-scalar-read-default-initialization.phpt | 27 ++++++ .../declared-scalar-read-final-class.phpt | 36 ++++++++ .../declared-scalar-read-nullable.phpt | 28 ++++++ ...clared-scalar-read-subclass-redeclare.phpt | 37 ++++++++ 10 files changed, 342 insertions(+) create mode 100644 phpunit/code/declared-scalar-property-read-final.php create mode 100644 phpunit/code/declared-scalar-property-read-nullable.php create mode 100644 phpunit/code/declared-scalar-property-read-open.php create mode 100644 phpunit/code/declared-scalar-property-read-readonly.php create mode 100644 phpunit/src/DeclaredScalarPropertyReadTest.php create mode 100644 tests/compiler/object_property/declared-scalar-read-default-initialization.phpt create mode 100644 tests/compiler/object_property/declared-scalar-read-final-class.phpt create mode 100644 tests/compiler/object_property/declared-scalar-read-nullable.phpt create mode 100644 tests/compiler/object_property/declared-scalar-read-subclass-redeclare.phpt diff --git a/phpunit/code/declared-scalar-property-read-final.php b/phpunit/code/declared-scalar-property-read-final.php new file mode 100644 index 00000000..2df87dc1 --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-final.php @@ -0,0 +1,17 @@ +ratio * $this->count; + } +} + +function declared_scalar_read_final(DeclaredScalarFinalBox $box): float +{ + return $box->ratio + $box->count; +} diff --git a/phpunit/code/declared-scalar-property-read-nullable.php b/phpunit/code/declared-scalar-property-read-nullable.php new file mode 100644 index 00000000..ebd668e2 --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-nullable.php @@ -0,0 +1,11 @@ +count; +} diff --git a/phpunit/code/declared-scalar-property-read-open.php b/phpunit/code/declared-scalar-property-read-open.php new file mode 100644 index 00000000..38b1d28f --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-open.php @@ -0,0 +1,11 @@ +count; +} diff --git a/phpunit/code/declared-scalar-property-read-readonly.php b/phpunit/code/declared-scalar-property-read-readonly.php new file mode 100644 index 00000000..f0505dab --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-readonly.php @@ -0,0 +1,13 @@ +count; +} diff --git a/phpunit/src/DeclaredScalarPropertyReadTest.php b/phpunit/src/DeclaredScalarPropertyReadTest.php new file mode 100644 index 00000000..2743b1d6 --- /dev/null +++ b/phpunit/src/DeclaredScalarPropertyReadTest.php @@ -0,0 +1,87 @@ +addFiles([$testFile]); + $compiler->prepareFile($testFile); + $compiler->convertFile($testFile); + + return TYPEPHP_ROOT_PATH . '/build/phpunit/code/' . basename($file, '.php') . '.cc'; + } + + public function testFinalClassReceiverUsesTypedOffsetRead(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-final.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + $this->assertStringContainsString('attrInt(get_persistent_prop(', $code); + $this->assertStringContainsString('attrFloat(get_persistent_prop(', $code); + $this->assertStringContainsString('this_.attrInt(', $code); + $this->assertStringContainsString('this_.attrFloat(', $code); + $this->assertStringNotContainsString('attr(get_persistent_prop(', $code); + } + + public function testNonFinalReceiverKeepsVariantRead(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-open.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + $this->assertStringContainsString('attr(get_persistent_prop(', $code); + $this->assertStringNotContainsString('attrInt(get_persistent_prop(', $code); + $this->assertStringNotContainsString('attrFloat(get_persistent_prop(', $code); + } + + public function testNullablePropertyKeepsVariantRead(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-nullable.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + $this->assertStringContainsString('attr(get_persistent_prop(', $code); + $this->assertStringNotContainsString('attrInt(get_persistent_prop(', $code); + } + + public function testReadonlyPropertyKeepsCheckedRead(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-readonly.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + $this->assertStringContainsString('typephp_read_property_scoped(', $code); + $this->assertStringNotContainsString('attrInt(get_persistent_prop(', $code); + } +} diff --git a/src/Parser/PropertyAccessTrait.php b/src/Parser/PropertyAccessTrait.php index 88d717ec..883ba7ce 100644 --- a/src/Parser/PropertyAccessTrait.php +++ b/src/Parser/PropertyAccessTrait.php @@ -1329,6 +1329,19 @@ protected function parsePropertyFetch(Expr\PropertyFetch $expr): string $def = $declared; } } + if ($property instanceof Node\Identifier) { + $scalarRead = $this->emitDeclaredScalarPropertyRead( + $expr, + $objectVar, + $objectName, + $this->parseIdentifier($property), + $def, + $update, + ); + if ($scalarRead !== null) { + return $scalarRead; + } + } if ($def && $this->usesNativeScalarStorage($def->type)) { $propName = $this->parseIdentifier($property); $typedFetch = $this->emitNativeInstancePropertyTypedFetch( @@ -1437,6 +1450,68 @@ protected function emitPropertyHookSetterCall(Expr\PropertyFetch $expr, string $ return $this->parseMethodCall($call); } + /** + * Lower a read of a declared scalar property to its zval slot. + * + * `attr(offset, AttrMode::Get)` materializes a Variant for every read, + * including the refcount traffic and the temporary that follows. When the + * property is stored as a plain zval scalar, the typed accessor reads the + * same slot without boxing, which removes that cost from hot loops. + * + * The receiver must be an exact class so the persistent property offset + * cannot move when a subclass redeclares the property: `$this` in a final + * class, or a typed object variable whose declared class is final. + * Readonly properties keep the Zend initialization check, nullable + * properties may hold null (which the typed accessors reject), and hooks + * require their own lowering, so all three keep the existing path. + */ + private function emitDeclaredScalarPropertyRead( + Expr\PropertyFetch $expr, + string $objectVar, + string $objectName, + string $propName, + ?PropertyDef $def, + bool $update, + ): ?string { + if ($def === null) { + $def = $this->findReadablePropertyDefinition($expr); + } + if ($def === null + || $update + || $def->isReadonly() + || $def->nullable + || !$def->isPublic() + || $def->isStatic() + || $def->getter !== null + || $def->setter !== null + || $def->virtual) { + return null; + } + if ($def->type !== Type::INT && $def->type !== Type::FLOAT) { + return null; + } + if (!$this->usesNativeScalarStorage($def->type)) { + return null; + } + if ($objectVar === 'this_') { + $receiverClass = $this->getFullClassName(); + } elseif ($this->isTypedObject($objectName)) { + $receiverClass = $this->getObjectType($objectName); + } else { + return null; + } + if ($receiverClass === '' + || $this->isNativeObjectClass($receiverClass) + || !$this->isFinalClass($receiverClass)) { + return null; + } + $accessor = $def->type === Type::INT ? 'attrInt' : 'attrFloat'; + $this->setNativePropertyValueSource($expr, self::NATIVE_PROPERTY_VALUE_VAR); + $expr->setAttribute(self::ATTR_LOWERED_TYPE, $def->type); + return $objectVar . '.' . $accessor + . '(' . $this->getPropertyOffset($receiverClass, $propName) . ')'; + } + private function emitNativeInstancePropertyTypedFetch( Expr\PropertyFetch $expr, string $objectVar, diff --git a/tests/compiler/object_property/declared-scalar-read-default-initialization.phpt b/tests/compiler/object_property/declared-scalar-read-default-initialization.phpt new file mode 100644 index 00000000..be931233 --- /dev/null +++ b/tests/compiler/object_property/declared-scalar-read-default-initialization.phpt @@ -0,0 +1,27 @@ +--TEST-- +declared scalar properties without defaults read as zero through typed receivers +--FILE-- +count; +} + +function main(): void +{ + $box = new DefaultScalarBox(); + var_dump(readCount($box)); + var_dump($box->count); + var_dump($box->ratio); +} +?> +--EXPECT-- +int(0) +int(0) +float(0) diff --git a/tests/compiler/object_property/declared-scalar-read-final-class.phpt b/tests/compiler/object_property/declared-scalar-read-final-class.phpt new file mode 100644 index 00000000..f2b2262c --- /dev/null +++ b/tests/compiler/object_property/declared-scalar-read-final-class.phpt @@ -0,0 +1,36 @@ +--TEST-- +final class public int and float properties read through typed receivers +--FILE-- +ratio + $this->count; + } +} + +function accumulate(ScalarBox $box, int $iterations): float +{ + $sum = 0.0; + for ($i = 0; $i < $iterations; $i++) { + $sum += $box->ratio + $box->count; + } + return $sum; +} + +function main(): void +{ + $box = new ScalarBox(); + $box->count = 7; + $box->ratio = 1.5; + var_dump(accumulate($box, 10)); + var_dump($box->total()); +} +?> +--EXPECT-- +float(85) +float(8.5) diff --git a/tests/compiler/object_property/declared-scalar-read-nullable.phpt b/tests/compiler/object_property/declared-scalar-read-nullable.phpt new file mode 100644 index 00000000..0302926e --- /dev/null +++ b/tests/compiler/object_property/declared-scalar-read-nullable.phpt @@ -0,0 +1,28 @@ +--TEST-- +nullable declared scalar properties keep returning null instead of a typed read +--FILE-- +count; +} + +function main(): void +{ + $box = new NullableScalarBox(); + var_dump(readCount($box)); + $box->count = 42; + var_dump(readCount($box)); + $box->count = null; + var_dump(readCount($box)); +} +?> +--EXPECT-- +NULL +int(42) +NULL diff --git a/tests/compiler/object_property/declared-scalar-read-subclass-redeclare.phpt b/tests/compiler/object_property/declared-scalar-read-subclass-redeclare.phpt new file mode 100644 index 00000000..66c8b3e4 --- /dev/null +++ b/tests/compiler/object_property/declared-scalar-read-subclass-redeclare.phpt @@ -0,0 +1,37 @@ +--TEST-- +non-final receivers keep the name-based read when a subclass redeclares the property +--FILE-- +count; + } +} + +class ChildScalarBox extends BaseScalarBox +{ + public int $count = 2; +} + +function readCount(BaseScalarBox $box): int +{ + return $box->count; +} + +function main(): void +{ + var_dump((new BaseScalarBox())->own()); + var_dump(readCount(new ChildScalarBox())); + $box = new ChildScalarBox(); + $box->count = 5; + var_dump(readCount($box)); +} +?> +--EXPECT-- +int(1) +int(2) +int(5) From e66f8d06f5426583b0fbc7032f10705cce6d21cb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E7=82=B9?= <467490186@qq.com> Date: Fri, 13 Nov 2026 16:32:48 +0800 Subject: [PATCH 2/5] fix(compiler): keep Variant property receivers on the generic read The typed offset read assumed that a proven runtime class also means Object storage. A `mixed` parameter narrowed by instanceof disproves that: the class is known, but the C++ binding is still a Variant, which has no attrInt or attrFloat member, so instanceof-type-narrowing.phpt failed to compile. Require Object storage for non-this receivers before emitting the typed accessor; Variant bindings fall back to attr(offset, AttrMode::Get). Union typed object parameters keep Object storage and still take the fast path. Cover both directions: a PHPT for a narrowed mixed receiver, and a codegen assertion that the fallback read is emitted instead of attrInt. --- ...declared-scalar-property-read-narrowed.php | 14 ++++++++++ .../src/DeclaredScalarPropertyReadTest.php | 13 ++++++++++ src/Parser/PropertyAccessTrait.php | 6 +++++ .../declared-scalar-read-narrowed-mixed.phpt | 26 +++++++++++++++++++ 4 files changed, 59 insertions(+) create mode 100644 phpunit/code/declared-scalar-property-read-narrowed.php create mode 100644 tests/compiler/object_property/declared-scalar-read-narrowed-mixed.phpt diff --git a/phpunit/code/declared-scalar-property-read-narrowed.php b/phpunit/code/declared-scalar-property-read-narrowed.php new file mode 100644 index 00000000..512add6f --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-narrowed.php @@ -0,0 +1,14 @@ +count; + } + return -1; +} diff --git a/phpunit/src/DeclaredScalarPropertyReadTest.php b/phpunit/src/DeclaredScalarPropertyReadTest.php index 2743b1d6..d844e1aa 100644 --- a/phpunit/src/DeclaredScalarPropertyReadTest.php +++ b/phpunit/src/DeclaredScalarPropertyReadTest.php @@ -84,4 +84,17 @@ public function testReadonlyPropertyKeepsCheckedRead(): void $this->assertStringContainsString('typephp_read_property_scoped(', $code); $this->assertStringNotContainsString('attrInt(get_persistent_prop(', $code); } + + public function testNarrowedMixedReceiverKeepsVariantRead(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-narrowed.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + $this->assertStringContainsString('attr(get_persistent_prop(', $code); + $this->assertStringNotContainsString('attrInt(get_persistent_prop(', $code); + } } diff --git a/src/Parser/PropertyAccessTrait.php b/src/Parser/PropertyAccessTrait.php index 883ba7ce..cda13232 100644 --- a/src/Parser/PropertyAccessTrait.php +++ b/src/Parser/PropertyAccessTrait.php @@ -1496,6 +1496,12 @@ private function emitDeclaredScalarPropertyRead( if ($objectVar === 'this_') { $receiverClass = $this->getFullClassName(); } elseif ($this->isTypedObject($objectName)) { + // A proven runtime class does not imply object storage: a `mixed` + // parameter narrowed by instanceof keeps Variant storage, and only + // Object exposes the typed accessors. + if ($this->getVarType($objectName) !== Type::OBJECT) { + return null; + } $receiverClass = $this->getObjectType($objectName); } else { return null; diff --git a/tests/compiler/object_property/declared-scalar-read-narrowed-mixed.phpt b/tests/compiler/object_property/declared-scalar-read-narrowed-mixed.phpt new file mode 100644 index 00000000..cb4f6222 --- /dev/null +++ b/tests/compiler/object_property/declared-scalar-read-narrowed-mixed.phpt @@ -0,0 +1,26 @@ +--TEST-- +instanceof narrowed mixed receivers keep the Variant property read +--FILE-- +count; + } + return -1; +} + +function main(): void +{ + var_dump(readCount(new NarrowedScalarBox())); + var_dump(readCount(new stdClass())); +} +?> +--EXPECT-- +int(3) +int(-1) From e63495f8ab61792406fc4410a0574bd942dbf198 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E7=82=B9?= <467490186@qq.com> Date: Fri, 13 Nov 2026 22:08:24 +0800 Subject: [PATCH 3/5] perf(compiler): read declared scalars through stable property slots The typed offset read only accepted a final receiver, which left most parameters and every non-final `$this` on the Variant path. Zend reuses the parent slot when a child redeclares a non-private property, so a declaration-class offset stays valid for every subclass instance unless a child adds a property hook the parent does not have. Prove that instead of requiring a final class, and keep the Variant path when a subclass can move the slot. The typed read also claimed stable receivers before the hoisting path ran. A hoisted slot reference is cheaper than re-resolving the offset on every read, so give hoisting the first chance and resolve the declaration first, otherwise an ordinary variable receiver has no definition there and skips hoisting outright. Only int and float declarations are resolved there so bool and string properties keep their previous lowering. Read through the slot for non-public properties as well: the resolver already proved the current scope can reach them. A trait method keeps the Variant path because `$this` has no runtime class at that point. Update the codegen assertions that frozen the previous Variant shape for parameter receivers, and cover a plain subclass, a hooking subclass and the hoisted loop read. --- ...d-scalar-property-read-hooked-subclass.php | 18 +++ .../declared-scalar-property-read-loop.php | 15 +++ ...declared-scalar-property-read-subclass.php | 16 +++ .../src/DeclaredScalarPropertyReadTest.php | 44 +++++++- phpunit/src/NativePropertyTest.php | 24 ++-- src/Parser/PropertyAccessTrait.php | 105 ++++++++++++++---- ...clared-scalar-read-subclass-redeclare.phpt | 2 +- 7 files changed, 188 insertions(+), 36 deletions(-) create mode 100644 phpunit/code/declared-scalar-property-read-hooked-subclass.php create mode 100644 phpunit/code/declared-scalar-property-read-loop.php create mode 100644 phpunit/code/declared-scalar-property-read-subclass.php diff --git a/phpunit/code/declared-scalar-property-read-hooked-subclass.php b/phpunit/code/declared-scalar-property-read-hooked-subclass.php new file mode 100644 index 00000000..5739a410 --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-hooked-subclass.php @@ -0,0 +1,18 @@ + 42; + } +} + +function declared_scalar_read_hooked(DeclaredScalarHookedBase $box): int +{ + return $box->count; +} diff --git a/phpunit/code/declared-scalar-property-read-loop.php b/phpunit/code/declared-scalar-property-read-loop.php new file mode 100644 index 00000000..b68668f8 --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-loop.php @@ -0,0 +1,15 @@ +count; + } + return $total; + } +} diff --git a/phpunit/code/declared-scalar-property-read-subclass.php b/phpunit/code/declared-scalar-property-read-subclass.php new file mode 100644 index 00000000..9409069d --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-subclass.php @@ -0,0 +1,16 @@ +count; +} diff --git a/phpunit/src/DeclaredScalarPropertyReadTest.php b/phpunit/src/DeclaredScalarPropertyReadTest.php index d844e1aa..907628f2 100644 --- a/phpunit/src/DeclaredScalarPropertyReadTest.php +++ b/phpunit/src/DeclaredScalarPropertyReadTest.php @@ -45,7 +45,7 @@ public function testFinalClassReceiverUsesTypedOffsetRead(): void $this->assertStringNotContainsString('attr(get_persistent_prop(', $code); } - public function testNonFinalReceiverKeepsVariantRead(): void + public function testNonFinalReceiverWithoutSubclassesUsesTypedOffsetRead(): void { try { $outputFile = $this->compileCode('declared-scalar-property-read-open.php'); @@ -53,10 +53,50 @@ public function testNonFinalReceiverKeepsVariantRead(): void $this->fail($e->getMessage()); } + $code = file_get_contents($outputFile); + $this->assertStringContainsString('attrInt(get_persistent_prop(', $code); + $this->assertStringNotContainsString('attr(get_persistent_prop(', $code); + } + + public function testSubclassRedeclaringThePropertyKeepsTypedOffsetRead(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-subclass.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + $this->assertStringContainsString('attrInt(get_persistent_prop(', $code); + $this->assertStringNotContainsString('attr(get_persistent_prop(', $code); + } + + public function testSubclassAddingAPropertyHookFallsBackToVariantRead(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-hooked-subclass.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + $code = file_get_contents($outputFile); $this->assertStringContainsString('attr(get_persistent_prop(', $code); $this->assertStringNotContainsString('attrInt(get_persistent_prop(', $code); - $this->assertStringNotContainsString('attrFloat(get_persistent_prop(', $code); + } + + public function testLoopReadHoistsBeforeTheTypedOffsetFallback(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-loop.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + $this->assertStringContainsString( + 'php::Int &_object_prop_this___count = this_.attrInt(', + $code + ); } public function testNullablePropertyKeepsVariantRead(): void diff --git a/phpunit/src/NativePropertyTest.php b/phpunit/src/NativePropertyTest.php index 435fcb58..2d8d845d 100644 --- a/phpunit/src/NativePropertyTest.php +++ b/phpunit/src/NativePropertyTest.php @@ -164,7 +164,9 @@ public function testUnsetObjectDisablesPropertySlotsButKeepsNativeMethodCall(): $code = file_get_contents($outputFile); $this->assertStringNotContainsString('_object_prop_object__value', $code); - $this->assertStringContainsString('object.attr(', $code); + // The receiver is unstable, so the slot is re-read through the typed + // accessor instead of being hoisted into a long-lived reference. + $this->assertStringContainsString('object.attrInt(', $code); $this->assertStringContainsString('php_nativemethodunsetkeepsoptimization__read(object)', $code); } @@ -252,20 +254,20 @@ public function testNativePropertyWritesAndCompoundAssignsConvertLoweredVariantS } $code = file_get_contents($outputFile); - $this->assertStringContainsString('_object_prop_this___number += (php::toInt(', $code); - $this->assertStringContainsString('_object_prop_this___amount += (php::toFloat(', $code); - $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) += (php::toInt(', $code); - $this->assertStringContainsString('typephp_static_float_ref(_typephp_static_property_1().direct_ptr()) += (php::toFloat(', $code); + $this->assertStringContainsString('_object_prop_this___number += (source.attrInt(', $code); + $this->assertStringContainsString('_object_prop_this___amount += (source.attrFloat(', $code); + $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) += (source.attrInt(', $code); + $this->assertStringContainsString('typephp_static_float_ref(_typephp_static_property_1().direct_ptr()) += (source.attrFloat(', $code); $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) *= (1.5);', $code); $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) /= (0.5);', $code); - $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) *= (php::toFloat(', $code); - $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) /= (php::toFloat(', $code); + $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) *= (source.attrFloat(', $code); + $this->assertStringContainsString('typephp_static_int_ref(_typephp_static_property_0().direct_ptr()) /= (source.attrFloat(', $code); $this->assertStringNotContainsString('php::toInt(1.5)', $code); $this->assertStringNotContainsString('php::toInt(0.5)', $code); - $this->assertMatchesRegularExpression('/_object_prop_this___number = php::toInt\(\(\(tmp_var_\d+\) \+ \(1L+\)\)\);/', $code); - $this->assertMatchesRegularExpression('/_object_prop_this___amount = php::toFloat\(\(\(tmp_var_\d+\) \+ \(0\.5\)\)\);/', $code); - $this->assertStringContainsString('_object_prop_this___number = php::toInt(-(source.attr(', $code); - $this->assertMatchesRegularExpression('/_object_prop_this___number = php::toInt\(\(php::toBool\(cond\)\) \? \(source\.attr\(.+?\) : \(0L+\)\);/', $code); + $this->assertMatchesRegularExpression('/_object_prop_this___number = \(\(tmp_var_\d+\) \+ \(1L+\)\);/', $code); + $this->assertMatchesRegularExpression('/_object_prop_this___amount = \(\(tmp_var_\d+\) \+ \(0\.5\)\);/', $code); + $this->assertStringContainsString('_object_prop_this___number = -(source.attrInt(', $code); + $this->assertMatchesRegularExpression('/_object_prop_this___number = \(php::toBool\(cond\)\) \? \(source\.attrInt\(.+?\)\) : \(0L+\);/', $code); $this->assertMatchesRegularExpression('/_object_prop_this___number = php::toInt\(tmp_var_\d+\);/', $code); } diff --git a/src/Parser/PropertyAccessTrait.php b/src/Parser/PropertyAccessTrait.php index cda13232..0f208129 100644 --- a/src/Parser/PropertyAccessTrait.php +++ b/src/Parser/PropertyAccessTrait.php @@ -1329,34 +1329,51 @@ protected function parsePropertyFetch(Expr\PropertyFetch $expr): string $def = $declared; } } - if ($property instanceof Node\Identifier) { - $scalarRead = $this->emitDeclaredScalarPropertyRead( - $expr, - $objectVar, - $objectName, - $this->parseIdentifier($property), - $def, - $update, - ); - if ($scalarRead !== null) { - return $scalarRead; + // Resolve the declaration before the hoisting path runs. Without this, + // an ordinary variable receiver has no definition here and skips + // hoisting entirely, which turns a stable slot reference into a fresh + // offset lookup on every read. Only the scalar types the typed + // accessors can read are resolved here, so bool and string properties + // keep their previous lowering. + $scalarDef = $def; + if ($scalarDef === null && $property instanceof Node\Identifier) { + $declared = $this->findReadablePropertyDefinition($expr); + if ($declared !== null + && ($declared->type === Type::INT || $declared->type === Type::FLOAT)) { + $scalarDef = $declared; } } - if ($def && $this->usesNativeScalarStorage($def->type)) { + if ($scalarDef && $this->usesNativeScalarStorage($scalarDef->type)) { $propName = $this->parseIdentifier($property); $typedFetch = $this->emitNativeInstancePropertyTypedFetch( $expr, $objectVar, $propName, $id, - $def, + $scalarDef, $getProperty, ); if ($typedFetch !== null) { - $expr->setAttribute(self::ATTR_LOWERED_TYPE, $def->type); + $expr->setAttribute(self::ATTR_LOWERED_TYPE, $scalarDef->type); return $typedFetch; } } + // Falls back after the hoisting path: a hoisted slot reference is + // cheaper than re-resolving the offset on every read, so the typed + // fetch must get the first chance to claim a stable receiver. + if ($property instanceof Node\Identifier) { + $scalarRead = $this->emitDeclaredScalarPropertyRead( + $expr, + $objectVar, + $objectName, + $this->parseIdentifier($property), + $scalarDef, + $update, + ); + if ($scalarRead !== null) { + return $scalarRead; + } + } if ($def) { $this->setNativePropertyValueSource($expr, self::NATIVE_PROPERTY_VALUE_DYNAMIC); } @@ -1458,12 +1475,12 @@ protected function emitPropertyHookSetterCall(Expr\PropertyFetch $expr, string $ * property is stored as a plain zval scalar, the typed accessor reads the * same slot without boxing, which removes that cost from hot loops. * - * The receiver must be an exact class so the persistent property offset - * cannot move when a subclass redeclares the property: `$this` in a final - * class, or a typed object variable whose declared class is final. - * Readonly properties keep the Zend initialization check, nullable - * properties may hold null (which the typed accessors reject), and hooks - * require their own lowering, so all three keep the existing path. + * The receiver's property offset must not move across the inheritance + * chain, which `isPropertyOffsetStable()` proves; both `$this` and typed + * object variables qualify. Readonly properties keep the Zend + * initialization check, nullable properties may hold null (which the typed + * accessors reject), and hooks require their own lowering, so all three + * keep the existing path. */ private function emitDeclaredScalarPropertyRead( Expr\PropertyFetch $expr, @@ -1480,7 +1497,6 @@ private function emitDeclaredScalarPropertyRead( || $update || $def->isReadonly() || $def->nullable - || !$def->isPublic() || $def->isStatic() || $def->getter !== null || $def->setter !== null @@ -1494,6 +1510,11 @@ private function emitDeclaredScalarPropertyRead( return null; } if ($objectVar === 'this_') { + // A trait method compiles before it knows the using class, so the + // offset cannot be resolved for `$this` there. + if ($this->classDef?->trait) { + return null; + } $receiverClass = $this->getFullClassName(); } elseif ($this->isTypedObject($objectName)) { // A proven runtime class does not imply object storage: a `mixed` @@ -1508,7 +1529,7 @@ private function emitDeclaredScalarPropertyRead( } if ($receiverClass === '' || $this->isNativeObjectClass($receiverClass) - || !$this->isFinalClass($receiverClass)) { + || !$this->isPropertyOffsetStable($receiverClass, $propName)) { return null; } $accessor = $def->type === Type::INT ? 'attrInt' : 'attrFloat'; @@ -1518,6 +1539,46 @@ private function emitDeclaredScalarPropertyRead( . '(' . $this->getPropertyOffset($receiverClass, $propName) . ')'; } + /** + * Prove that `$class::$prop` keeps one zval slot for every subclass. + * + * Zend reuses the parent's slot when a child redeclares a non-private + * property, so the declaring class offset stays valid for subclass + * instances. A child that adds a property hook the parent does not have is + * the exception: Zend resets the parent slot to IS_UNDEF and moves the + * child to a fresh offset, which would make the parent offset read the + * wrong slot. Unknown classes stay on the Variant path. + */ + private function isPropertyOffsetStable(string $class, string $prop): bool + { + if (!$this->hasClass($class)) { + return false; + } + if ($this->isFinalClass($class)) { + return true; + } + $pending = $this->classSubClasses[strtolower(ltrim($class, '\\'))] ?? []; + $visited = []; + while ($pending !== []) { + $sub = array_shift($pending); + if (isset($visited[$sub])) { + continue; + } + $visited[$sub] = true; + $subDef = $this->getClassDef($sub); + if ($subDef !== null && $subDef->hasProperty($prop)) { + $property = $subDef->getProperty($prop); + if ($property->getter !== null || $property->setter !== null || $property->virtual) { + return false; + } + } + foreach ($this->classSubClasses[$sub] ?? [] as $grandChild) { + $pending[] = $grandChild; + } + } + return true; + } + private function emitNativeInstancePropertyTypedFetch( Expr\PropertyFetch $expr, string $objectVar, diff --git a/tests/compiler/object_property/declared-scalar-read-subclass-redeclare.phpt b/tests/compiler/object_property/declared-scalar-read-subclass-redeclare.phpt index 66c8b3e4..6368071e 100644 --- a/tests/compiler/object_property/declared-scalar-read-subclass-redeclare.phpt +++ b/tests/compiler/object_property/declared-scalar-read-subclass-redeclare.phpt @@ -1,5 +1,5 @@ --TEST-- -non-final receivers keep the name-based read when a subclass redeclares the property +a subclass redeclaring a scalar property reuses the parent slot --FILE-- Date: Fri, 13 Nov 2026 22:19:45 +0800 Subject: [PATCH 4/5] test(compiler): assert the typed slot read inside a match arm The arm now reads the declared int property through attrInt, so the conversion happens at the lambda boundary instead of wrapping the property fetch. Keep asserting the boundary type and the typed read so the test still covers what it was written for. --- phpunit/src/MatchExpressionCodegenTest.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/phpunit/src/MatchExpressionCodegenTest.php b/phpunit/src/MatchExpressionCodegenTest.php index 3e285621..0a369921 100644 --- a/phpunit/src/MatchExpressionCodegenTest.php +++ b/phpunit/src/MatchExpressionCodegenTest.php @@ -90,7 +90,10 @@ public function testMatchArmPropertyReadConvertsAtTypedBoundary(): void { $fnCode = $this->extractFunction('php_testmatcharmpropertyread'); self::assertStringContainsString('[&]() -> php::Int {', $fnCode); - self::assertStringContainsString('php::toInt(obj.attr(', $fnCode); + // The arm already reads the slot as an int, so the conversion happens + // at the lambda boundary instead of around the property fetch. + self::assertStringContainsString('obj.attrInt(get_persistent_prop(', $fnCode); + self::assertStringContainsString('php::toInt([&]() -> php::Int {', $fnCode); $ternaryCode = $this->extractFunction('php_testmatcharmternarypropertyread'); self::assertStringContainsString('[&]() -> php::Int {', $ternaryCode); From 90dde0eddc4f2d40e1fca054f1b3a55b745e3215 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8E=9F=E7=82=B9?= <467490186@qq.com> Date: Fri, 13 Nov 2026 23:16:05 +0800 Subject: [PATCH 5/5] fix(compiler): do not claim native storage for a readonly scalar read A readonly scalar read keeps the dynamic value source, so its result is materialized as a Variant. #186 correctly converts the read back to the declared scalar, but it also stamped the expression with the declared type. The surrounding expression then trusted that type and dropped its own conversion: `$rect->width / 2.0` compiled to a raw Variant division assigned to php::Float, which is C2440. Keep the conversion in the read and leave the lowered type alone, so the arithmetic keeps its toFloat/toInt. The switch discriminant consequently falls back to PHP's loose equality over the Variant, which matches the value the read actually returns. Cover the readonly float division that the Drift2 layout code hits. --- ...ed-scalar-property-read-readonly-arith.php | 15 ++++++++++++ .../src/DeclaredScalarPropertyReadTest.php | 16 +++++++++++++ phpunit/src/ReadonlyTypedPropertyReadTest.php | 4 +++- src/Parser/PropertyAccessTrait.php | 23 +++++++++++++++---- 4 files changed, 53 insertions(+), 5 deletions(-) create mode 100644 phpunit/code/declared-scalar-property-read-readonly-arith.php diff --git a/phpunit/code/declared-scalar-property-read-readonly-arith.php b/phpunit/code/declared-scalar-property-read-readonly-arith.php new file mode 100644 index 00000000..516a6b24 --- /dev/null +++ b/phpunit/code/declared-scalar-property-read-readonly-arith.php @@ -0,0 +1,15 @@ +width < $box->height ? $box->width / 2.0 : $box->height / 2.0; +} diff --git a/phpunit/src/DeclaredScalarPropertyReadTest.php b/phpunit/src/DeclaredScalarPropertyReadTest.php index 907628f2..8718ffb6 100644 --- a/phpunit/src/DeclaredScalarPropertyReadTest.php +++ b/phpunit/src/DeclaredScalarPropertyReadTest.php @@ -125,6 +125,22 @@ public function testReadonlyPropertyKeepsCheckedRead(): void $this->assertStringNotContainsString('attrInt(get_persistent_prop(', $code); } + public function testReadonlyPropertyKeepsTheConversionOnArithmetic(): void + { + try { + $outputFile = $this->compileCode('declared-scalar-property-read-readonly-arith.php'); + } catch (TestError $e) { + $this->fail($e->getMessage()); + } + + $code = file_get_contents($outputFile); + // The read is materialized as a Variant, so the division still has to + // be converted instead of being treated as an already native float. + $this->assertStringContainsString('typephp_read_property_scoped(', $code); + $this->assertStringContainsString('php::toFloat(((tmp_var_', $code); + $this->assertStringNotContainsString('attrFloat(get_persistent_prop(', $code); + } + public function testNarrowedMixedReceiverKeepsVariantRead(): void { try { diff --git a/phpunit/src/ReadonlyTypedPropertyReadTest.php b/phpunit/src/ReadonlyTypedPropertyReadTest.php index d48f3a99..6e5fe11a 100644 --- a/phpunit/src/ReadonlyTypedPropertyReadTest.php +++ b/phpunit/src/ReadonlyTypedPropertyReadTest.php @@ -41,7 +41,9 @@ public function testReadonlyScalarReadsRestoreDeclaredStorageType(): void // initialized from it directly. $this->assertStringContainsString('php::toInt(typephp_read_property_scoped(this_,', $code); $this->assertStringContainsString('php::toFloat(typephp_read_property_scoped(this_,', $code); - $this->assertStringContainsString('switch (tmp_var_0)', $code); + // The read keeps its Variant storage, so the discriminant compares + // through PHP's loose equality instead of a native switch. + $this->assertStringContainsString('php::equals(tmp_var_0, 0LL)', $code); // Readonly properties stay out of the hoisted scalar reference path. $this->assertStringNotContainsString('_object_prop_this___status', $code); $this->assertStringNotContainsString('_object_prop_this___ratio', $code); diff --git a/src/Parser/PropertyAccessTrait.php b/src/Parser/PropertyAccessTrait.php index 0f208129..a7ecb9b4 100644 --- a/src/Parser/PropertyAccessTrait.php +++ b/src/Parser/PropertyAccessTrait.php @@ -1332,13 +1332,22 @@ protected function parsePropertyFetch(Expr\PropertyFetch $expr): string // Resolve the declaration before the hoisting path runs. Without this, // an ordinary variable receiver has no definition here and skips // hoisting entirely, which turns a stable slot reference into a fresh - // offset lookup on every read. Only the scalar types the typed - // accessors can read are resolved here, so bool and string properties - // keep their previous lowering. + // offset lookup on every read. + // + // Only a plain int/float declaration qualifies. Bool and string keep + // their previous lowering, and a readonly or hooked property keeps its + // own path: the readonly branch reads through the dynamic value source, + // so materializing its result as a native scalar while the temporary + // stays a Variant would drop the conversion the surrounding expression + // still needs. $scalarDef = $def; if ($scalarDef === null && $property instanceof Node\Identifier) { $declared = $this->findReadablePropertyDefinition($expr); if ($declared !== null + && !$declared->isReadonly() + && $declared->getter === null + && $declared->setter === null + && !$declared->virtual && ($declared->type === Type::INT || $declared->type === Type::FLOAT)) { $scalarDef = $declared; } @@ -1354,7 +1363,13 @@ protected function parsePropertyFetch(Expr\PropertyFetch $expr): string $getProperty, ); if ($typedFetch !== null) { - $expr->setAttribute(self::ATTR_LOWERED_TYPE, $scalarDef->type); + // A readonly read keeps the dynamic value source and is + // materialized as a Variant, so advertising a native scalar + // type would strip the conversion the surrounding expression + // still needs. + if (!$scalarDef->isReadonly()) { + $expr->setAttribute(self::ATTR_LOWERED_TYPE, $scalarDef->type); + } return $typedFetch; } }