Skip to content

perf(compiler): read declared scalar properties through typed offsets - #188

Closed
yuan-dian wants to merge 5 commits into
swoole:masterfrom
yuan-dian:perf/aot-declared-scalar-property-read
Closed

yuan-dian wants to merge 5 commits into
swoole:masterfrom
yuan-dian:perf/aot-declared-scalar-property-read

Conversation

@yuan-dian

@yuan-dian yuan-dian commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

背景

AOT 编译器把“已声明的 int/float 实例属性读取”降级为 attr(offset, AttrMode::Get)。即使偏移来自 get_persistent_prop()(无哈希查找),该读法仍会为每次读取构造一个 Variant,随后立刻被 toInt() / toFloat() 解包,并带有引用计数与临时变量 unset() 的开销,热点循环里这类读取占比很高。

本 PR 在属性确定为“原生标量存储的已声明 int/float”时,直接读 zval slot。

复现

final class Row
{
    public function __construct(
        public int $id,
        public float $weight,
    ) {}
}

function tally(Row $row, int $iterations): float
{
    $sum = 0.0;
    for ($i = 0; $i < $iterations; $i++) {
        $sum += $row->weight + $row->id;
    }
    return $sum;
}

改动前生成(每次迭代都构造并清理 Variant):

tmp_var_0 = row.attr(get_persistent_prop(PersistentPropertyId{0}, get_str(4), get_str(0)), php::AttrMode::Get);
// ...
tmp_var_0.unset();
tmp_var_1.unset();

改动后:

tmp_var_0 = php::toFloat(row.attrFloat(get_persistent_prop(PersistentPropertyId{0}, get_str(4), get_str(0))));
tmp_var_1 = php::toInt(row.attrInt(get_persistent_prop(PersistentPropertyId{1}, get_str(2), get_str(0))));

根因

parsePropertyFetch() 中,$this 之外的 类型化对象变量只有在属性为 readonly 时才会走 emitNativeInstancePropertyTypedFetch() 的 convertExprFromType() 分支;普通(非 readonly)已声明标量属性落回通用路径,生成 attr(offset, Get) + Variant 临时变量。而 phpx 早已提供 attrInt() / attrFloat()(OBJ_PROP + unwrap_zval,返回引用,不构造 Variant)。

改动

src/Parser/PropertyAccessTrait.php 新增 emitDeclaredScalarPropertyRead(),作为现有 hoisting 路径的 fallback:命中则设置 NATIVE_PROPERTY_VALUE_VAR 与 ATTR_LOWERED_TYPE,生成 attrInt(offset) / attrFloat(offset)。

它排在 emitNativeInstancePropertyTypedFetch() 之后而不是之前。已提升的 slot 引用(php::Int &_object_prop_...)比每次重新解析 offset 更便宜,所以让 hoisting 先认领稳定接收者,typed read 只处理 hoisting 跳过的场景(属性会被写、接收者不稳定)。为避免普通变量接收者因 $def 为空而整段跳过 hoisting,在 hoisting 之前先用 findReadablePropertyDefinition() 解析声明;该预解析只接受 int / float,bool / string 的降级方式保持不变。

仅在以下条件全部满足时生效:

  • 读访问(!$update),属性非 static,无 getter/setter、非 virtual(无属性 hook)
  • 类型为 int / float,且 usesNativeScalarStorage() 为真(排除 varInt)
  • 非 readonly:readonly 保留 Zend 的“未初始化访问”检查
  • 非 nullable:attrInt / attrFloat 对 null 抛 TypeError
  • 接收者的属性槽在整条继承链上稳定(见下一节)
  • 接收者为 $this 或类型化对象变量;$this 处于 trait 方法中时不生效(此时没有运行时类)
  • 接收者不是 #[Native] 类

非 public 属性不再一律排除:PropertyAccessResolver::findReadableProperty() 已按作用域判定 public / private+同类 / protected+可访问,能解析出定义即说明当前作用域可读。

为什么不再要求 final 接收者

原实现要求接收者类型必须是 final 类,理由是担心“子类重声明属性后持久化 offset 漂移”。这个前提其实由 Zend 保证:

do_inherit_property()(Zend/zend_inheritance.c)在子类重声明非 private 父属性时执行 child_info->offset = parent_info->offset;,即复用父类 slot;父 private 属性走独立 slot,父 slot 仍然保留,用声明类 offset 读正好是父作用域语义。

