SimObject.py revision 7742:611fe187288e
15818Sgblack@eecs.umich.edu# Copyright (c) 2004-2006 The Regents of The University of Michigan 25818Sgblack@eecs.umich.edu# Copyright (c) 2010 Advanced Micro Devices, Inc. 35818Sgblack@eecs.umich.edu# All rights reserved. 45818Sgblack@eecs.umich.edu# 55818Sgblack@eecs.umich.edu# Redistribution and use in source and binary forms, with or without 65818Sgblack@eecs.umich.edu# modification, are permitted provided that the following conditions are 75818Sgblack@eecs.umich.edu# met: redistributions of source code must retain the above copyright 85818Sgblack@eecs.umich.edu# notice, this list of conditions and the following disclaimer; 95818Sgblack@eecs.umich.edu# redistributions in binary form must reproduce the above copyright 105818Sgblack@eecs.umich.edu# notice, this list of conditions and the following disclaimer in the 115818Sgblack@eecs.umich.edu# documentation and/or other materials provided with the distribution; 125818Sgblack@eecs.umich.edu# neither the name of the copyright holders nor the names of its 135818Sgblack@eecs.umich.edu# contributors may be used to endorse or promote products derived from 145818Sgblack@eecs.umich.edu# this software without specific prior written permission. 155818Sgblack@eecs.umich.edu# 165818Sgblack@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 175818Sgblack@eecs.umich.edu# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 185818Sgblack@eecs.umich.edu# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 195818Sgblack@eecs.umich.edu# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 205818Sgblack@eecs.umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 215818Sgblack@eecs.umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 225818Sgblack@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 235818Sgblack@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 245818Sgblack@eecs.umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 255818Sgblack@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 265818Sgblack@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 275818Sgblack@eecs.umich.edu# 285818Sgblack@eecs.umich.edu# Authors: Steve Reinhardt 295818Sgblack@eecs.umich.edu# Nathan Binkert 305818Sgblack@eecs.umich.edu 315818Sgblack@eecs.umich.eduimport sys 325818Sgblack@eecs.umich.edufrom types import FunctionType, MethodType 335818Sgblack@eecs.umich.edu 345818Sgblack@eecs.umich.edutry: 355818Sgblack@eecs.umich.edu import pydot 365818Sgblack@eecs.umich.eduexcept: 375818Sgblack@eecs.umich.edu pydot = False 385818Sgblack@eecs.umich.edu 395818Sgblack@eecs.umich.eduimport m5 405818Sgblack@eecs.umich.edufrom m5.util import * 415818Sgblack@eecs.umich.edu 425818Sgblack@eecs.umich.edu# Have to import params up top since Param is referenced on initial 435818Sgblack@eecs.umich.edu# load (when SimObject class references Param to create a class 445818Sgblack@eecs.umich.edu# variable, the 'name' param)... 455818Sgblack@eecs.umich.edufrom m5.params import * 465818Sgblack@eecs.umich.edu# There are a few things we need that aren't in params.__all__ since 475818Sgblack@eecs.umich.edu# normal users don't need them 485818Sgblack@eecs.umich.edufrom m5.params import ParamDesc, VectorParamDesc, \ 495818Sgblack@eecs.umich.edu isNullPointer, SimObjectVector 505818Sgblack@eecs.umich.edu 515818Sgblack@eecs.umich.edufrom m5.proxy import * 525818Sgblack@eecs.umich.edufrom m5.proxy import isproxy 535818Sgblack@eecs.umich.edu 545818Sgblack@eecs.umich.edu##################################################################### 559808Sstever@gmail.com# 565818Sgblack@eecs.umich.edu# M5 Python Configuration Utility 575818Sgblack@eecs.umich.edu# 5811175Sandreas.hansson@arm.com# The basic idea is to write simple Python programs that build Python 595818Sgblack@eecs.umich.edu# objects corresponding to M5 SimObjects for the desired simulation 6011175Sandreas.hansson@arm.com# configuration. For now, the Python emits a .ini file that can be 617903Shestness@cs.utexas.edu# parsed by M5. In the future, some tighter integration between M5 6211168Sandreas.hansson@arm.com# and the Python interpreter may allow bypassing the .ini file. 6311168Sandreas.hansson@arm.com# 645818Sgblack@eecs.umich.edu# Each SimObject class in M5 is represented by a Python class with the 655818Sgblack@eecs.umich.edu# same name. The Python inheritance tree mirrors the M5 C++ tree 667811Ssteve.reinhardt@amd.com# (e.g., SimpleCPU derives from BaseCPU in both cases, and all 675818Sgblack@eecs.umich.edu# SimObjects inherit from a single SimObject base class). To specify 685818Sgblack@eecs.umich.edu# an instance of an M5 SimObject in a configuration, the user simply 69# instantiates the corresponding Python object. The parameters for 70# that SimObject are given by assigning to attributes of the Python 71# object, either using keyword assignment in the constructor or in 72# separate assignment statements. For example: 73# 74# cache = BaseCache(size='64KB') 75# cache.hit_latency = 3 76# cache.assoc = 8 77# 78# The magic lies in the mapping of the Python attributes for SimObject 79# classes to the actual SimObject parameter specifications. This 80# allows parameter validity checking in the Python code. Continuing 81# the example above, the statements "cache.blurfl=3" or 82# "cache.assoc='hello'" would both result in runtime errors in Python, 83# since the BaseCache object has no 'blurfl' parameter and the 'assoc' 84# parameter requires an integer, respectively. This magic is done 85# primarily by overriding the special __setattr__ method that controls 86# assignment to object attributes. 87# 88# Once a set of Python objects have been instantiated in a hierarchy, 89# calling 'instantiate(obj)' (where obj is the root of the hierarchy) 90# will generate a .ini file. 91# 92##################################################################### 93 94# list of all SimObject classes 95allClasses = {} 96 97# dict to look up SimObjects based on path 98instanceDict = {} 99 100def default_cxx_predecls(cls, code): 101 code('#include "params/$cls.hh"') 102 103def default_swig_predecls(cls, code): 104 code('%import "python/m5/internal/param_$cls.i"') 105 106def default_swig_objdecls(cls, code): 107 class_path = cls.cxx_class.split('::') 108 classname = class_path[-1] 109 namespaces = class_path[:-1] 110 111 for ns in namespaces: 112 code('namespace $ns {') 113 114 if namespaces: 115 code('// avoid name conflicts') 116 sep_string = '_COLONS_' 117 flat_name = sep_string.join(class_path) 118 code('%rename($flat_name) $classname;') 119 120 code() 121 code('// stop swig from creating/wrapping default ctor/dtor') 122 code('%nodefault $classname;') 123 code('class $classname') 124 if cls._base: 125 code(' : public ${{cls._base.cxx_class}}') 126 code('{};') 127 128 for ns in reversed(namespaces): 129 code('/* namespace $ns */ }') 130 131def public_value(key, value): 132 return key.startswith('_') or \ 133 isinstance(value, (FunctionType, MethodType, classmethod, type)) 134 135# The metaclass for SimObject. This class controls how new classes 136# that derive from SimObject are instantiated, and provides inherited 137# class behavior (just like a class controls how instances of that 138# class are instantiated, and provides inherited instance behavior). 139class MetaSimObject(type): 140 # Attributes that can be set only at initialization time 141 init_keywords = { 'abstract' : bool, 142 'cxx_class' : str, 143 'cxx_type' : str, 144 'cxx_predecls' : MethodType, 145 'swig_objdecls' : MethodType, 146 'swig_predecls' : MethodType, 147 'type' : str } 148 # Attributes that can be set any time 149 keywords = { 'check' : FunctionType } 150 151 # __new__ is called before __init__, and is where the statements 152 # in the body of the class definition get loaded into the class's 153 # __dict__. We intercept this to filter out parameter & port assignments 154 # and only allow "private" attributes to be passed to the base 155 # __new__ (starting with underscore). 156 def __new__(mcls, name, bases, dict): 157 assert name not in allClasses, "SimObject %s already present" % name 158 159 # Copy "private" attributes, functions, and classes to the 160 # official dict. Everything else goes in _init_dict to be 161 # filtered in __init__. 162 cls_dict = {} 163 value_dict = {} 164 for key,val in dict.items(): 165 if public_value(key, val): 166 cls_dict[key] = val 167 else: 168 # must be a param/port setting 169 value_dict[key] = val 170 if 'abstract' not in value_dict: 171 value_dict['abstract'] = False 172 cls_dict['_value_dict'] = value_dict 173 cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict) 174 if 'type' in value_dict: 175 allClasses[name] = cls 176 return cls 177 178 # subclass initialization 179 def __init__(cls, name, bases, dict): 180 # calls type.__init__()... I think that's a no-op, but leave 181 # it here just in case it's not. 182 super(MetaSimObject, cls).__init__(name, bases, dict) 183 184 # initialize required attributes 185 186 # class-only attributes 187 cls._params = multidict() # param descriptions 188 cls._ports = multidict() # port descriptions 189 190 # class or instance attributes 191 cls._values = multidict() # param values 192 cls._children = multidict() # SimObject children 193 cls._port_refs = multidict() # port ref objects 194 cls._instantiated = False # really instantiated, cloned, or subclassed 195 196 # We don't support multiple inheritance. If you want to, you 197 # must fix multidict to deal with it properly. 198 if len(bases) > 1: 199 raise TypeError, "SimObjects do not support multiple inheritance" 200 201 base = bases[0] 202 203 # Set up general inheritance via multidicts. A subclass will 204 # inherit all its settings from the base class. The only time 205 # the following is not true is when we define the SimObject 206 # class itself (in which case the multidicts have no parent). 207 if isinstance(base, MetaSimObject): 208 cls._base = base 209 cls._params.parent = base._params 210 cls._ports.parent = base._ports 211 cls._values.parent = base._values 212 cls._children.parent = base._children 213 cls._port_refs.parent = base._port_refs 214 # mark base as having been subclassed 215 base._instantiated = True 216 else: 217 cls._base = None 218 219 # default keyword values 220 if 'type' in cls._value_dict: 221 if 'cxx_class' not in cls._value_dict: 222 cls._value_dict['cxx_class'] = cls._value_dict['type'] 223 224 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class'] 225 226 if 'cxx_predecls' not in cls.__dict__: 227 m = MethodType(default_cxx_predecls, cls, MetaSimObject) 228 setattr(cls, 'cxx_predecls', m) 229 230 if 'swig_predecls' not in cls.__dict__: 231 m = MethodType(default_swig_predecls, cls, MetaSimObject) 232 setattr(cls, 'swig_predecls', m) 233 234 if 'swig_objdecls' not in cls.__dict__: 235 m = MethodType(default_swig_objdecls, cls, MetaSimObject) 236 setattr(cls, 'swig_objdecls', m) 237 238 # Now process the _value_dict items. They could be defining 239 # new (or overriding existing) parameters or ports, setting 240 # class keywords (e.g., 'abstract'), or setting parameter 241 # values or port bindings. The first 3 can only be set when 242 # the class is defined, so we handle them here. The others 243 # can be set later too, so just emulate that by calling 244 # setattr(). 245 for key,val in cls._value_dict.items(): 246 # param descriptions 247 if isinstance(val, ParamDesc): 248 cls._new_param(key, val) 249 250 # port objects 251 elif isinstance(val, Port): 252 cls._new_port(key, val) 253 254 # init-time-only keywords 255 elif cls.init_keywords.has_key(key): 256 cls._set_keyword(key, val, cls.init_keywords[key]) 257 258 # default: use normal path (ends up in __setattr__) 259 else: 260 setattr(cls, key, val) 261 262 def _set_keyword(cls, keyword, val, kwtype): 263 if not isinstance(val, kwtype): 264 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \ 265 (keyword, type(val), kwtype) 266 if isinstance(val, FunctionType): 267 val = classmethod(val) 268 type.__setattr__(cls, keyword, val) 269 270 def _new_param(cls, name, pdesc): 271 # each param desc should be uniquely assigned to one variable 272 assert(not hasattr(pdesc, 'name')) 273 pdesc.name = name 274 cls._params[name] = pdesc 275 if hasattr(pdesc, 'default'): 276 cls._set_param(name, pdesc.default, pdesc) 277 278 def _set_param(cls, name, value, param): 279 assert(param.name == name) 280 try: 281 cls._values[name] = param.convert(value) 282 except Exception, e: 283 msg = "%s\nError setting param %s.%s to %s\n" % \ 284 (e, cls.__name__, name, value) 285 e.args = (msg, ) 286 raise 287 288 def _new_port(cls, name, port): 289 # each port should be uniquely assigned to one variable 290 assert(not hasattr(port, 'name')) 291 port.name = name 292 cls._ports[name] = port 293 if hasattr(port, 'default'): 294 cls._cls_get_port_ref(name).connect(port.default) 295 296 # same as _get_port_ref, effectively, but for classes 297 def _cls_get_port_ref(cls, attr): 298 # Return reference that can be assigned to another port 299 # via __setattr__. There is only ever one reference 300 # object per port, but we create them lazily here. 301 ref = cls._port_refs.get(attr) 302 if not ref: 303 ref = cls._ports[attr].makeRef(cls) 304 cls._port_refs[attr] = ref 305 return ref 306 307 # Set attribute (called on foo.attr = value when foo is an 308 # instance of class cls). 309 def __setattr__(cls, attr, value): 310 # normal processing for private attributes 311 if public_value(attr, value): 312 type.__setattr__(cls, attr, value) 313 return 314 315 if cls.keywords.has_key(attr): 316 cls._set_keyword(attr, value, cls.keywords[attr]) 317 return 318 319 if cls._ports.has_key(attr): 320 cls._cls_get_port_ref(attr).connect(value) 321 return 322 323 if isSimObjectOrSequence(value) and cls._instantiated: 324 raise RuntimeError, \ 325 "cannot set SimObject parameter '%s' after\n" \ 326 " class %s has been instantiated or subclassed" \ 327 % (attr, cls.__name__) 328 329 # check for param 330 param = cls._params.get(attr) 331 if param: 332 cls._set_param(attr, value, param) 333 return 334 335 if isSimObjectOrSequence(value): 336 # If RHS is a SimObject, it's an implicit child assignment. 337 cls._children[attr] = coerceSimObjectOrVector(value) 338 return 339 340 # no valid assignment... raise exception 341 raise AttributeError, \ 342 "Class %s has no parameter \'%s\'" % (cls.__name__, attr) 343 344 def __getattr__(cls, attr): 345 if attr == 'cxx_class_path': 346 return cls.cxx_class.split('::') 347 348 if attr == 'cxx_class_name': 349 return cls.cxx_class_path[-1] 350 351 if attr == 'cxx_namespaces': 352 return cls.cxx_class_path[:-1] 353 354 if cls._values.has_key(attr): 355 return cls._values[attr] 356 357 if cls._children.has_key(attr): 358 return cls._children[attr] 359 360 raise AttributeError, \ 361 "object '%s' has no attribute '%s'" % (cls.__name__, attr) 362 363 def __str__(cls): 364 return cls.__name__ 365 366 def cxx_decl(cls, code): 367 # The 'dict' attribute restricts us to the params declared in 368 # the object itself, not including inherited params (which 369 # will also be inherited from the base class's param struct 370 # here). 371 params = cls._params.local.values() 372 try: 373 ptypes = [p.ptype for p in params] 374 except: 375 print cls, p, p.ptype_str 376 print params 377 raise 378 379 class_path = cls._value_dict['cxx_class'].split('::') 380 381 code('''\ 382#ifndef __PARAMS__${cls}__ 383#define __PARAMS__${cls}__ 384 385''') 386 387 # A forward class declaration is sufficient since we are just 388 # declaring a pointer. 389 for ns in class_path[:-1]: 390 code('namespace $ns {') 391 code('class $0;', class_path[-1]) 392 for ns in reversed(class_path[:-1]): 393 code('/* namespace $ns */ }') 394 code() 395 396 for param in params: 397 param.cxx_predecls(code) 398 code() 399 400 if cls._base: 401 code('#include "params/${{cls._base.type}}.hh"') 402 code() 403 404 for ptype in ptypes: 405 if issubclass(ptype, Enum): 406 code('#include "enums/${{ptype.__name__}}.hh"') 407 code() 408 409 cls.cxx_struct(code, cls._base, params) 410 411 code() 412 code('#endif // __PARAMS__${cls}__') 413 return code 414 415 def cxx_struct(cls, code, base, params): 416 if cls == SimObject: 417 code('#include "sim/sim_object_params.hh"') 418 return 419 420 # now generate the actual param struct 421 code("struct ${cls}Params") 422 if base: 423 code(" : public ${{base.type}}Params") 424 code("{") 425 if not hasattr(cls, 'abstract') or not cls.abstract: 426 if 'type' in cls.__dict__: 427 code(" ${{cls.cxx_type}} create();") 428 429 code.indent() 430 for param in params: 431 param.cxx_decl(code) 432 code.dedent() 433 code('};') 434 435 def swig_decl(cls, code): 436 code('''\ 437%module $cls 438 439%{ 440#include "params/$cls.hh" 441%} 442 443''') 444 445 # The 'dict' attribute restricts us to the params declared in 446 # the object itself, not including inherited params (which 447 # will also be inherited from the base class's param struct 448 # here). 449 params = cls._params.local.values() 450 ptypes = [p.ptype for p in params] 451 452 # get all predeclarations 453 for param in params: 454 param.swig_predecls(code) 455 code() 456 457 if cls._base: 458 code('%import "python/m5/internal/param_${{cls._base.type}}.i"') 459 code() 460 461 for ptype in ptypes: 462 if issubclass(ptype, Enum): 463 code('%import "enums/${{ptype.__name__}}.hh"') 464 code() 465 466 code('%import "params/${cls}_type.hh"') 467 code('%include "params/${cls}.hh"') 468 469# The SimObject class is the root of the special hierarchy. Most of 470# the code in this class deals with the configuration hierarchy itself 471# (parent/child node relationships). 472class SimObject(object): 473 # Specify metaclass. Any class inheriting from SimObject will 474 # get this metaclass. 475 __metaclass__ = MetaSimObject 476 type = 'SimObject' 477 abstract = True 478 479 @classmethod 480 def swig_objdecls(cls, code): 481 code('%include "python/swig/sim_object.i"') 482 483 # Initialize new instance. For objects with SimObject-valued 484 # children, we need to recursively clone the classes represented 485 # by those param values as well in a consistent "deep copy"-style 486 # fashion. That is, we want to make sure that each instance is 487 # cloned only once, and that if there are multiple references to 488 # the same original object, we end up with the corresponding 489 # cloned references all pointing to the same cloned instance. 490 def __init__(self, **kwargs): 491 ancestor = kwargs.get('_ancestor') 492 memo_dict = kwargs.get('_memo') 493 if memo_dict is None: 494 # prepare to memoize any recursively instantiated objects 495 memo_dict = {} 496 elif ancestor: 497 # memoize me now to avoid problems with recursive calls 498 memo_dict[ancestor] = self 499 500 if not ancestor: 501 ancestor = self.__class__ 502 ancestor._instantiated = True 503 504 # initialize required attributes 505 self._parent = None 506 self._name = None 507 self._ccObject = None # pointer to C++ object 508 self._ccParams = None 509 self._instantiated = False # really "cloned" 510 511 # Inherit parameter values from class using multidict so 512 # individual value settings can be overridden but we still 513 # inherit late changes to non-overridden class values. 514 self._values = multidict(ancestor._values) 515 # clone SimObject-valued parameters 516 for key,val in ancestor._values.iteritems(): 517 val = tryAsSimObjectOrVector(val) 518 if val is not None: 519 self._values[key] = val(_memo=memo_dict) 520 521 # Clone children specified at class level. No need for a 522 # multidict here since we will be cloning everything. 523 self._children = {} 524 for key,val in ancestor._children.iteritems(): 525 self.add_child(key, val(_memo=memo_dict)) 526 527 # clone port references. no need to use a multidict here 528 # since we will be creating new references for all ports. 529 self._port_refs = {} 530 for key,val in ancestor._port_refs.iteritems(): 531 self._port_refs[key] = val.clone(self, memo_dict) 532 # apply attribute assignments from keyword args, if any 533 for key,val in kwargs.iteritems(): 534 setattr(self, key, val) 535 536 # "Clone" the current instance by creating another instance of 537 # this instance's class, but that inherits its parameter values 538 # and port mappings from the current instance. If we're in a 539 # "deep copy" recursive clone, check the _memo dict to see if 540 # we've already cloned this instance. 541 def __call__(self, **kwargs): 542 memo_dict = kwargs.get('_memo') 543 if memo_dict is None: 544 # no memo_dict: must be top-level clone operation. 545 # this is only allowed at the root of a hierarchy 546 if self._parent: 547 raise RuntimeError, "attempt to clone object %s " \ 548 "not at the root of a tree (parent = %s)" \ 549 % (self, self._parent) 550 # create a new dict and use that. 551 memo_dict = {} 552 kwargs['_memo'] = memo_dict 553 elif memo_dict.has_key(self): 554 # clone already done & memoized 555 return memo_dict[self] 556 return self.__class__(_ancestor = self, **kwargs) 557 558 def _get_port_ref(self, attr): 559 # Return reference that can be assigned to another port 560 # via __setattr__. There is only ever one reference 561 # object per port, but we create them lazily here. 562 ref = self._port_refs.get(attr) 563 if not ref: 564 ref = self._ports[attr].makeRef(self) 565 self._port_refs[attr] = ref 566 return ref 567 568 def __getattr__(self, attr): 569 if self._ports.has_key(attr): 570 return self._get_port_ref(attr) 571 572 if self._values.has_key(attr): 573 return self._values[attr] 574 575 if self._children.has_key(attr): 576 return self._children[attr] 577 578 # If the attribute exists on the C++ object, transparently 579 # forward the reference there. This is typically used for 580 # SWIG-wrapped methods such as init(), regStats(), 581 # regFormulas(), resetStats(), startup(), drain(), and 582 # resume(). 583 if self._ccObject and hasattr(self._ccObject, attr): 584 return getattr(self._ccObject, attr) 585 586 raise AttributeError, "object '%s' has no attribute '%s'" \ 587 % (self.__class__.__name__, attr) 588 589 # Set attribute (called on foo.attr = value when foo is an 590 # instance of class cls). 591 def __setattr__(self, attr, value): 592 # normal processing for private attributes 593 if attr.startswith('_'): 594 object.__setattr__(self, attr, value) 595 return 596 597 if self._ports.has_key(attr): 598 # set up port connection 599 self._get_port_ref(attr).connect(value) 600 return 601 602 if isSimObjectOrSequence(value) and self._instantiated: 603 raise RuntimeError, \ 604 "cannot set SimObject parameter '%s' after\n" \ 605 " instance been cloned %s" % (attr, `self`) 606 607 param = self._params.get(attr) 608 if param: 609 try: 610 value = param.convert(value) 611 except Exception, e: 612 msg = "%s\nError setting param %s.%s to %s\n" % \ 613 (e, self.__class__.__name__, attr, value) 614 e.args = (msg, ) 615 raise 616 self._values[attr] = value 617 return 618 619 # if RHS is a SimObject, it's an implicit child assignment 620 if isSimObjectOrSequence(value): 621 self.add_child(attr, value) 622 return 623 624 # no valid assignment... raise exception 625 raise AttributeError, "Class %s has no parameter %s" \ 626 % (self.__class__.__name__, attr) 627 628 629 # this hack allows tacking a '[0]' onto parameters that may or may 630 # not be vectors, and always getting the first element (e.g. cpus) 631 def __getitem__(self, key): 632 if key == 0: 633 return self 634 raise TypeError, "Non-zero index '%s' to SimObject" % key 635 636 # Also implemented by SimObjectVector 637 def clear_parent(self, old_parent): 638 assert self._parent is old_parent 639 self._parent = None 640 641 # Also implemented by SimObjectVector 642 def set_parent(self, parent, name): 643 self._parent = parent 644 self._name = name 645 646 # Also implemented by SimObjectVector 647 def get_name(self): 648 return self._name 649 650 # use this rather than directly accessing _parent for symmetry 651 # with SimObjectVector 652 def get_parent(self): 653 return self._parent 654 655 # clear out child with given name. This code is not likely to be exercised. 656 # See comment in add_child. 657 def clear_child(self, name): 658 child = self._children[name] 659 child.clear_parent(self) 660 del self._children[name] 661 662 # Add a new child to this object. 663 def add_child(self, name, child): 664 child = coerceSimObjectOrVector(child) 665 if child.get_parent(): 666 raise RuntimeError, \ 667 "add_child('%s'): child '%s' already has parent '%s'" % \ 668 (name, child._name, child._parent) 669 if self._children.has_key(name): 670 # This code path had an undiscovered bug that would make it fail 671 # at runtime. It had been here for a long time and was only 672 # exposed by a buggy script. Changes here will probably not be 673 # exercised without specialized testing. 674 self.clear_child(name) 675 child.set_parent(self, name) 676 self._children[name] = child 677 678 # Take SimObject-valued parameters that haven't been explicitly 679 # assigned as children and make them children of the object that 680 # they were assigned to as a parameter value. This guarantees 681 # that when we instantiate all the parameter objects we're still 682 # inside the configuration hierarchy. 683 def adoptOrphanParams(self): 684 for key,val in self._values.iteritems(): 685 if not isSimObjectVector(val) and isSimObjectSequence(val): 686 # need to convert raw SimObject sequences to 687 # SimObjectVector class so we can call get_parent() 688 val = SimObjectVector(val) 689 self._values[key] = val 690 if isSimObjectOrVector(val) and not val.get_parent(): 691 self.add_child(key, val) 692 693 def path(self): 694 if not self._parent: 695 return '(orphan)' 696 ppath = self._parent.path() 697 if ppath == 'root': 698 return self._name 699 return ppath + "." + self._name 700 701 def __str__(self): 702 return self.path() 703 704 def ini_str(self): 705 return self.path() 706 707 def find_any(self, ptype): 708 if isinstance(self, ptype): 709 return self, True 710 711 found_obj = None 712 for child in self._children.itervalues(): 713 if isinstance(child, ptype): 714 if found_obj != None and child != found_obj: 715 raise AttributeError, \ 716 'parent.any matched more than one: %s %s' % \ 717 (found_obj.path, child.path) 718 found_obj = child 719 # search param space 720 for pname,pdesc in self._params.iteritems(): 721 if issubclass(pdesc.ptype, ptype): 722 match_obj = self._values[pname] 723 if found_obj != None and found_obj != match_obj: 724 raise AttributeError, \ 725 'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path) 726 found_obj = match_obj 727 return found_obj, found_obj != None 728 729 def unproxy(self, base): 730 return self 731 732 def unproxyParams(self): 733 for param in self._params.iterkeys(): 734 value = self._values.get(param) 735 if value != None and isproxy(value): 736 try: 737 value = value.unproxy(self) 738 except: 739 print "Error in unproxying param '%s' of %s" % \ 740 (param, self.path()) 741 raise 742 setattr(self, param, value) 743 744 # Unproxy ports in sorted order so that 'append' operations on 745 # vector ports are done in a deterministic fashion. 746 port_names = self._ports.keys() 747 port_names.sort() 748 for port_name in port_names: 749 port = self._port_refs.get(port_name) 750 if port != None: 751 port.unproxy(self) 752 753 def print_ini(self, ini_file): 754 print >>ini_file, '[' + self.path() + ']' # .ini section header 755 756 instanceDict[self.path()] = self 757 758 if hasattr(self, 'type'): 759 print >>ini_file, 'type=%s' % self.type 760 761 child_names = self._children.keys() 762 child_names.sort() 763 if len(child_names): 764 print >>ini_file, 'children=%s' % \ 765 ' '.join(self._children[n].get_name() for n in child_names) 766 767 param_names = self._params.keys() 768 param_names.sort() 769 for param in param_names: 770 value = self._values.get(param) 771 if value != None: 772 print >>ini_file, '%s=%s' % (param, 773 self._values[param].ini_str()) 774 775 port_names = self._ports.keys() 776 port_names.sort() 777 for port_name in port_names: 778 port = self._port_refs.get(port_name, None) 779 if port != None: 780 print >>ini_file, '%s=%s' % (port_name, port.ini_str()) 781 782 print >>ini_file # blank line between objects 783 784 def getCCParams(self): 785 if self._ccParams: 786 return self._ccParams 787 788 cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type) 789 cc_params = cc_params_struct() 790 cc_params.pyobj = self 791 cc_params.name = str(self) 792 793 param_names = self._params.keys() 794 param_names.sort() 795 for param in param_names: 796 value = self._values.get(param) 797 if value is None: 798 fatal("%s.%s without default or user set value", 799 self.path(), param) 800 801 value = value.getValue() 802 if isinstance(self._params[param], VectorParamDesc): 803 assert isinstance(value, list) 804 vec = getattr(cc_params, param) 805 assert not len(vec) 806 for v in value: 807 vec.append(v) 808 else: 809 setattr(cc_params, param, value) 810 811 port_names = self._ports.keys() 812 port_names.sort() 813 for port_name in port_names: 814 port = self._port_refs.get(port_name, None) 815 if port != None: 816 setattr(cc_params, port_name, port) 817 self._ccParams = cc_params 818 return self._ccParams 819 820 # Get C++ object corresponding to this object, calling C++ if 821 # necessary to construct it. Does *not* recursively create 822 # children. 823 def getCCObject(self): 824 if not self._ccObject: 825 # Make sure this object is in the configuration hierarchy 826 if not self._parent and not isRoot(self): 827 raise RuntimeError, "Attempt to instantiate orphan node" 828 # Cycles in the configuration hierarchy are not supported. This 829 # will catch the resulting recursion and stop. 830 self._ccObject = -1 831 params = self.getCCParams() 832 self._ccObject = params.create() 833 elif self._ccObject == -1: 834 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \ 835 % self.path() 836 return self._ccObject 837 838 def descendants(self): 839 yield self 840 for child in self._children.itervalues(): 841 for obj in child.descendants(): 842 yield obj 843 844 # Call C++ to create C++ object corresponding to this object 845 def createCCObject(self): 846 self.getCCParams() 847 self.getCCObject() # force creation 848 849 def getValue(self): 850 return self.getCCObject() 851 852 # Create C++ port connections corresponding to the connections in 853 # _port_refs 854 def connectPorts(self): 855 for portRef in self._port_refs.itervalues(): 856 portRef.ccConnect() 857 858 def getMemoryMode(self): 859 if not isinstance(self, m5.objects.System): 860 return None 861 862 return self._ccObject.getMemoryMode() 863 864 def changeTiming(self, mode): 865 if isinstance(self, m5.objects.System): 866 # i don't know if there's a better way to do this - calling 867 # setMemoryMode directly from self._ccObject results in calling 868 # SimObject::setMemoryMode, not the System::setMemoryMode 869 self._ccObject.setMemoryMode(mode) 870 871 def takeOverFrom(self, old_cpu): 872 self._ccObject.takeOverFrom(old_cpu._ccObject) 873 874 # generate output file for 'dot' to display as a pretty graph. 875 # this code is currently broken. 876 def outputDot(self, dot): 877 label = "{%s|" % self.path 878 if isSimObject(self.realtype): 879 label += '%s|' % self.type 880 881 if self.children: 882 # instantiate children in same order they were added for 883 # backward compatibility (else we can end up with cpu1 884 # before cpu0). 885 for c in self.children: 886 dot.add_edge(pydot.Edge(self.path,c.path, style="bold")) 887 888 simobjs = [] 889 for param in self.params: 890 try: 891 if param.value is None: 892 raise AttributeError, 'Parameter with no value' 893 894 value = param.value 895 string = param.string(value) 896 except Exception, e: 897 msg = 'exception in %s:%s\n%s' % (self.name, param.name, e) 898 e.args = (msg, ) 899 raise 900 901 if isSimObject(param.ptype) and string != "Null": 902 simobjs.append(string) 903 else: 904 label += '%s = %s\\n' % (param.name, string) 905 906 for so in simobjs: 907 label += "|<%s> %s" % (so, so) 908 dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so, 909 tailport="w")) 910 label += '}' 911 dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label)) 912 913 # recursively dump out children 914 for c in self.children: 915 c.outputDot(dot) 916 917# Function to provide to C++ so it can look up instances based on paths 918def resolveSimObject(name): 919 obj = instanceDict[name] 920 return obj.getCCObject() 921 922def isSimObject(value): 923 return isinstance(value, SimObject) 924 925def isSimObjectClass(value): 926 return issubclass(value, SimObject) 927 928def isSimObjectVector(value): 929 return isinstance(value, SimObjectVector) 930 931def isSimObjectSequence(value): 932 if not isinstance(value, (list, tuple)) or len(value) == 0: 933 return False 934 935 for val in value: 936 if not isNullPointer(val) and not isSimObject(val): 937 return False 938 939 return True 940 941def isSimObjectOrSequence(value): 942 return isSimObject(value) or isSimObjectSequence(value) 943 944def isRoot(obj): 945 from m5.objects import Root 946 return obj and obj is Root.getInstance() 947 948def isSimObjectOrVector(value): 949 return isSimObject(value) or isSimObjectVector(value) 950 951def tryAsSimObjectOrVector(value): 952 if isSimObjectOrVector(value): 953 return value 954 if isSimObjectSequence(value): 955 return SimObjectVector(value) 956 return None 957 958def coerceSimObjectOrVector(value): 959 value = tryAsSimObjectOrVector(value) 960 if value is None: 961 raise TypeError, "SimObject or SimObjectVector expected" 962 return value 963 964baseClasses = allClasses.copy() 965baseInstances = instanceDict.copy() 966 967def clear(): 968 global allClasses, instanceDict 969 970 allClasses = baseClasses.copy() 971 instanceDict = baseInstances.copy() 972 973# __all__ defines the list of symbols that get exported when 974# 'from config import *' is invoked. Try to keep this reasonably 975# short to avoid polluting other namespaces. 976__all__ = [ 'SimObject' ] 977