-
Notifications
You must be signed in to change notification settings - Fork 1
/
optimize
executable file
·90 lines (80 loc) · 2.5 KB
/
optimize
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
#!/usr/bin/env python3
import sys
import re
def isImmed(var):
if var[0] == '$':
return True
return False
def toOpr(var):
if var == 'sub':
return -1
if var == 'add':
return 1
print('Unexpected value', var)
exit(1)
fname = sys.argv[1]
c = [k for k in open(fname).read().split('\n') if len(k.strip())>0 and k.strip()[0] != '#']
print("New code size: ", len(c))
# Optimization pass 1; JUMP over JUMP
while True:
l = len(c)
flag = False
for i in range(0, l-1):
s1, s2 = c[i], c[i+1]
if s1.strip()[-1] == ':' and s2.strip().split()[0].lower() == 'jmp':
l1name = s1.strip()[:-1]
l2name = s2.strip().split()[1]
flag = True
break
if flag:
c = [k.replace(l1name, l2name) for k in c if k.strip().replace(' ', '') != l1name + ':']
else:
break
print("New code size: ", len(c))
# Optimization pass 2; WRITE before WRITE
while True:
writeOp = ['mov', 'lea']
l = len(c)
flag = False
for i in range(0, l-1):
s1 = [k.strip() for k in re.findall(r"((?:-?\d+)?\(.*?\)|[^ ,]+)", c[i].strip().replace('\t', ' '))]
s2 = [k.strip() for k in re.findall(r"((?:-?\d+)?\(.*?\)|[^ ,]+)", c[i+1].strip().replace('\t', ' '))]
if s1[0] not in writeOp or s2[0] not in writeOp:
continue
dst1 = s1[2]
dst2 = s2[2]
if dst1 == dst2:
if s2[2] not in s2[1]:
c[i] = ''
flag = True
break
if flag:
c = [k for k in c if len(k.strip()) > 0]
else:
break
# Optimization pass 3; CONSTANT FOLDING
while True:
arithOp = ['add', 'sub']
l = len(c)
flag = False
for i in range(0, l-1):
s1 = [k.strip() for k in re.findall(r"((?:-?\d+)?\(.*?\)|[^ ,]+)", c[i].strip().replace('\t', ' '))]
s2 = [k.strip() for k in re.findall(r"((?:-?\d+)?\(.*?\)|[^ ,]+)", c[i+1].strip().replace('\t', ' '))]
if s1[0] not in arithOp or s2[0] not in arithOp:
continue
if not isImmed(s1[1]) or not isImmed(s2[1]):
continue
if not s1[2] == s2[2]:
continue
val1 = toOpr(s1[0]) * int(s1[1][1:])
val2 = toOpr(s2[0]) * int(s2[1][1:])
c[i+1] = ''
c[i] = '\tadd ${}, {}'.format(val1+val2, s1[2])
flag = True
break
if flag:
c = [k for k in c if len(k.strip()) > 0]
else:
break
print("New code size: ", len(c))
open(fname, 'w').write('\n'.join(c) + "\n")