SimObject.py revision 7493
12740SN/A# Copyright (c) 2004-2006 The Regents of The University of Michigan 21046SN/A# All rights reserved. 31046SN/A# 41046SN/A# Redistribution and use in source and binary forms, with or without 51046SN/A# modification, are permitted provided that the following conditions are 61046SN/A# met: redistributions of source code must retain the above copyright 71046SN/A# notice, this list of conditions and the following disclaimer; 81046SN/A# redistributions in binary form must reproduce the above copyright 91046SN/A# notice, this list of conditions and the following disclaimer in the 101046SN/A# documentation and/or other materials provided with the distribution; 111046SN/A# neither the name of the copyright holders nor the names of its 121046SN/A# contributors may be used to endorse or promote products derived from 131046SN/A# this software without specific prior written permission. 141046SN/A# 151046SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 161046SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 171046SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 181046SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 191046SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 201046SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 211046SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 221046SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 231046SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 241046SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 251046SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 262665SN/A# 272665SN/A# Authors: Steve Reinhardt 282665SN/A# Nathan Binkert 291046SN/A 305766Snate@binkert.orgimport math 315766Snate@binkert.orgimport sys 327493Ssteve.reinhardt@amd.comfrom types import FunctionType 331438SN/A 346654Snate@binkert.orgtry: 356654Snate@binkert.org import pydot 366654Snate@binkert.orgexcept: 376654Snate@binkert.org pydot = False 386654Snate@binkert.org 394762Snate@binkert.orgimport m5 406654Snate@binkert.orgfrom m5.util import * 413102Sstever@eecs.umich.edu 423102Sstever@eecs.umich.edu# Have to import params up top since Param is referenced on initial 433102Sstever@eecs.umich.edu# load (when SimObject class references Param to create a class 443102Sstever@eecs.umich.edu# variable, the 'name' param)... 456654Snate@binkert.orgfrom m5.params import * 463102Sstever@eecs.umich.edu# There are a few things we need that aren't in params.__all__ since 473102Sstever@eecs.umich.edu# normal users don't need them 486654Snate@binkert.orgfrom m5.params import ParamDesc, VectorParamDesc, isNullPointer, SimObjVector 493102Sstever@eecs.umich.edu 506654Snate@binkert.orgfrom m5.proxy import * 516654Snate@binkert.orgfrom m5.proxy import isproxy 52679SN/A 53679SN/A##################################################################### 54679SN/A# 55679SN/A# M5 Python Configuration Utility 56679SN/A# 57679SN/A# The basic idea is to write simple Python programs that build Python 581692SN/A# objects corresponding to M5 SimObjects for the desired simulation 59679SN/A# configuration. For now, the Python emits a .ini file that can be 60679SN/A# parsed by M5. In the future, some tighter integration between M5 61679SN/A# and the Python interpreter may allow bypassing the .ini file. 62679SN/A# 63679SN/A# Each SimObject class in M5 is represented by a Python class with the 64679SN/A# same name. The Python inheritance tree mirrors the M5 C++ tree 65679SN/A# (e.g., SimpleCPU derives from BaseCPU in both cases, and all 66679SN/A# SimObjects inherit from a single SimObject base class). To specify 67679SN/A# an instance of an M5 SimObject in a configuration, the user simply 68679SN/A# instantiates the corresponding Python object. The parameters for 69679SN/A# that SimObject are given by assigning to attributes of the Python 70679SN/A# object, either using keyword assignment in the constructor or in 71679SN/A# separate assignment statements. For example: 72679SN/A# 731692SN/A# cache = BaseCache(size='64KB') 74679SN/A# cache.hit_latency = 3 75679SN/A# cache.assoc = 8 76679SN/A# 77679SN/A# The magic lies in the mapping of the Python attributes for SimObject 78679SN/A# classes to the actual SimObject parameter specifications. This 79679SN/A# allows parameter validity checking in the Python code. Continuing 80679SN/A# the example above, the statements "cache.blurfl=3" or 81679SN/A# "cache.assoc='hello'" would both result in runtime errors in Python, 82679SN/A# since the BaseCache object has no 'blurfl' parameter and the 'assoc' 83679SN/A# parameter requires an integer, respectively. This magic is done 84679SN/A# primarily by overriding the special __setattr__ method that controls 85679SN/A# assignment to object attributes. 86679SN/A# 87679SN/A# Once a set of Python objects have been instantiated in a hierarchy, 88679SN/A# calling 'instantiate(obj)' (where obj is the root of the hierarchy) 892740SN/A# will generate a .ini file. 90679SN/A# 91679SN/A##################################################################### 92679SN/A 934762Snate@binkert.org# list of all SimObject classes 944762Snate@binkert.orgallClasses = {} 954762Snate@binkert.org 962738SN/A# dict to look up SimObjects based on path 972738SN/AinstanceDict = {} 982738SN/A 992740SN/A# The metaclass for SimObject. This class controls how new classes 1002740SN/A# that derive from SimObject are instantiated, and provides inherited 1012740SN/A# class behavior (just like a class controls how instances of that 1022740SN/A# class are instantiated, and provides inherited instance behavior). 1031692SN/Aclass MetaSimObject(type): 1041427SN/A # Attributes that can be set only at initialization time 1057493Ssteve.reinhardt@amd.com init_keywords = { 'abstract' : bool, 1067493Ssteve.reinhardt@amd.com 'cxx_class' : str, 1077493Ssteve.reinhardt@amd.com 'cxx_type' : str, 1087493Ssteve.reinhardt@amd.com 'cxx_predecls' : list, 1097493Ssteve.reinhardt@amd.com 'swig_objdecls' : list, 1107493Ssteve.reinhardt@amd.com 'swig_predecls' : list, 1117493Ssteve.reinhardt@amd.com 'type' : str } 1121427SN/A # Attributes that can be set any time 1137493Ssteve.reinhardt@amd.com keywords = { 'check' : FunctionType } 114679SN/A 115679SN/A # __new__ is called before __init__, and is where the statements 116679SN/A # in the body of the class definition get loaded into the class's 1172740SN/A # __dict__. We intercept this to filter out parameter & port assignments 118679SN/A # and only allow "private" attributes to be passed to the base 119679SN/A # __new__ (starting with underscore). 1201310SN/A def __new__(mcls, name, bases, dict): 1216654Snate@binkert.org assert name not in allClasses, "SimObject %s already present" % name 1224762Snate@binkert.org 1232740SN/A # Copy "private" attributes, functions, and classes to the 1242740SN/A # official dict. Everything else goes in _init_dict to be 1252740SN/A # filtered in __init__. 1262740SN/A cls_dict = {} 1272740SN/A value_dict = {} 1282740SN/A for key,val in dict.items(): 1297493Ssteve.reinhardt@amd.com if key.startswith('_') or isinstance(val, (FunctionType, 1307493Ssteve.reinhardt@amd.com classmethod, 1317493Ssteve.reinhardt@amd.com type)): 1322740SN/A cls_dict[key] = val 1332740SN/A else: 1342740SN/A # must be a param/port setting 1352740SN/A value_dict[key] = val 1364762Snate@binkert.org if 'abstract' not in value_dict: 1374762Snate@binkert.org value_dict['abstract'] = False 1382740SN/A cls_dict['_value_dict'] = value_dict 1394762Snate@binkert.org cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict) 1404762Snate@binkert.org if 'type' in value_dict: 1414762Snate@binkert.org allClasses[name] = cls 1424762Snate@binkert.org return cls 143679SN/A 1442711SN/A # subclass initialization 145679SN/A def __init__(cls, name, bases, dict): 1462711SN/A # calls type.__init__()... I think that's a no-op, but leave 1472711SN/A # it here just in case it's not. 1481692SN/A super(MetaSimObject, cls).__init__(name, bases, dict) 1491310SN/A 1501427SN/A # initialize required attributes 1512740SN/A 1522740SN/A # class-only attributes 1532740SN/A cls._params = multidict() # param descriptions 1542740SN/A cls._ports = multidict() # port descriptions 1552740SN/A 1562740SN/A # class or instance attributes 1572740SN/A cls._values = multidict() # param values 1583105Sstever@eecs.umich.edu cls._port_refs = multidict() # port ref objects 1592740SN/A cls._instantiated = False # really instantiated, cloned, or subclassed 1601310SN/A 1611692SN/A # We don't support multiple inheritance. If you want to, you 1621585SN/A # must fix multidict to deal with it properly. 1631692SN/A if len(bases) > 1: 1641692SN/A raise TypeError, "SimObjects do not support multiple inheritance" 1651692SN/A 1661692SN/A base = bases[0] 1671692SN/A 1682740SN/A # Set up general inheritance via multidicts. A subclass will 1692740SN/A # inherit all its settings from the base class. The only time 1702740SN/A # the following is not true is when we define the SimObject 1712740SN/A # class itself (in which case the multidicts have no parent). 1721692SN/A if isinstance(base, MetaSimObject): 1735610Snate@binkert.org cls._base = base 1741692SN/A cls._params.parent = base._params 1752740SN/A cls._ports.parent = base._ports 1761692SN/A cls._values.parent = base._values 1773105Sstever@eecs.umich.edu cls._port_refs.parent = base._port_refs 1782740SN/A # mark base as having been subclassed 1792712SN/A base._instantiated = True 1805610Snate@binkert.org else: 1815610Snate@binkert.org cls._base = None 1821692SN/A 1834762Snate@binkert.org # default keyword values 1844762Snate@binkert.org if 'type' in cls._value_dict: 1854762Snate@binkert.org if 'cxx_class' not in cls._value_dict: 1865610Snate@binkert.org cls._value_dict['cxx_class'] = cls._value_dict['type'] 1874762Snate@binkert.org 1885610Snate@binkert.org cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class'] 1895610Snate@binkert.org 1904762Snate@binkert.org if 'cxx_predecls' not in cls._value_dict: 1914762Snate@binkert.org # A forward class declaration is sufficient since we are 1924762Snate@binkert.org # just declaring a pointer. 1935610Snate@binkert.org class_path = cls._value_dict['cxx_class'].split('::') 1945610Snate@binkert.org class_path.reverse() 1955610Snate@binkert.org decl = 'class %s;' % class_path[0] 1965610Snate@binkert.org for ns in class_path[1:]: 1975610Snate@binkert.org decl = 'namespace %s { %s }' % (ns, decl) 1984762Snate@binkert.org cls._value_dict['cxx_predecls'] = [decl] 1994762Snate@binkert.org 2004762Snate@binkert.org if 'swig_predecls' not in cls._value_dict: 2014762Snate@binkert.org # A forward class declaration is sufficient since we are 2024762Snate@binkert.org # just declaring a pointer. 2034762Snate@binkert.org cls._value_dict['swig_predecls'] = \ 2044762Snate@binkert.org cls._value_dict['cxx_predecls'] 2054762Snate@binkert.org 2064859Snate@binkert.org if 'swig_objdecls' not in cls._value_dict: 2074859Snate@binkert.org cls._value_dict['swig_objdecls'] = [] 2084859Snate@binkert.org 2092740SN/A # Now process the _value_dict items. They could be defining 2102740SN/A # new (or overriding existing) parameters or ports, setting 2112740SN/A # class keywords (e.g., 'abstract'), or setting parameter 2122740SN/A # values or port bindings. The first 3 can only be set when 2132740SN/A # the class is defined, so we handle them here. The others 2142740SN/A # can be set later too, so just emulate that by calling 2152740SN/A # setattr(). 2162740SN/A for key,val in cls._value_dict.items(): 2171527SN/A # param descriptions 2182740SN/A if isinstance(val, ParamDesc): 2191585SN/A cls._new_param(key, val) 2201427SN/A 2212738SN/A # port objects 2222738SN/A elif isinstance(val, Port): 2233105Sstever@eecs.umich.edu cls._new_port(key, val) 2242738SN/A 2251427SN/A # init-time-only keywords 2261427SN/A elif cls.init_keywords.has_key(key): 2271427SN/A cls._set_keyword(key, val, cls.init_keywords[key]) 2281427SN/A 2291427SN/A # default: use normal path (ends up in __setattr__) 2301427SN/A else: 2311427SN/A setattr(cls, key, val) 2321427SN/A 2331427SN/A def _set_keyword(cls, keyword, val, kwtype): 2341427SN/A if not isinstance(val, kwtype): 2351427SN/A raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \ 2361427SN/A (keyword, type(val), kwtype) 2377493Ssteve.reinhardt@amd.com if isinstance(val, FunctionType): 2381427SN/A val = classmethod(val) 2391427SN/A type.__setattr__(cls, keyword, val) 2401427SN/A 2413100SN/A def _new_param(cls, name, pdesc): 2423100SN/A # each param desc should be uniquely assigned to one variable 2433100SN/A assert(not hasattr(pdesc, 'name')) 2443100SN/A pdesc.name = name 2453100SN/A cls._params[name] = pdesc 2463100SN/A if hasattr(pdesc, 'default'): 2473105Sstever@eecs.umich.edu cls._set_param(name, pdesc.default, pdesc) 2483105Sstever@eecs.umich.edu 2493105Sstever@eecs.umich.edu def _set_param(cls, name, value, param): 2503105Sstever@eecs.umich.edu assert(param.name == name) 2513105Sstever@eecs.umich.edu try: 2523105Sstever@eecs.umich.edu cls._values[name] = param.convert(value) 2533105Sstever@eecs.umich.edu except Exception, e: 2543105Sstever@eecs.umich.edu msg = "%s\nError setting param %s.%s to %s\n" % \ 2553105Sstever@eecs.umich.edu (e, cls.__name__, name, value) 2563105Sstever@eecs.umich.edu e.args = (msg, ) 2573105Sstever@eecs.umich.edu raise 2583105Sstever@eecs.umich.edu 2593105Sstever@eecs.umich.edu def _new_port(cls, name, port): 2603105Sstever@eecs.umich.edu # each port should be uniquely assigned to one variable 2613105Sstever@eecs.umich.edu assert(not hasattr(port, 'name')) 2623105Sstever@eecs.umich.edu port.name = name 2633105Sstever@eecs.umich.edu cls._ports[name] = port 2643105Sstever@eecs.umich.edu if hasattr(port, 'default'): 2653105Sstever@eecs.umich.edu cls._cls_get_port_ref(name).connect(port.default) 2663105Sstever@eecs.umich.edu 2673105Sstever@eecs.umich.edu # same as _get_port_ref, effectively, but for classes 2683105Sstever@eecs.umich.edu def _cls_get_port_ref(cls, attr): 2693105Sstever@eecs.umich.edu # Return reference that can be assigned to another port 2703105Sstever@eecs.umich.edu # via __setattr__. There is only ever one reference 2713105Sstever@eecs.umich.edu # object per port, but we create them lazily here. 2723105Sstever@eecs.umich.edu ref = cls._port_refs.get(attr) 2733105Sstever@eecs.umich.edu if not ref: 2743105Sstever@eecs.umich.edu ref = cls._ports[attr].makeRef(cls) 2753105Sstever@eecs.umich.edu cls._port_refs[attr] = ref 2763105Sstever@eecs.umich.edu return ref 2771585SN/A 2781310SN/A # Set attribute (called on foo.attr = value when foo is an 2791310SN/A # instance of class cls). 2801310SN/A def __setattr__(cls, attr, value): 2811310SN/A # normal processing for private attributes 2821310SN/A if attr.startswith('_'): 2831310SN/A type.__setattr__(cls, attr, value) 2841310SN/A return 2851310SN/A 2861310SN/A if cls.keywords.has_key(attr): 2871427SN/A cls._set_keyword(attr, value, cls.keywords[attr]) 2881310SN/A return 2891310SN/A 2902738SN/A if cls._ports.has_key(attr): 2913105Sstever@eecs.umich.edu cls._cls_get_port_ref(attr).connect(value) 2922738SN/A return 2932738SN/A 2942740SN/A if isSimObjectOrSequence(value) and cls._instantiated: 2952740SN/A raise RuntimeError, \ 2962740SN/A "cannot set SimObject parameter '%s' after\n" \ 2972740SN/A " class %s has been instantiated or subclassed" \ 2982740SN/A % (attr, cls.__name__) 2992740SN/A 3002740SN/A # check for param 3013105Sstever@eecs.umich.edu param = cls._params.get(attr) 3021310SN/A if param: 3033105Sstever@eecs.umich.edu cls._set_param(attr, value, param) 3043105Sstever@eecs.umich.edu return 3053105Sstever@eecs.umich.edu 3063105Sstever@eecs.umich.edu if isSimObjectOrSequence(value): 3073105Sstever@eecs.umich.edu # If RHS is a SimObject, it's an implicit child assignment. 3083105Sstever@eecs.umich.edu # Classes don't have children, so we just put this object 3093105Sstever@eecs.umich.edu # in _values; later, each instance will do a 'setattr(self, 3103105Sstever@eecs.umich.edu # attr, _values[attr])' in SimObject.__init__ which will 3113105Sstever@eecs.umich.edu # add this object as a child. 3122740SN/A cls._values[attr] = value 3133105Sstever@eecs.umich.edu return 3143105Sstever@eecs.umich.edu 3153105Sstever@eecs.umich.edu # no valid assignment... raise exception 3163105Sstever@eecs.umich.edu raise AttributeError, \ 3173105Sstever@eecs.umich.edu "Class %s has no parameter \'%s\'" % (cls.__name__, attr) 3181310SN/A 3191585SN/A def __getattr__(cls, attr): 3201692SN/A if cls._values.has_key(attr): 3211692SN/A return cls._values[attr] 3221585SN/A 3231585SN/A raise AttributeError, \ 3241585SN/A "object '%s' has no attribute '%s'" % (cls.__name__, attr) 3251585SN/A 3263100SN/A def __str__(cls): 3273100SN/A return cls.__name__ 3283100SN/A 3293100SN/A def cxx_decl(cls): 3304762Snate@binkert.org code = "#ifndef __PARAMS__%s\n" % cls 3314762Snate@binkert.org code += "#define __PARAMS__%s\n\n" % cls 3324762Snate@binkert.org 3333100SN/A # The 'dict' attribute restricts us to the params declared in 3343100SN/A # the object itself, not including inherited params (which 3353100SN/A # will also be inherited from the base class's param struct 3363100SN/A # here). 3374762Snate@binkert.org params = cls._params.local.values() 3383100SN/A try: 3393100SN/A ptypes = [p.ptype for p in params] 3403100SN/A except: 3413100SN/A print cls, p, p.ptype_str 3423100SN/A print params 3433100SN/A raise 3443100SN/A 3453100SN/A # get a list of lists of predeclaration lines 3464762Snate@binkert.org predecls = [] 3474762Snate@binkert.org predecls.extend(cls.cxx_predecls) 3484762Snate@binkert.org for p in params: 3494762Snate@binkert.org predecls.extend(p.cxx_predecls()) 3504762Snate@binkert.org # remove redundant lines 3514762Snate@binkert.org predecls2 = [] 3524762Snate@binkert.org for pd in predecls: 3534762Snate@binkert.org if pd not in predecls2: 3544762Snate@binkert.org predecls2.append(pd) 3554762Snate@binkert.org predecls2.sort() 3564762Snate@binkert.org code += "\n".join(predecls2) 3574762Snate@binkert.org code += "\n\n"; 3584762Snate@binkert.org 3595610Snate@binkert.org if cls._base: 3605610Snate@binkert.org code += '#include "params/%s.hh"\n\n' % cls._base.type 3614762Snate@binkert.org 3624762Snate@binkert.org for ptype in ptypes: 3634762Snate@binkert.org if issubclass(ptype, Enum): 3644762Snate@binkert.org code += '#include "enums/%s.hh"\n' % ptype.__name__ 3654762Snate@binkert.org code += "\n\n" 3664762Snate@binkert.org 3675610Snate@binkert.org code += cls.cxx_struct(cls._base, params) 3685488Snate@binkert.org 3695488Snate@binkert.org # close #ifndef __PARAMS__* guard 3705488Snate@binkert.org code += "\n#endif\n" 3715488Snate@binkert.org return code 3725488Snate@binkert.org 3735488Snate@binkert.org def cxx_struct(cls, base, params): 3745488Snate@binkert.org if cls == SimObject: 3755488Snate@binkert.org return '#include "sim/sim_object_params.hh"\n' 3765488Snate@binkert.org 3774762Snate@binkert.org # now generate the actual param struct 3785488Snate@binkert.org code = "struct %sParams" % cls 3794762Snate@binkert.org if base: 3805610Snate@binkert.org code += " : public %sParams" % base.type 3814762Snate@binkert.org code += "\n{\n" 3824762Snate@binkert.org if not hasattr(cls, 'abstract') or not cls.abstract: 3834762Snate@binkert.org if 'type' in cls.__dict__: 3844762Snate@binkert.org code += " %s create();\n" % cls.cxx_type 3854762Snate@binkert.org decls = [p.cxx_decl() for p in params] 3864762Snate@binkert.org decls.sort() 3874762Snate@binkert.org code += "".join([" %s\n" % d for d in decls]) 3884762Snate@binkert.org code += "};\n" 3894762Snate@binkert.org 3904762Snate@binkert.org return code 3914762Snate@binkert.org 3924762Snate@binkert.org def swig_decl(cls): 3934762Snate@binkert.org code = '%%module %s\n' % cls 3944762Snate@binkert.org 3954762Snate@binkert.org code += '%{\n' 3964762Snate@binkert.org code += '#include "params/%s.hh"\n' % cls 3974762Snate@binkert.org code += '%}\n\n' 3984762Snate@binkert.org 3994762Snate@binkert.org # The 'dict' attribute restricts us to the params declared in 4004762Snate@binkert.org # the object itself, not including inherited params (which 4014762Snate@binkert.org # will also be inherited from the base class's param struct 4024762Snate@binkert.org # here). 4034762Snate@binkert.org params = cls._params.local.values() 4044762Snate@binkert.org ptypes = [p.ptype for p in params] 4054762Snate@binkert.org 4064762Snate@binkert.org # get a list of lists of predeclaration lines 4074762Snate@binkert.org predecls = [] 4084762Snate@binkert.org predecls.extend([ p.swig_predecls() for p in params ]) 4093100SN/A # flatten 4103100SN/A predecls = reduce(lambda x,y:x+y, predecls, []) 4113100SN/A # remove redundant lines 4123100SN/A predecls2 = [] 4133100SN/A for pd in predecls: 4143100SN/A if pd not in predecls2: 4153100SN/A predecls2.append(pd) 4163100SN/A predecls2.sort() 4173100SN/A code += "\n".join(predecls2) 4183100SN/A code += "\n\n"; 4193100SN/A 4205610Snate@binkert.org if cls._base: 4215610Snate@binkert.org code += '%%import "params/%s.i"\n\n' % cls._base.type 4223100SN/A 4234762Snate@binkert.org for ptype in ptypes: 4244762Snate@binkert.org if issubclass(ptype, Enum): 4254762Snate@binkert.org code += '%%import "enums/%s.hh"\n' % ptype.__name__ 4264762Snate@binkert.org code += "\n\n" 4273100SN/A 4284762Snate@binkert.org code += '%%import "params/%s_type.hh"\n\n' % cls 4293100SN/A code += '%%include "params/%s.hh"\n\n' % cls 4303100SN/A 4313100SN/A return code 4323100SN/A 4332740SN/A# The SimObject class is the root of the special hierarchy. Most of 434679SN/A# the code in this class deals with the configuration hierarchy itself 435679SN/A# (parent/child node relationships). 4361692SN/Aclass SimObject(object): 4371692SN/A # Specify metaclass. Any class inheriting from SimObject will 438679SN/A # get this metaclass. 4391692SN/A __metaclass__ = MetaSimObject 4403100SN/A type = 'SimObject' 4414762Snate@binkert.org abstract = True 4423100SN/A 4434859Snate@binkert.org swig_objdecls = [ '%include "python/swig/sim_object.i"' ] 444679SN/A 4452740SN/A # Initialize new instance. For objects with SimObject-valued 4462740SN/A # children, we need to recursively clone the classes represented 4472740SN/A # by those param values as well in a consistent "deep copy"-style 4482740SN/A # fashion. That is, we want to make sure that each instance is 4492740SN/A # cloned only once, and that if there are multiple references to 4502740SN/A # the same original object, we end up with the corresponding 4512740SN/A # cloned references all pointing to the same cloned instance. 4522740SN/A def __init__(self, **kwargs): 4532740SN/A ancestor = kwargs.get('_ancestor') 4542740SN/A memo_dict = kwargs.get('_memo') 4552740SN/A if memo_dict is None: 4562740SN/A # prepare to memoize any recursively instantiated objects 4572740SN/A memo_dict = {} 4582740SN/A elif ancestor: 4592740SN/A # memoize me now to avoid problems with recursive calls 4602740SN/A memo_dict[ancestor] = self 4612711SN/A 4622740SN/A if not ancestor: 4632740SN/A ancestor = self.__class__ 4642740SN/A ancestor._instantiated = True 4652711SN/A 4662740SN/A # initialize required attributes 4672740SN/A self._parent = None 4682740SN/A self._children = {} 4692740SN/A self._ccObject = None # pointer to C++ object 4704762Snate@binkert.org self._ccParams = None 4712740SN/A self._instantiated = False # really "cloned" 4722712SN/A 4732711SN/A # Inherit parameter values from class using multidict so 4742711SN/A # individual value settings can be overridden. 4752740SN/A self._values = multidict(ancestor._values) 4762740SN/A # clone SimObject-valued parameters 4772740SN/A for key,val in ancestor._values.iteritems(): 4782740SN/A if isSimObject(val): 4792740SN/A setattr(self, key, val(_memo=memo_dict)) 4802740SN/A elif isSimObjectSequence(val) and len(val): 4812740SN/A setattr(self, key, [ v(_memo=memo_dict) for v in val ]) 4822740SN/A # clone port references. no need to use a multidict here 4832740SN/A # since we will be creating new references for all ports. 4843105Sstever@eecs.umich.edu self._port_refs = {} 4853105Sstever@eecs.umich.edu for key,val in ancestor._port_refs.iteritems(): 4863105Sstever@eecs.umich.edu self._port_refs[key] = val.clone(self, memo_dict) 4871692SN/A # apply attribute assignments from keyword args, if any 4881692SN/A for key,val in kwargs.iteritems(): 4891692SN/A setattr(self, key, val) 490679SN/A 4912740SN/A # "Clone" the current instance by creating another instance of 4922740SN/A # this instance's class, but that inherits its parameter values 4932740SN/A # and port mappings from the current instance. If we're in a 4942740SN/A # "deep copy" recursive clone, check the _memo dict to see if 4952740SN/A # we've already cloned this instance. 4961692SN/A def __call__(self, **kwargs): 4972740SN/A memo_dict = kwargs.get('_memo') 4982740SN/A if memo_dict is None: 4992740SN/A # no memo_dict: must be top-level clone operation. 5002740SN/A # this is only allowed at the root of a hierarchy 5012740SN/A if self._parent: 5022740SN/A raise RuntimeError, "attempt to clone object %s " \ 5032740SN/A "not at the root of a tree (parent = %s)" \ 5042740SN/A % (self, self._parent) 5052740SN/A # create a new dict and use that. 5062740SN/A memo_dict = {} 5072740SN/A kwargs['_memo'] = memo_dict 5082740SN/A elif memo_dict.has_key(self): 5092740SN/A # clone already done & memoized 5102740SN/A return memo_dict[self] 5112740SN/A return self.__class__(_ancestor = self, **kwargs) 5121343SN/A 5133105Sstever@eecs.umich.edu def _get_port_ref(self, attr): 5143105Sstever@eecs.umich.edu # Return reference that can be assigned to another port 5153105Sstever@eecs.umich.edu # via __setattr__. There is only ever one reference 5163105Sstever@eecs.umich.edu # object per port, but we create them lazily here. 5173105Sstever@eecs.umich.edu ref = self._port_refs.get(attr) 5183105Sstever@eecs.umich.edu if not ref: 5193105Sstever@eecs.umich.edu ref = self._ports[attr].makeRef(self) 5203105Sstever@eecs.umich.edu self._port_refs[attr] = ref 5213105Sstever@eecs.umich.edu return ref 5223105Sstever@eecs.umich.edu 5231692SN/A def __getattr__(self, attr): 5242738SN/A if self._ports.has_key(attr): 5253105Sstever@eecs.umich.edu return self._get_port_ref(attr) 5262738SN/A 5271692SN/A if self._values.has_key(attr): 5281692SN/A return self._values[attr] 5291427SN/A 5301692SN/A raise AttributeError, "object '%s' has no attribute '%s'" \ 5311692SN/A % (self.__class__.__name__, attr) 5321427SN/A 5331692SN/A # Set attribute (called on foo.attr = value when foo is an 5341692SN/A # instance of class cls). 5351692SN/A def __setattr__(self, attr, value): 5361692SN/A # normal processing for private attributes 5371692SN/A if attr.startswith('_'): 5381692SN/A object.__setattr__(self, attr, value) 5391692SN/A return 5401427SN/A 5412738SN/A if self._ports.has_key(attr): 5422738SN/A # set up port connection 5433105Sstever@eecs.umich.edu self._get_port_ref(attr).connect(value) 5442738SN/A return 5452738SN/A 5462740SN/A if isSimObjectOrSequence(value) and self._instantiated: 5472740SN/A raise RuntimeError, \ 5482740SN/A "cannot set SimObject parameter '%s' after\n" \ 5492740SN/A " instance been cloned %s" % (attr, `self`) 5502740SN/A 5511692SN/A # must be SimObject param 5523105Sstever@eecs.umich.edu param = self._params.get(attr) 5531692SN/A if param: 5541310SN/A try: 5551692SN/A value = param.convert(value) 5561587SN/A except Exception, e: 5571692SN/A msg = "%s\nError setting param %s.%s to %s\n" % \ 5581692SN/A (e, self.__class__.__name__, attr, value) 5591605SN/A e.args = (msg, ) 5601605SN/A raise 5613105Sstever@eecs.umich.edu self._set_child(attr, value) 5623105Sstever@eecs.umich.edu return 5631310SN/A 5643105Sstever@eecs.umich.edu if isSimObjectOrSequence(value): 5653105Sstever@eecs.umich.edu self._set_child(attr, value) 5663105Sstever@eecs.umich.edu return 5671693SN/A 5683105Sstever@eecs.umich.edu # no valid assignment... raise exception 5693105Sstever@eecs.umich.edu raise AttributeError, "Class %s has no parameter %s" \ 5703105Sstever@eecs.umich.edu % (self.__class__.__name__, attr) 5711310SN/A 5721310SN/A 5731692SN/A # this hack allows tacking a '[0]' onto parameters that may or may 5741692SN/A # not be vectors, and always getting the first element (e.g. cpus) 5751692SN/A def __getitem__(self, key): 5761692SN/A if key == 0: 5771692SN/A return self 5781692SN/A raise TypeError, "Non-zero index '%s' to SimObject" % key 5791310SN/A 5801693SN/A # clear out children with given name, even if it's a vector 5811693SN/A def clear_child(self, name): 5821693SN/A if not self._children.has_key(name): 5831693SN/A return 5841693SN/A child = self._children[name] 5851693SN/A if isinstance(child, SimObjVector): 5861693SN/A for i in xrange(len(child)): 5871693SN/A del self._children["s%d" % (name, i)] 5881693SN/A del self._children[name] 5891693SN/A 5901692SN/A def add_child(self, name, value): 5911692SN/A self._children[name] = value 5921310SN/A 5933105Sstever@eecs.umich.edu def _maybe_set_parent(self, parent, name): 5942740SN/A if not self._parent: 5951692SN/A self._parent = parent 5961692SN/A self._name = name 5971692SN/A parent.add_child(name, self) 5981310SN/A 5993105Sstever@eecs.umich.edu def _set_child(self, attr, value): 6003105Sstever@eecs.umich.edu # if RHS is a SimObject, it's an implicit child assignment 6013105Sstever@eecs.umich.edu # clear out old child with this name, if any 6023105Sstever@eecs.umich.edu self.clear_child(attr) 6033105Sstever@eecs.umich.edu 6043105Sstever@eecs.umich.edu if isSimObject(value): 6053105Sstever@eecs.umich.edu value._maybe_set_parent(self, attr) 6063105Sstever@eecs.umich.edu elif isSimObjectSequence(value): 6073105Sstever@eecs.umich.edu value = SimObjVector(value) 6084762Snate@binkert.org if len(value) == 1: 6094762Snate@binkert.org value[0]._maybe_set_parent(self, attr) 6104762Snate@binkert.org else: 6115766Snate@binkert.org width = int(math.ceil(math.log(len(value))/math.log(10))) 6124762Snate@binkert.org for i,v in enumerate(value): 6135766Snate@binkert.org v._maybe_set_parent(self, "%s%0*d" % (attr, width, i)) 6143105Sstever@eecs.umich.edu 6153105Sstever@eecs.umich.edu self._values[attr] = value 6163105Sstever@eecs.umich.edu 6171692SN/A def path(self): 6182740SN/A if not self._parent: 6191692SN/A return 'root' 6201692SN/A ppath = self._parent.path() 6211692SN/A if ppath == 'root': 6221692SN/A return self._name 6231692SN/A return ppath + "." + self._name 6241310SN/A 6251692SN/A def __str__(self): 6261692SN/A return self.path() 6271310SN/A 6281692SN/A def ini_str(self): 6291692SN/A return self.path() 6301310SN/A 6311692SN/A def find_any(self, ptype): 6321692SN/A if isinstance(self, ptype): 6331692SN/A return self, True 6341310SN/A 6351692SN/A found_obj = None 6361692SN/A for child in self._children.itervalues(): 6371692SN/A if isinstance(child, ptype): 6381692SN/A if found_obj != None and child != found_obj: 6391692SN/A raise AttributeError, \ 6401692SN/A 'parent.any matched more than one: %s %s' % \ 6411814SN/A (found_obj.path, child.path) 6421692SN/A found_obj = child 6431692SN/A # search param space 6441692SN/A for pname,pdesc in self._params.iteritems(): 6451692SN/A if issubclass(pdesc.ptype, ptype): 6461692SN/A match_obj = self._values[pname] 6471692SN/A if found_obj != None and found_obj != match_obj: 6481692SN/A raise AttributeError, \ 6495952Ssaidi@eecs.umich.edu 'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path) 6501692SN/A found_obj = match_obj 6511692SN/A return found_obj, found_obj != None 6521692SN/A 6531815SN/A def unproxy(self, base): 6541815SN/A return self 6551815SN/A 6563105Sstever@eecs.umich.edu def unproxy_all(self): 6573105Sstever@eecs.umich.edu for param in self._params.iterkeys(): 6583105Sstever@eecs.umich.edu value = self._values.get(param) 6596654Snate@binkert.org if value != None and isproxy(value): 6603105Sstever@eecs.umich.edu try: 6613105Sstever@eecs.umich.edu value = value.unproxy(self) 6623105Sstever@eecs.umich.edu except: 6633105Sstever@eecs.umich.edu print "Error in unproxying param '%s' of %s" % \ 6643105Sstever@eecs.umich.edu (param, self.path()) 6653105Sstever@eecs.umich.edu raise 6663105Sstever@eecs.umich.edu setattr(self, param, value) 6673105Sstever@eecs.umich.edu 6683107Sstever@eecs.umich.edu # Unproxy ports in sorted order so that 'append' operations on 6693107Sstever@eecs.umich.edu # vector ports are done in a deterministic fashion. 6703107Sstever@eecs.umich.edu port_names = self._ports.keys() 6713107Sstever@eecs.umich.edu port_names.sort() 6723107Sstever@eecs.umich.edu for port_name in port_names: 6733105Sstever@eecs.umich.edu port = self._port_refs.get(port_name) 6743105Sstever@eecs.umich.edu if port != None: 6753105Sstever@eecs.umich.edu port.unproxy(self) 6763105Sstever@eecs.umich.edu 6773107Sstever@eecs.umich.edu # Unproxy children in sorted order for determinism also. 6783107Sstever@eecs.umich.edu child_names = self._children.keys() 6793107Sstever@eecs.umich.edu child_names.sort() 6803107Sstever@eecs.umich.edu for child in child_names: 6813107Sstever@eecs.umich.edu self._children[child].unproxy_all() 6823105Sstever@eecs.umich.edu 6835037Smilesck@eecs.umich.edu def print_ini(self, ini_file): 6845543Ssaidi@eecs.umich.edu print >>ini_file, '[' + self.path() + ']' # .ini section header 6851692SN/A 6862738SN/A instanceDict[self.path()] = self 6872738SN/A 6884081Sbinkertn@umich.edu if hasattr(self, 'type'): 6895037Smilesck@eecs.umich.edu print >>ini_file, 'type=%s' % self.type 6901692SN/A 6911692SN/A child_names = self._children.keys() 6921692SN/A child_names.sort() 6934081Sbinkertn@umich.edu if len(child_names): 6945037Smilesck@eecs.umich.edu print >>ini_file, 'children=%s' % ' '.join(child_names) 6951692SN/A 6961692SN/A param_names = self._params.keys() 6971692SN/A param_names.sort() 6981692SN/A for param in param_names: 6993105Sstever@eecs.umich.edu value = self._values.get(param) 7001692SN/A if value != None: 7015037Smilesck@eecs.umich.edu print >>ini_file, '%s=%s' % (param, 7025037Smilesck@eecs.umich.edu self._values[param].ini_str()) 7031692SN/A 7043103Sstever@eecs.umich.edu port_names = self._ports.keys() 7053103Sstever@eecs.umich.edu port_names.sort() 7063103Sstever@eecs.umich.edu for port_name in port_names: 7073105Sstever@eecs.umich.edu port = self._port_refs.get(port_name, None) 7083105Sstever@eecs.umich.edu if port != None: 7095037Smilesck@eecs.umich.edu print >>ini_file, '%s=%s' % (port_name, port.ini_str()) 7103103Sstever@eecs.umich.edu 7115543Ssaidi@eecs.umich.edu print >>ini_file # blank line between objects 7121692SN/A 7131692SN/A for child in child_names: 7145037Smilesck@eecs.umich.edu self._children[child].print_ini(ini_file) 7151692SN/A 7164762Snate@binkert.org def getCCParams(self): 7174762Snate@binkert.org if self._ccParams: 7184762Snate@binkert.org return self._ccParams 7194762Snate@binkert.org 7205033Smilesck@eecs.umich.edu cc_params_struct = getattr(m5.objects.params, '%sParams' % self.type) 7214762Snate@binkert.org cc_params = cc_params_struct() 7225488Snate@binkert.org cc_params.pyobj = self 7234762Snate@binkert.org cc_params.name = str(self) 7244762Snate@binkert.org 7254762Snate@binkert.org param_names = self._params.keys() 7264762Snate@binkert.org param_names.sort() 7274762Snate@binkert.org for param in param_names: 7284762Snate@binkert.org value = self._values.get(param) 7294762Snate@binkert.org if value is None: 7306654Snate@binkert.org fatal("%s.%s without default or user set value", 7316654Snate@binkert.org self.path(), param) 7324762Snate@binkert.org 7334762Snate@binkert.org value = value.getValue() 7344762Snate@binkert.org if isinstance(self._params[param], VectorParamDesc): 7354762Snate@binkert.org assert isinstance(value, list) 7364762Snate@binkert.org vec = getattr(cc_params, param) 7374762Snate@binkert.org assert not len(vec) 7384762Snate@binkert.org for v in value: 7394762Snate@binkert.org vec.append(v) 7404762Snate@binkert.org else: 7414762Snate@binkert.org setattr(cc_params, param, value) 7424762Snate@binkert.org 7434762Snate@binkert.org port_names = self._ports.keys() 7444762Snate@binkert.org port_names.sort() 7454762Snate@binkert.org for port_name in port_names: 7464762Snate@binkert.org port = self._port_refs.get(port_name, None) 7474762Snate@binkert.org if port != None: 7484762Snate@binkert.org setattr(cc_params, port_name, port) 7494762Snate@binkert.org self._ccParams = cc_params 7504762Snate@binkert.org return self._ccParams 7512738SN/A 7522740SN/A # Get C++ object corresponding to this object, calling C++ if 7532740SN/A # necessary to construct it. Does *not* recursively create 7542740SN/A # children. 7552740SN/A def getCCObject(self): 7562740SN/A if not self._ccObject: 7575244Sgblack@eecs.umich.edu # Cycles in the configuration heirarchy are not supported. This 7585244Sgblack@eecs.umich.edu # will catch the resulting recursion and stop. 7595244Sgblack@eecs.umich.edu self._ccObject = -1 7605244Sgblack@eecs.umich.edu params = self.getCCParams() 7614762Snate@binkert.org self._ccObject = params.create() 7622740SN/A elif self._ccObject == -1: 7635244Sgblack@eecs.umich.edu raise RuntimeError, "%s: Cycle found in configuration heirarchy." \ 7642740SN/A % self.path() 7652740SN/A return self._ccObject 7662740SN/A 7674762Snate@binkert.org # Call C++ to create C++ object corresponding to this object and 7684762Snate@binkert.org # (recursively) all its children 7694762Snate@binkert.org def createCCObject(self): 7704762Snate@binkert.org self.getCCParams() 7714762Snate@binkert.org self.getCCObject() # force creation 7724762Snate@binkert.org for child in self._children.itervalues(): 7734762Snate@binkert.org child.createCCObject() 7744762Snate@binkert.org 7754762Snate@binkert.org def getValue(self): 7764762Snate@binkert.org return self.getCCObject() 7774762Snate@binkert.org 7782738SN/A # Create C++ port connections corresponding to the connections in 7793105Sstever@eecs.umich.edu # _port_refs (& recursively for all children) 7802738SN/A def connectPorts(self): 7813105Sstever@eecs.umich.edu for portRef in self._port_refs.itervalues(): 7823105Sstever@eecs.umich.edu portRef.ccConnect() 7832738SN/A for child in self._children.itervalues(): 7842738SN/A child.connectPorts() 7852738SN/A 7862839SN/A def startDrain(self, drain_event, recursive): 7872797SN/A count = 0 7884081Sbinkertn@umich.edu if isinstance(self, SimObject): 7892901SN/A count += self._ccObject.drain(drain_event) 7902797SN/A if recursive: 7912797SN/A for child in self._children.itervalues(): 7922839SN/A count += child.startDrain(drain_event, True) 7932797SN/A return count 7942797SN/A 7952797SN/A def resume(self): 7964081Sbinkertn@umich.edu if isinstance(self, SimObject): 7972797SN/A self._ccObject.resume() 7982797SN/A for child in self._children.itervalues(): 7992797SN/A child.resume() 8002797SN/A 8014553Sbinkertn@umich.edu def getMemoryMode(self): 8024553Sbinkertn@umich.edu if not isinstance(self, m5.objects.System): 8034553Sbinkertn@umich.edu return None 8044553Sbinkertn@umich.edu 8054859Snate@binkert.org return self._ccObject.getMemoryMode() 8064553Sbinkertn@umich.edu 8072797SN/A def changeTiming(self, mode): 8083202Shsul@eecs.umich.edu if isinstance(self, m5.objects.System): 8093202Shsul@eecs.umich.edu # i don't know if there's a better way to do this - calling 8103202Shsul@eecs.umich.edu # setMemoryMode directly from self._ccObject results in calling 8113202Shsul@eecs.umich.edu # SimObject::setMemoryMode, not the System::setMemoryMode 8124859Snate@binkert.org self._ccObject.setMemoryMode(mode) 8132797SN/A for child in self._children.itervalues(): 8142797SN/A child.changeTiming(mode) 8152797SN/A 8162797SN/A def takeOverFrom(self, old_cpu): 8174859Snate@binkert.org self._ccObject.takeOverFrom(old_cpu._ccObject) 8182797SN/A 8191692SN/A # generate output file for 'dot' to display as a pretty graph. 8201692SN/A # this code is currently broken. 8211342SN/A def outputDot(self, dot): 8221342SN/A label = "{%s|" % self.path 8231342SN/A if isSimObject(self.realtype): 8241342SN/A label += '%s|' % self.type 8251342SN/A 8261342SN/A if self.children: 8271342SN/A # instantiate children in same order they were added for 8281342SN/A # backward compatibility (else we can end up with cpu1 8291342SN/A # before cpu0). 8301342SN/A for c in self.children: 8311342SN/A dot.add_edge(pydot.Edge(self.path,c.path, style="bold")) 8321342SN/A 8331342SN/A simobjs = [] 8341342SN/A for param in self.params: 8351342SN/A try: 8361342SN/A if param.value is None: 8371342SN/A raise AttributeError, 'Parameter with no value' 8381342SN/A 8391692SN/A value = param.value 8401342SN/A string = param.string(value) 8411587SN/A except Exception, e: 8421605SN/A msg = 'exception in %s:%s\n%s' % (self.name, param.name, e) 8431605SN/A e.args = (msg, ) 8441342SN/A raise 8451605SN/A 8461692SN/A if isSimObject(param.ptype) and string != "Null": 8471342SN/A simobjs.append(string) 8481342SN/A else: 8491342SN/A label += '%s = %s\\n' % (param.name, string) 8501342SN/A 8511342SN/A for so in simobjs: 8521342SN/A label += "|<%s> %s" % (so, so) 8531587SN/A dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so, 8541587SN/A tailport="w")) 8551342SN/A label += '}' 8561342SN/A dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label)) 8571342SN/A 8581342SN/A # recursively dump out children 8591342SN/A for c in self.children: 8601342SN/A c.outputDot(dot) 8611342SN/A 8623101Sstever@eecs.umich.edu# Function to provide to C++ so it can look up instances based on paths 8633101Sstever@eecs.umich.edudef resolveSimObject(name): 8643101Sstever@eecs.umich.edu obj = instanceDict[name] 8653101Sstever@eecs.umich.edu return obj.getCCObject() 866679SN/A 8676654Snate@binkert.orgdef isSimObject(value): 8686654Snate@binkert.org return isinstance(value, SimObject) 8696654Snate@binkert.org 8706654Snate@binkert.orgdef isSimObjectClass(value): 8716654Snate@binkert.org return issubclass(value, SimObject) 8726654Snate@binkert.org 8736654Snate@binkert.orgdef isSimObjectSequence(value): 8746654Snate@binkert.org if not isinstance(value, (list, tuple)) or len(value) == 0: 8756654Snate@binkert.org return False 8766654Snate@binkert.org 8776654Snate@binkert.org for val in value: 8786654Snate@binkert.org if not isNullPointer(val) and not isSimObject(val): 8796654Snate@binkert.org return False 8806654Snate@binkert.org 8816654Snate@binkert.org return True 8826654Snate@binkert.org 8836654Snate@binkert.orgdef isSimObjectOrSequence(value): 8846654Snate@binkert.org return isSimObject(value) or isSimObjectSequence(value) 8856654Snate@binkert.org 8866654Snate@binkert.orgbaseClasses = allClasses.copy() 8876654Snate@binkert.orgbaseInstances = instanceDict.copy() 8886654Snate@binkert.org 8896654Snate@binkert.orgdef clear(): 8906654Snate@binkert.org global allClasses, instanceDict 8916654Snate@binkert.org 8926654Snate@binkert.org allClasses = baseClasses.copy() 8936654Snate@binkert.org instanceDict = baseInstances.copy() 8946654Snate@binkert.org 8951528SN/A# __all__ defines the list of symbols that get exported when 8961528SN/A# 'from config import *' is invoked. Try to keep this reasonably 8971528SN/A# short to avoid polluting other namespaces. 8984762Snate@binkert.org__all__ = [ 'SimObject' ] 899