SimObject.py revision 12199
1# Copyright (c) 2017 ARM Limited
2# All rights reserved.
3#
4# The license below extends only to copyright in the software and shall
5# not be construed as granting a license to any other intellectual
6# property including but not limited to intellectual property relating
7# to a hardware implementation of the functionality of the software
8# licensed hereunder.  You may use the software subject to the license
9# terms below provided that you ensure that this notice is replicated
10# unmodified and in its entirety in all distributions of the software,
11# modified or unmodified, in source code or in binary form.
12#
13# Copyright (c) 2004-2006 The Regents of The University of Michigan
14# Copyright (c) 2010-20013 Advanced Micro Devices, Inc.
15# Copyright (c) 2013 Mark D. Hill and David A. Wood
16# All rights reserved.
17#
18# Redistribution and use in source and binary forms, with or without
19# modification, are permitted provided that the following conditions are
20# met: redistributions of source code must retain the above copyright
21# notice, this list of conditions and the following disclaimer;
22# redistributions in binary form must reproduce the above copyright
23# notice, this list of conditions and the following disclaimer in the
24# documentation and/or other materials provided with the distribution;
25# neither the name of the copyright holders nor the names of its
26# contributors may be used to endorse or promote products derived from
27# this software without specific prior written permission.
28#
29# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
30# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
31# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
32# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
33# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
34# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
35# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
36# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
37# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
38# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
39# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40#
41# Authors: Steve Reinhardt
42#          Nathan Binkert
43#          Andreas Hansson
44#          Andreas Sandberg
45
46import sys
47from types import FunctionType, MethodType, ModuleType
48from functools import wraps
49import inspect
50
51import m5
52from m5.util import *
53from m5.util.pybind import *
54
55# Have to import params up top since Param is referenced on initial
56# load (when SimObject class references Param to create a class
57# variable, the 'name' param)...
58from m5.params import *
59# There are a few things we need that aren't in params.__all__ since
60# normal users don't need them
61from m5.params import ParamDesc, VectorParamDesc, \
62     isNullPointer, SimObjectVector, Port
63
64from m5.proxy import *
65from m5.proxy import isproxy
66
67#####################################################################
68#
69# M5 Python Configuration Utility
70#
71# The basic idea is to write simple Python programs that build Python
72# objects corresponding to M5 SimObjects for the desired simulation
73# configuration.  For now, the Python emits a .ini file that can be
74# parsed by M5.  In the future, some tighter integration between M5
75# and the Python interpreter may allow bypassing the .ini file.
76#
77# Each SimObject class in M5 is represented by a Python class with the
78# same name.  The Python inheritance tree mirrors the M5 C++ tree
79# (e.g., SimpleCPU derives from BaseCPU in both cases, and all
80# SimObjects inherit from a single SimObject base class).  To specify
81# an instance of an M5 SimObject in a configuration, the user simply
82# instantiates the corresponding Python object.  The parameters for
83# that SimObject are given by assigning to attributes of the Python
84# object, either using keyword assignment in the constructor or in
85# separate assignment statements.  For example:
86#
87# cache = BaseCache(size='64KB')
88# cache.hit_latency = 3
89# cache.assoc = 8
90#
91# The magic lies in the mapping of the Python attributes for SimObject
92# classes to the actual SimObject parameter specifications.  This
93# allows parameter validity checking in the Python code.  Continuing
94# the example above, the statements "cache.blurfl=3" or
95# "cache.assoc='hello'" would both result in runtime errors in Python,
96# since the BaseCache object has no 'blurfl' parameter and the 'assoc'
97# parameter requires an integer, respectively.  This magic is done
98# primarily by overriding the special __setattr__ method that controls
99# assignment to object attributes.
100#
101# Once a set of Python objects have been instantiated in a hierarchy,
102# calling 'instantiate(obj)' (where obj is the root of the hierarchy)
103# will generate a .ini file.
104#
105#####################################################################
106
107# list of all SimObject classes
108allClasses = {}
109
110# dict to look up SimObjects based on path
111instanceDict = {}
112
113# Did any of the SimObjects lack a header file?
114noCxxHeader = False
115
116def public_value(key, value):
117    return key.startswith('_') or \
118               isinstance(value, (FunctionType, MethodType, ModuleType,
119                                  classmethod, type))
120
121def createCxxConfigDirectoryEntryFile(code, name, simobj, is_header):
122    entry_class = 'CxxConfigDirectoryEntry_%s' % name
123    param_class = '%sCxxConfigParams' % name
124
125    code('#include "params/%s.hh"' % name)
126
127    if not is_header:
128        for param in simobj._params.values():
129            if isSimObjectClass(param.ptype):
130                code('#include "%s"' % param.ptype._value_dict['cxx_header'])
131                code('#include "params/%s.hh"' % param.ptype.__name__)
132            else:
133                param.ptype.cxx_ini_predecls(code)
134
135    if is_header:
136        member_prefix = ''
137        end_of_decl = ';'
138        code('#include "sim/cxx_config.hh"')
139        code()
140        code('class ${param_class} : public CxxConfigParams,'
141            ' public ${name}Params')
142        code('{')
143        code('  private:')
144        code.indent()
145        code('class DirectoryEntry : public CxxConfigDirectoryEntry')
146        code('{')
147        code('  public:')
148        code.indent()
149        code('DirectoryEntry();');
150        code()
151        code('CxxConfigParams *makeParamsObject() const')
152        code('{ return new ${param_class}; }')
153        code.dedent()
154        code('};')
155        code()
156        code.dedent()
157        code('  public:')
158        code.indent()
159    else:
160        member_prefix = '%s::' % param_class
161        end_of_decl = ''
162        code('#include "%s"' % simobj._value_dict['cxx_header'])
163        code('#include "base/str.hh"')
164        code('#include "cxx_config/${name}.hh"')
165
166        if simobj._ports.values() != []:
167            code('#include "mem/mem_object.hh"')
168            code('#include "mem/port.hh"')
169
170        code()
171        code('${member_prefix}DirectoryEntry::DirectoryEntry()');
172        code('{')
173
174        def cxx_bool(b):
175            return 'true' if b else 'false'
176
177        code.indent()
178        for param in simobj._params.values():
179            is_vector = isinstance(param, m5.params.VectorParamDesc)
180            is_simobj = issubclass(param.ptype, m5.SimObject.SimObject)
181
182            code('parameters["%s"] = new ParamDesc("%s", %s, %s);' %
183                (param.name, param.name, cxx_bool(is_vector),
184                cxx_bool(is_simobj)));
185
186        for port in simobj._ports.values():
187            is_vector = isinstance(port, m5.params.VectorPort)
188            is_master = port.role == 'MASTER'
189
190            code('ports["%s"] = new PortDesc("%s", %s, %s);' %
191                (port.name, port.name, cxx_bool(is_vector),
192                cxx_bool(is_master)))
193
194        code.dedent()
195        code('}')
196        code()
197
198    code('bool ${member_prefix}setSimObject(const std::string &name,')
199    code('    SimObject *simObject)${end_of_decl}')
200
201    if not is_header:
202        code('{')
203        code.indent()
204        code('bool ret = true;')
205        code()
206        code('if (false) {')
207        for param in simobj._params.values():
208            is_vector = isinstance(param, m5.params.VectorParamDesc)
209            is_simobj = issubclass(param.ptype, m5.SimObject.SimObject)
210
211            if is_simobj and not is_vector:
212                code('} else if (name == "${{param.name}}") {')
213                code.indent()
214                code('this->${{param.name}} = '
215                    'dynamic_cast<${{param.ptype.cxx_type}}>(simObject);')
216                code('if (simObject && !this->${{param.name}})')
217                code('   ret = false;')
218                code.dedent()
219        code('} else {')
220        code('    ret = false;')
221        code('}')
222        code()
223        code('return ret;')
224        code.dedent()
225        code('}')
226
227    code()
228    code('bool ${member_prefix}setSimObjectVector('
229        'const std::string &name,')
230    code('    const std::vector<SimObject *> &simObjects)${end_of_decl}')
231
232    if not is_header:
233        code('{')
234        code.indent()
235        code('bool ret = true;')
236        code()
237        code('if (false) {')
238        for param in simobj._params.values():
239            is_vector = isinstance(param, m5.params.VectorParamDesc)
240            is_simobj = issubclass(param.ptype, m5.SimObject.SimObject)
241
242            if is_simobj and is_vector:
243                code('} else if (name == "${{param.name}}") {')
244                code.indent()
245                code('this->${{param.name}}.clear();')
246                code('for (auto i = simObjects.begin(); '
247                    'ret && i != simObjects.end(); i ++)')
248                code('{')
249                code.indent()
250                code('${{param.ptype.cxx_type}} object = '
251                    'dynamic_cast<${{param.ptype.cxx_type}}>(*i);')
252                code('if (*i && !object)')
253                code('    ret = false;')
254                code('else')
255                code('    this->${{param.name}}.push_back(object);')
256                code.dedent()
257                code('}')
258                code.dedent()
259        code('} else {')
260        code('    ret = false;')
261        code('}')
262        code()
263        code('return ret;')
264        code.dedent()
265        code('}')
266
267    code()
268    code('void ${member_prefix}setName(const std::string &name_)'
269        '${end_of_decl}')
270
271    if not is_header:
272        code('{')
273        code.indent()
274        code('this->name = name_;')
275        code.dedent()
276        code('}')
277
278    if is_header:
279        code('const std::string &${member_prefix}getName()')
280        code('{ return this->name; }')
281
282    code()
283    code('bool ${member_prefix}setParam(const std::string &name,')
284    code('    const std::string &value, const Flags flags)${end_of_decl}')
285
286    if not is_header:
287        code('{')
288        code.indent()
289        code('bool ret = true;')
290        code()
291        code('if (false) {')
292        for param in simobj._params.values():
293            is_vector = isinstance(param, m5.params.VectorParamDesc)
294            is_simobj = issubclass(param.ptype, m5.SimObject.SimObject)
295
296            if not is_simobj and not is_vector:
297                code('} else if (name == "${{param.name}}") {')
298                code.indent()
299                param.ptype.cxx_ini_parse(code,
300                    'value', 'this->%s' % param.name, 'ret =')
301                code.dedent()
302        code('} else {')
303        code('    ret = false;')
304        code('}')
305        code()
306        code('return ret;')
307        code.dedent()
308        code('}')
309
310    code()
311    code('bool ${member_prefix}setParamVector('
312        'const std::string &name,')
313    code('    const std::vector<std::string> &values,')
314    code('    const Flags flags)${end_of_decl}')
315
316    if not is_header:
317        code('{')
318        code.indent()
319        code('bool ret = true;')
320        code()
321        code('if (false) {')
322        for param in simobj._params.values():
323            is_vector = isinstance(param, m5.params.VectorParamDesc)
324            is_simobj = issubclass(param.ptype, m5.SimObject.SimObject)
325
326            if not is_simobj and is_vector:
327                code('} else if (name == "${{param.name}}") {')
328                code.indent()
329                code('${{param.name}}.clear();')
330                code('for (auto i = values.begin(); '
331                    'ret && i != values.end(); i ++)')
332                code('{')
333                code.indent()
334                code('${{param.ptype.cxx_type}} elem;')
335                param.ptype.cxx_ini_parse(code,
336                    '*i', 'elem', 'ret =')
337                code('if (ret)')
338                code('    this->${{param.name}}.push_back(elem);')
339                code.dedent()
340                code('}')
341                code.dedent()
342        code('} else {')
343        code('    ret = false;')
344        code('}')
345        code()
346        code('return ret;')
347        code.dedent()
348        code('}')
349
350    code()
351    code('bool ${member_prefix}setPortConnectionCount('
352        'const std::string &name,')
353    code('    unsigned int count)${end_of_decl}')
354
355    if not is_header:
356        code('{')
357        code.indent()
358        code('bool ret = true;')
359        code()
360        code('if (false)')
361        code('    ;')
362        for port in simobj._ports.values():
363            code('else if (name == "${{port.name}}")')
364            code('    this->port_${{port.name}}_connection_count = count;')
365        code('else')
366        code('    ret = false;')
367        code()
368        code('return ret;')
369        code.dedent()
370        code('}')
371
372    code()
373    code('SimObject *${member_prefix}simObjectCreate()${end_of_decl}')
374
375    if not is_header:
376        code('{')
377        if hasattr(simobj, 'abstract') and simobj.abstract:
378            code('    return NULL;')
379        else:
380            code('    return this->create();')
381        code('}')
382
383    if is_header:
384        code()
385        code('static CxxConfigDirectoryEntry'
386            ' *${member_prefix}makeDirectoryEntry()')
387        code('{ return new DirectoryEntry; }')
388
389    if is_header:
390        code.dedent()
391        code('};')
392
393# The metaclass for SimObject.  This class controls how new classes
394# that derive from SimObject are instantiated, and provides inherited
395# class behavior (just like a class controls how instances of that
396# class are instantiated, and provides inherited instance behavior).
397class MetaSimObject(type):
398    # Attributes that can be set only at initialization time
399    init_keywords = {
400        'abstract' : bool,
401        'cxx_class' : str,
402        'cxx_type' : str,
403        'cxx_header' : str,
404        'type' : str,
405        'cxx_bases' : list,
406        'cxx_exports' : list,
407        'cxx_param_exports' : list,
408    }
409    # Attributes that can be set any time
410    keywords = { 'check' : FunctionType }
411
412    # __new__ is called before __init__, and is where the statements
413    # in the body of the class definition get loaded into the class's
414    # __dict__.  We intercept this to filter out parameter & port assignments
415    # and only allow "private" attributes to be passed to the base
416    # __new__ (starting with underscore).
417    def __new__(mcls, name, bases, dict):
418        assert name not in allClasses, "SimObject %s already present" % name
419
420        # Copy "private" attributes, functions, and classes to the
421        # official dict.  Everything else goes in _init_dict to be
422        # filtered in __init__.
423        cls_dict = {}
424        value_dict = {}
425        cxx_exports = []
426        for key,val in dict.items():
427            try:
428                cxx_exports.append(getattr(val, "__pybind"))
429            except AttributeError:
430                pass
431
432            if public_value(key, val):
433                cls_dict[key] = val
434            else:
435                # must be a param/port setting
436                value_dict[key] = val
437        if 'abstract' not in value_dict:
438            value_dict['abstract'] = False
439        if 'cxx_bases' not in value_dict:
440            value_dict['cxx_bases'] = []
441        if 'cxx_exports' not in value_dict:
442            value_dict['cxx_exports'] = cxx_exports
443        else:
444            value_dict['cxx_exports'] += cxx_exports
445        if 'cxx_param_exports' not in value_dict:
446            value_dict['cxx_param_exports'] = []
447        cls_dict['_value_dict'] = value_dict
448        cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict)
449        if 'type' in value_dict:
450            allClasses[name] = cls
451        return cls
452
453    # subclass initialization
454    def __init__(cls, name, bases, dict):
455        # calls type.__init__()... I think that's a no-op, but leave
456        # it here just in case it's not.
457        super(MetaSimObject, cls).__init__(name, bases, dict)
458
459        # initialize required attributes
460
461        # class-only attributes
462        cls._params = multidict() # param descriptions
463        cls._ports = multidict()  # port descriptions
464
465        # class or instance attributes
466        cls._values = multidict()   # param values
467        cls._hr_values = multidict() # human readable param values
468        cls._children = multidict() # SimObject children
469        cls._port_refs = multidict() # port ref objects
470        cls._instantiated = False # really instantiated, cloned, or subclassed
471
472        # We don't support multiple inheritance of sim objects.  If you want
473        # to, you must fix multidict to deal with it properly. Non sim-objects
474        # are ok, though
475        bTotal = 0
476        for c in bases:
477            if isinstance(c, MetaSimObject):
478                bTotal += 1
479            if bTotal > 1:
480                raise TypeError, \
481                      "SimObjects do not support multiple inheritance"
482
483        base = bases[0]
484
485        # Set up general inheritance via multidicts.  A subclass will
486        # inherit all its settings from the base class.  The only time
487        # the following is not true is when we define the SimObject
488        # class itself (in which case the multidicts have no parent).
489        if isinstance(base, MetaSimObject):
490            cls._base = base
491            cls._params.parent = base._params
492            cls._ports.parent = base._ports
493            cls._values.parent = base._values
494            cls._hr_values.parent = base._hr_values
495            cls._children.parent = base._children
496            cls._port_refs.parent = base._port_refs
497            # mark base as having been subclassed
498            base._instantiated = True
499        else:
500            cls._base = None
501
502        # default keyword values
503        if 'type' in cls._value_dict:
504            if 'cxx_class' not in cls._value_dict:
505                cls._value_dict['cxx_class'] = cls._value_dict['type']
506
507            cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class']
508
509            if 'cxx_header' not in cls._value_dict:
510                global noCxxHeader
511                noCxxHeader = True
512                warn("No header file specified for SimObject: %s", name)
513
514        # Now process the _value_dict items.  They could be defining
515        # new (or overriding existing) parameters or ports, setting
516        # class keywords (e.g., 'abstract'), or setting parameter
517        # values or port bindings.  The first 3 can only be set when
518        # the class is defined, so we handle them here.  The others
519        # can be set later too, so just emulate that by calling
520        # setattr().
521        for key,val in cls._value_dict.items():
522            # param descriptions
523            if isinstance(val, ParamDesc):
524                cls._new_param(key, val)
525
526            # port objects
527            elif isinstance(val, Port):
528                cls._new_port(key, val)
529
530            # init-time-only keywords
531            elif cls.init_keywords.has_key(key):
532                cls._set_keyword(key, val, cls.init_keywords[key])
533
534            # default: use normal path (ends up in __setattr__)
535            else:
536                setattr(cls, key, val)
537
538    def _set_keyword(cls, keyword, val, kwtype):
539        if not isinstance(val, kwtype):
540            raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
541                  (keyword, type(val), kwtype)
542        if isinstance(val, FunctionType):
543            val = classmethod(val)
544        type.__setattr__(cls, keyword, val)
545
546    def _new_param(cls, name, pdesc):
547        # each param desc should be uniquely assigned to one variable
548        assert(not hasattr(pdesc, 'name'))
549        pdesc.name = name
550        cls._params[name] = pdesc
551        if hasattr(pdesc, 'default'):
552            cls._set_param(name, pdesc.default, pdesc)
553
554    def _set_param(cls, name, value, param):
555        assert(param.name == name)
556        try:
557            hr_value = value
558            value = param.convert(value)
559        except Exception, e:
560            msg = "%s\nError setting param %s.%s to %s\n" % \
561                  (e, cls.__name__, name, value)
562            e.args = (msg, )
563            raise
564        cls._values[name] = value
565        # if param value is a SimObject, make it a child too, so that
566        # it gets cloned properly when the class is instantiated
567        if isSimObjectOrVector(value) and not value.has_parent():
568            cls._add_cls_child(name, value)
569        # update human-readable values of the param if it has a literal
570        # value and is not an object or proxy.
571        if not (isSimObjectOrVector(value) or\
572                isinstance(value, m5.proxy.BaseProxy)):
573            cls._hr_values[name] = hr_value
574
575    def _add_cls_child(cls, name, child):
576        # It's a little funky to have a class as a parent, but these
577        # objects should never be instantiated (only cloned, which
578        # clears the parent pointer), and this makes it clear that the
579        # object is not an orphan and can provide better error
580        # messages.
581        child.set_parent(cls, name)
582        if not isNullPointer(child):
583            cls._children[name] = child
584
585    def _new_port(cls, name, port):
586        # each port should be uniquely assigned to one variable
587        assert(not hasattr(port, 'name'))
588        port.name = name
589        cls._ports[name] = port
590
591    # same as _get_port_ref, effectively, but for classes
592    def _cls_get_port_ref(cls, attr):
593        # Return reference that can be assigned to another port
594        # via __setattr__.  There is only ever one reference
595        # object per port, but we create them lazily here.
596        ref = cls._port_refs.get(attr)
597        if not ref:
598            ref = cls._ports[attr].makeRef(cls)
599            cls._port_refs[attr] = ref
600        return ref
601
602    # Set attribute (called on foo.attr = value when foo is an
603    # instance of class cls).
604    def __setattr__(cls, attr, value):
605        # normal processing for private attributes
606        if public_value(attr, value):
607            type.__setattr__(cls, attr, value)
608            return
609
610        if cls.keywords.has_key(attr):
611            cls._set_keyword(attr, value, cls.keywords[attr])
612            return
613
614        if cls._ports.has_key(attr):
615            cls._cls_get_port_ref(attr).connect(value)
616            return
617
618        if isSimObjectOrSequence(value) and cls._instantiated:
619            raise RuntimeError, \
620                  "cannot set SimObject parameter '%s' after\n" \
621                  "    class %s has been instantiated or subclassed" \
622                  % (attr, cls.__name__)
623
624        # check for param
625        param = cls._params.get(attr)
626        if param:
627            cls._set_param(attr, value, param)
628            return
629
630        if isSimObjectOrSequence(value):
631            # If RHS is a SimObject, it's an implicit child assignment.
632            cls._add_cls_child(attr, coerceSimObjectOrVector(value))
633            return
634
635        # no valid assignment... raise exception
636        raise AttributeError, \
637              "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
638
639    def __getattr__(cls, attr):
640        if attr == 'cxx_class_path':
641            return cls.cxx_class.split('::')
642
643        if attr == 'cxx_class_name':
644            return cls.cxx_class_path[-1]
645
646        if attr == 'cxx_namespaces':
647            return cls.cxx_class_path[:-1]
648
649        if cls._values.has_key(attr):
650            return cls._values[attr]
651
652        if cls._children.has_key(attr):
653            return cls._children[attr]
654
655        raise AttributeError, \
656              "object '%s' has no attribute '%s'" % (cls.__name__, attr)
657
658    def __str__(cls):
659        return cls.__name__
660
661    # See ParamValue.cxx_predecls for description.
662    def cxx_predecls(cls, code):
663        code('#include "params/$cls.hh"')
664
665    def pybind_predecls(cls, code):
666        code('#include "${{cls.cxx_header}}"')
667
668    def pybind_decl(cls, code):
669        class_path = cls.cxx_class.split('::')
670        namespaces, classname = class_path[:-1], class_path[-1]
671        py_class_name = '_COLONS_'.join(class_path) if namespaces else \
672                        classname;
673
674        # The 'local' attribute restricts us to the params declared in
675        # the object itself, not including inherited params (which
676        # will also be inherited from the base class's param struct
677        # here). Sort the params based on their key
678        params = map(lambda (k, v): v, sorted(cls._params.local.items()))
679        ports = cls._ports.local
680
681        code('''#include "pybind11/pybind11.h"
682#include "pybind11/stl.h"
683
684#include "params/$cls.hh"
685#include "python/pybind11/core.hh"
686#include "sim/init.hh"
687#include "sim/sim_object.hh"
688
689#include "${{cls.cxx_header}}"
690
691''')
692
693        for param in params:
694            param.pybind_predecls(code)
695
696        code('''namespace py = pybind11;
697
698static void
699module_init(py::module &m_internal)
700{
701    py::module m = m_internal.def_submodule("param_${cls}");
702''')
703        code.indent()
704        if cls._base:
705            code('py::class_<${cls}Params, ${{cls._base.type}}Params, ' \
706                 'std::unique_ptr<${{cls}}Params, py::nodelete>>(' \
707                 'm, "${cls}Params")')
708        else:
709            code('py::class_<${cls}Params, ' \
710                 'std::unique_ptr<${cls}Params, py::nodelete>>(' \
711                 'm, "${cls}Params")')
712
713        code.indent()
714        if not hasattr(cls, 'abstract') or not cls.abstract:
715            code('.def(py::init<>())')
716            code('.def("create", &${cls}Params::create)')
717
718        param_exports = cls.cxx_param_exports + [
719            PyBindProperty(k)
720            for k, v in sorted(cls._params.local.items())
721        ] + [
722            PyBindProperty("port_%s_connection_count" % port.name)
723            for port in ports.itervalues()
724        ]
725        for exp in param_exports:
726            exp.export(code, "%sParams" % cls)
727
728        code(';')
729        code()
730        code.dedent()
731
732        bases = [ cls._base.cxx_class ] + cls.cxx_bases if cls._base else \
733                cls.cxx_bases
734        if bases:
735            base_str = ", ".join(bases)
736            code('py::class_<${{cls.cxx_class}}, ${base_str}, ' \
737                 'std::unique_ptr<${{cls.cxx_class}}, py::nodelete>>(' \
738                 'm, "${py_class_name}")')
739        else:
740            code('py::class_<${{cls.cxx_class}}, ' \
741                 'std::unique_ptr<${{cls.cxx_class}}, py::nodelete>>(' \
742                 'm, "${py_class_name}")')
743        code.indent()
744        for exp in cls.cxx_exports:
745            exp.export(code, cls.cxx_class)
746        code(';')
747        code.dedent()
748        code()
749        code.dedent()
750        code('}')
751        code()
752        code('static EmbeddedPyBind embed_obj("${0}", module_init, "${1}");',
753             cls, cls._base.type if cls._base else "")
754
755
756    # Generate the C++ declaration (.hh file) for this SimObject's
757    # param struct.  Called from src/SConscript.
758    def cxx_param_decl(cls, code):
759        # The 'local' attribute restricts us to the params declared in
760        # the object itself, not including inherited params (which
761        # will also be inherited from the base class's param struct
762        # here). Sort the params based on their key
763        params = map(lambda (k, v): v, sorted(cls._params.local.items()))
764        ports = cls._ports.local
765        try:
766            ptypes = [p.ptype for p in params]
767        except:
768            print cls, p, p.ptype_str
769            print params
770            raise
771
772        class_path = cls._value_dict['cxx_class'].split('::')
773
774        code('''\
775#ifndef __PARAMS__${cls}__
776#define __PARAMS__${cls}__
777
778''')
779
780
781        # The base SimObject has a couple of params that get
782        # automatically set from Python without being declared through
783        # the normal Param mechanism; we slip them in here (needed
784        # predecls now, actual declarations below)
785        if cls == SimObject:
786            code('''#include <string>''')
787
788        # A forward class declaration is sufficient since we are just
789        # declaring a pointer.
790        for ns in class_path[:-1]:
791            code('namespace $ns {')
792        code('class $0;', class_path[-1])
793        for ns in reversed(class_path[:-1]):
794            code('} // namespace $ns')
795        code()
796
797        for param in params:
798            param.cxx_predecls(code)
799        for port in ports.itervalues():
800            port.cxx_predecls(code)
801        code()
802
803        if cls._base:
804            code('#include "params/${{cls._base.type}}.hh"')
805            code()
806
807        for ptype in ptypes:
808            if issubclass(ptype, Enum):
809                code('#include "enums/${{ptype.__name__}}.hh"')
810                code()
811
812        # now generate the actual param struct
813        code("struct ${cls}Params")
814        if cls._base:
815            code("    : public ${{cls._base.type}}Params")
816        code("{")
817        if not hasattr(cls, 'abstract') or not cls.abstract:
818            if 'type' in cls.__dict__:
819                code("    ${{cls.cxx_type}} create();")
820
821        code.indent()
822        if cls == SimObject:
823            code('''
824    SimObjectParams() {}
825    virtual ~SimObjectParams() {}
826
827    std::string name;
828            ''')
829
830        for param in params:
831            param.cxx_decl(code)
832        for port in ports.itervalues():
833            port.cxx_decl(code)
834
835        code.dedent()
836        code('};')
837
838        code()
839        code('#endif // __PARAMS__${cls}__')
840        return code
841
842    # Generate the C++ declaration/definition files for this SimObject's
843    # param struct to allow C++ initialisation
844    def cxx_config_param_file(cls, code, is_header):
845        createCxxConfigDirectoryEntryFile(code, cls.__name__, cls, is_header)
846        return code
847
848# This *temporary* definition is required to support calls from the
849# SimObject class definition to the MetaSimObject methods (in
850# particular _set_param, which gets called for parameters with default
851# values defined on the SimObject class itself).  It will get
852# overridden by the permanent definition (which requires that
853# SimObject be defined) lower in this file.
854def isSimObjectOrVector(value):
855    return False
856
857def cxxMethod(*args, **kwargs):
858    """Decorator to export C++ functions to Python"""
859
860    def decorate(func):
861        name = func.func_name
862        override = kwargs.get("override", False)
863        cxx_name = kwargs.get("cxx_name", name)
864
865        args, varargs, keywords, defaults = inspect.getargspec(func)
866        if varargs or keywords:
867            raise ValueError("Wrapped methods must not contain variable " \
868                             "arguments")
869
870        # Create tuples of (argument, default)
871        if defaults:
872            args = args[:-len(defaults)] + zip(args[-len(defaults):], defaults)
873        # Don't include self in the argument list to PyBind
874        args = args[1:]
875
876
877        @wraps(func)
878        def cxx_call(self, *args, **kwargs):
879            ccobj = self.getCCObject()
880            return getattr(ccobj, name)(*args, **kwargs)
881
882        @wraps(func)
883        def py_call(self, *args, **kwargs):
884            return self.func(*args, **kwargs)
885
886        f = py_call if override else cxx_call
887        f.__pybind = PyBindMethod(name, cxx_name=cxx_name, args=args)
888
889        return f
890
891    if len(args) == 0:
892        return decorate
893    elif len(args) == 1 and len(kwargs) == 0:
894        return decorate(*args)
895    else:
896        raise TypeError("One argument and no kwargs, or only kwargs expected")
897
898# This class holds information about each simobject parameter
899# that should be displayed on the command line for use in the
900# configuration system.
901class ParamInfo(object):
902  def __init__(self, type, desc, type_str, example, default_val, access_str):
903    self.type = type
904    self.desc = desc
905    self.type_str = type_str
906    self.example_str = example
907    self.default_val = default_val
908    # The string representation used to access this param through python.
909    # The method to access this parameter presented on the command line may
910    # be different, so this needs to be stored for later use.
911    self.access_str = access_str
912    self.created = True
913
914  # Make it so we can only set attributes at initialization time
915  # and effectively make this a const object.
916  def __setattr__(self, name, value):
917    if not "created" in self.__dict__:
918      self.__dict__[name] = value
919
920# The SimObject class is the root of the special hierarchy.  Most of
921# the code in this class deals with the configuration hierarchy itself
922# (parent/child node relationships).
923class SimObject(object):
924    # Specify metaclass.  Any class inheriting from SimObject will
925    # get this metaclass.
926    __metaclass__ = MetaSimObject
927    type = 'SimObject'
928    abstract = True
929
930    cxx_header = "sim/sim_object.hh"
931    cxx_bases = [ "Drainable", "Serializable" ]
932    eventq_index = Param.UInt32(Parent.eventq_index, "Event Queue Index")
933
934    cxx_exports = [
935        PyBindMethod("init"),
936        PyBindMethod("initState"),
937        PyBindMethod("memInvalidate"),
938        PyBindMethod("memWriteback"),
939        PyBindMethod("regStats"),
940        PyBindMethod("resetStats"),
941        PyBindMethod("regProbePoints"),
942        PyBindMethod("regProbeListeners"),
943        PyBindMethod("startup"),
944    ]
945
946    cxx_param_exports = [
947        PyBindProperty("name"),
948    ]
949
950    @cxxMethod
951    def loadState(self, cp):
952        """Load SimObject state from a checkpoint"""
953        pass
954
955    # Returns a dict of all the option strings that can be
956    # generated as command line options for this simobject instance
957    # by tracing all reachable params in the top level instance and
958    # any children it contains.
959    def enumerateParams(self, flags_dict = {},
960                        cmd_line_str = "", access_str = ""):
961        if hasattr(self, "_paramEnumed"):
962            print "Cycle detected enumerating params"
963        else:
964            self._paramEnumed = True
965            # Scan the children first to pick up all the objects in this SimObj
966            for keys in self._children:
967                child = self._children[keys]
968                next_cmdline_str = cmd_line_str + keys
969                next_access_str = access_str + keys
970                if not isSimObjectVector(child):
971                    next_cmdline_str = next_cmdline_str + "."
972                    next_access_str = next_access_str + "."
973                flags_dict = child.enumerateParams(flags_dict,
974                                                   next_cmdline_str,
975                                                   next_access_str)
976
977            # Go through the simple params in the simobject in this level
978            # of the simobject hierarchy and save information about the
979            # parameter to be used for generating and processing command line
980            # options to the simulator to set these parameters.
981            for keys,values in self._params.items():
982                if values.isCmdLineSettable():
983                    type_str = ''
984                    ex_str = values.example_str()
985                    ptype = None
986                    if isinstance(values, VectorParamDesc):
987                        type_str = 'Vector_%s' % values.ptype_str
988                        ptype = values
989                    else:
990                        type_str = '%s' % values.ptype_str
991                        ptype = values.ptype
992
993                    if keys in self._hr_values\
994                       and keys in self._values\
995                       and not isinstance(self._values[keys],
996                                          m5.proxy.BaseProxy):
997                        cmd_str = cmd_line_str + keys
998                        acc_str = access_str + keys
999                        flags_dict[cmd_str] = ParamInfo(ptype,
1000                                    self._params[keys].desc, type_str, ex_str,
1001                                    values.pretty_print(self._hr_values[keys]),
1002                                    acc_str)
1003                    elif not keys in self._hr_values\
1004                         and not keys in self._values:
1005                        # Empty param
1006                        cmd_str = cmd_line_str + keys
1007                        acc_str = access_str + keys
1008                        flags_dict[cmd_str] = ParamInfo(ptype,
1009                                    self._params[keys].desc,
1010                                    type_str, ex_str, '', acc_str)
1011
1012        return flags_dict
1013
1014    # Initialize new instance.  For objects with SimObject-valued
1015    # children, we need to recursively clone the classes represented
1016    # by those param values as well in a consistent "deep copy"-style
1017    # fashion.  That is, we want to make sure that each instance is
1018    # cloned only once, and that if there are multiple references to
1019    # the same original object, we end up with the corresponding
1020    # cloned references all pointing to the same cloned instance.
1021    def __init__(self, **kwargs):
1022        ancestor = kwargs.get('_ancestor')
1023        memo_dict = kwargs.get('_memo')
1024        if memo_dict is None:
1025            # prepare to memoize any recursively instantiated objects
1026            memo_dict = {}
1027        elif ancestor:
1028            # memoize me now to avoid problems with recursive calls
1029            memo_dict[ancestor] = self
1030
1031        if not ancestor:
1032            ancestor = self.__class__
1033        ancestor._instantiated = True
1034
1035        # initialize required attributes
1036        self._parent = None
1037        self._name = None
1038        self._ccObject = None  # pointer to C++ object
1039        self._ccParams = None
1040        self._instantiated = False # really "cloned"
1041
1042        # Clone children specified at class level.  No need for a
1043        # multidict here since we will be cloning everything.
1044        # Do children before parameter values so that children that
1045        # are also param values get cloned properly.
1046        self._children = {}
1047        for key,val in ancestor._children.iteritems():
1048            self.add_child(key, val(_memo=memo_dict))
1049
1050        # Inherit parameter values from class using multidict so
1051        # individual value settings can be overridden but we still
1052        # inherit late changes to non-overridden class values.
1053        self._values = multidict(ancestor._values)
1054        self._hr_values = multidict(ancestor._hr_values)
1055        # clone SimObject-valued parameters
1056        for key,val in ancestor._values.iteritems():
1057            val = tryAsSimObjectOrVector(val)
1058            if val is not None:
1059                self._values[key] = val(_memo=memo_dict)
1060
1061        # clone port references.  no need to use a multidict here
1062        # since we will be creating new references for all ports.
1063        self._port_refs = {}
1064        for key,val in ancestor._port_refs.iteritems():
1065            self._port_refs[key] = val.clone(self, memo_dict)
1066        # apply attribute assignments from keyword args, if any
1067        for key,val in kwargs.iteritems():
1068            setattr(self, key, val)
1069
1070    # "Clone" the current instance by creating another instance of
1071    # this instance's class, but that inherits its parameter values
1072    # and port mappings from the current instance.  If we're in a
1073    # "deep copy" recursive clone, check the _memo dict to see if
1074    # we've already cloned this instance.
1075    def __call__(self, **kwargs):
1076        memo_dict = kwargs.get('_memo')
1077        if memo_dict is None:
1078            # no memo_dict: must be top-level clone operation.
1079            # this is only allowed at the root of a hierarchy
1080            if self._parent:
1081                raise RuntimeError, "attempt to clone object %s " \
1082                      "not at the root of a tree (parent = %s)" \
1083                      % (self, self._parent)
1084            # create a new dict and use that.
1085            memo_dict = {}
1086            kwargs['_memo'] = memo_dict
1087        elif memo_dict.has_key(self):
1088            # clone already done & memoized
1089            return memo_dict[self]
1090        return self.__class__(_ancestor = self, **kwargs)
1091
1092    def _get_port_ref(self, attr):
1093        # Return reference that can be assigned to another port
1094        # via __setattr__.  There is only ever one reference
1095        # object per port, but we create them lazily here.
1096        ref = self._port_refs.get(attr)
1097        if ref == None:
1098            ref = self._ports[attr].makeRef(self)
1099            self._port_refs[attr] = ref
1100        return ref
1101
1102    def __getattr__(self, attr):
1103        if self._ports.has_key(attr):
1104            return self._get_port_ref(attr)
1105
1106        if self._values.has_key(attr):
1107            return self._values[attr]
1108
1109        if self._children.has_key(attr):
1110            return self._children[attr]
1111
1112        # If the attribute exists on the C++ object, transparently
1113        # forward the reference there.  This is typically used for
1114        # methods exported to Python (e.g., init(), and startup())
1115        if self._ccObject and hasattr(self._ccObject, attr):
1116            return getattr(self._ccObject, attr)
1117
1118        err_string = "object '%s' has no attribute '%s'" \
1119              % (self.__class__.__name__, attr)
1120
1121        if not self._ccObject:
1122            err_string += "\n  (C++ object is not yet constructed," \
1123                          " so wrapped C++ methods are unavailable.)"
1124
1125        raise AttributeError, err_string
1126
1127    # Set attribute (called on foo.attr = value when foo is an
1128    # instance of class cls).
1129    def __setattr__(self, attr, value):
1130        # normal processing for private attributes
1131        if attr.startswith('_'):
1132            object.__setattr__(self, attr, value)
1133            return
1134
1135        if self._ports.has_key(attr):
1136            # set up port connection
1137            self._get_port_ref(attr).connect(value)
1138            return
1139
1140        param = self._params.get(attr)
1141        if param:
1142            try:
1143                hr_value = value
1144                value = param.convert(value)
1145            except Exception, e:
1146                msg = "%s\nError setting param %s.%s to %s\n" % \
1147                      (e, self.__class__.__name__, attr, value)
1148                e.args = (msg, )
1149                raise
1150            self._values[attr] = value
1151            # implicitly parent unparented objects assigned as params
1152            if isSimObjectOrVector(value) and not value.has_parent():
1153                self.add_child(attr, value)
1154            # set the human-readable value dict if this is a param
1155            # with a literal value and is not being set as an object
1156            # or proxy.
1157            if not (isSimObjectOrVector(value) or\
1158                    isinstance(value, m5.proxy.BaseProxy)):
1159                self._hr_values[attr] = hr_value
1160
1161            return
1162
1163        # if RHS is a SimObject, it's an implicit child assignment
1164        if isSimObjectOrSequence(value):
1165            self.add_child(attr, value)
1166            return
1167
1168        # no valid assignment... raise exception
1169        raise AttributeError, "Class %s has no parameter %s" \
1170              % (self.__class__.__name__, attr)
1171
1172
1173    # this hack allows tacking a '[0]' onto parameters that may or may
1174    # not be vectors, and always getting the first element (e.g. cpus)
1175    def __getitem__(self, key):
1176        if key == 0:
1177            return self
1178        raise IndexError, "Non-zero index '%s' to SimObject" % key
1179
1180    # this hack allows us to iterate over a SimObject that may
1181    # not be a vector, so we can call a loop over it and get just one
1182    # element.
1183    def __len__(self):
1184        return 1
1185
1186    # Also implemented by SimObjectVector
1187    def clear_parent(self, old_parent):
1188        assert self._parent is old_parent
1189        self._parent = None
1190
1191    # Also implemented by SimObjectVector
1192    def set_parent(self, parent, name):
1193        self._parent = parent
1194        self._name = name
1195
1196    # Return parent object of this SimObject, not implemented by
1197    # SimObjectVector because the elements in a SimObjectVector may not share
1198    # the same parent
1199    def get_parent(self):
1200        return self._parent
1201
1202    # Also implemented by SimObjectVector
1203    def get_name(self):
1204        return self._name
1205
1206    # Also implemented by SimObjectVector
1207    def has_parent(self):
1208        return self._parent is not None
1209
1210    # clear out child with given name. This code is not likely to be exercised.
1211    # See comment in add_child.
1212    def clear_child(self, name):
1213        child = self._children[name]
1214        child.clear_parent(self)
1215        del self._children[name]
1216
1217    # Add a new child to this object.
1218    def add_child(self, name, child):
1219        child = coerceSimObjectOrVector(child)
1220        if child.has_parent():
1221            warn("add_child('%s'): child '%s' already has parent", name,
1222                child.get_name())
1223        if self._children.has_key(name):
1224            # This code path had an undiscovered bug that would make it fail
1225            # at runtime. It had been here for a long time and was only
1226            # exposed by a buggy script. Changes here will probably not be
1227            # exercised without specialized testing.
1228            self.clear_child(name)
1229        child.set_parent(self, name)
1230        if not isNullPointer(child):
1231            self._children[name] = child
1232
1233    # Take SimObject-valued parameters that haven't been explicitly
1234    # assigned as children and make them children of the object that
1235    # they were assigned to as a parameter value.  This guarantees
1236    # that when we instantiate all the parameter objects we're still
1237    # inside the configuration hierarchy.
1238    def adoptOrphanParams(self):
1239        for key,val in self._values.iteritems():
1240            if not isSimObjectVector(val) and isSimObjectSequence(val):
1241                # need to convert raw SimObject sequences to
1242                # SimObjectVector class so we can call has_parent()
1243                val = SimObjectVector(val)
1244                self._values[key] = val
1245            if isSimObjectOrVector(val) and not val.has_parent():
1246                warn("%s adopting orphan SimObject param '%s'", self, key)
1247                self.add_child(key, val)
1248
1249    def path(self):
1250        if not self._parent:
1251            return '<orphan %s>' % self.__class__
1252        elif isinstance(self._parent, MetaSimObject):
1253            return str(self.__class__)
1254
1255        ppath = self._parent.path()
1256        if ppath == 'root':
1257            return self._name
1258        return ppath + "." + self._name
1259
1260    def __str__(self):
1261        return self.path()
1262
1263    def config_value(self):
1264        return self.path()
1265
1266    def ini_str(self):
1267        return self.path()
1268
1269    def find_any(self, ptype):
1270        if isinstance(self, ptype):
1271            return self, True
1272
1273        found_obj = None
1274        for child in self._children.itervalues():
1275            visited = False
1276            if hasattr(child, '_visited'):
1277              visited = getattr(child, '_visited')
1278
1279            if isinstance(child, ptype) and not visited:
1280                if found_obj != None and child != found_obj:
1281                    raise AttributeError, \
1282                          'parent.any matched more than one: %s %s' % \
1283                          (found_obj.path, child.path)
1284                found_obj = child
1285        # search param space
1286        for pname,pdesc in self._params.iteritems():
1287            if issubclass(pdesc.ptype, ptype):
1288                match_obj = self._values[pname]
1289                if found_obj != None and found_obj != match_obj:
1290                    raise AttributeError, \
1291                          'parent.any matched more than one: %s and %s' % \
1292                          (found_obj.path, match_obj.path)
1293                found_obj = match_obj
1294        return found_obj, found_obj != None
1295
1296    def find_all(self, ptype):
1297        all = {}
1298        # search children
1299        for child in self._children.itervalues():
1300            # a child could be a list, so ensure we visit each item
1301            if isinstance(child, list):
1302                children = child
1303            else:
1304                children = [child]
1305
1306            for child in children:
1307                if isinstance(child, ptype) and not isproxy(child) and \
1308                        not isNullPointer(child):
1309                    all[child] = True
1310                if isSimObject(child):
1311                    # also add results from the child itself
1312                    child_all, done = child.find_all(ptype)
1313                    all.update(dict(zip(child_all, [done] * len(child_all))))
1314        # search param space
1315        for pname,pdesc in self._params.iteritems():
1316            if issubclass(pdesc.ptype, ptype):
1317                match_obj = self._values[pname]
1318                if not isproxy(match_obj) and not isNullPointer(match_obj):
1319                    all[match_obj] = True
1320        # Also make sure to sort the keys based on the objects' path to
1321        # ensure that the order is the same on all hosts
1322        return sorted(all.keys(), key = lambda o: o.path()), True
1323
1324    def unproxy(self, base):
1325        return self
1326
1327    def unproxyParams(self):
1328        for param in self._params.iterkeys():
1329            value = self._values.get(param)
1330            if value != None and isproxy(value):
1331                try:
1332                    value = value.unproxy(self)
1333                except:
1334                    print "Error in unproxying param '%s' of %s" % \
1335                          (param, self.path())
1336                    raise
1337                setattr(self, param, value)
1338
1339        # Unproxy ports in sorted order so that 'append' operations on
1340        # vector ports are done in a deterministic fashion.
1341        port_names = self._ports.keys()
1342        port_names.sort()
1343        for port_name in port_names:
1344            port = self._port_refs.get(port_name)
1345            if port != None:
1346                port.unproxy(self)
1347
1348    def print_ini(self, ini_file):
1349        print >>ini_file, '[' + self.path() + ']'       # .ini section header
1350
1351        instanceDict[self.path()] = self
1352
1353        if hasattr(self, 'type'):
1354            print >>ini_file, 'type=%s' % self.type
1355
1356        if len(self._children.keys()):
1357            print >>ini_file, 'children=%s' % \
1358                  ' '.join(self._children[n].get_name() \
1359                  for n in sorted(self._children.keys()))
1360
1361        for param in sorted(self._params.keys()):
1362            value = self._values.get(param)
1363            if value != None:
1364                print >>ini_file, '%s=%s' % (param,
1365                                             self._values[param].ini_str())
1366
1367        for port_name in sorted(self._ports.keys()):
1368            port = self._port_refs.get(port_name, None)
1369            if port != None:
1370                print >>ini_file, '%s=%s' % (port_name, port.ini_str())
1371
1372        print >>ini_file        # blank line between objects
1373
1374    # generate a tree of dictionaries expressing all the parameters in the
1375    # instantiated system for use by scripts that want to do power, thermal
1376    # visualization, and other similar tasks
1377    def get_config_as_dict(self):
1378        d = attrdict()
1379        if hasattr(self, 'type'):
1380            d.type = self.type
1381        if hasattr(self, 'cxx_class'):
1382            d.cxx_class = self.cxx_class
1383        # Add the name and path of this object to be able to link to
1384        # the stats
1385        d.name = self.get_name()
1386        d.path = self.path()
1387
1388        for param in sorted(self._params.keys()):
1389            value = self._values.get(param)
1390            if value != None:
1391                d[param] = value.config_value()
1392
1393        for n in sorted(self._children.keys()):
1394            child = self._children[n]
1395            # Use the name of the attribute (and not get_name()) as
1396            # the key in the JSON dictionary to capture the hierarchy
1397            # in the Python code that assembled this system
1398            d[n] = child.get_config_as_dict()
1399
1400        for port_name in sorted(self._ports.keys()):
1401            port = self._port_refs.get(port_name, None)
1402            if port != None:
1403                # Represent each port with a dictionary containing the
1404                # prominent attributes
1405                d[port_name] = port.get_config_as_dict()
1406
1407        return d
1408
1409    def getCCParams(self):
1410        if self._ccParams:
1411            return self._ccParams
1412
1413        cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type)
1414        cc_params = cc_params_struct()
1415        cc_params.name = str(self)
1416
1417        param_names = self._params.keys()
1418        param_names.sort()
1419        for param in param_names:
1420            value = self._values.get(param)
1421            if value is None:
1422                fatal("%s.%s without default or user set value",
1423                      self.path(), param)
1424
1425            value = value.getValue()
1426            if isinstance(self._params[param], VectorParamDesc):
1427                assert isinstance(value, list)
1428                vec = getattr(cc_params, param)
1429                assert not len(vec)
1430                # Some types are exposed as opaque types. They support
1431                # the append operation unlike the automatically
1432                # wrapped types.
1433                if isinstance(vec, list):
1434                    setattr(cc_params, param, list(value))
1435                else:
1436                    for v in value:
1437                        getattr(cc_params, param).append(v)
1438            else:
1439                setattr(cc_params, param, value)
1440
1441        port_names = self._ports.keys()
1442        port_names.sort()
1443        for port_name in port_names:
1444            port = self._port_refs.get(port_name, None)
1445            if port != None:
1446                port_count = len(port)
1447            else:
1448                port_count = 0
1449            setattr(cc_params, 'port_' + port_name + '_connection_count',
1450                    port_count)
1451        self._ccParams = cc_params
1452        return self._ccParams
1453
1454    # Get C++ object corresponding to this object, calling C++ if
1455    # necessary to construct it.  Does *not* recursively create
1456    # children.
1457    def getCCObject(self):
1458        if not self._ccObject:
1459            # Make sure this object is in the configuration hierarchy
1460            if not self._parent and not isRoot(self):
1461                raise RuntimeError, "Attempt to instantiate orphan node"
1462            # Cycles in the configuration hierarchy are not supported. This
1463            # will catch the resulting recursion and stop.
1464            self._ccObject = -1
1465            if not self.abstract:
1466                params = self.getCCParams()
1467                self._ccObject = params.create()
1468        elif self._ccObject == -1:
1469            raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
1470                  % self.path()
1471        return self._ccObject
1472
1473    def descendants(self):
1474        yield self
1475        # The order of the dict is implementation dependent, so sort
1476        # it based on the key (name) to ensure the order is the same
1477        # on all hosts
1478        for (name, child) in sorted(self._children.iteritems()):
1479            for obj in child.descendants():
1480                yield obj
1481
1482    # Call C++ to create C++ object corresponding to this object
1483    def createCCObject(self):
1484        self.getCCParams()
1485        self.getCCObject() # force creation
1486
1487    def getValue(self):
1488        return self.getCCObject()
1489
1490    # Create C++ port connections corresponding to the connections in
1491    # _port_refs
1492    def connectPorts(self):
1493        # Sort the ports based on their attribute name to ensure the
1494        # order is the same on all hosts
1495        for (attr, portRef) in sorted(self._port_refs.iteritems()):
1496            portRef.ccConnect()
1497
1498# Function to provide to C++ so it can look up instances based on paths
1499def resolveSimObject(name):
1500    obj = instanceDict[name]
1501    return obj.getCCObject()
1502
1503def isSimObject(value):
1504    return isinstance(value, SimObject)
1505
1506def isSimObjectClass(value):
1507    return issubclass(value, SimObject)
1508
1509def isSimObjectVector(value):
1510    return isinstance(value, SimObjectVector)
1511
1512def isSimObjectSequence(value):
1513    if not isinstance(value, (list, tuple)) or len(value) == 0:
1514        return False
1515
1516    for val in value:
1517        if not isNullPointer(val) and not isSimObject(val):
1518            return False
1519
1520    return True
1521
1522def isSimObjectOrSequence(value):
1523    return isSimObject(value) or isSimObjectSequence(value)
1524
1525def isRoot(obj):
1526    from m5.objects import Root
1527    return obj and obj is Root.getInstance()
1528
1529def isSimObjectOrVector(value):
1530    return isSimObject(value) or isSimObjectVector(value)
1531
1532def tryAsSimObjectOrVector(value):
1533    if isSimObjectOrVector(value):
1534        return value
1535    if isSimObjectSequence(value):
1536        return SimObjectVector(value)
1537    return None
1538
1539def coerceSimObjectOrVector(value):
1540    value = tryAsSimObjectOrVector(value)
1541    if value is None:
1542        raise TypeError, "SimObject or SimObjectVector expected"
1543    return value
1544
1545baseClasses = allClasses.copy()
1546baseInstances = instanceDict.copy()
1547
1548def clear():
1549    global allClasses, instanceDict, noCxxHeader
1550
1551    allClasses = baseClasses.copy()
1552    instanceDict = baseInstances.copy()
1553    noCxxHeader = False
1554
1555# __all__ defines the list of symbols that get exported when
1556# 'from config import *' is invoked.  Try to keep this reasonably
1557# short to avoid polluting other namespaces.
1558__all__ = [
1559    'SimObject',
1560    'cxxMethod',
1561    'PyBindMethod',
1562    'PyBindProperty',
1563]
1564