Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mesa
Path: blob/21.2-virgl/src/panfrost/lib/gen_pack.py
4560 views
1
#encoding=utf-8
2
3
# Copyright (C) 2016 Intel Corporation
4
# Copyright (C) 2016 Broadcom
5
# Copyright (C) 2020 Collabora, Ltd.
6
#
7
# Permission is hereby granted, free of charge, to any person obtaining a
8
# copy of this software and associated documentation files (the "Software"),
9
# to deal in the Software without restriction, including without limitation
10
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
11
# and/or sell copies of the Software, and to permit persons to whom the
12
# Software is furnished to do so, subject to the following conditions:
13
#
14
# The above copyright notice and this permission notice (including the next
15
# paragraph) shall be included in all copies or substantial portions of the
16
# Software.
17
#
18
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
21
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
24
# IN THE SOFTWARE.
25
26
import xml.parsers.expat
27
import sys
28
import operator
29
from functools import reduce
30
31
global_prefix = "mali"
32
33
pack_header = """
34
/* Generated code, see midgard.xml and gen_pack_header.py
35
*
36
* Packets, enums and structures for Panfrost.
37
*
38
* This file has been generated, do not hand edit.
39
*/
40
41
#ifndef PAN_PACK_H
42
#define PAN_PACK_H
43
44
#include <stdio.h>
45
#include <stdint.h>
46
#include <stdbool.h>
47
#include <assert.h>
48
#include <math.h>
49
#include <inttypes.h>
50
#include "util/macros.h"
51
#include "util/u_math.h"
52
53
#define __gen_unpack_float(x, y, z) uif(__gen_unpack_uint(x, y, z))
54
55
static inline uint64_t
56
__gen_uint(uint64_t v, uint32_t start, uint32_t end)
57
{
58
#ifndef NDEBUG
59
const int width = end - start + 1;
60
if (width < 64) {
61
const uint64_t max = (1ull << width) - 1;
62
assert(v <= max);
63
}
64
#endif
65
66
return v << start;
67
}
68
69
static inline uint32_t
70
__gen_sint(int32_t v, uint32_t start, uint32_t end)
71
{
72
#ifndef NDEBUG
73
const int width = end - start + 1;
74
if (width < 64) {
75
const int64_t max = (1ll << (width - 1)) - 1;
76
const int64_t min = -(1ll << (width - 1));
77
assert(min <= v && v <= max);
78
}
79
#endif
80
81
return (((uint32_t) v) << start) & ((2ll << end) - 1);
82
}
83
84
static inline uint32_t
85
__gen_padded(uint32_t v, uint32_t start, uint32_t end)
86
{
87
unsigned shift = __builtin_ctz(v);
88
unsigned odd = v >> (shift + 1);
89
90
#ifndef NDEBUG
91
assert((v >> shift) & 1);
92
assert(shift <= 31);
93
assert(odd <= 7);
94
assert((end - start + 1) == 8);
95
#endif
96
97
return __gen_uint(shift | (odd << 5), start, end);
98
}
99
100
101
static inline uint64_t
102
__gen_unpack_uint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
103
{
104
uint64_t val = 0;
105
const int width = end - start + 1;
106
const uint64_t mask = (width == 64 ? ~0 : (1ull << width) - 1 );
107
108
for (uint32_t byte = start / 8; byte <= end / 8; byte++) {
109
val |= ((uint64_t) cl[byte]) << ((byte - start / 8) * 8);
110
}
111
112
return (val >> (start % 8)) & mask;
113
}
114
115
static inline uint64_t
116
__gen_unpack_sint(const uint8_t *restrict cl, uint32_t start, uint32_t end)
117
{
118
int size = end - start + 1;
119
int64_t val = __gen_unpack_uint(cl, start, end);
120
121
/* Get the sign bit extended. */
122
return (val << (64 - size)) >> (64 - size);
123
}
124
125
static inline uint64_t
126
__gen_unpack_padded(const uint8_t *restrict cl, uint32_t start, uint32_t end)
127
{
128
unsigned val = __gen_unpack_uint(cl, start, end);
129
unsigned shift = val & 0b11111;
130
unsigned odd = val >> 5;
131
132
return (2*odd + 1) << shift;
133
}
134
135
#define pan_prepare(dst, T) \\
136
*(dst) = (struct MALI_ ## T){ MALI_ ## T ## _header }
137
138
#define pan_pack(dst, T, name) \\
139
for (struct MALI_ ## T name = { MALI_ ## T ## _header }, \\
140
*_loop_terminate = (void *) (dst); \\
141
__builtin_expect(_loop_terminate != NULL, 1); \\
142
({ MALI_ ## T ## _pack((uint32_t *) (dst), &name); \\
143
_loop_terminate = NULL; }))
144
145
#define pan_unpack(src, T, name) \\
146
struct MALI_ ## T name; \\
147
MALI_ ## T ## _unpack((uint8_t *)(src), &name)
148
149
#define pan_print(fp, T, var, indent) \\
150
MALI_ ## T ## _print(fp, &(var), indent)
151
152
#define pan_section_offset(A, S) \\
153
MALI_ ## A ## _SECTION_ ## S ## _OFFSET
154
155
#define pan_section_ptr(base, A, S) \\
156
((void *)((uint8_t *)(base) + pan_section_offset(A, S)))
157
158
#define pan_section_pack(dst, A, S, name) \\
159
for (MALI_ ## A ## _SECTION_ ## S ## _TYPE name = { MALI_ ## A ## _SECTION_ ## S ## _header }, \\
160
*_loop_terminate = (void *) (dst); \\
161
__builtin_expect(_loop_terminate != NULL, 1); \\
162
({ MALI_ ## A ## _SECTION_ ## S ## _pack(pan_section_ptr(dst, A, S), &name); \\
163
_loop_terminate = NULL; }))
164
165
#define pan_section_unpack(src, A, S, name) \\
166
MALI_ ## A ## _SECTION_ ## S ## _TYPE name; \\
167
MALI_ ## A ## _SECTION_ ## S ## _unpack(pan_section_ptr(src, A, S), &name)
168
169
#define pan_section_print(fp, A, S, var, indent) \\
170
MALI_ ## A ## _SECTION_ ## S ## _print(fp, &(var), indent)
171
172
#define pan_merge(packed1, packed2, type) \
173
do { \
174
for (unsigned i = 0; i < (MALI_ ## type ## _LENGTH / 4); ++i) \
175
packed1.opaque[i] |= packed2.opaque[i]; \
176
} while(0)
177
178
#define mali_pixel_format_print_v6(fp, format) \\
179
fprintf(fp, "%*sFormat (v6): %s%s%s %s%s%s%s\\n", indent, "", \\
180
mali_format_as_str((enum mali_format)((format >> 12) & 0xFF)), \\
181
(format & (1 << 20)) ? " sRGB" : "", \\
182
(format & (1 << 21)) ? " big-endian" : "", \\
183
mali_channel_as_str((enum mali_channel)((format >> 0) & 0x7)), \\
184
mali_channel_as_str((enum mali_channel)((format >> 3) & 0x7)), \\
185
mali_channel_as_str((enum mali_channel)((format >> 6) & 0x7)), \\
186
mali_channel_as_str((enum mali_channel)((format >> 9) & 0x7)));
187
188
#define mali_pixel_format_print_v7(fp, format) \\
189
fprintf(fp, "%*sFormat (v7): %s%s %s%s\\n", indent, "", \\
190
mali_format_as_str((enum mali_format)((format >> 12) & 0xFF)), \\
191
(format & (1 << 20)) ? " sRGB" : "", \\
192
mali_rgb_component_order_as_str((enum mali_rgb_component_order)(format & ((1 << 12) - 1))), \\
193
(format & (1 << 21)) ? " XXX BAD BIT" : "");
194
195
196
/* From presentations, 16x16 tiles externally. Use shift for fast computation
197
* of tile numbers. */
198
199
#define MALI_TILE_SHIFT 4
200
#define MALI_TILE_LENGTH (1 << MALI_TILE_SHIFT)
201
202
"""
203
204
def to_alphanum(name):
205
substitutions = {
206
' ': '_',
207
'/': '_',
208
'[': '',
209
']': '',
210
'(': '',
211
')': '',
212
'-': '_',
213
':': '',
214
'.': '',
215
',': '',
216
'=': '',
217
'>': '',
218
'#': '',
219
'&': '',
220
'*': '',
221
'"': '',
222
'+': '',
223
'\'': '',
224
}
225
226
for i, j in substitutions.items():
227
name = name.replace(i, j)
228
229
return name
230
231
def safe_name(name):
232
name = to_alphanum(name)
233
if not name[0].isalpha():
234
name = '_' + name
235
236
return name
237
238
def prefixed_upper_name(prefix, name):
239
if prefix:
240
name = prefix + "_" + name
241
return safe_name(name).upper()
242
243
def enum_name(name):
244
return "{}_{}".format(global_prefix, safe_name(name)).lower()
245
246
def num_from_str(num_str):
247
if num_str.lower().startswith('0x'):
248
return int(num_str, base=16)
249
else:
250
assert(not num_str.startswith('0') and 'octals numbers not allowed')
251
return int(num_str)
252
253
MODIFIERS = ["shr", "minus", "align", "log2"]
254
255
def parse_modifier(modifier):
256
if modifier is None:
257
return None
258
259
for mod in MODIFIERS:
260
if modifier[0:len(mod)] == mod:
261
if mod == "log2":
262
assert(len(mod) == len(modifier))
263
return [mod]
264
265
if modifier[len(mod)] == '(' and modifier[-1] == ')':
266
ret = [mod, int(modifier[(len(mod) + 1):-1])]
267
if ret[0] == 'align':
268
align = ret[1]
269
# Make sure the alignment is a power of 2
270
assert(align > 0 and not(align & (align - 1)));
271
272
return ret
273
274
print("Invalid modifier")
275
assert(False)
276
277
class Aggregate(object):
278
def __init__(self, parser, name, attrs):
279
self.parser = parser
280
self.sections = []
281
self.name = name
282
self.explicit_size = int(attrs["size"]) if "size" in attrs else 0
283
self.size = 0
284
self.align = int(attrs["align"]) if "align" in attrs else None
285
286
class Section:
287
def __init__(self, name):
288
self.name = name
289
290
def get_size(self):
291
if self.size > 0:
292
return self.size
293
294
size = 0
295
for section in self.sections:
296
size = max(size, section.offset + section.type.get_length())
297
298
if self.explicit_size > 0:
299
assert(self.explicit_size >= size)
300
self.size = self.explicit_size
301
else:
302
self.size = size
303
return self.size
304
305
def add_section(self, type_name, attrs):
306
assert("name" in attrs)
307
section = self.Section(safe_name(attrs["name"]).lower())
308
section.human_name = attrs["name"]
309
section.offset = int(attrs["offset"])
310
assert(section.offset % 4 == 0)
311
section.type = self.parser.structs[attrs["type"]]
312
section.type_name = type_name
313
self.sections.append(section)
314
315
class Field(object):
316
def __init__(self, parser, attrs):
317
self.parser = parser
318
if "name" in attrs:
319
self.name = safe_name(attrs["name"]).lower()
320
self.human_name = attrs["name"]
321
322
if ":" in str(attrs["start"]):
323
(word, bit) = attrs["start"].split(":")
324
self.start = (int(word) * 32) + int(bit)
325
else:
326
self.start = int(attrs["start"])
327
328
self.end = self.start + int(attrs["size"]) - 1
329
self.type = attrs["type"]
330
331
if self.type == 'bool' and self.start != self.end:
332
print("#error Field {} has bool type but more than one bit of size".format(self.name));
333
334
if "prefix" in attrs:
335
self.prefix = safe_name(attrs["prefix"]).upper()
336
else:
337
self.prefix = None
338
339
if "exact" in attrs:
340
self.exact = int(attrs["exact"])
341
else:
342
self.exact = None
343
344
self.default = attrs.get("default")
345
346
# Map enum values
347
if self.type in self.parser.enums and self.default is not None:
348
self.default = safe_name('{}_{}_{}'.format(global_prefix, self.type, self.default)).upper()
349
350
self.modifier = parse_modifier(attrs.get("modifier"))
351
352
def emit_template_struct(self, dim):
353
if self.type == 'address':
354
type = 'uint64_t'
355
elif self.type == 'bool':
356
type = 'bool'
357
elif self.type == 'float':
358
type = 'float'
359
elif self.type == 'uint' and self.end - self.start > 32:
360
type = 'uint64_t'
361
elif self.type == 'int':
362
type = 'int32_t'
363
elif self.type in ['uint', 'uint/float', 'padded', 'Pixel Format']:
364
type = 'uint32_t'
365
elif self.type in self.parser.structs:
366
type = 'struct ' + self.parser.gen_prefix(safe_name(self.type.upper()))
367
elif self.type in self.parser.enums:
368
type = 'enum ' + enum_name(self.type)
369
else:
370
print("#error unhandled type: %s" % self.type)
371
type = "uint32_t"
372
373
print(" %-36s %s%s;" % (type, self.name, dim))
374
375
for value in self.values:
376
name = prefixed_upper_name(self.prefix, value.name)
377
print("#define %-40s %d" % (name, value.value))
378
379
def overlaps(self, field):
380
return self != field and max(self.start, field.start) <= min(self.end, field.end)
381
382
class Group(object):
383
def __init__(self, parser, parent, start, count, label):
384
self.parser = parser
385
self.parent = parent
386
self.start = start
387
self.count = count
388
self.label = label
389
self.size = 0
390
self.length = 0
391
self.fields = []
392
393
def get_length(self):
394
# Determine number of bytes in this group.
395
calculated = max(field.end // 8 for field in self.fields) + 1 if len(self.fields) > 0 else 0
396
if self.length > 0:
397
assert(self.length >= calculated)
398
else:
399
self.length = calculated
400
return self.length
401
402
403
def emit_template_struct(self, dim):
404
if self.count == 0:
405
print(" /* variable length fields follow */")
406
else:
407
if self.count > 1:
408
dim = "%s[%d]" % (dim, self.count)
409
410
if len(self.fields) == 0:
411
print(" int dummy;")
412
413
for field in self.fields:
414
if field.exact is not None:
415
continue
416
417
field.emit_template_struct(dim)
418
419
class Word:
420
def __init__(self):
421
self.size = 32
422
self.contributors = []
423
424
class FieldRef:
425
def __init__(self, field, path, start, end):
426
self.field = field
427
self.path = path
428
self.start = start
429
self.end = end
430
431
def collect_fields(self, fields, offset, path, all_fields):
432
for field in fields:
433
field_path = '{}{}'.format(path, field.name)
434
field_offset = offset + field.start
435
436
if field.type in self.parser.structs:
437
sub_struct = self.parser.structs[field.type]
438
self.collect_fields(sub_struct.fields, field_offset, field_path + '.', all_fields)
439
continue
440
441
start = field_offset
442
end = offset + field.end
443
all_fields.append(self.FieldRef(field, field_path, start, end))
444
445
def collect_words(self, fields, offset, path, words):
446
for field in fields:
447
field_path = '{}{}'.format(path, field.name)
448
start = offset + field.start
449
450
if field.type in self.parser.structs:
451
sub_fields = self.parser.structs[field.type].fields
452
self.collect_words(sub_fields, start, field_path + '.', words)
453
continue
454
455
end = offset + field.end
456
contributor = self.FieldRef(field, field_path, start, end)
457
first_word = contributor.start // 32
458
last_word = contributor.end // 32
459
for b in range(first_word, last_word + 1):
460
if not b in words:
461
words[b] = self.Word()
462
words[b].contributors.append(contributor)
463
464
def emit_pack_function(self):
465
self.get_length()
466
467
words = {}
468
self.collect_words(self.fields, 0, '', words)
469
470
# Validate the modifier is lossless
471
for field in self.fields:
472
if field.modifier is None:
473
continue
474
475
assert(field.exact is None)
476
477
if field.modifier[0] == "shr":
478
shift = field.modifier[1]
479
mask = hex((1 << shift) - 1)
480
print(" assert((values->{} & {}) == 0);".format(field.name, mask))
481
elif field.modifier[0] == "minus":
482
print(" assert(values->{} >= {});".format(field.name, field.modifier[1]))
483
elif field.modifier[0] == "log2":
484
print(" assert(util_is_power_of_two_nonzero(values->{}));".format(field.name))
485
486
for index in range(self.length // 4):
487
# Handle MBZ words
488
if not index in words:
489
print(" cl[%2d] = 0;" % index)
490
continue
491
492
word = words[index]
493
494
word_start = index * 32
495
496
v = None
497
prefix = " cl[%2d] =" % index
498
499
for contributor in word.contributors:
500
field = contributor.field
501
name = field.name
502
start = contributor.start
503
end = contributor.end
504
contrib_word_start = (start // 32) * 32
505
start -= contrib_word_start
506
end -= contrib_word_start
507
508
value = str(field.exact) if field.exact is not None else "values->{}".format(contributor.path)
509
if field.modifier is not None:
510
if field.modifier[0] == "shr":
511
value = "{} >> {}".format(value, field.modifier[1])
512
elif field.modifier[0] == "minus":
513
value = "{} - {}".format(value, field.modifier[1])
514
elif field.modifier[0] == "align":
515
value = "ALIGN_POT({}, {})".format(value, field.modifier[1])
516
elif field.modifier[0] == "log2":
517
value = "util_logbase2({})".format(value)
518
519
if field.type in ["uint", "uint/float", "address", "Pixel Format"]:
520
s = "__gen_uint(%s, %d, %d)" % \
521
(value, start, end)
522
elif field.type == "padded":
523
s = "__gen_padded(%s, %d, %d)" % \
524
(value, start, end)
525
elif field.type in self.parser.enums:
526
s = "__gen_uint(%s, %d, %d)" % \
527
(value, start, end)
528
elif field.type == "int":
529
s = "__gen_sint(%s, %d, %d)" % \
530
(value, start, end)
531
elif field.type == "bool":
532
s = "__gen_uint(%s, %d, %d)" % \
533
(value, start, end)
534
elif field.type == "float":
535
assert(start == 0 and end == 31)
536
s = "__gen_uint(fui({}), 0, 32)".format(value)
537
else:
538
s = "#error unhandled field {}, type {}".format(contributor.path, field.type)
539
540
if not s == None:
541
shift = word_start - contrib_word_start
542
if shift:
543
s = "%s >> %d" % (s, shift)
544
545
if contributor == word.contributors[-1]:
546
print("%s %s;" % (prefix, s))
547
else:
548
print("%s %s |" % (prefix, s))
549
prefix = " "
550
551
continue
552
553
# Given a field (start, end) contained in word `index`, generate the 32-bit
554
# mask of present bits relative to the word
555
def mask_for_word(self, index, start, end):
556
field_word_start = index * 32
557
start -= field_word_start
558
end -= field_word_start
559
# Cap multiword at one word
560
start = max(start, 0)
561
end = min(end, 32 - 1)
562
count = (end - start + 1)
563
return (((1 << count) - 1) << start)
564
565
def emit_unpack_function(self):
566
# First, verify there is no garbage in unused bits
567
words = {}
568
self.collect_words(self.fields, 0, '', words)
569
570
for index in range(self.length // 4):
571
base = index * 32
572
word = words.get(index, self.Word())
573
masks = [self.mask_for_word(index, c.start, c.end) for c in word.contributors]
574
mask = reduce(lambda x,y: x | y, masks, 0)
575
576
ALL_ONES = 0xffffffff
577
578
if mask != ALL_ONES:
579
TMPL = ' if (((const uint32_t *) cl)[{}] & {}) fprintf(stderr, "XXX: Invalid field of {} unpacked at word {}\\n");'
580
print(TMPL.format(index, hex(mask ^ ALL_ONES), self.label, index))
581
582
fieldrefs = []
583
self.collect_fields(self.fields, 0, '', fieldrefs)
584
for fieldref in fieldrefs:
585
field = fieldref.field
586
convert = None
587
588
args = []
589
args.append('cl')
590
args.append(str(fieldref.start))
591
args.append(str(fieldref.end))
592
593
if field.type in set(["uint", "uint/float", "address", "Pixel Format"]):
594
convert = "__gen_unpack_uint"
595
elif field.type in self.parser.enums:
596
convert = "(enum %s)__gen_unpack_uint" % enum_name(field.type)
597
elif field.type == "int":
598
convert = "__gen_unpack_sint"
599
elif field.type == "padded":
600
convert = "__gen_unpack_padded"
601
elif field.type == "bool":
602
convert = "__gen_unpack_uint"
603
elif field.type == "float":
604
convert = "__gen_unpack_float"
605
else:
606
s = "/* unhandled field %s, type %s */\n" % (field.name, field.type)
607
608
suffix = ""
609
prefix = ""
610
if field.modifier:
611
if field.modifier[0] == "minus":
612
suffix = " + {}".format(field.modifier[1])
613
elif field.modifier[0] == "shr":
614
suffix = " << {}".format(field.modifier[1])
615
if field.modifier[0] == "log2":
616
prefix = "1 << "
617
618
decoded = '{}{}({}){}'.format(prefix, convert, ', '.join(args), suffix)
619
620
print(' values->{} = {};'.format(fieldref.path, decoded))
621
if field.modifier and field.modifier[0] == "align":
622
mask = hex(field.modifier[1] - 1)
623
print(' assert(!(values->{} & {}));'.format(fieldref.path, mask))
624
625
def emit_print_function(self):
626
for field in self.fields:
627
convert = None
628
name, val = field.human_name, 'values->{}'.format(field.name)
629
630
if field.type in self.parser.structs:
631
pack_name = self.parser.gen_prefix(safe_name(field.type)).upper()
632
print(' fprintf(fp, "%*s{}:\\n", indent, "");'.format(field.human_name))
633
print(" {}_print(fp, &values->{}, indent + 2);".format(pack_name, field.name))
634
elif field.type == "address":
635
# TODO resolve to name
636
print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
637
elif field.type in self.parser.enums:
638
print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {}_as_str({}));'.format(name, enum_name(field.type), val))
639
elif field.type == "int":
640
print(' fprintf(fp, "%*s{}: %d\\n", indent, "", {});'.format(name, val))
641
elif field.type == "bool":
642
print(' fprintf(fp, "%*s{}: %s\\n", indent, "", {} ? "true" : "false");'.format(name, val))
643
elif field.type == "float":
644
print(' fprintf(fp, "%*s{}: %f\\n", indent, "", {});'.format(name, val))
645
elif field.type == "uint" and (field.end - field.start) >= 32:
646
print(' fprintf(fp, "%*s{}: 0x%" PRIx64 "\\n", indent, "", {});'.format(name, val))
647
elif field.type == "uint/float":
648
print(' fprintf(fp, "%*s{}: 0x%X (%f)\\n", indent, "", {}, uif({}));'.format(name, val, val))
649
elif field.type == "Pixel Format":
650
print(' mali_pixel_format_print_v6(fp, {});'.format(val))
651
print(' mali_pixel_format_print_v7(fp, {});'.format(val))
652
else:
653
print(' fprintf(fp, "%*s{}: %u\\n", indent, "", {});'.format(name, val))
654
655
class Value(object):
656
def __init__(self, attrs):
657
self.name = attrs["name"]
658
self.value = int(attrs["value"], 0)
659
660
class Parser(object):
661
def __init__(self):
662
self.parser = xml.parsers.expat.ParserCreate()
663
self.parser.StartElementHandler = self.start_element
664
self.parser.EndElementHandler = self.end_element
665
666
self.struct = None
667
self.structs = {}
668
# Set of enum names we've seen.
669
self.enums = set()
670
self.aggregate = None
671
self.aggregates = {}
672
673
def gen_prefix(self, name):
674
return '{}_{}'.format(global_prefix.upper(), name)
675
676
def start_element(self, name, attrs):
677
if name == "panxml":
678
print(pack_header)
679
elif name == "struct":
680
name = attrs["name"]
681
self.no_direct_packing = attrs.get("no-direct-packing", False)
682
object_name = self.gen_prefix(safe_name(name.upper()))
683
self.struct = object_name
684
685
self.group = Group(self, None, 0, 1, name)
686
if "size" in attrs:
687
self.group.length = int(attrs["size"]) * 4
688
self.group.align = int(attrs["align"]) if "align" in attrs else None
689
self.structs[attrs["name"]] = self.group
690
elif name == "field":
691
self.group.fields.append(Field(self, attrs))
692
self.values = []
693
elif name == "enum":
694
self.values = []
695
self.enum = safe_name(attrs["name"])
696
self.enums.add(attrs["name"])
697
if "prefix" in attrs:
698
self.prefix = attrs["prefix"]
699
else:
700
self.prefix= None
701
elif name == "value":
702
self.values.append(Value(attrs))
703
elif name == "aggregate":
704
aggregate_name = self.gen_prefix(safe_name(attrs["name"].upper()))
705
self.aggregate = Aggregate(self, aggregate_name, attrs)
706
self.aggregates[attrs['name']] = self.aggregate
707
elif name == "section":
708
type_name = self.gen_prefix(safe_name(attrs["type"].upper()))
709
self.aggregate.add_section(type_name, attrs)
710
711
def end_element(self, name):
712
if name == "struct":
713
self.emit_struct()
714
self.struct = None
715
self.group = None
716
elif name == "field":
717
self.group.fields[-1].values = self.values
718
elif name == "enum":
719
self.emit_enum()
720
self.enum = None
721
elif name == "aggregate":
722
self.emit_aggregate()
723
self.aggregate = None
724
elif name == "panxml":
725
# Include at the end so it can depend on us but not the converse
726
print('#include "panfrost-job.h"')
727
print('#endif')
728
729
def emit_header(self, name):
730
default_fields = []
731
for field in self.group.fields:
732
if not type(field) is Field:
733
continue
734
if field.default is not None:
735
default_fields.append(" .{} = {}".format(field.name, field.default))
736
elif field.type in self.structs:
737
default_fields.append(" .{} = {{ {}_header }}".format(field.name, self.gen_prefix(safe_name(field.type.upper()))))
738
739
print('#define %-40s\\' % (name + '_header'))
740
if default_fields:
741
print(", \\\n".join(default_fields))
742
else:
743
print(' 0')
744
print('')
745
746
def emit_template_struct(self, name, group):
747
print("struct %s {" % name)
748
group.emit_template_struct("")
749
print("};\n")
750
751
def emit_aggregate(self):
752
aggregate = self.aggregate
753
print("struct %s_packed {" % aggregate.name.lower())
754
print(" uint32_t opaque[{}];".format(aggregate.get_size() // 4))
755
print("};\n")
756
print('#define {}_LENGTH {}'.format(aggregate.name.upper(), aggregate.size))
757
if aggregate.align != None:
758
print('#define {}_ALIGN {}'.format(aggregate.name.upper(), aggregate.align))
759
for section in aggregate.sections:
760
print('#define {}_SECTION_{}_TYPE struct {}'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
761
print('#define {}_SECTION_{}_header {}_header'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
762
print('#define {}_SECTION_{}_pack {}_pack'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
763
print('#define {}_SECTION_{}_unpack {}_unpack'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
764
print('#define {}_SECTION_{}_print {}_print'.format(aggregate.name.upper(), section.name.upper(), section.type_name))
765
print('#define {}_SECTION_{}_OFFSET {}'.format(aggregate.name.upper(), section.name.upper(), section.offset))
766
print("")
767
768
def emit_pack_function(self, name, group):
769
print("static inline void\n%s_pack(uint32_t * restrict cl,\n%sconst struct %s * restrict values)\n{" %
770
(name, ' ' * (len(name) + 6), name))
771
772
group.emit_pack_function()
773
774
print("}\n\n")
775
776
# Should be a whole number of words
777
assert((self.group.length % 4) == 0)
778
779
print('#define {} {}'.format (name + "_LENGTH", self.group.length))
780
if self.group.align != None:
781
print('#define {} {}'.format (name + "_ALIGN", self.group.align))
782
print('struct {}_packed {{ uint32_t opaque[{}]; }};'.format(name.lower(), self.group.length // 4))
783
784
def emit_unpack_function(self, name, group):
785
print("static inline void")
786
print("%s_unpack(const uint8_t * restrict cl,\n%sstruct %s * restrict values)\n{" %
787
(name.upper(), ' ' * (len(name) + 8), name))
788
789
group.emit_unpack_function()
790
791
print("}\n")
792
793
def emit_print_function(self, name, group):
794
print("static inline void")
795
print("{}_print(FILE *fp, const struct {} * values, unsigned indent)\n{{".format(name.upper(), name))
796
797
group.emit_print_function()
798
799
print("}\n")
800
801
def emit_struct(self):
802
name = self.struct
803
804
self.emit_template_struct(self.struct, self.group)
805
self.emit_header(name)
806
if self.no_direct_packing == False:
807
self.emit_pack_function(self.struct, self.group)
808
self.emit_unpack_function(self.struct, self.group)
809
self.emit_print_function(self.struct, self.group)
810
811
def enum_prefix(self, name):
812
return
813
814
def emit_enum(self):
815
e_name = enum_name(self.enum)
816
prefix = e_name if self.enum != 'Format' else global_prefix
817
print('enum {} {{'.format(e_name))
818
819
for value in self.values:
820
name = '{}_{}'.format(prefix, value.name)
821
name = safe_name(name).upper()
822
print(' % -36s = %6d,' % (name, value.value))
823
print('};\n')
824
825
print("static inline const char *")
826
print("{}_as_str(enum {} imm)\n{{".format(e_name.lower(), e_name))
827
print(" switch (imm) {")
828
for value in self.values:
829
name = '{}_{}'.format(prefix, value.name)
830
name = safe_name(name).upper()
831
print(' case {}: return "{}";'.format(name, value.name))
832
print(' default: return "XXX: INVALID";')
833
print(" }")
834
print("}\n")
835
836
def parse(self, filename):
837
file = open(filename, "rb")
838
self.parser.ParseFile(file)
839
file.close()
840
841
if len(sys.argv) < 2:
842
print("No input xml file specified")
843
sys.exit(1)
844
845
input_file = sys.argv[1]
846
847
p = Parser()
848
p.parse(input_file)
849
850