forked from davemenendez/alive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloops.py
1489 lines (1110 loc) · 40.8 KB
/
loops.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
#import argparse, glob, re, sys
from language import *
from precondition import *
from parser import parse_opt_file
#from codegen import *
from itertools import combinations, izip, count, chain, imap
from copy import copy
import alive
from pprint import pprint, pformat
import logging
import collections
import subsets
NAME, PRE, SRC_BB, TGT_BB, SRC, TGT, SRC_USED, TGT_USED, TGT_SKIP = range(9)
logger = logging.getLogger(__name__)
def dump(instr):
if isinstance(instr, Instr) and hasattr(instr, 'name'):
return '<{0}|{1}>#{2}'.format(instr.getName(), instr, id(instr))
return '<{0}>#{1}'.format(instr, id(instr))
class Visitor(object):
def default(self, v, *args, **kw):
raise AliveError('{1}: No default behavior for <{0}>'.format(v,
type(self).__name__))
def __getattr__(self, name):
if name.startswith('visit_'):
return lambda *v, **kw: self.default(*v, **kw)
raise AttributeError
def base_visit(obj, visitor, *args, **kws):
return getattr(visitor, 'visit_' + obj.__class__.__name__)(obj, *args, **kws)
# monkeypatch Value to handle visiting
Value.visit = base_visit
BoolPred.visit = base_visit
class _DependencyFinder(Visitor):
def __init__(self, exclude = None, tag = None):
self.uses = {}
self.exclude = exclude or frozenset()
self.tag = tag or (lambda n: n)
def default(self, v):
return frozenset()
def __call__(self, v):
k = self.tag(v)
if k in self.exclude:
return frozenset()
if k in self.uses:
return self.uses[k]
r = v.visit(self)
self.uses[k] = r
return r
def subtree(self, v):
'If v is not excluded, generate v and its dependencies'
k = self.tag(v)
if k in self.exclude:
return
yield k
for d in self(v):
yield d
def visit_CopyOperand(self, v):
return frozenset(self.subtree(v.v))
def visit_BinOp(self, v):
return frozenset(chain(self.subtree(v.v1), self.subtree(v.v2)))
def visit_ConversionOp(self, v):
return frozenset(chain(self.subtree(v.v)))
def visit_Icmp(self, v):
return frozenset(chain(self.subtree(v.v1), self.subtree(v.v2)))
def visit_Select(self, v):
return frozenset(
chain(self.subtree(v.c), self.subtree(v.v1), self.subtree(v.v2)))
def visit_CnstUnaryOp(self, v):
return frozenset(self.subtree(v.v))
def visit_CnstBinaryOp(self, v):
return frozenset(chain(self.subtree(v.v1), self.subtree(v.v2)))
def visit_CnstFunction(self, v):
return frozenset(chain.from_iterable(self.subtree(a) for a in v.args))
def visit_PredNot(self, t):
return self(t.v)
def visit_PredAnd(self, t):
return frozenset.union(*(self(a) for a in t.args))
def visit_PredOr(self, t):
return frozenset.union(*(self(a) for a in t.args))
def visit_BinaryBoolPred(self, t):
return frozenset.union(self(t.v1), self(t.v2))
def visit_LLVMBoolPred(self, t):
return frozenset.union(*(self(a) for a in t.args))
def all_uses(value, tag=None):
'''
Recursively walk value and its dependencies. Return a map from values to
sets of subvalues.
'''
find = _DependencyFinder(tag=tag)
find(value)
return find.uses
class UnacceptableArgument(AliveError):
def __init__(self, cls, arg, val, msg = ''):
self.cls = cls
self.arg = arg
self.val = val
self.msg = msg
def __repr__(self):
return 'UnacceptableArgument({0.cls!r}, {0.arg!r},'\
' {0.val!r}, {0.msg!r})'.format(self)
def __str__(self):
msg = ', expected ' + self.msg if self.msg else ''
return 'Unacceptable argument for {0.cls} #{0.arg}: {0.val!r}{1}'.\
format(self, msg)
def isConstExpr(val):
if isinstance(val, Input):
return val.name[0] == 'C'
return isinstance(val, Constant)
class CopyBase(Visitor):
logger = logger.getChild('CopyBase')
def subtree(self, val, *xargs, **kws):
return self.default(val, *xargs, **kws)
def operand(self, val, *xargs, **kws):
return self.subtree(val, *xargs, **kws)
# -- instructions
def visit_CopyOperand(self, val, *xargs, **kws):
return CopyOperand(self.operand(val.v, *xargs, **kws), copy_type(val.type))
def visit_BinOp(self, val, *xargs, **kws):
return BinOp(val.op, copy_type(val.type),
self.operand(val.v1, *xargs, **kws),
self.operand(val.v2, *xargs, **kws),
copy(val.flags))
def visit_ConversionOp(self, term, *xargs, **kws):
return ConversionOp(term.op, copy_type(term.stype),
self.operand(term.v, *xargs, **kws),
copy_type(term.type))
def visit_Icmp(self, term, *xargs, **kws):
op = term.opname if term.op == Icmp.Var else Icmp.opnames[term.op]
return Icmp(op, copy_type(term.stype),
self.operand(term.v1, *xargs, **kws),
self.operand(term.v2, *xargs, **kws))
def visit_Select(self, term, *xargs, **kws):
c = self.operand(term.c, *xargs, **kws)
v1 = self.operand(term.v1, *xargs, **kws)
v2 = self.operand(term.v2, *xargs, **kws)
# if not isinstance(c.type, IntType):
# self.logger.info('visit_Select: narrowing type of %s', c)
# c.type = c.type.ensureIntType()
return Select(copy_type(term.type), c, v1, v2)
# -- constants
@staticmethod
def _ensure_constant(val, cls, arg):
if isinstance(val, Input) and val.name[0] == 'C':
return val
if isinstance(val, Constant):
return val
raise UnacceptableArgument(cls, arg, val, 'constant')
def visit_ConstantVal(self, val, *xargs, **kws):
return ConstantVal(val.val, copy_type(val.type))
def visit_UndefVal(self, val, *xargs, **kws):
return UndefVal(copy_type(val.type))
def visit_CnstUnaryOp(self, val, *xargs, **kws):
return CnstUnaryOp(val.op,
self._ensure_constant(self.subtree(val.v, *xargs, **kws), CnstUnaryOp, 1))
def visit_CnstBinaryOp(self, val, *xargs, **kws):
return CnstBinaryOp(val.op,
self._ensure_constant(self.subtree(val.v1, *xargs, **kws), CnstBinaryOp, 1),
self._ensure_constant(self.subtree(val.v2, *xargs, **kws), CnstBinaryOp, 2))
def visit_CnstFunction(self, val, *xargs, **kws):
#FIXME: Alive currently doesn't check arguments to constant functions
return CnstFunction(val.op, [self.operand(a, *xargs, **kws) for a in val.args],
copy_type(val.type))
# -- predicates
def visit_TruePred(self, term, *xargs, **kws):
return term # FIXME?
def visit_PredNot(self, term, *xargs, **kws):
return PredNot(self.subtree(term.v, *xargs, **kws))
def visit_PredAnd(self, term, *xargs, **kws):
return PredAnd(*(self.subtree(a, *xargs, **kws) for a in term.args))
def visit_PredOr(self, term, *xargs, **kws):
return PredOr(*(self.subtree(a, *xargs, **kws) for a in term.args))
def visit_BinaryBoolPred(self, term, *xargs, **kws):
return BinaryBoolPred(term.op,
self.subtree(term.v1, *xargs, **kws),
self.subtree(term.v2, *xargs, **kws))
def visit_LLVMBoolPred(self, term, *xargs, **kws):
args = []
for i,a in izip(count(1), term.args):
new = self.operand(a, *xargs, **kws)
ok, msg = LLVMBoolPred.argAccepts(term.op, i, new)
if not ok:
raise UnacceptableArgument(LLVMBoolPred.opnames[term.op], i, new, msg)
args.append(new)
return LLVMBoolPred(term.op, args)
class ShallowCopier(CopyBase):
def subtree(self, term):
return term
def rename_Instr(instr, name):
assert isinstance(instr, Instr)
new = instr.visit(ShallowCopier())
new.setName(name)
return new
class Copier(CopyBase):
'''Makes a deep copy of a value, renaming as requested.'''
def __init__(self, vars = {}, renamer = None):
if renamer is None: renamer = lambda n: n
self.renamer = renamer
self.vars = vars
def __call__(self, term):
if term in self.vars:
return self.vars[term]
new_term = term.visit(self)
self.vars[term] = new_term
if isinstance(new_term, Instr):
new_term.setName(self.renamer(term.getName()))
return new_term
def subtree(self, term):
return self(term)
def visit_Input(self, term):
return Input(self.renamer(term.getName()), copy_type(term.type))
def copy_type(ty):
'''Copy the argument into a new anonymous type.'''
assert isinstance(ty, Type)
if isinstance(ty, IntType):
if ty.defined:
return IntType(ty.size)
return IntType()
if isinstance(ty, PtrType):
return PtrType(copy_type(ty.type))
if isinstance(ty, NamedType):
return NamedType(ty.name)
if isinstance(ty, UnknownType):
if isinstance(ty, NamedType):
nty = NamedType(ty.name)
nty.type = copy_type(ty.type)
# TODO: rethink this
else:
nty = UnknownType()
nty.types = {}
nty.myType = ty.myType
for kind, subtype in ty.types.iteritems():
nty.types[kind] = copy_type(ty.types[kind])
return nty
if isinstance(ty, ArrayType):
#sys.stderr.write('WARNING: not copying array type {0}\n'.format(ty))
# FIXME: handle ArrayType better
return ArrayType()
assert False
# ----
class AliveTypeError(AliveError):
pass
class Printer(Visitor):
def __init__(self, names):
self.names = names
def visit_TruePred(self, t):
return "true"
def visit_PredNot(self, t):
return '!' + t.v.visit(self)
def visit_PredAnd(self, t):
return '(' + ' && '.join(s.visit(self) for s in t.args) + ')'
def visit_PredOr(self, t):
return '(' + ' || '.join(s.visit(self) for s in t.args) + ')'
def visit_BinaryBoolPred(self, t):
lhs = t.v1.getName() if t.v1 in self.names else repr(t.v1)
rhs = t.v2.getName() if t.v2 in self.names else repr(t.v2)
return '(%s %s %s)' % (lhs, t.opnames[t.op], rhs)
def visit_LLVMBoolPred(self, t):
args = (a.getName() if a in self.names else repr(a) for a in t.args)
return '%s(%s)' % (t.opnames[t.op], ', '.join(args))
class Transformation(object):
'''Represents a single Alive transformation (optimization).'''
def __init__(self, name, pre, src_bb, tgt_bb, src, tgt, src_used, tgt_used,
tgt_skip):
self.name = name
self.pre = pre
self.src_bb = src_bb
self.tgt_bb = tgt_bb
self.src = src
self.tgt = tgt
self.src_used = src_used
self.tgt_used = tgt_used
self.tgt_skip = tgt_skip
def src_root(self):
'''Returns the root value of the source (i.e., the last instruction)'''
values = self.src.values()
root = values.pop()
while not isinstance(root, Instr):
root = values.pop()
return root
def tgt_root(self):
'''Returns the root value of the target'''
return self.tgt[self.src_root().getName()]
def __str__(self):
def lines(bbs, skip):
for bb, instrs in bbs.iteritems():
if bb != '':
yield '%s:' % bb
for k,v in instrs.iteritems():
if k in skip:
continue
k = str(k)
if k[0] == '%':
yield ' %s = %s' % (k,v)
else:
yield ' %s' % v
names = self.src.values()
pre = self.pre.visit(Printer(names))
return 'Name: {0}\nPre: {1}\n{2}\n=>\n{3}'.format(
self.name, pre,
'\n'.join(lines(self.src_bb, set())),
'\n'.join(lines(self.tgt_bb, self.tgt_skip)))
def dump(self):
print str(self)
# print 'Name:', self.name
# print 'Pre:', str(self.pre)
# print_prog(self.src_bb, set())
# print '=>'
# print_prog(self.tgt_bb, self.tgt_skip)
# print
# print 'src', self.src
# print 'tgt', self.tgt
# print 'src_used', self.src_used
# print 'tgt_used', self.tgt_used
# print 'tgt_skip', self.tgt_skip
def copy(self, rename = None):
import copy
assert len(self.src_bb) == 1 and len(self.tgt_bb) == 1
# TODO: handle basic blocks
if rename is None:
rename = lambda n: n
src = collections.OrderedDict()
vars = {}
copier = Copier(vars, rename)
for k,v in self.src.iteritems():
new_v = copier(v)
src[new_v.getUniqueName()] = new_v
# print 'copy: Value {0}[{1}] => {2}[{3}]'.format(k,v,new_v.getUniqueName(),new_v)
# precondition
pre = copier(self.pre)
# target
tgt = collections.OrderedDict()
for k,v in self.tgt.iteritems():
new_v = copier(v)
tgt[new_v.getUniqueName()] = new_v
# print 'copy: Value {0}[{1}] => {2}[{3}]'.format(k,v,new_v.getUniqueName(),new_v)
# source basic blocks
src_bb = collections.OrderedDict()
for lab,bb in self.src_bb.iteritems():
new_bb = collections.OrderedDict()
for v in bb.itervalues():
new_v = vars[v]
new_bb[new_v.getUniqueName()] = new_v
src_bb[lab] = new_bb
# target basic blocks
tgt_bb = collections.OrderedDict()
for lab,bb in self.tgt_bb.iteritems():
new_bb = collections.OrderedDict()
for v in bb.itervalues():
new_v = vars[v]
new_bb[new_v.getUniqueName()] = new_v
tgt_bb[lab] = new_bb
# target skip list
tgt_skip = set(rename(k) for k in self.tgt_skip)
new = Transformation(self.name, pre, src_bb, tgt_bb, src, tgt,
None, None, tgt_skip)
return new
def type_models(self):
'''Yields all type models satisfying the transformation's type constraints.
'''
reset_pick_one_type()
global gbl_prev_flags
gbl_prev_flags = []
# infer allowed types for registers
type_src = getTypeConstraints(self.src)
type_tgt = getTypeConstraints(self.tgt)
type_pre = self.pre.getTypeConstraints()
s = SolverFor('QF_LIA')
s.add(type_pre)
if s.check() != sat:
raise AliveTypeError(self.name + ': Precondition does not type check')
# Only one type per variable/expression in the precondition is required.
for v in s.model().decls():
register_pick_one_type(v)
s.add(type_src)
unregister_pick_one_type(alive.get_smt_vars(type_src))
if s.check() != sat:
raise AliveTypeError(self.name + ': Source program does not type check')
s.add(type_tgt)
unregister_pick_one_type(alive.get_smt_vars(type_tgt))
if s.check() != sat:
raise AliveTypeError(self.name +
': Source and Target programs do not type check')
# Pointers are assumed to be either 32 or 64 bits
ptrsize = Int('ptrsize')
s.add(Or(ptrsize == 32, ptrsize == 64))
sneg = SolverFor('QF_LIA')
sneg.add(Not(mk_and([type_pre] + type_src + type_tgt)))
# temporarily disabled
# has_unreach = any(v.startswith('unreachable') for v in self.tgt.iterkeys())
# for v in self.src.iterkeys():
# if v[0] == '%' and v not in self.src_used and v not in self.tgt_used and\
# v in self.tgt_skip and not has_unreach:
#
# raise AliveError(self.name +
# ':ERROR: Temporary register %s unused and not overwritten' % v)
#
# for v in self.tgt.iterkeys():
# if v[0] == '%' and v not in self.tgt_used and v not in self.src:
# raise AliveError(self.name +
# ':ERROR: Temporary register %s unused and does not overwrite any'\
# ' Source register' % v)
# disabled because it doesn't seem necessary
# # build constraints that indicate the number of users for each register.
# users_count = countUsers(self.src_bb)
# users = {}
# for k in self.src.iterkeys():
# n_users = users_count.get(k)
# users[k] = [get_users_var(k) != n_users] if n_users else []
# pick one representative type for types in Pre
res = s.check()
assert res != unknown
if res == sat:
s2 = SolverFor('QF_LIA')
s2.add(s.assertions())
alive.pick_pre_types(s, s2)
while res == sat:
types = s.model()
yield types
alive.block_model(s, sneg, types)
res = s.check()
assert res != unknown
# ----
def is_const(value):
return isinstance(value, Constant) or (isinstance(value, Input) and value.name[0] == 'C')
class TaggedValue(subsets.Tag):
def __repr__(self):
if isinstance(self.val, Instr) and hasattr(self.val, 'name'):
return '{}({} = {})'.format(type(self).__name__, self.val.name, self.val)
return '{}({})'.format(type(self).__name__, self.val)
class Pattern(TaggedValue): pass
class Code(TaggedValue): pass
# --
class NoMatch(AliveError): pass
class PatternMatchBase(Visitor):
'''
Determine if code matches pattern.
Define subtree() for specializing recursive calls.
'''
logger = logger.getChild('PatternMatchBase')
def __call__(self, pattern, code):
self.logger.info('Matching (%s) (%s)', pattern, code)
if isinstance(pattern, Input) or isinstance(code, Input):
return
if pattern.__class__ is not code.__class__:
raise NoMatch
pattern.visit(self, code)
def visit_BinOp(self, pat, code):
if pat.op != code.op or any(f not in code.flags for f in pat.flags):
raise NoMatch
self.subtree(pat.v1, code.v1)
self.subtree(pat.v2, code.v2)
def visit_ConversionOp(self, pat, code):
# TODO: handle types?
if pat.op != code.op:
raise NoMatch
self.subtree(pat.v, code.v)
def visit_Icmp(self, pat, code):
if pat.op == Icmp.Var or code.op == Icmp.Var:
raise AliveError('Matcher: general icmp matching unsupported')
if pat.op != code.op:
raise NoMatch
self.subtree(pat.v1, code.v1)
self.subtree(pat.v2, code.v2)
def visit_Select(self, pat, code):
self.subtree(pat.c, code.c)
self.subtree(pat.v1, code.v1)
self.subtree(pat.v2, code.v2)
# TODO: other instructions
def visit_ConstantVal(self, pat, code):
if pat.val != code.val:
raise NoMatch
# NOTE: pattern should not contain constant expressions
class BFSMatcher(PatternMatchBase):
'''Queues subtree matches for later examination.'''
def __init__(self, queue):
self.queue = queue
def subtree(self, pat, code):
self.queue.append((Pattern(pat), Code(code)))
# --
class PatternMergeBase(Visitor):
'''
Given two values, treated as patterns, find their least upper bound, if any.
Override subtree() to define recursive behavior.
'''
logger = logger.getChild('PatternMergeBase')
def __call__(self, pat1, pat2):
self.logger.info('merging |%s| |%s|', pat1, pat2)
if isinstance(pat2, Input):
return pat1
if isinstance(pat1, Input):
return pat2
if pat1.__class__ is not pat2.__class__:
raise NoMatch
return pat1.visit(self, pat2)
def visit_BinOp(self, pat1, pat2):
if pat1.op != pat2.op:
raise NoMatch
v1 = self.subtree(pat1.v1, pat2.v1)
v2 = self.subtree(pat1.v2, pat2.v2)
flags = copy(pat1.flags)
flags.extend(f for f in pat2.flags if f not in pat1.flags)
if v1 is pat1.v1 and v2 is pat1.v2 and flags == pat1.flags:
return pat1
pat = BinOp(pat1.op, copy_type(pat1.type), v1, v2, flags)
pat.setName(pat1.getName())
return pat
def visit_ConversionOp(self, pat1, pat2):
if pat1.op != pat2.op:
raise NoMatch
v = self.subtree(pat1.v, pat2.v)
self.logger.warning('unifying <%s> and <%s> without checking types',
pat1.v, pat2.v)
if v is pat1.v:
return pat1
pat = ConversionOp(pat1.op, copy_type(pat1.stype), v, copy_type(pat1.type))
pat.setName(pat1.getName())
return pat
def visit_Icmp(self, pat1, pat2):
if pat1.op == Icmp.Var or pat2.op == Icmp.Var:
raise AliveError('PatternUnifier: general icmp unifying unsupported')
if pat1.op != pat2.op:
raise NoMatch
v1 = self.subtree(pat1.v1, pat2.v1)
v2 = self.subtree(pat1.v2, pat2.v2)
if v1 == pat1.v1 and v2 == pat2.v2:
return pat1
op = Icmp.opnames[pat1.op]
pat = Icmp(op, copy_type(pat1.stype), v1, v2)
pat.setName(pat1.getName())
return pat
def visit_Select(self, pat1, pat2):
c = self.subtree(pat1.c, pat2.c)
v1 = self.subtree(pat1.v1, pat2.v1)
v2 = self.subtree(pat1.v2, pat2.v2)
if (c,v1,v2) == (pat1.c, pat1.v1, pat1.v2):
return pat1
pat = Select(copy_type(pat1.type), c, v1, v2)
pat.setName(pat1.getName())
def visit_ConstantVal(self, pat1, pat2):
if pat1.val != pat2.val:
raise NoMatch
return pat1
def visit_UndefVal(self, pat1, pat2):
return pat1
# No other constant expressions can occur in patterns
class BFSPatternMerger(PatternMergeBase):
'''Queues subtree matches for later examination.'''
def __init__(self, queue):
self.queue = queue
def subtree(self, pat1, pat2):
self.queue.append((Pattern(pat1), Pattern(pat2)))
return pat1
# --
class Grafter(CopyBase):
logger = logger.getChild('Grafter')
def __init__(self, replace):
self.replace = replace
self.ids = collections.OrderedDict()
self.done = {}
self.depth = 0
def operand(self, term, tag):
new_term = self.subtree(term, tag)
name = new_term.getUniqueName()
if name not in self.ids:
self.logger.debug('Adding id %s := %s', name, new_term)
self.ids[name] = new_term
return new_term
def subtree(self, term, tag):
self.logger.debug('(%s) subtree %s |%s|#%s', self.depth, tag.__name__, term, id(term))
key = tag(term)
if key in self.done:
self.logger.debug('(%s) reusing %s', self.depth, self.done[key])
return self.done[key]
if key in self.replace:
self.logger.debug('substituting %s -> %s', key, self.replace[key])
return self.subtree(self.replace[key].val, type(self.replace[key]))
self.depth += 1
new_term = term.visit(self, tag)
self.depth -= 1
if isinstance(new_term, Instr) and not hasattr(new_term, 'name'):
name = term.getName()
i = 0
while name in self.ids:
i += 1
name = term.getName() + str(i)
new_term.setName(name)
if not isinstance(new_term, Constant) or isinstance(new_term, ConstantVal):
self.done[key] = new_term
return new_term
def visit_Input(self, term, tag):
if tag(term) in self.replace:
raise AliveError('Grafter: unexpected visit_Input({},{})'.format(term,tag.__name__))
name = term.getName()
i = 0
while name in self.ids:
i += 1
name = term.getName() + str(i)
self.logger.debug('new input %s for %s(%s)', name, tag.__name__, term)
new_term = Input(name, copy_type(term.type))
self.ids[name] = new_term
return new_term
# --
def _match_pattern(pat, code):
'''
Used by compose to determine whether the provided code matches the pattern.
'''
log = logger.getChild('compose.match_pattern')
subs = subsets.DisjointSubsets()
pinstr = {} # rep -> merge of all pattern instrs, if any
cinstr = {} # rep -> code instr, if any
def add_key(k):
if k in subs:
return subs.rep(k)
log.debug('New key: %s', k)
subs.add_key(k)
if isinstance(k, Pattern) and isinstance(k.val, Instr):
pinstr[k] = k
if isinstance(k, Code) and isinstance(k.val, Instr):
cinstr[k] = k
return k
worklist = collections.deque()
worklist.append((Pattern(pat), Code(code)))
match = BFSMatcher(worklist)
merge = BFSPatternMerger(worklist)
while worklist:
if log.isEnabledFor(logging.DEBUG):
log.debug('\nworklist: ' + str(worklist)
+ '\nsubsets:\n ' + pformat(subs._subset, indent=2)
+ '\npinstr:\n ' + pformat(pinstr, indent=2)
+ '\ncinstr:\n ' + pformat(cinstr, indent=2))
k1,k2 = worklist.popleft()
r1 = add_key(k1)
r2 = add_key(k2)
log.debug('Checking %s %s', r1, r2)
if subs.unified(r1, r2):
continue
subs.unify(r1,r2)
# make sure r1 is the new rep
if r2 == subs.rep(r1):
r1,r2 = r2,r1
# only one cinstr permitted
# FIXME: CopyOperand
if r1 in cinstr and r2 in cinstr:
log.info('reject: unified code instrs %s, %s', cinstr[r1], cinstr[r2])
raise NoMatch
# we need to match if one subset has a cinstr and the other has pinstrs
# pinstrs and cinstrs in the same subset have already matched
match_needed = \
(r1 in cinstr and r2 in pinstr) or (r2 in cinstr and r1 in pinstr)
# if r2 had a cinstr, move it to r1
if r2 in cinstr:
cinstr[r1] = cinstr.pop(r2)
# if both subsets had pinstrs, merge them
if r1 in pinstr and r2 in pinstr:
log.debug('merging %s %s', pinstr[r1], pinstr[r2])
pinstr[r1] = Pattern(merge(pinstr[r1].val, pinstr.pop(r2).val))
# if only r2 had a pinstr, move it to r1
if r2 in pinstr:
pinstr[r1] = pinstr.pop(r2)
# by now both the pinstr and cinstr have moved to r1
if match_needed:
log.debug('matching %s %s', pinstr[r1], cinstr[r1])
match(pinstr[r1].val, cinstr[r1].val)
assert all(r == subs.rep(r) for r in chain(pinstr, cinstr))
# if a subset has a pinstr and a cinstr, the cinstr will be at
# least as specific
pinstr.update(cinstr)
return subs, pinstr
def _cycle_check(subsets, dependencies, sorted, parents):
'''
Used by compose to find cycles. Basic DFS, except the arcs are
determined by uses and eqs.
'''
log = logger.getChild('cycle_check')
done = {} # False when key is in progress, True when complete
def search(rep):
log.info('searching %s', rep)
log.debug('done: %s', done)
if rep in done:
return not done[rep]
done[rep] = False
vals = subsets.subset(rep)
uses = frozenset(subsets.rep(d) for v in vals if isinstance(v.val, Instr)
for d in dependencies[v] if d in subsets)
for k in uses:
parents[k].add(rep)
cycle = any(search(k) for k in uses)
sorted.append(rep)
done[rep] = True
return cycle
return any(search(rep) for rep in subsets.reps() if rep not in done)
def _check_subset(rep, subs, rep_replace, equations, is_starter):
'''
Used by compose to determine if a subset is valid, and what its replacement
should be.
'''
log = logger.getChild('compose.check_subset')
subset = subs.subset(rep)
log.debug('checking %s: %s', rep, subset)
symbols = set(k for k in subset
if isinstance(k.val, Input) and k.val.name[0] == 'C')
cexprs = set(k for k in subset
if isinstance(k.val, Constant) and
not isinstance(k.val, ConstantVal))
lits = set(k for k in subset
if isinstance(k.val, ConstantVal))
lit_vals = set(k.val.val for k in lits)
# subset cannot contain constants and instrs
if rep in rep_replace and (symbols or cexprs or lit_vals):
log.info('reject: subset contains consts and instrs')
raise NoMatch
# if this is an instr, we're okay (?)
if rep in rep_replace:
return
if len(lit_vals) > 1:
log.info('reject: subset unifies distinct literals')
raise NoMatch
if lit_vals:
new_c = lits.pop()
rep_replace[rep] = new_c # choose a literal at random
equations.extend((new_c, c) for c in cexprs)
return
if cexprs:
# if any of our users will appear in the pattern, create a new symbol
if is_starter:
new_c = symbols.pop() if symbols else Code(Input('C0', IntType()))
else:
new_c = cexprs.pop()
rep_replace[rep] = new_c
equations.extend((new_c, c) for c in cexprs)
return
if symbols:
rep_replace[rep] = symbols.pop()
return
# this subset contains no instrs or constants, so it must be all inputs