#!/usr/bin/python
import sys

if len(sys.argv) == 3:
  numfiles = int(sys.argv[1])
  tablesz = int(sys.argv[2])
  filenum = numfiles+1
else:
  filenum = int(sys.argv[1])
  numfiles = int(sys.argv[2])
  tablesz = int(sys.argv[3])

match = {}
mask = {}
seen = {}
for line in sys.stdin:
  (name, mtch, msk) = line.split('(')[1].split(')')[0].split(',')
  match[name] = int(mtch,16)
  mask[name] = int(msk,16)

redundant = {}
for name in match.iterkeys():
  if (mask[name] & (tablesz-1)) == mask[name]:
    for i in range(match[name]+1, tablesz):
      if (i & mask[name]) == match[name]:
        redundant[i] = match[name]

illegal = -1
for i in range(0, tablesz):
  used = 0
  for name in match.iterkeys():
    if match[name] % tablesz == (i & mask[name]):
      used = 1
  if not used and illegal == -1:
    illegal = i
  elif not used:
    redundant[i] = illegal

if filenum == numfiles:
  print '#include "processor.h"'
  print 'const insn_func_t processor_t::dispatch_table[DISPATCH_TABLE_SIZE] = {'
  for i in range(0, tablesz):
    func = i
    if i in redundant:
      func = redundant[i]
    print '  &processor_t::insn_func_%d,' % func
  print '};'

if filenum == numfiles+1:
  print 'static const size_t DISPATCH_TABLE_SIZE = %d;' % tablesz
  print 'static const insn_func_t dispatch_table[DISPATCH_TABLE_SIZE];'
  for i in range(0, tablesz):
    if i not in redundant:
      print 'reg_t insn_func_%d(insn_t insn, reg_t reg);' % i
  sys.exit(0)

print '#include "insn_header.h"'

for i in range(0, tablesz):
  if i % numfiles != filenum or i in redundant:
    continue

  print 'reg_t processor_t::insn_func_%d(insn_t insn, reg_t pc)' % i
  print '{'
  for name in match.iterkeys():
    if match[name] % tablesz == (i & mask[name]):
      print '  if((insn.bits & 0x%x) == 0x%x)' % (mask[name] & ~(tablesz-1), \
                                                  match[name] & ~(tablesz-1))
      print '  {'
      print '    reg_t npc = pc + insn_length(0x%x);' % match[name]
      print '    #include "insns/%s.h"' % name
      print '    return npc;'
      print '  }'
      print '  else',

  print '  throw trap_illegal_instruction;'
  print '}\n'
