8d0fee22ded16128f75d75c6d9a2caee7efba4ea
[gem5.git] / src / arch / isa_parser.py
1 # Copyright (c) 2014, 2016, 2018-2019 ARM Limited
2 # All rights reserved
3 #
4 # The license below extends only to copyright in the software and shall
5 # not be construed as granting a license to any other intellectual
6 # property including but not limited to intellectual property relating
7 # to a hardware implementation of the functionality of the software
8 # licensed hereunder. You may use the software subject to the license
9 # terms below provided that you ensure that this notice is replicated
10 # unmodified and in its entirety in all distributions of the software,
11 # modified or unmodified, in source code or in binary form.
12 #
13 # Copyright (c) 2003-2005 The Regents of The University of Michigan
14 # Copyright (c) 2013,2015 Advanced Micro Devices, Inc.
15 # All rights reserved.
16 #
17 # Redistribution and use in source and binary forms, with or without
18 # modification, are permitted provided that the following conditions are
19 # met: redistributions of source code must retain the above copyright
20 # notice, this list of conditions and the following disclaimer;
21 # redistributions in binary form must reproduce the above copyright
22 # notice, this list of conditions and the following disclaimer in the
23 # documentation and/or other materials provided with the distribution;
24 # neither the name of the copyright holders nor the names of its
25 # contributors may be used to endorse or promote products derived from
26 # this software without specific prior written permission.
27 #
28 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39
40 from __future__ import with_statement, print_function
41 import os
42 import sys
43 import re
44 import string
45 import inspect, traceback
46 # get type names
47 from types import *
48
49 from m5.util.grammar import Grammar
50
51 debug=False
52
53 ###################
54 # Utility functions
55
56 #
57 # Indent every line in string 's' by two spaces
58 # (except preprocessor directives).
59 # Used to make nested code blocks look pretty.
60 #
61 def indent(s):
62 return re.sub(r'(?m)^(?!#)', ' ', s)
63
64 #
65 # Munge a somewhat arbitrarily formatted piece of Python code
66 # (e.g. from a format 'let' block) into something whose indentation
67 # will get by the Python parser.
68 #
69 # The two keys here are that Python will give a syntax error if
70 # there's any whitespace at the beginning of the first line, and that
71 # all lines at the same lexical nesting level must have identical
72 # indentation. Unfortunately the way code literals work, an entire
73 # let block tends to have some initial indentation. Rather than
74 # trying to figure out what that is and strip it off, we prepend 'if
75 # 1:' to make the let code the nested block inside the if (and have
76 # the parser automatically deal with the indentation for us).
77 #
78 # We don't want to do this if (1) the code block is empty or (2) the
79 # first line of the block doesn't have any whitespace at the front.
80
81 def fixPythonIndentation(s):
82 # get rid of blank lines first
83 s = re.sub(r'(?m)^\s*\n', '', s);
84 if (s != '' and re.match(r'[ \t]', s[0])):
85 s = 'if 1:\n' + s
86 return s
87
88 class ISAParserError(Exception):
89 """Exception class for parser errors"""
90 def __init__(self, first, second=None):
91 if second is None:
92 self.lineno = 0
93 self.string = first
94 else:
95 self.lineno = first
96 self.string = second
97
98 def __str__(self):
99 return self.string
100
101 def error(*args):
102 raise ISAParserError(*args)
103
104 ####################
105 # Template objects.
106 #
107 # Template objects are format strings that allow substitution from
108 # the attribute spaces of other objects (e.g. InstObjParams instances).
109
110 labelRE = re.compile(r'(?<!%)%\(([^\)]+)\)[sd]')
111
112 class Template(object):
113 def __init__(self, parser, t):
114 self.parser = parser
115 self.template = t
116
117 def subst(self, d):
118 myDict = None
119
120 # Protect non-Python-dict substitutions (e.g. if there's a printf
121 # in the templated C++ code)
122 template = self.parser.protectNonSubstPercents(self.template)
123
124 # Build a dict ('myDict') to use for the template substitution.
125 # Start with the template namespace. Make a copy since we're
126 # going to modify it.
127 myDict = self.parser.templateMap.copy()
128
129 if isinstance(d, InstObjParams):
130 # If we're dealing with an InstObjParams object, we need
131 # to be a little more sophisticated. The instruction-wide
132 # parameters are already formed, but the parameters which
133 # are only function wide still need to be generated.
134 compositeCode = ''
135
136 myDict.update(d.__dict__)
137 # The "operands" and "snippets" attributes of the InstObjParams
138 # objects are for internal use and not substitution.
139 del myDict['operands']
140 del myDict['snippets']
141
142 snippetLabels = [l for l in labelRE.findall(template)
143 if l in d.snippets]
144
145 snippets = dict([(s, self.parser.mungeSnippet(d.snippets[s]))
146 for s in snippetLabels])
147
148 myDict.update(snippets)
149
150 compositeCode = ' '.join(map(str, snippets.values()))
151
152 # Add in template itself in case it references any
153 # operands explicitly (like Mem)
154 compositeCode += ' ' + template
155
156 operands = SubOperandList(self.parser, compositeCode, d.operands)
157
158 myDict['op_decl'] = operands.concatAttrStrings('op_decl')
159 if operands.readPC or operands.setPC:
160 myDict['op_decl'] += 'TheISA::PCState __parserAutoPCState;\n'
161
162 # In case there are predicated register reads and write, declare
163 # the variables for register indicies. It is being assumed that
164 # all the operands in the OperandList are also in the
165 # SubOperandList and in the same order. Otherwise, it is
166 # expected that predication would not be used for the operands.
167 if operands.predRead:
168 myDict['op_decl'] += 'uint8_t _sourceIndex = 0;\n'
169 if operands.predWrite:
170 myDict['op_decl'] += 'uint8_t M5_VAR_USED _destIndex = 0;\n'
171
172 is_src = lambda op: op.is_src
173 is_dest = lambda op: op.is_dest
174
175 myDict['op_src_decl'] = \
176 operands.concatSomeAttrStrings(is_src, 'op_src_decl')
177 myDict['op_dest_decl'] = \
178 operands.concatSomeAttrStrings(is_dest, 'op_dest_decl')
179 if operands.readPC:
180 myDict['op_src_decl'] += \
181 'TheISA::PCState __parserAutoPCState;\n'
182 if operands.setPC:
183 myDict['op_dest_decl'] += \
184 'TheISA::PCState __parserAutoPCState;\n'
185
186 myDict['op_rd'] = operands.concatAttrStrings('op_rd')
187 if operands.readPC:
188 myDict['op_rd'] = '__parserAutoPCState = xc->pcState();\n' + \
189 myDict['op_rd']
190
191 # Compose the op_wb string. If we're going to write back the
192 # PC state because we changed some of its elements, we'll need to
193 # do that as early as possible. That allows later uncoordinated
194 # modifications to the PC to layer appropriately.
195 reordered = list(operands.items)
196 reordered.reverse()
197 op_wb_str = ''
198 pcWbStr = 'xc->pcState(__parserAutoPCState);\n'
199 for op_desc in reordered:
200 if op_desc.isPCPart() and op_desc.is_dest:
201 op_wb_str = op_desc.op_wb + pcWbStr + op_wb_str
202 pcWbStr = ''
203 else:
204 op_wb_str = op_desc.op_wb + op_wb_str
205 myDict['op_wb'] = op_wb_str
206
207 elif isinstance(d, dict):
208 # if the argument is a dictionary, we just use it.
209 myDict.update(d)
210 elif hasattr(d, '__dict__'):
211 # if the argument is an object, we use its attribute map.
212 myDict.update(d.__dict__)
213 else:
214 raise TypeError, "Template.subst() arg must be or have dictionary"
215 return template % myDict
216
217 # Convert to string.
218 def __str__(self):
219 return self.template
220
221 ################
222 # Format object.
223 #
224 # A format object encapsulates an instruction format. It must provide
225 # a defineInst() method that generates the code for an instruction
226 # definition.
227
228 class Format(object):
229 def __init__(self, id, params, code):
230 self.id = id
231 self.params = params
232 label = 'def format ' + id
233 self.user_code = compile(fixPythonIndentation(code), label, 'exec')
234 param_list = string.join(params, ", ")
235 f = '''def defInst(_code, _context, %s):
236 my_locals = vars().copy()
237 exec _code in _context, my_locals
238 return my_locals\n''' % param_list
239 c = compile(f, label + ' wrapper', 'exec')
240 exec c
241 self.func = defInst
242
243 def defineInst(self, parser, name, args, lineno):
244 parser.updateExportContext()
245 context = parser.exportContext.copy()
246 if len(name):
247 Name = name[0].upper()
248 if len(name) > 1:
249 Name += name[1:]
250 context.update({ 'name' : name, 'Name' : Name })
251 try:
252 vars = self.func(self.user_code, context, *args[0], **args[1])
253 except Exception, exc:
254 if debug:
255 raise
256 error(lineno, 'error defining "%s": %s.' % (name, exc))
257 for k in vars.keys():
258 if k not in ('header_output', 'decoder_output',
259 'exec_output', 'decode_block'):
260 del vars[k]
261 return GenCode(parser, **vars)
262
263 # Special null format to catch an implicit-format instruction
264 # definition outside of any format block.
265 class NoFormat(object):
266 def __init__(self):
267 self.defaultInst = ''
268
269 def defineInst(self, parser, name, args, lineno):
270 error(lineno,
271 'instruction definition "%s" with no active format!' % name)
272
273 ###############
274 # GenCode class
275 #
276 # The GenCode class encapsulates generated code destined for various
277 # output files. The header_output and decoder_output attributes are
278 # strings containing code destined for decoder.hh and decoder.cc
279 # respectively. The decode_block attribute contains code to be
280 # incorporated in the decode function itself (that will also end up in
281 # decoder.cc). The exec_output attribute is the string of code for the
282 # exec.cc file. The has_decode_default attribute is used in the decode block
283 # to allow explicit default clauses to override default default clauses.
284
285 class GenCode(object):
286 # Constructor.
287 def __init__(self, parser,
288 header_output = '', decoder_output = '', exec_output = '',
289 decode_block = '', has_decode_default = False):
290 self.parser = parser
291 self.header_output = header_output
292 self.decoder_output = decoder_output
293 self.exec_output = exec_output
294 self.decode_block = decode_block
295 self.has_decode_default = has_decode_default
296
297 # Write these code chunks out to the filesystem. They will be properly
298 # interwoven by the write_top_level_files().
299 def emit(self):
300 if self.header_output:
301 self.parser.get_file('header').write(self.header_output)
302 if self.decoder_output:
303 self.parser.get_file('decoder').write(self.decoder_output)
304 if self.exec_output:
305 self.parser.get_file('exec').write(self.exec_output)
306 if self.decode_block:
307 self.parser.get_file('decode_block').write(self.decode_block)
308
309 # Override '+' operator: generate a new GenCode object that
310 # concatenates all the individual strings in the operands.
311 def __add__(self, other):
312 return GenCode(self.parser,
313 self.header_output + other.header_output,
314 self.decoder_output + other.decoder_output,
315 self.exec_output + other.exec_output,
316 self.decode_block + other.decode_block,
317 self.has_decode_default or other.has_decode_default)
318
319 # Prepend a string (typically a comment) to all the strings.
320 def prepend_all(self, pre):
321 self.header_output = pre + self.header_output
322 self.decoder_output = pre + self.decoder_output
323 self.decode_block = pre + self.decode_block
324 self.exec_output = pre + self.exec_output
325
326 # Wrap the decode block in a pair of strings (e.g., 'case foo:'
327 # and 'break;'). Used to build the big nested switch statement.
328 def wrap_decode_block(self, pre, post = ''):
329 self.decode_block = pre + indent(self.decode_block) + post
330
331 #####################################################################
332 #
333 # Bitfield Operator Support
334 #
335 #####################################################################
336
337 bitOp1ArgRE = re.compile(r'<\s*(\w+)\s*:\s*>')
338
339 bitOpWordRE = re.compile(r'(?<![\w\.])([\w\.]+)<\s*(\w+)\s*:\s*(\w+)\s*>')
340 bitOpExprRE = re.compile(r'\)<\s*(\w+)\s*:\s*(\w+)\s*>')
341
342 def substBitOps(code):
343 # first convert single-bit selectors to two-index form
344 # i.e., <n> --> <n:n>
345 code = bitOp1ArgRE.sub(r'<\1:\1>', code)
346 # simple case: selector applied to ID (name)
347 # i.e., foo<a:b> --> bits(foo, a, b)
348 code = bitOpWordRE.sub(r'bits(\1, \2, \3)', code)
349 # if selector is applied to expression (ending in ')'),
350 # we need to search backward for matching '('
351 match = bitOpExprRE.search(code)
352 while match:
353 exprEnd = match.start()
354 here = exprEnd - 1
355 nestLevel = 1
356 while nestLevel > 0:
357 if code[here] == '(':
358 nestLevel -= 1
359 elif code[here] == ')':
360 nestLevel += 1
361 here -= 1
362 if here < 0:
363 sys.exit("Didn't find '('!")
364 exprStart = here+1
365 newExpr = r'bits(%s, %s, %s)' % (code[exprStart:exprEnd+1],
366 match.group(1), match.group(2))
367 code = code[:exprStart] + newExpr + code[match.end():]
368 match = bitOpExprRE.search(code)
369 return code
370
371
372 #####################################################################
373 #
374 # Code Parser
375 #
376 # The remaining code is the support for automatically extracting
377 # instruction characteristics from pseudocode.
378 #
379 #####################################################################
380
381 # Force the argument to be a list. Useful for flags, where a caller
382 # can specify a singleton flag or a list of flags. Also usful for
383 # converting tuples to lists so they can be modified.
384 def makeList(arg):
385 if isinstance(arg, list):
386 return arg
387 elif isinstance(arg, tuple):
388 return list(arg)
389 elif not arg:
390 return []
391 else:
392 return [ arg ]
393
394 class Operand(object):
395 '''Base class for operand descriptors. An instance of this class
396 (or actually a class derived from this one) represents a specific
397 operand for a code block (e.g, "Rc.sq" as a dest). Intermediate
398 derived classes encapsulates the traits of a particular operand
399 type (e.g., "32-bit integer register").'''
400
401 def buildReadCode(self, func = None):
402 subst_dict = {"name": self.base_name,
403 "func": func,
404 "reg_idx": self.reg_spec,
405 "ctype": self.ctype}
406 if hasattr(self, 'src_reg_idx'):
407 subst_dict['op_idx'] = self.src_reg_idx
408 code = self.read_code % subst_dict
409 return '%s = %s;\n' % (self.base_name, code)
410
411 def buildWriteCode(self, func = None):
412 subst_dict = {"name": self.base_name,
413 "func": func,
414 "reg_idx": self.reg_spec,
415 "ctype": self.ctype,
416 "final_val": self.base_name}
417 if hasattr(self, 'dest_reg_idx'):
418 subst_dict['op_idx'] = self.dest_reg_idx
419 code = self.write_code % subst_dict
420 return '''
421 {
422 %s final_val = %s;
423 %s;
424 if (traceData) { traceData->setData(final_val); }
425 }''' % (self.dflt_ctype, self.base_name, code)
426
427 def __init__(self, parser, full_name, ext, is_src, is_dest):
428 self.full_name = full_name
429 self.ext = ext
430 self.is_src = is_src
431 self.is_dest = is_dest
432 # The 'effective extension' (eff_ext) is either the actual
433 # extension, if one was explicitly provided, or the default.
434 if ext:
435 self.eff_ext = ext
436 elif hasattr(self, 'dflt_ext'):
437 self.eff_ext = self.dflt_ext
438
439 if hasattr(self, 'eff_ext'):
440 self.ctype = parser.operandTypeMap[self.eff_ext]
441
442 # Finalize additional fields (primarily code fields). This step
443 # is done separately since some of these fields may depend on the
444 # register index enumeration that hasn't been performed yet at the
445 # time of __init__(). The register index enumeration is affected
446 # by predicated register reads/writes. Hence, we forward the flags
447 # that indicate whether or not predication is in use.
448 def finalize(self, predRead, predWrite):
449 self.flags = self.getFlags()
450 self.constructor = self.makeConstructor(predRead, predWrite)
451 self.op_decl = self.makeDecl()
452
453 if self.is_src:
454 self.op_rd = self.makeRead(predRead)
455 self.op_src_decl = self.makeDecl()
456 else:
457 self.op_rd = ''
458 self.op_src_decl = ''
459
460 if self.is_dest:
461 self.op_wb = self.makeWrite(predWrite)
462 self.op_dest_decl = self.makeDecl()
463 else:
464 self.op_wb = ''
465 self.op_dest_decl = ''
466
467 def isMem(self):
468 return 0
469
470 def isReg(self):
471 return 0
472
473 def isFloatReg(self):
474 return 0
475
476 def isIntReg(self):
477 return 0
478
479 def isCCReg(self):
480 return 0
481
482 def isControlReg(self):
483 return 0
484
485 def isVecReg(self):
486 return 0
487
488 def isVecElem(self):
489 return 0
490
491 def isVecPredReg(self):
492 return 0
493
494 def isPCState(self):
495 return 0
496
497 def isPCPart(self):
498 return self.isPCState() and self.reg_spec
499
500 def hasReadPred(self):
501 return self.read_predicate != None
502
503 def hasWritePred(self):
504 return self.write_predicate != None
505
506 def getFlags(self):
507 # note the empty slice '[:]' gives us a copy of self.flags[0]
508 # instead of a reference to it
509 my_flags = self.flags[0][:]
510 if self.is_src:
511 my_flags += self.flags[1]
512 if self.is_dest:
513 my_flags += self.flags[2]
514 return my_flags
515
516 def makeDecl(self):
517 # Note that initializations in the declarations are solely
518 # to avoid 'uninitialized variable' errors from the compiler.
519 return self.ctype + ' ' + self.base_name + ' = 0;\n';
520
521
522 src_reg_constructor = '\n\t_srcRegIdx[_numSrcRegs++] = RegId(%s, %s);'
523 dst_reg_constructor = '\n\t_destRegIdx[_numDestRegs++] = RegId(%s, %s);'
524
525
526 class IntRegOperand(Operand):
527 reg_class = 'IntRegClass'
528
529 def isReg(self):
530 return 1
531
532 def isIntReg(self):
533 return 1
534
535 def makeConstructor(self, predRead, predWrite):
536 c_src = ''
537 c_dest = ''
538
539 if self.is_src:
540 c_src = src_reg_constructor % (self.reg_class, self.reg_spec)
541 if self.hasReadPred():
542 c_src = '\n\tif (%s) {%s\n\t}' % \
543 (self.read_predicate, c_src)
544
545 if self.is_dest:
546 c_dest = dst_reg_constructor % (self.reg_class, self.reg_spec)
547 c_dest += '\n\t_numIntDestRegs++;'
548 if self.hasWritePred():
549 c_dest = '\n\tif (%s) {%s\n\t}' % \
550 (self.write_predicate, c_dest)
551
552 return c_src + c_dest
553
554 def makeRead(self, predRead):
555 if (self.ctype == 'float' or self.ctype == 'double'):
556 error('Attempt to read integer register as FP')
557 if self.read_code != None:
558 return self.buildReadCode('readIntRegOperand')
559
560 int_reg_val = ''
561 if predRead:
562 int_reg_val = 'xc->readIntRegOperand(this, _sourceIndex++)'
563 if self.hasReadPred():
564 int_reg_val = '(%s) ? %s : 0' % \
565 (self.read_predicate, int_reg_val)
566 else:
567 int_reg_val = 'xc->readIntRegOperand(this, %d)' % self.src_reg_idx
568
569 return '%s = %s;\n' % (self.base_name, int_reg_val)
570
571 def makeWrite(self, predWrite):
572 if (self.ctype == 'float' or self.ctype == 'double'):
573 error('Attempt to write integer register as FP')
574 if self.write_code != None:
575 return self.buildWriteCode('setIntRegOperand')
576
577 if predWrite:
578 wp = 'true'
579 if self.hasWritePred():
580 wp = self.write_predicate
581
582 wcond = 'if (%s)' % (wp)
583 windex = '_destIndex++'
584 else:
585 wcond = ''
586 windex = '%d' % self.dest_reg_idx
587
588 wb = '''
589 %s
590 {
591 %s final_val = %s;
592 xc->setIntRegOperand(this, %s, final_val);\n
593 if (traceData) { traceData->setData(final_val); }
594 }''' % (wcond, self.ctype, self.base_name, windex)
595
596 return wb
597
598 class FloatRegOperand(Operand):
599 reg_class = 'FloatRegClass'
600
601 def isReg(self):
602 return 1
603
604 def isFloatReg(self):
605 return 1
606
607 def makeConstructor(self, predRead, predWrite):
608 c_src = ''
609 c_dest = ''
610
611 if self.is_src:
612 c_src = src_reg_constructor % (self.reg_class, self.reg_spec)
613
614 if self.is_dest:
615 c_dest = dst_reg_constructor % (self.reg_class, self.reg_spec)
616 c_dest += '\n\t_numFPDestRegs++;'
617
618 return c_src + c_dest
619
620 def makeRead(self, predRead):
621 if self.read_code != None:
622 return self.buildReadCode('readFloatRegOperandBits')
623
624 if predRead:
625 rindex = '_sourceIndex++'
626 else:
627 rindex = '%d' % self.src_reg_idx
628
629 code = 'xc->readFloatRegOperandBits(this, %s)' % rindex
630 if self.ctype == 'float':
631 code = 'bitsToFloat32(%s)' % code
632 elif self.ctype == 'double':
633 code = 'bitsToFloat64(%s)' % code
634 return '%s = %s;\n' % (self.base_name, code)
635
636 def makeWrite(self, predWrite):
637 if self.write_code != None:
638 return self.buildWriteCode('setFloatRegOperandBits')
639
640 if predWrite:
641 wp = '_destIndex++'
642 else:
643 wp = '%d' % self.dest_reg_idx
644
645 val = 'final_val'
646 if self.ctype == 'float':
647 val = 'floatToBits32(%s)' % val
648 elif self.ctype == 'double':
649 val = 'floatToBits64(%s)' % val
650
651 wp = 'xc->setFloatRegOperandBits(this, %s, %s);' % (wp, val)
652
653 wb = '''
654 {
655 %s final_val = %s;
656 %s\n
657 if (traceData) { traceData->setData(final_val); }
658 }''' % (self.ctype, self.base_name, wp)
659 return wb
660
661 class VecRegOperand(Operand):
662 reg_class = 'VecRegClass'
663
664 def __init__(self, parser, full_name, ext, is_src, is_dest):
665 Operand.__init__(self, parser, full_name, ext, is_src, is_dest)
666 self.elemExt = None
667 self.parser = parser
668
669 def isReg(self):
670 return 1
671
672 def isVecReg(self):
673 return 1
674
675 def makeDeclElem(self, elem_op):
676 (elem_name, elem_ext) = elem_op
677 (elem_spec, dflt_elem_ext, zeroing) = self.elems[elem_name]
678 if elem_ext:
679 ext = elem_ext
680 else:
681 ext = dflt_elem_ext
682 ctype = self.parser.operandTypeMap[ext]
683 return '\n\t%s %s = 0;' % (ctype, elem_name)
684
685 def makeDecl(self):
686 if not self.is_dest and self.is_src:
687 c_decl = '\t/* Vars for %s*/' % (self.base_name)
688 if hasattr(self, 'active_elems'):
689 if self.active_elems:
690 for elem in self.active_elems:
691 c_decl += self.makeDeclElem(elem)
692 return c_decl + '\t/* End vars for %s */\n' % (self.base_name)
693 else:
694 return ''
695
696 def makeConstructor(self, predRead, predWrite):
697 c_src = ''
698 c_dest = ''
699
700 numAccessNeeded = 1
701
702 if self.is_src:
703 c_src = src_reg_constructor % (self.reg_class, self.reg_spec)
704
705 if self.is_dest:
706 c_dest = dst_reg_constructor % (self.reg_class, self.reg_spec)
707 c_dest += '\n\t_numVecDestRegs++;'
708
709 return c_src + c_dest
710
711 # Read destination register to write
712 def makeReadWElem(self, elem_op):
713 (elem_name, elem_ext) = elem_op
714 (elem_spec, dflt_elem_ext, zeroing) = self.elems[elem_name]
715 if elem_ext:
716 ext = elem_ext
717 else:
718 ext = dflt_elem_ext
719 ctype = self.parser.operandTypeMap[ext]
720 c_read = '\t\t%s& %s = %s[%s];\n' % \
721 (ctype, elem_name, self.base_name, elem_spec)
722 return c_read
723
724 def makeReadW(self, predWrite):
725 func = 'getWritableVecRegOperand'
726 if self.read_code != None:
727 return self.buildReadCode(func)
728
729 if predWrite:
730 rindex = '_destIndex++'
731 else:
732 rindex = '%d' % self.dest_reg_idx
733
734 c_readw = '\t\t%s& tmp_d%s = xc->%s(this, %s);\n'\
735 % ('TheISA::VecRegContainer', rindex, func, rindex)
736 if self.elemExt:
737 c_readw += '\t\tauto %s = tmp_d%s.as<%s>();\n' % (self.base_name,
738 rindex, self.parser.operandTypeMap[self.elemExt])
739 if self.ext:
740 c_readw += '\t\tauto %s = tmp_d%s.as<%s>();\n' % (self.base_name,
741 rindex, self.parser.operandTypeMap[self.ext])
742 if hasattr(self, 'active_elems'):
743 if self.active_elems:
744 for elem in self.active_elems:
745 c_readw += self.makeReadWElem(elem)
746 return c_readw
747
748 # Normal source operand read
749 def makeReadElem(self, elem_op, name):
750 (elem_name, elem_ext) = elem_op
751 (elem_spec, dflt_elem_ext, zeroing) = self.elems[elem_name]
752
753 if elem_ext:
754 ext = elem_ext
755 else:
756 ext = dflt_elem_ext
757 ctype = self.parser.operandTypeMap[ext]
758 c_read = '\t\t%s = %s[%s];\n' % \
759 (elem_name, name, elem_spec)
760 return c_read
761
762 def makeRead(self, predRead):
763 func = 'readVecRegOperand'
764 if self.read_code != None:
765 return self.buildReadCode(func)
766
767 if predRead:
768 rindex = '_sourceIndex++'
769 else:
770 rindex = '%d' % self.src_reg_idx
771
772 name = self.base_name
773 if self.is_dest and self.is_src:
774 name += '_merger'
775
776 c_read = '\t\t%s& tmp_s%s = xc->%s(this, %s);\n' \
777 % ('const TheISA::VecRegContainer', rindex, func, rindex)
778 # If the parser has detected that elements are being access, create
779 # the appropriate view
780 if self.elemExt:
781 c_read += '\t\tauto %s = tmp_s%s.as<%s>();\n' % \
782 (name, rindex, self.parser.operandTypeMap[self.elemExt])
783 if self.ext:
784 c_read += '\t\tauto %s = tmp_s%s.as<%s>();\n' % \
785 (name, rindex, self.parser.operandTypeMap[self.ext])
786 if hasattr(self, 'active_elems'):
787 if self.active_elems:
788 for elem in self.active_elems:
789 c_read += self.makeReadElem(elem, name)
790 return c_read
791
792 def makeWrite(self, predWrite):
793 func = 'setVecRegOperand'
794 if self.write_code != None:
795 return self.buildWriteCode(func)
796
797 wb = '''
798 if (traceData) {
799 traceData->setData(tmp_d%d);
800 }
801 ''' % self.dest_reg_idx
802 return wb
803
804 def finalize(self, predRead, predWrite):
805 super(VecRegOperand, self).finalize(predRead, predWrite)
806 if self.is_dest:
807 self.op_rd = self.makeReadW(predWrite) + self.op_rd
808
809 class VecElemOperand(Operand):
810 reg_class = 'VecElemClass'
811
812 def isReg(self):
813 return 1
814
815 def isVecElem(self):
816 return 1
817
818 def makeDecl(self):
819 if self.is_dest and not self.is_src:
820 return '\n\t%s %s;' % (self.ctype, self.base_name)
821 else:
822 return ''
823
824 def makeConstructor(self, predRead, predWrite):
825 c_src = ''
826 c_dest = ''
827
828 numAccessNeeded = 1
829
830 if self.is_src:
831 c_src = ('\n\t_srcRegIdx[_numSrcRegs++] = RegId(%s, %s, %s);' %
832 (self.reg_class, self.reg_spec, self.elem_spec))
833
834 if self.is_dest:
835 c_dest = ('\n\t_destRegIdx[_numDestRegs++] = RegId(%s, %s, %s);' %
836 (self.reg_class, self.reg_spec, self.elem_spec))
837 c_dest += '\n\t_numVecElemDestRegs++;'
838 return c_src + c_dest
839
840 def makeRead(self, predRead):
841 c_read = 'xc->readVecElemOperand(this, %d)' % self.src_reg_idx
842
843 if self.ctype == 'float':
844 c_read = 'bitsToFloat32(%s)' % c_read
845 elif self.ctype == 'double':
846 c_read = 'bitsToFloat64(%s)' % c_read
847
848 return '\n\t%s %s = %s;\n' % (self.ctype, self.base_name, c_read)
849
850 def makeWrite(self, predWrite):
851 if self.ctype == 'float':
852 c_write = 'floatToBits32(%s)' % self.base_name
853 elif self.ctype == 'double':
854 c_write = 'floatToBits64(%s)' % self.base_name
855 else:
856 c_write = self.base_name
857
858 c_write = ('\n\txc->setVecElemOperand(this, %d, %s);' %
859 (self.dest_reg_idx, c_write))
860
861 return c_write
862
863 class VecPredRegOperand(Operand):
864 reg_class = 'VecPredRegClass'
865
866 def __init__(self, parser, full_name, ext, is_src, is_dest):
867 Operand.__init__(self, parser, full_name, ext, is_src, is_dest)
868 self.parser = parser
869
870 def isReg(self):
871 return 1
872
873 def isVecPredReg(self):
874 return 1
875
876 def makeDecl(self):
877 return ''
878
879 def makeConstructor(self, predRead, predWrite):
880 c_src = ''
881 c_dest = ''
882
883 if self.is_src:
884 c_src = src_reg_constructor % (self.reg_class, self.reg_spec)
885
886 if self.is_dest:
887 c_dest = dst_reg_constructor % (self.reg_class, self.reg_spec)
888 c_dest += '\n\t_numVecPredDestRegs++;'
889
890 return c_src + c_dest
891
892 def makeRead(self, predRead):
893 func = 'readVecPredRegOperand'
894 if self.read_code != None:
895 return self.buildReadCode(func)
896
897 if predRead:
898 rindex = '_sourceIndex++'
899 else:
900 rindex = '%d' % self.src_reg_idx
901
902 c_read = '\t\t%s& tmp_s%s = xc->%s(this, %s);\n' % (
903 'const TheISA::VecPredRegContainer', rindex, func, rindex)
904 if self.ext:
905 c_read += '\t\tauto %s = tmp_s%s.as<%s>();\n' % (
906 self.base_name, rindex,
907 self.parser.operandTypeMap[self.ext])
908 return c_read
909
910 def makeReadW(self, predWrite):
911 func = 'getWritableVecPredRegOperand'
912 if self.read_code != None:
913 return self.buildReadCode(func)
914
915 if predWrite:
916 rindex = '_destIndex++'
917 else:
918 rindex = '%d' % self.dest_reg_idx
919
920 c_readw = '\t\t%s& tmp_d%s = xc->%s(this, %s);\n' % (
921 'TheISA::VecPredRegContainer', rindex, func, rindex)
922 if self.ext:
923 c_readw += '\t\tauto %s = tmp_d%s.as<%s>();\n' % (
924 self.base_name, rindex,
925 self.parser.operandTypeMap[self.ext])
926 return c_readw
927
928 def makeWrite(self, predWrite):
929 func = 'setVecPredRegOperand'
930 if self.write_code != None:
931 return self.buildWriteCode(func)
932
933 wb = '''
934 if (traceData) {
935 traceData->setData(tmp_d%d);
936 }
937 ''' % self.dest_reg_idx
938 return wb
939
940 def finalize(self, predRead, predWrite):
941 super(VecPredRegOperand, self).finalize(predRead, predWrite)
942 if self.is_dest:
943 self.op_rd = self.makeReadW(predWrite) + self.op_rd
944
945 class CCRegOperand(Operand):
946 reg_class = 'CCRegClass'
947
948 def isReg(self):
949 return 1
950
951 def isCCReg(self):
952 return 1
953
954 def makeConstructor(self, predRead, predWrite):
955 c_src = ''
956 c_dest = ''
957
958 if self.is_src:
959 c_src = src_reg_constructor % (self.reg_class, self.reg_spec)
960 if self.hasReadPred():
961 c_src = '\n\tif (%s) {%s\n\t}' % \
962 (self.read_predicate, c_src)
963
964 if self.is_dest:
965 c_dest = dst_reg_constructor % (self.reg_class, self.reg_spec)
966 c_dest += '\n\t_numCCDestRegs++;'
967 if self.hasWritePred():
968 c_dest = '\n\tif (%s) {%s\n\t}' % \
969 (self.write_predicate, c_dest)
970
971 return c_src + c_dest
972
973 def makeRead(self, predRead):
974 if (self.ctype == 'float' or self.ctype == 'double'):
975 error('Attempt to read condition-code register as FP')
976 if self.read_code != None:
977 return self.buildReadCode('readCCRegOperand')
978
979 int_reg_val = ''
980 if predRead:
981 int_reg_val = 'xc->readCCRegOperand(this, _sourceIndex++)'
982 if self.hasReadPred():
983 int_reg_val = '(%s) ? %s : 0' % \
984 (self.read_predicate, int_reg_val)
985 else:
986 int_reg_val = 'xc->readCCRegOperand(this, %d)' % self.src_reg_idx
987
988 return '%s = %s;\n' % (self.base_name, int_reg_val)
989
990 def makeWrite(self, predWrite):
991 if (self.ctype == 'float' or self.ctype == 'double'):
992 error('Attempt to write condition-code register as FP')
993 if self.write_code != None:
994 return self.buildWriteCode('setCCRegOperand')
995
996 if predWrite:
997 wp = 'true'
998 if self.hasWritePred():
999 wp = self.write_predicate
1000
1001 wcond = 'if (%s)' % (wp)
1002 windex = '_destIndex++'
1003 else:
1004 wcond = ''
1005 windex = '%d' % self.dest_reg_idx
1006
1007 wb = '''
1008 %s
1009 {
1010 %s final_val = %s;
1011 xc->setCCRegOperand(this, %s, final_val);\n
1012 if (traceData) { traceData->setData(final_val); }
1013 }''' % (wcond, self.ctype, self.base_name, windex)
1014
1015 return wb
1016
1017 class ControlRegOperand(Operand):
1018 reg_class = 'MiscRegClass'
1019
1020 def isReg(self):
1021 return 1
1022
1023 def isControlReg(self):
1024 return 1
1025
1026 def makeConstructor(self, predRead, predWrite):
1027 c_src = ''
1028 c_dest = ''
1029
1030 if self.is_src:
1031 c_src = src_reg_constructor % (self.reg_class, self.reg_spec)
1032
1033 if self.is_dest:
1034 c_dest = dst_reg_constructor % (self.reg_class, self.reg_spec)
1035
1036 return c_src + c_dest
1037
1038 def makeRead(self, predRead):
1039 bit_select = 0
1040 if (self.ctype == 'float' or self.ctype == 'double'):
1041 error('Attempt to read control register as FP')
1042 if self.read_code != None:
1043 return self.buildReadCode('readMiscRegOperand')
1044
1045 if predRead:
1046 rindex = '_sourceIndex++'
1047 else:
1048 rindex = '%d' % self.src_reg_idx
1049
1050 return '%s = xc->readMiscRegOperand(this, %s);\n' % \
1051 (self.base_name, rindex)
1052
1053 def makeWrite(self, predWrite):
1054 if (self.ctype == 'float' or self.ctype == 'double'):
1055 error('Attempt to write control register as FP')
1056 if self.write_code != None:
1057 return self.buildWriteCode('setMiscRegOperand')
1058
1059 if predWrite:
1060 windex = '_destIndex++'
1061 else:
1062 windex = '%d' % self.dest_reg_idx
1063
1064 wb = 'xc->setMiscRegOperand(this, %s, %s);\n' % \
1065 (windex, self.base_name)
1066 wb += 'if (traceData) { traceData->setData(%s); }' % \
1067 self.base_name
1068
1069 return wb
1070
1071 class MemOperand(Operand):
1072 def isMem(self):
1073 return 1
1074
1075 def makeConstructor(self, predRead, predWrite):
1076 return ''
1077
1078 def makeDecl(self):
1079 # Declare memory data variable.
1080 return '%s %s;\n' % (self.ctype, self.base_name)
1081
1082 def makeRead(self, predRead):
1083 if self.read_code != None:
1084 return self.buildReadCode()
1085 return ''
1086
1087 def makeWrite(self, predWrite):
1088 if self.write_code != None:
1089 return self.buildWriteCode()
1090 return ''
1091
1092 class PCStateOperand(Operand):
1093 def makeConstructor(self, predRead, predWrite):
1094 return ''
1095
1096 def makeRead(self, predRead):
1097 if self.reg_spec:
1098 # A component of the PC state.
1099 return '%s = __parserAutoPCState.%s();\n' % \
1100 (self.base_name, self.reg_spec)
1101 else:
1102 # The whole PC state itself.
1103 return '%s = xc->pcState();\n' % self.base_name
1104
1105 def makeWrite(self, predWrite):
1106 if self.reg_spec:
1107 # A component of the PC state.
1108 return '__parserAutoPCState.%s(%s);\n' % \
1109 (self.reg_spec, self.base_name)
1110 else:
1111 # The whole PC state itself.
1112 return 'xc->pcState(%s);\n' % self.base_name
1113
1114 def makeDecl(self):
1115 ctype = 'TheISA::PCState'
1116 if self.isPCPart():
1117 ctype = self.ctype
1118 # Note that initializations in the declarations are solely
1119 # to avoid 'uninitialized variable' errors from the compiler.
1120 return '%s %s = 0;\n' % (ctype, self.base_name)
1121
1122 def isPCState(self):
1123 return 1
1124
1125 class OperandList(object):
1126 '''Find all the operands in the given code block. Returns an operand
1127 descriptor list (instance of class OperandList).'''
1128 def __init__(self, parser, code):
1129 self.items = []
1130 self.bases = {}
1131 # delete strings and comments so we don't match on operands inside
1132 for regEx in (stringRE, commentRE):
1133 code = regEx.sub('', code)
1134 # search for operands
1135 next_pos = 0
1136 while 1:
1137 match = parser.operandsRE.search(code, next_pos)
1138 if not match:
1139 # no more matches: we're done
1140 break
1141 op = match.groups()
1142 # regexp groups are operand full name, base, and extension
1143 (op_full, op_base, op_ext) = op
1144 # If is a elem operand, define or update the corresponding
1145 # vector operand
1146 isElem = False
1147 if op_base in parser.elemToVector:
1148 isElem = True
1149 elem_op = (op_base, op_ext)
1150 op_base = parser.elemToVector[op_base]
1151 op_ext = '' # use the default one
1152 # if the token following the operand is an assignment, this is
1153 # a destination (LHS), else it's a source (RHS)
1154 is_dest = (assignRE.match(code, match.end()) != None)
1155 is_src = not is_dest
1156
1157 # see if we've already seen this one
1158 op_desc = self.find_base(op_base)
1159 if op_desc:
1160 if op_ext and op_ext != '' and op_desc.ext != op_ext:
1161 error ('Inconsistent extensions for operand %s: %s - %s' \
1162 % (op_base, op_desc.ext, op_ext))
1163 op_desc.is_src = op_desc.is_src or is_src
1164 op_desc.is_dest = op_desc.is_dest or is_dest
1165 if isElem:
1166 (elem_base, elem_ext) = elem_op
1167 found = False
1168 for ae in op_desc.active_elems:
1169 (ae_base, ae_ext) = ae
1170 if ae_base == elem_base:
1171 if ae_ext != elem_ext:
1172 error('Inconsistent extensions for elem'
1173 ' operand %s' % elem_base)
1174 else:
1175 found = True
1176 if not found:
1177 op_desc.active_elems.append(elem_op)
1178 else:
1179 # new operand: create new descriptor
1180 op_desc = parser.operandNameMap[op_base](parser,
1181 op_full, op_ext, is_src, is_dest)
1182 # if operand is a vector elem, add the corresponding vector
1183 # operand if not already done
1184 if isElem:
1185 op_desc.elemExt = elem_op[1]
1186 op_desc.active_elems = [elem_op]
1187 self.append(op_desc)
1188 # start next search after end of current match
1189 next_pos = match.end()
1190 self.sort()
1191 # enumerate source & dest register operands... used in building
1192 # constructor later
1193 self.numSrcRegs = 0
1194 self.numDestRegs = 0
1195 self.numFPDestRegs = 0
1196 self.numIntDestRegs = 0
1197 self.numVecDestRegs = 0
1198 self.numVecPredDestRegs = 0
1199 self.numCCDestRegs = 0
1200 self.numMiscDestRegs = 0
1201 self.memOperand = None
1202
1203 # Flags to keep track if one or more operands are to be read/written
1204 # conditionally.
1205 self.predRead = False
1206 self.predWrite = False
1207
1208 for op_desc in self.items:
1209 if op_desc.isReg():
1210 if op_desc.is_src:
1211 op_desc.src_reg_idx = self.numSrcRegs
1212 self.numSrcRegs += 1
1213 if op_desc.is_dest:
1214 op_desc.dest_reg_idx = self.numDestRegs
1215 self.numDestRegs += 1
1216 if op_desc.isFloatReg():
1217 self.numFPDestRegs += 1
1218 elif op_desc.isIntReg():
1219 self.numIntDestRegs += 1
1220 elif op_desc.isVecReg():
1221 self.numVecDestRegs += 1
1222 elif op_desc.isVecPredReg():
1223 self.numVecPredDestRegs += 1
1224 elif op_desc.isCCReg():
1225 self.numCCDestRegs += 1
1226 elif op_desc.isControlReg():
1227 self.numMiscDestRegs += 1
1228 elif op_desc.isMem():
1229 if self.memOperand:
1230 error("Code block has more than one memory operand.")
1231 self.memOperand = op_desc
1232
1233 # Check if this operand has read/write predication. If true, then
1234 # the microop will dynamically index source/dest registers.
1235 self.predRead = self.predRead or op_desc.hasReadPred()
1236 self.predWrite = self.predWrite or op_desc.hasWritePred()
1237
1238 if parser.maxInstSrcRegs < self.numSrcRegs:
1239 parser.maxInstSrcRegs = self.numSrcRegs
1240 if parser.maxInstDestRegs < self.numDestRegs:
1241 parser.maxInstDestRegs = self.numDestRegs
1242 if parser.maxMiscDestRegs < self.numMiscDestRegs:
1243 parser.maxMiscDestRegs = self.numMiscDestRegs
1244
1245 # now make a final pass to finalize op_desc fields that may depend
1246 # on the register enumeration
1247 for op_desc in self.items:
1248 op_desc.finalize(self.predRead, self.predWrite)
1249
1250 def __len__(self):
1251 return len(self.items)
1252
1253 def __getitem__(self, index):
1254 return self.items[index]
1255
1256 def append(self, op_desc):
1257 self.items.append(op_desc)
1258 self.bases[op_desc.base_name] = op_desc
1259
1260 def find_base(self, base_name):
1261 # like self.bases[base_name], but returns None if not found
1262 # (rather than raising exception)
1263 return self.bases.get(base_name)
1264
1265 # internal helper function for concat[Some]Attr{Strings|Lists}
1266 def __internalConcatAttrs(self, attr_name, filter, result):
1267 for op_desc in self.items:
1268 if filter(op_desc):
1269 result += getattr(op_desc, attr_name)
1270 return result
1271
1272 # return a single string that is the concatenation of the (string)
1273 # values of the specified attribute for all operands
1274 def concatAttrStrings(self, attr_name):
1275 return self.__internalConcatAttrs(attr_name, lambda x: 1, '')
1276
1277 # like concatAttrStrings, but only include the values for the operands
1278 # for which the provided filter function returns true
1279 def concatSomeAttrStrings(self, filter, attr_name):
1280 return self.__internalConcatAttrs(attr_name, filter, '')
1281
1282 # return a single list that is the concatenation of the (list)
1283 # values of the specified attribute for all operands
1284 def concatAttrLists(self, attr_name):
1285 return self.__internalConcatAttrs(attr_name, lambda x: 1, [])
1286
1287 # like concatAttrLists, but only include the values for the operands
1288 # for which the provided filter function returns true
1289 def concatSomeAttrLists(self, filter, attr_name):
1290 return self.__internalConcatAttrs(attr_name, filter, [])
1291
1292 def sort(self):
1293 self.items.sort(lambda a, b: a.sort_pri - b.sort_pri)
1294
1295 class SubOperandList(OperandList):
1296 '''Find all the operands in the given code block. Returns an operand
1297 descriptor list (instance of class OperandList).'''
1298 def __init__(self, parser, code, master_list):
1299 self.items = []
1300 self.bases = {}
1301 # delete strings and comments so we don't match on operands inside
1302 for regEx in (stringRE, commentRE):
1303 code = regEx.sub('', code)
1304 # search for operands
1305 next_pos = 0
1306 while 1:
1307 match = parser.operandsRE.search(code, next_pos)
1308 if not match:
1309 # no more matches: we're done
1310 break
1311 op = match.groups()
1312 # regexp groups are operand full name, base, and extension
1313 (op_full, op_base, op_ext) = op
1314 # If is a elem operand, define or update the corresponding
1315 # vector operand
1316 if op_base in parser.elemToVector:
1317 elem_op = op_base
1318 op_base = parser.elemToVector[elem_op]
1319 # find this op in the master list
1320 op_desc = master_list.find_base(op_base)
1321 if not op_desc:
1322 error('Found operand %s which is not in the master list!'
1323 % op_base)
1324 else:
1325 # See if we've already found this operand
1326 op_desc = self.find_base(op_base)
1327 if not op_desc:
1328 # if not, add a reference to it to this sub list
1329 self.append(master_list.bases[op_base])
1330
1331 # start next search after end of current match
1332 next_pos = match.end()
1333 self.sort()
1334 self.memOperand = None
1335 # Whether the whole PC needs to be read so parts of it can be accessed
1336 self.readPC = False
1337 # Whether the whole PC needs to be written after parts of it were
1338 # changed
1339 self.setPC = False
1340 # Whether this instruction manipulates the whole PC or parts of it.
1341 # Mixing the two is a bad idea and flagged as an error.
1342 self.pcPart = None
1343
1344 # Flags to keep track if one or more operands are to be read/written
1345 # conditionally.
1346 self.predRead = False
1347 self.predWrite = False
1348
1349 for op_desc in self.items:
1350 if op_desc.isPCPart():
1351 self.readPC = True
1352 if op_desc.is_dest:
1353 self.setPC = True
1354
1355 if op_desc.isPCState():
1356 if self.pcPart is not None:
1357 if self.pcPart and not op_desc.isPCPart() or \
1358 not self.pcPart and op_desc.isPCPart():
1359 error("Mixed whole and partial PC state operands.")
1360 self.pcPart = op_desc.isPCPart()
1361
1362 if op_desc.isMem():
1363 if self.memOperand:
1364 error("Code block has more than one memory operand.")
1365 self.memOperand = op_desc
1366
1367 # Check if this operand has read/write predication. If true, then
1368 # the microop will dynamically index source/dest registers.
1369 self.predRead = self.predRead or op_desc.hasReadPred()
1370 self.predWrite = self.predWrite or op_desc.hasWritePred()
1371
1372 # Regular expression object to match C++ strings
1373 stringRE = re.compile(r'"([^"\\]|\\.)*"')
1374
1375 # Regular expression object to match C++ comments
1376 # (used in findOperands())
1377 commentRE = re.compile(r'(^)?[^\S\n]*/(?:\*(.*?)\*/[^\S\n]*|/[^\n]*)($)?',
1378 re.DOTALL | re.MULTILINE)
1379
1380 # Regular expression object to match assignment statements (used in
1381 # findOperands()). If the code immediately following the first
1382 # appearance of the operand matches this regex, then the operand
1383 # appears to be on the LHS of an assignment, and is thus a
1384 # destination. basically we're looking for an '=' that's not '=='.
1385 # The heinous tangle before that handles the case where the operand
1386 # has an array subscript.
1387 assignRE = re.compile(r'(\[[^\]]+\])?\s*=(?!=)', re.MULTILINE)
1388
1389 def makeFlagConstructor(flag_list):
1390 if len(flag_list) == 0:
1391 return ''
1392 # filter out repeated flags
1393 flag_list.sort()
1394 i = 1
1395 while i < len(flag_list):
1396 if flag_list[i] == flag_list[i-1]:
1397 del flag_list[i]
1398 else:
1399 i += 1
1400 pre = '\n\tflags['
1401 post = '] = true;'
1402 code = pre + string.join(flag_list, post + pre) + post
1403 return code
1404
1405 # Assume all instruction flags are of the form 'IsFoo'
1406 instFlagRE = re.compile(r'Is.*')
1407
1408 # OpClass constants end in 'Op' except No_OpClass
1409 opClassRE = re.compile(r'.*Op|No_OpClass')
1410
1411 class InstObjParams(object):
1412 def __init__(self, parser, mnem, class_name, base_class = '',
1413 snippets = {}, opt_args = []):
1414 self.mnemonic = mnem
1415 self.class_name = class_name
1416 self.base_class = base_class
1417 if not isinstance(snippets, dict):
1418 snippets = {'code' : snippets}
1419 compositeCode = ' '.join(map(str, snippets.values()))
1420 self.snippets = snippets
1421
1422 self.operands = OperandList(parser, compositeCode)
1423
1424 # The header of the constructor declares the variables to be used
1425 # in the body of the constructor.
1426 header = ''
1427 header += '\n\t_numSrcRegs = 0;'
1428 header += '\n\t_numDestRegs = 0;'
1429 header += '\n\t_numFPDestRegs = 0;'
1430 header += '\n\t_numVecDestRegs = 0;'
1431 header += '\n\t_numVecElemDestRegs = 0;'
1432 header += '\n\t_numVecPredDestRegs = 0;'
1433 header += '\n\t_numIntDestRegs = 0;'
1434 header += '\n\t_numCCDestRegs = 0;'
1435
1436 self.constructor = header + \
1437 self.operands.concatAttrStrings('constructor')
1438
1439 self.flags = self.operands.concatAttrLists('flags')
1440
1441 self.op_class = None
1442
1443 # Optional arguments are assumed to be either StaticInst flags
1444 # or an OpClass value. To avoid having to import a complete
1445 # list of these values to match against, we do it ad-hoc
1446 # with regexps.
1447 for oa in opt_args:
1448 if instFlagRE.match(oa):
1449 self.flags.append(oa)
1450 elif opClassRE.match(oa):
1451 self.op_class = oa
1452 else:
1453 error('InstObjParams: optional arg "%s" not recognized '
1454 'as StaticInst::Flag or OpClass.' % oa)
1455
1456 # Make a basic guess on the operand class if not set.
1457 # These are good enough for most cases.
1458 if not self.op_class:
1459 if 'IsStore' in self.flags:
1460 # The order matters here: 'IsFloating' and 'IsInteger' are
1461 # usually set in FP instructions because of the base
1462 # register
1463 if 'IsFloating' in self.flags:
1464 self.op_class = 'FloatMemWriteOp'
1465 else:
1466 self.op_class = 'MemWriteOp'
1467 elif 'IsLoad' in self.flags or 'IsPrefetch' in self.flags:
1468 # The order matters here: 'IsFloating' and 'IsInteger' are
1469 # usually set in FP instructions because of the base
1470 # register
1471 if 'IsFloating' in self.flags:
1472 self.op_class = 'FloatMemReadOp'
1473 else:
1474 self.op_class = 'MemReadOp'
1475 elif 'IsFloating' in self.flags:
1476 self.op_class = 'FloatAddOp'
1477 elif 'IsVector' in self.flags:
1478 self.op_class = 'SimdAddOp'
1479 else:
1480 self.op_class = 'IntAluOp'
1481
1482 # add flag initialization to contructor here to include
1483 # any flags added via opt_args
1484 self.constructor += makeFlagConstructor(self.flags)
1485
1486 # if 'IsFloating' is set, add call to the FP enable check
1487 # function (which should be provided by isa_desc via a declare)
1488 # if 'IsVector' is set, add call to the Vector enable check
1489 # function (which should be provided by isa_desc via a declare)
1490 if 'IsFloating' in self.flags:
1491 self.fp_enable_check = 'fault = checkFpEnableFault(xc);'
1492 elif 'IsVector' in self.flags:
1493 self.fp_enable_check = 'fault = checkVecEnableFault(xc);'
1494 else:
1495 self.fp_enable_check = ''
1496
1497 ##############
1498 # Stack: a simple stack object. Used for both formats (formatStack)
1499 # and default cases (defaultStack). Simply wraps a list to give more
1500 # stack-like syntax and enable initialization with an argument list
1501 # (as opposed to an argument that's a list).
1502
1503 class Stack(list):
1504 def __init__(self, *items):
1505 list.__init__(self, items)
1506
1507 def push(self, item):
1508 self.append(item);
1509
1510 def top(self):
1511 return self[-1]
1512
1513 # Format a file include stack backtrace as a string
1514 def backtrace(filename_stack):
1515 fmt = "In file included from %s:"
1516 return "\n".join([fmt % f for f in filename_stack])
1517
1518
1519 #######################
1520 #
1521 # LineTracker: track filenames along with line numbers in PLY lineno fields
1522 # PLY explicitly doesn't do anything with 'lineno' except propagate
1523 # it. This class lets us tie filenames with the line numbers with a
1524 # minimum of disruption to existing increment code.
1525 #
1526
1527 class LineTracker(object):
1528 def __init__(self, filename, lineno=1):
1529 self.filename = filename
1530 self.lineno = lineno
1531
1532 # Overload '+=' for increments. We need to create a new object on
1533 # each update else every token ends up referencing the same
1534 # constantly incrementing instance.
1535 def __iadd__(self, incr):
1536 return LineTracker(self.filename, self.lineno + incr)
1537
1538 def __str__(self):
1539 return "%s:%d" % (self.filename, self.lineno)
1540
1541 # In case there are places where someone really expects a number
1542 def __int__(self):
1543 return self.lineno
1544
1545
1546 #######################
1547 #
1548 # ISA Parser
1549 # parses ISA DSL and emits C++ headers and source
1550 #
1551
1552 class ISAParser(Grammar):
1553 def __init__(self, output_dir):
1554 super(ISAParser, self).__init__()
1555 self.output_dir = output_dir
1556
1557 self.filename = None # for output file watermarking/scaremongering
1558
1559 # variable to hold templates
1560 self.templateMap = {}
1561
1562 # This dictionary maps format name strings to Format objects.
1563 self.formatMap = {}
1564
1565 # Track open files and, if applicable, how many chunks it has been
1566 # split into so far.
1567 self.files = {}
1568 self.splits = {}
1569
1570 # isa_name / namespace identifier from namespace declaration.
1571 # before the namespace declaration, None.
1572 self.isa_name = None
1573 self.namespace = None
1574
1575 # The format stack.
1576 self.formatStack = Stack(NoFormat())
1577
1578 # The default case stack.
1579 self.defaultStack = Stack(None)
1580
1581 # Stack that tracks current file and line number. Each
1582 # element is a tuple (filename, lineno) that records the
1583 # *current* filename and the line number in the *previous*
1584 # file where it was included.
1585 self.fileNameStack = Stack()
1586
1587 symbols = ('makeList', 're', 'string')
1588 self.exportContext = dict([(s, eval(s)) for s in symbols])
1589
1590 self.maxInstSrcRegs = 0
1591 self.maxInstDestRegs = 0
1592 self.maxMiscDestRegs = 0
1593
1594 def __getitem__(self, i): # Allow object (self) to be
1595 return getattr(self, i) # passed to %-substitutions
1596
1597 # Change the file suffix of a base filename:
1598 # (e.g.) decoder.cc -> decoder-g.cc.inc for 'global' outputs
1599 def suffixize(self, s, sec):
1600 extn = re.compile('(\.[^\.]+)$') # isolate extension
1601 if self.namespace:
1602 return extn.sub(r'-ns\1.inc', s) # insert some text on either side
1603 else:
1604 return extn.sub(r'-g\1.inc', s)
1605
1606 # Get the file object for emitting code into the specified section
1607 # (header, decoder, exec, decode_block).
1608 def get_file(self, section):
1609 if section == 'decode_block':
1610 filename = 'decode-method.cc.inc'
1611 else:
1612 if section == 'header':
1613 file = 'decoder.hh'
1614 else:
1615 file = '%s.cc' % section
1616 filename = self.suffixize(file, section)
1617 try:
1618 return self.files[filename]
1619 except KeyError: pass
1620
1621 f = self.open(filename)
1622 self.files[filename] = f
1623
1624 # The splittable files are the ones with many independent
1625 # per-instruction functions - the decoder's instruction constructors
1626 # and the instruction execution (execute()) methods. These both have
1627 # the suffix -ns.cc.inc, meaning they are within the namespace part
1628 # of the ISA, contain object-emitting C++ source, and are included
1629 # into other top-level files. These are the files that need special
1630 # #define's to allow parts of them to be compiled separately. Rather
1631 # than splitting the emissions into separate files, the monolithic
1632 # output of the ISA parser is maintained, but the value (or lack
1633 # thereof) of the __SPLIT definition during C preprocessing will
1634 # select the different chunks. If no 'split' directives are used,
1635 # the cpp emissions have no effect.
1636 if re.search('-ns.cc.inc$', filename):
1637 print('#if !defined(__SPLIT) || (__SPLIT == 1)', file=f)
1638 self.splits[f] = 1
1639 # ensure requisite #include's
1640 elif filename == 'decoder-g.hh.inc':
1641 print('#include "base/bitfield.hh"', file=f)
1642
1643 return f
1644
1645 # Weave together the parts of the different output sections by
1646 # #include'ing them into some very short top-level .cc/.hh files.
1647 # These small files make it much clearer how this tool works, since
1648 # you directly see the chunks emitted as files that are #include'd.
1649 def write_top_level_files(self):
1650 # decoder header - everything depends on this
1651 file = 'decoder.hh'
1652 with self.open(file) as f:
1653 f.write('#ifndef __ARCH_%(isa)s_GENERATED_DECODER_HH__\n'
1654 '#define __ARCH_%(isa)s_GENERATED_DECODER_HH__\n\n' %
1655 {'isa': self.isa_name.upper()})
1656 fn = 'decoder-g.hh.inc'
1657 assert(fn in self.files)
1658 f.write('#include "%s"\n' % fn)
1659
1660 fn = 'decoder-ns.hh.inc'
1661 assert(fn in self.files)
1662 f.write('namespace %s {\n#include "%s"\n}\n'
1663 % (self.namespace, fn))
1664 f.write('\n#endif // __ARCH_%s_GENERATED_DECODER_HH__\n' %
1665 self.isa_name.upper())
1666
1667 # decoder method - cannot be split
1668 file = 'decoder.cc'
1669 with self.open(file) as f:
1670 fn = 'base/compiler.hh'
1671 f.write('#include "%s"\n' % fn)
1672
1673 fn = 'decoder-g.cc.inc'
1674 assert(fn in self.files)
1675 f.write('#include "%s"\n' % fn)
1676
1677 fn = 'decoder.hh'
1678 f.write('#include "%s"\n' % fn)
1679
1680 fn = 'decode-method.cc.inc'
1681 # is guaranteed to have been written for parse to complete
1682 f.write('#include "%s"\n' % fn)
1683
1684 extn = re.compile('(\.[^\.]+)$')
1685
1686 # instruction constructors
1687 splits = self.splits[self.get_file('decoder')]
1688 file_ = 'inst-constrs.cc'
1689 for i in range(1, splits+1):
1690 if splits > 1:
1691 file = extn.sub(r'-%d\1' % i, file_)
1692 else:
1693 file = file_
1694 with self.open(file) as f:
1695 fn = 'decoder-g.cc.inc'
1696 assert(fn in self.files)
1697 f.write('#include "%s"\n' % fn)
1698
1699 fn = 'decoder.hh'
1700 f.write('#include "%s"\n' % fn)
1701
1702 fn = 'decoder-ns.cc.inc'
1703 assert(fn in self.files)
1704 print('namespace %s {' % self.namespace, file=f)
1705 if splits > 1:
1706 print('#define __SPLIT %u' % i, file=f)
1707 print('#include "%s"' % fn, file=f)
1708 print('}', file=f)
1709
1710 # instruction execution
1711 splits = self.splits[self.get_file('exec')]
1712 for i in range(1, splits+1):
1713 file = 'generic_cpu_exec.cc'
1714 if splits > 1:
1715 file = extn.sub(r'_%d\1' % i, file)
1716 with self.open(file) as f:
1717 fn = 'exec-g.cc.inc'
1718 assert(fn in self.files)
1719 f.write('#include "%s"\n' % fn)
1720 f.write('#include "cpu/exec_context.hh"\n')
1721 f.write('#include "decoder.hh"\n')
1722
1723 fn = 'exec-ns.cc.inc'
1724 assert(fn in self.files)
1725 print('namespace %s {' % self.namespace, file=f)
1726 if splits > 1:
1727 print('#define __SPLIT %u' % i, file=f)
1728 print('#include "%s"' % fn, file=f)
1729 print('}', file=f)
1730
1731 # max_inst_regs.hh
1732 self.update('max_inst_regs.hh',
1733 '''namespace %(namespace)s {
1734 const int MaxInstSrcRegs = %(maxInstSrcRegs)d;
1735 const int MaxInstDestRegs = %(maxInstDestRegs)d;
1736 const int MaxMiscDestRegs = %(maxMiscDestRegs)d;\n}\n''' % self)
1737
1738 scaremonger_template ='''// DO NOT EDIT
1739 // This file was automatically generated from an ISA description:
1740 // %(filename)s
1741
1742 ''';
1743
1744 #####################################################################
1745 #
1746 # Lexer
1747 #
1748 # The PLY lexer module takes two things as input:
1749 # - A list of token names (the string list 'tokens')
1750 # - A regular expression describing a match for each token. The
1751 # regexp for token FOO can be provided in two ways:
1752 # - as a string variable named t_FOO
1753 # - as the doc string for a function named t_FOO. In this case,
1754 # the function is also executed, allowing an action to be
1755 # associated with each token match.
1756 #
1757 #####################################################################
1758
1759 # Reserved words. These are listed separately as they are matched
1760 # using the same regexp as generic IDs, but distinguished in the
1761 # t_ID() function. The PLY documentation suggests this approach.
1762 reserved = (
1763 'BITFIELD', 'DECODE', 'DECODER', 'DEFAULT', 'DEF', 'EXEC', 'FORMAT',
1764 'HEADER', 'LET', 'NAMESPACE', 'OPERAND_TYPES', 'OPERANDS',
1765 'OUTPUT', 'SIGNED', 'SPLIT', 'TEMPLATE'
1766 )
1767
1768 # List of tokens. The lex module requires this.
1769 tokens = reserved + (
1770 # identifier
1771 'ID',
1772
1773 # integer literal
1774 'INTLIT',
1775
1776 # string literal
1777 'STRLIT',
1778
1779 # code literal
1780 'CODELIT',
1781
1782 # ( ) [ ] { } < > , ; . : :: *
1783 'LPAREN', 'RPAREN',
1784 'LBRACKET', 'RBRACKET',
1785 'LBRACE', 'RBRACE',
1786 'LESS', 'GREATER', 'EQUALS',
1787 'COMMA', 'SEMI', 'DOT', 'COLON', 'DBLCOLON',
1788 'ASTERISK',
1789
1790 # C preprocessor directives
1791 'CPPDIRECTIVE'
1792
1793 # The following are matched but never returned. commented out to
1794 # suppress PLY warning
1795 # newfile directive
1796 # 'NEWFILE',
1797
1798 # endfile directive
1799 # 'ENDFILE'
1800 )
1801
1802 # Regular expressions for token matching
1803 t_LPAREN = r'\('
1804 t_RPAREN = r'\)'
1805 t_LBRACKET = r'\['
1806 t_RBRACKET = r'\]'
1807 t_LBRACE = r'\{'
1808 t_RBRACE = r'\}'
1809 t_LESS = r'\<'
1810 t_GREATER = r'\>'
1811 t_EQUALS = r'='
1812 t_COMMA = r','
1813 t_SEMI = r';'
1814 t_DOT = r'\.'
1815 t_COLON = r':'
1816 t_DBLCOLON = r'::'
1817 t_ASTERISK = r'\*'
1818
1819 # Identifiers and reserved words
1820 reserved_map = { }
1821 for r in reserved:
1822 reserved_map[r.lower()] = r
1823
1824 def t_ID(self, t):
1825 r'[A-Za-z_]\w*'
1826 t.type = self.reserved_map.get(t.value, 'ID')
1827 return t
1828
1829 # Integer literal
1830 def t_INTLIT(self, t):
1831 r'-?(0x[\da-fA-F]+)|\d+'
1832 try:
1833 t.value = int(t.value,0)
1834 except ValueError:
1835 error(t.lexer.lineno, 'Integer value "%s" too large' % t.value)
1836 t.value = 0
1837 return t
1838
1839 # String literal. Note that these use only single quotes, and
1840 # can span multiple lines.
1841 def t_STRLIT(self, t):
1842 r"(?m)'([^'])+'"
1843 # strip off quotes
1844 t.value = t.value[1:-1]
1845 t.lexer.lineno += t.value.count('\n')
1846 return t
1847
1848
1849 # "Code literal"... like a string literal, but delimiters are
1850 # '{{' and '}}' so they get formatted nicely under emacs c-mode
1851 def t_CODELIT(self, t):
1852 r"(?m)\{\{([^\}]|}(?!\}))+\}\}"
1853 # strip off {{ & }}
1854 t.value = t.value[2:-2]
1855 t.lexer.lineno += t.value.count('\n')
1856 return t
1857
1858 def t_CPPDIRECTIVE(self, t):
1859 r'^\#[^\#].*\n'
1860 t.lexer.lineno += t.value.count('\n')
1861 return t
1862
1863 def t_NEWFILE(self, t):
1864 r'^\#\#newfile\s+"[^"]*"\n'
1865 self.fileNameStack.push(t.lexer.lineno)
1866 t.lexer.lineno = LineTracker(t.value[11:-2])
1867
1868 def t_ENDFILE(self, t):
1869 r'^\#\#endfile\n'
1870 t.lexer.lineno = self.fileNameStack.pop()
1871
1872 #
1873 # The functions t_NEWLINE, t_ignore, and t_error are
1874 # special for the lex module.
1875 #
1876
1877 # Newlines
1878 def t_NEWLINE(self, t):
1879 r'\n+'
1880 t.lexer.lineno += t.value.count('\n')
1881
1882 # Comments
1883 def t_comment(self, t):
1884 r'//.*'
1885
1886 # Completely ignored characters
1887 t_ignore = ' \t\x0c'
1888
1889 # Error handler
1890 def t_error(self, t):
1891 error(t.lexer.lineno, "illegal character '%s'" % t.value[0])
1892 t.skip(1)
1893
1894 #####################################################################
1895 #
1896 # Parser
1897 #
1898 # Every function whose name starts with 'p_' defines a grammar
1899 # rule. The rule is encoded in the function's doc string, while
1900 # the function body provides the action taken when the rule is
1901 # matched. The argument to each function is a list of the values
1902 # of the rule's symbols: t[0] for the LHS, and t[1..n] for the
1903 # symbols on the RHS. For tokens, the value is copied from the
1904 # t.value attribute provided by the lexer. For non-terminals, the
1905 # value is assigned by the producing rule; i.e., the job of the
1906 # grammar rule function is to set the value for the non-terminal
1907 # on the LHS (by assigning to t[0]).
1908 #####################################################################
1909
1910 # The LHS of the first grammar rule is used as the start symbol
1911 # (in this case, 'specification'). Note that this rule enforces
1912 # that there will be exactly one namespace declaration, with 0 or
1913 # more global defs/decls before and after it. The defs & decls
1914 # before the namespace decl will be outside the namespace; those
1915 # after will be inside. The decoder function is always inside the
1916 # namespace.
1917 def p_specification(self, t):
1918 'specification : opt_defs_and_outputs top_level_decode_block'
1919
1920 for f in self.splits.iterkeys():
1921 f.write('\n#endif\n')
1922
1923 for f in self.files.itervalues(): # close ALL the files;
1924 f.close() # not doing so can cause compilation to fail
1925
1926 self.write_top_level_files()
1927
1928 t[0] = True
1929
1930 # 'opt_defs_and_outputs' is a possibly empty sequence of def and/or
1931 # output statements. Its productions do the hard work of eventually
1932 # instantiating a GenCode, which are generally emitted (written to disk)
1933 # as soon as possible, except for the decode_block, which has to be
1934 # accumulated into one large function of nested switch/case blocks.
1935 def p_opt_defs_and_outputs_0(self, t):
1936 'opt_defs_and_outputs : empty'
1937
1938 def p_opt_defs_and_outputs_1(self, t):
1939 'opt_defs_and_outputs : defs_and_outputs'
1940
1941 def p_defs_and_outputs_0(self, t):
1942 'defs_and_outputs : def_or_output'
1943
1944 def p_defs_and_outputs_1(self, t):
1945 'defs_and_outputs : defs_and_outputs def_or_output'
1946
1947 # The list of possible definition/output statements.
1948 # They are all processed as they are seen.
1949 def p_def_or_output(self, t):
1950 '''def_or_output : name_decl
1951 | def_format
1952 | def_bitfield
1953 | def_bitfield_struct
1954 | def_template
1955 | def_operand_types
1956 | def_operands
1957 | output
1958 | global_let
1959 | split'''
1960
1961 # Utility function used by both invocations of splitting - explicit
1962 # 'split' keyword and split() function inside "let {{ }};" blocks.
1963 def split(self, sec, write=False):
1964 assert(sec != 'header' and "header cannot be split")
1965
1966 f = self.get_file(sec)
1967 self.splits[f] += 1
1968 s = '\n#endif\n#if __SPLIT == %u\n' % self.splits[f]
1969 if write:
1970 f.write(s)
1971 else:
1972 return s
1973
1974 # split output file to reduce compilation time
1975 def p_split(self, t):
1976 'split : SPLIT output_type SEMI'
1977 assert(self.isa_name and "'split' not allowed before namespace decl")
1978
1979 self.split(t[2], True)
1980
1981 def p_output_type(self, t):
1982 '''output_type : DECODER
1983 | HEADER
1984 | EXEC'''
1985 t[0] = t[1]
1986
1987 # ISA name declaration looks like "namespace <foo>;"
1988 def p_name_decl(self, t):
1989 'name_decl : NAMESPACE ID SEMI'
1990 assert(self.isa_name == None and "Only 1 namespace decl permitted")
1991 self.isa_name = t[2]
1992 self.namespace = t[2] + 'Inst'
1993
1994 # Output blocks 'output <foo> {{...}}' (C++ code blocks) are copied
1995 # directly to the appropriate output section.
1996
1997 # Massage output block by substituting in template definitions and
1998 # bit operators. We handle '%'s embedded in the string that don't
1999 # indicate template substitutions by doubling them first so that the
2000 # format operation will reduce them back to single '%'s.
2001 def process_output(self, s):
2002 s = self.protectNonSubstPercents(s)
2003 return substBitOps(s % self.templateMap)
2004
2005 def p_output(self, t):
2006 'output : OUTPUT output_type CODELIT SEMI'
2007 kwargs = { t[2]+'_output' : self.process_output(t[3]) }
2008 GenCode(self, **kwargs).emit()
2009
2010 # global let blocks 'let {{...}}' (Python code blocks) are
2011 # executed directly when seen. Note that these execute in a
2012 # special variable context 'exportContext' to prevent the code
2013 # from polluting this script's namespace.
2014 def p_global_let(self, t):
2015 'global_let : LET CODELIT SEMI'
2016 def _split(sec):
2017 return self.split(sec)
2018 self.updateExportContext()
2019 self.exportContext["header_output"] = ''
2020 self.exportContext["decoder_output"] = ''
2021 self.exportContext["exec_output"] = ''
2022 self.exportContext["decode_block"] = ''
2023 self.exportContext["split"] = _split
2024 split_setup = '''
2025 def wrap(func):
2026 def split(sec):
2027 globals()[sec + '_output'] += func(sec)
2028 return split
2029 split = wrap(split)
2030 del wrap
2031 '''
2032 # This tricky setup (immediately above) allows us to just write
2033 # (e.g.) "split('exec')" in the Python code and the split #ifdef's
2034 # will automatically be added to the exec_output variable. The inner
2035 # Python execution environment doesn't know about the split points,
2036 # so we carefully inject and wrap a closure that can retrieve the
2037 # next split's #define from the parser and add it to the current
2038 # emission-in-progress.
2039 try:
2040 exec split_setup+fixPythonIndentation(t[2]) in self.exportContext
2041 except Exception, exc:
2042 traceback.print_exc(file=sys.stdout)
2043 if debug:
2044 raise
2045 error(t.lineno(1), 'In global let block: %s' % exc)
2046 GenCode(self,
2047 header_output=self.exportContext["header_output"],
2048 decoder_output=self.exportContext["decoder_output"],
2049 exec_output=self.exportContext["exec_output"],
2050 decode_block=self.exportContext["decode_block"]).emit()
2051
2052 # Define the mapping from operand type extensions to C++ types and
2053 # bit widths (stored in operandTypeMap).
2054 def p_def_operand_types(self, t):
2055 'def_operand_types : DEF OPERAND_TYPES CODELIT SEMI'
2056 try:
2057 self.operandTypeMap = eval('{' + t[3] + '}')
2058 except Exception, exc:
2059 if debug:
2060 raise
2061 error(t.lineno(1),
2062 'In def operand_types: %s' % exc)
2063
2064 # Define the mapping from operand names to operand classes and
2065 # other traits. Stored in operandNameMap.
2066 def p_def_operands(self, t):
2067 'def_operands : DEF OPERANDS CODELIT SEMI'
2068 if not hasattr(self, 'operandTypeMap'):
2069 error(t.lineno(1),
2070 'error: operand types must be defined before operands')
2071 try:
2072 user_dict = eval('{' + t[3] + '}', self.exportContext)
2073 except Exception, exc:
2074 if debug:
2075 raise
2076 error(t.lineno(1), 'In def operands: %s' % exc)
2077 self.buildOperandNameMap(user_dict, t.lexer.lineno)
2078
2079 # A bitfield definition looks like:
2080 # 'def [signed] bitfield <ID> [<first>:<last>]'
2081 # This generates a preprocessor macro in the output file.
2082 def p_def_bitfield_0(self, t):
2083 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT COLON INTLIT GREATER SEMI'
2084 expr = 'bits(machInst, %2d, %2d)' % (t[6], t[8])
2085 if (t[2] == 'signed'):
2086 expr = 'sext<%d>(%s)' % (t[6] - t[8] + 1, expr)
2087 hash_define = '#undef %s\n#define %s\t%s\n' % (t[4], t[4], expr)
2088 GenCode(self, header_output=hash_define).emit()
2089
2090 # alternate form for single bit: 'def [signed] bitfield <ID> [<bit>]'
2091 def p_def_bitfield_1(self, t):
2092 'def_bitfield : DEF opt_signed BITFIELD ID LESS INTLIT GREATER SEMI'
2093 expr = 'bits(machInst, %2d, %2d)' % (t[6], t[6])
2094 if (t[2] == 'signed'):
2095 expr = 'sext<%d>(%s)' % (1, expr)
2096 hash_define = '#undef %s\n#define %s\t%s\n' % (t[4], t[4], expr)
2097 GenCode(self, header_output=hash_define).emit()
2098
2099 # alternate form for structure member: 'def bitfield <ID> <ID>'
2100 def p_def_bitfield_struct(self, t):
2101 'def_bitfield_struct : DEF opt_signed BITFIELD ID id_with_dot SEMI'
2102 if (t[2] != ''):
2103 error(t.lineno(1),
2104 'error: structure bitfields are always unsigned.')
2105 expr = 'machInst.%s' % t[5]
2106 hash_define = '#undef %s\n#define %s\t%s\n' % (t[4], t[4], expr)
2107 GenCode(self, header_output=hash_define).emit()
2108
2109 def p_id_with_dot_0(self, t):
2110 'id_with_dot : ID'
2111 t[0] = t[1]
2112
2113 def p_id_with_dot_1(self, t):
2114 'id_with_dot : ID DOT id_with_dot'
2115 t[0] = t[1] + t[2] + t[3]
2116
2117 def p_opt_signed_0(self, t):
2118 'opt_signed : SIGNED'
2119 t[0] = t[1]
2120
2121 def p_opt_signed_1(self, t):
2122 'opt_signed : empty'
2123 t[0] = ''
2124
2125 def p_def_template(self, t):
2126 'def_template : DEF TEMPLATE ID CODELIT SEMI'
2127 if t[3] in self.templateMap:
2128 print("warning: template %s already defined" % t[3])
2129 self.templateMap[t[3]] = Template(self, t[4])
2130
2131 # An instruction format definition looks like
2132 # "def format <fmt>(<params>) {{...}};"
2133 def p_def_format(self, t):
2134 'def_format : DEF FORMAT ID LPAREN param_list RPAREN CODELIT SEMI'
2135 (id, params, code) = (t[3], t[5], t[7])
2136 self.defFormat(id, params, code, t.lexer.lineno)
2137
2138 # The formal parameter list for an instruction format is a
2139 # possibly empty list of comma-separated parameters. Positional
2140 # (standard, non-keyword) parameters must come first, followed by
2141 # keyword parameters, followed by a '*foo' parameter that gets
2142 # excess positional arguments (as in Python). Each of these three
2143 # parameter categories is optional.
2144 #
2145 # Note that we do not support the '**foo' parameter for collecting
2146 # otherwise undefined keyword args. Otherwise the parameter list
2147 # is (I believe) identical to what is supported in Python.
2148 #
2149 # The param list generates a tuple, where the first element is a
2150 # list of the positional params and the second element is a dict
2151 # containing the keyword params.
2152 def p_param_list_0(self, t):
2153 'param_list : positional_param_list COMMA nonpositional_param_list'
2154 t[0] = t[1] + t[3]
2155
2156 def p_param_list_1(self, t):
2157 '''param_list : positional_param_list
2158 | nonpositional_param_list'''
2159 t[0] = t[1]
2160
2161 def p_positional_param_list_0(self, t):
2162 'positional_param_list : empty'
2163 t[0] = []
2164
2165 def p_positional_param_list_1(self, t):
2166 'positional_param_list : ID'
2167 t[0] = [t[1]]
2168
2169 def p_positional_param_list_2(self, t):
2170 'positional_param_list : positional_param_list COMMA ID'
2171 t[0] = t[1] + [t[3]]
2172
2173 def p_nonpositional_param_list_0(self, t):
2174 'nonpositional_param_list : keyword_param_list COMMA excess_args_param'
2175 t[0] = t[1] + t[3]
2176
2177 def p_nonpositional_param_list_1(self, t):
2178 '''nonpositional_param_list : keyword_param_list
2179 | excess_args_param'''
2180 t[0] = t[1]
2181
2182 def p_keyword_param_list_0(self, t):
2183 'keyword_param_list : keyword_param'
2184 t[0] = [t[1]]
2185
2186 def p_keyword_param_list_1(self, t):
2187 'keyword_param_list : keyword_param_list COMMA keyword_param'
2188 t[0] = t[1] + [t[3]]
2189
2190 def p_keyword_param(self, t):
2191 'keyword_param : ID EQUALS expr'
2192 t[0] = t[1] + ' = ' + t[3].__repr__()
2193
2194 def p_excess_args_param(self, t):
2195 'excess_args_param : ASTERISK ID'
2196 # Just concatenate them: '*ID'. Wrap in list to be consistent
2197 # with positional_param_list and keyword_param_list.
2198 t[0] = [t[1] + t[2]]
2199
2200 # End of format definition-related rules.
2201 ##############
2202
2203 #
2204 # A decode block looks like:
2205 # decode <field1> [, <field2>]* [default <inst>] { ... }
2206 #
2207 def p_top_level_decode_block(self, t):
2208 'top_level_decode_block : decode_block'
2209 codeObj = t[1]
2210 codeObj.wrap_decode_block('''
2211 StaticInstPtr
2212 %(isa_name)s::Decoder::decodeInst(%(isa_name)s::ExtMachInst machInst)
2213 {
2214 using namespace %(namespace)s;
2215 ''' % self, '}')
2216
2217 codeObj.emit()
2218
2219 def p_decode_block(self, t):
2220 'decode_block : DECODE ID opt_default LBRACE decode_stmt_list RBRACE'
2221 default_defaults = self.defaultStack.pop()
2222 codeObj = t[5]
2223 # use the "default defaults" only if there was no explicit
2224 # default statement in decode_stmt_list
2225 if not codeObj.has_decode_default:
2226 codeObj += default_defaults
2227 codeObj.wrap_decode_block('switch (%s) {\n' % t[2], '}\n')
2228 t[0] = codeObj
2229
2230 # The opt_default statement serves only to push the "default
2231 # defaults" onto defaultStack. This value will be used by nested
2232 # decode blocks, and used and popped off when the current
2233 # decode_block is processed (in p_decode_block() above).
2234 def p_opt_default_0(self, t):
2235 'opt_default : empty'
2236 # no default specified: reuse the one currently at the top of
2237 # the stack
2238 self.defaultStack.push(self.defaultStack.top())
2239 # no meaningful value returned
2240 t[0] = None
2241
2242 def p_opt_default_1(self, t):
2243 'opt_default : DEFAULT inst'
2244 # push the new default
2245 codeObj = t[2]
2246 codeObj.wrap_decode_block('\ndefault:\n', 'break;\n')
2247 self.defaultStack.push(codeObj)
2248 # no meaningful value returned
2249 t[0] = None
2250
2251 def p_decode_stmt_list_0(self, t):
2252 'decode_stmt_list : decode_stmt'
2253 t[0] = t[1]
2254
2255 def p_decode_stmt_list_1(self, t):
2256 'decode_stmt_list : decode_stmt decode_stmt_list'
2257 if (t[1].has_decode_default and t[2].has_decode_default):
2258 error(t.lineno(1), 'Two default cases in decode block')
2259 t[0] = t[1] + t[2]
2260
2261 #
2262 # Decode statement rules
2263 #
2264 # There are four types of statements allowed in a decode block:
2265 # 1. Format blocks 'format <foo> { ... }'
2266 # 2. Nested decode blocks
2267 # 3. Instruction definitions.
2268 # 4. C preprocessor directives.
2269
2270
2271 # Preprocessor directives found in a decode statement list are
2272 # passed through to the output, replicated to all of the output
2273 # code streams. This works well for ifdefs, so we can ifdef out
2274 # both the declarations and the decode cases generated by an
2275 # instruction definition. Handling them as part of the grammar
2276 # makes it easy to keep them in the right place with respect to
2277 # the code generated by the other statements.
2278 def p_decode_stmt_cpp(self, t):
2279 'decode_stmt : CPPDIRECTIVE'
2280 t[0] = GenCode(self, t[1], t[1], t[1], t[1])
2281
2282 # A format block 'format <foo> { ... }' sets the default
2283 # instruction format used to handle instruction definitions inside
2284 # the block. This format can be overridden by using an explicit
2285 # format on the instruction definition or with a nested format
2286 # block.
2287 def p_decode_stmt_format(self, t):
2288 'decode_stmt : FORMAT push_format_id LBRACE decode_stmt_list RBRACE'
2289 # The format will be pushed on the stack when 'push_format_id'
2290 # is processed (see below). Once the parser has recognized
2291 # the full production (though the right brace), we're done
2292 # with the format, so now we can pop it.
2293 self.formatStack.pop()
2294 t[0] = t[4]
2295
2296 # This rule exists so we can set the current format (& push the
2297 # stack) when we recognize the format name part of the format
2298 # block.
2299 def p_push_format_id(self, t):
2300 'push_format_id : ID'
2301 try:
2302 self.formatStack.push(self.formatMap[t[1]])
2303 t[0] = ('', '// format %s' % t[1])
2304 except KeyError:
2305 error(t.lineno(1), 'instruction format "%s" not defined.' % t[1])
2306
2307 # Nested decode block: if the value of the current field matches
2308 # the specified constant(s), do a nested decode on some other field.
2309 def p_decode_stmt_decode(self, t):
2310 'decode_stmt : case_list COLON decode_block'
2311 case_list = t[1]
2312 codeObj = t[3]
2313 # just wrap the decoding code from the block as a case in the
2314 # outer switch statement.
2315 codeObj.wrap_decode_block('\n%s\n' % ''.join(case_list),
2316 'M5_UNREACHABLE;\n')
2317 codeObj.has_decode_default = (case_list == ['default:'])
2318 t[0] = codeObj
2319
2320 # Instruction definition (finally!).
2321 def p_decode_stmt_inst(self, t):
2322 'decode_stmt : case_list COLON inst SEMI'
2323 case_list = t[1]
2324 codeObj = t[3]
2325 codeObj.wrap_decode_block('\n%s' % ''.join(case_list), 'break;\n')
2326 codeObj.has_decode_default = (case_list == ['default:'])
2327 t[0] = codeObj
2328
2329 # The constant list for a decode case label must be non-empty, and must
2330 # either be the keyword 'default', or made up of one or more
2331 # comma-separated integer literals or strings which evaluate to
2332 # constants when compiled as C++.
2333 def p_case_list_0(self, t):
2334 'case_list : DEFAULT'
2335 t[0] = ['default:']
2336
2337 def prep_int_lit_case_label(self, lit):
2338 if lit >= 2**32:
2339 return 'case ULL(%#x): ' % lit
2340 else:
2341 return 'case %#x: ' % lit
2342
2343 def prep_str_lit_case_label(self, lit):
2344 return 'case %s: ' % lit
2345
2346 def p_case_list_1(self, t):
2347 'case_list : INTLIT'
2348 t[0] = [self.prep_int_lit_case_label(t[1])]
2349
2350 def p_case_list_2(self, t):
2351 'case_list : STRLIT'
2352 t[0] = [self.prep_str_lit_case_label(t[1])]
2353
2354 def p_case_list_3(self, t):
2355 'case_list : case_list COMMA INTLIT'
2356 t[0] = t[1]
2357 t[0].append(self.prep_int_lit_case_label(t[3]))
2358
2359 def p_case_list_4(self, t):
2360 'case_list : case_list COMMA STRLIT'
2361 t[0] = t[1]
2362 t[0].append(self.prep_str_lit_case_label(t[3]))
2363
2364 # Define an instruction using the current instruction format
2365 # (specified by an enclosing format block).
2366 # "<mnemonic>(<args>)"
2367 def p_inst_0(self, t):
2368 'inst : ID LPAREN arg_list RPAREN'
2369 # Pass the ID and arg list to the current format class to deal with.
2370 currentFormat = self.formatStack.top()
2371 codeObj = currentFormat.defineInst(self, t[1], t[3], t.lexer.lineno)
2372 args = ','.join(map(str, t[3]))
2373 args = re.sub('(?m)^', '//', args)
2374 args = re.sub('^//', '', args)
2375 comment = '\n// %s::%s(%s)\n' % (currentFormat.id, t[1], args)
2376 codeObj.prepend_all(comment)
2377 t[0] = codeObj
2378
2379 # Define an instruction using an explicitly specified format:
2380 # "<fmt>::<mnemonic>(<args>)"
2381 def p_inst_1(self, t):
2382 'inst : ID DBLCOLON ID LPAREN arg_list RPAREN'
2383 try:
2384 format = self.formatMap[t[1]]
2385 except KeyError:
2386 error(t.lineno(1), 'instruction format "%s" not defined.' % t[1])
2387
2388 codeObj = format.defineInst(self, t[3], t[5], t.lexer.lineno)
2389 comment = '\n// %s::%s(%s)\n' % (t[1], t[3], t[5])
2390 codeObj.prepend_all(comment)
2391 t[0] = codeObj
2392
2393 # The arg list generates a tuple, where the first element is a
2394 # list of the positional args and the second element is a dict
2395 # containing the keyword args.
2396 def p_arg_list_0(self, t):
2397 'arg_list : positional_arg_list COMMA keyword_arg_list'
2398 t[0] = ( t[1], t[3] )
2399
2400 def p_arg_list_1(self, t):
2401 'arg_list : positional_arg_list'
2402 t[0] = ( t[1], {} )
2403
2404 def p_arg_list_2(self, t):
2405 'arg_list : keyword_arg_list'
2406 t[0] = ( [], t[1] )
2407
2408 def p_positional_arg_list_0(self, t):
2409 'positional_arg_list : empty'
2410 t[0] = []
2411
2412 def p_positional_arg_list_1(self, t):
2413 'positional_arg_list : expr'
2414 t[0] = [t[1]]
2415
2416 def p_positional_arg_list_2(self, t):
2417 'positional_arg_list : positional_arg_list COMMA expr'
2418 t[0] = t[1] + [t[3]]
2419
2420 def p_keyword_arg_list_0(self, t):
2421 'keyword_arg_list : keyword_arg'
2422 t[0] = t[1]
2423
2424 def p_keyword_arg_list_1(self, t):
2425 'keyword_arg_list : keyword_arg_list COMMA keyword_arg'
2426 t[0] = t[1]
2427 t[0].update(t[3])
2428
2429 def p_keyword_arg(self, t):
2430 'keyword_arg : ID EQUALS expr'
2431 t[0] = { t[1] : t[3] }
2432
2433 #
2434 # Basic expressions. These constitute the argument values of
2435 # "function calls" (i.e. instruction definitions in the decode
2436 # block) and default values for formal parameters of format
2437 # functions.
2438 #
2439 # Right now, these are either strings, integers, or (recursively)
2440 # lists of exprs (using Python square-bracket list syntax). Note
2441 # that bare identifiers are trated as string constants here (since
2442 # there isn't really a variable namespace to refer to).
2443 #
2444 def p_expr_0(self, t):
2445 '''expr : ID
2446 | INTLIT
2447 | STRLIT
2448 | CODELIT'''
2449 t[0] = t[1]
2450
2451 def p_expr_1(self, t):
2452 '''expr : LBRACKET list_expr RBRACKET'''
2453 t[0] = t[2]
2454
2455 def p_list_expr_0(self, t):
2456 'list_expr : expr'
2457 t[0] = [t[1]]
2458
2459 def p_list_expr_1(self, t):
2460 'list_expr : list_expr COMMA expr'
2461 t[0] = t[1] + [t[3]]
2462
2463 def p_list_expr_2(self, t):
2464 'list_expr : empty'
2465 t[0] = []
2466
2467 #
2468 # Empty production... use in other rules for readability.
2469 #
2470 def p_empty(self, t):
2471 'empty :'
2472 pass
2473
2474 # Parse error handler. Note that the argument here is the
2475 # offending *token*, not a grammar symbol (hence the need to use
2476 # t.value)
2477 def p_error(self, t):
2478 if t:
2479 error(t.lexer.lineno, "syntax error at '%s'" % t.value)
2480 else:
2481 error("unknown syntax error")
2482
2483 # END OF GRAMMAR RULES
2484
2485 def updateExportContext(self):
2486
2487 # create a continuation that allows us to grab the current parser
2488 def wrapInstObjParams(*args):
2489 return InstObjParams(self, *args)
2490 self.exportContext['InstObjParams'] = wrapInstObjParams
2491 self.exportContext.update(self.templateMap)
2492
2493 def defFormat(self, id, params, code, lineno):
2494 '''Define a new format'''
2495
2496 # make sure we haven't already defined this one
2497 if id in self.formatMap:
2498 error(lineno, 'format %s redefined.' % id)
2499
2500 # create new object and store in global map
2501 self.formatMap[id] = Format(id, params, code)
2502
2503 def protectNonSubstPercents(self, s):
2504 '''Protect any non-dict-substitution '%'s in a format string
2505 (i.e. those not followed by '(')'''
2506
2507 return re.sub(r'%(?!\()', '%%', s)
2508
2509 def buildOperandNameMap(self, user_dict, lineno):
2510 operand_name = {}
2511 for op_name, val in user_dict.iteritems():
2512
2513 # Check if extra attributes have been specified.
2514 if len(val) > 9:
2515 error(lineno, 'error: too many attributes for operand "%s"' %
2516 base_cls_name)
2517
2518 # Pad val with None in case optional args are missing
2519 val += (None, None, None, None)
2520 base_cls_name, dflt_ext, reg_spec, flags, sort_pri, \
2521 read_code, write_code, read_predicate, write_predicate = val[:9]
2522
2523 # Canonical flag structure is a triple of lists, where each list
2524 # indicates the set of flags implied by this operand always, when
2525 # used as a source, and when used as a dest, respectively.
2526 # For simplicity this can be initialized using a variety of fairly
2527 # obvious shortcuts; we convert these to canonical form here.
2528 if not flags:
2529 # no flags specified (e.g., 'None')
2530 flags = ( [], [], [] )
2531 elif isinstance(flags, str):
2532 # a single flag: assumed to be unconditional
2533 flags = ( [ flags ], [], [] )
2534 elif isinstance(flags, list):
2535 # a list of flags: also assumed to be unconditional
2536 flags = ( flags, [], [] )
2537 elif isinstance(flags, tuple):
2538 # it's a tuple: it should be a triple,
2539 # but each item could be a single string or a list
2540 (uncond_flags, src_flags, dest_flags) = flags
2541 flags = (makeList(uncond_flags),
2542 makeList(src_flags), makeList(dest_flags))
2543
2544 # Accumulate attributes of new operand class in tmp_dict
2545 tmp_dict = {}
2546 attrList = ['reg_spec', 'flags', 'sort_pri',
2547 'read_code', 'write_code',
2548 'read_predicate', 'write_predicate']
2549 if dflt_ext:
2550 dflt_ctype = self.operandTypeMap[dflt_ext]
2551 attrList.extend(['dflt_ctype', 'dflt_ext'])
2552 # reg_spec is either just a string or a dictionary
2553 # (for elems of vector)
2554 if isinstance(reg_spec, tuple):
2555 (reg_spec, elem_spec) = reg_spec
2556 if isinstance(elem_spec, str):
2557 attrList.append('elem_spec')
2558 else:
2559 assert(isinstance(elem_spec, dict))
2560 elems = elem_spec
2561 attrList.append('elems')
2562 for attr in attrList:
2563 tmp_dict[attr] = eval(attr)
2564 tmp_dict['base_name'] = op_name
2565
2566 # New class name will be e.g. "IntReg_Ra"
2567 cls_name = base_cls_name + '_' + op_name
2568 # Evaluate string arg to get class object. Note that the
2569 # actual base class for "IntReg" is "IntRegOperand", i.e. we
2570 # have to append "Operand".
2571 try:
2572 base_cls = eval(base_cls_name + 'Operand')
2573 except NameError:
2574 error(lineno,
2575 'error: unknown operand base class "%s"' % base_cls_name)
2576 # The following statement creates a new class called
2577 # <cls_name> as a subclass of <base_cls> with the attributes
2578 # in tmp_dict, just as if we evaluated a class declaration.
2579 operand_name[op_name] = type(cls_name, (base_cls,), tmp_dict)
2580
2581 self.operandNameMap = operand_name
2582
2583 # Define operand variables.
2584 operands = user_dict.keys()
2585 # Add the elems defined in the vector operands and
2586 # build a map elem -> vector (used in OperandList)
2587 elem_to_vec = {}
2588 for op in user_dict.keys():
2589 if hasattr(self.operandNameMap[op], 'elems'):
2590 for elem in self.operandNameMap[op].elems.keys():
2591 operands.append(elem)
2592 elem_to_vec[elem] = op
2593 self.elemToVector = elem_to_vec
2594 extensions = self.operandTypeMap.keys()
2595
2596 operandsREString = r'''
2597 (?<!\w) # neg. lookbehind assertion: prevent partial matches
2598 ((%s)(?:_(%s))?) # match: operand with optional '_' then suffix
2599 (?!\w) # neg. lookahead assertion: prevent partial matches
2600 ''' % (string.join(operands, '|'), string.join(extensions, '|'))
2601
2602 self.operandsRE = re.compile(operandsREString, re.MULTILINE|re.VERBOSE)
2603
2604 # Same as operandsREString, but extension is mandatory, and only two
2605 # groups are returned (base and ext, not full name as above).
2606 # Used for subtituting '_' for '.' to make C++ identifiers.
2607 operandsWithExtREString = r'(?<!\w)(%s)_(%s)(?!\w)' \
2608 % (string.join(operands, '|'), string.join(extensions, '|'))
2609
2610 self.operandsWithExtRE = \
2611 re.compile(operandsWithExtREString, re.MULTILINE)
2612
2613 def substMungedOpNames(self, code):
2614 '''Munge operand names in code string to make legal C++
2615 variable names. This means getting rid of the type extension
2616 if any. Will match base_name attribute of Operand object.)'''
2617 return self.operandsWithExtRE.sub(r'\1', code)
2618
2619 def mungeSnippet(self, s):
2620 '''Fix up code snippets for final substitution in templates.'''
2621 if isinstance(s, str):
2622 return self.substMungedOpNames(substBitOps(s))
2623 else:
2624 return s
2625
2626 def open(self, name, bare=False):
2627 '''Open the output file for writing and include scary warning.'''
2628 filename = os.path.join(self.output_dir, name)
2629 f = open(filename, 'w')
2630 if f:
2631 if not bare:
2632 f.write(ISAParser.scaremonger_template % self)
2633 return f
2634
2635 def update(self, file, contents):
2636 '''Update the output file only. Scons should handle the case when
2637 the new contents are unchanged using its built-in hash feature.'''
2638 f = self.open(file)
2639 f.write(contents)
2640 f.close()
2641
2642 # This regular expression matches '##include' directives
2643 includeRE = re.compile(r'^\s*##include\s+"(?P<filename>[^"]*)".*$',
2644 re.MULTILINE)
2645
2646 def replace_include(self, matchobj, dirname):
2647 """Function to replace a matched '##include' directive with the
2648 contents of the specified file (with nested ##includes
2649 replaced recursively). 'matchobj' is an re match object
2650 (from a match of includeRE) and 'dirname' is the directory
2651 relative to which the file path should be resolved."""
2652
2653 fname = matchobj.group('filename')
2654 full_fname = os.path.normpath(os.path.join(dirname, fname))
2655 contents = '##newfile "%s"\n%s\n##endfile\n' % \
2656 (full_fname, self.read_and_flatten(full_fname))
2657 return contents
2658
2659 def read_and_flatten(self, filename):
2660 """Read a file and recursively flatten nested '##include' files."""
2661
2662 current_dir = os.path.dirname(filename)
2663 try:
2664 contents = open(filename).read()
2665 except IOError:
2666 error('Error including file "%s"' % filename)
2667
2668 self.fileNameStack.push(LineTracker(filename))
2669
2670 # Find any includes and include them
2671 def replace(matchobj):
2672 return self.replace_include(matchobj, current_dir)
2673 contents = self.includeRE.sub(replace, contents)
2674
2675 self.fileNameStack.pop()
2676 return contents
2677
2678 AlreadyGenerated = {}
2679
2680 def _parse_isa_desc(self, isa_desc_file):
2681 '''Read in and parse the ISA description.'''
2682
2683 # The build system can end up running the ISA parser twice: once to
2684 # finalize the build dependencies, and then to actually generate
2685 # the files it expects (in src/arch/$ARCH/generated). This code
2686 # doesn't do anything different either time, however; the SCons
2687 # invocations just expect different things. Since this code runs
2688 # within SCons, we can just remember that we've already run and
2689 # not perform a completely unnecessary run, since the ISA parser's
2690 # effect is idempotent.
2691 if isa_desc_file in ISAParser.AlreadyGenerated:
2692 return
2693
2694 # grab the last three path components of isa_desc_file
2695 self.filename = '/'.join(isa_desc_file.split('/')[-3:])
2696
2697 # Read file and (recursively) all included files into a string.
2698 # PLY requires that the input be in a single string so we have to
2699 # do this up front.
2700 isa_desc = self.read_and_flatten(isa_desc_file)
2701
2702 # Initialize lineno tracker
2703 self.lex.lineno = LineTracker(isa_desc_file)
2704
2705 # Parse.
2706 self.parse_string(isa_desc)
2707
2708 ISAParser.AlreadyGenerated[isa_desc_file] = None
2709
2710 def parse_isa_desc(self, *args, **kwargs):
2711 try:
2712 self._parse_isa_desc(*args, **kwargs)
2713 except ISAParserError, e:
2714 print(backtrace(self.fileNameStack))
2715 print("At %s:" % e.lineno)
2716 print(e)
2717 sys.exit(1)
2718
2719 # Called as script: get args from command line.
2720 # Args are: <isa desc file> <output dir>
2721 if __name__ == '__main__':
2722 ISAParser(sys.argv[2]).parse_isa_desc(sys.argv[1])