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
31 from types
import FunctionType
41 # Have to import params up top since Param is referenced on initial
42 # load (when SimObject class references Param to create a class
43 # variable, the 'name' param)...
44 from m5
.params
import *
45 # There are a few things we need that aren't in params.__all__ since
46 # normal users don't need them
47 from m5
.params
import ParamDesc
, VectorParamDesc
, \
48 isNullPointer
, SimObjectVector
50 from m5
.proxy
import *
51 from m5
.proxy
import isproxy
53 #####################################################################
55 # M5 Python Configuration Utility
57 # The basic idea is to write simple Python programs that build Python
58 # objects corresponding to M5 SimObjects for the desired simulation
59 # configuration. For now, the Python emits a .ini file that can be
60 # parsed by M5. In the future, some tighter integration between M5
61 # and the Python interpreter may allow bypassing the .ini file.
63 # Each SimObject class in M5 is represented by a Python class with the
64 # same name. The Python inheritance tree mirrors the M5 C++ tree
65 # (e.g., SimpleCPU derives from BaseCPU in both cases, and all
66 # SimObjects inherit from a single SimObject base class). To specify
67 # an instance of an M5 SimObject in a configuration, the user simply
68 # instantiates the corresponding Python object. The parameters for
69 # that SimObject are given by assigning to attributes of the Python
70 # object, either using keyword assignment in the constructor or in
71 # separate assignment statements. For example:
73 # cache = BaseCache(size='64KB')
74 # cache.hit_latency = 3
77 # The magic lies in the mapping of the Python attributes for SimObject
78 # classes to the actual SimObject parameter specifications. This
79 # allows parameter validity checking in the Python code. Continuing
80 # the example above, the statements "cache.blurfl=3" or
81 # "cache.assoc='hello'" would both result in runtime errors in Python,
82 # since the BaseCache object has no 'blurfl' parameter and the 'assoc'
83 # parameter requires an integer, respectively. This magic is done
84 # primarily by overriding the special __setattr__ method that controls
85 # assignment to object attributes.
87 # Once a set of Python objects have been instantiated in a hierarchy,
88 # calling 'instantiate(obj)' (where obj is the root of the hierarchy)
89 # will generate a .ini file.
91 #####################################################################
93 # list of all SimObject classes
96 # dict to look up SimObjects based on path
99 # The metaclass for SimObject. This class controls how new classes
100 # that derive from SimObject are instantiated, and provides inherited
101 # class behavior (just like a class controls how instances of that
102 # class are instantiated, and provides inherited instance behavior).
103 class MetaSimObject(type):
104 # Attributes that can be set only at initialization time
105 init_keywords
= { 'abstract' : bool,
108 'cxx_predecls' : list,
109 'swig_objdecls' : list,
110 'swig_predecls' : list,
112 # Attributes that can be set any time
113 keywords
= { 'check' : FunctionType
}
115 # __new__ is called before __init__, and is where the statements
116 # in the body of the class definition get loaded into the class's
117 # __dict__. We intercept this to filter out parameter & port assignments
118 # and only allow "private" attributes to be passed to the base
119 # __new__ (starting with underscore).
120 def __new__(mcls
, name
, bases
, dict):
121 assert name
not in allClasses
, "SimObject %s already present" % name
123 # Copy "private" attributes, functions, and classes to the
124 # official dict. Everything else goes in _init_dict to be
125 # filtered in __init__.
128 for key
,val
in dict.items():
129 if key
.startswith('_') or isinstance(val
, (FunctionType
,
134 # must be a param/port setting
135 value_dict
[key
] = val
136 if 'abstract' not in value_dict
:
137 value_dict
['abstract'] = False
138 cls_dict
['_value_dict'] = value_dict
139 cls
= super(MetaSimObject
, mcls
).__new
__(mcls
, name
, bases
, cls_dict
)
140 if 'type' in value_dict
:
141 allClasses
[name
] = cls
144 # subclass initialization
145 def __init__(cls
, name
, bases
, dict):
146 # calls type.__init__()... I think that's a no-op, but leave
147 # it here just in case it's not.
148 super(MetaSimObject
, cls
).__init
__(name
, bases
, dict)
150 # initialize required attributes
152 # class-only attributes
153 cls
._params
= multidict() # param descriptions
154 cls
._ports
= multidict() # port descriptions
156 # class or instance attributes
157 cls
._values
= multidict() # param values
158 cls
._children
= multidict() # SimObject children
159 cls
._port
_refs
= multidict() # port ref objects
160 cls
._instantiated
= False # really instantiated, cloned, or subclassed
162 # We don't support multiple inheritance. If you want to, you
163 # must fix multidict to deal with it properly.
165 raise TypeError, "SimObjects do not support multiple inheritance"
169 # Set up general inheritance via multidicts. A subclass will
170 # inherit all its settings from the base class. The only time
171 # the following is not true is when we define the SimObject
172 # class itself (in which case the multidicts have no parent).
173 if isinstance(base
, MetaSimObject
):
175 cls
._params
.parent
= base
._params
176 cls
._ports
.parent
= base
._ports
177 cls
._values
.parent
= base
._values
178 cls
._children
.parent
= base
._children
179 cls
._port
_refs
.parent
= base
._port
_refs
180 # mark base as having been subclassed
181 base
._instantiated
= True
185 # default keyword values
186 if 'type' in cls
._value
_dict
:
187 if 'cxx_class' not in cls
._value
_dict
:
188 cls
._value
_dict
['cxx_class'] = cls
._value
_dict
['type']
190 cls
._value
_dict
['cxx_type'] = '%s *' % cls
._value
_dict
['cxx_class']
192 if 'cxx_predecls' not in cls
._value
_dict
:
193 # A forward class declaration is sufficient since we are
194 # just declaring a pointer.
195 class_path
= cls
._value
_dict
['cxx_class'].split('::')
197 decl
= 'class %s;' % class_path
[0]
198 for ns
in class_path
[1:]:
199 decl
= 'namespace %s { %s }' % (ns
, decl
)
200 cls
._value
_dict
['cxx_predecls'] = [decl
]
202 if 'swig_predecls' not in cls
._value
_dict
:
203 # A forward class declaration is sufficient since we are
204 # just declaring a pointer.
205 cls
._value
_dict
['swig_predecls'] = \
206 cls
._value
_dict
['cxx_predecls']
208 if 'swig_objdecls' not in cls
._value
_dict
:
209 cls
._value
_dict
['swig_objdecls'] = []
211 # Now process the _value_dict items. They could be defining
212 # new (or overriding existing) parameters or ports, setting
213 # class keywords (e.g., 'abstract'), or setting parameter
214 # values or port bindings. The first 3 can only be set when
215 # the class is defined, so we handle them here. The others
216 # can be set later too, so just emulate that by calling
218 for key
,val
in cls
._value
_dict
.items():
220 if isinstance(val
, ParamDesc
):
221 cls
._new
_param
(key
, val
)
224 elif isinstance(val
, Port
):
225 cls
._new
_port
(key
, val
)
227 # init-time-only keywords
228 elif cls
.init_keywords
.has_key(key
):
229 cls
._set
_keyword
(key
, val
, cls
.init_keywords
[key
])
231 # default: use normal path (ends up in __setattr__)
233 setattr(cls
, key
, val
)
235 def _set_keyword(cls
, keyword
, val
, kwtype
):
236 if not isinstance(val
, kwtype
):
237 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \
238 (keyword
, type(val
), kwtype
)
239 if isinstance(val
, FunctionType
):
240 val
= classmethod(val
)
241 type.__setattr
__(cls
, keyword
, val
)
243 def _new_param(cls
, name
, pdesc
):
244 # each param desc should be uniquely assigned to one variable
245 assert(not hasattr(pdesc
, 'name'))
247 cls
._params
[name
] = pdesc
248 if hasattr(pdesc
, 'default'):
249 cls
._set
_param
(name
, pdesc
.default
, pdesc
)
251 def _set_param(cls
, name
, value
, param
):
252 assert(param
.name
== name
)
254 cls
._values
[name
] = param
.convert(value
)
256 msg
= "%s\nError setting param %s.%s to %s\n" % \
257 (e
, cls
.__name
__, name
, value
)
261 def _new_port(cls
, name
, port
):
262 # each port should be uniquely assigned to one variable
263 assert(not hasattr(port
, 'name'))
265 cls
._ports
[name
] = port
266 if hasattr(port
, 'default'):
267 cls
._cls
_get
_port
_ref
(name
).connect(port
.default
)
269 # same as _get_port_ref, effectively, but for classes
270 def _cls_get_port_ref(cls
, attr
):
271 # Return reference that can be assigned to another port
272 # via __setattr__. There is only ever one reference
273 # object per port, but we create them lazily here.
274 ref
= cls
._port
_refs
.get(attr
)
276 ref
= cls
._ports
[attr
].makeRef(cls
)
277 cls
._port
_refs
[attr
] = ref
280 # Set attribute (called on foo.attr = value when foo is an
281 # instance of class cls).
282 def __setattr__(cls
, attr
, value
):
283 # normal processing for private attributes
284 if attr
.startswith('_'):
285 type.__setattr
__(cls
, attr
, value
)
288 if cls
.keywords
.has_key(attr
):
289 cls
._set
_keyword
(attr
, value
, cls
.keywords
[attr
])
292 if cls
._ports
.has_key(attr
):
293 cls
._cls
_get
_port
_ref
(attr
).connect(value
)
296 if isSimObjectOrSequence(value
) and cls
._instantiated
:
297 raise RuntimeError, \
298 "cannot set SimObject parameter '%s' after\n" \
299 " class %s has been instantiated or subclassed" \
300 % (attr
, cls
.__name
__)
303 param
= cls
._params
.get(attr
)
305 cls
._set
_param
(attr
, value
, param
)
308 if isSimObjectOrSequence(value
):
309 # If RHS is a SimObject, it's an implicit child assignment.
310 cls
._children
[attr
] = coerceSimObjectOrVector(value
)
313 # no valid assignment... raise exception
314 raise AttributeError, \
315 "Class %s has no parameter \'%s\'" % (cls
.__name
__, attr
)
317 def __getattr__(cls
, attr
):
318 if cls
._values
.has_key(attr
):
319 return cls
._values
[attr
]
321 if cls
._children
.has_key(attr
):
322 return cls
._children
[attr
]
324 raise AttributeError, \
325 "object '%s' has no attribute '%s'" % (cls
.__name
__, attr
)
331 code
= "#ifndef __PARAMS__%s\n" % cls
332 code
+= "#define __PARAMS__%s\n\n" % cls
334 # The 'dict' attribute restricts us to the params declared in
335 # the object itself, not including inherited params (which
336 # will also be inherited from the base class's param struct
338 params
= cls
._params
.local
.values()
340 ptypes
= [p
.ptype
for p
in params
]
342 print cls
, p
, p
.ptype_str
346 # get a list of lists of predeclaration lines
348 predecls
.extend(cls
.cxx_predecls
)
350 predecls
.extend(p
.cxx_predecls())
351 # remove redundant lines
354 if pd
not in predecls2
:
357 code
+= "\n".join(predecls2
)
361 code
+= '#include "params/%s.hh"\n\n' % cls
._base
.type
364 if issubclass(ptype
, Enum
):
365 code
+= '#include "enums/%s.hh"\n' % ptype
.__name
__
368 code
+= cls
.cxx_struct(cls
._base
, params
)
370 # close #ifndef __PARAMS__* guard
374 def cxx_struct(cls
, base
, params
):
376 return '#include "sim/sim_object_params.hh"\n'
378 # now generate the actual param struct
379 code
= "struct %sParams" % cls
381 code
+= " : public %sParams" % base
.type
383 if not hasattr(cls
, 'abstract') or not cls
.abstract
:
384 if 'type' in cls
.__dict
__:
385 code
+= " %s create();\n" % cls
.cxx_type
386 decls
= [p
.cxx_decl() for p
in params
]
388 code
+= "".join([" %s\n" % d
for d
in decls
])
394 code
= '%%module %s\n' % cls
397 code
+= '#include "params/%s.hh"\n' % cls
400 # The 'dict' attribute restricts us to the params declared in
401 # the object itself, not including inherited params (which
402 # will also be inherited from the base class's param struct
404 params
= cls
._params
.local
.values()
405 ptypes
= [p
.ptype
for p
in params
]
407 # get a list of lists of predeclaration lines
409 predecls
.extend([ p
.swig_predecls() for p
in params
])
411 predecls
= reduce(lambda x
,y
:x
+y
, predecls
, [])
412 # remove redundant lines
415 if pd
not in predecls2
:
418 code
+= "\n".join(predecls2
)
422 code
+= '%%import "params/%s.i"\n\n' % cls
._base
.type
425 if issubclass(ptype
, Enum
):
426 code
+= '%%import "enums/%s.hh"\n' % ptype
.__name
__
429 code
+= '%%import "params/%s_type.hh"\n\n' % cls
430 code
+= '%%include "params/%s.hh"\n\n' % cls
434 # The SimObject class is the root of the special hierarchy. Most of
435 # the code in this class deals with the configuration hierarchy itself
436 # (parent/child node relationships).
437 class SimObject(object):
438 # Specify metaclass. Any class inheriting from SimObject will
439 # get this metaclass.
440 __metaclass__
= MetaSimObject
444 swig_objdecls
= [ '%include "python/swig/sim_object.i"' ]
446 # Initialize new instance. For objects with SimObject-valued
447 # children, we need to recursively clone the classes represented
448 # by those param values as well in a consistent "deep copy"-style
449 # fashion. That is, we want to make sure that each instance is
450 # cloned only once, and that if there are multiple references to
451 # the same original object, we end up with the corresponding
452 # cloned references all pointing to the same cloned instance.
453 def __init__(self
, **kwargs
):
454 ancestor
= kwargs
.get('_ancestor')
455 memo_dict
= kwargs
.get('_memo')
456 if memo_dict
is None:
457 # prepare to memoize any recursively instantiated objects
460 # memoize me now to avoid problems with recursive calls
461 memo_dict
[ancestor
] = self
464 ancestor
= self
.__class
__
465 ancestor
._instantiated
= True
467 # initialize required attributes
470 self
._ccObject
= None # pointer to C++ object
471 self
._ccParams
= None
472 self
._instantiated
= False # really "cloned"
474 # Inherit parameter values from class using multidict so
475 # individual value settings can be overridden but we still
476 # inherit late changes to non-overridden class values.
477 self
._values
= multidict(ancestor
._values
)
478 # clone SimObject-valued parameters
479 for key
,val
in ancestor
._values
.iteritems():
480 val
= tryAsSimObjectOrVector(val
)
482 self
._values
[key
] = val(_memo
=memo_dict
)
484 # Clone children specified at class level. No need for a
485 # multidict here since we will be cloning everything.
487 for key
,val
in ancestor
._children
.iteritems():
488 self
.add_child(key
, val(_memo
=memo_dict
))
490 # clone port references. no need to use a multidict here
491 # since we will be creating new references for all ports.
493 for key
,val
in ancestor
._port
_refs
.iteritems():
494 self
._port
_refs
[key
] = val
.clone(self
, memo_dict
)
495 # apply attribute assignments from keyword args, if any
496 for key
,val
in kwargs
.iteritems():
497 setattr(self
, key
, val
)
499 # "Clone" the current instance by creating another instance of
500 # this instance's class, but that inherits its parameter values
501 # and port mappings from the current instance. If we're in a
502 # "deep copy" recursive clone, check the _memo dict to see if
503 # we've already cloned this instance.
504 def __call__(self
, **kwargs
):
505 memo_dict
= kwargs
.get('_memo')
506 if memo_dict
is None:
507 # no memo_dict: must be top-level clone operation.
508 # this is only allowed at the root of a hierarchy
510 raise RuntimeError, "attempt to clone object %s " \
511 "not at the root of a tree (parent = %s)" \
512 % (self
, self
._parent
)
513 # create a new dict and use that.
515 kwargs
['_memo'] = memo_dict
516 elif memo_dict
.has_key(self
):
517 # clone already done & memoized
518 return memo_dict
[self
]
519 return self
.__class
__(_ancestor
= self
, **kwargs
)
521 def _get_port_ref(self
, attr
):
522 # Return reference that can be assigned to another port
523 # via __setattr__. There is only ever one reference
524 # object per port, but we create them lazily here.
525 ref
= self
._port
_refs
.get(attr
)
527 ref
= self
._ports
[attr
].makeRef(self
)
528 self
._port
_refs
[attr
] = ref
531 def __getattr__(self
, attr
):
532 if self
._ports
.has_key(attr
):
533 return self
._get
_port
_ref
(attr
)
535 if self
._values
.has_key(attr
):
536 return self
._values
[attr
]
538 if self
._children
.has_key(attr
):
539 return self
._children
[attr
]
541 # If the attribute exists on the C++ object, transparently
542 # forward the reference there. This is typically used for
543 # SWIG-wrapped methods such as init(), regStats(),
544 # regFormulas(), resetStats(), startup(), drain(), and
546 if self
._ccObject
and hasattr(self
._ccObject
, attr
):
547 return getattr(self
._ccObject
, attr
)
549 raise AttributeError, "object '%s' has no attribute '%s'" \
550 % (self
.__class
__.__name
__, attr
)
552 # Set attribute (called on foo.attr = value when foo is an
553 # instance of class cls).
554 def __setattr__(self
, attr
, value
):
555 # normal processing for private attributes
556 if attr
.startswith('_'):
557 object.__setattr
__(self
, attr
, value
)
560 if self
._ports
.has_key(attr
):
561 # set up port connection
562 self
._get
_port
_ref
(attr
).connect(value
)
565 if isSimObjectOrSequence(value
) and self
._instantiated
:
566 raise RuntimeError, \
567 "cannot set SimObject parameter '%s' after\n" \
568 " instance been cloned %s" % (attr
, `self`
)
570 param
= self
._params
.get(attr
)
573 value
= param
.convert(value
)
575 msg
= "%s\nError setting param %s.%s to %s\n" % \
576 (e
, self
.__class
__.__name
__, attr
, value
)
579 self
._values
[attr
] = value
582 # if RHS is a SimObject, it's an implicit child assignment
583 if isSimObjectOrSequence(value
):
584 self
.add_child(attr
, value
)
587 # no valid assignment... raise exception
588 raise AttributeError, "Class %s has no parameter %s" \
589 % (self
.__class
__.__name
__, attr
)
592 # this hack allows tacking a '[0]' onto parameters that may or may
593 # not be vectors, and always getting the first element (e.g. cpus)
594 def __getitem__(self
, key
):
597 raise TypeError, "Non-zero index '%s' to SimObject" % key
599 # Also implemented by SimObjectVector
600 def clear_parent(self
, old_parent
):
601 assert self
._parent
is old_parent
604 # Also implemented by SimObjectVector
605 def set_parent(self
, parent
, name
):
606 self
._parent
= parent
609 # Also implemented by SimObjectVector
613 # use this rather than directly accessing _parent for symmetry
614 # with SimObjectVector
615 def get_parent(self
):
618 # clear out child with given name
619 def clear_child(self
, name
):
620 child
= self
._children
[name
]
621 child
.clear_parent(self
)
622 del self
._children
[name
]
624 # Add a new child to this object.
625 def add_child(self
, name
, child
):
626 child
= coerceSimObjectOrVector(child
)
627 if child
.get_parent():
628 raise RuntimeError, \
629 "add_child('%s'): child '%s' already has parent '%s'" % \
630 (name
, child
._name
, child
._parent
)
631 if self
._children
.has_key(name
):
633 child
.set_parent(self
, name
)
634 self
._children
[name
] = child
636 # Take SimObject-valued parameters that haven't been explicitly
637 # assigned as children and make them children of the object that
638 # they were assigned to as a parameter value. This guarantees
639 # that when we instantiate all the parameter objects we're still
640 # inside the configuration hierarchy.
641 def adoptOrphanParams(self
):
642 for key
,val
in self
._values
.iteritems():
643 if not isSimObjectVector(val
) and isSimObjectSequence(val
):
644 # need to convert raw SimObject sequences to
645 # SimObjectVector class so we can call get_parent()
646 val
= SimObjectVector(val
)
647 self
._values
[key
] = val
648 if isSimObjectOrVector(val
) and not val
.get_parent():
649 self
.add_child(key
, val
)
654 ppath
= self
._parent
.path()
657 return ppath
+ "." + self
._name
665 def find_any(self
, ptype
):
666 if isinstance(self
, ptype
):
670 for child
in self
._children
.itervalues():
671 if isinstance(child
, ptype
):
672 if found_obj
!= None and child
!= found_obj
:
673 raise AttributeError, \
674 'parent.any matched more than one: %s %s' % \
675 (found_obj
.path
, child
.path
)
678 for pname
,pdesc
in self
._params
.iteritems():
679 if issubclass(pdesc
.ptype
, ptype
):
680 match_obj
= self
._values
[pname
]
681 if found_obj
!= None and found_obj
!= match_obj
:
682 raise AttributeError, \
683 'parent.any matched more than one: %s and %s' % (found_obj
.path
, match_obj
.path
)
684 found_obj
= match_obj
685 return found_obj
, found_obj
!= None
687 def unproxy(self
, base
):
690 def unproxyParams(self
):
691 for param
in self
._params
.iterkeys():
692 value
= self
._values
.get(param
)
693 if value
!= None and isproxy(value
):
695 value
= value
.unproxy(self
)
697 print "Error in unproxying param '%s' of %s" % \
700 setattr(self
, param
, value
)
702 # Unproxy ports in sorted order so that 'append' operations on
703 # vector ports are done in a deterministic fashion.
704 port_names
= self
._ports
.keys()
706 for port_name
in port_names
:
707 port
= self
._port
_refs
.get(port_name
)
711 def print_ini(self
, ini_file
):
712 print >>ini_file
, '[' + self
.path() + ']' # .ini section header
714 instanceDict
[self
.path()] = self
716 if hasattr(self
, 'type'):
717 print >>ini_file
, 'type=%s' % self
.type
719 child_names
= self
._children
.keys()
722 print >>ini_file
, 'children=%s' % \
723 ' '.join(self
._children
[n
].get_name() for n
in child_names
)
725 param_names
= self
._params
.keys()
727 for param
in param_names
:
728 value
= self
._values
.get(param
)
730 print >>ini_file
, '%s=%s' % (param
,
731 self
._values
[param
].ini_str())
733 port_names
= self
._ports
.keys()
735 for port_name
in port_names
:
736 port
= self
._port
_refs
.get(port_name
, None)
738 print >>ini_file
, '%s=%s' % (port_name
, port
.ini_str())
740 print >>ini_file
# blank line between objects
742 def getCCParams(self
):
744 return self
._ccParams
746 cc_params_struct
= getattr(m5
.objects
.params
, '%sParams' % self
.type)
747 cc_params
= cc_params_struct()
748 cc_params
.pyobj
= self
749 cc_params
.name
= str(self
)
751 param_names
= self
._params
.keys()
753 for param
in param_names
:
754 value
= self
._values
.get(param
)
756 fatal("%s.%s without default or user set value",
759 value
= value
.getValue()
760 if isinstance(self
._params
[param
], VectorParamDesc
):
761 assert isinstance(value
, list)
762 vec
= getattr(cc_params
, param
)
767 setattr(cc_params
, param
, value
)
769 port_names
= self
._ports
.keys()
771 for port_name
in port_names
:
772 port
= self
._port
_refs
.get(port_name
, None)
774 setattr(cc_params
, port_name
, port
)
775 self
._ccParams
= cc_params
776 return self
._ccParams
778 # Get C++ object corresponding to this object, calling C++ if
779 # necessary to construct it. Does *not* recursively create
781 def getCCObject(self
):
782 if not self
._ccObject
:
783 # Make sure this object is in the configuration hierarchy
784 if not self
._parent
and not isRoot(self
):
785 raise RuntimeError, "Attempt to instantiate orphan node"
786 # Cycles in the configuration hierarchy are not supported. This
787 # will catch the resulting recursion and stop.
789 params
= self
.getCCParams()
790 self
._ccObject
= params
.create()
791 elif self
._ccObject
== -1:
792 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \
794 return self
._ccObject
796 def descendants(self
):
798 for child
in self
._children
.itervalues():
799 for obj
in child
.descendants():
802 # Call C++ to create C++ object corresponding to this object
803 def createCCObject(self
):
805 self
.getCCObject() # force creation
808 return self
.getCCObject()
810 # Create C++ port connections corresponding to the connections in
812 def connectPorts(self
):
813 for portRef
in self
._port
_refs
.itervalues():
816 def getMemoryMode(self
):
817 if not isinstance(self
, m5
.objects
.System
):
820 return self
._ccObject
.getMemoryMode()
822 def changeTiming(self
, mode
):
823 if isinstance(self
, m5
.objects
.System
):
824 # i don't know if there's a better way to do this - calling
825 # setMemoryMode directly from self._ccObject results in calling
826 # SimObject::setMemoryMode, not the System::setMemoryMode
827 self
._ccObject
.setMemoryMode(mode
)
829 def takeOverFrom(self
, old_cpu
):
830 self
._ccObject
.takeOverFrom(old_cpu
._ccObject
)
832 # generate output file for 'dot' to display as a pretty graph.
833 # this code is currently broken.
834 def outputDot(self
, dot
):
835 label
= "{%s|" % self
.path
836 if isSimObject(self
.realtype
):
837 label
+= '%s|' % self
.type
840 # instantiate children in same order they were added for
841 # backward compatibility (else we can end up with cpu1
843 for c
in self
.children
:
844 dot
.add_edge(pydot
.Edge(self
.path
,c
.path
, style
="bold"))
847 for param
in self
.params
:
849 if param
.value
is None:
850 raise AttributeError, 'Parameter with no value'
853 string
= param
.string(value
)
855 msg
= 'exception in %s:%s\n%s' % (self
.name
, param
.name
, e
)
859 if isSimObject(param
.ptype
) and string
!= "Null":
860 simobjs
.append(string
)
862 label
+= '%s = %s\\n' % (param
.name
, string
)
865 label
+= "|<%s> %s" % (so
, so
)
866 dot
.add_edge(pydot
.Edge("%s:%s" % (self
.path
, so
), so
,
869 dot
.add_node(pydot
.Node(self
.path
,shape
="Mrecord",label
=label
))
871 # recursively dump out children
872 for c
in self
.children
:
875 # Function to provide to C++ so it can look up instances based on paths
876 def resolveSimObject(name
):
877 obj
= instanceDict
[name
]
878 return obj
.getCCObject()
880 def isSimObject(value
):
881 return isinstance(value
, SimObject
)
883 def isSimObjectClass(value
):
884 return issubclass(value
, SimObject
)
886 def isSimObjectVector(value
):
887 return isinstance(value
, SimObjectVector
)
889 def isSimObjectSequence(value
):
890 if not isinstance(value
, (list, tuple)) or len(value
) == 0:
894 if not isNullPointer(val
) and not isSimObject(val
):
899 def isSimObjectOrSequence(value
):
900 return isSimObject(value
) or isSimObjectSequence(value
)
903 from m5
.objects
import Root
904 return obj
and obj
is Root
.getInstance()
906 def isSimObjectOrVector(value
):
907 return isSimObject(value
) or isSimObjectVector(value
)
909 def tryAsSimObjectOrVector(value
):
910 if isSimObjectOrVector(value
):
912 if isSimObjectSequence(value
):
913 return SimObjectVector(value
)
916 def coerceSimObjectOrVector(value
):
917 value
= tryAsSimObjectOrVector(value
)
919 raise TypeError, "SimObject or SimObjectVector expected"
922 baseClasses
= allClasses
.copy()
923 baseInstances
= instanceDict
.copy()
926 global allClasses
, instanceDict
928 allClasses
= baseClasses
.copy()
929 instanceDict
= baseInstances
.copy()
931 # __all__ defines the list of symbols that get exported when
932 # 'from config import *' is invoked. Try to keep this reasonably
933 # short to avoid polluting other namespaces.
934 __all__
= [ 'SimObject' ]