-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
ir_utils.py
2167 lines (1924 loc) · 83.8 KB
/
ir_utils.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
#
# Copyright (c) 2017 Intel Corporation
# SPDX-License-Identifier: BSD-2-Clause
#
import numpy
import types as pytypes
import collections
import operator
import warnings
from llvmlite import ir as lir
import numba
from numba.core.extending import _Intrinsic
from numba.core import types, utils, typing, ir, analysis, postproc, rewrites, config, cgutils
from numba.core.typing.templates import (signature, infer_global,
AbstractTemplate)
from numba.core.imputils import impl_ret_untracked
from numba.core.analysis import (compute_live_map, compute_use_defs,
compute_cfg_from_blocks)
from numba.core.errors import (TypingError, UnsupportedError,
NumbaPendingDeprecationWarning, NumbaWarning,
feedback_details, CompilerError)
import copy
_unique_var_count = 0
def mk_unique_var(prefix):
global _unique_var_count
var = prefix + "." + str(_unique_var_count)
_unique_var_count = _unique_var_count + 1
return var
_max_label = 0
def get_unused_var_name(prefix, var_table):
""" Get a new var name with a given prefix and
make sure it is unused in the given variable table.
"""
cur = 0
while True:
var = prefix + str(cur)
if var not in var_table:
return var
cur += 1
def next_label():
global _max_label
_max_label += 1
return _max_label
def mk_alloc(typemap, calltypes, lhs, size_var, dtype, scope, loc):
"""generate an array allocation with np.empty() and return list of nodes.
size_var can be an int variable or tuple of int variables.
"""
out = []
ndims = 1
size_typ = types.intp
if isinstance(size_var, tuple):
if len(size_var) == 1:
size_var = size_var[0]
size_var = convert_size_to_var(size_var, typemap, scope, loc, out)
else:
# tuple_var = build_tuple([size_var...])
ndims = len(size_var)
tuple_var = ir.Var(scope, mk_unique_var("$tuple_var"), loc)
if typemap:
typemap[tuple_var.name] = types.containers.UniTuple(
types.intp, ndims)
# constant sizes need to be assigned to vars
new_sizes = [convert_size_to_var(s, typemap, scope, loc, out)
for s in size_var]
tuple_call = ir.Expr.build_tuple(new_sizes, loc)
tuple_assign = ir.Assign(tuple_call, tuple_var, loc)
out.append(tuple_assign)
size_var = tuple_var
size_typ = types.containers.UniTuple(types.intp, ndims)
# g_np_var = Global(numpy)
g_np_var = ir.Var(scope, mk_unique_var("$np_g_var"), loc)
if typemap:
typemap[g_np_var.name] = types.misc.Module(numpy)
g_np = ir.Global('np', numpy, loc)
g_np_assign = ir.Assign(g_np, g_np_var, loc)
# attr call: empty_attr = getattr(g_np_var, empty)
empty_attr_call = ir.Expr.getattr(g_np_var, "empty", loc)
attr_var = ir.Var(scope, mk_unique_var("$empty_attr_attr"), loc)
if typemap:
typemap[attr_var.name] = get_np_ufunc_typ(numpy.empty)
attr_assign = ir.Assign(empty_attr_call, attr_var, loc)
# alloc call: lhs = empty_attr(size_var, typ_var)
typ_var = ir.Var(scope, mk_unique_var("$np_typ_var"), loc)
if typemap:
typemap[typ_var.name] = types.functions.NumberClass(dtype)
# assuming str(dtype) returns valid np dtype string
dtype_str = str(dtype)
if dtype_str=='bool':
# empty doesn't like 'bool' sometimes (e.g. kmeans example)
dtype_str = 'bool_'
np_typ_getattr = ir.Expr.getattr(g_np_var, dtype_str, loc)
typ_var_assign = ir.Assign(np_typ_getattr, typ_var, loc)
alloc_call = ir.Expr.call(attr_var, [size_var, typ_var], (), loc)
if calltypes:
calltypes[alloc_call] = typemap[attr_var.name].get_call_type(
typing.Context(), [size_typ, types.functions.NumberClass(dtype)], {})
# signature(
# types.npytypes.Array(dtype, ndims, 'C'), size_typ,
# types.functions.NumberClass(dtype))
alloc_assign = ir.Assign(alloc_call, lhs, loc)
out.extend([g_np_assign, attr_assign, typ_var_assign, alloc_assign])
return out
def convert_size_to_var(size_var, typemap, scope, loc, nodes):
if isinstance(size_var, int):
new_size = ir.Var(scope, mk_unique_var("$alloc_size"), loc)
if typemap:
typemap[new_size.name] = types.intp
size_assign = ir.Assign(ir.Const(size_var, loc), new_size, loc)
nodes.append(size_assign)
return new_size
assert isinstance(size_var, ir.Var)
return size_var
def get_np_ufunc_typ(func):
"""get type of the incoming function from builtin registry"""
for (k, v) in typing.npydecl.registry.globals:
if k == func:
return v
raise RuntimeError("type for func ", func, " not found")
def mk_range_block(typemap, start, stop, step, calltypes, scope, loc):
"""make a block that initializes loop range and iteration variables.
target label in jump needs to be set.
"""
# g_range_var = Global(range)
g_range_var = ir.Var(scope, mk_unique_var("$range_g_var"), loc)
typemap[g_range_var.name] = get_global_func_typ(range)
g_range = ir.Global('range', range, loc)
g_range_assign = ir.Assign(g_range, g_range_var, loc)
arg_nodes, args = _mk_range_args(typemap, start, stop, step, scope, loc)
# range_call_var = call g_range_var(start, stop, step)
range_call = ir.Expr.call(g_range_var, args, (), loc)
calltypes[range_call] = typemap[g_range_var.name].get_call_type(
typing.Context(), [types.intp] * len(args), {})
#signature(types.range_state64_type, types.intp)
range_call_var = ir.Var(scope, mk_unique_var("$range_c_var"), loc)
typemap[range_call_var.name] = types.iterators.RangeType(types.intp)
range_call_assign = ir.Assign(range_call, range_call_var, loc)
# iter_var = getiter(range_call_var)
iter_call = ir.Expr.getiter(range_call_var, loc)
calltypes[iter_call] = signature(types.range_iter64_type,
types.range_state64_type)
iter_var = ir.Var(scope, mk_unique_var("$iter_var"), loc)
typemap[iter_var.name] = types.iterators.RangeIteratorType(types.intp)
iter_call_assign = ir.Assign(iter_call, iter_var, loc)
# $phi = iter_var
phi_var = ir.Var(scope, mk_unique_var("$phi"), loc)
typemap[phi_var.name] = types.iterators.RangeIteratorType(types.intp)
phi_assign = ir.Assign(iter_var, phi_var, loc)
# jump to header
jump_header = ir.Jump(-1, loc)
range_block = ir.Block(scope, loc)
range_block.body = arg_nodes + [g_range_assign, range_call_assign,
iter_call_assign, phi_assign, jump_header]
return range_block
def _mk_range_args(typemap, start, stop, step, scope, loc):
nodes = []
if isinstance(stop, ir.Var):
g_stop_var = stop
else:
assert isinstance(stop, int)
g_stop_var = ir.Var(scope, mk_unique_var("$range_stop"), loc)
if typemap:
typemap[g_stop_var.name] = types.intp
stop_assign = ir.Assign(ir.Const(stop, loc), g_stop_var, loc)
nodes.append(stop_assign)
if start == 0 and step == 1:
return nodes, [g_stop_var]
if isinstance(start, ir.Var):
g_start_var = start
else:
assert isinstance(start, int)
g_start_var = ir.Var(scope, mk_unique_var("$range_start"), loc)
if typemap:
typemap[g_start_var.name] = types.intp
start_assign = ir.Assign(ir.Const(start, loc), g_start_var, loc)
nodes.append(start_assign)
if step == 1:
return nodes, [g_start_var, g_stop_var]
if isinstance(step, ir.Var):
g_step_var = step
else:
assert isinstance(step, int)
g_step_var = ir.Var(scope, mk_unique_var("$range_step"), loc)
if typemap:
typemap[g_step_var.name] = types.intp
step_assign = ir.Assign(ir.Const(step, loc), g_step_var, loc)
nodes.append(step_assign)
return nodes, [g_start_var, g_stop_var, g_step_var]
def get_global_func_typ(func):
"""get type variable for func() from builtin registry"""
for (k, v) in typing.templates.builtin_registry.globals:
if k == func:
return v
raise RuntimeError("func type not found {}".format(func))
def mk_loop_header(typemap, phi_var, calltypes, scope, loc):
"""make a block that is a loop header updating iteration variables.
target labels in branch need to be set.
"""
# iternext_var = iternext(phi_var)
iternext_var = ir.Var(scope, mk_unique_var("$iternext_var"), loc)
typemap[iternext_var.name] = types.containers.Pair(
types.intp, types.boolean)
iternext_call = ir.Expr.iternext(phi_var, loc)
calltypes[iternext_call] = signature(
types.containers.Pair(
types.intp,
types.boolean),
types.range_iter64_type)
iternext_assign = ir.Assign(iternext_call, iternext_var, loc)
# pair_first_var = pair_first(iternext_var)
pair_first_var = ir.Var(scope, mk_unique_var("$pair_first_var"), loc)
typemap[pair_first_var.name] = types.intp
pair_first_call = ir.Expr.pair_first(iternext_var, loc)
pair_first_assign = ir.Assign(pair_first_call, pair_first_var, loc)
# pair_second_var = pair_second(iternext_var)
pair_second_var = ir.Var(scope, mk_unique_var("$pair_second_var"), loc)
typemap[pair_second_var.name] = types.boolean
pair_second_call = ir.Expr.pair_second(iternext_var, loc)
pair_second_assign = ir.Assign(pair_second_call, pair_second_var, loc)
# phi_b_var = pair_first_var
phi_b_var = ir.Var(scope, mk_unique_var("$phi"), loc)
typemap[phi_b_var.name] = types.intp
phi_b_assign = ir.Assign(pair_first_var, phi_b_var, loc)
# branch pair_second_var body_block out_block
branch = ir.Branch(pair_second_var, -1, -1, loc)
header_block = ir.Block(scope, loc)
header_block.body = [iternext_assign, pair_first_assign,
pair_second_assign, phi_b_assign, branch]
return header_block
def legalize_names(varnames):
"""returns a dictionary for conversion of variable names to legal
parameter names.
"""
var_map = {}
for var in varnames:
new_name = var.replace("_", "__").replace("$", "_").replace(".", "_")
assert new_name not in var_map
var_map[var] = new_name
return var_map
def get_name_var_table(blocks):
"""create a mapping from variable names to their ir.Var objects"""
def get_name_var_visit(var, namevar):
namevar[var.name] = var
return var
namevar = {}
visit_vars(blocks, get_name_var_visit, namevar)
return namevar
def replace_var_names(blocks, namedict):
"""replace variables (ir.Var to ir.Var) from dictionary (name -> name)"""
# remove identity values to avoid infinite loop
new_namedict = {}
for l, r in namedict.items():
if l != r:
new_namedict[l] = r
def replace_name(var, namedict):
assert isinstance(var, ir.Var)
while var.name in namedict:
var = ir.Var(var.scope, namedict[var.name], var.loc)
return var
visit_vars(blocks, replace_name, new_namedict)
def replace_var_callback(var, vardict):
assert isinstance(var, ir.Var)
while var.name in vardict.keys():
assert(vardict[var.name].name != var.name)
new_var = vardict[var.name]
var = ir.Var(new_var.scope, new_var.name, new_var.loc)
return var
def replace_vars(blocks, vardict):
"""replace variables (ir.Var to ir.Var) from dictionary (name -> ir.Var)"""
# remove identity values to avoid infinite loop
new_vardict = {}
for l, r in vardict.items():
if l != r.name:
new_vardict[l] = r
visit_vars(blocks, replace_var_callback, new_vardict)
def replace_vars_stmt(stmt, vardict):
visit_vars_stmt(stmt, replace_var_callback, vardict)
def replace_vars_inner(node, vardict):
return visit_vars_inner(node, replace_var_callback, vardict)
# other packages that define new nodes add calls to visit variables in them
# format: {type:function}
visit_vars_extensions = {}
def visit_vars(blocks, callback, cbdata):
"""go over statements of block bodies and replace variable names with
dictionary.
"""
for block in blocks.values():
for stmt in block.body:
visit_vars_stmt(stmt, callback, cbdata)
return
def visit_vars_stmt(stmt, callback, cbdata):
# let external calls handle stmt if type matches
for t, f in visit_vars_extensions.items():
if isinstance(stmt, t):
f(stmt, callback, cbdata)
return
if isinstance(stmt, ir.Assign):
stmt.target = visit_vars_inner(stmt.target, callback, cbdata)
stmt.value = visit_vars_inner(stmt.value, callback, cbdata)
elif isinstance(stmt, ir.Arg):
stmt.name = visit_vars_inner(stmt.name, callback, cbdata)
elif isinstance(stmt, ir.Return):
stmt.value = visit_vars_inner(stmt.value, callback, cbdata)
elif isinstance(stmt, ir.Raise):
stmt.exception = visit_vars_inner(stmt.exception, callback, cbdata)
elif isinstance(stmt, ir.Branch):
stmt.cond = visit_vars_inner(stmt.cond, callback, cbdata)
elif isinstance(stmt, ir.Jump):
stmt.target = visit_vars_inner(stmt.target, callback, cbdata)
elif isinstance(stmt, ir.Del):
# Because Del takes only a var name, we make up by
# constructing a temporary variable.
var = ir.Var(None, stmt.value, stmt.loc)
var = visit_vars_inner(var, callback, cbdata)
stmt.value = var.name
elif isinstance(stmt, ir.DelAttr):
stmt.target = visit_vars_inner(stmt.target, callback, cbdata)
stmt.attr = visit_vars_inner(stmt.attr, callback, cbdata)
elif isinstance(stmt, ir.SetAttr):
stmt.target = visit_vars_inner(stmt.target, callback, cbdata)
stmt.attr = visit_vars_inner(stmt.attr, callback, cbdata)
stmt.value = visit_vars_inner(stmt.value, callback, cbdata)
elif isinstance(stmt, ir.DelItem):
stmt.target = visit_vars_inner(stmt.target, callback, cbdata)
stmt.index = visit_vars_inner(stmt.index, callback, cbdata)
elif isinstance(stmt, ir.StaticSetItem):
stmt.target = visit_vars_inner(stmt.target, callback, cbdata)
stmt.index_var = visit_vars_inner(stmt.index_var, callback, cbdata)
stmt.value = visit_vars_inner(stmt.value, callback, cbdata)
elif isinstance(stmt, ir.SetItem):
stmt.target = visit_vars_inner(stmt.target, callback, cbdata)
stmt.index = visit_vars_inner(stmt.index, callback, cbdata)
stmt.value = visit_vars_inner(stmt.value, callback, cbdata)
elif isinstance(stmt, ir.Print):
stmt.args = [visit_vars_inner(x, callback, cbdata) for x in stmt.args]
else:
# TODO: raise NotImplementedError("no replacement for IR node: ", stmt)
pass
return
def visit_vars_inner(node, callback, cbdata):
if isinstance(node, ir.Var):
return callback(node, cbdata)
elif isinstance(node, list):
return [visit_vars_inner(n, callback, cbdata) for n in node]
elif isinstance(node, tuple):
return tuple([visit_vars_inner(n, callback, cbdata) for n in node])
elif isinstance(node, ir.Expr):
# if node.op in ['binop', 'inplace_binop']:
# lhs = node.lhs.name
# rhs = node.rhs.name
# node.lhs.name = callback, cbdata.get(lhs, lhs)
# node.rhs.name = callback, cbdata.get(rhs, rhs)
for arg in node._kws.keys():
node._kws[arg] = visit_vars_inner(node._kws[arg], callback, cbdata)
elif isinstance(node, ir.Yield):
node.value = visit_vars_inner(node.value, callback, cbdata)
return node
add_offset_to_labels_extensions = {}
def add_offset_to_labels(blocks, offset):
"""add an offset to all block labels and jump/branch targets
"""
new_blocks = {}
for l, b in blocks.items():
# some parfor last blocks might be empty
term = None
if b.body:
term = b.body[-1]
for inst in b.body:
for T, f in add_offset_to_labels_extensions.items():
if isinstance(inst, T):
f_max = f(inst, offset)
if isinstance(term, ir.Jump):
b.body[-1] = ir.Jump(term.target + offset, term.loc)
if isinstance(term, ir.Branch):
b.body[-1] = ir.Branch(term.cond, term.truebr + offset,
term.falsebr + offset, term.loc)
new_blocks[l + offset] = b
return new_blocks
find_max_label_extensions = {}
def find_max_label(blocks):
max_label = 0
for l, b in blocks.items():
term = None
if b.body:
term = b.body[-1]
for inst in b.body:
for T, f in find_max_label_extensions.items():
if isinstance(inst, T):
f_max = f(inst)
if f_max > max_label:
max_label = f_max
if l > max_label:
max_label = l
return max_label
def flatten_labels(blocks):
"""makes the labels in range(0, len(blocks)), useful to compare CFGs
"""
# first bulk move the labels out of the rewrite range
blocks = add_offset_to_labels(blocks, find_max_label(blocks) + 1)
# order them in topo order because it's easier to read
new_blocks = {}
topo_order = find_topo_order(blocks)
l_map = dict()
idx = 0
for x in topo_order:
l_map[x] = idx
idx += 1
for t_node in topo_order:
b = blocks[t_node]
# some parfor last blocks might be empty
term = None
if b.body:
term = b.body[-1]
if isinstance(term, ir.Jump):
b.body[-1] = ir.Jump(l_map[term.target], term.loc)
if isinstance(term, ir.Branch):
b.body[-1] = ir.Branch(term.cond, l_map[term.truebr],
l_map[term.falsebr], term.loc)
new_blocks[l_map[t_node]] = b
return new_blocks
def remove_dels(blocks):
"""remove ir.Del nodes"""
for block in blocks.values():
new_body = []
for stmt in block.body:
if not isinstance(stmt, ir.Del):
new_body.append(stmt)
block.body = new_body
return
def remove_args(blocks):
"""remove ir.Arg nodes"""
for block in blocks.values():
new_body = []
for stmt in block.body:
if isinstance(stmt, ir.Assign) and isinstance(stmt.value, ir.Arg):
continue
new_body.append(stmt)
block.body = new_body
return
def dead_code_elimination(func_ir, typemap=None, alias_map=None,
arg_aliases=None):
""" Performs dead code elimination and leaves the IR in a valid state on
exit
"""
do_post_proc = False
while (remove_dead(func_ir.blocks, func_ir.arg_names, func_ir, typemap,
alias_map, arg_aliases)):
do_post_proc = True
if do_post_proc:
post_proc = postproc.PostProcessor(func_ir)
post_proc.run()
def remove_dead(blocks, args, func_ir, typemap=None, alias_map=None, arg_aliases=None):
"""dead code elimination using liveness and CFG info.
Returns True if something has been removed, or False if nothing is removed.
"""
cfg = compute_cfg_from_blocks(blocks)
usedefs = compute_use_defs(blocks)
live_map = compute_live_map(cfg, blocks, usedefs.usemap, usedefs.defmap)
call_table, _ = get_call_table(blocks)
if alias_map is None or arg_aliases is None:
alias_map, arg_aliases = find_potential_aliases(blocks, args, typemap,
func_ir)
if config.DEBUG_ARRAY_OPT >= 1:
print("remove_dead alias map:", alias_map)
print("live_map:", live_map)
print("usemap:", usedefs.usemap)
print("defmap:", usedefs.defmap)
# keep set for easier search
alias_set = set(alias_map.keys())
removed = False
for label, block in blocks.items():
# find live variables at each statement to delete dead assignment
lives = {v.name for v in block.terminator.list_vars()}
if config.DEBUG_ARRAY_OPT >= 2:
print("remove_dead processing block", label, lives)
# find live variables at the end of block
for out_blk, _data in cfg.successors(label):
if config.DEBUG_ARRAY_OPT >= 2:
print("succ live_map", out_blk, live_map[out_blk])
lives |= live_map[out_blk]
removed |= remove_dead_block(block, lives, call_table, arg_aliases,
alias_map, alias_set, func_ir, typemap)
return removed
# other packages that define new nodes add calls to remove dead code in them
# format: {type:function}
remove_dead_extensions = {}
def remove_dead_block(block, lives, call_table, arg_aliases, alias_map,
alias_set, func_ir, typemap):
"""remove dead code using liveness info.
Mutable arguments (e.g. arrays) that are not definitely assigned are live
after return of function.
"""
# TODO: find mutable args that are not definitely assigned instead of
# assuming all args are live after return
removed = False
# add statements in reverse order
new_body = [block.terminator]
# for each statement in reverse order, excluding terminator
for stmt in reversed(block.body[:-1]):
if config.DEBUG_ARRAY_OPT >= 2:
print("remove_dead_block", stmt)
# aliases of lives are also live
alias_lives = set()
init_alias_lives = lives & alias_set
for v in init_alias_lives:
alias_lives |= alias_map[v]
lives_n_aliases = lives | alias_lives | arg_aliases
# let external calls handle stmt if type matches
if type(stmt) in remove_dead_extensions:
f = remove_dead_extensions[type(stmt)]
stmt = f(stmt, lives, lives_n_aliases, arg_aliases, alias_map, func_ir,
typemap)
if stmt is None:
if config.DEBUG_ARRAY_OPT >= 2:
print("Statement was removed.")
removed = True
continue
# ignore assignments that their lhs is not live or lhs==rhs
if isinstance(stmt, ir.Assign):
lhs = stmt.target
rhs = stmt.value
if lhs.name not in lives and has_no_side_effect(
rhs, lives_n_aliases, call_table):
if config.DEBUG_ARRAY_OPT >= 2:
print("Statement was removed.")
removed = True
continue
if isinstance(rhs, ir.Var) and lhs.name == rhs.name:
if config.DEBUG_ARRAY_OPT >= 2:
print("Statement was removed.")
removed = True
continue
# TODO: remove other nodes like SetItem etc.
if isinstance(stmt, ir.Del):
if stmt.value not in lives:
if config.DEBUG_ARRAY_OPT >= 2:
print("Statement was removed.")
removed = True
continue
if isinstance(stmt, ir.SetItem):
name = stmt.target.name
if name not in lives_n_aliases:
if config.DEBUG_ARRAY_OPT >= 2:
print("Statement was removed.")
continue
if type(stmt) in analysis.ir_extension_usedefs:
def_func = analysis.ir_extension_usedefs[type(stmt)]
uses, defs = def_func(stmt)
lives -= defs
lives |= uses
else:
lives |= {v.name for v in stmt.list_vars()}
if isinstance(stmt, ir.Assign):
lives.remove(lhs.name)
new_body.append(stmt)
new_body.reverse()
block.body = new_body
return removed
# list of functions
remove_call_handlers = []
def remove_dead_random_call(rhs, lives, call_list):
if len(call_list) == 3 and call_list[1:] == ['random', numpy]:
return call_list[0] not in {'seed', 'shuffle'}
return False
remove_call_handlers.append(remove_dead_random_call)
def has_no_side_effect(rhs, lives, call_table):
""" Returns True if this expression has no side effects that
would prevent re-ordering.
"""
from numba.parfors import array_analysis, parfor
from numba.misc.special import prange
if isinstance(rhs, ir.Expr) and rhs.op == 'call':
func_name = rhs.func.name
if func_name not in call_table or call_table[func_name] == []:
return False
call_list = call_table[func_name]
if (call_list == ['empty', numpy] or
call_list == [slice] or
call_list == ['stencil', numba] or
call_list == ['log', numpy] or
call_list == ['dtype', numpy] or
call_list == [array_analysis.wrap_index] or
call_list == [prange] or
call_list == ['prange', numba] or
call_list == [parfor.internal_prange]):
return True
elif (isinstance(call_list[0], _Intrinsic) and
(call_list[0]._name == 'empty_inferred' or
call_list[0]._name == 'unsafe_empty_inferred')):
return True
from numba.core.registry import CPUDispatcher
from numba.np.linalg import dot_3_mv_check_args
if isinstance(call_list[0], CPUDispatcher):
py_func = call_list[0].py_func
if py_func == dot_3_mv_check_args:
return True
for f in remove_call_handlers:
if f(rhs, lives, call_list):
return True
return False
if isinstance(rhs, ir.Expr) and rhs.op == 'inplace_binop':
return rhs.lhs.name not in lives
if isinstance(rhs, ir.Yield):
return False
if isinstance(rhs, ir.Expr) and rhs.op == 'pair_first':
# don't remove pair_first since prange looks for it
return False
return True
is_pure_extensions = []
def is_pure(rhs, lives, call_table):
""" Returns True if every time this expression is evaluated it
returns the same result. This is not the case for things
like calls to numpy.random.
"""
if isinstance(rhs, ir.Expr):
if rhs.op == 'call':
func_name = rhs.func.name
if func_name not in call_table or call_table[func_name] == []:
return False
call_list = call_table[func_name]
if (call_list == [slice] or
call_list == ['log', numpy] or
call_list == ['empty', numpy]):
return True
for f in is_pure_extensions:
if f(rhs, lives, call_list):
return True
return False
elif rhs.op == 'getiter' or rhs.op == 'iternext':
return False
if isinstance(rhs, ir.Yield):
return False
return True
def is_const_call(module_name, func_name):
# Returns True if there is no state in the given module changed by the given function.
if module_name == 'numpy':
if func_name in ['empty']:
return True
return False
alias_analysis_extensions = {}
alias_func_extensions = {}
def find_potential_aliases(blocks, args, typemap, func_ir, alias_map=None,
arg_aliases=None):
"find all array aliases and argument aliases to avoid remove as dead"
if alias_map is None:
alias_map = {}
if arg_aliases is None:
arg_aliases = set(a for a in args if not is_immutable_type(a, typemap))
# update definitions since they are not guaranteed to be up-to-date
# FIXME keep definitions up-to-date to avoid the need for rebuilding
func_ir._definitions = build_definitions(func_ir.blocks)
np_alias_funcs = ['ravel', 'transpose', 'reshape']
for bl in blocks.values():
for instr in bl.body:
if type(instr) in alias_analysis_extensions:
f = alias_analysis_extensions[type(instr)]
f(instr, args, typemap, func_ir, alias_map, arg_aliases)
if isinstance(instr, ir.Assign):
expr = instr.value
lhs = instr.target.name
# only mutable types can alias
if is_immutable_type(lhs, typemap):
continue
if isinstance(expr, ir.Var) and lhs!=expr.name:
_add_alias(lhs, expr.name, alias_map, arg_aliases)
# subarrays like A = B[0] for 2D B
if (isinstance(expr, ir.Expr) and (expr.op == 'cast' or
expr.op in ['getitem', 'static_getitem'])):
_add_alias(lhs, expr.value.name, alias_map, arg_aliases)
# array attributes like A.T
if (isinstance(expr, ir.Expr) and expr.op == 'getattr'
and expr.attr in ['T', 'ctypes', 'flat']):
_add_alias(lhs, expr.value.name, alias_map, arg_aliases)
# a = b.c. a should alias b
if (isinstance(expr, ir.Expr) and expr.op == 'getattr'
and expr.value.name in arg_aliases):
_add_alias(lhs, expr.value.name, alias_map, arg_aliases)
# calls that can create aliases such as B = A.ravel()
if isinstance(expr, ir.Expr) and expr.op == 'call':
fdef = guard(find_callname, func_ir, expr, typemap)
# TODO: sometimes gufunc backend creates duplicate code
# causing find_callname to fail. Example: test_argmax
# ignored here since those cases don't create aliases
# but should be fixed in general
if fdef is None:
continue
fname, fmod = fdef
if fdef in alias_func_extensions:
alias_func = alias_func_extensions[fdef]
alias_func(lhs, expr.args, alias_map, arg_aliases)
if fmod == 'numpy' and fname in np_alias_funcs:
_add_alias(lhs, expr.args[0].name, alias_map, arg_aliases)
if isinstance(fmod, ir.Var) and fname in np_alias_funcs:
_add_alias(lhs, fmod.name, alias_map, arg_aliases)
# copy to avoid changing size during iteration
old_alias_map = copy.deepcopy(alias_map)
# combine all aliases transitively
for v in old_alias_map:
for w in old_alias_map[v]:
alias_map[v] |= alias_map[w]
for w in old_alias_map[v]:
alias_map[w] = alias_map[v]
return alias_map, arg_aliases
def _add_alias(lhs, rhs, alias_map, arg_aliases):
if rhs in arg_aliases:
arg_aliases.add(lhs)
else:
if rhs not in alias_map:
alias_map[rhs] = set()
if lhs not in alias_map:
alias_map[lhs] = set()
alias_map[rhs].add(lhs)
alias_map[lhs].add(rhs)
return
def is_immutable_type(var, typemap):
# Conservatively, assume mutable if type not available
if typemap is None or var not in typemap:
return False
typ = typemap[var]
# TODO: add more immutable types
if isinstance(typ, (types.Number, types.scalars._NPDatetimeBase,
types.containers.BaseTuple,
types.iterators.RangeType)):
return True
if typ==types.string:
return True
# consevatively, assume mutable
return False
def copy_propagate(blocks, typemap):
"""compute copy propagation information for each block using fixed-point
iteration on data flow equations:
in_b = intersect(predec(B))
out_b = gen_b | (in_b - kill_b)
"""
cfg = compute_cfg_from_blocks(blocks)
entry = cfg.entry_point()
# format: dict of block labels to copies as tuples
# label -> (l,r)
c_data = init_copy_propagate_data(blocks, entry, typemap)
(gen_copies, all_copies, kill_copies, in_copies, out_copies) = c_data
old_point = None
new_point = copy.deepcopy(out_copies)
# comparison works since dictionary of built-in types
while old_point != new_point:
for label in blocks.keys():
if label == entry:
continue
predecs = [i for i, _d in cfg.predecessors(label)]
# in_b = intersect(predec(B))
in_copies[label] = out_copies[predecs[0]].copy()
for p in predecs:
in_copies[label] &= out_copies[p]
# out_b = gen_b | (in_b - kill_b)
out_copies[label] = (gen_copies[label]
| (in_copies[label] - kill_copies[label]))
old_point = new_point
new_point = copy.deepcopy(out_copies)
if config.DEBUG_ARRAY_OPT >= 1:
print("copy propagate out_copies:", out_copies)
return in_copies, out_copies
def init_copy_propagate_data(blocks, entry, typemap):
"""get initial condition of copy propagation data flow for each block.
"""
# gen is all definite copies, extra_kill is additional ones that may hit
# for example, parfors can have control flow so they may hit extra copies
gen_copies, extra_kill = get_block_copies(blocks, typemap)
# set of all program copies
all_copies = set()
for l, s in gen_copies.items():
all_copies |= gen_copies[l]
kill_copies = {}
for label, gen_set in gen_copies.items():
kill_copies[label] = set()
for lhs, rhs in all_copies:
if lhs in extra_kill[label] or rhs in extra_kill[label]:
kill_copies[label].add((lhs, rhs))
# a copy is killed if it is not in this block and lhs or rhs are
# assigned in this block
assigned = {lhs for lhs, rhs in gen_set}
if ((lhs, rhs) not in gen_set
and (lhs in assigned or rhs in assigned)):
kill_copies[label].add((lhs, rhs))
# set initial values
# all copies are in for all blocks except entry
in_copies = {l: all_copies.copy() for l in blocks.keys()}
in_copies[entry] = set()
out_copies = {}
for label in blocks.keys():
# out_b = gen_b | (in_b - kill_b)
out_copies[label] = (gen_copies[label]
| (in_copies[label] - kill_copies[label]))
out_copies[entry] = gen_copies[entry]
return (gen_copies, all_copies, kill_copies, in_copies, out_copies)
# other packages that define new nodes add calls to get copies in them
# format: {type:function}
copy_propagate_extensions = {}
def get_block_copies(blocks, typemap):
"""get copies generated and killed by each block
"""
block_copies = {}
extra_kill = {}
for label, block in blocks.items():
assign_dict = {}
extra_kill[label] = set()
# assignments as dict to replace with latest value
for stmt in block.body:
for T, f in copy_propagate_extensions.items():
if isinstance(stmt, T):
gen_set, kill_set = f(stmt, typemap)
for lhs, rhs in gen_set:
assign_dict[lhs] = rhs
# if a=b is in dict and b is killed, a is also killed
new_assign_dict = {}
for l, r in assign_dict.items():
if l not in kill_set and r not in kill_set:
new_assign_dict[l] = r
if r in kill_set:
extra_kill[label].add(l)
assign_dict = new_assign_dict
extra_kill[label] |= kill_set
if isinstance(stmt, ir.Assign):
lhs = stmt.target.name
if isinstance(stmt.value, ir.Var):
rhs = stmt.value.name
# copy is valid only if same type (see
# TestCFunc.test_locals)
# Some transformations can produce assignments of the
# form A = A. We don't put these mapping in the
# copy propagation set because then you get cycles and
# infinite loops in the replacement phase.
if typemap[lhs] == typemap[rhs] and lhs != rhs:
assign_dict[lhs] = rhs
continue
if isinstance(stmt.value,
ir.Expr) and stmt.value.op == 'inplace_binop':
in1_var = stmt.value.lhs.name
in1_typ = typemap[in1_var]
# inplace_binop assigns first operand if mutable
if not (isinstance(in1_typ, types.Number)
or in1_typ == types.string):
extra_kill[label].add(in1_var)
# if a=b is in dict and b is killed, a is also killed
new_assign_dict = {}
for l, r in assign_dict.items():
if l != in1_var and r != in1_var:
new_assign_dict[l] = r
if r == in1_var:
extra_kill[label].add(l)
assign_dict = new_assign_dict
extra_kill[label].add(lhs)
block_cps = set(assign_dict.items())
block_copies[label] = block_cps
return block_copies, extra_kill
# other packages that define new nodes add calls to apply copy propagate in them
# format: {type:function}
apply_copy_propagate_extensions = {}
def apply_copy_propagate(blocks, in_copies, name_var_table, typemap, calltypes,
save_copies=None):
"""apply copy propagation to IR: replace variables when copies available"""
# save_copies keeps an approximation of the copies that were applied, so
# that the variable names of removed user variables can be recovered to some
# extent.
if save_copies is None:
save_copies = []
for label, block in blocks.items():
var_dict = {l: name_var_table[r] for l, r in in_copies[label]}
# assignments as dict to replace with latest value
for stmt in block.body:
if type(stmt) in apply_copy_propagate_extensions:
f = apply_copy_propagate_extensions[type(stmt)]
f(stmt, var_dict, name_var_table,
typemap, calltypes, save_copies)
# only rhs of assignments should be replaced
# e.g. if x=y is available, x in x=z shouldn't be replaced
elif isinstance(stmt, ir.Assign):
stmt.value = replace_vars_inner(stmt.value, var_dict)
else:
replace_vars_stmt(stmt, var_dict)
fix_setitem_type(stmt, typemap, calltypes)
for T, f in copy_propagate_extensions.items():
if isinstance(stmt, T):
gen_set, kill_set = f(stmt, typemap)
for lhs, rhs in gen_set: