SimObject.py revision 7673
12740SN/A# Copyright (c) 2004-2006 The Regents of The University of Michigan
27534Ssteve.reinhardt@amd.com# Copyright (c) 2010 Advanced Micro Devices, Inc.
31046SN/A# All rights reserved.
41046SN/A#
51046SN/A# Redistribution and use in source and binary forms, with or without
61046SN/A# modification, are permitted provided that the following conditions are
71046SN/A# met: redistributions of source code must retain the above copyright
81046SN/A# notice, this list of conditions and the following disclaimer;
91046SN/A# redistributions in binary form must reproduce the above copyright
101046SN/A# notice, this list of conditions and the following disclaimer in the
111046SN/A# documentation and/or other materials provided with the distribution;
121046SN/A# neither the name of the copyright holders nor the names of its
131046SN/A# contributors may be used to endorse or promote products derived from
141046SN/A# this software without specific prior written permission.
151046SN/A#
161046SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
171046SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
181046SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
191046SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
201046SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
211046SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
221046SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
231046SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
241046SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
251046SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
261046SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
272665SN/A#
282665SN/A# Authors: Steve Reinhardt
292665SN/A#          Nathan Binkert
301046SN/A
315766Snate@binkert.orgimport sys
327673Snate@binkert.orgfrom types import FunctionType, MethodType
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
487528Ssteve.reinhardt@amd.comfrom m5.params import ParamDesc, VectorParamDesc, \
497528Ssteve.reinhardt@amd.com     isNullPointer, SimObjectVector
503102Sstever@eecs.umich.edu
516654Snate@binkert.orgfrom m5.proxy import *
526654Snate@binkert.orgfrom m5.proxy import isproxy
53679SN/A
54679SN/A#####################################################################
55679SN/A#
56679SN/A# M5 Python Configuration Utility
57679SN/A#
58679SN/A# The basic idea is to write simple Python programs that build Python
591692SN/A# objects corresponding to M5 SimObjects for the desired simulation
60679SN/A# configuration.  For now, the Python emits a .ini file that can be
61679SN/A# parsed by M5.  In the future, some tighter integration between M5
62679SN/A# and the Python interpreter may allow bypassing the .ini file.
63679SN/A#
64679SN/A# Each SimObject class in M5 is represented by a Python class with the
65679SN/A# same name.  The Python inheritance tree mirrors the M5 C++ tree
66679SN/A# (e.g., SimpleCPU derives from BaseCPU in both cases, and all
67679SN/A# SimObjects inherit from a single SimObject base class).  To specify
68679SN/A# an instance of an M5 SimObject in a configuration, the user simply
69679SN/A# instantiates the corresponding Python object.  The parameters for
70679SN/A# that SimObject are given by assigning to attributes of the Python
71679SN/A# object, either using keyword assignment in the constructor or in
72679SN/A# separate assignment statements.  For example:
73679SN/A#
741692SN/A# cache = BaseCache(size='64KB')
75679SN/A# cache.hit_latency = 3
76679SN/A# cache.assoc = 8
77679SN/A#
78679SN/A# The magic lies in the mapping of the Python attributes for SimObject
79679SN/A# classes to the actual SimObject parameter specifications.  This
80679SN/A# allows parameter validity checking in the Python code.  Continuing
81679SN/A# the example above, the statements "cache.blurfl=3" or
82679SN/A# "cache.assoc='hello'" would both result in runtime errors in Python,
83679SN/A# since the BaseCache object has no 'blurfl' parameter and the 'assoc'
84679SN/A# parameter requires an integer, respectively.  This magic is done
85679SN/A# primarily by overriding the special __setattr__ method that controls
86679SN/A# assignment to object attributes.
87679SN/A#
88679SN/A# Once a set of Python objects have been instantiated in a hierarchy,
89679SN/A# calling 'instantiate(obj)' (where obj is the root of the hierarchy)
902740SN/A# will generate a .ini file.
91679SN/A#
92679SN/A#####################################################################
93679SN/A
944762Snate@binkert.org# list of all SimObject classes
954762Snate@binkert.orgallClasses = {}
964762Snate@binkert.org
972738SN/A# dict to look up SimObjects based on path
982738SN/AinstanceDict = {}
992738SN/A
1007673Snate@binkert.orgdef default_cxx_predecls(cls, code):
1017673Snate@binkert.org    '''A forward class declaration is sufficient since we are
1027673Snate@binkert.org    just declaring a pointer.'''
1037673Snate@binkert.org
1047673Snate@binkert.org    class_path = cls._value_dict['cxx_class'].split('::')
1057673Snate@binkert.org    for ns in class_path[:-1]:
1067673Snate@binkert.org        code('namespace $ns {')
1077673Snate@binkert.org    code('class $0;', class_path[-1])
1087673Snate@binkert.org    for ns in reversed(class_path[:-1]):
1097673Snate@binkert.org        code('/* namespace $ns */ }')
1107673Snate@binkert.org
1117673Snate@binkert.orgdef default_swig_objdecls(cls, code):
1127673Snate@binkert.org    class_path = cls.cxx_class.split('::')
1137673Snate@binkert.org    classname = class_path[-1]
1147673Snate@binkert.org    namespaces = class_path[:-1]
1157673Snate@binkert.org
1167673Snate@binkert.org    for ns in namespaces:
1177673Snate@binkert.org        code('namespace $ns {')
1187673Snate@binkert.org
1197673Snate@binkert.org    if namespaces:
1207673Snate@binkert.org        code('// avoid name conflicts')
1217673Snate@binkert.org        sep_string = '_COLONS_'
1227673Snate@binkert.org        flat_name = sep_string.join(class_path)
1237673Snate@binkert.org        code('%rename($flat_name) $classname;')
1247673Snate@binkert.org
1257673Snate@binkert.org    code()
1267673Snate@binkert.org    code('// stop swig from creating/wrapping default ctor/dtor')
1277673Snate@binkert.org    code('%nodefault $classname;')
1287673Snate@binkert.org    code('class $classname')
1297673Snate@binkert.org    if cls._base:
1307673Snate@binkert.org        code('    : public ${{cls._base.cxx_class}}')
1317673Snate@binkert.org    code('{};')
1327673Snate@binkert.org
1337673Snate@binkert.org    for ns in reversed(namespaces):
1347673Snate@binkert.org        code('/* namespace $ns */ }')
1357673Snate@binkert.org
1367673Snate@binkert.orgdef public_value(key, value):
1377673Snate@binkert.org    return key.startswith('_') or \
1387673Snate@binkert.org               isinstance(value, (FunctionType, MethodType, classmethod, type))
1397673Snate@binkert.org
1402740SN/A# The metaclass for SimObject.  This class controls how new classes
1412740SN/A# that derive from SimObject are instantiated, and provides inherited
1422740SN/A# class behavior (just like a class controls how instances of that
1432740SN/A# class are instantiated, and provides inherited instance behavior).
1441692SN/Aclass MetaSimObject(type):
1451427SN/A    # Attributes that can be set only at initialization time
1467493Ssteve.reinhardt@amd.com    init_keywords = { 'abstract' : bool,
1477493Ssteve.reinhardt@amd.com                      'cxx_class' : str,
1487493Ssteve.reinhardt@amd.com                      'cxx_type' : str,
1497673Snate@binkert.org                      'cxx_predecls'  : MethodType,
1507673Snate@binkert.org                      'swig_objdecls' : MethodType,
1517673Snate@binkert.org                      'swig_predecls' : MethodType,
1527493Ssteve.reinhardt@amd.com                      'type' : str }
1531427SN/A    # Attributes that can be set any time
1547493Ssteve.reinhardt@amd.com    keywords = { 'check' : FunctionType }
155679SN/A
156679SN/A    # __new__ is called before __init__, and is where the statements
157679SN/A    # in the body of the class definition get loaded into the class's
1582740SN/A    # __dict__.  We intercept this to filter out parameter & port assignments
159679SN/A    # and only allow "private" attributes to be passed to the base
160679SN/A    # __new__ (starting with underscore).
1611310SN/A    def __new__(mcls, name, bases, dict):
1626654Snate@binkert.org        assert name not in allClasses, "SimObject %s already present" % name
1634762Snate@binkert.org
1642740SN/A        # Copy "private" attributes, functions, and classes to the
1652740SN/A        # official dict.  Everything else goes in _init_dict to be
1662740SN/A        # filtered in __init__.
1672740SN/A        cls_dict = {}
1682740SN/A        value_dict = {}
1692740SN/A        for key,val in dict.items():
1707673Snate@binkert.org            if public_value(key, val):
1712740SN/A                cls_dict[key] = val
1722740SN/A            else:
1732740SN/A                # must be a param/port setting
1742740SN/A                value_dict[key] = val
1754762Snate@binkert.org        if 'abstract' not in value_dict:
1764762Snate@binkert.org            value_dict['abstract'] = False
1772740SN/A        cls_dict['_value_dict'] = value_dict
1784762Snate@binkert.org        cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
1794762Snate@binkert.org        if 'type' in value_dict:
1804762Snate@binkert.org            allClasses[name] = cls
1814762Snate@binkert.org        return cls
182679SN/A
1832711SN/A    # subclass initialization
184679SN/A    def __init__(cls, name, bases, dict):
1852711SN/A        # calls type.__init__()... I think that's a no-op, but leave
1862711SN/A        # it here just in case it's not.
1871692SN/A        super(MetaSimObject, cls).__init__(name, bases, dict)
1881310SN/A
1891427SN/A        # initialize required attributes
1902740SN/A
1912740SN/A        # class-only attributes
1922740SN/A        cls._params = multidict() # param descriptions
1932740SN/A        cls._ports = multidict()  # port descriptions
1942740SN/A
1952740SN/A        # class or instance attributes
1962740SN/A        cls._values = multidict()   # param values
1977528Ssteve.reinhardt@amd.com        cls._children = multidict() # SimObject children
1983105Sstever@eecs.umich.edu        cls._port_refs = multidict() # port ref objects
1992740SN/A        cls._instantiated = False # really instantiated, cloned, or subclassed
2001310SN/A
2011692SN/A        # We don't support multiple inheritance.  If you want to, you
2021585SN/A        # must fix multidict to deal with it properly.
2031692SN/A        if len(bases) > 1:
2041692SN/A            raise TypeError, "SimObjects do not support multiple inheritance"
2051692SN/A
2061692SN/A        base = bases[0]
2071692SN/A
2082740SN/A        # Set up general inheritance via multidicts.  A subclass will
2092740SN/A        # inherit all its settings from the base class.  The only time
2102740SN/A        # the following is not true is when we define the SimObject
2112740SN/A        # class itself (in which case the multidicts have no parent).
2121692SN/A        if isinstance(base, MetaSimObject):
2135610Snate@binkert.org            cls._base = base
2141692SN/A            cls._params.parent = base._params
2152740SN/A            cls._ports.parent = base._ports
2161692SN/A            cls._values.parent = base._values
2177528Ssteve.reinhardt@amd.com            cls._children.parent = base._children
2183105Sstever@eecs.umich.edu            cls._port_refs.parent = base._port_refs
2192740SN/A            # mark base as having been subclassed
2202712SN/A            base._instantiated = True
2215610Snate@binkert.org        else:
2225610Snate@binkert.org            cls._base = None
2231692SN/A
2244762Snate@binkert.org        # default keyword values
2254762Snate@binkert.org        if 'type' in cls._value_dict:
2264762Snate@binkert.org            if 'cxx_class' not in cls._value_dict:
2275610Snate@binkert.org                cls._value_dict['cxx_class'] = cls._value_dict['type']
2284762Snate@binkert.org
2295610Snate@binkert.org            cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class']
2305610Snate@binkert.org
2317673Snate@binkert.org            if 'cxx_predecls' not in cls.__dict__:
2327673Snate@binkert.org                m = MethodType(default_cxx_predecls, cls, MetaSimObject)
2337673Snate@binkert.org                setattr(cls, 'cxx_predecls', m)
2344762Snate@binkert.org
2357673Snate@binkert.org            if 'swig_predecls' not in cls.__dict__:
2367673Snate@binkert.org                setattr(cls, 'swig_predecls', getattr(cls, 'cxx_predecls'))
2374762Snate@binkert.org
2387673Snate@binkert.org        if 'swig_objdecls' not in cls.__dict__:
2397673Snate@binkert.org            m = MethodType(default_swig_objdecls, cls, MetaSimObject)
2407673Snate@binkert.org            setattr(cls, 'swig_objdecls', m)
2414859Snate@binkert.org
2422740SN/A        # Now process the _value_dict items.  They could be defining
2432740SN/A        # new (or overriding existing) parameters or ports, setting
2442740SN/A        # class keywords (e.g., 'abstract'), or setting parameter
2452740SN/A        # values or port bindings.  The first 3 can only be set when
2462740SN/A        # the class is defined, so we handle them here.  The others
2472740SN/A        # can be set later too, so just emulate that by calling
2482740SN/A        # setattr().
2492740SN/A        for key,val in cls._value_dict.items():
2501527SN/A            # param descriptions
2512740SN/A            if isinstance(val, ParamDesc):
2521585SN/A                cls._new_param(key, val)
2531427SN/A
2542738SN/A            # port objects
2552738SN/A            elif isinstance(val, Port):
2563105Sstever@eecs.umich.edu                cls._new_port(key, val)
2572738SN/A
2581427SN/A            # init-time-only keywords
2591427SN/A            elif cls.init_keywords.has_key(key):
2601427SN/A                cls._set_keyword(key, val, cls.init_keywords[key])
2611427SN/A
2621427SN/A            # default: use normal path (ends up in __setattr__)
2631427SN/A            else:
2641427SN/A                setattr(cls, key, val)
2651427SN/A
2661427SN/A    def _set_keyword(cls, keyword, val, kwtype):
2671427SN/A        if not isinstance(val, kwtype):
2681427SN/A            raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
2691427SN/A                  (keyword, type(val), kwtype)
2707493Ssteve.reinhardt@amd.com        if isinstance(val, FunctionType):
2711427SN/A            val = classmethod(val)
2721427SN/A        type.__setattr__(cls, keyword, val)
2731427SN/A
2743100SN/A    def _new_param(cls, name, pdesc):
2753100SN/A        # each param desc should be uniquely assigned to one variable
2763100SN/A        assert(not hasattr(pdesc, 'name'))
2773100SN/A        pdesc.name = name
2783100SN/A        cls._params[name] = pdesc
2793100SN/A        if hasattr(pdesc, 'default'):
2803105Sstever@eecs.umich.edu            cls._set_param(name, pdesc.default, pdesc)
2813105Sstever@eecs.umich.edu
2823105Sstever@eecs.umich.edu    def _set_param(cls, name, value, param):
2833105Sstever@eecs.umich.edu        assert(param.name == name)
2843105Sstever@eecs.umich.edu        try:
2853105Sstever@eecs.umich.edu            cls._values[name] = param.convert(value)
2863105Sstever@eecs.umich.edu        except Exception, e:
2873105Sstever@eecs.umich.edu            msg = "%s\nError setting param %s.%s to %s\n" % \
2883105Sstever@eecs.umich.edu                  (e, cls.__name__, name, value)
2893105Sstever@eecs.umich.edu            e.args = (msg, )
2903105Sstever@eecs.umich.edu            raise
2913105Sstever@eecs.umich.edu
2923105Sstever@eecs.umich.edu    def _new_port(cls, name, port):
2933105Sstever@eecs.umich.edu        # each port should be uniquely assigned to one variable
2943105Sstever@eecs.umich.edu        assert(not hasattr(port, 'name'))
2953105Sstever@eecs.umich.edu        port.name = name
2963105Sstever@eecs.umich.edu        cls._ports[name] = port
2973105Sstever@eecs.umich.edu        if hasattr(port, 'default'):
2983105Sstever@eecs.umich.edu            cls._cls_get_port_ref(name).connect(port.default)
2993105Sstever@eecs.umich.edu
3003105Sstever@eecs.umich.edu    # same as _get_port_ref, effectively, but for classes
3013105Sstever@eecs.umich.edu    def _cls_get_port_ref(cls, attr):
3023105Sstever@eecs.umich.edu        # Return reference that can be assigned to another port
3033105Sstever@eecs.umich.edu        # via __setattr__.  There is only ever one reference
3043105Sstever@eecs.umich.edu        # object per port, but we create them lazily here.
3053105Sstever@eecs.umich.edu        ref = cls._port_refs.get(attr)
3063105Sstever@eecs.umich.edu        if not ref:
3073105Sstever@eecs.umich.edu            ref = cls._ports[attr].makeRef(cls)
3083105Sstever@eecs.umich.edu            cls._port_refs[attr] = ref
3093105Sstever@eecs.umich.edu        return ref
3101585SN/A
3111310SN/A    # Set attribute (called on foo.attr = value when foo is an
3121310SN/A    # instance of class cls).
3131310SN/A    def __setattr__(cls, attr, value):
3141310SN/A        # normal processing for private attributes
3157673Snate@binkert.org        if public_value(attr, value):
3161310SN/A            type.__setattr__(cls, attr, value)
3171310SN/A            return
3181310SN/A
3191310SN/A        if cls.keywords.has_key(attr):
3201427SN/A            cls._set_keyword(attr, value, cls.keywords[attr])
3211310SN/A            return
3221310SN/A
3232738SN/A        if cls._ports.has_key(attr):
3243105Sstever@eecs.umich.edu            cls._cls_get_port_ref(attr).connect(value)
3252738SN/A            return
3262738SN/A
3272740SN/A        if isSimObjectOrSequence(value) and cls._instantiated:
3282740SN/A            raise RuntimeError, \
3292740SN/A                  "cannot set SimObject parameter '%s' after\n" \
3302740SN/A                  "    class %s has been instantiated or subclassed" \
3312740SN/A                  % (attr, cls.__name__)
3322740SN/A
3332740SN/A        # check for param
3343105Sstever@eecs.umich.edu        param = cls._params.get(attr)
3351310SN/A        if param:
3363105Sstever@eecs.umich.edu            cls._set_param(attr, value, param)
3373105Sstever@eecs.umich.edu            return
3383105Sstever@eecs.umich.edu
3393105Sstever@eecs.umich.edu        if isSimObjectOrSequence(value):
3403105Sstever@eecs.umich.edu            # If RHS is a SimObject, it's an implicit child assignment.
3417528Ssteve.reinhardt@amd.com            cls._children[attr] = coerceSimObjectOrVector(value)
3423105Sstever@eecs.umich.edu            return
3433105Sstever@eecs.umich.edu
3443105Sstever@eecs.umich.edu        # no valid assignment... raise exception
3453105Sstever@eecs.umich.edu        raise AttributeError, \
3463105Sstever@eecs.umich.edu              "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
3471310SN/A
3481585SN/A    def __getattr__(cls, attr):
3491692SN/A        if cls._values.has_key(attr):
3501692SN/A            return cls._values[attr]
3511585SN/A
3527528Ssteve.reinhardt@amd.com        if cls._children.has_key(attr):
3537528Ssteve.reinhardt@amd.com            return cls._children[attr]
3547528Ssteve.reinhardt@amd.com
3551585SN/A        raise AttributeError, \
3561585SN/A              "object '%s' has no attribute '%s'" % (cls.__name__, attr)
3571585SN/A
3583100SN/A    def __str__(cls):
3593100SN/A        return cls.__name__
3603100SN/A
3617673Snate@binkert.org    def cxx_decl(cls, code):
3627673Snate@binkert.org        code('''\
3637673Snate@binkert.org#ifndef __PARAMS__${cls}__
3647673Snate@binkert.org#define __PARAMS__${cls}__
3657673Snate@binkert.org
3667673Snate@binkert.org''')
3674762Snate@binkert.org
3683100SN/A        # The 'dict' attribute restricts us to the params declared in
3693100SN/A        # the object itself, not including inherited params (which
3703100SN/A        # will also be inherited from the base class's param struct
3713100SN/A        # here).
3724762Snate@binkert.org        params = cls._params.local.values()
3733100SN/A        try:
3743100SN/A            ptypes = [p.ptype for p in params]
3753100SN/A        except:
3763100SN/A            print cls, p, p.ptype_str
3773100SN/A            print params
3783100SN/A            raise
3793100SN/A
3807673Snate@binkert.org        # get all predeclarations
3817673Snate@binkert.org        cls.cxx_predecls(code)
3827673Snate@binkert.org        for param in params:
3837673Snate@binkert.org            param.cxx_predecls(code)
3847673Snate@binkert.org        code()
3854762Snate@binkert.org
3865610Snate@binkert.org        if cls._base:
3877673Snate@binkert.org            code('#include "params/${{cls._base.type}}.hh"')
3887673Snate@binkert.org            code()
3894762Snate@binkert.org
3904762Snate@binkert.org        for ptype in ptypes:
3914762Snate@binkert.org            if issubclass(ptype, Enum):
3927673Snate@binkert.org                code('#include "enums/${{ptype.__name__}}.hh"')
3937673Snate@binkert.org                code()
3944762Snate@binkert.org
3957673Snate@binkert.org        cls.cxx_struct(code, cls._base, params)
3965488Snate@binkert.org
3975488Snate@binkert.org        # close #ifndef __PARAMS__* guard
3987673Snate@binkert.org        code()
3997673Snate@binkert.org        code('#endif // __PARAMS__${cls}__')
4005488Snate@binkert.org        return code
4015488Snate@binkert.org
4027673Snate@binkert.org    def cxx_struct(cls, code, base, params):
4035488Snate@binkert.org        if cls == SimObject:
4047673Snate@binkert.org            code('#include "sim/sim_object_params.hh"')
4057673Snate@binkert.org            return
4065488Snate@binkert.org
4074762Snate@binkert.org        # now generate the actual param struct
4087673Snate@binkert.org        code("struct ${cls}Params")
4094762Snate@binkert.org        if base:
4107673Snate@binkert.org            code("    : public ${{base.type}}Params")
4117673Snate@binkert.org        code("{")
4124762Snate@binkert.org        if not hasattr(cls, 'abstract') or not cls.abstract:
4134762Snate@binkert.org            if 'type' in cls.__dict__:
4147673Snate@binkert.org                code("    ${{cls.cxx_type}} create();")
4154762Snate@binkert.org
4167673Snate@binkert.org        code.indent()
4177673Snate@binkert.org        for param in params:
4187673Snate@binkert.org            param.cxx_decl(code)
4197673Snate@binkert.org        code.dedent()
4207673Snate@binkert.org        code('};')
4214762Snate@binkert.org
4227673Snate@binkert.org    def swig_decl(cls, code):
4237673Snate@binkert.org        code('''\
4247673Snate@binkert.org%module $cls
4254762Snate@binkert.org
4267673Snate@binkert.org%{
4277673Snate@binkert.org#include "params/$cls.hh"
4287673Snate@binkert.org%}
4297673Snate@binkert.org
4307673Snate@binkert.org''')
4314762Snate@binkert.org
4324762Snate@binkert.org        # The 'dict' attribute restricts us to the params declared in
4334762Snate@binkert.org        # the object itself, not including inherited params (which
4344762Snate@binkert.org        # will also be inherited from the base class's param struct
4354762Snate@binkert.org        # here).
4364762Snate@binkert.org        params = cls._params.local.values()
4374762Snate@binkert.org        ptypes = [p.ptype for p in params]
4384762Snate@binkert.org
4397673Snate@binkert.org        # get all predeclarations
4407673Snate@binkert.org        for param in params:
4417673Snate@binkert.org            param.swig_predecls(code)
4427673Snate@binkert.org        code()
4433100SN/A
4445610Snate@binkert.org        if cls._base:
4457673Snate@binkert.org            code('%import "params/${{cls._base.type}}.i"')
4467673Snate@binkert.org            code()
4473100SN/A
4484762Snate@binkert.org        for ptype in ptypes:
4494762Snate@binkert.org            if issubclass(ptype, Enum):
4507673Snate@binkert.org                code('%import "enums/${{ptype.__name__}}.hh"')
4517673Snate@binkert.org                code()
4523100SN/A
4537673Snate@binkert.org        code('%import "params/${cls}_type.hh"')
4547673Snate@binkert.org        code('%include "params/${cls}.hh"')
4553100SN/A
4562740SN/A# The SimObject class is the root of the special hierarchy.  Most of
457679SN/A# the code in this class deals with the configuration hierarchy itself
458679SN/A# (parent/child node relationships).
4591692SN/Aclass SimObject(object):
4601692SN/A    # Specify metaclass.  Any class inheriting from SimObject will
461679SN/A    # get this metaclass.
4621692SN/A    __metaclass__ = MetaSimObject
4633100SN/A    type = 'SimObject'
4644762Snate@binkert.org    abstract = True
4653100SN/A
4667673Snate@binkert.org    @classmethod
4677673Snate@binkert.org    def swig_objdecls(cls, code):
4687673Snate@binkert.org        code('%include "python/swig/sim_object.i"')
469679SN/A
4702740SN/A    # Initialize new instance.  For objects with SimObject-valued
4712740SN/A    # children, we need to recursively clone the classes represented
4722740SN/A    # by those param values as well in a consistent "deep copy"-style
4732740SN/A    # fashion.  That is, we want to make sure that each instance is
4742740SN/A    # cloned only once, and that if there are multiple references to
4752740SN/A    # the same original object, we end up with the corresponding
4762740SN/A    # cloned references all pointing to the same cloned instance.
4772740SN/A    def __init__(self, **kwargs):
4782740SN/A        ancestor = kwargs.get('_ancestor')
4792740SN/A        memo_dict = kwargs.get('_memo')
4802740SN/A        if memo_dict is None:
4812740SN/A            # prepare to memoize any recursively instantiated objects
4822740SN/A            memo_dict = {}
4832740SN/A        elif ancestor:
4842740SN/A            # memoize me now to avoid problems with recursive calls
4852740SN/A            memo_dict[ancestor] = self
4862711SN/A
4872740SN/A        if not ancestor:
4882740SN/A            ancestor = self.__class__
4892740SN/A        ancestor._instantiated = True
4902711SN/A
4912740SN/A        # initialize required attributes
4922740SN/A        self._parent = None
4937528Ssteve.reinhardt@amd.com        self._name = None
4942740SN/A        self._ccObject = None  # pointer to C++ object
4954762Snate@binkert.org        self._ccParams = None
4962740SN/A        self._instantiated = False # really "cloned"
4972712SN/A
4982711SN/A        # Inherit parameter values from class using multidict so
4997528Ssteve.reinhardt@amd.com        # individual value settings can be overridden but we still
5007528Ssteve.reinhardt@amd.com        # inherit late changes to non-overridden class values.
5012740SN/A        self._values = multidict(ancestor._values)
5022740SN/A        # clone SimObject-valued parameters
5032740SN/A        for key,val in ancestor._values.iteritems():
5047528Ssteve.reinhardt@amd.com            val = tryAsSimObjectOrVector(val)
5057528Ssteve.reinhardt@amd.com            if val is not None:
5067528Ssteve.reinhardt@amd.com                self._values[key] = val(_memo=memo_dict)
5077528Ssteve.reinhardt@amd.com
5087528Ssteve.reinhardt@amd.com        # Clone children specified at class level.  No need for a
5097528Ssteve.reinhardt@amd.com        # multidict here since we will be cloning everything.
5107528Ssteve.reinhardt@amd.com        self._children = {}
5117528Ssteve.reinhardt@amd.com        for key,val in ancestor._children.iteritems():
5127528Ssteve.reinhardt@amd.com            self.add_child(key, val(_memo=memo_dict))
5137528Ssteve.reinhardt@amd.com
5142740SN/A        # clone port references.  no need to use a multidict here
5152740SN/A        # since we will be creating new references for all ports.
5163105Sstever@eecs.umich.edu        self._port_refs = {}
5173105Sstever@eecs.umich.edu        for key,val in ancestor._port_refs.iteritems():
5183105Sstever@eecs.umich.edu            self._port_refs[key] = val.clone(self, memo_dict)
5191692SN/A        # apply attribute assignments from keyword args, if any
5201692SN/A        for key,val in kwargs.iteritems():
5211692SN/A            setattr(self, key, val)
522679SN/A
5232740SN/A    # "Clone" the current instance by creating another instance of
5242740SN/A    # this instance's class, but that inherits its parameter values
5252740SN/A    # and port mappings from the current instance.  If we're in a
5262740SN/A    # "deep copy" recursive clone, check the _memo dict to see if
5272740SN/A    # we've already cloned this instance.
5281692SN/A    def __call__(self, **kwargs):
5292740SN/A        memo_dict = kwargs.get('_memo')
5302740SN/A        if memo_dict is None:
5312740SN/A            # no memo_dict: must be top-level clone operation.
5322740SN/A            # this is only allowed at the root of a hierarchy
5332740SN/A            if self._parent:
5342740SN/A                raise RuntimeError, "attempt to clone object %s " \
5352740SN/A                      "not at the root of a tree (parent = %s)" \
5362740SN/A                      % (self, self._parent)
5372740SN/A            # create a new dict and use that.
5382740SN/A            memo_dict = {}
5392740SN/A            kwargs['_memo'] = memo_dict
5402740SN/A        elif memo_dict.has_key(self):
5412740SN/A            # clone already done & memoized
5422740SN/A            return memo_dict[self]
5432740SN/A        return self.__class__(_ancestor = self, **kwargs)
5441343SN/A
5453105Sstever@eecs.umich.edu    def _get_port_ref(self, attr):
5463105Sstever@eecs.umich.edu        # Return reference that can be assigned to another port
5473105Sstever@eecs.umich.edu        # via __setattr__.  There is only ever one reference
5483105Sstever@eecs.umich.edu        # object per port, but we create them lazily here.
5493105Sstever@eecs.umich.edu        ref = self._port_refs.get(attr)
5503105Sstever@eecs.umich.edu        if not ref:
5513105Sstever@eecs.umich.edu            ref = self._ports[attr].makeRef(self)
5523105Sstever@eecs.umich.edu            self._port_refs[attr] = ref
5533105Sstever@eecs.umich.edu        return ref
5543105Sstever@eecs.umich.edu
5551692SN/A    def __getattr__(self, attr):
5562738SN/A        if self._ports.has_key(attr):
5573105Sstever@eecs.umich.edu            return self._get_port_ref(attr)
5582738SN/A
5591692SN/A        if self._values.has_key(attr):
5601692SN/A            return self._values[attr]
5611427SN/A
5627528Ssteve.reinhardt@amd.com        if self._children.has_key(attr):
5637528Ssteve.reinhardt@amd.com            return self._children[attr]
5647528Ssteve.reinhardt@amd.com
5657500Ssteve.reinhardt@amd.com        # If the attribute exists on the C++ object, transparently
5667500Ssteve.reinhardt@amd.com        # forward the reference there.  This is typically used for
5677500Ssteve.reinhardt@amd.com        # SWIG-wrapped methods such as init(), regStats(),
5687527Ssteve.reinhardt@amd.com        # regFormulas(), resetStats(), startup(), drain(), and
5697527Ssteve.reinhardt@amd.com        # resume().
5707500Ssteve.reinhardt@amd.com        if self._ccObject and hasattr(self._ccObject, attr):
5717500Ssteve.reinhardt@amd.com            return getattr(self._ccObject, attr)
5727500Ssteve.reinhardt@amd.com
5731692SN/A        raise AttributeError, "object '%s' has no attribute '%s'" \
5741692SN/A              % (self.__class__.__name__, attr)
5751427SN/A
5761692SN/A    # Set attribute (called on foo.attr = value when foo is an
5771692SN/A    # instance of class cls).
5781692SN/A    def __setattr__(self, attr, value):
5791692SN/A        # normal processing for private attributes
5801692SN/A        if attr.startswith('_'):
5811692SN/A            object.__setattr__(self, attr, value)
5821692SN/A            return
5831427SN/A
5842738SN/A        if self._ports.has_key(attr):
5852738SN/A            # set up port connection
5863105Sstever@eecs.umich.edu            self._get_port_ref(attr).connect(value)
5872738SN/A            return
5882738SN/A
5892740SN/A        if isSimObjectOrSequence(value) and self._instantiated:
5902740SN/A            raise RuntimeError, \
5912740SN/A                  "cannot set SimObject parameter '%s' after\n" \
5922740SN/A                  "    instance been cloned %s" % (attr, `self`)
5932740SN/A
5943105Sstever@eecs.umich.edu        param = self._params.get(attr)
5951692SN/A        if param:
5961310SN/A            try:
5971692SN/A                value = param.convert(value)
5981587SN/A            except Exception, e:
5991692SN/A                msg = "%s\nError setting param %s.%s to %s\n" % \
6001692SN/A                      (e, self.__class__.__name__, attr, value)
6011605SN/A                e.args = (msg, )
6021605SN/A                raise
6037528Ssteve.reinhardt@amd.com            self._values[attr] = value
6043105Sstever@eecs.umich.edu            return
6051310SN/A
6067528Ssteve.reinhardt@amd.com        # if RHS is a SimObject, it's an implicit child assignment
6073105Sstever@eecs.umich.edu        if isSimObjectOrSequence(value):
6087528Ssteve.reinhardt@amd.com            self.add_child(attr, value)
6093105Sstever@eecs.umich.edu            return
6101693SN/A
6113105Sstever@eecs.umich.edu        # no valid assignment... raise exception
6123105Sstever@eecs.umich.edu        raise AttributeError, "Class %s has no parameter %s" \
6133105Sstever@eecs.umich.edu              % (self.__class__.__name__, attr)
6141310SN/A
6151310SN/A
6161692SN/A    # this hack allows tacking a '[0]' onto parameters that may or may
6171692SN/A    # not be vectors, and always getting the first element (e.g. cpus)
6181692SN/A    def __getitem__(self, key):
6191692SN/A        if key == 0:
6201692SN/A            return self
6211692SN/A        raise TypeError, "Non-zero index '%s' to SimObject" % key
6221310SN/A
6237528Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
6247528Ssteve.reinhardt@amd.com    def clear_parent(self, old_parent):
6257528Ssteve.reinhardt@amd.com        assert self._parent is old_parent
6267528Ssteve.reinhardt@amd.com        self._parent = None
6277528Ssteve.reinhardt@amd.com
6287528Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
6297528Ssteve.reinhardt@amd.com    def set_parent(self, parent, name):
6307528Ssteve.reinhardt@amd.com        self._parent = parent
6317528Ssteve.reinhardt@amd.com        self._name = name
6327528Ssteve.reinhardt@amd.com
6337528Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
6347528Ssteve.reinhardt@amd.com    def get_name(self):
6357528Ssteve.reinhardt@amd.com        return self._name
6367528Ssteve.reinhardt@amd.com
6377528Ssteve.reinhardt@amd.com    # use this rather than directly accessing _parent for symmetry
6387528Ssteve.reinhardt@amd.com    # with SimObjectVector
6397528Ssteve.reinhardt@amd.com    def get_parent(self):
6407528Ssteve.reinhardt@amd.com        return self._parent
6417528Ssteve.reinhardt@amd.com
6427528Ssteve.reinhardt@amd.com    # clear out child with given name
6431693SN/A    def clear_child(self, name):
6441693SN/A        child = self._children[name]
6457528Ssteve.reinhardt@amd.com        child.clear_parent(self)
6461693SN/A        del self._children[name]
6471693SN/A
6487528Ssteve.reinhardt@amd.com    # Add a new child to this object.
6497528Ssteve.reinhardt@amd.com    def add_child(self, name, child):
6507528Ssteve.reinhardt@amd.com        child = coerceSimObjectOrVector(child)
6517528Ssteve.reinhardt@amd.com        if child.get_parent():
6527528Ssteve.reinhardt@amd.com            raise RuntimeError, \
6537528Ssteve.reinhardt@amd.com                  "add_child('%s'): child '%s' already has parent '%s'" % \
6547528Ssteve.reinhardt@amd.com                  (name, child._name, child._parent)
6557528Ssteve.reinhardt@amd.com        if self._children.has_key(name):
6567528Ssteve.reinhardt@amd.com            clear_child(name)
6577528Ssteve.reinhardt@amd.com        child.set_parent(self, name)
6587528Ssteve.reinhardt@amd.com        self._children[name] = child
6591310SN/A
6607528Ssteve.reinhardt@amd.com    # Take SimObject-valued parameters that haven't been explicitly
6617528Ssteve.reinhardt@amd.com    # assigned as children and make them children of the object that
6627528Ssteve.reinhardt@amd.com    # they were assigned to as a parameter value.  This guarantees
6637528Ssteve.reinhardt@amd.com    # that when we instantiate all the parameter objects we're still
6647528Ssteve.reinhardt@amd.com    # inside the configuration hierarchy.
6657528Ssteve.reinhardt@amd.com    def adoptOrphanParams(self):
6667528Ssteve.reinhardt@amd.com        for key,val in self._values.iteritems():
6677528Ssteve.reinhardt@amd.com            if not isSimObjectVector(val) and isSimObjectSequence(val):
6687528Ssteve.reinhardt@amd.com                # need to convert raw SimObject sequences to
6697528Ssteve.reinhardt@amd.com                # SimObjectVector class so we can call get_parent()
6707528Ssteve.reinhardt@amd.com                val = SimObjectVector(val)
6717528Ssteve.reinhardt@amd.com                self._values[key] = val
6727528Ssteve.reinhardt@amd.com            if isSimObjectOrVector(val) and not val.get_parent():
6737528Ssteve.reinhardt@amd.com                self.add_child(key, val)
6743105Sstever@eecs.umich.edu
6751692SN/A    def path(self):
6762740SN/A        if not self._parent:
6777525Ssteve.reinhardt@amd.com            return '(orphan)'
6781692SN/A        ppath = self._parent.path()
6791692SN/A        if ppath == 'root':
6801692SN/A            return self._name
6811692SN/A        return ppath + "." + self._name
6821310SN/A
6831692SN/A    def __str__(self):
6841692SN/A        return self.path()
6851310SN/A
6861692SN/A    def ini_str(self):
6871692SN/A        return self.path()
6881310SN/A
6891692SN/A    def find_any(self, ptype):
6901692SN/A        if isinstance(self, ptype):
6911692SN/A            return self, True
6921310SN/A
6931692SN/A        found_obj = None
6941692SN/A        for child in self._children.itervalues():
6951692SN/A            if isinstance(child, ptype):
6961692SN/A                if found_obj != None and child != found_obj:
6971692SN/A                    raise AttributeError, \
6981692SN/A                          'parent.any matched more than one: %s %s' % \
6991814SN/A                          (found_obj.path, child.path)
7001692SN/A                found_obj = child
7011692SN/A        # search param space
7021692SN/A        for pname,pdesc in self._params.iteritems():
7031692SN/A            if issubclass(pdesc.ptype, ptype):
7041692SN/A                match_obj = self._values[pname]
7051692SN/A                if found_obj != None and found_obj != match_obj:
7061692SN/A                    raise AttributeError, \
7075952Ssaidi@eecs.umich.edu                          'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path)
7081692SN/A                found_obj = match_obj
7091692SN/A        return found_obj, found_obj != None
7101692SN/A
7111815SN/A    def unproxy(self, base):
7121815SN/A        return self
7131815SN/A
7147527Ssteve.reinhardt@amd.com    def unproxyParams(self):
7153105Sstever@eecs.umich.edu        for param in self._params.iterkeys():
7163105Sstever@eecs.umich.edu            value = self._values.get(param)
7176654Snate@binkert.org            if value != None and isproxy(value):
7183105Sstever@eecs.umich.edu                try:
7193105Sstever@eecs.umich.edu                    value = value.unproxy(self)
7203105Sstever@eecs.umich.edu                except:
7213105Sstever@eecs.umich.edu                    print "Error in unproxying param '%s' of %s" % \
7223105Sstever@eecs.umich.edu                          (param, self.path())
7233105Sstever@eecs.umich.edu                    raise
7243105Sstever@eecs.umich.edu                setattr(self, param, value)
7253105Sstever@eecs.umich.edu
7263107Sstever@eecs.umich.edu        # Unproxy ports in sorted order so that 'append' operations on
7273107Sstever@eecs.umich.edu        # vector ports are done in a deterministic fashion.
7283107Sstever@eecs.umich.edu        port_names = self._ports.keys()
7293107Sstever@eecs.umich.edu        port_names.sort()
7303107Sstever@eecs.umich.edu        for port_name in port_names:
7313105Sstever@eecs.umich.edu            port = self._port_refs.get(port_name)
7323105Sstever@eecs.umich.edu            if port != None:
7333105Sstever@eecs.umich.edu                port.unproxy(self)
7343105Sstever@eecs.umich.edu
7355037Smilesck@eecs.umich.edu    def print_ini(self, ini_file):
7365543Ssaidi@eecs.umich.edu        print >>ini_file, '[' + self.path() + ']'       # .ini section header
7371692SN/A
7382738SN/A        instanceDict[self.path()] = self
7392738SN/A
7404081Sbinkertn@umich.edu        if hasattr(self, 'type'):
7415037Smilesck@eecs.umich.edu            print >>ini_file, 'type=%s' % self.type
7421692SN/A
7431692SN/A        child_names = self._children.keys()
7441692SN/A        child_names.sort()
7454081Sbinkertn@umich.edu        if len(child_names):
7467528Ssteve.reinhardt@amd.com            print >>ini_file, 'children=%s' % \
7477528Ssteve.reinhardt@amd.com                  ' '.join(self._children[n].get_name() for n in child_names)
7481692SN/A
7491692SN/A        param_names = self._params.keys()
7501692SN/A        param_names.sort()
7511692SN/A        for param in param_names:
7523105Sstever@eecs.umich.edu            value = self._values.get(param)
7531692SN/A            if value != None:
7545037Smilesck@eecs.umich.edu                print >>ini_file, '%s=%s' % (param,
7555037Smilesck@eecs.umich.edu                                             self._values[param].ini_str())
7561692SN/A
7573103Sstever@eecs.umich.edu        port_names = self._ports.keys()
7583103Sstever@eecs.umich.edu        port_names.sort()
7593103Sstever@eecs.umich.edu        for port_name in port_names:
7603105Sstever@eecs.umich.edu            port = self._port_refs.get(port_name, None)
7613105Sstever@eecs.umich.edu            if port != None:
7625037Smilesck@eecs.umich.edu                print >>ini_file, '%s=%s' % (port_name, port.ini_str())
7633103Sstever@eecs.umich.edu
7645543Ssaidi@eecs.umich.edu        print >>ini_file        # blank line between objects
7651692SN/A
7664762Snate@binkert.org    def getCCParams(self):
7674762Snate@binkert.org        if self._ccParams:
7684762Snate@binkert.org            return self._ccParams
7694762Snate@binkert.org
7705033Smilesck@eecs.umich.edu        cc_params_struct = getattr(m5.objects.params, '%sParams' % self.type)
7714762Snate@binkert.org        cc_params = cc_params_struct()
7725488Snate@binkert.org        cc_params.pyobj = self
7734762Snate@binkert.org        cc_params.name = str(self)
7744762Snate@binkert.org
7754762Snate@binkert.org        param_names = self._params.keys()
7764762Snate@binkert.org        param_names.sort()
7774762Snate@binkert.org        for param in param_names:
7784762Snate@binkert.org            value = self._values.get(param)
7794762Snate@binkert.org            if value is None:
7806654Snate@binkert.org                fatal("%s.%s without default or user set value",
7816654Snate@binkert.org                      self.path(), param)
7824762Snate@binkert.org
7834762Snate@binkert.org            value = value.getValue()
7844762Snate@binkert.org            if isinstance(self._params[param], VectorParamDesc):
7854762Snate@binkert.org                assert isinstance(value, list)
7864762Snate@binkert.org                vec = getattr(cc_params, param)
7874762Snate@binkert.org                assert not len(vec)
7884762Snate@binkert.org                for v in value:
7894762Snate@binkert.org                    vec.append(v)
7904762Snate@binkert.org            else:
7914762Snate@binkert.org                setattr(cc_params, param, value)
7924762Snate@binkert.org
7934762Snate@binkert.org        port_names = self._ports.keys()
7944762Snate@binkert.org        port_names.sort()
7954762Snate@binkert.org        for port_name in port_names:
7964762Snate@binkert.org            port = self._port_refs.get(port_name, None)
7974762Snate@binkert.org            if port != None:
7984762Snate@binkert.org                setattr(cc_params, port_name, port)
7994762Snate@binkert.org        self._ccParams = cc_params
8004762Snate@binkert.org        return self._ccParams
8012738SN/A
8022740SN/A    # Get C++ object corresponding to this object, calling C++ if
8032740SN/A    # necessary to construct it.  Does *not* recursively create
8042740SN/A    # children.
8052740SN/A    def getCCObject(self):
8062740SN/A        if not self._ccObject:
8077526Ssteve.reinhardt@amd.com            # Make sure this object is in the configuration hierarchy
8087526Ssteve.reinhardt@amd.com            if not self._parent and not isRoot(self):
8097526Ssteve.reinhardt@amd.com                raise RuntimeError, "Attempt to instantiate orphan node"
8107526Ssteve.reinhardt@amd.com            # Cycles in the configuration hierarchy are not supported. This
8115244Sgblack@eecs.umich.edu            # will catch the resulting recursion and stop.
8125244Sgblack@eecs.umich.edu            self._ccObject = -1
8135244Sgblack@eecs.umich.edu            params = self.getCCParams()
8144762Snate@binkert.org            self._ccObject = params.create()
8152740SN/A        elif self._ccObject == -1:
8167526Ssteve.reinhardt@amd.com            raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
8172740SN/A                  % self.path()
8182740SN/A        return self._ccObject
8192740SN/A
8207527Ssteve.reinhardt@amd.com    def descendants(self):
8217527Ssteve.reinhardt@amd.com        yield self
8227527Ssteve.reinhardt@amd.com        for child in self._children.itervalues():
8237527Ssteve.reinhardt@amd.com            for obj in child.descendants():
8247527Ssteve.reinhardt@amd.com                yield obj
8257527Ssteve.reinhardt@amd.com
8267527Ssteve.reinhardt@amd.com    # Call C++ to create C++ object corresponding to this object
8274762Snate@binkert.org    def createCCObject(self):
8284762Snate@binkert.org        self.getCCParams()
8294762Snate@binkert.org        self.getCCObject() # force creation
8304762Snate@binkert.org
8314762Snate@binkert.org    def getValue(self):
8324762Snate@binkert.org        return self.getCCObject()
8334762Snate@binkert.org
8342738SN/A    # Create C++ port connections corresponding to the connections in
8357527Ssteve.reinhardt@amd.com    # _port_refs
8362738SN/A    def connectPorts(self):
8373105Sstever@eecs.umich.edu        for portRef in self._port_refs.itervalues():
8383105Sstever@eecs.umich.edu            portRef.ccConnect()
8392797SN/A
8404553Sbinkertn@umich.edu    def getMemoryMode(self):
8414553Sbinkertn@umich.edu        if not isinstance(self, m5.objects.System):
8424553Sbinkertn@umich.edu            return None
8434553Sbinkertn@umich.edu
8444859Snate@binkert.org        return self._ccObject.getMemoryMode()
8454553Sbinkertn@umich.edu
8462797SN/A    def changeTiming(self, mode):
8473202Shsul@eecs.umich.edu        if isinstance(self, m5.objects.System):
8483202Shsul@eecs.umich.edu            # i don't know if there's a better way to do this - calling
8493202Shsul@eecs.umich.edu            # setMemoryMode directly from self._ccObject results in calling
8503202Shsul@eecs.umich.edu            # SimObject::setMemoryMode, not the System::setMemoryMode
8514859Snate@binkert.org            self._ccObject.setMemoryMode(mode)
8522797SN/A
8532797SN/A    def takeOverFrom(self, old_cpu):
8544859Snate@binkert.org        self._ccObject.takeOverFrom(old_cpu._ccObject)
8552797SN/A
8561692SN/A    # generate output file for 'dot' to display as a pretty graph.
8571692SN/A    # this code is currently broken.
8581342SN/A    def outputDot(self, dot):
8591342SN/A        label = "{%s|" % self.path
8601342SN/A        if isSimObject(self.realtype):
8611342SN/A            label +=  '%s|' % self.type
8621342SN/A
8631342SN/A        if self.children:
8641342SN/A            # instantiate children in same order they were added for
8651342SN/A            # backward compatibility (else we can end up with cpu1
8661342SN/A            # before cpu0).
8671342SN/A            for c in self.children:
8681342SN/A                dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
8691342SN/A
8701342SN/A        simobjs = []
8711342SN/A        for param in self.params:
8721342SN/A            try:
8731342SN/A                if param.value is None:
8741342SN/A                    raise AttributeError, 'Parameter with no value'
8751342SN/A
8761692SN/A                value = param.value
8771342SN/A                string = param.string(value)
8781587SN/A            except Exception, e:
8791605SN/A                msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
8801605SN/A                e.args = (msg, )
8811342SN/A                raise
8821605SN/A
8831692SN/A            if isSimObject(param.ptype) and string != "Null":
8841342SN/A                simobjs.append(string)
8851342SN/A            else:
8861342SN/A                label += '%s = %s\\n' % (param.name, string)
8871342SN/A
8881342SN/A        for so in simobjs:
8891342SN/A            label += "|<%s> %s" % (so, so)
8901587SN/A            dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
8911587SN/A                                    tailport="w"))
8921342SN/A        label += '}'
8931342SN/A        dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
8941342SN/A
8951342SN/A        # recursively dump out children
8961342SN/A        for c in self.children:
8971342SN/A            c.outputDot(dot)
8981342SN/A
8993101Sstever@eecs.umich.edu# Function to provide to C++ so it can look up instances based on paths
9003101Sstever@eecs.umich.edudef resolveSimObject(name):
9013101Sstever@eecs.umich.edu    obj = instanceDict[name]
9023101Sstever@eecs.umich.edu    return obj.getCCObject()
903679SN/A
9046654Snate@binkert.orgdef isSimObject(value):
9056654Snate@binkert.org    return isinstance(value, SimObject)
9066654Snate@binkert.org
9076654Snate@binkert.orgdef isSimObjectClass(value):
9086654Snate@binkert.org    return issubclass(value, SimObject)
9096654Snate@binkert.org
9107528Ssteve.reinhardt@amd.comdef isSimObjectVector(value):
9117528Ssteve.reinhardt@amd.com    return isinstance(value, SimObjectVector)
9127528Ssteve.reinhardt@amd.com
9136654Snate@binkert.orgdef isSimObjectSequence(value):
9146654Snate@binkert.org    if not isinstance(value, (list, tuple)) or len(value) == 0:
9156654Snate@binkert.org        return False
9166654Snate@binkert.org
9176654Snate@binkert.org    for val in value:
9186654Snate@binkert.org        if not isNullPointer(val) and not isSimObject(val):
9196654Snate@binkert.org            return False
9206654Snate@binkert.org
9216654Snate@binkert.org    return True
9226654Snate@binkert.org
9236654Snate@binkert.orgdef isSimObjectOrSequence(value):
9246654Snate@binkert.org    return isSimObject(value) or isSimObjectSequence(value)
9256654Snate@binkert.org
9267526Ssteve.reinhardt@amd.comdef isRoot(obj):
9277526Ssteve.reinhardt@amd.com    from m5.objects import Root
9287526Ssteve.reinhardt@amd.com    return obj and obj is Root.getInstance()
9297526Ssteve.reinhardt@amd.com
9307528Ssteve.reinhardt@amd.comdef isSimObjectOrVector(value):
9317528Ssteve.reinhardt@amd.com    return isSimObject(value) or isSimObjectVector(value)
9327528Ssteve.reinhardt@amd.com
9337528Ssteve.reinhardt@amd.comdef tryAsSimObjectOrVector(value):
9347528Ssteve.reinhardt@amd.com    if isSimObjectOrVector(value):
9357528Ssteve.reinhardt@amd.com        return value
9367528Ssteve.reinhardt@amd.com    if isSimObjectSequence(value):
9377528Ssteve.reinhardt@amd.com        return SimObjectVector(value)
9387528Ssteve.reinhardt@amd.com    return None
9397528Ssteve.reinhardt@amd.com
9407528Ssteve.reinhardt@amd.comdef coerceSimObjectOrVector(value):
9417528Ssteve.reinhardt@amd.com    value = tryAsSimObjectOrVector(value)
9427528Ssteve.reinhardt@amd.com    if value is None:
9437528Ssteve.reinhardt@amd.com        raise TypeError, "SimObject or SimObjectVector expected"
9447528Ssteve.reinhardt@amd.com    return value
9457528Ssteve.reinhardt@amd.com
9466654Snate@binkert.orgbaseClasses = allClasses.copy()
9476654Snate@binkert.orgbaseInstances = instanceDict.copy()
9486654Snate@binkert.org
9496654Snate@binkert.orgdef clear():
9506654Snate@binkert.org    global allClasses, instanceDict
9516654Snate@binkert.org
9526654Snate@binkert.org    allClasses = baseClasses.copy()
9536654Snate@binkert.org    instanceDict = baseInstances.copy()
9546654Snate@binkert.org
9551528SN/A# __all__ defines the list of symbols that get exported when
9561528SN/A# 'from config import *' is invoked.  Try to keep this reasonably
9571528SN/A# short to avoid polluting other namespaces.
9584762Snate@binkert.org__all__ = [ 'SimObject' ]
959