Merge remote-tracking branch 'origin/master' into vulkan
[mesa.git] / src / intel / genxml / gen_pack_header.py
1 #!/usr/bin/env python3
2
3 import xml.parsers.expat
4 import re
5 import sys
6 import copy
7
8 license = """/*
9 * Copyright (C) 2016 Intel Corporation
10 *
11 * Permission is hereby granted, free of charge, to any person obtaining a
12 * copy of this software and associated documentation files (the "Software"),
13 * to deal in the Software without restriction, including without limitation
14 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
15 * and/or sell copies of the Software, and to permit persons to whom the
16 * Software is furnished to do so, subject to the following conditions:
17 *
18 * The above copyright notice and this permission notice (including the next
19 * paragraph) shall be included in all copies or substantial portions of the
20 * Software.
21 *
22 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
25 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
27 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
28 * IN THE SOFTWARE.
29 */
30 """
31
32 pack_header = """%(license)s
33
34 /* Instructions, enums and structures for %(platform)s.
35 *
36 * This file has been generated, do not hand edit.
37 */
38
39 #pragma once
40
41 #include <stdio.h>
42 #include <stdint.h>
43 #include <stdbool.h>
44 #include <assert.h>
45 #include <math.h>
46
47 #ifndef __gen_validate_value
48 #define __gen_validate_value(x)
49 #endif
50
51 #ifndef __gen_field_functions
52 #define __gen_field_functions
53
54 union __gen_value {
55 float f;
56 uint32_t dw;
57 };
58
59 static inline uint64_t
60 __gen_mbo(uint32_t start, uint32_t end)
61 {
62 return (~0ull >> (64 - (end - start + 1))) << start;
63 }
64
65 static inline uint64_t
66 __gen_uint(uint64_t v, uint32_t start, uint32_t end)
67 {
68 __gen_validate_value(v);
69
70 #if DEBUG
71 const int width = end - start + 1;
72 if (width < 64) {
73 const uint64_t max = (1ull << width) - 1;
74 assert(v <= max);
75 }
76 #endif
77
78 return v << start;
79 }
80
81 static inline uint64_t
82 __gen_sint(int64_t v, uint32_t start, uint32_t end)
83 {
84 const int width = end - start + 1;
85
86 __gen_validate_value(v);
87
88 #if DEBUG
89 if (width < 64) {
90 const int64_t max = (1ll << (width - 1)) - 1;
91 const int64_t min = -(1ll << (width - 1));
92 assert(min <= v && v <= max);
93 }
94 #endif
95
96 const uint64_t mask = ~0ull >> (64 - width);
97
98 return (v & mask) << start;
99 }
100
101 static inline uint64_t
102 __gen_offset(uint64_t v, uint32_t start, uint32_t end)
103 {
104 __gen_validate_value(v);
105 #if DEBUG
106 uint64_t mask = (~0ull >> (64 - (end - start + 1))) << start;
107
108 assert((v & ~mask) == 0);
109 #endif
110
111 return v;
112 }
113
114 static inline uint32_t
115 __gen_float(float v)
116 {
117 __gen_validate_value(v);
118 return ((union __gen_value) { .f = (v) }).dw;
119 }
120
121 static inline uint64_t
122 __gen_sfixed(float v, uint32_t start, uint32_t end, uint32_t fract_bits)
123 {
124 __gen_validate_value(v);
125
126 const float factor = (1 << fract_bits);
127
128 #if DEBUG
129 const float max = ((1 << (end - start)) - 1) / factor;
130 const float min = -(1 << (end - start)) / factor;
131 assert(min <= v && v <= max);
132 #endif
133
134 const int32_t int_val = roundf(v * factor);
135 const uint64_t mask = ~0ull >> (64 - (end - start + 1));
136
137 return (int_val & mask) << start;
138 }
139
140 static inline uint64_t
141 __gen_ufixed(float v, uint32_t start, uint32_t end, uint32_t fract_bits)
142 {
143 __gen_validate_value(v);
144
145 const float factor = (1 << fract_bits);
146
147 #if DEBUG
148 const float max = ((1 << (end - start + 1)) - 1) / factor;
149 const float min = 0.0f;
150 assert(min <= v && v <= max);
151 #endif
152
153 const uint32_t uint_val = roundf(v * factor);
154
155 return uint_val << start;
156 }
157
158 #ifndef __gen_address_type
159 #error #define __gen_address_type before including this file
160 #endif
161
162 #ifndef __gen_user_data
163 #error #define __gen_combine_address before including this file
164 #endif
165
166 #endif
167
168 """
169
170 def to_alphanum(name):
171 substitutions = {
172 ' ': '',
173 '/': '',
174 '[': '',
175 ']': '',
176 '(': '',
177 ')': '',
178 '-': '',
179 ':': '',
180 '.': '',
181 ',': '',
182 '=': '',
183 '>': '',
184 '#': '',
185 'α': 'alpha',
186 '&': '',
187 '*': '',
188 '"': '',
189 '+': '',
190 '\'': '',
191 }
192
193 for i, j in substitutions.items():
194 name = name.replace(i, j)
195
196 return name
197
198 def safe_name(name):
199 name = to_alphanum(name)
200 if not str.isalpha(name[0]):
201 name = '_' + name
202
203 return name
204
205 class Field:
206 ufixed_pattern = re.compile("u(\d+)\.(\d+)")
207 sfixed_pattern = re.compile("s(\d+)\.(\d+)")
208
209 def __init__(self, parser, attrs):
210 self.parser = parser
211 if "name" in attrs:
212 self.name = safe_name(attrs["name"])
213 self.start = int(attrs["start"])
214 self.end = int(attrs["end"])
215 self.type = attrs["type"]
216
217 if "prefix" in attrs:
218 self.prefix = attrs["prefix"]
219 else:
220 self.prefix = None
221
222 if "default" in attrs:
223 self.default = int(attrs["default"])
224 else:
225 self.default = None
226
227 ufixed_match = Field.ufixed_pattern.match(self.type)
228 if ufixed_match:
229 self.type = 'ufixed'
230 self.fractional_size = int(ufixed_match.group(2))
231
232 sfixed_match = Field.sfixed_pattern.match(self.type)
233 if sfixed_match:
234 self.type = 'sfixed'
235 self.fractional_size = int(sfixed_match.group(2))
236
237 def emit_template_struct(self, dim):
238 if self.type == 'address':
239 type = '__gen_address_type'
240 elif self.type == 'bool':
241 type = 'bool'
242 elif self.type == 'float':
243 type = 'float'
244 elif self.type == 'ufixed':
245 type = 'float'
246 elif self.type == 'sfixed':
247 type = 'float'
248 elif self.type == 'uint' and self.end - self.start > 32:
249 type = 'uint64_t'
250 elif self.type == 'offset':
251 type = 'uint64_t'
252 elif self.type == 'int':
253 type = 'int32_t'
254 elif self.type == 'uint':
255 type = 'uint32_t'
256 elif self.type in self.parser.structs:
257 type = 'struct ' + self.parser.gen_prefix(safe_name(self.type))
258 elif self.type == 'mbo':
259 return
260 else:
261 print("#error unhandled type: %s" % self.type)
262
263 print(" %-36s %s%s;" % (type, self.name, dim))
264
265 if len(self.values) > 0 and self.default == None:
266 if self.prefix:
267 prefix = self.prefix + "_"
268 else:
269 prefix = ""
270
271 for value in self.values:
272 print("#define %-40s %d" % (prefix + value.name, value.value))
273
274 class Group:
275 def __init__(self, parser, parent, start, count, size):
276 self.parser = parser
277 self.parent = parent
278 self.start = start
279 self.count = count
280 self.size = size
281 self.fields = []
282
283 def emit_template_struct(self, dim):
284 if self.count == 0:
285 print(" /* variable length fields follow */")
286 else:
287 if self.count > 1:
288 dim = "%s[%d]" % (dim, self.count)
289
290 for field in self.fields:
291 field.emit_template_struct(dim)
292
293 class DWord:
294 def __init__(self):
295 self.size = 32
296 self.fields = []
297 self.address = None
298
299 def collect_dwords(self, dwords, start, dim):
300 for field in self.fields:
301 if type(field) is Group:
302 if field.count == 1:
303 field.collect_dwords(dwords, start + field.start, dim)
304 else:
305 for i in range(field.count):
306 field.collect_dwords(dwords,
307 start + field.start + i * field.size,
308 "%s[%d]" % (dim, i))
309 continue
310
311 index = (start + field.start) // 32
312 if not index in dwords:
313 dwords[index] = self.DWord()
314
315 clone = copy.copy(field)
316 clone.start = clone.start + start
317 clone.end = clone.end + start
318 clone.dim = dim
319 dwords[index].fields.append(clone)
320
321 if field.type == "address":
322 # assert dwords[index].address == None
323 dwords[index].address = field
324
325 # Coalesce all the dwords covered by this field. The two cases we
326 # handle are where multiple fields are in a 64 bit word (typically
327 # and address and a few bits) or where a single struct field
328 # completely covers multiple dwords.
329 while index < (start + field.end) // 32:
330 if index + 1 in dwords and not dwords[index] == dwords[index + 1]:
331 dwords[index].fields.extend(dwords[index + 1].fields)
332 dwords[index].size = 64
333 dwords[index + 1] = dwords[index]
334 index = index + 1
335
336 def emit_pack_function(self, start):
337 dwords = {}
338 self.collect_dwords(dwords, 0, "")
339
340 # Determine number of dwords in this group. If we have a size, use
341 # that, since that'll account for MBZ dwords at the end of a group
342 # (like dword 8 on BDW+ 3DSTATE_HS). Otherwise, use the largest dword
343 # index we've seen plus one.
344 if self.size > 0:
345 length = self.size // 32
346 else:
347 length = max(dwords.keys()) + 1
348
349 for index in range(length):
350 # Handle MBZ dwords
351 if not index in dwords:
352 print("")
353 print(" dw[%d] = 0;" % index)
354 continue
355
356 # For 64 bit dwords, we aliased the two dword entries in the dword
357 # dict it occupies. Now that we're emitting the pack function,
358 # skip the duplicate entries.
359 dw = dwords[index]
360 if index > 0 and index - 1 in dwords and dw == dwords[index - 1]:
361 continue
362
363 # Special case: only one field and it's a struct at the beginning
364 # of the dword. In this case we pack directly into the
365 # destination. This is the only way we handle embedded structs
366 # larger than 32 bits.
367 if len(dw.fields) == 1:
368 field = dw.fields[0]
369 name = field.name + field.dim
370 if field.type in self.parser.structs and field.start % 32 == 0:
371 print("")
372 print(" %s_pack(data, &dw[%d], &values->%s);" %
373 (self.parser.gen_prefix(safe_name(field.type)), index, name))
374 continue
375
376 # Pack any fields of struct type first so we have integer values
377 # to the dword for those fields.
378 field_index = 0
379 for field in dw.fields:
380 if type(field) is Field and field.type in self.parser.structs:
381 name = field.name + field.dim
382 print("")
383 print(" uint32_t v%d_%d;" % (index, field_index))
384 print(" %s_pack(data, &v%d_%d, &values->%s);" %
385 (self.parser.gen_prefix(safe_name(field.type)), index, field_index, name))
386 field_index = field_index + 1
387
388 print("")
389 dword_start = index * 32
390 if dw.address == None:
391 address_count = 0
392 else:
393 address_count = 1
394
395 if dw.size == 32 and dw.address == None:
396 v = None
397 print(" dw[%d] =" % index)
398 elif len(dw.fields) > address_count:
399 v = "v%d" % index
400 print(" const uint%d_t %s =" % (dw.size, v))
401 else:
402 v = "0"
403
404 field_index = 0
405 for field in dw.fields:
406 if field.type != "mbo":
407 name = field.name + field.dim
408
409 if field.type == "mbo":
410 s = "__gen_mbo(%d, %d)" % \
411 (field.start - dword_start, field.end - dword_start)
412 elif field.type == "address":
413 s = None
414 elif field.type == "uint":
415 s = "__gen_uint(values->%s, %d, %d)" % \
416 (name, field.start - dword_start, field.end - dword_start)
417 elif field.type == "int":
418 s = "__gen_sint(values->%s, %d, %d)" % \
419 (name, field.start - dword_start, field.end - dword_start)
420 elif field.type == "bool":
421 s = "__gen_uint(values->%s, %d, %d)" % \
422 (name, field.start - dword_start, field.end - dword_start)
423 elif field.type == "float":
424 s = "__gen_float(values->%s)" % name
425 elif field.type == "offset":
426 s = "__gen_offset(values->%s, %d, %d)" % \
427 (name, field.start - dword_start, field.end - dword_start)
428 elif field.type == 'ufixed':
429 s = "__gen_ufixed(values->%s, %d, %d, %d)" % \
430 (name, field.start - dword_start, field.end - dword_start, field.fractional_size)
431 elif field.type == 'sfixed':
432 s = "__gen_sfixed(values->%s, %d, %d, %d)" % \
433 (name, field.start - dword_start, field.end - dword_start, field.fractional_size)
434 elif field.type in self.parser.structs:
435 s = "__gen_uint(v%d_%d, %d, %d)" % \
436 (index, field_index, field.start - dword_start, field.end - dword_start)
437 field_index = field_index + 1
438 else:
439 print("/* unhandled field %s, type %s */\n" % (name, field.type))
440 s = None
441
442 if not s == None:
443 if field == dw.fields[-1]:
444 print(" %s;" % s)
445 else:
446 print(" %s |" % s)
447
448 if dw.size == 32:
449 if dw.address:
450 print(" dw[%d] = __gen_combine_address(data, &dw[%d], values->%s, %s);" % (index, index, dw.address.name, v))
451 continue
452
453 if dw.address:
454 v_address = "v%d_address" % index
455 print(" const uint64_t %s =\n __gen_combine_address(data, &dw[%d], values->%s, %s);" %
456 (v_address, index, dw.address.name, v))
457 v = v_address
458
459 print(" dw[%d] = %s;" % (index, v))
460 print(" dw[%d] = %s >> 32;" % (index + 1, v))
461
462 class Value:
463 def __init__(self, attrs):
464 self.name = safe_name(attrs["name"])
465 self.value = int(attrs["value"])
466
467 class Parser:
468 def __init__(self):
469 self.parser = xml.parsers.expat.ParserCreate()
470 self.parser.StartElementHandler = self.start_element
471 self.parser.EndElementHandler = self.end_element
472
473 self.instruction = None
474 self.structs = {}
475
476 def start_element(self, name, attrs):
477 if name == "genxml":
478 self.platform = attrs["name"]
479 self.gen = attrs["gen"].replace('.', '')
480 print(pack_header % {'license': license, 'platform': self.platform})
481 elif name == "instruction":
482 self.instruction = safe_name(attrs["name"])
483 self.length_bias = int(attrs["bias"])
484 if "length" in attrs:
485 self.length = int(attrs["length"])
486 size = self.length * 32
487 else:
488 self.length = None
489 size = 0
490 self.group = Group(self, None, 0, 1, size)
491 elif name == "struct":
492 self.struct = safe_name(attrs["name"])
493 self.structs[attrs["name"]] = 1
494 if "length" in attrs:
495 self.length = int(attrs["length"])
496 size = self.length * 32
497 else:
498 self.length = None
499 size = 0
500 self.group = Group(self, None, 0, 1, size)
501
502 elif name == "group":
503 group = Group(self, self.group,
504 int(attrs["start"]), int(attrs["count"]), int(attrs["size"]))
505 self.group.fields.append(group)
506 self.group = group
507 elif name == "field":
508 self.group.fields.append(Field(self, attrs))
509 self.values = []
510 elif name == "enum":
511 self.values = []
512 self.enum = safe_name(attrs["name"])
513 if "prefix" in attrs:
514 self.prefix = safe_name(attrs["prefix"])
515 else:
516 self.prefix= None
517 elif name == "value":
518 self.values.append(Value(attrs))
519
520 def end_element(self, name):
521 if name == "instruction":
522 self.emit_instruction()
523 self.instruction = None
524 self.group = None
525 elif name == "struct":
526 self.emit_struct()
527 self.struct = None
528 self.group = None
529 elif name == "group":
530 self.group = self.group.parent
531 elif name == "field":
532 self.group.fields[-1].values = self.values
533 elif name == "enum":
534 self.emit_enum()
535 self.enum = None
536
537 def gen_prefix(self, name):
538 if name[0] == "_":
539 return 'GEN%s%s' % (self.gen, name)
540 else:
541 return 'GEN%s_%s' % (self.gen, name)
542
543 def emit_template_struct(self, name, group):
544 print("struct %s {" % self.gen_prefix(name))
545 group.emit_template_struct("")
546 print("};\n")
547
548 def emit_pack_function(self, name, group):
549 name = self.gen_prefix(name)
550 print("static inline void\n%s_pack(__gen_user_data *data, void * restrict dst,\n%sconst struct %s * restrict values)\n{" %
551 (name, ' ' * (len(name) + 6), name))
552
553 # Cast dst to make header C++ friendly
554 print(" uint32_t * restrict dw = (uint32_t * restrict) dst;")
555
556 group.emit_pack_function(0)
557
558 print("}\n")
559
560 def emit_instruction(self):
561 name = self.instruction
562 if not self.length == None:
563 print('#define %-33s %4d' %
564 (self.gen_prefix(name + "_length"), self.length))
565 print('#define %-33s %4d' %
566 (self.gen_prefix(name + "_length_bias"), self.length_bias))
567
568 default_fields = []
569 for field in self.group.fields:
570 if not type(field) is Field:
571 continue
572 if field.default == None:
573 continue
574 default_fields.append(" .%-35s = %4d" % (field.name, field.default))
575
576 if default_fields:
577 print('#define %-40s\\' % (self.gen_prefix(name + '_header')))
578 print(", \\\n".join(default_fields))
579 print('')
580
581 self.emit_template_struct(self.instruction, self.group)
582
583 self.emit_pack_function(self.instruction, self.group)
584
585 def emit_struct(self):
586 name = self.struct
587 if not self.length == None:
588 print('#define %-33s %4d' %
589 (self.gen_prefix(name + "_length"), self.length))
590
591 self.emit_template_struct(self.struct, self.group)
592 self.emit_pack_function(self.struct, self.group)
593
594 def emit_enum(self):
595 print('/* enum %s */' % self.gen_prefix(self.enum))
596 for value in self.values:
597 if self.prefix:
598 name = self.prefix + "_" + value.name
599 else:
600 name = value.name
601 print('#define %-36s %4d' % (name.upper(), value.value))
602 print('')
603
604 def parse(self, filename):
605 file = open(filename, "rb")
606 self.parser.ParseFile(file)
607 file.close()
608
609 if len(sys.argv) < 2:
610 print("No input xml file specified")
611 sys.exit(1)
612
613 input_file = sys.argv[1]
614
615 p = Parser()
616 p.parse(input_file)