-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
Expand file tree
/
Copy pathops.py
More file actions
1642 lines (1210 loc) · 46.8 KB
/
ops.py
File metadata and controls
1642 lines (1210 loc) · 46.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Low-level opcodes for compiler intermediate representation (IR).
Opcodes operate on abstract values (Value) in a register machine. Each
value has a type (RType). A value can hold various things, such as:
- local variables (Register)
- intermediate values of expressions (RegisterOp subclasses)
- condition flags (true/false)
- literals (integer literals, True, False, etc.)
"""
from __future__ import annotations
from abc import abstractmethod
from typing import TYPE_CHECKING, Final, Generic, List, NamedTuple, Sequence, TypeVar, Union
from mypy_extensions import trait
from mypyc.ir.rtypes import (
RArray,
RInstance,
RTuple,
RType,
RVoid,
bit_rprimitive,
bool_rprimitive,
float_rprimitive,
int_rprimitive,
is_bit_rprimitive,
is_bool_rprimitive,
is_int_rprimitive,
is_none_rprimitive,
is_pointer_rprimitive,
is_short_int_rprimitive,
object_rprimitive,
pointer_rprimitive,
short_int_rprimitive,
void_rtype,
)
if TYPE_CHECKING:
from mypyc.codegen.literals import LiteralValue
from mypyc.ir.class_ir import ClassIR
from mypyc.ir.func_ir import FuncDecl, FuncIR
T = TypeVar("T")
class BasicBlock:
"""IR basic block.
Contains a sequence of Ops and ends with a ControlOp (Goto,
Branch, Return or Unreachable). Only the last op can be a
ControlOp.
All generated Ops live in basic blocks. Basic blocks determine the
order of evaluation and control flow within a function. A basic
block is always associated with a single function/method (FuncIR).
When building the IR, ops that raise exceptions can be included in
the middle of a basic block, but the exceptions aren't checked.
Afterwards we perform a transform that inserts explicit checks for
all error conditions and splits basic blocks accordingly to preserve
the invariant that a jump, branch or return can only ever appear
as the final op in a block. Manually inserting error checking ops
would be boring and error-prone.
BasicBlocks have an error_handler attribute that determines where
to jump if an error occurs. If none is specified, an error will
propagate up out of the function. This is compiled away by the
`exceptions` module.
Block labels are used for pretty printing and emitting C code, and
get filled in by those passes.
Ops that may terminate the program aren't treated as exits.
"""
def __init__(self, label: int = -1) -> None:
self.label = label
self.ops: list[Op] = []
self.error_handler: BasicBlock | None = None
self.referenced = False
@property
def terminated(self) -> bool:
"""Does the block end with a jump, branch or return?
This should always be true after the basic block has been fully built, but
this is false during construction.
"""
return bool(self.ops) and isinstance(self.ops[-1], ControlOp)
@property
def terminator(self) -> ControlOp:
"""The terminator operation of the block."""
assert bool(self.ops) and isinstance(self.ops[-1], ControlOp)
return self.ops[-1]
# Never generates an exception
ERR_NEVER: Final = 0
# Generates magic value (c_error_value) based on target RType on exception
ERR_MAGIC: Final = 1
# Generates false (bool) on exception
ERR_FALSE: Final = 2
# Always fails
ERR_ALWAYS: Final = 3
# Like ERR_MAGIC, but the magic return overlaps with a possible return value, and
# an extra PyErr_Occurred() check is also required
ERR_MAGIC_OVERLAPPING: Final = 4
# Hack: using this line number for an op will suppress it in tracebacks
NO_TRACEBACK_LINE_NO = -10000
class Value:
"""Abstract base class for all IR values.
These include references to registers, literals, and all
operations (Ops), such as assignments, calls and branches.
Values are often used as inputs of Ops. Register can be used as an
assignment target.
A Value is part of the IR being compiled if it's included in a BasicBlock
that is reachable from a FuncIR (i.e., is part of a function).
See also: Op is a subclass of Value that is the base class of all
operations.
"""
# Source line number (-1 for no/unknown line)
line = -1
# Type of the value or the result of the operation
type: RType = void_rtype
is_borrowed = False
@property
def is_void(self) -> bool:
return isinstance(self.type, RVoid)
class Register(Value):
"""A Register holds a value of a specific type, and it can be read and mutated.
A Register is always local to a function. Each local variable maps
to a Register, and they are also used for some (but not all)
temporary values.
Note that the term 'register' is overloaded and is sometimes used
to refer to arbitrary Values (for example, in RegisterOp).
"""
def __init__(self, type: RType, name: str = "", is_arg: bool = False, line: int = -1) -> None:
self.type = type
self.name = name
self.is_arg = is_arg
self.is_borrowed = is_arg
self.line = line
@property
def is_void(self) -> bool:
return False
def __repr__(self) -> str:
return f"<Register {self.name!r} at {hex(id(self))}>"
class Integer(Value):
"""Short integer literal.
Integer literals are treated as constant values and are generally
not included in data flow analyses and such, unlike Register and
Op subclasses.
Integer can represent multiple types:
* Short tagged integers (short_int_primitive type; the tag bit is clear)
* Ordinary fixed-width integers (e.g., int32_rprimitive)
* Values of other unboxed primitive types that are represented as integers
(none_rprimitive, bool_rprimitive)
* Null pointers (value 0) of various types, including object_rprimitive
"""
def __init__(self, value: int, rtype: RType = short_int_rprimitive, line: int = -1) -> None:
if is_short_int_rprimitive(rtype) or is_int_rprimitive(rtype):
self.value = value * 2
else:
self.value = value
self.type = rtype
self.line = line
def numeric_value(self) -> int:
if is_short_int_rprimitive(self.type) or is_int_rprimitive(self.type):
return self.value // 2
return self.value
class Float(Value):
"""Float literal.
Floating point literals are treated as constant values and are generally
not included in data flow analyses and such, unlike Register and
Op subclasses.
"""
def __init__(self, value: float, line: int = -1) -> None:
self.value = value
self.type = float_rprimitive
self.line = line
class Op(Value):
"""Abstract base class for all IR operations.
Each operation must be stored in a BasicBlock (in 'ops') to be
active in the IR. This is different from non-Op values, including
Register and Integer, where a reference from an active Op is
sufficient to be considered active.
In well-formed IR an active Op has no references to inactive ops
or ops used in another function.
"""
def __init__(self, line: int) -> None:
self.line = line
def can_raise(self) -> bool:
# Override this is if Op may raise an exception. Note that currently the fact that
# only RegisterOps may raise an exception in hard coded in some places.
return False
@abstractmethod
def sources(self) -> list[Value]:
"""All the values the op may read."""
def stolen(self) -> list[Value]:
"""Return arguments that have a reference count stolen by this op"""
return []
def unique_sources(self) -> list[Value]:
result: list[Value] = []
for reg in self.sources():
if reg not in result:
result.append(reg)
return result
@abstractmethod
def accept(self, visitor: OpVisitor[T]) -> T:
pass
class BaseAssign(Op):
"""Base class for ops that assign to a register."""
def __init__(self, dest: Register, line: int = -1) -> None:
super().__init__(line)
self.dest = dest
class Assign(BaseAssign):
"""Assign a value to a Register (dest = src)."""
error_kind = ERR_NEVER
def __init__(self, dest: Register, src: Value, line: int = -1) -> None:
super().__init__(dest, line)
self.src = src
def sources(self) -> list[Value]:
return [self.src]
def stolen(self) -> list[Value]:
return [self.src]
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_assign(self)
class AssignMulti(BaseAssign):
"""Assign multiple values to a Register (dest = src1, src2, ...).
This is used to initialize RArray values. It's provided to avoid
very verbose IR for common vectorcall operations.
Note that this interacts atypically with reference counting. We
assume that each RArray register is initialized exactly once
with this op.
"""
error_kind = ERR_NEVER
def __init__(self, dest: Register, src: list[Value], line: int = -1) -> None:
super().__init__(dest, line)
assert src
assert isinstance(dest.type, RArray)
assert dest.type.length == len(src)
self.src = src
def sources(self) -> list[Value]:
return self.src.copy()
def stolen(self) -> list[Value]:
return []
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_assign_multi(self)
class ControlOp(Op):
"""Control flow operation."""
def targets(self) -> Sequence[BasicBlock]:
"""Get all basic block targets of the control operation."""
return ()
def set_target(self, i: int, new: BasicBlock) -> None:
"""Update a basic block target."""
raise AssertionError(f"Invalid set_target({self}, {i})")
class Goto(ControlOp):
"""Unconditional jump."""
error_kind = ERR_NEVER
def __init__(self, label: BasicBlock, line: int = -1) -> None:
super().__init__(line)
self.label = label
def targets(self) -> Sequence[BasicBlock]:
return (self.label,)
def set_target(self, i: int, new: BasicBlock) -> None:
assert i == 0
self.label = new
def __repr__(self) -> str:
return "<Goto %s>" % self.label.label
def sources(self) -> list[Value]:
return []
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_goto(self)
class Branch(ControlOp):
"""Branch based on a value.
If op is BOOL, branch based on a bit/bool value:
if [not] r1 goto L1 else goto L2
If op is IS_ERROR, branch based on whether there is an error value:
if [not] is_error(r1) goto L1 else goto L2
"""
# Branch ops never raise an exception.
error_kind = ERR_NEVER
BOOL: Final = 100
IS_ERROR: Final = 101
def __init__(
self,
value: Value,
true_label: BasicBlock,
false_label: BasicBlock,
op: int,
line: int = -1,
*,
rare: bool = False,
) -> None:
super().__init__(line)
# Target value being checked
self.value = value
# Branch here if the condition is true
self.true = true_label
# Branch here if the condition is false
self.false = false_label
# Branch.BOOL (boolean check) or Branch.IS_ERROR (error value check)
self.op = op
# If True, the condition is negated
self.negated = False
# If not None, the true label should generate a traceback entry (func name, line number)
self.traceback_entry: tuple[str, int] | None = None
# If True, we expect to usually take the false branch (for optimization purposes);
# this is implicitly treated as true if there is a traceback entry
self.rare = rare
def targets(self) -> Sequence[BasicBlock]:
return (self.true, self.false)
def set_target(self, i: int, new: BasicBlock) -> None:
assert i == 0 or i == 1
if i == 0:
self.true = new
else:
self.false = new
def sources(self) -> list[Value]:
return [self.value]
def invert(self) -> None:
self.negated = not self.negated
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_branch(self)
class Return(ControlOp):
"""Return a value from a function."""
error_kind = ERR_NEVER
def __init__(self, value: Value, line: int = -1) -> None:
super().__init__(line)
self.value = value
def sources(self) -> list[Value]:
return [self.value]
def stolen(self) -> list[Value]:
return [self.value]
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_return(self)
class Unreachable(ControlOp):
"""Mark the end of basic block as unreachable.
This is sometimes necessary when the end of a basic block is never
reached. This can also be explicitly added to the end of non-None
returning functions (in None-returning function we can just return
None).
Mypy statically guarantees that the end of the function is not
unreachable if there is not a return statement.
This prevents the block formatter from being confused due to lack
of a leave and also leaves a nifty note in the IR. It is not
generally processed by visitors.
"""
error_kind = ERR_NEVER
def __init__(self, line: int = -1) -> None:
super().__init__(line)
def sources(self) -> list[Value]:
return []
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_unreachable(self)
class RegisterOp(Op):
"""Abstract base class for operations that can be written as r1 = f(r2, ..., rn).
Takes some values, performs an operation, and generates an output
(unless the 'type' attribute is void_rtype, which is the default).
Other ops can refer to the result of the Op by referring to the Op
instance. This doesn't do any explicit control flow, but can raise an
error.
Note that the operands can be arbitrary Values, not just Register
instances, even though the naming may suggest otherwise.
"""
error_kind = -1 # Can this raise exception and how is it signalled; one of ERR_*
_type: RType | None = None
def __init__(self, line: int) -> None:
super().__init__(line)
assert self.error_kind != -1, "error_kind not defined"
def can_raise(self) -> bool:
return self.error_kind != ERR_NEVER
class IncRef(RegisterOp):
"""Increase reference count (inc_ref src)."""
error_kind = ERR_NEVER
def __init__(self, src: Value, line: int = -1) -> None:
assert src.type.is_refcounted
super().__init__(line)
self.src = src
def sources(self) -> list[Value]:
return [self.src]
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_inc_ref(self)
class DecRef(RegisterOp):
"""Decrease reference count and free object if zero (dec_ref src).
The is_xdec flag says to use an XDECREF, which checks if the
pointer is NULL first.
"""
error_kind = ERR_NEVER
def __init__(self, src: Value, is_xdec: bool = False, line: int = -1) -> None:
assert src.type.is_refcounted
super().__init__(line)
self.src = src
self.is_xdec = is_xdec
def __repr__(self) -> str:
return "<{}DecRef {!r}>".format("X" if self.is_xdec else "", self.src)
def sources(self) -> list[Value]:
return [self.src]
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_dec_ref(self)
class Call(RegisterOp):
"""Native call f(arg, ...).
The call target can be a module-level function or a class.
"""
def __init__(self, fn: FuncDecl, args: Sequence[Value], line: int) -> None:
self.fn = fn
self.args = list(args)
assert len(self.args) == len(fn.sig.args)
self.type = fn.sig.ret_type
ret_type = fn.sig.ret_type
if not ret_type.error_overlap:
self.error_kind = ERR_MAGIC
else:
self.error_kind = ERR_MAGIC_OVERLAPPING
super().__init__(line)
def sources(self) -> list[Value]:
return list(self.args.copy())
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_call(self)
class MethodCall(RegisterOp):
"""Native method call obj.method(arg, ...)"""
def __init__(self, obj: Value, method: str, args: list[Value], line: int = -1) -> None:
self.obj = obj
self.method = method
self.args = args
assert isinstance(obj.type, RInstance), "Methods can only be called on instances"
self.receiver_type = obj.type
method_ir = self.receiver_type.class_ir.method_sig(method)
assert method_ir is not None, "{} doesn't have method {}".format(
self.receiver_type.name, method
)
ret_type = method_ir.ret_type
self.type = ret_type
if not ret_type.error_overlap:
self.error_kind = ERR_MAGIC
else:
self.error_kind = ERR_MAGIC_OVERLAPPING
super().__init__(line)
def sources(self) -> list[Value]:
return self.args.copy() + [self.obj]
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_method_call(self)
class LoadErrorValue(RegisterOp):
"""Load an error value.
Each type has one reserved value that signals an error (exception). This
loads the error value for a specific type.
"""
error_kind = ERR_NEVER
def __init__(
self, rtype: RType, line: int = -1, is_borrowed: bool = False, undefines: bool = False
) -> None:
super().__init__(line)
self.type = rtype
self.is_borrowed = is_borrowed
# Undefines is true if this should viewed by the definedness
# analysis pass as making the register it is assigned to
# undefined (and thus checks should be added on uses).
self.undefines = undefines
def sources(self) -> list[Value]:
return []
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_load_error_value(self)
class LoadLiteral(RegisterOp):
"""Load a Python literal object (dest = 'foo' / b'foo' / ...).
This is used to load a static PyObject * value corresponding to
a literal of one of the supported types.
Tuple / frozenset literals must contain only valid literal values as items.
NOTE: You can use this to load boxed (Python) int objects. Use
Integer to load unboxed, tagged integers or fixed-width,
low-level integers.
For int literals, both int_rprimitive (CPyTagged) and
object_primitive (PyObject *) are supported as rtype. However,
when using int_rprimitive, the value must *not* be small enough
to fit in an unboxed integer.
"""
error_kind = ERR_NEVER
is_borrowed = True
def __init__(self, value: LiteralValue, rtype: RType) -> None:
self.value = value
self.type = rtype
def sources(self) -> list[Value]:
return []
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_load_literal(self)
class GetAttr(RegisterOp):
"""obj.attr (for a native object)"""
error_kind = ERR_MAGIC
def __init__(self, obj: Value, attr: str, line: int, *, borrow: bool = False) -> None:
super().__init__(line)
self.obj = obj
self.attr = attr
assert isinstance(obj.type, RInstance), "Attribute access not supported: %s" % obj.type
self.class_type = obj.type
attr_type = obj.type.attr_type(attr)
self.type = attr_type
if attr_type.error_overlap:
self.error_kind = ERR_MAGIC_OVERLAPPING
self.is_borrowed = borrow and attr_type.is_refcounted
def sources(self) -> list[Value]:
return [self.obj]
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_get_attr(self)
class SetAttr(RegisterOp):
"""obj.attr = src (for a native object)
Steals the reference to src.
"""
error_kind = ERR_FALSE
def __init__(self, obj: Value, attr: str, src: Value, line: int) -> None:
super().__init__(line)
self.obj = obj
self.attr = attr
self.src = src
assert isinstance(obj.type, RInstance), "Attribute access not supported: %s" % obj.type
self.class_type = obj.type
self.type = bool_rprimitive
# If True, we can safely assume that the attribute is previously undefined
# and we don't use a setter
self.is_init = False
def mark_as_initializer(self) -> None:
self.is_init = True
self.error_kind = ERR_NEVER
self.type = void_rtype
def sources(self) -> list[Value]:
return [self.obj, self.src]
def stolen(self) -> list[Value]:
return [self.src]
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_set_attr(self)
# Default name space for statics, variables
NAMESPACE_STATIC: Final = "static"
# Static namespace for pointers to native type objects
NAMESPACE_TYPE: Final = "type"
# Namespace for modules
NAMESPACE_MODULE: Final = "module"
class LoadStatic(RegisterOp):
"""Load a static name (name :: static).
Load a C static variable/pointer. The namespace for statics is shared
for the entire compilation group. You can optionally provide a module
name and a sub-namespace identifier for additional namespacing to avoid
name conflicts. The static namespace does not overlap with other C names,
since the final C name will get a prefix, so conflicts only must be
avoided with other statics.
"""
error_kind = ERR_NEVER
is_borrowed = True
def __init__(
self,
type: RType,
identifier: str,
module_name: str | None = None,
namespace: str = NAMESPACE_STATIC,
line: int = -1,
ann: object = None,
) -> None:
super().__init__(line)
self.identifier = identifier
self.module_name = module_name
self.namespace = namespace
self.type = type
self.ann = ann # An object to pretty print with the load
def sources(self) -> list[Value]:
return []
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_load_static(self)
class InitStatic(RegisterOp):
"""static = value :: static
Initialize a C static variable/pointer. See everything in LoadStatic.
"""
error_kind = ERR_NEVER
def __init__(
self,
value: Value,
identifier: str,
module_name: str | None = None,
namespace: str = NAMESPACE_STATIC,
line: int = -1,
) -> None:
super().__init__(line)
self.identifier = identifier
self.module_name = module_name
self.namespace = namespace
self.value = value
def sources(self) -> list[Value]:
return [self.value]
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_init_static(self)
class TupleSet(RegisterOp):
"""dest = (reg, ...) (for fixed-length tuple)"""
error_kind = ERR_NEVER
def __init__(self, items: list[Value], line: int) -> None:
super().__init__(line)
self.items = items
# Don't keep track of the fact that an int is short after it
# is put into a tuple, since we don't properly implement
# runtime subtyping for tuples.
self.tuple_type = RTuple(
[
arg.type if not is_short_int_rprimitive(arg.type) else int_rprimitive
for arg in items
]
)
self.type = self.tuple_type
def sources(self) -> list[Value]:
return self.items.copy()
def stolen(self) -> list[Value]:
return self.items.copy()
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_tuple_set(self)
class TupleGet(RegisterOp):
"""Get item of a fixed-length tuple (src[index])."""
error_kind = ERR_NEVER
def __init__(self, src: Value, index: int, line: int = -1, *, borrow: bool = False) -> None:
super().__init__(line)
self.src = src
self.index = index
assert isinstance(src.type, RTuple), "TupleGet only operates on tuples"
assert index >= 0
self.type = src.type.types[index]
self.is_borrowed = borrow
def sources(self) -> list[Value]:
return [self.src]
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_tuple_get(self)
class Cast(RegisterOp):
"""cast(type, src)
Perform a runtime type check (no representation or value conversion).
DO NOT increment reference counts.
"""
error_kind = ERR_MAGIC
def __init__(self, src: Value, typ: RType, line: int, *, borrow: bool = False) -> None:
super().__init__(line)
self.src = src
self.type = typ
self.is_borrowed = borrow
def sources(self) -> list[Value]:
return [self.src]
def stolen(self) -> list[Value]:
if self.is_borrowed:
return []
return [self.src]
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_cast(self)
class Box(RegisterOp):
"""box(type, src)
This converts from a potentially unboxed representation to a straight Python object.
Only supported for types with an unboxed representation.
"""
error_kind = ERR_NEVER
def __init__(self, src: Value, line: int = -1) -> None:
super().__init__(line)
self.src = src
self.type = object_rprimitive
# When we box None and bool values, we produce a borrowed result
if (
is_none_rprimitive(self.src.type)
or is_bool_rprimitive(self.src.type)
or is_bit_rprimitive(self.src.type)
):
self.is_borrowed = True
def sources(self) -> list[Value]:
return [self.src]
def stolen(self) -> list[Value]:
return [self.src]
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_box(self)
class Unbox(RegisterOp):
"""unbox(type, src)
This is similar to a cast, but it also changes to a (potentially) unboxed runtime
representation. Only supported for types with an unboxed representation.
"""
def __init__(self, src: Value, typ: RType, line: int) -> None:
self.src = src
self.type = typ
if not typ.error_overlap:
self.error_kind = ERR_MAGIC
else:
self.error_kind = ERR_MAGIC_OVERLAPPING
super().__init__(line)
def sources(self) -> list[Value]:
return [self.src]
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_unbox(self)
class RaiseStandardError(RegisterOp):
"""Raise built-in exception with an optional error string.
We have a separate opcode for this for convenience and to
generate smaller, more idiomatic C code.
"""
# TODO: Make it more explicit at IR level that this always raises
error_kind = ERR_FALSE
VALUE_ERROR: Final = "ValueError"
ASSERTION_ERROR: Final = "AssertionError"
STOP_ITERATION: Final = "StopIteration"
UNBOUND_LOCAL_ERROR: Final = "UnboundLocalError"
RUNTIME_ERROR: Final = "RuntimeError"
NAME_ERROR: Final = "NameError"
ZERO_DIVISION_ERROR: Final = "ZeroDivisionError"
def __init__(self, class_name: str, value: str | Value | None, line: int) -> None:
super().__init__(line)
self.class_name = class_name
self.value = value
self.type = bool_rprimitive
def sources(self) -> list[Value]:
return []
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_raise_standard_error(self)
# True steals all arguments, False steals none, a list steals those in matching positions
StealsDescription = Union[bool, List[bool]]
class CallC(RegisterOp):
"""result = function(arg0, arg1, ...)
Call a C function that is not a compiled/native function (for
example, a Python C API function). Use Call to call native
functions.
"""
def __init__(
self,
function_name: str,
args: list[Value],
ret_type: RType,
steals: StealsDescription,
is_borrowed: bool,
error_kind: int,
line: int,
var_arg_idx: int = -1,
) -> None:
self.error_kind = error_kind
super().__init__(line)
self.function_name = function_name
self.args = args
self.type = ret_type
self.steals = steals
self.is_borrowed = is_borrowed
# The position of the first variable argument in args (if >= 0)
self.var_arg_idx = var_arg_idx
def sources(self) -> list[Value]:
return self.args
def stolen(self) -> list[Value]:
if isinstance(self.steals, list):
assert len(self.steals) == len(self.args)
return [arg for arg, steal in zip(self.args, self.steals) if steal]
else:
return [] if not self.steals else self.sources()
def accept(self, visitor: OpVisitor[T]) -> T:
return visitor.visit_call_c(self)
class Truncate(RegisterOp):
"""result = truncate src from src_type to dst_type
Truncate a value from type with more bits to type with less bits.
dst_type and src_type can be native integer types, bools or tagged
integers. Tagged integers should have the tag bit unset.
"""
error_kind = ERR_NEVER
def __init__(self, src: Value, dst_type: RType, line: int = -1) -> None:
super().__init__(line)
self.src = src
self.type = dst_type
self.src_type = src.type