17ec681f3Smrg#encoding=utf-8
27ec681f3Smrg
37ec681f3Smrg# Copyright (C) 2016 Intel Corporation
47ec681f3Smrg# Copyright (C) 2016 Broadcom
57ec681f3Smrg# Copyright (C) 2020 Collabora, Ltd.
67ec681f3Smrg#
77ec681f3Smrg# Permission is hereby granted, free of charge, to any person obtaining a
87ec681f3Smrg# copy of this software and associated documentation files (the "Software"),
97ec681f3Smrg# to deal in the Software without restriction, including without limitation
107ec681f3Smrg# the rights to use, copy, modify, merge, publish, distribute, sublicense,
117ec681f3Smrg# and/or sell copies of the Software, and to permit persons to whom the
127ec681f3Smrg# Software is furnished to do so, subject to the following conditions:
137ec681f3Smrg#
147ec681f3Smrg# The above copyright notice and this permission notice (including the next
157ec681f3Smrg# paragraph) shall be included in all copies or substantial portions of the
167ec681f3Smrg# Software.
177ec681f3Smrg#
187ec681f3Smrg# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
197ec681f3Smrg# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
207ec681f3Smrg# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
217ec681f3Smrg# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
227ec681f3Smrg# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
237ec681f3Smrg# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
247ec681f3Smrg# IN THE SOFTWARE.
257ec681f3Smrg
267ec681f3Smrgimport xml.parsers.expat
277ec681f3Smrgimport sys
287ec681f3Smrgimport operator
297ec681f3Smrgfrom functools import reduce
307ec681f3Smrg
317ec681f3Smrgglobal_prefix = "mali"
327ec681f3Smrg
337ec681f3Smrgpack_header = """
347ec681f3Smrg/* Generated code, see midgard.xml and gen_pack_header.py
357ec681f3Smrg *
367ec681f3Smrg * Packets, enums and structures for Panfrost.
377ec681f3Smrg *
387ec681f3Smrg * This file has been generated, do not hand edit.
397ec681f3Smrg */
407ec681f3Smrg
417ec681f3Smrg#ifndef PAN_PACK_H
427ec681f3Smrg#define PAN_PACK_H
437ec681f3Smrg
447ec681f3Smrg#include <stdio.h>
457ec681f3Smrg#include <stdint.h>
467ec681f3Smrg#include <stdbool.h>
477ec681f3Smrg#include <assert.h>
487ec681f3Smrg#include <math.h>
497ec681f3Smrg#include <inttypes.h>
507ec681f3Smrg#include "util/macros.h"
517ec681f3Smrg#include "util/u_math.h"
527ec681f3Smrg
537ec681f3Smrg#define __gen_unpack_float(x, y, z) uif(__gen_unpack_uint(x, y, z))
547ec681f3Smrg
557ec681f3Smrgstatic inline uint64_t
567ec681f3Smrg__gen_uint(uint64_t v, uint32_t start, uint32_t end)
577ec681f3Smrg{
587ec681f3Smrg#ifndef NDEBUG
597ec681f3Smrg   const int width = end - start + 1;
607ec681f3Smrg   if (width < 64) {
617ec681f3Smrg      const uint64_t max = (1ull << width) - 1;
627ec681f3Smrg      assert(v <= max);
637ec681f3Smrg   }
647ec681f3Smrg#endif
657ec681f3Smrg
667ec681f3Smrg   return v << start;
677ec681f3Smrg}
687ec681f3Smrg
697ec681f3Smrgstatic inline uint32_t
707ec681f3Smrg__gen_sint(int32_t v, uint32_t start, uint32_t end)
717ec681f3Smrg{
727ec681f3Smrg#ifndef NDEBUG
737ec681f3Smrg   const int width = end - start + 1;
747ec681f3Smrg   if (width < 64) {
757ec681f3Smrg      const int64_t max = (1ll << (width - 1)) - 1;
767ec681f3Smrg      const int64_t min = -(1ll << (width - 1));
777ec681f3Smrg      assert(min <= v && v <= max);
787ec681f3Smrg   }
797ec681f3Smrg#endif
807ec681f3Smrg
817ec681f3Smrg   return (((uint32_t) v) << start) & ((2ll << end) - 1);
827ec681f3Smrg}
837ec681f3Smrg
847ec681f3Smrgstatic inline uint32_t
857ec681f3Smrg__gen_padded(uint32_t v, uint32_t start, uint32_t end)
867ec681f3Smrg{
877ec681f3Smrg    unsigned shift = __builtin_ctz(v);
887ec681f3Smrg    unsigned odd = v >> (shift + 1);
897ec681f3Smrg
907ec681f3Smrg#ifndef NDEBUG
917ec681f3Smrg    assert((v >> shift) & 1);
927ec681f3Smrg    assert(shift <= 31);
937ec681f3Smrg    assert(odd <= 7);
947ec681f3Smrg    assert((end - start + 1) == 8);
957ec681f3Smrg#endif
967ec681f3Smrg
977ec681f3Smrg    return __gen_uint(shift | (odd << 5), start, end);
987ec681f3Smrg}
997ec681f3Smrg
1007ec681f3Smrg
1017ec681f3Smrgstatic inline uint64_t
1027ec681f3Smrg__gen_unpack_uint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
1037ec681f3Smrg{
1047ec681f3Smrg   uint64_t val = 0;
1057ec681f3Smrg   const int width = end - start + 1;
1067ec681f3Smrg   const uint64_t mask = (width == 64 ? ~0 : (1ull << width) - 1 );
1077ec681f3Smrg
1087ec681f3Smrg   for (uint32_t byte = start / 8; byte <= end / 8; byte++) {
1097ec681f3Smrg      val |= ((uint64_t) cl[byte]) << ((byte - start / 8) * 8);
1107ec681f3Smrg   }
1117ec681f3Smrg
1127ec681f3Smrg   return (val >> (start % 8)) & mask;
1137ec681f3Smrg}
1147ec681f3Smrg
1157ec681f3Smrgstatic inline uint64_t
1167ec681f3Smrg__gen_unpack_sint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
1177ec681f3Smrg{
1187ec681f3Smrg   int size = end - start + 1;
1197ec681f3Smrg   int64_t val = __gen_unpack_uint(cl, start, end);
1207ec681f3Smrg
1217ec681f3Smrg   /* Get the sign bit extended. */
1227ec681f3Smrg   return (val << (64 - size)) >> (64 - size);
1237ec681f3Smrg}
1247ec681f3Smrg
1257ec681f3Smrgstatic inline uint64_t
1267ec681f3Smrg__gen_unpack_padded(const uint8_t *restrict cl, uint32_t start, uint32_t end)
1277ec681f3Smrg{
1287ec681f3Smrg   unsigned val = __gen_unpack_uint(cl, start, end);
1297ec681f3Smrg   unsigned shift = val & 0b11111;
1307ec681f3Smrg   unsigned odd = val >> 5;
1317ec681f3Smrg
1327ec681f3Smrg   return (2*odd + 1) << shift;
1337ec681f3Smrg}
1347ec681f3Smrg
1357ec681f3Smrg#define PREFIX1(A) MALI_ ## A
1367ec681f3Smrg#define PREFIX2(A, B) MALI_ ## A ## _ ## B
1377ec681f3Smrg#define PREFIX4(A, B, C, D) MALI_ ## A ## _ ## B ## _ ## C ## _ ## D
1387ec681f3Smrg
1397ec681f3Smrg#define pan_prepare(dst, T)                                 \\
1407ec681f3Smrg   *(dst) = (struct PREFIX1(T)){ PREFIX2(T, header) }
1417ec681f3Smrg
1427ec681f3Smrg#define pan_pack(dst, T, name)                              \\
1437ec681f3Smrg   for (struct PREFIX1(T) name = { PREFIX2(T, header) }, \\
1447ec681f3Smrg        *_loop_terminate = (void *) (dst);                  \\
1457ec681f3Smrg        __builtin_expect(_loop_terminate != NULL, 1);       \\
1467ec681f3Smrg        ({ PREFIX2(T, pack)((uint32_t *) (dst), &name);  \\
1477ec681f3Smrg           _loop_terminate = NULL; }))
1487ec681f3Smrg
1497ec681f3Smrg#define pan_unpack(src, T, name)                        \\
1507ec681f3Smrg        struct PREFIX1(T) name;                         \\
1517ec681f3Smrg        PREFIX2(T, unpack)((uint8_t *)(src), &name)
1527ec681f3Smrg
1537ec681f3Smrg#define pan_print(fp, T, var, indent)                   \\
1547ec681f3Smrg        PREFIX2(T, print)(fp, &(var), indent)
1557ec681f3Smrg
1567ec681f3Smrg#define pan_size(T) PREFIX2(T, LENGTH)
1577ec681f3Smrg#define pan_alignment(T) PREFIX2(T, ALIGN)
1587ec681f3Smrg
1597ec681f3Smrg#define pan_section_offset(A, S) \\
1607ec681f3Smrg        PREFIX4(A, SECTION, S, OFFSET)
1617ec681f3Smrg
1627ec681f3Smrg#define pan_section_ptr(base, A, S) \\
1637ec681f3Smrg        ((void *)((uint8_t *)(base) + pan_section_offset(A, S)))
1647ec681f3Smrg
1657ec681f3Smrg#define pan_section_pack(dst, A, S, name)                                                         \\
1667ec681f3Smrg   for (PREFIX4(A, SECTION, S, TYPE) name = { PREFIX4(A, SECTION, S, header) }, \\
1677ec681f3Smrg        *_loop_terminate = (void *) (dst);                                                        \\
1687ec681f3Smrg        __builtin_expect(_loop_terminate != NULL, 1);                                             \\
1697ec681f3Smrg        ({ PREFIX4(A, SECTION, S, pack) (pan_section_ptr(dst, A, S), &name);              \\
1707ec681f3Smrg           _loop_terminate = NULL; }))
1717ec681f3Smrg
1727ec681f3Smrg#define pan_section_unpack(src, A, S, name)                               \\
1737ec681f3Smrg        PREFIX4(A, SECTION, S, TYPE) name;                             \\
1747ec681f3Smrg        PREFIX4(A, SECTION, S, unpack)(pan_section_ptr(src, A, S), &name)
1757ec681f3Smrg
1767ec681f3Smrg#define pan_section_print(fp, A, S, var, indent)                          \\
1777ec681f3Smrg        PREFIX4(A, SECTION, S, print)(fp, &(var), indent)
1787ec681f3Smrg
1797ec681f3Smrg#define pan_merge(packed1, packed2, type) \
1807ec681f3Smrg        do { \
1817ec681f3Smrg                for (unsigned i = 0; i < (PREFIX2(type, LENGTH) / 4); ++i) \
1827ec681f3Smrg                        (packed1).opaque[i] |= (packed2).opaque[i]; \
1837ec681f3Smrg        } while(0)
1847ec681f3Smrg
1857ec681f3Smrg/* From presentations, 16x16 tiles externally. Use shift for fast computation
1867ec681f3Smrg * of tile numbers. */
1877ec681f3Smrg
1887ec681f3Smrg#define MALI_TILE_SHIFT 4
1897ec681f3Smrg#define MALI_TILE_LENGTH (1 << MALI_TILE_SHIFT)
1907ec681f3Smrg
1917ec681f3Smrg"""
1927ec681f3Smrg
1937ec681f3Smrgv6_format_printer = """
1947ec681f3Smrg
1957ec681f3Smrg#define mali_pixel_format_print(fp, format) \\
1967ec681f3Smrg    fprintf(fp, "%*sFormat (v6): %s%s%s %s%s%s%s\\n", indent, "", \\
1977ec681f3Smrg        mali_format_as_str((enum mali_format)((format >> 12) & 0xFF)), \\
1987ec681f3Smrg        (format & (1 << 20)) ? " sRGB" : "", \\
1997ec681f3Smrg        (format & (1 << 21)) ? " big-endian" : "", \\
2007ec681f3Smrg        mali_channel_as_str((enum mali_channel)((format >> 0) & 0x7)), \\
2017ec681f3Smrg        mali_channel_as_str((enum mali_channel)((format >> 3) & 0x7)), \\
2027ec681f3Smrg        mali_channel_as_str((enum mali_channel)((format >> 6) & 0x7)), \\
2037ec681f3Smrg        mali_channel_as_str((enum mali_channel)((format >> 9) & 0x7)));
2047ec681f3Smrg
2057ec681f3Smrg"""
2067ec681f3Smrg
2077ec681f3Smrgv7_format_printer = """
2087ec681f3Smrg
2097ec681f3Smrg#define mali_pixel_format_print(fp, format) \\
2107ec681f3Smrg    fprintf(fp, "%*sFormat (v7): %s%s %s%s\\n", indent, "", \\
2117ec681f3Smrg        mali_format_as_str((enum mali_format)((format >> 12) & 0xFF)), \\
2127ec681f3Smrg        (format & (1 << 20)) ? " sRGB" : "", \\
2137ec681f3Smrg        mali_rgb_component_order_as_str((enum mali_rgb_component_order)(format & ((1 << 12) - 1))), \\
2147ec681f3Smrg        (format & (1 << 21)) ? " XXX BAD BIT" : "");
2157ec681f3Smrg
2167ec681f3Smrg"""
2177ec681f3Smrg
2187ec681f3Smrgdef to_alphanum(name):
2197ec681f3Smrg    substitutions = {
2207ec681f3Smrg        ' ': '_',
2217ec681f3Smrg        '/': '_',
2227ec681f3Smrg        '[': '',
2237ec681f3Smrg        ']': '',
2247ec681f3Smrg        '(': '',
2257ec681f3Smrg        ')': '',
2267ec681f3Smrg        '-': '_',
2277ec681f3Smrg        ':': '',
2287ec681f3Smrg        '.': '',
2297ec681f3Smrg        ',': '',
2307ec681f3Smrg        '=': '',
2317ec681f3Smrg        '>': '',
2327ec681f3Smrg        '#': '',
2337ec681f3Smrg        '&': '',
2347ec681f3Smrg        '*': '',
2357ec681f3Smrg        '"': '',
2367ec681f3Smrg        '+': '',
2377ec681f3Smrg        '\'': '',
2387ec681f3Smrg    }
2397ec681f3Smrg
2407ec681f3Smrg    for i, j in substitutions.items():
2417ec681f3Smrg        name = name.replace(i, j)
2427ec681f3Smrg
2437ec681f3Smrg    return name
2447ec681f3Smrg
2457ec681f3Smrgdef safe_name(name):
2467ec681f3Smrg    name = to_alphanum(name)
2477ec681f3Smrg    if not name[0].isalpha():
2487ec681f3Smrg        name = '_' + name
2497ec681f3Smrg
2507ec681f3Smrg    return name
2517ec681f3Smrg
2527ec681f3Smrgdef prefixed_upper_name(prefix, name):
2537ec681f3Smrg    if prefix:
2547ec681f3Smrg        name = prefix + "_" + name
2557ec681f3Smrg    return safe_name(name).upper()
2567ec681f3Smrg
2577ec681f3Smrgdef enum_name(name):
2587ec681f3Smrg    return "{}_{}".format(global_prefix, safe_name(name)).lower()
2597ec681f3Smrg
2607ec681f3Smrgdef num_from_str(num_str):
2617ec681f3Smrg    if num_str.lower().startswith('0x'):
2627ec681f3Smrg        return int(num_str, base=16)
2637ec681f3Smrg    else:
2647ec681f3Smrg        assert(not num_str.startswith('0') and 'octals numbers not allowed')
2657ec681f3Smrg        return int(num_str)
2667ec681f3Smrg
2677ec681f3SmrgMODIFIERS = ["shr", "minus", "align", "log2"]
2687ec681f3Smrg
2697ec681f3Smrgdef parse_modifier(modifier):
2707ec681f3Smrg    if modifier is None:
2717ec681f3Smrg        return None
2727ec681f3Smrg
2737ec681f3Smrg    for mod in MODIFIERS:
2747ec681f3Smrg        if modifier[0:len(mod)] == mod:
2757ec681f3Smrg            if mod == "log2":
2767ec681f3Smrg                assert(len(mod) == len(modifier))
2777ec681f3Smrg                return [mod]
2787ec681f3Smrg
2797ec681f3Smrg            if modifier[len(mod)] == '(' and modifier[-1] == ')':
2807ec681f3Smrg                ret = [mod, int(modifier[(len(mod) + 1):-1])]
2817ec681f3Smrg                if ret[0] == 'align':
2827ec681f3Smrg                    align = ret[1]
2837ec681f3Smrg                    # Make sure the alignment is a power of 2
2847ec681f3Smrg                    assert(align > 0 and not(align & (align - 1)));
2857ec681f3Smrg
2867ec681f3Smrg                return ret
2877ec681f3Smrg
2887ec681f3Smrg    print("Invalid modifier")
2897ec681f3Smrg    assert(False)
2907ec681f3Smrg
2917ec681f3Smrgclass Aggregate(object):
2927ec681f3Smrg    def __init__(self, parser, name, attrs):
2937ec681f3Smrg        self.parser = parser
2947ec681f3Smrg        self.sections = []
2957ec681f3Smrg        self.name = name
2967ec681f3Smrg        self.explicit_size = int(attrs["size"]) if "size" in attrs else 0
2977ec681f3Smrg        self.size = 0
2987ec681f3Smrg        self.align = int(attrs["align"]) if "align" in attrs else None
2997ec681f3Smrg
3007ec681f3Smrg    class Section:
3017ec681f3Smrg        def __init__(self, name):
3027ec681f3Smrg            self.name = name
3037ec681f3Smrg
3047ec681f3Smrg    def get_size(self):
3057ec681f3Smrg        if self.size > 0:
3067ec681f3Smrg            return self.size
3077ec681f3Smrg
3087ec681f3Smrg        size = 0
3097ec681f3Smrg        for section in self.sections:
3107ec681f3Smrg            size = max(size, section.offset + section.type.get_length())
3117ec681f3Smrg
3127ec681f3Smrg        if self.explicit_size > 0:
3137ec681f3Smrg            assert(self.explicit_size >= size)
3147ec681f3Smrg            self.size = self.explicit_size
3157ec681f3Smrg        else:
3167ec681f3Smrg            self.size = size
3177ec681f3Smrg        return self.size
3187ec681f3Smrg
3197ec681f3Smrg    def add_section(self, type_name, attrs):
3207ec681f3Smrg        assert("name" in attrs)
3217ec681f3Smrg        section = self.Section(safe_name(attrs["name"]).lower())
3227ec681f3Smrg        section.human_name = attrs["name"]
3237ec681f3Smrg        section.offset = int(attrs["offset"])
3247ec681f3Smrg        assert(section.offset % 4 == 0)
3257ec681f3Smrg        section.type = self.parser.structs[attrs["type"]]
3267ec681f3Smrg        section.type_name = type_name
3277ec681f3Smrg        self.sections.append(section)
3287ec681f3Smrg
3297ec681f3Smrgclass Field(object):
3307ec681f3Smrg    def __init__(self, parser, attrs):
3317ec681f3Smrg        self.parser = parser
3327ec681f3Smrg        if "name" in attrs:
3337ec681f3Smrg            self.name = safe_name(attrs["name"]).lower()
3347ec681f3Smrg            self.human_name = attrs["name"]
3357ec681f3Smrg
3367ec681f3Smrg        if ":" in str(attrs["start"]):
3377ec681f3Smrg            (word, bit) = attrs["start"].split(":")
3387ec681f3Smrg            self.start = (int(word) * 32) + int(bit)
3397ec681f3Smrg        else:
3407ec681f3Smrg            self.start = int(attrs["start"])
3417ec681f3Smrg
3427ec681f3Smrg        self.end = self.start + int(attrs["size"]) - 1
3437ec681f3Smrg        self.type = attrs["type"]
3447ec681f3Smrg
3457ec681f3Smrg        if self.type == 'bool' and self.start != self.end:
3467ec681f3Smrg            print("#error Field {} has bool type but more than one bit of size".format(self.name));
3477ec681f3Smrg
3487ec681f3Smrg        if "prefix" in attrs:
3497ec681f3Smrg            self.prefix = safe_name(attrs["prefix"]).upper()
3507ec681f3Smrg        else:
3517ec681f3Smrg            self.prefix = None
3527ec681f3Smrg
3537ec681f3Smrg        if "exact" in attrs:
3547ec681f3Smrg            self.exact = int(attrs["exact"])
3557ec681f3Smrg        else:
3567ec681f3Smrg            self.exact = None
3577ec681f3Smrg
3587ec681f3Smrg        self.default = attrs.get("default")
3597ec681f3Smrg
3607ec681f3Smrg        # Map enum values
3617ec681f3Smrg        if self.type in self.parser.enums and self.default is not None:
3627ec681f3Smrg            self.default = safe_name('{}_{}_{}'.format(global_prefix, self.type, self.default)).upper()
3637ec681f3Smrg
3647ec681f3Smrg        self.modifier  = parse_modifier(attrs.get("modifier"))
3657ec681f3Smrg
3667ec681f3Smrg    def emit_template_struct(self, dim):
3677ec681f3Smrg        if self.type == 'address':
3687ec681f3Smrg            type = 'uint64_t'
3697ec681f3Smrg        elif self.type == 'bool':
3707ec681f3Smrg            type = 'bool'
3717ec681f3Smrg        elif self.type == 'float':
3727ec681f3Smrg            type = 'float'
3737ec681f3Smrg        elif self.type == 'uint' and self.end - self.start > 32:
3747ec681f3Smrg            type = 'uint64_t'
3757ec681f3Smrg        elif self.type == 'int':
3767ec681f3Smrg            type = 'int32_t'
3777ec681f3Smrg        elif self.type in ['uint', 'uint/float', 'padded', 'Pixel Format']:
3787ec681f3Smrg            type = 'uint32_t'
3797ec681f3Smrg        elif self.type in self.parser.structs:
3807ec681f3Smrg            type = 'struct ' + self.parser.gen_prefix(safe_name(self.type.upper()))
3817ec681f3Smrg        elif self.type in self.parser.enums:
3827ec681f3Smrg            type = 'enum ' + enum_name(self.type)
3837ec681f3Smrg        else:
3847ec681f3Smrg            print("#error unhandled type: %s" % self.type)
3857ec681f3Smrg            type = "uint32_t"
3867ec681f3Smrg
3877ec681f3Smrg        print("   %-36s %s%s;" % (type, self.name, dim))
3887ec681f3Smrg
3897ec681f3Smrg        for value in self.values:
3907ec681f3Smrg            name = prefixed_upper_name(self.prefix, value.name)
3917ec681f3Smrg            print("#define %-40s %d" % (name, value.value))
3927ec681f3Smrg
3937ec681f3Smrg    def overlaps(self, field):
3947ec681f3Smrg        return self != field and max(self.start, field.start) <= min(self.end, field.end)
3957ec681f3Smrg
3967ec681f3Smrgclass Group(object):
3977ec681f3Smrg    def __init__(self, parser, parent, start, count, label):
3987ec681f3Smrg        self.parser = parser
3997ec681f3Smrg        self.parent = parent
4007ec681f3Smrg        self.start = start
4017ec681f3Smrg        self.count = count
4027ec681f3Smrg        self.label = label
4037ec681f3Smrg        self.size = 0
4047ec681f3Smrg        self.length = 0
4057ec681f3Smrg        self.fields = []
4067ec681f3Smrg
4077ec681f3Smrg    def get_length(self):
4087ec681f3Smrg        # Determine number of bytes in this group.
4097ec681f3Smrg        calculated = max(field.end // 8 for field in self.fields) + 1 if len(self.fields) > 0 else 0
4107ec681f3Smrg        if self.length > 0:
4117ec681f3Smrg            assert(self.length >= calculated)
4127ec681f3Smrg        else:
4137ec681f3Smrg            self.length = calculated
4147ec681f3Smrg        return self.length
4157ec681f3Smrg
4167ec681f3Smrg
4177ec681f3Smrg    def emit_template_struct(self, dim):
4187ec681f3Smrg        if self.count == 0:
4197ec681f3Smrg            print("   /* variable length fields follow */")
4207ec681f3Smrg        else:
4217ec681f3Smrg            if self.count > 1:
4227ec681f3Smrg                dim = "%s[%d]" % (dim, self.count)
4237ec681f3Smrg
4247ec681f3Smrg            if len(self.fields) == 0:
4257ec681f3Smrg                print("   int dummy;")
4267ec681f3Smrg
4277ec681f3Smrg            for field in self.fields:
4287ec681f3Smrg                if field.exact is not None:
4297ec681f3Smrg                    continue
4307ec681f3Smrg
4317ec681f3Smrg                field.emit_template_struct(dim)
4327ec681f3Smrg
4337ec681f3Smrg    class Word:
4347ec681f3Smrg        def __init__(self):
4357ec681f3Smrg            self.size = 32
4367ec681f3Smrg            self.contributors = []
4377ec681f3Smrg
4387ec681f3Smrg    class FieldRef:
4397ec681f3Smrg        def __init__(self, field, path, start, end):
4407ec681f3Smrg            self.field = field
4417ec681f3Smrg            self.path = path
4427ec681f3Smrg            self.start = start
4437ec681f3Smrg            self.end = end
4447ec681f3Smrg
4457ec681f3Smrg    def collect_fields(self, fields, offset, path, all_fields):
4467ec681f3Smrg        for field in fields:
4477ec681f3Smrg            field_path = '{}{}'.format(path, field.name)
4487ec681f3Smrg            field_offset = offset + field.start
4497ec681f3Smrg
4507ec681f3Smrg            if field.type in self.parser.structs:
4517ec681f3Smrg                sub_struct = self.parser.structs[field.type]
4527ec681f3Smrg                self.collect_fields(sub_struct.fields, field_offset, field_path + '.', all_fields)
4537ec681f3Smrg                continue
4547ec681f3Smrg
4557ec681f3Smrg            start = field_offset
4567ec681f3Smrg            end = offset + field.end
4577ec681f3Smrg            all_fields.append(self.FieldRef(field, field_path, start, end))
4587ec681f3Smrg
4597ec681f3Smrg    def collect_words(self, fields, offset, path, words):
4607ec681f3Smrg        for field in fields:
4617ec681f3Smrg            field_path = '{}{}'.format(path, field.name)
4627ec681f3Smrg            start = offset + field.start
4637ec681f3Smrg
4647ec681f3Smrg            if field.type in self.parser.structs:
4657ec681f3Smrg                sub_fields = self.parser.structs[field.type].fields
4667ec681f3Smrg                self.collect_words(sub_fields, start, field_path + '.', words)
4677ec681f3Smrg                continue
4687ec681f3Smrg
4697ec681f3Smrg            end = offset + field.end
4707ec681f3Smrg            contributor = self.FieldRef(field, field_path, start, end)
4717ec681f3Smrg            first_word = contributor.start // 32
4727ec681f3Smrg            last_word = contributor.end // 32
4737ec681f3Smrg            for b in range(first_word, last_word + 1):
4747ec681f3Smrg                if not b in words:
4757ec681f3Smrg                    words[b] = self.Word()
4767ec681f3Smrg                words[b].contributors.append(contributor)
4777ec681f3Smrg
4787ec681f3Smrg    def emit_pack_function(self):
4797ec681f3Smrg        self.get_length()
4807ec681f3Smrg
4817ec681f3Smrg        words = {}
4827ec681f3Smrg        self.collect_words(self.fields, 0, '', words)
4837ec681f3Smrg
4847ec681f3Smrg        # Validate the modifier is lossless
4857ec681f3Smrg        for field in self.fields:
4867ec681f3Smrg            if field.modifier is None:
4877ec681f3Smrg                continue
4887ec681f3Smrg
4897ec681f3Smrg            assert(field.exact is None)
4907ec681f3Smrg
4917ec681f3Smrg            if field.modifier[0] == "shr":
4927ec681f3Smrg                shift = field.modifier[1]
4937ec681f3Smrg                mask = hex((1 << shift) - 1)
4947ec681f3Smrg                print("   assert((values->{} & {}) == 0);".format(field.name, mask))
4957ec681f3Smrg            elif field.modifier[0] == "minus":
4967ec681f3Smrg                print("   assert(values->{} >= {});".format(field.name, field.modifier[1]))
4977ec681f3Smrg            elif field.modifier[0] == "log2":
4987ec681f3Smrg                print("   assert(util_is_power_of_two_nonzero(values->{}));".format(field.name))
4997ec681f3Smrg
5007ec681f3Smrg        for index in range(self.length // 4):
5017ec681f3Smrg            # Handle MBZ words
5027ec681f3Smrg            if not index in words:
5037ec681f3Smrg                print("   cl[%2d] = 0;" % index)
5047ec681f3Smrg                continue
5057ec681f3Smrg
5067ec681f3Smrg            word = words[index]
5077ec681f3Smrg
5087ec681f3Smrg            word_start = index * 32
5097ec681f3Smrg
5107ec681f3Smrg            v = None
5117ec681f3Smrg            prefix = "   cl[%2d] =" % index
5127ec681f3Smrg
5137ec681f3Smrg            for contributor in word.contributors:
5147ec681f3Smrg                field = contributor.field
5157ec681f3Smrg                name = field.name
5167ec681f3Smrg                start = contributor.start
5177ec681f3Smrg                end = contributor.end
5187ec681f3Smrg                contrib_word_start = (start // 32) * 32
5197ec681f3Smrg                start -= contrib_word_start
5207ec681f3Smrg                end -= contrib_word_start
5217ec681f3Smrg
5227ec681f3Smrg                value = str(field.exact) if field.exact is not None else "values->{}".format(contributor.path)
5237ec681f3Smrg                if field.modifier is not None:
5247ec681f3Smrg                    if field.modifier[0] == "shr":
5257ec681f3Smrg                        value = "{} >> {}".format(value, field.modifier[1])
5267ec681f3Smrg                    elif field.modifier[0] == "minus":
5277ec681f3Smrg                        value = "{} - {}".format(value, field.modifier[1])
5287ec681f3Smrg                    elif field.modifier[0] == "align":
5297ec681f3Smrg                        value = "ALIGN_POT({}, {})".format(value, field.modifier[1])
5307ec681f3Smrg                    elif field.modifier[0] == "log2":
5317ec681f3Smrg                        value = "util_logbase2({})".format(value)
5327ec681f3Smrg
5337ec681f3Smrg                if field.type in ["uint", "uint/float", "address", "Pixel Format"]:
5347ec681f3Smrg                    s = "__gen_uint(%s, %d, %d)" % \
5357ec681f3Smrg                        (value, start, end)
5367ec681f3Smrg                elif field.type == "padded":
5377ec681f3Smrg                    s = "__gen_padded(%s, %d, %d)" % \
5387ec681f3Smrg                        (value, start, end)
5397ec681f3Smrg                elif field.type in self.parser.enums:
5407ec681f3Smrg                    s = "__gen_uint(%s, %d, %d)" % \
5417ec681f3Smrg                        (value, start, end)
5427ec681f3Smrg                elif field.type == "int":
5437ec681f3Smrg                    s = "__gen_sint(%s, %d, %d)" % \
5447ec681f3Smrg                        (value, start, end)
5457ec681f3Smrg                elif field.type == "bool":
5467ec681f3Smrg                    s = "__gen_uint(%s, %d, %d)" % \
5477ec681f3Smrg                        (value, start, end)
5487ec681f3Smrg                elif field.type == "float":
5497ec681f3Smrg                    assert(start == 0 and end == 31)
5507ec681f3Smrg                    s = "__gen_uint(fui({}), 0, 32)".format(value)
5517ec681f3Smrg                else:
5527ec681f3Smrg                    s = "#error unhandled field {}, type {}".format(contributor.path, field.type)
5537ec681f3Smrg
5547ec681f3Smrg                if not s == None:
5557ec681f3Smrg                    shift = word_start - contrib_word_start
5567ec681f3Smrg                    if shift:
5577ec681f3Smrg                        s = "%s >> %d" % (s, shift)
5587ec681f3Smrg
5597ec681f3Smrg                    if contributor == word.contributors[-1]:
5607ec681f3Smrg                        print("%s %s;" % (prefix, s))
5617ec681f3Smrg                    else:
5627ec681f3Smrg                        print("%s %s |" % (prefix, s))
5637ec681f3Smrg                    prefix = "           "
5647ec681f3Smrg
5657ec681f3Smrg            continue
5667ec681f3Smrg
5677ec681f3Smrg    # Given a field (start, end) contained in word `index`, generate the 32-bit
5687ec681f3Smrg    # mask of present bits relative to the word
5697ec681f3Smrg    def mask_for_word(self, index, start, end):
5707ec681f3Smrg        field_word_start = index * 32
5717ec681f3Smrg        start -= field_word_start
5727ec681f3Smrg        end -= field_word_start
5737ec681f3Smrg        # Cap multiword at one word
5747ec681f3Smrg        start = max(start, 0)
5757ec681f3Smrg        end = min(end, 32 - 1)
5767ec681f3Smrg        count = (end - start + 1)
5777ec681f3Smrg        return (((1 << count) - 1) << start)
5787ec681f3Smrg
5797ec681f3Smrg    def emit_unpack_function(self):
5807ec681f3Smrg        # First, verify there is no garbage in unused bits
5817ec681f3Smrg        words = {}
5827ec681f3Smrg        self.collect_words(self.fields, 0, '', words)
5837ec681f3Smrg
5847ec681f3Smrg        for index in range(self.length // 4):
5857ec681f3Smrg            base = index * 32
5867ec681f3Smrg            word = words.get(index, self.Word())
5877ec681f3Smrg            masks = [self.mask_for_word(index, c.start, c.end) for c in word.contributors]
5887ec681f3Smrg            mask = reduce(lambda x,y: x | y, masks, 0)
5897ec681f3Smrg
5907ec681f3Smrg            ALL_ONES = 0xffffffff
5917ec681f3Smrg
5927ec681f3Smrg            if mask != ALL_ONES:
5937ec681f3Smrg                TMPL = '   if (((const uint32_t *) cl)[{}] & {}) fprintf(stderr, "XXX: Invalid field of {} unpacked at word {}\\n");'
5947ec681f3Smrg                print(TMPL.format(index, hex(mask ^ ALL_ONES), self.label, index))
5957ec681f3Smrg
5967ec681f3Smrg        fieldrefs = []
5977ec681f3Smrg        self.collect_fields(self.fields, 0, '', fieldrefs)
5987ec681f3Smrg        for fieldref in fieldrefs:
5997ec681f3Smrg            field = fieldref.field
6007ec681f3Smrg            convert = None
6017ec681f3Smrg
6027ec681f3Smrg            args = []
6037ec681f3Smrg            args.append('cl')
6047ec681f3Smrg            args.append(str(fieldref.start))
6057ec681f3Smrg            args.append(str(fieldref.end))
6067ec681f3Smrg
6077ec681f3Smrg            if field.type in set(["uint", "uint/float", "address", "Pixel Format"]):
6087ec681f3Smrg                convert = "__gen_unpack_uint"
6097ec681f3Smrg            elif field.type in self.parser.enums:
6107ec681f3Smrg                convert = "(enum %s)__gen_unpack_uint" % enum_name(field.type)
6117ec681f3Smrg            elif field.type == "int":
6127ec681f3Smrg                convert = "__gen_unpack_sint"
6137ec681f3Smrg            elif field.type == "padded":
6147ec681f3Smrg                convert = "__gen_unpack_padded"
6157ec681f3Smrg            elif field.type == "bool":
6167ec681f3Smrg                convert = "__gen_unpack_uint"
6177ec681f3Smrg            elif field.type == "float":
6187ec681f3Smrg                convert = "__gen_unpack_float"
6197ec681f3Smrg            else:
6207ec681f3Smrg                s = "/* unhandled field %s, type %s */\n" % (field.name, field.type)
6217ec681f3Smrg
6227ec681f3Smrg            suffix = ""
6237ec681f3Smrg            prefix = ""
6247ec681f3Smrg            if field.modifier:
6257ec681f3Smrg                if field.modifier[0] == "minus":
6267ec681f3Smrg                    suffix = " + {}".format(field.modifier[1])
6277ec681f3Smrg                elif field.modifier[0] == "shr":
6287ec681f3Smrg                    suffix = " << {}".format(field.modifier[1])
6297ec681f3Smrg                if field.modifier[0] == "log2":
6307ec681f3Smrg                    prefix = "1U << "
6317ec681f3Smrg
6327ec681f3Smrg            decoded = '{}{}({}){}'.format(prefix, convert, ', '.join(args), suffix)
6337ec681f3Smrg
6347ec681f3Smrg            print('   values->{} = {};'.format(fieldref.path, decoded))
6357ec681f3Smrg            if field.modifier and field.modifier[0] == "align":
6367ec681f3Smrg                mask = hex(field.modifier[1] - 1)
6377ec681f3Smrg                print('   assert(!(values->{} & {}));'.format(fieldref.path, mask))
6387ec681f3Smrg
6397ec681f3Smrg    def emit_print_function(self):
6407ec681f3Smrg        for field in self.fields:
6417ec681f3Smrg            convert = None
6427ec681f3Smrg            name, val = field.human_name, 'values->{}'.format(field.name)
6437ec681f3Smrg
6447ec681f3Smrg            if field.type in self.parser.structs:
6457ec681f3Smrg                pack_name = self.parser.gen_prefix(safe_name(field.type)).upper()
6467ec681f3Smrg                print('   fprintf(fp, "%*s{}:\\n", indent, "");'.format(field.human_name))
6477ec681f3Smrg                print("   {}_print(fp, &values->{}, indent + 2);".format(pack_name, field.name))
6487ec681f3Smrg            elif field.type == "address":
6497ec681f3Smrg                # TODO resolve to name
6507ec681f3Smrg                print('   fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
6517ec681f3Smrg            elif field.type in self.parser.enums:
6527ec681f3Smrg                print('   fprintf(fp, "%*s{}: %s\\n", indent, "", {}_as_str({}));'.format(name, enum_name(field.type), val))
6537ec681f3Smrg            elif field.type == "int":
6547ec681f3Smrg                print('   fprintf(fp, "%*s{}: %d\\n", indent, "", {});'.format(name, val))
6557ec681f3Smrg            elif field.type == "bool":
6567ec681f3Smrg                print('   fprintf(fp, "%*s{}: %s\\n", indent, "", {} ? "true" : "false");'.format(name, val))
6577ec681f3Smrg            elif field.type == "float":
6587ec681f3Smrg                print('   fprintf(fp, "%*s{}: %f\\n", indent, "", {});'.format(name, val))
6597ec681f3Smrg            elif field.type == "uint" and (field.end - field.start) >= 32:
6607ec681f3Smrg                print('   fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
6617ec681f3Smrg            elif field.type == "uint/float":
6627ec681f3Smrg                print('   fprintf(fp, "%*s{}: 0x%X (%f)\\n", indent, "", {}, uif({}));'.format(name, val, val))
6637ec681f3Smrg            elif field.type == "Pixel Format":
6647ec681f3Smrg                print('   mali_pixel_format_print(fp, {});'.format(val))
6657ec681f3Smrg            else:
6667ec681f3Smrg                print('   fprintf(fp, "%*s{}: %u\\n", indent, "", {});'.format(name, val))
6677ec681f3Smrg
6687ec681f3Smrgclass Value(object):
6697ec681f3Smrg    def __init__(self, attrs):
6707ec681f3Smrg        self.name = attrs["name"]
6717ec681f3Smrg        self.value = int(attrs["value"], 0)
6727ec681f3Smrg
6737ec681f3Smrgclass Parser(object):
6747ec681f3Smrg    def __init__(self):
6757ec681f3Smrg        self.parser = xml.parsers.expat.ParserCreate()
6767ec681f3Smrg        self.parser.StartElementHandler = self.start_element
6777ec681f3Smrg        self.parser.EndElementHandler = self.end_element
6787ec681f3Smrg
6797ec681f3Smrg        self.struct = None
6807ec681f3Smrg        self.structs = {}
6817ec681f3Smrg        # Set of enum names we've seen.
6827ec681f3Smrg        self.enums = set()
6837ec681f3Smrg        self.aggregate = None
6847ec681f3Smrg        self.aggregates = {}
6857ec681f3Smrg
6867ec681f3Smrg    def gen_prefix(self, name):
6877ec681f3Smrg        return '{}_{}'.format(global_prefix.upper(), name)
6887ec681f3Smrg
6897ec681f3Smrg    def start_element(self, name, attrs):
6907ec681f3Smrg        if name == "panxml":
6917ec681f3Smrg            print(pack_header)
6927ec681f3Smrg            if "arch" in attrs:
6937ec681f3Smrg                arch = int(attrs["arch"])
6947ec681f3Smrg                if arch <= 6:
6957ec681f3Smrg                    print(v6_format_printer)
6967ec681f3Smrg                else:
6977ec681f3Smrg                    print(v7_format_printer)
6987ec681f3Smrg        elif name == "struct":
6997ec681f3Smrg            name = attrs["name"]
7007ec681f3Smrg            self.no_direct_packing = attrs.get("no-direct-packing", False)
7017ec681f3Smrg            object_name = self.gen_prefix(safe_name(name.upper()))
7027ec681f3Smrg            self.struct = object_name
7037ec681f3Smrg
7047ec681f3Smrg            self.group = Group(self, None, 0, 1, name)
7057ec681f3Smrg            if "size" in attrs:
7067ec681f3Smrg                self.group.length = int(attrs["size"]) * 4
7077ec681f3Smrg            self.group.align = int(attrs["align"]) if "align" in attrs else None
7087ec681f3Smrg            self.structs[attrs["name"]] = self.group
7097ec681f3Smrg        elif name == "field":
7107ec681f3Smrg            self.group.fields.append(Field(self, attrs))
7117ec681f3Smrg            self.values = []
7127ec681f3Smrg        elif name == "enum":
7137ec681f3Smrg            self.values = []
7147ec681f3Smrg            self.enum = safe_name(attrs["name"])
7157ec681f3Smrg            self.enums.add(attrs["name"])
7167ec681f3Smrg            if "prefix" in attrs:
7177ec681f3Smrg                self.prefix = attrs["prefix"]
7187ec681f3Smrg            else:
7197ec681f3Smrg                self.prefix= None
7207ec681f3Smrg        elif name == "value":
7217ec681f3Smrg            self.values.append(Value(attrs))
7227ec681f3Smrg        elif name == "aggregate":
7237ec681f3Smrg            aggregate_name = self.gen_prefix(safe_name(attrs["name"].upper()))
7247ec681f3Smrg            self.aggregate = Aggregate(self, aggregate_name, attrs)
7257ec681f3Smrg            self.aggregates[attrs['name']] = self.aggregate
7267ec681f3Smrg        elif name == "section":
7277ec681f3Smrg            type_name = self.gen_prefix(safe_name(attrs["type"].upper()))
7287ec681f3Smrg            self.aggregate.add_section(type_name, attrs)
7297ec681f3Smrg
7307ec681f3Smrg    def end_element(self, name):
7317ec681f3Smrg        if name == "struct":
7327ec681f3Smrg            self.emit_struct()
7337ec681f3Smrg            self.struct = None
7347ec681f3Smrg            self.group = None
7357ec681f3Smrg        elif name  == "field":
7367ec681f3Smrg            self.group.fields[-1].values = self.values
7377ec681f3Smrg        elif name  == "enum":
7387ec681f3Smrg            self.emit_enum()
7397ec681f3Smrg            self.enum = None
7407ec681f3Smrg        elif name == "aggregate":
7417ec681f3Smrg            self.emit_aggregate()
7427ec681f3Smrg            self.aggregate = None
7437ec681f3Smrg        elif name == "panxml":
7447ec681f3Smrg            # Include at the end so it can depend on us but not the converse
7457ec681f3Smrg            print('#include "panfrost-job.h"')
7467ec681f3Smrg            print('#endif')
7477ec681f3Smrg
7487ec681f3Smrg    def emit_header(self, name):
7497ec681f3Smrg        default_fields = []
7507ec681f3Smrg        for field in self.group.fields:
7517ec681f3Smrg            if not type(field) is Field:
7527ec681f3Smrg                continue
7537ec681f3Smrg            if field.default is not None:
7547ec681f3Smrg                default_fields.append("   .{} = {}".format(field.name, field.default))
7557ec681f3Smrg            elif field.type in self.structs:
7567ec681f3Smrg                default_fields.append("   .{} = {{ {}_header }}".format(field.name, self.gen_prefix(safe_name(field.type.upper()))))
7577ec681f3Smrg
7587ec681f3Smrg        print('#define %-40s\\' % (name + '_header'))
7597ec681f3Smrg        if default_fields:
7607ec681f3Smrg            print(",  \\\n".join(default_fields))
7617ec681f3Smrg        else:
7627ec681f3Smrg            print('   0')
7637ec681f3Smrg        print('')
7647ec681f3Smrg
7657ec681f3Smrg    def emit_template_struct(self, name, group):
7667ec681f3Smrg        print("struct %s {" % name)
7677ec681f3Smrg        group.emit_template_struct("")
7687ec681f3Smrg        print("};\n")
7697ec681f3Smrg
7707ec681f3Smrg    def emit_aggregate(self):
7717ec681f3Smrg        aggregate = self.aggregate
7727ec681f3Smrg        print("struct %s_packed {" % aggregate.name.lower())
7737ec681f3Smrg        print("   uint32_t opaque[{}];".format(aggregate.get_size() // 4))
7747ec681f3Smrg        print("};\n")
7757ec681f3Smrg        print('#define {}_LENGTH {}'.format(aggregate.name.upper(), aggregate.size))
7767ec681f3Smrg        if aggregate.align != None:
7777ec681f3Smrg            print('#define {}_ALIGN {}'.format(aggregate.name.upper(), aggregate.align))
7787ec681f3Smrg        for section in aggregate.sections:
7797ec681f3Smrg            print('#define {}_SECTION_{}_TYPE struct {}'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
7807ec681f3Smrg            print('#define {}_SECTION_{}_header {}_header'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
7817ec681f3Smrg            print('#define {}_SECTION_{}_pack {}_pack'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
7827ec681f3Smrg            print('#define {}_SECTION_{}_unpack {}_unpack'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
7837ec681f3Smrg            print('#define {}_SECTION_{}_print {}_print'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
7847ec681f3Smrg            print('#define {}_SECTION_{}_OFFSET {}'.format(aggregate.name.upper(), section.name.upper(), section.offset))
7857ec681f3Smrg        print("")
7867ec681f3Smrg
7877ec681f3Smrg    def emit_pack_function(self, name, group):
7887ec681f3Smrg        print("static inline void\n%s_pack(uint32_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
7897ec681f3Smrg              (name, ' ' * (len(name) + 6), name))
7907ec681f3Smrg
7917ec681f3Smrg        group.emit_pack_function()
7927ec681f3Smrg
7937ec681f3Smrg        print("}\n\n")
7947ec681f3Smrg
7957ec681f3Smrg        # Should be a whole number of words
7967ec681f3Smrg        assert((self.group.length % 4) == 0)
7977ec681f3Smrg
7987ec681f3Smrg        print('#define {} {}'.format (name + "_LENGTH", self.group.length))
7997ec681f3Smrg        if self.group.align != None:
8007ec681f3Smrg            print('#define {} {}'.format (name + "_ALIGN", self.group.align))
8017ec681f3Smrg        print('struct {}_packed {{ uint32_t opaque[{}]; }};'.format(name.lower(), self.group.length // 4))
8027ec681f3Smrg
8037ec681f3Smrg    def emit_unpack_function(self, name, group):
8047ec681f3Smrg        print("static inline void")
8057ec681f3Smrg        print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
8067ec681f3Smrg              (name.upper(), ' ' * (len(name) + 8), name))
8077ec681f3Smrg
8087ec681f3Smrg        group.emit_unpack_function()
8097ec681f3Smrg
8107ec681f3Smrg        print("}\n")
8117ec681f3Smrg
8127ec681f3Smrg    def emit_print_function(self, name, group):
8137ec681f3Smrg        print("static inline void")
8147ec681f3Smrg        print("{}_print(FILE *fp, const struct {} * values, unsigned indent)\n{{".format(name.upper(), name))
8157ec681f3Smrg
8167ec681f3Smrg        group.emit_print_function()
8177ec681f3Smrg
8187ec681f3Smrg        print("}\n")
8197ec681f3Smrg
8207ec681f3Smrg    def emit_struct(self):
8217ec681f3Smrg        name = self.struct
8227ec681f3Smrg
8237ec681f3Smrg        self.emit_template_struct(self.struct, self.group)
8247ec681f3Smrg        self.emit_header(name)
8257ec681f3Smrg        if self.no_direct_packing == False:
8267ec681f3Smrg            self.emit_pack_function(self.struct, self.group)
8277ec681f3Smrg            self.emit_unpack_function(self.struct, self.group)
8287ec681f3Smrg        self.emit_print_function(self.struct, self.group)
8297ec681f3Smrg
8307ec681f3Smrg    def enum_prefix(self, name):
8317ec681f3Smrg        return
8327ec681f3Smrg
8337ec681f3Smrg    def emit_enum(self):
8347ec681f3Smrg        e_name = enum_name(self.enum)
8357ec681f3Smrg        prefix = e_name if self.enum != 'Format' else global_prefix
8367ec681f3Smrg        print('enum {} {{'.format(e_name))
8377ec681f3Smrg
8387ec681f3Smrg        for value in self.values:
8397ec681f3Smrg            name = '{}_{}'.format(prefix, value.name)
8407ec681f3Smrg            name = safe_name(name).upper()
8417ec681f3Smrg            print('        % -36s = %6d,' % (name, value.value))
8427ec681f3Smrg        print('};\n')
8437ec681f3Smrg
8447ec681f3Smrg        print("static inline const char *")
8457ec681f3Smrg        print("{}_as_str(enum {} imm)\n{{".format(e_name.lower(), e_name))
8467ec681f3Smrg        print("    switch (imm) {")
8477ec681f3Smrg        for value in self.values:
8487ec681f3Smrg            name = '{}_{}'.format(prefix, value.name)
8497ec681f3Smrg            name = safe_name(name).upper()
8507ec681f3Smrg            print('    case {}: return "{}";'.format(name, value.name))
8517ec681f3Smrg        print('    default: return "XXX: INVALID";')
8527ec681f3Smrg        print("    }")
8537ec681f3Smrg        print("}\n")
8547ec681f3Smrg
8557ec681f3Smrg    def parse(self, filename):
8567ec681f3Smrg        file = open(filename, "rb")
8577ec681f3Smrg        self.parser.ParseFile(file)
8587ec681f3Smrg        file.close()
8597ec681f3Smrg
8607ec681f3Smrgif len(sys.argv) < 2:
8617ec681f3Smrg    print("No input xml file specified")
8627ec681f3Smrg    sys.exit(1)
8637ec681f3Smrg
8647ec681f3Smrginput_file = sys.argv[1]
8657ec681f3Smrg
8667ec681f3Smrgp = Parser()
8677ec681f3Smrgp.parse(input_file)
868