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.
38 translate_prefix
= 'trans'
39 translate_scope
= 'static '
44 decode_function
= 'decode'
46 re_ident
= '[a-zA-Z][a-zA-Z0-9_]*'
49 def error_with_file(file, lineno
, *args
):
50 """Print an error message from file:line and args and exit."""
55 r
= '{0}:{1}: error:'.format(file, lineno
)
57 r
= '{0}: error:'.format(file)
64 if output_file
and output_fd
:
66 os
.remove(output_file
)
69 def error(lineno
, *args
):
70 error_with_file(input_file
, lineno
, args
)
78 if sys
.version_info
>= (3, 4):
79 re_fullmatch
= re
.fullmatch
81 def re_fullmatch(pat
, str):
82 return re
.match('^' + pat
+ '$', str)
86 output('/* This file is autogenerated by scripts/decodetree.py. */\n\n')
90 """Return a string with C spaces"""
94 def str_fields(fields
):
95 """Return a string uniquely identifing FIELDS"""
97 for n
in sorted(fields
.keys()):
102 def str_match_bits(bits
, mask
):
103 """Return a string pretty-printing BITS/MASK"""
106 i
= 1 << (insnwidth
- 1)
124 """Return true iff X is equal to a power of 2."""
125 return (x
& (x
- 1)) == 0
129 """Return the number of times 2 factors into X."""
131 while ((x
>> r
) & 1) == 0:
136 def is_contiguous(bits
):
138 if is_pow2((bits
>> shift
) + 1):
144 def eq_fields_for_args(flds_a
, flds_b
):
145 if len(flds_a
) != len(flds_b
):
147 for k
, a
in flds_a
.items():
153 def eq_fields_for_fmts(flds_a
, flds_b
):
154 if len(flds_a
) != len(flds_b
):
156 for k
, a
in flds_a
.items():
160 if a
.__class
__ != b
.__class
__ or a
!= b
:
166 """Class representing a simple instruction field"""
167 def __init__(self
, sign
, pos
, len):
171 self
.mask
= ((1 << len) - 1) << pos
178 return str(self
.pos
) + ':' + s
+ str(self
.len)
180 def str_extract(self
):
185 return '{0}(insn, {1}, {2})'.format(extr
, self
.pos
, self
.len)
187 def __eq__(self
, other
):
188 return self
.sign
== other
.sign
and self
.mask
== other
.mask
190 def __ne__(self
, other
):
191 return not self
.__eq
__(other
)
196 """Class representing a compound instruction field"""
197 def __init__(self
, subs
, mask
):
199 self
.sign
= subs
[0].sign
203 return str(self
.subs
)
205 def str_extract(self
):
208 for f
in reversed(self
.subs
):
210 ret
= f
.str_extract()
212 ret
= 'deposit32({0}, {1}, {2}, {3})' \
213 .format(ret
, pos
, 32 - pos
, f
.str_extract())
217 def __ne__(self
, other
):
218 if len(self
.subs
) != len(other
.subs
):
220 for a
, b
in zip(self
.subs
, other
.subs
):
221 if a
.__class
__ != b
.__class
__ or a
!= b
:
225 def __eq__(self
, other
):
226 return not self
.__ne
__(other
)
231 """Class representing an argument field with constant value"""
232 def __init__(self
, value
):
235 self
.sign
= value
< 0
238 return str(self
.value
)
240 def str_extract(self
):
241 return str(self
.value
)
243 def __cmp__(self
, other
):
244 return self
.value
- other
.value
249 """Class representing a field passed through a function"""
250 def __init__(self
, func
, base
):
251 self
.mask
= base
.mask
252 self
.sign
= base
.sign
257 return self
.func
+ '(' + str(self
.base
) + ')'
259 def str_extract(self
):
260 return self
.func
+ '(ctx, ' + self
.base
.str_extract() + ')'
262 def __eq__(self
, other
):
263 return self
.func
== other
.func
and self
.base
== other
.base
265 def __ne__(self
, other
):
266 return not self
.__eq
__(other
)
270 class ParameterField
:
271 """Class representing a pseudo-field read from a function"""
272 def __init__(self
, func
):
280 def str_extract(self
):
281 return self
.func
+ '(ctx)'
283 def __eq__(self
, other
):
284 return self
.func
== other
.func
286 def __ne__(self
, other
):
287 return not self
.__eq
__(other
)
292 """Class representing the extracted fields of a format"""
293 def __init__(self
, nm
, flds
, extern
):
296 self
.fields
= sorted(flds
)
299 return self
.name
+ ' ' + str(self
.fields
)
301 def struct_name(self
):
302 return 'arg_' + self
.name
304 def output_def(self
):
306 output('typedef struct {\n')
307 for n
in self
.fields
:
308 output(' int ', n
, ';\n')
309 output('} ', self
.struct_name(), ';\n\n')
314 """Common code between instruction formats and instruction patterns"""
315 def __init__(self
, name
, lineno
, base
, fixb
, fixm
, udfm
, fldm
, flds
, w
):
317 self
.file = input_file
320 self
.fixedbits
= fixb
321 self
.fixedmask
= fixm
322 self
.undefmask
= udfm
323 self
.fieldmask
= fldm
328 return self
.name
+ ' ' + str_match_bits(self
.fixedbits
, self
.fixedmask
)
331 return str_indent(i
) + self
.__str
__()
335 class Format(General
):
336 """Class representing an instruction format"""
338 def extract_name(self
):
339 global decode_function
340 return decode_function
+ '_extract_' + self
.name
342 def output_extract(self
):
343 output('static void ', self
.extract_name(), '(DisasContext *ctx, ',
344 self
.base
.struct_name(), ' *a, ', insntype
, ' insn)\n{\n')
345 for n
, f
in self
.fields
.items():
346 output(' a->', n
, ' = ', f
.str_extract(), ';\n')
351 class Pattern(General
):
352 """Class representing an instruction pattern"""
354 def output_decl(self
):
355 global translate_scope
356 global translate_prefix
357 output('typedef ', self
.base
.base
.struct_name(),
358 ' arg_', self
.name
, ';\n')
359 output(translate_scope
, 'bool ', translate_prefix
, '_', self
.name
,
360 '(DisasContext *ctx, arg_', self
.name
, ' *a);\n')
362 def output_code(self
, i
, extracted
, outerbits
, outermask
):
363 global translate_prefix
365 arg
= self
.base
.base
.name
366 output(ind
, '/* ', self
.file, ':', str(self
.lineno
), ' */\n')
368 output(ind
, self
.base
.extract_name(),
369 '(ctx, &u.f_', arg
, ', insn);\n')
370 for n
, f
in self
.fields
.items():
371 output(ind
, 'u.f_', arg
, '.', n
, ' = ', f
.str_extract(), ';\n')
372 output(ind
, 'if (', translate_prefix
, '_', self
.name
,
373 '(ctx, &u.f_', arg
, ')) return true;\n')
377 class MultiPattern(General
):
378 """Class representing an overlapping set of instruction patterns"""
380 def __init__(self
, lineno
, pats
, fixb
, fixm
, udfm
, w
):
381 self
.file = input_file
385 self
.fixedbits
= fixb
386 self
.fixedmask
= fixm
387 self
.undefmask
= udfm
396 def output_decl(self
):
400 def output_code(self
, i
, extracted
, outerbits
, outermask
):
401 global translate_prefix
404 if outermask
!= p
.fixedmask
:
405 innermask
= p
.fixedmask
& ~outermask
406 innerbits
= p
.fixedbits
& ~outermask
407 output(ind
, 'if ((insn & ',
408 '0x{0:08x}) == 0x{1:08x}'.format(innermask
, innerbits
),
411 str_match_bits(p
.fixedbits
, p
.fixedmask
), ' */\n')
412 p
.output_code(i
+ 4, extracted
, p
.fixedbits
, p
.fixedmask
)
415 p
.output_code(i
, extracted
, p
.fixedbits
, p
.fixedmask
)
419 def parse_field(lineno
, name
, toks
):
420 """Parse one instruction field from TOKS at LINENO"""
425 # A "simple" field will have only one entry;
426 # a "multifield" will have several.
431 if re_fullmatch('!function=' + re_ident
, t
):
433 error(lineno
, 'duplicate function')
438 if re_fullmatch('[0-9]+:s[0-9]+', t
):
439 # Signed field extract
440 subtoks
= t
.split(':s')
442 elif re_fullmatch('[0-9]+:[0-9]+', t
):
443 # Unsigned field extract
444 subtoks
= t
.split(':')
447 error(lineno
, 'invalid field token "{0}"'.format(t
))
450 if po
+ le
> insnwidth
:
451 error(lineno
, 'field {0} too large'.format(t
))
452 f
= Field(sign
, po
, le
)
456 if width
> insnwidth
:
457 error(lineno
, 'field too large')
460 f
= ParameterField(func
)
462 error(lineno
, 'field with no value')
470 error(lineno
, 'field components overlap')
472 f
= MultiField(subs
, mask
)
474 f
= FunctionField(func
, f
)
477 error(lineno
, 'duplicate field', name
)
482 def parse_arguments(lineno
, name
, toks
):
483 """Parse one argument set from TOKS at LINENO"""
491 if re_fullmatch('!extern', t
):
495 if not re_fullmatch(re_ident
, t
):
496 error(lineno
, 'invalid argument set token "{0}"'.format(t
))
498 error(lineno
, 'duplicate argument "{0}"'.format(t
))
501 if name
in arguments
:
502 error(lineno
, 'duplicate argument set', name
)
503 arguments
[name
] = Arguments(name
, flds
, extern
)
504 # end parse_arguments
507 def lookup_field(lineno
, name
):
511 error(lineno
, 'undefined field', name
)
514 def add_field(lineno
, flds
, new_name
, f
):
516 error(lineno
, 'duplicate field', new_name
)
521 def add_field_byname(lineno
, flds
, new_name
, old_name
):
522 return add_field(lineno
, flds
, new_name
, lookup_field(lineno
, old_name
))
525 def infer_argument_set(flds
):
527 global decode_function
529 for arg
in arguments
.values():
530 if eq_fields_for_args(flds
, arg
.fields
):
533 name
= decode_function
+ str(len(arguments
))
534 arg
= Arguments(name
, flds
.keys(), False)
535 arguments
[name
] = arg
539 def infer_format(arg
, fieldmask
, flds
, width
):
542 global decode_function
546 for n
, c
in flds
.items():
552 # Look for an existing format with the same argument set and fields
553 for fmt
in formats
.values():
554 if arg
and fmt
.base
!= arg
:
556 if fieldmask
!= fmt
.fieldmask
:
558 if width
!= fmt
.width
:
560 if not eq_fields_for_fmts(flds
, fmt
.fields
):
562 return (fmt
, const_flds
)
564 name
= decode_function
+ '_Fmt_' + str(len(formats
))
566 arg
= infer_argument_set(flds
)
568 fmt
= Format(name
, 0, arg
, 0, 0, 0, fieldmask
, var_flds
, width
)
571 return (fmt
, const_flds
)
575 def parse_generic(lineno
, is_format
, name
, toks
):
576 """Parse one instruction format from TOKS at LINENO"""
595 # '&Foo' gives a format an explcit argument set.
599 error(lineno
, 'multiple argument sets')
603 error(lineno
, 'undefined argument set', t
)
606 # '@Foo' gives a pattern an explicit format.
610 error(lineno
, 'multiple formats')
614 error(lineno
, 'undefined format', t
)
617 # '%Foo' imports a field.
620 flds
= add_field_byname(lineno
, flds
, tt
, tt
)
623 # 'Foo=%Bar' imports a field with a different name.
624 if re_fullmatch(re_ident
+ '=%' + re_ident
, t
):
625 (fname
, iname
) = t
.split('=%')
626 flds
= add_field_byname(lineno
, flds
, fname
, iname
)
629 # 'Foo=number' sets an argument field to a constant value
630 if re_fullmatch(re_ident
+ '=[+-]?[0-9]+', t
):
631 (fname
, value
) = t
.split('=')
633 flds
= add_field(lineno
, flds
, fname
, ConstField(value
))
636 # Pattern of 0s, 1s, dots and dashes indicate required zeros,
637 # required ones, or dont-cares.
638 if re_fullmatch('[01.-]+', t
):
640 fms
= t
.replace('0', '1')
641 fms
= fms
.replace('.', '0')
642 fms
= fms
.replace('-', '0')
643 fbs
= t
.replace('.', '0')
644 fbs
= fbs
.replace('-', '0')
645 ubm
= t
.replace('1', '0')
646 ubm
= ubm
.replace('.', '0')
647 ubm
= ubm
.replace('-', '1')
651 fixedbits
= (fixedbits
<< shift
) | fbs
652 fixedmask
= (fixedmask
<< shift
) | fms
653 undefmask
= (undefmask
<< shift
) | ubm
654 # Otherwise, fieldname:fieldwidth
655 elif re_fullmatch(re_ident
+ ':s?[0-9]+', t
):
656 (fname
, flen
) = t
.split(':')
661 shift
= int(flen
, 10)
662 if shift
+ width
> insnwidth
:
663 error(lineno
, 'field {0} exceeds insnwidth'.format(fname
))
664 f
= Field(sign
, insnwidth
- width
- shift
, shift
)
665 flds
= add_field(lineno
, flds
, fname
, f
)
670 error(lineno
, 'invalid token "{0}"'.format(t
))
673 if variablewidth
and width
< insnwidth
and width
% 8 == 0:
674 shift
= insnwidth
- width
678 undefmask |
= (1 << shift
) - 1
680 # We should have filled in all of the bits of the instruction.
681 elif not (is_format
and width
== 0) and width
!= insnwidth
:
682 error(lineno
, 'definition has {0} bits'.format(width
))
684 # Do not check for fields overlaping fields; one valid usage
685 # is to be able to duplicate fields via import.
687 for f
in flds
.values():
690 # Fix up what we've parsed to match either a format or a pattern.
692 # Formats cannot reference formats.
694 error(lineno
, 'format referencing format')
695 # If an argument set is given, then there should be no fields
696 # without a place to store it.
698 for f
in flds
.keys():
699 if f
not in arg
.fields
:
700 error(lineno
, 'field {0} not in argument set {1}'
701 .format(f
, arg
.name
))
703 arg
= infer_argument_set(flds
)
705 error(lineno
, 'duplicate format name', name
)
706 fmt
= Format(name
, lineno
, arg
, fixedbits
, fixedmask
,
707 undefmask
, fieldmask
, flds
, width
)
710 # Patterns can reference a format ...
712 # ... but not an argument simultaneously
714 error(lineno
, 'pattern specifies both format and argument set')
715 if fixedmask
& fmt
.fixedmask
:
716 error(lineno
, 'pattern fixed bits overlap format fixed bits')
717 if width
!= fmt
.width
:
718 error(lineno
, 'pattern uses format of different width')
719 fieldmask |
= fmt
.fieldmask
720 fixedbits |
= fmt
.fixedbits
721 fixedmask |
= fmt
.fixedmask
722 undefmask |
= fmt
.undefmask
724 (fmt
, flds
) = infer_format(arg
, fieldmask
, flds
, width
)
726 for f
in flds
.keys():
727 if f
not in arg
.fields
:
728 error(lineno
, 'field {0} not in argument set {1}'
729 .format(f
, arg
.name
))
730 if f
in fmt
.fields
.keys():
731 error(lineno
, 'field {0} set by format and pattern'.format(f
))
733 if f
not in flds
.keys() and f
not in fmt
.fields
.keys():
734 error(lineno
, 'field {0} not initialized'.format(f
))
735 pat
= Pattern(name
, lineno
, fmt
, fixedbits
, fixedmask
,
736 undefmask
, fieldmask
, flds
, width
)
738 allpatterns
.append(pat
)
740 # Validate the masks that we have assembled.
741 if fieldmask
& fixedmask
:
742 error(lineno
, 'fieldmask overlaps fixedmask (0x{0:08x} & 0x{1:08x})'
743 .format(fieldmask
, fixedmask
))
744 if fieldmask
& undefmask
:
745 error(lineno
, 'fieldmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
746 .format(fieldmask
, undefmask
))
747 if fixedmask
& undefmask
:
748 error(lineno
, 'fixedmask overlaps undefmask (0x{0:08x} & 0x{1:08x})'
749 .format(fixedmask
, undefmask
))
751 allbits
= fieldmask | fixedmask | undefmask
752 if allbits
!= insnmask
:
753 error(lineno
, 'bits left unspecified (0x{0:08x})'
754 .format(allbits ^ insnmask
))
757 def build_multi_pattern(lineno
, pats
):
758 """Validate the Patterns going into a MultiPattern."""
763 error(lineno
, 'less than two patterns within braces')
768 # Collect fixed/undefmask for all of the children.
769 # Move the defining lineno back to that of the first child.
771 fixedmask
&= p
.fixedmask
772 undefmask
&= p
.undefmask
773 if p
.lineno
< lineno
:
780 elif width
!= p
.width
:
781 error(lineno
, 'width mismatch in patterns within braces')
786 error(lineno
, 'no overlap in patterns within braces')
789 thisbits
= p
.fixedbits
& fixedmask
790 if fixedbits
is None:
792 elif fixedbits
!= thisbits
:
793 fixedmask
&= ~
(fixedbits ^ thisbits
)
798 mp
= MultiPattern(lineno
, pats
, fixedbits
, fixedmask
, undefmask
, width
)
800 # end build_multi_pattern
803 """Parse all of the patterns within a file"""
807 # Read all of the lines of the file. Concatenate lines
808 # ending in backslash; discard empty lines and comments.
817 # Expand and strip spaces, to find indent.
819 line
= line
.expandtabs()
831 # Next line after continuation
834 # Allow completely blank lines.
838 # Empty line due to comment.
840 # Indentation must be correct, even for comment lines.
841 if indent
!= nesting
:
842 error(lineno
, 'indentation ', indent
, ' != ', nesting
)
844 start_lineno
= lineno
858 error(start_lineno
, 'mismatched close brace')
860 error(start_lineno
, 'extra tokens after close brace')
862 if indent
!= nesting
:
863 error(start_lineno
, 'indentation ', indent
, ' != ', nesting
)
865 patterns
= saved_pats
.pop()
866 build_multi_pattern(lineno
, pats
)
870 # Everything else should have current indentation.
871 if indent
!= nesting
:
872 error(start_lineno
, 'indentation ', indent
, ' != ', nesting
)
877 error(start_lineno
, 'extra tokens after open brace')
878 saved_pats
.append(patterns
)
884 # Determine the type of object needing to be parsed.
886 parse_field(start_lineno
, name
[1:], toks
)
888 parse_arguments(start_lineno
, name
[1:], toks
)
890 parse_generic(start_lineno
, True, name
[1:], toks
)
892 parse_generic(start_lineno
, False, name
, toks
)
898 """Class representing a node in a decode tree"""
900 def __init__(self
, fm
, tm
):
908 r
= '{0}{1:08x}'.format(ind
, self
.fixedmask
)
910 r
+= ' ' + self
.format
.name
912 for (b
, s
) in self
.subs
:
913 r
+= '{0} {1:08x}:\n'.format(ind
, b
)
914 r
+= s
.str1(i
+ 4) + '\n'
921 def output_code(self
, i
, extracted
, outerbits
, outermask
):
924 # If we identified all nodes below have the same format,
925 # extract the fields now.
926 if not extracted
and self
.base
:
927 output(ind
, self
.base
.extract_name(),
928 '(ctx, &u.f_', self
.base
.base
.name
, ', insn);\n')
931 # Attempt to aid the compiler in producing compact switch statements.
932 # If the bits in the mask are contiguous, extract them.
933 sh
= is_contiguous(self
.thismask
)
935 # Propagate SH down into the local functions.
936 def str_switch(b
, sh
=sh
):
937 return '(insn >> {0}) & 0x{1:x}'.format(sh
, b
>> sh
)
939 def str_case(b
, sh
=sh
):
940 return '0x{0:x}'.format(b
>> sh
)
943 return 'insn & 0x{0:08x}'.format(b
)
946 return '0x{0:08x}'.format(b
)
948 output(ind
, 'switch (', str_switch(self
.thismask
), ') {\n')
949 for b
, s
in sorted(self
.subs
):
950 assert (self
.thismask
& ~s
.fixedmask
) == 0
951 innermask
= outermask | self
.thismask
952 innerbits
= outerbits | b
953 output(ind
, 'case ', str_case(b
), ':\n')
955 str_match_bits(innerbits
, innermask
), ' */\n')
956 s
.output_code(i
+ 4, extracted
, innerbits
, innermask
)
957 output(ind
, ' return false;\n')
962 def build_tree(pats
, outerbits
, outermask
):
963 # Find the intersection of all remaining fixedmask.
964 innermask
= ~outermask
& insnmask
966 innermask
&= i
.fixedmask
969 text
= 'overlapping patterns:'
971 text
+= '\n' + p
.file + ':' + str(p
.lineno
) + ': ' + str(p
)
972 error_with_file(pats
[0].file, pats
[0].lineno
, text
)
974 fullmask
= outermask | innermask
976 # Sort each element of pats into the bin selected by the mask.
979 fb
= i
.fixedbits
& innermask
985 # We must recurse if any bin has more than one element or if
986 # the single element in the bin has not been fully matched.
987 t
= Tree(fullmask
, innermask
)
989 for b
, l
in bins
.items():
991 if len(l
) > 1 or s
.fixedmask
& ~fullmask
!= 0:
992 s
= build_tree(l
, b | outerbits
, fullmask
)
993 t
.subs
.append((b
, s
))
1000 """Class representing a node in a size decode tree"""
1002 def __init__(self
, m
, w
):
1010 r
= '{0}{1:08x}'.format(ind
, self
.mask
)
1012 for (b
, s
) in self
.subs
:
1013 r
+= '{0} {1:08x}:\n'.format(ind
, b
)
1014 r
+= s
.str1(i
+ 4) + '\n'
1021 def output_code(self
, i
, extracted
, outerbits
, outermask
):
1024 # If we need to load more bytes to test, do so now.
1025 if extracted
< self
.width
:
1026 output(ind
, 'insn = ', decode_function
,
1027 '_load_bytes(ctx, insn, {0}, {1});\n'
1028 .format(extracted
/ 8, self
.width
/ 8));
1029 extracted
= self
.width
1031 # Attempt to aid the compiler in producing compact switch statements.
1032 # If the bits in the mask are contiguous, extract them.
1033 sh
= is_contiguous(self
.mask
)
1035 # Propagate SH down into the local functions.
1036 def str_switch(b
, sh
=sh
):
1037 return '(insn >> {0}) & 0x{1:x}'.format(sh
, b
>> sh
)
1039 def str_case(b
, sh
=sh
):
1040 return '0x{0:x}'.format(b
>> sh
)
1043 return 'insn & 0x{0:08x}'.format(b
)
1046 return '0x{0:08x}'.format(b
)
1048 output(ind
, 'switch (', str_switch(self
.mask
), ') {\n')
1049 for b
, s
in sorted(self
.subs
):
1050 innermask
= outermask | self
.mask
1051 innerbits
= outerbits | b
1052 output(ind
, 'case ', str_case(b
), ':\n')
1054 str_match_bits(innerbits
, innermask
), ' */\n')
1055 s
.output_code(i
+ 4, extracted
, innerbits
, innermask
)
1057 output(ind
, 'return insn;\n')
1061 """Class representing a leaf node in a size decode tree"""
1063 def __init__(self
, m
, w
):
1069 return '{0}{1:08x}'.format(ind
, self
.mask
)
1074 def output_code(self
, i
, extracted
, outerbits
, outermask
):
1075 global decode_function
1078 # If we need to load more bytes, do so now.
1079 if extracted
< self
.width
:
1080 output(ind
, 'insn = ', decode_function
,
1081 '_load_bytes(ctx, insn, {0}, {1});\n'
1082 .format(extracted
/ 8, self
.width
/ 8));
1083 extracted
= self
.width
1084 output(ind
, 'return insn;\n')
1088 def build_size_tree(pats
, width
, outerbits
, outermask
):
1091 # Collect the mask of bits that are fixed in this width
1092 innermask
= 0xff << (insnwidth
- width
)
1093 innermask
&= ~outermask
1097 innermask
&= i
.fixedmask
1098 if minwidth
is None:
1100 elif minwidth
!= i
.width
:
1102 if minwidth
< i
.width
:
1106 return SizeLeaf(innermask
, minwidth
)
1109 if width
< minwidth
:
1110 return build_size_tree(pats
, width
+ 8, outerbits
, outermask
)
1114 pnames
.append(p
.name
+ ':' + p
.file + ':' + str(p
.lineno
))
1115 error_with_file(pats
[0].file, pats
[0].lineno
,
1116 'overlapping patterns size {0}:'.format(width
), pnames
)
1120 fb
= i
.fixedbits
& innermask
1126 fullmask
= outermask | innermask
1127 lens
= sorted(bins
.keys())
1130 return build_size_tree(bins
[b
], width
+ 8, b | outerbits
, fullmask
)
1132 r
= SizeTree(innermask
, width
)
1133 for b
, l
in bins
.items():
1134 s
= build_size_tree(l
, width
, b | outerbits
, fullmask
)
1135 r
.subs
.append((b
, s
))
1137 # end build_size_tree
1140 def prop_format(tree
):
1141 """Propagate Format objects into the decode tree"""
1143 # Depth first search.
1144 for (b
, s
) in tree
.subs
:
1145 if isinstance(s
, Tree
):
1148 # If all entries in SUBS have the same format, then
1149 # propagate that into the tree.
1151 for (b
, s
) in tree
.subs
:
1162 def prop_size(tree
):
1163 """Propagate minimum widths up the decode size tree"""
1165 if isinstance(tree
, SizeTree
):
1167 for (b
, s
) in tree
.subs
:
1168 width
= prop_size(s
)
1169 if min is None or min > width
:
1171 assert min >= tree
.width
1184 global translate_scope
1185 global translate_prefix
1192 global decode_function
1193 global variablewidth
1196 decode_scope
= 'static '
1198 long_opts
= ['decode=', 'translate=', 'output=', 'insnwidth=',
1199 'static-decode=', 'varinsnwidth=']
1201 (opts
, args
) = getopt
.getopt(sys
.argv
[1:], 'o:vw:', long_opts
)
1202 except getopt
.GetoptError
as err
:
1205 if o
in ('-o', '--output'):
1207 elif o
== '--decode':
1210 elif o
== '--static-decode':
1212 elif o
== '--translate':
1213 translate_prefix
= a
1214 translate_scope
= ''
1215 elif o
in ('-w', '--insnwidth', '--varinsnwidth'):
1216 if o
== '--varinsnwidth':
1217 variablewidth
= True
1220 insntype
= 'uint16_t'
1222 elif insnwidth
!= 32:
1223 error(0, 'cannot handle insns of width', insnwidth
)
1225 assert False, 'unhandled option'
1228 error(0, 'missing input file')
1229 for filename
in args
:
1230 input_file
= filename
1231 f
= open(filename
, 'r')
1236 stree
= build_size_tree(patterns
, 8, 0, 0)
1239 dtree
= build_tree(patterns
, 0, 0)
1243 output_fd
= open(output_file
, 'w')
1245 output_fd
= sys
.stdout
1248 for n
in sorted(arguments
.keys()):
1252 # A single translate function can be invoked for different patterns.
1253 # Make sure that the argument sets are the same, and declare the
1254 # function only once.
1256 # If we're sharing formats, we're likely also sharing trans_* functions,
1257 # but we can't tell which ones. Prevent issues from the compiler by
1258 # suppressing redundant declaration warnings.
1260 output("#ifdef CONFIG_PRAGMA_DIAGNOSTIC_AVAILABLE\n",
1261 "# pragma GCC diagnostic push\n",
1262 "# pragma GCC diagnostic ignored \"-Wredundant-decls\"\n",
1263 "# ifdef __clang__\n"
1264 "# pragma GCC diagnostic ignored \"-Wtypedef-redefinition\"\n",
1269 for i
in allpatterns
:
1270 if i
.name
in out_pats
:
1271 p
= out_pats
[i
.name
]
1272 if i
.base
.base
!= p
.base
.base
:
1273 error(0, i
.name
, ' has conflicting argument sets')
1276 out_pats
[i
.name
] = i
1280 output("#ifdef CONFIG_PRAGMA_DIAGNOSTIC_AVAILABLE\n",
1281 "# pragma GCC diagnostic pop\n",
1284 for n
in sorted(formats
.keys()):
1288 output(decode_scope
, 'bool ', decode_function
,
1289 '(DisasContext *ctx, ', insntype
, ' insn)\n{\n')
1293 if len(allpatterns
) != 0:
1294 output(i4
, 'union {\n')
1295 for n
in sorted(arguments
.keys()):
1297 output(i4
, i4
, f
.struct_name(), ' f_', f
.name
, ';\n')
1298 output(i4
, '} u;\n\n')
1299 dtree
.output_code(4, False, 0, 0)
1301 output(i4
, 'return false;\n')
1305 output('\n', decode_scope
, insntype
, ' ', decode_function
,
1306 '_load(DisasContext *ctx)\n{\n',
1307 ' ', insntype
, ' insn = 0;\n\n')
1308 stree
.output_code(4, 0, 0, 0)
1316 if __name__
== '__main__':