SimObject.py revision 7528:6efc3672733b
113481Sgiacomo.travaglini@arm.com# Copyright (c) 2004-2006 The Regents of The University of Michigan 213481Sgiacomo.travaglini@arm.com# All rights reserved. 313481Sgiacomo.travaglini@arm.com# 413481Sgiacomo.travaglini@arm.com# Redistribution and use in source and binary forms, with or without 513481Sgiacomo.travaglini@arm.com# modification, are permitted provided that the following conditions are 613481Sgiacomo.travaglini@arm.com# met: redistributions of source code must retain the above copyright 713481Sgiacomo.travaglini@arm.com# notice, this list of conditions and the following disclaimer; 813481Sgiacomo.travaglini@arm.com# redistributions in binary form must reproduce the above copyright 913481Sgiacomo.travaglini@arm.com# notice, this list of conditions and the following disclaimer in the 1013481Sgiacomo.travaglini@arm.com# documentation and/or other materials provided with the distribution; 1113481Sgiacomo.travaglini@arm.com# neither the name of the copyright holders nor the names of its 1213481Sgiacomo.travaglini@arm.com# contributors may be used to endorse or promote products derived from 1313481Sgiacomo.travaglini@arm.com# this software without specific prior written permission. 1413481Sgiacomo.travaglini@arm.com# 1513481Sgiacomo.travaglini@arm.com# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 1613481Sgiacomo.travaglini@arm.com# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 1713481Sgiacomo.travaglini@arm.com# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 1813481Sgiacomo.travaglini@arm.com# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 1913481Sgiacomo.travaglini@arm.com# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 2013481Sgiacomo.travaglini@arm.com# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 2113481Sgiacomo.travaglini@arm.com# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 2213481Sgiacomo.travaglini@arm.com# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 2313481Sgiacomo.travaglini@arm.com# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 2413481Sgiacomo.travaglini@arm.com# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 2513481Sgiacomo.travaglini@arm.com# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 2613481Sgiacomo.travaglini@arm.com# 2713481Sgiacomo.travaglini@arm.com# Authors: Steve Reinhardt 2813481Sgiacomo.travaglini@arm.com# Nathan Binkert 2913481Sgiacomo.travaglini@arm.com 3013481Sgiacomo.travaglini@arm.comimport sys 3113481Sgiacomo.travaglini@arm.comfrom types import FunctionType 3213481Sgiacomo.travaglini@arm.com 3313481Sgiacomo.travaglini@arm.comtry: 3413481Sgiacomo.travaglini@arm.com import pydot 3513481Sgiacomo.travaglini@arm.comexcept: 3613481Sgiacomo.travaglini@arm.com pydot = False 3713481Sgiacomo.travaglini@arm.com 3813481Sgiacomo.travaglini@arm.comimport m5 3913481Sgiacomo.travaglini@arm.comfrom m5.util import * 4013481Sgiacomo.travaglini@arm.com 4113481Sgiacomo.travaglini@arm.com# Have to import params up top since Param is referenced on initial 4213481Sgiacomo.travaglini@arm.com# load (when SimObject class references Param to create a class 4313481Sgiacomo.travaglini@arm.com# variable, the 'name' param)... 4413481Sgiacomo.travaglini@arm.comfrom m5.params import * 4513481Sgiacomo.travaglini@arm.com# There are a few things we need that aren't in params.__all__ since 4613481Sgiacomo.travaglini@arm.com# normal users don't need them 4713481Sgiacomo.travaglini@arm.comfrom m5.params import ParamDesc, VectorParamDesc, \ 4813481Sgiacomo.travaglini@arm.com isNullPointer, SimObjectVector 4913481Sgiacomo.travaglini@arm.com 5013481Sgiacomo.travaglini@arm.comfrom m5.proxy import * 5113481Sgiacomo.travaglini@arm.comfrom m5.proxy import isproxy 5213481Sgiacomo.travaglini@arm.com 5313481Sgiacomo.travaglini@arm.com##################################################################### 5413481Sgiacomo.travaglini@arm.com# 5513481Sgiacomo.travaglini@arm.com# M5 Python Configuration Utility 5613481Sgiacomo.travaglini@arm.com# 5713481Sgiacomo.travaglini@arm.com# The basic idea is to write simple Python programs that build Python 5813481Sgiacomo.travaglini@arm.com# objects corresponding to M5 SimObjects for the desired simulation 5913481Sgiacomo.travaglini@arm.com# configuration. For now, the Python emits a .ini file that can be 6013481Sgiacomo.travaglini@arm.com# parsed by M5. In the future, some tighter integration between M5 6113481Sgiacomo.travaglini@arm.com# and the Python interpreter may allow bypassing the .ini file. 6213481Sgiacomo.travaglini@arm.com# 6313481Sgiacomo.travaglini@arm.com# Each SimObject class in M5 is represented by a Python class with the 6413481Sgiacomo.travaglini@arm.com# same name. The Python inheritance tree mirrors the M5 C++ tree 6513481Sgiacomo.travaglini@arm.com# (e.g., SimpleCPU derives from BaseCPU in both cases, and all 6613481Sgiacomo.travaglini@arm.com# SimObjects inherit from a single SimObject base class). To specify 6713481Sgiacomo.travaglini@arm.com# an instance of an M5 SimObject in a configuration, the user simply 6813481Sgiacomo.travaglini@arm.com# instantiates the corresponding Python object. The parameters for 6913481Sgiacomo.travaglini@arm.com# that SimObject are given by assigning to attributes of the Python 7013481Sgiacomo.travaglini@arm.com# object, either using keyword assignment in the constructor or in 7113481Sgiacomo.travaglini@arm.com# separate assignment statements. For example: 7213481Sgiacomo.travaglini@arm.com# 7313481Sgiacomo.travaglini@arm.com# cache = BaseCache(size='64KB') 7413481Sgiacomo.travaglini@arm.com# cache.hit_latency = 3 7513481Sgiacomo.travaglini@arm.com# cache.assoc = 8 7613481Sgiacomo.travaglini@arm.com# 7713481Sgiacomo.travaglini@arm.com# The magic lies in the mapping of the Python attributes for SimObject 7813481Sgiacomo.travaglini@arm.com# classes to the actual SimObject parameter specifications. This 7913481Sgiacomo.travaglini@arm.com# allows parameter validity checking in the Python code. Continuing 8013481Sgiacomo.travaglini@arm.com# the example above, the statements "cache.blurfl=3" or 8113481Sgiacomo.travaglini@arm.com# "cache.assoc='hello'" would both result in runtime errors in Python, 8213481Sgiacomo.travaglini@arm.com# since the BaseCache object has no 'blurfl' parameter and the 'assoc' 8313481Sgiacomo.travaglini@arm.com# parameter requires an integer, respectively. This magic is done 8413481Sgiacomo.travaglini@arm.com# primarily by overriding the special __setattr__ method that controls 8513481Sgiacomo.travaglini@arm.com# assignment to object attributes. 8613481Sgiacomo.travaglini@arm.com# 8713481Sgiacomo.travaglini@arm.com# Once a set of Python objects have been instantiated in a hierarchy, 8813481Sgiacomo.travaglini@arm.com# calling 'instantiate(obj)' (where obj is the root of the hierarchy) 8913481Sgiacomo.travaglini@arm.com# will generate a .ini file. 9013481Sgiacomo.travaglini@arm.com# 9113481Sgiacomo.travaglini@arm.com##################################################################### 9213481Sgiacomo.travaglini@arm.com 9313481Sgiacomo.travaglini@arm.com# list of all SimObject classes 9413481Sgiacomo.travaglini@arm.comallClasses = {} 9513481Sgiacomo.travaglini@arm.com 9613481Sgiacomo.travaglini@arm.com# dict to look up SimObjects based on path 9713481Sgiacomo.travaglini@arm.cominstanceDict = {} 9813481Sgiacomo.travaglini@arm.com 9913481Sgiacomo.travaglini@arm.com# The metaclass for SimObject. This class controls how new classes 10013481Sgiacomo.travaglini@arm.com# that derive from SimObject are instantiated, and provides inherited 10113481Sgiacomo.travaglini@arm.com# class behavior (just like a class controls how instances of that 10213481Sgiacomo.travaglini@arm.com# class are instantiated, and provides inherited instance behavior). 10313481Sgiacomo.travaglini@arm.comclass MetaSimObject(type): 10413481Sgiacomo.travaglini@arm.com # Attributes that can be set only at initialization time 10513481Sgiacomo.travaglini@arm.com init_keywords = { 'abstract' : bool, 10613481Sgiacomo.travaglini@arm.com 'cxx_class' : str, 10713481Sgiacomo.travaglini@arm.com 'cxx_type' : str, 10813481Sgiacomo.travaglini@arm.com 'cxx_predecls' : list, 10913481Sgiacomo.travaglini@arm.com 'swig_objdecls' : list, 11013481Sgiacomo.travaglini@arm.com 'swig_predecls' : list, 11113481Sgiacomo.travaglini@arm.com 'type' : str } 11213481Sgiacomo.travaglini@arm.com # Attributes that can be set any time 11313481Sgiacomo.travaglini@arm.com keywords = { 'check' : FunctionType } 11413481Sgiacomo.travaglini@arm.com 11513481Sgiacomo.travaglini@arm.com # __new__ is called before __init__, and is where the statements 11613481Sgiacomo.travaglini@arm.com # in the body of the class definition get loaded into the class's 11713481Sgiacomo.travaglini@arm.com # __dict__. We intercept this to filter out parameter & port assignments 11813481Sgiacomo.travaglini@arm.com # and only allow "private" attributes to be passed to the base 11913481Sgiacomo.travaglini@arm.com # __new__ (starting with underscore). 12013481Sgiacomo.travaglini@arm.com def __new__(mcls, name, bases, dict): 12113481Sgiacomo.travaglini@arm.com assert name not in allClasses, "SimObject %s already present" % name 12213481Sgiacomo.travaglini@arm.com 12313481Sgiacomo.travaglini@arm.com # Copy "private" attributes, functions, and classes to the 12413481Sgiacomo.travaglini@arm.com # official dict. Everything else goes in _init_dict to be 12513481Sgiacomo.travaglini@arm.com # filtered in __init__. 12613481Sgiacomo.travaglini@arm.com cls_dict = {} 12713481Sgiacomo.travaglini@arm.com value_dict = {} 12813481Sgiacomo.travaglini@arm.com for key,val in dict.items(): 12913481Sgiacomo.travaglini@arm.com if key.startswith('_') or isinstance(val, (FunctionType, 13013481Sgiacomo.travaglini@arm.com classmethod, 13113481Sgiacomo.travaglini@arm.com type)): 13213481Sgiacomo.travaglini@arm.com cls_dict[key] = val 13313481Sgiacomo.travaglini@arm.com else: 13413481Sgiacomo.travaglini@arm.com # must be a param/port setting 13513481Sgiacomo.travaglini@arm.com value_dict[key] = val 13613481Sgiacomo.travaglini@arm.com if 'abstract' not in value_dict: 13713481Sgiacomo.travaglini@arm.com value_dict['abstract'] = False 13813481Sgiacomo.travaglini@arm.com cls_dict['_value_dict'] = value_dict 13913481Sgiacomo.travaglini@arm.com cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict) 14013481Sgiacomo.travaglini@arm.com if 'type' in value_dict: 14113481Sgiacomo.travaglini@arm.com allClasses[name] = cls 14213481Sgiacomo.travaglini@arm.com return cls 14313481Sgiacomo.travaglini@arm.com 14413481Sgiacomo.travaglini@arm.com # subclass initialization 14513481Sgiacomo.travaglini@arm.com def __init__(cls, name, bases, dict): 14613481Sgiacomo.travaglini@arm.com # calls type.__init__()... I think that's a no-op, but leave 14713481Sgiacomo.travaglini@arm.com # it here just in case it's not. 14813481Sgiacomo.travaglini@arm.com super(MetaSimObject, cls).__init__(name, bases, dict) 14913481Sgiacomo.travaglini@arm.com 15013481Sgiacomo.travaglini@arm.com # initialize required attributes 15113481Sgiacomo.travaglini@arm.com 15213481Sgiacomo.travaglini@arm.com # class-only attributes 15313481Sgiacomo.travaglini@arm.com cls._params = multidict() # param descriptions 15413481Sgiacomo.travaglini@arm.com cls._ports = multidict() # port descriptions 15513481Sgiacomo.travaglini@arm.com 15613481Sgiacomo.travaglini@arm.com # class or instance attributes 15713481Sgiacomo.travaglini@arm.com cls._values = multidict() # param values 15813481Sgiacomo.travaglini@arm.com cls._children = multidict() # SimObject children 15913481Sgiacomo.travaglini@arm.com cls._port_refs = multidict() # port ref objects 16013481Sgiacomo.travaglini@arm.com cls._instantiated = False # really instantiated, cloned, or subclassed 16113481Sgiacomo.travaglini@arm.com 16213481Sgiacomo.travaglini@arm.com # We don't support multiple inheritance. If you want to, you 16313481Sgiacomo.travaglini@arm.com # must fix multidict to deal with it properly. 16413481Sgiacomo.travaglini@arm.com if len(bases) > 1: 16513481Sgiacomo.travaglini@arm.com raise TypeError, "SimObjects do not support multiple inheritance" 16613481Sgiacomo.travaglini@arm.com 16713481Sgiacomo.travaglini@arm.com base = bases[0] 16813481Sgiacomo.travaglini@arm.com 16913481Sgiacomo.travaglini@arm.com # Set up general inheritance via multidicts. A subclass will 17013481Sgiacomo.travaglini@arm.com # inherit all its settings from the base class. The only time 17113481Sgiacomo.travaglini@arm.com # the following is not true is when we define the SimObject 17213481Sgiacomo.travaglini@arm.com # class itself (in which case the multidicts have no parent). 17313481Sgiacomo.travaglini@arm.com if isinstance(base, MetaSimObject): 17413481Sgiacomo.travaglini@arm.com cls._base = base 175 cls._params.parent = base._params 176 cls._ports.parent = base._ports 177 cls._values.parent = base._values 178 cls._children.parent = base._children 179 cls._port_refs.parent = base._port_refs 180 # mark base as having been subclassed 181 base._instantiated = True 182 else: 183 cls._base = None 184 185 # default keyword values 186 if 'type' in cls._value_dict: 187 if 'cxx_class' not in cls._value_dict: 188 cls._value_dict['cxx_class'] = cls._value_dict['type'] 189 190 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class'] 191 192 if 'cxx_predecls' not in cls._value_dict: 193 # A forward class declaration is sufficient since we are 194 # just declaring a pointer. 195 class_path = cls._value_dict['cxx_class'].split('::') 196 class_path.reverse() 197 decl = 'class %s;' % class_path[0] 198 for ns in class_path[1:]: 199 decl = 'namespace %s { %s }' % (ns, decl) 200 cls._value_dict['cxx_predecls'] = [decl] 201 202 if 'swig_predecls' not in cls._value_dict: 203 # A forward class declaration is sufficient since we are 204 # just declaring a pointer. 205 cls._value_dict['swig_predecls'] = \ 206 cls._value_dict['cxx_predecls'] 207 208 if 'swig_objdecls' not in cls._value_dict: 209 cls._value_dict['swig_objdecls'] = [] 210 211 # Now process the _value_dict items. They could be defining 212 # new (or overriding existing) parameters or ports, setting 213 # class keywords (e.g., 'abstract'), or setting parameter 214 # values or port bindings. The first 3 can only be set when 215 # the class is defined, so we handle them here. The others 216 # can be set later too, so just emulate that by calling 217 # setattr(). 218 for key,val in cls._value_dict.items(): 219 # param descriptions 220 if isinstance(val, ParamDesc): 221 cls._new_param(key, val) 222 223 # port objects 224 elif isinstance(val, Port): 225 cls._new_port(key, val) 226 227 # init-time-only keywords 228 elif cls.init_keywords.has_key(key): 229 cls._set_keyword(key, val, cls.init_keywords[key]) 230 231 # default: use normal path (ends up in __setattr__) 232 else: 233 setattr(cls, key, val) 234 235 def _set_keyword(cls, keyword, val, kwtype): 236 if not isinstance(val, kwtype): 237 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \ 238 (keyword, type(val), kwtype) 239 if isinstance(val, FunctionType): 240 val = classmethod(val) 241 type.__setattr__(cls, keyword, val) 242 243 def _new_param(cls, name, pdesc): 244 # each param desc should be uniquely assigned to one variable 245 assert(not hasattr(pdesc, 'name')) 246 pdesc.name = name 247 cls._params[name] = pdesc 248 if hasattr(pdesc, 'default'): 249 cls._set_param(name, pdesc.default, pdesc) 250 251 def _set_param(cls, name, value, param): 252 assert(param.name == name) 253 try: 254 cls._values[name] = param.convert(value) 255 except Exception, e: 256 msg = "%s\nError setting param %s.%s to %s\n" % \ 257 (e, cls.__name__, name, value) 258 e.args = (msg, ) 259 raise 260 261 def _new_port(cls, name, port): 262 # each port should be uniquely assigned to one variable 263 assert(not hasattr(port, 'name')) 264 port.name = name 265 cls._ports[name] = port 266 if hasattr(port, 'default'): 267 cls._cls_get_port_ref(name).connect(port.default) 268 269 # same as _get_port_ref, effectively, but for classes 270 def _cls_get_port_ref(cls, attr): 271 # Return reference that can be assigned to another port 272 # via __setattr__. There is only ever one reference 273 # object per port, but we create them lazily here. 274 ref = cls._port_refs.get(attr) 275 if not ref: 276 ref = cls._ports[attr].makeRef(cls) 277 cls._port_refs[attr] = ref 278 return ref 279 280 # Set attribute (called on foo.attr = value when foo is an 281 # instance of class cls). 282 def __setattr__(cls, attr, value): 283 # normal processing for private attributes 284 if attr.startswith('_'): 285 type.__setattr__(cls, attr, value) 286 return 287 288 if cls.keywords.has_key(attr): 289 cls._set_keyword(attr, value, cls.keywords[attr]) 290 return 291 292 if cls._ports.has_key(attr): 293 cls._cls_get_port_ref(attr).connect(value) 294 return 295 296 if isSimObjectOrSequence(value) and cls._instantiated: 297 raise RuntimeError, \ 298 "cannot set SimObject parameter '%s' after\n" \ 299 " class %s has been instantiated or subclassed" \ 300 % (attr, cls.__name__) 301 302 # check for param 303 param = cls._params.get(attr) 304 if param: 305 cls._set_param(attr, value, param) 306 return 307 308 if isSimObjectOrSequence(value): 309 # If RHS is a SimObject, it's an implicit child assignment. 310 cls._children[attr] = coerceSimObjectOrVector(value) 311 return 312 313 # no valid assignment... raise exception 314 raise AttributeError, \ 315 "Class %s has no parameter \'%s\'" % (cls.__name__, attr) 316 317 def __getattr__(cls, attr): 318 if cls._values.has_key(attr): 319 return cls._values[attr] 320 321 if cls._children.has_key(attr): 322 return cls._children[attr] 323 324 raise AttributeError, \ 325 "object '%s' has no attribute '%s'" % (cls.__name__, attr) 326 327 def __str__(cls): 328 return cls.__name__ 329 330 def cxx_decl(cls): 331 code = "#ifndef __PARAMS__%s\n" % cls 332 code += "#define __PARAMS__%s\n\n" % cls 333 334 # The 'dict' attribute restricts us to the params declared in 335 # the object itself, not including inherited params (which 336 # will also be inherited from the base class's param struct 337 # here). 338 params = cls._params.local.values() 339 try: 340 ptypes = [p.ptype for p in params] 341 except: 342 print cls, p, p.ptype_str 343 print params 344 raise 345 346 # get a list of lists of predeclaration lines 347 predecls = [] 348 predecls.extend(cls.cxx_predecls) 349 for p in params: 350 predecls.extend(p.cxx_predecls()) 351 # remove redundant lines 352 predecls2 = [] 353 for pd in predecls: 354 if pd not in predecls2: 355 predecls2.append(pd) 356 predecls2.sort() 357 code += "\n".join(predecls2) 358 code += "\n\n"; 359 360 if cls._base: 361 code += '#include "params/%s.hh"\n\n' % cls._base.type 362 363 for ptype in ptypes: 364 if issubclass(ptype, Enum): 365 code += '#include "enums/%s.hh"\n' % ptype.__name__ 366 code += "\n\n" 367 368 code += cls.cxx_struct(cls._base, params) 369 370 # close #ifndef __PARAMS__* guard 371 code += "\n#endif\n" 372 return code 373 374 def cxx_struct(cls, base, params): 375 if cls == SimObject: 376 return '#include "sim/sim_object_params.hh"\n' 377 378 # now generate the actual param struct 379 code = "struct %sParams" % cls 380 if base: 381 code += " : public %sParams" % base.type 382 code += "\n{\n" 383 if not hasattr(cls, 'abstract') or not cls.abstract: 384 if 'type' in cls.__dict__: 385 code += " %s create();\n" % cls.cxx_type 386 decls = [p.cxx_decl() for p in params] 387 decls.sort() 388 code += "".join([" %s\n" % d for d in decls]) 389 code += "};\n" 390 391 return code 392 393 def swig_decl(cls): 394 code = '%%module %s\n' % cls 395 396 code += '%{\n' 397 code += '#include "params/%s.hh"\n' % cls 398 code += '%}\n\n' 399 400 # The 'dict' attribute restricts us to the params declared in 401 # the object itself, not including inherited params (which 402 # will also be inherited from the base class's param struct 403 # here). 404 params = cls._params.local.values() 405 ptypes = [p.ptype for p in params] 406 407 # get a list of lists of predeclaration lines 408 predecls = [] 409 predecls.extend([ p.swig_predecls() for p in params ]) 410 # flatten 411 predecls = reduce(lambda x,y:x+y, predecls, []) 412 # remove redundant lines 413 predecls2 = [] 414 for pd in predecls: 415 if pd not in predecls2: 416 predecls2.append(pd) 417 predecls2.sort() 418 code += "\n".join(predecls2) 419 code += "\n\n"; 420 421 if cls._base: 422 code += '%%import "params/%s.i"\n\n' % cls._base.type 423 424 for ptype in ptypes: 425 if issubclass(ptype, Enum): 426 code += '%%import "enums/%s.hh"\n' % ptype.__name__ 427 code += "\n\n" 428 429 code += '%%import "params/%s_type.hh"\n\n' % cls 430 code += '%%include "params/%s.hh"\n\n' % cls 431 432 return code 433 434# The SimObject class is the root of the special hierarchy. Most of 435# the code in this class deals with the configuration hierarchy itself 436# (parent/child node relationships). 437class SimObject(object): 438 # Specify metaclass. Any class inheriting from SimObject will 439 # get this metaclass. 440 __metaclass__ = MetaSimObject 441 type = 'SimObject' 442 abstract = True 443 444 swig_objdecls = [ '%include "python/swig/sim_object.i"' ] 445 446 # Initialize new instance. For objects with SimObject-valued 447 # children, we need to recursively clone the classes represented 448 # by those param values as well in a consistent "deep copy"-style 449 # fashion. That is, we want to make sure that each instance is 450 # cloned only once, and that if there are multiple references to 451 # the same original object, we end up with the corresponding 452 # cloned references all pointing to the same cloned instance. 453 def __init__(self, **kwargs): 454 ancestor = kwargs.get('_ancestor') 455 memo_dict = kwargs.get('_memo') 456 if memo_dict is None: 457 # prepare to memoize any recursively instantiated objects 458 memo_dict = {} 459 elif ancestor: 460 # memoize me now to avoid problems with recursive calls 461 memo_dict[ancestor] = self 462 463 if not ancestor: 464 ancestor = self.__class__ 465 ancestor._instantiated = True 466 467 # initialize required attributes 468 self._parent = None 469 self._name = None 470 self._ccObject = None # pointer to C++ object 471 self._ccParams = None 472 self._instantiated = False # really "cloned" 473 474 # Inherit parameter values from class using multidict so 475 # individual value settings can be overridden but we still 476 # inherit late changes to non-overridden class values. 477 self._values = multidict(ancestor._values) 478 # clone SimObject-valued parameters 479 for key,val in ancestor._values.iteritems(): 480 val = tryAsSimObjectOrVector(val) 481 if val is not None: 482 self._values[key] = val(_memo=memo_dict) 483 484 # Clone children specified at class level. No need for a 485 # multidict here since we will be cloning everything. 486 self._children = {} 487 for key,val in ancestor._children.iteritems(): 488 self.add_child(key, val(_memo=memo_dict)) 489 490 # clone port references. no need to use a multidict here 491 # since we will be creating new references for all ports. 492 self._port_refs = {} 493 for key,val in ancestor._port_refs.iteritems(): 494 self._port_refs[key] = val.clone(self, memo_dict) 495 # apply attribute assignments from keyword args, if any 496 for key,val in kwargs.iteritems(): 497 setattr(self, key, val) 498 499 # "Clone" the current instance by creating another instance of 500 # this instance's class, but that inherits its parameter values 501 # and port mappings from the current instance. If we're in a 502 # "deep copy" recursive clone, check the _memo dict to see if 503 # we've already cloned this instance. 504 def __call__(self, **kwargs): 505 memo_dict = kwargs.get('_memo') 506 if memo_dict is None: 507 # no memo_dict: must be top-level clone operation. 508 # this is only allowed at the root of a hierarchy 509 if self._parent: 510 raise RuntimeError, "attempt to clone object %s " \ 511 "not at the root of a tree (parent = %s)" \ 512 % (self, self._parent) 513 # create a new dict and use that. 514 memo_dict = {} 515 kwargs['_memo'] = memo_dict 516 elif memo_dict.has_key(self): 517 # clone already done & memoized 518 return memo_dict[self] 519 return self.__class__(_ancestor = self, **kwargs) 520 521 def _get_port_ref(self, attr): 522 # Return reference that can be assigned to another port 523 # via __setattr__. There is only ever one reference 524 # object per port, but we create them lazily here. 525 ref = self._port_refs.get(attr) 526 if not ref: 527 ref = self._ports[attr].makeRef(self) 528 self._port_refs[attr] = ref 529 return ref 530 531 def __getattr__(self, attr): 532 if self._ports.has_key(attr): 533 return self._get_port_ref(attr) 534 535 if self._values.has_key(attr): 536 return self._values[attr] 537 538 if self._children.has_key(attr): 539 return self._children[attr] 540 541 # If the attribute exists on the C++ object, transparently 542 # forward the reference there. This is typically used for 543 # SWIG-wrapped methods such as init(), regStats(), 544 # regFormulas(), resetStats(), startup(), drain(), and 545 # resume(). 546 if self._ccObject and hasattr(self._ccObject, attr): 547 return getattr(self._ccObject, attr) 548 549 raise AttributeError, "object '%s' has no attribute '%s'" \ 550 % (self.__class__.__name__, attr) 551 552 # Set attribute (called on foo.attr = value when foo is an 553 # instance of class cls). 554 def __setattr__(self, attr, value): 555 # normal processing for private attributes 556 if attr.startswith('_'): 557 object.__setattr__(self, attr, value) 558 return 559 560 if self._ports.has_key(attr): 561 # set up port connection 562 self._get_port_ref(attr).connect(value) 563 return 564 565 if isSimObjectOrSequence(value) and self._instantiated: 566 raise RuntimeError, \ 567 "cannot set SimObject parameter '%s' after\n" \ 568 " instance been cloned %s" % (attr, `self`) 569 570 param = self._params.get(attr) 571 if param: 572 try: 573 value = param.convert(value) 574 except Exception, e: 575 msg = "%s\nError setting param %s.%s to %s\n" % \ 576 (e, self.__class__.__name__, attr, value) 577 e.args = (msg, ) 578 raise 579 self._values[attr] = value 580 return 581 582 # if RHS is a SimObject, it's an implicit child assignment 583 if isSimObjectOrSequence(value): 584 self.add_child(attr, value) 585 return 586 587 # no valid assignment... raise exception 588 raise AttributeError, "Class %s has no parameter %s" \ 589 % (self.__class__.__name__, attr) 590 591 592 # this hack allows tacking a '[0]' onto parameters that may or may 593 # not be vectors, and always getting the first element (e.g. cpus) 594 def __getitem__(self, key): 595 if key == 0: 596 return self 597 raise TypeError, "Non-zero index '%s' to SimObject" % key 598 599 # Also implemented by SimObjectVector 600 def clear_parent(self, old_parent): 601 assert self._parent is old_parent 602 self._parent = None 603 604 # Also implemented by SimObjectVector 605 def set_parent(self, parent, name): 606 self._parent = parent 607 self._name = name 608 609 # Also implemented by SimObjectVector 610 def get_name(self): 611 return self._name 612 613 # use this rather than directly accessing _parent for symmetry 614 # with SimObjectVector 615 def get_parent(self): 616 return self._parent 617 618 # clear out child with given name 619 def clear_child(self, name): 620 child = self._children[name] 621 child.clear_parent(self) 622 del self._children[name] 623 624 # Add a new child to this object. 625 def add_child(self, name, child): 626 child = coerceSimObjectOrVector(child) 627 if child.get_parent(): 628 raise RuntimeError, \ 629 "add_child('%s'): child '%s' already has parent '%s'" % \ 630 (name, child._name, child._parent) 631 if self._children.has_key(name): 632 clear_child(name) 633 child.set_parent(self, name) 634 self._children[name] = child 635 636 # Take SimObject-valued parameters that haven't been explicitly 637 # assigned as children and make them children of the object that 638 # they were assigned to as a parameter value. This guarantees 639 # that when we instantiate all the parameter objects we're still 640 # inside the configuration hierarchy. 641 def adoptOrphanParams(self): 642 for key,val in self._values.iteritems(): 643 if not isSimObjectVector(val) and isSimObjectSequence(val): 644 # need to convert raw SimObject sequences to 645 # SimObjectVector class so we can call get_parent() 646 val = SimObjectVector(val) 647 self._values[key] = val 648 if isSimObjectOrVector(val) and not val.get_parent(): 649 self.add_child(key, val) 650 651 def path(self): 652 if not self._parent: 653 return '(orphan)' 654 ppath = self._parent.path() 655 if ppath == 'root': 656 return self._name 657 return ppath + "." + self._name 658 659 def __str__(self): 660 return self.path() 661 662 def ini_str(self): 663 return self.path() 664 665 def find_any(self, ptype): 666 if isinstance(self, ptype): 667 return self, True 668 669 found_obj = None 670 for child in self._children.itervalues(): 671 if isinstance(child, ptype): 672 if found_obj != None and child != found_obj: 673 raise AttributeError, \ 674 'parent.any matched more than one: %s %s' % \ 675 (found_obj.path, child.path) 676 found_obj = child 677 # search param space 678 for pname,pdesc in self._params.iteritems(): 679 if issubclass(pdesc.ptype, ptype): 680 match_obj = self._values[pname] 681 if found_obj != None and found_obj != match_obj: 682 raise AttributeError, \ 683 'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path) 684 found_obj = match_obj 685 return found_obj, found_obj != None 686 687 def unproxy(self, base): 688 return self 689 690 def unproxyParams(self): 691 for param in self._params.iterkeys(): 692 value = self._values.get(param) 693 if value != None and isproxy(value): 694 try: 695 value = value.unproxy(self) 696 except: 697 print "Error in unproxying param '%s' of %s" % \ 698 (param, self.path()) 699 raise 700 setattr(self, param, value) 701 702 # Unproxy ports in sorted order so that 'append' operations on 703 # vector ports are done in a deterministic fashion. 704 port_names = self._ports.keys() 705 port_names.sort() 706 for port_name in port_names: 707 port = self._port_refs.get(port_name) 708 if port != None: 709 port.unproxy(self) 710 711 def print_ini(self, ini_file): 712 print >>ini_file, '[' + self.path() + ']' # .ini section header 713 714 instanceDict[self.path()] = self 715 716 if hasattr(self, 'type'): 717 print >>ini_file, 'type=%s' % self.type 718 719 child_names = self._children.keys() 720 child_names.sort() 721 if len(child_names): 722 print >>ini_file, 'children=%s' % \ 723 ' '.join(self._children[n].get_name() for n in child_names) 724 725 param_names = self._params.keys() 726 param_names.sort() 727 for param in param_names: 728 value = self._values.get(param) 729 if value != None: 730 print >>ini_file, '%s=%s' % (param, 731 self._values[param].ini_str()) 732 733 port_names = self._ports.keys() 734 port_names.sort() 735 for port_name in port_names: 736 port = self._port_refs.get(port_name, None) 737 if port != None: 738 print >>ini_file, '%s=%s' % (port_name, port.ini_str()) 739 740 print >>ini_file # blank line between objects 741 742 def getCCParams(self): 743 if self._ccParams: 744 return self._ccParams 745 746 cc_params_struct = getattr(m5.objects.params, '%sParams' % self.type) 747 cc_params = cc_params_struct() 748 cc_params.pyobj = self 749 cc_params.name = str(self) 750 751 param_names = self._params.keys() 752 param_names.sort() 753 for param in param_names: 754 value = self._values.get(param) 755 if value is None: 756 fatal("%s.%s without default or user set value", 757 self.path(), param) 758 759 value = value.getValue() 760 if isinstance(self._params[param], VectorParamDesc): 761 assert isinstance(value, list) 762 vec = getattr(cc_params, param) 763 assert not len(vec) 764 for v in value: 765 vec.append(v) 766 else: 767 setattr(cc_params, param, value) 768 769 port_names = self._ports.keys() 770 port_names.sort() 771 for port_name in port_names: 772 port = self._port_refs.get(port_name, None) 773 if port != None: 774 setattr(cc_params, port_name, port) 775 self._ccParams = cc_params 776 return self._ccParams 777 778 # Get C++ object corresponding to this object, calling C++ if 779 # necessary to construct it. Does *not* recursively create 780 # children. 781 def getCCObject(self): 782 if not self._ccObject: 783 # Make sure this object is in the configuration hierarchy 784 if not self._parent and not isRoot(self): 785 raise RuntimeError, "Attempt to instantiate orphan node" 786 # Cycles in the configuration hierarchy are not supported. This 787 # will catch the resulting recursion and stop. 788 self._ccObject = -1 789 params = self.getCCParams() 790 self._ccObject = params.create() 791 elif self._ccObject == -1: 792 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \ 793 % self.path() 794 return self._ccObject 795 796 def descendants(self): 797 yield self 798 for child in self._children.itervalues(): 799 for obj in child.descendants(): 800 yield obj 801 802 # Call C++ to create C++ object corresponding to this object 803 def createCCObject(self): 804 self.getCCParams() 805 self.getCCObject() # force creation 806 807 def getValue(self): 808 return self.getCCObject() 809 810 # Create C++ port connections corresponding to the connections in 811 # _port_refs 812 def connectPorts(self): 813 for portRef in self._port_refs.itervalues(): 814 portRef.ccConnect() 815 816 def getMemoryMode(self): 817 if not isinstance(self, m5.objects.System): 818 return None 819 820 return self._ccObject.getMemoryMode() 821 822 def changeTiming(self, mode): 823 if isinstance(self, m5.objects.System): 824 # i don't know if there's a better way to do this - calling 825 # setMemoryMode directly from self._ccObject results in calling 826 # SimObject::setMemoryMode, not the System::setMemoryMode 827 self._ccObject.setMemoryMode(mode) 828 829 def takeOverFrom(self, old_cpu): 830 self._ccObject.takeOverFrom(old_cpu._ccObject) 831 832 # generate output file for 'dot' to display as a pretty graph. 833 # this code is currently broken. 834 def outputDot(self, dot): 835 label = "{%s|" % self.path 836 if isSimObject(self.realtype): 837 label += '%s|' % self.type 838 839 if self.children: 840 # instantiate children in same order they were added for 841 # backward compatibility (else we can end up with cpu1 842 # before cpu0). 843 for c in self.children: 844 dot.add_edge(pydot.Edge(self.path,c.path, style="bold")) 845 846 simobjs = [] 847 for param in self.params: 848 try: 849 if param.value is None: 850 raise AttributeError, 'Parameter with no value' 851 852 value = param.value 853 string = param.string(value) 854 except Exception, e: 855 msg = 'exception in %s:%s\n%s' % (self.name, param.name, e) 856 e.args = (msg, ) 857 raise 858 859 if isSimObject(param.ptype) and string != "Null": 860 simobjs.append(string) 861 else: 862 label += '%s = %s\\n' % (param.name, string) 863 864 for so in simobjs: 865 label += "|<%s> %s" % (so, so) 866 dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so, 867 tailport="w")) 868 label += '}' 869 dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label)) 870 871 # recursively dump out children 872 for c in self.children: 873 c.outputDot(dot) 874 875# Function to provide to C++ so it can look up instances based on paths 876def resolveSimObject(name): 877 obj = instanceDict[name] 878 return obj.getCCObject() 879 880def isSimObject(value): 881 return isinstance(value, SimObject) 882 883def isSimObjectClass(value): 884 return issubclass(value, SimObject) 885 886def isSimObjectVector(value): 887 return isinstance(value, SimObjectVector) 888 889def isSimObjectSequence(value): 890 if not isinstance(value, (list, tuple)) or len(value) == 0: 891 return False 892 893 for val in value: 894 if not isNullPointer(val) and not isSimObject(val): 895 return False 896 897 return True 898 899def isSimObjectOrSequence(value): 900 return isSimObject(value) or isSimObjectSequence(value) 901 902def isRoot(obj): 903 from m5.objects import Root 904 return obj and obj is Root.getInstance() 905 906def isSimObjectOrVector(value): 907 return isSimObject(value) or isSimObjectVector(value) 908 909def tryAsSimObjectOrVector(value): 910 if isSimObjectOrVector(value): 911 return value 912 if isSimObjectSequence(value): 913 return SimObjectVector(value) 914 return None 915 916def coerceSimObjectOrVector(value): 917 value = tryAsSimObjectOrVector(value) 918 if value is None: 919 raise TypeError, "SimObject or SimObjectVector expected" 920 return value 921 922baseClasses = allClasses.copy() 923baseInstances = instanceDict.copy() 924 925def clear(): 926 global allClasses, instanceDict 927 928 allClasses = baseClasses.copy() 929 instanceDict = baseInstances.copy() 930 931# __all__ defines the list of symbols that get exported when 932# 'from config import *' is invoked. Try to keep this reasonably 933# short to avoid polluting other namespaces. 934__all__ = [ 'SimObject' ] 935