about summary refs log tree commit diff stats
path: root/src/miasm/expression/expression.py
blob: 4b0bbe6bbcfcaf0b7a052c6607e20e5017881205 (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
#
# Copyright (C) 2011 EADS France, Fabrice Desclaux <fabrice.desclaux@eads.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# These module implements Miasm IR components and basic operations related.
# IR components are :
#  - ExprInt
#  - ExprId
#  - ExprLoc
#  - ExprAssign
#  - ExprCond
#  - ExprMem
#  - ExprOp
#  - ExprSlice
#  - ExprCompose
#


from builtins import zip
from builtins import range
import warnings
import itertools
from builtins import int as int_types
from functools import cmp_to_key, total_ordering
from future.utils import viewitems

from miasm.core.utils import force_bytes, cmp_elts
from miasm.core.graph import DiGraph
from functools import reduce

# Define tokens
TOK_INF = "<"
TOK_INF_SIGNED = TOK_INF + "s"
TOK_INF_UNSIGNED = TOK_INF + "u"
TOK_INF_EQUAL = "<="
TOK_INF_EQUAL_SIGNED = TOK_INF_EQUAL + "s"
TOK_INF_EQUAL_UNSIGNED = TOK_INF_EQUAL + "u"
TOK_EQUAL = "=="
TOK_POS = "pos"
TOK_POS_STRICT = "Spos"

# Hashing constants
EXPRINT = 1
EXPRID = 2
EXPRLOC = 3
EXPRASSIGN = 4
EXPRCOND = 5
EXPRMEM = 6
EXPROP = 7
EXPRSLICE = 8
EXPRCOMPOSE = 9


priorities_list = [
    [ '+' ],
    [ '*', '/', '%'  ],
    [ '**' ],
    [ '-' ],	# Unary '-', associativity with + not handled
]

# dictionary from 'op' to priority, derived from above
priorities = dict((op, prio)
                  for prio, l in enumerate(priorities_list)
                  for op in l)
PRIORITY_MAX = len(priorities_list) - 1

def should_parenthesize_child(child, parent):
    if (isinstance(child, ExprId) or isinstance(child, ExprInt) or
        isinstance(child, ExprCompose) or isinstance(child, ExprMem) or
        isinstance(child, ExprSlice)):
        return False
    elif isinstance(child, ExprOp) and not child.is_infix():
        return False
    elif (isinstance(child, ExprCond) or isinstance(parent, ExprSlice)):
        return True
    elif (isinstance(child, ExprOp) and isinstance(parent, ExprOp)):
        pri_child = priorities.get(child.op, -1)
        pri_parent = priorities.get(parent.op, PRIORITY_MAX + 1)
        return pri_child < pri_parent
    else:
        return True

def str_protected_child(child, parent):
    return ("(%s)" % child) if should_parenthesize_child(child, parent) else str(child)


# Expression display


class DiGraphExpr(DiGraph):

    """Enhanced graph for Expression display
    Expression are displayed as a tree with node and edge labeled
    with only relevant information"""

    def node2str(self, node):
        if isinstance(node, ExprOp):
            return node.op
        elif isinstance(node, ExprId):
            return node.name
        elif isinstance(node, ExprLoc):
            return "%s" % node.loc_key
        elif isinstance(node, ExprMem):
            return "@%d" % node.size
        elif isinstance(node, ExprCompose):
            return "{ %d }" % node.size
        elif isinstance(node, ExprCond):
            return "? %d" % node.size
        elif isinstance(node, ExprSlice):
            return "[%d:%d]" % (node.start, node.stop)
        return str(node)

    def edge2str(self, nfrom, nto):
        if isinstance(nfrom, ExprCompose):
            for i in nfrom.args:
                if i[0] == nto:
                    return "[%s, %s]" % (i[1], i[2])
        elif isinstance(nfrom, ExprCond):
            if nfrom.cond == nto:
                return "?"
            elif nfrom.src1 == nto:
                return "True"
            elif nfrom.src2 == nto:
                return "False"

        return ""

def is_expr(expr):
    return isinstance(
        expr,
        (
            ExprInt, ExprId, ExprMem,
            ExprSlice, ExprCompose, ExprCond,
            ExprLoc, ExprOp
        )
    )

def is_associative(expr):
    "Return True iff current operation is associative"
    return (expr.op in ['+', '*', '^', '&', '|'])

def is_commutative(expr):
    "Return True iff current operation is commutative"
    return (expr.op in ['+', '*', '^', '&', '|'])

def canonize_to_exprloc(locdb, expr):
    """
    If expr is ExprInt, return ExprLoc with corresponding loc_key
    Else, return expr

    @expr: Expr instance
    """
    if expr.is_int():
        loc_key = locdb.get_or_create_offset_location(int(expr))
        ret = ExprLoc(loc_key, expr.size)
        return ret
    return expr

def is_function_call(expr):
    """Returns true if the considered Expr is a function call
    """
    return expr.is_op() and expr.op.startswith('call')

@total_ordering
class LocKey(object):
    def __init__(self, key):
        self._key = key

    key = property(lambda self: self._key)

    def __hash__(self):
        return hash(self._key)

    def __eq__(self, other):
        if self is other:
            return True
        if self.__class__ is not other.__class__:
            return False
        return self.key == other.key

    def __ne__(self, other):
        # required Python 2.7.14
        return not self == other

    def __lt__(self, other):
        return self.key < other.key

    def __repr__(self):
        return "<%s %d>" % (self.__class__.__name__, self._key)

    def __str__(self):
        return "loc_key_%d" % self.key


class ExprWalkBase(object):
    """
    Walk through sub-expressions, call @callback on them.
    If @callback returns a non None value, stop walk and return this value
    """

    def __init__(self, callback):
        self.callback = callback

    def visit(self, expr, *args, **kwargs):
        if expr.is_int() or expr.is_id() or expr.is_loc():
            pass
        elif expr.is_assign():
            ret = self.visit(expr.dst, *args, **kwargs)
            if ret:
                return ret
            src = self.visit(expr.src, *args, **kwargs)
            if ret:
                return ret
        elif expr.is_cond():
            ret = self.visit(expr.cond, *args, **kwargs)
            if ret:
                return ret
            ret = self.visit(expr.src1, *args, **kwargs)
            if ret:
                return ret
            ret = self.visit(expr.src2, *args, **kwargs)
            if ret:
                return ret
        elif expr.is_mem():
            ret = self.visit(expr.ptr, *args, **kwargs)
            if ret:
                return ret
        elif expr.is_slice():
            ret = self.visit(expr.arg, *args, **kwargs)
            if ret:
                return ret
        elif expr.is_op():
            for arg in expr.args:
                ret = self.visit(arg, *args, **kwargs)
                if ret:
                    return ret
        elif expr.is_compose():
            for arg in expr.args:
                ret = self.visit(arg, *args, **kwargs)
                if ret:
                    return ret
        else:
            raise TypeError("Visitor can only take Expr")

        ret = self.callback(expr, *args, **kwargs)
        return ret


class ExprWalk(ExprWalkBase):
    """
    Walk through sub-expressions, call @callback on them.
    If @callback returns a non None value, stop walk and return this value
    Use cache mechanism.
    """
    def __init__(self, callback):
        self.cache = set()
        self.callback = callback

    def visit(self, expr, *args, **kwargs):
        if expr in self.cache:
            return None
        ret = super(ExprWalk, self).visit(expr, *args, **kwargs)
        if ret:
            return ret
        self.cache.add(expr)
        return None


class ExprGetR(ExprWalkBase):
    """
    Return ExprId/ExprMem used by a given expression
    """
    def __init__(self, mem_read=False, cst_read=False):
        super(ExprGetR, self).__init__(lambda x:None)
        self.mem_read = mem_read
        self.cst_read = cst_read
        self.elements = set()
        self.cache = dict()

    def get_r_leaves(self, expr):
        if (expr.is_int() or expr.is_loc()) and self.cst_read:
            self.elements.add(expr)
        elif expr.is_mem():
            self.elements.add(expr)
        elif expr.is_id():
            self.elements.add(expr)

    def visit(self, expr, *args, **kwargs):
        cache_key = (expr, self.mem_read, self.cst_read)
        if cache_key in self.cache:
            return self.cache[cache_key]
        ret = self.visit_inner(expr, *args, **kwargs)
        self.cache[cache_key] = ret
        return ret

    def visit_inner(self, expr, *args, **kwargs):
        self.get_r_leaves(expr)
        if expr.is_mem() and not self.mem_read:
            # Don't visit memory sons
            return None

        if expr.is_assign():
            if expr.dst.is_mem() and self.mem_read:
                ret = super(ExprGetR, self).visit(expr.dst, *args, **kwargs)
            if expr.src.is_mem():
                self.elements.add(expr.src)
            self.get_r_leaves(expr.src)
            if expr.src.is_mem() and not self.mem_read:
                return None
            ret = super(ExprGetR, self).visit(expr.src, *args, **kwargs)
            return ret
        ret = super(ExprGetR, self).visit(expr, *args, **kwargs)
        return ret


class ExprVisitorBase(object):
    """
    Rebuild expression by visiting sub-expressions
    """
    def visit(self, expr, *args, **kwargs):
        if expr.is_int() or expr.is_id() or expr.is_loc():
            ret = expr
        elif expr.is_assign():
            dst = self.visit(expr.dst, *args, **kwargs)
            src = self.visit(expr.src, *args, **kwargs)
            ret = ExprAssign(dst, src)
        elif expr.is_cond():
            cond = self.visit(expr.cond, *args, **kwargs)
            src1 = self.visit(expr.src1, *args, **kwargs)
            src2 = self.visit(expr.src2, *args, **kwargs)
            ret = ExprCond(cond, src1, src2)
        elif expr.is_mem():
            ptr = self.visit(expr.ptr, *args, **kwargs)
            ret = ExprMem(ptr, expr.size)
        elif expr.is_slice():
            arg = self.visit(expr.arg, *args, **kwargs)
            ret = ExprSlice(arg, expr.start, expr.stop)
        elif expr.is_op():
            args = [self.visit(arg, *args, **kwargs) for arg in expr.args]
            ret = ExprOp(expr.op, *args)
        elif expr.is_compose():
            args = [self.visit(arg, *args, **kwargs) for arg in expr.args]
            ret = ExprCompose(*args)
        else:
            raise TypeError("Visitor can only take Expr")
        return ret


class ExprVisitorCallbackTopToBottom(ExprVisitorBase):
    """
    Rebuild expression by visiting sub-expressions
    Call @callback on each sub-expression
    if @callback return non None value, replace current node with this value
    Else, continue visit of sub-expressions
    """
    def __init__(self, callback):
        super(ExprVisitorCallbackTopToBottom, self).__init__()
        self.cache = dict()
        self.callback = callback

    def visit(self, expr, *args, **kwargs):
        if expr in self.cache:
            return self.cache[expr]
        ret = self.visit_inner(expr, *args, **kwargs)
        self.cache[expr] = ret
        return ret

    def visit_inner(self, expr, *args, **kwargs):
        ret = self.callback(expr)
        if ret:
            return ret
        ret = super(ExprVisitorCallbackTopToBottom, self).visit(expr, *args, **kwargs)
        return ret


class ExprVisitorCallbackBottomToTop(ExprVisitorBase):
    """
    Rebuild expression by visiting sub-expressions
    Call @callback from leaves to root expressions
    """
    def __init__(self, callback):
        super(ExprVisitorCallbackBottomToTop, self).__init__()
        self.cache = dict()
        self.callback = callback

    def visit(self, expr, *args, **kwargs):
        if expr in self.cache:
            return self.cache[expr]
        ret = self.visit_inner(expr, *args, **kwargs)
        self.cache[expr] = ret
        return ret

    def visit_inner(self, expr, *args, **kwargs):
        ret = super(ExprVisitorCallbackBottomToTop, self).visit(expr, *args, **kwargs)
        ret = self.callback(ret)
        return ret


class ExprVisitorCanonize(ExprVisitorCallbackBottomToTop):
    def __init__(self):
        super(ExprVisitorCanonize, self).__init__(self.canonize)

    def canonize(self, expr):
        if not expr.is_op():
            return expr
        if not expr.is_associative():
            return expr

        # ((a+b) + c) => (a + b + c)
        args = []
        for arg in expr.args:
            if isinstance(arg, ExprOp) and expr.op == arg.op:
                args += arg.args
            else:
                args.append(arg)
        args = canonize_expr_list(args)
        new_expr = ExprOp(expr.op, *args)
        return new_expr


class ExprVisitorContains(ExprWalkBase):
    """
    Visitor to test if a needle is in an Expression
    Cache results
    """
    def __init__(self):
        self.cache = set()
        super(ExprVisitorContains, self).__init__(self.eq_expr)

    def eq_expr(self, expr, needle, *args, **kwargs):
        if expr == needle:
            return True
        return None

    def visit(self, expr, needle,  *args, **kwargs):
        if (expr, needle) in self.cache:
            return None
        ret = super(ExprVisitorContains, self).visit(expr, needle, *args, **kwargs)
        if ret:
            return ret
        self.cache.add((expr, needle))
        return None


    def contains(self, expr, needle):
        return self.visit(expr, needle)

contains_visitor = ExprVisitorContains()
canonize_visitor = ExprVisitorCanonize()

# IR definitions

class Expr(object):

    "Parent class for Miasm Expressions"

    __slots__ = ["_hash", "_repr", "_size"]

    args2expr = {}
    canon_exprs = set()
    use_singleton = True

    def set_size(self, _):
        raise ValueError('size is not mutable')

    def __init__(self, size):
        """Instantiate an Expr with size @size
        @size: int
        """
        # Common attribute
        self._size = size

        # Lazy cache needs
        self._hash = None
        self._repr = None

    size = property(lambda self: self._size)

    @staticmethod
    def get_object(expr_cls, args):
        if not expr_cls.use_singleton:
            return object.__new__(expr_cls)

        expr = Expr.args2expr.get((expr_cls, args))
        if expr is None:
            expr = object.__new__(expr_cls)
            Expr.args2expr[(expr_cls, args)] = expr
        return expr

    def get_is_canon(self):
        return self in Expr.canon_exprs

    def set_is_canon(self, value):
        assert value is True
        Expr.canon_exprs.add(self)

    is_canon = property(get_is_canon, set_is_canon)

    # Common operations

    def __str__(self):
        raise NotImplementedError("Abstract Method")

    def __getitem__(self, i):
        if not isinstance(i, slice):
            raise TypeError("Expression: Bad slice: %s" % i)
        start, stop, step = i.indices(self.size)
        if step != 1:
            raise ValueError("Expression: Bad slice: %s" % i)
        return ExprSlice(self, start, stop)

    def get_size(self):
        raise DeprecationWarning("use X.size instead of X.get_size()")

    def is_function_call(self):
        """Returns true if the considered Expr is a function call
        """
        return False

    def __repr__(self):
        if self._repr is None:
            self._repr = self._exprrepr()
        return self._repr

    def __hash__(self):
        if self._hash is None:
            self._hash = self._exprhash()
        return self._hash

    def __eq__(self, other):
        if self is other:
            return True
        elif self.use_singleton:
            # In case of Singleton, pointer comparison is sufficient
            # Avoid computation of hash and repr
            return False

        if self.__class__ is not other.__class__:
            return False
        if hash(self) != hash(other):
            return False
        return repr(self) == repr(other)

    def __ne__(self, other):
        return not self.__eq__(other)

    def __lt__(self, other):
        weight1 = EXPR_ORDER_DICT[self.__class__]
        weight2 = EXPR_ORDER_DICT[other.__class__]
        return weight1 < weight2

    def __add__(self, other):
        return ExprOp('+', self, other)

    def __sub__(self, other):
        return ExprOp('+', self, ExprOp('-', other))

    def __truediv__(self, other):
        return ExprOp('/', self, other)

    def __floordiv__(self, other):
        return self.__truediv__(other)

    def __mod__(self, other):
        return ExprOp('%', self, other)

    def __mul__(self, other):
        return ExprOp('*', self, other)

    def __lshift__(self, other):
        return ExprOp('<<', self, other)

    def __rshift__(self, other):
        return ExprOp('>>', self, other)

    def __xor__(self, other):
        return ExprOp('^', self, other)

    def __or__(self, other):
        return ExprOp('|', self, other)

    def __and__(self, other):
        return ExprOp('&', self, other)

    def __neg__(self):
        return ExprOp('-', self)

    def __pow__(self, other):
        return ExprOp("**", self, other)

    def __invert__(self):
        return ExprOp('^', self, self.mask)

    def copy(self):
        "Deep copy of the expression"
        return self.visit(lambda x: x)

    def __deepcopy__(self, _):
        return self.copy()

    def replace_expr(self, dct):
        """Find and replace sub expression using dct
        @dct: dictionary associating replaced Expr to its new Expr value
        """
        def replace(expr):
            if expr in dct:
                return dct[expr]
            return None
        visitor = ExprVisitorCallbackTopToBottom(lambda expr:replace(expr))
        return visitor.visit(self)

    def canonize(self):
        "Canonize the Expression"
        return canonize_visitor.visit(self)

    def msb(self):
        "Return the Most Significant Bit"
        return self[self.size - 1:self.size]

    def zeroExtend(self, size):
        """Zero extend to size
        @size: int
        """
        assert self.size <= size
        if self.size == size:
            return self
        return ExprOp('zeroExt_%d' % size, self)

    def signExtend(self, size):
        """Sign extend to size
        @size: int
        """
        assert self.size <= size
        if self.size == size:
            return self
        return ExprOp('signExt_%d' % size, self)

    def graph_recursive(self, graph):
        """Recursive method used by graph
        @graph: miasm.core.graph.DiGraph instance
        Update @graph instance to include sons
        This is an Abstract method"""

        raise ValueError("Abstract method")

    def graph(self):
        """Return a DiGraph instance standing for Expr tree
        Instance's display functions have been override for better visibility
        Wrapper on graph_recursive"""

        # Create recursively the graph
        graph = DiGraphExpr()
        self.graph_recursive(graph)

        return graph

    def set_mask(self, value):
        raise ValueError('mask is not mutable')

    mask = property(lambda self: ExprInt(-1, self.size))

    def is_int(self, value=None):
        return False

    def is_id(self, name=None):
        return False

    def is_loc(self, label=None):
        return False

    def is_aff(self):
        warnings.warn('DEPRECATION WARNING: use is_assign()')
        return False

    def is_assign(self):
        return False

    def is_cond(self):
        return False

    def is_mem(self):
        return False

    def is_op(self, op=None):
        return False

    def is_slice(self, start=None, stop=None):
        return False

    def is_compose(self):
        return False

    def is_op_segm(self):
        """Returns True if is ExprOp and op == 'segm'"""
        warnings.warn('DEPRECATION WARNING: use is_op_segm(expr)')
        raise RuntimeError("Moved api")

    def is_mem_segm(self):
        """Returns True if is ExprMem and ptr is_op_segm"""
        warnings.warn('DEPRECATION WARNING: use is_mem_segm(expr)')
        raise RuntimeError("Moved api")

    def __contains__(self, expr):
        ret = contains_visitor.contains(self, expr)
        return ret

    def visit(self, callback):
        """
        Apply callback to all sub expression of @self
        This function keeps a cache to avoid rerunning @callback on common sub
        expressions.

        @callback: fn(Expr) -> Expr
        """
        visitor = ExprVisitorCallbackBottomToTop(callback)
        return visitor.visit(self)

    def get_r(self, mem_read=False, cst_read=False):
        visitor = ExprGetR(mem_read, cst_read)
        visitor.visit(self)
        return visitor.elements


    def get_w(self, mem_read=False, cst_read=False):
        if self.is_assign():
            return set([self.dst])
        return set()

class ExprInt(Expr):

    """An ExprInt represent a constant in Miasm IR.

    Some use cases:
     - Constant 0x42
     - Constant -0x30
     - Constant 0x12345678 on 32bits
     """

    __slots__ = Expr.__slots__ + ["_arg"]


    def __init__(self, arg, size):
        """Create an ExprInt from num/size
        @arg: int/long number
        @size: int size"""
        super(ExprInt, self).__init__(size)
        # Work for ._arg is done in __new__

    arg = property(lambda self: self._arg)

    def __reduce__(self):
        state = int(self._arg), self._size
        return self.__class__, state

    def __new__(cls, arg, size):
        """Create an ExprInt from num/size
        @arg: int/long number
        @size: int size"""

        assert isinstance(arg, int_types)
        arg  = arg & ((1 << size) - 1)
        # Get the Singleton instance
        expr = Expr.get_object(cls, (arg, size))

        # Save parameters (__init__ is called with parameters unchanged)
        expr._arg = arg
        return expr

    def __str__(self):
        return str("0x%X" % self.arg)

    def get_w(self):
        return set()

    def _exprhash(self):
        return hash((EXPRINT, self._arg, self._size))

    def _exprrepr(self):
        return "%s(0x%X, %d)" % (self.__class__.__name__, self.arg,
                                 self._size)

    def copy(self):
        return ExprInt(self._arg, self._size)

    def depth(self):
        return 1

    def graph_recursive(self, graph):
        graph.add_node(self)

    def __int__(self):
        return int(self.arg)

    def __long__(self):
        return int(self.arg)

    def is_int(self, value=None):
        if value is not None and self._arg != value:
            return False
        return True


class ExprId(Expr):

    """An ExprId represent an identifier in Miasm IR.

    Some use cases:
     - EAX register
     - 'start' offset
     - variable v1
     """

    __slots__ = Expr.__slots__ + ["_name"]

    def __init__(self, name, size=None):
        """Create an identifier
        @name: str, identifier's name
        @size: int, identifier's size
        """
        if size is None:
            warnings.warn('DEPRECATION WARNING: size is a mandatory argument: use ExprId(name, SIZE)')
            size = 32
        assert isinstance(name, (str, bytes))
        super(ExprId, self).__init__(size)
        self._name = name

    name = property(lambda self: self._name)

    def __reduce__(self):
        state = self._name, self._size
        return self.__class__, state

    def __new__(cls, name, size=None):
        if size is None:
            warnings.warn('DEPRECATION WARNING: size is a mandatory argument: use ExprId(name, SIZE)')
            size = 32
        return Expr.get_object(cls, (name, size))

    def __str__(self):
        return str(self._name)

    def get_w(self):
        return set([self])

    def _exprhash(self):
        return hash((EXPRID, self._name, self._size))

    def _exprrepr(self):
        return "%s(%r, %d)" % (self.__class__.__name__, self._name, self._size)

    def copy(self):
        return ExprId(self._name, self._size)

    def depth(self):
        return 1

    def graph_recursive(self, graph):
        graph.add_node(self)

    def is_id(self, name=None):
        if name is not None and self._name != name:
            return False
        return True


class ExprLoc(Expr):

    """An ExprLoc represent a Label in Miasm IR.
    """

    __slots__ = Expr.__slots__ + ["_loc_key"]

    def __init__(self, loc_key, size):
        """Create an identifier
        @loc_key: int, label loc_key
        @size: int, identifier's size
        """
        assert isinstance(loc_key, LocKey)
        super(ExprLoc, self).__init__(size)
        self._loc_key = loc_key

    loc_key= property(lambda self: self._loc_key)

    def __reduce__(self):
        state = self._loc_key, self._size
        return self.__class__, state

    def __new__(cls, loc_key, size):
        return Expr.get_object(cls, (loc_key, size))

    def __str__(self):
        return str(self._loc_key)

    def get_w(self):
        return set()

    def _exprhash(self):
        return hash((EXPRLOC, self._loc_key, self._size))

    def _exprrepr(self):
        return "%s(%r, %d)" % (self.__class__.__name__, self._loc_key, self._size)

    def copy(self):
        return ExprLoc(self._loc_key, self._size)

    def depth(self):
        return 1

    def graph_recursive(self, graph):
        graph.add_node(self)

    def is_loc(self, loc_key=None):
        if loc_key is not None and self._loc_key != loc_key:
            return False
        return True


class ExprAssign(Expr):

    """An ExprAssign represent an assignment from an Expression to another one.

    Some use cases:
     - var1 <- 2
    """

    __slots__ = Expr.__slots__ + ["_dst", "_src"]

    def __init__(self, dst, src):
        """Create an ExprAssign for dst <- src
        @dst: Expr, assignment destination
        @src: Expr, assignment source
        """
        # dst & src must be Expr
        assert isinstance(dst, Expr)
        assert isinstance(src, Expr)

        if dst.size != src.size:
            raise ValueError(
                "sanitycheck: ExprAssign args must have same size! %s" %
                ([(str(arg), arg.size) for arg in [dst, src]]))

        super(ExprAssign, self).__init__(self.dst.size)

    dst = property(lambda self: self._dst)
    src = property(lambda self: self._src)


    def __reduce__(self):
        state = self._dst, self._src
        return self.__class__, state

    def __new__(cls, dst, src):
        if dst.is_slice() and dst.arg.size == src.size:
            new_dst, new_src = dst.arg, src
        elif dst.is_slice():
            # Complete the source with missing slice parts
            new_dst = dst.arg
            rest = [(ExprSlice(dst.arg, r[0], r[1]), r[0], r[1])
                    for r in dst.slice_rest()]
            all_a = [(src, dst.start, dst.stop)] + rest
            all_a.sort(key=lambda x: x[1])
            args = [expr for (expr, _, _) in all_a]
            new_src = ExprCompose(*args)
        else:
            new_dst, new_src = dst, src
        expr = Expr.get_object(cls, (new_dst, new_src))
        expr._dst, expr._src = new_dst, new_src
        return expr

    def __str__(self):
        return "%s = %s" % (str(self._dst), str(self._src))

    def get_w(self):
        if isinstance(self._dst, ExprMem):
            return set([self._dst])  # [memreg]
        else:
            return self._dst.get_w()

    def _exprhash(self):
        return hash((EXPRASSIGN, hash(self._dst), hash(self._src)))

    def _exprrepr(self):
        return "%s(%r, %r)" % (self.__class__.__name__, self._dst, self._src)

    def copy(self):
        return ExprAssign(self._dst.copy(), self._src.copy())

    def depth(self):
        return max(self._src.depth(), self._dst.depth()) + 1

    def graph_recursive(self, graph):
        graph.add_node(self)
        for arg in [self._src, self._dst]:
            arg.graph_recursive(graph)
            graph.add_uniq_edge(self, arg)


    def is_aff(self):
        warnings.warn('DEPRECATION WARNING: use is_assign()')
        return True

    def is_assign(self):
        return True


class ExprAff(ExprAssign):
    """
    DEPRECATED class.
    Use ExprAssign instead of ExprAff
    """

    def __init__(self, dst, src):
        warnings.warn('DEPRECATION WARNING: use ExprAssign instead of ExprAff')
        super(ExprAff, self).__init__(dst, src)


class ExprCond(Expr):

    """An ExprCond stand for a condition on an Expr

    Use cases:
     - var1 < var2
     - min(var1, var2)
     - if (cond) then ... else ...
    """

    __slots__ = Expr.__slots__ + ["_cond", "_src1", "_src2"]

    def __init__(self, cond, src1, src2):
        """Create an ExprCond
        @cond: Expr, condition
        @src1: Expr, value if condition is evaled to not zero
        @src2: Expr, value if condition is evaled zero
        """

        # cond, src1, src2 must be Expr
        assert isinstance(cond, Expr)
        assert isinstance(src1, Expr)
        assert isinstance(src2, Expr)

        self._cond, self._src1, self._src2 = cond, src1, src2
        assert src1.size == src2.size
        super(ExprCond, self).__init__(self.src1.size)

    cond = property(lambda self: self._cond)
    src1 = property(lambda self: self._src1)
    src2 = property(lambda self: self._src2)

    def __reduce__(self):
        state = self._cond, self._src1, self._src2
        return self.__class__, state

    def __new__(cls, cond, src1, src2):
        return Expr.get_object(cls, (cond, src1, src2))

    def __str__(self):
        return "%s?(%s,%s)" % (str_protected_child(self._cond, self), str(self._src1), str(self._src2))

    def get_w(self):
        return set()

    def _exprhash(self):
        return hash((EXPRCOND, hash(self.cond),
                     hash(self._src1), hash(self._src2)))

    def _exprrepr(self):
        return "%s(%r, %r, %r)" % (self.__class__.__name__,
                                   self._cond, self._src1, self._src2)

    def copy(self):
        return ExprCond(self._cond.copy(),
                        self._src1.copy(),
                        self._src2.copy())

    def depth(self):
        return max(self._cond.depth(),
                   self._src1.depth(),
                   self._src2.depth()) + 1

    def graph_recursive(self, graph):
        graph.add_node(self)
        for arg in [self._cond, self._src1, self._src2]:
            arg.graph_recursive(graph)
            graph.add_uniq_edge(self, arg)

    def is_cond(self):
        return True


class ExprMem(Expr):

    """An ExprMem stand for a memory access

    Use cases:
     - Memory read
     - Memory write
    """

    __slots__ = Expr.__slots__ + ["_ptr"]

    def __init__(self, ptr, size=None):
        """Create an ExprMem
        @ptr: Expr, memory access address
        @size: int, memory access size
        """
        if size is None:
            warnings.warn('DEPRECATION WARNING: size is a mandatory argument: use ExprMem(ptr, SIZE)')
            size = 32

        # ptr must be Expr
        assert isinstance(ptr, Expr)
        assert isinstance(size, int_types)

        if not isinstance(ptr, Expr):
            raise ValueError(
                'ExprMem: ptr must be an Expr (not %s)' % type(ptr))

        super(ExprMem, self).__init__(size)
        self._ptr = ptr

    def get_arg(self):
        warnings.warn('DEPRECATION WARNING: use exprmem.ptr instead of exprmem.arg')
        return self.ptr

    def set_arg(self, value):
        warnings.warn('DEPRECATION WARNING: use exprmem.ptr instead of exprmem.arg')
        self.ptr = value

    ptr = property(lambda self: self._ptr)
    arg = property(get_arg, set_arg)

    def __reduce__(self):
        state = self._ptr, self._size
        return self.__class__, state

    def __new__(cls, ptr, size=None):
        if size is None:
            warnings.warn('DEPRECATION WARNING: size is a mandatory argument: use ExprMem(ptr, SIZE)')
            size = 32

        return Expr.get_object(cls, (ptr, size))

    def __str__(self):
        return "@%d[%s]" % (self.size, str(self.ptr))

    def get_w(self):
        return set([self])  # [memreg]

    def _exprhash(self):
        return hash((EXPRMEM, hash(self._ptr), self._size))

    def _exprrepr(self):
        return "%s(%r, %r)" % (self.__class__.__name__,
                               self._ptr, self._size)

    def copy(self):
        ptr = self.ptr.copy()
        return ExprMem(ptr, size=self.size)

    def is_mem_segm(self):
        """Returns True if is ExprMem and ptr is_op_segm"""
        warnings.warn('DEPRECATION WARNING: use is_mem_segm(expr)')
        raise RuntimeError("Moved api")

    def depth(self):
        return self._ptr.depth() + 1

    def graph_recursive(self, graph):
        graph.add_node(self)
        self._ptr.graph_recursive(graph)
        graph.add_uniq_edge(self, self._ptr)

    def is_mem(self):
        return True


class ExprOp(Expr):

    """An ExprOp stand for an operation between Expr

    Use cases:
     - var1 XOR var2
     - var1 + var2 + var3
     - parity bit(var1)
    """

    __slots__ = Expr.__slots__ + ["_op", "_args"]

    def __init__(self, op, *args):
        """Create an ExprOp
        @op: str, operation
        @*args: Expr, operand list
        """

        # args must be Expr
        assert all(isinstance(arg, Expr) for arg in args)

        sizes = set([arg.size for arg in args])

        if len(sizes) != 1:
            # Special cases : operande sizes can differ
            if op not in [
                    "segm",
                    "FLAG_EQ_ADDWC", "FLAG_EQ_SUBWC",
                    "FLAG_SIGN_ADDWC", "FLAG_SIGN_SUBWC",
                    "FLAG_ADDWC_CF", "FLAG_ADDWC_OF",
                    "FLAG_SUBWC_CF", "FLAG_SUBWC_OF",

            ]:
                raise ValueError(
                    "sanitycheck: ExprOp args must have same size! %s" %
                    ([(str(arg), arg.size) for arg in args]))

        if not isinstance(op, str):
            raise ValueError("ExprOp: 'op' argument must be a string")

        assert isinstance(args, tuple)
        self._op, self._args = op, args

        # Set size for special cases
        if self._op in [
                TOK_EQUAL, 'parity', 'fcom_c0', 'fcom_c1', 'fcom_c2', 'fcom_c3',
                'fxam_c0', 'fxam_c1', 'fxam_c2', 'fxam_c3',
                "access_segment_ok", "load_segment_limit_ok", "bcdadd_cf",
                "ucomiss_zf", "ucomiss_pf", "ucomiss_cf",
                "ucomisd_zf", "ucomisd_pf", "ucomisd_cf"]:
            size = 1
        elif self._op in [TOK_INF, TOK_INF_SIGNED,
                           TOK_INF_UNSIGNED, TOK_INF_EQUAL,
                           TOK_INF_EQUAL_SIGNED, TOK_INF_EQUAL_UNSIGNED,
                           TOK_EQUAL, TOK_POS,
                           TOK_POS_STRICT,
                          ]:
            size = 1
        elif self._op.startswith("fp_to_sint"):
            size = int(self._op[len("fp_to_sint"):])
        elif self._op.startswith("fpconvert_fp"):
            size = int(self._op[len("fpconvert_fp"):])
        elif self._op in [
                "FLAG_ADD_CF", "FLAG_SUB_CF",
                "FLAG_ADD_OF", "FLAG_SUB_OF",
                "FLAG_EQ", "FLAG_EQ_CMP",
                "FLAG_SIGN_SUB", "FLAG_SIGN_ADD",
                "FLAG_EQ_AND",
                "FLAG_EQ_ADDWC", "FLAG_EQ_SUBWC",
                "FLAG_SIGN_ADDWC", "FLAG_SIGN_SUBWC",
                "FLAG_ADDWC_CF", "FLAG_ADDWC_OF",
                "FLAG_SUBWC_CF", "FLAG_SUBWC_OF",
        ]:
            size = 1

        elif self._op.startswith('signExt_'):
            size = int(self._op[8:])
        elif self._op.startswith('zeroExt_'):
            size = int(self._op[8:])
        elif self._op in ['segm']:
            size = self._args[1].size
        else:
            if None in sizes:
                size = None
            else:
                # All arguments have the same size
                size = list(sizes)[0]

        super(ExprOp, self).__init__(size)

    op = property(lambda self: self._op)
    args = property(lambda self: self._args)

    def __reduce__(self):
        state = tuple([self._op] + list(self._args))
        return self.__class__, state

    def __new__(cls, op, *args):
        return Expr.get_object(cls, (op, args))

    def __str__(self):
        if self._op == '-':		# Unary minus
            return '-' + str_protected_child(self._args[0], self)
        if self.is_associative() or self.is_infix():
            return (' ' + self._op + ' ').join([str_protected_child(arg, self)
                                                for arg in self._args])
        return (self._op + '(' +
                ', '.join([str(arg) for arg in self._args]) + ')')

    def get_w(self):
        raise ValueError('op cannot be written!', self)

    def _exprhash(self):
        h_hargs = [hash(arg) for arg in self._args]
        return hash((EXPROP, self._op, tuple(h_hargs)))

    def _exprrepr(self):
        return "%s(%r, %s)" % (self.__class__.__name__, self._op,
                               ', '.join(repr(arg) for arg in self._args))

    def is_function_call(self):
        return self._op.startswith('call')

    def is_infix(self):
        return self._op in [
            '-', '+', '*', '^', '&', '|', '>>', '<<',
            'a>>', '>>>', '<<<', '/', '%', '**',
            TOK_INF_UNSIGNED,
            TOK_INF_SIGNED,
            TOK_INF_EQUAL_UNSIGNED,
            TOK_INF_EQUAL_SIGNED,
            TOK_EQUAL
        ]

    def is_associative(self):
        "Return True iff current operation is associative"
        return (self._op in ['+', '*', '^', '&', '|'])

    def is_commutative(self):
        "Return True iff current operation is commutative"
        return (self._op in ['+', '*', '^', '&', '|'])

    def copy(self):
        args = [arg.copy() for arg in self._args]
        return ExprOp(self._op, *args)

    def depth(self):
        depth = [arg.depth() for arg in self._args]
        return max(depth) + 1

    def graph_recursive(self, graph):
        graph.add_node(self)
        for arg in self._args:
            arg.graph_recursive(graph)
            graph.add_uniq_edge(self, arg)

    def is_op(self, op=None):
        if op is None:
            return True
        return self.op == op

    def is_op_segm(self):
        """Returns True if is ExprOp and op == 'segm'"""
        warnings.warn('DEPRECATION WARNING: use is_op_segm(expr)')
        raise RuntimeError("Moved api")

class ExprSlice(Expr):

    __slots__ = Expr.__slots__ + ["_arg", "_start", "_stop"]

    def __init__(self, arg, start, stop):

        # arg must be Expr
        assert isinstance(arg, Expr)
        assert isinstance(start, int_types)
        assert isinstance(stop, int_types)
        assert start < stop

        self._arg, self._start, self._stop = arg, start, stop
        super(ExprSlice, self).__init__(self._stop - self._start)

    arg = property(lambda self: self._arg)
    start = property(lambda self: self._start)
    stop = property(lambda self: self._stop)

    def __reduce__(self):
        state = self._arg, self._start, self._stop
        return self.__class__, state

    def __new__(cls, arg, start, stop):
        return Expr.get_object(cls, (arg, start, stop))

    def __str__(self):
        return "%s[%d:%d]" % (str_protected_child(self._arg, self), self._start, self._stop)

    def get_w(self):
        return self._arg.get_w()

    def _exprhash(self):
        return hash((EXPRSLICE, hash(self._arg), self._start, self._stop))

    def _exprrepr(self):
        return "%s(%r, %d, %d)" % (self.__class__.__name__, self._arg,
                                   self._start, self._stop)

    def copy(self):
        return ExprSlice(self._arg.copy(), self._start, self._stop)

    def depth(self):
        return self._arg.depth() + 1

    def slice_rest(self):
        "Return the completion of the current slice"
        size = self._arg.size
        if self._start >= size or self._stop > size:
            raise ValueError('bad slice rest %s %s %s' %
                             (size, self._start, self._stop))

        if self._start == self._stop:
            return [(0, size)]

        rest = []
        if self._start != 0:
            rest.append((0, self._start))
        if self._stop < size:
            rest.append((self._stop, size))

        return rest

    def graph_recursive(self, graph):
        graph.add_node(self)
        self._arg.graph_recursive(graph)
        graph.add_uniq_edge(self, self._arg)

    def is_slice(self, start=None, stop=None):
        if start is not None and self._start != start:
            return False
        if stop is not None and self._stop != stop:
            return False
        return True


class ExprCompose(Expr):

    """
    Compose is like a hamburger. It concatenate Expressions
    """

    __slots__ = Expr.__slots__ + ["_args"]

    def __init__(self, *args):
        """Create an ExprCompose
        The ExprCompose is contiguous and starts at 0
        @args: [Expr, Expr, ...]
        DEPRECATED:
        @args: [(Expr, int, int), (Expr, int, int), ...]
        """

        # args must be Expr
        assert all(isinstance(arg, Expr) for arg in args)

        assert isinstance(args, tuple)
        self._args = args
        super(ExprCompose, self).__init__(sum(arg.size for arg in args))

    args = property(lambda self: self._args)

    def __reduce__(self):
        state = self._args
        return self.__class__, state

    def __new__(cls, *args):
        return Expr.get_object(cls, args)

    def __str__(self):
        return '{' + ', '.join(["%s %s %s" % (arg, idx, idx + arg.size) for idx, arg in self.iter_args()]) + '}'

    def get_w(self):
        return reduce(lambda elements, arg:
                      elements.union(arg.get_w()), self._args, set())

    def _exprhash(self):
        h_args = [EXPRCOMPOSE] + [hash(arg) for arg in self._args]
        return hash(tuple(h_args))

    def _exprrepr(self):
        return "%s%r" % (self.__class__.__name__, self._args)

    def copy(self):
        args = [arg.copy() for arg in self._args]
        return ExprCompose(*args)

    def depth(self):
        depth = [arg.depth() for arg in self._args]
        return max(depth) + 1

    def graph_recursive(self, graph):
        graph.add_node(self)
        for arg in self.args:
            arg.graph_recursive(graph)
            graph.add_uniq_edge(self, arg)

    def iter_args(self):
        index = 0
        for arg in self._args:
            yield index, arg
            index += arg.size

    def is_compose(self):
        return True

# Expression order for comparison
EXPR_ORDER_DICT = {
    ExprId: 1,
    ExprLoc: 2,
    ExprCond: 3,
    ExprMem: 4,
    ExprOp: 5,
    ExprSlice: 6,
    ExprCompose: 7,
    ExprInt: 8,
}


def compare_exprs_compose(expr1, expr2):
    # Sort by start bit address, then expr, then stop bit address
    ret = cmp_elts(expr1[1], expr2[1])
    if ret:
        return ret
    ret = compare_exprs(expr1[0], expr2[0])
    if ret:
        return ret
    ret = cmp_elts(expr1[2], expr2[2])
    return ret


def compare_expr_list_compose(l1_e, l2_e):
    # Sort by list elements in incremental order, then by list size
    for i in range(min(len(l1_e), len(l2_e))):
        ret = compare_exprs(l1_e[i], l2_e[i])
        if ret:
            return ret
    return cmp_elts(len(l1_e), len(l2_e))


def compare_expr_list(l1_e, l2_e):
    # Sort by list elements in incremental order, then by list size
    for i in range(min(len(l1_e), len(l2_e))):
        ret = compare_exprs(l1_e[i], l2_e[i])
        if ret:
            return ret
    return cmp_elts(len(l1_e), len(l2_e))


def compare_exprs(expr1, expr2):
    """Compare 2 expressions for canonization
    @expr1: Expr
    @expr2: Expr
    0  => ==
    1  => expr1 > expr2
    -1 => expr1 < expr2
    """
    cls1 = expr1.__class__
    cls2 = expr2.__class__
    if cls1 != cls2:
        return cmp_elts(EXPR_ORDER_DICT[cls1], EXPR_ORDER_DICT[cls2])
    if expr1 == expr2:
        return 0
    if cls1 == ExprInt:
        ret = cmp_elts(expr1.size, expr2.size)
        if ret != 0:
            return ret
        return cmp_elts(expr1.arg, expr2.arg)
    elif cls1 == ExprId:
        name1 = force_bytes(expr1.name)
        name2 = force_bytes(expr2.name)
        ret = cmp_elts(name1, name2)
        if ret:
            return ret
        return cmp_elts(expr1.size, expr2.size)
    elif cls1 == ExprLoc:
        ret = cmp_elts(expr1.loc_key, expr2.loc_key)
        if ret:
            return ret
        return cmp_elts(expr1.size, expr2.size)
    elif cls1 == ExprAssign:
        raise NotImplementedError(
            "Comparison from an ExprAssign not yet implemented"
        )
    elif cls2 == ExprCond:
        ret = compare_exprs(expr1.cond, expr2.cond)
        if ret:
            return ret
        ret = compare_exprs(expr1.src1, expr2.src1)
        if ret:
            return ret
        ret = compare_exprs(expr1.src2, expr2.src2)
        return ret
    elif cls1 == ExprMem:
        ret = compare_exprs(expr1.ptr, expr2.ptr)
        if ret:
            return ret
        return cmp_elts(expr1.size, expr2.size)
    elif cls1 == ExprOp:
        if expr1.op != expr2.op:
            return cmp_elts(expr1.op, expr2.op)
        return compare_expr_list(expr1.args, expr2.args)
    elif cls1 == ExprSlice:
        ret = compare_exprs(expr1.arg, expr2.arg)
        if ret:
            return ret
        ret = cmp_elts(expr1.start, expr2.start)
        if ret:
            return ret
        ret = cmp_elts(expr1.stop, expr2.stop)
        return ret
    elif cls1 == ExprCompose:
        return compare_expr_list_compose(expr1.args, expr2.args)
    raise NotImplementedError(
        "Comparison between %r %r not implemented" % (expr1, expr2)
    )


def canonize_expr_list(expr_list):
    return sorted(expr_list, key=cmp_to_key(compare_exprs))


def canonize_expr_list_compose(expr_list):
    return sorted(expr_list, key=cmp_to_key(compare_exprs_compose))

# Generate ExprInt with common size


def ExprInt1(i):
    warnings.warn('DEPRECATION WARNING: use ExprInt(i, 1) instead of '\
                  'ExprInt1(i))')
    return ExprInt(i, 1)


def ExprInt8(i):
    warnings.warn('DEPRECATION WARNING: use ExprInt(i, 8) instead of '\
                  'ExprInt8(i))')
    return ExprInt(i, 8)


def ExprInt16(i):
    warnings.warn('DEPRECATION WARNING: use ExprInt(i, 16) instead of '\
                  'ExprInt16(i))')
    return ExprInt(i, 16)


def ExprInt32(i):
    warnings.warn('DEPRECATION WARNING: use ExprInt(i, 32) instead of '\
                  'ExprInt32(i))')
    return ExprInt(i, 32)


def ExprInt64(i):
    warnings.warn('DEPRECATION WARNING: use ExprInt(i, 64) instead of '\
                  'ExprInt64(i))')
    return ExprInt(i, 64)


def ExprInt_from(expr, i):
    "Generate ExprInt with size equal to expression"
    warnings.warn('DEPRECATION WARNING: use ExprInt(i, expr.size) instead of'\
                  'ExprInt_from(expr, i))')
    return ExprInt(i, expr.size)


def get_expr_ids_visit(expr, ids):
    """Visitor to retrieve ExprId in @expr
    @expr: Expr"""
    if expr.is_id():
        ids.add(expr)
    return expr


def get_expr_locs_visit(expr, locs):
    """Visitor to retrieve ExprLoc in @expr
    @expr: Expr"""
    if expr.is_loc():
        locs.add(expr)
    return expr


def get_expr_ids(expr):
    """Retrieve ExprId in @expr
    @expr: Expr"""
    ids = set()
    expr.visit(lambda x: get_expr_ids_visit(x, ids))
    return ids


def get_expr_locs(expr):
    """Retrieve ExprLoc in @expr
    @expr: Expr"""
    locs = set()
    expr.visit(lambda x: get_expr_locs_visit(x, locs))
    return locs


def test_set(expr, pattern, tks, result):
    """Test if v can correspond to e. If so, update the context in result.
    Otherwise, return False
    @expr : Expr to match
    @pattern : pattern Expr
    @tks : list of ExprId, available jokers
    @result : dictionary of ExprId -> Expr, current context
    """

    if not pattern in tks:
        return expr == pattern
    if pattern in result and result[pattern] != expr:
        return False
    result[pattern] = expr
    return result


def match_expr(expr, pattern, tks, result=None):
    """Try to match the @pattern expression with the pattern @expr with @tks jokers.
    Result is output dictionary with matching joker values.
    @expr : Expr pattern
    @pattern : Targeted Expr to match
    @tks : list of ExprId, available jokers
    @result : dictionary of ExprId -> Expr, output matching context
    """

    if result is None:
        result = {}

    if pattern in tks:
        # pattern is a Joker
        return test_set(expr, pattern, tks, result)

    if expr.is_int():
        return test_set(expr, pattern, tks, result)

    elif expr.is_id():
        return test_set(expr, pattern, tks, result)

    elif expr.is_loc():
        return test_set(expr, pattern, tks, result)

    elif expr.is_op():

        # expr need to be the same operation than pattern
        if not pattern.is_op():
            return False
        if expr.op != pattern.op:
            return False
        if len(expr.args) != len(pattern.args):
            return False

        # Perform permutation only if the current operation is commutative
        if expr.is_commutative():
            permutations = itertools.permutations(expr.args)
        else:
            permutations = [expr.args]

        # For each permutations of arguments
        for permut in permutations:
            good = True
            # We need to use a copy of result to not override it
            myresult = dict(result)
            for sub_expr, sub_pattern in zip(permut, pattern.args):
                ret = match_expr(sub_expr, sub_pattern, tks, myresult)
                # If the current permutation do not match EVERY terms
                if ret is False:
                    good = False
                    break
            if good is True:
                # We found a possibility
                for joker, value in viewitems(myresult):
                    # Updating result in place (to keep pointer in recursion)
                    result[joker] = value
                return result
        return False

    # Recursive tests

    elif expr.is_mem():
        if not pattern.is_mem():
            return False
        if expr.size != pattern.size:
            return False
        return match_expr(expr.ptr, pattern.ptr, tks, result)

    elif expr.is_slice():
        if not pattern.is_slice():
            return False
        if expr.start != pattern.start or expr.stop != pattern.stop:
            return False
        return match_expr(expr.arg, pattern.arg, tks, result)

    elif expr.is_cond():
        if not pattern.is_cond():
            return False
        if match_expr(expr.cond, pattern.cond, tks, result) is False:
            return False
        if match_expr(expr.src1, pattern.src1, tks, result) is False:
            return False
        if match_expr(expr.src2, pattern.src2, tks, result) is False:
            return False
        return result

    elif expr.is_compose():
        if not pattern.is_compose():
            return False
        for sub_expr, sub_pattern in zip(expr.args, pattern.args):
            if  match_expr(sub_expr, sub_pattern, tks, result) is False:
                return False
        return result

    elif expr.is_assign():
        if not pattern.is_assign():
            return False
        if match_expr(expr.src, pattern.src, tks, result) is False:
            return False
        if match_expr(expr.dst, pattern.dst, tks, result) is False:
            return False
        return result

    else:
        raise NotImplementedError("match_expr: Unknown type: %s" % type(expr))


def MatchExpr(expr, pattern, tks, result=None):
    warnings.warn('DEPRECATION WARNING: use match_expr instead of MatchExpr')
    return match_expr(expr, pattern, tks, result)


def get_rw(exprs):
    o_r = set()
    o_w = set()
    for expr in exprs:
        o_r.update(expr.get_r(mem_read=True))
    for expr in exprs:
        o_w.update(expr.get_w())
    return o_r, o_w


def get_list_rw(exprs, mem_read=False, cst_read=True):
    """Return list of read/write reg/cst/mem for each @exprs
    @exprs: list of expressions
    @mem_read: walk though memory accesses
    @cst_read: retrieve constants
    """
    list_rw = []
    # cst_num = 0
    for expr in exprs:
        o_r = set()
        o_w = set()
        # get r/w
        o_r.update(expr.get_r(mem_read=mem_read, cst_read=cst_read))
        if isinstance(expr.dst, ExprMem):
            o_r.update(expr.dst.arg.get_r(mem_read=mem_read, cst_read=cst_read))
        o_w.update(expr.get_w())
        # each cst is indexed
        o_r_rw = set()
        for read in o_r:
            o_r_rw.add(read)
        o_r = o_r_rw
        list_rw.append((o_r, o_w))

    return list_rw


def get_expr_ops(expr):
    """Retrieve operators of an @expr
    @expr: Expr"""
    def visit_getops(expr, out=None):
        if out is None:
            out = set()
        if isinstance(expr, ExprOp):
            out.add(expr.op)
        return expr
    ops = set()
    expr.visit(lambda x: visit_getops(x, ops))
    return ops


def get_expr_mem(expr):
    """Retrieve memory accesses of an @expr
    @expr: Expr"""
    def visit_getmem(expr, out=None):
        if out is None:
            out = set()
        if isinstance(expr, ExprMem):
            out.add(expr)
        return expr
    ops = set()
    expr.visit(lambda x: visit_getmem(x, ops))
    return ops


def _expr_compute_cf(op1, op2):
    """
    Get carry flag of @op1 - @op2
    Ref: x86 cf flag
    @op1: Expression
    @op2: Expression
    """
    res = op1 - op2
    cf = (((op1 ^ op2) ^ res) ^ ((op1 ^ res) & (op1 ^ op2))).msb()
    return cf

def _expr_compute_of(op1, op2):
    """
    Get overflow flag of @op1 - @op2
    Ref: x86 of flag
    @op1: Expression
    @op2: Expression
    """
    res = op1 - op2
    of = (((op1 ^ res) & (op1 ^ op2))).msb()
    return of

def _expr_compute_zf(op1, op2):
    """
    Get zero flag of @op1 - @op2
    @op1: Expression
    @op2: Expression
    """
    res = op1 - op2
    zf = ExprCond(res,
                  ExprInt(0, 1),
                  ExprInt(1, 1))
    return zf


def _expr_compute_nf(op1, op2):
    """
    Get negative (or sign) flag of @op1 - @op2
    @op1: Expression
    @op2: Expression
    """
    res = op1 - op2
    nf = res.msb()
    return nf


def expr_is_equal(op1, op2):
    """
    if op1 == op2:
       Return ExprInt(1, 1)
    else:
       Return ExprInt(0, 1)
    """

    zf = _expr_compute_zf(op1, op2)
    return zf


def expr_is_not_equal(op1, op2):
    """
    if op1 != op2:
       Return ExprInt(1, 1)
    else:
       Return ExprInt(0, 1)
    """

    zf = _expr_compute_zf(op1, op2)
    return ~zf


def expr_is_unsigned_greater(op1, op2):
    """
    UNSIGNED cmp
    if op1 > op2:
       Return ExprInt(1, 1)
    else:
       Return ExprInt(0, 1)
    """

    cf = _expr_compute_cf(op1, op2)
    zf = _expr_compute_zf(op1, op2)
    return ~(cf | zf)


def expr_is_unsigned_greater_or_equal(op1, op2):
    """
    Unsigned cmp
    if op1 >= op2:
       Return ExprInt(1, 1)
    else:
       Return ExprInt(0, 1)
    """

    cf = _expr_compute_cf(op1, op2)
    return ~cf


def expr_is_unsigned_lower(op1, op2):
    """
    Unsigned cmp
    if op1 < op2:
       Return ExprInt(1, 1)
    else:
       Return ExprInt(0, 1)
    """

    cf = _expr_compute_cf(op1, op2)
    return cf


def expr_is_unsigned_lower_or_equal(op1, op2):
    """
    Unsigned cmp
    if op1 <= op2:
       Return ExprInt(1, 1)
    else:
       Return ExprInt(0, 1)
    """

    cf = _expr_compute_cf(op1, op2)
    zf = _expr_compute_zf(op1, op2)
    return cf | zf


def expr_is_signed_greater(op1, op2):
    """
    Signed cmp
    if op1 > op2:
       Return ExprInt(1, 1)
    else:
       Return ExprInt(0, 1)
    """

    nf = _expr_compute_nf(op1, op2)
    of = _expr_compute_of(op1, op2)
    zf = _expr_compute_zf(op1, op2)
    return ~(zf | (nf ^ of))


def expr_is_signed_greater_or_equal(op1, op2):
    """
    Signed cmp
    if op1 > op2:
       Return ExprInt(1, 1)
    else:
       Return ExprInt(0, 1)
    """

    nf = _expr_compute_nf(op1, op2)
    of = _expr_compute_of(op1, op2)
    return ~(nf ^ of)


def expr_is_signed_lower(op1, op2):
    """
    Signed cmp
    if op1 < op2:
       Return ExprInt(1, 1)
    else:
       Return ExprInt(0, 1)
    """

    nf = _expr_compute_nf(op1, op2)
    of = _expr_compute_of(op1, op2)
    return nf ^ of


def expr_is_signed_lower_or_equal(op1, op2):
    """
    Signed cmp
    if op1 <= op2:
       Return ExprInt(1, 1)
    else:
       Return ExprInt(0, 1)
    """

    nf = _expr_compute_nf(op1, op2)
    of = _expr_compute_of(op1, op2)
    zf = _expr_compute_zf(op1, op2)
    return zf | (nf ^ of)

# sign bit | exponent | significand
size_to_IEEE754_info = {
    16: {
        "exponent": 5,
        "significand": 10,
    },
    32: {
        "exponent": 8,
        "significand": 23,
    },
    64: {
        "exponent": 11,
        "significand": 52,
    },
}

def expr_is_NaN(expr):
    """Return 1 or 0 on 1 bit if expr represent a NaN value according to IEEE754
    """
    info = size_to_IEEE754_info[expr.size]
    exponent = expr[info["significand"]: info["significand"] + info["exponent"]]

    # exponent is full of 1s and significand is not NULL
    return ExprCond(exponent - ExprInt(-1, exponent.size),
                    ExprInt(0, 1),
                    ExprCond(expr[:info["significand"]], ExprInt(1, 1),
                             ExprInt(0, 1)))


def expr_is_infinite(expr):
    """Return 1 or 0 on 1 bit if expr represent an infinite value according to
    IEEE754
    """
    info = size_to_IEEE754_info[expr.size]
    exponent = expr[info["significand"]: info["significand"] + info["exponent"]]

    # exponent is full of 1s and significand is NULL
    return ExprCond(exponent - ExprInt(-1, exponent.size),
                    ExprInt(0, 1),
                    ExprCond(expr[:info["significand"]], ExprInt(0, 1),
                             ExprInt(1, 1)))


def expr_is_IEEE754_zero(expr):
    """Return 1 or 0 on 1 bit if expr represent a zero value according to
    IEEE754
    """
    # Sign is the msb
    expr_no_sign = expr[:expr.size - 1]
    return ExprCond(expr_no_sign, ExprInt(0, 1), ExprInt(1, 1))


def expr_is_IEEE754_denormal(expr):
    """Return 1 or 0 on 1 bit if expr represent a denormalized value according
    to IEEE754
    """
    info = size_to_IEEE754_info[expr.size]
    exponent = expr[info["significand"]: info["significand"] + info["exponent"]]
    # exponent is full of 0s
    return ExprCond(exponent, ExprInt(0, 1), ExprInt(1, 1))


def expr_is_qNaN(expr):
    """Return 1 or 0 on 1 bit if expr represent a qNaN (quiet) value according to
    IEEE754
    """
    info = size_to_IEEE754_info[expr.size]
    significand_top = expr[info["significand"]: info["significand"] + 1]
    return expr_is_NaN(expr) & significand_top


def expr_is_sNaN(expr):
    """Return 1 or 0 on 1 bit if expr represent a sNaN (signalling) value according
    to IEEE754
    """
    info = size_to_IEEE754_info[expr.size]
    significand_top = expr[info["significand"]: info["significand"] + 1]
    return expr_is_NaN(expr) & ~significand_top


def expr_is_float_lower(op1, op2):
    """Return 1 on 1 bit if @op1 < @op2, 0 otherwise.
    [!] Assume @op1 and @op2 are not NaN
    Comparison is the floating point one, defined in IEEE754
    """
    sign1, sign2 = op1.msb(), op2.msb()
    magn1, magn2 = op1[:-1], op2[:-1]
    return ExprCond(sign1 ^ sign2,
                    # Sign different, only the sign matters
                    sign1, # sign1 ? op1 < op2 : op1 >= op2
                    # Sign equals, the result is inversed for negatives
                    sign1 ^ (expr_is_unsigned_lower(magn1, magn2)))


def expr_is_float_equal(op1, op2):
    """Return 1 on 1 bit if @op1 == @op2, 0 otherwise.
    [!] Assume @op1 and @op2 are not NaN
    Comparison is the floating point one, defined in IEEE754
    """
    sign1, sign2 = op1.msb(), op2.msb()
    magn1, magn2 = op1[:-1], op2[:-1]
    return ExprCond(magn1 ^ magn2,
                    ExprInt(0, 1),
                    ExprCond(magn1,
                             # magn1 == magn2, are the signal equals?
                             ~(sign1 ^ sign2),
                             # Special case: -0.0 == +0.0
                             ExprInt(1, 1))
                    )