summaryrefslogtreecommitdiffstats
path: root/src/intel/genxml/gen_bits_header.py
blob: 9a89da4048f9805b85185fc8dacd26ab865d0c87 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
#encoding=utf-8
# Copyright © 2017 Intel Corporation

# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

from __future__ import (
    absolute_import, division, print_function, unicode_literals
)

import argparse
import os
import sys
import xml.parsers.expat

from mako.template import Template

TEMPLATE = Template("""\
<%!
from operator import itemgetter
%>\
/*
 * Copyright © 2017 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

/* THIS FILE HAS BEEN GENERATED, DO NOT HAND EDIT.
 *
 * Sizes of bitfields in genxml instructions, structures, and registers.
 */

#ifndef ${guard}
#define ${guard}

#include <stdint.h>

#include "common/gen_device_info.h"
#include "util/macros.h"

#ifdef __cplusplus
extern "C" {
#endif
% for _, container in sorted(containers.iteritems(), key=itemgetter(0)):
% for _, field in sorted(container.fields.iteritems(), key=itemgetter(0)):

/* ${container.name}::${field.name} */
% for gen, bits in sorted(field.bits_by_gen.iteritems(), reverse=True):
#define ${gen.prefix(field.token_name, padded=True)}    ${bits}
% endfor

static inline uint32_t ATTRIBUTE_PURE
${field.token_name}(const struct gen_device_info *devinfo)
{
   switch (devinfo->gen) {
   case 9: return ${field.bits(9)};
   case 8: return ${field.bits(8)};
   case 7:
      if (devinfo->is_haswell) {
         return ${field.bits(7.5)};
      } else {
         return ${field.bits(7)};
      }
   case 6: return ${field.bits(6)};
   case 5: return ${field.bits(5)};
   case 4:
      if (devinfo->is_g4x) {
         return ${field.bits(4.5)};
      } else {
         return ${field.bits(4)};
      }
   default:
      unreachable("Invalid hardware generation");
   }
}

% endfor
% endfor

#ifdef __cplusplus
}
#endif

#endif /* ${guard} */""", output_encoding='utf-8')

def to_alphanum(name):
    substitutions = {
        ' ': '',
        '/': '',
        '[': '',
        ']': '',
        '(': '',
        ')': '',
        '-': '',
        ':': '',
        '.': '',
        ',': '',
        '=': '',
        '>': '',
        '#': '',
        'α': 'alpha',
        '&': '',
        '*': '',
        '"': '',
        '+': '',
        '\'': '',
    }

    for i, j in substitutions.items():
        name = name.replace(i, j)

    return name

def safe_name(name):
    name = to_alphanum(name)
    if not name[0].isalpha():
        name = '_' + name
    return name

class Gen(object):

    def __init__(self, z):
        # Convert potential "major.minor" string
        z = float(z)
        if z < 10:
            z *= 10
        self.tenx = int(z)

    def __lt__(self, other):
        return self.tenx < other.tenx

    def __hash__(self):
        return hash(self.tenx)

    def __eq__(self, other):
        return self.tenx == other.tenx

    def prefix(self, token, padded=False):
        gen = self.tenx
        pad = ''

        if gen % 10 == 0:
            gen //= 10
            if padded:
                pad = ' '

        if token[0] == '_':
            token = token[1:]

        return 'GEN{}_{}{}'.format(gen, token, pad)

class Container(object):

    def __init__(self, name):
        self.name = name
        self.fields = {}

    def get_field(self, field_name, create=False):
        if field_name not in self.fields:
            if create:
                self.fields[field_name] = Field(self, field_name)
            else:
                return None
        return self.fields[field_name]

class Field(object):

    def __init__(self, container, name):
        self.name = name
        self.token_name = safe_name('_'.join([container.name, self.name, 'bits']))
        self.bits_by_gen = {}

    def add_gen(self, gen, xml_attrs):
        assert isinstance(gen, Gen)
        start = int(xml_attrs['start'])
        end = int(xml_attrs['end'])
        self.bits_by_gen[gen] = 1 + end - start

    def bits(self, gen):
        if not isinstance(gen, Gen):
            gen = Gen(gen)
        return self.bits_by_gen.get(gen, 0)

class XmlParser(object):

    def __init__(self, containers):
        self.parser = xml.parsers.expat.ParserCreate()
        self.parser.StartElementHandler = self.start_element
        self.parser.EndElementHandler = self.end_element

        self.gen = None
        self.containers = containers
        self.container = None

    def parse(self, filename):
        with open(filename) as f:
            self.parser.ParseFile(f)

    def start_element(self, name, attrs):
        if name == 'genxml':
            self.gen = Gen(attrs['gen'])
        elif name in ('instruction', 'struct', 'register'):
            self.start_container(attrs)
        elif name == 'field':
            self.start_field(attrs)
        else:
            pass

    def end_element(self, name):
        if name == 'genxml':
            self.gen = None
        elif name in ('instruction', 'struct', 'register'):
            self.container = None
        else:
            pass

    def start_container(self, attrs):
        assert self.container is None
        name = attrs['name']
        if name not in self.containers:
            self.containers[name] = Container(name)
        self.container = self.containers[name]

    def start_field(self, attrs):
        if self.container is None:
            return

        field_name = attrs.get('name', None)
        if not field_name:
            return

        self.container.get_field(field_name, True).add_gen(self.gen, attrs)

def parse_args():
    p = argparse.ArgumentParser()
    p.add_argument('-o', '--output', type=str,
                   help="If OUTPUT is unset or '-', then it defaults to '/dev/stdout'")
    p.add_argument('--cpp-guard', type=str,
                   help='If unset, then CPP_GUARD is derived from OUTPUT.')
    p.add_argument('xml_sources', metavar='XML_SOURCE', nargs='+')

    pargs = p.parse_args()

    if pargs.output in (None, '-'):
        pargs.output = '/dev/stdout'

    if pargs.cpp_guard is None:
        pargs.cpp_guard = os.path.basename(pargs.output).upper().replace('.', '_')

    return pargs

def main():
    pargs = parse_args()

    # Maps name => Container
    containers = {}

    for source in pargs.xml_sources:
        XmlParser(containers).parse(source)

    with open(pargs.output, 'wb') as f:
        f.write(TEMPLATE.render(containers=containers, guard=pargs.cpp_guard))

if __name__ == '__main__':
    main()