faster-cpython / ideas

1.68k stars 48 forks source link

Lower `BEFORE_WITH` and `BEFORE_ASYNC_WITH` to attribute lookups and calls. #685

Closed markshannon closed 3 months ago

markshannon commented 3 months ago

With the JIT and better tier 2 optimizations, effective specialization is becoming more important that plain speed in tier 1.

BEFORE_WITH and BEFORE_ASYNC_WITH could be specialized, but they are bulky and won't optimize well in tier 2. Instead, we should lower them to attribute lookups and calls which can then be optimized. We should add a LOAD_SPECIAL instruction for loading dunder methods and replace BEFORE_WITH as follows:

    COPY 1
    LOAD_SPECIAL __enter__ + NULL|self
    SWAP 3
    LOAD_SPECIAL __exit__
    SWAP 3
    CALL 0

Likewise for BEFORE_ASYNC_WITH.

Even without any specialization of LOAD_SPECIAL, the CALL will be specialized and the JIT can eliminate the COPY and SWAPs.

markshannon commented 3 months ago

https://github.com/python/cpython/issues/120507