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