3fdef5c981ee001697048856b69e444d35bb1ff5
[mesa.git] / src / panfrost / lib / gen_pack.py
1 #encoding=utf-8
2
3 # Copyright (C) 2016 Intel Corporation
4 # Copyright (C) 2016 Broadcom
5 # Copyright (C) 2020 Collabora, Ltd.
6 #
7 # Permission is hereby granted, free of charge, to any person obtaining a
8 # copy of this software and associated documentation files (the "Software"),
9 # to deal in the Software without restriction, including without limitation
10 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 # and/or sell copies of the Software, and to permit persons to whom the
12 # Software is furnished to do so, subject to the following conditions:
13 #
14 # The above copyright notice and this permission notice (including the next
15 # paragraph) shall be included in all copies or substantial portions of the
16 # Software.
17 #
18 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24 # IN THE SOFTWARE.
25
26 import xml.parsers.expat
27 import sys
28 import operator
29 from functools import reduce
30
31 global_prefix = "mali"
32
33 pack_header = """
34 /* Generated code, see midgard.xml and gen_pack_header.py
35 *
36 * Packets, enums and structures for Panfrost.
37 *
38 * This file has been generated, do not hand edit.
39 */
40
41 #ifndef PAN_PACK_H
42 #define PAN_PACK_H
43
44 #include <stdio.h>
45 #include <stdint.h>
46 #include <stdbool.h>
47 #include <assert.h>
48 #include <math.h>
49 #include <inttypes.h>
50 #include "util/u_math.h"
51
52 #define __gen_unpack_float(x, y, z) uif(__gen_unpack_uint(x, y, z))
53
54 static inline uint64_t
55 __gen_uint(uint64_t v, uint32_t start, uint32_t end)
56 {
57 #ifndef NDEBUG
58 const int width = end - start + 1;
59 if (width < 64) {
60 const uint64_t max = (1ull << width) - 1;
61 assert(v <= max);
62 }
63 #endif
64
65 return v << start;
66 }
67
68 static inline uint32_t
69 __gen_sint(int32_t v, uint32_t start, uint32_t end)
70 {
71 const int width = end - start + 1;
72
73 #ifndef NDEBUG
74 if (width < 64) {
75 const int64_t max = (1ll << (width - 1)) - 1;
76 const int64_t min = -(1ll << (width - 1));
77 assert(min <= v && v <= max);
78 }
79 #endif
80
81 return ((uint32_t) v) << start;
82 }
83
84 static inline uint32_t
85 __gen_padded(uint32_t v, uint32_t start, uint32_t end)
86 {
87 unsigned shift = __builtin_ctz(v);
88 unsigned odd = v >> (shift + 1);
89
90 #ifndef NDEBUG
91 assert((v >> shift) & 1);
92 assert(shift <= 31);
93 assert(odd <= 7);
94 assert((end - start + 1) == 8);
95 #endif
96
97 return __gen_uint(shift | (odd << 5), start, end);
98 }
99
100
101 static inline uint64_t
102 __gen_unpack_uint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
103 {
104 uint64_t val = 0;
105 const int width = end - start + 1;
106 const uint32_t mask = (width == 32 ? ~0 : (1 << width) - 1 );
107
108 for (int byte = start / 8; byte <= end / 8; byte++) {
109 val |= cl[byte] << ((byte - start / 8) * 8);
110 }
111
112 return (val >> (start % 8)) & mask;
113 }
114
115 static inline uint64_t
116 __gen_unpack_sint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
117 {
118 int size = end - start + 1;
119 int64_t val = __gen_unpack_uint(cl, start, end);
120
121 /* Get the sign bit extended. */
122 return (val << (64 - size)) >> (64 - size);
123 }
124
125 static inline uint64_t
126 __gen_unpack_padded(const uint8_t *restrict cl, uint32_t start, uint32_t end)
127 {
128 unsigned val = __gen_unpack_uint(cl, start, end);
129 unsigned shift = val & 0b11111;
130 unsigned odd = val >> 5;
131
132 return (2*odd + 1) << shift;
133 }
134
135 #define pan_pack(dst, T, name) \
136 for (struct MALI_ ## T name = { MALI_ ## T ## _header }, \
137 *_loop_terminate = (void *) (dst); \
138 __builtin_expect(_loop_terminate != NULL, 1); \
139 ({ MALI_ ## T ## _pack((uint32_t *) (dst), &name); \
140 _loop_terminate = NULL; }))
141
142 """
143
144 def to_alphanum(name):
145 substitutions = {
146 ' ': '_',
147 '/': '_',
148 '[': '',
149 ']': '',
150 '(': '',
151 ')': '',
152 '-': '_',
153 ':': '',
154 '.': '',
155 ',': '',
156 '=': '',
157 '>': '',
158 '#': '',
159 '&': '',
160 '*': '',
161 '"': '',
162 '+': '',
163 '\'': '',
164 }
165
166 for i, j in substitutions.items():
167 name = name.replace(i, j)
168
169 return name
170
171 def safe_name(name):
172 name = to_alphanum(name)
173 if not name[0].isalpha():
174 name = '_' + name
175
176 return name
177
178 def prefixed_upper_name(prefix, name):
179 if prefix:
180 name = prefix + "_" + name
181 return safe_name(name).upper()
182
183 def enum_name(name):
184 return "{}_{}".format(global_prefix, safe_name(name)).lower()
185
186 def num_from_str(num_str):
187 if num_str.lower().startswith('0x'):
188 return int(num_str, base=16)
189 else:
190 assert(not num_str.startswith('0') and 'octals numbers not allowed')
191 return int(num_str)
192
193 MODIFIERS = ["shr", "minus"]
194
195 def parse_modifier(modifier):
196 if modifier is None:
197 return None
198
199 for mod in MODIFIERS:
200 if modifier[0:len(mod)] == mod and modifier[len(mod)] == '(' and modifier[-1] == ')':
201 return [mod, int(modifier[(len(mod) + 1):-1])]
202
203 print("Invalid modifier")
204 assert(False)
205
206 class Field(object):
207 def __init__(self, parser, attrs):
208 self.parser = parser
209 if "name" in attrs:
210 self.name = safe_name(attrs["name"]).lower()
211 self.human_name = attrs["name"]
212
213 if ":" in str(attrs["start"]):
214 (word, bit) = attrs["start"].split(":")
215 self.start = (int(word) * 32) + int(bit)
216 else:
217 self.start = int(attrs["start"])
218
219 self.end = self.start + int(attrs["size"]) - 1
220 self.type = attrs["type"]
221
222 if self.type == 'bool' and self.start != self.end:
223 print("#error Field {} has bool type but more than one bit of size".format(self.name));
224
225 if "prefix" in attrs:
226 self.prefix = safe_name(attrs["prefix"]).upper()
227 else:
228 self.prefix = None
229
230 if "exact" in attrs:
231 self.exact = int(attrs["exact"])
232 else:
233 self.exact = None
234
235 self.default = attrs.get("default")
236
237 # Map enum values
238 if self.type in self.parser.enums and self.default is not None:
239 self.default = safe_name('{}_{}_{}'.format(global_prefix, self.type, self.default)).upper()
240
241 self.modifier = parse_modifier(attrs.get("modifier"))
242
243 def emit_template_struct(self, dim, opaque_structs):
244 if self.type == 'address':
245 type = 'uint64_t'
246 elif self.type == 'bool':
247 type = 'bool'
248 elif self.type == 'float':
249 type = 'float'
250 elif self.type == 'uint' and self.end - self.start > 32:
251 type = 'uint64_t'
252 elif self.type == 'int':
253 type = 'int32_t'
254 elif self.type in ['uint', 'padded']:
255 type = 'uint32_t'
256 elif self.type in self.parser.structs:
257 type = 'struct ' + self.parser.gen_prefix(safe_name(self.type.upper()))
258
259 if opaque_structs:
260 type = type.lower() + '_packed'
261 elif self.type in self.parser.enums:
262 type = 'enum ' + enum_name(self.type)
263 else:
264 print("#error unhandled type: %s" % self.type)
265 type = "uint32_t"
266
267 print(" %-36s %s%s;" % (type, self.name, dim))
268
269 for value in self.values:
270 name = prefixed_upper_name(self.prefix, value.name)
271 print("#define %-40s %d" % (name, value.value))
272
273 def overlaps(self, field):
274 return self != field and max(self.start, field.start) <= min(self.end, field.end)
275
276
277 class Group(object):
278 def __init__(self, parser, parent, start, count):
279 self.parser = parser
280 self.parent = parent
281 self.start = start
282 self.count = count
283 self.size = 0
284 self.length = 0
285 self.fields = []
286
287 def emit_template_struct(self, dim, opaque_structs):
288 if self.count == 0:
289 print(" /* variable length fields follow */")
290 else:
291 if self.count > 1:
292 dim = "%s[%d]" % (dim, self.count)
293
294 for field in self.fields:
295 if field.exact is not None:
296 continue
297
298 field.emit_template_struct(dim, opaque_structs)
299
300 class Word:
301 def __init__(self):
302 self.size = 32
303 self.fields = []
304
305 def collect_words(self, words):
306 for field in self.fields:
307 first_word = field.start // 32
308 last_word = field.end // 32
309
310 for b in range(first_word, last_word + 1):
311 if not b in words:
312 words[b] = self.Word()
313
314 words[b].fields.append(field)
315
316 def emit_pack_function(self, opaque_structs):
317 # Determine number of bytes in this group.
318 calculated = max(field.end // 8 for field in self.fields) + 1
319
320 if self.length > 0:
321 assert(self.length >= calculated)
322 else:
323 self.length = calculated
324
325 words = {}
326 self.collect_words(words)
327
328 emitted_structs = set()
329
330 # Validate the modifier is lossless
331 for field in self.fields:
332 if field.modifier is None:
333 continue
334
335 assert(field.exact is None)
336
337 if field.modifier[0] == "shr":
338 shift = field.modifier[1]
339 mask = hex((1 << shift) - 1)
340 print(" assert((values->{} & {}) == 0);".format(field.name, mask))
341 elif field.modifier[0] == "minus":
342 print(" assert(values->{} >= {});".format(field.name, field.modifier[1]))
343
344 for index in range(self.length // 4):
345 # Handle MBZ words
346 if not index in words:
347 print(" cl[%2d] = 0;" % index)
348 continue
349
350 word = words[index]
351
352 word_start = index * 32
353
354 v = None
355 prefix = " cl[%2d] =" % index
356
357 first = word.fields[0]
358 if first.type in self.parser.structs and first.start not in emitted_structs:
359 pack_name = self.parser.gen_prefix(safe_name(first.type.upper()))
360 start = first.start
361 assert((first.start % 32) == 0)
362 assert(first.end == first.start + (self.parser.structs[first.type].length * 8) - 1)
363 emitted_structs.add(first.start)
364
365 if opaque_structs:
366 print(" memcpy(cl + {}, &values->{}, {});".format(first.start // 32, first.name, (first.end - first.start + 1) // 8))
367 else:
368 print(" {}_pack(cl + {}, &values->{});".format(pack_name, first.start // 32, first.name))
369
370 for field in word.fields:
371 name = field.name
372 start = field.start
373 end = field.end
374 field_word_start = (field.start // 32) * 32
375 start -= field_word_start
376 end -= field_word_start
377
378 value = str(field.exact) if field.exact is not None else "values->%s" % name
379 if field.modifier is not None:
380 if field.modifier[0] == "shr":
381 value = "{} >> {}".format(value, field.modifier[1])
382 elif field.modifier[0] == "minus":
383 value = "{} - {}".format(value, field.modifier[1])
384
385 if field.type == "uint" or field.type == "address":
386 s = "__gen_uint(%s, %d, %d)" % \
387 (value, start, end)
388 elif field.type == "padded":
389 s = "__gen_padded(%s, %d, %d)" % \
390 (value, start, end)
391 elif field.type in self.parser.enums:
392 s = "__gen_uint(%s, %d, %d)" % \
393 (value, start, end)
394 elif field.type == "int":
395 s = "__gen_sint(%s, %d, %d)" % \
396 (value, start, end)
397 elif field.type == "bool":
398 s = "__gen_uint(%s, %d, %d)" % \
399 (value, start, end)
400 elif field.type == "float":
401 assert(start == 0 and end == 31)
402 s = "__gen_uint(fui({}), 0, 32)".format(value)
403 elif field.type in self.parser.structs:
404 # Structs are packed directly
405 assert(len(word.fields) == 1)
406 continue
407 else:
408 s = "#error unhandled field {}, type {}".format(name, field.type)
409
410 if not s == None:
411 shift = word_start - field_word_start
412 if shift:
413 s = "%s >> %d" % (s, shift)
414
415 if field == word.fields[-1]:
416 print("%s %s;" % (prefix, s))
417 else:
418 print("%s %s |" % (prefix, s))
419 prefix = " "
420
421 continue
422
423 # Given a field (start, end) contained in word `index`, generate the 32-bit
424 # mask of present bits relative to the word
425 def mask_for_word(self, index, start, end):
426 field_word_start = index * 32
427 start -= field_word_start
428 end -= field_word_start
429 # Cap multiword at one word
430 start = max(start, 0)
431 end = min(end, 32 - 1)
432 count = (end - start + 1)
433 return (((1 << count) - 1) << start)
434
435 def emit_unpack_function(self):
436 # First, verify there is no garbage in unused bits
437 words = {}
438 self.collect_words(words)
439
440 for index in range(self.length // 4):
441 base = index * 32
442 word = words.get(index, self.Word())
443 masks = [self.mask_for_word(index, f.start, f.end) for f in word.fields]
444 mask = reduce(lambda x,y: x | y, masks, 0)
445
446 ALL_ONES = 0xffffffff
447
448 if mask != ALL_ONES:
449 TMPL = ' if (((const uint32_t *) cl)[{}] & {}) fprintf(stderr, "XXX: Invalid field unpacked at word {}\\n");'
450 print(TMPL.format(index, hex(mask ^ ALL_ONES), index))
451
452 for field in self.fields:
453 # Recurse for structs, see pack() for validation
454 if field.type in self.parser.structs:
455 pack_name = self.parser.gen_prefix(safe_name(field.type)).upper()
456 print(" {}_unpack(cl + {}, &values->{});".format(pack_name, field.start // 8, field.name))
457 continue
458
459 convert = None
460
461 args = []
462 args.append('cl')
463 args.append(str(field.start))
464 args.append(str(field.end))
465
466 if field.type in set(["uint", "address"]) | self.parser.enums:
467 convert = "__gen_unpack_uint"
468 elif field.type == "int":
469 convert = "__gen_unpack_sint"
470 elif field.type == "padded":
471 convert = "__gen_unpack_padded"
472 elif field.type == "bool":
473 convert = "__gen_unpack_uint"
474 elif field.type == "float":
475 convert = "__gen_unpack_float"
476 else:
477 s = "/* unhandled field %s, type %s */\n" % (field.name, field.type)
478
479 suffix = ""
480 if field.modifier:
481 if field.modifier[0] == "minus":
482 suffix = " + {}".format(field.modifier[1])
483 elif field.modifier[0] == "shr":
484 suffix = " << {}".format(field.modifier[1])
485
486 decoded = '{}({}){}'.format(convert, ', '.join(args), suffix)
487
488 print(' values->{} = {};'.format(field.name, decoded))
489
490 def emit_print_function(self):
491 for field in self.fields:
492 convert = None
493 name, val = field.human_name, 'values->{}'.format(field.name)
494
495 if field.type in self.parser.structs:
496 pack_name = self.parser.gen_prefix(safe_name(field.type)).upper()
497 print(' fprintf(fp, "%*s{}:\\n", indent, "");'.format(field.human_name))
498 print(" {}_print(fp, &values->{}, indent + 2);".format(pack_name, field.name))
499 elif field.type == "address":
500 # TODO resolve to name
501 print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
502 elif field.type in self.parser.enums:
503 print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {}_as_str({}));'.format(name, enum_name(field.type), val))
504 elif field.type == "int":
505 print(' fprintf(fp, "%*s{}: %d\\n", indent, "", {});'.format(name, val))
506 elif field.type == "bool":
507 print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {} ? "true" : "false");'.format(name, val))
508 elif field.type == "float":
509 print(' fprintf(fp, "%*s{}: %f\\n", indent, "", {});'.format(name, val))
510 elif field.type == "uint" and (field.end - field.start) >= 32:
511 print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
512 else:
513 print(' fprintf(fp, "%*s{}: %u\\n", indent, "", {});'.format(name, val))
514
515 class Value(object):
516 def __init__(self, attrs):
517 self.name = attrs["name"]
518 self.value = int(attrs["value"])
519
520 class Parser(object):
521 def __init__(self):
522 self.parser = xml.parsers.expat.ParserCreate()
523 self.parser.StartElementHandler = self.start_element
524 self.parser.EndElementHandler = self.end_element
525
526 self.struct = None
527 self.structs = {}
528 # Set of enum names we've seen.
529 self.enums = set()
530
531 def gen_prefix(self, name):
532 return '{}_{}'.format(global_prefix.upper(), name)
533
534 def start_element(self, name, attrs):
535 if name == "panxml":
536 print(pack_header)
537 elif name == "struct":
538 name = attrs["name"]
539 self.with_opaque = attrs.get("with_opaque", False)
540
541 object_name = self.gen_prefix(safe_name(name.upper()))
542 self.struct = object_name
543
544 self.group = Group(self, None, 0, 1)
545 if "size" in attrs:
546 self.group.length = int(attrs["size"]) * 4
547 self.structs[attrs["name"]] = self.group
548 elif name == "field":
549 self.group.fields.append(Field(self, attrs))
550 self.values = []
551 elif name == "enum":
552 self.values = []
553 self.enum = safe_name(attrs["name"])
554 self.enums.add(attrs["name"])
555 if "prefix" in attrs:
556 self.prefix = attrs["prefix"]
557 else:
558 self.prefix= None
559 elif name == "value":
560 self.values.append(Value(attrs))
561
562 def end_element(self, name):
563 if name == "struct":
564 self.emit_struct()
565 self.struct = None
566 self.group = None
567 elif name == "field":
568 self.group.fields[-1].values = self.values
569 elif name == "enum":
570 self.emit_enum()
571 self.enum = None
572 elif name == "panxml":
573 # Include at the end so it can depend on us but not the converse
574 print('#include "panfrost-job.h"')
575 print('#endif')
576
577 def emit_header(self, name):
578 default_fields = []
579 for field in self.group.fields:
580 if not type(field) is Field:
581 continue
582 if field.default is not None:
583 default_fields.append(" .{} = {}".format(field.name, field.default))
584 elif field.type in self.structs:
585 default_fields.append(" .{} = {{ {}_header }}".format(field.name, self.gen_prefix(safe_name(field.type.upper()))))
586
587 print('#define %-40s\\' % (name + '_header'))
588 print(", \\\n".join(default_fields))
589 print('')
590
591 def emit_template_struct(self, name, group, opaque_structs):
592 print("struct %s {" % (name + ('_OPAQUE' if opaque_structs else '')))
593 group.emit_template_struct("", opaque_structs)
594 print("};\n")
595
596 if opaque_structs:
597 # Just so it isn't left undefined
598 print('#define %-40s 0' % (name + '_OPAQUE_header'))
599
600 def emit_pack_function(self, name, group, with_opaque):
601 print("static inline void\n%s_pack(uint32_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
602 (name, ' ' * (len(name) + 6), name))
603
604 group.emit_pack_function(False)
605
606 print("}\n\n")
607
608 if with_opaque:
609 print("static inline void\n%s_OPAQUE_pack(uint32_t * restrict cl,\n%sconst struct %s_OPAQUE * restrict values)\n{" %
610 (name, ' ' * (len(name) + 6), name))
611
612 group.emit_pack_function(True)
613
614 print("}\n")
615
616 # Should be a whole number of words
617 assert((self.group.length % 4) == 0)
618
619 print('#define {} {}'.format (name + "_LENGTH", self.group.length))
620 print('struct {}_packed {{ uint32_t opaque[{}]; }};'.format(name.lower(), self.group.length // 4))
621
622 def emit_unpack_function(self, name, group):
623 print("static inline void")
624 print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
625 (name.upper(), ' ' * (len(name) + 8), name))
626
627 group.emit_unpack_function()
628
629 print("}\n")
630
631 def emit_print_function(self, name, group):
632 print("static inline void")
633 print("{}_print(FILE *fp, const struct {} * values, unsigned indent)\n{{".format(name.upper(), name))
634
635 group.emit_print_function()
636
637 print("}\n")
638
639 def emit_struct(self):
640 name = self.struct
641
642 self.emit_template_struct(self.struct, self.group, False)
643 if self.with_opaque:
644 self.emit_template_struct(self.struct, self.group, True)
645 self.emit_header(name)
646 self.emit_pack_function(self.struct, self.group, self.with_opaque)
647 self.emit_unpack_function(self.struct, self.group)
648 self.emit_print_function(self.struct, self.group)
649
650 def enum_prefix(self, name):
651 return
652
653 def emit_enum(self):
654 e_name = enum_name(self.enum)
655 prefix = e_name if self.enum != 'Format' else global_prefix
656 print('enum {} {{'.format(e_name))
657
658 for value in self.values:
659 name = '{}_{}'.format(prefix, value.name)
660 name = safe_name(name).upper()
661 print(' % -36s = %6d,' % (name, value.value))
662 print('};\n')
663
664 print("static inline const char *")
665 print("{}_as_str(enum {} imm)\n{{".format(e_name.lower(), e_name))
666 print(" switch (imm) {")
667 for value in self.values:
668 name = '{}_{}'.format(prefix, value.name)
669 name = safe_name(name).upper()
670 print(' case {}: return "{}";'.format(name, value.name))
671 print(' default: return "XXX: INVALID";')
672 print(" }")
673 print("}\n")
674
675 def parse(self, filename):
676 file = open(filename, "rb")
677 self.parser.ParseFile(file)
678 file.close()
679
680 if len(sys.argv) < 2:
681 print("No input xml file specified")
682 sys.exit(1)
683
684 input_file = sys.argv[1]
685
686 p = Parser()
687 p.parse(input_file)