SimObject.py revision 8912:62f60ee68b45
111988Sandreas.sandberg@arm.com# Copyright (c) 2012 ARM Limited
28839Sandreas.hansson@arm.com# All rights reserved.
38839Sandreas.hansson@arm.com#
48839Sandreas.hansson@arm.com# The license below extends only to copyright in the software and shall
58839Sandreas.hansson@arm.com# not be construed as granting a license to any other intellectual
68839Sandreas.hansson@arm.com# property including but not limited to intellectual property relating
78839Sandreas.hansson@arm.com# to a hardware implementation of the functionality of the software
88839Sandreas.hansson@arm.com# licensed hereunder.  You may use the software subject to the license
98839Sandreas.hansson@arm.com# terms below provided that you ensure that this notice is replicated
108839Sandreas.hansson@arm.com# unmodified and in its entirety in all distributions of the software,
118839Sandreas.hansson@arm.com# modified or unmodified, in source code or in binary form.
128839Sandreas.hansson@arm.com#
133101Sstever@eecs.umich.edu# Copyright (c) 2004-2006 The Regents of The University of Michigan
148579Ssteve.reinhardt@amd.com# Copyright (c) 2010 Advanced Micro Devices, Inc.
153101Sstever@eecs.umich.edu# All rights reserved.
163101Sstever@eecs.umich.edu#
173101Sstever@eecs.umich.edu# Redistribution and use in source and binary forms, with or without
183101Sstever@eecs.umich.edu# modification, are permitted provided that the following conditions are
193101Sstever@eecs.umich.edu# met: redistributions of source code must retain the above copyright
203101Sstever@eecs.umich.edu# notice, this list of conditions and the following disclaimer;
213101Sstever@eecs.umich.edu# redistributions in binary form must reproduce the above copyright
223101Sstever@eecs.umich.edu# notice, this list of conditions and the following disclaimer in the
233101Sstever@eecs.umich.edu# documentation and/or other materials provided with the distribution;
243101Sstever@eecs.umich.edu# neither the name of the copyright holders nor the names of its
253101Sstever@eecs.umich.edu# contributors may be used to endorse or promote products derived from
263101Sstever@eecs.umich.edu# this software without specific prior written permission.
273101Sstever@eecs.umich.edu#
283101Sstever@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
293101Sstever@eecs.umich.edu# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
303101Sstever@eecs.umich.edu# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
313101Sstever@eecs.umich.edu# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
323101Sstever@eecs.umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
333101Sstever@eecs.umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
343101Sstever@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
353101Sstever@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
363101Sstever@eecs.umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
373101Sstever@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
383101Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
393101Sstever@eecs.umich.edu#
403101Sstever@eecs.umich.edu# Authors: Steve Reinhardt
413101Sstever@eecs.umich.edu#          Nathan Binkert
427778Sgblack@eecs.umich.edu#          Andreas Hansson
438839Sandreas.hansson@arm.com
443101Sstever@eecs.umich.eduimport sys
453101Sstever@eecs.umich.edufrom types import FunctionType, MethodType, ModuleType
463101Sstever@eecs.umich.edu
473101Sstever@eecs.umich.edutry:
483101Sstever@eecs.umich.edu    import pydot
493101Sstever@eecs.umich.eduexcept:
503101Sstever@eecs.umich.edu    pydot = False
513101Sstever@eecs.umich.edu
523101Sstever@eecs.umich.eduimport m5
533101Sstever@eecs.umich.edufrom m5.util import *
543101Sstever@eecs.umich.edu
553101Sstever@eecs.umich.edu# Have to import params up top since Param is referenced on initial
563101Sstever@eecs.umich.edu# load (when SimObject class references Param to create a class
573101Sstever@eecs.umich.edu# variable, the 'name' param)...
583101Sstever@eecs.umich.edufrom m5.params import *
593101Sstever@eecs.umich.edu# There are a few things we need that aren't in params.__all__ since
603101Sstever@eecs.umich.edu# normal users don't need them
613101Sstever@eecs.umich.edufrom m5.params import ParamDesc, VectorParamDesc, \
6212563Sgabeblack@google.com     isNullPointer, SimObjectVector, Port
6312563Sgabeblack@google.com
643885Sbinkertn@umich.edufrom m5.proxy import *
653885Sbinkertn@umich.edufrom m5.proxy import isproxy
664762Snate@binkert.org
673885Sbinkertn@umich.edu#####################################################################
683885Sbinkertn@umich.edu#
697528Ssteve.reinhardt@amd.com# M5 Python Configuration Utility
703885Sbinkertn@umich.edu#
714380Sbinkertn@umich.edu# The basic idea is to write simple Python programs that build Python
724167Sbinkertn@umich.edu# objects corresponding to M5 SimObjects for the desired simulation
733102Sstever@eecs.umich.edu# configuration.  For now, the Python emits a .ini file that can be
743101Sstever@eecs.umich.edu# parsed by M5.  In the future, some tighter integration between M5
754762Snate@binkert.org# and the Python interpreter may allow bypassing the .ini file.
764762Snate@binkert.org#
774762Snate@binkert.org# Each SimObject class in M5 is represented by a Python class with the
784762Snate@binkert.org# same name.  The Python inheritance tree mirrors the M5 C++ tree
794762Snate@binkert.org# (e.g., SimpleCPU derives from BaseCPU in both cases, and all
804762Snate@binkert.org# SimObjects inherit from a single SimObject base class).  To specify
814762Snate@binkert.org# an instance of an M5 SimObject in a configuration, the user simply
824762Snate@binkert.org# instantiates the corresponding Python object.  The parameters for
834762Snate@binkert.org# that SimObject are given by assigning to attributes of the Python
845033Smilesck@eecs.umich.edu# object, either using keyword assignment in the constructor or in
855033Smilesck@eecs.umich.edu# separate assignment statements.  For example:
865033Smilesck@eecs.umich.edu#
875033Smilesck@eecs.umich.edu# cache = BaseCache(size='64KB')
885033Smilesck@eecs.umich.edu# cache.hit_latency = 3
895033Smilesck@eecs.umich.edu# cache.assoc = 8
905033Smilesck@eecs.umich.edu#
915033Smilesck@eecs.umich.edu# The magic lies in the mapping of the Python attributes for SimObject
925033Smilesck@eecs.umich.edu# classes to the actual SimObject parameter specifications.  This
935033Smilesck@eecs.umich.edu# allows parameter validity checking in the Python code.  Continuing
943101Sstever@eecs.umich.edu# the example above, the statements "cache.blurfl=3" or
953101Sstever@eecs.umich.edu# "cache.assoc='hello'" would both result in runtime errors in Python,
963101Sstever@eecs.umich.edu# since the BaseCache object has no 'blurfl' parameter and the 'assoc'
975033Smilesck@eecs.umich.edu# parameter requires an integer, respectively.  This magic is done
9810267SGeoffrey.Blake@arm.com# primarily by overriding the special __setattr__ method that controls
998596Ssteve.reinhardt@amd.com# assignment to object attributes.
1008596Ssteve.reinhardt@amd.com#
1018596Ssteve.reinhardt@amd.com# Once a set of Python objects have been instantiated in a hierarchy,
1028596Ssteve.reinhardt@amd.com# calling 'instantiate(obj)' (where obj is the root of the hierarchy)
1037673Snate@binkert.org# will generate a .ini file.
1047673Snate@binkert.org#
1057673Snate@binkert.org#####################################################################
1067673Snate@binkert.org
10711988Sandreas.sandberg@arm.com# list of all SimObject classes
10811988Sandreas.sandberg@arm.comallClasses = {}
10911988Sandreas.sandberg@arm.com
11011988Sandreas.sandberg@arm.com# dict to look up SimObjects based on path
1113101Sstever@eecs.umich.eduinstanceDict = {}
1123101Sstever@eecs.umich.edu
1133101Sstever@eecs.umich.edudef public_value(key, value):
1143101Sstever@eecs.umich.edu    return key.startswith('_') or \
1153101Sstever@eecs.umich.edu               isinstance(value, (FunctionType, MethodType, ModuleType,
11610380SAndrew.Bardsley@arm.com                                  classmethod, type))
11710380SAndrew.Bardsley@arm.com
11810380SAndrew.Bardsley@arm.com# The metaclass for SimObject.  This class controls how new classes
11910380SAndrew.Bardsley@arm.com# that derive from SimObject are instantiated, and provides inherited
12010380SAndrew.Bardsley@arm.com# class behavior (just like a class controls how instances of that
12110380SAndrew.Bardsley@arm.com# class are instantiated, and provides inherited instance behavior).
12210458Sandreas.hansson@arm.comclass MetaSimObject(type):
12310458Sandreas.hansson@arm.com    # Attributes that can be set only at initialization time
12410458Sandreas.hansson@arm.com    init_keywords = { 'abstract' : bool,
12510458Sandreas.hansson@arm.com                      'cxx_class' : str,
12610458Sandreas.hansson@arm.com                      'cxx_type' : str,
12710458Sandreas.hansson@arm.com                      'type' : str }
12810458Sandreas.hansson@arm.com    # Attributes that can be set any time
12910458Sandreas.hansson@arm.com    keywords = { 'check' : FunctionType }
13010458Sandreas.hansson@arm.com
13110458Sandreas.hansson@arm.com    # __new__ is called before __init__, and is where the statements
13210458Sandreas.hansson@arm.com    # in the body of the class definition get loaded into the class's
13310458Sandreas.hansson@arm.com    # __dict__.  We intercept this to filter out parameter & port assignments
1343101Sstever@eecs.umich.edu    # and only allow "private" attributes to be passed to the base
1353101Sstever@eecs.umich.edu    # __new__ (starting with underscore).
1363101Sstever@eecs.umich.edu    def __new__(mcls, name, bases, dict):
1373101Sstever@eecs.umich.edu        assert name not in allClasses, "SimObject %s already present" % name
1383101Sstever@eecs.umich.edu
13910267SGeoffrey.Blake@arm.com        # Copy "private" attributes, functions, and classes to the
14010267SGeoffrey.Blake@arm.com        # official dict.  Everything else goes in _init_dict to be
14110267SGeoffrey.Blake@arm.com        # filtered in __init__.
14210267SGeoffrey.Blake@arm.com        cls_dict = {}
1433101Sstever@eecs.umich.edu        value_dict = {}
1443101Sstever@eecs.umich.edu        for key,val in dict.items():
1453101Sstever@eecs.umich.edu            if public_value(key, val):
1463101Sstever@eecs.umich.edu                cls_dict[key] = val
1473101Sstever@eecs.umich.edu            else:
1483101Sstever@eecs.umich.edu                # must be a param/port setting
1493101Sstever@eecs.umich.edu                value_dict[key] = val
1503101Sstever@eecs.umich.edu        if 'abstract' not in value_dict:
1513101Sstever@eecs.umich.edu            value_dict['abstract'] = False
1523101Sstever@eecs.umich.edu        cls_dict['_value_dict'] = value_dict
1533101Sstever@eecs.umich.edu        cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
1543101Sstever@eecs.umich.edu        if 'type' in value_dict:
1553101Sstever@eecs.umich.edu            allClasses[name] = cls
1563101Sstever@eecs.umich.edu        return cls
1573101Sstever@eecs.umich.edu
1583101Sstever@eecs.umich.edu    # subclass initialization
1593101Sstever@eecs.umich.edu    def __init__(cls, name, bases, dict):
1603101Sstever@eecs.umich.edu        # calls type.__init__()... I think that's a no-op, but leave
1613101Sstever@eecs.umich.edu        # it here just in case it's not.
1623101Sstever@eecs.umich.edu        super(MetaSimObject, cls).__init__(name, bases, dict)
1633101Sstever@eecs.umich.edu
1643101Sstever@eecs.umich.edu        # initialize required attributes
1653101Sstever@eecs.umich.edu
1663101Sstever@eecs.umich.edu        # class-only attributes
1673101Sstever@eecs.umich.edu        cls._params = multidict() # param descriptions
1683101Sstever@eecs.umich.edu        cls._ports = multidict()  # port descriptions
1693101Sstever@eecs.umich.edu
1703101Sstever@eecs.umich.edu        # class or instance attributes
1713101Sstever@eecs.umich.edu        cls._values = multidict()   # param values
1723101Sstever@eecs.umich.edu        cls._children = multidict() # SimObject children
1733101Sstever@eecs.umich.edu        cls._port_refs = multidict() # port ref objects
1743101Sstever@eecs.umich.edu        cls._instantiated = False # really instantiated, cloned, or subclassed
1753101Sstever@eecs.umich.edu
1763101Sstever@eecs.umich.edu        # We don't support multiple inheritance.  If you want to, you
1773101Sstever@eecs.umich.edu        # must fix multidict to deal with it properly.
1785033Smilesck@eecs.umich.edu        if len(bases) > 1:
1796656Snate@binkert.org            raise TypeError, "SimObjects do not support multiple inheritance"
1805033Smilesck@eecs.umich.edu
1815033Smilesck@eecs.umich.edu        base = bases[0]
1825033Smilesck@eecs.umich.edu
1833101Sstever@eecs.umich.edu        # Set up general inheritance via multidicts.  A subclass will
1843101Sstever@eecs.umich.edu        # inherit all its settings from the base class.  The only time
1853101Sstever@eecs.umich.edu        # the following is not true is when we define the SimObject
18610267SGeoffrey.Blake@arm.com        # class itself (in which case the multidicts have no parent).
18710267SGeoffrey.Blake@arm.com        if isinstance(base, MetaSimObject):
18810267SGeoffrey.Blake@arm.com            cls._base = base
18910267SGeoffrey.Blake@arm.com            cls._params.parent = base._params
19010267SGeoffrey.Blake@arm.com            cls._ports.parent = base._ports
19110267SGeoffrey.Blake@arm.com            cls._values.parent = base._values
19210267SGeoffrey.Blake@arm.com            cls._children.parent = base._children
19310267SGeoffrey.Blake@arm.com            cls._port_refs.parent = base._port_refs
19410267SGeoffrey.Blake@arm.com            # mark base as having been subclassed
19510267SGeoffrey.Blake@arm.com            base._instantiated = True
19610267SGeoffrey.Blake@arm.com        else:
19710267SGeoffrey.Blake@arm.com            cls._base = None
19810267SGeoffrey.Blake@arm.com
1993101Sstever@eecs.umich.edu        # default keyword values
2003101Sstever@eecs.umich.edu        if 'type' in cls._value_dict:
2013101Sstever@eecs.umich.edu            if 'cxx_class' not in cls._value_dict:
2023101Sstever@eecs.umich.edu                cls._value_dict['cxx_class'] = cls._value_dict['type']
2033101Sstever@eecs.umich.edu
2043101Sstever@eecs.umich.edu            cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class']
2053101Sstever@eecs.umich.edu
2063101Sstever@eecs.umich.edu        # Export methods are automatically inherited via C++, so we
2073101Sstever@eecs.umich.edu        # don't want the method declarations to get inherited on the
2083101Sstever@eecs.umich.edu        # python side (and thus end up getting repeated in the wrapped
2093102Sstever@eecs.umich.edu        # versions of derived classes).  The code below basicallly
2103101Sstever@eecs.umich.edu        # suppresses inheritance by substituting in the base (null)
2113101Sstever@eecs.umich.edu        # versions of these methods unless a different version is
2123101Sstever@eecs.umich.edu        # explicitly supplied.
21310267SGeoffrey.Blake@arm.com        for method_name in ('export_methods', 'export_method_cxx_predecls',
21410267SGeoffrey.Blake@arm.com                            'export_method_swig_predecls'):
21510267SGeoffrey.Blake@arm.com            if method_name not in cls.__dict__:
21610267SGeoffrey.Blake@arm.com                base_method = getattr(MetaSimObject, method_name)
21710267SGeoffrey.Blake@arm.com                m = MethodType(base_method, cls, MetaSimObject)
21810267SGeoffrey.Blake@arm.com                setattr(cls, method_name, m)
21910267SGeoffrey.Blake@arm.com
2207673Snate@binkert.org        # Now process the _value_dict items.  They could be defining
2218607Sgblack@eecs.umich.edu        # new (or overriding existing) parameters or ports, setting
2227673Snate@binkert.org        # class keywords (e.g., 'abstract'), or setting parameter
2233101Sstever@eecs.umich.edu        # values or port bindings.  The first 3 can only be set when
22411988Sandreas.sandberg@arm.com        # the class is defined, so we handle them here.  The others
22511988Sandreas.sandberg@arm.com        # can be set later too, so just emulate that by calling
22611988Sandreas.sandberg@arm.com        # setattr().
2277673Snate@binkert.org        for key,val in cls._value_dict.items():
2287673Snate@binkert.org            # param descriptions
2293101Sstever@eecs.umich.edu            if isinstance(val, ParamDesc):
2303101Sstever@eecs.umich.edu                cls._new_param(key, val)
2313101Sstever@eecs.umich.edu
2323101Sstever@eecs.umich.edu            # port objects
2333101Sstever@eecs.umich.edu            elif isinstance(val, Port):
2343101Sstever@eecs.umich.edu                cls._new_port(key, val)
2355033Smilesck@eecs.umich.edu
2365475Snate@binkert.org            # init-time-only keywords
2375475Snate@binkert.org            elif cls.init_keywords.has_key(key):
2385475Snate@binkert.org                cls._set_keyword(key, val, cls.init_keywords[key])
2395475Snate@binkert.org
24010380SAndrew.Bardsley@arm.com            # default: use normal path (ends up in __setattr__)
24110380SAndrew.Bardsley@arm.com            else:
24210380SAndrew.Bardsley@arm.com                setattr(cls, key, val)
2433101Sstever@eecs.umich.edu
2443101Sstever@eecs.umich.edu    def _set_keyword(cls, keyword, val, kwtype):
2453101Sstever@eecs.umich.edu        if not isinstance(val, kwtype):
2464762Snate@binkert.org            raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
2474762Snate@binkert.org                  (keyword, type(val), kwtype)
2484762Snate@binkert.org        if isinstance(val, FunctionType):
2493101Sstever@eecs.umich.edu            val = classmethod(val)
25012050Snikos.nikoleris@arm.com        type.__setattr__(cls, keyword, val)
25112050Snikos.nikoleris@arm.com
25212050Snikos.nikoleris@arm.com    def _new_param(cls, name, pdesc):
2538459SAli.Saidi@ARM.com        # each param desc should be uniquely assigned to one variable
2548459SAli.Saidi@ARM.com        assert(not hasattr(pdesc, 'name'))
25512050Snikos.nikoleris@arm.com        pdesc.name = name
2563101Sstever@eecs.umich.edu        cls._params[name] = pdesc
2577528Ssteve.reinhardt@amd.com        if hasattr(pdesc, 'default'):
2587528Ssteve.reinhardt@amd.com            cls._set_param(name, pdesc.default, pdesc)
2597528Ssteve.reinhardt@amd.com
2607528Ssteve.reinhardt@amd.com    def _set_param(cls, name, value, param):
2617528Ssteve.reinhardt@amd.com        assert(param.name == name)
2627528Ssteve.reinhardt@amd.com        try:
2633101Sstever@eecs.umich.edu            value = param.convert(value)
2647528Ssteve.reinhardt@amd.com        except Exception, e:
2657528Ssteve.reinhardt@amd.com            msg = "%s\nError setting param %s.%s to %s\n" % \
2667528Ssteve.reinhardt@amd.com                  (e, cls.__name__, name, value)
2677528Ssteve.reinhardt@amd.com            e.args = (msg, )
2687528Ssteve.reinhardt@amd.com            raise
2697528Ssteve.reinhardt@amd.com        cls._values[name] = value
2707528Ssteve.reinhardt@amd.com        # if param value is a SimObject, make it a child too, so that
2717528Ssteve.reinhardt@amd.com        # it gets cloned properly when the class is instantiated
2727528Ssteve.reinhardt@amd.com        if isSimObjectOrVector(value) and not value.has_parent():
2737528Ssteve.reinhardt@amd.com            cls._add_cls_child(name, value)
2748321Ssteve.reinhardt@amd.com
27512194Sgabeblack@google.com    def _add_cls_child(cls, name, child):
2767528Ssteve.reinhardt@amd.com        # It's a little funky to have a class as a parent, but these
2777528Ssteve.reinhardt@amd.com        # objects should never be instantiated (only cloned, which
2787528Ssteve.reinhardt@amd.com        # clears the parent pointer), and this makes it clear that the
2797528Ssteve.reinhardt@amd.com        # object is not an orphan and can provide better error
2807528Ssteve.reinhardt@amd.com        # messages.
2817528Ssteve.reinhardt@amd.com        child.set_parent(cls, name)
2827528Ssteve.reinhardt@amd.com        cls._children[name] = child
2837528Ssteve.reinhardt@amd.com
2847528Ssteve.reinhardt@amd.com    def _new_port(cls, name, port):
2857528Ssteve.reinhardt@amd.com        # each port should be uniquely assigned to one variable
2867528Ssteve.reinhardt@amd.com        assert(not hasattr(port, 'name'))
2877528Ssteve.reinhardt@amd.com        port.name = name
2887528Ssteve.reinhardt@amd.com        cls._ports[name] = port
2893101Sstever@eecs.umich.edu
2908664SAli.Saidi@ARM.com    # same as _get_port_ref, effectively, but for classes
2918664SAli.Saidi@ARM.com    def _cls_get_port_ref(cls, attr):
2928664SAli.Saidi@ARM.com        # Return reference that can be assigned to another port
2938664SAli.Saidi@ARM.com        # via __setattr__.  There is only ever one reference
2948664SAli.Saidi@ARM.com        # object per port, but we create them lazily here.
2958664SAli.Saidi@ARM.com        ref = cls._port_refs.get(attr)
2969953Sgeoffrey.blake@arm.com        if not ref:
2979953Sgeoffrey.blake@arm.com            ref = cls._ports[attr].makeRef(cls)
2989953Sgeoffrey.blake@arm.com            cls._port_refs[attr] = ref
2999953Sgeoffrey.blake@arm.com        return ref
3009953Sgeoffrey.blake@arm.com
3019953Sgeoffrey.blake@arm.com    # Set attribute (called on foo.attr = value when foo is an
3029953Sgeoffrey.blake@arm.com    # instance of class cls).
3039953Sgeoffrey.blake@arm.com    def __setattr__(cls, attr, value):
3049953Sgeoffrey.blake@arm.com        # normal processing for private attributes
3059953Sgeoffrey.blake@arm.com        if public_value(attr, value):
3069953Sgeoffrey.blake@arm.com            type.__setattr__(cls, attr, value)
3079953Sgeoffrey.blake@arm.com            return
3089953Sgeoffrey.blake@arm.com
30910267SGeoffrey.Blake@arm.com        if cls.keywords.has_key(attr):
31010267SGeoffrey.Blake@arm.com            cls._set_keyword(attr, value, cls.keywords[attr])
31110267SGeoffrey.Blake@arm.com            return
31210267SGeoffrey.Blake@arm.com
31310267SGeoffrey.Blake@arm.com        if cls._ports.has_key(attr):
31410267SGeoffrey.Blake@arm.com            cls._cls_get_port_ref(attr).connect(value)
31510267SGeoffrey.Blake@arm.com            return
31612563Sgabeblack@google.com
31710267SGeoffrey.Blake@arm.com        if isSimObjectOrSequence(value) and cls._instantiated:
31810267SGeoffrey.Blake@arm.com            raise RuntimeError, \
31910267SGeoffrey.Blake@arm.com                  "cannot set SimObject parameter '%s' after\n" \
32010267SGeoffrey.Blake@arm.com                  "    class %s has been instantiated or subclassed" \
32110267SGeoffrey.Blake@arm.com                  % (attr, cls.__name__)
32210267SGeoffrey.Blake@arm.com
32310267SGeoffrey.Blake@arm.com        # check for param
32410267SGeoffrey.Blake@arm.com        param = cls._params.get(attr)
32510267SGeoffrey.Blake@arm.com        if param:
32610267SGeoffrey.Blake@arm.com            cls._set_param(attr, value, param)
32710267SGeoffrey.Blake@arm.com            return
32810267SGeoffrey.Blake@arm.com
3293101Sstever@eecs.umich.edu        if isSimObjectOrSequence(value):
3303101Sstever@eecs.umich.edu            # If RHS is a SimObject, it's an implicit child assignment.
3313101Sstever@eecs.umich.edu            cls._add_cls_child(attr, coerceSimObjectOrVector(value))
3323101Sstever@eecs.umich.edu            return
3333101Sstever@eecs.umich.edu
3343101Sstever@eecs.umich.edu        # no valid assignment... raise exception
3353101Sstever@eecs.umich.edu        raise AttributeError, \
33610364SGeoffrey.Blake@arm.com              "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
33710364SGeoffrey.Blake@arm.com
33810364SGeoffrey.Blake@arm.com    def __getattr__(cls, attr):
33910364SGeoffrey.Blake@arm.com        if attr == 'cxx_class_path':
3403101Sstever@eecs.umich.edu            return cls.cxx_class.split('::')
3414762Snate@binkert.org
3424762Snate@binkert.org        if attr == 'cxx_class_name':
3434762Snate@binkert.org            return cls.cxx_class_path[-1]
3444762Snate@binkert.org
3457528Ssteve.reinhardt@amd.com        if attr == 'cxx_namespaces':
3464762Snate@binkert.org            return cls.cxx_class_path[:-1]
3474762Snate@binkert.org
3484762Snate@binkert.org        if cls._values.has_key(attr):
34910267SGeoffrey.Blake@arm.com            return cls._values[attr]
35010267SGeoffrey.Blake@arm.com
35110267SGeoffrey.Blake@arm.com        if cls._children.has_key(attr):
35210267SGeoffrey.Blake@arm.com            return cls._children[attr]
35310267SGeoffrey.Blake@arm.com
35410267SGeoffrey.Blake@arm.com        raise AttributeError, \
35510267SGeoffrey.Blake@arm.com              "object '%s' has no attribute '%s'" % (cls.__name__, attr)
35610267SGeoffrey.Blake@arm.com
35710267SGeoffrey.Blake@arm.com    def __str__(cls):
35810267SGeoffrey.Blake@arm.com        return cls.__name__
35910267SGeoffrey.Blake@arm.com
36010267SGeoffrey.Blake@arm.com    # See ParamValue.cxx_predecls for description.
36110267SGeoffrey.Blake@arm.com    def cxx_predecls(cls, code):
36210267SGeoffrey.Blake@arm.com        code('#include "params/$cls.hh"')
36310267SGeoffrey.Blake@arm.com
36410267SGeoffrey.Blake@arm.com    # See ParamValue.swig_predecls for description.
36510267SGeoffrey.Blake@arm.com    def swig_predecls(cls, code):
36610267SGeoffrey.Blake@arm.com        code('%import "python/m5/internal/param_$cls.i"')
36710267SGeoffrey.Blake@arm.com
36810267SGeoffrey.Blake@arm.com    # Hook for exporting additional C++ methods to Python via SWIG.
36910267SGeoffrey.Blake@arm.com    # Default is none, override using @classmethod in class definition.
37010267SGeoffrey.Blake@arm.com    def export_methods(cls, code):
37110267SGeoffrey.Blake@arm.com        pass
37210267SGeoffrey.Blake@arm.com
37310267SGeoffrey.Blake@arm.com    # Generate the code needed as a prerequisite for the C++ methods
37410267SGeoffrey.Blake@arm.com    # exported via export_methods() to be compiled in the _wrap.cc
37510364SGeoffrey.Blake@arm.com    # file.  Typically generates one or more #include statements.  If
37610364SGeoffrey.Blake@arm.com    # any methods are exported, typically at least the C++ header
37710267SGeoffrey.Blake@arm.com    # declaring the relevant SimObject class must be included.
37810267SGeoffrey.Blake@arm.com    def export_method_cxx_predecls(cls, code):
37910267SGeoffrey.Blake@arm.com        pass
38010267SGeoffrey.Blake@arm.com
38110267SGeoffrey.Blake@arm.com    # Generate the code needed as a prerequisite for the C++ methods
38210267SGeoffrey.Blake@arm.com    # exported via export_methods() to be processed by SWIG.
3837673Snate@binkert.org    # Typically generates one or more %include or %import statements.
3847673Snate@binkert.org    # If any methods are exported, typically at least the C++ header
3857673Snate@binkert.org    # declaring the relevant SimObject class must be included.
3863101Sstever@eecs.umich.edu    def export_method_swig_predecls(cls, code):
38711988Sandreas.sandberg@arm.com        pass
38811988Sandreas.sandberg@arm.com
38911988Sandreas.sandberg@arm.com    # Generate the declaration for this object for wrapping with SWIG.
39011988Sandreas.sandberg@arm.com    # Generates code that goes into a SWIG .i file.  Called from
3917673Snate@binkert.org    # src/SConscript.
3927673Snate@binkert.org    def swig_decl(cls, code):
3933101Sstever@eecs.umich.edu        class_path = cls.cxx_class.split('::')
3943101Sstever@eecs.umich.edu        classname = class_path[-1]
3953101Sstever@eecs.umich.edu        namespaces = class_path[:-1]
3963101Sstever@eecs.umich.edu
3973101Sstever@eecs.umich.edu        # The 'local' attribute restricts us to the params declared in
3983101Sstever@eecs.umich.edu        # the object itself, not including inherited params (which
3993101Sstever@eecs.umich.edu        # will also be inherited from the base class's param struct
4003101Sstever@eecs.umich.edu        # here).
4013101Sstever@eecs.umich.edu        params = cls._params.local.values()
4023101Sstever@eecs.umich.edu        ports = cls._ports.local
4033101Sstever@eecs.umich.edu
4043101Sstever@eecs.umich.edu        code('%module(package="m5.internal") param_$cls')
4053101Sstever@eecs.umich.edu        code()
4063101Sstever@eecs.umich.edu        code('%{')
4073101Sstever@eecs.umich.edu        code('#include "params/$cls.hh"')
4085033Smilesck@eecs.umich.edu        for param in params:
4095033Smilesck@eecs.umich.edu            param.cxx_predecls(code)
4103101Sstever@eecs.umich.edu        cls.export_method_cxx_predecls(code)
4113101Sstever@eecs.umich.edu        code('''\
4123101Sstever@eecs.umich.edu/**
4133101Sstever@eecs.umich.edu  * This is a workaround for bug in swig. Prior to gcc 4.6.1 the STL
4143101Sstever@eecs.umich.edu  * headers like vector, string, etc. used to automatically pull in
4153101Sstever@eecs.umich.edu  * the cstddef header but starting with gcc 4.6.1 they no longer do.
4163101Sstever@eecs.umich.edu  * This leads to swig generated a file that does not compile so we
4173101Sstever@eecs.umich.edu  * explicitly include cstddef. Additionally, including version 2.0.4,
4183101Sstever@eecs.umich.edu  * swig uses ptrdiff_t without the std:: namespace prefix which is
4193101Sstever@eecs.umich.edu  * required with gcc 4.6.1. We explicitly provide access to it.
4203101Sstever@eecs.umich.edu  */
4213101Sstever@eecs.umich.edu#include <cstddef>
4223101Sstever@eecs.umich.eduusing std::ptrdiff_t;
4233101Sstever@eecs.umich.edu''')
4243101Sstever@eecs.umich.edu        code('%}')
4253101Sstever@eecs.umich.edu        code()
4263101Sstever@eecs.umich.edu
4273101Sstever@eecs.umich.edu        for param in params:
4283101Sstever@eecs.umich.edu            param.swig_predecls(code)
4293101Sstever@eecs.umich.edu        cls.export_method_swig_predecls(code)
4303101Sstever@eecs.umich.edu
4313101Sstever@eecs.umich.edu        code()
4323101Sstever@eecs.umich.edu        if cls._base:
4333101Sstever@eecs.umich.edu            code('%import "python/m5/internal/param_${{cls._base}}.i"')
4343101Sstever@eecs.umich.edu        code()
43510267SGeoffrey.Blake@arm.com
4367673Snate@binkert.org        for ns in namespaces:
4377673Snate@binkert.org            code('namespace $ns {')
4387673Snate@binkert.org
4397673Snate@binkert.org        if namespaces:
4407673Snate@binkert.org            code('// avoid name conflicts')
44110267SGeoffrey.Blake@arm.com            sep_string = '_COLONS_'
44210267SGeoffrey.Blake@arm.com            flat_name = sep_string.join(class_path)
44310267SGeoffrey.Blake@arm.com            code('%rename($flat_name) $classname;')
44410267SGeoffrey.Blake@arm.com
44510458Sandreas.hansson@arm.com        code()
44610458Sandreas.hansson@arm.com        code('// stop swig from creating/wrapping default ctor/dtor')
44710458Sandreas.hansson@arm.com        code('%nodefault $classname;')
44810458Sandreas.hansson@arm.com        code('class $classname')
44910458Sandreas.hansson@arm.com        if cls._base:
4504762Snate@binkert.org            code('    : public ${{cls._base.cxx_class}}')
4514762Snate@binkert.org        code('{')
4523101Sstever@eecs.umich.edu        code('  public:')
4533101Sstever@eecs.umich.edu        cls.export_methods(code)
4543101Sstever@eecs.umich.edu        code('};')
4553101Sstever@eecs.umich.edu
4563101Sstever@eecs.umich.edu        for ns in reversed(namespaces):
4573101Sstever@eecs.umich.edu            code('} // namespace $ns')
4583101Sstever@eecs.umich.edu
4593101Sstever@eecs.umich.edu        code()
4603101Sstever@eecs.umich.edu        code('%include "params/$cls.hh"')
4613101Sstever@eecs.umich.edu
4623101Sstever@eecs.umich.edu
4633714Sstever@eecs.umich.edu    # Generate the C++ declaration (.hh file) for this SimObject's
4643714Sstever@eecs.umich.edu    # param struct.  Called from src/SConscript.
4653714Sstever@eecs.umich.edu    def cxx_param_decl(cls, code):
4663714Sstever@eecs.umich.edu        # The 'local' attribute restricts us to the params declared in
4673714Sstever@eecs.umich.edu        # the object itself, not including inherited params (which
4683714Sstever@eecs.umich.edu        # will also be inherited from the base class's param struct
4693101Sstever@eecs.umich.edu        # here).
4703101Sstever@eecs.umich.edu        params = cls._params.local.values()
4713101Sstever@eecs.umich.edu        ports = cls._ports.local
4723101Sstever@eecs.umich.edu        try:
4733101Sstever@eecs.umich.edu            ptypes = [p.ptype for p in params]
4743101Sstever@eecs.umich.edu        except:
4753101Sstever@eecs.umich.edu            print cls, p, p.ptype_str
4763101Sstever@eecs.umich.edu            print params
4773101Sstever@eecs.umich.edu            raise
4783101Sstever@eecs.umich.edu
4793101Sstever@eecs.umich.edu        class_path = cls._value_dict['cxx_class'].split('::')
4803101Sstever@eecs.umich.edu
4813101Sstever@eecs.umich.edu        code('''\
4823101Sstever@eecs.umich.edu#ifndef __PARAMS__${cls}__
4833101Sstever@eecs.umich.edu#define __PARAMS__${cls}__
4843101Sstever@eecs.umich.edu
4853101Sstever@eecs.umich.edu''')
4863101Sstever@eecs.umich.edu
4873101Sstever@eecs.umich.edu        # A forward class declaration is sufficient since we are just
4883101Sstever@eecs.umich.edu        # declaring a pointer.
4893101Sstever@eecs.umich.edu        for ns in class_path[:-1]:
4903101Sstever@eecs.umich.edu            code('namespace $ns {')
4913101Sstever@eecs.umich.edu        code('class $0;', class_path[-1])
4923101Sstever@eecs.umich.edu        for ns in reversed(class_path[:-1]):
49310380SAndrew.Bardsley@arm.com            code('} // namespace $ns')
49410380SAndrew.Bardsley@arm.com        code()
49510380SAndrew.Bardsley@arm.com
49610458Sandreas.hansson@arm.com        # The base SimObject has a couple of params that get
49710458Sandreas.hansson@arm.com        # automatically set from Python without being declared through
49810458Sandreas.hansson@arm.com        # the normal Param mechanism; we slip them in here (needed
49910458Sandreas.hansson@arm.com        # predecls now, actual declarations below)
50010458Sandreas.hansson@arm.com        if cls == SimObject:
50110458Sandreas.hansson@arm.com            code('''
50210458Sandreas.hansson@arm.com#ifndef PY_VERSION
50310458Sandreas.hansson@arm.comstruct PyObject;
50410458Sandreas.hansson@arm.com#endif
50510458Sandreas.hansson@arm.com
50610458Sandreas.hansson@arm.com#include <string>
50710458Sandreas.hansson@arm.com
50810458Sandreas.hansson@arm.comclass EventQueue;
5093101Sstever@eecs.umich.edu''')
5105033Smilesck@eecs.umich.edu        for param in params:
5113101Sstever@eecs.umich.edu            param.cxx_predecls(code)
5123101Sstever@eecs.umich.edu        for port in ports.itervalues():
5133101Sstever@eecs.umich.edu            port.cxx_predecls(code)
5143101Sstever@eecs.umich.edu        code()
5153101Sstever@eecs.umich.edu
5163101Sstever@eecs.umich.edu        if cls._base:
5173101Sstever@eecs.umich.edu            code('#include "params/${{cls._base.type}}.hh"')
5183101Sstever@eecs.umich.edu            code()
5193101Sstever@eecs.umich.edu
5203101Sstever@eecs.umich.edu        for ptype in ptypes:
5213101Sstever@eecs.umich.edu            if issubclass(ptype, Enum):
5223101Sstever@eecs.umich.edu                code('#include "enums/${{ptype.__name__}}.hh"')
5235822Ssaidi@eecs.umich.edu                code()
5245822Ssaidi@eecs.umich.edu
5253101Sstever@eecs.umich.edu        # now generate the actual param struct
5263101Sstever@eecs.umich.edu        code("struct ${cls}Params")
5273101Sstever@eecs.umich.edu        if cls._base:
5283101Sstever@eecs.umich.edu            code("    : public ${{cls._base.type}}Params")
5293101Sstever@eecs.umich.edu        code("{")
5303101Sstever@eecs.umich.edu        if not hasattr(cls, 'abstract') or not cls.abstract:
5313101Sstever@eecs.umich.edu            if 'type' in cls.__dict__:
5323101Sstever@eecs.umich.edu                code("    ${{cls.cxx_type}} create();")
5333101Sstever@eecs.umich.edu
5343101Sstever@eecs.umich.edu        code.indent()
5353101Sstever@eecs.umich.edu        if cls == SimObject:
5363101Sstever@eecs.umich.edu            code('''
5373101Sstever@eecs.umich.edu    SimObjectParams()
53810267SGeoffrey.Blake@arm.com    {
5393101Sstever@eecs.umich.edu        extern EventQueue mainEventQueue;
5403101Sstever@eecs.umich.edu        eventq = &mainEventQueue;
5413101Sstever@eecs.umich.edu    }
5423101Sstever@eecs.umich.edu    virtual ~SimObjectParams() {}
5433101Sstever@eecs.umich.edu
5443101Sstever@eecs.umich.edu    std::string name;
5453101Sstever@eecs.umich.edu    PyObject *pyobj;
5463101Sstever@eecs.umich.edu    EventQueue *eventq;
5473102Sstever@eecs.umich.edu            ''')
5483714Sstever@eecs.umich.edu        for param in params:
5493101Sstever@eecs.umich.edu            param.cxx_decl(code)
5503714Sstever@eecs.umich.edu        for port in ports.itervalues():
5513714Sstever@eecs.umich.edu            port.cxx_decl(code)
5523714Sstever@eecs.umich.edu
5533101Sstever@eecs.umich.edu        code.dedent()
5543101Sstever@eecs.umich.edu        code('};')
55510267SGeoffrey.Blake@arm.com
55610267SGeoffrey.Blake@arm.com        code()
55710267SGeoffrey.Blake@arm.com        code('#endif // __PARAMS__${cls}__')
55810267SGeoffrey.Blake@arm.com        return code
5597673Snate@binkert.org
5607673Snate@binkert.org
5617673Snate@binkert.org
5627673Snate@binkert.org# The SimObject class is the root of the special hierarchy.  Most of
5637673Snate@binkert.org# the code in this class deals with the configuration hierarchy itself
5644762Snate@binkert.org# (parent/child node relationships).
5654762Snate@binkert.orgclass SimObject(object):
5664762Snate@binkert.org    # Specify metaclass.  Any class inheriting from SimObject will
5673101Sstever@eecs.umich.edu    # get this metaclass.
5683101Sstever@eecs.umich.edu    __metaclass__ = MetaSimObject
5693101Sstever@eecs.umich.edu    type = 'SimObject'
5703101Sstever@eecs.umich.edu    abstract = True
5713101Sstever@eecs.umich.edu
5723101Sstever@eecs.umich.edu    @classmethod
5733101Sstever@eecs.umich.edu    def export_method_cxx_predecls(cls, code):
5743101Sstever@eecs.umich.edu        code('''
5753101Sstever@eecs.umich.edu#include <Python.h>
5763101Sstever@eecs.umich.edu
5773101Sstever@eecs.umich.edu#include "sim/serialize.hh"
5783101Sstever@eecs.umich.edu#include "sim/sim_object.hh"
5793101Sstever@eecs.umich.edu''')
5803101Sstever@eecs.umich.edu
5813101Sstever@eecs.umich.edu    @classmethod
5823101Sstever@eecs.umich.edu    def export_method_swig_predecls(cls, code):
5833101Sstever@eecs.umich.edu        code('''
5843101Sstever@eecs.umich.edu%include <std_string.i>
5853101Sstever@eecs.umich.edu''')
5869184Sandreas.hansson@arm.com
5879184Sandreas.hansson@arm.com    @classmethod
5889184Sandreas.hansson@arm.com    def export_methods(cls, code):
5899184Sandreas.hansson@arm.com        code('''
5909184Sandreas.hansson@arm.com    enum State {
5919184Sandreas.hansson@arm.com      Running,
59211802Sandreas.sandberg@arm.com      Draining,
5939184Sandreas.hansson@arm.com      Drained
5949184Sandreas.hansson@arm.com    };
59510458Sandreas.hansson@arm.com
59610458Sandreas.hansson@arm.com    void init();
59710458Sandreas.hansson@arm.com    void loadState(Checkpoint *cp);
59810458Sandreas.hansson@arm.com    void initState();
59910458Sandreas.hansson@arm.com    void regStats();
60010458Sandreas.hansson@arm.com    void regFormulas();
60110458Sandreas.hansson@arm.com    void resetStats();
60210458Sandreas.hansson@arm.com    void startup();
60310458Sandreas.hansson@arm.com
60410458Sandreas.hansson@arm.com    unsigned int drain(Event *drain_event);
60510458Sandreas.hansson@arm.com    void resume();
60610458Sandreas.hansson@arm.com    void switchOut();
60710458Sandreas.hansson@arm.com    void takeOverFrom(BaseCPU *cpu);
60810458Sandreas.hansson@arm.com''')
6093101Sstever@eecs.umich.edu
6104446Sbinkertn@umich.edu    # Initialize new instance.  For objects with SimObject-valued
61110668SGeoffrey.Blake@arm.com    # children, we need to recursively clone the classes represented
6123101Sstever@eecs.umich.edu    # by those param values as well in a consistent "deep copy"-style
6135468Snate@binkert.org    # fashion.  That is, we want to make sure that each instance is
61410267SGeoffrey.Blake@arm.com    # cloned only once, and that if there are multiple references to
6155468Snate@binkert.org    # the same original object, we end up with the corresponding
6165468Snate@binkert.org    # cloned references all pointing to the same cloned instance.
6175468Snate@binkert.org    def __init__(self, **kwargs):
6185468Snate@binkert.org        ancestor = kwargs.get('_ancestor')
6195468Snate@binkert.org        memo_dict = kwargs.get('_memo')
62010267SGeoffrey.Blake@arm.com        if memo_dict is None:
62110267SGeoffrey.Blake@arm.com            # prepare to memoize any recursively instantiated objects
62210267SGeoffrey.Blake@arm.com            memo_dict = {}
62310267SGeoffrey.Blake@arm.com        elif ancestor:
6244762Snate@binkert.org            # memoize me now to avoid problems with recursive calls
6254762Snate@binkert.org            memo_dict[ancestor] = self
6264762Snate@binkert.org
62710380SAndrew.Bardsley@arm.com        if not ancestor:
62810380SAndrew.Bardsley@arm.com            ancestor = self.__class__
62910380SAndrew.Bardsley@arm.com        ancestor._instantiated = True
63010458Sandreas.hansson@arm.com
63110458Sandreas.hansson@arm.com        # initialize required attributes
63210458Sandreas.hansson@arm.com        self._parent = None
63310458Sandreas.hansson@arm.com        self._name = None
63410458Sandreas.hansson@arm.com        self._ccObject = None  # pointer to C++ object
63510458Sandreas.hansson@arm.com        self._ccParams = None
63610458Sandreas.hansson@arm.com        self._instantiated = False # really "cloned"
63710458Sandreas.hansson@arm.com
6383101Sstever@eecs.umich.edu        # Clone children specified at class level.  No need for a
6393101Sstever@eecs.umich.edu        # multidict here since we will be cloning everything.
64010267SGeoffrey.Blake@arm.com        # Do children before parameter values so that children that
6413101Sstever@eecs.umich.edu        # are also param values get cloned properly.
6423101Sstever@eecs.umich.edu        self._children = {}
6433101Sstever@eecs.umich.edu        for key,val in ancestor._children.iteritems():
6443101Sstever@eecs.umich.edu            self.add_child(key, val(_memo=memo_dict))
6453101Sstever@eecs.umich.edu
6463101Sstever@eecs.umich.edu        # Inherit parameter values from class using multidict so
6473102Sstever@eecs.umich.edu        # individual value settings can be overridden but we still
6483101Sstever@eecs.umich.edu        # inherit late changes to non-overridden class values.
6493101Sstever@eecs.umich.edu        self._values = multidict(ancestor._values)
6503101Sstever@eecs.umich.edu        # clone SimObject-valued parameters
6514168Sbinkertn@umich.edu        for key,val in ancestor._values.iteritems():
65210267SGeoffrey.Blake@arm.com            val = tryAsSimObjectOrVector(val)
6533101Sstever@eecs.umich.edu            if val is not None:
6543101Sstever@eecs.umich.edu                self._values[key] = val(_memo=memo_dict)
6553101Sstever@eecs.umich.edu
6563101Sstever@eecs.umich.edu        # clone port references.  no need to use a multidict here
6573101Sstever@eecs.umich.edu        # since we will be creating new references for all ports.
6583101Sstever@eecs.umich.edu        self._port_refs = {}
6593102Sstever@eecs.umich.edu        for key,val in ancestor._port_refs.iteritems():
6603101Sstever@eecs.umich.edu            self._port_refs[key] = val.clone(self, memo_dict)
6613101Sstever@eecs.umich.edu        # apply attribute assignments from keyword args, if any
6623101Sstever@eecs.umich.edu        for key,val in kwargs.iteritems():
6633101Sstever@eecs.umich.edu            setattr(self, key, val)
6643101Sstever@eecs.umich.edu
6653101Sstever@eecs.umich.edu    # "Clone" the current instance by creating another instance of
6663101Sstever@eecs.umich.edu    # this instance's class, but that inherits its parameter values
6673101Sstever@eecs.umich.edu    # and port mappings from the current instance.  If we're in a
6683101Sstever@eecs.umich.edu    # "deep copy" recursive clone, check the _memo dict to see if
6693101Sstever@eecs.umich.edu    # we've already cloned this instance.
6703101Sstever@eecs.umich.edu    def __call__(self, **kwargs):
67110317Smitch.hayenga@arm.com        memo_dict = kwargs.get('_memo')
67210317Smitch.hayenga@arm.com        if memo_dict is None:
67310317Smitch.hayenga@arm.com            # no memo_dict: must be top-level clone operation.
67410317Smitch.hayenga@arm.com            # this is only allowed at the root of a hierarchy
67510317Smitch.hayenga@arm.com            if self._parent:
6763102Sstever@eecs.umich.edu                raise RuntimeError, "attempt to clone object %s " \
67710317Smitch.hayenga@arm.com                      "not at the root of a tree (parent = %s)" \
67810317Smitch.hayenga@arm.com                      % (self, self._parent)
67910317Smitch.hayenga@arm.com            # create a new dict and use that.
68010317Smitch.hayenga@arm.com            memo_dict = {}
68110317Smitch.hayenga@arm.com            kwargs['_memo'] = memo_dict
6823101Sstever@eecs.umich.edu        elif memo_dict.has_key(self):
6833584Ssaidi@eecs.umich.edu            # clone already done & memoized
6843584Ssaidi@eecs.umich.edu            return memo_dict[self]
6853584Ssaidi@eecs.umich.edu        return self.__class__(_ancestor = self, **kwargs)
6863584Ssaidi@eecs.umich.edu
6873584Ssaidi@eecs.umich.edu    def _get_port_ref(self, attr):
68810267SGeoffrey.Blake@arm.com        # Return reference that can be assigned to another port
68910267SGeoffrey.Blake@arm.com        # via __setattr__.  There is only ever one reference
69010267SGeoffrey.Blake@arm.com        # object per port, but we create them lazily here.
69110267SGeoffrey.Blake@arm.com        ref = self._port_refs.get(attr)
69210267SGeoffrey.Blake@arm.com        if not ref:
69310267SGeoffrey.Blake@arm.com            ref = self._ports[attr].makeRef(self)
6943101Sstever@eecs.umich.edu            self._port_refs[attr] = ref
6959232Sandreas.hansson@arm.com        return ref
6969235Sandreas.hansson@arm.com
6973101Sstever@eecs.umich.edu    def __getattr__(self, attr):
6983101Sstever@eecs.umich.edu        if self._ports.has_key(attr):
69910676Sandreas.hansson@arm.com            return self._get_port_ref(attr)
7009411Sandreas.hansson@arm.com
70110676Sandreas.hansson@arm.com        if self._values.has_key(attr):
7029411Sandreas.hansson@arm.com            return self._values[attr]
7039411Sandreas.hansson@arm.com
7049411Sandreas.hansson@arm.com        if self._children.has_key(attr):
7053101Sstever@eecs.umich.edu            return self._children[attr]
7069411Sandreas.hansson@arm.com
7079411Sandreas.hansson@arm.com        # If the attribute exists on the C++ object, transparently
7089411Sandreas.hansson@arm.com        # forward the reference there.  This is typically used for
7093101Sstever@eecs.umich.edu        # SWIG-wrapped methods such as init(), regStats(),
7109232Sandreas.hansson@arm.com        # regFormulas(), resetStats(), startup(), drain(), and
7113101Sstever@eecs.umich.edu        # resume().
7129232Sandreas.hansson@arm.com        if self._ccObject and hasattr(self._ccObject, attr):
7133101Sstever@eecs.umich.edu            return getattr(self._ccObject, attr)
7143101Sstever@eecs.umich.edu
7153101Sstever@eecs.umich.edu        raise AttributeError, "object '%s' has no attribute '%s'" \
7169411Sandreas.hansson@arm.com              % (self.__class__.__name__, attr)
7179411Sandreas.hansson@arm.com
7189411Sandreas.hansson@arm.com    # Set attribute (called on foo.attr = value when foo is an
71910676Sandreas.hansson@arm.com    # instance of class cls).
72010676Sandreas.hansson@arm.com    def __setattr__(self, attr, value):
7219411Sandreas.hansson@arm.com        # normal processing for private attributes
7229411Sandreas.hansson@arm.com        if attr.startswith('_'):
7239411Sandreas.hansson@arm.com            object.__setattr__(self, attr, value)
7249411Sandreas.hansson@arm.com            return
7259411Sandreas.hansson@arm.com
7263101Sstever@eecs.umich.edu        if self._ports.has_key(attr):
7279232Sandreas.hansson@arm.com            # set up port connection
7283101Sstever@eecs.umich.edu            self._get_port_ref(attr).connect(value)
7293101Sstever@eecs.umich.edu            return
7303101Sstever@eecs.umich.edu
7313101Sstever@eecs.umich.edu        if isSimObjectOrSequence(value) and self._instantiated:
7329232Sandreas.hansson@arm.com            raise RuntimeError, \
7333101Sstever@eecs.umich.edu                  "cannot set SimObject parameter '%s' after\n" \
7345219Ssaidi@eecs.umich.edu                  "    instance been cloned %s" % (attr, `self`)
7359232Sandreas.hansson@arm.com
7369232Sandreas.hansson@arm.com        param = self._params.get(attr)
7373101Sstever@eecs.umich.edu        if param:
7389232Sandreas.hansson@arm.com            try:
7399232Sandreas.hansson@arm.com                value = param.convert(value)
7403101Sstever@eecs.umich.edu            except Exception, e:
7413101Sstever@eecs.umich.edu                msg = "%s\nError setting param %s.%s to %s\n" % \
7429232Sandreas.hansson@arm.com                      (e, self.__class__.__name__, attr, value)
7439232Sandreas.hansson@arm.com                e.args = (msg, )
7443101Sstever@eecs.umich.edu                raise
7453101Sstever@eecs.umich.edu            self._values[attr] = value
7463101Sstever@eecs.umich.edu            # implicitly parent unparented objects assigned as params
7473101Sstever@eecs.umich.edu            if isSimObjectOrVector(value) and not value.has_parent():
7489232Sandreas.hansson@arm.com                self.add_child(attr, value)
7493101Sstever@eecs.umich.edu            return
7503101Sstever@eecs.umich.edu
75111620SMatthew.Poremba@amd.com        # if RHS is a SimObject, it's an implicit child assignment
75211620SMatthew.Poremba@amd.com        if isSimObjectOrSequence(value):
75311620SMatthew.Poremba@amd.com            self.add_child(attr, value)
7549232Sandreas.hansson@arm.com            return
7559232Sandreas.hansson@arm.com
7569411Sandreas.hansson@arm.com        # no valid assignment... raise exception
7579411Sandreas.hansson@arm.com        raise AttributeError, "Class %s has no parameter %s" \
7583101Sstever@eecs.umich.edu              % (self.__class__.__name__, attr)
7597673Snate@binkert.org
7607673Snate@binkert.org
7619232Sandreas.hansson@arm.com    # this hack allows tacking a '[0]' onto parameters that may or may
7629235Sandreas.hansson@arm.com    # not be vectors, and always getting the first element (e.g. cpus)
7637675Snate@binkert.org    def __getitem__(self, key):
7647675Snate@binkert.org        if key == 0:
76511988Sandreas.sandberg@arm.com            return self
76611988Sandreas.sandberg@arm.com        raise TypeError, "Non-zero index '%s' to SimObject" % key
76711988Sandreas.sandberg@arm.com
76811988Sandreas.sandberg@arm.com    # Also implemented by SimObjectVector
76911988Sandreas.sandberg@arm.com    def clear_parent(self, old_parent):
77010458Sandreas.hansson@arm.com        assert self._parent is old_parent
77110458Sandreas.hansson@arm.com        self._parent = None
77210458Sandreas.hansson@arm.com
77310458Sandreas.hansson@arm.com    # Also implemented by SimObjectVector
77410458Sandreas.hansson@arm.com    def set_parent(self, parent, name):
77511620SMatthew.Poremba@amd.com        self._parent = parent
77611620SMatthew.Poremba@amd.com        self._name = name
77710458Sandreas.hansson@arm.com
77810458Sandreas.hansson@arm.com    # Also implemented by SimObjectVector
77910458Sandreas.hansson@arm.com    def get_name(self):
78010458Sandreas.hansson@arm.com        return self._name
78110458Sandreas.hansson@arm.com
78211620SMatthew.Poremba@amd.com    # Also implemented by SimObjectVector
78311620SMatthew.Poremba@amd.com    def has_parent(self):
78411620SMatthew.Poremba@amd.com        return self._parent is not None
78511620SMatthew.Poremba@amd.com
78611620SMatthew.Poremba@amd.com    # clear out child with given name. This code is not likely to be exercised.
78711620SMatthew.Poremba@amd.com    # See comment in add_child.
78811620SMatthew.Poremba@amd.com    def clear_child(self, name):
78911620SMatthew.Poremba@amd.com        child = self._children[name]
79011620SMatthew.Poremba@amd.com        child.clear_parent(self)
79111620SMatthew.Poremba@amd.com        del self._children[name]
79210458Sandreas.hansson@arm.com
79310458Sandreas.hansson@arm.com    # Add a new child to this object.
79410458Sandreas.hansson@arm.com    def add_child(self, name, child):
79511620SMatthew.Poremba@amd.com        child = coerceSimObjectOrVector(child)
79611620SMatthew.Poremba@amd.com        if child.has_parent():
79710458Sandreas.hansson@arm.com            print "warning: add_child('%s'): child '%s' already has parent" % \
79810458Sandreas.hansson@arm.com                  (name, child.get_name())
7994762Snate@binkert.org        if self._children.has_key(name):
80011991Sandreas.sandberg@arm.com            # This code path had an undiscovered bug that would make it fail
80111802Sandreas.sandberg@arm.com            # at runtime. It had been here for a long time and was only
8024762Snate@binkert.org            # exposed by a buggy script. Changes here will probably not be
8039411Sandreas.hansson@arm.com            # exercised without specialized testing.
80410676Sandreas.hansson@arm.com            self.clear_child(name)
80510676Sandreas.hansson@arm.com        child.set_parent(self, name)
8063101Sstever@eecs.umich.edu        self._children[name] = child
8073101Sstever@eecs.umich.edu
8083101Sstever@eecs.umich.edu    # Take SimObject-valued parameters that haven't been explicitly
8093101Sstever@eecs.umich.edu    # assigned as children and make them children of the object that
8103101Sstever@eecs.umich.edu    # they were assigned to as a parameter value.  This guarantees
8113101Sstever@eecs.umich.edu    # that when we instantiate all the parameter objects we're still
81210267SGeoffrey.Blake@arm.com    # inside the configuration hierarchy.
81310267SGeoffrey.Blake@arm.com    def adoptOrphanParams(self):
8143101Sstever@eecs.umich.edu        for key,val in self._values.iteritems():
8153101Sstever@eecs.umich.edu            if not isSimObjectVector(val) and isSimObjectSequence(val):
8163102Sstever@eecs.umich.edu                # need to convert raw SimObject sequences to
8173101Sstever@eecs.umich.edu                # SimObjectVector class so we can call has_parent()
8183101Sstever@eecs.umich.edu                val = SimObjectVector(val)
8193101Sstever@eecs.umich.edu                self._values[key] = val
82010267SGeoffrey.Blake@arm.com            if isSimObjectOrVector(val) and not val.has_parent():
82110267SGeoffrey.Blake@arm.com                print "warning: %s adopting orphan SimObject param '%s'" \
82210267SGeoffrey.Blake@arm.com                      % (self, key)
82310267SGeoffrey.Blake@arm.com                self.add_child(key, val)
8244762Snate@binkert.org
8254762Snate@binkert.org    def path(self):
8264762Snate@binkert.org        if not self._parent:
8273101Sstever@eecs.umich.edu            return '<orphan %s>' % self.__class__
8283101Sstever@eecs.umich.edu        ppath = self._parent.path()
8293101Sstever@eecs.umich.edu        if ppath == 'root':
8308934SBrad.Beckmann@amd.com            return self._name
8318934SBrad.Beckmann@amd.com        return ppath + "." + self._name
8328934SBrad.Beckmann@amd.com
8338934SBrad.Beckmann@amd.com    def __str__(self):
8348934SBrad.Beckmann@amd.com        return self.path()
8353101Sstever@eecs.umich.edu
8363101Sstever@eecs.umich.edu    def ini_str(self):
8373101Sstever@eecs.umich.edu        return self.path()
8383101Sstever@eecs.umich.edu
8393101Sstever@eecs.umich.edu    def find_any(self, ptype):
84010380SAndrew.Bardsley@arm.com        if isinstance(self, ptype):
84110380SAndrew.Bardsley@arm.com            return self, True
84210380SAndrew.Bardsley@arm.com
84310458Sandreas.hansson@arm.com        found_obj = None
84410458Sandreas.hansson@arm.com        for child in self._children.itervalues():
84510458Sandreas.hansson@arm.com            if isinstance(child, ptype):
84610458Sandreas.hansson@arm.com                if found_obj != None and child != found_obj:
84710458Sandreas.hansson@arm.com                    raise AttributeError, \
84810458Sandreas.hansson@arm.com                          'parent.any matched more than one: %s %s' % \
84910458Sandreas.hansson@arm.com                          (found_obj.path, child.path)
85010458Sandreas.hansson@arm.com                found_obj = child
85110458Sandreas.hansson@arm.com        # search param space
85210458Sandreas.hansson@arm.com        for pname,pdesc in self._params.iteritems():
8533101Sstever@eecs.umich.edu            if issubclass(pdesc.ptype, ptype):
8543101Sstever@eecs.umich.edu                match_obj = self._values[pname]
8553101Sstever@eecs.umich.edu                if found_obj != None and found_obj != match_obj:
8563101Sstever@eecs.umich.edu                    raise AttributeError, \
8573101Sstever@eecs.umich.edu                          'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path)
8583101Sstever@eecs.umich.edu                found_obj = match_obj
8593101Sstever@eecs.umich.edu        return found_obj, found_obj != None
8603101Sstever@eecs.umich.edu
8613101Sstever@eecs.umich.edu    def find_all(self, ptype):
8623101Sstever@eecs.umich.edu        all = {}
8633101Sstever@eecs.umich.edu        # search children
8643101Sstever@eecs.umich.edu        for child in self._children.itervalues():
8654380Sbinkertn@umich.edu            if isinstance(child, ptype) and not isproxy(child) and \
8664380Sbinkertn@umich.edu               not isNullPointer(child):
8674380Sbinkertn@umich.edu                all[child] = True
8683101Sstever@eecs.umich.edu        # search param space
8694380Sbinkertn@umich.edu        for pname,pdesc in self._params.iteritems():
8704380Sbinkertn@umich.edu            if issubclass(pdesc.ptype, ptype):
8714380Sbinkertn@umich.edu                match_obj = self._values[pname]
8723101Sstever@eecs.umich.edu                if not isproxy(match_obj) and not isNullPointer(match_obj):
8733101Sstever@eecs.umich.edu                    all[match_obj] = True
8743101Sstever@eecs.umich.edu        return all.keys(), True
87510267SGeoffrey.Blake@arm.com
87610267SGeoffrey.Blake@arm.com    def unproxy(self, base):
8777673Snate@binkert.org        return self
8787673Snate@binkert.org
8797673Snate@binkert.org    def unproxyParams(self):
8807673Snate@binkert.org        for param in self._params.iterkeys():
8817673Snate@binkert.org            value = self._values.get(param)
8823101Sstever@eecs.umich.edu            if value != None and isproxy(value):
8833101Sstever@eecs.umich.edu                try:
8843101Sstever@eecs.umich.edu                    value = value.unproxy(self)
8853101Sstever@eecs.umich.edu                except:
8863101Sstever@eecs.umich.edu                    print "Error in unproxying param '%s' of %s" % \
8873101Sstever@eecs.umich.edu                          (param, self.path())
8883101Sstever@eecs.umich.edu                    raise
8893101Sstever@eecs.umich.edu                setattr(self, param, value)
8903101Sstever@eecs.umich.edu
8913101Sstever@eecs.umich.edu        # Unproxy ports in sorted order so that 'append' operations on
8923101Sstever@eecs.umich.edu        # vector ports are done in a deterministic fashion.
8933101Sstever@eecs.umich.edu        port_names = self._ports.keys()
8943101Sstever@eecs.umich.edu        port_names.sort()
8959941SGeoffrey.Blake@arm.com        for port_name in port_names:
8963101Sstever@eecs.umich.edu            port = self._port_refs.get(port_name)
8973101Sstever@eecs.umich.edu            if port != None:
8983101Sstever@eecs.umich.edu                port.unproxy(self)
8993101Sstever@eecs.umich.edu
90010267SGeoffrey.Blake@arm.com    def print_ini(self, ini_file):
90110267SGeoffrey.Blake@arm.com        print >>ini_file, '[' + self.path() + ']'       # .ini section header
90210267SGeoffrey.Blake@arm.com
90310267SGeoffrey.Blake@arm.com        instanceDict[self.path()] = self
9043101Sstever@eecs.umich.edu
9053101Sstever@eecs.umich.edu        if hasattr(self, 'type'):
9064380Sbinkertn@umich.edu            print >>ini_file, 'type=%s' % self.type
9073101Sstever@eecs.umich.edu
9083101Sstever@eecs.umich.edu        if len(self._children.keys()):
9094762Snate@binkert.org            print >>ini_file, 'children=%s' % \
91011988Sandreas.sandberg@arm.com                  ' '.join(self._children[n].get_name() \
9114762Snate@binkert.org                  for n in sorted(self._children.keys()))
9124762Snate@binkert.org
91311228SAndrew.Bardsley@arm.com        for param in sorted(self._params.keys()):
91411228SAndrew.Bardsley@arm.com            value = self._values.get(param)
91511228SAndrew.Bardsley@arm.com            if value != None:
9164380Sbinkertn@umich.edu                print >>ini_file, '%s=%s' % (param,
9174380Sbinkertn@umich.edu                                             self._values[param].ini_str())
9183101Sstever@eecs.umich.edu
91910458Sandreas.hansson@arm.com        for port_name in sorted(self._ports.keys()):
92010458Sandreas.hansson@arm.com            port = self._port_refs.get(port_name, None)
92110458Sandreas.hansson@arm.com            if port != None:
92210458Sandreas.hansson@arm.com                print >>ini_file, '%s=%s' % (port_name, port.ini_str())
92310458Sandreas.hansson@arm.com
9247777Sgblack@eecs.umich.edu        print >>ini_file        # blank line between objects
9257777Sgblack@eecs.umich.edu
9267777Sgblack@eecs.umich.edu    # generate a tree of dictionaries expressing all the parameters in the
9277777Sgblack@eecs.umich.edu    # instantiated system for use by scripts that want to do power, thermal
92810267SGeoffrey.Blake@arm.com    # visualization, and other similar tasks
92910267SGeoffrey.Blake@arm.com    def get_config_as_dict(self):
9307777Sgblack@eecs.umich.edu        d = attrdict()
9317777Sgblack@eecs.umich.edu        if hasattr(self, 'type'):
9327777Sgblack@eecs.umich.edu            d.type = self.type
9337777Sgblack@eecs.umich.edu        if hasattr(self, 'cxx_class'):
9347777Sgblack@eecs.umich.edu            d.cxx_class = self.cxx_class
9357777Sgblack@eecs.umich.edu
9367777Sgblack@eecs.umich.edu        for param in sorted(self._params.keys()):
9377777Sgblack@eecs.umich.edu            value = self._values.get(param)
9387777Sgblack@eecs.umich.edu            if value != None:
9397777Sgblack@eecs.umich.edu                try:
9407777Sgblack@eecs.umich.edu                    # Use native type for those supported by JSON and
9417777Sgblack@eecs.umich.edu                    # strings for everything else. skipkeys=True seems
9427777Sgblack@eecs.umich.edu                    # to not work as well as one would hope
9437777Sgblack@eecs.umich.edu                    if type(self._values[param].value) in \
9447777Sgblack@eecs.umich.edu                            [str, unicode, int, long, float, bool, None]:
94510267SGeoffrey.Blake@arm.com                        d[param] = self._values[param].value
94610267SGeoffrey.Blake@arm.com                    else:
94710267SGeoffrey.Blake@arm.com                        d[param] = str(self._values[param])
94810267SGeoffrey.Blake@arm.com
9498579Ssteve.reinhardt@amd.com                except AttributeError:
9508579Ssteve.reinhardt@amd.com                    pass
9518579Ssteve.reinhardt@amd.com
9528579Ssteve.reinhardt@amd.com        for n in sorted(self._children.keys()):
9538579Ssteve.reinhardt@amd.com            d[self._children[n].get_name()] =  self._children[n].get_config_as_dict()
9548579Ssteve.reinhardt@amd.com
9558579Ssteve.reinhardt@amd.com        for port_name in sorted(self._ports.keys()):
9568579Ssteve.reinhardt@amd.com            port = self._port_refs.get(port_name, None)
9578579Ssteve.reinhardt@amd.com            if port != None:
9588579Ssteve.reinhardt@amd.com                # Might want to actually make this reference the object
9598579Ssteve.reinhardt@amd.com                # in the future, although execing the string problem would
9608579Ssteve.reinhardt@amd.com                # get some of the way there
9618579Ssteve.reinhardt@amd.com                d[port_name] = port.ini_str()
9628579Ssteve.reinhardt@amd.com
9638579Ssteve.reinhardt@amd.com        return d
9648579Ssteve.reinhardt@amd.com
9658579Ssteve.reinhardt@amd.com    def getCCParams(self):
9668579Ssteve.reinhardt@amd.com        if self._ccParams:
9677777Sgblack@eecs.umich.edu            return self._ccParams
9687777Sgblack@eecs.umich.edu
9697798Sgblack@eecs.umich.edu        cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type)
9707777Sgblack@eecs.umich.edu        cc_params = cc_params_struct()
9717777Sgblack@eecs.umich.edu        cc_params.pyobj = self
97211988Sandreas.sandberg@arm.com        cc_params.name = str(self)
9737777Sgblack@eecs.umich.edu
9747777Sgblack@eecs.umich.edu        param_names = self._params.keys()
9757777Sgblack@eecs.umich.edu        param_names.sort()
9767777Sgblack@eecs.umich.edu        for param in param_names:
9777777Sgblack@eecs.umich.edu            value = self._values.get(param)
9787777Sgblack@eecs.umich.edu            if value is None:
9797777Sgblack@eecs.umich.edu                fatal("%s.%s without default or user set value",
98010267SGeoffrey.Blake@arm.com                      self.path(), param)
98110267SGeoffrey.Blake@arm.com
9827777Sgblack@eecs.umich.edu            value = value.getValue()
9837777Sgblack@eecs.umich.edu            if isinstance(self._params[param], VectorParamDesc):
9847777Sgblack@eecs.umich.edu                assert isinstance(value, list)
9857777Sgblack@eecs.umich.edu                vec = getattr(cc_params, param)
9867777Sgblack@eecs.umich.edu                assert not len(vec)
9877777Sgblack@eecs.umich.edu                for v in value:
9887777Sgblack@eecs.umich.edu                    vec.append(v)
9897777Sgblack@eecs.umich.edu            else:
9907777Sgblack@eecs.umich.edu                setattr(cc_params, param, value)
9917777Sgblack@eecs.umich.edu
9927777Sgblack@eecs.umich.edu        port_names = self._ports.keys()
9937777Sgblack@eecs.umich.edu        port_names.sort()
9947777Sgblack@eecs.umich.edu        for port_name in port_names:
9957777Sgblack@eecs.umich.edu            port = self._port_refs.get(port_name, None)
9967777Sgblack@eecs.umich.edu            if port != None:
9977777Sgblack@eecs.umich.edu                port_count = len(port)
9987777Sgblack@eecs.umich.edu            else:
9997777Sgblack@eecs.umich.edu                port_count = 0
10007777Sgblack@eecs.umich.edu            setattr(cc_params, 'port_' + port_name + '_connection_count',
10017777Sgblack@eecs.umich.edu                    port_count)
10027777Sgblack@eecs.umich.edu        self._ccParams = cc_params
10037777Sgblack@eecs.umich.edu        return self._ccParams
10047777Sgblack@eecs.umich.edu
10057777Sgblack@eecs.umich.edu    # Get C++ object corresponding to this object, calling C++ if
10067777Sgblack@eecs.umich.edu    # necessary to construct it.  Does *not* recursively create
10077777Sgblack@eecs.umich.edu    # children.
10087777Sgblack@eecs.umich.edu    def getCCObject(self):
10097777Sgblack@eecs.umich.edu        if not self._ccObject:
10107777Sgblack@eecs.umich.edu            # Make sure this object is in the configuration hierarchy
10117777Sgblack@eecs.umich.edu            if not self._parent and not isRoot(self):
10127777Sgblack@eecs.umich.edu                raise RuntimeError, "Attempt to instantiate orphan node"
10137777Sgblack@eecs.umich.edu            # Cycles in the configuration hierarchy are not supported. This
10147777Sgblack@eecs.umich.edu            # will catch the resulting recursion and stop.
10157777Sgblack@eecs.umich.edu            self._ccObject = -1
10167777Sgblack@eecs.umich.edu            params = self.getCCParams()
10177777Sgblack@eecs.umich.edu            self._ccObject = params.create()
10187777Sgblack@eecs.umich.edu        elif self._ccObject == -1:
10197777Sgblack@eecs.umich.edu            raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
10207777Sgblack@eecs.umich.edu                  % self.path()
10217777Sgblack@eecs.umich.edu        return self._ccObject
10227777Sgblack@eecs.umich.edu
102310267SGeoffrey.Blake@arm.com    def descendants(self):
102410267SGeoffrey.Blake@arm.com        yield self
102510267SGeoffrey.Blake@arm.com        for child in self._children.itervalues():
102610267SGeoffrey.Blake@arm.com            for obj in child.descendants():
10278579Ssteve.reinhardt@amd.com                yield obj
10288579Ssteve.reinhardt@amd.com
10298579Ssteve.reinhardt@amd.com    # Call C++ to create C++ object corresponding to this object
10308579Ssteve.reinhardt@amd.com    def createCCObject(self):
10318579Ssteve.reinhardt@amd.com        self.getCCParams()
10328579Ssteve.reinhardt@amd.com        self.getCCObject() # force creation
10338579Ssteve.reinhardt@amd.com
10348579Ssteve.reinhardt@amd.com    def getValue(self):
10358579Ssteve.reinhardt@amd.com        return self.getCCObject()
10368579Ssteve.reinhardt@amd.com
10378579Ssteve.reinhardt@amd.com    # Create C++ port connections corresponding to the connections in
10388579Ssteve.reinhardt@amd.com    # _port_refs
10398579Ssteve.reinhardt@amd.com    def connectPorts(self):
10408579Ssteve.reinhardt@amd.com        for portRef in self._port_refs.itervalues():
10417777Sgblack@eecs.umich.edu            portRef.ccConnect()
10427777Sgblack@eecs.umich.edu
10437777Sgblack@eecs.umich.edu    def getMemoryMode(self):
10447777Sgblack@eecs.umich.edu        if not isinstance(self, m5.objects.System):
10457777Sgblack@eecs.umich.edu            return None
10467777Sgblack@eecs.umich.edu
104711988Sandreas.sandberg@arm.com        return self._ccObject.getMemoryMode()
10487777Sgblack@eecs.umich.edu
10497777Sgblack@eecs.umich.edu    def changeTiming(self, mode):
10507777Sgblack@eecs.umich.edu        if isinstance(self, m5.objects.System):
10517777Sgblack@eecs.umich.edu            # i don't know if there's a better way to do this - calling
10527777Sgblack@eecs.umich.edu            # setMemoryMode directly from self._ccObject results in calling
10537777Sgblack@eecs.umich.edu            # SimObject::setMemoryMode, not the System::setMemoryMode
105410267SGeoffrey.Blake@arm.com            self._ccObject.setMemoryMode(mode)
105510267SGeoffrey.Blake@arm.com
10567777Sgblack@eecs.umich.edu    def takeOverFrom(self, old_cpu):
10577777Sgblack@eecs.umich.edu        self._ccObject.takeOverFrom(old_cpu._ccObject)
10587777Sgblack@eecs.umich.edu
10597777Sgblack@eecs.umich.edu    # generate output file for 'dot' to display as a pretty graph.
10607777Sgblack@eecs.umich.edu    # this code is currently broken.
10617777Sgblack@eecs.umich.edu    def outputDot(self, dot):
10627777Sgblack@eecs.umich.edu        label = "{%s|" % self.path
10637777Sgblack@eecs.umich.edu        if isSimObject(self.realtype):
10647777Sgblack@eecs.umich.edu            label +=  '%s|' % self.type
10657777Sgblack@eecs.umich.edu
10667777Sgblack@eecs.umich.edu        if self.children:
10677777Sgblack@eecs.umich.edu            # instantiate children in same order they were added for
10687777Sgblack@eecs.umich.edu            # backward compatibility (else we can end up with cpu1
10697777Sgblack@eecs.umich.edu            # before cpu0).
10707777Sgblack@eecs.umich.edu            for c in self.children:
10717777Sgblack@eecs.umich.edu                dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
10727777Sgblack@eecs.umich.edu
10737777Sgblack@eecs.umich.edu        simobjs = []
10747777Sgblack@eecs.umich.edu        for param in self.params:
10757777Sgblack@eecs.umich.edu            try:
10767777Sgblack@eecs.umich.edu                if param.value is None:
10777777Sgblack@eecs.umich.edu                    raise AttributeError, 'Parameter with no value'
10787777Sgblack@eecs.umich.edu
10797777Sgblack@eecs.umich.edu                value = param.value
10807777Sgblack@eecs.umich.edu                string = param.string(value)
10817777Sgblack@eecs.umich.edu            except Exception, e:
10827777Sgblack@eecs.umich.edu                msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
10837777Sgblack@eecs.umich.edu                e.args = (msg, )
10847777Sgblack@eecs.umich.edu                raise
10857777Sgblack@eecs.umich.edu
10867777Sgblack@eecs.umich.edu            if isSimObject(param.ptype) and string != "Null":
10877777Sgblack@eecs.umich.edu                simobjs.append(string)
10887777Sgblack@eecs.umich.edu            else:
10897777Sgblack@eecs.umich.edu                label += '%s = %s\\n' % (param.name, string)
10907777Sgblack@eecs.umich.edu
10917777Sgblack@eecs.umich.edu        for so in simobjs:
10927777Sgblack@eecs.umich.edu            label += "|<%s> %s" % (so, so)
10937777Sgblack@eecs.umich.edu            dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
10947777Sgblack@eecs.umich.edu                                    tailport="w"))
10957777Sgblack@eecs.umich.edu        label += '}'
10967777Sgblack@eecs.umich.edu        dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
109710267SGeoffrey.Blake@arm.com
109810267SGeoffrey.Blake@arm.com        # recursively dump out children
109910267SGeoffrey.Blake@arm.com        for c in self.children:
110010267SGeoffrey.Blake@arm.com            c.outputDot(dot)
11018579Ssteve.reinhardt@amd.com
11028579Ssteve.reinhardt@amd.com# Function to provide to C++ so it can look up instances based on paths
11038579Ssteve.reinhardt@amd.comdef resolveSimObject(name):
11048579Ssteve.reinhardt@amd.com    obj = instanceDict[name]
11058579Ssteve.reinhardt@amd.com    return obj.getCCObject()
11068579Ssteve.reinhardt@amd.com
11078579Ssteve.reinhardt@amd.comdef isSimObject(value):
11088579Ssteve.reinhardt@amd.com    return isinstance(value, SimObject)
11098579Ssteve.reinhardt@amd.com
11108579Ssteve.reinhardt@amd.comdef isSimObjectClass(value):
11118579Ssteve.reinhardt@amd.com    return issubclass(value, SimObject)
11128579Ssteve.reinhardt@amd.com
11138579Ssteve.reinhardt@amd.comdef isSimObjectVector(value):
11148579Ssteve.reinhardt@amd.com    return isinstance(value, SimObjectVector)
11157777Sgblack@eecs.umich.edu
11167777Sgblack@eecs.umich.edudef isSimObjectSequence(value):
11177777Sgblack@eecs.umich.edu    if not isinstance(value, (list, tuple)) or len(value) == 0:
11187777Sgblack@eecs.umich.edu        return False
11197777Sgblack@eecs.umich.edu
11207777Sgblack@eecs.umich.edu    for val in value:
112111988Sandreas.sandberg@arm.com        if not isNullPointer(val) and not isSimObject(val):
11227777Sgblack@eecs.umich.edu            return False
11237777Sgblack@eecs.umich.edu
11243932Sbinkertn@umich.edu    return True
112510380SAndrew.Bardsley@arm.com
11263932Sbinkertn@umich.edudef isSimObjectOrSequence(value):
11273932Sbinkertn@umich.edu    return isSimObject(value) or isSimObjectSequence(value)
11283932Sbinkertn@umich.edu
11293932Sbinkertn@umich.edudef isRoot(obj):
11303932Sbinkertn@umich.edu    from m5.objects import Root
11313932Sbinkertn@umich.edu    return obj and obj is Root.getInstance()
11323932Sbinkertn@umich.edu
11333932Sbinkertn@umich.edudef isSimObjectOrVector(value):
11343932Sbinkertn@umich.edu    return isSimObject(value) or isSimObjectVector(value)
11353932Sbinkertn@umich.edu
11363932Sbinkertn@umich.edudef tryAsSimObjectOrVector(value):
11373885Sbinkertn@umich.edu    if isSimObjectOrVector(value):
11383932Sbinkertn@umich.edu        return value
11393932Sbinkertn@umich.edu    if isSimObjectSequence(value):
11403885Sbinkertn@umich.edu        return SimObjectVector(value)
11413932Sbinkertn@umich.edu    return None
11423932Sbinkertn@umich.edu
11433932Sbinkertn@umich.edudef coerceSimObjectOrVector(value):
11443932Sbinkertn@umich.edu    value = tryAsSimObjectOrVector(value)
11453932Sbinkertn@umich.edu    if value is None:
11463932Sbinkertn@umich.edu        raise TypeError, "SimObject or SimObjectVector expected"
11473932Sbinkertn@umich.edu    return value
11483932Sbinkertn@umich.edu
11493932Sbinkertn@umich.edubaseClasses = allClasses.copy()
11503932Sbinkertn@umich.edubaseInstances = instanceDict.copy()
11513932Sbinkertn@umich.edu
11523932Sbinkertn@umich.edudef clear():
11533932Sbinkertn@umich.edu    global allClasses, instanceDict
11543932Sbinkertn@umich.edu
11553932Sbinkertn@umich.edu    allClasses = baseClasses.copy()
11563932Sbinkertn@umich.edu    instanceDict = baseInstances.copy()
11573932Sbinkertn@umich.edu
11583932Sbinkertn@umich.edu# __all__ defines the list of symbols that get exported when
11593885Sbinkertn@umich.edu# 'from config import *' is invoked.  Try to keep this reasonably
11603885Sbinkertn@umich.edu# short to avoid polluting other namespaces.
11613885Sbinkertn@umich.edu__all__ = [ 'SimObject' ]
11623885Sbinkertn@umich.edu