add fpcvt.mdwn pseudocode which calls new auto-generated function
[openpower-isa.git] / src / openpower / decoder / pseudo / pywriter.py
1 # python code-writer for OpenPOWER ISA pseudo-code parsing
2
3 import os
4 import sys
5 import shutil
6 import subprocess
7 from openpower.decoder.pseudo.pagereader import ISA
8 from openpower.decoder.power_pseudo import convert_to_python
9 from openpower.decoder.orderedset import OrderedSet
10 from openpower.decoder.isa.caller import create_args
11
12
13 def get_isasrc_dir():
14 fdir = os.path.abspath(os.path.dirname(__file__))
15 fdir = os.path.split(fdir)[0]
16 return os.path.join(fdir, "isa")
17
18
19 header = """\
20 # auto-generated by pywriter.py, do not edit or commit
21
22 from openpower.decoder.isa.caller import inject, instruction_info
23 from openpower.decoder.helpers import (EXTS, EXTS64, EXTZ64, ROTL64, ROTL32,
24 MASK, MASK32,
25 ne, eq, gt, ge, lt, le, ltu, gtu, length,
26 trunc_divs, trunc_rems, MULS, DIVS, MODS,
27 EXTS128, undefined,
28 DOUBLE, SINGLE,
29 FPADD32, FPSUB32, FPMUL32, FPDIV32,
30 FPADD64, FPSUB64, FPMUL64, FPDIV64,
31 )
32 from openpower.decoder.selectable_int import SelectableInt
33 from openpower.decoder.selectable_int import selectconcat as concat
34 from openpower.decoder.orderedset import OrderedSet
35
36 """
37
38 fpheader = """
39 from openpower.decoder.helpers import (
40 DOUBLE, SINGLE,
41 FPADD32, FPSUB32, FPMUL32, FPDIV32,
42 FPADD64, FPSUB64, FPMUL64, FPDIV64,
43 )
44 from openpower.decoder.isafunctions.fpfromint import INT2FP
45
46
47 """
48
49 iinfo_template = """instruction_info(func=%s,
50 read_regs=%s,
51 uninit_regs=%s, write_regs=%s,
52 special_regs=%s, op_fields=%s,
53 form='%s',
54 asmregs=%s)"""
55
56
57 class PyISAWriter(ISA):
58 def __init__(self):
59 ISA.__init__(self)
60 self.pages_written = []
61
62 def write_pysource(self, pagename):
63 self.pages_written.append(pagename)
64 instrs = self.page[pagename]
65 isadir = get_isasrc_dir()
66 fname = os.path.join(isadir, "%s.py" % pagename)
67 with open(fname, "w") as f:
68 iinf = ''
69 # write headers: FP gets extra imports
70 f.write(header) # write out header
71 if pagename.startswith("fp"):
72 f.write(fpheader)
73 f.write("class %s:\n" % pagename)
74
75 # go through all instructions
76 for page in instrs:
77 d = self.instr[page]
78 print("page", pagename, page, fname, d.opcode)
79 pcode = '\n'.join(d.pcode) + '\n'
80 print(pcode)
81 incl_carry = pagename == 'fixedshift'
82 pycode, rused = convert_to_python(pcode, d.form, incl_carry)
83 # create list of arguments to call
84 regs = list(rused['read_regs']) + list(rused['uninit_regs'])
85 regs += list(rused['special_regs'])
86 args = ', '.join(create_args(regs, 'self'))
87 # create list of arguments to return
88 retargs = ', '.join(create_args(rused['write_regs']))
89 # write out function. pre-pend "op_" because some instrs are
90 # also python keywords (cmp). also replace "." with "_"
91 op_fname = "op_%s" % page.replace(".", "_")
92 f.write(" @inject()\n")
93 f.write(" def %s(%s):\n" % (op_fname, args))
94 if 'NIA' in pycode: # HACK - TODO fix
95 f.write(" global NIA\n")
96 pycode = pycode.split("\n")
97 pycode = '\n'.join(map(lambda x: " %s" % x, pycode))
98 pycode = pycode.rstrip()
99 f.write(pycode + '\n')
100 if retargs:
101 f.write(" return (%s,)\n\n" % retargs)
102 else:
103 f.write("\n")
104 # accumulate the instruction info
105 ops = repr(rused['op_fields'])
106 iinfo = iinfo_template % (op_fname, rused['read_regs'],
107 rused['uninit_regs'],
108 rused['write_regs'],
109 rused['special_regs'],
110 ops, d.form, d.regs)
111 iinf += " %s_instrs['%s'] = %s\n" % (pagename, page, iinfo)
112 # write out initialisation of info, for ISACaller to use
113 f.write(" %s_instrs = {}\n" % pagename)
114 f.write(iinf)
115
116 def patch_if_needed(self, source):
117 isadir = get_isasrc_dir()
118 fname = os.path.join(isadir, "%s.py" % source)
119 patchname = os.path.join(isadir, "%s.patch" % source)
120
121 try:
122 with open(patchname, 'r') as patch:
123 newfname = fname + '.orig'
124 shutil.copyfile(fname, newfname)
125 subprocess.check_call(['patch', fname],
126 stdin=patch)
127 except:
128 pass
129
130 def write_isa_class(self):
131 isadir = get_isasrc_dir()
132 fname = os.path.join(isadir, "all.py")
133
134 with open(fname, "w") as f:
135 f.write('# auto-generated by pywriter.py: do not edit or commit\n')
136 f.write('from openpower.decoder.isa.caller import ISACaller\n')
137 for page in self.pages_written:
138 f.write('from openpower.decoder.isa.%s ' \
139 'import %s\n' % (page, page))
140 f.write('\n')
141
142 classes = ', '.join(['ISACaller'] + self.pages_written)
143 f.write('class ISA(%s):\n' % classes)
144 f.write(' def __init__(self, *args, **kwargs):\n')
145 f.write(' super().__init__(*args, **kwargs)\n')
146 f.write(' self.instrs = {\n')
147 for page in self.pages_written:
148 f.write(' **self.%s_instrs,\n' % page)
149 f.write(' }\n')
150
151
152 def pywriter():
153 isa = PyISAWriter()
154 write_isa_class = True
155 if len(sys.argv) == 1: # quick way to do it
156 print(dir(isa))
157 sources = isa.page.keys()
158 else:
159 sources = sys.argv[1:]
160 if sources[0] == "noall": # don't rewrite all.py
161 write_isa_class = False
162 sources.pop(0)
163 print ("sources", write_isa_class, sources)
164 for source in sources:
165 isa.write_pysource(source)
166 isa.patch_if_needed(source)
167 if write_isa_class:
168 isa.write_isa_class()
169
170 if __name__ == '__main__':
171 pywriter()