8ef22be4e3f43438f04da55a9a9ed4526b2ef88e
1 # Copyright (c) 2004-2006 The Regents of The University of Michigan
4 # Redistribution and use in source and binary forms, with or without
5 # modification, are permitted provided that the following conditions are
6 # met: redistributions of source code must retain the above copyright
7 # notice, this list of conditions and the following disclaimer;
8 # redistributions in binary form must reproduce the above copyright
9 # notice, this list of conditions and the following disclaimer in the
10 # documentation and/or other materials provided with the distribution;
11 # neither the name of the copyright holders nor the names of its
12 # contributors may be used to endorse or promote products derived from
13 # this software without specific prior written permission.
15 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
20 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 # Authors: Steve Reinhardt
38 # These utility functions have to come first because they're
39 # referenced in params.py... otherwise they won't be defined when we
40 # import params below, and the recursive import of this file from
41 # params.py will not find these names.
42 def isSimObject(value
):
43 return isinstance(value
, SimObject
)
45 def isSimObjectClass(value
):
46 return issubclass(value
, SimObject
)
48 def isSimObjectSequence(value
):
49 if not isinstance(value
, (list, tuple)) or len(value
) == 0:
53 if not isNullPointer(val
) and not isSimObject(val
):
58 def isSimObjectOrSequence(value
):
59 return isSimObject(value
) or isSimObjectSequence(value
)
61 # Have to import params up top since Param is referenced on initial
62 # load (when SimObject class references Param to create a class
63 # variable, the 'name' param)...
65 # There are a few things we need that aren't in params.__all__ since
66 # normal users don't need them
67 from params
import ParamDesc
, VectorParamDesc
, isNullPointer
, SimObjVector
76 #####################################################################
78 # M5 Python Configuration Utility
80 # The basic idea is to write simple Python programs that build Python
81 # objects corresponding to M5 SimObjects for the desired simulation
82 # configuration. For now, the Python emits a .ini file that can be
83 # parsed by M5. In the future, some tighter integration between M5
84 # and the Python interpreter may allow bypassing the .ini file.
86 # Each SimObject class in M5 is represented by a Python class with the
87 # same name. The Python inheritance tree mirrors the M5 C++ tree
88 # (e.g., SimpleCPU derives from BaseCPU in both cases, and all
89 # SimObjects inherit from a single SimObject base class). To specify
90 # an instance of an M5 SimObject in a configuration, the user simply
91 # instantiates the corresponding Python object. The parameters for
92 # that SimObject are given by assigning to attributes of the Python
93 # object, either using keyword assignment in the constructor or in
94 # separate assignment statements. For example:
96 # cache = BaseCache(size='64KB')
97 # cache.hit_latency = 3
100 # The magic lies in the mapping of the Python attributes for SimObject
101 # classes to the actual SimObject parameter specifications. This
102 # allows parameter validity checking in the Python code. Continuing
103 # the example above, the statements "cache.blurfl=3" or
104 # "cache.assoc='hello'" would both result in runtime errors in Python,
105 # since the BaseCache object has no 'blurfl' parameter and the 'assoc'
106 # parameter requires an integer, respectively. This magic is done
107 # primarily by overriding the special __setattr__ method that controls
108 # assignment to object attributes.
110 # Once a set of Python objects have been instantiated in a hierarchy,
111 # calling 'instantiate(obj)' (where obj is the root of the hierarchy)
112 # will generate a .ini file.
114 #####################################################################
116 # list of all SimObject classes
119 # dict to look up SimObjects based on path
122 # The metaclass for SimObject. This class controls how new classes
123 # that derive from SimObject are instantiated, and provides inherited
124 # class behavior (just like a class controls how instances of that
125 # class are instantiated, and provides inherited instance behavior).
126 class MetaSimObject(type):
127 # Attributes that can be set only at initialization time
128 init_keywords
= { 'abstract' : types
.BooleanType
,
129 'cxx_class' : types
.StringType
,
130 'cxx_type' : types
.StringType
,
131 'cxx_predecls' : types
.ListType
,
132 'swig_objdecls' : types
.ListType
,
133 'swig_predecls' : types
.ListType
,
134 'type' : types
.StringType
}
135 # Attributes that can be set any time
136 keywords
= { 'check' : types
.FunctionType
}
138 # __new__ is called before __init__, and is where the statements
139 # in the body of the class definition get loaded into the class's
140 # __dict__. We intercept this to filter out parameter & port assignments
141 # and only allow "private" attributes to be passed to the base
142 # __new__ (starting with underscore).
143 def __new__(mcls
, name
, bases
, dict):
144 assert name
not in allClasses
146 # Copy "private" attributes, functions, and classes to the
147 # official dict. Everything else goes in _init_dict to be
148 # filtered in __init__.
151 for key
,val
in dict.items():
152 if key
.startswith('_') or isinstance(val
, (types
.FunctionType
,
156 # must be a param/port setting
157 value_dict
[key
] = val
158 if 'abstract' not in value_dict
:
159 value_dict
['abstract'] = False
160 cls_dict
['_value_dict'] = value_dict
161 cls
= super(MetaSimObject
, mcls
).__new
__(mcls
, name
, bases
, cls_dict
)
162 if 'type' in value_dict
:
163 allClasses
[name
] = cls
166 # subclass initialization
167 def __init__(cls
, name
, bases
, dict):
168 # calls type.__init__()... I think that's a no-op, but leave
169 # it here just in case it's not.
170 super(MetaSimObject
, cls
).__init
__(name
, bases
, dict)
172 # initialize required attributes
174 # class-only attributes
175 cls
._params
= multidict() # param descriptions
176 cls
._ports
= multidict() # port descriptions
178 # class or instance attributes
179 cls
._values
= multidict() # param values
180 cls
._port
_refs
= multidict() # port ref objects
181 cls
._instantiated
= False # really instantiated, cloned, or subclassed
183 # We don't support multiple inheritance. If you want to, you
184 # must fix multidict to deal with it properly.
186 raise TypeError, "SimObjects do not support multiple inheritance"
190 # Set up general inheritance via multidicts. A subclass will
191 # inherit all its settings from the base class. The only time
192 # the following is not true is when we define the SimObject
193 # class itself (in which case the multidicts have no parent).
194 if isinstance(base
, MetaSimObject
):
196 cls
._params
.parent
= base
._params
197 cls
._ports
.parent
= base
._ports
198 cls
._values
.parent
= base
._values
199 cls
._port
_refs
.parent
= base
._port
_refs
200 # mark base as having been subclassed
201 base
._instantiated
= True
205 # default keyword values
206 if 'type' in cls
._value
_dict
:
207 if 'cxx_class' not in cls
._value
_dict
:
208 cls
._value
_dict
['cxx_class'] = cls
._value
_dict
['type']
210 cls
._value
_dict
['cxx_type'] = '%s *' % cls
._value
_dict
['cxx_class']
212 if 'cxx_predecls' not in cls
._value
_dict
:
213 # A forward class declaration is sufficient since we are
214 # just declaring a pointer.
215 class_path
= cls
._value
_dict
['cxx_class'].split('::')
217 decl
= 'class %s;' % class_path
[0]
218 for ns
in class_path
[1:]:
219 decl
= 'namespace %s { %s }' % (ns
, decl
)
220 cls
._value
_dict
['cxx_predecls'] = [decl
]
222 if 'swig_predecls' not in cls
._value
_dict
:
223 # A forward class declaration is sufficient since we are
224 # just declaring a pointer.
225 cls
._value
_dict
['swig_predecls'] = \
226 cls
._value
_dict
['cxx_predecls']
228 if 'swig_objdecls' not in cls
._value
_dict
:
229 cls
._value
_dict
['swig_objdecls'] = []
231 # Now process the _value_dict items. They could be defining
232 # new (or overriding existing) parameters or ports, setting
233 # class keywords (e.g., 'abstract'), or setting parameter
234 # values or port bindings. The first 3 can only be set when
235 # the class is defined, so we handle them here. The others
236 # can be set later too, so just emulate that by calling
238 for key
,val
in cls
._value
_dict
.items():
240 if isinstance(val
, ParamDesc
):
241 cls
._new
_param
(key
, val
)
244 elif isinstance(val
, Port
):
245 cls
._new
_port
(key
, val
)
247 # init-time-only keywords
248 elif cls
.init_keywords
.has_key(key
):
249 cls
._set
_keyword
(key
, val
, cls
.init_keywords
[key
])
251 # default: use normal path (ends up in __setattr__)
253 setattr(cls
, key
, val
)
255 def _set_keyword(cls
, keyword
, val
, kwtype
):
256 if not isinstance(val
, kwtype
):
257 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
258 (keyword
, type(val
), kwtype
)
259 if isinstance(val
, types
.FunctionType
):
260 val
= classmethod(val
)
261 type.__setattr
__(cls
, keyword
, val
)
263 def _new_param(cls
, name
, pdesc
):
264 # each param desc should be uniquely assigned to one variable
265 assert(not hasattr(pdesc
, 'name'))
267 cls
._params
[name
] = pdesc
268 if hasattr(pdesc
, 'default'):
269 cls
._set
_param
(name
, pdesc
.default
, pdesc
)
271 def _set_param(cls
, name
, value
, param
):
272 assert(param
.name
== name
)
274 cls
._values
[name
] = param
.convert(value
)
276 msg
= "%s\nError setting param %s.%s to %s\n" % \
277 (e
, cls
.__name
__, name
, value
)
281 def _new_port(cls
, name
, port
):
282 # each port should be uniquely assigned to one variable
283 assert(not hasattr(port
, 'name'))
285 cls
._ports
[name
] = port
286 if hasattr(port
, 'default'):
287 cls
._cls
_get
_port
_ref
(name
).connect(port
.default
)
289 # same as _get_port_ref, effectively, but for classes
290 def _cls_get_port_ref(cls
, attr
):
291 # Return reference that can be assigned to another port
292 # via __setattr__. There is only ever one reference
293 # object per port, but we create them lazily here.
294 ref
= cls
._port
_refs
.get(attr
)
296 ref
= cls
._ports
[attr
].makeRef(cls
)
297 cls
._port
_refs
[attr
] = ref
300 # Set attribute (called on foo.attr = value when foo is an
301 # instance of class cls).
302 def __setattr__(cls
, attr
, value
):
303 # normal processing for private attributes
304 if attr
.startswith('_'):
305 type.__setattr
__(cls
, attr
, value
)
308 if cls
.keywords
.has_key(attr
):
309 cls
._set
_keyword
(attr
, value
, cls
.keywords
[attr
])
312 if cls
._ports
.has_key(attr
):
313 cls
._cls
_get
_port
_ref
(attr
).connect(value
)
316 if isSimObjectOrSequence(value
) and cls
._instantiated
:
317 raise RuntimeError, \
318 "cannot set SimObject parameter '%s' after\n" \
319 " class %s has been instantiated or subclassed" \
320 % (attr
, cls
.__name
__)
323 param
= cls
._params
.get(attr
)
325 cls
._set
_param
(attr
, value
, param
)
328 if isSimObjectOrSequence(value
):
329 # If RHS is a SimObject, it's an implicit child assignment.
330 # Classes don't have children, so we just put this object
331 # in _values; later, each instance will do a 'setattr(self,
332 # attr, _values[attr])' in SimObject.__init__ which will
333 # add this object as a child.
334 cls
._values
[attr
] = value
337 # no valid assignment... raise exception
338 raise AttributeError, \
339 "Class %s has no parameter \'%s\'" % (cls
.__name
__, attr
)
341 def __getattr__(cls
, attr
):
342 if cls
._values
.has_key(attr
):
343 return cls
._values
[attr
]
345 raise AttributeError, \
346 "object '%s' has no attribute '%s'" % (cls
.__name
__, attr
)
352 code
= "#ifndef __PARAMS__%s\n" % cls
353 code
+= "#define __PARAMS__%s\n\n" % cls
355 # The 'dict' attribute restricts us to the params declared in
356 # the object itself, not including inherited params (which
357 # will also be inherited from the base class's param struct
359 params
= cls
._params
.local
.values()
361 ptypes
= [p
.ptype
for p
in params
]
363 print cls
, p
, p
.ptype_str
367 # get a list of lists of predeclaration lines
369 predecls
.extend(cls
.cxx_predecls
)
371 predecls
.extend(p
.cxx_predecls())
372 # remove redundant lines
375 if pd
not in predecls2
:
378 code
+= "\n".join(predecls2
)
382 code
+= '#include "params/%s.hh"\n\n' % cls
._base
.type
385 if issubclass(ptype
, Enum
):
386 code
+= '#include "enums/%s.hh"\n' % ptype
.__name
__
389 code
+= cls
.cxx_struct(cls
._base
, params
)
391 # close #ifndef __PARAMS__* guard
395 def cxx_struct(cls
, base
, params
):
397 return '#include "sim/sim_object_params.hh"\n'
399 # now generate the actual param struct
400 code
= "struct %sParams" % cls
402 code
+= " : public %sParams" % base
.type
404 if not hasattr(cls
, 'abstract') or not cls
.abstract
:
405 if 'type' in cls
.__dict
__:
406 code
+= " %s create();\n" % cls
.cxx_type
407 decls
= [p
.cxx_decl() for p
in params
]
409 code
+= "".join([" %s\n" % d
for d
in decls
])
415 code
= '%%module %s\n' % cls
418 code
+= '#include "params/%s.hh"\n' % cls
421 # The 'dict' attribute restricts us to the params declared in
422 # the object itself, not including inherited params (which
423 # will also be inherited from the base class's param struct
425 params
= cls
._params
.local
.values()
426 ptypes
= [p
.ptype
for p
in params
]
428 # get a list of lists of predeclaration lines
430 predecls
.extend([ p
.swig_predecls() for p
in params
])
432 predecls
= reduce(lambda x
,y
:x
+y
, predecls
, [])
433 # remove redundant lines
436 if pd
not in predecls2
:
439 code
+= "\n".join(predecls2
)
443 code
+= '%%import "params/%s.i"\n\n' % cls
._base
.type
446 if issubclass(ptype
, Enum
):
447 code
+= '%%import "enums/%s.hh"\n' % ptype
.__name
__
450 code
+= '%%import "params/%s_type.hh"\n\n' % cls
451 code
+= '%%include "params/%s.hh"\n\n' % cls
455 # The SimObject class is the root of the special hierarchy. Most of
456 # the code in this class deals with the configuration hierarchy itself
457 # (parent/child node relationships).
458 class SimObject(object):
459 # Specify metaclass. Any class inheriting from SimObject will
460 # get this metaclass.
461 __metaclass__
= MetaSimObject
465 swig_objdecls
= [ '%include "python/swig/sim_object.i"' ]
467 # Initialize new instance. For objects with SimObject-valued
468 # children, we need to recursively clone the classes represented
469 # by those param values as well in a consistent "deep copy"-style
470 # fashion. That is, we want to make sure that each instance is
471 # cloned only once, and that if there are multiple references to
472 # the same original object, we end up with the corresponding
473 # cloned references all pointing to the same cloned instance.
474 def __init__(self
, **kwargs
):
475 ancestor
= kwargs
.get('_ancestor')
476 memo_dict
= kwargs
.get('_memo')
477 if memo_dict
is None:
478 # prepare to memoize any recursively instantiated objects
481 # memoize me now to avoid problems with recursive calls
482 memo_dict
[ancestor
] = self
485 ancestor
= self
.__class
__
486 ancestor
._instantiated
= True
488 # initialize required attributes
491 self
._ccObject
= None # pointer to C++ object
492 self
._ccParams
= None
493 self
._instantiated
= False # really "cloned"
495 # Inherit parameter values from class using multidict so
496 # individual value settings can be overridden.
497 self
._values
= multidict(ancestor
._values
)
498 # clone SimObject-valued parameters
499 for key
,val
in ancestor
._values
.iteritems():
501 setattr(self
, key
, val(_memo
=memo_dict
))
502 elif isSimObjectSequence(val
) and len(val
):
503 setattr(self
, key
, [ v(_memo
=memo_dict
) for v
in val
])
504 # clone port references. no need to use a multidict here
505 # since we will be creating new references for all ports.
507 for key
,val
in ancestor
._port
_refs
.iteritems():
508 self
._port
_refs
[key
] = val
.clone(self
, memo_dict
)
509 # apply attribute assignments from keyword args, if any
510 for key
,val
in kwargs
.iteritems():
511 setattr(self
, key
, val
)
513 # "Clone" the current instance by creating another instance of
514 # this instance's class, but that inherits its parameter values
515 # and port mappings from the current instance. If we're in a
516 # "deep copy" recursive clone, check the _memo dict to see if
517 # we've already cloned this instance.
518 def __call__(self
, **kwargs
):
519 memo_dict
= kwargs
.get('_memo')
520 if memo_dict
is None:
521 # no memo_dict: must be top-level clone operation.
522 # this is only allowed at the root of a hierarchy
524 raise RuntimeError, "attempt to clone object %s " \
525 "not at the root of a tree (parent = %s)" \
526 % (self
, self
._parent
)
527 # create a new dict and use that.
529 kwargs
['_memo'] = memo_dict
530 elif memo_dict
.has_key(self
):
531 # clone already done & memoized
532 return memo_dict
[self
]
533 return self
.__class
__(_ancestor
= self
, **kwargs
)
535 def _get_port_ref(self
, attr
):
536 # Return reference that can be assigned to another port
537 # via __setattr__. There is only ever one reference
538 # object per port, but we create them lazily here.
539 ref
= self
._port
_refs
.get(attr
)
541 ref
= self
._ports
[attr
].makeRef(self
)
542 self
._port
_refs
[attr
] = ref
545 def __getattr__(self
, attr
):
546 if self
._ports
.has_key(attr
):
547 return self
._get
_port
_ref
(attr
)
549 if self
._values
.has_key(attr
):
550 return self
._values
[attr
]
552 raise AttributeError, "object '%s' has no attribute '%s'" \
553 % (self
.__class
__.__name
__, attr
)
555 # Set attribute (called on foo.attr = value when foo is an
556 # instance of class cls).
557 def __setattr__(self
, attr
, value
):
558 # normal processing for private attributes
559 if attr
.startswith('_'):
560 object.__setattr
__(self
, attr
, value
)
563 if self
._ports
.has_key(attr
):
564 # set up port connection
565 self
._get
_port
_ref
(attr
).connect(value
)
568 if isSimObjectOrSequence(value
) and self
._instantiated
:
569 raise RuntimeError, \
570 "cannot set SimObject parameter '%s' after\n" \
571 " instance been cloned %s" % (attr
, `self`
)
573 # must be SimObject param
574 param
= self
._params
.get(attr
)
577 value
= param
.convert(value
)
579 msg
= "%s\nError setting param %s.%s to %s\n" % \
580 (e
, self
.__class
__.__name
__, attr
, value
)
583 self
._set
_child
(attr
, value
)
586 if isSimObjectOrSequence(value
):
587 self
._set
_child
(attr
, value
)
590 # no valid assignment... raise exception
591 raise AttributeError, "Class %s has no parameter %s" \
592 % (self
.__class
__.__name
__, attr
)
595 # this hack allows tacking a '[0]' onto parameters that may or may
596 # not be vectors, and always getting the first element (e.g. cpus)
597 def __getitem__(self
, key
):
600 raise TypeError, "Non-zero index '%s' to SimObject" % key
602 # clear out children with given name, even if it's a vector
603 def clear_child(self
, name
):
604 if not self
._children
.has_key(name
):
606 child
= self
._children
[name
]
607 if isinstance(child
, SimObjVector
):
608 for i
in xrange(len(child
)):
609 del self
._children
["s%d" % (name
, i
)]
610 del self
._children
[name
]
612 def add_child(self
, name
, value
):
613 self
._children
[name
] = value
615 def _maybe_set_parent(self
, parent
, name
):
617 self
._parent
= parent
619 parent
.add_child(name
, self
)
621 def _set_child(self
, attr
, value
):
622 # if RHS is a SimObject, it's an implicit child assignment
623 # clear out old child with this name, if any
624 self
.clear_child(attr
)
626 if isSimObject(value
):
627 value
._maybe
_set
_parent
(self
, attr
)
628 elif isSimObjectSequence(value
):
629 value
= SimObjVector(value
)
631 value
[0]._maybe
_set
_parent
(self
, attr
)
633 width
= int(math
.ceil(math
.log(len(value
))/math
.log(10)))
634 for i
,v
in enumerate(value
):
635 v
._maybe
_set
_parent
(self
, "%s%0*d" % (attr
, width
, i
))
637 self
._values
[attr
] = value
642 ppath
= self
._parent
.path()
645 return ppath
+ "." + self
._name
653 def find_any(self
, ptype
):
654 if isinstance(self
, ptype
):
658 for child
in self
._children
.itervalues():
659 if isinstance(child
, ptype
):
660 if found_obj
!= None and child
!= found_obj
:
661 raise AttributeError, \
662 'parent.any matched more than one: %s %s' % \
663 (found_obj
.path
, child
.path
)
666 for pname
,pdesc
in self
._params
.iteritems():
667 if issubclass(pdesc
.ptype
, ptype
):
668 match_obj
= self
._values
[pname
]
669 if found_obj
!= None and found_obj
!= match_obj
:
670 raise AttributeError, \
671 'parent.any matched more than one: %s and %s' % (found_obj
.path
, match_obj
.path
)
672 found_obj
= match_obj
673 return found_obj
, found_obj
!= None
675 def unproxy(self
, base
):
678 def unproxy_all(self
):
679 for param
in self
._params
.iterkeys():
680 value
= self
._values
.get(param
)
681 if value
!= None and proxy
.isproxy(value
):
683 value
= value
.unproxy(self
)
685 print "Error in unproxying param '%s' of %s" % \
688 setattr(self
, param
, value
)
690 # Unproxy ports in sorted order so that 'append' operations on
691 # vector ports are done in a deterministic fashion.
692 port_names
= self
._ports
.keys()
694 for port_name
in port_names
:
695 port
= self
._port
_refs
.get(port_name
)
699 # Unproxy children in sorted order for determinism also.
700 child_names
= self
._children
.keys()
702 for child
in child_names
:
703 self
._children
[child
].unproxy_all()
705 def print_ini(self
, ini_file
):
706 print >>ini_file
, '[' + self
.path() + ']' # .ini section header
708 instanceDict
[self
.path()] = self
710 if hasattr(self
, 'type'):
711 print >>ini_file
, 'type=%s' % self
.type
713 child_names
= self
._children
.keys()
716 print >>ini_file
, 'children=%s' % ' '.join(child_names
)
718 param_names
= self
._params
.keys()
720 for param
in param_names
:
721 value
= self
._values
.get(param
)
723 print >>ini_file
, '%s=%s' % (param
,
724 self
._values
[param
].ini_str())
726 port_names
= self
._ports
.keys()
728 for port_name
in port_names
:
729 port
= self
._port
_refs
.get(port_name
, None)
731 print >>ini_file
, '%s=%s' % (port_name
, port
.ini_str())
733 print >>ini_file
# blank line between objects
735 for child
in child_names
:
736 self
._children
[child
].print_ini(ini_file
)
738 def getCCParams(self
):
740 return self
._ccParams
742 cc_params_struct
= getattr(m5
.objects
.params
, '%sParams' % self
.type)
743 cc_params
= cc_params_struct()
744 cc_params
.pyobj
= self
745 cc_params
.name
= str(self
)
747 param_names
= self
._params
.keys()
749 for param
in param_names
:
750 value
= self
._values
.get(param
)
752 m5
.fatal("%s.%s without default or user set value",
755 value
= value
.getValue()
756 if isinstance(self
._params
[param
], VectorParamDesc
):
757 assert isinstance(value
, list)
758 vec
= getattr(cc_params
, param
)
763 setattr(cc_params
, param
, value
)
765 port_names
= self
._ports
.keys()
767 for port_name
in port_names
:
768 port
= self
._port
_refs
.get(port_name
, None)
770 setattr(cc_params
, port_name
, port
)
771 self
._ccParams
= cc_params
772 return self
._ccParams
774 # Get C++ object corresponding to this object, calling C++ if
775 # necessary to construct it. Does *not* recursively create
777 def getCCObject(self
):
778 if not self
._ccObject
:
779 # Cycles in the configuration heirarchy are not supported. This
780 # will catch the resulting recursion and stop.
782 params
= self
.getCCParams()
783 self
._ccObject
= params
.create()
784 elif self
._ccObject
== -1:
785 raise RuntimeError, "%s: Cycle found in configuration heirarchy." \
787 return self
._ccObject
789 # Call C++ to create C++ object corresponding to this object and
790 # (recursively) all its children
791 def createCCObject(self
):
793 self
.getCCObject() # force creation
794 for child
in self
._children
.itervalues():
795 child
.createCCObject()
798 return self
.getCCObject()
800 # Create C++ port connections corresponding to the connections in
801 # _port_refs (& recursively for all children)
802 def connectPorts(self
):
803 for portRef
in self
._port
_refs
.itervalues():
805 for child
in self
._children
.itervalues():
808 def startDrain(self
, drain_event
, recursive
):
810 if isinstance(self
, SimObject
):
811 count
+= self
._ccObject
.drain(drain_event
)
813 for child
in self
._children
.itervalues():
814 count
+= child
.startDrain(drain_event
, True)
818 if isinstance(self
, SimObject
):
819 self
._ccObject
.resume()
820 for child
in self
._children
.itervalues():
823 def getMemoryMode(self
):
824 if not isinstance(self
, m5
.objects
.System
):
827 return self
._ccObject
.getMemoryMode()
829 def changeTiming(self
, mode
):
830 if isinstance(self
, m5
.objects
.System
):
831 # i don't know if there's a better way to do this - calling
832 # setMemoryMode directly from self._ccObject results in calling
833 # SimObject::setMemoryMode, not the System::setMemoryMode
834 self
._ccObject
.setMemoryMode(mode
)
835 for child
in self
._children
.itervalues():
836 child
.changeTiming(mode
)
838 def takeOverFrom(self
, old_cpu
):
839 self
._ccObject
.takeOverFrom(old_cpu
._ccObject
)
841 # generate output file for 'dot' to display as a pretty graph.
842 # this code is currently broken.
843 def outputDot(self
, dot
):
844 label
= "{%s|" % self
.path
845 if isSimObject(self
.realtype
):
846 label
+= '%s|' % self
.type
849 # instantiate children in same order they were added for
850 # backward compatibility (else we can end up with cpu1
852 for c
in self
.children
:
853 dot
.add_edge(pydot
.Edge(self
.path
,c
.path
, style
="bold"))
856 for param
in self
.params
:
858 if param
.value
is None:
859 raise AttributeError, 'Parameter with no value'
862 string
= param
.string(value
)
864 msg
= 'exception in %s:%s\n%s' % (self
.name
, param
.name
, e
)
868 if isSimObject(param
.ptype
) and string
!= "Null":
869 simobjs
.append(string
)
871 label
+= '%s = %s\\n' % (param
.name
, string
)
874 label
+= "|<%s> %s" % (so
, so
)
875 dot
.add_edge(pydot
.Edge("%s:%s" % (self
.path
, so
), so
,
878 dot
.add_node(pydot
.Node(self
.path
,shape
="Mrecord",label
=label
))
880 # recursively dump out children
881 for c
in self
.children
:
884 # Function to provide to C++ so it can look up instances based on paths
885 def resolveSimObject(name
):
886 obj
= instanceDict
[name
]
887 return obj
.getCCObject()
889 # __all__ defines the list of symbols that get exported when
890 # 'from config import *' is invoked. Try to keep this reasonably
891 # short to avoid polluting other namespaces.
892 __all__
= [ 'SimObject' ]