SimObject.py revision 11991
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, "SimObjects do not support multiple inheritance"
481
482        base = bases[0]
483
484        # Set up general inheritance via multidicts.  A subclass will
485        # inherit all its settings from the base class.  The only time
486        # the following is not true is when we define the SimObject
487        # class itself (in which case the multidicts have no parent).
488        if isinstance(base, MetaSimObject):
489            cls._base = base
490            cls._params.parent = base._params
491            cls._ports.parent = base._ports
492            cls._values.parent = base._values
493            cls._hr_values.parent = base._hr_values
494            cls._children.parent = base._children
495            cls._port_refs.parent = base._port_refs
496            # mark base as having been subclassed
497            base._instantiated = True
498        else:
499            cls._base = None
500
501        # default keyword values
502        if 'type' in cls._value_dict:
503            if 'cxx_class' not in cls._value_dict:
504                cls._value_dict['cxx_class'] = cls._value_dict['type']
505
506            cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class']
507
508            if 'cxx_header' not in cls._value_dict:
509                global noCxxHeader
510                noCxxHeader = True
511                warn("No header file specified for SimObject: %s", name)
512
513        # Now process the _value_dict items.  They could be defining
514        # new (or overriding existing) parameters or ports, setting
515        # class keywords (e.g., 'abstract'), or setting parameter
516        # values or port bindings.  The first 3 can only be set when
517        # the class is defined, so we handle them here.  The others
518        # can be set later too, so just emulate that by calling
519        # setattr().
520        for key,val in cls._value_dict.items():
521            # param descriptions
522            if isinstance(val, ParamDesc):
523                cls._new_param(key, val)
524
525            # port objects
526            elif isinstance(val, Port):
527                cls._new_port(key, val)
528
529            # init-time-only keywords
530            elif cls.init_keywords.has_key(key):
531                cls._set_keyword(key, val, cls.init_keywords[key])
532
533            # default: use normal path (ends up in __setattr__)
534            else:
535                setattr(cls, key, val)
536
537    def _set_keyword(cls, keyword, val, kwtype):
538        if not isinstance(val, kwtype):
539            raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
540                  (keyword, type(val), kwtype)
541        if isinstance(val, FunctionType):
542            val = classmethod(val)
543        type.__setattr__(cls, keyword, val)
544
545    def _new_param(cls, name, pdesc):
546        # each param desc should be uniquely assigned to one variable
547        assert(not hasattr(pdesc, 'name'))
548        pdesc.name = name
549        cls._params[name] = pdesc
550        if hasattr(pdesc, 'default'):
551            cls._set_param(name, pdesc.default, pdesc)
552
553    def _set_param(cls, name, value, param):
554        assert(param.name == name)
555        try:
556            hr_value = value
557            value = param.convert(value)
558        except Exception, e:
559            msg = "%s\nError setting param %s.%s to %s\n" % \
560                  (e, cls.__name__, name, value)
561            e.args = (msg, )
562            raise
563        cls._values[name] = value
564        # if param value is a SimObject, make it a child too, so that
565        # it gets cloned properly when the class is instantiated
566        if isSimObjectOrVector(value) and not value.has_parent():
567            cls._add_cls_child(name, value)
568        # update human-readable values of the param if it has a literal
569        # value and is not an object or proxy.
570        if not (isSimObjectOrVector(value) or\
571                isinstance(value, m5.proxy.BaseProxy)):
572            cls._hr_values[name] = hr_value
573
574    def _add_cls_child(cls, name, child):
575        # It's a little funky to have a class as a parent, but these
576        # objects should never be instantiated (only cloned, which
577        # clears the parent pointer), and this makes it clear that the
578        # object is not an orphan and can provide better error
579        # messages.
580        child.set_parent(cls, name)
581        cls._children[name] = child
582
583    def _new_port(cls, name, port):
584        # each port should be uniquely assigned to one variable
585        assert(not hasattr(port, 'name'))
586        port.name = name
587        cls._ports[name] = port
588
589    # same as _get_port_ref, effectively, but for classes
590    def _cls_get_port_ref(cls, attr):
591        # Return reference that can be assigned to another port
592        # via __setattr__.  There is only ever one reference
593        # object per port, but we create them lazily here.
594        ref = cls._port_refs.get(attr)
595        if not ref:
596            ref = cls._ports[attr].makeRef(cls)
597            cls._port_refs[attr] = ref
598        return ref
599
600    # Set attribute (called on foo.attr = value when foo is an
601    # instance of class cls).
602    def __setattr__(cls, attr, value):
603        # normal processing for private attributes
604        if public_value(attr, value):
605            type.__setattr__(cls, attr, value)
606            return
607
608        if cls.keywords.has_key(attr):
609            cls._set_keyword(attr, value, cls.keywords[attr])
610            return
611
612        if cls._ports.has_key(attr):
613            cls._cls_get_port_ref(attr).connect(value)
614            return
615
616        if isSimObjectOrSequence(value) and cls._instantiated:
617            raise RuntimeError, \
618                  "cannot set SimObject parameter '%s' after\n" \
619                  "    class %s has been instantiated or subclassed" \
620                  % (attr, cls.__name__)
621
622        # check for param
623        param = cls._params.get(attr)
624        if param:
625            cls._set_param(attr, value, param)
626            return
627
628        if isSimObjectOrSequence(value):
629            # If RHS is a SimObject, it's an implicit child assignment.
630            cls._add_cls_child(attr, coerceSimObjectOrVector(value))
631            return
632
633        # no valid assignment... raise exception
634        raise AttributeError, \
635              "Class %s has no parameter \'%s\'" % (cls.__name__, attr)
636
637    def __getattr__(cls, attr):
638        if attr == 'cxx_class_path':
639            return cls.cxx_class.split('::')
640
641        if attr == 'cxx_class_name':
642            return cls.cxx_class_path[-1]
643
644        if attr == 'cxx_namespaces':
645            return cls.cxx_class_path[:-1]
646
647        if cls._values.has_key(attr):
648            return cls._values[attr]
649
650        if cls._children.has_key(attr):
651            return cls._children[attr]
652
653        raise AttributeError, \
654              "object '%s' has no attribute '%s'" % (cls.__name__, attr)
655
656    def __str__(cls):
657        return cls.__name__
658
659    # See ParamValue.cxx_predecls for description.
660    def cxx_predecls(cls, code):
661        code('#include "params/$cls.hh"')
662
663    def pybind_predecls(cls, code):
664        code('#include "${{cls.cxx_header}}"')
665
666    def pybind_decl(cls, code):
667        class_path = cls.cxx_class.split('::')
668        namespaces, classname = class_path[:-1], class_path[-1]
669        py_class_name = '_COLONS_'.join(class_path) if namespaces else \
670                        classname;
671
672        # The 'local' attribute restricts us to the params declared in
673        # the object itself, not including inherited params (which
674        # will also be inherited from the base class's param struct
675        # here). Sort the params based on their key
676        params = map(lambda (k, v): v, sorted(cls._params.local.items()))
677        ports = cls._ports.local
678
679        code('''#include "pybind11/pybind11.h"
680#include "pybind11/stl.h"
681
682#include "sim/sim_object.hh"
683#include "params/$cls.hh"
684#include "sim/init.hh"
685#include "${{cls.cxx_header}}"
686
687''')
688
689        for param in params:
690            param.pybind_predecls(code)
691
692        code('''namespace py = pybind11;
693
694static void
695module_init(py::module &m_internal)
696{
697    py::module m = m_internal.def_submodule("param_${cls}");
698''')
699        code.indent()
700        if cls._base:
701            code('py::class_<${cls}Params, ${{cls._base.type}}Params>(m, ' \
702                 '"${cls}Params")')
703        else:
704            code('py::class_<${cls}Params>(m, "${cls}Params")')
705
706        code.indent()
707        if not hasattr(cls, 'abstract') or not cls.abstract:
708            code('.def(py::init<>())')
709            code('.def("create", &${cls}Params::create)')
710
711        param_exports = cls.cxx_param_exports + [
712            PyBindProperty(k)
713            for k, v in sorted(cls._params.local.items())
714        ] + [
715            PyBindProperty("port_%s_connection_count" % port.name)
716            for port in ports.itervalues()
717        ]
718        for exp in param_exports:
719            exp.export(code, "%sParams" % cls)
720
721        code(';')
722        code()
723        code.dedent()
724
725        bases = [ cls._base.cxx_class ] + cls.cxx_bases if cls._base else \
726                cls.cxx_bases
727        if bases:
728            base_str = ", ".join(bases)
729            code('py::class_<${{cls.cxx_class}}, ${base_str}>(m, ' \
730                 '"${py_class_name}")')
731        else:
732            code('py::class_<${{cls.cxx_class}}>(m, "${py_class_name}")')
733        code.indent()
734        for exp in cls.cxx_exports:
735            exp.export(code, cls.cxx_class)
736        code(';')
737        code.dedent()
738        code()
739        code.dedent()
740        code('}')
741        code()
742        code('static EmbeddedPyBind embed_obj("${0}", module_init, "${1}");',
743             cls, cls._base.type if cls._base else "")
744
745
746    # Generate the C++ declaration (.hh file) for this SimObject's
747    # param struct.  Called from src/SConscript.
748    def cxx_param_decl(cls, code):
749        # The 'local' attribute restricts us to the params declared in
750        # the object itself, not including inherited params (which
751        # will also be inherited from the base class's param struct
752        # here). Sort the params based on their key
753        params = map(lambda (k, v): v, sorted(cls._params.local.items()))
754        ports = cls._ports.local
755        try:
756            ptypes = [p.ptype for p in params]
757        except:
758            print cls, p, p.ptype_str
759            print params
760            raise
761
762        class_path = cls._value_dict['cxx_class'].split('::')
763
764        code('''\
765#ifndef __PARAMS__${cls}__
766#define __PARAMS__${cls}__
767
768''')
769
770
771        # The base SimObject has a couple of params that get
772        # automatically set from Python without being declared through
773        # the normal Param mechanism; we slip them in here (needed
774        # predecls now, actual declarations below)
775        if cls == SimObject:
776            code('''#include <string>''')
777
778        # A forward class declaration is sufficient since we are just
779        # declaring a pointer.
780        for ns in class_path[:-1]:
781            code('namespace $ns {')
782        code('class $0;', class_path[-1])
783        for ns in reversed(class_path[:-1]):
784            code('} // namespace $ns')
785        code()
786
787        for param in params:
788            param.cxx_predecls(code)
789        for port in ports.itervalues():
790            port.cxx_predecls(code)
791        code()
792
793        if cls._base:
794            code('#include "params/${{cls._base.type}}.hh"')
795            code()
796
797        for ptype in ptypes:
798            if issubclass(ptype, Enum):
799                code('#include "enums/${{ptype.__name__}}.hh"')
800                code()
801
802        # now generate the actual param struct
803        code("struct ${cls}Params")
804        if cls._base:
805            code("    : public ${{cls._base.type}}Params")
806        code("{")
807        if not hasattr(cls, 'abstract') or not cls.abstract:
808            if 'type' in cls.__dict__:
809                code("    ${{cls.cxx_type}} create();")
810
811        code.indent()
812        if cls == SimObject:
813            code('''
814    SimObjectParams() {}
815    virtual ~SimObjectParams() {}
816
817    std::string name;
818            ''')
819
820        for param in params:
821            param.cxx_decl(code)
822        for port in ports.itervalues():
823            port.cxx_decl(code)
824
825        code.dedent()
826        code('};')
827
828        code()
829        code('#endif // __PARAMS__${cls}__')
830        return code
831
832    # Generate the C++ declaration/definition files for this SimObject's
833    # param struct to allow C++ initialisation
834    def cxx_config_param_file(cls, code, is_header):
835        createCxxConfigDirectoryEntryFile(code, cls.__name__, cls, is_header)
836        return code
837
838# This *temporary* definition is required to support calls from the
839# SimObject class definition to the MetaSimObject methods (in
840# particular _set_param, which gets called for parameters with default
841# values defined on the SimObject class itself).  It will get
842# overridden by the permanent definition (which requires that
843# SimObject be defined) lower in this file.
844def isSimObjectOrVector(value):
845    return False
846
847def cxxMethod(*args, **kwargs):
848    """Decorator to export C++ functions to Python"""
849
850    def decorate(func):
851        name = func.func_name
852        override = kwargs.get("override", False)
853        cxx_name = kwargs.get("cxx_name", name)
854
855        args, varargs, keywords, defaults = inspect.getargspec(func)
856        if varargs or keywords:
857            raise ValueError("Wrapped methods must not contain variable " \
858                             "arguments")
859
860        # Create tuples of (argument, default)
861        if defaults:
862            args = args[:-len(defaults)] + zip(args[-len(defaults):], defaults)
863        # Don't include self in the argument list to PyBind
864        args = args[1:]
865
866
867        @wraps(func)
868        def cxx_call(self, *args, **kwargs):
869            ccobj = self.getCCObject()
870            return getattr(ccobj, name)(*args, **kwargs)
871
872        @wraps(func)
873        def py_call(self, *args, **kwargs):
874            return self.func(*args, **kwargs)
875
876        f = py_call if override else cxx_call
877        f.__pybind = PyBindMethod(name, cxx_name=cxx_name, args=args)
878
879        return f
880
881    if len(args) == 0:
882        return decorate
883    elif len(args) == 1 and len(kwargs) == 0:
884        return decorate(*args)
885    else:
886        raise TypeError("One argument and no kwargs, or only kwargs expected")
887
888# This class holds information about each simobject parameter
889# that should be displayed on the command line for use in the
890# configuration system.
891class ParamInfo(object):
892  def __init__(self, type, desc, type_str, example, default_val, access_str):
893    self.type = type
894    self.desc = desc
895    self.type_str = type_str
896    self.example_str = example
897    self.default_val = default_val
898    # The string representation used to access this param through python.
899    # The method to access this parameter presented on the command line may
900    # be different, so this needs to be stored for later use.
901    self.access_str = access_str
902    self.created = True
903
904  # Make it so we can only set attributes at initialization time
905  # and effectively make this a const object.
906  def __setattr__(self, name, value):
907    if not "created" in self.__dict__:
908      self.__dict__[name] = value
909
910# The SimObject class is the root of the special hierarchy.  Most of
911# the code in this class deals with the configuration hierarchy itself
912# (parent/child node relationships).
913class SimObject(object):
914    # Specify metaclass.  Any class inheriting from SimObject will
915    # get this metaclass.
916    __metaclass__ = MetaSimObject
917    type = 'SimObject'
918    abstract = True
919
920    cxx_header = "sim/sim_object.hh"
921    cxx_bases = [ "Drainable", "Serializable" ]
922    eventq_index = Param.UInt32(Parent.eventq_index, "Event Queue Index")
923
924    cxx_exports = [
925        PyBindMethod("init"),
926        PyBindMethod("initState"),
927        PyBindMethod("memInvalidate"),
928        PyBindMethod("memWriteback"),
929        PyBindMethod("regStats"),
930        PyBindMethod("resetStats"),
931        PyBindMethod("regProbePoints"),
932        PyBindMethod("regProbeListeners"),
933        PyBindMethod("startup"),
934    ]
935
936    cxx_param_exports = [
937        PyBindProperty("name"),
938    ]
939
940    @cxxMethod
941    def loadState(self, cp):
942        """Load SimObject state from a checkpoint"""
943        pass
944
945    # Returns a dict of all the option strings that can be
946    # generated as command line options for this simobject instance
947    # by tracing all reachable params in the top level instance and
948    # any children it contains.
949    def enumerateParams(self, flags_dict = {},
950                        cmd_line_str = "", access_str = ""):
951        if hasattr(self, "_paramEnumed"):
952            print "Cycle detected enumerating params"
953        else:
954            self._paramEnumed = True
955            # Scan the children first to pick up all the objects in this SimObj
956            for keys in self._children:
957                child = self._children[keys]
958                next_cmdline_str = cmd_line_str + keys
959                next_access_str = access_str + keys
960                if not isSimObjectVector(child):
961                    next_cmdline_str = next_cmdline_str + "."
962                    next_access_str = next_access_str + "."
963                flags_dict = child.enumerateParams(flags_dict,
964                                                   next_cmdline_str,
965                                                   next_access_str)
966
967            # Go through the simple params in the simobject in this level
968            # of the simobject hierarchy and save information about the
969            # parameter to be used for generating and processing command line
970            # options to the simulator to set these parameters.
971            for keys,values in self._params.items():
972                if values.isCmdLineSettable():
973                    type_str = ''
974                    ex_str = values.example_str()
975                    ptype = None
976                    if isinstance(values, VectorParamDesc):
977                        type_str = 'Vector_%s' % values.ptype_str
978                        ptype = values
979                    else:
980                        type_str = '%s' % values.ptype_str
981                        ptype = values.ptype
982
983                    if keys in self._hr_values\
984                       and keys in self._values\
985                       and not isinstance(self._values[keys], m5.proxy.BaseProxy):
986                        cmd_str = cmd_line_str + keys
987                        acc_str = access_str + keys
988                        flags_dict[cmd_str] = ParamInfo(ptype,
989                                    self._params[keys].desc, type_str, ex_str,
990                                    values.pretty_print(self._hr_values[keys]),
991                                    acc_str)
992                    elif not keys in self._hr_values\
993                         and not keys in self._values:
994                        # Empty param
995                        cmd_str = cmd_line_str + keys
996                        acc_str = access_str + keys
997                        flags_dict[cmd_str] = ParamInfo(ptype,
998                                    self._params[keys].desc,
999                                    type_str, ex_str, '', acc_str)
1000
1001        return flags_dict
1002
1003    # Initialize new instance.  For objects with SimObject-valued
1004    # children, we need to recursively clone the classes represented
1005    # by those param values as well in a consistent "deep copy"-style
1006    # fashion.  That is, we want to make sure that each instance is
1007    # cloned only once, and that if there are multiple references to
1008    # the same original object, we end up with the corresponding
1009    # cloned references all pointing to the same cloned instance.
1010    def __init__(self, **kwargs):
1011        ancestor = kwargs.get('_ancestor')
1012        memo_dict = kwargs.get('_memo')
1013        if memo_dict is None:
1014            # prepare to memoize any recursively instantiated objects
1015            memo_dict = {}
1016        elif ancestor:
1017            # memoize me now to avoid problems with recursive calls
1018            memo_dict[ancestor] = self
1019
1020        if not ancestor:
1021            ancestor = self.__class__
1022        ancestor._instantiated = True
1023
1024        # initialize required attributes
1025        self._parent = None
1026        self._name = None
1027        self._ccObject = None  # pointer to C++ object
1028        self._ccParams = None
1029        self._instantiated = False # really "cloned"
1030
1031        # Clone children specified at class level.  No need for a
1032        # multidict here since we will be cloning everything.
1033        # Do children before parameter values so that children that
1034        # are also param values get cloned properly.
1035        self._children = {}
1036        for key,val in ancestor._children.iteritems():
1037            self.add_child(key, val(_memo=memo_dict))
1038
1039        # Inherit parameter values from class using multidict so
1040        # individual value settings can be overridden but we still
1041        # inherit late changes to non-overridden class values.
1042        self._values = multidict(ancestor._values)
1043        self._hr_values = multidict(ancestor._hr_values)
1044        # clone SimObject-valued parameters
1045        for key,val in ancestor._values.iteritems():
1046            val = tryAsSimObjectOrVector(val)
1047            if val is not None:
1048                self._values[key] = val(_memo=memo_dict)
1049
1050        # clone port references.  no need to use a multidict here
1051        # since we will be creating new references for all ports.
1052        self._port_refs = {}
1053        for key,val in ancestor._port_refs.iteritems():
1054            self._port_refs[key] = val.clone(self, memo_dict)
1055        # apply attribute assignments from keyword args, if any
1056        for key,val in kwargs.iteritems():
1057            setattr(self, key, val)
1058
1059    # "Clone" the current instance by creating another instance of
1060    # this instance's class, but that inherits its parameter values
1061    # and port mappings from the current instance.  If we're in a
1062    # "deep copy" recursive clone, check the _memo dict to see if
1063    # we've already cloned this instance.
1064    def __call__(self, **kwargs):
1065        memo_dict = kwargs.get('_memo')
1066        if memo_dict is None:
1067            # no memo_dict: must be top-level clone operation.
1068            # this is only allowed at the root of a hierarchy
1069            if self._parent:
1070                raise RuntimeError, "attempt to clone object %s " \
1071                      "not at the root of a tree (parent = %s)" \
1072                      % (self, self._parent)
1073            # create a new dict and use that.
1074            memo_dict = {}
1075            kwargs['_memo'] = memo_dict
1076        elif memo_dict.has_key(self):
1077            # clone already done & memoized
1078            return memo_dict[self]
1079        return self.__class__(_ancestor = self, **kwargs)
1080
1081    def _get_port_ref(self, attr):
1082        # Return reference that can be assigned to another port
1083        # via __setattr__.  There is only ever one reference
1084        # object per port, but we create them lazily here.
1085        ref = self._port_refs.get(attr)
1086        if ref == None:
1087            ref = self._ports[attr].makeRef(self)
1088            self._port_refs[attr] = ref
1089        return ref
1090
1091    def __getattr__(self, attr):
1092        if self._ports.has_key(attr):
1093            return self._get_port_ref(attr)
1094
1095        if self._values.has_key(attr):
1096            return self._values[attr]
1097
1098        if self._children.has_key(attr):
1099            return self._children[attr]
1100
1101        # If the attribute exists on the C++ object, transparently
1102        # forward the reference there.  This is typically used for
1103        # methods exported to Python (e.g., init(), and startup())
1104        if self._ccObject and hasattr(self._ccObject, attr):
1105            return getattr(self._ccObject, attr)
1106
1107        err_string = "object '%s' has no attribute '%s'" \
1108              % (self.__class__.__name__, attr)
1109
1110        if not self._ccObject:
1111            err_string += "\n  (C++ object is not yet constructed," \
1112                          " so wrapped C++ methods are unavailable.)"
1113
1114        raise AttributeError, err_string
1115
1116    # Set attribute (called on foo.attr = value when foo is an
1117    # instance of class cls).
1118    def __setattr__(self, attr, value):
1119        # normal processing for private attributes
1120        if attr.startswith('_'):
1121            object.__setattr__(self, attr, value)
1122            return
1123
1124        if self._ports.has_key(attr):
1125            # set up port connection
1126            self._get_port_ref(attr).connect(value)
1127            return
1128
1129        param = self._params.get(attr)
1130        if param:
1131            try:
1132                hr_value = value
1133                value = param.convert(value)
1134            except Exception, e:
1135                msg = "%s\nError setting param %s.%s to %s\n" % \
1136                      (e, self.__class__.__name__, attr, value)
1137                e.args = (msg, )
1138                raise
1139            self._values[attr] = value
1140            # implicitly parent unparented objects assigned as params
1141            if isSimObjectOrVector(value) and not value.has_parent():
1142                self.add_child(attr, value)
1143            # set the human-readable value dict if this is a param
1144            # with a literal value and is not being set as an object
1145            # or proxy.
1146            if not (isSimObjectOrVector(value) or\
1147                    isinstance(value, m5.proxy.BaseProxy)):
1148                self._hr_values[attr] = hr_value
1149
1150            return
1151
1152        # if RHS is a SimObject, it's an implicit child assignment
1153        if isSimObjectOrSequence(value):
1154            self.add_child(attr, value)
1155            return
1156
1157        # no valid assignment... raise exception
1158        raise AttributeError, "Class %s has no parameter %s" \
1159              % (self.__class__.__name__, attr)
1160
1161
1162    # this hack allows tacking a '[0]' onto parameters that may or may
1163    # not be vectors, and always getting the first element (e.g. cpus)
1164    def __getitem__(self, key):
1165        if key == 0:
1166            return self
1167        raise IndexError, "Non-zero index '%s' to SimObject" % key
1168
1169    # this hack allows us to iterate over a SimObject that may
1170    # not be a vector, so we can call a loop over it and get just one
1171    # element.
1172    def __len__(self):
1173        return 1
1174
1175    # Also implemented by SimObjectVector
1176    def clear_parent(self, old_parent):
1177        assert self._parent is old_parent
1178        self._parent = None
1179
1180    # Also implemented by SimObjectVector
1181    def set_parent(self, parent, name):
1182        self._parent = parent
1183        self._name = name
1184
1185    # Return parent object of this SimObject, not implemented by SimObjectVector
1186    # because the elements in a SimObjectVector may not share the same parent
1187    def get_parent(self):
1188        return self._parent
1189
1190    # Also implemented by SimObjectVector
1191    def get_name(self):
1192        return self._name
1193
1194    # Also implemented by SimObjectVector
1195    def has_parent(self):
1196        return self._parent is not None
1197
1198    # clear out child with given name. This code is not likely to be exercised.
1199    # See comment in add_child.
1200    def clear_child(self, name):
1201        child = self._children[name]
1202        child.clear_parent(self)
1203        del self._children[name]
1204
1205    # Add a new child to this object.
1206    def add_child(self, name, child):
1207        child = coerceSimObjectOrVector(child)
1208        if child.has_parent():
1209            warn("add_child('%s'): child '%s' already has parent", name,
1210                child.get_name())
1211        if self._children.has_key(name):
1212            # This code path had an undiscovered bug that would make it fail
1213            # at runtime. It had been here for a long time and was only
1214            # exposed by a buggy script. Changes here will probably not be
1215            # exercised without specialized testing.
1216            self.clear_child(name)
1217        child.set_parent(self, name)
1218        self._children[name] = child
1219
1220    # Take SimObject-valued parameters that haven't been explicitly
1221    # assigned as children and make them children of the object that
1222    # they were assigned to as a parameter value.  This guarantees
1223    # that when we instantiate all the parameter objects we're still
1224    # inside the configuration hierarchy.
1225    def adoptOrphanParams(self):
1226        for key,val in self._values.iteritems():
1227            if not isSimObjectVector(val) and isSimObjectSequence(val):
1228                # need to convert raw SimObject sequences to
1229                # SimObjectVector class so we can call has_parent()
1230                val = SimObjectVector(val)
1231                self._values[key] = val
1232            if isSimObjectOrVector(val) and not val.has_parent():
1233                warn("%s adopting orphan SimObject param '%s'", self, key)
1234                self.add_child(key, val)
1235
1236    def path(self):
1237        if not self._parent:
1238            return '<orphan %s>' % self.__class__
1239        elif isinstance(self._parent, MetaSimObject):
1240            return str(self.__class__)
1241
1242        ppath = self._parent.path()
1243        if ppath == 'root':
1244            return self._name
1245        return ppath + "." + self._name
1246
1247    def __str__(self):
1248        return self.path()
1249
1250    def config_value(self):
1251        return self.path()
1252
1253    def ini_str(self):
1254        return self.path()
1255
1256    def find_any(self, ptype):
1257        if isinstance(self, ptype):
1258            return self, True
1259
1260        found_obj = None
1261        for child in self._children.itervalues():
1262            visited = False
1263            if hasattr(child, '_visited'):
1264              visited = getattr(child, '_visited')
1265
1266            if isinstance(child, ptype) and not visited:
1267                if found_obj != None and child != found_obj:
1268                    raise AttributeError, \
1269                          'parent.any matched more than one: %s %s' % \
1270                          (found_obj.path, child.path)
1271                found_obj = child
1272        # search param space
1273        for pname,pdesc in self._params.iteritems():
1274            if issubclass(pdesc.ptype, ptype):
1275                match_obj = self._values[pname]
1276                if found_obj != None and found_obj != match_obj:
1277                    raise AttributeError, \
1278                          'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path)
1279                found_obj = match_obj
1280        return found_obj, found_obj != None
1281
1282    def find_all(self, ptype):
1283        all = {}
1284        # search children
1285        for child in self._children.itervalues():
1286            # a child could be a list, so ensure we visit each item
1287            if isinstance(child, list):
1288                children = child
1289            else:
1290                children = [child]
1291
1292            for child in children:
1293                if isinstance(child, ptype) and not isproxy(child) and \
1294                        not isNullPointer(child):
1295                    all[child] = True
1296                if isSimObject(child):
1297                    # also add results from the child itself
1298                    child_all, done = child.find_all(ptype)
1299                    all.update(dict(zip(child_all, [done] * len(child_all))))
1300        # search param space
1301        for pname,pdesc in self._params.iteritems():
1302            if issubclass(pdesc.ptype, ptype):
1303                match_obj = self._values[pname]
1304                if not isproxy(match_obj) and not isNullPointer(match_obj):
1305                    all[match_obj] = True
1306        # Also make sure to sort the keys based on the objects' path to
1307        # ensure that the order is the same on all hosts
1308        return sorted(all.keys(), key = lambda o: o.path()), True
1309
1310    def unproxy(self, base):
1311        return self
1312
1313    def unproxyParams(self):
1314        for param in self._params.iterkeys():
1315            value = self._values.get(param)
1316            if value != None and isproxy(value):
1317                try:
1318                    value = value.unproxy(self)
1319                except:
1320                    print "Error in unproxying param '%s' of %s" % \
1321                          (param, self.path())
1322                    raise
1323                setattr(self, param, value)
1324
1325        # Unproxy ports in sorted order so that 'append' operations on
1326        # vector ports are done in a deterministic fashion.
1327        port_names = self._ports.keys()
1328        port_names.sort()
1329        for port_name in port_names:
1330            port = self._port_refs.get(port_name)
1331            if port != None:
1332                port.unproxy(self)
1333
1334    def print_ini(self, ini_file):
1335        print >>ini_file, '[' + self.path() + ']'       # .ini section header
1336
1337        instanceDict[self.path()] = self
1338
1339        if hasattr(self, 'type'):
1340            print >>ini_file, 'type=%s' % self.type
1341
1342        if len(self._children.keys()):
1343            print >>ini_file, 'children=%s' % \
1344                  ' '.join(self._children[n].get_name() \
1345                  for n in sorted(self._children.keys()))
1346
1347        for param in sorted(self._params.keys()):
1348            value = self._values.get(param)
1349            if value != None:
1350                print >>ini_file, '%s=%s' % (param,
1351                                             self._values[param].ini_str())
1352
1353        for port_name in sorted(self._ports.keys()):
1354            port = self._port_refs.get(port_name, None)
1355            if port != None:
1356                print >>ini_file, '%s=%s' % (port_name, port.ini_str())
1357
1358        print >>ini_file        # blank line between objects
1359
1360    # generate a tree of dictionaries expressing all the parameters in the
1361    # instantiated system for use by scripts that want to do power, thermal
1362    # visualization, and other similar tasks
1363    def get_config_as_dict(self):
1364        d = attrdict()
1365        if hasattr(self, 'type'):
1366            d.type = self.type
1367        if hasattr(self, 'cxx_class'):
1368            d.cxx_class = self.cxx_class
1369        # Add the name and path of this object to be able to link to
1370        # the stats
1371        d.name = self.get_name()
1372        d.path = self.path()
1373
1374        for param in sorted(self._params.keys()):
1375            value = self._values.get(param)
1376            if value != None:
1377                d[param] = value.config_value()
1378
1379        for n in sorted(self._children.keys()):
1380            child = self._children[n]
1381            # Use the name of the attribute (and not get_name()) as
1382            # the key in the JSON dictionary to capture the hierarchy
1383            # in the Python code that assembled this system
1384            d[n] = child.get_config_as_dict()
1385
1386        for port_name in sorted(self._ports.keys()):
1387            port = self._port_refs.get(port_name, None)
1388            if port != None:
1389                # Represent each port with a dictionary containing the
1390                # prominent attributes
1391                d[port_name] = port.get_config_as_dict()
1392
1393        return d
1394
1395    def getCCParams(self):
1396        if self._ccParams:
1397            return self._ccParams
1398
1399        cc_params_struct = getattr(m5.internal.params, '%sParams' % self.type)
1400        cc_params = cc_params_struct()
1401        cc_params.name = str(self)
1402
1403        param_names = self._params.keys()
1404        param_names.sort()
1405        for param in param_names:
1406            value = self._values.get(param)
1407            if value is None:
1408                fatal("%s.%s without default or user set value",
1409                      self.path(), param)
1410
1411            value = value.getValue()
1412            if isinstance(self._params[param], VectorParamDesc):
1413                assert isinstance(value, list)
1414                vec = getattr(cc_params, param)
1415                assert not len(vec)
1416                setattr(cc_params, param, list(value))
1417            else:
1418                setattr(cc_params, param, value)
1419
1420        port_names = self._ports.keys()
1421        port_names.sort()
1422        for port_name in port_names:
1423            port = self._port_refs.get(port_name, None)
1424            if port != None:
1425                port_count = len(port)
1426            else:
1427                port_count = 0
1428            setattr(cc_params, 'port_' + port_name + '_connection_count',
1429                    port_count)
1430        self._ccParams = cc_params
1431        return self._ccParams
1432
1433    # Get C++ object corresponding to this object, calling C++ if
1434    # necessary to construct it.  Does *not* recursively create
1435    # children.
1436    def getCCObject(self):
1437        if not self._ccObject:
1438            # Make sure this object is in the configuration hierarchy
1439            if not self._parent and not isRoot(self):
1440                raise RuntimeError, "Attempt to instantiate orphan node"
1441            # Cycles in the configuration hierarchy are not supported. This
1442            # will catch the resulting recursion and stop.
1443            self._ccObject = -1
1444            if not self.abstract:
1445                params = self.getCCParams()
1446                self._ccObject = params.create()
1447        elif self._ccObject == -1:
1448            raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
1449                  % self.path()
1450        return self._ccObject
1451
1452    def descendants(self):
1453        yield self
1454        # The order of the dict is implementation dependent, so sort
1455        # it based on the key (name) to ensure the order is the same
1456        # on all hosts
1457        for (name, child) in sorted(self._children.iteritems()):
1458            for obj in child.descendants():
1459                yield obj
1460
1461    # Call C++ to create C++ object corresponding to this object
1462    def createCCObject(self):
1463        self.getCCParams()
1464        self.getCCObject() # force creation
1465
1466    def getValue(self):
1467        return self.getCCObject()
1468
1469    # Create C++ port connections corresponding to the connections in
1470    # _port_refs
1471    def connectPorts(self):
1472        # Sort the ports based on their attribute name to ensure the
1473        # order is the same on all hosts
1474        for (attr, portRef) in sorted(self._port_refs.iteritems()):
1475            portRef.ccConnect()
1476
1477# Function to provide to C++ so it can look up instances based on paths
1478def resolveSimObject(name):
1479    obj = instanceDict[name]
1480    return obj.getCCObject()
1481
1482def isSimObject(value):
1483    return isinstance(value, SimObject)
1484
1485def isSimObjectClass(value):
1486    return issubclass(value, SimObject)
1487
1488def isSimObjectVector(value):
1489    return isinstance(value, SimObjectVector)
1490
1491def isSimObjectSequence(value):
1492    if not isinstance(value, (list, tuple)) or len(value) == 0:
1493        return False
1494
1495    for val in value:
1496        if not isNullPointer(val) and not isSimObject(val):
1497            return False
1498
1499    return True
1500
1501def isSimObjectOrSequence(value):
1502    return isSimObject(value) or isSimObjectSequence(value)
1503
1504def isRoot(obj):
1505    from m5.objects import Root
1506    return obj and obj is Root.getInstance()
1507
1508def isSimObjectOrVector(value):
1509    return isSimObject(value) or isSimObjectVector(value)
1510
1511def tryAsSimObjectOrVector(value):
1512    if isSimObjectOrVector(value):
1513        return value
1514    if isSimObjectSequence(value):
1515        return SimObjectVector(value)
1516    return None
1517
1518def coerceSimObjectOrVector(value):
1519    value = tryAsSimObjectOrVector(value)
1520    if value is None:
1521        raise TypeError, "SimObject or SimObjectVector expected"
1522    return value
1523
1524baseClasses = allClasses.copy()
1525baseInstances = instanceDict.copy()
1526
1527def clear():
1528    global allClasses, instanceDict, noCxxHeader
1529
1530    allClasses = baseClasses.copy()
1531    instanceDict = baseInstances.copy()
1532    noCxxHeader = False
1533
1534# __all__ defines the list of symbols that get exported when
1535# 'from config import *' is invoked.  Try to keep this reasonably
1536# short to avoid polluting other namespaces.
1537__all__ = [
1538    'SimObject',
1539    'cxxMethod',
1540    'PyBindMethod',
1541    'PyBindProperty',
1542]
1543