SimObject.py revision 3102
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
303101Sstever@eecs.umich.eduimport sys, types
311438SN/A
323102Sstever@eecs.umich.edufrom util import *
331585SN/Afrom multidict import multidict
341438SN/A
353102Sstever@eecs.umich.edu# These utility functions have to come first because they're
363102Sstever@eecs.umich.edu# referenced in params.py... otherwise they won't be defined when we
373102Sstever@eecs.umich.edu# import params below, and the recursive import of this file from
383102Sstever@eecs.umich.edu# params.py will not find these names.
393102Sstever@eecs.umich.edudef isSimObject(value):
403102Sstever@eecs.umich.edu    return isinstance(value, SimObject)
413102Sstever@eecs.umich.edu
423102Sstever@eecs.umich.edudef isSimObjectClass(value):
433102Sstever@eecs.umich.edu    return issubclass(value, SimObject)
443102Sstever@eecs.umich.edu
453102Sstever@eecs.umich.edudef isSimObjectSequence(value):
463102Sstever@eecs.umich.edu    if not isinstance(value, (list, tuple)) or len(value) == 0:
473102Sstever@eecs.umich.edu        return False
483102Sstever@eecs.umich.edu
493102Sstever@eecs.umich.edu    for val in value:
503102Sstever@eecs.umich.edu        if not isNullPointer(val) and not isSimObject(val):
513102Sstever@eecs.umich.edu            return False
523102Sstever@eecs.umich.edu
533102Sstever@eecs.umich.edu    return True
543102Sstever@eecs.umich.edu
553102Sstever@eecs.umich.edudef isSimObjectOrSequence(value):
563102Sstever@eecs.umich.edu    return isSimObject(value) or isSimObjectSequence(value)
573102Sstever@eecs.umich.edu
583102Sstever@eecs.umich.edu# Have to import params up top since Param is referenced on initial
593102Sstever@eecs.umich.edu# load (when SimObject class references Param to create a class
603102Sstever@eecs.umich.edu# variable, the 'name' param)...
613102Sstever@eecs.umich.edufrom params import *
623102Sstever@eecs.umich.edu# There are a few things we need that aren't in params.__all__ since
633102Sstever@eecs.umich.edu# normal users don't need them
643102Sstever@eecs.umich.edufrom params import ParamDesc, isNullPointer, SimObjVector
653102Sstever@eecs.umich.edu
661342SN/AnoDot = False
671342SN/Atry:
681378SN/A    import pydot
691342SN/Aexcept:
701378SN/A    noDot = True
71679SN/A
72679SN/A#####################################################################
73679SN/A#
74679SN/A# M5 Python Configuration Utility
75679SN/A#
76679SN/A# The basic idea is to write simple Python programs that build Python
771692SN/A# objects corresponding to M5 SimObjects for the desired simulation
78679SN/A# configuration.  For now, the Python emits a .ini file that can be
79679SN/A# parsed by M5.  In the future, some tighter integration between M5
80679SN/A# and the Python interpreter may allow bypassing the .ini file.
81679SN/A#
82679SN/A# Each SimObject class in M5 is represented by a Python class with the
83679SN/A# same name.  The Python inheritance tree mirrors the M5 C++ tree
84679SN/A# (e.g., SimpleCPU derives from BaseCPU in both cases, and all
85679SN/A# SimObjects inherit from a single SimObject base class).  To specify
86679SN/A# an instance of an M5 SimObject in a configuration, the user simply
87679SN/A# instantiates the corresponding Python object.  The parameters for
88679SN/A# that SimObject are given by assigning to attributes of the Python
89679SN/A# object, either using keyword assignment in the constructor or in
90679SN/A# separate assignment statements.  For example:
91679SN/A#
921692SN/A# cache = BaseCache(size='64KB')
93679SN/A# cache.hit_latency = 3
94679SN/A# cache.assoc = 8
95679SN/A#
96679SN/A# The magic lies in the mapping of the Python attributes for SimObject
97679SN/A# classes to the actual SimObject parameter specifications.  This
98679SN/A# allows parameter validity checking in the Python code.  Continuing
99679SN/A# the example above, the statements "cache.blurfl=3" or
100679SN/A# "cache.assoc='hello'" would both result in runtime errors in Python,
101679SN/A# since the BaseCache object has no 'blurfl' parameter and the 'assoc'
102679SN/A# parameter requires an integer, respectively.  This magic is done
103679SN/A# primarily by overriding the special __setattr__ method that controls
104679SN/A# assignment to object attributes.
105679SN/A#
106679SN/A# Once a set of Python objects have been instantiated in a hierarchy,
107679SN/A# calling 'instantiate(obj)' (where obj is the root of the hierarchy)
1082740SN/A# will generate a .ini file.
109679SN/A#
110679SN/A#####################################################################
111679SN/A
1122738SN/A# dict to look up SimObjects based on path
1132738SN/AinstanceDict = {}
1142738SN/A
1152740SN/A# The metaclass for SimObject.  This class controls how new classes
1162740SN/A# that derive from SimObject are instantiated, and provides inherited
1172740SN/A# class behavior (just like a class controls how instances of that
1182740SN/A# class are instantiated, and provides inherited instance behavior).
1191692SN/Aclass MetaSimObject(type):
1201427SN/A    # Attributes that can be set only at initialization time
1211692SN/A    init_keywords = { 'abstract' : types.BooleanType,
1221692SN/A                      'type' : types.StringType }
1231427SN/A    # Attributes that can be set any time
1243100SN/A    keywords = { 'check' : types.FunctionType,
1253100SN/A                 'cxx_type' : types.StringType,
1263100SN/A                 'cxx_predecls' : types.ListType,
1273100SN/A                 'swig_predecls' : types.ListType }
128679SN/A
129679SN/A    # __new__ is called before __init__, and is where the statements
130679SN/A    # in the body of the class definition get loaded into the class's
1312740SN/A    # __dict__.  We intercept this to filter out parameter & port assignments
132679SN/A    # and only allow "private" attributes to be passed to the base
133679SN/A    # __new__ (starting with underscore).
1341310SN/A    def __new__(mcls, name, bases, dict):
1352740SN/A        # Copy "private" attributes, functions, and classes to the
1362740SN/A        # official dict.  Everything else goes in _init_dict to be
1372740SN/A        # filtered in __init__.
1382740SN/A        cls_dict = {}
1392740SN/A        value_dict = {}
1402740SN/A        for key,val in dict.items():
1412740SN/A            if key.startswith('_') or isinstance(val, (types.FunctionType,
1422740SN/A                                                       types.TypeType)):
1432740SN/A                cls_dict[key] = val
1442740SN/A            else:
1452740SN/A                # must be a param/port setting
1462740SN/A                value_dict[key] = val
1472740SN/A        cls_dict['_value_dict'] = value_dict
1481692SN/A        return super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
149679SN/A
1502711SN/A    # subclass initialization
151679SN/A    def __init__(cls, name, bases, dict):
1522711SN/A        # calls type.__init__()... I think that's a no-op, but leave
1532711SN/A        # it here just in case it's not.
1541692SN/A        super(MetaSimObject, cls).__init__(name, bases, dict)
1551310SN/A
1561427SN/A        # initialize required attributes
1572740SN/A
1582740SN/A        # class-only attributes
1592740SN/A        cls._params = multidict() # param descriptions
1602740SN/A        cls._ports = multidict()  # port descriptions
1612740SN/A
1622740SN/A        # class or instance attributes
1632740SN/A        cls._values = multidict()   # param values
1642740SN/A        cls._port_map = multidict() # port bindings
1652740SN/A        cls._instantiated = False # really instantiated, cloned, or subclassed
1661310SN/A
1671692SN/A        # We don't support multiple inheritance.  If you want to, you
1681585SN/A        # must fix multidict to deal with it properly.
1691692SN/A        if len(bases) > 1:
1701692SN/A            raise TypeError, "SimObjects do not support multiple inheritance"
1711692SN/A
1721692SN/A        base = bases[0]
1731692SN/A
1742740SN/A        # Set up general inheritance via multidicts.  A subclass will
1752740SN/A        # inherit all its settings from the base class.  The only time
1762740SN/A        # the following is not true is when we define the SimObject
1772740SN/A        # class itself (in which case the multidicts have no parent).
1781692SN/A        if isinstance(base, MetaSimObject):
1791692SN/A            cls._params.parent = base._params
1802740SN/A            cls._ports.parent = base._ports
1811692SN/A            cls._values.parent = base._values
1822740SN/A            cls._port_map.parent = base._port_map
1832740SN/A            # mark base as having been subclassed
1842712SN/A            base._instantiated = True
1851692SN/A
1862740SN/A        # Now process the _value_dict items.  They could be defining
1872740SN/A        # new (or overriding existing) parameters or ports, setting
1882740SN/A        # class keywords (e.g., 'abstract'), or setting parameter
1892740SN/A        # values or port bindings.  The first 3 can only be set when
1902740SN/A        # the class is defined, so we handle them here.  The others
1912740SN/A        # can be set later too, so just emulate that by calling
1922740SN/A        # setattr().
1932740SN/A        for key,val in cls._value_dict.items():
1941527SN/A            # param descriptions
1952740SN/A            if isinstance(val, ParamDesc):
1961585SN/A                cls._new_param(key, val)
1971427SN/A
1982738SN/A            # port objects
1992738SN/A            elif isinstance(val, Port):
2002738SN/A                cls._ports[key] = val
2012738SN/A
2021427SN/A            # init-time-only keywords
2031427SN/A            elif cls.init_keywords.has_key(key):
2041427SN/A                cls._set_keyword(key, val, cls.init_keywords[key])
2051427SN/A
2061427SN/A            # default: use normal path (ends up in __setattr__)
2071427SN/A            else:
2081427SN/A                setattr(cls, key, val)
2091427SN/A
2103100SN/A        cls.cxx_type = cls.type + '*'
2113100SN/A        # A forward class declaration is sufficient since we are just
2123100SN/A        # declaring a pointer.
2133100SN/A        cls.cxx_predecls = ['class %s;' % cls.type]
2143100SN/A        cls.swig_predecls = cls.cxx_predecls
2153100SN/A
2161427SN/A    def _set_keyword(cls, keyword, val, kwtype):
2171427SN/A        if not isinstance(val, kwtype):
2181427SN/A            raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
2191427SN/A                  (keyword, type(val), kwtype)
2201427SN/A        if isinstance(val, types.FunctionType):
2211427SN/A            val = classmethod(val)
2221427SN/A        type.__setattr__(cls, keyword, val)
2231427SN/A
2243100SN/A    def _new_param(cls, name, pdesc):
2253100SN/A        # each param desc should be uniquely assigned to one variable
2263100SN/A        assert(not hasattr(pdesc, 'name'))
2273100SN/A        pdesc.name = name
2283100SN/A        cls._params[name] = pdesc
2293100SN/A        if hasattr(pdesc, 'default'):
2303100SN/A            setattr(cls, name, pdesc.default)
2311585SN/A
2321310SN/A    # Set attribute (called on foo.attr = value when foo is an
2331310SN/A    # instance of class cls).
2341310SN/A    def __setattr__(cls, attr, value):
2351310SN/A        # normal processing for private attributes
2361310SN/A        if attr.startswith('_'):
2371310SN/A            type.__setattr__(cls, attr, value)
2381310SN/A            return
2391310SN/A
2401310SN/A        if cls.keywords.has_key(attr):
2411427SN/A            cls._set_keyword(attr, value, cls.keywords[attr])
2421310SN/A            return
2431310SN/A
2442738SN/A        if cls._ports.has_key(attr):
2452738SN/A            self._ports[attr].connect(self, attr, value)
2462738SN/A            return
2472738SN/A
2482740SN/A        if isSimObjectOrSequence(value) and cls._instantiated:
2492740SN/A            raise RuntimeError, \
2502740SN/A                  "cannot set SimObject parameter '%s' after\n" \
2512740SN/A                  "    class %s has been instantiated or subclassed" \
2522740SN/A                  % (attr, cls.__name__)
2532740SN/A
2542740SN/A        # check for param
2551585SN/A        param = cls._params.get(attr, None)
2561310SN/A        if param:
2571527SN/A            try:
2581692SN/A                cls._values[attr] = param.convert(value)
2591585SN/A            except Exception, e:
2601605SN/A                msg = "%s\nError setting param %s.%s to %s\n" % \
2611590SN/A                      (e, cls.__name__, attr, value)
2621605SN/A                e.args = (msg, )
2631605SN/A                raise
2642714SN/A        elif isSimObjectOrSequence(value):
2652740SN/A            # if RHS is a SimObject, it's an implicit child assignment
2662740SN/A            cls._values[attr] = value
2671310SN/A        else:
2681310SN/A            raise AttributeError, \
2692831SN/A                  "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
2701310SN/A
2711585SN/A    def __getattr__(cls, attr):
2721692SN/A        if cls._values.has_key(attr):
2731692SN/A            return cls._values[attr]
2741585SN/A
2751585SN/A        raise AttributeError, \
2761585SN/A              "object '%s' has no attribute '%s'" % (cls.__name__, attr)
2771585SN/A
2783100SN/A    def __str__(cls):
2793100SN/A        return cls.__name__
2803100SN/A
2813100SN/A    def cxx_decl(cls):
2823100SN/A        code = "#ifndef __PARAMS__%s\n#define __PARAMS__%s\n\n" % (cls, cls)
2833100SN/A
2843100SN/A        if str(cls) != 'SimObject':
2853100SN/A            base = cls.__bases__[0].type
2863100SN/A        else:
2873100SN/A            base = None
2883100SN/A
2893100SN/A        # The 'dict' attribute restricts us to the params declared in
2903100SN/A        # the object itself, not including inherited params (which
2913100SN/A        # will also be inherited from the base class's param struct
2923100SN/A        # here).
2933100SN/A        params = cls._params.dict.values()
2943100SN/A        try:
2953100SN/A            ptypes = [p.ptype for p in params]
2963100SN/A        except:
2973100SN/A            print cls, p, p.ptype_str
2983100SN/A            print params
2993100SN/A            raise
3003100SN/A
3013100SN/A        # get a list of lists of predeclaration lines
3023100SN/A        predecls = [p.cxx_predecls() for p in params]
3033100SN/A        # flatten
3043100SN/A        predecls = reduce(lambda x,y:x+y, predecls, [])
3053100SN/A        # remove redundant lines
3063100SN/A        predecls2 = []
3073100SN/A        for pd in predecls:
3083100SN/A            if pd not in predecls2:
3093100SN/A                predecls2.append(pd)
3103100SN/A        predecls2.sort()
3113100SN/A        code += "\n".join(predecls2)
3123100SN/A        code += "\n\n";
3133100SN/A
3143100SN/A        if base:
3153100SN/A            code += '#include "params/%s.hh"\n\n' % base
3163100SN/A
3173100SN/A        # Generate declarations for locally defined enumerations.
3183100SN/A        enum_ptypes = [t for t in ptypes if issubclass(t, Enum)]
3193100SN/A        if enum_ptypes:
3203100SN/A            code += "\n".join([t.cxx_decl() for t in enum_ptypes])
3213100SN/A            code += "\n\n"
3223100SN/A
3233100SN/A        # now generate the actual param struct
3243100SN/A        code += "struct %sParams" % cls
3253100SN/A        if base:
3263100SN/A            code += " : public %sParams" % base
3273100SN/A        code += " {\n"
3283100SN/A        decls = [p.cxx_decl() for p in params]
3293100SN/A        decls.sort()
3303100SN/A        code += "".join(["    %s\n" % d for d in decls])
3313100SN/A        code += "};\n"
3323100SN/A
3333100SN/A        # close #ifndef __PARAMS__* guard
3343100SN/A        code += "\n#endif\n"
3353100SN/A        return code
3363100SN/A
3373100SN/A    def swig_decl(cls):
3383100SN/A
3393100SN/A        code = '%%module %sParams\n' % cls
3403100SN/A
3413100SN/A        if str(cls) != 'SimObject':
3423100SN/A            base = cls.__bases__[0].type
3433100SN/A        else:
3443100SN/A            base = None
3453100SN/A
3463100SN/A        # The 'dict' attribute restricts us to the params declared in
3473100SN/A        # the object itself, not including inherited params (which
3483100SN/A        # will also be inherited from the base class's param struct
3493100SN/A        # here).
3503100SN/A        params = cls._params.dict.values()
3513100SN/A        ptypes = [p.ptype for p in params]
3523100SN/A
3533100SN/A        # get a list of lists of predeclaration lines
3543100SN/A        predecls = [p.swig_predecls() for p in params]
3553100SN/A        # flatten
3563100SN/A        predecls = reduce(lambda x,y:x+y, predecls, [])
3573100SN/A        # remove redundant lines
3583100SN/A        predecls2 = []
3593100SN/A        for pd in predecls:
3603100SN/A            if pd not in predecls2:
3613100SN/A                predecls2.append(pd)
3623100SN/A        predecls2.sort()
3633100SN/A        code += "\n".join(predecls2)
3643100SN/A        code += "\n\n";
3653100SN/A
3663100SN/A        if base:
3673100SN/A            code += '%%import "python/m5/swig/%sParams.i"\n\n' % base
3683100SN/A
3693100SN/A        code += '%{\n'
3703100SN/A        code += '#include "params/%s.hh"\n' % cls
3713100SN/A        code += '%}\n\n'
3723100SN/A        code += '%%include "params/%s.hh"\n\n' % cls
3733100SN/A
3743100SN/A        return code
3753100SN/A
3762740SN/A# The SimObject class is the root of the special hierarchy.  Most of
377679SN/A# the code in this class deals with the configuration hierarchy itself
378679SN/A# (parent/child node relationships).
3791692SN/Aclass SimObject(object):
3801692SN/A    # Specify metaclass.  Any class inheriting from SimObject will
381679SN/A    # get this metaclass.
3821692SN/A    __metaclass__ = MetaSimObject
3833100SN/A    type = 'SimObject'
3843100SN/A
3853100SN/A    name = Param.String("Object name")
386679SN/A
3872740SN/A    # Initialize new instance.  For objects with SimObject-valued
3882740SN/A    # children, we need to recursively clone the classes represented
3892740SN/A    # by those param values as well in a consistent "deep copy"-style
3902740SN/A    # fashion.  That is, we want to make sure that each instance is
3912740SN/A    # cloned only once, and that if there are multiple references to
3922740SN/A    # the same original object, we end up with the corresponding
3932740SN/A    # cloned references all pointing to the same cloned instance.
3942740SN/A    def __init__(self, **kwargs):
3952740SN/A        ancestor = kwargs.get('_ancestor')
3962740SN/A        memo_dict = kwargs.get('_memo')
3972740SN/A        if memo_dict is None:
3982740SN/A            # prepare to memoize any recursively instantiated objects
3992740SN/A            memo_dict = {}
4002740SN/A        elif ancestor:
4012740SN/A            # memoize me now to avoid problems with recursive calls
4022740SN/A            memo_dict[ancestor] = self
4032711SN/A
4042740SN/A        if not ancestor:
4052740SN/A            ancestor = self.__class__
4062740SN/A        ancestor._instantiated = True
4072711SN/A
4082740SN/A        # initialize required attributes
4092740SN/A        self._parent = None
4102740SN/A        self._children = {}
4112740SN/A        self._ccObject = None  # pointer to C++ object
4122740SN/A        self._instantiated = False # really "cloned"
4132712SN/A
4142711SN/A        # Inherit parameter values from class using multidict so
4152711SN/A        # individual value settings can be overridden.
4162740SN/A        self._values = multidict(ancestor._values)
4172740SN/A        # clone SimObject-valued parameters
4182740SN/A        for key,val in ancestor._values.iteritems():
4192740SN/A            if isSimObject(val):
4202740SN/A                setattr(self, key, val(_memo=memo_dict))
4212740SN/A            elif isSimObjectSequence(val) and len(val):
4222740SN/A                setattr(self, key, [ v(_memo=memo_dict) for v in val ])
4232740SN/A        # clone port references.  no need to use a multidict here
4242740SN/A        # since we will be creating new references for all ports.
4252740SN/A        self._port_map = {}
4262740SN/A        for key,val in ancestor._port_map.iteritems():
4272740SN/A            self._port_map[key] = applyOrMap(val, 'clone', memo_dict)
4281692SN/A        # apply attribute assignments from keyword args, if any
4291692SN/A        for key,val in kwargs.iteritems():
4301692SN/A            setattr(self, key, val)
431679SN/A
4322740SN/A    # "Clone" the current instance by creating another instance of
4332740SN/A    # this instance's class, but that inherits its parameter values
4342740SN/A    # and port mappings from the current instance.  If we're in a
4352740SN/A    # "deep copy" recursive clone, check the _memo dict to see if
4362740SN/A    # we've already cloned this instance.
4371692SN/A    def __call__(self, **kwargs):
4382740SN/A        memo_dict = kwargs.get('_memo')
4392740SN/A        if memo_dict is None:
4402740SN/A            # no memo_dict: must be top-level clone operation.
4412740SN/A            # this is only allowed at the root of a hierarchy
4422740SN/A            if self._parent:
4432740SN/A                raise RuntimeError, "attempt to clone object %s " \
4442740SN/A                      "not at the root of a tree (parent = %s)" \
4452740SN/A                      % (self, self._parent)
4462740SN/A            # create a new dict and use that.
4472740SN/A            memo_dict = {}
4482740SN/A            kwargs['_memo'] = memo_dict
4492740SN/A        elif memo_dict.has_key(self):
4502740SN/A            # clone already done & memoized
4512740SN/A            return memo_dict[self]
4522740SN/A        return self.__class__(_ancestor = self, **kwargs)
4531343SN/A
4541692SN/A    def __getattr__(self, attr):
4552738SN/A        if self._ports.has_key(attr):
4562738SN/A            # return reference that can be assigned to another port
4572738SN/A            # via __setattr__
4582738SN/A            return self._ports[attr].makeRef(self, attr)
4592738SN/A
4601692SN/A        if self._values.has_key(attr):
4611692SN/A            return self._values[attr]
4621427SN/A
4631692SN/A        raise AttributeError, "object '%s' has no attribute '%s'" \
4641692SN/A              % (self.__class__.__name__, attr)
4651427SN/A
4661692SN/A    # Set attribute (called on foo.attr = value when foo is an
4671692SN/A    # instance of class cls).
4681692SN/A    def __setattr__(self, attr, value):
4691692SN/A        # normal processing for private attributes
4701692SN/A        if attr.startswith('_'):
4711692SN/A            object.__setattr__(self, attr, value)
4721692SN/A            return
4731427SN/A
4742738SN/A        if self._ports.has_key(attr):
4752738SN/A            # set up port connection
4762738SN/A            self._ports[attr].connect(self, attr, value)
4772738SN/A            return
4782738SN/A
4792740SN/A        if isSimObjectOrSequence(value) and self._instantiated:
4802740SN/A            raise RuntimeError, \
4812740SN/A                  "cannot set SimObject parameter '%s' after\n" \
4822740SN/A                  "    instance been cloned %s" % (attr, `self`)
4832740SN/A
4841692SN/A        # must be SimObject param
4851692SN/A        param = self._params.get(attr, None)
4861692SN/A        if param:
4871310SN/A            try:
4881692SN/A                value = param.convert(value)
4891587SN/A            except Exception, e:
4901692SN/A                msg = "%s\nError setting param %s.%s to %s\n" % \
4911692SN/A                      (e, self.__class__.__name__, attr, value)
4921605SN/A                e.args = (msg, )
4931605SN/A                raise
4942714SN/A        elif isSimObjectOrSequence(value):
4951692SN/A            pass
4961692SN/A        else:
4971692SN/A            raise AttributeError, "Class %s has no parameter %s" \
4981692SN/A                  % (self.__class__.__name__, attr)
4991310SN/A
5001693SN/A        # clear out old child with this name, if any
5011693SN/A        self.clear_child(attr)
5021693SN/A
5031692SN/A        if isSimObject(value):
5041692SN/A            value.set_path(self, attr)
5052714SN/A        elif isSimObjectSequence(value):
5061692SN/A            value = SimObjVector(value)
5071692SN/A            [v.set_path(self, "%s%d" % (attr, i)) for i,v in enumerate(value)]
5081310SN/A
5091692SN/A        self._values[attr] = value
5101310SN/A
5111692SN/A    # this hack allows tacking a '[0]' onto parameters that may or may
5121692SN/A    # not be vectors, and always getting the first element (e.g. cpus)
5131692SN/A    def __getitem__(self, key):
5141692SN/A        if key == 0:
5151692SN/A            return self
5161692SN/A        raise TypeError, "Non-zero index '%s' to SimObject" % key
5171310SN/A
5181693SN/A    # clear out children with given name, even if it's a vector
5191693SN/A    def clear_child(self, name):
5201693SN/A        if not self._children.has_key(name):
5211693SN/A            return
5221693SN/A        child = self._children[name]
5231693SN/A        if isinstance(child, SimObjVector):
5241693SN/A            for i in xrange(len(child)):
5251693SN/A                del self._children["s%d" % (name, i)]
5261693SN/A        del self._children[name]
5271693SN/A
5281692SN/A    def add_child(self, name, value):
5291692SN/A        self._children[name] = value
5301310SN/A
5311692SN/A    def set_path(self, parent, name):
5322740SN/A        if not self._parent:
5331692SN/A            self._parent = parent
5341692SN/A            self._name = name
5351692SN/A            parent.add_child(name, self)
5361310SN/A
5371692SN/A    def path(self):
5382740SN/A        if not self._parent:
5391692SN/A            return 'root'
5401692SN/A        ppath = self._parent.path()
5411692SN/A        if ppath == 'root':
5421692SN/A            return self._name
5431692SN/A        return ppath + "." + self._name
5441310SN/A
5451692SN/A    def __str__(self):
5461692SN/A        return self.path()
5471310SN/A
5481692SN/A    def ini_str(self):
5491692SN/A        return self.path()
5501310SN/A
5511692SN/A    def find_any(self, ptype):
5521692SN/A        if isinstance(self, ptype):
5531692SN/A            return self, True
5541310SN/A
5551692SN/A        found_obj = None
5561692SN/A        for child in self._children.itervalues():
5571692SN/A            if isinstance(child, ptype):
5581692SN/A                if found_obj != None and child != found_obj:
5591692SN/A                    raise AttributeError, \
5601692SN/A                          'parent.any matched more than one: %s %s' % \
5611814SN/A                          (found_obj.path, child.path)
5621692SN/A                found_obj = child
5631692SN/A        # search param space
5641692SN/A        for pname,pdesc in self._params.iteritems():
5651692SN/A            if issubclass(pdesc.ptype, ptype):
5661692SN/A                match_obj = self._values[pname]
5671692SN/A                if found_obj != None and found_obj != match_obj:
5681692SN/A                    raise AttributeError, \
5691692SN/A                          'parent.any matched more than one: %s' % obj.path
5701692SN/A                found_obj = match_obj
5711692SN/A        return found_obj, found_obj != None
5721692SN/A
5731815SN/A    def unproxy(self, base):
5741815SN/A        return self
5751815SN/A
5761692SN/A    def print_ini(self):
5771692SN/A        print '[' + self.path() + ']'	# .ini section header
5781692SN/A
5792738SN/A        instanceDict[self.path()] = self
5802738SN/A
5811692SN/A        if hasattr(self, 'type') and not isinstance(self, ParamContext):
5821799SN/A            print 'type=%s' % self.type
5831692SN/A
5841692SN/A        child_names = self._children.keys()
5851692SN/A        child_names.sort()
5861692SN/A        np_child_names = [c for c in child_names \
5871692SN/A                          if not isinstance(self._children[c], ParamContext)]
5881692SN/A        if len(np_child_names):
5891799SN/A            print 'children=%s' % ' '.join(np_child_names)
5901692SN/A
5911692SN/A        param_names = self._params.keys()
5921692SN/A        param_names.sort()
5931692SN/A        for param in param_names:
5941692SN/A            value = self._values.get(param, None)
5951692SN/A            if value != None:
5963102Sstever@eecs.umich.edu                if proxy.isproxy(value):
5971692SN/A                    try:
5981692SN/A                        value = value.unproxy(self)
5991692SN/A                    except:
6001692SN/A                        print >> sys.stderr, \
6011692SN/A                              "Error in unproxying param '%s' of %s" % \
6021692SN/A                              (param, self.path())
6031692SN/A                        raise
6041692SN/A                    setattr(self, param, value)
6051799SN/A                print '%s=%s' % (param, self._values[param].ini_str())
6061692SN/A
6071692SN/A        print	# blank line between objects
6081692SN/A
6091692SN/A        for child in child_names:
6101692SN/A            self._children[child].print_ini()
6111692SN/A
6122738SN/A    # Call C++ to create C++ object corresponding to this object and
6132738SN/A    # (recursively) all its children
6142738SN/A    def createCCObject(self):
6152740SN/A        self.getCCObject() # force creation
6162738SN/A        for child in self._children.itervalues():
6172738SN/A            child.createCCObject()
6182738SN/A
6192740SN/A    # Get C++ object corresponding to this object, calling C++ if
6202740SN/A    # necessary to construct it.  Does *not* recursively create
6212740SN/A    # children.
6222740SN/A    def getCCObject(self):
6232740SN/A        if not self._ccObject:
6242740SN/A            self._ccObject = -1 # flag to catch cycles in recursion
6252763SN/A            self._ccObject = cc_main.createSimObject(self.path())
6262740SN/A        elif self._ccObject == -1:
6272740SN/A            raise RuntimeError, "%s: recursive call to getCCObject()" \
6282740SN/A                  % self.path()
6292740SN/A        return self._ccObject
6302740SN/A
6312738SN/A    # Create C++ port connections corresponding to the connections in
6322738SN/A    # _port_map (& recursively for all children)
6332738SN/A    def connectPorts(self):
6342738SN/A        for portRef in self._port_map.itervalues():
6352738SN/A            applyOrMap(portRef, 'ccConnect')
6362738SN/A        for child in self._children.itervalues():
6372738SN/A            child.connectPorts()
6382738SN/A
6392839SN/A    def startDrain(self, drain_event, recursive):
6402797SN/A        count = 0
6412797SN/A        # ParamContexts don't serialize
6422797SN/A        if isinstance(self, SimObject) and not isinstance(self, ParamContext):
6432901SN/A            count += self._ccObject.drain(drain_event)
6442797SN/A        if recursive:
6452797SN/A            for child in self._children.itervalues():
6462839SN/A                count += child.startDrain(drain_event, True)
6472797SN/A        return count
6482797SN/A
6492797SN/A    def resume(self):
6502797SN/A        if isinstance(self, SimObject) and not isinstance(self, ParamContext):
6512797SN/A            self._ccObject.resume()
6522797SN/A        for child in self._children.itervalues():
6532797SN/A            child.resume()
6542797SN/A
6552797SN/A    def changeTiming(self, mode):
6562901SN/A        if isinstance(self, System):
6572797SN/A            self._ccObject.setMemoryMode(mode)
6582797SN/A        for child in self._children.itervalues():
6592797SN/A            child.changeTiming(mode)
6602797SN/A
6612797SN/A    def takeOverFrom(self, old_cpu):
6622797SN/A        cpu_ptr = cc_main.convertToBaseCPUPtr(old_cpu._ccObject)
6632797SN/A        self._ccObject.takeOverFrom(cpu_ptr)
6642797SN/A
6651692SN/A    # generate output file for 'dot' to display as a pretty graph.
6661692SN/A    # this code is currently broken.
6671342SN/A    def outputDot(self, dot):
6681342SN/A        label = "{%s|" % self.path
6691342SN/A        if isSimObject(self.realtype):
6701342SN/A            label +=  '%s|' % self.type
6711342SN/A
6721342SN/A        if self.children:
6731342SN/A            # instantiate children in same order they were added for
6741342SN/A            # backward compatibility (else we can end up with cpu1
6751342SN/A            # before cpu0).
6761342SN/A            for c in self.children:
6771342SN/A                dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
6781342SN/A
6791342SN/A        simobjs = []
6801342SN/A        for param in self.params:
6811342SN/A            try:
6821342SN/A                if param.value is None:
6831342SN/A                    raise AttributeError, 'Parameter with no value'
6841342SN/A
6851692SN/A                value = param.value
6861342SN/A                string = param.string(value)
6871587SN/A            except Exception, e:
6881605SN/A                msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
6891605SN/A                e.args = (msg, )
6901342SN/A                raise
6911605SN/A
6921692SN/A            if isSimObject(param.ptype) and string != "Null":
6931342SN/A                simobjs.append(string)
6941342SN/A            else:
6951342SN/A                label += '%s = %s\\n' % (param.name, string)
6961342SN/A
6971342SN/A        for so in simobjs:
6981342SN/A            label += "|<%s> %s" % (so, so)
6991587SN/A            dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
7001587SN/A                                    tailport="w"))
7011342SN/A        label += '}'
7021342SN/A        dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
7031342SN/A
7041342SN/A        # recursively dump out children
7051342SN/A        for c in self.children:
7061342SN/A            c.outputDot(dot)
7071342SN/A
7081692SN/Aclass ParamContext(SimObject):
7091692SN/A    pass
7101692SN/A
7113101Sstever@eecs.umich.edu# Function to provide to C++ so it can look up instances based on paths
7123101Sstever@eecs.umich.edudef resolveSimObject(name):
7133101Sstever@eecs.umich.edu    obj = instanceDict[name]
7143101Sstever@eecs.umich.edu    return obj.getCCObject()
715679SN/A
7161528SN/A# __all__ defines the list of symbols that get exported when
7171528SN/A# 'from config import *' is invoked.  Try to keep this reasonably
7181528SN/A# short to avoid polluting other namespaces.
7193101Sstever@eecs.umich.edu__all__ = ['SimObject', 'ParamContext']
7201692SN/A
7213102Sstever@eecs.umich.edu
7223102Sstever@eecs.umich.edu# see comment on imports at end of __init__.py.
7233102Sstever@eecs.umich.eduimport proxy
7243102Sstever@eecs.umich.eduimport cc_main
725