Debian Codegraph @

mypyc/ir/ops.py

raw
1 """Low-level opcodes for compiler intermediate representation (IR).
2
3 Opcodes operate on abstract values (Value) in a register machine. Each
4 value has a type (RType). A value can hold various things, such as:
5
6 - local variables or temporaries (Register)
7 - intermediate values of expressions (RegisterOp subclasses)
8 - condition flags (true/false)
9 - literals (integer literals, True, False, etc.)
10
11 NOTE: As a convention, we don't create subclasses of concrete Value/Op
12 subclasses (e.g. you shouldn't define a subclass of Integer, which
13 is a concrete class).
14
15 If you want to introduce a variant of an existing class, you'd
16 typically add an attribute (e.g. a flag) to an existing concrete
17 class to enable the new behavior. Sometimes adding a new abstract
18 base class is also an option, or just creating a new subclass
19 without any inheritance relationship (some duplication of code
20 is preferred over introducing complex implementation inheritance).
21
22 This makes it possible to use isinstance(x, <concrete Value
23 subclass>) checks without worrying about potential subclasses.
24 """
25
26 from __future__ import annotations
27
28 from abc import abstractmethod
29 from collections.abc import Sequence
30 from typing import TYPE_CHECKING, Final, Generic, NamedTuple, TypeVar, final
31
32 from mypy_extensions import trait
33
34 from mypyc.common import KEEP_ALIVE_SHORT_LIVED, PROPSET_PREFIX
35 from mypyc.ir.deps import Dependency
36 from mypyc.ir.rtypes import (
37 RArray,
38 RInstance,
39 RStruct,
40 RTuple,
41 RType,
42 RTypeVar,
43 RUnion,
44 RVec,
45 RVoid,
46 bit_rprimitive,
47 bool_rprimitive,
48 cstring_rprimitive,
49 float_rprimitive,
50 int_rprimitive,
51 is_bool_or_bit_rprimitive,
52 is_fixed_width_rtype,
53 is_int_rprimitive,
54 is_none_rprimitive,
55 is_pointer_rprimitive,
56 is_short_int_rprimitive,
57 object_rprimitive,
58 pointer_rprimitive,
59 short_int_rprimitive,
60 void_rtype,
61 )
62
63 if TYPE_CHECKING:
64 from mypyc.codegen.literals import LiteralValue
65 from mypyc.ir.class_ir import ClassIR
66 from mypyc.ir.func_ir import FuncDecl, FuncIR
67
68 T = TypeVar("T")
69
70
71 @final
72 class BasicBlock:
73 """IR basic block.
74
75 Contains a sequence of Ops and ends with a ControlOp (Goto,
76 Branch, Return or Unreachable). Only the last op can be a
77 ControlOp.
78
79 All generated Ops live in basic blocks. Basic blocks determine the
80 order of evaluation and control flow within a function. A basic
81 block is always associated with a single function/method (FuncIR).
82
83 When building the IR, ops that raise exceptions can be included in
84 the middle of a basic block, but the exceptions aren't checked.
85 Afterwards we perform a transform that inserts explicit checks for
86 all error conditions and splits basic blocks accordingly to preserve
87 the invariant that a jump, branch or return can only ever appear
88 as the final op in a block. Manually inserting error checking ops
89 would be boring and error-prone.
90
91 BasicBlocks have an error_handler attribute that determines where
92 to jump if an error occurs. If none is specified, an error will
93 propagate up out of the function. This is compiled away by the
94 `exceptions` module.
95
96 Block labels are used for pretty printing and emitting C code, and
97 get filled in by those passes.
98
99 Ops that may terminate the program aren't treated as exits.
100 """
101
102 def __init__(self, label: int = -1) -> None:
103 self.label = label
104 self.ops: list[Op] = []
105 self.error_handler: BasicBlock | None = None
106 self.referenced = False
107
108 @property
109 def terminated(self) -> bool:
110 """Does the block end with a jump, branch or return?
111
112 This should always be true after the basic block has been fully built, but
113 this is false during construction.
114 """
115 return bool(self.ops) and isinstance(self.ops[-1], ControlOp)
116
117 @property
118 def terminator(self) -> ControlOp:
119 """The terminator operation of the block."""
120 assert bool(self.ops) and isinstance(self.ops[-1], ControlOp)
121 return self.ops[-1]
122
123
124 # Never generates an exception
125 ERR_NEVER: Final = 0
126 # Generates magic value (c_error_value) based on target RType on exception
127 ERR_MAGIC: Final = 1
128 # Generates false (bool) on exception
129 ERR_FALSE: Final = 2
130 # Always fails
131 ERR_ALWAYS: Final = 3
132 # Like ERR_MAGIC, but the magic return overlaps with a possible return value, and
133 # an extra PyErr_Occurred() check is also required
134 ERR_MAGIC_OVERLAPPING: Final = 4
135
136 # Hack: using this line number for an op will suppress it in tracebacks
137 NO_TRACEBACK_LINE_NO = -10000
138
139
140 class Value:
141 """Abstract base class for all IR values.
142
143 These include references to registers, literals, and all
144 operations (Ops), such as assignments, calls and branches.
145
146 Values are often used as inputs of Ops. Register can be used as an
147 assignment target.
148
149 A Value is part of the IR being compiled if it's included in a BasicBlock
150 that is reachable from a FuncIR (i.e., is part of a function).
151
152 See also: Op is a subclass of Value that is the base class of all
153 operations.
154 """
155
156 # Source line number (-1 for no/unknown line)
157 line = -1
158 # Type of the value or the result of the operation
159 type: RType = void_rtype
160 is_borrowed = False
161
162 @property
163 def is_void(self) -> bool:
164 return isinstance(self.type, RVoid)
165
166
167 @final
168 class Register(Value):
169 """A Register holds a value of a specific type, and it can be read and mutated.
170
171 A Register is always local to a function. Each local variable maps
172 to a Register, and they are also used for some (but not all)
173 temporary values.
174
175 Note that the term 'register' is overloaded and is sometimes used
176 to refer to arbitrary Values (for example, in RegisterOp).
177 """
178
179 def __init__(self, type: RType, name: str = "", is_arg: bool = False, line: int = -1) -> None:
180 self.type = type
181 self.name = name
182 self.is_arg = is_arg
183 self.is_borrowed = is_arg
184 self.line = line
185
186 @property
187 def is_void(self) -> bool:
188 return False
189
190 def __repr__(self) -> str:
191 return f"<Register {self.name!r} at {hex(id(self))}>"
192
193
194 @final
195 class Integer(Value):
196 """Short integer literal.
197
198 Integer literals are treated as constant values and are generally
199 not included in data flow analyses and such, unlike Register and
200 Op subclasses.
201
202 Integer can represent multiple types:
203
204 * Short tagged integers (short_int_primitive type; the tag bit is clear)
205 * Ordinary fixed-width integers (e.g., int32_rprimitive)
206 * Values of other unboxed primitive types that are represented as integers
207 (none_rprimitive, bool_rprimitive)
208 * Null pointers (value 0) of various types, including object_rprimitive
209 """
210
211 def __init__(self, value: int, rtype: RType = short_int_rprimitive, line: int = -1) -> None:
212 if is_short_int_rprimitive(rtype) or is_int_rprimitive(rtype):
213 self.value = value * 2
214 else:
215 self.value = value
216 self.type = rtype
217 self.line = line
218
219 def numeric_value(self) -> int:
220 if is_short_int_rprimitive(self.type) or is_int_rprimitive(self.type):
221 return self.value // 2
222 return self.value
223
224
225 @final
226 class Float(Value):
227 """Float literal.
228
229 Floating point literals are treated as constant values and are generally
230 not included in data flow analyses and such, unlike Register and
231 Op subclasses.
232 """
233
234 def __init__(self, value: float, line: int = -1) -> None:
235 self.value = value
236 self.type = float_rprimitive
237 self.line = line
238
239
240 @final
241 class CString(Value):
242 """C string literal (zero-terminated).
243
244 You can also include zero values in the value, but then you'll need to track
245 the length of the string separately.
246 """
247
248 def __init__(self, value: bytes, line: int = -1) -> None:
249 self.value = value
250 self.type = cstring_rprimitive
251 self.line = line
252
253
254 @final
255 class Undef(Value):
256 """An undefined value.
257
258 Use Undef() as the initial value followed by one or more SetElement
259 ops to initialize a struct. Pseudocode example:
260
261 r0 = set_element undef MyStruct, "field1", f1
262 r1 = set_element r0, "field2", f2
263 # r1 now has new struct value with two fields set
264
265 Warning: Always initialize undefined values before using them,
266 as otherwise the values are garbage. You shouldn't expect that
267 undefined values are zeroed, in particular.
268 """
269
270 def __init__(self, rtype: RType) -> None:
271 self.type = rtype
272
273
274 class Op(Value):
275 """Abstract base class for all IR operations.
276
277 Each operation must be stored in a BasicBlock (in 'ops') to be
278 active in the IR. This is different from non-Op values, including
279 Register and Integer, where a reference from an active Op is
280 sufficient to be considered active.
281
282 In well-formed IR an active Op has no references to inactive ops
283 or ops used in another function.
284 """
285
286 def __init__(self, line: int) -> None:
287 self.line = line
288
289 def can_raise(self) -> bool:
290 # Override this is if Op may raise an exception. Note that currently the fact that
291 # only RegisterOps may raise an exception in hard coded in some places.
292 return False
293
294 @abstractmethod
295 def sources(self) -> list[Value]:
296 """All the values the op may read."""
297
298 @abstractmethod
299 def set_sources(self, new: list[Value]) -> None:
300 """Rewrite the sources of an op"""
301
302 def stolen(self) -> list[Value]:
303 """Return arguments that have a reference count stolen by this op"""
304 return []
305
306 def unique_sources(self) -> list[Value]:
307 result: list[Value] = []
308 for reg in self.sources():
309 if reg not in result:
310 result.append(reg)
311 return result
312
313 @abstractmethod
314 def accept(self, visitor: OpVisitor[T]) -> T:
315 pass
316
317
318 class BaseAssign(Op):
319 """Abstract base class for ops that assign to a register."""
320
321 def __init__(self, dest: Register, line: int = -1) -> None:
322 super().__init__(line)
323 self.dest = dest
324
325
326 @final
327 class Assign(BaseAssign):
328 """Assign a value to a Register (dest = src)."""
329
330 error_kind = ERR_NEVER
331
332 def __init__(self, dest: Register, src: Value, line: int = -1) -> None:
333 super().__init__(dest, line)
334 self.src = src
335
336 def sources(self) -> list[Value]:
337 return [self.src]
338
339 def set_sources(self, new: list[Value]) -> None:
340 (self.src,) = new
341
342 def stolen(self) -> list[Value]:
343 if not self.dest.type.is_refcounted:
344 return []
345 return [self.src]
346
347 def accept(self, visitor: OpVisitor[T]) -> T:
348 return visitor.visit_assign(self)
349
350
351 @final
352 class AssignMulti(BaseAssign):
353 """Assign multiple values to a Register (dest = src1, src2, ...).
354
355 This is used to initialize RArray values. It's provided to avoid
356 very verbose IR for common vectorcall operations.
357
358 Note that this interacts atypically with reference counting. We
359 assume that each RArray register is initialized exactly once
360 with this op.
361 """
362
363 error_kind = ERR_NEVER
364
365 def __init__(self, dest: Register, src: list[Value], line: int = -1) -> None:
366 super().__init__(dest, line)
367 assert src
368 assert isinstance(dest.type, RArray)
369 assert dest.type.length == len(src)
370 self.src = src
371
372 def sources(self) -> list[Value]:
373 return self.src.copy()
374
375 def set_sources(self, new: list[Value]) -> None:
376 self.src = new[:]
377
378 def stolen(self) -> list[Value]:
379 return []
380
381 def accept(self, visitor: OpVisitor[T]) -> T:
382 return visitor.visit_assign_multi(self)
383
384
385 class ControlOp(Op):
386 """Abstract base class for control flow operations."""
387
388 def targets(self) -> Sequence[BasicBlock]:
389 """Get all basic block targets of the control operation."""
390 return ()
391
392 def set_target(self, i: int, new: BasicBlock) -> None:
393 """Update a basic block target."""
394 raise AssertionError(f"Invalid set_target({self}, {i})")
395
396
397 @final
398 class Goto(ControlOp):
399 """Unconditional jump."""
400
401 error_kind = ERR_NEVER
402
403 def __init__(self, label: BasicBlock, line: int = -1) -> None:
404 super().__init__(line)
405 self.label = label
406
407 def targets(self) -> Sequence[BasicBlock]:
408 return (self.label,)
409
410 def set_target(self, i: int, new: BasicBlock) -> None:
411 assert i == 0
412 self.label = new
413
414 def __repr__(self) -> str:
415 return "<Goto %s>" % self.label.label
416
417 def sources(self) -> list[Value]:
418 return []
419
420 def set_sources(self, new: list[Value]) -> None:
421 assert not new
422
423 def accept(self, visitor: OpVisitor[T]) -> T:
424 return visitor.visit_goto(self)
425
426
427 @final
428 class Branch(ControlOp):
429 """Branch based on a value.
430
431 If op is BOOL, branch based on a bit/bool value:
432 if [not] r1 goto L1 else goto L2
433
434 If op is IS_ERROR, branch based on whether there is an error value:
435 if [not] is_error(r1) goto L1 else goto L2
436 """
437
438 # Branch ops never raise an exception.
439 error_kind = ERR_NEVER
440
441 BOOL: Final = 100
442 IS_ERROR: Final = 101
443
444 def __init__(
445 self,
446 value: Value,
447 true_label: BasicBlock,
448 false_label: BasicBlock,
449 op: int,
450 line: int = -1,
451 *,
452 rare: bool = False,
453 ) -> None:
454 super().__init__(line)
455 # Target value being checked
456 self.value = value
457 # Branch here if the condition is true
458 self.true = true_label
459 # Branch here if the condition is false
460 self.false = false_label
461 # Branch.BOOL (boolean check) or Branch.IS_ERROR (error value check)
462 self.op = op
463 # If True, the condition is negated
464 self.negated = False
465 # If not None, the true label should generate a traceback entry (func name, line number)
466 self.traceback_entry: tuple[str, int] | None = None
467 # If True, we expect to usually take the false branch (for optimization purposes);
468 # this is implicitly treated as true if there is a traceback entry
469 self.rare = rare
470
471 def targets(self) -> Sequence[BasicBlock]:
472 return (self.true, self.false)
473
474 def set_target(self, i: int, new: BasicBlock) -> None:
475 assert i == 0 or i == 1
476 if i == 0:
477 self.true = new
478 else:
479 self.false = new
480
481 def sources(self) -> list[Value]:
482 return [self.value]
483
484 def set_sources(self, new: list[Value]) -> None:
485 (self.value,) = new
486
487 def invert(self) -> None:
488 self.negated = not self.negated
489
490 def accept(self, visitor: OpVisitor[T]) -> T:
491 return visitor.visit_branch(self)
492
493
494 @final
495 class Return(ControlOp):
496 """Return a value from a function."""
497
498 error_kind = ERR_NEVER
499
500 def __init__(
501 self, value: Value, line: int = -1, *, yield_target: BasicBlock | None = None
502 ) -> None:
503 super().__init__(line)
504 self.value = value
505 # If this return is created by a yield, keep track of the next
506 # basic block. This doesn't affect the code we generate but
507 # can feed into analysis that need to understand the
508 # *original* CFG.
509 self.yield_target = yield_target
510
511 def sources(self) -> list[Value]:
512 return [self.value]
513
514 def set_sources(self, new: list[Value]) -> None:
515 (self.value,) = new
516
517 def stolen(self) -> list[Value]:
518 return [self.value]
519
520 def accept(self, visitor: OpVisitor[T]) -> T:
521 return visitor.visit_return(self)
522
523
524 @final
525 class Unreachable(ControlOp):
526 """Mark the end of basic block as unreachable.
527
528 This is sometimes necessary when the end of a basic block is never
529 reached. This can also be explicitly added to the end of non-None
530 returning functions (in None-returning function we can just return
531 None).
532
533 Mypy statically guarantees that the end of the function is not
534 unreachable if there is not a return statement.
535
536 This prevents the block formatter from being confused due to lack
537 of a leave and also leaves a nifty note in the IR. It is not
538 generally processed by visitors.
539 """
540
541 error_kind = ERR_NEVER
542
543 def __init__(self, line: int = -1) -> None:
544 super().__init__(line)
545
546 def sources(self) -> list[Value]:
547 return []
548
549 def set_sources(self, new: list[Value]) -> None:
550 assert not new
551
552 def accept(self, visitor: OpVisitor[T]) -> T:
553 return visitor.visit_unreachable(self)
554
555
556 class RegisterOp(Op):
557 """Abstract base class for operations that can be written as r1 = f(r2, ..., rn).
558
559 Takes some values, performs an operation, and generates an output
560 (unless the 'type' attribute is void_rtype, which is the default).
561 Other ops can refer to the result of the Op by referring to the Op
562 instance. This doesn't do any explicit control flow, but can raise an
563 error.
564
565 Note that the operands can be arbitrary Values, not just Register
566 instances, even though the naming may suggest otherwise.
567 """
568
569 error_kind = -1 # Can this raise exception and how is it signalled; one of ERR_*
570
571 _type: RType | None = None
572
573 def __init__(self, line: int) -> None:
574 super().__init__(line)
575 assert self.error_kind != -1, "error_kind not defined"
576
577 def can_raise(self) -> bool:
578 return self.error_kind != ERR_NEVER
579
580
581 @final
582 class IncRef(RegisterOp):
583 """Increase reference count (inc_ref src)."""
584
585 error_kind = ERR_NEVER
586
587 def __init__(self, src: Value, line: int = -1) -> None:
588 assert src.type.is_refcounted
589 super().__init__(line)
590 self.src = src
591
592 def sources(self) -> list[Value]:
593 return [self.src]
594
595 def set_sources(self, new: list[Value]) -> None:
596 (self.src,) = new
597
598 def accept(self, visitor: OpVisitor[T]) -> T:
599 return visitor.visit_inc_ref(self)
600
601
602 @final
603 class DecRef(RegisterOp):
604 """Decrease reference count and free object if zero (dec_ref src).
605
606 The is_xdec flag says to use an XDECREF, which checks if the
607 pointer is NULL first.
608 """
609
610 error_kind = ERR_NEVER
611
612 def __init__(self, src: Value, is_xdec: bool = False, line: int = -1) -> None:
613 assert src.type.is_refcounted
614 super().__init__(line)
615 self.src = src
616 self.is_xdec = is_xdec
617
618 def __repr__(self) -> str:
619 return "<{}DecRef {!r}>".format("X" if self.is_xdec else "", self.src)
620
621 def sources(self) -> list[Value]:
622 return [self.src]
623
624 def set_sources(self, new: list[Value]) -> None:
625 (self.src,) = new
626
627 def accept(self, visitor: OpVisitor[T]) -> T:
628 return visitor.visit_dec_ref(self)
629
630
631 @final
632 class Call(RegisterOp):
633 """Native call f(arg, ...).
634
635 The call target can be a module-level function or a class.
636 """
637
638 def __init__(self, fn: FuncDecl, args: Sequence[Value], line: int) -> None:
639 self.fn = fn
640 self.args = list(args)
641 assert len(self.args) == len(fn.sig.args)
642 self.type = fn.sig.ret_type
643 ret_type = fn.sig.ret_type
644 if not ret_type.error_overlap:
645 self.error_kind = ERR_MAGIC
646 else:
647 self.error_kind = ERR_MAGIC_OVERLAPPING
648 super().__init__(line)
649
650 def sources(self) -> list[Value]:
651 return list(self.args.copy())
652
653 def set_sources(self, new: list[Value]) -> None:
654 self.args = new[:]
655
656 def accept(self, visitor: OpVisitor[T]) -> T:
657 return visitor.visit_call(self)
658
659
660 @final
661 class MethodCall(RegisterOp):
662 """Native method call obj.method(arg, ...)"""
663
664 def __init__(self, obj: Value, method: str, args: list[Value], line: int = -1) -> None:
665 self.obj = obj
666 self.method = method
667 self.args = args
668 assert isinstance(obj.type, RInstance), "Methods can only be called on instances"
669 self.receiver_type = obj.type
670 method_ir = self.receiver_type.class_ir.method_sig(method)
671 assert method_ir is not None, "{} doesn't have method {}".format(
672 self.receiver_type.name, method
673 )
674 ret_type = method_ir.ret_type
675 self.type = ret_type
676 if not ret_type.error_overlap:
677 self.error_kind = ERR_MAGIC
678 else:
679 self.error_kind = ERR_MAGIC_OVERLAPPING
680 super().__init__(line)
681
682 def sources(self) -> list[Value]:
683 return self.args.copy() + [self.obj]
684
685 def set_sources(self, new: list[Value]) -> None:
686 *self.args, self.obj = new
687
688 def accept(self, visitor: OpVisitor[T]) -> T:
689 return visitor.visit_method_call(self)
690
691
692 @final
693 class PrimitiveDescription:
694 """Description of a primitive op.
695
696 Primitives get lowered into lower-level ops before code generation.
697
698 If c_function_name is provided, a primitive will be lowered into a CallC op.
699 Otherwise, custom logic will need to be implemented to transform the
700 primitive into lower-level ops.
701 """
702
703 def __init__(
704 self,
705 name: str,
706 arg_types: list[RType],
707 return_type: RType,
708 var_arg_type: RType | None,
709 truncated_type: RType | None,
710 c_function_name: str | None,
711 error_kind: int,
712 steals: StealsDescription,
713 is_borrowed: bool,
714 ordering: list[int] | None,
715 extra_int_constants: list[tuple[int, RType]],
716 priority: int,
717 is_pure: bool,
718 experimental: bool,
719 dependencies: list[Dependency] | None,
720 type_params: list[RTypeVar] | None,
721 ) -> None:
722 # Each primitive much have a distinct name, but otherwise they are arbitrary.
723 self.name: Final = name
724 self.arg_types: Final = arg_types
725 self.return_type: Final = return_type
726 self.var_arg_type: Final = var_arg_type
727 self.truncated_type: Final = truncated_type
728 # If non-None, this will map to a call of a C helper function; if None,
729 # there must be a custom handler function that gets invoked during the lowering
730 # pass to generate low-level IR for the primitive (in the mypyc.lower package)
731 self.c_function_name: Final = c_function_name
732 self.error_kind: Final = error_kind
733 self.steals: Final = steals
734 self.is_borrowed: Final = is_borrowed
735 self.ordering: Final = ordering
736 self.extra_int_constants: Final = extra_int_constants
737 self.priority: Final = priority
738 # Pure primitives have no side effects, take immutable arguments, and
739 # never fail. They support additional optimizations.
740 self.is_pure: Final = is_pure
741 if is_pure:
742 assert error_kind == ERR_NEVER
743 # Experimental primitives are not used unless mypyc experimental features are
744 # explicitly enabled
745 self.experimental = experimental
746 # Dependencies for the primitive, such as a capsule that needs to imported
747 # and configured to call the primitive.
748 self.dependencies = dependencies
749 # Native integer types such as u8 can cause ambiguity in primitive
750 # matching, since these are assignable to plain int *and* vice versa.
751 # If this flag is set, the primitive has native integer types and must
752 # be matched using more complex rules.
753 self.is_ambiguous = any(has_fixed_width_int(t) for t in arg_types)
754 self.type_params = None if not type_params else type_params
755
756 def __repr__(self) -> str:
757 return f"<PrimitiveDescription {self.name!r}: {self.arg_types}>"
758
759
760 def has_fixed_width_int(t: RType) -> bool:
761 if isinstance(t, RTuple):
762 return any(has_fixed_width_int(t) for t in t.types)
763 elif isinstance(t, RUnion):
764 return any(has_fixed_width_int(t) for t in t.items)
765 return is_fixed_width_rtype(t)
766
767
768 @final
769 class PrimitiveOp(RegisterOp):
770 """A higher-level primitive operation.
771
772 Some of these have special compiler support. These will be lowered
773 (transformed) into lower-level IR ops before code generation, and after
774 reference counting op insertion. Others will be transformed into CallC
775 ops.
776
777 Tagged integer equality is a typical primitive op with non-trivial
778 lowering. It gets transformed into a tag check, followed by different
779 code paths for short and long representations.
780 """
781
782 def __init__(
783 self,
784 args: list[Value],
785 desc: PrimitiveDescription,
786 line: int = -1,
787 *,
788 arg_types: list[RType] | None = None,
789 return_type: RType | None = None,
790 type_args: list[RType] | None = None,
791 ) -> None:
792 self.error_kind = desc.error_kind
793 super().__init__(line)
794 self.args = args
795 self.arg_types = arg_types if arg_types is not None else desc.arg_types
796 self.type = return_type if return_type is not None else desc.return_type
797 self.is_borrowed = desc.is_borrowed
798 self.type_args = type_args
799 self.desc = desc
800
801 def sources(self) -> list[Value]:
802 return self.args
803
804 def set_sources(self, new: list[Value]) -> None:
805 self.args = new[:]
806
807 def stolen(self) -> list[Value]:
808 steals = self.desc.steals
809 if isinstance(steals, list):
810 assert len(steals) == len(self.args)
811 return [arg for arg, steal in zip(self.args, steals) if steal]
812 else:
813 return [] if not steals else self.sources()
814
815 def accept(self, visitor: OpVisitor[T]) -> T:
816 return visitor.visit_primitive_op(self)
817
818
819 @final
820 class LoadErrorValue(RegisterOp):
821 """Load an error value.
822
823 Each type has one reserved value that signals an error (exception). This
824 loads the error value for a specific type.
825 """
826
827 error_kind = ERR_NEVER
828
829 def __init__(
830 self, rtype: RType, line: int = -1, is_borrowed: bool = False, undefines: bool = False
831 ) -> None:
832 super().__init__(line)
833 self.type = rtype
834 self.is_borrowed = is_borrowed
835 # Undefines is true if this should viewed by the definedness
836 # analysis pass as making the register it is assigned to
837 # undefined (and thus checks should be added on uses).
838 self.undefines = undefines
839
840 def sources(self) -> list[Value]:
841 return []
842
843 def set_sources(self, new: list[Value]) -> None:
844 assert not new
845
846 def accept(self, visitor: OpVisitor[T]) -> T:
847 return visitor.visit_load_error_value(self)
848
849
850 @final
851 class LoadLiteral(RegisterOp):
852 """Load a Python literal object (dest = 'foo' / b'foo' / ...).
853
854 This is used to load a static PyObject * value corresponding to
855 a literal of one of the supported types.
856
857 Tuple / frozenset literals must contain only valid literal values as items.
858
859 NOTE: You can use this to load boxed (Python) int objects. Use
860 Integer to load unboxed, tagged integers or fixed-width,
861 low-level integers.
862
863 For int literals, both int_rprimitive (CPyTagged) and
864 object_primitive (PyObject *) are supported as rtype. However,
865 when using int_rprimitive, the value must *not* be small enough
866 to fit in an unboxed integer.
867 """
868
869 error_kind = ERR_NEVER
870 is_borrowed = True
871
872 def __init__(self, value: LiteralValue, rtype: RType, line: int = -1) -> None:
873 super().__init__(line)
874 self.value = value
875 self.type = rtype
876
877 def sources(self) -> list[Value]:
878 return []
879
880 def set_sources(self, new: list[Value]) -> None:
881 assert not new
882
883 def accept(self, visitor: OpVisitor[T]) -> T:
884 return visitor.visit_load_literal(self)
885
886
887 @final
888 class GetAttr(RegisterOp):
889 """obj.attr (for a native object)"""
890
891 error_kind = ERR_MAGIC
892
893 def __init__(
894 self,
895 obj: Value,
896 attr: str,
897 line: int,
898 *,
899 borrow: bool = False,
900 allow_error_value: bool = False,
901 borrow_scope: int = KEEP_ALIVE_SHORT_LIVED,
902 ) -> None:
903 super().__init__(line)
904 self.obj = obj
905 self.attr = attr
906 self.allow_error_value = allow_error_value
907 assert isinstance(obj.type, RInstance), "Attribute access not supported: %s" % obj.type
908 self.class_type = obj.type
909 attr_type = obj.type.attr_type(attr)
910 self.type = attr_type
911 if allow_error_value:
912 self.error_kind = ERR_NEVER
913 elif attr_type.error_overlap:
914 self.error_kind = ERR_MAGIC_OVERLAPPING
915 self.is_borrowed = borrow and attr_type.is_refcounted
916 # How long a borrowed result of this op stays valid (a KEEP_ALIVE_* constant).
917 self.borrow_scope = borrow_scope
918
919 def sources(self) -> list[Value]:
920 return [self.obj]
921
922 def set_sources(self, new: list[Value]) -> None:
923 (self.obj,) = new
924
925 def accept(self, visitor: OpVisitor[T]) -> T:
926 return visitor.visit_get_attr(self)
927
928
929 @final
930 class SetAttr(RegisterOp):
931 """obj.attr = src (for a native object)"""
932
933 error_kind = ERR_FALSE
934
935 def __init__(self, obj: Value, attr: str, src: Value, line: int) -> None:
936 super().__init__(line)
937 self.obj = obj
938 self.attr = attr
939 self.src = src
940 assert isinstance(obj.type, RInstance), "Attribute access not supported: %s" % obj.type
941 self.class_type = obj.type
942 self.type = bool_rprimitive
943 # If True, we can safely assume that the attribute is previously undefined
944 # and we don't use a setter
945 self.is_init = False
946
947 cl = self.class_type.class_ir
948 is_propset = False
949 for ir in cl.mro:
950 propset = ir.method_decls.get(PROPSET_PREFIX + attr)
951 if propset is not None:
952 is_propset = not propset.implicit
953 break
954 # If True, this op represents calling a property setter.
955 self.is_propset = is_propset
956
957 def mark_as_initializer(self) -> None:
958 self.is_init = True
959 self.error_kind = ERR_NEVER
960 self.type = void_rtype
961
962 def sources(self) -> list[Value]:
963 return [self.obj, self.src]
964
965 def set_sources(self, new: list[Value]) -> None:
966 self.obj, self.src = new
967
968 def stolen(self) -> list[Value]:
969 # The property setter method increfs the passed value so don't treat it as a steal
970 # to avoid leaking.
971 if self.is_propset:
972 return []
973 return [self.src]
974
975 def accept(self, visitor: OpVisitor[T]) -> T:
976 return visitor.visit_set_attr(self)
977
978
979 # Default name space for statics, variables
980 NAMESPACE_STATIC: Final = "static"
981
982 # Static namespace for pointers to native type objects
983 NAMESPACE_TYPE: Final = "type"
984
985 # Namespace for modules
986 NAMESPACE_MODULE: Final = "module"
987
988 # Namespace for Python 3.12 type variable objects (implicitly created TypeVar instances, etc.)
989 NAMESPACE_TYPE_VAR: Final = "typevar"
990
991
992 @final
993 class LoadStatic(RegisterOp):
994 """Load a static name (name :: static).
995
996 Load a C static variable/pointer. The namespace for statics is shared
997 for the entire compilation group. You can optionally provide a module
998 name and a sub-namespace identifier for additional namespacing to avoid
999 name conflicts. The static namespace does not overlap with other C names,
1000 since the final C name will get a prefix, so conflicts only must be
1001 avoided with other statics.
1002 """
1003
1004 error_kind = ERR_NEVER
1005 is_borrowed = True
1006
1007 def __init__(
1008 self,
1009 type: RType,
1010 identifier: str,
1011 module_name: str | None = None,
1012 namespace: str = NAMESPACE_STATIC,
1013 line: int = -1,
1014 ann: object = None,
1015 ) -> None:
1016 super().__init__(line)
1017 self.identifier = identifier
1018 self.module_name = module_name
1019 self.namespace = namespace
1020 self.type = type
1021 self.ann = ann # An object to pretty print with the load
1022
1023 def sources(self) -> list[Value]:
1024 return []
1025
1026 def set_sources(self, new: list[Value]) -> None:
1027 assert not new
1028
1029 def accept(self, visitor: OpVisitor[T]) -> T:
1030 return visitor.visit_load_static(self)
1031
1032
1033 @final
1034 class InitStatic(RegisterOp):
1035 """static = value :: static
1036
1037 Initialize a C static variable/pointer. See everything in LoadStatic.
1038 """
1039
1040 error_kind = ERR_NEVER
1041
1042 def __init__(
1043 self,
1044 value: Value,
1045 identifier: str,
1046 module_name: str | None = None,
1047 namespace: str = NAMESPACE_STATIC,
1048 line: int = -1,
1049 ) -> None:
1050 super().__init__(line)
1051 self.identifier = identifier
1052 self.module_name = module_name
1053 self.namespace = namespace
1054 self.value = value
1055
1056 def sources(self) -> list[Value]:
1057 return [self.value]
1058
1059 def set_sources(self, new: list[Value]) -> None:
1060 (self.value,) = new
1061
1062 def accept(self, visitor: OpVisitor[T]) -> T:
1063 return visitor.visit_init_static(self)
1064
1065
1066 @final
1067 class TupleSet(RegisterOp):
1068 """dest = (reg, ...) (for fixed-length tuple)"""
1069
1070 error_kind = ERR_NEVER
1071
1072 def __init__(self, items: list[Value], line: int) -> None:
1073 super().__init__(line)
1074 self.items = items
1075 # Don't keep track of the fact that an int is short after it
1076 # is put into a tuple, since we don't properly implement
1077 # runtime subtyping for tuples.
1078 self.tuple_type = RTuple(
1079 [
1080 arg.type if not is_short_int_rprimitive(arg.type) else int_rprimitive
1081 for arg in items
1082 ]
1083 )
1084 self.type = self.tuple_type
1085
1086 def sources(self) -> list[Value]:
1087 return self.items.copy()
1088
1089 def stolen(self) -> list[Value]:
1090 return self.items.copy()
1091
1092 def set_sources(self, new: list[Value]) -> None:
1093 self.items = new[:]
1094
1095 def accept(self, visitor: OpVisitor[T]) -> T:
1096 return visitor.visit_tuple_set(self)
1097
1098
1099 @final
1100 class TupleGet(RegisterOp):
1101 """Get item of a fixed-length tuple (src[index])."""
1102
1103 error_kind = ERR_NEVER
1104
1105 def __init__(self, src: Value, index: int, line: int = -1, *, borrow: bool = False) -> None:
1106 super().__init__(line)
1107 assert isinstance(
1108 src.type, RTuple
1109 ), f"TupleGet only operates on tuples, not {type(src.type).__name__}"
1110 src_len = len(src.type.types)
1111 self.src = src
1112 self.index = index
1113 if index < 0:
1114 self.index += src_len
1115 assert (
1116 self.index <= src_len - 1
1117 ), f"Index out of range.\nsource type: {src.type}\nindex: {index}"
1118 self.type = src.type.types[index]
1119 self.is_borrowed = borrow
1120
1121 def sources(self) -> list[Value]:
1122 return [self.src]
1123
1124 def set_sources(self, new: list[Value]) -> None:
1125 (self.src,) = new
1126
1127 def accept(self, visitor: OpVisitor[T]) -> T:
1128 return visitor.visit_tuple_get(self)
1129
1130
1131 @final
1132 class Cast(RegisterOp):
1133 """cast(type, src)
1134
1135 Perform a runtime type check (no representation or value conversion).
1136
1137 DO NOT increment reference counts.
1138 """
1139
1140 error_kind = ERR_MAGIC
1141
1142 def __init__(
1143 self, src: Value, typ: RType, line: int, *, borrow: bool = False, unchecked: bool = False
1144 ) -> None:
1145 super().__init__(line)
1146 self.src = src
1147 self.type = typ
1148 # If true, don't incref the result.
1149 self.is_borrowed = borrow
1150 # If true, don't perform a runtime type check (only changes the static type of
1151 # the operand). Used when we know that the cast will always succeed.
1152 self.is_unchecked = unchecked
1153 if unchecked:
1154 self.error_kind = ERR_NEVER
1155
1156 def sources(self) -> list[Value]:
1157 return [self.src]
1158
1159 def set_sources(self, new: list[Value]) -> None:
1160 (self.src,) = new
1161
1162 def stolen(self) -> list[Value]:
1163 if self.is_borrowed:
1164 return []
1165 return [self.src]
1166
1167 def accept(self, visitor: OpVisitor[T]) -> T:
1168 return visitor.visit_cast(self)
1169
1170
1171 @final
1172 class Box(RegisterOp):
1173 """box(type, src)
1174
1175 This converts from a potentially unboxed representation to a straight Python object.
1176 Only supported for types with an unboxed representation.
1177 """
1178
1179 error_kind = ERR_NEVER
1180
1181 def __init__(self, src: Value, line: int = -1) -> None:
1182 super().__init__(line)
1183 self.src = src
1184 self.type = object_rprimitive
1185 # When we box None and bool values, we produce a borrowed result
1186 if is_none_rprimitive(self.src.type) or is_bool_or_bit_rprimitive(self.src.type):
1187 self.is_borrowed = True
1188
1189 def sources(self) -> list[Value]:
1190 return [self.src]
1191
1192 def set_sources(self, new: list[Value]) -> None:
1193 (self.src,) = new
1194
1195 def stolen(self) -> list[Value]:
1196 return [self.src]
1197
1198 def accept(self, visitor: OpVisitor[T]) -> T:
1199 return visitor.visit_box(self)
1200
1201
1202 @final
1203 class Unbox(RegisterOp):
1204 """unbox(type, src)
1205
1206 This is similar to a cast, but it also changes to a (potentially) unboxed runtime
1207 representation. Only supported for types with an unboxed representation.
1208 """
1209
1210 def __init__(self, src: Value, typ: RType, line: int) -> None:
1211 self.src = src
1212 self.type = typ
1213 if not typ.error_overlap:
1214 self.error_kind = ERR_MAGIC
1215 else:
1216 self.error_kind = ERR_MAGIC_OVERLAPPING
1217 super().__init__(line)
1218
1219 def sources(self) -> list[Value]:
1220 return [self.src]
1221
1222 def set_sources(self, new: list[Value]) -> None:
1223 (self.src,) = new
1224
1225 def accept(self, visitor: OpVisitor[T]) -> T:
1226 return visitor.visit_unbox(self)
1227
1228
1229 @final
1230 class RaiseStandardError(RegisterOp):
1231 """Raise built-in exception with an optional error string.
1232
1233 We have a separate opcode for this for convenience and to
1234 generate smaller, more idiomatic C code.
1235 """
1236
1237 # TODO: Make it more explicit at IR level that this always raises
1238
1239 error_kind = ERR_FALSE
1240
1241 VALUE_ERROR: Final = "ValueError"
1242 ASSERTION_ERROR: Final = "AssertionError"
1243 STOP_ITERATION: Final = "StopIteration"
1244 UNBOUND_LOCAL_ERROR: Final = "UnboundLocalError"
1245 RUNTIME_ERROR: Final = "RuntimeError"
1246 NAME_ERROR: Final = "NameError"
1247 ZERO_DIVISION_ERROR: Final = "ZeroDivisionError"
1248 INDEX_ERROR: Final = "IndexError"
1249
1250 def __init__(self, class_name: str, value: str | Value | None, line: int) -> None:
1251 super().__init__(line)
1252 self.class_name = class_name
1253 self.value = value
1254 self.type = bool_rprimitive
1255
1256 def sources(self) -> list[Value]:
1257 return []
1258
1259 def set_sources(self, new: list[Value]) -> None:
1260 assert not new
1261
1262 def accept(self, visitor: OpVisitor[T]) -> T:
1263 return visitor.visit_raise_standard_error(self)
1264
1265
1266 # True steals all arguments, False steals none, a list steals those in matching positions
1267 StealsDescription = bool | list[bool]
1268
1269
1270 @final
1271 class CallC(RegisterOp):
1272 """result = function(arg0, arg1, ...)
1273
1274 Call a C function that is not a compiled/native function (for
1275 example, a Python C API function). Use Call to call native
1276 functions.
1277 """
1278
1279 def __init__(
1280 self,
1281 function_name: str,
1282 args: list[Value],
1283 ret_type: RType,
1284 steals: StealsDescription,
1285 is_borrowed: bool,
1286 error_kind: int,
1287 line: int,
1288 var_arg_idx: int = -1,
1289 *,
1290 is_pure: bool = False,
1291 returns_null: bool = False,
1292 dependencies: list[Dependency] | None = None,
1293 ) -> None:
1294 self.error_kind = error_kind
1295 super().__init__(line)
1296 self.function_name = function_name
1297 self.args = args
1298 self.type = ret_type
1299 self.steals = steals
1300 self.is_borrowed = is_borrowed
1301 # The position of the first variable argument in args (if >= 0)
1302 self.var_arg_idx = var_arg_idx
1303 # Is the function pure? Pure functions have no side effects
1304 # and all the arguments are immutable. Pure functions support
1305 # additional optimizations. Pure functions never fail.
1306 self.is_pure = is_pure
1307 # The function might return a null value that does not indicate
1308 # an error.
1309 self.returns_null = returns_null
1310 # Dependencies (such as capsules) that must be imported and initialized before
1311 # calling this function (used for C functions exported from librt).
1312 self.dependencies = dependencies
1313 if is_pure or returns_null:
1314 assert error_kind == ERR_NEVER
1315
1316 def sources(self) -> list[Value]:
1317 return self.args[:]
1318
1319 def set_sources(self, new: list[Value]) -> None:
1320 self.args = new[:]
1321
1322 def stolen(self) -> list[Value]:
1323 if isinstance(self.steals, list):
1324 assert len(self.steals) == len(self.args)
1325 return [arg for arg, steal in zip(self.args, self.steals) if steal]
1326 else:
1327 return [] if not self.steals else self.sources()
1328
1329 def accept(self, visitor: OpVisitor[T]) -> T:
1330 return visitor.visit_call_c(self)
1331
1332
1333 @final
1334 class Truncate(RegisterOp):
1335 """result = truncate src from src_type to dst_type
1336
1337 Truncate a value from type with more bits to type with less bits.
1338
1339 dst_type and src_type can be native integer types, bools or tagged
1340 integers. Tagged integers should have the tag bit unset.
1341 """
1342
1343 error_kind = ERR_NEVER
1344
1345 def __init__(self, src: Value, dst_type: RType, line: int = -1) -> None:
1346 super().__init__(line)
1347 self.src = src
1348 self.type = dst_type
1349 self.src_type = src.type
1350
1351 def sources(self) -> list[Value]:
1352 return [self.src]
1353
1354 def set_sources(self, new: list[Value]) -> None:
1355 (self.src,) = new
1356
1357 def stolen(self) -> list[Value]:
1358 return []
1359
1360 def accept(self, visitor: OpVisitor[T]) -> T:
1361 return visitor.visit_truncate(self)
1362
1363
1364 @final
1365 class Extend(RegisterOp):
1366 """result = extend src from src_type to dst_type
1367
1368 Extend a value from a type with fewer bits to a type with more bits.
1369
1370 dst_type and src_type can be native integer types, bools or tagged
1371 integers. Tagged integers should have the tag bit unset.
1372
1373 If 'signed' is true, perform sign extension. Otherwise, the result will be
1374 zero extended.
1375 """
1376
1377 error_kind = ERR_NEVER
1378
1379 def __init__(self, src: Value, dst_type: RType, signed: bool, line: int = -1) -> None:
1380 super().__init__(line)
1381 self.src = src
1382 self.type = dst_type
1383 self.src_type = src.type
1384 self.signed = signed
1385
1386 def sources(self) -> list[Value]:
1387 return [self.src]
1388
1389 def set_sources(self, new: list[Value]) -> None:
1390 (self.src,) = new
1391
1392 def stolen(self) -> list[Value]:
1393 return []
1394
1395 def accept(self, visitor: OpVisitor[T]) -> T:
1396 return visitor.visit_extend(self)
1397
1398
1399 @final
1400 class LoadGlobal(RegisterOp):
1401 """Load a low-level global variable/pointer.
1402
1403 Note that can't be used to directly load Python module-level
1404 global variable, since they are stored in a globals dictionary
1405 and accessed using dictionary operations.
1406 """
1407
1408 error_kind = ERR_NEVER
1409 is_borrowed = True
1410
1411 def __init__(self, type: RType, identifier: str, line: int = -1, ann: object = None) -> None:
1412 super().__init__(line)
1413 self.identifier = identifier
1414 self.type = type
1415 self.ann = ann # An object to pretty print with the load
1416
1417 def sources(self) -> list[Value]:
1418 return []
1419
1420 def set_sources(self, new: list[Value]) -> None:
1421 assert not new
1422
1423 def accept(self, visitor: OpVisitor[T]) -> T:
1424 return visitor.visit_load_global(self)
1425
1426
1427 @final
1428 class IntOp(RegisterOp):
1429 """Binary arithmetic or bitwise op on integer operands (e.g., r1 = r2 + r3).
1430
1431 These ops are low-level and are similar to the corresponding C
1432 operations.
1433
1434 The left and right values must have low-level integer types with
1435 compatible representations. Fixed-width integers, short_int_rprimitive,
1436 bool_rprimitive and bit_rprimitive are supported.
1437
1438 For tagged (arbitrary-precision) integer ops look at mypyc.primitives.int_ops.
1439 """
1440
1441 error_kind = ERR_NEVER
1442
1443 # Arithmetic ops
1444 ADD: Final = 0
1445 SUB: Final = 1
1446 MUL: Final = 2
1447 DIV: Final = 3
1448 MOD: Final = 4
1449
1450 # Bitwise ops
1451 AND: Final = 200
1452 OR: Final = 201
1453 XOR: Final = 202
1454 LEFT_SHIFT: Final = 203
1455 RIGHT_SHIFT: Final = 204
1456
1457 op_str: Final = {
1458 ADD: "+",
1459 SUB: "-",
1460 MUL: "*",
1461 DIV: "/",
1462 MOD: "%",
1463 AND: "&",
1464 OR: "|",
1465 XOR: "^",
1466 LEFT_SHIFT: "<<",
1467 RIGHT_SHIFT: ">>",
1468 }
1469
1470 def __init__(self, type: RType, lhs: Value, rhs: Value, op: int, line: int = -1) -> None:
1471 super().__init__(line)
1472 self.type = type
1473 self.lhs = lhs
1474 self.rhs = rhs
1475 self.op = op
1476
1477 def sources(self) -> list[Value]:
1478 return [self.lhs, self.rhs]
1479
1480 def set_sources(self, new: list[Value]) -> None:
1481 self.lhs, self.rhs = new
1482
1483 def accept(self, visitor: OpVisitor[T]) -> T:
1484 return visitor.visit_int_op(self)
1485
1486
1487 # We can't have this in the IntOp class body, because of
1488 # https://github.com/mypyc/mypyc/issues/932.
1489 int_op_to_id: Final = {op: op_id for op_id, op in IntOp.op_str.items()}
1490
1491
1492 @final
1493 class ComparisonOp(RegisterOp):
1494 """Low-level comparison op for integers and pointers.
1495
1496 Both unsigned and signed comparisons are supported. Supports
1497 comparisons between fixed-width integer types and pointer types.
1498 The operands should have matching sizes.
1499
1500 The result is always a bit (representing a boolean).
1501
1502 Python semantics, such as calling __eq__, are not supported.
1503 """
1504
1505 # Must be ERR_NEVER or ERR_FALSE. ERR_FALSE means that a false result
1506 # indicates that an exception has been raised and should be propagated.
1507 error_kind = ERR_NEVER
1508
1509 # S for signed and U for unsigned
1510 EQ: Final = 100
1511 NEQ: Final = 101
1512 SLT: Final = 102
1513 SGT: Final = 103
1514 SLE: Final = 104
1515 SGE: Final = 105
1516 ULT: Final = 106
1517 UGT: Final = 107
1518 ULE: Final = 108
1519 UGE: Final = 109
1520
1521 op_str: Final = {
1522 EQ: "==",
1523 NEQ: "!=",
1524 SLT: "<",
1525 SGT: ">",
1526 SLE: "<=",
1527 SGE: ">=",
1528 ULT: "<",
1529 UGT: ">",
1530 ULE: "<=",
1531 UGE: ">=",
1532 }
1533
1534 signed_ops: Final = {"==": EQ, "!=": NEQ, "<": SLT, ">": SGT, "<=": SLE, ">=": SGE}
1535 unsigned_ops: Final = {"==": EQ, "!=": NEQ, "<": ULT, ">": UGT, "<=": ULE, ">=": UGE}
1536
1537 def __init__(self, lhs: Value, rhs: Value, op: int, line: int = -1) -> None:
1538 super().__init__(line)
1539 self.type = bit_rprimitive
1540 self.lhs = lhs
1541 self.rhs = rhs
1542 self.op = op
1543
1544 def sources(self) -> list[Value]:
1545 return [self.lhs, self.rhs]
1546
1547 def set_sources(self, new: list[Value]) -> None:
1548 self.lhs, self.rhs = new
1549
1550 def accept(self, visitor: OpVisitor[T]) -> T:
1551 return visitor.visit_comparison_op(self)
1552
1553
1554 @final
1555 class FloatOp(RegisterOp):
1556 """Binary float arithmetic op (e.g., r1 = r2 + r3).
1557
1558 These ops are low-level and are similar to the corresponding C
1559 operations (and somewhat different from Python operations).
1560
1561 The left and right values must be floats.
1562 """
1563
1564 error_kind = ERR_NEVER
1565
1566 ADD: Final = 0
1567 SUB: Final = 1
1568 MUL: Final = 2
1569 DIV: Final = 3
1570 MOD: Final = 4
1571
1572 op_str: Final = {ADD: "+", SUB: "-", MUL: "*", DIV: "/", MOD: "%"}
1573
1574 def __init__(self, lhs: Value, rhs: Value, op: int, line: int = -1) -> None:
1575 super().__init__(line)
1576 self.type = float_rprimitive
1577 self.lhs = lhs
1578 self.rhs = rhs
1579 self.op = op
1580
1581 def sources(self) -> list[Value]:
1582 return [self.lhs, self.rhs]
1583
1584 def set_sources(self, new: list[Value]) -> None:
1585 self.lhs, self.rhs = new
1586
1587 def accept(self, visitor: OpVisitor[T]) -> T:
1588 return visitor.visit_float_op(self)
1589
1590
1591 # We can't have this in the FloatOp class body, because of
1592 # https://github.com/mypyc/mypyc/issues/932.
1593 float_op_to_id: Final = {op: op_id for op_id, op in FloatOp.op_str.items()}
1594
1595
1596 @final
1597 class FloatNeg(RegisterOp):
1598 """Float negation op (r1 = -r2)."""
1599
1600 error_kind = ERR_NEVER
1601
1602 def __init__(self, src: Value, line: int = -1) -> None:
1603 super().__init__(line)
1604 self.type = float_rprimitive
1605 self.src = src
1606
1607 def sources(self) -> list[Value]:
1608 return [self.src]
1609
1610 def set_sources(self, new: list[Value]) -> None:
1611 (self.src,) = new
1612
1613 def accept(self, visitor: OpVisitor[T]) -> T:
1614 return visitor.visit_float_neg(self)
1615
1616
1617 @final
1618 class FloatComparisonOp(RegisterOp):
1619 """Low-level comparison op for floats."""
1620
1621 error_kind = ERR_NEVER
1622
1623 EQ: Final = 200
1624 NEQ: Final = 201
1625 LT: Final = 202
1626 GT: Final = 203
1627 LE: Final = 204
1628 GE: Final = 205
1629
1630 op_str: Final = {EQ: "==", NEQ: "!=", LT: "<", GT: ">", LE: "<=", GE: ">="}
1631
1632 def __init__(self, lhs: Value, rhs: Value, op: int, line: int = -1) -> None:
1633 super().__init__(line)
1634 self.type = bit_rprimitive
1635 self.lhs = lhs
1636 self.rhs = rhs
1637 self.op = op
1638
1639 def sources(self) -> list[Value]:
1640 return [self.lhs, self.rhs]
1641
1642 def set_sources(self, new: list[Value]) -> None:
1643 self.lhs, self.rhs = new
1644
1645 def accept(self, visitor: OpVisitor[T]) -> T:
1646 return visitor.visit_float_comparison_op(self)
1647
1648
1649 # We can't have this in the FloatOp class body, because of
1650 # https://github.com/mypyc/mypyc/issues/932.
1651 float_comparison_op_to_id: Final = {op: op_id for op_id, op in FloatComparisonOp.op_str.items()}
1652
1653
1654 @final
1655 class LoadMem(RegisterOp):
1656 """Read a memory location: result = *(type *)src.
1657
1658 Attributes:
1659 type: Type of the read value
1660 src: Pointer to memory to read
1661 """
1662
1663 error_kind = ERR_NEVER
1664
1665 def __init__(self, type: RType, src: Value, line: int = -1, *, borrow: bool = False) -> None:
1666 super().__init__(line)
1667 self.type = type
1668 # TODO: Support other native integer types
1669 assert is_pointer_rprimitive(src.type)
1670 self.src = src
1671 self.is_borrowed = borrow and type.is_refcounted
1672
1673 def sources(self) -> list[Value]:
1674 return [self.src]
1675
1676 def set_sources(self, new: list[Value]) -> None:
1677 (self.src,) = new
1678
1679 def accept(self, visitor: OpVisitor[T]) -> T:
1680 return visitor.visit_load_mem(self)
1681
1682
1683 @final
1684 class SetMem(Op):
1685 """Write to a memory location: *(type *)dest = src
1686
1687 Attributes:
1688 type: Type of the written value
1689 dest: Pointer to memory to write
1690 src: Source value
1691 """
1692
1693 error_kind = ERR_NEVER
1694
1695 def __init__(self, type: RType, dest: Value, src: Value, line: int = -1) -> None:
1696 super().__init__(line)
1697 self.type = void_rtype
1698 self.dest_type = type
1699 self.src = src
1700 self.dest = dest
1701
1702 def sources(self) -> list[Value]:
1703 return [self.src, self.dest]
1704
1705 def set_sources(self, new: list[Value]) -> None:
1706 self.src, self.dest = new
1707
1708 def stolen(self) -> list[Value]:
1709 return [self.src]
1710
1711 def accept(self, visitor: OpVisitor[T]) -> T:
1712 return visitor.visit_set_mem(self)
1713
1714
1715 @final
1716 class GetElement(RegisterOp):
1717 """Get the value of a struct element from a struct value."""
1718
1719 error_kind = ERR_NEVER
1720 is_borrowed = True
1721
1722 def __init__(self, src: Value, field: str, line: int = -1) -> None:
1723 super().__init__(line)
1724 assert isinstance(src.type, (RStruct, RVec))
1725 self.type = src.type.field_type(field)
1726 self.src = src
1727 self.src_type = src.type
1728 self.field = field
1729
1730 def sources(self) -> list[Value]:
1731 return [self.src]
1732
1733 def set_sources(self, new: list[Value]) -> None:
1734 (self.src,) = new
1735
1736 def accept(self, visitor: OpVisitor[T]) -> T:
1737 return visitor.visit_get_element(self)
1738
1739
1740 @final
1741 class GetElementPtr(RegisterOp):
1742 """Get the address of a struct element from a pointer to a struct.
1743
1744 If you have a struct value, use GetElement instead.
1745
1746 Note that you may need to use KeepAlive to avoid the struct
1747 being freed, if it's reference counted, such as PyObject *.
1748 """
1749
1750 error_kind = ERR_NEVER
1751
1752 def __init__(self, src: Value, src_type: RType, field: str, line: int = -1) -> None:
1753 super().__init__(line)
1754 assert not isinstance(src.type, (RStruct, RVec))
1755 self.type = pointer_rprimitive
1756 self.src = src
1757 self.src_type = src_type
1758 self.field = field
1759
1760 def sources(self) -> list[Value]:
1761 return [self.src]
1762
1763 def set_sources(self, new: list[Value]) -> None:
1764 (self.src,) = new
1765
1766 def accept(self, visitor: OpVisitor[T]) -> T:
1767 return visitor.visit_get_element_ptr(self)
1768
1769
1770 @final
1771 class SetElement(RegisterOp):
1772 """Set the value of a struct element.
1773
1774 This evaluates to a new struct with the changed value.
1775
1776 Use together with Undef to initialize a fresh struct value
1777 (see Undef for more details).
1778 """
1779
1780 error_kind = ERR_NEVER
1781
1782 def __init__(self, src: Value, field: str, item: Value, line: int = -1) -> None:
1783 super().__init__(line)
1784 assert isinstance(src.type, (RStruct, RVec)), src.type
1785 self.type = src.type
1786 self.src = src
1787 self.item = item
1788 self.field = field
1789
1790 def sources(self) -> list[Value]:
1791 return [self.src]
1792
1793 def set_sources(self, new: list[Value]) -> None:
1794 (self.src,) = new
1795
1796 def stolen(self) -> list[Value]:
1797 return [self.src]
1798
1799 def accept(self, visitor: OpVisitor[T]) -> T:
1800 return visitor.visit_set_element(self)
1801
1802
1803 @final
1804 class LoadAddress(RegisterOp):
1805 """Get the address of a value: result = (type)&src
1806
1807 Attributes:
1808 type: Type of the loaded address(e.g. ptr/object_ptr)
1809 src: Source value (str for globals like 'PyList_Type',
1810 Register for temporary values or locals, LoadStatic
1811 for statics.)
1812 """
1813
1814 error_kind = ERR_NEVER
1815 is_borrowed = True
1816
1817 def __init__(self, type: RType, src: str | Register | LoadStatic, line: int = -1) -> None:
1818 super().__init__(line)
1819 self.type = type
1820 self.src = src
1821
1822 def sources(self) -> list[Value]:
1823 if isinstance(self.src, Register):
1824 return [self.src]
1825 else:
1826 return []
1827
1828 def set_sources(self, new: list[Value]) -> None:
1829 if new:
1830 assert isinstance(new[0], Register)
1831 assert len(new) == 1
1832 self.src = new[0]
1833
1834 def accept(self, visitor: OpVisitor[T]) -> T:
1835 return visitor.visit_load_address(self)
1836
1837
1838 @final
1839 class KeepAlive(RegisterOp):
1840 """A no-op operation that ensures source values aren't freed.
1841
1842 This is sometimes useful to avoid decref when a reference is still
1843 being held but not seen by the compiler.
1844
1845 A typical use case is like this (C-like pseudocode):
1846
1847 ptr = &x.item
1848 r = *ptr
1849 keep_alive x # x must not be freed here
1850 # x may be freed here
1851
1852 If we didn't have "keep_alive x", x could be freed immediately
1853 after taking the address of 'item', resulting in a read after free
1854 on the second line.
1855
1856 If 'steal' is true, the value is considered to be stolen at
1857 this op, i.e. it won't be decref'd. You need to ensure that
1858 the value is freed otherwise, perhaps by using borrowing
1859 followed by Unborrow.
1860
1861 Be careful with steal=True -- this can cause memory leaks.
1862 """
1863
1864 error_kind = ERR_NEVER
1865
1866 def __init__(self, src: list[Value], line: int = -1, *, steal: bool = False) -> None:
1867 super().__init__(line)
1868 assert src
1869 self.src = src
1870 self.steal = steal
1871
1872 def sources(self) -> list[Value]:
1873 return self.src.copy()
1874
1875 def stolen(self) -> list[Value]:
1876 if self.steal:
1877 return self.src.copy()
1878 return []
1879
1880 def set_sources(self, new: list[Value]) -> None:
1881 self.src = new[:]
1882
1883 def accept(self, visitor: OpVisitor[T]) -> T:
1884 return visitor.visit_keep_alive(self)
1885
1886
1887 @final
1888 class Unborrow(RegisterOp):
1889 """A no-op op to create a regular reference from a borrowed one.
1890
1891 Borrowed references can only be used temporarily and the reference
1892 counts won't be managed. This value will be refcounted normally.
1893
1894 This is mainly useful if you split an aggregate value, such as
1895 a tuple, into components using borrowed values (to avoid increfs),
1896 and want to treat the components as sharing the original managed
1897 reference. You'll also need to use KeepAlive with steal=True to
1898 "consume" the original tuple reference:
1899
1900 # t is a 2-tuple
1901 r0 = borrow t[0]
1902 r1 = borrow t[1]
1903 keep_alive steal t
1904 r2 = unborrow r0
1905 r3 = unborrow r1
1906 # now (r2, r3) represent the tuple as separate items, that are
1907 # managed again. (Note we need to steal before unborrow, to avoid
1908 # refcount briefly touching zero if r2 or r3 are unused.)
1909
1910 Be careful with this -- this can easily cause double freeing.
1911 """
1912
1913 error_kind = ERR_NEVER
1914
1915 def __init__(self, src: Value, line: int = -1) -> None:
1916 super().__init__(line)
1917 assert src.is_borrowed
1918 self.src = src
1919 self.type = src.type
1920
1921 def sources(self) -> list[Value]:
1922 return [self.src]
1923
1924 def set_sources(self, new: list[Value]) -> None:
1925 (self.src,) = new
1926
1927 def stolen(self) -> list[Value]:
1928 return []
1929
1930 def accept(self, visitor: OpVisitor[T]) -> T:
1931 return visitor.visit_unborrow(self)
1932
1933
1934 @trait
1935 class OpVisitor(Generic[T]):
1936 """Generic visitor over ops (uses the visitor design pattern)."""
1937
1938 @abstractmethod
1939 def visit_goto(self, op: Goto) -> T:
1940 raise NotImplementedError
1941
1942 @abstractmethod
1943 def visit_branch(self, op: Branch) -> T:
1944 raise NotImplementedError
1945
1946 @abstractmethod
1947 def visit_return(self, op: Return) -> T:
1948 raise NotImplementedError
1949
1950 @abstractmethod
1951 def visit_unreachable(self, op: Unreachable) -> T:
1952 raise NotImplementedError
1953
1954 @abstractmethod
1955 def visit_assign(self, op: Assign) -> T:
1956 raise NotImplementedError
1957
1958 @abstractmethod
1959 def visit_assign_multi(self, op: AssignMulti) -> T:
1960 raise NotImplementedError
1961
1962 @abstractmethod
1963 def visit_load_error_value(self, op: LoadErrorValue) -> T:
1964 raise NotImplementedError
1965
1966 @abstractmethod
1967 def visit_load_literal(self, op: LoadLiteral) -> T:
1968 raise NotImplementedError
1969
1970 @abstractmethod
1971 def visit_get_attr(self, op: GetAttr) -> T:
1972 raise NotImplementedError
1973
1974 @abstractmethod
1975 def visit_set_attr(self, op: SetAttr) -> T:
1976 raise NotImplementedError
1977
1978 @abstractmethod
1979 def visit_load_static(self, op: LoadStatic) -> T:
1980 raise NotImplementedError
1981
1982 @abstractmethod
1983 def visit_init_static(self, op: InitStatic) -> T:
1984 raise NotImplementedError
1985
1986 @abstractmethod
1987 def visit_tuple_get(self, op: TupleGet) -> T:
1988 raise NotImplementedError
1989
1990 @abstractmethod
1991 def visit_tuple_set(self, op: TupleSet) -> T:
1992 raise NotImplementedError
1993
1994 def visit_inc_ref(self, op: IncRef) -> T:
1995 raise NotImplementedError
1996
1997 def visit_dec_ref(self, op: DecRef) -> T:
1998 raise NotImplementedError
1999
2000 @abstractmethod
2001 def visit_call(self, op: Call) -> T:
2002 raise NotImplementedError
2003
2004 @abstractmethod
2005 def visit_method_call(self, op: MethodCall) -> T:
2006 raise NotImplementedError
2007
2008 @abstractmethod
2009 def visit_cast(self, op: Cast) -> T:
2010 raise NotImplementedError
2011
2012 @abstractmethod
2013 def visit_box(self, op: Box) -> T:
2014 raise NotImplementedError
2015
2016 @abstractmethod
2017 def visit_unbox(self, op: Unbox) -> T:
2018 raise NotImplementedError
2019
2020 @abstractmethod
2021 def visit_raise_standard_error(self, op: RaiseStandardError) -> T:
2022 raise NotImplementedError
2023
2024 @abstractmethod
2025 def visit_call_c(self, op: CallC) -> T:
2026 raise NotImplementedError
2027
2028 @abstractmethod
2029 def visit_primitive_op(self, op: PrimitiveOp) -> T:
2030 raise NotImplementedError
2031
2032 @abstractmethod
2033 def visit_truncate(self, op: Truncate) -> T:
2034 raise NotImplementedError
2035
2036 @abstractmethod
2037 def visit_extend(self, op: Extend) -> T:
2038 raise NotImplementedError
2039
2040 @abstractmethod
2041 def visit_load_global(self, op: LoadGlobal) -> T:
2042 raise NotImplementedError
2043
2044 @abstractmethod
2045 def visit_int_op(self, op: IntOp) -> T:
2046 raise NotImplementedError
2047
2048 @abstractmethod
2049 def visit_comparison_op(self, op: ComparisonOp) -> T:
2050 raise NotImplementedError
2051
2052 @abstractmethod
2053 def visit_float_op(self, op: FloatOp) -> T:
2054 raise NotImplementedError
2055
2056 @abstractmethod
2057 def visit_float_neg(self, op: FloatNeg) -> T:
2058 raise NotImplementedError
2059
2060 @abstractmethod
2061 def visit_float_comparison_op(self, op: FloatComparisonOp) -> T:
2062 raise NotImplementedError
2063
2064 @abstractmethod
2065 def visit_load_mem(self, op: LoadMem) -> T:
2066 raise NotImplementedError
2067
2068 @abstractmethod
2069 def visit_set_mem(self, op: SetMem) -> T:
2070 raise NotImplementedError
2071
2072 @abstractmethod
2073 def visit_get_element(self, op: GetElement) -> T:
2074 raise NotImplementedError
2075
2076 @abstractmethod
2077 def visit_get_element_ptr(self, op: GetElementPtr) -> T:
2078 raise NotImplementedError
2079
2080 @abstractmethod
2081 def visit_set_element(self, op: SetElement) -> T:
2082 raise NotImplementedError
2083
2084 @abstractmethod
2085 def visit_load_address(self, op: LoadAddress) -> T:
2086 raise NotImplementedError
2087
2088 @abstractmethod
2089 def visit_keep_alive(self, op: KeepAlive) -> T:
2090 raise NotImplementedError
2091
2092 @abstractmethod
2093 def visit_unborrow(self, op: Unborrow) -> T:
2094 raise NotImplementedError
2095
2096
2097 # TODO: Should the following definition live somewhere else?
2098
2099
2100 # We do a three-pass deserialization scheme in order to resolve name
2101 # references.
2102 # 1. Create an empty ClassIR for each class in an SCC.
2103 # 2. Deserialize all of the functions, which can contain references
2104 # to ClassIRs in their types
2105 # 3. Deserialize all of the classes, which contain lots of references
2106 # to the functions they contain. (And to other classes.)
2107 #
2108 # Note that this approach differs from how we deserialize ASTs in mypy itself,
2109 # where everything is deserialized in one pass then a second pass cleans up
2110 # 'cross_refs'. We don't follow that approach here because it seems to be more
2111 # code for not a lot of gain since it is easy in mypyc to identify all the objects
2112 # we might need to reference.
2113 #
2114 # Because of these references, we need to maintain maps from class
2115 # names to ClassIRs and func IDs to FuncIRs.
2116 #
2117 # These are tracked in a DeserMaps which is passed to every
2118 # deserialization function.
2119 #
2120 # (Serialization and deserialization *will* be used for incremental
2121 # compilation but so far it is not hooked up to anything.)
2122 class DeserMaps(NamedTuple):
2123 classes: dict[str, ClassIR]
2124 functions: dict[str, FuncIR]