diff --git a/mypyc/doc/tuple_operations.rst b/mypyc/doc/tuple_operations.rst index 4c9da9b894af..32a610a79507 100644 --- a/mypyc/doc/tuple_operations.rst +++ b/mypyc/doc/tuple_operations.rst @@ -33,3 +33,4 @@ Functions --------- * ``len(tup: tuple)`` +* ``hash(tup)`` (for fixed-length tuples) diff --git a/mypyc/irbuild/specialize.py b/mypyc/irbuild/specialize.py index 69cb21a00213..2369f69773d5 100644 --- a/mypyc/irbuild/specialize.py +++ b/mypyc/irbuild/specialize.py @@ -40,8 +40,10 @@ from mypy.types import AnyType, TypeOfAny from mypyc.ir.class_ir import ClassIR from mypyc.ir.ops import ( + ERR_FALSE, BasicBlock, Call, + ComparisonOp, Extend, Integer, LoadErrorValue, @@ -50,6 +52,7 @@ Register, SetAttr, Truncate, + TupleGet, Unreachable, Value, ) @@ -63,12 +66,14 @@ bytes_rprimitive, bytes_writer_rprimitive, c_int_rprimitive, + c_pyssize_t_rprimitive, dict_rprimitive, int16_rprimitive, int32_rprimitive, int64_rprimitive, int_rprimitive, is_any_int, + is_bool_or_bit_rprimitive, is_bool_rprimitive, is_bytes_rprimitive, is_dict_rprimitive, @@ -178,7 +183,15 @@ str_get_item_unsafe_as_int_op, str_range_check_op, ) -from mypyc.primitives.tuple_ops import isinstance_tuple, new_tuple_set_item_op +from mypyc.primitives.tuple_ops import ( + isinstance_tuple, + new_tuple_set_item_op, + tuple_hash_add_op, + tuple_hash_finish_op, + tuple_hash_int_op, + tuple_hash_object_op, + tuple_hash_start_op, +) # Specializers are attempted before compiling the arguments to the # function. Specializers can return None to indicate that they failed @@ -312,6 +325,50 @@ def apply_dunder_specialization( return None +@specialize_function("builtins.hash") +def translate_hash(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None: + """Hash a fixed-length tuple without boxing it (and its items) into a tuple object.""" + if len(expr.args) == 1 and expr.arg_kinds == [ARG_POS]: + if isinstance(builder.node_type(expr.args[0]), RTuple): + t = builder.accept(expr.args[0]) + return builder.coerce(tuple_hash(builder, t, expr.line), int_rprimitive, expr.line) + return None + + +def tuple_hash(builder: IRBuilder, t: Value, line: int) -> Value: + """Return the hash of an unboxed tuple as a C Py_hash_t, like hash() of the boxed tuple.""" + assert isinstance(t.type, RTuple) + acc = builder.call_c(tuple_hash_start_op, [], line) + for i in range(len(t.type.types)): + item_hash = tuple_item_hash(builder, builder.add(TupleGet(t, i, line)), line) + acc = builder.call_c(tuple_hash_add_op, [acc, item_hash], line) + length = Integer(len(t.type.types), c_pyssize_t_rprimitive, line) + return builder.call_c(tuple_hash_finish_op, [acc, length], line) + + +def tuple_item_hash(builder: IRBuilder, item: Value, line: int) -> Value: + """Return the hash of a tuple item as a C Py_hash_t.""" + typ = item.type + if isinstance(typ, RTuple): + return tuple_hash(builder, item, line) + if is_bool_or_bit_rprimitive(typ): + # hash(False) is 0 and hash(True) is 1 + return builder.add(Extend(item, c_pyssize_t_rprimitive, signed=False, line=line)) + if is_tagged(typ) or is_fixed_width_rtype(typ): + # A fixed-width int hashes like the int object it boxes to + value = builder.coerce(item, int_rprimitive, line) + return builder.call_c(tuple_hash_int_op, [value], line) + obj = builder.coerce(item, object_rprimitive, line) + item_hash = builder.call_c(tuple_hash_object_op, [obj], line) + # -1 means that the item couldn't be hashed + check = ComparisonOp( + item_hash, Integer(-1, c_pyssize_t_rprimitive, line), ComparisonOp.NEQ, line + ) + check.error_kind = ERR_FALSE + builder.add(check) + return item_hash + + @specialize_function("builtins.globals") def translate_globals(builder: IRBuilder, expr: CallExpr, callee: RefExpr) -> Value | None: if len(expr.args) == 0: diff --git a/mypyc/lib-rt/CPy.h b/mypyc/lib-rt/CPy.h index d4bd2d8938ce..809bfb40af8b 100644 --- a/mypyc/lib-rt/CPy.h +++ b/mypyc/lib-rt/CPy.h @@ -1164,6 +1164,59 @@ static inline void CPySequenceTuple_SetItemUnsafe(PyObject *tuple, Py_ssize_t in PyTuple_SET_ITEM(tuple, index, value); } +// hash() of a fixed-length tuple, worked out from the hashes of its items without +// building a tuple object. These are the steps of the tuple hash in CPython's +// Objects/tupleobject.c (with the constants in Include/internal/pycore_tuple.h on +// 3.14 and later), which has been the same since Python 3.8. + +#if SIZEOF_PY_UHASH_T > 4 +#define CPY_TUPLE_HASH_XXPRIME_1 ((Py_uhash_t)11400714785074694791ULL) +#define CPY_TUPLE_HASH_XXPRIME_2 ((Py_uhash_t)14029467366897019727ULL) +#define CPY_TUPLE_HASH_XXPRIME_5 ((Py_uhash_t)2870177450012600261ULL) +#define CPY_TUPLE_HASH_XXROTATE(x) (((x) << 31) | ((x) >> 33)) // Rotate left 31 bits +#else +#define CPY_TUPLE_HASH_XXPRIME_1 ((Py_uhash_t)2654435761UL) +#define CPY_TUPLE_HASH_XXPRIME_2 ((Py_uhash_t)2246822519UL) +#define CPY_TUPLE_HASH_XXPRIME_5 ((Py_uhash_t)374761393UL) +#define CPY_TUPLE_HASH_XXROTATE(x) (((x) << 13) | ((x) >> 19)) // Rotate left 13 bits +#endif + +static inline Py_uhash_t CPyTupleHash_Start(void) { + return CPY_TUPLE_HASH_XXPRIME_5; +} + +static inline Py_uhash_t CPyTupleHash_Add(Py_uhash_t acc, Py_hash_t item_hash) { + acc += (Py_uhash_t)item_hash * CPY_TUPLE_HASH_XXPRIME_2; + acc = CPY_TUPLE_HASH_XXROTATE(acc); + return acc * CPY_TUPLE_HASH_XXPRIME_1; +} + +static inline Py_hash_t CPyTupleHash_Finish(Py_uhash_t acc, Py_ssize_t len) { + // Add the length, mangled to keep the historical value of hash(()) + acc += len ^ (CPY_TUPLE_HASH_XXPRIME_5 ^ 3527539UL); + if (acc == (Py_uhash_t)-1) { + return 1546275796; + } + return (Py_hash_t)acc; +} + +// The hash of an int item, the same as hash() gives for an int object +static inline Py_hash_t CPyTupleHash_Int(CPyTagged x) { + if (likely(CPyTagged_CheckShort(x))) { + // An int hashes to its value modulo PyHASH_MODULUS, keeping its sign, except that + // -1 (which signals an error) becomes -2 + Py_ssize_t value = CPyTagged_ShortAsSsize_t(x); + Py_uhash_t magnitude = value < 0 ? -(Py_uhash_t)value : (Py_uhash_t)value; + if (unlikely(magnitude >= PyHASH_MODULUS)) { + magnitude %= PyHASH_MODULUS; + } + Py_hash_t h = value < 0 ? -(Py_hash_t)magnitude : (Py_hash_t)magnitude; + return h == -1 ? -2 : h; + } + // This can't fail for an int + return PyObject_Hash(CPyTagged_LongAsObject(x)); +} + // Exception operations diff --git a/mypyc/primitives/tuple_ops.py b/mypyc/primitives/tuple_ops.py index 09daf5396bf0..cca97262bfa5 100644 --- a/mypyc/primitives/tuple_ops.py +++ b/mypyc/primitives/tuple_ops.py @@ -10,6 +10,7 @@ from mypyc.ir.rtypes import ( bit_rprimitive, c_pyssize_t_rprimitive, + c_size_t_rprimitive, int_rprimitive, list_rprimitive, object_rprimitive, @@ -134,3 +135,42 @@ c_function_name="CPySequenceTuple_GetSlice", error_kind=ERR_MAGIC, ) + +# The steps of hash() for a fixed-length tuple (RTuple), which combine the C hashes +# of its items without building a tuple object (see CPyTupleHash_Start in CPy.h) +tuple_hash_start_op = custom_op( + arg_types=[], + return_type=c_size_t_rprimitive, + c_function_name="CPyTupleHash_Start", + error_kind=ERR_NEVER, +) + +tuple_hash_add_op = custom_op( + arg_types=[c_size_t_rprimitive, c_pyssize_t_rprimitive], + return_type=c_size_t_rprimitive, + c_function_name="CPyTupleHash_Add", + error_kind=ERR_NEVER, +) + +tuple_hash_finish_op = custom_op( + arg_types=[c_size_t_rprimitive, c_pyssize_t_rprimitive], + return_type=c_pyssize_t_rprimitive, + c_function_name="CPyTupleHash_Finish", + error_kind=ERR_NEVER, +) + +# The C hash of an int item +tuple_hash_int_op = custom_op( + arg_types=[int_rprimitive], + return_type=c_pyssize_t_rprimitive, + c_function_name="CPyTupleHash_Int", + error_kind=ERR_NEVER, +) + +# The C hash of any other item, which is -1 on error (the caller checks for it) +tuple_hash_object_op = custom_op( + arg_types=[object_rprimitive], + return_type=c_pyssize_t_rprimitive, + c_function_name="PyObject_Hash", + error_kind=ERR_NEVER, +) diff --git a/mypyc/test-data/irbuild-tuple.test b/mypyc/test-data/irbuild-tuple.test index 56a57b04a6b0..e839c0097995 100644 --- a/mypyc/test-data/irbuild-tuple.test +++ b/mypyc/test-data/irbuild-tuple.test @@ -1244,3 +1244,63 @@ L3: L4: r7 = PyList_AsTuple(r0) return r7 + +[case testTupleHash_64bit] +from typing import Any + +def f(a: int, b: bool, c: Any) -> int: + return hash((a, b, c)) +[out] +def f(a, b, c): + a :: int + b :: bool + c :: object + r0 :: int + r1 :: bool + r2 :: object + r3 :: tuple[int, bool, object] + r4 :: u64 + r5 :: int + r6 :: native_int + r7 :: u64 + r8 :: bool + r9 :: native_int + r10 :: u64 + r11 :: object + r12 :: native_int + r13 :: bit + r14 :: u64 + r15 :: native_int + r16, r17 :: bit + r18, r19, r20 :: int +L0: + r0 = a + r1 = b + r2 = c + r3 = (r0, r1, r2) + r4 = CPyTupleHash_Start() + r5 = r3[0] + r6 = CPyTupleHash_Int(r5) + r7 = CPyTupleHash_Add(r4, r6) + r8 = r3[1] + r9 = extend r8: builtins.bool to native_int + r10 = CPyTupleHash_Add(r7, r9) + r11 = r3[2] + r12 = PyObject_Hash(r11) + r13 = r12 != -1 + r14 = CPyTupleHash_Add(r10, r12) + r15 = CPyTupleHash_Finish(r14, 3) + r16 = r15 <= 4611686018427387903 :: signed + if r16 goto L1 else goto L2 :: bool +L1: + r17 = r15 >= -4611686018427387904 :: signed + if r17 goto L3 else goto L2 :: bool +L2: + r18 = CPyTagged_FromInt64(r15) + r19 = r18 + goto L4 +L3: + r20 = r15 << 1 + r19 = r20 +L4: + return r19 diff --git a/mypyc/test-data/run-tuples.test b/mypyc/test-data/run-tuples.test index a04b89a5070d..d9bcd577abe6 100644 --- a/mypyc/test-data/run-tuples.test +++ b/mypyc/test-data/run-tuples.test @@ -517,3 +517,72 @@ class GoodTuple(tuple): return GoodTuple(tuple(self) * n + (2,)) def __rmul__(self, n: Any) -> Any: return GoodTuple(tuple(self) * n + (3,)) + +[case testTupleHash] +from typing import Any, Tuple + +from mypy_extensions import i64, u16, u32, u64 +from testutil import assertRaises + +def boxed(t: Any) -> int: + # hash() of a tuple object + return hash(t) + +INTS = [0, 1, -1, -2, 2**30, -(2**30), 2**61 - 1, 2**61, -(2**61), -(2**61) - 1, 2**62 - 1, + -(2**62), 2**62, 2**63, -(2**100)] + +def test_ints() -> None: + for a in INTS: + for b in INTS: + assert hash((a, b)) == boxed((a, b)) + assert hash((a,)) == boxed((a,)) + assert hash((a, a, a, a, a)) == boxed((a, a, a, a, a)) + +def test_fixed_width_ints() -> None: + for x in [0, 1, -1, -2, 2**62 - 1, 2**62, -(2**62) - 1, 2**63 - 1, -(2**63)]: + n: i64 = x + assert hash((n, x)) == boxed((n, x)) + for x in [0, 1, 2**62 - 1, 2**62, 2**63, 2**64 - 1]: + n64: u64 = x + assert hash((n64, 1)) == boxed((n64, 1)) + for x in [0, 2**31, 2**32 - 1]: + n32: u32 = x + assert hash((n32, 1)) == boxed((n32, 1)) + for x in [0, 2**16 - 1]: + n16: u16 = x + assert hash((n16, 1)) == boxed((n16, 1)) + +def test_other_items() -> None: + assert hash(()) == boxed(()) + for b in [True, False]: + assert hash((b, 1 > 2)) == boxed((b, 1 > 2)) + for f in [0.0, -0.0, 1.5, float("inf")]: + assert hash((f, "x", None)) == boxed((f, "x", None)) + for o in [None, 5]: + assert hash((o, 1)) == boxed((o, 1)) + assert hash((1, (2, (3, "a")), ())) == boxed((1, (2, (3, "a")), ())) + +def hash_arg(t: Tuple[int, str]) -> int: + return hash(t) + +class Point: + def __init__(self, x: int, y: int, label: str) -> None: + self.x = x + self.y = y + self.label = label + + def __hash__(self) -> int: + return hash((self.x, self.y, self.label)) + +def test_tuple_values() -> None: + assert hash_arg((3, "x")) == boxed((3, "x")) + assert hash(Point(3, -4, "p")) == boxed((3, -4, "p")) + +def test_unhashable_item() -> None: + a: Any = [] + with assertRaises(TypeError, "unhashable type: 'list'"): + hash((1, a)) + with assertRaises(TypeError, "unhashable type: 'list'"): + hash((a, 1)) + with assertRaises(TypeError, "unhashable type: 'list'"): + hash((1, (2, a)))