From 4f97de6b7215c582afc8b1d08c8ae152fd7155a3 Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Sat, 28 Nov 2026 01:25:56 +0100 Subject: [PATCH 1/7] Copy exact complex, int and float values to native structs for C Values that cross into C no longer always get a Java wrapper plus a native stub. Shared native state (NativeComplex): one native block holds the allocators that C and Java share without upcalls, the borrowed-reference stack and the downcall depth. Generated downcall invokers (and vectorcall slot calls) enter and leave the depth; when the outermost downcall returns, the counts on the borrowed stack are dropped. - complex: an exact complex is passed to C as a native PyComplexObject from a size-class allocator. A list of exact complex values stores counted pointers to such structs (ComplexPtrSequenceStorage); PComplex keeps an unowned pointer and serial so a value read from such a list is the same object when stored or passed again. PyComplex_FromDoubles and exact complex allocation/deallocation in C use the same allocator. - int: an exact int that does not fit the tagged pointer (up to 120 bits) is passed as a native PyLongObject with no Java companion; the Java value stays a long. PyLong_From*/PyLong_As* handle these in C. - float: an exact float that cannot be tagged is passed as a native PyFloatObject from a 64-byte small-block pool that PyObject_Malloc and Java share. An instance of a static native float subclass that is only (type, ob_fval) is held in Java as a value copy (PNativeFloat) instead of a native object with a weak reference and lookup entry. Lifetime: a copy passed as an argument or borrowed result holds a count on the borrowed stack until the outermost C call returns; C that increfs it keeps it. Items that a container holds (dict and list items, PyDict_Next) are still promoted to objects with stable stubs, as before. A copy that C keeps without its own reference past the outermost call is freed under it. Also included, experimental and opt-in: classes with __slots__ that set __native_layout__ = True (and derive directly from object) get instances whose slots live in native reference-counted structs, with a pointer-aware list storage for them and pins on dict, cell, global and attribute stores. No class in the standard library or the tests sets it. The pins, the list storage and the struct paths are guarded by an assumption that holds until such a class is created. What runs for every program: a bytecode fast path for stores to __slots__ attributes (shape- cached, like the existing load fast path), and a profiled "native instance" type check on slot reads and writes. __graalpython__ gains measurement helpers: complex_counters, native_long_live, slots_counters (counters need -Dgraalpy.complexCounters or -Dgraalpy.slotsCounters) and native_quiesce. --- .../com.oracle.graal.python.cext/src/capi.c | 9 + .../src/complexobject.c | 166 ++++- .../src/floatobject.c | 11 +- .../src/longobject.c | 250 +++++++ .../src/obmalloc.c | 110 +++ .../processor/CApiBuiltinsProcessor.java | 6 +- .../modules/GraalPythonModuleBuiltins.java | 75 ++ .../modules/PolyglotModuleBuiltins.java | 2 +- .../cext/PythonCextComplexBuiltins.java | 15 +- .../modules/cext/PythonCextDictBuiltins.java | 30 +- .../modules/cext/PythonCextFloatBuiltins.java | 10 + .../modules/cext/PythonCextLongBuiltins.java | 11 + .../python/builtins/objects/cell/PCell.java | 2 + .../objects/cext/capi/CApiFunction.java | 1 + .../builtins/objects/cext/capi/CExtNodes.java | 35 +- .../cext/capi/PySequenceArrayWrapper.java | 7 +- .../capi/transitions/CApiTransitions.java | 214 +++++- .../objects/common/DynamicObjectStorage.java | 2 + .../objects/common/ObjectHashMap.java | 4 + .../objects/common/SequenceStorageNodes.java | 379 +++++++++- .../builtins/objects/complex/PComplex.java | 35 + .../builtins/objects/floats/PNativeFloat.java | 62 ++ .../getsetdescriptor/DescriptorBuiltins.java | 51 +- .../builtins/objects/list/ListBuiltins.java | 4 + .../objects/object/ObjectBuiltins.java | 35 +- .../builtins/objects/object/ObjectNodes.java | 11 +- .../objects/object/PNativeLayoutObject.java | 93 +++ .../builtins/objects/type/PythonClass.java | 11 + .../builtins/objects/type/TypeNodes.java | 2 + .../objects/type/slots/TpSlotVarargs.java | 4 + .../WriteAttributeToObjectNode.java | 4 +- .../WriteAttributeToPythonObjectNode.java | 1 + .../python/nodes/builtins/ListNodes.java | 11 +- .../bytecode_dsl/PBytecodeDSLRootNode.java | 75 +- .../bytecode_dsl/SequenceFromArrayNode.java | 30 +- .../python/nodes/frame/WriteGlobalNode.java | 2 + .../python/nodes/frame/WriteNameNode.java | 1 + .../graal/python/nodes/object/IsNode.java | 41 ++ .../graal/python/runtime/PythonContext.java | 32 + .../runtime/nativeaccess/NativeComplex.java | 451 ++++++++++++ .../runtime/nativeaccess/NativeInstance.java | 677 ++++++++++++++++++ .../runtime/nativeaccess/NativeLong.java | 301 ++++++++ .../runtime/nativeaccess/NativeSlotNodes.java | 460 ++++++++++++ .../runtime/nativeaccess/NativeSmall.java | 290 ++++++++ .../storage/ComplexPtrSequenceStorage.java | 475 ++++++++++++ .../storage/InstPtrSequenceStorage.java | 136 ++++ .../storage/ObjectSequenceStorage.java | 5 + .../sequence/storage/SequenceStorage.java | 6 + .../storage/SequenceStorageFactory.java | 12 + 49 files changed, 4590 insertions(+), 67 deletions(-) create mode 100644 graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/floats/PNativeFloat.java create mode 100644 graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/object/PNativeLayoutObject.java create mode 100644 graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeComplex.java create mode 100644 graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeInstance.java create mode 100644 graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeLong.java create mode 100644 graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeSlotNodes.java create mode 100644 graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeSmall.java create mode 100644 graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/ComplexPtrSequenceStorage.java create mode 100644 graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/InstPtrSequenceStorage.java diff --git a/graalpython/com.oracle.graal.python.cext/src/capi.c b/graalpython/com.oracle.graal.python.cext/src/capi.c index c340293058..237dec845a 100644 --- a/graalpython/com.oracle.graal.python.cext/src/capi.c +++ b/graalpython/com.oracle.graal.python.cext/src/capi.c @@ -275,7 +275,10 @@ CAPI_BUILTINS } Py_LOCAL_SYMBOL uint32_t Py_Truffle_Options; +Py_LOCAL_SYMBOL void graalpy_init_complex_alloc(void); // complexobject.c Py_LOCAL_SYMBOL void graalpy_init_list_slots(void); // listobject.c +Py_LOCAL_SYMBOL void graalpy_init_long_alloc(void); // longobject.c +Py_LOCAL_SYMBOL void graalpy_init_small_alloc(void); // obmalloc.c Py_LOCAL_SYMBOL void graalpy_init_dict_mirror(void); // dictobject.c #undef bool @@ -602,6 +605,12 @@ PyAPI_FUNC(PyThreadState **) initialize_graal_capi(void **builtin_closures, GCSt Py_Truffle_Options = GraalPyPrivate_Native_Options(); initialize_builtin_types_and_structs(); + // GraalPy change: shared native allocator for exact complex + graalpy_init_complex_alloc(); + // GraalPy change: shared native allocator for exact int + graalpy_init_long_alloc(); + // GraalPy change: small-block pool for PyObject_Malloc shared with Java (floats) + graalpy_init_small_alloc(); // 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 diff --git a/graalpython/com.oracle.graal.python.cext/src/complexobject.c b/graalpython/com.oracle.graal.python.cext/src/complexobject.c index 1ee8d890a7..5277613258 100644 --- a/graalpython/com.oracle.graal.python.cext/src/complexobject.c +++ b/graalpython/com.oracle.graal.python.cext/src/complexobject.c @@ -29,6 +29,160 @@ class complex "PyComplexObject *" "&PyComplex_Type" #include "clinic/complexobject.c.h" #endif // GraalPy change +/* GraalPy change: Exact complex objects are native structs allocated from a size-class + * free list shared with Java (com.oracle.graal.python.runtime.nativeaccess.NativeComplex); the layouts below + * must match the Java offsets. Single-threaded (GIL). */ +typedef struct { + PyComplexObject obj; /* ob_refcnt @0, ob_type @8, cval @16 */ + int64_t serial; /* @32, 0 = free */ + int64_t in_fifo; /* @40 */ +} GraalPyComplexBlock; + +#define GRAALPY_COMPLEX_FIFO_SIZE 64 +#define GRAALPY_COMPLEX_ARENA_SIZE (64 * 1024) +#define GRAALPY_COMPLEX_ARENA_HEADER 16 +enum { GC_ALLOC = 0, GC_FREE = 1, GC_INCREF = 2, GC_DECREF = 3, GC_STALE = 4, GC_EVICT_FREED = 5, GC_EVICT_KEPT = 6 }; + +typedef struct { + GraalPyComplexBlock *free_list; /* @0 */ + char *bump; /* @8 */ + char *end; /* @16 */ + int64_t serial; /* @24 */ + PyTypeObject *type; /* @32 */ + int64_t fifo_pos; /* @40 */ + int64_t flags; /* @48: bit 0 = counters on */ + char *arenas; /* @56 */ + int64_t counters[16]; /* @64 */ + struct { + GraalPyComplexBlock *p; + int64_t serial; + } fifo[GRAALPY_COMPLEX_FIFO_SIZE]; /* @192 */ +} GraalPyComplexAllocState; + +_Static_assert(sizeof(GraalPyComplexBlock) == 48, "complex block layout"); +_Static_assert(offsetof(GraalPyComplexAllocState, fifo) == 192, "complex state layout"); + +static GraalPyComplexAllocState *graalpy_complex_state; +static destructor graalpy_complex_orig_dealloc; + +#define GRAALPY_COMPLEX_COUNT(IDX) do { if (graalpy_complex_state->flags & 1) graalpy_complex_state->counters[IDX]++; } while (0) +#define GRAALPY_COMPLEX_LINK(B) (*(GraalPyComplexBlock **) &(B)->obj.cval.real) + +static GraalPyComplexBlock * +graalpy_complex_new_arena(GraalPyComplexAllocState *st) +{ + char *arena = (char *) malloc(GRAALPY_COMPLEX_ARENA_SIZE); + if (arena == NULL) { + return NULL; + } + *(char **) arena = st->arenas; + st->arenas = arena; + char *p = arena + GRAALPY_COMPLEX_ARENA_HEADER; + st->bump = p + sizeof(GraalPyComplexBlock); + st->end = arena + GRAALPY_COMPLEX_ARENA_SIZE; + return (GraalPyComplexBlock *) p; +} + +/* New exact complex with refcount 1 (owned by the caller). */ +static PyObject * +graalpy_complex_alloc(double real, double imag) +{ + GraalPyComplexAllocState *st = graalpy_complex_state; + GraalPyComplexBlock *b = st->free_list; + if (b != NULL) { + st->free_list = GRAALPY_COMPLEX_LINK(b); + } else if (st->bump + sizeof(GraalPyComplexBlock) <= st->end) { + b = (GraalPyComplexBlock *) st->bump; + st->bump += sizeof(GraalPyComplexBlock); + } else { + b = graalpy_complex_new_arena(st); + if (b == NULL) { + return PyErr_NoMemory(); + } + } + b->serial = ++st->serial; + b->in_fifo = 0; + Py_SET_REFCNT((PyObject *) b, 1); + Py_SET_TYPE((PyObject *) b, st->type); + b->obj.cval.real = real; + b->obj.cval.imag = imag; + GRAALPY_COMPLEX_COUNT(GC_ALLOC); + return (PyObject *) b; +} + +static void +graalpy_complex_free_block(GraalPyComplexAllocState *st, GraalPyComplexBlock *b) +{ + b->serial = 0; + GRAALPY_COMPLEX_LINK(b) = st->free_list; + st->free_list = b; + GRAALPY_COMPLEX_COUNT(GC_FREE); +} + +/* Same algorithm as NativeComplex.enqueue: a zero-count struct waits in the FIFO; the evicted entry is freed + * if it is the same incarnation (serial) and its count is still zero. */ +static void +graalpy_complex_enqueue(GraalPyComplexBlock *b) +{ + GraalPyComplexAllocState *st = graalpy_complex_state; + if (b->in_fifo) { + return; + } + b->in_fifo = 1; + int64_t pos = st->fifo_pos; + int idx = (int) (pos & (GRAALPY_COMPLEX_FIFO_SIZE - 1)); + GraalPyComplexBlock *old = st->fifo[idx].p; + if (old != NULL) { + if (old->serial == st->fifo[idx].serial) { + old->in_fifo = 0; + if (Py_REFCNT((PyObject *) old) == 0) { + graalpy_complex_free_block(st, old); + GRAALPY_COMPLEX_COUNT(GC_EVICT_FREED); + } else { + GRAALPY_COMPLEX_COUNT(GC_EVICT_KEPT); + } + } else { + GRAALPY_COMPLEX_COUNT(GC_EVICT_KEPT); + } + } + st->fifo[idx].p = b; + st->fifo[idx].serial = b->serial; + st->fifo_pos = pos + 1; +} + +static void +graalpy_complex_dealloc(PyObject *op) +{ + if (Py_TYPE(op) != &PyComplex_Type) { + /* native subtype that inherited this slot */ + if (graalpy_complex_orig_dealloc != NULL) { + graalpy_complex_orig_dealloc(op); + } + return; + } + graalpy_complex_enqueue((GraalPyComplexBlock *) op); +} + +static PyObject * +graalpy_complex_tp_alloc(PyTypeObject *type, Py_ssize_t nitems) +{ + if (type == &PyComplex_Type && nitems == 0) { + return graalpy_complex_alloc(0.0, 0.0); + } + return PyType_GenericAlloc(type, nitems); +} + +Py_LOCAL_SYMBOL void +graalpy_init_complex_alloc(void) +{ + graalpy_complex_state = (GraalPyComplexAllocState *) GraalPyPrivate_Complex_AllocState(); + graalpy_complex_state->type = &PyComplex_Type; + graalpy_complex_orig_dealloc = PyComplex_Type.tp_dealloc; + PyComplex_Type.tp_dealloc = graalpy_complex_dealloc; + PyComplex_Type.tp_alloc = graalpy_complex_tp_alloc; +} +/* end GraalPy change */ + /* elementary operations on complex numbers */ static Py_complex c_1 = {1., 0.}; @@ -226,6 +380,10 @@ static PyObject * complex_subtype_from_c_complex(PyTypeObject *type, Py_complex cval) { PyObject *op; + // GraalPy change: exact complex from the shared allocator + if (type == &PyComplex_Type) { + return graalpy_complex_alloc(cval.real, cval.imag); + } op = type->tp_alloc(type, 0); if (op != NULL) @@ -249,16 +407,12 @@ GraalPyPrivate_Complex_SubtypeFromDoubles(PyTypeObject *type, double real, doubl return complex_subtype_from_c_complex(type, c); } -#if 0 // GraalPy change PyObject * PyComplex_FromDoubles(double real, double imag) { - Py_complex c; - c.real = real; - c.imag = imag; - return PyComplex_FromCComplex(c); + // GraalPy change: no upcall: shared native allocator + return graalpy_complex_alloc(real, imag); } -#endif // GraalPy change static PyObject * try_complex_special_method(PyObject *); diff --git a/graalpython/com.oracle.graal.python.cext/src/floatobject.c b/graalpython/com.oracle.graal.python.cext/src/floatobject.c index 4600dfaa73..9e86eeab82 100644 --- a/graalpython/com.oracle.graal.python.cext/src/floatobject.c +++ b/graalpython/com.oracle.graal.python.cext/src/floatobject.c @@ -151,9 +151,16 @@ PyFloat_FromDouble(double fval) // GraalPy: different implementation if (fval == (float)fval) { return float_to_pointer(fval); - } else { - return GraalPyPrivate_Float_FromDouble(fval); } + // A native PyFloatObject struct (PyObject_Malloc: small-block pool shared with Java) instead of + // an upcall that creates a Java PFloat and a handle-space stub + op = (PyFloatObject *) PyObject_Malloc(sizeof(PyFloatObject)); + if (op == NULL) { + return PyErr_NoMemory(); + } + (void) PyObject_Init((PyObject *) op, &PyFloat_Type); + op->ob_fval = fval; + return (PyObject *) op; } #if 0 // GraalPy change #ifdef WITH_FREELISTS diff --git a/graalpython/com.oracle.graal.python.cext/src/longobject.c b/graalpython/com.oracle.graal.python.cext/src/longobject.c index 31a3da82d2..12d3220186 100644 --- a/graalpython/com.oracle.graal.python.cext/src/longobject.c +++ b/graalpython/com.oracle.graal.python.cext/src/longobject.c @@ -67,6 +67,210 @@ is_medium_int(stwodigits x) #endif // GraalPy change +/* GraalPy change: Exact int objects whose value does not fit the tagged pointer are native + * structs from a size-class free list shared with Java (com.oracle.graal.python.runtime.nativeaccess.NativeLong); + * the layouts must match the Java offsets. Up to GRAALPY_LONG_MAX_DIGITS digits per struct. Single-threaded (GIL). */ +#define GRAALPY_LONG_MAX_DIGITS 4 +typedef struct { + PyObject_HEAD /* ob_refcnt @0, ob_type @8 */ + uintptr_t lv_tag; /* @16; free-list link of a free block */ + digit ob_digit[GRAALPY_LONG_MAX_DIGITS]; /* @24 */ +} GraalPyLongBlock; + +typedef struct { + GraalPyLongBlock *free_list; /* @0 */ + char *bump; /* @8 */ + char *end; /* @16 */ + PyTypeObject *type; /* @24 */ + char *arenas; /* @32 */ + int64_t counters[8]; /* @40 */ +} GraalPyLongAllocState; + +_Static_assert(sizeof(GraalPyLongBlock) == 40, "int block layout"); +_Static_assert(offsetof(GraalPyLongBlock, ob_digit) == offsetof(PyLongObject, long_value.ob_digit), "int block digits"); +_Static_assert(offsetof(GraalPyLongBlock, lv_tag) == offsetof(PyLongObject, long_value.lv_tag), "int block tag"); +_Static_assert(offsetof(GraalPyLongAllocState, counters) == 40, "int state layout"); + +#define GRAALPY_LONG_ARENA_SIZE (64 * 1024) +#define GRAALPY_LONG_ARENA_HEADER 16 +#define GRAALPY_LONG_LINK(B) (*(GraalPyLongBlock **) &(B)->lv_tag) + +static GraalPyLongAllocState *graalpy_long_state; +static destructor graalpy_long_orig_dealloc; + +static GraalPyLongBlock * +graalpy_long_block(void) +{ + GraalPyLongAllocState *st = graalpy_long_state; + GraalPyLongBlock *b = st->free_list; + if (b != NULL) { + st->free_list = GRAALPY_LONG_LINK(b); + } else if (st->bump + sizeof(GraalPyLongBlock) <= st->end) { + b = (GraalPyLongBlock *) st->bump; + st->bump += sizeof(GraalPyLongBlock); + } else { + char *arena = (char *) malloc(GRAALPY_LONG_ARENA_SIZE); + if (arena == NULL) { + return NULL; + } + *(char **) arena = st->arenas; + st->arenas = arena; + b = (GraalPyLongBlock *) (arena + GRAALPY_LONG_ARENA_HEADER); + st->bump = arena + GRAALPY_LONG_ARENA_HEADER + sizeof(GraalPyLongBlock); + st->end = arena + GRAALPY_LONG_ARENA_SIZE; + } + Py_SET_REFCNT((PyObject *) b, 1); + Py_SET_TYPE((PyObject *) b, &PyLong_Type); + return b; +} + +/* New exact int with refcount 1 from sign and 64-bit magnitude. */ +static PyObject * +graalpy_long_from_mag(int negative, unsigned long long mag) +{ + GraalPyLongBlock *b = graalpy_long_block(); + if (b == NULL) { + return PyErr_NoMemory(); + } + digit d0 = (digit) (mag & PyLong_MASK); + digit d1 = (digit) ((mag >> PyLong_SHIFT) & PyLong_MASK); + digit d2 = (digit) (mag >> (2 * PyLong_SHIFT)); + uintptr_t n = d2 ? 3 : d1 ? 2 : mag ? 1 : 0; + b->lv_tag = (n << NON_SIZE_BITS) | (negative ? SIGN_NEGATIVE : mag == 0 ? SIGN_ZERO : 0); + b->ob_digit[0] = d0; + b->ob_digit[1] = d1; + b->ob_digit[2] = d2; + b->ob_digit[3] = 0; + return (PyObject *) b; +} + +static void +graalpy_long_dealloc(PyObject *op) +{ + if (points_to_py_handle_space(op) || Py_TYPE(op) != &PyLong_Type) { + /* stub of a managed int (legacy path) or a native subtype that inherited this slot */ + if (graalpy_long_orig_dealloc != NULL) { + graalpy_long_orig_dealloc(op); + } + return; + } + GraalPyLongBlock *b = (GraalPyLongBlock *) op; + Py_SET_TYPE(op, NULL); + GRAALPY_LONG_LINK(b) = graalpy_long_state->free_list; + graalpy_long_state->free_list = b; +} + +static PyObject * +graalpy_long_tp_alloc(PyTypeObject *type, Py_ssize_t nitems) +{ + if (type == &PyLong_Type) { + if (nitems > GRAALPY_LONG_MAX_DIGITS) { + PyErr_SetString(PyExc_SystemError, "GraalPy: exact int objects with more than 4 digits cannot be allocated natively"); + return NULL; + } + GraalPyLongBlock *b = graalpy_long_block(); + if (b == NULL) { + return PyErr_NoMemory(); + } + b->lv_tag = SIGN_ZERO; + memset(b->ob_digit, 0, sizeof(b->ob_digit)); + return (PyObject *) b; + } + return PyType_GenericAlloc(type, nitems); +} + +Py_LOCAL_SYMBOL void +graalpy_init_long_alloc(void) +{ + graalpy_long_state = (GraalPyLongAllocState *) GraalPyPrivate_Long_AllocState(); + graalpy_long_orig_dealloc = PyLong_Type.tp_dealloc; + PyLong_Type.tp_dealloc = graalpy_long_dealloc; + PyLong_Type.tp_alloc = graalpy_long_tp_alloc; + graalpy_long_state->type = &PyLong_Type; +} + +/* Exact native int struct (not a handle, not a tagged int)? */ +static inline int +graalpy_long_is_struct(PyObject *op) +{ + return !points_to_py_handle_space(op) && Py_TYPE(op) == &PyLong_Type; +} + +/* Reads sign and magnitude of an exact native int struct; 0 if the magnitude needs more than 64 bits. */ +static inline int +graalpy_long_read(PyObject *op, int *negative, unsigned long long *mag) +{ + GraalPyLongBlock *b = (GraalPyLongBlock *) op; + uintptr_t tag = b->lv_tag; + uintptr_t n = tag >> NON_SIZE_BITS; + unsigned long long m; + switch (n) { + case 0: m = 0; break; + case 1: m = b->ob_digit[0]; break; + case 2: m = b->ob_digit[0] | ((unsigned long long) b->ob_digit[1] << PyLong_SHIFT); break; + case 3: + if (b->ob_digit[2] >= 16) { + return 0; + } + m = b->ob_digit[0] | ((unsigned long long) b->ob_digit[1] << PyLong_SHIFT) | ((unsigned long long) b->ob_digit[2] << (2 * PyLong_SHIFT)); + break; + default: return 0; + } + *negative = (tag & SIGN_MASK) == SIGN_NEGATIVE; + *mag = m; + return 1; +} + +/* Signed 64-bit value of an exact native int struct; 0 if it is not one or does not fit (caller falls back). */ +static inline int +graalpy_long_signed(PyObject *op, long long *out) +{ + int neg; + unsigned long long mag; + if (!graalpy_long_is_struct(op) || !graalpy_long_read(op, &neg, &mag)) { + return 0; + } + if (neg) { + if (mag > (unsigned long long) LLONG_MAX + 1) { + return 0; + } + *out = (long long) (0ULL - mag); + } else { + if (mag > (unsigned long long) LLONG_MAX) { + return 0; + } + *out = (long long) mag; + } + return 1; +} + +/* Non-negative value of an exact native int struct that fits 64 bits unsigned. */ +static inline int +graalpy_long_unsigned(PyObject *op, unsigned long long *out) +{ + int neg; + unsigned long long mag; + if (!graalpy_long_is_struct(op) || !graalpy_long_read(op, &neg, &mag) || neg) { + return 0; + } + *out = mag; + return 1; +} + +/* Value modulo 2**64 of an exact native int struct whose magnitude fits 64 bits. */ +static inline int +graalpy_long_mask(PyObject *op, unsigned long long *out) +{ + int neg; + unsigned long long mag; + if (!graalpy_long_is_struct(op) || !graalpy_long_read(op, &neg, &mag)) { + return 0; + } + *out = neg ? 0ULL - mag : mag; + return 1; +} +/* end GraalPy change */ + static PyObject * get_small_int(sdigit ival) { @@ -325,6 +529,9 @@ PyLong_FromLong(long ival) if ((ival) <= INT32_MAX) { \ return int32_to_pointer((int)(ival)); \ } \ + if (graalpy_long_state != NULL) { /* native struct, no upcall */ \ + return graalpy_long_from_mag(0, (unsigned long long)(ival)); \ + } \ return GraalPyPrivate_Long_FromUnsignedLongLong((unsigned long long)(ival)); \ } while(0) @@ -472,6 +679,10 @@ PyLong_AsLongAndOverflow(PyObject *vv, int *overflow) if (points_to_py_int_handle(vv)) { return pointer_to_int64(vv); } + long long fast; + if (graalpy_long_signed(vv, &fast)) { + return (long) fast; + } return (long) GraalPyPrivate_Long_AsPrimitiveAndOverflow(vv, sizeof(long), overflow); } @@ -485,6 +696,10 @@ PyLong_AsLong(PyObject *obj) if (points_to_py_int_handle(obj)) { return pointer_to_int64(obj); } + long long fast; + if (graalpy_long_signed(obj, &fast)) { + return (long) fast; + } return (long) GraalPyPrivate_Long_AsPrimitiveWithCoercion(obj, MODE_SIGNED, sizeof(long)); } @@ -514,6 +729,10 @@ PyLong_AsSsize_t(PyObject *vv) { if (points_to_py_int_handle(vv)) { return pointer_to_int64(vv); } + long long fast; + if (graalpy_long_signed(vv, &fast)) { + return (Py_ssize_t) fast; + } return (Py_ssize_t) GraalPyPrivate_Long_AsPrimitive(vv, MODE_SIGNED, sizeof(Py_ssize_t)); } @@ -536,6 +755,10 @@ PyLong_AsUnsignedLong(PyObject *vv) } return (unsigned long) value; } + unsigned long long fast; + if (graalpy_long_unsigned(vv, &fast)) { + return (unsigned long) fast; + } return (unsigned long) GraalPyPrivate_Long_AsPrimitive(vv, MODE_UNSIGNED, sizeof(unsigned long)); } @@ -554,6 +777,10 @@ PyLong_AsSize_t(PyObject *vv) } return (size_t) value; } + unsigned long long fast; + if (graalpy_long_unsigned(vv, &fast)) { + return (size_t) fast; + } return (size_t) GraalPyPrivate_Long_AsPrimitive(vv, MODE_UNSIGNED, sizeof(size_t)); } @@ -601,6 +828,10 @@ PyLong_AsUnsignedLongMask(PyObject *op) if (points_to_py_int_handle(op)) { return pointer_to_int64(op); } + unsigned long long fast; + if (graalpy_long_mask(op, &fast)) { + return (unsigned long) fast; + } return (unsigned long) GraalPyPrivate_Long_AsPrimitiveWithCoercion(op, MODE_MASK, sizeof(unsigned long)); } @@ -1260,6 +1491,9 @@ PyLong_FromLongLong(long long ival) // GraalPy change: different implementation if ((int)ival == ival) { return int32_to_pointer(ival); + } else if (graalpy_long_state != NULL) { + // Native struct, no upcall + return graalpy_long_from_mag(ival < 0, ival < 0 ? 0ULL - (unsigned long long) ival : (unsigned long long) ival); } else { return GraalPyPrivate_Long_FromLongLong(ival); } @@ -1288,6 +1522,10 @@ PyLong_AsLongLong(PyObject *vv) if (points_to_py_int_handle(vv)) { return pointer_to_int64(vv); } + long long fast; + if (graalpy_long_signed(vv, &fast)) { + return fast; + } return (long long) GraalPyPrivate_Long_AsPrimitiveWithCoercion(vv, MODE_SIGNED, sizeof(long long)); } @@ -1310,6 +1548,10 @@ PyLong_AsUnsignedLongLong(PyObject *vv) } return (unsigned long long) value; } + unsigned long long fast; + if (graalpy_long_unsigned(vv, &fast)) { + return fast; + } return (unsigned long long) GraalPyPrivate_Long_AsPrimitive(vv, MODE_UNSIGNED, sizeof(unsigned long long)); } @@ -1358,6 +1600,10 @@ PyLong_AsUnsignedLongLongMask(PyObject *op) if (points_to_py_int_handle(op)) { return pointer_to_int64(op); } + unsigned long long fast; + if (graalpy_long_mask(op, &fast)) { + return fast; + } return (unsigned long long) GraalPyPrivate_Long_AsPrimitiveWithCoercion(op, MODE_MASK, sizeof(unsigned long long)); } @@ -1383,6 +1629,10 @@ PyLong_AsLongLongAndOverflow(PyObject *vv, int *overflow) if (points_to_py_int_handle(vv)) { return pointer_to_int64(vv); } + long long fast; + if (graalpy_long_signed(vv, &fast)) { + return fast; + } return GraalPyPrivate_Long_AsPrimitiveAndOverflow(vv, sizeof(long long), overflow); } diff --git a/graalpython/com.oracle.graal.python.cext/src/obmalloc.c b/graalpython/com.oracle.graal.python.cext/src/obmalloc.c index 8bd24a1f2b..12ef252085 100644 --- a/graalpython/com.oracle.graal.python.cext/src/obmalloc.c +++ b/graalpython/com.oracle.graal.python.cext/src/obmalloc.c @@ -139,6 +139,88 @@ _GraalPyMem_Footprint(void) } #endif +/* Small-block pool for PyObject_Malloc, shared with Java + (NativeSmall.java), like CPython's pymalloc for small objects. A pool block is 64 bytes: the usual + 16-byte header (requested size, GRAALPY_MEM_HEAD_POOL_MAGIC) and up to 48 bytes of payload. Free + blocks keep the magic, hold the free-list link in the size word, have the payload's second word + (ob_type of an object) cleared and the payload's last word (generation, unused by objects up to 40 bytes) + incremented. Arenas of 64 KB are never freed. Pool blocks are not counted in + allocated_memory. Only the PyObject_* entry points allocate from the pool (they need the GIL, as + does the Java side); every free/realloc path recognises pool blocks by the magic. */ +#define GRAALPY_MEM_HEAD_POOL_MAGIC ((size_t)0x47505241504F4F4CULL) +#define GRAALPY_SMALL_BLOCK 64 +#define GRAALPY_SMALL_MAX ((size_t)(GRAALPY_SMALL_BLOCK - 16)) +#define GRAALPY_SMALL_ARENA_SIZE (64 * 1024) +#define GRAALPY_SMALL_ARENA_HEADER 16 + +typedef struct { + char *free_list; /* @0 */ + char *bump; /* @8 */ + char *end; /* @16 */ + char *arenas; /* @24 */ + PyTypeObject *float_type; /* @32 */ + void *float_dealloc; /* @40 */ + void *float_free; /* @48 */ + int64_t counters[4]; /* @56: C allocs, C frees */ +} GraalPySmallState; + +_Static_assert(offsetof(GraalPySmallState, counters) == 56, "small state layout"); + +Py_LOCAL_SYMBOL GraalPySmallState *graalpy_small_state = NULL; + +static void * +graalpy_small_alloc(size_t size) +{ + GraalPySmallState *st = graalpy_small_state; + char *b = st->free_list; + if (b != NULL) { + st->free_list = *(char **) b; + } else if (st->bump + GRAALPY_SMALL_BLOCK <= st->end) { + b = st->bump; + st->bump += GRAALPY_SMALL_BLOCK; + } else { + char *arena = (char *) malloc(GRAALPY_SMALL_ARENA_SIZE); + if (arena == NULL) { + return NULL; + } + *(char **) arena = st->arenas; + st->arenas = arena; + b = arena + GRAALPY_SMALL_ARENA_HEADER; + st->bump = b + GRAALPY_SMALL_BLOCK; + st->end = arena + GRAALPY_SMALL_ARENA_SIZE; + } + ((size_t *) b)[0] = size; + ((size_t *) b)[1] = GRAALPY_MEM_HEAD_POOL_MAGIC; + return b + 16; +} + +static inline int +graalpy_small_is_pool(void *ptr) +{ + return ((size_t *) ptr)[-1] == GRAALPY_MEM_HEAD_POOL_MAGIC; +} + +static void +graalpy_small_free(void *ptr) +{ + GraalPySmallState *st = graalpy_small_state; + char *b = (char *) ptr - 16; + ((void **) ptr)[1] = NULL; + ((size_t *) ptr)[5]++; /* generation word (payload + 40): a Java value copy's struct hint is stale */ + *(char **) b = st->free_list; + st->free_list = b; +} + +/* called from capi.c after the builtin types are initialized */ +Py_LOCAL_SYMBOL void +graalpy_init_small_alloc(void) +{ + GraalPySmallState *st = (GraalPySmallState *) GraalPyPrivate_Small_AllocState(); + st->float_type = &PyFloat_Type; + st->float_dealloc = (void *) PyFloat_Type.tp_dealloc; + st->float_free = (void *) PyFloat_Type.tp_free; + graalpy_small_state = st; +} static GraalPyMemSample_t _GraalPyMem_Samples[GRAALPY_MEM_SAMPLE_RING_SIZE] = {{0}}; static unsigned long long _GraalPyMem_SampleSerial = 0; static size_t _GraalPyMem_SampleIndex = 0; @@ -404,6 +486,9 @@ PyObject_Malloc(size_t size) OBJECT_STAT_INC_COND(allocations_big, size >= 4094); OBJECT_STAT_INC(allocations); #endif // GraalPy change + if (size <= GRAALPY_SMALL_MAX && graalpy_small_state != NULL) { // GraalPy change: small-block pool + return graalpy_small_alloc(size == 0 ? 1 : size); + } return _PyObject.malloc(_PyObject.ctx, size); } @@ -419,6 +504,14 @@ PyObject_Calloc(size_t nelem, size_t elsize) OBJECT_STAT_INC_COND(allocations_big, elsize >= 4094); OBJECT_STAT_INC(allocations); #endif // GraalPy change + if (graalpy_small_state != NULL && nelem * elsize <= GRAALPY_SMALL_MAX) { // GraalPy change: small-block pool + size_t n = nelem * elsize; + void *p = graalpy_small_alloc(n == 0 ? 1 : n); + if (p != NULL) { + memset(p, 0, n == 0 ? 1 : n); + } + return p; + } return _PyObject.calloc(_PyObject.ctx, nelem, elsize); } @@ -706,6 +799,19 @@ _GraalPyMem_RawRealloc(void *ctx, void *ptr, size_t size) if (size == 0) size = 1; + if (ptr != NULL && graalpy_small_is_pool(ptr)) { // GraalPy change: small-block pool block + size_t cur = ((size_t *) ptr)[-2]; + if (size <= GRAALPY_SMALL_MAX) { + ((size_t *) ptr)[-2] = size; + return ptr; + } + void *np = _GraalPyMem_RawMalloc(ctx, size); + if (np != NULL) { + memcpy(np, ptr, cur); + graalpy_small_free(ptr); + } + return np; + } 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); @@ -755,6 +861,10 @@ _GraalPyMem_RawFree(void *ctx, void *ptr) * 'free' would just do nothing. */ if (ptr == NULL) return; + if (graalpy_small_is_pool(ptr)) { // GraalPy change: small-block pool block + graalpy_small_free(ptr); + return; + } GraalPyMem_t *state = (GraalPyMem_t *)ctx; mem_head_t *ptr_with_head = _GraalPyMem_GetValidatedHead(__func__, ptr); const size_t size = ptr_with_head->size; 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 21184c4244..41b0d3ddd0 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 @@ -1506,7 +1506,7 @@ private void generateExternalFunctionInvoker(List native struct + if (profiled instanceof com.oracle.graal.python.builtins.objects.complex.PComplex c && c.isExact()) { + return com.oracle.graal.python.runtime.nativeaccess.NativeComplex.toNative(context.getNativeComplexState(), c, needsTransfer); + } + + // Value copy of a value-type native float subclass instance -> struct + if (profiled instanceof com.oracle.graal.python.builtins.objects.floats.PNativeFloat f) { + return doNativeFloatValue(inliningTarget, f, needsTransfer); + } + // Step 3: handle native objects if (profiled instanceof PythonAbstractNativeObject pythonAbstractNativeObject) { return doNative(inliningTarget, pythonAbstractNativeObject, needsTransfer, hasReplicatedNativeReferences, updateRefNode); @@ -2239,6 +2315,10 @@ static Object doGeneric(Node inliningTarget, long pointer, boolean needsTransfer @Cached InlinedConditionProfile isNativeProfile, @Cached InlinedConditionProfile isNativeObjectProfile, @Cached InlinedConditionProfile isHandleSpaceProfile, + @Cached InlinedConditionProfile isNativeComplexProfile, + @Cached InlinedConditionProfile isNativeLongProfile, + @Cached InlinedConditionProfile isNativeFloatProfile, + @Cached(inline = false) NativeFloatValueNode floatValueNode, @Exclusive @Cached InlinedExactClassProfile wrapperProfile, @Exclusive @Cached UpdateStrongRefNode updateRefNode) { if (isZeroProfile.profile(inliningTarget, pointer == 0)) { @@ -2286,6 +2366,26 @@ static Object doGeneric(Node inliningTarget, long pointer, boolean needsTransfer throw CompilerDirectives.shouldNotReachHere("reference was collected: " + Long.toHexString(pointer)); } } else { + // An exact native complex struct becomes an in-flight PComplex directly + long complexState = pythonContext.peekNativeComplexState(); + if (isNativeLongProfile.profile(inliningTarget, complexState != 0 && com.oracle.graal.python.runtime.nativeaccess.NativeLong.isNativeLong(complexState, pointer))) { + // An exact native int struct becomes a Java value + return com.oracle.graal.python.runtime.nativeaccess.NativeLong.fromNative(pythonContext.getLanguage(), complexState, pointer, needsTransfer); + } + if (isNativeComplexProfile.profile(inliningTarget, complexState != 0 && com.oracle.graal.python.runtime.nativeaccess.NativeComplex.isNativeComplex(complexState, pointer))) { + return com.oracle.graal.python.runtime.nativeaccess.NativeComplex.fromNative(pythonContext.getLanguage(), complexState, pointer, needsTransfer); + } + if (complexState != 0) { + // Exact float struct -> Java double; value-type float subclass -> value copy + long obType = UNSAFE.getLong(pointer + 8); + if (isNativeFloatProfile.profile(inliningTarget, obType == com.oracle.graal.python.runtime.nativeaccess.NativeSmall.getFloatType(complexState) && obType != 0)) { + return com.oracle.graal.python.runtime.nativeaccess.NativeSmall.floatFromNative(complexState, pointer, needsTransfer); + } + Object value = floatValueNode.execute(complexState, pointer, obType, needsTransfer); + if (value != null) { + return value; + } + } IdReference lookup = nativeLookupGet(handleContext, pointer); PythonThreadState threadState = pythonContext.getThreadState(pythonContext.getLanguage()); if (isNativeProfile.profile(inliningTarget, lookup != null)) { @@ -2342,6 +2442,92 @@ static PythonAbstractObject updateRef(Node node, InlinedExactClassProfile wrappe } } + /** + * Per-type verdict of {@code NativeSmall.isFloatValueType}. Only static types qualify, so + * a verdict stays valid while the extension is loaded. + */ + public static final class NativeFloatValueTypes { + private static final java.util.HashMap VERDICTS = new java.util.HashMap<>(); + + private NativeFloatValueTypes() { + } + + @TruffleBoundary + public static boolean isValueType(long st, long typePtr) { + synchronized (VERDICTS) { + Boolean v = VERDICTS.get(typePtr); + if (v == null) { + v = com.oracle.graal.python.runtime.nativeaccess.NativeSmall.isFloatValueType(st, typePtr); + VERDICTS.put(typePtr, v); + } + return v; + } + } + } + + /** + * A non-handle pointer whose type is a value-type native float subclass becomes an + * in-flight {@link com.oracle.graal.python.builtins.objects.floats.PNativeFloat} (value copy, + * no weak reference, no lookup-table entry); with {@code transfer} C's count is dropped (the + * struct is freed at zero). Returns {@code null} for any other type. + */ + @GenerateUncached + @GenerateInline(false) + public abstract static class NativeFloatValueNode extends PNodeWithContext { + + public abstract Object execute(long st, long pointer, long typePtr, boolean transfer); + + @Specialization(guards = {"isSingleContext()", "typePtr == cachedType"}, limit = "3") + static Object doCached(long st, long pointer, @SuppressWarnings("unused") long typePtr, boolean transfer, + @SuppressWarnings("unused") @Cached("typePtr") long cachedType, + @Cached("isValue(st, typePtr)") boolean isValue, + @Cached("lookupClass(isValue, typePtr)") Object cls, + @Cached("lookupShape(isValue, cls)") Shape shape) { + if (!isValue) { + return null; + } + return make(st, pointer, cls, shape, transfer); + } + + @Specialization(replaces = "doCached") + static Object doGeneric(long st, long pointer, long typePtr, boolean transfer) { + if (!NativeFloatValueTypes.isValueType(st, typePtr)) { + return null; + } + Object cls = lookupClass(true, typePtr); + return make(st, pointer, cls, lookupShape(true, cls), transfer); + } + + static boolean isValue(long st, long typePtr) { + return NativeFloatValueTypes.isValueType(st, typePtr); + } + + @TruffleBoundary + static Object lookupClass(boolean isValue, long typePtr) { + return isValue ? NativeToPythonClassInternalNode.executeUncached(typePtr) : null; + } + + @TruffleBoundary + static Shape lookupShape(boolean isValue, Object cls) { + return isValue ? TypeNodes.GetInstanceShape.executeUncached(cls) : null; + } + + private static Object make(long st, long pointer, Object cls, Shape shape, boolean transfer) { + // the pointer is kept as a reuse hint only for pool blocks (always readable, even when freed) + boolean pool = com.oracle.graal.python.runtime.nativeaccess.NativeSmall.isPool(pointer); + double d = com.oracle.graal.python.runtime.nativeaccess.NativeSmall.floatFromNative(st, pointer, transfer && !pool); + if (transfer && pool) { + /* + * The count C gave us is dropped when the next outermost downcall returns (borrowed + * stack), so a value passed straight back to C reuses this struct. + */ + com.oracle.graal.python.runtime.nativeaccess.NativeSmall.deferRelease(st, pointer); + } + return new com.oracle.graal.python.builtins.objects.floats.PNativeFloat(cls, shape, d, pool ? pointer : 0, + pool ? com.oracle.graal.python.runtime.nativeaccess.NativeSmall.generation(pointer) : 0); + } + } + @GenerateUncached @GenerateInline(false) public abstract static class NativeToPythonNode extends CExtToJavaNode { @@ -2435,6 +2621,10 @@ static Object doNonWrapper(long pointer, boolean stealing, @Cached InlinedConditionProfile isNativeProfile, @Cached InlinedConditionProfile isNativeObjectProfile, @Cached InlinedConditionProfile isHandleSpaceProfile, + @Cached InlinedConditionProfile isNativeComplexProfile, + @Cached InlinedConditionProfile isNativeLongProfile, + @Cached InlinedConditionProfile isNativeFloatProfile, + @Cached(inline = false) NativeFloatValueNode floatValueNode, @Cached InlinedExactClassProfile wrapperProfile, @Cached UpdateStrongRefNode updateRefNode) { @@ -2471,6 +2661,26 @@ static Object doNonWrapper(long pointer, boolean stealing, throw CompilerDirectives.shouldNotReachHere("reference was collected: " + Long.toHexString(pointer)); } } else { + // An exact native complex struct becomes an in-flight PComplex directly + long complexState = pythonContext.peekNativeComplexState(); + if (isNativeLongProfile.profile(inliningTarget, complexState != 0 && com.oracle.graal.python.runtime.nativeaccess.NativeLong.isNativeLong(complexState, pointer))) { + // An exact native int struct becomes a Java value + return com.oracle.graal.python.runtime.nativeaccess.NativeLong.fromNative(pythonContext.getLanguage(), complexState, pointer, stealing); + } + if (isNativeComplexProfile.profile(inliningTarget, complexState != 0 && com.oracle.graal.python.runtime.nativeaccess.NativeComplex.isNativeComplex(complexState, pointer))) { + return com.oracle.graal.python.runtime.nativeaccess.NativeComplex.fromNative(pythonContext.getLanguage(), complexState, pointer, stealing); + } + if (complexState != 0) { + // Exact float struct -> Java double; value-type float subclass -> value copy + long obType = UNSAFE.getLong(pointer + 8); + if (isNativeFloatProfile.profile(inliningTarget, obType == com.oracle.graal.python.runtime.nativeaccess.NativeSmall.getFloatType(complexState) && obType != 0)) { + return com.oracle.graal.python.runtime.nativeaccess.NativeSmall.floatFromNative(complexState, pointer, stealing); + } + Object value = floatValueNode.execute(complexState, pointer, obType, stealing); + if (value != null) { + return value; + } + } IdReference lookup = nativeLookupGet(handleContext, pointer); PythonThreadState threadState = pythonContext.getThreadState(pythonContext.getLanguage()); if (isNativeProfile.profile(inliningTarget, lookup != null)) { diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/DynamicObjectStorage.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/DynamicObjectStorage.java index e7e2b22e3c..ce914214ac 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/DynamicObjectStorage.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/DynamicObjectStorage.java @@ -313,12 +313,14 @@ private static boolean hasNext(Iterator keys) { void setStringKey(Node inliningTarget, TruffleString key, Object value, DynamicObject.PutNode putNode, InlinedBranchProfile invalidateLengthProfile, DynamicObject.SetShapeFlagsNode setShapeFlagsNode) { invalidateLength(inliningTarget, value, invalidateLengthProfile, setShapeFlagsNode); + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value, com.oracle.graal.python.runtime.nativeaccess.NativeInstance.C_PIN_DICT); putNode.execute(store, key, assertNoJavaString(value)); } boolean setStringKeyIfPresent(Node inliningTarget, TruffleString key, Object value, DynamicObject.PutNode putNode, InlinedBranchProfile invalidateLengthProfile, DynamicObject.SetShapeFlagsNode setShapeFlagsNode) { invalidateLength(inliningTarget, value, invalidateLengthProfile, setShapeFlagsNode); + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value, com.oracle.graal.python.runtime.nativeaccess.NativeInstance.C_PIN_DICT); return putNode.executeIfPresent(store, key, assertNoJavaString(value)); } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/ObjectHashMap.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/ObjectHashMap.java index b74a2cdc89..736a2d0574 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/ObjectHashMap.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/ObjectHashMap.java @@ -781,6 +781,7 @@ static void doPut(Frame frame, ObjectHashMap map, Object key, long keyHash, Obje if (foundEqKey.profile(inliningTarget, index != DUMMY_INDEX && map.keysEqual(metadata, frame, inliningTarget, unwrapIndex(index), key, keyHash, eqNode))) { // we found the key, override the value, Python does not override the key though + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value, com.oracle.graal.python.runtime.nativeaccess.NativeInstance.C_PIN_DICT); map.setValue(unwrapIndex(index), value); return; } @@ -815,6 +816,7 @@ private static void putCollision(Frame frame, ObjectHashMap map, Object key, lon if (collisionFoundEqKey.profile(inliningTarget, index != DUMMY_INDEX && map.keysEqual(metadata, frame, inliningTarget, unwrapIndex(index), key, keyHash, eqNode))) { // we found the key, override the value, Python does not override the key // though + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value, com.oracle.graal.python.runtime.nativeaccess.NativeInstance.C_PIN_DICT); map.setValue(unwrapIndex(index), value); return; } @@ -866,6 +868,8 @@ private void insertNewKey(byte[] localMetadata, int indicesLen, int indicesOffse private void putInNewSlot(byte[] localMetadata, int indicesOffset, int indexByteSize, int physicalCollisionMask, int entryCapacity, int bucketsCount, Node inliningTarget, InlinedBranchProfile rehashProfile, Object key, long keyHash, Object value, int compactIndex) { assert metadata == localMetadata; + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(key, com.oracle.graal.python.runtime.nativeaccess.NativeInstance.C_PIN_DICT); + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value, com.oracle.graal.python.runtime.nativeaccess.NativeInstance.C_PIN_DICT); assert entryCapacity == getEntryCapacity(); if (CompilerDirectives.injectBranchProbability(SLOWPATH_PROBABILITY, needsResize(entryCapacity, bucketsCount))) { rehashProfile.enter(inliningTarget); diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/SequenceStorageNodes.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/SequenceStorageNodes.java index e5f6c45b92..88918c2192 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/SequenceStorageNodes.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/SequenceStorageNodes.java @@ -127,6 +127,13 @@ import com.oracle.graal.python.runtime.sequence.storage.ArrayBasedSequenceStorage; import com.oracle.graal.python.runtime.sequence.storage.BoolSequenceStorage; import com.oracle.graal.python.runtime.sequence.storage.ByteSequenceStorage; +import com.oracle.graal.python.runtime.sequence.storage.ComplexPtrSequenceStorage; +import com.oracle.graal.python.runtime.sequence.storage.InstPtrSequenceStorage; +import com.oracle.graal.python.runtime.nativeaccess.NativeInstance; +import com.oracle.graal.python.runtime.nativeaccess.NativeSlotNodes; +import com.oracle.graal.python.builtins.objects.complex.PComplex; +import com.oracle.graal.python.runtime.nativeaccess.NativeComplex; +import org.graalvm.nativeimage.ImageInfo; import com.oracle.graal.python.runtime.sequence.storage.DoubleSequenceStorage; import com.oracle.graal.python.runtime.sequence.storage.EmptySequenceStorage; import com.oracle.graal.python.runtime.sequence.storage.ForeignSequenceStorage; @@ -284,6 +291,10 @@ static boolean compatibleAssign(Node inliningTarget, SequenceStorage lhs, Sequen return rhsType == Double || rhsType == Uninitialized || rhsType == Empty; case Generic: return true; + case ComplexPtr: + return rhsType == StorageType.ComplexPtr || rhsType == Uninitialized || rhsType == Empty; + case InstPtr: + return rhsType == StorageType.InstPtr || rhsType == Uninitialized || rhsType == Empty; case Empty: case Uninitialized: return false; @@ -317,6 +328,10 @@ static boolean compatibleAssign(Node inliningTarget, SequenceStorage lhs, Sequen return rhsType == Double || rhsType == Uninitialized || rhsType == Empty; case Generic: return true; + case ComplexPtr: + return rhsType == StorageType.ComplexPtr || rhsType == Uninitialized || rhsType == Empty; + case InstPtr: + return rhsType == StorageType.InstPtr || rhsType == Uninitialized || rhsType == Empty; case Empty: case Uninitialized: return false; @@ -367,6 +382,27 @@ protected static boolean isDouble(StorageType et) { protected static boolean isObject(StorageType et) { return et == StorageType.Generic; } + + protected static boolean isComplexPtr(SequenceStorage s) { + return s instanceof ComplexPtrSequenceStorage; + } + + protected static boolean isComplexPtrType(StorageType et) { + return et == StorageType.ComplexPtr; + } + + /** Pointer-aware list of native-instance words (a subclass of the complex one). */ + protected static boolean isInstPtr(SequenceStorage s) { + return s instanceof InstPtrSequenceStorage; + } + + protected static boolean isInstPtrType(StorageType et) { + return et == StorageType.InstPtr; + } + + protected static boolean isListWordValue(Object v) { + return NativeInstance.isListWordValue(v); + } } abstract static class NormalizingNode extends PNodeWithContext { @@ -621,6 +657,18 @@ protected static Object doObject(ObjectSequenceStorage storage, int idx) { return storage.getObjectItemNormalized(idx); } + /** A load builds an in-flight object around the pointer (no count). */ + @Specialization + protected static Object doInstPtr(InstPtrSequenceStorage storage, int idx, + @Cached(value = "createForList()", uncached = "getUncachedForList()", inline = false) NativeSlotNodes.FromWordNode fromWord) { + return fromWord.execute(storage.getWord(idx)); + } + + @Specialization(guards = "!isInstPtr(storage)") + protected static Object doComplexPtr(Node inliningTarget, ComplexPtrSequenceStorage storage, int idx) { + return storage.getItemNormalized(PythonLanguage.get(inliningTarget), idx); + } + @Specialization protected static int doNativeInt(NativeIntSequenceStorage storage, int idx) { return storage.getIntItemNormalized(idx); @@ -682,6 +730,11 @@ protected static EmptySequenceStorage doEmpty(EmptySequenceStorage storage, int return EmptySequenceStorage.INSTANCE; } + @Specialization + protected static SequenceStorage doComplexPtr(ComplexPtrSequenceStorage storage, int start, @SuppressWarnings("unused") int stop, int step, int length) { + return storage.getSliceCopy(start, step, length); + } + @Specialization protected static SequenceStorage doIntSequenceStorage(IntSequenceStorage storage, int start, int stop, int step, int length, @Bind Node inliningTarget) { @@ -1326,6 +1379,18 @@ protected static void doObject(@SuppressWarnings("unused") Node inliningTarget, storage.setObjectItemNormalized(idx, value); } + /** +1 on the stored instance (made native first if needed), -1 on the old word. */ + @Specialization(guards = "isListWordValue(value)") + protected static void doInstPtr(@SuppressWarnings("unused") Node inliningTarget, InstPtrSequenceStorage storage, int idx, Object value, + @Cached(inline = false) NativeSlotNodes.ToWordNode toWord) { + storage.setWordOwned(idx, toWord.execute(value)); + } + + @Specialization(guards = {"value.isExact()", "!isInstPtr(storage)"}) + protected static void doComplexPtr(@SuppressWarnings("unused") Node inliningTarget, ComplexPtrSequenceStorage storage, int idx, PComplex value) { + storage.setItemNormalized(idx, value); + } + @Specialization protected static void doForeign(Node inliningTarget, ForeignSequenceStorage storage, int idx, Object value, @Cached ForeignSequenceStorage.WriteNode writeNode) { @@ -1591,6 +1656,11 @@ public abstract static class ReverseNode extends PNodeWithContext { static void doEmpty(@SuppressWarnings("unused") EmptySequenceStorage storage) { } + @Specialization + static void doComplexPtr(ComplexPtrSequenceStorage storage) { + storage.reverse(); + } + @Specialization static void doIntStorage(Node inliningTarget, IntSequenceStorage storage) { storage.reverse(); @@ -1730,7 +1800,38 @@ abstract static class SetStorageSliceNode extends Node { public abstract void execute(SequenceStorage s, SliceInfo info, SequenceStorage iterable, boolean canGeneralize); - @Specialization(limit = "MAX_BASIC_STORAGES", guards = {"self.getClass() == cachedClass", "self.getClass() == sequence.getClass()", "replacesWholeSequence(cachedClass, self, info)"}) + /** Slice assignment into a pointer list keeps every count exact. */ + @Specialization + static void doComplexPtr(ComplexPtrSequenceStorage self, SliceInfo sinfo, SequenceStorage values, @SuppressWarnings("unused") boolean canGeneralize, + @Bind Node inliningTarget, + @Exclusive @Cached PRaiseNode raiseNode) { + long[] owned = ownedWords(self, values); + if (owned == null) { + throw new SequenceStoreException(values.getIndicativeValue()); + } + int n = owned.length; + int start = sinfo.start; + int stop = sinfo.stop; + int step = sinfo.step; + if (step == 1) { + if (start > stop) { + stop = start; + } + self.replaceRange(start, stop, owned, n); + } else { + int slicelen = sinfo.sliceLength; + if (n == 0) { + self.deleteSlice(start, step, slicelen); + } else if (n != slicelen) { + releaseOwned(self, owned); + throw raiseNode.raise(inliningTarget, ValueError, ErrorMessages.ATTEMPT_TO_ASSIGN_SEQ_OF_SIZE_TO_SLICE_OF_SIZE, n, slicelen); + } else { + self.setStepped(start, step, owned, n); + } + } + } + + @Specialization(limit = "MAX_BASIC_STORAGES", guards = {"self.getClass() == cachedClass", "self.getClass() == sequence.getClass()", "replacesWholeSequence(cachedClass, self, info)", "!isComplexPtr(self)"}) static void doWholeSequence(ArrayBasedSequenceStorage self, @SuppressWarnings("unused") SliceInfo info, ArrayBasedSequenceStorage sequence, @SuppressWarnings("unused") boolean canGeneralize, @Cached("self.getClass()") Class cachedClass) { ArrayBasedSequenceStorage selfProfiled = cachedClass.cast(self); @@ -1740,7 +1841,7 @@ static void doWholeSequence(ArrayBasedSequenceStorage self, @SuppressWarnings("u selfProfiled.minimizeCapacity(); } - @Specialization(guards = {"!canGeneralize || isDataTypeCompatibleNode.execute(inliningTarget, self, values)", "sinfo.step == 1"}, limit = "1") + @Specialization(guards = {"!isComplexPtr(self)", "!canGeneralize || isDataTypeCompatibleNode.execute(inliningTarget, self, values)", "sinfo.step == 1"}, limit = "1") static void singleStep(SequenceStorage self, SliceInfo sinfo, SequenceStorage values, @SuppressWarnings("unused") boolean canGeneralize, @Bind Node inliningTarget, @Exclusive @Cached @SuppressWarnings("unused") IsDataTypeCompatibleNode isDataTypeCompatibleNode, @@ -1766,7 +1867,7 @@ static void singleStep(SequenceStorage self, SliceInfo sinfo, SequenceStorage va singleStep(self, start, stop, data, needed, inliningTarget, setLenNode, ensureCapacityNode, memove, memcpy, memoryError, negGrowth, posGrowth, raiseNode); } - @Specialization(guards = {"!canGeneralize || isDataTypeCompatibleNode.execute(inliningTarget, self, values)", "sinfo.step != 1"}, limit = "1") + @Specialization(guards = {"!isComplexPtr(self)", "!canGeneralize || isDataTypeCompatibleNode.execute(inliningTarget, self, values)", "sinfo.step != 1"}, limit = "1") static void multiStep(SequenceStorage self, SliceInfo sinfo, SequenceStorage values, @SuppressWarnings("unused") boolean canGeneralize, @Bind Node inliningTarget, @Exclusive @Cached @SuppressWarnings("unused") IsDataTypeCompatibleNode isDataTypeCompatibleNode, @@ -1800,7 +1901,7 @@ static void multiStep(SequenceStorage self, SliceInfo sinfo, SequenceStorage val } } - @Specialization(guards = {"canGeneralize", "!isAssignCompatibleNode.execute(inliningTarget, self, sequence)"}, limit = "1") + @Specialization(guards = {"!isComplexPtr(self)", "canGeneralize", "!isAssignCompatibleNode.execute(inliningTarget, self, sequence)"}, limit = "1") static void doError(@SuppressWarnings("unused") SequenceStorage self, @SuppressWarnings("unused") SliceInfo info, SequenceStorage sequence, @SuppressWarnings("unused") boolean canGeneralize, @SuppressWarnings("unused") @Bind Node inliningTarget, @Cached @SuppressWarnings("unused") IsAssignCompatibleNode isAssignCompatibleNode) { @@ -2275,7 +2376,7 @@ static SequenceStorage doRightEmpty(@SuppressWarnings("unused") EmptySequenceSto } } - @Specialization(guards = {"dest == left", "left.getClass() == right.getClass()", "cachedClass == left.getClass()"}, limit = "1") + @Specialization(guards = {"dest == left", "left.getClass() == right.getClass()", "cachedClass == left.getClass()", "!isComplexPtr(left)"}, limit = "1") static SequenceStorage doArrayBasedManagedManagedSameTypeInplace(@SuppressWarnings("unused") ArrayBasedSequenceStorage dest, ArrayBasedSequenceStorage left, ArrayBasedSequenceStorage right, @Bind Node inliningTarget, @Cached("left.getClass()") Class cachedClass, @@ -2291,7 +2392,7 @@ static SequenceStorage doArrayBasedManagedManagedSameTypeInplace(@SuppressWarnin return leftProfiled; } - @Specialization(guards = {"dest != left", "dest.getClass() == left.getClass()", "left.getClass() == right.getClass()", "cachedClass == dest.getClass()"}, limit = "1") + @Specialization(guards = {"dest != left", "dest.getClass() == left.getClass()", "left.getClass() == right.getClass()", "cachedClass == dest.getClass()", "!isComplexPtr(dest)"}, limit = "1") static SequenceStorage doArrayBasedManagedManagedSameType(ArrayBasedSequenceStorage dest, ArrayBasedSequenceStorage left, ArrayBasedSequenceStorage right, @Bind Node inliningTarget, @Cached("left.getClass()") Class cachedClass, @@ -2308,7 +2409,7 @@ static SequenceStorage doArrayBasedManagedManagedSameType(ArrayBasedSequenceStor return destProfiled; } - @Specialization(guards = {"dest.getClass() == right.getClass()", "cachedClass == dest.getClass()"}, limit = "1") + @Specialization(guards = {"dest.getClass() == right.getClass()", "cachedClass == dest.getClass()", "!isComplexPtr(dest)"}, limit = "1") static SequenceStorage doArrayBasedEmptyManagedSameType(ArrayBasedSequenceStorage dest, @SuppressWarnings("unused") EmptySequenceStorage left, ArrayBasedSequenceStorage right, @Bind Node inliningTarget, @Cached("dest.getClass()") Class cachedClass, @@ -2322,7 +2423,7 @@ static SequenceStorage doArrayBasedEmptyManagedSameType(ArrayBasedSequenceStorag return destProfiled; } - @Specialization(guards = {"dest.getClass() == left.getClass()", "cachedClass == dest.getClass()"}, limit = "1") + @Specialization(guards = {"dest.getClass() == left.getClass()", "cachedClass == dest.getClass()", "!isComplexPtr(dest)"}, limit = "1") static SequenceStorage doArrayBasedManagedEmptySameType(ArrayBasedSequenceStorage dest, ArrayBasedSequenceStorage left, @SuppressWarnings("unused") EmptySequenceStorage right, @Bind Node inliningTarget, @Cached("left.getClass()") Class cachedClass, @@ -2526,6 +2627,19 @@ protected RepeatNode(PythonBuiltinClassType errorForOverflow) { public abstract SequenceStorage execute(VirtualFrame frame, SequenceStorage left, int times); + @Specialization(guards = "times > 0") + SequenceStorage doComplexPtr(ComplexPtrSequenceStorage s, int times, + @Bind Node inliningTarget, + @Exclusive @Cached PRaiseNode raiseNode) { + try { + return s.repeat(times); + } catch (OutOfMemoryError e) { + throw raiseNode.raise(inliningTarget, MemoryError); + } catch (ArithmeticException e) { + throw raiseNode.raise(inliningTarget, errorForOverflow); + } + } + @Specialization static SequenceStorage doEmpty(EmptySequenceStorage s, @SuppressWarnings("unused") int times) { return s; @@ -2634,7 +2748,7 @@ ObjectSequenceStorage doObjectSingleElement(ObjectSequenceStorage s, int times, } } - @Specialization(limit = "MAX_BASIC_STORAGES", guards = {"times > 0", "!isNative(s)", "s.getClass() == cachedClass"}) + @Specialization(limit = "MAX_BASIC_STORAGES", guards = {"times > 0", "!isNative(s)", "s.getClass() == cachedClass", "!isComplexPtr(s)"}) SequenceStorage doArrayBasedManaged(ArrayBasedSequenceStorage s, int times, @Bind Node inliningTarget, @Shared @Cached PRaiseNode raiseNode, @@ -2656,7 +2770,7 @@ SequenceStorage doArrayBasedManaged(ArrayBasedSequenceStorage s, int times, } } - @Specialization(replaces = "doArrayBasedManaged", guards = "times > 0") + @Specialization(replaces = "doArrayBasedManaged", guards = {"times > 0", "!isComplexPtr(s)"}) @SuppressWarnings("truffle-static-method") SequenceStorage doGeneric(SequenceStorage s, int times, @Bind Node inliningTarget, @@ -2933,7 +3047,58 @@ static DoubleSequenceStorage doEmptyDouble(@SuppressWarnings("unused") EmptySequ } protected static boolean isKnownType(Object val) { - return val instanceof Byte || val instanceof Integer || val instanceof Long || val instanceof Double; + return val instanceof Byte || val instanceof Integer || val instanceof Long || val instanceof Double || isNativeComplexCandidate(val) || isNativeInstCandidate(val); + } + + /** + * A native-layout instance or None (once an opt-in class exists) starts a + * pointer-aware list (never at image build time). + */ + protected static boolean isNativeInstCandidate(Object val) { + return NativeInstance.isListWordValue(val) && !ImageInfo.inImageBuildtimeCode(); + } + + @Specialization(guards = "isNativeInstCandidate(val)") + static InstPtrSequenceStorage doEmptyInst(Node inliningTarget, @SuppressWarnings("unused") EmptySequenceStorage s, @SuppressWarnings("unused") Object val) { + return new InstPtrSequenceStorage(NativeInstance.state(PythonContext.get(inliningTarget)), ArrayBasedSequenceStorage.DEFAULT_CAPACITY); + } + + protected static boolean isInstOrSame(Object val) { + return NativeInstance.isListWordValue(val) || val instanceof InstPtrSequenceStorage; + } + + @Specialization(guards = "isInstOrSame(val)") + static InstPtrSequenceStorage doInstInst(InstPtrSequenceStorage s, @SuppressWarnings("unused") Object val) { + return s; + } + + @Specialization(guards = "!isInstOrSame(val)") + static ObjectSequenceStorage doInstGeneric(Node inliningTarget, InstPtrSequenceStorage s, @SuppressWarnings("unused") Object val) { + return generalizeComplexPtr(PythonLanguage.get(inliningTarget), s); + } + + /** An exact complex that starts a pointer list (never at image build time). */ + protected static boolean isNativeComplexCandidate(Object val) { + return val instanceof PComplex c && c.isExact() && !ImageInfo.inImageBuildtimeCode(); + } + + @Specialization(guards = "isNativeComplexCandidate(val)") + static ComplexPtrSequenceStorage doEmptyComplex(Node inliningTarget, @SuppressWarnings("unused") EmptySequenceStorage s, @SuppressWarnings("unused") Object val) { + return new ComplexPtrSequenceStorage(PythonContext.get(inliningTarget).getNativeComplexState(), ArrayBasedSequenceStorage.DEFAULT_CAPACITY); + } + + protected static boolean isExactComplexOrSame(Object val) { + return val instanceof PComplex c && c.isExact() || val instanceof ComplexPtrSequenceStorage c2 && !c2.isInst(); + } + + @Specialization(guards = {"isExactComplexOrSame(val)", "!s.isInst()"}) + static ComplexPtrSequenceStorage doComplexComplex(ComplexPtrSequenceStorage s, @SuppressWarnings("unused") Object val) { + return s; + } + + @Specialization(guards = {"!isExactComplexOrSame(val)", "!s.isInst()"}) + static ObjectSequenceStorage doComplexGeneric(Node inliningTarget, ComplexPtrSequenceStorage s, @SuppressWarnings("unused") Object val) { + return generalizeComplexPtr(PythonLanguage.get(inliningTarget), s); } @Specialization(guards = "!isKnownType(val)") @@ -3012,7 +3177,7 @@ static SequenceStorage doGeneric(Node inliningTarget, SequenceStorage s, Object protected static boolean isFallbackCase(SequenceStorage s, Object value) { // there are explicit specializations for all cases with EmptySequenceStorage - if (s instanceof EmptySequenceStorage || s instanceof ObjectSequenceStorage || s instanceof NativeSequenceStorage) { + if (s instanceof EmptySequenceStorage || s instanceof ObjectSequenceStorage || s instanceof NativeSequenceStorage || s instanceof ComplexPtrSequenceStorage) { return false; } if ((s instanceof ByteSequenceStorage || s instanceof IntSequenceStorage || s instanceof LongSequenceStorage) && @@ -3136,6 +3301,16 @@ abstract static class CreateEmptyForTypeNode extends SequenceStorageBaseNode { public abstract ArrayBasedSequenceStorage execute(Node inliningTarget, StorageType type, int cap); + @Specialization(guards = "isInstPtrType(type)") + static InstPtrSequenceStorage doInstPtr(Node inliningTarget, @SuppressWarnings("unused") StorageType type, int cap) { + return new InstPtrSequenceStorage(NativeInstance.state(PythonContext.get(inliningTarget)), Math.max(cap, 1)); + } + + @Specialization(guards = "isComplexPtrType(type)") + static ComplexPtrSequenceStorage doComplexPtr(Node inliningTarget, @SuppressWarnings("unused") StorageType type, int cap) { + return new ComplexPtrSequenceStorage(PythonContext.get(inliningTarget).getNativeComplexState(), Math.max(cap, 1)); + } + @Specialization(guards = "isBoolean(type)") static BoolSequenceStorage doBoolean(@SuppressWarnings("unused") StorageType type, int cap) { return new BoolSequenceStorage(cap); @@ -3244,6 +3419,11 @@ static void doObject(ObjectSequenceStorage storage, int cap) { storage.ensureCapacity(cap); } + @Specialization + static void doComplexPtr(ComplexPtrSequenceStorage storage, int cap) { + storage.ensureCapacity(cap); + } + @Specialization static void doNativePrimitive(NativePrimitiveSequenceStorage storage, int cap) { if (CompilerDirectives.injectBranchProbability(CompilerDirectives.UNLIKELY_PROBABILITY, cap > storage.getCapacity())) { @@ -3334,6 +3514,11 @@ static SequenceStorage doEmpty(EmptySequenceStorage s) { return s; } + @Specialization + static SequenceStorage doComplexPtr(Node inliningTarget, ComplexPtrSequenceStorage storage) { + return new ObjectSequenceStorage(storage.getCopyOfInternalArray(PythonLanguage.get(inliningTarget))); + } + @Specialization static SequenceStorage doInt(IntSequenceStorage storage) { return new IntSequenceStorage(PythonUtils.arrayCopyOf(storage.getInternalIntArray(), storage.length())); @@ -3422,6 +3607,11 @@ public static Object[] executeUncached(SequenceStorage s) { return SequenceStorageNodesFactory.CopyInternalArrayNodeGen.getUncached().execute(null, s); } + @Specialization + static Object[] doComplexPtr(Node inliningTarget, ComplexPtrSequenceStorage storage) { + return storage.getCopyOfInternalArray(PythonLanguage.get(inliningTarget)); + } + @Specialization static Object[] doInt(Node inliningTarget, IntSequenceStorage storage) { return storage.getCopyOfInternalArray(inliningTarget); @@ -3482,9 +3672,15 @@ public abstract static class SetLenNode extends PNodeWithContext { public abstract void execute(Node inliningTarget, SequenceStorage s, int len); + /* + * The exact class profile lets compiled code bind setNewLength statically: once a storage + * class overrides it (the pointer storages of the native object model), the call is + * otherwise virtual and stays an out-of-line call in every del/pop/clear of a list. + */ @Specialization - static void doBasic(ArrayBasedSequenceStorage s, int len) { - s.setNewLength(len); + static void doBasic(Node inliningTarget, ArrayBasedSequenceStorage s, int len, + @Cached InlinedExactClassProfile storageClassProfile) { + storageClassProfile.profile(inliningTarget, s).setNewLength(len); } @Specialization @@ -3623,13 +3819,21 @@ public abstract static class DeleteItemNode extends SequenceStorageBaseNode { public abstract void execute(Node node, SequenceStorage s, int idx); + @Specialization + static void doComplexPtr(ComplexPtrSequenceStorage s, int idx) { + long p = s.removePtr(idx); + if (p != 0) { + s.decw(p); + } + } + @Specialization(guards = {"isLastItem(s, idx)", "!isForeignSequenceStorage(s)"}) static void doLastItem(Node inliningTarget, SequenceStorage s, @SuppressWarnings("unused") int idx, @Exclusive @Cached SetLenNode setLenNode) { setLenNode.execute(inliningTarget, s, s.length() - 1); } - @Specialization(guards = {"!isNativeObjectStorage(s)", "!isForeignSequenceStorage(s)"}) + @Specialization(guards = {"!isNativeObjectStorage(s)", "!isForeignSequenceStorage(s)", "!isComplexPtr(s)"}) static void doGeneric(Node inliningTarget, SequenceStorage s, int idx, @Cached GetItemScalarNode getItemNode, @Cached SetItemScalarNode setItemNode, @@ -3672,7 +3876,20 @@ public abstract static class DeleteSliceNode extends SequenceStorageBaseNode { public abstract void execute(Node inliningTarget, SequenceStorage s, SliceInfo info); - @Specialization(guards = "sinfo.step == 1") + @Specialization + static void doComplexPtr(ComplexPtrSequenceStorage store, SliceInfo sinfo) { + int start = sinfo.start; + int step = sinfo.step; + int slicelen = sinfo.sliceLength; + if (step < 0) { + // same normalization as multipleSteps: delete the same elements in ascending order + start = start + step * (slicelen - 1); + step = -step; + } + store.deleteSlice(start, step, slicelen); + } + + @Specialization(guards = {"!isComplexPtr(store)", "sinfo.step == 1"}) static void singleStep(Node inliningTarget, SequenceStorage store, SliceInfo sinfo, @Cached InlinedConditionProfile shortCircuitProfile, @Exclusive @Cached SetLenNode setLenNode, @@ -3711,7 +3928,7 @@ static void singleStep(Node inliningTarget, SequenceStorage store, SliceInfo sin setLenNode.execute(inliningTarget, store, length + d); } - @Specialization(guards = "sinfo.step != 1") + @Specialization(guards = {"!isComplexPtr(store)", "sinfo.step != 1"}) static void multipleSteps(Node inliningTarget, SequenceStorage store, SliceInfo sinfo, @Cached EnsureCapacityNode ensureCapacityNode, @Exclusive @Cached SetLenNode setLenNode, @@ -3778,6 +3995,12 @@ public abstract static class GetElementType extends Node { public abstract StorageType execute(Node inliningTarget, SequenceStorage s); + @Specialization + static StorageType type(ComplexPtrSequenceStorage s) { + // The instance-word subclass reports InstPtr + return s.getElementType(); + } + @Specialization static StorageType type(EmptySequenceStorage s) { return Empty; @@ -4008,6 +4231,41 @@ public abstract static class InsertItemArrayBasedStorageNode extends Node { protected abstract SequenceStorage execute(Node inliningTarget, ArrayBasedSequenceStorage storage, int index, Object value); + @Specialization(guards = "isListWordValue(value)") + static SequenceStorage doInstPtr(InstPtrSequenceStorage storage, int idx, Object value, + @Cached(inline = false) NativeSlotNodes.ToWordNode toWord) { + storage.insertWordOwned(idx, toWord.execute(value)); + return storage; + } + + @Specialization(guards = "!isListWordValue(value)") + static SequenceStorage doInstPtrGeneralize(Node inliningTarget, InstPtrSequenceStorage storage, int idx, Object value) { + ObjectSequenceStorage newStorage = generalizeComplexPtr(PythonLanguage.get(inliningTarget), storage); + newStorage.insertItem(idx, value); + return newStorage; + } + + @Specialization(guards = {"value.isExact()", "!storage.isInst()"}) + static SequenceStorage doComplexPtr(ComplexPtrSequenceStorage storage, int idx, PComplex value) { + storage.insertItem(idx, value); + return storage; + } + + @Specialization(guards = {"!isExactComplex(value)", "!storage.isInst()"}) + static SequenceStorage doComplexPtrGeneralize(Node inliningTarget, ComplexPtrSequenceStorage storage, int idx, Object value) { + ObjectSequenceStorage newStorage = generalizeComplexPtr(PythonLanguage.get(inliningTarget), storage); + newStorage.insertItem(idx, value); + return newStorage; + } + + protected static boolean isListWordValue(Object v) { + return NativeInstance.isListWordValue(v); + } + + protected static boolean isExactComplex(Object value) { + return value instanceof PComplex c && c.isExact(); + } + @Specialization static SequenceStorage doIntStorage(IntSequenceStorage storage, int idx, int value) { storage.insertIntItem(idx, value); @@ -4435,4 +4693,91 @@ public static CreateStorageFromIteratorNode getUncached() { return CreateStorageFromIteratorUncachedNode.INSTANCE; } } + + /** + * Replaces a pointer list storage by an object storage. The elements become Java + * complex objects (value copies) and every element reference is dropped. + */ + @TruffleBoundary + public static ObjectSequenceStorage generalizeComplexPtr(PythonLanguage language, ComplexPtrSequenceStorage s) { + Object[] boxed = s.getCopyOfInternalArray(language); + // The object storage pins boxed instances before the list's references are dropped + ObjectSequenceStorage res = new ObjectSequenceStorage(boxed); + if (s.isInst()) { + NativeInstance.count(NativeInstance.C_LIST_GENERALIZE); + } + s.releaseAllAndClear(); + return res; + } + + /** + * Counted words for every element of {@code values} if they all fit {@code self}'s kind (pointer + * storage of the same kind, empty storage, or object storage of fitting values); else null. + */ + @TruffleBoundary + static long[] ownedWords(ComplexPtrSequenceStorage self, SequenceStorage values) { + if (!self.isInst()) { + if (values instanceof ComplexPtrSequenceStorage c && c.isInst()) { + return null; + } + return complexOwnedPtrs(self.getState(), values); + } + if (values instanceof InstPtrSequenceStorage c) { + return c.getCountedPtrs(); + } else if (values instanceof EmptySequenceStorage) { + return new long[0]; + } else if (values instanceof ObjectSequenceStorage o) { + Object[] arr = o.getInternalObjectArray(); + int n = o.length(); + for (int i = 0; i < n; i++) { + if (!NativeInstance.isListWordValue(arr[i])) { + return null; + } + } + PythonContext ctx = PythonContext.get(null); + long st = NativeInstance.state(ctx); + long[] res = new long[n]; + for (int i = 0; i < n; i++) { + res[i] = NativeInstance.toWordGeneric(ctx, st, arr[i]); + } + return res; + } + return null; + } + + static void releaseOwned(ComplexPtrSequenceStorage self, long[] owned) { + for (long w : owned) { + self.decw(w); + } + } + + /** + * Counted pointers for every element of {@code values} if all are exact complex + * (pointer storage, empty storage, or object storage holding only exact complex); else null. + */ + static long[] complexOwnedPtrs(long state, SequenceStorage values) { + if (values instanceof ComplexPtrSequenceStorage c) { + return c.getCountedPtrs(); + } else if (values instanceof EmptySequenceStorage) { + return new long[0]; + } else if (values instanceof ObjectSequenceStorage o) { + Object[] arr = o.getInternalObjectArray(); + int n = o.length(); + for (int i = 0; i < n; i++) { + if (!(arr[i] instanceof PComplex c && c.isExact())) { + return null; + } + } + long[] res = new long[n]; + for (int i = 0; i < n; i++) { + long p = NativeComplex.materialize(state, (PComplex) arr[i]); + NativeComplex.incref(p); + res[i] = p; + } + return res; + } + return null; + } + + } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/complex/PComplex.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/complex/PComplex.java index 4d340011cf..c98e18033f 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/complex/PComplex.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/complex/PComplex.java @@ -25,7 +25,9 @@ */ package com.oracle.graal.python.builtins.objects.complex; +import com.oracle.graal.python.builtins.PythonBuiltinClassType; import com.oracle.graal.python.builtins.objects.object.PythonBuiltinObject; +import com.oracle.graal.python.builtins.objects.type.PythonBuiltinClass; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; import com.oracle.truffle.api.object.Shape; @@ -33,11 +35,44 @@ public final class PComplex extends PythonBuiltinObject { private final double real; private final double imag; + /** Exact type {@code complex} (not a subclass). */ + private final boolean exact; + /** + * Unowned pointer to a native struct holding the same value (0 = none) and the + * serial the struct had when the pointer was recorded. Not counted in the native refcount; may + * be stale (see {@code NativeComplex}). + */ + private long nativePtr; + private long serial; public PComplex(Object clazz, Shape instanceShape, double real, double imaginary) { super(clazz, instanceShape); this.real = real; this.imag = imaginary; + this.exact = clazz == PythonBuiltinClassType.PComplex || (clazz instanceof PythonBuiltinClass b && b.getType() == PythonBuiltinClassType.PComplex); + } + + public PComplex(Object clazz, Shape instanceShape, double real, double imaginary, long nativePtr, long serial) { + this(clazz, instanceShape, real, imaginary); + this.nativePtr = nativePtr; + this.serial = serial; + } + + public boolean isExact() { + return exact; + } + + public long getNativePtr() { + return nativePtr; + } + + public long getSerial() { + return serial; + } + + public void setNative(long ptr, long ser) { + this.nativePtr = ptr; + this.serial = ser; } @Override diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/floats/PNativeFloat.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/floats/PNativeFloat.java new file mode 100644 index 0000000000..dda6841a30 --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/floats/PNativeFloat.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2017, 2025, Oracle and/or its affiliates. + * Copyright (c) 2014, Regents of the University of California + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other materials provided + * with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package com.oracle.graal.python.builtins.objects.floats; + +import com.oracle.truffle.api.object.Shape; + +/** + * In-flight value copy of an instance of a native subclass of + * {@code float} whose instances are nothing but (type, {@code ob_fval}) (see + * {@code NativeSmall.isFloatValueType}). The class is the native type. {@code structHint} is the + * struct this value was last converted from or to (0 if none) and {@code structGen} its pool generation + * word at that time; it is a hint only: before reuse it is checked to be the same incarnation (generation + * unchanged) and alive with the same type and bits. Not counted: the struct may be freed under it. + */ +public final class PNativeFloat extends PFloat { + + private long structHint; + private long structGen; + + public PNativeFloat(Object clazz, Shape instanceShape, double value, long structHint, long structGen) { + super(clazz, instanceShape, value); + this.structHint = structHint; + this.structGen = structGen; + } + + public long getStructHint() { + return structHint; + } + + public long getStructGen() { + return structGen; + } + + public void setStructHint(long p, long gen) { + this.structHint = p; + this.structGen = gen; + } +} diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/getsetdescriptor/DescriptorBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/getsetdescriptor/DescriptorBuiltins.java index 4aa4bda8c1..8d04ad3f79 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/getsetdescriptor/DescriptorBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/getsetdescriptor/DescriptorBuiltins.java @@ -150,9 +150,15 @@ Object doGetSetDescriptor(VirtualFrame frame, GetSetDescriptor descr, Object obj static Object doIndexedSlotDescriptor(IndexedSlotDescriptor descr, PythonAbstractObject obj, @Bind Node inliningTarget, @Exclusive @Cached PRaiseNode raiseNode, - @Cached GetOrCreateIndexedSlots getSlotsNode) { - Object[] slots = getSlotsNode.execute(inliningTarget, obj); - Object val = slots[descr.getIndex()]; + @Cached GetOrCreateIndexedSlots getSlotsNode, + @Cached com.oracle.graal.python.runtime.nativeaccess.NativeSlotNodes.ReadSlotNode readSlot) { + Object val; + if (readSlot.profileNative(obj instanceof com.oracle.graal.python.builtins.objects.object.PNativeLayoutObject n && n.getSlotsPtr() != 0)) { + val = readSlot.execute((com.oracle.graal.python.builtins.objects.object.PNativeLayoutObject) obj, descr.getIndex()); + } else { + Object[] slots = getSlotsNode.execute(inliningTarget, obj); + val = slots[descr.getIndex()]; + } if (val != null) { return val; } @@ -179,12 +185,32 @@ Object doGetSetDescriptor(VirtualFrame frame, GetSetDescriptor descr, Object obj @Specialization static Object doIndexedSlotDescriptor(IndexedSlotDescriptor descr, PythonAbstractObject obj, Object value, @Bind Node inliningTarget, - @Cached GetOrCreateIndexedSlots getSlotsNode) { - getSlotsNode.execute(inliningTarget, obj)[descr.getIndex()] = value; + @Cached GetOrCreateIndexedSlots getSlotsNode, + @Cached com.oracle.graal.python.runtime.nativeaccess.NativeSlotNodes.WriteSlotNode writeSlot) { + writeIndexedSlot(inliningTarget, obj, descr.getIndex(), value, getSlotsNode, writeSlot); return true; } } + /** + * Slot write shared by the descriptor and the bytecode fast path. A native + * instance writes its struct; a not-yet-native opt-in instance keeps the value in its Java slots + * (they become native together with it); any other object's slots are a Java-heap location, so a + * native-layout value stored there is pinned. + */ + public static void writeIndexedSlot(Node inliningTarget, PythonAbstractObject obj, int index, Object value, GetOrCreateIndexedSlots getSlotsNode, + com.oracle.graal.python.runtime.nativeaccess.NativeSlotNodes.WriteSlotNode writeSlot) { + if (obj instanceof com.oracle.graal.python.builtins.objects.object.PNativeLayoutObject n) { + if (n.getSlotsPtr() != 0) { + writeSlot.execute(n, index, value); + return; + } + } else { + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value); + } + getSlotsNode.execute(inliningTarget, obj)[index] = value; + } + @GenerateInline(value = false) public abstract static class DescrDeleteNode extends Node { public abstract Object execute(VirtualFrame frame, Object descr, Object obj); @@ -213,6 +239,12 @@ Object doIndexedSlotDescriptor(IndexedSlotDescriptor descr, PythonAbstractObject @Exclusive @Cached PRaiseNode raiseNode, @Cached GetOrCreateIndexedSlots getSlotsNode, @Cached InlinedConditionProfile profile) { + if (obj instanceof com.oracle.graal.python.builtins.objects.object.PNativeLayoutObject n && n.getSlotsPtr() != 0) { + if (com.oracle.graal.python.runtime.nativeaccess.NativeSlotNodes.WriteSlotNode.getUncached().execute(n, descr.getIndex(), null)) { + return PNone.NONE; + } + throw raiseNode.raise(inliningTarget, PythonBuiltinClassType.AttributeError, ErrorMessages.S, descr.getName()); + } // PyMember_SetOne - Check if the attribute is set. Object[] slots = getSlotsNode.execute(inliningTarget, obj); if (profile.profile(inliningTarget, slots[descr.getIndex()] != null)) { @@ -233,12 +265,20 @@ public static Object[] executeKnownCount(Node inliningTarget, InlinedBranchProfi Object[] slots = object.getIndexedSlots(); if (slots == null) { initProfile.enter(inliningTarget); + checkNotNative(object); slots = new Object[slotsCount]; object.setIndexedSlots(slots); } return slots; } + /** A native instance has no Java slots; creating them would fork its state. */ + static void checkNotNative(PythonAbstractObject object) { + if (object instanceof com.oracle.graal.python.builtins.objects.object.PNativeLayoutObject n && n.getSlotsPtr() != 0) { + throw com.oracle.truffle.api.CompilerDirectives.shouldNotReachHere("Java slots requested for a native instance"); + } + } + @Specialization(guards = "object.getIndexedSlots() != null") static Object[] doGet(PythonAbstractObject object) { return object.getIndexedSlots(); @@ -248,6 +288,7 @@ static Object[] doGet(PythonAbstractObject object) { static Object[] doCreate(Node inliningTarget, PythonAbstractObject object, @Cached GetIndexedSlotsCountNode getIndexedSlotsCountNode, @Cached GetClassNode getClassNode) { + checkNotNative(object); Object cls = getClassNode.execute(inliningTarget, object); int slotCount = getIndexedSlotsCountNode.execute(inliningTarget, cls); Object[] slots = new Object[slotCount]; diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/list/ListBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/list/ListBuiltins.java index ccc2edb21b..5394d8fc64 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/list/ListBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/list/ListBuiltins.java @@ -487,6 +487,10 @@ static PList copySequence(Object list, @Cached TypeNodes.GetInstanceShape getInstanceShape) { var sequenceStorage = getStorageNode.execute(inliningTarget, list); Object newClass = getClassForNewListNode.execute(inliningTarget, list); + if (sequenceStorage instanceof com.oracle.graal.python.runtime.sequence.storage.ComplexPtrSequenceStorage cp) { + // List copies keep the pointer representation (each element counted) + return PFactory.createList(newClass, getInstanceShape.execute(newClass), cp.copyCounted()); + } return PFactory.createList(newClass, getInstanceShape.execute(newClass), copy.execute(inliningTarget, sequenceStorage)); } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/object/ObjectBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/object/ObjectBuiltins.java index b4a7fcb738..8ab7a9523a 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/object/ObjectBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/object/ObjectBuiltins.java @@ -296,7 +296,28 @@ static void check(Node inliningTarget, Object type, Object[] args, PKeyword[] kw } } - @Specialization(guards = {"!self.needsNativeAllocation()"}) + static boolean isNativeLayout(Object self) { + return self instanceof com.oracle.graal.python.builtins.objects.type.PythonClass pc && pc.getNativeLayoutId() != 0; + } + + /** + * Instances of native-layout classes. A separate specialization (not a branch + * in doManagedObject) so compiled code does not merge two allocation types, which would force + * escape analysis to materialize the new object. + */ + @Specialization(guards = {"isNativeLayout(self)"}) + Object doNativeLayoutObject(VirtualFrame frame, PythonManagedClass self, Object[] varargs, PKeyword[] kwargs, + @Bind Node inliningTarget, + @Shared @Cached CheckExcessArgsNode checkExcessArgsNode, + @Shared @Cached TypeNodes.GetInstanceShape getInstanceShape) { + checkExcessArgsNode.execute(inliningTarget, self, varargs, kwargs); + if (self.isAbstractClass()) { + throw reportAbstractClass(frame, self); + } + return new com.oracle.graal.python.builtins.objects.object.PNativeLayoutObject(self, getInstanceShape.execute(self)); + } + + @Specialization(guards = {"!self.needsNativeAllocation()", "!isNativeLayout(self)"}) Object doManagedObject(VirtualFrame frame, PythonManagedClass self, Object[] varargs, PKeyword[] kwargs, @Bind Node inliningTarget, @Shared @Cached CheckExcessArgsNode checkExcessArgsNode, @@ -429,11 +450,21 @@ public long hash(PythonBuiltinClassType self) { return hash(getContext().lookupType(self)); } + /** Default hash of a native-layout instance derives from the struct pointer. */ + @Specialization + public static long hash(PNativeLayoutObject self) { + return Long.rotateRight(com.oracle.graal.python.runtime.nativeaccess.NativeInstance.identity(self), 4); + } + @TruffleBoundary - @Specialization(guards = "!isPythonBuiltinClassType(self)") + @Specialization(guards = {"!isPythonBuiltinClassType(self)", "!isNativeLayout(self)"}) public static long hash(Object self) { return self.hashCode(); } + + protected static boolean isNativeLayout(Object self) { + return self instanceof PNativeLayoutObject; + } } @Slot(value = SlotKind.tp_richcompare, isComplex = true) diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/object/ObjectNodes.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/object/ObjectNodes.java index eb488a5cbb..ff6749422c 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/object/ObjectNodes.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/object/ObjectNodes.java @@ -387,8 +387,15 @@ static Object id(PString self, return getObjectIdNode.execute(inliningTarget, self); } + /** The struct pointer, equal for every in-flight copy (made native and pinned if needed). */ + @Specialization + static Object id(PNativeLayoutObject self) { + return com.oracle.graal.python.runtime.nativeaccess.NativeInstance.identity(self); + } + protected static boolean isDefaultCase(PythonObject object) { - return !(object instanceof PBytes || + return !(object instanceof PNativeLayoutObject || + object instanceof PBytes || object instanceof PFrozenSet || object instanceof PTuple || object instanceof PInt || @@ -654,7 +661,7 @@ static boolean doManaged(Object obj, @SuppressWarnings("unused") Object type, @S * * See: typeobject.c:_PyObject_GetState */ - return obj.getClass() == PythonObject.class; + return obj.getClass() == PythonObject.class || obj.getClass() == com.oracle.graal.python.builtins.objects.object.PNativeLayoutObject.class; } } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/object/PNativeLayoutObject.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/object/PNativeLayoutObject.java new file mode 100644 index 0000000000..f91c5f055d --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/object/PNativeLayoutObject.java @@ -0,0 +1,93 @@ +/* + * 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.object; + +import com.oracle.truffle.api.object.Shape; + +/** + * An instance of a class that declares {@code __slots__} and + * {@code __native_layout__ = True} (derived directly from {@code object}). + * + *

+ * While {@link #slotsPtr} is 0 the slots live in the Java object ({@code indexedSlots}) as for any + * other slots class. Once it is set, the native struct is the only copy of the slots and this Java + * object is an in-flight reference to it (several Java objects may refer to the same struct; identity + * is the pointer). See {@code NativeInstance}. + *

+ */ +public final class PNativeLayoutObject extends PythonObject { + private long slotsPtr; + /** Debug mode only: serial of the struct incarnation this object refers to. */ + private long serial; + /** True once this Java object holds a pin (+1) on its struct. */ + private boolean pinned; + + public PNativeLayoutObject(Object pythonClass, Shape instanceShape) { + super(pythonClass, instanceShape); + } + + public PNativeLayoutObject(Object pythonClass, Shape instanceShape, long slotsPtr, long serial) { + super(pythonClass, instanceShape); + this.slotsPtr = slotsPtr; + this.serial = serial; + } + + public long getSlotsPtr() { + return slotsPtr; + } + + public void setSlotsPtr(long slotsPtr, long serial) { + this.slotsPtr = slotsPtr; + this.serial = serial; + } + + public long getSerial() { + return serial; + } + + public boolean isPinned() { + return pinned; + } + + public void setPinned() { + this.pinned = true; + } +} diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/type/PythonClass.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/type/PythonClass.java index a4226ed02e..b0934c16c3 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/type/PythonClass.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/type/PythonClass.java @@ -73,6 +73,17 @@ public final class PythonClass extends PythonManagedClass { private MroShape mroShape; private byte mroShapeInvalidationsCount; + /** Id of a native-layout class (see NativeInstance), 0 otherwise. */ + @com.oracle.truffle.api.CompilerDirectives.CompilationFinal private int nativeLayoutId; + + public int getNativeLayoutId() { + return nativeLayoutId; + } + + public void setNativeLayoutId(int id) { + this.nativeLayoutId = id; + } + /** Assumption for instance attribute fast paths, which are only used in single-context mode. */ private final LazyCyclicAssumption typeStableAssumption; diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/type/TypeNodes.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/type/TypeNodes.java index 010868bed4..4e0f1a3365 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/type/TypeNodes.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/type/TypeNodes.java @@ -2177,6 +2177,8 @@ static PythonClass typeMetaclass(VirtualFrame frame, TruffleString name, PTuple LoopNode.reportLoopCount(inliningTarget, ctx.copiedSlots.length); } pythonClass.setIndexedSlotCount(indexedSlotCount); + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.maybeRegister(pythonClass, base, basesArray.length, indexedSlotCount, ctx.copiedSlots != null && ctx.copiedSlots.length > 0, + ctx.addDict, ctx.addWeak); if (ctx.addDict) { addDictDescrAttribute(basesArray, pythonClass, language); diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/type/slots/TpSlotVarargs.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/type/slots/TpSlotVarargs.java index e24d6d70cb..99a251b648 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/type/slots/TpSlotVarargs.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/type/slots/TpSlotVarargs.java @@ -407,6 +407,9 @@ private static long invokeVectorcall(VirtualFrame frame, long vectorcallPointer, long callable, long args, long nargs, long keywordNames) { Object state = BoundaryCallContext.enter(frame, threadState, boundaryCallData); CApiTiming.enter(); + // The raw invoker does not count the downcall depth; without this, a nested + // downcall made while the vectorcall runs releases the borrowed copies of its arguments + com.oracle.graal.python.runtime.nativeaccess.NativeComplex.enterDowncall(); try { return ExternalFunctionInvoker.invokeVECTORCALL(vectorcallPointer, callable, args, nargs, keywordNames); } catch (Throwable exception) { @@ -414,6 +417,7 @@ private static long invokeVectorcall(VirtualFrame frame, long vectorcallPointer, GilNode.uncachedAcquire(); throw CompilerDirectives.shouldNotReachHere(exception); } finally { + com.oracle.graal.python.runtime.nativeaccess.NativeComplex.exitDowncall(); CApiTiming.exit(C_API_TIMING_VECTORCALL); if (frame != null && threadState.getCaughtException() != null) { PArguments.setException(frame, threadState.getCaughtException()); diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/attributes/WriteAttributeToObjectNode.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/attributes/WriteAttributeToObjectNode.java index ba1c5b3cc1..5150498634 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/attributes/WriteAttributeToObjectNode.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/attributes/WriteAttributeToObjectNode.java @@ -94,7 +94,8 @@ public static WriteAttributeToObjectNode getUncached() { } static boolean isAttrWritable(PythonObject self) { - return (self.getShape().getFlags() & PythonObject.HAS_SLOTS_BUT_NO_DICT_FLAG) == 0; + // A value copy of a native float subclass instance has no dict (the native type has none) + return (self.getShape().getFlags() & PythonObject.HAS_SLOTS_BUT_NO_DICT_FLAG) == 0 && !(self instanceof com.oracle.graal.python.builtins.objects.floats.PNativeFloat); } static boolean writeToDynamicStorageNoTypeGuard(PythonObject obj, GetDictIfExistsNode getDict) { @@ -153,6 +154,7 @@ static boolean writeToDynamicStoragePythonClass(PythonClass klass, TruffleString private static boolean writeToDynamicStorageManagedClass(PythonManagedClass klass, TruffleString key, Object value, DynamicObject.PutNode putNode) { CompilerAsserts.partialEvaluationConstant(klass.getClass()); try { + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value); putNode.execute(klass, key, value); return true; } finally { diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/attributes/WriteAttributeToPythonObjectNode.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/attributes/WriteAttributeToPythonObjectNode.java index ba036bf121..2d1911079e 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/attributes/WriteAttributeToPythonObjectNode.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/attributes/WriteAttributeToPythonObjectNode.java @@ -86,6 +86,7 @@ public static WriteAttributeToPythonObjectNode getUncached() { static void write(PythonObject dynamicObject, TruffleString key, Object value, @Cached DynamicObject.PutNode putNode) { assert !PythonOptions.detailedAssertionsEnabled() || GetDictIfExistsNode.getDictUncached(dynamicObject) == null : "direct attribute write with a backing dictionary"; + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value); putNode.execute(dynamicObject, key, value); } } 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 dd3f55ab9a..f40f9ab1db 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 @@ -180,6 +180,10 @@ public abstract static class ClearListStorageNode extends PNodeWithContext { @Specialization static void doPList(PList list) { + if (list.getSequenceStorage() instanceof com.oracle.graal.python.runtime.sequence.storage.ComplexPtrSequenceStorage cp) { + // Drop the element references now instead of when the storage is collected + cp.releaseAllAndClear(); + } list.setSequenceStorage(EmptySequenceStorage.INSTANCE); } @@ -230,7 +234,12 @@ static PList fromList(PList list, @Bind Node inliningTarget, @Bind PythonLanguage language, @Cached SequenceStorageNodes.CopyNode copyNode) { - return PFactory.createList(language, copyNode.execute(inliningTarget, list.getSequenceStorage())); + SequenceStorage storage = list.getSequenceStorage(); + if (storage instanceof com.oracle.graal.python.runtime.sequence.storage.ComplexPtrSequenceStorage cp) { + // List copies keep the pointer representation (each element counted) + return PFactory.createList(language, cp.copyCounted()); + } + return PFactory.createList(language, copyNode.execute(inliningTarget, storage)); } @Specialization(guards = "!isNoValue(iterable)") 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 7334d9bf41..58e15941b4 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 @@ -2583,7 +2583,20 @@ static boolean isValidDescriptor(Shape cachedShape, IndexedSlotDescriptor descri return IsSubtypeNode.getUncached().execute(cachedShape.getDynamicType(), descriptor.getType()); } - static Object getIndexedSlotValue(Node inliningTarget, InlinedBranchProfile initProfile, PythonObject receiver, int index, int slotsCount) throws FastPathBailoutException { + static Object getIndexedSlotValue(Node inliningTarget, InlinedBranchProfile initProfile, PythonObject receiver, int index, int slotsCount, + com.oracle.graal.python.runtime.nativeaccess.NativeSlotNodes.ReadSlotNode readSlot) throws FastPathBailoutException { + /* + * The profile in readSlot cuts whichever of the two branches this site + * has not seen; otherwise the result is a phi of a (virtual) in-flight object from the + * native branch and a Java slot value, and escape analysis materializes the object. + */ + if (readSlot.profileNative(receiver instanceof com.oracle.graal.python.builtins.objects.object.PNativeLayoutObject n && n.getSlotsPtr() != 0)) { + Object v = readSlot.execute((com.oracle.graal.python.builtins.objects.object.PNativeLayoutObject) receiver, index); + if (v != null) { + return v; + } + throw FastPathBailoutException.INSTANCE; + } Object[] slots = GetOrCreateIndexedSlots.executeKnownCount(inliningTarget, initProfile, receiver, slotsCount); Object value = slots[index]; if (value != null) { @@ -2614,10 +2627,11 @@ static int doIndexedSlotDescriptorInt(TruffleString key, PythonObject receiver, @Cached("indexedSlotDescriptor.getIndex()") int index, @Cached("getTypeStableAssumption(cachedShape)") Assumption typeStableAssumption, @Cached("getIndexedSlotsCount(cachedShape)") int slotsCount, - @Exclusive @Cached InlinedBranchProfile initProfile) throws FastPathBailoutException, UnexpectedResultException, InvalidAssumptionException { + @Exclusive @Cached InlinedBranchProfile initProfile, + @Exclusive @Cached com.oracle.graal.python.runtime.nativeaccess.NativeSlotNodes.ReadSlotNode readSlot) throws FastPathBailoutException, UnexpectedResultException, InvalidAssumptionException { assert !shouldInternConstant(key) || isInterned(key); checkAssumption(typeStableAssumption); - Object value = getIndexedSlotValue(inliningTarget, initProfile, receiver, index, slotsCount); + Object value = getIndexedSlotValue(inliningTarget, initProfile, receiver, index, slotsCount, readSlot); if (value instanceof Integer integer) { return integer; } @@ -2637,10 +2651,11 @@ static Object doIndexedSlotDescriptor(TruffleString key, PythonObject receiver, @Cached("indexedSlotDescriptor.getIndex()") int index, @Cached("getTypeStableAssumption(cachedShape)") Assumption typeStableAssumption, @Cached("getIndexedSlotsCount(cachedShape)") int slotsCount, - @Exclusive @Cached InlinedBranchProfile initProfile) throws FastPathBailoutException, InvalidAssumptionException { + @Exclusive @Cached InlinedBranchProfile initProfile, + @Exclusive @Cached com.oracle.graal.python.runtime.nativeaccess.NativeSlotNodes.ReadSlotNode readSlot) throws FastPathBailoutException, InvalidAssumptionException { assert !shouldInternConstant(key) || isInterned(key); checkAssumption(typeStableAssumption); - return getIndexedSlotValue(inliningTarget, initProfile, receiver, index, slotsCount); + return getIndexedSlotValue(inliningTarget, initProfile, receiver, index, slotsCount, readSlot); } @Specialization(guards = { @@ -2758,10 +2773,51 @@ static void doInstanceValue(TruffleString key, Object value, PythonObject receiv @Cached("getTypeStableAssumption(cachedPythonClass)") Assumption typeStableAssumption, @Cached DynamicObject.PutNode putNode) { assert !shouldInternConstant(key) || isInterned(key); + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value); putNode.execute(receiver, key, value); } - @Specialization(replaces = "doInstanceValue") + static IndexedSlotDescriptor getIndexedSlotDescriptorForStore(Shape cachedShape, TruffleString key) { + Object type = cachedShape.getDynamicType(); + if (!(type instanceof PythonClass klass) || !hasObjectSetattro(klass.getTpSlots())) { + return null; + } + Object value = LookupAttributeInMRONode.lookupSlowPathNoSideEffects(klass, key); + return value instanceof IndexedSlotDescriptor descriptor ? descriptor : null; + } + + /** + * Slot store fast path (mirrors GetAttribute.doIndexedSlotDescriptor), so + * that a store into a slot is inlined with a constant index for both Java and native + * instances. + */ + @Specialization(guards = { + "indexedSlotDescriptor != null", "isValidDescriptor(cachedShape, indexedSlotDescriptor)", // + "cachedShape.check(receiver)"}, // + assumptions = "typeStableAssumption", // + limit = "3") + static void doIndexedSlotDescriptor(TruffleString key, Object value, PythonObject receiver, + @Bind Node inliningTarget, + @Cached("receiver.getShape()") Shape cachedShape, + @Cached("getIndexedSlotDescriptorForStore(cachedShape, key)") IndexedSlotDescriptor indexedSlotDescriptor, + @Cached("indexedSlotDescriptor.getIndex()") int index, + @Cached("getTypeStableAssumption(cachedShape)") Assumption typeStableAssumption, + @Cached("getIndexedSlotsCount(cachedShape)") int slotsCount, + @Exclusive @Cached InlinedBranchProfile initProfile, + @Exclusive @Cached com.oracle.graal.python.runtime.nativeaccess.NativeSlotNodes.WriteSlotNode writeSlot) { + assert !shouldInternConstant(key) || isInterned(key); + if (receiver instanceof com.oracle.graal.python.builtins.objects.object.PNativeLayoutObject n) { + if (n.getSlotsPtr() != 0) { + writeSlot.execute(n, index, value); + return; + } + } else { + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value); + } + GetOrCreateIndexedSlots.executeKnownCount(inliningTarget, initProfile, receiver, slotsCount)[index] = value; + } + + @Specialization(replaces = {"doInstanceValue", "doIndexedSlotDescriptor"}) public static void doIt(VirtualFrame frame, TruffleString key, Object value, @@ -2954,7 +3010,12 @@ public static final class MakeConstantObjectList { @Specialization public static PList perform(Object[] array, @Bind PBytecodeDSLRootNode rootNode) { - SequenceStorage storage = new ObjectSequenceStorage(PythonUtils.arrayCopyOf(array, array.length)); + // An all-None constant list is pointer-aware once an opt-in class exists + SequenceStorage storage = com.oracle.graal.python.runtime.nativeaccess.NativeInstance.NO_CLASSES.isValid() ? null + : com.oracle.graal.python.runtime.sequence.storage.InstPtrSequenceStorage.tryCreate(array, array.length, array.length); + if (storage == null) { + storage = new ObjectSequenceStorage(PythonUtils.arrayCopyOf(array, array.length)); + } return PFactory.createList(rootNode.getLanguage(), storage); } } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/bytecode_dsl/SequenceFromArrayNode.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/bytecode_dsl/SequenceFromArrayNode.java index e5ff5b774c..f9a80f07f7 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/bytecode_dsl/SequenceFromArrayNode.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/bytecode_dsl/SequenceFromArrayNode.java @@ -51,6 +51,7 @@ import com.oracle.graal.python.runtime.sequence.storage.BoolSequenceStorage; import com.oracle.graal.python.runtime.sequence.storage.DoubleSequenceStorage; import com.oracle.graal.python.runtime.sequence.storage.EmptySequenceStorage; +import com.oracle.graal.python.runtime.sequence.storage.InstPtrSequenceStorage; import com.oracle.graal.python.runtime.sequence.storage.IntSequenceStorage; import com.oracle.graal.python.runtime.sequence.storage.LongSequenceStorage; import com.oracle.graal.python.runtime.sequence.storage.ObjectSequenceStorage; @@ -126,6 +127,22 @@ SequenceStorage createSequenceStorage(Object[] objectElements, int length) { storage = new ObjectSequenceStorage(objectElements, length); break; } + case InstPtr: { + // Only list sites get this type + if (length == 0) { + storage = EmptySequenceStorage.INSTANCE; + break; + } + storage = InstPtrSequenceStorage.tryCreate(objectElements, length, getCapacityEstimate(length)); + if (storage == null) { + throw SLOW_PATH_EXCEPTION; + } + break; + } + case ComplexPtr: + // literals are never built as pointer storage; the type can come from + // reportUpdatedCapacity (append of a complex to a literal list) + throw SLOW_PATH_EXCEPTION; default: CompilerDirectives.transferToInterpreterAndInvalidate(); throw new RuntimeException("unexpected state"); @@ -143,7 +160,7 @@ SequenceStorage createSequenceStorage(Object[] objectElements, int length) { private SequenceStorage initialize(Object[] objectElements) { SequenceStorage storage; try { - storage = SequenceStorageFactory.createStorage(this, objectElements); + storage = createInitialStorage(objectElements); type = storage.getElementType(); } catch (Throwable t) { // we do not want to repeatedly deopt if a value execution @@ -184,12 +201,16 @@ private static boolean castBoolean(Object o) throws SlowPathException { protected abstract int getCapacityEstimate(int length); + protected SequenceStorage createInitialStorage(Object[] objectElements) { + return SequenceStorageFactory.createStorage(this, objectElements); + } + public abstract static class ListFromArrayNode extends SequenceFromArrayNode implements ListOrigin { private static final TruffleLogger LOGGER = PythonLanguage.getLogger(ListFromArrayNode.class); private static final ListFromArrayNode UNCACHED = new ListFromArrayNode() { @Override public PList execute(PythonLanguage language, Object[] elements) { - return PFactory.createList(language, SequenceStorageFactory.createStorage(this, elements)); + return PFactory.createList(language, SequenceStorageFactory.createListStorage(this, elements)); } }; @@ -201,6 +222,11 @@ public static ListFromArrayNode getUncached() { public abstract PList execute(PythonLanguage language, Object[] elements); + @Override + protected SequenceStorage createInitialStorage(Object[] objectElements) { + return SequenceStorageFactory.createListStorage(this, objectElements); + } + @Specialization PList doIt(PythonLanguage language, Object[] elements, @Bind Node inliningTarget, diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/frame/WriteGlobalNode.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/frame/WriteGlobalNode.java index 6ef428c580..d38330bc99 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/frame/WriteGlobalNode.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/frame/WriteGlobalNode.java @@ -72,11 +72,13 @@ public static WriteGlobalNode create() { public final void executeObject(VirtualFrame frame, TruffleString name, Object value) { CompilerAsserts.partialEvaluationConstant(name); + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value); executeObjectWithGlobals(frame, PArguments.getGlobals(frame), name, value); } public final void write(Frame frame, Object globals, TruffleString name, Object value) { CompilerAsserts.partialEvaluationConstant(name); + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value); executeObjectWithGlobals((VirtualFrame) frame, globals, name, value); } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/frame/WriteNameNode.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/frame/WriteNameNode.java index d4d6641546..24f1fc8d73 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/frame/WriteNameNode.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/frame/WriteNameNode.java @@ -60,6 +60,7 @@ public abstract class WriteNameNode extends PNodeWithContext implements AccessNa public final void execute(VirtualFrame frame, TruffleString attributeId, Object value) { CompilerAsserts.partialEvaluationConstant(attributeId); + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value); executeImpl(frame, attributeId, value); } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/object/IsNode.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/object/IsNode.java index 9bb8643a2f..9994b599c6 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/object/IsNode.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/object/IsNode.java @@ -256,6 +256,47 @@ public static boolean doPString(PString left, PString right) { return PGuards.isBuiltinPString(left) && PGuards.isBuiltinPString(right) && left.isMaterialized() && right.isMaterialized() && left.getMaterialized() == right.getMaterialized(); } + /** + * Two in-flight exact complex values are the same object if they were taken from + * the same native struct incarnation (same pointer and serial). {@code id()} is not changed. + */ + @Specialization + public static boolean doComplex(com.oracle.graal.python.builtins.objects.complex.PComplex left, com.oracle.graal.python.builtins.objects.complex.PComplex right) { + if (left == right) { + return true; + } + long p = left.getNativePtr(); + return p != 0 && left.isExact() && right.isExact() && p == right.getNativePtr() && left.getSerial() == right.getSerial(); + } + + /** + * Two in-flight references to native-layout instances are the same object if + * they refer to the same struct. + */ + @Specialization + public static boolean doNativeLayout(com.oracle.graal.python.builtins.objects.object.PNativeLayoutObject left, com.oracle.graal.python.builtins.objects.object.PNativeLayoutObject right) { + if (left == right) { + return true; + } + long p = left.getSlotsPtr(); + return p != 0 && p == right.getSlotsPtr(); + } + + /** + * Two in-flight value copies of a value-type native float subclass instance are the + * same object if they come from (or went to) the same struct incarnation (pointer and pool generation) + * and have the same class and bits. + */ + @Specialization + public static boolean doNativeFloat(com.oracle.graal.python.builtins.objects.floats.PNativeFloat left, com.oracle.graal.python.builtins.objects.floats.PNativeFloat right) { + if (left == right) { + return true; + } + long p = left.getStructHint(); + return p != 0 && p == right.getStructHint() && left.getStructGen() == right.getStructGen() && left.getPythonClass() == right.getPythonClass() && + Double.doubleToRawLongBits(left.getValue()) == Double.doubleToRawLongBits(right.getValue()); + } + // everything else @Fallback @InliningCutoff 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 36493007aa..852f4f1407 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 @@ -766,6 +766,9 @@ static PythonThreadState getThreadState(Node n) { @CompilationFinal private SecureRandom secureRandom; + /** Address of the shared native complex allocator state (0 = not yet created). */ + @CompilationFinal private long nativeComplexState; + @CompilationFinal private long nativeInstanceState; /** Address of the C API "Java ran" epoch word (see CApiEpoch), 0 until C asks for it. */ @CompilationFinal private long capiEpochAddress; private InitializationEntropySource initializationEntropySource; @@ -2582,6 +2585,35 @@ public void setCApiState(CApiState state) { cApiState = state; } + /** The native complex allocator state; created lazily at run time. */ + public long getNativeComplexState() { + long st = nativeComplexState; + if (CompilerDirectives.injectBranchProbability(CompilerDirectives.SLOWPATH_PROBABILITY, st == 0)) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + st = nativeComplexState = com.oracle.graal.python.runtime.nativeaccess.NativeComplex.createState(); + } + return st; + } + + /** Native instance allocator state; created lazily at run time. */ + public long getNativeInstanceState() { + long st = nativeInstanceState; + if (CompilerDirectives.injectBranchProbability(CompilerDirectives.SLOWPATH_PROBABILITY, st == 0)) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + st = nativeInstanceState = com.oracle.graal.python.runtime.nativeaccess.NativeInstance.createState(); + } + return st; + } + + public long peekNativeInstanceState() { + return nativeInstanceState; + } + + /** The state if it exists, else 0 (no creation). */ + public long peekNativeComplexState() { + return nativeComplexState; + } + /** Address of the C API "Java ran" epoch word; allocated on first use. */ public long getCApiEpochAddress() { long p = capiEpochAddress; diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeComplex.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeComplex.java new file mode 100644 index 0000000000..c6caf9905f --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeComplex.java @@ -0,0 +1,451 @@ +/* + * 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.runtime.nativeaccess; + +import static com.oracle.graal.python.runtime.nativeaccess.NativeMemory.UNSAFE; + +import com.oracle.graal.python.PythonLanguage; +import com.oracle.graal.python.builtins.PythonBuiltinClassType; +import com.oracle.graal.python.builtins.objects.complex.PComplex; +import com.oracle.truffle.api.CompilerDirectives; +import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; + +/** + * Exact {@code complex} objects as native, reference-counted CPython-layout structs. + * + *

+ * Struct layout (48 bytes): {@code ob_refcnt} @0, {@code ob_type} @8, {@code cval.real} @16, + * {@code cval.imag} @24, serial @32, in-FIFO flag @40. A free block has serial 0 and keeps its + * free-list link at @16. + * Serials are globally increasing and never 0, so a stale (pointer, serial) pair never matches a + * freed or reused block. + *

+ * + *

+ * All allocator state lives in one native block (the "state") so that C code can use the same free + * list without an upcall (see {@code complexobject.c}). Arenas are allocated with the system allocator + * once and are never returned, so reading the serial of any block that was ever handed out is safe. + * Single-threaded: callers hold the GIL. + *

+ * + *

+ * Reference counts count list slots and C references only; an in-flight Java {@link PComplex} is a + * value copy plus an unowned (pointer, serial) pair. A struct whose count drops to zero enters a FIFO + * of {@link #FIFO_SIZE} (pointer, serial) entries; on eviction it is freed if its count is still zero + * and its serial still matches. + *

+ */ +public final class NativeComplex { + + /** Counters (measurement only): constant false unless -Dgraalpy.complexCounters=true. */ + public static final boolean COUNTERS = Boolean.getBoolean("graalpy.complexCounters"); + + public static final int BLOCK_SIZE = 48; + public static final long OFF_REFCNT = 0; + public static final long OFF_TYPE = 8; + public static final long OFF_REAL = 16; + public static final long OFF_IMAG = 24; + public static final long OFF_SERIAL = 32; + public static final long OFF_INFIFO = 40; + private static final long OFF_LINK = 16; + + // state layout (must match GraalPyComplexAllocState in complexobject.c) + public static final long S_FREE = 0; + public static final long S_BUMP = 8; + public static final long S_END = 16; + public static final long S_SERIAL = 24; + public static final long S_TYPE = 32; + public static final long S_FIFO_POS = 40; + public static final long S_FLAGS = 48; + public static final long S_ARENAS = 56; + public static final long S_COUNTERS = 64; // N_COUNTERS longs, updated by C code + public static final int FIFO_SIZE = 64; // power of two + public static final long S_FIFO = S_COUNTERS + 8 * 16; + // borrowed-reference stack: counted references held for the duration of a C call + public static final long S_BSTACK = S_FIFO + 16L * FIFO_SIZE; + public static final long S_BTOP = S_BSTACK + 8; + public static final long S_BCAP = S_BTOP + 8; + public static final long S_BDEPTH = S_BCAP + 8; // downcall nesting depth + // Allocator region of exact int structs (see NativeLong) + public static final long S_LONG = S_BDEPTH + 8; + public static final long S_SMALL = S_LONG + NativeLong.REGION_SIZE; // NativeSmall region + public static final long STATE_SIZE = S_SMALL + NativeSmall.REGION_SIZE; + + private static final long ARENA_SIZE = 64 * 1024; + private static final long ARENA_HEADER = 16; + + // counter indices + public static final int C_ALLOC = 0; + public static final int C_FREE = 1; + public static final int C_INCREF = 2; + public static final int C_DECREF = 3; + public static final int C_STALE = 4; + public static final int C_EVICT_FREED = 5; + public static final int C_EVICT_KEPT = 6; + public static final int C_C_TO_JAVA = 7; + public static final int C_JAVA_TO_C = 8; + public static final int C_REUSE = 9; // store of an in-flight complex whose struct was still valid + public static final int N_COUNTERS = 10; + public static final String[] COUNTER_NAMES = {"native_alloc", "native_free", "incref", "decref", "stale_realloc", "fifo_evict_freed", "fifo_evict_kept", + "c_to_java", "java_to_c", "reuse"}; + + private static final long[] JAVA_COUNTS = new long[N_COUNTERS]; + + private NativeComplex() { + } + + public static void count(int idx) { + if (COUNTERS) { + JAVA_COUNTS[idx]++; + } + } + + @TruffleBoundary + public static long createState() { + long st = UNSAFE.allocateMemory(STATE_SIZE); + UNSAFE.setMemory(st, STATE_SIZE, (byte) 0); + UNSAFE.putLong(st + S_FLAGS, COUNTERS ? 1 : 0); + return st; + } + + @TruffleBoundary + public static long[] snapshot(long st, boolean reset) { + long[] res = new long[N_COUNTERS]; + for (int i = 0; i < N_COUNTERS; i++) { + res[i] = JAVA_COUNTS[i] + (st != 0 ? UNSAFE.getLong(st + S_COUNTERS + 8L * i) : 0); + if (reset) { + JAVA_COUNTS[i] = 0; + if (st != 0) { + UNSAFE.putLong(st + S_COUNTERS + 8L * i, 0); + } + } + } + return res; + } + + /** Number of blocks currently allocated (carved minus free-list length); debug only. */ + @TruffleBoundary + public static long liveBlocks(long st) { + long carved = 0; + long arena = UNSAFE.getLong(st + S_ARENAS); + boolean first = true; + while (arena != 0) { + long end = first ? UNSAFE.getLong(st + S_BUMP) : arena + ARENA_SIZE; + carved += (end - (arena + ARENA_HEADER)) / BLOCK_SIZE; + first = false; + arena = UNSAFE.getLong(arena); + } + long free = 0; + for (long p = UNSAFE.getLong(st + S_FREE); p != 0; p = UNSAFE.getLong(p + OFF_LINK)) { + free++; + } + return carved - free; + } + + // ---------------------------------------------------------------- allocation + + public static long alloc(long st, double real, double imag) { + long p = UNSAFE.getLong(st + S_FREE); + if (p != 0) { + UNSAFE.putLong(st + S_FREE, UNSAFE.getLong(p + OFF_LINK)); + } else { + p = UNSAFE.getLong(st + S_BUMP); + if (CompilerDirectives.injectBranchProbability(CompilerDirectives.SLOWPATH_PROBABILITY, p + BLOCK_SIZE > UNSAFE.getLong(st + S_END))) { + p = newArena(st); + } else { + UNSAFE.putLong(st + S_BUMP, p + BLOCK_SIZE); + } + } + long serial = UNSAFE.getLong(st + S_SERIAL) + 1; + UNSAFE.putLong(st + S_SERIAL, serial); + UNSAFE.putLong(p + OFF_REFCNT, 0); + UNSAFE.putLong(p + OFF_TYPE, UNSAFE.getLong(st + S_TYPE)); + UNSAFE.putDouble(p + OFF_REAL, real); + UNSAFE.putDouble(p + OFF_IMAG, imag); + UNSAFE.putLong(p + OFF_SERIAL, serial); + UNSAFE.putLong(p + OFF_INFIFO, 0); + count(C_ALLOC); + return p; + } + + @TruffleBoundary + private static long newArena(long st) { + long arena = UNSAFE.allocateMemory(ARENA_SIZE); + UNSAFE.putLong(arena, UNSAFE.getLong(st + S_ARENAS)); + UNSAFE.putLong(st + S_ARENAS, arena); + long p = arena + ARENA_HEADER; + UNSAFE.putLong(st + S_BUMP, p + BLOCK_SIZE); + UNSAFE.putLong(st + S_END, arena + ARENA_SIZE); + return p; + } + + private static void free(long st, long p) { + UNSAFE.putLong(p + OFF_SERIAL, 0); + UNSAFE.putLong(p + OFF_LINK, UNSAFE.getLong(st + S_FREE)); + UNSAFE.putLong(st + S_FREE, p); + count(C_FREE); + } + + // ---------------------------------------------------------------- reference counting + + public static void incref(long p) { + UNSAFE.putLong(p + OFF_REFCNT, UNSAFE.getLong(p + OFF_REFCNT) + 1); + count(C_INCREF); + } + + public static void decref(long st, long p) { + long rc = UNSAFE.getLong(p + OFF_REFCNT) - 1; + UNSAFE.putLong(p + OFF_REFCNT, rc); + count(C_DECREF); + if (rc == 0) { + enqueue(st, p); + } + } + + /** + * Puts a zero-count struct into the deferred-free FIFO (unless it is already queued), evicting + * the oldest entry; the evicted struct is freed if its count is still zero and its serial still + * matches. + */ + public static void enqueue(long st, long p) { + if (UNSAFE.getLong(p + OFF_INFIFO) != 0) { + return; + } + UNSAFE.putLong(p + OFF_INFIFO, 1); + long pos = UNSAFE.getLong(st + S_FIFO_POS); + long entry = st + S_FIFO + 16L * (pos & (FIFO_SIZE - 1)); + long old = UNSAFE.getLong(entry); + if (old != 0) { + if (UNSAFE.getLong(old + OFF_SERIAL) == UNSAFE.getLong(entry + 8)) { + // same incarnation: it is leaving the FIFO + UNSAFE.putLong(old + OFF_INFIFO, 0); + if (UNSAFE.getLong(old + OFF_REFCNT) == 0) { + free(st, old); + count(C_EVICT_FREED); + } else { + count(C_EVICT_KEPT); + } + } else { + count(C_EVICT_KEPT); + } + } + UNSAFE.putLong(entry, p); + UNSAFE.putLong(entry + 8, UNSAFE.getLong(p + OFF_SERIAL)); + UNSAFE.putLong(st + S_FIFO_POS, pos + 1); + } + + // ---------------------------------------------------------------- Java <-> struct + + public static boolean isValid(long p, long serial) { + return p != 0 && UNSAFE.getLong(p + OFF_SERIAL) == serial; + } + + /** + * Returns a valid struct for the in-flight complex (allocating one if it has none or a stale + * one) and records it in the Java object. Does not change the reference count. The argument is + * only read and written field-wise, so a virtual {@link PComplex} stays virtual. + */ + public static long materialize(long st, PComplex c) { + long p = c.getNativePtr(); + if (p != 0) { + if (UNSAFE.getLong(p + OFF_SERIAL) == c.getSerial()) { + count(C_REUSE); + return p; + } + count(C_STALE); + } + p = alloc(st, c.getReal(), c.getImag()); + c.setNative(p, UNSAFE.getLong(p + OFF_SERIAL)); + return p; + } + + /** Builds an in-flight complex from a struct (no reference count change). */ + public static PComplex load(PythonLanguage language, long p) { + return new PComplex(PythonBuiltinClassType.PComplex, PythonBuiltinClassType.PComplex.getInstanceShape(language), + UNSAFE.getDouble(p + OFF_REAL), UNSAFE.getDouble(p + OFF_IMAG), p, UNSAFE.getLong(p + OFF_SERIAL)); + } + + public static double readReal(long p) { + return UNSAFE.getDouble(p + OFF_REAL); + } + + public static double readImag(long p) { + return UNSAFE.getDouble(p + OFF_IMAG); + } + + public static long readSerial(long p) { + return UNSAFE.getLong(p + OFF_SERIAL); + } + + public static long readRefcnt(long p) { + return UNSAFE.getLong(p + OFF_REFCNT); + } + + public static void writeType(long p, long type) { + UNSAFE.putLong(p + OFF_TYPE, type); + } + + public static long readType(long p) { + return UNSAFE.getLong(p + OFF_TYPE); + } + + // ---------------------------------------------------------------- C API + + /** + * Struct pointer for an exact complex handed to C. With {@code newRef} the caller (C) owns one + * count; otherwise the count is taken for the duration of the current C call (borrowed stack, + * released by {@link #borrowRelease} when the invoking downcall returns), so C can incref/decref + * the argument without it reaching zero. + */ + public static long toNative(long st, PComplex c, boolean newRef) { + long p = materialize(st, c); + UNSAFE.putLong(p + OFF_TYPE, UNSAFE.getLong(st + S_TYPE)); + incref(p); + if (!newRef) { + borrowPush(st, p); + } + count(C_JAVA_TO_C); + return p; + } + + /** Builds an in-flight complex from a struct coming from C; with {@code transfer} drops C's count. */ + public static PComplex fromNative(PythonLanguage language, long st, long p, boolean transfer) { + PComplex c = load(language, p); + if (transfer) { + decref(st, p); + } + count(C_C_TO_JAVA); + return c; + } + + /** True if {@code p} (a non-handle PyObject pointer) is an exact native complex struct. */ + public static boolean isNativeComplex(long st, long p) { + long type = UNSAFE.getLong(st + S_TYPE); + return type != 0 && UNSAFE.getLong(p + OFF_TYPE) == type; + } + + public static long getComplexType(long st) { + return UNSAFE.getLong(st + S_TYPE); + } + + static void borrowPush(long st, long p) { + long top = UNSAFE.getLong(st + S_BTOP); + if (CompilerDirectives.injectBranchProbability(CompilerDirectives.SLOWPATH_PROBABILITY, top >= UNSAFE.getLong(st + S_BCAP))) { + growBorrowStack(st); + } + UNSAFE.putLong(UNSAFE.getLong(st + S_BSTACK) + 8 * top, p); + UNSAFE.putLong(st + S_BTOP, top + 1); + } + + @TruffleBoundary + private static void growBorrowStack(long st) { + long cap = UNSAFE.getLong(st + S_BCAP); + long newCap = cap == 0 ? 256 : cap * 2; + long old = UNSAFE.getLong(st + S_BSTACK); + long arr = UNSAFE.allocateMemory(8 * newCap); + if (old != 0) { + UNSAFE.copyMemory(old, arr, 8 * cap); + UNSAFE.freeMemory(old); + } + UNSAFE.putLong(st + S_BSTACK, arr); + UNSAFE.putLong(st + S_BCAP, newCap); + } + + /** Called by every generated downcall invoker before the native call. */ + public static void enterDowncall() { + long st = com.oracle.graal.python.runtime.PythonContext.get(null).peekNativeComplexState(); + if (st != 0) { + UNSAFE.putLong(st + S_BDEPTH, UNSAFE.getLong(st + S_BDEPTH) + 1); + } + com.oracle.graal.python.builtins.objects.cext.capi.CApiEpoch.javaRan(); + } + + /** + * Called by every generated downcall invoker after the native call. Borrowed counts (arguments + * converted before the call and borrowed results of upcalls made during it) are dropped when the + * outermost downcall returns. + */ + public static void exitDowncall() { + long st = com.oracle.graal.python.runtime.PythonContext.get(null).peekNativeComplexState(); + if (st != 0) { + long depth = UNSAFE.getLong(st + S_BDEPTH); + if (depth > 0) { + depth--; + UNSAFE.putLong(st + S_BDEPTH, depth); + } + if (depth == 0) { + borrowRelease(st, 0); + } + } + } + + /** Depth of the borrowed stack at entry of a downcall (0 if there is no state). */ + public static long borrowMark(long st) { + return st == 0 ? 0 : UNSAFE.getLong(st + S_BTOP); + } + + /** Drops the borrowed counts taken since {@code mark}. */ + public static void borrowRelease(long st, long mark) { + if (st == 0) { + return; + } + long top = UNSAFE.getLong(st + S_BTOP); + if (top > mark) { + long arr = UNSAFE.getLong(st + S_BSTACK); + long longType = NativeLong.getLongType(st); + long complexType = UNSAFE.getLong(st + S_TYPE); + while (top > mark) { + top--; + long p = UNSAFE.getLong(arr + 8 * top); + long type = UNSAFE.getLong(p + OFF_TYPE); + if (type == longType) { + NativeLong.decref(st, p); + } else if (type == complexType) { + decref(st, p); + } else { + // Float struct (exact or value-type subclass) + NativeSmall.decref(st, p); + } + } + UNSAFE.putLong(st + S_BTOP, top); + } + } +} diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeInstance.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeInstance.java new file mode 100644 index 0000000000..9b18f60aca --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeInstance.java @@ -0,0 +1,677 @@ +/* + * 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.runtime.nativeaccess; + +import static com.oracle.graal.python.runtime.nativeaccess.NativeMemory.UNSAFE; +import static com.oracle.graal.python.util.PythonUtils.tsLiteral; + +import java.util.ArrayList; + +import com.oracle.graal.python.builtins.PythonBuiltinClassType; +import com.oracle.graal.python.builtins.objects.PNone; +import com.oracle.graal.python.builtins.objects.complex.PComplex; +import com.oracle.graal.python.builtins.objects.object.PNativeLayoutObject; +import com.oracle.graal.python.builtins.objects.type.PythonBuiltinClass; +import com.oracle.graal.python.builtins.objects.type.PythonClass; +import com.oracle.graal.python.runtime.AsyncHandler; +import com.oracle.graal.python.runtime.PythonContext; +import com.oracle.truffle.api.Assumption; +import com.oracle.truffle.api.CompilerDirectives; +import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; +import com.oracle.truffle.api.Truffle; +import com.oracle.truffle.api.strings.TruffleString; + +/** + * Instances of opt-in {@code __slots__} classes as native, reference-counted structs. + * + *

+ * Struct: refcount @0 (long), meta @8 (class id in the low 32 bits, "recorded" flag in bit 32, debug + * serial in bits 33..63), then one 8-byte word per slot @16. A free block keeps its free-list link + * at @0 and has meta 0 (class id 0 is never used), so the debug check sees it as freed. + *

+ * + *

+ * Words (low two bits are the tag): {@code 00} counted pointer to a native instance (0 = slot not + * set), {@code 01} tagged int ({@code value << 2}, 62 bits), {@code 10} counted pointer to a + * native complex ({@code ptr | 2}), {@code 11} special: bit 2 clear = constant ({@code None} 3, + * {@code False} 11, {@code True} 19), bit 2 set = handle ({@code index << 3 | 7}) into a Java table + * that owns one strong reference per handle word. + *

+ * + *

+ * Counts: only heap references (slot words and pins). A struct whose count reaches zero is recorded + * (once, flag in meta) in a native array; {@link #quiesce} frees recorded structs whose count is still + * zero, recursively. Nothing is freed anywhere else. Single-threaded: callers hold the GIL. + *

+ */ +public final class NativeInstance { + + public static final boolean COUNTERS = Boolean.getBoolean("graalpy.slotsCounters"); + public static final boolean DEBUG = Boolean.getBoolean("graalpy.nativeSlotsDebug"); + + public static final int MAX_SLOTS = 64; + + public static final long OFF_REFCNT = 0; + public static final long OFF_META = 8; + public static final long HEADER = 16; + private static final long OFF_LINK = 0; + static final long META_RECORDED = 1L << 32; + static final int SERIAL_SHIFT = 33; + + public static final long W_EMPTY = 0; + public static final long W_NONE = 3; + public static final long W_FALSE = 11; + public static final long W_TRUE = 19; + static final long TAGGED_MIN = -(1L << 61); + static final long TAGGED_MAX = (1L << 61) - 1; + + // state layout + static final long S_BUMP = 0; + static final long S_END = 8; + static final long S_SERIAL = 16; + static final long S_REC = 24; + static final long S_RECLEN = 32; + static final long S_RECCAP = 40; + static final long S_FREE = 48; // MAX_SLOTS + 1 free-list heads, by slot count + static final long STATE_SIZE = S_FREE + 8L * (MAX_SLOTS + 1); + private static final long ARENA_SIZE = 1024 * 1024; + + // counters + public static final int C_ALLOC = 0; + public static final int C_FREE = 1; + public static final int C_INCREF = 2; + public static final int C_DECREF = 3; + public static final int C_PIN = 4; + public static final int C_UNPIN = 5; + public static final int C_HANDLE_STORE = 6; + public static final int C_HANDLE_LOAD = 7; + public static final int C_INFLIGHT = 8; // in-flight Java objects created from slot loads + public static final int C_RECORD = 9; // structs entering the zero-count record + public static final int C_MAT_INLINE = 10; // made native by the inlined (one class) path + public static final int C_MAT_SLOW = 11; // made native by the boundary (worklist) path + public static final int C_COMPLEX_STORE = 12; + public static final int C_QUIESCE = 13; + public static final int C_LIST_NEW = 14; // pointer-aware list storages created + public static final int C_LIST_STORE = 15; // words stored into pointer-aware list storages + public static final int C_LIST_INFLIGHT = 16; // in-flight Java objects created from list loads + public static final int C_LIST_GENERALIZE = 17; // pointer-aware list storages generalized to object storage + public static final int C_LIST_CLEANER = 18; // pointer-aware list storages released by the cleaner + public static final int C_PIN_DICT = 19; // pins at dict key/value stores (also counted in pin) + public static final int C_PIN_CELL = 20; // pins at cell stores (also counted in pin) + public static final int C_PIN_ID = 21; // pins for id()/default hash (also counted in pin) + public static final int N_COUNTERS = 22; + public static final String[] COUNTER_NAMES = {"inst_alloc", "inst_free", "incref", "decref", "pin", "unpin", "handle_store", "handle_load", "inflight_from_load", + "record", "make_native_inline", "make_native_slow", "complex_store", "quiesce", "list_new", "list_store", "inflight_from_list", + "list_generalize", "list_cleaner", "pin_dict", "pin_cell", "pin_id"}; + private static final long[] COUNTS = new long[N_COUNTERS]; + + /** Valid while no opt-in class exists: all pin checks fold away. */ + public static final Assumption NO_CLASSES = Truffle.getRuntime().createAssumption("no native-layout classes"); + + private static PythonClass[] classes = new PythonClass[16]; + private static int[] slotCounts = new int[16]; + private static int nClasses = 0; // ids are 1..nClasses + + private static final TruffleString T___NATIVE_LAYOUT__ = tsLiteral("__native_layout__"); + + private NativeInstance() { + } + + public static void count(int idx) { + if (COUNTERS) { + COUNTS[idx]++; + } + } + + @TruffleBoundary + public static long[] snapshot(boolean reset) { + long[] res = COUNTS.clone(); + if (reset) { + java.util.Arrays.fill(COUNTS, 0); + } + return res; + } + + // ---------------------------------------------------------------- classes + + /** + * Called by type creation after the slot descriptors exist. Opts the class in if it declares + * {@code __native_layout__ = True} in its own namespace, has {@code object} as its only base, + * non-empty {@code __slots__} and neither {@code __dict__} nor {@code __weakref__}. + */ + @TruffleBoundary + public static void maybeRegister(PythonClass cls, Object base, int nBases, int slotCount, boolean hasOwnSlots, boolean addDict, boolean addWeak) { + if (!hasOwnSlots || addDict || addWeak || nBases != 1 || slotCount <= 0 || slotCount > MAX_SLOTS) { + return; + } + if (!(base instanceof PythonBuiltinClass pbc && pbc.getType() == PythonBuiltinClassType.PythonObject)) { + return; + } + Object marker = cls.getAttribute(T___NATIVE_LAYOUT__); + if (marker != Boolean.TRUE) { + return; + } + int id = ++nClasses; + if (id >= classes.length) { + classes = java.util.Arrays.copyOf(classes, classes.length * 2); + slotCounts = java.util.Arrays.copyOf(slotCounts, slotCounts.length * 2); + } + classes[id] = cls; + slotCounts[id] = slotCount; + cls.setNativeLayoutId(id); + NO_CLASSES.invalidate(); + } + + public static PythonClass classOf(int id) { + return classes[id]; + } + + public static int slotCountOf(int id) { + return slotCounts[id]; + } + + // ---------------------------------------------------------------- state and allocation + + @TruffleBoundary + public static long createState() { + long st = UNSAFE.allocateMemory(STATE_SIZE); + UNSAFE.setMemory(st, STATE_SIZE, (byte) 0); + return st; + } + + public static long state(PythonContext ctx) { + return ctx.getNativeInstanceState(); + } + + public static long alloc(long st, int classId, int n) { + long head = st + S_FREE + 8L * n; + long p = UNSAFE.getLong(head); + if (p != 0) { + UNSAFE.putLong(head, UNSAFE.getLong(p + OFF_LINK)); + } else { + p = UNSAFE.getLong(st + S_BUMP); + long size = HEADER + 8L * n; + if (CompilerDirectives.injectBranchProbability(CompilerDirectives.SLOWPATH_PROBABILITY, p + size > UNSAFE.getLong(st + S_END))) { + p = newArena(st, size); + } else { + UNSAFE.putLong(st + S_BUMP, p + size); + } + } + UNSAFE.putLong(p + OFF_REFCNT, 0); + long meta = classId; + if (DEBUG) { + long serial = UNSAFE.getLong(st + S_SERIAL) + 1; + if (serial >= (1L << (64 - SERIAL_SHIFT))) { + serial = 1; + } + UNSAFE.putLong(st + S_SERIAL, serial); + meta |= serial << SERIAL_SHIFT; + } + UNSAFE.putLong(p + OFF_META, meta); + count(C_ALLOC); + return p; + } + + public static long serialOf(long p) { + return DEBUG ? UNSAFE.getLong(p + OFF_META) >>> SERIAL_SHIFT : 0; + } + + @TruffleBoundary + private static long newArena(long st, long size) { + long arena = UNSAFE.allocateMemory(ARENA_SIZE); + long p = arena; + UNSAFE.putLong(st + S_BUMP, p + size); + UNSAFE.putLong(st + S_END, arena + ARENA_SIZE); + return p; + } + + public static void incref(long p) { + UNSAFE.putLong(p + OFF_REFCNT, UNSAFE.getLong(p + OFF_REFCNT) + 1); + count(C_INCREF); + } + + public static void decref(long st, long p) { + long rc = UNSAFE.getLong(p + OFF_REFCNT) - 1; + UNSAFE.putLong(p + OFF_REFCNT, rc); + count(C_DECREF); + if (rc == 0) { + record(st, p); + } + } + + /** Puts a zero-count struct into the record (once; the flag is cleared when quiesce looks at it). */ + public static void record(long st, long p) { + long meta = UNSAFE.getLong(p + OFF_META); + if ((meta & META_RECORDED) == 0) { + UNSAFE.putLong(p + OFF_META, meta | META_RECORDED); + long len = UNSAFE.getLong(st + S_RECLEN); + if (CompilerDirectives.injectBranchProbability(CompilerDirectives.SLOWPATH_PROBABILITY, len >= UNSAFE.getLong(st + S_RECCAP))) { + growRecord(st); + } + UNSAFE.putLong(UNSAFE.getLong(st + S_REC) + 8 * len, p); + UNSAFE.putLong(st + S_RECLEN, len + 1); + count(C_RECORD); + } + } + + @TruffleBoundary + private static void growRecord(long st) { + long cap = UNSAFE.getLong(st + S_RECCAP); + long newCap = cap == 0 ? 4096 : cap * 2; + long old = UNSAFE.getLong(st + S_REC); + long arr = UNSAFE.allocateMemory(8 * newCap); + if (old != 0) { + UNSAFE.copyMemory(old, arr, 8 * cap); + UNSAFE.freeMemory(old); + } + UNSAFE.putLong(st + S_REC, arr); + UNSAFE.putLong(st + S_RECCAP, newCap); + } + + /** + * Frees every recorded struct whose count is still zero; freeing drops the references held by + * its slots, which may record more structs (processed in the same loop, no recursion). + */ + @TruffleBoundary + public static long quiesce(PythonContext ctx) { + long st = ctx.peekNativeInstanceState(); + if (st == 0) { + return 0; + } + count(C_QUIESCE); + long freed = 0; + long len; + while ((len = UNSAFE.getLong(st + S_RECLEN)) > 0) { + len--; + UNSAFE.putLong(st + S_RECLEN, len); + long p = UNSAFE.getLong(UNSAFE.getLong(st + S_REC) + 8 * len); + long meta = UNSAFE.getLong(p + OFF_META); + UNSAFE.putLong(p + OFF_META, meta & ~META_RECORDED); + if (UNSAFE.getLong(p + OFF_REFCNT) == 0) { + freeStruct(ctx, st, p); + freed++; + } + } + return freed; + } + + private static void freeStruct(PythonContext ctx, long st, long p) { + int cid = (int) UNSAFE.getLong(p + OFF_META); + if (cid <= 0 || cid > nClasses) { + throw CompilerDirectives.shouldNotReachHere("native instance: freeing a struct with bad class id " + cid + " at 0x" + Long.toHexString(p)); + } + int n = slotCounts[cid]; + for (int i = 0; i < n; i++) { + long a = p + HEADER + 8L * i; + long w = UNSAFE.getLong(a); + UNSAFE.putLong(a, DEBUG ? 0xDEADDEADDEADDEADL : 0); + releaseGeneric(ctx, st, w); + } + UNSAFE.putLong(p + OFF_META, 0); + long head = st + S_FREE + 8L * n; + UNSAFE.putLong(p + OFF_LINK, UNSAFE.getLong(head)); + UNSAFE.putLong(head, p); + count(C_FREE); + } + + // ---------------------------------------------------------------- debug checks + + /** Debug mode: the Java object must refer to a live struct of the incarnation it was made for. */ + public static void checkLive(PNativeLayoutObject o) { + if (DEBUG) { + long p = o.getSlotsPtr(); + long meta = UNSAFE.getLong(p + OFF_META); + if ((int) meta == 0 || (meta >>> SERIAL_SHIFT) != o.getSerial()) { + useAfterFree(p, meta, o.getSerial()); + } + } + } + + /** Debug mode: a pointer found in a slot must point to a live struct. */ + public static void checkStruct(long p) { + if (DEBUG) { + long meta = UNSAFE.getLong(p + OFF_META); + if ((int) meta == 0) { + useAfterFree(p, meta, -1); + } + } + } + + @TruffleBoundary + private static void useAfterFree(long p, long meta, long expectedSerial) { + String msg = "native instance: use after free at 0x" + Long.toHexString(p) + " (meta 0x" + Long.toHexString(meta) + ", expected serial " + expectedSerial + ")"; + System.err.println(msg); + System.err.flush(); + throw new IllegalStateException(msg); + } + + // ---------------------------------------------------------------- words + + public static boolean fitsTagged(long v) { + return v >= TAGGED_MIN && v <= TAGGED_MAX; + } + + public static long tagInt(long v) { + return (v << 2) | 1; + } + + public static boolean isHandleWord(long w) { + return (w & 7) == 7; + } + + /** Generic value -> word conversion (counted). Used by uncached paths and the slow path. */ + @TruffleBoundary + public static long toWordGeneric(PythonContext ctx, long st, Object v) { + if (v == null) { + return W_EMPTY; + } else if (v instanceof Integer i) { + return tagInt(i); + } else if (v instanceof Long l && fitsTagged(l)) { + return tagInt(l); + } else if (v instanceof Boolean b) { + return b ? W_TRUE : W_FALSE; + } else if (v == PNone.NONE) { + return W_NONE; + } else if (v instanceof PNativeLayoutObject o) { + long p = o.getSlotsPtr(); + if (p == 0) { + p = makeNativeSlow(ctx, st, o); + } else { + checkLive(o); + } + incref(p); + return p; + } else if (v instanceof PComplex c && c.isExact()) { + return complexWord(ctx, c); + } + return handleStore(v); + } + + public static long complexWord(PythonContext ctx, PComplex c) { + long cst = ctx.getNativeComplexState(); + long p = NativeComplex.materialize(cst, c); + NativeComplex.incref(p); + count(C_COMPLEX_STORE); + return p | 2; + } + + /** Generic word -> value; {@code null} for an empty slot. */ + @TruffleBoundary + public static Object fromWordGeneric(PythonContext ctx, long w) { + int tag = (int) w & 3; + if (tag == 1) { + long v = w >> 2; + return v == (int) v ? (Object) (int) v : (Object) v; + } else if (tag == 0) { + if (w == 0) { + return null; + } + return loadInstanceGeneric(w); + } else if (tag == 2) { + return NativeComplex.load(ctx.getLanguage(), w & ~3L); + } else if ((w & 4) == 0) { + return constant(w); + } else { + return handleLoad(w); + } + } + + public static Object constant(long w) { + if (w == W_NONE) { + return PNone.NONE; + } else if (w == W_TRUE) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } + + public static PNativeLayoutObject loadInstanceGeneric(long p) { + count(C_INFLIGHT); + return loadInstanceUncounted(p); + } + + /** New in-flight object around {@code p} (no count change, no counter). */ + public static PNativeLayoutObject loadInstanceUncounted(long p) { + checkStruct(p); + int cid = (int) UNSAFE.getLong(p + OFF_META); + PythonClass cls = classes[cid]; + return new PNativeLayoutObject(cls, cls.getInstanceShape(), p, serialOf(p)); + } + + /** Drops the reference a word holds (generic). */ + public static void releaseGeneric(PythonContext ctx, long st, long w) { + int tag = (int) w & 3; + if (tag == 0) { + if (w != 0) { + checkStruct(w); + decref(st, w); + } + } else if (tag == 2) { + NativeComplex.decref(ctx.getNativeComplexState(), w & ~3L); + } else if (tag == 3 && (w & 4) != 0) { + handleFree(w); + } + } + + @TruffleBoundary + public static void releaseSlow(long w) { + releaseGeneric(PythonContext.get(null), state(PythonContext.get(null)), w); + } + + // ---------------------------------------------------------------- handle table (declared shim) + + private static Object[] handles = new Object[1024]; + private static int[] handleNext = new int[1024]; + private static int handleFree = -1; + private static int handleTop = 0; + + @TruffleBoundary + public static long handleStore(Object v) { + int idx; + if (handleFree >= 0) { + idx = handleFree; + handleFree = handleNext[idx]; + } else { + if (handleTop == handles.length) { + handles = java.util.Arrays.copyOf(handles, handles.length * 2); + handleNext = java.util.Arrays.copyOf(handleNext, handleNext.length * 2); + } + idx = handleTop++; + } + handles[idx] = v; + count(C_HANDLE_STORE); + return ((long) idx << 3) | 7; + } + + public static Object handleLoad(long w) { + count(C_HANDLE_LOAD); + return handles[(int) (w >>> 3)]; + } + + @TruffleBoundary + public static void handleFree(long w) { + int idx = (int) (w >>> 3); + handles[idx] = null; + handleNext[idx] = handleFree; + handleFree = idx; + } + + // ---------------------------------------------------------------- making native + + /** + * Makes {@code o} and every not-yet-native opt-in object reachable from its Java slots native. + * Two phases with an explicit worklist (no recursion): allocate structs and set the pointers, + * then convert the Java slots into words. New structs start with count 0; the caller's store + * adds the first count. + */ + @TruffleBoundary + public static long makeNativeSlow(PythonContext ctx, long st, PNativeLayoutObject o) { + if (o.getSlotsPtr() != 0) { + return o.getSlotsPtr(); + } + ArrayList made = new ArrayList<>(); + allocFor(st, o); + made.add(o); + for (int k = 0; k < made.size(); k++) { + Object[] js = made.get(k).getIndexedSlots(); + if (js != null) { + for (Object v : js) { + if (v instanceof PNativeLayoutObject y && y.getSlotsPtr() == 0) { + allocFor(st, y); + made.add(y); + } + } + } + } + for (PNativeLayoutObject x : made) { + int cid = ((PythonClass) x.getPythonClass()).getNativeLayoutId(); + int n = slotCounts[cid]; + long p = x.getSlotsPtr(); + Object[] js = x.getIndexedSlots(); + for (int i = 0; i < n; i++) { + Object v = js == null || i >= js.length ? null : js[i]; + UNSAFE.putLong(p + HEADER + 8L * i, toWordGeneric(ctx, st, v)); + } + x.setIndexedSlots(null); + count(C_MAT_SLOW); + } + return o.getSlotsPtr(); + } + + private static void allocFor(long st, PNativeLayoutObject o) { + int cid = ((PythonClass) o.getPythonClass()).getNativeLayoutId(); + long p = alloc(st, cid, slotCounts[cid]); + o.setSlotsPtr(p, serialOf(p)); + } + + // ---------------------------------------------------------------- pins (Java-heap stores) + + /** Store-site hook: a native-layout object stored into a Java-heap location is made native and pinned. */ + public static void pinIfNative(Object value) { + if (!NO_CLASSES.isValid() && value instanceof PNativeLayoutObject o && !o.isPinned()) { + pin(o); + } + } + + /** Same as {@link #pinIfNative(Object)}, also counting the pin under {@code siteCounter}. */ + public static void pinIfNative(Object value, int siteCounter) { + if (!NO_CLASSES.isValid() && value instanceof PNativeLayoutObject o && !o.isPinned()) { + pin(o); + count(siteCounter); + } + } + + /** + * Identity for {@code id()} and the default hash: the struct pointer, so every in-flight copy of + * a struct yields the same value. An object that is not native yet is made native and pinned (a + * struct made native without a counted reference would never be recorded, i.e. leak; the pin + * keeps it, and the identity, alive as long as this Java object). An object that is already + * native is not pinned again. + */ + @TruffleBoundary + public static long identity(PNativeLayoutObject o) { + long p = o.getSlotsPtr(); + if (p == 0) { + pin(o); + count(C_PIN_ID); + p = o.getSlotsPtr(); + } else { + checkLive(o); + } + return p; + } + + /** Values a pointer-aware list holds: native-layout instances and None (only once an opt-in class exists). */ + public static boolean isListWordValue(Object v) { + return v instanceof PNativeLayoutObject || (v == PNone.NONE && !NO_CLASSES.isValid()); + } + + public static void pinArray(Object[] values, int from, int to) { + if (!NO_CLASSES.isValid()) { + for (int i = from; i < to; i++) { + pinIfNative(values[i]); + } + } + } + + @TruffleBoundary + public static void pin(PNativeLayoutObject o) { + if (o.isPinned()) { + return; + } + PythonContext ctx = PythonContext.get(null); + long st = state(ctx); + long p = o.getSlotsPtr(); + if (p == 0) { + p = makeNativeSlow(ctx, st, o); + } else { + checkLive(o); + } + incref(p); + o.setPinned(); + count(C_PIN); + new PinRef(o, p, ctx.getSharedFinalizer()); + } + + static final class PinRef extends AsyncHandler.SharedFinalizer.FinalizableReference { + private long ptr; + + PinRef(PNativeLayoutObject referent, long ptr, AsyncHandler.SharedFinalizer finalizer) { + super(referent, finalizer); + this.ptr = ptr; + } + + @Override + public AsyncHandler.AsyncAction release() { + final long p = ptr; + ptr = 0; + if (p == 0) { + return null; + } + return (context, access) -> { + count(C_UNPIN); + decref(state(context), p); + }; + } + } + +} diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeLong.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeLong.java new file mode 100644 index 0000000000..f1f257b3d1 --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeLong.java @@ -0,0 +1,301 @@ +/* + * 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.runtime.nativeaccess; + +import static com.oracle.graal.python.runtime.nativeaccess.NativeMemory.UNSAFE; + +import java.math.BigInteger; + +import com.oracle.graal.python.PythonLanguage; +import com.oracle.graal.python.runtime.object.PFactory; +import com.oracle.truffle.api.CompilerDirectives; +import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; + +/** + * Exact {@code int} values that do not fit GraalPy's tagged pointer + * become native CPython {@code PyLongObject} structs when they escape to C. There is no Java + * companion object and no handle table entry: the in-flight value stays a Java {@code long}, the + * struct exists only while C holds a count on it. + * + *

+ * Struct layout (40 bytes, one size class): {@code ob_refcnt} @0, {@code ob_type} @8, + * {@code long_value.lv_tag} @16, {@code long_value.ob_digit[4]} @24 (30-bit digits, as CPython on + * 64-bit platforms). Up to 4 digits (120 bits) fit; larger values keep the stub path (Java + * {@code PInt} plus native stub). A free block keeps its free-list link at @16. + *

+ * + *

+ * The allocator state is a region of the shared native value state block ({@link NativeComplex#S_LONG}) so that + * C ({@code longobject.c}) uses the same free list without an upcall, and so that the borrowed stack + * of {@link NativeComplex} also holds the counts of int arguments. A struct whose count reaches zero + * is freed at once: nothing on the Java side keeps a pointer to it (the Java value is a copy). + * Single-threaded: callers hold the GIL. + *

+ */ +public final class NativeLong { + + public static final boolean COUNTERS = NativeComplex.COUNTERS; + + public static final int BLOCK_SIZE = 40; + public static final long OFF_REFCNT = 0; + public static final long OFF_TYPE = 8; + public static final long OFF_TAG = 16; + public static final long OFF_DIGITS = 24; + public static final int MAX_DIGITS = 4; + private static final long OFF_LINK = 16; + + // region layout, relative to st + NativeComplex.S_LONG (must match GraalPyLongAllocState in longobject.c) + public static final long L_FREE = 0; + public static final long L_BUMP = 8; + public static final long L_END = 16; + public static final long L_TYPE = 24; + public static final long L_ARENAS = 32; + public static final long L_COUNTERS = 40; + public static final int N_COUNTERS = 8; + public static final long REGION_SIZE = L_COUNTERS + 8 * N_COUNTERS; + + public static final int C_ALLOC = 0; + public static final int C_FREE = 1; + public static final int C_JAVA_TO_C = 2; + public static final int C_C_TO_JAVA = 3; + public static final int C_C_ALLOC = 4; // updated by C + public static final int C_C_FREE = 5; // updated by C + public static final String[] COUNTER_NAMES = {"long_alloc", "long_free", "long_java_to_c", "long_c_to_java", "long_c_alloc", "long_c_free", "", ""}; + + private static final long ARENA_SIZE = 64 * 1024; + private static final long ARENA_HEADER = 16; + + private static final int SHIFT = 30; + private static final long MASK = (1L << SHIFT) - 1; + private static final long SIGN_ZERO = 1; + private static final long SIGN_NEGATIVE = 2; + + private static final long[] JAVA_COUNTS = new long[N_COUNTERS]; + + private NativeLong() { + } + + private static void count(int idx) { + if (COUNTERS) { + JAVA_COUNTS[idx]++; + } + } + + private static long region(long st) { + return st + NativeComplex.S_LONG; + } + + @TruffleBoundary + public static long[] snapshot(long st, boolean reset) { + long[] res = new long[N_COUNTERS]; + for (int i = 0; i < N_COUNTERS; i++) { + res[i] = JAVA_COUNTS[i] + (st != 0 ? UNSAFE.getLong(region(st) + L_COUNTERS + 8L * i) : 0); + if (reset) { + JAVA_COUNTS[i] = 0; + if (st != 0) { + UNSAFE.putLong(region(st) + L_COUNTERS + 8L * i, 0); + } + } + } + return res; + } + + /** Type pointer of {@code PyLong_Type}, or 0 before the C API is initialized. */ + public static long getLongType(long st) { + return UNSAFE.getLong(region(st) + L_TYPE); + } + + /** True if {@code p} (a non-handle PyObject pointer) is an exact native int struct. */ + public static boolean isNativeLong(long st, long p) { + long type = UNSAFE.getLong(region(st) + L_TYPE); + return type != 0 && UNSAFE.getLong(p + OFF_TYPE) == type; + } + + // ---------------------------------------------------------------- allocation + + private static long alloc(long r) { + long p = UNSAFE.getLong(r + L_FREE); + if (p != 0) { + UNSAFE.putLong(r + L_FREE, UNSAFE.getLong(p + OFF_LINK)); + } else { + p = UNSAFE.getLong(r + L_BUMP); + if (CompilerDirectives.injectBranchProbability(CompilerDirectives.SLOWPATH_PROBABILITY, p + BLOCK_SIZE > UNSAFE.getLong(r + L_END))) { + p = newArena(r); + } else { + UNSAFE.putLong(r + L_BUMP, p + BLOCK_SIZE); + } + } + count(C_ALLOC); + return p; + } + + @TruffleBoundary + private static long newArena(long r) { + long arena = UNSAFE.allocateMemory(ARENA_SIZE); + UNSAFE.putLong(arena, UNSAFE.getLong(r + L_ARENAS)); + UNSAFE.putLong(r + L_ARENAS, arena); + long p = arena + ARENA_HEADER; + UNSAFE.putLong(r + L_BUMP, p + BLOCK_SIZE); + UNSAFE.putLong(r + L_END, arena + ARENA_SIZE); + return p; + } + + private static void free(long r, long p) { + UNSAFE.putLong(p + OFF_TYPE, 0); + UNSAFE.putLong(p + OFF_LINK, UNSAFE.getLong(r + L_FREE)); + UNSAFE.putLong(r + L_FREE, p); + count(C_FREE); + } + + /** Drops one count; frees the struct when it reaches zero. */ + public static void decref(long st, long p) { + long rc = UNSAFE.getLong(p + OFF_REFCNT) - 1; + UNSAFE.putLong(p + OFF_REFCNT, rc); + if (rc == 0) { + free(region(st), p); + } + } + + // ---------------------------------------------------------------- Java <-> struct + + /** + * Struct for a Java {@code long} handed to C, with one count. With {@code newRef} the count is + * owned by C; otherwise it is held for the duration of the current C call (borrowed stack of + * {@link NativeComplex}, released when the outermost downcall returns). + */ + public static long toNative(long st, long v, boolean newRef) { + long r = region(st); + if (CompilerDirectives.injectBranchProbability(CompilerDirectives.SLOWPATH_PROBABILITY, UNSAFE.getLong(r + L_TYPE) == 0)) { + return toNativeBeforeInit(v); + } + long p = alloc(r); + // branch-free encoding; callers pass only values outside the int32 range (2 or 3 digits) + assert v != (int) v; + long neg = v >> 63; // 0 or -1 + long mag = (v ^ neg) - neg; // |v|; Long.MIN_VALUE stays 2**63 read unsigned + long d2 = mag >>> (2 * SHIFT); // 0..8 + long n = 2 + ((d2 + 15) >>> 4); // 2, or 3 if d2 != 0 + UNSAFE.putLong(p + OFF_REFCNT, 1); + UNSAFE.putLong(p + OFF_TYPE, UNSAFE.getLong(r + L_TYPE)); + UNSAFE.putLong(p + OFF_TAG, (n << 3) | (neg & SIGN_NEGATIVE)); + UNSAFE.putLong(p + OFF_DIGITS, (mag & MASK) | (((mag >>> SHIFT) & MASK) << 32)); + UNSAFE.putLong(p + OFF_DIGITS + 8, d2); + if (!newRef) { + NativeComplex.borrowPush(st, p); + } + count(C_JAVA_TO_C); + return p; + } + + /** + * Before {@code graalpy_init_long_alloc} has run (C API initialization) the type pointer is not + * known: the stub path (a {@code PInt} with a native stub). The count is owned by C, so the + * promoted object stays alive (it may leak; only possible during initialization). + */ + @TruffleBoundary + private static long toNativeBeforeInit(long v) { + return com.oracle.graal.python.builtins.objects.cext.capi.transitions.CApiTransitions.PythonToNativeInternalNode.executeUncached( + PFactory.createInt(PythonLanguage.get(null), v), true); + } + + /** Number of int structs currently allocated (carved minus free-list length); measurement only. */ + @TruffleBoundary + public static long liveBlocks(long st) { + long r = region(st); + long carved = 0; + long arena = UNSAFE.getLong(r + L_ARENAS); + boolean first = true; + while (arena != 0) { + long end = first ? UNSAFE.getLong(r + L_BUMP) : arena + ARENA_SIZE; + carved += (end - (arena + ARENA_HEADER)) / BLOCK_SIZE; + first = false; + arena = UNSAFE.getLong(arena); + } + long free = 0; + for (long p = UNSAFE.getLong(r + L_FREE); p != 0; p = UNSAFE.getLong(p + OFF_LINK)) { + free++; + } + return carved - free; + } + + /** + * Value of an exact int struct coming from C ({@code Long} or, above 64 bits, a {@code PInt}); + * with {@code transfer} drops C's count. + */ + public static Object fromNative(PythonLanguage language, long st, long p, boolean transfer) { + long tag = UNSAFE.getLong(p + OFF_TAG); + long n = tag >>> 3; + Object result; + long d2 = UNSAFE.getInt(p + OFF_DIGITS + 8) & 0xFFFFFFFFL; + if (CompilerDirectives.injectBranchProbability(CompilerDirectives.LIKELY_PROBABILITY, n <= 2 || (n == 3 && d2 < 8))) { + long lo = UNSAFE.getLong(p + OFF_DIGITS); + long mag = n == 0 ? 0 : n == 1 ? (lo & MASK) : ((lo & MASK) | ((lo >>> 32) << SHIFT) | (n == 3 ? d2 << (2 * SHIFT) : 0)); + result = (tag & 3) == SIGN_NEGATIVE ? -mag : mag; + } else { + result = readSlow(language, p, n, tag & 3); + } + if (transfer) { + decref(st, p); + } + count(C_C_TO_JAVA); + return result; + } + + @TruffleBoundary + private static Object readSlow(PythonLanguage language, long p, long n, long sign) { + if (n == 3) { + long lo = UNSAFE.getLong(p + OFF_DIGITS); + long d2 = UNSAFE.getInt(p + OFF_DIGITS + 8) & 0xFFFFFFFFL; + if (d2 < 8) { + long mag = (lo & MASK) | ((lo >>> 32) << SHIFT) | (d2 << (2 * SHIFT)); + return sign == SIGN_NEGATIVE ? -mag : mag; + } + if (sign == SIGN_NEGATIVE && d2 == 8 && lo == 0) { + return Long.MIN_VALUE; + } + } + BigInteger mag = BigInteger.ZERO; + for (long i = n - 1; i >= 0; i--) { + mag = mag.shiftLeft(SHIFT).or(BigInteger.valueOf(UNSAFE.getInt(p + OFF_DIGITS + 4 * i) & 0xFFFFFFFFL)); + } + return PFactory.createInt(language, sign == SIGN_NEGATIVE ? mag.negate() : mag); + } +} diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeSlotNodes.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeSlotNodes.java new file mode 100644 index 0000000000..632f7b443d --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeSlotNodes.java @@ -0,0 +1,460 @@ +/* + * 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.runtime.nativeaccess; + +import static com.oracle.graal.python.runtime.nativeaccess.NativeInstance.HEADER; +import static com.oracle.graal.python.runtime.nativeaccess.NativeInstance.OFF_META; +import static com.oracle.graal.python.runtime.nativeaccess.NativeInstance.W_EMPTY; +import static com.oracle.graal.python.runtime.nativeaccess.NativeInstance.W_FALSE; +import static com.oracle.graal.python.runtime.nativeaccess.NativeInstance.W_NONE; +import static com.oracle.graal.python.runtime.nativeaccess.NativeInstance.W_TRUE; +import static com.oracle.graal.python.runtime.nativeaccess.NativeMemory.UNSAFE; + +import com.oracle.graal.python.PythonLanguage; +import com.oracle.graal.python.builtins.objects.PNone; +import com.oracle.graal.python.builtins.objects.complex.PComplex; +import com.oracle.graal.python.builtins.objects.object.PNativeLayoutObject; +import com.oracle.graal.python.builtins.objects.type.PythonClass; +import com.oracle.graal.python.runtime.PythonContext; +import com.oracle.truffle.api.CompilerDirectives; +import com.oracle.truffle.api.CompilerDirectives.CompilationFinal; +import com.oracle.truffle.api.nodes.ExplodeLoop; +import com.oracle.truffle.api.nodes.Node; + +/** + * Nodes for slot access on native-layout instances. Hand-written (no DSL); each node + * profiles the word kinds it has seen in {@code @CompilationFinal} bits so compiled code contains only + * those branches. The uncached instances (for uncached callers) always take the generic path. + */ +public final class NativeSlotNodes { + private NativeSlotNodes() { + } + + /** Inline depth of making nested not-yet-native objects native; deeper levels use the boundary worklist. */ + static final int MAX_INLINE_DEPTH = 2; + + // seen bits + static final int S_INT = 1; + static final int S_LONG = 1 << 1; + static final int S_CONST = 1 << 2; + static final int S_INST = 1 << 3; + static final int S_COMPLEX = 1 << 4; + static final int S_HANDLE = 1 << 5; + static final int S_EMPTY = 1 << 6; + static final int S_NEW_INST = 1 << 7; // not-yet-native instance stored + + // ------------------------------------------------------------------ word -> value + + public static final class FromWordNode extends Node { + private static final FromWordNode UNCACHED = new FromWordNode(true, NativeInstance.C_INFLIGHT); + private static final FromWordNode UNCACHED_LIST = new FromWordNode(true, NativeInstance.C_LIST_INFLIGHT); + private final boolean uncached; + /** Counter for in-flight objects built by this node (slot loads or list loads). */ + private final int inflightCounter; + @CompilationFinal private int seen; + @CompilationFinal private int cachedId; // 0 = uninitialized, -1 = generic + @CompilationFinal private PythonClass cachedClass; + + private FromWordNode(boolean uncached, int inflightCounter) { + this.uncached = uncached; + this.inflightCounter = inflightCounter; + } + + @com.oracle.truffle.api.dsl.NeverDefault + public static FromWordNode create() { + return new FromWordNode(false, NativeInstance.C_INFLIGHT); + } + + /** For loads from pointer-aware lists (counted as list loads). */ + @com.oracle.truffle.api.dsl.NeverDefault + public static FromWordNode createForList() { + return new FromWordNode(false, NativeInstance.C_LIST_INFLIGHT); + } + + public static FromWordNode getUncachedForList() { + return UNCACHED_LIST; + } + + @Override + public boolean isAdoptable() { + return !uncached; + } + + private void see(int bit) { + if ((seen & bit) == 0) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + seen |= bit; + } + } + + /** Returns the value, or {@code null} for an empty slot. */ + public Object execute(long w) { + if (uncached) { + if (inflightCounter == NativeInstance.C_LIST_INFLIGHT && (w & 3) == 0 && w != 0) { + NativeInstance.count(inflightCounter); + return NativeInstance.loadInstanceUncounted(w); + } + return NativeInstance.fromWordGeneric(PythonContext.get(null), w); + } + int tag = (int) w & 3; + if (tag == 1) { + long v = w >> 2; + if (v == (int) v) { + see(S_INT); + return (int) v; + } + see(S_LONG); + return v; + } else if (tag == 0) { + if (w == W_EMPTY) { + see(S_EMPTY); + return null; + } + see(S_INST); + return loadInstance(w); + } else if (tag == 3) { + if ((w & 4) == 0) { + see(S_CONST); + if (w == W_NONE) { + return PNone.NONE; + } + return w == W_TRUE; + } + see(S_HANDLE); + return NativeInstance.handleLoad(w); + } else { + see(S_COMPLEX); + return NativeComplex.load(PythonLanguage.get(this), w & ~3L); + } + } + + private PNativeLayoutObject loadInstance(long p) { + NativeInstance.checkStruct(p); + int cid = (int) UNSAFE.getLong(p + OFF_META); + PythonClass cls; + if (cid == cachedId) { + cls = cachedClass; + } else { + if (cachedId == 0) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + cachedId = cid; + cachedClass = NativeInstance.classOf(cid); + } else if (cachedId != -1) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + cachedId = -1; + cachedClass = null; + } + cls = NativeInstance.classOf(cid); + } + NativeInstance.count(inflightCounter); + return new PNativeLayoutObject(cls, cls.getInstanceShape(), p, NativeInstance.serialOf(p)); + } + } + + // ------------------------------------------------------------------ value -> word + + public static final class ToWordNode extends Node { + private static final ToWordNode UNCACHED = new ToWordNode(true, MAX_INLINE_DEPTH); + private final boolean uncached; + private final int depth; + @CompilationFinal private int seen; + @Child private MakeNativeNode makeNative; + + private ToWordNode(boolean uncached, int depth) { + this.uncached = uncached; + this.depth = depth; + } + + @com.oracle.truffle.api.dsl.NeverDefault + public static ToWordNode create() { + return new ToWordNode(false, 0); + } + + public static ToWordNode getUncached() { + return UNCACHED; + } + + static ToWordNode create(int depth) { + return new ToWordNode(false, depth); + } + + @Override + public boolean isAdoptable() { + return !uncached; + } + + private void see(int bit) { + if ((seen & bit) == 0) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + seen |= bit; + } + } + + /** Converts a value into a counted word (adds the reference the word holds). */ + public long execute(Object v) { + if (uncached) { + PythonContext ctx = PythonContext.get(null); + return NativeInstance.toWordGeneric(ctx, NativeInstance.state(ctx), v); + } + if (v instanceof Integer i) { + see(S_INT); + return NativeInstance.tagInt(i); + } else if (v instanceof PNativeLayoutObject o) { + long p = o.getSlotsPtr(); + if (p == 0) { + see(S_NEW_INST); + p = getMakeNative().execute(o); + } else { + see(S_INST); + NativeInstance.checkLive(o); + } + NativeInstance.incref(p); + return p; + } else if (v == PNone.NONE) { + see(S_CONST); + return W_NONE; + } else if (v instanceof Boolean b) { + see(S_CONST); + return b ? W_TRUE : W_FALSE; + } else if (v instanceof Long l && NativeInstance.fitsTagged(l)) { + see(S_LONG); + return NativeInstance.tagInt(l); + } else if (v instanceof PComplex c && c.isExact()) { + see(S_COMPLEX); + return NativeInstance.complexWord(PythonContext.get(this), c); + } + see(S_HANDLE); + return NativeInstance.handleStore(v); + } + + private MakeNativeNode getMakeNative() { + if (makeNative == null) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + makeNative = insert(new MakeNativeNode(depth)); + } + return makeNative; + } + } + + // ------------------------------------------------------------------ making an object native + + /** + * Allocates the struct for a not-yet-native object and converts its Java slots (exploded loop for + * one cached class, so a virtual object stays virtual). Nested not-yet-native objects are made + * native by nested nodes up to {@link #MAX_INLINE_DEPTH}, below that by the boundary worklist. + */ + public static final class MakeNativeNode extends Node { + private final int depth; + @CompilationFinal private Object cachedClass; + @CompilationFinal private int cachedId; + @CompilationFinal private boolean generic; + @Children private ToWordNode[] words; + + MakeNativeNode(int depth) { + this.depth = depth; + } + + public long execute(PNativeLayoutObject o) { + Object cls = o.getPythonClass(); + if (cachedClass != null && cls == cachedClass) { + return inline(o); + } + if (!generic && cachedClass == null && depth < MAX_INLINE_DEPTH) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + PythonClass pc = (PythonClass) cls; + cachedId = pc.getNativeLayoutId(); + int n = NativeInstance.slotCountOf(cachedId); + ToWordNode[] w = new ToWordNode[n]; + for (int i = 0; i < n; i++) { + w[i] = ToWordNode.create(depth + 1); + } + words = insert(w); + cachedClass = cls; + return inline(o); + } + if (!generic) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + generic = true; + } + PythonContext ctx = PythonContext.get(this); + return NativeInstance.makeNativeSlow(ctx, NativeInstance.state(ctx), o); + } + + @ExplodeLoop + private long inline(PNativeLayoutObject o) { + long st = NativeInstance.state(PythonContext.get(this)); + ToWordNode[] w = words; + int n = w.length; + long p = NativeInstance.alloc(st, cachedId, n); + o.setSlotsPtr(p, NativeInstance.serialOf(p)); + Object[] js = o.getIndexedSlots(); + for (int i = 0; i < n; i++) { + Object v = js == null ? null : js[i]; + long word = v == null ? W_EMPTY : w[i].execute(v); + UNSAFE.putLong(p + HEADER + 8L * i, word); + } + o.setIndexedSlots(null); + NativeInstance.count(NativeInstance.C_MAT_INLINE); + return p; + } + } + + // ------------------------------------------------------------------ slot read / write + + public static final class ReadSlotNode extends Node { + private static final ReadSlotNode UNCACHED = new ReadSlotNode(true); + @Child private FromWordNode fromWord; + + private ReadSlotNode(boolean uncached) { + this.fromWord = uncached ? FromWordNode.UNCACHED : FromWordNode.create(); + } + + @com.oracle.truffle.api.dsl.NeverDefault + public static ReadSlotNode create() { + return new ReadSlotNode(false); + } + + public static ReadSlotNode getUncached() { + return UNCACHED; + } + + @Override + public boolean isAdoptable() { + return this != UNCACHED; + } + + @CompilationFinal private byte seenSides; // 1 = native receiver seen, 2 = Java-slots receiver seen + + /** + * Two-sided profile of "receiver is a native instance" for the caller's branch: a side never + * seen becomes a deoptimization, so the two branches' results do not meet in a phi. + */ + public boolean profileNative(boolean isNative) { + if (this == UNCACHED) { + return isNative; + } + if (isNative) { + if ((seenSides & 1) == 0) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + seenSides |= 1; + } + return true; + } else { + if ((seenSides & 2) == 0) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + seenSides |= 2; + } + return false; + } + } + + /** Reads slot {@code index} of a native instance; {@code null} if it is not set. */ + public Object execute(PNativeLayoutObject o, int index) { + NativeInstance.checkLive(o); + long w = UNSAFE.getLong(o.getSlotsPtr() + HEADER + 8L * index); + return fromWord.execute(w); + } + } + + public static final class WriteSlotNode extends Node { + private static final WriteSlotNode UNCACHED = new WriteSlotNode(true); + private final boolean uncached; + @Child private ToWordNode toWord; + @CompilationFinal private int seenOld; + + private WriteSlotNode(boolean uncached) { + this.uncached = uncached; + this.toWord = uncached ? ToWordNode.UNCACHED : ToWordNode.create(); + } + + @com.oracle.truffle.api.dsl.NeverDefault + public static WriteSlotNode create() { + return new WriteSlotNode(false); + } + + public static WriteSlotNode getUncached() { + return UNCACHED; + } + + @Override + public boolean isAdoptable() { + return this != UNCACHED; + } + + /** Writes slot {@code index}; {@code value == null} deletes it. Returns false if deleting an unset slot. */ + public boolean execute(PNativeLayoutObject o, int index, Object value) { + NativeInstance.checkLive(o); + long w = value == null ? W_EMPTY : toWord.execute(value); + long a = o.getSlotsPtr() + HEADER + 8L * index; + long old = UNSAFE.getLong(a); + UNSAFE.putLong(a, w); + release(old); + return old != W_EMPTY; + } + + private void release(long old) { + if (uncached) { + NativeInstance.releaseSlow(old); + return; + } + int tag = (int) old & 3; + if (tag == 1 || old == W_EMPTY) { + return; + } + if (tag == 0) { + if ((seenOld & S_INST) == 0) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + seenOld |= S_INST; + } + NativeInstance.checkStruct(old); + NativeInstance.decref(NativeInstance.state(PythonContext.get(this)), old); + } else if (tag == 3 && (old & 4) == 0) { + return; // constant + } else { + if ((seenOld & S_HANDLE) == 0) { + CompilerDirectives.transferToInterpreterAndInvalidate(); + seenOld |= S_HANDLE; + } + NativeInstance.releaseSlow(old); + } + } + } +} diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeSmall.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeSmall.java new file mode 100644 index 0000000000..6783c19870 --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeSmall.java @@ -0,0 +1,290 @@ +/* + * 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.runtime.nativeaccess; + +import static com.oracle.graal.python.runtime.nativeaccess.NativeMemory.UNSAFE; + +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.floats.PNativeFloat; +import com.oracle.truffle.api.CompilerDirectives; +import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; + +/** + * The small-block pool of {@code PyObject_Malloc} ({@code obmalloc.c}), + * shared with Java, and the native {@code float} structs built from it. + * + *

+ * A pool block is 64 bytes: a 16-byte header (requested size, {@link #POOL_MAGIC}) and up to 48 bytes + * of payload; pointers handed out are payload pointers, so {@code PyObject_Free} (C) and + * {@link #free} (Java) handle the same blocks. Free blocks keep the magic, hold the free-list link in + * the size word and have the payload's {@code ob_type} cleared (a stale pointer kept by an in-flight + * {@link PNativeFloat} is recognised by that). Arenas (64 KB) are never freed. Single-threaded: + * callers hold the GIL. + *

+ * + *

+ * Floats: an exact {@code float} that GraalPy cannot tag (not exactly representable as a 32-bit + * float) becomes a {@code PyFloatObject} struct from this pool when it escapes to C; a struct coming + * back is read into a Java {@code double}. An instance of a native subclass of {@code float} that is + * nothing but (type, {@code ob_fval}) ({@link #isFloatValueType}) is held in Java as a + * {@link PNativeFloat} value copy instead of a {@code PythonAbstractNativeObject} with a weak + * reference and lookup-table entry; it becomes a struct again when it escapes to C. + *

+ */ +public final class NativeSmall { + + public static final long POOL_MAGIC = 0x47505241504F4F4CL; + public static final int BLOCK_SIZE = 64; + public static final int MAX_PAYLOAD = BLOCK_SIZE - 16; + private static final long ARENA_SIZE = 64 * 1024; + private static final long ARENA_HEADER = 16; + + // region layout, relative to st + NativeComplex.S_SMALL (must match GraalPySmallState in obmalloc.c) + public static final long R_FREE = 0; + public static final long R_BUMP = 8; + public static final long R_END = 16; + public static final long R_ARENAS = 24; + public static final long R_FLOAT_TYPE = 32; + public static final long R_FLOAT_DEALLOC = 40; + public static final long R_FLOAT_FREE = 48; + public static final long R_COUNTERS = 56; + public static final long REGION_SIZE = R_COUNTERS + 8 * 4; + + // PyFloatObject + public static final long OFF_REFCNT = 0; + public static final long OFF_TYPE = 8; + public static final long OFF_FVAL = 16; + public static final int FLOAT_SIZE = 24; + /** Generation word of a pool block (last payload word), incremented on every free (C and Java). */ + public static final long OFF_GEN = 40; + + public static long generation(long p) { + return UNSAFE.getLong(p + OFF_GEN); + } + + private NativeSmall() { + } + + private static long region(long st) { + return st + NativeComplex.S_SMALL; + } + + /** Pointer of {@code PyFloat_Type}, or 0 before the C API is initialized. */ + public static long getFloatType(long st) { + return UNSAFE.getLong(region(st) + R_FLOAT_TYPE); + } + + // ---------------------------------------------------------------- pool + + /** Payload pointer of a new pool block for {@code size} (at most {@link #MAX_PAYLOAD}) bytes. */ + public static long alloc(long st, long size) { + long r = region(st); + long b = UNSAFE.getLong(r + R_FREE); + if (b != 0) { + UNSAFE.putLong(r + R_FREE, UNSAFE.getLong(b)); + } else { + b = UNSAFE.getLong(r + R_BUMP); + if (CompilerDirectives.injectBranchProbability(CompilerDirectives.SLOWPATH_PROBABILITY, b + BLOCK_SIZE > UNSAFE.getLong(r + R_END))) { + b = newArena(r); + } else { + UNSAFE.putLong(r + R_BUMP, b + BLOCK_SIZE); + } + } + UNSAFE.putLong(b, size); + UNSAFE.putLong(b + 8, POOL_MAGIC); + return b + 16; + } + + @TruffleBoundary + private static long newArena(long r) { + long arena = UNSAFE.allocateMemory(ARENA_SIZE); + UNSAFE.putLong(arena, UNSAFE.getLong(r + R_ARENAS)); + UNSAFE.putLong(r + R_ARENAS, arena); + long b = arena + ARENA_HEADER; + UNSAFE.putLong(r + R_BUMP, b + BLOCK_SIZE); + UNSAFE.putLong(r + R_END, arena + ARENA_SIZE); + return b; + } + + /** True if {@code p} is the payload pointer of a pool block (allocated or free). */ + public static boolean isPool(long p) { + return UNSAFE.getLong(p - 8) == POOL_MAGIC; + } + + /** Returns a pool block (payload pointer) to the free list. */ + public static void free(long st, long p) { + long r = region(st); + long b = p - 16; + UNSAFE.putLong(p + OFF_TYPE, 0); + UNSAFE.putLong(p + OFF_GEN, UNSAFE.getLong(p + OFF_GEN) + 1); + UNSAFE.putLong(b, UNSAFE.getLong(r + R_FREE)); + UNSAFE.putLong(r + R_FREE, b); + } + + /** + * Drops one count of a float struct (exact or value-type subclass, see {@link #isFloatValueType}) + * and deallocates it at zero. Both have {@code tp_dealloc = object_dealloc} and + * {@code tp_free = PyObject_Free}, so a pool block is freed here; any other block is deallocated + * by C. + */ + public static void decref(long st, long p) { + long rc = UNSAFE.getLong(p + OFF_REFCNT) - 1; + UNSAFE.putLong(p + OFF_REFCNT, rc); + if (rc == 0) { + if (CompilerDirectives.injectBranchProbability(CompilerDirectives.LIKELY_PROBABILITY, isPool(p))) { + free(st, p); + } else { + deallocSlow(p); + } + } + } + + @TruffleBoundary + private static void deallocSlow(long p) { + // count is zero: let C run the type's tp_dealloc (_Py_Dealloc) + com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.XDecRefPointerNode.deallocNative(p); + } + + // ---------------------------------------------------------------- floats + + /** True if {@code p} (a non-handle PyObject pointer) is an exact native float struct. */ + public static boolean isNativeFloat(long st, long p) { + long type = getFloatType(st); + return type != 0 && UNSAFE.getLong(p + OFF_TYPE) == type; + } + + /** + * Struct for a Java {@code double} handed to C, with one count; with {@code newRef} the count is + * C's, otherwise it is on the borrowed stack until the outermost downcall returns. Callers check + * {@link #getFloatType} first. + */ + public static long floatToNative(long st, double d, boolean newRef) { + long p = alloc(st, FLOAT_SIZE); + UNSAFE.putLong(p + OFF_REFCNT, 1); + UNSAFE.putLong(p + OFF_TYPE, getFloatType(st)); + UNSAFE.putDouble(p + OFF_FVAL, d); + if (!newRef) { + NativeComplex.borrowPush(st, p); + } + return p; + } + + /** Value of a float struct (exact or value-type subclass); with {@code transfer} drops C's count. */ + public static double floatFromNative(long st, long p, boolean transfer) { + double d = UNSAFE.getDouble(p + OFF_FVAL); + if (transfer) { + decref(st, p); + } + return d; + } + + /** + * Struct for an in-flight instance of a value-type float subclass. The struct the value was last + * converted from or to is reused while it is the same incarnation (generation word unchanged, i.e. + * not freed since) and alive with the same type and bits, so identity survives a round trip through + * C; otherwise a new one is made. + */ + public static long valueToNative(long st, PNativeFloat f, long typePtr, boolean newRef) { + double d = f.getValue(); + long p = f.getStructHint(); + if (p != 0 && UNSAFE.getLong(p + OFF_GEN) == f.getStructGen() && UNSAFE.getLong(p + OFF_REFCNT) > 0 && UNSAFE.getLong(p + OFF_TYPE) == typePtr && + UNSAFE.getLong(p + OFF_FVAL) == Double.doubleToRawLongBits(d)) { + UNSAFE.putLong(p + OFF_REFCNT, UNSAFE.getLong(p + OFF_REFCNT) + 1); + } else { + p = alloc(st, FLOAT_SIZE); + UNSAFE.putLong(p + OFF_REFCNT, 1); + UNSAFE.putLong(p + OFF_TYPE, typePtr); + UNSAFE.putDouble(p + OFF_FVAL, d); + f.setStructHint(p, UNSAFE.getLong(p + OFF_GEN)); + } + if (!newRef) { + NativeComplex.borrowPush(st, p); + } + return p; + } + + /** Keeps one count of {@code p} until the outermost downcall returns (borrowed stack). */ + public static void deferRelease(long st, long p) { + NativeComplex.borrowPush(st, p); + } + + private static final long TPFLAGS_MANAGED_WEAKREF = 1L << 3; + private static final long TPFLAGS_MANAGED_DICT = 1L << 4; + private static final long TPFLAGS_HEAPTYPE = 1L << 9; + private static final long TPFLAGS_HAVE_GC = 1L << 14; + + /** + * A native type whose instances are nothing but (type, {@code ob_fval}): a static subtype of + * {@code float} with the size of {@code PyFloatObject}, no items, dict, weak list or GC, no + * finalizer, and {@code float}'s deallocator and free function. Computed once per type (cached by + * the caller). + */ + @TruffleBoundary + public static boolean isFloatValueType(long st, long t) { + long r = region(st); + long floatType = UNSAFE.getLong(r + R_FLOAT_TYPE); + if (floatType == 0 || t == 0 || t == floatType) { + return false; + } + if (CStructAccess.readLongField(t, CFields.PyTypeObject__tp_basicsize) != FLOAT_SIZE || CStructAccess.readLongField(t, CFields.PyTypeObject__tp_itemsize) != 0 || + CStructAccess.readLongField(t, CFields.PyTypeObject__tp_dictoffset) != 0 || CStructAccess.readLongField(t, CFields.PyTypeObject__tp_weaklistoffset) != 0) { + return false; + } + long flags = CStructAccess.readLongField(t, CFields.PyTypeObject__tp_flags); + if ((flags & (TPFLAGS_MANAGED_WEAKREF | TPFLAGS_MANAGED_DICT | TPFLAGS_HEAPTYPE | TPFLAGS_HAVE_GC)) != 0) { + return false; + } + if (CStructAccess.readPtrField(t, CFields.PyTypeObject__tp_dealloc) != UNSAFE.getLong(r + R_FLOAT_DEALLOC) || + CStructAccess.readPtrField(t, CFields.PyTypeObject__tp_free) != UNSAFE.getLong(r + R_FLOAT_FREE) || + CStructAccess.readPtrField(t, CFields.PyTypeObject__tp_finalize) != 0 || CStructAccess.readPtrField(t, CFields.PyTypeObject__tp_del) != 0) { + return false; + } + long base = CStructAccess.readPtrField(t, CFields.PyTypeObject__tp_base); + for (int i = 0; i < 16 && base != 0; i++) { + if (base == floatType) { + return true; + } + base = CStructAccess.readPtrField(base, CFields.PyTypeObject__tp_base); + } + return false; + } +} diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/ComplexPtrSequenceStorage.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/ComplexPtrSequenceStorage.java new file mode 100644 index 0000000000..4ce9439d18 --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/ComplexPtrSequenceStorage.java @@ -0,0 +1,475 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other materials provided + * with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.oracle.graal.python.runtime.sequence.storage; + +import java.util.Arrays; + +import com.oracle.graal.python.PythonLanguage; +import com.oracle.graal.python.builtins.objects.complex.PComplex; +import com.oracle.graal.python.runtime.AsyncHandler; +import com.oracle.graal.python.runtime.PythonContext; +import com.oracle.graal.python.runtime.nativeaccess.NativeComplex; +import com.oracle.graal.python.runtime.nativeaccess.NativeInstance; +import com.oracle.graal.python.util.PythonUtils; +import com.oracle.truffle.api.CompilerDirectives; +import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; + +/** + * List storage of exact {@code complex} values as raw pointers to native, + * reference-counted structs (see {@link NativeComplex}). Every non-zero slot below {@code length} + * holds one counted reference; slots at or above {@code length} are always 0. When the storage + * object dies, a {@link Cleaner} (phantom reference, declared shim) drops the remaining references. + */ +public class ComplexPtrSequenceStorage extends ArrayBasedSequenceStorage { + + protected long[] values; + protected final long state; + /** + * Element kind. false = raw complex pointers; true = native-instance + * words ({@link InstPtrSequenceStorage}: counted instance pointer or the {@code None} word). + */ + protected final boolean inst; + private Cleaner cleaner; + + public ComplexPtrSequenceStorage(long state, int capacity) { + this(state, capacity, false); + } + + protected ComplexPtrSequenceStorage(long state, int capacity, boolean inst) { + this.state = state; + this.inst = inst; + this.values = new long[capacity]; + this.capacity = capacity; + this.length = 0; + } + + /** Takes ownership of {@code length} counted references in {@code elements}. */ + public ComplexPtrSequenceStorage(long state, long[] elements, int length) { + this(state, elements, length, false); + } + + protected ComplexPtrSequenceStorage(long state, long[] elements, int length, boolean inst) { + this.state = state; + this.inst = inst; + this.values = elements; + this.capacity = elements.length; + this.length = length; + if (length > 0) { + registerCleaner(); + } + } + + /** New storage of the same kind taking ownership of the counted words in {@code elements}. */ + protected ComplexPtrSequenceStorage newSameKind(long[] elements, int len) { + return new ComplexPtrSequenceStorage(state, elements, len); + } + + public final boolean isInst() { + return inst; + } + + // ------------------------------------------------------------------ reference operations by kind + + /** Adds the reference a word holds (instance words: only tag-0 pointers hold one). */ + static void incw(boolean inst, long w) { + if (inst) { + if ((w & 3) == 0 && w != 0) { + NativeInstance.checkStruct(w); + NativeInstance.incref(w); + } + } else if (w != 0) { + NativeComplex.incref(w); + } + } + + /** Drops the reference a word holds. */ + static void decw(boolean inst, long st, long w) { + if (inst) { + if ((w & 3) == 0 && w != 0) { + NativeInstance.checkStruct(w); + NativeInstance.decref(st, w); + } + } else if (w != 0) { + NativeComplex.decref(st, w); + } + } + + public final void incw(long w) { + incw(inst, w); + } + + public final void decw(long w) { + decw(inst, state, w); + } + + public long getState() { + return state; + } + + // ------------------------------------------------------------------ lifetime + + static final class Cleaner extends AsyncHandler.SharedFinalizer.FinalizableReference { + long[] values; + final long state; + final boolean inst; + + Cleaner(ComplexPtrSequenceStorage storage, AsyncHandler.SharedFinalizer finalizer) { + super(storage, finalizer); + this.values = storage.values; + this.state = storage.state; + this.inst = storage.inst; + } + + @Override + public AsyncHandler.AsyncAction release() { + final long[] v = values; + values = null; + if (v == null) { + return null; + } + if (inst) { + return (context, access) -> { + NativeInstance.count(NativeInstance.C_LIST_CLEANER); + releaseAll(true, state, v, v.length); + }; + } + return (context, access) -> releaseAll(false, state, v, v.length); + } + } + + @TruffleBoundary + private void registerCleaner() { + cleaner = new Cleaner(this, PythonContext.get(null).getSharedFinalizer()); + } + + protected final void ensureCleaner() { + if (CompilerDirectives.injectBranchProbability(CompilerDirectives.SLOWPATH_PROBABILITY, cleaner == null)) { + registerCleaner(); + } + } + + private void setValues(long[] newValues) { + values = newValues; + capacity = newValues.length; + if (cleaner != null) { + cleaner.values = newValues; + } + } + + static void releaseAll(boolean inst, long st, long[] v, int n) { + for (int i = 0; i < n; i++) { + long p = v[i]; + if (p != 0) { + v[i] = 0; + decw(inst, st, p); + } + } + } + + /** + * Drops every element reference (count -1 each) and empties the storage. Used before the storage + * is replaced by a generalized one. + */ + public void releaseAllAndClear() { + // whole array: a failed bulk operation may have left counted slots above length + releaseAll(inst, state, values, values.length); + length = 0; + } + + /** + * Replaces slots [lo, hi) by the {@code n} already counted pointers in {@code owned}; drops the + * replaced references. + */ + public void replaceRange(int lo, int hi, long[] owned, int n) { + int len = length; + int growth = n - (hi - lo); + ensureCapacity(len + growth); + for (int i = lo; i < hi; i++) { + long p = values[i]; + values[i] = 0; + if (p != 0) { + decw(p); + } + } + if (growth != 0) { + PythonUtils.arraycopy(values, hi, values, lo + n, len - hi); + } + if (n > 0) { + PythonUtils.arraycopy(owned, 0, values, lo, n); + } + int newLen = len + growth; + for (int i = newLen; i < len; i++) { + values[i] = 0; + } + length = newLen; + if (newLen > 0) { + ensureCleaner(); + } + } + + /** Extended-slice assignment: slot start + i*step gets owned[i] (counted); old refs dropped. */ + public void setStepped(int start, int step, long[] owned, int n) { + for (int i = 0, cur = start; i < n; i++, cur += step) { + long old = values[cur]; + values[cur] = owned[i]; + if (old != 0) { + decw(old); + } + } + } + + /** Deletes the slice (start, step, sliceLength) as adjusted by SliceInfo, dropping references. */ + public void deleteSlice(int start, int step, int sliceLength) { + if (sliceLength <= 0) { + return; + } + if (step == 1) { + replaceRange(start, start + sliceLength, null, 0); + return; + } + int len = length; + boolean[] removed = new boolean[len]; + for (int i = 0, cur = start; i < sliceLength; i++, cur += step) { + removed[cur] = true; + } + int j = 0; + for (int i = 0; i < len; i++) { + long p = values[i]; + if (removed[i]) { + if (p != 0) { + decw(p); + } + } else { + values[j++] = p; + } + } + for (int i = j; i < len; i++) { + values[i] = 0; + } + length = j; + } + + /** Copy of the pointers [0, length), each incref'd. */ + public long[] getCountedPtrs() { + long[] res = new long[length]; + for (int i = 0; i < length; i++) { + long p = values[i]; + incw(p); + res[i] = p; + } + return res; + } + + /** New storage with the elements repeated {@code times} times, each slot counted. */ + public ComplexPtrSequenceStorage repeat(int times) throws ArithmeticException { + int len = length; + int newLen = Math.multiplyExact(len, times); + long[] arr = new long[Math.max(newLen, 1)]; + for (int t = 0; t < times; t++) { + for (int i = 0; i < len; i++) { + long p = values[i]; + incw(p); + arr[t * len + i] = p; + } + } + return newSameKind(arr, newLen); + } + + // ------------------------------------------------------------------ capacity + + private void increaseCapacityExactWithCopy(int newCapacity) { + setValues(PythonUtils.arrayCopyOf(values, newCapacity)); + } + + public void ensureCapacity(int newCapacity) throws ArithmeticException { + if (CompilerDirectives.injectBranchProbability(CompilerDirectives.UNLIKELY_PROBABILITY, newCapacity > capacity)) { + increaseCapacityExactWithCopy(capacityFor(newCapacity)); + } + } + + @Override + public ComplexPtrSequenceStorage createEmpty(int newCapacity) { + return new ComplexPtrSequenceStorage(state, newCapacity); + } + + @Override + public void setNewLength(int newLength) { + // slots at or above length must be 0; shrinking drops references + if (newLength < length) { + releaseRange(newLength, length); + } + this.length = newLength; + } + + /** Drops the references in slots [from, to) and zeroes them. */ + public void releaseRange(int from, int to) { + for (int i = from; i < to; i++) { + long p = values[i]; + if (p != 0) { + values[i] = 0; + decw(p); + } + } + } + + // ------------------------------------------------------------------ element access + + public long getPtr(int idx) { + return values[idx]; + } + + public PComplex getItemNormalized(PythonLanguage language, int idx) { + assert !inst; + return NativeComplex.load(language, values[idx]); + } + + /** Overwrites a live slot: materialise, +1 new, write, -1 old. */ + public void setItemNormalized(int idx, PComplex value) { + assert !inst; + long p = NativeComplex.materialize(state, value); + NativeComplex.incref(p); + long old = values[idx]; + values[idx] = p; + if (old != 0) { + NativeComplex.decref(state, old); + } else { + ensureCleaner(); + } + } + + /** Writes a slot that holds no reference (append / insert after shifting). */ + public void initItemNormalized(int idx, PComplex value) { + assert !inst; + long p = NativeComplex.materialize(state, value); + NativeComplex.incref(p); + ensureCleaner(); + values[idx] = p; + } + + /** Writes an already counted pointer into a slot that holds no reference. */ + public void initPtrOwned(int idx, long p) { + ensureCleaner(); + values[idx] = p; + } + + public void insertItem(int idx, PComplex value) { + ensureCapacity(length + 1); + if (idx < length) { + PythonUtils.arraycopy(values, idx, values, idx + 1, length - idx); + } + values[idx] = 0; + initItemNormalized(idx, value); + incLength(); + } + + /** Removes the slot at idx and returns its counted pointer (ownership passes to the caller). */ + public long removePtr(int idx) { + long p = values[idx]; + int n = length; + if (idx < n - 1) { + PythonUtils.arraycopy(values, idx + 1, values, idx, n - idx - 1); + } + values[n - 1] = 0; + length = n - 1; + return p; + } + + public void reverse() { + if (length > 0) { + int head = 0; + int tail = length - 1; + int middle = (length - 1) / 2; + for (; head <= middle; head++, tail--) { + long temp = values[head]; + values[head] = values[tail]; + values[tail] = temp; + } + } + } + + /** New storage with the elements [start, stop) by step, each incref'd. */ + public ComplexPtrSequenceStorage getSliceCopy(int start, int step, int sliceLength) { + long[] newArray = new long[Math.max(sliceLength, 1)]; + for (int i = start, j = 0; j < sliceLength; i += step, j++) { + long p = values[i]; + incw(p); + newArray[j] = p; + } + return newSameKind(newArray, sliceLength); + } + + /** Copy with every element incref'd. */ + public ComplexPtrSequenceStorage copyCounted() { + return getSliceCopy(0, 1, length); + } + + /** Boxes all elements as in-flight complex objects (no count change). */ + public Object[] getCopyOfInternalArray(PythonLanguage language) { + Object[] boxed = new Object[length]; + for (int i = 0; i < length; i++) { + boxed[i] = NativeComplex.load(language, values[i]); + } + return boxed; + } + + public long[] getInternalPtrArray() { + return values; + } + + @Override + public Object getIndicativeValue() { + // ListGeneralizationNode.doEmptyStorage then creates an empty pointer storage + return this; + } + + /** + * Generic array-based code must not copy the raw pointers without adjusting counts; the + * storage nodes route every operation on this storage through explicit specializations. + */ + @Override + public Object getInternalArrayObject() { + throw CompilerDirectives.shouldNotReachHere("ComplexPtrSequenceStorage: raw array access"); + } + + @Override + public Object getCopyOfInternalArrayObject() { + throw CompilerDirectives.shouldNotReachHere("ComplexPtrSequenceStorage: raw array copy"); + } + + @Override + public void setInternalArrayObject(Object arrayObject) { + throw CompilerDirectives.shouldNotReachHere("ComplexPtrSequenceStorage: raw array replace"); + } + + @Override + public StorageType getElementType() { + return StorageType.ComplexPtr; + } + + @TruffleBoundary + public long[] debugCopy() { + return Arrays.copyOf(values, length); + } +} diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/InstPtrSequenceStorage.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/InstPtrSequenceStorage.java new file mode 100644 index 0000000000..8628658188 --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/InstPtrSequenceStorage.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2026, Oracle and/or its affiliates. + * + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright notice, this list of + * conditions and the following disclaimer in the documentation and/or other materials provided + * with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS + * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED + * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED + * OF THE POSSIBILITY OF SUCH DAMAGE. + */ +package com.oracle.graal.python.runtime.sequence.storage; + +import com.oracle.graal.python.builtins.objects.PNone; +import com.oracle.graal.python.runtime.nativeaccess.NativeInstance; + +/** + * Pointer-aware list storage for native-layout instances (see {@link NativeInstance}). + * Every slot below {@code length} holds a native-instance word: a counted pointer to an instance + * struct (tag 0, holds one reference) or the {@code None} word (holds nothing). Slots at or above + * {@code length} are 0. Shares the count-exact array operations and the Cleaner of + * {@link ComplexPtrSequenceStorage}; the element-kind flag makes their reference operations + * instance-aware. A store of anything but an instance or {@code None} generalizes the list to an + * {@link ObjectSequenceStorage} (instances are then pinned there). + */ +public final class InstPtrSequenceStorage extends ComplexPtrSequenceStorage { + + public InstPtrSequenceStorage(long state, int capacity) { + super(state, capacity, true); + NativeInstance.count(NativeInstance.C_LIST_NEW); + } + + /** Takes ownership of {@code length} counted words in {@code elements}. */ + public InstPtrSequenceStorage(long state, long[] elements, int length) { + super(state, elements, length, true); + NativeInstance.count(NativeInstance.C_LIST_NEW); + } + + @Override + protected ComplexPtrSequenceStorage newSameKind(long[] elements, int len) { + return new InstPtrSequenceStorage(state, elements, len); + } + + @Override + public InstPtrSequenceStorage createEmpty(int newCapacity) { + return new InstPtrSequenceStorage(state, Math.max(newCapacity, 1)); + } + + public long getWord(int idx) { + return values[idx]; + } + + /** Writes an already counted word into slot idx (below length); drops the old word's reference. */ + public void setWordOwned(int idx, long w) { + NativeInstance.count(NativeInstance.C_LIST_STORE); + long old = values[idx]; + values[idx] = w; + if (old != 0) { + decw(old); + } else { + ensureCleaner(); + } + } + + /** Inserts an already counted word at idx. */ + public void insertWordOwned(int idx, long w) { + ensureCapacity(length + 1); + if (idx < length) { + com.oracle.graal.python.util.PythonUtils.arraycopy(values, idx, values, idx + 1, length - idx); + } + values[idx] = 0; + setWordOwned(idx, w); + incLength(); + } + + /** Boxes all elements (in-flight instances or None; no count change). */ + @Override + public Object[] getCopyOfInternalArray(com.oracle.graal.python.PythonLanguage language) { + Object[] boxed = new Object[length]; + for (int i = 0; i < length; i++) { + boxed[i] = box(values[i]); + } + return boxed; + } + + static Object box(long w) { + if (w == NativeInstance.W_NONE) { + return PNone.NONE; + } + NativeInstance.count(NativeInstance.C_LIST_INFLIGHT); + return NativeInstance.loadInstanceUncounted(w); + } + + /** + * Storage for a list literal (or constant list) whose elements are all native-layout instances + * and/or None, with every word counted; null if any element is something else, if no opt-in + * class exists, or at image build time. + */ + @com.oracle.truffle.api.CompilerDirectives.TruffleBoundary + public static InstPtrSequenceStorage tryCreate(Object[] elements, int len, int capacity) { + if (len == 0 || NativeInstance.NO_CLASSES.isValid() || org.graalvm.nativeimage.ImageInfo.inImageBuildtimeCode()) { + return null; + } + for (int i = 0; i < len; i++) { + if (!NativeInstance.isListWordValue(elements[i])) { + return null; + } + } + com.oracle.graal.python.runtime.PythonContext ctx = com.oracle.graal.python.runtime.PythonContext.get(null); + long st = NativeInstance.state(ctx); + long[] words = new long[Math.max(capacity, len)]; + for (int i = 0; i < len; i++) { + words[i] = NativeInstance.toWordGeneric(ctx, st, elements[i]); + NativeInstance.count(NativeInstance.C_LIST_STORE); + } + return new InstPtrSequenceStorage(st, words, len); + } + + @Override + public StorageType getElementType() { + return StorageType.InstPtr; + } +} diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/ObjectSequenceStorage.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/ObjectSequenceStorage.java index f8b4d83505..da1df114b3 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/ObjectSequenceStorage.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/ObjectSequenceStorage.java @@ -43,6 +43,7 @@ public ObjectSequenceStorage() { } public ObjectSequenceStorage(Object[] elements) { + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinArray(elements, 0, elements.length); this.values = elements; this.capacity = elements.length; this.length = elements.length; @@ -50,6 +51,7 @@ public ObjectSequenceStorage(Object[] elements) { } public ObjectSequenceStorage(Object[] elements, int length) { + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinArray(elements, 0, length); this.values = elements; this.capacity = elements.length; this.length = length; @@ -81,6 +83,7 @@ public void reverse() { } public void setObjectItemNormalized(int idx, Object value) { + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value); values[idx] = assertNoJavaString(value); } @@ -98,6 +101,7 @@ public Object[] getCopyOfInternalArray() { } public void insertItem(int idx, Object value) { + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value); ensureCapacity(length + 1); // shifting tail to the right by one slot @@ -110,6 +114,7 @@ public void insertItem(int idx, Object value) { } public void appendItem(Object value) { + com.oracle.graal.python.runtime.nativeaccess.NativeInstance.pinIfNative(value); ensureCapacity(length + 1); values[length] = assertNoJavaString(value); incLength(); diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/SequenceStorage.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/SequenceStorage.java index 7083b7ad47..409e08a151 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/SequenceStorage.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/SequenceStorage.java @@ -35,6 +35,10 @@ public enum StorageType { Int, Long, Double, + /** Raw pointers to native complex structs. */ + ComplexPtr, + /** Native-instance words (instance pointers or None). */ + InstPtr, Generic; public boolean generalizesFrom(StorageType other) { @@ -42,6 +46,8 @@ public boolean generalizesFrom(StorageType other) { case Uninitialized, Empty -> false; case Boolean, Byte, Double, Int -> other == Uninitialized || other == Empty || other == Byte; case Long -> other == Uninitialized || other == Empty || other == Byte || other == Int; + case ComplexPtr -> other == Uninitialized || other == Empty; + case InstPtr -> other == Uninitialized || other == Empty; default -> true; }; } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/SequenceStorageFactory.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/SequenceStorageFactory.java index a9ea0b1c10..bb095342aa 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/SequenceStorageFactory.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/SequenceStorageFactory.java @@ -58,6 +58,18 @@ public static SequenceStorage createStorage(Node inliningTarget, Object[] values } } + /** + * Like {@link #createStorage} but for lists only: all native-layout instances + * and/or None give a pointer-aware storage (tuples never get one). + */ + public static SequenceStorage createListStorage(Node inliningTarget, Object[] values) { + InstPtrSequenceStorage inst = InstPtrSequenceStorage.tryCreate(values, values.length, values.length); + if (inst != null) { + return inst; + } + return createStorage(inliningTarget, values); + } + private static boolean canSpecializeToInt(Node inliningTarget, Object[] values) { for (int i = 0; i < values.length; i++) { if (!(values[i] instanceof Integer)) { From 7b4bac9ba1ea74b4eee52b129292b9cf5e5de042 Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Sat, 28 Nov 2026 01:25:56 +0100 Subject: [PATCH 2/7] Pass exact str to C as a native CPython-layout copy An exact str that is a bare Java string (TruffleString) and that C gets as an argument or as a new reference is now a CPython 3.13 compact unicode object in malloc'd memory (PyASCIIObject or PyCompactUnicodeObject with the characters inline, kind chosen from the string's code range), with no PString wrapper, no stub and no handle. C reads it with CPython's own layout, so PyUnicode_GET_LENGTH, KIND, DATA, READ and PyUnicode_AsUTF8AndSize run without entering Java. PyObject_Hash (same value as Java's hash), PyUnicode_Compare, PyUnicode_CompareWithASCIIString and PyUnicode_EqualToUTF8AndSize have C paths for these objects, and PyUnicode_InternInPlace answers from a C cache of interned stubs. Strings created by C (PyUnicode_New, PyUnicode_FromStringAndSize, PyUnicode_FromString, PyUnicode_DecodeUTF8[Stateful] for valid input, PyUnicode_FromKindAndData) are born in that layout and become Java strings only when Java reads them. PyUnicode_Resize is implemented (it was not) and resizes an unshared native string in place. Identity: the struct's padding word holds a mark bit and an index into a 4096-entry ring that maps it to the Java string it was made from, so f(s) is s holds and a struct handed back to Java is not copied again. The same string passed twice in one call gets one struct. Lifetime: C's reference count owns the struct (unicode_dealloc frees it, or Java when it drops the last count). A borrowed or new-reference copy also holds one count on the borrowed stack until the outermost C call returns. Borrowed and new references to items a container holds (PyTuple_GetItem, PyList_GetItem, PyDict_GetItem*, ...Ref variants, PyCell_Get, items written into native storage, raw invoker calls) keep a stable PString stub as before. str subclasses and strings that are already PString objects take the existing path. GRAALPY_NATIVE_STR=0 turns the scheme off at C API initialization. __graalpython__.native_str_stats() reports live stubs and str counters. --- .../com.oracle.graal.python.cext/src/capi.c | 3 + .../com.oracle.graal.python.cext/src/object.c | 12 + .../src/unicodeobject.c | 714 ++++++++++++++++++ .../modules/GraalPythonModuleBuiltins.java | 32 + .../modules/cext/PythonCextDictBuiltins.java | 18 +- .../modules/cext/PythonCextFuncBuiltins.java | 4 +- .../modules/cext/PythonCextListBuiltins.java | 4 +- .../cext/PythonCextModuleBuiltins.java | 2 +- .../cext/PythonCextObjectBuiltins.java | 11 +- .../modules/cext/PythonCextSlotBuiltins.java | 2 +- .../modules/cext/PythonCextSysBuiltins.java | 2 +- .../modules/cext/PythonCextTupleBuiltins.java | 4 +- .../modules/cext/PythonCextTypeBuiltins.java | 2 +- .../cext/PythonCextUnicodeBuiltins.java | 31 +- .../objects/cext/capi/CApiFunction.java | 8 +- .../builtins/objects/cext/capi/CExtNodes.java | 24 +- .../cext/capi/ExternalFunctionNodes.java | 23 +- .../capi/transitions/CApiTransitions.java | 47 +- .../cext/capi/transitions/NativeStrNodes.java | 163 ++++ .../objects/cext/structs/CStructAccess.java | 4 +- .../objects/common/SequenceStorageNodes.java | 6 +- .../runtime/nativeaccess/NativeComplex.java | 18 +- .../runtime/nativeaccess/NativeStr.java | 283 +++++++ 23 files changed, 1372 insertions(+), 45 deletions(-) create mode 100644 graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/NativeStrNodes.java create mode 100644 graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java diff --git a/graalpython/com.oracle.graal.python.cext/src/capi.c b/graalpython/com.oracle.graal.python.cext/src/capi.c index 237dec845a..d6380d3b6e 100644 --- a/graalpython/com.oracle.graal.python.cext/src/capi.c +++ b/graalpython/com.oracle.graal.python.cext/src/capi.c @@ -278,6 +278,7 @@ Py_LOCAL_SYMBOL uint32_t Py_Truffle_Options; Py_LOCAL_SYMBOL void graalpy_init_complex_alloc(void); // complexobject.c Py_LOCAL_SYMBOL void graalpy_init_list_slots(void); // listobject.c Py_LOCAL_SYMBOL void graalpy_init_long_alloc(void); // longobject.c +Py_LOCAL_SYMBOL void graalpy_init_str(void); // unicodeobject.c Py_LOCAL_SYMBOL void graalpy_init_small_alloc(void); // obmalloc.c Py_LOCAL_SYMBOL void graalpy_init_dict_mirror(void); // dictobject.c @@ -609,6 +610,8 @@ PyAPI_FUNC(PyThreadState **) initialize_graal_capi(void **builtin_closures, GCSt graalpy_init_complex_alloc(); // GraalPy change: shared native allocator for exact int graalpy_init_long_alloc(); + // GraalPy change: native str values + graalpy_init_str(); // GraalPy change: small-block pool for PyObject_Malloc shared with Java (floats) graalpy_init_small_alloc(); // GraalPy change: PyDict_Next entry mirror ("Java ran" epoch) diff --git a/graalpython/com.oracle.graal.python.cext/src/object.c b/graalpython/com.oracle.graal.python.cext/src/object.c index 861f296a72..45db60bf46 100644 --- a/graalpython/com.oracle.graal.python.cext/src/object.c +++ b/graalpython/com.oracle.graal.python.cext/src/object.c @@ -1154,6 +1154,18 @@ PyObject_RichCompareBool(PyObject *v, PyObject *w, int op) return ok; } +// GraalPy change: native strs hash in C; everything else goes to the managed builtin +Py_LOCAL_SYMBOL int GraalPyPrivate_Str_HashIfNative(PyObject *op, Py_hash_t *hash); +Py_hash_t +PyObject_Hash(PyObject *v) +{ + Py_hash_t h; + if (GraalPyPrivate_Str_HashIfNative(v, &h)) { + return h; + } + return GraalPyPrivate_Object_Hash(v); +} + #if 0 // GraalPy change Py_hash_t PyObject_HashNotImplemented(PyObject *v) diff --git a/graalpython/com.oracle.graal.python.cext/src/unicodeobject.c b/graalpython/com.oracle.graal.python.cext/src/unicodeobject.c index e97eb3ad25..cf1f51f12f 100644 --- a/graalpython/com.oracle.graal.python.cext/src/unicodeobject.c +++ b/graalpython/com.oracle.graal.python.cext/src/unicodeobject.c @@ -290,6 +290,502 @@ static inline PyObject* unicode_get_empty(void) #endif // GraalPy change } +/* --------------------------------------------------------------------------------------------- + * GraalPy change: exact str values as native CPython-layout compact objects. + * + * An exact str that crosses into C (made by Java, NativeStr.java) or that C creates + * (PyUnicode_New, PyUnicode_FromStringAndSize, the UTF-8 decoder, PyUnicode_FromKindAndData) is a + * plain PyASCIIObject / PyCompactUnicodeObject with the characters inline, allocated with malloc, + * counted by C and freed by unicode_dealloc. It has no Java wrapper, no stub and no handle. The + * 4 bytes of padding after 'state' (offset 36) carry bit 31 as the mark of this scheme and, in the + * low bits, 1 + an index into Java's identity ring (0: none). Java reads such a struct into a + * TruffleString when it needs the value. + * ------------------------------------------------------------------------------------------- */ + +typedef struct { + PyTypeObject *type; /* @0: &PyUnicode_Type when the scheme is on, else NULL */ + int64_t counters[8]; /* @8: see NativeStr.COUNTER_NAMES */ +} GraalPyStrState; + +_Static_assert(sizeof(PyASCIIObject) == 40, "str layout"); +_Static_assert(sizeof(PyCompactUnicodeObject) == 56, "str layout"); +_Static_assert(offsetof(PyASCIIObject, state) == 32, "str layout"); +_Static_assert(offsetof(GraalPyStrState, counters) == 8, "str state layout"); + +#define GRAALPY_STR_MARK 0x80000000u +#define GRAALPY_STR_SLOT_MASK 0x7fffffffu +#define GRAALPY_STR_C_ALLOC 4 +#define GRAALPY_STR_C_FREE 5 + +static GraalPyStrState graalpy_str_state_dummy; +static GraalPyStrState *graalpy_str_state = &graalpy_str_state_dummy; + +static inline uint32_t * +graalpy_str_jslot(PyObject *op) +{ + return (uint32_t *) ((char *) op + 36); +} + +static inline int +graalpy_str_enabled(void) +{ + return graalpy_str_state->type != NULL; +} + +/* A str struct of this scheme (not a handle, exact, marked)? */ +static inline int +graalpy_str_is_native(PyObject *op) +{ + return !points_to_py_handle_space(op) && op->ob_type == &PyUnicode_Type && (*graalpy_str_jslot(op) & GRAALPY_STR_MARK); +} + +static inline void * +graalpy_str_data(PyObject *op) +{ + PyASCIIObject *a = (PyASCIIObject *) op; + return a->state.ascii ? (void *) (a + 1) : (void *) (((PyCompactUnicodeObject *) op) + 1); +} + +/* New str with count 1, header initialized and the NUL unit written; characters not written. */ +static PyObject * +graalpy_str_alloc(Py_ssize_t length, int kind, int ascii) +{ + size_t header = ascii ? sizeof(PyASCIIObject) : sizeof(PyCompactUnicodeObject); + /* a Java string holds at most INT32_MAX bytes of characters: same limit as the managed path */ + if (length < 0 || (size_t) length > (size_t) INT32_MAX / (size_t) kind - 1) { + return PyErr_NoMemory(); + } + char *p = (char *) malloc(header + ((size_t) length + 1) * (size_t) kind); + if (p == NULL) { + return PyErr_NoMemory(); + } + PyASCIIObject *a = (PyASCIIObject *) p; + ((PyObject *) p)->ob_refcnt = 1; + ((PyObject *) p)->ob_type = &PyUnicode_Type; + a->length = length; + a->hash = -1; + memset(&a->state, 0, sizeof(a->state)); + a->state.kind = kind; + a->state.compact = 1; + a->state.ascii = ascii ? 1 : 0; + *graalpy_str_jslot((PyObject *) p) = GRAALPY_STR_MARK; + if (!ascii) { + ((PyCompactUnicodeObject *) p)->utf8_length = 0; + ((PyCompactUnicodeObject *) p)->utf8 = NULL; + } + char *end = p + header + (size_t) length * kind; + memset(end, 0, kind); + graalpy_str_state->counters[GRAALPY_STR_C_ALLOC]++; + return (PyObject *) p; +} + +static void +graalpy_str_free(PyObject *op) +{ + if (!((PyASCIIObject *) op)->state.ascii) { + char *u8 = ((PyCompactUnicodeObject *) op)->utf8; + if (u8 != NULL) { + free(u8); + } + } + op->ob_type = NULL; + free(op); + graalpy_str_state->counters[GRAALPY_STR_C_FREE]++; +} + +/* Resizes a native str in place (caller checked unicode_modifiable); libc realloc, as allocated. */ +static PyObject * +graalpy_str_resize_inplace(PyObject *u, Py_ssize_t length) +{ + PyASCIIObject *a = (PyASCIIObject *) u; + int kind = a->state.kind; + size_t header = a->state.ascii ? sizeof(PyASCIIObject) : sizeof(PyCompactUnicodeObject); + if (length < 0 || (size_t) length > (size_t) INT32_MAX / (size_t) kind - 1) { + PyErr_NoMemory(); + return NULL; + } + if (!a->state.ascii && ((PyCompactUnicodeObject *) u)->utf8 != NULL) { + free(((PyCompactUnicodeObject *) u)->utf8); + ((PyCompactUnicodeObject *) u)->utf8 = NULL; + ((PyCompactUnicodeObject *) u)->utf8_length = 0; + } + char *n = (char *) realloc(u, header + ((size_t) length + 1) * kind); + if (n == NULL) { + PyErr_NoMemory(); + return NULL; + } + a = (PyASCIIObject *) n; + a->length = length; + a->hash = -1; + memset(n + header + (size_t) length * kind, 0, kind); + return (PyObject *) n; +} + +/* Hash equal to Java's str hash (TruffleString's hash of the UTF-32 code points, then GraalPy's + avoidNegative1), cached in the struct like CPython. */ +static Py_hash_t +graalpy_str_hash(PyObject *op) +{ + PyASCIIObject *a = (PyASCIIObject *) op; + if (a->hash != -1) { + return a->hash; + } + Py_ssize_t n = a->length; + /* A long string that Java still maps to its Java string: Java caches the hash there, so one + upcall is cheaper than hashing again for every fresh copy. */ + if (n >= 128 && (*graalpy_str_jslot(op) & GRAALPY_STR_SLOT_MASK) != 0) { + Py_hash_t jh = GraalPyPrivate_Object_Hash(op); + if (jh != -1) { + a->hash = jh; + return jh; + } + PyErr_Clear(); + } + uint32_t h = 0; + const void *data = graalpy_str_data(op); + /* h = 31*h + c, 8 characters per step with independent products (same value, shorter chain) */ +#define GRAALPY_HASH_LOOP(T) do { \ + const T *d = (const T *) data; Py_ssize_t i = 0; \ + for (; i + 8 <= n; i += 8) { \ + h = h * 0x94446F01u /* 31^8 mod 2^32 */ \ + + d[i] * 0x67E12CDFu + d[i + 1] * 0x34E63B41u + d[i + 2] * 0x01B4D89Fu /* 31^7..31^5 */ \ + + d[i + 3] * 0x000E1781u + d[i + 4] * 0x0000745Fu + d[i + 5] * 0x000003C1u /* 31^4..31^2 */ \ + + d[i + 6] * 31u + d[i + 7]; \ + } \ + for (; i < n; i++) h = 31 * h + d[i]; \ + } while (0) + switch (a->state.kind) { + case PyUnicode_1BYTE_KIND: + GRAALPY_HASH_LOOP(Py_UCS1); + break; + case PyUnicode_2BYTE_KIND: + GRAALPY_HASH_LOOP(Py_UCS2); + break; + default: + GRAALPY_HASH_LOOP(Py_UCS4); + break; + } +#undef GRAALPY_HASH_LOOP + int32_t hi = (int32_t) h; + if (hi == 0) { + hi = -1; /* TruffleString's MASKED_ZERO_HASH_CODE */ + } + Py_hash_t r = hi; + if (r == -1) { + r = -2; /* PyObjectHashNode.avoidNegative1 */ + } + a->hash = r; + return r; +} + +/* Code-point comparison of two native str structs (any kinds): <0, 0, >0. */ +static int +graalpy_str_compare(PyObject *x, PyObject *y) +{ + PyASCIIObject *a = (PyASCIIObject *) x, *b = (PyASCIIObject *) y; + Py_ssize_t n1 = a->length, n2 = b->length, n = n1 < n2 ? n1 : n2; + int k1 = a->state.kind, k2 = b->state.kind; + const void *d1 = graalpy_str_data(x), *d2 = graalpy_str_data(y); + if (k1 == 1 && k2 == 1) { + int c = memcmp(d1, d2, (size_t) n); + if (c != 0) { + return c < 0 ? -1 : 1; + } + } else { + for (Py_ssize_t i = 0; i < n; i++) { + Py_UCS4 c1 = PyUnicode_READ(k1, d1, i), c2 = PyUnicode_READ(k2, d2, i); + if (c1 != c2) { + return c1 < c2 ? -1 : 1; + } + } + } + return n1 < n2 ? -1 : n1 > n2 ? 1 : 0; +} + +/* Decodes strict UTF-8 into a new native str. Returns NULL with *invalid = 1 (no exception set) + if the input is not valid UTF-8 (lone surrogates included); NULL with an exception on memory + errors. */ +static PyObject * +graalpy_str_from_utf8(const char *s, Py_ssize_t size, int *invalid) +{ + const unsigned char *p = (const unsigned char *) s, *end = p + size; + *invalid = 0; + /* ASCII prefix, 8 bytes at a time */ + while (p + 8 <= end) { + uint64_t w; + memcpy(&w, p, 8); + if (w & 0x8080808080808080ULL) { + break; + } + p += 8; + } + while (p < end && *p < 0x80) { + p++; + } + if (p == end) { + PyObject *u = graalpy_str_alloc(size, 1, 1); + if (u != NULL && size > 0) { + memcpy(graalpy_str_data(u), s, (size_t) size); + } + return u; + } + /* validate the rest, count code points, find the max */ + Py_ssize_t n = (const char *) p - s; + Py_UCS4 maxchar = 0x7f; + const unsigned char *q = p; + while (q < end) { + unsigned int c = *q; + Py_UCS4 cp; + if (c < 0x80) { + q++; + n++; + continue; + } else if (c < 0xC2) { + goto bad; + } else if (c < 0xE0) { + if (end - q < 2 || (q[1] & 0xC0) != 0x80) goto bad; + cp = ((c & 0x1F) << 6) | (q[1] & 0x3F); + q += 2; + } else if (c < 0xF0) { + if (end - q < 3 || (q[1] & 0xC0) != 0x80 || (q[2] & 0xC0) != 0x80) goto bad; + if (c == 0xE0 && q[1] < 0xA0) goto bad; /* overlong */ + if (c == 0xED && q[1] >= 0xA0) goto bad; /* surrogate */ + cp = ((c & 0x0F) << 12) | ((q[1] & 0x3F) << 6) | (q[2] & 0x3F); + q += 3; + } else if (c < 0xF5) { + if (end - q < 4 || (q[1] & 0xC0) != 0x80 || (q[2] & 0xC0) != 0x80 || (q[3] & 0xC0) != 0x80) goto bad; + if (c == 0xF0 && q[1] < 0x90) goto bad; /* overlong */ + if (c == 0xF4 && q[1] >= 0x90) goto bad; /* > U+10FFFF */ + cp = ((c & 0x07) << 18) | ((q[1] & 0x3F) << 12) | ((q[2] & 0x3F) << 6) | (q[3] & 0x3F); + q += 4; + } else { + goto bad; + } + if (cp > maxchar) maxchar = cp; + n++; + } + { + int kind = maxchar < 256 ? 1 : maxchar < 65536 ? 2 : 4; + PyObject *u = graalpy_str_alloc(n, kind, 0); + if (u == NULL) { + return NULL; + } + void *data = graalpy_str_data(u); + Py_ssize_t i = 0; + q = (const unsigned char *) s; + while (q < end) { + unsigned int c = *q; + Py_UCS4 cp; + if (c < 0x80) { + cp = c; + q++; + } else if (c < 0xE0) { + cp = ((c & 0x1F) << 6) | (q[1] & 0x3F); + q += 2; + } else if (c < 0xF0) { + cp = ((c & 0x0F) << 12) | ((q[1] & 0x3F) << 6) | (q[2] & 0x3F); + q += 3; + } else { + cp = ((c & 0x07) << 18) | ((q[1] & 0x3F) << 12) | ((q[2] & 0x3F) << 6) | (q[3] & 0x3F); + q += 4; + } + PyUnicode_WRITE(kind, data, i, cp); + i++; + } + return u; + } +bad: + *invalid = 1; + return NULL; +} + +/* New native str from kind data; picks the smallest kind like CPython. */ +static PyObject * +graalpy_str_from_kind(int kind, const void *buf, Py_ssize_t size) +{ + Py_UCS4 maxchar = 0; + for (Py_ssize_t i = 0; i < size; i++) { + Py_UCS4 c = PyUnicode_READ(kind, buf, i); + if (c > maxchar) maxchar = c; + } + if (maxchar > MAX_UNICODE) { + PyErr_SetString(PyExc_ValueError, "character is not in range [U+0000; U+10ffff]"); + return NULL; + } + int k = maxchar < 256 ? 1 : maxchar < 65536 ? 2 : 4; + PyObject *u = graalpy_str_alloc(size, k, maxchar < 128); + if (u == NULL) { + return NULL; + } + void *data = graalpy_str_data(u); + if (k == kind) { + memcpy(data, buf, (size_t) size * kind); + } else { + for (Py_ssize_t i = 0; i < size; i++) { + PyUnicode_WRITE(k, data, i, PyUnicode_READ(kind, buf, i)); + } + } + return u; +} + +/* Fills the UTF-8 cache of a native non-ASCII str. -1 with an exception for lone surrogates. */ +static int +graalpy_str_fill_utf8(PyObject *op) +{ + PyCompactUnicodeObject *c = (PyCompactUnicodeObject *) op; + Py_ssize_t n = c->_base.length; + int kind = c->_base.state.kind; + const void *data = graalpy_str_data(op); + size_t len = 0; + for (Py_ssize_t i = 0; i < n; i++) { + Py_UCS4 ch = PyUnicode_READ(kind, data, i); + if (ch < 0x80) { + len += 1; + } else if (ch < 0x800) { + len += 2; + } else if (ch < 0x10000) { + if (Py_UNICODE_IS_SURROGATE(ch)) { + /* let the managed encoder raise the proper UnicodeEncodeError */ + PyObject *r = PyUnicode_AsUTF8String(op); + Py_XDECREF(r); + if (!PyErr_Occurred()) { + PyErr_SetString(PyExc_UnicodeEncodeError, "surrogates not allowed"); + } + return -1; + } + len += 3; + } else { + len += 4; + } + } + char *u8 = (char *) malloc(len + 1); + if (u8 == NULL) { + PyErr_NoMemory(); + return -1; + } + char *w = u8; + for (Py_ssize_t i = 0; i < n; i++) { + Py_UCS4 ch = PyUnicode_READ(kind, data, i); + if (ch < 0x80) { + *w++ = (char) ch; + } else if (ch < 0x800) { + *w++ = (char) (0xc0 | (ch >> 6)); + *w++ = (char) (0x80 | (ch & 0x3f)); + } else if (ch < 0x10000) { + *w++ = (char) (0xe0 | (ch >> 12)); + *w++ = (char) (0x80 | ((ch >> 6) & 0x3f)); + *w++ = (char) (0x80 | (ch & 0x3f)); + } else { + *w++ = (char) (0xf0 | (ch >> 18)); + *w++ = (char) (0x80 | ((ch >> 12) & 0x3f)); + *w++ = (char) (0x80 | ((ch >> 6) & 0x3f)); + *w++ = (char) (0x80 | (ch & 0x3f)); + } + } + *w = 0; + c->utf8 = u8; + c->utf8_length = (Py_ssize_t) len; + return 0; +} + +/* For object.c: the hash of a native str, computed in C; 0 if op is not one. */ +Py_LOCAL_SYMBOL int +GraalPyPrivate_Str_HashIfNative(PyObject *op, Py_hash_t *hash) +{ + if (graalpy_str_is_native(op)) { + *hash = graalpy_str_hash(op); + return 1; + } + return 0; +} + +/* Equality of a native str with any exact str (a handle-space stub included), by code points. */ +static int +graalpy_str_equal_any(PyObject *x, PyObject *y) +{ + Py_ssize_t n = PyUnicode_GET_LENGTH(x); + if (n != PyUnicode_GET_LENGTH(y)) { + return 0; + } + int k1 = PyUnicode_KIND(x), k2 = PyUnicode_KIND(y); + const void *d1 = PyUnicode_DATA(x), *d2 = PyUnicode_DATA(y); + if (k1 == k2) { + return memcmp(d1, d2, (size_t) n * k1) == 0; + } + for (Py_ssize_t i = 0; i < n; i++) { + if (PyUnicode_READ(k1, d1, i) != PyUnicode_READ(k2, d2, i)) { + return 0; + } + } + return 1; +} + +#define GRAALPY_INTERN_CACHE 4096 +typedef struct { + Py_hash_t hash; + PyObject *obj; /* owned reference to the interned object */ +} GraalPyInternEntry; +static GraalPyInternEntry graalpy_intern_cache[GRAALPY_INTERN_CACHE]; + +static destructor graalpy_unicode_orig_dealloc; +static hashfunc graalpy_unicode_orig_hash; + +static void +graalpy_unicode_dealloc(PyObject *op) +{ + if (graalpy_str_is_native(op)) { + graalpy_str_free(op); + return; + } + if (graalpy_unicode_orig_dealloc != NULL) { + graalpy_unicode_orig_dealloc(op); + } +} + +static Py_hash_t +graalpy_unicode_hash_slot(PyObject *op) +{ + if (graalpy_str_is_native(op)) { + return graalpy_str_hash(op); + } + return graalpy_unicode_orig_hash(op); +} + +/* Called from capi.c after the builtin types are initialized. GRAALPY_NATIVE_STR=0 turns the + scheme off (Java then sees no type pointer and keeps the stub path). */ +Py_LOCAL_SYMBOL void +graalpy_init_str(void) +{ + graalpy_str_state = (GraalPyStrState *) GraalPyPrivate_Str_State(); + const char *env = getenv("GRAALPY_NATIVE_STR"); + if (env != NULL && env[0] == '0') { + graalpy_str_state->type = NULL; + return; + } + /* NativeStr.java writes the state word as an int: check the bitfield order agrees */ + PyASCIIObject probe; + memset(&probe, 0, sizeof(probe)); + probe.state.kind = 2; + probe.state.compact = 1; + probe.state.ascii = 1; + uint32_t word; + memcpy(&word, &probe.state, 4); + if (word != ((2u << 2) | (1u << 5) | (1u << 6))) { + fprintf(stderr, "GraalPy: native str disabled, unexpected state bit layout 0x%x\n", word); + graalpy_str_state->type = NULL; + return; + } + graalpy_unicode_orig_dealloc = PyUnicode_Type.tp_dealloc; + PyUnicode_Type.tp_dealloc = graalpy_unicode_dealloc; + graalpy_unicode_orig_hash = PyUnicode_Type.tp_hash; + if (graalpy_unicode_orig_hash != NULL) { + PyUnicode_Type.tp_hash = graalpy_unicode_hash_slot; + } + graalpy_str_state->type = &PyUnicode_Type; +} +/* ------------------------------------------------------------------ end of native str block */ + + #if 0 // GraalPy change /* This dictionary holds per-interpreter interned strings. * See InternalDocs/string_interning.md for details. @@ -1217,6 +1713,10 @@ resize_compact(PyObject *unicode, Py_ssize_t length) return copy; } assert(PyUnicode_IS_COMPACT(unicode)); + // GraalPy change: native strs come from libc malloc + if (graalpy_str_is_native(unicode)) { + return graalpy_str_resize_inplace(unicode, length); + } char_size = PyUnicode_KIND(unicode); if (PyUnicode_IS_ASCII(unicode)) @@ -1474,6 +1974,10 @@ PyUnicode_New(Py_ssize_t size, Py_UCS4 maxchar) return NULL; } + // GraalPy change: born native + if (graalpy_str_enabled()) { + return graalpy_str_alloc(size, kind, is_ascii); + } return GraalPyPrivate_Unicode_New(size, kind, is_ascii); } @@ -1898,6 +2402,9 @@ unicode_modifiable(PyObject *unicode) // GraalPy change if (points_to_py_handle_space(unicode) && Py_REFCNT(unicode) != MANAGED_REFCNT) // GraalPy change return GraalPyPrivate_Unicode_IsMaterialized(unicode) == 0; + // GraalPy change: a native str Java has seen may be mapped to a Java string + if (graalpy_str_is_native(unicode) && (*graalpy_str_jslot(unicode) & GRAALPY_STR_SLOT_MASK) != 0) + return 0; if (!_PyObject_IsUniquelyReferenced(unicode)) return 0; if (PyUnicode_HASH(unicode) != -1) @@ -1913,6 +2420,46 @@ unicode_modifiable(PyObject *unicode) return 1; } +// GraalPy change: PyUnicode_Resize (was not implemented): a native str that nothing else +// can see is resized in place; anything else is copied into a new string. +int +PyUnicode_Resize(PyObject **p_unicode, Py_ssize_t length) +{ + if (p_unicode == NULL) { + PyErr_BadInternalCall(); + return -1; + } + PyObject *u = *p_unicode; + if (u == NULL || !PyUnicode_Check(u) || length < 0) { + PyErr_BadInternalCall(); + return -1; + } + Py_ssize_t old = PyUnicode_GET_LENGTH(u); + if (old == length) { + return 0; + } + if (graalpy_str_is_native(u) && unicode_modifiable(u)) { + PyObject *n = graalpy_str_resize_inplace(u, length); + if (n == NULL) { + return -1; + } + *p_unicode = n; + return 0; + } + PyObject *c = PyUnicode_New(length, PyUnicode_MAX_CHAR_VALUE(u)); + if (c == NULL) { + return -1; + } + int k1 = PyUnicode_KIND(u), k2 = PyUnicode_KIND(c); + const void *d1 = PyUnicode_DATA(u); + void *d2 = PyUnicode_DATA(c); + for (Py_ssize_t i = 0; i < old && i < length; i++) { + PyUnicode_WRITE(k2, d2, i, PyUnicode_READ(k1, d1, i)); + } + Py_SETREF(*p_unicode, c); + return 0; +} + #if 0 // GraalPy change static int unicode_resize(PyObject **p_unicode, Py_ssize_t length) @@ -2154,6 +2701,14 @@ PyUnicode_FromStringAndSize(const char *u, Py_ssize_t size) return NULL; } if (u != NULL) { + // GraalPy change: decode valid UTF-8 natively; invalid input takes the managed path (errors) + if (graalpy_str_enabled()) { + int invalid; + PyObject *r = graalpy_str_from_utf8(u, size, &invalid); + if (r != NULL || !invalid) { + return r; + } + } // GraalPy change: decode through the managed Unicode implementation. return GraalPyPrivate_Unicode_FromUTF((void*) u, size, 1); } @@ -2179,6 +2734,21 @@ PyUnicode_FromString(const char *u) #endif +// GraalPy change: C implementation (was a managed builtin) +PyObject * +PyUnicode_FromString(const char *u) +{ + if (graalpy_str_enabled()) { + size_t size = strlen(u); + int invalid; + PyObject *r = graalpy_str_from_utf8(u, (Py_ssize_t) size, &invalid); + if (r != NULL || !invalid) { + return r; + } + } + return GraalPyPrivate_Unicode_FromString(u); +} + PyObject * _PyUnicode_FromId(_Py_Identifier *id) { @@ -2255,6 +2825,10 @@ kind_maxchar_limit(int kind) static PyObject* _PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size) { + // GraalPy change + if (graalpy_str_enabled()) { + return graalpy_str_from_kind(PyUnicode_1BYTE_KIND, u, size); + } // GraalPy change: different implementation return GraalPyPrivate_Unicode_FromUCS((int8_t *)u, size, PyUnicode_1BYTE_KIND); } @@ -2262,6 +2836,10 @@ _PyUnicode_FromUCS1(const Py_UCS1* u, Py_ssize_t size) static PyObject* _PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size) { + // GraalPy change + if (graalpy_str_enabled()) { + return graalpy_str_from_kind(PyUnicode_2BYTE_KIND, u, size); + } // GraalPy change: different implementation const Py_ssize_t byte_size = size * PyUnicode_2BYTE_KIND; return GraalPyPrivate_Unicode_FromUCS((int8_t *)u, byte_size, PyUnicode_2BYTE_KIND); @@ -2270,6 +2848,10 @@ _PyUnicode_FromUCS2(const Py_UCS2 *u, Py_ssize_t size) static PyObject* _PyUnicode_FromUCS4(const Py_UCS4 *u, Py_ssize_t size) { + // GraalPy change + if (graalpy_str_enabled()) { + return graalpy_str_from_kind(PyUnicode_4BYTE_KIND, u, size); + } // GraalPy change: different implementation const Py_ssize_t byte_size = size * PyUnicode_4BYTE_KIND; return GraalPyPrivate_Unicode_FromUCS((int8_t *)u, byte_size, PyUnicode_4BYTE_KIND); @@ -4000,6 +4582,15 @@ PyUnicode_AsUTF8AndSize(PyObject *unicode, Py_ssize_t *psize) } if (PyUnicode_UTF8(unicode) == NULL) { + // GraalPy change: native strs encode in C + if (graalpy_str_is_native(unicode)) { + if (graalpy_str_fill_utf8(unicode) == -1) { + if (psize) { + *psize = -1; + } + return NULL; + } + } else // GraalPy change: upcall if (GraalPyPrivate_Unicode_FillUtf8(unicode) == -1) { if (psize) { @@ -5011,6 +5602,17 @@ PyUnicode_DecodeUTF8Stateful(const char *s, const char *errors, Py_ssize_t *consumed) { + // GraalPy change: valid UTF-8 is decoded natively (any error handler: none is used) + if (graalpy_str_enabled() && size >= 0) { + int invalid; + PyObject *r = graalpy_str_from_utf8(s, size, &invalid); + if (r != NULL || !invalid) { + if (r != NULL && consumed != NULL) { + *consumed = size; + } + return r; + } + } // GraalPy change: different implementation PyObject* result = GraalPyPrivate_Unicode_DecodeUTF8Stateful( (void*) s, size, @@ -10580,6 +11182,94 @@ PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str) } #endif // GraalPy change +// GraalPy change: C implementations for native strs; others go to the managed builtins +int +PyUnicode_Compare(PyObject *left, PyObject *right) +{ + if (graalpy_str_is_native(left) && graalpy_str_is_native(right)) { + return graalpy_str_compare(left, right); + } + return GraalPyPrivate_Unicode_Compare(left, right); +} + +int +PyUnicode_CompareWithASCIIString(PyObject* uni, const char* str) +{ + if (!graalpy_str_is_native(uni)) { + return GraalPyPrivate_Unicode_CompareWithASCIIString(uni, str); + } + Py_ssize_t i; + int kind = ((PyASCIIObject *) uni)->state.kind; + const void *data = graalpy_str_data(uni); + Py_ssize_t len1 = ((PyASCIIObject *) uni)->length; + Py_UCS4 chr = 0; + if (kind == PyUnicode_1BYTE_KIND) { + size_t len, len2 = strlen(str); + int cmp; + len = Py_MIN((size_t) len1, len2); + cmp = memcmp(data, str, len); + if (cmp != 0) { + return cmp < 0 ? -1 : 1; + } + if ((size_t) len1 > len2) + return 1; + if ((size_t) len1 < len2) + return -1; + return 0; + } + for (i = 0; i < len1 && (chr = PyUnicode_READ(kind, data, i)) && str[i]; i++) + if (chr != (unsigned char)str[i]) + return (chr < (unsigned char)(str[i])) ? -1 : 1; + if (len1 != i || (i < len1 && chr)) + return 1; + if (str[i]) + return -1; + return 0; +} + +int +PyUnicode_EqualToUTF8AndSize(PyObject *unicode, const char *str, Py_ssize_t size) +{ + if (!graalpy_str_is_native(unicode)) { + return GraalPyPrivate_Unicode_EqualToUTF8AndSize(unicode, str, size); + } + PyASCIIObject *a = (PyASCIIObject *) unicode; + Py_ssize_t len = a->length; + if (a->state.ascii) { + return size == len && memcmp(graalpy_str_data(unicode), str, len) == 0; + } + PyCompactUnicodeObject *c = (PyCompactUnicodeObject *) unicode; + if (c->utf8 != NULL) { + return size == c->utf8_length && memcmp(c->utf8, str, size) == 0; + } + if (size < 0 || (size_t)len >= (size_t)size || (size_t)len < (size_t)size / 4) { + return 0; + } + const unsigned char *s = (const unsigned char *)str; + const unsigned char *ends = s + (size_t)size; + int kind = a->state.kind; + const void *data = graalpy_str_data(unicode); + for (Py_ssize_t i = 0; i < len; i++) { + Py_UCS4 ch = PyUnicode_READ(kind, data, i); + if (ch < 0x80) { + if (ends == s || s[0] != ch) return 0; + s += 1; + } else if (ch < 0x800) { + if ((ends - s) < 2 || s[0] != (0xc0 | (ch >> 6)) || s[1] != (0x80 | (ch & 0x3f))) return 0; + s += 2; + } else if (ch < 0x10000) { + if (Py_UNICODE_IS_SURROGATE(ch) || (ends - s) < 3 || s[0] != (0xe0 | (ch >> 12)) || + s[1] != (0x80 | ((ch >> 6) & 0x3f)) || s[2] != (0x80 | (ch & 0x3f))) return 0; + s += 3; + } else { + if ((ends - s) < 4 || s[0] != (0xf0 | (ch >> 18)) || s[1] != (0x80 | ((ch >> 12) & 0x3f)) || + s[2] != (0x80 | ((ch >> 6) & 0x3f)) || s[3] != (0x80 | (ch & 0x3f))) return 0; + s += 4; + } + } + return s == ends; +} + int PyUnicode_EqualToUTF8(PyObject *unicode, const char *str) { @@ -14707,6 +15397,30 @@ _PyUnicode_InternStatic(PyInterpreterState *interp, PyObject **p) return; } + // GraalPy change: interning a native str is answered from a C cache of interned + // objects (each entry owns a reference) when possible; only a miss asks the managed side + if (graalpy_str_is_native(s)) { + Py_hash_t h = graalpy_str_hash(s); + GraalPyInternEntry *e = &graalpy_intern_cache[(size_t) h & (GRAALPY_INTERN_CACHE - 1)]; + if (e->obj != NULL && e->hash == h && graalpy_str_equal_any(e->obj, s)) { + Py_INCREF(e->obj); + *p = e->obj; + Py_DECREF(s); + return; + } + PyObject *t = GraalPyPrivate_Unicode_LookupAndIntern(s); + if (t == NULL) { + return; /* keep s (not interned); the caller still owns it */ + } + if (t != s) { + Py_INCREF(t); + Py_XSETREF(e->obj, t); + e->hash = h; + *p = t; + } + Py_DECREF(s); + return; + } PyObject *t = GraalPyPrivate_Unicode_LookupAndIntern(s); #if 0 // GraalPy change // This should only be called as part of runtime initialization diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/GraalPythonModuleBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/GraalPythonModuleBuiltins.java index b4eef0296a..c20e20c46c 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/GraalPythonModuleBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/GraalPythonModuleBuiltins.java @@ -1452,6 +1452,38 @@ Object get(Object reset) { } } + @Builtin(name = "native_str_stats", minNumOfPositionalArgs = 0, maxNumOfPositionalArgs = 0, doc = "Measurement only: ((name, value), ...): " + + "live_stubs (occupied native stub table entries) and the native str counters (counts need -Dgraalpy.complexCounters=true).") + @GenerateNodeFactory + public abstract static class NativeStrStatsNode extends PythonBuiltinNode { + + @Specialization + @TruffleBoundary + static Object get() { + PythonContext ctx = PythonContext.get(null); + long live = 0; + var lookup = ctx.handleContext == null ? null : ctx.handleContext.nativeStubLookup; + if (lookup != null) { + for (Object o : lookup) { + if (o != null) { + live++; + } + } + } + long st = ctx.peekNativeComplexState(); + long[] counts = com.oracle.graal.python.runtime.nativeaccess.NativeStr.snapshot(st, false); + String[] names = com.oracle.graal.python.runtime.nativeaccess.NativeStr.COUNTER_NAMES; + PythonLanguage language = PythonLanguage.get(null); + Object[] result = new Object[counts.length + 2]; + result[0] = PFactory.createTuple(language, new Object[]{toTruffleStringUncached("live_stubs"), live}); + result[1] = PFactory.createTuple(language, new Object[]{toTruffleStringUncached("str_enabled"), com.oracle.graal.python.runtime.nativeaccess.NativeStr.getStrType(st) != 0}); + for (int i = 0; i < counts.length; i++) { + result[i + 2] = PFactory.createTuple(language, new Object[]{toTruffleStringUncached(names[i]), counts[i]}); + } + return PFactory.createTuple(language, result); + } + } + @Builtin(name = "native_long_live", minNumOfPositionalArgs = 0, maxNumOfPositionalArgs = 0, doc = "Measurement only: number of native int structs " + "currently allocated by the shared allocator (0 before the C API is initialized).") @GenerateNodeFactory diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextDictBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextDictBuiltins.java index 599ffabb38..9c0563e38b 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextDictBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextDictBuiltins.java @@ -340,7 +340,7 @@ static Object promoteForBorrow(PythonContext context, EnsurePythonObjectNode ens } else if (o instanceof Double d && !com.oracle.graal.python.builtins.objects.floats.PFloat.fitsInFloat(d)) { return PFactory.createFloat(context.getLanguage(), d); } - return ensureNode.execute(context, o, false); + return com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, o, false)); } /** @@ -462,7 +462,7 @@ static Object doPDict(Node inliningTarget, PDict dict, Object key, noResultProfile.enter(inliningTarget); return NATIVE_NULL; } - Object promotedValue = ensureNode.execute(context, res, false); + Object promotedValue = com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, res, false)); if (promotedValue != res) { setItemNode.execute(null, inliningTarget, dict, key, promotedValue); return promotedValue; @@ -510,7 +510,7 @@ static Object doPDict(Node inliningTarget, PDict dict, Object key, noResultProfile.enter(inliningTarget); return NATIVE_NULL; } - Object promotedValue = ensureNode.execute(context, res, false); + Object promotedValue = com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, res, false)); if (promotedValue != res) { setItemNode.execute(null, inliningTarget, dict, key, promotedValue); return promotedValue; @@ -553,7 +553,7 @@ static int getItem(PDict dict, Object key, long resultPtr, * This is sad, but code out there still likes to assume that anything they get from the dictionary * is kept alive by the dictionary. CPython itself does that in getargs.c. */ - Object promotedValue = ensureNode.execute(context, value, false); + Object promotedValue = com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, value, false)); if (promotedValue != value) { setItemNode.execute(null, inliningTarget, dict, key, promotedValue); } @@ -593,7 +593,7 @@ static int getItemString(PDict dict, long keyPtr, long resultPtr, Object value = getItem.execute(null, inliningTarget, dict.getDictStorage(), key); // See PyDict_GetItemRef if (value != null) { - Object promotedValue = ensureNode.execute(context, value, false); + Object promotedValue = com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, value, false)); if (promotedValue != value) { setItemNode.execute(null, inliningTarget, dict, key, promotedValue); } @@ -634,7 +634,7 @@ static int pop(PDict dict, long keyPtr, long resultPtr, return 0; } if (resultPtr != NULLPTR) { - result = toNativeNode.executeNewRef(inliningTarget, ensureNode.execute(context, value, false)); + result = toNativeNode.executeNewRef(inliningTarget, com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, value, false))); } return 1; } finally { @@ -744,7 +744,7 @@ static Object setItem(PDict dict, Object key, Object value, @Cached EnsurePythonObjectNode ensureNode, @Cached SetItemNode setItemNode) { Object result = setDefault.execute(null, inliningTarget, dict, key, value); - Object promotedValue = ensureNode.execute(context, result, false); + Object promotedValue = com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, result, false)); if (promotedValue != result) { setItemNode.execute(null, inliningTarget, dict, key, promotedValue); return promotedValue; @@ -777,12 +777,12 @@ static int setDefault(PDict dict, Object key, Object defaultValue, long resultPt long hash = hashNode.execute(null, inliningTarget, key); Object value = getItemNode.execute(null, inliningTarget, storage, key, hash); if (value != null) { - result = toNativeNode.executeNewRef(inliningTarget, ensureNode.execute(context, value, false)); + result = toNativeNode.executeNewRef(inliningTarget, com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, value, false))); return 1; } HashingStorage newStorage = setItemNode.execute(null, inliningTarget, storage, key, hash, defaultValue); updateStorageNode.execute(inliningTarget, dict, storage, newStorage); - result = toNativeNode.executeNewRef(inliningTarget, ensureNode.execute(context, defaultValue, false)); + result = toNativeNode.executeNewRef(inliningTarget, com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, defaultValue, false))); return 0; } finally { if (resultPtr != NULLPTR) { diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextFuncBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextFuncBuiltins.java index b34c65b828..79e77420b1 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextFuncBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextFuncBuiltins.java @@ -98,7 +98,7 @@ private static Object getPromotedCellRef(long cellPtr) { if (ref == null) { return null; } - Object promotedRef = EnsurePythonObjectNode.executeUncached(PythonContext.get(null), ref, false); + Object promotedRef = EnsurePythonObjectNode.promoteBorrowedString(PythonContext.get(null), EnsurePythonObjectNode.executeUncached(PythonContext.get(null), ref, false)); if (promotedRef != ref) { cell.setRef(promotedRef); } @@ -220,7 +220,7 @@ static long GraalPyFunction_GET_MODULE(long functionPtr) { module = PNone.NONE; } } - Object promotedModule = EnsurePythonObjectNode.executeUncached(PythonContext.get(null), module, false); + Object promotedModule = EnsurePythonObjectNode.promoteBorrowedString(PythonContext.get(null), EnsurePythonObjectNode.executeUncached(PythonContext.get(null), module, false)); WriteAttributeToObjectNode.getUncached().execute(function, T___MODULE__, promotedModule); return ToNativeBorrowedNode.executeUncached(promotedModule); } 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 b0cc771c10..f0d70493f7 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 @@ -148,7 +148,7 @@ static Object doPList(PList list, long key, throw raiseNode.raise(inliningTarget, IndexError, ErrorMessages.LIST_INDEX_OUT_OF_RANGE); } Object result = getItemNode.execute(inliningTarget, sequenceStorage, (int) key); - Object promotedValue = ensureNode.execute(context, result, false); + Object promotedValue = com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, result, false)); if (promotedValue != result) { sequenceStorage = generalizationNode.execute(inliningTarget, sequenceStorage, promotedValue); list.setSequenceStorage(sequenceStorage); @@ -181,7 +181,7 @@ static long PyList_GetItemRef(long opPtr, long key) { } Object result = GetItemScalarNode.executeUncached(sequenceStorage, (int) key); // See the note in PyDict_GetItemRef - Object promotedValue = EnsurePythonObjectNode.executeUncached(PythonContext.get(null), result, false); + Object promotedValue = EnsurePythonObjectNode.promoteBorrowedString(PythonContext.get(null), EnsurePythonObjectNode.executeUncached(PythonContext.get(null), result, false)); if (promotedValue != result) { sequenceStorage = ListGeneralizationNode.executeUncached(sequenceStorage, promotedValue); list.setSequenceStorage(sequenceStorage); diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextModuleBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextModuleBuiltins.java index 768443c15b..a07411c50f 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextModuleBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextModuleBuiltins.java @@ -202,7 +202,7 @@ static Object getName(PythonModule module, CompilerDirectives.transferToInterpreterAndInvalidate(); throw PRaiseNode.raiseStatic(inliningTarget, SystemError, ErrorMessages.NAMELESS_MODULE); } - Object promotedName = ensureNode.execute(context, nameAttr, false); + Object promotedName = com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, nameAttr, false)); if (promotedName == nameAttr) { return nameAttr; } else { diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextObjectBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextObjectBuiltins.java index 0f6bdf9070..52097dd3c3 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextObjectBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextObjectBuiltins.java @@ -571,7 +571,7 @@ static int getOptionalAttr(Object obj, Object attr, long resultPointer, if (value == PNone.NO_VALUE) { return 0; } - result = toNativeNode.executeNewRef(inliningTarget, ensureNode.execute(context, value, false)); + result = toNativeNode.executeNewRef(inliningTarget, com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, value, false))); return 1; } finally { writePtr(resultPointer, result); @@ -598,7 +598,7 @@ static int getMethod(Object receiver, TruffleString name, long resultPointer, result = ((BoundDescriptor) result).descriptor; } resultPointerValue = toNativeNode.executeNewRef(inliningTarget, - ensureNode.execute(context, result, false)); + com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, result, false))); return isBound ? 0 : 1; } finally { writePtr(resultPointer, resultPointerValue); @@ -623,7 +623,7 @@ static int getOptionalAttr(Object obj, long attrPointer, long resultPointer, if (value == PNone.NO_VALUE) { return 0; } - result = toNativeNode.executeNewRef(inliningTarget, ensureNode.execute(context, value, false)); + result = toNativeNode.executeNewRef(inliningTarget, com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, value, false))); return 1; } finally { writePtr(resultPointer, result); @@ -853,8 +853,9 @@ static long GraalPyPrivate_Object_GetIter(long objectPtr) { * Moving this to pure C is much faster (100x) for true native tp_hash, but hashing managed * objects (e.g. Strings) regresses (also by ~100x). */ - @CApiBuiltin(ret = Py_hash_t, args = {PyObject}, call = Direct, retConversion = long.class, argConversions = {NativeToPythonNode.class}) - abstract static class PyObject_Hash extends CApiUnaryBuiltinNode { + // PyObject_Hash is in C (native strs hash there); this is its path for everything else + @CApiBuiltin(ret = Py_hash_t, args = {PyObject}, call = Ignored, retConversion = long.class, argConversions = {NativeToPythonNode.class}) + abstract static class GraalPyPrivate_Object_Hash extends CApiUnaryBuiltinNode { @Specialization static long hash(Object object, @Bind Node inliningTarget, diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextSlotBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextSlotBuiltins.java index b8f2505f69..76bcb3c141 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextSlotBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextSlotBuiltins.java @@ -523,7 +523,7 @@ static Object get(Node inliningTarget, PSlice object, HiddenAttr key, Object val @Cached CExtNodes.EnsurePythonObjectNode ensureNode) { Object promotedValue = read.execute(inliningTarget, object, key, null); if (promotedValue == null) { - promotedValue = ensureNode.execute(context, value, false); + promotedValue = com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, value, false)); if (promotedValue == value) { return value; } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextSysBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextSysBuiltins.java index fa55e4b314..6de5126e83 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextSysBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextSysBuiltins.java @@ -92,7 +92,7 @@ Object getObject(TruffleString name, if (value == PNone.NO_VALUE) { return NATIVE_NULL; } - Object promotedValue = ensureNode.execute(context, value, false); + Object promotedValue = com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, value, false)); if (promotedValue != value) { setAttrNode.execute(inliningTarget, sys, name, promotedValue); return promotedValue; diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextTupleBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextTupleBuiltins.java index 3d4e84c44d..d429214626 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextTupleBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextTupleBuiltins.java @@ -109,7 +109,7 @@ static Object doPTuple(PTuple tuple, long key, int index = checkIndex(inliningTarget, key, sequenceStorage, raiseNode); Object result = getItemNode.execute(inliningTarget, sequenceStorage, index); assert result != null : "tuple must not contain Java null"; - Object promotedValue = ensureNode.execute(context, result, false); + Object promotedValue = com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, result, false)); if (promotedValue != result) { sequenceStorage = generalizationNode.execute(inliningTarget, sequenceStorage, promotedValue); tuple.setSequenceStorage(sequenceStorage); @@ -133,7 +133,7 @@ static Object doNative(PythonAbstractNativeObject tuple, long key, if (result == null) { return NATIVE_NULL; } - Object promotedValue = ensureNode.execute(context, result, false); + Object promotedValue = com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, result, false)); if (promotedValue != result) { setItemNode.execute(inliningTarget, sequenceStorage, index, promotedValue); return promotedValue; diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextTypeBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextTypeBuiltins.java index 28471b9db8..1a385fa757 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextTypeBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextTypeBuiltins.java @@ -179,7 +179,7 @@ Object doGeneric(Object type, Object name, value = getItem.execute(null, inliningTarget, dict, key); } if (value != null && value != PNone.NO_VALUE) { - Object promoted = ensureNode.execute(context, value, false); + Object promoted = com.oracle.graal.python.builtins.objects.cext.capi.CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(context, ensureNode.execute(context, value, false)); if (promoted != value) { if (dict == null) { putNode.execute((PythonManagedClass) cls, key, promoted); diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextUnicodeBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextUnicodeBuiltins.java index 6993912164..f29a1fcea1 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextUnicodeBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextUnicodeBuiltins.java @@ -233,8 +233,9 @@ static Object chr(int value, } } - @CApiBuiltin(ret = PyObject, args = {ConstCharPtr}, call = Direct, retConversion = PythonToNativeNewRefNode.class, argConversions = {CharPtrToPythonStrictNode.class}) - abstract static class PyUnicode_FromString extends CApiUnaryBuiltinNode { + // PyUnicode_FromString is implemented in C; this is its fallback for invalid UTF-8 + @CApiBuiltin(ret = PyObject, args = {ConstCharPtr}, call = Ignored, retConversion = PythonToNativeNewRefNode.class, argConversions = {CharPtrToPythonStrictNode.class}) + abstract static class GraalPyPrivate_Unicode_FromString extends CApiUnaryBuiltinNode { @Specialization static TruffleString fromString(TruffleString value) { return value; @@ -360,6 +361,10 @@ static long GraalPyPrivate_Unicode_LookupAndIntern(long objPtr) { CApiTiming.enter(); try { Object obj = NativeToPythonInternalNode.executeUncached(objPtr, false); + if (obj instanceof TruffleString ts) { + // A native str struct; the interned object is a (stable) PString stub + obj = PFactory.createString(PythonLanguage.get(null), ts); + } if (obj instanceof PString str) { if (!PGuards.isBuiltinPString(str)) { return NULLPTR; @@ -640,8 +645,9 @@ static Object compare(Object left, Object right, private static final CApiTiming TIMING_PYUNICODE_COMPAREWITHASCIISTRING = CApiTiming.create(false, "PyUnicode_CompareWithASCIIString"); - @CApiBuiltin(ret = Int, args = {PyObject, ConstCharPtr}, call = Direct, retConversion = int.class, argConversions = {ToPythonStringNode.class, long.class}) - public static int PyUnicode_CompareWithASCIIString(long uniPtr, long str) { + // PyUnicode_CompareWithASCIIString is in C; this handles non-native strings + @CApiBuiltin(ret = Int, args = {PyObject, ConstCharPtr}, call = Ignored, retConversion = int.class, argConversions = {ToPythonStringNode.class, long.class}) + public static int GraalPyPrivate_Unicode_CompareWithASCIIString(long uniPtr, long str) { /* * This method cannot throw Python exceptions and doesn't need a GIL since both, the unicode * object and the ASCII string are assumed to be immutable. @@ -688,8 +694,9 @@ private static class InvalidStringException extends ControlFlowException { static final InvalidStringException INSTANCE = new InvalidStringException(); } - @CApiBuiltin(ret = Int, args = {PyObject, ConstCharPtr, Py_ssize_t}, call = Direct, retConversion = int.class, argConversions = {ToPythonStringNode.class, long.class, long.class}) - public static int PyUnicode_EqualToUTF8AndSize(long unicodePtr, long str, long size) { + // PyUnicode_EqualToUTF8AndSize is in C; this handles non-native strings + @CApiBuiltin(ret = Int, args = {PyObject, ConstCharPtr, Py_ssize_t}, call = Ignored, retConversion = int.class, argConversions = {ToPythonStringNode.class, long.class, long.class}) + public static int GraalPyPrivate_Unicode_EqualToUTF8AndSize(long unicodePtr, long str, long size) { if (size < 0) { return 0; } @@ -707,9 +714,10 @@ public static int PyUnicode_EqualToUTF8AndSize(long unicodePtr, long str, long s } } - @CApiBuiltin(ret = Int, args = {PyObject, PyObject}, call = Direct, retConversion = int.class, argConversions = {NativeToPythonNode.class, NativeToPythonNode.class}) + // PyUnicode_Compare is in C; this handles non-native strings + @CApiBuiltin(ret = Int, args = {PyObject, PyObject}, call = Ignored, retConversion = int.class, argConversions = {NativeToPythonNode.class, NativeToPythonNode.class}) @ImportStatic(PythonCextUnicodeBuiltins.class) - abstract static class PyUnicode_Compare extends CApiBinaryBuiltinNode { + abstract static class GraalPyPrivate_Unicode_Compare extends CApiBinaryBuiltinNode { @Specialization(guards = {"isAnyString(inliningTarget, left, getClassNode, isSubtypeNode)", "isAnyString(inliningTarget, right, getClassNode, isSubtypeNode)"}, limit = "1") static Object compare(Object left, Object right, @@ -892,6 +900,13 @@ static int doGeneric(Object type, long lindex, } } + /* C gets the native str region once (unicodeobject.c, graalpy_init_str) */ + @CApiBuiltin(ret = Pointer, call = Ignored, retConversion = long.class, argConversions = {}) + @TruffleBoundary + static long GraalPyPrivate_Str_State() { + return PythonContext.get(null).getNativeComplexState() + com.oracle.graal.python.runtime.nativeaccess.NativeComplex.S_STR; + } + @CApiBuiltin(ret = PyObject, args = {Py_ssize_t, Int, Int}, call = Ignored, retConversion = PythonToNativeNode.class, argConversions = {long.class, int.class, int.class}) static long GraalPyPrivate_Unicode_New(long nChars, int charSize, int isAscii) { if (nChars < 0 || nChars > Long.MAX_VALUE / charSize) { 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 77a11a2ac3..0166e210cf 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 @@ -569,6 +569,11 @@ public final class CApiFunction { @CApiBuiltin(name = "PyUnicode_GetLength", ret = Py_ssize_t, args = {PyObject}, call = CImpl) @CApiBuiltin(name = "PyUnicode_InternInPlace", ret = Void, args = {PyObjectPtr}, call = CImpl) @CApiBuiltin(name = "PyUnicode_New", ret = PyObject, args = {Py_ssize_t, PY_UCS4}, call = CImpl) + // C implementations with native fast paths + @CApiBuiltin(name = "PyUnicode_FromString", ret = PyObject, args = {ConstCharPtr}, call = CImpl) + @CApiBuiltin(name = "PyUnicode_Compare", ret = Int, args = {PyObject, PyObject}, call = CImpl) + @CApiBuiltin(name = "PyUnicode_CompareWithASCIIString", ret = Int, args = {PyObject, ConstCharPtr}, call = CImpl) + @CApiBuiltin(name = "PyUnicode_EqualToUTF8AndSize", ret = Int, args = {PyObject, ConstCharPtr, Py_ssize_t}, call = CImpl) @CApiBuiltin(name = "PyUnstable_InterpreterState_GetMainModule", ret = PyObject, args = {PyInterpreterState}, call = CImpl) @CApiBuiltin(name = "PyVectorcall_Call", ret = PyObject, args = {PyObject, PyObject, PyObject}, call = CImpl) @CApiBuiltin(name = "PyVectorcall_Call", ret = PyObject, args = {PyObject, PyObject, PyObject}, call = CImpl) @@ -908,7 +913,8 @@ public final class CApiFunction { @CApiBuiltin(name = "PyUnicode_IsIdentifier", ret = Int, args = {PyObject}, call = NotImplemented) @CApiBuiltin(name = "PyUnicode_Partition", ret = PyObject, args = {PyObject, PyObject}, call = NotImplemented) @CApiBuiltin(name = "PyUnicode_RPartition", ret = PyObject, args = {PyObject, PyObject}, call = NotImplemented) - @CApiBuiltin(name = "PyUnicode_Resize", ret = Int, args = {PyObjectPtr, Py_ssize_t}, call = NotImplemented) + @CApiBuiltin(name = "PyUnicode_Resize", ret = Int, args = {PyObjectPtr, Py_ssize_t}, call = CImpl) + @CApiBuiltin(name = "PyObject_Hash", ret = Py_hash_t, args = {PyObject}, call = CImpl) @CApiBuiltin(name = "PyUnicode_RichCompare", ret = PyObject, args = {PyObject, PyObject, Int}, call = NotImplemented) @CApiBuiltin(name = "PyUnicode_Splitlines", ret = PyObject, args = {PyObject, Int}, call = NotImplemented) @CApiBuiltin(name = "PyUnicode_Translate", ret = PyObject, args = {PyObject, PyObject, ConstCharPtr}, call = NotImplemented) diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CExtNodes.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CExtNodes.java index 7a57f1f1ca..06246ed583 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CExtNodes.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/CExtNodes.java @@ -243,7 +243,9 @@ static Object doGeneric(Node inliningTarget, Object object, Object arg, assert TypeNodes.NeedsNativeAllocationNode.executeUncached(object); NativeFunctionPointer callable = CApiContext.getNativeSymbol(inliningTarget, NativeCAPISymbol.FUN_UNICODE_SUBTYPE_NEW); try { - Object promotedArg = ensurePythonObjectNode.execute(PythonContext.get(inliningTarget), arg, false); + // Raw invoker (no downcall depth): keep the str a stub held by promotedArg + Object promotedArg = EnsurePythonObjectNode.promoteBorrowedString(PythonContext.get(inliningTarget), + ensurePythonObjectNode.execute(PythonContext.get(inliningTarget), arg, false)); long result = ExternalFunctionInvoker.invokeUNICODE_SUBTYPE_NEW(callable.getAddress(), toNativeNode.execute(inliningTarget, object), toNativeNode.execute(inliningTarget, promotedArg)); @@ -860,6 +862,11 @@ static void doDecref(Node inliningTarget, long pointer, com.oracle.graal.python.runtime.nativeaccess.NativeComplex.decref(st, pointer); return; } + // Native str structs have no Java object + if (st != 0 && com.oracle.graal.python.runtime.nativeaccess.NativeStr.isNativeStr(st, pointer)) { + com.oracle.graal.python.runtime.nativeaccess.NativeStr.decref(pointer); + return; + } // Float structs (exact, or a value-type float subclass) have no Java object if (st != 0 && (com.oracle.graal.python.runtime.nativeaccess.NativeSmall.isNativeFloat(st, pointer) || CApiTransitions.NativeFloatValueTypes.isValueType(st, CStructAccess.readPtrField(pointer, CFields.PyObject__ob_type)))) { @@ -1440,6 +1447,17 @@ public static PythonAbstractObject executeUncached(PythonContext context, Object return (PythonAbstractObject) EnsurePythonObjectNodeGen.getUncached().execute(context, object, true); } + /** + * For borrowed references C may keep as long as a container holds the item + * (tuple, list, dict items): a bare str becomes a PString (stable stub), as before. + */ + public static Object promoteBorrowedString(PythonContext context, Object object) { + if (object instanceof TruffleString s) { + return PFactory.createString(context.getLanguage(), s); + } + return object; + } + @TruffleBoundary public static boolean doesNotNeedPromotion(Object object) { return EnsurePythonObjectNodeGen.getUncached().execute(PythonContext.get(null), object, false) == object; @@ -1479,6 +1497,10 @@ static Object doGeneric(PythonContext context, Object obj, boolean promoteBoxabl } else if (profiled instanceof Boolean b) { return b ? context.getTrue() : context.getFalse(); } else if (profiled instanceof TruffleString s) { + // Unless boxables are promoted, a bare str crosses as a native str struct + if (!promoteBoxable && com.oracle.graal.python.runtime.nativeaccess.NativeStr.getStrType(context.peekNativeComplexState()) != 0) { + return s; + } return PFactory.createString(context.getLanguage(), s); } else if (profiled instanceof PythonBuiltinClassType pbct) { return context.lookupType(pbct); diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/ExternalFunctionNodes.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/ExternalFunctionNodes.java index 1dc2d0ccff..31a1054981 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/ExternalFunctionNodes.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/ExternalFunctionNodes.java @@ -233,8 +233,9 @@ public long execute(Object object) { * could be, e.g., Java primitive 'true' which will be promoted to an immortal object. */ PythonContext ctx = PythonContext.get(this); - Object promoted = ensurePythonObjectNode.execute(ctx, object, false); - assert promoted == object || PythonToNativeInternalNode.isImmortal(ctx, promoted); + // A borrowed str must stay valid as long as its owner: stable stub + Object promoted = EnsurePythonObjectNode.promoteBorrowedString(ctx, ensurePythonObjectNode.execute(ctx, object, false)); + assert promoted == object || object instanceof TruffleString || PythonToNativeInternalNode.isImmortal(ctx, promoted); return toNative.execute(promoted); } @@ -253,7 +254,7 @@ public static ToNativeBorrowedNode create() { @TruffleBoundary(allowInlining = true) public static long executeUncached(Object object) { - Object promoted = EnsurePythonObjectNode.executeUncached(PythonContext.get(null), object, false); + Object promoted = EnsurePythonObjectNode.promoteBorrowedString(PythonContext.get(null), EnsurePythonObjectNode.executeUncached(PythonContext.get(null), object, false)); return PythonToNativeInternalNode.executeUncached(promoted, false); } } @@ -2332,7 +2333,21 @@ static long doGeneric(PythonContext context, Object[] args, for (int i = 0; i < n; i++) { Object promoted = materializePrimitiveNode.execute(context, args[i], false); args[i] = promoted; - writePtrArrayElement(obItem, i, pythonToNativeNode.executeNewRef(inliningTarget, promoted)); + long elem = 0; + if (promoted instanceof TruffleString) { + // One string passed twice in one call gets one native str + for (int j = 0; j < i; j++) { + if (args[j] == promoted) { + elem = readPtrArrayElement(obItem, j); + com.oracle.graal.python.runtime.nativeaccess.NativeStr.incref(elem); + break; + } + } + } + if (elem == 0) { + elem = pythonToNativeNode.executeNewRef(inliningTarget, promoted); + } + writePtrArrayElement(obItem, i, elem); } if (LOGGER.isLoggable(Level.FINE)) { 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 0434034f73..1e1f06e1a2 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 @@ -1970,6 +1970,33 @@ public static boolean mapsToNull(Object obj) { return PNone.NO_VALUE == obj || DescriptorDeleteMarker.INSTANCE == obj; } + /** + * An exact str that is a bare Java string crosses as a native str struct (no + * wrapper, no stub, no handle). Callers that need a stable pointer (borrowed items of + * containers) promote it to a PString first. + */ + @Specialization + static long doString(Node inliningTarget, TruffleString s, boolean needsTransfer, + @Exclusive @Cached NativeStrNodes.StrToNativeNode strToNativeNode) { + CompilerAsserts.partialEvaluationConstant(needsTransfer); + return stringToNative(inliningTarget, s, needsTransfer, strToNativeNode); + } + + static long stringToNative(Node inliningTarget, TruffleString s, boolean needsTransfer, NativeStrNodes.StrToNativeNode strToNativeNode) { + PythonContext context = PythonContext.get(inliningTarget); + long st = context.getNativeComplexState(); + if (CompilerDirectives.injectBranchProbability(CompilerDirectives.SLOWPATH_PROBABILITY, com.oracle.graal.python.runtime.nativeaccess.NativeStr.getStrType(st) == 0)) { + return stringToNativeOff(s); + } + return strToNativeNode.execute(inliningTarget, st, s, needsTransfer); + } + + /** Scheme off (or C not initialized): a PString with a stub whose count is owned by C. */ + @TruffleBoundary + private static long stringToNativeOff(TruffleString s) { + return executeUncached(PFactory.createString(PythonLanguage.get(null), s), true); + } + @Specialization(guards = "mapsToNull(obj)") @SuppressWarnings("unused") static long doNullValues(Node inliningTarget, Object obj, boolean needsTransfer) { @@ -2065,9 +2092,10 @@ static boolean isExactComplex(Object o) { return o instanceof com.oracle.graal.python.builtins.objects.complex.PComplex c && c.isExact(); } - @Specialization(replaces = {"doNative", "doNullValues", "doPythonObject", "doExactComplex", "doLongNative", "doDoubleNative", "doNativeFloatValue"}) + @Specialization(replaces = {"doNative", "doNullValues", "doPythonObject", "doExactComplex", "doLongNative", "doDoubleNative", "doNativeFloatValue", "doString"}) static long doGeneric(Node inliningTarget, Object obj, boolean needsTransfer, @Cached InlinedExactClassProfile classProfile, + @Exclusive @Cached NativeStrNodes.StrToNativeNode strToNativeNode, @Exclusive @Cached InlinedBranchProfile hasReplicatedNativeReferences, @Exclusive @Cached FirstToNativeNode firstToNativeNode, @Exclusive @Cached UpdateStrongRefNode updateRefNode) { @@ -2100,6 +2128,11 @@ static long doGeneric(Node inliningTarget, Object obj, boolean needsTransfer, return 0; } + // Bare Java string -> native str struct + if (profiled instanceof TruffleString s) { + return stringToNative(inliningTarget, s, needsTransfer, strToNativeNode); + } + // Exact complex -> native struct if (profiled instanceof com.oracle.graal.python.builtins.objects.complex.PComplex c && c.isExact()) { return com.oracle.graal.python.runtime.nativeaccess.NativeComplex.toNative(context.getNativeComplexState(), c, needsTransfer); @@ -2318,6 +2351,8 @@ static Object doGeneric(Node inliningTarget, long pointer, boolean needsTransfer @Cached InlinedConditionProfile isNativeComplexProfile, @Cached InlinedConditionProfile isNativeLongProfile, @Cached InlinedConditionProfile isNativeFloatProfile, + @Cached InlinedConditionProfile isNativeStrProfile, + @Cached NativeStrNodes.NativeToStrNode nativeToStrNode, @Cached(inline = false) NativeFloatValueNode floatValueNode, @Exclusive @Cached InlinedExactClassProfile wrapperProfile, @Exclusive @Cached UpdateStrongRefNode updateRefNode) { @@ -2381,6 +2416,10 @@ static Object doGeneric(Node inliningTarget, long pointer, boolean needsTransfer if (isNativeFloatProfile.profile(inliningTarget, obType == com.oracle.graal.python.runtime.nativeaccess.NativeSmall.getFloatType(complexState) && obType != 0)) { return com.oracle.graal.python.runtime.nativeaccess.NativeSmall.floatFromNative(complexState, pointer, needsTransfer); } + // Native str struct -> Java string + if (isNativeStrProfile.profile(inliningTarget, com.oracle.graal.python.runtime.nativeaccess.NativeStr.isNativeStr(complexState, pointer, obType))) { + return nativeToStrNode.execute(inliningTarget, pointer, needsTransfer); + } Object value = floatValueNode.execute(complexState, pointer, obType, needsTransfer); if (value != null) { return value; @@ -2624,6 +2663,8 @@ static Object doNonWrapper(long pointer, boolean stealing, @Cached InlinedConditionProfile isNativeComplexProfile, @Cached InlinedConditionProfile isNativeLongProfile, @Cached InlinedConditionProfile isNativeFloatProfile, + @Cached InlinedConditionProfile isNativeStrProfile, + @Cached NativeStrNodes.NativeToStrNode nativeToStrNode, @Cached(inline = false) NativeFloatValueNode floatValueNode, @Cached InlinedExactClassProfile wrapperProfile, @Cached UpdateStrongRefNode updateRefNode) { @@ -2676,6 +2717,10 @@ static Object doNonWrapper(long pointer, boolean stealing, if (isNativeFloatProfile.profile(inliningTarget, obType == com.oracle.graal.python.runtime.nativeaccess.NativeSmall.getFloatType(complexState) && obType != 0)) { return com.oracle.graal.python.runtime.nativeaccess.NativeSmall.floatFromNative(complexState, pointer, stealing); } + // Native str struct -> Java string + if (isNativeStrProfile.profile(inliningTarget, com.oracle.graal.python.runtime.nativeaccess.NativeStr.isNativeStr(complexState, pointer, obType))) { + return nativeToStrNode.execute(inliningTarget, pointer, stealing); + } Object value = floatValueNode.execute(complexState, pointer, obType, stealing); if (value != null) { return value; diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/NativeStrNodes.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/NativeStrNodes.java new file mode 100644 index 0000000000..9adee41123 --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/NativeStrNodes.java @@ -0,0 +1,163 @@ +/* + * 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.transitions; + +import static com.oracle.graal.python.util.PythonUtils.TS_ENCODING; + +import com.oracle.graal.python.runtime.nativeaccess.NativeComplex; +import com.oracle.graal.python.runtime.nativeaccess.NativeStr; +import com.oracle.truffle.api.CompilerAsserts; +import com.oracle.truffle.api.dsl.Cached; +import com.oracle.truffle.api.dsl.GenerateCached; +import com.oracle.truffle.api.dsl.GenerateInline; +import com.oracle.truffle.api.dsl.GenerateUncached; +import com.oracle.truffle.api.dsl.Specialization; +import com.oracle.truffle.api.nodes.Node; +import com.oracle.truffle.api.profiles.InlinedConditionProfile; +import com.oracle.truffle.api.strings.TruffleString; + +/** Conversions between Java strings and native str structs (see {@link NativeStr}). */ +public final class NativeStrNodes { + + private NativeStrNodes() { + } + + /** + * A native str struct with the value of {@code s} and one count: owned by C with + * {@code newRef}, otherwise held on the borrowed stack until the outermost downcall returns. + */ + @GenerateInline + @GenerateCached(false) + @GenerateUncached + public abstract static class StrToNativeNode extends Node { + + public abstract long execute(Node inliningTarget, long st, TruffleString s, boolean newRef); + + @Specialization + static long doIt(Node inliningTarget, long st, TruffleString s, boolean newRef, + @Cached InlinedConditionProfile asciiProfile, + @Cached(inline = false) TruffleString.GetCodeRangeNode getCodeRangeNode, + @Cached(inline = false) TruffleString.CodePointLengthNode lengthNode, + @Cached(inline = false) TruffleString.SwitchEncodingNode switchEncodingNode, + @Cached(inline = false) TruffleString.CopyToNativeMemoryNode copyNode) { + CompilerAsserts.partialEvaluationConstant(newRef); + long prev = NativeStr.lastBorrowed(st, s); + if (prev != 0) { + if (newRef) { + NativeStr.incref(prev); // C's count; the borrowed stack already holds one + } + return prev; + } + TruffleString.CodeRange range = getCodeRangeNode.execute(s, TS_ENCODING); + int length = lengthNode.execute(s, TS_ENCODING); + int kind; + boolean ascii; + TruffleString.Encoding enc; + if (asciiProfile.profile(inliningTarget, range == TruffleString.CodeRange.ASCII)) { + kind = 1; + ascii = true; + enc = TruffleString.Encoding.US_ASCII; + } else if (range == TruffleString.CodeRange.LATIN_1) { + kind = 1; + ascii = false; + enc = TruffleString.Encoding.ISO_8859_1; + } else if (range == TruffleString.CodeRange.BMP) { + kind = 2; + ascii = false; + enc = TruffleString.Encoding.UTF_16; + } else { + // VALID (astral) and BROKEN (lone surrogates; same as the stub path's choice) + kind = 4; + ascii = false; + enc = TruffleString.Encoding.UTF_32; + } + long p = NativeStr.allocate(st, length, kind, ascii); + if (length > 0) { + TruffleString converted = switchEncodingNode.execute(s, enc); + copyNode.execute(converted, 0, p, ascii ? (int) NativeStr.ASCII_HEADER : (int) NativeStr.COMPACT_HEADER, length * kind, enc); + } + NativeStr.remember(p, s); + /* + * A borrowed copy holds its one count on the borrowed stack. A new-reference copy gets one + * more count there: C code may drop its new reference and keep using the pointer because + * another holder (a list, a dict, an attribute) keeps the object alive in CPython (getargs.c + * does this with PySequence_GetItem); here the holder has the Java string, not this copy, + * so the copy stays valid until the outermost downcall returns, like a borrowed argument. + */ + if (newRef) { + NativeStr.incref(p); + NativeComplex.borrowPush(st, p); + } else { + NativeComplex.borrowPush(st, p); + NativeStr.setLastBorrowed(st, s, p); + } + return p; + } + } + + /** The Java value of a native str struct; with {@code transfer} drops C's count. */ + @GenerateInline + @GenerateCached(false) + @GenerateUncached + public abstract static class NativeToStrNode extends Node { + + public abstract TruffleString execute(Node inliningTarget, long p, boolean transfer); + + @Specialization + static TruffleString doIt(Node inliningTarget, long p, boolean transfer, + @Cached InlinedConditionProfile hitProfile, + @Cached(inline = false) TruffleString.FromNativePointerWithCompactionUTF32Node fromNativeNode) { + TruffleString s = NativeStr.recall(p); + if (!hitProfile.profile(inliningTarget, s != null)) { + int kind = NativeStr.kind(p); + long length = NativeStr.length(p); + TruffleString.CompactionLevel level = kind == 1 ? TruffleString.CompactionLevel.S1 : kind == 2 ? TruffleString.CompactionLevel.S2 : TruffleString.CompactionLevel.S4; + s = fromNativeNode.execute(NativeStr.data(p), 0, (int) (length * kind), level, true); + NativeStr.remember(p, s); + NativeStr.count(NativeStr.C_C_TO_JAVA, 1); + } + if (transfer) { + NativeStr.decref(p); + } + return s; + } + } +} diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/structs/CStructAccess.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/structs/CStructAccess.java index f2fd8314d9..702e521590 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/structs/CStructAccess.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/structs/CStructAccess.java @@ -314,7 +314,9 @@ static void writeLong(long pointer, long offset, Object value, if (old != NULLPTR) { toPython.execute(old, true); } - Object promoted = ensurePythonObjectNode.execute(PythonContext.get(inliningTarget), value, false); + // Items written into native storage/struct fields keep a stable stub (C compares them by pointer) + Object promoted = EnsurePythonObjectNode.promoteBorrowedString(PythonContext.get(inliningTarget), + ensurePythonObjectNode.execute(PythonContext.get(inliningTarget), value, false)); NativeMemory.writePtr(pointer + offset, toNative.executeNewRef(inliningTarget, promoted)); } } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/SequenceStorageNodes.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/SequenceStorageNodes.java index 88918c2192..5132fc1b40 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/SequenceStorageNodes.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/SequenceStorageNodes.java @@ -1482,7 +1482,7 @@ protected static void doNativeObject(NativeObjectSequenceStorage storage, int id @Cached PythonToNativeInternalNode toNative, @Cached CExtNodes.XDecRefPointerNode decRefPointerNode) { long old = readPtrArrayElement(storage.getPtr(), idx); - Object promoted = ensurePythonObjectNode.execute(PythonContext.get(inliningTarget), value, false); + Object promoted = CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(PythonContext.get(inliningTarget), ensurePythonObjectNode.execute(PythonContext.get(inliningTarget), value, false)); writePtrArrayElement(storage.getPtr(), idx, toNative.executeNewRef(inliningTarget, promoted)); decRefPointerNode.execute(inliningTarget, old); } @@ -1505,7 +1505,7 @@ protected static void doNativeObject(NativeObjectSequenceStorage storage, int id @Bind Node inliningTarget, @Cached CExtNodes.EnsurePythonObjectNode ensurePythonObjectNode, @Cached PythonToNativeInternalNode toNative) { - Object promoted = ensurePythonObjectNode.execute(PythonContext.get(inliningTarget), value, false); + Object promoted = CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(PythonContext.get(inliningTarget), ensurePythonObjectNode.execute(PythonContext.get(inliningTarget), value, false)); writePtrArrayElement(storage.getPtr(), idx, toNative.executeNewRef(inliningTarget, promoted)); } } @@ -4405,7 +4405,7 @@ protected static SequenceStorage doNativeObjectStorage(Node inliningTarget, Nati writePtrArrayElement(storage.getPtr(), i, readPtrArrayElement(storage.getPtr(), i - 1)); } LoopNode.reportLoopCount(inliningTarget, (int) Math.min(Integer.MAX_VALUE, Math.max(0L, (long) storage.length() - index))); - Object promoted = ensurePythonObjectNode.execute(PythonContext.get(inliningTarget), value, false); + Object promoted = CExtNodes.EnsurePythonObjectNode.promoteBorrowedString(PythonContext.get(inliningTarget), ensurePythonObjectNode.execute(PythonContext.get(inliningTarget), value, false)); writePtrArrayElement(storage.getPtr(), index, toNative.executeNewRef(inliningTarget, promoted)); storage.setNewLength(newLength); return storage; diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeComplex.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeComplex.java index c6caf9905f..2a91554e1b 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeComplex.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeComplex.java @@ -107,7 +107,9 @@ public final class NativeComplex { // Allocator region of exact int structs (see NativeLong) public static final long S_LONG = S_BDEPTH + 8; public static final long S_SMALL = S_LONG + NativeLong.REGION_SIZE; // NativeSmall region - public static final long STATE_SIZE = S_SMALL + NativeSmall.REGION_SIZE; + // Native str region (see NativeStr) + public static final long S_STR = S_SMALL + NativeSmall.REGION_SIZE; + public static final long STATE_SIZE = S_STR + NativeStr.REGION_SIZE; private static final long ARENA_SIZE = 64 * 1024; private static final long ARENA_HEADER = 16; @@ -366,7 +368,7 @@ public static long getComplexType(long st) { return UNSAFE.getLong(st + S_TYPE); } - static void borrowPush(long st, long p) { + public static void borrowPush(long st, long p) { long top = UNSAFE.getLong(st + S_BTOP); if (CompilerDirectives.injectBranchProbability(CompilerDirectives.SLOWPATH_PROBABILITY, top >= UNSAFE.getLong(st + S_BCAP))) { growBorrowStack(st); @@ -417,6 +419,14 @@ public static void exitDowncall() { } } + /** Entry {@code idx} of the borrowed stack, or 0 if the stack is not that deep. */ + public static long borrowAt(long st, long idx) { + if (idx >= UNSAFE.getLong(st + S_BTOP)) { + return 0; + } + return UNSAFE.getLong(UNSAFE.getLong(st + S_BSTACK) + 8 * idx); + } + /** Depth of the borrowed stack at entry of a downcall (0 if there is no state). */ public static long borrowMark(long st) { return st == 0 ? 0 : UNSAFE.getLong(st + S_BTOP); @@ -432,12 +442,16 @@ public static void borrowRelease(long st, long mark) { long arr = UNSAFE.getLong(st + S_BSTACK); long longType = NativeLong.getLongType(st); long complexType = UNSAFE.getLong(st + S_TYPE); + long strType = NativeStr.getStrType(st); while (top > mark) { top--; long p = UNSAFE.getLong(arr + 8 * top); long type = UNSAFE.getLong(p + OFF_TYPE); if (type == longType) { NativeLong.decref(st, p); + } else if (type == strType && type != 0) { + // Str struct made for a borrowed argument + NativeStr.decref(p); } else if (type == complexType) { decref(st, p); } else { diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java new file mode 100644 index 0000000000..75ff494b93 --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java @@ -0,0 +1,283 @@ +/* + * 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.runtime.nativeaccess; + +import static com.oracle.graal.python.runtime.nativeaccess.NativeMemory.UNSAFE; + +import com.oracle.truffle.api.CompilerDirectives; +import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; +import com.oracle.truffle.api.strings.TruffleString; + +/** + * Exact {@code str} values cross into C as native CPython-layout compact unicode + * objects ({@code PyASCIIObject} / {@code PyCompactUnicodeObject} with the characters inline), made + * when C asks, with no Java wrapper, no stub and no handle-table entry. C's reference count owns + * the struct: it is freed by {@code unicode_dealloc} in C (or by Java when Java drops the last + * count). Strings created by C ({@code PyUnicode_New}, {@code PyUnicode_FromStringAndSize}, the + * UTF-8 decoders) are born in the same layout and become Java strings only when Java reads them. + * + *

+ * Layout (CPython 3.13, 64-bit): {@code ob_refcnt} @0, {@code ob_type} @8, {@code length} @16, + * {@code hash} @24, {@code state} @32 (32-bit bitfield: interned:2, kind:3, compact:1, ascii:1, + * statically_allocated:1), 4 bytes of padding @36 that CPython never reads. ASCII strings: data @40. + * Other strings: {@code utf8_length} @40, {@code utf8} @48, data @56. Data is followed by one NUL + * code unit. + *

+ * + *

+ * The padding word @36 is ours: bit 31 marks a struct made by this scheme (by Java or by C); the + * low bits hold 1 + the index of an entry of a small ring that maps the struct back to the Java + * string it was made from or converted to. The ring keeps the last {@link #RING_SIZE} crossings. + * An entry is valid for a struct only if it still names that struct's address; a struct is + * freed and re-made only with a fresh word, so a stale entry is never followed. The ring gives + * {@code f(s) is s} for a string that C returns while its struct lives, and saves the second copy + * when C hands the same struct back to Java. + *

+ * + * Single-threaded: callers hold the GIL. + */ +public final class NativeStr { + + public static final long OFF_REFCNT = 0; + public static final long OFF_TYPE = 8; + public static final long OFF_LENGTH = 16; + public static final long OFF_HASH = 24; + public static final long OFF_STATE = 32; + public static final long OFF_JSLOT = 36; + public static final long OFF_UTF8_LENGTH = 40; + public static final long OFF_UTF8 = 48; + public static final long ASCII_HEADER = 40; + public static final long COMPACT_HEADER = 56; + + public static final int MARK = 0x80000000; + public static final int SLOT_MASK = 0x7fffffff; + + // state bits (clang/gcc bitfield order on little-endian targets: first field in the low bits) + public static final int STATE_KIND_SHIFT = 2; + public static final int STATE_COMPACT = 1 << 5; + public static final int STATE_ASCII = 1 << 6; + + // region layout, relative to st + NativeComplex.S_STR (must match GraalPyStrState in unicodeobject.c) + public static final long R_TYPE = 0; + public static final long R_COUNTERS = 8; + public static final int N_COUNTERS = 8; + public static final long REGION_SIZE = R_COUNTERS + 8 * N_COUNTERS; + + public static final int C_JAVA_TO_C = 0; + public static final int C_C_TO_JAVA = 1; + public static final int C_RING_HIT = 2; + public static final int C_JAVA_FREE = 3; + public static final int C_C_ALLOC = 4; // updated by C + public static final int C_C_FREE = 5; // updated by C + public static final int C_JAVA_BYTES = 6; + public static final String[] COUNTER_NAMES = {"str_java_to_c", "str_c_to_java", "str_ring_hit", "str_java_free", "str_c_alloc", "str_c_free", "str_java_bytes", ""}; + + public static final int RING_SIZE = 4096; // power of two + private static final TruffleString[] RING_STR = new TruffleString[RING_SIZE]; + private static final long[] RING_PTR = new long[RING_SIZE]; + private static int ringCursor; + + private static final long[] JAVA_COUNTS = new long[N_COUNTERS]; + + private NativeStr() { + } + + public static final boolean COUNTERS = NativeComplex.COUNTERS; + + public static void count(int idx, long n) { + if (COUNTERS) { + JAVA_COUNTS[idx] += n; + } + } + + private static long region(long st) { + return st + NativeComplex.S_STR; + } + + /** Type pointer of {@code PyUnicode_Type}, or 0 if the scheme is off or C is not initialized. */ + public static long getStrType(long st) { + return st == 0 ? 0 : UNSAFE.getLong(region(st) + R_TYPE); + } + + /** True if {@code p} (a non-handle PyObject pointer) is a str struct of this scheme. */ + public static boolean isNativeStr(long st, long p) { + long type = getStrType(st); + return type != 0 && UNSAFE.getLong(p + OFF_TYPE) == type && (UNSAFE.getInt(p + OFF_JSLOT) & MARK) != 0; + } + + public static boolean isNativeStr(long st, long p, long obType) { + return obType == getStrType(st) && obType != 0 && (UNSAFE.getInt(p + OFF_JSLOT) & MARK) != 0; + } + + @TruffleBoundary + public static long[] snapshot(long st, boolean reset) { + long[] res = new long[N_COUNTERS]; + for (int i = 0; i < N_COUNTERS; i++) { + res[i] = JAVA_COUNTS[i] + (st != 0 ? UNSAFE.getLong(region(st) + R_COUNTERS + 8L * i) : 0); + if (reset) { + JAVA_COUNTS[i] = 0; + if (st != 0) { + UNSAFE.putLong(region(st) + R_COUNTERS + 8L * i, 0); + } + } + } + return res; + } + + // ---------------------------------------------------------------- struct + + public static int kind(long p) { + return (UNSAFE.getInt(p + OFF_STATE) >>> STATE_KIND_SHIFT) & 7; + } + + public static boolean isAscii(long p) { + return (UNSAFE.getInt(p + OFF_STATE) & STATE_ASCII) != 0; + } + + public static long length(long p) { + return UNSAFE.getLong(p + OFF_LENGTH); + } + + public static long data(long p) { + return p + (isAscii(p) ? ASCII_HEADER : COMPACT_HEADER); + } + + /** + * Allocates a struct with count 1 and an initialized header; the caller writes {@code length * + * kind} bytes of characters at {@link #data}. The NUL code unit is written here. + */ + public static long allocate(long st, long length, int kind, boolean ascii) { + long header = ascii ? ASCII_HEADER : COMPACT_HEADER; + long size = header + (length + 1) * kind; + long p = UNSAFE.allocateMemory(size); + UNSAFE.putLong(p + OFF_REFCNT, 1); + UNSAFE.putLong(p + OFF_TYPE, getStrType(st)); + UNSAFE.putLong(p + OFF_LENGTH, length); + UNSAFE.putLong(p + OFF_HASH, -1); + UNSAFE.putInt(p + OFF_STATE, (kind << STATE_KIND_SHIFT) | STATE_COMPACT | (ascii ? STATE_ASCII : 0)); + UNSAFE.putInt(p + OFF_JSLOT, MARK); + if (!ascii) { + UNSAFE.putLong(p + OFF_UTF8_LENGTH, 0); + UNSAFE.putLong(p + OFF_UTF8, 0); + } + long end = p + header + length * kind; + if (kind == 1) { + UNSAFE.putByte(end, (byte) 0); + } else if (kind == 2) { + UNSAFE.putShort(end, (short) 0); + } else { + UNSAFE.putInt(end, 0); + } + count(C_JAVA_TO_C, 1); + count(C_JAVA_BYTES, size); + return p; + } + + /** Drops one count; frees the struct (and its UTF-8 cache) when it reaches zero. */ + public static void decref(long p) { + long rc = UNSAFE.getLong(p + OFF_REFCNT) - 1; + UNSAFE.putLong(p + OFF_REFCNT, rc); + if (rc == 0) { + free(p); + } + } + + private static void free(long p) { + if (!isAscii(p)) { + long utf8 = UNSAFE.getLong(p + OFF_UTF8); + if (utf8 != 0) { + UNSAFE.freeMemory(utf8); + } + } + UNSAFE.putLong(p + OFF_TYPE, 0); + UNSAFE.freeMemory(p); + count(C_JAVA_FREE, 1); + } + + // ---------------------------------------------------------------- same string twice in one call + + private static TruffleString lastStr; + private static long lastPtr; + private static long lastIdx = -1; + + /** + * The struct made for {@code s} as the most recent borrowed argument, if it is still held on + * the borrowed stack (so alive until the outermost downcall returns); else 0. Gives one + * pointer for one string passed twice in a call ({@code f(s, s)}) and saves the copy. + */ + public static long lastBorrowed(long st, TruffleString s) { + if (lastStr == s && lastIdx >= 0 && NativeComplex.borrowAt(st, lastIdx) == lastPtr) { + return lastPtr; + } + return 0; + } + + public static void setLastBorrowed(long st, TruffleString s, long p) { + lastStr = s; + lastPtr = p; + lastIdx = NativeComplex.borrowMark(st) - 1; + } + + public static void incref(long p) { + UNSAFE.putLong(p + OFF_REFCNT, UNSAFE.getLong(p + OFF_REFCNT) + 1); + } + + // ---------------------------------------------------------------- identity ring + + /** Remembers that struct {@code p} holds the value of {@code s}. */ + public static void remember(long p, TruffleString s) { + int k = ringCursor; + ringCursor = (k + 1) & (RING_SIZE - 1); + RING_STR[k] = s; + RING_PTR[k] = p; + UNSAFE.putInt(p + OFF_JSLOT, MARK | (k + 1)); + } + + /** The Java string struct {@code p} was made from or converted to, if still known; else null. */ + public static TruffleString recall(long p) { + int k = (UNSAFE.getInt(p + OFF_JSLOT) & SLOT_MASK) - 1; + if (CompilerDirectives.injectBranchProbability(CompilerDirectives.LIKELY_PROBABILITY, k >= 0 && k < RING_SIZE) && RING_PTR[k] == p) { + count(C_RING_HIT, 1); + return RING_STR[k]; + } + return null; + } +} From fdfae80906ae55855b693aea59670231e31e709a Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Sat, 28 Nov 2026 01:34:04 +0100 Subject: [PATCH 3/7] Read and write the free list links of native int and complex blocks with memcpy GCC rejects the previous cast of the value field's address to a block pointer under -Werror=strict-aliasing. Clang accepted it. The stored bytes are the same. --- .../src/complexobject.c | 20 ++++++++++++++++--- .../src/longobject.c | 20 ++++++++++++++++--- 2 files changed, 34 insertions(+), 6 deletions(-) diff --git a/graalpython/com.oracle.graal.python.cext/src/complexobject.c b/graalpython/com.oracle.graal.python.cext/src/complexobject.c index 5277613258..9e0061e769 100644 --- a/graalpython/com.oracle.graal.python.cext/src/complexobject.c +++ b/graalpython/com.oracle.graal.python.cext/src/complexobject.c @@ -66,7 +66,21 @@ static GraalPyComplexAllocState *graalpy_complex_state; static destructor graalpy_complex_orig_dealloc; #define GRAALPY_COMPLEX_COUNT(IDX) do { if (graalpy_complex_state->flags & 1) graalpy_complex_state->counters[IDX]++; } while (0) -#define GRAALPY_COMPLEX_LINK(B) (*(GraalPyComplexBlock **) &(B)->obj.cval.real) +/* The free list link is stored in the bytes of a free block's first value field. memcpy keeps + this within the aliasing rules; compilers turn it into a plain load or store. */ +static inline GraalPyComplexBlock * +graalpy_complex_get_link(GraalPyComplexBlock *b) +{ + GraalPyComplexBlock *next; + memcpy(&next, &b->obj.cval.real, sizeof(next)); + return next; +} + +static inline void +graalpy_complex_set_link(GraalPyComplexBlock *b, GraalPyComplexBlock *next) +{ + memcpy(&b->obj.cval.real, &next, sizeof(next)); +} static GraalPyComplexBlock * graalpy_complex_new_arena(GraalPyComplexAllocState *st) @@ -90,7 +104,7 @@ graalpy_complex_alloc(double real, double imag) GraalPyComplexAllocState *st = graalpy_complex_state; GraalPyComplexBlock *b = st->free_list; if (b != NULL) { - st->free_list = GRAALPY_COMPLEX_LINK(b); + st->free_list = graalpy_complex_get_link(b); } else if (st->bump + sizeof(GraalPyComplexBlock) <= st->end) { b = (GraalPyComplexBlock *) st->bump; st->bump += sizeof(GraalPyComplexBlock); @@ -114,7 +128,7 @@ static void graalpy_complex_free_block(GraalPyComplexAllocState *st, GraalPyComplexBlock *b) { b->serial = 0; - GRAALPY_COMPLEX_LINK(b) = st->free_list; + graalpy_complex_set_link(b, st->free_list); st->free_list = b; GRAALPY_COMPLEX_COUNT(GC_FREE); } diff --git a/graalpython/com.oracle.graal.python.cext/src/longobject.c b/graalpython/com.oracle.graal.python.cext/src/longobject.c index 12d3220186..dad90db146 100644 --- a/graalpython/com.oracle.graal.python.cext/src/longobject.c +++ b/graalpython/com.oracle.graal.python.cext/src/longobject.c @@ -93,7 +93,21 @@ _Static_assert(offsetof(GraalPyLongAllocState, counters) == 40, "int state layou #define GRAALPY_LONG_ARENA_SIZE (64 * 1024) #define GRAALPY_LONG_ARENA_HEADER 16 -#define GRAALPY_LONG_LINK(B) (*(GraalPyLongBlock **) &(B)->lv_tag) +/* The free list link is stored in the bytes of a free block's first value field. memcpy keeps + this within the aliasing rules; compilers turn it into a plain load or store. */ +static inline GraalPyLongBlock * +graalpy_long_get_link(GraalPyLongBlock *b) +{ + GraalPyLongBlock *next; + memcpy(&next, &b->lv_tag, sizeof(next)); + return next; +} + +static inline void +graalpy_long_set_link(GraalPyLongBlock *b, GraalPyLongBlock *next) +{ + memcpy(&b->lv_tag, &next, sizeof(next)); +} static GraalPyLongAllocState *graalpy_long_state; static destructor graalpy_long_orig_dealloc; @@ -104,7 +118,7 @@ graalpy_long_block(void) GraalPyLongAllocState *st = graalpy_long_state; GraalPyLongBlock *b = st->free_list; if (b != NULL) { - st->free_list = GRAALPY_LONG_LINK(b); + st->free_list = graalpy_long_get_link(b); } else if (st->bump + sizeof(GraalPyLongBlock) <= st->end) { b = (GraalPyLongBlock *) st->bump; st->bump += sizeof(GraalPyLongBlock); @@ -156,7 +170,7 @@ graalpy_long_dealloc(PyObject *op) } GraalPyLongBlock *b = (GraalPyLongBlock *) op; Py_SET_TYPE(op, NULL); - GRAALPY_LONG_LINK(b) = graalpy_long_state->free_list; + graalpy_long_set_link(b, graalpy_long_state->free_list); graalpy_long_state->free_list = b; } From f31d46839f3e25341b6072bcddd7173bf6a38db7 Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Sat, 28 Nov 2026 02:05:06 +0100 Subject: [PATCH 4/7] Check native value copies by value when releasing a native args tuple ReleaseNativeArgsTupleNode asserted (with detailed assertions) that every element of the args tuple is still the pointer that converting the managed argument again yields. That holds for stubs, handles and tagged values, but not for arguments that cross as native value copies (str, int, float, complex): each conversion makes a new struct, so the check failed for correct tuples (e.g. a str class name passed to a native metaclass tp_init during "import ctypes"), and the conversion done by the check itself allocated a further copy. For an element that is a value copy, compare the struct's type and value with the managed argument (code points for str, value for int, raw bits for float and complex, type and bits for value-type float subclasses) and require that it is still alive; other elements keep the pointer check. --- .../cext/capi/ExternalFunctionNodes.java | 18 +++++++- .../capi/transitions/CApiTransitions.java | 41 +++++++++++++++++++ .../runtime/nativeaccess/NativeStr.java | 19 +++++++++ 3 files changed, 77 insertions(+), 1 deletion(-) diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/ExternalFunctionNodes.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/ExternalFunctionNodes.java index 31a1054981..cb6877f5d7 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/ExternalFunctionNodes.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/ExternalFunctionNodes.java @@ -2451,10 +2451,26 @@ static void doGeneric(long argsTuplePtr, Object[] managedArgs, argsTuplePtr); } + /** + * Each element must still be the native representation of its managed argument: the same + * pointer (stubs, handles, tagged values, native objects), or, for an argument that crossed + * as a native value copy (str, int, float, complex), a struct of the same type and value. + * A copy is made per conversion, so it is not converted again here: that would make a new + * struct with a different address. + */ + @TruffleBoundary private static boolean verifyElements(long op, Object[] managedArgs) { long obItem = CStructAccess.getFieldPtr(op, CFields.PyTupleObject__ob_item); for (int i = 0; i < managedArgs.length; i++) { - if (readPtrArrayElement(obItem, i) != PythonToNativeInternalNode.executeUncached(managedArgs[i], false)) { + long elem = readPtrArrayElement(obItem, i); + if (CApiTransitions.isNativeValueCopyOf(elem, managedArgs[i])) { + // the tuple owns one reference to each element + if (CApiTransitions.readNativeRefCount(elem) < 1) { + return false; + } + continue; + } + if (elem != PythonToNativeInternalNode.executeUncached(managedArgs[i], false)) { return false; } } 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 1e1f06e1a2..27bd0fadde 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 @@ -1865,6 +1865,47 @@ public static CharPtrToPythonStrictNode getUncached() { } } + /** + * For assertions: whether {@code pointer} is a native value copy (a str, int, float or complex + * struct made by {@link PythonToNativeInternalNode}) that stands for {@code value}. A value copy + * is made per conversion, so converting {@code value} again gives a different struct; this + * compares the type and the value the struct holds instead of the pointer. Returns false for + * anything that is not such a struct (handles, stubs, other native objects). + */ + @TruffleBoundary + public static boolean isNativeValueCopyOf(long pointer, Object value) { + if (pointer == 0 || HandlePointerConverter.pointsToPyHandleSpace(pointer)) { + return false; + } + PythonContext context = PythonContext.get(null); + long st = context.peekNativeComplexState(); + if (st == 0) { + return false; + } + if (com.oracle.graal.python.runtime.nativeaccess.NativeStr.isNativeStr(st, pointer)) { + return value instanceof TruffleString s && com.oracle.graal.python.runtime.nativeaccess.NativeStr.contentEquals(pointer, s); + } + if (com.oracle.graal.python.runtime.nativeaccess.NativeLong.isNativeLong(st, pointer)) { + return value instanceof Long l && com.oracle.graal.python.runtime.nativeaccess.NativeLong.fromNative(context.getLanguage(), st, pointer, false) instanceof Long v && v.longValue() == l; + } + if (com.oracle.graal.python.runtime.nativeaccess.NativeSmall.isNativeFloat(st, pointer)) { + return value instanceof Double d && + Double.doubleToRawLongBits(com.oracle.graal.python.runtime.nativeaccess.NativeSmall.floatFromNative(st, pointer, false)) == Double.doubleToRawLongBits(d); + } + if (com.oracle.graal.python.runtime.nativeaccess.NativeComplex.isNativeComplex(st, pointer)) { + return value instanceof com.oracle.graal.python.builtins.objects.complex.PComplex c && c.isExact() && + Double.doubleToRawLongBits(com.oracle.graal.python.runtime.nativeaccess.NativeComplex.readReal(pointer)) == Double.doubleToRawLongBits(c.getReal()) && + Double.doubleToRawLongBits(com.oracle.graal.python.runtime.nativeaccess.NativeComplex.readImag(pointer)) == Double.doubleToRawLongBits(c.getImag()); + } + if (value instanceof com.oracle.graal.python.builtins.objects.floats.PNativeFloat f) { + // a value-type native float subclass instance: same type, same bits + long type = PythonToNativeInternalNode.executeUncached(GetClassNode.executeUncached(f), false); + return NativeMemory.readLong(pointer + 8) == type && + Double.doubleToRawLongBits(com.oracle.graal.python.runtime.nativeaccess.NativeSmall.floatFromNative(st, pointer, false)) == Double.doubleToRawLongBits(f.getValue()); + } + return false; + } + @GenerateUncached @GenerateInline @GenerateCached(false) diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java index 75ff494b93..c55a591cf8 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java @@ -41,6 +41,7 @@ package com.oracle.graal.python.runtime.nativeaccess; import static com.oracle.graal.python.runtime.nativeaccess.NativeMemory.UNSAFE; +import static com.oracle.graal.python.util.PythonUtils.TS_ENCODING; import com.oracle.truffle.api.CompilerDirectives; import com.oracle.truffle.api.CompilerDirectives.TruffleBoundary; @@ -262,6 +263,24 @@ public static void incref(long p) { // ---------------------------------------------------------------- identity ring + /** Whether struct {@code p} holds the same code points as {@code s} (for assertions). */ + @TruffleBoundary + public static boolean contentEquals(long p, TruffleString s) { + int n = s.codePointLengthUncached(TS_ENCODING); + if (length(p) != n) { + return false; + } + int k = kind(p); + long d = data(p); + for (int i = 0; i < n; i++) { + int c = k == 1 ? UNSAFE.getByte(d + i) & 0xFF : k == 2 ? UNSAFE.getShort(d + 2L * i) & 0xFFFF : UNSAFE.getInt(d + 4L * i); + if (c != s.codePointAtIndexUncached(i, TS_ENCODING)) { + return false; + } + } + return true; + } + /** Remembers that struct {@code p} holds the value of {@code s}. */ public static void remember(long p, TruffleString s) { int k = ringCursor; From 048189e66f04c8d2f1e276891776a6c31a9f78cb Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Sat, 28 Nov 2026 02:24:44 +0100 Subject: [PATCH 5/7] Forget the last borrowed str copy when the borrowed stack is released A str passed twice in one call reuses the struct made for its previous borrowed conversion while that struct is still on the borrowed stack, checked by comparing the stack entry at the remembered index with the remembered pointer. After the outermost C call returned, the struct was freed, but the cache kept its address. In a later call a new struct for a different string could be allocated at the same address and pushed at the same index; the check then passed and the new string's struct was handed out for the old string. test_capi.test_unicode test_fromobject showed it: PyUnicode_FromObject(Str('abc')) returned the class name 'Str'. Clear the cache whenever the stack is released below its index. --- .../python/runtime/nativeaccess/NativeComplex.java | 1 + .../python/runtime/nativeaccess/NativeStr.java | 14 ++++++++++++++ 2 files changed, 15 insertions(+) diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeComplex.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeComplex.java index 2a91554e1b..0a58ddc220 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeComplex.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeComplex.java @@ -460,6 +460,7 @@ public static void borrowRelease(long st, long mark) { } } UNSAFE.putLong(st + S_BTOP, top); + NativeStr.forgetBorrowedAbove(mark); } } } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java index c55a591cf8..f879470674 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java @@ -251,6 +251,20 @@ public static long lastBorrowed(long st, TruffleString s) { return 0; } + /** + * Called when the borrowed stack is released down to {@code mark}: the remembered struct is no + * longer held there and may be freed. Without this, a later struct allocated at the same address + * and pushed at the same stack index would pass the check in {@link #lastBorrowed} and be + * handed out for {@code s} although it holds a different string. + */ + public static void forgetBorrowedAbove(long mark) { + if (lastIdx >= mark) { + lastStr = null; + lastPtr = 0; + lastIdx = -1; + } + } + public static void setLastBorrowed(long st, TruffleString s, long p) { lastStr = s; lastPtr = p; From a71afd80f8525c3065d8b2d8276a40cb1cc41e84 Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Sat, 28 Nov 2026 02:46:33 +0100 Subject: [PATCH 6/7] Return a new str from PyUnicode_FromObject for a str subclass instance PyUnicode_FromObject of a str subclass instance returned the bare Java string that str() of the instance yields. That string can be the very object another str holds, and a bare string now keeps its identity when it crosses to C and back, so the result was identical to the original str (test_capi.test_unicode test_fromobject: assertIsNot(s2, s)). As in CPython, wrap it in a new exact str object. --- .../modules/cext/PythonCextUnicodeBuiltins.java | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextUnicodeBuiltins.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextUnicodeBuiltins.java index f29a1fcea1..f0d8de3437 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextUnicodeBuiltins.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/modules/cext/PythonCextUnicodeBuiltins.java @@ -263,7 +263,16 @@ static Object fromObject(Object obj, @Cached StringBuiltins.StrNewNode strNode, @SuppressWarnings("unused") @Shared @Cached GetClassNode getClassNode, @SuppressWarnings("unused") @Shared @Cached IsSubtypeNode isSubtypeNode) { - return strNode.executeWith(obj); + Object result = strNode.executeWith(obj); + if (result instanceof TruffleString ts) { + /* + * As in CPython, a str subclass instance gives a new exact str object. The bare + * Java string may be the one another str object holds, and a bare string keeps its + * identity across C (native str copies), so wrap it in a fresh object. + */ + return PFactory.createString(PythonLanguage.get(inliningTarget), ts); + } + return result; } @Specialization(guards = {"!isStringSubtype(inliningTarget, obj, getClassNode, isSubtypeNode)"}) From dc7a331fdc40c8350151643e1b30b3b8bd4940c6 Mon Sep 17 00:00:00 2001 From: Ivo Horak Date: Sat, 28 Nov 2026 05:40:13 +0100 Subject: [PATCH 7/7] Read native str structs as remembered str objects so containers keep identity Java read a native str struct as a bare Java string. When C created a str and stored it into a dict, the dict held that bare string; the first time C borrowed it from the dict (PyDict_GetItemRef and friends promote bare strings to an object with a stable stub, and write it back), the dict's value became a new object. Python code that had already received the first one saw a different object afterwards. pyexpat's element name interning showed it (test_pyexpat InterningTest: the first handler call got another object than the later ones). Java now reads every native str struct as an exact str object, made once per struct and remembered in the identity ring, for structs created by C and for copies of Java strings alike. The same struct read again (key and value of one PyDict_SetItem, then an argument tuple element) gives the same object while its ring entry lives, so a str that C stores into a container is the object the container keeps, and C reading it back gets its stub. This gives up "f(s) is s" for a bare Java string passed through C: the result is an equal, new object, as for every str that crosses through a stub. Adds a cpyext test for the interning-dict pattern. --- .../src/tests/cpyext/test_unicode.py | 65 +++++++++++++++++++ .../cext/capi/transitions/NativeStrNodes.java | 43 ++++++++---- .../runtime/nativeaccess/NativeStr.java | 37 +++++++---- 3 files changed, 121 insertions(+), 24 deletions(-) diff --git a/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_unicode.py b/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_unicode.py index 958d9c4937..edc0596f5b 100644 --- a/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_unicode.py +++ b/graalpython/com.oracle.graal.python.test/src/tests/cpyext/test_unicode.py @@ -1494,3 +1494,68 @@ def test_builtins(self): assert "sd" in s assert UnicodeSubclass("<{}>").format("asdf") == "" assert UnicodeSubclass("<%s>") % "asdf" == "" + + +class TestStrIdentityThroughDict(unittest.TestCase): + """ + C code that interns strings in a dict (look the string up, insert it if missing, return the + dict's value), as pyexpat does for element names, must hand Python the same object every time, + and that object must be the one the dict holds. + """ + + StrInternDict = CPyExtType( + "StrInternDict", + ''' + static PyObject* intern_in_dict(PyObject *d, PyObject *result) { + PyObject *value; + if (result == NULL) { + return NULL; + } + if (PyDict_GetItemRef(d, result, &value) == 0 && PyDict_SetItem(d, result, result) == 0) { + return result; + } + Py_DECREF(result); + return value; + } + + static PyObject* intern_utf8(PyObject *cls, PyObject *args) { + PyObject *d; + const char *s; + if (!PyArg_ParseTuple(args, "Os", &d, &s)) { + return NULL; + } + return intern_in_dict(d, PyUnicode_DecodeUTF8(s, (Py_ssize_t) strlen(s), NULL)); + } + + static PyObject* intern_obj(PyObject *cls, PyObject *args) { + PyObject *d, *o; + if (!PyArg_ParseTuple(args, "OO", &d, &o)) { + return NULL; + } + Py_INCREF(o); + return intern_in_dict(d, o); + } + ''', + tp_methods='{"intern_utf8", (PyCFunction)intern_utf8, METH_VARARGS | METH_STATIC, ""}, ' + '{"intern_obj", (PyCFunction)intern_obj, METH_VARARGS | METH_STATIC, ""}', + ) + + def test_c_created_str(self): + d = {} + first = self.StrInternDict.intern_utf8(d, "tag") + second = self.StrInternDict.intern_utf8(d, "tag") + self.assertEqual(first, "tag") + self.assertIs(type(first), str) + self.assertIs(first, second) + self.assertIs(d["tag"], first) + self.assertIs(list(d.values())[0], first) + self.assertIs(list(d.keys())[0], first) + + def test_python_created_str(self): + d = {} + first = self.StrInternDict.intern_obj(d, "".join(["ta", "g"])) + second = self.StrInternDict.intern_obj(d, "".join(["t", "ag"])) + self.assertEqual(first, "tag") + self.assertIs(first, second) + self.assertIs(d["tag"], first) + self.assertIs(list(d.values())[0], first) diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/NativeStrNodes.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/NativeStrNodes.java index 9adee41123..3f602d10e4 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/NativeStrNodes.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/cext/capi/transitions/NativeStrNodes.java @@ -42,8 +42,11 @@ import static com.oracle.graal.python.util.PythonUtils.TS_ENCODING; +import com.oracle.graal.python.PythonLanguage; +import com.oracle.graal.python.builtins.objects.str.PString; import com.oracle.graal.python.runtime.nativeaccess.NativeComplex; import com.oracle.graal.python.runtime.nativeaccess.NativeStr; +import com.oracle.graal.python.runtime.object.PFactory; import com.oracle.truffle.api.CompilerAsserts; import com.oracle.truffle.api.dsl.Cached; import com.oracle.truffle.api.dsl.GenerateCached; @@ -139,25 +142,43 @@ static long doIt(Node inliningTarget, long st, TruffleString s, boolean newRef, @GenerateUncached public abstract static class NativeToStrNode extends Node { - public abstract TruffleString execute(Node inliningTarget, long p, boolean transfer); + public abstract Object execute(Node inliningTarget, long p, boolean transfer); + /* + * The result is always an exact str object (PString), made once per struct and remembered + * in the ring: C code that interns strings in a dict (look up, insert if missing, return the + * dict's value) must hand Python the object the dict holds, and a bare Java string stored + * into a container would get a different object once C borrows it from there. + */ @Specialization - static TruffleString doIt(Node inliningTarget, long p, boolean transfer, + static Object doIt(Node inliningTarget, long p, boolean transfer, @Cached InlinedConditionProfile hitProfile, + @Cached InlinedConditionProfile copyProfile, @Cached(inline = false) TruffleString.FromNativePointerWithCompactionUTF32Node fromNativeNode) { - TruffleString s = NativeStr.recall(p); - if (!hitProfile.profile(inliningTarget, s != null)) { - int kind = NativeStr.kind(p); - long length = NativeStr.length(p); - TruffleString.CompactionLevel level = kind == 1 ? TruffleString.CompactionLevel.S1 : kind == 2 ? TruffleString.CompactionLevel.S2 : TruffleString.CompactionLevel.S4; - s = fromNativeNode.execute(NativeStr.data(p), 0, (int) (length * kind), level, true); - NativeStr.remember(p, s); - NativeStr.count(NativeStr.C_C_TO_JAVA, 1); + Object known = NativeStr.recall(p); + Object result; + if (hitProfile.profile(inliningTarget, known instanceof PString)) { + result = known; + } else { + TruffleString s; + if (copyProfile.profile(inliningTarget, known instanceof TruffleString)) { + // a copy Java made of this Java string + s = (TruffleString) known; + } else { + int kind = NativeStr.kind(p); + long length = NativeStr.length(p); + TruffleString.CompactionLevel level = kind == 1 ? TruffleString.CompactionLevel.S1 : kind == 2 ? TruffleString.CompactionLevel.S2 : TruffleString.CompactionLevel.S4; + s = fromNativeNode.execute(NativeStr.data(p), 0, (int) (length * kind), level, true); + NativeStr.count(NativeStr.C_C_TO_JAVA, 1); + } + PString str = PFactory.createString(PythonLanguage.get(inliningTarget), s); + NativeStr.remember(p, str); + result = str; } if (transfer) { NativeStr.decref(p); } - return s; + return result; } } } diff --git a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java index f879470674..4ce190709a 100644 --- a/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeStr.java @@ -65,12 +65,20 @@ * *

* The padding word @36 is ours: bit 31 marks a struct made by this scheme (by Java or by C); the - * low bits hold 1 + the index of an entry of a small ring that maps the struct back to the Java - * string it was made from or converted to. The ring keeps the last {@link #RING_SIZE} crossings. - * An entry is valid for a struct only if it still names that struct's address; a struct is - * freed and re-made only with a fresh word, so a stale entry is never followed. The ring gives - * {@code f(s) is s} for a string that C returns while its struct lives, and saves the second copy - * when C hands the same struct back to Java. + * low bits hold 1 + the index of an entry of a small ring that maps the struct to a Java object: + * the Java string it was copied from, or the str object ({@code PString}) Java made when it read + * the struct. The ring keeps the last {@link #RING_SIZE} crossings. An entry is valid for a struct + * only if it still names that struct's address; a struct is freed and re-made only with a fresh + * word, so a stale entry is never followed. + *

+ * + *

+ * Identity: Java reads a struct as an exact str object, made once per struct and remembered in the + * ring, so the same struct read again (the key and the value of one {@code PyDict_SetItem}, then the + * element of an argument tuple) is the same object while its entry lives. A str that C stores into + * a container is therefore an object the container keeps, and C reading it back gets that object's + * stable stub. A bare Java string passed to C and handed back is an equal, new object + * ({@code f(s) is s} is false), as for any str that crosses through a stub. *

* * Single-threaded: callers hold the GIL. @@ -112,7 +120,7 @@ public final class NativeStr { public static final String[] COUNTER_NAMES = {"str_java_to_c", "str_c_to_java", "str_ring_hit", "str_java_free", "str_c_alloc", "str_c_free", "str_java_bytes", ""}; public static final int RING_SIZE = 4096; // power of two - private static final TruffleString[] RING_STR = new TruffleString[RING_SIZE]; + private static final Object[] RING_OBJ = new Object[RING_SIZE]; private static final long[] RING_PTR = new long[RING_SIZE]; private static int ringCursor; @@ -295,21 +303,24 @@ public static boolean contentEquals(long p, TruffleString s) { return true; } - /** Remembers that struct {@code p} holds the value of {@code s}. */ - public static void remember(long p, TruffleString s) { + /** + * Remembers that struct {@code p} holds the value of {@code o}: the Java string it was copied + * from, or the str object Java made when it read the struct. + */ + public static void remember(long p, Object o) { int k = ringCursor; ringCursor = (k + 1) & (RING_SIZE - 1); - RING_STR[k] = s; + RING_OBJ[k] = o; RING_PTR[k] = p; UNSAFE.putInt(p + OFF_JSLOT, MARK | (k + 1)); } - /** The Java string struct {@code p} was made from or converted to, if still known; else null. */ - public static TruffleString recall(long p) { + /** The object struct {@code p} was made from or converted to, if still known; else null. */ + public static Object recall(long p) { int k = (UNSAFE.getInt(p + OFF_JSLOT) & SLOT_MASK) - 1; if (CompilerDirectives.injectBranchProbability(CompilerDirectives.LIKELY_PROBABILITY, k >= 0 && k < RING_SIZE) && RING_PTR[k] == p) { count(C_RING_HIT, 1); - return RING_STR[k]; + return RING_OBJ[k]; } return null; }