• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#encoding=utf-8
2# Copyright © 2017 Intel Corporation
3
4# Permission is hereby granted, free of charge, to any person obtaining a copy
5# of this software and associated documentation files (the "Software"), to deal
6# in the Software without restriction, including without limitation the rights
7# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8# copies of the Software, and to permit persons to whom the Software is
9# furnished to do so, subject to the following conditions:
10
11# The above copyright notice and this permission notice shall be included in
12# all copies or substantial portions of the Software.
13
14# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20# SOFTWARE.
21
22import argparse
23import os
24import xml.parsers.expat
25
26from mako.template import Template
27from util import *
28
29TEMPLATE = Template("""\
30<%!
31from operator import itemgetter
32%>\
33/*
34 * Copyright © 2017 Intel Corporation
35 *
36 * Permission is hereby granted, free of charge, to any person obtaining a
37 * copy of this software and associated documentation files (the "Software"),
38 * to deal in the Software without restriction, including without limitation
39 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
40 * and/or sell copies of the Software, and to permit persons to whom the
41 * Software is furnished to do so, subject to the following conditions:
42 *
43 * The above copyright notice and this permission notice (including the next
44 * paragraph) shall be included in all copies or substantial portions of the
45 * Software.
46 *
47 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
48 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
49 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
50 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
51 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
52 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
53 * IN THE SOFTWARE.
54 */
55
56/* THIS FILE HAS BEEN GENERATED, DO NOT HAND EDIT.
57 *
58 * Sizes of bitfields in genxml instructions, structures, and registers.
59 */
60
61#ifndef ${guard}
62#define ${guard}
63
64#include <stdint.h>
65
66#include "dev/intel_device_info.h"
67#include "util/macros.h"
68
69<%def name="emit_per_gen_prop_func(item, prop, protect_defines)">
70%if item.has_prop(prop):
71% for gen, value in sorted(item.iter_prop(prop), reverse=True):
72%  if protect_defines:
73#ifndef ${gen.prefix(item.token_name)}_${prop}
74#define ${gen.prefix(item.token_name)}_${prop}  ${value}
75#endif
76%  else:
77#define ${gen.prefix(item.token_name)}_${prop}  ${value}
78%  endif
79% endfor
80
81static inline uint32_t ATTRIBUTE_PURE
82${item.token_name}_${prop}(const struct intel_device_info *devinfo)
83{
84   switch (devinfo->verx10) {
85   case 125: return ${item.get_prop(prop, 12.5)};
86   case 120: return ${item.get_prop(prop, 12)};
87   case 110: return ${item.get_prop(prop, 11)};
88   case 90: return ${item.get_prop(prop, 9)};
89   case 80: return ${item.get_prop(prop, 8)};
90   case 75: return ${item.get_prop(prop, 7.5)};
91   case 70: return ${item.get_prop(prop, 7)};
92   case 60: return ${item.get_prop(prop, 6)};
93   case 50: return ${item.get_prop(prop, 5)};
94   case 45: return ${item.get_prop(prop, 4.5)};
95   case 40: return ${item.get_prop(prop, 4)};
96   default:
97      unreachable("Invalid hardware generation");
98   }
99}
100%endif
101</%def>
102
103#ifdef __cplusplus
104extern "C" {
105#endif
106% for _, container in sorted(containers.items(), key=itemgetter(0)):
107%  if container.allowed:
108
109/* ${container.name} */
110
111${emit_per_gen_prop_func(container, 'length', True)}
112
113%   for _, field in sorted(container.fields.items(), key=itemgetter(0)):
114%    if field.allowed:
115
116/* ${container.name}::${field.name} */
117
118${emit_per_gen_prop_func(field, 'bits', False)}
119
120${emit_per_gen_prop_func(field, 'start', False)}
121%    endif
122%   endfor
123%  endif
124% endfor
125
126#ifdef __cplusplus
127}
128#endif
129
130#endif /* ${guard} */""")
131
132class Gen(object):
133
134    def __init__(self, z):
135        # Convert potential "major.minor" string
136        self.tenx = int(float(z) * 10)
137
138    def __lt__(self, other):
139        return self.tenx < other.tenx
140
141    def __hash__(self):
142        return hash(self.tenx)
143
144    def __eq__(self, other):
145        return self.tenx == other.tenx
146
147    def prefix(self, token):
148        gen = self.tenx
149
150        if gen % 10 == 0:
151            gen //= 10
152
153        if token[0] == '_':
154            token = token[1:]
155
156        return 'GFX{}_{}'.format(gen, token)
157
158class Container(object):
159
160    def __init__(self, name):
161        self.name = name
162        self.token_name = safe_name(name)
163        self.length_by_gen = {}
164        self.fields = {}
165        self.allowed = False
166
167    def add_gen(self, gen, xml_attrs):
168        assert isinstance(gen, Gen)
169        if 'length' in xml_attrs:
170            self.length_by_gen[gen] = xml_attrs['length']
171
172    def get_field(self, field_name, create=False):
173        key = to_alphanum(field_name)
174        if key not in self.fields:
175            if create:
176                self.fields[key] = Field(self, field_name)
177            else:
178                return None
179        return self.fields[key]
180
181    def has_prop(self, prop):
182        if prop == 'length':
183            return bool(self.length_by_gen)
184        else:
185            raise ValueError('Invalid property: "{0}"'.format(prop))
186
187    def iter_prop(self, prop):
188        if prop == 'length':
189            return self.length_by_gen.items()
190        else:
191            raise ValueError('Invalid property: "{0}"'.format(prop))
192
193    def get_prop(self, prop, gen):
194        if not isinstance(gen, Gen):
195            gen = Gen(gen)
196
197        if prop == 'length':
198            return self.length_by_gen.get(gen, 0)
199        else:
200            raise ValueError('Invalid property: "{0}"'.format(prop))
201
202class Field(object):
203
204    def __init__(self, container, name):
205        self.name = name
206        self.token_name = safe_name('_'.join([container.name, self.name]))
207        self.bits_by_gen = {}
208        self.start_by_gen = {}
209        self.allowed = False
210
211    def add_gen(self, gen, xml_attrs):
212        assert isinstance(gen, Gen)
213        start = int(xml_attrs['start'])
214        end = int(xml_attrs['end'])
215        self.start_by_gen[gen] = start
216        self.bits_by_gen[gen] = 1 + end - start
217
218    def has_prop(self, prop):
219        return True
220
221    def iter_prop(self, prop):
222        if prop == 'bits':
223            return self.bits_by_gen.items()
224        elif prop == 'start':
225            return self.start_by_gen.items()
226        else:
227            raise ValueError('Invalid property: "{0}"'.format(prop))
228
229    def get_prop(self, prop, gen):
230        if not isinstance(gen, Gen):
231            gen = Gen(gen)
232
233        if prop == 'bits':
234            return self.bits_by_gen.get(gen, 0)
235        elif prop == 'start':
236            return self.start_by_gen.get(gen, 0)
237        else:
238            raise ValueError('Invalid property: "{0}"'.format(prop))
239
240class XmlParser(object):
241
242    def __init__(self, containers):
243        self.parser = xml.parsers.expat.ParserCreate()
244        self.parser.StartElementHandler = self.start_element
245        self.parser.EndElementHandler = self.end_element
246
247        self.gen = None
248        self.containers = containers
249        self.container_stack = []
250        self.container_stack.append(None)
251
252    def parse(self, filename):
253        with open(filename, 'rb') as f:
254            self.parser.ParseFile(f)
255
256    def start_element(self, name, attrs):
257        if name == 'genxml':
258            self.gen = Gen(attrs['gen'])
259        elif name in ('instruction', 'struct', 'register'):
260            if name == 'instruction' and 'engine' in attrs:
261                engines = set(attrs['engine'].split('|'))
262                if not engines & self.engines:
263                    self.container_stack.append(None)
264                    return
265            self.start_container(attrs)
266        elif name == 'group':
267            self.container_stack.append(None)
268        elif name == 'field':
269            self.start_field(attrs)
270        else:
271            pass
272
273    def end_element(self, name):
274        if name == 'genxml':
275            self.gen = None
276        elif name in ('instruction', 'struct', 'register', 'group'):
277            self.container_stack.pop()
278        else:
279            pass
280
281    def start_container(self, attrs):
282        assert self.container_stack[-1] is None
283        name = attrs['name']
284        if name not in self.containers:
285            self.containers[name] = Container(name)
286        self.container_stack.append(self.containers[name])
287        self.container_stack[-1].add_gen(self.gen, attrs)
288
289    def start_field(self, attrs):
290        if self.container_stack[-1] is None:
291            return
292
293        field_name = attrs.get('name', None)
294        if not field_name:
295            return
296
297        self.container_stack[-1].get_field(field_name, True).add_gen(self.gen, attrs)
298
299def parse_args():
300    p = argparse.ArgumentParser()
301    p.add_argument('-o', '--output', type=str,
302                   help="If OUTPUT is unset or '-', then it defaults to '/dev/stdout'")
303    p.add_argument('--cpp-guard', type=str,
304                   help='If unset, then CPP_GUARD is derived from OUTPUT.')
305    p.add_argument('--engines', nargs='?', type=str, default='render',
306                   help="Comma-separated list of engines whose instructions should be parsed (default: %(default)s)")
307    p.add_argument('--include-symbols', type=str, action='store',
308                   help='List of instruction/structures to generate',
309                   required=True)
310    p.add_argument('xml_sources', metavar='XML_SOURCE', nargs='+')
311
312    pargs = p.parse_args()
313
314    if pargs.output in (None, '-'):
315        pargs.output = '/dev/stdout'
316
317    if pargs.cpp_guard is None:
318        pargs.cpp_guard = os.path.basename(pargs.output).upper().replace('.', '_')
319
320    return pargs
321
322def main():
323    pargs = parse_args()
324
325    engines = pargs.engines.split(',')
326    valid_engines = [ 'render', 'blitter', 'video' ]
327    if set(engines) - set(valid_engines):
328        print("Invalid engine specified, valid engines are:\n")
329        for e in valid_engines:
330            print("\t%s" % e)
331        sys.exit(1)
332
333    # Maps name => Container
334    containers = {}
335
336    for source in pargs.xml_sources:
337        p = XmlParser(containers)
338        p.engines = set(engines)
339        p.parse(source)
340
341    included_symbols_list = pargs.include_symbols.split(',')
342    for _name_field in included_symbols_list:
343        name_field = _name_field.split('::')
344        container = containers[name_field[0]]
345        container.allowed = True
346        if len(name_field) > 1:
347            field = container.get_field(name_field[1])
348            assert field
349            field.allowed = True
350
351    with open(pargs.output, 'w') as f:
352        f.write(TEMPLATE.render(containers=containers, guard=pargs.cpp_guard))
353
354if __name__ == '__main__':
355    main()
356