SimObject.py revision 8321
1# Copyright (c) 2004-2006 The Regents of The University of Michigan
2# Copyright (c) 2010 Advanced Micro Devices, Inc.
3# All rights reserved.
4#
5# Redistribution and use in source and binary forms, with or without
6# modification, are permitted provided that the following conditions are
7# met: redistributions of source code must retain the above copyright
8# notice, this list of conditions and the following disclaimer;
9# redistributions in binary form must reproduce the above copyright
10# notice, this list of conditions and the following disclaimer in the
11# documentation and/or other materials provided with the distribution;
12# neither the name of the copyright holders nor the names of its
13# contributors may be used to endorse or promote products derived from
14# this software without specific prior written permission.
15#
16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27#
28# Authors: Steve Reinhardt
29#          Nathan Binkert
30
31import sys
32from types import FunctionType, MethodType
33
34try:
35    import pydot
36except:
37    pydot = False
38
39import m5
40from m5.util import *
41
42# Have to import params up top since Param is referenced on initial
43# load (when SimObject class references Param to create a class
44# variable, the 'name' param)...
45from m5.params import *
46# There are a few things we need that aren't in params.__all__ since
47# normal users don't need them
48from m5.params import ParamDesc, VectorParamDesc, \
49     isNullPointer, SimObjectVector
50
51from m5.proxy import *
52from m5.proxy import isproxy
53
54#####################################################################
55#
56# M5 Python Configuration Utility
57#
58# The basic idea is to write simple Python programs that build Python
59# objects corresponding to M5 SimObjects for the desired simulation
60# configuration.  For now, the Python emits a .ini file that can be
61# parsed by M5.  In the future, some tighter integration between M5
62# and the Python interpreter may allow bypassing the .ini file.
63#
64# Each SimObject class in M5 is represented by a Python class with the
65# same name.  The Python inheritance tree mirrors the M5 C++ tree
66# (e.g., SimpleCPU derives from BaseCPU in both cases, and all
67# SimObjects inherit from a single SimObject base class).  To specify
68# an instance of an M5 SimObject in a configuration, the user simply
69# instantiates the corresponding Python object.  The parameters for
70# that SimObject are given by assigning to attributes of the Python
71# object, either using keyword assignment in the constructor or in
72# separate assignment statements.  For example:
73#
74# cache = BaseCache(size='64KB')
75# cache.hit_latency = 3
76# cache.assoc = 8
77#
78# The magic lies in the mapping of the Python attributes for SimObject
79# classes to the actual SimObject parameter specifications.  This
80# allows parameter validity checking in the Python code.  Continuing
81# the example above, the statements "cache.blurfl=3" or
82# "cache.assoc='hello'" would both result in runtime errors in Python,
83# since the BaseCache object has no 'blurfl' parameter and the 'assoc'
84# parameter requires an integer, respectively.  This magic is done
85# primarily by overriding the special __setattr__ method that controls
86# assignment to object attributes.
87#
88# Once a set of Python objects have been instantiated in a hierarchy,
89# calling 'instantiate(obj)' (where obj is the root of the hierarchy)
90# will generate a .ini file.
91#
92#####################################################################
93
94# list of all SimObject classes
95allClasses = {}
96
97# dict to look up SimObjects based on path
98instanceDict = {}
99
100def default_cxx_predecls(cls, code):
101    code('#include "params/$cls.hh"')
102
103def default_swig_predecls(cls, code):
104    code('%import "python/m5/internal/param_$cls.i"')
105
106def default_swig_objdecls(cls, code):
107    class_path = cls.cxx_class.split('::')
108    classname = class_path[-1]
109    namespaces = class_path[:-1]
110
111    for ns in namespaces:
112        code('namespace $ns {')
113
114    if namespaces:
115        code('// avoid name conflicts')
116        sep_string = '_COLONS_'
117        flat_name = sep_string.join(class_path)
118        code('%rename($flat_name) $classname;')
119
120    code()
121    code('// stop swig from creating/wrapping default ctor/dtor')
122    code('%nodefault $classname;')
123    code('class $classname')
124    if cls._base:
125        code('    : public ${{cls._base.cxx_class}}')
126    code('{};')
127
128    for ns in reversed(namespaces):
129        code('} // namespace $ns')
130
131def public_value(key, value):
132    return key.startswith('_') or \
133               isinstance(value, (FunctionType, MethodType, classmethod, type))
134
135# The metaclass for SimObject.  This class controls how new classes
136# that derive from SimObject are instantiated, and provides inherited
137# class behavior (just like a class controls how instances of that
138# class are instantiated, and provides inherited instance behavior).
139class MetaSimObject(type):
140    # Attributes that can be set only at initialization time
141    init_keywords = { 'abstract' : bool,
142                      'cxx_class' : str,
143                      'cxx_type' : str,
144                      'cxx_predecls'  : MethodType,
145                      'swig_objdecls' : MethodType,
146                      'swig_predecls' : MethodType,
147                      'type' : str }
148    # Attributes that can be set any time
149    keywords = { 'check' : FunctionType }
150
151    # __new__ is called before __init__, and is where the statements
152    # in the body of the class definition get loaded into the class's
153    # __dict__.  We intercept this to filter out parameter & port assignments
154    # and only allow "private" attributes to be passed to the base
155    # __new__ (starting with underscore).
156    def __new__(mcls, name, bases, dict):
157        assert name not in allClasses, "SimObject %s already present" % name
158
159        # Copy "private" attributes, functions, and classes to the
160        # official dict.  Everything else goes in _init_dict to be
161        # filtered in __init__.
162        cls_dict = {}
163        value_dict = {}
164        for key,val in dict.items():
165            if public_value(key, val):
166                cls_dict[key] = val
167            else:
168                # must be a param/port setting
169                value_dict[key] = val
170        if 'abstract' not in value_dict:
171            value_dict['abstract'] = False
172        cls_dict['_value_dict'] = value_dict
173        cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
174        if 'type' in value_dict:
175            allClasses[name] = cls
176        return cls
177
178    # subclass initialization
179    def __init__(cls, name, bases, dict):
180        # calls type.__init__()... I think that's a no-op, but leave
181        # it here just in case it's not.
182        super(MetaSimObject, cls).__init__(name, bases, dict)
183
184        # initialize required attributes
185
186        # class-only attributes
187        cls._params = multidict() # param descriptions
188        cls._ports = multidict()  # port descriptions
189
190        # class or instance attributes
191        cls._values = multidict()   # param values
192        cls._children = multidict() # SimObject children
193        cls._port_refs = multidict() # port ref objects
194        cls._instantiated = False # really instantiated, cloned, or subclassed
195
196        # We don't support multiple inheritance.  If you want to, you
197        # must fix multidict to deal with it properly.
198        if len(bases) > 1:
199            raise TypeError, "SimObjects do not support multiple inheritance"
200
201        base = bases[0]
202
203        # Set up general inheritance via multidicts.  A subclass will
204        # inherit all its settings from the base class.  The only time
205        # the following is not true is when we define the SimObject
206        # class itself (in which case the multidicts have no parent).
207        if isinstance(base, MetaSimObject):
208            cls._base = base
209            cls._params.parent = base._params
210            cls._ports.parent = base._ports
211            cls._values.parent = base._values
212            cls._children.parent = base._children
213            cls._port_refs.parent = base._port_refs
214            # mark base as having been subclassed
215            base._instantiated = True
216        else:
217            cls._base = None
218
219        # default keyword values
220        if 'type' in cls._value_dict:
221            if 'cxx_class' not in cls._value_dict:
222                cls._value_dict['cxx_class'] = cls._value_dict['type']
223
224            cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class']
225
226            if 'cxx_predecls' not in cls.__dict__:
227                m = MethodType(default_cxx_predecls, cls, MetaSimObject)
228                setattr(cls, 'cxx_predecls', m)
229
230            if 'swig_predecls' not in cls.__dict__:
231                m = MethodType(default_swig_predecls, cls, MetaSimObject)
232                setattr(cls, 'swig_predecls', m)
233
234        if 'swig_objdecls' not in cls.__dict__:
235            m = MethodType(default_swig_objdecls, cls, MetaSimObject)
236            setattr(cls, 'swig_objdecls', m)
237
238        # Now process the _value_dict items.  They could be defining
239        # new (or overriding existing) parameters or ports, setting
240        # class keywords (e.g., 'abstract'), or setting parameter
241        # values or port bindings.  The first 3 can only be set when
242        # the class is defined, so we handle them here.  The others
243        # can be set later too, so just emulate that by calling
244        # setattr().
245        for key,val in cls._value_dict.items():
246            # param descriptions
247            if isinstance(val, ParamDesc):
248                cls._new_param(key, val)
249
250            # port objects
251            elif isinstance(val, Port):
252                cls._new_port(key, val)
253
254            # init-time-only keywords
255            elif cls.init_keywords.has_key(key):
256                cls._set_keyword(key, val, cls.init_keywords[key])
257
258            # default: use normal path (ends up in __setattr__)
259            else:
260                setattr(cls, key, val)
261
262    def _set_keyword(cls, keyword, val, kwtype):
263        if not isinstance(val, kwtype):
264            raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
265                  (keyword, type(val), kwtype)
266        if isinstance(val, FunctionType):
267            val = classmethod(val)
268        type.__setattr__(cls, keyword, val)
269
270    def _new_param(cls, name, pdesc):
271        # each param desc should be uniquely assigned to one variable
272        assert(not hasattr(pdesc, 'name'))
273        pdesc.name = name
274        cls._params[name] = pdesc
275        if hasattr(pdesc, 'default'):
276            cls._set_param(name, pdesc.default, pdesc)
277
278    def _set_param(cls, name, value, param):
279        assert(param.name == name)
280        try:
281            value = param.convert(value)
282        except Exception, e:
283            msg = "%s\nError setting param %s.%s to %s\n" % \
284                  (e, cls.__name__, name, value)
285            e.args = (msg, )
286            raise
287        cls._values[name] = value
288        # if param value is a SimObject, make it a child too, so that
289        # it gets cloned properly when the class is instantiated
290        if isSimObjectOrVector(value) and not value.has_parent():
291            cls._add_cls_child(name, value)
292
293    def _add_cls_child(cls, name, child):
294        # It's a little funky to have a class as a parent, but these
295        # objects should never be instantiated (only cloned, which
296        # clears the parent pointer), and this makes it clear that the
297        # object is not an orphan and can provide better error
298        # messages.
299        child.set_parent(cls, name)
300        cls._children[name] = child
301
302    def _new_port(cls, name, port):
303        # each port should be uniquely assigned to one variable
304        assert(not hasattr(port, 'name'))
305        port.name = name
306        cls._ports[name] = port
307        if hasattr(port, 'default'):
308            cls._cls_get_port_ref(name).connect(port.default)
309
310    # same as _get_port_ref, effectively, but for classes
311    def _cls_get_port_ref(cls, attr):
312        # Return reference that can be assigned to another port
313        # via __setattr__.  There is only ever one reference
314        # object per port, but we create them lazily here.
315        ref = cls._port_refs.get(attr)
316        if not ref:
317            ref = cls._ports[attr].makeRef(cls)
318            cls._port_refs[attr] = ref
319        return ref
320
321    # Set attribute (called on foo.attr = value when foo is an
322    # instance of class cls).
323    def __setattr__(cls, attr, value):
324        # normal processing for private attributes
325        if public_value(attr, value):
326            type.__setattr__(cls, attr, value)
327            return
328
329        if cls.keywords.has_key(attr):
330            cls._set_keyword(attr, value, cls.keywords[attr])
331            return
332
333        if cls._ports.has_key(attr):
334            cls._cls_get_port_ref(attr).connect(value)
335            return
336
337        if isSimObjectOrSequence(value) and cls._instantiated:
338            raise RuntimeError, \
339                  "cannot set SimObject parameter '%s' after\n" \
340                  "    class %s has been instantiated or subclassed" \
341                  % (attr, cls.__name__)
342
343        # check for param
344        param = cls._params.get(attr)
345        if param:
346            cls._set_param(attr, value, param)
347            return
348
349        if isSimObjectOrSequence(value):
350            # If RHS is a SimObject, it's an implicit child assignment.
351            cls._add_cls_child(attr, coerceSimObjectOrVector(value))
352            return
353
354        # no valid assignment... raise exception
355        raise AttributeError, \
356              "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
357
358    def __getattr__(cls, attr):
359        if attr == 'cxx_class_path':
360            return cls.cxx_class.split('::')
361
362        if attr == 'cxx_class_name':
363            return cls.cxx_class_path[-1]
364
365        if attr == 'cxx_namespaces':
366            return cls.cxx_class_path[:-1]
367
368        if cls._values.has_key(attr):
369            return cls._values[attr]
370
371        if cls._children.has_key(attr):
372            return cls._children[attr]
373
374        raise AttributeError, \
375              "object '%s' has no attribute '%s'" % (cls.__name__, attr)
376
377    def __str__(cls):
378        return cls.__name__
379
380    def cxx_decl(cls, code):
381        # The 'dict' attribute restricts us to the params declared in
382        # the object itself, not including inherited params (which
383        # will also be inherited from the base class's param struct
384        # here).
385        params = cls._params.local.values()
386        try:
387            ptypes = [p.ptype for p in params]
388        except:
389            print cls, p, p.ptype_str
390            print params
391            raise
392
393        class_path = cls._value_dict['cxx_class'].split('::')
394
395        code('''\
396#ifndef __PARAMS__${cls}__
397#define __PARAMS__${cls}__
398
399''')
400
401        # A forward class declaration is sufficient since we are just
402        # declaring a pointer.
403        for ns in class_path[:-1]:
404            code('namespace $ns {')
405        code('class $0;', class_path[-1])
406        for ns in reversed(class_path[:-1]):
407            code('} // namespace $ns')
408        code()
409
410        for param in params:
411            param.cxx_predecls(code)
412        code()
413
414        if cls._base:
415            code('#include "params/${{cls._base.type}}.hh"')
416            code()
417
418        for ptype in ptypes:
419            if issubclass(ptype, Enum):
420                code('#include "enums/${{ptype.__name__}}.hh"')
421                code()
422
423        cls.cxx_struct(code, cls._base, params)
424
425        code()
426        code('#endif // __PARAMS__${cls}__')
427        return code
428
429    def cxx_struct(cls, code, base, params):
430        if cls == SimObject:
431            code('#include "sim/sim_object_params.hh"')
432            return
433
434        # now generate the actual param struct
435        code("struct ${cls}Params")
436        if base:
437            code("    : public ${{base.type}}Params")
438        code("{")
439        if not hasattr(cls, 'abstract') or not cls.abstract:
440            if 'type' in cls.__dict__:
441                code("    ${{cls.cxx_type}} create();")
442
443        code.indent()
444        for param in params:
445            param.cxx_decl(code)
446        code.dedent()
447        code('};')
448
449    def swig_decl(cls, code):
450        code('''\
451%module $cls
452
453%{
454#include "params/$cls.hh"
455%}
456
457''')
458
459        # The 'dict' attribute restricts us to the params declared in
460        # the object itself, not including inherited params (which
461        # will also be inherited from the base class's param struct
462        # here).
463        params = cls._params.local.values()
464        ptypes = [p.ptype for p in params]
465
466        # get all predeclarations
467        for param in params:
468            param.swig_predecls(code)
469        code()
470
471        if cls._base:
472            code('%import "python/m5/internal/param_${{cls._base.type}}.i"')
473            code()
474
475        for ptype in ptypes:
476            if issubclass(ptype, Enum):
477                code('%import "enums/${{ptype.__name__}}.hh"')
478                code()
479
480        code('%import "params/${cls}_type.hh"')
481        code('%include "params/${cls}.hh"')
482
483# The SimObject class is the root of the special hierarchy.  Most of
484# the code in this class deals with the configuration hierarchy itself
485# (parent/child node relationships).
486class SimObject(object):
487    # Specify metaclass.  Any class inheriting from SimObject will
488    # get this metaclass.
489    __metaclass__ = MetaSimObject
490    type = 'SimObject'
491    abstract = True
492
493    @classmethod
494    def swig_objdecls(cls, code):
495        code('%include "python/swig/sim_object.i"')
496
497    # Initialize new instance.  For objects with SimObject-valued
498    # children, we need to recursively clone the classes represented
499    # by those param values as well in a consistent "deep copy"-style
500    # fashion.  That is, we want to make sure that each instance is
501    # cloned only once, and that if there are multiple references to
502    # the same original object, we end up with the corresponding
503    # cloned references all pointing to the same cloned instance.
504    def __init__(self, **kwargs):
505        ancestor = kwargs.get('_ancestor')
506        memo_dict = kwargs.get('_memo')
507        if memo_dict is None:
508            # prepare to memoize any recursively instantiated objects
509            memo_dict = {}
510        elif ancestor:
511            # memoize me now to avoid problems with recursive calls
512            memo_dict[ancestor] = self
513
514        if not ancestor:
515            ancestor = self.__class__
516        ancestor._instantiated = True
517
518        # initialize required attributes
519        self._parent = None
520        self._name = None
521        self._ccObject = None  # pointer to C++ object
522        self._ccParams = None
523        self._instantiated = False # really "cloned"
524
525        # Clone children specified at class level.  No need for a
526        # multidict here since we will be cloning everything.
527        # Do children before parameter values so that children that
528        # are also param values get cloned properly.
529        self._children = {}
530        for key,val in ancestor._children.iteritems():
531            self.add_child(key, val(_memo=memo_dict))
532
533        # Inherit parameter values from class using multidict so
534        # individual value settings can be overridden but we still
535        # inherit late changes to non-overridden class values.
536        self._values = multidict(ancestor._values)
537        # clone SimObject-valued parameters
538        for key,val in ancestor._values.iteritems():
539            val = tryAsSimObjectOrVector(val)
540            if val is not None:
541                self._values[key] = val(_memo=memo_dict)
542
543        # clone port references.  no need to use a multidict here
544        # since we will be creating new references for all ports.
545        self._port_refs = {}
546        for key,val in ancestor._port_refs.iteritems():
547            self._port_refs[key] = val.clone(self, memo_dict)
548        # apply attribute assignments from keyword args, if any
549        for key,val in kwargs.iteritems():
550            setattr(self, key, val)
551
552    # "Clone" the current instance by creating another instance of
553    # this instance's class, but that inherits its parameter values
554    # and port mappings from the current instance.  If we're in a
555    # "deep copy" recursive clone, check the _memo dict to see if
556    # we've already cloned this instance.
557    def __call__(self, **kwargs):
558        memo_dict = kwargs.get('_memo')
559        if memo_dict is None:
560            # no memo_dict: must be top-level clone operation.
561            # this is only allowed at the root of a hierarchy
562            if self._parent:
563                raise RuntimeError, "attempt to clone object %s " \
564                      "not at the root of a tree (parent = %s)" \
565                      % (self, self._parent)
566            # create a new dict and use that.
567            memo_dict = {}
568            kwargs['_memo'] = memo_dict
569        elif memo_dict.has_key(self):
570            # clone already done & memoized
571            return memo_dict[self]
572        return self.__class__(_ancestor = self, **kwargs)
573
574    def _get_port_ref(self, attr):
575        # Return reference that can be assigned to another port
576        # via __setattr__.  There is only ever one reference
577        # object per port, but we create them lazily here.
578        ref = self._port_refs.get(attr)
579        if not ref:
580            ref = self._ports[attr].makeRef(self)
581            self._port_refs[attr] = ref
582        return ref
583
584    def __getattr__(self, attr):
585        if self._ports.has_key(attr):
586            return self._get_port_ref(attr)
587
588        if self._values.has_key(attr):
589            return self._values[attr]
590
591        if self._children.has_key(attr):
592            return self._children[attr]
593
594        # If the attribute exists on the C++ object, transparently
595        # forward the reference there.  This is typically used for
596        # SWIG-wrapped methods such as init(), regStats(),
597        # regFormulas(), resetStats(), startup(), drain(), and
598        # resume().
599        if self._ccObject and hasattr(self._ccObject, attr):
600            return getattr(self._ccObject, attr)
601
602        raise AttributeError, "object '%s' has no attribute '%s'" \
603              % (self.__class__.__name__, attr)
604
605    # Set attribute (called on foo.attr = value when foo is an
606    # instance of class cls).
607    def __setattr__(self, attr, value):
608        # normal processing for private attributes
609        if attr.startswith('_'):
610            object.__setattr__(self, attr, value)
611            return
612
613        if self._ports.has_key(attr):
614            # set up port connection
615            self._get_port_ref(attr).connect(value)
616            return
617
618        if isSimObjectOrSequence(value) and self._instantiated:
619            raise RuntimeError, \
620                  "cannot set SimObject parameter '%s' after\n" \
621                  "    instance been cloned %s" % (attr, `self`)
622
623        param = self._params.get(attr)
624        if param:
625            try:
626                value = param.convert(value)
627            except Exception, e:
628                msg = "%s\nError setting param %s.%s to %s\n" % \
629                      (e, self.__class__.__name__, attr, value)
630                e.args = (msg, )
631                raise
632            self._values[attr] = value
633            # implicitly parent unparented objects assigned as params
634            if isSimObjectOrVector(value) and not value.has_parent():
635                self.add_child(attr, value)
636            return
637
638        # if RHS is a SimObject, it's an implicit child assignment
639        if isSimObjectOrSequence(value):
640            self.add_child(attr, value)
641            return
642
643        # no valid assignment... raise exception
644        raise AttributeError, "Class %s has no parameter %s" \
645              % (self.__class__.__name__, attr)
646
647
648    # this hack allows tacking a '[0]' onto parameters that may or may
649    # not be vectors, and always getting the first element (e.g. cpus)
650    def __getitem__(self, key):
651        if key == 0:
652            return self
653        raise TypeError, "Non-zero index '%s' to SimObject" % key
654
655    # Also implemented by SimObjectVector
656    def clear_parent(self, old_parent):
657        assert self._parent is old_parent
658        self._parent = None
659
660    # Also implemented by SimObjectVector
661    def set_parent(self, parent, name):
662        self._parent = parent
663        self._name = name
664
665    # Also implemented by SimObjectVector
666    def get_name(self):
667        return self._name
668
669    # Also implemented by SimObjectVector
670    def has_parent(self):
671        return self._parent is not None
672
673    # clear out child with given name. This code is not likely to be exercised.
674    # See comment in add_child.
675    def clear_child(self, name):
676        child = self._children[name]
677        child.clear_parent(self)
678        del self._children[name]
679
680    # Add a new child to this object.
681    def add_child(self, name, child):
682        child = coerceSimObjectOrVector(child)
683        if child.has_parent():
684            print "warning: add_child('%s'): child '%s' already has parent" % \
685                  (name, child.get_name())
686        if self._children.has_key(name):
687            # This code path had an undiscovered bug that would make it fail
688            # at runtime. It had been here for a long time and was only
689            # exposed by a buggy script. Changes here will probably not be
690            # exercised without specialized testing.
691            self.clear_child(name)
692        child.set_parent(self, name)
693        self._children[name] = child
694
695    # Take SimObject-valued parameters that haven't been explicitly
696    # assigned as children and make them children of the object that
697    # they were assigned to as a parameter value.  This guarantees
698    # that when we instantiate all the parameter objects we're still
699    # inside the configuration hierarchy.
700    def adoptOrphanParams(self):
701        for key,val in self._values.iteritems():
702            if not isSimObjectVector(val) and isSimObjectSequence(val):
703                # need to convert raw SimObject sequences to
704                # SimObjectVector class so we can call has_parent()
705                val = SimObjectVector(val)
706                self._values[key] = val
707            if isSimObjectOrVector(val) and not val.has_parent():
708                print "warning: %s adopting orphan SimObject param '%s'" \
709                      % (self, key)
710                self.add_child(key, val)
711
712    def path(self):
713        if not self._parent:
714            return '<orphan %s>' % self.__class__
715        ppath = self._parent.path()
716        if ppath == 'root':
717            return self._name
718        return ppath + "." + self._name
719
720    def __str__(self):
721        return self.path()
722
723    def ini_str(self):
724        return self.path()
725
726    def find_any(self, ptype):
727        if isinstance(self, ptype):
728            return self, True
729
730        found_obj = None
731        for child in self._children.itervalues():
732            if isinstance(child, ptype):
733                if found_obj != None and child != found_obj:
734                    raise AttributeError, \
735                          'parent.any matched more than one: %s %s' % \
736                          (found_obj.path, child.path)
737                found_obj = child
738        # search param space
739        for pname,pdesc in self._params.iteritems():
740            if issubclass(pdesc.ptype, ptype):
741                match_obj = self._values[pname]
742                if found_obj != None and found_obj != match_obj:
743                    raise AttributeError, \
744                          'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path)
745                found_obj = match_obj
746        return found_obj, found_obj != None
747
748    def unproxy(self, base):
749        return self
750
751    def unproxyParams(self):
752        for param in self._params.iterkeys():
753            value = self._values.get(param)
754            if value != None and isproxy(value):
755                try:
756                    value = value.unproxy(self)
757                except:
758                    print "Error in unproxying param '%s' of %s" % \
759                          (param, self.path())
760                    raise
761                setattr(self, param, value)
762
763        # Unproxy ports in sorted order so that 'append' operations on
764        # vector ports are done in a deterministic fashion.
765        port_names = self._ports.keys()
766        port_names.sort()
767        for port_name in port_names:
768            port = self._port_refs.get(port_name)
769            if port != None:
770                port.unproxy(self)
771
772    def print_ini(self, ini_file):
773        print >>ini_file, '[' + self.path() + ']'       # .ini section header
774
775        instanceDict[self.path()] = self
776
777        if hasattr(self, 'type'):
778            print >>ini_file, 'type=%s' % self.type
779
780        child_names = self._children.keys()
781        child_names.sort()
782        if len(child_names):
783            print >>ini_file, 'children=%s' % \
784                  ' '.join(self._children[n].get_name() for n in child_names)
785
786        param_names = self._params.keys()
787        param_names.sort()
788        for param in param_names:
789            value = self._values.get(param)
790            if value != None:
791                print >>ini_file, '%s=%s' % (param,
792                                             self._values[param].ini_str())
793
794        port_names = self._ports.keys()
795        port_names.sort()
796        for port_name in port_names:
797            port = self._port_refs.get(port_name, None)
798            if port != None:
799                print >>ini_file, '%s=%s' % (port_name, port.ini_str())
800
801        print >>ini_file        # blank line between objects
802
803    def getCCParams(self):
804        if self._ccParams:
805            return self._ccParams
806
807        cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type)
808        cc_params = cc_params_struct()
809        cc_params.pyobj = self
810        cc_params.name = str(self)
811
812        param_names = self._params.keys()
813        param_names.sort()
814        for param in param_names:
815            value = self._values.get(param)
816            if value is None:
817                fatal("%s.%s without default or user set value",
818                      self.path(), param)
819
820            value = value.getValue()
821            if isinstance(self._params[param], VectorParamDesc):
822                assert isinstance(value, list)
823                vec = getattr(cc_params, param)
824                assert not len(vec)
825                for v in value:
826                    vec.append(v)
827            else:
828                setattr(cc_params, param, value)
829
830        port_names = self._ports.keys()
831        port_names.sort()
832        for port_name in port_names:
833            port = self._port_refs.get(port_name, None)
834            if port != None:
835                setattr(cc_params, port_name, port)
836        self._ccParams = cc_params
837        return self._ccParams
838
839    # Get C++ object corresponding to this object, calling C++ if
840    # necessary to construct it.  Does *not* recursively create
841    # children.
842    def getCCObject(self):
843        if not self._ccObject:
844            # Make sure this object is in the configuration hierarchy
845            if not self._parent and not isRoot(self):
846                raise RuntimeError, "Attempt to instantiate orphan node"
847            # Cycles in the configuration hierarchy are not supported. This
848            # will catch the resulting recursion and stop.
849            self._ccObject = -1
850            params = self.getCCParams()
851            self._ccObject = params.create()
852        elif self._ccObject == -1:
853            raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
854                  % self.path()
855        return self._ccObject
856
857    def descendants(self):
858        yield self
859        for child in self._children.itervalues():
860            for obj in child.descendants():
861                yield obj
862
863    # Call C++ to create C++ object corresponding to this object
864    def createCCObject(self):
865        self.getCCParams()
866        self.getCCObject() # force creation
867
868    def getValue(self):
869        return self.getCCObject()
870
871    # Create C++ port connections corresponding to the connections in
872    # _port_refs
873    def connectPorts(self):
874        for portRef in self._port_refs.itervalues():
875            portRef.ccConnect()
876
877    def getMemoryMode(self):
878        if not isinstance(self, m5.objects.System):
879            return None
880
881        return self._ccObject.getMemoryMode()
882
883    def changeTiming(self, mode):
884        if isinstance(self, m5.objects.System):
885            # i don't know if there's a better way to do this - calling
886            # setMemoryMode directly from self._ccObject results in calling
887            # SimObject::setMemoryMode, not the System::setMemoryMode
888            self._ccObject.setMemoryMode(mode)
889
890    def takeOverFrom(self, old_cpu):
891        self._ccObject.takeOverFrom(old_cpu._ccObject)
892
893    # generate output file for 'dot' to display as a pretty graph.
894    # this code is currently broken.
895    def outputDot(self, dot):
896        label = "{%s|" % self.path
897        if isSimObject(self.realtype):
898            label +=  '%s|' % self.type
899
900        if self.children:
901            # instantiate children in same order they were added for
902            # backward compatibility (else we can end up with cpu1
903            # before cpu0).
904            for c in self.children:
905                dot.add_edge(pydot.Edge(self.path,c.path, style="bold"))
906
907        simobjs = []
908        for param in self.params:
909            try:
910                if param.value is None:
911                    raise AttributeError, 'Parameter with no value'
912
913                value = param.value
914                string = param.string(value)
915            except Exception, e:
916                msg = 'exception in %s:%s\n%s' % (self.name, param.name, e)
917                e.args = (msg, )
918                raise
919
920            if isSimObject(param.ptype) and string != "Null":
921                simobjs.append(string)
922            else:
923                label += '%s = %s\\n' % (param.name, string)
924
925        for so in simobjs:
926            label += "|<%s> %s" % (so, so)
927            dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so,
928                                    tailport="w"))
929        label += '}'
930        dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label))
931
932        # recursively dump out children
933        for c in self.children:
934            c.outputDot(dot)
935
936# Function to provide to C++ so it can look up instances based on paths
937def resolveSimObject(name):
938    obj = instanceDict[name]
939    return obj.getCCObject()
940
941def isSimObject(value):
942    return isinstance(value, SimObject)
943
944def isSimObjectClass(value):
945    return issubclass(value, SimObject)
946
947def isSimObjectVector(value):
948    return isinstance(value, SimObjectVector)
949
950def isSimObjectSequence(value):
951    if not isinstance(value, (list, tuple)) or len(value) == 0:
952        return False
953
954    for val in value:
955        if not isNullPointer(val) and not isSimObject(val):
956            return False
957
958    return True
959
960def isSimObjectOrSequence(value):
961    return isSimObject(value) or isSimObjectSequence(value)
962
963def isRoot(obj):
964    from m5.objects import Root
965    return obj and obj is Root.getInstance()
966
967def isSimObjectOrVector(value):
968    return isSimObject(value) or isSimObjectVector(value)
969
970def tryAsSimObjectOrVector(value):
971    if isSimObjectOrVector(value):
972        return value
973    if isSimObjectSequence(value):
974        return SimObjectVector(value)
975    return None
976
977def coerceSimObjectOrVector(value):
978    value = tryAsSimObjectOrVector(value)
979    if value is None:
980        raise TypeError, "SimObject or SimObjectVector expected"
981    return value
982
983baseClasses = allClasses.copy()
984baseInstances = instanceDict.copy()
985
986def clear():
987    global allClasses, instanceDict
988
989    allClasses = baseClasses.copy()
990    instanceDict = baseInstances.copy()
991
992# __all__ defines the list of symbols that get exported when
993# 'from config import *' is invoked.  Try to keep this reasonably
994# short to avoid polluting other namespaces.
995__all__ = [ 'SimObject' ]
996