From 499fab75367cbd112fd10a8e8f6ec7d5d04d82e3 Mon Sep 17 00:00:00 2001 From: Jukka Lehtosalo Date: Tue, 24 Nov 2026 14:51:01 +0000 Subject: [PATCH] [mypyc] Give defined semantics for native int shifts In C, a left shift that overflows a signed type (also u8 and u16, which are promoted to int) is undefined behavior. A shift by a negative count or a count that at least the bit width of the type is also undefined. Left shifts now wrap around (two's complement), by shifting using an unsigned type and converting the result back. The shift count is treated as unsigned (similar to NumPy). A count that is negative or at least the bit width evaluates to 0, or -1 for a right shift of a negative value. A constant count within range is compiled into a plain C shift as before. --- mypyc/codegen/emitfunc.py | 107 +++++++++++++++++++++++++++---- mypyc/doc/int_operations.rst | 24 ++++--- mypyc/ir/ops.py | 6 ++ mypyc/ir/rtypes.py | 17 ++++- mypyc/irbuild/constant_fold.py | 24 ++++++- mypyc/test-data/irbuild-i64.test | 26 ++++++++ mypyc/test-data/irbuild-i8.test | 19 ++++++ mypyc/test-data/irbuild-u64.test | 21 ++++++ mypyc/test-data/irbuild-u8.test | 21 ++++++ mypyc/test-data/run-i16.test | 20 ++++++ mypyc/test-data/run-i32.test | 20 ++++++ mypyc/test-data/run-i64.test | 44 ++++++++++++- mypyc/test-data/run-i8.test | 20 ++++++ mypyc/test-data/run-u16.test | 16 +++++ mypyc/test-data/run-u32.test | 16 +++++ mypyc/test-data/run-u8.test | 16 +++++ mypyc/test/test_emitfunc.py | 49 +++++++++++++- 17 files changed, 440 insertions(+), 26 deletions(-) diff --git a/mypyc/codegen/emitfunc.py b/mypyc/codegen/emitfunc.py index 62013e0c34990..ed979200e22bb 100644 --- a/mypyc/codegen/emitfunc.py +++ b/mypyc/codegen/emitfunc.py @@ -85,6 +85,7 @@ RType, RVec, is_bool_or_bit_rprimitive, + is_fixed_width_rtype, is_int32_rprimitive, is_int64_rprimitive, is_int_rprimitive, @@ -928,7 +929,7 @@ def visit_extend(self, op: Extend) -> None: dest = self.reg(op) value = self.reg(op.src) if op.signed: - src_cast = self.emit_signed_int_cast(op.src.type) + src_cast = self.signed_cast_if_tagged(op.src.type) else: src_cast = self.emit_unsigned_int_cast(op.src.type) self.emit_line(f"{dest} = {src_cast}{value};") @@ -938,17 +939,19 @@ def visit_load_global(self, op: LoadGlobal) -> None: self.emit_line(f"{dest} = {op.identifier};", ann=op.ann) def visit_int_op(self, op: IntOp) -> None: + if op.op in (IntOp.LEFT_SHIFT, IntOp.RIGHT_SHIFT) and is_fixed_width_rtype(op.type): + self.emit_native_int_shift(op) + return dest = self.reg(op) lhs = self.reg(op.lhs) rhs = self.reg(op.rhs) if op.op == IntOp.RIGHT_SHIFT: # Signed right shift - lhs = self.emit_signed_int_cast(op.lhs.type) + lhs - rhs = self.emit_signed_int_cast(op.rhs.type) + rhs + lhs = self.signed_cast_if_tagged(op.lhs.type) + lhs + rhs = self.signed_cast_if_tagged(op.rhs.type) + rhs elif ( - op.op in (IntOp.MUL, IntOp.LEFT_SHIFT) - and isinstance(op.type, RPrimitive) - and op.type.is_native_int + op.op == IntOp.MUL + and is_fixed_width_rtype(op.type) and not op.type.is_signed and op.type.size < 4 ): @@ -958,6 +961,61 @@ def visit_int_op(self, op: IntOp) -> None: lhs = f"(unsigned int){lhs}" self.emit_line(f"{dest} = {lhs} {op.op_str[op.op]} {rhs};") + def emit_native_int_shift(self, op: IntOp) -> None: + """Emit a left or right shift with a fixed-width native int result type. + + The left operand is usually of the same type, but it can also be a tagged int, + when untagging an int (a right shift by 1). + + Unlike in C, a left shift wraps around on overflow, and a shift count that is + negative or at least the bit width of the type is defined (like NumPy): the + count is treated as unsigned, and the result is 0, or -1 for a right shift of + a negative value. + """ + rtype = op.type + assert is_fixed_width_rtype(rtype) + dest = self.reg(op) + lhs = self.reg(op.lhs) + rhs = self.reg(op.rhs) + bits = 8 * rtype.size + is_signed_right_shift = op.op == IntOp.RIGHT_SHIFT and rtype.is_signed + + if op.op == IntOp.RIGHT_SHIFT: + # A tagged operand (when untagging an int) is unsigned in C, but the shift must + # be signed to preserve the sign. Native int operands already have the right + # signedness, so they are used as is. + lhs = self.signed_cast_if_tagged(op.lhs.type) + lhs + + def shift(count: str) -> str: + if op.op == IntOp.RIGHT_SHIFT: + return f"{lhs} >> {count}" + unsigned_type = left_shift_unsigned_ctype(rtype) + if unsigned_type is None: + return f"{lhs} << {count}" + # Left shift of a negative value, or one that overflows a signed type, is + # undefined behavior in C, so shift using an unsigned type, which wraps + # around, and convert the result back. + return f"({self.ctype(rtype)})(({unsigned_type}){lhs} << {count})" + + if isinstance(op.rhs, Integer): + if 0 <= op.rhs.value < bits: + self.emit_line(f"{dest} = {shift(rhs)};") + elif is_signed_right_shift: + self.emit_line(f"{dest} = {lhs} >> {bits - 1};") + else: + self.emit_line(f"{dest} = 0;") + return + # A shift count outside [0, bits) is undefined behavior in C. Compare the count + # as unsigned, so that a negative count is also out of range. Compilers generate + # branchless code for this (e.g. lsl, cmp, csel on arm64). + assert isinstance(op.rhs.type, RPrimitive) + count = f"({unsigned_ctype_of_size(op.rhs.type.size)}){rhs}" + if is_signed_right_shift: + # Shifting by bits - 1 gives 0, or -1 if the value is negative + self.emit_line(f"{dest} = {lhs} >> ({count} < {bits} ? {rhs} : {bits - 1});") + else: + self.emit_line(f"{dest} = {count} < {bits} ? {shift(rhs)} : 0;") + def visit_comparison_op(self, op: ComparisonOp) -> None: dest = self.reg(op) lhs = self.reg(op.lhs) @@ -966,18 +1024,18 @@ def visit_comparison_op(self, op: ComparisonOp) -> None: rhs_cast = "" if op.op in (ComparisonOp.SLT, ComparisonOp.SGT, ComparisonOp.SLE, ComparisonOp.SGE): # Always signed comparison op - lhs_cast = self.emit_signed_int_cast(op.lhs.type) - rhs_cast = self.emit_signed_int_cast(op.rhs.type) + lhs_cast = self.signed_cast_if_tagged(op.lhs.type) + rhs_cast = self.signed_cast_if_tagged(op.rhs.type) elif op.op in (ComparisonOp.ULT, ComparisonOp.UGT, ComparisonOp.ULE, ComparisonOp.UGE): # Always unsigned comparison op lhs_cast = self.emit_unsigned_int_cast(op.lhs.type) rhs_cast = self.emit_unsigned_int_cast(op.rhs.type) elif isinstance(op.lhs, Integer) and op.lhs.value < 0: # Force signed ==/!= with negative operand - rhs_cast = self.emit_signed_int_cast(op.rhs.type) + rhs_cast = self.signed_cast_if_tagged(op.rhs.type) elif isinstance(op.rhs, Integer) and op.rhs.value < 0: # Force signed ==/!= with negative operand - lhs_cast = self.emit_signed_int_cast(op.lhs.type) + lhs_cast = self.signed_cast_if_tagged(op.lhs.type) self.emit_line(f"{dest} = {lhs_cast}{lhs} {op.op_str[op.op]} {rhs_cast}{rhs};") def visit_float_op(self, op: FloatOp) -> None: @@ -1184,7 +1242,12 @@ def emit_attribute_error(self, op: Branch, class_name: str, source_attr_name: st if DEBUG_ERRORS: self.emit_line('assert(PyErr_Occurred() != NULL && "failure w/o err!");') - def emit_signed_int_cast(self, type: RType) -> str: + def signed_cast_if_tagged(self, type: RType) -> str: + """Return a C cast prefix that makes a tagged int operand signed. + + CPyTagged is unsigned in C. Return "" for all other types, including + unsigned native ints, which must keep their signedness. + """ if is_tagged(type): return "(Py_ssize_t)" else: @@ -1199,6 +1262,28 @@ def emit_unsigned_int_cast(self, type: RType) -> str: return "" +def left_shift_unsigned_ctype(rtype: RPrimitive) -> str | None: + """Return the unsigned C type to use so that a native int left shift wraps around. + + Signed types need this, since a left shift of a negative value, or one that overflows, + is undefined behavior in C. Return None if the shift already uses an unsigned C type + at least as wide as int (u32 and u64). + + C promotes narrower unsigned types (u8 and u16) to (signed) int. A valid count (less + than the bit width) can't overflow int (at most 0xFFFF << 15), but use an unsigned + type anyway, so that the shift stays defined even without the range check on the + count. This generates the same machine code. Only the left operand needs a cast, + since it alone determines the type of a shift. + """ + if not rtype.is_signed and rtype.size >= 4: + return None + return unsigned_ctype_of_size(max(rtype.size, 4)) + + +def unsigned_ctype_of_size(size: int) -> str: + return f"uint{8 * size}_t" + + _translation_table: Final[dict[int, str]] = {} diff --git a/mypyc/doc/int_operations.rst b/mypyc/doc/int_operations.rst index 31b64d8d172d8..86247217fc9ef 100644 --- a/mypyc/doc/int_operations.rst +++ b/mypyc/doc/int_operations.rst @@ -214,16 +214,6 @@ Operators * Comparisons (``==``, ``!=``, ``<``, etc.) * Augmented assignment (``x += y``, etc.) -If one of the above native integer operations overflows or underflows -with signed operands, the behavior is undefined. Signed native integer -types should only be used if all possible values are small enough for -the type. For this reason, the arbitrary-precision ``int`` type is -recommended for signed values unless the performance of integer -operations is critical. - -Operations on unsigned integers (``u64``, ``u32``, ``u16`` and ``u8``) wrap -around on overflow. - It's a compile-time error to mix different native integer types in a binary operation such as addition. An explicit conversion is required:: @@ -244,6 +234,20 @@ and the ``int`` operand is coerced to the native integer type:: b = 1 - x # Similarly, type of "b" is "i64" +If one of the above native integer arithmetic operations overflows or underflows +with signed operands, the behavior is undefined. Signed native integer +types should only be used if all possible values are small enough for +the type. For this reason, the arbitrary-precision ``int`` type is +recommended for signed values unless the performance of integer +operations is critical. + +Operations on unsigned integers (``u64``, ``u32``, ``u16`` and ``u8``) wrap +around on overflow. Left shifts (``<<``) wrap around on overflow for both signed +and unsigned types. For example, ``i8(64) << 1`` is ``-128``. + +Shifting by a negative count or by at least the bit width gives 0, or +-1 for a right shift of a negative value (similar to NumPy). + Functions --------- diff --git a/mypyc/ir/ops.py b/mypyc/ir/ops.py index 0dbbeab4c95ae..e5e4762913673 100644 --- a/mypyc/ir/ops.py +++ b/mypyc/ir/ops.py @@ -1443,6 +1443,12 @@ class IntOp(RegisterOp): compatible representations. Fixed-width integers, short_int_rprimitive, bool_rprimitive and bit_rprimitive are supported. + For fixed-width native int types, shifts are defined for all operand + values, unlike in C. Left shift wraps around on overflow (two's + complement). The shift count is treated as unsigned, so a count that is + negative or at least the bit width of the type gives 0, or -1 for a right + shift of a negative value (like NumPy). + For tagged (arbitrary-precision) integer ops look at mypyc.primitives.int_ops. """ diff --git a/mypyc/ir/rtypes.py b/mypyc/ir/rtypes.py index cc56c333e3122..86431283c0d48 100644 --- a/mypyc/ir/rtypes.py +++ b/mypyc/ir/rtypes.py @@ -1433,8 +1433,21 @@ def wrap_unsigned_native_int(rtype: RType, n: int) -> int: Return n unchanged for other types. """ if is_fixed_width_rtype(rtype) and not rtype.is_signed: - # The largest value of an unsigned type is also a mask of all its bits - return n & native_int_bounds(rtype)[1] + return wrap_native_int(rtype, n) + return n + + +def wrap_native_int(rtype: RType, n: int) -> int: + """Wrap n around to the range of rtype if it's a native int type. + + This is two's complement wrap-around, such as for a left shift that overflows + (e.g. i8(64) << 1 is -128) or unsigned negation (e.g. -u8(1) is 255). + Return n unchanged for other types. + """ + if is_fixed_width_rtype(rtype): + lo, hi = native_int_bounds(rtype) + # The size of the range is a power of two, so hi - lo is a mask of all its bits + return ((n - lo) & (hi - lo)) + lo return n diff --git a/mypyc/irbuild/constant_fold.py b/mypyc/irbuild/constant_fold.py index 69a3b9893d2de..fb62538f929f1 100644 --- a/mypyc/irbuild/constant_fold.py +++ b/mypyc/irbuild/constant_fold.py @@ -26,7 +26,12 @@ UnaryExpr, Var, ) -from mypyc.ir.rtypes import wrap_unsigned_native_int +from mypyc.ir.rtypes import ( + RPrimitive, + is_fixed_width_rtype, + wrap_native_int, + wrap_unsigned_native_int, +) from mypyc.irbuild.util import bytes_from_str if TYPE_CHECKING: @@ -80,6 +85,10 @@ def constant_fold_expr_inner(builder: IRBuilder, expr: Expression) -> ConstantVa left = constant_fold_expr(builder, expr.left) right = constant_fold_expr(builder, expr.right) if left is not None and right is not None: + if expr.op in ("<<", ">>") and isinstance(left, int) and isinstance(right, int): + rtype = builder.node_type(expr) + if is_fixed_width_rtype(rtype): + return constant_fold_native_int_shift(rtype, expr.op, left, right) return constant_fold_binary_op_extended(expr.op, left, right) elif isinstance(expr, UnaryExpr): value = constant_fold_expr(builder, expr.expr) @@ -88,6 +97,19 @@ def constant_fold_expr_inner(builder: IRBuilder, expr: Expression) -> ConstantVa return None +def constant_fold_native_int_shift(rtype: RPrimitive, op: str, left: int, right: int) -> int: + """Fold a shift of a fixed-width native int (see IntOp for the semantics). + + A count that is negative or at least the bit width gives 0, or -1 for a right shift + of a negative value. A left shift wraps around, also for signed types. + """ + if not 0 <= right < 8 * rtype.size: + return -1 if op == ">>" and left < 0 else 0 + if op == ">>": + return left >> right + return wrap_native_int(rtype, left << right) + + def constant_fold_binary_op_extended( op: str, left: ConstantValue, right: ConstantValue ) -> ConstantValue | None: diff --git a/mypyc/test-data/irbuild-i64.test b/mypyc/test-data/irbuild-i64.test index 023e9ccf7af27..fa64b4da2f991 100644 --- a/mypyc/test-data/irbuild-i64.test +++ b/mypyc/test-data/irbuild-i64.test @@ -2339,3 +2339,29 @@ def gen() -> Iterator[i64]: del value # E: "value" cannot be deleted \ # N: Using "__deletable__ = ['']" in the class body enables "del obj." yield 0 + +[case testI64ConstantFoldShiftByCountOutOfRange] +from typing import Final +from mypy_extensions import i64 + +ONE: Final[i64] = 1 +NEG: Final[i64] = -5 + +def f() -> None: + a = ONE << 64 + b = NEG << -ONE + c = NEG >> 64 + d = NEG >> -ONE + e = ONE >> 64 + g = NEG >> 2 +[out] +def f(): + a, b, c, d, e, g :: i64 +L0: + a = 0 + b = 0 + c = -1 + d = -1 + e = 0 + g = -2 + return 1 diff --git a/mypyc/test-data/irbuild-i8.test b/mypyc/test-data/irbuild-i8.test index 6ce4ec9eb017b..8ba2bbfb83a48 100644 --- a/mypyc/test-data/irbuild-i8.test +++ b/mypyc/test-data/irbuild-i8.test @@ -81,6 +81,25 @@ L4: L5: return r6 +[case testI8ConstantFoldLeftShiftWrapsAround] +from typing import Final +from mypy_extensions import i8 + +ONE: Final[i8] = 1 + +def f() -> None: + a = ONE << 7 + b = (ONE << 7) >> 7 + d = ONE << 6 +[out] +def f(): + a, b, d :: i8 +L0: + a = -128 + b = -1 + d = 64 + return 1 + [case testI8DetectOutOfRangeLiterals] from mypy_extensions import i8 diff --git a/mypyc/test-data/irbuild-u64.test b/mypyc/test-data/irbuild-u64.test index cfad3e7a11348..1abe1f1f721b6 100644 --- a/mypyc/test-data/irbuild-u64.test +++ b/mypyc/test-data/irbuild-u64.test @@ -566,3 +566,24 @@ L0: r1 = box(int, x) r2 = CPyList_SetItemInt64(a, r0, r1) return 1 + +[case testU64ConstantFoldShiftByCountOutOfRange] +from typing import Final +from mypy_extensions import u64 + +ONE: Final[u64] = 1 + +def f() -> None: + a = ONE << -ONE + b = ONE << ~ONE + c = ONE << 64 + d = ONE >> -ONE +[out] +def f(): + a, b, c, d :: u64 +L0: + a = 0 + b = 0 + c = 0 + d = 0 + return 1 diff --git a/mypyc/test-data/irbuild-u8.test b/mypyc/test-data/irbuild-u8.test index 03843e2afa51f..6ce99141f8c27 100644 --- a/mypyc/test-data/irbuild-u8.test +++ b/mypyc/test-data/irbuild-u8.test @@ -742,3 +742,24 @@ L3: goto L1 L4: return 1 + +[case testU8ConstantFoldShiftByCountOutOfRange] +from typing import Final +from mypy_extensions import u8 + +ONE: Final[u8] = 1 + +def f() -> None: + a = ONE << -ONE + b = ONE << 8 + c = ONE << 7 + d = ONE >> 8 +[out] +def f(): + a, b, c, d :: u8 +L0: + a = 0 + b = 0 + c = 128 + d = 0 + return 1 diff --git a/mypyc/test-data/run-i16.test b/mypyc/test-data/run-i16.test index 6ce77ba836122..b19456bf83416 100644 --- a/mypyc/test-data/run-i16.test +++ b/mypyc/test-data/run-i16.test @@ -125,6 +125,26 @@ def test_simple_arithmetic_ops() -> None: assert abs(neg_one) == 1 assert abs(zero) == 0 +def test_left_shift_wraps_around() -> None: + max_i16: i16 = 2**15 - 1 + int() + min_i16: i16 = -2**15 + int() + one: i16 = 1 + int() + assert max_i16 << one == -2 + assert min_i16 << one == 0 + assert -one << (one * 15) == min_i16 + +def test_shift_count_out_of_range() -> None: + one: i16 = 1 + int() + neg: i16 = -5 + int() + width: i16 = 16 + int() + for n in [width, -one, -width]: + assert one << n == 0 + assert one >> n == 0 + assert neg >> n == -1 + # The largest valid count + assert one << (width - one) == -2**15 + assert neg >> (width - one) == -1 + def test_bitwise_ops() -> None: x: i16 = 13855 + int() y: i16 = 367 + int() diff --git a/mypyc/test-data/run-i32.test b/mypyc/test-data/run-i32.test index a094889e5c464..ebff99d7c8cb8 100644 --- a/mypyc/test-data/run-i32.test +++ b/mypyc/test-data/run-i32.test @@ -125,6 +125,26 @@ def test_simple_arithmetic_ops() -> None: assert abs(neg_one) == 1 assert abs(zero) == 0 +def test_left_shift_wraps_around() -> None: + max_i32: i32 = 2**31 - 1 + int() + min_i32: i32 = -2**31 + int() + one: i32 = 1 + int() + assert max_i32 << one == -2 + assert min_i32 << one == 0 + assert -one << (one * 31) == min_i32 + +def test_shift_count_out_of_range() -> None: + one: i32 = 1 + int() + neg: i32 = -5 + int() + width: i32 = 32 + int() + for n in [width, -one, -width]: + assert one << n == 0 + assert one >> n == 0 + assert neg >> n == -1 + # The largest valid count + assert one << (width - one) == -2**31 + assert neg >> (width - one) == -1 + def test_bitwise_ops() -> None: x: i32 = 1920687484 + int() y: i32 = 383354614 + int() diff --git a/mypyc/test-data/run-i64.test b/mypyc/test-data/run-i64.test index 7113eaaed26d7..a1c324d68f7cc 100644 --- a/mypyc/test-data/run-i64.test +++ b/mypyc/test-data/run-i64.test @@ -1,6 +1,6 @@ [case testI64BasicOps] import sys -from typing import List, Any, Tuple, Union +from typing import List, Any, Tuple, Union, Final from mypy_extensions import i64, i32, i16 @@ -213,6 +213,48 @@ def test_simple_arithmetic_ops() -> None: assert abs(neg_one) == 1 assert abs(zero) == 0 +def test_left_shift_wraps_around() -> None: + max_i64: i64 = 2**63 - 1 + int() + min_i64: i64 = -2**63 + int() + one: i64 = 1 + int() + assert max_i64 << one == -2 + assert min_i64 << one == 0 + assert -one << (one * 63) == min_i64 + x = max_i64 + x <<= one + one + assert x == -4 + +ONE_I64: Final[i64] = 1 + +def test_left_shift_wraps_around_constant() -> None: + assert ONE_I64 << 63 == -2**63 + assert (ONE_I64 << 63) >> 63 == -1 + +def test_shift_count_out_of_range() -> None: + one: i64 = 1 + int() + neg: i64 = -5 + int() + width: i64 = 64 + int() + for n in [width, width + one, -one, -2**63 + int()]: + assert one << n == 0 + assert neg << n == 0 + assert one >> n == 0 + assert neg >> n == -1 + x = neg + x <<= n + assert x == 0 + x = neg + x >>= n + assert x == -1 + # The largest valid count + assert one << (width - one) == -2**63 + assert neg >> (width - one) == -1 + # Constant counts + assert neg << 64 == 0 + assert neg << -1 == 0 + assert neg >> 64 == -1 + assert one >> 65 == 0 + assert neg >> -1 == -1 + def test_bitwise_ops() -> None: x: i64 = 7997307308812232241 + int() y: i64 = 4333433528471475340 + int() diff --git a/mypyc/test-data/run-i8.test b/mypyc/test-data/run-i8.test index 82b653c2d6605..609ee1e2be600 100644 --- a/mypyc/test-data/run-i8.test +++ b/mypyc/test-data/run-i8.test @@ -56,6 +56,26 @@ def test_operations() -> None: assert abs(x) == 65 assert abs(y) == 12 +def test_left_shift_wraps_around() -> None: + max_i8: i8 = 2**7 - 1 + int() + min_i8: i8 = -2**7 + int() + one: i8 = 1 + int() + assert max_i8 << one == -2 + assert min_i8 << one == 0 + assert -one << (one * 7) == min_i8 + +def test_shift_count_out_of_range() -> None: + one: i8 = 1 + int() + neg: i8 = -5 + int() + width: i8 = 8 + int() + for n in [width, -one, -width]: + assert one << n == 0 + assert one >> n == 0 + assert neg >> n == -1 + # The largest valid count + assert one << (width - one) == -2**7 + assert neg >> (width - one) == -1 + def test_conversions() -> None: assert to_i8(127) == 127 assert to_i8(128) == -128 diff --git a/mypyc/test-data/run-u16.test b/mypyc/test-data/run-u16.test index 8b9c0ab0efca3..475e28cc7e808 100644 --- a/mypyc/test-data/run-u16.test +++ b/mypyc/test-data/run-u16.test @@ -86,6 +86,22 @@ def test_simple_arithmetic_ops() -> None: assert abs(neg_one) == 65535 assert abs(zero) == 0 +def test_left_shift_wraps_around() -> None: + one: u16 = 1 + int() + max_u16: u16 = 65535 + int() + assert max_u16 << one == 65534 + assert max_u16 << (one * 15) == 32768 + +def test_shift_count_out_of_range() -> None: + one: u16 = 1 + int() + max_u16: u16 = 65535 + int() + width: u16 = 16 + int() + for n in [width, -one]: + assert max_u16 << n == 0 + assert max_u16 >> n == 0 + # The largest valid count + assert max_u16 >> (width - one) == 1 + def test_bitwise_ops() -> None: x: u16 = 47384 + int() y: u16 = 20239 + int() diff --git a/mypyc/test-data/run-u32.test b/mypyc/test-data/run-u32.test index 026d6fee311ca..ce84803e42e7f 100644 --- a/mypyc/test-data/run-u32.test +++ b/mypyc/test-data/run-u32.test @@ -113,6 +113,22 @@ def test_simple_arithmetic_ops() -> None: assert abs(neg_one) == 4294967295 assert abs(zero) == 0 +def test_left_shift_wraps_around() -> None: + one: u32 = 1 + int() + max_u32: u32 = 4294967295 + int() + assert max_u32 << one == 4294967294 + assert max_u32 << (one * 31) == 2147483648 + +def test_shift_count_out_of_range() -> None: + one: u32 = 1 + int() + max_u32: u32 = 4294967295 + int() + width: u32 = 32 + int() + for n in [width, -one]: + assert max_u32 << n == 0 + assert max_u32 >> n == 0 + # The largest valid count + assert max_u32 >> (width - one) == 1 + def test_bitwise_ops() -> None: x: u32 = 47384 + int() y: u32 = 20239 + int() diff --git a/mypyc/test-data/run-u8.test b/mypyc/test-data/run-u8.test index 5db54396f0fe8..0a9c47dea1c99 100644 --- a/mypyc/test-data/run-u8.test +++ b/mypyc/test-data/run-u8.test @@ -86,6 +86,22 @@ def test_simple_arithmetic_ops() -> None: assert abs(neg_one) == 255 assert abs(zero) == 0 +def test_left_shift_wraps_around() -> None: + one: u8 = 1 + int() + max_u8: u8 = 255 + int() + assert max_u8 << one == 254 + assert one << (one * 7) == 128 + +def test_shift_count_out_of_range() -> None: + one: u8 = 1 + int() + max_u8: u8 = 255 + int() + width: u8 = 8 + int() + for n in [width, -one]: + assert max_u8 << n == 0 + assert max_u8 >> n == 0 + # The largest valid count + assert max_u8 >> (width - one) == 1 + def test_bitwise_ops() -> None: x: u8 = 184 + int() y: u8 = 79 + int() diff --git a/mypyc/test/test_emitfunc.py b/mypyc/test/test_emitfunc.py index e3f6a3e0ea1d7..90c364b5a0730 100644 --- a/mypyc/test/test_emitfunc.py +++ b/mypyc/test/test_emitfunc.py @@ -66,6 +66,7 @@ c_pointer_rprimitive, cstring_rprimitive, dict_rprimitive, + int16_rprimitive, int32_rprimitive, int64_rprimitive, int_rprimitive, @@ -128,6 +129,7 @@ def add_local(name: str, rtype: RType) -> Register: self.u32 = add_local("u32", uint32_rprimitive) self.u32_1 = add_local("u32_1", uint32_rprimitive) self.ptr = add_local("ptr", pointer_rprimitive) + self.i16 = add_local("i16", int16_rprimitive) self.t = add_local("t", RTuple([int_rprimitive, bool_rprimitive])) self.tt = add_local( "tt", RTuple([RTuple([int_rprimitive, bool_rprimitive]), bool_rprimitive]) @@ -1008,7 +1010,7 @@ def test_int_op_narrow_unsigned(self) -> None: ) self.assert_emit( IntOp(uint16_rprimitive, self.u16, self.u16_1, IntOp.LEFT_SHIFT, 1), - """cpy_r_r0 = (unsigned int)cpy_r_u16 << cpy_r_u16_1;""", + """cpy_r_r0 = (uint16_t)cpy_r_u16_1 < 16 ? (uint16_t)((uint32_t)cpy_r_u16 << cpy_r_u16_1) : 0;""", ) self.assert_emit( IntOp(uint8_rprimitive, self.u8, self.u8_1, IntOp.MUL, 1), @@ -1023,6 +1025,51 @@ def test_int_op_narrow_unsigned(self) -> None: """cpy_r_r0 = cpy_r_u32 * cpy_r_u32_1;""", ) + def test_int_op_native_int_shift(self) -> None: + # Signed left shift is calculated using an unsigned type, so that it wraps around + self.assert_emit( + IntOp(int64_rprimitive, self.i64, Integer(3, int64_rprimitive), IntOp.LEFT_SHIFT, 1), + """cpy_r_r0 = (int64_t)((uint64_t)cpy_r_i64 << 3);""", + ) + # Narrow types are promoted to (signed) int in C + self.assert_emit( + IntOp(int16_rprimitive, self.i16, Integer(3, int16_rprimitive), IntOp.LEFT_SHIFT, 1), + """cpy_r_r0 = (int16_t)((uint32_t)cpy_r_i16 << 3);""", + ) + # A count that is negative or at least the bit width gives 0, or -1 for a right + # shift of a negative value + self.assert_emit( + IntOp(uint32_rprimitive, self.u32, self.u32_1, IntOp.LEFT_SHIFT, 1), + """cpy_r_r0 = (uint32_t)cpy_r_u32_1 < 32 ? cpy_r_u32 << cpy_r_u32_1 : 0;""", + ) + self.assert_emit( + IntOp(int64_rprimitive, self.i64, self.i64_1, IntOp.RIGHT_SHIFT, 1), + """cpy_r_r0 = cpy_r_i64 >> ((uint64_t)cpy_r_i64_1 < 64 ? cpy_r_i64_1 : 63);""", + ) + self.assert_emit( + IntOp(uint8_rprimitive, self.u8, self.u8_1, IntOp.RIGHT_SHIFT, 1), + """cpy_r_r0 = (uint8_t)cpy_r_u8_1 < 8 ? cpy_r_u8 >> cpy_r_u8_1 : 0;""", + ) + # Constant count out of range + self.assert_emit( + IntOp(int64_rprimitive, self.i64, Integer(-1, int64_rprimitive), IntOp.LEFT_SHIFT, 1), + """cpy_r_r0 = 0;""", + ) + self.assert_emit( + IntOp(int64_rprimitive, self.i64, Integer(64, int64_rprimitive), IntOp.RIGHT_SHIFT, 1), + """cpy_r_r0 = cpy_r_i64 >> 63;""", + ) + # When untagging, the tagged operand is unsigned in C, but the shift must be signed + self.assert_emit( + IntOp(int64_rprimitive, self.n, Integer(1, int64_rprimitive), IntOp.RIGHT_SHIFT, 1), + """cpy_r_r0 = (Py_ssize_t)cpy_r_n >> 1;""", + ) + # Internal shifts of tagged values have counts that are known to be valid + self.assert_emit( + IntOp(short_int_rprimitive, self.s1, self.s2, IntOp.LEFT_SHIFT, 1), + """cpy_r_r0 = cpy_r_s1 << cpy_r_s2;""", + ) + def test_comparison_op(self) -> None: # signed self.assert_emit(