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