from functools import wraps
from soc.decoder.orderedset import OrderedSet
from soc.decoder.selectable_int import SelectableInt, selectconcat
+from collections import namedtuple
import math
+instruction_info = namedtuple('instruction_info',
+ 'func read_regs uninit_regs write_regs op_fields form asmregs')
+
+
def create_args(reglist, extra=None):
args = OrderedSet()
for reg in reglist:
args = [extra] + args
return args
+
class Mem:
def __init__(self, bytes_per_word=8):
s = ' '.join(s)
print("reg", "%2d" % i, s)
+class PC:
+ def __init__(self, pc_init=0):
+ self.CIA = SelectableInt(pc_init, 64)
+ self.NIA = self.CIA + SelectableInt(4, 64)
+
+ def update(self, namespace):
+ self.CIA = self.NIA
+ self.NIA = self.CIA + SelectableInt(4, 64)
+ namespace['CIA'] = self.CIA
+ namespace['NIA'] = self.NIA
+
class ISACaller:
# decoder2 - an instance of power_decoder2
def __init__(self, decoder2, regfile):
self.gpr = GPR(decoder2, regfile)
self.mem = Mem()
+ self.pc = PC()
self.namespace = {'GPR': self.gpr,
'MEM': self.mem,
- 'memassign': self.memassign
+ 'memassign': self.memassign,
+ 'NIA': self.pc.NIA,
+ 'CIA': self.pc.CIA,
}
+
self.decoder = decoder2
def memassign(self, ea, sz, val):
# from spec
# then "yield" fields only from op_fields rather than hard-coded
# list, here.
- for name in ['SI', 'UI', 'D', 'BD']:
- signal = getattr(self.decoder, name)
- val = yield signal
- self.namespace[name] = SelectableInt(val, bits=signal.width)
+ fields = self.decoder.sigforms[formname]
+ for name in fields._fields:
+ if name not in ["RA", "RB", "RT"]:
+ sig = getattr(fields, name)
+ val = yield sig
+ self.namespace[name] = SelectableInt(val, sig.width)
def call(self, name):
# TODO, asmregs is from the spec, e.g. add RT,RA,RB
# see http://bugs.libre-riscv.org/show_bug.cgi?id=282
- fn, read_regs, uninit_regs, write_regs, op_fields, asmregs, form \
- = self.instrs[name]
- yield from self.prep_namespace(form, op_fields)
+ info = self.instrs[name]
+ yield from self.prep_namespace(info.form, info.op_fields)
- input_names = create_args(read_regs | uninit_regs)
+ input_names = create_args(info.read_regs | info.uninit_regs)
print(input_names)
inputs = []
print('reading reg %d' % regnum)
inputs.append(self.gpr(regnum))
print(inputs)
- results = fn(self, *inputs)
+ results = info.func(self, *inputs)
print(results)
- if write_regs:
- output_names = create_args(write_regs)
+ if info.write_regs:
+ output_names = create_args(info.write_regs)
for name, output in zip(output_names, results):
regnum = yield getattr(self.decoder, name)
print('writing reg %d' % regnum)
if output.bits > 64:
output = SelectableInt(output.value, 64)
self.gpr[regnum] = output
+ self.pc.update(self.namespace)
def inject():
print(sim.gpr(1))
self.assertEqual(sim.gpr(3), SelectableInt(0x1234, 64))
+ def test_addpcis(self):
+ lst = ["addpcis 1, 0x1",
+ "addpcis 2, 0x1",
+ "addpcis 3, 0x1"]
+ with Program(lst) as program:
+ sim = self.run_tst_program(program)
+ self.assertEqual(sim.gpr(1), SelectableInt(0x10004, 64))
+ self.assertEqual(sim.gpr(2), SelectableInt(0x10008, 64))
+ self.assertEqual(sim.gpr(3), SelectableInt(0x1000c, 64))
+
def run_tst_program(self, prog, initial_regs=[0] * 32):
simulator = self.run_tst(prog, initial_regs)
simulator.gpr.dump()
res = {}
for field in fields:
f, spec = field.strip().split(" ")
+ ss = spec[1:-1].split(",")
+ fs = f.split(",")
+ if len(fs) > 1:
+ individualfields = []
+ for f0, s0 in zip(fs, ss):
+ txt = "%s (%s)" % (f0, s0)
+ individualfields.append(txt)
+ if len(fs) > 1:
+ res.update(self.decode_instruction_fields(individualfields))
d = self.bitkls(*self.bitargs)
idx = 0
- for s in spec[1:-1].split(","):
+ for s in ss:
s = s.split(':')
if len(s) == 1:
d[idx] = int(s[0])
dec = DecodeFields()
dec.create_specs()
forms, instrs = dec.forms, dec.instrs
+ for form, fields in instrs.items():
+ print ("Form", form)
+ for field, bits in fields.items():
+ print ("\tfield", field, bits)
def INDENT(lineno):
return _new_token("INDENT", lineno)
+def count_spaces(l):
+ for i in range(len(l)):
+ if l[i] != ' ':
+ return i
+ return 0
+
+def annoying_case_hack_filter(code):
+ """add annoying "silent keyword" (fallthrough)
+
+ this which tricks the parser into taking the (silent) case statement
+ as a "small expression". it can then be spotted and used to indicate
+ "fall through" to the next case (in the parser)
+
+ also skips blank lines
+
+ bugs: any function that starts with the letters "case" or "default"
+ will be detected erroneously. fixing that involves doing a token
+ lexer which spots the fact that "case" and "default" are words,
+ separating them from space, colon, bracket etc.
+
+ http://bugs.libre-riscv.org/show_bug.cgi?id=280
+ """
+ res = []
+ prev_spc_count = None
+ for l in code.split("\n"):
+ spc_count = count_spaces(l)
+ nwhite = l[spc_count:]
+ if len(nwhite) == 0: # skip blank lines
+ continue
+ if nwhite.startswith("case") or nwhite.startswith("default"):
+ #print ("case/default", nwhite, spc_count, prev_spc_count)
+ if (prev_spc_count is not None and
+ prev_spc_count == spc_count and
+ (res[-1].endswith(":") or res[-1].endswith(": fallthrough"))):
+ res[-1] += " fallthrough" # add to previous line
+ prev_spc_count = spc_count
+ else:
+ #print ("notstarts", spc_count, nwhite)
+ prev_spc_count = None
+ res.append(l)
+ return '\n'.join(res)
+
# Track the indentation level and emit the right INDENT / DEDENT events.
def indentation_filter(tokens):
class IndentLexer(PowerLexer):
def __init__(self, debug=0, optimize=0, lextab='lextab', reflags=0):
+ self.debug = debug
self.build(debug=debug, optimize=optimize,
lextab=lextab, reflags=reflags)
self.token_stream = None
def input(self, s, add_endmarker=True):
+ s = annoying_case_hack_filter(s)
+ if self.debug:
+ print (s)
+ s += "\n"
self.lexer.paren_count = 0
self.lexer.brack_count = 0
self.lexer.input(s)
switchtest = """
switch (n)
case(1): x <- 5
- case(2): fallthrough
- case(3):
+ case(3): x <- 2
+ case(2):
+
+ case(4):
x <- 3
+ case(9):
+
default:
x <- 9
print (5)
# quick test/demo
#code = cnttzd
code = switchtest
+ print (code)
lexer = IndentLexer(debug=1)
# Give the lexer some input
opcode, regs = o[0], o[1:]
op = copy(d)
op['regs'] = regs
+ regs[0] = regs[0].split(",")
op['opcode'] = opcode
self.instr[opcode] = Ops(**op)
header = """\
# auto-generated by pywriter.py, do not edit or commit
-from soc.decoder.isa.caller import inject
+from soc.decoder.isa.caller import inject, instruction_info
from soc.decoder.helpers import (EXTS, EXTS64, EXTZ64, ROTL64, ROTL32, MASK,)
from soc.decoder.selectable_int import SelectableInt
from soc.decoder.selectable_int import selectconcat as concat
"""
-iinfo_template = """(%s, %s,
- %s, %s,
- %s, '%s',
- %s)"""
+iinfo_template = """instruction_info(func=%s,
+ read_regs=%s,
+ uninit_regs=%s, write_regs=%s,
+ op_fields=%s, form='%s',
+ asmregs=%s)"""
class PyISAWriter(ISA):
def __init__(self):
# accumulate the instruction info
ops = repr(rused['op_fields'])
iinfo = iinfo_template % (op_fname, rused['read_regs'],
- rused['uninit_regs'], rused['write_regs'],
- ops, d.form, d.regs)
+ rused['uninit_regs'],
+ rused['write_regs'],
+ ops, d.form, d.regs)
iinf += " %s_instrs['%s'] = %s\n" % (pagename, page, iinfo)
# write out initialisation of info, for ISACaller to use
f.write(" %s_instrs = {}\n" % pagename)
f.write(' }\n')
-
-
-
if __name__ == '__main__':
isa = PyISAWriter()
if len(sys.argv) == 1: # quick way to do it
def _assemble(self):
with tempfile.NamedTemporaryFile(suffix=".o") as outfile:
args = ["powerpc64-linux-gnu-as",
+ '-mpower9',
obj_fmt,
"-o",
outfile.name]