broadcom/xml: Fix up safe name confusion with prefixing.
[mesa.git] / src / broadcom / cle / gen_pack_header.py
1 #encoding=utf-8
2
3 # Copyright (C) 2016 Intel Corporation
4 # Copyright (C) 2016 Broadcom
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 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 # and/or sell copies of the Software, and to permit persons to whom the
11 # 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 NONINFRINGEMENT. IN NO EVENT SHALL
20 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
23 # IN THE SOFTWARE.
24
25 from __future__ import (
26 absolute_import, division, print_function, unicode_literals
27 )
28 import xml.parsers.expat
29 import re
30 import sys
31 import copy
32
33 license = """/* Generated code, see packets.xml and gen_packet_header.py */
34 """
35
36 pack_header = """%(license)s
37
38 /* Packets, enums and structures for %(platform)s.
39 *
40 * This file has been generated, do not hand edit.
41 */
42
43 #ifndef %(guard)s
44 #define %(guard)s
45
46 #include "v3d_packet_helpers.h"
47
48 """
49
50 def to_alphanum(name):
51 substitutions = {
52 ' ': '_',
53 '/': '_',
54 '[': '',
55 ']': '',
56 '(': '',
57 ')': '',
58 '-': '_',
59 ':': '',
60 '.': '',
61 ',': '',
62 '=': '',
63 '>': '',
64 '#': '',
65 'α': 'alpha',
66 '&': '',
67 '*': '',
68 '"': '',
69 '+': '',
70 '\'': '',
71 }
72
73 for i, j in substitutions.items():
74 name = name.replace(i, j)
75
76 return name
77
78 def safe_name(name):
79 name = to_alphanum(name)
80 if not name[0].isalpha():
81 name = '_' + name
82
83 return name
84
85 def prefixed_upper_name(prefix, name):
86 if prefix:
87 name = prefix + "_" + name
88 return safe_name(name).upper()
89
90 def num_from_str(num_str):
91 if num_str.lower().startswith('0x'):
92 return int(num_str, base=16)
93 else:
94 assert(not num_str.startswith('0') and 'octals numbers not allowed')
95 return int(num_str)
96
97 class Field(object):
98 ufixed_pattern = re.compile(r"u(\d+)\.(\d+)")
99 sfixed_pattern = re.compile(r"s(\d+)\.(\d+)")
100
101 def __init__(self, parser, attrs):
102 self.parser = parser
103 if "name" in attrs:
104 self.name = safe_name(attrs["name"]).lower()
105
106 if str(attrs["start"]).endswith("b"):
107 self.start = int(attrs["start"][:-1]) * 8
108 else:
109 self.start = int(attrs["start"])
110 # packet <field> entries in XML start from the bit after the
111 # opcode, so shift everything up by 8 since we'll also have a
112 # Field for the opcode.
113 if not parser.struct:
114 self.start += 8
115
116 self.end = self.start + int(attrs["size"]) - 1
117 self.type = attrs["type"]
118
119 if self.type == 'bool' and self.start != self.end:
120 print("#error Field {} has bool type but more than one bit of size".format(self.name));
121
122 if "prefix" in attrs:
123 self.prefix = safe_name(attrs["prefix"]).upper()
124 else:
125 self.prefix = None
126
127 if "default" in attrs:
128 self.default = int(attrs["default"])
129 else:
130 self.default = None
131
132 ufixed_match = Field.ufixed_pattern.match(self.type)
133 if ufixed_match:
134 self.type = 'ufixed'
135 self.fractional_size = int(ufixed_match.group(2))
136
137 sfixed_match = Field.sfixed_pattern.match(self.type)
138 if sfixed_match:
139 self.type = 'sfixed'
140 self.fractional_size = int(sfixed_match.group(2))
141
142 def emit_template_struct(self, dim):
143 if self.type == 'address':
144 type = '__gen_address_type'
145 elif self.type == 'bool':
146 type = 'bool'
147 elif self.type == 'float':
148 type = 'float'
149 elif self.type == 'ufixed':
150 type = 'float'
151 elif self.type == 'sfixed':
152 type = 'float'
153 elif self.type == 'uint' and self.end - self.start > 32:
154 type = 'uint64_t'
155 elif self.type == 'offset':
156 type = 'uint64_t'
157 elif self.type == 'int':
158 type = 'int32_t'
159 elif self.type == 'uint':
160 type = 'uint32_t'
161 elif self.type in self.parser.structs:
162 type = 'struct ' + self.parser.gen_prefix(safe_name(self.type))
163 elif self.type in self.parser.enums:
164 type = 'enum ' + self.parser.gen_prefix(safe_name(self.type))
165 elif self.type == 'mbo':
166 return
167 else:
168 print("#error unhandled type: %s" % self.type)
169
170 print(" %-36s %s%s;" % (type, self.name, dim))
171
172 for value in self.values:
173 name = prefixed_upper_name(self.prefix, value.name)
174 print("#define %-40s %d" % (name, value.value))
175
176 def overlaps(self, field):
177 return self != field and max(self.start, field.start) <= min(self.end, field.end)
178
179
180 class Group(object):
181 def __init__(self, parser, parent, start, count):
182 self.parser = parser
183 self.parent = parent
184 self.start = start
185 self.count = count
186 self.size = 0
187 self.fields = []
188
189 def emit_template_struct(self, dim):
190 if self.count == 0:
191 print(" /* variable length fields follow */")
192 else:
193 if self.count > 1:
194 dim = "%s[%d]" % (dim, self.count)
195
196 for field in self.fields:
197 field.emit_template_struct(dim)
198
199 class Byte:
200 def __init__(self):
201 self.size = 8
202 self.fields = []
203 self.address = None
204
205 def collect_bytes(self, bytes):
206 for field in self.fields:
207 first_byte = field.start // 8
208 last_byte = field.end // 8
209
210 for b in xrange(first_byte, last_byte + 1):
211 if not b in bytes:
212 bytes[b] = self.Byte()
213
214 bytes[b].fields.append(field)
215
216 if field.type == "address":
217 # assert bytes[index].address == None
218 bytes[b].address = field
219
220 def emit_pack_function(self, start):
221 # Determine number of bytes in this group.
222 self.length = max(field.end // 8 for field in self.fields) + 1
223
224 bytes = {}
225 self.collect_bytes(bytes)
226
227 relocs_emitted = set()
228 memcpy_fields = set()
229
230 for index in range(self.length):
231 # Handle MBZ bytes
232 if not index in bytes:
233 print(" cl[%2d] = 0;" % index)
234 continue
235 byte = bytes[index]
236
237 # Call out to the driver to note our relocations. Inside of the
238 # packet we only store offsets within the BOs, and we store the
239 # handle to the packet outside. Unlike Intel genxml, we don't
240 # need to have the other bits that will be stored together with
241 # the address during the reloc process, so there's no need for the
242 # complicated combine_address() function.
243 if byte.address and byte.address not in relocs_emitted:
244 print(" __gen_emit_reloc(data, &values->%s);" % byte.address.name)
245 relocs_emitted.add(byte.address)
246
247 # Special case: floats can't have any other fields packed into
248 # them (since they'd change the meaning of the float), and the
249 # per-byte bitshifting math below bloats the pack code for floats,
250 # so just copy them directly here. Also handle 16/32-bit
251 # uints/ints with no merged fields.
252 if len(byte.fields) == 1:
253 field = byte.fields[0]
254 if field.type in ["float", "uint", "int"] and field.start % 8 == 0 and field.end - field.start == 31:
255 if field in memcpy_fields:
256 continue
257
258 if not any(field.overlaps(scan_field) for scan_field in self.fields):
259 assert(field.start == index * 8)
260 print("")
261 print(" memcpy(&cl[%d], &values->%s, sizeof(values->%s));" %
262 (index, field.name, field.name))
263 memcpy_fields.add(field)
264 continue
265
266 byte_start = index * 8
267
268 v = None
269 prefix = " cl[%2d] =" % index
270
271 field_index = 0
272 for field in byte.fields:
273 if field.type != "mbo":
274 name = field.name
275
276 start = field.start
277 end = field.end
278 field_byte_start = (field.start // 8) * 8
279 start -= field_byte_start
280 end -= field_byte_start
281 extra_shift = 0
282
283 if field.type == "mbo":
284 s = "__gen_mbo(%d, %d)" % \
285 (start, end)
286 elif field.type == "address":
287 extra_shift = (31 - (end - start)) // 8 * 8
288 s = "__gen_address_offset(&values->%s)" % byte.address.name
289 elif field.type == "uint":
290 s = "__gen_uint(values->%s, %d, %d)" % \
291 (name, start, end)
292 elif field.type in self.parser.enums:
293 s = "__gen_uint(values->%s, %d, %d)" % \
294 (name, start, end)
295 elif field.type == "int":
296 s = "__gen_sint(values->%s, %d, %d)" % \
297 (name, start, end)
298 elif field.type == "bool":
299 s = "__gen_uint(values->%s, %d, %d)" % \
300 (name, start, end)
301 elif field.type == "float":
302 s = "#error %s float value mixed in with other fields" % name
303 elif field.type == "offset":
304 s = "__gen_offset(values->%s, %d, %d)" % \
305 (name, start, end)
306 elif field.type == 'ufixed':
307 s = "__gen_ufixed(values->%s, %d, %d, %d)" % \
308 (name, start, end, field.fractional_size)
309 elif field.type == 'sfixed':
310 s = "__gen_sfixed(values->%s, %d, %d, %d)" % \
311 (name, start, end, field.fractional_size)
312 elif field.type in self.parser.structs:
313 s = "__gen_uint(v%d_%d, %d, %d)" % \
314 (index, field_index, start, end)
315 field_index = field_index + 1
316 else:
317 print("/* unhandled field %s, type %s */\n" % (name, field.type))
318 s = None
319
320 if not s == None:
321 shift = byte_start - field_byte_start + extra_shift
322 if shift:
323 s = "%s >> %d" % (s, shift)
324
325 if field == byte.fields[-1]:
326 print("%s %s;" % (prefix, s))
327 else:
328 print("%s %s |" % (prefix, s))
329 prefix = " "
330
331 print("")
332 continue
333
334 def emit_unpack_function(self, start):
335 for field in self.fields:
336 if field.type != "mbo":
337 convert = None
338
339 args = []
340 args.append('cl')
341 args.append(str(start + field.start))
342 args.append(str(start + field.end))
343
344 if field.type == "address":
345 convert = "__gen_unpack_address"
346 elif field.type == "uint":
347 convert = "__gen_unpack_uint"
348 elif field.type in self.parser.enums:
349 convert = "__gen_unpack_uint"
350 elif field.type == "int":
351 convert = "__gen_unpack_sint"
352 elif field.type == "bool":
353 convert = "__gen_unpack_uint"
354 elif field.type == "float":
355 convert = "__gen_unpack_float"
356 elif field.type == "offset":
357 convert = "__gen_unpack_offset"
358 elif field.type == 'ufixed':
359 args.append(str(field.fractional_size))
360 convert = "__gen_unpack_ufixed"
361 elif field.type == 'sfixed':
362 args.append(str(field.fractional_size))
363 convert = "__gen_unpack_sfixed"
364 else:
365 print("/* unhandled field %s, type %s */\n" % (name, field.type))
366 s = None
367
368 print(" values->%s = %s(%s);" % \
369 (field.name, convert, ', '.join(args)))
370
371 class Value(object):
372 def __init__(self, attrs):
373 self.name = attrs["name"]
374 self.value = int(attrs["value"])
375
376 class Parser(object):
377 def __init__(self):
378 self.parser = xml.parsers.expat.ParserCreate()
379 self.parser.StartElementHandler = self.start_element
380 self.parser.EndElementHandler = self.end_element
381
382 self.packet = None
383 self.struct = None
384 self.structs = {}
385 # Set of enum names we've seen.
386 self.enums = set()
387 self.registers = {}
388
389 def gen_prefix(self, name):
390 if name[0] == "_":
391 return 'V3D%s%s' % (self.ver, name)
392 else:
393 return 'V3D%s_%s' % (self.ver, name)
394
395 def gen_guard(self):
396 return self.gen_prefix("PACK_H")
397
398 def start_element(self, name, attrs):
399 if name == "vcxml":
400 self.platform = "V3D {}".format(attrs["gen"])
401 self.ver = attrs["gen"].replace('.', '')
402 print(pack_header % {'license': license, 'platform': self.platform, 'guard': self.gen_guard()})
403 elif name in ("packet", "struct", "register"):
404 default_field = None
405
406 object_name = self.gen_prefix(safe_name(attrs["name"].upper()))
407 if name == "packet":
408 self.packet = object_name
409
410 # Add a fixed Field for the opcode. We only make <field>s in
411 # the XML for the fields listed in the spec, and all of those
412 # start from bit 0 after of the opcode.
413 default_field = {
414 "name" : "opcode",
415 "default" : attrs["code"],
416 "type" : "uint",
417 "start" : -8,
418 "size" : 8,
419 }
420 elif name == "struct":
421 self.struct = object_name
422 self.structs[attrs["name"]] = 1
423 elif name == "register":
424 self.register = object_name
425 self.reg_num = num_from_str(attrs["num"])
426 self.registers[attrs["name"]] = 1
427
428 self.group = Group(self, None, 0, 1)
429 if default_field:
430 field = Field(self, default_field)
431 field.values = []
432 self.group.fields.append(field)
433
434 elif name == "field":
435 self.group.fields.append(Field(self, attrs))
436 self.values = []
437 elif name == "enum":
438 self.values = []
439 self.enum = safe_name(attrs["name"])
440 self.enums.add(attrs["name"])
441 if "prefix" in attrs:
442 self.prefix = attrs["prefix"]
443 else:
444 self.prefix= None
445 elif name == "value":
446 self.values.append(Value(attrs))
447
448 def end_element(self, name):
449 if name == "packet":
450 self.emit_packet()
451 self.packet = None
452 self.group = None
453 elif name == "struct":
454 self.emit_struct()
455 self.struct = None
456 self.group = None
457 elif name == "register":
458 self.emit_register()
459 self.register = None
460 self.reg_num = None
461 self.group = None
462 elif name == "field":
463 self.group.fields[-1].values = self.values
464 elif name == "enum":
465 self.emit_enum()
466 self.enum = None
467 elif name == "vcxml":
468 print('#endif /* %s */' % self.gen_guard())
469
470 def emit_template_struct(self, name, group):
471 print("struct %s {" % name)
472 group.emit_template_struct("")
473 print("};\n")
474
475 def emit_pack_function(self, name, group):
476 print("static inline void\n%s_pack(__gen_user_data *data, uint8_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
477 (name, ' ' * (len(name) + 6), name))
478
479 group.emit_pack_function(0)
480
481 print("}\n")
482
483 print('#define %-33s %6d' %
484 (name + "_length", self.group.length))
485
486 def emit_unpack_function(self, name, group):
487 print("#ifdef __gen_unpack_address")
488 print("static inline void")
489 print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
490 (name, ' ' * (len(name) + 8), name))
491
492 group.emit_unpack_function(0)
493
494 print("}\n#endif\n")
495
496 def emit_header(self, name):
497 default_fields = []
498 for field in self.group.fields:
499 if not type(field) is Field:
500 continue
501 if field.default == None:
502 continue
503 default_fields.append(" .%-35s = %6d" % (field.name, field.default))
504
505 print('#define %-40s\\' % (name + '_header'))
506 print(", \\\n".join(default_fields))
507 print('')
508
509 def emit_packet(self):
510 name = self.packet
511
512 assert(self.group.fields[0].name == "opcode")
513 print('#define %-33s %6d' %
514 (name + "_opcode", self.group.fields[0].default))
515
516 self.emit_header(name)
517 self.emit_template_struct(self.packet, self.group)
518 self.emit_pack_function(self.packet, self.group)
519 self.emit_unpack_function(self.packet, self.group)
520
521 print('')
522
523 def emit_register(self):
524 name = self.register
525 if not self.reg_num == None:
526 print('#define %-33s 0x%04x' %
527 (self.gen_prefix(name + "_num"), self.reg_num))
528
529 self.emit_template_struct(self.register, self.group)
530 self.emit_pack_function(self.register, self.group)
531 self.emit_unpack_function(self.register, self.group)
532
533 def emit_struct(self):
534 name = self.struct
535
536 self.emit_header(name)
537 self.emit_template_struct(self.struct, self.group)
538 self.emit_pack_function(self.struct, self.group)
539 self.emit_unpack_function(self.struct, self.group)
540
541 print('')
542
543 def emit_enum(self):
544 print('enum %s {' % self.gen_prefix(self.enum))
545 for value in self.values:
546 name = value.name
547 if self.prefix:
548 name = self.prefix + "_" + name
549 name = safe_name(name).upper()
550 print(' % -36s = %6d,' % (name, value.value))
551 print('};\n')
552
553 def parse(self, filename):
554 file = open(filename, "rb")
555 self.parser.ParseFile(file)
556 file.close()
557
558 if len(sys.argv) < 2:
559 print("No input xml file specified")
560 sys.exit(1)
561
562 input_file = sys.argv[1]
563
564 p = Parser()
565 p.parse(input_file)