-
Notifications
You must be signed in to change notification settings - Fork 11
/
search.py
1862 lines (1650 loc) · 57.3 KB
/
search.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 solver
from solver import mk_smt_expr, to_smt_expr, smt_expr
import check
from check import restr_others, loops_to_split, ProofNode
from rep_graph import (mk_graph_slice, vc_num, vc_offs, vc_upto,
vc_double_range, VisitCount, vc_offset_upto)
import rep_graph
from syntax import (mk_and, mk_cast, mk_implies, mk_not, mk_uminus, mk_var,
foldr1, boolT, word32T, word8T, builtinTs, true_term, false_term,
mk_word32, mk_word8, mk_times, Expr, Type, mk_or, mk_eq, mk_memacc,
mk_num, mk_minus, mk_plus, mk_less)
import syntax
import logic
from target_objects import trace, printout
import target_objects
import itertools
last_knowledge = [1]
class NoSplit(Exception):
pass
def get_loop_var_analysis_at (p, n):
k = ('search_loop_var_analysis', n)
if k in p.cached_analysis:
return p.cached_analysis[k]
for hook in target_objects.hooks ('loop_var_analysis'):
res = hook (p, n)
if res != None:
p.cached_analysis[k] = res
return res
var_deps = p.compute_var_dependencies ()
res = p.get_loop_var_analysis (var_deps, n)
p.cached_analysis[k] = res
return res
def get_loop_vars_at (p, n):
vs = [var for (var, data) in get_loop_var_analysis_at (p, n)
if data == 'LoopVariable'] + [mk_word32 (0)]
vs.sort ()
return vs
default_loop_N = 3
last_proof = [None]
def build_proof (p):
init_hyps = check.init_point_hyps (p)
proof = build_proof_rec (default_searcher, p, (), list (init_hyps))
trace ('Built proof for %s' % p.name)
printout (repr (proof))
last_proof[0] = proof
return proof
def split_sample_set (bound):
ns = (range (10) + range (10, 20, 2)
+ range (20, 40, 5) + range (40, 100, 10)
+ range (100, 1000, 50))
return [n for n in ns if n < bound]
last_find_split_limit = [0]
def find_split_limit (p, n, restrs, hyps, kind, bound = 51, must_find = True,
hints = [], use_rep = None):
tag = p.node_tags[n][0]
trace ('Finding split limit: %d (%s)' % (n, tag))
last_find_split_limit[0] = (p, n, restrs, hyps, kind)
if use_rep == None:
rep = mk_graph_slice (p, fast = True)
else:
rep = use_rep
check_order = hints + split_sample_set (bound) + [bound]
# bounds strictly outside this range won't be considered
bound_range = [0, bound]
best_bound_found = [None]
def check (i):
if i < bound_range[0]:
return True
if i > bound_range[1]:
return False
restrs2 = restrs + ((n, VisitCount (kind, i)), )
pc = rep.get_pc ((n, restrs2))
restrs3 = restr_others (p, restrs2, 2)
epc = rep.get_pc (('Err', restrs3), tag = tag)
hyp = mk_implies (mk_not (epc), mk_not (pc))
res = rep.test_hyp_whyps (hyp, hyps)
if res:
trace ('split limit found: %d' % i)
bound_range[1] = i - 1
best_bound_found[0] = i
else:
bound_range[0] = i + 1
return res
map (check, check_order)
while bound_range[0] <= bound_range[1]:
split = (bound_range[0] + bound_range[1]) / 2
check (split)
bound = best_bound_found[0]
if bound == None:
trace ('No split limit found for %d (%s).' % (n, tag))
if must_find:
assert not 'split limit found'
return bound
def get_split_limit (p, n, restrs, hyps, kind, bound = 51,
must_find = True, est_bound = 1, hints = None):
k = ('SplitLimit', n, restrs, tuple (hyps), kind)
if k in p.cached_analysis:
(lim, prev_bound) = p.cached_analysis[k]
if lim != None or bound <= prev_bound:
return lim
if hints == None:
hints = [est_bound, est_bound + 1, est_bound + 2]
res = find_split_limit (p, n, restrs, hyps, kind,
hints = hints, must_find = must_find, bound = bound)
p.cached_analysis[k] = (res, bound)
return res
def init_case_splits (p, hyps, tags = None):
if 'init_case_splits' in p.cached_analysis:
return p.cached_analysis['init_case_splits']
if tags == None:
tags = p.pairing.tags
poss = logic.possible_graph_divs (p)
if len (set ([p.node_tags[n][0] for n in poss])) < 2:
return None
rep = rep_graph.mk_graph_slice (p)
assert all ([p.nodes[n].kind == 'Cond' for n in poss])
pc_map = logic.dict_list ([(rep.get_pc ((c, ())), c)
for n in poss for c in p.nodes[n].get_conts ()
if c not in p.loop_data])
no_loop_restrs = tuple ([(n, vc_num (0)) for n in p.loop_heads ()])
err_pc_hyps = [rep_graph.pc_false_hyp ((('Err', no_loop_restrs), tag))
for tag in p.pairing.tags]
knowledge = EqSearchKnowledge (rep, hyps + err_pc_hyps, list (pc_map))
last_knowledge[0] = knowledge
pc_ids = knowledge.classify_vs ()
id_n_map = logic.dict_list ([(i, n) for (pc, i) in pc_ids.iteritems ()
for n in pc_map[pc]])
tag_div_ns = [[[n for n in ns if p.node_tags[n][0] == t] for t in tags]
for (i, ns) in id_n_map.iteritems ()]
split_pairs = [(l_ns[0], r_ns[0]) for (l_ns, r_ns) in tag_div_ns
if l_ns and r_ns]
p.cached_analysis['init_case_splits'] = split_pairs
return split_pairs
case_split_tr = []
def init_proof_case_split (p, restrs, hyps):
ps = init_case_splits (p, hyps)
if ps == None:
return None
p.cached_analysis.setdefault ('finished_init_case_splits', [])
fin = p.cached_analysis['finished_init_case_splits']
known_s = set.union (set (restrs), set (hyps))
for rs in fin:
if rs <= known_s:
return None
rep = rep_graph.mk_graph_slice (p)
no_loop_restrs = tuple ([(n, vc_num (0)) for n in p.loop_heads ()])
err_pc_hyps = [rep_graph.pc_false_hyp ((('Err', no_loop_restrs), tag))
for tag in p.pairing.tags]
for (n1, n2) in ps:
pc = rep.get_pc ((n1, ()))
if rep.test_hyp_whyps (pc, hyps + err_pc_hyps):
continue
if rep.test_hyp_whyps (mk_not (pc), hyps + err_pc_hyps):
continue
case_split_tr.append ((n1, restrs, hyps))
return ('CaseSplit', ((n1, p.node_tags[n1][0]), [n1, n2]))
fin.append (known_s)
return None
# TODO: deal with all the code duplication between these two searches
class EqSearchKnowledge:
def __init__ (self, rep, hyps, vs):
self.rep = rep
self.hyps = hyps
self.v_ids = dict ([(v, 1) for v in vs])
self.model_trace = []
self.facts = set ()
self.premise = foldr1 (mk_and, map (rep.interpret_hyp, hyps))
def add_model (self, m):
self.model_trace.append (m)
update_v_ids_for_model2 (self, self.v_ids, m)
def hyps_add_model (self, hyps):
if hyps:
test_expr = foldr1 (mk_and, hyps)
else:
# we want to learn something, either a new model, or
# that all hyps are true. if there are no hyps,
# learning they're all true is learning nothing.
# instead force a model
test_expr = false_term
test_expr = mk_implies (self.premise, test_expr)
m = {}
(r, _) = self.rep.solv.parallel_check_hyps ([(1, test_expr)],
{}, model = m)
if r == 'unsat':
if not hyps:
trace ('WARNING: EqSearchKnowledge: premise unsat.')
trace (" ... learning procedure isn't going to work.")
for hyp in hyps:
self.facts.add (hyp)
else:
assert r == 'sat', r
self.add_model (m)
def classify_vs (self):
while not self.facts:
hyps = v_id_eq_hyps (self.v_ids)
if not hyps:
break
self.hyps_add_model (hyps)
return self.v_ids
def update_v_ids_for_model2 (knowledge, v_ids, m):
# first update the live variables
ev = lambda v: eval_model_expr (m, knowledge.rep.solv, v)
groups = logic.dict_list ([((k, ev (v)), v)
for (v, k) in v_ids.iteritems ()])
v_ids.clear ()
for (i, kt) in enumerate (sorted (groups)):
for v in groups[kt]:
v_ids[v] = i
def v_id_eq_hyps (v_ids):
groups = logic.dict_list ([(k, v) for (v, k) in v_ids.iteritems ()])
hyps = []
for vs in groups.itervalues ():
for v in vs[1:]:
hyps.append (mk_eq (v, vs[0]))
return hyps
class SearchKnowledge:
def __init__ (self, rep, name, restrs, hyps, tags, cand_elts = None):
self.rep = rep
self.name = name
self.restrs = restrs
self.hyps = hyps
self.tags = tags
if cand_elts != None:
(loop_elts, r_elts) = cand_elts
else:
(loop_elts, r_elts) = ([], [])
(pairs, vs) = init_knowledge_pairs (rep, loop_elts, r_elts)
self.pairs = pairs
self.v_ids = vs
self.model_trace = []
self.facts = set ()
self.weak_splits = set ()
self.premise = syntax.true_term
self.live_pairs_trace = []
def add_model (self, m):
self.model_trace.append (m)
update_v_ids_for_model (self, self.pairs, self.v_ids, m)
def hyps_add_model (self, hyps, assert_progress = True):
if hyps:
test_expr = foldr1 (mk_and, hyps)
else:
# we want to learn something, either a new model, or
# that all hyps are true. if there are no hyps,
# learning they're all true is learning nothing.
# instead force a model
test_expr = false_term
test_expr = mk_implies (self.premise, test_expr)
m = {}
(r, _) = self.rep.solv.parallel_check_hyps ([(1, test_expr)],
{}, model = m)
if r == 'unsat':
if not hyps:
trace ('WARNING: SearchKnowledge: premise unsat.')
trace (" ... learning procedure isn't going to work.")
return
if assert_progress:
assert not (set (hyps) <= self.facts), hyps
for hyp in hyps:
self.facts.add (hyp)
else:
assert r == 'sat', r
self.add_model (m)
if assert_progress:
assert self.model_trace[-2:-1] != [m]
def eqs_add_model (self, eqs, assert_progress = True):
preds = [pred for vpair in eqs
for pred in expand_var_eqs (self, vpair)
if pred not in self.facts]
self.hyps_add_model (preds,
assert_progress = assert_progress)
def add_weak_split (self, eqs):
preds = [pred for vpair in eqs
for pred in expand_var_eqs (self, vpair)]
self.weak_splits.add (tuple (sorted (preds)))
def is_weak_split (self, eqs):
preds = [pred for vpair in eqs
for pred in expand_var_eqs (self, vpair)]
return tuple (sorted (preds)) in self.weak_splits
def init_knowledge_pairs (rep, loop_elts, cand_r_loop_elts):
trace ('Doing search knowledge setup now.')
v_is = [(i, i_offs, i_step,
[(v, i, i_offs, i_step) for v in get_loop_vars_at (rep.p, i)])
for (i, i_offs, i_step) in sorted (loop_elts)]
l_vtyps = set ([v[0].typ for (_, _, _, vs) in v_is for v in vs])
v_js = [(j, j_offs, j_step,
[(v, j, j_offs, j_step) for v in get_loop_vars_at (rep.p, j)
if v.typ in l_vtyps])
for (j, j_offs, j_step) in sorted (cand_r_loop_elts)]
vs = {}
for (_, _, _, var_vs) in v_is + v_js:
for v in var_vs:
vs[v] = (v[0].typ, True)
pairs = {}
for (i, i_offs, i_step, i_vs) in v_is:
for (j, j_offs, j_step, j_vs) in v_js:
pair = ((i, i_offs, i_step), (j, j_offs, j_step))
pairs[pair] = (i_vs, j_vs)
trace ('... done.')
return (pairs, vs)
def update_v_ids_for_model (knowledge, pairs, vs, m):
rep = knowledge.rep
# first update the live variables
groups = {}
for v in vs:
(k, const) = vs[v]
groups.setdefault (k, [])
groups[k].append ((v, const))
k_counter = 1
vs.clear ()
for k in groups:
for (const, xs) in split_group (knowledge, m, groups[k]):
for x in xs:
vs[x] = (k_counter, const)
k_counter += 1
# then figure out which pairings are still viable
needed_ks = set ()
zero = syntax.mk_word32 (0)
for (pair, data) in pairs.items ():
if data[0] == 'Failed':
continue
(lvs, rvs) = data
lv_ks = set ([vs[v][0] for v in lvs
if v[0] == zero or not vs[v][1]])
rv_ks = set ([vs[v][0] for v in rvs])
miss_vars = lv_ks - rv_ks
if miss_vars:
lv_miss = [v[0] for v in lvs if vs[v][0] in miss_vars]
pairs[pair] = ('Failed', lv_miss.pop ())
else:
needed_ks.update ([vs[v][0] for v in lvs + rvs])
# then drop any vars which are no longer relevant
for v in vs.keys ():
if vs[v][0] not in needed_ks:
del vs[v]
def get_entry_visits_up_to (rep, head, restrs, hyps):
"""get the set of nodes visited on the entry path entry
to the loop, up to and including the head point."""
k = ('loop_visits_up_to', head, restrs, tuple (hyps))
if k in rep.p.cached_analysis:
return rep.p.cached_analysis[k]
[entry] = get_loop_entry_sites (rep, restrs, hyps, head)
frontier = set ([entry])
up_to = set ()
loop = rep.p.loop_body (head)
while frontier:
n = frontier.pop ()
if n == head:
continue
new_conts = [n2 for n2 in rep.p.nodes[n].get_conts ()
if n2 in loop if n2 not in up_to]
up_to.update (new_conts)
frontier.update (new_conts)
rep.p.cached_analysis[k] = up_to
return up_to
def get_nth_visit_restrs (rep, restrs, hyps, i, visit_num):
"""get the nth (visit_num-th) visit to node i, using its loop head
as a restriction point. tricky because there may be a loop entry point
that brings us in with the loop head before i, or vice-versa."""
head = rep.p.loop_id (i)
if i in get_entry_visits_up_to (rep, head, restrs, hyps):
# node i is in the set visited on the entry path, so
# the head is visited no more often than it
offs = 0
else:
# these are visited after the head point on the entry path,
# so the head point is visited 1 more time than it.
offs = 1
return ((head, vc_num (visit_num + offs)), ) + restrs
def get_var_pc_var_list (knowledge, v_i):
rep = knowledge.rep
(v_i, i, i_offs, i_step) = v_i
def get_var (k):
restrs2 = get_nth_visit_restrs (rep, knowledge.restrs,
knowledge.hyps, i, k)
(pc, env) = rep.get_node_pc_env ((i, restrs2))
return (to_smt_expr (pc, env, rep.solv),
to_smt_expr (v_i, env, rep.solv))
return [get_var (i_offs + (k * i_step))
for k in [0, 1, 2]]
def expand_var_eqs (knowledge, (v_i, v_j)):
if v_j == 'Const':
pc_vs = get_var_pc_var_list (knowledge, v_i)
(_, v0) = pc_vs[0]
return [mk_implies (pc, mk_eq (v, v0))
for (pc, v) in pc_vs[1:]]
# sorting the vars guarantees we generate the same
# mem eqs each time which is important for the solver
(v_i, v_j) = sorted ([v_i, v_j])
pc_vs = zip (get_var_pc_var_list (knowledge, v_i),
get_var_pc_var_list (knowledge, v_j))
return [pred for ((pc_i, v_i), (pc_j, v_j)) in pc_vs
for pred in [mk_eq (pc_i, pc_j),
mk_implies (pc_i, logic.mk_eq_with_cast (v_i, v_j))]]
word_ops = {'bvadd':lambda x, y: x + y, 'bvsub':lambda x, y: x - y,
'bvmul':lambda x, y: x * y, 'bvurem':lambda x, y: x % y,
'bvudiv':lambda x, y: x / y, 'bvand':lambda x, y: x & y,
'bvor':lambda x, y: x | y, 'bvxor': lambda x, y: x ^ y,
'bvnot': lambda x: ~ x, 'bvneg': lambda x: - x,
'bvshl': lambda x, y: x << y, 'bvlshr': lambda x, y: x >> y}
bool_ops = {'=>':lambda x, y: (not x) or y, '=': lambda x, y: x == y,
'not': lambda x: not x, 'true': lambda: True, 'false': lambda: False}
word_ineq_ops = {'=': (lambda x, y: x == y, 'Unsigned'),
'bvult': (lambda x, y: x < y, 'Unsigned'),
'word32-eq': (lambda x, y: x == y, 'Unsigned'),
'bvule': (lambda x, y: x <= y, 'Unsigned'),
'bvsle': (lambda x, y: x <= y, 'Signed'),
'bvslt': (lambda x, y: x < y, 'Signed'),
}
def eval_model (m, s, toplevel = None):
if s in m:
return m[s]
if toplevel == None:
toplevel = s
if type (s) == str:
try:
result = solver.smt_to_val (s)
except Exception, e:
trace ('Error with eval_model')
trace (toplevel)
raise e
return result
op = s[0]
if op == 'ite':
[_, b, x, y] = s
b = eval_model (m, b, toplevel)
assert b in [false_term, true_term]
if b == true_term:
result = eval_model (m, x, toplevel)
else:
result = eval_model (m, y, toplevel)
m[s] = result
return result
xs = [eval_model (m, x, toplevel) for x in s[1:]]
if op[0] == '_' and op[1] in ['zero_extend', 'sign_extend']:
[_, ex_kind, n_extend] = op
n_extend = int (n_extend)
[x] = xs
assert x.typ.kind == 'Word' and x.kind == 'Num'
if ex_kind == 'sign_extend':
val = get_signed_val (x)
else:
val = get_unsigned_val (x)
result = mk_num (val, x.typ.num + n_extend)
elif op[0] == '_' and op[1] == 'extract':
[_, _, n_top, n_bot] = op
n_top = int (n_top)
n_bot = int (n_bot)
[x] = xs
assert x.typ.kind == 'Word' and x.kind == 'Num'
length = (n_top - n_bot) + 1
result = mk_num ((x.val >> n_bot) & ((1 << length) - 1), length)
elif op[0] == 'store-word32':
(m, p, v) = xs
(naming, eqs) = m
eqs = dict (eqs)
eqs[p.val] = v.val
eqs = tuple (sorted (eqs.items ()))
result = (naming, eqs)
elif op[0] == 'store-word8':
(m, p, v) = xs
p_al = p.val & -4
shift = (p.val & 3) * 8
(naming, eqs) = m
eqs = dict (eqs)
prev_v = eqs[p_al]
mask_v = prev_v & (((1 << 32) - 1) ^ (255 << shift))
new_v = mask_v | ((v.val & 255) << shift)
eqs[p.val] = new_v
eqs = tuple (sorted (eqs.items ()))
result = (naming, eqs)
elif op[0] == 'load-word32':
(m, p) = xs
(naming, eqs) = m
eqs = dict (eqs)
result = syntax.mk_word32 (eqs[p.val])
elif op[0] == 'load-word8':
(m, p) = xs
p_al = p.val & -4
shift = (p.val & 3) * 8
(naming, eqs) = m
eqs = dict (eqs)
v = (eqs[p_al] >> shift) & 255
result = syntax.mk_word8 (v)
elif xs and xs[0].typ.kind == 'Word' and op in word_ops:
for x in xs:
assert x.kind == 'Num', (s, op, x)
result = word_ops[op](* [x.val for x in xs])
result = result & ((1 << xs[0].typ.num) - 1)
result = Expr ('Num', xs[0].typ, val = result)
elif xs and xs[0].typ.kind == 'Word' and op in word_ineq_ops:
(oper, signed) = word_ineq_ops[op]
if signed == 'Signed':
result = oper (* map (get_signed_val, xs))
else:
assert signed == 'Unsigned'
result = oper (* [x.val for x in xs])
result = {True: true_term, False: false_term}[result]
elif op == 'and':
result = all ([x == true_term for x in xs])
result = {True: true_term, False: false_term}[result]
elif op == 'or':
result = bool ([x for x in xs if x == true_term])
result = {True: true_term, False: false_term}[result]
elif op in bool_ops:
assert all ([x.typ == boolT for x in xs])
result = bool_ops[op](* [x == true_term for x in xs])
result = {True: true_term, False: false_term}[result]
else:
assert not 's_expr handled', (s, op)
m[s] = result
return result
def get_unsigned_val (x):
assert x.typ.kind == 'Word'
assert x.kind == 'Num'
bits = x.typ.num
v = x.val & ((1 << bits) - 1)
return v
def get_signed_val (x):
assert x.typ.kind == 'Word'
assert x.kind == 'Num'
bits = x.typ.num
v = x.val & ((1 << bits) - 1)
if v >= (1 << (bits - 1)):
v = v - (1 << bits)
return v
def short_array_str (arr):
items = [('%x: %x' % (p.val * 4, v.val))
for (p, v) in arr.iteritems ()
if type (p) != str]
items.sort ()
return '{' + ', '.join (items) + '}'
def eval_model_expr (m, solv, v):
s = solver.smt_expr (v, {}, solv)
s_x = solver.parse_s_expression (s)
return eval_model (m, s_x)
def model_equal (m, knowledge, vpair):
preds = expand_var_eqs (knowledge, vpair)
for pred in preds:
x = eval_model_expr (m, knowledge.rep.solv, pred)
assert x in [syntax.true_term, syntax.false_term]
if x == syntax.false_term:
return False
return True
def get_model_trace (knowledge, m, v):
rep = knowledge.rep
pc_vs = get_var_pc_var_list (knowledge, v)
trace = []
for (pc, v) in pc_vs:
x = eval_model_expr (m, rep.solv, pc)
assert x in [syntax.true_term, syntax.false_term]
if x == syntax.false_term:
trace.append (None)
else:
trace.append (eval_model_expr (m, rep.solv, v))
return tuple (trace)
def split_group (knowledge, m, group):
group = list (set (group))
if group[0][0][0].typ == syntax.builtinTs['Mem']:
bins = []
for (v, const) in group:
for i in range (len (bins)):
if model_equal (m, knowledge,
(v, bins[i][1][0])):
bins[i][1].append (v)
break
else:
if const:
const = model_equal (m, knowledge,
(v, 'Const'))
bins.append ((const, [v]))
return bins
else:
bins = {}
for (v, const) in group:
trace = get_model_trace (knowledge, m, v)
if trace not in bins:
tconst = len (set (trace) - set ([None])) <= 1
bins[trace] = (const and tconst, [])
bins[trace][1].append (v)
return bins.values ()
def mk_pairing_v_eqs (knowledge, pair, endorsed = True):
v_eqs = []
(lvs, rvs) = knowledge.pairs[pair]
zero = mk_word32 (0)
for v_i in lvs:
(k, const) = knowledge.v_ids[v_i]
if const and v_i[0] != zero:
if not endorsed or eq_known (knowledge, (v_i, 'Const')):
v_eqs.append ((v_i, 'Const'))
continue
vs_j = [v_j for v_j in rvs if knowledge.v_ids[v_j][0] == k]
if endorsed:
vs_j = [v_j for v_j in vs_j
if eq_known (knowledge, (v_i, v_j))]
if not vs_j:
return None
v_j = vs_j[0]
v_eqs.append ((v_i, v_j))
return v_eqs
def eq_known (knowledge, vpair):
preds = expand_var_eqs (knowledge, vpair)
return set (preds) <= knowledge.facts
def find_split_loop (p, head, restrs, hyps, unfold_limit = 9,
node_restrs = None, trace_ind_fails = None):
assert p.loop_data[head][0] == 'Head'
assert p.node_tags[head][0] == p.pairing.tags[0]
# the idea is to loop through testable hyps, starting with ones that
# need smaller models (the most unfolded models will time out for
# large problems like finaliseSlot)
rep = mk_graph_slice (p, fast = True)
nec = get_necessary_split_opts (p, head, restrs, hyps)
if nec and nec[0] in ['CaseSplit', 'LoopUnroll']:
return nec
elif nec:
i_j_opts = nec
else:
i_j_opts = default_i_j_opts (unfold_limit)
if trace_ind_fails == None:
ind_fails = []
else:
ind_fails = trace_ind_fails
for (i_opts, j_opts) in i_j_opts:
result = find_split (rep, head, restrs, hyps,
i_opts, j_opts, node_restrs = node_restrs)
if result[0] != None:
return result
ind_fails.extend (result[1])
if ind_fails:
trace ('Warning: inductive failures: %s' % ind_fails)
raise NoSplit ()
def default_i_j_opts (unfold_limit = 9):
return mk_i_j_opts (unfold_limit = unfold_limit)
def mk_i_j_opts (i_seq_opts = None, j_seq_opts = None, unfold_limit = 9):
if i_seq_opts == None:
i_seq_opts = [(0, 1), (1, 1), (2, 1), (3, 1)]
if j_seq_opts == None:
j_seq_opts = [(0, 1), (0, 2), (1, 1), (1, 2),
(2, 1), (2, 2), (3, 1)]
all_opts = set (i_seq_opts + j_seq_opts)
def filt (opts, lim):
return [(start, step) for (start, step) in opts
if start + (2 * step) + 1 <= lim]
lims = [(filt (i_seq_opts, lim), filt (j_seq_opts, lim))
for lim in range (unfold_limit)
if [1 for (start, step) in all_opts
if start + (2 * step) + 1 == lim]]
lims = [(i_opts, j_opts) for (i_opts, j_opts) in lims
if i_opts and j_opts]
return lims
necessary_split_opts_trace = []
def get_interesting_linear_series_exprs (p, head):
k = ('interesting_linear_series', head)
if k in p.cached_analysis:
return p.cached_analysis[k]
res = logic.interesting_linear_series_exprs (p, head,
get_loop_var_analysis_at (p, head))
p.cached_analysis[k] = res
return res
def split_opt_test (p, tags = None):
if not tags:
tags = p.pairing.tags
heads = [head for head in init_loops_to_split (p, ())
if p.node_tags[head][0] == tags[0]]
hyps = check.init_point_hyps (p)
return [(head, get_necessary_split_opts (p, head, (), hyps))
for head in heads]
def interesting_linear_test (p):
p.do_analysis ()
for head in p.loop_heads ():
inter = get_interesting_linear_series_exprs (p, head)
hooks = target_objects.hooks ('loop_var_analysis')
n_exprs = [(n, expr, offs) for (n, vs) in inter.iteritems ()
if not [hook for hook in hooks if hook (p, n) != None]
for (kind, expr, offs) in vs]
if n_exprs:
rep = rep_graph.mk_graph_slice (p)
for (n, expr, offs) in n_exprs:
restrs = tuple ([(n2, vc) for (n2, vc)
in restr_others_both (p, (), 2, 2)
if p.loop_id (n2) != p.loop_id (head)])
vis1 = (n, ((head, vc_offs (1)), ) + restrs)
vis2 = (n, ((head, vc_offs (2)), ) + restrs)
pc = rep.get_pc (vis2)
imp = mk_implies (pc, mk_eq (rep.to_smt_expr (expr, vis2),
rep.to_smt_expr (mk_plus (expr, offs), vis1)))
assert rep.test_hyp_whyps (imp, [])
return True
last_necessary_split_opts = [0]
def get_necessary_split_opts (p, head, restrs, hyps, tags = None):
if not tags:
tags = p.pairing.tags
[l_tag, r_tag] = tags
last_necessary_split_opts[0] = (p, head, restrs, hyps, tags)
rep = rep_graph.mk_graph_slice (p, fast = True)
entries = get_loop_entry_sites (rep, restrs, hyps, head)
if len (entries) > 1:
return ('CaseSplit', ((entries[0], tags[0]), [entries[0]]))
for n in init_loops_to_split (p, restrs):
if p.node_tags[n][0] != r_tag:
continue
entries = get_loop_entry_sites (rep, restrs, hyps, n)
if len (entries) > 1:
return ('CaseSplit', ((entries[0], r_tag),
[entries[0]]))
stuff = linear_setup_stuff (rep, head, restrs, hyps, tags)
if stuff == None:
return None
seq_eqs = get_matching_linear_seqs (rep, head, restrs, hyps, tags)
vis = stuff['vis']
for v in seq_eqs:
if v[0] == 'LoopUnroll':
(_, n, est_bound) = v
lim = get_split_limit (p, n, restrs, hyps, 'Number',
est_bound = est_bound, must_find = False)
if lim != None:
return ('LoopUnroll', n)
continue
((n, expr), (n2, expr2), (l_start, l_step), (r_start, r_step),
_, _) = v
eqs = [rep_graph.eq_hyp ((expr,
(vis (n, l_start + (i * l_step)), l_tag)),
(expr2, (vis (n2, r_start + (i * r_step)), r_tag)))
for i in range (2)]
vis_hyp = rep_graph.pc_true_hyp ((vis (n, l_start), l_tag))
vis_hyps = [vis_hyp] + stuff['hyps']
eq = foldr1 (mk_and, map (rep.interpret_hyp, eqs))
m = {}
if rep.test_hyp_whyps (eq, vis_hyps, model = m):
trace ('found necessary split info: (%s, %s), (%s, %s)'
% (l_start, l_step, r_start, r_step))
return mk_i_j_opts ([(l_start + i, l_step)
for i in range (r_step + 1)],
[(r_start + i, r_step)
for i in range (l_step + 1)],
unfold_limit = 100)
n_vcs = entry_path_no_loops (rep, l_tag, m, head)
path_hyps = [rep_graph.pc_true_hyp ((n_vc, l_tag)) for n_vc in n_vcs]
if rep.test_hyp_whyps (eq, stuff['hyps'] + path_hyps):
# immediate case split on difference between entry paths
checks = [(stuff['hyps'], eq_hyp, 'eq')
for eq_hyp in eqs]
return derive_case_split (rep, n_vcs, checks)
necessary_split_opts_trace.append ((n, expr, (l_start, l_step),
(r_start, r_step), 'Seq check failed'))
return None
def linear_setup_stuff (rep, head, restrs, hyps, tags):
[l_tag, r_tag] = tags
k = ('linear_seq setup', head, restrs, tuple (hyps), tuple (tags))
p = rep.p
if k in p.cached_analysis:
return p.cached_analysis[k]
assert p.node_tags[head][0] == l_tag
l_seq_vs = get_interesting_linear_series_exprs (p, head)
if not l_seq_vs:
return None
r_seq_vs = {}
restr_env = {p.loop_id (head): restrs}
for n in init_loops_to_split (p, restrs):
if p.node_tags[n][0] != r_tag:
continue
vs = get_interesting_linear_series_exprs (p, n)
r_seq_vs.update (vs)
if not r_seq_vs:
return None
def vis (n, i):
restrs2 = get_nth_visit_restrs (rep, restrs, hyps, n, i)
return (n, restrs2)
smt = lambda expr, n, i: rep.to_smt_expr (expr, vis (n, i))
smt_pc = lambda n, i: rep.get_pc (vis (n, i))
# remove duplicates by concretising
l_seq_vs = dict ([(smt (expr, n, 2), (kind, n, expr, offs, oset))
for n in l_seq_vs
for (kind, expr, offs, oset) in l_seq_vs[n]]).values ()
r_seq_vs = dict ([(smt (expr, n, 2), (kind, n, expr, offs, oset))
for n in r_seq_vs
for (kind, expr, offs, oset) in r_seq_vs[n]]).values ()
hyps = hyps + [rep_graph.pc_triv_hyp ((vis (n, 3), r_tag))
for n in set ([n for (_, n, _, _, _) in r_seq_vs])]
hyps = hyps + [rep_graph.pc_triv_hyp ((vis (n, 3), l_tag))
for n in set ([n for (_, n, _, _, _) in l_seq_vs])]
hyps = hyps + [check.non_r_err_pc_hyp (tags,
restr_others (p, restrs, 2))]
r = {'l_seq_vs': l_seq_vs, 'r_seq_vs': r_seq_vs,
'hyps': hyps, 'vis': vis, 'smt': smt, 'smt_pc': smt_pc}
p.cached_analysis[k] = r
return r
def get_matching_linear_seqs (rep, head, restrs, hyps, tags):
k = ('matching linear seqs', head, restrs, tuple (hyps), tuple (tags))
p = rep.p
if k in p.cached_analysis:
v = p.cached_analysis[k]
(x, y) = itertools.tee (v[0])
v[0] = x
return y
[l_tag, r_tag] = tags
stuff = linear_setup_stuff (rep, head, restrs, hyps, tags)
if stuff == None:
return []
hyps = stuff['hyps']
vis = stuff['vis']
def get_model (n, offs):
m = {}
offs_smt = stuff['smt'] (offs, n, 1)
eq = mk_eq (mk_times (offs_smt, mk_num (4, offs_smt.typ)),
mk_num (0, offs_smt.typ))
ex_hyps = [rep_graph.pc_true_hyp ((vis (n, 1), l_tag)),
rep_graph.pc_true_hyp ((vis (n, 2), l_tag))]
res = rep.test_hyp_whyps (eq, hyps + ex_hyps, model = m)
if not m:
necessary_split_opts_trace.append ((n, kind, 'NoModel'))
return None
return m
r = (seq_eq
for (kind, n, expr, offs, oset) in sorted (stuff['l_seq_vs'])
if [v for v in stuff['r_seq_vs'] if v[0] == kind]
for m in [get_model (n, offs)]
if m
for seq_eq in [get_linear_seq_eq (rep, m, stuff,
(kind, n, expr, offs, oset)),
get_model_r_side_unroll (rep, tags, m,
restrs, hyps, stuff)]
if seq_eq != None)
(x, y) = itertools.tee (r)
p.cached_analysis[k] = [y]
return x
def get_linear_seq_eq (rep, m, stuff, expr_t1):
def get_int_min (expr):
v = eval_model_expr (m, rep.solv, expr)
assert v.kind == 'Num', v
vs = [v.val + (i << v.typ.num) for i in range (-2, 3)]
(_, v) = min ([(abs (v), v) for v in vs])
return v
(kind, n1, expr1, offs1, oset1) = expr_t1
smt = stuff['smt']
expr_init = smt (expr1, n1, 0)
expr_v = get_int_min (expr_init)
offs_v = get_int_min (smt (offs1, n1, 1))
r_seqs = [(n, expr, offs, oset2,
get_int_min (mk_minus (expr_init, smt (expr, n, 0))),
get_int_min (smt (offs, n, 0)))
for (kind2, n, expr, offs, oset2) in sorted (stuff['r_seq_vs'])
if kind2 == kind]
for (n, expr, offs2, oset2, diff, offs_v2) in sorted (r_seqs):
mult = offs_v / offs_v2
if offs_v % offs_v2 != 0 or mult > 8:
necessary_split_opts_trace.append ((n, expr,
'StepWrong', offs_v, offs_v2))
elif diff % offs_v2 != 0 or (diff * offs_v2) < 0 or (diff / offs_v2) > 8:
necessary_split_opts_trace.append ((n, expr,
'StartWrong', diff, offs_v2))
else:
return ((n1, expr1), (n, expr), (0, 1),
(diff / offs_v2, mult), (offs1, offs2),
(oset1, oset2))
return None
last_r_side_unroll = [None]
def get_model_r_side_unroll (rep, tags, m, restrs, hyps, stuff):
p = rep.p
[l_tag, r_tag] = tags
last_r_side_unroll[0] = (rep, tags, m, restrs, hyps, stuff)
r_kinds = set ([kind for (kind, n, _, _, _) in stuff['r_seq_vs']])
l_visited_ns_vcs = logic.dict_list ([(n, vc)
for (tag, n, vc) in rep.node_pc_env_order
if tag == l_tag
if eval_pc (rep, m, (n, vc))])
l_arc_interesting = [(n, vc, kind, expr)
for (n, vcs) in l_visited_ns_vcs.iteritems ()
if len (vcs) == 1
for vc in vcs
for (kind, expr)
in logic.interesting_node_exprs (p, n, tags = tags)
if kind in r_kinds
if expr.typ.kind == 'Word']
l_kinds = set ([kind for (n, vc, kind, _) in l_arc_interesting])
# FIXME: cloned
def canon_n (n, typ):
vs = [n + (i << typ.num) for i in range (-2, 3)]
(_, v) = min ([(abs (v), v) for v in vs])
return v
def get_int_min (expr):
v = eval_model_expr (m, rep.solv, expr)
assert v.kind == 'Num', v
return canon_n (v.val, v.typ)
def eval (expr, n, vc):
expr = rep.to_smt_expr (expr, (n, vc))
return get_int_min (expr)
val_interesting_map = logic.dict_list ([((kind, eval (expr, n, vc)), n)
for (n, vc, kind, expr) in l_arc_interesting])
smt = stuff['smt']
for (kind, n, expr, offs, _) in stuff['r_seq_vs']:
if kind not in l_kinds:
continue
if expr.typ.kind != 'Word':
continue
expr_n = get_int_min (smt (expr, n, 0))
offs_n = get_int_min (smt (offs, n, 0))
hit = ([i for i in range (64)
if (kind, canon_n (expr_n + (offs_n * i), expr.typ))