Debian Codegraph @

mypyc/irbuild/ll_builder.py

raw
1 """A "low-level" IR builder class.
2
3 See the docstring of class LowLevelIRBuilder for more information.
4
5 """
6
7 from __future__ import annotations
8
9 import sys
10 from collections.abc import Callable, Sequence
11 from typing import Final, TypeGuard, cast
12
13 from mypy.argmap import map_actuals_to_formals
14 from mypy.nodes import ARG_POS, ARG_STAR, ARG_STAR2, ArgKind
15 from mypy.operators import op_methods, unary_op_methods
16 from mypy.types import AnyType, TypeOfAny
17 from mypyc.common import (
18 BITMAP_BITS,
19 FAST_ISINSTANCE_MAX_SUBCLASSES,
20 FAST_PREFIX,
21 IS_FREE_THREADED,
22 MAX_LITERAL_SHORT_INT,
23 MAX_SHORT_INT,
24 MIN_LITERAL_SHORT_INT,
25 MIN_SHORT_INT,
26 PLATFORM_SIZE,
27 )
28 from mypyc.errors import Errors
29 from mypyc.ir.class_ir import ClassIR, all_concrete_classes
30 from mypyc.ir.func_ir import FuncDecl, FuncSignature
31 from mypyc.ir.ops import (
32 ERR_FALSE,
33 ERR_NEVER,
34 NAMESPACE_MODULE,
35 NAMESPACE_STATIC,
36 NAMESPACE_TYPE,
37 Assign,
38 AssignMulti,
39 BasicBlock,
40 Box,
41 Branch,
42 Call,
43 CallC,
44 Cast,
45 ComparisonOp,
46 Extend,
47 Float,
48 FloatComparisonOp,
49 FloatNeg,
50 FloatOp,
51 GetAttr,
52 GetElement,
53 GetElementPtr,
54 Goto,
55 Integer,
56 IntOp,
57 KeepAlive,
58 LoadAddress,
59 LoadErrorValue,
60 LoadGlobal,
61 LoadLiteral,
62 LoadMem,
63 LoadStatic,
64 MethodCall,
65 Op,
66 PrimitiveDescription,
67 PrimitiveOp,
68 RaiseStandardError,
69 Register,
70 SetMem,
71 Truncate,
72 TupleGet,
73 TupleSet,
74 Unbox,
75 Unreachable,
76 Value,
77 float_comparison_op_to_id,
78 float_op_to_id,
79 int_op_to_id,
80 )
81 from mypyc.ir.rtypes import (
82 PyObject,
83 PySetObject,
84 RArray,
85 RInstance,
86 RPrimitive,
87 RStruct,
88 RTuple,
89 RType,
90 RUnion,
91 RVec,
92 bit_rprimitive,
93 bitmap_rprimitive,
94 bool_rprimitive,
95 bytes_rprimitive,
96 c_int_rprimitive,
97 c_pointer_rprimitive,
98 c_pyssize_t_rprimitive,
99 c_size_t_rprimitive,
100 check_native_int_range,
101 float_rprimitive,
102 int64_rprimitive,
103 int_rprimitive,
104 is_bool_or_bit_rprimitive,
105 is_bytes_rprimitive,
106 is_c_py_ssize_t_rprimitive,
107 is_dict_rprimitive,
108 is_fixed_width_rtype,
109 is_float_rprimitive,
110 is_frozenset_rprimitive,
111 is_int16_rprimitive,
112 is_int32_rprimitive,
113 is_int64_rprimitive,
114 is_int_rprimitive,
115 is_list_rprimitive,
116 is_none_rprimitive,
117 is_object_rprimitive,
118 is_optional_type,
119 is_set_rprimitive,
120 is_short_int_rprimitive,
121 is_str_rprimitive,
122 is_tagged,
123 is_tuple_rprimitive,
124 is_uint8_rprimitive,
125 none_rprimitive,
126 object_pointer_rprimitive,
127 object_rprimitive,
128 optional_value_type,
129 pointer_rprimitive,
130 short_int_rprimitive,
131 str_rprimitive,
132 )
133 from mypyc.irbuild.util import concrete_arg_kind
134 from mypyc.irbuild.vec import vec_contains, vec_get_item, vec_len_native
135 from mypyc.options import CompilerOptions
136 from mypyc.primitives.bytes_ops import bytes_compare
137 from mypyc.primitives.dict_ops import (
138 dict_build_op,
139 dict_copy,
140 dict_copy_op,
141 dict_new_op,
142 dict_ssize_t_size_op,
143 dict_update_in_display_op,
144 )
145 from mypyc.primitives.exc_ops import err_occurred_op, keep_propagating_op
146 from mypyc.primitives.float_ops import copysign_op, int_to_float_op
147 from mypyc.primitives.generic_ops import (
148 generic_len_op,
149 generic_ssize_t_len_op,
150 py_call_op,
151 py_call_with_kwargs_op,
152 py_call_with_posargs_op,
153 py_getattr_op,
154 py_method_call_op,
155 py_vectorcall_method_op,
156 py_vectorcall_op,
157 )
158 from mypyc.primitives.int_ops import (
159 int16_divide_op,
160 int16_mod_op,
161 int16_overflow,
162 int32_divide_op,
163 int32_mod_op,
164 int32_overflow,
165 int64_divide_op,
166 int64_mod_op,
167 int64_to_int_op,
168 int_to_int32_op,
169 int_to_int64_op,
170 ssize_t_to_int_op,
171 uint8_overflow,
172 )
173 from mypyc.primitives.list_ops import list_build_op, list_extend_op, list_items, new_list_op
174 from mypyc.primitives.misc_ops import (
175 bool_op,
176 buf_init_item,
177 debug_print_op,
178 fast_isinstance_op,
179 none_object_op,
180 not_implemented_op,
181 set_immortal_op,
182 var_object_size,
183 )
184 from mypyc.primitives.registry import (
185 ERR_NEG_INT,
186 CFunctionDescription,
187 binary_ops,
188 builtin_names,
189 function_ops,
190 global_names,
191 method_call_ops,
192 unary_ops,
193 )
194 from mypyc.primitives.set_ops import new_set_op
195 from mypyc.primitives.str_ops import (
196 str_check_if_true,
197 str_eq,
198 str_eq_literal,
199 str_ssize_t_size_op,
200 unicode_compare,
201 )
202 from mypyc.primitives.tuple_ops import (
203 list_tuple_op,
204 load_empty_tuple_constant_op,
205 new_tuple_op,
206 new_tuple_with_length_op,
207 sequence_tuple_op,
208 )
209 from mypyc.rt_subtype import is_runtime_subtype
210 from mypyc.sametype import is_same_type
211 from mypyc.subtype import is_subtype
212
213 DictEntry = tuple[Value | None, Value]
214
215 # If the number of items is less than the threshold when initializing
216 # a list, we would inline the generate IR using SetMem and expanded
217 # for-loop. Otherwise, we would call `list_build_op` for larger lists.
218 # TODO: The threshold is a randomly chosen number which needs further
219 # study on real-world projects for a better balance.
220 LIST_BUILDING_EXPANSION_THRESHOLD = 10
221
222 # From CPython
223 PY_VECTORCALL_ARGUMENTS_OFFSET: Final = 1 << (PLATFORM_SIZE * 8 - 1)
224
225 FIXED_WIDTH_INT_BINARY_OPS: Final = {
226 "+",
227 "-",
228 "*",
229 "//",
230 "%",
231 "&",
232 "|",
233 "^",
234 "<<",
235 ">>",
236 "+=",
237 "-=",
238 "*=",
239 "//=",
240 "%=",
241 "&=",
242 "|=",
243 "^=",
244 "<<=",
245 ">>=",
246 }
247
248 # Binary operations on bools that are specialized and don't just promote operands to int
249 BOOL_BINARY_OPS: Final = {"&", "&=", "|", "|=", "^", "^=", "==", "!=", "<", "<=", ">", ">="}
250
251
252 class LowLevelIRBuilder:
253 """A "low-level" IR builder class.
254
255 LowLevelIRBuilder provides core abstractions we use for constructing
256 IR as well as a number of higher-level ones (accessing attributes,
257 calling functions and methods, and coercing between types, for
258 example).
259
260 The core principle of the low-level IR builder is that all of its
261 facilities operate solely on the mypyc IR level and not the mypy AST
262 level---it has *no knowledge* of mypy types or expressions.
263
264 The mypyc.irbuilder.builder.IRBuilder class wraps an instance of this
265 class and provides additional functionality to transform mypy AST nodes
266 to IR.
267 """
268
269 def __init__(self, errors: Errors | None, options: CompilerOptions) -> None:
270 self.errors = errors
271 self.options = options
272 self.args: list[Register] = []
273 self.blocks: list[BasicBlock] = []
274 # Stack of except handler entry blocks
275 self.error_handlers: list[BasicBlock | None] = [None]
276 # Values that we need to keep alive as long as we have borrowed
277 # temporaries. Use flush_keep_alives() to mark the end of the live range.
278 self.keep_alives: list[Value] = []
279
280 def set_module(self, module_name: str, module_path: str) -> None:
281 """Set the name and path of the current module."""
282 self.module_name = module_name
283 self.module_path = module_path
284
285 # Basic operations
286
287 def add(self, op: Op) -> Value:
288 """Add an op."""
289 assert not self.blocks[-1].terminated, "Can't add to finished block"
290 self.blocks[-1].ops.append(op)
291 return op
292
293 def assign(self, lvalue: Register, rvalue: Value | int) -> None:
294 if isinstance(rvalue, int):
295 rvalue = Integer(rvalue, lvalue.type)
296 self.add(Assign(lvalue, rvalue))
297
298 def goto(self, target: BasicBlock) -> None:
299 """Add goto to a basic block."""
300 if not self.blocks[-1].terminated:
301 self.add(Goto(target))
302
303 def activate_block(self, block: BasicBlock) -> None:
304 """Add a basic block and make it the active one (target of adds)."""
305 if self.blocks:
306 assert self.blocks[-1].terminated
307
308 block.error_handler = self.error_handlers[-1]
309 self.blocks.append(block)
310
311 def goto_and_activate(self, block: BasicBlock) -> None:
312 """Add goto a block and make it the active block."""
313 self.goto(block)
314 self.activate_block(block)
315
316 def keep_alive(self, values: list[Value], line: int, *, steal: bool = False) -> None:
317 self.add(KeepAlive(values, line, steal=steal))
318
319 def load_mem(self, ptr: Value, value_type: RType, *, borrow: bool = False) -> Value:
320 return self.add(LoadMem(value_type, ptr, borrow=borrow))
321
322 def set_mem(self, ptr: Value, value_type: RType, value: Value) -> None:
323 self.add(SetMem(value_type, ptr, value, line=-1))
324
325 def get_element(self, reg: Value, field: str) -> Value:
326 return self.add(GetElement(reg, field))
327
328 def load_address(self, name: str, rtype: RType, line: int = -1) -> Value:
329 return self.add(LoadAddress(rtype, name, line))
330
331 def load_global(self, name: str, rtype: RType, line: int) -> Value:
332 return self.add(LoadGlobal(rtype, name, line))
333
334 def load_builtin(self, name: str, line: int) -> Value | None:
335 if builtin := builtin_names.get(name):
336 return self.load_address(builtin[1], builtin[0], line)
337 if glob := global_names.get(name):
338 return self.load_global(glob[1], glob[0], line)
339 return None
340
341 def load_struct_field(
342 self, ptr: Value, struct: RStruct, field: str, *, borrow: bool = False
343 ) -> Value:
344 address = self.add(GetElementPtr(ptr, struct, field))
345 return self.load_mem(address, struct.field_type(field), borrow=borrow)
346
347 def set_struct_field(
348 self, ptr: Value, struct: RStruct, field: str, value: Value, line: int
349 ) -> None:
350 address = self.add(GetElementPtr(ptr, struct, field))
351 field_type = struct.field_type(field)
352 value = self.coerce(value, field_type, line)
353 self.set_mem(address, field_type, value)
354 self.keep_alive([ptr], line)
355
356 def push_error_handler(self, handler: BasicBlock | None) -> None:
357 self.error_handlers.append(handler)
358
359 def pop_error_handler(self) -> BasicBlock | None:
360 return self.error_handlers.pop()
361
362 def self(self) -> Register:
363 """Return reference to the 'self' argument.
364
365 This only works in a method.
366 """
367 return self.args[0]
368
369 def flush_keep_alives(self, line: int) -> None:
370 if self.keep_alives:
371 self.add(KeepAlive(self.keep_alives.copy(), line))
372 self.keep_alives = []
373
374 def debug_print(self, toprint: str | Value) -> None:
375 if isinstance(toprint, str):
376 toprint = self.load_str(toprint)
377 self.primitive_op(debug_print_op, [toprint], -1)
378
379 # Type conversions
380
381 def box(self, src: Value) -> Value:
382 if src.type.is_unboxed:
383 if isinstance(src, Integer) and is_tagged(src.type):
384 return self.add(LoadLiteral(src.value >> 1, rtype=object_rprimitive))
385 return self.add(Box(src, src.line))
386 else:
387 return src
388
389 def unbox_or_cast(
390 self,
391 src: Value,
392 target_type: RType,
393 line: int,
394 *,
395 can_borrow: bool = False,
396 unchecked: bool = False,
397 ) -> Value:
398 if target_type.is_unboxed:
399 return self.add(Unbox(src, target_type, line))
400 else:
401 if can_borrow:
402 self.keep_alives.append(src)
403 return self.add(Cast(src, target_type, line, borrow=can_borrow, unchecked=unchecked))
404
405 def coerce(
406 self,
407 src: Value,
408 target_type: RType,
409 line: int,
410 force: bool = False,
411 *,
412 can_borrow: bool = False,
413 ) -> Value:
414 """Generate a coercion/cast from one type to other (only if needed).
415
416 For example, int -> object boxes the source int; int -> int emits nothing;
417 object -> int unboxes the object. All conversions preserve object value.
418
419 If force is true, always generate an op (even if it is just an assignment) so
420 that the result will have exactly target_type as the type.
421
422 Returns the register with the converted value (may be same as src).
423 """
424 src_type = src.type
425 if src_type.is_unboxed and not target_type.is_unboxed:
426 # Unboxed -> boxed
427 return self.box(src)
428 if (src_type.is_unboxed and target_type.is_unboxed) and not is_runtime_subtype(
429 src_type, target_type
430 ):
431 if (
432 isinstance(src, Integer)
433 and is_short_int_rprimitive(src_type)
434 and is_fixed_width_rtype(target_type)
435 ):
436 value = src.numeric_value()
437 if not check_native_int_range(target_type, value):
438 self.error(f'Value {value} is out of range for "{target_type}"', line)
439 return Integer(src.value >> 1, target_type)
440 elif is_int_rprimitive(src_type) and is_fixed_width_rtype(target_type):
441 return self.coerce_int_to_fixed_width(src, target_type, line)
442 elif is_fixed_width_rtype(src_type) and is_int_rprimitive(target_type):
443 return self.coerce_fixed_width_to_int(src, line)
444 elif is_short_int_rprimitive(src_type) and is_fixed_width_rtype(target_type):
445 return self.coerce_short_int_to_fixed_width(src, target_type, line)
446 elif (
447 isinstance(src_type, RPrimitive)
448 and isinstance(target_type, RPrimitive)
449 and src_type.is_native_int
450 and target_type.is_native_int
451 and src_type.size <= target_type.size
452 and src_type.is_signed == target_type.is_signed
453 ):
454 if src_type.size == target_type.size:
455 # Equivalent types
456 return src
457 else:
458 # Extend to larger type
459 return self.add(Extend(src, target_type, target_type.is_signed, line))
460 elif is_int64_rprimitive(src_type) and is_c_py_ssize_t_rprimitive(target_type):
461 return self.coerce_i64_to_ssize_t(src, line)
462 elif is_bool_or_bit_rprimitive(src_type) and is_tagged(target_type):
463 shifted = self.int_op(
464 bool_rprimitive, src, Integer(1, bool_rprimitive), IntOp.LEFT_SHIFT
465 )
466 return self.add(Extend(shifted, target_type, signed=False))
467 elif is_bool_or_bit_rprimitive(src_type) and is_fixed_width_rtype(target_type):
468 return self.add(Extend(src, target_type, signed=False))
469 elif isinstance(src, Integer) and is_float_rprimitive(target_type):
470 if is_tagged(src_type):
471 return Float(float(src.value // 2))
472 return Float(float(src.value))
473 elif is_tagged(src_type) and is_float_rprimitive(target_type):
474 return self.int_to_float(src, line)
475 elif (
476 isinstance(src_type, RTuple)
477 and isinstance(target_type, RTuple)
478 and len(src_type.types) == len(target_type.types)
479 ):
480 # Coerce between two tuple types by coercing each item separately
481 values = []
482 for i in range(len(src_type.types)):
483 v = None
484 if isinstance(src, TupleSet):
485 item = src.items[i]
486 # We can't reuse register values, since they can be modified.
487 if not isinstance(item, Register):
488 v = item
489 if v is None:
490 v = TupleGet(src, i)
491 self.add(v)
492 values.append(v)
493 return self.add(
494 TupleSet(
495 [self.coerce(v, t, line) for v, t in zip(values, target_type.types)], line
496 )
497 )
498 # To go between any other unboxed types, we go through a boxed
499 # in-between value, for simplicity.
500 tmp = self.box(src)
501 return self.unbox_or_cast(tmp, target_type, line)
502 if (not src_type.is_unboxed and target_type.is_unboxed) or not is_subtype(
503 src_type, target_type
504 ):
505 return self.unbox_or_cast(src, target_type, line, can_borrow=can_borrow)
506 elif force:
507 tmp = Register(target_type)
508 self.add(Assign(tmp, src, line))
509 return tmp
510 return src
511
512 def coerce_int_to_fixed_width(self, src: Value, target_type: RType, line: int) -> Value:
513 assert is_fixed_width_rtype(target_type), target_type
514 assert isinstance(target_type, RPrimitive), target_type
515
516 fast, slow, end = BasicBlock(), BasicBlock(), BasicBlock()
517
518 check = self.check_tagged_short_int(src, line)
519 self.add(Branch(check, fast, slow, Branch.BOOL))
520
521 self.activate_block(fast)
522
523 size = target_type.size
524 if size < int_rprimitive.size:
525 # Add a range check when the target type is smaller than the source type
526 # Use helper method to generate range checking and conversion
527 res = self.coerce_tagged_to_fixed_width_with_range_check(
528 src, target_type, int_rprimitive.size, slow, end, line
529 )
530 else:
531 # No range check needed when target is same size or larger
532 if size > int_rprimitive.size:
533 tmp = self.add(Extend(src, target_type, signed=True))
534 else:
535 tmp = src
536 tmp = self.int_op(target_type, tmp, Integer(1, target_type), IntOp.RIGHT_SHIFT, line)
537 res = Register(target_type)
538 self.add(Assign(res, tmp))
539 self.goto(end)
540
541 self.activate_block(slow)
542 if is_int64_rprimitive(target_type) or (
543 is_int32_rprimitive(target_type) and size == int_rprimitive.size
544 ):
545 # Slow path calls a library function that handles more complex logic
546 ptr = self.int_op(
547 pointer_rprimitive, src, Integer(1, pointer_rprimitive), IntOp.XOR, line
548 )
549 ptr2 = Register(c_pointer_rprimitive)
550 self.add(Assign(ptr2, ptr))
551 if is_int64_rprimitive(target_type):
552 conv_op = int_to_int64_op
553 else:
554 conv_op = int_to_int32_op
555 tmp = self.call_c(conv_op, [ptr2], line)
556 self.add(Assign(res, tmp))
557 self.add(KeepAlive([src]))
558 self.goto(end)
559 else:
560 # Slow path just always generates an OverflowError
561 self.emit_fixed_width_overflow_error(target_type, line)
562
563 self.activate_block(end)
564 return res
565
566 def check_fixed_width_range(
567 self, src: Value, target_type: RPrimitive, overflow_block: BasicBlock, line: int
568 ) -> None:
569 """Check if src fits in target_type range, branch to overflow_block if not.
570
571 On success, continues in a newly activated block where the value is
572 known to be in range.
573
574 Args:
575 src: Source value to check
576 target_type: Target fixed-width type defining the valid range
577 overflow_block: Block to branch to if value is out of range
578 line: Line number
579 """
580 in_range, in_range2 = BasicBlock(), BasicBlock()
581
582 size = target_type.size
583 upper_bound = 1 << (size * 8 - 1)
584 if not target_type.is_signed:
585 upper_bound *= 2
586
587 # Check if value < upper_bound
588 check_upper = self.add(
589 ComparisonOp(src, Integer(upper_bound, src.type), ComparisonOp.SLT, line)
590 )
591 self.add(Branch(check_upper, in_range, overflow_block, Branch.BOOL, line))
592
593 self.activate_block(in_range)
594
595 # Check if value >= lower_bound
596 if target_type.is_signed:
597 lower_bound = -upper_bound
598 else:
599 lower_bound = 0
600 check_lower = self.add(
601 ComparisonOp(src, Integer(lower_bound, src.type), ComparisonOp.SGE, line)
602 )
603 self.add(Branch(check_lower, in_range2, overflow_block, Branch.BOOL, line))
604
605 self.activate_block(in_range2)
606
607 def coerce_tagged_to_fixed_width_with_range_check(
608 self,
609 src: Value,
610 target_type: RType,
611 source_size: int,
612 overflow_block: BasicBlock,
613 success_block: BasicBlock,
614 line: int,
615 ) -> Register:
616 """Helper to convert a tagged value to a smaller fixed-width type with range checking.
617
618 This method generates IR for converting a tagged integer (like short_int or the fast
619 path of int) to a smaller fixed-width type (i32, i16, uint8) with overflow detection.
620
621 The method performs range checks and branches to overflow_block on failure, or
622 success_block on success (after assigning the result to a register).
623
624 Args:
625 src: Tagged source value (with tag bit set)
626 target_type: Target fixed-width type (must be smaller than source_size)
627 source_size: Size in bytes of the source type
628 overflow_block: Block to branch to on overflow
629 success_block: Block to goto after successful conversion
630 line: Line number
631
632 Returns:
633 Result register containing the converted value (valid in success_block)
634 """
635 assert is_fixed_width_rtype(target_type), target_type
636 assert isinstance(target_type, RPrimitive), target_type
637 size = target_type.size
638 assert size < source_size, (target_type, size, source_size)
639
640 res = Register(target_type)
641
642 self.check_fixed_width_range(src, target_type, overflow_block, line)
643
644 # Value is in range - shift right to remove tag, then truncate
645 shifted = self.int_op(
646 c_pyssize_t_rprimitive,
647 src,
648 Integer(1, c_pyssize_t_rprimitive),
649 IntOp.RIGHT_SHIFT,
650 line,
651 )
652 tmp = self.add(Truncate(shifted, target_type, line))
653 self.add(Assign(res, tmp, line))
654 self.goto(success_block)
655
656 return res
657
658 def emit_fixed_width_overflow_error(self, target_type: RType, line: int) -> None:
659 """Emit overflow error for fixed-width type conversion."""
660 if is_int32_rprimitive(target_type):
661 self.call_c(int32_overflow, [], line)
662 elif is_int16_rprimitive(target_type):
663 self.call_c(int16_overflow, [], line)
664 elif is_uint8_rprimitive(target_type):
665 self.call_c(uint8_overflow, [], line)
666 else:
667 assert False, target_type
668 self.add(Unreachable())
669
670 def coerce_short_int_to_fixed_width(self, src: Value, target_type: RType, line: int) -> Value:
671 # short_int (CPyTagged) is guaranteed to be a tagged value, never a pointer,
672 # so we don't need the fast/slow path split like coerce_int_to_fixed_width.
673 # However, we still need range checking when target type is smaller than source.
674 assert is_fixed_width_rtype(target_type), target_type
675 assert isinstance(target_type, RPrimitive), target_type
676
677 if is_int64_rprimitive(target_type) or (
678 PLATFORM_SIZE == 4 and is_int32_rprimitive(target_type)
679 ):
680 # No range check needed - target is same size or larger than source
681 return self.int_op(target_type, src, Integer(1, target_type), IntOp.RIGHT_SHIFT, line)
682
683 # Target is smaller than source - need range checking
684 # Use helper method to generate range checking and conversion
685 overflow, end = BasicBlock(), BasicBlock()
686 res = self.coerce_tagged_to_fixed_width_with_range_check(
687 src, target_type, short_int_rprimitive.size, overflow, end, line
688 )
689
690 # Handle overflow case
691 self.activate_block(overflow)
692 self.emit_fixed_width_overflow_error(target_type, line)
693
694 self.activate_block(end)
695 return res
696
697 def coerce_fixed_width_to_int(self, src: Value, line: int) -> Value:
698 if (
699 (is_int32_rprimitive(src.type) and PLATFORM_SIZE == 8)
700 or is_int16_rprimitive(src.type)
701 or is_uint8_rprimitive(src.type)
702 ):
703 # Simple case -- just sign extend and shift.
704 extended = self.add(Extend(src, c_pyssize_t_rprimitive, signed=src.type.is_signed))
705 return self.int_op(
706 int_rprimitive,
707 extended,
708 Integer(1, c_pyssize_t_rprimitive),
709 IntOp.LEFT_SHIFT,
710 line,
711 )
712
713 src_type = src.type
714
715 assert is_fixed_width_rtype(src_type), src_type
716 assert isinstance(src_type, RPrimitive), src_type
717
718 res = Register(int_rprimitive)
719
720 fast, fast2, slow, end = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock()
721
722 c1 = self.add(ComparisonOp(src, Integer(MAX_SHORT_INT, src_type), ComparisonOp.SLE, line))
723 self.add(Branch(c1, fast, slow, Branch.BOOL))
724
725 self.activate_block(fast)
726 c2 = self.add(ComparisonOp(src, Integer(MIN_SHORT_INT, src_type), ComparisonOp.SGE, line))
727 self.add(Branch(c2, fast2, slow, Branch.BOOL))
728
729 self.activate_block(slow)
730 if is_int64_rprimitive(src_type):
731 conv_op = int64_to_int_op
732 elif is_int32_rprimitive(src_type):
733 assert PLATFORM_SIZE == 4
734 conv_op = ssize_t_to_int_op
735 else:
736 assert False, src_type
737 x = self.call_c(conv_op, [src], line)
738 self.add(Assign(res, x))
739 self.goto(end)
740
741 self.activate_block(fast2)
742 if int_rprimitive.size < src_type.size:
743 tmp = self.add(Truncate(src, c_pyssize_t_rprimitive))
744 else:
745 tmp = src
746 s = self.int_op(int_rprimitive, tmp, Integer(1, tmp.type), IntOp.LEFT_SHIFT, line)
747 self.add(Assign(res, s))
748 self.goto(end)
749
750 self.activate_block(end)
751 return res
752
753 def coerce_i64_to_ssize_t(self, src: Value, line: int) -> Value:
754 """Coerce int64 to c_pyssize_t with range check on 32-bit platforms.
755
756 On 64-bit platforms, this is a no-op since the types have the same size.
757 On 32-bit platforms, raises ValueError if the value doesn't fit in 32 bits.
758 """
759 if PLATFORM_SIZE == 8:
760 return src
761
762 # 32-bit platform: need range check
763 overflow, end = BasicBlock(), BasicBlock()
764
765 self.check_fixed_width_range(src, c_pyssize_t_rprimitive, overflow, line)
766
767 # Value is in range - truncate to 32 bits
768 res = self.add(Truncate(src, c_pyssize_t_rprimitive, line))
769 self.goto(end)
770
771 # Handle overflow case
772 self.activate_block(overflow)
773 self.call_c(int32_overflow, [], line)
774 self.add(Unreachable())
775
776 self.activate_block(end)
777 return res
778
779 def coerce_nullable(self, src: Value, target_type: RType, line: int) -> Value:
780 """Generate a coercion from a potentially null value."""
781 if src.type.is_unboxed == target_type.is_unboxed and (
782 (target_type.is_unboxed and is_runtime_subtype(src.type, target_type))
783 or (not target_type.is_unboxed and is_subtype(src.type, target_type))
784 ):
785 return src
786
787 target = Register(target_type)
788
789 valid, invalid, out = BasicBlock(), BasicBlock(), BasicBlock()
790 self.add(Branch(src, invalid, valid, Branch.IS_ERROR))
791
792 self.activate_block(valid)
793 coerced = self.coerce(src, target_type, line)
794 self.add(Assign(target, coerced, line))
795 self.goto(out)
796
797 self.activate_block(invalid)
798 error = self.add(LoadErrorValue(target_type))
799 self.add(Assign(target, error, line))
800
801 self.goto_and_activate(out)
802 return target
803
804 # Attribute access
805
806 def get_attr(
807 self, obj: Value, attr: str, result_type: RType, line: int, *, borrow: bool = False
808 ) -> Value:
809 """Get a native or Python attribute of an object."""
810 if (
811 isinstance(obj.type, RInstance)
812 and obj.type.class_ir.is_ext_class
813 and obj.type.class_ir.has_attr(attr)
814 ):
815 op = GetAttr(obj, attr, line, borrow=borrow)
816 # For non-refcounted attribute types, the borrow might be
817 # disabled even if requested, so don't check 'borrow'.
818 if op.is_borrowed:
819 self.keep_alives.append(obj)
820 return self.add(op)
821 elif isinstance(obj.type, RUnion):
822 return self.union_get_attr(obj, obj.type, attr, result_type, line)
823 else:
824 return self.py_get_attr(obj, attr, line)
825
826 def union_get_attr(
827 self, obj: Value, rtype: RUnion, attr: str, result_type: RType, line: int
828 ) -> Value:
829 """Get an attribute of an object with a union type."""
830
831 def get_item_attr(value: Value) -> Value:
832 return self.get_attr(value, attr, result_type, line)
833
834 return self.decompose_union_helper(obj, rtype, result_type, get_item_attr, line)
835
836 def py_get_attr(self, obj: Value, attr: str, line: int) -> Value:
837 """Get a Python attribute (slow).
838
839 Prefer get_attr() which generates optimized code for native classes.
840 """
841 key = self.load_str(attr)
842 return self.primitive_op(py_getattr_op, [obj, key], line)
843
844 # isinstance() checks
845
846 def isinstance_helper(self, obj: Value, class_irs: list[ClassIR], line: int) -> Value:
847 """Fast path for isinstance() that checks against a list of native classes."""
848 if not class_irs:
849 return self.false()
850 ret = self.isinstance_native(obj, class_irs[0], line)
851 for class_ir in class_irs[1:]:
852
853 def other() -> Value:
854 return self.isinstance_native(obj, class_ir, line)
855
856 ret = self.shortcircuit_helper("or", bool_rprimitive, lambda: ret, other, line)
857 return ret
858
859 def get_type_of_obj(self, obj: Value, line: int) -> Value:
860 ob_type_address = self.add(GetElementPtr(obj, PyObject, "ob_type", line))
861 ob_type = self.load_mem(ob_type_address, object_rprimitive, borrow=True)
862 self.add(KeepAlive([obj], line))
863 return ob_type
864
865 def type_is_op(self, obj: Value, type_obj: Value, line: int) -> Value:
866 typ = self.get_type_of_obj(obj, line)
867 return self.add(ComparisonOp(typ, type_obj, ComparisonOp.EQ, line))
868
869 def isinstance_native(self, obj: Value, class_ir: ClassIR, line: int) -> Value:
870 """Fast isinstance() check for a native class.
871
872 If there are three or fewer concrete (non-trait) classes among the class
873 and all its children, use even faster type comparison checks `type(obj)
874 is typ`.
875 """
876 concrete = all_concrete_classes(class_ir)
877 if concrete is None or len(concrete) > FAST_ISINSTANCE_MAX_SUBCLASSES + 1:
878 return self.primitive_op(
879 fast_isinstance_op, [obj, self.get_native_type(class_ir)], line
880 )
881 if not concrete:
882 # There can't be any concrete instance that matches this.
883 return self.false()
884 type_obj = self.get_native_type(concrete[0])
885 ret = self.type_is_op(obj, type_obj, line)
886 for c in concrete[1:]:
887
888 def other() -> Value:
889 return self.type_is_op(obj, self.get_native_type(c), line)
890
891 ret = self.shortcircuit_helper("or", bool_rprimitive, lambda: ret, other, line)
892 return ret
893
894 # Calls
895
896 def _construct_varargs(
897 self,
898 args: Sequence[tuple[Value, ArgKind, str | None]],
899 line: int,
900 *,
901 has_star: bool,
902 has_star2: bool,
903 ) -> tuple[Value | None, Value | None]:
904 """Construct *args and **kwargs from a collection of arguments
905
906 This is pretty complicated, and almost all of the complication here stems from
907 one of two things (but mostly the second):
908 * The handling of ARG_STAR/ARG_STAR2. We want to create as much of the args/kwargs
909 values in one go as we can, so we collect values until our hand is forced, and
910 then we emit creation of the list/tuple, and expand it from there if needed.
911
912 * Support potentially nullable argument values. This has very narrow applicability,
913 as this will never be done by our compiled Python code, but is critically used
914 by gen_glue_method when generating glue methods to mediate between the function
915 signature of a parent class and its subclasses.
916
917 For named-only arguments, this is quite simple: if it is
918 null, don't put it in the dict.
919
920 For positional-or-named arguments, things are much more complicated.
921 * First, anything that was passed as a positional arg
922 must be forwarded along as a positional arg. It *must
923 not* be converted to a named arg. This is because mypy
924 does not enforce that positional-or-named arguments
925 have the same name in subclasses, and it is not
926 uncommon for code to have different names in
927 subclasses (a bunch of mypy's visitors do this, for
928 example!). This is arguably a bug in both mypy and code doing
929 this, and they ought to be using positional-only arguments, but
930 positional-only arguments are new and ugly.
931
932 * On the flip side, we're willing to accept the
933 infelicity of sometimes turning an argument that was
934 passed by keyword into a positional argument. It's wrong,
935 but it's very marginal, and avoiding it would require passing
936 a bitmask of which arguments were named with every function call,
937 or something similar.
938 (See some discussion of this in testComplicatedArgs)
939
940 Thus, our strategy for positional-or-named arguments is to
941 always pass them as positional, except in the one
942 situation where we can not, and where we can be absolutely
943 sure they were passed by name: when an *earlier*
944 positional argument was missing its value.
945
946 This means that if we have a method `f(self, x: int=..., y: object=...)`:
947 * x and y present: args=(x, y), kwargs={}
948 * x present, y missing: args=(x,), kwargs={}
949 * x missing, y present: args=(), kwargs={'y': y}
950
951 To implement this, when we have multiple optional
952 positional arguments, we maintain a flag in a register
953 that tracks whether an argument has been missing, and for
954 each such optional argument (except the first), we check
955 the flag to determine whether to append the argument to
956 the *args list or add it to the **kwargs dict. What a
957 mess!
958
959 This is what really makes everything here such a tangle;
960 otherwise the *args and **kwargs code could be separated.
961
962 The arguments has_star and has_star2 indicate whether the target function
963 takes an ARG_STAR and ARG_STAR2 argument, respectively.
964 (These will always be true when making a pycall, and be based
965 on the actual target signature for a native call.)
966 """
967
968 star_result: Value | None = None
969 star2_result: Value | None = None
970 # We aggregate values that need to go into *args and **kwargs
971 # in these lists. Once all arguments are processed (in the
972 # happiest case), or we encounter an ARG_STAR/ARG_STAR2 or a
973 # nullable arg, then we create the list and/or dict.
974 star_values: list[Value] = []
975 star2_keys: list[Value] = []
976 star2_values: list[Value] = []
977
978 seen_empty_reg: Register | None = None
979
980 for value, kind, name in args:
981 if kind == ARG_STAR:
982 if star_result is None:
983 # star args fastpath
984 if len(args) == 1:
985 # fn(*args)
986 if is_list_rprimitive(value.type):
987 value = self.primitive_op(list_tuple_op, [value], line)
988 elif not is_tuple_rprimitive(value.type) and not isinstance(
989 value.type, RTuple
990 ):
991 value = self.primitive_op(sequence_tuple_op, [value], line)
992 return value, None
993 elif len(args) == 2 and args[1][1] == ARG_STAR2:
994 # fn(*args, **kwargs)
995 # TODO: extend to cover(*args, **k, **w, **a, **r, **g, **s)
996 if is_tuple_rprimitive(value.type) or isinstance(value.type, RTuple):
997 star_result = value
998 elif is_list_rprimitive(value.type):
999 star_result = self.primitive_op(list_tuple_op, [value], line)
1000 else:
1001 star_result = self.primitive_op(sequence_tuple_op, [value], line)
1002
1003 star2_arg = args[1]
1004 star2_value = star2_arg[0]
1005 if is_dict_rprimitive(star2_value.type):
1006 star2_fastpath_op = dict_copy_op
1007 else:
1008 star2_fastpath_op = dict_copy
1009 return star_result, self.primitive_op(
1010 star2_fastpath_op, [star2_value], line
1011 )
1012 # elif ...: TODO extend this to optimize fn(*args, k=1, **kwargs) case
1013 # TODO optimize this case using the length utils - currently in review
1014 star_result = self.new_list_op(star_values, line)
1015 self.primitive_op(list_extend_op, [star_result, value], line)
1016 elif kind == ARG_STAR2:
1017 if star2_result is None:
1018 if len(args) == 1:
1019 # early exit with fastpath if the only arg is ARG_STAR2
1020 # TODO: can we maintain an empty tuple in memory and just reuse it again and again?
1021 if is_dict_rprimitive(value.type):
1022 star2_fastpath_op = dict_copy_op
1023 else:
1024 star2_fastpath_op = dict_copy
1025 return self.new_tuple([], line), self.primitive_op(
1026 star2_fastpath_op, [value], line
1027 )
1028
1029 star2_result = self._create_dict(star2_keys, star2_values, line)
1030
1031 self.call_c(dict_update_in_display_op, [star2_result, value], line=line)
1032 else:
1033 nullable = kind.is_optional()
1034 maybe_pos = kind.is_positional() and has_star
1035 maybe_named = kind.is_named() or (kind.is_optional() and name and has_star2)
1036
1037 # If the argument is nullable, we need to create the
1038 # relevant args/kwargs objects so that we can
1039 # conditionally modify them.
1040 if nullable:
1041 if maybe_pos and star_result is None:
1042 star_result = self.new_list_op(star_values, line)
1043 if maybe_named and star2_result is None:
1044 star2_result = self._create_dict(star2_keys, star2_values, line)
1045
1046 # Easy cases: just collect the argument.
1047 if maybe_pos and star_result is None:
1048 star_values.append(value)
1049 continue
1050
1051 if maybe_named and star2_result is None:
1052 assert name is not None
1053 key = self.load_str(name)
1054 star2_keys.append(key)
1055 star2_values.append(value)
1056 continue
1057
1058 # OK, anything that is nullable or *after* a nullable arg needs to be here
1059 # TODO: We could try harder to avoid creating basic blocks in the common case
1060 new_seen_empty_reg = seen_empty_reg
1061
1062 out = BasicBlock()
1063 if nullable:
1064 # If this is the first nullable positional arg we've seen, create
1065 # a register to track whether anything has been null.
1066 # (We won't *check* the register until the next argument, though.)
1067 if maybe_pos and not seen_empty_reg:
1068 new_seen_empty_reg = Register(bool_rprimitive)
1069 self.add(Assign(new_seen_empty_reg, self.false(), line))
1070
1071 skip = BasicBlock() if maybe_pos else out
1072 keep = BasicBlock()
1073 self.add(Branch(value, skip, keep, Branch.IS_ERROR))
1074 self.activate_block(keep)
1075
1076 # If this could be positional or named and we /might/ have seen a missing
1077 # positional arg, then we need to compile *both* a positional and named
1078 # version! What a pain!
1079 if maybe_pos and maybe_named and seen_empty_reg:
1080 pos_block, named_block = BasicBlock(), BasicBlock()
1081 self.add(Branch(seen_empty_reg, named_block, pos_block, Branch.BOOL))
1082 else:
1083 pos_block = named_block = BasicBlock()
1084 self.goto(pos_block)
1085
1086 if maybe_pos:
1087 self.activate_block(pos_block)
1088 assert star_result
1089 self.translate_special_method_call(
1090 star_result, "append", [value], result_type=None, line=line
1091 )
1092 self.goto(out)
1093
1094 if maybe_named and (not maybe_pos or seen_empty_reg):
1095 self.activate_block(named_block)
1096 assert name is not None
1097 key = self.load_str(name)
1098 assert star2_result
1099 self.translate_special_method_call(
1100 star2_result, "__setitem__", [key, value], result_type=None, line=line
1101 )
1102 self.goto(out)
1103
1104 if nullable and maybe_pos and new_seen_empty_reg:
1105 assert skip is not out
1106 self.activate_block(skip)
1107 self.add(Assign(new_seen_empty_reg, self.true(), line))
1108 self.goto(out)
1109
1110 self.activate_block(out)
1111
1112 seen_empty_reg = new_seen_empty_reg
1113
1114 assert not (star_result or star_values) or has_star
1115 assert not (star2_result or star2_values) or has_star2
1116 if has_star:
1117 # If we managed to make it this far without creating a
1118 # *args list, then we can directly create a
1119 # tuple. Otherwise create the tuple from the list.
1120 if star_result is None:
1121 star_result = self.new_tuple(star_values, line)
1122 elif not is_tuple_rprimitive(star_result.type):
1123 # if star_result is a tuple we took the fast path
1124 star_result = self.primitive_op(list_tuple_op, [star_result], line)
1125 if has_star2 and star2_result is None and len(star2_keys) > 0:
1126 # TODO: use dict_copy_op for simple cases of **kwargs
1127 star2_result = self._create_dict(star2_keys, star2_values, line)
1128
1129 return star_result, star2_result
1130
1131 def py_call(
1132 self,
1133 function: Value,
1134 arg_values: list[Value],
1135 line: int,
1136 arg_kinds: list[ArgKind] | None = None,
1137 arg_names: Sequence[str | None] | None = None,
1138 ) -> Value:
1139 """Call a Python function (non-native and slow).
1140
1141 Use py_call_op or py_call_with_kwargs_op for Python function call.
1142 """
1143 result = self._py_vector_call(function, arg_values, line, arg_kinds, arg_names)
1144 if result is not None:
1145 return result
1146
1147 # If all arguments are positional, we can use py_call_op.
1148 if arg_kinds is None or all(kind == ARG_POS for kind in arg_kinds):
1149 return self.call_c(py_call_op, [function] + arg_values, line)
1150
1151 # Otherwise fallback to py_call_with_posargs_op or py_call_with_kwargs_op.
1152 assert arg_names is not None
1153
1154 pos_args_tuple, kw_args_dict = self._construct_varargs(
1155 list(zip(arg_values, arg_kinds, arg_names)), line, has_star=True, has_star2=True
1156 )
1157 assert pos_args_tuple
1158
1159 if kw_args_dict is None:
1160 return self.call_c(py_call_with_posargs_op, [function, pos_args_tuple], line)
1161
1162 return self.call_c(py_call_with_kwargs_op, [function, pos_args_tuple, kw_args_dict], line)
1163
1164 def _py_vector_call(
1165 self,
1166 function: Value,
1167 arg_values: list[Value],
1168 line: int,
1169 arg_kinds: list[ArgKind] | None = None,
1170 arg_names: Sequence[str | None] | None = None,
1171 ) -> Value | None:
1172 """Call function using the vectorcall API if possible.
1173
1174 Return the return value if successful. Return None if a non-vectorcall
1175 API should be used instead.
1176 """
1177 # We can do this if all args are positional or named (no *args or **kwargs, not optional).
1178 if arg_kinds is None or all(
1179 not kind.is_star() and not kind.is_optional() for kind in arg_kinds
1180 ):
1181 if arg_values:
1182 # Create a C array containing all arguments as boxed values.
1183 coerced_args = [self.coerce(arg, object_rprimitive, line) for arg in arg_values]
1184 arg_ptr = self.setup_rarray(object_rprimitive, coerced_args, line, object_ptr=True)
1185 else:
1186 arg_ptr = Integer(0, object_pointer_rprimitive)
1187 num_pos = num_positional_args(arg_values, arg_kinds)
1188 keywords = self._vectorcall_keywords(arg_names)
1189 value = self.call_c(
1190 py_vectorcall_op,
1191 [function, arg_ptr, Integer(num_pos, c_size_t_rprimitive), keywords],
1192 line,
1193 )
1194 if arg_values:
1195 # Make sure arguments won't be freed until after the call.
1196 # We need this because RArray doesn't support automatic
1197 # memory management.
1198 self.add(KeepAlive(coerced_args, line))
1199 return value
1200 return None
1201
1202 def _vectorcall_keywords(self, arg_names: Sequence[str | None] | None) -> Value:
1203 """Return a reference to a tuple literal with keyword argument names.
1204
1205 Return null pointer if there are no keyword arguments.
1206 """
1207 if arg_names:
1208 kw_list = [name for name in arg_names if name is not None]
1209 if kw_list:
1210 return self.add(LoadLiteral(tuple(kw_list), object_rprimitive))
1211 return Integer(0, object_rprimitive)
1212
1213 def py_method_call(
1214 self,
1215 obj: Value,
1216 method_name: str,
1217 arg_values: list[Value],
1218 line: int,
1219 arg_kinds: list[ArgKind] | None,
1220 arg_names: Sequence[str | None] | None,
1221 ) -> Value:
1222 """Call a Python method (non-native and slow)."""
1223 result = self._py_vector_method_call(
1224 obj, method_name, arg_values, line, arg_kinds, arg_names
1225 )
1226 if result is not None:
1227 return result
1228
1229 if arg_kinds is None or all(kind == ARG_POS for kind in arg_kinds):
1230 # Use legacy method call API
1231 method_name_reg = self.load_str(method_name)
1232 return self.call_c(py_method_call_op, [obj, method_name_reg] + arg_values, line)
1233 else:
1234 # Use py_call since it supports keyword arguments (and vectorcalls).
1235 method = self.py_get_attr(obj, method_name, line)
1236 return self.py_call(method, arg_values, line, arg_kinds=arg_kinds, arg_names=arg_names)
1237
1238 def _py_vector_method_call(
1239 self,
1240 obj: Value,
1241 method_name: str,
1242 arg_values: list[Value],
1243 line: int,
1244 arg_kinds: list[ArgKind] | None,
1245 arg_names: Sequence[str | None] | None,
1246 ) -> Value | None:
1247 """Call method using the vectorcall API if possible.
1248
1249 Return the return value if successful. Return None if a non-vectorcall
1250 API should be used instead.
1251 """
1252 if arg_kinds is None or all(
1253 not kind.is_star() and not kind.is_optional() for kind in arg_kinds
1254 ):
1255 method_name_reg = self.load_str(method_name)
1256 coerced_args = [
1257 self.coerce(arg, object_rprimitive, line) for arg in [obj] + arg_values
1258 ]
1259 arg_ptr = self.setup_rarray(object_rprimitive, coerced_args, line, object_ptr=True)
1260 num_pos = num_positional_args(arg_values, arg_kinds)
1261 keywords = self._vectorcall_keywords(arg_names)
1262 value = self.call_c(
1263 py_vectorcall_method_op,
1264 [
1265 method_name_reg,
1266 arg_ptr,
1267 Integer((num_pos + 1) | PY_VECTORCALL_ARGUMENTS_OFFSET, c_size_t_rprimitive),
1268 keywords,
1269 ],
1270 line,
1271 )
1272 # Make sure arguments won't be freed until after the call.
1273 # We need this because RArray doesn't support automatic
1274 # memory management.
1275 self.add(KeepAlive(coerced_args, line))
1276 return value
1277 return None
1278
1279 def call(
1280 self,
1281 decl: FuncDecl,
1282 args: Sequence[Value],
1283 arg_kinds: list[ArgKind],
1284 arg_names: Sequence[str | None],
1285 line: int,
1286 *,
1287 bitmap_args: list[Register] | None = None,
1288 ) -> Value:
1289 """Call a native function.
1290
1291 If bitmap_args is given, they override the values of (some) of the bitmap
1292 arguments used to track the presence of values for certain arguments. By
1293 default, the values of the bitmap arguments are inferred from args.
1294 """
1295 # Normalize args to positionals.
1296 args = self.native_args_to_positional(
1297 args, arg_kinds, arg_names, decl.sig, line, bitmap_args=bitmap_args
1298 )
1299 return self.add(Call(decl, args, line))
1300
1301 def native_args_to_positional(
1302 self,
1303 args: Sequence[Value],
1304 arg_kinds: list[ArgKind],
1305 arg_names: Sequence[str | None],
1306 sig: FuncSignature,
1307 line: int,
1308 *,
1309 bitmap_args: list[Register] | None = None,
1310 ) -> list[Value]:
1311 """Prepare arguments for a native call.
1312
1313 Given args/kinds/names and a target signature for a native call, map
1314 keyword arguments to their appropriate place in the argument list,
1315 fill in error values for unspecified default arguments,
1316 package arguments that will go into *args/**kwargs into a tuple/dict,
1317 and coerce arguments to the appropriate type.
1318 """
1319
1320 sig_args = sig.args
1321 n = sig.num_bitmap_args
1322 if n:
1323 sig_args = sig_args[:-n]
1324
1325 sig_arg_kinds = [arg.kind for arg in sig_args]
1326 sig_arg_names = [arg.name for arg in sig_args]
1327
1328 concrete_kinds = [concrete_arg_kind(arg_kind) for arg_kind in arg_kinds]
1329 formal_to_actual = map_actuals_to_formals(
1330 concrete_kinds,
1331 arg_names,
1332 sig_arg_kinds,
1333 sig_arg_names,
1334 lambda n: AnyType(TypeOfAny.special_form),
1335 )
1336
1337 # First scan for */** and construct those
1338 has_star = has_star2 = False
1339 star_arg_entries = []
1340 for lst, arg in zip(formal_to_actual, sig_args):
1341 if arg.kind.is_star():
1342 star_arg_entries.extend([(args[i], arg_kinds[i], arg_names[i]) for i in lst])
1343 has_star = has_star or arg.kind == ARG_STAR
1344 has_star2 = has_star2 or arg.kind == ARG_STAR2
1345
1346 star_arg, star2_arg = self._construct_varargs(
1347 star_arg_entries, line, has_star=has_star, has_star2=has_star2
1348 )
1349
1350 # Flatten out the arguments, loading error values for default
1351 # arguments, constructing tuples/dicts for star args, and
1352 # coercing everything to the expected type.
1353 output_args: list[Value] = []
1354 for lst, arg in zip(formal_to_actual, sig_args):
1355 if arg.kind == ARG_STAR:
1356 assert star_arg
1357 output_arg = star_arg
1358 elif arg.kind == ARG_STAR2:
1359 output_arg = star2_arg or self._create_dict([], [], line)
1360 elif not lst:
1361 if is_fixed_width_rtype(arg.type):
1362 output_arg = Integer(0, arg.type)
1363 elif is_float_rprimitive(arg.type):
1364 output_arg = Float(0.0)
1365 else:
1366 output_arg = self.add(LoadErrorValue(arg.type, is_borrowed=True))
1367 else:
1368 base_arg = args[lst[0]]
1369
1370 if arg_kinds[lst[0]].is_optional():
1371 output_arg = self.coerce_nullable(base_arg, arg.type, line)
1372 else:
1373 output_arg = self.coerce(base_arg, arg.type, line)
1374
1375 output_args.append(output_arg)
1376
1377 for i in reversed(range(n)):
1378 if bitmap_args and i < len(bitmap_args):
1379 # Use override provided by caller
1380 output_args.append(bitmap_args[i])
1381 continue
1382 # Infer values of bitmap args
1383 bitmap = 0
1384 c = 0
1385 for lst, arg in zip(formal_to_actual, sig_args):
1386 if arg.kind.is_optional() and arg.type.error_overlap:
1387 if i * BITMAP_BITS <= c < (i + 1) * BITMAP_BITS:
1388 if lst:
1389 bitmap |= 1 << (c & (BITMAP_BITS - 1))
1390 c += 1
1391 output_args.append(Integer(bitmap, bitmap_rprimitive))
1392
1393 return output_args
1394
1395 def gen_method_call(
1396 self,
1397 base: Value,
1398 name: str,
1399 arg_values: list[Value],
1400 result_type: RType | None,
1401 line: int,
1402 arg_kinds: list[ArgKind] | None = None,
1403 arg_names: list[str | None] | None = None,
1404 can_borrow: bool = False,
1405 ) -> Value:
1406 """Generate either a native or Python method call."""
1407 # If we have *args, then fallback to Python method call.
1408 if arg_kinds is not None and any(kind.is_star() for kind in arg_kinds):
1409 return self.py_method_call(base, name, arg_values, line, arg_kinds, arg_names)
1410
1411 # If the base type is one of ours, do a MethodCall
1412 fast_name = FAST_PREFIX + name
1413 if (
1414 isinstance(base.type, RInstance)
1415 and (base.type.class_ir.is_ext_class or base.type.class_ir.has_method(fast_name))
1416 and not base.type.class_ir.builtin_base
1417 ):
1418 name = name if base.type.class_ir.is_ext_class else fast_name
1419 if base.type.class_ir.has_method(name):
1420 decl = base.type.class_ir.method_decl(name)
1421 if arg_kinds is None:
1422 assert arg_names is None, "arg_kinds not present but arg_names is"
1423 arg_kinds = [ARG_POS for _ in arg_values]
1424 arg_names = [None for _ in arg_values]
1425 else:
1426 assert arg_names is not None, "arg_kinds present but arg_names is not"
1427
1428 # Normalize args to positionals.
1429 assert decl.bound_sig
1430 arg_values = self.native_args_to_positional(
1431 arg_values, arg_kinds, arg_names, decl.bound_sig, line
1432 )
1433 return self.add(MethodCall(base, name, arg_values, line))
1434 elif base.type.class_ir.has_attr(name):
1435 function = self.add(GetAttr(base, name, line))
1436 return self.py_call(
1437 function, arg_values, line, arg_kinds=arg_kinds, arg_names=arg_names
1438 )
1439
1440 elif isinstance(base.type, RUnion):
1441 return self.union_method_call(
1442 base, base.type, name, arg_values, result_type, line, arg_kinds, arg_names
1443 )
1444
1445 # Try to do a special-cased method call
1446 if not arg_kinds or arg_kinds == [ARG_POS] * len(arg_values):
1447 target = self.translate_special_method_call(
1448 base, name, arg_values, result_type, line, can_borrow=can_borrow
1449 )
1450 if target:
1451 return target
1452
1453 # Fall back to Python method call
1454 return self.py_method_call(base, name, arg_values, line, arg_kinds, arg_names)
1455
1456 def union_method_call(
1457 self,
1458 base: Value,
1459 obj_type: RUnion,
1460 name: str,
1461 arg_values: list[Value],
1462 return_rtype: RType | None,
1463 line: int,
1464 arg_kinds: list[ArgKind] | None,
1465 arg_names: list[str | None] | None,
1466 ) -> Value:
1467 """Generate a method call with a union type for the object."""
1468 # Union method call needs a return_rtype for the type of the output register.
1469 # If we don't have one, use object_rprimitive.
1470 return_rtype = return_rtype or object_rprimitive
1471
1472 def call_union_item(value: Value) -> Value:
1473 return self.gen_method_call(
1474 value, name, arg_values, return_rtype, line, arg_kinds, arg_names
1475 )
1476
1477 return self.decompose_union_helper(base, obj_type, return_rtype, call_union_item, line)
1478
1479 # Loading various values
1480
1481 def none(self, line: int = -1) -> Value:
1482 """Load unboxed None value (type: none_rprimitive)."""
1483 return Integer(1, none_rprimitive, line)
1484
1485 def true(self, line: int = -1) -> Value:
1486 """Load unboxed True value (type: bool_rprimitive)."""
1487 return Integer(1, bool_rprimitive, line)
1488
1489 def false(self, line: int = -1) -> Value:
1490 """Load unboxed False value (type: bool_rprimitive)."""
1491 return Integer(0, bool_rprimitive, line)
1492
1493 def none_object(self, line: int = -1) -> Value:
1494 """Load Python None value (type: object_rprimitive)."""
1495 return self.add(LoadAddress(none_object_op.type, none_object_op.src, line))
1496
1497 def true_object(self, line: int = -1) -> Value:
1498 """Load Python True object (type: object_rprimitive)."""
1499 return self.add(LoadGlobal(object_rprimitive, "Py_True", line))
1500
1501 def false_object(self, line: int = -1) -> Value:
1502 """Load Python False object (type: object_rprimitive)."""
1503 return self.add(LoadGlobal(object_rprimitive, "Py_False", line))
1504
1505 def load_int(self, value: int, line: int = -1) -> Value:
1506 """Load a tagged (Python) integer literal value."""
1507 if value > MAX_LITERAL_SHORT_INT or value < MIN_LITERAL_SHORT_INT:
1508 return self.add(LoadLiteral(value, int_rprimitive, line))
1509 else:
1510 return Integer(value, line=line)
1511
1512 def load_float(self, value: float, line: int = -1) -> Value:
1513 """Load a float literal value."""
1514 return Float(value, line)
1515
1516 def load_str(self, value: str, line: int = -1) -> Value:
1517 """Load a str literal value.
1518
1519 This is useful for more than just str literals; for example, method calls
1520 also require a PyObject * form for the name of the method.
1521 """
1522 return self.add(LoadLiteral(value, str_rprimitive, line))
1523
1524 def load_bytes(self, value: bytes, line: int = -1) -> Value:
1525 """Load a bytes literal value."""
1526 return self.add(LoadLiteral(value, bytes_rprimitive, line))
1527
1528 def load_complex(self, value: complex, line: int = -1) -> Value:
1529 """Load a complex literal value."""
1530 return self.add(LoadLiteral(value, object_rprimitive, line))
1531
1532 def load_static_checked(
1533 self,
1534 typ: RType,
1535 identifier: str,
1536 module_name: str | None = None,
1537 namespace: str = NAMESPACE_STATIC,
1538 line: int = -1,
1539 error_msg: str | None = None,
1540 ) -> Value:
1541 if error_msg is None:
1542 error_msg = f'name "{identifier}" is not defined'
1543 ok_block, error_block = BasicBlock(), BasicBlock()
1544 value = self.add(LoadStatic(typ, identifier, module_name, namespace, line=line))
1545 self.add(Branch(value, error_block, ok_block, Branch.IS_ERROR, rare=True))
1546 self.activate_block(error_block)
1547 self.add(RaiseStandardError(RaiseStandardError.NAME_ERROR, error_msg, line))
1548 self.add(Unreachable())
1549 self.activate_block(ok_block)
1550 return value
1551
1552 def load_module(self, name: str) -> Value:
1553 return self.add(LoadStatic(object_rprimitive, name, namespace=NAMESPACE_MODULE))
1554
1555 def get_native_type(self, cls: ClassIR) -> Value:
1556 """Load native type object."""
1557 fullname = f"{cls.module_name}.{cls.name}"
1558 return self.load_native_type_object(fullname)
1559
1560 def load_native_type_object(self, fullname: str) -> Value:
1561 module, name = fullname.rsplit(".", 1)
1562 return self.add(LoadStatic(object_rprimitive, name, module, NAMESPACE_TYPE))
1563
1564 # Other primitive operations
1565
1566 def binary_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value:
1567 """Perform a binary operation.
1568
1569 Generate specialized operations based on operand types, with a fallback
1570 to generic operations.
1571 """
1572 ltype = lreg.type
1573 rtype = rreg.type
1574
1575 # Special case tuple comparison here so that nested tuples can be supported
1576 if isinstance(ltype, RTuple) and isinstance(rtype, RTuple) and op in ("==", "!="):
1577 return self.compare_tuples(lreg, rreg, op, line)
1578
1579 # Special case == and != when we can resolve the method call statically
1580 if op in ("==", "!="):
1581 value = self.translate_eq_cmp(lreg, rreg, op, line)
1582 if value is not None:
1583 return value
1584
1585 # Special case various ops
1586 if op in ("is", "is not"):
1587 return self.translate_is_op(lreg, rreg, op, line)
1588 if (
1589 is_bool_or_bit_rprimitive(ltype)
1590 and is_bool_or_bit_rprimitive(rtype)
1591 and op in BOOL_BINARY_OPS
1592 ):
1593 if op in ComparisonOp.signed_ops:
1594 return self.bool_comparison_op(lreg, rreg, op, line)
1595 else:
1596 return self.bool_bitwise_op(lreg, rreg, op[0], line)
1597 if isinstance(rtype, RInstance) and op in ("in", "not in"):
1598 return self.translate_instance_contains(rreg, lreg, op, line)
1599 if is_fixed_width_rtype(ltype):
1600 if op in FIXED_WIDTH_INT_BINARY_OPS:
1601 op = op.removesuffix("=")
1602 if op != "//":
1603 op_id = int_op_to_id[op]
1604 else:
1605 op_id = IntOp.DIV
1606 if is_bool_or_bit_rprimitive(rtype):
1607 rreg = self.coerce(rreg, ltype, line)
1608 rtype = ltype
1609 if is_fixed_width_rtype(rtype) or is_tagged(rtype):
1610 return self.fixed_width_int_op(ltype, lreg, rreg, op_id, line)
1611 if isinstance(rreg, Integer):
1612 return self.fixed_width_int_op(
1613 ltype, lreg, self.coerce(rreg, ltype, line), op_id, line
1614 )
1615 elif op in ComparisonOp.signed_ops:
1616 if is_int_rprimitive(rtype):
1617 rreg = self.coerce_int_to_fixed_width(rreg, ltype, line)
1618 elif is_bool_or_bit_rprimitive(rtype):
1619 rreg = self.coerce(rreg, ltype, line)
1620 op_id = ComparisonOp.signed_ops[op]
1621 if is_fixed_width_rtype(rreg.type):
1622 return self.comparison_op(lreg, rreg, op_id, line)
1623 if isinstance(rreg, Integer):
1624 return self.comparison_op(lreg, self.coerce(rreg, ltype, line), op_id, line)
1625 elif is_fixed_width_rtype(rtype):
1626 if op in FIXED_WIDTH_INT_BINARY_OPS:
1627 op = op.removesuffix("=")
1628 if op != "//":
1629 op_id = int_op_to_id[op]
1630 else:
1631 op_id = IntOp.DIV
1632 if isinstance(lreg, Integer):
1633 return self.fixed_width_int_op(
1634 rtype, self.coerce(lreg, rtype, line), rreg, op_id, line
1635 )
1636 if is_tagged(ltype):
1637 return self.fixed_width_int_op(rtype, lreg, rreg, op_id, line)
1638 if is_bool_or_bit_rprimitive(ltype):
1639 lreg = self.coerce(lreg, rtype, line)
1640 return self.fixed_width_int_op(rtype, lreg, rreg, op_id, line)
1641 elif op in ComparisonOp.signed_ops:
1642 if is_int_rprimitive(ltype):
1643 lreg = self.coerce_int_to_fixed_width(lreg, rtype, line)
1644 elif is_bool_or_bit_rprimitive(ltype):
1645 lreg = self.coerce(lreg, rtype, line)
1646 op_id = ComparisonOp.signed_ops[op]
1647 if isinstance(lreg, Integer):
1648 return self.comparison_op(self.coerce(lreg, rtype, line), rreg, op_id, line)
1649 if is_fixed_width_rtype(lreg.type):
1650 return self.comparison_op(lreg, rreg, op_id, line)
1651
1652 if is_float_rprimitive(ltype) or is_float_rprimitive(rtype):
1653 if isinstance(lreg, Integer):
1654 lreg = Float(float(lreg.numeric_value()))
1655 elif isinstance(rreg, Integer):
1656 rreg = Float(float(rreg.numeric_value()))
1657 elif is_int_rprimitive(lreg.type):
1658 lreg = self.int_to_float(lreg, line)
1659 elif is_int_rprimitive(rreg.type):
1660 rreg = self.int_to_float(rreg, line)
1661 if is_float_rprimitive(lreg.type) and is_float_rprimitive(rreg.type):
1662 if op in float_comparison_op_to_id:
1663 return self.compare_floats(lreg, rreg, float_comparison_op_to_id[op], line)
1664 if op.endswith("="):
1665 base_op = op[:-1]
1666 else:
1667 base_op = op
1668 if base_op in float_op_to_id:
1669 return self.float_op(lreg, rreg, base_op, line)
1670
1671 dunder_op = self.dunder_op(lreg, rreg, op, line)
1672 if dunder_op:
1673 return dunder_op
1674
1675 if isinstance(rtype, RVec) and op == "in":
1676 return vec_contains(self, rreg, lreg, line)
1677
1678 primitive_ops_candidates = binary_ops.get(op, [])
1679 target = self.matching_primitive_op(primitive_ops_candidates, [lreg, rreg], line)
1680 assert target, "Unsupported binary operation: %s" % op
1681 return target
1682
1683 def dunder_op(self, lreg: Value, rreg: Value | None, op: str, line: int) -> Value | None:
1684 """
1685 Dispatch a dunder method if applicable.
1686
1687 For example for `a + b` it will use `a.__add__(b)` which can lead to higher performance
1688 due to the fact that the method could be already compiled and optimized instead of going
1689 all the way through `PyNumber_Add(a, b)` python api (making a jump into the python DL).
1690 """
1691 ltype = lreg.type
1692 if not isinstance(ltype, RInstance):
1693 return None
1694
1695 method_name = op_methods.get(op) if rreg else unary_op_methods.get(op)
1696 if method_name is None:
1697 return None
1698
1699 if not ltype.class_ir.has_method(method_name):
1700 return None
1701
1702 decl = ltype.class_ir.method_decl(method_name)
1703 if not rreg and len(decl.sig.args) != 1:
1704 return None
1705
1706 if rreg and (len(decl.sig.args) != 2 or not is_subtype(rreg.type, decl.sig.args[1].type)):
1707 return None
1708
1709 if rreg and is_subtype(not_implemented_op.type, decl.sig.ret_type):
1710 # If the method is able to return NotImplemented, we should not optimize it.
1711 # We can just let go so it will be handled through the python api.
1712 return None
1713
1714 args = [rreg] if rreg else []
1715 return self.gen_method_call(lreg, method_name, args, decl.sig.ret_type, line)
1716
1717 def check_tagged_short_int(self, val: Value, line: int, negated: bool = False) -> Value:
1718 """Check if a tagged integer is a short integer.
1719
1720 Return the result of the check (value of type 'bit').
1721 """
1722 int_tag = Integer(1, c_pyssize_t_rprimitive, line)
1723 bitwise_and = self.int_op(c_pyssize_t_rprimitive, val, int_tag, IntOp.AND, line)
1724 zero = Integer(0, c_pyssize_t_rprimitive, line)
1725 op = ComparisonOp.NEQ if negated else ComparisonOp.EQ
1726 check = self.comparison_op(bitwise_and, zero, op, line)
1727 return check
1728
1729 def compare_strings(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:
1730 """Compare two strings"""
1731 if op == "==":
1732 # We can specialize this case if one or both values are string literals
1733 literal_fastpath = False
1734
1735 def is_string_literal(value: Value) -> TypeGuard[LoadLiteral]:
1736 return isinstance(value, LoadLiteral) and is_str_rprimitive(value.type)
1737
1738 if is_string_literal(lhs):
1739 if is_string_literal(rhs):
1740 # we can optimize out the check entirely in some constant-folded cases
1741 return self.true() if lhs.value == rhs.value else self.false()
1742
1743 # if lhs argument is string literal, switch sides to match specializer C api
1744 lhs, rhs = rhs, lhs
1745 literal_fastpath = True
1746 elif is_string_literal(rhs):
1747 literal_fastpath = True
1748
1749 if literal_fastpath:
1750 literal_string = cast(str, cast(LoadLiteral, rhs).value)
1751 literal_length = Integer(len(literal_string), c_pyssize_t_rprimitive, line)
1752 return self.primitive_op(str_eq_literal, [lhs, rhs, literal_length], line)
1753
1754 return self.primitive_op(str_eq, [lhs, rhs], line)
1755
1756 elif op == "!=":
1757 # perform a standard equality check, then negate
1758 eq = self.compare_strings(lhs, rhs, "==", line)
1759 return self.add(ComparisonOp(eq, self.false(), ComparisonOp.EQ, line))
1760
1761 # TODO: modify 'str' to use same interface as 'compare_bytes' as it would avoid
1762 # call to PyErr_Occurred() below
1763
1764 compare_result = self.call_c(unicode_compare, [lhs, rhs], line)
1765 error_constant = Integer(-1, c_int_rprimitive, line)
1766 compare_error_check = self.add(
1767 ComparisonOp(compare_result, error_constant, ComparisonOp.EQ, line)
1768 )
1769 exception_check, propagate, final_compare = BasicBlock(), BasicBlock(), BasicBlock()
1770 branch = Branch(compare_error_check, exception_check, final_compare, Branch.BOOL)
1771 branch.negated = False
1772 self.add(branch)
1773 self.activate_block(exception_check)
1774 check_error_result = self.call_c(err_occurred_op, [], line)
1775 null = Integer(0, pointer_rprimitive, line)
1776 compare_error_check = self.add(
1777 ComparisonOp(check_error_result, null, ComparisonOp.NEQ, line)
1778 )
1779 branch = Branch(compare_error_check, propagate, final_compare, Branch.BOOL)
1780 branch.negated = False
1781 self.add(branch)
1782 self.activate_block(propagate)
1783 self.call_c(keep_propagating_op, [], line)
1784 self.goto(final_compare)
1785 self.activate_block(final_compare)
1786 op_type = ComparisonOp.EQ if op == "==" else ComparisonOp.NEQ
1787 return self.add(ComparisonOp(compare_result, Integer(0, c_int_rprimitive), op_type, line))
1788
1789 def compare_bytes(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:
1790 compare_result = self.call_c(bytes_compare, [lhs, rhs], line)
1791 op_type = ComparisonOp.EQ if op == "==" else ComparisonOp.NEQ
1792 return self.add(ComparisonOp(compare_result, Integer(1, c_int_rprimitive), op_type, line))
1793
1794 def compare_tuples(self, lhs: Value, rhs: Value, op: str, line: int = -1) -> Value:
1795 """Compare two tuples item by item"""
1796 # type cast to pass mypy check
1797 assert isinstance(lhs.type, RTuple) and isinstance(rhs.type, RTuple), (lhs.type, rhs.type)
1798 equal = True if op == "==" else False
1799 result = Register(bool_rprimitive)
1800 # tuples of different lengths
1801 if len(lhs.type.types) != len(rhs.type.types):
1802 self.add(Assign(result, self.false() if equal else self.true(), line))
1803 return result
1804 # empty tuples
1805 if len(lhs.type.types) == 0 and len(rhs.type.types) == 0:
1806 self.add(Assign(result, self.true() if equal else self.false(), line))
1807 return result
1808 length = len(lhs.type.types)
1809 false_assign, true_assign, out = BasicBlock(), BasicBlock(), BasicBlock()
1810 check_blocks = [BasicBlock() for _ in range(length)]
1811 lhs_items = [self.add(TupleGet(lhs, i, line)) for i in range(length)]
1812 rhs_items = [self.add(TupleGet(rhs, i, line)) for i in range(length)]
1813
1814 if equal:
1815 early_stop, final = false_assign, true_assign
1816 else:
1817 early_stop, final = true_assign, false_assign
1818
1819 for i in range(len(lhs.type.types)):
1820 if i != 0:
1821 self.activate_block(check_blocks[i])
1822 lhs_item = lhs_items[i]
1823 rhs_item = rhs_items[i]
1824 compare = self.binary_op(lhs_item, rhs_item, op, line)
1825 # Cast to bool if necessary since most types uses comparison returning a object type
1826 # See generic_ops.py for more information
1827 if not is_bool_or_bit_rprimitive(compare.type):
1828 compare = self.primitive_op(bool_op, [compare], line)
1829 if i < len(lhs.type.types) - 1:
1830 branch = Branch(compare, early_stop, check_blocks[i + 1], Branch.BOOL)
1831 else:
1832 branch = Branch(compare, early_stop, final, Branch.BOOL)
1833 # if op is ==, we branch on false, else branch on true
1834 branch.negated = equal
1835 self.add(branch)
1836 self.activate_block(false_assign)
1837 self.add(Assign(result, self.false(), line))
1838 self.goto(out)
1839 self.activate_block(true_assign)
1840 self.add(Assign(result, self.true(), line))
1841 self.goto_and_activate(out)
1842 return result
1843
1844 def translate_instance_contains(self, inst: Value, item: Value, op: str, line: int) -> Value:
1845 res = self.gen_method_call(inst, "__contains__", [item], None, line)
1846 if not is_bool_or_bit_rprimitive(res.type):
1847 res = self.primitive_op(bool_op, [res], line)
1848 if op == "not in":
1849 res = self.bool_bitwise_op(res, Integer(1, rtype=bool_rprimitive), "^", line)
1850 return res
1851
1852 def bool_bitwise_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value:
1853 if op == "&":
1854 code = IntOp.AND
1855 elif op == "|":
1856 code = IntOp.OR
1857 elif op == "^":
1858 code = IntOp.XOR
1859 else:
1860 assert False, op
1861 return self.add(IntOp(bool_rprimitive, lreg, rreg, code, line))
1862
1863 def bool_comparison_op(self, lreg: Value, rreg: Value, op: str, line: int) -> Value:
1864 op_id = ComparisonOp.signed_ops[op]
1865 return self.comparison_op(lreg, rreg, op_id, line)
1866
1867 def _non_specialized_unary_op(self, value: Value, op: str, line: int) -> Value:
1868 if isinstance(value.type, RInstance):
1869 result = self.dunder_op(value, None, op, line)
1870 if result is not None:
1871 return result
1872 primitive_ops_candidates = unary_ops.get(op, [])
1873 target = self.matching_primitive_op(primitive_ops_candidates, [value], line)
1874 assert target, "Unsupported unary operation: %s" % op
1875 return target
1876
1877 def unary_not(self, value: Value, line: int, *, likely_bool: bool = False) -> Value:
1878 """Perform unary 'not'.
1879
1880 Args:
1881 likely_bool: The operand is likely a bool value, even if the type is something
1882 more general, so specialize for bool values
1883 """
1884 typ = value.type
1885 if is_bool_or_bit_rprimitive(typ):
1886 mask = Integer(1, typ, line)
1887 return self.int_op(typ, value, mask, IntOp.XOR, line)
1888 if is_tagged(typ) or is_fixed_width_rtype(typ):
1889 return self.binary_op(value, Integer(0), "==", line)
1890 if (
1891 is_str_rprimitive(typ)
1892 or is_list_rprimitive(typ)
1893 or is_tuple_rprimitive(typ)
1894 or is_dict_rprimitive(typ)
1895 or isinstance(typ, RInstance)
1896 ):
1897 bool_val = self.bool_value(value)
1898 return self.unary_not(bool_val, line)
1899 if is_optional_type(typ):
1900 value_typ = optional_value_type(typ)
1901 assert value_typ
1902 if (
1903 is_str_rprimitive(value_typ)
1904 or is_list_rprimitive(value_typ)
1905 or is_tuple_rprimitive(value_typ)
1906 or is_dict_rprimitive(value_typ)
1907 or isinstance(value_typ, RInstance)
1908 ):
1909 # 'X | None' type: Check for None first and then specialize for X.
1910 res = Register(bit_rprimitive)
1911 cmp = self.add(ComparisonOp(value, self.none_object(), ComparisonOp.EQ, line))
1912 none, not_none, out = BasicBlock(), BasicBlock(), BasicBlock()
1913 self.add(Branch(cmp, none, not_none, Branch.BOOL))
1914 self.activate_block(none)
1915 self.add(Assign(res, self.true()))
1916 self.goto(out)
1917 self.activate_block(not_none)
1918 val = self.unary_not(
1919 self.unbox_or_cast(value, value_typ, line, can_borrow=True, unchecked=True),
1920 line,
1921 )
1922 self.add(Assign(res, val))
1923 self.goto(out)
1924 self.activate_block(out)
1925 return res
1926 if likely_bool and is_object_rprimitive(typ):
1927 # First quickly check if it's a bool, and otherwise fall back to generic op.
1928 res = Register(bit_rprimitive)
1929 false, not_false, true, other = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock()
1930 out = BasicBlock()
1931 cmp = self.add(ComparisonOp(value, self.true_object(), ComparisonOp.EQ, line))
1932 self.add(Branch(cmp, false, not_false, Branch.BOOL))
1933 self.activate_block(false)
1934 self.add(Assign(res, self.false()))
1935 self.goto(out)
1936 self.activate_block(not_false)
1937 cmp = self.add(ComparisonOp(value, self.false_object(), ComparisonOp.EQ, line))
1938 self.add(Branch(cmp, true, other, Branch.BOOL))
1939 self.activate_block(true)
1940 self.add(Assign(res, self.true()))
1941 self.goto(out)
1942 self.activate_block(other)
1943 val = self._non_specialized_unary_op(value, "not", line)
1944 self.add(Assign(res, val))
1945 self.goto(out)
1946 self.activate_block(out)
1947 return res
1948 return self._non_specialized_unary_op(value, "not", line)
1949
1950 def unary_minus(self, value: Value, line: int) -> Value:
1951 """Perform unary '-'."""
1952 typ = value.type
1953 if isinstance(value, Integer):
1954 # TODO: Overflow? Unsigned?
1955 return Integer(-value.numeric_value(), typ, line)
1956 elif isinstance(value, Float):
1957 return Float(-value.value, line)
1958 elif is_fixed_width_rtype(typ):
1959 # Translate to '0 - x'
1960 return self.int_op(typ, Integer(0, typ), value, IntOp.SUB, line)
1961 elif is_float_rprimitive(typ):
1962 return self.add(FloatNeg(value, line))
1963 return self._non_specialized_unary_op(value, "-", line)
1964
1965 def unary_plus(self, value: Value, line: int) -> Value:
1966 """Perform unary '+'."""
1967 typ = value.type
1968 if (
1969 is_tagged(typ)
1970 or is_float_rprimitive(typ)
1971 or is_bool_or_bit_rprimitive(typ)
1972 or is_fixed_width_rtype(typ)
1973 ):
1974 return value
1975 return self._non_specialized_unary_op(value, "+", line)
1976
1977 def unary_invert(self, value: Value, line: int) -> Value:
1978 """Perform unary '~'."""
1979 typ = value.type
1980 if is_fixed_width_rtype(typ):
1981 if typ.is_signed:
1982 # Translate to 'x ^ -1'
1983 return self.int_op(typ, value, Integer(-1, typ), IntOp.XOR, line)
1984 else:
1985 # Translate to 'x ^ 0xff...'
1986 mask = (1 << (typ.size * 8)) - 1
1987 return self.int_op(typ, value, Integer(mask, typ), IntOp.XOR, line)
1988 return self._non_specialized_unary_op(value, "~", line)
1989
1990 def unary_op(self, value: Value, op: str, line: int) -> Value:
1991 """Perform a unary operation."""
1992 if op == "not":
1993 return self.unary_not(value, line)
1994 elif op == "-":
1995 return self.unary_minus(value, line)
1996 elif op == "+":
1997 return self.unary_plus(value, line)
1998 elif op == "~":
1999 return self.unary_invert(value, line)
2000 raise RuntimeError("Unsupported unary operation: %s" % op)
2001
2002 def get_item(
2003 self,
2004 base: Value,
2005 item: Value,
2006 result_type: RType | None,
2007 line: int,
2008 *,
2009 can_borrow: bool = False,
2010 ) -> Value:
2011 """Generate base[item]."""
2012 if isinstance(base.type, RVec):
2013 if is_int_rprimitive(item.type) or is_short_int_rprimitive(item.type):
2014 item = self.coerce(item, int64_rprimitive, line)
2015 if is_int64_rprimitive(item.type):
2016 return vec_get_item(self, base, item, line, can_borrow=can_borrow)
2017 # TODO: Move special casing for RTuple here from transform_index_expr
2018 return self.gen_method_call(
2019 base, "__getitem__", [item], result_type, line, can_borrow=can_borrow
2020 )
2021
2022 def make_dict(self, key_value_pairs: Sequence[DictEntry], line: int) -> Value:
2023 result: Value | None = None
2024 keys: list[Value] = []
2025 values: list[Value] = []
2026 for key, value in key_value_pairs:
2027 if key is not None:
2028 # key:value
2029 if result is None:
2030 keys.append(key)
2031 values.append(value)
2032 continue
2033
2034 self.translate_special_method_call(
2035 result, "__setitem__", [key, value], result_type=None, line=line
2036 )
2037 else:
2038 # **value
2039 if result is None:
2040 result = self._create_dict(keys, values, line)
2041
2042 self.call_c(dict_update_in_display_op, [result, value], line=line)
2043
2044 if result is None:
2045 result = self._create_dict(keys, values, line)
2046
2047 return result
2048
2049 def new_list_op_with_length(self, length: Value, line: int) -> Value:
2050 """This function returns an uninitialized list.
2051
2052 If the length is non-zero, the caller must initialize the list, before
2053 it can be made visible to user code -- otherwise the list object is broken.
2054 You might need further initialization with `new_list_set_item_op` op.
2055
2056 Args:
2057 length: desired length of the new list. The rtype should be
2058 c_pyssize_t_rprimitive
2059 line: line number
2060 """
2061 return self.call_c(new_list_op, [length], line)
2062
2063 def new_list_op(self, values: list[Value], line: int) -> Value:
2064 length: list[Value] = [Integer(len(values), c_pyssize_t_rprimitive, line)]
2065 if len(values) >= LIST_BUILDING_EXPANSION_THRESHOLD:
2066 return self.call_c(list_build_op, length + values, line)
2067
2068 # If the length of the list is less than the threshold,
2069 # LIST_BUILDING_EXPANSION_THRESHOLD, we directly expand the
2070 # for-loop and inline the SetMem operation, which is faster
2071 # than list_build_op, however generates more code.
2072 result_list = self.call_c(new_list_op, length, line)
2073 if not values:
2074 return result_list
2075 args = [self.coerce(item, object_rprimitive, line) for item in values]
2076 ob_item_base = self.add(PrimitiveOp([result_list], list_items, line))
2077 for i in range(len(values)):
2078 self.primitive_op(
2079 buf_init_item, [ob_item_base, Integer(i, c_pyssize_t_rprimitive), args[i]], line
2080 )
2081 self.add(KeepAlive([result_list], line))
2082 return result_list
2083
2084 def new_set_op(self, values: list[Value], line: int) -> Value:
2085 return self.primitive_op(new_set_op, values, line)
2086
2087 def setup_rarray(
2088 self, item_type: RType, values: Sequence[Value], line: int, *, object_ptr: bool = False
2089 ) -> Value:
2090 """Declare and initialize a new RArray, returning its address."""
2091 array = Register(RArray(item_type, len(values)))
2092 self.add(AssignMulti(array, list(values), line))
2093 return self.add(
2094 LoadAddress(object_pointer_rprimitive if object_ptr else c_pointer_rprimitive, array)
2095 )
2096
2097 def shortcircuit_helper(
2098 self,
2099 op: str,
2100 expr_type: RType,
2101 left: Callable[[], Value],
2102 right: Callable[[], Value],
2103 line: int,
2104 ) -> Value:
2105 # Having actual Phi nodes would be really nice here!
2106 target = Register(expr_type, line=line)
2107 # left_body takes the value of the left side, right_body the right
2108 left_body, right_body, next_block = BasicBlock(), BasicBlock(), BasicBlock()
2109 # true_body is taken if the left is true, false_body if it is false.
2110 # For 'and' the value is the right side if the left is true, and for 'or'
2111 # it is the right side if the left is false.
2112 true_body, false_body = (right_body, left_body) if op == "and" else (left_body, right_body)
2113
2114 left_value = left()
2115 self.add_bool_branch(left_value, true_body, false_body)
2116
2117 self.activate_block(left_body)
2118 left_coerced = self.coerce(left_value, expr_type, line)
2119 self.add(Assign(target, left_coerced, line))
2120 self.goto(next_block)
2121
2122 self.activate_block(right_body)
2123 right_value = right()
2124 right_coerced = self.coerce(right_value, expr_type, line)
2125 self.add(Assign(target, right_coerced, line))
2126 self.goto(next_block)
2127
2128 self.activate_block(next_block)
2129 return target
2130
2131 def bool_value(self, value: Value) -> Value:
2132 """Return bool(value).
2133
2134 The result type can be bit_rprimitive or bool_rprimitive.
2135 """
2136 if is_bool_or_bit_rprimitive(value.type):
2137 result = value
2138 elif is_runtime_subtype(value.type, int_rprimitive):
2139 zero = Integer(0, short_int_rprimitive)
2140 result = self.comparison_op(value, zero, ComparisonOp.NEQ, value.line)
2141 elif is_fixed_width_rtype(value.type):
2142 zero = Integer(0, value.type)
2143 result = self.add(ComparisonOp(value, zero, ComparisonOp.NEQ))
2144 elif is_str_rprimitive(value.type):
2145 result = self.call_c(str_check_if_true, [value], value.line)
2146 elif (
2147 is_list_rprimitive(value.type)
2148 or is_dict_rprimitive(value.type)
2149 or is_tuple_rprimitive(value.type)
2150 ):
2151 length = self.builtin_len(value, value.line)
2152 zero = Integer(0)
2153 result = self.binary_op(length, zero, "!=", value.line)
2154 elif (
2155 isinstance(value.type, RInstance)
2156 and value.type.class_ir.is_ext_class
2157 and value.type.class_ir.has_method("__bool__")
2158 ):
2159 # Directly call the __bool__ method on classes that have it.
2160 result = self.gen_method_call(value, "__bool__", [], bool_rprimitive, value.line)
2161 elif is_float_rprimitive(value.type):
2162 result = self.compare_floats(value, Float(0.0), FloatComparisonOp.NEQ, value.line)
2163 else:
2164 value_type = optional_value_type(value.type)
2165 if value_type is not None:
2166 not_none = self.translate_is_op(value, self.none_object(), "is not", value.line)
2167 always_truthy = False
2168 if isinstance(value_type, RInstance):
2169 # check whether X.__bool__ is always just the default (object.__bool__)
2170 if not value_type.class_ir.has_method(
2171 "__bool__"
2172 ) and value_type.class_ir.is_method_final("__bool__"):
2173 always_truthy = True
2174
2175 if always_truthy:
2176 result = not_none
2177 else:
2178 # "X | None" where X may be falsey and requires a check
2179 result = Register(bit_rprimitive)
2180 true, false, end = BasicBlock(), BasicBlock(), BasicBlock()
2181 branch = Branch(not_none, true, false, Branch.BOOL)
2182 self.add(branch)
2183 self.activate_block(true)
2184 # unbox_or_cast instead of coerce because we want the
2185 # type to change even if it is a subtype.
2186 remaining = self.unbox_or_cast(value, value_type, value.line)
2187 as_bool = self.bool_value(remaining)
2188 self.add(Assign(result, as_bool))
2189 self.goto(end)
2190 self.activate_block(false)
2191 self.add(Assign(result, Integer(0, bit_rprimitive)))
2192 self.goto(end)
2193 self.activate_block(end)
2194 else:
2195 result = self.primitive_op(bool_op, [value], value.line)
2196 return result
2197
2198 def add_bool_branch(self, value: Value, true: BasicBlock, false: BasicBlock) -> None:
2199 opt_value_type = optional_value_type(value.type)
2200 if opt_value_type is None:
2201 bool_value = self.bool_value(value)
2202 self.add(Branch(bool_value, true, false, Branch.BOOL, value.line))
2203 else:
2204 # Special-case optional types
2205 is_none = self.translate_is_op(value, self.none_object(), "is not", value.line)
2206 branch = Branch(is_none, true, false, Branch.BOOL, value.line)
2207 self.add(branch)
2208 always_truthy = False
2209 if isinstance(opt_value_type, RInstance):
2210 # check whether X.__bool__ is always just the default (object.__bool__)
2211 if not opt_value_type.class_ir.has_method(
2212 "__bool__"
2213 ) and opt_value_type.class_ir.is_method_final("__bool__"):
2214 always_truthy = True
2215
2216 if not always_truthy:
2217 # Optional[X] where X may be falsey and requires a check
2218 branch.true = BasicBlock()
2219 self.activate_block(branch.true)
2220 # unbox_or_cast instead of coerce because we want the
2221 # type to change even if it is a subtype.
2222 remaining = self.unbox_or_cast(value, opt_value_type, value.line)
2223 self.add_bool_branch(remaining, true, false)
2224
2225 def call_c(
2226 self,
2227 desc: CFunctionDescription,
2228 args: list[Value],
2229 line: int,
2230 result_type: RType | None = None,
2231 ) -> Value:
2232 """Call function using C/native calling convention (not a Python callable)."""
2233 # Handle void function via singleton RVoid instance
2234 coerced = []
2235 # Coerce fixed number arguments
2236 for i in range(min(len(args), len(desc.arg_types))):
2237 formal_type = desc.arg_types[i]
2238 arg = args[i]
2239 arg = self.coerce(arg, formal_type, line)
2240 coerced.append(arg)
2241 # Reorder args if necessary
2242 if desc.ordering is not None:
2243 assert desc.var_arg_type is None
2244 coerced = [coerced[i] for i in desc.ordering]
2245 # Coerce any var_arg
2246 var_arg_idx = -1
2247 if desc.var_arg_type is not None:
2248 var_arg_idx = len(desc.arg_types)
2249 for i in range(len(desc.arg_types), len(args)):
2250 arg = args[i]
2251 arg = self.coerce(arg, desc.var_arg_type, line)
2252 coerced.append(arg)
2253 # Add extra integer constant if any
2254 for item in desc.extra_int_constants:
2255 val, typ = item
2256 extra_int_constant = Integer(val, typ, line)
2257 coerced.append(extra_int_constant)
2258 error_kind = desc.error_kind
2259 if error_kind == ERR_NEG_INT:
2260 # Handled with an explicit comparison
2261 error_kind = ERR_NEVER
2262 target = self.add(
2263 CallC(
2264 desc.c_function_name,
2265 coerced,
2266 desc.return_type,
2267 desc.steals,
2268 desc.is_borrowed,
2269 error_kind,
2270 line,
2271 var_arg_idx,
2272 is_pure=desc.is_pure,
2273 returns_null=desc.returns_null,
2274 dependencies=desc.dependencies,
2275 )
2276 )
2277 if desc.is_borrowed:
2278 # If the result is borrowed, force the arguments to be
2279 # kept alive afterwards, as otherwise the result might be
2280 # immediately freed, at the risk of a dangling pointer.
2281 for arg in coerced:
2282 if not isinstance(arg, (Integer, LoadLiteral)):
2283 self.keep_alives.append(arg)
2284 if desc.error_kind == ERR_NEG_INT:
2285 comp = ComparisonOp(target, Integer(0, desc.return_type, line), ComparisonOp.SGE, line)
2286 comp.error_kind = ERR_FALSE
2287 self.add(comp)
2288
2289 if desc.truncated_type is None:
2290 result = target
2291 else:
2292 truncate = self.add(Truncate(target, desc.truncated_type))
2293 result = truncate
2294 if result_type and not is_runtime_subtype(result.type, result_type):
2295 if is_none_rprimitive(result_type):
2296 # Special case None return. The actual result may actually be a bool
2297 # and so we can't just coerce it.
2298 result = self.none()
2299 else:
2300 result = self.coerce(target, result_type, line, can_borrow=desc.is_borrowed)
2301 return result
2302
2303 def matching_call_c(
2304 self,
2305 candidates: list[CFunctionDescription],
2306 args: list[Value],
2307 line: int,
2308 result_type: RType | None = None,
2309 can_borrow: bool = False,
2310 ) -> Value | None:
2311 matching: CFunctionDescription | None = None
2312 for desc in candidates:
2313 if len(desc.arg_types) != len(args):
2314 continue
2315 if all(
2316 is_subtype(actual.type, formal) for actual, formal in zip(args, desc.arg_types)
2317 ) and (not desc.is_borrowed or can_borrow):
2318 if matching:
2319 assert matching.priority != desc.priority, "Ambiguous:\n1) {}\n2) {}".format(
2320 matching, desc
2321 )
2322 if desc.priority > matching.priority:
2323 matching = desc
2324 else:
2325 matching = desc
2326 if matching:
2327 target = self.call_c(matching, args, line, result_type)
2328 return target
2329 return None
2330
2331 def primitive_op(
2332 self,
2333 desc: PrimitiveDescription,
2334 args: list[Value],
2335 line: int,
2336 result_type: RType | None = None,
2337 ) -> Value:
2338 """Add a primitive op."""
2339 # Does this primitive map into calling a Python C API
2340 # or an internal mypyc C API function?
2341 if desc.c_function_name:
2342 # TODO: Generate PrimitiveOps here and transform them into CallC
2343 # ops only later in the lowering pass
2344 c_desc = CFunctionDescription(
2345 desc.name,
2346 desc.arg_types,
2347 desc.return_type,
2348 desc.var_arg_type,
2349 desc.truncated_type,
2350 desc.c_function_name,
2351 desc.error_kind,
2352 desc.steals,
2353 desc.is_borrowed,
2354 desc.ordering,
2355 desc.extra_int_constants,
2356 desc.priority,
2357 is_pure=desc.is_pure,
2358 returns_null=False,
2359 dependencies=desc.dependencies,
2360 )
2361 return self.call_c(c_desc, args, line, result_type=result_type)
2362
2363 # This primitive gets transformed in a lowering pass to
2364 # lower-level IR ops using a custom transform function.
2365
2366 coerced = []
2367 # Coerce fixed number arguments
2368 for i in range(min(len(args), len(desc.arg_types))):
2369 formal_type = desc.arg_types[i]
2370 arg = args[i]
2371 assert formal_type is not None # TODO
2372 arg = self.coerce(arg, formal_type, line)
2373 coerced.append(arg)
2374 assert desc.ordering is None
2375 assert desc.var_arg_type is None
2376 assert not desc.extra_int_constants
2377 target = self.add(PrimitiveOp(coerced, desc, line=line))
2378 if desc.is_borrowed:
2379 # If the result is borrowed, force the arguments to be
2380 # kept alive afterwards, as otherwise the result might be
2381 # immediately freed, at the risk of a dangling pointer.
2382 for arg in coerced:
2383 if not isinstance(arg, (Integer, LoadLiteral)):
2384 self.keep_alives.append(arg)
2385 if desc.error_kind == ERR_NEG_INT:
2386 comp = ComparisonOp(target, Integer(0, desc.return_type, line), ComparisonOp.SGE, line)
2387 comp.error_kind = ERR_FALSE
2388 self.add(comp)
2389
2390 assert desc.truncated_type is None
2391 result = target
2392 if result_type and not is_runtime_subtype(result.type, result_type):
2393 if is_none_rprimitive(result_type):
2394 # Special case None return. The actual result may actually be a bool
2395 # and so we can't just coerce it.
2396 result = self.none()
2397 else:
2398 result = self.coerce(result, result_type, line, can_borrow=desc.is_borrowed)
2399 return result
2400
2401 def matching_primitive_op(
2402 self,
2403 candidates: list[PrimitiveDescription],
2404 args: list[Value],
2405 line: int,
2406 result_type: RType | None = None,
2407 *,
2408 can_borrow: bool = False,
2409 strict: bool = True,
2410 ) -> Value | None:
2411 """Find primitive operation that is compatible with types of args.
2412
2413 Return None if none of them match.
2414 """
2415 matching: PrimitiveDescription | None = None
2416 for desc in candidates:
2417 if len(desc.arg_types) != len(args):
2418 continue
2419 if desc.experimental and not self.options.experimental_features:
2420 continue
2421 if all(
2422 # formal is not None and # TODO
2423 is_subtype(actual.type, formal, relaxed=not strict)
2424 for actual, formal in zip(args, desc.arg_types)
2425 ) and (not desc.is_borrowed or can_borrow):
2426 if matching:
2427 assert matching.priority != desc.priority, "Ambiguous:\n1) {}\n2) {}".format(
2428 matching, desc
2429 )
2430 if desc.priority > matching.priority:
2431 matching = desc
2432 else:
2433 matching = desc
2434 if matching:
2435 return self.primitive_op(matching, args, line=line, result_type=result_type)
2436 if strict and any(prim.is_ambiguous for prim in candidates):
2437 # Also try a non-exact match if any primitives have ambiguous types.
2438 return self.matching_primitive_op(
2439 candidates, args, line, result_type, can_borrow=can_borrow, strict=False
2440 )
2441
2442 return None
2443
2444 def int_op(self, type: RType, lhs: Value, rhs: Value, op: int, line: int = -1) -> Value:
2445 """Generate a native integer binary op.
2446
2447 Use native/C semantics, which sometimes differ from Python
2448 semantics.
2449
2450 Args:
2451 type: Either int64_rprimitive or int32_rprimitive
2452 op: IntOp.* constant (e.g. IntOp.ADD)
2453 """
2454 return self.add(IntOp(type, lhs, rhs, op, line))
2455
2456 def float_op(self, lhs: Value, rhs: Value, op: str, line: int) -> Value:
2457 """Generate a native float binary arithmetic operation.
2458
2459 This follows Python semantics (e.g. raise exception on division by zero).
2460 Add a FloatOp directly if you want low-level semantics.
2461
2462 Args:
2463 op: Binary operator (e.g. '+' or '*')
2464 """
2465 op_id = float_op_to_id[op]
2466 if op_id in (FloatOp.DIV, FloatOp.MOD):
2467 if not (isinstance(rhs, Float) and rhs.value != 0.0):
2468 c = self.compare_floats(rhs, Float(0.0), FloatComparisonOp.EQ, line)
2469 err, ok = BasicBlock(), BasicBlock()
2470 self.add(Branch(c, err, ok, Branch.BOOL, rare=True))
2471 self.activate_block(err)
2472 if op_id == FloatOp.DIV:
2473 msg = "float division by zero"
2474 else:
2475 msg = "float modulo"
2476 self.add(RaiseStandardError(RaiseStandardError.ZERO_DIVISION_ERROR, msg, line))
2477 self.add(Unreachable())
2478 self.activate_block(ok)
2479 if op_id == FloatOp.MOD:
2480 # Adjust the result to match Python semantics (FloatOp follows C semantics).
2481 return self.float_mod(lhs, rhs, line)
2482 else:
2483 return self.add(FloatOp(lhs, rhs, op_id, line))
2484
2485 def float_mod(self, lhs: Value, rhs: Value, line: int) -> Value:
2486 """Perform x % y on floats using Python semantics."""
2487 mod = self.add(FloatOp(lhs, rhs, FloatOp.MOD, line))
2488 res = Register(float_rprimitive)
2489 self.add(Assign(res, mod))
2490 tricky, adjust, copysign, done = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock()
2491 is_zero = self.add(FloatComparisonOp(res, Float(0.0), FloatComparisonOp.EQ, line))
2492 self.add(Branch(is_zero, copysign, tricky, Branch.BOOL))
2493 self.activate_block(tricky)
2494 same_signs = self.is_same_float_signs(lhs, rhs, line)
2495 self.add(Branch(same_signs, done, adjust, Branch.BOOL))
2496 self.activate_block(adjust)
2497 adj = self.float_op(res, rhs, "+", line)
2498 self.add(Assign(res, adj))
2499 self.add(Goto(done))
2500 self.activate_block(copysign)
2501 # If the remainder is zero, CPython ensures the result has the
2502 # same sign as the denominator.
2503 adj = self.primitive_op(copysign_op, [Float(0.0), rhs], line)
2504 self.add(Assign(res, adj))
2505 self.add(Goto(done))
2506 self.activate_block(done)
2507 return res
2508
2509 def compare_floats(self, lhs: Value, rhs: Value, op: int, line: int) -> Value:
2510 return self.add(FloatComparisonOp(lhs, rhs, op, line))
2511
2512 def int_add(self, lhs: Value, rhs: Value | int) -> Value:
2513 """Helper to add two native integers.
2514
2515 The result has the type of lhs.
2516 """
2517 if isinstance(rhs, int):
2518 rhs = Integer(rhs, lhs.type)
2519 return self.int_op(lhs.type, lhs, rhs, IntOp.ADD, lhs.line)
2520
2521 def int_sub(self, lhs: Value, rhs: Value | int) -> Value:
2522 """Helper to subtract a native integer from another one.
2523
2524 The result has the type of lhs.
2525 """
2526 if isinstance(rhs, int):
2527 rhs = Integer(rhs, lhs.type)
2528 return self.int_op(lhs.type, lhs, rhs, IntOp.SUB, lhs.line)
2529
2530 def int_mul(self, lhs: Value, rhs: Value | int) -> Value:
2531 """Helper to multiply two native integers.
2532
2533 The result has the type of lhs.
2534 """
2535 if isinstance(rhs, int):
2536 rhs = Integer(rhs, lhs.type)
2537 return self.int_op(lhs.type, lhs, rhs, IntOp.MUL, lhs.line)
2538
2539 def fixed_width_int_op(
2540 self, type: RPrimitive, lhs: Value, rhs: Value, op: int, line: int
2541 ) -> Value:
2542 """Generate a binary op using Python fixed-width integer semantics.
2543
2544 These may differ in overflow/rounding behavior from native/C ops.
2545
2546 Args:
2547 type: Either int64_rprimitive or int32_rprimitive
2548 op: IntOp.* constant (e.g. IntOp.ADD)
2549 """
2550 lhs = self.coerce(lhs, type, line)
2551 rhs = self.coerce(rhs, type, line)
2552 if op == IntOp.DIV:
2553 if isinstance(rhs, Integer) and rhs.value not in (-1, 0):
2554 if not type.is_signed:
2555 return self.int_op(type, lhs, rhs, IntOp.DIV, line)
2556 else:
2557 # Inline simple division by a constant, so that C
2558 # compilers can optimize more
2559 return self.inline_fixed_width_divide(type, lhs, rhs, line)
2560 if is_int64_rprimitive(type):
2561 prim = int64_divide_op
2562 elif is_int32_rprimitive(type):
2563 prim = int32_divide_op
2564 elif is_int16_rprimitive(type):
2565 prim = int16_divide_op
2566 elif is_uint8_rprimitive(type):
2567 self.check_for_zero_division(rhs, type, line)
2568 return self.int_op(type, lhs, rhs, op, line)
2569 else:
2570 assert False, type
2571 return self.call_c(prim, [lhs, rhs], line)
2572 if op == IntOp.MOD:
2573 if isinstance(rhs, Integer) and rhs.value not in (-1, 0):
2574 if not type.is_signed:
2575 return self.int_op(type, lhs, rhs, IntOp.MOD, line)
2576 else:
2577 # Inline simple % by a constant, so that C
2578 # compilers can optimize more
2579 return self.inline_fixed_width_mod(type, lhs, rhs, line)
2580 if is_int64_rprimitive(type):
2581 prim = int64_mod_op
2582 elif is_int32_rprimitive(type):
2583 prim = int32_mod_op
2584 elif is_int16_rprimitive(type):
2585 prim = int16_mod_op
2586 elif is_uint8_rprimitive(type):
2587 self.check_for_zero_division(rhs, type, line)
2588 return self.int_op(type, lhs, rhs, op, line)
2589 else:
2590 assert False, type
2591 return self.call_c(prim, [lhs, rhs], line)
2592 return self.int_op(type, lhs, rhs, op, line)
2593
2594 def check_for_zero_division(self, rhs: Value, type: RType, line: int) -> None:
2595 err, ok = BasicBlock(), BasicBlock()
2596 is_zero = self.binary_op(rhs, Integer(0, type), "==", line)
2597 self.add(Branch(is_zero, err, ok, Branch.BOOL))
2598 self.activate_block(err)
2599 self.add(
2600 RaiseStandardError(
2601 RaiseStandardError.ZERO_DIVISION_ERROR, "integer division or modulo by zero", line
2602 )
2603 )
2604 self.add(Unreachable())
2605 self.activate_block(ok)
2606
2607 def inline_fixed_width_divide(self, type: RType, lhs: Value, rhs: Value, line: int) -> Value:
2608 # Perform floor division (native division truncates)
2609 res = Register(type)
2610 div = self.int_op(type, lhs, rhs, IntOp.DIV, line)
2611 self.add(Assign(res, div))
2612 same_signs = self.is_same_native_int_signs(type, lhs, rhs, line)
2613 tricky, adjust, done = BasicBlock(), BasicBlock(), BasicBlock()
2614 self.add(Branch(same_signs, done, tricky, Branch.BOOL))
2615 self.activate_block(tricky)
2616 mul = self.int_op(type, res, rhs, IntOp.MUL, line)
2617 mul_eq = self.add(ComparisonOp(mul, lhs, ComparisonOp.EQ, line))
2618 self.add(Branch(mul_eq, done, adjust, Branch.BOOL))
2619 self.activate_block(adjust)
2620 adj = self.int_op(type, res, Integer(1, type), IntOp.SUB, line)
2621 self.add(Assign(res, adj))
2622 self.add(Goto(done))
2623 self.activate_block(done)
2624 return res
2625
2626 def inline_fixed_width_mod(self, type: RType, lhs: Value, rhs: Value, line: int) -> Value:
2627 # Perform floor modulus
2628 res = Register(type)
2629 mod = self.int_op(type, lhs, rhs, IntOp.MOD, line)
2630 self.add(Assign(res, mod))
2631 same_signs = self.is_same_native_int_signs(type, lhs, rhs, line)
2632 tricky, adjust, done = BasicBlock(), BasicBlock(), BasicBlock()
2633 self.add(Branch(same_signs, done, tricky, Branch.BOOL))
2634 self.activate_block(tricky)
2635 is_zero = self.add(ComparisonOp(res, Integer(0, type), ComparisonOp.EQ, line))
2636 self.add(Branch(is_zero, done, adjust, Branch.BOOL))
2637 self.activate_block(adjust)
2638 adj = self.int_op(type, res, rhs, IntOp.ADD, line)
2639 self.add(Assign(res, adj))
2640 self.add(Goto(done))
2641 self.activate_block(done)
2642 return res
2643
2644 def is_same_native_int_signs(self, type: RType, a: Value, b: Value, line: int) -> Value:
2645 neg1 = self.add(ComparisonOp(a, Integer(0, type), ComparisonOp.SLT, line))
2646 neg2 = self.add(ComparisonOp(b, Integer(0, type), ComparisonOp.SLT, line))
2647 return self.add(ComparisonOp(neg1, neg2, ComparisonOp.EQ, line))
2648
2649 def is_same_float_signs(self, a: Value, b: Value, line: int) -> Value:
2650 neg1 = self.add(FloatComparisonOp(a, Float(0.0), FloatComparisonOp.LT, line))
2651 neg2 = self.add(FloatComparisonOp(b, Float(0.0), FloatComparisonOp.LT, line))
2652 return self.add(ComparisonOp(neg1, neg2, ComparisonOp.EQ, line))
2653
2654 def comparison_op(self, lhs: Value, rhs: Value, op: int, line: int) -> Value:
2655 return self.add(ComparisonOp(lhs, rhs, op, line))
2656
2657 def builtin_len(self, val: Value, line: int, use_pyssize_t: bool = False) -> Value:
2658 """Generate len(val).
2659
2660 Return short_int_rprimitive by default.
2661 Return c_pyssize_t if use_pyssize_t is true (unshifted).
2662 """
2663 typ = val.type
2664 size_value = None
2665 if is_list_rprimitive(typ) or is_tuple_rprimitive(typ) or is_bytes_rprimitive(typ):
2666 size_value = self.primitive_op(var_object_size, [val], line)
2667 elif is_set_rprimitive(typ) or is_frozenset_rprimitive(typ):
2668 elem_address = self.add(GetElementPtr(val, PySetObject, "used"))
2669 size_value = self.load_mem(elem_address, c_pyssize_t_rprimitive)
2670 self.add(KeepAlive([val], line))
2671 elif is_dict_rprimitive(typ):
2672 size_value = self.call_c(dict_ssize_t_size_op, [val], line)
2673 elif is_str_rprimitive(typ):
2674 size_value = self.call_c(str_ssize_t_size_op, [val], line)
2675
2676 if size_value is not None:
2677 if use_pyssize_t:
2678 return size_value
2679 offset = Integer(1, c_pyssize_t_rprimitive, line)
2680 return self.int_op(short_int_rprimitive, size_value, offset, IntOp.LEFT_SHIFT, line)
2681
2682 if isinstance(typ, RInstance):
2683 # TODO: Support use_pyssize_t
2684 assert not use_pyssize_t
2685 length = self.gen_method_call(val, "__len__", [], int_rprimitive, line)
2686 length = self.coerce(length, int_rprimitive, line)
2687 ok, fail = BasicBlock(), BasicBlock()
2688 cond = self.binary_op(length, Integer(0), ">=", line)
2689 self.add_bool_branch(cond, ok, fail)
2690 self.activate_block(fail)
2691 self.add(
2692 RaiseStandardError(
2693 RaiseStandardError.VALUE_ERROR, "__len__() should return >= 0", line
2694 )
2695 )
2696 self.add(Unreachable())
2697 self.activate_block(ok)
2698 return length
2699
2700 elif isinstance(typ, RVec):
2701 len_value = vec_len_native(self, val)
2702 if use_pyssize_t:
2703 return len_value
2704 count = Integer(1, c_pyssize_t_rprimitive, line)
2705 return self.int_op(short_int_rprimitive, len_value, count, IntOp.LEFT_SHIFT, line)
2706
2707 op = self.matching_primitive_op(function_ops["builtins.len"], [val], line)
2708 if op is not None:
2709 return op
2710
2711 # Fallback generic case
2712 if use_pyssize_t:
2713 return self.call_c(generic_ssize_t_len_op, [val], line)
2714 else:
2715 return self.call_c(generic_len_op, [val], line)
2716
2717 def new_tuple(self, items: list[Value], line: int) -> Value:
2718 if items:
2719 size: Value = Integer(len(items), c_pyssize_t_rprimitive)
2720 return self.call_c(new_tuple_op, [size] + items, line)
2721 else:
2722 return self.call_c(load_empty_tuple_constant_op, [], line)
2723
2724 def new_tuple_with_length(self, length: Value, line: int) -> Value:
2725 """This function returns an uninitialized tuple.
2726
2727 If the length is non-zero, the caller must initialize the tuple, before
2728 it can be made visible to user code -- otherwise the tuple object is broken.
2729 You might need further initialization with `new_tuple_set_item_op` op.
2730
2731 Args:
2732 length: desired length of the new tuple. The rtype should be
2733 c_pyssize_t_rprimitive
2734 line: line number
2735 """
2736 return self.call_c(new_tuple_with_length_op, [length], line)
2737
2738 def int_to_float(self, n: Value, line: int) -> Value:
2739 return self.primitive_op(int_to_float_op, [n], line)
2740
2741 def set_immortal_if_free_threaded(self, v: Value, line: int) -> None:
2742 """Make an object immortal on free-threaded builds (to avoid contention)."""
2743 if IS_FREE_THREADED and sys.version_info >= (3, 14):
2744 self.primitive_op(set_immortal_op, [v], line)
2745
2746 # Internal helpers
2747
2748 def decompose_union_helper(
2749 self,
2750 obj: Value,
2751 rtype: RUnion,
2752 result_type: RType,
2753 process_item: Callable[[Value], Value],
2754 line: int,
2755 ) -> Value:
2756 """Generate isinstance() + specialized operations for union items.
2757
2758 Say, for Union[A, B] generate ops resembling this (pseudocode):
2759
2760 if isinstance(obj, A):
2761 result = <result of process_item(cast(A, obj)>
2762 else:
2763 result = <result of process_item(cast(B, obj)>
2764
2765 Args:
2766 obj: value with a union type
2767 rtype: the union type
2768 result_type: result of the operation
2769 process_item: callback to generate op for a single union item (arg is coerced
2770 to union item type)
2771 line: line number
2772 """
2773 # TODO: Optimize cases where a single operation can handle multiple union items
2774 # (say a method is implemented in a common base class)
2775 fast_items = []
2776 rest_items = []
2777 for item in rtype.items:
2778 if isinstance(item, RInstance):
2779 fast_items.append(item)
2780 else:
2781 # For everything but RInstance we fall back to C API
2782 rest_items.append(item)
2783 exit_block = BasicBlock()
2784 result = Register(result_type, line=line)
2785 for i, item in enumerate(fast_items):
2786 more_types = i < len(fast_items) - 1 or rest_items
2787 if more_types:
2788 # We are not at the final item so we need one more branch
2789 op = self.isinstance_native(obj, item.class_ir, line)
2790 true_block, false_block = BasicBlock(), BasicBlock()
2791 self.add_bool_branch(op, true_block, false_block)
2792 self.activate_block(true_block)
2793 coerced = self.coerce(obj, item, line)
2794 temp = process_item(coerced)
2795 temp2 = self.coerce(temp, result_type, line)
2796 self.add(Assign(result, temp2, line))
2797 self.goto(exit_block)
2798 if more_types:
2799 self.activate_block(false_block)
2800 if rest_items:
2801 # For everything else we use generic operation. Use force=True to drop the
2802 # union type.
2803 coerced = self.coerce(obj, object_rprimitive, line, force=True)
2804 temp = process_item(coerced)
2805 temp2 = self.coerce(temp, result_type, line)
2806 self.add(Assign(result, temp2, line))
2807 self.goto(exit_block)
2808 self.activate_block(exit_block)
2809 return result
2810
2811 def translate_special_method_call(
2812 self,
2813 base_reg: Value,
2814 name: str,
2815 args: list[Value],
2816 result_type: RType | None,
2817 line: int,
2818 can_borrow: bool = False,
2819 ) -> Value | None:
2820 """Translate a method call which is handled nongenerically.
2821
2822 These are special in the sense that we have code generated specifically for them.
2823 They tend to be method calls which have equivalents in C that are more direct
2824 than calling with the PyObject api.
2825
2826 Return None if no translation found; otherwise return the target register.
2827 """
2828 low_level_op = self._translate_special_low_level_method_call(
2829 base_reg, name, args, result_type, line, can_borrow
2830 )
2831 if low_level_op is not None:
2832 return low_level_op
2833 primitive_ops_candidates = method_call_ops.get(name, [])
2834 primitive_op = self.matching_primitive_op(
2835 primitive_ops_candidates, [base_reg] + args, line, result_type, can_borrow=can_borrow
2836 )
2837 return primitive_op
2838
2839 def _translate_special_low_level_method_call(
2840 self,
2841 base_reg: Value,
2842 name: str,
2843 args: list[Value],
2844 result_type: RType | None,
2845 line: int,
2846 can_borrow: bool = False,
2847 ) -> Value | None:
2848 if name == "__getitem__" and len(args) == 1:
2849 arg = args[0]
2850 if isinstance(base_reg.type, RVec) and (
2851 is_int64_rprimitive(arg.type) or is_tagged(arg.type)
2852 ):
2853 if is_tagged(arg.type):
2854 arg = self.coerce(arg, int64_rprimitive, line)
2855 return vec_get_item(self, base_reg, arg, line)
2856 return None
2857
2858 def translate_eq_cmp(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value | None:
2859 """Add an equality comparison operation.
2860
2861 Note that this doesn't cover all possible types.
2862
2863 Args:
2864 expr_op: either '==' or '!='
2865 """
2866 ltype = lreg.type
2867 rtype = rreg.type
2868
2869 if is_str_rprimitive(ltype) and is_str_rprimitive(rtype):
2870 return self.compare_strings(lreg, rreg, expr_op, line)
2871 if is_bytes_rprimitive(ltype) and is_bytes_rprimitive(rtype):
2872 return self.compare_bytes(lreg, rreg, expr_op, line)
2873
2874 lopt = optional_value_type(ltype)
2875 ropt = optional_value_type(rtype)
2876
2877 # Can we do a quick comparison of two optional types (special case None values)?
2878 fast_opt_eq = False
2879 if lopt is not None:
2880 if ropt is not None and is_same_type(lopt, ropt) and self._never_equal_to_none(lopt):
2881 fast_opt_eq = True
2882 if is_same_type(lopt, rtype) and self._never_equal_to_none(lopt):
2883 fast_opt_eq = True
2884 elif ropt is not None:
2885 if is_same_type(ropt, ltype) and self._never_equal_to_none(ropt):
2886 fast_opt_eq = True
2887 if fast_opt_eq:
2888 return self._translate_fast_optional_eq_cmp(lreg, rreg, expr_op, line)
2889
2890 if not (isinstance(ltype, RInstance) and ltype == rtype):
2891 return None
2892
2893 class_ir = ltype.class_ir
2894 # Check whether any subclasses of the operand redefines __eq__
2895 # or it might be redefined in a Python parent class or by
2896 # dataclasses
2897 cmp_varies_at_runtime = (
2898 not class_ir.is_method_final("__eq__")
2899 or not class_ir.is_method_final("__ne__")
2900 or class_ir.inherits_python
2901 or class_ir.is_augmented
2902 )
2903
2904 if cmp_varies_at_runtime:
2905 # We might need to call left.__eq__(right) or right.__eq__(left)
2906 # depending on which is the more specific type.
2907 return None
2908
2909 if not class_ir.has_method("__eq__"):
2910 # There's no __eq__ defined, so just use object identity.
2911 identity_ref_op = "is" if expr_op == "==" else "is not"
2912 return self.translate_is_op(lreg, rreg, identity_ref_op, line)
2913
2914 return self.gen_method_call(lreg, op_methods[expr_op], [rreg], ltype, line)
2915
2916 def _never_equal_to_none(self, typ: RType) -> bool:
2917 """Are the values of type never equal to None?"""
2918 # TODO: Support RInstance with no custom __eq__/__ne__ and other primitive types.
2919 return is_str_rprimitive(typ) or is_bytes_rprimitive(typ)
2920
2921 def _translate_fast_optional_eq_cmp(
2922 self, lreg: Value, rreg: Value, expr_op: str, line: int
2923 ) -> Value:
2924 """Generate eq/ne fast path between 'X | None' and ('X | None' or X).
2925
2926 Assume 'X' never compares equal to None.
2927 """
2928 if not isinstance(lreg.type, RUnion):
2929 lreg, rreg = rreg, lreg
2930 value_typ = optional_value_type(lreg.type)
2931 assert value_typ
2932 res = Register(bool_rprimitive, line=line)
2933
2934 # Fast path: left value is None?
2935 cmp = self.add(ComparisonOp(lreg, self.none_object(), ComparisonOp.EQ, line))
2936 l_none = BasicBlock()
2937 l_not_none = BasicBlock()
2938 out = BasicBlock()
2939 self.add(Branch(cmp, l_none, l_not_none, Branch.BOOL))
2940 self.activate_block(l_none)
2941 if not isinstance(rreg.type, RUnion):
2942 val = self.false() if expr_op == "==" else self.true()
2943 self.add(Assign(res, val, line))
2944 else:
2945 op = ComparisonOp.EQ if expr_op == "==" else ComparisonOp.NEQ
2946 cmp = self.add(ComparisonOp(rreg, self.none_object(), op, line))
2947 self.add(Assign(res, cmp, line))
2948 self.goto(out)
2949
2950 self.activate_block(l_not_none)
2951 if not isinstance(rreg.type, RUnion):
2952 # Both operands are known to be not None, perform specialized comparison
2953 eq = self.translate_eq_cmp(
2954 self.unbox_or_cast(lreg, value_typ, line, can_borrow=True, unchecked=True),
2955 rreg,
2956 expr_op,
2957 line,
2958 )
2959 assert eq is not None
2960 self.add(Assign(res, eq, line))
2961 else:
2962 r_none = BasicBlock()
2963 r_not_none = BasicBlock()
2964 # Fast path: right value is None?
2965 cmp = self.add(ComparisonOp(rreg, self.none_object(), ComparisonOp.EQ, line))
2966 self.add(Branch(cmp, r_none, r_not_none, Branch.BOOL))
2967 self.activate_block(r_none)
2968 # None vs not-None
2969 val = self.false() if expr_op == "==" else self.true()
2970 self.add(Assign(res, val, line))
2971 self.goto(out)
2972 self.activate_block(r_not_none)
2973 # Both operands are known to be not None, perform specialized comparison
2974 eq = self.translate_eq_cmp(
2975 self.unbox_or_cast(lreg, value_typ, line, can_borrow=True, unchecked=True),
2976 self.unbox_or_cast(rreg, value_typ, line, can_borrow=True, unchecked=True),
2977 expr_op,
2978 line,
2979 )
2980 assert eq is not None
2981 self.add(Assign(res, eq, line))
2982 self.goto(out)
2983 self.activate_block(out)
2984 return res
2985
2986 def translate_is_op(self, lreg: Value, rreg: Value, expr_op: str, line: int) -> Value:
2987 """Create equality comparison operation between object identities
2988
2989 Args:
2990 expr_op: either 'is' or 'is not'
2991 """
2992 op = ComparisonOp.EQ if expr_op == "is" else ComparisonOp.NEQ
2993 lhs = self.coerce(lreg, object_rprimitive, line)
2994 rhs = self.coerce(rreg, object_rprimitive, line)
2995 return self.add(ComparisonOp(lhs, rhs, op, line))
2996
2997 def _create_dict(self, keys: list[Value], values: list[Value], line: int) -> Value:
2998 """Create a dictionary(possibly empty) using keys and values"""
2999 # keys and values should have the same number of items
3000 size = len(keys)
3001 if size > 0:
3002 size_value: Value = Integer(size, c_pyssize_t_rprimitive)
3003 # merge keys and values
3004 items = [i for t in list(zip(keys, values)) for i in t]
3005 return self.call_c(dict_build_op, [size_value] + items, line)
3006 else:
3007 return self.call_c(dict_new_op, [], line)
3008
3009 # Loop helpers
3010
3011 def begin_for(self, start: Value, end: Value, step: Value, *, signed: bool) -> ForBuilder:
3012 """Generate for loop over a pointer or native int range.
3013
3014 Roughly corresponds to "for i in range(start, end, step): ....". Only
3015 positive values for step are supported.
3016
3017 The loop index register is generated automatically and is available
3018 via the return value. Do not modify it!
3019
3020 Example usage that clears a memory area:
3021
3022 for_loop = builder.begin_for(start_ptr, end_ptr, int32_rprimitive.size)
3023
3024 # For loop body
3025 builder.set_mem(for_loop.index, int32_rprimitive, Integer(0, int32_rprimitive))
3026
3027 for_loop.finish()
3028 """
3029 b = ForBuilder(self, start, end, step, signed=signed)
3030 b.begin()
3031 return b
3032
3033 def error(self, msg: str, line: int) -> None:
3034 assert self.errors is not None, "cannot generate errors in this compiler phase"
3035 self.errors.error(msg, self.module_path, line)
3036
3037
3038 def num_positional_args(arg_values: list[Value], arg_kinds: list[ArgKind] | None) -> int:
3039 if arg_kinds is None:
3040 return len(arg_values)
3041 num_pos = 0
3042 for kind in arg_kinds:
3043 if kind == ARG_POS:
3044 num_pos += 1
3045 return num_pos
3046
3047
3048 class ForBuilder:
3049 """Builder for simple for loops."""
3050
3051 def __init__(
3052 self, builder: LowLevelIRBuilder, start: Value, end: Value, step: Value, *, signed: bool
3053 ) -> None:
3054 self.builder = builder
3055 self.start = start
3056 self.end = end
3057 self.step = step
3058 self.signed = signed
3059 self.index = Register(start.type)
3060 self.top = BasicBlock()
3061 self.body = BasicBlock()
3062 self.loop_exit = BasicBlock()
3063
3064 def begin(self) -> None:
3065 builder = self.builder
3066 builder.assign(self.index, self.start)
3067 builder.goto_and_activate(self.top)
3068 op = ComparisonOp.SLT if self.signed else ComparisonOp.ULT
3069 comp = ComparisonOp(self.index, self.end, op, line=-1)
3070 builder.add(comp)
3071 builder.add(Branch(comp, self.body, self.loop_exit, Branch.BOOL))
3072 builder.goto_and_activate(self.body)
3073
3074 def finish(self) -> None:
3075 builder = self.builder
3076 builder.assign(self.index, builder.int_add(self.index, self.step))
3077 builder.goto(self.top)
3078 builder.activate_block(self.loop_exit)