SimObject.py (9195:77fd8912c9d4) | SimObject.py (9253:e0d2a8e9f445) |
---|---|
1# Copyright (c) 2012 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) 2004-2006 The Regents of The University of Michigan 14# Copyright (c) 2010 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# Nathan Binkert 42# Andreas Hansson 43 44import sys 45from types import FunctionType, MethodType, ModuleType 46 47import m5 48from m5.util import * 49 50# Have to import params up top since Param is referenced on initial 51# load (when SimObject class references Param to create a class 52# variable, the 'name' param)... 53from m5.params import * 54# There are a few things we need that aren't in params.__all__ since 55# normal users don't need them 56from m5.params import ParamDesc, VectorParamDesc, \ 57 isNullPointer, SimObjectVector, Port 58 59from m5.proxy import * 60from m5.proxy import isproxy 61 62##################################################################### 63# 64# M5 Python Configuration Utility 65# 66# The basic idea is to write simple Python programs that build Python 67# objects corresponding to M5 SimObjects for the desired simulation 68# configuration. For now, the Python emits a .ini file that can be 69# parsed by M5. In the future, some tighter integration between M5 70# and the Python interpreter may allow bypassing the .ini file. 71# 72# Each SimObject class in M5 is represented by a Python class with the 73# same name. The Python inheritance tree mirrors the M5 C++ tree 74# (e.g., SimpleCPU derives from BaseCPU in both cases, and all 75# SimObjects inherit from a single SimObject base class). To specify 76# an instance of an M5 SimObject in a configuration, the user simply 77# instantiates the corresponding Python object. The parameters for 78# that SimObject are given by assigning to attributes of the Python 79# object, either using keyword assignment in the constructor or in 80# separate assignment statements. For example: 81# 82# cache = BaseCache(size='64KB') 83# cache.hit_latency = 3 84# cache.assoc = 8 85# 86# The magic lies in the mapping of the Python attributes for SimObject 87# classes to the actual SimObject parameter specifications. This 88# allows parameter validity checking in the Python code. Continuing 89# the example above, the statements "cache.blurfl=3" or 90# "cache.assoc='hello'" would both result in runtime errors in Python, 91# since the BaseCache object has no 'blurfl' parameter and the 'assoc' 92# parameter requires an integer, respectively. This magic is done 93# primarily by overriding the special __setattr__ method that controls 94# assignment to object attributes. 95# 96# Once a set of Python objects have been instantiated in a hierarchy, 97# calling 'instantiate(obj)' (where obj is the root of the hierarchy) 98# will generate a .ini file. 99# 100##################################################################### 101 102# list of all SimObject classes 103allClasses = {} 104 105# dict to look up SimObjects based on path 106instanceDict = {} 107 108def public_value(key, value): 109 return key.startswith('_') or \ 110 isinstance(value, (FunctionType, MethodType, ModuleType, 111 classmethod, type)) 112 113# The metaclass for SimObject. This class controls how new classes 114# that derive from SimObject are instantiated, and provides inherited 115# class behavior (just like a class controls how instances of that 116# class are instantiated, and provides inherited instance behavior). 117class MetaSimObject(type): 118 # Attributes that can be set only at initialization time 119 init_keywords = { 'abstract' : bool, 120 'cxx_class' : str, 121 'cxx_type' : str, 122 'type' : str } 123 # Attributes that can be set any time 124 keywords = { 'check' : FunctionType } 125 126 # __new__ is called before __init__, and is where the statements 127 # in the body of the class definition get loaded into the class's 128 # __dict__. We intercept this to filter out parameter & port assignments 129 # and only allow "private" attributes to be passed to the base 130 # __new__ (starting with underscore). 131 def __new__(mcls, name, bases, dict): 132 assert name not in allClasses, "SimObject %s already present" % name 133 134 # Copy "private" attributes, functions, and classes to the 135 # official dict. Everything else goes in _init_dict to be 136 # filtered in __init__. 137 cls_dict = {} 138 value_dict = {} 139 for key,val in dict.items(): 140 if public_value(key, val): 141 cls_dict[key] = val 142 else: 143 # must be a param/port setting 144 value_dict[key] = val 145 if 'abstract' not in value_dict: 146 value_dict['abstract'] = False 147 cls_dict['_value_dict'] = value_dict 148 cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict) 149 if 'type' in value_dict: 150 allClasses[name] = cls 151 return cls 152 153 # subclass initialization 154 def __init__(cls, name, bases, dict): 155 # calls type.__init__()... I think that's a no-op, but leave 156 # it here just in case it's not. 157 super(MetaSimObject, cls).__init__(name, bases, dict) 158 159 # initialize required attributes 160 161 # class-only attributes 162 cls._params = multidict() # param descriptions 163 cls._ports = multidict() # port descriptions 164 165 # class or instance attributes 166 cls._values = multidict() # param values 167 cls._children = multidict() # SimObject children 168 cls._port_refs = multidict() # port ref objects 169 cls._instantiated = False # really instantiated, cloned, or subclassed 170 171 # We don't support multiple inheritance of sim objects. If you want 172 # to, you must fix multidict to deal with it properly. Non sim-objects 173 # are ok, though 174 bTotal = 0 175 for c in bases: 176 if isinstance(c, MetaSimObject): 177 bTotal += 1 178 if bTotal > 1: 179 raise TypeError, "SimObjects do not support multiple inheritance" 180 181 base = bases[0] 182 183 # Set up general inheritance via multidicts. A subclass will 184 # inherit all its settings from the base class. The only time 185 # the following is not true is when we define the SimObject 186 # class itself (in which case the multidicts have no parent). 187 if isinstance(base, MetaSimObject): 188 cls._base = base 189 cls._params.parent = base._params 190 cls._ports.parent = base._ports 191 cls._values.parent = base._values 192 cls._children.parent = base._children 193 cls._port_refs.parent = base._port_refs 194 # mark base as having been subclassed 195 base._instantiated = True 196 else: 197 cls._base = None 198 199 # default keyword values 200 if 'type' in cls._value_dict: 201 if 'cxx_class' not in cls._value_dict: 202 cls._value_dict['cxx_class'] = cls._value_dict['type'] 203 204 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class'] 205 206 # Export methods are automatically inherited via C++, so we 207 # don't want the method declarations to get inherited on the 208 # python side (and thus end up getting repeated in the wrapped 209 # versions of derived classes). The code below basicallly 210 # suppresses inheritance by substituting in the base (null) 211 # versions of these methods unless a different version is 212 # explicitly supplied. 213 for method_name in ('export_methods', 'export_method_cxx_predecls', 214 'export_method_swig_predecls'): 215 if method_name not in cls.__dict__: 216 base_method = getattr(MetaSimObject, method_name) 217 m = MethodType(base_method, cls, MetaSimObject) 218 setattr(cls, method_name, m) 219 220 # Now process the _value_dict items. They could be defining 221 # new (or overriding existing) parameters or ports, setting 222 # class keywords (e.g., 'abstract'), or setting parameter 223 # values or port bindings. The first 3 can only be set when 224 # the class is defined, so we handle them here. The others 225 # can be set later too, so just emulate that by calling 226 # setattr(). 227 for key,val in cls._value_dict.items(): 228 # param descriptions 229 if isinstance(val, ParamDesc): 230 cls._new_param(key, val) 231 232 # port objects 233 elif isinstance(val, Port): 234 cls._new_port(key, val) 235 236 # init-time-only keywords 237 elif cls.init_keywords.has_key(key): 238 cls._set_keyword(key, val, cls.init_keywords[key]) 239 240 # default: use normal path (ends up in __setattr__) 241 else: 242 setattr(cls, key, val) 243 244 def _set_keyword(cls, keyword, val, kwtype): 245 if not isinstance(val, kwtype): 246 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \ 247 (keyword, type(val), kwtype) 248 if isinstance(val, FunctionType): 249 val = classmethod(val) 250 type.__setattr__(cls, keyword, val) 251 252 def _new_param(cls, name, pdesc): 253 # each param desc should be uniquely assigned to one variable 254 assert(not hasattr(pdesc, 'name')) 255 pdesc.name = name 256 cls._params[name] = pdesc 257 if hasattr(pdesc, 'default'): 258 cls._set_param(name, pdesc.default, pdesc) 259 260 def _set_param(cls, name, value, param): 261 assert(param.name == name) 262 try: 263 value = param.convert(value) 264 except Exception, e: 265 msg = "%s\nError setting param %s.%s to %s\n" % \ 266 (e, cls.__name__, name, value) 267 e.args = (msg, ) 268 raise 269 cls._values[name] = value 270 # if param value is a SimObject, make it a child too, so that 271 # it gets cloned properly when the class is instantiated 272 if isSimObjectOrVector(value) and not value.has_parent(): 273 cls._add_cls_child(name, value) 274 275 def _add_cls_child(cls, name, child): 276 # It's a little funky to have a class as a parent, but these 277 # objects should never be instantiated (only cloned, which 278 # clears the parent pointer), and this makes it clear that the 279 # object is not an orphan and can provide better error 280 # messages. 281 child.set_parent(cls, name) 282 cls._children[name] = child 283 284 def _new_port(cls, name, port): 285 # each port should be uniquely assigned to one variable 286 assert(not hasattr(port, 'name')) 287 port.name = name 288 cls._ports[name] = port 289 290 # same as _get_port_ref, effectively, but for classes 291 def _cls_get_port_ref(cls, attr): 292 # Return reference that can be assigned to another port 293 # via __setattr__. There is only ever one reference 294 # object per port, but we create them lazily here. 295 ref = cls._port_refs.get(attr) 296 if not ref: 297 ref = cls._ports[attr].makeRef(cls) 298 cls._port_refs[attr] = ref 299 return ref 300 301 # Set attribute (called on foo.attr = value when foo is an 302 # instance of class cls). 303 def __setattr__(cls, attr, value): 304 # normal processing for private attributes 305 if public_value(attr, value): 306 type.__setattr__(cls, attr, value) 307 return 308 309 if cls.keywords.has_key(attr): 310 cls._set_keyword(attr, value, cls.keywords[attr]) 311 return 312 313 if cls._ports.has_key(attr): 314 cls._cls_get_port_ref(attr).connect(value) 315 return 316 317 if isSimObjectOrSequence(value) and cls._instantiated: 318 raise RuntimeError, \ 319 "cannot set SimObject parameter '%s' after\n" \ 320 " class %s has been instantiated or subclassed" \ 321 % (attr, cls.__name__) 322 323 # check for param 324 param = cls._params.get(attr) 325 if param: 326 cls._set_param(attr, value, param) 327 return 328 329 if isSimObjectOrSequence(value): 330 # If RHS is a SimObject, it's an implicit child assignment. 331 cls._add_cls_child(attr, coerceSimObjectOrVector(value)) 332 return 333 334 # no valid assignment... raise exception 335 raise AttributeError, \ 336 "Class %s has no parameter \'%s\'" % (cls.__name__, attr) 337 338 def __getattr__(cls, attr): 339 if attr == 'cxx_class_path': 340 return cls.cxx_class.split('::') 341 342 if attr == 'cxx_class_name': 343 return cls.cxx_class_path[-1] 344 345 if attr == 'cxx_namespaces': 346 return cls.cxx_class_path[:-1] 347 348 if cls._values.has_key(attr): 349 return cls._values[attr] 350 351 if cls._children.has_key(attr): 352 return cls._children[attr] 353 354 raise AttributeError, \ 355 "object '%s' has no attribute '%s'" % (cls.__name__, attr) 356 357 def __str__(cls): 358 return cls.__name__ 359 360 # See ParamValue.cxx_predecls for description. 361 def cxx_predecls(cls, code): 362 code('#include "params/$cls.hh"') 363 364 # See ParamValue.swig_predecls for description. 365 def swig_predecls(cls, code): 366 code('%import "python/m5/internal/param_$cls.i"') 367 368 # Hook for exporting additional C++ methods to Python via SWIG. 369 # Default is none, override using @classmethod in class definition. 370 def export_methods(cls, code): 371 pass 372 373 # Generate the code needed as a prerequisite for the C++ methods 374 # exported via export_methods() to be compiled in the _wrap.cc 375 # file. Typically generates one or more #include statements. If 376 # any methods are exported, typically at least the C++ header 377 # declaring the relevant SimObject class must be included. 378 def export_method_cxx_predecls(cls, code): 379 pass 380 381 # Generate the code needed as a prerequisite for the C++ methods 382 # exported via export_methods() to be processed by SWIG. 383 # Typically generates one or more %include or %import statements. 384 # If any methods are exported, typically at least the C++ header 385 # declaring the relevant SimObject class must be included. 386 def export_method_swig_predecls(cls, code): 387 pass 388 389 # Generate the declaration for this object for wrapping with SWIG. 390 # Generates code that goes into a SWIG .i file. Called from 391 # src/SConscript. 392 def swig_decl(cls, code): 393 class_path = cls.cxx_class.split('::') 394 classname = class_path[-1] 395 namespaces = class_path[:-1] 396 397 # The 'local' attribute restricts us to the params declared in 398 # the object itself, not including inherited params (which 399 # will also be inherited from the base class's param struct 400 # here). 401 params = cls._params.local.values() 402 ports = cls._ports.local 403 404 code('%module(package="m5.internal") param_$cls') 405 code() 406 code('%{') 407 code('#include "params/$cls.hh"') 408 for param in params: 409 param.cxx_predecls(code) 410 cls.export_method_cxx_predecls(code) 411 code('''\ 412/** 413 * This is a workaround for bug in swig. Prior to gcc 4.6.1 the STL 414 * headers like vector, string, etc. used to automatically pull in 415 * the cstddef header but starting with gcc 4.6.1 they no longer do. 416 * This leads to swig generated a file that does not compile so we 417 * explicitly include cstddef. Additionally, including version 2.0.4, 418 * swig uses ptrdiff_t without the std:: namespace prefix which is 419 * required with gcc 4.6.1. We explicitly provide access to it. 420 */ 421#include <cstddef> 422using std::ptrdiff_t; 423''') 424 code('%}') 425 code() 426 427 for param in params: 428 param.swig_predecls(code) 429 cls.export_method_swig_predecls(code) 430 431 code() 432 if cls._base: 433 code('%import "python/m5/internal/param_${{cls._base}}.i"') 434 code() 435 436 for ns in namespaces: 437 code('namespace $ns {') 438 439 if namespaces: 440 code('// avoid name conflicts') 441 sep_string = '_COLONS_' 442 flat_name = sep_string.join(class_path) 443 code('%rename($flat_name) $classname;') 444 445 code() 446 code('// stop swig from creating/wrapping default ctor/dtor') 447 code('%nodefault $classname;') 448 code('class $classname') 449 if cls._base: 450 code(' : public ${{cls._base.cxx_class}}') 451 code('{') 452 code(' public:') 453 cls.export_methods(code) 454 code('};') 455 456 for ns in reversed(namespaces): 457 code('} // namespace $ns') 458 459 code() 460 code('%include "params/$cls.hh"') 461 462 463 # Generate the C++ declaration (.hh file) for this SimObject's 464 # param struct. Called from src/SConscript. 465 def cxx_param_decl(cls, code): 466 # The 'local' attribute restricts us to the params declared in 467 # the object itself, not including inherited params (which 468 # will also be inherited from the base class's param struct 469 # here). 470 params = cls._params.local.values() 471 ports = cls._ports.local 472 try: 473 ptypes = [p.ptype for p in params] 474 except: 475 print cls, p, p.ptype_str 476 print params 477 raise 478 479 class_path = cls._value_dict['cxx_class'].split('::') 480 481 code('''\ 482#ifndef __PARAMS__${cls}__ 483#define __PARAMS__${cls}__ 484 485''') 486 487 # A forward class declaration is sufficient since we are just 488 # declaring a pointer. 489 for ns in class_path[:-1]: 490 code('namespace $ns {') 491 code('class $0;', class_path[-1]) 492 for ns in reversed(class_path[:-1]): 493 code('} // namespace $ns') 494 code() 495 496 # The base SimObject has a couple of params that get 497 # automatically set from Python without being declared through 498 # the normal Param mechanism; we slip them in here (needed 499 # predecls now, actual declarations below) 500 if cls == SimObject: 501 code(''' 502#ifndef PY_VERSION 503struct PyObject; 504#endif 505 506#include <string> 507 508class EventQueue; 509''') 510 for param in params: 511 param.cxx_predecls(code) 512 for port in ports.itervalues(): 513 port.cxx_predecls(code) 514 code() 515 516 if cls._base: 517 code('#include "params/${{cls._base.type}}.hh"') 518 code() 519 520 for ptype in ptypes: 521 if issubclass(ptype, Enum): 522 code('#include "enums/${{ptype.__name__}}.hh"') 523 code() 524 525 # now generate the actual param struct 526 code("struct ${cls}Params") 527 if cls._base: 528 code(" : public ${{cls._base.type}}Params") 529 code("{") 530 if not hasattr(cls, 'abstract') or not cls.abstract: 531 if 'type' in cls.__dict__: 532 code(" ${{cls.cxx_type}} create();") 533 534 code.indent() 535 if cls == SimObject: 536 code(''' 537 SimObjectParams() 538 { 539 extern EventQueue mainEventQueue; 540 eventq = &mainEventQueue; 541 } 542 virtual ~SimObjectParams() {} 543 544 std::string name; 545 PyObject *pyobj; 546 EventQueue *eventq; 547 ''') 548 for param in params: 549 param.cxx_decl(code) 550 for port in ports.itervalues(): 551 port.cxx_decl(code) 552 553 code.dedent() 554 code('};') 555 556 code() 557 code('#endif // __PARAMS__${cls}__') 558 return code 559 560 561 562# The SimObject class is the root of the special hierarchy. Most of 563# the code in this class deals with the configuration hierarchy itself 564# (parent/child node relationships). 565class SimObject(object): 566 # Specify metaclass. Any class inheriting from SimObject will 567 # get this metaclass. 568 __metaclass__ = MetaSimObject 569 type = 'SimObject' 570 abstract = True 571 572 @classmethod 573 def export_method_cxx_predecls(cls, code): 574 code(''' 575#include <Python.h> 576 577#include "sim/serialize.hh" 578#include "sim/sim_object.hh" 579''') 580 581 @classmethod 582 def export_method_swig_predecls(cls, code): 583 code(''' 584%include <std_string.i> 585''') 586 587 @classmethod 588 def export_methods(cls, code): 589 code(''' 590 enum State { 591 Running, 592 Draining, 593 Drained 594 }; 595 596 void init(); 597 void loadState(Checkpoint *cp); 598 void initState(); 599 void regStats(); 600 void resetStats(); 601 void startup(); 602 603 unsigned int drain(Event *drain_event); 604 void resume(); 605 void switchOut(); 606 void takeOverFrom(BaseCPU *cpu); 607''') 608 609 # Initialize new instance. For objects with SimObject-valued 610 # children, we need to recursively clone the classes represented 611 # by those param values as well in a consistent "deep copy"-style 612 # fashion. That is, we want to make sure that each instance is 613 # cloned only once, and that if there are multiple references to 614 # the same original object, we end up with the corresponding 615 # cloned references all pointing to the same cloned instance. 616 def __init__(self, **kwargs): 617 ancestor = kwargs.get('_ancestor') 618 memo_dict = kwargs.get('_memo') 619 if memo_dict is None: 620 # prepare to memoize any recursively instantiated objects 621 memo_dict = {} 622 elif ancestor: 623 # memoize me now to avoid problems with recursive calls 624 memo_dict[ancestor] = self 625 626 if not ancestor: 627 ancestor = self.__class__ 628 ancestor._instantiated = True 629 630 # initialize required attributes 631 self._parent = None 632 self._name = None 633 self._ccObject = None # pointer to C++ object 634 self._ccParams = None 635 self._instantiated = False # really "cloned" 636 637 # Clone children specified at class level. No need for a 638 # multidict here since we will be cloning everything. 639 # Do children before parameter values so that children that 640 # are also param values get cloned properly. 641 self._children = {} 642 for key,val in ancestor._children.iteritems(): 643 self.add_child(key, val(_memo=memo_dict)) 644 645 # Inherit parameter values from class using multidict so 646 # individual value settings can be overridden but we still 647 # inherit late changes to non-overridden class values. 648 self._values = multidict(ancestor._values) 649 # clone SimObject-valued parameters 650 for key,val in ancestor._values.iteritems(): 651 val = tryAsSimObjectOrVector(val) 652 if val is not None: 653 self._values[key] = val(_memo=memo_dict) 654 655 # clone port references. no need to use a multidict here 656 # since we will be creating new references for all ports. 657 self._port_refs = {} 658 for key,val in ancestor._port_refs.iteritems(): 659 self._port_refs[key] = val.clone(self, memo_dict) 660 # apply attribute assignments from keyword args, if any 661 for key,val in kwargs.iteritems(): 662 setattr(self, key, val) 663 664 # "Clone" the current instance by creating another instance of 665 # this instance's class, but that inherits its parameter values 666 # and port mappings from the current instance. If we're in a 667 # "deep copy" recursive clone, check the _memo dict to see if 668 # we've already cloned this instance. 669 def __call__(self, **kwargs): 670 memo_dict = kwargs.get('_memo') 671 if memo_dict is None: 672 # no memo_dict: must be top-level clone operation. 673 # this is only allowed at the root of a hierarchy 674 if self._parent: 675 raise RuntimeError, "attempt to clone object %s " \ 676 "not at the root of a tree (parent = %s)" \ 677 % (self, self._parent) 678 # create a new dict and use that. 679 memo_dict = {} 680 kwargs['_memo'] = memo_dict 681 elif memo_dict.has_key(self): 682 # clone already done & memoized 683 return memo_dict[self] 684 return self.__class__(_ancestor = self, **kwargs) 685 686 def _get_port_ref(self, attr): 687 # Return reference that can be assigned to another port 688 # via __setattr__. There is only ever one reference 689 # object per port, but we create them lazily here. 690 ref = self._port_refs.get(attr) 691 if not ref: 692 ref = self._ports[attr].makeRef(self) 693 self._port_refs[attr] = ref 694 return ref 695 696 def __getattr__(self, attr): 697 if self._ports.has_key(attr): 698 return self._get_port_ref(attr) 699 700 if self._values.has_key(attr): 701 return self._values[attr] 702 703 if self._children.has_key(attr): 704 return self._children[attr] 705 706 # If the attribute exists on the C++ object, transparently 707 # forward the reference there. This is typically used for 708 # SWIG-wrapped methods such as init(), regStats(), 709 # resetStats(), startup(), drain(), and 710 # resume(). 711 if self._ccObject and hasattr(self._ccObject, attr): 712 return getattr(self._ccObject, attr) 713 714 raise AttributeError, "object '%s' has no attribute '%s'" \ 715 % (self.__class__.__name__, attr) 716 717 # Set attribute (called on foo.attr = value when foo is an 718 # instance of class cls). 719 def __setattr__(self, attr, value): 720 # normal processing for private attributes 721 if attr.startswith('_'): 722 object.__setattr__(self, attr, value) 723 return 724 725 if self._ports.has_key(attr): 726 # set up port connection 727 self._get_port_ref(attr).connect(value) 728 return 729 730 if isSimObjectOrSequence(value) and self._instantiated: 731 raise RuntimeError, \ 732 "cannot set SimObject parameter '%s' after\n" \ 733 " instance been cloned %s" % (attr, `self`) 734 735 param = self._params.get(attr) 736 if param: 737 try: 738 value = param.convert(value) 739 except Exception, e: 740 msg = "%s\nError setting param %s.%s to %s\n" % \ 741 (e, self.__class__.__name__, attr, value) 742 e.args = (msg, ) 743 raise 744 self._values[attr] = value 745 # implicitly parent unparented objects assigned as params 746 if isSimObjectOrVector(value) and not value.has_parent(): 747 self.add_child(attr, value) 748 return 749 750 # if RHS is a SimObject, it's an implicit child assignment 751 if isSimObjectOrSequence(value): 752 self.add_child(attr, value) 753 return 754 755 # no valid assignment... raise exception 756 raise AttributeError, "Class %s has no parameter %s" \ 757 % (self.__class__.__name__, attr) 758 759 760 # this hack allows tacking a '[0]' onto parameters that may or may 761 # not be vectors, and always getting the first element (e.g. cpus) 762 def __getitem__(self, key): 763 if key == 0: 764 return self 765 raise TypeError, "Non-zero index '%s' to SimObject" % key 766 767 # Also implemented by SimObjectVector 768 def clear_parent(self, old_parent): 769 assert self._parent is old_parent 770 self._parent = None 771 772 # Also implemented by SimObjectVector 773 def set_parent(self, parent, name): 774 self._parent = parent 775 self._name = name 776 777 # Also implemented by SimObjectVector 778 def get_name(self): 779 return self._name 780 781 # Also implemented by SimObjectVector 782 def has_parent(self): 783 return self._parent is not None 784 785 # clear out child with given name. This code is not likely to be exercised. 786 # See comment in add_child. 787 def clear_child(self, name): 788 child = self._children[name] 789 child.clear_parent(self) 790 del self._children[name] 791 792 # Add a new child to this object. 793 def add_child(self, name, child): 794 child = coerceSimObjectOrVector(child) 795 if child.has_parent(): 796 print "warning: add_child('%s'): child '%s' already has parent" % \ 797 (name, child.get_name()) 798 if self._children.has_key(name): 799 # This code path had an undiscovered bug that would make it fail 800 # at runtime. It had been here for a long time and was only 801 # exposed by a buggy script. Changes here will probably not be 802 # exercised without specialized testing. 803 self.clear_child(name) 804 child.set_parent(self, name) 805 self._children[name] = child 806 807 # Take SimObject-valued parameters that haven't been explicitly 808 # assigned as children and make them children of the object that 809 # they were assigned to as a parameter value. This guarantees 810 # that when we instantiate all the parameter objects we're still 811 # inside the configuration hierarchy. 812 def adoptOrphanParams(self): 813 for key,val in self._values.iteritems(): 814 if not isSimObjectVector(val) and isSimObjectSequence(val): 815 # need to convert raw SimObject sequences to 816 # SimObjectVector class so we can call has_parent() 817 val = SimObjectVector(val) 818 self._values[key] = val 819 if isSimObjectOrVector(val) and not val.has_parent(): 820 print "warning: %s adopting orphan SimObject param '%s'" \ 821 % (self, key) 822 self.add_child(key, val) 823 824 def path(self): 825 if not self._parent: 826 return '<orphan %s>' % self.__class__ 827 ppath = self._parent.path() 828 if ppath == 'root': 829 return self._name 830 return ppath + "." + self._name 831 832 def __str__(self): 833 return self.path() 834 835 def ini_str(self): 836 return self.path() 837 838 def find_any(self, ptype): 839 if isinstance(self, ptype): 840 return self, True 841 842 found_obj = None 843 for child in self._children.itervalues(): 844 if isinstance(child, ptype): 845 if found_obj != None and child != found_obj: 846 raise AttributeError, \ 847 'parent.any matched more than one: %s %s' % \ 848 (found_obj.path, child.path) 849 found_obj = child 850 # search param space 851 for pname,pdesc in self._params.iteritems(): 852 if issubclass(pdesc.ptype, ptype): 853 match_obj = self._values[pname] 854 if found_obj != None and found_obj != match_obj: 855 raise AttributeError, \ 856 'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path) 857 found_obj = match_obj 858 return found_obj, found_obj != None 859 860 def find_all(self, ptype): 861 all = {} 862 # search children 863 for child in self._children.itervalues(): 864 if isinstance(child, ptype) and not isproxy(child) and \ 865 not isNullPointer(child): 866 all[child] = True 867 if isSimObject(child): 868 # also add results from the child itself 869 child_all, done = child.find_all(ptype) 870 all.update(dict(zip(child_all, [done] * len(child_all)))) 871 # search param space 872 for pname,pdesc in self._params.iteritems(): 873 if issubclass(pdesc.ptype, ptype): 874 match_obj = self._values[pname] 875 if not isproxy(match_obj) and not isNullPointer(match_obj): 876 all[match_obj] = True 877 return all.keys(), True 878 879 def unproxy(self, base): 880 return self 881 882 def unproxyParams(self): 883 for param in self._params.iterkeys(): 884 value = self._values.get(param) 885 if value != None and isproxy(value): 886 try: 887 value = value.unproxy(self) 888 except: 889 print "Error in unproxying param '%s' of %s" % \ 890 (param, self.path()) 891 raise 892 setattr(self, param, value) 893 894 # Unproxy ports in sorted order so that 'append' operations on 895 # vector ports are done in a deterministic fashion. 896 port_names = self._ports.keys() 897 port_names.sort() 898 for port_name in port_names: 899 port = self._port_refs.get(port_name) 900 if port != None: 901 port.unproxy(self) 902 903 def print_ini(self, ini_file): 904 print >>ini_file, '[' + self.path() + ']' # .ini section header 905 906 instanceDict[self.path()] = self 907 908 if hasattr(self, 'type'): 909 print >>ini_file, 'type=%s' % self.type 910 911 if len(self._children.keys()): 912 print >>ini_file, 'children=%s' % \ 913 ' '.join(self._children[n].get_name() \ 914 for n in sorted(self._children.keys())) 915 916 for param in sorted(self._params.keys()): 917 value = self._values.get(param) 918 if value != None: 919 print >>ini_file, '%s=%s' % (param, 920 self._values[param].ini_str()) 921 922 for port_name in sorted(self._ports.keys()): 923 port = self._port_refs.get(port_name, None) 924 if port != None: 925 print >>ini_file, '%s=%s' % (port_name, port.ini_str()) 926 927 print >>ini_file # blank line between objects 928 929 # generate a tree of dictionaries expressing all the parameters in the 930 # instantiated system for use by scripts that want to do power, thermal 931 # visualization, and other similar tasks 932 def get_config_as_dict(self): 933 d = attrdict() 934 if hasattr(self, 'type'): 935 d.type = self.type 936 if hasattr(self, 'cxx_class'): 937 d.cxx_class = self.cxx_class 938 # Add the name and path of this object to be able to link to 939 # the stats 940 d.name = self.get_name() 941 d.path = self.path() 942 943 for param in sorted(self._params.keys()): 944 value = self._values.get(param) 945 if value != None: 946 try: 947 # Use native type for those supported by JSON and 948 # strings for everything else. skipkeys=True seems 949 # to not work as well as one would hope 950 if type(self._values[param].value) in \ 951 [str, unicode, int, long, float, bool, None]: 952 d[param] = self._values[param].value 953 else: 954 d[param] = str(self._values[param]) 955 956 except AttributeError: 957 pass 958 959 for n in sorted(self._children.keys()): 960 child = self._children[n] 961 # Use the name of the attribute (and not get_name()) as 962 # the key in the JSON dictionary to capture the hierarchy 963 # in the Python code that assembled this system 964 d[n] = child.get_config_as_dict() 965 966 for port_name in sorted(self._ports.keys()): 967 port = self._port_refs.get(port_name, None) 968 if port != None: 969 # Represent each port with a dictionary containing the 970 # prominent attributes 971 d[port_name] = port.get_config_as_dict() 972 973 return d 974 975 def getCCParams(self): 976 if self._ccParams: 977 return self._ccParams 978 979 cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type) 980 cc_params = cc_params_struct() 981 cc_params.pyobj = self 982 cc_params.name = str(self) 983 984 param_names = self._params.keys() 985 param_names.sort() 986 for param in param_names: 987 value = self._values.get(param) 988 if value is None: 989 fatal("%s.%s without default or user set value", 990 self.path(), param) 991 992 value = value.getValue() 993 if isinstance(self._params[param], VectorParamDesc): 994 assert isinstance(value, list) 995 vec = getattr(cc_params, param) 996 assert not len(vec) 997 for v in value: 998 vec.append(v) 999 else: 1000 setattr(cc_params, param, value) 1001 1002 port_names = self._ports.keys() 1003 port_names.sort() 1004 for port_name in port_names: 1005 port = self._port_refs.get(port_name, None) 1006 if port != None: 1007 port_count = len(port) 1008 else: 1009 port_count = 0 1010 setattr(cc_params, 'port_' + port_name + '_connection_count', 1011 port_count) 1012 self._ccParams = cc_params 1013 return self._ccParams 1014 1015 # Get C++ object corresponding to this object, calling C++ if 1016 # necessary to construct it. Does *not* recursively create 1017 # children. 1018 def getCCObject(self): 1019 if not self._ccObject: 1020 # Make sure this object is in the configuration hierarchy 1021 if not self._parent and not isRoot(self): 1022 raise RuntimeError, "Attempt to instantiate orphan node" 1023 # Cycles in the configuration hierarchy are not supported. This 1024 # will catch the resulting recursion and stop. 1025 self._ccObject = -1 1026 params = self.getCCParams() 1027 self._ccObject = params.create() 1028 elif self._ccObject == -1: 1029 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \ 1030 % self.path() 1031 return self._ccObject 1032 1033 def descendants(self): 1034 yield self 1035 for child in self._children.itervalues(): 1036 for obj in child.descendants(): 1037 yield obj 1038 1039 # Call C++ to create C++ object corresponding to this object 1040 def createCCObject(self): 1041 self.getCCParams() 1042 self.getCCObject() # force creation 1043 1044 def getValue(self): 1045 return self.getCCObject() 1046 1047 # Create C++ port connections corresponding to the connections in 1048 # _port_refs 1049 def connectPorts(self): 1050 for portRef in self._port_refs.itervalues(): 1051 portRef.ccConnect() 1052 | 1# Copyright (c) 2012 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) 2004-2006 The Regents of The University of Michigan 14# Copyright (c) 2010 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# Nathan Binkert 42# Andreas Hansson 43 44import sys 45from types import FunctionType, MethodType, ModuleType 46 47import m5 48from m5.util import * 49 50# Have to import params up top since Param is referenced on initial 51# load (when SimObject class references Param to create a class 52# variable, the 'name' param)... 53from m5.params import * 54# There are a few things we need that aren't in params.__all__ since 55# normal users don't need them 56from m5.params import ParamDesc, VectorParamDesc, \ 57 isNullPointer, SimObjectVector, Port 58 59from m5.proxy import * 60from m5.proxy import isproxy 61 62##################################################################### 63# 64# M5 Python Configuration Utility 65# 66# The basic idea is to write simple Python programs that build Python 67# objects corresponding to M5 SimObjects for the desired simulation 68# configuration. For now, the Python emits a .ini file that can be 69# parsed by M5. In the future, some tighter integration between M5 70# and the Python interpreter may allow bypassing the .ini file. 71# 72# Each SimObject class in M5 is represented by a Python class with the 73# same name. The Python inheritance tree mirrors the M5 C++ tree 74# (e.g., SimpleCPU derives from BaseCPU in both cases, and all 75# SimObjects inherit from a single SimObject base class). To specify 76# an instance of an M5 SimObject in a configuration, the user simply 77# instantiates the corresponding Python object. The parameters for 78# that SimObject are given by assigning to attributes of the Python 79# object, either using keyword assignment in the constructor or in 80# separate assignment statements. For example: 81# 82# cache = BaseCache(size='64KB') 83# cache.hit_latency = 3 84# cache.assoc = 8 85# 86# The magic lies in the mapping of the Python attributes for SimObject 87# classes to the actual SimObject parameter specifications. This 88# allows parameter validity checking in the Python code. Continuing 89# the example above, the statements "cache.blurfl=3" or 90# "cache.assoc='hello'" would both result in runtime errors in Python, 91# since the BaseCache object has no 'blurfl' parameter and the 'assoc' 92# parameter requires an integer, respectively. This magic is done 93# primarily by overriding the special __setattr__ method that controls 94# assignment to object attributes. 95# 96# Once a set of Python objects have been instantiated in a hierarchy, 97# calling 'instantiate(obj)' (where obj is the root of the hierarchy) 98# will generate a .ini file. 99# 100##################################################################### 101 102# list of all SimObject classes 103allClasses = {} 104 105# dict to look up SimObjects based on path 106instanceDict = {} 107 108def public_value(key, value): 109 return key.startswith('_') or \ 110 isinstance(value, (FunctionType, MethodType, ModuleType, 111 classmethod, type)) 112 113# The metaclass for SimObject. This class controls how new classes 114# that derive from SimObject are instantiated, and provides inherited 115# class behavior (just like a class controls how instances of that 116# class are instantiated, and provides inherited instance behavior). 117class MetaSimObject(type): 118 # Attributes that can be set only at initialization time 119 init_keywords = { 'abstract' : bool, 120 'cxx_class' : str, 121 'cxx_type' : str, 122 'type' : str } 123 # Attributes that can be set any time 124 keywords = { 'check' : FunctionType } 125 126 # __new__ is called before __init__, and is where the statements 127 # in the body of the class definition get loaded into the class's 128 # __dict__. We intercept this to filter out parameter & port assignments 129 # and only allow "private" attributes to be passed to the base 130 # __new__ (starting with underscore). 131 def __new__(mcls, name, bases, dict): 132 assert name not in allClasses, "SimObject %s already present" % name 133 134 # Copy "private" attributes, functions, and classes to the 135 # official dict. Everything else goes in _init_dict to be 136 # filtered in __init__. 137 cls_dict = {} 138 value_dict = {} 139 for key,val in dict.items(): 140 if public_value(key, val): 141 cls_dict[key] = val 142 else: 143 # must be a param/port setting 144 value_dict[key] = val 145 if 'abstract' not in value_dict: 146 value_dict['abstract'] = False 147 cls_dict['_value_dict'] = value_dict 148 cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict) 149 if 'type' in value_dict: 150 allClasses[name] = cls 151 return cls 152 153 # subclass initialization 154 def __init__(cls, name, bases, dict): 155 # calls type.__init__()... I think that's a no-op, but leave 156 # it here just in case it's not. 157 super(MetaSimObject, cls).__init__(name, bases, dict) 158 159 # initialize required attributes 160 161 # class-only attributes 162 cls._params = multidict() # param descriptions 163 cls._ports = multidict() # port descriptions 164 165 # class or instance attributes 166 cls._values = multidict() # param values 167 cls._children = multidict() # SimObject children 168 cls._port_refs = multidict() # port ref objects 169 cls._instantiated = False # really instantiated, cloned, or subclassed 170 171 # We don't support multiple inheritance of sim objects. If you want 172 # to, you must fix multidict to deal with it properly. Non sim-objects 173 # are ok, though 174 bTotal = 0 175 for c in bases: 176 if isinstance(c, MetaSimObject): 177 bTotal += 1 178 if bTotal > 1: 179 raise TypeError, "SimObjects do not support multiple inheritance" 180 181 base = bases[0] 182 183 # Set up general inheritance via multidicts. A subclass will 184 # inherit all its settings from the base class. The only time 185 # the following is not true is when we define the SimObject 186 # class itself (in which case the multidicts have no parent). 187 if isinstance(base, MetaSimObject): 188 cls._base = base 189 cls._params.parent = base._params 190 cls._ports.parent = base._ports 191 cls._values.parent = base._values 192 cls._children.parent = base._children 193 cls._port_refs.parent = base._port_refs 194 # mark base as having been subclassed 195 base._instantiated = True 196 else: 197 cls._base = None 198 199 # default keyword values 200 if 'type' in cls._value_dict: 201 if 'cxx_class' not in cls._value_dict: 202 cls._value_dict['cxx_class'] = cls._value_dict['type'] 203 204 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class'] 205 206 # Export methods are automatically inherited via C++, so we 207 # don't want the method declarations to get inherited on the 208 # python side (and thus end up getting repeated in the wrapped 209 # versions of derived classes). The code below basicallly 210 # suppresses inheritance by substituting in the base (null) 211 # versions of these methods unless a different version is 212 # explicitly supplied. 213 for method_name in ('export_methods', 'export_method_cxx_predecls', 214 'export_method_swig_predecls'): 215 if method_name not in cls.__dict__: 216 base_method = getattr(MetaSimObject, method_name) 217 m = MethodType(base_method, cls, MetaSimObject) 218 setattr(cls, method_name, m) 219 220 # Now process the _value_dict items. They could be defining 221 # new (or overriding existing) parameters or ports, setting 222 # class keywords (e.g., 'abstract'), or setting parameter 223 # values or port bindings. The first 3 can only be set when 224 # the class is defined, so we handle them here. The others 225 # can be set later too, so just emulate that by calling 226 # setattr(). 227 for key,val in cls._value_dict.items(): 228 # param descriptions 229 if isinstance(val, ParamDesc): 230 cls._new_param(key, val) 231 232 # port objects 233 elif isinstance(val, Port): 234 cls._new_port(key, val) 235 236 # init-time-only keywords 237 elif cls.init_keywords.has_key(key): 238 cls._set_keyword(key, val, cls.init_keywords[key]) 239 240 # default: use normal path (ends up in __setattr__) 241 else: 242 setattr(cls, key, val) 243 244 def _set_keyword(cls, keyword, val, kwtype): 245 if not isinstance(val, kwtype): 246 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \ 247 (keyword, type(val), kwtype) 248 if isinstance(val, FunctionType): 249 val = classmethod(val) 250 type.__setattr__(cls, keyword, val) 251 252 def _new_param(cls, name, pdesc): 253 # each param desc should be uniquely assigned to one variable 254 assert(not hasattr(pdesc, 'name')) 255 pdesc.name = name 256 cls._params[name] = pdesc 257 if hasattr(pdesc, 'default'): 258 cls._set_param(name, pdesc.default, pdesc) 259 260 def _set_param(cls, name, value, param): 261 assert(param.name == name) 262 try: 263 value = param.convert(value) 264 except Exception, e: 265 msg = "%s\nError setting param %s.%s to %s\n" % \ 266 (e, cls.__name__, name, value) 267 e.args = (msg, ) 268 raise 269 cls._values[name] = value 270 # if param value is a SimObject, make it a child too, so that 271 # it gets cloned properly when the class is instantiated 272 if isSimObjectOrVector(value) and not value.has_parent(): 273 cls._add_cls_child(name, value) 274 275 def _add_cls_child(cls, name, child): 276 # It's a little funky to have a class as a parent, but these 277 # objects should never be instantiated (only cloned, which 278 # clears the parent pointer), and this makes it clear that the 279 # object is not an orphan and can provide better error 280 # messages. 281 child.set_parent(cls, name) 282 cls._children[name] = child 283 284 def _new_port(cls, name, port): 285 # each port should be uniquely assigned to one variable 286 assert(not hasattr(port, 'name')) 287 port.name = name 288 cls._ports[name] = port 289 290 # same as _get_port_ref, effectively, but for classes 291 def _cls_get_port_ref(cls, attr): 292 # Return reference that can be assigned to another port 293 # via __setattr__. There is only ever one reference 294 # object per port, but we create them lazily here. 295 ref = cls._port_refs.get(attr) 296 if not ref: 297 ref = cls._ports[attr].makeRef(cls) 298 cls._port_refs[attr] = ref 299 return ref 300 301 # Set attribute (called on foo.attr = value when foo is an 302 # instance of class cls). 303 def __setattr__(cls, attr, value): 304 # normal processing for private attributes 305 if public_value(attr, value): 306 type.__setattr__(cls, attr, value) 307 return 308 309 if cls.keywords.has_key(attr): 310 cls._set_keyword(attr, value, cls.keywords[attr]) 311 return 312 313 if cls._ports.has_key(attr): 314 cls._cls_get_port_ref(attr).connect(value) 315 return 316 317 if isSimObjectOrSequence(value) and cls._instantiated: 318 raise RuntimeError, \ 319 "cannot set SimObject parameter '%s' after\n" \ 320 " class %s has been instantiated or subclassed" \ 321 % (attr, cls.__name__) 322 323 # check for param 324 param = cls._params.get(attr) 325 if param: 326 cls._set_param(attr, value, param) 327 return 328 329 if isSimObjectOrSequence(value): 330 # If RHS is a SimObject, it's an implicit child assignment. 331 cls._add_cls_child(attr, coerceSimObjectOrVector(value)) 332 return 333 334 # no valid assignment... raise exception 335 raise AttributeError, \ 336 "Class %s has no parameter \'%s\'" % (cls.__name__, attr) 337 338 def __getattr__(cls, attr): 339 if attr == 'cxx_class_path': 340 return cls.cxx_class.split('::') 341 342 if attr == 'cxx_class_name': 343 return cls.cxx_class_path[-1] 344 345 if attr == 'cxx_namespaces': 346 return cls.cxx_class_path[:-1] 347 348 if cls._values.has_key(attr): 349 return cls._values[attr] 350 351 if cls._children.has_key(attr): 352 return cls._children[attr] 353 354 raise AttributeError, \ 355 "object '%s' has no attribute '%s'" % (cls.__name__, attr) 356 357 def __str__(cls): 358 return cls.__name__ 359 360 # See ParamValue.cxx_predecls for description. 361 def cxx_predecls(cls, code): 362 code('#include "params/$cls.hh"') 363 364 # See ParamValue.swig_predecls for description. 365 def swig_predecls(cls, code): 366 code('%import "python/m5/internal/param_$cls.i"') 367 368 # Hook for exporting additional C++ methods to Python via SWIG. 369 # Default is none, override using @classmethod in class definition. 370 def export_methods(cls, code): 371 pass 372 373 # Generate the code needed as a prerequisite for the C++ methods 374 # exported via export_methods() to be compiled in the _wrap.cc 375 # file. Typically generates one or more #include statements. If 376 # any methods are exported, typically at least the C++ header 377 # declaring the relevant SimObject class must be included. 378 def export_method_cxx_predecls(cls, code): 379 pass 380 381 # Generate the code needed as a prerequisite for the C++ methods 382 # exported via export_methods() to be processed by SWIG. 383 # Typically generates one or more %include or %import statements. 384 # If any methods are exported, typically at least the C++ header 385 # declaring the relevant SimObject class must be included. 386 def export_method_swig_predecls(cls, code): 387 pass 388 389 # Generate the declaration for this object for wrapping with SWIG. 390 # Generates code that goes into a SWIG .i file. Called from 391 # src/SConscript. 392 def swig_decl(cls, code): 393 class_path = cls.cxx_class.split('::') 394 classname = class_path[-1] 395 namespaces = class_path[:-1] 396 397 # The 'local' attribute restricts us to the params declared in 398 # the object itself, not including inherited params (which 399 # will also be inherited from the base class's param struct 400 # here). 401 params = cls._params.local.values() 402 ports = cls._ports.local 403 404 code('%module(package="m5.internal") param_$cls') 405 code() 406 code('%{') 407 code('#include "params/$cls.hh"') 408 for param in params: 409 param.cxx_predecls(code) 410 cls.export_method_cxx_predecls(code) 411 code('''\ 412/** 413 * This is a workaround for bug in swig. Prior to gcc 4.6.1 the STL 414 * headers like vector, string, etc. used to automatically pull in 415 * the cstddef header but starting with gcc 4.6.1 they no longer do. 416 * This leads to swig generated a file that does not compile so we 417 * explicitly include cstddef. Additionally, including version 2.0.4, 418 * swig uses ptrdiff_t without the std:: namespace prefix which is 419 * required with gcc 4.6.1. We explicitly provide access to it. 420 */ 421#include <cstddef> 422using std::ptrdiff_t; 423''') 424 code('%}') 425 code() 426 427 for param in params: 428 param.swig_predecls(code) 429 cls.export_method_swig_predecls(code) 430 431 code() 432 if cls._base: 433 code('%import "python/m5/internal/param_${{cls._base}}.i"') 434 code() 435 436 for ns in namespaces: 437 code('namespace $ns {') 438 439 if namespaces: 440 code('// avoid name conflicts') 441 sep_string = '_COLONS_' 442 flat_name = sep_string.join(class_path) 443 code('%rename($flat_name) $classname;') 444 445 code() 446 code('// stop swig from creating/wrapping default ctor/dtor') 447 code('%nodefault $classname;') 448 code('class $classname') 449 if cls._base: 450 code(' : public ${{cls._base.cxx_class}}') 451 code('{') 452 code(' public:') 453 cls.export_methods(code) 454 code('};') 455 456 for ns in reversed(namespaces): 457 code('} // namespace $ns') 458 459 code() 460 code('%include "params/$cls.hh"') 461 462 463 # Generate the C++ declaration (.hh file) for this SimObject's 464 # param struct. Called from src/SConscript. 465 def cxx_param_decl(cls, code): 466 # The 'local' attribute restricts us to the params declared in 467 # the object itself, not including inherited params (which 468 # will also be inherited from the base class's param struct 469 # here). 470 params = cls._params.local.values() 471 ports = cls._ports.local 472 try: 473 ptypes = [p.ptype for p in params] 474 except: 475 print cls, p, p.ptype_str 476 print params 477 raise 478 479 class_path = cls._value_dict['cxx_class'].split('::') 480 481 code('''\ 482#ifndef __PARAMS__${cls}__ 483#define __PARAMS__${cls}__ 484 485''') 486 487 # A forward class declaration is sufficient since we are just 488 # declaring a pointer. 489 for ns in class_path[:-1]: 490 code('namespace $ns {') 491 code('class $0;', class_path[-1]) 492 for ns in reversed(class_path[:-1]): 493 code('} // namespace $ns') 494 code() 495 496 # The base SimObject has a couple of params that get 497 # automatically set from Python without being declared through 498 # the normal Param mechanism; we slip them in here (needed 499 # predecls now, actual declarations below) 500 if cls == SimObject: 501 code(''' 502#ifndef PY_VERSION 503struct PyObject; 504#endif 505 506#include <string> 507 508class EventQueue; 509''') 510 for param in params: 511 param.cxx_predecls(code) 512 for port in ports.itervalues(): 513 port.cxx_predecls(code) 514 code() 515 516 if cls._base: 517 code('#include "params/${{cls._base.type}}.hh"') 518 code() 519 520 for ptype in ptypes: 521 if issubclass(ptype, Enum): 522 code('#include "enums/${{ptype.__name__}}.hh"') 523 code() 524 525 # now generate the actual param struct 526 code("struct ${cls}Params") 527 if cls._base: 528 code(" : public ${{cls._base.type}}Params") 529 code("{") 530 if not hasattr(cls, 'abstract') or not cls.abstract: 531 if 'type' in cls.__dict__: 532 code(" ${{cls.cxx_type}} create();") 533 534 code.indent() 535 if cls == SimObject: 536 code(''' 537 SimObjectParams() 538 { 539 extern EventQueue mainEventQueue; 540 eventq = &mainEventQueue; 541 } 542 virtual ~SimObjectParams() {} 543 544 std::string name; 545 PyObject *pyobj; 546 EventQueue *eventq; 547 ''') 548 for param in params: 549 param.cxx_decl(code) 550 for port in ports.itervalues(): 551 port.cxx_decl(code) 552 553 code.dedent() 554 code('};') 555 556 code() 557 code('#endif // __PARAMS__${cls}__') 558 return code 559 560 561 562# The SimObject class is the root of the special hierarchy. Most of 563# the code in this class deals with the configuration hierarchy itself 564# (parent/child node relationships). 565class SimObject(object): 566 # Specify metaclass. Any class inheriting from SimObject will 567 # get this metaclass. 568 __metaclass__ = MetaSimObject 569 type = 'SimObject' 570 abstract = True 571 572 @classmethod 573 def export_method_cxx_predecls(cls, code): 574 code(''' 575#include <Python.h> 576 577#include "sim/serialize.hh" 578#include "sim/sim_object.hh" 579''') 580 581 @classmethod 582 def export_method_swig_predecls(cls, code): 583 code(''' 584%include <std_string.i> 585''') 586 587 @classmethod 588 def export_methods(cls, code): 589 code(''' 590 enum State { 591 Running, 592 Draining, 593 Drained 594 }; 595 596 void init(); 597 void loadState(Checkpoint *cp); 598 void initState(); 599 void regStats(); 600 void resetStats(); 601 void startup(); 602 603 unsigned int drain(Event *drain_event); 604 void resume(); 605 void switchOut(); 606 void takeOverFrom(BaseCPU *cpu); 607''') 608 609 # Initialize new instance. For objects with SimObject-valued 610 # children, we need to recursively clone the classes represented 611 # by those param values as well in a consistent "deep copy"-style 612 # fashion. That is, we want to make sure that each instance is 613 # cloned only once, and that if there are multiple references to 614 # the same original object, we end up with the corresponding 615 # cloned references all pointing to the same cloned instance. 616 def __init__(self, **kwargs): 617 ancestor = kwargs.get('_ancestor') 618 memo_dict = kwargs.get('_memo') 619 if memo_dict is None: 620 # prepare to memoize any recursively instantiated objects 621 memo_dict = {} 622 elif ancestor: 623 # memoize me now to avoid problems with recursive calls 624 memo_dict[ancestor] = self 625 626 if not ancestor: 627 ancestor = self.__class__ 628 ancestor._instantiated = True 629 630 # initialize required attributes 631 self._parent = None 632 self._name = None 633 self._ccObject = None # pointer to C++ object 634 self._ccParams = None 635 self._instantiated = False # really "cloned" 636 637 # Clone children specified at class level. No need for a 638 # multidict here since we will be cloning everything. 639 # Do children before parameter values so that children that 640 # are also param values get cloned properly. 641 self._children = {} 642 for key,val in ancestor._children.iteritems(): 643 self.add_child(key, val(_memo=memo_dict)) 644 645 # Inherit parameter values from class using multidict so 646 # individual value settings can be overridden but we still 647 # inherit late changes to non-overridden class values. 648 self._values = multidict(ancestor._values) 649 # clone SimObject-valued parameters 650 for key,val in ancestor._values.iteritems(): 651 val = tryAsSimObjectOrVector(val) 652 if val is not None: 653 self._values[key] = val(_memo=memo_dict) 654 655 # clone port references. no need to use a multidict here 656 # since we will be creating new references for all ports. 657 self._port_refs = {} 658 for key,val in ancestor._port_refs.iteritems(): 659 self._port_refs[key] = val.clone(self, memo_dict) 660 # apply attribute assignments from keyword args, if any 661 for key,val in kwargs.iteritems(): 662 setattr(self, key, val) 663 664 # "Clone" the current instance by creating another instance of 665 # this instance's class, but that inherits its parameter values 666 # and port mappings from the current instance. If we're in a 667 # "deep copy" recursive clone, check the _memo dict to see if 668 # we've already cloned this instance. 669 def __call__(self, **kwargs): 670 memo_dict = kwargs.get('_memo') 671 if memo_dict is None: 672 # no memo_dict: must be top-level clone operation. 673 # this is only allowed at the root of a hierarchy 674 if self._parent: 675 raise RuntimeError, "attempt to clone object %s " \ 676 "not at the root of a tree (parent = %s)" \ 677 % (self, self._parent) 678 # create a new dict and use that. 679 memo_dict = {} 680 kwargs['_memo'] = memo_dict 681 elif memo_dict.has_key(self): 682 # clone already done & memoized 683 return memo_dict[self] 684 return self.__class__(_ancestor = self, **kwargs) 685 686 def _get_port_ref(self, attr): 687 # Return reference that can be assigned to another port 688 # via __setattr__. There is only ever one reference 689 # object per port, but we create them lazily here. 690 ref = self._port_refs.get(attr) 691 if not ref: 692 ref = self._ports[attr].makeRef(self) 693 self._port_refs[attr] = ref 694 return ref 695 696 def __getattr__(self, attr): 697 if self._ports.has_key(attr): 698 return self._get_port_ref(attr) 699 700 if self._values.has_key(attr): 701 return self._values[attr] 702 703 if self._children.has_key(attr): 704 return self._children[attr] 705 706 # If the attribute exists on the C++ object, transparently 707 # forward the reference there. This is typically used for 708 # SWIG-wrapped methods such as init(), regStats(), 709 # resetStats(), startup(), drain(), and 710 # resume(). 711 if self._ccObject and hasattr(self._ccObject, attr): 712 return getattr(self._ccObject, attr) 713 714 raise AttributeError, "object '%s' has no attribute '%s'" \ 715 % (self.__class__.__name__, attr) 716 717 # Set attribute (called on foo.attr = value when foo is an 718 # instance of class cls). 719 def __setattr__(self, attr, value): 720 # normal processing for private attributes 721 if attr.startswith('_'): 722 object.__setattr__(self, attr, value) 723 return 724 725 if self._ports.has_key(attr): 726 # set up port connection 727 self._get_port_ref(attr).connect(value) 728 return 729 730 if isSimObjectOrSequence(value) and self._instantiated: 731 raise RuntimeError, \ 732 "cannot set SimObject parameter '%s' after\n" \ 733 " instance been cloned %s" % (attr, `self`) 734 735 param = self._params.get(attr) 736 if param: 737 try: 738 value = param.convert(value) 739 except Exception, e: 740 msg = "%s\nError setting param %s.%s to %s\n" % \ 741 (e, self.__class__.__name__, attr, value) 742 e.args = (msg, ) 743 raise 744 self._values[attr] = value 745 # implicitly parent unparented objects assigned as params 746 if isSimObjectOrVector(value) and not value.has_parent(): 747 self.add_child(attr, value) 748 return 749 750 # if RHS is a SimObject, it's an implicit child assignment 751 if isSimObjectOrSequence(value): 752 self.add_child(attr, value) 753 return 754 755 # no valid assignment... raise exception 756 raise AttributeError, "Class %s has no parameter %s" \ 757 % (self.__class__.__name__, attr) 758 759 760 # this hack allows tacking a '[0]' onto parameters that may or may 761 # not be vectors, and always getting the first element (e.g. cpus) 762 def __getitem__(self, key): 763 if key == 0: 764 return self 765 raise TypeError, "Non-zero index '%s' to SimObject" % key 766 767 # Also implemented by SimObjectVector 768 def clear_parent(self, old_parent): 769 assert self._parent is old_parent 770 self._parent = None 771 772 # Also implemented by SimObjectVector 773 def set_parent(self, parent, name): 774 self._parent = parent 775 self._name = name 776 777 # Also implemented by SimObjectVector 778 def get_name(self): 779 return self._name 780 781 # Also implemented by SimObjectVector 782 def has_parent(self): 783 return self._parent is not None 784 785 # clear out child with given name. This code is not likely to be exercised. 786 # See comment in add_child. 787 def clear_child(self, name): 788 child = self._children[name] 789 child.clear_parent(self) 790 del self._children[name] 791 792 # Add a new child to this object. 793 def add_child(self, name, child): 794 child = coerceSimObjectOrVector(child) 795 if child.has_parent(): 796 print "warning: add_child('%s'): child '%s' already has parent" % \ 797 (name, child.get_name()) 798 if self._children.has_key(name): 799 # This code path had an undiscovered bug that would make it fail 800 # at runtime. It had been here for a long time and was only 801 # exposed by a buggy script. Changes here will probably not be 802 # exercised without specialized testing. 803 self.clear_child(name) 804 child.set_parent(self, name) 805 self._children[name] = child 806 807 # Take SimObject-valued parameters that haven't been explicitly 808 # assigned as children and make them children of the object that 809 # they were assigned to as a parameter value. This guarantees 810 # that when we instantiate all the parameter objects we're still 811 # inside the configuration hierarchy. 812 def adoptOrphanParams(self): 813 for key,val in self._values.iteritems(): 814 if not isSimObjectVector(val) and isSimObjectSequence(val): 815 # need to convert raw SimObject sequences to 816 # SimObjectVector class so we can call has_parent() 817 val = SimObjectVector(val) 818 self._values[key] = val 819 if isSimObjectOrVector(val) and not val.has_parent(): 820 print "warning: %s adopting orphan SimObject param '%s'" \ 821 % (self, key) 822 self.add_child(key, val) 823 824 def path(self): 825 if not self._parent: 826 return '<orphan %s>' % self.__class__ 827 ppath = self._parent.path() 828 if ppath == 'root': 829 return self._name 830 return ppath + "." + self._name 831 832 def __str__(self): 833 return self.path() 834 835 def ini_str(self): 836 return self.path() 837 838 def find_any(self, ptype): 839 if isinstance(self, ptype): 840 return self, True 841 842 found_obj = None 843 for child in self._children.itervalues(): 844 if isinstance(child, ptype): 845 if found_obj != None and child != found_obj: 846 raise AttributeError, \ 847 'parent.any matched more than one: %s %s' % \ 848 (found_obj.path, child.path) 849 found_obj = child 850 # search param space 851 for pname,pdesc in self._params.iteritems(): 852 if issubclass(pdesc.ptype, ptype): 853 match_obj = self._values[pname] 854 if found_obj != None and found_obj != match_obj: 855 raise AttributeError, \ 856 'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path) 857 found_obj = match_obj 858 return found_obj, found_obj != None 859 860 def find_all(self, ptype): 861 all = {} 862 # search children 863 for child in self._children.itervalues(): 864 if isinstance(child, ptype) and not isproxy(child) and \ 865 not isNullPointer(child): 866 all[child] = True 867 if isSimObject(child): 868 # also add results from the child itself 869 child_all, done = child.find_all(ptype) 870 all.update(dict(zip(child_all, [done] * len(child_all)))) 871 # search param space 872 for pname,pdesc in self._params.iteritems(): 873 if issubclass(pdesc.ptype, ptype): 874 match_obj = self._values[pname] 875 if not isproxy(match_obj) and not isNullPointer(match_obj): 876 all[match_obj] = True 877 return all.keys(), True 878 879 def unproxy(self, base): 880 return self 881 882 def unproxyParams(self): 883 for param in self._params.iterkeys(): 884 value = self._values.get(param) 885 if value != None and isproxy(value): 886 try: 887 value = value.unproxy(self) 888 except: 889 print "Error in unproxying param '%s' of %s" % \ 890 (param, self.path()) 891 raise 892 setattr(self, param, value) 893 894 # Unproxy ports in sorted order so that 'append' operations on 895 # vector ports are done in a deterministic fashion. 896 port_names = self._ports.keys() 897 port_names.sort() 898 for port_name in port_names: 899 port = self._port_refs.get(port_name) 900 if port != None: 901 port.unproxy(self) 902 903 def print_ini(self, ini_file): 904 print >>ini_file, '[' + self.path() + ']' # .ini section header 905 906 instanceDict[self.path()] = self 907 908 if hasattr(self, 'type'): 909 print >>ini_file, 'type=%s' % self.type 910 911 if len(self._children.keys()): 912 print >>ini_file, 'children=%s' % \ 913 ' '.join(self._children[n].get_name() \ 914 for n in sorted(self._children.keys())) 915 916 for param in sorted(self._params.keys()): 917 value = self._values.get(param) 918 if value != None: 919 print >>ini_file, '%s=%s' % (param, 920 self._values[param].ini_str()) 921 922 for port_name in sorted(self._ports.keys()): 923 port = self._port_refs.get(port_name, None) 924 if port != None: 925 print >>ini_file, '%s=%s' % (port_name, port.ini_str()) 926 927 print >>ini_file # blank line between objects 928 929 # generate a tree of dictionaries expressing all the parameters in the 930 # instantiated system for use by scripts that want to do power, thermal 931 # visualization, and other similar tasks 932 def get_config_as_dict(self): 933 d = attrdict() 934 if hasattr(self, 'type'): 935 d.type = self.type 936 if hasattr(self, 'cxx_class'): 937 d.cxx_class = self.cxx_class 938 # Add the name and path of this object to be able to link to 939 # the stats 940 d.name = self.get_name() 941 d.path = self.path() 942 943 for param in sorted(self._params.keys()): 944 value = self._values.get(param) 945 if value != None: 946 try: 947 # Use native type for those supported by JSON and 948 # strings for everything else. skipkeys=True seems 949 # to not work as well as one would hope 950 if type(self._values[param].value) in \ 951 [str, unicode, int, long, float, bool, None]: 952 d[param] = self._values[param].value 953 else: 954 d[param] = str(self._values[param]) 955 956 except AttributeError: 957 pass 958 959 for n in sorted(self._children.keys()): 960 child = self._children[n] 961 # Use the name of the attribute (and not get_name()) as 962 # the key in the JSON dictionary to capture the hierarchy 963 # in the Python code that assembled this system 964 d[n] = child.get_config_as_dict() 965 966 for port_name in sorted(self._ports.keys()): 967 port = self._port_refs.get(port_name, None) 968 if port != None: 969 # Represent each port with a dictionary containing the 970 # prominent attributes 971 d[port_name] = port.get_config_as_dict() 972 973 return d 974 975 def getCCParams(self): 976 if self._ccParams: 977 return self._ccParams 978 979 cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type) 980 cc_params = cc_params_struct() 981 cc_params.pyobj = self 982 cc_params.name = str(self) 983 984 param_names = self._params.keys() 985 param_names.sort() 986 for param in param_names: 987 value = self._values.get(param) 988 if value is None: 989 fatal("%s.%s without default or user set value", 990 self.path(), param) 991 992 value = value.getValue() 993 if isinstance(self._params[param], VectorParamDesc): 994 assert isinstance(value, list) 995 vec = getattr(cc_params, param) 996 assert not len(vec) 997 for v in value: 998 vec.append(v) 999 else: 1000 setattr(cc_params, param, value) 1001 1002 port_names = self._ports.keys() 1003 port_names.sort() 1004 for port_name in port_names: 1005 port = self._port_refs.get(port_name, None) 1006 if port != None: 1007 port_count = len(port) 1008 else: 1009 port_count = 0 1010 setattr(cc_params, 'port_' + port_name + '_connection_count', 1011 port_count) 1012 self._ccParams = cc_params 1013 return self._ccParams 1014 1015 # Get C++ object corresponding to this object, calling C++ if 1016 # necessary to construct it. Does *not* recursively create 1017 # children. 1018 def getCCObject(self): 1019 if not self._ccObject: 1020 # Make sure this object is in the configuration hierarchy 1021 if not self._parent and not isRoot(self): 1022 raise RuntimeError, "Attempt to instantiate orphan node" 1023 # Cycles in the configuration hierarchy are not supported. This 1024 # will catch the resulting recursion and stop. 1025 self._ccObject = -1 1026 params = self.getCCParams() 1027 self._ccObject = params.create() 1028 elif self._ccObject == -1: 1029 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \ 1030 % self.path() 1031 return self._ccObject 1032 1033 def descendants(self): 1034 yield self 1035 for child in self._children.itervalues(): 1036 for obj in child.descendants(): 1037 yield obj 1038 1039 # Call C++ to create C++ object corresponding to this object 1040 def createCCObject(self): 1041 self.getCCParams() 1042 self.getCCObject() # force creation 1043 1044 def getValue(self): 1045 return self.getCCObject() 1046 1047 # Create C++ port connections corresponding to the connections in 1048 # _port_refs 1049 def connectPorts(self): 1050 for portRef in self._port_refs.itervalues(): 1051 portRef.ccConnect() 1052 |
1053 def getMemoryMode(self): 1054 if not isinstance(self, m5.objects.System): 1055 return None 1056 1057 return self._ccObject.getMemoryMode() 1058 1059 def changeTiming(self, mode): 1060 if isinstance(self, m5.objects.System): 1061 # i don't know if there's a better way to do this - calling 1062 # setMemoryMode directly from self._ccObject results in calling 1063 # SimObject::setMemoryMode, not the System::setMemoryMode 1064 self._ccObject.setMemoryMode(mode) 1065 | |
1066 def takeOverFrom(self, old_cpu): 1067 self._ccObject.takeOverFrom(old_cpu._ccObject) 1068 1069# Function to provide to C++ so it can look up instances based on paths 1070def resolveSimObject(name): 1071 obj = instanceDict[name] 1072 return obj.getCCObject() 1073 1074def isSimObject(value): 1075 return isinstance(value, SimObject) 1076 1077def isSimObjectClass(value): 1078 return issubclass(value, SimObject) 1079 1080def isSimObjectVector(value): 1081 return isinstance(value, SimObjectVector) 1082 1083def isSimObjectSequence(value): 1084 if not isinstance(value, (list, tuple)) or len(value) == 0: 1085 return False 1086 1087 for val in value: 1088 if not isNullPointer(val) and not isSimObject(val): 1089 return False 1090 1091 return True 1092 1093def isSimObjectOrSequence(value): 1094 return isSimObject(value) or isSimObjectSequence(value) 1095 1096def isRoot(obj): 1097 from m5.objects import Root 1098 return obj and obj is Root.getInstance() 1099 1100def isSimObjectOrVector(value): 1101 return isSimObject(value) or isSimObjectVector(value) 1102 1103def tryAsSimObjectOrVector(value): 1104 if isSimObjectOrVector(value): 1105 return value 1106 if isSimObjectSequence(value): 1107 return SimObjectVector(value) 1108 return None 1109 1110def coerceSimObjectOrVector(value): 1111 value = tryAsSimObjectOrVector(value) 1112 if value is None: 1113 raise TypeError, "SimObject or SimObjectVector expected" 1114 return value 1115 1116baseClasses = allClasses.copy() 1117baseInstances = instanceDict.copy() 1118 1119def clear(): 1120 global allClasses, instanceDict 1121 1122 allClasses = baseClasses.copy() 1123 instanceDict = baseInstances.copy() 1124 1125# __all__ defines the list of symbols that get exported when 1126# 'from config import *' is invoked. Try to keep this reasonably 1127# short to avoid polluting other namespaces. 1128__all__ = [ 'SimObject' ] | 1053 def takeOverFrom(self, old_cpu): 1054 self._ccObject.takeOverFrom(old_cpu._ccObject) 1055 1056# Function to provide to C++ so it can look up instances based on paths 1057def resolveSimObject(name): 1058 obj = instanceDict[name] 1059 return obj.getCCObject() 1060 1061def isSimObject(value): 1062 return isinstance(value, SimObject) 1063 1064def isSimObjectClass(value): 1065 return issubclass(value, SimObject) 1066 1067def isSimObjectVector(value): 1068 return isinstance(value, SimObjectVector) 1069 1070def isSimObjectSequence(value): 1071 if not isinstance(value, (list, tuple)) or len(value) == 0: 1072 return False 1073 1074 for val in value: 1075 if not isNullPointer(val) and not isSimObject(val): 1076 return False 1077 1078 return True 1079 1080def isSimObjectOrSequence(value): 1081 return isSimObject(value) or isSimObjectSequence(value) 1082 1083def isRoot(obj): 1084 from m5.objects import Root 1085 return obj and obj is Root.getInstance() 1086 1087def isSimObjectOrVector(value): 1088 return isSimObject(value) or isSimObjectVector(value) 1089 1090def tryAsSimObjectOrVector(value): 1091 if isSimObjectOrVector(value): 1092 return value 1093 if isSimObjectSequence(value): 1094 return SimObjectVector(value) 1095 return None 1096 1097def coerceSimObjectOrVector(value): 1098 value = tryAsSimObjectOrVector(value) 1099 if value is None: 1100 raise TypeError, "SimObject or SimObjectVector expected" 1101 return value 1102 1103baseClasses = allClasses.copy() 1104baseInstances = instanceDict.copy() 1105 1106def clear(): 1107 global allClasses, instanceDict 1108 1109 allClasses = baseClasses.copy() 1110 instanceDict = baseInstances.copy() 1111 1112# __all__ defines the list of symbols that get exported when 1113# 'from config import *' is invoked. Try to keep this reasonably 1114# short to avoid polluting other namespaces. 1115__all__ = [ 'SimObject' ] |