SimObject.py revision 8321
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):
1017675Snate@binkert.org    code('#include "params/$cls.hh"')
1027673Snate@binkert.org
1037675Snate@binkert.orgdef default_swig_predecls(cls, code):
1047677Snate@binkert.org    code('%import "python/m5/internal/param_$cls.i"')
1057673Snate@binkert.org
1067673Snate@binkert.orgdef default_swig_objdecls(cls, code):
1077673Snate@binkert.org    class_path = cls.cxx_class.split('::')
1087673Snate@binkert.org    classname = class_path[-1]
1097673Snate@binkert.org    namespaces = class_path[:-1]
1107673Snate@binkert.org
1117673Snate@binkert.org    for ns in namespaces:
1127673Snate@binkert.org        code('namespace $ns {')
1137673Snate@binkert.org
1147673Snate@binkert.org    if namespaces:
1157673Snate@binkert.org        code('// avoid name conflicts')
1167673Snate@binkert.org        sep_string = '_COLONS_'
1177673Snate@binkert.org        flat_name = sep_string.join(class_path)
1187673Snate@binkert.org        code('%rename($flat_name) $classname;')
1197673Snate@binkert.org
1207673Snate@binkert.org    code()
1217673Snate@binkert.org    code('// stop swig from creating/wrapping default ctor/dtor')
1227673Snate@binkert.org    code('%nodefault $classname;')
1237673Snate@binkert.org    code('class $classname')
1247673Snate@binkert.org    if cls._base:
1257673Snate@binkert.org        code('    : public ${{cls._base.cxx_class}}')
1267673Snate@binkert.org    code('{};')
1277673Snate@binkert.org
1287673Snate@binkert.org    for ns in reversed(namespaces):
1297811Ssteve.reinhardt@amd.com        code('} // namespace $ns')
1307673Snate@binkert.org
1317673Snate@binkert.orgdef public_value(key, value):
1327673Snate@binkert.org    return key.startswith('_') or \
1337673Snate@binkert.org               isinstance(value, (FunctionType, MethodType, classmethod, type))
1347673Snate@binkert.org
1352740SN/A# The metaclass for SimObject.  This class controls how new classes
1362740SN/A# that derive from SimObject are instantiated, and provides inherited
1372740SN/A# class behavior (just like a class controls how instances of that
1382740SN/A# class are instantiated, and provides inherited instance behavior).
1391692SN/Aclass MetaSimObject(type):
1401427SN/A    # Attributes that can be set only at initialization time
1417493Ssteve.reinhardt@amd.com    init_keywords = { 'abstract' : bool,
1427493Ssteve.reinhardt@amd.com                      'cxx_class' : str,
1437493Ssteve.reinhardt@amd.com                      'cxx_type' : str,
1447673Snate@binkert.org                      'cxx_predecls'  : MethodType,
1457673Snate@binkert.org                      'swig_objdecls' : MethodType,
1467673Snate@binkert.org                      'swig_predecls' : MethodType,
1477493Ssteve.reinhardt@amd.com                      'type' : str }
1481427SN/A    # Attributes that can be set any time
1497493Ssteve.reinhardt@amd.com    keywords = { 'check' : FunctionType }
150679SN/A
151679SN/A    # __new__ is called before __init__, and is where the statements
152679SN/A    # in the body of the class definition get loaded into the class's
1532740SN/A    # __dict__.  We intercept this to filter out parameter & port assignments
154679SN/A    # and only allow "private" attributes to be passed to the base
155679SN/A    # __new__ (starting with underscore).
1561310SN/A    def __new__(mcls, name, bases, dict):
1576654Snate@binkert.org        assert name not in allClasses, "SimObject %s already present" % name
1584762Snate@binkert.org
1592740SN/A        # Copy "private" attributes, functions, and classes to the
1602740SN/A        # official dict.  Everything else goes in _init_dict to be
1612740SN/A        # filtered in __init__.
1622740SN/A        cls_dict = {}
1632740SN/A        value_dict = {}
1642740SN/A        for key,val in dict.items():
1657673Snate@binkert.org            if public_value(key, val):
1662740SN/A                cls_dict[key] = val
1672740SN/A            else:
1682740SN/A                # must be a param/port setting
1692740SN/A                value_dict[key] = val
1704762Snate@binkert.org        if 'abstract' not in value_dict:
1714762Snate@binkert.org            value_dict['abstract'] = False
1722740SN/A        cls_dict['_value_dict'] = value_dict
1734762Snate@binkert.org        cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
1744762Snate@binkert.org        if 'type' in value_dict:
1754762Snate@binkert.org            allClasses[name] = cls
1764762Snate@binkert.org        return cls
177679SN/A
1782711SN/A    # subclass initialization
179679SN/A    def __init__(cls, name, bases, dict):
1802711SN/A        # calls type.__init__()... I think that's a no-op, but leave
1812711SN/A        # it here just in case it's not.
1821692SN/A        super(MetaSimObject, cls).__init__(name, bases, dict)
1831310SN/A
1841427SN/A        # initialize required attributes
1852740SN/A
1862740SN/A        # class-only attributes
1872740SN/A        cls._params = multidict() # param descriptions
1882740SN/A        cls._ports = multidict()  # port descriptions
1892740SN/A
1902740SN/A        # class or instance attributes
1912740SN/A        cls._values = multidict()   # param values
1927528Ssteve.reinhardt@amd.com        cls._children = multidict() # SimObject children
1933105Sstever@eecs.umich.edu        cls._port_refs = multidict() # port ref objects
1942740SN/A        cls._instantiated = False # really instantiated, cloned, or subclassed
1951310SN/A
1961692SN/A        # We don't support multiple inheritance.  If you want to, you
1971585SN/A        # must fix multidict to deal with it properly.
1981692SN/A        if len(bases) > 1:
1991692SN/A            raise TypeError, "SimObjects do not support multiple inheritance"
2001692SN/A
2011692SN/A        base = bases[0]
2021692SN/A
2032740SN/A        # Set up general inheritance via multidicts.  A subclass will
2042740SN/A        # inherit all its settings from the base class.  The only time
2052740SN/A        # the following is not true is when we define the SimObject
2062740SN/A        # class itself (in which case the multidicts have no parent).
2071692SN/A        if isinstance(base, MetaSimObject):
2085610Snate@binkert.org            cls._base = base
2091692SN/A            cls._params.parent = base._params
2102740SN/A            cls._ports.parent = base._ports
2111692SN/A            cls._values.parent = base._values
2127528Ssteve.reinhardt@amd.com            cls._children.parent = base._children
2133105Sstever@eecs.umich.edu            cls._port_refs.parent = base._port_refs
2142740SN/A            # mark base as having been subclassed
2152712SN/A            base._instantiated = True
2165610Snate@binkert.org        else:
2175610Snate@binkert.org            cls._base = None
2181692SN/A
2194762Snate@binkert.org        # default keyword values
2204762Snate@binkert.org        if 'type' in cls._value_dict:
2214762Snate@binkert.org            if 'cxx_class' not in cls._value_dict:
2225610Snate@binkert.org                cls._value_dict['cxx_class'] = cls._value_dict['type']
2234762Snate@binkert.org
2245610Snate@binkert.org            cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class']
2255610Snate@binkert.org
2267673Snate@binkert.org            if 'cxx_predecls' not in cls.__dict__:
2277673Snate@binkert.org                m = MethodType(default_cxx_predecls, cls, MetaSimObject)
2287673Snate@binkert.org                setattr(cls, 'cxx_predecls', m)
2294762Snate@binkert.org
2307673Snate@binkert.org            if 'swig_predecls' not in cls.__dict__:
2317675Snate@binkert.org                m = MethodType(default_swig_predecls, cls, MetaSimObject)
2327675Snate@binkert.org                setattr(cls, 'swig_predecls', m)
2334762Snate@binkert.org
2347673Snate@binkert.org        if 'swig_objdecls' not in cls.__dict__:
2357673Snate@binkert.org            m = MethodType(default_swig_objdecls, cls, MetaSimObject)
2367673Snate@binkert.org            setattr(cls, 'swig_objdecls', m)
2374859Snate@binkert.org
2382740SN/A        # Now process the _value_dict items.  They could be defining
2392740SN/A        # new (or overriding existing) parameters or ports, setting
2402740SN/A        # class keywords (e.g., 'abstract'), or setting parameter
2412740SN/A        # values or port bindings.  The first 3 can only be set when
2422740SN/A        # the class is defined, so we handle them here.  The others
2432740SN/A        # can be set later too, so just emulate that by calling
2442740SN/A        # setattr().
2452740SN/A        for key,val in cls._value_dict.items():
2461527SN/A            # param descriptions
2472740SN/A            if isinstance(val, ParamDesc):
2481585SN/A                cls._new_param(key, val)
2491427SN/A
2502738SN/A            # port objects
2512738SN/A            elif isinstance(val, Port):
2523105Sstever@eecs.umich.edu                cls._new_port(key, val)
2532738SN/A
2541427SN/A            # init-time-only keywords
2551427SN/A            elif cls.init_keywords.has_key(key):
2561427SN/A                cls._set_keyword(key, val, cls.init_keywords[key])
2571427SN/A
2581427SN/A            # default: use normal path (ends up in __setattr__)
2591427SN/A            else:
2601427SN/A                setattr(cls, key, val)
2611427SN/A
2621427SN/A    def _set_keyword(cls, keyword, val, kwtype):
2631427SN/A        if not isinstance(val, kwtype):
2641427SN/A            raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
2651427SN/A                  (keyword, type(val), kwtype)
2667493Ssteve.reinhardt@amd.com        if isinstance(val, FunctionType):
2671427SN/A            val = classmethod(val)
2681427SN/A        type.__setattr__(cls, keyword, val)
2691427SN/A
2703100SN/A    def _new_param(cls, name, pdesc):
2713100SN/A        # each param desc should be uniquely assigned to one variable
2723100SN/A        assert(not hasattr(pdesc, 'name'))
2733100SN/A        pdesc.name = name
2743100SN/A        cls._params[name] = pdesc
2753100SN/A        if hasattr(pdesc, 'default'):
2763105Sstever@eecs.umich.edu            cls._set_param(name, pdesc.default, pdesc)
2773105Sstever@eecs.umich.edu
2783105Sstever@eecs.umich.edu    def _set_param(cls, name, value, param):
2793105Sstever@eecs.umich.edu        assert(param.name == name)
2803105Sstever@eecs.umich.edu        try:
2818321Ssteve.reinhardt@amd.com            value = param.convert(value)
2823105Sstever@eecs.umich.edu        except Exception, e:
2833105Sstever@eecs.umich.edu            msg = "%s\nError setting param %s.%s to %s\n" % \
2843105Sstever@eecs.umich.edu                  (e, cls.__name__, name, value)
2853105Sstever@eecs.umich.edu            e.args = (msg, )
2863105Sstever@eecs.umich.edu            raise
2878321Ssteve.reinhardt@amd.com        cls._values[name] = value
2888321Ssteve.reinhardt@amd.com        # if param value is a SimObject, make it a child too, so that
2898321Ssteve.reinhardt@amd.com        # it gets cloned properly when the class is instantiated
2908321Ssteve.reinhardt@amd.com        if isSimObjectOrVector(value) and not value.has_parent():
2918321Ssteve.reinhardt@amd.com            cls._add_cls_child(name, value)
2928321Ssteve.reinhardt@amd.com
2938321Ssteve.reinhardt@amd.com    def _add_cls_child(cls, name, child):
2948321Ssteve.reinhardt@amd.com        # It's a little funky to have a class as a parent, but these
2958321Ssteve.reinhardt@amd.com        # objects should never be instantiated (only cloned, which
2968321Ssteve.reinhardt@amd.com        # clears the parent pointer), and this makes it clear that the
2978321Ssteve.reinhardt@amd.com        # object is not an orphan and can provide better error
2988321Ssteve.reinhardt@amd.com        # messages.
2998321Ssteve.reinhardt@amd.com        child.set_parent(cls, name)
3008321Ssteve.reinhardt@amd.com        cls._children[name] = child
3013105Sstever@eecs.umich.edu
3023105Sstever@eecs.umich.edu    def _new_port(cls, name, port):
3033105Sstever@eecs.umich.edu        # each port should be uniquely assigned to one variable
3043105Sstever@eecs.umich.edu        assert(not hasattr(port, 'name'))
3053105Sstever@eecs.umich.edu        port.name = name
3063105Sstever@eecs.umich.edu        cls._ports[name] = port
3073105Sstever@eecs.umich.edu        if hasattr(port, 'default'):
3083105Sstever@eecs.umich.edu            cls._cls_get_port_ref(name).connect(port.default)
3093105Sstever@eecs.umich.edu
3103105Sstever@eecs.umich.edu    # same as _get_port_ref, effectively, but for classes
3113105Sstever@eecs.umich.edu    def _cls_get_port_ref(cls, attr):
3123105Sstever@eecs.umich.edu        # Return reference that can be assigned to another port
3133105Sstever@eecs.umich.edu        # via __setattr__.  There is only ever one reference
3143105Sstever@eecs.umich.edu        # object per port, but we create them lazily here.
3153105Sstever@eecs.umich.edu        ref = cls._port_refs.get(attr)
3163105Sstever@eecs.umich.edu        if not ref:
3173105Sstever@eecs.umich.edu            ref = cls._ports[attr].makeRef(cls)
3183105Sstever@eecs.umich.edu            cls._port_refs[attr] = ref
3193105Sstever@eecs.umich.edu        return ref
3201585SN/A
3211310SN/A    # Set attribute (called on foo.attr = value when foo is an
3221310SN/A    # instance of class cls).
3231310SN/A    def __setattr__(cls, attr, value):
3241310SN/A        # normal processing for private attributes
3257673Snate@binkert.org        if public_value(attr, value):
3261310SN/A            type.__setattr__(cls, attr, value)
3271310SN/A            return
3281310SN/A
3291310SN/A        if cls.keywords.has_key(attr):
3301427SN/A            cls._set_keyword(attr, value, cls.keywords[attr])
3311310SN/A            return
3321310SN/A
3332738SN/A        if cls._ports.has_key(attr):
3343105Sstever@eecs.umich.edu            cls._cls_get_port_ref(attr).connect(value)
3352738SN/A            return
3362738SN/A
3372740SN/A        if isSimObjectOrSequence(value) and cls._instantiated:
3382740SN/A            raise RuntimeError, \
3392740SN/A                  "cannot set SimObject parameter '%s' after\n" \
3402740SN/A                  "    class %s has been instantiated or subclassed" \
3412740SN/A                  % (attr, cls.__name__)
3422740SN/A
3432740SN/A        # check for param
3443105Sstever@eecs.umich.edu        param = cls._params.get(attr)
3451310SN/A        if param:
3463105Sstever@eecs.umich.edu            cls._set_param(attr, value, param)
3473105Sstever@eecs.umich.edu            return
3483105Sstever@eecs.umich.edu
3493105Sstever@eecs.umich.edu        if isSimObjectOrSequence(value):
3503105Sstever@eecs.umich.edu            # If RHS is a SimObject, it's an implicit child assignment.
3518321Ssteve.reinhardt@amd.com            cls._add_cls_child(attr, coerceSimObjectOrVector(value))
3523105Sstever@eecs.umich.edu            return
3533105Sstever@eecs.umich.edu
3543105Sstever@eecs.umich.edu        # no valid assignment... raise exception
3553105Sstever@eecs.umich.edu        raise AttributeError, \
3563105Sstever@eecs.umich.edu              "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
3571310SN/A
3581585SN/A    def __getattr__(cls, attr):
3597675Snate@binkert.org        if attr == 'cxx_class_path':
3607675Snate@binkert.org            return cls.cxx_class.split('::')
3617675Snate@binkert.org
3627675Snate@binkert.org        if attr == 'cxx_class_name':
3637675Snate@binkert.org            return cls.cxx_class_path[-1]
3647675Snate@binkert.org
3657675Snate@binkert.org        if attr == 'cxx_namespaces':
3667675Snate@binkert.org            return cls.cxx_class_path[:-1]
3677675Snate@binkert.org
3681692SN/A        if cls._values.has_key(attr):
3691692SN/A            return cls._values[attr]
3701585SN/A
3717528Ssteve.reinhardt@amd.com        if cls._children.has_key(attr):
3727528Ssteve.reinhardt@amd.com            return cls._children[attr]
3737528Ssteve.reinhardt@amd.com
3741585SN/A        raise AttributeError, \
3751585SN/A              "object '%s' has no attribute '%s'" % (cls.__name__, attr)
3761585SN/A
3773100SN/A    def __str__(cls):
3783100SN/A        return cls.__name__
3793100SN/A
3807673Snate@binkert.org    def cxx_decl(cls, code):
3813100SN/A        # The 'dict' attribute restricts us to the params declared in
3823100SN/A        # the object itself, not including inherited params (which
3833100SN/A        # will also be inherited from the base class's param struct
3843100SN/A        # here).
3854762Snate@binkert.org        params = cls._params.local.values()
3863100SN/A        try:
3873100SN/A            ptypes = [p.ptype for p in params]
3883100SN/A        except:
3893100SN/A            print cls, p, p.ptype_str
3903100SN/A            print params
3913100SN/A            raise
3923100SN/A
3937675Snate@binkert.org        class_path = cls._value_dict['cxx_class'].split('::')
3947675Snate@binkert.org
3957675Snate@binkert.org        code('''\
3967675Snate@binkert.org#ifndef __PARAMS__${cls}__
3977675Snate@binkert.org#define __PARAMS__${cls}__
3987675Snate@binkert.org
3997675Snate@binkert.org''')
4007675Snate@binkert.org
4017675Snate@binkert.org        # A forward class declaration is sufficient since we are just
4027675Snate@binkert.org        # declaring a pointer.
4037675Snate@binkert.org        for ns in class_path[:-1]:
4047675Snate@binkert.org            code('namespace $ns {')
4057675Snate@binkert.org        code('class $0;', class_path[-1])
4067675Snate@binkert.org        for ns in reversed(class_path[:-1]):
4077811Ssteve.reinhardt@amd.com            code('} // namespace $ns')
4087675Snate@binkert.org        code()
4097675Snate@binkert.org
4107673Snate@binkert.org        for param in params:
4117673Snate@binkert.org            param.cxx_predecls(code)
4127673Snate@binkert.org        code()
4134762Snate@binkert.org
4145610Snate@binkert.org        if cls._base:
4157673Snate@binkert.org            code('#include "params/${{cls._base.type}}.hh"')
4167673Snate@binkert.org            code()
4174762Snate@binkert.org
4184762Snate@binkert.org        for ptype in ptypes:
4194762Snate@binkert.org            if issubclass(ptype, Enum):
4207673Snate@binkert.org                code('#include "enums/${{ptype.__name__}}.hh"')
4217673Snate@binkert.org                code()
4224762Snate@binkert.org
4237673Snate@binkert.org        cls.cxx_struct(code, cls._base, params)
4245488Snate@binkert.org
4257673Snate@binkert.org        code()
4267673Snate@binkert.org        code('#endif // __PARAMS__${cls}__')
4275488Snate@binkert.org        return code
4285488Snate@binkert.org
4297673Snate@binkert.org    def cxx_struct(cls, code, base, params):
4305488Snate@binkert.org        if cls == SimObject:
4317673Snate@binkert.org            code('#include "sim/sim_object_params.hh"')
4327673Snate@binkert.org            return
4335488Snate@binkert.org
4344762Snate@binkert.org        # now generate the actual param struct
4357673Snate@binkert.org        code("struct ${cls}Params")
4364762Snate@binkert.org        if base:
4377673Snate@binkert.org            code("    : public ${{base.type}}Params")
4387673Snate@binkert.org        code("{")
4394762Snate@binkert.org        if not hasattr(cls, 'abstract') or not cls.abstract:
4404762Snate@binkert.org            if 'type' in cls.__dict__:
4417673Snate@binkert.org                code("    ${{cls.cxx_type}} create();")
4424762Snate@binkert.org
4437673Snate@binkert.org        code.indent()
4447673Snate@binkert.org        for param in params:
4457673Snate@binkert.org            param.cxx_decl(code)
4467673Snate@binkert.org        code.dedent()
4477673Snate@binkert.org        code('};')
4484762Snate@binkert.org
4497673Snate@binkert.org    def swig_decl(cls, code):
4507673Snate@binkert.org        code('''\
4517673Snate@binkert.org%module $cls
4524762Snate@binkert.org
4537673Snate@binkert.org%{
4547673Snate@binkert.org#include "params/$cls.hh"
4557673Snate@binkert.org%}
4567673Snate@binkert.org
4577673Snate@binkert.org''')
4584762Snate@binkert.org
4594762Snate@binkert.org        # The 'dict' attribute restricts us to the params declared in
4604762Snate@binkert.org        # the object itself, not including inherited params (which
4614762Snate@binkert.org        # will also be inherited from the base class's param struct
4624762Snate@binkert.org        # here).
4634762Snate@binkert.org        params = cls._params.local.values()
4644762Snate@binkert.org        ptypes = [p.ptype for p in params]
4654762Snate@binkert.org
4667673Snate@binkert.org        # get all predeclarations
4677673Snate@binkert.org        for param in params:
4687673Snate@binkert.org            param.swig_predecls(code)
4697673Snate@binkert.org        code()
4703100SN/A
4715610Snate@binkert.org        if cls._base:
4727677Snate@binkert.org            code('%import "python/m5/internal/param_${{cls._base.type}}.i"')
4737673Snate@binkert.org            code()
4743100SN/A
4754762Snate@binkert.org        for ptype in ptypes:
4764762Snate@binkert.org            if issubclass(ptype, Enum):
4777673Snate@binkert.org                code('%import "enums/${{ptype.__name__}}.hh"')
4787673Snate@binkert.org                code()
4793100SN/A
4807673Snate@binkert.org        code('%import "params/${cls}_type.hh"')
4817673Snate@binkert.org        code('%include "params/${cls}.hh"')
4823100SN/A
4832740SN/A# The SimObject class is the root of the special hierarchy.  Most of
484679SN/A# the code in this class deals with the configuration hierarchy itself
485679SN/A# (parent/child node relationships).
4861692SN/Aclass SimObject(object):
4871692SN/A    # Specify metaclass.  Any class inheriting from SimObject will
488679SN/A    # get this metaclass.
4891692SN/A    __metaclass__ = MetaSimObject
4903100SN/A    type = 'SimObject'
4914762Snate@binkert.org    abstract = True
4923100SN/A
4937673Snate@binkert.org    @classmethod
4947673Snate@binkert.org    def swig_objdecls(cls, code):
4957673Snate@binkert.org        code('%include "python/swig/sim_object.i"')
496679SN/A
4972740SN/A    # Initialize new instance.  For objects with SimObject-valued
4982740SN/A    # children, we need to recursively clone the classes represented
4992740SN/A    # by those param values as well in a consistent "deep copy"-style
5002740SN/A    # fashion.  That is, we want to make sure that each instance is
5012740SN/A    # cloned only once, and that if there are multiple references to
5022740SN/A    # the same original object, we end up with the corresponding
5032740SN/A    # cloned references all pointing to the same cloned instance.
5042740SN/A    def __init__(self, **kwargs):
5052740SN/A        ancestor = kwargs.get('_ancestor')
5062740SN/A        memo_dict = kwargs.get('_memo')
5072740SN/A        if memo_dict is None:
5082740SN/A            # prepare to memoize any recursively instantiated objects
5092740SN/A            memo_dict = {}
5102740SN/A        elif ancestor:
5112740SN/A            # memoize me now to avoid problems with recursive calls
5122740SN/A            memo_dict[ancestor] = self
5132711SN/A
5142740SN/A        if not ancestor:
5152740SN/A            ancestor = self.__class__
5162740SN/A        ancestor._instantiated = True
5172711SN/A
5182740SN/A        # initialize required attributes
5192740SN/A        self._parent = None
5207528Ssteve.reinhardt@amd.com        self._name = None
5212740SN/A        self._ccObject = None  # pointer to C++ object
5224762Snate@binkert.org        self._ccParams = None
5232740SN/A        self._instantiated = False # really "cloned"
5242712SN/A
5258321Ssteve.reinhardt@amd.com        # Clone children specified at class level.  No need for a
5268321Ssteve.reinhardt@amd.com        # multidict here since we will be cloning everything.
5278321Ssteve.reinhardt@amd.com        # Do children before parameter values so that children that
5288321Ssteve.reinhardt@amd.com        # are also param values get cloned properly.
5298321Ssteve.reinhardt@amd.com        self._children = {}
5308321Ssteve.reinhardt@amd.com        for key,val in ancestor._children.iteritems():
5318321Ssteve.reinhardt@amd.com            self.add_child(key, val(_memo=memo_dict))
5328321Ssteve.reinhardt@amd.com
5332711SN/A        # Inherit parameter values from class using multidict so
5347528Ssteve.reinhardt@amd.com        # individual value settings can be overridden but we still
5357528Ssteve.reinhardt@amd.com        # inherit late changes to non-overridden class values.
5362740SN/A        self._values = multidict(ancestor._values)
5372740SN/A        # clone SimObject-valued parameters
5382740SN/A        for key,val in ancestor._values.iteritems():
5397528Ssteve.reinhardt@amd.com            val = tryAsSimObjectOrVector(val)
5407528Ssteve.reinhardt@amd.com            if val is not None:
5417528Ssteve.reinhardt@amd.com                self._values[key] = val(_memo=memo_dict)
5427528Ssteve.reinhardt@amd.com
5432740SN/A        # clone port references.  no need to use a multidict here
5442740SN/A        # since we will be creating new references for all ports.
5453105Sstever@eecs.umich.edu        self._port_refs = {}
5463105Sstever@eecs.umich.edu        for key,val in ancestor._port_refs.iteritems():
5473105Sstever@eecs.umich.edu            self._port_refs[key] = val.clone(self, memo_dict)
5481692SN/A        # apply attribute assignments from keyword args, if any
5491692SN/A        for key,val in kwargs.iteritems():
5501692SN/A            setattr(self, key, val)
551679SN/A
5522740SN/A    # "Clone" the current instance by creating another instance of
5532740SN/A    # this instance's class, but that inherits its parameter values
5542740SN/A    # and port mappings from the current instance.  If we're in a
5552740SN/A    # "deep copy" recursive clone, check the _memo dict to see if
5562740SN/A    # we've already cloned this instance.
5571692SN/A    def __call__(self, **kwargs):
5582740SN/A        memo_dict = kwargs.get('_memo')
5592740SN/A        if memo_dict is None:
5602740SN/A            # no memo_dict: must be top-level clone operation.
5612740SN/A            # this is only allowed at the root of a hierarchy
5622740SN/A            if self._parent:
5632740SN/A                raise RuntimeError, "attempt to clone object %s " \
5642740SN/A                      "not at the root of a tree (parent = %s)" \
5652740SN/A                      % (self, self._parent)
5662740SN/A            # create a new dict and use that.
5672740SN/A            memo_dict = {}
5682740SN/A            kwargs['_memo'] = memo_dict
5692740SN/A        elif memo_dict.has_key(self):
5702740SN/A            # clone already done & memoized
5712740SN/A            return memo_dict[self]
5722740SN/A        return self.__class__(_ancestor = self, **kwargs)
5731343SN/A
5743105Sstever@eecs.umich.edu    def _get_port_ref(self, attr):
5753105Sstever@eecs.umich.edu        # Return reference that can be assigned to another port
5763105Sstever@eecs.umich.edu        # via __setattr__.  There is only ever one reference
5773105Sstever@eecs.umich.edu        # object per port, but we create them lazily here.
5783105Sstever@eecs.umich.edu        ref = self._port_refs.get(attr)
5793105Sstever@eecs.umich.edu        if not ref:
5803105Sstever@eecs.umich.edu            ref = self._ports[attr].makeRef(self)
5813105Sstever@eecs.umich.edu            self._port_refs[attr] = ref
5823105Sstever@eecs.umich.edu        return ref
5833105Sstever@eecs.umich.edu
5841692SN/A    def __getattr__(self, attr):
5852738SN/A        if self._ports.has_key(attr):
5863105Sstever@eecs.umich.edu            return self._get_port_ref(attr)
5872738SN/A
5881692SN/A        if self._values.has_key(attr):
5891692SN/A            return self._values[attr]
5901427SN/A
5917528Ssteve.reinhardt@amd.com        if self._children.has_key(attr):
5927528Ssteve.reinhardt@amd.com            return self._children[attr]
5937528Ssteve.reinhardt@amd.com
5947500Ssteve.reinhardt@amd.com        # If the attribute exists on the C++ object, transparently
5957500Ssteve.reinhardt@amd.com        # forward the reference there.  This is typically used for
5967500Ssteve.reinhardt@amd.com        # SWIG-wrapped methods such as init(), regStats(),
5977527Ssteve.reinhardt@amd.com        # regFormulas(), resetStats(), startup(), drain(), and
5987527Ssteve.reinhardt@amd.com        # resume().
5997500Ssteve.reinhardt@amd.com        if self._ccObject and hasattr(self._ccObject, attr):
6007500Ssteve.reinhardt@amd.com            return getattr(self._ccObject, attr)
6017500Ssteve.reinhardt@amd.com
6021692SN/A        raise AttributeError, "object '%s' has no attribute '%s'" \
6031692SN/A              % (self.__class__.__name__, attr)
6041427SN/A
6051692SN/A    # Set attribute (called on foo.attr = value when foo is an
6061692SN/A    # instance of class cls).
6071692SN/A    def __setattr__(self, attr, value):
6081692SN/A        # normal processing for private attributes
6091692SN/A        if attr.startswith('_'):
6101692SN/A            object.__setattr__(self, attr, value)
6111692SN/A            return
6121427SN/A
6132738SN/A        if self._ports.has_key(attr):
6142738SN/A            # set up port connection
6153105Sstever@eecs.umich.edu            self._get_port_ref(attr).connect(value)
6162738SN/A            return
6172738SN/A
6182740SN/A        if isSimObjectOrSequence(value) and self._instantiated:
6192740SN/A            raise RuntimeError, \
6202740SN/A                  "cannot set SimObject parameter '%s' after\n" \
6212740SN/A                  "    instance been cloned %s" % (attr, `self`)
6222740SN/A
6233105Sstever@eecs.umich.edu        param = self._params.get(attr)
6241692SN/A        if param:
6251310SN/A            try:
6261692SN/A                value = param.convert(value)
6271587SN/A            except Exception, e:
6281692SN/A                msg = "%s\nError setting param %s.%s to %s\n" % \
6291692SN/A                      (e, self.__class__.__name__, attr, value)
6301605SN/A                e.args = (msg, )
6311605SN/A                raise
6327528Ssteve.reinhardt@amd.com            self._values[attr] = value
6338321Ssteve.reinhardt@amd.com            # implicitly parent unparented objects assigned as params
6348321Ssteve.reinhardt@amd.com            if isSimObjectOrVector(value) and not value.has_parent():
6358321Ssteve.reinhardt@amd.com                self.add_child(attr, value)
6363105Sstever@eecs.umich.edu            return
6371310SN/A
6387528Ssteve.reinhardt@amd.com        # if RHS is a SimObject, it's an implicit child assignment
6393105Sstever@eecs.umich.edu        if isSimObjectOrSequence(value):
6407528Ssteve.reinhardt@amd.com            self.add_child(attr, value)
6413105Sstever@eecs.umich.edu            return
6421693SN/A
6433105Sstever@eecs.umich.edu        # no valid assignment... raise exception
6443105Sstever@eecs.umich.edu        raise AttributeError, "Class %s has no parameter %s" \
6453105Sstever@eecs.umich.edu              % (self.__class__.__name__, attr)
6461310SN/A
6471310SN/A
6481692SN/A    # this hack allows tacking a '[0]' onto parameters that may or may
6491692SN/A    # not be vectors, and always getting the first element (e.g. cpus)
6501692SN/A    def __getitem__(self, key):
6511692SN/A        if key == 0:
6521692SN/A            return self
6531692SN/A        raise TypeError, "Non-zero index '%s' to SimObject" % key
6541310SN/A
6557528Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
6567528Ssteve.reinhardt@amd.com    def clear_parent(self, old_parent):
6577528Ssteve.reinhardt@amd.com        assert self._parent is old_parent
6587528Ssteve.reinhardt@amd.com        self._parent = None
6597528Ssteve.reinhardt@amd.com
6607528Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
6617528Ssteve.reinhardt@amd.com    def set_parent(self, parent, name):
6627528Ssteve.reinhardt@amd.com        self._parent = parent
6637528Ssteve.reinhardt@amd.com        self._name = name
6647528Ssteve.reinhardt@amd.com
6657528Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
6667528Ssteve.reinhardt@amd.com    def get_name(self):
6677528Ssteve.reinhardt@amd.com        return self._name
6687528Ssteve.reinhardt@amd.com
6698321Ssteve.reinhardt@amd.com    # Also implemented by SimObjectVector
6708321Ssteve.reinhardt@amd.com    def has_parent(self):
6718321Ssteve.reinhardt@amd.com        return self._parent is not None
6727528Ssteve.reinhardt@amd.com
6737742Sgblack@eecs.umich.edu    # clear out child with given name. This code is not likely to be exercised.
6747742Sgblack@eecs.umich.edu    # See comment in add_child.
6751693SN/A    def clear_child(self, name):
6761693SN/A        child = self._children[name]
6777528Ssteve.reinhardt@amd.com        child.clear_parent(self)
6781693SN/A        del self._children[name]
6791693SN/A
6807528Ssteve.reinhardt@amd.com    # Add a new child to this object.
6817528Ssteve.reinhardt@amd.com    def add_child(self, name, child):
6827528Ssteve.reinhardt@amd.com        child = coerceSimObjectOrVector(child)
6838321Ssteve.reinhardt@amd.com        if child.has_parent():
6848321Ssteve.reinhardt@amd.com            print "warning: add_child('%s'): child '%s' already has parent" % \
6858321Ssteve.reinhardt@amd.com                  (name, child.get_name())
6867528Ssteve.reinhardt@amd.com        if self._children.has_key(name):
6877742Sgblack@eecs.umich.edu            # This code path had an undiscovered bug that would make it fail
6887742Sgblack@eecs.umich.edu            # at runtime. It had been here for a long time and was only
6897742Sgblack@eecs.umich.edu            # exposed by a buggy script. Changes here will probably not be
6907742Sgblack@eecs.umich.edu            # exercised without specialized testing.
6917738Sgblack@eecs.umich.edu            self.clear_child(name)
6927528Ssteve.reinhardt@amd.com        child.set_parent(self, name)
6937528Ssteve.reinhardt@amd.com        self._children[name] = child
6941310SN/A
6957528Ssteve.reinhardt@amd.com    # Take SimObject-valued parameters that haven't been explicitly
6967528Ssteve.reinhardt@amd.com    # assigned as children and make them children of the object that
6977528Ssteve.reinhardt@amd.com    # they were assigned to as a parameter value.  This guarantees
6987528Ssteve.reinhardt@amd.com    # that when we instantiate all the parameter objects we're still
6997528Ssteve.reinhardt@amd.com    # inside the configuration hierarchy.
7007528Ssteve.reinhardt@amd.com    def adoptOrphanParams(self):
7017528Ssteve.reinhardt@amd.com        for key,val in self._values.iteritems():
7027528Ssteve.reinhardt@amd.com            if not isSimObjectVector(val) and isSimObjectSequence(val):
7037528Ssteve.reinhardt@amd.com                # need to convert raw SimObject sequences to
7048321Ssteve.reinhardt@amd.com                # SimObjectVector class so we can call has_parent()
7057528Ssteve.reinhardt@amd.com                val = SimObjectVector(val)
7067528Ssteve.reinhardt@amd.com                self._values[key] = val
7078321Ssteve.reinhardt@amd.com            if isSimObjectOrVector(val) and not val.has_parent():
7088321Ssteve.reinhardt@amd.com                print "warning: %s adopting orphan SimObject param '%s'" \
7098321Ssteve.reinhardt@amd.com                      % (self, key)
7107528Ssteve.reinhardt@amd.com                self.add_child(key, val)
7113105Sstever@eecs.umich.edu
7121692SN/A    def path(self):
7132740SN/A        if not self._parent:
7148321Ssteve.reinhardt@amd.com            return '<orphan %s>' % self.__class__
7151692SN/A        ppath = self._parent.path()
7161692SN/A        if ppath == 'root':
7171692SN/A            return self._name
7181692SN/A        return ppath + "." + self._name
7191310SN/A
7201692SN/A    def __str__(self):
7211692SN/A        return self.path()
7221310SN/A
7231692SN/A    def ini_str(self):
7241692SN/A        return self.path()
7251310SN/A
7261692SN/A    def find_any(self, ptype):
7271692SN/A        if isinstance(self, ptype):
7281692SN/A            return self, True
7291310SN/A
7301692SN/A        found_obj = None
7311692SN/A        for child in self._children.itervalues():
7321692SN/A            if isinstance(child, ptype):
7331692SN/A                if found_obj != None and child != found_obj:
7341692SN/A                    raise AttributeError, \
7351692SN/A                          'parent.any matched more than one: %s %s' % \
7361814SN/A                          (found_obj.path, child.path)
7371692SN/A                found_obj = child
7381692SN/A        # search param space
7391692SN/A        for pname,pdesc in self._params.iteritems():
7401692SN/A            if issubclass(pdesc.ptype, ptype):
7411692SN/A                match_obj = self._values[pname]
7421692SN/A                if found_obj != None and found_obj != match_obj:
7431692SN/A                    raise AttributeError, \
7445952Ssaidi@eecs.umich.edu                          'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path)
7451692SN/A                found_obj = match_obj
7461692SN/A        return found_obj, found_obj != None
7471692SN/A
7481815SN/A    def unproxy(self, base):
7491815SN/A        return self
7501815SN/A
7517527Ssteve.reinhardt@amd.com    def unproxyParams(self):
7523105Sstever@eecs.umich.edu        for param in self._params.iterkeys():
7533105Sstever@eecs.umich.edu            value = self._values.get(param)
7546654Snate@binkert.org            if value != None and isproxy(value):
7553105Sstever@eecs.umich.edu                try:
7563105Sstever@eecs.umich.edu                    value = value.unproxy(self)
7573105Sstever@eecs.umich.edu                except:
7583105Sstever@eecs.umich.edu                    print "Error in unproxying param '%s' of %s" % \
7593105Sstever@eecs.umich.edu                          (param, self.path())
7603105Sstever@eecs.umich.edu                    raise
7613105Sstever@eecs.umich.edu                setattr(self, param, value)
7623105Sstever@eecs.umich.edu
7633107Sstever@eecs.umich.edu        # Unproxy ports in sorted order so that 'append' operations on
7643107Sstever@eecs.umich.edu        # vector ports are done in a deterministic fashion.
7653107Sstever@eecs.umich.edu        port_names = self._ports.keys()
7663107Sstever@eecs.umich.edu        port_names.sort()
7673107Sstever@eecs.umich.edu        for port_name in port_names:
7683105Sstever@eecs.umich.edu            port = self._port_refs.get(port_name)
7693105Sstever@eecs.umich.edu            if port != None:
7703105Sstever@eecs.umich.edu                port.unproxy(self)
7713105Sstever@eecs.umich.edu
7725037Smilesck@eecs.umich.edu    def print_ini(self, ini_file):
7735543Ssaidi@eecs.umich.edu        print >>ini_file, '[' + self.path() + ']'       # .ini section header
7741692SN/A
7752738SN/A        instanceDict[self.path()] = self
7762738SN/A
7774081Sbinkertn@umich.edu        if hasattr(self, 'type'):
7785037Smilesck@eecs.umich.edu            print >>ini_file, 'type=%s' % self.type
7791692SN/A
7801692SN/A        child_names = self._children.keys()
7811692SN/A        child_names.sort()
7824081Sbinkertn@umich.edu        if len(child_names):
7837528Ssteve.reinhardt@amd.com            print >>ini_file, 'children=%s' % \
7847528Ssteve.reinhardt@amd.com                  ' '.join(self._children[n].get_name() for n in child_names)
7851692SN/A
7861692SN/A        param_names = self._params.keys()
7871692SN/A        param_names.sort()
7881692SN/A        for param in param_names:
7893105Sstever@eecs.umich.edu            value = self._values.get(param)
7901692SN/A            if value != None:
7915037Smilesck@eecs.umich.edu                print >>ini_file, '%s=%s' % (param,
7925037Smilesck@eecs.umich.edu                                             self._values[param].ini_str())
7931692SN/A
7943103Sstever@eecs.umich.edu        port_names = self._ports.keys()
7953103Sstever@eecs.umich.edu        port_names.sort()
7963103Sstever@eecs.umich.edu        for port_name in port_names:
7973105Sstever@eecs.umich.edu            port = self._port_refs.get(port_name, None)
7983105Sstever@eecs.umich.edu            if port != None:
7995037Smilesck@eecs.umich.edu                print >>ini_file, '%s=%s' % (port_name, port.ini_str())
8003103Sstever@eecs.umich.edu
8015543Ssaidi@eecs.umich.edu        print >>ini_file        # blank line between objects
8021692SN/A
8034762Snate@binkert.org    def getCCParams(self):
8044762Snate@binkert.org        if self._ccParams:
8054762Snate@binkert.org            return self._ccParams
8064762Snate@binkert.org
8077677Snate@binkert.org        cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type)
8084762Snate@binkert.org        cc_params = cc_params_struct()
8095488Snate@binkert.org        cc_params.pyobj = self
8104762Snate@binkert.org        cc_params.name = str(self)
8114762Snate@binkert.org
8124762Snate@binkert.org        param_names = self._params.keys()
8134762Snate@binkert.org        param_names.sort()
8144762Snate@binkert.org        for param in param_names:
8154762Snate@binkert.org            value = self._values.get(param)
8164762Snate@binkert.org            if value is None:
8176654Snate@binkert.org                fatal("%s.%s without default or user set value",
8186654Snate@binkert.org                      self.path(), param)
8194762Snate@binkert.org
8204762Snate@binkert.org            value = value.getValue()
8214762Snate@binkert.org            if isinstance(self._params[param], VectorParamDesc):
8224762Snate@binkert.org                assert isinstance(value, list)
8234762Snate@binkert.org                vec = getattr(cc_params, param)
8244762Snate@binkert.org                assert not len(vec)
8254762Snate@binkert.org                for v in value:
8264762Snate@binkert.org                    vec.append(v)
8274762Snate@binkert.org            else:
8284762Snate@binkert.org                setattr(cc_params, param, value)
8294762Snate@binkert.org
8304762Snate@binkert.org        port_names = self._ports.keys()
8314762Snate@binkert.org        port_names.sort()
8324762Snate@binkert.org        for port_name in port_names:
8334762Snate@binkert.org            port = self._port_refs.get(port_name, None)
8344762Snate@binkert.org            if port != None:
8354762Snate@binkert.org                setattr(cc_params, port_name, port)
8364762Snate@binkert.org        self._ccParams = cc_params
8374762Snate@binkert.org        return self._ccParams
8382738SN/A
8392740SN/A    # Get C++ object corresponding to this object, calling C++ if
8402740SN/A    # necessary to construct it.  Does *not* recursively create
8412740SN/A    # children.
8422740SN/A    def getCCObject(self):
8432740SN/A        if not self._ccObject:
8447526Ssteve.reinhardt@amd.com            # Make sure this object is in the configuration hierarchy
8457526Ssteve.reinhardt@amd.com            if not self._parent and not isRoot(self):
8467526Ssteve.reinhardt@amd.com                raise RuntimeError, "Attempt to instantiate orphan node"
8477526Ssteve.reinhardt@amd.com            # Cycles in the configuration hierarchy are not supported. This
8485244Sgblack@eecs.umich.edu            # will catch the resulting recursion and stop.
8495244Sgblack@eecs.umich.edu            self._ccObject = -1
8505244Sgblack@eecs.umich.edu            params = self.getCCParams()
8514762Snate@binkert.org            self._ccObject = params.create()
8522740SN/A        elif self._ccObject == -1:
8537526Ssteve.reinhardt@amd.com            raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
8542740SN/A                  % self.path()
8552740SN/A        return self._ccObject
8562740SN/A
8577527Ssteve.reinhardt@amd.com    def descendants(self):
8587527Ssteve.reinhardt@amd.com        yield self
8597527Ssteve.reinhardt@amd.com        for child in self._children.itervalues():
8607527Ssteve.reinhardt@amd.com            for obj in child.descendants():
8617527Ssteve.reinhardt@amd.com                yield obj
8627527Ssteve.reinhardt@amd.com
8637527Ssteve.reinhardt@amd.com    # Call C++ to create C++ object corresponding to this object
8644762Snate@binkert.org    def createCCObject(self):
8654762Snate@binkert.org        self.getCCParams()
8664762Snate@binkert.org        self.getCCObject() # force creation
8674762Snate@binkert.org
8684762Snate@binkert.org    def getValue(self):
8694762Snate@binkert.org        return self.getCCObject()
8704762Snate@binkert.org
8712738SN/A    # Create C++ port connections corresponding to the connections in
8727527Ssteve.reinhardt@amd.com    # _port_refs
8732738SN/A    def connectPorts(self):
8743105Sstever@eecs.umich.edu        for portRef in self._port_refs.itervalues():
8753105Sstever@eecs.umich.edu            portRef.ccConnect()
8762797SN/A
8774553Sbinkertn@umich.edu    def getMemoryMode(self):
8784553Sbinkertn@umich.edu        if not isinstance(self, m5.objects.System):
8794553Sbinkertn@umich.edu            return None
8804553Sbinkertn@umich.edu
8814859Snate@binkert.org        return self._ccObject.getMemoryMode()
8824553Sbinkertn@umich.edu
8832797SN/A    def changeTiming(self, mode):
8843202Shsul@eecs.umich.edu        if isinstance(self, m5.objects.System):
8853202Shsul@eecs.umich.edu            # i don't know if there's a better way to do this - calling
8863202Shsul@eecs.umich.edu            # setMemoryMode directly from self._ccObject results in calling
8873202Shsul@eecs.umich.edu            # SimObject::setMemoryMode, not the System::setMemoryMode
8884859Snate@binkert.org            self._ccObject.setMemoryMode(mode)
8892797SN/A
8902797SN/A    def takeOverFrom(self, old_cpu):
8914859Snate@binkert.org        self._ccObject.takeOverFrom(old_cpu._ccObject)
8922797SN/A
8931692SN/A    # generate output file for 'dot' to display as a pretty graph.
8941692SN/A    # this code is currently broken.
8951342SN/A    def outputDot(self, dot):
8961342SN/A        label = "{%s|" % self.path
8971342SN/A        if isSimObject(self.realtype):
8981342SN/A            label +=  '%s|' % self.type
8991342SN/A
9001342SN/A        if self.children:
9011342SN/A            # instantiate children in same order they were added for
9021342SN/A            # backward compatibility (else we can end up with cpu1
9031342SN/A            # before cpu0).
9041342SN/A            for c in self.children:
9051342SN/A                dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
9061342SN/A
9071342SN/A        simobjs = []
9081342SN/A        for param in self.params:
9091342SN/A            try:
9101342SN/A                if param.value is None:
9111342SN/A                    raise AttributeError, 'Parameter with no value'
9121342SN/A
9131692SN/A                value = param.value
9141342SN/A                string = param.string(value)
9151587SN/A            except Exception, e:
9161605SN/A                msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
9171605SN/A                e.args = (msg, )
9181342SN/A                raise
9191605SN/A
9201692SN/A            if isSimObject(param.ptype) and string != "Null":
9211342SN/A                simobjs.append(string)
9221342SN/A            else:
9231342SN/A                label += '%s = %s\\n' % (param.name, string)
9241342SN/A
9251342SN/A        for so in simobjs:
9261342SN/A            label += "|<%s> %s" % (so, so)
9271587SN/A            dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
9281587SN/A                                    tailport="w"))
9291342SN/A        label += '}'
9301342SN/A        dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
9311342SN/A
9321342SN/A        # recursively dump out children
9331342SN/A        for c in self.children:
9341342SN/A            c.outputDot(dot)
9351342SN/A
9363101Sstever@eecs.umich.edu# Function to provide to C++ so it can look up instances based on paths
9373101Sstever@eecs.umich.edudef resolveSimObject(name):
9383101Sstever@eecs.umich.edu    obj = instanceDict[name]
9393101Sstever@eecs.umich.edu    return obj.getCCObject()
940679SN/A
9416654Snate@binkert.orgdef isSimObject(value):
9426654Snate@binkert.org    return isinstance(value, SimObject)
9436654Snate@binkert.org
9446654Snate@binkert.orgdef isSimObjectClass(value):
9456654Snate@binkert.org    return issubclass(value, SimObject)
9466654Snate@binkert.org
9477528Ssteve.reinhardt@amd.comdef isSimObjectVector(value):
9487528Ssteve.reinhardt@amd.com    return isinstance(value, SimObjectVector)
9497528Ssteve.reinhardt@amd.com
9506654Snate@binkert.orgdef isSimObjectSequence(value):
9516654Snate@binkert.org    if not isinstance(value, (list, tuple)) or len(value) == 0:
9526654Snate@binkert.org        return False
9536654Snate@binkert.org
9546654Snate@binkert.org    for val in value:
9556654Snate@binkert.org        if not isNullPointer(val) and not isSimObject(val):
9566654Snate@binkert.org            return False
9576654Snate@binkert.org
9586654Snate@binkert.org    return True
9596654Snate@binkert.org
9606654Snate@binkert.orgdef isSimObjectOrSequence(value):
9616654Snate@binkert.org    return isSimObject(value) or isSimObjectSequence(value)
9626654Snate@binkert.org
9637526Ssteve.reinhardt@amd.comdef isRoot(obj):
9647526Ssteve.reinhardt@amd.com    from m5.objects import Root
9657526Ssteve.reinhardt@amd.com    return obj and obj is Root.getInstance()
9667526Ssteve.reinhardt@amd.com
9677528Ssteve.reinhardt@amd.comdef isSimObjectOrVector(value):
9687528Ssteve.reinhardt@amd.com    return isSimObject(value) or isSimObjectVector(value)
9697528Ssteve.reinhardt@amd.com
9707528Ssteve.reinhardt@amd.comdef tryAsSimObjectOrVector(value):
9717528Ssteve.reinhardt@amd.com    if isSimObjectOrVector(value):
9727528Ssteve.reinhardt@amd.com        return value
9737528Ssteve.reinhardt@amd.com    if isSimObjectSequence(value):
9747528Ssteve.reinhardt@amd.com        return SimObjectVector(value)
9757528Ssteve.reinhardt@amd.com    return None
9767528Ssteve.reinhardt@amd.com
9777528Ssteve.reinhardt@amd.comdef coerceSimObjectOrVector(value):
9787528Ssteve.reinhardt@amd.com    value = tryAsSimObjectOrVector(value)
9797528Ssteve.reinhardt@amd.com    if value is None:
9807528Ssteve.reinhardt@amd.com        raise TypeError, "SimObject or SimObjectVector expected"
9817528Ssteve.reinhardt@amd.com    return value
9827528Ssteve.reinhardt@amd.com
9836654Snate@binkert.orgbaseClasses = allClasses.copy()
9846654Snate@binkert.orgbaseInstances = instanceDict.copy()
9856654Snate@binkert.org
9866654Snate@binkert.orgdef clear():
9876654Snate@binkert.org    global allClasses, instanceDict
9886654Snate@binkert.org
9896654Snate@binkert.org    allClasses = baseClasses.copy()
9906654Snate@binkert.org    instanceDict = baseInstances.copy()
9916654Snate@binkert.org
9921528SN/A# __all__ defines the list of symbols that get exported when
9931528SN/A# 'from config import *' is invoked.  Try to keep this reasonably
9941528SN/A# short to avoid polluting other namespaces.
9954762Snate@binkert.org__all__ = [ 'SimObject' ]
996