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