Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
107 changes: 96 additions & 11 deletions mypyc/codegen/emitfunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@
RType,
RVec,
is_bool_or_bit_rprimitive,
is_fixed_width_rtype,
is_int32_rprimitive,
is_int64_rprimitive,
is_int_rprimitive,
Expand Down Expand Up @@ -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};")
Expand All @@ -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
):
Expand All @@ -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)
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand All @@ -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]] = {}


Expand Down
24 changes: 14 additions & 10 deletions mypyc/doc/int_operations.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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::

Expand All @@ -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
---------

Expand Down
6 changes: 6 additions & 0 deletions mypyc/ir/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
"""

Expand Down
17 changes: 15 additions & 2 deletions mypyc/ir/rtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
24 changes: 23 additions & 1 deletion mypyc/irbuild/constant_fold.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand Down
26 changes: 26 additions & 0 deletions mypyc/test-data/irbuild-i64.test
Original file line number Diff line number Diff line change
Expand Up @@ -2339,3 +2339,29 @@ def gen() -> Iterator[i64]:
del value # E: "value" cannot be deleted \
# N: Using "__deletable__ = ['<attr>']" in the class body enables "del obj.<attr>"
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
19 changes: 19 additions & 0 deletions mypyc/test-data/irbuild-i8.test
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
21 changes: 21 additions & 0 deletions mypyc/test-data/irbuild-u64.test
Original file line number Diff line number Diff line change
Expand Up @@ -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
21 changes: 21 additions & 0 deletions mypyc/test-data/irbuild-u8.test
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading
Loading