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
4 changes: 2 additions & 2 deletions mypyc/ir/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -1796,10 +1796,10 @@ def __init__(self, src: Value, field: str, item: Value, line: int = -1) -> None:
self.field = field

def sources(self) -> list[Value]:
return [self.src]
return [self.src, self.item]

def set_sources(self, new: list[Value]) -> None:
(self.src,) = new
self.src, self.item = new

def stolen(self) -> list[Value]:
return [self.src]
Expand Down
116 changes: 104 additions & 12 deletions mypyc/irbuild/for_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,13 @@
from mypyc.irbuild.context import FuncInfo
from mypyc.irbuild.env_class import add_vars_to_env, finalize_env_class, setup_env_class
from mypyc.irbuild.targets import AssignmentTargetRegister, AssignmentTargetTuple
from mypyc.irbuild.vec import vec_append, vec_create, vec_get_item_unsafe, vec_init_item_unsafe
from mypyc.irbuild.vec import (
vec_append,
vec_create,
vec_get_item_unsafe,
vec_init_item_unsafe,
vec_set_len_unsafe,
)
from mypyc.primitives.dict_ops import (
dict_check_size_op,
dict_item_iter_op,
Expand All @@ -102,6 +108,7 @@
list_get_item_int64_op,
list_get_item_unsafe_op,
new_list_set_item_op,
new_list_set_size_op,
)
from mypyc.primitives.misc_ops import stop_async_iteration_op
from mypyc.primitives.registry import CFunctionDescription
Expand Down Expand Up @@ -197,11 +204,12 @@ def for_loop_helper_with_index(
body_insts: Callable[[Value], None],
line: int,
length: Value,
) -> None:
) -> Register:
"""Generate IR for a sequence iteration.

This function only works for sequence type. Compared to for_loop_helper,
it would feed iteration index to body_insts.
it would feed iteration index to body_insts. Return the index register,
which holds the number of iterations after the loop.

Args:
index: the loop index Lvalue
Expand Down Expand Up @@ -245,19 +253,26 @@ def for_loop_helper_with_index(
builder.pop_loop_stack()

builder.activate_block(exit_block)
return for_gen.index_target


def can_preallocate_from_generator(builder: IRBuilder, gen: GeneratorExpr) -> bool:
def can_preallocate_from_generator(
builder: IRBuilder, gen: GeneratorExpr, *, resizable: bool = False
) -> bool:
"""Can a sequence be built from a generator expression with a preallocated length?

This requires a single loop without conditions over a sequence of known length.
If the length of the sequence can change during iteration (e.g. a list), the
built sequence must be resizable, since the preallocated length can be wrong.
"""
if not (len(gen.sequences) == 1 and len(gen.indices) == 1 and len(gen.condlists[0]) == 0):
return False
rtype = builder.node_type(gen.sequences[0])
if isinstance(rtype, RTuple):
# for_loop_helper_with_index crashes for empty tuples
return bool(rtype.types)
if not resizable and sequence_length_can_change(builder, gen.sequences[0]):
return False
return is_indexed_sequence_rprimitive(rtype) or isinstance(rtype, RVec)


Expand All @@ -270,12 +285,27 @@ def is_indexed_sequence_rprimitive(rtype: RType) -> bool:
return is_sequence_rprimitive(rtype) and not is_bytearray_rprimitive(rtype)


def sequence_length_can_change(builder: IRBuilder, expr: Expression) -> bool:
"""Can the length of a sequence change while we iterate over it?

A list can be modified in the loop body, or by another thread. This isn't
possible if the length is known at compile time, since the list is then
created by the expression (e.g. a list display), and nothing else refers to it.
"""
rtype = builder.node_type(expr)
if not is_list_rprimitive(rtype):
return False
return get_expr_length(builder, expr) is None


def sequence_from_generator_preallocate_helper(
builder: IRBuilder,
gen: GeneratorExpr,
empty_op_llbuilder: Callable[[Value, int], Value],
set_item_op: Callable[[Value, Value, Value, int], None],
after_first_init: GenFunc | None = None,
append_op: Callable[[Value, Value, Value, int], Value] | None = None,
set_size_op: Callable[[Value, Value, int], Value] | None = None,
) -> Value | None:
"""Generate a new tuple or list from a simple generator expression.

