/
ll_builder.py
2115 lines (1882 loc) · 84.9 KB
/
ll_builder.py
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
"""A "low-level" IR builder class.
LowLevelIRBuilder provides core abstractions we use for constructing
IR as well as a number of higher-level ones (accessing attributes,
calling functions and methods, and coercing between types, for
example). The core principle of the low-level IR builder is that all
of its facilities operate solely on the IR level and not the AST
level---it has *no knowledge* of mypy types or expressions.
"""
from __future__ import annotations
from typing import Callable, Optional, Sequence, Tuple
from typing_extensions import Final
from mypy.argmap import map_actuals_to_formals
from mypy.nodes import ARG_POS, ARG_STAR, ARG_STAR2, ArgKind
from mypy.operators import op_methods
from mypy.types import AnyType, TypeOfAny
from mypyc.common import (
BITMAP_BITS,
FAST_ISINSTANCE_MAX_SUBCLASSES,
MAX_LITERAL_SHORT_INT,
MAX_SHORT_INT,
MIN_LITERAL_SHORT_INT,
MIN_SHORT_INT,
PLATFORM_SIZE,
use_method_vectorcall,
use_vectorcall,
)
from mypyc.ir.class_ir import ClassIR, all_concrete_classes
from mypyc.ir.func_ir import FuncDecl, FuncSignature
from mypyc.ir.ops import (
ERR_FALSE,
ERR_NEVER,
NAMESPACE_MODULE,
NAMESPACE_STATIC,
NAMESPACE_TYPE,
Assign,
AssignMulti,
BasicBlock,
Box,
Branch,
Call,
CallC,
Cast,
ComparisonOp,
Extend,
GetAttr,
GetElementPtr,
Goto,
Integer,
IntOp,
KeepAlive,
LoadAddress,
LoadErrorValue,
LoadLiteral,
LoadMem,
LoadStatic,
MethodCall,
Op,
RaiseStandardError,
Register,
SetMem,
Truncate,
TupleGet,
Unbox,
Unreachable,
Value,
int_op_to_id,
)
from mypyc.ir.rtypes import (
PyListObject,
PyObject,
PySetObject,
PyVarObject,
RArray,
RInstance,
RPrimitive,
RTuple,
RType,
RUnion,
bit_rprimitive,
bitmap_rprimitive,
bool_rprimitive,
bytes_rprimitive,
c_int_rprimitive,
c_pointer_rprimitive,
c_pyssize_t_rprimitive,
c_size_t_rprimitive,
dict_rprimitive,
float_rprimitive,
int_rprimitive,
is_bit_rprimitive,
is_bool_rprimitive,
is_bytes_rprimitive,
is_dict_rprimitive,
is_fixed_width_rtype,
is_int32_rprimitive,
is_int64_rprimitive,
is_int_rprimitive,
is_list_rprimitive,
is_none_rprimitive,
is_set_rprimitive,
is_short_int_rprimitive,
is_str_rprimitive,
is_tagged,
is_tuple_rprimitive,
list_rprimitive,
none_rprimitive,
object_pointer_rprimitive,
object_rprimitive,
optional_value_type,
pointer_rprimitive,
short_int_rprimitive,
str_rprimitive,
)
from mypyc.irbuild.mapper import Mapper
from mypyc.irbuild.util import concrete_arg_kind
from mypyc.options import CompilerOptions
from mypyc.primitives.bytes_ops import bytes_compare
from mypyc.primitives.dict_ops import (
dict_build_op,
dict_new_op,
dict_ssize_t_size_op,
dict_update_in_display_op,
)
from mypyc.primitives.exc_ops import err_occurred_op, keep_propagating_op
from mypyc.primitives.generic_ops import (
generic_len_op,
generic_ssize_t_len_op,
py_call_op,
py_call_with_kwargs_op,
py_getattr_op,
py_method_call_op,
py_vectorcall_method_op,
py_vectorcall_op,
)
from mypyc.primitives.int_ops import (
int32_divide_op,
int32_mod_op,
int32_overflow,
int64_divide_op,
int64_mod_op,
int64_to_int_op,
int_comparison_op_mapping,
int_to_int32_op,
int_to_int64_op,
ssize_t_to_int_op,
)
from mypyc.primitives.list_ops import list_build_op, list_extend_op, new_list_op
from mypyc.primitives.misc_ops import bool_op, fast_isinstance_op, none_object_op
from mypyc.primitives.registry import (
ERR_NEG_INT,
CFunctionDescription,
binary_ops,
method_call_ops,
unary_ops,
)
from mypyc.primitives.set_ops import new_set_op
from mypyc.primitives.str_ops import str_check_if_true, str_ssize_t_size_op, unicode_compare
from mypyc.primitives.tuple_ops import list_tuple_op, new_tuple_op, new_tuple_with_length_op
from mypyc.rt_subtype import is_runtime_subtype
from mypyc.sametype import is_same_type
from mypyc.subtype import is_subtype
DictEntry = Tuple[Optional[Value], Value]
# If the number of items is less than the threshold when initializing
# a list, we would inline the generate IR using SetMem and expanded
# for-loop. Otherwise, we would call `list_build_op` for larger lists.
# TODO: The threshold is a randomly chosen number which needs further
# study on real-world projects for a better balance.
LIST_BUILDING_EXPANSION_THRESHOLD = 10
# From CPython
PY_VECTORCALL_ARGUMENTS_OFFSET: Final = 1 << (PLATFORM_SIZE * 8 - 1)
FIXED_WIDTH_INT_BINARY_OPS: Final = {
"+",
"-",
"*",
"//",
"%",
"&",
"|",
"^",
"<<",
">>",
"+=",
"-=",
"*=",
"//=",
"%=",
"&=",
"|=",
"^=",
"<<=",
">>=",
}
class LowLevelIRBuilder:
def __init__(self, current_module: str, mapper: Mapper, options: CompilerOptions) -> None:
self.current_module = current_module
self.mapper = mapper
self.options = options
self.args: list[Register] = []
self.blocks: list[BasicBlock] = []
# Stack of except handler entry blocks
self.error_handlers: list[BasicBlock | None] = [None]
# Values that we need to keep alive as long as we have borrowed
# temporaries. Use flush_keep_alives() to mark the end of the live range.
self.keep_alives: list[Value] = []
# Basic operations
def add(self, op: Op) -> Value:
"""Add an op."""
assert not self.blocks[-1].terminated, "Can't add to finished block"
self.blocks[-1].ops.append(op)
return op
def goto(self, target: BasicBlock) -> None:
"""Add goto to a basic block."""
if not self.blocks[-1].terminated:
self.add(Goto(target))
def activate_block(self, block: BasicBlock) -> None:
"""Add a basic block and make it the active one (target of adds)."""
if self.blocks:
assert self.blocks[-1].terminated
block.error_handler = self.error_handlers[-1]
self.blocks.append(block)
def goto_and_activate(self, block: BasicBlock) -> None:
"""Add goto a block and make it the active block."""
self.goto(block)
self.activate_block(block)
def push_error_handler(self, handler: BasicBlock | None) -> None:
self.error_handlers.append(handler)
def pop_error_handler(self) -> BasicBlock | None:
return self.error_handlers.pop()
def self(self) -> Register:
"""Return reference to the 'self' argument.
This only works in a method.
"""
return self.args[0]
def flush_keep_alives(self) -> None:
if self.keep_alives:
self.add(KeepAlive(self.keep_alives[:]))
self.keep_alives = []
# Type conversions
def box(self, src: Value) -> Value:
if src.type.is_unboxed:
if isinstance(src, Integer) and is_tagged(src.type):
return self.add(LoadLiteral(src.value >> 1, rtype=object_rprimitive))
return self.add(Box(src))
else:
return src
def unbox_or_cast(
self, src: Value, target_type: RType, line: int, *, can_borrow: bool = False
) -> Value:
if target_type.is_unboxed:
return self.add(Unbox(src, target_type, line))
else:
if can_borrow:
self.keep_alives.append(src)
return self.add(Cast(src, target_type, line, borrow=can_borrow))
def coerce(
self,
src: Value,
target_type: RType,
line: int,
force: bool = False,
*,
can_borrow: bool = False,
) -> Value:
"""Generate a coercion/cast from one type to other (only if needed).
For example, int -> object boxes the source int; int -> int emits nothing;
object -> int unboxes the object. All conversions preserve object value.
If force is true, always generate an op (even if it is just an assignment) so
that the result will have exactly target_type as the type.
Returns the register with the converted value (may be same as src).
"""
src_type = src.type
if src_type.is_unboxed and not target_type.is_unboxed:
# Unboxed -> boxed
return self.box(src)
if (src_type.is_unboxed and target_type.is_unboxed) and not is_runtime_subtype(
src_type, target_type
):
if (
isinstance(src, Integer)
and is_short_int_rprimitive(src_type)
and is_fixed_width_rtype(target_type)
):
# TODO: range check
return Integer(src.value >> 1, target_type)
elif is_int_rprimitive(src_type) and is_fixed_width_rtype(target_type):
return self.coerce_int_to_fixed_width(src, target_type, line)
elif is_fixed_width_rtype(src_type) and is_int_rprimitive(target_type):
return self.coerce_fixed_width_to_int(src, line)
elif is_short_int_rprimitive(src_type) and is_fixed_width_rtype(target_type):
return self.coerce_short_int_to_fixed_width(src, target_type, line)
elif (
isinstance(src_type, RPrimitive)
and isinstance(target_type, RPrimitive)
and src_type.is_native_int
and target_type.is_native_int
and src_type.size == target_type.size
and src_type.is_signed == target_type.is_signed
):
# Equivalent types
return src
else:
# To go from one unboxed type to another, we go through a boxed
# in-between value, for simplicity.
tmp = self.box(src)
return self.unbox_or_cast(tmp, target_type, line)
if (not src_type.is_unboxed and target_type.is_unboxed) or not is_subtype(
src_type, target_type
):
return self.unbox_or_cast(src, target_type, line, can_borrow=can_borrow)
elif force:
tmp = Register(target_type)
self.add(Assign(tmp, src))
return tmp
return src
def coerce_int_to_fixed_width(self, src: Value, target_type: RType, line: int) -> Value:
assert is_fixed_width_rtype(target_type), target_type
assert isinstance(target_type, RPrimitive)
res = Register(target_type)
fast, slow, end = BasicBlock(), BasicBlock(), BasicBlock()
check = self.check_tagged_short_int(src, line)
self.add(Branch(check, fast, slow, Branch.BOOL))
self.activate_block(fast)
size = target_type.size
if size < int_rprimitive.size:
# Add a range check when the target type is smaller than the source tyoe
fast2, fast3 = BasicBlock(), BasicBlock()
upper_bound = 1 << (size * 8 - 1)
check2 = self.add(ComparisonOp(src, Integer(upper_bound, src.type), ComparisonOp.SLT))
self.add(Branch(check2, fast2, slow, Branch.BOOL))
self.activate_block(fast2)
check3 = self.add(ComparisonOp(src, Integer(-upper_bound, src.type), ComparisonOp.SGE))
self.add(Branch(check3, fast3, slow, Branch.BOOL))
self.activate_block(fast3)
tmp = self.int_op(
c_pyssize_t_rprimitive,
src,
Integer(1, c_pyssize_t_rprimitive),
IntOp.RIGHT_SHIFT,
line,
)
tmp = self.add(Truncate(tmp, target_type))
else:
if size > int_rprimitive.size:
tmp = self.add(Extend(src, target_type, signed=True))
else:
tmp = src
tmp = self.int_op(target_type, tmp, Integer(1, target_type), IntOp.RIGHT_SHIFT, line)
self.add(Assign(res, tmp))
self.goto(end)
self.activate_block(slow)
if is_int64_rprimitive(target_type) or (
is_int32_rprimitive(target_type) and size == int_rprimitive.size
):
# Slow path calls a library function that handles more complex logic
ptr = self.int_op(
pointer_rprimitive, src, Integer(1, pointer_rprimitive), IntOp.XOR, line
)
ptr2 = Register(c_pointer_rprimitive)
self.add(Assign(ptr2, ptr))
if is_int64_rprimitive(target_type):
conv_op = int_to_int64_op
else:
conv_op = int_to_int32_op
tmp = self.call_c(conv_op, [ptr2], line)
self.add(Assign(res, tmp))
self.add(KeepAlive([src]))
self.goto(end)
elif is_int32_rprimitive(target_type):
# Slow path just always generates an OverflowError
self.call_c(int32_overflow, [], line)
self.add(Unreachable())
else:
assert False, target_type
self.activate_block(end)
return res
def coerce_short_int_to_fixed_width(self, src: Value, target_type: RType, line: int) -> Value:
if is_int64_rprimitive(target_type):
return self.int_op(target_type, src, Integer(1, target_type), IntOp.RIGHT_SHIFT, line)
# TODO: i32
assert False, (src.type, target_type)
def coerce_fixed_width_to_int(self, src: Value, line: int) -> Value:
if is_int32_rprimitive(src.type) and PLATFORM_SIZE == 8:
# Simple case -- just sign extend and shift.
extended = self.add(Extend(src, c_pyssize_t_rprimitive, signed=True))
return self.int_op(
int_rprimitive,
extended,
Integer(1, c_pyssize_t_rprimitive),
IntOp.LEFT_SHIFT,
line,
)
assert is_fixed_width_rtype(src.type)
assert isinstance(src.type, RPrimitive)
src_type = src.type
res = Register(int_rprimitive)
fast, fast2, slow, end = BasicBlock(), BasicBlock(), BasicBlock(), BasicBlock()
c1 = self.add(ComparisonOp(src, Integer(MAX_SHORT_INT, src_type), ComparisonOp.SLE))
self.add(Branch(c1, fast, slow, Branch.BOOL))
self.activate_block(fast)
c2 = self.add(ComparisonOp(src, Integer(MIN_SHORT_INT, src_type), ComparisonOp.SGE))
self.add(Branch(c2, fast2, slow, Branch.BOOL))
self.activate_block(slow)
if is_int64_rprimitive(src_type):
conv_op = int64_to_int_op
elif is_int32_rprimitive(src_type):
assert PLATFORM_SIZE == 4
conv_op = ssize_t_to_int_op
else:
assert False, src_type
x = self.call_c(conv_op, [src], line)
self.add(Assign(res, x))
self.goto(end)
self.activate_block(fast2)
if int_rprimitive.size < src_type.size:
tmp = self.add(Truncate(src, c_pyssize_t_rprimitive))
else:
tmp = src
s = self.int_op(int_rprimitive, tmp, Integer(1, tmp.type), IntOp.LEFT_SHIFT, line)
self.add(Assign(res, s))
self.goto(end)
self.activate_block(end)
return res
def coerce_nullable(self, src: Value, target_type: RType, line: int) -> Value:
"""Generate a coercion from a potentially null value."""
if src.type.is_unboxed == target_type.is_unboxed and (
(target_type.is_unboxed and is_runtime_subtype(src.type, target_type))
or (not target_type.is_unboxed and is_subtype(src.type, target_type))
):
return src
target = Register(target_type)
valid, invalid, out = BasicBlock(), BasicBlock(), BasicBlock()
self.add(Branch(src, invalid, valid, Branch.IS_ERROR))
self.activate_block(valid)
coerced = self.coerce(src, target_type, line)
self.add(Assign(target, coerced, line))
self.goto(out)
self.activate_block(invalid)
error = self.add(LoadErrorValue(target_type))
self.add(Assign(target, error, line))
self.goto_and_activate(out)
return target
# Attribute access
def get_attr(
self, obj: Value, attr: str, result_type: RType, line: int, *, borrow: bool = False
) -> Value:
"""Get a native or Python attribute of an object."""
if (
isinstance(obj.type, RInstance)
and obj.type.class_ir.is_ext_class
and obj.type.class_ir.has_attr(attr)
):
op = GetAttr(obj, attr, line, borrow=borrow)
# For non-refcounted attribute types, the borrow might be
# disabled even if requested, so don't check 'borrow'.
if op.is_borrowed:
self.keep_alives.append(obj)
return self.add(op)
elif isinstance(obj.type, RUnion):
return self.union_get_attr(obj, obj.type, attr, result_type, line)
else:
return self.py_get_attr(obj, attr, line)
def union_get_attr(
self, obj: Value, rtype: RUnion, attr: str, result_type: RType, line: int
) -> Value:
"""Get an attribute of an object with a union type."""
def get_item_attr(value: Value) -> Value:
return self.get_attr(value, attr, result_type, line)
return self.decompose_union_helper(obj, rtype, result_type, get_item_attr, line)
def py_get_attr(self, obj: Value, attr: str, line: int) -> Value:
"""Get a Python attribute (slow).
Prefer get_attr() which generates optimized code for native classes.
"""
key = self.load_str(attr)
return self.call_c(py_getattr_op, [obj, key], line)
# isinstance() checks
def isinstance_helper(self, obj: Value, class_irs: list[ClassIR], line: int) -> Value:
"""Fast path for isinstance() that checks against a list of native classes."""
if not class_irs:
return self.false()
ret = self.isinstance_native(obj, class_irs[0], line)
for class_ir in class_irs[1:]:
def other() -> Value:
return self.isinstance_native(obj, class_ir, line)
ret = self.shortcircuit_helper("or", bool_rprimitive, lambda: ret, other, line)
return ret
def get_type_of_obj(self, obj: Value, line: int) -> Value:
ob_type_address = self.add(GetElementPtr(obj, PyObject, "ob_type", line))
ob_type = self.add(LoadMem(object_rprimitive, ob_type_address))
self.add(KeepAlive([obj]))
return ob_type
def type_is_op(self, obj: Value, type_obj: Value, line: int) -> Value:
typ = self.get_type_of_obj(obj, line)
return self.add(ComparisonOp(typ, type_obj, ComparisonOp.EQ, line))
def isinstance_native(self, obj: Value, class_ir: ClassIR, line: int) -> Value:
"""Fast isinstance() check for a native class.
If there are three or fewer concrete (non-trait) classes among the class
and all its children, use even faster type comparison checks `type(obj)
is typ`.
"""
concrete = all_concrete_classes(class_ir)
if concrete is None or len(concrete) > FAST_ISINSTANCE_MAX_SUBCLASSES + 1:
return self.call_c(fast_isinstance_op, [obj, self.get_native_type(class_ir)], line)
if not concrete:
# There can't be any concrete instance that matches this.
return self.false()
type_obj = self.get_native_type(concrete[0])
ret = self.type_is_op(obj, type_obj, line)
for c in concrete[1:]:
def other() -> Value:
return self.type_is_op(obj, self.get_native_type(c), line)
ret = self.shortcircuit_helper("or", bool_rprimitive, lambda: ret, other, line)
return ret
# Calls
def _construct_varargs(
self,
args: Sequence[tuple[Value, ArgKind, str | None]],
line: int,
*,
has_star: bool,
has_star2: bool,
) -> tuple[Value | None, Value | None]:
"""Construct *args and **kwargs from a collection of arguments
This is pretty complicated, and almost all of the complication here stems from
one of two things (but mostly the second):
* The handling of ARG_STAR/ARG_STAR2. We want to create as much of the args/kwargs
values in one go as we can, so we collect values until our hand is forced, and
then we emit creation of the list/tuple, and expand it from there if needed.
* Support potentially nullable argument values. This has very narrow applicability,
as this will never be done by our compiled Python code, but is critically used
by gen_glue_method when generating glue methods to mediate between the function
signature of a parent class and its subclasses.
For named-only arguments, this is quite simple: if it is
null, don't put it in the dict.
For positional-or-named arguments, things are much more complicated.
* First, anything that was passed as a positional arg
must be forwarded along as a positional arg. It *must
not* be converted to a named arg. This is because mypy
does not enforce that positional-or-named arguments
have the same name in subclasses, and it is not
uncommon for code to have different names in
subclasses (a bunch of mypy's visitors do this, for
example!). This is arguably a bug in both mypy and code doing
this, and they ought to be using positional-only arguments, but
positional-only arguments are new and ugly.
* On the flip side, we're willing to accept the
infelicity of sometimes turning an argument that was
passed by keyword into a positional argument. It's wrong,
but it's very marginal, and avoiding it would require passing
a bitmask of which arguments were named with every function call,
or something similar.
(See some discussion of this in testComplicatedArgs)
Thus, our strategy for positional-or-named arguments is to
always pass them as positional, except in the one
situation where we can not, and where we can be absolutely
sure they were passed by name: when an *earlier*
positional argument was missing its value.
This means that if we have a method `f(self, x: int=..., y: object=...)`:
* x and y present: args=(x, y), kwargs={}
* x present, y missing: args=(x,), kwargs={}
* x missing, y present: args=(), kwargs={'y': y}
To implement this, when we have multiple optional
positional arguments, we maintain a flag in a register
that tracks whether an argument has been missing, and for
each such optional argument (except the first), we check
the flag to determine whether to append the argument to
the *args list or add it to the **kwargs dict. What a
mess!
This is what really makes everything here such a tangle;
otherwise the *args and **kwargs code could be separated.
The arguments has_star and has_star2 indicate whether the target function
takes an ARG_STAR and ARG_STAR2 argument, respectively.
(These will always be true when making a pycall, and be based
on the actual target signature for a native call.)
"""
star_result: Value | None = None
star2_result: Value | None = None
# We aggregate values that need to go into *args and **kwargs
# in these lists. Once all arguments are processed (in the
# happiest case), or we encounter an ARG_STAR/ARG_STAR2 or a
# nullable arg, then we create the list and/or dict.
star_values: list[Value] = []
star2_keys: list[Value] = []
star2_values: list[Value] = []
seen_empty_reg: Register | None = None
for value, kind, name in args:
if kind == ARG_STAR:
if star_result is None:
star_result = self.new_list_op(star_values, line)
self.call_c(list_extend_op, [star_result, value], line)
elif kind == ARG_STAR2:
if star2_result is None:
star2_result = self._create_dict(star2_keys, star2_values, line)
self.call_c(dict_update_in_display_op, [star2_result, value], line=line)
else:
nullable = kind.is_optional()
maybe_pos = kind.is_positional() and has_star
maybe_named = kind.is_named() or (kind.is_optional() and name and has_star2)
# If the argument is nullable, we need to create the
# relevant args/kwargs objects so that we can
# conditionally modify them.
if nullable:
if maybe_pos and star_result is None:
star_result = self.new_list_op(star_values, line)
if maybe_named and star2_result is None:
star2_result = self._create_dict(star2_keys, star2_values, line)
# Easy cases: just collect the argument.
if maybe_pos and star_result is None:
star_values.append(value)
continue
if maybe_named and star2_result is None:
assert name is not None
key = self.load_str(name)
star2_keys.append(key)
star2_values.append(value)
continue
# OK, anything that is nullable or *after* a nullable arg needs to be here
# TODO: We could try harder to avoid creating basic blocks in the common case
new_seen_empty_reg = seen_empty_reg
out = BasicBlock()
if nullable:
# If this is the first nullable positional arg we've seen, create
# a register to track whether anything has been null.
# (We won't *check* the register until the next argument, though.)
if maybe_pos and not seen_empty_reg:
new_seen_empty_reg = Register(bool_rprimitive)
self.add(Assign(new_seen_empty_reg, self.false(), line))
skip = BasicBlock() if maybe_pos else out
keep = BasicBlock()
self.add(Branch(value, skip, keep, Branch.IS_ERROR))
self.activate_block(keep)
# If this could be positional or named and we /might/ have seen a missing
# positional arg, then we need to compile *both* a positional and named
# version! What a pain!
if maybe_pos and maybe_named and seen_empty_reg:
pos_block, named_block = BasicBlock(), BasicBlock()
self.add(Branch(seen_empty_reg, named_block, pos_block, Branch.BOOL))
else:
pos_block = named_block = BasicBlock()
self.goto(pos_block)
if maybe_pos:
self.activate_block(pos_block)
assert star_result
self.translate_special_method_call(
star_result, "append", [value], result_type=None, line=line
)
self.goto(out)
if maybe_named and (not maybe_pos or seen_empty_reg):
self.activate_block(named_block)
assert name is not None
key = self.load_str(name)
assert star2_result
self.translate_special_method_call(
star2_result, "__setitem__", [key, value], result_type=None, line=line
)
self.goto(out)
if nullable and maybe_pos and new_seen_empty_reg:
assert skip is not out
self.activate_block(skip)
self.add(Assign(new_seen_empty_reg, self.true(), line))
self.goto(out)
self.activate_block(out)
seen_empty_reg = new_seen_empty_reg
assert not (star_result or star_values) or has_star
assert not (star2_result or star2_values) or has_star2
if has_star:
# If we managed to make it this far without creating a
# *args list, then we can directly create a
# tuple. Otherwise create the tuple from the list.
if star_result is None:
star_result = self.new_tuple(star_values, line)
else:
star_result = self.call_c(list_tuple_op, [star_result], line)
if has_star2 and star2_result is None:
star2_result = self._create_dict(star2_keys, star2_values, line)
return star_result, star2_result
def py_call(
self,
function: Value,
arg_values: list[Value],
line: int,
arg_kinds: list[ArgKind] | None = None,
arg_names: Sequence[str | None] | None = None,
) -> Value:
"""Call a Python function (non-native and slow).
Use py_call_op or py_call_with_kwargs_op for Python function call.
"""
if use_vectorcall(self.options.capi_version):
# More recent Python versions support faster vectorcalls.
result = self._py_vector_call(function, arg_values, line, arg_kinds, arg_names)
if result is not None:
return result
# If all arguments are positional, we can use py_call_op.
if arg_kinds is None or all(kind == ARG_POS for kind in arg_kinds):
return self.call_c(py_call_op, [function] + arg_values, line)
# Otherwise fallback to py_call_with_kwargs_op.
assert arg_names is not None
pos_args_tuple, kw_args_dict = self._construct_varargs(
list(zip(arg_values, arg_kinds, arg_names)), line, has_star=True, has_star2=True
)
assert pos_args_tuple and kw_args_dict
return self.call_c(py_call_with_kwargs_op, [function, pos_args_tuple, kw_args_dict], line)
def _py_vector_call(
self,
function: Value,
arg_values: list[Value],
line: int,
arg_kinds: list[ArgKind] | None = None,
arg_names: Sequence[str | None] | None = None,
) -> Value | None:
"""Call function using the vectorcall API if possible.
Return the return value if successful. Return None if a non-vectorcall
API should be used instead.
"""
# We can do this if all args are positional or named (no *args or **kwargs, not optional).
if arg_kinds is None or all(
not kind.is_star() and not kind.is_optional() for kind in arg_kinds
):
if arg_values:
# Create a C array containing all arguments as boxed values.
array = Register(RArray(object_rprimitive, len(arg_values)))
coerced_args = [self.coerce(arg, object_rprimitive, line) for arg in arg_values]
self.add(AssignMulti(array, coerced_args))
arg_ptr = self.add(LoadAddress(object_pointer_rprimitive, array))
else:
arg_ptr = Integer(0, object_pointer_rprimitive)
num_pos = num_positional_args(arg_values, arg_kinds)
keywords = self._vectorcall_keywords(arg_names)
value = self.call_c(
py_vectorcall_op,
[function, arg_ptr, Integer(num_pos, c_size_t_rprimitive), keywords],
line,
)
if arg_values:
# Make sure arguments won't be freed until after the call.
# We need this because RArray doesn't support automatic
# memory management.
self.add(KeepAlive(coerced_args))
return value
return None
def _vectorcall_keywords(self, arg_names: Sequence[str | None] | None) -> Value:
"""Return a reference to a tuple literal with keyword argument names.
Return null pointer if there are no keyword arguments.
"""
if arg_names:
kw_list = [name for name in arg_names if name is not None]
if kw_list:
return self.add(LoadLiteral(tuple(kw_list), object_rprimitive))
return Integer(0, object_rprimitive)
def py_method_call(
self,
obj: Value,
method_name: str,
arg_values: list[Value],
line: int,
arg_kinds: list[ArgKind] | None,
arg_names: Sequence[str | None] | None,
) -> Value:
"""Call a Python method (non-native and slow)."""
if use_method_vectorcall(self.options.capi_version):
# More recent Python versions support faster vectorcalls.
result = self._py_vector_method_call(
obj, method_name, arg_values, line, arg_kinds, arg_names
)
if result is not None:
return result
if arg_kinds is None or all(kind == ARG_POS for kind in arg_kinds):
# Use legacy method call API
method_name_reg = self.load_str(method_name)
return self.call_c(py_method_call_op, [obj, method_name_reg] + arg_values, line)
else:
# Use py_call since it supports keyword arguments (and vectorcalls).
method = self.py_get_attr(obj, method_name, line)
return self.py_call(method, arg_values, line, arg_kinds=arg_kinds, arg_names=arg_names)
def _py_vector_method_call(
self,
obj: Value,
method_name: str,
arg_values: list[Value],
line: int,
arg_kinds: list[ArgKind] | None,
arg_names: Sequence[str | None] | None,
) -> Value | None:
"""Call method using the vectorcall API if possible.
Return the return value if successful. Return None if a non-vectorcall
API should be used instead.
"""
if arg_kinds is None or all(
not kind.is_star() and not kind.is_optional() for kind in arg_kinds
):
method_name_reg = self.load_str(method_name)
array = Register(RArray(object_rprimitive, len(arg_values) + 1))
self_arg = self.coerce(obj, object_rprimitive, line)
coerced_args = [self_arg] + [
self.coerce(arg, object_rprimitive, line) for arg in arg_values
]
self.add(AssignMulti(array, coerced_args))
arg_ptr = self.add(LoadAddress(object_pointer_rprimitive, array))
num_pos = num_positional_args(arg_values, arg_kinds)
keywords = self._vectorcall_keywords(arg_names)
value = self.call_c(
py_vectorcall_method_op,
[
method_name_reg,
arg_ptr,
Integer((num_pos + 1) | PY_VECTORCALL_ARGUMENTS_OFFSET, c_size_t_rprimitive),
keywords,
],
line,
)
# Make sure arguments won't be freed until after the call.
# We need this because RArray doesn't support automatic
# memory management.
self.add(KeepAlive(coerced_args))
return value
return None
def call(
self,
decl: FuncDecl,
args: Sequence[Value],
arg_kinds: list[ArgKind],
arg_names: Sequence[str | None],
line: int,
*,
bitmap_args: list[Register] | None = None,
) -> Value:
"""Call a native function.
If bitmap_args is given, they override the values of (some) of the bitmap
arguments used to track the presence of values for certain arguments. By
default, the values of the bitmap arguments are inferred from args.
"""
# Normalize args to positionals.
args = self.native_args_to_positional(
args, arg_kinds, arg_names, decl.sig, line, bitmap_args=bitmap_args
)
return self.add(Call(decl, args, line))
def native_args_to_positional(
self,
args: Sequence[Value],
arg_kinds: list[ArgKind],
arg_names: Sequence[str | None],
sig: FuncSignature,
line: int,
*,
bitmap_args: list[Register] | None = None,
) -> list[Value]:
"""Prepare arguments for a native call.
Given args/kinds/names and a target signature for a native call, map
keyword arguments to their appropriate place in the argument list,
fill in error values for unspecified default arguments,
package arguments that will go into *args/**kwargs into a tuple/dict,
and coerce arguments to the appropriate type.
"""
sig_args = sig.args
n = sig.num_bitmap_args
if n:
sig_args = sig_args[:-n]
sig_arg_kinds = [arg.kind for arg in sig_args]
sig_arg_names = [arg.name for arg in sig_args]
concrete_kinds = [concrete_arg_kind(arg_kind) for arg_kind in arg_kinds]
formal_to_actual = map_actuals_to_formals(
concrete_kinds,
arg_names,
sig_arg_kinds,
sig_arg_names,
lambda n: AnyType(TypeOfAny.special_form),
)
# First scan for */** and construct those
has_star = has_star2 = False
star_arg_entries = []
for lst, arg in zip(formal_to_actual, sig_args):
if arg.kind.is_star():
star_arg_entries.extend([(args[i], arg_kinds[i], arg_names[i]) for i in lst])
has_star = has_star or arg.kind == ARG_STAR
has_star2 = has_star2 or arg.kind == ARG_STAR2
star_arg, star2_arg = self._construct_varargs(
star_arg_entries, line, has_star=has_star, has_star2=has_star2
)