params.py revision 3584
111988Sandreas.sandberg@arm.com# Copyright (c) 2004-2006 The Regents of The University of Michigan
28839Sandreas.hansson@arm.com# All rights reserved.
38839Sandreas.hansson@arm.com#
48839Sandreas.hansson@arm.com# Redistribution and use in source and binary forms, with or without
58839Sandreas.hansson@arm.com# modification, are permitted provided that the following conditions are
68839Sandreas.hansson@arm.com# met: redistributions of source code must retain the above copyright
78839Sandreas.hansson@arm.com# notice, this list of conditions and the following disclaimer;
88839Sandreas.hansson@arm.com# redistributions in binary form must reproduce the above copyright
98839Sandreas.hansson@arm.com# notice, this list of conditions and the following disclaimer in the
108839Sandreas.hansson@arm.com# documentation and/or other materials provided with the distribution;
118839Sandreas.hansson@arm.com# neither the name of the copyright holders nor the names of its
128839Sandreas.hansson@arm.com# contributors may be used to endorse or promote products derived from
133101Sstever@eecs.umich.edu# this software without specific prior written permission.
148579Ssteve.reinhardt@amd.com#
153101Sstever@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
163101Sstever@eecs.umich.edu# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
173101Sstever@eecs.umich.edu# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
183101Sstever@eecs.umich.edu# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
193101Sstever@eecs.umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
203101Sstever@eecs.umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
213101Sstever@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
223101Sstever@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
233101Sstever@eecs.umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
243101Sstever@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
253101Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
263101Sstever@eecs.umich.edu#
273101Sstever@eecs.umich.edu# Authors: Steve Reinhardt
283101Sstever@eecs.umich.edu#          Nathan Binkert
293101Sstever@eecs.umich.edu
303101Sstever@eecs.umich.edu#####################################################################
313101Sstever@eecs.umich.edu#
323101Sstever@eecs.umich.edu# Parameter description classes
333101Sstever@eecs.umich.edu#
343101Sstever@eecs.umich.edu# The _params dictionary in each class maps parameter names to either
353101Sstever@eecs.umich.edu# a Param or a VectorParam object.  These objects contain the
363101Sstever@eecs.umich.edu# parameter description string, the parameter type, and the default
373101Sstever@eecs.umich.edu# value (if any).  The convert() method on these objects is used to
383101Sstever@eecs.umich.edu# force whatever value is assigned to the parameter to the appropriate
393101Sstever@eecs.umich.edu# type.
403101Sstever@eecs.umich.edu#
413101Sstever@eecs.umich.edu# Note that the default values are loaded into the class's attribute
427778Sgblack@eecs.umich.edu# space when the parameter dictionary is initialized (in
438839Sandreas.hansson@arm.com# MetaSimObject._new_param()); after that point they aren't used.
443101Sstever@eecs.umich.edu#
453101Sstever@eecs.umich.edu#####################################################################
463101Sstever@eecs.umich.edu
473101Sstever@eecs.umich.eduimport sys, inspect, copy
483101Sstever@eecs.umich.eduimport convert
493101Sstever@eecs.umich.edufrom util import *
503101Sstever@eecs.umich.edu
513101Sstever@eecs.umich.edu# Dummy base class to identify types that are legitimate for SimObject
523101Sstever@eecs.umich.edu# parameters.
533101Sstever@eecs.umich.educlass ParamValue(object):
543101Sstever@eecs.umich.edu
553101Sstever@eecs.umich.edu    cxx_predecls = []
563101Sstever@eecs.umich.edu    swig_predecls = []
573101Sstever@eecs.umich.edu
583101Sstever@eecs.umich.edu    # default for printing to .ini file is regular string conversion.
593101Sstever@eecs.umich.edu    # will be overridden in some cases
603101Sstever@eecs.umich.edu    def ini_str(self):
613101Sstever@eecs.umich.edu        return str(self)
6212563Sgabeblack@google.com
6312563Sgabeblack@google.com    # allows us to blithely call unproxy() on things without checking
643885Sbinkertn@umich.edu    # if they're really proxies or not
653885Sbinkertn@umich.edu    def unproxy(self, base):
664762Snate@binkert.org        return self
673885Sbinkertn@umich.edu
683885Sbinkertn@umich.edu# Regular parameter description.
697528Ssteve.reinhardt@amd.comclass ParamDesc(object):
703885Sbinkertn@umich.edu    def __init__(self, ptype_str, ptype, *args, **kwargs):
714380Sbinkertn@umich.edu        self.ptype_str = ptype_str
724167Sbinkertn@umich.edu        # remember ptype only if it is provided
733102Sstever@eecs.umich.edu        if ptype != None:
743101Sstever@eecs.umich.edu            self.ptype = ptype
754762Snate@binkert.org
764762Snate@binkert.org        if args:
774762Snate@binkert.org            if len(args) == 1:
784762Snate@binkert.org                self.desc = args[0]
794762Snate@binkert.org            elif len(args) == 2:
804762Snate@binkert.org                self.default = args[0]
814762Snate@binkert.org                self.desc = args[1]
824762Snate@binkert.org            else:
834762Snate@binkert.org                raise TypeError, 'too many arguments'
845033Smilesck@eecs.umich.edu
855033Smilesck@eecs.umich.edu        if kwargs.has_key('desc'):
865033Smilesck@eecs.umich.edu            assert(not hasattr(self, 'desc'))
875033Smilesck@eecs.umich.edu            self.desc = kwargs['desc']
885033Smilesck@eecs.umich.edu            del kwargs['desc']
895033Smilesck@eecs.umich.edu
905033Smilesck@eecs.umich.edu        if kwargs.has_key('default'):
915033Smilesck@eecs.umich.edu            assert(not hasattr(self, 'default'))
925033Smilesck@eecs.umich.edu            self.default = kwargs['default']
935033Smilesck@eecs.umich.edu            del kwargs['default']
943101Sstever@eecs.umich.edu
953101Sstever@eecs.umich.edu        if kwargs:
963101Sstever@eecs.umich.edu            raise TypeError, 'extra unknown kwargs %s' % kwargs
975033Smilesck@eecs.umich.edu
9810267SGeoffrey.Blake@arm.com        if not hasattr(self, 'desc'):
998596Ssteve.reinhardt@amd.com            raise TypeError, 'desc attribute missing'
1008596Ssteve.reinhardt@amd.com
1018596Ssteve.reinhardt@amd.com    def __getattr__(self, attr):
1028596Ssteve.reinhardt@amd.com        if attr == 'ptype':
1037673Snate@binkert.org            try:
1047673Snate@binkert.org                ptype = eval(self.ptype_str, objects.__dict__)
1057673Snate@binkert.org                if not isinstance(ptype, type):
1067673Snate@binkert.org                    raise NameError
10711988Sandreas.sandberg@arm.com                self.ptype = ptype
10811988Sandreas.sandberg@arm.com                return ptype
10911988Sandreas.sandberg@arm.com            except NameError:
11011988Sandreas.sandberg@arm.com                raise TypeError, \
1113101Sstever@eecs.umich.edu                      "Param qualifier '%s' is not a type" % self.ptype_str
1123101Sstever@eecs.umich.edu        raise AttributeError, "'%s' object has no attribute '%s'" % \
1133101Sstever@eecs.umich.edu              (type(self).__name__, attr)
1143101Sstever@eecs.umich.edu
1153101Sstever@eecs.umich.edu    def convert(self, value):
11610380SAndrew.Bardsley@arm.com        if isinstance(value, proxy.BaseProxy):
11710380SAndrew.Bardsley@arm.com            value.set_param_desc(self)
11810380SAndrew.Bardsley@arm.com            return value
11910380SAndrew.Bardsley@arm.com        if not hasattr(self, 'ptype') and isNullPointer(value):
12010380SAndrew.Bardsley@arm.com            # deferred evaluation of SimObject; continue to defer if
12110380SAndrew.Bardsley@arm.com            # we're just assigning a null pointer
12210458Sandreas.hansson@arm.com            return value
12310458Sandreas.hansson@arm.com        if isinstance(value, self.ptype):
12410458Sandreas.hansson@arm.com            return value
12510458Sandreas.hansson@arm.com        if isNullPointer(value) and isSimObjectClass(self.ptype):
12610458Sandreas.hansson@arm.com            return value
12710458Sandreas.hansson@arm.com        return self.ptype(value)
12810458Sandreas.hansson@arm.com
12910458Sandreas.hansson@arm.com    def cxx_predecls(self):
13010458Sandreas.hansson@arm.com        return self.ptype.cxx_predecls
13110458Sandreas.hansson@arm.com
13210458Sandreas.hansson@arm.com    def swig_predecls(self):
13310458Sandreas.hansson@arm.com        return self.ptype.swig_predecls
1343101Sstever@eecs.umich.edu
1353101Sstever@eecs.umich.edu    def cxx_decl(self):
1363101Sstever@eecs.umich.edu        return '%s %s;' % (self.ptype.cxx_type, self.name)
1373101Sstever@eecs.umich.edu
1383101Sstever@eecs.umich.edu# Vector-valued parameter description.  Just like ParamDesc, except
13910267SGeoffrey.Blake@arm.com# that the value is a vector (list) of the specified type instead of a
14010267SGeoffrey.Blake@arm.com# single value.
14110267SGeoffrey.Blake@arm.com
14210267SGeoffrey.Blake@arm.comclass VectorParamValue(list):
1433101Sstever@eecs.umich.edu    def ini_str(self):
1443101Sstever@eecs.umich.edu        return ' '.join([v.ini_str() for v in self])
1453101Sstever@eecs.umich.edu
1463101Sstever@eecs.umich.edu    def unproxy(self, base):
1473101Sstever@eecs.umich.edu        return [v.unproxy(base) for v in self]
1483101Sstever@eecs.umich.edu
1493101Sstever@eecs.umich.educlass SimObjVector(VectorParamValue):
1503101Sstever@eecs.umich.edu    def print_ini(self):
1513101Sstever@eecs.umich.edu        for v in self:
1523101Sstever@eecs.umich.edu            v.print_ini()
1533101Sstever@eecs.umich.edu
1543101Sstever@eecs.umich.educlass VectorParamDesc(ParamDesc):
1553101Sstever@eecs.umich.edu    # Convert assigned value to appropriate type.  If the RHS is not a
1563101Sstever@eecs.umich.edu    # list or tuple, it generates a single-element list.
1573101Sstever@eecs.umich.edu    def convert(self, value):
1583101Sstever@eecs.umich.edu        if isinstance(value, (list, tuple)):
1593101Sstever@eecs.umich.edu            # list: coerce each element into new list
1603101Sstever@eecs.umich.edu            tmp_list = [ ParamDesc.convert(self, v) for v in value ]
1613101Sstever@eecs.umich.edu            if isSimObjectSequence(tmp_list):
1623101Sstever@eecs.umich.edu                return SimObjVector(tmp_list)
1633101Sstever@eecs.umich.edu            else:
1643101Sstever@eecs.umich.edu                return VectorParamValue(tmp_list)
1653101Sstever@eecs.umich.edu        else:
1663101Sstever@eecs.umich.edu            # singleton: leave it be (could coerce to a single-element
1673101Sstever@eecs.umich.edu            # list here, but for some historical reason we don't...
1683101Sstever@eecs.umich.edu            return ParamDesc.convert(self, value)
1693101Sstever@eecs.umich.edu
1703101Sstever@eecs.umich.edu    def cxx_predecls(self):
1713101Sstever@eecs.umich.edu        return ['#include <vector>'] + self.ptype.cxx_predecls
1723101Sstever@eecs.umich.edu
1733101Sstever@eecs.umich.edu    def swig_predecls(self):
1743101Sstever@eecs.umich.edu        return ['%include "std_vector.i"'] + self.ptype.swig_predecls
1753101Sstever@eecs.umich.edu
1763101Sstever@eecs.umich.edu    def cxx_decl(self):
1773101Sstever@eecs.umich.edu        return 'std::vector< %s > %s;' % (self.ptype.cxx_type, self.name)
1785033Smilesck@eecs.umich.edu
1796656Snate@binkert.orgclass ParamFactory(object):
1805033Smilesck@eecs.umich.edu    def __init__(self, param_desc_class, ptype_str = None):
1815033Smilesck@eecs.umich.edu        self.param_desc_class = param_desc_class
1825033Smilesck@eecs.umich.edu        self.ptype_str = ptype_str
1833101Sstever@eecs.umich.edu
1843101Sstever@eecs.umich.edu    def __getattr__(self, attr):
1853101Sstever@eecs.umich.edu        if self.ptype_str:
18610267SGeoffrey.Blake@arm.com            attr = self.ptype_str + '.' + attr
18710267SGeoffrey.Blake@arm.com        return ParamFactory(self.param_desc_class, attr)
18810267SGeoffrey.Blake@arm.com
18910267SGeoffrey.Blake@arm.com    # E.g., Param.Int(5, "number of widgets")
19010267SGeoffrey.Blake@arm.com    def __call__(self, *args, **kwargs):
19110267SGeoffrey.Blake@arm.com        caller_frame = inspect.currentframe().f_back
19210267SGeoffrey.Blake@arm.com        ptype = None
19310267SGeoffrey.Blake@arm.com        try:
19410267SGeoffrey.Blake@arm.com            ptype = eval(self.ptype_str,
19510267SGeoffrey.Blake@arm.com                         caller_frame.f_globals, caller_frame.f_locals)
19610267SGeoffrey.Blake@arm.com            if not isinstance(ptype, type):
19710267SGeoffrey.Blake@arm.com                raise TypeError, \
19810267SGeoffrey.Blake@arm.com                      "Param qualifier is not a type: %s" % ptype
1993101Sstever@eecs.umich.edu        except NameError:
2003101Sstever@eecs.umich.edu            # if name isn't defined yet, assume it's a SimObject, and
2013101Sstever@eecs.umich.edu            # try to resolve it later
2023101Sstever@eecs.umich.edu            pass
2033101Sstever@eecs.umich.edu        return self.param_desc_class(self.ptype_str, ptype, *args, **kwargs)
2043101Sstever@eecs.umich.edu
2053101Sstever@eecs.umich.eduParam = ParamFactory(ParamDesc)
2063101Sstever@eecs.umich.eduVectorParam = ParamFactory(VectorParamDesc)
2073101Sstever@eecs.umich.edu
2083101Sstever@eecs.umich.edu#####################################################################
2093102Sstever@eecs.umich.edu#
2103101Sstever@eecs.umich.edu# Parameter Types
2113101Sstever@eecs.umich.edu#
2123101Sstever@eecs.umich.edu# Though native Python types could be used to specify parameter types
21310267SGeoffrey.Blake@arm.com# (the 'ptype' field of the Param and VectorParam classes), it's more
21410267SGeoffrey.Blake@arm.com# flexible to define our own set of types.  This gives us more control
21510267SGeoffrey.Blake@arm.com# over how Python expressions are converted to values (via the
21610267SGeoffrey.Blake@arm.com# __init__() constructor) and how these values are printed out (via
21710267SGeoffrey.Blake@arm.com# the __str__() conversion method).
21810267SGeoffrey.Blake@arm.com#
21910267SGeoffrey.Blake@arm.com#####################################################################
2207673Snate@binkert.org
2218607Sgblack@eecs.umich.edu# String-valued parameter.  Just mixin the ParamValue class with the
2227673Snate@binkert.org# built-in str class.
2233101Sstever@eecs.umich.educlass String(ParamValue,str):
22411988Sandreas.sandberg@arm.com    cxx_type = 'std::string'
22511988Sandreas.sandberg@arm.com    cxx_predecls = ['#include <string>']
22611988Sandreas.sandberg@arm.com    swig_predecls = ['%include "std_string.i"\n' +
2277673Snate@binkert.org                     '%apply const std::string& {std::string *};']
2287673Snate@binkert.org    pass
2293101Sstever@eecs.umich.edu
2303101Sstever@eecs.umich.edu# superclass for "numeric" parameter values, to emulate math
2313101Sstever@eecs.umich.edu# operations in a type-safe way.  e.g., a Latency times an int returns
2323101Sstever@eecs.umich.edu# a new Latency object.
2333101Sstever@eecs.umich.educlass NumericParamValue(ParamValue):
2343101Sstever@eecs.umich.edu    def __str__(self):
2355033Smilesck@eecs.umich.edu        return str(self.value)
2365475Snate@binkert.org
2375475Snate@binkert.org    def __float__(self):
2385475Snate@binkert.org        return float(self.value)
2395475Snate@binkert.org
24010380SAndrew.Bardsley@arm.com    # hook for bounds checking
24110380SAndrew.Bardsley@arm.com    def _check(self):
24210380SAndrew.Bardsley@arm.com        return
2433101Sstever@eecs.umich.edu
2443101Sstever@eecs.umich.edu    def __mul__(self, other):
2453101Sstever@eecs.umich.edu        newobj = self.__class__(self)
2464762Snate@binkert.org        newobj.value *= other
2474762Snate@binkert.org        newobj._check()
2484762Snate@binkert.org        return newobj
2493101Sstever@eecs.umich.edu
25012050Snikos.nikoleris@arm.com    __rmul__ = __mul__
25112050Snikos.nikoleris@arm.com
25212050Snikos.nikoleris@arm.com    def __div__(self, other):
2538459SAli.Saidi@ARM.com        newobj = self.__class__(self)
2548459SAli.Saidi@ARM.com        newobj.value /= other
25512050Snikos.nikoleris@arm.com        newobj._check()
2563101Sstever@eecs.umich.edu        return newobj
2577528Ssteve.reinhardt@amd.com
2587528Ssteve.reinhardt@amd.com    def __sub__(self, other):
2597528Ssteve.reinhardt@amd.com        newobj = self.__class__(self)
2607528Ssteve.reinhardt@amd.com        newobj.value -= other
2617528Ssteve.reinhardt@amd.com        newobj._check()
2627528Ssteve.reinhardt@amd.com        return newobj
2633101Sstever@eecs.umich.edu
2647528Ssteve.reinhardt@amd.com# Metaclass for bounds-checked integer parameters.  See CheckedInt.
2657528Ssteve.reinhardt@amd.comclass CheckedIntType(type):
2667528Ssteve.reinhardt@amd.com    def __init__(cls, name, bases, dict):
2677528Ssteve.reinhardt@amd.com        super(CheckedIntType, cls).__init__(name, bases, dict)
2687528Ssteve.reinhardt@amd.com
2697528Ssteve.reinhardt@amd.com        # CheckedInt is an abstract base class, so we actually don't
2707528Ssteve.reinhardt@amd.com        # want to do any processing on it... the rest of this code is
2717528Ssteve.reinhardt@amd.com        # just for classes that derive from CheckedInt.
2727528Ssteve.reinhardt@amd.com        if name == 'CheckedInt':
2737528Ssteve.reinhardt@amd.com            return
2748321Ssteve.reinhardt@amd.com
27512194Sgabeblack@google.com        if not cls.cxx_predecls:
2767528Ssteve.reinhardt@amd.com            # most derived types require this, so we just do it here once
2777528Ssteve.reinhardt@amd.com            cls.cxx_predecls = ['#include "sim/host.hh"']
2787528Ssteve.reinhardt@amd.com
2797528Ssteve.reinhardt@amd.com        if not cls.swig_predecls:
2807528Ssteve.reinhardt@amd.com            # most derived types require this, so we just do it here once
2817528Ssteve.reinhardt@amd.com            cls.swig_predecls = ['%import "python/m5/swig/stdint.i"\n' +
2827528Ssteve.reinhardt@amd.com                                 '%import "sim/host.hh"']
2837528Ssteve.reinhardt@amd.com
2847528Ssteve.reinhardt@amd.com        if not (hasattr(cls, 'min') and hasattr(cls, 'max')):
2857528Ssteve.reinhardt@amd.com            if not (hasattr(cls, 'size') and hasattr(cls, 'unsigned')):
2867528Ssteve.reinhardt@amd.com                panic("CheckedInt subclass %s must define either\n" \
2877528Ssteve.reinhardt@amd.com                      "    'min' and 'max' or 'size' and 'unsigned'\n" \
2887528Ssteve.reinhardt@amd.com                      % name);
2893101Sstever@eecs.umich.edu            if cls.unsigned:
2908664SAli.Saidi@ARM.com                cls.min = 0
2918664SAli.Saidi@ARM.com                cls.max = 2 ** cls.size - 1
2928664SAli.Saidi@ARM.com            else:
2938664SAli.Saidi@ARM.com                cls.min = -(2 ** (cls.size - 1))
2948664SAli.Saidi@ARM.com                cls.max = (2 ** (cls.size - 1)) - 1
2958664SAli.Saidi@ARM.com
2969953Sgeoffrey.blake@arm.com# Abstract superclass for bounds-checked integer parameters.  This
2979953Sgeoffrey.blake@arm.com# class is subclassed to generate parameter classes with specific
2989953Sgeoffrey.blake@arm.com# bounds.  Initialization of the min and max bounds is done in the
2999953Sgeoffrey.blake@arm.com# metaclass CheckedIntType.__init__.
3009953Sgeoffrey.blake@arm.comclass CheckedInt(NumericParamValue):
3019953Sgeoffrey.blake@arm.com    __metaclass__ = CheckedIntType
3029953Sgeoffrey.blake@arm.com
3039953Sgeoffrey.blake@arm.com    def _check(self):
3049953Sgeoffrey.blake@arm.com        if not self.min <= self.value <= self.max:
3059953Sgeoffrey.blake@arm.com            raise TypeError, 'Integer param out of bounds %d < %d < %d' % \
3069953Sgeoffrey.blake@arm.com                  (self.min, self.value, self.max)
3079953Sgeoffrey.blake@arm.com
3089953Sgeoffrey.blake@arm.com    def __init__(self, value):
30910267SGeoffrey.Blake@arm.com        if isinstance(value, str):
31010267SGeoffrey.Blake@arm.com            self.value = convert.toInteger(value)
31110267SGeoffrey.Blake@arm.com        elif isinstance(value, (int, long, float)):
31210267SGeoffrey.Blake@arm.com            self.value = long(value)
31310267SGeoffrey.Blake@arm.com        self._check()
31410267SGeoffrey.Blake@arm.com
31510267SGeoffrey.Blake@arm.comclass Int(CheckedInt):      cxx_type = 'int';      size = 32; unsigned = False
31612563Sgabeblack@google.comclass Unsigned(CheckedInt): cxx_type = 'unsigned'; size = 32; unsigned = True
31710267SGeoffrey.Blake@arm.com
31810267SGeoffrey.Blake@arm.comclass Int8(CheckedInt):     cxx_type =   'int8_t'; size =  8; unsigned = False
31910267SGeoffrey.Blake@arm.comclass UInt8(CheckedInt):    cxx_type =  'uint8_t'; size =  8; unsigned = True
32010267SGeoffrey.Blake@arm.comclass Int16(CheckedInt):    cxx_type =  'int16_t'; size = 16; unsigned = False
32110267SGeoffrey.Blake@arm.comclass UInt16(CheckedInt):   cxx_type = 'uint16_t'; size = 16; unsigned = True
32210267SGeoffrey.Blake@arm.comclass Int32(CheckedInt):    cxx_type =  'int32_t'; size = 32; unsigned = False
32310267SGeoffrey.Blake@arm.comclass UInt32(CheckedInt):   cxx_type = 'uint32_t'; size = 32; unsigned = True
32410267SGeoffrey.Blake@arm.comclass Int64(CheckedInt):    cxx_type =  'int64_t'; size = 64; unsigned = False
32510267SGeoffrey.Blake@arm.comclass UInt64(CheckedInt):   cxx_type = 'uint64_t'; size = 64; unsigned = True
32610267SGeoffrey.Blake@arm.com
32710267SGeoffrey.Blake@arm.comclass Counter(CheckedInt):  cxx_type = 'Counter';  size = 64; unsigned = True
32810267SGeoffrey.Blake@arm.comclass Tick(CheckedInt):     cxx_type = 'Tick';     size = 64; unsigned = True
3293101Sstever@eecs.umich.educlass TcpPort(CheckedInt):  cxx_type = 'uint16_t'; size = 16; unsigned = True
3303101Sstever@eecs.umich.educlass UdpPort(CheckedInt):  cxx_type = 'uint16_t'; size = 16; unsigned = True
3313101Sstever@eecs.umich.edu
3323101Sstever@eecs.umich.educlass Percent(CheckedInt):  cxx_type = 'int'; min = 0; max = 100
3333101Sstever@eecs.umich.edu
3343101Sstever@eecs.umich.educlass Float(ParamValue, float):
3353101Sstever@eecs.umich.edu    pass
33610364SGeoffrey.Blake@arm.com
33710364SGeoffrey.Blake@arm.comclass MemorySize(CheckedInt):
33810364SGeoffrey.Blake@arm.com    cxx_type = 'uint64_t'
33910364SGeoffrey.Blake@arm.com    size = 64
3403101Sstever@eecs.umich.edu    unsigned = True
3414762Snate@binkert.org    def __init__(self, value):
3424762Snate@binkert.org        if isinstance(value, MemorySize):
3434762Snate@binkert.org            self.value = value.value
3444762Snate@binkert.org        else:
3457528Ssteve.reinhardt@amd.com            self.value = convert.toMemorySize(value)
3464762Snate@binkert.org        self._check()
3474762Snate@binkert.org
3484762Snate@binkert.orgclass MemorySize32(CheckedInt):
34910267SGeoffrey.Blake@arm.com    size = 32
35010267SGeoffrey.Blake@arm.com    unsigned = True
35110267SGeoffrey.Blake@arm.com    def __init__(self, value):
35210267SGeoffrey.Blake@arm.com        if isinstance(value, MemorySize):
35310267SGeoffrey.Blake@arm.com            self.value = value.value
35410267SGeoffrey.Blake@arm.com        else:
35510267SGeoffrey.Blake@arm.com            self.value = convert.toMemorySize(value)
35610267SGeoffrey.Blake@arm.com        self._check()
35710267SGeoffrey.Blake@arm.com
35810267SGeoffrey.Blake@arm.comclass Addr(CheckedInt):
35910267SGeoffrey.Blake@arm.com    cxx_type = 'Addr'
36010267SGeoffrey.Blake@arm.com    cxx_predecls = ['#include "targetarch/isa_traits.hh"']
36110267SGeoffrey.Blake@arm.com    size = 64
36210267SGeoffrey.Blake@arm.com    unsigned = True
36310267SGeoffrey.Blake@arm.com    def __init__(self, value):
36410267SGeoffrey.Blake@arm.com        if isinstance(value, Addr):
36510267SGeoffrey.Blake@arm.com            self.value = value.value
36610267SGeoffrey.Blake@arm.com        else:
36710267SGeoffrey.Blake@arm.com            try:
36810267SGeoffrey.Blake@arm.com                self.value = convert.toMemorySize(value)
36910267SGeoffrey.Blake@arm.com            except TypeError:
37010267SGeoffrey.Blake@arm.com                self.value = long(value)
37110267SGeoffrey.Blake@arm.com        self._check()
37210267SGeoffrey.Blake@arm.com    def __add__(self, other):
37310267SGeoffrey.Blake@arm.com        if isinstance(other, Addr):
37410267SGeoffrey.Blake@arm.com            return self.value + other.value
37510364SGeoffrey.Blake@arm.com        else:
37610364SGeoffrey.Blake@arm.com            return self.value + other
37710267SGeoffrey.Blake@arm.com
37810267SGeoffrey.Blake@arm.com
37910267SGeoffrey.Blake@arm.comclass MetaRange(type):
38010267SGeoffrey.Blake@arm.com    def __init__(cls, name, bases, dict):
38110267SGeoffrey.Blake@arm.com        super(MetaRange, cls).__init__(name, bases, dict)
38210267SGeoffrey.Blake@arm.com        if name == 'Range':
3837673Snate@binkert.org            return
3847673Snate@binkert.org        cls.cxx_type = 'Range< %s >' % cls.type.cxx_type
3857673Snate@binkert.org        cls.cxx_predecls = \
3863101Sstever@eecs.umich.edu                       ['#include "base/range.hh"'] + cls.type.cxx_predecls
38711988Sandreas.sandberg@arm.com
38811988Sandreas.sandberg@arm.comclass Range(ParamValue):
38911988Sandreas.sandberg@arm.com    __metaclass__ = MetaRange
39011988Sandreas.sandberg@arm.com    type = Int # default; can be overridden in subclasses
3917673Snate@binkert.org    def __init__(self, *args, **kwargs):
3927673Snate@binkert.org        def handle_kwargs(self, kwargs):
3933101Sstever@eecs.umich.edu            if 'end' in kwargs:
3943101Sstever@eecs.umich.edu                self.second = self.type(kwargs.pop('end'))
3953101Sstever@eecs.umich.edu            elif 'size' in kwargs:
3963101Sstever@eecs.umich.edu                self.second = self.first + self.type(kwargs.pop('size')) - 1
3973101Sstever@eecs.umich.edu            else:
3983101Sstever@eecs.umich.edu                raise TypeError, "Either end or size must be specified"
3993101Sstever@eecs.umich.edu
4003101Sstever@eecs.umich.edu        if len(args) == 0:
4013101Sstever@eecs.umich.edu            self.first = self.type(kwargs.pop('start'))
4023101Sstever@eecs.umich.edu            handle_kwargs(self, kwargs)
4033101Sstever@eecs.umich.edu
4043101Sstever@eecs.umich.edu        elif len(args) == 1:
4053101Sstever@eecs.umich.edu            if kwargs:
4063101Sstever@eecs.umich.edu                self.first = self.type(args[0])
4073101Sstever@eecs.umich.edu                handle_kwargs(self, kwargs)
4085033Smilesck@eecs.umich.edu            elif isinstance(args[0], Range):
4095033Smilesck@eecs.umich.edu                self.first = self.type(args[0].first)
4103101Sstever@eecs.umich.edu                self.second = self.type(args[0].second)
4113101Sstever@eecs.umich.edu            else:
4123101Sstever@eecs.umich.edu                self.first = self.type(0)
4133101Sstever@eecs.umich.edu                self.second = self.type(args[0]) - 1
4143101Sstever@eecs.umich.edu
4153101Sstever@eecs.umich.edu        elif len(args) == 2:
4163101Sstever@eecs.umich.edu            self.first = self.type(args[0])
4173101Sstever@eecs.umich.edu            self.second = self.type(args[1])
4183101Sstever@eecs.umich.edu        else:
4193101Sstever@eecs.umich.edu            raise TypeError, "Too many arguments specified"
4203101Sstever@eecs.umich.edu
4213101Sstever@eecs.umich.edu        if kwargs:
4223101Sstever@eecs.umich.edu            raise TypeError, "too many keywords: %s" % kwargs.keys()
4233101Sstever@eecs.umich.edu
4243101Sstever@eecs.umich.edu    def __str__(self):
4253101Sstever@eecs.umich.edu        return '%s:%s' % (self.first, self.second)
4263101Sstever@eecs.umich.edu
4273101Sstever@eecs.umich.educlass AddrRange(Range):
4283101Sstever@eecs.umich.edu    type = Addr
4293101Sstever@eecs.umich.edu
4303101Sstever@eecs.umich.educlass TickRange(Range):
4313101Sstever@eecs.umich.edu    type = Tick
4323101Sstever@eecs.umich.edu
4333101Sstever@eecs.umich.edu# Boolean parameter type.  Python doesn't let you subclass bool, since
4343101Sstever@eecs.umich.edu# it doesn't want to let you create multiple instances of True and
43510267SGeoffrey.Blake@arm.com# False.  Thus this is a little more complicated than String.
4367673Snate@binkert.orgclass Bool(ParamValue):
4377673Snate@binkert.org    cxx_type = 'bool'
4387673Snate@binkert.org    def __init__(self, value):
4397673Snate@binkert.org        try:
4407673Snate@binkert.org            self.value = convert.toBool(value)
44110267SGeoffrey.Blake@arm.com        except TypeError:
44210267SGeoffrey.Blake@arm.com            self.value = bool(value)
44310267SGeoffrey.Blake@arm.com
44410267SGeoffrey.Blake@arm.com    def __str__(self):
44510458Sandreas.hansson@arm.com        return str(self.value)
44610458Sandreas.hansson@arm.com
44710458Sandreas.hansson@arm.com    def ini_str(self):
44810458Sandreas.hansson@arm.com        if self.value:
44910458Sandreas.hansson@arm.com            return 'true'
4504762Snate@binkert.org        return 'false'
4514762Snate@binkert.org
4523101Sstever@eecs.umich.edudef IncEthernetAddr(addr, val = 1):
4533101Sstever@eecs.umich.edu    bytes = map(lambda x: int(x, 16), addr.split(':'))
4543101Sstever@eecs.umich.edu    bytes[5] += val
4553101Sstever@eecs.umich.edu    for i in (5, 4, 3, 2, 1):
4563101Sstever@eecs.umich.edu        val,rem = divmod(bytes[i], 256)
4573101Sstever@eecs.umich.edu        bytes[i] = rem
4583101Sstever@eecs.umich.edu        if val == 0:
4593101Sstever@eecs.umich.edu            break
4603101Sstever@eecs.umich.edu        bytes[i - 1] += val
4613101Sstever@eecs.umich.edu    assert(bytes[0] <= 255)
4623101Sstever@eecs.umich.edu    return ':'.join(map(lambda x: '%02x' % x, bytes))
4633714Sstever@eecs.umich.edu
4643714Sstever@eecs.umich.educlass NextEthernetAddr(object):
4653714Sstever@eecs.umich.edu    addr = "00:90:00:00:00:01"
4663714Sstever@eecs.umich.edu
4673714Sstever@eecs.umich.edu    def __init__(self, inc = 1):
4683714Sstever@eecs.umich.edu        self.value = NextEthernetAddr.addr
4693101Sstever@eecs.umich.edu        NextEthernetAddr.addr = IncEthernetAddr(NextEthernetAddr.addr, inc)
4703101Sstever@eecs.umich.edu
4713101Sstever@eecs.umich.educlass EthernetAddr(ParamValue):
4723101Sstever@eecs.umich.edu    cxx_type = 'Net::EthAddr'
4733101Sstever@eecs.umich.edu    cxx_predecls = ['#include "base/inet.hh"']
4743101Sstever@eecs.umich.edu    swig_predecls = ['class Net::EthAddr;']
4753101Sstever@eecs.umich.edu    def __init__(self, value):
4763101Sstever@eecs.umich.edu        if value == NextEthernetAddr:
4773101Sstever@eecs.umich.edu            self.value = value
4783101Sstever@eecs.umich.edu            return
4793101Sstever@eecs.umich.edu
4803101Sstever@eecs.umich.edu        if not isinstance(value, str):
4813101Sstever@eecs.umich.edu            raise TypeError, "expected an ethernet address and didn't get one"
4823101Sstever@eecs.umich.edu
4833101Sstever@eecs.umich.edu        bytes = value.split(':')
4843101Sstever@eecs.umich.edu        if len(bytes) != 6:
4853101Sstever@eecs.umich.edu            raise TypeError, 'invalid ethernet address %s' % value
4863101Sstever@eecs.umich.edu
4873101Sstever@eecs.umich.edu        for byte in bytes:
4883101Sstever@eecs.umich.edu            if not 0 <= int(byte) <= 256:
4893101Sstever@eecs.umich.edu                raise TypeError, 'invalid ethernet address %s' % value
4903101Sstever@eecs.umich.edu
4913101Sstever@eecs.umich.edu        self.value = value
4923101Sstever@eecs.umich.edu
49310380SAndrew.Bardsley@arm.com    def unproxy(self, base):
49410380SAndrew.Bardsley@arm.com        if self.value == NextEthernetAddr:
49510380SAndrew.Bardsley@arm.com            self.addr = self.value().value
49610458Sandreas.hansson@arm.com        return self
49710458Sandreas.hansson@arm.com
49810458Sandreas.hansson@arm.com    def __str__(self):
49910458Sandreas.hansson@arm.com        if self.value == NextEthernetAddr:
50010458Sandreas.hansson@arm.com            if hasattr(self, 'addr'):
50110458Sandreas.hansson@arm.com                return self.addr
50210458Sandreas.hansson@arm.com            else:
50310458Sandreas.hansson@arm.com                return "NextEthernetAddr (unresolved)"
50410458Sandreas.hansson@arm.com        else:
50510458Sandreas.hansson@arm.com            return self.value
50610458Sandreas.hansson@arm.com
50710458Sandreas.hansson@arm.com# Enumerated types are a little more complex.  The user specifies the
50810458Sandreas.hansson@arm.com# type as Enum(foo) where foo is either a list or dictionary of
5093101Sstever@eecs.umich.edu# alternatives (typically strings, but not necessarily so).  (In the
5105033Smilesck@eecs.umich.edu# long run, the integer value of the parameter will be the list index
5113101Sstever@eecs.umich.edu# or the corresponding dictionary value.  For now, since we only check
5123101Sstever@eecs.umich.edu# that the alternative is valid and then spit it into a .ini file,
5133101Sstever@eecs.umich.edu# there's not much point in using the dictionary.)
5143101Sstever@eecs.umich.edu
5153101Sstever@eecs.umich.edu# What Enum() must do is generate a new type encapsulating the
5163101Sstever@eecs.umich.edu# provided list/dictionary so that specific values of the parameter
5173101Sstever@eecs.umich.edu# can be instances of that type.  We define two hidden internal
5183101Sstever@eecs.umich.edu# classes (_ListEnum and _DictEnum) to serve as base classes, then
5193101Sstever@eecs.umich.edu# derive the new type from the appropriate base class on the fly.
5203101Sstever@eecs.umich.edu
5213101Sstever@eecs.umich.edu
5223101Sstever@eecs.umich.edu# Metaclass for Enum types
5235822Ssaidi@eecs.umich.educlass MetaEnum(type):
5245822Ssaidi@eecs.umich.edu    def __init__(cls, name, bases, init_dict):
5253101Sstever@eecs.umich.edu        if init_dict.has_key('map'):
5263101Sstever@eecs.umich.edu            if not isinstance(cls.map, dict):
5273101Sstever@eecs.umich.edu                raise TypeError, "Enum-derived class attribute 'map' " \
5283101Sstever@eecs.umich.edu                      "must be of type dict"
5293101Sstever@eecs.umich.edu            # build list of value strings from map
5303101Sstever@eecs.umich.edu            cls.vals = cls.map.keys()
5313101Sstever@eecs.umich.edu            cls.vals.sort()
5323101Sstever@eecs.umich.edu        elif init_dict.has_key('vals'):
5333101Sstever@eecs.umich.edu            if not isinstance(cls.vals, list):
5343101Sstever@eecs.umich.edu                raise TypeError, "Enum-derived class attribute 'vals' " \
5353101Sstever@eecs.umich.edu                      "must be of type list"
5363101Sstever@eecs.umich.edu            # build string->value map from vals sequence
5373101Sstever@eecs.umich.edu            cls.map = {}
53810267SGeoffrey.Blake@arm.com            for idx,val in enumerate(cls.vals):
5393101Sstever@eecs.umich.edu                cls.map[val] = idx
5403101Sstever@eecs.umich.edu        else:
5413101Sstever@eecs.umich.edu            raise TypeError, "Enum-derived class must define "\
5423101Sstever@eecs.umich.edu                  "attribute 'map' or 'vals'"
5433101Sstever@eecs.umich.edu
5443101Sstever@eecs.umich.edu        cls.cxx_type = name + '::Enum'
5453101Sstever@eecs.umich.edu
5463101Sstever@eecs.umich.edu        super(MetaEnum, cls).__init__(name, bases, init_dict)
5473102Sstever@eecs.umich.edu
5483714Sstever@eecs.umich.edu    # Generate C++ class declaration for this enum type.
5493101Sstever@eecs.umich.edu    # Note that we wrap the enum in a class/struct to act as a namespace,
5503714Sstever@eecs.umich.edu    # so that the enum strings can be brief w/o worrying about collisions.
5513714Sstever@eecs.umich.edu    def cxx_decl(cls):
5523714Sstever@eecs.umich.edu        s = 'struct %s {\n  enum Enum {\n    ' % cls.__name__
5533101Sstever@eecs.umich.edu        s += ',\n    '.join(['%s = %d' % (v,cls.map[v]) for v in cls.vals])
5543101Sstever@eecs.umich.edu        s += '\n  };\n};\n'
55510267SGeoffrey.Blake@arm.com        return s
55610267SGeoffrey.Blake@arm.com
55710267SGeoffrey.Blake@arm.com# Base class for enum types.
55810267SGeoffrey.Blake@arm.comclass Enum(ParamValue):
5597673Snate@binkert.org    __metaclass__ = MetaEnum
5607673Snate@binkert.org    vals = []
5617673Snate@binkert.org
5627673Snate@binkert.org    def __init__(self, value):
5637673Snate@binkert.org        if value not in self.map:
5644762Snate@binkert.org            raise TypeError, "Enum param got bad value '%s' (not in %s)" \
5654762Snate@binkert.org                  % (value, self.vals)
5664762Snate@binkert.org        self.value = value
5673101Sstever@eecs.umich.edu
5683101Sstever@eecs.umich.edu    def __str__(self):
5693101Sstever@eecs.umich.edu        return self.value
5703101Sstever@eecs.umich.edu
5713101Sstever@eecs.umich.eduticks_per_sec = None
5723101Sstever@eecs.umich.edu
5733101Sstever@eecs.umich.edu# how big does a rounding error need to be before we warn about it?
5743101Sstever@eecs.umich.edufrequency_tolerance = 0.001  # 0.1%
5753101Sstever@eecs.umich.edu
5763101Sstever@eecs.umich.edu# convert a floting-point # of ticks to integer, and warn if rounding
5773101Sstever@eecs.umich.edu# discards too much precision
5783101Sstever@eecs.umich.edudef tick_check(float_ticks):
5793101Sstever@eecs.umich.edu    if float_ticks == 0:
5803101Sstever@eecs.umich.edu        return 0
5813101Sstever@eecs.umich.edu    int_ticks = int(round(float_ticks))
5823101Sstever@eecs.umich.edu    err = (float_ticks - int_ticks) / float_ticks
5833101Sstever@eecs.umich.edu    if err > frequency_tolerance:
5843101Sstever@eecs.umich.edu        print >> sys.stderr, "Warning: rounding error > tolerance"
5853101Sstever@eecs.umich.edu        print >> sys.stderr, "    %f rounded to %d" % (float_ticks, int_ticks)
5869184Sandreas.hansson@arm.com        #raise ValueError
5879184Sandreas.hansson@arm.com    return int_ticks
5889184Sandreas.hansson@arm.com
5899184Sandreas.hansson@arm.comdef getLatency(value):
5909184Sandreas.hansson@arm.com    if isinstance(value, Latency) or isinstance(value, Clock):
5919184Sandreas.hansson@arm.com        return value.value
59211802Sandreas.sandberg@arm.com    elif isinstance(value, Frequency) or isinstance(value, RootClock):
5939184Sandreas.hansson@arm.com        return 1 / value.value
5949184Sandreas.hansson@arm.com    elif isinstance(value, str):
59510458Sandreas.hansson@arm.com        try:
59610458Sandreas.hansson@arm.com            return convert.toLatency(value)
59710458Sandreas.hansson@arm.com        except ValueError:
59810458Sandreas.hansson@arm.com            try:
59910458Sandreas.hansson@arm.com                return 1 / convert.toFrequency(value)
60010458Sandreas.hansson@arm.com            except ValueError:
60110458Sandreas.hansson@arm.com                pass # fall through
60210458Sandreas.hansson@arm.com    raise ValueError, "Invalid Frequency/Latency value '%s'" % value
60310458Sandreas.hansson@arm.com
60410458Sandreas.hansson@arm.com
60510458Sandreas.hansson@arm.comclass Latency(NumericParamValue):
60610458Sandreas.hansson@arm.com    cxx_type = 'Tick'
60710458Sandreas.hansson@arm.com    cxx_predecls = ['#include "sim/host.hh"']
60810458Sandreas.hansson@arm.com    swig_predecls = ['%import "python/m5/swig/stdint.i"\n' +
6093101Sstever@eecs.umich.edu                     '%import "sim/host.hh"']
6104446Sbinkertn@umich.edu    def __init__(self, value):
61110668SGeoffrey.Blake@arm.com        self.value = getLatency(value)
6123101Sstever@eecs.umich.edu
6135468Snate@binkert.org    def __getattr__(self, attr):
61410267SGeoffrey.Blake@arm.com        if attr in ('latency', 'period'):
6155468Snate@binkert.org            return self
6165468Snate@binkert.org        if attr == 'frequency':
6175468Snate@binkert.org            return Frequency(self)
6185468Snate@binkert.org        raise AttributeError, "Latency object has no attribute '%s'" % attr
6195468Snate@binkert.org
62010267SGeoffrey.Blake@arm.com    # convert latency to ticks
62110267SGeoffrey.Blake@arm.com    def ini_str(self):
62210267SGeoffrey.Blake@arm.com        return str(tick_check(self.value * ticks_per_sec))
62310267SGeoffrey.Blake@arm.com
6244762Snate@binkert.orgclass Frequency(NumericParamValue):
6254762Snate@binkert.org    cxx_type = 'Tick'
6264762Snate@binkert.org    cxx_predecls = ['#include "sim/host.hh"']
62710380SAndrew.Bardsley@arm.com    swig_predecls = ['%import "python/m5/swig/stdint.i"\n' +
62810380SAndrew.Bardsley@arm.com                     '%import "sim/host.hh"']
62910380SAndrew.Bardsley@arm.com    def __init__(self, value):
63010458Sandreas.hansson@arm.com        self.value = 1 / getLatency(value)
63110458Sandreas.hansson@arm.com
63210458Sandreas.hansson@arm.com    def __getattr__(self, attr):
63310458Sandreas.hansson@arm.com        if attr == 'frequency':
63410458Sandreas.hansson@arm.com            return self
63510458Sandreas.hansson@arm.com        if attr in ('latency', 'period'):
63610458Sandreas.hansson@arm.com            return Latency(self)
63710458Sandreas.hansson@arm.com        raise AttributeError, "Frequency object has no attribute '%s'" % attr
6383101Sstever@eecs.umich.edu
6393101Sstever@eecs.umich.edu    # convert frequency to ticks per period
64010267SGeoffrey.Blake@arm.com    def ini_str(self):
6413101Sstever@eecs.umich.edu        return self.period.ini_str()
6423101Sstever@eecs.umich.edu
6433101Sstever@eecs.umich.edu# Just like Frequency, except ini_str() is absolute # of ticks per sec (Hz).
6443101Sstever@eecs.umich.edu# We can't inherit from Frequency because we don't want it to be directly
6453101Sstever@eecs.umich.edu# assignable to a regular Frequency parameter.
6463101Sstever@eecs.umich.educlass RootClock(ParamValue):
6473102Sstever@eecs.umich.edu    cxx_type = 'Tick'
6483101Sstever@eecs.umich.edu    cxx_predecls = ['#include "sim/host.hh"']
6493101Sstever@eecs.umich.edu    swig_predecls = ['%import "python/m5/swig/stdint.i"\n' +
6503101Sstever@eecs.umich.edu                     '%import "sim/host.hh"']
6514168Sbinkertn@umich.edu    def __init__(self, value):
65210267SGeoffrey.Blake@arm.com        self.value = 1 / getLatency(value)
6533101Sstever@eecs.umich.edu
6543101Sstever@eecs.umich.edu    def __getattr__(self, attr):
6553101Sstever@eecs.umich.edu        if attr == 'frequency':
6563101Sstever@eecs.umich.edu            return Frequency(self)
6573101Sstever@eecs.umich.edu        if attr in ('latency', 'period'):
6583101Sstever@eecs.umich.edu            return Latency(self)
6593102Sstever@eecs.umich.edu        raise AttributeError, "Frequency object has no attribute '%s'" % attr
6603101Sstever@eecs.umich.edu
6613101Sstever@eecs.umich.edu    def ini_str(self):
6623101Sstever@eecs.umich.edu        return str(tick_check(self.value))
6633101Sstever@eecs.umich.edu
6643101Sstever@eecs.umich.edu# A generic frequency and/or Latency value.  Value is stored as a latency,
6653101Sstever@eecs.umich.edu# but to avoid ambiguity this object does not support numeric ops (* or /).
6663101Sstever@eecs.umich.edu# An explicit conversion to a Latency or Frequency must be made first.
6673101Sstever@eecs.umich.educlass Clock(ParamValue):
6683101Sstever@eecs.umich.edu    cxx_type = 'Tick'
6693101Sstever@eecs.umich.edu    cxx_predecls = ['#include "sim/host.hh"']
6703101Sstever@eecs.umich.edu    swig_predecls = ['%import "python/m5/swig/stdint.i"\n' +
67110317Smitch.hayenga@arm.com                     '%import "sim/host.hh"']
67210317Smitch.hayenga@arm.com    def __init__(self, value):
67310317Smitch.hayenga@arm.com        self.value = getLatency(value)
67410317Smitch.hayenga@arm.com
67510317Smitch.hayenga@arm.com    def __getattr__(self, attr):
6763102Sstever@eecs.umich.edu        if attr == 'frequency':
67710317Smitch.hayenga@arm.com            return Frequency(self)
67810317Smitch.hayenga@arm.com        if attr in ('latency', 'period'):
67910317Smitch.hayenga@arm.com            return Latency(self)
68010317Smitch.hayenga@arm.com        raise AttributeError, "Frequency object has no attribute '%s'" % attr
68110317Smitch.hayenga@arm.com
6823101Sstever@eecs.umich.edu    def ini_str(self):
6833584Ssaidi@eecs.umich.edu        return self.period.ini_str()
6843584Ssaidi@eecs.umich.edu
6853584Ssaidi@eecs.umich.educlass NetworkBandwidth(float,ParamValue):
6863584Ssaidi@eecs.umich.edu    cxx_type = 'float'
6873584Ssaidi@eecs.umich.edu    def __new__(cls, value):
68810267SGeoffrey.Blake@arm.com        val = convert.toNetworkBandwidth(value) / 8.0
68910267SGeoffrey.Blake@arm.com        return super(cls, NetworkBandwidth).__new__(cls, val)
69010267SGeoffrey.Blake@arm.com
69110267SGeoffrey.Blake@arm.com    def __str__(self):
69210267SGeoffrey.Blake@arm.com        return str(self.val)
69310267SGeoffrey.Blake@arm.com
6943101Sstever@eecs.umich.edu    def ini_str(self):
6959232Sandreas.hansson@arm.com        return '%f' % (ticks_per_sec / float(self))
6969235Sandreas.hansson@arm.com
6973101Sstever@eecs.umich.educlass MemoryBandwidth(float,ParamValue):
6983101Sstever@eecs.umich.edu    cxx_type = 'float'
69910676Sandreas.hansson@arm.com    def __new__(self, value):
7009411Sandreas.hansson@arm.com        val = convert.toMemoryBandwidth(value)
70110676Sandreas.hansson@arm.com        return super(cls, MemoryBandwidth).__new__(cls, val)
7029411Sandreas.hansson@arm.com
7039411Sandreas.hansson@arm.com    def __str__(self):
7049411Sandreas.hansson@arm.com        return str(self.val)
7053101Sstever@eecs.umich.edu
7069411Sandreas.hansson@arm.com    def ini_str(self):
7079411Sandreas.hansson@arm.com        return '%f' % (ticks_per_sec / float(self))
7089411Sandreas.hansson@arm.com
7093101Sstever@eecs.umich.edu#
7109232Sandreas.hansson@arm.com# "Constants"... handy aliases for various values.
7113101Sstever@eecs.umich.edu#
7129232Sandreas.hansson@arm.com
7133101Sstever@eecs.umich.edu# Special class for NULL pointers.  Note the special check in
7143101Sstever@eecs.umich.edu# make_param_value() above that lets these be assigned where a
7153101Sstever@eecs.umich.edu# SimObject is required.
7169411Sandreas.hansson@arm.com# only one copy of a particular node
7179411Sandreas.hansson@arm.comclass NullSimObject(object):
7189411Sandreas.hansson@arm.com    __metaclass__ = Singleton
71910676Sandreas.hansson@arm.com
72010676Sandreas.hansson@arm.com    def __call__(cls):
7219411Sandreas.hansson@arm.com        return cls
7229411Sandreas.hansson@arm.com
7239411Sandreas.hansson@arm.com    def _instantiate(self, parent = None, path = ''):
7249411Sandreas.hansson@arm.com        pass
7259411Sandreas.hansson@arm.com
7263101Sstever@eecs.umich.edu    def ini_str(self):
7279232Sandreas.hansson@arm.com        return 'Null'
7283101Sstever@eecs.umich.edu
7293101Sstever@eecs.umich.edu    def unproxy(self, base):
7303101Sstever@eecs.umich.edu        return self
7313101Sstever@eecs.umich.edu
7329232Sandreas.hansson@arm.com    def set_path(self, parent, name):
7333101Sstever@eecs.umich.edu        pass
7345219Ssaidi@eecs.umich.edu    def __str__(self):
7359232Sandreas.hansson@arm.com        return 'Null'
7369232Sandreas.hansson@arm.com
7373101Sstever@eecs.umich.edu# The only instance you'll ever need...
7389232Sandreas.hansson@arm.comNULL = NullSimObject()
7399232Sandreas.hansson@arm.com
7403101Sstever@eecs.umich.edudef isNullPointer(value):
7413101Sstever@eecs.umich.edu    return isinstance(value, NullSimObject)
7429232Sandreas.hansson@arm.com
7439232Sandreas.hansson@arm.com# Some memory range specifications use this as a default upper bound.
7443101Sstever@eecs.umich.eduMaxAddr = Addr.max
7453101Sstever@eecs.umich.eduMaxTick = Tick.max
7463101Sstever@eecs.umich.eduAllMemory = AddrRange(0, MaxAddr)
7473101Sstever@eecs.umich.edu
7489232Sandreas.hansson@arm.com
7493101Sstever@eecs.umich.edu#####################################################################
7503101Sstever@eecs.umich.edu#
75111620SMatthew.Poremba@amd.com# Port objects
75211620SMatthew.Poremba@amd.com#
75311620SMatthew.Poremba@amd.com# Ports are used to interconnect objects in the memory system.
7549232Sandreas.hansson@arm.com#
7559232Sandreas.hansson@arm.com#####################################################################
7569411Sandreas.hansson@arm.com
7579411Sandreas.hansson@arm.com# Port reference: encapsulates a reference to a particular port on a
7583101Sstever@eecs.umich.edu# particular SimObject.
7597673Snate@binkert.orgclass PortRef(object):
7607673Snate@binkert.org    def __init__(self, simobj, name):
7619232Sandreas.hansson@arm.com        assert(isSimObject(simobj) or isSimObjectClass(simobj))
7629235Sandreas.hansson@arm.com        self.simobj = simobj
7637675Snate@binkert.org        self.name = name
7647675Snate@binkert.org        self.peer = None   # not associated with another port yet
76511988Sandreas.sandberg@arm.com        self.ccConnected = False # C++ port connection done?
76611988Sandreas.sandberg@arm.com        self.index = -1  # always -1 for non-vector ports
76711988Sandreas.sandberg@arm.com
76811988Sandreas.sandberg@arm.com    def __str__(self):
76911988Sandreas.sandberg@arm.com        return '%s.%s' % (self.simobj, self.name)
77010458Sandreas.hansson@arm.com
77110458Sandreas.hansson@arm.com    # for config.ini, print peer's name (not ours)
77210458Sandreas.hansson@arm.com    def ini_str(self):
77310458Sandreas.hansson@arm.com        return str(self.peer)
77410458Sandreas.hansson@arm.com
77511620SMatthew.Poremba@amd.com    def __getattr__(self, attr):
77611620SMatthew.Poremba@amd.com        if attr == 'peerObj':
77710458Sandreas.hansson@arm.com            # shorthand for proxies
77810458Sandreas.hansson@arm.com            return self.peer.simobj
77910458Sandreas.hansson@arm.com        raise AttributeError, "'%s' object has no attribute '%s'" % \
78010458Sandreas.hansson@arm.com              (self.__class__.__name__, attr)
78110458Sandreas.hansson@arm.com
78211620SMatthew.Poremba@amd.com    # Full connection is symmetric (both ways).  Called via
78311620SMatthew.Poremba@amd.com    # SimObject.__setattr__ as a result of a port assignment, e.g.,
78411620SMatthew.Poremba@amd.com    # "obj1.portA = obj2.portB", or via VectorPortElementRef.__setitem__,
78511620SMatthew.Poremba@amd.com    # e.g., "obj1.portA[3] = obj2.portB".
78611620SMatthew.Poremba@amd.com    def connect(self, other):
78711620SMatthew.Poremba@amd.com        if isinstance(other, VectorPortRef):
78811620SMatthew.Poremba@amd.com            # reference to plain VectorPort is implicit append
78911620SMatthew.Poremba@amd.com            other = other._get_next()
79011620SMatthew.Poremba@amd.com        if self.peer and not proxy.isproxy(self.peer):
79111620SMatthew.Poremba@amd.com            print "warning: overwriting port", self, \
79210458Sandreas.hansson@arm.com                  "value", self.peer, "with", other
79310458Sandreas.hansson@arm.com        self.peer = other
79410458Sandreas.hansson@arm.com        if proxy.isproxy(other):
79511620SMatthew.Poremba@amd.com            other.set_param_desc(PortParamDesc())
79611620SMatthew.Poremba@amd.com        elif isinstance(other, PortRef):
79710458Sandreas.hansson@arm.com            if other.peer is not self:
79810458Sandreas.hansson@arm.com                other.connect(self)
7994762Snate@binkert.org        else:
80011991Sandreas.sandberg@arm.com            raise TypeError, \
80111802Sandreas.sandberg@arm.com                  "assigning non-port reference '%s' to port '%s'" \
8024762Snate@binkert.org                  % (other, self)
8039411Sandreas.hansson@arm.com
80410676Sandreas.hansson@arm.com    def clone(self, simobj, memo):
80510676Sandreas.hansson@arm.com        if memo.has_key(self):
8063101Sstever@eecs.umich.edu            return memo[self]
8073101Sstever@eecs.umich.edu        newRef = copy.copy(self)
8083101Sstever@eecs.umich.edu        memo[self] = newRef
8093101Sstever@eecs.umich.edu        newRef.simobj = simobj
8103101Sstever@eecs.umich.edu        assert(isSimObject(newRef.simobj))
8113101Sstever@eecs.umich.edu        if self.peer and not proxy.isproxy(self.peer):
81210267SGeoffrey.Blake@arm.com            peerObj = self.peer.simobj(_memo=memo)
81310267SGeoffrey.Blake@arm.com            newRef.peer = self.peer.clone(peerObj, memo)
8143101Sstever@eecs.umich.edu            assert(not isinstance(newRef.peer, VectorPortRef))
8153101Sstever@eecs.umich.edu        return newRef
8163102Sstever@eecs.umich.edu
8173101Sstever@eecs.umich.edu    def unproxy(self, simobj):
8183101Sstever@eecs.umich.edu        assert(simobj is self.simobj)
8193101Sstever@eecs.umich.edu        if proxy.isproxy(self.peer):
82010267SGeoffrey.Blake@arm.com            try:
82110267SGeoffrey.Blake@arm.com                realPeer = self.peer.unproxy(self.simobj)
82210267SGeoffrey.Blake@arm.com            except:
82310267SGeoffrey.Blake@arm.com                print "Error in unproxying port '%s' of %s" % \
8244762Snate@binkert.org                      (self.name, self.simobj.path())
8254762Snate@binkert.org                raise
8264762Snate@binkert.org            self.connect(realPeer)
8273101Sstever@eecs.umich.edu
8283101Sstever@eecs.umich.edu    # Call C++ to create corresponding port connection between C++ objects
8293101Sstever@eecs.umich.edu    def ccConnect(self):
8308934SBrad.Beckmann@amd.com        if self.ccConnected: # already done this
8318934SBrad.Beckmann@amd.com            return
8328934SBrad.Beckmann@amd.com        peer = self.peer
8338934SBrad.Beckmann@amd.com        cc_main.connectPorts(self.simobj.getCCObject(), self.name, self.index,
8348934SBrad.Beckmann@amd.com                             peer.simobj.getCCObject(), peer.name, peer.index)
8353101Sstever@eecs.umich.edu        self.ccConnected = True
8363101Sstever@eecs.umich.edu        peer.ccConnected = True
8373101Sstever@eecs.umich.edu
8383101Sstever@eecs.umich.edu# A reference to an individual element of a VectorPort... much like a
8393101Sstever@eecs.umich.edu# PortRef, but has an index.
84010380SAndrew.Bardsley@arm.comclass VectorPortElementRef(PortRef):
84110380SAndrew.Bardsley@arm.com    def __init__(self, simobj, name, index):
84210380SAndrew.Bardsley@arm.com        PortRef.__init__(self, simobj, name)
84310458Sandreas.hansson@arm.com        self.index = index
84410458Sandreas.hansson@arm.com
84510458Sandreas.hansson@arm.com    def __str__(self):
84610458Sandreas.hansson@arm.com        return '%s.%s[%d]' % (self.simobj, self.name, self.index)
84710458Sandreas.hansson@arm.com
84810458Sandreas.hansson@arm.com# A reference to a complete vector-valued port (not just a single element).
84910458Sandreas.hansson@arm.com# Can be indexed to retrieve individual VectorPortElementRef instances.
85010458Sandreas.hansson@arm.comclass VectorPortRef(object):
85110458Sandreas.hansson@arm.com    def __init__(self, simobj, name):
85210458Sandreas.hansson@arm.com        assert(isSimObject(simobj) or isSimObjectClass(simobj))
8533101Sstever@eecs.umich.edu        self.simobj = simobj
8543101Sstever@eecs.umich.edu        self.name = name
8553101Sstever@eecs.umich.edu        self.elements = []
8563101Sstever@eecs.umich.edu
8573101Sstever@eecs.umich.edu    def __str__(self):
8583101Sstever@eecs.umich.edu        return '%s.%s[:]' % (self.simobj, self.name)
8593101Sstever@eecs.umich.edu
8603101Sstever@eecs.umich.edu    # for config.ini, print peer's name (not ours)
8613101Sstever@eecs.umich.edu    def ini_str(self):
8623101Sstever@eecs.umich.edu        return ' '.join([el.ini_str() for el in self.elements])
8633101Sstever@eecs.umich.edu
8643101Sstever@eecs.umich.edu    def __getitem__(self, key):
8654380Sbinkertn@umich.edu        if not isinstance(key, int):
8664380Sbinkertn@umich.edu            raise TypeError, "VectorPort index must be integer"
8674380Sbinkertn@umich.edu        if key >= len(self.elements):
8683101Sstever@eecs.umich.edu            # need to extend list
8694380Sbinkertn@umich.edu            ext = [VectorPortElementRef(self.simobj, self.name, i)
8704380Sbinkertn@umich.edu                   for i in range(len(self.elements), key+1)]
8714380Sbinkertn@umich.edu            self.elements.extend(ext)
8723101Sstever@eecs.umich.edu        return self.elements[key]
8733101Sstever@eecs.umich.edu
8743101Sstever@eecs.umich.edu    def _get_next(self):
87510267SGeoffrey.Blake@arm.com        return self[len(self.elements)]
87610267SGeoffrey.Blake@arm.com
8777673Snate@binkert.org    def __setitem__(self, key, value):
8787673Snate@binkert.org        if not isinstance(key, int):
8797673Snate@binkert.org            raise TypeError, "VectorPort index must be integer"
8807673Snate@binkert.org        self[key].connect(value)
8817673Snate@binkert.org
8823101Sstever@eecs.umich.edu    def connect(self, other):
8833101Sstever@eecs.umich.edu        if isinstance(other, (list, tuple)):
8843101Sstever@eecs.umich.edu            # Assign list of port refs to vector port.
8853101Sstever@eecs.umich.edu            # For now, append them... not sure if that's the right semantics
8863101Sstever@eecs.umich.edu            # or if it should replace the current vector.
8873101Sstever@eecs.umich.edu            for ref in other:
8883101Sstever@eecs.umich.edu                self._get_next().connect(ref)
8893101Sstever@eecs.umich.edu        else:
8903101Sstever@eecs.umich.edu            # scalar assignment to plain VectorPort is implicit append
8913101Sstever@eecs.umich.edu            self._get_next().connect(other)
8923101Sstever@eecs.umich.edu
8933101Sstever@eecs.umich.edu    def clone(self, simobj, memo):
8943101Sstever@eecs.umich.edu        if memo.has_key(self):
8959941SGeoffrey.Blake@arm.com            return memo[self]
8963101Sstever@eecs.umich.edu        newRef = copy.copy(self)
8973101Sstever@eecs.umich.edu        memo[self] = newRef
8983101Sstever@eecs.umich.edu        newRef.simobj = simobj
8993101Sstever@eecs.umich.edu        assert(isSimObject(newRef.simobj))
90010267SGeoffrey.Blake@arm.com        newRef.elements = [el.clone(simobj, memo) for el in self.elements]
90110267SGeoffrey.Blake@arm.com        return newRef
90210267SGeoffrey.Blake@arm.com
90310267SGeoffrey.Blake@arm.com    def unproxy(self, simobj):
9043101Sstever@eecs.umich.edu        [el.unproxy(simobj) for el in self.elements]
9053101Sstever@eecs.umich.edu
9064380Sbinkertn@umich.edu    def ccConnect(self):
9073101Sstever@eecs.umich.edu        [el.ccConnect() for el in self.elements]
9083101Sstever@eecs.umich.edu
9094762Snate@binkert.org# Port description object.  Like a ParamDesc object, this represents a
91011988Sandreas.sandberg@arm.com# logical port in the SimObject class, not a particular port on a
9114762Snate@binkert.org# SimObject instance.  The latter are represented by PortRef objects.
9124762Snate@binkert.orgclass Port(object):
91311228SAndrew.Bardsley@arm.com    # Port("description") or Port(default, "description")
91411228SAndrew.Bardsley@arm.com    def __init__(self, *args):
91511228SAndrew.Bardsley@arm.com        if len(args) == 1:
9164380Sbinkertn@umich.edu            self.desc = args[0]
9174380Sbinkertn@umich.edu        elif len(args) == 2:
9183101Sstever@eecs.umich.edu            self.default = args[0]
91910458Sandreas.hansson@arm.com            self.desc = args[1]
92010458Sandreas.hansson@arm.com        else:
92110458Sandreas.hansson@arm.com            raise TypeError, 'wrong number of arguments'
92210458Sandreas.hansson@arm.com        # self.name is set by SimObject class on assignment
92310458Sandreas.hansson@arm.com        # e.g., pio_port = Port("blah") sets self.name to 'pio_port'
9247777Sgblack@eecs.umich.edu
9257777Sgblack@eecs.umich.edu    # Generate a PortRef for this port on the given SimObject with the
9267777Sgblack@eecs.umich.edu    # given name
9277777Sgblack@eecs.umich.edu    def makeRef(self, simobj):
92810267SGeoffrey.Blake@arm.com        return PortRef(simobj, self.name)
92910267SGeoffrey.Blake@arm.com
9307777Sgblack@eecs.umich.edu    # Connect an instance of this port (on the given SimObject with
9317777Sgblack@eecs.umich.edu    # the given name) with the port described by the supplied PortRef
9327777Sgblack@eecs.umich.edu    def connect(self, simobj, ref):
9337777Sgblack@eecs.umich.edu        self.makeRef(simobj).connect(ref)
9347777Sgblack@eecs.umich.edu
9357777Sgblack@eecs.umich.edu# VectorPort description object.  Like Port, but represents a vector
9367777Sgblack@eecs.umich.edu# of connections (e.g., as on a Bus).
9377777Sgblack@eecs.umich.educlass VectorPort(Port):
9387777Sgblack@eecs.umich.edu    def __init__(self, *args):
9397777Sgblack@eecs.umich.edu        Port.__init__(self, *args)
9407777Sgblack@eecs.umich.edu        self.isVec = True
9417777Sgblack@eecs.umich.edu
9427777Sgblack@eecs.umich.edu    def makeRef(self, simobj):
9437777Sgblack@eecs.umich.edu        return VectorPortRef(simobj, self.name)
9447777Sgblack@eecs.umich.edu
94510267SGeoffrey.Blake@arm.com# 'Fake' ParamDesc for Port references to assign to the _pdesc slot of
94610267SGeoffrey.Blake@arm.com# proxy objects (via set_param_desc()) so that proxy error messages
94710267SGeoffrey.Blake@arm.com# make sense.
94810267SGeoffrey.Blake@arm.comclass PortParamDesc(object):
9498579Ssteve.reinhardt@amd.com    __metaclass__ = Singleton
9508579Ssteve.reinhardt@amd.com
9518579Ssteve.reinhardt@amd.com    ptype_str = 'Port'
9528579Ssteve.reinhardt@amd.com    ptype = Port
9538579Ssteve.reinhardt@amd.com
9548579Ssteve.reinhardt@amd.com
9558579Ssteve.reinhardt@amd.com__all__ = ['Param', 'VectorParam',
9568579Ssteve.reinhardt@amd.com           'Enum', 'Bool', 'String', 'Float',
9578579Ssteve.reinhardt@amd.com           'Int', 'Unsigned', 'Int8', 'UInt8', 'Int16', 'UInt16',
9588579Ssteve.reinhardt@amd.com           'Int32', 'UInt32', 'Int64', 'UInt64',
9598579Ssteve.reinhardt@amd.com           'Counter', 'Addr', 'Tick', 'Percent',
9608579Ssteve.reinhardt@amd.com           'TcpPort', 'UdpPort', 'EthernetAddr',
9618579Ssteve.reinhardt@amd.com           'MemorySize', 'MemorySize32',
9628579Ssteve.reinhardt@amd.com           'Latency', 'Frequency', 'RootClock', 'Clock',
9638579Ssteve.reinhardt@amd.com           'NetworkBandwidth', 'MemoryBandwidth',
9648579Ssteve.reinhardt@amd.com           'Range', 'AddrRange', 'TickRange',
9658579Ssteve.reinhardt@amd.com           'MaxAddr', 'MaxTick', 'AllMemory',
9668579Ssteve.reinhardt@amd.com           'NextEthernetAddr', 'NULL',
9677777Sgblack@eecs.umich.edu           'Port', 'VectorPort']
9687777Sgblack@eecs.umich.edu
9697798Sgblack@eecs.umich.edu# see comment on imports at end of __init__.py.
9707777Sgblack@eecs.umich.edufrom SimObject import isSimObject, isSimObjectSequence, isSimObjectClass
9717777Sgblack@eecs.umich.eduimport proxy
97211988Sandreas.sandberg@arm.comimport objects
9737777Sgblack@eecs.umich.eduimport cc_main
9747777Sgblack@eecs.umich.edu