Expand All @@ -300,8 +330,20 @@ def sequence_from_generator_preallocate_helper(
implementation.
after_first_init: Optional function that generates instructions to run after the
sequence has been evaluated (see comprehension_helper).
append_op: Optional function that appends an item to a sequence, when the
target position is at or after the preallocated length. It's called with
Self, Target position and New Value, and returns the resulting sequence
(which can be a new value, e.g. for vecs and tuples).
set_size_op: Optional function that reduces the length of a sequence, dropping
uninitialized items at the end. It's called with Self and New Length, and
returns the resulting sequence.

If the length of the original sequence can change during iteration (e.g. it's a
list), append_op and set_size_op are required, since the preallocated length can
be wrong. If they aren't given, return None for such sequences.
"""
if can_preallocate_from_generator(builder, gen):
resizable = append_op is not None and set_size_op is not None
if can_preallocate_from_generator(builder, gen, resizable=resizable):
line = gen.line
sequence_expr = gen.sequences[0]
rtype = builder.node_type(sequence_expr)
Expand Down Expand Up @@ -344,16 +386,48 @@ def sequence_from_generator_preallocate_helper(

target_op = empty_op_llbuilder(length, line)

def set_item(item_index: Value) -> None:
if not sequence_length_can_change(builder, sequence_expr):

def set_item(item_index: Value) -> None:
with builder.enter_borrow_scope(line):
e = builder.accept(gen.left_expr)
set_item_op(target_op, item_index, e, line)

for_loop_helper_with_index(
builder, gen.indices[0], sequence_expr, sequence, set_item, line, length
)
return target_op

# The original sequence can grow or shrink while we iterate over it (e.g. if
# it's modified in the loop body). Like CPython, we include all items that
# we see, so the preallocated length can be wrong.
assert append_op is not None and set_size_op is not None
target = builder.ensure_register(target_op)

def update_target(value: Value) -> None:
if value is not target:
builder.assign(target, value, line)

def set_or_append_item(item_index: Value) -> None:
with builder.enter_borrow_scope(line):
e = builder.accept(gen.left_expr)
set_item_op(target_op, item_index, e, line)

for_loop_helper_with_index(
builder, gen.indices[0], sequence_expr, sequence, set_item, line, length
set_block, append_block, next_block = BasicBlock(), BasicBlock(), BasicBlock()
fits = builder.binary_op(item_index, length, "<", line)
builder.add_bool_branch(fits, set_block, append_block)
builder.activate_block(set_block)
set_item_op(target, item_index, e, line)
builder.goto(next_block)
builder.activate_block(append_block)
update_target(append_op(target, item_index, e, line))
builder.goto_and_activate(next_block)

index = for_loop_helper_with_index(
builder, gen.indices[0], sequence_expr, sequence, set_or_append_item, line, length
)

return target_op
# If the sequence shrank, drop the items at the end that we didn't set. After the
# loop, the index is the number of items we set or appended.
update_target(set_size_op(target, index, line))
return target
return None


Expand All @@ -372,13 +446,23 @@ def translate_list_comprehension(
def set_item(x: Value, y: Value, z: Value, line: int) -> None:
builder.call_c(new_list_set_item_op, [x, y, z], line)

def append(x: Value, y: Value, z: Value, line: int) -> Value:
builder.primitive_op(list_append_op, [x, z], line)
return x

def set_size(x: Value, y: Value, line: int) -> Value:
builder.call_c(new_list_set_size_op, [x, y], line)
return x

# Try simplest list comprehension, otherwise fall back to general one
val = sequence_from_generator_preallocate_helper(
builder,
gen,
empty_op_llbuilder=builder.builder.new_list_op_with_length,
set_item_op=set_item,
after_first_init=after_first_init,
append_op=append,
set_size_op=set_size,
)
if val is not None:
return val
Expand Down Expand Up @@ -504,6 +588,12 @@ def translate_vec_comprehension(
def set_item(x: Value, y: Value, z: Value, line: int) -> None:
vec_init_item_unsafe(builder.builder, x, y, z, line)

def append(x: Value, y: Value, z: Value, line: int) -> Value:
return vec_append(builder.builder, x, z, line)

def set_size(x: Value, y: Value, line: int) -> Value:
return vec_set_len_unsafe(builder.builder, x, y, line)

# Try simplest comprehension, otherwise fall back to general one
val = sequence_from_generator_preallocate_helper(
builder,
Expand All @@ -512,6 +602,8 @@ def set_item(x: Value, y: Value, z: Value, line: int) -> None:
builder.builder, vec_type, length, line, capacity=capacity
),
set_item_op=set_item,
append_op=append,
set_size_op=set_size,
)
if val is not None:
return val
Expand Down
12 changes: 11 additions & 1 deletion mypyc/irbuild/specialize.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,9 @@
)
from mypyc.primitives.tuple_ops import (
isinstance_tuple,
new_tuple_set_item_grow_op,
new_tuple_set_item_op,
new_tuple_set_size_op,
tuple_hash_add_op,
tuple_hash_finish_op,
tuple_hash_int_op,
Expand Down Expand Up @@ -548,19 +550,27 @@ def translate_tuple_from_generator_call(
len(expr.args) == 1
and expr.arg_kinds[0] == ARG_POS
and isinstance(expr.args[0], GeneratorExpr)
and can_preallocate_from_generator(builder, expr.args[0])
and can_preallocate_from_generator(builder, expr.args[0], resizable=True)
):
gen = expr.args[0]

def set_item(x: Value, y: Value, z: Value, line: int) -> None:
builder.call_c(new_tuple_set_item_op, [x, y, z], line)

def set_item_grow(x: Value, y: Value, z: Value, line: int) -> Value:
return builder.call_c(new_tuple_set_item_grow_op, [x, y, z], line)

def set_size(x: Value, y: Value, line: int) -> Value:
return builder.call_c(new_tuple_set_size_op, [x, y], line)

with comprehension_scope(builder, gen):
return sequence_from_generator_preallocate_helper(
builder,
gen,
empty_op_llbuilder=builder.builder.new_tuple_with_length,
set_item_op=set_item,
append_op=set_item_grow,
set_size_op=set_size,
)
return None

Expand Down
12 changes: 12 additions & 0 deletions mypyc/irbuild/vec.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,18 @@ def vec_len_native(builder: LowLevelIRBuilder, val: Value) -> Value:
return builder.get_element(val, "len")


def vec_set_len_unsafe(
builder: LowLevelIRBuilder, vecobj: Value, length: Value, line: int
) -> Value:
"""Return <vec> with a reduced length (steal <vec>).

Items at or after the new length must not have been initialized, so that
they don't need to be freed (vec_create initializes them to NULL if needed).
"""
length = as_platform_int(builder, length, line)
return builder.add(SetElement(vecobj, "len", length, line))


def vec_items(builder: LowLevelIRBuilder, vecobj: Value) -> Value:
"""Return pointer to first item in vec.

Expand Down
10 changes: 10 additions & 0 deletions mypyc/lib-rt/CPy.h
Original file line number Diff line number Diff line change
Expand Up @@ -1024,6 +1024,13 @@ PyObject *CPyList_GetItemShortBorrow(PyObject *list, CPyTagged index);
PyObject *CPyList_GetItemInt64Borrow(PyObject *list, int64_t index);
PyObject *CPyList_GetItemUInt64Borrow(PyObject *list, uint64_t index);
void CPyList_SetItemUnsafe(PyObject *list, Py_ssize_t index, PyObject *value);

// Reduce the size of a list that is being built using CPyList_SetItemUnsafe.
// Items at or after the new size must not have been set.
static inline void CPyList_SetSizeUnsafe(PyObject *list, Py_ssize_t size) {
Py_SET_SIZE(list, size);
}

PyObject *CPyList_Build(Py_ssize_t len, ...);
PyObject *CPyList_PopLast(PyObject *obj);
PyObject *CPyList_Pop(PyObject *obj, CPyTagged index);
Expand Down Expand Up @@ -1205,6 +1212,9 @@ static inline void CPySequenceTuple_SetItemUnsafe(PyObject *tuple, Py_ssize_t in
PyTuple_SET_ITEM(tuple, index, value);
}

PyObject *CPySequenceTuple_SetItemGrow(PyObject *tuple, Py_ssize_t index, PyObject *value);
PyObject *CPySequenceTuple_SetSize(PyObject *tuple, Py_ssize_t size);

// 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
Expand Down
49 changes: 49 additions & 0 deletions mypyc/lib-rt/tuple_ops.c
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,52 @@ PyObject *CPySequenceTuple_GetSlice(PyObject *obj, CPyTagged start, CPyTagged en
}
return CPyObject_GetSlice(obj, start, end);
}

