]>
Commit | Line | Data |
---|---|---|
568ae7ef RH |
1 | #!/usr/bin/env python |
2 | # Copyright (c) 2018 Linaro Limited | |
3 | # | |
4 | # This library is free software; you can redistribute it and/or | |
5 | # modify it under the terms of the GNU Lesser General Public | |
6 | # License as published by the Free Software Foundation; either | |
7 | # version 2 of the License, or (at your option) any later version. | |
8 | # | |
9 | # This library is distributed in the hope that it will be useful, | |
10 | # but WITHOUT ANY WARRANTY; without even the implied warranty of | |
11 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU | |
12 | # Lesser General Public License for more details. | |
13 | # | |
14 | # You should have received a copy of the GNU Lesser General Public | |
15 | # License along with this library; if not, see <http://www.gnu.org/licenses/>. | |
16 | # | |
17 | ||
18 | # | |
19 | # Generate a decoding tree from a specification file. | |
20 | # | |
21 | # The tree is built from instruction "patterns". A pattern may represent | |
22 | # a single architectural instruction or a group of same, depending on what | |
23 | # is convenient for further processing. | |
24 | # | |
25 | # Each pattern has "fixedbits" & "fixedmask", the combination of which | |
26 | # describes the condition under which the pattern is matched: | |
27 | # | |
28 | # (insn & fixedmask) == fixedbits | |
29 | # | |
30 | # Each pattern may have "fields", which are extracted from the insn and | |
31 | # passed along to the translator. Examples of such are registers, | |
32 | # immediates, and sub-opcodes. | |
33 | # | |
34 | # In support of patterns, one may declare fields, argument sets, and | |
35 | # formats, each of which may be re-used to simplify further definitions. | |
36 | # | |
37 | # *** Field syntax: | |
38 | # | |
39 | # field_def := '%' identifier ( unnamed_field )+ ( !function=identifier )? | |
40 | # unnamed_field := number ':' ( 's' ) number | |
41 | # | |
42 | # For unnamed_field, the first number is the least-significant bit position of | |
43 | # the field and the second number is the length of the field. If the 's' is | |
44 | # present, the field is considered signed. If multiple unnamed_fields are | |
45 | # present, they are concatenated. In this way one can define disjoint fields. | |
46 | # | |
47 | # If !function is specified, the concatenated result is passed through the | |
48 | # named function, taking and returning an integral value. | |
49 | # | |
50 | # FIXME: the fields of the structure into which this result will be stored | |
51 | # is restricted to "int". Which means that we cannot expand 64-bit items. | |
52 | # | |
53 | # Field examples: | |
54 | # | |
55 | # %disp 0:s16 -- sextract(i, 0, 16) | |
56 | # %imm9 16:6 10:3 -- extract(i, 16, 6) << 3 | extract(i, 10, 3) | |
57 | # %disp12 0:s1 1:1 2:10 -- sextract(i, 0, 1) << 11 | |
58 | # | extract(i, 1, 1) << 10 | |
59 | # | extract(i, 2, 10) | |
60 | # %shimm8 5:s8 13:1 !function=expand_shimm8 | |
61 | # -- expand_shimm8(sextract(i, 5, 8) << 1 | |
62 | # | extract(i, 13, 1)) | |
63 | # | |
64 | # *** Argument set syntax: | |
65 | # | |
abd04f92 | 66 | # args_def := '&' identifier ( args_elt )+ ( !extern )? |
568ae7ef RH |
67 | # args_elt := identifier |
68 | # | |
69 | # Each args_elt defines an argument within the argument set. | |
70 | # Each argument set will be rendered as a C structure "arg_$name" | |
71 | # with each of the fields being one of the member arguments. | |
72 | # | |
abd04f92 RH |
73 | # If !extern is specified, the backing structure is assumed to |
74 | # have been already declared, typically via a second decoder. | |
75 | # | |
568ae7ef RH |
76 | # Argument set examples: |
77 | # | |
78 | # ®3 ra rb rc | |
79 | # &loadstore reg base offset | |
80 | # | |
81 | # *** Format syntax: | |
82 | # | |
83 | # fmt_def := '@' identifier ( fmt_elt )+ | |
84 | # fmt_elt := fixedbit_elt | field_elt | field_ref | args_ref | |
85 | # fixedbit_elt := [01.-]+ | |
86 | # field_elt := identifier ':' 's'? number | |
87 | # field_ref := '%' identifier | identifier '=' '%' identifier | |
88 | # args_ref := '&' identifier | |
89 | # | |
90 | # Defining a format is a handy way to avoid replicating groups of fields | |
91 | # across many instruction patterns. | |
92 | # | |
93 | # A fixedbit_elt describes a contiguous sequence of bits that must | |
94 | # be 1, 0, [.-] for don't care. The difference between '.' and '-' | |
95 | # is that '.' means that the bit will be covered with a field or a | |
96 | # final [01] from the pattern, and '-' means that the bit is really | |
97 | # ignored by the cpu and will not be specified. | |
98 | # | |
99 | # A field_elt describes a simple field only given a width; the position of | |
100 | # the field is implied by its position with respect to other fixedbit_elt | |
101 | # and field_elt. | |
102 | # | |
103 | # If any fixedbit_elt or field_elt appear then all bits must be defined. | |
104 | # Padding with a fixedbit_elt of all '.' is an easy way to accomplish that. | |
105 | # | |
106 | # A field_ref incorporates a field by reference. This is the only way to | |
107 | # add a complex field to a format. A field may be renamed in the process | |
108 | # via assignment to another identifier. This is intended to allow the | |
109 | # same argument set be used with disjoint named fields. | |
110 | # | |
111 | # A single args_ref may specify an argument set to use for the format. | |
112 | # The set of fields in the format must be a subset of the arguments in | |
113 | # the argument set. If an argument set is not specified, one will be | |
114 | # inferred from the set of fields. | |
115 | # | |
116 | # It is recommended, but not required, that all field_ref and args_ref | |
117 | # appear at the end of the line, not interleaving with fixedbit_elf or | |
118 | # field_elt. | |
119 | # | |
120 | # Format examples: | |
121 | # | |
122 | # @opr ...... ra:5 rb:5 ... 0 ....... rc:5 | |
123 | # @opi ...... ra:5 lit:8 1 ....... rc:5 | |
124 | # | |
125 | # *** Pattern syntax: | |
126 | # | |
127 | # pat_def := identifier ( pat_elt )+ | |
128 | # pat_elt := fixedbit_elt | field_elt | field_ref | |
129 | # | args_ref | fmt_ref | const_elt | |
130 | # fmt_ref := '@' identifier | |
131 | # const_elt := identifier '=' number | |
132 | # | |
133 | # The fixedbit_elt and field_elt specifiers are unchanged from formats. | |
134 | # A pattern that does not specify a named format will have one inferred | |
135 | # from a referenced argument set (if present) and the set of fields. | |
136 | # | |
137 | # A const_elt allows a argument to be set to a constant value. This may | |
138 | # come in handy when fields overlap between patterns and one has to | |
139 | # include the values in the fixedbit_elt instead. | |
140 | # | |
141 | # The decoder will call a translator function for each pattern matched. | |
142 | # | |
143 | # Pattern examples: | |
144 | # | |
145 | # addl_r 010000 ..... ..... .... 0000000 ..... @opr | |
146 | # addl_i 010000 ..... ..... .... 0000000 ..... @opi | |
147 | # | |
148 | # which will, in part, invoke | |
149 | # | |
150 | # trans_addl_r(ctx, &arg_opr, insn) | |
151 | # and | |
152 | # trans_addl_i(ctx, &arg_opi, insn) | |
153 | # | |
154 | ||
568ae7ef RH |
155 | import os |
156 | import re | |
157 | import sys | |
158 | import getopt | |
568ae7ef RH |
159 | |
160 | insnwidth = 32 | |
161 | insnmask = 0xffffffff | |
162 | fields = {} | |
163 | arguments = {} | |
164 | formats = {} | |
165 | patterns = [] | |
166 | ||
167 | translate_prefix = 'trans' | |
168 | translate_scope = 'static ' | |
169 | input_file = '' | |
170 | output_file = None | |
171 | output_fd = None | |
172 | insntype = 'uint32_t' | |
abd04f92 | 173 | decode_function = 'decode' |
568ae7ef RH |
174 | |
175 | re_ident = '[a-zA-Z][a-zA-Z0-9_]*' | |
176 | ||
177 | ||
178 | def error(lineno, *args): | |
179 | """Print an error message from file:line and args and exit.""" | |
180 | global output_file | |
181 | global output_fd | |
182 | ||
183 | if lineno: | |
184 | r = '{0}:{1}: error:'.format(input_file, lineno) | |
185 | elif input_file: | |
186 | r = '{0}: error:'.format(input_file) | |
187 | else: | |
188 | r = 'error:' | |
189 | for a in args: | |
190 | r += ' ' + str(a) | |
191 | r += '\n' | |
192 | sys.stderr.write(r) | |
193 | if output_file and output_fd: | |
194 | output_fd.close() | |
195 | os.remove(output_file) | |
196 | exit(1) | |
197 | ||
198 | ||
199 | def output(*args): | |
200 | global output_fd | |
201 | for a in args: | |
202 | output_fd.write(a) | |
203 | ||
204 | ||
205 | if sys.version_info >= (3, 0): | |
206 | re_fullmatch = re.fullmatch | |
207 | else: | |
208 | def re_fullmatch(pat, str): | |
209 | return re.match('^' + pat + '$', str) | |
210 | ||
211 | ||
212 | def output_autogen(): | |
213 | output('/* This file is autogenerated by scripts/decodetree.py. */\n\n') | |
214 | ||
215 | ||
216 | def str_indent(c): | |
217 | """Return a string with C spaces""" | |
218 | return ' ' * c | |
219 | ||
220 | ||
221 | def str_fields(fields): | |
222 | """Return a string uniquely identifing FIELDS""" | |
223 | r = '' | |
224 | for n in sorted(fields.keys()): | |
225 | r += '_' + n | |
226 | return r[1:] | |
227 | ||
228 | ||
229 | def str_match_bits(bits, mask): | |
230 | """Return a string pretty-printing BITS/MASK""" | |
231 | global insnwidth | |
232 | ||
233 | i = 1 << (insnwidth - 1) | |
234 | space = 0x01010100 | |
235 | r = '' | |
236 | while i != 0: | |
237 | if i & mask: | |
238 | if i & bits: | |
239 | r += '1' | |
240 | else: | |
241 | r += '0' | |
242 | else: | |
243 | r += '.' | |
244 | if i & space: | |
245 | r += ' ' | |
246 | i >>= 1 | |
247 | return r | |
248 | ||
249 | ||
250 | def is_pow2(x): | |
251 | """Return true iff X is equal to a power of 2.""" | |
252 | return (x & (x - 1)) == 0 | |
253 | ||
254 | ||
255 | def ctz(x): | |
256 | """Return the number of times 2 factors into X.""" | |
257 | r = 0 | |
258 | while ((x >> r) & 1) == 0: | |
259 | r += 1 | |
260 | return r | |
261 | ||
262 | ||
263 | def is_contiguous(bits): | |
264 | shift = ctz(bits) | |
265 | if is_pow2((bits >> shift) + 1): | |
266 | return shift | |
267 | else: | |
268 | return -1 | |
269 | ||
270 | ||
271 | def eq_fields_for_args(flds_a, flds_b): | |
272 | if len(flds_a) != len(flds_b): | |
273 | return False | |
274 | for k, a in flds_a.items(): | |
275 | if k not in flds_b: | |
276 | return False | |
277 | return True | |
278 | ||
279 | ||
280 | def eq_fields_for_fmts(flds_a, flds_b): | |
281 | if len(flds_a) != len(flds_b): | |
282 | return False | |
283 | for k, a in flds_a.items(): | |
284 | if k not in flds_b: | |
285 | return False | |
286 | b = flds_b[k] | |
287 | if a.__class__ != b.__class__ or a != b: | |
288 | return False | |
289 | return True | |
290 | ||
291 | ||
292 | class Field: | |
293 | """Class representing a simple instruction field""" | |
294 | def __init__(self, sign, pos, len): | |
295 | self.sign = sign | |
296 | self.pos = pos | |
297 | self.len = len | |
298 | self.mask = ((1 << len) - 1) << pos | |
299 | ||
300 | def __str__(self): | |
301 | if self.sign: | |
302 | s = 's' | |
303 | else: | |
304 | s = '' | |
305 | return str(pos) + ':' + s + str(len) | |
306 | ||
307 | def str_extract(self): | |
308 | if self.sign: | |
309 | extr = 'sextract32' | |
310 | else: | |
311 | extr = 'extract32' | |
312 | return '{0}(insn, {1}, {2})'.format(extr, self.pos, self.len) | |
313 | ||
314 | def __eq__(self, other): | |
315 | return self.sign == other.sign and self.sign == other.sign | |
316 | ||
317 | def __ne__(self, other): | |
318 | return not self.__eq__(other) | |
319 | # end Field | |
320 | ||
321 | ||
322 | class MultiField: | |
323 | """Class representing a compound instruction field""" | |
324 | def __init__(self, subs, mask): | |
325 | self.subs = subs | |
326 | self.sign = subs[0].sign | |
327 | self.mask = mask | |
328 | ||
329 | def __str__(self): | |
330 | return str(self.subs) | |
331 | ||
332 | def str_extract(self): | |
333 | ret = '0' | |
334 | pos = 0 | |
335 | for f in reversed(self.subs): | |
336 | if pos == 0: | |
337 | ret = f.str_extract() | |
338 | else: | |
339 | ret = 'deposit32({0}, {1}, {2}, {3})' \ | |
340 | .format(ret, pos, 32 - pos, f.str_extract()) | |
341 | pos += f.len | |
342 | return ret | |
343 | ||
344 | def __ne__(self, other): | |
345 | if len(self.subs) != len(other.subs): | |
346 | return True | |
347 | for a, b in zip(self.subs, other.subs): | |
348 | if a.__class__ != b.__class__ or a != b: | |
349 | return True | |
350 | return False | |
351 | ||
352 | def __eq__(self, other): | |
353 | return not self.__ne__(other) | |
354 | # end MultiField | |
355 | ||
356 | ||
357 | class ConstField: | |
358 | """Class representing an argument field with constant value""" | |
359 | def __init__(self, value): | |
360 | self.value = value | |
361 | self.mask = 0 | |
362 | self.sign = value < 0 | |
363 | ||
364 | def __str__(self): | |
365 | return str(self.value) | |
366 | ||
367 | def str_extract(self): | |
368 | return str(self.value) | |
369 | ||
370 | def __cmp__(self, other): | |
371 | return self.value - other.value | |
372 | # end ConstField | |
373 | ||
374 | ||
375 | class FunctionField: | |
376 | """Class representing a field passed through an expander""" | |
377 | def __init__(self, func, base): | |
378 | self.mask = base.mask | |
379 | self.sign = base.sign | |
380 | self.base = base | |
381 | self.func = func | |
382 | ||
383 | def __str__(self): | |
384 | return self.func + '(' + str(self.base) + ')' | |
385 | ||
386 | def str_extract(self): | |
387 | return self.func + '(' + self.base.str_extract() + ')' | |
388 | ||
389 | def __eq__(self, other): | |
390 | return self.func == other.func and self.base == other.base | |
391 | ||
392 | def __ne__(self, other): | |
393 | return not self.__eq__(other) | |
394 | # end FunctionField | |
395 | ||
396 | ||
397 | class Arguments: | |
398 | """Class representing the extracted fields of a format""" | |
abd04f92 | 399 | def __init__(self, nm, flds, extern): |
568ae7ef | 400 | self.name = nm |
abd04f92 | 401 | self.extern = extern |
568ae7ef RH |
402 | self.fields = sorted(flds) |
403 | ||
404 | def __str__(self): | |
405 | return self.name + ' ' + str(self.fields) | |
406 | ||
407 | def struct_name(self): | |
408 | return 'arg_' + self.name | |
409 | ||
410 | def output_def(self): | |
abd04f92 RH |
411 | if not self.extern: |
412 | output('typedef struct {\n') | |
413 | for n in self.fields: | |
414 | output(' int ', n, ';\n') | |
415 | output('} ', self.struct_name(), ';\n\n') | |
568ae7ef RH |
416 | # end Arguments |
417 | ||
418 | ||
419 | class General: | |
420 | """Common code between instruction formats and instruction patterns""" | |
421 | def __init__(self, name, lineno, base, fixb, fixm, udfm, fldm, flds): | |
422 | self.name = name | |
423 | self.lineno = lineno | |
424 | self.base = base | |
425 | self.fixedbits = fixb | |
426 | self.fixedmask = fixm | |
427 | self.undefmask = udfm | |
428 | self.fieldmask = fldm | |
429 | self.fields = flds | |
430 | ||
431 | def __str__(self): | |
432 | r = self.name | |
433 | if self.base: | |
434 | r = r + ' ' + self.base.name | |
435 | else: | |
436 | r = r + ' ' + str(self.fields) | |
437 | r = r + ' ' + str_match_bits(self.fixedbits, self.fixedmask) | |
438 | return r | |
439 | ||
440 | def str1(self, i): | |
441 | return str_indent(i) + self.__str__() | |
442 | # end General | |
443 | ||
444 | ||
445 | class Format(General): | |
446 | """Class representing an instruction format""" | |
447 | ||
448 | def extract_name(self): | |
449 | return 'extract_' + self.name | |
450 | ||
451 | def output_extract(self): | |
452 | output('static void ', self.extract_name(), '(', | |
453 | self.base.struct_name(), ' *a, ', insntype, ' insn)\n{\n') | |
454 | for n, f in self.fields.items(): | |
455 | output(' a->', n, ' = ', f.str_extract(), ';\n') | |
456 | output('}\n\n') | |
457 | # end Format | |
458 | ||
459 | ||
460 | class Pattern(General): | |
461 | """Class representing an instruction pattern""" | |
462 | ||
463 | def output_decl(self): | |
464 | global translate_scope | |
465 | global translate_prefix | |
466 | output('typedef ', self.base.base.struct_name(), | |
467 | ' arg_', self.name, ';\n') | |
76805598 | 468 | output(translate_scope, 'bool ', translate_prefix, '_', self.name, |
3a7be554 | 469 | '(DisasContext *ctx, arg_', self.name, ' *a);\n') |
568ae7ef RH |
470 | |
471 | def output_code(self, i, extracted, outerbits, outermask): | |
472 | global translate_prefix | |
473 | ind = str_indent(i) | |
474 | arg = self.base.base.name | |
475 | output(ind, '/* line ', str(self.lineno), ' */\n') | |
476 | if not extracted: | |
477 | output(ind, self.base.extract_name(), '(&u.f_', arg, ', insn);\n') | |
478 | for n, f in self.fields.items(): | |
479 | output(ind, 'u.f_', arg, '.', n, ' = ', f.str_extract(), ';\n') | |
76805598 | 480 | output(ind, 'return ', translate_prefix, '_', self.name, |
3a7be554 | 481 | '(ctx, &u.f_', arg, ');\n') |
568ae7ef RH |
482 | # end Pattern |
483 | ||
484 | ||
485 | def parse_field(lineno, name, toks): | |
486 | """Parse one instruction field from TOKS at LINENO""" | |
487 | global fields | |
488 | global re_ident | |
489 | global insnwidth | |
490 | ||
491 | # A "simple" field will have only one entry; | |
492 | # a "multifield" will have several. | |
493 | subs = [] | |
494 | width = 0 | |
495 | func = None | |
496 | for t in toks: | |
497 | if re_fullmatch('!function=' + re_ident, t): | |
498 | if func: | |
499 | error(lineno, 'duplicate function') | |
500 | func = t.split('=') | |
501 | func = func[1] | |
502 | continue | |
503 | ||
504 | if re_fullmatch('[0-9]+:s[0-9]+', t): | |
505 | # Signed field extract | |
506 | subtoks = t.split(':s') | |
507 | sign = True | |
508 | elif re_fullmatch('[0-9]+:[0-9]+', t): | |
509 | # Unsigned field extract | |
510 | subtoks = t.split(':') | |
511 | sign = False | |
512 | else: | |
513 | error(lineno, 'invalid field token "{0}"'.format(t)) | |
514 | po = int(subtoks[0]) | |
515 | le = int(subtoks[1]) | |
516 | if po + le > insnwidth: | |
517 | error(lineno, 'field {0} too large'.format(t)) | |
518 | f = Field(sign, po, le) | |
519 | subs.append(f) | |
520 | width += le | |
521 | ||
522 | if width > insnwidth: | |
523 | error(lineno, 'field too large') | |
524 | if len(subs) == 1: | |
525 | f = subs[0] | |
526 | else: | |
527 | mask = 0 | |
528 | for s in subs: | |
529 | if mask & s.mask: | |
530 | error(lineno, 'field components overlap') | |
531 | mask |= s.mask | |
532 | f = MultiField(subs, mask) | |
533 | if func: | |
534 | f = FunctionField(func, f) | |
535 | ||
536 | if name in fields: | |
537 | error(lineno, 'duplicate field', name) | |
538 | fields[name] = f | |
539 | # end parse_field | |
540 | ||
541 | ||
542 | def parse_arguments(lineno, name, toks): | |
543 | """Parse one argument set from TOKS at LINENO""" | |
544 | global arguments | |
545 | global re_ident | |
546 | ||
547 | flds = [] | |
abd04f92 | 548 | extern = False |
568ae7ef | 549 | for t in toks: |
abd04f92 RH |
550 | if re_fullmatch('!extern', t): |
551 | extern = True | |
552 | continue | |
568ae7ef RH |
553 | if not re_fullmatch(re_ident, t): |
554 | error(lineno, 'invalid argument set token "{0}"'.format(t)) | |
555 | if t in flds: | |
556 | error(lineno, 'duplicate argument "{0}"'.format(t)) | |
557 | flds.append(t) | |
558 | ||
559 | if name in arguments: | |
560 | error(lineno, 'duplicate argument set', name) | |
abd04f92 | 561 | arguments[name] = Arguments(name, flds, extern) |
568ae7ef RH |
562 | # end parse_arguments |
563 | ||
564 | ||
565 | def lookup_field(lineno, name): | |
566 | global fields | |
567 | if name in fields: | |
568 | return fields[name] | |
569 | error(lineno, 'undefined field', name) | |
570 | ||
571 | ||
572 | def add_field(lineno, flds, new_name, f): | |
573 | if new_name in flds: | |
574 | error(lineno, 'duplicate field', new_name) | |
575 | flds[new_name] = f | |
576 | return flds | |
577 | ||
578 | ||
579 | def add_field_byname(lineno, flds, new_name, old_name): | |
580 | return add_field(lineno, flds, new_name, lookup_field(lineno, old_name)) | |
581 | ||
582 | ||
583 | def infer_argument_set(flds): | |
584 | global arguments | |
abd04f92 | 585 | global decode_function |
568ae7ef RH |
586 | |
587 | for arg in arguments.values(): | |
588 | if eq_fields_for_args(flds, arg.fields): | |
589 | return arg | |
590 | ||
abd04f92 RH |
591 | name = decode_function + str(len(arguments)) |
592 | arg = Arguments(name, flds.keys(), False) | |
568ae7ef RH |
593 | arguments[name] = arg |
594 | return arg | |
595 | ||
596 | ||
597 | def infer_format(arg, fieldmask, flds): | |
598 | global arguments | |
599 | global formats | |
abd04f92 | 600 | global decode_function |
568ae7ef RH |
601 | |
602 | const_flds = {} | |
603 | var_flds = {} | |
604 | for n, c in flds.items(): | |
605 | if c is ConstField: | |
606 | const_flds[n] = c | |
607 | else: | |
608 | var_flds[n] = c | |
609 | ||
610 | # Look for an existing format with the same argument set and fields | |
611 | for fmt in formats.values(): | |
612 | if arg and fmt.base != arg: | |
613 | continue | |
614 | if fieldmask != fmt.fieldmask: | |
615 | continue | |
616 | if not eq_fields_for_fmts(flds, fmt.fields): | |
617 | continue | |
618 | return (fmt, const_flds) | |
619 | ||
abd04f92 | 620 | name = decode_function + '_Fmt_' + str(len(formats)) |
568ae7ef RH |
621 | if not arg: |
622 | arg = infer_argument_set(flds) | |
623 | ||
624 | fmt = Format(name, 0, arg, 0, 0, 0, fieldmask, var_flds) | |
625 | formats[name] = fmt | |
626 | ||
627 | return (fmt, const_flds) | |
628 | # end infer_format | |
629 | ||
630 | ||
631 | def parse_generic(lineno, is_format, name, toks): | |
632 | """Parse one instruction format from TOKS at LINENO""" | |
633 | global fields | |
634 | global arguments | |
635 | global formats | |
636 | global patterns | |
637 | global re_ident | |
638 | global insnwidth | |
639 | global insnmask | |
640 | ||
641 | fixedmask = 0 | |
642 | fixedbits = 0 | |
643 | undefmask = 0 | |
644 | width = 0 | |
645 | flds = {} | |
646 | arg = None | |
647 | fmt = None | |
648 | for t in toks: | |
649 | # '&Foo' gives a format an explcit argument set. | |
650 | if t[0] == '&': | |
651 | tt = t[1:] | |
652 | if arg: | |
653 | error(lineno, 'multiple argument sets') | |
654 | if tt in arguments: | |
655 | arg = arguments[tt] | |
656 | else: | |
657 | error(lineno, 'undefined argument set', t) | |
658 | continue | |
659 | ||
660 | # '@Foo' gives a pattern an explicit format. | |
661 | if t[0] == '@': | |
662 | tt = t[1:] | |
663 | if fmt: | |
664 | error(lineno, 'multiple formats') | |
665 | if tt in formats: | |
666 | fmt = formats[tt] | |
667 | else: | |
668 | error(lineno, 'undefined format', t) | |
669 | continue | |
670 | ||
671 | # '%Foo' imports a field. | |
672 | if t[0] == '%': | |
673 | tt = t[1:] | |
674 | flds = add_field_byname(lineno, flds, tt, tt) | |
675 | continue | |
676 | ||
677 | # 'Foo=%Bar' imports a field with a different name. | |
678 | if re_fullmatch(re_ident + '=%' + re_ident, t): | |
679 | (fname, iname) = t.split('=%') | |
680 | flds = add_field_byname(lineno, flds, fname, iname) | |
681 | continue | |
682 | ||
683 | # 'Foo=number' sets an argument field to a constant value | |
684 | if re_fullmatch(re_ident + '=[0-9]+', t): | |
685 | (fname, value) = t.split('=') | |
686 | value = int(value) | |
687 | flds = add_field(lineno, flds, fname, ConstField(value)) | |
688 | continue | |
689 | ||
690 | # Pattern of 0s, 1s, dots and dashes indicate required zeros, | |
691 | # required ones, or dont-cares. | |
692 | if re_fullmatch('[01.-]+', t): | |
693 | shift = len(t) | |
694 | fms = t.replace('0', '1') | |
695 | fms = fms.replace('.', '0') | |
696 | fms = fms.replace('-', '0') | |
697 | fbs = t.replace('.', '0') | |
698 | fbs = fbs.replace('-', '0') | |
699 | ubm = t.replace('1', '0') | |
700 | ubm = ubm.replace('.', '0') | |
701 | ubm = ubm.replace('-', '1') | |
702 | fms = int(fms, 2) | |
703 | fbs = int(fbs, 2) | |
704 | ubm = int(ubm, 2) | |
705 | fixedbits = (fixedbits << shift) | fbs | |
706 | fixedmask = (fixedmask << shift) | fms | |
707 | undefmask = (undefmask << shift) | ubm | |
708 | # Otherwise, fieldname:fieldwidth | |
709 | elif re_fullmatch(re_ident + ':s?[0-9]+', t): | |
710 | (fname, flen) = t.split(':') | |
711 | sign = False | |
712 | if flen[0] == 's': | |
713 | sign = True | |
714 | flen = flen[1:] | |
715 | shift = int(flen, 10) | |
716 | f = Field(sign, insnwidth - width - shift, shift) | |
717 | flds = add_field(lineno, flds, fname, f) | |
718 | fixedbits <<= shift | |
719 | fixedmask <<= shift | |
720 | undefmask <<= shift | |
721 | else: | |
722 | error(lineno, 'invalid token "{0}"'.format(t)) | |
723 | width += shift | |
724 | ||
725 | # We should have filled in all of the bits of the instruction. | |
726 | if not (is_format and width == 0) and width != insnwidth: | |
727 | error(lineno, 'definition has {0} bits'.format(width)) | |
728 | ||
729 | # Do not check for fields overlaping fields; one valid usage | |
730 | # is to be able to duplicate fields via import. | |
731 | fieldmask = 0 | |
732 | for f in flds.values(): | |
733 | fieldmask |= f.mask | |
734 | ||
735 | # Fix up what we've parsed to match either a format or a pattern. | |
736 | if is_format: | |
737 | # Formats cannot reference formats. | |
738 | if fmt: | |
739 | error(lineno, 'format referencing format') | |
740 | # If an argument set is given, then there should be no fields | |
741 | # without a place to store it. | |
742 | if arg: | |
743 | for f in flds.keys(): | |
744 | if f not in arg.fields: | |
745 | error(lineno, 'field {0} not in argument set {1}' | |
746 | .format(f, arg.name)) | |
747 | else: | |
748 | arg = infer_argument_set(flds) | |
749 | if name in formats: | |
750 | error(lineno, 'duplicate format name', name) | |
751 | fmt = Format(name, lineno, arg, fixedbits, fixedmask, | |
752 | undefmask, fieldmask, flds) | |
753 | formats[name] = fmt | |
754 | else: | |
755 | # Patterns can reference a format ... | |
756 | if fmt: | |
757 | # ... but not an argument simultaneously | |
758 | if arg: | |
759 | error(lineno, 'pattern specifies both format and argument set') | |
760 | if fixedmask & fmt.fixedmask: | |
761 | error(lineno, 'pattern fixed bits overlap format fixed bits') | |
762 | fieldmask |= fmt.fieldmask | |
763 | fixedbits |= fmt.fixedbits | |
764 | fixedmask |= fmt.fixedmask | |
765 | undefmask |= fmt.undefmask | |
766 | else: | |
767 | (fmt, flds) = infer_format(arg, fieldmask, flds) | |
768 | arg = fmt.base | |
769 | for f in flds.keys(): | |
770 | if f not in arg.fields: | |
771 | error(lineno, 'field {0} not in argument set {1}' | |
772 | .format(f, arg.name)) | |
773 | if f in fmt.fields.keys(): | |
774 | error(lineno, 'field {0} set by format and pattern'.format(f)) | |
775 | for f in arg.fields: | |
776 | if f not in flds.keys() and f not in fmt.fields.keys(): | |
777 | error(lineno, 'field {0} not initialized'.format(f)) | |
778 | pat = Pattern(name, lineno, fmt, fixedbits, fixedmask, | |
779 | undefmask, fieldmask, flds) | |
780 | patterns.append(pat) | |
781 | ||
782 | # Validate the masks that we have assembled. | |
783 | if fieldmask & fixedmask: | |
784 | error(lineno, 'fieldmask overlaps fixedmask (0x{0:08x} & 0x{1:08x})' | |
785 | .format(fieldmask, fixedmask)) | |
786 | if fieldmask & undefmask: | |
787 | error(lineno, 'fieldmask overlaps undefmask (0x{0:08x} & 0x{1:08x})' | |
788 | .format(fieldmask, undefmask)) | |
789 | if fixedmask & undefmask: | |
790 | error(lineno, 'fixedmask overlaps undefmask (0x{0:08x} & 0x{1:08x})' | |
791 | .format(fixedmask, undefmask)) | |
792 | if not is_format: | |
793 | allbits = fieldmask | fixedmask | undefmask | |
794 | if allbits != insnmask: | |
795 | error(lineno, 'bits left unspecified (0x{0:08x})' | |
796 | .format(allbits ^ insnmask)) | |
797 | # end parse_general | |
798 | ||
799 | ||
800 | def parse_file(f): | |
801 | """Parse all of the patterns within a file""" | |
802 | ||
803 | # Read all of the lines of the file. Concatenate lines | |
804 | # ending in backslash; discard empty lines and comments. | |
805 | toks = [] | |
806 | lineno = 0 | |
807 | for line in f: | |
808 | lineno += 1 | |
809 | ||
810 | # Discard comments | |
811 | end = line.find('#') | |
812 | if end >= 0: | |
813 | line = line[:end] | |
814 | ||
815 | t = line.split() | |
816 | if len(toks) != 0: | |
817 | # Next line after continuation | |
818 | toks.extend(t) | |
819 | elif len(t) == 0: | |
820 | # Empty line | |
821 | continue | |
822 | else: | |
823 | toks = t | |
824 | ||
825 | # Continuation? | |
826 | if toks[-1] == '\\': | |
827 | toks.pop() | |
828 | continue | |
829 | ||
830 | if len(toks) < 2: | |
831 | error(lineno, 'short line') | |
832 | ||
833 | name = toks[0] | |
834 | del toks[0] | |
835 | ||
836 | # Determine the type of object needing to be parsed. | |
837 | if name[0] == '%': | |
838 | parse_field(lineno, name[1:], toks) | |
839 | elif name[0] == '&': | |
840 | parse_arguments(lineno, name[1:], toks) | |
841 | elif name[0] == '@': | |
842 | parse_generic(lineno, True, name[1:], toks) | |
843 | else: | |
844 | parse_generic(lineno, False, name, toks) | |
845 | toks = [] | |
846 | # end parse_file | |
847 | ||
848 | ||
849 | class Tree: | |
850 | """Class representing a node in a decode tree""" | |
851 | ||
852 | def __init__(self, fm, tm): | |
853 | self.fixedmask = fm | |
854 | self.thismask = tm | |
855 | self.subs = [] | |
856 | self.base = None | |
857 | ||
858 | def str1(self, i): | |
859 | ind = str_indent(i) | |
860 | r = '{0}{1:08x}'.format(ind, self.fixedmask) | |
861 | if self.format: | |
862 | r += ' ' + self.format.name | |
863 | r += ' [\n' | |
864 | for (b, s) in self.subs: | |
865 | r += '{0} {1:08x}:\n'.format(ind, b) | |
866 | r += s.str1(i + 4) + '\n' | |
867 | r += ind + ']' | |
868 | return r | |
869 | ||
870 | def __str__(self): | |
871 | return self.str1(0) | |
872 | ||
873 | def output_code(self, i, extracted, outerbits, outermask): | |
874 | ind = str_indent(i) | |
875 | ||
876 | # If we identified all nodes below have the same format, | |
877 | # extract the fields now. | |
878 | if not extracted and self.base: | |
879 | output(ind, self.base.extract_name(), | |
880 | '(&u.f_', self.base.base.name, ', insn);\n') | |
881 | extracted = True | |
882 | ||
883 | # Attempt to aid the compiler in producing compact switch statements. | |
884 | # If the bits in the mask are contiguous, extract them. | |
885 | sh = is_contiguous(self.thismask) | |
886 | if sh > 0: | |
887 | # Propagate SH down into the local functions. | |
888 | def str_switch(b, sh=sh): | |
889 | return '(insn >> {0}) & 0x{1:x}'.format(sh, b >> sh) | |
890 | ||
891 | def str_case(b, sh=sh): | |
892 | return '0x{0:x}'.format(b >> sh) | |
893 | else: | |
894 | def str_switch(b): | |
895 | return 'insn & 0x{0:08x}'.format(b) | |
896 | ||
897 | def str_case(b): | |
898 | return '0x{0:08x}'.format(b) | |
899 | ||
900 | output(ind, 'switch (', str_switch(self.thismask), ') {\n') | |
901 | for b, s in sorted(self.subs): | |
902 | assert (self.thismask & ~s.fixedmask) == 0 | |
903 | innermask = outermask | self.thismask | |
904 | innerbits = outerbits | b | |
905 | output(ind, 'case ', str_case(b), ':\n') | |
906 | output(ind, ' /* ', | |
907 | str_match_bits(innerbits, innermask), ' */\n') | |
908 | s.output_code(i + 4, extracted, innerbits, innermask) | |
909 | output(ind, '}\n') | |
910 | output(ind, 'return false;\n') | |
911 | # end Tree | |
912 | ||
913 | ||
914 | def build_tree(pats, outerbits, outermask): | |
915 | # Find the intersection of all remaining fixedmask. | |
916 | innermask = ~outermask | |
917 | for i in pats: | |
918 | innermask &= i.fixedmask | |
919 | ||
920 | if innermask == 0: | |
921 | pnames = [] | |
922 | for p in pats: | |
923 | pnames.append(p.name + ':' + str(p.lineno)) | |
924 | error(pats[0].lineno, 'overlapping patterns:', pnames) | |
925 | ||
926 | fullmask = outermask | innermask | |
927 | ||
928 | # Sort each element of pats into the bin selected by the mask. | |
929 | bins = {} | |
930 | for i in pats: | |
931 | fb = i.fixedbits & innermask | |
932 | if fb in bins: | |
933 | bins[fb].append(i) | |
934 | else: | |
935 | bins[fb] = [i] | |
936 | ||
937 | # We must recurse if any bin has more than one element or if | |
938 | # the single element in the bin has not been fully matched. | |
939 | t = Tree(fullmask, innermask) | |
940 | ||
941 | for b, l in bins.items(): | |
942 | s = l[0] | |
943 | if len(l) > 1 or s.fixedmask & ~fullmask != 0: | |
944 | s = build_tree(l, b | outerbits, fullmask) | |
945 | t.subs.append((b, s)) | |
946 | ||
947 | return t | |
948 | # end build_tree | |
949 | ||
950 | ||
951 | def prop_format(tree): | |
952 | """Propagate Format objects into the decode tree""" | |
953 | ||
954 | # Depth first search. | |
955 | for (b, s) in tree.subs: | |
956 | if isinstance(s, Tree): | |
957 | prop_format(s) | |
958 | ||
959 | # If all entries in SUBS have the same format, then | |
960 | # propagate that into the tree. | |
961 | f = None | |
962 | for (b, s) in tree.subs: | |
963 | if f is None: | |
964 | f = s.base | |
965 | if f is None: | |
966 | return | |
967 | if f is not s.base: | |
968 | return | |
969 | tree.base = f | |
970 | # end prop_format | |
971 | ||
972 | ||
973 | def main(): | |
974 | global arguments | |
975 | global formats | |
976 | global patterns | |
977 | global translate_scope | |
978 | global translate_prefix | |
979 | global output_fd | |
980 | global output_file | |
981 | global input_file | |
982 | global insnwidth | |
983 | global insntype | |
83d7c40c | 984 | global insnmask |
abd04f92 | 985 | global decode_function |
568ae7ef | 986 | |
568ae7ef RH |
987 | decode_scope = 'static ' |
988 | ||
989 | long_opts = ['decode=', 'translate=', 'output=', 'insnwidth='] | |
990 | try: | |
991 | (opts, args) = getopt.getopt(sys.argv[1:], 'o:w:', long_opts) | |
992 | except getopt.GetoptError as err: | |
993 | error(0, err) | |
994 | for o, a in opts: | |
995 | if o in ('-o', '--output'): | |
996 | output_file = a | |
997 | elif o == '--decode': | |
998 | decode_function = a | |
999 | decode_scope = '' | |
1000 | elif o == '--translate': | |
1001 | translate_prefix = a | |
1002 | translate_scope = '' | |
1003 | elif o in ('-w', '--insnwidth'): | |
1004 | insnwidth = int(a) | |
1005 | if insnwidth == 16: | |
1006 | insntype = 'uint16_t' | |
1007 | insnmask = 0xffff | |
1008 | elif insnwidth != 32: | |
1009 | error(0, 'cannot handle insns of width', insnwidth) | |
1010 | else: | |
1011 | assert False, 'unhandled option' | |
1012 | ||
1013 | if len(args) < 1: | |
1014 | error(0, 'missing input file') | |
1015 | input_file = args[0] | |
1016 | f = open(input_file, 'r') | |
1017 | parse_file(f) | |
1018 | f.close() | |
1019 | ||
1020 | t = build_tree(patterns, 0, 0) | |
1021 | prop_format(t) | |
1022 | ||
1023 | if output_file: | |
1024 | output_fd = open(output_file, 'w') | |
1025 | else: | |
1026 | output_fd = sys.stdout | |
1027 | ||
1028 | output_autogen() | |
1029 | for n in sorted(arguments.keys()): | |
1030 | f = arguments[n] | |
1031 | f.output_def() | |
1032 | ||
1033 | # A single translate function can be invoked for different patterns. | |
1034 | # Make sure that the argument sets are the same, and declare the | |
1035 | # function only once. | |
1036 | out_pats = {} | |
1037 | for i in patterns: | |
1038 | if i.name in out_pats: | |
1039 | p = out_pats[i.name] | |
1040 | if i.base.base != p.base.base: | |
1041 | error(0, i.name, ' has conflicting argument sets') | |
1042 | else: | |
1043 | i.output_decl() | |
1044 | out_pats[i.name] = i | |
1045 | output('\n') | |
1046 | ||
1047 | for n in sorted(formats.keys()): | |
1048 | f = formats[n] | |
1049 | f.output_extract() | |
1050 | ||
1051 | output(decode_scope, 'bool ', decode_function, | |
1052 | '(DisasContext *ctx, ', insntype, ' insn)\n{\n') | |
1053 | ||
1054 | i4 = str_indent(4) | |
1055 | output(i4, 'union {\n') | |
1056 | for n in sorted(arguments.keys()): | |
1057 | f = arguments[n] | |
1058 | output(i4, i4, f.struct_name(), ' f_', f.name, ';\n') | |
1059 | output(i4, '} u;\n\n') | |
1060 | ||
1061 | t.output_code(4, False, 0, 0) | |
1062 | ||
1063 | output('}\n') | |
1064 | ||
1065 | if output_file: | |
1066 | output_fd.close() | |
1067 | # end main | |
1068 | ||
1069 | ||
1070 | if __name__ == '__main__': | |
1071 | main() |