intel/perf: export performance counters sorted by [group|set] and name
[mesa.git] / src / intel / isl / gen_format_layout.py
1 # encoding=utf-8
2 # Copyright © 2016 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
22 """Generates isl_format_layout.c."""
23
24 from __future__ import absolute_import, division, print_function
25 import argparse
26 import csv
27 import re
28
29 from mako import template
30
31 # Load the template, ensure that __future__.division is imported, and set the
32 # bytes encoding to be utf-8. This last bit is important to getting simple
33 # consistent behavior for python 3 when we get there.
34 TEMPLATE = template.Template(future_imports=['division'],
35 output_encoding='utf-8',
36 text="""\
37 /* This file is autogenerated by gen_format_layout.py. DO NOT EDIT! */
38
39 /*
40 * Copyright 2015 Intel Corporation
41 *
42 * Permission is hereby granted, free of charge, to any person obtaining a
43 * copy of this software and associated documentation files (the "Software"),
44 * to deal in the Software without restriction, including without limitation
45 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
46 * and/or sell copies of the Software, and to permit persons to whom the
47 * Software is furnished to do so, subject to the following conditions:
48 *
49 * The above copyright notice and this permission notice (including the next
50 * paragraph) shall be included in all copies or substantial portions of the
51 * Software.
52 *
53 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
54 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
55 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
56 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
57 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
58 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
59 * IN THE SOFTWARE.
60 */
61
62 #include "isl/isl.h"
63
64 const struct isl_format_layout
65 isl_format_layouts[] = {
66 % for format in formats:
67 [ISL_FORMAT_${format.name}] = {
68 .format = ISL_FORMAT_${format.name},
69 .name = "ISL_FORMAT_${format.name}",
70 .bpb = ${format.bpb},
71 .bw = ${format.bw},
72 .bh = ${format.bh},
73 .bd = ${format.bd},
74 .channels = {
75 % for mask in ['r', 'g', 'b', 'a', 'l', 'i', 'p']:
76 <% channel = getattr(format, mask, None) %>\\
77 % if channel.type is not None:
78 .${mask} = { ISL_${channel.type}, ${channel.start}, ${channel.size} },
79 % else:
80 .${mask} = {},
81 % endif
82 % endfor
83 },
84 .colorspace = ISL_COLORSPACE_${format.colorspace},
85 .txc = ISL_TXC_${format.txc},
86 },
87
88 % endfor
89 };
90
91 bool
92 isl_format_is_valid(enum isl_format format)
93 {
94 if (format >= sizeof(isl_format_layouts) / sizeof(isl_format_layouts[0]))
95 return false;
96 return isl_format_layouts[format].name;
97 }
98
99 enum isl_format
100 isl_format_srgb_to_linear(enum isl_format format)
101 {
102 switch (format) {
103 % for srgb, rgb in srgb_to_linear_map:
104 case ISL_FORMAT_${srgb}:
105 return ISL_FORMAT_${rgb};
106 %endfor
107 default:
108 return format;
109 }
110 }
111 """)
112
113
114 class Channel(object):
115 """Class representing a Channel.
116
117 Converts the csv encoded data into the format that the template (and thus
118 the consuming C code) expects.
119
120 """
121 # If the csv file grew very large this class could be put behind a factory
122 # to increase efficiency. Right now though it's fast enough that It didn't
123 # seem worthwhile to add all of the boilerplate
124 _types = {
125 'x': 'void',
126 'r': 'raw',
127 'un': 'unorm',
128 'sn': 'snorm',
129 'uf': 'ufloat',
130 'sf': 'sfloat',
131 'ux': 'ufixed',
132 'sx': 'sfixed',
133 'ui': 'uint',
134 'si': 'sint',
135 'us': 'uscaled',
136 'ss': 'sscaled',
137 }
138 _splitter = re.compile(r'\s*(?P<type>[a-z]+)(?P<size>[0-9]+)')
139
140 def __init__(self, line):
141 # If the line is just whitespace then just set everything to None to
142 # save on the regex cost and let the template skip on None.
143 if line.isspace():
144 self.size = None
145 self.type = None
146 else:
147 grouped = self._splitter.match(line)
148 self.type = self._types[grouped.group('type')].upper()
149 self.size = int(grouped.group('size'))
150
151 # Default the start bit to -1
152 self.start = -1
153
154
155 class Format(object):
156 """Class taht contains all values needed by the template."""
157 def __init__(self, line):
158 # pylint: disable=invalid-name
159 self.name = line[0].strip()
160
161 # Future division makes this work in python 2.
162 self.bpb = int(line[1])
163 self.bw = line[2].strip()
164 self.bh = line[3].strip()
165 self.bd = line[4].strip()
166 self.r = Channel(line[5])
167 self.g = Channel(line[6])
168 self.b = Channel(line[7])
169 self.a = Channel(line[8])
170 self.l = Channel(line[9])
171 self.i = Channel(line[10])
172 self.p = Channel(line[11])
173
174 # Set the start bit value for each channel
175 self.order = line[12].strip()
176 bit = 0
177 for c in self.order:
178 chan = getattr(self, c)
179 chan.start = bit
180 bit = bit + chan.size
181
182 # alpha doesn't have a colorspace of it's own.
183 self.colorspace = line[13].strip().upper()
184 if self.colorspace in ['']:
185 self.colorspace = 'NONE'
186
187 # This sets it to the line value, or if it's an empty string 'NONE'
188 self.txc = line[14].strip().upper() or 'NONE'
189
190
191 def reader(csvfile):
192 """Wrapper around csv.reader that skips comments and blanks."""
193 # csv.reader actually reads the file one line at a time (it was designed to
194 # open excel generated sheets), so hold the file until all of the lines are
195 # read.
196 with open(csvfile, 'r') as f:
197 for line in csv.reader(f):
198 if line and not line[0].startswith('#'):
199 yield line
200
201 def get_srgb_to_linear_map(formats):
202 """Compute a map from sRGB to linear formats.
203
204 This function uses some probably somewhat fragile string munging to do
205 the conversion. However, we do assert that, if it's SRGB, the munging
206 succeeded so that gives some safety.
207 """
208 names = {f.name for f in formats}
209 for fmt in formats:
210 if fmt.colorspace != 'SRGB':
211 continue
212
213 replacements = [
214 ('_SRGB', ''),
215 ('SRGB', 'RGB'),
216 ('U8SRGB', 'FLT16'),
217 ]
218
219 found = False
220 for rep in replacements:
221 rgb_name = fmt.name.replace(rep[0], rep[1])
222 if rgb_name in names:
223 found = True
224 yield fmt.name, rgb_name
225 break
226
227 # We should have found a format name
228 assert found
229
230 def main():
231 """Main function."""
232 parser = argparse.ArgumentParser()
233 parser.add_argument('--csv', action='store', help='The CSV file to parse.')
234 parser.add_argument(
235 '--out',
236 action='store',
237 help='The location to put the generated C file.')
238 args = parser.parse_args()
239
240 # This generator opens and writes the file itself, and it does so in bytes
241 # mode. This solves both python 2 vs 3 problems and solves the locale
242 # problem: Unicode can be rendered even if the shell calling this script
243 # doesn't.
244 with open(args.out, 'wb') as f:
245 formats = [Format(l) for l in reader(args.csv)]
246 try:
247 # This basically does lazy evaluation and initialization, which
248 # saves on memory and startup overhead.
249 f.write(TEMPLATE.render(
250 formats = formats,
251 srgb_to_linear_map = list(get_srgb_to_linear_map(formats)),
252 ))
253 except Exception:
254 # In the even there's an error this imports some helpers from mako
255 # to print a useful stack trace and prints it, then exits with
256 # status 1, if python is run with debug; otherwise it just raises
257 # the exception
258 if __debug__:
259 import sys
260 from mako import exceptions
261 print(exceptions.text_error_template().render(),
262 file=sys.stderr)
263 sys.exit(1)
264 raise
265
266
267 if __name__ == '__main__':
268 main()