diff --git a/Doc/c-api/frame.rst b/Doc/c-api/frame.rst index a086c60905402e..2fe2192ac030cd 100644 --- a/Doc/c-api/frame.rst +++ b/Doc/c-api/frame.rst @@ -78,13 +78,17 @@ See also :ref:`Reflection `. .. c:function:: PyObject* PyFrame_GetGenerator(PyFrameObject *frame) Get the generator, coroutine, or async generator that owns this frame, - or ``NULL`` if this frame is not owned by a generator. - Does not raise an exception, even if the return value is ``NULL``. + or ``None`` if this frame is not owned by a generator. + Does not raise an exception. - Return a :term:`strong reference`, or ``NULL``. + Return a :term:`strong reference`. .. versionadded:: 3.11 + .. versionchanged:: 3.16 + May return ``None`` for a coroutine frame before its first suspension; + see :attr:`frame.f_generator`. + .. c:function:: PyObject* PyFrame_GetGlobals(PyFrameObject *frame) diff --git a/Doc/library/dis.rst b/Doc/library/dis.rst index 1b5f0c92faf02c..f86e59d50289e0 100644 --- a/Doc/library/dis.rst +++ b/Doc/library/dis.rst @@ -815,7 +815,7 @@ not have to be) the original ``STACK[-2]``. **Coroutine opcodes** -.. opcode:: GET_AWAITABLE (where) +.. opcode:: GET_AWAITABLE (flags) Replaces ``STACK[-1]`` with ``get_awaitable(STACK[-1])``, ``NULL`` and ``None``, ready for :opcode:`SEND`. ``get_awaitable(o)`` @@ -823,11 +823,26 @@ not have to be) the original ``STACK[-2]``. the :data:`~inspect.CO_ITERABLE_COROUTINE` flag, or resolves ``o.__await__``. - If the ``where`` operand is nonzero, it indicates where the instruction - occurs: - - * ``1``: After a call to ``__aenter__`` - * ``2``: After a call to ``__aexit__`` + The low two bits of *flags*, if nonzero, indicate where the instruction + occurs: + + * ``1``: After a call to ``__aenter__`` + * ``2``: After a call to ``__aexit__`` + + If *flags* has the ``4`` bit set, the instruction follows a call whose + result is awaited right away (``await f()``, and the calls of + :meth:`~object.__aenter__` and :meth:`~object.__aexit__` in + :keyword:`async with`). The compiler pushes an extra ``NULL``, the + *lazy outcome*, below the callable of such a call, and the call may run + the body of a coroutine function without creating the coroutine object, + reporting in the lazy outcome, ``STACK[-2]``, how the body ended. + If the lazy outcome is ``NULL``, it is removed and the instruction + proceeds as described above. If the body returned, it is removed and + execution continues after the :opcode:`END_SEND` of the following + :opcode:`SEND` loop. If the body suspended, the coroutine object is + created and execution continues at the :opcode:`YIELD_VALUE` of that + loop, with ``STACK[-3:]`` set to the coroutine, ``NULL`` and the yielded + value. .. versionadded:: 3.5 @@ -836,7 +851,7 @@ not have to be) the original ``STACK[-2]``. .. versionchanged:: next Also pushes ``NULL`` and ``None``, which were previously pushed by - separate instructions. + separate instructions. Added the awaited call flag. .. opcode:: GET_AITER diff --git a/Doc/library/inspect.rst b/Doc/library/inspect.rst index 51c465e8f00b5e..328bfea8a372ab 100644 --- a/Doc/library/inspect.rst +++ b/Doc/library/inspect.rst @@ -151,7 +151,9 @@ attributes (see :ref:`import-mod-attrs` for module attributes): | | | coroutine object that | | | | owns this frame, or | | | | ``None`` if the frame is | -| | | of a regular function | +| | | of a regular function or | +| | | the generator is not | +| | | materialized yet | +-----------------+-------------------+---------------------------+ | | f_trace | tracing function for this | | | | frame, or ``None`` | diff --git a/Doc/reference/datamodel.rst b/Doc/reference/datamodel.rst index 02663ed465f424..07fa9cf5441e64 100644 --- a/Doc/reference/datamodel.rst +++ b/Doc/reference/datamodel.rst @@ -1736,10 +1736,22 @@ Special read-only attributes * - .. attribute:: frame.f_generator - The :term:`generator` or :term:`coroutine` object that owns this frame, - or ``None`` if the frame is a normal function. + or ``None`` if the frame is a normal function or if the generator + is not materialized yet. + + .. impl-detail:: + + A coroutine that is awaited as soon as it is called + (``await coro_func()``) may run without a coroutine object until + it first suspends, so this attribute is ``None`` before that. + Use :attr:`~codeobject.co_flags` of :attr:`frame.f_code` to tell + coroutine frames apart from normal function frames. .. versionadded:: 3.14 + .. versionchanged:: 3.16 + May be ``None`` for a coroutine frame before its first suspension. + .. index:: single: f_trace (frame attribute) single: f_trace_lines (frame attribute) diff --git a/Doc/whatsnew/3.16.rst b/Doc/whatsnew/3.16.rst index 33328b2ee00521..b941c3b95dd1ac 100644 --- a/Doc/whatsnew/3.16.rst +++ b/Doc/whatsnew/3.16.rst @@ -1147,6 +1147,26 @@ datetime and time (Contributed by Paul Ganssle in :gh:`158252`, based on work by Stan Ulbrych.) +Interpreter +----------- + +* A coroutine that is awaited as soon as it is called + (``await coro_func()``), and an ``async def`` :meth:`~object.__aenter__` + or :meth:`~object.__aexit__` of an :keyword:`async with` statement, now + runs without creating a coroutine object unless it suspends, making awaits + that complete immediately about twice as fast in a micro-benchmark + (``await noop()``: 52 ns to 27 ns on x86-64). + :meth:`~object.__aexit__` still runs with a coroutine object when the body + of the :keyword:`async with` statement raised an exception. + This does not apply while coroutine origin tracking is enabled, while a + profiler or :mod:`sys.monitoring` tool receives call events (for example + :func:`sys.setprofile` or :mod:`profiling.tracing`), while a :pep:`523` frame + evaluation function is set, or inside code compiled by the experimental JIT. + Until it first suspends, :attr:`frame.f_generator` is ``None`` for such a + coroutine, so its value may differ when one of these is active; + see :ref:`whatsnew316-porting`. + (Contributed by Andrew Svetlov in :gh:`161170`.) + re -- @@ -1405,12 +1425,26 @@ New deprecations .. include:: ../deprecations/pending-removal-in-future.rst +.. _whatsnew316-porting: + Porting to Python 3.16 ====================== This section lists previously described changes and other bugfixes that may require changes to your code. +* :attr:`frame.f_generator` and :c:func:`PyFrame_GetGenerator` may now + return ``None`` for a coroutine frame before its first + suspension, because a coroutine that is awaited as soon as it is called + (``await coro_func()``) runs without a coroutine object until then. + Code that used ``frame.f_generator is None`` to detect frames of normal + functions should check ``frame.f_code.co_flags`` for + :data:`~inspect.CO_COROUTINE` instead. + For the same reason, such a coroutine takes its ``__name__`` and + ``__qualname__`` from its function when it first suspends, not when it + is called. + (Contributed by Andrew Svetlov in :gh:`161170`.) + * In :mod:`tkinter`, the *name* parameter of the :meth:`~tkinter.Misc.wait_variable`, :meth:`~tkinter.Misc.setvar` and :meth:`~tkinter.Misc.getvar` methods and the *value* parameter of @@ -1488,6 +1522,18 @@ that may require changes to your code. (Contributed by An Long in :gh:`86768`.) +CPython bytecode changes +======================== + +* ``await `` and the calls of :meth:`~object.__aenter__` and + :meth:`~object.__aexit__` in :keyword:`async with` now push an extra + ``NULL`` below the callable and + follow the call with :opcode:`GET_AWAITABLE` with a new flag in its oparg. + It then also either skips the :opcode:`SEND` loop or jumps to its + :opcode:`YIELD_VALUE`. + (Contributed by Andrew Svetlov in :gh:`161170`.) + + Build changes ============= diff --git a/Include/internal/pycore_ceval.h b/Include/internal/pycore_ceval.h index c404fc6e67d193..d25afac268becd 100644 --- a/Include/internal/pycore_ceval.h +++ b/Include/internal/pycore_ceval.h @@ -267,6 +267,13 @@ extern int _PyEval_EnsureBuiltinsWithModule( PyObject **p_builtins); PyAPI_FUNC(PyObject *)_Py_MakeCoro(PyFunctionObject *func); +PyAPI_FUNC(PyObject *) _PyCoro_MaterializeLazy(_PyInterpreterFrame *frame); +PyAPI_FUNC(_PyInterpreterFrame *) _PyEval_SuspendLazyCoro( + PyThreadState *tstate, _PyInterpreterFrame *frame); +PyAPI_FUNC(PyGenObject *) _PyEval_MaterializeLazyCoro(PyThreadState *tstate, + _PyInterpreterFrame *frame); +PyAPI_FUNC(_PyInterpreterFrame *) _PyEval_ThrowIntoLazyCoro( + PyThreadState *tstate, _PyInterpreterFrame *frame, _PyStackRef value); /* Handle signals, pending calls, GIL drop request and asynchronous exception */ diff --git a/Include/internal/pycore_interpframe.h b/Include/internal/pycore_interpframe.h index a85fa9bd32853c..7eeb6b1a6a9766 100644 --- a/Include/internal/pycore_interpframe.h +++ b/Include/internal/pycore_interpframe.h @@ -152,6 +152,7 @@ static inline void _PyFrame_Copy(_PyInterpreterFrame *src, _PyInterpreterFrame * dest->stackpointer = dest->localsplus + stacktop; // visited is GC bookkeeping for the current stack walk, not frame state. dest->visited = 0; + dest->lazy_coro = 0; #ifdef Py_DEBUG dest->stackpointer_valid = src->stackpointer_valid; dest->lltrace = src->lltrace; @@ -208,6 +209,7 @@ _PyFrame_Initialize( frame->return_offset = 0; frame->owner = FRAME_OWNED_BY_THREAD; frame->visited = 0; + frame->lazy_coro = 0; #ifdef Py_DEBUG frame->stackpointer_valid = 1; frame->lltrace = 0; @@ -292,7 +294,7 @@ _PyFrame_StackAssertInvalid(_PyInterpreterFrame *frame) static inline bool _Py_NO_SANITIZE_THREAD _PyFrame_IsIncomplete(_PyInterpreterFrame *frame) { - if (frame->owner >= FRAME_OWNED_BY_INTERPRETER) { + if (frame->owner == FRAME_OWNED_BY_INTERPRETER) { return true; } return frame->owner != FRAME_OWNED_BY_GENERATOR && @@ -441,6 +443,7 @@ _PyFrame_PushTrampolineUnchecked(PyThreadState *tstate, PyCodeObject *code, int #endif frame->owner = FRAME_OWNED_BY_THREAD; frame->visited = 0; + frame->lazy_coro = 0; #ifdef Py_DEBUG frame->stackpointer_valid = 1; frame->lltrace = 0; diff --git a/Include/internal/pycore_interpframe_structs.h b/Include/internal/pycore_interpframe_structs.h index 0d6a37cc2c1a17..572f7301b52709 100644 --- a/Include/internal/pycore_interpframe_structs.h +++ b/Include/internal/pycore_interpframe_structs.h @@ -24,6 +24,9 @@ enum _frameowner { FRAME_OWNED_BY_GENERATOR = 1, FRAME_OWNED_BY_FRAME_OBJECT = 2, FRAME_OWNED_BY_INTERPRETER = 3, + /* A coroutine body running in the frame of the thread, without a + * coroutine object; see RETURN_GENERATOR. */ + FRAME_OWNED_BY_LAZY_CORO = 4, }; struct _PyInterpreterFrame { @@ -44,14 +47,17 @@ struct _PyInterpreterFrame { char owner; uint8_t visited:1; uint8_t external:1; /* Set when the frame was pushed by something other than the VM */ + uint8_t lazy_coro:1; /* LAZY_CORO_REQUESTED */ #ifdef Py_DEBUG uint8_t stackpointer_valid:1; - uint8_t lltrace:5; + uint8_t lltrace:4; #endif /* Locals and stack */ _PyStackRef localsplus[1]; }; +#define LAZY_CORO_REQUESTED 1 + /* _PyGenObject_HEAD defines the initial segment of generator and coroutine objects. */ diff --git a/Include/internal/pycore_magic_number.h b/Include/internal/pycore_magic_number.h index 041256df56b493..364e6ed20608b4 100644 --- a/Include/internal/pycore_magic_number.h +++ b/Include/internal/pycore_magic_number.h @@ -306,6 +306,7 @@ Known values: Python 3.16a1 3706 (Add INTRINSIC_MATCH_CLASS_ISINSTANCE) Python 3.16a1 3707 (GET_AWAITABLE also pushes NULL and None for SEND) Python 3.16a1 3708 (GET_ANEXT also pushes NULL and None for SEND) + Python 3.16a1 3709 (Lazily materialize coroutine objects for awaited calls) Python 3.17 will start with 3750 @@ -315,7 +316,7 @@ Known values: */ -#define PYC_MAGIC_NUMBER 3708 +#define PYC_MAGIC_NUMBER 3709 /* This is equivalent to converting PYC_MAGIC_NUMBER to 2 bytes (little-endian) and then appending b'\r\n'. */ #define PYC_MAGIC_NUMBER_TOKEN \ diff --git a/Include/internal/pycore_opcode_metadata.h b/Include/internal/pycore_opcode_metadata.h index f1e6f1beae644a..31dadf002b72de 100644 --- a/Include/internal/pycore_opcode_metadata.h +++ b/Include/internal/pycore_opcode_metadata.h @@ -98,8 +98,12 @@ int _PyOpcode_num_popped(int opcode, int oparg) { return 2 + oparg; case CALL_BOUND_METHOD_EXACT_ARGS: return 2 + oparg; + case CALL_BOUND_METHOD_EXACT_ARGS_AWAITED: + return 2 + oparg; case CALL_BOUND_METHOD_GENERAL: return 2 + oparg; + case CALL_BOUND_METHOD_GENERAL_AWAITED: + return 2 + oparg; case CALL_BUILTIN_CLASS: return 2 + oparg; case CALL_BUILTIN_FAST: @@ -124,10 +128,14 @@ int _PyOpcode_num_popped(int opcode, int oparg) { return 3 + oparg; case CALL_KW_BOUND_METHOD: return 3 + oparg; + case CALL_KW_BOUND_METHOD_AWAITED: + return 3 + oparg; case CALL_KW_NON_PY: return 3 + oparg; case CALL_KW_PY: return 3 + oparg; + case CALL_KW_PY_AWAITED: + return 3 + oparg; case CALL_LEN: return 3; case CALL_LIST_APPEND: @@ -144,8 +152,12 @@ int _PyOpcode_num_popped(int opcode, int oparg) { return 2 + oparg; case CALL_PY_EXACT_ARGS: return 2 + oparg; + case CALL_PY_EXACT_ARGS_AWAITED: + return 2 + oparg; case CALL_PY_GENERAL: return 2 + oparg; + case CALL_PY_GENERAL_AWAITED: + return 2 + oparg; case CALL_STR_1: return 3; case CALL_TUPLE_1: @@ -221,7 +233,7 @@ int _PyOpcode_num_popped(int opcode, int oparg) { case GET_ANEXT: return 1; case GET_AWAITABLE: - return 1; + return 1 + ((oparg >> 2) & 1); case GET_ITER: return 1; case GET_ITER_SELF: @@ -593,8 +605,12 @@ int _PyOpcode_num_pushed(int opcode, int oparg) { return 0; case CALL_BOUND_METHOD_EXACT_ARGS: return 0; + case CALL_BOUND_METHOD_EXACT_ARGS_AWAITED: + return 0; case CALL_BOUND_METHOD_GENERAL: return 0; + case CALL_BOUND_METHOD_GENERAL_AWAITED: + return 0; case CALL_BUILTIN_CLASS: return 1; case CALL_BUILTIN_FAST: @@ -619,10 +635,14 @@ int _PyOpcode_num_pushed(int opcode, int oparg) { return 1; case CALL_KW_BOUND_METHOD: return 0; + case CALL_KW_BOUND_METHOD_AWAITED: + return 0; case CALL_KW_NON_PY: return 1; case CALL_KW_PY: return 0; + case CALL_KW_PY_AWAITED: + return 0; case CALL_LEN: return 1; case CALL_LIST_APPEND: @@ -639,8 +659,12 @@ int _PyOpcode_num_pushed(int opcode, int oparg) { return 1; case CALL_PY_EXACT_ARGS: return 0; + case CALL_PY_EXACT_ARGS_AWAITED: + return 0; case CALL_PY_GENERAL: return 0; + case CALL_PY_GENERAL_AWAITED: + return 0; case CALL_STR_1: return 1; case CALL_TUPLE_1: @@ -1130,7 +1154,9 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = { [CALL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG }, [CALL_ALLOC_AND_ENTER_INIT] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_BOUND_METHOD_EXACT_ARGS] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_BOUND_METHOD_GENERAL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_BUILTIN_CLASS] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_BUILTIN_FAST] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_BUILTIN_FAST_WITH_KEYWORDS] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_RECORDS_VALUE_FLAG }, @@ -1143,8 +1169,10 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = { [CALL_ISINSTANCE] = { true, INSTR_FMT_IXC00, HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG }, [CALL_KW] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG }, [CALL_KW_BOUND_METHOD] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, + [CALL_KW_BOUND_METHOD_AWAITED] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_KW_NON_PY] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG }, [CALL_KW_PY] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, + [CALL_KW_PY_AWAITED] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_LEN] = { true, INSTR_FMT_IXC00, HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG }, [CALL_LIST_APPEND] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG }, [CALL_METHOD_DESCRIPTOR_FAST] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG }, @@ -1153,7 +1181,9 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = { [CALL_METHOD_DESCRIPTOR_O] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_NON_PY_GENERAL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_PY_EXACT_ARGS] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, + [CALL_PY_EXACT_ARGS_AWAITED] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_PY_GENERAL] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, + [CALL_PY_GENERAL_AWAITED] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_DEOPT_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG | HAS_RECORDS_VALUE_FLAG }, [CALL_STR_1] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG }, [CALL_TUPLE_1] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EVAL_BREAK_FLAG | HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG }, [CALL_TYPE_1] = { true, INSTR_FMT_IBC00, HAS_ARG_FLAG | HAS_EXIT_FLAG | HAS_ESCAPES_FLAG }, @@ -1345,7 +1375,7 @@ const struct opcode_metadata _PyOpcode_opcode_metadata[267] = { }; #endif -#define MAX_UOP_PER_EXPANSION 11 +#define MAX_UOP_PER_EXPANSION 12 struct opcode_macro_expansion { int nuops; struct { int16_t uop; int8_t size; int8_t offset; } uops[MAX_UOP_PER_EXPANSION]; @@ -1383,19 +1413,23 @@ _PyOpcode_macro_expansion[256] = { [BUILD_TUPLE] = { .nuops = 1, .uops = { { _BUILD_TUPLE, OPARG_SIMPLE, 0 } } }, [CALL_ALLOC_AND_ENTER_INIT] = { .nuops = 7, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_OBJECT, 2, 1 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _ALLOCATE_OBJECT, OPARG_SIMPLE, 3 }, { _CREATE_INIT_FRAME, OPARG_SIMPLE, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, [CALL_BOUND_METHOD_EXACT_ARGS] = { .nuops = 11, .uops = { { _RECORD_BOUND_METHOD, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_CALL_BOUND_METHOD_EXACT_ARGS, OPARG_SIMPLE, 1 }, { _INIT_CALL_BOUND_METHOD_EXACT_ARGS, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION, 2, 1 }, { _CHECK_FUNCTION_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _CHECK_STACK_SPACE, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _INIT_CALL_PY_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = { .nuops = 12, .uops = { { _RECORD_BOUND_METHOD, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_CALL_BOUND_METHOD_EXACT_ARGS, OPARG_SIMPLE, 1 }, { _INIT_CALL_BOUND_METHOD_EXACT_ARGS, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION, 2, 1 }, { _CHECK_FUNCTION_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _CHECK_STACK_SPACE, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _INIT_CALL_PY_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _START_LAZY_CORO, OPARG_REPLACED, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, [CALL_BOUND_METHOD_GENERAL] = { .nuops = 8, .uops = { { _RECORD_BOUND_METHOD, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_METHOD_VERSION, 2, 1 }, { _EXPAND_METHOD, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _PY_FRAME_GENERAL, OPARG_SIMPLE, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = { .nuops = 9, .uops = { { _RECORD_BOUND_METHOD, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_METHOD_VERSION, 2, 1 }, { _EXPAND_METHOD, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _PY_FRAME_GENERAL, OPARG_SIMPLE, 3 }, { _START_LAZY_CORO, OPARG_REPLACED, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, [CALL_BUILTIN_CLASS] = { .nuops = 6, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _GUARD_CALLABLE_BUILTIN_CLASS, OPARG_SIMPLE, 3 }, { _CALL_BUILTIN_CLASS, OPARG_SIMPLE, 3 }, { _POP_TOP_OPARG, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_BUILTIN_FAST] = { .nuops = 6, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _GUARD_CALLABLE_BUILTIN_FAST, OPARG_SIMPLE, 3 }, { _CALL_BUILTIN_FAST, OPARG_SIMPLE, 3 }, { _POP_TOP_OPARG, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_BUILTIN_FAST_WITH_KEYWORDS] = { .nuops = 6, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _GUARD_CALLABLE_BUILTIN_FAST_WITH_KEYWORDS, OPARG_SIMPLE, 3 }, { _CALL_BUILTIN_FAST_WITH_KEYWORDS, OPARG_SIMPLE, 3 }, { _POP_TOP_OPARG, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_BUILTIN_O] = { .nuops = 7, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _GUARD_CALLABLE_BUILTIN_O, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_LIMIT, OPARG_SIMPLE, 3 }, { _CALL_BUILTIN_O, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_EX_NON_PY_GENERAL] = { .nuops = 4, .uops = { { _CHECK_IS_NOT_PY_CALLABLE_EX, OPARG_SIMPLE, 1 }, { _MAKE_CALLARGS_A_TUPLE, OPARG_SIMPLE, 1 }, { _CALL_FUNCTION_EX_NON_PY_GENERAL, OPARG_SIMPLE, 1 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 1 } } }, - [CALL_EX_PY] = { .nuops = 7, .uops = { { _RECORD_4OS, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _MAKE_CALLARGS_A_TUPLE, OPARG_SIMPLE, 1 }, { _CHECK_IS_PY_CALLABLE_EX, OPARG_SIMPLE, 1 }, { _PY_FRAME_EX, OPARG_SIMPLE, 1 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 1 }, { _PUSH_FRAME, OPARG_SIMPLE, 1 } } }, + [CALL_EX_PY] = { .nuops = 8, .uops = { { _RECORD_4OS, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _MAKE_CALLARGS_A_TUPLE, OPARG_SIMPLE, 1 }, { _CHECK_IS_PY_CALLABLE_EX, OPARG_SIMPLE, 1 }, { _PY_FRAME_EX, OPARG_SIMPLE, 1 }, { _MAYBE_LAZY_CORO, OPARG_REPLACED, 1 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 1 }, { _PUSH_FRAME, OPARG_SIMPLE, 1 } } }, [CALL_INTRINSIC_1] = { .nuops = 2, .uops = { { _CALL_INTRINSIC_1, OPARG_SIMPLE, 0 }, { _POP_TOP, OPARG_SIMPLE, 0 } } }, [CALL_INTRINSIC_2] = { .nuops = 3, .uops = { { _CALL_INTRINSIC_2, OPARG_SIMPLE, 0 }, { _POP_TOP, OPARG_SIMPLE, 0 }, { _POP_TOP, OPARG_SIMPLE, 0 } } }, [CALL_ISINSTANCE] = { .nuops = 3, .uops = { { _GUARD_THIRD_NULL, OPARG_SIMPLE, 3 }, { _GUARD_CALLABLE_ISINSTANCE, OPARG_SIMPLE, 3 }, { _CALL_ISINSTANCE, OPARG_SIMPLE, 3 } } }, [CALL_KW_BOUND_METHOD] = { .nuops = 7, .uops = { { _RECORD_CALLABLE_KW, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_METHOD_VERSION_KW, 2, 1 }, { _EXPAND_METHOD_KW, OPARG_SIMPLE, 3 }, { _PY_FRAME_KW, OPARG_SIMPLE, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, + [CALL_KW_BOUND_METHOD_AWAITED] = { .nuops = 8, .uops = { { _RECORD_CALLABLE_KW, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_METHOD_VERSION_KW, 2, 1 }, { _EXPAND_METHOD_KW, OPARG_SIMPLE, 3 }, { _PY_FRAME_KW, OPARG_SIMPLE, 3 }, { _START_LAZY_CORO, OPARG_REPLACED, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, [CALL_KW_NON_PY] = { .nuops = 3, .uops = { { _CHECK_IS_NOT_PY_CALLABLE_KW, OPARG_SIMPLE, 3 }, { _CALL_KW_NON_PY, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_KW_PY] = { .nuops = 7, .uops = { { _RECORD_CALLABLE_KW, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION_KW, 2, 1 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _PY_FRAME_KW, OPARG_SIMPLE, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, + [CALL_KW_PY_AWAITED] = { .nuops = 8, .uops = { { _RECORD_CALLABLE_KW, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION_KW, 2, 1 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _PY_FRAME_KW, OPARG_SIMPLE, 3 }, { _START_LAZY_CORO, OPARG_REPLACED, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, [CALL_LEN] = { .nuops = 5, .uops = { { _GUARD_NOS_NULL, OPARG_SIMPLE, 3 }, { _GUARD_CALLABLE_LEN, OPARG_SIMPLE, 3 }, { _CALL_LEN, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 } } }, [CALL_LIST_APPEND] = { .nuops = 6, .uops = { { _GUARD_CALLABLE_LIST_APPEND, OPARG_SIMPLE, 3 }, { _GUARD_NOS_NOT_NULL, OPARG_SIMPLE, 3 }, { _GUARD_NOS_LIST, OPARG_SIMPLE, 3 }, { _CALL_LIST_APPEND, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 } } }, [CALL_METHOD_DESCRIPTOR_FAST] = { .nuops = 5, .uops = { { _GUARD_CALLABLE_METHOD_DESCRIPTOR_FAST, OPARG_SIMPLE, 3 }, { _CALL_METHOD_DESCRIPTOR_FAST, OPARG_SIMPLE, 3 }, { _POP_TOP_OPARG, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, @@ -1404,7 +1438,9 @@ _PyOpcode_macro_expansion[256] = { [CALL_METHOD_DESCRIPTOR_O] = { .nuops = 8, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _GUARD_CALLABLE_METHOD_DESCRIPTOR_O, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_LIMIT, OPARG_SIMPLE, 3 }, { _CALL_METHOD_DESCRIPTOR_O, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_NON_PY_GENERAL] = { .nuops = 4, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _CHECK_IS_NOT_PY_CALLABLE, OPARG_SIMPLE, 3 }, { _CALL_NON_PY_GENERAL, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_PY_EXACT_ARGS] = { .nuops = 9, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION, 2, 1 }, { _CHECK_FUNCTION_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _CHECK_STACK_SPACE, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _INIT_CALL_PY_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, + [CALL_PY_EXACT_ARGS_AWAITED] = { .nuops = 10, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION, 2, 1 }, { _CHECK_FUNCTION_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _CHECK_STACK_SPACE, OPARG_SIMPLE, 3 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _INIT_CALL_PY_EXACT_ARGS, OPARG_SIMPLE, 3 }, { _START_LAZY_CORO, OPARG_REPLACED, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, [CALL_PY_GENERAL] = { .nuops = 7, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION, 2, 1 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _PY_FRAME_GENERAL, OPARG_SIMPLE, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, + [CALL_PY_GENERAL_AWAITED] = { .nuops = 8, .uops = { { _RECORD_CALLABLE, OPARG_SIMPLE, 0 }, { _CHECK_PEP_523, OPARG_SIMPLE, 1 }, { _CHECK_FUNCTION_VERSION, 2, 1 }, { _CHECK_RECURSION_REMAINING, OPARG_SIMPLE, 3 }, { _PY_FRAME_GENERAL, OPARG_SIMPLE, 3 }, { _START_LAZY_CORO, OPARG_REPLACED, 3 }, { _SAVE_RETURN_OFFSET, OPARG_SAVE_RETURN_OFFSET, 3 }, { _PUSH_FRAME, OPARG_SIMPLE, 3 } } }, [CALL_STR_1] = { .nuops = 5, .uops = { { _GUARD_NOS_NULL, OPARG_SIMPLE, 3 }, { _GUARD_CALLABLE_STR_1, OPARG_SIMPLE, 3 }, { _CALL_STR_1, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_TUPLE_1] = { .nuops = 5, .uops = { { _GUARD_NOS_NULL, OPARG_SIMPLE, 3 }, { _GUARD_CALLABLE_TUPLE_1, OPARG_SIMPLE, 3 }, { _CALL_TUPLE_1, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 }, { _CHECK_PERIODIC_AT_END, OPARG_REPLACED, 3 } } }, [CALL_TYPE_1] = { .nuops = 4, .uops = { { _GUARD_NOS_NULL, OPARG_SIMPLE, 3 }, { _GUARD_CALLABLE_TYPE_1, OPARG_SIMPLE, 3 }, { _CALL_TYPE_1, OPARG_SIMPLE, 3 }, { _POP_TOP, OPARG_SIMPLE, 3 } } }, @@ -1438,7 +1474,7 @@ _PyOpcode_macro_expansion[256] = { [FOR_ITER_VIRTUAL] = { .nuops = 2, .uops = { { _GUARD_TOS_NOT_NULL, OPARG_SIMPLE, 1 }, { _FOR_ITER_VIRTUAL, OPARG_REPLACED, 1 } } }, [GET_AITER] = { .nuops = 1, .uops = { { _GET_AITER, OPARG_SIMPLE, 0 } } }, [GET_ANEXT] = { .nuops = 1, .uops = { { _GET_ANEXT, OPARG_SIMPLE, 0 } } }, - [GET_AWAITABLE] = { .nuops = 1, .uops = { { _GET_AWAITABLE, OPARG_SIMPLE, 0 } } }, + [GET_AWAITABLE] = { .nuops = 3, .uops = { { _LAZY_CALL_OUTCOME, OPARG_REPLACED, 0 }, { _POP_LAZY_OUTCOME, OPARG_SIMPLE, 0 }, { _GET_AWAITABLE, OPARG_SIMPLE, 0 } } }, [GET_ITER] = { .nuops = 2, .uops = { { _RECORD_TOS_TYPE, OPARG_SIMPLE, 0 }, { _GET_ITER, OPARG_SIMPLE, 0 } } }, [GET_ITER_SELF] = { .nuops = 3, .uops = { { _RECORD_TOS_TYPE, OPARG_SIMPLE, 0 }, { _GUARD_ITERATOR, OPARG_SIMPLE, 1 }, { _PUSH_NULL, OPARG_SIMPLE, 1 } } }, [GET_ITER_VIRTUAL] = { .nuops = 3, .uops = { { _RECORD_TOS_TYPE, OPARG_SIMPLE, 0 }, { _GUARD_ITER_VIRTUAL, OPARG_SIMPLE, 1 }, { _PUSH_TAGGED_ZERO, OPARG_SIMPLE, 1 } } }, @@ -1545,7 +1581,7 @@ _PyOpcode_macro_expansion[256] = { [UNPACK_SEQUENCE_TUPLE] = { .nuops = 2, .uops = { { _GUARD_TOS_TUPLE, OPARG_SIMPLE, 0 }, { _UNPACK_SEQUENCE_TUPLE, OPARG_SIMPLE, 1 } } }, [UNPACK_SEQUENCE_TWO_TUPLE] = { .nuops = 2, .uops = { { _GUARD_TOS_TUPLE, OPARG_SIMPLE, 0 }, { _UNPACK_SEQUENCE_TWO_TUPLE, OPARG_SIMPLE, 1 } } }, [WITH_EXCEPT_START] = { .nuops = 1, .uops = { { _WITH_EXCEPT_START, OPARG_SIMPLE, 0 } } }, - [YIELD_VALUE] = { .nuops = 2, .uops = { { _MAKE_HEAP_SAFE, OPARG_SIMPLE, 0 }, { _YIELD_VALUE, OPARG_SIMPLE, 0 } } }, + [YIELD_VALUE] = { .nuops = 3, .uops = { { _CHECK_LAZY_CORO, OPARG_REPLACED, 0 }, { _MAKE_HEAP_SAFE, OPARG_SIMPLE, 0 }, { _YIELD_VALUE, OPARG_SIMPLE, 0 } } }, }; #endif // NEED_OPCODE_METADATA @@ -1583,7 +1619,9 @@ const char *_PyOpcode_OpName[267] = { [CALL] = "CALL", [CALL_ALLOC_AND_ENTER_INIT] = "CALL_ALLOC_AND_ENTER_INIT", [CALL_BOUND_METHOD_EXACT_ARGS] = "CALL_BOUND_METHOD_EXACT_ARGS", + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = "CALL_BOUND_METHOD_EXACT_ARGS_AWAITED", [CALL_BOUND_METHOD_GENERAL] = "CALL_BOUND_METHOD_GENERAL", + [CALL_BOUND_METHOD_GENERAL_AWAITED] = "CALL_BOUND_METHOD_GENERAL_AWAITED", [CALL_BUILTIN_CLASS] = "CALL_BUILTIN_CLASS", [CALL_BUILTIN_FAST] = "CALL_BUILTIN_FAST", [CALL_BUILTIN_FAST_WITH_KEYWORDS] = "CALL_BUILTIN_FAST_WITH_KEYWORDS", @@ -1596,8 +1634,10 @@ const char *_PyOpcode_OpName[267] = { [CALL_ISINSTANCE] = "CALL_ISINSTANCE", [CALL_KW] = "CALL_KW", [CALL_KW_BOUND_METHOD] = "CALL_KW_BOUND_METHOD", + [CALL_KW_BOUND_METHOD_AWAITED] = "CALL_KW_BOUND_METHOD_AWAITED", [CALL_KW_NON_PY] = "CALL_KW_NON_PY", [CALL_KW_PY] = "CALL_KW_PY", + [CALL_KW_PY_AWAITED] = "CALL_KW_PY_AWAITED", [CALL_LEN] = "CALL_LEN", [CALL_LIST_APPEND] = "CALL_LIST_APPEND", [CALL_METHOD_DESCRIPTOR_FAST] = "CALL_METHOD_DESCRIPTOR_FAST", @@ -1606,7 +1646,9 @@ const char *_PyOpcode_OpName[267] = { [CALL_METHOD_DESCRIPTOR_O] = "CALL_METHOD_DESCRIPTOR_O", [CALL_NON_PY_GENERAL] = "CALL_NON_PY_GENERAL", [CALL_PY_EXACT_ARGS] = "CALL_PY_EXACT_ARGS", + [CALL_PY_EXACT_ARGS_AWAITED] = "CALL_PY_EXACT_ARGS_AWAITED", [CALL_PY_GENERAL] = "CALL_PY_GENERAL", + [CALL_PY_GENERAL_AWAITED] = "CALL_PY_GENERAL_AWAITED", [CALL_STR_1] = "CALL_STR_1", [CALL_TUPLE_1] = "CALL_TUPLE_1", [CALL_TYPE_1] = "CALL_TYPE_1", @@ -1839,12 +1881,6 @@ const uint8_t _PyOpcode_Deopt[256] = { [125] = 125, [126] = 126, [127] = 127, - [219] = 219, - [220] = 220, - [221] = 221, - [222] = 222, - [223] = 223, - [224] = 224, [225] = 225, [226] = 226, [227] = 227, @@ -1883,7 +1919,9 @@ const uint8_t _PyOpcode_Deopt[256] = { [CALL] = CALL, [CALL_ALLOC_AND_ENTER_INIT] = CALL, [CALL_BOUND_METHOD_EXACT_ARGS] = CALL, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = CALL, [CALL_BOUND_METHOD_GENERAL] = CALL, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = CALL, [CALL_BUILTIN_CLASS] = CALL, [CALL_BUILTIN_FAST] = CALL, [CALL_BUILTIN_FAST_WITH_KEYWORDS] = CALL, @@ -1896,8 +1934,10 @@ const uint8_t _PyOpcode_Deopt[256] = { [CALL_ISINSTANCE] = CALL, [CALL_KW] = CALL_KW, [CALL_KW_BOUND_METHOD] = CALL_KW, + [CALL_KW_BOUND_METHOD_AWAITED] = CALL_KW, [CALL_KW_NON_PY] = CALL_KW, [CALL_KW_PY] = CALL_KW, + [CALL_KW_PY_AWAITED] = CALL_KW, [CALL_LEN] = CALL, [CALL_LIST_APPEND] = CALL, [CALL_METHOD_DESCRIPTOR_FAST] = CALL, @@ -1906,7 +1946,9 @@ const uint8_t _PyOpcode_Deopt[256] = { [CALL_METHOD_DESCRIPTOR_O] = CALL, [CALL_NON_PY_GENERAL] = CALL, [CALL_PY_EXACT_ARGS] = CALL, + [CALL_PY_EXACT_ARGS_AWAITED] = CALL, [CALL_PY_GENERAL] = CALL, + [CALL_PY_GENERAL_AWAITED] = CALL, [CALL_STR_1] = CALL, [CALL_TUPLE_1] = CALL, [CALL_TYPE_1] = CALL, @@ -2100,12 +2142,6 @@ const uint8_t _PyOpcode_Deopt[256] = { case 125: \ case 126: \ case 127: \ - case 219: \ - case 220: \ - case 221: \ - case 222: \ - case 223: \ - case 224: \ case 225: \ case 226: \ case 227: \ diff --git a/Include/internal/pycore_opcode_utils.h b/Include/internal/pycore_opcode_utils.h index 7067b48ec22cb3..d70c6eeab8eeda 100644 --- a/Include/internal/pycore_opcode_utils.h +++ b/Include/internal/pycore_opcode_utils.h @@ -98,6 +98,10 @@ extern "C" { #define GET_ITER_YIELD_FROM_NO_CHECK 2 #define GET_ITER_YIELD_FROM_CORO_CHECK 3 +/* Values used in the oparg for GET_AWAITABLE */ +#define GET_AWAITABLE_WHERE_MASK 0x3 +#define GET_AWAITABLE_AWAITED_CALL 0x4 + #ifdef __cplusplus } #endif diff --git a/Include/internal/pycore_uop_ids.h b/Include/internal/pycore_uop_ids.h index 31a8e60259f4ba..9bc947b1cd0dc8 100644 --- a/Include/internal/pycore_uop_ids.h +++ b/Include/internal/pycore_uop_ids.h @@ -82,6 +82,7 @@ enum { _CHECK_IS_NOT_PY_CALLABLE_EX, _CHECK_IS_NOT_PY_CALLABLE_KW, _CHECK_IS_PY_CALLABLE_EX, + _CHECK_LAZY_CORO, _CHECK_MANAGED_OBJECT_HAS_VALUES, _CHECK_METHOD_VERSION, _CHECK_METHOD_VERSION_KW, @@ -125,6 +126,7 @@ enum { _FOR_ITER_TIER_TWO, _FOR_ITER_VIRTUAL, _FOR_ITER_VIRTUAL_TIER_TWO, + _GET_AWAITABLE, _GET_ITER, _GET_ITER_TRAD, _GUARD_3OS_ASYNC_GEN_ASEND, @@ -173,6 +175,7 @@ enum { _GUARD_IS_TRUE_POP, _GUARD_ITERATOR, _GUARD_ITER_VIRTUAL, + _GUARD_LAZY_OUTCOME_NULL, _GUARD_LOAD_SUPER_ATTR_METHOD, _GUARD_NOS_COMPACT_ASCII, _GUARD_NOS_DICT_STORE_SUBSCRIPT, @@ -191,6 +194,7 @@ enum { _GUARD_NOT_EXHAUSTED_LIST, _GUARD_NOT_EXHAUSTED_RANGE, _GUARD_NOT_EXHAUSTED_TUPLE, + _GUARD_NOT_LAZY_CORO, _GUARD_THIRD_NULL, _GUARD_TOS_ANY_DICT, _GUARD_TOS_ANY_SET, @@ -234,6 +238,7 @@ enum { _ITER_NEXT_RANGE, _ITER_NEXT_TUPLE, _JUMP_TO_TOP, + _LAZY_CALL_OUTCOME, _LIST_EXTEND, _LOAD_ATTR, _LOAD_ATTR_CLASS, @@ -287,12 +292,14 @@ enum { _MATCH_CLASS, _MAYBE_EXPAND_METHOD, _MAYBE_EXPAND_METHOD_KW, + _MAYBE_LAZY_CORO, _MONITOR_CALL, _MONITOR_CALL_KW, _MONITOR_JUMP_BACKWARD, _MONITOR_RESUME, _POP_JUMP_IF_FALSE, _POP_JUMP_IF_TRUE, + _POP_LAZY_OUTCOME, _POP_TOP_FLOAT, _POP_TOP_INT, _POP_TOP_NOP, @@ -328,6 +335,7 @@ enum { _SET_UPDATE, _SPILL_OR_RELOAD, _START_EXECUTOR, + _START_LAZY_CORO, _STORE_ATTR, _STORE_ATTR_INSTANCE_VALUE, _STORE_ATTR_SLOT, @@ -366,7 +374,7 @@ enum { _UNPACK_SEQUENCE_UNIQUE_TWO_TUPLE, _YIELD_VALUE, }; -#define MAX_UOP_ID 654 +#define MAX_UOP_ID 662 #define _BUILD_INTERPOLATION BUILD_INTERPOLATION #define _BUILD_LIST BUILD_LIST @@ -390,7 +398,6 @@ enum { #define _FORMAT_WITH_SPEC FORMAT_WITH_SPEC #define _GET_AITER GET_AITER #define _GET_ANEXT GET_ANEXT -#define _GET_AWAITABLE GET_AWAITABLE #define _GET_LEN GET_LEN #define _IMPORT_FROM IMPORT_FROM #define _IMPORT_NAME IMPORT_NAME @@ -590,6 +597,10 @@ enum { _CHECK_IS_PY_CALLABLE_EX_r13, _CHECK_IS_PY_CALLABLE_EX_r23, _CHECK_IS_PY_CALLABLE_EX_r33, + _CHECK_LAZY_CORO_r00, + _CHECK_LAZY_CORO_r11, + _CHECK_LAZY_CORO_r22, + _CHECK_LAZY_CORO_r33, _CHECK_MANAGED_OBJECT_HAS_VALUES_r01, _CHECK_MANAGED_OBJECT_HAS_VALUES_r11, _CHECK_MANAGED_OBJECT_HAS_VALUES_r22, @@ -848,6 +859,7 @@ enum { _GUARD_ITER_VIRTUAL_r11, _GUARD_ITER_VIRTUAL_r22, _GUARD_ITER_VIRTUAL_r33, + _GUARD_LAZY_OUTCOME_NULL_r11, _GUARD_LOAD_SUPER_ATTR_METHOD_r03, _GUARD_LOAD_SUPER_ATTR_METHOD_r13, _GUARD_LOAD_SUPER_ATTR_METHOD_r23, @@ -920,6 +932,10 @@ enum { _GUARD_NOT_EXHAUSTED_TUPLE_r12, _GUARD_NOT_EXHAUSTED_TUPLE_r22, _GUARD_NOT_EXHAUSTED_TUPLE_r33, + _GUARD_NOT_LAZY_CORO_r00, + _GUARD_NOT_LAZY_CORO_r11, + _GUARD_NOT_LAZY_CORO_r22, + _GUARD_NOT_LAZY_CORO_r33, _GUARD_THIRD_NULL_r03, _GUARD_THIRD_NULL_r13, _GUARD_THIRD_NULL_r23, @@ -1077,6 +1093,7 @@ enum { _JUMP_BACKWARD_NO_INTERRUPT_r22, _JUMP_BACKWARD_NO_INTERRUPT_r33, _JUMP_TO_TOP_r00, + _LAZY_CALL_OUTCOME_r11, _LIST_APPEND_r10, _LIST_EXTEND_r11, _LOAD_ATTR_r10, @@ -1237,6 +1254,10 @@ enum { _MATCH_SEQUENCE_r23, _MAYBE_EXPAND_METHOD_r00, _MAYBE_EXPAND_METHOD_KW_r11, + _MAYBE_LAZY_CORO_r01, + _MAYBE_LAZY_CORO_r11, + _MAYBE_LAZY_CORO_r22, + _MAYBE_LAZY_CORO_r33, _MONITOR_CALL_r00, _MONITOR_CALL_KW_r11, _MONITOR_JUMP_BACKWARD_r00, @@ -1258,6 +1279,7 @@ enum { _POP_JUMP_IF_TRUE_r10, _POP_JUMP_IF_TRUE_r21, _POP_JUMP_IF_TRUE_r32, + _POP_LAZY_OUTCOME_r11, _POP_TOP_r10, _POP_TOP_FLOAT_r00, _POP_TOP_FLOAT_r10, @@ -1339,6 +1361,10 @@ enum { _SPILL_OR_RELOAD_r31, _SPILL_OR_RELOAD_r32, _START_EXECUTOR_r00, + _START_LAZY_CORO_r01, + _START_LAZY_CORO_r11, + _START_LAZY_CORO_r22, + _START_LAZY_CORO_r33, _STORE_ATTR_r20, _STORE_ATTR_INSTANCE_VALUE_r21, _STORE_ATTR_SLOT_r21, @@ -1444,7 +1470,7 @@ enum { _WITH_EXCEPT_START_r33, _YIELD_VALUE_r11, }; -#define MAX_UOP_REGS_ID 1655 +#define MAX_UOP_REGS_ID 1682 #ifdef __cplusplus } diff --git a/Include/internal/pycore_uop_metadata.h b/Include/internal/pycore_uop_metadata.h index a264ad3f7848b7..b41e49fb03d2b8 100644 --- a/Include/internal/pycore_uop_metadata.h +++ b/Include/internal/pycore_uop_metadata.h @@ -168,12 +168,15 @@ const uint32_t _PyUop_Flags[MAX_UOP_ID+1] = { [_GET_AITER] = HAS_ERROR_FLAG | HAS_ESCAPES_FLAG, [_GET_ANEXT] = HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG, [_GET_AWAITABLE] = HAS_ARG_FLAG | HAS_ERROR_FLAG | HAS_ESCAPES_FLAG, + [_GUARD_LAZY_OUTCOME_NULL] = HAS_ARG_FLAG | HAS_EXIT_FLAG, + [_POP_LAZY_OUTCOME] = HAS_ARG_FLAG, [_SEND_GEN_FRAME] = HAS_ARG_FLAG | HAS_EXIT_FLAG, [_GUARD_TOS_IS_NONE] = HAS_EXIT_FLAG, [_GUARD_NOS_NOT_NULL] = HAS_EXIT_FLAG, [_SEND_VIRTUAL_TIER_TWO] = HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG, [_GUARD_3OS_ASYNC_GEN_ASEND] = HAS_EXIT_FLAG, [_SEND_ASYNC_GEN_TIER_TWO] = HAS_EXIT_FLAG | HAS_ERROR_FLAG | HAS_ERROR_NO_POP_FLAG | HAS_ESCAPES_FLAG, + [_GUARD_NOT_LAZY_CORO] = HAS_EXIT_FLAG, [_YIELD_VALUE] = HAS_ARG_FLAG | HAS_ESCAPES_FLAG | HAS_SYNC_SP_FLAG | HAS_NEEDS_GUARD_IP_FLAG, [_POP_EXCEPT] = HAS_ESCAPES_FLAG, [_LOAD_COMMON_CONSTANT] = HAS_ARG_FLAG, @@ -1644,6 +1647,24 @@ const _PyUopCachingInfo _PyUop_Caching[MAX_UOP_ID+1] = { { -1, -1, -1 }, }, }, + [_GUARD_LAZY_OUTCOME_NULL] = { + .best = { 1, 1, 1, 1 }, + .entries = { + { -1, -1, -1 }, + { 1, 1, _GUARD_LAZY_OUTCOME_NULL_r11 }, + { -1, -1, -1 }, + { -1, -1, -1 }, + }, + }, + [_POP_LAZY_OUTCOME] = { + .best = { 1, 1, 1, 1 }, + .entries = { + { -1, -1, -1 }, + { 1, 1, _POP_LAZY_OUTCOME_r11 }, + { -1, -1, -1 }, + { -1, -1, -1 }, + }, + }, [_SEND_GEN_FRAME] = { .best = { 3, 3, 3, 3 }, .entries = { @@ -1698,6 +1719,15 @@ const _PyUopCachingInfo _PyUop_Caching[MAX_UOP_ID+1] = { { 3, 3, _SEND_ASYNC_GEN_TIER_TWO_r33 }, }, }, + [_GUARD_NOT_LAZY_CORO] = { + .best = { 0, 1, 2, 3 }, + .entries = { + { 0, 0, _GUARD_NOT_LAZY_CORO_r00 }, + { 1, 1, _GUARD_NOT_LAZY_CORO_r11 }, + { 2, 2, _GUARD_NOT_LAZY_CORO_r22 }, + { 3, 3, _GUARD_NOT_LAZY_CORO_r33 }, + }, + }, [_YIELD_VALUE] = { .best = { 1, 1, 1, 1 }, .entries = { @@ -4285,6 +4315,8 @@ const uint16_t _PyUop_Uncached[MAX_UOP_REGS_ID+1] = { [_GET_AITER_r11] = _GET_AITER, [_GET_ANEXT_r13] = _GET_ANEXT, [_GET_AWAITABLE_r13] = _GET_AWAITABLE, + [_GUARD_LAZY_OUTCOME_NULL_r11] = _GUARD_LAZY_OUTCOME_NULL, + [_POP_LAZY_OUTCOME_r11] = _POP_LAZY_OUTCOME, [_SEND_GEN_FRAME_r33] = _SEND_GEN_FRAME, [_GUARD_TOS_IS_NONE_r01] = _GUARD_TOS_IS_NONE, [_GUARD_TOS_IS_NONE_r11] = _GUARD_TOS_IS_NONE, @@ -4303,6 +4335,10 @@ const uint16_t _PyUop_Uncached[MAX_UOP_REGS_ID+1] = { [_GUARD_3OS_ASYNC_GEN_ASEND_r23] = _GUARD_3OS_ASYNC_GEN_ASEND, [_GUARD_3OS_ASYNC_GEN_ASEND_r33] = _GUARD_3OS_ASYNC_GEN_ASEND, [_SEND_ASYNC_GEN_TIER_TWO_r33] = _SEND_ASYNC_GEN_TIER_TWO, + [_GUARD_NOT_LAZY_CORO_r00] = _GUARD_NOT_LAZY_CORO, + [_GUARD_NOT_LAZY_CORO_r11] = _GUARD_NOT_LAZY_CORO, + [_GUARD_NOT_LAZY_CORO_r22] = _GUARD_NOT_LAZY_CORO, + [_GUARD_NOT_LAZY_CORO_r33] = _GUARD_NOT_LAZY_CORO, [_YIELD_VALUE_r11] = _YIELD_VALUE, [_POP_EXCEPT_r10] = _POP_EXCEPT, [_LOAD_COMMON_CONSTANT_r01] = _LOAD_COMMON_CONSTANT, @@ -5445,6 +5481,8 @@ const char *const _PyOpcode_uop_name[MAX_UOP_REGS_ID+1] = { [_GUARD_ITER_VIRTUAL_r11] = "_GUARD_ITER_VIRTUAL_r11", [_GUARD_ITER_VIRTUAL_r22] = "_GUARD_ITER_VIRTUAL_r22", [_GUARD_ITER_VIRTUAL_r33] = "_GUARD_ITER_VIRTUAL_r33", + [_GUARD_LAZY_OUTCOME_NULL] = "_GUARD_LAZY_OUTCOME_NULL", + [_GUARD_LAZY_OUTCOME_NULL_r11] = "_GUARD_LAZY_OUTCOME_NULL_r11", [_GUARD_LOAD_SUPER_ATTR_METHOD] = "_GUARD_LOAD_SUPER_ATTR_METHOD", [_GUARD_LOAD_SUPER_ATTR_METHOD_r03] = "_GUARD_LOAD_SUPER_ATTR_METHOD_r03", [_GUARD_LOAD_SUPER_ATTR_METHOD_r13] = "_GUARD_LOAD_SUPER_ATTR_METHOD_r13", @@ -5535,6 +5573,11 @@ const char *const _PyOpcode_uop_name[MAX_UOP_REGS_ID+1] = { [_GUARD_NOT_EXHAUSTED_TUPLE_r12] = "_GUARD_NOT_EXHAUSTED_TUPLE_r12", [_GUARD_NOT_EXHAUSTED_TUPLE_r22] = "_GUARD_NOT_EXHAUSTED_TUPLE_r22", [_GUARD_NOT_EXHAUSTED_TUPLE_r33] = "_GUARD_NOT_EXHAUSTED_TUPLE_r33", + [_GUARD_NOT_LAZY_CORO] = "_GUARD_NOT_LAZY_CORO", + [_GUARD_NOT_LAZY_CORO_r00] = "_GUARD_NOT_LAZY_CORO_r00", + [_GUARD_NOT_LAZY_CORO_r11] = "_GUARD_NOT_LAZY_CORO_r11", + [_GUARD_NOT_LAZY_CORO_r22] = "_GUARD_NOT_LAZY_CORO_r22", + [_GUARD_NOT_LAZY_CORO_r33] = "_GUARD_NOT_LAZY_CORO_r33", [_GUARD_THIRD_NULL] = "_GUARD_THIRD_NULL", [_GUARD_THIRD_NULL_r03] = "_GUARD_THIRD_NULL_r03", [_GUARD_THIRD_NULL_r13] = "_GUARD_THIRD_NULL_r13", @@ -5928,6 +5971,8 @@ const char *const _PyOpcode_uop_name[MAX_UOP_REGS_ID+1] = { [_POP_EXCEPT_r10] = "_POP_EXCEPT_r10", [_POP_ITER] = "_POP_ITER", [_POP_ITER_r20] = "_POP_ITER_r20", + [_POP_LAZY_OUTCOME] = "_POP_LAZY_OUTCOME", + [_POP_LAZY_OUTCOME_r11] = "_POP_LAZY_OUTCOME_r11", [_POP_TOP] = "_POP_TOP", [_POP_TOP_r10] = "_POP_TOP_r10", [_POP_TOP_FLOAT] = "_POP_TOP_FLOAT", @@ -6464,6 +6509,10 @@ int _PyUop_num_popped(int opcode, int oparg) return 0; case _GET_AWAITABLE: return 1; + case _GUARD_LAZY_OUTCOME_NULL: + return 0; + case _POP_LAZY_OUTCOME: + return 1 + ((oparg >> 2) & 1); case _SEND_GEN_FRAME: return 1; case _GUARD_TOS_IS_NONE: @@ -6476,6 +6525,8 @@ int _PyUop_num_popped(int opcode, int oparg) return 0; case _SEND_ASYNC_GEN_TIER_TWO: return 3; + case _GUARD_NOT_LAZY_CORO: + return 0; case _YIELD_VALUE: return 1; case _POP_EXCEPT: diff --git a/Include/opcode_ids.h b/Include/opcode_ids.h index 11342ae451b9f6..c0d307f78dec28 100644 --- a/Include/opcode_ids.h +++ b/Include/opcode_ids.h @@ -145,79 +145,85 @@ extern "C" { #define BINARY_OP_SUBTRACT_INT 143 #define CALL_ALLOC_AND_ENTER_INIT 144 #define CALL_BOUND_METHOD_EXACT_ARGS 145 -#define CALL_BOUND_METHOD_GENERAL 146 -#define CALL_BUILTIN_CLASS 147 -#define CALL_BUILTIN_FAST 148 -#define CALL_BUILTIN_FAST_WITH_KEYWORDS 149 -#define CALL_BUILTIN_O 150 -#define CALL_EX_NON_PY_GENERAL 151 -#define CALL_EX_PY 152 -#define CALL_ISINSTANCE 153 -#define CALL_KW_BOUND_METHOD 154 -#define CALL_KW_NON_PY 155 -#define CALL_KW_PY 156 -#define CALL_LEN 157 -#define CALL_LIST_APPEND 158 -#define CALL_METHOD_DESCRIPTOR_FAST 159 -#define CALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS 160 -#define CALL_METHOD_DESCRIPTOR_NOARGS 161 -#define CALL_METHOD_DESCRIPTOR_O 162 -#define CALL_NON_PY_GENERAL 163 -#define CALL_PY_EXACT_ARGS 164 -#define CALL_PY_GENERAL 165 -#define CALL_STR_1 166 -#define CALL_TUPLE_1 167 -#define CALL_TYPE_1 168 -#define COMPARE_OP_FLOAT 169 -#define COMPARE_OP_INT 170 -#define COMPARE_OP_STR 171 -#define CONTAINS_OP_DICT 172 -#define CONTAINS_OP_SET 173 -#define FOR_ITER_GEN 174 -#define FOR_ITER_LIST 175 -#define FOR_ITER_RANGE 176 -#define FOR_ITER_TUPLE 177 -#define FOR_ITER_VIRTUAL 178 -#define GET_ITER_SELF 179 -#define GET_ITER_VIRTUAL 180 -#define JUMP_BACKWARD_JIT 181 -#define JUMP_BACKWARD_NO_JIT 182 -#define LOAD_ATTR_CLASS 183 -#define LOAD_ATTR_CLASS_WITH_METACLASS_CHECK 184 -#define LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN 185 -#define LOAD_ATTR_INSTANCE_VALUE 186 -#define LOAD_ATTR_METHOD_LAZY_DICT 187 -#define LOAD_ATTR_METHOD_NO_DICT 188 -#define LOAD_ATTR_METHOD_WITH_VALUES 189 -#define LOAD_ATTR_MODULE 190 -#define LOAD_ATTR_NONDESCRIPTOR_NO_DICT 191 -#define LOAD_ATTR_NONDESCRIPTOR_WITH_VALUES 192 -#define LOAD_ATTR_PROPERTY 193 -#define LOAD_ATTR_SLOT 194 -#define LOAD_ATTR_WITH_HINT 195 -#define LOAD_GLOBAL_BUILTIN 196 -#define LOAD_GLOBAL_MODULE 197 -#define LOAD_SUPER_ATTR_ATTR 198 -#define LOAD_SUPER_ATTR_METHOD 199 -#define RESUME_CHECK 200 -#define RESUME_CHECK_JIT 201 -#define SEND_ASYNC_GEN 202 -#define SEND_GEN 203 -#define SEND_VIRTUAL 204 -#define STORE_ATTR_INSTANCE_VALUE 205 -#define STORE_ATTR_SLOT 206 -#define STORE_ATTR_WITH_HINT 207 -#define STORE_SUBSCR_DICT 208 -#define STORE_SUBSCR_LIST_INT 209 -#define TO_BOOL_ALWAYS_TRUE 210 -#define TO_BOOL_BOOL 211 -#define TO_BOOL_INT 212 -#define TO_BOOL_LIST 213 -#define TO_BOOL_NONE 214 -#define TO_BOOL_STR 215 -#define UNPACK_SEQUENCE_LIST 216 -#define UNPACK_SEQUENCE_TUPLE 217 -#define UNPACK_SEQUENCE_TWO_TUPLE 218 +#define CALL_BOUND_METHOD_EXACT_ARGS_AWAITED 146 +#define CALL_BOUND_METHOD_GENERAL 147 +#define CALL_BOUND_METHOD_GENERAL_AWAITED 148 +#define CALL_BUILTIN_CLASS 149 +#define CALL_BUILTIN_FAST 150 +#define CALL_BUILTIN_FAST_WITH_KEYWORDS 151 +#define CALL_BUILTIN_O 152 +#define CALL_EX_NON_PY_GENERAL 153 +#define CALL_EX_PY 154 +#define CALL_ISINSTANCE 155 +#define CALL_KW_BOUND_METHOD 156 +#define CALL_KW_BOUND_METHOD_AWAITED 157 +#define CALL_KW_NON_PY 158 +#define CALL_KW_PY 159 +#define CALL_KW_PY_AWAITED 160 +#define CALL_LEN 161 +#define CALL_LIST_APPEND 162 +#define CALL_METHOD_DESCRIPTOR_FAST 163 +#define CALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS 164 +#define CALL_METHOD_DESCRIPTOR_NOARGS 165 +#define CALL_METHOD_DESCRIPTOR_O 166 +#define CALL_NON_PY_GENERAL 167 +#define CALL_PY_EXACT_ARGS 168 +#define CALL_PY_EXACT_ARGS_AWAITED 169 +#define CALL_PY_GENERAL 170 +#define CALL_PY_GENERAL_AWAITED 171 +#define CALL_STR_1 172 +#define CALL_TUPLE_1 173 +#define CALL_TYPE_1 174 +#define COMPARE_OP_FLOAT 175 +#define COMPARE_OP_INT 176 +#define COMPARE_OP_STR 177 +#define CONTAINS_OP_DICT 178 +#define CONTAINS_OP_SET 179 +#define FOR_ITER_GEN 180 +#define FOR_ITER_LIST 181 +#define FOR_ITER_RANGE 182 +#define FOR_ITER_TUPLE 183 +#define FOR_ITER_VIRTUAL 184 +#define GET_ITER_SELF 185 +#define GET_ITER_VIRTUAL 186 +#define JUMP_BACKWARD_JIT 187 +#define JUMP_BACKWARD_NO_JIT 188 +#define LOAD_ATTR_CLASS 189 +#define LOAD_ATTR_CLASS_WITH_METACLASS_CHECK 190 +#define LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN 191 +#define LOAD_ATTR_INSTANCE_VALUE 192 +#define LOAD_ATTR_METHOD_LAZY_DICT 193 +#define LOAD_ATTR_METHOD_NO_DICT 194 +#define LOAD_ATTR_METHOD_WITH_VALUES 195 +#define LOAD_ATTR_MODULE 196 +#define LOAD_ATTR_NONDESCRIPTOR_NO_DICT 197 +#define LOAD_ATTR_NONDESCRIPTOR_WITH_VALUES 198 +#define LOAD_ATTR_PROPERTY 199 +#define LOAD_ATTR_SLOT 200 +#define LOAD_ATTR_WITH_HINT 201 +#define LOAD_GLOBAL_BUILTIN 202 +#define LOAD_GLOBAL_MODULE 203 +#define LOAD_SUPER_ATTR_ATTR 204 +#define LOAD_SUPER_ATTR_METHOD 205 +#define RESUME_CHECK 206 +#define RESUME_CHECK_JIT 207 +#define SEND_ASYNC_GEN 208 +#define SEND_GEN 209 +#define SEND_VIRTUAL 210 +#define STORE_ATTR_INSTANCE_VALUE 211 +#define STORE_ATTR_SLOT 212 +#define STORE_ATTR_WITH_HINT 213 +#define STORE_SUBSCR_DICT 214 +#define STORE_SUBSCR_LIST_INT 215 +#define TO_BOOL_ALWAYS_TRUE 216 +#define TO_BOOL_BOOL 217 +#define TO_BOOL_INT 218 +#define TO_BOOL_LIST 219 +#define TO_BOOL_NONE 220 +#define TO_BOOL_STR 221 +#define UNPACK_SEQUENCE_LIST 222 +#define UNPACK_SEQUENCE_TUPLE 223 +#define UNPACK_SEQUENCE_TWO_TUPLE 224 #define INSTRUMENTED_END_FOR 233 #define INSTRUMENTED_POP_ITER 234 #define INSTRUMENTED_END_SEND 235 diff --git a/InternalDocs/generators.md b/InternalDocs/generators.md index fa652cd231cfa9..919043ea97de77 100644 --- a/InternalDocs/generators.md +++ b/InternalDocs/generators.md @@ -45,7 +45,45 @@ The generator's frame is initialized as a copy of the frame in which `RETURN_GENERATOR` is executing, but its `owner` field is overwritten to indicate that it is owned by a generator. Finally, `RETURN_GENERATOR` pushes the new generator object to the stack and returns to the caller of the generator function (at -which time its frame is destroyed). When the generator is next resumed by +which time its frame is destroyed). + +There is one exception: a coroutine function called by an awaited call +(`await f()` or the calls of `__aenter__` and `__aexit__` in `async with`: a +`CALL`, `CALL_KW` or `CALL_FUNCTION_EX` followed by `GET_AWAITABLE` with the +`GET_AWAITABLE_AWAITED_CALL` flag, see +`IS_AWAITED_CALL()`) sets `lazy_coro` to +`LAZY_CORO_REQUESTED` on its frame (see `MAYBE_START_LAZY_CORO()`). The +specializer gives such a call of a coroutine function an `*_AWAITED` form, +which does the same. `RETURN_GENERATOR` then pushes the body's own +`_PyErr_StackItem` on the data stack right after the frame, sets the frame's +`owner` to `FRAME_OWNED_BY_LAZY_CORO`, moves the caller to its `GET_AWAITABLE` (which has +the location of the `await`, like `SEND`) and keeps running the body in that +frame, so that a +body that returns or raises without suspending never creates a coroutine +object. A frame that unwinds before `RETURN_GENERATOR` (for example on +`RecursionError`) is cleared like any other. + +The compiler pushes an extra `NULL`, the `lazy_outcome`, below the callable of +an awaited call and follows the call with `GET_AWAITABLE` with the +`GET_AWAITABLE_AWAITED_CALL` flag set in its oparg. The `SEND` loop for the +await starts right after it. A lazily run body reports in `lazy_outcome` how it +ended: + +- It returned: `clear_thread_frame()` stores the tagged int + `LAZY_CORO_RETURNED`, and `GET_AWAITABLE` skips the `SEND` loop, jumping + past the `END_SEND` that the `SEND` right before `YIELD_VALUE` jumps to. +- It suspended: `YIELD_VALUE` leaves the frame and its `_PyErr_StackItem` on the + data stack and stores a pointer to the frame. `GET_AWAITABLE` creates the + coroutine object, moves the frame and the exception state into it (see + `_PyEval_MaterializeLazyCoro()`) and jumps to `YIELD_VALUE` with the + coroutine, `NULL` and the yielded value on the stack, as `SEND` would have + left them. +- It raised: the exception is raised from the caller's `GET_AWAITABLE`. + +Otherwise `lazy_outcome` stays `NULL`, and `GET_AWAITABLE` pops it and gets +the awaitable as usual. + +When the generator is next resumed by [`gen_send_ex2()`](../Objects/genobject.c), `_PyEval_EvalFrame()` is called to continue executing the generator function, in the frame that is embedded in the generator object. diff --git a/Lib/_opcode_metadata.py b/Lib/_opcode_metadata.py index df92eae151d248..d9c4eefe137e8f 100644 --- a/Lib/_opcode_metadata.py +++ b/Lib/_opcode_metadata.py @@ -120,11 +120,17 @@ "CALL_PY_GENERAL", "CALL_BOUND_METHOD_GENERAL", "CALL_NON_PY_GENERAL", + "CALL_PY_EXACT_ARGS_AWAITED", + "CALL_BOUND_METHOD_EXACT_ARGS_AWAITED", + "CALL_PY_GENERAL_AWAITED", + "CALL_BOUND_METHOD_GENERAL_AWAITED", ), CALL_KW=( "CALL_KW_BOUND_METHOD", "CALL_KW_PY", "CALL_KW_NON_PY", + "CALL_KW_PY_AWAITED", + "CALL_KW_BOUND_METHOD_AWAITED", ), CALL_FUNCTION_EX=( "CALL_EX_PY", @@ -151,79 +157,85 @@ BINARY_OP_SUBTRACT_INT=143, CALL_ALLOC_AND_ENTER_INIT=144, CALL_BOUND_METHOD_EXACT_ARGS=145, - CALL_BOUND_METHOD_GENERAL=146, - CALL_BUILTIN_CLASS=147, - CALL_BUILTIN_FAST=148, - CALL_BUILTIN_FAST_WITH_KEYWORDS=149, - CALL_BUILTIN_O=150, - CALL_EX_NON_PY_GENERAL=151, - CALL_EX_PY=152, - CALL_ISINSTANCE=153, - CALL_KW_BOUND_METHOD=154, - CALL_KW_NON_PY=155, - CALL_KW_PY=156, - CALL_LEN=157, - CALL_LIST_APPEND=158, - CALL_METHOD_DESCRIPTOR_FAST=159, - CALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS=160, - CALL_METHOD_DESCRIPTOR_NOARGS=161, - CALL_METHOD_DESCRIPTOR_O=162, - CALL_NON_PY_GENERAL=163, - CALL_PY_EXACT_ARGS=164, - CALL_PY_GENERAL=165, - CALL_STR_1=166, - CALL_TUPLE_1=167, - CALL_TYPE_1=168, - COMPARE_OP_FLOAT=169, - COMPARE_OP_INT=170, - COMPARE_OP_STR=171, - CONTAINS_OP_DICT=172, - CONTAINS_OP_SET=173, - FOR_ITER_GEN=174, - FOR_ITER_LIST=175, - FOR_ITER_RANGE=176, - FOR_ITER_TUPLE=177, - FOR_ITER_VIRTUAL=178, - GET_ITER_SELF=179, - GET_ITER_VIRTUAL=180, - JUMP_BACKWARD_JIT=181, - JUMP_BACKWARD_NO_JIT=182, - LOAD_ATTR_CLASS=183, - LOAD_ATTR_CLASS_WITH_METACLASS_CHECK=184, - LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN=185, - LOAD_ATTR_INSTANCE_VALUE=186, - LOAD_ATTR_METHOD_LAZY_DICT=187, - LOAD_ATTR_METHOD_NO_DICT=188, - LOAD_ATTR_METHOD_WITH_VALUES=189, - LOAD_ATTR_MODULE=190, - LOAD_ATTR_NONDESCRIPTOR_NO_DICT=191, - LOAD_ATTR_NONDESCRIPTOR_WITH_VALUES=192, - LOAD_ATTR_PROPERTY=193, - LOAD_ATTR_SLOT=194, - LOAD_ATTR_WITH_HINT=195, - LOAD_GLOBAL_BUILTIN=196, - LOAD_GLOBAL_MODULE=197, - LOAD_SUPER_ATTR_ATTR=198, - LOAD_SUPER_ATTR_METHOD=199, - RESUME_CHECK=200, - RESUME_CHECK_JIT=201, - SEND_ASYNC_GEN=202, - SEND_GEN=203, - SEND_VIRTUAL=204, - STORE_ATTR_INSTANCE_VALUE=205, - STORE_ATTR_SLOT=206, - STORE_ATTR_WITH_HINT=207, - STORE_SUBSCR_DICT=208, - STORE_SUBSCR_LIST_INT=209, - TO_BOOL_ALWAYS_TRUE=210, - TO_BOOL_BOOL=211, - TO_BOOL_INT=212, - TO_BOOL_LIST=213, - TO_BOOL_NONE=214, - TO_BOOL_STR=215, - UNPACK_SEQUENCE_LIST=216, - UNPACK_SEQUENCE_TUPLE=217, - UNPACK_SEQUENCE_TWO_TUPLE=218, + CALL_BOUND_METHOD_EXACT_ARGS_AWAITED=146, + CALL_BOUND_METHOD_GENERAL=147, + CALL_BOUND_METHOD_GENERAL_AWAITED=148, + CALL_BUILTIN_CLASS=149, + CALL_BUILTIN_FAST=150, + CALL_BUILTIN_FAST_WITH_KEYWORDS=151, + CALL_BUILTIN_O=152, + CALL_EX_NON_PY_GENERAL=153, + CALL_EX_PY=154, + CALL_ISINSTANCE=155, + CALL_KW_BOUND_METHOD=156, + CALL_KW_BOUND_METHOD_AWAITED=157, + CALL_KW_NON_PY=158, + CALL_KW_PY=159, + CALL_KW_PY_AWAITED=160, + CALL_LEN=161, + CALL_LIST_APPEND=162, + CALL_METHOD_DESCRIPTOR_FAST=163, + CALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS=164, + CALL_METHOD_DESCRIPTOR_NOARGS=165, + CALL_METHOD_DESCRIPTOR_O=166, + CALL_NON_PY_GENERAL=167, + CALL_PY_EXACT_ARGS=168, + CALL_PY_EXACT_ARGS_AWAITED=169, + CALL_PY_GENERAL=170, + CALL_PY_GENERAL_AWAITED=171, + CALL_STR_1=172, + CALL_TUPLE_1=173, + CALL_TYPE_1=174, + COMPARE_OP_FLOAT=175, + COMPARE_OP_INT=176, + COMPARE_OP_STR=177, + CONTAINS_OP_DICT=178, + CONTAINS_OP_SET=179, + FOR_ITER_GEN=180, + FOR_ITER_LIST=181, + FOR_ITER_RANGE=182, + FOR_ITER_TUPLE=183, + FOR_ITER_VIRTUAL=184, + GET_ITER_SELF=185, + GET_ITER_VIRTUAL=186, + JUMP_BACKWARD_JIT=187, + JUMP_BACKWARD_NO_JIT=188, + LOAD_ATTR_CLASS=189, + LOAD_ATTR_CLASS_WITH_METACLASS_CHECK=190, + LOAD_ATTR_GETATTRIBUTE_OVERRIDDEN=191, + LOAD_ATTR_INSTANCE_VALUE=192, + LOAD_ATTR_METHOD_LAZY_DICT=193, + LOAD_ATTR_METHOD_NO_DICT=194, + LOAD_ATTR_METHOD_WITH_VALUES=195, + LOAD_ATTR_MODULE=196, + LOAD_ATTR_NONDESCRIPTOR_NO_DICT=197, + LOAD_ATTR_NONDESCRIPTOR_WITH_VALUES=198, + LOAD_ATTR_PROPERTY=199, + LOAD_ATTR_SLOT=200, + LOAD_ATTR_WITH_HINT=201, + LOAD_GLOBAL_BUILTIN=202, + LOAD_GLOBAL_MODULE=203, + LOAD_SUPER_ATTR_ATTR=204, + LOAD_SUPER_ATTR_METHOD=205, + RESUME_CHECK=206, + RESUME_CHECK_JIT=207, + SEND_ASYNC_GEN=208, + SEND_GEN=209, + SEND_VIRTUAL=210, + STORE_ATTR_INSTANCE_VALUE=211, + STORE_ATTR_SLOT=212, + STORE_ATTR_WITH_HINT=213, + STORE_SUBSCR_DICT=214, + STORE_SUBSCR_LIST_INT=215, + TO_BOOL_ALWAYS_TRUE=216, + TO_BOOL_BOOL=217, + TO_BOOL_INT=218, + TO_BOOL_LIST=219, + TO_BOOL_NONE=220, + TO_BOOL_STR=221, + UNPACK_SEQUENCE_LIST=222, + UNPACK_SEQUENCE_TUPLE=223, + UNPACK_SEQUENCE_TWO_TUPLE=224, ) opmap = frozendict( diff --git a/Lib/asyncio/graph.py b/Lib/asyncio/graph.py index d76d2f6383343d..f18bb7611d85dd 100644 --- a/Lib/asyncio/graph.py +++ b/Lib/asyncio/graph.py @@ -1,6 +1,7 @@ """Introspection utils for tasks call graphs.""" import dataclasses +import inspect import io import operator import sys @@ -38,6 +39,24 @@ class FutureCallGraph: awaited_by: tuple["FutureCallGraph", ...] +# f_generator is None until a lazily started coroutine first suspends. +_CO_ASYNC_FLAGS = inspect.CO_COROUTINE | inspect.CO_ASYNC_GENERATOR +_CO_GEN_FLAGS = _CO_ASYNC_FLAGS | inspect.CO_GENERATOR +_FRAME_TAGS = { + inspect.CO_COROUTINE: 'async ', + inspect.CO_ASYNC_GENERATOR: 'async generator ', + inspect.CO_GENERATOR: 'generator ', +} + + +def _is_async_frame(f): + return bool(f.f_code.co_flags & _CO_ASYNC_FLAGS) + + +def _is_sync_frame(f): + return not (f.f_code.co_flags & _CO_GEN_FLAGS) + + def _build_graph_for_future( future: futures.Future, *, @@ -166,12 +185,10 @@ def capture_call_graph( try: while f is not None: # gh-156988: sync gen should not clear the call chain - is_async = isinstance( - f.f_generator, (types.CoroutineType, types.AsyncGeneratorType)) call_stack.append(FrameCallGraphEntry(f)) - if is_async: - if f.f_back is not None and f.f_back.f_generator is None: + if _is_async_frame(f): + if f.f_back is not None and _is_sync_frame(f.f_back): # We've reached the bottom of the coroutine stack, which # must be the Task that runs it. break @@ -228,36 +245,12 @@ def add_line(line: str) -> None: ) for ste in st.call_stack: f = ste.frame - - if f.f_generator is None: - f = ste.frame - add_line( - f' | File {f.f_code.co_filename!r},' - f' line {f.f_lineno}, in' - f' {f.f_code.co_qualname}()' - ) - else: - c = f.f_generator - - try: - f = c.cr_frame - code = c.cr_code - tag = 'async' - except AttributeError: - try: - f = c.ag_frame - code = c.ag_code - tag = 'async generator' - except AttributeError: - f = c.gi_frame - code = c.gi_code - tag = 'generator' - - add_line( - f' | File {f.f_code.co_filename!r},' - f' line {f.f_lineno}, in' - f' {tag} {code.co_qualname}()' - ) + tag = _FRAME_TAGS.get(f.f_code.co_flags & _CO_GEN_FLAGS, '') + add_line( + f' | File {f.f_code.co_filename!r},' + f' line {f.f_lineno}, in' + f' {tag}{f.f_code.co_qualname}()' + ) if st.awaited_by: add_line( diff --git a/Lib/test/test__opcode.py b/Lib/test/test__opcode.py index c253bc2be025a0..150187b36e557d 100644 --- a/Lib/test/test__opcode.py +++ b/Lib/test/test__opcode.py @@ -67,6 +67,9 @@ def test_stack_effect(self): self.assertEqual(stack_effect(dis.opmap['POP_TOP']), -1) self.assertEqual(stack_effect(dis.opmap['BUILD_SLICE'], 2), -1) self.assertEqual(stack_effect(dis.opmap['BUILD_SLICE'], 3), -2) + # After an awaited call, GET_AWAITABLE also pops the lazy outcome. + self.assertEqual(stack_effect(dis.opmap['GET_AWAITABLE'], 1), 2) + self.assertEqual(stack_effect(dis.opmap['GET_AWAITABLE'], 4 | 1), 1) self.assertRaises(ValueError, stack_effect, 30000) # All defined opcodes has_arg = dis.hasarg diff --git a/Lib/test/test_asyncio/test_graph.py b/Lib/test/test_asyncio/test_graph.py index 1f1c76e4aef69f..8df17a2a87de3c 100644 --- a/Lib/test/test_asyncio/test_graph.py +++ b/Lib/test/test_asyncio/test_graph.py @@ -1,4 +1,5 @@ import asyncio +import inspect import io import sys import types @@ -20,19 +21,22 @@ def walk(s): if isinstance(s.future, asyncio.Task) else 'F' ] + def tag(frame): + # f_generator is None until a lazily started coroutine + # first suspends. + flags = frame.f_code.co_flags + if flags & inspect.CO_COROUTINE: + return "a" + if flags & inspect.CO_ASYNC_GENERATOR: + return "ag" + if flags & inspect.CO_GENERATOR: + return "g" + return "s" + ret.append( [ - ( - f"s {entry.frame.f_code.co_name}" - if entry.frame.f_generator is None else - ( - f"a {entry.frame.f_generator.cr_code.co_name}" - if hasattr(entry.frame.f_generator, 'cr_code') else - f"ag {entry.frame.f_generator.ag_code.co_name}" - if hasattr(entry.frame.f_generator, 'ag_code') else - f"g {entry.frame.f_generator.gi_code.co_name}" - ) - ) for entry in s.call_stack + f"{tag(entry.frame)} {entry.frame.f_code.co_name}" + for entry in s.call_stack # Skip the pure Python Future.__await__ generator frame if entry.frame.f_code is not future_await_code ] @@ -986,6 +990,26 @@ async def child(): self.assertEqual(stack[0][2], [['T', ['a test_stack_eager_task'], []]]) + async def test_capture_call_graph_through_generator_based_coroutine(self): + # A native coroutine driven by a generator-based coroutine + # (yield from) keeps the frames of its callers. + stack = None + + async def native(): + nonlocal stack + graph = asyncio.capture_call_graph() + stack = [entry.frame.f_code.co_name for entry in graph.call_stack] + + @types.coroutine + def legacy(): + return (yield from native()) + + async def main(): + await legacy() + + await main() + self.assertEqual(stack[:3], ['native', 'legacy', 'main']) + @unittest.skipIf( not hasattr(asyncio.futures, "_c_future_add_to_awaited_by"), diff --git a/Lib/test/test_capi/test_opt.py b/Lib/test/test_capi/test_opt.py index 88077aacecbf5b..0fef739eb2dbb4 100644 --- a/Lib/test/test_capi/test_opt.py +++ b/Lib/test/test_capi/test_opt.py @@ -188,6 +188,44 @@ class TestUops(unittest.TestCase): def setUp(self): self.guard_is_false, self.guard_is_true = get_bool_guard_ops() + def test_awaited_call_jump_not_traced(self): + # Tier two runs only GET_AWAITABLE's fall-through: no trace may + # continue past END_SEND after a lazily started coroutine returned. + async def body(): + t = 0 + for i in range(2): + t += i + return t + + async def main(): + x = await body() + return x + 1 + + def run(): + coro = main() + try: + coro.send(None) + except StopIteration as exc: + return exc.value + return "suspended" + + offset = next(i.offset for i in dis.get_instructions(main) + if i.opname == "GET_AWAITABLE" and i.arg & 4) + enter_executor = dis.opmap["ENTER_EXECUTOR"] + for _ in range(30_000): # Long enough to chain side exits. + self.assertEqual(run(), 2) + if main.__code__._co_code_adaptive[offset] == enter_executor: + break + # Origin tracking makes the coroutine start eagerly. + old_depth = sys.get_coroutine_origin_tracking_depth() + sys.set_coroutine_origin_tracking_depth(1) + try: + self.assertEqual(run(), 2) + finally: + sys.set_coroutine_origin_tracking_depth(old_depth) + self.assertNotEqual(main.__code__._co_code_adaptive[offset], + enter_executor) + def test_basic_loop(self): def testfunc(x): i = 0 diff --git a/Lib/test/test_coroutines.py b/Lib/test/test_coroutines.py index c5900da09501b3..0a53ae162348e6 100644 --- a/Lib/test/test_coroutines.py +++ b/Lib/test/test_coroutines.py @@ -1,6 +1,9 @@ import ast import contextlib import copy +import dis +import builtins +import gc import inspect import pickle import sys @@ -2594,6 +2597,1189 @@ def test_unawaited_warning_during_shutdown(self): assert_python_ok("-c", code) +@support.cpython_only +class LazyCoroutineTest(unittest.TestCase): + """A coroutine that is awaited right away (``await f()``) runs in + the calling thread's frame and only gets a coroutine object when + it first suspends. This must not be observable, except that no + coroutine object exists before the first suspension.""" + + @staticmethod + def coroutines_for(code): + return [o for o in gc.get_objects() + if type(o) is types.CoroutineType and o.cr_code is code] + + def test_no_object_before_first_suspension(self): + seen = [] + + async def inner(): + seen.append(len(self.coroutines_for(inner.__code__))) + await AsyncYield(1) + seen.append(len(self.coroutines_for(inner.__code__))) + return 42 + + async def outer(): + return await inner() + + self.assertEqual(run_async(outer()), ([1], 42)) + self.assertEqual(seen, [0, 1]) + + def test_return_without_suspending(self): + async def inner(x): + return x + 1 + + async def outer(): + total = 0 + for i in range(100): + total += await inner(i) + return total + + self.assertEqual(run_async(outer()), ([], sum(range(1, 101)))) + + def test_nested_chain(self): + async def chain(n): + if n == 0: + await AsyncYield("bottom") + return 0 + return 1 + await chain(n - 1) + + self.assertEqual(run_async(chain(20)), (["bottom"], 20)) + + def test_exception_before_first_suspension(self): + async def inner(): + raise ValueError("boom") + + async def outer(): + try: + await inner() + except ValueError as exc: + tb = exc.__traceback__ + names = [] + while tb is not None: + names.append(tb.tb_frame.f_code.co_name) + tb = tb.tb_next + return names + + self.assertEqual(run_async(outer()), ([], ["outer", "inner"])) + + def test_stopiteration_before_first_suspension(self): + async def inner(): + raise StopIteration + + async def outer(): + await inner() + + with self.assertRaisesRegex(RuntimeError, + "coroutine raised StopIteration"): + run_async(outer()) + + def test_frame_object(self): + async def inner(): + x = 1 + frame = sys._getframe() + self.assertIsNone(frame.f_generator) + self.assertEqual(frame.f_locals["x"], 1) + self.assertEqual(frame.f_back.f_code.co_name, "outer") + await AsyncYield(1) + coro = frame.f_generator + self.assertIsInstance(coro, types.CoroutineType) + self.assertIs(coro.cr_frame, frame) + self.assertIs(coro.cr_code, inner.__code__) + self.assertEqual(frame.f_locals["x"], 1) + self.assertEqual(frame.f_back.f_code.co_name, "outer") + x = 2 + return frame + + async def outer(): + return await inner() + + _, frame = run_async(outer()) + self.assertIsNone(frame.f_generator) # finished + self.assertEqual(frame.f_locals["x"], 2) + + def test_exc_info_suspend_inside_handler(self): + async def inner(): + try: + raise KeyError + except KeyError: + await AsyncYield(1) + self.assertIsInstance(sys.exc_info()[1], KeyError) + await AsyncYield(2) + self.assertIsInstance(sys.exc_info()[1], KeyError) + # The caller's context is visible after the handler. + self.assertIsInstance(sys.exc_info()[1], TypeError) + await AsyncYield(3) + self.assertIsInstance(sys.exc_info()[1], TypeError) + return "ok" + + async def outer(): + try: + raise TypeError + except TypeError: + result = await inner() + self.assertIsInstance(sys.exc_info()[1], TypeError) + self.assertIsNone(sys.exc_info()[1]) + return result + + self.assertEqual(run_async(outer()), ([1, 2, 3], "ok")) + + def test_exc_info_handler_without_suspending(self): + async def inner(): + try: + raise KeyError + except KeyError: + self.assertIsInstance(sys.exc_info()[1], KeyError) + self.assertIsInstance(sys.exc_info()[1], TypeError) + return "ok" + + async def outer(): + try: + raise TypeError + except TypeError: + result = await inner() + self.assertIsInstance(sys.exc_info()[1], TypeError) + self.assertIsNone(sys.exc_info()[1]) + return result + + self.assertEqual(run_async(outer()), ([], "ok")) + + def test_throw_into_materialized_coroutine(self): + async def inner(): + try: + await AsyncYield(1) + except ZeroDivisionError: + return "caught" + return "not caught" + + async def outer(): + return await inner() + + coro = outer() + self.assertEqual(coro.send(None), 1) + with self.assertRaises(StopIteration) as cm: + coro.throw(ZeroDivisionError) + self.assertEqual(cm.exception.value, "caught") + + def test_close_materialized_coroutine(self): + closed = [] + + async def inner(): + try: + await AsyncYield(1) + finally: + closed.append(True) + + async def outer(): + await inner() + + coro = outer() + self.assertEqual(coro.send(None), 1) + coro.close() + self.assertEqual(closed, [True]) + + def test_async_with(self): + log = [] + + class CM: + async def __aenter__(self): + log.append("enter") + return self + + async def __aexit__(self, *args): + log.append("exit") + return False + + async def outer(): + async with CM() as cm: + log.append(type(cm).__name__) + await AsyncYield(1) + return "done" + + self.assertEqual(run_async(outer()), ([1], "done")) + self.assertEqual(log, ["enter", "CM", "exit"]) + + def test_async_with_lazy(self): + log = [] + + class CM: + def __init__(self, suspend=False, suppress=False): + self.suspend = suspend + self.suppress = suppress + + async def __aenter__(self): + log.append(("enter", sys._getframe().f_generator is None)) + if self.suspend: + await AsyncYield("enter") + return self + + async def __aexit__(self, typ, *args): + log.append(("exit", typ, sys._getframe().f_generator is None)) + if self.suspend: + await AsyncYield("exit") + return self.suppress + + async def body(cm): + async with cm: + return "returned" + + async def loop(cm): + for i in range(2): + async with cm: + if i == 0: + continue + break + return "looped" + + async def nested(cm): + async with cm, cm as x: + pass + return x + + async def raises(cm): + async with cm: + raise ValueError + return "suppressed" + + for suspend in False, True: + with self.subTest(suspend=suspend): + y = ["enter", "exit"] if suspend else [] + lazy = [("enter", True), ("exit", None, True)] + log.clear() + self.assertEqual(run_async(body(CM(suspend))), (y, "returned")) + self.assertEqual(log, lazy) + log.clear() + self.assertEqual(run_async(loop(CM(suspend))), (y * 2, "looped")) + self.assertEqual(log, lazy * 2) + log.clear() + cm = CM(suspend) + self.assertEqual(run_async(nested(cm)), (y[:1] * 2 + y[1:] * 2, cm)) + self.assertEqual(log, [lazy[0], lazy[0], lazy[1], lazy[1]]) + # WITH_EXCEPT_START calls __aexit__() eagerly. + log.clear() + self.assertEqual(run_async(raises(CM(suspend, True))), + (y, "suppressed")) + self.assertEqual(log, [("enter", True), ("exit", ValueError, False)]) + log.clear() + with self.assertRaises(ValueError): + run_async(raises(CM(suspend))) + + def test_async_comprehension(self): + async def inner(x): + return x * 2 + + async def outer(): + return [await inner(x) for x in range(5)] + + self.assertEqual(run_async(outer()), ([], [0, 2, 4, 6, 8])) + + def test_origin_tracking(self): + orig_depth = sys.get_coroutine_origin_tracking_depth() + + async def inner(): + await AsyncYield(1) + return sys._getframe().f_generator.cr_origin + + async def outer(): + coro = inner() + eager = (await coro)[0] + lazy = (await inner())[0] + return eager, lazy + + sys.set_coroutine_origin_tracking_depth(2) + try: + _, (eager, lazy) = run_async(outer()) + finally: + sys.set_coroutine_origin_tracking_depth(orig_depth) + # Origin tracking disables the lazy path: the origin is the + # call, not the await, and is captured at creation. + self.assertEqual(eager[0], __file__) + self.assertEqual(eager[2], "outer") + self.assertEqual(lazy[0], __file__) + self.assertEqual(lazy[2], "outer") + self.assertEqual(lazy[1], eager[1] + 2) + + def test_origin_tracking_multiline_await(self): + orig_depth = sys.get_coroutine_origin_tracking_depth() + + async def inner(): + await AsyncYield(1) + return sys._getframe().f_generator.cr_origin + + async def outer(): + origin = await ( + inner() + ) + return origin[0][1] - outer.__code__.co_firstlineno + + sys.set_coroutine_origin_tracking_depth(1) + try: + _, line = run_async(outer()) + finally: + sys.set_coroutine_origin_tracking_depth(orig_depth) + # The line of the call, not of the await. + self.assertEqual(line, 2) + + def test_settrace_events(self): + async def inner(): + await AsyncYield(1) + return 1 + + async def eager(): + coro = inner() + return await coro + + async def lazy(): + return await inner() + + def trace(coro_fn): + events = [] + + def tracer(frame, event, arg): + if frame.f_code is inner.__code__: + events.append((event, frame.f_lineno - frame.f_code.co_firstlineno)) + return tracer + + sys.settrace(tracer) + try: + result = run_async(coro_fn()) + finally: + sys.settrace(None) + return events, result + + self.assertEqual(trace(lazy), trace(eager)) + + def test_monitoring_events(self): + async def inner(): + await AsyncYield(1) + return 1 + + async def eager(): + coro = inner() + return await coro + + async def lazy(): + return await inner() + + E = sys.monitoring.events + # No LINE events: eager() has one more line. + names = {E.PY_START: "start", E.PY_RESUME: "resume", + E.PY_RETURN: "return", E.PY_YIELD: "yield", + E.STOP_ITERATION: "stop_iteration"} + codes = {inner.__code__: "inner", eager.__code__: "outer", + lazy.__code__: "outer"} + + def monitor(coro_fn): + events = [] + tool = sys.monitoring.DEBUGGER_ID + sys.monitoring.use_tool_id(tool, "test") + try: + for event, name in names.items(): + def callback(code, offset, *args, name=name): + if code in codes: + events.append( + (codes[code], name, type(args[-1]) if args else None)) + sys.monitoring.register_callback(tool, event, callback) + sys.monitoring.set_events(tool, sum(names)) + result = run_async(coro_fn()) + finally: + sys.monitoring.set_events(tool, 0) + sys.monitoring.free_tool_id(tool) + return events, result + + self.assertEqual(monitor(lazy), monitor(eager)) + self.assertIn(("outer", "stop_iteration", StopIteration), + monitor(lazy)[0]) + + def test_stop_iteration_event_without_suspending(self): + async def inner(): + return 42 + + async def outer(): + return await inner() + + E = sys.monitoring.events + events = [] + tool = sys.monitoring.DEBUGGER_ID + sys.monitoring.use_tool_id(tool, "test") + try: + def callback(code, offset, exc): + if code is outer.__code__: + events.append(exc.value) + sys.monitoring.register_callback(tool, E.STOP_ITERATION, callback) + sys.monitoring.set_events(tool, E.STOP_ITERATION) + self.assertEqual(run_async(outer()), ([], 42)) + finally: + sys.monitoring.set_events(tool, 0) + sys.monitoring.free_tool_id(tool) + self.assertEqual(events, [42]) + + def test_exc_state_after_suspending_inside_handler(self): + # The coroutine's own exception state must not keep the + # caller's exception once its handler is done. + async def inner(): + try: + raise KeyError + except KeyError: + await AsyncYield(1) + await AsyncYield(2) + return sys.exc_info()[1] + + async def outer(): + try: + raise TypeError + except TypeError: + return await inner() + + coro = outer() + coro.send(None) + inner_coro = coro.cr_await + inner_coro.send(None) + self.assertNotIn(TypeError, + map(type, gc.get_referents(inner_coro))) + # Resumed directly, not through outer: no handled exception. + with self.assertRaises(StopIteration) as cm: + inner_coro.send(None) + self.assertIsNone(cm.exception.value) + coro.close() + + def test_throw_into_coroutine_suspended_inside_handler(self): + async def inner(): + try: + raise KeyError + except KeyError: + try: + await AsyncYield(1) + except ZeroDivisionError: + pass + return sys.exception() + + async def outer(): + try: + raise TypeError + except TypeError: + result = await inner() + self.assertIsInstance(sys.exception(), TypeError) + return result + + coro = outer() + self.assertEqual(coro.send(None), 1) + with self.assertRaises(StopIteration) as cm: + coro.throw(ZeroDivisionError) + self.assertIsNone(cm.exception.value) + + def test_import_hook_locals(self): + seen = [] + orig_import = builtins.__import__ + + def hook(name, globals=None, locals=None, fromlist=(), level=0): + seen.append(locals) + return orig_import(name, globals, locals, fromlist, level) + + async def inner(): + import sys as _sys + return _sys + + async def outer(): + try: + raise TypeError + except TypeError: + return await inner() + + with support.swap_attr(builtins, "__import__", hook): + self.assertEqual(run_async(outer()), ([], sys)) + self.assertEqual(seen, [None]) + + def test_traceback_frame_keeps_no_caller_exception(self): + async def inner(): + raise ValueError + + async def outer(): + try: + raise TypeError + except TypeError: + try: + await inner() + except ValueError as exc: + return exc.__traceback__.tb_next.tb_frame + + _, frame = run_async(outer()) + self.assertIs(frame.f_code, inner.__code__) + self.assertNotIn(TypeError, map(type, gc.get_referents(frame))) + + def test_code_replaced_before_first_suspension(self): + # The coroutine object is created at the first suspension, so it + # must be sized for the code the frame runs, not func.__code__. + async def small(): + big, small # same free variables as big() + await AsyncYield(1) + + async def big(): + a = b = c = d = e = f = g = h = i = j = k = m = n = o = p = 1 + big.__code__ = small.__code__ + await AsyncYield(1) + return (a, b, c, d, e, f, g, h, i, j, k, m, n, o, p) + + async def outer(): + return await big() + + self.assertEqual(run_async(outer()), ([1], (1,) * 15)) + + def test_finished_frame_has_no_f_back(self): + async def inner(): + return sys._getframe() + + async def outer(): + return await inner() + + _, frame = run_async(outer()) + self.assertIs(frame.f_code, inner.__code__) + self.assertIsNone(frame.f_back) + + def run_failing_first_suspension(self, make_outer): + """Drive the coroutine returned by make_outer(awaitable, fail, failed). + + fail() makes allocation number *start* fail; failed() stops that + and records the state of the awaitable. Retry with a later *start* + until the allocation that fails creates a coroutine object when its + body first suspends at "await awaitable". + """ + @types.coroutine + def suspend(): + yield "suspended" + + for start in range(20): + awaitable = suspend() + states = [] + def fail(): + _testcapi.set_nomemory(start, start + 1) + def failed(): + _testcapi.remove_mem_hooks() + states.append(inspect.getgeneratorstate(awaitable)) + coro = make_outer(awaitable, fail, failed) + yields = [] + try: + try: + while True: + yields.append(coro.send(None)) + except BaseException as e: + outcome = e + finally: + _testcapi.remove_mem_hooks() + awaitable.close() + if (states[:1] == [inspect.GEN_SUSPENDED] + and "suspended" not in yields): + return yields, outcome + coro.close() + self.fail("no allocation failed at the first suspension") + + @unittest.skipIf(_testcapi is None, "requires _testcapi") + def test_memory_error_at_first_suspension(self): + class CM: + async def __aenter__(self): + log.append("enter") + async def __aexit__(self, typ, *args): + log.append(("exit", typ)) + + log = [] + def make_outer(awaitable, fail, failed): + async def inner(): + async with CM(): + fail() + try: + await awaitable + finally: + failed() + log.append("finally") + return "resumed" + + async def outer(): + return await inner() + + log.clear() + return outer() + + yields, outcome = self.run_failing_first_suspension(make_outer) + self.assertEqual(yields, []) + self.assertIsInstance(outcome, MemoryError) + self.assertEqual(log, ["enter", "finally", ("exit", MemoryError)]) + + @unittest.skipIf(_testcapi is None, "requires _testcapi") + def test_memory_error_at_first_suspension_caught(self): + @types.coroutine + def suspend_again(): + yield "again" + + def make_outer(awaitable, fail, failed): + async def inner(): + fail() + try: + await awaitable + except MemoryError: + failed() + await suspend_again() + return "caught" + finally: + failed() + + async def outer(): + # The list checks the stack of outer() after the await. + return ["x", await inner(), "y"] + + return outer() + + yields, outcome = self.run_failing_first_suspension(make_outer) + self.assertEqual(yields, ["again"]) + self.assertIsInstance(outcome, StopIteration) + self.assertEqual(outcome.value, ["x", "caught", "y"]) + + @unittest.skipIf(_testcapi is None, "requires _testcapi") + def test_memory_error_at_first_suspension_monitoring(self): + events = [] + tool = 2 + E = sys.monitoring.events + sys.monitoring.use_tool_id(tool, "test_coroutines") + self.addCleanup(sys.monitoring.free_tool_id, tool) + sys.monitoring.register_callback( + tool, E.PY_THROW, + lambda code, offset, exc: events.append((code.co_name, type(exc)))) + sys.monitoring.set_events(tool, E.PY_THROW) + self.addCleanup(sys.monitoring.set_events, tool, 0) + + def make_outer(awaitable, fail, failed): + async def inner(): + fail() + try: + await awaitable + finally: + failed() + + async def outer(): + return await inner() + + events.clear() + return outer() + + _, outcome = self.run_failing_first_suspension(make_outer) + self.assertIsInstance(outcome, MemoryError) + self.assertEqual(events[0], ("inner", MemoryError)) + + def test_recursion_error_before_body_runs(self): + async def f(): + return await f() + + coro = f() + with support.infinite_recursion(50): + with self.assertRaises(RecursionError): + coro.send(None) + + @unittest.skipIf(_testcapi is None, "requires _testcapi") + def test_memory_error_before_body_runs(self): + # MAKE_CELL runs before RETURN_GENERATOR. + async def inner(x): + def g(): + return x + return g + + async def outer(): + _testcapi.set_nomemory(0, 1) + try: + await inner(1) + except MemoryError: + return "MemoryError" + finally: + _testcapi.remove_mem_hooks() + + self.assertEqual(run_async(outer()), ([], "MemoryError")) + + def test_caller_location_while_body_runs(self): + positions = [] + + async def inner(): + caller = sys._getframe(1) + positions.append( + list(caller.f_code.co_positions())[caller.f_lasti // 2]) + + async def outer(): + x = (await + inner()) + + run_async(outer()) + line = outer.__code__.co_firstlineno + 1 + self.assertEqual(positions, [(line, line + 1, 17, 24)]) + + def test_origin_tracking_enabled_in_body(self): + @types.coroutine + def suspend(): + yield + + async def inner(): + sys.set_coroutine_origin_tracking_depth(5) + await suspend() + + async def outer(): + await inner() + + coro = outer() + try: + coro.send(None) + self.assertIsNone(coro.cr_await.cr_origin) + finally: + sys.set_coroutine_origin_tracking_depth(0) + coro.close() + + def test_coroutine_flag_without_coroutine_body(self): + def f(): + return 42 + code = f.__code__.replace(co_flags=f.__code__.co_flags | inspect.CO_COROUTINE) + g = types.FunctionType(code, globals()) + + async def outer(): + return await g() + + with self.assertRaisesRegex(TypeError, "can't be awaited"): + run_async(outer()) + + def test_line_events_at_awaited_call_jump_target(self): + # The list(genexpr) fast path jumps to GET_AWAITABLE. + async def list(arg): + await AsyncYield("suspended") + return "done" + + async def outer(): + x = (await + list(i for i in range(3))) + return x + + def tracer(frame, event, arg): + if event == "line" and frame.f_code is outer.__code__: + gc.collect() + return tracer + + for _ in range(100): # Specialize the call. + run_async(outer()) + old_trace = sys.gettrace() + sys.settrace(tracer) + try: + self.assertEqual(run_async(outer()), (["suspended"], "done")) + finally: + sys.settrace(old_trace) + + def test_line_events_on_await_line(self): + async def returns(): + return "done" + + async def suspends(): + await AsyncYield("suspended") + return "done" + + async def outer(f): + x = (await + f()) + return x + + mon = sys.monitoring + tool = mon.DEBUGGER_ID + for f in returns, suspends: + with self.subTest(f=f.__name__): + lines = [] + def line(code, lineno): + if code is outer.__code__: + lines.append(lineno - code.co_firstlineno) + mon.use_tool_id(tool, "test") + try: + mon.register_callback(tool, mon.events.LINE, line) + mon.set_events(tool, mon.events.LINE) + run_async(outer(f)) + finally: + mon.set_events(tool, 0) + mon.register_callback(tool, mon.events.LINE, None) + mon.free_tool_id(tool) + self.assertEqual(lines, [2, 1, 3]) + + def test_call_forms(self): + class C: + async def meth(self, x, *, y=0): + if y: + await AsyncYield(y) + return ("meth", x, y) + + async def func(*args, **kwargs): + if kwargs.get("suspend"): + await AsyncYield("f") + return (args, kwargs) + + obj = C() + bound = obj.meth + + async def outer(): + return [ + await obj.meth(1), + await obj.meth(2, y=3), + await bound(4), + await bound(5, y=6), + await func(7), + await func(*[8, 9]), + await func(**{"a": 10}), + await func(11, suspend=True), + ] + + for _ in range(3): # also with specialized calls + self.assertEqual(run_async(outer()), ( + [3, 6, "f"], + [("meth", 1, 0), ("meth", 2, 3), ("meth", 4, 0), + ("meth", 5, 6), ((7,), {}), ((8, 9), {}), + ((), {"a": 10}), ((11,), {"suspend": True})], + )) + + def test_send_specialized_for_other_awaitables(self): + # The SEND of an await site may have been specialized for another + # kind of awaitable before a coroutine function is awaited there. + async def agen(): + yield 1 + + class Iterator: + async def __anext__(self): + return 2 + + class SuspendingIterator: + async def __anext__(self): + await AsyncYield("s") + return 3 + + async def outer(it): + return await type(it).__anext__(it) + + def check(it, expected): + self.assertEqual(run_async(outer(it)), expected) + + for _ in range(3): + for _ in range(20): + check(agen(), ([], 1)) + check(Iterator(), ([], 2)) + check(SuspendingIterator(), (["s"], 3)) + + def test_traceback_like_eager_coroutine(self): + async def inner(): + raise ValueError + + async def outer(): + await inner() + + def format_tb(): + try: + run_async(outer()) + except ValueError: + return traceback.format_exc() + + lazy = format_tb() + # Origin tracking makes awaited calls create the coroutine eagerly. + old_depth = sys.get_coroutine_origin_tracking_depth() + sys.set_coroutine_origin_tracking_depth(1) + try: + eager = format_tb() + finally: + sys.set_coroutine_origin_tracking_depth(old_depth) + # The whole `await inner()` line, not just `inner()` with carets. + self.assertIn(" await inner()\n File", lazy) + self.assertEqual(lazy, eager) + + def test_traceback_multiline_await(self): + async def inner(): + raise ValueError + + async def outer(): + x = (await + inner()) + return x + + def format_tb(): + try: + run_async(outer()) + except ValueError: + return traceback.format_exc() + + lazy = format_tb() + old_depth = sys.get_coroutine_origin_tracking_depth() + sys.set_coroutine_origin_tracking_depth(1) + try: + eager = format_tb() + finally: + sys.set_coroutine_origin_tracking_depth(old_depth) + self.assertEqual(lazy, eager) + + def test_instrumentation_enabled_before_first_suspension(self): + # GET_AWAITABLE must run right after the body suspends, before + # anything else, even if LINE or INSTRUCTION events get enabled + # while the body runs. + E = sys.monitoring.events + tool = sys.monitoring.DEBUGGER_ID + + async def inner(events): + sys.monitoring.set_events(tool, events) + await AsyncYield("suspended") + return "done" + + async def outer(events): + x = (await + inner(events)) + return x + + for events in (E.LINE, E.INSTRUCTION, E.LINE | E.INSTRUCTION): + with self.subTest(events=events): + sys.monitoring.use_tool_id(tool, "test") + try: + for event in (E.LINE, E.INSTRUCTION): + sys.monitoring.register_callback( + tool, event, lambda *args: gc.collect()) + self.assertEqual(run_async(outer(events)), + (["suspended"], "done")) + finally: + sys.monitoring.set_events(tool, 0) + sys.monitoring.free_tool_id(tool) + + def test_lazy_with_line_events_at_awaited_call_jump_target(self): + # The list(genexpr) fast path jumps to GET_AWAITABLE, which must + # not get INSTRUMENTED_LINE. + async def list(arg): + return sys._getframe().f_generator is None + + async def outer(): + return await list(i for i in range(3)) + + mon = sys.monitoring + tool = mon.DEBUGGER_ID + self.assertEqual(run_async(outer()), ([], True)) + mon.use_tool_id(tool, "test") + try: + mon.register_callback(tool, mon.events.LINE, lambda *args: None) + mon.set_events(tool, mon.events.LINE) + self.assertEqual(run_async(outer()), ([], True)) + finally: + mon.set_events(tool, 0) + mon.register_callback(tool, mon.events.LINE, None) + mon.free_tool_id(tool) + self.assertEqual(run_async(outer()), ([], True)) + + def test_line_event_raises_at_await(self): + async def inner(): + await AsyncYield("suspended") + return "done" + + async def outer(): + x = (await + inner()) + return x + + def line(code, lineno): + if code is outer.__code__ and lineno == code.co_firstlineno + 1: + raise ValueError("line") + + mon = sys.monitoring + tool = mon.DEBUGGER_ID + mon.use_tool_id(tool, "test") + try: + mon.register_callback(tool, mon.events.LINE, line) + mon.set_events(tool, mon.events.LINE) + with self.assertRaisesRegex(ValueError, "line"): + run_async(outer()) + finally: + mon.set_events(tool, 0) + mon.register_callback(tool, mon.events.LINE, None) + mon.free_tool_id(tool) + + @staticmethod + @contextlib.contextmanager + def eager(): + # Origin tracking makes awaited calls create the coroutine eagerly. + old_depth = sys.get_coroutine_origin_tracking_depth() + sys.set_coroutine_origin_tracking_depth(1) + try: + yield + finally: + sys.set_coroutine_origin_tracking_depth(old_depth) + + def test_settrace_events_like_eager_coroutine(self): + async def returns(): + return 1 + + async def suspends(): + await AsyncYield(None) + return 1 + + async def raises(): + raise ValueError + + async def outer(f): + try: + x = (await + f()) + except ValueError: + x = 0 + return x + + def trace(f): + events = [] + def tracer(frame, event, arg): + code = frame.f_code + if code in (outer.__code__, f.__code__): + events.append((code.co_name, event, + frame.f_lineno - code.co_firstlineno)) + return tracer + old_trace = sys.gettrace() + sys.settrace(tracer) + try: + run_async(outer(f)) + finally: + sys.settrace(old_trace) + return events + + for f in returns, suspends, raises: + with self.subTest(f=f.__name__): + lazy = trace(f) + with self.eager(): + eager = trace(f) + self.assertEqual(lazy, eager) + + def test_traceback_lineno_with_line_events(self): + async def outer(): + await ( + int()) + + def tb_lineno(): + try: + run_async(outer()) + except TypeError as e: + tb = e.__traceback__ + while tb.tb_frame.f_code is not outer.__code__: + tb = tb.tb_next + return tb.tb_lineno - outer.__code__.co_firstlineno + + mon = sys.monitoring + tool = mon.DEBUGGER_ID + self.assertEqual(tb_lineno(), 1) + mon.use_tool_id(tool, "test") + try: + mon.register_callback(tool, mon.events.LINE, lambda *args: None) + mon.set_local_events(tool, outer.__code__, mon.events.LINE) + self.assertEqual(tb_lineno(), 1) + mon.set_local_events(tool, outer.__code__, 0) + self.assertEqual(tb_lineno(), 1) + finally: + mon.register_callback(tool, mon.events.LINE, None) + mon.free_tool_id(tool) + + def test_instruction_events_at_awaited_call(self): + async def inner(): + return 1 + + async def outer(): + return await inner() + + get_awaitable = [i.offset for i in dis.get_instructions(outer) + if i.opname == "GET_AWAITABLE"] + offsets = [] + def instruction(code, offset): + if code is outer.__code__: + offsets.append(offset) + + mon = sys.monitoring + tool = mon.DEBUGGER_ID + mon.use_tool_id(tool, "test") + try: + mon.register_callback(tool, mon.events.INSTRUCTION, instruction) + mon.set_local_events(tool, outer.__code__, mon.events.INSTRUCTION) + self.assertEqual(run_async(outer()), ([], 1)) + finally: + mon.set_local_events(tool, outer.__code__, 0) + mon.register_callback(tool, mon.events.INSTRUCTION, None) + mon.free_tool_id(tool) + self.assertEqual(len(get_awaitable), 1) + self.assertIn(get_awaitable[0], offsets) + + def test_set_lineno_on_await_line_before_body(self): + async def inner(): + return "done" + + async def outer(): + x = (await + inner()) + return x + + first = outer.__code__.co_firstlineno + errors = [] + def tracer(frame, event, arg): + if (event == "line" and frame.f_code is outer.__code__ + and frame.f_lineno == first + 1): + try: + frame.f_lineno = first + 3 + except ValueError as e: + errors.append(str(e)) + return tracer + + old_trace = sys.gettrace() + sys.settrace(tracer) + try: + self.assertEqual(run_async(outer()), ([], "done")) + finally: + sys.settrace(old_trace) + self.assertEqual(errors, + ["can't jump from the await of a lazily run coroutine"]) + + def test_set_lineno_to_multiline_await(self): + # The await line must not start at GET_AWAITABLE, whose lazy + # outcome slot cannot hold an arbitrary object. + async def inner(): + return "done" + + async def outer(): + a = b = [1] + t = (a, b, + a) + x = (await + inner()) + return x + + first = outer.__code__.co_firstlineno + errors = [] + def tracer(frame, event, arg): + if (event == "line" and frame.f_code is outer.__code__ + and frame.f_lineno == first + 3): + try: + frame.f_lineno = first + 4 + except ValueError as e: + errors.append(str(e)) + return tracer + + old_trace = sys.gettrace() + sys.settrace(tracer) + try: + self.assertEqual(run_async(outer()), ([], "done")) + finally: + sys.settrace(old_trace) + self.assertEqual(len(errors), 1) + self.assertIn("incompatible stacks", errors[0]) + + def test_exc_state_at_data_stack_chunk_end(self): + # The body's exception state may start a new data stack chunk. + async def rec(n): + if n == 0: + await AsyncYield(None) + return 0 + return await rec(n - 1) + 1 + + def padded(k): + ns = {} + names = "=".join(f"a{i}" for i in range(k)) + body = f" {names} = None\n" if k else "" + exec(f"def f(fn):\n{body} return fn()\n", ns) + return ns["f"] + + # Shift the frames by one slot at a time. + for k in range(32): + self.assertEqual(padded(k)(lambda: run_async(rec(200))), + ([None], 200)) + + @support.cpython_only @unittest.skipIf(_testcapi is None, "requires _testcapi") class CAPITest(unittest.TestCase): diff --git a/Lib/test/test_dis.py b/Lib/test/test_dis.py index 2c3972c7394d01..c3ff3ced29808c 100644 --- a/Lib/test/test_dis.py +++ b/Lib/test/test_dis.py @@ -608,13 +608,17 @@ async def _asyncwith(c): L1: RESUME 0 %4d LOAD_FAST 0 (c) + PUSH_NULL + SWAP 2 COPY 1 LOAD_SPECIAL 3 (__aexit__) SWAP 2 SWAP 3 + PUSH_NULL + SWAP 2 LOAD_SPECIAL 2 (__aenter__) CALL 0 - GET_AWAITABLE 1 + GET_AWAITABLE 5 L2: SEND 4 (to L5) L3: YIELD_VALUE 1 L4: RESUME 3 @@ -629,7 +633,7 @@ async def _asyncwith(c): LOAD_COMMON_CONSTANT 7 (None) LOAD_COMMON_CONSTANT 7 (None) CALL 3 - GET_AWAITABLE 2 + GET_AWAITABLE 6 L8: SEND 4 (to L11) L9: YIELD_VALUE 1 L10: RESUME 3 @@ -664,6 +668,7 @@ async def _asyncwith(c): POP_TOP POP_TOP POP_TOP + POP_TOP %4d LOAD_SMALL_INT 2 STORE_FAST 2 (y) @@ -677,16 +682,16 @@ async def _asyncwith(c): RERAISE 1 ExceptionTable: L1 to L3 -> L25 [0] lasti - L3 to L4 -> L12 [5] + L3 to L4 -> L12 [6] L4 to L6 -> L25 [0] lasti - L6 to L7 -> L16 [2] lasti + L6 to L7 -> L16 [3] lasti L7 to L9 -> L25 [0] lasti L9 to L10 -> L14 [3] L10 to L13 -> L25 [0] lasti L14 to L15 -> L25 [0] lasti - L16 to L18 -> L24 [4] lasti - L18 to L19 -> L20 [8] - L19 to L23 -> L24 [4] lasti + L16 to L18 -> L24 [5] lasti + L18 to L19 -> L20 [9] + L19 to L23 -> L24 [5] lasti L23 to L25 -> L25 [0] lasti """ % (_asyncwith.__code__.co_firstlineno, _asyncwith.__code__.co_firstlineno + 1, @@ -1308,6 +1313,22 @@ async def afunc(): self.assertNotIn("to", line) self.assertIn("from", line) + def test_awaited_call(self): + + async def afunc(): + await f(1) + await x + + instrs = list(dis.get_instructions(afunc)) + names = [i.opname for i in instrs] + start = names.index('GET_AWAITABLE') + self.assertEqual(names[start - 2:start + 4], [ + 'LOAD_SMALL_INT', 'CALL', 'GET_AWAITABLE', + 'SEND', 'YIELD_VALUE', 'RESUME']) + # Only `await ` sets the awaited call flag. + self.assertEqual([i.arg for i in instrs if i.opname == 'GET_AWAITABLE'], + [4, 0]) + @staticmethod def code_quicken(f): diff --git a/Lib/test/test_opcache.py b/Lib/test/test_opcache.py index 5f7c15f93a8332..033c349aca4bf4 100644 --- a/Lib/test/test_opcache.py +++ b/Lib/test/test_opcache.py @@ -548,6 +548,101 @@ def count_args(self, *args): MyClass.__init__.__code__ = count_args.__code__ instantiate() + @requires_jit_disabled + @requires_specialization + def test_awaited_calls(self): + async def exact(x): + return sys._getframe().f_generator is None + + async def general(x, y=None): + return sys._getframe().f_generator is None + + class C: + async def exact(self, x): + return sys._getframe().f_generator is None + + async def general(self, x, y=None): + return sys._getframe().f_generator is None + + c = C() + bound_exact = c.exact + bound_general = c.general + + async def outer(): + return [ + await exact(1), + await general(1), + await bound_exact(1), + await bound_general(1), + await exact(x=1), + await bound_exact(x=1), + ] + + def run(): + coro = outer() + try: + coro.send(None) + except StopIteration as exc: + return exc.value + self.fail("outer() suspended") + + for _ in range(_testinternalcapi.SPECIALIZATION_THRESHOLD): + # All coroutines run without a coroutine object. + self.assertEqual(run(), [True] * 6) + for opname in ("CALL_PY_EXACT_ARGS_AWAITED", + "CALL_PY_GENERAL_AWAITED", + "CALL_BOUND_METHOD_EXACT_ARGS_AWAITED", + "CALL_BOUND_METHOD_GENERAL_AWAITED", + "CALL_KW_PY_AWAITED", + "CALL_KW_BOUND_METHOD_AWAITED"): + self.assert_specialized(outer, opname) + self.assert_no_opcode(outer, "CALL_PY_EXACT_ARGS") + self.assertEqual(run(), [True] * 6) + + @requires_jit_disabled + @requires_specialization + def test_awaited_non_coroutine_calls(self): + # Awaited calls of anything but a coroutine function get the same + # specializations as other calls. + class Ready: + def __init__(self, value): + self.value = value + + def __await__(self): + return self.value + yield + + ready = Ready(1) + + def make_ready(): + return ready + + get_ready = [ready].__getitem__ + + async def outer(): + return [ + await Ready(1), + await make_ready(), + await get_ready(0), + ] + + def run(): + coro = outer() + try: + coro.send(None) + except StopIteration as exc: + return exc.value + self.fail("outer() suspended") + + for _ in range(_testinternalcapi.SPECIALIZATION_THRESHOLD): + self.assertEqual(run(), [1, 1, 1]) + for opname in ("CALL_ALLOC_AND_ENTER_INIT", + "CALL_PY_EXACT_ARGS", + "CALL_BUILTIN_O"): + self.assert_specialized(outer, opname) + self.assert_no_opcode(outer, "CALL_PY_EXACT_ARGS_AWAITED") + self.assertEqual(run(), [1, 1, 1]) + @requires_jit_disabled @requires_specialization def test_push_init_frame_fails(self): @@ -1630,8 +1725,15 @@ def run_async(coro): except StopIteration: break + class Suspend: + def __await__(self): + yield + class CM: async def __aenter__(self): + # Without suspending, it would run lazily and the SEND + # after it would be skipped. + await Suspend() return self async def __aexit__(self, *exc): diff --git a/Lib/test/test_sys_settrace.py b/Lib/test/test_sys_settrace.py index a5e7bbbfad5ffc..917625964c1231 100644 --- a/Lib/test/test_sys_settrace.py +++ b/Lib/test/test_sys_settrace.py @@ -42,6 +42,9 @@ async def __aenter__(self): async def __aexit__(self, *exc_info): self.output.append(-self.value) +async def async_noop(): + pass + async def asynciter(iterable): """Convert an iterable to an asynchronous iterator.""" for x in iterable: @@ -2165,6 +2168,20 @@ def test_jump_out_of_block_backwards(output): output.append(6) output.append(7) + @async_jump_test(3, 4, [1, 4]) + async def test_jump_forwards_after_awaited_call(output): + output.append(1) + await async_noop() + output.append(3) + output.append(4) + + @async_jump_test(4, 2, [1, 3, 3, 4]) + async def test_jump_backwards_over_awaited_call(output): + output.append(1) + await async_noop() + output.append(3) + output.append(4) + @async_jump_test(4, 5, [3, 5]) @clean_asynciter async def test_jump_out_of_async_for_block_forwards(output, asynciter): diff --git a/Misc/NEWS.d/next/Core_and_Builtins/2026-10-27-12-00-00.gh-issue-161170.lazyCo.rst b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-27-12-00-00.gh-issue-161170.lazyCo.rst new file mode 100644 index 00000000000000..fb20cc7fa50ba0 --- /dev/null +++ b/Misc/NEWS.d/next/Core_and_Builtins/2026-10-27-12-00-00.gh-issue-161170.lazyCo.rst @@ -0,0 +1,5 @@ +Make ``await`` of a coroutine that completes without suspending about twice as +fast by running it without creating a coroutine object. This also applies to +``async def`` :meth:`~object.__aenter__` and :meth:`~object.__aexit__` methods +in :keyword:`async with`. Until such a coroutine +first suspends, :attr:`frame.f_generator` is ``None``. diff --git a/Modules/_remote_debugging/frames.c b/Modules/_remote_debugging/frames.c index 3f8d628a6314e6..e1e3050a7e2214 100644 --- a/Modules/_remote_debugging/frames.c +++ b/Modules/_remote_debugging/frames.c @@ -182,7 +182,9 @@ is_frame_valid( return FRAME_PARSE_INTERPRETER; // C frame or sentinel base frame } - if (owner != FRAME_OWNED_BY_GENERATOR && owner != FRAME_OWNED_BY_THREAD) { + if (owner != FRAME_OWNED_BY_GENERATOR && owner != FRAME_OWNED_BY_THREAD && + owner != FRAME_OWNED_BY_LAZY_CORO) + { PyErr_Format(PyExc_RuntimeError, "Unhandled frame owner %d.\n", owner); set_exception_cause(unwinder, PyExc_RuntimeError, "Unhandled frame owner type in async frame"); return -1; diff --git a/Modules/_testinternalcapi/test_cases.c.h b/Modules/_testinternalcapi/test_cases.c.h index 8bb3f857437792..e49b28757ccac9 100644 --- a/Modules/_testinternalcapi/test_cases.c.h +++ b/Modules/_testinternalcapi/test_cases.c.h @@ -1896,6 +1896,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL) { + MAYBE_START_LAZY_CORO(new_frame); + } frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); } @@ -2233,6 +2236,160 @@ DISPATCH(); } + TARGET(CALL_BOUND_METHOD_EXACT_ARGS_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_BOUND_METHOD_EXACT_ARGS_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_BOUND_METHOD_EXACT_ARGS_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef null; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_CALL_BOUND_METHOD_EXACT_ARGS + { + null = stack_pointer[-1 - oparg]; + callable = stack_pointer[-2 - oparg]; + if (!PyStackRef_IsNull(null)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + if (Py_TYPE(PyStackRef_AsPyObjectBorrow(callable)) != &PyMethod_Type) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _INIT_CALL_BOUND_METHOD_EXACT_ARGS + { + self_or_null = null; + assert(PyStackRef_IsNull(self_or_null)); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + STAT_INC(CALL, hit); + self_or_null = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_self); + _PyStackRef temp = callable; + callable = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_func); + stack_pointer[-2 - oparg] = callable; + stack_pointer[-1 - oparg] = self_or_null; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } + // flush + // _CHECK_FUNCTION_VERSION + { + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_EXACT_ARGS + { + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(PyFunction_Check(callable_o)); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (code->co_argcount != oparg + (!PyStackRef_IsNull(self_or_null))) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_STACK_SPACE + { + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (!_PyThreadState_HasStackSpace(tstate, code->co_framesize)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _INIT_CALL_PY_EXACT_ARGS + { + args = &stack_pointer[-oparg]; + int has_self = !PyStackRef_IsNull(self_or_null); + STAT_INC(CALL, hit); + _PyInterpreterFrame *pushed_frame = _PyFrame_PushUnchecked(tstate, callable, oparg + has_self, frame); + _PyStackRef *first_non_self_local = pushed_frame->localsplus + has_self; + pushed_frame->localsplus[0] = self_or_null; + for (int i = 0; i < oparg; i++) { + first_non_self_local[i] = args[i]; + } + new_frame = PyStackRef_Wrap(pushed_frame); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_BOUND_METHOD_GENERAL) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_BOUND_METHOD_GENERAL; @@ -2369,6 +2526,146 @@ DISPATCH(); } + TARGET(CALL_BOUND_METHOD_GENERAL_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_BOUND_METHOD_GENERAL_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_BOUND_METHOD_GENERAL_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef null; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_METHOD_VERSION + { + null = stack_pointer[-1 - oparg]; + callable = stack_pointer[-2 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (Py_TYPE(callable_o) != &PyMethod_Type) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyObject *func = ((PyMethodObject *)callable_o)->im_func; + if (!PyFunction_Check(func)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + if (((PyFunctionObject *)func)->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + if (!PyStackRef_IsNull(null)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _EXPAND_METHOD + { + self_or_null = null; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(PyStackRef_IsNull(self_or_null)); + assert(Py_TYPE(callable_o) == &PyMethod_Type); + self_or_null = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_self); + _PyStackRef temp = callable; + callable = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_func); + assert(PyStackRef_FunctionCheck(callable)); + stack_pointer[-2 - oparg] = callable; + stack_pointer[-1 - oparg] = self_or_null; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } + // flush + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _PY_FRAME_GENERAL + { + args = &stack_pointer[-oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + if (!PyStackRef_IsNull(self_or_null)) { + args--; + total_args++; + } + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + args, total_args, NULL, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_BUILTIN_CLASS) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_BUILTIN_CLASS; @@ -2972,6 +3269,13 @@ } ex_frame = PyStackRef_Wrap(new_frame); } + // _MAYBE_LAZY_CORO + { + new_frame = ex_frame; + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + } // _SAVE_RETURN_OFFSET { #if TIER_ONE @@ -2983,7 +3287,6 @@ } // _PUSH_FRAME { - new_frame = ex_frame; assert(!IS_PEP523_HOOKED(tstate)); _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); _PyFrame_SetStackPointer(frame, stack_pointer); @@ -3150,6 +3453,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 2u == 1 + INLINE_CACHE_ENTRIES_CALL_FUNCTION_EX); frame->return_offset = 2u ; DISPATCH_INLINED(new_frame); @@ -3466,6 +3772,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL_KW) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 4u == 1 + INLINE_CACHE_ENTRIES_CALL_KW); frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); @@ -3474,39 +3783,178 @@ stack_pointer[-2 - oparg] = self_or_null; _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); - PyObject* res_o = _Py_VectorCallInstrumentation_StackRefSteal( - callable, - arguments, - total_args, - kwnames, - opcode == INSTRUMENTED_CALL_KW, - frame, - this_instr, - tstate); + PyObject* res_o = _Py_VectorCallInstrumentation_StackRefSteal( + callable, + arguments, + total_args, + kwnames, + opcode == INSTRUMENTED_CALL_KW, + frame, + this_instr, + tstate); + _PyFrame_StackPointerInvalidate(frame); + if (res_o == NULL) { + stack_pointer += -3 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + JUMP_TO_LABEL(error); + } + res = PyStackRef_FromPyObjectSteal(res_o); + } + stack_pointer[-3 - oparg] = res; + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + DISPATCH(); + } + + TARGET(CALL_KW_BOUND_METHOD) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_KW_BOUND_METHOD; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_KW_BOUND_METHOD); + static_assert(INLINE_CACHE_ENTRIES_CALL_KW == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef null; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef kwnames; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _CHECK_METHOD_VERSION_KW + { + null = stack_pointer[-2 - oparg]; + callable = stack_pointer[-3 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (Py_TYPE(callable_o) != &PyMethod_Type) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + PyObject *func = ((PyMethodObject *)callable_o)->im_func; + if (!PyFunction_Check(func)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + if (((PyFunctionObject *)func)->func_version != func_version) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + if (!PyStackRef_IsNull(null)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _EXPAND_METHOD_KW + { + self_or_null = null; + assert(PyStackRef_IsNull(self_or_null)); + _PyStackRef callable_s = callable; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(Py_TYPE(callable_o) == &PyMethod_Type); + self_or_null = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_self); + callable = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_func); + assert(PyStackRef_FunctionCheck(callable)); + stack_pointer[-3 - oparg] = callable; + stack_pointer[-2 - oparg] = self_or_null; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(callable_s); + _PyFrame_StackPointerInvalidate(frame); + } + // flush + // _PY_FRAME_KW + { + kwnames = stack_pointer[-1]; + args = &stack_pointer[-1 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + _PyStackRef *arguments = args; + if (!PyStackRef_IsNull(self_or_null)) { + arguments--; + total_args++; + } + PyObject *kwnames_o = PyStackRef_AsPyObjectBorrow(kwnames); + int positional_args = total_args - (int)PyTuple_GET_SIZE(kwnames_o); + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + arguments, positional_args, kwnames_o, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(kwnames); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - if (res_o == NULL) { - stack_pointer += -3 - oparg; - ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); - JUMP_TO_LABEL(error); - } - res = PyStackRef_FromPyObjectSteal(res_o); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); } - stack_pointer[-3 - oparg] = res; - stack_pointer += -2 - oparg; - ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } - TARGET(CALL_KW_BOUND_METHOD) { + TARGET(CALL_KW_BOUND_METHOD_AWAITED) { #if _Py_TAIL_CALL_INTERP - int opcode = CALL_KW_BOUND_METHOD; + int opcode = CALL_KW_BOUND_METHOD_AWAITED; (void)(opcode); #endif _Py_CODEUNIT* const this_instr = next_instr; (void)this_instr; frame->instr_ptr = next_instr; next_instr += 4; - INSTRUCTION_STATS(CALL_KW_BOUND_METHOD); + INSTRUCTION_STATS(CALL_KW_BOUND_METHOD_AWAITED); static_assert(INLINE_CACHE_ENTRIES_CALL_KW == 3, "incorrect cache size"); _PyStackRef callable; _PyStackRef null; @@ -3605,6 +4053,10 @@ } new_frame = PyStackRef_Wrap(temp); } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } // _SAVE_RETURN_OFFSET { #if TIER_ONE @@ -3833,6 +4285,128 @@ DISPATCH(); } + TARGET(CALL_KW_PY_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_KW_PY_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_KW_PY_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL_KW == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef kwnames; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _CHECK_FUNCTION_VERSION_KW + { + callable = stack_pointer[-3 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _PY_FRAME_KW + { + kwnames = stack_pointer[-1]; + args = &stack_pointer[-1 - oparg]; + self_or_null = stack_pointer[-2 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + _PyStackRef *arguments = args; + if (!PyStackRef_IsNull(self_or_null)) { + arguments--; + total_args++; + } + PyObject *kwnames_o = PyStackRef_AsPyObjectBorrow(kwnames); + int positional_args = total_args - (int)PyTuple_GET_SIZE(kwnames_o); + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + arguments, positional_args, kwnames_o, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(kwnames); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_LEN) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_LEN; @@ -4592,32 +5166,151 @@ } res = PyStackRef_FromPyObjectSteal(res_o); } - // _CHECK_PERIODIC_AT_END + // _CHECK_PERIODIC_AT_END + { + stack_pointer[-2 - oparg] = res; + stack_pointer += -1 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + int err = check_periodics_at_end(tstate, frame); + _PyFrame_StackPointerInvalidate(frame); + if (err != 0) { + JUMP_TO_LABEL(error); + } + } + DISPATCH(); + } + + TARGET(CALL_PY_EXACT_ARGS) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_PY_EXACT_ARGS; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_PY_EXACT_ARGS); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_VERSION + { + callable = stack_pointer[-2 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_EXACT_ARGS + { + self_or_null = stack_pointer[-1 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(PyFunction_Check(callable_o)); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (code->co_argcount != oparg + (!PyStackRef_IsNull(self_or_null))) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_STACK_SPACE + { + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (!_PyThreadState_HasStackSpace(tstate, code->co_framesize)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _INIT_CALL_PY_EXACT_ARGS + { + args = &stack_pointer[-oparg]; + int has_self = !PyStackRef_IsNull(self_or_null); + STAT_INC(CALL, hit); + _PyInterpreterFrame *pushed_frame = _PyFrame_PushUnchecked(tstate, callable, oparg + has_self, frame); + _PyStackRef *first_non_self_local = pushed_frame->localsplus + has_self; + pushed_frame->localsplus[0] = self_or_null; + for (int i = 0; i < oparg; i++) { + first_non_self_local[i] = args[i]; + } + new_frame = PyStackRef_Wrap(pushed_frame); + } + // _SAVE_RETURN_OFFSET { - stack_pointer[-2 - oparg] = res; - stack_pointer += -1 - oparg; + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + stack_pointer += -2 - oparg; ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); - int err = check_periodics_at_end(tstate, frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - if (err != 0) { - JUMP_TO_LABEL(error); - } + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); } DISPATCH(); } - TARGET(CALL_PY_EXACT_ARGS) { + TARGET(CALL_PY_EXACT_ARGS_AWAITED) { #if _Py_TAIL_CALL_INTERP - int opcode = CALL_PY_EXACT_ARGS; + int opcode = CALL_PY_EXACT_ARGS_AWAITED; (void)(opcode); #endif _Py_CODEUNIT* const this_instr = next_instr; (void)this_instr; frame->instr_ptr = next_instr; next_instr += 4; - INSTRUCTION_STATS(CALL_PY_EXACT_ARGS); + INSTRUCTION_STATS(CALL_PY_EXACT_ARGS_AWAITED); static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); _PyStackRef callable; _PyStackRef self_or_null; @@ -4694,6 +5387,10 @@ } new_frame = PyStackRef_Wrap(pushed_frame); } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } // _SAVE_RETURN_OFFSET { #if TIER_ONE @@ -4834,6 +5531,117 @@ DISPATCH(); } + TARGET(CALL_PY_GENERAL_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_PY_GENERAL_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_PY_GENERAL_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_VERSION + { + callable = stack_pointer[-2 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _PY_FRAME_GENERAL + { + args = &stack_pointer[-oparg]; + self_or_null = stack_pointer[-1 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + if (!PyStackRef_IsNull(self_or_null)) { + args--; + total_args++; + } + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + args, total_args, NULL, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_STR_1) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_STR_1; @@ -5198,7 +6006,8 @@ sub_iter = stack_pointer[-4]; PyObject *exc_value = PyStackRef_AsPyObjectBorrow(exc_value_st); #if !_Py_TAIL_CALL_INTERP - assert(throwflag); + + assert(throwflag || frame->owner == FRAME_OWNED_BY_LAZY_CORO); #endif assert(exc_value && PyExceptionInstance_Check(exc_value)); _PyFrame_SetStackPointer(frame, stack_pointer); @@ -6828,27 +7637,104 @@ frame->instr_ptr = next_instr; next_instr += 1; INSTRUCTION_STATS(GET_AWAITABLE); + _PyStackRef *lazy_outcome; + _PyStackRef res; + _PyStackRef value; _PyStackRef iterable; _PyStackRef iter; _PyStackRef null; _PyStackRef none; - iterable = stack_pointer[-1]; - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), oparg); - _PyFrame_StackPointerInvalidate(frame); - stack_pointer += -1; - ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyStackRef_CLOSE(iterable); - _PyFrame_StackPointerInvalidate(frame); - if (iter_o == NULL) { - JUMP_TO_LABEL(error); + // _LAZY_CALL_OUTCOME + { + res = stack_pointer[-1]; + lazy_outcome = &stack_pointer[-1 - ((oparg >> 2) & 1)]; + if (oparg & GET_AWAITABLE_AWAITED_CALL) { + _PyStackRef *slot = &stack_pointer[-2]; + assert(slot == lazy_outcome); + (void)lazy_outcome; + _PyStackRef outcome = *slot; + if (PyStackRef_IsTaggedInt(outcome)) { + *slot = PyStackRef_NULL; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(_Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), + (int)(next_instr - _PyFrame_GetBytecode(frame))).op.code == SEND); + _PyFrame_StackPointerInvalidate(frame); + _Py_CODEUNIT *end_send = next_instr + 1 + INLINE_CACHE_ENTRIES_SEND + next_instr->op.arg; + if (end_send->op.code != END_SEND) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int err = monitor_stop_iteration(tstate, frame, end_send, + PyStackRef_AsPyObjectBorrow(res)); + _PyFrame_StackPointerInvalidate(frame); + if (err) { + JUMP_TO_LABEL(error); + } + } + _PyStackRef v = res; + stack_pointer[-2] = v; + stack_pointer -= 1; + next_instr = end_send + 1; + DISPATCH(); + } + else if (!PyStackRef_IsNull(outcome)) { + _PyInterpreterFrame *lazy_frame = PyStackRef_Unwrap(outcome); + *slot = PyStackRef_NULL; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyGenObject *gen = _PyEval_MaterializeLazyCoro(tstate, lazy_frame); + _PyFrame_StackPointerInvalidate(frame); + _PyStackRef v = res; + if (gen == NULL) { + stack_pointer[-1] = PyStackRef_NULL; + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + frame = _PyEval_ThrowIntoLazyCoro(tstate, lazy_frame, v); + _PyFrame_StackPointerInvalidate(frame); + next_instr = frame->instr_ptr; + LOAD_SP(); + JUMP_TO_LABEL(error); + } + stack_pointer[-2] = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + stack_pointer[-1] = PyStackRef_NULL; + stack_pointer[0] = v; + stack_pointer += 1; + next_instr += 1 + INLINE_CACHE_ENTRIES_SEND; + DISPATCH(); + } + } + } + // _POP_LAZY_OUTCOME + { + assert(!(oparg & GET_AWAITABLE_AWAITED_CALL) || + PyStackRef_IsNull(lazy_outcome[0])); + (void)lazy_outcome; + value = res; + } + // _GET_AWAITABLE + { + iterable = value; + stack_pointer[-1 - ((oparg >> 2) & 1)] = iterable; + stack_pointer += -((oparg >> 2) & 1); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), + oparg & GET_AWAITABLE_WHERE_MASK); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(iterable); + _PyFrame_StackPointerInvalidate(frame); + if (iter_o == NULL) { + JUMP_TO_LABEL(error); + } + iter = PyStackRef_FromPyObjectSteal(iter_o); + null = PyStackRef_NULL; + none = PyStackRef_None; } - iter = PyStackRef_FromPyObjectSteal(iter_o); - null = PyStackRef_NULL; - none = PyStackRef_None; stack_pointer[0] = iter; stack_pointer[1] = null; stack_pointer[2] = none; @@ -7200,6 +8086,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL) { + MAYBE_START_LAZY_CORO(new_frame); + } frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); } @@ -7367,6 +8256,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 2u == 1 + INLINE_CACHE_ENTRIES_CALL_FUNCTION_EX); frame->return_offset = 2u ; DISPATCH_INLINED(new_frame); @@ -7519,6 +8411,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL_KW) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 4u == 1 + INLINE_CACHE_ENTRIES_CALL_KW); frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); @@ -8295,6 +9190,9 @@ _PyStackRef val; _PyStackRef value; _PyStackRef retval; + // _CHECK_LAZY_CORO + { + } // _YIELD_VALUE_EVENT { val = stack_pointer[-1]; @@ -8328,7 +9226,6 @@ retval = value; assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); frame->instr_ptr++; - PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); assert(FRAME_SUSPENDED_YIELD_FROM == FRAME_SUSPENDED + 1); assert(oparg == 0 || oparg == 1); _PyStackRef temp = retval; @@ -8337,29 +9234,41 @@ _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); DTRACE_FUNCTION_RETURN(); - tstate->exc_info = gen->gi_exc_state.previous_item; - gen->gi_exc_state.previous_item = NULL; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *gen_frame = frame; - _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); - frame = tstate->current_frame = frame->previous; - gen_frame->previous = NULL; - ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; - FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + int offset = 1 + INLINE_CACHE_ENTRIES_SEND; + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { + assert(oparg == 1); + frame = _PyEval_SuspendLazyCoro(tstate, frame); + offset = 0; + } + else { + PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); + tstate->exc_info = gen->gi_exc_state.previous_item; + gen->gi_exc_state.previous_item = NULL; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *gen_frame = frame; + _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); + frame = tstate->current_frame = frame->previous; + gen_frame->previous = NULL; + ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; + FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + } assert(INLINE_CACHE_ENTRIES_SEND == INLINE_CACHE_ENTRIES_FOR_ITER); #if TIER_ONE && defined(Py_DEBUG) if (!PyStackRef_IsNone(frame->f_executable)) { Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(opcode == SEND || opcode == FOR_ITER); + assert(offset == 0 ? opcode == GET_AWAITABLE + : (opcode == SEND || opcode == FOR_ITER)); } #endif stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - LOAD_IP(1 + INLINE_CACHE_ENTRIES_SEND); + LOAD_IP(offset); value = temp; - LLTRACE_RESUME_FRAME(); + if (offset != 0) { + LLTRACE_RESUME_FRAME(); + } } stack_pointer[0] = value; stack_pointer += 1; @@ -11454,32 +12363,72 @@ _PyStackRef res; assert(PyStackRef_FunctionCheck(frame->f_funcobj)); PyFunctionObject *func = (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(frame->f_funcobj); - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); - _PyFrame_StackPointerInvalidate(frame); - if (gen == NULL) { - JUMP_TO_LABEL(error); + _PyErr_StackItem *exc_info = NULL; + #if TIER_ONE + if (frame->lazy_coro == LAZY_CORO_REQUESTED) { + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + exc_info = (_PyErr_StackItem *)_PyThreadState_PushFrame( + tstate, sizeof(_PyErr_StackItem) / sizeof(PyObject *)); + _PyFrame_StackPointerInvalidate(frame); + if (exc_info == NULL) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyErr_Clear(tstate); + _PyFrame_StackPointerInvalidate(frame); + } + } + #endif + if (exc_info != NULL) { + exc_info->exc_value = NULL; + exc_info->previous_item = tstate->exc_info; + tstate->exc_info = exc_info; + frame->owner = FRAME_OWNED_BY_LAZY_CORO; + _PyInterpreterFrame *caller = frame->previous; + caller->instr_ptr += caller->return_offset; + caller->return_offset = 0; + _Py_CODEUNIT *send = caller->instr_ptr + 1; + if (send->op.code == INSTRUMENTED_LINE && !tstate->tracing) { + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + int err = _Py_call_instrumentation_line( + tstate, caller, send, caller->instr_ptr) < 0; + _PyFrame_StackPointerInvalidate(frame); + if (err) { + JUMP_TO_LABEL(error); + } + } + res = PyStackRef_None; + } + else { + frame->lazy_coro = 0; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); + _PyFrame_StackPointerInvalidate(frame); + if (gen == NULL) { + JUMP_TO_LABEL(error); + } + assert(STACK_LEVEL() <= 2); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *gen_frame = &gen->gi_iframe; + frame->instr_ptr++; + _PyFrame_Copy(frame, gen_frame); + assert(frame->frame_obj == NULL); + gen->gi_frame_state = FRAME_CREATED; + gen_frame->owner = FRAME_OWNED_BY_GENERATOR; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *prev = frame->previous; + _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); + _PyThreadState_PopFrame(tstate, frame); + frame = tstate->current_frame = prev; + LOAD_IP(frame->return_offset); + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + LLTRACE_RESUME_FRAME(); } - assert(STACK_LEVEL() <= 2); - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - _PyInterpreterFrame *gen_frame = &gen->gi_iframe; - frame->instr_ptr++; - _PyFrame_Copy(frame, gen_frame); - assert(frame->frame_obj == NULL); - gen->gi_frame_state = FRAME_CREATED; - gen_frame->owner = FRAME_OWNED_BY_GENERATOR; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *prev = frame->previous; - _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); - _PyThreadState_PopFrame(tstate, frame); - frame = tstate->current_frame = prev; - LOAD_IP(frame->return_offset); - stack_pointer = _PyFrame_GetStackPointer(frame); - _PyFrame_StackPointerInvalidate(frame); - res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); - LLTRACE_RESUME_FRAME(); stack_pointer[0] = res; stack_pointer += 1; ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); @@ -13586,6 +14535,9 @@ opcode = YIELD_VALUE; _PyStackRef value; _PyStackRef retval; + // _CHECK_LAZY_CORO + { + } // _MAKE_HEAP_SAFE { value = stack_pointer[-1]; @@ -13596,7 +14548,6 @@ retval = value; assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); frame->instr_ptr++; - PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); assert(FRAME_SUSPENDED_YIELD_FROM == FRAME_SUSPENDED + 1); assert(oparg == 0 || oparg == 1); _PyStackRef temp = retval; @@ -13605,29 +14556,41 @@ _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); DTRACE_FUNCTION_RETURN(); - tstate->exc_info = gen->gi_exc_state.previous_item; - gen->gi_exc_state.previous_item = NULL; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *gen_frame = frame; - _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); - frame = tstate->current_frame = frame->previous; - gen_frame->previous = NULL; - ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; - FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + int offset = 1 + INLINE_CACHE_ENTRIES_SEND; + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { + assert(oparg == 1); + frame = _PyEval_SuspendLazyCoro(tstate, frame); + offset = 0; + } + else { + PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); + tstate->exc_info = gen->gi_exc_state.previous_item; + gen->gi_exc_state.previous_item = NULL; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *gen_frame = frame; + _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); + frame = tstate->current_frame = frame->previous; + gen_frame->previous = NULL; + ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; + FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + } assert(INLINE_CACHE_ENTRIES_SEND == INLINE_CACHE_ENTRIES_FOR_ITER); #if TIER_ONE && defined(Py_DEBUG) if (!PyStackRef_IsNone(frame->f_executable)) { Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(opcode == SEND || opcode == FOR_ITER); + assert(offset == 0 ? opcode == GET_AWAITABLE + : (opcode == SEND || opcode == FOR_ITER)); } #endif stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - LOAD_IP(1 + INLINE_CACHE_ENTRIES_SEND); + LOAD_IP(offset); value = temp; - LLTRACE_RESUME_FRAME(); + if (offset != 0) { + LLTRACE_RESUME_FRAME(); + } } stack_pointer[0] = value; stack_pointer += 1; diff --git a/Modules/_testinternalcapi/test_targets.h b/Modules/_testinternalcapi/test_targets.h index 91b424773224e4..8fd141bfb7ba18 100644 --- a/Modules/_testinternalcapi/test_targets.h +++ b/Modules/_testinternalcapi/test_targets.h @@ -146,7 +146,9 @@ static void *opcode_targets_table[256] = { &&TARGET_BINARY_OP_SUBTRACT_INT, &&TARGET_CALL_ALLOC_AND_ENTER_INIT, &&TARGET_CALL_BOUND_METHOD_EXACT_ARGS, + &&TARGET_CALL_BOUND_METHOD_EXACT_ARGS_AWAITED, &&TARGET_CALL_BOUND_METHOD_GENERAL, + &&TARGET_CALL_BOUND_METHOD_GENERAL_AWAITED, &&TARGET_CALL_BUILTIN_CLASS, &&TARGET_CALL_BUILTIN_FAST, &&TARGET_CALL_BUILTIN_FAST_WITH_KEYWORDS, @@ -155,8 +157,10 @@ static void *opcode_targets_table[256] = { &&TARGET_CALL_EX_PY, &&TARGET_CALL_ISINSTANCE, &&TARGET_CALL_KW_BOUND_METHOD, + &&TARGET_CALL_KW_BOUND_METHOD_AWAITED, &&TARGET_CALL_KW_NON_PY, &&TARGET_CALL_KW_PY, + &&TARGET_CALL_KW_PY_AWAITED, &&TARGET_CALL_LEN, &&TARGET_CALL_LIST_APPEND, &&TARGET_CALL_METHOD_DESCRIPTOR_FAST, @@ -165,7 +169,9 @@ static void *opcode_targets_table[256] = { &&TARGET_CALL_METHOD_DESCRIPTOR_O, &&TARGET_CALL_NON_PY_GENERAL, &&TARGET_CALL_PY_EXACT_ARGS, + &&TARGET_CALL_PY_EXACT_ARGS_AWAITED, &&TARGET_CALL_PY_GENERAL, + &&TARGET_CALL_PY_GENERAL_AWAITED, &&TARGET_CALL_STR_1, &&TARGET_CALL_TUPLE_1, &&TARGET_CALL_TYPE_1, @@ -227,12 +233,6 @@ static void *opcode_targets_table[256] = { &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, &&TARGET_INSTRUMENTED_END_FOR, &&TARGET_INSTRUMENTED_POP_ITER, &&TARGET_INSTRUMENTED_END_SEND, @@ -478,12 +478,12 @@ static void *opcode_tracing_targets_table[256] = { &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, @@ -561,7 +561,9 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CACHE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_ALLOC_AND_ENTER_INIT(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_GENERAL(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_GENERAL_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BUILTIN_CLASS(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BUILTIN_FAST(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BUILTIN_FAST_WITH_KEYWORDS(TAIL_CALL_PARAMS); @@ -574,8 +576,10 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_INTRINSIC_2(TAIL_CALL_PARAM static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_ISINSTANCE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_BOUND_METHOD(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_BOUND_METHOD_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_NON_PY(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_PY(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_PY_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_LEN(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_LIST_APPEND(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_METHOD_DESCRIPTOR_FAST(TAIL_CALL_PARAMS); @@ -584,7 +588,9 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_METHOD_DESCRIPTOR_NOARGS(TA static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_METHOD_DESCRIPTOR_O(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_NON_PY_GENERAL(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_EXACT_ARGS(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_EXACT_ARGS_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_GENERAL(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_GENERAL_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_STR_1(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_TUPLE_1(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_TYPE_1(TAIL_CALL_PARAMS); @@ -804,7 +810,9 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [CALL] = _TAIL_CALL_CALL, [CALL_ALLOC_AND_ENTER_INIT] = _TAIL_CALL_CALL_ALLOC_AND_ENTER_INIT, [CALL_BOUND_METHOD_EXACT_ARGS] = _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS_AWAITED, [CALL_BOUND_METHOD_GENERAL] = _TAIL_CALL_CALL_BOUND_METHOD_GENERAL, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = _TAIL_CALL_CALL_BOUND_METHOD_GENERAL_AWAITED, [CALL_BUILTIN_CLASS] = _TAIL_CALL_CALL_BUILTIN_CLASS, [CALL_BUILTIN_FAST] = _TAIL_CALL_CALL_BUILTIN_FAST, [CALL_BUILTIN_FAST_WITH_KEYWORDS] = _TAIL_CALL_CALL_BUILTIN_FAST_WITH_KEYWORDS, @@ -817,8 +825,10 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [CALL_ISINSTANCE] = _TAIL_CALL_CALL_ISINSTANCE, [CALL_KW] = _TAIL_CALL_CALL_KW, [CALL_KW_BOUND_METHOD] = _TAIL_CALL_CALL_KW_BOUND_METHOD, + [CALL_KW_BOUND_METHOD_AWAITED] = _TAIL_CALL_CALL_KW_BOUND_METHOD_AWAITED, [CALL_KW_NON_PY] = _TAIL_CALL_CALL_KW_NON_PY, [CALL_KW_PY] = _TAIL_CALL_CALL_KW_PY, + [CALL_KW_PY_AWAITED] = _TAIL_CALL_CALL_KW_PY_AWAITED, [CALL_LEN] = _TAIL_CALL_CALL_LEN, [CALL_LIST_APPEND] = _TAIL_CALL_CALL_LIST_APPEND, [CALL_METHOD_DESCRIPTOR_FAST] = _TAIL_CALL_CALL_METHOD_DESCRIPTOR_FAST, @@ -827,7 +837,9 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [CALL_METHOD_DESCRIPTOR_O] = _TAIL_CALL_CALL_METHOD_DESCRIPTOR_O, [CALL_NON_PY_GENERAL] = _TAIL_CALL_CALL_NON_PY_GENERAL, [CALL_PY_EXACT_ARGS] = _TAIL_CALL_CALL_PY_EXACT_ARGS, + [CALL_PY_EXACT_ARGS_AWAITED] = _TAIL_CALL_CALL_PY_EXACT_ARGS_AWAITED, [CALL_PY_GENERAL] = _TAIL_CALL_CALL_PY_GENERAL, + [CALL_PY_GENERAL_AWAITED] = _TAIL_CALL_CALL_PY_GENERAL_AWAITED, [CALL_STR_1] = _TAIL_CALL_CALL_STR_1, [CALL_TUPLE_1] = _TAIL_CALL_CALL_TUPLE_1, [CALL_TYPE_1] = _TAIL_CALL_CALL_TYPE_1, @@ -1016,12 +1028,6 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [125] = _TAIL_CALL_UNKNOWN_OPCODE, [126] = _TAIL_CALL_UNKNOWN_OPCODE, [127] = _TAIL_CALL_UNKNOWN_OPCODE, - [219] = _TAIL_CALL_UNKNOWN_OPCODE, - [220] = _TAIL_CALL_UNKNOWN_OPCODE, - [221] = _TAIL_CALL_UNKNOWN_OPCODE, - [222] = _TAIL_CALL_UNKNOWN_OPCODE, - [223] = _TAIL_CALL_UNKNOWN_OPCODE, - [224] = _TAIL_CALL_UNKNOWN_OPCODE, [225] = _TAIL_CALL_UNKNOWN_OPCODE, [226] = _TAIL_CALL_UNKNOWN_OPCODE, [227] = _TAIL_CALL_UNKNOWN_OPCODE, @@ -1062,7 +1068,9 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [CALL] = _TAIL_CALL_TRACE_RECORD, [CALL_ALLOC_AND_ENTER_INIT] = _TAIL_CALL_TRACE_RECORD, [CALL_BOUND_METHOD_EXACT_ARGS] = _TAIL_CALL_TRACE_RECORD, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_BOUND_METHOD_GENERAL] = _TAIL_CALL_TRACE_RECORD, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_BUILTIN_CLASS] = _TAIL_CALL_TRACE_RECORD, [CALL_BUILTIN_FAST] = _TAIL_CALL_TRACE_RECORD, [CALL_BUILTIN_FAST_WITH_KEYWORDS] = _TAIL_CALL_TRACE_RECORD, @@ -1075,8 +1083,10 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [CALL_ISINSTANCE] = _TAIL_CALL_TRACE_RECORD, [CALL_KW] = _TAIL_CALL_TRACE_RECORD, [CALL_KW_BOUND_METHOD] = _TAIL_CALL_TRACE_RECORD, + [CALL_KW_BOUND_METHOD_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_KW_NON_PY] = _TAIL_CALL_TRACE_RECORD, [CALL_KW_PY] = _TAIL_CALL_TRACE_RECORD, + [CALL_KW_PY_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_LEN] = _TAIL_CALL_TRACE_RECORD, [CALL_LIST_APPEND] = _TAIL_CALL_TRACE_RECORD, [CALL_METHOD_DESCRIPTOR_FAST] = _TAIL_CALL_TRACE_RECORD, @@ -1085,7 +1095,9 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [CALL_METHOD_DESCRIPTOR_O] = _TAIL_CALL_TRACE_RECORD, [CALL_NON_PY_GENERAL] = _TAIL_CALL_TRACE_RECORD, [CALL_PY_EXACT_ARGS] = _TAIL_CALL_TRACE_RECORD, + [CALL_PY_EXACT_ARGS_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_PY_GENERAL] = _TAIL_CALL_TRACE_RECORD, + [CALL_PY_GENERAL_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_STR_1] = _TAIL_CALL_TRACE_RECORD, [CALL_TUPLE_1] = _TAIL_CALL_TRACE_RECORD, [CALL_TYPE_1] = _TAIL_CALL_TRACE_RECORD, @@ -1274,12 +1286,6 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [125] = _TAIL_CALL_UNKNOWN_OPCODE, [126] = _TAIL_CALL_UNKNOWN_OPCODE, [127] = _TAIL_CALL_UNKNOWN_OPCODE, - [219] = _TAIL_CALL_UNKNOWN_OPCODE, - [220] = _TAIL_CALL_UNKNOWN_OPCODE, - [221] = _TAIL_CALL_UNKNOWN_OPCODE, - [222] = _TAIL_CALL_UNKNOWN_OPCODE, - [223] = _TAIL_CALL_UNKNOWN_OPCODE, - [224] = _TAIL_CALL_UNKNOWN_OPCODE, [225] = _TAIL_CALL_UNKNOWN_OPCODE, [226] = _TAIL_CALL_UNKNOWN_OPCODE, [227] = _TAIL_CALL_UNKNOWN_OPCODE, diff --git a/Objects/frameobject.c b/Objects/frameobject.c index 475be76dc3da21..8b5d9d218e0c40 100644 --- a/Objects/frameobject.c +++ b/Objects/frameobject.c @@ -13,6 +13,7 @@ #include "pycore_modsupport.h" // _PyArg_CheckPositional() #include "pycore_object.h" // _PyObject_GC_UNTRACK() #include "pycore_opcode_metadata.h" // _PyOpcode_Caches +#include "pycore_opcode_utils.h" // GET_AWAITABLE_AWAITED_CALL #include "pycore_optimizer.h" // _Py_Executors_InvalidateDependency() #include "pycore_tuple.h" // _PyTuple_FromPair #include "pycore_unicodeobject.h" // _PyUnicode_Equal() @@ -1453,6 +1454,29 @@ mark_stacks(PyCodeObject *code_obj, int len) stacks[j] = next_stack; stacks[next_i] = next_stack; break; + case GET_AWAITABLE: + { + /* (lazy_outcome, res) after an awaited call, else (res); + * pushes (iter, NULL, None). After an awaited call it may + * also jump to YIELD_VALUE with (coroutine, NULL, res), + * as left by SEND. */ + int awaited_call = oparg & GET_AWAITABLE_AWAITED_CALL; + next_stack = pop_value(next_stack); + if (awaited_call) { + next_stack = pop_value(next_stack); + } + next_stack = push_value(next_stack, Object); + next_stack = push_value(next_stack, Object); + next_stack = push_value(next_stack, Object); + if (awaited_call) { + j = next_i + 1 + INLINE_CACHE_ENTRIES_SEND; + assert(j < len); + assert(stacks[j] == UNINITIALIZED || stacks[j] == next_stack); + stacks[j] = next_stack; + } + stacks[next_i] = next_stack; + break; + } case JUMP_FORWARD: j = oparg + i + 1; assert(j < len); @@ -1673,7 +1697,16 @@ marklines(PyCodeObject *code, int len) while (_PyLineTable_NextAddressRange(&bounds)) { assert(bounds.ar_start / (int)sizeof(_Py_CODEUNIT) < len); if (bounds.ar_line != last_line && bounds.ar_line != -1) { - linestarts[bounds.ar_start / sizeof(_Py_CODEUNIT)] = bounds.ar_line; + int i = bounds.ar_start / (int)sizeof(_Py_CODEUNIT); + _Py_CODEUNIT inst = _Py_GetBaseCodeUnit(code, i); + if (inst.op.code == GET_AWAITABLE && + (inst.op.arg & GET_AWAITABLE_AWAITED_CALL)) + { + /* Its lazy outcome slot must hold NULL or an outcome, + * so jump to the SEND that follows it instead. */ + i++; + } + linestarts[i] = bounds.ar_line; last_line = bounds.ar_line; } } @@ -1787,6 +1820,20 @@ frame_lineno_set_impl(PyFrameObject *self, PyObject *value) return -1; } + if (!is_suspended) { + _Py_CODEUNIT inst = _Py_GetBaseCodeUnit( + code, _PyInterpreterFrame_LASTI(self->f_frame)); + if (inst.op.code == GET_AWAITABLE && + (inst.op.arg & GET_AWAITABLE_AWAITED_CALL)) + { + /* The LINE event of an await, emitted before a lazily run + * body starts, when the stack is not as at a line start. */ + PyErr_SetString(PyExc_ValueError, + "can't jump from the await of a lazily run coroutine"); + return -1; + } + } + int new_lineno; /* Fail if the line falls outside the code block and @@ -2091,7 +2138,9 @@ frame_clear_impl(PyFrameObject *self) return NULL; } } - else if (self->f_frame->owner == FRAME_OWNED_BY_THREAD) { + else if (self->f_frame->owner == FRAME_OWNED_BY_THREAD || + self->f_frame->owner == FRAME_OWNED_BY_LAZY_CORO) + { PyErr_SetString(PyExc_RuntimeError, "cannot clear an executing frame"); return NULL; diff --git a/Objects/genobject.c b/Objects/genobject.c index 82a1bb1ff42068..4e9ef3cd640158 100644 --- a/Objects/genobject.c +++ b/Objects/genobject.c @@ -1104,9 +1104,8 @@ PyTypeObject PyGen_Type = { }; static PyObject * -make_gen(PyTypeObject *type, PyFunctionObject *func) +make_gen(PyTypeObject *type, PyFunctionObject *func, PyCodeObject *code) { - PyCodeObject *code = (PyCodeObject *)func->func_code; int slots = _PyFrame_NumSlotsForCodeObject(code); PyGenObject *gen = PyObject_GC_NewVar(PyGenObject, type, slots); if (gen == NULL) { @@ -1127,18 +1126,44 @@ make_gen(PyTypeObject *type, PyFunctionObject *func) return (PyObject *)gen; } +static PyObject * +make_coro(PyFunctionObject *func, PyCodeObject *code, + _PyInterpreterFrame *caller) +{ + PyObject *coro = make_gen(&PyCoro_Type, func, code); + if (!coro) { + return NULL; + } + PyThreadState *tstate = _PyThreadState_GET(); + int origin_depth = tstate->coroutine_origin_tracking_depth; + + if (origin_depth == 0) { + ((PyCoroObject *)coro)->cr_origin_or_finalizer = NULL; + } else { + _PyInterpreterFrame *frame = _PyFrame_GetFirstComplete(caller); + PyObject *cr_origin = _PyCoro_ComputeOrigin(origin_depth, frame); + ((PyCoroObject *)coro)->cr_origin_or_finalizer = cr_origin; + if (!cr_origin) { + Py_DECREF(coro); + return NULL; + } + } + return coro; +} + PyObject * _Py_MakeCoro(PyFunctionObject *func) { - int coro_flags = ((PyCodeObject *)func->func_code)->co_flags & + PyCodeObject *code = (PyCodeObject *)func->func_code; + int coro_flags = code->co_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR); assert(coro_flags); if (coro_flags == CO_GENERATOR) { - return make_gen(&PyGen_Type, func); + return make_gen(&PyGen_Type, func, code); } if (coro_flags == CO_ASYNC_GENERATOR) { PyAsyncGenObject *ag; - ag = (PyAsyncGenObject *)make_gen(&PyAsyncGen_Type, func); + ag = (PyAsyncGenObject *)make_gen(&PyAsyncGen_Type, func, code); if (ag == NULL) { return NULL; } @@ -1150,26 +1175,29 @@ _Py_MakeCoro(PyFunctionObject *func) } assert (coro_flags == CO_COROUTINE); - PyObject *coro = make_gen(&PyCoro_Type, func); - if (!coro) { - return NULL; - } PyThreadState *tstate = _PyThreadState_GET(); - int origin_depth = tstate->coroutine_origin_tracking_depth; + _PyInterpreterFrame *frame = tstate->current_frame; + assert(frame); + assert(_PyFrame_IsIncomplete(frame)); + return make_coro(func, code, frame->previous); +} - if (origin_depth == 0) { +/* The body may have replaced func.__code__, so size the coroutine for the + * code the frame is running. The caller moves the frame into it. */ +PyObject * +_PyCoro_MaterializeLazy(_PyInterpreterFrame *frame) +{ + assert(frame->owner == FRAME_OWNED_BY_LAZY_CORO); + assert(PyStackRef_FunctionCheck(frame->f_funcobj)); + PyFunctionObject *func = + (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(frame->f_funcobj); + PyCodeObject *code = _PyFrame_GetCode(frame); + assert((code->co_flags & + (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) == CO_COROUTINE); + PyObject *coro = make_gen(&PyCoro_Type, func, code); + if (coro != NULL) { + // Origin tracking was off at the call (see MAYBE_START_LAZY_CORO). ((PyCoroObject *)coro)->cr_origin_or_finalizer = NULL; - } else { - _PyInterpreterFrame *frame = tstate->current_frame; - assert(frame); - assert(_PyFrame_IsIncomplete(frame)); - frame = _PyFrame_GetFirstComplete(frame->previous); - PyObject *cr_origin = _PyCoro_ComputeOrigin(origin_depth, frame); - ((PyCoroObject *)coro)->cr_origin_or_finalizer = cr_origin; - if (!cr_origin) { - Py_DECREF(coro); - return NULL; - } } return coro; } diff --git a/Python/bytecodes.c b/Python/bytecodes.c index c6f1f61f3e08fe..0994d9ee5328ab 100644 --- a/Python/bytecodes.c +++ b/Python/bytecodes.c @@ -1651,8 +1651,9 @@ dummy_func( none = PyStackRef_None; } - inst(GET_AWAITABLE, (iterable -- iter, null, none)) { - PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), oparg); + op(_GET_AWAITABLE, (iterable -- iter, null, none)) { + PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), + oparg & GET_AWAITABLE_WHERE_MASK); PyStackRef_CLOSE(iterable); ERROR_IF(iter_o == NULL); iter = PyStackRef_FromPyObjectSteal(iter_o); @@ -1660,6 +1661,73 @@ dummy_func( none = PyStackRef_None; } + // After an awaited call, the SEND loop starts right after + // GET_AWAITABLE: SEND is at next_instr and YIELD_VALUE follows its cache. + replaced op(_LAZY_CALL_OUTCOME, (lazy_outcome[(oparg >> 2) & 1], res -- lazy_outcome[(oparg >> 2) & 1], res)) { + if (oparg & GET_AWAITABLE_AWAITED_CALL) { + // The slot is at a fixed offset here: reading it through + // lazy_outcome would make the load wait for oparg. + _PyStackRef *slot = &stack_pointer[-2]; + assert(slot == lazy_outcome); + (void)lazy_outcome; + _PyStackRef outcome = *slot; + if (PyStackRef_IsTaggedInt(outcome)) { + *slot = PyStackRef_NULL; + assert(_Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), + (int)(next_instr - _PyFrame_GetBytecode(frame))).op.code == SEND); + _Py_CODEUNIT *end_send = next_instr + 1 + INLINE_CACHE_ENTRIES_SEND + next_instr->op.arg; + if (end_send->op.code != END_SEND) { + // Emulate the monitoring event of INSTRUMENTED_END_SEND. + int err = monitor_stop_iteration(tstate, frame, end_send, + PyStackRef_AsPyObjectBorrow(res)); + ERROR_IF(err); + } + _PyStackRef v = res; + DEAD(res); + stack_pointer[-2] = v; + stack_pointer -= 1; + next_instr = end_send + 1; + DISPATCH(); + } + else if (!PyStackRef_IsNull(outcome)) { + _PyInterpreterFrame *lazy_frame = PyStackRef_Unwrap(outcome); + *slot = PyStackRef_NULL; + PyGenObject *gen = _PyEval_MaterializeLazyCoro(tstate, lazy_frame); + _PyStackRef v = res; + DEAD(res); + if (gen == NULL) { + stack_pointer[-1] = PyStackRef_NULL; + frame = _PyEval_ThrowIntoLazyCoro(tstate, lazy_frame, v); + next_instr = frame->instr_ptr; + LOAD_SP(); + goto error; + } + stack_pointer[-2] = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + stack_pointer[-1] = PyStackRef_NULL; + stack_pointer[0] = v; + stack_pointer += 1; + next_instr += 1 + INLINE_CACHE_ENTRIES_SEND; + DISPATCH(); + } + } + } + + tier2 op(_GUARD_LAZY_OUTCOME_NULL, (lazy_outcome[(oparg >> 2) & 1], unused -- lazy_outcome[(oparg >> 2) & 1], unused)) { + EXIT_IF((oparg & GET_AWAITABLE_AWAITED_CALL) && + !PyStackRef_IsNull(lazy_outcome[0])); + } + + op(_POP_LAZY_OUTCOME, (lazy_outcome[(oparg >> 2) & 1], res -- value)) { + assert(!(oparg & GET_AWAITABLE_AWAITED_CALL) || + PyStackRef_IsNull(lazy_outcome[0])); + (void)lazy_outcome; + DEAD(lazy_outcome); + value = res; + DEAD(res); + } + + macro(GET_AWAITABLE) = _LAZY_CALL_OUTCOME + _POP_LAZY_OUTCOME + _GET_AWAITABLE; + family(SEND, INLINE_CACHE_ENTRIES_SEND) = { SEND_GEN, SEND_VIRTUAL, @@ -1853,28 +1921,45 @@ dummy_func( EXIT_IF(what == PYGEN_RETURN); } + replaced op(_CHECK_LAZY_CORO, (--)) { + } + + tier2 op(_GUARD_NOT_LAZY_CORO, (--)) { + EXIT_IF(frame->owner == FRAME_OWNED_BY_LAZY_CORO); + } + op(_YIELD_VALUE, (retval -- value)) { // NOTE: It's important that YIELD_VALUE never raises an exception! // The compiler treats any exception raised here as a failed close() // or throw() call. assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); frame->instr_ptr++; - PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); assert(FRAME_SUSPENDED_YIELD_FROM == FRAME_SUSPENDED + 1); assert(oparg == 0 || oparg == 1); _PyStackRef temp = retval; DEAD(retval); SAVE_STACK(); DTRACE_FUNCTION_RETURN(); - tstate->exc_info = gen->gi_exc_state.previous_item; - gen->gi_exc_state.previous_item = NULL; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *gen_frame = frame; - _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); - frame = tstate->current_frame = frame->previous; - gen_frame->previous = NULL; - ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; - FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + int offset = 1 + INLINE_CACHE_ENTRIES_SEND; + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { + // The caller's GET_AWAITABLE creates the coroutine. It is + // never instrumented, so nothing runs in between. + assert(oparg == 1); + frame = _PyEval_SuspendLazyCoro(tstate, frame); + offset = 0; + } + else { + PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); + tstate->exc_info = gen->gi_exc_state.previous_item; + gen->gi_exc_state.previous_item = NULL; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *gen_frame = frame; + _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); + frame = tstate->current_frame = frame->previous; + gen_frame->previous = NULL; + ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; + FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + } /* We don't know which of these is relevant here, so keep them equal */ assert(INLINE_CACHE_ENTRIES_SEND == INLINE_CACHE_ENTRIES_FOR_ITER); #if TIER_ONE && defined(Py_DEBUG) @@ -1882,16 +1967,22 @@ dummy_func( Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(opcode == SEND || opcode == FOR_ITER); + assert(offset == 0 ? opcode == GET_AWAITABLE + : (opcode == SEND || opcode == FOR_ITER)); } #endif RELOAD_STACK(); - LOAD_IP(1 + INLINE_CACHE_ENTRIES_SEND); + LOAD_IP(offset); value = temp; - LLTRACE_RESUME_FRAME(); + // After a lazy suspension, the caller's lazy outcome slot holds a + // frame pointer, which nothing may see before GET_AWAITABLE runs. + if (offset != 0) { + LLTRACE_RESUME_FRAME(); + } } macro(YIELD_VALUE) = + _CHECK_LAZY_CORO + _MAKE_HEAP_SAFE + _YIELD_VALUE; @@ -1911,6 +2002,7 @@ dummy_func( } macro(INSTRUMENTED_YIELD_VALUE) = + _CHECK_LAZY_CORO + _YIELD_VALUE_EVENT + _MAKE_HEAP_SAFE + _YIELD_VALUE; @@ -1967,7 +2059,8 @@ dummy_func( tier1 inst(CLEANUP_THROW, (sub_iter, null_in, last_sent_val, exc_value_st -- none, null_out, value)) { PyObject *exc_value = PyStackRef_AsPyObjectBorrow(exc_value_st); #if !_Py_TAIL_CALL_INTERP - assert(throwflag); + // _PyEval_ThrowIntoLazyCoro() raises in a lazily run body. + assert(throwflag || frame->owner == FRAME_OWNED_BY_LAZY_CORO); #endif assert(exc_value && PyExceptionInstance_Check(exc_value)); int matches = PyErr_GivenExceptionMatches(exc_value, PyExc_StopIteration); @@ -4318,6 +4411,10 @@ dummy_func( CALL_PY_GENERAL, CALL_BOUND_METHOD_GENERAL, CALL_NON_PY_GENERAL, + CALL_PY_EXACT_ARGS_AWAITED, + CALL_BOUND_METHOD_EXACT_ARGS_AWAITED, + CALL_PY_GENERAL_AWAITED, + CALL_BOUND_METHOD_GENERAL_AWAITED, }; specializing op(_SPECIALIZE_CALL, (counter/1, callable, self_or_null, unused[oparg] -- callable, self_or_null, unused[oparg])) { @@ -4376,6 +4473,9 @@ dummy_func( if (new_frame == NULL) { ERROR_NO_POP(); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL) { + MAYBE_START_LAZY_CORO(new_frame); + } frame->return_offset = INSTRUCTION_SIZE; DISPATCH_INLINED(new_frame); } @@ -4467,6 +4567,17 @@ dummy_func( _SAVE_RETURN_OFFSET + _PUSH_FRAME; + macro(CALL_PY_GENERAL_AWAITED) = + _RECORD_CALLABLE + + unused/1 + + _CHECK_PEP_523 + + _CHECK_FUNCTION_VERSION + + _CHECK_RECURSION_REMAINING + + _PY_FRAME_GENERAL + + _START_LAZY_CORO + + _SAVE_RETURN_OFFSET + + _PUSH_FRAME; + op(_CHECK_METHOD_VERSION, (func_version/2, callable, null, unused[oparg] -- callable, null, unused[oparg])) { PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); @@ -4500,6 +4611,19 @@ dummy_func( _SAVE_RETURN_OFFSET + _PUSH_FRAME; + macro(CALL_BOUND_METHOD_GENERAL_AWAITED) = + _RECORD_BOUND_METHOD + + unused/1 + + _CHECK_PEP_523 + + _CHECK_METHOD_VERSION + + _EXPAND_METHOD + + flush + + _CHECK_RECURSION_REMAINING + + _PY_FRAME_GENERAL + + _START_LAZY_CORO + + _SAVE_RETURN_OFFSET + + _PUSH_FRAME; + op(_CHECK_IS_NOT_PY_CALLABLE, (callable, unused, unused[oparg] -- callable, unused, unused[oparg])) { PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); EXIT_IF(PyFunction_Check(callable_o)); @@ -4620,6 +4744,26 @@ dummy_func( _SAVE_RETURN_OFFSET + _PUSH_FRAME; + macro(CALL_BOUND_METHOD_EXACT_ARGS_AWAITED) = + _RECORD_BOUND_METHOD + + unused/1 + + _CHECK_PEP_523 + + _CHECK_CALL_BOUND_METHOD_EXACT_ARGS + + _INIT_CALL_BOUND_METHOD_EXACT_ARGS + + flush + + _CHECK_FUNCTION_VERSION + + _CHECK_FUNCTION_EXACT_ARGS + + _CHECK_STACK_SPACE + + _CHECK_RECURSION_REMAINING + + _INIT_CALL_PY_EXACT_ARGS + + _START_LAZY_CORO + + _SAVE_RETURN_OFFSET + + _PUSH_FRAME; + + replaced op(_START_LAZY_CORO, (new_frame -- new_frame)) { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + macro(CALL_PY_EXACT_ARGS) = _RECORD_CALLABLE + unused/1 + // Skip over the counter @@ -4632,6 +4776,19 @@ dummy_func( _SAVE_RETURN_OFFSET + _PUSH_FRAME; + macro(CALL_PY_EXACT_ARGS_AWAITED) = + _RECORD_CALLABLE + + unused/1 + + _CHECK_PEP_523 + + _CHECK_FUNCTION_VERSION + + _CHECK_FUNCTION_EXACT_ARGS + + _CHECK_STACK_SPACE + + _CHECK_RECURSION_REMAINING + + _INIT_CALL_PY_EXACT_ARGS + + _START_LAZY_CORO + + _SAVE_RETURN_OFFSET + + _PUSH_FRAME; + op(_GUARD_NOS_NULL, (null, unused -- null, unused)) { EXIT_IF(!PyStackRef_IsNull(null)); } @@ -5354,6 +5511,8 @@ dummy_func( CALL_KW_BOUND_METHOD, CALL_KW_PY, CALL_KW_NON_PY, + CALL_KW_PY_AWAITED, + CALL_KW_BOUND_METHOD_AWAITED, }; op(_MONITOR_CALL_KW, (callable, self_or_null, args[oparg], unused -- callable, self_or_null, args[oparg], unused)) { @@ -5421,6 +5580,9 @@ dummy_func( if (new_frame == NULL) { ERROR_NO_POP(); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL_KW) { + MAYBE_START_LAZY_CORO(new_frame); + } assert(INSTRUCTION_SIZE == 1 + INLINE_CACHE_ENTRIES_CALL_KW); frame->return_offset = INSTRUCTION_SIZE; DISPATCH_INLINED(new_frame); @@ -5489,6 +5651,17 @@ dummy_func( _SAVE_RETURN_OFFSET + _PUSH_FRAME; + macro(CALL_KW_PY_AWAITED) = + _RECORD_CALLABLE_KW + + unused/1 + + _CHECK_PEP_523 + + _CHECK_FUNCTION_VERSION_KW + + _CHECK_RECURSION_REMAINING + + _PY_FRAME_KW + + _START_LAZY_CORO + + _SAVE_RETURN_OFFSET + + _PUSH_FRAME; + op(_CHECK_METHOD_VERSION_KW, (func_version/2, callable, null, unused[oparg], unused -- callable, null, unused[oparg], unused)) { PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); @@ -5521,6 +5694,18 @@ dummy_func( _SAVE_RETURN_OFFSET + _PUSH_FRAME; + macro(CALL_KW_BOUND_METHOD_AWAITED) = + _RECORD_CALLABLE_KW + + unused/1 + + _CHECK_PEP_523 + + _CHECK_METHOD_VERSION_KW + + _EXPAND_METHOD_KW + + flush + + _PY_FRAME_KW + + _START_LAZY_CORO + + _SAVE_RETURN_OFFSET + + _PUSH_FRAME; + specializing op(_SPECIALIZE_CALL_KW, (counter/1, callable, self_or_null, unused[oparg], unused -- callable, self_or_null, unused[oparg], unused)) { #if ENABLE_SPECIALIZATION if (ADAPTIVE_COUNTER_TRIGGERS(counter)) { @@ -5666,6 +5851,9 @@ dummy_func( if (new_frame == NULL) { ERROR_NO_POP(); } + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(new_frame); + } assert(INSTRUCTION_SIZE == 1 + INLINE_CACHE_ENTRIES_CALL_FUNCTION_EX); frame->return_offset = INSTRUCTION_SIZE; DISPATCH_INLINED(new_frame); @@ -5738,6 +5926,7 @@ dummy_func( _MAKE_CALLARGS_A_TUPLE + _CHECK_IS_PY_CALLABLE_EX + _PY_FRAME_EX + + _MAYBE_LAZY_CORO + _SAVE_RETURN_OFFSET + _PUSH_FRAME; @@ -5810,25 +5999,60 @@ dummy_func( inst(RETURN_GENERATOR, (-- res)) { assert(PyStackRef_FunctionCheck(frame->f_funcobj)); PyFunctionObject *func = (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(frame->f_funcobj); - PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); - ERROR_IF(gen == NULL); - assert(STACK_LEVEL() <= 2); - SAVE_STACK(); - _PyInterpreterFrame *gen_frame = &gen->gi_iframe; - frame->instr_ptr++; - _PyFrame_Copy(frame, gen_frame); - assert(frame->frame_obj == NULL); - gen->gi_frame_state = FRAME_CREATED; - gen_frame->owner = FRAME_OWNED_BY_GENERATOR; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *prev = frame->previous; - _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); - _PyThreadState_PopFrame(tstate, frame); - frame = tstate->current_frame = prev; - LOAD_IP(frame->return_offset); - RELOAD_STACK(); - res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); - LLTRACE_RESUME_FRAME(); + _PyErr_StackItem *exc_info = NULL; + #if TIER_ONE + if (frame->lazy_coro == LAZY_CORO_REQUESTED) { + /* The body's exception state, as SEND_GEN would push. */ + exc_info = (_PyErr_StackItem *)_PyThreadState_PushFrame( + tstate, sizeof(_PyErr_StackItem) / sizeof(PyObject *)); + if (exc_info == NULL) { + _PyErr_Clear(tstate); + } + } + #endif + if (exc_info != NULL) { + exc_info->exc_value = NULL; + exc_info->previous_item = tstate->exc_info; + tstate->exc_info = exc_info; + frame->owner = FRAME_OWNED_BY_LAZY_CORO; + /* While the body runs, the caller is at the await, as at + * SEND on the eager path. */ + _PyInterpreterFrame *caller = frame->previous; + caller->instr_ptr += caller->return_offset; + caller->return_offset = 0; + _Py_CODEUNIT *send = caller->instr_ptr + 1; + if (send->op.code == INSTRUMENTED_LINE && !tstate->tracing) { + /* The LINE event of the await, which the eager path + * emits at SEND before the body runs. */ + int err = _Py_call_instrumentation_line( + tstate, caller, send, caller->instr_ptr) < 0; + ERROR_IF(err); + } + /* The following POP_TOP discards this. */ + res = PyStackRef_None; + } + else { + frame->lazy_coro = 0; + PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); + ERROR_IF(gen == NULL); + assert(STACK_LEVEL() <= 2); + SAVE_STACK(); + _PyInterpreterFrame *gen_frame = &gen->gi_iframe; + frame->instr_ptr++; + _PyFrame_Copy(frame, gen_frame); + assert(frame->frame_obj == NULL); + gen->gi_frame_state = FRAME_CREATED; + gen_frame->owner = FRAME_OWNED_BY_GENERATOR; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *prev = frame->previous; + _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); + _PyThreadState_PopFrame(tstate, frame); + frame = tstate->current_frame = prev; + LOAD_IP(frame->return_offset); + RELOAD_STACK(); + res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + LLTRACE_RESUME_FRAME(); + } } inst(BUILD_SLICE, (args[oparg] -- slice)) { @@ -6105,6 +6329,12 @@ dummy_func( DEOPT_IF(!_PyThreadState_HasStackSpace(tstate, framesize)); } + replaced op(_MAYBE_LAZY_CORO, (new_frame -- new_frame)) { + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + } + op(_SAVE_RETURN_OFFSET, (--)) { #if TIER_ONE frame->return_offset = (uint16_t)(next_instr - this_instr); @@ -6235,7 +6465,7 @@ dummy_func( tier2 op(_COLD_EXIT, ( -- )) { _PyExitData *exit = tstate->jit_exit; assert(exit != NULL); - assert(frame->owner < FRAME_OWNED_BY_INTERPRETER); + assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); _Py_CODEUNIT *target = _PyFrame_GetBytecode(frame) + exit->target; _Py_BackoffCounter temperature = exit->temperature; _PyExecutorObject *executor; diff --git a/Python/ceval.c b/Python/ceval.c index ccc0edca2fc794..ff4f6a01e53b0f 100644 --- a/Python/ceval.c +++ b/Python/ceval.c @@ -2005,10 +2005,9 @@ initialize_locals(PyThreadState *tstate, PyFunctionObject *func, return -1; } -static void -clear_thread_frame(PyThreadState *tstate, _PyInterpreterFrame * frame) +static inline void +clear_and_pop_thread_frame(PyThreadState *tstate, _PyInterpreterFrame *frame) { - assert(frame->owner == FRAME_OWNED_BY_THREAD); // Make sure that this is, indeed, the top frame. We can't check this in // _PyThreadState_PopFrame, since f_code is already cleared at that point: assert((PyObject **)frame + _PyFrame_GetCode(frame)->co_framesize == @@ -2019,6 +2018,31 @@ clear_thread_frame(PyThreadState *tstate, _PyInterpreterFrame * frame) _PyThreadState_PopFrame(tstate, frame); } +static Py_NO_INLINE void +clear_lazy_coro_frame(PyThreadState *tstate, _PyInterpreterFrame *frame) +{ + _PyErr_StackItem *exc_info = tstate->exc_info; + tstate->exc_info = exc_info->previous_item; + PyObject *exc_value = exc_info->exc_value; + _PyThreadState_PopFrame(tstate, (_PyInterpreterFrame *)exc_info); + frame->owner = FRAME_OWNED_BY_THREAD; + _PyInterpreterFrame *caller = frame->previous; + assert(PyStackRef_IsNull(caller->stackpointer[-1])); + caller->stackpointer[-1] = LAZY_CORO_RETURNED; + // Like clear_gen_frame(): a frame object that outlives the + // coroutine must not keep the caller's frame alive via f_back. + frame->previous = NULL; + clear_and_pop_thread_frame(tstate, frame); + Py_XDECREF(exc_value); +} + +static void +clear_thread_frame(PyThreadState *tstate, _PyInterpreterFrame * frame) +{ + assert(frame->owner == FRAME_OWNED_BY_THREAD); + clear_and_pop_thread_frame(tstate, frame); +} + static void clear_gen_frame(PyThreadState *tstate, _PyInterpreterFrame * frame) { @@ -2048,6 +2072,9 @@ _PyEval_FrameClearAndPop(PyThreadState *tstate, _PyInterpreterFrame * frame) if (frame->owner == FRAME_OWNED_BY_THREAD) { clear_thread_frame(tstate, frame); } + else if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { + clear_lazy_coro_frame(tstate, frame); + } else { clear_gen_frame(tstate, frame); } @@ -3686,6 +3713,92 @@ _PyEval_LoadGlobalStackRef(PyObject *globals, PyObject *builtins, PyObject *name } } +/* Suspend the lazy coroutine running in frame, leaving the frame and its + * exception state on the data stack for the caller's GET_AWAITABLE. */ +_PyInterpreterFrame * +_PyEval_SuspendLazyCoro(PyThreadState *tstate, _PyInterpreterFrame *frame) +{ + assert(frame->owner == FRAME_OWNED_BY_LAZY_CORO); + _PyErr_StackItem *exc_info = tstate->exc_info; + tstate->exc_info = exc_info->previous_item; + exc_info->previous_item = NULL; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *caller = frame->previous; + _PyThreadState_UpdateLastProfiledFrame(tstate, frame, caller); + tstate->current_frame = caller; + frame->previous = NULL; + ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; + assert(caller->return_offset == 0); + assert(PyStackRef_IsNull(caller->stackpointer[-1])); + caller->stackpointer[-1] = PyStackRef_Wrap(frame); + return caller; +} + +PyGenObject * +_PyEval_MaterializeLazyCoro(PyThreadState *tstate, _PyInterpreterFrame *frame) +{ + assert(frame->owner == FRAME_OWNED_BY_LAZY_CORO); + assert(frame->previous == NULL); + const int item_slots = sizeof(_PyErr_StackItem) / sizeof(PyObject *); + _PyErr_StackItem *exc_info = + (_PyErr_StackItem *)(tstate->datastack_top - item_slots); + assert(exc_info->previous_item == NULL); + // Right after the frame, unless it starts a new data stack chunk. + assert((PyObject **)frame + _PyFrame_GetCode(frame)->co_framesize == + (PyObject **)exc_info || + (PyObject **)exc_info == &tstate->datastack_chunk->data[0]); + PyGenObject *gen = (PyGenObject *)_PyCoro_MaterializeLazy(frame); + if (gen == NULL) { + return NULL; + } + gen->gi_exc_state.exc_value = exc_info->exc_value; + _PyThreadState_PopFrame(tstate, (_PyInterpreterFrame *)exc_info); + _PyInterpreterFrame *gen_frame = &gen->gi_iframe; + _PyFrame_Copy(frame, gen_frame); + gen_frame->owner = FRAME_OWNED_BY_GENERATOR; + PyFrameObject *f = gen_frame->frame_obj; + if (f != NULL) { + Py_BEGIN_CRITICAL_SECTION(f); + f->f_frame = gen_frame; + Py_END_CRITICAL_SECTION(); + } + // Publish the frame only once the frame object points to it, as the + // critical section may let the GC run. + FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED_YIELD_FROM); + _PyThreadState_PopFrame(tstate, frame); + return gen; +} + +/* Resume the frame of a lazy coroutine that could not be materialized, raising + * the current exception at its suspension point, so its handlers run. */ +_PyInterpreterFrame * +_PyEval_ThrowIntoLazyCoro(PyThreadState *tstate, _PyInterpreterFrame *frame, + _PyStackRef value) +{ + assert(frame->owner == FRAME_OWNED_BY_LAZY_CORO); + assert(_PyErr_Occurred(tstate)); + const int item_slots = sizeof(_PyErr_StackItem) / sizeof(PyObject *); + _PyErr_StackItem *exc_info = + (_PyErr_StackItem *)(tstate->datastack_top - item_slots); + exc_info->previous_item = tstate->exc_info; + tstate->exc_info = exc_info; + _PyInterpreterFrame *caller = tstate->current_frame; + assert(caller->return_offset == 0); + // The value moves to the body, leaving the caller as while the body runs. + assert(PyStackRef_IsNull(caller->stackpointer[-1])); + caller->stackpointer--; + assert(PyStackRef_IsNull(caller->stackpointer[-1])); + frame->previous = caller; + tstate->current_frame = frame; + int too_deep = _Py_EnterRecursivePy(tstate); + assert(!too_deep); + (void)too_deep; + // Stands in for the value sent on resumption, like gen_send_ex2(). + _PyFrame_StackPush(frame, value); + monitor_throw(tstate, frame, frame->instr_ptr); + return frame; +} + PyObject * _PyEval_GetAwaitable(PyObject *iterable, int oparg) { diff --git a/Python/ceval.h b/Python/ceval.h index 00db67265a4f3a..19b3e9b6f3bfe5 100644 --- a/Python/ceval.h +++ b/Python/ceval.h @@ -229,7 +229,7 @@ lltrace_instruction(_PyInterpreterFrame *frame, int oparg) { int offset = 0; - if (frame->owner < FRAME_OWNED_BY_INTERPRETER) { + if (frame->owner != FRAME_OWNED_BY_INTERPRETER) { dump_stack(frame, stack_pointer); offset = (int)(next_instr - _PyFrame_GetBytecode(frame)); } @@ -288,7 +288,7 @@ maybe_lltrace_resume_frame(_PyInterpreterFrame *frame, PyObject *globals) if (globals == NULL) { return 0; } - if (frame->owner >= FRAME_OWNED_BY_INTERPRETER) { + if (frame->owner == FRAME_OWNED_BY_INTERPRETER) { return 0; } int r = PyDict_Contains(globals, &_Py_ID(__lltrace__)); @@ -304,6 +304,8 @@ maybe_lltrace_resume_frame(_PyInterpreterFrame *frame, PyObject *globals) lltrace = *python_lltrace - '0'; // TODO: Parse an int and all that } } + // 5 is the highest level; it must fit in frame->lltrace + lltrace = Py_MIN(lltrace, 5); if (lltrace >= 5) { lltrace_resume_frame(frame); } diff --git a/Python/ceval_macros.h b/Python/ceval_macros.h index 36921e35533433..957d8fe89aaa4d 100644 --- a/Python/ceval_macros.h +++ b/Python/ceval_macros.h @@ -156,6 +156,36 @@ # define LEAVE_TRACING() tracing_mode = 0 #endif +/* Tier one only, after next_instr has skipped the call's inline cache. + * GET_AWAITABLE is never specialized. After an awaited call, it is never + * instrumented with INSTRUMENTED_LINE; with INSTRUCTION events on, the call + * is not lazy. */ +#define IS_AWAITED_CALL() \ + (next_instr->op.code == GET_AWAITABLE && \ + (next_instr->op.arg & GET_AWAITABLE_AWAITED_CALL)) + +/* The JIT recorder expects the regular path, and coroutine origin tracking + * captures the origin when the object is created. */ +#if _Py_TIER2 +# define LAZY_CORO_ALLOWED() (!IS_JIT_TRACING()) +#else +# define LAZY_CORO_ALLOWED() 1 +#endif + +/* The lazy_outcome of a lazily run body that returned. */ +#define LAZY_CORO_RETURNED PyStackRef_TagInt(0) + +#define MAYBE_START_LAZY_CORO(FRAME) \ + do { \ + _PyInterpreterFrame *lazy_frame_ = (FRAME); \ + if ((_PyFrame_GetCode(lazy_frame_)->co_flags & CO_COROUTINE) && \ + tstate->coroutine_origin_tracking_depth == 0 && \ + LAZY_CORO_ALLOWED()) \ + { \ + lazy_frame_->lazy_coro = LAZY_CORO_REQUESTED; \ + } \ + } while (0) + #if _Py_TIER2 #define STOP_TRACING() \ do { \ diff --git a/Python/codegen.c b/Python/codegen.c index ae60caf195f23c..f7cbc9f7fd5f62 100644 --- a/Python/codegen.c +++ b/Python/codegen.c @@ -521,6 +521,13 @@ codegen_add_yield_from(compiler *c, location loc, int await) return SUCCESS; } +static int +codegen_await_call_result(compiler *c, location loc, int where) +{ + ADDOP_I(c, loc, GET_AWAITABLE, GET_AWAITABLE_AWAITED_CALL | where); + return codegen_add_yield_from(c, loc, 1); +} + static int codegen_pop_except_and_reraise(compiler *c, location loc) { @@ -612,13 +619,15 @@ codegen_unwind_fblock(compiler *c, location *ploc, *ploc = info->fb_loc; ADDOP(c, *ploc, POP_BLOCK); if (preserve_tos) { + if (info->fb_type == COMPILE_FBLOCK_ASYNC_WITH) { + ADDOP_I(c, *ploc, SWAP, 4); + } ADDOP_I(c, *ploc, SWAP, 3); ADDOP_I(c, *ploc, SWAP, 2); } RETURN_IF_ERROR(codegen_call_exit_with_nones(c, *ploc)); if (info->fb_type == COMPILE_FBLOCK_ASYNC_WITH) { - ADDOP_I(c, *ploc, GET_AWAITABLE, 2); - ADD_YIELD_FROM(c, *ploc, 1); + RETURN_IF_ERROR(codegen_await_call_result(c, *ploc, 2)); } ADDOP(c, *ploc, POP_TOP); /* The exit block should appear to execute after the @@ -4266,6 +4275,22 @@ codegen_call(compiler *c, expr_ty e) return ret; } +static int +codegen_await(compiler *c, expr_ty e) +{ + location loc = LOC(e); + expr_ty value = e->v.Await.value; + if (value->kind != Call_kind) { + VISIT(c, expr, value); + ADDOP_I(c, loc, GET_AWAITABLE, 0); + ADD_YIELD_FROM(c, loc, 1); + return SUCCESS; + } + ADDOP(c, LOC(value), PUSH_NULL); + RETURN_IF_ERROR(codegen_call(c, value)); + return codegen_await_call_result(c, loc, 0); +} + static int codegen_template_str(compiler *c, expr_ty e) { @@ -5234,7 +5259,8 @@ codegen_visit_keyword(compiler *c, keyword_ty k) static int -codegen_with_except_finish(compiler *c, jump_target_label cleanup) { +codegen_with_except_finish(compiler *c, jump_target_label cleanup, + int is_async) { NEW_JUMP_TARGET_LABEL(c, suppress); ADDOP(c, NO_LOCATION, TO_BOOL); ADDOP_JUMP(c, NO_LOCATION, POP_JUMP_IF_TRUE, suppress); @@ -5247,6 +5273,9 @@ codegen_with_except_finish(compiler *c, jump_target_label cleanup) { ADDOP(c, NO_LOCATION, POP_TOP); ADDOP(c, NO_LOCATION, POP_TOP); ADDOP(c, NO_LOCATION, POP_TOP); + if (is_async) { + ADDOP(c, NO_LOCATION, POP_TOP); + } NEW_JUMP_TARGET_LABEL(c, exit); ADDOP_JUMP(c, NO_LOCATION, JUMP_NO_INTERRUPT, exit); @@ -5297,14 +5326,17 @@ codegen_async_with_inner(compiler *c, stmt_ty s, int pos) /* Evaluate EXPR */ VISIT(c, expr, item->context_expr); loc = LOC(item->context_expr); + ADDOP(c, loc, PUSH_NULL); + ADDOP_I(c, loc, SWAP, 2); ADDOP_I(c, loc, COPY, 1); ADDOP_I(c, loc, LOAD_SPECIAL, SPECIAL___AEXIT__); ADDOP_I(c, loc, SWAP, 2); ADDOP_I(c, loc, SWAP, 3); + ADDOP(c, loc, PUSH_NULL); + ADDOP_I(c, loc, SWAP, 2); ADDOP_I(c, loc, LOAD_SPECIAL, SPECIAL___AENTER__); ADDOP_I(c, loc, CALL, 0); - ADDOP_I(c, loc, GET_AWAITABLE, 1); - ADD_YIELD_FROM(c, loc, 1); + RETURN_IF_ERROR(codegen_await_call_result(c, loc, 1)); ADDOP_JUMP(c, loc, SETUP_WITH, final); @@ -5338,8 +5370,7 @@ codegen_async_with_inner(compiler *c, stmt_ty s, int pos) * call __exit__(None, None, None) */ RETURN_IF_ERROR(codegen_call_exit_with_nones(c, loc)); - ADDOP_I(c, loc, GET_AWAITABLE, 2); - ADD_YIELD_FROM(c, loc, 1); + RETURN_IF_ERROR(codegen_await_call_result(c, loc, 2)); ADDOP(c, loc, POP_TOP); @@ -5353,7 +5384,7 @@ codegen_async_with_inner(compiler *c, stmt_ty s, int pos) ADDOP(c, loc, WITH_EXCEPT_START); ADDOP_I(c, loc, GET_AWAITABLE, 2); ADD_YIELD_FROM(c, loc, 1); - RETURN_IF_ERROR(codegen_with_except_finish(c, cleanup)); + RETURN_IF_ERROR(codegen_with_except_finish(c, cleanup, 1)); USE_LABEL(c, exit); return SUCCESS; @@ -5450,7 +5481,7 @@ codegen_with_inner(compiler *c, stmt_ty s, int pos) ADDOP_JUMP(c, loc, SETUP_CLEANUP, cleanup); ADDOP(c, loc, PUSH_EXC_INFO); ADDOP(c, loc, WITH_EXCEPT_START); - RETURN_IF_ERROR(codegen_with_except_finish(c, cleanup)); + RETURN_IF_ERROR(codegen_with_except_finish(c, cleanup, 0)); USE_LABEL(c, exit); return SUCCESS; @@ -5536,10 +5567,7 @@ codegen_visit_expr_impl(compiler *c, expr_ty e, bool result_is_unused) ADD_YIELD_FROM(c, loc, 0); break; case Await_kind: - VISIT(c, expr, e->v.Await.value); - ADDOP_I(c, loc, GET_AWAITABLE, 0); - ADD_YIELD_FROM(c, loc, 1); - break; + return codegen_await(c, e); case Compare_kind: return codegen_compare(c, e); case Call_kind: diff --git a/Python/executor_cases.c.h b/Python/executor_cases.c.h index 5df8120e7424b9..760b870317a1a1 100644 --- a/Python/executor_cases.c.h +++ b/Python/executor_cases.c.h @@ -8923,7 +8923,8 @@ ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); - PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), oparg); + PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), + oparg & GET_AWAITABLE_WHERE_MASK); _PyFrame_StackPointerInvalidate(frame); stack_pointer += -1; ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); @@ -8946,6 +8947,50 @@ break; } + /* _LAZY_CALL_OUTCOME is not a viable micro-op for tier 2 because it is replaced */ + + case _GUARD_LAZY_OUTCOME_NULL_r11: { + CHECK_CURRENT_CACHED_VALUES(1); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + _PyStackRef *lazy_outcome; + _PyStackRef _stack_item_0 = _tos_cache0; + oparg = CURRENT_OPARG(); + lazy_outcome = &stack_pointer[-((oparg >> 2) & 1)]; + if ((oparg & GET_AWAITABLE_AWAITED_CALL) && + !PyStackRef_IsNull(lazy_outcome[0])) { + UOP_STAT_INC(uopcode, miss); + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(1); + JUMP_TO_JUMP_TARGET(); + } + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(1); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + break; + } + + case _POP_LAZY_OUTCOME_r11: { + CHECK_CURRENT_CACHED_VALUES(1); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + _PyStackRef res; + _PyStackRef *lazy_outcome; + _PyStackRef value; + _PyStackRef _stack_item_0 = _tos_cache0; + oparg = CURRENT_OPARG(); + res = _stack_item_0; + lazy_outcome = &stack_pointer[-((oparg >> 2) & 1)]; + assert(!(oparg & GET_AWAITABLE_AWAITED_CALL) || + PyStackRef_IsNull(lazy_outcome[0])); + (void)lazy_outcome; + value = res; + _tos_cache0 = value; + SET_CURRENT_CACHED_VALUES(1); + stack_pointer += -((oparg >> 2) & 1); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + break; + } + case _SEND_GEN_FRAME_r33: { CHECK_CURRENT_CACHED_VALUES(3); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); @@ -9495,6 +9540,78 @@ break; } + /* _CHECK_LAZY_CORO is not a viable micro-op for tier 2 because it is replaced */ + + case _GUARD_NOT_LAZY_CORO_r00: { + CHECK_CURRENT_CACHED_VALUES(0); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { + UOP_STAT_INC(uopcode, miss); + SET_CURRENT_CACHED_VALUES(0); + JUMP_TO_JUMP_TARGET(); + } + SET_CURRENT_CACHED_VALUES(0); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + break; + } + + case _GUARD_NOT_LAZY_CORO_r11: { + CHECK_CURRENT_CACHED_VALUES(1); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + _PyStackRef _stack_item_0 = _tos_cache0; + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { + UOP_STAT_INC(uopcode, miss); + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(1); + JUMP_TO_JUMP_TARGET(); + } + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(1); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + break; + } + + case _GUARD_NOT_LAZY_CORO_r22: { + CHECK_CURRENT_CACHED_VALUES(2); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + _PyStackRef _stack_item_0 = _tos_cache0; + _PyStackRef _stack_item_1 = _tos_cache1; + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { + UOP_STAT_INC(uopcode, miss); + _tos_cache1 = _stack_item_1; + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(2); + JUMP_TO_JUMP_TARGET(); + } + _tos_cache1 = _stack_item_1; + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(2); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + break; + } + + case _GUARD_NOT_LAZY_CORO_r33: { + CHECK_CURRENT_CACHED_VALUES(3); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + _PyStackRef _stack_item_0 = _tos_cache0; + _PyStackRef _stack_item_1 = _tos_cache1; + _PyStackRef _stack_item_2 = _tos_cache2; + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { + UOP_STAT_INC(uopcode, miss); + _tos_cache2 = _stack_item_2; + _tos_cache1 = _stack_item_1; + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(3); + JUMP_TO_JUMP_TARGET(); + } + _tos_cache2 = _stack_item_2; + _tos_cache1 = _stack_item_1; + _tos_cache0 = _stack_item_0; + SET_CURRENT_CACHED_VALUES(3); + ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); + break; + } + case _YIELD_VALUE_r11: { CHECK_CURRENT_CACHED_VALUES(1); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); @@ -9505,36 +9622,47 @@ retval = _stack_item_0; assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); frame->instr_ptr++; - PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); assert(FRAME_SUSPENDED_YIELD_FROM == FRAME_SUSPENDED + 1); assert(oparg == 0 || oparg == 1); _PyStackRef temp = retval; _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); DTRACE_FUNCTION_RETURN(); - tstate->exc_info = gen->gi_exc_state.previous_item; - gen->gi_exc_state.previous_item = NULL; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *gen_frame = frame; - _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); - frame = tstate->current_frame = frame->previous; - gen_frame->previous = NULL; - ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; - FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + int offset = 1 + INLINE_CACHE_ENTRIES_SEND; + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { + assert(oparg == 1); + frame = _PyEval_SuspendLazyCoro(tstate, frame); + offset = 0; + } + else { + PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); + tstate->exc_info = gen->gi_exc_state.previous_item; + gen->gi_exc_state.previous_item = NULL; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *gen_frame = frame; + _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); + frame = tstate->current_frame = frame->previous; + gen_frame->previous = NULL; + ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; + FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + } assert(INLINE_CACHE_ENTRIES_SEND == INLINE_CACHE_ENTRIES_FOR_ITER); #if TIER_ONE && defined(Py_DEBUG) if (!PyStackRef_IsNone(frame->f_executable)) { Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(opcode == SEND || opcode == FOR_ITER); + assert(offset == 0 ? opcode == GET_AWAITABLE + : (opcode == SEND || opcode == FOR_ITER)); } #endif stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - LOAD_IP(1 + INLINE_CACHE_ENTRIES_SEND); + LOAD_IP(offset); value = temp; - LLTRACE_RESUME_FRAME(); + if (offset != 0) { + LLTRACE_RESUME_FRAME(); + } _tos_cache0 = value; _tos_cache1 = PyStackRef_ZERO_BITS; _tos_cache2 = PyStackRef_ZERO_BITS; @@ -17612,6 +17740,8 @@ break; } + /* _START_LAZY_CORO is not a viable micro-op for tier 2 because it is replaced */ + case _GUARD_NOS_NULL_r02: { CHECK_CURRENT_CACHED_VALUES(0); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); @@ -20726,33 +20856,74 @@ _PyStackRef res; assert(PyStackRef_FunctionCheck(frame->f_funcobj)); PyFunctionObject *func = (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(frame->f_funcobj); - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); - _PyFrame_StackPointerInvalidate(frame); - if (gen == NULL) { - SET_CURRENT_CACHED_VALUES(0); - JUMP_TO_ERROR(); + _PyErr_StackItem *exc_info = NULL; + #if TIER_ONE + if (frame->lazy_coro == LAZY_CORO_REQUESTED) { + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + exc_info = (_PyErr_StackItem *)_PyThreadState_PushFrame( + tstate, sizeof(_PyErr_StackItem) / sizeof(PyObject *)); + _PyFrame_StackPointerInvalidate(frame); + if (exc_info == NULL) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyErr_Clear(tstate); + _PyFrame_StackPointerInvalidate(frame); + } + } + #endif + if (exc_info != NULL) { + exc_info->exc_value = NULL; + exc_info->previous_item = tstate->exc_info; + tstate->exc_info = exc_info; + frame->owner = FRAME_OWNED_BY_LAZY_CORO; + _PyInterpreterFrame *caller = frame->previous; + caller->instr_ptr += caller->return_offset; + caller->return_offset = 0; + _Py_CODEUNIT *send = caller->instr_ptr + 1; + if (send->op.code == INSTRUMENTED_LINE && !tstate->tracing) { + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + int err = _Py_call_instrumentation_line( + tstate, caller, send, caller->instr_ptr) < 0; + _PyFrame_StackPointerInvalidate(frame); + if (err) { + SET_CURRENT_CACHED_VALUES(0); + JUMP_TO_ERROR(); + } + } + res = PyStackRef_None; + } + else { + frame->lazy_coro = 0; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); + _PyFrame_StackPointerInvalidate(frame); + if (gen == NULL) { + SET_CURRENT_CACHED_VALUES(0); + JUMP_TO_ERROR(); + } + assert(STACK_LEVEL() <= 2); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *gen_frame = &gen->gi_iframe; + frame->instr_ptr++; + _PyFrame_Copy(frame, gen_frame); + assert(frame->frame_obj == NULL); + gen->gi_frame_state = FRAME_CREATED; + gen_frame->owner = FRAME_OWNED_BY_GENERATOR; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *prev = frame->previous; + _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); + _PyThreadState_PopFrame(tstate, frame); + frame = tstate->current_frame = prev; + LOAD_IP(frame->return_offset); + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + LLTRACE_RESUME_FRAME(); } - assert(STACK_LEVEL() <= 2); - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - _PyInterpreterFrame *gen_frame = &gen->gi_iframe; - frame->instr_ptr++; - _PyFrame_Copy(frame, gen_frame); - assert(frame->frame_obj == NULL); - gen->gi_frame_state = FRAME_CREATED; - gen_frame->owner = FRAME_OWNED_BY_GENERATOR; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *prev = frame->previous; - _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); - _PyThreadState_PopFrame(tstate, frame); - frame = tstate->current_frame = prev; - LOAD_IP(frame->return_offset); - stack_pointer = _PyFrame_GetStackPointer(frame); - _PyFrame_StackPointerInvalidate(frame); - res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); - LLTRACE_RESUME_FRAME(); _tos_cache0 = res; _tos_cache1 = PyStackRef_ZERO_BITS; _tos_cache2 = PyStackRef_ZERO_BITS; @@ -22857,6 +23028,8 @@ break; } + /* _MAYBE_LAZY_CORO is not a viable micro-op for tier 2 because it is replaced */ + case _SAVE_RETURN_OFFSET_r00: { CHECK_CURRENT_CACHED_VALUES(0); ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); @@ -24034,7 +24207,7 @@ ASSERT_WITHIN_STACK_BOUNDS_IGNORING_CACHE(__FILE__, __LINE__); _PyExitData *exit = tstate->jit_exit; assert(exit != NULL); - assert(frame->owner < FRAME_OWNED_BY_INTERPRETER); + assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); _Py_CODEUNIT *target = _PyFrame_GetBytecode(frame) + exit->target; _Py_BackoffCounter temperature = exit->temperature; _PyExecutorObject *executor; diff --git a/Python/frame.c b/Python/frame.c index 79522b00b47f11..f860a6b603dcff 100644 --- a/Python/frame.c +++ b/Python/frame.c @@ -55,7 +55,7 @@ static void take_ownership(PyFrameObject *f, _PyInterpreterFrame *frame) { Py_BEGIN_CRITICAL_SECTION(f); - assert(frame->owner < FRAME_OWNED_BY_INTERPRETER); + assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); assert(frame->owner != FRAME_OWNED_BY_FRAME_OBJECT); _PyInterpreterFrame *new_frame = (_PyInterpreterFrame *)f->_f_frame_data; _PyFrame_Copy(frame, new_frame); @@ -75,7 +75,7 @@ take_ownership(PyFrameObject *f, _PyInterpreterFrame *frame) assert(f->f_back == NULL); _PyInterpreterFrame *prev = _PyFrame_GetFirstComplete(frame->previous); if (prev) { - assert(prev->owner < FRAME_OWNED_BY_INTERPRETER); + assert(prev->owner != FRAME_OWNED_BY_INTERPRETER); PyObject *exc = PyErr_GetRaisedException(); /* Link PyFrameObjects.f_back and remove link through _PyInterpreterFrame.previous */ PyFrameObject *back = _PyFrame_GetFrameObject(prev); diff --git a/Python/gc_free_threading.c b/Python/gc_free_threading.c index f4f1a7777f3522..f839f968dd6e9f 100644 --- a/Python/gc_free_threading.c +++ b/Python/gc_free_threading.c @@ -457,7 +457,7 @@ gc_visit_thread_stacks(PyInterpreterState *interp, struct collection_state *stat } for (_PyInterpreterFrame *f = p->current_frame; f != NULL; f = f->previous) { - if (f->owner >= FRAME_OWNED_BY_INTERPRETER) { + if (f->owner == FRAME_OWNED_BY_INTERPRETER) { continue; } @@ -855,7 +855,7 @@ gc_visit_thread_stacks_mark_alive(PyInterpreterState *interp, gc_mark_args_t *ar int err = 0; _Py_FOR_EACH_TSTATE_BEGIN(interp, p) { for (_PyInterpreterFrame *f = p->current_frame; f != NULL; f = f->previous) { - if (f->owner >= FRAME_OWNED_BY_INTERPRETER) { + if (f->owner == FRAME_OWNED_BY_INTERPRETER) { continue; } diff --git a/Python/generated_cases.c.h b/Python/generated_cases.c.h index 3af7863e80d2c6..589dbc65af57aa 100644 --- a/Python/generated_cases.c.h +++ b/Python/generated_cases.c.h @@ -1896,6 +1896,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL) { + MAYBE_START_LAZY_CORO(new_frame); + } frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); } @@ -2233,6 +2236,160 @@ DISPATCH(); } + TARGET(CALL_BOUND_METHOD_EXACT_ARGS_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_BOUND_METHOD_EXACT_ARGS_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_BOUND_METHOD_EXACT_ARGS_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef null; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_CALL_BOUND_METHOD_EXACT_ARGS + { + null = stack_pointer[-1 - oparg]; + callable = stack_pointer[-2 - oparg]; + if (!PyStackRef_IsNull(null)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + if (Py_TYPE(PyStackRef_AsPyObjectBorrow(callable)) != &PyMethod_Type) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _INIT_CALL_BOUND_METHOD_EXACT_ARGS + { + self_or_null = null; + assert(PyStackRef_IsNull(self_or_null)); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + STAT_INC(CALL, hit); + self_or_null = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_self); + _PyStackRef temp = callable; + callable = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_func); + stack_pointer[-2 - oparg] = callable; + stack_pointer[-1 - oparg] = self_or_null; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } + // flush + // _CHECK_FUNCTION_VERSION + { + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_EXACT_ARGS + { + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(PyFunction_Check(callable_o)); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (code->co_argcount != oparg + (!PyStackRef_IsNull(self_or_null))) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_STACK_SPACE + { + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (!_PyThreadState_HasStackSpace(tstate, code->co_framesize)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _INIT_CALL_PY_EXACT_ARGS + { + args = &stack_pointer[-oparg]; + int has_self = !PyStackRef_IsNull(self_or_null); + STAT_INC(CALL, hit); + _PyInterpreterFrame *pushed_frame = _PyFrame_PushUnchecked(tstate, callable, oparg + has_self, frame); + _PyStackRef *first_non_self_local = pushed_frame->localsplus + has_self; + pushed_frame->localsplus[0] = self_or_null; + for (int i = 0; i < oparg; i++) { + first_non_self_local[i] = args[i]; + } + new_frame = PyStackRef_Wrap(pushed_frame); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_BOUND_METHOD_GENERAL) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_BOUND_METHOD_GENERAL; @@ -2369,6 +2526,146 @@ DISPATCH(); } + TARGET(CALL_BOUND_METHOD_GENERAL_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_BOUND_METHOD_GENERAL_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_BOUND_METHOD_GENERAL_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef null; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_METHOD_VERSION + { + null = stack_pointer[-1 - oparg]; + callable = stack_pointer[-2 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (Py_TYPE(callable_o) != &PyMethod_Type) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyObject *func = ((PyMethodObject *)callable_o)->im_func; + if (!PyFunction_Check(func)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + if (((PyFunctionObject *)func)->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + if (!PyStackRef_IsNull(null)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _EXPAND_METHOD + { + self_or_null = null; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(PyStackRef_IsNull(self_or_null)); + assert(Py_TYPE(callable_o) == &PyMethod_Type); + self_or_null = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_self); + _PyStackRef temp = callable; + callable = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_func); + assert(PyStackRef_FunctionCheck(callable)); + stack_pointer[-2 - oparg] = callable; + stack_pointer[-1 - oparg] = self_or_null; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(temp); + _PyFrame_StackPointerInvalidate(frame); + } + // flush + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _PY_FRAME_GENERAL + { + args = &stack_pointer[-oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + if (!PyStackRef_IsNull(self_or_null)) { + args--; + total_args++; + } + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + args, total_args, NULL, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_BUILTIN_CLASS) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_BUILTIN_CLASS; @@ -2972,6 +3269,13 @@ } ex_frame = PyStackRef_Wrap(new_frame); } + // _MAYBE_LAZY_CORO + { + new_frame = ex_frame; + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + } // _SAVE_RETURN_OFFSET { #if TIER_ONE @@ -2983,7 +3287,6 @@ } // _PUSH_FRAME { - new_frame = ex_frame; assert(!IS_PEP523_HOOKED(tstate)); _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); _PyFrame_SetStackPointer(frame, stack_pointer); @@ -3150,6 +3453,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 2u == 1 + INLINE_CACHE_ENTRIES_CALL_FUNCTION_EX); frame->return_offset = 2u ; DISPATCH_INLINED(new_frame); @@ -3466,6 +3772,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL_KW) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 4u == 1 + INLINE_CACHE_ENTRIES_CALL_KW); frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); @@ -3474,39 +3783,178 @@ stack_pointer[-2 - oparg] = self_or_null; _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); - PyObject* res_o = _Py_VectorCallInstrumentation_StackRefSteal( - callable, - arguments, - total_args, - kwnames, - opcode == INSTRUMENTED_CALL_KW, - frame, - this_instr, - tstate); + PyObject* res_o = _Py_VectorCallInstrumentation_StackRefSteal( + callable, + arguments, + total_args, + kwnames, + opcode == INSTRUMENTED_CALL_KW, + frame, + this_instr, + tstate); + _PyFrame_StackPointerInvalidate(frame); + if (res_o == NULL) { + stack_pointer += -3 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + JUMP_TO_LABEL(error); + } + res = PyStackRef_FromPyObjectSteal(res_o); + } + stack_pointer[-3 - oparg] = res; + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + DISPATCH(); + } + + TARGET(CALL_KW_BOUND_METHOD) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_KW_BOUND_METHOD; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_KW_BOUND_METHOD); + static_assert(INLINE_CACHE_ENTRIES_CALL_KW == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef null; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef kwnames; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _CHECK_METHOD_VERSION_KW + { + null = stack_pointer[-2 - oparg]; + callable = stack_pointer[-3 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (Py_TYPE(callable_o) != &PyMethod_Type) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + PyObject *func = ((PyMethodObject *)callable_o)->im_func; + if (!PyFunction_Check(func)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + if (((PyFunctionObject *)func)->func_version != func_version) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + if (!PyStackRef_IsNull(null)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _EXPAND_METHOD_KW + { + self_or_null = null; + assert(PyStackRef_IsNull(self_or_null)); + _PyStackRef callable_s = callable; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(Py_TYPE(callable_o) == &PyMethod_Type); + self_or_null = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_self); + callable = PyStackRef_FromPyObjectNew(((PyMethodObject *)callable_o)->im_func); + assert(PyStackRef_FunctionCheck(callable)); + stack_pointer[-3 - oparg] = callable; + stack_pointer[-2 - oparg] = self_or_null; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(callable_s); + _PyFrame_StackPointerInvalidate(frame); + } + // flush + // _PY_FRAME_KW + { + kwnames = stack_pointer[-1]; + args = &stack_pointer[-1 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + _PyStackRef *arguments = args; + if (!PyStackRef_IsNull(self_or_null)) { + arguments--; + total_args++; + } + PyObject *kwnames_o = PyStackRef_AsPyObjectBorrow(kwnames); + int positional_args = total_args - (int)PyTuple_GET_SIZE(kwnames_o); + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + arguments, positional_args, kwnames_o, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(kwnames); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - if (res_o == NULL) { - stack_pointer += -3 - oparg; - ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); - JUMP_TO_LABEL(error); - } - res = PyStackRef_FromPyObjectSteal(res_o); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); } - stack_pointer[-3 - oparg] = res; - stack_pointer += -2 - oparg; - ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); DISPATCH(); } - TARGET(CALL_KW_BOUND_METHOD) { + TARGET(CALL_KW_BOUND_METHOD_AWAITED) { #if _Py_TAIL_CALL_INTERP - int opcode = CALL_KW_BOUND_METHOD; + int opcode = CALL_KW_BOUND_METHOD_AWAITED; (void)(opcode); #endif _Py_CODEUNIT* const this_instr = next_instr; (void)this_instr; frame->instr_ptr = next_instr; next_instr += 4; - INSTRUCTION_STATS(CALL_KW_BOUND_METHOD); + INSTRUCTION_STATS(CALL_KW_BOUND_METHOD_AWAITED); static_assert(INLINE_CACHE_ENTRIES_CALL_KW == 3, "incorrect cache size"); _PyStackRef callable; _PyStackRef null; @@ -3605,6 +4053,10 @@ } new_frame = PyStackRef_Wrap(temp); } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } // _SAVE_RETURN_OFFSET { #if TIER_ONE @@ -3833,6 +4285,128 @@ DISPATCH(); } + TARGET(CALL_KW_PY_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_KW_PY_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_KW_PY_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL_KW == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef kwnames; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _CHECK_FUNCTION_VERSION_KW + { + callable = stack_pointer[-3 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL_KW); + assert(_PyOpcode_Deopt[opcode] == (CALL_KW)); + JUMP_TO_PREDICTED(CALL_KW); + } + } + // _PY_FRAME_KW + { + kwnames = stack_pointer[-1]; + args = &stack_pointer[-1 - oparg]; + self_or_null = stack_pointer[-2 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + _PyStackRef *arguments = args; + if (!PyStackRef_IsNull(self_or_null)) { + arguments--; + total_args++; + } + PyObject *kwnames_o = PyStackRef_AsPyObjectBorrow(kwnames); + int positional_args = total_args - (int)PyTuple_GET_SIZE(kwnames_o); + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + arguments, positional_args, kwnames_o, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(kwnames); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_LEN) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_LEN; @@ -4592,32 +5166,151 @@ } res = PyStackRef_FromPyObjectSteal(res_o); } - // _CHECK_PERIODIC_AT_END + // _CHECK_PERIODIC_AT_END + { + stack_pointer[-2 - oparg] = res; + stack_pointer += -1 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + int err = check_periodics_at_end(tstate, frame); + _PyFrame_StackPointerInvalidate(frame); + if (err != 0) { + JUMP_TO_LABEL(error); + } + } + DISPATCH(); + } + + TARGET(CALL_PY_EXACT_ARGS) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_PY_EXACT_ARGS; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_PY_EXACT_ARGS); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_VERSION + { + callable = stack_pointer[-2 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_EXACT_ARGS + { + self_or_null = stack_pointer[-1 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + assert(PyFunction_Check(callable_o)); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (code->co_argcount != oparg + (!PyStackRef_IsNull(self_or_null))) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_STACK_SPACE + { + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + PyFunctionObject *func = (PyFunctionObject *)callable_o; + PyCodeObject *code = (PyCodeObject *)func->func_code; + if (!_PyThreadState_HasStackSpace(tstate, code->co_framesize)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _INIT_CALL_PY_EXACT_ARGS + { + args = &stack_pointer[-oparg]; + int has_self = !PyStackRef_IsNull(self_or_null); + STAT_INC(CALL, hit); + _PyInterpreterFrame *pushed_frame = _PyFrame_PushUnchecked(tstate, callable, oparg + has_self, frame); + _PyStackRef *first_non_self_local = pushed_frame->localsplus + has_self; + pushed_frame->localsplus[0] = self_or_null; + for (int i = 0; i < oparg; i++) { + first_non_self_local[i] = args[i]; + } + new_frame = PyStackRef_Wrap(pushed_frame); + } + // _SAVE_RETURN_OFFSET { - stack_pointer[-2 - oparg] = res; - stack_pointer += -1 - oparg; + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + stack_pointer += -2 - oparg; ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); - int err = check_periodics_at_end(tstate, frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - if (err != 0) { - JUMP_TO_LABEL(error); - } + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); } DISPATCH(); } - TARGET(CALL_PY_EXACT_ARGS) { + TARGET(CALL_PY_EXACT_ARGS_AWAITED) { #if _Py_TAIL_CALL_INTERP - int opcode = CALL_PY_EXACT_ARGS; + int opcode = CALL_PY_EXACT_ARGS_AWAITED; (void)(opcode); #endif _Py_CODEUNIT* const this_instr = next_instr; (void)this_instr; frame->instr_ptr = next_instr; next_instr += 4; - INSTRUCTION_STATS(CALL_PY_EXACT_ARGS); + INSTRUCTION_STATS(CALL_PY_EXACT_ARGS_AWAITED); static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); _PyStackRef callable; _PyStackRef self_or_null; @@ -4694,6 +5387,10 @@ } new_frame = PyStackRef_Wrap(pushed_frame); } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } // _SAVE_RETURN_OFFSET { #if TIER_ONE @@ -4834,6 +5531,117 @@ DISPATCH(); } + TARGET(CALL_PY_GENERAL_AWAITED) { + #if _Py_TAIL_CALL_INTERP + int opcode = CALL_PY_GENERAL_AWAITED; + (void)(opcode); + #endif + _Py_CODEUNIT* const this_instr = next_instr; + (void)this_instr; + frame->instr_ptr = next_instr; + next_instr += 4; + INSTRUCTION_STATS(CALL_PY_GENERAL_AWAITED); + static_assert(INLINE_CACHE_ENTRIES_CALL == 3, "incorrect cache size"); + _PyStackRef callable; + _PyStackRef self_or_null; + _PyStackRef *args; + _PyStackRef new_frame; + /* Skip 1 cache entry */ + // _CHECK_PEP_523 + { + if (IS_PEP523_HOOKED(tstate)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_FUNCTION_VERSION + { + callable = stack_pointer[-2 - oparg]; + uint32_t func_version = read_u32(&this_instr[2].cache); + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + if (!PyFunction_Check(callable_o)) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + PyFunctionObject *func = (PyFunctionObject *)callable_o; + if (func->func_version != func_version) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _CHECK_RECURSION_REMAINING + { + if (tstate->py_recursion_remaining <= 1) { + UPDATE_MISS_STATS(CALL); + assert(_PyOpcode_Deopt[opcode] == (CALL)); + JUMP_TO_PREDICTED(CALL); + } + } + // _PY_FRAME_GENERAL + { + args = &stack_pointer[-oparg]; + self_or_null = stack_pointer[-1 - oparg]; + PyObject *callable_o = PyStackRef_AsPyObjectBorrow(callable); + int total_args = oparg; + if (!PyStackRef_IsNull(self_or_null)) { + args--; + total_args++; + } + assert(Py_TYPE(callable_o) == &PyFunction_Type); + int code_flags = ((PyCodeObject*)PyFunction_GET_CODE(callable_o))->co_flags; + PyObject *locals = code_flags & CO_OPTIMIZED ? NULL : Py_NewRef(PyFunction_GET_GLOBALS(callable_o)); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *temp = _PyEvalFramePushAndInit( + tstate, callable, locals, + args, total_args, NULL, frame + ); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -2 - oparg; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + if (temp == NULL) { + JUMP_TO_LABEL(error); + } + new_frame = PyStackRef_Wrap(temp); + } + // _START_LAZY_CORO + { + MAYBE_START_LAZY_CORO(PyStackRef_Unwrap(new_frame)); + } + // _SAVE_RETURN_OFFSET + { + #if TIER_ONE + frame->return_offset = (uint16_t)(next_instr - this_instr); + #endif + #if TIER_TWO + frame->return_offset = oparg; + #endif + } + // _PUSH_FRAME + { + assert(!IS_PEP523_HOOKED(tstate)); + _PyInterpreterFrame *temp = PyStackRef_Unwrap(new_frame); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(temp->previous == frame || temp->previous->previous == frame); + CALL_STAT_INC(inlined_py_calls); + frame = tstate->current_frame = temp; + tstate->py_recursion_remaining--; + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + LOAD_IP(0); + #ifdef Py_DEBUG + assert(frame->previous->stackpointer_valid == 1); + #endif + DTRACE_FUNCTION_ENTRY(); + LLTRACE_RESUME_FRAME(); + } + DISPATCH(); + } + TARGET(CALL_STR_1) { #if _Py_TAIL_CALL_INTERP int opcode = CALL_STR_1; @@ -5198,7 +6006,8 @@ sub_iter = stack_pointer[-4]; PyObject *exc_value = PyStackRef_AsPyObjectBorrow(exc_value_st); #if !_Py_TAIL_CALL_INTERP - assert(throwflag); + + assert(throwflag || frame->owner == FRAME_OWNED_BY_LAZY_CORO); #endif assert(exc_value && PyExceptionInstance_Check(exc_value)); _PyFrame_SetStackPointer(frame, stack_pointer); @@ -6828,27 +7637,104 @@ frame->instr_ptr = next_instr; next_instr += 1; INSTRUCTION_STATS(GET_AWAITABLE); + _PyStackRef *lazy_outcome; + _PyStackRef res; + _PyStackRef value; _PyStackRef iterable; _PyStackRef iter; _PyStackRef null; _PyStackRef none; - iterable = stack_pointer[-1]; - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), oparg); - _PyFrame_StackPointerInvalidate(frame); - stack_pointer += -1; - ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyStackRef_CLOSE(iterable); - _PyFrame_StackPointerInvalidate(frame); - if (iter_o == NULL) { - JUMP_TO_LABEL(error); + // _LAZY_CALL_OUTCOME + { + res = stack_pointer[-1]; + lazy_outcome = &stack_pointer[-1 - ((oparg >> 2) & 1)]; + if (oparg & GET_AWAITABLE_AWAITED_CALL) { + _PyStackRef *slot = &stack_pointer[-2]; + assert(slot == lazy_outcome); + (void)lazy_outcome; + _PyStackRef outcome = *slot; + if (PyStackRef_IsTaggedInt(outcome)) { + *slot = PyStackRef_NULL; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + assert(_Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), + (int)(next_instr - _PyFrame_GetBytecode(frame))).op.code == SEND); + _PyFrame_StackPointerInvalidate(frame); + _Py_CODEUNIT *end_send = next_instr + 1 + INLINE_CACHE_ENTRIES_SEND + next_instr->op.arg; + if (end_send->op.code != END_SEND) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + int err = monitor_stop_iteration(tstate, frame, end_send, + PyStackRef_AsPyObjectBorrow(res)); + _PyFrame_StackPointerInvalidate(frame); + if (err) { + JUMP_TO_LABEL(error); + } + } + _PyStackRef v = res; + stack_pointer[-2] = v; + stack_pointer -= 1; + next_instr = end_send + 1; + DISPATCH(); + } + else if (!PyStackRef_IsNull(outcome)) { + _PyInterpreterFrame *lazy_frame = PyStackRef_Unwrap(outcome); + *slot = PyStackRef_NULL; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyGenObject *gen = _PyEval_MaterializeLazyCoro(tstate, lazy_frame); + _PyFrame_StackPointerInvalidate(frame); + _PyStackRef v = res; + if (gen == NULL) { + stack_pointer[-1] = PyStackRef_NULL; + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + frame = _PyEval_ThrowIntoLazyCoro(tstate, lazy_frame, v); + _PyFrame_StackPointerInvalidate(frame); + next_instr = frame->instr_ptr; + LOAD_SP(); + JUMP_TO_LABEL(error); + } + stack_pointer[-2] = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + stack_pointer[-1] = PyStackRef_NULL; + stack_pointer[0] = v; + stack_pointer += 1; + next_instr += 1 + INLINE_CACHE_ENTRIES_SEND; + DISPATCH(); + } + } + } + // _POP_LAZY_OUTCOME + { + assert(!(oparg & GET_AWAITABLE_AWAITED_CALL) || + PyStackRef_IsNull(lazy_outcome[0])); + (void)lazy_outcome; + value = res; + } + // _GET_AWAITABLE + { + iterable = value; + stack_pointer[-1 - ((oparg >> 2) & 1)] = iterable; + stack_pointer += -((oparg >> 2) & 1); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyObject *iter_o = _PyEval_GetAwaitable(PyStackRef_AsPyObjectBorrow(iterable), + oparg & GET_AWAITABLE_WHERE_MASK); + _PyFrame_StackPointerInvalidate(frame); + stack_pointer += -1; + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyStackRef_CLOSE(iterable); + _PyFrame_StackPointerInvalidate(frame); + if (iter_o == NULL) { + JUMP_TO_LABEL(error); + } + iter = PyStackRef_FromPyObjectSteal(iter_o); + null = PyStackRef_NULL; + none = PyStackRef_None; } - iter = PyStackRef_FromPyObjectSteal(iter_o); - null = PyStackRef_NULL; - none = PyStackRef_None; stack_pointer[0] = iter; stack_pointer[1] = null; stack_pointer[2] = none; @@ -7200,6 +8086,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL) { + MAYBE_START_LAZY_CORO(new_frame); + } frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); } @@ -7367,6 +8256,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL()) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 2u == 1 + INLINE_CACHE_ENTRIES_CALL_FUNCTION_EX); frame->return_offset = 2u ; DISPATCH_INLINED(new_frame); @@ -7519,6 +8411,9 @@ if (new_frame == NULL) { JUMP_TO_LABEL(error); } + if (IS_AWAITED_CALL() && opcode != INSTRUMENTED_CALL_KW) { + MAYBE_START_LAZY_CORO(new_frame); + } assert( 4u == 1 + INLINE_CACHE_ENTRIES_CALL_KW); frame->return_offset = 4u ; DISPATCH_INLINED(new_frame); @@ -8294,6 +9189,9 @@ _PyStackRef val; _PyStackRef value; _PyStackRef retval; + // _CHECK_LAZY_CORO + { + } // _YIELD_VALUE_EVENT { val = stack_pointer[-1]; @@ -8327,7 +9225,6 @@ retval = value; assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); frame->instr_ptr++; - PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); assert(FRAME_SUSPENDED_YIELD_FROM == FRAME_SUSPENDED + 1); assert(oparg == 0 || oparg == 1); _PyStackRef temp = retval; @@ -8336,29 +9233,41 @@ _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); DTRACE_FUNCTION_RETURN(); - tstate->exc_info = gen->gi_exc_state.previous_item; - gen->gi_exc_state.previous_item = NULL; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *gen_frame = frame; - _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); - frame = tstate->current_frame = frame->previous; - gen_frame->previous = NULL; - ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; - FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + int offset = 1 + INLINE_CACHE_ENTRIES_SEND; + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { + assert(oparg == 1); + frame = _PyEval_SuspendLazyCoro(tstate, frame); + offset = 0; + } + else { + PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); + tstate->exc_info = gen->gi_exc_state.previous_item; + gen->gi_exc_state.previous_item = NULL; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *gen_frame = frame; + _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); + frame = tstate->current_frame = frame->previous; + gen_frame->previous = NULL; + ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; + FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + } assert(INLINE_CACHE_ENTRIES_SEND == INLINE_CACHE_ENTRIES_FOR_ITER); #if TIER_ONE && defined(Py_DEBUG) if (!PyStackRef_IsNone(frame->f_executable)) { Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(opcode == SEND || opcode == FOR_ITER); + assert(offset == 0 ? opcode == GET_AWAITABLE + : (opcode == SEND || opcode == FOR_ITER)); } #endif stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - LOAD_IP(1 + INLINE_CACHE_ENTRIES_SEND); + LOAD_IP(offset); value = temp; - LLTRACE_RESUME_FRAME(); + if (offset != 0) { + LLTRACE_RESUME_FRAME(); + } } stack_pointer[0] = value; stack_pointer += 1; @@ -11451,32 +12360,72 @@ _PyStackRef res; assert(PyStackRef_FunctionCheck(frame->f_funcobj)); PyFunctionObject *func = (PyFunctionObject *)PyStackRef_AsPyObjectBorrow(frame->f_funcobj); - _PyFrame_SetStackPointer(frame, stack_pointer); - _PyFrame_StackPointerValidate(frame); - PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); - _PyFrame_StackPointerInvalidate(frame); - if (gen == NULL) { - JUMP_TO_LABEL(error); + _PyErr_StackItem *exc_info = NULL; + #if TIER_ONE + if (frame->lazy_coro == LAZY_CORO_REQUESTED) { + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + exc_info = (_PyErr_StackItem *)_PyThreadState_PushFrame( + tstate, sizeof(_PyErr_StackItem) / sizeof(PyObject *)); + _PyFrame_StackPointerInvalidate(frame); + if (exc_info == NULL) { + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyErr_Clear(tstate); + _PyFrame_StackPointerInvalidate(frame); + } + } + #endif + if (exc_info != NULL) { + exc_info->exc_value = NULL; + exc_info->previous_item = tstate->exc_info; + tstate->exc_info = exc_info; + frame->owner = FRAME_OWNED_BY_LAZY_CORO; + _PyInterpreterFrame *caller = frame->previous; + caller->instr_ptr += caller->return_offset; + caller->return_offset = 0; + _Py_CODEUNIT *send = caller->instr_ptr + 1; + if (send->op.code == INSTRUMENTED_LINE && !tstate->tracing) { + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + int err = _Py_call_instrumentation_line( + tstate, caller, send, caller->instr_ptr) < 0; + _PyFrame_StackPointerInvalidate(frame); + if (err) { + JUMP_TO_LABEL(error); + } + } + res = PyStackRef_None; + } + else { + frame->lazy_coro = 0; + _PyFrame_SetStackPointer(frame, stack_pointer); + _PyFrame_StackPointerValidate(frame); + PyGenObject *gen = (PyGenObject *)_Py_MakeCoro(func); + _PyFrame_StackPointerInvalidate(frame); + if (gen == NULL) { + JUMP_TO_LABEL(error); + } + assert(STACK_LEVEL() <= 2); + assert(stack_pointer == _PyFrame_GetStackPointer(frame)); + _PyFrame_StackPointerValidate(frame); + _PyInterpreterFrame *gen_frame = &gen->gi_iframe; + frame->instr_ptr++; + _PyFrame_Copy(frame, gen_frame); + assert(frame->frame_obj == NULL); + gen->gi_frame_state = FRAME_CREATED; + gen_frame->owner = FRAME_OWNED_BY_GENERATOR; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *prev = frame->previous; + _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); + _PyThreadState_PopFrame(tstate, frame); + frame = tstate->current_frame = prev; + LOAD_IP(frame->return_offset); + stack_pointer = _PyFrame_GetStackPointer(frame); + _PyFrame_StackPointerInvalidate(frame); + res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); + LLTRACE_RESUME_FRAME(); } - assert(STACK_LEVEL() <= 2); - assert(stack_pointer == _PyFrame_GetStackPointer(frame)); - _PyFrame_StackPointerValidate(frame); - _PyInterpreterFrame *gen_frame = &gen->gi_iframe; - frame->instr_ptr++; - _PyFrame_Copy(frame, gen_frame); - assert(frame->frame_obj == NULL); - gen->gi_frame_state = FRAME_CREATED; - gen_frame->owner = FRAME_OWNED_BY_GENERATOR; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *prev = frame->previous; - _PyThreadState_UpdateLastProfiledFrame(tstate, frame, prev); - _PyThreadState_PopFrame(tstate, frame); - frame = tstate->current_frame = prev; - LOAD_IP(frame->return_offset); - stack_pointer = _PyFrame_GetStackPointer(frame); - _PyFrame_StackPointerInvalidate(frame); - res = PyStackRef_FromPyObjectStealMortal((PyObject *)gen); - LLTRACE_RESUME_FRAME(); stack_pointer[0] = res; stack_pointer += 1; ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); @@ -13583,6 +14532,9 @@ opcode = YIELD_VALUE; _PyStackRef value; _PyStackRef retval; + // _CHECK_LAZY_CORO + { + } // _MAKE_HEAP_SAFE { value = stack_pointer[-1]; @@ -13593,7 +14545,6 @@ retval = value; assert(frame->owner != FRAME_OWNED_BY_INTERPRETER); frame->instr_ptr++; - PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); assert(FRAME_SUSPENDED_YIELD_FROM == FRAME_SUSPENDED + 1); assert(oparg == 0 || oparg == 1); _PyStackRef temp = retval; @@ -13602,29 +14553,41 @@ _PyFrame_SetStackPointer(frame, stack_pointer); _PyFrame_StackPointerValidate(frame); DTRACE_FUNCTION_RETURN(); - tstate->exc_info = gen->gi_exc_state.previous_item; - gen->gi_exc_state.previous_item = NULL; - _Py_LeaveRecursiveCallPy(tstate); - _PyInterpreterFrame *gen_frame = frame; - _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); - frame = tstate->current_frame = frame->previous; - gen_frame->previous = NULL; - ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; - FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + int offset = 1 + INLINE_CACHE_ENTRIES_SEND; + if (frame->owner == FRAME_OWNED_BY_LAZY_CORO) { + assert(oparg == 1); + frame = _PyEval_SuspendLazyCoro(tstate, frame); + offset = 0; + } + else { + PyGenObject *gen = _PyGen_GetGeneratorFromFrame(frame); + tstate->exc_info = gen->gi_exc_state.previous_item; + gen->gi_exc_state.previous_item = NULL; + _Py_LeaveRecursiveCallPy(tstate); + _PyInterpreterFrame *gen_frame = frame; + _PyThreadState_UpdateLastProfiledFrame(tstate, gen_frame, gen_frame->previous); + frame = tstate->current_frame = frame->previous; + gen_frame->previous = NULL; + ((_PyThreadStateImpl *)tstate)->generator_return_kind = GENERATOR_YIELD; + FT_ATOMIC_STORE_INT8_RELEASE(gen->gi_frame_state, FRAME_SUSPENDED + oparg); + } assert(INLINE_CACHE_ENTRIES_SEND == INLINE_CACHE_ENTRIES_FOR_ITER); #if TIER_ONE && defined(Py_DEBUG) if (!PyStackRef_IsNone(frame->f_executable)) { Py_ssize_t i = frame->instr_ptr - _PyFrame_GetBytecode(frame); assert(i >= 0 && i <= INT_MAX); int opcode = _Py_GetBaseCodeUnit(_PyFrame_GetCode(frame), (int)i).op.code; - assert(opcode == SEND || opcode == FOR_ITER); + assert(offset == 0 ? opcode == GET_AWAITABLE + : (opcode == SEND || opcode == FOR_ITER)); } #endif stack_pointer = _PyFrame_GetStackPointer(frame); _PyFrame_StackPointerInvalidate(frame); - LOAD_IP(1 + INLINE_CACHE_ENTRIES_SEND); + LOAD_IP(offset); value = temp; - LLTRACE_RESUME_FRAME(); + if (offset != 0) { + LLTRACE_RESUME_FRAME(); + } } stack_pointer[0] = value; stack_pointer += 1; diff --git a/Python/instrumentation.c b/Python/instrumentation.c index 48daa91259d3c9..9767397e65cf79 100644 --- a/Python/instrumentation.c +++ b/Python/instrumentation.c @@ -191,6 +191,16 @@ _PyCode_Deinstrument(uint8_t opcode) return DE_INSTRUMENT[opcode]; } +/* GET_AWAITABLE after an awaited call is never instrumented, + * see IS_AWAITED_CALL(). */ +static inline bool +is_awaited_call_get_awaitable(PyCodeObject *code, int i) +{ + _Py_CODEUNIT inst = _Py_GetBaseCodeUnit(code, i); + return inst.op.code == GET_AWAITABLE && + (inst.op.arg & GET_AWAITABLE_AWAITED_CALL); +} + static inline bool is_instrumented(int opcode) { @@ -574,6 +584,7 @@ sanity_check_instrumentation(PyCodeObject *code) opcode = _PyCode_GetOriginalOpcode(data->lines, i); CHECK(valid_opcode(opcode)); CHECK(opcode != END_FOR); + CHECK(!is_awaited_call_get_awaitable(code, i)); CHECK(opcode != RESUME); CHECK(opcode != RESUME_CHECK); CHECK(opcode != RESUME_CHECK_JIT); @@ -1353,8 +1364,13 @@ _Py_call_instrumentation_line(PyThreadState *tstate, _PyInterpreterFrame* frame, int prev_opcode = bytecode[prev_index].op.code; /* RESUME and INSTRUMENTED_RESUME are needed for the operation of * instrumentation, so must never be hidden by an INSTRUMENTED_LINE. + * GET_AWAITABLE after an awaited call cannot start a line, so + * the SEND after it does. */ - if (prev_opcode != RESUME && prev_opcode != INSTRUMENTED_RESUME) { + if (prev_opcode != RESUME && prev_opcode != INSTRUMENTED_RESUME && + !(i == prev_index + 1 && + is_awaited_call_get_awaitable(code, prev_index))) + { goto done; } } @@ -1451,6 +1467,14 @@ _Py_call_instrumentation_instruction(PyThreadState *tstate, _PyInterpreterFrame* if (tstate->tracing) { return next_opcode; } + if (next_opcode == GET_AWAITABLE && + (instr->op.arg & GET_AWAITABLE_AWAITED_CALL) && + !PyStackRef_IsNull(frame->stackpointer[-2])) + { + /* Instrumented while a lazy coroutine ran: its outcome must reach + * GET_AWAITABLE before anything else runs. */ + return next_opcode; + } assert(debug_check_sanity(tstate->interp, code)); PyInterpreterState *interp = tstate->interp; uint8_t tools = instrumentation_data->per_instruction_tools != NULL ? @@ -1579,6 +1603,16 @@ initialize_lines(_PyCoLineInstrumentationData *line_data, PyCodeObject *code, in * RESUME and POP_ITER must not be instrumented with INSTRUMENTED_LINE */ set_original_opcode(line_data, i, 0); break; + case GET_AWAITABLE: + if (is_awaited_call_get_awaitable(code, i)) { + /* GET_AWAITABLE after an awaited call must not be + * instrumented with INSTRUMENTED_LINE, as no events may + * fire before it handles a lazy coroutine. + * The SEND after it starts the line of the await. */ + set_original_opcode(line_data, i, 0); + break; + } + _Py_FALLTHROUGH; default: /* Set original_opcode to the opcode iff the instruction * starts a line, and thus should be instrumented. @@ -1644,7 +1678,9 @@ initialize_lines(_PyCoLineInstrumentationData *line_data, PyCodeObject *code, in assert(target >= 0); if (get_line_delta(line_data, target) != NO_LINE) { int opcode = _Py_GetBaseCodeUnit(code, target).op.code; - if (opcode != POP_ITER) { + if (opcode != POP_ITER && + !is_awaited_call_get_awaitable(code, target)) + { set_original_opcode(line_data, target, opcode); } } @@ -1990,7 +2026,7 @@ instrument_all_executing_code_objects(PyInterpreterState *interp) _Py_FOR_EACH_TSTATE_BEGIN(interp, ts) { _PyInterpreterFrame *frame = ts->current_frame; while (frame) { - if (frame->owner < FRAME_OWNED_BY_INTERPRETER) { + if (frame->owner != FRAME_OWNED_BY_INTERPRETER) { err = instrument_lock_held(_PyFrame_GetCode(frame), interp); if (err) { goto done; diff --git a/Python/intrinsics.c b/Python/intrinsics.c index dfa81baa654e12..50c53ba603e246 100644 --- a/Python/intrinsics.c +++ b/Python/intrinsics.c @@ -144,7 +144,8 @@ static PyObject * stopiteration_error(PyThreadState* tstate, PyObject *exc) { _PyInterpreterFrame *frame = tstate->current_frame; - assert(frame->owner == FRAME_OWNED_BY_GENERATOR); + assert(frame->owner == FRAME_OWNED_BY_GENERATOR || + frame->owner == FRAME_OWNED_BY_LAZY_CORO); assert(PyExceptionInstance_Check(exc)); const char *msg = NULL; if (PyErr_GivenExceptionMatches(exc, PyExc_StopIteration)) { diff --git a/Python/opcode_targets.h b/Python/opcode_targets.h index 91b424773224e4..8fd141bfb7ba18 100644 --- a/Python/opcode_targets.h +++ b/Python/opcode_targets.h @@ -146,7 +146,9 @@ static void *opcode_targets_table[256] = { &&TARGET_BINARY_OP_SUBTRACT_INT, &&TARGET_CALL_ALLOC_AND_ENTER_INIT, &&TARGET_CALL_BOUND_METHOD_EXACT_ARGS, + &&TARGET_CALL_BOUND_METHOD_EXACT_ARGS_AWAITED, &&TARGET_CALL_BOUND_METHOD_GENERAL, + &&TARGET_CALL_BOUND_METHOD_GENERAL_AWAITED, &&TARGET_CALL_BUILTIN_CLASS, &&TARGET_CALL_BUILTIN_FAST, &&TARGET_CALL_BUILTIN_FAST_WITH_KEYWORDS, @@ -155,8 +157,10 @@ static void *opcode_targets_table[256] = { &&TARGET_CALL_EX_PY, &&TARGET_CALL_ISINSTANCE, &&TARGET_CALL_KW_BOUND_METHOD, + &&TARGET_CALL_KW_BOUND_METHOD_AWAITED, &&TARGET_CALL_KW_NON_PY, &&TARGET_CALL_KW_PY, + &&TARGET_CALL_KW_PY_AWAITED, &&TARGET_CALL_LEN, &&TARGET_CALL_LIST_APPEND, &&TARGET_CALL_METHOD_DESCRIPTOR_FAST, @@ -165,7 +169,9 @@ static void *opcode_targets_table[256] = { &&TARGET_CALL_METHOD_DESCRIPTOR_O, &&TARGET_CALL_NON_PY_GENERAL, &&TARGET_CALL_PY_EXACT_ARGS, + &&TARGET_CALL_PY_EXACT_ARGS_AWAITED, &&TARGET_CALL_PY_GENERAL, + &&TARGET_CALL_PY_GENERAL_AWAITED, &&TARGET_CALL_STR_1, &&TARGET_CALL_TUPLE_1, &&TARGET_CALL_TYPE_1, @@ -227,12 +233,6 @@ static void *opcode_targets_table[256] = { &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, &&TARGET_INSTRUMENTED_END_FOR, &&TARGET_INSTRUMENTED_POP_ITER, &&TARGET_INSTRUMENTED_END_SEND, @@ -478,12 +478,12 @@ static void *opcode_tracing_targets_table[256] = { &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, &&TARGET_TRACE_RECORD, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, - &&_unknown_opcode, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, + &&TARGET_TRACE_RECORD, &&_unknown_opcode, &&_unknown_opcode, &&_unknown_opcode, @@ -561,7 +561,9 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CACHE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_ALLOC_AND_ENTER_INIT(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_GENERAL(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BOUND_METHOD_GENERAL_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BUILTIN_CLASS(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BUILTIN_FAST(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_BUILTIN_FAST_WITH_KEYWORDS(TAIL_CALL_PARAMS); @@ -574,8 +576,10 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_INTRINSIC_2(TAIL_CALL_PARAM static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_ISINSTANCE(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_BOUND_METHOD(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_BOUND_METHOD_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_NON_PY(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_PY(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_KW_PY_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_LEN(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_LIST_APPEND(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_METHOD_DESCRIPTOR_FAST(TAIL_CALL_PARAMS); @@ -584,7 +588,9 @@ static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_METHOD_DESCRIPTOR_NOARGS(TA static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_METHOD_DESCRIPTOR_O(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_NON_PY_GENERAL(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_EXACT_ARGS(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_EXACT_ARGS_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_GENERAL(TAIL_CALL_PARAMS); +static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_PY_GENERAL_AWAITED(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_STR_1(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_TUPLE_1(TAIL_CALL_PARAMS); static PyObject *Py_PRESERVE_NONE_CC _TAIL_CALL_CALL_TYPE_1(TAIL_CALL_PARAMS); @@ -804,7 +810,9 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [CALL] = _TAIL_CALL_CALL, [CALL_ALLOC_AND_ENTER_INIT] = _TAIL_CALL_CALL_ALLOC_AND_ENTER_INIT, [CALL_BOUND_METHOD_EXACT_ARGS] = _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = _TAIL_CALL_CALL_BOUND_METHOD_EXACT_ARGS_AWAITED, [CALL_BOUND_METHOD_GENERAL] = _TAIL_CALL_CALL_BOUND_METHOD_GENERAL, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = _TAIL_CALL_CALL_BOUND_METHOD_GENERAL_AWAITED, [CALL_BUILTIN_CLASS] = _TAIL_CALL_CALL_BUILTIN_CLASS, [CALL_BUILTIN_FAST] = _TAIL_CALL_CALL_BUILTIN_FAST, [CALL_BUILTIN_FAST_WITH_KEYWORDS] = _TAIL_CALL_CALL_BUILTIN_FAST_WITH_KEYWORDS, @@ -817,8 +825,10 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [CALL_ISINSTANCE] = _TAIL_CALL_CALL_ISINSTANCE, [CALL_KW] = _TAIL_CALL_CALL_KW, [CALL_KW_BOUND_METHOD] = _TAIL_CALL_CALL_KW_BOUND_METHOD, + [CALL_KW_BOUND_METHOD_AWAITED] = _TAIL_CALL_CALL_KW_BOUND_METHOD_AWAITED, [CALL_KW_NON_PY] = _TAIL_CALL_CALL_KW_NON_PY, [CALL_KW_PY] = _TAIL_CALL_CALL_KW_PY, + [CALL_KW_PY_AWAITED] = _TAIL_CALL_CALL_KW_PY_AWAITED, [CALL_LEN] = _TAIL_CALL_CALL_LEN, [CALL_LIST_APPEND] = _TAIL_CALL_CALL_LIST_APPEND, [CALL_METHOD_DESCRIPTOR_FAST] = _TAIL_CALL_CALL_METHOD_DESCRIPTOR_FAST, @@ -827,7 +837,9 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [CALL_METHOD_DESCRIPTOR_O] = _TAIL_CALL_CALL_METHOD_DESCRIPTOR_O, [CALL_NON_PY_GENERAL] = _TAIL_CALL_CALL_NON_PY_GENERAL, [CALL_PY_EXACT_ARGS] = _TAIL_CALL_CALL_PY_EXACT_ARGS, + [CALL_PY_EXACT_ARGS_AWAITED] = _TAIL_CALL_CALL_PY_EXACT_ARGS_AWAITED, [CALL_PY_GENERAL] = _TAIL_CALL_CALL_PY_GENERAL, + [CALL_PY_GENERAL_AWAITED] = _TAIL_CALL_CALL_PY_GENERAL_AWAITED, [CALL_STR_1] = _TAIL_CALL_CALL_STR_1, [CALL_TUPLE_1] = _TAIL_CALL_CALL_TUPLE_1, [CALL_TYPE_1] = _TAIL_CALL_CALL_TYPE_1, @@ -1016,12 +1028,6 @@ static py_tail_call_funcptr instruction_funcptr_handler_table[256] = { [125] = _TAIL_CALL_UNKNOWN_OPCODE, [126] = _TAIL_CALL_UNKNOWN_OPCODE, [127] = _TAIL_CALL_UNKNOWN_OPCODE, - [219] = _TAIL_CALL_UNKNOWN_OPCODE, - [220] = _TAIL_CALL_UNKNOWN_OPCODE, - [221] = _TAIL_CALL_UNKNOWN_OPCODE, - [222] = _TAIL_CALL_UNKNOWN_OPCODE, - [223] = _TAIL_CALL_UNKNOWN_OPCODE, - [224] = _TAIL_CALL_UNKNOWN_OPCODE, [225] = _TAIL_CALL_UNKNOWN_OPCODE, [226] = _TAIL_CALL_UNKNOWN_OPCODE, [227] = _TAIL_CALL_UNKNOWN_OPCODE, @@ -1062,7 +1068,9 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [CALL] = _TAIL_CALL_TRACE_RECORD, [CALL_ALLOC_AND_ENTER_INIT] = _TAIL_CALL_TRACE_RECORD, [CALL_BOUND_METHOD_EXACT_ARGS] = _TAIL_CALL_TRACE_RECORD, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_BOUND_METHOD_GENERAL] = _TAIL_CALL_TRACE_RECORD, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_BUILTIN_CLASS] = _TAIL_CALL_TRACE_RECORD, [CALL_BUILTIN_FAST] = _TAIL_CALL_TRACE_RECORD, [CALL_BUILTIN_FAST_WITH_KEYWORDS] = _TAIL_CALL_TRACE_RECORD, @@ -1075,8 +1083,10 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [CALL_ISINSTANCE] = _TAIL_CALL_TRACE_RECORD, [CALL_KW] = _TAIL_CALL_TRACE_RECORD, [CALL_KW_BOUND_METHOD] = _TAIL_CALL_TRACE_RECORD, + [CALL_KW_BOUND_METHOD_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_KW_NON_PY] = _TAIL_CALL_TRACE_RECORD, [CALL_KW_PY] = _TAIL_CALL_TRACE_RECORD, + [CALL_KW_PY_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_LEN] = _TAIL_CALL_TRACE_RECORD, [CALL_LIST_APPEND] = _TAIL_CALL_TRACE_RECORD, [CALL_METHOD_DESCRIPTOR_FAST] = _TAIL_CALL_TRACE_RECORD, @@ -1085,7 +1095,9 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [CALL_METHOD_DESCRIPTOR_O] = _TAIL_CALL_TRACE_RECORD, [CALL_NON_PY_GENERAL] = _TAIL_CALL_TRACE_RECORD, [CALL_PY_EXACT_ARGS] = _TAIL_CALL_TRACE_RECORD, + [CALL_PY_EXACT_ARGS_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_PY_GENERAL] = _TAIL_CALL_TRACE_RECORD, + [CALL_PY_GENERAL_AWAITED] = _TAIL_CALL_TRACE_RECORD, [CALL_STR_1] = _TAIL_CALL_TRACE_RECORD, [CALL_TUPLE_1] = _TAIL_CALL_TRACE_RECORD, [CALL_TYPE_1] = _TAIL_CALL_TRACE_RECORD, @@ -1274,12 +1286,6 @@ static py_tail_call_funcptr instruction_funcptr_tracing_table[256] = { [125] = _TAIL_CALL_UNKNOWN_OPCODE, [126] = _TAIL_CALL_UNKNOWN_OPCODE, [127] = _TAIL_CALL_UNKNOWN_OPCODE, - [219] = _TAIL_CALL_UNKNOWN_OPCODE, - [220] = _TAIL_CALL_UNKNOWN_OPCODE, - [221] = _TAIL_CALL_UNKNOWN_OPCODE, - [222] = _TAIL_CALL_UNKNOWN_OPCODE, - [223] = _TAIL_CALL_UNKNOWN_OPCODE, - [224] = _TAIL_CALL_UNKNOWN_OPCODE, [225] = _TAIL_CALL_UNKNOWN_OPCODE, [226] = _TAIL_CALL_UNKNOWN_OPCODE, [227] = _TAIL_CALL_UNKNOWN_OPCODE, diff --git a/Python/optimizer.c b/Python/optimizer.c index e05adb344c8d06..219c3893163b13 100644 --- a/Python/optimizer.c +++ b/Python/optimizer.c @@ -502,6 +502,10 @@ _PyUOp_Replacements[MAX_UOP_ID + 1] = { [_LOAD_BYTECODE] = _NOP, [_SEND_VIRTUAL] = _SEND_VIRTUAL_TIER_TWO, [_SEND_ASYNC_GEN] = _SEND_ASYNC_GEN_TIER_TWO, + [_LAZY_CALL_OUTCOME] = _GUARD_LAZY_OUTCOME_NULL, + [_MAYBE_LAZY_CORO] = _NOP, + [_START_LAZY_CORO] = _NOP, + [_CHECK_LAZY_CORO] = _GUARD_NOT_LAZY_CORO, }; static const uint8_t @@ -731,7 +735,9 @@ _PyJit_translate_single_bytecode_to_trace( } // Strange control-flow - bool has_dynamic_jump_taken = OPCODE_HAS_UNPREDICTABLE_JUMP(opcode) && + // Tier two only runs GET_AWAITABLE's fall-through. + bool has_dynamic_jump_taken = + (OPCODE_HAS_UNPREDICTABLE_JUMP(opcode) || opcode == GET_AWAITABLE) && (next_instr != this_instr + 1 + _PyOpcode_Caches[_PyOpcode_Deopt[opcode]]); /* Special case the first instruction, @@ -966,6 +972,10 @@ _PyJit_translate_single_bytecode_to_trace( target = next_inst; } } + else if (uop == _GUARD_LAZY_OUTCOME_NULL || + uop == _NOP || uop == _GUARD_NOT_LAZY_CORO) { + // These don't jump. + } else { int extended_arg = orig_oparg > 255; uint32_t jump_target = next_inst + orig_oparg + extended_arg; @@ -1136,6 +1146,11 @@ _PyJit_TryInitializeTracing( if (oparg > 0xFFFF) { return 0; } + // IS_AWAITED_CALL() needs GET_AWAITABLE in the bytecode, so no + // ENTER_EXECUTOR may replace it. + if (start_instr->op.code == GET_AWAITABLE) { + return 0; + } PyObject *func = PyStackRef_AsPyObjectBorrow(frame->f_funcobj); if (func == NULL || !PyFunction_Check(func)) { return 0; diff --git a/Python/optimizer_cases.c.h b/Python/optimizer_cases.c.h index c86121fcfc0e79..005779c0d2de1c 100644 --- a/Python/optimizer_cases.c.h +++ b/Python/optimizer_cases.c.h @@ -1908,6 +1908,22 @@ break; } + /* _LAZY_CALL_OUTCOME is not a viable micro-op for tier 2 */ + + case _GUARD_LAZY_OUTCOME_NULL: { + break; + } + + case _POP_LAZY_OUTCOME: { + JitOptRef value; + value = sym_new_not_null(ctx); + CHECK_STACK_BOUNDS(-((oparg >> 2) & 1)); + stack_pointer[-1 - ((oparg >> 2) & 1)] = value; + stack_pointer += -((oparg >> 2) & 1); + ASSERT_WITHIN_STACK_BOUNDS(__FILE__, __LINE__); + break; + } + case _SEND_GEN_FRAME: { JitOptRef v; JitOptRef receiver; @@ -1978,6 +1994,12 @@ break; } + /* _CHECK_LAZY_CORO is not a viable micro-op for tier 2 */ + + case _GUARD_NOT_LAZY_CORO: { + break; + } + case _YIELD_VALUE: { JitOptRef retval; JitOptRef value; @@ -4290,6 +4312,8 @@ break; } + /* _START_LAZY_CORO is not a viable micro-op for tier 2 */ + case _GUARD_NOS_NULL: { JitOptRef null; null = stack_pointer[-2]; @@ -5596,6 +5620,8 @@ break; } + /* _MAYBE_LAZY_CORO is not a viable micro-op for tier 2 */ + case _SAVE_RETURN_OFFSET: { break; } diff --git a/Python/record_functions.c.h b/Python/record_functions.c.h index 98abe3d0505e20..cd2ff022f48eb1 100644 --- a/Python/record_functions.c.h +++ b/Python/record_functions.c.h @@ -171,10 +171,14 @@ const _PyOpcodeRecordEntry _PyOpcode_RecordEntries[256] = { [LOAD_ATTR_METHOD_LAZY_DICT] = {1, {_RECORD_TOS_INDEX}}, [CALL] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_PY_GENERAL] = {1, {_RECORD_CALLABLE_INDEX}}, + [CALL_PY_GENERAL_AWAITED] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_BOUND_METHOD_GENERAL] = {1, {_RECORD_CALLABLE_INDEX}}, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_NON_PY_GENERAL] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_BOUND_METHOD_EXACT_ARGS] = {1, {_RECORD_CALLABLE_INDEX}}, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_PY_EXACT_ARGS] = {1, {_RECORD_CALLABLE_INDEX}}, + [CALL_PY_EXACT_ARGS_AWAITED] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_TYPE_1] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_STR_1] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_TUPLE_1] = {1, {_RECORD_CALLABLE_INDEX}}, @@ -191,7 +195,9 @@ const _PyOpcodeRecordEntry _PyOpcode_RecordEntries[256] = { [CALL_METHOD_DESCRIPTOR_NOARGS] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_METHOD_DESCRIPTOR_FAST] = {1, {_RECORD_CALLABLE_INDEX}}, [CALL_KW_PY] = {1, {_RECORD_CALLABLE_KW_INDEX}}, + [CALL_KW_PY_AWAITED] = {1, {_RECORD_CALLABLE_KW_INDEX}}, [CALL_KW_BOUND_METHOD] = {1, {_RECORD_CALLABLE_KW_INDEX}}, + [CALL_KW_BOUND_METHOD_AWAITED] = {1, {_RECORD_CALLABLE_KW_INDEX}}, [CALL_KW] = {1, {_RECORD_CALLABLE_KW_INDEX}}, [CALL_KW_NON_PY] = {1, {_RECORD_CALLABLE_KW_INDEX}}, [CALL_FUNCTION_EX] = {1, {_RECORD_4OS_INDEX}}, @@ -229,10 +235,14 @@ const _PyOpcodeRecordSlotMap _PyOpcode_RecordSlotMaps[256] = { [LOAD_ATTR_NONDESCRIPTOR_NO_DICT] = {1, 1, {0}}, [LOAD_ATTR_METHOD_LAZY_DICT] = {1, 1, {0}}, [CALL_PY_GENERAL] = {1, 0, {0}}, + [CALL_PY_GENERAL_AWAITED] = {1, 0, {0}}, [CALL_BOUND_METHOD_GENERAL] = {1, 1, {0}}, + [CALL_BOUND_METHOD_GENERAL_AWAITED] = {1, 1, {0}}, [CALL_NON_PY_GENERAL] = {1, 0, {0}}, [CALL_BOUND_METHOD_EXACT_ARGS] = {1, 1, {0}}, + [CALL_BOUND_METHOD_EXACT_ARGS_AWAITED] = {1, 1, {0}}, [CALL_PY_EXACT_ARGS] = {1, 0, {0}}, + [CALL_PY_EXACT_ARGS_AWAITED] = {1, 0, {0}}, [CALL_ALLOC_AND_ENTER_INIT] = {1, 0, {0}}, [CALL_BUILTIN_CLASS] = {1, 0, {0}}, [CALL_BUILTIN_O] = {1, 0, {0}}, @@ -242,7 +252,9 @@ const _PyOpcodeRecordSlotMap _PyOpcode_RecordSlotMaps[256] = { [CALL_METHOD_DESCRIPTOR_FAST_WITH_KEYWORDS] = {1, 0, {0}}, [CALL_METHOD_DESCRIPTOR_NOARGS] = {1, 0, {0}}, [CALL_KW_PY] = {1, 0, {0}}, + [CALL_KW_PY_AWAITED] = {1, 0, {0}}, [CALL_KW_BOUND_METHOD] = {1, 0, {0}}, + [CALL_KW_BOUND_METHOD_AWAITED] = {1, 0, {0}}, [CALL_EX_PY] = {1, 0, {0}}, [BINARY_OP] = {2, 2, {1, 0}}, }; diff --git a/Python/specialize.c b/Python/specialize.c index b5cf4ebc31142a..5e0e29ade1ddf2 100644 --- a/Python/specialize.c +++ b/Python/specialize.c @@ -1751,6 +1751,16 @@ specialize_method_descriptor(PyMethodDescrObject *descr, PyObject *self_or_null, return 0; } +static bool +is_awaited_coroutine_call(_Py_CODEUNIT *instr, int cache_entries, + PyCodeObject *code) +{ + _Py_CODEUNIT next = instr[1 + cache_entries]; + return (next.op.code == GET_AWAITABLE && + (next.op.arg & GET_AWAITABLE_AWAITED_CALL) && + (code->co_flags & CO_COROUTINE)); +} + static int specialize_py_call(PyFunctionObject *func, _Py_CODEUNIT *instr, int nargs, bool bound_method) @@ -1782,7 +1792,17 @@ specialize_py_call(PyFunctionObject *func, _Py_CODEUNIT *instr, int nargs, } write_u32(cache->func_version, version); uint8_t opcode; - if (argcount == nargs + bound_method) { + if (is_awaited_coroutine_call(instr, INLINE_CACHE_ENTRIES_CALL, code)) { + if (argcount == nargs + bound_method) { + opcode = bound_method ? CALL_BOUND_METHOD_EXACT_ARGS_AWAITED + : CALL_PY_EXACT_ARGS_AWAITED; + } + else { + opcode = bound_method ? CALL_BOUND_METHOD_GENERAL_AWAITED + : CALL_PY_GENERAL_AWAITED; + } + } + else if (argcount == nargs + bound_method) { opcode = bound_method ? CALL_BOUND_METHOD_EXACT_ARGS : CALL_PY_EXACT_ARGS; } @@ -1820,7 +1840,13 @@ specialize_py_call_kw(PyFunctionObject *func, _Py_CODEUNIT *instr, int nargs, return -1; } write_u32(cache->func_version, version); - specialize(instr, bound_method ? CALL_KW_BOUND_METHOD : CALL_KW_PY); + if (is_awaited_coroutine_call(instr, INLINE_CACHE_ENTRIES_CALL_KW, code)) { + specialize(instr, bound_method ? CALL_KW_BOUND_METHOD_AWAITED + : CALL_KW_PY_AWAITED); + } + else { + specialize(instr, bound_method ? CALL_KW_BOUND_METHOD : CALL_KW_PY); + } return 0; }