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
+ * 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.
+ *
+ * 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 (