2 # Copyright (c) 2018 Linaro Limited
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.
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.
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/>.
19 # Generate a decoding tree from a specification file.
20 # See the syntax and semantics in docs/devel/decodetree.rst.
37 translate_prefix
= 'trans'
38 translate_scope
= 'static '
43 decode_function
= 'decode'
45 re_ident
= '[a-zA-Z][a-zA-Z0-9_]*'
48 def error_with_file(file, lineno
, *args
):
49 """Print an error message from file:line and args and exit."""
54 r
= '{0}:{1}: error:'.format(file, lineno
)
56 r
= '{0}: error:'.format(file)
63 if output_file
and output_fd
:
65 os
.remove(output_file
)
68 def error(lineno
, *args
):
69 error_with_file(input_file
, lineno
, args
)
77 if sys
.version_info
>= (3, 4):
78 re_fullmatch
= re
.fullmatch
80 def re_fullmatch(pat
, str):
81 return re
.match('^' + pat
+ '$', str)
85 output('/* This file is autogenerated by scripts/decodetree.py. */\n\n')
89 """Return a string with C spaces"""
93 def str_fields(fields
):
94 """Return a string uniquely identifing FIELDS"""
96 for n
in sorted(fields
.keys()):
101 def str_match_bits(bits
, mask
):
102 """Return a string pretty-printing BITS/MASK"""
105 i
= 1 << (insnwidth
- 1)
123 """Return true iff X is equal to a power of 2."""
124 return (x
& (x
- 1)) == 0
128 """Return the number of times 2 factors into X."""
130 while ((x
>> r
) & 1) == 0:
135 def is_contiguous(bits
):
137 if is_pow2((bits
>> shift
) + 1):
143 def eq_fields_for_args(flds_a
, flds_b
):
144 if len(flds_a
) != len(flds_b
):
146 for k
, a
in flds_a
.items():
152 def eq_fields_for_fmts(flds_a
, flds_b
):
153 if len(flds_a
) != len(flds_b
):
155 for k
, a
in flds_a
.items():
159 if a
.__class
__ != b
.__class
__ or a
!= b
:
165 """Class representing a simple instruction field"""
166 def __init__(self
, sign
, pos
, len):
170 self
.mask
= ((1 << len) - 1) << pos
177 return str(self
.pos
) + ':' + s
+ str(self
.len)
179 def str_extract(self
):
184 return '{0}(insn, {1}, {2})'.format(extr
, self
.pos
, self
.len)
186 def __eq__(self
, other
):
187 return self
.sign
== other
.sign
and self
.sign
== other
.sign
189 def __ne__(self
, other
):
190 return not self
.__eq
__(other
)
195 """Class representing a compound instruction field"""
196 def __init__(self
, subs
, mask
):
198 self
.sign
= subs
[0].sign
202 return str(self
.subs
)
204 def str_extract(self
):
207 for f
in reversed(self
.subs
):
209 ret
= f
.str_extract()
211 ret
= 'deposit32({0}, {1}, {2}, {3})' \
212 .format(ret
, pos
, 32 - pos
, f
.str_extract())
216 def __ne__(self
, other
):
217 if len(self
.subs
) != len(other
.subs
):
219 for a
, b
in zip(self
.subs
, other
.subs
):
220 if a
.__class
__ != b
.__class
__ or a
!= b
:
224 def __eq__(self
, other
):
225 return not self
.__ne
__(other
)
230 """Class representing an argument field with constant value"""
231 def __init__(self
, value
):
234 self
.sign
= value
< 0
237 return str(self
.value
)
239 def str_extract(self
):
240 return str(self
.value
)
242 def __cmp__(self
, other
):
243 return self
.value
- other
.value
248 """Class representing a field passed through an expander"""
249 def __init__(self
, func
, base
):
250 self
.mask
= base
.mask
251 self
.sign
= base
.sign
256 return self
.func
+ '(' + str(self
.base
) + ')'
258 def str_extract(self
):
259 return self
.func
+ '(' + self
.base
.str_extract() + ')'
261 def __eq__(self
, other
):
262 return self
.func
== other
.func
and self
.base
== other
.base
264 def __ne__(self
, other
):
265 return not self
.__eq
__(other
)
270 """Class representing the extracted fields of a format"""
271 def __init__(self
, nm
, flds
, extern
):
274 self
.fields
= sorted(flds
)
277 return self
.name
+ ' ' + str(self
.fields
)
279 def struct_name(self
):
280 return 'arg_' + self
.name
282 def output_def(self
):
284 output('typedef struct {\n')
285 for n
in self
.fields
:
286 output(' int ', n
, ';\n')
287 output('} ', self
.struct_name(), ';\n\n')
292 """Common code between instruction formats and instruction patterns"""
293 def __init__(self
, name
, lineno
, base
, fixb
, fixm
, udfm
, fldm
, flds
, w
):
295 self
.file = input_file
298 self
.fixedbits
= fixb
299 self
.fixedmask
= fixm
300 self
.undefmask
= udfm
301 self
.fieldmask
= fldm
306 return self
.name
+ ' ' + str_match_bits(self
.fixedbits
, self
.fixedmask
)
309 return str_indent(i
) + self
.__str
__()
313 class Format(General
):
314 """Class representing an instruction format"""
316 def extract_name(self
):
317 global decode_function
318 return decode_function
+ '_extract_' + self
.name
320 def output_extract(self
):
321 output('static void ', self
.extract_name(), '(',
322 self
.base
.struct_name(), ' *a, ', insntype
, ' insn)\n{\n')
323 for n
, f
in self
.fields
.items():
324 output(' a->', n
, ' = ', f
.str_extract(), ';\n')
329 class Pattern(General
):
330 """Class representing an instruction pattern"""
332 def output_decl(self
):
333 global translate_scope
334 global translate_prefix
335 output('typedef ', self
.base
.base
.struct_name(),
336 ' arg_', self
.name
, ';\n')
337 output(translate_scope
, 'bool ', translate_prefix
, '_', self
.name
,
338 '(DisasContext *ctx, arg_', self
.name
, ' *a);\n')
340 def output_code(self
, i
, extracted
, outerbits
, outermask
):
341 global translate_prefix
343 arg
= self
.base
.base
.name
344 output(ind
, '/* ', self
.file, ':', str(self
.lineno
), ' */\n')
346 output(ind
, self
.base
.extract_name(), '(&u.f_', arg
, ', insn);\n')
347 for n
, f
in self
.fields
.items():
348 output(ind
, 'u.f_', arg
, '.', n
, ' = ', f
.str_extract(), ';\n')
349 output(ind
, 'if (', translate_prefix
, '_', self
.name
,
350 '(ctx, &u.f_', arg
, ')) return true;\n')
354 class MultiPattern(General
):
355 """Class representing an overlapping set of instruction patterns"""
357 def __init__(self
, lineno
, pats
, fixb
, fixm
, udfm
, w
):
358 self
.file = input_file
362 self
.fixedbits
= fixb
363 self
.fixedmask
= fixm
364 self
.undefmask
= udfm
373 def output_decl(self
):
377 def output_code(self
, i
, extracted
, outerbits
, outermask
):
378 global translate_prefix
381 if outermask
!= p
.fixedmask
:
382 innermask
= p
.fixedmask
& ~outermask
383 innerbits
= p
.fixedbits
& ~outermask
384 output(ind
, 'if ((insn & ',
385 '0x{0:08x}) == 0x{1:08x}'.format(innermask
, innerbits
),
388 str_match_bits(p
.fixedbits
, p
.fixedmask
), ' */\n')
389 p
.output_code(i
+ 4, extracted
, p
.fixedbits
, p
.fixedmask
)
392 p
.output_code(i
, extracted
, p
.fixedbits
, p
.fixedmask
)
396 def parse_field(lineno
, name
, toks
):
397 """Parse one instruction field from TOKS at LINENO"""
402 # A "simple" field will have only one entry;
403 # a "multifield" will have several.
408 if re_fullmatch('!function=' + re_ident
, t
):
410 error(lineno
, 'duplicate function')
415 if re_fullmatch('[0-9]+:s[0-9]+', t
):
416 # Signed field extract
417 subtoks
= t
.split(':s')
419 elif re_fullmatch('[0-9]+:[0-9]+', t
):
420 # Unsigned field extract
421 subtoks
= t
.split(':')
424 error(lineno
, 'invalid field token "{0}"'.format(t
))
427 if po
+ le
> insnwidth
:
428 error(lineno
, 'field {0} too large'.format(t
))
429 f
= Field(sign
, po
, le
)
433 if width
> insnwidth
:
434 error(lineno
, 'field too large')
441 error(lineno
, 'field components overlap')
443 f
= MultiField(subs
, mask
)
445 f
= FunctionField(func
, f
)
448 error(lineno
, 'duplicate field', name
)
453 def parse_arguments(lineno
, name
, toks
):
454 """Parse one argument set from TOKS at LINENO"""
461 if re_fullmatch('!extern', t
):
464 if not re_fullmatch(re_ident
, t
):
465 error(lineno
, 'invalid argument set token "{0}"'.format(t
))
467 error(lineno
, 'duplicate argument "{0}"'.format(t
))
470 if name
in arguments
:
471 error(lineno
, 'duplicate argument set', name
)
472 arguments
[name
] = Arguments(name
, flds
, extern
)
473 # end parse_arguments
476 def lookup_field(lineno
, name
):
480 error(lineno
, 'undefined field', name
)
483 def add_field(lineno
, flds
, new_name
, f
):
485 error(lineno
, 'duplicate field', new_name
)
490 def add_field_byname(lineno
, flds
, new_name
, old_name
):
491 return add_field(lineno
, flds
, new_name
, lookup_field(lineno
, old_name
))
494 def infer_argument_set(flds
):
496 global decode_function
498 for arg
in arguments
.values():
499 if eq_fields_for_args(flds
, arg
.fields
):
502 name
= decode_function
+ str(len(arguments
))
503 arg
= Arguments(name
, flds
.keys(), False)
504 arguments
[name
] = arg
508 def infer_format(arg
, fieldmask
, flds
, width
):
511 global decode_function
515 for n
, c
in flds
.items():
521 # Look for an existing format with the same argument set and fields
522 for fmt
in formats
.values():
523 if arg
and fmt
.base
!= arg
:
525 if fieldmask
!= fmt
.fieldmask
:
527 if width
!= fmt
.width
:
529 if not eq_fields_for_fmts(flds
, fmt
.fields
):
531 return (fmt
, const_flds
)
533 name
= decode_function
+ '_Fmt_' + str(len(formats
))
535 arg
= infer_argument_set(flds
)
537 fmt
= Format(name
, 0, arg
, 0, 0, 0, fieldmask
, var_flds
, width
)
540 return (fmt
, const_flds
)
544 def parse_generic(lineno
, is_format
, name
, toks
):
545 """Parse one instruction format from TOKS at LINENO"""
564 # '&Foo' gives a format an explcit argument set.
568 error(lineno
, 'multiple argument sets')
572 error(lineno
, 'undefined argument set', t
)
575 # '@Foo' gives a pattern an explicit format.
579 error(lineno
, 'multiple formats')
583 error(lineno
, 'undefined format', t
)
586 # '%Foo' imports a field.
589 flds
= add_field_byname(lineno
, flds
, tt
, tt
)
592 # 'Foo=%Bar' imports a field with a different name.
593 if re_fullmatch(re_ident
+ '=%' + re_ident
, t
):
594 (fname
, iname
) = t
.split('=%')
595 flds
= add_field_byname(lineno
, flds
, fname
, iname
)
598 # 'Foo=number' sets an argument field to a constant value
599 if re_fullmatch(re_ident
+ '=[+-]?[0-9]+', t
):
600 (fname
, value
) = t
.split('=')
602 flds
= add_field(lineno
, flds
, fname
, ConstField(value
))
605 # Pattern of 0s, 1s, dots and dashes indicate required zeros,
606 # required ones, or dont-cares.
607 if re_fullmatch('[01.-]+', t
):
609 fms
= t
.replace('0', '1')
610 fms
= fms
.replace('.', '0')
611 fms
= fms
.replace('-', '0')
612 fbs
= t
.replace('.', '0')
613 fbs
= fbs
.replace('-', '0')
614 ubm
= t
.replace('1', '0')
615 ubm
= ubm
.replace('.', '0')
616 ubm
= ubm
.replace('-', '1')
620 fixedbits
= (fixedbits
<< shift
) | fbs
621 fixedmask
= (fixedmask
<< shift
) | fms
622 undefmask
= (undefmask
<< shift
) | ubm
623 # Otherwise, fieldname:fieldwidth
624 elif re_fullmatch(re_ident
+ ':s?[0-9]+', t
):
625 (fname
, flen
) = t
.split(':')
630 shift
= int(flen
, 10)
631 if shift
+ width
> insnwidth
:
632 error(lineno
, 'field {0} exceeds insnwidth'.format(fname
))
633 f
= Field(sign
, insnwidth
- width
- shift
, shift
)
634 flds
= add_field(lineno
, flds
, fname
, f
)
639 error(lineno
, 'invalid token "{0}"'.format(t
))
642 if variablewidth
and width
< insnwidth
and width
% 8 == 0:
643 shift
= insnwidth
- width
647 undefmask |
= (1 << shift
) - 1
649 # We should have filled in all of the bits of the instruction.
650 elif not (is_format
and width
== 0) and width
!= insnwidth
:
651 error(lineno
, 'definition has {0} bits'.format(width
))
653 # Do not check for fields overlaping fields; one valid usage
654 # is to be able to duplicate fields via import.
656 for f
in flds
.values():
659 # Fix up what we've parsed to match either a format or a pattern.
661 # Formats cannot reference formats.
663 error(lineno
, 'format referencing format')
664 # If an argument set is given, then there should be no fields
665 # without a place to store it.
667 for f
in flds
.keys():
668 if f
not in arg
.fields
:
669 error(lineno
, 'field {0} not in argument set {1}'
670 .format(f
, arg
.name
))
672 arg
= infer_argument_set(flds
)
674 error(lineno
, 'duplicate format name', name
)
675 fmt
= Format(name
, lineno
, arg
, fixedbits
, fixedmask
,
676 undefmask
, fieldmask
, flds
, width
)
679 # Patterns can reference a format ...
681 # ... but not an argument simultaneously
683 error(lineno
, 'pattern specifies both format and argument set')
684 if fixedmask
& fmt
.fixedmask
:
685 error(lineno
, 'pattern fixed bits overlap format fixed bits')
686 if width
!= fmt
.width
:
687 error(lineno
, 'pattern uses format of different width')
688 fieldmask |
= fmt
.fieldmask
689 fixedbits |
= fmt
.fixedbits
690 fixedmask |
= fmt
.fixedmask
691 undefmask |
= fmt
.undefmask
693 (fmt
, flds
) = infer_format(arg
, fieldmask
, flds
, width
)
695 for f
in flds
.keys():
696 if f
not in arg
.fields
:
697 error(lineno
, 'field {0} not in argument set {1}'
698 .format(f
, arg
.name
))
699 if f
in fmt
.fields
.keys():
700 error(lineno
, 'field {0} set by format and pattern'.format(f
))
702 if f
not in flds
.keys() and f
not in fmt
.fields
.keys():
703 error(lineno
, 'field {0} not initialized'.format(f
))
704 pat
= Pattern(name
, lineno
, fmt
, fixedbits
, fixedmask
,
705 undefmask
, fieldmask
, flds
, width
)
707 allpatterns
.append(pat
)
709 # Validate the masks that we have assembled.
710 if fieldmask
& fixedmask
:
711 error(lineno
, 'fieldmask overlaps fixedmask (0x{0:08x} & 0x{1:08x})'
712 .format(fieldmask
, fixedmask
))
713 if fieldmask
& undefmask
:
714 error(lineno
, 'fieldmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
715 .format(fieldmask
, undefmask
))
716 if fixedmask
& undefmask
:
717 error(lineno
, 'fixedmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
718 .format(fixedmask
, undefmask
))
720 allbits
= fieldmask | fixedmask | undefmask
721 if allbits
!= insnmask
:
722 error(lineno
, 'bits left unspecified (0x{0:08x})'
723 .format(allbits ^ insnmask
))
726 def build_multi_pattern(lineno
, pats
):
727 """Validate the Patterns going into a MultiPattern."""
732 error(lineno
, 'less than two patterns within braces')
737 # Collect fixed/undefmask for all of the children.
738 # Move the defining lineno back to that of the first child.
740 fixedmask
&= p
.fixedmask
741 undefmask
&= p
.undefmask
742 if p
.lineno
< lineno
:
749 elif width
!= p
.width
:
750 error(lineno
, 'width mismatch in patterns within braces')
755 error(lineno
, 'no overlap in patterns within braces')
758 thisbits
= p
.fixedbits
& fixedmask
759 if fixedbits
is None:
761 elif fixedbits
!= thisbits
:
762 fixedmask
&= ~
(fixedbits ^ thisbits
)
767 mp
= MultiPattern(lineno
, pats
, fixedbits
, fixedmask
, undefmask
, width
)
769 # end build_multi_pattern
772 """Parse all of the patterns within a file"""
776 # Read all of the lines of the file. Concatenate lines
777 # ending in backslash; discard empty lines and comments.
786 # Expand and strip spaces, to find indent.
788 line
= line
.expandtabs()
800 # Next line after continuation
803 # Allow completely blank lines.
807 # Empty line due to comment.
809 # Indentation must be correct, even for comment lines.
810 if indent
!= nesting
:
811 error(lineno
, 'indentation ', indent
, ' != ', nesting
)
813 start_lineno
= lineno
827 error(start_lineno
, 'mismatched close brace')
829 error(start_lineno
, 'extra tokens after close brace')
831 if indent
!= nesting
:
832 error(start_lineno
, 'indentation ', indent
, ' != ', nesting
)
834 patterns
= saved_pats
.pop()
835 build_multi_pattern(lineno
, pats
)
839 # Everything else should have current indentation.
840 if indent
!= nesting
:
841 error(start_lineno
, 'indentation ', indent
, ' != ', nesting
)
846 error(start_lineno
, 'extra tokens after open brace')
847 saved_pats
.append(patterns
)
853 # Determine the type of object needing to be parsed.
855 parse_field(start_lineno
, name
[1:], toks
)
857 parse_arguments(start_lineno
, name
[1:], toks
)
859 parse_generic(start_lineno
, True, name
[1:], toks
)
861 parse_generic(start_lineno
, False, name
, toks
)
867 """Class representing a node in a decode tree"""
869 def __init__(self
, fm
, tm
):
877 r
= '{0}{1:08x}'.format(ind
, self
.fixedmask
)
879 r
+= ' ' + self
.format
.name
881 for (b
, s
) in self
.subs
:
882 r
+= '{0} {1:08x}:\n'.format(ind
, b
)
883 r
+= s
.str1(i
+ 4) + '\n'
890 def output_code(self
, i
, extracted
, outerbits
, outermask
):
893 # If we identified all nodes below have the same format,
894 # extract the fields now.
895 if not extracted
and self
.base
:
896 output(ind
, self
.base
.extract_name(),
897 '(&u.f_', self
.base
.base
.name
, ', insn);\n')
900 # Attempt to aid the compiler in producing compact switch statements.
901 # If the bits in the mask are contiguous, extract them.
902 sh
= is_contiguous(self
.thismask
)
904 # Propagate SH down into the local functions.
905 def str_switch(b
, sh
=sh
):
906 return '(insn >> {0}) & 0x{1:x}'.format(sh
, b
>> sh
)
908 def str_case(b
, sh
=sh
):
909 return '0x{0:x}'.format(b
>> sh
)
912 return 'insn & 0x{0:08x}'.format(b
)
915 return '0x{0:08x}'.format(b
)
917 output(ind
, 'switch (', str_switch(self
.thismask
), ') {\n')
918 for b
, s
in sorted(self
.subs
):
919 assert (self
.thismask
& ~s
.fixedmask
) == 0
920 innermask
= outermask | self
.thismask
921 innerbits
= outerbits | b
922 output(ind
, 'case ', str_case(b
), ':\n')
924 str_match_bits(innerbits
, innermask
), ' */\n')
925 s
.output_code(i
+ 4, extracted
, innerbits
, innermask
)
926 output(ind
, ' return false;\n')
931 def build_tree(pats
, outerbits
, outermask
):
932 # Find the intersection of all remaining fixedmask.
933 innermask
= ~outermask
& insnmask
935 innermask
&= i
.fixedmask
938 text
= 'overlapping patterns:'
940 text
+= '\n' + p
.file + ':' + str(p
.lineno
) + ': ' + str(p
)
941 error_with_file(pats
[0].file, pats
[0].lineno
, text
)
943 fullmask
= outermask | innermask
945 # Sort each element of pats into the bin selected by the mask.
948 fb
= i
.fixedbits
& innermask
954 # We must recurse if any bin has more than one element or if
955 # the single element in the bin has not been fully matched.
956 t
= Tree(fullmask
, innermask
)
958 for b
, l
in bins
.items():
960 if len(l
) > 1 or s
.fixedmask
& ~fullmask
!= 0:
961 s
= build_tree(l
, b | outerbits
, fullmask
)
962 t
.subs
.append((b
, s
))
969 """Class representing a node in a size decode tree"""
971 def __init__(self
, m
, w
):
979 r
= '{0}{1:08x}'.format(ind
, self
.mask
)
981 for (b
, s
) in self
.subs
:
982 r
+= '{0} {1:08x}:\n'.format(ind
, b
)
983 r
+= s
.str1(i
+ 4) + '\n'
990 def output_code(self
, i
, extracted
, outerbits
, outermask
):
993 # If we need to load more bytes to test, do so now.
994 if extracted
< self
.width
:
995 output(ind
, 'insn = ', decode_function
,
996 '_load_bytes(ctx, insn, {0}, {1});\n'
997 .format(extracted
/ 8, self
.width
/ 8));
998 extracted
= self
.width
1000 # Attempt to aid the compiler in producing compact switch statements.
1001 # If the bits in the mask are contiguous, extract them.
1002 sh
= is_contiguous(self
.mask
)
1004 # Propagate SH down into the local functions.
1005 def str_switch(b
, sh
=sh
):
1006 return '(insn >> {0}) & 0x{1:x}'.format(sh
, b
>> sh
)
1008 def str_case(b
, sh
=sh
):
1009 return '0x{0:x}'.format(b
>> sh
)
1012 return 'insn & 0x{0:08x}'.format(b
)
1015 return '0x{0:08x}'.format(b
)
1017 output(ind
, 'switch (', str_switch(self
.mask
), ') {\n')
1018 for b
, s
in sorted(self
.subs
):
1019 innermask
= outermask | self
.mask
1020 innerbits
= outerbits | b
1021 output(ind
, 'case ', str_case(b
), ':\n')
1023 str_match_bits(innerbits
, innermask
), ' */\n')
1024 s
.output_code(i
+ 4, extracted
, innerbits
, innermask
)
1026 output(ind
, 'return insn;\n')
1030 """Class representing a leaf node in a size decode tree"""
1032 def __init__(self
, m
, w
):
1038 return '{0}{1:08x}'.format(ind
, self
.mask
)
1043 def output_code(self
, i
, extracted
, outerbits
, outermask
):
1044 global decode_function
1047 # If we need to load more bytes, do so now.
1048 if extracted
< self
.width
:
1049 output(ind
, 'insn = ', decode_function
,
1050 '_load_bytes(ctx, insn, {0}, {1});\n'
1051 .format(extracted
/ 8, self
.width
/ 8));
1052 extracted
= self
.width
1053 output(ind
, 'return insn;\n')
1057 def build_size_tree(pats
, width
, outerbits
, outermask
):
1060 # Collect the mask of bits that are fixed in this width
1061 innermask
= 0xff << (insnwidth
- width
)
1062 innermask
&= ~outermask
1066 innermask
&= i
.fixedmask
1067 if minwidth
is None:
1069 elif minwidth
!= i
.width
:
1071 if minwidth
< i
.width
:
1075 return SizeLeaf(innermask
, minwidth
)
1078 if width
< minwidth
:
1079 return build_size_tree(pats
, width
+ 8, outerbits
, outermask
)
1083 pnames
.append(p
.name
+ ':' + p
.file + ':' + str(p
.lineno
))
1084 error_with_file(pats
[0].file, pats
[0].lineno
,
1085 'overlapping patterns size {0}:'.format(width
), pnames
)
1089 fb
= i
.fixedbits
& innermask
1095 fullmask
= outermask | innermask
1096 lens
= sorted(bins
.keys())
1099 return build_size_tree(bins
[b
], width
+ 8, b | outerbits
, fullmask
)
1101 r
= SizeTree(innermask
, width
)
1102 for b
, l
in bins
.items():
1103 s
= build_size_tree(l
, width
, b | outerbits
, fullmask
)
1104 r
.subs
.append((b
, s
))
1106 # end build_size_tree
1109 def prop_format(tree
):
1110 """Propagate Format objects into the decode tree"""
1112 # Depth first search.
1113 for (b
, s
) in tree
.subs
:
1114 if isinstance(s
, Tree
):
1117 # If all entries in SUBS have the same format, then
1118 # propagate that into the tree.
1120 for (b
, s
) in tree
.subs
:
1131 def prop_size(tree
):
1132 """Propagate minimum widths up the decode size tree"""
1134 if isinstance(tree
, SizeTree
):
1136 for (b
, s
) in tree
.subs
:
1137 width
= prop_size(s
)
1138 if min is None or min > width
:
1140 assert min >= tree
.width
1153 global translate_scope
1154 global translate_prefix
1161 global decode_function
1162 global variablewidth
1164 decode_scope
= 'static '
1166 long_opts
= ['decode=', 'translate=', 'output=', 'insnwidth=',
1167 'static-decode=', 'varinsnwidth=']
1169 (opts
, args
) = getopt
.getopt(sys
.argv
[1:], 'o:vw:', long_opts
)
1170 except getopt
.GetoptError
as err
:
1173 if o
in ('-o', '--output'):
1175 elif o
== '--decode':
1178 elif o
== '--static-decode':
1180 elif o
== '--translate':
1181 translate_prefix
= a
1182 translate_scope
= ''
1183 elif o
in ('-w', '--insnwidth', '--varinsnwidth'):
1184 if o
== '--varinsnwidth':
1185 variablewidth
= True
1188 insntype
= 'uint16_t'
1190 elif insnwidth
!= 32:
1191 error(0, 'cannot handle insns of width', insnwidth
)
1193 assert False, 'unhandled option'
1196 error(0, 'missing input file')
1197 for filename
in args
:
1198 input_file
= filename
1199 f
= open(filename
, 'r')
1204 stree
= build_size_tree(patterns
, 8, 0, 0)
1207 dtree
= build_tree(patterns
, 0, 0)
1211 output_fd
= open(output_file
, 'w')
1213 output_fd
= sys
.stdout
1216 for n
in sorted(arguments
.keys()):
1220 # A single translate function can be invoked for different patterns.
1221 # Make sure that the argument sets are the same, and declare the
1222 # function only once.
1224 for i
in allpatterns
:
1225 if i
.name
in out_pats
:
1226 p
= out_pats
[i
.name
]
1227 if i
.base
.base
!= p
.base
.base
:
1228 error(0, i
.name
, ' has conflicting argument sets')
1231 out_pats
[i
.name
] = i
1234 for n
in sorted(formats
.keys()):
1238 output(decode_scope
, 'bool ', decode_function
,
1239 '(DisasContext *ctx, ', insntype
, ' insn)\n{\n')
1243 if len(allpatterns
) != 0:
1244 output(i4
, 'union {\n')
1245 for n
in sorted(arguments
.keys()):
1247 output(i4
, i4
, f
.struct_name(), ' f_', f
.name
, ';\n')
1248 output(i4
, '} u;\n\n')
1249 dtree
.output_code(4, False, 0, 0)
1251 output(i4
, 'return false;\n')
1255 output('\n', decode_scope
, insntype
, ' ', decode_function
,
1256 '_load(DisasContext *ctx)\n{\n',
1257 ' ', insntype
, ' insn = 0;\n\n')
1258 stree
.output_code(4, 0, 0, 0)
1266 if __name__
== '__main__':