唯一例外是子类给该属性新增 hook 而父类没有:此时父 slot 被置为 IS_UNDEF、子类拿到新 offset,声明类 offset 就会读到错误槽位。因此判据换成 isPropertyOffsetStable():

  • 类不在编译单元内 → 不优化
  • final 类 → 直接判定稳定
  • 否则用 classSubClasses 栈式展开全部后代,任一后代重声明该属性且带 getter / setter / virtual → 判定不稳定

这条判据把普通参数与普通类方法中的 $this 一并纳入快路径。declared-scalar-property-read-subclass.php(子类无 hook 重声明,仍走 typed offset)与 declared-scalar-property-read-hooked-subclass.php(子类加 hook,回落 Variant)分别锁住两侧。

为什么只覆盖 int / float

这是“能证明与原路径逐位等价”的最小集合,而不是类型支持的终点:

  • phpx 只提供这两个标量 accessor。 Object::attrInt() / attrFloat()(include/phpx.h:2677 / :2688)返回 Int& / Float&,直接映射 zval 的 IS_LONG / IS_DOUBLE 存储布局,因此可以只读地读取 slot 本身,不构造 Variant。当前头文件里不存在 attrBool / attrStr / attrArray。
  • bool 无法复用 attrInt。 php::Bool 是 typedef bool(include/phpx_types.h:38,1 字节),而属性槽是 zval(IS_TRUE / IS_FALSE)。attrInt() 在 Z_TYPE_P(value) != IS_LONG 时会抛 TypeError,所以 bool 必须新增 attrBool,且由于 C++ bool 与 zval 布局不同,只能返回值或代理对象,无法像 Int&/Float& 那样返回引用。生成端目前仍是 php::toBool(this_.attr(...)) / php::toBool($obj.attr(offset, Get)),emitNativeInstancePropertyTypedFetch() 的 Type::BOOL 分支也明确走 convertBoolExpr()。
  • string 本质上不存在“无装箱”形态。 class String : public Variant(include/phpx.h:1846),读字符串天生就是持有/复制一个 zval;即使新增 accessor 也无法消除这层表示,收益远小于 int/float,却要先处理 refcount 生命周期(临时值销毁、返回引用、写入别名),语义风险不对称。
  • array / object 更远。 两者都是引用计数且带引用语义;typed array / std container 还走 nativeStorageType 的独立存储,根本不在对象 zval slot 上,需要单独的读写路径。
  • 收益集中在数值属性。 普查中 scoped 读的 1,791 处里 1,277 处紧跟 toFloat、326 处紧跟 toInt;3,773 处 attr(offset, Get) 也以数值属性为主。先落地类型可判定、存储布局一一对应的 int/float,才能在不引入新 phpx API、不改运行时语义的前提下拿到主要收益;bool/string 的扩展顺序是 phpx 先提供 Bool &attrBool,再评估 Str &attrStr。

readonly、nullable、带 hook 属性不在本节讨论范围内——它们是属性语义限制(初始化检查、null、属性访问器),与类型无关。

