Repository navigation
Native copies of int, float, complex and str for C extensions - #22
Draft
Ivo Horák (horakivo) wants to merge 3 commits into
Draft
Ivo Horák (horakivo) wants to merge 3 commits into
Ivo Horák (horakivo) wants to merge 3 commits into
Conversation
Values that cross into C no longer always get a Java wrapper plus a native stub. Shared native state (NativeComplex): one native block holds the allocators that C and Java share without upcalls, the borrowed-reference stack and the downcall depth. Generated downcall invokers (and vectorcall slot calls) enter and leave the depth; when the outermost downcall returns, the counts on the borrowed stack are dropped. - complex: an exact complex is passed to C as a native PyComplexObject from a size-class allocator. A list of exact complex values stores counted pointers to such structs (ComplexPtrSequenceStorage); PComplex keeps an unowned pointer and serial so a value read from such a list is the same object when stored or passed again. PyComplex_FromDoubles and exact complex allocation/deallocation in C use the same allocator. - int: an exact int that does not fit the tagged pointer (up to 120 bits) is passed as a native PyLongObject with no Java companion; the Java value stays a long. PyLong_From*/PyLong_As* handle these in C. - float: an exact float that cannot be tagged is passed as a native PyFloatObject from a 64-byte small-block pool that PyObject_Malloc and Java share. An instance of a static native float subclass that is only (type, ob_fval) is held in Java as a value copy (PNativeFloat) instead of a native object with a weak reference and lookup entry. Lifetime: a copy passed as an argument or borrowed result holds a count on the borrowed stack until the outermost C call returns; C that increfs it keeps it. Items that a container holds (dict and list items, PyDict_Next) are still promoted to objects with stable stubs, as before. A copy that C keeps without its own reference past the outermost call is freed under it. Also included, experimental and opt-in: classes with __slots__ that set __native_layout__ = True (and derive directly from object) get instances whose slots live in native reference-counted structs, with a pointer-aware list storage for them and pins on dict, cell, global and attribute stores. No class in the standard library or the tests sets it. The pins, the list storage and the struct paths are guarded by an assumption that holds until such a class is created. What runs for every program: a bytecode fast path for stores to __slots__ attributes (shape- cached, like the existing load fast path), and a profiled "native instance" type check on slot reads and writes. __graalpython__ gains measurement helpers: complex_counters, native_long_live, slots_counters (counters need -Dgraalpy.complexCounters or -Dgraalpy.slotsCounters) and native_quiesce.
An exact str that is a bare Java string (TruffleString) and that C gets as an argument or as a new reference is now a CPython 3.13 compact unicode object in malloc'd memory (PyASCIIObject or PyCompactUnicodeObject with the characters inline, kind chosen from the string's code range), with no PString wrapper, no stub and no handle. C reads it with CPython's own layout, so PyUnicode_GET_LENGTH, KIND, DATA, READ and PyUnicode_AsUTF8AndSize run without entering Java. PyObject_Hash (same value as Java's hash), PyUnicode_Compare, PyUnicode_CompareWithASCIIString and PyUnicode_EqualToUTF8AndSize have C paths for these objects, and PyUnicode_InternInPlace answers from a C cache of interned stubs. Strings created by C (PyUnicode_New, PyUnicode_FromStringAndSize, PyUnicode_FromString, PyUnicode_DecodeUTF8[Stateful] for valid input, PyUnicode_FromKindAndData) are born in that layout and become Java strings only when Java reads them. PyUnicode_Resize is implemented (it was not) and resizes an unshared native string in place. Identity: the struct's padding word holds a mark bit and an index into a 4096-entry ring that maps it to the Java string it was made from, so f(s) is s holds and a struct handed back to Java is not copied again. The same string passed twice in one call gets one struct. Lifetime: C's reference count owns the struct (unicode_dealloc frees it, or Java when it drops the last count). A borrowed or new-reference copy also holds one count on the borrowed stack until the outermost C call returns. Borrowed and new references to items a container holds (PyTuple_GetItem, PyList_GetItem, PyDict_GetItem*, ...Ref variants, PyCell_Get, items written into native storage, raw invoker calls) keep a stable PString stub as before. str subclasses and strings that are already PString objects take the existing path. GRAALPY_NATIVE_STR=0 turns the scheme off at C API initialization. __graalpython__.native_str_stats() reports live stubs and str counters.
|
…ith memcpy GCC rejects the previous cast of the value field's address to a block pointer under -Werror=strict-aliasing. Clang accepted it. The stored bytes are the same.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Draft, do not merge. Stacked on #21 (the C API fast paths that do not change object representation); review that one first. This PR only adds the two commits on top.
What this changes
Today every Python value that crosses into C gets a Java wrapper plus a native stub (and a handle-table entry), and C reads most of its fields through upcalls into Java. This branch copies simple value types into native CPython-layout structs when C needs them, so C reads them directly, and does not create stubs for them.
Complex, int and float (commit 1)
complexcrosses as a nativePyComplexObjectfrom a size-class allocator. Lists of exact complex values store counted pointers to these structs;PComplexkeeps an unowned pointer and serial so that a value read from such a list stays the same object.intthat does not fit GraalPy's tagged pointer (up to 120 bits) crosses as a nativePyLongObjectwith no Java companion;PyLong_From*/PyLong_As*handle these in C.floatthat cannot be tagged crosses as aPyFloatObjectfrom a 64-byte small-block pool shared byPyObject_Mallocand Java. Instances of static nativefloatsubclasses that are only (type,ob_fval) are held in Java as value copies.PyDict_Next) are still promoted to objects with stable stubs, as before.str (commit 2)
strthat is a bare Java string crosses as a CPython 3.13 compact unicode object in malloc'd memory (no wrapper, no stub, no handle).PyUnicode_GET_LENGTH/KIND/DATA/READandPyUnicode_AsUTF8AndSizerun in C; hash, compare and equality have C paths.PyUnicode_New,PyUnicode_FromStringAndSize, the UTF-8 decoders for valid input, ...) are born in that layout and become Java strings only when Java reads them.PyUnicode_Resizeis implemented.f(s) is sholds and a struct handed back is not copied again.strsubclasses, interned strings and strings that already have a stub keep the existing path.GRAALPY_NATIVE_STR=0turns the scheme off.Lifetime rule (both commits)
C's reference count owns a copy. A copy passed as an argument or returned as a new reference also holds one count until the outermost C call returns; C that increfs it keeps it.
Known problems
GRAALPY_NATIVE_STR=0. Container getters (PyTuple_GetItem,PyList_GetItem,PyDict_GetItem*, ...) return stable stubs, but generic ones (PyObject_GetItem,PySequence_GetItem,PyIter_Next) return copies.complexis larger for all code.PComplexgained three fields (pointer, serial, exact flag), which slows complex-heavy pure Python code (e.g. a Mandelbrot kernel). Some large numpy workloads also use more peak memory.malloc/free) holds in the native standalone; a JVM run with native memory tracking enabled would break it. Onlyunicodeobject.cwas audited for frees of str objects through GraalPy's allocator.__slots__classes as native reference-counted structs (classes that set__native_layout__ = True), with a pointer-aware list storage and pins on stores. Nothing sets it. Its pins, list storage and struct paths are guarded by an assumption that holds until such a class exists; two parts run for every program: a bytecode fast path for stores to__slots__attributes, and a profiled "native instance" type check on slot reads and writes. It is intertwined with the complex list storage and was left in rather than removed.Testing
graalpython/com.oracle.graal.python.benchmarks/python/packages, which check their own results) and a few C API micro benchmarks run for correctness only. No performance numbers here; measurements will follow separately.Not in this pull request
Ordinary objects (instances, dicts, lists) still cross into C through wrappers and stubs. A prototype that gives them native handles which the garbage collector reads exists, but it needs a change in GraalVM's serial collector and is not part of this branch.
🤖 Generated with Claude Code