1# Copyright (c) 2004-2006 The Regents of The University of Michigan 2# Copyright (c) 2010 Advanced Micro Devices, Inc. 3# All rights reserved. 4# 5# Redistribution and use in source and binary forms, with or without 6# modification, are permitted provided that the following conditions are 7# met: redistributions of source code must retain the above copyright 8# notice, this list of conditions and the following disclaimer; 9# redistributions in binary form must reproduce the above copyright 10# notice, this list of conditions and the following disclaimer in the 11# documentation and/or other materials provided with the distribution; 12# neither the name of the copyright holders nor the names of its 13# contributors may be used to endorse or promote products derived from 14# this software without specific prior written permission. 15# 16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 18# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 19# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 20# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 21# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 22# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27# 28# Authors: Steve Reinhardt 29# Nathan Binkert 30 31import sys
| 1# Copyright (c) 2004-2006 The Regents of The University of Michigan 2# Copyright (c) 2010 Advanced Micro Devices, Inc. 3# All rights reserved. 4# 5# Redistribution and use in source and binary forms, with or without 6# modification, are permitted provided that the following conditions are 7# met: redistributions of source code must retain the above copyright 8# notice, this list of conditions and the following disclaimer; 9# redistributions in binary form must reproduce the above copyright 10# notice, this list of conditions and the following disclaimer in the 11# documentation and/or other materials provided with the distribution; 12# neither the name of the copyright holders nor the names of its 13# contributors may be used to endorse or promote products derived from 14# this software without specific prior written permission. 15# 16# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 17# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 18# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 19# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 20# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 21# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 22# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 23# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 24# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 26# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27# 28# Authors: Steve Reinhardt 29# Nathan Binkert 30 31import sys
|
32from types import FunctionType
| 32from types import FunctionType, MethodType
|
33 34try: 35 import pydot 36except: 37 pydot = False 38 39import m5 40from m5.util import * 41 42# Have to import params up top since Param is referenced on initial 43# load (when SimObject class references Param to create a class 44# variable, the 'name' param)... 45from m5.params import * 46# There are a few things we need that aren't in params.__all__ since 47# normal users don't need them 48from m5.params import ParamDesc, VectorParamDesc, \ 49 isNullPointer, SimObjectVector 50 51from m5.proxy import * 52from m5.proxy import isproxy 53 54##################################################################### 55# 56# M5 Python Configuration Utility 57# 58# The basic idea is to write simple Python programs that build Python 59# objects corresponding to M5 SimObjects for the desired simulation 60# configuration. For now, the Python emits a .ini file that can be 61# parsed by M5. In the future, some tighter integration between M5 62# and the Python interpreter may allow bypassing the .ini file. 63# 64# Each SimObject class in M5 is represented by a Python class with the 65# same name. The Python inheritance tree mirrors the M5 C++ tree 66# (e.g., SimpleCPU derives from BaseCPU in both cases, and all 67# SimObjects inherit from a single SimObject base class). To specify 68# an instance of an M5 SimObject in a configuration, the user simply 69# instantiates the corresponding Python object. The parameters for 70# that SimObject are given by assigning to attributes of the Python 71# object, either using keyword assignment in the constructor or in 72# separate assignment statements. For example: 73# 74# cache = BaseCache(size='64KB') 75# cache.hit_latency = 3 76# cache.assoc = 8 77# 78# The magic lies in the mapping of the Python attributes for SimObject 79# classes to the actual SimObject parameter specifications. This 80# allows parameter validity checking in the Python code. Continuing 81# the example above, the statements "cache.blurfl=3" or 82# "cache.assoc='hello'" would both result in runtime errors in Python, 83# since the BaseCache object has no 'blurfl' parameter and the 'assoc' 84# parameter requires an integer, respectively. This magic is done 85# primarily by overriding the special __setattr__ method that controls 86# assignment to object attributes. 87# 88# Once a set of Python objects have been instantiated in a hierarchy, 89# calling 'instantiate(obj)' (where obj is the root of the hierarchy) 90# will generate a .ini file. 91# 92##################################################################### 93 94# list of all SimObject classes 95allClasses = {} 96 97# dict to look up SimObjects based on path 98instanceDict = {} 99
| 33 34try: 35 import pydot 36except: 37 pydot = False 38 39import m5 40from m5.util import * 41 42# Have to import params up top since Param is referenced on initial 43# load (when SimObject class references Param to create a class 44# variable, the 'name' param)... 45from m5.params import * 46# There are a few things we need that aren't in params.__all__ since 47# normal users don't need them 48from m5.params import ParamDesc, VectorParamDesc, \ 49 isNullPointer, SimObjectVector 50 51from m5.proxy import * 52from m5.proxy import isproxy 53 54##################################################################### 55# 56# M5 Python Configuration Utility 57# 58# The basic idea is to write simple Python programs that build Python 59# objects corresponding to M5 SimObjects for the desired simulation 60# configuration. For now, the Python emits a .ini file that can be 61# parsed by M5. In the future, some tighter integration between M5 62# and the Python interpreter may allow bypassing the .ini file. 63# 64# Each SimObject class in M5 is represented by a Python class with the 65# same name. The Python inheritance tree mirrors the M5 C++ tree 66# (e.g., SimpleCPU derives from BaseCPU in both cases, and all 67# SimObjects inherit from a single SimObject base class). To specify 68# an instance of an M5 SimObject in a configuration, the user simply 69# instantiates the corresponding Python object. The parameters for 70# that SimObject are given by assigning to attributes of the Python 71# object, either using keyword assignment in the constructor or in 72# separate assignment statements. For example: 73# 74# cache = BaseCache(size='64KB') 75# cache.hit_latency = 3 76# cache.assoc = 8 77# 78# The magic lies in the mapping of the Python attributes for SimObject 79# classes to the actual SimObject parameter specifications. This 80# allows parameter validity checking in the Python code. Continuing 81# the example above, the statements "cache.blurfl=3" or 82# "cache.assoc='hello'" would both result in runtime errors in Python, 83# since the BaseCache object has no 'blurfl' parameter and the 'assoc' 84# parameter requires an integer, respectively. This magic is done 85# primarily by overriding the special __setattr__ method that controls 86# assignment to object attributes. 87# 88# Once a set of Python objects have been instantiated in a hierarchy, 89# calling 'instantiate(obj)' (where obj is the root of the hierarchy) 90# will generate a .ini file. 91# 92##################################################################### 93 94# list of all SimObject classes 95allClasses = {} 96 97# dict to look up SimObjects based on path 98instanceDict = {} 99
|
| 100def default_cxx_predecls(cls, code): 101 '''A forward class declaration is sufficient since we are 102 just declaring a pointer.''' 103 104 class_path = cls._value_dict['cxx_class'].split('::') 105 for ns in class_path[:-1]: 106 code('namespace $ns {') 107 code('class $0;', class_path[-1]) 108 for ns in reversed(class_path[:-1]): 109 code('/* namespace $ns */ }') 110 111def default_swig_objdecls(cls, code): 112 class_path = cls.cxx_class.split('::') 113 classname = class_path[-1] 114 namespaces = class_path[:-1] 115 116 for ns in namespaces: 117 code('namespace $ns {') 118 119 if namespaces: 120 code('// avoid name conflicts') 121 sep_string = '_COLONS_' 122 flat_name = sep_string.join(class_path) 123 code('%rename($flat_name) $classname;') 124 125 code() 126 code('// stop swig from creating/wrapping default ctor/dtor') 127 code('%nodefault $classname;') 128 code('class $classname') 129 if cls._base: 130 code(' : public ${{cls._base.cxx_class}}') 131 code('{};') 132 133 for ns in reversed(namespaces): 134 code('/* namespace $ns */ }') 135 136def public_value(key, value): 137 return key.startswith('_') or \ 138 isinstance(value, (FunctionType, MethodType, classmethod, type)) 139
|
100# The metaclass for SimObject. This class controls how new classes 101# that derive from SimObject are instantiated, and provides inherited 102# class behavior (just like a class controls how instances of that 103# class are instantiated, and provides inherited instance behavior). 104class MetaSimObject(type): 105 # Attributes that can be set only at initialization time 106 init_keywords = { 'abstract' : bool, 107 'cxx_class' : str, 108 'cxx_type' : str,
| 140# The metaclass for SimObject. This class controls how new classes 141# that derive from SimObject are instantiated, and provides inherited 142# class behavior (just like a class controls how instances of that 143# class are instantiated, and provides inherited instance behavior). 144class MetaSimObject(type): 145 # Attributes that can be set only at initialization time 146 init_keywords = { 'abstract' : bool, 147 'cxx_class' : str, 148 'cxx_type' : str,
|
109 'cxx_predecls' : list, 110 'swig_objdecls' : list, 111 'swig_predecls' : list,
| 149 'cxx_predecls' : MethodType, 150 'swig_objdecls' : MethodType, 151 'swig_predecls' : MethodType,
|
112 'type' : str } 113 # Attributes that can be set any time 114 keywords = { 'check' : FunctionType } 115 116 # __new__ is called before __init__, and is where the statements 117 # in the body of the class definition get loaded into the class's 118 # __dict__. We intercept this to filter out parameter & port assignments 119 # and only allow "private" attributes to be passed to the base 120 # __new__ (starting with underscore). 121 def __new__(mcls, name, bases, dict): 122 assert name not in allClasses, "SimObject %s already present" % name 123 124 # Copy "private" attributes, functions, and classes to the 125 # official dict. Everything else goes in _init_dict to be 126 # filtered in __init__. 127 cls_dict = {} 128 value_dict = {} 129 for key,val in dict.items():
| 152 'type' : str } 153 # Attributes that can be set any time 154 keywords = { 'check' : FunctionType } 155 156 # __new__ is called before __init__, and is where the statements 157 # in the body of the class definition get loaded into the class's 158 # __dict__. We intercept this to filter out parameter & port assignments 159 # and only allow "private" attributes to be passed to the base 160 # __new__ (starting with underscore). 161 def __new__(mcls, name, bases, dict): 162 assert name not in allClasses, "SimObject %s already present" % name 163 164 # Copy "private" attributes, functions, and classes to the 165 # official dict. Everything else goes in _init_dict to be 166 # filtered in __init__. 167 cls_dict = {} 168 value_dict = {} 169 for key,val in dict.items():
|
130 if key.startswith('_') or isinstance(val, (FunctionType, 131 classmethod, 132 type)):
| 170 if public_value(key, val):
|
133 cls_dict[key] = val 134 else: 135 # must be a param/port setting 136 value_dict[key] = val 137 if 'abstract' not in value_dict: 138 value_dict['abstract'] = False 139 cls_dict['_value_dict'] = value_dict 140 cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict) 141 if 'type' in value_dict: 142 allClasses[name] = cls 143 return cls 144 145 # subclass initialization 146 def __init__(cls, name, bases, dict): 147 # calls type.__init__()... I think that's a no-op, but leave 148 # it here just in case it's not. 149 super(MetaSimObject, cls).__init__(name, bases, dict) 150 151 # initialize required attributes 152 153 # class-only attributes 154 cls._params = multidict() # param descriptions 155 cls._ports = multidict() # port descriptions 156 157 # class or instance attributes 158 cls._values = multidict() # param values 159 cls._children = multidict() # SimObject children 160 cls._port_refs = multidict() # port ref objects 161 cls._instantiated = False # really instantiated, cloned, or subclassed 162 163 # We don't support multiple inheritance. If you want to, you 164 # must fix multidict to deal with it properly. 165 if len(bases) > 1: 166 raise TypeError, "SimObjects do not support multiple inheritance" 167 168 base = bases[0] 169 170 # Set up general inheritance via multidicts. A subclass will 171 # inherit all its settings from the base class. The only time 172 # the following is not true is when we define the SimObject 173 # class itself (in which case the multidicts have no parent). 174 if isinstance(base, MetaSimObject): 175 cls._base = base 176 cls._params.parent = base._params 177 cls._ports.parent = base._ports 178 cls._values.parent = base._values 179 cls._children.parent = base._children 180 cls._port_refs.parent = base._port_refs 181 # mark base as having been subclassed 182 base._instantiated = True 183 else: 184 cls._base = None 185 186 # default keyword values 187 if 'type' in cls._value_dict: 188 if 'cxx_class' not in cls._value_dict: 189 cls._value_dict['cxx_class'] = cls._value_dict['type'] 190 191 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class'] 192
| 171 cls_dict[key] = val 172 else: 173 # must be a param/port setting 174 value_dict[key] = val 175 if 'abstract' not in value_dict: 176 value_dict['abstract'] = False 177 cls_dict['_value_dict'] = value_dict 178 cls = super(MetaSimObject, mcls).__new__(mcls, name, bases, cls_dict) 179 if 'type' in value_dict: 180 allClasses[name] = cls 181 return cls 182 183 # subclass initialization 184 def __init__(cls, name, bases, dict): 185 # calls type.__init__()... I think that's a no-op, but leave 186 # it here just in case it's not. 187 super(MetaSimObject, cls).__init__(name, bases, dict) 188 189 # initialize required attributes 190 191 # class-only attributes 192 cls._params = multidict() # param descriptions 193 cls._ports = multidict() # port descriptions 194 195 # class or instance attributes 196 cls._values = multidict() # param values 197 cls._children = multidict() # SimObject children 198 cls._port_refs = multidict() # port ref objects 199 cls._instantiated = False # really instantiated, cloned, or subclassed 200 201 # We don't support multiple inheritance. If you want to, you 202 # must fix multidict to deal with it properly. 203 if len(bases) > 1: 204 raise TypeError, "SimObjects do not support multiple inheritance" 205 206 base = bases[0] 207 208 # Set up general inheritance via multidicts. A subclass will 209 # inherit all its settings from the base class. The only time 210 # the following is not true is when we define the SimObject 211 # class itself (in which case the multidicts have no parent). 212 if isinstance(base, MetaSimObject): 213 cls._base = base 214 cls._params.parent = base._params 215 cls._ports.parent = base._ports 216 cls._values.parent = base._values 217 cls._children.parent = base._children 218 cls._port_refs.parent = base._port_refs 219 # mark base as having been subclassed 220 base._instantiated = True 221 else: 222 cls._base = None 223 224 # default keyword values 225 if 'type' in cls._value_dict: 226 if 'cxx_class' not in cls._value_dict: 227 cls._value_dict['cxx_class'] = cls._value_dict['type'] 228 229 cls._value_dict['cxx_type'] = '%s *' % cls._value_dict['cxx_class'] 230
|
193 if 'cxx_predecls' not in cls._value_dict: 194 # A forward class declaration is sufficient since we are 195 # just declaring a pointer. 196 class_path = cls._value_dict['cxx_class'].split('::') 197 class_path.reverse() 198 decl = 'class %s;' % class_path[0] 199 for ns in class_path[1:]: 200 decl = 'namespace %s { %s }' % (ns, decl) 201 cls._value_dict['cxx_predecls'] = [decl]
| 231 if 'cxx_predecls' not in cls.__dict__: 232 m = MethodType(default_cxx_predecls, cls, MetaSimObject) 233 setattr(cls, 'cxx_predecls', m)
|
202
| 234
|
203 if 'swig_predecls' not in cls._value_dict: 204 # A forward class declaration is sufficient since we are 205 # just declaring a pointer. 206 cls._value_dict['swig_predecls'] = \ 207 cls._value_dict['cxx_predecls']
| 235 if 'swig_predecls' not in cls.__dict__: 236 setattr(cls, 'swig_predecls', getattr(cls, 'cxx_predecls'))
|
208
| 237
|
209 if 'swig_objdecls' not in cls._value_dict: 210 cls._value_dict['swig_objdecls'] = []
| 238 if 'swig_objdecls' not in cls.__dict__: 239 m = MethodType(default_swig_objdecls, cls, MetaSimObject) 240 setattr(cls, 'swig_objdecls', m)
|
211 212 # Now process the _value_dict items. They could be defining 213 # new (or overriding existing) parameters or ports, setting 214 # class keywords (e.g., 'abstract'), or setting parameter 215 # values or port bindings. The first 3 can only be set when 216 # the class is defined, so we handle them here. The others 217 # can be set later too, so just emulate that by calling 218 # setattr(). 219 for key,val in cls._value_dict.items(): 220 # param descriptions 221 if isinstance(val, ParamDesc): 222 cls._new_param(key, val) 223 224 # port objects 225 elif isinstance(val, Port): 226 cls._new_port(key, val) 227 228 # init-time-only keywords 229 elif cls.init_keywords.has_key(key): 230 cls._set_keyword(key, val, cls.init_keywords[key]) 231 232 # default: use normal path (ends up in __setattr__) 233 else: 234 setattr(cls, key, val) 235 236 def _set_keyword(cls, keyword, val, kwtype): 237 if not isinstance(val, kwtype): 238 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \ 239 (keyword, type(val), kwtype) 240 if isinstance(val, FunctionType): 241 val = classmethod(val) 242 type.__setattr__(cls, keyword, val) 243 244 def _new_param(cls, name, pdesc): 245 # each param desc should be uniquely assigned to one variable 246 assert(not hasattr(pdesc, 'name')) 247 pdesc.name = name 248 cls._params[name] = pdesc 249 if hasattr(pdesc, 'default'): 250 cls._set_param(name, pdesc.default, pdesc) 251 252 def _set_param(cls, name, value, param): 253 assert(param.name == name) 254 try: 255 cls._values[name] = param.convert(value) 256 except Exception, e: 257 msg = "%s\nError setting param %s.%s to %s\n" % \ 258 (e, cls.__name__, name, value) 259 e.args = (msg, ) 260 raise 261 262 def _new_port(cls, name, port): 263 # each port should be uniquely assigned to one variable 264 assert(not hasattr(port, 'name')) 265 port.name = name 266 cls._ports[name] = port 267 if hasattr(port, 'default'): 268 cls._cls_get_port_ref(name).connect(port.default) 269 270 # same as _get_port_ref, effectively, but for classes 271 def _cls_get_port_ref(cls, attr): 272 # Return reference that can be assigned to another port 273 # via __setattr__. There is only ever one reference 274 # object per port, but we create them lazily here. 275 ref = cls._port_refs.get(attr) 276 if not ref: 277 ref = cls._ports[attr].makeRef(cls) 278 cls._port_refs[attr] = ref 279 return ref 280 281 # Set attribute (called on foo.attr = value when foo is an 282 # instance of class cls). 283 def __setattr__(cls, attr, value): 284 # normal processing for private attributes
| 241 242 # Now process the _value_dict items. They could be defining 243 # new (or overriding existing) parameters or ports, setting 244 # class keywords (e.g., 'abstract'), or setting parameter 245 # values or port bindings. The first 3 can only be set when 246 # the class is defined, so we handle them here. The others 247 # can be set later too, so just emulate that by calling 248 # setattr(). 249 for key,val in cls._value_dict.items(): 250 # param descriptions 251 if isinstance(val, ParamDesc): 252 cls._new_param(key, val) 253 254 # port objects 255 elif isinstance(val, Port): 256 cls._new_port(key, val) 257 258 # init-time-only keywords 259 elif cls.init_keywords.has_key(key): 260 cls._set_keyword(key, val, cls.init_keywords[key]) 261 262 # default: use normal path (ends up in __setattr__) 263 else: 264 setattr(cls, key, val) 265 266 def _set_keyword(cls, keyword, val, kwtype): 267 if not isinstance(val, kwtype): 268 raise TypeError, 'keyword %s has bad type %s (expecting %s)' % \ 269 (keyword, type(val), kwtype) 270 if isinstance(val, FunctionType): 271 val = classmethod(val) 272 type.__setattr__(cls, keyword, val) 273 274 def _new_param(cls, name, pdesc): 275 # each param desc should be uniquely assigned to one variable 276 assert(not hasattr(pdesc, 'name')) 277 pdesc.name = name 278 cls._params[name] = pdesc 279 if hasattr(pdesc, 'default'): 280 cls._set_param(name, pdesc.default, pdesc) 281 282 def _set_param(cls, name, value, param): 283 assert(param.name == name) 284 try: 285 cls._values[name] = param.convert(value) 286 except Exception, e: 287 msg = "%s\nError setting param %s.%s to %s\n" % \ 288 (e, cls.__name__, name, value) 289 e.args = (msg, ) 290 raise 291 292 def _new_port(cls, name, port): 293 # each port should be uniquely assigned to one variable 294 assert(not hasattr(port, 'name')) 295 port.name = name 296 cls._ports[name] = port 297 if hasattr(port, 'default'): 298 cls._cls_get_port_ref(name).connect(port.default) 299 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) 306 if not ref: 307 ref = cls._ports[attr].makeRef(cls) 308 cls._port_refs[attr] = ref 309 return ref 310 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
|
285 if attr.startswith('_'):
| 315 if public_value(attr, value):
|
286 type.__setattr__(cls, attr, value) 287 return 288 289 if cls.keywords.has_key(attr): 290 cls._set_keyword(attr, value, cls.keywords[attr]) 291 return 292 293 if cls._ports.has_key(attr): 294 cls._cls_get_port_ref(attr).connect(value) 295 return 296 297 if isSimObjectOrSequence(value) and cls._instantiated: 298 raise RuntimeError, \ 299 "cannot set SimObject parameter '%s' after\n" \ 300 " class %s has been instantiated or subclassed" \ 301 % (attr, cls.__name__) 302 303 # check for param 304 param = cls._params.get(attr) 305 if param: 306 cls._set_param(attr, value, param) 307 return 308 309 if isSimObjectOrSequence(value): 310 # If RHS is a SimObject, it's an implicit child assignment. 311 cls._children[attr] = coerceSimObjectOrVector(value) 312 return 313 314 # no valid assignment... raise exception 315 raise AttributeError, \ 316 "Class %s has no parameter \'%s\'" % (cls.__name__, attr) 317 318 def __getattr__(cls, attr): 319 if cls._values.has_key(attr): 320 return cls._values[attr] 321 322 if cls._children.has_key(attr): 323 return cls._children[attr] 324 325 raise AttributeError, \ 326 "object '%s' has no attribute '%s'" % (cls.__name__, attr) 327 328 def __str__(cls): 329 return cls.__name__ 330
| 316 type.__setattr__(cls, attr, value) 317 return 318 319 if cls.keywords.has_key(attr): 320 cls._set_keyword(attr, value, cls.keywords[attr]) 321 return 322 323 if cls._ports.has_key(attr): 324 cls._cls_get_port_ref(attr).connect(value) 325 return 326 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__) 332 333 # check for param 334 param = cls._params.get(attr) 335 if param: 336 cls._set_param(attr, value, param) 337 return 338 339 if isSimObjectOrSequence(value): 340 # If RHS is a SimObject, it's an implicit child assignment. 341 cls._children[attr] = coerceSimObjectOrVector(value) 342 return 343 344 # no valid assignment... raise exception 345 raise AttributeError, \ 346 "Class %s has no parameter \'%s\'" % (cls.__name__, attr) 347 348 def __getattr__(cls, attr): 349 if cls._values.has_key(attr): 350 return cls._values[attr] 351 352 if cls._children.has_key(attr): 353 return cls._children[attr] 354 355 raise AttributeError, \ 356 "object '%s' has no attribute '%s'" % (cls.__name__, attr) 357 358 def __str__(cls): 359 return cls.__name__ 360
|
331 def cxx_decl(cls): 332 code = "#ifndef __PARAMS__%s\n" % cls 333 code += "#define __PARAMS__%s\n\n" % cls
| 361 def cxx_decl(cls, code): 362 code('''\ 363#ifndef __PARAMS__${cls}__ 364#define __PARAMS__${cls}__
|
334
| 365
|
| 366''') 367
|
335 # The 'dict' attribute restricts us to the params declared in 336 # the object itself, not including inherited params (which 337 # will also be inherited from the base class's param struct 338 # here). 339 params = cls._params.local.values() 340 try: 341 ptypes = [p.ptype for p in params] 342 except: 343 print cls, p, p.ptype_str 344 print params 345 raise 346
| 368 # The 'dict' attribute restricts us to the params declared in 369 # the object itself, not including inherited params (which 370 # will also be inherited from the base class's param struct 371 # here). 372 params = cls._params.local.values() 373 try: 374 ptypes = [p.ptype for p in params] 375 except: 376 print cls, p, p.ptype_str 377 print params 378 raise 379
|
347 # get a list of lists of predeclaration lines 348 predecls = [] 349 predecls.extend(cls.cxx_predecls) 350 for p in params: 351 predecls.extend(p.cxx_predecls()) 352 # remove redundant lines 353 predecls2 = [] 354 for pd in predecls: 355 if pd not in predecls2: 356 predecls2.append(pd) 357 predecls2.sort() 358 code += "\n".join(predecls2) 359 code += "\n\n";
| 380 # get all predeclarations 381 cls.cxx_predecls(code) 382 for param in params: 383 param.cxx_predecls(code) 384 code()
|
360 361 if cls._base:
| 385 386 if cls._base:
|
362 code += '#include "params/%s.hh"\n\n' % cls._base.type
| 387 code('#include "params/${{cls._base.type}}.hh"') 388 code()
|
363 364 for ptype in ptypes: 365 if issubclass(ptype, Enum):
| 389 390 for ptype in ptypes: 391 if issubclass(ptype, Enum):
|
366 code += '#include "enums/%s.hh"\n' % ptype.__name__ 367 code += "\n\n"
| 392 code('#include "enums/${{ptype.__name__}}.hh"') 393 code()
|
368
| 394
|
369 code += cls.cxx_struct(cls._base, params)
| 395 cls.cxx_struct(code, cls._base, params)
|
370 371 # close #ifndef __PARAMS__* guard
| 396 397 # close #ifndef __PARAMS__* guard
|
372 code += "\n#endif\n"
| 398 code() 399 code('#endif // __PARAMS__${cls}__')
|
373 return code 374
| 400 return code 401
|
375 def cxx_struct(cls, base, params):
| 402 def cxx_struct(cls, code, base, params):
|
376 if cls == SimObject:
| 403 if cls == SimObject:
|
377 return '#include "sim/sim_object_params.hh"\n'
| 404 code('#include "sim/sim_object_params.hh"') 405 return
|
378 379 # now generate the actual param struct
| 406 407 # now generate the actual param struct
|
380 code = "struct %sParams" % cls
| 408 code("struct ${cls}Params")
|
381 if base:
| 409 if base:
|
382 code += " : public %sParams" % base.type 383 code += "\n{\n"
| 410 code(" : public ${{base.type}}Params") 411 code("{")
|
384 if not hasattr(cls, 'abstract') or not cls.abstract: 385 if 'type' in cls.__dict__:
| 412 if not hasattr(cls, 'abstract') or not cls.abstract: 413 if 'type' in cls.__dict__:
|
386 code += " %s create();\n" % cls.cxx_type 387 decls = [p.cxx_decl() for p in params] 388 decls.sort() 389 code += "".join([" %s\n" % d for d in decls]) 390 code += "};\n"
| 414 code(" ${{cls.cxx_type}} create();")
|
391
| 415
|
392 return code
| 416 code.indent() 417 for param in params: 418 param.cxx_decl(code) 419 code.dedent() 420 code('};')
|
393
| 421
|
394 def swig_decl(cls): 395 code = '%%module %s\n' % cls
| 422 def swig_decl(cls, code): 423 code('''\ 424%module $cls
|
396
| 425
|
397 code += '%{\n' 398 code += '#include "params/%s.hh"\n' % cls 399 code += '%}\n\n'
| 426%{ 427#include "params/$cls.hh" 428%}
|
400
| 429
|
| 430''') 431
|
401 # The 'dict' attribute restricts us to the params declared in 402 # the object itself, not including inherited params (which 403 # will also be inherited from the base class's param struct 404 # here). 405 params = cls._params.local.values() 406 ptypes = [p.ptype for p in params] 407
| 432 # The 'dict' attribute restricts us to the params declared in 433 # the object itself, not including inherited params (which 434 # will also be inherited from the base class's param struct 435 # here). 436 params = cls._params.local.values() 437 ptypes = [p.ptype for p in params] 438
|
408 # get a list of lists of predeclaration lines 409 predecls = [] 410 predecls.extend([ p.swig_predecls() for p in params ]) 411 # flatten 412 predecls = reduce(lambda x,y:x+y, predecls, []) 413 # remove redundant lines 414 predecls2 = [] 415 for pd in predecls: 416 if pd not in predecls2: 417 predecls2.append(pd) 418 predecls2.sort() 419 code += "\n".join(predecls2) 420 code += "\n\n";
| 439 # get all predeclarations 440 for param in params: 441 param.swig_predecls(code) 442 code()
|
421 422 if cls._base:
| 443 444 if cls._base:
|
423 code += '%%import "params/%s.i"\n\n' % cls._base.type
| 445 code('%import "params/${{cls._base.type}}.i"') 446 code()
|
424 425 for ptype in ptypes: 426 if issubclass(ptype, Enum):
| 447 448 for ptype in ptypes: 449 if issubclass(ptype, Enum):
|
427 code += '%%import "enums/%s.hh"\n' % ptype.__name__ 428 code += "\n\n"
| 450 code('%import "enums/${{ptype.__name__}}.hh"') 451 code()
|
429
| 452
|
430 code += '%%import "params/%s_type.hh"\n\n' % cls 431 code += '%%include "params/%s.hh"\n\n' % cls
| 453 code('%import "params/${cls}_type.hh"') 454 code('%include "params/${cls}.hh"')
|
432
| 455
|
433 return code 434
| |
435# The SimObject class is the root of the special hierarchy. Most of 436# the code in this class deals with the configuration hierarchy itself 437# (parent/child node relationships). 438class SimObject(object): 439 # Specify metaclass. Any class inheriting from SimObject will 440 # get this metaclass. 441 __metaclass__ = MetaSimObject 442 type = 'SimObject' 443 abstract = True 444
| 456# The SimObject class is the root of the special hierarchy. Most of 457# the code in this class deals with the configuration hierarchy itself 458# (parent/child node relationships). 459class SimObject(object): 460 # Specify metaclass. Any class inheriting from SimObject will 461 # get this metaclass. 462 __metaclass__ = MetaSimObject 463 type = 'SimObject' 464 abstract = True 465
|
445 swig_objdecls = [ '%include "python/swig/sim_object.i"' ]
| 466 @classmethod 467 def swig_objdecls(cls, code): 468 code('%include "python/swig/sim_object.i"')
|
446 447 # Initialize new instance. For objects with SimObject-valued 448 # children, we need to recursively clone the classes represented 449 # by those param values as well in a consistent "deep copy"-style 450 # fashion. That is, we want to make sure that each instance is 451 # cloned only once, and that if there are multiple references to 452 # the same original object, we end up with the corresponding 453 # cloned references all pointing to the same cloned instance. 454 def __init__(self, **kwargs): 455 ancestor = kwargs.get('_ancestor') 456 memo_dict = kwargs.get('_memo') 457 if memo_dict is None: 458 # prepare to memoize any recursively instantiated objects 459 memo_dict = {} 460 elif ancestor: 461 # memoize me now to avoid problems with recursive calls 462 memo_dict[ancestor] = self 463 464 if not ancestor: 465 ancestor = self.__class__ 466 ancestor._instantiated = True 467 468 # initialize required attributes 469 self._parent = None 470 self._name = None 471 self._ccObject = None # pointer to C++ object 472 self._ccParams = None 473 self._instantiated = False # really "cloned" 474 475 # Inherit parameter values from class using multidict so 476 # individual value settings can be overridden but we still 477 # inherit late changes to non-overridden class values. 478 self._values = multidict(ancestor._values) 479 # clone SimObject-valued parameters 480 for key,val in ancestor._values.iteritems(): 481 val = tryAsSimObjectOrVector(val) 482 if val is not None: 483 self._values[key] = val(_memo=memo_dict) 484 485 # Clone children specified at class level. No need for a 486 # multidict here since we will be cloning everything. 487 self._children = {} 488 for key,val in ancestor._children.iteritems(): 489 self.add_child(key, val(_memo=memo_dict)) 490 491 # clone port references. no need to use a multidict here 492 # since we will be creating new references for all ports. 493 self._port_refs = {} 494 for key,val in ancestor._port_refs.iteritems(): 495 self._port_refs[key] = val.clone(self, memo_dict) 496 # apply attribute assignments from keyword args, if any 497 for key,val in kwargs.iteritems(): 498 setattr(self, key, val) 499 500 # "Clone" the current instance by creating another instance of 501 # this instance's class, but that inherits its parameter values 502 # and port mappings from the current instance. If we're in a 503 # "deep copy" recursive clone, check the _memo dict to see if 504 # we've already cloned this instance. 505 def __call__(self, **kwargs): 506 memo_dict = kwargs.get('_memo') 507 if memo_dict is None: 508 # no memo_dict: must be top-level clone operation. 509 # this is only allowed at the root of a hierarchy 510 if self._parent: 511 raise RuntimeError, "attempt to clone object %s " \ 512 "not at the root of a tree (parent = %s)" \ 513 % (self, self._parent) 514 # create a new dict and use that. 515 memo_dict = {} 516 kwargs['_memo'] = memo_dict 517 elif memo_dict.has_key(self): 518 # clone already done & memoized 519 return memo_dict[self] 520 return self.__class__(_ancestor = self, **kwargs) 521 522 def _get_port_ref(self, attr): 523 # Return reference that can be assigned to another port 524 # via __setattr__. There is only ever one reference 525 # object per port, but we create them lazily here. 526 ref = self._port_refs.get(attr) 527 if not ref: 528 ref = self._ports[attr].makeRef(self) 529 self._port_refs[attr] = ref 530 return ref 531 532 def __getattr__(self, attr): 533 if self._ports.has_key(attr): 534 return self._get_port_ref(attr) 535 536 if self._values.has_key(attr): 537 return self._values[attr] 538 539 if self._children.has_key(attr): 540 return self._children[attr] 541 542 # If the attribute exists on the C++ object, transparently 543 # forward the reference there. This is typically used for 544 # SWIG-wrapped methods such as init(), regStats(), 545 # regFormulas(), resetStats(), startup(), drain(), and 546 # resume(). 547 if self._ccObject and hasattr(self._ccObject, attr): 548 return getattr(self._ccObject, attr) 549 550 raise AttributeError, "object '%s' has no attribute '%s'" \ 551 % (self.__class__.__name__, attr) 552 553 # Set attribute (called on foo.attr = value when foo is an 554 # instance of class cls). 555 def __setattr__(self, attr, value): 556 # normal processing for private attributes 557 if attr.startswith('_'): 558 object.__setattr__(self, attr, value) 559 return 560 561 if self._ports.has_key(attr): 562 # set up port connection 563 self._get_port_ref(attr).connect(value) 564 return 565 566 if isSimObjectOrSequence(value) and self._instantiated: 567 raise RuntimeError, \ 568 "cannot set SimObject parameter '%s' after\n" \ 569 " instance been cloned %s" % (attr, `self`) 570 571 param = self._params.get(attr) 572 if param: 573 try: 574 value = param.convert(value) 575 except Exception, e: 576 msg = "%s\nError setting param %s.%s to %s\n" % \ 577 (e, self.__class__.__name__, attr, value) 578 e.args = (msg, ) 579 raise 580 self._values[attr] = value 581 return 582 583 # if RHS is a SimObject, it's an implicit child assignment 584 if isSimObjectOrSequence(value): 585 self.add_child(attr, value) 586 return 587 588 # no valid assignment... raise exception 589 raise AttributeError, "Class %s has no parameter %s" \ 590 % (self.__class__.__name__, attr) 591 592 593 # this hack allows tacking a '[0]' onto parameters that may or may 594 # not be vectors, and always getting the first element (e.g. cpus) 595 def __getitem__(self, key): 596 if key == 0: 597 return self 598 raise TypeError, "Non-zero index '%s' to SimObject" % key 599 600 # Also implemented by SimObjectVector 601 def clear_parent(self, old_parent): 602 assert self._parent is old_parent 603 self._parent = None 604 605 # Also implemented by SimObjectVector 606 def set_parent(self, parent, name): 607 self._parent = parent 608 self._name = name 609 610 # Also implemented by SimObjectVector 611 def get_name(self): 612 return self._name 613 614 # use this rather than directly accessing _parent for symmetry 615 # with SimObjectVector 616 def get_parent(self): 617 return self._parent 618 619 # clear out child with given name 620 def clear_child(self, name): 621 child = self._children[name] 622 child.clear_parent(self) 623 del self._children[name] 624 625 # Add a new child to this object. 626 def add_child(self, name, child): 627 child = coerceSimObjectOrVector(child) 628 if child.get_parent(): 629 raise RuntimeError, \ 630 "add_child('%s'): child '%s' already has parent '%s'" % \ 631 (name, child._name, child._parent) 632 if self._children.has_key(name): 633 clear_child(name) 634 child.set_parent(self, name) 635 self._children[name] = child 636 637 # Take SimObject-valued parameters that haven't been explicitly 638 # assigned as children and make them children of the object that 639 # they were assigned to as a parameter value. This guarantees 640 # that when we instantiate all the parameter objects we're still 641 # inside the configuration hierarchy. 642 def adoptOrphanParams(self): 643 for key,val in self._values.iteritems(): 644 if not isSimObjectVector(val) and isSimObjectSequence(val): 645 # need to convert raw SimObject sequences to 646 # SimObjectVector class so we can call get_parent() 647 val = SimObjectVector(val) 648 self._values[key] = val 649 if isSimObjectOrVector(val) and not val.get_parent(): 650 self.add_child(key, val) 651 652 def path(self): 653 if not self._parent: 654 return '(orphan)' 655 ppath = self._parent.path() 656 if ppath == 'root': 657 return self._name 658 return ppath + "." + self._name 659 660 def __str__(self): 661 return self.path() 662 663 def ini_str(self): 664 return self.path() 665 666 def find_any(self, ptype): 667 if isinstance(self, ptype): 668 return self, True 669 670 found_obj = None 671 for child in self._children.itervalues(): 672 if isinstance(child, ptype): 673 if found_obj != None and child != found_obj: 674 raise AttributeError, \ 675 'parent.any matched more than one: %s %s' % \ 676 (found_obj.path, child.path) 677 found_obj = child 678 # search param space 679 for pname,pdesc in self._params.iteritems(): 680 if issubclass(pdesc.ptype, ptype): 681 match_obj = self._values[pname] 682 if found_obj != None and found_obj != match_obj: 683 raise AttributeError, \ 684 'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path) 685 found_obj = match_obj 686 return found_obj, found_obj != None 687 688 def unproxy(self, base): 689 return self 690 691 def unproxyParams(self): 692 for param in self._params.iterkeys(): 693 value = self._values.get(param) 694 if value != None and isproxy(value): 695 try: 696 value = value.unproxy(self) 697 except: 698 print "Error in unproxying param '%s' of %s" % \ 699 (param, self.path()) 700 raise 701 setattr(self, param, value) 702 703 # Unproxy ports in sorted order so that 'append' operations on 704 # vector ports are done in a deterministic fashion. 705 port_names = self._ports.keys() 706 port_names.sort() 707 for port_name in port_names: 708 port = self._port_refs.get(port_name) 709 if port != None: 710 port.unproxy(self) 711 712 def print_ini(self, ini_file): 713 print >>ini_file, '[' + self.path() + ']' # .ini section header 714 715 instanceDict[self.path()] = self 716 717 if hasattr(self, 'type'): 718 print >>ini_file, 'type=%s' % self.type 719 720 child_names = self._children.keys() 721 child_names.sort() 722 if len(child_names): 723 print >>ini_file, 'children=%s' % \ 724 ' '.join(self._children[n].get_name() for n in child_names) 725 726 param_names = self._params.keys() 727 param_names.sort() 728 for param in param_names: 729 value = self._values.get(param) 730 if value != None: 731 print >>ini_file, '%s=%s' % (param, 732 self._values[param].ini_str()) 733 734 port_names = self._ports.keys() 735 port_names.sort() 736 for port_name in port_names: 737 port = self._port_refs.get(port_name, None) 738 if port != None: 739 print >>ini_file, '%s=%s' % (port_name, port.ini_str()) 740 741 print >>ini_file # blank line between objects 742 743 def getCCParams(self): 744 if self._ccParams: 745 return self._ccParams 746 747 cc_params_struct = getattr(m5.objects.params, '%sParams' % self.type) 748 cc_params = cc_params_struct() 749 cc_params.pyobj = self 750 cc_params.name = str(self) 751 752 param_names = self._params.keys() 753 param_names.sort() 754 for param in param_names: 755 value = self._values.get(param) 756 if value is None: 757 fatal("%s.%s without default or user set value", 758 self.path(), param) 759 760 value = value.getValue() 761 if isinstance(self._params[param], VectorParamDesc): 762 assert isinstance(value, list) 763 vec = getattr(cc_params, param) 764 assert not len(vec) 765 for v in value: 766 vec.append(v) 767 else: 768 setattr(cc_params, param, value) 769 770 port_names = self._ports.keys() 771 port_names.sort() 772 for port_name in port_names: 773 port = self._port_refs.get(port_name, None) 774 if port != None: 775 setattr(cc_params, port_name, port) 776 self._ccParams = cc_params 777 return self._ccParams 778 779 # Get C++ object corresponding to this object, calling C++ if 780 # necessary to construct it. Does *not* recursively create 781 # children. 782 def getCCObject(self): 783 if not self._ccObject: 784 # Make sure this object is in the configuration hierarchy 785 if not self._parent and not isRoot(self): 786 raise RuntimeError, "Attempt to instantiate orphan node" 787 # Cycles in the configuration hierarchy are not supported. This 788 # will catch the resulting recursion and stop. 789 self._ccObject = -1 790 params = self.getCCParams() 791 self._ccObject = params.create() 792 elif self._ccObject == -1: 793 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \ 794 % self.path() 795 return self._ccObject 796 797 def descendants(self): 798 yield self 799 for child in self._children.itervalues(): 800 for obj in child.descendants(): 801 yield obj 802 803 # Call C++ to create C++ object corresponding to this object 804 def createCCObject(self): 805 self.getCCParams() 806 self.getCCObject() # force creation 807 808 def getValue(self): 809 return self.getCCObject() 810 811 # Create C++ port connections corresponding to the connections in 812 # _port_refs 813 def connectPorts(self): 814 for portRef in self._port_refs.itervalues(): 815 portRef.ccConnect() 816 817 def getMemoryMode(self): 818 if not isinstance(self, m5.objects.System): 819 return None 820 821 return self._ccObject.getMemoryMode() 822 823 def changeTiming(self, mode): 824 if isinstance(self, m5.objects.System): 825 # i don't know if there's a better way to do this - calling 826 # setMemoryMode directly from self._ccObject results in calling 827 # SimObject::setMemoryMode, not the System::setMemoryMode 828 self._ccObject.setMemoryMode(mode) 829 830 def takeOverFrom(self, old_cpu): 831 self._ccObject.takeOverFrom(old_cpu._ccObject) 832 833 # generate output file for 'dot' to display as a pretty graph. 834 # this code is currently broken. 835 def outputDot(self, dot): 836 label = "{%s|" % self.path 837 if isSimObject(self.realtype): 838 label += '%s|' % self.type 839 840 if self.children: 841 # instantiate children in same order they were added for 842 # backward compatibility (else we can end up with cpu1 843 # before cpu0). 844 for c in self.children: 845 dot.add_edge(pydot.Edge(self.path,c.path, style="bold")) 846 847 simobjs = [] 848 for param in self.params: 849 try: 850 if param.value is None: 851 raise AttributeError, 'Parameter with no value' 852 853 value = param.value 854 string = param.string(value) 855 except Exception, e: 856 msg = 'exception in %s:%s\n%s' % (self.name, param.name, e) 857 e.args = (msg, ) 858 raise 859 860 if isSimObject(param.ptype) and string != "Null": 861 simobjs.append(string) 862 else: 863 label += '%s = %s\\n' % (param.name, string) 864 865 for so in simobjs: 866 label += "|<%s> %s" % (so, so) 867 dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so, 868 tailport="w")) 869 label += '}' 870 dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label)) 871 872 # recursively dump out children 873 for c in self.children: 874 c.outputDot(dot) 875 876# Function to provide to C++ so it can look up instances based on paths 877def resolveSimObject(name): 878 obj = instanceDict[name] 879 return obj.getCCObject() 880 881def isSimObject(value): 882 return isinstance(value, SimObject) 883 884def isSimObjectClass(value): 885 return issubclass(value, SimObject) 886 887def isSimObjectVector(value): 888 return isinstance(value, SimObjectVector) 889 890def isSimObjectSequence(value): 891 if not isinstance(value, (list, tuple)) or len(value) == 0: 892 return False 893 894 for val in value: 895 if not isNullPointer(val) and not isSimObject(val): 896 return False 897 898 return True 899 900def isSimObjectOrSequence(value): 901 return isSimObject(value) or isSimObjectSequence(value) 902 903def isRoot(obj): 904 from m5.objects import Root 905 return obj and obj is Root.getInstance() 906 907def isSimObjectOrVector(value): 908 return isSimObject(value) or isSimObjectVector(value) 909 910def tryAsSimObjectOrVector(value): 911 if isSimObjectOrVector(value): 912 return value 913 if isSimObjectSequence(value): 914 return SimObjectVector(value) 915 return None 916 917def coerceSimObjectOrVector(value): 918 value = tryAsSimObjectOrVector(value) 919 if value is None: 920 raise TypeError, "SimObject or SimObjectVector expected" 921 return value 922 923baseClasses = allClasses.copy() 924baseInstances = instanceDict.copy() 925 926def clear(): 927 global allClasses, instanceDict 928 929 allClasses = baseClasses.copy() 930 instanceDict = baseInstances.copy() 931 932# __all__ defines the list of symbols that get exported when 933# 'from config import *' is invoked. Try to keep this reasonably 934# short to avoid polluting other namespaces. 935__all__ = [ 'SimObject' ]
| 469 470 # Initialize new instance. For objects with SimObject-valued 471 # children, we need to recursively clone the classes represented 472 # by those param values as well in a consistent "deep copy"-style 473 # fashion. That is, we want to make sure that each instance is 474 # cloned only once, and that if there are multiple references to 475 # the same original object, we end up with the corresponding 476 # cloned references all pointing to the same cloned instance. 477 def __init__(self, **kwargs): 478 ancestor = kwargs.get('_ancestor') 479 memo_dict = kwargs.get('_memo') 480 if memo_dict is None: 481 # prepare to memoize any recursively instantiated objects 482 memo_dict = {} 483 elif ancestor: 484 # memoize me now to avoid problems with recursive calls 485 memo_dict[ancestor] = self 486 487 if not ancestor: 488 ancestor = self.__class__ 489 ancestor._instantiated = True 490 491 # initialize required attributes 492 self._parent = None 493 self._name = None 494 self._ccObject = None # pointer to C++ object 495 self._ccParams = None 496 self._instantiated = False # really "cloned" 497 498 # Inherit parameter values from class using multidict so 499 # individual value settings can be overridden but we still 500 # inherit late changes to non-overridden class values. 501 self._values = multidict(ancestor._values) 502 # clone SimObject-valued parameters 503 for key,val in ancestor._values.iteritems(): 504 val = tryAsSimObjectOrVector(val) 505 if val is not None: 506 self._values[key] = val(_memo=memo_dict) 507 508 # Clone children specified at class level. No need for a 509 # multidict here since we will be cloning everything. 510 self._children = {} 511 for key,val in ancestor._children.iteritems(): 512 self.add_child(key, val(_memo=memo_dict)) 513 514 # clone port references. no need to use a multidict here 515 # since we will be creating new references for all ports. 516 self._port_refs = {} 517 for key,val in ancestor._port_refs.iteritems(): 518 self._port_refs[key] = val.clone(self, memo_dict) 519 # apply attribute assignments from keyword args, if any 520 for key,val in kwargs.iteritems(): 521 setattr(self, key, val) 522 523 # "Clone" the current instance by creating another instance of 524 # this instance's class, but that inherits its parameter values 525 # and port mappings from the current instance. If we're in a 526 # "deep copy" recursive clone, check the _memo dict to see if 527 # we've already cloned this instance. 528 def __call__(self, **kwargs): 529 memo_dict = kwargs.get('_memo') 530 if memo_dict is None: 531 # no memo_dict: must be top-level clone operation. 532 # this is only allowed at the root of a hierarchy 533 if self._parent: 534 raise RuntimeError, "attempt to clone object %s " \ 535 "not at the root of a tree (parent = %s)" \ 536 % (self, self._parent) 537 # create a new dict and use that. 538 memo_dict = {} 539 kwargs['_memo'] = memo_dict 540 elif memo_dict.has_key(self): 541 # clone already done & memoized 542 return memo_dict[self] 543 return self.__class__(_ancestor = self, **kwargs) 544 545 def _get_port_ref(self, attr): 546 # Return reference that can be assigned to another port 547 # via __setattr__. There is only ever one reference 548 # object per port, but we create them lazily here. 549 ref = self._port_refs.get(attr) 550 if not ref: 551 ref = self._ports[attr].makeRef(self) 552 self._port_refs[attr] = ref 553 return ref 554 555 def __getattr__(self, attr): 556 if self._ports.has_key(attr): 557 return self._get_port_ref(attr) 558 559 if self._values.has_key(attr): 560 return self._values[attr] 561 562 if self._children.has_key(attr): 563 return self._children[attr] 564 565 # If the attribute exists on the C++ object, transparently 566 # forward the reference there. This is typically used for 567 # SWIG-wrapped methods such as init(), regStats(), 568 # regFormulas(), resetStats(), startup(), drain(), and 569 # resume(). 570 if self._ccObject and hasattr(self._ccObject, attr): 571 return getattr(self._ccObject, attr) 572 573 raise AttributeError, "object '%s' has no attribute '%s'" \ 574 % (self.__class__.__name__, attr) 575 576 # Set attribute (called on foo.attr = value when foo is an 577 # instance of class cls). 578 def __setattr__(self, attr, value): 579 # normal processing for private attributes 580 if attr.startswith('_'): 581 object.__setattr__(self, attr, value) 582 return 583 584 if self._ports.has_key(attr): 585 # set up port connection 586 self._get_port_ref(attr).connect(value) 587 return 588 589 if isSimObjectOrSequence(value) and self._instantiated: 590 raise RuntimeError, \ 591 "cannot set SimObject parameter '%s' after\n" \ 592 " instance been cloned %s" % (attr, `self`) 593 594 param = self._params.get(attr) 595 if param: 596 try: 597 value = param.convert(value) 598 except Exception, e: 599 msg = "%s\nError setting param %s.%s to %s\n" % \ 600 (e, self.__class__.__name__, attr, value) 601 e.args = (msg, ) 602 raise 603 self._values[attr] = value 604 return 605 606 # if RHS is a SimObject, it's an implicit child assignment 607 if isSimObjectOrSequence(value): 608 self.add_child(attr, value) 609 return 610 611 # no valid assignment... raise exception 612 raise AttributeError, "Class %s has no parameter %s" \ 613 % (self.__class__.__name__, attr) 614 615 616 # this hack allows tacking a '[0]' onto parameters that may or may 617 # not be vectors, and always getting the first element (e.g. cpus) 618 def __getitem__(self, key): 619 if key == 0: 620 return self 621 raise TypeError, "Non-zero index '%s' to SimObject" % key 622 623 # Also implemented by SimObjectVector 624 def clear_parent(self, old_parent): 625 assert self._parent is old_parent 626 self._parent = None 627 628 # Also implemented by SimObjectVector 629 def set_parent(self, parent, name): 630 self._parent = parent 631 self._name = name 632 633 # Also implemented by SimObjectVector 634 def get_name(self): 635 return self._name 636 637 # use this rather than directly accessing _parent for symmetry 638 # with SimObjectVector 639 def get_parent(self): 640 return self._parent 641 642 # clear out child with given name 643 def clear_child(self, name): 644 child = self._children[name] 645 child.clear_parent(self) 646 del self._children[name] 647 648 # Add a new child to this object. 649 def add_child(self, name, child): 650 child = coerceSimObjectOrVector(child) 651 if child.get_parent(): 652 raise RuntimeError, \ 653 "add_child('%s'): child '%s' already has parent '%s'" % \ 654 (name, child._name, child._parent) 655 if self._children.has_key(name): 656 clear_child(name) 657 child.set_parent(self, name) 658 self._children[name] = child 659 660 # Take SimObject-valued parameters that haven't been explicitly 661 # assigned as children and make them children of the object that 662 # they were assigned to as a parameter value. This guarantees 663 # that when we instantiate all the parameter objects we're still 664 # inside the configuration hierarchy. 665 def adoptOrphanParams(self): 666 for key,val in self._values.iteritems(): 667 if not isSimObjectVector(val) and isSimObjectSequence(val): 668 # need to convert raw SimObject sequences to 669 # SimObjectVector class so we can call get_parent() 670 val = SimObjectVector(val) 671 self._values[key] = val 672 if isSimObjectOrVector(val) and not val.get_parent(): 673 self.add_child(key, val) 674 675 def path(self): 676 if not self._parent: 677 return '(orphan)' 678 ppath = self._parent.path() 679 if ppath == 'root': 680 return self._name 681 return ppath + "." + self._name 682 683 def __str__(self): 684 return self.path() 685 686 def ini_str(self): 687 return self.path() 688 689 def find_any(self, ptype): 690 if isinstance(self, ptype): 691 return self, True 692 693 found_obj = None 694 for child in self._children.itervalues(): 695 if isinstance(child, ptype): 696 if found_obj != None and child != found_obj: 697 raise AttributeError, \ 698 'parent.any matched more than one: %s %s' % \ 699 (found_obj.path, child.path) 700 found_obj = child 701 # search param space 702 for pname,pdesc in self._params.iteritems(): 703 if issubclass(pdesc.ptype, ptype): 704 match_obj = self._values[pname] 705 if found_obj != None and found_obj != match_obj: 706 raise AttributeError, \ 707 'parent.any matched more than one: %s and %s' % (found_obj.path, match_obj.path) 708 found_obj = match_obj 709 return found_obj, found_obj != None 710 711 def unproxy(self, base): 712 return self 713 714 def unproxyParams(self): 715 for param in self._params.iterkeys(): 716 value = self._values.get(param) 717 if value != None and isproxy(value): 718 try: 719 value = value.unproxy(self) 720 except: 721 print "Error in unproxying param '%s' of %s" % \ 722 (param, self.path()) 723 raise 724 setattr(self, param, value) 725 726 # Unproxy ports in sorted order so that 'append' operations on 727 # vector ports are done in a deterministic fashion. 728 port_names = self._ports.keys() 729 port_names.sort() 730 for port_name in port_names: 731 port = self._port_refs.get(port_name) 732 if port != None: 733 port.unproxy(self) 734 735 def print_ini(self, ini_file): 736 print >>ini_file, '[' + self.path() + ']' # .ini section header 737 738 instanceDict[self.path()] = self 739 740 if hasattr(self, 'type'): 741 print >>ini_file, 'type=%s' % self.type 742 743 child_names = self._children.keys() 744 child_names.sort() 745 if len(child_names): 746 print >>ini_file, 'children=%s' % \ 747 ' '.join(self._children[n].get_name() for n in child_names) 748 749 param_names = self._params.keys() 750 param_names.sort() 751 for param in param_names: 752 value = self._values.get(param) 753 if value != None: 754 print >>ini_file, '%s=%s' % (param, 755 self._values[param].ini_str()) 756 757 port_names = self._ports.keys() 758 port_names.sort() 759 for port_name in port_names: 760 port = self._port_refs.get(port_name, None) 761 if port != None: 762 print >>ini_file, '%s=%s' % (port_name, port.ini_str()) 763 764 print >>ini_file # blank line between objects 765 766 def getCCParams(self): 767 if self._ccParams: 768 return self._ccParams 769 770 cc_params_struct = getattr(m5.objects.params, '%sParams' % self.type) 771 cc_params = cc_params_struct() 772 cc_params.pyobj = self 773 cc_params.name = str(self) 774 775 param_names = self._params.keys() 776 param_names.sort() 777 for param in param_names: 778 value = self._values.get(param) 779 if value is None: 780 fatal("%s.%s without default or user set value", 781 self.path(), param) 782 783 value = value.getValue() 784 if isinstance(self._params[param], VectorParamDesc): 785 assert isinstance(value, list) 786 vec = getattr(cc_params, param) 787 assert not len(vec) 788 for v in value: 789 vec.append(v) 790 else: 791 setattr(cc_params, param, value) 792 793 port_names = self._ports.keys() 794 port_names.sort() 795 for port_name in port_names: 796 port = self._port_refs.get(port_name, None) 797 if port != None: 798 setattr(cc_params, port_name, port) 799 self._ccParams = cc_params 800 return self._ccParams 801 802 # Get C++ object corresponding to this object, calling C++ if 803 # necessary to construct it. Does *not* recursively create 804 # children. 805 def getCCObject(self): 806 if not self._ccObject: 807 # Make sure this object is in the configuration hierarchy 808 if not self._parent and not isRoot(self): 809 raise RuntimeError, "Attempt to instantiate orphan node" 810 # Cycles in the configuration hierarchy are not supported. This 811 # will catch the resulting recursion and stop. 812 self._ccObject = -1 813 params = self.getCCParams() 814 self._ccObject = params.create() 815 elif self._ccObject == -1: 816 raise RuntimeError, "%s: Cycle found in configuration hierarchy." \ 817 % self.path() 818 return self._ccObject 819 820 def descendants(self): 821 yield self 822 for child in self._children.itervalues(): 823 for obj in child.descendants(): 824 yield obj 825 826 # Call C++ to create C++ object corresponding to this object 827 def createCCObject(self): 828 self.getCCParams() 829 self.getCCObject() # force creation 830 831 def getValue(self): 832 return self.getCCObject() 833 834 # Create C++ port connections corresponding to the connections in 835 # _port_refs 836 def connectPorts(self): 837 for portRef in self._port_refs.itervalues(): 838 portRef.ccConnect() 839 840 def getMemoryMode(self): 841 if not isinstance(self, m5.objects.System): 842 return None 843 844 return self._ccObject.getMemoryMode() 845 846 def changeTiming(self, mode): 847 if isinstance(self, m5.objects.System): 848 # i don't know if there's a better way to do this - calling 849 # setMemoryMode directly from self._ccObject results in calling 850 # SimObject::setMemoryMode, not the System::setMemoryMode 851 self._ccObject.setMemoryMode(mode) 852 853 def takeOverFrom(self, old_cpu): 854 self._ccObject.takeOverFrom(old_cpu._ccObject) 855 856 # generate output file for 'dot' to display as a pretty graph. 857 # this code is currently broken. 858 def outputDot(self, dot): 859 label = "{%s|" % self.path 860 if isSimObject(self.realtype): 861 label += '%s|' % self.type 862 863 if self.children: 864 # instantiate children in same order they were added for 865 # backward compatibility (else we can end up with cpu1 866 # before cpu0). 867 for c in self.children: 868 dot.add_edge(pydot.Edge(self.path,c.path, style="bold")) 869 870 simobjs = [] 871 for param in self.params: 872 try: 873 if param.value is None: 874 raise AttributeError, 'Parameter with no value' 875 876 value = param.value 877 string = param.string(value) 878 except Exception, e: 879 msg = 'exception in %s:%s\n%s' % (self.name, param.name, e) 880 e.args = (msg, ) 881 raise 882 883 if isSimObject(param.ptype) and string != "Null": 884 simobjs.append(string) 885 else: 886 label += '%s = %s\\n' % (param.name, string) 887 888 for so in simobjs: 889 label += "|<%s> %s" % (so, so) 890 dot.add_edge(pydot.Edge("%s:%s" % (self.path, so), so, 891 tailport="w")) 892 label += '}' 893 dot.add_node(pydot.Node(self.path,shape="Mrecord",label=label)) 894 895 # recursively dump out children 896 for c in self.children: 897 c.outputDot(dot) 898 899# Function to provide to C++ so it can look up instances based on paths 900def resolveSimObject(name): 901 obj = instanceDict[name] 902 return obj.getCCObject() 903 904def isSimObject(value): 905 return isinstance(value, SimObject) 906 907def isSimObjectClass(value): 908 return issubclass(value, SimObject) 909 910def isSimObjectVector(value): 911 return isinstance(value, SimObjectVector) 912 913def isSimObjectSequence(value): 914 if not isinstance(value, (list, tuple)) or len(value) == 0: 915 return False 916 917 for val in value: 918 if not isNullPointer(val) and not isSimObject(val): 919 return False 920 921 return True 922 923def isSimObjectOrSequence(value): 924 return isSimObject(value) or isSimObjectSequence(value) 925 926def isRoot(obj): 927 from m5.objects import Root 928 return obj and obj is Root.getInstance() 929 930def isSimObjectOrVector(value): 931 return isSimObject(value) or isSimObjectVector(value) 932 933def tryAsSimObjectOrVector(value): 934 if isSimObjectOrVector(value): 935 return value 936 if isSimObjectSequence(value): 937 return SimObjectVector(value) 938 return None 939 940def coerceSimObjectOrVector(value): 941 value = tryAsSimObjectOrVector(value) 942 if value is None: 943 raise TypeError, "SimObject or SimObjectVector expected" 944 return value 945 946baseClasses = allClasses.copy() 947baseInstances = instanceDict.copy() 948 949def clear(): 950 global allClasses, instanceDict 951 952 allClasses = baseClasses.copy() 953 instanceDict = baseInstances.copy() 954 955# __all__ defines the list of symbols that get exported when 956# 'from config import *' is invoked. Try to keep this reasonably 957# short to avoid polluting other namespaces. 958__all__ = [ 'SimObject' ]
|