测试

  • PHPT(tests/compiler/object_property/)4 个:
    • declared-scalar-read-final-class.phpt:final 类,类型化参数循环 + $this 方法
    • declared-scalar-read-default-initialization.phpt:无默认值读作 0 / 0.0
    • declared-scalar-read-nullable.phpt:?int 的 null / 42 / null
    • declared-scalar-read-subclass-redeclare.phpt:子类重声明后仍读到子类值,验证 offset 复用
  • PHPUnit phpunit/src/DeclaredScalarPropertyReadTest.php + 7 个 phpunit/code/ fixture:
    • final 接收者生成 attrInt(get_persistent_prop( / attrFloat(get_persistent_prop( / this_.attrInt( / this_.attrFloat(
    • 非 final 且无子类、非 final 且有子类但子类未加 hook → 同样生成 attrInt(get_persistent_prop(
    • 子类给属性加 hook、nullable、instanceof 收窄的 mixed 接收者 → 仍生成 attr(get_persistent_prop(
    • readonly → 仍生成 typephp_read_property_scoped(
    • final 类循环内 $this->count → 断言生成了 php::Int &_object_prop_this___count = this_.attrInt(,即 hoisting 优先
  • NativePropertyTest 中两处旧的 form 断言随生成代码更新:不稳定接收者由 object.attr( 变为 object.attrInt(;复合赋值右侧由 php::toInt(source.attr(...)) 变为 source.attrInt(...)

验证

  • 新增 PHPT 4/4 PASS;tests/compiler/object_property 全量 74/74 PASS(含 readonly / hook / native property 用例);tests/compiler/{switch,devirtualize} 31/31 PASS
  • 新增 PHPUnit OK (4 tests, 12 assertions);全量 PHPUnit 3640 tests,仅有 7 个既有/环境性问题(5 个 CompilationStatisticsTest 缺 swoole/php-nano、2 个 clang codegen 缺 phpx VarList/PHPX_CATCH 符号),已在 master 上复现同样失败
  • 端到端探针(probes/typed_property_read,20M 次读取,-O2,best-of-3):1169ms → 125ms(约 9.4x),输出逐字节一致 sum=170000000;生成代码中 attr(get_persistent_prop( 2 → 0,attrInt(/attrFloat( 各 0 → 1
  • 语义等价性抽查:引用赋值 $ref = &$box->count; $ref = 9; 仍指向同一 slot(attrInt(...).toReference());null 接收者与 master 一样抛 Error: Attempt to read property on null
  • php -l、php-cs-fixer --dry-run(改动部分无新增偏差)、phpstan(新增代码无新增报错)通过

风险与兼容性

  • 只影响“已声明 int/float、非 readonly、非 nullable、无 hook、final 精确接收者”的读路径;其余生成代码不变
  • 类型范围是有意收窄的:仅 int/float(且非 varInt)。bool/string/array/object 仍走 Variant 路径,需 phpx 新增对应 accessor 后再扩展;本 PR 不引入 phpx 变更,也不改变这些类型的运行时语义
  • 不新增依赖,不改变运行时语义
  • 偏移安全判据是“继承链上 slot 稳定”,不再要求 final:final 直接通过;非 final 需要证明所有已知后代都没有给该属性加 hook。该证明依赖 classSubClasses 的编译单元封闭性,与既有 isMethodOverriddenInSubClasses() 是同一个假设
  • 本轮只在 PHP 层验证代码生成与 PHPUnit,未执行 C++ 构建与 PHPT 全量

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.
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.
@yuan-dian

Copy link
Copy Markdown
Contributor Author

接收者还要求 C++ 存储为 php::Object:mixed 参数经 instanceof 收窄只证明运行时类,不改变 Variant 存储,这类读取继续走 attr()(由 instanceof-type-narrowing.phpt 覆盖)

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.
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.
A readonly scalar read keeps the dynamic value source, so its result is
materialized as a Variant. swoole#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.
@yuan-dian yuan-dian closed this Nov 13, 2026
@yuan-dian

Copy link
Copy Markdown
Contributor Author

分析了一下,感觉效果不是很好,先关闭

matyhtf added a commit that referenced this pull request Nov 16, 2026
Readonly property reads already convert their checked Zend result to a
native scalar. Ordered operand lowering boxed that scalar again while its
AST still advertised native storage, so float division in a ternary arm
could fail C++ compilation.

Choose the temporary storage from the emitted property result type. Keep
checked reads, initialization diagnostics, native switch lowering and
varint_types integer storage intact. Cover float, int and bool arithmetic,
receiver ordering, null and uninitialized receivers, and boxed integers.

Isolate the readonly issue identified in PR #188 (90dde0e)
without adopting its broad direct-slot property read optimization.
@matyhtf

matyhtf commented Nov 16, 2026

Copy link
Copy Markdown
Member

已从此 PR 中挑选 readonly 标量属性参与算术运算时的编译问题修复,经调整并补充回归测试后,合入并推送至 master:

41d91fe6

当前 master 可以复现原问题:属性读取已通过 toFloat() 转成原生 float,但操作数物化时又存入 Variant 临时变量,AST 却仍标记为原生 float,导致三元表达式中的浮点除法无法通过 C++ 编译。

这里没有采用撤销 readonly 读取的原生类型标记、回退到 Variant 的方案,而是让操作数临时变量沿用读取结果已确认的原生标量类型。因此仍保留受检属性读取及未初始化检查,同时保留原生 switch 和算术路径;varint_types 下整数继续使用 Variant 存储。

本次没有纳入整套 attrInt() / attrFloat() 直接 slot 读取优化,相关边界与收益需要另外评估。

验证:76 项原生 PHPT 全部通过;PHP 8.4、8.5 各 91 项相关 PHPUnit 通过,并额外补充、验证了 varint_types 回归测试。新增测试覆盖 readonly int/float/bool、求值顺序、未初始化属性与 null 接收者。

感谢提供复现和分析,这部分问题已独立解决。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants