8946 Commits

Author SHA1 Message Date
Sergey Miryanov
10bec7c1eb GH-141312: Allow only integers to longrangeiter_setstate state (GH-141317)
This fixes an assertion error when the new computed start is not an integer.
2025-11-14 14:52:01 +00:00
Victor Stinner
3bacae5598 gh-131510: Use PyUnstable_Unicode_GET_CACHED_HASH() (GH-141520)
Replace code that directly accesses PyASCIIObject.hash with
PyUnstable_Unicode_GET_CACHED_HASH().

Remove redundant "assert(PyUnicode_Check(op))" from
PyUnstable_Unicode_GET_CACHED_HASH(), _PyASCIIObject_CAST() already
implements the check.
2025-11-14 11:13:24 +01:00
Petr Viktorin
a4dd66275b gh-140550: Use a bool for the Py_mod_gil value (GH-141519)
This needs a single bit, but was stored as a void* in the module
struct. This didn't matter due to packing, but now that there's
another bool in the struct, we can save a bit of memory by
making md_gil a bool.

Variables that changed type are renamed, to detect conflicts.
2025-11-14 10:38:49 +01:00
Ken Jin
4fa80ce74c gh-139109: A new tracing JIT compiler frontend for CPython (GH-140310)
This PR changes the current JIT model from trace projection to trace recording. Benchmarking: better pyperformance (about 1.7% overall) geomean versus current https://raw.githubusercontent.com/facebookexperimental/free-threading-benchmarking/refs/heads/main/results/bm-20251108-3.15.0a1%2B-7e2bc1d-JIT/bm-20251108-vultr-x86_64-Fidget%252dSpinner-tracing_jit-3.15.0a1%2B-7e2bc1d-vs-base.svg, 100% faster Richards on the most improved benchmark versus the current JIT. Slowdown of about 10-15% on the worst benchmark versus the current JIT. **Note: the fastest version isn't the one merged, as it relies on fixing bugs in the specializing interpreter, which is left to another PR**. The speedup in the merged version is about 1.1%. https://raw.githubusercontent.com/facebookexperimental/free-threading-benchmarking/refs/heads/main/results/bm-20251112-3.15.0a1%2B-f8a764a-JIT/bm-20251112-vultr-x86_64-Fidget%252dSpinner-tracing_jit-3.15.0a1%2B-f8a764a-vs-base.svg

Stats: 50% more uops executed, 30% more traces entered the last time we ran them. It also suggests our trace lengths for a real trace recording JIT are too short, as a lot of trace too long aborts https://github.com/facebookexperimental/free-threading-benchmarking/blob/main/results/bm-20251023-3.15.0a1%2B-eb73378-CLANG%2CJIT/bm-20251023-vultr-x86_64-Fidget%252dSpinner-tracing_jit-3.15.0a1%2B-eb73378-pystats-vs-base.md .

This new JIT frontend is already able to record/execute significantly more instructions than the previous JIT frontend. In this PR, we are now able to record through custom dunders, simple object creation, generators, etc. None of these were done by the old JIT frontend. Some custom dunders uops were discovered to be broken as part of this work gh-140277

The optimizer stack space check is disabled, as it's no longer valid to deal with underflow.

Pros:
* Ignoring the generated tracer code as it's automatically created, this is only additional 1k lines of code. The maintenance burden is handled by the DSL and code generator.
* `optimizer.c` is now significantly simpler, as we don't have to do strange things to recover the bytecode from a trace.
* The new JIT frontend is able to handle a lot more control-flow than the old one.
* Tracing is very low overhead. We use the tail calling interpreter/computed goto interpreter to switch between tracing mode and non-tracing mode. I call this mechanism dual dispatch, as we have two dispatch tables dispatching to each other. Specialization is still enabled while tracing.
* Better handling of polymorphism. We leverage the specializing interpreter for this.

Cons:
* (For now) requires tail calling interpreter or computed gotos. This means no Windows JIT for now :(. Not to fret, tail calling is coming soon to Windows though https://github.com/python/cpython/pull/139962

Design:
* After each instruction, the `record_previous_inst` function/label is executed. This does as the name suggests.
* The tracing interpreter lowers bytecode to uops directly so that it can obtain "fresh" values at the point of lowering.
* The tracing version behaves nearly identical to the normal interpreter, in fact it even has specialization! This allows it to run without much of a slowdown when tracing. The actual cost of tracing is only a function call and writes to memory.
* The tracing interpreter uses the specializing interpreter's deopt to naturally form the side exit chains. This allows it to side exit chain effectively, without repeating much code. We force a re-specializing when tracing a deopt.
* The tracing interpreter can even handle goto errors/exceptions, but I chose to disable them for now as it's not tested.
* Because we do not share interpreter dispatch, there is should be no significant slowdown to the original specializing interpreter on tailcall and computed got with JIT disabled. With JIT enabled, there might be a slowdown in the form of the JIT trying to trace.
* Things that could have dynamic instruction pointer effects are guarded on. The guard deopts to a new instruction --- `_DYNAMIC_EXIT`.
2025-11-13 18:08:32 +00:00
Cody Maloney
732224e113 gh-139871: Add bytearray.take_bytes([n]) to efficiently extract bytes (GH-140128)
Update `bytearray` to contain a `bytes` and provide a zero-copy path to
"extract" the `bytes`. This allows making several code paths more efficient.

This does not move any codepaths to make use of this new API. The documentation
changes include common code patterns which can be made more efficient with
this API.

---

When just changing `bytearray` to contain `bytes` I ran pyperformance on a
`--with-lto --enable-optimizations --with-static-libpython` build and don't see
any major speedups or slowdowns with this; all seems to be in the noise of
my machine (Generally changes under 5% or benchmarks that don't touch
bytes/bytearray).


Co-authored-by: Victor Stinner <vstinner@python.org>
Co-authored-by: Maurycy Pawłowski-Wieroński <5383+maurycy@users.noreply.github.com>
2025-11-13 13:19:44 +00:00
Sergey B Kirpichev
e2026731f5 gh-141004: soft-deprecate Py_INFINITY macro (#141033)
Co-authored-by: Victor Stinner <vstinner@python.org>
2025-11-12 13:44:49 +01:00
Sergey B Kirpichev
23d85a2a3f gh-141042: fix sNaN's packing for mixed floating-point formats (#141107) 2025-11-12 11:06:29 +01:00
Alper
298e9074cd gh-140476: optimize PySet_Add for frozenset in free-threading (#140440)
Avoids critical section in `PySet_Add` when adding items to newly created frozensets.

Co-authored-by: Kumar Aditya <kumaraditya@python.org>
2025-11-12 01:57:21 +05:30
Kumar Aditya
7211a34fe1 gh-132657: optimize PySet_Contains for frozenset (#141183) 2025-11-11 20:02:32 +05:30
Victor Stinner
8435a2278f gh-141376: Fix exported symbols (GH-141377)
* gh-141376: Fix exported symbols

* _io module: add "_Py_" prefix to "spec" variables. For example,
  rename bufferedrandom_spec to _Py_bufferedrandom_spec.
* typevarobject.c: add "static" to "spec" and "slots" variables.
* import.c: add "static" to "pkgcontext" variable.

* No longer export textiowrapper_slots
2025-11-11 09:21:24 +01:00
Bénédikt Tran
ae1f435071 gh-111389: replace deprecated occurrences of _PyHASH_* macros (#141236) 2025-11-09 15:14:08 +01:00
Stan Ulbrych
d6c89a2df2 gh-140939: Fix memory leak in _PyBytes_FormatEx error path (#140957) 2025-11-06 11:20:57 +05:30
Edward Xu
b83f379a97 gh-133467: Fix typeobject tp_base race in free threading (gh-140549) 2025-11-05 16:20:40 -05:00
Petr Viktorin
589a03a8ce gh-140550: Initial implementation of PEP 793 – PyModExport (GH-140556)
Co-authored-by: Victor Stinner <vstinner@python.org>
Co-authored-by: Kumar Aditya <kumaraditya@python.org>
2025-11-05 12:31:42 +01:00
Victor Stinner
a84181c31b gh-140815: Fix faulthandler for invalid/freed frame (#140921)
faulthandler now detects if a frame or a code object is invalid or
freed.

Add helper functions:

* _PyCode_SafeAddr2Line()
* _PyFrame_SafeGetCode()
* _PyFrame_SafeGetLasti()

_PyMem_IsPtrFreed() now detects pointers in [-0xff, 0xff] range
as freed.
2025-11-04 11:48:28 +01:00
Jelle Zijlstra
7a9437d986 gh-140348: Fix using | on unusual objects plus Unions (#140383) 2025-11-03 06:50:37 -08:00
Sergey Miryanov
da65f38a94 gh-134786: raise error if Py_TPFLAGS_MANAGED_WEAKREF or Py_TPFLAGS_MANAGED_DICT is used without Py_TPFLAGS_HAVE_GC set (#135863) 2025-11-02 16:34:49 +05:30
Mikhail Efimov
d17f28fed5 gh-140373: Correctly emit PY_UNWIND event when generator is closed (GH-140767) 2025-10-31 10:09:22 +00:00
Stan Ulbrych
a3ce2f77f0 gh-55531: Implement normalize_encoding in C (#136643)
Closes gh-55531
2025-10-30 15:31:47 +01:00
Victor Stinner
efc37ba49e gh-139353: Add Objects/unicode_writer.c file (#139911)
Move the public PyUnicodeWriter API and the private _PyUnicodeWriter
API to a new Objects/unicode_writer.c file.

Rename a few helper functions to share them between unicodeobject.c
and unicode_writer.c, such as resize_compact() or unicode_result().
2025-10-30 14:36:15 +01:00
Stan Ulbrych
dbe3950a76 gh-129117: Add unicodedata.isxidstart() function (#140269)
Expose `_PyUnicode_IsXidContinue/Start` in `unicodedata`:
add isxidstart() and isxidcontinue() functions.

Co-authored-by: Victor Stinner <vstinner@python.org>
2025-10-30 10:18:12 +00:00
Mikhail Efimov
02202c117b gh-140551: Fix dict crash if clear is called at lookup stage (#140558)
Co-authored-by: Inada Naoki <songofacandy@gmail.com>
2025-10-29 14:36:23 +05:30
Shamil
7d70a147f5 Remove dead stores to 'size' in UTF-8 decoder (unicodeobject.c) (#140637) 2025-10-27 11:55:57 +03:00
Kumar Aditya
df07364106 gh-140544: use faster _PyInterpreterState_GET for type lock (#140584) 2025-10-25 14:53:26 +00:00
Sam Gross
574405c19e gh-140431: Fix GC crash due to partially initialized coroutines (gh-140470)
The `make_gen()` function creates and tracks generator/coro objects, but
doesn't fully initialize all the fields. At a minimum, we need to
initialize all the fields that may be accessed by gen_traverse because
the call to `compute_cr_origin()` can trigger a GC.
2025-10-23 10:18:13 -04:00
Emma Smith
a8edca62fc gh-132835: Add defensive NULL checks to MRO resolution (GH-134763)
Currently, there are a few places where tp_mro could theoretically
become NULL, but do not in practice. This commit adds defensive checks for
NULL values to ensure that any changes do not introduce a crash and that
state invariants are upheld.

The assertions added in this commit are all instances where a NULL value would get passed to something not expecting a NULL, so it is better to catch an assertion failure than crash later on.

There are a few cases where it is OK for the return of lookup_tp_mro to be NULL, such as when passed to is_subtype_with_mro, which handles this explicitly.
2025-10-21 14:48:29 -07:00
Mark Shannon
0c01090ad9 GH-139951: Fix major GC performance regression (GH-140262)
* Count number of actually tracked objects, instead of trackable objects. This ensures that untracking tuples has the desired effect of reducing GC overhead

* Do not track most untrackable tuples during creation. This prevents large numbers of small tuples causing execessive GCs.
2025-10-21 15:22:15 +01:00
Peter Bierma
71db05a12d gh-140406: Fix memory leak upon __hash__ returning a non-integer (GH-140411) 2025-10-21 08:10:01 -04:00
Petr Viktorin
ea4cc585cd gh-139817: Fix refleak in TypeAliasType(qualname=non_string) (GH-140197) 2025-10-16 11:04:04 +00:00
Mikhail Efimov
f673f0e7b4 gh-139817: Attribute __qualname__ is added to TypeAliasType (#139919) 2025-10-15 09:08:17 -07:00
Sergey Miryanov
32c264982e gh-140061: Use _PyObject_IsUniquelyReferenced() to check if objects are uniquely referenced (gh-140062)
The previous `Py_REFCNT(x) == 1` checks can have data races in the free
threaded build. `_PyObject_IsUniquelyReferenced(x)` is a more conservative
check that is safe in the free threaded build and is identical to
`Py_REFCNT(x) == 1` in the default GIL-enabled build.
2025-10-15 09:48:21 -04:00
Cody Maloney
6416e6ebe5 gh-129559: Remove extra dot in bytearray.resize AC (#140134) 2025-10-15 02:39:17 +00:00
Neil Schemenauer
1e1f435196 gh-140126: Fix compile error if --with-assertions is enabled (#140133)
The `types_world_is_stopped()` function needs to be defined if NDEBUG
is not defined.
2025-10-14 23:34:30 +00:00
Sergey Miryanov
ded59f7e8e GH-140058: Clear key and value if PyTuple_New fails in dictiter_iternextitem (#140059) 2025-10-14 18:15:39 +05:30
Mikhail Efimov
be60e4b4f3 gh-140000: Traverse name attribute for TypeVar, TypeVarTuple, TypeAliasType, ParamSpec (#140016) 2025-10-13 13:10:39 -07:00
Kumar Aditya
6481539a6d gh-125996: fix thread safety of collections.OrderedDict (#133734) 2025-10-13 22:55:07 +05:30
Pieter Eendebak
e6aa515296 gh-140009: Improve performance of list_extend_dictitems by using PyTuple_FromArray (#140010) 2025-10-13 15:58:25 +05:30
Bénédikt Tran
6710156bd2 gh-139988: fix a leak when failing to create a Union type (#139990) 2025-10-12 12:51:44 +02:00
Victor Stinner
166cdaa6fb gh-111489: Remove _PyTuple_FromArray() alias (#139973)
Replace _PyTuple_FromArray() with PyTuple_FromArray().
Remove pycore_tuple.h includes.
2025-10-11 22:58:14 +02:00
Dino Viehland
ff7bb565d8 gh-139924: Add PyFunction_PYFUNC_EVENT_MODIFY_QUALNAME event for function watchers (#139925)
Add PyFunction_PYFUNC_EVENT_MODIFY_QUALNAME event for function watchers
2025-10-10 15:25:38 -07:00
Victor Stinner
4c119714d5 gh-139353: Add Objects/unicode_format.c file (#139491)
* Move PyUnicode_Format() implementation from unicodeobject.c
  to unicode_format.c.
* Replace unicode_modifiable() with _PyUnicode_IsModifiable()
* Add empty lines to have two empty lines between functions.
2025-10-10 12:52:59 +02:00
Victor Stinner
e31c22dbf9 gh-111489: Add PyTuple_FromArray() function (#139691) 2025-10-10 08:54:12 +02:00
Victor Stinner
3d3f126e86 gh-139353: Rename formatter_unicode.c to unicode_formatter.c (#139723)
* Move Python/formatter_unicode.c to Objects/unicode_formatter.c.
* Move Objects/stringlib/localeutil.h content into
  unicode_formatter.c. Remove localeutil.h.
* Move _PyUnicode_InsertThousandsGrouping() to unicode_formatter.c
  and mark the function as static.
* Rename unicode_fill() to _PyUnicode_Fill() and export it in
  pycore_unicodeobject.h.
* Move MAX_UNICODE to pycore_unicodeobject.h as _Py_MAX_UNICODE.
2025-10-08 14:56:00 +02:00
Sergey Miryanov
e6e376a760 gh-132042: Remove resolve_slotdups() to speedup class creation (#132156)
Co-authored-by: Victor Stinner <vstinner@python.org>
Co-authored-by: sobolevn <mail@sobolevn.me>
Co-authored-by: Kumar Aditya <kumaraditya@python.org>
2025-10-03 11:58:00 +02:00
Victor Stinner
e9c538dd54 gh-139156: Optimize _PyUnicode_EncodeCharmap() (#139306)
Specialize _PyUnicode_EncodeCharmap() for EncodingMapType which is
used by Python codecs such as iso8859_15.
2025-09-25 11:42:16 +02:00
Victor Stinner
8d83b7df3f gh-139156: Optimize the UTF-7 encoder (#139253)
Remove base64SetO and base64WhiteSpace parameters.
2025-09-24 17:57:29 +02:00
Victor Stinner
c7b11b7546 gh-139156: Use PyBytesWriter in PyUnicode_EncodeCodePage() (#139259)
Replace PyBytes_FromStringAndSize() and _PyBytes_Resize() with the
PyBytesWriter API.
2025-09-24 16:39:40 +02:00
Victor Stinner
c9a79a02a8 gh-139156: Use PyBytesWriter in _PyUnicode_EncodeCharmap() (#139251)
Replace PyBytes_FromStringAndSize() and _PyBytes_Resize() with the
PyBytesWriter API.

Add _PyBytesWriter_GetSize() and _PyBytesWriter_GetData() static
inline functions.
2025-09-24 16:15:34 +02:00
Bénédikt Tran
a5e0562350 gh-133644: remove PyWeakref_GetObject and PyWeakref_GET_OBJECT (GH-133657) 2025-09-24 11:25:56 +02:00
Victor Stinner
dd45179fa0 gh-129813, PEP 782: Remove the private _PyBytesWriter API (#139264)
It is now replaced with the new public PyBytesWriter API (PEP 782).
2025-09-23 15:29:55 +00:00