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..9e0061e769 100644 --- a/graalpython/com.oracle.graal.python.cext/src/complexobject.c +++ b/graalpython/com.oracle.graal.python.cext/src/complexobject.c @@ -29,6 +29,174 @@ 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) +/* 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) +{ + 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_get_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_set_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 +394,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 +421,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..dad90db146 100644 --- a/graalpython/com.oracle.graal.python.cext/src/longobject.c +++ b/graalpython/com.oracle.graal.python.cext/src/longobject.c @@ -67,6 +67,224 @@ 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 +/* 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; + +static GraalPyLongBlock * +graalpy_long_block(void) +{ + GraalPyLongAllocState *st = graalpy_long_state; + GraalPyLongBlock *b = st->free_list; + if (b != NULL) { + st->free_list = graalpy_long_get_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_set_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 +543,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 +693,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 +710,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 +743,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 +769,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 +791,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 +842,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 +1505,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 +1536,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 +1562,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 +1614,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 +1643,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 1efbb7a36b..72c9c1021d 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); } @@ -712,6 +805,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; + } #ifdef GRAALPY_MEM_MMAP_MIN if (ptr != NULL && AS_MEM_HEAD(ptr)->dummy == GRAALPY_MEM_HEAD_MMAP_MAGIC) { // GraalPy change: mapped block mem_head_t *head = AS_MEM_HEAD(ptr); @@ -784,6 +890,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); @@ -2232,6 +2346,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)) { @@ -2279,6 +2397,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)) { @@ -2335,6 +2473,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 { @@ -2428,6 +2652,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) { @@ -2464,6 +2692,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/SequenceStorageNodes.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/builtins/objects/common/SequenceStorageNodes.java index e5f6c45b92..33775dc8a5 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,10 @@ 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.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 +288,8 @@ 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 Empty: case Uninitialized: return false; @@ -317,6 +323,8 @@ 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 Empty: case Uninitialized: return false; @@ -367,6 +375,14 @@ 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; + } } abstract static class NormalizingNode extends PNodeWithContext { @@ -621,6 +637,11 @@ protected static Object doObject(ObjectSequenceStorage storage, int idx) { return storage.getObjectItemNormalized(idx); } + @Specialization + 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 +703,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 +1352,11 @@ protected static void doObject(@SuppressWarnings("unused") Node inliningTarget, storage.setObjectItemNormalized(idx, value); } + @Specialization(guards = "value.isExact()") + 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 +1622,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 +1766,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 = complexOwnedPtrs(self.getState(), 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.getState(), 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 +1807,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 +1833,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 +1867,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 +2342,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 +2358,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 +2375,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 +2389,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 +2593,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 +2714,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 +2736,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 +3013,31 @@ 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); + } + + /** 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; + } + + @Specialization(guards = "isExactComplexOrSame(val)") + static ComplexPtrSequenceStorage doComplexComplex(ComplexPtrSequenceStorage s, @SuppressWarnings("unused") Object val) { + return s; + } + + @Specialization(guards = "!isExactComplexOrSame(val)") + static ObjectSequenceStorage doComplexGeneric(Node inliningTarget, ComplexPtrSequenceStorage s, @SuppressWarnings("unused") Object val) { + return generalizeComplexPtr(PythonLanguage.get(inliningTarget), s); } @Specialization(guards = "!isKnownType(val)") @@ -3012,7 +3116,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 +3240,11 @@ abstract static class CreateEmptyForTypeNode extends SequenceStorageBaseNode { public abstract ArrayBasedSequenceStorage execute(Node inliningTarget, StorageType type, int cap); + @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 +3353,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 +3448,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 +3541,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 +3606,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 +3753,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) { + NativeComplex.decref(s.getState(), 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 +3810,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 +3862,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 +3929,11 @@ public abstract static class GetElementType extends Node { public abstract StorageType execute(Node inliningTarget, SequenceStorage s); + @Specialization + static StorageType type(@SuppressWarnings("unused") ComplexPtrSequenceStorage s) { + return StorageType.ComplexPtr; + } + @Specialization static StorageType type(EmptySequenceStorage s) { return Empty; @@ -4008,6 +4164,23 @@ public abstract static class InsertItemArrayBasedStorageNode extends Node { protected abstract SequenceStorage execute(Node inliningTarget, ArrayBasedSequenceStorage storage, int index, Object value); + @Specialization(guards = "value.isExact()") + static SequenceStorage doComplexPtr(ComplexPtrSequenceStorage storage, int idx, PComplex value) { + storage.insertItem(idx, value); + return storage; + } + + @Specialization(guards = "!isExactComplex(value)") + 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 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 +4608,49 @@ 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); + s.releaseAllAndClear(); + return new ObjectSequenceStorage(boxed); + } + + /** + * 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; + } + + static void releaseOwned(long state, long[] owned) { + for (long p : owned) { + NativeComplex.decref(state, p); + } + } } 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..a86cfb7a86 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; @@ -40,6 +42,12 @@ public PComplex(Object clazz, Shape instanceShape, double real, double imaginary this.imag = imaginary; } + /** Exact type {@code complex} (not a subclass). */ + public boolean isExact() { + Object clazz = getPythonClass(); + return clazz == PythonBuiltinClassType.PComplex || (clazz instanceof PythonBuiltinClass b && b.getType() == PythonBuiltinClassType.PComplex); + } + @Override public boolean equals(Object c) { if (c instanceof PComplex) { 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/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/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..b10bdbd1b9 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) { 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/SequenceFromArrayNode.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/nodes/bytecode_dsl/SequenceFromArrayNode.java index e5ff5b774c..f89cb052ac 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 @@ -126,6 +126,10 @@ SequenceStorage createSequenceStorage(Object[] objectElements, int length) { storage = new ObjectSequenceStorage(objectElements, length); 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"); 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..03cb63b336 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,35 @@ public static boolean doPString(PString left, PString right) { return PGuards.isBuiltinPString(left) && PGuards.isBuiltinPString(right) && left.isMaterialized() && right.isMaterialized() && left.getMaterialized() == right.getMaterialized(); } + /** + * Exact complex numbers are values, like floats (see {@link #doDD}): a list of them keeps native + * structs, and each read makes a new Java object, so two exact complex numbers with the same bits + * are the same object. {@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; + } + return left.isExact() && right.isExact() && Double.doubleToRawLongBits(left.getReal()) == Double.doubleToRawLongBits(right.getReal()) && + Double.doubleToRawLongBits(left.getImag()) == Double.doubleToRawLongBits(right.getImag()); + } + + /** + * 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..9d812fd46d 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,8 @@ 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; /** 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 +2584,21 @@ 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; + } + + /** 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..30ce74024d --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/nativeaccess/NativeComplex.java @@ -0,0 +1,442 @@ +/* + * 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 + * plain value copy that does not refer to the struct (exact complex numbers compare by value under + * {@code is}, like floats). 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) { + return alloc(st, c.getReal(), c.getImag()); + } + + /** 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)); + } + + 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/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/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..ec9a8fcd8f --- /dev/null +++ b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/ComplexPtrSequenceStorage.java @@ -0,0 +1,426 @@ +/* + * 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.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; + private Cleaner cleaner; + + public ComplexPtrSequenceStorage(long state, int capacity) { + this.state = state; + 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 = state; + 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); + } + + // ------------------------------------------------------------------ reference operations + + /** Adds the reference a slot holds. */ + public final void incw(long w) { + if (w != 0) { + NativeComplex.incref(w); + } + } + + /** Drops the reference a slot holds. */ + public final void decw(long w) { + if (w != 0) { + NativeComplex.decref(state, w); + } + } + + public long getState() { + return state; + } + + // ------------------------------------------------------------------ lifetime + + static final class Cleaner extends AsyncHandler.SharedFinalizer.FinalizableReference { + long[] values; + final long state; + + Cleaner(ComplexPtrSequenceStorage storage, AsyncHandler.SharedFinalizer finalizer) { + super(storage, finalizer); + this.values = storage.values; + this.state = storage.state; + } + + @Override + public AsyncHandler.AsyncAction release() { + final long[] v = values; + values = null; + if (v == null) { + return null; + } + return (context, access) -> releaseAll(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(long st, long[] v, int n) { + for (int i = 0; i < n; i++) { + long p = v[i]; + if (p != 0) { + v[i] = 0; + NativeComplex.decref(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(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) { + return NativeComplex.load(language, values[idx]); + } + + /** Overwrites a live slot: materialise, +1 new, write, -1 old. */ + public void setItemNormalized(int idx, PComplex value) { + 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) { + 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/SequenceStorage.java b/graalpython/com.oracle.graal.python/src/com/oracle/graal/python/runtime/sequence/storage/SequenceStorage.java index 7083b7ad47..f04712ab52 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,8 @@ public enum StorageType { Int, Long, Double, + /** Raw pointers to native complex structs. */ + ComplexPtr, Generic; public boolean generalizesFrom(StorageType other) { @@ -42,6 +44,7 @@ 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; default -> true; }; }