]>
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, |
568ae7ef RH |
469 | '(DisasContext *ctx, arg_', self.name, |
470 | ' *a, ', insntype, ' insn);\n') | |
471 | ||
472 | def output_code(self, i, extracted, outerbits, outermask): | |
473 | global translate_prefix | |
474 | ind = str_indent(i) | |
475 | arg = self.base.base.name | |
476 | output(ind, '/* line ', str(self.lineno), ' */\n') | |
477 | if not extracted: | |
478 | output(ind, self.base.extract_name(), '(&u.f_', arg, ', insn);\n') | |
479 | for n, f in self.fields.items(): | |
480 | output(ind, 'u.f_', arg, '.', n, ' = ', f.str_extract(), ';\n') | |
76805598 | 481 | output(ind, 'return ', translate_prefix, '_', self.name, |
568ae7ef | 482 | '(ctx, &u.f_', arg, ', insn);\n') |
568ae7ef RH |
483 | # end Pattern |
484 | ||
485 | ||
486 | def parse_field(lineno, name, toks): | |
487 | """Parse one instruction field from TOKS at LINENO""" | |
488 | global fields | |
489 | global re_ident | |
490 | global insnwidth | |
491 | ||
492 | # A "simple" field will have only one entry; | |
493 | # a "multifield" will have several. | |
494 | subs = [] | |
495 | width = 0 | |
496 | func = None | |
497 | for t in toks: | |
498 | if re_fullmatch('!function=' + re_ident, t): | |
499 | if func: | |
500 | error(lineno, 'duplicate function') | |
501 | func = t.split('=') | |
502 | func = func[1] | |
503 | continue | |
504 | ||
505 | if re_fullmatch('[0-9]+:s[0-9]+', t): | |
506 | # Signed field extract | |
507 | subtoks = t.split(':s') | |
508 | sign = True | |
509 | elif re_fullmatch('[0-9]+:[0-9]+', t): | |
510 | # Unsigned field extract | |
511 | subtoks = t.split(':') | |
512 | sign = False | |
513 | else: | |
514 | error(lineno, 'invalid field token "{0}"'.format(t)) | |
515 | po = int(subtoks[0]) | |
516 | le = int(subtoks[1]) | |
517 | if po + le > insnwidth: | |
518 | error(lineno, 'field {0} too large'.format(t)) | |
519 | f = Field(sign, po, le) | |
520 | subs.append(f) | |
521 | width += le | |
522 | ||
523 | if width > insnwidth: | |
524 | error(lineno, 'field too large') | |
525 | if len(subs) == 1: | |
526 | f = subs[0] | |
527 | else: | |
528 | mask = 0 | |
529 | for s in subs: | |
530 | if mask & s.mask: | |
531 | error(lineno, 'field components overlap') | |
532 | mask |= s.mask | |
533 | f = MultiField(subs, mask) | |
534 | if func: | |
535 | f = FunctionField(func, f) | |
536 | ||
537 | if name in fields: | |
538 | error(lineno, 'duplicate field', name) | |
539 | fields[name] = f | |
540 | # end parse_field | |
541 | ||
542 | ||
543 | def parse_arguments(lineno, name, toks): | |
544 | """Parse one argument set from TOKS at LINENO""" | |
545 | global arguments | |
546 | global re_ident | |
547 | ||
548 | flds = [] | |
abd04f92 | 549 | extern = False |
568ae7ef | 550 | for t in toks: |
abd04f92 RH |
551 | if re_fullmatch('!extern', t): |
552 | extern = True | |
553 | continue | |
568ae7ef RH |
554 | if not re_fullmatch(re_ident, t): |
555 | error(lineno, 'invalid argument set token "{0}"'.format(t)) | |
556 | if t in flds: | |
557 | error(lineno, 'duplicate argument "{0}"'.format(t)) | |
558 | flds.append(t) | |
559 | ||
560 | if name in arguments: | |
561 | error(lineno, 'duplicate argument set', name) | |
abd04f92 | 562 | arguments[name] = Arguments(name, flds, extern) |
568ae7ef RH |
563 | # end parse_arguments |
564 | ||
565 | ||
566 | def lookup_field(lineno, name): | |
567 | global fields | |
568 | if name in fields: | |
569 | return fields[name] | |
570 | error(lineno, 'undefined field', name) | |
571 | ||
572 | ||
573 | def add_field(lineno, flds, new_name, f): | |
574 | if new_name in flds: | |
575 | error(lineno, 'duplicate field', new_name) | |
576 | flds[new_name] = f | |
577 | return flds | |
578 | ||
579 | ||
580 | def add_field_byname(lineno, flds, new_name, old_name): | |
581 | return add_field(lineno, flds, new_name, lookup_field(lineno, old_name)) | |
582 | ||
583 | ||
584 | def infer_argument_set(flds): | |
585 | global arguments | |
abd04f92 | 586 | global decode_function |
568ae7ef RH |
587 | |
588 | for arg in arguments.values(): | |
589 | if eq_fields_for_args(flds, arg.fields): | |
590 | return arg | |
591 | ||
abd04f92 RH |
592 | name = decode_function + str(len(arguments)) |
593 | arg = Arguments(name, flds.keys(), False) | |
568ae7ef RH |
594 | arguments[name] = arg |
595 | return arg | |
596 | ||
597 | ||
598 | def infer_format(arg, fieldmask, flds): | |
599 | global arguments | |
600 | global formats | |
abd04f92 | 601 | global decode_function |
568ae7ef RH |
602 | |
603 | const_flds = {} | |
604 | var_flds = {} | |
605 | for n, c in flds.items(): | |
606 | if c is ConstField: | |
607 | const_flds[n] = c | |
608 | else: | |
609 | var_flds[n] = c | |
610 | ||
611 | # Look for an existing format with the same argument set and fields | |
612 | for fmt in formats.values(): | |
613 | if arg and fmt.base != arg: | |
614 | continue | |
615 | if fieldmask != fmt.fieldmask: | |
616 | continue | |
617 | if not eq_fields_for_fmts(flds, fmt.fields): | |
618 | continue | |
619 | return (fmt, const_flds) | |
620 | ||
abd04f92 | 621 | name = decode_function + '_Fmt_' + str(len(formats)) |
568ae7ef RH |
622 | if not arg: |
623 | arg = infer_argument_set(flds) | |
624 | ||
625 | fmt = Format(name, 0, arg, 0, 0, 0, fieldmask, var_flds) | |
626 | formats[name] = fmt | |
627 | ||
628 | return (fmt, const_flds) | |
629 | # end infer_format | |
630 | ||
631 | ||
632 | def parse_generic(lineno, is_format, name, toks): | |
633 | """Parse one instruction format from TOKS at LINENO""" | |
634 | global fields | |
635 | global arguments | |
636 | global formats | |
637 | global patterns | |
638 | global re_ident | |
639 | global insnwidth | |
640 | global insnmask | |
641 | ||
642 | fixedmask = 0 | |
643 | fixedbits = 0 | |
644 | undefmask = 0 | |
645 | width = 0 | |
646 | flds = {} | |
647 | arg = None | |
648 | fmt = None | |
649 | for t in toks: | |
650 | # '&Foo' gives a format an explcit argument set. | |
651 | if t[0] == '&': | |
652 | tt = t[1:] | |
653 | if arg: | |
654 | error(lineno, 'multiple argument sets') | |
655 | if tt in arguments: | |
656 | arg = arguments[tt] | |
657 | else: | |
658 | error(lineno, 'undefined argument set', t) | |
659 | continue | |
660 | ||
661 | # '@Foo' gives a pattern an explicit format. | |
662 | if t[0] == '@': | |
663 | tt = t[1:] | |
664 | if fmt: | |
665 | error(lineno, 'multiple formats') | |
666 | if tt in formats: | |
667 | fmt = formats[tt] | |
668 | else: | |
669 | error(lineno, 'undefined format', t) | |
670 | continue | |
671 | ||
672 | # '%Foo' imports a field. | |
673 | if t[0] == '%': | |
674 | tt = t[1:] | |
675 | flds = add_field_byname(lineno, flds, tt, tt) | |
676 | continue | |
677 | ||
678 | # 'Foo=%Bar' imports a field with a different name. | |
679 | if re_fullmatch(re_ident + '=%' + re_ident, t): | |
680 | (fname, iname) = t.split('=%') | |
681 | flds = add_field_byname(lineno, flds, fname, iname) | |
682 | continue | |
683 | ||
684 | # 'Foo=number' sets an argument field to a constant value | |
685 | if re_fullmatch(re_ident + '=[0-9]+', t): | |
686 | (fname, value) = t.split('=') | |
687 | value = int(value) | |
688 | flds = add_field(lineno, flds, fname, ConstField(value)) | |
689 | continue | |
690 | ||
691 | # Pattern of 0s, 1s, dots and dashes indicate required zeros, | |
692 | # required ones, or dont-cares. | |
693 | if re_fullmatch('[01.-]+', t): | |
694 | shift = len(t) | |
695 | fms = t.replace('0', '1') | |
696 | fms = fms.replace('.', '0') | |
697 | fms = fms.replace('-', '0') | |
698 | fbs = t.replace('.', '0') | |
699 | fbs = fbs.replace('-', '0') | |
700 | ubm = t.replace('1', '0') | |
701 | ubm = ubm.replace('.', '0') | |
702 | ubm = ubm.replace('-', '1') | |
703 | fms = int(fms, 2) | |
704 | fbs = int(fbs, 2) | |
705 | ubm = int(ubm, 2) | |
706 | fixedbits = (fixedbits << shift) | fbs | |
707 | fixedmask = (fixedmask << shift) | fms | |
708 | undefmask = (undefmask << shift) | ubm | |
709 | # Otherwise, fieldname:fieldwidth | |
710 | elif re_fullmatch(re_ident + ':s?[0-9]+', t): | |
711 | (fname, flen) = t.split(':') | |
712 | sign = False | |
713 | if flen[0] == 's': | |
714 | sign = True | |
715 | flen = flen[1:] | |
716 | shift = int(flen, 10) | |
717 | f = Field(sign, insnwidth - width - shift, shift) | |
718 | flds = add_field(lineno, flds, fname, f) | |
719 | fixedbits <<= shift | |
720 | fixedmask <<= shift | |
721 | undefmask <<= shift | |
722 | else: | |
723 | error(lineno, 'invalid token "{0}"'.format(t)) | |
724 | width += shift | |
725 | ||
726 | # We should have filled in all of the bits of the instruction. | |
727 | if not (is_format and width == 0) and width != insnwidth: | |
728 | error(lineno, 'definition has {0} bits'.format(width)) | |
729 | ||
730 | # Do not check for fields overlaping fields; one valid usage | |
731 | # is to be able to duplicate fields via import. | |
732 | fieldmask = 0 | |
733 | for f in flds.values(): | |
734 | fieldmask |= f.mask | |
735 | ||
736 | # Fix up what we've parsed to match either a format or a pattern. | |
737 | if is_format: | |
738 | # Formats cannot reference formats. | |
739 | if fmt: | |
740 | error(lineno, 'format referencing format') | |
741 | # If an argument set is given, then there should be no fields | |
742 | # without a place to store it. | |
743 | if arg: | |
744 | for f in flds.keys(): | |
745 | if f not in arg.fields: | |
746 | error(lineno, 'field {0} not in argument set {1}' | |
747 | .format(f, arg.name)) | |
748 | else: | |
749 | arg = infer_argument_set(flds) | |
750 | if name in formats: | |
751 | error(lineno, 'duplicate format name', name) | |
752 | fmt = Format(name, lineno, arg, fixedbits, fixedmask, | |
753 | undefmask, fieldmask, flds) | |
754 | formats[name] = fmt | |
755 | else: | |
756 | # Patterns can reference a format ... | |
757 | if fmt: | |
758 | # ... but not an argument simultaneously | |
759 | if arg: | |
760 | error(lineno, 'pattern specifies both format and argument set') | |
761 | if fixedmask & fmt.fixedmask: | |
762 | error(lineno, 'pattern fixed bits overlap format fixed bits') | |
763 | fieldmask |= fmt.fieldmask | |
764 | fixedbits |= fmt.fixedbits | |
765 | fixedmask |= fmt.fixedmask | |
766 | undefmask |= fmt.undefmask | |
767 | else: | |
768 | (fmt, flds) = infer_format(arg, fieldmask, flds) | |
769 | arg = fmt.base | |
770 | for f in flds.keys(): | |
771 | if f not in arg.fields: | |
772 | error(lineno, 'field {0} not in argument set {1}' | |
773 | .format(f, arg.name)) | |
774 | if f in fmt.fields.keys(): | |
775 | error(lineno, 'field {0} set by format and pattern'.format(f)) | |
776 | for f in arg.fields: | |
777 | if f not in flds.keys() and f not in fmt.fields.keys(): | |
778 | error(lineno, 'field {0} not initialized'.format(f)) | |
779 | pat = Pattern(name, lineno, fmt, fixedbits, fixedmask, | |
780 | undefmask, fieldmask, flds) | |
781 | patterns.append(pat) | |
782 | ||
783 | # Validate the masks that we have assembled. | |
784 | if fieldmask & fixedmask: | |
785 | error(lineno, 'fieldmask overlaps fixedmask (0x{0:08x} & 0x{1:08x})' | |
786 | .format(fieldmask, fixedmask)) | |
787 | if fieldmask & undefmask: | |
788 | error(lineno, 'fieldmask overlaps undefmask (0x{0:08x} & 0x{1:08x})' | |
789 | .format(fieldmask, undefmask)) | |
790 | if fixedmask & undefmask: | |
791 | error(lineno, 'fixedmask overlaps undefmask (0x{0:08x} & 0x{1:08x})' | |
792 | .format(fixedmask, undefmask)) | |
793 | if not is_format: | |
794 | allbits = fieldmask | fixedmask | undefmask | |
795 | if allbits != insnmask: | |
796 | error(lineno, 'bits left unspecified (0x{0:08x})' | |
797 | .format(allbits ^ insnmask)) | |
798 | # end parse_general | |
799 | ||
800 | ||
801 | def parse_file(f): | |
802 | """Parse all of the patterns within a file""" | |
803 | ||
804 | # Read all of the lines of the file. Concatenate lines | |
805 | # ending in backslash; discard empty lines and comments. | |
806 | toks = [] | |
807 | lineno = 0 | |
808 | for line in f: | |
809 | lineno += 1 | |
810 | ||
811 | # Discard comments | |
812 | end = line.find('#') | |
813 | if end >= 0: | |
814 | line = line[:end] | |
815 | ||
816 | t = line.split() | |
817 | if len(toks) != 0: | |
818 | # Next line after continuation | |
819 | toks.extend(t) | |
820 | elif len(t) == 0: | |
821 | # Empty line | |
822 | continue | |
823 | else: | |
824 | toks = t | |
825 | ||
826 | # Continuation? | |
827 | if toks[-1] == '\\': | |
828 | toks.pop() | |
829 | continue | |
830 | ||
831 | if len(toks) < 2: | |
832 | error(lineno, 'short line') | |
833 | ||
834 | name = toks[0] | |
835 | del toks[0] | |
836 | ||
837 | # Determine the type of object needing to be parsed. | |
838 | if name[0] == '%': | |
839 | parse_field(lineno, name[1:], toks) | |
840 | elif name[0] == '&': | |
841 | parse_arguments(lineno, name[1:], toks) | |
842 | elif name[0] == '@': | |
843 | parse_generic(lineno, True, name[1:], toks) | |
844 | else: | |
845 | parse_generic(lineno, False, name, toks) | |
846 | toks = [] | |
847 | # end parse_file | |
848 | ||
849 | ||
850 | class Tree: | |
851 | """Class representing a node in a decode tree""" | |
852 | ||
853 | def __init__(self, fm, tm): | |
854 | self.fixedmask = fm | |
855 | self.thismask = tm | |
856 | self.subs = [] | |
857 | self.base = None | |
858 | ||
859 | def str1(self, i): | |
860 | ind = str_indent(i) | |
861 | r = '{0}{1:08x}'.format(ind, self.fixedmask) | |
862 | if self.format: | |
863 | r += ' ' + self.format.name | |
864 | r += ' [\n' | |
865 | for (b, s) in self.subs: | |
866 | r += '{0} {1:08x}:\n'.format(ind, b) | |
867 | r += s.str1(i + 4) + '\n' | |
868 | r += ind + ']' | |
869 | return r | |
870 | ||
871 | def __str__(self): | |
872 | return self.str1(0) | |
873 | ||
874 | def output_code(self, i, extracted, outerbits, outermask): | |
875 | ind = str_indent(i) | |
876 | ||
877 | # If we identified all nodes below have the same format, | |
878 | # extract the fields now. | |
879 | if not extracted and self.base: | |
880 | output(ind, self.base.extract_name(), | |
881 | '(&u.f_', self.base.base.name, ', insn);\n') | |
882 | extracted = True | |
883 | ||
884 | # Attempt to aid the compiler in producing compact switch statements. | |
885 | # If the bits in the mask are contiguous, extract them. | |
886 | sh = is_contiguous(self.thismask) | |
887 | if sh > 0: | |
888 | # Propagate SH down into the local functions. | |
889 | def str_switch(b, sh=sh): | |
890 | return '(insn >> {0}) & 0x{1:x}'.format(sh, b >> sh) | |
891 | ||
892 | def str_case(b, sh=sh): | |
893 | return '0x{0:x}'.format(b >> sh) | |
894 | else: | |
895 | def str_switch(b): | |
896 | return 'insn & 0x{0:08x}'.format(b) | |
897 | ||
898 | def str_case(b): | |
899 | return '0x{0:08x}'.format(b) | |
900 | ||
901 | output(ind, 'switch (', str_switch(self.thismask), ') {\n') | |
902 | for b, s in sorted(self.subs): | |
903 | assert (self.thismask & ~s.fixedmask) == 0 | |
904 | innermask = outermask | self.thismask | |
905 | innerbits = outerbits | b | |
906 | output(ind, 'case ', str_case(b), ':\n') | |
907 | output(ind, ' /* ', | |
908 | str_match_bits(innerbits, innermask), ' */\n') | |
909 | s.output_code(i + 4, extracted, innerbits, innermask) | |
910 | output(ind, '}\n') | |
911 | output(ind, 'return false;\n') | |
912 | # end Tree | |
913 | ||
914 | ||
915 | def build_tree(pats, outerbits, outermask): | |
916 | # Find the intersection of all remaining fixedmask. | |
917 | innermask = ~outermask | |
918 | for i in pats: | |
919 | innermask &= i.fixedmask | |
920 | ||
921 | if innermask == 0: | |
922 | pnames = [] | |
923 | for p in pats: | |
924 | pnames.append(p.name + ':' + str(p.lineno)) | |
925 | error(pats[0].lineno, 'overlapping patterns:', pnames) | |
926 | ||
927 | fullmask = outermask | innermask | |
928 | ||
929 | # Sort each element of pats into the bin selected by the mask. | |
930 | bins = {} | |
931 | for i in pats: | |
932 | fb = i.fixedbits & innermask | |
933 | if fb in bins: | |
934 | bins[fb].append(i) | |
935 | else: | |
936 | bins[fb] = [i] | |
937 | ||
938 | # We must recurse if any bin has more than one element or if | |
939 | # the single element in the bin has not been fully matched. | |
940 | t = Tree(fullmask, innermask) | |
941 | ||
942 | for b, l in bins.items(): | |
943 | s = l[0] | |
944 | if len(l) > 1 or s.fixedmask & ~fullmask != 0: | |
945 | s = build_tree(l, b | outerbits, fullmask) | |
946 | t.subs.append((b, s)) | |
947 | ||
948 | return t | |
949 | # end build_tree | |
950 | ||
951 | ||
952 | def prop_format(tree): | |
953 | """Propagate Format objects into the decode tree""" | |
954 | ||
955 | # Depth first search. | |
956 | for (b, s) in tree.subs: | |
957 | if isinstance(s, Tree): | |
958 | prop_format(s) | |
959 | ||
960 | # If all entries in SUBS have the same format, then | |
961 | # propagate that into the tree. | |
962 | f = None | |
963 | for (b, s) in tree.subs: | |
964 | if f is None: | |
965 | f = s.base | |
966 | if f is None: | |
967 | return | |
968 | if f is not s.base: | |
969 | return | |
970 | tree.base = f | |
971 | # end prop_format | |
972 | ||
973 | ||
974 | def main(): | |
975 | global arguments | |
976 | global formats | |
977 | global patterns | |
978 | global translate_scope | |
979 | global translate_prefix | |
980 | global output_fd | |
981 | global output_file | |
982 | global input_file | |
983 | global insnwidth | |
984 | global insntype | |
83d7c40c | 985 | global insnmask |
abd04f92 | 986 | global decode_function |
568ae7ef | 987 | |
568ae7ef RH |
988 | decode_scope = 'static ' |
989 | ||
990 | long_opts = ['decode=', 'translate=', 'output=', 'insnwidth='] | |
991 | try: | |
992 | (opts, args) = getopt.getopt(sys.argv[1:], 'o:w:', long_opts) | |
993 | except getopt.GetoptError as err: | |
994 | error(0, err) | |
995 | for o, a in opts: | |
996 | if o in ('-o', '--output'): | |
997 | output_file = a | |
998 | elif o == '--decode': | |
999 | decode_function = a | |
1000 | decode_scope = '' | |
1001 | elif o == '--translate': | |
1002 | translate_prefix = a | |
1003 | translate_scope = '' | |
1004 | elif o in ('-w', '--insnwidth'): | |
1005 | insnwidth = int(a) | |
1006 | if insnwidth == 16: | |
1007 | insntype = 'uint16_t' | |
1008 | insnmask = 0xffff | |
1009 | elif insnwidth != 32: | |
1010 | error(0, 'cannot handle insns of width', insnwidth) | |
1011 | else: | |
1012 | assert False, 'unhandled option' | |
1013 | ||
1014 | if len(args) < 1: | |
1015 | error(0, 'missing input file') | |
1016 | input_file = args[0] | |
1017 | f = open(input_file, 'r') | |
1018 | parse_file(f) | |
1019 | f.close() | |
1020 | ||
1021 | t = build_tree(patterns, 0, 0) | |
1022 | prop_format(t) | |
1023 | ||
1024 | if output_file: | |
1025 | output_fd = open(output_file, 'w') | |
1026 | else: | |
1027 | output_fd = sys.stdout | |
1028 | ||
1029 | output_autogen() | |
1030 | for n in sorted(arguments.keys()): | |
1031 | f = arguments[n] | |
1032 | f.output_def() | |
1033 | ||
1034 | # A single translate function can be invoked for different patterns. | |
1035 | # Make sure that the argument sets are the same, and declare the | |
1036 | # function only once. | |
1037 | out_pats = {} | |
1038 | for i in patterns: | |
1039 | if i.name in out_pats: | |
1040 | p = out_pats[i.name] | |
1041 | if i.base.base != p.base.base: | |
1042 | error(0, i.name, ' has conflicting argument sets') | |
1043 | else: | |
1044 | i.output_decl() | |
1045 | out_pats[i.name] = i | |
1046 | output('\n') | |
1047 | ||
1048 | for n in sorted(formats.keys()): | |
1049 | f = formats[n] | |
1050 | f.output_extract() | |
1051 | ||
1052 | output(decode_scope, 'bool ', decode_function, | |
1053 | '(DisasContext *ctx, ', insntype, ' insn)\n{\n') | |
1054 | ||
1055 | i4 = str_indent(4) | |
1056 | output(i4, 'union {\n') | |
1057 | for n in sorted(arguments.keys()): | |
1058 | f = arguments[n] | |
1059 | output(i4, i4, f.struct_name(), ' f_', f.name, ';\n') | |
1060 | output(i4, '} u;\n\n') | |
1061 | ||
1062 | t.output_code(4, False, 0, 0) | |
1063 | ||
1064 | output('}\n') | |
1065 | ||
1066 | if output_file: | |
1067 | output_fd.close() | |
1068 | # end main | |
1069 | ||
1070 | ||
1071 | if __name__ == '__main__': | |
1072 | main() |