Path: blob/21.2-virgl/src/gallium/drivers/r600/egd_tables.py
4570 views
from __future__ import print_function12CopyRight = '''3/*4* Copyright 2015 Advanced Micro Devices, Inc.5*6* Permission is hereby granted, free of charge, to any person obtaining a7* copy of this software and associated documentation files (the "Software"),8* to deal in the Software without restriction, including without limitation9* on the rights to use, copy, modify, merge, publish, distribute, sub10* license, and/or sell copies of the Software, and to permit persons to whom11* the Software is furnished to do so, subject to the following conditions:12*13* The above copyright notice and this permission notice (including the next14* paragraph) shall be included in all copies or substantial portions of the15* Software.16*17* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR18* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,19* FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL20* THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,21* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR22* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE23* USE OR OTHER DEALINGS IN THE SOFTWARE.24*25*/26'''2728import sys29import re303132class StringTable:33"""34A class for collecting multiple strings in a single larger string that is35used by indexing (to avoid relocations in the resulting binary)36"""37def __init__(self):38self.table = []39self.length = 04041def add(self, string):42# We might get lucky with string being a suffix of a previously added string43for te in self.table:44if te[0].endswith(string):45idx = te[1] + len(te[0]) - len(string)46te[2].add(idx)47return idx4849idx = self.length50self.table.append((string, idx, set((idx,))))51self.length += len(string) + 15253return idx5455def emit(self, filp, name, static=True):56"""57Write58[static] const char name[] = "...";59to filp.60"""61fragments = [62'"%s\\0" /* %s */' % (63te[0].encode('unicode_escape').decode(),64', '.join(str(idx) for idx in te[2])65)66for te in self.table67]68filp.write('%sconst char %s[] =\n%s;\n' % (69'static ' if static else '',70name,71'\n'.join('\t' + fragment for fragment in fragments)72))7374class IntTable:75"""76A class for collecting multiple arrays of integers in a single big array77that is used by indexing (to avoid relocations in the resulting binary)78"""79def __init__(self, typename):80self.typename = typename81self.table = []82self.idxs = set()8384def add(self, array):85# We might get lucky and find the array somewhere in the existing data86try:87idx = 088while True:89idx = self.table.index(array[0], idx, len(self.table) - len(array) + 1)9091for i in range(1, len(array)):92if array[i] != self.table[idx + i]:93break94else:95self.idxs.add(idx)96return idx9798idx += 199except ValueError:100pass101102idx = len(self.table)103self.table += array104self.idxs.add(idx)105return idx106107def emit(self, filp, name, static=True):108"""109Write110[static] const typename name[] = { ... };111to filp.112"""113idxs = sorted(self.idxs) + [len(self.table)]114115fragments = [116('\t/* %s */ %s' % (117idxs[i],118' '.join((str(elt) + ',') for elt in self.table[idxs[i]:idxs[i+1]])119))120for i in range(len(idxs) - 1)121]122123filp.write('%sconst %s %s[] = {\n%s\n};\n' % (124'static ' if static else '',125self.typename, name,126'\n'.join(fragments)127))128129class Field:130def __init__(self, reg, s_name):131self.s_name = s_name132self.name = strip_prefix(s_name)133self.values = []134self.varname_values = '%s__%s__values' % (reg.r_name.lower(), self.name.lower())135136class Reg:137def __init__(self, r_name):138self.r_name = r_name139self.name = strip_prefix(r_name)140self.fields = []141self.own_fields = True142143144def strip_prefix(s):145'''Strip prefix in the form ._.*_, e.g. R_001234_'''146return s[s[2:].find('_')+3:]147148def parse(filename, regs, packets):149stream = open(filename)150151for line in stream:152if not line.startswith('#define '):153continue154155line = line[8:].strip()156157if line.startswith('R_'):158name = line.split()[0]159160for it in regs:161if it.r_name == name:162reg = it163break164else:165reg = Reg(name)166regs.append(reg)167168elif line.startswith('S_'):169name = line[:line.find('(')]170171for it in reg.fields:172if it.s_name == name:173field = it174break175else:176field = Field(reg, name)177reg.fields.append(field)178179elif line.startswith('V_'):180split = line.split()181name = split[0]182value = int(split[1], 0)183184for (n,v) in field.values:185if n == name:186if v != value:187sys.exit('Value mismatch: name = ' + name)188189field.values.append((name, value))190191elif line.startswith('PKT3_') and line.find('0x') != -1 and line.find('(') == -1:192packets.append(line.split()[0])193194# Copy fields to indexed registers which have their fields only defined195# at register index 0.196# For example, copy fields from CB_COLOR0_INFO to CB_COLORn_INFO, n > 0.197match_number = re.compile('[0-9]+')198reg_dict = dict()199200# Create a dict of registers with fields and '0' in their name201for reg in regs:202if len(reg.fields) and reg.name.find('0') != -1:203reg_dict[reg.name] = reg204205# Assign fields206for reg in regs:207if not len(reg.fields):208reg0 = reg_dict.get(match_number.sub('0', reg.name))209if reg0 != None:210reg.fields = reg0.fields211reg.fields_owner = reg0212reg.own_fields = False213214215def write_tables(regs, packets):216217strings = StringTable()218strings_offsets = IntTable("int")219220print('/* This file is autogenerated by egd_tables.py from evergreend.h. Do not edit directly. */')221print()222print(CopyRight.strip())223print('''224#ifndef EG_TABLES_H225#define EG_TABLES_H226227struct eg_field {228unsigned name_offset;229unsigned mask;230unsigned num_values;231unsigned values_offset; /* offset into eg_strings_offsets */232};233234struct eg_reg {235unsigned name_offset;236unsigned offset;237unsigned num_fields;238unsigned fields_offset;239};240241struct eg_packet3 {242unsigned name_offset;243unsigned op;244};245''')246247print('static const struct eg_packet3 packet3_table[] = {')248for pkt in packets:249print('\t{%s, %s},' % (strings.add(pkt[5:]), pkt))250print('};')251print()252253print('static const struct eg_field egd_fields_table[] = {')254255fields_idx = 0256for reg in regs:257if len(reg.fields) and reg.own_fields:258print('\t/* %s */' % (fields_idx))259260reg.fields_idx = fields_idx261262for field in reg.fields:263if len(field.values):264values_offsets = []265for value in field.values:266while value[1] >= len(values_offsets):267values_offsets.append(-1)268values_offsets[value[1]] = strings.add(strip_prefix(value[0]))269print('\t{%s, %s(~0u), %s, %s},' % (270strings.add(field.name), field.s_name,271len(values_offsets), strings_offsets.add(values_offsets)))272else:273print('\t{%s, %s(~0u)},' % (strings.add(field.name), field.s_name))274fields_idx += 1275276print('};')277print()278279print('static const struct eg_reg egd_reg_table[] = {')280for reg in regs:281if len(reg.fields):282print('\t{%s, %s, %s, %s},' % (strings.add(reg.name), reg.r_name,283len(reg.fields), reg.fields_idx if reg.own_fields else reg.fields_owner.fields_idx))284else:285print('\t{%s, %s},' % (strings.add(reg.name), reg.r_name))286print('};')287print()288289strings.emit(sys.stdout, "egd_strings")290291print()292293strings_offsets.emit(sys.stdout, "egd_strings_offsets")294295print()296print('#endif')297298299def main():300regs = []301packets = []302for arg in sys.argv[1:]:303parse(arg, regs, packets)304write_tables(regs, packets)305306307if __name__ == '__main__':308main()309310# kate: space-indent on; indent-width 4; replace-tabs on;311312313