SimObject.py revision 3101
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
321692SN/Aimport m5
332763SN/Afrom m5 import panic, cc_main
341519SN/Afrom convert import *
351585SN/Afrom multidict import multidict
361438SN/A
371342SN/AnoDot = False
381342SN/Atry:
391378SN/A    import pydot
401342SN/Aexcept:
411378SN/A    noDot = True
42679SN/A
43679SN/A#####################################################################
44679SN/A#
45679SN/A# M5 Python Configuration Utility
46679SN/A#
47679SN/A# The basic idea is to write simple Python programs that build Python
481692SN/A# objects corresponding to M5 SimObjects for the desired simulation
49679SN/A# configuration.  For now, the Python emits a .ini file that can be
50679SN/A# parsed by M5.  In the future, some tighter integration between M5
51679SN/A# and the Python interpreter may allow bypassing the .ini file.
52679SN/A#
53679SN/A# Each SimObject class in M5 is represented by a Python class with the
54679SN/A# same name.  The Python inheritance tree mirrors the M5 C++ tree
55679SN/A# (e.g., SimpleCPU derives from BaseCPU in both cases, and all
56679SN/A# SimObjects inherit from a single SimObject base class).  To specify
57679SN/A# an instance of an M5 SimObject in a configuration, the user simply
58679SN/A# instantiates the corresponding Python object.  The parameters for
59679SN/A# that SimObject are given by assigning to attributes of the Python
60679SN/A# object, either using keyword assignment in the constructor or in
61679SN/A# separate assignment statements.  For example:
62679SN/A#
631692SN/A# cache = BaseCache(size='64KB')
64679SN/A# cache.hit_latency = 3
65679SN/A# cache.assoc = 8
66679SN/A#
67679SN/A# The magic lies in the mapping of the Python attributes for SimObject
68679SN/A# classes to the actual SimObject parameter specifications.  This
69679SN/A# allows parameter validity checking in the Python code.  Continuing
70679SN/A# the example above, the statements "cache.blurfl=3" or
71679SN/A# "cache.assoc='hello'" would both result in runtime errors in Python,
72679SN/A# since the BaseCache object has no 'blurfl' parameter and the 'assoc'
73679SN/A# parameter requires an integer, respectively.  This magic is done
74679SN/A# primarily by overriding the special __setattr__ method that controls
75679SN/A# assignment to object attributes.
76679SN/A#
77679SN/A# Once a set of Python objects have been instantiated in a hierarchy,
78679SN/A# calling 'instantiate(obj)' (where obj is the root of the hierarchy)
792740SN/A# will generate a .ini file.
80679SN/A#
81679SN/A#####################################################################
82679SN/A
832738SN/A# dict to look up SimObjects based on path
842738SN/AinstanceDict = {}
852738SN/A
862740SN/A# The metaclass for SimObject.  This class controls how new classes
872740SN/A# that derive from SimObject are instantiated, and provides inherited
882740SN/A# class behavior (just like a class controls how instances of that
892740SN/A# class are instantiated, and provides inherited instance behavior).
901692SN/Aclass MetaSimObject(type):
911427SN/A    # Attributes that can be set only at initialization time
921692SN/A    init_keywords = { 'abstract' : types.BooleanType,
931692SN/A                      'type' : types.StringType }
941427SN/A    # Attributes that can be set any time
953100SN/A    keywords = { 'check' : types.FunctionType,
963100SN/A                 'cxx_type' : types.StringType,
973100SN/A                 'cxx_predecls' : types.ListType,
983100SN/A                 'swig_predecls' : types.ListType }
99679SN/A
100679SN/A    # __new__ is called before __init__, and is where the statements
101679SN/A    # in the body of the class definition get loaded into the class's
1022740SN/A    # __dict__.  We intercept this to filter out parameter & port assignments
103679SN/A    # and only allow "private" attributes to be passed to the base
104679SN/A    # __new__ (starting with underscore).
1051310SN/A    def __new__(mcls, name, bases, dict):
1062740SN/A        # Copy "private" attributes, functions, and classes to the
1072740SN/A        # official dict.  Everything else goes in _init_dict to be
1082740SN/A        # filtered in __init__.
1092740SN/A        cls_dict = {}
1102740SN/A        value_dict = {}
1112740SN/A        for key,val in dict.items():
1122740SN/A            if key.startswith('_') or isinstance(val, (types.FunctionType,
1132740SN/A                                                       types.TypeType)):
1142740SN/A                cls_dict[key] = val
1152740SN/A            else:
1162740SN/A                # must be a param/port setting
1172740SN/A                value_dict[key] = val
1182740SN/A        cls_dict['_value_dict'] = value_dict
1191692SN/A        return super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
120679SN/A
1212711SN/A    # subclass initialization
122679SN/A    def __init__(cls, name, bases, dict):
1232711SN/A        # calls type.__init__()... I think that's a no-op, but leave
1242711SN/A        # it here just in case it's not.
1251692SN/A        super(MetaSimObject, cls).__init__(name, bases, dict)
1261310SN/A
1271427SN/A        # initialize required attributes
1282740SN/A
1292740SN/A        # class-only attributes
1302740SN/A        cls._params = multidict() # param descriptions
1312740SN/A        cls._ports = multidict()  # port descriptions
1322740SN/A
1332740SN/A        # class or instance attributes
1342740SN/A        cls._values = multidict()   # param values
1352740SN/A        cls._port_map = multidict() # port bindings
1362740SN/A        cls._instantiated = False # really instantiated, cloned, or subclassed
1371310SN/A
1381692SN/A        # We don't support multiple inheritance.  If you want to, you
1391585SN/A        # must fix multidict to deal with it properly.
1401692SN/A        if len(bases) > 1:
1411692SN/A            raise TypeError, "SimObjects do not support multiple inheritance"
1421692SN/A
1431692SN/A        base = bases[0]
1441692SN/A
1452740SN/A        # Set up general inheritance via multidicts.  A subclass will
1462740SN/A        # inherit all its settings from the base class.  The only time
1472740SN/A        # the following is not true is when we define the SimObject
1482740SN/A        # class itself (in which case the multidicts have no parent).
1491692SN/A        if isinstance(base, MetaSimObject):
1501692SN/A            cls._params.parent = base._params
1512740SN/A            cls._ports.parent = base._ports
1521692SN/A            cls._values.parent = base._values
1532740SN/A            cls._port_map.parent = base._port_map
1542740SN/A            # mark base as having been subclassed
1552712SN/A            base._instantiated = True
1561692SN/A
1572740SN/A        # Now process the _value_dict items.  They could be defining
1582740SN/A        # new (or overriding existing) parameters or ports, setting
1592740SN/A        # class keywords (e.g., 'abstract'), or setting parameter
1602740SN/A        # values or port bindings.  The first 3 can only be set when
1612740SN/A        # the class is defined, so we handle them here.  The others
1622740SN/A        # can be set later too, so just emulate that by calling
1632740SN/A        # setattr().
1642740SN/A        for key,val in cls._value_dict.items():
1651527SN/A            # param descriptions
1662740SN/A            if isinstance(val, ParamDesc):
1671585SN/A                cls._new_param(key, val)
1681427SN/A
1692738SN/A            # port objects
1702738SN/A            elif isinstance(val, Port):
1712738SN/A                cls._ports[key] = val
1722738SN/A
1731427SN/A            # init-time-only keywords
1741427SN/A            elif cls.init_keywords.has_key(key):
1751427SN/A                cls._set_keyword(key, val, cls.init_keywords[key])
1761427SN/A
1771427SN/A            # default: use normal path (ends up in __setattr__)
1781427SN/A            else:
1791427SN/A                setattr(cls, key, val)
1801427SN/A
1813100SN/A        cls.cxx_type = cls.type + '*'
1823100SN/A        # A forward class declaration is sufficient since we are just
1833100SN/A        # declaring a pointer.
1843100SN/A        cls.cxx_predecls = ['class %s;' % cls.type]
1853100SN/A        cls.swig_predecls = cls.cxx_predecls
1863100SN/A
1871427SN/A    def _set_keyword(cls, keyword, val, kwtype):
1881427SN/A        if not isinstance(val, kwtype):
1891427SN/A            raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
1901427SN/A                  (keyword, type(val), kwtype)
1911427SN/A        if isinstance(val, types.FunctionType):
1921427SN/A            val = classmethod(val)
1931427SN/A        type.__setattr__(cls, keyword, val)
1941427SN/A
1953100SN/A    def _new_param(cls, name, pdesc):
1963100SN/A        # each param desc should be uniquely assigned to one variable
1973100SN/A        assert(not hasattr(pdesc, 'name'))
1983100SN/A        pdesc.name = name
1993100SN/A        cls._params[name] = pdesc
2003100SN/A        if hasattr(pdesc, 'default'):
2013100SN/A            setattr(cls, name, pdesc.default)
2021585SN/A
2031310SN/A    # Set attribute (called on foo.attr = value when foo is an
2041310SN/A    # instance of class cls).
2051310SN/A    def __setattr__(cls, attr, value):
2061310SN/A        # normal processing for private attributes
2071310SN/A        if attr.startswith('_'):
2081310SN/A            type.__setattr__(cls, attr, value)
2091310SN/A            return
2101310SN/A
2111310SN/A        if cls.keywords.has_key(attr):
2121427SN/A            cls._set_keyword(attr, value, cls.keywords[attr])
2131310SN/A            return
2141310SN/A
2152738SN/A        if cls._ports.has_key(attr):
2162738SN/A            self._ports[attr].connect(self, attr, value)
2172738SN/A            return
2182738SN/A
2192740SN/A        if isSimObjectOrSequence(value) and cls._instantiated:
2202740SN/A            raise RuntimeError, \
2212740SN/A                  "cannot set SimObject parameter '%s' after\n" \
2222740SN/A                  "    class %s has been instantiated or subclassed" \
2232740SN/A                  % (attr, cls.__name__)
2242740SN/A
2252740SN/A        # check for param
2261585SN/A        param = cls._params.get(attr, None)
2271310SN/A        if param:
2281527SN/A            try:
2291692SN/A                cls._values[attr] = param.convert(value)
2301585SN/A            except Exception, e:
2311605SN/A                msg = "%s\nError setting param %s.%s to %s\n" % \
2321590SN/A                      (e, cls.__name__, attr, value)
2331605SN/A                e.args = (msg, )
2341605SN/A                raise
2352714SN/A        elif isSimObjectOrSequence(value):
2362740SN/A            # if RHS is a SimObject, it's an implicit child assignment
2372740SN/A            cls._values[attr] = value
2381310SN/A        else:
2391310SN/A            raise AttributeError, \
2402831SN/A                  "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
2411310SN/A
2421585SN/A    def __getattr__(cls, attr):
2431692SN/A        if cls._values.has_key(attr):
2441692SN/A            return cls._values[attr]
2451585SN/A
2461585SN/A        raise AttributeError, \
2471585SN/A              "object '%s' has no attribute '%s'" % (cls.__name__, attr)
2481585SN/A
2493100SN/A    def __str__(cls):
2503100SN/A        return cls.__name__
2513100SN/A
2523100SN/A    def cxx_decl(cls):
2533100SN/A        code = "#ifndef __PARAMS__%s\n#define __PARAMS__%s\n\n" % (cls, cls)
2543100SN/A
2553100SN/A        if str(cls) != 'SimObject':
2563100SN/A            base = cls.__bases__[0].type
2573100SN/A        else:
2583100SN/A            base = None
2593100SN/A
2603100SN/A        # The 'dict' attribute restricts us to the params declared in
2613100SN/A        # the object itself, not including inherited params (which
2623100SN/A        # will also be inherited from the base class's param struct
2633100SN/A        # here).
2643100SN/A        params = cls._params.dict.values()
2653100SN/A        try:
2663100SN/A            ptypes = [p.ptype for p in params]
2673100SN/A        except:
2683100SN/A            print cls, p, p.ptype_str
2693100SN/A            print params
2703100SN/A            raise
2713100SN/A
2723100SN/A        # get a list of lists of predeclaration lines
2733100SN/A        predecls = [p.cxx_predecls() for p in params]
2743100SN/A        # flatten
2753100SN/A        predecls = reduce(lambda x,y:x+y, predecls, [])
2763100SN/A        # remove redundant lines
2773100SN/A        predecls2 = []
2783100SN/A        for pd in predecls:
2793100SN/A            if pd not in predecls2:
2803100SN/A                predecls2.append(pd)
2813100SN/A        predecls2.sort()
2823100SN/A        code += "\n".join(predecls2)
2833100SN/A        code += "\n\n";
2843100SN/A
2853100SN/A        if base:
2863100SN/A            code += '#include "params/%s.hh"\n\n' % base
2873100SN/A
2883100SN/A        # Generate declarations for locally defined enumerations.
2893100SN/A        enum_ptypes = [t for t in ptypes if issubclass(t, Enum)]
2903100SN/A        if enum_ptypes:
2913100SN/A            code += "\n".join([t.cxx_decl() for t in enum_ptypes])
2923100SN/A            code += "\n\n"
2933100SN/A
2943100SN/A        # now generate the actual param struct
2953100SN/A        code += "struct %sParams" % cls
2963100SN/A        if base:
2973100SN/A            code += " : public %sParams" % base
2983100SN/A        code += " {\n"
2993100SN/A        decls = [p.cxx_decl() for p in params]
3003100SN/A        decls.sort()
3013100SN/A        code += "".join(["    %s\n" % d for d in decls])
3023100SN/A        code += "};\n"
3033100SN/A
3043100SN/A        # close #ifndef __PARAMS__* guard
3053100SN/A        code += "\n#endif\n"
3063100SN/A        return code
3073100SN/A
3083100SN/A    def swig_decl(cls):
3093100SN/A
3103100SN/A        code = '%%module %sParams\n' % cls
3113100SN/A
3123100SN/A        if str(cls) != 'SimObject':
3133100SN/A            base = cls.__bases__[0].type
3143100SN/A        else:
3153100SN/A            base = None
3163100SN/A
3173100SN/A        # The 'dict' attribute restricts us to the params declared in
3183100SN/A        # the object itself, not including inherited params (which
3193100SN/A        # will also be inherited from the base class's param struct
3203100SN/A        # here).
3213100SN/A        params = cls._params.dict.values()
3223100SN/A        ptypes = [p.ptype for p in params]
3233100SN/A
3243100SN/A        # get a list of lists of predeclaration lines
3253100SN/A        predecls = [p.swig_predecls() for p in params]
3263100SN/A        # flatten
3273100SN/A        predecls = reduce(lambda x,y:x+y, predecls, [])
3283100SN/A        # remove redundant lines
3293100SN/A        predecls2 = []
3303100SN/A        for pd in predecls:
3313100SN/A            if pd not in predecls2:
3323100SN/A                predecls2.append(pd)
3333100SN/A        predecls2.sort()
3343100SN/A        code += "\n".join(predecls2)
3353100SN/A        code += "\n\n";
3363100SN/A
3373100SN/A        if base:
3383100SN/A            code += '%%import "python/m5/swig/%sParams.i"\n\n' % base
3393100SN/A
3403100SN/A        code += '%{\n'
3413100SN/A        code += '#include "params/%s.hh"\n' % cls
3423100SN/A        code += '%}\n\n'
3433100SN/A        code += '%%include "params/%s.hh"\n\n' % cls
3443100SN/A
3453100SN/A        return code
3463100SN/A
3472740SN/A# The SimObject class is the root of the special hierarchy.  Most of
348679SN/A# the code in this class deals with the configuration hierarchy itself
349679SN/A# (parent/child node relationships).
3501692SN/Aclass SimObject(object):
3511692SN/A    # Specify metaclass.  Any class inheriting from SimObject will
352679SN/A    # get this metaclass.
3531692SN/A    __metaclass__ = MetaSimObject
3543100SN/A    type = 'SimObject'
3553100SN/A
3563100SN/A    name = Param.String("Object name")
357679SN/A
3582740SN/A    # Initialize new instance.  For objects with SimObject-valued
3592740SN/A    # children, we need to recursively clone the classes represented
3602740SN/A    # by those param values as well in a consistent "deep copy"-style
3612740SN/A    # fashion.  That is, we want to make sure that each instance is
3622740SN/A    # cloned only once, and that if there are multiple references to
3632740SN/A    # the same original object, we end up with the corresponding
3642740SN/A    # cloned references all pointing to the same cloned instance.
3652740SN/A    def __init__(self, **kwargs):
3662740SN/A        ancestor = kwargs.get('_ancestor')
3672740SN/A        memo_dict = kwargs.get('_memo')
3682740SN/A        if memo_dict is None:
3692740SN/A            # prepare to memoize any recursively instantiated objects
3702740SN/A            memo_dict = {}
3712740SN/A        elif ancestor:
3722740SN/A            # memoize me now to avoid problems with recursive calls
3732740SN/A            memo_dict[ancestor] = self
3742711SN/A
3752740SN/A        if not ancestor:
3762740SN/A            ancestor = self.__class__
3772740SN/A        ancestor._instantiated = True
3782711SN/A
3792740SN/A        # initialize required attributes
3802740SN/A        self._parent = None
3812740SN/A        self._children = {}
3822740SN/A        self._ccObject = None  # pointer to C++ object
3832740SN/A        self._instantiated = False # really "cloned"
3842712SN/A
3852711SN/A        # Inherit parameter values from class using multidict so
3862711SN/A        # individual value settings can be overridden.
3872740SN/A        self._values = multidict(ancestor._values)
3882740SN/A        # clone SimObject-valued parameters
3892740SN/A        for key,val in ancestor._values.iteritems():
3902740SN/A            if isSimObject(val):
3912740SN/A                setattr(self, key, val(_memo=memo_dict))
3922740SN/A            elif isSimObjectSequence(val) and len(val):
3932740SN/A                setattr(self, key, [ v(_memo=memo_dict) for v in val ])
3942740SN/A        # clone port references.  no need to use a multidict here
3952740SN/A        # since we will be creating new references for all ports.
3962740SN/A        self._port_map = {}
3972740SN/A        for key,val in ancestor._port_map.iteritems():
3982740SN/A            self._port_map[key] = applyOrMap(val, 'clone', memo_dict)
3991692SN/A        # apply attribute assignments from keyword args, if any
4001692SN/A        for key,val in kwargs.iteritems():
4011692SN/A            setattr(self, key, val)
402679SN/A
4032740SN/A    # "Clone" the current instance by creating another instance of
4042740SN/A    # this instance's class, but that inherits its parameter values
4052740SN/A    # and port mappings from the current instance.  If we're in a
4062740SN/A    # "deep copy" recursive clone, check the _memo dict to see if
4072740SN/A    # we've already cloned this instance.
4081692SN/A    def __call__(self, **kwargs):
4092740SN/A        memo_dict = kwargs.get('_memo')
4102740SN/A        if memo_dict is None:
4112740SN/A            # no memo_dict: must be top-level clone operation.
4122740SN/A            # this is only allowed at the root of a hierarchy
4132740SN/A            if self._parent:
4142740SN/A                raise RuntimeError, "attempt to clone object %s " \
4152740SN/A                      "not at the root of a tree (parent = %s)" \
4162740SN/A                      % (self, self._parent)
4172740SN/A            # create a new dict and use that.
4182740SN/A            memo_dict = {}
4192740SN/A            kwargs['_memo'] = memo_dict
4202740SN/A        elif memo_dict.has_key(self):
4212740SN/A            # clone already done & memoized
4222740SN/A            return memo_dict[self]
4232740SN/A        return self.__class__(_ancestor = self, **kwargs)
4241343SN/A
4251692SN/A    def __getattr__(self, attr):
4262738SN/A        if self._ports.has_key(attr):
4272738SN/A            # return reference that can be assigned to another port
4282738SN/A            # via __setattr__
4292738SN/A            return self._ports[attr].makeRef(self, attr)
4302738SN/A
4311692SN/A        if self._values.has_key(attr):
4321692SN/A            return self._values[attr]
4331427SN/A
4341692SN/A        raise AttributeError, "object '%s' has no attribute '%s'" \
4351692SN/A              % (self.__class__.__name__, attr)
4361427SN/A
4371692SN/A    # Set attribute (called on foo.attr = value when foo is an
4381692SN/A    # instance of class cls).
4391692SN/A    def __setattr__(self, attr, value):
4401692SN/A        # normal processing for private attributes
4411692SN/A        if attr.startswith('_'):
4421692SN/A            object.__setattr__(self, attr, value)
4431692SN/A            return
4441427SN/A
4452738SN/A        if self._ports.has_key(attr):
4462738SN/A            # set up port connection
4472738SN/A            self._ports[attr].connect(self, attr, value)
4482738SN/A            return
4492738SN/A
4502740SN/A        if isSimObjectOrSequence(value) and self._instantiated:
4512740SN/A            raise RuntimeError, \
4522740SN/A                  "cannot set SimObject parameter '%s' after\n" \
4532740SN/A                  "    instance been cloned %s" % (attr, `self`)
4542740SN/A
4551692SN/A        # must be SimObject param
4561692SN/A        param = self._params.get(attr, None)
4571692SN/A        if param:
4581310SN/A            try:
4591692SN/A                value = param.convert(value)
4601587SN/A            except Exception, e:
4611692SN/A                msg = "%s\nError setting param %s.%s to %s\n" % \
4621692SN/A                      (e, self.__class__.__name__, attr, value)
4631605SN/A                e.args = (msg, )
4641605SN/A                raise
4652714SN/A        elif isSimObjectOrSequence(value):
4661692SN/A            pass
4671692SN/A        else:
4681692SN/A            raise AttributeError, "Class %s has no parameter %s" \
4691692SN/A                  % (self.__class__.__name__, attr)
4701310SN/A
4711693SN/A        # clear out old child with this name, if any
4721693SN/A        self.clear_child(attr)
4731693SN/A
4741692SN/A        if isSimObject(value):
4751692SN/A            value.set_path(self, attr)
4762714SN/A        elif isSimObjectSequence(value):
4771692SN/A            value = SimObjVector(value)
4781692SN/A            [v.set_path(self, "%s%d" % (attr, i)) for i,v in enumerate(value)]
4791310SN/A
4801692SN/A        self._values[attr] = value
4811310SN/A
4821692SN/A    # this hack allows tacking a '[0]' onto parameters that may or may
4831692SN/A    # not be vectors, and always getting the first element (e.g. cpus)
4841692SN/A    def __getitem__(self, key):
4851692SN/A        if key == 0:
4861692SN/A            return self
4871692SN/A        raise TypeError, "Non-zero index '%s' to SimObject" % key
4881310SN/A
4891693SN/A    # clear out children with given name, even if it's a vector
4901693SN/A    def clear_child(self, name):
4911693SN/A        if not self._children.has_key(name):
4921693SN/A            return
4931693SN/A        child = self._children[name]
4941693SN/A        if isinstance(child, SimObjVector):
4951693SN/A            for i in xrange(len(child)):
4961693SN/A                del self._children["s%d" % (name, i)]
4971693SN/A        del self._children[name]
4981693SN/A
4991692SN/A    def add_child(self, name, value):
5001692SN/A        self._children[name] = value
5011310SN/A
5021692SN/A    def set_path(self, parent, name):
5032740SN/A        if not self._parent:
5041692SN/A            self._parent = parent
5051692SN/A            self._name = name
5061692SN/A            parent.add_child(name, self)
5071310SN/A
5081692SN/A    def path(self):
5092740SN/A        if not self._parent:
5101692SN/A            return 'root'
5111692SN/A        ppath = self._parent.path()
5121692SN/A        if ppath == 'root':
5131692SN/A            return self._name
5141692SN/A        return ppath + "." + self._name
5151310SN/A
5161692SN/A    def __str__(self):
5171692SN/A        return self.path()
5181310SN/A
5191692SN/A    def ini_str(self):
5201692SN/A        return self.path()
5211310SN/A
5221692SN/A    def find_any(self, ptype):
5231692SN/A        if isinstance(self, ptype):
5241692SN/A            return self, True
5251310SN/A
5261692SN/A        found_obj = None
5271692SN/A        for child in self._children.itervalues():
5281692SN/A            if isinstance(child, ptype):
5291692SN/A                if found_obj != None and child != found_obj:
5301692SN/A                    raise AttributeError, \
5311692SN/A                          'parent.any matched more than one: %s %s' % \
5321814SN/A                          (found_obj.path, child.path)
5331692SN/A                found_obj = child
5341692SN/A        # search param space
5351692SN/A        for pname,pdesc in self._params.iteritems():
5361692SN/A            if issubclass(pdesc.ptype, ptype):
5371692SN/A                match_obj = self._values[pname]
5381692SN/A                if found_obj != None and found_obj != match_obj:
5391692SN/A                    raise AttributeError, \
5401692SN/A                          'parent.any matched more than one: %s' % obj.path
5411692SN/A                found_obj = match_obj
5421692SN/A        return found_obj, found_obj != None
5431692SN/A
5441815SN/A    def unproxy(self, base):
5451815SN/A        return self
5461815SN/A
5471692SN/A    def print_ini(self):
5481692SN/A        print '[' + self.path() + ']'	# .ini section header
5491692SN/A
5502738SN/A        instanceDict[self.path()] = self
5512738SN/A
5521692SN/A        if hasattr(self, 'type') and not isinstance(self, ParamContext):
5531799SN/A            print 'type=%s' % self.type
5541692SN/A
5551692SN/A        child_names = self._children.keys()
5561692SN/A        child_names.sort()
5571692SN/A        np_child_names = [c for c in child_names \
5581692SN/A                          if not isinstance(self._children[c], ParamContext)]
5591692SN/A        if len(np_child_names):
5601799SN/A            print 'children=%s' % ' '.join(np_child_names)
5611692SN/A
5621692SN/A        param_names = self._params.keys()
5631692SN/A        param_names.sort()
5641692SN/A        for param in param_names:
5651692SN/A            value = self._values.get(param, None)
5661692SN/A            if value != None:
5671692SN/A                if isproxy(value):
5681692SN/A                    try:
5691692SN/A                        value = value.unproxy(self)
5701692SN/A                    except:
5711692SN/A                        print >> sys.stderr, \
5721692SN/A                              "Error in unproxying param '%s' of %s" % \
5731692SN/A                              (param, self.path())
5741692SN/A                        raise
5751692SN/A                    setattr(self, param, value)
5761799SN/A                print '%s=%s' % (param, self._values[param].ini_str())
5771692SN/A
5781692SN/A        print	# blank line between objects
5791692SN/A
5801692SN/A        for child in child_names:
5811692SN/A            self._children[child].print_ini()
5821692SN/A
5832738SN/A    # Call C++ to create C++ object corresponding to this object and
5842738SN/A    # (recursively) all its children
5852738SN/A    def createCCObject(self):
5862740SN/A        self.getCCObject() # force creation
5872738SN/A        for child in self._children.itervalues():
5882738SN/A            child.createCCObject()
5892738SN/A
5902740SN/A    # Get C++ object corresponding to this object, calling C++ if
5912740SN/A    # necessary to construct it.  Does *not* recursively create
5922740SN/A    # children.
5932740SN/A    def getCCObject(self):
5942740SN/A        if not self._ccObject:
5952740SN/A            self._ccObject = -1 # flag to catch cycles in recursion
5962763SN/A            self._ccObject = cc_main.createSimObject(self.path())
5972740SN/A        elif self._ccObject == -1:
5982740SN/A            raise RuntimeError, "%s: recursive call to getCCObject()" \
5992740SN/A                  % self.path()
6002740SN/A        return self._ccObject
6012740SN/A
6022738SN/A    # Create C++ port connections corresponding to the connections in
6032738SN/A    # _port_map (& recursively for all children)
6042738SN/A    def connectPorts(self):
6052738SN/A        for portRef in self._port_map.itervalues():
6062738SN/A            applyOrMap(portRef, 'ccConnect')
6072738SN/A        for child in self._children.itervalues():
6082738SN/A            child.connectPorts()
6092738SN/A
6102839SN/A    def startDrain(self, drain_event, recursive):
6112797SN/A        count = 0
6122797SN/A        # ParamContexts don't serialize
6132797SN/A        if isinstance(self, SimObject) and not isinstance(self, ParamContext):
6142901SN/A            count += self._ccObject.drain(drain_event)
6152797SN/A        if recursive:
6162797SN/A            for child in self._children.itervalues():
6172839SN/A                count += child.startDrain(drain_event, True)
6182797SN/A        return count
6192797SN/A
6202797SN/A    def resume(self):
6212797SN/A        if isinstance(self, SimObject) and not isinstance(self, ParamContext):
6222797SN/A            self._ccObject.resume()
6232797SN/A        for child in self._children.itervalues():
6242797SN/A            child.resume()
6252797SN/A
6262797SN/A    def changeTiming(self, mode):
6272901SN/A        if isinstance(self, System):
6282797SN/A            self._ccObject.setMemoryMode(mode)
6292797SN/A        for child in self._children.itervalues():
6302797SN/A            child.changeTiming(mode)
6312797SN/A
6322797SN/A    def takeOverFrom(self, old_cpu):
6332797SN/A        cpu_ptr = cc_main.convertToBaseCPUPtr(old_cpu._ccObject)
6342797SN/A        self._ccObject.takeOverFrom(cpu_ptr)
6352797SN/A
6361692SN/A    # generate output file for 'dot' to display as a pretty graph.
6371692SN/A    # this code is currently broken.
6381342SN/A    def outputDot(self, dot):
6391342SN/A        label = "{%s|" % self.path
6401342SN/A        if isSimObject(self.realtype):
6411342SN/A            label +=  '%s|' % self.type
6421342SN/A
6431342SN/A        if self.children:
6441342SN/A            # instantiate children in same order they were added for
6451342SN/A            # backward compatibility (else we can end up with cpu1
6461342SN/A            # before cpu0).
6471342SN/A            for c in self.children:
6481342SN/A                dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
6491342SN/A
6501342SN/A        simobjs = []
6511342SN/A        for param in self.params:
6521342SN/A            try:
6531342SN/A                if param.value is None:
6541342SN/A                    raise AttributeError, 'Parameter with no value'
6551342SN/A
6561692SN/A                value = param.value
6571342SN/A                string = param.string(value)
6581587SN/A            except Exception, e:
6591605SN/A                msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
6601605SN/A                e.args = (msg, )
6611342SN/A                raise
6621605SN/A
6631692SN/A            if isSimObject(param.ptype) and string != "Null":
6641342SN/A                simobjs.append(string)
6651342SN/A            else:
6661342SN/A                label += '%s = %s\\n' % (param.name, string)
6671342SN/A
6681342SN/A        for so in simobjs:
6691342SN/A            label += "|<%s> %s" % (so, so)
6701587SN/A            dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
6711587SN/A                                    tailport="w"))
6721342SN/A        label += '}'
6731342SN/A        dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
6741342SN/A
6751342SN/A        # recursively dump out children
6761342SN/A        for c in self.children:
6771342SN/A            c.outputDot(dot)
6781342SN/A
6791692SN/Aclass ParamContext(SimObject):
6801692SN/A    pass
6811692SN/A
682702SN/A# Special class for NULL pointers.  Note the special check in
683702SN/A# make_param_value() above that lets these be assigned where a
684702SN/A# SimObject is required.
6851310SN/A# only one copy of a particular node
686702SN/Aclass NullSimObject(object):
6871310SN/A    __metaclass__ = Singleton
6881310SN/A
6891310SN/A    def __call__(cls):
6901310SN/A        return cls
6911310SN/A
6921310SN/A    def _instantiate(self, parent = None, path = ''):
693702SN/A        pass
694702SN/A
6951692SN/A    def ini_str(self):
6961692SN/A        return 'Null'
697702SN/A
6981815SN/A    def unproxy(self, base):
6991799SN/A        return self
7001799SN/A
7011799SN/A    def set_path(self, parent, name):
7021799SN/A        pass
7031799SN/A    def __str__(self):
7041799SN/A        return 'Null'
7051799SN/A
706702SN/A# The only instance you'll ever need...
7071310SN/ANull = NULL = NullSimObject()
708679SN/A
7093101Sstever@eecs.umich.edudef isSimObject(value):
7103101Sstever@eecs.umich.edu    return isinstance(value, SimObject)
711679SN/A
7123101Sstever@eecs.umich.edudef isNullPointer(value):
7133101Sstever@eecs.umich.edu    return isinstance(value, NullSimObject)
714679SN/A
7153101Sstever@eecs.umich.edudef isSimObjectSequence(value):
7163101Sstever@eecs.umich.edu    if not isinstance(value, (list, tuple)) or len(value) == 0:
7173101Sstever@eecs.umich.edu        return False
718679SN/A
7193101Sstever@eecs.umich.edu    for val in value:
7203101Sstever@eecs.umich.edu        if not isNullPointer(val) and not isSimObject(val):
7213101Sstever@eecs.umich.edu            return False
7221427SN/A
7233101Sstever@eecs.umich.edu    return True
7243100SN/A
7253101Sstever@eecs.umich.edudef isSimObjectOrSequence(value):
7263101Sstever@eecs.umich.edu    return isSimObject(value) or isSimObjectSequence(value)
7271427SN/A
7283101Sstever@eecs.umich.edu# Function to provide to C++ so it can look up instances based on paths
7293101Sstever@eecs.umich.edudef resolveSimObject(name):
7303101Sstever@eecs.umich.edu    obj = instanceDict[name]
7313101Sstever@eecs.umich.edu    return obj.getCCObject()
732679SN/A
7331528SN/A# __all__ defines the list of symbols that get exported when
7341528SN/A# 'from config import *' is invoked.  Try to keep this reasonably
7351528SN/A# short to avoid polluting other namespaces.
7363101Sstever@eecs.umich.edu__all__ = ['SimObject', 'ParamContext']
7371692SN/A
738