diff --git a/graalpython/com.oracle.graal.python.cext/include/cpython/floatobject.h b/graalpython/com.oracle.graal.python.cext/include/cpython/floatobject.h index 9642bdf942..e0526ebadf 100644 --- a/graalpython/com.oracle.graal.python.cext/include/cpython/floatobject.h +++ b/graalpython/com.oracle.graal.python.cext/include/cpython/floatobject.h @@ -21,7 +21,10 @@ PyAPI_FUNC(double) GraalPyFloat_AS_DOUBLE(PyObject* op); // Static inline version of PyFloat_AsDouble() trading safety for speed. // It doesn't check if op is a double object. static inline double PyFloat_AS_DOUBLE(PyObject *op) { - // GraalPy change + // GraalPy change: a native float struct (no handle tag, bit 63) is read directly + if (!((uint64_t)(uintptr_t)op & ((uint64_t)1 << 63))) { + return ((PyFloatObject *) op)->ob_fval; + } return GraalPyFloat_AS_DOUBLE(op); } #define PyFloat_AS_DOUBLE(op) PyFloat_AS_DOUBLE(_PyObject_CAST(op)) diff --git a/graalpython/com.oracle.graal.python.cext/include/object.h b/graalpython/com.oracle.graal.python.cext/include/object.h index 7f9101b5b0..e27c97edc8 100644 --- a/graalpython/com.oracle.graal.python.cext/include/object.h +++ b/graalpython/com.oracle.graal.python.cext/include/object.h @@ -319,15 +319,42 @@ _Py_IsOwnedByCurrentThread(PyObject *ob) #endif PyAPI_FUNC(Py_ssize_t) Py_REFCNT(PyObject *ob); +// GraalPy change: inline like Py_TYPE: a native object (no handle tag, bit 63) and a stub +// (tag cleared) are read directly; tagged ints (bit 62) and floats (bit 61) are immortal. The exported +// function Py_REFCNT stays for the ABI and for non-C callers (it does the same, plus a debug-mode check). +static inline Py_ssize_t _GraalPy_REFCNT_inline(PyObject *ob) { + uint64_t bits = (uint64_t)(uintptr_t)ob; + if (!(bits & ((uint64_t)1 << 63))) { + return ob->ob_refcnt; + } + if (bits & (((uint64_t)1 << 62) | ((uint64_t)1 << 61))) { + return _Py_IMMORTAL_REFCNT; + } + return ((PyObject *)(uintptr_t)(bits & ~((uint64_t)1 << 63)))->ob_refcnt; +} #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000 -# define Py_REFCNT(ob) Py_REFCNT(_PyObject_CAST(ob)) +# define Py_REFCNT(ob) _GraalPy_REFCNT_inline(_PyObject_CAST(ob)) #endif // GraalPy public API, mainly for non-C languages that can't use macros PyAPI_FUNC(PyTypeObject*) GraalPy_TYPE(PyObject *ob); // bpo-39573: The Py_SET_TYPE() function must be used to set an object type. +PyAPI_DATA(PyTypeObject) PyLong_Type; +PyAPI_DATA(PyTypeObject) PyFloat_Type; static inline PyTypeObject* Py_TYPE(PyObject *ob) { + // GraalPy change: a native object (no handle tag, bit 63) is read directly; tagged ints + // (bit 62) and floats (bit 61) have fixed types (see graalpy/handles.h and GraalPy_TYPE) + uint64_t bits = (uint64_t)(uintptr_t)ob; + if (!(bits & ((uint64_t)1 << 63))) { + return ob->ob_type; + } + if (bits & ((uint64_t)1 << 62)) { + return &PyLong_Type; + } + if (bits & ((uint64_t)1 << 61)) { + return &PyFloat_Type; + } return GraalPy_TYPE(ob); } #if !defined(Py_LIMITED_API) || Py_LIMITED_API+0 < 0x030b0000 diff --git a/graalpython/com.oracle.graal.python.cext/src/capi.c b/graalpython/com.oracle.graal.python.cext/src/capi.c index b340263c84..c340293058 100644 --- a/graalpython/com.oracle.graal.python.cext/src/capi.c +++ b/graalpython/com.oracle.graal.python.cext/src/capi.c @@ -275,6 +275,8 @@ CAPI_BUILTINS } Py_LOCAL_SYMBOL uint32_t Py_Truffle_Options; +Py_LOCAL_SYMBOL void graalpy_init_list_slots(void); // listobject.c +Py_LOCAL_SYMBOL void graalpy_init_dict_mirror(void); // dictobject.c #undef bool static void initialize_builtin_types_and_structs() { @@ -600,6 +602,10 @@ PyAPI_FUNC(PyThreadState **) initialize_graal_capi(void **builtin_closures, GCSt Py_Truffle_Options = GraalPyPrivate_Native_Options(); initialize_builtin_types_and_structs(); + // GraalPy change: PyDict_Next entry mirror ("Java ran" epoch) + graalpy_init_dict_mirror(); + // GraalPy change: PyList_Type's sq_length/mp_length read the list stub's mirrored ob_size + graalpy_init_list_slots(); // initialize global variables like '_Py_NoneStruct', etc. initialize_globals(tstate); initialize_exceptions(); diff --git a/graalpython/com.oracle.graal.python.cext/src/dictobject.c b/graalpython/com.oracle.graal.python.cext/src/dictobject.c index d12cff53a9..0853f401df 100644 --- a/graalpython/com.oracle.graal.python.cext/src/dictobject.c +++ b/graalpython/com.oracle.graal.python.cext/src/dictobject.c @@ -2862,10 +2862,210 @@ _PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, * the values associated with the keys (but doesn't insert new keys or * delete keys), via PyDict_SetItem(). */ +/* + * PyDict_Next without an upcall per step. + * + * A dict's storage lives in Java. After two consecutive PyDict_Next calls on the same dict (the first at + * position 0) with no Java code having run in between, C asks Java once for a mirror of the entry table: + * (key, value) borrowed pointers indexed by the storage's iteration position (holes are NULL), the same + * position space as _PyDict_Next. Further steps read the mirror while it is valid. Validity: the mirror + * is stamped with the "Java ran" epoch (CApiEpoch.java), which Java bumps on entry of every + * downcall and on exit of every upcall; a dict can only change while Java runs, so an unchanged epoch + * means an unchanged dict. When the epoch has moved, the step goes to _PyDict_Next (as before), and a + * new mirror is built only at the start of the next pass. Entries are promoted by Java (strings, + * large ints, non-float32 floats get objects owned by the dict) before a mirror is built, so the + * borrowed pointers live as long as the dict holds the entries. Mirrors live in a small direct-mapped + * cache keyed by the dict pointer (not in the dict), single-threaded under the GIL. + */ +typedef struct { + PyObject *key; + PyObject *value; +} GraalPyDictMirrorEntry; + +typedef struct { + PyObject *op; /* the dict (NULL: slot empty) */ + uint64_t epoch; /* valid iff equal to *graalpy_dict_epoch */ + Py_ssize_t n; /* index slots */ + GraalPyDictMirrorEntry *entries; +} GraalPyDictMirror; /* 32 bytes; capacity in graalpy_dict_mirror_cap */ + +#define GRAALPY_DICT_MIRRORS 8 /* power of two */ +#define GRAALPY_DICT_MIRROR_MAX (1 << 20) /* larger dicts keep the upcall path (16 MB of mirror) */ + +static uint64_t graalpy_dict_epoch_dummy = 1; +static uint64_t *graalpy_dict_epoch = &graalpy_dict_epoch_dummy; +static GraalPyDictMirror graalpy_dict_mirrors[GRAALPY_DICT_MIRRORS]; +static Py_ssize_t graalpy_dict_mirror_cap[GRAALPY_DICT_MIRRORS]; +/* candidate: the last pass that started at position 0 in Java */ +static PyObject *graalpy_dict_cand_op; +static Py_ssize_t graalpy_dict_cand_pos; +static uint64_t graalpy_dict_cand_epoch; +static int graalpy_dict_mirror_mode = 1; /* 0: off, 1: on, 2: on and every hit verified against Java */ +/* verify-mode statistics (only counted in mode 2) */ +static long long graalpy_dict_stat_builds, graalpy_dict_stat_refused, graalpy_dict_stat_verified; + +static void +graalpy_dict_mirror_report(void) +{ + fprintf(stderr, "GRAALPY_DICT_MIRROR=2: builds %lld refused %lld verified hits %lld\n", + graalpy_dict_stat_builds, graalpy_dict_stat_refused, graalpy_dict_stat_verified); +} + +Py_LOCAL_SYMBOL void +graalpy_init_dict_mirror(void) +{ + graalpy_dict_epoch = (uint64_t *) GraalPyPrivate_Dict_EpochPtr(); + const char *m = getenv("GRAALPY_DICT_MIRROR"); + if (m != NULL) { + graalpy_dict_mirror_mode = atoi(m); + if (graalpy_dict_mirror_mode == 2) { + atexit(graalpy_dict_mirror_report); + } + } +} + +static inline GraalPyDictMirror * +graalpy_dict_mirror_slot(PyObject *op) +{ + return &graalpy_dict_mirrors[((uintptr_t) op >> 4) & (GRAALPY_DICT_MIRRORS - 1)]; +} + +static int graalpy_dict_next_slow(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) __attribute__((noinline)); + +static inline int +graalpy_dict_mirror_next(GraalPyDictMirror *m, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) +{ + Py_ssize_t i = *ppos; + Py_ssize_t n = m->n; + GraalPyDictMirrorEntry *e = m->entries; + if (i < 0) { + return 0; + } + while (i < n && e[i].key == NULL) { + i++; + } + if (i >= n) { + return 0; + } + *ppos = i + 1; + if (pkey) { + *pkey = e[i].key; + } + if (pvalue) { + *pvalue = e[i].value; + } + return 1; +} + +static uint64_t graalpy_dict_verify_epoch[GRAALPY_DICT_MIRRORS]; /* verify mode: the real stamp */ + +static int +graalpy_dict_verify(GraalPyDictMirror *m, PyObject *op, Py_ssize_t pos, int r, Py_ssize_t newpos, PyObject *k, PyObject *v) +{ + Py_ssize_t jpos = pos; + PyObject *jk = NULL, *jv = NULL; + int jr = _PyDict_Next(op, &jpos, &jk, &jv, NULL); + if (jr != r || (r && (jpos != newpos || jk != k || jv != v))) { + fprintf(stderr, "GRAALPY_DICT_MIRROR verify mismatch: dict %p pos %zd: mirror (%d, %zd, %p, %p) java (%d, %zd, %p, %p)\n", + (void *) op, pos, r, newpos, (void *) k, (void *) v, jr, jpos, (void *) jk, (void *) jv); + abort(); + } + graalpy_dict_stat_verified++; + /* the verifying upcall bumped the epoch; nothing changed the dict */ + graalpy_dict_verify_epoch[m - graalpy_dict_mirrors] = *graalpy_dict_epoch; + return r; +} + int PyDict_Next(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) { - return _PyDict_Next(op, ppos, pkey, pvalue, NULL); + /* fast path: a leaf (the slow path is out of line); verify mode (2) never stamps a mirror valid here */ + GraalPyDictMirror *m = graalpy_dict_mirror_slot(op); + if (m->op == op && m->epoch == *graalpy_dict_epoch) { + return graalpy_dict_mirror_next(m, ppos, pkey, pvalue); + } + return graalpy_dict_next_slow(op, ppos, pkey, pvalue); +} + +static int +graalpy_dict_build_mirror(PyObject *op, GraalPyDictMirror *m) +{ + Py_ssize_t *pcap = &graalpy_dict_mirror_cap[m - graalpy_dict_mirrors]; + m->op = NULL; + Py_ssize_t n = GraalPyPrivate_Dict_FillMirror(op, m->entries, *pcap); + if (n > *pcap) { + if (n > GRAALPY_DICT_MIRROR_MAX) { + return 0; + } + Py_ssize_t cap = n < 8 ? 8 : n + n / 4; + GraalPyDictMirrorEntry *e = (GraalPyDictMirrorEntry *) realloc(m->entries, cap * sizeof(GraalPyDictMirrorEntry)); + if (e == NULL) { + return 0; + } + m->entries = e; + *pcap = cap; + n = GraalPyPrivate_Dict_FillMirror(op, m->entries, *pcap); + if (n < 0 || n > *pcap) { + return 0; + } + } else if (n < 0) { + return 0; + } else if (*pcap > 1024 && n < *pcap / 4) { + /* shrink a mirror left by a much larger dict */ + Py_ssize_t cap = n < 8 ? 8 : n + n / 4; + GraalPyDictMirrorEntry *e = (GraalPyDictMirrorEntry *) realloc(m->entries, cap * sizeof(GraalPyDictMirrorEntry)); + if (e != NULL) { + m->entries = e; + *pcap = cap; + } + } + m->n = n; + m->op = op; + /* stamped after the filling upcall returned (its exit bumped the epoch); no Java code ran since */ + if (graalpy_dict_mirror_mode == 2) { + /* verify mode: never valid for the fast path; the slow path checks the real stamp and verifies */ + m->epoch = 0; + graalpy_dict_verify_epoch[m - graalpy_dict_mirrors] = *graalpy_dict_epoch; + } else { + m->epoch = *graalpy_dict_epoch; + } + return 1; +} + +static int +graalpy_dict_next_slow(PyObject *op, Py_ssize_t *ppos, PyObject **pkey, PyObject **pvalue) +{ + Py_ssize_t pos = *ppos; + if (graalpy_dict_mirror_mode == 2) { + GraalPyDictMirror *m = graalpy_dict_mirror_slot(op); + if (m->op == op && graalpy_dict_verify_epoch[m - graalpy_dict_mirrors] == *graalpy_dict_epoch) { + PyObject *k = NULL, *v = NULL; + int r = graalpy_dict_mirror_next(m, ppos, &k, &v); + if (r) { + if (pkey) *pkey = k; + if (pvalue) *pvalue = v; + } + return graalpy_dict_verify(m, op, pos, r, *ppos, k, v); + } + } + if (graalpy_dict_mirror_mode != 0 && pos != 0 && op == graalpy_dict_cand_op && pos == graalpy_dict_cand_pos && + graalpy_dict_cand_epoch == *graalpy_dict_epoch) { + /* second step of a pass that started at 0, nothing ran in Java since: mirror the dict */ + graalpy_dict_cand_op = NULL; + GraalPyDictMirror *m = graalpy_dict_mirror_slot(op); + if (graalpy_dict_build_mirror(op, m)) { + graalpy_dict_stat_builds += graalpy_dict_mirror_mode == 2; + return graalpy_dict_mirror_next(m, ppos, pkey, pvalue); + } + graalpy_dict_stat_refused += graalpy_dict_mirror_mode == 2; + } + int r = _PyDict_Next(op, ppos, pkey, pvalue, NULL); + if (pos == 0 && r) { + graalpy_dict_cand_op = op; + graalpy_dict_cand_pos = *ppos; + graalpy_dict_cand_epoch = *graalpy_dict_epoch; + } + return r; } diff --git a/graalpython/com.oracle.graal.python.cext/src/listobject.c b/graalpython/com.oracle.graal.python.cext/src/listobject.c index 08550223d4..75187e7814 100644 --- a/graalpython/com.oracle.graal.python.cext/src/listobject.c +++ b/graalpython/com.oracle.graal.python.cext/src/listobject.c @@ -176,8 +176,123 @@ PyList_SetItem(PyObject *op, Py_ssize_t i, } // GraalPy-additions + +/* + * A list's native stub is a GraalPyVarObject whose ob_size/ob_item Java keeps valid while the list's + * storage is empty (0, NULL) or a native PyObject* array attached to the list (length, array); otherwise ob_size is + * -1 and C asks Java (see ListStubMirror.java). Reads below never enter Java when the stub is valid. + */ +static inline GraalPyVarObject * +graalpy_list_stub(PyObject *op) +{ + if (points_to_py_handle_space(op)) { + GraalPyVarObject *s = (GraalPyVarObject *) pointer_to_stub(op); + PyTypeObject *t = ((PyObject *) s)->ob_type; + if (t == &PyList_Type || PyType_FastSubclass(t, Py_TPFLAGS_LIST_SUBCLASS)) { + return s; + } + } + return NULL; +} + PyObject ** GraalPyList_ITEMS(PyObject *op) { + GraalPyVarObject *s = graalpy_list_stub(op); + if (s != NULL && s->ob_item != NULL) { + return s->ob_item; + } return GraalPyPrivate_GET_PyListObject_ob_item(op); } + +Py_ssize_t +PyList_Size(PyObject *op) +{ + GraalPyVarObject *s = graalpy_list_stub(op); + if (s != NULL && s->ob_size >= 0) { + return s->ob_size; + } + return GraalPyPrivate_List_Size(op); +} + +PyObject * +PyList_GetItem(PyObject *op, Py_ssize_t i) +{ + GraalPyVarObject *s = graalpy_list_stub(op); + if (s != NULL) { + if (s->ob_size < 0) { + /* C reads an element: the list's storage becomes a native PyObject* array (as for ob_item) */ + GraalPyPrivate_GET_PyListObject_ob_item(op); + } + Py_ssize_t n = s->ob_size; + if (n >= 0) { + if (!valid_index(i, n)) { + PyErr_SetString(PyExc_IndexError, "list index out of range"); + return NULL; + } + return s->ob_item[i]; + } + } + return GraalPyPrivate_List_GetItem(op, i); +} + +/* PyList_Type's sq_length / mp_length: the stub's ob_size if valid, else the Java slot installed at type init */ +static lenfunc graalpy_list_java_sq_length; +static lenfunc graalpy_list_java_mp_length; + +static Py_ssize_t +graalpy_list_sq_length(PyObject *op) +{ + /* No type test, as CPython's list_length: only a real stub (tag 0b100 in the top bits; tagged ints/floats + have no memory) is read; every stub has a zeroed ob_size slot (CApiTransitions), lists keep it valid or -1 */ + if (((uint64_t)(uintptr_t) op >> 61) == 4) { + Py_ssize_t n = ((GraalPyVarObject *) pointer_to_stub(op))->ob_size; + if (n >= 0) { + return n; + } + } + return graalpy_list_java_sq_length(op); +} + +static Py_ssize_t +graalpy_list_mp_length(PyObject *op) +{ + /* No type test, as CPython's list_length: only a real stub (tag 0b100 in the top bits; tagged ints/floats + have no memory) is read; every stub has a zeroed ob_size slot (CApiTransitions), lists keep it valid or -1 */ + if (((uint64_t)(uintptr_t) op >> 61) == 4) { + Py_ssize_t n = ((GraalPyVarObject *) pointer_to_stub(op))->ob_size; + if (n >= 0) { + return n; + } + } + return graalpy_list_java_mp_length(op); +} + +/* ml_meth of list.clear (METH_NOARGS) as C sees it: an empty list whose stub is valid needs no work (as in CPython); + everything else goes to Java through PyList_Clear */ +static PyObject * +graalpy_list_clear_meth(PyObject *self, PyObject *Py_UNUSED(ignored)) +{ + /* no type test, as CPython's list_clear (ml_meth is only valid with a list self); a real stub (top bits 0b100) + always has a zeroed or valid ob_size slot (CApiTransitions) */ + if (((uint64_t)(uintptr_t) self >> 61) != 4 || ((GraalPyVarObject *) pointer_to_stub(self))->ob_size != 0) { + if (PyList_Clear(self) < 0) { + return NULL; + } + } + return Py_None; /* immortal: no reference count change (Py_RETURN_NONE's incref is a no-op for it) */ +} + +Py_LOCAL_SYMBOL void +graalpy_init_list_slots(void) +{ + GraalPyPrivate_List_SetClearMeth((void *) graalpy_list_clear_meth); + if (PyList_Type.tp_as_sequence != NULL && PyList_Type.tp_as_sequence->sq_length != NULL) { + graalpy_list_java_sq_length = PyList_Type.tp_as_sequence->sq_length; + PyList_Type.tp_as_sequence->sq_length = graalpy_list_sq_length; + } + if (PyList_Type.tp_as_mapping != NULL && PyList_Type.tp_as_mapping->mp_length != NULL) { + graalpy_list_java_mp_length = PyList_Type.tp_as_mapping->mp_length; + PyList_Type.tp_as_mapping->mp_length = graalpy_list_mp_length; + } +} diff --git a/graalpython/com.oracle.graal.python.cext/src/object.c b/graalpython/com.oracle.graal.python.cext/src/object.c index 2a67cf1cf6..861f296a72 100644 --- a/graalpython/com.oracle.graal.python.cext/src/object.c +++ b/graalpython/com.oracle.graal.python.cext/src/object.c @@ -3345,6 +3345,14 @@ Py_ssize_t GraalPy_SIZE(PyObject *ob) { } #endif } + else if (PyType_FastSubclass(ptr->ob_type, Py_TPFLAGS_LIST_SUBCLASS)) + { + /* List stubs mirror ob_size while the storage is empty or native, else -1 */ + res = ((GraalPyVarObject *) ptr)->ob_size; + if (res < 0) { + res = GraalPyPrivate_List_Size(ob); + } + } else { res = GraalPyPrivate_Get_PyVarObject_ob_size(a); diff --git a/graalpython/com.oracle.graal.python.cext/src/obmalloc.c b/graalpython/com.oracle.graal.python.cext/src/obmalloc.c index 6683b778df..8bd24a1f2b 100644 --- a/graalpython/com.oracle.graal.python.cext/src/obmalloc.c +++ b/graalpython/com.oracle.graal.python.cext/src/obmalloc.c @@ -68,6 +68,14 @@ typedef struct { #define FROM_MEM_HEAD(g) ((void *)(((mem_head_t *)g)+1)) #define GRAALPY_MEM_HEAD_MAGIC ((size_t)0x47505241574D454DULL) +/* GraalPy change: zeroed blocks of at least GRAALPY_MEM_MMAP_MIN bytes are mapped directly + (fresh zero pages, unmapped on free) instead of calloc: the system allocator keeps freed large blocks in + a cache and calloc then zeroes a reused block, which makes all of it resident. */ +#define GRAALPY_MEM_HEAD_MMAP_MAGIC ((size_t)0x475052414D4D4150ULL) +#if defined(__APPLE__) || defined(__linux__) +#include +#define GRAALPY_MEM_MMAP_MIN ((size_t)256 * 1024) +#endif #define GRAALPY_MEM_HEAD_POISON ((size_t)0xDDDDBAD0DDDDBAD0ULL) #define GRAALPY_MEM_SAMPLE_RING_SIZE (4096) #define GRAALPY_MEM_SAMPLE_HISTORY (8) @@ -85,9 +93,52 @@ typedef struct { size_t allocated_memory; size_t max_native_memory; size_t native_memory_gc_barrier; + /* GraalPy change: requested bytes allowed above the barrier without a collection because + the resident footprint did not grow with them (e.g. zeroed allocations whose pages were never + touched), and the footprint measured after the last collection (0 = not measured yet). */ + size_t deferred_memory; + size_t footprint_base; } GraalPyMem_t; -static GraalPyMem_t _GraalPyMem_State = { 0, 0, 0 }; +static GraalPyMem_t _GraalPyMem_State = { 0, 0, 0, 0, 0 }; + +/* GraalPy change: resident footprint of the process in bytes, 0 if unknown. */ +#if defined(__APPLE__) +#include +static size_t +_GraalPyMem_Footprint(void) +{ + task_vm_info_data_t info; + mach_msg_type_number_t count = TASK_VM_INFO_COUNT; + if (task_info(mach_task_self(), TASK_VM_INFO, (task_info_t) &info, &count) != KERN_SUCCESS) { + return 0; + } + return (size_t) info.phys_footprint; +} +#elif defined(__linux__) +#include +static size_t +_GraalPyMem_Footprint(void) +{ + FILE *f = fopen("/proc/self/statm", "r"); + unsigned long size = 0, resident = 0; + if (f == NULL) { + return 0; + } + if (fscanf(f, "%lu %lu", &size, &resident) != 2) { + resident = 0; + } + fclose(f); + return (size_t) resident * (size_t) sysconf(_SC_PAGESIZE); +} +#else +static size_t +_GraalPyMem_Footprint(void) +{ + return 0; +} +#endif + static GraalPyMemSample_t _GraalPyMem_Samples[GRAALPY_MEM_SAMPLE_RING_SIZE] = {{0}}; static unsigned long long _GraalPyMem_SampleSerial = 0; static size_t _GraalPyMem_SampleIndex = 0; @@ -190,7 +241,7 @@ static mem_head_t * _GraalPyMem_GetValidatedHead(const char *func, void *ptr) { mem_head_t *ptr_with_head = AS_MEM_HEAD(ptr); - if (UNLIKELY(ptr_with_head->dummy != GRAALPY_MEM_HEAD_MAGIC)) { + if (UNLIKELY(ptr_with_head->dummy != GRAALPY_MEM_HEAD_MAGIC && ptr_with_head->dummy != GRAALPY_MEM_HEAD_MMAP_MAGIC)) { _GraalPyMem_FatalInvalidHeader(func, ptr, ptr_with_head); } return ptr_with_head; @@ -505,13 +556,31 @@ static int _GraalPyMem_PrepareAlloc(GraalPyMem_t *state, size_t size) { // memory management - while ((state->allocated_memory + size) > state->native_memory_gc_barrier) { + while ((state->allocated_memory + size) > state->native_memory_gc_barrier + state->deferred_memory) { if (state->max_native_memory == 0) { state->allocated_memory = 0; + state->deferred_memory = 0; + state->footprint_base = 0; state->max_native_memory = GraalPyPrivate_GetMaxNativeMemory(); state->native_memory_gc_barrier = GraalPyPrivate_GetInitialNativeMemory(); continue; } + /* GraalPy change: the barrier counts requested bytes. Garbage that is waiting for the + Java GC only costs memory if its pages are resident. If the footprint grew by less than half a + barrier since the last collection, allow another barrier's worth of requested bytes (up to the + maximum) instead of forcing a full collection. */ + if (state->native_memory_gc_barrier + state->deferred_memory + state->native_memory_gc_barrier <= state->max_native_memory) { + size_t footprint = _GraalPyMem_Footprint(); + if (footprint != 0) { + if (state->footprint_base == 0) { + state->footprint_base = footprint; + } + if (footprint < state->footprint_base + state->native_memory_gc_barrier / 2) { + state->deferred_memory += state->native_memory_gc_barrier; + continue; + } + } + } GraalPyPrivate_Log(GRAALPY_LOG_CONFIG, "%s: exceeding native_memory_gc_barrier (%lu) with allocation of size %lu, current allocated_memory: %lu\n", __func__, state->native_memory_gc_barrier, size, state->allocated_memory); @@ -520,13 +589,23 @@ _GraalPyMem_PrepareAlloc(GraalPyMem_t *state, size_t size) for (int iteration = 0; iteration < MAX_COLLECTION_RETRIES; iteration++) { GraalPyPrivate_TriggerGC(delay); + /* GraalPy change: cleared references are enqueued by another thread after the + collection returns; wait for them in short steps (negative delay: no collection, wait + 100 us, drain the reference queue) before collecting again. */ + for (int w = 0; w < 200 && (state->allocated_memory + size) > state->native_memory_gc_barrier; w++) { + GraalPyPrivate_TriggerGC((size_t) -1); + } delay += COLLECTION_DELAY_INCREMENT; if ((state->allocated_memory + size) <= state->native_memory_gc_barrier) { state->allocated_memory += size; + state->deferred_memory = 0; + state->footprint_base = _GraalPyMem_Footprint(); return 0; } } + state->deferred_memory = 0; + state->footprint_base = 0; if (state->native_memory_gc_barrier < state->max_native_memory) { state->native_memory_gc_barrier *= 2; if (state->native_memory_gc_barrier > state->max_native_memory) { @@ -590,15 +669,28 @@ _GraalPyMem_RawCalloc(void *ctx, size_t nelem, size_t elsize) if (_GraalPyMem_PrepareAlloc(state, nbytes)) { return NULL; } - /* We cannot use 'calloc' because we need to allocate following layout: - [ mem_head_t ] [ e_0 ] [ e_1 ] [ e_2 ] ... [ n_nelem ] */ + /* Layout: [ mem_head_t ] [ e_0 ] [ e_1 ] [ e_2 ] ... [ n_nelem ] + GraalPy change: 'calloc' of the whole block (header included) instead of malloc + + memset, so that fresh pages from the OS are not touched (large blocks stay non-resident until used). */ size_t total = nbytes + sizeof(mem_head_t); - mem_head_t *ptr_with_head = (mem_head_t *)malloc(total); +#ifdef GRAALPY_MEM_MMAP_MIN + if (total >= GRAALPY_MEM_MMAP_MIN) { + void *m = mmap(NULL, total, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); + if (m == MAP_FAILED) { + state->allocated_memory -= nbytes; + return NULL; + } + mem_head_t *mapped = (mem_head_t *) m; + mapped->size = nbytes; + mapped->dummy = GRAALPY_MEM_HEAD_MMAP_MAGIC; + return FROM_MEM_HEAD(mapped); + } +#endif + mem_head_t *ptr_with_head = (mem_head_t *)calloc(1, total); if (ptr_with_head == NULL) { state->allocated_memory -= nbytes; return NULL; } - memset(ptr_with_head, 0, total); _GraalPyMem_InitHeader(ptr_with_head, nbytes); return FROM_MEM_HEAD(ptr_with_head); } @@ -614,6 +706,15 @@ _GraalPyMem_RawRealloc(void *ctx, void *ptr, size_t size) if (size == 0) size = 1; + if (ptr != NULL && AS_MEM_HEAD(ptr)->dummy == GRAALPY_MEM_HEAD_MMAP_MAGIC) { // GraalPy change: mapped block + size_t cur = AS_MEM_HEAD(ptr)->size; + void *np = _GraalPyMem_RawMalloc(ctx, size); + if (np != NULL) { + memcpy(np, ptr, cur < size ? cur : size); + _GraalPyMem_RawFree(ctx, ptr); + } + return np; + } if (ptr != NULL) { old = _GraalPyMem_GetValidatedHead(__func__, ptr); old_size = old->size; @@ -664,6 +765,17 @@ _GraalPyMem_RawFree(void *ctx, void *ptr) state->allocated_memory = size; } state->allocated_memory -= size; + if (UNLIKELY(state->deferred_memory != 0) && state->allocated_memory < state->native_memory_gc_barrier) { + // GraalPy change: back under the barrier, the deferral ends + state->deferred_memory = 0; + state->footprint_base = 0; + } +#ifdef GRAALPY_MEM_MMAP_MIN + if (ptr_with_head->dummy == GRAALPY_MEM_HEAD_MMAP_MAGIC) { // GraalPy change: mapped block + munmap(ptr_with_head, size + sizeof(mem_head_t)); + return; + } +#endif _GraalPyMem_PoisonBlock(ptr_with_head, size); free(ptr_with_head); } diff --git a/graalpython/com.oracle.graal.python.cext/src/thread.c b/graalpython/com.oracle.graal.python.cext/src/thread.c index 598f3693c2..0b6d1a0436 100644 --- a/graalpython/com.oracle.graal.python.cext/src/thread.c +++ b/graalpython/com.oracle.graal.python.cext/src/thread.c @@ -79,6 +79,28 @@ PyThread_init_thread(void) # error "Require native threads. See https://bugs.python.org/issue31370" #endif +// GraalPy change: PyThread_get_thread_ident must equal _thread.get_ident(), the Java thread id. It is +// fixed for the life of the Java thread bound to this OS thread, so it is cached in this thread's +// native PyThreadState ('thread_id', zeroed at allocation). Its validity is the struct's: Java frees +// the struct and clears 'tstate_current' when it detaches the thread (GraalPyPrivate_BeforeThreadDetach), +// and a re-attach allocates a fresh (zeroed) struct. Without a native thread state (thread never +// attached, or C API not yet initialized on it) every call asks Java and nothing is cached. +unsigned long +PyThread_get_thread_ident(void) +{ + PyThreadState *ts = tstate_current; + if (LIKELY(ts != NULL)) { + unsigned long id = ts->thread_id; + if (LIKELY(id != 0)) { + return id; + } + id = GraalPyPrivate_Thread_GetIdent(); + ts->thread_id = id; + return id; + } + return GraalPyPrivate_Thread_GetIdent(); +} + #if 0 // GraalPy change /* return the current thread stack size */ diff --git a/graalpython/com.oracle.graal.python.cext/src/thread_nt.h b/graalpython/com.oracle.graal.python.cext/src/thread_nt.h index fbb8dd9e48..62edfc8298 100644 --- a/graalpython/com.oracle.graal.python.cext/src/thread_nt.h +++ b/graalpython/com.oracle.graal.python.cext/src/thread_nt.h @@ -262,7 +262,7 @@ PyThread_get_thread_ident_ex(void) return GetCurrentThreadId(); } -#if 0 // GraalPy change: implemented in Java to match _thread.get_ident() +#if 0 // GraalPy change: implemented in thread.c to match _thread.get_ident() unsigned long PyThread_get_thread_ident(void) { diff --git a/graalpython/com.oracle.graal.python.cext/src/thread_pthread.h b/graalpython/com.oracle.graal.python.cext/src/thread_pthread.h index 87340f3d52..9f92d4ede9 100644 --- a/graalpython/com.oracle.graal.python.cext/src/thread_pthread.h +++ b/graalpython/com.oracle.graal.python.cext/src/thread_pthread.h @@ -381,7 +381,7 @@ PyThread_get_thread_ident_ex(void) { return _pthread_t_to_ident(threadid); } -#if 0 // GraalPy change: implemented in Java to match _thread.get_ident() +#if 0 // GraalPy change: implemented in thread.c to match _thread.get_ident() unsigned long PyThread_get_thread_ident(void) { diff --git a/graalpython/com.oracle.graal.python.cext/src/typeobject.c b/graalpython/com.oracle.graal.python.cext/src/typeobject.c index 5816f24d16..5b46ea4eb3 100644 --- a/graalpython/com.oracle.graal.python.cext/src/typeobject.c +++ b/graalpython/com.oracle.graal.python.cext/src/typeobject.c @@ -2092,7 +2092,9 @@ _PyType_AllocNoTrack(PyTypeObject *type, Py_ssize_t nitems) assert(type->tp_itemsize == 0); size += _PyInlineValuesSize(type); } - char *alloc = _PyObject_MallocWithType(type, size + presize); + // GraalPy change: zeroed allocation instead of malloc + memset, so that pages of a large + // instance that are never written stay non-resident + char *alloc = PyObject_Calloc(1, size + presize); if (alloc == NULL) { return PyErr_NoMemory(); } @@ -2101,10 +2103,8 @@ _PyType_AllocNoTrack(PyTypeObject *type, Py_ssize_t nitems) // GraalPy change: different header layout // ((PyObject **)alloc)[0] = NULL; // ((PyObject **)alloc)[1] = NULL; - memset(alloc, '\0', presize); _PyObject_GC_Link(obj); } - memset(obj, '\0', size); if (type->tp_itemsize == 0) { _PyObject_Init(obj, type); @@ -2524,12 +2524,32 @@ type_is_subtype_base_chain(PyTypeObject *a, PyTypeObject *b) return (b == &PyBaseObject_Type); } +/* GraalPy change: the MRO walk calls GraalPyTuple_GET_ITEM; kept out of line so that the + common paths of is_subtype_with_mro need no stack frame. */ +static int __attribute__((noinline)) +graalpy_mro_contains(PyObject *a_mro, PyTypeObject *b) +{ + Py_ssize_t i, n; + assert(PyTuple_Check(a_mro)); + n = PyTuple_GET_SIZE(a_mro); + for (i = 0; i < n; i++) { + if (PyTuple_GET_ITEM(a_mro, i) == (PyObject *)b) { + return 1; + } + } + return 0; +} + static int is_subtype_with_mro(PyObject *a_mro, PyTypeObject *a, PyTypeObject *b) { // GraalPy change: add fast-paths for common builtin types if (a == b) { return 1; + } else if (b == &PyFloat_Type) { + // Float has no subclass flag; its layout differs from object's, so every subtype has it + // in its tp_base chain (PyFloat_Check) + return type_is_subtype_base_chain(a, b); } else if (b == &PyType_Type) { return PyType_FastSubclass(a, Py_TPFLAGS_TYPE_SUBCLASS); } else if (b == &PyLong_Type) { @@ -2547,20 +2567,19 @@ is_subtype_with_mro(PyObject *a_mro, PyTypeObject *a, PyTypeObject *b) } else if ((PyObject *)b == PyExc_BaseException) { return PyType_FastSubclass(a, Py_TPFLAGS_BASE_EXC_SUBCLASS); } + // GraalPy change: if b's instance layout differs from its base's (b is its own + // "solid base"), every subtype of b has b in its tp_base chain (best_base/solid_base rules), so the + // chain answers without walking the MRO tuple. + PyTypeObject *b_base = b->tp_base; + if (a_mro != NULL && b_base != NULL && + (b->tp_basicsize != b_base->tp_basicsize || b->tp_itemsize != b_base->tp_itemsize)) { + return type_is_subtype_base_chain(a, b); + } int res; if (a_mro != NULL) { /* Deal with multiple inheritance without recursion by walking the MRO tuple */ - Py_ssize_t i, n; - assert(PyTuple_Check(a_mro)); - n = PyTuple_GET_SIZE(a_mro); - res = 0; - for (i = 0; i < n; i++) { - if (PyTuple_GET_ITEM(a_mro, i) == (PyObject *)b) { - res = 1; - break; - } - } + res = graalpy_mro_contains(a_mro, b); } else { /* a is not completely initialized yet; follow tp_base */ diff --git a/graalpython/com.oracle.graal.python.processor/src/com/oracle/graal/python/processor/CApiBuiltinsProcessor.java b/graalpython/com.oracle.graal.python.processor/src/com/oracle/graal/python/processor/CApiBuiltinsProcessor.java index eb6a4a0e79..21184c4244 100644 --- a/graalpython/com.oracle.graal.python.processor/src/com/oracle/graal/python/processor/CApiBuiltinsProcessor.java +++ b/graalpython/com.oracle.graal.python.processor/src/com/oracle/graal/python/processor/CApiBuiltinsProcessor.java @@ -1089,9 +1089,15 @@ private PythonCextBuiltinRegistry() { lines.add(" public static " + capiTypeToJavaPrimitiveType(builtin.returnType) + " upcall_" + builtin.name + "(" + argString + ") {"); String paramString = IntStream.range(0, builtin.arguments.length).mapToObj(i -> argName(i)).collect(Collectors.joining(", ")); boolean isVoidReturn = isVoid(builtin.returnType); + // Every upcall bumps the "Java ran" epoch on exit (see CApiEpoch) + String epochBump = "com.oracle.graal.python.builtins.objects.cext.capi.CApiEpoch.javaRan();"; if (builtin.origin instanceof TypeElement) { String retString = isVoidReturn ? "" : "return (" + capiTypeToJavaPrimitiveType(builtin.returnType) + ")"; - lines.add(" " + retString + builtin.name + ".getCallTarget().call(" + paramString + ");"); + lines.add(" try {"); + lines.add(" " + retString + builtin.name + ".getCallTarget().call(" + paramString + ");"); + lines.add(" } finally {"); + lines.add(" " + epochBump); + lines.add(" }"); } else { String retString = isVoidReturn ? "" : "return "; assert builtin.canRaise; @@ -1107,6 +1113,8 @@ private PythonCextBuiltinRegistry() { if (!isVoidReturn) { lines.add(" return " + capiTypeToErrorValue(builtin.returnType) + ";"); } + lines.add(" } finally {"); + lines.add(" " + epochBump); lines.add(" }"); } lines.add(" }"); @@ -1498,6 +1506,7 @@ private void generateExternalFunctionInvoker(List cap) { + return n; + } + NativeMemory.memset(entries, (byte) 0, 16 * n); + it = getIterator.execute(inliningTarget, storage); + while (itNext.execute(inliningTarget, storage, it)) { + long slot = entries + 16L * it.getState(); + // borrowed references: the dict holds key and value (promoted above) + NativeMemory.writePtr(slot, toNativeNode.execute(inliningTarget, itKey.execute(inliningTarget, storage, it))); + NativeMemory.writePtr(slot + 8, toNativeNode.execute(inliningTarget, itValue.execute(inliningTarget, storage, it))); + } + /* + * Conversions may run native code (deallocation of released references when the reference + * queue is polled) or hand the GIL to another thread at a safepoint; both bump the epoch and + * may have changed the dict while we read it: refuse the mirror then. + */ + if (epoch0 == 0 || CApiEpoch.read(context) != epoch0) { + return -1; + } + return n; + } + + @Fallback + @SuppressWarnings("unused") + static long run(Object dict, Object entries, Object cap) { + return -1; + } + } + @CApiBuiltin(ret = PyObject, args = {PyObject, PyObject, PyObject}, call = Direct, retConversion = PythonToNativeNewRefNode.class, argConversions = {NativeToPythonNode.class, NativeToPythonNode.class, NativeToPythonNode.class}) abstract static class _PyDict_Pop extends CApiTernaryBuiltinNode { diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextListBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextListBuiltins.java index 739e8fde6f..b0cc771c10 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextListBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextListBuiltins.java @@ -129,8 +129,9 @@ static long PyList_New(long size) { } } - @CApiBuiltin(ret = PyObject, args = {PyObject, Py_ssize_t}, call = Direct, retConversion = ToNativeBorrowedNode.class, argConversions = {NativeToPythonNode.class, long.class}) - abstract static class PyList_GetItem extends CApiBinaryBuiltinNode { + /** Java fallback of the C {@code PyList_GetItem} (lists whose stub is not mirrored, errors). */ + @CApiBuiltin(ret = PyObject, args = {PyObject, Py_ssize_t}, call = Ignored, retConversion = ToNativeBorrowedNode.class, argConversions = {NativeToPythonNode.class, long.class}) + abstract static class GraalPyPrivate_List_GetItem extends CApiBinaryBuiltinNode { @Specialization static Object doPList(PList list, long key, @@ -300,8 +301,9 @@ Object fallback(Object list, @SuppressWarnings("unused") Object iterable) { * A pure-C Py_SIZE implementation regressed mixed managed/native/list-subclass workload by * about 1.26x. */ - @CApiBuiltin(ret = Py_ssize_t, args = {PyObject}, call = Direct, retConversion = long.class, argConversions = {NativeToPythonNode.class}) - static long PyList_Size(long opPtr) { + /** Java fallback of the C {@code PyList_Size}. */ + @CApiBuiltin(ret = Py_ssize_t, args = {PyObject}, call = Ignored, retConversion = long.class, argConversions = {NativeToPythonNode.class}) + static long GraalPyPrivate_List_Size(long opPtr) { CApiTiming.enter(); try { Object op = NativeToPythonInternalNode.executeUncached(opPtr, false); @@ -378,6 +380,14 @@ static int error(@SuppressWarnings("unused") Object self, } } + /** C registers its list.clear ml_meth once at C API initialization. */ + @CApiBuiltin(ret = Int, args = {Pointer}, call = Ignored, retConversion = int.class, argConversions = {long.class}) + @com.oracle.truffle.api.CompilerDirectives.TruffleBoundary + static int GraalPyPrivate_List_SetClearMeth(long ptr) { + PythonContext.get(null).getCApiContext().setListClearMeth(ptr); + return 0; + } + @CApiBuiltin(ret = INT64_T, args = {PyObject, Pointer}, call = Ignored, retConversion = long.class, argConversions = {NativeToPythonNode.class, long.class}) abstract static class GraalPyPrivate_List_TruncateNativeStorage extends CApiBinaryBuiltinNode { diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextPyThreadBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextPyThreadBuiltins.java index 2cb118a61d..488c256a81 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextPyThreadBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextPyThreadBuiltins.java @@ -41,14 +41,18 @@ package com.oracle.graal.python.builtins.modules.cext; import static com.oracle.graal.python.annotations.ArgDescriptor.UNSIGNED_LONG; -import static com.oracle.graal.python.builtins.modules.cext.PythonCextBuiltins.CApiCallPath.Direct; +import static com.oracle.graal.python.builtins.modules.cext.PythonCextBuiltins.CApiCallPath.Ignored; import com.oracle.graal.python.builtins.modules.cext.PythonCextBuiltins.CApiBuiltin; public final class PythonCextPyThreadBuiltins { - @CApiBuiltin(ret = UNSIGNED_LONG, args = {}, call = Direct, acquireGil = false, canRaise = false, retConversion = long.class, argConversions = {}) - public static long PyThread_get_thread_ident() { + /** + * Java side of {@code PyThread_get_thread_ident} (thread.c), which caches the value in the + * current thread's native PyThreadState. Must equal {@code _thread.get_ident()}. + */ + @CApiBuiltin(ret = UNSIGNED_LONG, args = {}, call = Ignored, acquireGil = false, canRaise = false, retConversion = long.class, argConversions = {}) + public static long GraalPyPrivate_Thread_GetIdent() { return Thread.currentThread().threadId(); } } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CApiContext.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CApiContext.java index 922b244680..308f53421d 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CApiContext.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CApiContext.java @@ -202,6 +202,16 @@ public final class CApiContext { * {@code PyInterpreterState.gc}. */ private long gcState; + /** C implementation of {@code list.clear}'s {@code ml_meth} (0 until C registered it). */ + private long listClearMeth = NULLPTR; + + public long getListClearMeth() { + return listClearMeth; + } + + public void setListClearMeth(long ptr) { + listClearMeth = ptr; + } /** Same as {@code import.c: extensions} but we don't keep a PDict; just a bare Java HashMap. */ private final HashMap, PythonModule> extensions = new HashMap<>(4); diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CApiEpoch.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CApiEpoch.java new file mode 100644 index 0000000000..748ecf433e --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CApiEpoch.java @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * The Universal Permissive License (UPL), Version 1.0 + * + * Subject to the condition set forth below, permission is hereby granted to any + * person obtaining a copy of this software, associated documentation and/or + * data (collectively the "Software"), free of charge and under any and all + * copyright rights in the Software, and any and all patent rights owned or + * freely licensable by each licensor hereunder covering either (i) the + * unmodified Software as contributed to or provided by such licensor, or (ii) + * the Larger Works (as defined below), to deal in both + * + * (a) the Software, and + * + * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if + * one is included with the Software each a "Larger Work" to which the Software + * is contributed by such licensors), + * + * without restriction, including without limitation the rights to copy, create + * derivative works of, display, perform, and distribute the Software and make, + * use, sell, offer for sale, import, export, have made, and have sold the + * Software and the Larger Work(s), and to sublicense the foregoing rights on + * either these or other terms. + * + * This license is subject to the following condition: + * + * The above copyright notice and either this complete permission notice or at a + * minimum a reference to the UPL must be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.oracle.graal.python.builtins.objects.cext.capi; + +import com.oracle.graal.python.runtime.PythonContext; +import com.oracle.graal.python.runtime.nativeaccess.NativeMemory; + +/** + * The "Java ran" epoch: one native word that is bumped whenever Java code may have run since C last + * looked at it, i.e. on entry of every downcall, on exit of every upcall (generated C API builtin + * wrappers, slot and method closures through {@code GilNode.UncachedAcquire}) and whenever a thread + * (re)acquires the GIL. Managed objects can only change while Java runs, so a C-side cache derived + * from managed state (the {@code PyDict_Next} entry mirror in {@code dictobject.c}) stays valid + * while the epoch is unchanged. + * + *

