amd: remove shebang from python scripts
[mesa.git] / src / amd / common / sid_tables.py
1
2 CopyRight = '''
3 /*
4 * Copyright 2015 Advanced Micro Devices, Inc.
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * on the rights to use, copy, modify, merge, publish, distribute, sub
10 * license, and/or sell copies of the Software, and to permit persons to whom
11 * the Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice (including the next
14 * paragraph) shall be included in all copies or substantial portions of the
15 * Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHOR(S) AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM,
21 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
22 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
23 * USE OR OTHER DEALINGS IN THE SOFTWARE.
24 *
25 */
26 '''
27
28 import sys
29 import re
30
31
32 class StringTable:
33 """
34 A class for collecting multiple strings in a single larger string that is
35 used by indexing (to avoid relocations in the resulting binary)
36 """
37 def __init__(self):
38 self.table = []
39 self.length = 0
40
41 def add(self, string):
42 # We might get lucky with string being a suffix of a previously added string
43 for te in self.table:
44 if te[0].endswith(string):
45 idx = te[1] + len(te[0]) - len(string)
46 te[2].add(idx)
47 return idx
48
49 idx = self.length
50 self.table.append((string, idx, set((idx,))))
51 self.length += len(string) + 1
52
53 return idx
54
55 def emit(self, filp, name, static=True):
56 """
57 Write
58 [static] const char name[] = "...";
59 to filp.
60 """
61 fragments = [
62 '"%s\\0" /* %s */' % (
63 te[0].encode('string_escape'),
64 ', '.join(str(idx) for idx in te[2])
65 )
66 for te in self.table
67 ]
68 filp.write('%sconst char %s[] =\n%s;\n' % (
69 'static ' if static else '',
70 name,
71 '\n'.join('\t' + fragment for fragment in fragments)
72 ))
73
74 class IntTable:
75 """
76 A class for collecting multiple arrays of integers in a single big array
77 that is used by indexing (to avoid relocations in the resulting binary)
78 """
79 def __init__(self, typename):
80 self.typename = typename
81 self.table = []
82 self.idxs = set()
83
84 def add(self, array):
85 # We might get lucky and find the array somewhere in the existing data
86 try:
87 idx = 0
88 while True:
89 idx = self.table.index(array[0], idx, len(self.table) - len(array) + 1)
90
91 for i in range(1, len(array)):
92 if array[i] != self.table[idx + i]:
93 break
94 else:
95 self.idxs.add(idx)
96 return idx
97
98 idx += 1
99 except ValueError:
100 pass
101
102 idx = len(self.table)
103 self.table += array
104 self.idxs.add(idx)
105 return idx
106
107 def emit(self, filp, name, static=True):
108 """
109 Write
110 [static] const typename name[] = { ... };
111 to filp.
112 """
113 idxs = sorted(self.idxs) + [-1]
114
115 fragments = [
116 ('\t/* %s */ %s' % (
117 idxs[i],
118 ' '.join((str(elt) + ',') for elt in self.table[idxs[i]:idxs[i+1]])
119 ))
120 for i in range(len(idxs) - 1)
121 ]
122
123 filp.write('%sconst %s %s[] = {\n%s\n};\n' % (
124 'static ' if static else '',
125 self.typename, name,
126 '\n'.join(fragments)
127 ))
128
129 class Field:
130 def __init__(self, reg, s_name):
131 self.s_name = s_name
132 self.name = strip_prefix(s_name)
133 self.values = []
134 self.varname_values = '%s__%s__values' % (reg.r_name.lower(), self.name.lower())
135
136 class Reg:
137 def __init__(self, r_name):
138 self.r_name = r_name
139 self.name = strip_prefix(r_name)
140 self.fields = []
141 self.own_fields = True
142
143
144 def strip_prefix(s):
145 '''Strip prefix in the form ._.*_, e.g. R_001234_'''
146 return s[s[2:].find('_')+3:]
147
148
149 def parse(filename):
150 stream = open(filename)
151 regs = []
152 packets = []
153
154 for line in stream:
155 if not line.startswith('#define '):
156 continue
157
158 line = line[8:].strip()
159
160 if line.startswith('R_'):
161 reg = Reg(line.split()[0])
162 regs.append(reg)
163
164 elif line.startswith('S_'):
165 field = Field(reg, line[:line.find('(')])
166 reg.fields.append(field)
167
168 elif line.startswith('V_'):
169 split = line.split()
170 field.values.append((split[0], int(split[1], 0)))
171
172 elif line.startswith('PKT3_') and line.find('0x') != -1 and line.find('(') == -1:
173 packets.append(line.split()[0])
174
175 # Copy fields to indexed registers which have their fields only defined
176 # at register index 0.
177 # For example, copy fields from CB_COLOR0_INFO to CB_COLORn_INFO, n > 0.
178 match_number = re.compile('[0-9]+')
179 reg_dict = dict()
180
181 # Create a dict of registers with fields and '0' in their name
182 for reg in regs:
183 if len(reg.fields) and reg.name.find('0') != -1:
184 reg_dict[reg.name] = reg
185
186 # Assign fields
187 for reg in regs:
188 if not len(reg.fields):
189 reg0 = reg_dict.get(match_number.sub('0', reg.name))
190 if reg0 != None:
191 reg.fields = reg0.fields
192 reg.fields_owner = reg0
193 reg.own_fields = False
194
195 return (regs, packets)
196
197
198 def write_tables(tables):
199 regs = tables[0]
200 packets = tables[1]
201
202 strings = StringTable()
203 strings_offsets = IntTable("int")
204
205 print '/* This file is autogenerated by sid_tables.py from sid.h. Do not edit directly. */'
206 print
207 print CopyRight.strip()
208 print '''
209 #ifndef SID_TABLES_H
210 #define SID_TABLES_H
211
212 struct si_field {
213 unsigned name_offset;
214 unsigned mask;
215 unsigned num_values;
216 unsigned values_offset; /* offset into sid_strings_offsets */
217 };
218
219 struct si_reg {
220 unsigned name_offset;
221 unsigned offset;
222 unsigned num_fields;
223 unsigned fields_offset;
224 };
225
226 struct si_packet3 {
227 unsigned name_offset;
228 unsigned op;
229 };
230 '''
231
232 print 'static const struct si_packet3 packet3_table[] = {'
233 for pkt in packets:
234 print '\t{%s, %s},' % (strings.add(pkt[5:]), pkt)
235 print '};'
236 print
237
238 print 'static const struct si_field sid_fields_table[] = {'
239
240 fields_idx = 0
241 for reg in regs:
242 if len(reg.fields) and reg.own_fields:
243 print '\t/* %s */' % (fields_idx)
244
245 reg.fields_idx = fields_idx
246
247 for field in reg.fields:
248 if len(field.values):
249 values_offsets = []
250 for value in field.values:
251 while value[1] >= len(values_offsets):
252 values_offsets.append(-1)
253 values_offsets[value[1]] = strings.add(strip_prefix(value[0]))
254 print '\t{%s, %s(~0u), %s, %s},' % (
255 strings.add(field.name), field.s_name,
256 len(values_offsets), strings_offsets.add(values_offsets))
257 else:
258 print '\t{%s, %s(~0u)},' % (strings.add(field.name), field.s_name)
259 fields_idx += 1
260
261 print '};'
262 print
263
264 print 'static const struct si_reg sid_reg_table[] = {'
265 for reg in regs:
266 if len(reg.fields):
267 print '\t{%s, %s, %s, %s},' % (strings.add(reg.name), reg.r_name,
268 len(reg.fields), reg.fields_idx if reg.own_fields else reg.fields_owner.fields_idx)
269 else:
270 print '\t{%s, %s},' % (strings.add(reg.name), reg.r_name)
271 print '};'
272 print
273
274 strings.emit(sys.stdout, "sid_strings")
275
276 print
277
278 strings_offsets.emit(sys.stdout, "sid_strings_offsets")
279
280 print
281 print '#endif'
282
283
284 def main():
285 tables = []
286 for arg in sys.argv[1:]:
287 tables.extend(parse(arg))
288 write_tables(tables)
289
290
291 if __name__ == '__main__':
292 main()
293
294 # kate: space-indent on; indent-width 4; replace-tabs on;