Repository navigation
C API fast paths that keep the object representation - #21
Draft
Ivo Horák (horakivo) wants to merge 9 commits into
Draft
Ivo Horák (horakivo) wants to merge 9 commits into
Ivo Horák (horakivo) wants to merge 9 commits into
Conversation
…OS/aarch64 GraalPy's sysconfig set OPT to "-DNDEBUG" only, so C extensions built through it were compiled without optimisation (CPython uses "-DNDEBUG -g -O3 -Wall"). Use "-DNDEBUG -O3" on all platforms except Windows. On darwin-aarch64, build libpythonvm with -H:-RandomizeRuntimeCodeCache. macOS ignores address hints for MAP_JIT mappings, so with the randomisation every runtime-compiled method lands far (hundreds of GB) away from libpythonvm and the C extensions, and Apple cores predict indirect calls across that distance poorly. Without a hint the code cache is mapped next to the (ASLR-slid) libraries. The trade-off is that the code cache loses its own address randomisation on this platform; the flag is not added if the user sets either form of it.
…rint - _PyType_AllocNoTrack allocates with PyObject_Calloc instead of malloc plus memset, and _GraalPyMem_RawCalloc uses calloc for the whole block, so pages of a large object that are never written stay non-resident. - On macOS and Linux, zeroed blocks of 256 KB or more are mapped with mmap and unmapped on free: the system allocator keeps freed large blocks in a cache, and calloc of a reused block zeroes (and so touches) all of it. - The native-memory barrier counts requested bytes. Before forcing a full Java collection, check the resident footprint of the process: if it grew by less than half a barrier since the last collection, allow another barrier's worth of requests (up to the configured maximum). - After a forced collection, wait for the reference handler in short steps (100 us, draining the reference queue) instead of collecting again after fixed delays.
PyDict_Next was an upcall per step. C now keeps a mirror of a dict's entry table: borrowed (key, value) pointers indexed by the storage's iteration position, the same position space as _PyDict_Next. The mirror is built on the second step of a pass and lives in a small direct-mapped cache keyed by the dict pointer. Validity rests on a "Java ran" epoch (CApiEpoch): one native word that Java bumps on entry of every downcall, on exit of every upcall (generated C API wrappers and the closures that go through GilNode.UncachedAcquire) and whenever a thread acquires the GIL. A dict can only change while Java runs, so an unchanged epoch means an unchanged dict. A mirror is refused if the epoch moved while it was filled, and a stale mirror falls back to _PyDict_Next. Entries are promoted before a mirror is built, so the borrowed pointers live as long as the dict holds the entries. GRAALPY_DICT_MIRROR=0 disables the mirror, GRAALPY_DICT_MIRROR=2 checks every mirror hit against _PyDict_Next and reports counts at exit.
C code that calls the ml_meth of a GraalPy builtin (PyCFunctionWrapper) and the lenfunc/hashfunc/inquiry slot wrappers ran uncached nodes on every call. Each wrapper now forwards to one root node of its own (cached argument conversion, argument creation with the builtin's positional and keyword-only defaults, direct call, exception transfer, epoch bump), which the JIT compiles per wrapper so the target is a constant. This also fixes calls through ml_meth of builtins that have keyword-only defaults (e.g. sorted, min, max), which raised "missing keyword-only argument".
- Py_TYPE and Py_REFCNT are inline: a native object or a stub is read directly, tagged ints and floats have fixed types and are immortal. The exported functions stay for the ABI. PyFloat_AS_DOUBLE reads a native float object directly. - PyType_IsSubtype answers PyFloat_Check, and subtype tests against a type whose instance layout differs from its base's, from the tp_base chain instead of the MRO tuple; the MRO walk is kept out of line. - PyThread_get_thread_ident reads the thread id from the thread's native PyThreadState. - Reading the current exception after a downcall does not store anything when C set no exception (the common case). - _PyObject_GetDictPtr is not called for a native object whose type has neither a managed dict nor a tp_dictoffset.
A list's native stub is now a GraalPyVarObject like a tuple's. Its ob_size and ob_item are valid while the list's storage is empty or is native storage attached to that list; otherwise ob_size is -1 and C asks Java. Java keeps the fields current in two places only: PTupleListBase's storage replacement (out of line, only for lists that have a stub) and the length and pointer setters of the attached native storage. With that, PyList_GetItem, PyList_Size, Py_SIZE of a list and PyList_Type's sq_length/mp_length are answered in C, and list.clear's ml_meth is a C function that returns at once for an empty list and calls PyList_Clear otherwise. Every stub now has at least the GraalPyVarObject fields, zeroed. Compiled list append of a list without a stub keeps the code path without the stub sync, so pure-Python appends compile as before.
A range whose bounds are outside the int range but whose values all fit a Java long (e.g. range(2**32, 2**32 + n)) is iterated with longs instead of BigInteger values wrapped in PInt, in the iterator builtins and in the bytecode interpreter's for-loop iteration.
graalpy_list_stub took every pointer with the handle bit as a stub and read its type from the stub memory. Tagged ints and floats also have the handle bit set but are immediates, so PyList_Size(23) or PyList_GetItem(42, 1) dereferenced an invalid address and crashed (test_capi.test_list) instead of raising SystemError. Only pointers whose top three bits are 0b100 are stubs; the other inline list paths (sq_length, mp_length, list.clear) already checked that.
The lenfunc/hashfunc/inquiry slot wrappers each created their own upcall
root node, bound to the language of the context that created the
wrapper. Wrappers of builtin slots hang off static slot objects and are
shared by all contexts, so a context with a different sharing layer
executed a node of another layer ("Invalid sharing of AST nodes
detected", multi-context tests, cpyext test_nb_bool).
The roots are now created once per language and kind
(PythonLanguage.getSlotUpcallCallTarget) and the wrapper is passed as an
argument. The PyCFunctionWrapper roots stay per wrapper: those wrappers
are cached per context (CApiContext) and only that context calls them.
Merging this PR will improve performance by ×3.21 warning
Performance ChangesTip Curious why performance improved? Comment Comparing |
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 yet. C API fast paths that do not change how Python objects are represented. They are the base for #22, which adds native copies of value types; keeping them separate lets the benchmarks show each part on its own.
What this changes
libpythonvmon macOS/aarch64, where calls across a large distance are slow; that part does nothing on Linux.calloc-style allocation instead of allocate-then-clear, large zeroed blocks mapped directly, and the native-memory collection trigger looks at the resident footprint.PyDict_Nextreads a native copy of the entry table instead of calling into Java for every entry. The copy is checked against a counter that changes whenever Java code ran.ml_methfor builtins with keyword-only arguments such assorted,minandmax.Py_TYPE,Py_REFCNT, type checks and the thread identifier for common cases.PyList_GET_SIZE,PyList_GET_ITEMand the list length slots read native data for lists that C has seen.rangewhose values fit 64 bits no longer produces big integers.Known limits
-O3can expose undefined behaviour in extensions that-O0hid./proc/self/statm, which counts file-backed pages, unlike the macOS figure.Py_TYPE/Py_REFCNTpaths assume that native pointers have the top bit clear.Testing
The C API test suite passed on a native standalone built from the tip of #22 (macOS/aarch64): 765 run, 756 passed, 9 skipped, 0 failures. No performance numbers here; the benchmark run of this pull request is the measurement.
🤖 Generated with Claude Code