Various changes to I/O, addition of PciFake device to improve FreeBSD compatibility.
[gem5.git] / arch / isa_parser.py
1 #! /usr/bin/env python
2
3 # Copyright (c) 2003-2005 The Regents of The University of Michigan
4 # All rights reserved.
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are
8 # met: redistributions of source code must retain the above copyright
9 # notice, this list of conditions and the following disclaimer;
10 # redistributions in binary form must reproduce the above copyright
11 # notice, this list of conditions and the following disclaimer in the
12 # documentation and/or other materials provided with the distribution;
13 # neither the name of the copyright holders nor the names of its
14 # contributors may be used to endorse or promote products derived from
15 # this software without specific prior written permission.
16 #
17 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29 import os
30 import sys
31 import re
32 import string
33 import traceback
34 # get type names
35 from types import *
36
37 # Prepend the directory where the PLY lex & yacc modules are found
38 # to the search path. Assumes we're compiling in a subdirectory
39 # of 'build' in the current tree.
40 sys.path[0:0] = [os.environ['M5_EXT'] + '/ply']
41
42 import lex
43 import yacc
44
45 #####################################################################
46 #
47 # Lexer
48 #
49 # The PLY lexer module takes two things as input:
50 # - A list of token names (the string list 'tokens')
51 # - A regular expression describing a match for each token. The
52 # regexp for token FOO can be provided in two ways:
53 # - as a string variable named t_FOO
54 # - as the doc string for a function named t_FOO. In this case,
55 # the function is also executed, allowing an action to be
56 # associated with each token match.
57 #
58 #####################################################################
59
60 # Reserved words. These are listed separately as they are matched
61 # using the same regexp as generic IDs, but distinguished in the
62 # t_ID() function. The PLY documentation suggests this approach.
63 reserved = (
64 'BITFIELD', 'DECODE', 'DECODER', 'DEFAULT', 'DEF', 'EXEC', 'FORMAT',
65 'HEADER', 'LET', 'NAMESPACE', 'OPERAND_TYPES', 'OPERANDS',
66 'OUTPUT', 'SIGNED', 'TEMPLATE'
67 )
68
69 # List of tokens. The lex module requires this.
70 tokens = reserved + (
71 # identifier
72 'ID',
73
74 # integer literal
75 'INTLIT',
76
77 # string literal
78 'STRLIT',
79
80 # code literal
81 'CODELIT',
82
83 # ( ) [ ] { } < > , ; : :: *
84 'LPAREN', 'RPAREN',
85 # not used any more... commented out to suppress PLY warning
86 # 'LBRACKET', 'RBRACKET',
87 'LBRACE', 'RBRACE',
88 'LESS', 'GREATER',
89 'COMMA', 'SEMI', 'COLON', 'DBLCOLON',
90 'ASTERISK',
91
92 # C preprocessor directives
93 'CPPDIRECTIVE'
94 )
95
96 # Regular expressions for token matching
97 t_LPAREN = r'\('
98 t_RPAREN = r'\)'
99 # not used any more... commented out to suppress PLY warning
100 # t_LBRACKET = r'\['
101 # t_RBRACKET = r'\]'
102 t_LBRACE = r'\{'
103 t_RBRACE = r'\}'
104 t_LESS = r'\<'
105 t_GREATER = r'\>'
106 t_COMMA = r','
107 t_SEMI = r';'
108 t_COLON = r':'
109 t_DBLCOLON = r'::'
110 t_ASTERISK = r'\*'
111
112 # Identifiers and reserved words
113 reserved_map = { }
114 for r in reserved:
115 reserved_map[r.lower()] = r
116
117 def t_ID(t):
118 r'[A-Za-z_]\w*'
119 t.type = reserved_map.get(t.value,'ID')
120 return t
121
122 # Integer literal
123 def t_INTLIT(t):
124 r'(0x[\da-fA-F]+)|\d+'
125 try:
126 t.value = int(t.value,0)
127 except ValueError:
128 error(t.lineno, 'Integer value "%s" too large' % t.value)
129 t.value = 0
130 return t
131
132 # String literal. Note that these use only single quotes, and
133 # can span multiple lines.
134 def t_STRLIT(t):
135 r"(?m)'([^'])+'"
136 # strip off quotes
137 t.value = t.value[1:-1]
138 t.lineno += t.value.count('\n')
139 return t
140
141
142 # "Code literal"... like a string literal, but delimiters are
143 # '{{' and '}}' so they get formatted nicely under emacs c-mode
144 def t_CODELIT(t):
145 r"(?m)\{\{([^\}]|}(?!\}))+\}\}"
146 # strip off {{ & }}
147 t.value = t.value[2:-2]
148 t.lineno += t.value.count('\n')
149 return t
150
151 def t_CPPDIRECTIVE(t):
152 r'^\#.*\n'
153 t.lineno += t.value.count('\n')
154 return t
155
156 #
157 # The functions t_NEWLINE, t_ignore, and t_error are
158 # special for the lex module.
159 #
160
161 # Newlines
162 def t_NEWLINE(t):
163 r'\n+'
164 t.lineno += t.value.count('\n')
165
166 # Comments
167 def t_comment(t):
168 r'//.*'
169
170 # Completely ignored characters
171 t_ignore = ' \t\x0c'
172
173 # Error handler
174 def t_error(t):
175 error(t.lineno, "illegal character '%s'" % t.value[0])
176 t.skip(1)
177
178 # Build the lexer
179 lex.lex()
180
181 #####################################################################
182 #
183 # Parser
184 #
185 # Every function whose name starts with 'p_' defines a grammar rule.
186 # The rule is encoded in the function's doc string, while the
187 # function body provides the action taken when the rule is matched.
188 # The argument to each function is a list of the values of the
189 # rule's symbols: t[0] for the LHS, and t[1..n] for the symbols
190 # on the RHS. For tokens, the value is copied from the t.value
191 # attribute provided by the lexer. For non-terminals, the value
192 # is assigned by the producing rule; i.e., the job of the grammar
193 # rule function is to set the value for the non-terminal on the LHS
194 # (by assigning to t[0]).
195 #####################################################################
196
197 # The LHS of the first grammar rule is used as the start symbol
198 # (in this case, 'specification'). Note that this rule enforces
199 # that there will be exactly one namespace declaration, with 0 or more
200 # global defs/decls before and after it. The defs & decls before
201 # the namespace decl will be outside the namespace; those after
202 # will be inside. The decoder function is always inside the namespace.
203 def p_specification(t):
204 'specification : opt_defs_and_outputs name_decl opt_defs_and_outputs decode_block'
205 global_code = t[1]
206 isa_name = t[2]
207 namespace = isa_name + "Inst"
208 # wrap the decode block as a function definition
209 t[4].wrap_decode_block('''
210 StaticInstPtr<%(isa_name)s>
211 %(isa_name)s::decodeInst(%(isa_name)s::MachInst machInst)
212 {
213 using namespace %(namespace)s;
214 ''' % vars(), '}')
215 # both the latter output blocks and the decode block are in the namespace
216 namespace_code = t[3] + t[4]
217 # pass it all back to the caller of yacc.parse()
218 t[0] = (isa_name, namespace, global_code, namespace_code)
219
220 # ISA name declaration looks like "namespace <foo>;"
221 def p_name_decl(t):
222 'name_decl : NAMESPACE ID SEMI'
223 t[0] = t[2]
224
225 # 'opt_defs_and_outputs' is a possibly empty sequence of
226 # def and/or output statements.
227 def p_opt_defs_and_outputs_0(t):
228 'opt_defs_and_outputs : empty'
229 t[0] = GenCode()
230
231 def p_opt_defs_and_outputs_1(t):
232 'opt_defs_and_outputs : defs_and_outputs'
233 t[0] = t[1]
234
235 def p_defs_and_outputs_0(t):
236 'defs_and_outputs : def_or_output'
237 t[0] = t[1]
238
239 def p_defs_and_outputs_1(t):
240 'defs_and_outputs : defs_and_outputs def_or_output'
241 t[0] = t[1] + t[2]
242
243 # The list of possible definition/output statements.
244 def p_def_or_output(t):
245 '''def_or_output : def_format
246 | def_bitfield
247 | def_template
248 | def_operand_types
249 | def_operands
250 | output_header
251 | output_decoder
252 | output_exec
253 | global_let'''
254 t[0] = t[1]
255
256 # Output blocks 'output <foo> {{...}}' (C++ code blocks) are copied
257 # directly to the appropriate output section.
258
259 # Massage output block by substituting in template definitions and bit
260 # operators. We handle '%'s embedded in the string that don't
261 # indicate template substitutions (or CPU-specific symbols, which get
262 # handled in GenCode) by doubling them first so that the format
263 # operation will reduce them back to single '%'s.
264 def process_output(s):
265 # protect any non-substitution '%'s (not followed by '(')
266 s = re.sub(r'%(?!\()', '%%', s)
267 # protects cpu-specific symbols too
268 s = protect_cpu_symbols(s)
269 return substBitOps(s % templateMap)
270
271 def p_output_header(t):
272 'output_header : OUTPUT HEADER CODELIT SEMI'
273 t[0] = GenCode(header_output = process_output(t[3]))
274
275 def p_output_decoder(t):
276 'output_decoder : OUTPUT DECODER CODELIT SEMI'
277 t[0] = GenCode(decoder_output = process_output(t[3]))
278
279 def p_output_exec(t):
280 'output_exec : OUTPUT EXEC CODELIT SEMI'
281 t[0] = GenCode(exec_output = process_output(t[3]))
282
283 # global let blocks 'let {{...}}' (Python code blocks) are executed
284 # directly when seen. Note that these execute in a special variable
285 # context 'exportContext' to prevent the code from polluting this
286 # script's namespace.
287 def p_global_let(t):
288 'global_let : LET CODELIT SEMI'
289 updateExportContext()
290 try:
291 exec fixPythonIndentation(t[2]) in exportContext
292 except Exception, exc:
293 error(t.lineno(1),
294 'error: %s in global let block "%s".' % (exc, t[2]))
295 t[0] = GenCode() # contributes nothing to the output C++ file
296
297 # Define the mapping from operand type extensions to C++ types and bit
298 # widths (stored in operandTypeMap).
299 def p_def_operand_types(t):
300 'def_operand_types : DEF OPERAND_TYPES CODELIT SEMI'
301 s = 'global operandTypeMap; operandTypeMap = {' + t[3] + '}'
302 try:
303 exec s
304 except Exception, exc:
305 error(t.lineno(1),
306 'error: %s in def operand_types block "%s".' % (exc, t[3]))
307 t[0] = GenCode() # contributes nothing to the output C++ file
308
309 # Define the mapping from operand names to operand classes and other
310 # traits. Stored in operandTraitsMap.
311 def p_def_operands(t):
312 'def_operands : DEF OPERANDS CODELIT SEMI'
313 s = 'global operandTraitsMap; operandTraitsMap = {' + t[3] + '}'
314 try:
315 exec s
316 except Exception, exc:
317 error(t.lineno(1),
318 'error: %s in def operands block "%s".' % (exc, t[3]))
319 defineDerivedOperandVars()
320 t[0] = GenCode() # contributes nothing to the output C++ file
321
322 # A bitfield definition looks like:
323 # 'def [signed] bitfield <ID> [<first>:<last>]'
324 # This generates a preprocessor macro in the output file.
325 def p_def_bitfield_0(t):
326 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT COLON INTLIT GREATER SEMI'
327 expr = 'bits(machInst, %2d, %2d)' % (t[6], t[8])
328 if (t[2] == 'signed'):
329 expr = 'sext<%d>(%s)' % (t[6] - t[8] + 1, expr)
330 hash_define = '#undef %s\n#define %s\t%s\n' % (t[4], t[4], expr)
331 t[0] = GenCode(header_output = hash_define)
332
333 # alternate form for single bit: 'def [signed] bitfield <ID> [<bit>]'
334 def p_def_bitfield_1(t):
335 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT GREATER SEMI'
336 expr = 'bits(machInst, %2d, %2d)' % (t[6], t[6])
337 if (t[2] == 'signed'):
338 expr = 'sext<%d>(%s)' % (1, expr)
339 hash_define = '#undef %s\n#define %s\t%s\n' % (t[4], t[4], expr)
340 t[0] = GenCode(header_output = hash_define)
341
342 def p_opt_signed_0(t):
343 'opt_signed : SIGNED'
344 t[0] = t[1]
345
346 def p_opt_signed_1(t):
347 'opt_signed : empty'
348 t[0] = ''
349
350 # Global map variable to hold templates
351 templateMap = {}
352
353 def p_def_template(t):
354 'def_template : DEF TEMPLATE ID CODELIT SEMI'
355 templateMap[t[3]] = Template(t[4])
356 t[0] = GenCode()
357
358 # An instruction format definition looks like
359 # "def format <fmt>(<params>) {{...}};"
360 def p_def_format(t):
361 'def_format : DEF FORMAT ID LPAREN param_list RPAREN CODELIT SEMI'
362 (id, params, code) = (t[3], t[5], t[7])
363 defFormat(id, params, code, t.lineno(1))
364 t[0] = GenCode()
365
366 # The formal parameter list for an instruction format is a possibly
367 # empty list of comma-separated parameters.
368 def p_param_list_0(t):
369 'param_list : empty'
370 t[0] = [ ]
371
372 def p_param_list_1(t):
373 'param_list : param'
374 t[0] = [t[1]]
375
376 def p_param_list_2(t):
377 'param_list : param_list COMMA param'
378 t[0] = t[1]
379 t[0].append(t[3])
380
381 # Each formal parameter is either an identifier or an identifier
382 # preceded by an asterisk. As in Python, the latter (if present) gets
383 # a tuple containing all the excess positional arguments, allowing
384 # varargs functions.
385 def p_param_0(t):
386 'param : ID'
387 t[0] = t[1]
388
389 def p_param_1(t):
390 'param : ASTERISK ID'
391 # just concatenate them: '*ID'
392 t[0] = t[1] + t[2]
393
394 # End of format definition-related rules.
395 ##############
396
397 #
398 # A decode block looks like:
399 # decode <field1> [, <field2>]* [default <inst>] { ... }
400 #
401 def p_decode_block(t):
402 'decode_block : DECODE ID opt_default LBRACE decode_stmt_list RBRACE'
403 default_defaults = defaultStack.pop()
404 codeObj = t[5]
405 # use the "default defaults" only if there was no explicit
406 # default statement in decode_stmt_list
407 if not codeObj.has_decode_default:
408 codeObj += default_defaults
409 codeObj.wrap_decode_block('switch (%s) {\n' % t[2], '}\n')
410 t[0] = codeObj
411
412 # The opt_default statement serves only to push the "default defaults"
413 # onto defaultStack. This value will be used by nested decode blocks,
414 # and used and popped off when the current decode_block is processed
415 # (in p_decode_block() above).
416 def p_opt_default_0(t):
417 'opt_default : empty'
418 # no default specified: reuse the one currently at the top of the stack
419 defaultStack.push(defaultStack.top())
420 # no meaningful value returned
421 t[0] = None
422
423 def p_opt_default_1(t):
424 'opt_default : DEFAULT inst'
425 # push the new default
426 codeObj = t[2]
427 codeObj.wrap_decode_block('\ndefault:\n', 'break;\n')
428 defaultStack.push(codeObj)
429 # no meaningful value returned
430 t[0] = None
431
432 def p_decode_stmt_list_0(t):
433 'decode_stmt_list : decode_stmt'
434 t[0] = t[1]
435
436 def p_decode_stmt_list_1(t):
437 'decode_stmt_list : decode_stmt decode_stmt_list'
438 if (t[1].has_decode_default and t[2].has_decode_default):
439 error(t.lineno(1), 'Two default cases in decode block')
440 t[0] = t[1] + t[2]
441
442 #
443 # Decode statement rules
444 #
445 # There are four types of statements allowed in a decode block:
446 # 1. Format blocks 'format <foo> { ... }'
447 # 2. Nested decode blocks
448 # 3. Instruction definitions.
449 # 4. C preprocessor directives.
450
451
452 # Preprocessor directives found in a decode statement list are passed
453 # through to the output, replicated to all of the output code
454 # streams. This works well for ifdefs, so we can ifdef out both the
455 # declarations and the decode cases generated by an instruction
456 # definition. Handling them as part of the grammar makes it easy to
457 # keep them in the right place with respect to the code generated by
458 # the other statements.
459 def p_decode_stmt_cpp(t):
460 'decode_stmt : CPPDIRECTIVE'
461 t[0] = GenCode(t[1], t[1], t[1], t[1])
462
463 # A format block 'format <foo> { ... }' sets the default instruction
464 # format used to handle instruction definitions inside the block.
465 # This format can be overridden by using an explicit format on the
466 # instruction definition or with a nested format block.
467 def p_decode_stmt_format(t):
468 'decode_stmt : FORMAT push_format_id LBRACE decode_stmt_list RBRACE'
469 # The format will be pushed on the stack when 'push_format_id' is
470 # processed (see below). Once the parser has recognized the full
471 # production (though the right brace), we're done with the format,
472 # so now we can pop it.
473 formatStack.pop()
474 t[0] = t[4]
475
476 # This rule exists so we can set the current format (& push the stack)
477 # when we recognize the format name part of the format block.
478 def p_push_format_id(t):
479 'push_format_id : ID'
480 try:
481 formatStack.push(formatMap[t[1]])
482 t[0] = ('', '// format %s' % t[1])
483 except KeyError:
484 error(t.lineno(1), 'instruction format "%s" not defined.' % t[1])
485
486 # Nested decode block: if the value of the current field matches the
487 # specified constant, do a nested decode on some other field.
488 def p_decode_stmt_decode(t):
489 'decode_stmt : case_label COLON decode_block'
490 label = t[1]
491 codeObj = t[3]
492 # just wrap the decoding code from the block as a case in the
493 # outer switch statement.
494 codeObj.wrap_decode_block('\n%s:\n' % label)
495 codeObj.has_decode_default = (label == 'default')
496 t[0] = codeObj
497
498 # Instruction definition (finally!).
499 def p_decode_stmt_inst(t):
500 'decode_stmt : case_label COLON inst SEMI'
501 label = t[1]
502 codeObj = t[3]
503 codeObj.wrap_decode_block('\n%s:' % label, 'break;\n')
504 codeObj.has_decode_default = (label == 'default')
505 t[0] = codeObj
506
507 # The case label is either a list of one or more constants or 'default'
508 def p_case_label_0(t):
509 'case_label : intlit_list'
510 t[0] = ': '.join(map(lambda a: 'case %#x' % a, t[1]))
511
512 def p_case_label_1(t):
513 'case_label : DEFAULT'
514 t[0] = 'default'
515
516 #
517 # The constant list for a decode case label must be non-empty, but may have
518 # one or more comma-separated integer literals in it.
519 #
520 def p_intlit_list_0(t):
521 'intlit_list : INTLIT'
522 t[0] = [t[1]]
523
524 def p_intlit_list_1(t):
525 'intlit_list : intlit_list COMMA INTLIT'
526 t[0] = t[1]
527 t[0].append(t[3])
528
529 # Define an instruction using the current instruction format (specified
530 # by an enclosing format block).
531 # "<mnemonic>(<args>)"
532 def p_inst_0(t):
533 'inst : ID LPAREN arg_list RPAREN'
534 # Pass the ID and arg list to the current format class to deal with.
535 currentFormat = formatStack.top()
536 codeObj = currentFormat.defineInst(t[1], t[3], t.lineno(1))
537 args = ','.join(map(str, t[3]))
538 args = re.sub('(?m)^', '//', args)
539 args = re.sub('^//', '', args)
540 comment = '\n// %s::%s(%s)\n' % (currentFormat.id, t[1], args)
541 codeObj.prepend_all(comment)
542 t[0] = codeObj
543
544 # Define an instruction using an explicitly specified format:
545 # "<fmt>::<mnemonic>(<args>)"
546 def p_inst_1(t):
547 'inst : ID DBLCOLON ID LPAREN arg_list RPAREN'
548 try:
549 format = formatMap[t[1]]
550 except KeyError:
551 error(t.lineno(1), 'instruction format "%s" not defined.' % t[1])
552 codeObj = format.defineInst(t[3], t[5], t.lineno(1))
553 comment = '\n// %s::%s(%s)\n' % (t[1], t[3], t[5])
554 codeObj.prepend_all(comment)
555 t[0] = codeObj
556
557 def p_arg_list_0(t):
558 'arg_list : empty'
559 t[0] = [ ]
560
561 def p_arg_list_1(t):
562 'arg_list : arg'
563 t[0] = [t[1]]
564
565 def p_arg_list_2(t):
566 'arg_list : arg_list COMMA arg'
567 t[0] = t[1]
568 t[0].append(t[3])
569
570 def p_arg(t):
571 '''arg : ID
572 | INTLIT
573 | STRLIT
574 | CODELIT'''
575 t[0] = t[1]
576
577 #
578 # Empty production... use in other rules for readability.
579 #
580 def p_empty(t):
581 'empty :'
582 pass
583
584 # Parse error handler. Note that the argument here is the offending
585 # *token*, not a grammar symbol (hence the need to use t.value)
586 def p_error(t):
587 if t:
588 error(t.lineno, "syntax error at '%s'" % t.value)
589 else:
590 error_bt(0, "unknown syntax error")
591
592 # END OF GRAMMAR RULES
593 #
594 # Now build the parser.
595 yacc.yacc()
596
597
598 #####################################################################
599 #
600 # Support Classes
601 #
602 #####################################################################
603
604 ################
605 # CpuModel class
606 #
607 # The CpuModel class encapsulates everything we need to know about a
608 # particular CPU model.
609
610 class CpuModel:
611 # List of all CPU models. Accessible as CpuModel.list.
612 list = []
613
614 # Constructor. Automatically adds models to CpuModel.list.
615 def __init__(self, name, filename, includes, strings):
616 self.name = name
617 self.filename = filename # filename for output exec code
618 self.includes = includes # include files needed in exec file
619 # The 'strings' dict holds all the per-CPU symbols we can
620 # substitute into templates etc.
621 self.strings = strings
622 # Add self to list.
623 CpuModel.list.append(self)
624
625 # Define CPU models. The following lines should contain the only
626 # CPU-model-specific information in this file. Note that the ISA
627 # description itself should have *no* CPU-model-specific content.
628 CpuModel('SimpleCPU', 'simple_cpu_exec.cc',
629 '#include "cpu/simple/cpu.hh"',
630 { 'CPU_exec_context': 'SimpleCPU' })
631 CpuModel('FastCPU', 'fast_cpu_exec.cc',
632 '#include "cpu/fast/cpu.hh"',
633 { 'CPU_exec_context': 'FastCPU' })
634 CpuModel('FullCPU', 'full_cpu_exec.cc',
635 '#include "encumbered/cpu/full/dyn_inst.hh"',
636 { 'CPU_exec_context': 'DynInst' })
637 CpuModel('AlphaFullCPU', 'alpha_o3_exec.cc',
638 '#include "cpu/o3/alpha_dyn_inst.hh"',
639 { 'CPU_exec_context': 'AlphaDynInst<AlphaSimpleImpl>' })
640
641 # Expand template with CPU-specific references into a dictionary with
642 # an entry for each CPU model name. The entry key is the model name
643 # and the corresponding value is the template with the CPU-specific
644 # refs substituted for that model.
645 def expand_cpu_symbols_to_dict(template):
646 # Protect '%'s that don't go with CPU-specific terms
647 t = re.sub(r'%(?!\(CPU_)', '%%', template)
648 result = {}
649 for cpu in CpuModel.list:
650 result[cpu.name] = t % cpu.strings
651 return result
652
653 # *If* the template has CPU-specific references, return a single
654 # string containing a copy of the template for each CPU model with the
655 # corresponding values substituted in. If the template has no
656 # CPU-specific references, it is returned unmodified.
657 def expand_cpu_symbols_to_string(template):
658 if template.find('%(CPU_') != -1:
659 return reduce(lambda x,y: x+y,
660 expand_cpu_symbols_to_dict(template).values())
661 else:
662 return template
663
664 # Protect CPU-specific references by doubling the corresponding '%'s
665 # (in preparation for substituting a different set of references into
666 # the template).
667 def protect_cpu_symbols(template):
668 return re.sub(r'%(?=\(CPU_)', '%%', template)
669
670 ###############
671 # GenCode class
672 #
673 # The GenCode class encapsulates generated code destined for various
674 # output files. The header_output and decoder_output attributes are
675 # strings containing code destined for decoder.hh and decoder.cc
676 # respectively. The decode_block attribute contains code to be
677 # incorporated in the decode function itself (that will also end up in
678 # decoder.cc). The exec_output attribute is a dictionary with a key
679 # for each CPU model name; the value associated with a particular key
680 # is the string of code for that CPU model's exec.cc file. The
681 # has_decode_default attribute is used in the decode block to allow
682 # explicit default clauses to override default default clauses.
683
684 class GenCode:
685 # Constructor. At this point we substitute out all CPU-specific
686 # symbols. For the exec output, these go into the per-model
687 # dictionary. For all other output types they get collapsed into
688 # a single string.
689 def __init__(self,
690 header_output = '', decoder_output = '', exec_output = '',
691 decode_block = '', has_decode_default = False):
692 self.header_output = expand_cpu_symbols_to_string(header_output)
693 self.decoder_output = expand_cpu_symbols_to_string(decoder_output)
694 if isinstance(exec_output, dict):
695 self.exec_output = exec_output
696 elif isinstance(exec_output, str):
697 # If the exec_output arg is a single string, we replicate
698 # it for each of the CPU models, substituting and
699 # %(CPU_foo)s params appropriately.
700 self.exec_output = expand_cpu_symbols_to_dict(exec_output)
701 self.decode_block = expand_cpu_symbols_to_string(decode_block)
702 self.has_decode_default = has_decode_default
703
704 # Override '+' operator: generate a new GenCode object that
705 # concatenates all the individual strings in the operands.
706 def __add__(self, other):
707 exec_output = {}
708 for cpu in CpuModel.list:
709 n = cpu.name
710 exec_output[n] = self.exec_output[n] + other.exec_output[n]
711 return GenCode(self.header_output + other.header_output,
712 self.decoder_output + other.decoder_output,
713 exec_output,
714 self.decode_block + other.decode_block,
715 self.has_decode_default or other.has_decode_default)
716
717 # Prepend a string (typically a comment) to all the strings.
718 def prepend_all(self, pre):
719 self.header_output = pre + self.header_output
720 self.decoder_output = pre + self.decoder_output
721 self.decode_block = pre + self.decode_block
722 for cpu in CpuModel.list:
723 self.exec_output[cpu.name] = pre + self.exec_output[cpu.name]
724
725 # Wrap the decode block in a pair of strings (e.g., 'case foo:'
726 # and 'break;'). Used to build the big nested switch statement.
727 def wrap_decode_block(self, pre, post = ''):
728 self.decode_block = pre + indent(self.decode_block) + post
729
730 ################
731 # Format object.
732 #
733 # A format object encapsulates an instruction format. It must provide
734 # a defineInst() method that generates the code for an instruction
735 # definition.
736
737 class Format:
738 def __init__(self, id, params, code):
739 # constructor: just save away arguments
740 self.id = id
741 self.params = params
742 label = 'def format ' + id
743 self.user_code = compile(fixPythonIndentation(code), label, 'exec')
744 param_list = string.join(params, ", ")
745 f = '''def defInst(_code, _context, %s):
746 my_locals = vars().copy()
747 exec _code in _context, my_locals
748 return my_locals\n''' % param_list
749 c = compile(f, label + ' wrapper', 'exec')
750 exec c
751 self.func = defInst
752
753 def defineInst(self, name, args, lineno):
754 context = {}
755 updateExportContext()
756 context.update(exportContext)
757 context.update({ 'name': name, 'Name': string.capitalize(name) })
758 try:
759 vars = self.func(self.user_code, context, *args)
760 except Exception, exc:
761 error(lineno, 'error defining "%s": %s.' % (name, exc))
762 for k in vars.keys():
763 if k not in ('header_output', 'decoder_output',
764 'exec_output', 'decode_block'):
765 del vars[k]
766 return GenCode(**vars)
767
768 # Special null format to catch an implicit-format instruction
769 # definition outside of any format block.
770 class NoFormat:
771 def __init__(self):
772 self.defaultInst = ''
773
774 def defineInst(self, name, args, lineno):
775 error(lineno,
776 'instruction definition "%s" with no active format!' % name)
777
778 # This dictionary maps format name strings to Format objects.
779 formatMap = {}
780
781 # Define a new format
782 def defFormat(id, params, code, lineno):
783 # make sure we haven't already defined this one
784 if formatMap.get(id, None) != None:
785 error(lineno, 'format %s redefined.' % id)
786 # create new object and store in global map
787 formatMap[id] = Format(id, params, code)
788
789
790 ##############
791 # Stack: a simple stack object. Used for both formats (formatStack)
792 # and default cases (defaultStack).
793
794 class Stack:
795 def __init__(self, initItem):
796 self.stack = [ initItem ]
797
798 def push(self, item):
799 self.stack.append(item);
800
801 def pop(self):
802 return self.stack.pop()
803
804 def top(self):
805 return self.stack[-1]
806
807 # The global format stack.
808 formatStack = Stack(NoFormat())
809
810 # The global default case stack.
811 defaultStack = Stack( None )
812
813 ###################
814 # Utility functions
815
816 #
817 # Indent every line in string 's' by two spaces
818 # (except preprocessor directives).
819 # Used to make nested code blocks look pretty.
820 #
821 def indent(s):
822 return re.sub(r'(?m)^(?!\#)', ' ', s)
823
824 #
825 # Munge a somewhat arbitrarily formatted piece of Python code
826 # (e.g. from a format 'let' block) into something whose indentation
827 # will get by the Python parser.
828 #
829 # The two keys here are that Python will give a syntax error if
830 # there's any whitespace at the beginning of the first line, and that
831 # all lines at the same lexical nesting level must have identical
832 # indentation. Unfortunately the way code literals work, an entire
833 # let block tends to have some initial indentation. Rather than
834 # trying to figure out what that is and strip it off, we prepend 'if
835 # 1:' to make the let code the nested block inside the if (and have
836 # the parser automatically deal with the indentation for us).
837 #
838 # We don't want to do this if (1) the code block is empty or (2) the
839 # first line of the block doesn't have any whitespace at the front.
840
841 def fixPythonIndentation(s):
842 # get rid of blank lines first
843 s = re.sub(r'(?m)^\s*\n', '', s);
844 if (s != '' and re.match(r'[ \t]', s[0])):
845 s = 'if 1:\n' + s
846 return s
847
848 # Error handler. Just call exit. Output formatted to work under
849 # Emacs compile-mode.
850 def error(lineno, string):
851 sys.exit("%s:%d: %s" % (input_filename, lineno, string))
852
853 # Like error(), but include a Python stack backtrace (for processing
854 # Python exceptions).
855 def error_bt(lineno, string):
856 traceback.print_exc()
857 print >> sys.stderr, "%s:%d: %s" % (input_filename, lineno, string)
858 sys.exit(1)
859
860
861 #####################################################################
862 #
863 # Bitfield Operator Support
864 #
865 #####################################################################
866
867 bitOp1ArgRE = re.compile(r'<\s*(\w+)\s*:\s*>')
868
869 bitOpWordRE = re.compile(r'(?<![\w\.])([\w\.]+)<\s*(\w+)\s*:\s*(\w+)\s*>')
870 bitOpExprRE = re.compile(r'\)<\s*(\w+)\s*:\s*(\w+)\s*>')
871
872 def substBitOps(code):
873 # first convert single-bit selectors to two-index form
874 # i.e., <n> --> <n:n>
875 code = bitOp1ArgRE.sub(r'<\1:\1>', code)
876 # simple case: selector applied to ID (name)
877 # i.e., foo<a:b> --> bits(foo, a, b)
878 code = bitOpWordRE.sub(r'bits(\1, \2, \3)', code)
879 # if selector is applied to expression (ending in ')'),
880 # we need to search backward for matching '('
881 match = bitOpExprRE.search(code)
882 while match:
883 exprEnd = match.start()
884 here = exprEnd - 1
885 nestLevel = 1
886 while nestLevel > 0:
887 if code[here] == '(':
888 nestLevel -= 1
889 elif code[here] == ')':
890 nestLevel += 1
891 here -= 1
892 if here < 0:
893 sys.exit("Didn't find '('!")
894 exprStart = here+1
895 newExpr = r'bits(%s, %s, %s)' % (code[exprStart:exprEnd+1],
896 match.group(1), match.group(2))
897 code = code[:exprStart] + newExpr + code[match.end():]
898 match = bitOpExprRE.search(code)
899 return code
900
901
902 ####################
903 # Template objects.
904 #
905 # Template objects are format strings that allow substitution from
906 # the attribute spaces of other objects (e.g. InstObjParams instances).
907
908 class Template:
909 def __init__(self, t):
910 self.template = t
911
912 def subst(self, d):
913 # Start with the template namespace. Make a copy since we're
914 # going to modify it.
915 myDict = templateMap.copy()
916 # if the argument is a dictionary, we just use it.
917 if isinstance(d, dict):
918 myDict.update(d)
919 # if the argument is an object, we use its attribute map.
920 elif hasattr(d, '__dict__'):
921 myDict.update(d.__dict__)
922 else:
923 raise TypeError, "Template.subst() arg must be or have dictionary"
924 # CPU-model-specific substitutions are handled later (in GenCode).
925 return protect_cpu_symbols(self.template) % myDict
926
927 # Convert to string. This handles the case when a template with a
928 # CPU-specific term gets interpolated into another template or into
929 # an output block.
930 def __str__(self):
931 return expand_cpu_symbols_to_string(self.template)
932
933 #####################################################################
934 #
935 # Code Parser
936 #
937 # The remaining code is the support for automatically extracting
938 # instruction characteristics from pseudocode.
939 #
940 #####################################################################
941
942 # Force the argument to be a list
943 def makeList(list_or_item):
944 if not list_or_item:
945 return []
946 elif type(list_or_item) == ListType:
947 return list_or_item
948 else:
949 return [ list_or_item ]
950
951 # generate operandSizeMap based on provided operandTypeMap:
952 # basically generate equiv. C++ type and make is_signed flag
953 def buildOperandSizeMap():
954 global operandSizeMap
955 operandSizeMap = {}
956 for ext in operandTypeMap.keys():
957 (desc, size) = operandTypeMap[ext]
958 if desc == 'signed int':
959 type = 'int%d_t' % size
960 is_signed = 1
961 elif desc == 'unsigned int':
962 type = 'uint%d_t' % size
963 is_signed = 0
964 elif desc == 'float':
965 is_signed = 1 # shouldn't really matter
966 if size == 32:
967 type = 'float'
968 elif size == 64:
969 type = 'double'
970 if type == '':
971 error(0, 'Unrecognized type description "%s" in operandTypeMap')
972 operandSizeMap[ext] = (size, type, is_signed)
973
974 #
975 # Base class for operand traits. An instance of this class (or actually
976 # a class derived from this one) encapsulates the traits of a particular
977 # operand type (e.g., "32-bit integer register").
978 #
979 class OperandTraits:
980 def __init__(self, dflt_ext, reg_spec, flags, sort_pri):
981 # Force construction of operandSizeMap from operandTypeMap
982 # if it hasn't happened yet
983 if not globals().has_key('operandSizeMap'):
984 buildOperandSizeMap()
985 self.dflt_ext = dflt_ext
986 (self.dflt_size, self.dflt_type, self.dflt_is_signed) = \
987 operandSizeMap[dflt_ext]
988 self.reg_spec = reg_spec
989 # Canonical flag structure is a triple of lists, where each list
990 # indicates the set of flags implied by this operand always, when
991 # used as a source, and when used as a dest, respectively.
992 # For simplicity this can be initialized using a variety of fairly
993 # obvious shortcuts; we convert these to canonical form here.
994 if not flags:
995 # no flags specified (e.g., 'None')
996 self.flags = ( [], [], [] )
997 elif type(flags) == StringType:
998 # a single flag: assumed to be unconditional
999 self.flags = ( [ flags ], [], [] )
1000 elif type(flags) == ListType:
1001 # a list of flags: also assumed to be unconditional
1002 self.flags = ( flags, [], [] )
1003 elif type(flags) == TupleType:
1004 # it's a tuple: it should be a triple,
1005 # but each item could be a single string or a list
1006 (uncond_flags, src_flags, dest_flags) = flags
1007 self.flags = (makeList(uncond_flags),
1008 makeList(src_flags), makeList(dest_flags))
1009 self.sort_pri = sort_pri
1010
1011 def isMem(self):
1012 return 0
1013
1014 def isReg(self):
1015 return 0
1016
1017 def isFloatReg(self):
1018 return 0
1019
1020 def isIntReg(self):
1021 return 0
1022
1023 def isControlReg(self):
1024 return 0
1025
1026 def getFlags(self, op_desc):
1027 # note the empty slice '[:]' gives us a copy of self.flags[0]
1028 # instead of a reference to it
1029 my_flags = self.flags[0][:]
1030 if op_desc.is_src:
1031 my_flags += self.flags[1]
1032 if op_desc.is_dest:
1033 my_flags += self.flags[2]
1034 return my_flags
1035
1036 def makeDecl(self, op_desc):
1037 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1038 # Note that initializations in the declarations are solely
1039 # to avoid 'uninitialized variable' errors from the compiler.
1040 return type + ' ' + op_desc.munged_name + ' = 0;\n';
1041
1042 class IntRegOperandTraits(OperandTraits):
1043 def isReg(self):
1044 return 1
1045
1046 def isIntReg(self):
1047 return 1
1048
1049 def makeConstructor(self, op_desc):
1050 c = ''
1051 if op_desc.is_src:
1052 c += '\n\t_srcRegIdx[%d] = %s;' % \
1053 (op_desc.src_reg_idx, self.reg_spec)
1054 if op_desc.is_dest:
1055 c += '\n\t_destRegIdx[%d] = %s;' % \
1056 (op_desc.dest_reg_idx, self.reg_spec)
1057 return c
1058
1059 def makeRead(self, op_desc):
1060 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1061 if (type == 'float' or type == 'double'):
1062 error(0, 'Attempt to read integer register as FP')
1063 if (size == self.dflt_size):
1064 return '%s = xc->readIntReg(this, %d);\n' % \
1065 (op_desc.munged_name, op_desc.src_reg_idx)
1066 else:
1067 return '%s = bits(xc->readIntReg(this, %d), %d, 0);\n' % \
1068 (op_desc.munged_name, op_desc.src_reg_idx, size-1)
1069
1070 def makeWrite(self, op_desc):
1071 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1072 if (type == 'float' or type == 'double'):
1073 error(0, 'Attempt to write integer register as FP')
1074 if (size != self.dflt_size and is_signed):
1075 final_val = 'sext<%d>(%s)' % (size, op_desc.munged_name)
1076 else:
1077 final_val = op_desc.munged_name
1078 wb = '''
1079 {
1080 %s final_val = %s;
1081 xc->setIntReg(this, %d, final_val);\n
1082 if (traceData) { traceData->setData(final_val); }
1083 }''' % (self.dflt_type, final_val, op_desc.dest_reg_idx)
1084 return wb
1085
1086 class FloatRegOperandTraits(OperandTraits):
1087 def isReg(self):
1088 return 1
1089
1090 def isFloatReg(self):
1091 return 1
1092
1093 def makeConstructor(self, op_desc):
1094 c = ''
1095 if op_desc.is_src:
1096 c += '\n\t_srcRegIdx[%d] = %s + FP_Base_DepTag;' % \
1097 (op_desc.src_reg_idx, self.reg_spec)
1098 if op_desc.is_dest:
1099 c += '\n\t_destRegIdx[%d] = %s + FP_Base_DepTag;' % \
1100 (op_desc.dest_reg_idx, self.reg_spec)
1101 return c
1102
1103 def makeRead(self, op_desc):
1104 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1105 bit_select = 0
1106 if (type == 'float'):
1107 func = 'readFloatRegSingle'
1108 elif (type == 'double'):
1109 func = 'readFloatRegDouble'
1110 else:
1111 func = 'readFloatRegInt'
1112 if (size != self.dflt_size):
1113 bit_select = 1
1114 base = 'xc->%s(this, %d)' % \
1115 (func, op_desc.src_reg_idx)
1116 if bit_select:
1117 return '%s = bits(%s, %d, 0);\n' % \
1118 (op_desc.munged_name, base, size-1)
1119 else:
1120 return '%s = %s;\n' % (op_desc.munged_name, base)
1121
1122 def makeWrite(self, op_desc):
1123 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1124 final_val = op_desc.munged_name
1125 if (type == 'float'):
1126 func = 'setFloatRegSingle'
1127 elif (type == 'double'):
1128 func = 'setFloatRegDouble'
1129 else:
1130 func = 'setFloatRegInt'
1131 type = 'uint%d_t' % self.dflt_size
1132 if (size != self.dflt_size and is_signed):
1133 final_val = 'sext<%d>(%s)' % (size, op_desc.munged_name)
1134 wb = '''
1135 {
1136 %s final_val = %s;
1137 xc->%s(this, %d, final_val);\n
1138 if (traceData) { traceData->setData(final_val); }
1139 }''' % (type, final_val, func, op_desc.dest_reg_idx)
1140 return wb
1141
1142 class ControlRegOperandTraits(OperandTraits):
1143 def isReg(self):
1144 return 1
1145
1146 def isControlReg(self):
1147 return 1
1148
1149 def makeConstructor(self, op_desc):
1150 c = ''
1151 if op_desc.is_src:
1152 c += '\n\t_srcRegIdx[%d] = %s_DepTag;' % \
1153 (op_desc.src_reg_idx, self.reg_spec)
1154 if op_desc.is_dest:
1155 c += '\n\t_destRegIdx[%d] = %s_DepTag;' % \
1156 (op_desc.dest_reg_idx, self.reg_spec)
1157 return c
1158
1159 def makeRead(self, op_desc):
1160 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1161 bit_select = 0
1162 if (type == 'float' or type == 'double'):
1163 error(0, 'Attempt to read control register as FP')
1164 base = 'xc->read%s()' % self.reg_spec
1165 if size == self.dflt_size:
1166 return '%s = %s;\n' % (op_desc.munged_name, base)
1167 else:
1168 return '%s = bits(%s, %d, 0);\n' % \
1169 (op_desc.munged_name, base, size-1)
1170
1171 def makeWrite(self, op_desc):
1172 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1173 if (type == 'float' or type == 'double'):
1174 error(0, 'Attempt to write control register as FP')
1175 wb = 'xc->set%s(%s);\n' % (self.reg_spec, op_desc.munged_name)
1176 wb += 'if (traceData) { traceData->setData(%s); }' % \
1177 op_desc.munged_name
1178 return wb
1179
1180 class MemOperandTraits(OperandTraits):
1181 def isMem(self):
1182 return 1
1183
1184 def makeConstructor(self, op_desc):
1185 return ''
1186
1187 def makeDecl(self, op_desc):
1188 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1189 # Note that initializations in the declarations are solely
1190 # to avoid 'uninitialized variable' errors from the compiler.
1191 # Declare memory data variable.
1192 c = '%s %s = 0;\n' % (type, op_desc.munged_name)
1193 # Declare var to hold memory access flags.
1194 c += 'unsigned %s_flags = memAccessFlags;\n' % op_desc.base_name
1195 # If this operand is a dest (i.e., it's a store operation),
1196 # then we need to declare a variable for the write result code
1197 # as well.
1198 if op_desc.is_dest:
1199 c += 'uint64_t %s_write_result = 0;\n' % op_desc.base_name
1200 return c
1201
1202 def makeRead(self, op_desc):
1203 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1204 eff_type = 'uint%d_t' % size
1205 return 'fault = xc->read(EA, (%s&)%s, %s_flags);\n' \
1206 % (eff_type, op_desc.munged_name, op_desc.base_name)
1207
1208 def makeWrite(self, op_desc):
1209 (size, type, is_signed) = operandSizeMap[op_desc.eff_ext]
1210 eff_type = 'uint%d_t' % size
1211 wb = 'fault = xc->write((%s&)%s, EA, %s_flags, &%s_write_result);\n' \
1212 % (eff_type, op_desc.munged_name, op_desc.base_name,
1213 op_desc.base_name)
1214 wb += 'if (traceData) { traceData->setData(%s); }' % \
1215 op_desc.munged_name
1216 return wb
1217
1218 class NPCOperandTraits(OperandTraits):
1219 def makeConstructor(self, op_desc):
1220 return ''
1221
1222 def makeRead(self, op_desc):
1223 return '%s = xc->readPC() + 4;\n' % op_desc.munged_name
1224
1225 def makeWrite(self, op_desc):
1226 return 'xc->setNextPC(%s);\n' % op_desc.munged_name
1227
1228
1229 exportContextSymbols = ('IntRegOperandTraits', 'FloatRegOperandTraits',
1230 'ControlRegOperandTraits', 'MemOperandTraits',
1231 'NPCOperandTraits', 'InstObjParams', 'CodeBlock',
1232 're', 'string')
1233
1234 exportContext = {}
1235
1236 def updateExportContext():
1237 exportContext.update(exportDict(*exportContextSymbols))
1238 exportContext.update(templateMap)
1239
1240
1241 def exportDict(*symNames):
1242 return dict([(s, eval(s)) for s in symNames])
1243
1244
1245 #
1246 # Define operand variables that get derived from the basic declaration
1247 # of ISA-specific operands in operandTraitsMap. This function must be
1248 # called by the ISA description file explicitly after defining
1249 # operandTraitsMap (in a 'let' block).
1250 #
1251 def defineDerivedOperandVars():
1252 global operands
1253 operands = operandTraitsMap.keys()
1254
1255 operandsREString = (r'''
1256 (?<![\w\.]) # neg. lookbehind assertion: prevent partial matches
1257 ((%s)(?:\.(\w+))?) # match: operand with optional '.' then suffix
1258 (?![\w\.]) # neg. lookahead assertion: prevent partial matches
1259 '''
1260 % string.join(operands, '|'))
1261
1262 global operandsRE
1263 operandsRE = re.compile(operandsREString, re.MULTILINE|re.VERBOSE)
1264
1265 # Same as operandsREString, but extension is mandatory, and only two
1266 # groups are returned (base and ext, not full name as above).
1267 # Used for subtituting '_' for '.' to make C++ identifiers.
1268 operandsWithExtREString = (r'(?<![\w\.])(%s)\.(\w+)(?![\w\.])'
1269 % string.join(operands, '|'))
1270
1271 global operandsWithExtRE
1272 operandsWithExtRE = re.compile(operandsWithExtREString, re.MULTILINE)
1273
1274
1275 #
1276 # Operand descriptor class. An instance of this class represents
1277 # a specific operand for a code block.
1278 #
1279 class OperandDescriptor:
1280 def __init__(self, full_name, base_name, ext, is_src, is_dest):
1281 self.full_name = full_name
1282 self.base_name = base_name
1283 self.ext = ext
1284 self.is_src = is_src
1285 self.is_dest = is_dest
1286 self.traits = operandTraitsMap[base_name]
1287 # The 'effective extension' (eff_ext) is either the actual
1288 # extension, if one was explicitly provided, or the default.
1289 # The 'munged name' replaces the '.' between the base and
1290 # extension (if any) with a '_' to make a legal C++ variable name.
1291 if ext:
1292 self.eff_ext = ext
1293 self.munged_name = base_name + '_' + ext
1294 else:
1295 self.eff_ext = self.traits.dflt_ext
1296 self.munged_name = base_name
1297
1298 # Finalize additional fields (primarily code fields). This step
1299 # is done separately since some of these fields may depend on the
1300 # register index enumeration that hasn't been performed yet at the
1301 # time of __init__().
1302 def finalize(self):
1303 self.flags = self.traits.getFlags(self)
1304 self.constructor = self.traits.makeConstructor(self)
1305 self.op_decl = self.traits.makeDecl(self)
1306
1307 if self.is_src:
1308 self.op_rd = self.traits.makeRead(self)
1309 else:
1310 self.op_rd = ''
1311
1312 if self.is_dest:
1313 self.op_wb = self.traits.makeWrite(self)
1314 else:
1315 self.op_wb = ''
1316
1317 class OperandDescriptorList:
1318 def __init__(self):
1319 self.items = []
1320 self.bases = {}
1321
1322 def __len__(self):
1323 return len(self.items)
1324
1325 def __getitem__(self, index):
1326 return self.items[index]
1327
1328 def append(self, op_desc):
1329 self.items.append(op_desc)
1330 self.bases[op_desc.base_name] = op_desc
1331
1332 def find_base(self, base_name):
1333 # like self.bases[base_name], but returns None if not found
1334 # (rather than raising exception)
1335 return self.bases.get(base_name)
1336
1337 # internal helper function for concat[Some]Attr{Strings|Lists}
1338 def __internalConcatAttrs(self, attr_name, filter, result):
1339 for op_desc in self.items:
1340 if filter(op_desc):
1341 result += getattr(op_desc, attr_name)
1342 return result
1343
1344 # return a single string that is the concatenation of the (string)
1345 # values of the specified attribute for all operands
1346 def concatAttrStrings(self, attr_name):
1347 return self.__internalConcatAttrs(attr_name, lambda x: 1, '')
1348
1349 # like concatAttrStrings, but only include the values for the operands
1350 # for which the provided filter function returns true
1351 def concatSomeAttrStrings(self, filter, attr_name):
1352 return self.__internalConcatAttrs(attr_name, filter, '')
1353
1354 # return a single list that is the concatenation of the (list)
1355 # values of the specified attribute for all operands
1356 def concatAttrLists(self, attr_name):
1357 return self.__internalConcatAttrs(attr_name, lambda x: 1, [])
1358
1359 # like concatAttrLists, but only include the values for the operands
1360 # for which the provided filter function returns true
1361 def concatSomeAttrLists(self, filter, attr_name):
1362 return self.__internalConcatAttrs(attr_name, filter, [])
1363
1364 def sort(self):
1365 self.items.sort(lambda a, b: a.traits.sort_pri - b.traits.sort_pri)
1366
1367 # Regular expression object to match C++ comments
1368 # (used in findOperands())
1369 commentRE = re.compile(r'//.*\n')
1370
1371 # Regular expression object to match assignment statements
1372 # (used in findOperands())
1373 assignRE = re.compile(r'\s*=(?!=)', re.MULTILINE)
1374
1375 #
1376 # Find all the operands in the given code block. Returns an operand
1377 # descriptor list (instance of class OperandDescriptorList).
1378 #
1379 def findOperands(code):
1380 operands = OperandDescriptorList()
1381 # delete comments so we don't accidentally match on reg specifiers inside
1382 code = commentRE.sub('', code)
1383 # search for operands
1384 next_pos = 0
1385 while 1:
1386 match = operandsRE.search(code, next_pos)
1387 if not match:
1388 # no more matches: we're done
1389 break
1390 op = match.groups()
1391 # regexp groups are operand full name, base, and extension
1392 (op_full, op_base, op_ext) = op
1393 # if the token following the operand is an assignment, this is
1394 # a destination (LHS), else it's a source (RHS)
1395 is_dest = (assignRE.match(code, match.end()) != None)
1396 is_src = not is_dest
1397 # see if we've already seen this one
1398 op_desc = operands.find_base(op_base)
1399 if op_desc:
1400 if op_desc.ext != op_ext:
1401 error(0, 'Inconsistent extensions for operand %s' % op_base)
1402 op_desc.is_src = op_desc.is_src or is_src
1403 op_desc.is_dest = op_desc.is_dest or is_dest
1404 else:
1405 # new operand: create new descriptor
1406 op_desc = OperandDescriptor(op_full, op_base, op_ext,
1407 is_src, is_dest)
1408 operands.append(op_desc)
1409 # start next search after end of current match
1410 next_pos = match.end()
1411 operands.sort()
1412 # enumerate source & dest register operands... used in building
1413 # constructor later
1414 srcRegs = 0
1415 destRegs = 0
1416 operands.numFPDestRegs = 0
1417 operands.numIntDestRegs = 0
1418 for op_desc in operands:
1419 if op_desc.traits.isReg():
1420 if op_desc.is_src:
1421 op_desc.src_reg_idx = srcRegs
1422 srcRegs += 1
1423 if op_desc.is_dest:
1424 op_desc.dest_reg_idx = destRegs
1425 destRegs += 1
1426 if op_desc.traits.isFloatReg():
1427 operands.numFPDestRegs += 1
1428 elif op_desc.traits.isIntReg():
1429 operands.numIntDestRegs += 1
1430 operands.numSrcRegs = srcRegs
1431 operands.numDestRegs = destRegs
1432 # now make a final pass to finalize op_desc fields that may depend
1433 # on the register enumeration
1434 for op_desc in operands:
1435 op_desc.finalize()
1436 return operands
1437
1438 # Munge operand names in code string to make legal C++ variable names.
1439 # (Will match munged_name attribute of OperandDescriptor object.)
1440 def substMungedOpNames(code):
1441 return operandsWithExtRE.sub(r'\1_\2', code)
1442
1443 def joinLists(t):
1444 return map(string.join, t)
1445
1446 def makeFlagConstructor(flag_list):
1447 if len(flag_list) == 0:
1448 return ''
1449 # filter out repeated flags
1450 flag_list.sort()
1451 i = 1
1452 while i < len(flag_list):
1453 if flag_list[i] == flag_list[i-1]:
1454 del flag_list[i]
1455 else:
1456 i += 1
1457 pre = '\n\tflags['
1458 post = '] = true;'
1459 code = pre + string.join(flag_list, post + pre) + post
1460 return code
1461
1462 class CodeBlock:
1463 def __init__(self, code):
1464 self.orig_code = code
1465 self.operands = findOperands(code)
1466 self.code = substMungedOpNames(substBitOps(code))
1467 self.constructor = self.operands.concatAttrStrings('constructor')
1468 self.constructor += \
1469 '\n\t_numSrcRegs = %d;' % self.operands.numSrcRegs
1470 self.constructor += \
1471 '\n\t_numDestRegs = %d;' % self.operands.numDestRegs
1472 self.constructor += \
1473 '\n\t_numFPDestRegs = %d;' % self.operands.numFPDestRegs
1474 self.constructor += \
1475 '\n\t_numIntDestRegs = %d;' % self.operands.numIntDestRegs
1476
1477 self.op_decl = self.operands.concatAttrStrings('op_decl')
1478
1479 is_mem = lambda op: op.traits.isMem()
1480 not_mem = lambda op: not op.traits.isMem()
1481
1482 self.op_rd = self.operands.concatAttrStrings('op_rd')
1483 self.op_wb = self.operands.concatAttrStrings('op_wb')
1484 self.op_mem_rd = \
1485 self.operands.concatSomeAttrStrings(is_mem, 'op_rd')
1486 self.op_mem_wb = \
1487 self.operands.concatSomeAttrStrings(is_mem, 'op_wb')
1488 self.op_nonmem_rd = \
1489 self.operands.concatSomeAttrStrings(not_mem, 'op_rd')
1490 self.op_nonmem_wb = \
1491 self.operands.concatSomeAttrStrings(not_mem, 'op_wb')
1492
1493 self.flags = self.operands.concatAttrLists('flags')
1494
1495 # Make a basic guess on the operand class (function unit type).
1496 # These are good enough for most cases, and will be overridden
1497 # later otherwise.
1498 if 'IsStore' in self.flags:
1499 self.op_class = 'MemWriteOp'
1500 elif 'IsLoad' in self.flags or 'IsPrefetch' in self.flags:
1501 self.op_class = 'MemReadOp'
1502 elif 'IsFloating' in self.flags:
1503 self.op_class = 'FloatAddOp'
1504 else:
1505 self.op_class = 'IntAluOp'
1506
1507 # Assume all instruction flags are of the form 'IsFoo'
1508 instFlagRE = re.compile(r'Is.*')
1509
1510 # OpClass constants end in 'Op' except No_OpClass
1511 opClassRE = re.compile(r'.*Op|No_OpClass')
1512
1513 class InstObjParams:
1514 def __init__(self, mnem, class_name, base_class = '',
1515 code_block = None, opt_args = []):
1516 self.mnemonic = mnem
1517 self.class_name = class_name
1518 self.base_class = base_class
1519 if code_block:
1520 for code_attr in code_block.__dict__.keys():
1521 setattr(self, code_attr, getattr(code_block, code_attr))
1522 else:
1523 self.constructor = ''
1524 self.flags = []
1525 # Optional arguments are assumed to be either StaticInst flags
1526 # or an OpClass value. To avoid having to import a complete
1527 # list of these values to match against, we do it ad-hoc
1528 # with regexps.
1529 for oa in opt_args:
1530 if instFlagRE.match(oa):
1531 self.flags.append(oa)
1532 elif opClassRE.match(oa):
1533 self.op_class = oa
1534 else:
1535 error(0, 'InstObjParams: optional arg "%s" not recognized '
1536 'as StaticInst::Flag or OpClass.' % oa)
1537
1538 # add flag initialization to contructor here to include
1539 # any flags added via opt_args
1540 self.constructor += makeFlagConstructor(self.flags)
1541
1542 # if 'IsFloating' is set, add call to the FP enable check
1543 # function (which should be provided by isa_desc via a declare)
1544 if 'IsFloating' in self.flags:
1545 self.fp_enable_check = 'fault = checkFpEnableFault(xc);'
1546 else:
1547 self.fp_enable_check = ''
1548
1549 #######################
1550 #
1551 # Output file template
1552 #
1553
1554 file_template = '''
1555 /*
1556 * DO NOT EDIT THIS FILE!!!
1557 *
1558 * It was automatically generated from the ISA description in %(filename)s
1559 */
1560
1561 %(includes)s
1562
1563 %(global_output)s
1564
1565 namespace %(namespace)s {
1566
1567 %(namespace_output)s
1568
1569 } // namespace %(namespace)s
1570 '''
1571
1572
1573 # Update the output file only if the new contents are different from
1574 # the current contents. Minimizes the files that need to be rebuilt
1575 # after minor changes.
1576 def update_if_needed(file, contents):
1577 update = False
1578 if os.access(file, os.R_OK):
1579 f = open(file, 'r')
1580 old_contents = f.read()
1581 f.close()
1582 if contents != old_contents:
1583 print 'Updating', file
1584 os.remove(file) # in case it's write-protected
1585 update = True
1586 else:
1587 print 'File', file, 'is unchanged'
1588 else:
1589 print 'Generating', file
1590 update = True
1591 if update:
1592 f = open(file, 'w')
1593 f.write(contents)
1594 f.close()
1595
1596 #
1597 # Read in and parse the ISA description.
1598 #
1599 def parse_isa_desc(isa_desc_file, output_dir, include_path):
1600 # set a global var for the input filename... used in error messages
1601 global input_filename
1602 input_filename = isa_desc_file
1603
1604 # Suck the ISA description file in.
1605 input = open(isa_desc_file)
1606 isa_desc = input.read()
1607 input.close()
1608
1609 # Parse it.
1610 (isa_name, namespace, global_code, namespace_code) = yacc.parse(isa_desc)
1611
1612 # grab the last three path components of isa_desc_file to put in
1613 # the output
1614 filename = '/'.join(isa_desc_file.split('/')[-3:])
1615
1616 # generate decoder.hh
1617 includes = '#include "base/bitfield.hh" // for bitfield support'
1618 global_output = global_code.header_output
1619 namespace_output = namespace_code.header_output
1620 update_if_needed(output_dir + '/decoder.hh', file_template % vars())
1621
1622 # generate decoder.cc
1623 includes = '#include "%s/decoder.hh"' % include_path
1624 global_output = global_code.decoder_output
1625 namespace_output = namespace_code.decoder_output
1626 namespace_output += namespace_code.decode_block
1627 update_if_needed(output_dir + '/decoder.cc', file_template % vars())
1628
1629 # generate per-cpu exec files
1630 for cpu in CpuModel.list:
1631 includes = '#include "%s/decoder.hh"\n' % include_path
1632 includes += cpu.includes
1633 global_output = global_code.exec_output[cpu.name]
1634 namespace_output = namespace_code.exec_output[cpu.name]
1635 update_if_needed(output_dir + '/' + cpu.filename,
1636 file_template % vars())
1637
1638 # Called as script: get args from command line.
1639 if __name__ == '__main__':
1640 parse_isa_desc(sys.argv[1], sys.argv[2], sys.argv[3])