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
36 # These utility functions have to come first because they're
37 # referenced in params.py... otherwise they won't be defined when we
38 # import params below, and the recursive import of this file from
39 # params.py will not find these names.
40 def isSimObject(value
):
41 return isinstance(value
, SimObject
)
43 def isSimObjectClass(value
):
44 return issubclass(value
, SimObject
)
46 def isSimObjectSequence(value
):
47 if not isinstance(value
, (list, tuple)) or len(value
) == 0:
51 if not isNullPointer(val
) and not isSimObject(val
):
56 def isSimObjectOrSequence(value
):
57 return isSimObject(value
) or isSimObjectSequence(value
)
59 # Have to import params up top since Param is referenced on initial
60 # load (when SimObject class references Param to create a class
61 # variable, the 'name' param)...
63 # There are a few things we need that aren't in params.__all__ since
64 # normal users don't need them
65 from params
import ParamDesc
, VectorParamDesc
, isNullPointer
, SimObjVector
73 #####################################################################
75 # M5 Python Configuration Utility
77 # The basic idea is to write simple Python programs that build Python
78 # objects corresponding to M5 SimObjects for the desired simulation
79 # configuration. For now, the Python emits a .ini file that can be
80 # parsed by M5. In the future, some tighter integration between M5
81 # and the Python interpreter may allow bypassing the .ini file.
83 # Each SimObject class in M5 is represented by a Python class with the
84 # same name. The Python inheritance tree mirrors the M5 C++ tree
85 # (e.g., SimpleCPU derives from BaseCPU in both cases, and all
86 # SimObjects inherit from a single SimObject base class). To specify
87 # an instance of an M5 SimObject in a configuration, the user simply
88 # instantiates the corresponding Python object. The parameters for
89 # that SimObject are given by assigning to attributes of the Python
90 # object, either using keyword assignment in the constructor or in
91 # separate assignment statements. For example:
93 # cache = BaseCache(size='64KB')
94 # cache.hit_latency = 3
97 # The magic lies in the mapping of the Python attributes for SimObject
98 # classes to the actual SimObject parameter specifications. This
99 # allows parameter validity checking in the Python code. Continuing
100 # the example above, the statements "cache.blurfl=3" or
101 # "cache.assoc='hello'" would both result in runtime errors in Python,
102 # since the BaseCache object has no 'blurfl' parameter and the 'assoc'
103 # parameter requires an integer, respectively. This magic is done
104 # primarily by overriding the special __setattr__ method that controls
105 # assignment to object attributes.
107 # Once a set of Python objects have been instantiated in a hierarchy,
108 # calling 'instantiate(obj)' (where obj is the root of the hierarchy)
109 # will generate a .ini file.
111 #####################################################################
113 # list of all SimObject classes
116 # dict to look up SimObjects based on path
119 # The metaclass for SimObject. This class controls how new classes
120 # that derive from SimObject are instantiated, and provides inherited
121 # class behavior (just like a class controls how instances of that
122 # class are instantiated, and provides inherited instance behavior).
123 class MetaSimObject(type):
124 # Attributes that can be set only at initialization time
125 init_keywords
= { 'abstract' : types
.BooleanType
,
126 'cxx_namespace' : types
.StringType
,
127 'cxx_class' : types
.StringType
,
128 'cxx_type' : types
.StringType
,
129 'cxx_predecls' : types
.ListType
,
130 'swig_objdecls' : types
.ListType
,
131 'swig_predecls' : types
.ListType
,
132 'type' : types
.StringType
}
133 # Attributes that can be set any time
134 keywords
= { 'check' : types
.FunctionType
}
136 # __new__ is called before __init__, and is where the statements
137 # in the body of the class definition get loaded into the class's
138 # __dict__. We intercept this to filter out parameter & port assignments
139 # and only allow "private" attributes to be passed to the base
140 # __new__ (starting with underscore).
141 def __new__(mcls
, name
, bases
, dict):
142 assert name
not in allClasses
144 # Copy "private" attributes, functions, and classes to the
145 # official dict. Everything else goes in _init_dict to be
146 # filtered in __init__.
149 for key
,val
in dict.items():
150 if key
.startswith('_') or isinstance(val
, (types
.FunctionType
,
154 # must be a param/port setting
155 value_dict
[key
] = val
156 if 'abstract' not in value_dict
:
157 value_dict
['abstract'] = False
158 cls_dict
['_value_dict'] = value_dict
159 cls
= super(MetaSimObject
, mcls
).__new
__(mcls
, name
, bases
, cls_dict
)
160 if 'type' in value_dict
:
161 allClasses
[name
] = cls
164 # subclass initialization
165 def __init__(cls
, name
, bases
, dict):
166 # calls type.__init__()... I think that's a no-op, but leave
167 # it here just in case it's not.
168 super(MetaSimObject
, cls
).__init
__(name
, bases
, dict)
170 # initialize required attributes
172 # class-only attributes
173 cls
._params
= multidict() # param descriptions
174 cls
._ports
= multidict() # port descriptions
176 # class or instance attributes
177 cls
._values
= multidict() # param values
178 cls
._port
_refs
= multidict() # port ref objects
179 cls
._instantiated
= False # really instantiated, cloned, or subclassed
181 # We don't support multiple inheritance. If you want to, you
182 # must fix multidict to deal with it properly.
184 raise TypeError, "SimObjects do not support multiple inheritance"
188 # Set up general inheritance via multidicts. A subclass will
189 # inherit all its settings from the base class. The only time
190 # the following is not true is when we define the SimObject
191 # class itself (in which case the multidicts have no parent).
192 if isinstance(base
, MetaSimObject
):
193 cls
._params
.parent
= base
._params
194 cls
._ports
.parent
= base
._ports
195 cls
._values
.parent
= base
._values
196 cls
._port
_refs
.parent
= base
._port
_refs
197 # mark base as having been subclassed
198 base
._instantiated
= True
200 # default keyword values
201 if 'type' in cls
._value
_dict
:
202 _type
= cls
._value
_dict
['type']
203 if 'cxx_class' not in cls
._value
_dict
:
204 cls
._value
_dict
['cxx_class'] = _type
206 namespace
= cls
._value
_dict
.get('cxx_namespace', None)
208 _cxx_class
= cls
._value
_dict
['cxx_class']
209 if 'cxx_type' not in cls
._value
_dict
:
212 t
= '%s::%s' % (namespace
, t
)
213 cls
._value
_dict
['cxx_type'] = t
214 if 'cxx_predecls' not in cls
._value
_dict
:
215 # A forward class declaration is sufficient since we are
216 # just declaring a pointer.
217 decl
= 'class %s;' % _cxx_class
219 namespaces
= namespace
.split('::')
221 for namespace
in namespaces
:
222 decl
= 'namespace %s { %s }' % (namespace
, decl
)
223 cls
._value
_dict
['cxx_predecls'] = [decl
]
225 if 'swig_predecls' not in cls
._value
_dict
:
226 # A forward class declaration is sufficient since we are
227 # just declaring a pointer.
228 cls
._value
_dict
['swig_predecls'] = \
229 cls
._value
_dict
['cxx_predecls']
231 if 'swig_objdecls' not in cls
._value
_dict
:
232 cls
._value
_dict
['swig_objdecls'] = []
234 # Now process the _value_dict items. They could be defining
235 # new (or overriding existing) parameters or ports, setting
236 # class keywords (e.g., 'abstract'), or setting parameter
237 # values or port bindings. The first 3 can only be set when
238 # the class is defined, so we handle them here. The others
239 # can be set later too, so just emulate that by calling
241 for key
,val
in cls
._value
_dict
.items():
243 if isinstance(val
, ParamDesc
):
244 cls
._new
_param
(key
, val
)
247 elif isinstance(val
, Port
):
248 cls
._new
_port
(key
, val
)
250 # init-time-only keywords
251 elif cls
.init_keywords
.has_key(key
):
252 cls
._set
_keyword
(key
, val
, cls
.init_keywords
[key
])
254 # default: use normal path (ends up in __setattr__)
256 setattr(cls
, key
, val
)
258 def _set_keyword(cls
, keyword
, val
, kwtype
):
259 if not isinstance(val
, kwtype
):
260 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
261 (keyword
, type(val
), kwtype
)
262 if isinstance(val
, types
.FunctionType
):
263 val
= classmethod(val
)
264 type.__setattr
__(cls
, keyword
, val
)
266 def _new_param(cls
, name
, pdesc
):
267 # each param desc should be uniquely assigned to one variable
268 assert(not hasattr(pdesc
, 'name'))
270 cls
._params
[name
] = pdesc
271 if hasattr(pdesc
, 'default'):
272 cls
._set
_param
(name
, pdesc
.default
, pdesc
)
274 def _set_param(cls
, name
, value
, param
):
275 assert(param
.name
== name
)
277 cls
._values
[name
] = param
.convert(value
)
279 msg
= "%s\nError setting param %s.%s to %s\n" % \
280 (e
, cls
.__name
__, name
, value
)
284 def _new_port(cls
, name
, port
):
285 # each port should be uniquely assigned to one variable
286 assert(not hasattr(port
, 'name'))
288 cls
._ports
[name
] = port
289 if hasattr(port
, 'default'):
290 cls
._cls
_get
_port
_ref
(name
).connect(port
.default
)
292 # same as _get_port_ref, effectively, but for classes
293 def _cls_get_port_ref(cls
, attr
):
294 # Return reference that can be assigned to another port
295 # via __setattr__. There is only ever one reference
296 # object per port, but we create them lazily here.
297 ref
= cls
._port
_refs
.get(attr
)
299 ref
= cls
._ports
[attr
].makeRef(cls
)
300 cls
._port
_refs
[attr
] = ref
303 # Set attribute (called on foo.attr = value when foo is an
304 # instance of class cls).
305 def __setattr__(cls
, attr
, value
):
306 # normal processing for private attributes
307 if attr
.startswith('_'):
308 type.__setattr
__(cls
, attr
, value
)
311 if cls
.keywords
.has_key(attr
):
312 cls
._set
_keyword
(attr
, value
, cls
.keywords
[attr
])
315 if cls
._ports
.has_key(attr
):
316 cls
._cls
_get
_port
_ref
(attr
).connect(value
)
319 if isSimObjectOrSequence(value
) and cls
._instantiated
:
320 raise RuntimeError, \
321 "cannot set SimObject parameter '%s' after\n" \
322 " class %s has been instantiated or subclassed" \
323 % (attr
, cls
.__name
__)
326 param
= cls
._params
.get(attr
)
328 cls
._set
_param
(attr
, value
, param
)
331 if isSimObjectOrSequence(value
):
332 # If RHS is a SimObject, it's an implicit child assignment.
333 # Classes don't have children, so we just put this object
334 # in _values; later, each instance will do a 'setattr(self,
335 # attr, _values[attr])' in SimObject.__init__ which will
336 # add this object as a child.
337 cls
._values
[attr
] = value
340 # no valid assignment... raise exception
341 raise AttributeError, \
342 "Class %s has no parameter \'%s\'" % (cls
.__name
__, attr
)
344 def __getattr__(cls
, attr
):
345 if cls
._values
.has_key(attr
):
346 return cls
._values
[attr
]
348 raise AttributeError, \
349 "object '%s' has no attribute '%s'" % (cls
.__name
__, attr
)
355 if str(cls
) == 'SimObject':
358 return cls
.__bases
__[0].type
361 code
= "#ifndef __PARAMS__%s\n" % cls
362 code
+= "#define __PARAMS__%s\n\n" % cls
364 # The 'dict' attribute restricts us to the params declared in
365 # the object itself, not including inherited params (which
366 # will also be inherited from the base class's param struct
368 params
= cls
._params
.local
.values()
370 ptypes
= [p
.ptype
for p
in params
]
372 print cls
, p
, p
.ptype_str
376 # get a list of lists of predeclaration lines
378 predecls
.extend(cls
.cxx_predecls
)
380 predecls
.extend(p
.cxx_predecls())
381 # remove redundant lines
384 if pd
not in predecls2
:
387 code
+= "\n".join(predecls2
)
390 base
= cls
.get_base()
392 code
+= '#include "params/%s.hh"\n\n' % base
395 if issubclass(ptype
, Enum
):
396 code
+= '#include "enums/%s.hh"\n' % ptype
.__name
__
399 # now generate the actual param struct
400 code
+= "struct %sParams" % cls
402 code
+= " : public %sParams" % base
405 code
+= " virtual ~%sParams() {}\n" % cls
406 if not hasattr(cls
, 'abstract') or not cls
.abstract
:
407 if 'type' in cls
.__dict
__:
408 code
+= " %s create();\n" % cls
.cxx_type
409 decls
= [p
.cxx_decl() for p
in params
]
411 code
+= "".join([" %s\n" % d
for d
in decls
])
414 # close #ifndef __PARAMS__* guard
418 def cxx_type_decl(cls
):
419 base
= cls
.get_base()
423 code
+= '#include "%s_type.h"\n' % base
425 # now generate dummy code for inheritance
426 code
+= "struct %s" % cls
.cxx_class
428 code
+= " : public %s" % base
.cxx_class
434 base
= cls
.get_base()
436 code
= '%%module %s\n' % cls
439 code
+= '#include "params/%s.hh"\n' % cls
442 # The 'dict' attribute restricts us to the params declared in
443 # the object itself, not including inherited params (which
444 # will also be inherited from the base class's param struct
446 params
= cls
._params
.local
.values()
447 ptypes
= [p
.ptype
for p
in params
]
449 # get a list of lists of predeclaration lines
451 predecls
.extend([ p
.swig_predecls() for p
in params
])
453 predecls
= reduce(lambda x
,y
:x
+y
, predecls
, [])
454 # remove redundant lines
457 if pd
not in predecls2
:
460 code
+= "\n".join(predecls2
)
464 code
+= '%%import "params/%s.i"\n\n' % base
467 if issubclass(ptype
, Enum
):
468 code
+= '%%import "enums/%s.hh"\n' % ptype
.__name
__
471 code
+= '%%import "params/%s_type.hh"\n\n' % cls
472 code
+= '%%include "params/%s.hh"\n\n' % cls
476 # The SimObject class is the root of the special hierarchy. Most of
477 # the code in this class deals with the configuration hierarchy itself
478 # (parent/child node relationships).
479 class SimObject(object):
480 # Specify metaclass. Any class inheriting from SimObject will
481 # get this metaclass.
482 __metaclass__
= MetaSimObject
486 name
= Param
.String("Object name")
487 swig_objdecls
= [ '%include "python/swig/sim_object.i"' ]
489 # Initialize new instance. For objects with SimObject-valued
490 # children, we need to recursively clone the classes represented
491 # by those param values as well in a consistent "deep copy"-style
492 # fashion. That is, we want to make sure that each instance is
493 # cloned only once, and that if there are multiple references to
494 # the same original object, we end up with the corresponding
495 # cloned references all pointing to the same cloned instance.
496 def __init__(self
, **kwargs
):
497 ancestor
= kwargs
.get('_ancestor')
498 memo_dict
= kwargs
.get('_memo')
499 if memo_dict
is None:
500 # prepare to memoize any recursively instantiated objects
503 # memoize me now to avoid problems with recursive calls
504 memo_dict
[ancestor
] = self
507 ancestor
= self
.__class
__
508 ancestor
._instantiated
= True
510 # initialize required attributes
513 self
._ccObject
= None # pointer to C++ object
514 self
._ccParams
= None
515 self
._instantiated
= False # really "cloned"
517 # Inherit parameter values from class using multidict so
518 # individual value settings can be overridden.
519 self
._values
= multidict(ancestor
._values
)
520 # clone SimObject-valued parameters
521 for key
,val
in ancestor
._values
.iteritems():
523 setattr(self
, key
, val(_memo
=memo_dict
))
524 elif isSimObjectSequence(val
) and len(val
):
525 setattr(self
, key
, [ v(_memo
=memo_dict
) for v
in val
])
526 # clone port references. no need to use a multidict here
527 # since we will be creating new references for all ports.
529 for key
,val
in ancestor
._port
_refs
.iteritems():
530 self
._port
_refs
[key
] = val
.clone(self
, memo_dict
)
531 # apply attribute assignments from keyword args, if any
532 for key
,val
in kwargs
.iteritems():
533 setattr(self
, key
, val
)
535 # "Clone" the current instance by creating another instance of
536 # this instance's class, but that inherits its parameter values
537 # and port mappings from the current instance. If we're in a
538 # "deep copy" recursive clone, check the _memo dict to see if
539 # we've already cloned this instance.
540 def __call__(self
, **kwargs
):
541 memo_dict
= kwargs
.get('_memo')
542 if memo_dict
is None:
543 # no memo_dict: must be top-level clone operation.
544 # this is only allowed at the root of a hierarchy
546 raise RuntimeError, "attempt to clone object %s " \
547 "not at the root of a tree (parent = %s)" \
548 % (self
, self
._parent
)
549 # create a new dict and use that.
551 kwargs
['_memo'] = memo_dict
552 elif memo_dict
.has_key(self
):
553 # clone already done & memoized
554 return memo_dict
[self
]
555 return self
.__class
__(_ancestor
= self
, **kwargs
)
557 def _get_port_ref(self
, attr
):
558 # Return reference that can be assigned to another port
559 # via __setattr__. There is only ever one reference
560 # object per port, but we create them lazily here.
561 ref
= self
._port
_refs
.get(attr
)
563 ref
= self
._ports
[attr
].makeRef(self
)
564 self
._port
_refs
[attr
] = ref
567 def __getattr__(self
, attr
):
568 if self
._ports
.has_key(attr
):
569 return self
._get
_port
_ref
(attr
)
571 if self
._values
.has_key(attr
):
572 return self
._values
[attr
]
574 raise AttributeError, "object '%s' has no attribute '%s'" \
575 % (self
.__class
__.__name
__, attr
)
577 # Set attribute (called on foo.attr = value when foo is an
578 # instance of class cls).
579 def __setattr__(self
, attr
, value
):
580 # normal processing for private attributes
581 if attr
.startswith('_'):
582 object.__setattr
__(self
, attr
, value
)
585 if self
._ports
.has_key(attr
):
586 # set up port connection
587 self
._get
_port
_ref
(attr
).connect(value
)
590 if isSimObjectOrSequence(value
) and self
._instantiated
:
591 raise RuntimeError, \
592 "cannot set SimObject parameter '%s' after\n" \
593 " instance been cloned %s" % (attr
, `self`
)
595 # must be SimObject param
596 param
= self
._params
.get(attr
)
599 value
= param
.convert(value
)
601 msg
= "%s\nError setting param %s.%s to %s\n" % \
602 (e
, self
.__class
__.__name
__, attr
, value
)
605 self
._set
_child
(attr
, value
)
608 if isSimObjectOrSequence(value
):
609 self
._set
_child
(attr
, value
)
612 # no valid assignment... raise exception
613 raise AttributeError, "Class %s has no parameter %s" \
614 % (self
.__class
__.__name
__, attr
)
617 # this hack allows tacking a '[0]' onto parameters that may or may
618 # not be vectors, and always getting the first element (e.g. cpus)
619 def __getitem__(self
, key
):
622 raise TypeError, "Non-zero index '%s' to SimObject" % key
624 # clear out children with given name, even if it's a vector
625 def clear_child(self
, name
):
626 if not self
._children
.has_key(name
):
628 child
= self
._children
[name
]
629 if isinstance(child
, SimObjVector
):
630 for i
in xrange(len(child
)):
631 del self
._children
["s%d" % (name
, i
)]
632 del self
._children
[name
]
634 def add_child(self
, name
, value
):
635 self
._children
[name
] = value
637 def _maybe_set_parent(self
, parent
, name
):
639 self
._parent
= parent
641 parent
.add_child(name
, self
)
643 def _set_child(self
, attr
, value
):
644 # if RHS is a SimObject, it's an implicit child assignment
645 # clear out old child with this name, if any
646 self
.clear_child(attr
)
648 if isSimObject(value
):
649 value
._maybe
_set
_parent
(self
, attr
)
650 elif isSimObjectSequence(value
):
651 value
= SimObjVector(value
)
653 value
[0]._maybe
_set
_parent
(self
, attr
)
655 for i
,v
in enumerate(value
):
656 v
._maybe
_set
_parent
(self
, "%s%d" % (attr
, i
))
658 self
._values
[attr
] = value
663 ppath
= self
._parent
.path()
666 return ppath
+ "." + self
._name
674 def find_any(self
, ptype
):
675 if isinstance(self
, ptype
):
679 for child
in self
._children
.itervalues():
680 if isinstance(child
, ptype
):
681 if found_obj
!= None and child
!= found_obj
:
682 raise AttributeError, \
683 'parent.any matched more than one: %s %s' % \
684 (found_obj
.path
, child
.path
)
687 for pname
,pdesc
in self
._params
.iteritems():
688 if issubclass(pdesc
.ptype
, ptype
):
689 match_obj
= self
._values
[pname
]
690 if found_obj
!= None and found_obj
!= match_obj
:
691 raise AttributeError, \
692 'parent.any matched more than one: %s' % obj
.path
693 found_obj
= match_obj
694 return found_obj
, found_obj
!= None
696 def unproxy(self
, base
):
699 def unproxy_all(self
):
700 for param
in self
._params
.iterkeys():
701 value
= self
._values
.get(param
)
702 if value
!= None and proxy
.isproxy(value
):
704 value
= value
.unproxy(self
)
706 print "Error in unproxying param '%s' of %s" % \
709 setattr(self
, param
, value
)
711 # Unproxy ports in sorted order so that 'append' operations on
712 # vector ports are done in a deterministic fashion.
713 port_names
= self
._ports
.keys()
715 for port_name
in port_names
:
716 port
= self
._port
_refs
.get(port_name
)
720 # Unproxy children in sorted order for determinism also.
721 child_names
= self
._children
.keys()
723 for child
in child_names
:
724 self
._children
[child
].unproxy_all()
726 def print_ini(self
, ini_file
):
727 print >>ini_file
, '[' + self
.path() + ']' # .ini section header
729 instanceDict
[self
.path()] = self
731 if hasattr(self
, 'type'):
732 print >>ini_file
, 'type=%s' % self
.type
734 child_names
= self
._children
.keys()
737 print >>ini_file
, 'children=%s' % ' '.join(child_names
)
739 param_names
= self
._params
.keys()
741 for param
in param_names
:
742 value
= self
._values
.get(param
)
744 print >>ini_file
, '%s=%s' % (param
,
745 self
._values
[param
].ini_str())
747 port_names
= self
._ports
.keys()
749 for port_name
in port_names
:
750 port
= self
._port
_refs
.get(port_name
, None)
752 print >>ini_file
, '%s=%s' % (port_name
, port
.ini_str())
754 print >>ini_file
# blank line between objects
756 for child
in child_names
:
757 self
._children
[child
].print_ini(ini_file
)
759 def getCCParams(self
):
761 return self
._ccParams
763 cc_params_struct
= getattr(m5
.objects
.params
, '%sParams' % self
.type)
764 cc_params
= cc_params_struct()
765 cc_params
.object = self
766 cc_params
.name
= str(self
)
768 param_names
= self
._params
.keys()
770 for param
in param_names
:
771 value
= self
._values
.get(param
)
775 value
= value
.getValue()
776 if isinstance(self
._params
[param
], VectorParamDesc
):
777 assert isinstance(value
, list)
778 vec
= getattr(cc_params
, param
)
783 setattr(cc_params
, param
, value
)
785 port_names
= self
._ports
.keys()
787 for port_name
in port_names
:
788 port
= self
._port
_refs
.get(port_name
, None)
790 setattr(cc_params
, port_name
, port
)
791 self
._ccParams
= cc_params
792 return self
._ccParams
794 # Get C++ object corresponding to this object, calling C++ if
795 # necessary to construct it. Does *not* recursively create
797 def getCCObject(self
):
798 if not self
._ccObject
:
799 # Cycles in the configuration heirarchy are not supported. This
800 # will catch the resulting recursion and stop.
802 params
= self
.getCCParams()
803 self
._ccObject
= params
.create()
804 elif self
._ccObject
== -1:
805 raise RuntimeError, "%s: Cycle found in configuration heirarchy." \
807 return self
._ccObject
809 # Call C++ to create C++ object corresponding to this object and
810 # (recursively) all its children
811 def createCCObject(self
):
813 self
.getCCObject() # force creation
814 for child
in self
._children
.itervalues():
815 child
.createCCObject()
818 return self
.getCCObject()
820 # Create C++ port connections corresponding to the connections in
821 # _port_refs (& recursively for all children)
822 def connectPorts(self
):
823 for portRef
in self
._port
_refs
.itervalues():
825 for child
in self
._children
.itervalues():
828 def startDrain(self
, drain_event
, recursive
):
830 if isinstance(self
, SimObject
):
831 count
+= self
._ccObject
.drain(drain_event
)
833 for child
in self
._children
.itervalues():
834 count
+= child
.startDrain(drain_event
, True)
838 if isinstance(self
, SimObject
):
839 self
._ccObject
.resume()
840 for child
in self
._children
.itervalues():
843 def getMemoryMode(self
):
844 if not isinstance(self
, m5
.objects
.System
):
847 return self
._ccObject
.getMemoryMode()
849 def changeTiming(self
, mode
):
850 if isinstance(self
, m5
.objects
.System
):
851 # i don't know if there's a better way to do this - calling
852 # setMemoryMode directly from self._ccObject results in calling
853 # SimObject::setMemoryMode, not the System::setMemoryMode
854 self
._ccObject
.setMemoryMode(mode
)
855 for child
in self
._children
.itervalues():
856 child
.changeTiming(mode
)
858 def takeOverFrom(self
, old_cpu
):
859 self
._ccObject
.takeOverFrom(old_cpu
._ccObject
)
861 # generate output file for 'dot' to display as a pretty graph.
862 # this code is currently broken.
863 def outputDot(self
, dot
):
864 label
= "{%s|" % self
.path
865 if isSimObject(self
.realtype
):
866 label
+= '%s|' % self
.type
869 # instantiate children in same order they were added for
870 # backward compatibility (else we can end up with cpu1
872 for c
in self
.children
:
873 dot
.add_edge(pydot
.Edge(self
.path
,c
.path
, style
="bold"))
876 for param
in self
.params
:
878 if param
.value
is None:
879 raise AttributeError, 'Parameter with no value'
882 string
= param
.string(value
)
884 msg
= 'exception in %s:%s\n%s' % (self
.name
, param
.name
, e
)
888 if isSimObject(param
.ptype
) and string
!= "Null":
889 simobjs
.append(string
)
891 label
+= '%s = %s\\n' % (param
.name
, string
)
894 label
+= "|<%s> %s" % (so
, so
)
895 dot
.add_edge(pydot
.Edge("%s:%s" % (self
.path
, so
), so
,
898 dot
.add_node(pydot
.Node(self
.path
,shape
="Mrecord",label
=label
))
900 # recursively dump out children
901 for c
in self
.children
:
904 # Function to provide to C++ so it can look up instances based on paths
905 def resolveSimObject(name
):
906 obj
= instanceDict
[name
]
907 return obj
.getCCObject()
909 # __all__ defines the list of symbols that get exported when
910 # 'from config import *' is invoked. Try to keep this reasonably
911 # short to avoid polluting other namespaces.
912 __all__
= [ 'SimObject' ]