forked from inaos/iron-array-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpy2llvm.py
More file actions
1315 lines (1069 loc) · 39.5 KB
/
Copy pathpy2llvm.py
File metadata and controls
1315 lines (1069 loc) · 39.5 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
# Standard Library
import ast
import builtins
import collections
import inspect
import math
import operator
from types import FunctionType
import typing
# Requirements
from llvmlite import binding, ir
from llvmlite.llvmpy.core import Module
from . import default
from . import types
# Plugins
plugins = [default]
class Range:
def __init__(self, builder, *args):
start = step = None
# Unpack
n = len(args)
if n == 1:
(stop,) = args
elif n == 2:
start, stop = args
else:
start, stop, step = args
# Defaults
type_ = stop.type if isinstance(stop, ir.Value) else types.int64
if start is None:
start = ir.Constant(type_, 0)
if step is None:
step = ir.Constant(type_, 1)
# Keep IR values
self.start = types.value_to_ir_value(builder, start)
self.stop = types.value_to_ir_value(builder, stop)
self.step = types.value_to_ir_value(builder, step)
def values_to_type(left, right):
"""
Given two values return their type. If mixing Python and IR values, IR
wins. If mixing integers and floats, float wins.
If mixing different lengths the longer one wins (e.g. float and double).
"""
ltype = types.value_to_type(left)
rtype = types.value_to_type(right)
# Both are Python
if not isinstance(ltype, ir.Type) and not isinstance(rtype, ir.Type):
if ltype is float or rtype is float:
return float
return int
# At least 1 is IR
ltype = types.type_to_ir_type(ltype)
rtype = types.type_to_ir_type(ltype)
if ltype is types.float64 or rtype is types.float64:
return types.float64
if ltype is types.float32 or rtype is types.float32:
return types.float32
if ltype is types.int64 or rtype is types.int64:
return types.int64
return types.int32
#
# AST
#
LEAFS = {
ast.Constant, # 3.8
ast.Name,
ast.NameConstant, # 3.7
ast.Num, # 3.7
# boolop
ast.And,
ast.Or,
# operator
ast.Add,
ast.Sub,
ast.Mult,
ast.MatMult,
ast.Div,
ast.Mod,
ast.Pow,
ast.LShift,
ast.RShift,
ast.BitOr,
ast.BitXor,
ast.BitAnd,
ast.FloorDiv,
# unaryop
ast.Invert,
ast.Not,
ast.UAdd,
ast.USub,
# cmpop
ast.Eq,
ast.NotEq,
ast.Lt,
ast.LtE,
ast.Gt,
ast.GtE,
ast.Is,
ast.IsNot,
ast.In,
ast.NotIn,
# expr_context
ast.Load,
ast.Store,
ast.Del,
ast.AugLoad,
ast.AugStore,
ast.Param,
}
class BaseNodeVisitor:
"""
The ast.NodeVisitor class traverses the AST and calls user defined
callbacks when entering a node.
Here we do the same thing but we've more callbacks:
- Callback as well when exiting the node
- Callback as well after traversing an attribute
- Except leaf nodes, which are called only once (like in ast.NodeVisitor)
- To find out the callback we use the MRO
And we pass more information to the callbacks:
- Pass the parent node to the callback
- Pass the value of the attribute to the attribute callback
- Pass the values of all the attributes to the exit callback
Override this class and define the callbacks you need:
- def <classname>_enter(node, parent)
- def <classname>_<attribute>(node, parent, value)
- def <classname>_exit(node, parent, *args)
For leaf nodes use:
- def <classname>_visit(node, parent)
Call using traverse:
class NodeVisitor(BaseNodeVisitor):
...
node = ast.parse(source)
NodeVisitor().traverse(node)
"""
def __init__(self, verbose):
self.verbose = verbose
self.depth = 0
@classmethod
def get_fields(cls, node):
fields = {
# Skip "decorator_list", and traverse "returns" before "body"
# ('name', 'args', 'body', 'decorator_list', 'returns')
ast.FunctionDef: ("name", "args", "returns", "body"),
}
return fields.get(type(node), node._fields)
@classmethod
def iter_fields(cls, node):
for field in cls.get_fields(node):
try:
yield field, getattr(node, field)
except AttributeError:
pass
def traverse(self, node, parent=None):
if node.__class__ in LEAFS:
return self.callback("visit", node, parent)
# Enter
# enter callback return False to skip traversing the subtree
if self.callback("enter", node, parent) is False:
return None
self.depth += 1
# Traverse
args = []
for name, field in self.iter_fields(node):
if isinstance(field, list):
value = [self.traverse(x, node) for x in field if isinstance(x, ast.AST)]
elif isinstance(field, ast.AST):
value = self.traverse(field, node)
else:
value = field
self.callback(name, node, parent, value)
args.append(value)
# Exit
self.depth -= 1
return self.callback("exit", node, parent, *args)
def callback(self, event, node, parent, *args):
for cls in node.__class__.__mro__:
method = f"{cls.__name__}_{event}"
cb = getattr(self, method, None)
if cb is not None:
break
# Call
value = cb(node, parent, *args) if cb is not None else None
# Debug
if self.verbose > 1:
name = node.__class__.__name__
line = None
if event == "enter":
line = f"<{name}>"
if node._fields:
attrs = " ".join(f"{k}" for k, _ in ast.iter_fields(node))
line = f"<{name} {attrs}>"
if value is False:
line += " SKIP"
elif event == "exit":
line = f"</{name}> -> {value}"
# if args:
# attrs = ' '.join(repr(x) for x in args)
# line = f'</{name} {attrs}>'
# else:
# line = f'</{name}>'
elif event == "visit":
if node._fields:
attrs = " ".join(f"{k}" for k, _ in ast.iter_fields(node))
line = f"<{name} {attrs} />"
else:
line = f"<{name} />"
if cb is not None:
line += f" -> {value}"
else:
if cb is not None:
attrs = " ".join([repr(x) for x in args])
line = f"_{event}({attrs})"
if line:
print(self.depth * " " + line)
return value
class NodeVisitor(BaseNodeVisitor):
def lookup(self, name):
if name in self.locals:
return self.locals[name]
# To support recursivity XXX
if name in self.root.compiled:
return self.root.compiled[name]
if name in self.root.globals:
return self.root.globals[name]
return getattr(builtins, name)
def load(self, name):
value = self.lookup(name)
if type(value) is ir.AllocaInstr:
if not isinstance(value.type.pointee, ir.Aggregate):
return self.builder.load(value)
return value
def Module_enter(self, node, parent):
"""
Module(stmt* body)
"""
self.root = node
def FunctionDef_enter(self, node, parent):
"""
FunctionDef(identifier name, arguments args,
stmt* body, expr* decorator_list, expr? returns)
"""
assert type(parent) is ast.Module, "nested functions not implemented"
# Initialize function context
node.locals = {}
self.locals = node.locals
def arguments_enter(self, node, parent):
"""
arguments = (arg* args, arg? vararg, arg* kwonlyargs, expr* kw_defaults,
arg? kwarg, expr* defaults)
"""
# We don't parse arguments because arguments are handled in compile
return False
def Assign_enter(self, node, parent):
"""
Assign(expr* targets, expr value)
Assign(expr* targets, expr value, string? type_comment) # 3.8
"""
assert len(node.targets) == 1, "Unpacking not supported"
#
# Leaf nodes
#
def Constant_visit(self, node, parent):
"""
Constant(constant value, string? kind)
Pythonr 3.8
"""
return node.value
def NameConstant_visit(self, node, parent):
"""
NameConstant(singleton value)
Pythonr 3.7
"""
return node.value
def Num_visit(self, node, parent):
"""
Num(object n)
Pythonr 3.7
"""
return node.n
def expr_context_visit(self, node, parent):
return type(node)
def Name_visit(self, node, parent):
"""
Name(identifier id, expr_context ctx)
"""
name = node.id
ctx = type(node.ctx)
if ctx is ast.Load:
try:
return self.lookup(name)
except AttributeError:
return None
elif ctx is ast.Store:
return name
raise NotImplementedError(f"unexpected ctx={ctx}")
class InferVisitor(NodeVisitor):
"""
This optional pass is to infer the return type of the function if not given
explicitely.
"""
def Assign_exit(self, node, parent, targets, value, *args):
target = targets[0]
if type(target) is str:
# x =
self.locals.setdefault(target, value)
def Return_exit(self, node, parent, value):
return_type = type(value)
root = self.root
if root.return_type is inspect._empty:
root.return_type = return_type
return
assert root.return_type is return_type
def FunctionDef_exit(self, node, parent, *args):
root = self.root
if root.return_type is inspect._empty:
root.return_type = None
class BlockVisitor(NodeVisitor):
"""
The algorithm makes 2 passes to the AST. This is the first one, here:
- We fail early for features we don't support.
- We populate the AST attaching structure IR objects (module, functions,
blocks). These will be used in the 2nd pass.
"""
def __init__(self, verbose, function):
super().__init__(verbose)
self.function = function
def FunctionDef_returns(self, node, parent, returns):
"""
When we reach this point we have all the function signature: arguments
and return type.
"""
root = self.root
ir_signature = root.ir_signature
# Keep the function in globals so it can be called
function = root.ir_function
self.root.compiled[node.name] = function
# Create the first block of the function, and the associated builder.
# The first block, named "vars", is where all local variables will be
# allocated. We will keep it open until we close the function in the
# 2nd pass.
block_vars = function.append_basic_block("vars")
builder = ir.IRBuilder(block_vars)
# Function start: allocate a local variable for every argument
args = {}
for i, param in enumerate(ir_signature.parameters):
arg = function.args[i]
assert arg.type is param.type
ptr = builder.alloca(arg.type, name=param.name)
builder.store(arg, ptr)
# Keep Give a name to the arguments, and keep them in local namespace
args[param.name] = ptr
# Function preamble
self.function.preamble(builder, args)
# Every Python argument is a local variable
locals_ = node.locals
for param in self.function.py_signature.parameters:
if type(param.type) is type and issubclass(param.type, types.ComplexType):
value = param.type(self.function, param.name, args)
# The params can inject IR at the beginning
value.preamble(builder)
else:
value = args[param.name]
locals_[param.name] = value
# Create the second block, this is where the code proper will start,
# after allocation of the local variables.
block_start = function.append_basic_block("start")
builder.position_at_end(block_start)
# Keep stuff we will need in this first pass
self.function = function
# Keep stuff for the second pass
node.block_vars = block_vars
node.block_start = block_start
node.builder = builder
node.f_rtype = ir_signature.return_type
def If_test(self, node, parent, test):
"""
If(expr test, stmt* body, stmt* orelse)
"""
node.block_true = self.function.append_basic_block("if_true")
def If_body(self, node, parent, body):
node.block_false = self.function.append_basic_block("if_false")
def If_orelse(self, node, parent, orelse):
node.block_next = self.function.append_basic_block("if_next")
def IfExp_test(self, node, parent, test):
"""
IfExp(expr test, expr body, expr orelse)
"""
node.block_true = self.function.append_basic_block("ifexp_true")
def IfExp_body(self, node, parent, body):
node.block_false = self.function.append_basic_block("ifexp_false")
def IfExp_orelse(self, node, parent, orelse):
node.block_next = self.function.append_basic_block("ifexp_next")
def For_enter(self, node, parent):
"""
For(expr target, expr iter, stmt* body, stmt* orelse)
"""
assert not node.orelse, '"for ... else .." not supported'
node.block_for = self.function.append_basic_block("for")
node.block_body = self.function.append_basic_block("for_body")
def For_exit(self, node, parent, *args):
node.block_next = self.function.append_basic_block("for_out")
def While_enter(self, node, parent):
"""
While(expr test, stmt* body, stmt* orelse)
"""
assert not node.orelse, '"while ... else .." not supported'
node.block_while = self.function.append_basic_block("while")
node.block_body = self.function.append_basic_block("while_body")
def While_exit(self, node, parent, *args):
node.block_next = self.function.append_basic_block("while_out")
class GenVisitor(NodeVisitor):
"""
Builtin types are:
identifier, int, string, bytes, object, singleton, constant
singleton: None, True or False
constant can be None, whereas None means "no value" for object.
"""
function = None
args = None
builder = None
f_rtype = None # Type of the return value
ltype = None # Type of the local variable
def print(self, line):
print(self.depth * " " + line)
def debug(self, node, parent):
for name, field in ast.iter_fields(node):
self.print(f"- {name} {field}")
def convert(self, value, type_):
"""
Return the value converted to the given type.
"""
return types.value_to_ir_value(self.builder, value, type_)
#
# Leaf nodes
#
def Name_visit(self, node, parent):
"""
Name(identifier id, expr_context ctx)
"""
name = node.id
ctx = type(node.ctx)
if ctx is ast.Load:
return self.load(name)
elif ctx is ast.Store:
return name
raise NotImplementedError(f"unexpected ctx={ctx}")
def boolop_visit(self, node, parent):
return type(node)
def operator_visit(self, node, parent):
return type(node)
def unaryop_visit(self, node, parent):
return type(node)
def Eq_visit(self, node, parent):
return "=="
def NotEq_visit(self, node, parent):
return "!="
def Lt_visit(self, node, parent):
return "<"
def LtE_visit(self, node, parent):
return "<="
def Gt_visit(self, node, parent):
return ">"
def GtE_visit(self, node, parent):
return ">="
#
# Literals
#
def List_exit(self, node, parent, elts, ctx):
"""
List(expr* elts, expr_context ctx)
"""
py_types = {type(x) for x in elts}
n = len(py_types)
if n == 0:
# any type will do because the list is empty
py_type = int
elif n == 1:
py_type = py_types.pop()
else:
raise TypeError("all list elements must be of the same type")
el_type = types.type_to_ir_type(py_type)
typ = ir.ArrayType(el_type, len(elts))
return ir.Constant(typ, elts)
#
# Expressions
#
def FunctionDef_enter(self, node, parent):
self.locals = node.locals
self.builder = node.builder
self.f_rtype = node.f_rtype
self.block_vars = node.block_vars
def FunctionDef_exit(self, node, parent, *args):
if self.root.py_signature.return_type is None:
if not self.builder.block.is_terminated:
node.builder.ret_void()
node.builder.position_at_end(node.block_vars)
node.builder.branch(node.block_start)
def BoolOp_exit(self, node, parent, op, values):
"""
BoolOp(boolop op, expr* values)
"""
ir_op = {
ast.And: self.builder.and_,
ast.Or: self.builder.or_,
}[op]
assert len(values) == 2
left, right = values
return ir_op(left, right)
def BinOp_exit(self, node, parent, left, op, right):
type_ = values_to_type(left, right)
# Two Python values
if not isinstance(type_, ir.Type):
ast2op = {
ast.Add: operator.add,
ast.Sub: operator.sub,
ast.Mult: operator.mul,
ast.Div: operator.truediv,
}
py_op = ast2op.get(op)
if py_op is None:
raise NotImplementedError(
f"{op.__name__} operator for {type_} type not implemented"
)
return py_op(left, right)
# One or more IR values
left = self.convert(left, type_)
right = self.convert(right, type_)
d = {
(ast.Add, ir.IntType): self.builder.add,
(ast.Sub, ir.IntType): self.builder.sub,
(ast.Mult, ir.IntType): self.builder.mul,
(ast.Div, ir.IntType): self.builder.sdiv,
(ast.Mod, ir.IntType): self.builder.srem,
(ast.Add, ir.FloatType): self.builder.fadd,
(ast.Sub, ir.FloatType): self.builder.fsub,
(ast.Mult, ir.FloatType): self.builder.fmul,
(ast.Div, ir.FloatType): self.builder.fdiv,
(ast.Add, ir.DoubleType): self.builder.fadd,
(ast.Sub, ir.DoubleType): self.builder.fsub,
(ast.Mult, ir.DoubleType): self.builder.fmul,
(ast.Div, ir.DoubleType): self.builder.fdiv,
}
base_type = type(type_)
ir_op = d.get((op, base_type))
if ir_op is None:
raise NotImplementedError(f"{op.__name__} operator for {type_} type not implemented")
return ir_op(left, right)
def UnaryOp_exit(self, node, parent, op, operand):
"""
UnaryOp(unaryop op, expr operand)
"""
type_ = types.value_to_type(operand)
if isinstance(type_, ir.Type):
# Python value
ops = {
ast.Not: self.builder.not_,
ast.USub: self.builder.neg,
}
else:
# IR value
ops = {
ast.Not: operator.not_,
ast.USub: operator.neg,
}
return ops[op](operand)
def IfExp_test(self, node, parent, test):
"""
If(expr test, stmt* body, stmt* orelse)
"""
self.builder.cbranch(test, node.block_true, node.block_false)
self.builder.position_at_end(node.block_true)
def IfExp_body(self, node, parent, body):
if not self.builder.block.is_terminated:
self.builder.branch(node.block_next)
self.builder.position_at_end(node.block_false)
def IfExp_orelse(self, node, parent, orelse):
self.builder.branch(node.block_next)
self.builder.position_at_end(node.block_next)
def IfExp_exit(self, node, parent, test, body, orelse):
"""
IfExp(expr test, expr body, expr orelse)
"""
ltype = types.value_to_type(body)
rtype = types.value_to_type(orelse)
assert ltype is rtype
phi = self.builder.phi(ltype)
phi.add_incoming(body, node.block_true)
phi.add_incoming(orelse, node.block_false)
return phi
def Compare_exit(self, node, parent, left, ops, comparators):
"""
Compare(expr left, cmpop* ops, expr* comparators)
"""
assert len(ops) == 1
assert len(comparators) == 1
op = ops[0]
right = comparators[0]
type_ = values_to_type(left, right)
# Two Python values
if not isinstance(type_, ir.Type):
ast2op = {
"==": operator.eq,
"!=": operator.ne,
"<": operator.lt,
"<=": operator.le,
">": operator.gt,
">=": operator.ge,
}
py_op = ast2op.get(op)
return py_op(left, right)
# At least 1 IR value
left = self.convert(left, type_)
right = self.convert(right, type_)
d = {
ir.IntType: self.builder.icmp_signed,
ir.FloatType: self.builder.fcmp_unordered, # XXX fcmp_ordered
ir.DoubleType: self.builder.fcmp_unordered, # XXX fcmp_ordered
}
base_type = type(type_)
ir_op = d.get(base_type)
return ir_op(op, left, right)
def Index_exit(self, node, parent, value):
"""
Index(expr value)
"""
return value
def Subscript_exit(self, node, parent, value, slice, ctx):
"""
Subscript(expr value, slice slice, expr_context ctx)
"""
# An smart object
subscript = getattr(value, "subscript", None)
if subscript is not None:
return subscript(self, slice, ctx)
# A pointer!
if isinstance(value, ir.Value) and value.type.is_pointer:
ptr = value
ptr = self.builder.gep(ptr, [slice])
return self.builder.load(ptr)
raise NotImplementedError(f"{type(value)} does not support subscript []")
def Tuple_exit(self, node, parent, elts, ctx):
"""
Tuple(expr* elts, expr_context ctx)
"""
assert ctx is ast.Load
return elts
#
# if .. elif .. else
#
def If_test(self, node, parent, test):
"""
If(expr test, stmt* body, stmt* orelse)
"""
self.builder.cbranch(test, node.block_true, node.block_false)
self.builder.position_at_end(node.block_true)
def If_body(self, node, parent, body):
if not self.builder.block.is_terminated:
self.builder.branch(node.block_next)
self.builder.position_at_end(node.block_false)
def If_orelse(self, node, parent, orelse):
self.builder.branch(node.block_next)
self.builder.position_at_end(node.block_next)
#
# for ...
#
def For_iter(self, node, parent, expr):
"""
For(expr target, expr iter, stmt* body, stmt* orelse)
"""
target = node.target.id
if isinstance(expr, Range):
start = expr.start
stop = expr.stop
node.step = expr.step
name = target
else:
start = types.zero
stop = ir.Constant(types.int64, expr.type.count)
node.step = types.one
name = "i"
# Allocate and store the literal array to iterate
arr = self.builder.alloca(expr.type)
self.builder.store(expr, arr)
# Allocate and initialize the index variable
node.i = self.builder.alloca(stop.type, name=name)
self.builder.store(start, node.i) # i = start
self.builder.branch(node.block_for) # br %for
# Stop condition
self.builder.position_at_end(node.block_for) # %for
idx = self.builder.load(node.i) # %idx = i
test = self.builder.icmp_unsigned("<", idx, stop) # %idx < stop
self.builder.cbranch(test, node.block_body, node.block_next) # br %test %body %next
self.builder.position_at_end(node.block_body) # %body
# Keep variable to use within the loop
if isinstance(expr, Range):
self.locals[target] = idx
else:
ptr = self.builder.gep(arr, [types.zero, idx]) # expr[idx]
x = self.builder.load(ptr) # % = expr[i]
self.locals[target] = x
def For_exit(self, node, parent, *args):
# Increment index variable
a = self.builder.load(node.i) # % = i
b = self.builder.add(a, node.step) # % = % + step
self.builder.store(b, node.i) # i = %
# Continue
self.builder.branch(node.block_for) # br %for
self.builder.position_at_end(node.block_next) # %next
#
# while ...
#
def While_enter(self, node, parent):
self.builder.branch(node.block_while)
self.builder.position_at_end(node.block_while)
def While_test(self, node, parent, test):
self.builder.cbranch(test, node.block_body, node.block_next)
self.builder.position_at_end(node.block_body)
def While_exit(self, node, parent, *args):
self.builder.branch(node.block_while)
self.builder.position_at_end(node.block_next)
#
# Other non-leaf nodes
#
def Attribute_exit(self, node, parent, value, attr, ctx):
"""
Attribute(expr value, identifier attr, expr_context ctx)
"""
assert ctx is ast.Load
value = getattr(value, attr)
if isinstance(value, types.Node):
value = value.Attribute_exit(self)
if isinstance(value, ir.Value) and value.type.is_pointer:
value = self.builder.load(value)
return value
def AnnAssign_annotation(self, node, parent, value):
self.ltype = value
def AnnAssign_exit(self, node, parent, target, annotation, value, simple):
"""
AnnAssign(expr target, expr annotation, expr? value, int simple)
"""
assert value is not None
assert simple == 1
ltype = types.type_to_ir_type(self.ltype)
value = self.convert(value, ltype)
self.ltype = None
name = target
try:
ptr = self.lookup(name)
except AttributeError:
block_cur = self.builder.block
self.builder.position_at_end(self.block_vars)
ptr = self.builder.alloca(value.type, name=name)
self.builder.position_at_end(block_cur)
self.locals[name] = ptr
return self.builder.store(value, ptr)
def Assign_exit(self, node, parent, targets, value, *args):
if len(targets) > 1:
raise NotImplementedError("unpacking not supported")
builder = self.builder
value = types.value_to_ir_value(builder, value)
target = targets[0]
if type(target) is str:
# x =
name = target
try:
ptr = self.lookup(name)
except AttributeError:
block_cur = builder.block
builder.position_at_end(self.block_vars)
ptr = builder.alloca(value.type, name=name)
builder.position_at_end(block_cur)
self.locals[name] = ptr
else:
# x[i] =
ptr = target
return builder.store(value, ptr)
def AugAssign_exit(self, node, parent, target, op, value):
"""
AugAssign(expr target, operator op, expr value)
"""
# Translate "a += b" to "a = a + b"
left = self.load(target)
value = self.BinOp_exit(node, parent, left, op, value) # a + b
return self.Assign_exit(node, parent, [target], value) # a =
def Return_enter(self, node, parent):
self.ltype = self.f_rtype
def Return_exit(self, node, parent, value):
"""
Return(expr? value)
"""
if value is None:
assert self.f_rtype is types.void
return self.builder.ret_void()
value = self.convert(value, self.f_rtype)
self.ltype = None
return self.builder.ret(value)
def Call_exit(self, node, parent, func, args, keywords):
"""
Call(expr func, expr* args, keyword* keywords)
"""
assert not keywords
if func is range:
return Range(self.builder, *args)
func = self.root.compiled.get(func, func)
if not isinstance(func, ir.Function):
raise TypeError(f"unexpected {func}")
# Check the number of arguments is correct
if len(args) != len(func.args):
n = len(func.args)
raise TypeError(
f"{func.name} takes exactly one argument ({len(args)} given)"
if n == 1
else f"{func.name} expects {n} arguments, got {len(args)}"
)
# Convert to IR values of the correct type
args = [
types.value_to_ir_value(self.builder, arg, type_=func_arg.type)