-
Notifications
You must be signed in to change notification settings - Fork 9
/
iteration.py
722 lines (669 loc) · 23.1 KB
/
iteration.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
import typing
from collections.abc import Sequence
import structlog
from puya.avm_type import AVMType
from puya.awst import (
nodes as awst_nodes,
wtypes,
)
from puya.awst.nodes import (
Expression,
)
from puya.errors import CodeError, InternalError
from puya.ir.avm_ops import AVMOp
from puya.ir.builder import arc4
from puya.ir.builder.assignment import handle_assignment
from puya.ir.builder.utils import (
assert_value,
assign,
assign_intrinsic_op,
mkblocks,
reassign,
)
from puya.ir.context import IRFunctionBuildContext
from puya.ir.models import (
BasicBlock,
ConditionalBranch,
Goto,
GotoNth,
Intrinsic,
Register,
UInt64Constant,
Value,
ValueProvider,
)
from puya.parse import SourceLocation
logger = structlog.get_logger(__name__)
def handle_for_in_loop(context: IRFunctionBuildContext, statement: awst_nodes.ForInLoop) -> None:
sequence = statement.sequence
has_enumerate = False
reverse_items = False
reverse_index = False
while True:
match sequence:
case awst_nodes.Enumeration():
if has_enumerate:
raise CodeError(
"Nested enumeration is not currently supported",
sequence.source_location,
)
sequence = sequence.expr
has_enumerate = True
case awst_nodes.Reversed():
sequence = sequence.expr
reverse_items = not reverse_items
if not has_enumerate:
reverse_index = not reverse_index
case _:
break
if has_enumerate:
if not (
isinstance(statement.items, awst_nodes.TupleExpression)
and len(statement.items.items) == 2
):
# TODO: fix this
raise CodeError(
"when using uenumerate(), loop variables must be an unpacked two item tuple",
statement.sequence.source_location,
)
index_var, item_var = statement.items.items
else:
index_var = None
item_var = statement.items
match sequence:
case awst_nodes.Range(
start=range_start, stop=range_stop, step=range_step, source_location=range_loc
):
_iterate_urange(
context,
loop_body=statement.loop_body,
item_var=item_var,
index_var=index_var,
statement_loc=statement.source_location,
range_start=range_start,
range_stop=range_stop,
range_step=range_step,
range_loc=range_loc,
reverse_items=reverse_items,
reverse_index=reverse_index,
)
case awst_nodes.Expression(wtype=wtypes.WTuple()) as tuple_expression:
tuple_items = context.visitor.visit_and_materialise(tuple_expression)
if not tuple_items:
logger.debug("Skipping ForInStatement which iterates an empty sequence.")
else:
_iterate_tuple(
context,
loop_body=statement.loop_body,
item_var=item_var,
index_var=index_var,
tuple_items=tuple_items,
statement_loc=statement.source_location,
reverse_index=reverse_index,
reverse_items=reverse_items,
)
case awst_nodes.Expression(wtype=wtypes.bytes_wtype) as bytes_expression:
bytes_value = context.visitor.visit_and_materialise_single(bytes_expression)
(byte_length,) = assign(
context,
temp_description="bytes_length",
source=Intrinsic(
op=AVMOp.len_,
args=[bytes_value],
source_location=statement.source_location,
),
source_location=statement.source_location,
)
def get_byte_at_index(index_register: Register) -> ValueProvider:
return Intrinsic(
op=AVMOp.extract3,
args=[
bytes_value,
index_register,
UInt64Constant(value=1, source_location=None),
],
source_location=item_var.source_location,
)
_iterate_indexable(
context,
loop_body=statement.loop_body,
indexable_size=byte_length,
get_value_at_index=get_byte_at_index,
item_var=item_var,
index_var=index_var,
statement_loc=statement.source_location,
reverse_index=reverse_index,
reverse_items=reverse_items,
)
case awst_nodes.Expression(
wtype=wtypes.ARC4DynamicArray() as dynamic_array_wtype
) as arc4_dynamic_array_expression:
iterator = arc4.build_for_in_dynamic_array(
context, statement, dynamic_array_wtype, arc4_dynamic_array_expression
)
_iterate_indexable(
context,
loop_body=statement.loop_body,
indexable_size=iterator.size,
get_value_at_index=iterator.get_value_at_index,
item_var=item_var,
index_var=index_var,
statement_loc=statement.source_location,
reverse_index=reverse_index,
reverse_items=reverse_items,
)
case awst_nodes.Expression(
wtype=wtypes.ARC4StaticArray() as static_array_wtype
) as arc4_static_array_expression:
iterator = arc4.build_for_in_static_array(
context, statement, static_array_wtype, arc4_static_array_expression
)
_iterate_indexable(
context,
loop_body=statement.loop_body,
indexable_size=iterator.size,
get_value_at_index=iterator.get_value_at_index,
item_var=item_var,
index_var=index_var,
statement_loc=statement.source_location,
reverse_index=reverse_index,
reverse_items=reverse_items,
)
case _:
raise InternalError("Unsupported for in loop sequence", statement.source_location)
def _check_urange_will_loop(
context: IRFunctionBuildContext,
*,
stop: Value,
start: Value,
after_for: BasicBlock,
statement_loc: SourceLocation,
) -> None:
(preamble,) = mkblocks(statement_loc, "for_preamble")
(should_loop,) = assign_intrinsic_op(
context,
target="should_loop",
op=AVMOp.lt,
args=[start, stop],
source_location=statement_loc,
)
context.block_builder.terminate(
ConditionalBranch(
condition=should_loop,
non_zero=preamble,
zero=after_for,
source_location=statement_loc,
)
)
context.block_builder.activate_block(preamble)
context.ssa.seal_block(preamble)
def _iterate_urange(
context: IRFunctionBuildContext,
*,
loop_body: awst_nodes.Block,
item_var: Expression,
index_var: Expression | None,
statement_loc: SourceLocation,
range_start: Expression,
range_stop: Expression,
range_step: Expression,
range_loc: SourceLocation,
reverse_items: bool,
reverse_index: bool,
) -> None:
header, body, footer, increment_block, next_block = mkblocks(
statement_loc,
"for_header",
"for_body",
"for_footer",
"for_increment",
"after_for",
)
step = context.visitor.visit_and_materialise_single(range_step)
stop = context.visitor.visit_and_materialise_single(range_stop)
start = context.visitor.visit_and_materialise_single(range_start)
assert_value(context, step, source_location=statement_loc, comment="Step cannot be zero")
iteration_count_minus_one: Register | None
if reverse_items or reverse_index:
# The following code will result in negative uints if we don't pre-check the urange
# params
_check_urange_will_loop(
context,
stop=stop,
start=start,
after_for=next_block,
statement_loc=statement_loc,
)
# Determine the iteration count by doing the equivalent of
# ceiling((stop - start) / step)
# which is
# floor((stop - start) / step) + (mod((stop - start), step) != 0)
(range_length,) = assign_intrinsic_op(
context,
target="range_length",
source_location=statement_loc,
op=AVMOp.sub,
args=[
stop,
start,
],
)
(range_mod_step,) = assign_intrinsic_op(
context,
target="range_mod_step",
source_location=statement_loc,
op=AVMOp.mod,
args=[range_length, step],
)
(range_mod_step_not_zero,) = assign_intrinsic_op(
context,
target="range_mod_step_not_zero",
source_location=statement_loc,
op=AVMOp.neq,
args=[range_mod_step, 0],
)
(range_floor_div_step,) = assign_intrinsic_op(
context,
target="range_floor_div_step",
source_location=statement_loc,
op=AVMOp.div_floor,
args=[
range_length,
step,
],
)
(iteration_count,) = assign_intrinsic_op(
context,
target="iteration_count",
source_location=statement_loc,
op=AVMOp.add,
args=[
range_floor_div_step,
range_mod_step_not_zero,
],
)
(iteration_count_minus_one,) = assign_intrinsic_op(
context,
target="iteration_count_minus_one",
source_location=statement_loc,
op=AVMOp.sub,
args=[
iteration_count,
1,
],
)
else:
iteration_count_minus_one = None
if reverse_items and iteration_count_minus_one:
(range_delta,) = assign_intrinsic_op(
context,
target="range_delta",
source_location=statement_loc,
op=AVMOp.mul,
args=[step, iteration_count_minus_one],
)
(stop,) = assign(
context,
temp_description="stop",
source_location=statement_loc,
source=start,
)
(start,) = assign_intrinsic_op(
context,
target="start",
source_location=statement_loc,
op=AVMOp.add,
args=[start, range_delta],
)
(range_item,) = assign(
context,
source=start,
temp_description="range_item",
source_location=item_var.source_location,
)
index_var_src_loc = index_var.source_location if index_var else None
range_index: Register | None = None
if index_var:
(range_index,) = assign(
context,
source=UInt64Constant(value=0, source_location=None),
temp_description="range_index",
source_location=index_var_src_loc,
)
context.block_builder.goto_and_activate(header)
if reverse_items:
(continue_looping,) = assign(
context,
source=(
Intrinsic(
op=AVMOp(">="),
args=[_refresh_mutated_variable(context, range_item), stop],
source_location=range_loc,
)
),
temp_description="continue_looping",
source_location=range_loc,
)
else:
(continue_looping,) = assign(
context,
source=(
Intrinsic(
op=AVMOp("<"),
args=[_refresh_mutated_variable(context, range_item), stop],
source_location=range_loc,
)
),
temp_description="continue_looping",
source_location=range_loc,
)
context.block_builder.terminate(
ConditionalBranch(
condition=continue_looping,
non_zero=body,
zero=next_block,
source_location=statement_loc,
)
)
context.block_builder.activate_block(body)
handle_assignment(
context,
target=item_var,
value=_refresh_mutated_variable(context, range_item),
assignment_location=item_var.source_location,
)
if index_var and range_index:
if reverse_index and iteration_count_minus_one:
(next_index,) = assign_intrinsic_op(
context,
target="next_index",
source_location=index_var.source_location,
op=AVMOp.sub,
args=[iteration_count_minus_one, _refresh_mutated_variable(context, range_index)],
)
handle_assignment(
context,
target=index_var,
value=next_index,
assignment_location=index_var.source_location,
)
else:
handle_assignment(
context,
target=index_var,
value=_refresh_mutated_variable(context, range_index),
assignment_location=index_var.source_location,
)
with context.block_builder.enter_loop(on_continue=footer, on_break=next_block):
loop_body.accept(context.visitor)
context.block_builder.goto_and_activate(footer)
context.ssa.seal_block(footer)
if reverse_items:
(continue_looping,) = assign(
context,
source=(
Intrinsic(
op=AVMOp(">"),
args=[_refresh_mutated_variable(context, range_item), stop],
source_location=range_loc,
)
),
temp_description="continue_looping",
source_location=range_loc,
)
context.block_builder.terminate(
ConditionalBranch(
condition=continue_looping,
non_zero=increment_block,
zero=next_block,
source_location=statement_loc,
)
)
context.block_builder.activate_block(increment_block)
else:
context.block_builder.goto_and_activate(increment_block)
context.ssa.seal_block(increment_block)
new_range_item_value = Intrinsic(
op=AVMOp.sub if reverse_items else AVMOp.add,
args=[_refresh_mutated_variable(context, range_item), step],
source_location=range_loc,
)
reassign(context, range_item, new_range_item_value, statement_loc)
if range_index and index_var:
assign_intrinsic_op(
context,
target=range_index,
op=AVMOp("+"),
args=[
_refresh_mutated_variable(context, range_index),
UInt64Constant(value=1, source_location=None),
],
source_location=index_var.source_location,
)
if reverse_items:
context.block_builder.goto(body)
else:
context.block_builder.goto(header)
context.ssa.seal_block(header)
context.ssa.seal_block(body)
context.ssa.seal_block(next_block)
context.block_builder.activate_block(next_block)
def _iterate_indexable(
context: IRFunctionBuildContext,
*,
loop_body: awst_nodes.Block,
item_var: Expression,
index_var: Expression | None,
statement_loc: SourceLocation,
indexable_size: Value,
get_value_at_index: typing.Callable[[Register], ValueProvider],
reverse_items: bool,
reverse_index: bool,
) -> None:
header, body, footer, next_block = mkblocks(
statement_loc,
"for_header",
"for_body",
"for_footer",
"after_for",
)
(index_internal,) = assign(
context,
source=UInt64Constant(value=0, source_location=None),
temp_description="item_index_internal",
source_location=None,
)
(reverse_index_internal,) = assign(
context,
source=indexable_size,
temp_description="reverse_index_internal",
source_location=None,
)
context.block_builder.goto_and_activate(header)
(continue_looping,) = assign(
context,
source=(
Intrinsic(
op=AVMOp.lt,
args=[_refresh_mutated_variable(context, index_internal), indexable_size],
source_location=statement_loc,
)
),
temp_description="continue_looping",
source_location=statement_loc,
)
context.block_builder.terminate(
ConditionalBranch(
condition=continue_looping,
non_zero=body,
zero=next_block,
source_location=statement_loc,
)
)
context.ssa.seal_block(body)
context.block_builder.activate_block(body)
current_index_internal = _refresh_mutated_variable(context, index_internal)
if reverse_items or reverse_index:
(reverse_index_internal,) = assign_intrinsic_op(
context,
target=reverse_index_internal,
source_location=None,
op=AVMOp.sub,
args=[_refresh_mutated_variable(context, reverse_index_internal), 1],
)
handle_assignment(
context,
target=item_var,
value=get_value_at_index(
reverse_index_internal if reverse_items else current_index_internal
),
assignment_location=item_var.source_location,
)
if index_var:
handle_assignment(
context,
target=index_var,
value=reverse_index_internal if reverse_index else current_index_internal,
assignment_location=index_var.source_location,
)
else:
handle_assignment(
context,
target=item_var,
value=get_value_at_index(current_index_internal),
assignment_location=item_var.source_location,
)
if index_var:
handle_assignment(
context,
target=index_var,
value=current_index_internal,
assignment_location=index_var.source_location,
)
with context.block_builder.enter_loop(on_continue=footer, on_break=next_block):
loop_body.accept(context.visitor)
context.block_builder.goto_and_activate(footer)
context.ssa.seal_block(footer)
context.ssa.seal_block(next_block)
new_index_internal_value = Intrinsic(
op=AVMOp("+"),
args=[
_refresh_mutated_variable(context, index_internal),
UInt64Constant(value=1, source_location=None),
],
source_location=None,
)
reassign(context, index_internal, new_index_internal_value, source_location=None)
context.block_builder.goto(header)
context.ssa.seal_block(header)
context.block_builder.activate_block(next_block)
def _iterate_tuple(
context: IRFunctionBuildContext,
*,
loop_body: awst_nodes.Block,
item_var: awst_nodes.Expression,
index_var: awst_nodes.Expression | None,
tuple_items: Sequence[Value],
statement_loc: SourceLocation,
reverse_index: bool,
reverse_items: bool,
) -> None:
headers = [
BasicBlock(comment=f"for_header_{index}", source_location=statement_loc)
for index, _ in enumerate(tuple_items)
]
if reverse_items:
headers.reverse()
tuple_items = [*tuple_items]
tuple_items.reverse()
body, footer, next_block = mkblocks(
statement_loc,
"for_body",
"for_footer",
"after_for",
)
tuple_index = context.next_tmp_name("tuple_index")
for index, (item, header) in enumerate(zip(tuple_items, headers)):
if index == 0:
context.block_builder.goto_and_activate(header)
context.ssa.seal_block(header)
assign(
context,
source=UInt64Constant(value=0, source_location=None),
names=[(tuple_index, None)],
source_location=None,
)
else:
context.block_builder.activate_block(header, ignore_predecessor_check=True)
handle_assignment(
context,
target=item_var,
value=item,
assignment_location=item_var.source_location,
)
context.block_builder.goto(body)
context.ssa.seal_block(body)
context.block_builder.activate_block(body)
if index_var:
if reverse_index:
(reversed_index,) = assign_intrinsic_op(
context,
target="reversed_index",
source_location=None,
op=AVMOp.sub,
args=[
len(tuple_items) - 1,
context.ssa.read_variable(tuple_index, AVMType.uint64, body),
],
)
handle_assignment(
context,
target=index_var,
value=reversed_index,
assignment_location=index_var.source_location,
)
else:
handle_assignment(
context,
target=index_var,
value=context.ssa.read_variable(tuple_index, AVMType.uint64, body),
assignment_location=index_var.source_location,
)
with context.block_builder.enter_loop(on_continue=footer, on_break=next_block):
loop_body.accept(context.visitor)
context.block_builder.goto_and_activate(footer)
context.ssa.seal_block(footer)
curr_index_internal = context.ssa.read_variable(tuple_index, AVMType.uint64, footer)
(_updated_r,) = assign(
context,
source=Intrinsic(
op=AVMOp("+"),
args=[curr_index_internal, UInt64Constant(value=1, source_location=None)],
source_location=None,
),
names=[(tuple_index, None)],
source_location=None,
)
goto_default = Goto(target=next_block, source_location=statement_loc)
context.block_builder.terminate(
GotoNth(
source_location=statement_loc,
value=curr_index_internal,
blocks=headers[1:],
default=goto_default,
)
)
for header in headers[1:]:
context.ssa.seal_block(header)
context.ssa.seal_block(next_block)
context.block_builder.activate_block(next_block)
def _refresh_mutated_variable(context: IRFunctionBuildContext, reg: Register) -> Register:
"""
Given a register pointing to an underlying root operand (ie name) that is mutated,
do an SSA read in the current block.
This is *only* required when there is control flow involved in the generated IR,
if it's only the builder that needs to loop then it should usually have an updated
reference to the most recent assigned register which will still be valid because it's
within the same block.
"""
return context.ssa.read_variable(reg.name, reg.atype, context.block_builder.active_block)