• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
26import xml.parsers.expat
27import sys
28import operator
29from functools import reduce
30
31global_prefix = "mali"
32
33pack_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/macros.h"
51#include "util/u_math.h"
52
53#define __gen_unpack_float(x, y, z) uif(__gen_unpack_uint(x, y, z))
54
55static inline uint64_t
56__gen_uint(uint64_t v, uint32_t start, uint32_t end)
57{
58#ifndef NDEBUG
59   const int width = end - start + 1;
60   if (width < 64) {
61      const uint64_t max = (1ull << width) - 1;
62      assert(v <= max);
63   }
64#endif
65
66   return v << start;
67}
68
69static inline uint32_t
70__gen_sint(int32_t v, uint32_t start, uint32_t end)
71{
72#ifndef NDEBUG
73   const int width = end - start + 1;
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) & ((2ll << end) - 1);
82}
83
84static 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
101static 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 uint64_t mask = (width == 64 ? ~0 : (1ull << width) - 1 );
107
108   for (uint32_t byte = start / 8; byte <= end / 8; byte++) {
109      val |= ((uint64_t) cl[byte]) << ((byte - start / 8) * 8);
110   }
111
112   return (val >> (start % 8)) & mask;
113}
114
115static 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   return util_sign_extend(val, size);
122}
123
124static inline uint64_t
125__gen_unpack_padded(const uint8_t *restrict cl, uint32_t start, uint32_t end)
126{
127   unsigned val = __gen_unpack_uint(cl, start, end);
128   unsigned shift = val & 0b11111;
129   unsigned odd = val >> 5;
130
131   return (2*odd + 1) << shift;
132}
133
134#define PREFIX1(A) MALI_ ## A
135#define PREFIX2(A, B) MALI_ ## A ## _ ## B
136#define PREFIX4(A, B, C, D) MALI_ ## A ## _ ## B ## _ ## C ## _ ## D
137
138#define pan_prepare(dst, T)                                 \\
139   *(dst) = (struct PREFIX1(T)){ PREFIX2(T, header) }
140
141#define pan_pack(dst, T, name)                              \\
142   for (struct PREFIX1(T) name = { PREFIX2(T, header) }, \\
143        *_loop_terminate = (void *) (dst);                  \\
144        __builtin_expect(_loop_terminate != NULL, 1);       \\
145        ({ PREFIX2(T, pack)((uint32_t *) (dst), &name);  \\
146           _loop_terminate = NULL; }))
147
148#define pan_unpack(src, T, name)                        \\
149        struct PREFIX1(T) name;                         \\
150        PREFIX2(T, unpack)((uint8_t *)(src), &name)
151
152#define pan_print(fp, T, var, indent)                   \\
153        PREFIX2(T, print)(fp, &(var), indent)
154
155#define pan_size(T) PREFIX2(T, LENGTH)
156#define pan_alignment(T) PREFIX2(T, ALIGN)
157
158#define pan_section_offset(A, S) \\
159        PREFIX4(A, SECTION, S, OFFSET)
160
161#define pan_section_ptr(base, A, S) \\
162        ((void *)((uint8_t *)(base) + pan_section_offset(A, S)))
163
164#define pan_section_pack(dst, A, S, name)                                                         \\
165   for (PREFIX4(A, SECTION, S, TYPE) name = { PREFIX4(A, SECTION, S, header) }, \\
166        *_loop_terminate = (void *) (dst);                                                        \\
167        __builtin_expect(_loop_terminate != NULL, 1);                                             \\
168        ({ PREFIX4(A, SECTION, S, pack) (pan_section_ptr(dst, A, S), &name);              \\
169           _loop_terminate = NULL; }))
170
171#define pan_section_unpack(src, A, S, name)                               \\
172        PREFIX4(A, SECTION, S, TYPE) name;                             \\
173        PREFIX4(A, SECTION, S, unpack)(pan_section_ptr(src, A, S), &name)
174
175#define pan_section_print(fp, A, S, var, indent)                          \\
176        PREFIX4(A, SECTION, S, print)(fp, &(var), indent)
177
178static inline void pan_merge_helper(uint32_t *dst, const uint32_t *src, size_t bytes)
179{
180        assert((bytes & 3) == 0);
181
182        for (unsigned i = 0; i < (bytes / 4); ++i)
183                dst[i] |= src[i];
184}
185
186#define pan_merge(packed1, packed2, type) \
187        pan_merge_helper((packed1).opaque, (packed2).opaque, pan_size(type))
188
189/* From presentations, 16x16 tiles externally. Use shift for fast computation
190 * of tile numbers. */
191
192#define MALI_TILE_SHIFT 4
193#define MALI_TILE_LENGTH (1 << MALI_TILE_SHIFT)
194
195"""
196
197v6_format_printer = """
198
199#define mali_pixel_format_print(fp, format) \\
200    fprintf(fp, "%*sFormat (v6): %s%s%s %s%s%s%s\\n", indent, "", \\
201        mali_format_as_str((enum mali_format)((format >> 12) & 0xFF)), \\
202        (format & (1 << 20)) ? " sRGB" : "", \\
203        (format & (1 << 21)) ? " big-endian" : "", \\
204        mali_channel_as_str((enum mali_channel)((format >> 0) & 0x7)), \\
205        mali_channel_as_str((enum mali_channel)((format >> 3) & 0x7)), \\
206        mali_channel_as_str((enum mali_channel)((format >> 6) & 0x7)), \\
207        mali_channel_as_str((enum mali_channel)((format >> 9) & 0x7)));
208
209"""
210
211v7_format_printer = """
212
213#define mali_pixel_format_print(fp, format) \\
214    fprintf(fp, "%*sFormat (v7): %s%s %s%s\\n", indent, "", \\
215        mali_format_as_str((enum mali_format)((format >> 12) & 0xFF)), \\
216        (format & (1 << 20)) ? " sRGB" : "", \\
217        mali_rgb_component_order_as_str((enum mali_rgb_component_order)(format & ((1 << 12) - 1))), \\
218        (format & (1 << 21)) ? " XXX BAD BIT" : "");
219
220"""
221
222def to_alphanum(name):
223    substitutions = {
224        ' ': '_',
225        '/': '_',
226        '[': '',
227        ']': '',
228        '(': '',
229        ')': '',
230        '-': '_',
231        ':': '',
232        '.': '',
233        ',': '',
234        '=': '',
235        '>': '',
236        '#': '',
237        '&': '',
238        '%': '',
239        '*': '',
240        '"': '',
241        '+': '',
242        '\'': '',
243    }
244
245    for i, j in substitutions.items():
246        name = name.replace(i, j)
247
248    return name
249
250def safe_name(name):
251    name = to_alphanum(name)
252    if not name[0].isalpha():
253        name = '_' + name
254
255    return name
256
257def prefixed_upper_name(prefix, name):
258    if prefix:
259        name = prefix + "_" + name
260    return safe_name(name).upper()
261
262def enum_name(name):
263    return "{}_{}".format(global_prefix, safe_name(name)).lower()
264
265def num_from_str(num_str):
266    if num_str.lower().startswith('0x'):
267        return int(num_str, base=16)
268    else:
269        assert(not num_str.startswith('0') and 'octals numbers not allowed')
270        return int(num_str)
271
272MODIFIERS = ["shr", "minus", "align", "log2"]
273
274def parse_modifier(modifier):
275    if modifier is None:
276        return None
277
278    for mod in MODIFIERS:
279        if modifier[0:len(mod)] == mod:
280            if mod == "log2":
281                assert(len(mod) == len(modifier))
282                return [mod]
283
284            if modifier[len(mod)] == '(' and modifier[-1] == ')':
285                ret = [mod, int(modifier[(len(mod) + 1):-1])]
286                if ret[0] == 'align':
287                    align = ret[1]
288                    # Make sure the alignment is a power of 2
289                    assert(align > 0 and not(align & (align - 1)));
290
291                return ret
292
293    print("Invalid modifier")
294    assert(False)
295
296class Aggregate(object):
297    def __init__(self, parser, name, attrs):
298        self.parser = parser
299        self.sections = []
300        self.name = name
301        self.explicit_size = int(attrs["size"]) if "size" in attrs else 0
302        self.size = 0
303        self.align = int(attrs["align"]) if "align" in attrs else None
304
305    class Section:
306        def __init__(self, name):
307            self.name = name
308
309    def get_size(self):
310        if self.size > 0:
311            return self.size
312
313        size = 0
314        for section in self.sections:
315            size = max(size, section.offset + section.type.get_length())
316
317        if self.explicit_size > 0:
318            assert(self.explicit_size >= size)
319            self.size = self.explicit_size
320        else:
321            self.size = size
322        return self.size
323
324    def add_section(self, type_name, attrs):
325        assert("name" in attrs)
326        section = self.Section(safe_name(attrs["name"]).lower())
327        section.human_name = attrs["name"]
328        section.offset = int(attrs["offset"])
329        assert(section.offset % 4 == 0)
330        section.type = self.parser.structs[attrs["type"]]
331        section.type_name = type_name
332        self.sections.append(section)
333
334class Field(object):
335    def __init__(self, parser, attrs):
336        self.parser = parser
337        if "name" in attrs:
338            self.name = safe_name(attrs["name"]).lower()
339            self.human_name = attrs["name"]
340
341        if ":" in str(attrs["start"]):
342            (word, bit) = attrs["start"].split(":")
343            self.start = (int(word) * 32) + int(bit)
344        else:
345            self.start = int(attrs["start"])
346
347        self.end = self.start + int(attrs["size"]) - 1
348        self.type = attrs["type"]
349
350        if self.type == 'bool' and self.start != self.end:
351            print("#error Field {} has bool type but more than one bit of size".format(self.name));
352
353        if "prefix" in attrs:
354            self.prefix = safe_name(attrs["prefix"]).upper()
355        else:
356            self.prefix = None
357
358        if "exact" in attrs:
359            self.exact = int(attrs["exact"])
360        else:
361            self.exact = None
362
363        self.default = attrs.get("default")
364
365        # Map enum values
366        if self.type in self.parser.enums and self.default is not None:
367            self.default = safe_name('{}_{}_{}'.format(global_prefix, self.type, self.default)).upper()
368
369        self.modifier  = parse_modifier(attrs.get("modifier"))
370
371    def emit_template_struct(self, dim):
372        if self.type == 'address':
373            type = 'uint64_t'
374        elif self.type == 'bool':
375            type = 'bool'
376        elif self.type == 'float':
377            type = 'float'
378        elif self.type in ['uint', 'hex'] and self.end - self.start > 32:
379            type = 'uint64_t'
380        elif self.type == 'int':
381            type = 'int32_t'
382        elif self.type in ['uint', 'hex', 'uint/float', 'padded', 'Pixel Format']:
383            type = 'uint32_t'
384        elif self.type in self.parser.structs:
385            type = 'struct ' + self.parser.gen_prefix(safe_name(self.type.upper()))
386        elif self.type in self.parser.enums:
387            type = 'enum ' + enum_name(self.type)
388        else:
389            print("#error unhandled type: %s" % self.type)
390            type = "uint32_t"
391
392        print("   %-36s %s%s;" % (type, self.name, dim))
393
394        for value in self.values:
395            name = prefixed_upper_name(self.prefix, value.name)
396            print("#define %-40s %d" % (name, value.value))
397
398    def overlaps(self, field):
399        return self != field and max(self.start, field.start) <= min(self.end, field.end)
400
401class Group(object):
402    def __init__(self, parser, parent, start, count, label):
403        self.parser = parser
404        self.parent = parent
405        self.start = start
406        self.count = count
407        self.label = label
408        self.size = 0
409        self.length = 0
410        self.fields = []
411
412    def get_length(self):
413        # Determine number of bytes in this group.
414        calculated = max(field.end // 8 for field in self.fields) + 1 if len(self.fields) > 0 else 0
415        if self.length > 0:
416            assert(self.length >= calculated)
417        else:
418            self.length = calculated
419        return self.length
420
421
422    def emit_template_struct(self, dim):
423        if self.count == 0:
424            print("   /* variable length fields follow */")
425        else:
426            if self.count > 1:
427                dim = "%s[%d]" % (dim, self.count)
428
429            if len(self.fields) == 0:
430                print("   int dummy;")
431
432            for field in self.fields:
433                if field.exact is not None:
434                    continue
435
436                field.emit_template_struct(dim)
437
438    class Word:
439        def __init__(self):
440            self.size = 32
441            self.contributors = []
442
443    class FieldRef:
444        def __init__(self, field, path, start, end):
445            self.field = field
446            self.path = path
447            self.start = start
448            self.end = end
449
450    def collect_fields(self, fields, offset, path, all_fields):
451        for field in fields:
452            field_path = '{}{}'.format(path, field.name)
453            field_offset = offset + field.start
454
455            if field.type in self.parser.structs:
456                sub_struct = self.parser.structs[field.type]
457                self.collect_fields(sub_struct.fields, field_offset, field_path + '.', all_fields)
458                continue
459
460            start = field_offset
461            end = offset + field.end
462            all_fields.append(self.FieldRef(field, field_path, start, end))
463
464    def collect_words(self, fields, offset, path, words):
465        for field in fields:
466            field_path = '{}{}'.format(path, field.name)
467            start = offset + field.start
468
469            if field.type in self.parser.structs:
470                sub_fields = self.parser.structs[field.type].fields
471                self.collect_words(sub_fields, start, field_path + '.', words)
472                continue
473
474            end = offset + field.end
475            contributor = self.FieldRef(field, field_path, start, end)
476            first_word = contributor.start // 32
477            last_word = contributor.end // 32
478            for b in range(first_word, last_word + 1):
479                if not b in words:
480                    words[b] = self.Word()
481                words[b].contributors.append(contributor)
482
483    def emit_pack_function(self):
484        self.get_length()
485
486        words = {}
487        self.collect_words(self.fields, 0, '', words)
488
489        # Validate the modifier is lossless
490        for field in self.fields:
491            if field.modifier is None:
492                continue
493
494            assert(field.exact is None)
495
496            if field.modifier[0] == "shr":
497                shift = field.modifier[1]
498                mask = hex((1 << shift) - 1)
499                print("   assert((values->{} & {}) == 0);".format(field.name, mask))
500            elif field.modifier[0] == "minus":
501                print("   assert(values->{} >= {});".format(field.name, field.modifier[1]))
502            elif field.modifier[0] == "log2":
503                print("   assert(util_is_power_of_two_nonzero(values->{}));".format(field.name))
504
505        for index in range(self.length // 4):
506            # Handle MBZ words
507            if not index in words:
508                print("   cl[%2d] = 0;" % index)
509                continue
510
511            word = words[index]
512
513            word_start = index * 32
514
515            v = None
516            prefix = "   cl[%2d] =" % index
517
518            for contributor in word.contributors:
519                field = contributor.field
520                name = field.name
521                start = contributor.start
522                end = contributor.end
523                contrib_word_start = (start // 32) * 32
524                start -= contrib_word_start
525                end -= contrib_word_start
526
527                value = str(field.exact) if field.exact is not None else "values->{}".format(contributor.path)
528                if field.modifier is not None:
529                    if field.modifier[0] == "shr":
530                        value = "{} >> {}".format(value, field.modifier[1])
531                    elif field.modifier[0] == "minus":
532                        value = "{} - {}".format(value, field.modifier[1])
533                    elif field.modifier[0] == "align":
534                        value = "ALIGN_POT({}, {})".format(value, field.modifier[1])
535                    elif field.modifier[0] == "log2":
536                        value = "util_logbase2({})".format(value)
537
538                if field.type in ["uint", "hex", "uint/float", "address", "Pixel Format"]:
539                    s = "__gen_uint(%s, %d, %d)" % \
540                        (value, start, end)
541                elif field.type == "padded":
542                    s = "__gen_padded(%s, %d, %d)" % \
543                        (value, start, end)
544                elif field.type in self.parser.enums:
545                    s = "__gen_uint(%s, %d, %d)" % \
546                        (value, start, end)
547                elif field.type == "int":
548                    s = "__gen_sint(%s, %d, %d)" % \
549                        (value, start, end)
550                elif field.type == "bool":
551                    s = "__gen_uint(%s, %d, %d)" % \
552                        (value, start, end)
553                elif field.type == "float":
554                    assert(start == 0 and end == 31)
555                    s = "__gen_uint(fui({}), 0, 32)".format(value)
556                else:
557                    s = "#error unhandled field {}, type {}".format(contributor.path, field.type)
558
559                if not s == None:
560                    shift = word_start - contrib_word_start
561                    if shift:
562                        s = "%s >> %d" % (s, shift)
563
564                    if contributor == word.contributors[-1]:
565                        print("%s %s;" % (prefix, s))
566                    else:
567                        print("%s %s |" % (prefix, s))
568                    prefix = "           "
569
570            continue
571
572    # Given a field (start, end) contained in word `index`, generate the 32-bit
573    # mask of present bits relative to the word
574    def mask_for_word(self, index, start, end):
575        field_word_start = index * 32
576        start -= field_word_start
577        end -= field_word_start
578        # Cap multiword at one word
579        start = max(start, 0)
580        end = min(end, 32 - 1)
581        count = (end - start + 1)
582        return (((1 << count) - 1) << start)
583
584    def emit_unpack_function(self):
585        # First, verify there is no garbage in unused bits
586        words = {}
587        self.collect_words(self.fields, 0, '', words)
588
589        for index in range(self.length // 4):
590            base = index * 32
591            word = words.get(index, self.Word())
592            masks = [self.mask_for_word(index, c.start, c.end) for c in word.contributors]
593            mask = reduce(lambda x,y: x | y, masks, 0)
594
595            ALL_ONES = 0xffffffff
596
597            if mask != ALL_ONES:
598                TMPL = '   if (((const uint32_t *) cl)[{}] & {}) fprintf(stderr, "XXX: Invalid field of {} unpacked at word {}\\n");'
599                print(TMPL.format(index, hex(mask ^ ALL_ONES), self.label, index))
600
601        fieldrefs = []
602        self.collect_fields(self.fields, 0, '', fieldrefs)
603        for fieldref in fieldrefs:
604            field = fieldref.field
605            convert = None
606
607            args = []
608            args.append('cl')
609            args.append(str(fieldref.start))
610            args.append(str(fieldref.end))
611
612            if field.type in set(["uint", "hex", "uint/float", "address", "Pixel Format"]):
613                convert = "__gen_unpack_uint"
614            elif field.type in self.parser.enums:
615                convert = "(enum %s)__gen_unpack_uint" % enum_name(field.type)
616            elif field.type == "int":
617                convert = "__gen_unpack_sint"
618            elif field.type == "padded":
619                convert = "__gen_unpack_padded"
620            elif field.type == "bool":
621                convert = "__gen_unpack_uint"
622            elif field.type == "float":
623                convert = "__gen_unpack_float"
624            else:
625                s = "/* unhandled field %s, type %s */\n" % (field.name, field.type)
626
627            suffix = ""
628            prefix = ""
629            if field.modifier:
630                if field.modifier[0] == "minus":
631                    suffix = " + {}".format(field.modifier[1])
632                elif field.modifier[0] == "shr":
633                    suffix = " << {}".format(field.modifier[1])
634                if field.modifier[0] == "log2":
635                    prefix = "1U << "
636
637            decoded = '{}{}({}){}'.format(prefix, convert, ', '.join(args), suffix)
638
639            print('   values->{} = {};'.format(fieldref.path, decoded))
640            if field.modifier and field.modifier[0] == "align":
641                mask = hex(field.modifier[1] - 1)
642                print('   assert(!(values->{} & {}));'.format(fieldref.path, mask))
643
644    def emit_print_function(self):
645        for field in self.fields:
646            convert = None
647            name, val = field.human_name, 'values->{}'.format(field.name)
648
649            if field.type in self.parser.structs:
650                pack_name = self.parser.gen_prefix(safe_name(field.type)).upper()
651                print('   fprintf(fp, "%*s{}:\\n", indent, "");'.format(field.human_name))
652                print("   {}_print(fp, &values->{}, indent + 2);".format(pack_name, field.name))
653            elif field.type == "address":
654                # TODO resolve to name
655                print('   fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
656            elif field.type in self.parser.enums:
657                print('   fprintf(fp, "%*s{}: %s\\n", indent, "", {}_as_str({}));'.format(name, enum_name(field.type), val))
658            elif field.type == "int":
659                print('   fprintf(fp, "%*s{}: %d\\n", indent, "", {});'.format(name, val))
660            elif field.type == "bool":
661                print('   fprintf(fp, "%*s{}: %s\\n", indent, "", {} ? "true" : "false");'.format(name, val))
662            elif field.type == "float":
663                print('   fprintf(fp, "%*s{}: %f\\n", indent, "", {});'.format(name, val))
664            elif field.type in ["uint", "hex"] and (field.end - field.start) >= 32:
665                print('   fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
666            elif field.type == "hex":
667                print('   fprintf(fp, "%*s{}: 0x%x\\n", indent, "", {});'.format(name, val))
668            elif field.type == "uint/float":
669                print('   fprintf(fp, "%*s{}: 0x%X (%f)\\n", indent, "", {}, uif({}));'.format(name, val, val))
670            elif field.type == "Pixel Format":
671                print('   mali_pixel_format_print(fp, {});'.format(val))
672            else:
673                print('   fprintf(fp, "%*s{}: %u\\n", indent, "", {});'.format(name, val))
674
675class Value(object):
676    def __init__(self, attrs):
677        self.name = attrs["name"]
678        self.value = int(attrs["value"], 0)
679
680class Parser(object):
681    def __init__(self):
682        self.parser = xml.parsers.expat.ParserCreate()
683        self.parser.StartElementHandler = self.start_element
684        self.parser.EndElementHandler = self.end_element
685
686        self.struct = None
687        self.structs = {}
688        # Set of enum names we've seen.
689        self.enums = set()
690        self.aggregate = None
691        self.aggregates = {}
692
693    def gen_prefix(self, name):
694        return '{}_{}'.format(global_prefix.upper(), name)
695
696    def start_element(self, name, attrs):
697        if name == "panxml":
698            print(pack_header)
699            if "arch" in attrs:
700                arch = int(attrs["arch"])
701                if arch <= 6:
702                    print(v6_format_printer)
703                else:
704                    print(v7_format_printer)
705        elif name == "struct":
706            name = attrs["name"]
707            self.no_direct_packing = attrs.get("no-direct-packing", False)
708            object_name = self.gen_prefix(safe_name(name.upper()))
709            self.struct = object_name
710
711            self.group = Group(self, None, 0, 1, name)
712            if "size" in attrs:
713                self.group.length = int(attrs["size"]) * 4
714            self.group.align = int(attrs["align"]) if "align" in attrs else None
715            self.structs[attrs["name"]] = self.group
716        elif name == "field":
717            self.group.fields.append(Field(self, attrs))
718            self.values = []
719        elif name == "enum":
720            self.values = []
721            self.enum = safe_name(attrs["name"])
722            self.enums.add(attrs["name"])
723            if "prefix" in attrs:
724                self.prefix = attrs["prefix"]
725            else:
726                self.prefix= None
727        elif name == "value":
728            self.values.append(Value(attrs))
729        elif name == "aggregate":
730            aggregate_name = self.gen_prefix(safe_name(attrs["name"].upper()))
731            self.aggregate = Aggregate(self, aggregate_name, attrs)
732            self.aggregates[attrs['name']] = self.aggregate
733        elif name == "section":
734            type_name = self.gen_prefix(safe_name(attrs["type"].upper()))
735            self.aggregate.add_section(type_name, attrs)
736
737    def end_element(self, name):
738        if name == "struct":
739            self.emit_struct()
740            self.struct = None
741            self.group = None
742        elif name  == "field":
743            self.group.fields[-1].values = self.values
744        elif name  == "enum":
745            self.emit_enum()
746            self.enum = None
747        elif name == "aggregate":
748            self.emit_aggregate()
749            self.aggregate = None
750        elif name == "panxml":
751            # Include at the end so it can depend on us but not the converse
752            print('#include "panfrost-job.h"')
753            print('#endif')
754
755    def emit_header(self, name):
756        default_fields = []
757        for field in self.group.fields:
758            if not type(field) is Field:
759                continue
760            if field.default is not None:
761                default_fields.append("   .{} = {}".format(field.name, field.default))
762            elif field.type in self.structs:
763                default_fields.append("   .{} = {{ {}_header }}".format(field.name, self.gen_prefix(safe_name(field.type.upper()))))
764
765        print('#define %-40s\\' % (name + '_header'))
766        if default_fields:
767            print(",  \\\n".join(default_fields))
768        else:
769            print('   0')
770        print('')
771
772    def emit_template_struct(self, name, group):
773        print("struct %s {" % name)
774        group.emit_template_struct("")
775        print("};\n")
776
777    def emit_aggregate(self):
778        aggregate = self.aggregate
779        print("struct %s_packed {" % aggregate.name.lower())
780        print("   uint32_t opaque[{}];".format(aggregate.get_size() // 4))
781        print("};\n")
782        print('#define {}_LENGTH {}'.format(aggregate.name.upper(), aggregate.size))
783        if aggregate.align != None:
784            print('#define {}_ALIGN {}'.format(aggregate.name.upper(), aggregate.align))
785        for section in aggregate.sections:
786            print('#define {}_SECTION_{}_TYPE struct {}'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
787            print('#define {}_SECTION_{}_header {}_header'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
788            print('#define {}_SECTION_{}_pack {}_pack'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
789            print('#define {}_SECTION_{}_unpack {}_unpack'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
790            print('#define {}_SECTION_{}_print {}_print'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
791            print('#define {}_SECTION_{}_OFFSET {}'.format(aggregate.name.upper(), section.name.upper(), section.offset))
792        print("")
793
794    def emit_pack_function(self, name, group):
795        print("static inline void\n%s_pack(uint32_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
796              (name, ' ' * (len(name) + 6), name))
797
798        group.emit_pack_function()
799
800        print("}\n\n")
801
802        # Should be a whole number of words
803        assert((self.group.length % 4) == 0)
804
805        print('#define {} {}'.format (name + "_LENGTH", self.group.length))
806        if self.group.align != None:
807            print('#define {} {}'.format (name + "_ALIGN", self.group.align))
808        print('struct {}_packed {{ uint32_t opaque[{}]; }};'.format(name.lower(), self.group.length // 4))
809
810    def emit_unpack_function(self, name, group):
811        print("static inline void")
812        print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
813              (name.upper(), ' ' * (len(name) + 8), name))
814
815        group.emit_unpack_function()
816
817        print("}\n")
818
819    def emit_print_function(self, name, group):
820        print("static inline void")
821        print("{}_print(FILE *fp, const struct {} * values, unsigned indent)\n{{".format(name.upper(), name))
822
823        group.emit_print_function()
824
825        print("}\n")
826
827    def emit_struct(self):
828        name = self.struct
829
830        self.emit_template_struct(self.struct, self.group)
831        self.emit_header(name)
832        if self.no_direct_packing == False:
833            self.emit_pack_function(self.struct, self.group)
834            self.emit_unpack_function(self.struct, self.group)
835        self.emit_print_function(self.struct, self.group)
836
837    def enum_prefix(self, name):
838        return
839
840    def emit_enum(self):
841        e_name = enum_name(self.enum)
842        prefix = e_name if self.enum != 'Format' else global_prefix
843        print('enum {} {{'.format(e_name))
844
845        for value in self.values:
846            name = '{}_{}'.format(prefix, value.name)
847            name = safe_name(name).upper()
848            print('        % -36s = %6d,' % (name, value.value))
849        print('};\n')
850
851        print("static inline const char *")
852        print("{}_as_str(enum {} imm)\n{{".format(e_name.lower(), e_name))
853        print("    switch (imm) {")
854        for value in self.values:
855            name = '{}_{}'.format(prefix, value.name)
856            name = safe_name(name).upper()
857            print('    case {}: return "{}";'.format(name, value.name))
858        print('    default: return "XXX: INVALID";')
859        print("    }")
860        print("}\n")
861
862    def parse(self, filename):
863        file = open(filename, "rb")
864        self.parser.ParseFile(file)
865        file.close()
866
867if len(sys.argv) < 2:
868    print("No input xml file specified")
869    sys.exit(1)
870
871input_file = sys.argv[1]
872
873p = Parser()
874p.parse(input_file)
875