// Move the first n items of a tuple being built into a new tuple of the given size.
// Steals the reference to the original tuple.
static PyObject *CPyTuple_MoveItems(PyObject *tuple, Py_ssize_t n, Py_ssize_t size) {
PyObject *result = PyTuple_New(size);
if (result == NULL) {
Py_DECREF(tuple);
return NULL;
}
for (Py_ssize_t i = 0; i < n; i++) {
PyTuple_SET_ITEM(result, i, PyTuple_GET_ITEM(tuple, i));
PyTuple_SET_ITEM(tuple, i, NULL);
}
Py_DECREF(tuple);
return result;
}

// Set an item of a tuple that is being built using CPySequenceTuple_SetItemUnsafe, and
// grow the tuple if the index is out of range. Items before the index must have been
// set, and items at or after it must not have been set (so the index is at most the
// size of the tuple). Steals the tuple and the value,
// and returns the resulting tuple, which may be a new object.
PyObject *CPySequenceTuple_SetItemGrow(PyObject *tuple, Py_ssize_t index, PyObject *value) {
Py_ssize_t size = PyTuple_GET_SIZE(tuple);
if (index >= size) {
Py_ssize_t new_size = size < 4 ? 8 : size * 2;
if (new_size <= index) {
new_size = index + 1;
}
tuple = CPyTuple_MoveItems(tuple, size, new_size);
if (tuple == NULL) {
Py_DECREF(value);
return NULL;
}
}
PyTuple_SET_ITEM(tuple, index, value);
return tuple;
}

// Set the size of a tuple that is being built using CPySequenceTuple_SetItemUnsafe or
// CPySequenceTuple_SetItemGrow. Items before the size must have been set, and items at
// or after it must not have been set. Steals the tuple and returns the resulting tuple,
// which may be a new object.
PyObject *CPySequenceTuple_SetSize(PyObject *tuple, Py_ssize_t size) {
if (size == PyTuple_GET_SIZE(tuple)) {
return tuple;
}
return CPyTuple_MoveItems(tuple, size, size);
}
9 changes: 9 additions & 0 deletions mypyc/primitives/list_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,15 @@
steals=[False, False, True],
)

# Reduce the size of a list built using new_list_set_item_op. Items at or after
# the new size must not have been set.
new_list_set_size_op = custom_op(
arg_types=[list_rprimitive, c_pyssize_t_rprimitive],
return_type=void_rtype,
c_function_name="CPyList_SetSizeUnsafe",
error_kind=ERR_NEVER,
)

# list.append(obj)
list_append_op = method_op(
name="append",
Expand Down
Loading
Loading