+ * The word is allocated when C first asks for its address ({@link PythonContext#getCApiEpochAddress}); + * until then there is no C-side cache and bumping is a no-op. + *

+ */ +public final class CApiEpoch { + + private CApiEpoch() { + } + + /** Allocates the epoch word; the first value is 1 so that a zero stamp never matches. */ + public static long allocate() { + long p = NativeMemory.malloc(8); + NativeMemory.writeLong(p, 1); + return p; + } + + /** Java code may have run: invalidates every C-side cache stamped with the current epoch. */ + public static void javaRan(PythonContext context) { + long p = context.peekCApiEpochAddress(); + if (p != 0) { + NativeMemory.writeLong(p, NativeMemory.readLong(p) + 1); + } + } + + public static void javaRan() { + javaRan(PythonContext.get(null)); + } + + /** The current epoch, or 0 if C has not asked for it yet. */ + public static long read(PythonContext context) { + long p = context.peekCApiEpochAddress(); + return p == 0 ? 0 : NativeMemory.readLong(p); + } +} diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CApiFunction.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CApiFunction.java index 64237269a0..e6c8f58690 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CApiFunction.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CApiFunction.java @@ -301,7 +301,9 @@ public final class CApiFunction { @CApiBuiltin(name = "PyInterpreterState_Main", ret = PyInterpreterState, args = {}, call = CImpl) @CApiBuiltin(name = "PyIter_Check", ret = Int, args = {PyObject}, call = CImpl) @CApiBuiltin(name = "PyIter_Send", ret = PySendResult, args = {PyObject, PyObject, PyObjectPtr}, call = CImpl) + @CApiBuiltin(name = "PyList_GetItem", ret = PyObject, args = {PyObject, Py_ssize_t}, call = CImpl) @CApiBuiltin(name = "PyList_SetItem", ret = Int, args = {PyObject, Py_ssize_t, PyObject}, call = CImpl) + @CApiBuiltin(name = "PyList_Size", ret = Py_ssize_t, args = {PyObject}, call = CImpl) @CApiBuiltin(name = "PyLong_AsDouble", ret = Double, args = {PyObject}, call = CImpl) @CApiBuiltin(name = "PyLong_AsInt", ret = Int, args = {PyObject}, call = CImpl) @CApiBuiltin(name = "PyLong_AsLong", ret = Long, args = {PyObject}, call = CImpl) @@ -849,6 +851,7 @@ public final class CApiFunction { @CApiBuiltin(name = "PyThread_exit_thread", ret = Void, args = {}, call = CImpl) @CApiBuiltin(name = "PyThread_get_key_value", ret = Pointer, args = {Int}, call = CImpl) @CApiBuiltin(name = "PyThread_get_stacksize", ret = SIZE_T, args = {}, call = NotImplemented) + @CApiBuiltin(name = "PyThread_get_thread_ident", ret = UNSIGNED_LONG, args = {}, call = CImpl) @CApiBuiltin(name = "PyThread_get_thread_native_id", ret = UNSIGNED_LONG, args = {}, call = CImpl) @CApiBuiltin(name = "PyThread_init_thread", ret = Void, args = {}, call = CImpl) @CApiBuiltin(name = "PyThread_set_key_value", ret = Int, args = {Int, Pointer}, call = CImpl) diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/PyCFunctionWrapper.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/PyCFunctionWrapper.java index 81dae9da65..373b3fb78f 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/PyCFunctionWrapper.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/PyCFunctionWrapper.java @@ -48,29 +48,40 @@ import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; +import com.oracle.graal.python.PythonLanguage; import com.oracle.graal.python.annotations.Builtin; import com.oracle.graal.python.annotations.CApiUpcallTarget; import com.oracle.graal.python.annotations.NativeSimpleType; import com.oracle.graal.python.builtins.objects.PNone; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTiming; -import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.NativeToPythonInternalNode; -import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.PythonToNativeInternalNode; -import com.oracle.graal.python.builtins.objects.cext.common.CExtCommonNodes.TransformExceptionToNativeNode; +import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.NativeToPythonNode; +import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.PythonToNativeNewRefNode; +import com.oracle.graal.python.builtins.objects.cext.common.CExtCommonNodes.TransformPExceptionToNativeCachedNode; import com.oracle.graal.python.builtins.objects.function.PBuiltinFunction; import com.oracle.graal.python.builtins.objects.function.PKeyword; import com.oracle.graal.python.builtins.objects.function.Signature; import com.oracle.graal.python.nodes.argument.CreateArgumentsNode; import com.oracle.graal.python.nodes.argument.keywords.ExpandKeywordStarargsNode; import com.oracle.graal.python.nodes.argument.positional.ExecutePositionalStarargsNode; -import com.oracle.graal.python.nodes.call.CallDispatchers.SimpleIndirectInvokeNode; +import com.oracle.graal.python.nodes.call.CallDispatchers.SimpleDirectInvokeNode; import com.oracle.graal.python.nodes.function.BuiltinFunctionRootNode; import com.oracle.graal.python.runtime.GilNode; import com.oracle.graal.python.runtime.PythonContext; import com.oracle.graal.python.runtime.exception.PException; import com.oracle.graal.python.runtime.nativeaccess.NativeSignature; import com.oracle.graal.python.util.PythonUtils; +import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.RootCallTarget; +import com.oracle.truffle.api.Truffle; +import com.oracle.truffle.api.dsl.Bind; +import com.oracle.truffle.api.dsl.Cached; +import com.oracle.truffle.api.dsl.GenerateInline; +import com.oracle.truffle.api.dsl.Specialization; +import com.oracle.truffle.api.frame.VirtualFrame; +import com.oracle.truffle.api.nodes.DirectCallNode; +import com.oracle.truffle.api.nodes.Node; +import com.oracle.truffle.api.nodes.RootNode; import com.oracle.truffle.api.strings.TruffleString; /** @@ -83,6 +94,13 @@ * kept alive as long as the context lives. Referencing a function object like {@link TpSlotWrapper} * does may therefore cause significant memory leaks. *

+ *

+ * The closure entry points only forward to a compiled {@link UpcallRootNode} per + * wrapper (argument conversion, argument creation with the builtin's defaults and keyword defaults, + * a direct (inlinable) call of the builtin, result conversion, exception transfer, GIL and the + * "Java ran" epoch bump), like {@code ExecuteCApiBuiltinRootNode} does for C API builtins. Before, + * all of it ran through uncached nodes on every call. + *

*/ public abstract class PyCFunctionWrapper { @@ -96,6 +114,11 @@ public abstract class PyCFunctionWrapper { private static final MethodHandle HANDLE_VARARGS; private static final MethodHandle HANDLE_KEYWORDS; + static final int KIND_NOARGS = 0; + static final int KIND_O = 1; + static final int KIND_VARARGS = 2; + static final int KIND_KEYWORDS = 3; + static { try { HANDLE_UNARY = MethodHandles.lookup().findVirtual(PyCFunctionUnaryWrapper.class, @@ -128,17 +151,24 @@ public abstract class PyCFunctionWrapper { * {@link PNone#NO_VALUE} to indicate that the argument is missing). */ protected final Object[] defaults; + /** Keyword-only defaults of the builtin (as for a call through the function object). */ + protected final PKeyword[] kwDefaults; + /** Compiled upcall body ({@link UpcallRootNode}). */ + protected final RootCallTarget upcallTarget; @SuppressWarnings("this-escape") - protected PyCFunctionWrapper(BuiltinFunctionRootNode rootNode, Signature signature, Object[] defaults, NativeSignature upcallSignature, MethodHandle methodHandle) { + protected PyCFunctionWrapper(BuiltinFunctionRootNode rootNode, Signature signature, Object[] defaults, PKeyword[] kwDefaults, NativeSignature upcallSignature, MethodHandle methodHandle, + int kind) { assert rootNode != null; assert signature != null; this.rootNode = rootNode; this.signature = signature; this.defaults = defaults; + this.kwDefaults = kwDefaults != null ? kwDefaults : PKeyword.EMPTY_KEYWORDS; String ctName = rootNode.getName(); this.callTargetName = PythonUtils.toTruffleStringUncached(ctName); this.timing = CApiTiming.create(false, ctName); + this.upcallTarget = new UpcallRootNode(PythonLanguage.get(null), this, kind).getCallTarget(); CApiContext cApiContext = PythonContext.get(null).getCApiContext(); this.pointer = cApiContext.registerClosure(getClass().getSimpleName(), upcallSignature, methodHandle.bindTo(this), this, getDelegate()); } @@ -182,46 +212,146 @@ public static PyCFunctionWrapper createFromBuiltinFunction(CApiContext cApiConte BuiltinFunctionRootNode root = builtinFunction.getFunctionRootNode(); Signature signature = builtinFunction.getSignature(); Object[] defaults = builtinFunction.getDefaults(); + PKeyword[] kwDefaults = builtinFunction.getKwDefaults(); if (PyMethodFlags.isMethNoArgs(flags)) { - return cApiContext.getOrCreatePyCFunctionWrapper(root, k -> new PyCFunctionUnaryWrapper(k, signature, defaults)); + return cApiContext.getOrCreatePyCFunctionWrapper(root, k -> new PyCFunctionUnaryWrapper(k, signature, defaults, kwDefaults)); } else if (PyMethodFlags.isMethO(flags)) { - return cApiContext.getOrCreatePyCFunctionWrapper(root, k -> new PyCFunctionBinaryWrapper(k, signature, defaults)); + return cApiContext.getOrCreatePyCFunctionWrapper(root, k -> new PyCFunctionBinaryWrapper(k, signature, defaults, kwDefaults)); } else if (PyMethodFlags.isMethVarargs(flags)) { - return cApiContext.getOrCreatePyCFunctionWrapper(root, k -> new PyCFunctionVarargsWrapper(k, signature, defaults)); + return cApiContext.getOrCreatePyCFunctionWrapper(root, k -> new PyCFunctionVarargsWrapper(k, signature, defaults, kwDefaults)); } else if (PyMethodFlags.isMethVarargsWithKeywords(flags)) { - return cApiContext.getOrCreatePyCFunctionWrapper(root, k -> new PyCFunctionKeywordsWrapper(k, signature, defaults)); + return cApiContext.getOrCreatePyCFunctionWrapper(root, k -> new PyCFunctionKeywordsWrapper(k, signature, defaults, kwDefaults)); } else { throw shouldNotReachHere("other signature " + Integer.toHexString(flags)); } } - public static final class PyCFunctionUnaryWrapper extends PyCFunctionWrapper { + /** + * Compiled body of one wrapper's upcall. Arguments: the native pointers (as {@code Long}) the + * closure received. Returns the new reference (as {@code Long}) or {@code NULLPTR} with the + * exception set. + */ + static final class UpcallRootNode extends RootNode { + private final PyCFunctionWrapper wrapper; + private final int kind; + @Child private GilNode gilNode = GilNode.create(); + @Child private NativeToPythonNode toJava0 = NativeToPythonNode.create(); + @Child private NativeToPythonNode toJava1; + @Child private NativeToPythonNode toJava2; + @Child private ExecutePositionalStarargsNode starargsNode; + @Child private DirectCallNode callNode; + @Child private InvokeBuiltinNode invokeNode = PyCFunctionWrapperFactory.InvokeBuiltinNodeGen.create(); + @Child private PythonToNativeNewRefNode toNative = PythonToNativeNewRefNode.create(); + @Child private TransformPExceptionToNativeCachedNode transformExceptionNode; + + UpcallRootNode(PythonLanguage language, PyCFunctionWrapper wrapper, int kind) { + super(language); + this.wrapper = wrapper; + this.kind = kind; + this.callNode = Truffle.getRuntime().createDirectCallNode(wrapper.rootNode.getCallTarget()); + if (kind != KIND_NOARGS) { + toJava1 = NativeToPythonNode.create(); + } + if (kind == KIND_VARARGS || kind == KIND_KEYWORDS) { + starargsNode = ExecutePositionalStarargsNode.create(); + } + if (kind == KIND_KEYWORDS) { + toJava2 = NativeToPythonNode.create(); + } + } - PyCFunctionUnaryWrapper(BuiltinFunctionRootNode root, Signature signature, Object[] defaults) { - super(root, signature, defaults, SIGNATURE_1_ARG, HANDLE_UNARY); + @Override + public String getName() { + return wrapper.rootNode.getName(); } - @CApiUpcallTarget - @SuppressWarnings({"try", "unused"}) - public long executeUnary(long arg0) { - try (var gil = GilNode.uncachedAcquire()) { - CApiTiming.enter(); + @Override + public String toString() { + return "PyCFunctionUpcall(" + getName() + ")"; + } + + @Override + public boolean isCloningAllowed() { + return false; + } + + @Override + public Object execute(VirtualFrame frame) { + Object[] args = frame.getArguments(); + PyCFunctionWrapper w = wrapper; + boolean wasAcquired = gilNode.acquire(); + CApiTiming.enter(); + try { try { - Object jArg0 = NativeToPythonInternalNode.executeUncached(arg0, false); - Object[] pArgs = CreateArgumentsNode.executeUncached(callTargetName, PythonUtils.EMPTY_OBJECT_ARRAY, PKeyword.EMPTY_KEYWORDS, signature, jArg0, null, - defaults, PKeyword.EMPTY_KEYWORDS, false); - Object result = SimpleIndirectInvokeNode.executeUncachedBuiltin(rootNode, pArgs); - return PythonToNativeInternalNode.executeNewRefUncached(result); + Object self = toJava0.execute((long) args[0]); + Object[] positional; + Object kw = null; + switch (kind) { + case KIND_NOARGS: + positional = PythonUtils.EMPTY_OBJECT_ARRAY; + break; + case KIND_O: + positional = new Object[]{toJava1.execute((long) args[1])}; + break; + case KIND_VARARGS: + positional = starargsNode.executeWith(null, toJava1.execute((long) args[1])); + break; + case KIND_KEYWORDS: + positional = starargsNode.executeWith(null, toJava1.execute((long) args[1])); + kw = toJava2.execute((long) args[2]); + break; + default: + throw CompilerDirectives.shouldNotReachHere(); + } + Object result = invokeNode.execute(w, callNode, self, positional, kw); + return toNative.execute(result); } catch (Throwable t) { - throw checkThrowableBeforeNative(t, toString(), ""); + throw checkThrowableBeforeNative(t, w.toString(), ""); } } catch (PException e) { - TransformExceptionToNativeNode.executeUncached(e.getEscapedException()); + if (transformExceptionNode == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + transformExceptionNode = insert(TransformPExceptionToNativeCachedNode.create()); + } + transformExceptionNode.execute(e); return NULLPTR; } finally { - CApiTiming.exit(timing); + // Java ran inside an upcall (validity of C-side dict mirrors) + CApiEpoch.javaRan(PythonContext.get(this)); + gilNode.release(wasAcquired); + CApiTiming.exit(w.timing); } } + } + + @GenerateInline(false) + abstract static class InvokeBuiltinNode extends Node { + + abstract Object execute(PyCFunctionWrapper wrapper, DirectCallNode callNode, Object self, Object[] positional, Object kw); + + @Specialization + static Object doIt(PyCFunctionWrapper wrapper, DirectCallNode callNode, Object self, Object[] positional, Object kw, + @Bind Node inliningTarget, + @Cached ExpandKeywordStarargsNode expandKeywordsNode, + @Cached CreateArgumentsNode createArgumentsNode, + @Cached SimpleDirectInvokeNode invokeNode) { + PKeyword[] keywords = kw == null ? PKeyword.EMPTY_KEYWORDS : expandKeywordsNode.execute(null, inliningTarget, kw); + Object[] pArgs = createArgumentsNode.execute(inliningTarget, wrapper.callTargetName, positional, keywords, wrapper.signature, self, null, wrapper.defaults, wrapper.kwDefaults, + false); + return invokeNode.executeBuiltin(null, inliningTarget, callNode, pArgs); + } + } + + public static final class PyCFunctionUnaryWrapper extends PyCFunctionWrapper { + + PyCFunctionUnaryWrapper(BuiltinFunctionRootNode root, Signature signature, Object[] defaults, PKeyword[] kwDefaults) { + super(root, signature, defaults, kwDefaults, SIGNATURE_1_ARG, HANDLE_UNARY, KIND_NOARGS); + } + + @CApiUpcallTarget + public long executeUnary(long arg0) { + return (long) upcallTarget.call(arg0); + } @Override protected String getFlagsRepr() { @@ -231,31 +361,13 @@ protected String getFlagsRepr() { public static final class PyCFunctionBinaryWrapper extends PyCFunctionWrapper { - PyCFunctionBinaryWrapper(BuiltinFunctionRootNode root, Signature signature, Object[] defaults) { - super(root, signature, defaults, SIGNATURE_2_ARG, HANDLE_BINARY); + PyCFunctionBinaryWrapper(BuiltinFunctionRootNode root, Signature signature, Object[] defaults, PKeyword[] kwDefaults) { + super(root, signature, defaults, kwDefaults, SIGNATURE_2_ARG, HANDLE_BINARY, KIND_O); } @CApiUpcallTarget - @SuppressWarnings({"try", "unused"}) public long executeBinary(long arg0, long arg1) { - try (var gil = GilNode.uncachedAcquire()) { - CApiTiming.enter(); - try { - Object jArg0 = NativeToPythonInternalNode.executeUncached(arg0, false); - Object jArg1 = NativeToPythonInternalNode.executeUncached(arg1, false); - Object[] pArgs = CreateArgumentsNode.executeUncached(callTargetName, new Object[]{jArg1}, PKeyword.EMPTY_KEYWORDS, signature, jArg0, null, - defaults, PKeyword.EMPTY_KEYWORDS, false); - Object result = SimpleIndirectInvokeNode.executeUncachedBuiltin(rootNode, pArgs); - return PythonToNativeInternalNode.executeNewRefUncached(result); - } catch (Throwable t) { - throw checkThrowableBeforeNative(t, toString(), ""); - } - } catch (PException e) { - TransformExceptionToNativeNode.executeUncached(e.getEscapedException()); - return NULLPTR; - } finally { - CApiTiming.exit(timing); - } + return (long) upcallTarget.call(arg0, arg1); } @Override @@ -266,32 +378,13 @@ protected String getFlagsRepr() { public static final class PyCFunctionVarargsWrapper extends PyCFunctionWrapper { - PyCFunctionVarargsWrapper(BuiltinFunctionRootNode root, Signature signature, Object[] defaults) { - super(root, signature, defaults, SIGNATURE_2_ARG, HANDLE_VARARGS); + PyCFunctionVarargsWrapper(BuiltinFunctionRootNode root, Signature signature, Object[] defaults, PKeyword[] kwDefaults) { + super(root, signature, defaults, kwDefaults, SIGNATURE_2_ARG, HANDLE_VARARGS, KIND_VARARGS); } @CApiUpcallTarget - @SuppressWarnings({"try", "unused"}) public long executeVarargs(long arg0, long arg1) { - try (var gil = GilNode.uncachedAcquire()) { - CApiTiming.enter(); - try { - Object receiver = NativeToPythonInternalNode.executeUncached(arg0, false); - Object starArgs = NativeToPythonInternalNode.executeUncached(arg1, false); - Object[] starArgsArray = ExecutePositionalStarargsNode.executeUncached(starArgs); - Object[] pArgs = CreateArgumentsNode.executeUncached(callTargetName, starArgsArray, PKeyword.EMPTY_KEYWORDS, signature, receiver, null, - defaults, PKeyword.EMPTY_KEYWORDS, false); - Object result = SimpleIndirectInvokeNode.executeUncachedBuiltin(rootNode, pArgs); - return PythonToNativeInternalNode.executeNewRefUncached(result); - } catch (Throwable t) { - throw checkThrowableBeforeNative(t, toString(), ""); - } - } catch (PException e) { - TransformExceptionToNativeNode.executeUncached(e.getEscapedException()); - return NULLPTR; - } finally { - CApiTiming.exit(timing); - } + return (long) upcallTarget.call(arg0, arg1); } @Override @@ -302,34 +395,13 @@ protected String getFlagsRepr() { public static final class PyCFunctionKeywordsWrapper extends PyCFunctionWrapper { - PyCFunctionKeywordsWrapper(BuiltinFunctionRootNode root, Signature signature, Object[] defaults) { - super(root, signature, defaults, SIGNATURE_3_ARG, HANDLE_KEYWORDS); + PyCFunctionKeywordsWrapper(BuiltinFunctionRootNode root, Signature signature, Object[] defaults, PKeyword[] kwDefaults) { + super(root, signature, defaults, kwDefaults, SIGNATURE_3_ARG, HANDLE_KEYWORDS, KIND_KEYWORDS); } @CApiUpcallTarget - @SuppressWarnings({"try", "unused"}) public long executeKeywords(long arg0, long arg1, long arg2) { - try (var gil = GilNode.uncachedAcquire()) { - CApiTiming.enter(); - try { - Object receiver = NativeToPythonInternalNode.executeUncached(arg0, false); - Object starArgs = NativeToPythonInternalNode.executeUncached(arg1, false); - Object kwArgs = NativeToPythonInternalNode.executeUncached(arg2, false); - Object[] starArgsArray = ExecutePositionalStarargsNode.executeUncached(starArgs); - PKeyword[] kwArgsArray = ExpandKeywordStarargsNode.getUncached().execute(null, kwArgs); - Object[] pArgs = CreateArgumentsNode.executeUncached(callTargetName, starArgsArray, kwArgsArray, signature, receiver, null, - defaults, PKeyword.EMPTY_KEYWORDS, false); - Object result = SimpleIndirectInvokeNode.executeUncachedBuiltin(rootNode, pArgs); - return PythonToNativeInternalNode.executeNewRefUncached(result); - } catch (Throwable t) { - throw checkThrowableBeforeNative(t, toString(), ""); - } - } catch (PException e) { - TransformExceptionToNativeNode.executeUncached(e.getEscapedException()); - return NULLPTR; - } finally { - CApiTiming.exit(timing); - } + return (long) upcallTarget.call(arg0, arg1, arg2); } @Override diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/PyMethodDefHelper.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/PyMethodDefHelper.java index 1b5797f261..721e29aa90 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/PyMethodDefHelper.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/PyMethodDefHelper.java @@ -108,6 +108,15 @@ private static Object getMethFromBuiltinFunction(CApiContext cApiContext, PBuilt return kwDefaults[i].getValue(); } } + if (cApiContext.getListClearMeth() != NULLPTR && com.oracle.graal.python.builtins.objects.list.ListBuiltins.ListClearNode.class.isAssignableFrom(object.getNodeClass())) { + /* + * List.clear's ml_meth is a C function: a list whose stub says size 0 + * returns None without entering Java, anything else calls PyList_Clear (Java). + */ + return NativeFunctionPointer.create(PythonContext.get(null).ensureNativeContext(), cApiContext.getListClearMeth(), + com.oracle.graal.python.annotations.NativeSimpleType.POINTER, com.oracle.graal.python.annotations.NativeSimpleType.POINTER, + com.oracle.graal.python.annotations.NativeSimpleType.POINTER); + } return PyCFunctionWrapper.createFromBuiltinFunction(cApiContext, object); } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/TpSlotWrapper.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/TpSlotWrapper.java index b73045de85..8a22925593 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/TpSlotWrapper.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/TpSlotWrapper.java @@ -57,8 +57,10 @@ import com.oracle.graal.python.builtins.objects.PNone; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTiming; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.NativeToPythonInternalNode; +import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.NativeToPythonNode; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.PythonToNativeInternalNode; import com.oracle.graal.python.builtins.objects.cext.common.CExtCommonNodes.TransformExceptionToNativeNode; +import com.oracle.graal.python.builtins.objects.cext.common.CExtCommonNodes.TransformPExceptionToNativeCachedNode; import com.oracle.graal.python.builtins.objects.function.PKeyword; import com.oracle.graal.python.builtins.objects.ints.PInt; import com.oracle.graal.python.builtins.objects.type.TpSlots; @@ -100,7 +102,16 @@ import com.oracle.graal.python.runtime.PythonOptions; import com.oracle.graal.python.runtime.exception.PException; import com.oracle.graal.python.runtime.nativeaccess.NativeSignature; +import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; +import com.oracle.truffle.api.RootCallTarget; +import com.oracle.truffle.api.dsl.Bind; +import com.oracle.truffle.api.dsl.Cached; +import com.oracle.truffle.api.dsl.GenerateInline; +import com.oracle.truffle.api.dsl.Specialization; +import com.oracle.truffle.api.frame.VirtualFrame; +import com.oracle.truffle.api.nodes.Node; +import com.oracle.truffle.api.nodes.RootNode; public abstract class TpSlotWrapper { @@ -232,6 +243,102 @@ public final long getPointer() { public abstract TpSlotWrapper cloneWith(TpSlotManaged slot); + /** + * Compiled body of a one-argument slot upcall ({@code lenfunc}, {@code hashfunc}, + * {@code inquiry}), one root per wrapper, so the slot is a constant of the compiled code. Same + * duties as the uncached closure bodies (GIL, argument conversion, slot call, exception transfer, + * C API timing) plus the "Java ran" epoch bump (CApiEpoch), which those get from + * {@code GilNode.UncachedAcquire.close}. The argument is the native pointer (as {@code Long}); the + * result is the C return value as {@code Long}. + */ + static final class UnarySlotUpcallRootNode extends RootNode { + static final int KIND_LEN = 0; + static final int KIND_HASH = 1; + static final int KIND_INQUIRY = 2; + + private final TpSlotWrapper wrapper; + private final int kind; + private final String name; + @Child private GilNode gilNode = GilNode.create(); + @Child private NativeToPythonNode toJava0 = NativeToPythonNode.create(); + @Child private CallUnarySlotNode callNode = TpSlotWrapperFactory.CallUnarySlotNodeGen.create(); + @Child private TransformPExceptionToNativeCachedNode transformExceptionNode; + + UnarySlotUpcallRootNode(TpSlotWrapper wrapper, int kind, String name) { + super(PythonLanguage.get(null)); + this.wrapper = wrapper; + this.kind = kind; + this.name = name; + } + + @Override + public String getName() { + return name; + } + + @Override + public String toString() { + return "SlotUpcall(" + name + ")"; + } + + @Override + public boolean isCloningAllowed() { + return false; + } + + @Override + public Object execute(VirtualFrame frame) { + long arg0 = (long) frame.getArguments()[0]; + TpSlotWrapper w = wrapper; + boolean wasAcquired = gilNode.acquire(); + CApiTiming.enter(); + try { + try { + Object self = toJava0.execute(arg0); + return callNode.execute(kind, w.getSlot(), self); + } catch (Throwable t) { + throw checkThrowableBeforeNative(t, name, w.getSlot()); + } + } catch (PException e) { + if (transformExceptionNode == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + transformExceptionNode = insert(TransformPExceptionToNativeCachedNode.create()); + } + transformExceptionNode.execute(e); + return -1L; + } finally { + // Java ran inside an upcall (validity of C-side dict mirrors) + CApiEpoch.javaRan(PythonContext.get(this)); + gilNode.release(wasAcquired); + CApiTiming.exit(w.timing); + } + } + } + + @GenerateInline(false) + abstract static class CallUnarySlotNode extends Node { + + abstract long execute(int kind, TpSlot slot, Object self); + + @Specialization + static long doIt(int kind, TpSlot slot, Object self, + @Bind Node inliningTarget, + @Cached CallSlotLenNode lenNode, + @Cached CallSlotHashFunNode hashNode, + @Cached CallSlotNbBoolNode boolNode) { + switch (kind) { + case UnarySlotUpcallRootNode.KIND_LEN: + return lenNode.execute(null, inliningTarget, slot, self); + case UnarySlotUpcallRootNode.KIND_HASH: + return hashNode.execute(null, inliningTarget, slot, self); + case UnarySlotUpcallRootNode.KIND_INQUIRY: + return boolNode.execute(null, inliningTarget, slot, self) ? 1 : 0; + default: + throw CompilerDirectives.shouldNotReachHere(); + } + } + } + public static final class GetAttrWrapper extends TpSlotWrapper { public GetAttrWrapper(TpSlotManaged slot) { super(slot, SIGNATURE_P_PP, HANDLE_GET_ATTR); @@ -458,27 +565,16 @@ public TpSlotWrapper cloneWith(TpSlotManaged slot) { } public static final class InquiryWrapper extends TpSlotWrapper { + private final RootCallTarget upcallTarget; + public InquiryWrapper(TpSlotManaged slot) { super(slot, SIGNATURE_I_P, HANDLE_INQUIRY); + this.upcallTarget = new UnarySlotUpcallRootNode(this, UnarySlotUpcallRootNode.KIND_INQUIRY, "InquiryWrapper").getCallTarget(); } @CApiUpcallTarget - @SuppressWarnings("try") private int executeInquiry(long arg0) { - try (var gil = GilNode.uncachedAcquire()) { - CApiTiming.enter(); - try { - Object jArg0 = NativeToPythonInternalNode.executeUncached(arg0, false); - return CallSlotNbBoolNode.executeUncached(getSlot(), jArg0) ? 1 : 0; - } catch (Throwable t) { - throw checkThrowableBeforeNative(t, "InquiryWrapper", getSlot()); - } - } catch (PException e) { - TransformExceptionToNativeNode.executeUncached(e.getEscapedException()); - return -1; - } finally { - CApiTiming.exit(timing); - } + return (int) (long) upcallTarget.call(arg0); } @Override @@ -925,27 +1021,16 @@ public TpSlotWrapper cloneWith(TpSlotManaged slot) { } public static final class LenfuncWrapper extends TpSlotWrapper { + private final RootCallTarget upcallTarget; + public LenfuncWrapper(TpSlotManaged managedSlot) { super(managedSlot, SIGNATURE_L_P, HANDLE_LENFUNC); + this.upcallTarget = new UnarySlotUpcallRootNode(this, UnarySlotUpcallRootNode.KIND_LEN, "LenfuncWrapper").getCallTarget(); } @CApiUpcallTarget - @SuppressWarnings("try") private long executeLenfunc(long arg0) { - try (var gil = GilNode.uncachedAcquire()) { - CApiTiming.enter(); - try { - Object jArg0 = NativeToPythonInternalNode.executeUncached(arg0, false); - return CallSlotLenNode.executeUncached(getSlot(), jArg0); - } catch (Throwable t) { - throw checkThrowableBeforeNative(t, "LenfuncWrapper", getSlot()); - } - } catch (PException e) { - TransformExceptionToNativeNode.executeUncached(e.getEscapedException()); - return -1; - } finally { - CApiTiming.exit(timing); - } + return (long) upcallTarget.call(arg0); } @Override @@ -955,28 +1040,17 @@ public TpSlotWrapper cloneWith(TpSlotManaged slot) { } public static final class HashfuncWrapper extends TpSlotWrapper { + private final RootCallTarget upcallTarget; + public HashfuncWrapper(TpSlotManaged slot) { super(slot, SIGNATURE_L_P, HANDLE_HASHFUNC); + this.upcallTarget = new UnarySlotUpcallRootNode(this, UnarySlotUpcallRootNode.KIND_HASH, "HashfuncWrapper").getCallTarget(); } @CApiUpcallTarget - @SuppressWarnings("try") private long executeHashfunc(long arg0) { - try (var gil = GilNode.uncachedAcquire()) { - CApiTiming.enter(); - try { - Object jArg0 = NativeToPythonInternalNode.executeUncached(arg0, false); - return CallSlotHashFunNode.executeUncached(getSlot(), jArg0); - } catch (Throwable t) { - throw checkThrowableBeforeNative(t, "HashfuncWrapper", getSlot()); - } - } catch (PException e) { - TransformExceptionToNativeNode.executeUncached(e.getEscapedException()); - return -1; - } finally { - CApiTiming.exit(timing); - } + return (long) upcallTarget.call(arg0); } @Override diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/CApiTransitions.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/CApiTransitions.java index c253a96f80..9849b90baf 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/CApiTransitions.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/CApiTransitions.java @@ -113,6 +113,8 @@ import com.oracle.graal.python.builtins.objects.object.PythonObject; import com.oracle.graal.python.builtins.objects.str.PString; import com.oracle.graal.python.builtins.objects.str.StringNodes.StringMaterializeNode; +import com.oracle.graal.python.builtins.objects.list.ListStubMirror; +import com.oracle.graal.python.builtins.objects.list.PList; import com.oracle.graal.python.builtins.objects.tuple.PTuple; import com.oracle.graal.python.builtins.objects.type.PythonAbstractClass; import com.oracle.graal.python.builtins.objects.type.PythonBuiltinClass; @@ -1481,7 +1483,7 @@ static long doOther(Node inliningTarget, PythonObject pythonObject, long initial Object type = getClassNode.execute(inliningTarget, pythonObject); CStructs ctype; - if (isVarObjectProfile.profile(inliningTarget, pythonObject instanceof PTuple)) { + if (isVarObjectProfile.profile(inliningTarget, pythonObject instanceof PTuple || pythonObject instanceof PList)) { ctype = CStructs.GraalPyVarObject; } else if (isFloatObjectProfile.profile(inliningTarget, pythonObject instanceof PFloat)) { ctype = CStructs.GraalPyFloatObject; @@ -1498,7 +1500,10 @@ static long doOther(Node inliningTarget, PythonObject pythonObject, long initial long taggedPointer = allocateNativeObjectStubNode.execute(inliningTarget, pythonObject, type, ctype, initialRefCount, gc, 0); // allocate a native stub object (C type: GraalPy*Object) - if (ctype == CStructs.GraalPyVarObject) { + if (ctype == CStructs.GraalPyVarObject && pythonObject instanceof PList list) { + // List stubs carry ob_size/ob_item, valid for empty or native storage + ListStubMirror.sync(list, HandlePointerConverter.pointerToStub(taggedPointer)); + } else if (ctype == CStructs.GraalPyVarObject) { assert pythonObject instanceof PTuple; SequenceStorage sequenceStorage = ((PTuple) pythonObject).getSequenceStorage(); long realPointer = HandlePointerConverter.pointerToStub(taggedPointer); @@ -1559,9 +1564,16 @@ static long doGeneric(Node inliningTarget, PythonAbstractObject object, Object t * Python's GC, we will also allocate space for 'PyGC_Head'. */ long presize = gc ? CStructs.PyGC_Head.size() : 0; - long allocationSize = ctype.size() + presize + extraSize; + /* + * Every stub has at least the GraalPyVarObject fields, zeroed, so that C + * reading a stub's ob_size (PyList_Type's sq_length, like CPython's list_length, does not + * test the type) stays in bounds and reads 0 for non-var objects. Same malloc size class + * as the 24-byte GraalPyObject (16-byte quantum), so no extra memory. + */ + long structSize = Math.max(ctype.size(), CStructs.GraalPyVarObject.size()); + long allocationSize = structSize + presize + extraSize; long stubPointer = NativeMemory.malloc(allocationSize); - NativeMemory.memset(stubPointer, (byte) 0, ctype.size() + presize); + NativeMemory.memset(stubPointer, (byte) 0, structSize + presize); HandleContext handleContext = pythonContext.handleContext; long taggedPointer = HandlePointerConverter.stubToPointer(stubPointer); diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/common/CExtCommonNodes.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/common/CExtCommonNodes.java index c1f2b61495..5a65fadcc1 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/common/CExtCommonNodes.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/common/CExtCommonNodes.java @@ -385,7 +385,12 @@ static Object getException(Node inliningTarget, PythonThreadState threadState, long nativeThreadState = threadState.getNativePointer(); if (nativeThreadState != PythonAbstractObject.UNINITIALIZED) { assert nativeThreadState != PythonAbstractObject.NATIVE_POINTER_FREED; - Object exception = nativeToPythonNode.executeTransfer(inliningTarget, readPtrField(nativeThreadState, CFields.PyThreadState__current_exception)); + long exceptionPtr = readPtrField(nativeThreadState, CFields.PyThreadState__current_exception); + if (exceptionPtr == 0) { + // No store when there is no exception (the common case) + return PNone.NO_VALUE; + } + Object exception = nativeToPythonNode.executeTransfer(inliningTarget, exceptionPtr); writePtrField(nativeThreadState, CFields.PyThreadState__current_exception, 0L); return exception; } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/iterator/IteratorBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/iterator/IteratorBuiltins.java index 37e01fe8a9..455c8ab798 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/iterator/IteratorBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/iterator/IteratorBuiltins.java @@ -189,7 +189,16 @@ static Object next(Node inliningTarget, PIntRangeIterator self, return stopIteration(self); } - @Specialization(guards = "!self.isExhausted()") + @Specialization(guards = {"!self.isExhausted()", "self.isLongMode()"}) + static Object nextLong(Node inliningTarget, PBigRangeIterator self, + @Exclusive @Cached InlinedConditionProfile profile) { + if (profile.profile(inliningTarget, self.hasNextLong())) { + return self.nextLong(); + } + return stopIteration(self); + } + + @Specialization(guards = {"!self.isExhausted()", "!self.isLongMode()"}) static Object next(PBigRangeIterator self, @Bind PythonLanguage language) { if (self.hasNextBigInt()) { diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/iterator/PBigRangeIterator.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/iterator/PBigRangeIterator.java index 21a3cff0ba..616529250a 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/iterator/PBigRangeIterator.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/iterator/PBigRangeIterator.java @@ -56,6 +56,17 @@ public final class PBigRangeIterator extends PBuiltinIterator { private BigInteger longIndex; + /* + * When every value of the range fits a Java long (e.g. range(2**32, 2**32 + n)), the + * iterator yields Java longs, like any other int in that range, instead of a BigInteger and a + * PInt per element. In that mode the index is fastIndex and longIndex is unused. + */ + private final boolean longMode; + private final long fastStart; + private final long fastStep; + private final long fastLen; + private long fastIndex; + public PBigRangeIterator(Object clazz, Shape instanceShape, PInt start, PInt stop, PInt step, PInt len) { super(clazz, instanceShape); this.start = start; @@ -64,15 +75,55 @@ public PBigRangeIterator(Object clazz, Shape instanceShape, PInt start, PInt sto this.len = len; this.longIndex = BigInteger.ZERO; + long[] fast = fitsLong(start.getValue(), step.getValue(), len.getValue()); + this.longMode = fast != null; + this.fastStart = fast != null ? fast[0] : 0; + this.fastStep = fast != null ? fast[1] : 0; + this.fastLen = fast != null ? fast[2] : 0; + } + + @TruffleBoundary + private static long[] fitsLong(BigInteger start, BigInteger step, BigInteger len) { + if (start.bitLength() > 63 || step.bitLength() > 63 || len.bitLength() > 63) { + return null; + } + if (len.signum() > 0) { + BigInteger last = start.add(len.subtract(BigInteger.ONE).multiply(step)); + if (last.bitLength() > 63) { + return null; + } + } + return new long[]{start.longValue(), step.longValue(), len.longValue()}; + } + + public boolean isLongMode() { + return longMode; + } + + public boolean hasNextLong() { + return fastIndex < fastLen; + } + + public long nextLong() { + long v = fastStart + fastIndex * fastStep; + fastIndex++; + return v; + } + + private BigInteger currentIndex() { + return longMode ? BigInteger.valueOf(fastIndex) : longIndex; } @TruffleBoundary public BigInteger getRemainingLength() { - return this.len.subtract(this.longIndex); + return this.len.subtract(currentIndex()); } @TruffleBoundary public BigInteger nextBigInt() { + if (longMode) { + return BigInteger.valueOf(nextLong()); + } BigInteger nextVal = start.add(longIndex.multiply(step.getValue())); this.longIndex = longIndex.add(BigInteger.ONE); return nextVal; @@ -80,6 +131,9 @@ public BigInteger nextBigInt() { @TruffleBoundary public boolean hasNextBigInt() { + if (longMode) { + return hasNextLong(); + } return longIndex.compareTo(len.getValue()) < 0; } @@ -99,11 +153,18 @@ public PInt getLen() { return len; } + @TruffleBoundary public PInt getLongIndex(PythonLanguage language) { - return PFactory.createInt(language, longIndex); + return PFactory.createInt(language, currentIndex()); } + @TruffleBoundary public void setLongIndex(BigInteger idx) { - this.longIndex = idx; + if (longMode) { + // __setstate__ clamps idx below at 0; above len the iterator is exhausted either way + this.fastIndex = idx.compareTo(len.getValue()) > 0 ? fastLen : idx.longValue(); + } else { + this.longIndex = idx; + } } } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/list/ListStubMirror.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/list/ListStubMirror.java new file mode 100644 index 0000000000..49f4ebaaba --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/list/ListStubMirror.java @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2018, 2026, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * The Universal Permissive License (UPL), Version 1.0 + * + * Subject to the condition set forth below, permission is hereby granted to any + * person obtaining a copy of this software, associated documentation and/or + * data (collectively the "Software"), free of charge and under any and all + * copyright rights in the Software, and any and all patent rights owned or + * freely licensable by each licensor hereunder covering either (i) the + * unmodified Software as contributed to or provided by such licensor, or (ii) + * the Larger Works (as defined below), to deal in both + * + * (a) the Software, and + * + * (b) any piece of software and/or hardware listed in the lrgrwrks.txt file if + * one is included with the Software each a "Larger Work" to which the Software + * is contributed by such licensors), + * + * without restriction, including without limitation the rights to copy, create + * derivative works of, display, perform, and distribute the Software and make, + * use, sell, offer for sale, import, export, have made, and have sold the + * Software and the Larger Work(s), and to sublicense the foregoing rights on + * either these or other terms. + * + * This license is subject to the following condition: + * + * The above copyright notice and either this complete permission notice or at a + * minimum a reference to the UPL must be included in all copies or substantial + * portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ +package com.oracle.graal.python.builtins.objects.list; + +import static com.oracle.graal.python.runtime.nativeaccess.NativeMemory.NULLPTR; + +import com.oracle.graal.python.builtins.objects.PythonAbstractObject; +import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.HandlePointerConverter; +import com.oracle.graal.python.builtins.objects.cext.structs.CFields; +import com.oracle.graal.python.builtins.objects.cext.structs.CStructAccess; +import com.oracle.graal.python.builtins.objects.object.PythonObject; +import com.oracle.graal.python.runtime.sequence.storage.EmptySequenceStorage; +import com.oracle.graal.python.runtime.sequence.storage.NativeObjectSequenceStorage; +import com.oracle.graal.python.runtime.sequence.storage.SequenceStorage; +import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; + +/** + * Native list size/items for C. A list's native stub is a {@code GraalPyVarObject} + * ({@code ob_size}, {@code ob_item}), like a tuple's. The stub's fields are valid exactly when the + * list's storage is {@link EmptySequenceStorage} ({@code 0, NULL}) or a + * {@link NativeObjectSequenceStorage} attached to this list (its length and its native + * {@code PyObject*} array). For any other storage the stub holds {@link #UNKNOWN} and {@code NULL}, + * and C asks Java. Java keeps the fields current through two funnels only: the list's storage + * replacement ({@code PTupleListBase.setSequenceStorage}, only for lists that have a stub) and the + * attached native storage's length/pointer setters ({@code NativeSequenceStorage.setNewLength/setPtr}, + * which write only while the storage is still the list's storage, so a replaced storage needs no + * detaching). The element array is + * the one GraalPy already keeps for lists whose {@code ob_item} C asked for; it holds counted + * references and is freed by its {@code NativeStorageReference}. + */ +public final class ListStubMirror { + /** Stub {@code ob_size} meaning "not mirrored: ask Java". */ + public static final long UNKNOWN = -1; + + private ListStubMirror() { + } + + /** Called after the storage of a list that has a stub was set. */ + @TruffleBoundary + public static void syncOutOfLine(PList list) { + sync(list, HandlePointerConverter.pointerToStub(list.getNativePointer())); + } + + /** Writes the stub fields from the list's current storage (stub creation, storage swap). */ + public static void sync(PList list, long realStubPointer) { + SequenceStorage s = list.getSequenceStorage(); + long size; + long items; + if (s instanceof EmptySequenceStorage) { + size = 0; + items = NULLPTR; + } else if (s instanceof NativeObjectSequenceStorage ns) { + ns.attachMirror(list); + size = ns.length(); + items = ns.getPtr(); + } else { + size = UNKNOWN; + items = NULLPTR; + } + CStructAccess.writeLongField(realStubPointer, CFields.GraalPyVarObject__ob_size, size); + CStructAccess.writePtrField(realStubPointer, CFields.GraalPyVarObject__ob_item, items); + } + + /** Attached native storage changed its length. */ + public static void writeSize(PythonObject owner, SequenceStorage storage, long length) { + long p = owner.getNativePointer(); + if (p != PythonAbstractObject.UNINITIALIZED && ((PList) owner).getSequenceStorage() == storage) { + CStructAccess.writeLongField(HandlePointerConverter.pointerToStub(p), CFields.GraalPyVarObject__ob_size, length); + } + } + + /** Attached native storage moved its element array. */ + public static void writeItems(PythonObject owner, SequenceStorage storage, long ptr) { + long p = owner.getNativePointer(); + if (p != PythonAbstractObject.UNINITIALIZED && ((PList) owner).getSequenceStorage() == storage) { + CStructAccess.writePtrField(HandlePointerConverter.pointerToStub(p), CFields.GraalPyVarObject__ob_item, ptr); + } + } +} diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/list/PList.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/list/PList.java index fd5f3de4fd..20a2d740ce 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/list/PList.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/list/PList.java @@ -149,7 +149,7 @@ public void writeArrayElement(long index, Object value, } if (newStorage != store) { generalizedProfile.enter(inliningTarget); - store = newStorage; + setSequenceStorage(newStorage); } } catch (OverflowException e) { CompilerDirectives.transferToInterpreterAndInvalidate(); diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/builtins/ListNodes.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/builtins/ListNodes.java index 73f1634036..dd3f55ab9a 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/builtins/ListNodes.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/builtins/ListNodes.java @@ -72,6 +72,7 @@ import com.oracle.graal.python.runtime.sequence.storage.EmptySequenceStorage; import com.oracle.graal.python.runtime.sequence.storage.ForeignSequenceStorage; import com.oracle.graal.python.runtime.sequence.storage.NativeObjectSequenceStorage; +import com.oracle.graal.python.builtins.objects.PythonAbstractObject; import com.oracle.graal.python.runtime.sequence.storage.NativeSequenceStorage; import com.oracle.graal.python.runtime.sequence.storage.SequenceStorage; import com.oracle.truffle.api.CompilerDirectives; @@ -339,7 +340,8 @@ public static BranchProfile[] getUpdateStoreProfileUncached() { public static void doPList(PList list, Object value, @Bind Node inliningTarget, @Cached SequenceStorageNodes.AppendNode appendNode, - @Cached(value = "getUpdateStoreProfile()", uncached = "getUpdateStoreProfileUncached()", dimensions = 1) BranchProfile[] updateStoreProfile) { + @Cached(value = "getUpdateStoreProfile()", uncached = "getUpdateStoreProfileUncached()", dimensions = 1) BranchProfile[] updateStoreProfile, + @Cached InlinedConditionProfile mirroredProfile) { if (updateStoreProfile[0] == null) { // Executed for the first time. We don't pollute the AppendNode specializations, // yet, in case we're transitioning exactly once, because we'll pontentially pass @@ -351,7 +353,11 @@ public static void doPList(PList list, Object value, if (list.getOrigin() != null && newStore instanceof ArrayBasedSequenceStorage newArrayBasedStore) { list.getOrigin().reportUpdatedCapacity(newArrayBasedStore); } - } else { + } else if (mirroredProfile.profile(inliningTarget, list.getNativePointer() != PythonAbstractObject.UNINITIALIZED || list.getSequenceStorage() instanceof NativeSequenceStorage)) { + /* + * A list that has a native stub (or native storage, which can give it + * a stub during the append) replaces its storage through setSequenceStorage, which re-syncs the stub. + */ SequenceStorage newStore = appendNode.execute(inliningTarget, list.getSequenceStorage(), value, ListGeneralizationNode.SUPPLIER); if (list.getSequenceStorage() != newStore) { updateStoreProfile[0].enter(); @@ -360,6 +366,23 @@ public static void doPList(PList list, Object value, if (CompilerDirectives.inInterpreter() && list.getOrigin() != null && newStore instanceof ArrayBasedSequenceStorage newArrayBasedStore) { list.getOrigin().reportUpdatedCapacity(newArrayBasedStore); } + } else { + /* + * No stub: the plain append without the stub sync. With the stub sync in + * this branch, partial evaluation no longer resolved the "storage changed" test per + * incoming path (Empty -> typed transition vs. plain append), the loop got an extra + * back edge and the storage could not stay virtual (append of ints got much slower). The + * profile above makes the stub case a deoptimization in compiled code until this + * site meets such a list. Nothing in a Java-storage append gives the list a stub. + */ + SequenceStorage newStore = appendNode.execute(inliningTarget, list.getSequenceStorage(), value, ListGeneralizationNode.SUPPLIER); + if (list.getSequenceStorage() != newStore) { + updateStoreProfile[0].enter(); + list.setSequenceStorageNoStub(newStore); + } + if (CompilerDirectives.inInterpreter() && list.getOrigin() != null && newStore instanceof ArrayBasedSequenceStorage newArrayBasedStore) { + list.getOrigin().reportUpdatedCapacity(newArrayBasedStore); + } } } } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/bytecode_dsl/PBytecodeDSLRootNode.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/bytecode_dsl/PBytecodeDSLRootNode.java index 9b62d843df..7334d9bf41 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/bytecode_dsl/PBytecodeDSLRootNode.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/bytecode_dsl/PBytecodeDSLRootNode.java @@ -1964,6 +1964,18 @@ public static boolean doLongIterator(VirtualFrame frame, LocalAccessor output, P return true; } + /** A range whose values all fit a long yields longs (no BigInteger, no PInt). */ + @Specialization(guards = "iterator.isLongMode()") + public static boolean doBigRangeLong(VirtualFrame frame, LocalAccessor output, com.oracle.graal.python.builtins.objects.iterator.PBigRangeIterator iterator, + @Bind BytecodeNode bytecode) { + if (iterator.isExhausted() || !iterator.hasNextLong()) { + iterator.setExhausted(); + return false; + } + output.setLong(bytecode, frame, iterator.nextLong()); + return true; + } + @Specialization public static boolean doDoubleIterator(VirtualFrame frame, LocalAccessor output, PDoubleSequenceIterator iterator, @Bind BytecodeNode bytecode) { diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/object/GetDictIfExistsNode.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/object/GetDictIfExistsNode.java index 395c5f7105..3e8e5bfe77 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/object/GetDictIfExistsNode.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/object/GetDictIfExistsNode.java @@ -162,6 +162,22 @@ static PDict doNativeObject(PythonAbstractNativeObject object, } } + /* + * _PyObject_GetDictPtr returns NULL when the type has no managed dict and + * tp_dictoffset == 0 (most extension types); decide that from the native type struct + * instead of a downcall on every attribute lookup. + */ + long typePtr = com.oracle.graal.python.builtins.objects.cext.structs.CStructAccess.readPtrField(object.getPtr(), + com.oracle.graal.python.builtins.objects.cext.structs.CFields.PyObject__ob_type); + if (!com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.HandlePointerConverter.pointsToPyHandleSpace(typePtr) && + (com.oracle.graal.python.builtins.objects.cext.structs.CStructAccess.readLongField(typePtr, + com.oracle.graal.python.builtins.objects.cext.structs.CFields.PyTypeObject__tp_flags) & + com.oracle.graal.python.builtins.objects.type.TypeFlags.MANAGED_DICT) == 0 && + com.oracle.graal.python.builtins.objects.cext.structs.CStructAccess.readLongField(typePtr, + com.oracle.graal.python.builtins.objects.cext.structs.CFields.PyTypeObject__tp_dictoffset) == 0) { + return null; + } + assert EnsurePythonObjectNode.doesNotNeedPromotion(object); NativeFunctionPointer callable = CApiContext.getNativeSymbol(inliningTarget, FUN_PY_OBJECT_GET_DICT_PTR); try { diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/GilNode.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/GilNode.java index be1c2cf45b..510700724e 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/GilNode.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/GilNode.java @@ -161,6 +161,8 @@ private UncachedAcquire() { @Override public final void close() { PythonContext context = PythonContext.get(this); + // Java ran inside an upcall (slot/method closures use this) + com.oracle.graal.python.builtins.objects.cext.capi.CApiEpoch.javaRan(context); if (context.ownsGil()) { // we are forgiving in this usage for cases where the gil is released and we're // exiting with an exception diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/PythonContext.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/PythonContext.java index 6df48c68be..36493007aa 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/PythonContext.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/PythonContext.java @@ -765,6 +765,9 @@ static PythonThreadState getThreadState(Node n) { private final IDUtils idUtils = new IDUtils(); @CompilationFinal private SecureRandom secureRandom; + + /** Address of the C API "Java ran" epoch word (see CApiEpoch), 0 until C asks for it. */ + @CompilationFinal private long capiEpochAddress; private InitializationEntropySource initializationEntropySource; // Equivalent of _Py_HashSecret @@ -2207,6 +2210,8 @@ public CyclicAssumption getNativeClassStableAssumption(PythonNativeClass cls, bo public void ensureGilAfterFailure() { if (!ownsGil()) { globalInterpreterLock.lock(); + // Another thread may have run Python code while we waited + com.oracle.graal.python.builtins.objects.cext.capi.CApiEpoch.javaRan(this); } } @@ -2242,7 +2247,12 @@ boolean gilHasQueuedThreads() { boolean tryAcquireGil() { try { // Using tryLock with empty timeout to ensure fairness - return globalInterpreterLock.tryLock(0, TimeUnit.SECONDS); + boolean acquired = globalInterpreterLock.tryLock(0, TimeUnit.SECONDS); + if (acquired) { + // Another thread may have run Python code since we held the GIL + com.oracle.graal.python.builtins.objects.cext.capi.CApiEpoch.javaRan(this); + } + return acquired; } catch (InterruptedException e) { Thread.currentThread().interrupt(); return false; @@ -2258,6 +2268,8 @@ boolean tryAcquireGil() { void acquireGil() throws InterruptedException { assert !ownsGil() : dumpStackOnAssertionHelper("trying to acquire the GIL more than once"); globalInterpreterLock.lockInterruptibly(); + // Another thread may have run Python code while we waited + com.oracle.graal.python.builtins.objects.cext.capi.CApiEpoch.javaRan(this); } static String dumpStackOnAssertionHelper(String msg) { @@ -2570,6 +2582,21 @@ public void setCApiState(CApiState state) { cApiState = state; } + /** Address of the C API "Java ran" epoch word; allocated on first use. */ + public long getCApiEpochAddress() { + long p = capiEpochAddress; + if (p == 0) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + p = capiEpochAddress = com.oracle.graal.python.builtins.objects.cext.capi.CApiEpoch.allocate(); + } + return p; + } + + /** The epoch word's address if it exists, else 0 (no allocation). */ + public long peekCApiEpochAddress() { + return capiEpochAddress; + } + public CApiContext getCApiContext() { assert cApiContext != null || cApiState == CApiState.UNINITIALIZED || cApiState == CApiState.FAILED || cApiState == CApiState.CANNOT_IMPORT; return cApiContext; diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/PTupleListBase.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/PTupleListBase.java index 15596fc50b..3a4d869228 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/PTupleListBase.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/PTupleListBase.java @@ -40,6 +40,8 @@ */ package com.oracle.graal.python.runtime.sequence; +import com.oracle.graal.python.builtins.objects.list.ListStubMirror; +import com.oracle.graal.python.builtins.objects.list.PList; import com.oracle.graal.python.runtime.sequence.storage.MroSequenceStorage; import com.oracle.graal.python.runtime.sequence.storage.SequenceStorage; import com.oracle.truffle.api.object.Shape; @@ -56,10 +58,28 @@ public final SequenceStorage getSequenceStorage() { return store; } + /** + * Storage replacement without the list stub sync, for a list that has no native + * stub (see {@code ListNodes.PListAppendNode}). Same body as setSequenceStorage without the sync. + */ + public final void setSequenceStorageNoStub(SequenceStorage store) { + assert !(this.store instanceof MroSequenceStorage) : "attempting to replace MroSequenceStorage"; + this.store = store; + } + @Override public final void setSequenceStorage(SequenceStorage store) { assert !(this.store instanceof MroSequenceStorage) : "attempting to replace MroSequenceStorage"; this.store = store; + /* + * A list with a native stub re-syncs the stub's ob_size/ob_item mirror (out + * of line). A storage that was replaced never writes the stub again (it checks that it is + * still its list's storage). Compiled list append avoids this method for lists without a + * stub (see ListNodes.PListAppendNode). + */ + if (getNativePointer() != UNINITIALIZED && this instanceof PList list) { + ListStubMirror.syncOutOfLine(list); + } } } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/NativeSequenceStorage.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/NativeSequenceStorage.java index 4728a56fe3..4a767191ba 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/NativeSequenceStorage.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/NativeSequenceStorage.java @@ -48,6 +48,8 @@ import com.oracle.graal.python.PythonLanguage; import com.oracle.graal.python.builtins.objects.cext.capi.CApiContext; import com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.NativeStorageReference; +import com.oracle.graal.python.builtins.objects.list.ListStubMirror; +import com.oracle.graal.python.builtins.objects.object.PythonObject; import com.oracle.graal.python.util.PythonUtils; import com.oracle.truffle.api.TruffleLogger; @@ -59,6 +61,11 @@ public abstract class NativeSequenceStorage extends SequenceStorage { /* native pointer object */ private long ptr; private NativeStorageReference reference; + /** + * The list whose native stub mirrors this storage's length and pointer (see + * {@link ListStubMirror}); {@code null} if none. Only set on {@link NativeObjectSequenceStorage}. + */ + private PythonObject mirrorOwner; /** * State for the two independent lifetime obligations of a native sequence storage: @@ -125,8 +132,16 @@ public final void setPtr(long ptr) { reference.setPtr(ptr); } this.ptr = ptr; + if (mirrorOwner != null) { + ListStubMirror.writeItems(mirrorOwner, this, ptr); + } } + public final void attachMirror(PythonObject owner) { + mirrorOwner = owner; + } + + public void setCapacity(int capacity) { this.capacity = capacity; } @@ -147,6 +162,9 @@ public final void setNewLength(int length) { if (reference != null) { reference.setSize(length); } + if (mirrorOwner != null) { + ListStubMirror.writeSize(mirrorOwner, this, length); + } } @Override diff --git a/graalpython/graalpy-pyconfig/CMakeLists.txt b/graalpython/graalpy-pyconfig/CMakeLists.txt index 51624c268d..18c13af9c1 100644 --- a/graalpython/graalpy-pyconfig/CMakeLists.txt +++ b/graalpython/graalpy-pyconfig/CMakeLists.txt @@ -120,7 +120,13 @@ function(graalpy_sysconfig_python_string name) set(${name}_PYTHON_STRING "${value}" PARENT_SCOPE) endfunction() -graalpy_sysconfig_value("OPT" "-DNDEBUG") +# Optimisation level for C extensions: CPython's sysconfig has "-DNDEBUG -g -O3 -Wall"; without -O, +# extensions were built at -O0 on GraalPy. +if(WIN32) + graalpy_sysconfig_value("OPT" "-DNDEBUG") +else() + graalpy_sysconfig_value("OPT" "-DNDEBUG -O3") +endif() graalpy_sysconfig_value("ARFLAGS" "rc") graalpy_sysconfig_value("USE_GNU_SOURCE" "-D_GNU_SOURCE=1") set(GRAALPY_SYSCONFIG_CFLAGS_DEFAULT_VALUE "${GRAALPY_SYSCONFIG_OPT}") diff --git a/mx.graalpython/mx_graalpython.py b/mx.graalpython/mx_graalpython.py index 97a0902caf..f2e85d7998 100644 --- a/mx.graalpython/mx_graalpython.py +++ b/mx.graalpython/mx_graalpython.py @@ -513,6 +513,20 @@ def libpythonvm_build_args(): ): build_args += ['-H:-ProtectionKeys'] + if ( + mx.get_os() == 'darwin' + and mx.get_arch() == 'aarch64' + and mx_sdk_vm_ng.get_bootstrap_graalvm_version() >= mx.VersionSpec("25.6") + and not _is_overridden_native_image_arg("-H:+RandomizeRuntimeCodeCache") + and not _is_overridden_native_image_arg("-H:-RandomizeRuntimeCodeCache") + ): + # macOS ignores address hints for MAP_JIT mappings: with the randomization, every runtime-compiled method + # lands at 0x70_0000_0000 + n * size (no entropy), ~440 GB away from libpythonvm and the C extensions. + # Apple M1 cores do not predict indirect calls across that distance well once a loop has more than a few + # call sites, which slows down code that calls between compiled Python code and C a lot. Without a hint, + # MAP_JIT memory is mapped next to the (ASLR-slid) dylibs. + build_args += ['-H:-RandomizeRuntimeCodeCache'] + profile = None require_profile = get_boolean_env("GRAALPY_REQUIRE_PGO_PROFILE") if (