decodetree.py 31 KB

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