1 # Copyright (c) 2012 ARM Limited
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.
13 # Copyright (c) 2004-2006 The Regents of The University of Michigan
14 # Copyright (c) 2010 Advanced Micro Devices, Inc.
15 # All rights reserved.
17 # Redistribution and use in source and binary forms, with or without
18 # modification, are permitted provided that the following conditions are
19 # met: redistributions of source code must retain the above copyright
20 # notice, this list of conditions and the following disclaimer;
21 # redistributions in binary form must reproduce the above copyright
22 # notice, this list of conditions and the following disclaimer in the
23 # documentation and/or other materials provided with the distribution;
24 # neither the name of the copyright holders nor the names of its
25 # contributors may be used to endorse or promote products derived from
26 # this software without specific prior written permission.
28 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
31 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
33 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
34 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
35 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
36 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
37 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
38 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 # Authors: Steve Reinhardt
45 from types
import FunctionType
, MethodType
, ModuleType
50 # Have to import params up top since Param is referenced on initial
51 # load (when SimObject class references Param to create a class
52 # variable, the 'name' param)...
53 from m5
.params
import *
54 # There are a few things we need that aren't in params.__all__ since
55 # normal users don't need them
56 from m5
.params
import ParamDesc
, VectorParamDesc
, \
57 isNullPointer
, SimObjectVector
, Port
59 from m5
.proxy
import *
60 from m5
.proxy
import isproxy
62 #####################################################################
64 # M5 Python Configuration Utility
66 # The basic idea is to write simple Python programs that build Python
67 # objects corresponding to M5 SimObjects for the desired simulation
68 # configuration. For now, the Python emits a .ini file that can be
69 # parsed by M5. In the future, some tighter integration between M5
70 # and the Python interpreter may allow bypassing the .ini file.
72 # Each SimObject class in M5 is represented by a Python class with the
73 # same name. The Python inheritance tree mirrors the M5 C++ tree
74 # (e.g., SimpleCPU derives from BaseCPU in both cases, and all
75 # SimObjects inherit from a single SimObject base class). To specify
76 # an instance of an M5 SimObject in a configuration, the user simply
77 # instantiates the corresponding Python object. The parameters for
78 # that SimObject are given by assigning to attributes of the Python
79 # object, either using keyword assignment in the constructor or in
80 # separate assignment statements. For example:
82 # cache = BaseCache(size='64KB')
83 # cache.hit_latency = 3
86 # The magic lies in the mapping of the Python attributes for SimObject
87 # classes to the actual SimObject parameter specifications. This
88 # allows parameter validity checking in the Python code. Continuing
89 # the example above, the statements "cache.blurfl=3" or
90 # "cache.assoc='hello'" would both result in runtime errors in Python,
91 # since the BaseCache object has no 'blurfl' parameter and the 'assoc'
92 # parameter requires an integer, respectively. This magic is done
93 # primarily by overriding the special __setattr__ method that controls
94 # assignment to object attributes.
96 # Once a set of Python objects have been instantiated in a hierarchy,
97 # calling 'instantiate(obj)' (where obj is the root of the hierarchy)
98 # will generate a .ini file.
100 #####################################################################
102 # list of all SimObject classes
105 # dict to look up SimObjects based on path
108 # Did any of the SimObjects lack a header file?
111 def public_value(key
, value
):
112 return key
.startswith('_') or \
113 isinstance(value
, (FunctionType
, MethodType
, ModuleType
,
116 # The metaclass for SimObject. This class controls how new classes
117 # that derive from SimObject are instantiated, and provides inherited
118 # class behavior (just like a class controls how instances of that
119 # class are instantiated, and provides inherited instance behavior).
120 class MetaSimObject(type):
121 # Attributes that can be set only at initialization time
122 init_keywords
= { 'abstract' : bool,
127 # Attributes that can be set any time
128 keywords
= { 'check' : FunctionType
}
130 # __new__ is called before __init__, and is where the statements
131 # in the body of the class definition get loaded into the class's
132 # __dict__. We intercept this to filter out parameter & port assignments
133 # and only allow "private" attributes to be passed to the base
134 # __new__ (starting with underscore).
135 def __new__(mcls
, name
, bases
, dict):
136 assert name
not in allClasses
, "SimObject %s already present" % name
138 # Copy "private" attributes, functions, and classes to the
139 # official dict. Everything else goes in _init_dict to be
140 # filtered in __init__.
143 for key
,val
in dict.items():
144 if public_value(key
, val
):
147 # must be a param/port setting
148 value_dict
[key
] = val
149 if 'abstract' not in value_dict
:
150 value_dict
['abstract'] = False
151 cls_dict
['_value_dict'] = value_dict
152 cls
= super(MetaSimObject
, mcls
).__new
__(mcls
, name
, bases
, cls_dict
)
153 if 'type' in value_dict
:
154 allClasses
[name
] = cls
157 # subclass initialization
158 def __init__(cls
, name
, bases
, dict):
159 # calls type.__init__()... I think that's a no-op, but leave
160 # it here just in case it's not.
161 super(MetaSimObject
, cls
).__init
__(name
, bases
, dict)
163 # initialize required attributes
165 # class-only attributes
166 cls
._params
= multidict() # param descriptions
167 cls
._ports
= multidict() # port descriptions
169 # class or instance attributes
170 cls
._values
= multidict() # param values
171 cls
._children
= multidict() # SimObject children
172 cls
._port
_refs
= multidict() # port ref objects
173 cls
._instantiated
= False # really instantiated, cloned, or subclassed
175 # We don't support multiple inheritance of sim objects. If you want
176 # to, you must fix multidict to deal with it properly. Non sim-objects
180 if isinstance(c
, MetaSimObject
):
183 raise TypeError, "SimObjects do not support multiple inheritance"
187 # Set up general inheritance via multidicts. A subclass will
188 # inherit all its settings from the base class. The only time
189 # the following is not true is when we define the SimObject
190 # class itself (in which case the multidicts have no parent).
191 if isinstance(base
, MetaSimObject
):
193 cls
._params
.parent
= base
._params
194 cls
._ports
.parent
= base
._ports
195 cls
._values
.parent
= base
._values
196 cls
._children
.parent
= base
._children
197 cls
._port
_refs
.parent
= base
._port
_refs
198 # mark base as having been subclassed
199 base
._instantiated
= True
203 # default keyword values
204 if 'type' in cls
._value
_dict
:
205 if 'cxx_class' not in cls
._value
_dict
:
206 cls
._value
_dict
['cxx_class'] = cls
._value
_dict
['type']
208 cls
._value
_dict
['cxx_type'] = '%s *' % cls
._value
_dict
['cxx_class']
210 if 'cxx_header' not in cls
._value
_dict
:
213 print >> sys
.stderr
, \
214 "warning: No header file specified for SimObject: %s" % name
216 # Export methods are automatically inherited via C++, so we
217 # don't want the method declarations to get inherited on the
218 # python side (and thus end up getting repeated in the wrapped
219 # versions of derived classes). The code below basicallly
220 # suppresses inheritance by substituting in the base (null)
221 # versions of these methods unless a different version is
222 # explicitly supplied.
223 for method_name
in ('export_methods', 'export_method_cxx_predecls',
224 'export_method_swig_predecls'):
225 if method_name
not in cls
.__dict
__:
226 base_method
= getattr(MetaSimObject
, method_name
)
227 m
= MethodType(base_method
, cls
, MetaSimObject
)
228 setattr(cls
, method_name
, m
)
230 # Now process the _value_dict items. They could be defining
231 # new (or overriding existing) parameters or ports, setting
232 # class keywords (e.g., 'abstract'), or setting parameter
233 # values or port bindings. The first 3 can only be set when
234 # the class is defined, so we handle them here. The others
235 # can be set later too, so just emulate that by calling
237 for key
,val
in cls
._value
_dict
.items():
239 if isinstance(val
, ParamDesc
):
240 cls
._new
_param
(key
, val
)
243 elif isinstance(val
, Port
):
244 cls
._new
_port
(key
, val
)
246 # init-time-only keywords
247 elif cls
.init_keywords
.has_key(key
):
248 cls
._set
_keyword
(key
, val
, cls
.init_keywords
[key
])
250 # default: use normal path (ends up in __setattr__)
252 setattr(cls
, key
, val
)
254 def _set_keyword(cls
, keyword
, val
, kwtype
):
255 if not isinstance(val
, kwtype
):
256 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
257 (keyword
, type(val
), kwtype
)
258 if isinstance(val
, FunctionType
):
259 val
= classmethod(val
)
260 type.__setattr
__(cls
, keyword
, val
)
262 def _new_param(cls
, name
, pdesc
):
263 # each param desc should be uniquely assigned to one variable
264 assert(not hasattr(pdesc
, 'name'))
266 cls
._params
[name
] = pdesc
267 if hasattr(pdesc
, 'default'):
268 cls
._set
_param
(name
, pdesc
.default
, pdesc
)
270 def _set_param(cls
, name
, value
, param
):
271 assert(param
.name
== name
)
273 value
= param
.convert(value
)
275 msg
= "%s\nError setting param %s.%s to %s\n" % \
276 (e
, cls
.__name
__, name
, value
)
279 cls
._values
[name
] = value
280 # if param value is a SimObject, make it a child too, so that
281 # it gets cloned properly when the class is instantiated
282 if isSimObjectOrVector(value
) and not value
.has_parent():
283 cls
._add
_cls
_child
(name
, value
)
285 def _add_cls_child(cls
, name
, child
):
286 # It's a little funky to have a class as a parent, but these
287 # objects should never be instantiated (only cloned, which
288 # clears the parent pointer), and this makes it clear that the
289 # object is not an orphan and can provide better error
291 child
.set_parent(cls
, name
)
292 cls
._children
[name
] = child
294 def _new_port(cls
, name
, port
):
295 # each port should be uniquely assigned to one variable
296 assert(not hasattr(port
, 'name'))
298 cls
._ports
[name
] = port
300 # same as _get_port_ref, effectively, but for classes
301 def _cls_get_port_ref(cls
, attr
):
302 # Return reference that can be assigned to another port
303 # via __setattr__. There is only ever one reference
304 # object per port, but we create them lazily here.
305 ref
= cls
._port
_refs
.get(attr
)
307 ref
= cls
._ports
[attr
].makeRef(cls
)
308 cls
._port
_refs
[attr
] = ref
311 # Set attribute (called on foo.attr = value when foo is an
312 # instance of class cls).
313 def __setattr__(cls
, attr
, value
):
314 # normal processing for private attributes
315 if public_value(attr
, value
):
316 type.__setattr
__(cls
, attr
, value
)
319 if cls
.keywords
.has_key(attr
):
320 cls
._set
_keyword
(attr
, value
, cls
.keywords
[attr
])
323 if cls
._ports
.has_key(attr
):
324 cls
._cls
_get
_port
_ref
(attr
).connect(value
)
327 if isSimObjectOrSequence(value
) and cls
._instantiated
:
328 raise RuntimeError, \
329 "cannot set SimObject parameter '%s' after\n" \
330 " class %s has been instantiated or subclassed" \
331 % (attr
, cls
.__name
__)
334 param
= cls
._params
.get(attr
)
336 cls
._set
_param
(attr
, value
, param
)
339 if isSimObjectOrSequence(value
):
340 # If RHS is a SimObject, it's an implicit child assignment.
341 cls
._add
_cls
_child
(attr
, coerceSimObjectOrVector(value
))
344 # no valid assignment... raise exception
345 raise AttributeError, \
346 "Class %s has no parameter \'%s\'" % (cls
.__name
__, attr
)
348 def __getattr__(cls
, attr
):
349 if attr
== 'cxx_class_path':
350 return cls
.cxx_class
.split('::')
352 if attr
== 'cxx_class_name':
353 return cls
.cxx_class_path
[-1]
355 if attr
== 'cxx_namespaces':
356 return cls
.cxx_class_path
[:-1]
358 if cls
._values
.has_key(attr
):
359 return cls
._values
[attr
]
361 if cls
._children
.has_key(attr
):
362 return cls
._children
[attr
]
364 raise AttributeError, \
365 "object '%s' has no attribute '%s'" % (cls
.__name
__, attr
)
370 # See ParamValue.cxx_predecls for description.
371 def cxx_predecls(cls
, code
):
372 code('#include "params/$cls.hh"')
374 # See ParamValue.swig_predecls for description.
375 def swig_predecls(cls
, code
):
376 code('%import "python/m5/internal/param_$cls.i"')
378 # Hook for exporting additional C++ methods to Python via SWIG.
379 # Default is none, override using @classmethod in class definition.
380 def export_methods(cls
, code
):
383 # Generate the code needed as a prerequisite for the C++ methods
384 # exported via export_methods() to be compiled in the _wrap.cc
385 # file. Typically generates one or more #include statements. If
386 # any methods are exported, typically at least the C++ header
387 # declaring the relevant SimObject class must be included.
388 def export_method_cxx_predecls(cls
, code
):
391 # Generate the code needed as a prerequisite for the C++ methods
392 # exported via export_methods() to be processed by SWIG.
393 # Typically generates one or more %include or %import statements.
394 # If any methods are exported, typically at least the C++ header
395 # declaring the relevant SimObject class must be included.
396 def export_method_swig_predecls(cls
, code
):
399 # Generate the declaration for this object for wrapping with SWIG.
400 # Generates code that goes into a SWIG .i file. Called from
402 def swig_decl(cls
, code
):
403 class_path
= cls
.cxx_class
.split('::')
404 classname
= class_path
[-1]
405 namespaces
= class_path
[:-1]
407 # The 'local' attribute restricts us to the params declared in
408 # the object itself, not including inherited params (which
409 # will also be inherited from the base class's param struct
411 params
= cls
._params
.local
.values()
412 ports
= cls
._ports
.local
414 code('%module(package="m5.internal") param_$cls')
417 code('#include "params/$cls.hh"')
419 param
.cxx_predecls(code
)
420 code('#include "${{cls.cxx_header}}"')
421 cls
.export_method_cxx_predecls(code
)
424 * This is a workaround for bug in swig. Prior to gcc 4.6.1 the STL
425 * headers like vector, string, etc. used to automatically pull in
426 * the cstddef header but starting with gcc 4.6.1 they no longer do.
427 * This leads to swig generated a file that does not compile so we
428 * explicitly include cstddef. Additionally, including version 2.0.4,
429 * swig uses ptrdiff_t without the std:: namespace prefix which is
430 * required with gcc 4.6.1. We explicitly provide access to it.
433 using std::ptrdiff_t;
439 param
.swig_predecls(code
)
440 cls
.export_method_swig_predecls(code
)
444 code('%import "python/m5/internal/param_${{cls._base}}.i"')
447 for ns
in namespaces
:
448 code('namespace $ns {')
451 code('// avoid name conflicts')
452 sep_string
= '_COLONS_'
453 flat_name
= sep_string
.join(class_path
)
454 code('%rename($flat_name) $classname;')
457 code('// stop swig from creating/wrapping default ctor/dtor')
458 code('%nodefault $classname;')
459 code('class $classname')
461 code(' : public ${{cls._base.cxx_class}}')
464 cls
.export_methods(code
)
467 for ns
in reversed(namespaces
):
468 code('} // namespace $ns')
471 code('%include "params/$cls.hh"')
474 # Generate the C++ declaration (.hh file) for this SimObject's
475 # param struct. Called from src/SConscript.
476 def cxx_param_decl(cls
, code
):
477 # The 'local' attribute restricts us to the params declared in
478 # the object itself, not including inherited params (which
479 # will also be inherited from the base class's param struct
481 params
= cls
._params
.local
.values()
482 ports
= cls
._ports
.local
484 ptypes
= [p
.ptype
for p
in params
]
486 print cls
, p
, p
.ptype_str
490 class_path
= cls
._value
_dict
['cxx_class'].split('::')
493 #ifndef __PARAMS__${cls}__
494 #define __PARAMS__${cls}__
498 # A forward class declaration is sufficient since we are just
499 # declaring a pointer.
500 for ns
in class_path
[:-1]:
501 code('namespace $ns {')
502 code('class $0;', class_path
[-1])
503 for ns
in reversed(class_path
[:-1]):
504 code('} // namespace $ns')
507 # The base SimObject has a couple of params that get
508 # automatically set from Python without being declared through
509 # the normal Param mechanism; we slip them in here (needed
510 # predecls now, actual declarations below)
522 param
.cxx_predecls(code
)
523 for port
in ports
.itervalues():
524 port
.cxx_predecls(code
)
528 code('#include "params/${{cls._base.type}}.hh"')
532 if issubclass(ptype
, Enum
):
533 code('#include "enums/${{ptype.__name__}}.hh"')
536 # now generate the actual param struct
537 code("struct ${cls}Params")
539 code(" : public ${{cls._base.type}}Params")
541 if not hasattr(cls
, 'abstract') or not cls
.abstract
:
542 if 'type' in cls
.__dict
__:
543 code(" ${{cls.cxx_type}} create();")
550 extern EventQueue mainEventQueue;
551 eventq = &mainEventQueue;
553 virtual ~SimObjectParams() {}
561 for port
in ports
.itervalues():
568 code('#endif // __PARAMS__${cls}__')
573 # The SimObject class is the root of the special hierarchy. Most of
574 # the code in this class deals with the configuration hierarchy itself
575 # (parent/child node relationships).
576 class SimObject(object):
577 # Specify metaclass. Any class inheriting from SimObject will
578 # get this metaclass.
579 __metaclass__
= MetaSimObject
582 cxx_header
= "sim/sim_object.hh"
585 def export_method_swig_predecls(cls
, code
):
587 %include <std_string.i>
591 def export_methods(cls
, code
):
600 void loadState(Checkpoint *cp);
606 unsigned int drain(Event *drain_event);
610 # Initialize new instance. For objects with SimObject-valued
611 # children, we need to recursively clone the classes represented
612 # by those param values as well in a consistent "deep copy"-style
613 # fashion. That is, we want to make sure that each instance is
614 # cloned only once, and that if there are multiple references to
615 # the same original object, we end up with the corresponding
616 # cloned references all pointing to the same cloned instance.
617 def __init__(self
, **kwargs
):
618 ancestor
= kwargs
.get('_ancestor')
619 memo_dict
= kwargs
.get('_memo')
620 if memo_dict
is None:
621 # prepare to memoize any recursively instantiated objects
624 # memoize me now to avoid problems with recursive calls
625 memo_dict
[ancestor
] = self
628 ancestor
= self
.__class
__
629 ancestor
._instantiated
= True
631 # initialize required attributes
634 self
._ccObject
= None # pointer to C++ object
635 self
._ccParams
= None
636 self
._instantiated
= False # really "cloned"
638 # Clone children specified at class level. No need for a
639 # multidict here since we will be cloning everything.
640 # Do children before parameter values so that children that
641 # are also param values get cloned properly.
643 for key
,val
in ancestor
._children
.iteritems():
644 self
.add_child(key
, val(_memo
=memo_dict
))
646 # Inherit parameter values from class using multidict so
647 # individual value settings can be overridden but we still
648 # inherit late changes to non-overridden class values.
649 self
._values
= multidict(ancestor
._values
)
650 # clone SimObject-valued parameters
651 for key
,val
in ancestor
._values
.iteritems():
652 val
= tryAsSimObjectOrVector(val
)
654 self
._values
[key
] = val(_memo
=memo_dict
)
656 # clone port references. no need to use a multidict here
657 # since we will be creating new references for all ports.
659 for key
,val
in ancestor
._port
_refs
.iteritems():
660 self
._port
_refs
[key
] = val
.clone(self
, memo_dict
)
661 # apply attribute assignments from keyword args, if any
662 for key
,val
in kwargs
.iteritems():
663 setattr(self
, key
, val
)
665 # "Clone" the current instance by creating another instance of
666 # this instance's class, but that inherits its parameter values
667 # and port mappings from the current instance. If we're in a
668 # "deep copy" recursive clone, check the _memo dict to see if
669 # we've already cloned this instance.
670 def __call__(self
, **kwargs
):
671 memo_dict
= kwargs
.get('_memo')
672 if memo_dict
is None:
673 # no memo_dict: must be top-level clone operation.
674 # this is only allowed at the root of a hierarchy
676 raise RuntimeError, "attempt to clone object %s " \
677 "not at the root of a tree (parent = %s)" \
678 % (self
, self
._parent
)
679 # create a new dict and use that.
681 kwargs
['_memo'] = memo_dict
682 elif memo_dict
.has_key(self
):
683 # clone already done & memoized
684 return memo_dict
[self
]
685 return self
.__class
__(_ancestor
= self
, **kwargs
)
687 def _get_port_ref(self
, attr
):
688 # Return reference that can be assigned to another port
689 # via __setattr__. There is only ever one reference
690 # object per port, but we create them lazily here.
691 ref
= self
._port
_refs
.get(attr
)
693 ref
= self
._ports
[attr
].makeRef(self
)
694 self
._port
_refs
[attr
] = ref
697 def __getattr__(self
, attr
):
698 if self
._ports
.has_key(attr
):
699 return self
._get
_port
_ref
(attr
)
701 if self
._values
.has_key(attr
):
702 return self
._values
[attr
]
704 if self
._children
.has_key(attr
):
705 return self
._children
[attr
]
707 # If the attribute exists on the C++ object, transparently
708 # forward the reference there. This is typically used for
709 # SWIG-wrapped methods such as init(), regStats(),
710 # resetStats(), startup(), drain(), and
712 if self
._ccObject
and hasattr(self
._ccObject
, attr
):
713 return getattr(self
._ccObject
, attr
)
715 raise AttributeError, "object '%s' has no attribute '%s'" \
716 % (self
.__class
__.__name
__, attr
)
718 # Set attribute (called on foo.attr = value when foo is an
719 # instance of class cls).
720 def __setattr__(self
, attr
, value
):
721 # normal processing for private attributes
722 if attr
.startswith('_'):
723 object.__setattr
__(self
, attr
, value
)
726 if self
._ports
.has_key(attr
):
727 # set up port connection
728 self
._get
_port
_ref
(attr
).connect(value
)
731 if isSimObjectOrSequence(value
) and self
._instantiated
:
732 raise RuntimeError, \
733 "cannot set SimObject parameter '%s' after\n" \
734 " instance been cloned %s" % (attr
, `self`
)
736 param
= self
._params
.get(attr
)
739 value
= param
.convert(value
)
741 msg
= "%s\nError setting param %s.%s to %s\n" % \
742 (e
, self
.__class
__.__name
__, attr
, value
)
745 self
._values
[attr
] = value
746 # implicitly parent unparented objects assigned as params
747 if isSimObjectOrVector(value
) and not value
.has_parent():
748 self
.add_child(attr
, value
)
751 # if RHS is a SimObject, it's an implicit child assignment
752 if isSimObjectOrSequence(value
):
753 self
.add_child(attr
, value
)
756 # no valid assignment... raise exception
757 raise AttributeError, "Class %s has no parameter %s" \
758 % (self
.__class
__.__name
__, attr
)
761 # this hack allows tacking a '[0]' onto parameters that may or may
762 # not be vectors, and always getting the first element (e.g. cpus)
763 def __getitem__(self
, key
):
766 raise TypeError, "Non-zero index '%s' to SimObject" % key
768 # Also implemented by SimObjectVector
769 def clear_parent(self
, old_parent
):
770 assert self
._parent
is old_parent
773 # Also implemented by SimObjectVector
774 def set_parent(self
, parent
, name
):
775 self
._parent
= parent
778 # Also implemented by SimObjectVector
782 # Also implemented by SimObjectVector
783 def has_parent(self
):
784 return self
._parent
is not None
786 # clear out child with given name. This code is not likely to be exercised.
787 # See comment in add_child.
788 def clear_child(self
, name
):
789 child
= self
._children
[name
]
790 child
.clear_parent(self
)
791 del self
._children
[name
]
793 # Add a new child to this object.
794 def add_child(self
, name
, child
):
795 child
= coerceSimObjectOrVector(child
)
796 if child
.has_parent():
797 print "warning: add_child('%s'): child '%s' already has parent" % \
798 (name
, child
.get_name())
799 if self
._children
.has_key(name
):
800 # This code path had an undiscovered bug that would make it fail
801 # at runtime. It had been here for a long time and was only
802 # exposed by a buggy script. Changes here will probably not be
803 # exercised without specialized testing.
804 self
.clear_child(name
)
805 child
.set_parent(self
, name
)
806 self
._children
[name
] = child
808 # Take SimObject-valued parameters that haven't been explicitly
809 # assigned as children and make them children of the object that
810 # they were assigned to as a parameter value. This guarantees
811 # that when we instantiate all the parameter objects we're still
812 # inside the configuration hierarchy.
813 def adoptOrphanParams(self
):
814 for key
,val
in self
._values
.iteritems():
815 if not isSimObjectVector(val
) and isSimObjectSequence(val
):
816 # need to convert raw SimObject sequences to
817 # SimObjectVector class so we can call has_parent()
818 val
= SimObjectVector(val
)
819 self
._values
[key
] = val
820 if isSimObjectOrVector(val
) and not val
.has_parent():
821 print "warning: %s adopting orphan SimObject param '%s'" \
823 self
.add_child(key
, val
)
827 return '<orphan %s>' % self
.__class
__
828 ppath
= self
._parent
.path()
831 return ppath
+ "." + self
._name
839 def find_any(self
, ptype
):
840 if isinstance(self
, ptype
):
844 for child
in self
._children
.itervalues():
845 if isinstance(child
, ptype
):
846 if found_obj
!= None and child
!= found_obj
:
847 raise AttributeError, \
848 'parent.any matched more than one: %s %s' % \
849 (found_obj
.path
, child
.path
)
852 for pname
,pdesc
in self
._params
.iteritems():
853 if issubclass(pdesc
.ptype
, ptype
):
854 match_obj
= self
._values
[pname
]
855 if found_obj
!= None and found_obj
!= match_obj
:
856 raise AttributeError, \
857 'parent.any matched more than one: %s and %s' % (found_obj
.path
, match_obj
.path
)
858 found_obj
= match_obj
859 return found_obj
, found_obj
!= None
861 def find_all(self
, ptype
):
864 for child
in self
._children
.itervalues():
865 if isinstance(child
, ptype
) and not isproxy(child
) and \
866 not isNullPointer(child
):
868 if isSimObject(child
):
869 # also add results from the child itself
870 child_all
, done
= child
.find_all(ptype
)
871 all
.update(dict(zip(child_all
, [done
] * len(child_all
))))
873 for pname
,pdesc
in self
._params
.iteritems():
874 if issubclass(pdesc
.ptype
, ptype
):
875 match_obj
= self
._values
[pname
]
876 if not isproxy(match_obj
) and not isNullPointer(match_obj
):
877 all
[match_obj
] = True
878 return all
.keys(), True
880 def unproxy(self
, base
):
883 def unproxyParams(self
):
884 for param
in self
._params
.iterkeys():
885 value
= self
._values
.get(param
)
886 if value
!= None and isproxy(value
):
888 value
= value
.unproxy(self
)
890 print "Error in unproxying param '%s' of %s" % \
893 setattr(self
, param
, value
)
895 # Unproxy ports in sorted order so that 'append' operations on
896 # vector ports are done in a deterministic fashion.
897 port_names
= self
._ports
.keys()
899 for port_name
in port_names
:
900 port
= self
._port
_refs
.get(port_name
)
904 def print_ini(self
, ini_file
):
905 print >>ini_file
, '[' + self
.path() + ']' # .ini section header
907 instanceDict
[self
.path()] = self
909 if hasattr(self
, 'type'):
910 print >>ini_file
, 'type=%s' % self
.type
912 if len(self
._children
.keys()):
913 print >>ini_file
, 'children=%s' % \
914 ' '.join(self
._children
[n
].get_name() \
915 for n
in sorted(self
._children
.keys()))
917 for param
in sorted(self
._params
.keys()):
918 value
= self
._values
.get(param
)
920 print >>ini_file
, '%s=%s' % (param
,
921 self
._values
[param
].ini_str())
923 for port_name
in sorted(self
._ports
.keys()):
924 port
= self
._port
_refs
.get(port_name
, None)
926 print >>ini_file
, '%s=%s' % (port_name
, port
.ini_str())
928 print >>ini_file
# blank line between objects
930 # generate a tree of dictionaries expressing all the parameters in the
931 # instantiated system for use by scripts that want to do power, thermal
932 # visualization, and other similar tasks
933 def get_config_as_dict(self
):
935 if hasattr(self
, 'type'):
937 if hasattr(self
, 'cxx_class'):
938 d
.cxx_class
= self
.cxx_class
939 # Add the name and path of this object to be able to link to
941 d
.name
= self
.get_name()
944 for param
in sorted(self
._params
.keys()):
945 value
= self
._values
.get(param
)
948 # Use native type for those supported by JSON and
949 # strings for everything else. skipkeys=True seems
950 # to not work as well as one would hope
951 if type(self
._values
[param
].value
) in \
952 [str, unicode, int, long, float, bool, None]:
953 d
[param
] = self
._values
[param
].value
955 d
[param
] = str(self
._values
[param
])
957 except AttributeError:
960 for n
in sorted(self
._children
.keys()):
961 child
= self
._children
[n
]
962 # Use the name of the attribute (and not get_name()) as
963 # the key in the JSON dictionary to capture the hierarchy
964 # in the Python code that assembled this system
965 d
[n
] = child
.get_config_as_dict()
967 for port_name
in sorted(self
._ports
.keys()):
968 port
= self
._port
_refs
.get(port_name
, None)
970 # Represent each port with a dictionary containing the
971 # prominent attributes
972 d
[port_name
] = port
.get_config_as_dict()
976 def getCCParams(self
):
978 return self
._ccParams
980 cc_params_struct
= getattr(m5
.internal
.params
, '%sParams' % self
.type)
981 cc_params
= cc_params_struct()
982 cc_params
.pyobj
= self
983 cc_params
.name
= str(self
)
985 param_names
= self
._params
.keys()
987 for param
in param_names
:
988 value
= self
._values
.get(param
)
990 fatal("%s.%s without default or user set value",
993 value
= value
.getValue()
994 if isinstance(self
._params
[param
], VectorParamDesc
):
995 assert isinstance(value
, list)
996 vec
= getattr(cc_params
, param
)
1001 setattr(cc_params
, param
, value
)
1003 port_names
= self
._ports
.keys()
1005 for port_name
in port_names
:
1006 port
= self
._port
_refs
.get(port_name
, None)
1008 port_count
= len(port
)
1011 setattr(cc_params
, 'port_' + port_name
+ '_connection_count',
1013 self
._ccParams
= cc_params
1014 return self
._ccParams
1016 # Get C++ object corresponding to this object, calling C++ if
1017 # necessary to construct it. Does *not* recursively create
1019 def getCCObject(self
):
1020 if not self
._ccObject
:
1021 # Make sure this object is in the configuration hierarchy
1022 if not self
._parent
and not isRoot(self
):
1023 raise RuntimeError, "Attempt to instantiate orphan node"
1024 # Cycles in the configuration hierarchy are not supported. This
1025 # will catch the resulting recursion and stop.
1027 params
= self
.getCCParams()
1028 self
._ccObject
= params
.create()
1029 elif self
._ccObject
== -1:
1030 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
1032 return self
._ccObject
1034 def descendants(self
):
1036 for child
in self
._children
.itervalues():
1037 for obj
in child
.descendants():
1040 # Call C++ to create C++ object corresponding to this object
1041 def createCCObject(self
):
1043 self
.getCCObject() # force creation
1046 return self
.getCCObject()
1048 # Create C++ port connections corresponding to the connections in
1050 def connectPorts(self
):
1051 for portRef
in self
._port
_refs
.itervalues():
1054 # Function to provide to C++ so it can look up instances based on paths
1055 def resolveSimObject(name
):
1056 obj
= instanceDict
[name
]
1057 return obj
.getCCObject()
1059 def isSimObject(value
):
1060 return isinstance(value
, SimObject
)
1062 def isSimObjectClass(value
):
1063 return issubclass(value
, SimObject
)
1065 def isSimObjectVector(value
):
1066 return isinstance(value
, SimObjectVector
)
1068 def isSimObjectSequence(value
):
1069 if not isinstance(value
, (list, tuple)) or len(value
) == 0:
1073 if not isNullPointer(val
) and not isSimObject(val
):
1078 def isSimObjectOrSequence(value
):
1079 return isSimObject(value
) or isSimObjectSequence(value
)
1082 from m5
.objects
import Root
1083 return obj
and obj
is Root
.getInstance()
1085 def isSimObjectOrVector(value
):
1086 return isSimObject(value
) or isSimObjectVector(value
)
1088 def tryAsSimObjectOrVector(value
):
1089 if isSimObjectOrVector(value
):
1091 if isSimObjectSequence(value
):
1092 return SimObjectVector(value
)
1095 def coerceSimObjectOrVector(value
):
1096 value
= tryAsSimObjectOrVector(value
)
1098 raise TypeError, "SimObject or SimObjectVector expected"
1101 baseClasses
= allClasses
.copy()
1102 baseInstances
= instanceDict
.copy()
1105 global allClasses
, instanceDict
, noCxxHeader
1107 allClasses
= baseClasses
.copy()
1108 instanceDict
= baseInstances
.copy()
1111 # __all__ defines the list of symbols that get exported when
1112 # 'from config import *' is invoked. Try to keep this reasonably
1113 # short to avoid polluting other namespaces.
1114 __all__
= [ 'SimObject' ]