-
Notifications
You must be signed in to change notification settings - Fork 11
/
logic.py
1692 lines (1540 loc) · 48.4 KB
/
logic.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 2020, Data61, CSIRO (ABN 41 687 119 230)
#
# SPDX-License-Identifier: BSD-2-Clause
#
import syntax
from syntax import word32T, word8T, boolT, builtinTs, Expr, Node
from syntax import true_term, false_term, mk_num
from syntax import foldr1
(mk_var, mk_plus, mk_uminus, mk_minus, mk_times, mk_modulus, mk_bwand, mk_eq,
mk_less_eq, mk_less, mk_implies, mk_and, mk_or, mk_not, mk_word32, mk_word8,
mk_word32_maybe, mk_cast, mk_memacc, mk_memupd, mk_arr_index, mk_arroffs,
mk_if, mk_meta_typ, mk_pvalid) = syntax.mks
from syntax import structs
from target_objects import trace, printout
def is_int (n):
return hasattr (n, '__int__')
def mk_eq_with_cast (a, c):
return mk_eq (a, mk_cast (c, a.typ))
def mk_rodata (m):
assert m.typ == builtinTs['Mem']
return Expr ('Op', boolT, name = 'ROData', vals = [m])
def cast_pair (((a, a_addr), (c, c_addr))):
if a.typ != c.typ and c.typ == boolT:
c = mk_if (c, mk_word32 (1), mk_word32 (0))
return ((a, a_addr), (mk_cast (c, a.typ), c_addr))
ghost_assertion_type = syntax.Type ('WordArray', 50, 32)
def split_scalar_globals (vs):
for i in range (len (vs)):
if vs[i].typ.kind != 'Word' and vs[i].typ != boolT:
break
else:
i = len (vs)
scalars = vs[:i]
global_vars = vs[i:]
for v in global_vars:
if v.typ not in [builtinTs['Mem'], builtinTs['Dom'],
builtinTs['HTD'], builtinTs['PMS'],
ghost_assertion_type]:
assert not "scalar_global split expected", vs
memT = builtinTs['Mem']
mems = [v for v in global_vars if v.typ == memT]
others = [v for v in global_vars if v.typ != memT]
return (scalars, mems, others)
def mk_vars (tups):
return [mk_var (nm, typ) for (nm, typ) in tups]
def split_scalar_pairs (var_pairs):
return split_scalar_globals (mk_vars (var_pairs))
def azip (xs, ys):
assert len (xs) == len (ys)
return zip (xs, ys)
def mk_mem_eqs (a_imem, c_imem, a_omem, c_omem, tags):
[a_imem] = a_imem
a_tag, c_tag = tags
(c_in, c_out) = (c_tag + '_IN', c_tag + '_OUT')
(a_in, a_out) = (a_tag + '_IN', a_tag + '_OUT')
if c_imem:
[c_imem] = c_imem
ieqs = [((a_imem, a_in), (c_imem, c_in)),
((mk_rodata (c_imem), c_in), (true_term, c_in))]
else:
ieqs = [((mk_rodata (a_imem), a_in), (true_term, c_in))]
if c_omem:
[a_m] = a_omem
[c_omem] = c_omem
oeqs = [((a_m, a_out), (c_omem, c_out)),
((mk_rodata (c_omem), c_out), (true_term, c_out))]
else:
oeqs = [((a_m, a_out), (a_imem, a_in)) for a_m in a_omem]
return (ieqs, oeqs)
def mk_fun_eqs (as_f, c_f, prunes = None):
(var_a_args, a_imem, glob_a_args) = split_scalar_pairs (as_f.inputs)
(var_c_args, c_imem, glob_c_args) = split_scalar_pairs (c_f.inputs)
(var_a_rets, a_omem, glob_a_rets) = split_scalar_pairs (as_f.outputs)
(var_c_rets, c_omem, glob_c_rets) = split_scalar_pairs (c_f.outputs)
(mem_ieqs, mem_oeqs) = mk_mem_eqs (a_imem, c_imem, a_omem, c_omem,
['ASM', 'C'])
if not prunes:
prunes = (var_a_args, var_a_args)
assert len (prunes[0]) == len (var_c_args), (params, var_a_args,
var_c_args, prunes)
a_map = dict (azip (prunes[1], var_a_args))
ivar_pairs = [((a_map[p], 'ASM_IN'), (c, 'C_IN')) for (p, c)
in azip (prunes[0], var_c_args) if p in a_map]
ovar_pairs = [((a_ret, 'ASM_OUT'), (c_ret, 'C_OUT')) for (a_ret, c_ret)
in azip (var_a_rets, var_c_rets)]
return (map (cast_pair, mem_ieqs + ivar_pairs),
map (cast_pair, mem_oeqs + ovar_pairs))
def mk_var_list (vs, typ):
return [syntax.mk_var (v, typ) for v in vs]
def mk_offs_sequence (init, offs, n, do_reverse = False):
r = range (n)
if do_reverse:
r.reverse ()
def mk_offs (n):
return Expr ('Num', init.typ, val = offs * n)
return [mk_plus (init, mk_offs (m)) for m in r]
def mk_stack_sequence (sp, offs, stack, typ, n, do_reverse = False):
return [(mk_memacc (stack, addr, typ), addr)
for addr in mk_offs_sequence (sp, offs, n, do_reverse)]
def mk_aligned (w, n):
assert w.typ.kind == 'Word'
mask = Expr ('Num', w.typ, val = ((1 << n) - 1))
return mk_eq (mk_bwand (w, mask), mk_num (0, w.typ))
def mk_eqs_arm_none_eabi_gnu (var_c_args, var_c_rets, c_imem, c_omem,
min_stack_size):
arg_regs = mk_var_list (['r0', 'r1', 'r2', 'r3'], word32T)
r0 = arg_regs[0]
sp = mk_var ('r13', word32T)
st = mk_var ('stack', builtinTs['Mem'])
r0_input = mk_var ('ret_addr_input', word32T)
sregs = mk_stack_sequence (sp, 4, st, word32T, len (var_c_args) + 1)
ret = mk_var ('ret', word32T)
preconds = [mk_aligned (sp, 2), mk_eq (ret, mk_var ('r14', word32T)),
mk_aligned (ret, 2), mk_eq (r0_input, r0),
mk_less_eq (min_stack_size, sp)]
post_eqs = [(x, x) for x in mk_var_list (['r4', 'r5', 'r6', 'r7', 'r8',
'r9', 'r10', 'r11', 'r13'], word32T)]
arg_seq = [(r, None) for r in arg_regs] + sregs
if len (var_c_rets) > 1:
# the 'return-too-much' issue.
# instead r0 is a save-returns-here pointer
arg_seq.pop (0)
preconds += [mk_aligned (r0, 2), mk_less_eq (sp, r0)]
save_seq = mk_stack_sequence (r0_input, 4, st, word32T,
len (var_c_rets))
save_addrs = [addr for (_, addr) in save_seq]
post_eqs += [(r0_input, r0_input)]
out_eqs = zip (var_c_rets, [x for (x, _) in save_seq])
out_eqs = [(c, mk_cast (a, c.typ)) for (c, a) in out_eqs]
init_save_seq = mk_stack_sequence (r0, 4, st, word32T,
len (var_c_rets))
(_, last_arg_addr) = arg_seq[len (var_c_args) - 1]
preconds += [mk_less_eq (sp, addr)
for (_, addr) in init_save_seq[-1:]]
if last_arg_addr:
preconds += [mk_less (last_arg_addr, addr)
for (_, addr) in init_save_seq[:1]]
else:
out_eqs = zip (var_c_rets, [r0])
save_addrs = []
arg_seq_addrs = [addr for ((_, addr), _) in zip (arg_seq, var_c_args)
if addr != None]
swrap = mk_stack_wrapper (sp, st, arg_seq_addrs)
swrap2 = mk_stack_wrapper (sp, st, save_addrs)
post_eqs += [(swrap, swrap2)]
mem = mk_var ('mem', builtinTs['Mem'])
(mem_ieqs, mem_oeqs) = mk_mem_eqs ([mem], c_imem, [mem], c_omem,
['ASM', 'C'])
addr = None
arg_eqs = [cast_pair (((a_x, 'ASM_IN'), (c_x, 'C_IN')))
for (c_x, (a_x, addr)) in zip (var_c_args, arg_seq)]
if addr:
preconds += [mk_less_eq (sp, addr)]
ret_eqs = [cast_pair (((a_x, 'ASM_OUT'), (c_x, 'C_OUT')))
for (c_x, a_x) in out_eqs]
preconds = [((a_x, 'ASM_IN'), (true_term, 'ASM_IN')) for a_x in preconds]
asm_invs = [((vin, 'ASM_IN'), (vout, 'ASM_OUT')) for (vin, vout) in post_eqs]
return (arg_eqs + mem_ieqs + preconds,
ret_eqs + mem_oeqs + asm_invs)
known_CPUs = {
'arm-none-eabi-gnu': mk_eqs_arm_none_eabi_gnu
}
def mk_fun_eqs_CPU (cpu_f, c_f, cpu_name, funcall_depth = 1):
cpu = known_CPUs[cpu_name]
(var_c_args, c_imem, glob_c_args) = split_scalar_pairs (c_f.inputs)
(var_c_rets, c_omem, glob_c_rets) = split_scalar_pairs (c_f.outputs)
return cpu (var_c_args, var_c_rets, c_imem, c_omem,
(funcall_depth * 256) + 256)
class Pairing:
def __init__ (self, tags, funs, eqs, notes = None):
[l_tag, r_tag] = tags
self.tags = tags
assert set (funs) == set (tags)
self.funs = funs
self.eqs = eqs
self.l_f = funs[l_tag]
self.r_f = funs[r_tag]
self.name = 'Pairing (%s (%s) <= %s (%s))' % (self.l_f,
l_tag, self.r_f, r_tag)
self.notes = {}
if notes != None:
self.notes.update (notes)
def __str__ (self):
return self.name
def __hash__ (self):
return hash (self.name)
def __eq__ (self, other):
return self.name == other.name and self.eqs == other.eqs
def __ne__ (self, other):
return not other or not self == other
def mk_pairing (functions, c_f, as_f, prunes = None, cpu = None):
fs = (functions[as_f], functions[c_f])
if cpu:
eqs = mk_fun_eqs_CPU (fs[0], fs[1], cpu,
funcall_depth = funcall_depth (functions, c_f))
else:
eqs = mk_fun_eqs (fs[0], fs[1], prunes = prunes)
return Pairing (['ASM', 'C'], {'C': c_f, 'ASM': as_f}, eqs)
def inst_eqs_pattern (pattern, params):
(pat_params, inp_eqs, out_eqs) = pattern
substs = [((x.name, x.typ), y)
for (pat_vs, vs) in azip (pat_params, params)
for (x, y) in azip (pat_vs, vs)]
substs = dict (substs)
subst = lambda x: var_subst (x, substs)
return ([(subst (x), subst (y)) for (x, y) in inp_eqs],
[(subst (x), subst (y)) for (x, y) in out_eqs])
def inst_eqs_pattern_tuples (pattern, params):
return inst_eqs_pattern (pattern, map (mk_vars, params))
def inst_eqs_pattern_exprs (pattern, params):
(inp_eqs, out_eqs) = inst_eqs_pattern (pattern, params)
return (foldr1 (mk_and, [mk_eq (a, c) for (a, c) in inp_eqs]),
foldr1 (mk_and, [mk_eq (a, c) for (a, c) in out_eqs]))
def var_match (var_exp, conc_exp, assigns):
if var_exp.typ != conc_exp.typ:
return False
if var_exp.kind == 'Var':
key = (var_exp.name, var_exp.typ)
if key in assigns:
return conc_exp == assigns[key]
else:
assigns[key] = conc_exp
return True
elif var_exp.kind == 'Op':
if conc_exp.kind != 'Op' or var_exp.name != conc_exp.name:
return False
return all ([var_match (a, b, assigns)
for (a, b) in azip (var_exp.vals, conc_exp.vals)])
else:
return False
def var_subst (var_exp, assigns, must_subst = True):
def substor (var_exp):
if var_exp.kind == 'Var':
k = (var_exp.name, var_exp.typ)
if must_subst or k in assigns:
return assigns[k]
else:
return None
else:
return None
return syntax.do_subst (var_exp, substor)
def recursive_term_subst (eqs, expr):
if expr in eqs:
return eqs[expr]
if expr.kind == 'Op':
vals = [recursive_term_subst (eqs, x) for x in expr.vals]
return syntax.adjust_op_vals (expr, vals)
return expr
def mk_accum_rewrites (typ):
x = mk_var ('x', typ)
y = mk_var ('y', typ)
z = mk_var ('z', typ)
i = mk_var ('i', typ)
return [(x, i, mk_plus (x, y), mk_plus (x, mk_times (i, y)),
y),
(x, i, mk_plus (y, x), mk_plus (x, mk_times (i, y)),
y),
(x, i, mk_minus (x, y), mk_minus (x, mk_times (i, y)),
mk_uminus (y)),
(x, i, mk_plus (mk_plus (x, y), z),
mk_plus (x, mk_times (i, mk_plus (y, z))),
mk_plus (y, z)),
(x, i, mk_plus (mk_plus (y, x), z),
mk_plus (x, mk_times (i, mk_plus (y, z))),
mk_plus (y, z)),
(x, i, mk_plus (y, mk_plus (x, z)),
mk_plus (x, mk_times (i, mk_plus (y, z))),
mk_plus (y, z)),
(x, i, mk_plus (y, mk_plus (z, x)),
mk_plus (x, mk_times (i, mk_plus (y, z))),
mk_plus (y, z)),
(x, i, mk_minus (mk_minus (x, y), z),
mk_minus (x, mk_times (i, mk_plus (y, z))),
mk_plus (y, z)),
]
def mk_all_accum_rewrites ():
return [rew for typ in [word8T, word32T, syntax.word16T,
syntax.word64T]
for rew in mk_accum_rewrites (typ)]
accum_rewrites = mk_all_accum_rewrites ()
def default_val (typ):
if typ.kind == 'Word':
return Expr ('Num', typ, val = 0)
elif typ == boolT:
return false_term
else:
assert not 'default value for type %s created', typ
trace_accumulators = []
def accumulator_closed_form (expr, (nm, typ), add_mask = None):
expr = toplevel_split_out_cast (expr)
n = get_bwand_mask (expr)
if n and not add_mask:
return accumulator_closed_form (expr.vals[0], (nm, typ),
add_mask = n)
for (x, i, pattern, rewrite, offset) in accum_rewrites:
var = mk_var (nm, typ)
ass = {(x.name, x.typ): var}
m = var_match (pattern, expr, ass)
if m:
x2_def = default_val (typ)
i2_def = default_val (word32T)
def do_rewrite (x2 = x2_def, i2 = i2_def):
ass[(x.name, x.typ)] = x2
ass[(i.name, i.typ)] = i2
vs = var_subst (rewrite, ass)
if add_mask:
vs = mk_bwand_mask (vs, add_mask)
return vs
offs = var_subst (offset, ass)
return (do_rewrite, offs)
if trace_accumulators:
trace ('no accumulator %s' % ((expr, nm, typ), ))
return (None, None)
def split_out_cast (expr, target_typ, bits):
"""given a word-type expression expr (of any word length),
compute a simplified expression expr' of the target type, which will
have the property that expr' && mask bits = cast expr,
where && is bitwise-and (BWAnd), mask n is the bitpattern set at the
bottom n bits, e.g. (1 << n) - 1, and cast is WordCast."""
if expr.is_op (['WordCast', 'WordCastSigned']):
[x] = expr.vals
if x.typ.num >= bits and expr.typ.num >= bits:
return split_out_cast (x, target_typ, bits)
else:
return mk_cast (expr, target_typ)
elif expr.is_op ('BWAnd'):
[x, y] = expr.vals
if y.kind == 'Num':
val = y.val
else:
val = 0
full_mask = (1 << bits) - 1
if val & full_mask == full_mask:
return split_out_cast (x, target_typ, bits)
else:
return mk_cast (expr, target_typ)
elif expr.is_op (['Plus', 'Minus']):
# rounding issues will appear if this arithmetic is done
# at a smaller number of bits than we'll eventually report
if expr.typ.num >= bits:
vals = [split_out_cast (x, target_typ, bits)
for x in expr.vals]
if expr.is_op ('Plus'):
return mk_plus (vals[0], vals[1])
else:
return mk_minus (vals[0], vals[1])
else:
return mk_cast (expr, target_typ)
else:
return mk_cast (expr, target_typ)
def toplevel_split_out_cast (expr):
bits = None
if expr.is_op (['WordCast', 'WordCastSigned']):
bits = min ([expr.typ.num, expr.vals[0].typ.num])
elif expr.is_op ('BWAnd'):
bits = get_bwand_mask (expr)
if bits:
expr = split_out_cast (expr, expr.typ, bits)
return mk_bwand_mask (expr, bits)
else:
return expr
two_powers = {}
def get_bwand_mask (expr):
"""recognise (x && mask) opers, where mask = ((1 << n) - 1)
for some n"""
if not expr.is_op ('BWAnd'):
return
[x, y] = expr.vals
if not y.kind == 'Num':
return
val = y.val & ((1 << (y.typ.num)) - 1)
if not two_powers:
for i in range (129):
two_powers[1 << i] = i
return two_powers.get (val + 1)
def mk_bwand_mask (expr, n):
return mk_bwand (expr, mk_num (((1 << n) - 1), expr.typ))
def end_addr (p, typ):
if typ[0] == 'Array':
(_, typ, n) = typ
sz = mk_times (mk_word32 (typ.size ()), n)
else:
assert typ[0] == 'Type', typ
(_, typ) = typ
sz = mk_word32 (typ.size ())
return mk_plus (p, mk_minus (sz, mk_word32 (1)))
def pvalid_assertion1 ((typ, k, p, pv), (typ2, k2, p2, pv2)):
"""first pointer validity assertion: incompatibility.
pvalid1 & pvalid2 --> non-overlapping OR somehow-contained.
typ/typ2 is ('Type', syntax.Type) or ('Array', Type, Expr) for
dynamically sized arrays.
"""
offs1 = mk_minus (p, p2)
cond1 = get_styp_condition (offs1, typ, typ2)
offs2 = mk_minus (p2, p)
cond2 = get_styp_condition (offs2, typ2, typ)
out1 = mk_less (end_addr (p, typ), p2)
out2 = mk_less (end_addr (p2, typ2), p)
return mk_implies (mk_and (pv, pv2), foldr1 (mk_or,
[cond1, cond2, out1, out2]))
def pvalid_assertion2 ((typ, k, p, pv), (typ2, k2, p2, pv2)):
"""second pointer validity assertion: implication.
pvalid1 & strictly-contained --> pvalid2
"""
if typ[0] == 'Array' and typ2[0] == 'Array':
# this is such a vague notion it's not worth it
return true_term
offs1 = mk_minus (p, p2)
cond1 = get_styp_condition (offs1, typ, typ2)
imp1 = mk_implies (mk_and (cond1, pv2), pv)
offs2 = mk_minus (p2, p)
cond2 = get_styp_condition (offs2, typ2, typ)
imp2 = mk_implies (mk_and (cond2, pv), pv2)
return mk_and (imp1, imp2)
def sym_distinct_assertion ((typ, p, pv), (start, end)):
out1 = mk_less (mk_plus (p, mk_word32 (typ.size () - 1)), mk_word32 (start))
out2 = mk_less (mk_word32 (end), p)
return mk_implies (pv, mk_or (out1, out2))
def norm_array_type (t):
if t[0] == 'Type' and t[1].kind == 'Array':
(_, atyp) = t
return ('Array', atyp.el_typ_symb, mk_word32 (atyp.num), 'Strong')
elif t[0] == 'Array' and len (t) == 3:
(_, typ, l) = t
# these derive from PArrayValid assertions. we know the array is
# at least this long, but it might be longer.
return ('Array', typ, l, 'Weak')
else:
return t
stored_styp_conditions = {}
def get_styp_condition (offs, inner_typ, outer_typ):
r = get_styp_condition_inner1 (inner_typ, outer_typ)
if not r:
return false_term
else:
return r (offs)
def get_styp_condition_inner1 (inner_typ, outer_typ):
inner_typ = norm_array_type (inner_typ)
outer_typ = norm_array_type (outer_typ)
k = (inner_typ, outer_typ)
if k in stored_styp_conditions:
return stored_styp_conditions[k]
r = get_styp_condition_inner2 (inner_typ, outer_typ)
stored_styp_conditions[k] = r
return r
def array_typ_size ((kind, el_typ, num, _)):
el_size = mk_word32 (el_typ.size ())
return mk_times (num, el_size)
def get_styp_condition_inner2 (inner_typ, outer_typ):
if inner_typ[0] == 'Array' and outer_typ[0] == 'Array':
(_, ityp, inum, _) = inner_typ
(_, otyp, onum, outer_bound) = outer_typ
# array fits in another array if the starting element is
# a sub-element, and if the size of the left array plus
# the offset fits in the right array
cond = get_styp_condition_inner1 (('Type', ityp), outer_typ)
isize = array_typ_size (inner_typ)
osize = array_typ_size (outer_typ)
if outer_bound == 'Strong' and cond:
return lambda offs: mk_and (cond (offs),
mk_less_eq (mk_plus (isize, offs), osize))
else:
return cond
elif inner_typ == outer_typ:
return lambda offs: mk_eq (offs, mk_word32 (0))
elif outer_typ[0] == 'Type' and outer_typ[1].kind == 'Struct':
conds = [(get_styp_condition_inner1 (inner_typ,
('Type', sf_typ)), mk_word32 (offs2))
for (_, offs2, sf_typ)
in structs[outer_typ[1].name].fields.itervalues()]
conds = [cond for cond in conds if cond[0]]
if conds:
return lambda offs: foldr1 (mk_or,
[c (mk_minus (offs, offs2))
for (c, offs2) in conds])
else:
return None
elif outer_typ[0] == 'Array':
(_, el_typ, n, bound) = outer_typ
cond = get_styp_condition_inner1 (inner_typ, ('Type', el_typ))
el_size = mk_word32 (el_typ.size ())
size = mk_times (n, el_size)
if bound == 'Strong' and cond:
return lambda offs: mk_and (mk_less (offs, size),
cond (mk_modulus (offs, el_size)))
elif cond:
return lambda offs: cond (mk_modulus (offs, el_size))
else:
return None
else:
return None
def all_vars_have_prop (expr, prop):
class Failed (Exception):
pass
def visit (expr):
if expr.kind != 'Var':
return
v2 = (expr.name, expr.typ)
if not prop (v2):
raise Failed ()
try:
expr.visit (visit)
return True
except Failed:
return False
def all_vars_in_set (expr, var_set):
return all_vars_have_prop (expr, lambda v: v in var_set)
def var_not_in_expr (var, expr):
v2 = (var.name, var.typ)
return all_vars_have_prop (expr, lambda v: v != v2)
def mk_array_size_ineq (typ, num, p):
align = typ.align ()
size = mk_times (mk_word32 (typ.size ()), num)
size_lim = ((2 ** 32) - 4) / typ.size ()
return mk_less_eq (num, mk_word32 (size_lim))
def mk_align_valid_ineq (typ, p):
if typ[0] == 'Type':
(_, typ) = typ
align = typ.align ()
size = mk_word32 (typ.size ())
size_req = []
else:
assert typ[0] == 'Array', typ
(kind, typ, num) = typ
align = typ.align ()
size = mk_times (mk_word32 (typ.size ()), num)
size_req = [mk_array_size_ineq (typ, num, p)]
assert align in [1, 4, 8]
w0 = mk_word32 (0)
if align > 1:
align_req = [mk_eq (mk_bwand (p, mk_word32 (align - 1)), w0)]
else:
align_req = []
return foldr1 (mk_and, align_req + size_req + [mk_not (mk_eq (p, w0)),
mk_implies (mk_less (w0, size),
mk_less_eq (p, mk_uminus (size)))])
# generic operations on function/problem graphs
def dict_list (xys, keys = None):
"""dict_list ([(1, 2), (1, 3), (2, 4)]) = {1: [2, 3], 2: [4]}"""
d = {}
for (x, y) in xys:
d.setdefault (x, [])
d[x].append (y)
if keys:
for x in keys:
d.setdefault (x, [])
return d
def compute_preds (nodes):
preds = dict_list ([(c, n) for n in nodes
for c in nodes[n].get_conts ()],
keys = nodes)
for n in ['Ret', 'Err']:
preds.setdefault (n, [])
preds = dict ([(n, sorted (set (ps)))
for (n, ps) in preds.iteritems ()])
return preds
def simplify_node_elementary(node):
if node.kind == 'Cond' and node.cond == true_term:
return Node ('Basic', node.left, [])
elif node.kind == 'Cond' and node.cond == false_term:
return Node ('Basic', node.right, [])
elif node.kind == 'Cond' and node.left == node.right:
return Node ('Basic', node.left, [])
else:
return node
def compute_var_flows (nodes, outputs, preds, override_lvals_rvals = {}):
# compute a graph of reverse var flows to pass to tarjan's algorithm
graph = {}
entries = ['Ret']
for (n, node) in nodes.iteritems ():
if node.kind == 'Basic':
for (lv, rv) in node.upds:
graph[(n, 'Post', lv)] = [(n, 'Pre', v)
for v in syntax.get_expr_var_set (rv)]
elif node.is_noop ():
pass
else:
if n in override_lvals_rvals:
(lvals, rvals) = override_lvals_rvals[n]
else:
rvals = syntax.get_node_rvals (node)
rvals = set (rvals.iteritems ())
lvals = set (node.get_lvals ())
if node.kind != 'Basic':
lvals = list (lvals) + ['PC']
entries.append ((n, 'Post', 'PC'))
for lv in lvals:
graph[(n, 'Post', lv)] = [(n, 'Pre', rv)
for rv in rvals]
graph['Ret'] = [(n, 'Post', v)
for n in preds['Ret'] for v in outputs (n)]
vs = set ([v for k in graph for (_, _, v) in graph[k]])
for v in vs:
for n in nodes:
graph.setdefault ((n, 'Post', v), [(n, 'Pre', v)])
graph[(n, 'Pre', v)] = [(n2, 'Post', v)
for n2 in preds[n]]
comps = tarjan (graph, entries)
return (graph, comps)
def mk_not_red (v):
if v.is_op ('Not'):
[v] = v.vals
return v
else:
return syntax.mk_not (v)
def cont_with_conds (nodes, n, conds):
while True:
if n not in nodes or nodes[n].kind != 'Cond':
return n
cond = nodes[n].cond
if cond in conds:
n = nodes[n].left
elif mk_not_red (cond) in conds:
n = nodes[n].right
else:
return n
def contextual_conds (nodes, preds):
"""computes a collection of conditions that can be assumed true
at any point in the node graph."""
pre_conds = {}
arc_conds = {}
visit = [n for n in nodes if not (preds[n])]
while visit:
n = visit.pop ()
if n not in nodes:
continue
in_arc_conds = [arc_conds.get ((pre, n), set ())
for pre in preds[n]]
if not in_arc_conds:
conds = set ()
else:
conds = set.intersection (* in_arc_conds)
if pre_conds.get (n) == conds:
continue
pre_conds[n] = conds
if n not in nodes:
continue
if nodes[n].kind == 'Cond' and nodes[n].left == nodes[n].right:
c_conds = [conds, conds]
elif nodes[n].kind == 'Cond':
c_conds = [nodes[n].cond, mk_not_red (nodes[n].cond)]
c_conds = [set.union (set ([c]), conds)
for c in c_conds]
else:
upds = set (nodes[n].get_lvals ())
c_conds = [set ([c for c in conds if
not set.intersection (upds,
syntax.get_expr_var_set (c))])]
for (cont, conds) in zip (nodes[n].get_conts (), c_conds):
arc_conds[(n, cont)] = conds
visit.append (cont)
return (arc_conds, pre_conds)
def contextual_cond_simps (nodes, preds):
"""a common pattern in architectures with conditional operations is
a sequence of instructions with the same condition.
we can usually then reduce to a single contional block.
b e => b-e
/ \ / \ => / \
a-c-d-f-g => a-c-f-g
this is sometimes important if b calculates a register that e uses
since variable dependency analysis will see this register escape via
the impossible path a-c-d-e
"""
(arc_conds, pre_conds) = contextual_conds (nodes, preds)
nodes = dict (nodes)
for n in nodes:
if nodes[n].kind == 'Cond':
continue
cont = nodes[n].cont
conds = arc_conds[(n, cont)]
cont2 = cont_with_conds (nodes, cont, conds)
if cont2 != cont:
nodes[n] = syntax.copy_rename (nodes[n],
({}, {cont: cont2}))
return nodes
def minimal_loop_node_set (p):
"""discover a minimal set of loop addresses, excluding some operations
using conditional instructions which are syntactically within the
loop but semantically must always be followed by an immediate loop
exit.
amounts to rerunning loop detection after contextual_cond_simps."""
loop_ns = set (p.loop_data)
really_in_loop = {}
nodes = contextual_cond_simps (p.nodes, p.preds)
def is_really_in_loop (n):
if n in really_in_loop:
return really_in_loop[n]
ns = []
r = None
while r == None:
ns.append (n)
if n not in loop_ns:
r = False
elif n in p.splittable_points (n):
r = True
else:
conts = [n2 for n2 in nodes[n].get_conts ()
if n2 != 'Err']
if len (conts) > 1:
r = True
else:
[n] = conts
for n in ns:
really_in_loop[n] = r
return r
return set ([n for n in loop_ns if is_really_in_loop (n)])
def possible_graph_divs (p, min_cost = 20, max_cost = 20, ratio = 0.85,
trace = None):
es = [e[0] for e in p.entries]
divs = []
direct_costs = {}
future_costs = {'Ret': set (), 'Err': set ()}
prev_costs = {}
int_costs = {}
fracs = {}
for n in p.nodes:
node = p.nodes[n]
if node.kind == 'Call':
cost = set ([(n, 20)])
elif p.loop_id (n):
cost = set ([(p.loop_id (n), 50)])
else:
cost = set ([(n, len (node.get_mem_accesses ()))])
cost.discard ((n, 0))
direct_costs[n] = cost
for n in p.tarjan_order:
prev_costs[n] = set.union (* ([direct_costs[n]]
+ [prev_costs.get (c, set ()) for c in p.preds[n]]))
for n in reversed (p.tarjan_order):
cont_costs = [future_costs.get (c, set ())
for c in p.nodes[n].get_conts ()]
cost = set.union (* ([direct_costs[n]] + cont_costs))
p_ct = sum ([c for (_, c) in prev_costs[n]])
future_costs[n] = cost
if p.nodes[n].kind != 'Cond' or p_ct > max_cost:
continue
ct = sum ([c for (_, c) in set.union (cost, prev_costs[n])])
if ct < min_cost:
continue
[c1, c2] = [sum ([c for (_, c)
in set.union (cs, prev_costs[n])])
for cs in cont_costs]
fracs[n] = ((c1 * c1) + (c2 * c2)) / (ct * ct * 1.0)
if fracs[n] < ratio:
divs.append (n)
divs.reverse ()
if trace != None:
trace[0] = (direct_costs, future_costs, prev_costs,
int_costs, fracs)
return divs
def compute_var_deps (nodes, outputs, preds, override_lvals_rvals = {},
trace = None):
# outs = list of (outname, retvars)
var_deps = {}
visit = set ()
visit.update (preds['Ret'])
visit.update (preds['Err'])
nodes = contextual_cond_simps (nodes, preds)
while visit:
n = visit.pop ()
node = simplify_node_elementary (nodes[n])
if n in override_lvals_rvals:
(lvals, rvals) = override_lvals_rvals[n]
lvals = set (lvals)
rvals = set (rvals)
elif node.is_noop ():
lvals = set ([])
rvals = set ([])
else:
rvals = syntax.get_node_rvals (node)
rvals = set (rvals.iteritems ())
lvals = set (node.get_lvals ())
cont_vs = set ()
for c in node.get_conts ():
if c == 'Ret':
cont_vs.update (outputs (n))
elif c == 'Err':
pass
else:
cont_vs.update (var_deps.get (c, []))
vs = set.union (rvals, cont_vs - lvals)
if n in var_deps and vs <= var_deps[n]:
continue
if trace and n in trace:
diff = vs - var_deps.get (n, set())
printout ('add %s at %d' % (diff, n))
printout (' %s, %s, %s, %s' % (len (vs), len (cont_vs), len (lvals), len (rvals)))
var_deps[n] = vs
visit.update (preds[n])
return var_deps
def compute_loop_var_analysis (p, var_deps, n, override_nodes = None):
if override_nodes == None:
nodes = p.nodes
else:
nodes = override_nodes
upd_vs = set ([v for n2 in p.loop_body (n)
if not nodes[n2].is_noop ()
for v in nodes[n2].get_lvals ()])
const_vs = set ([v for n2 in p.loop_body (n)
for v in var_deps[n2] if v not in upd_vs])
vca = compute_var_cycle_analysis (p, nodes, n,
const_vs, set (var_deps[n]))
vca = [(syntax.mk_var (nm, typ), data)
for ((nm, typ), data) in vca.items ()]
return vca
cvca_trace = []
cvca_diag = [False]
no_accum_expressions = set ()
def compute_var_cycle_analysis (p, nodes, n, const_vars, vs, diag = None):
if diag == None:
diag = cvca_diag[0]
cache = {}
del cvca_trace[:]
impossible_nodes = {}
loop = p.loop_body (n)
def warm_cache_before (n2, v):
cvca_trace.append ((n2, v))
cvca_trace.append ('(')
arc = []
for i in range (100000):
opts = [n3 for n3 in p.preds[n2] if n3 in loop
if v not in nodes[n3].get_lvals ()
if n3 != n
if (n3, v) not in cache]
if not opts:
break
n2 = opts[0]
arc.append (n2)
if not (len (arc) < 100000):
trace ('warmup overrun in compute_var_cycle_analysis')
trace ('chasing %s in %s' % (v, set (arc)))
assert False, (v, arc[-500:])
for n2 in reversed (arc):
var_eval_before (n2, v)
cvca_trace.append (')')
def var_eval_before (n2, v, do_cmp = True):
if (n2, v) in cache and do_cmp:
return cache[(n2, v)]
if n2 == n and do_cmp:
var_exp = mk_var (v[0], v[1])
vs = set ([v for v in [v] if v not in const_vars])
return (vs, var_exp)
warm_cache_before (n2, v)
ps = [n3 for n3 in p.preds[n2] if n3 in loop
if not node_impossible (n3)]
if not ps:
return None
vs = [var_eval_after (n3, v) for n3 in ps]
if not all ([v3 == vs[0] for v3 in vs]):
if diag:
trace ('vs disagree for %s @ %d: %s' % (v, n2, vs))
r = None
else:
r = vs[0]
if do_cmp:
cache[(n2, v)] = r
return r
def var_eval_after (n2, v):
node = nodes[n2]
if node.kind == 'Call' and v in node.rets:
if diag:
trace ('fetched %s from call at %d' % (v, n2))
return None
elif node.kind == 'Basic':
for (lv, val) in node.upds:
if lv == v:
return expr_eval_before (n2, val)
return var_eval_before (n2, v)
else:
return var_eval_before (n2, v)
def expr_eval_before (n2, expr):
if expr.kind == 'Op':
if expr.vals == []:
return (set(), expr)
vals = [expr_eval_before (n2, v)
for v in expr.vals]
if None in vals:
return None
s = set.union (* [s for (s, v) in vals])
if len(s) > 1:
if diag:
trace ('too many vars for %s @ %d: %s' % (expr, n2, s))
return None
return (s, Expr ('Op', expr.typ,
name = expr.name,
vals = [v for (s, v) in vals]))
elif expr.kind == 'Num':
return (set(), expr)
elif expr.kind == 'Var':
return var_eval_before (n2,
(expr.name, expr.typ))
else:
if diag:
trace ('Unwalkable expr %s' % expr)
return None
def node_impossible (n2):