SConscript revision 6168
16657Snate@binkert.org# -*- mode:python -*-
26657Snate@binkert.org
36657Snate@binkert.org# Copyright (c) 2004-2005 The Regents of The University of Michigan
46657Snate@binkert.org# All rights reserved.
56657Snate@binkert.org#
66657Snate@binkert.org# Redistribution and use in source and binary forms, with or without
76657Snate@binkert.org# modification, are permitted provided that the following conditions are
86657Snate@binkert.org# met: redistributions of source code must retain the above copyright
96657Snate@binkert.org# notice, this list of conditions and the following disclaimer;
106657Snate@binkert.org# redistributions in binary form must reproduce the above copyright
116657Snate@binkert.org# notice, this list of conditions and the following disclaimer in the
126657Snate@binkert.org# documentation and/or other materials provided with the distribution;
136657Snate@binkert.org# neither the name of the copyright holders nor the names of its
146657Snate@binkert.org# contributors may be used to endorse or promote products derived from
156657Snate@binkert.org# this software without specific prior written permission.
166657Snate@binkert.org#
176657Snate@binkert.org# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
186657Snate@binkert.org# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
196657Snate@binkert.org# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
206657Snate@binkert.org# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
216657Snate@binkert.org# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
226657Snate@binkert.org# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
236657Snate@binkert.org# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
246657Snate@binkert.org# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
256657Snate@binkert.org# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
266657Snate@binkert.org# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
276657Snate@binkert.org# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
286657Snate@binkert.org#
296657Snate@binkert.org# Authors: Nathan Binkert
306657Snate@binkert.org
316657Snate@binkert.orgimport array
326657Snate@binkert.orgimport bisect
336999Snate@binkert.orgimport imp
348452Snate@binkert.orgimport marshal
356657Snate@binkert.orgimport os
366657Snate@binkert.orgimport re
376657Snate@binkert.orgimport sys
386657Snate@binkert.orgimport zlib
396657Snate@binkert.org
406657Snate@binkert.orgfrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
419219Spower.jg@gmail.com
428454Snate@binkert.orgimport SCons
438454Snate@binkert.org
448453Snate@binkert.org# This file defines how to build a particular configuration of M5
456999Snate@binkert.org# based on variable settings in the 'env' build environment.
469219Spower.jg@gmail.com
476999Snate@binkert.orgImport('*')
488454Snate@binkert.org
498454Snate@binkert.org# Children need to see the environment
508454Snate@binkert.orgExport('env')
518454Snate@binkert.org
528454Snate@binkert.orgbuild_env = dict([(opt, env[opt]) for opt in export_vars])
538454Snate@binkert.org
548454Snate@binkert.org########################################################################
558453Snate@binkert.org# Code for adding source files of various types
568453Snate@binkert.org#
578453Snate@binkert.orgclass SourceMeta(type):
588453Snate@binkert.org    def __init__(cls, name, bases, dict):
596999Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
606999Snate@binkert.org        cls.all = []
616999Snate@binkert.org        
626999Snate@binkert.org    def get(cls, **kwargs):
636657Snate@binkert.org        for src in cls.all:
648453Snate@binkert.org            for attr,value in kwargs.iteritems():
658454Snate@binkert.org                if getattr(src, attr) != value:
668454Snate@binkert.org                    break
676657Snate@binkert.org            else:
689219Spower.jg@gmail.com                yield src
699219Spower.jg@gmail.com
706657Snate@binkert.orgclass SourceFile(object):
718453Snate@binkert.org    __metaclass__ = SourceMeta
728453Snate@binkert.org    def __init__(self, source):
736657Snate@binkert.org        tnode = source
746657Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
756714Ssteve.reinhardt@amd.com            tnode = File(source)
766714Ssteve.reinhardt@amd.com
776657Snate@binkert.org        self.tnode = tnode
786657Snate@binkert.org        self.snode = tnode.srcnode()
796657Snate@binkert.org        self.filename = str(tnode)
808454Snate@binkert.org        self.dirname = dirname(self.filename)
816657Snate@binkert.org        self.basename = basename(self.filename)
826714Ssteve.reinhardt@amd.com        index = self.basename.rfind('.')
836657Snate@binkert.org        if index <= 0:
846657Snate@binkert.org            # dot files aren't extensions
856657Snate@binkert.org            self.extname = self.basename, None
866657Snate@binkert.org        else:
876657Snate@binkert.org            self.extname = self.basename[:index], self.basename[index+1:]
886657Snate@binkert.org
896657Snate@binkert.org        for base in type(self).__mro__:
906657Snate@binkert.org            if issubclass(base, SourceFile):
916657Snate@binkert.org                bisect.insort_right(base.all, self)       
926657Snate@binkert.org
936657Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
946657Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
956657Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
966657Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
976657Snate@binkert.org    def __eq__(self, other): return self.filename == other.filename
986657Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
996657Snate@binkert.org        
1008454Snate@binkert.orgclass Source(SourceFile):
1018454Snate@binkert.org    '''Add a c/c++ source file to the build'''
1026657Snate@binkert.org    def __init__(self, source, Werror=True, swig=False, bin_only=False,
1036657Snate@binkert.org                 skip_lib=False):
1046657Snate@binkert.org        super(Source, self).__init__(source)
1056657Snate@binkert.org
1066657Snate@binkert.org        self.Werror = Werror
1076657Snate@binkert.org        self.swig = swig
1086657Snate@binkert.org        self.bin_only = bin_only
1096657Snate@binkert.org        self.skip_lib = bin_only or skip_lib
1106657Snate@binkert.org
1118086SBrad.Beckmann@amd.comclass PySource(SourceFile):
1126657Snate@binkert.org    '''Add a python source file to the named package'''
1137567SBrad.Beckmann@amd.com    invalid_sym_char = re.compile('[^A-z0-9_]')
1146657Snate@binkert.org    modules = {}
1156657Snate@binkert.org    tnodes = {}
1166657Snate@binkert.org    symnames = {}
1176882SBrad.Beckmann@amd.com    
1186657Snate@binkert.org    def __init__(self, package, source):
1197839Snilay@cs.wisc.edu        super(PySource, self).__init__(source)
1207839Snilay@cs.wisc.edu
1216657Snate@binkert.org        modname,ext = self.extname
1226657Snate@binkert.org        assert ext == 'py'
1236657Snate@binkert.org
1246657Snate@binkert.org        if package:
1257839Snilay@cs.wisc.edu            path = package.split('.')
1266657Snate@binkert.org        else:
1276657Snate@binkert.org            path = []
1286657Snate@binkert.org
1296657Snate@binkert.org        modpath = path[:]
1306657Snate@binkert.org        if modname != '__init__':
1316657Snate@binkert.org            modpath += [ modname ]
1326657Snate@binkert.org        modpath = '.'.join(modpath)
1336657Snate@binkert.org
1349692Snilay@cs.wisc.edu        arcpath = path + [ self.basename ]
1356657Snate@binkert.org        debugname = self.snode.abspath
1366657Snate@binkert.org        if not exists(debugname):
1376657Snate@binkert.org            debugname = self.tnode.abspath
1386657Snate@binkert.org
1396657Snate@binkert.org        self.package = package
1406657Snate@binkert.org        self.modname = modname
1416657Snate@binkert.org        self.modpath = modpath
1426657Snate@binkert.org        self.arcname = joinpath(*arcpath)
1436657Snate@binkert.org        self.debugname = debugname
1446657Snate@binkert.org        self.compiled = File(self.filename + 'c')
1456657Snate@binkert.org        self.assembly = File(self.filename + '.s')
1466657Snate@binkert.org        self.symname = "PyEMB_" + PySource.invalid_sym_char.sub('_', modpath)
1476657Snate@binkert.org
1486657Snate@binkert.org        PySource.modules[modpath] = self
1496657Snate@binkert.org        PySource.tnodes[self.tnode] = self
1506657Snate@binkert.org        PySource.symnames[self.symname] = self
1516657Snate@binkert.org
1526657Snate@binkert.orgclass SimObject(PySource):
1536657Snate@binkert.org    '''Add a SimObject python file as a python source object and add
1546657Snate@binkert.org    it to a list of sim object modules'''
1556657Snate@binkert.org
1566657Snate@binkert.org    fixed = False
1576657Snate@binkert.org    modnames = []
1586657Snate@binkert.org
1599692Snilay@cs.wisc.edu    def __init__(self, source):
1609692Snilay@cs.wisc.edu        super(SimObject, self).__init__('m5.objects', source)
1616657Snate@binkert.org        if self.fixed:
1626657Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
1639692Snilay@cs.wisc.edu
1646657Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
1656657Snate@binkert.org
1666657Snate@binkert.orgclass SwigSource(SourceFile):
1676657Snate@binkert.org    '''Add a swig file to build'''
1686657Snate@binkert.org
1696657Snate@binkert.org    def __init__(self, package, source):
1706657Snate@binkert.org        super(SwigSource, self).__init__(source)
1716657Snate@binkert.org
1726657Snate@binkert.org        modname,ext = self.extname
1736657Snate@binkert.org        assert ext == 'i'
1746657Snate@binkert.org
1756657Snate@binkert.org        self.module = modname
1766657Snate@binkert.org        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
1776657Snate@binkert.org        py_file = joinpath(self.dirname, modname + '.py')
1786657Snate@binkert.org
1796657Snate@binkert.org        self.cc_source = Source(cc_file, swig=True)
1806657Snate@binkert.org        self.py_source = PySource(package, py_file)
1816657Snate@binkert.org
1826657Snate@binkert.orgunit_tests = []
1836657Snate@binkert.orgdef UnitTest(target, sources):
1846657Snate@binkert.org    if not isinstance(sources, (list, tuple)):
1856657Snate@binkert.org        sources = [ sources ]
1866657Snate@binkert.org
1876657Snate@binkert.org    sources = [ Source(src, skip_lib=True) for src in sources ]
1886657Snate@binkert.org    unit_tests.append((target, sources))
1896657Snate@binkert.org
1906657Snate@binkert.org# Children should have access
1916657Snate@binkert.orgExport('Source')
1926657Snate@binkert.orgExport('PySource')
1936657Snate@binkert.orgExport('SimObject')
1948452Snate@binkert.orgExport('SwigSource')
1956657Snate@binkert.orgExport('UnitTest')
1966657Snate@binkert.org
1976657Snate@binkert.org########################################################################
1986657Snate@binkert.org#
1996657Snate@binkert.org# Trace Flags
2006657Snate@binkert.org#
2016657Snate@binkert.orgtrace_flags = {}
2028452Snate@binkert.orgdef TraceFlag(name, desc=None):
2036657Snate@binkert.org    if name in trace_flags:
2046657Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
2056657Snate@binkert.org    trace_flags[name] = (name, (), desc)
2066657Snate@binkert.org
2076657Snate@binkert.orgdef CompoundFlag(name, flags, desc=None):
2086657Snate@binkert.org    if name in trace_flags:
2096657Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
2106657Snate@binkert.org
2116657Snate@binkert.org    compound = tuple(flags)
2126657Snate@binkert.org    for flag in compound:
2136657Snate@binkert.org        if flag not in trace_flags:
2146657Snate@binkert.org            raise AttributeError, "Trace flag %s not found" % flag
2156657Snate@binkert.org        if trace_flags[flag][1]:
2166657Snate@binkert.org            raise AttributeError, \
2176657Snate@binkert.org                "Compound flag can't point to another compound flag"
2186657Snate@binkert.org
2196657Snate@binkert.org    trace_flags[name] = (name, compound, desc)
2206657Snate@binkert.org
2216657Snate@binkert.orgExport('TraceFlag')
2226657Snate@binkert.orgExport('CompoundFlag')
2236657Snate@binkert.org
2246657Snate@binkert.org########################################################################
2256657Snate@binkert.org#
2266657Snate@binkert.org# Set some compiler variables
2276657Snate@binkert.org#
2286657Snate@binkert.org
2296657Snate@binkert.org# Include file paths are rooted in this directory.  SCons will
2308454Snate@binkert.org# automatically expand '.' to refer to both the source directory and
2318454Snate@binkert.org# the corresponding build directory to pick up generated include
2328454Snate@binkert.org# files.
2338454Snate@binkert.orgenv.Append(CPPPATH=Dir('.'))
2348454Snate@binkert.org
2358454Snate@binkert.orgfor extra_dir in extras_dir_list:
2368454Snate@binkert.org    env.Append(CPPPATH=Dir(extra_dir))
2376657Snate@binkert.org
2386657Snate@binkert.org# Add a flag defining what THE_ISA should be for all compilation
2396657Snate@binkert.orgenv.Append(CPPDEFINES=[('THE_ISA','%s_ISA' % env['TARGET_ISA'].upper())])
2406657Snate@binkert.org
2416657Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
2428454Snate@binkert.org# Scons bug id: 2006 M5 Bug id: 308 
2438454Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
2448454Snate@binkert.org    Dir(root[len(base_dir) + 1:])
2458454Snate@binkert.org
2468454Snate@binkert.org########################################################################
2478454Snate@binkert.org#
2488454Snate@binkert.org# Walk the tree and execute all SConscripts in subdirectories
2498454Snate@binkert.org#
2508454Snate@binkert.org
2518454Snate@binkert.orghere = Dir('.').srcnode().abspath
2528454Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
2538454Snate@binkert.org    if root == here:
2549219Spower.jg@gmail.com        # we don't want to recurse back into this SConscript
2559219Spower.jg@gmail.com        continue
2569219Spower.jg@gmail.com
2579219Spower.jg@gmail.com    if 'SConscript' in files:
2588454Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
2598454Snate@binkert.org        SConscript(joinpath(root, 'SConscript'), build_dir=build_dir)
2609773Snilay@cs.wisc.edu
2619773Snilay@cs.wisc.edufor extra_dir in extras_dir_list:
2629773Snilay@cs.wisc.edu    prefix_len = len(dirname(extra_dir)) + 1
2639773Snilay@cs.wisc.edu    for root, dirs, files in os.walk(extra_dir, topdown=True):
2649773Snilay@cs.wisc.edu        if 'SConscript' in files:
2659773Snilay@cs.wisc.edu            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
2666657Snate@binkert.org            SConscript(joinpath(root, 'SConscript'), build_dir=build_dir)
2676657Snate@binkert.org
2686657Snate@binkert.orgfor opt in export_vars:
2696657Snate@binkert.org    env.ConfigFile(opt)
2706657Snate@binkert.org
2716657Snate@binkert.org########################################################################
2726657Snate@binkert.org#
2736657Snate@binkert.org# Prevent any SimObjects from being added after this point, they
2746657Snate@binkert.org# should all have been added in the SConscripts above
2756657Snate@binkert.org#
2766657Snate@binkert.orgclass DictImporter(object):
2776657Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
2786657Snate@binkert.org    map to arbitrary filenames.'''
2796657Snate@binkert.org    def __init__(self, modules):
2806657Snate@binkert.org        self.modules = modules
28110165Snilay@cs.wisc.edu        self.installed = set()
28210165Snilay@cs.wisc.edu
2836657Snate@binkert.org    def __del__(self):
2846657Snate@binkert.org        self.unload()
28510165Snilay@cs.wisc.edu
28610165Snilay@cs.wisc.edu    def unload(self):
2879104Shestness@cs.utexas.edu        import sys
2889104Shestness@cs.utexas.edu        for module in self.installed:
28910165Snilay@cs.wisc.edu            del sys.modules[module]
29010165Snilay@cs.wisc.edu        self.installed = set()
2919104Shestness@cs.utexas.edu
2929104Shestness@cs.utexas.edu    def find_module(self, fullname, path):
29310165Snilay@cs.wisc.edu        if fullname == 'defines':
29410165Snilay@cs.wisc.edu            return self
2956657Snate@binkert.org
2966657Snate@binkert.org        if fullname == 'm5.objects':
2976657Snate@binkert.org            return self
2986657Snate@binkert.org
2996657Snate@binkert.org        if fullname.startswith('m5.internal'):
3006657Snate@binkert.org            return None
3016657Snate@binkert.org
3026657Snate@binkert.org        source = self.modules.get(fullname, None)
3036657Snate@binkert.org        if source is not None and exists(source.snode.abspath):
3046657Snate@binkert.org            return self
3056657Snate@binkert.org
3066657Snate@binkert.org        return None
3076657Snate@binkert.org
3086657Snate@binkert.org    def load_module(self, fullname):
3096657Snate@binkert.org        mod = imp.new_module(fullname)
3106657Snate@binkert.org        sys.modules[fullname] = mod
3116657Snate@binkert.org        self.installed.add(fullname)
3126657Snate@binkert.org
3136657Snate@binkert.org        mod.__loader__ = self
3146657Snate@binkert.org        if fullname == 'm5.objects':
3158086SBrad.Beckmann@amd.com            mod.__path__ = fullname.split('.')
3168086SBrad.Beckmann@amd.com            return mod
3178086SBrad.Beckmann@amd.com
3188086SBrad.Beckmann@amd.com        if fullname == 'defines':
3198086SBrad.Beckmann@amd.com            mod.__dict__['buildEnv'] = build_env
3208086SBrad.Beckmann@amd.com            return mod
32110307Snilay@cs.wisc.edu
32210307Snilay@cs.wisc.edu        source = self.modules[fullname]
32310307Snilay@cs.wisc.edu        if source.modname == '__init__':
32410307Snilay@cs.wisc.edu            mod.__path__ = source.modpath
32510307Snilay@cs.wisc.edu        mod.__file__ = source.snode.abspath
32610307Snilay@cs.wisc.edu
32710307Snilay@cs.wisc.edu        exec file(source.snode.abspath, 'r') in mod.__dict__
32810307Snilay@cs.wisc.edu
32910307Snilay@cs.wisc.edu        return mod
33010307Snilay@cs.wisc.edu
33110307Snilay@cs.wisc.edu# install the python importer so we can grab stuff from the source
33210307Snilay@cs.wisc.edu# tree itself.  We can't have SimObjects added after this point or
33310307Snilay@cs.wisc.edu# else we won't know about them for the rest of the stuff.
33410307Snilay@cs.wisc.eduSimObject.fixed = True
33510307Snilay@cs.wisc.eduimporter = DictImporter(PySource.modules)
33610307Snilay@cs.wisc.edusys.meta_path[0:0] = [ importer ]
33710307Snilay@cs.wisc.edu
33810307Snilay@cs.wisc.eduimport m5
33910307Snilay@cs.wisc.edu
34010307Snilay@cs.wisc.edu# import all sim objects so we can populate the all_objects list
34110307Snilay@cs.wisc.edu# make sure that we're working with a list, then let's sort it
34210307Snilay@cs.wisc.edufor modname in SimObject.modnames:
34310307Snilay@cs.wisc.edu    exec('from m5.objects import %s' % modname)
34410307Snilay@cs.wisc.edu
34510307Snilay@cs.wisc.edu# we need to unload all of the currently imported modules so that they
34610307Snilay@cs.wisc.edu# will be re-imported the next time the sconscript is run
34710307Snilay@cs.wisc.eduimporter.unload()
34810307Snilay@cs.wisc.edusys.meta_path.remove(importer)
34910307Snilay@cs.wisc.edu
35010307Snilay@cs.wisc.edusim_objects = m5.SimObject.allClasses
35110307Snilay@cs.wisc.eduall_enums = m5.params.allEnums
35210307Snilay@cs.wisc.edu
35310307Snilay@cs.wisc.eduall_params = {}
35410307Snilay@cs.wisc.edufor name,obj in sorted(sim_objects.iteritems()):
35510307Snilay@cs.wisc.edu    for param in obj._params.local.values():
3566657Snate@binkert.org        if not hasattr(param, 'swig_decl'):
3579298Snilay@cs.wisc.edu            continue
3586657Snate@binkert.org        pname = param.ptype_str
3599298Snilay@cs.wisc.edu        if pname not in all_params:
3609298Snilay@cs.wisc.edu            all_params[pname] = param
3619298Snilay@cs.wisc.edu
3629298Snilay@cs.wisc.edu########################################################################
3639298Snilay@cs.wisc.edu#
3646657Snate@binkert.org# calculate extra dependencies
3656657Snate@binkert.org#
3666657Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
36710307Snilay@cs.wisc.edudepends = [ PySource.modules[dep].tnode for dep in module_depends ]
36810307Snilay@cs.wisc.edu
36910307Snilay@cs.wisc.edu########################################################################
37010307Snilay@cs.wisc.edu#
37110307Snilay@cs.wisc.edu# Commands for the basic automatically generated python files
3726657Snate@binkert.org#
3739298Snilay@cs.wisc.edu
3749298Snilay@cs.wisc.edu# Generate Python file containing a dict specifying the current
3759298Snilay@cs.wisc.edu# build_env flags.
3769298Snilay@cs.wisc.edudef makeDefinesPyFile(target, source, env):
3779298Snilay@cs.wisc.edu    f = file(str(target[0]), 'w')
3789298Snilay@cs.wisc.edu    build_env, hg_info = [ x.get_contents() for x in source ]
3796657Snate@binkert.org    print >>f, "buildEnv = %s" % build_env
3806657Snate@binkert.org    print >>f, "hgRev = '%s'" % hg_info
3816657Snate@binkert.org    f.close()
3826657Snate@binkert.org
3836657Snate@binkert.orgdefines_info = [ Value(build_env), Value(env['HG_INFO']) ]
3846657Snate@binkert.org# Generate a file with all of the compile options in it
3856657Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info, makeDefinesPyFile)
3866657Snate@binkert.orgPySource('m5', 'python/m5/defines.py')
3876657Snate@binkert.org
3886657Snate@binkert.org# Generate python file containing info about the M5 source code
3896657Snate@binkert.orgdef makeInfoPyFile(target, source, env):
3906657Snate@binkert.org    f = file(str(target[0]), 'w')
3916657Snate@binkert.org    for src in source:
3926657Snate@binkert.org        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
3936657Snate@binkert.org        print >>f, "%s = %s" % (src, repr(data))
3948086SBrad.Beckmann@amd.com    f.close()
3958086SBrad.Beckmann@amd.com
3968086SBrad.Beckmann@amd.com# Generate a file that wraps the basic top level files
3978086SBrad.Beckmann@amd.comenv.Command('python/m5/info.py',
3988086SBrad.Beckmann@amd.com            [ '#/AUTHORS', '#/LICENSE', '#/README', '#/RELEASE_NOTES' ],
3998086SBrad.Beckmann@amd.com            makeInfoPyFile)
4008086SBrad.Beckmann@amd.comPySource('m5', 'python/m5/info.py')
4018086SBrad.Beckmann@amd.com
4028086SBrad.Beckmann@amd.com# Generate the __init__.py file for m5.objects
4038086SBrad.Beckmann@amd.comdef makeObjectsInitFile(target, source, env):
4048086SBrad.Beckmann@amd.com    f = file(str(target[0]), 'w')
4058086SBrad.Beckmann@amd.com    print >>f, 'from params import *'
4068086SBrad.Beckmann@amd.com    print >>f, 'from m5.SimObject import *'
4076657Snate@binkert.org    for module in source:
4086657Snate@binkert.org        print >>f, 'from %s import *' % module.get_contents()
4096657Snate@binkert.org    f.close()
4106657Snate@binkert.org
4116657Snate@binkert.org# Generate an __init__.py file for the objects package
4126657Snate@binkert.orgenv.Command('python/m5/objects/__init__.py',
4136657Snate@binkert.org            map(Value, SimObject.modnames),
4146657Snate@binkert.org            makeObjectsInitFile)
4156657Snate@binkert.orgPySource('m5.objects', 'python/m5/objects/__init__.py')
4166657Snate@binkert.org
4176657Snate@binkert.org########################################################################
4186657Snate@binkert.org#
4196657Snate@binkert.org# Create all of the SimObject param headers and enum headers
4206657Snate@binkert.org#
4216657Snate@binkert.org
4226657Snate@binkert.orgdef createSimObjectParam(target, source, env):
4236657Snate@binkert.org    assert len(target) == 1 and len(source) == 1
4246882SBrad.Beckmann@amd.com
4256882SBrad.Beckmann@amd.com    hh_file = file(target[0].abspath, 'w')
4266882SBrad.Beckmann@amd.com    name = str(source[0].get_contents())
4276882SBrad.Beckmann@amd.com    obj = sim_objects[name]
4286907SBrad.Beckmann@amd.com
4296907SBrad.Beckmann@amd.com    print >>hh_file, obj.cxx_decl()
4306907SBrad.Beckmann@amd.com    hh_file.close()
4316907SBrad.Beckmann@amd.com
4326907SBrad.Beckmann@amd.comdef createSwigParam(target, source, env):
4336877Ssteve.reinhardt@amd.com    assert len(target) == 1 and len(source) == 1
4346877Ssteve.reinhardt@amd.com
4356877Ssteve.reinhardt@amd.com    i_file = file(target[0].abspath, 'w')
4366907SBrad.Beckmann@amd.com    name = str(source[0].get_contents())
4376907SBrad.Beckmann@amd.com    param = all_params[name]
4386907SBrad.Beckmann@amd.com
4396907SBrad.Beckmann@amd.com    for line in param.swig_decl():
4406907SBrad.Beckmann@amd.com        print >>i_file, line
4416907SBrad.Beckmann@amd.com    i_file.close()
4426907SBrad.Beckmann@amd.com
4436907SBrad.Beckmann@amd.comdef createEnumStrings(target, source, env):
44410307Snilay@cs.wisc.edu    assert len(target) == 1 and len(source) == 1
44510307Snilay@cs.wisc.edu
44610307Snilay@cs.wisc.edu    cc_file = file(target[0].abspath, 'w')
44710307Snilay@cs.wisc.edu    name = str(source[0].get_contents())
44810307Snilay@cs.wisc.edu    obj = all_enums[name]
44910307Snilay@cs.wisc.edu
45010307Snilay@cs.wisc.edu    print >>cc_file, obj.cxx_def()
45110307Snilay@cs.wisc.edu    cc_file.close()
45210307Snilay@cs.wisc.edu
45310307Snilay@cs.wisc.edudef createEnumParam(target, source, env):
45410307Snilay@cs.wisc.edu    assert len(target) == 1 and len(source) == 1
45510307Snilay@cs.wisc.edu
45610307Snilay@cs.wisc.edu    hh_file = file(target[0].abspath, 'w')
45710307Snilay@cs.wisc.edu    name = str(source[0].get_contents())
45810307Snilay@cs.wisc.edu    obj = all_enums[name]
45910307Snilay@cs.wisc.edu
46010307Snilay@cs.wisc.edu    print >>hh_file, obj.cxx_decl()
46110307Snilay@cs.wisc.edu    hh_file.close()
46210307Snilay@cs.wisc.edu
46310307Snilay@cs.wisc.edu# Generate all of the SimObject param struct header files
46410307Snilay@cs.wisc.eduparams_hh_files = []
46510307Snilay@cs.wisc.edufor name,simobj in sorted(sim_objects.iteritems()):
46610307Snilay@cs.wisc.edu    py_source = PySource.modules[simobj.__module__]
46710307Snilay@cs.wisc.edu    extra_deps = [ py_source.tnode ]
46810307Snilay@cs.wisc.edu
46910307Snilay@cs.wisc.edu    hh_file = File('params/%s.hh' % name)
47010307Snilay@cs.wisc.edu    params_hh_files.append(hh_file)
47110307Snilay@cs.wisc.edu    env.Command(hh_file, Value(name), createSimObjectParam)
47210307Snilay@cs.wisc.edu    env.Depends(hh_file, depends + extra_deps)
4736657Snate@binkert.org
4746657Snate@binkert.org# Generate any parameter header files needed
4756657Snate@binkert.orgparams_i_files = []
4766657Snate@binkert.orgfor name,param in all_params.iteritems():
4776657Snate@binkert.org    if isinstance(param, m5.params.VectorParamDesc):
4786657Snate@binkert.org        ext = 'vptype'
4796657Snate@binkert.org    else:
4806657Snate@binkert.org        ext = 'ptype'
4816657Snate@binkert.org
4826657Snate@binkert.org    i_file = File('params/%s_%s.i' % (name, ext))
4836657Snate@binkert.org    params_i_files.append(i_file)
4846657Snate@binkert.org    env.Command(i_file, Value(name), createSwigParam)
4856657Snate@binkert.org    env.Depends(i_file, depends)
4866657Snate@binkert.org
4876657Snate@binkert.org# Generate all enum header files
4886657Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
4896657Snate@binkert.org    py_source = PySource.modules[enum.__module__]
4906657Snate@binkert.org    extra_deps = [ py_source.tnode ]
4916657Snate@binkert.org
4926657Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
4936657Snate@binkert.org    env.Command(cc_file, Value(name), createEnumStrings)
4946657Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
4956657Snate@binkert.org    Source(cc_file)
4966657Snate@binkert.org
4976657Snate@binkert.org    hh_file = File('enums/%s.hh' % name)
4986657Snate@binkert.org    env.Command(hh_file, Value(name), createEnumParam)
4996657Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
5006657Snate@binkert.org
5016657Snate@binkert.org# Build the big monolithic swigged params module (wraps all SimObject
5026657Snate@binkert.org# param structs and enum structs)
5036657Snate@binkert.orgdef buildParams(target, source, env):
5046657Snate@binkert.org    names = [ s.get_contents() for s in source ]
5056657Snate@binkert.org    objs = [ sim_objects[name] for name in names ]
5066657Snate@binkert.org    out = file(target[0].abspath, 'w')
5076657Snate@binkert.org
5086657Snate@binkert.org    ordered_objs = []
5096657Snate@binkert.org    obj_seen = set()
5106657Snate@binkert.org    def order_obj(obj):
5116657Snate@binkert.org        name = str(obj)
5126657Snate@binkert.org        if name in obj_seen:
5136657Snate@binkert.org            return
5146657Snate@binkert.org
5156657Snate@binkert.org        obj_seen.add(name)
5166657Snate@binkert.org        if str(obj) != 'SimObject':
5176657Snate@binkert.org            order_obj(obj.__bases__[0])
5186657Snate@binkert.org
5196657Snate@binkert.org        ordered_objs.append(obj)
5207567SBrad.Beckmann@amd.com
5217567SBrad.Beckmann@amd.com    for obj in objs:
5226657Snate@binkert.org        order_obj(obj)
5236657Snate@binkert.org
5246657Snate@binkert.org    enums = set()
5256657Snate@binkert.org    predecls = []
5266657Snate@binkert.org    pd_seen = set()
5276657Snate@binkert.org
5286657Snate@binkert.org    def add_pds(*pds):
5296657Snate@binkert.org        for pd in pds:
5306657Snate@binkert.org            if pd not in pd_seen:
5316657Snate@binkert.org                predecls.append(pd)
5326657Snate@binkert.org                pd_seen.add(pd)
5336657Snate@binkert.org
5346657Snate@binkert.org    for obj in ordered_objs:
5356657Snate@binkert.org        params = obj._params.local.values()
5366657Snate@binkert.org        for param in params:
5376657Snate@binkert.org            ptype = param.ptype
5386657Snate@binkert.org            if issubclass(ptype, m5.params.Enum):
5396657Snate@binkert.org                if ptype not in enums:
5406657Snate@binkert.org                    enums.add(ptype)
5416657Snate@binkert.org            pds = param.swig_predecls()
5426657Snate@binkert.org            if isinstance(pds, (list, tuple)):
5436657Snate@binkert.org                add_pds(*pds)
5446657Snate@binkert.org            else:
5456657Snate@binkert.org                add_pds(pds)
5466657Snate@binkert.org
5476657Snate@binkert.org    print >>out, '%module params'
5486657Snate@binkert.org
5496657Snate@binkert.org    print >>out, '%{'
5506657Snate@binkert.org    for obj in ordered_objs:
5516657Snate@binkert.org        print >>out, '#include "params/%s.hh"' % obj
5526657Snate@binkert.org    print >>out, '%}'
5536657Snate@binkert.org
5546657Snate@binkert.org    for pd in predecls:
5556657Snate@binkert.org        print >>out, pd
5566657Snate@binkert.org
5576657Snate@binkert.org    enums = list(enums)
5586657Snate@binkert.org    enums.sort()
5596657Snate@binkert.org    for enum in enums:
5606657Snate@binkert.org        print >>out, '%%include "enums/%s.hh"' % enum.__name__
5616657Snate@binkert.org    print >>out
5626657Snate@binkert.org
5636657Snate@binkert.org    for obj in ordered_objs:
5646657Snate@binkert.org        if obj.swig_objdecls:
5656657Snate@binkert.org            for decl in obj.swig_objdecls:
56610155Snilay@cs.wisc.edu                print >>out, decl
56710155Snilay@cs.wisc.edu            continue
56810155Snilay@cs.wisc.edu
56910155Snilay@cs.wisc.edu        class_path = obj.cxx_class.split('::')
57010155Snilay@cs.wisc.edu        classname = class_path[-1]
57110155Snilay@cs.wisc.edu        namespaces = class_path[:-1]
5726657Snate@binkert.org        namespaces.reverse()
5737567SBrad.Beckmann@amd.com
5747567SBrad.Beckmann@amd.com        code = ''
5757567SBrad.Beckmann@amd.com
5767567SBrad.Beckmann@amd.com        if namespaces:
5776657Snate@binkert.org            code += '// avoid name conflicts\n'
5786863Sdrh5@cs.wisc.edu            sep_string = '_COLONS_'
5796863Sdrh5@cs.wisc.edu            flat_name = sep_string.join(class_path)
5806657Snate@binkert.org            code += '%%rename(%s) %s;\n' % (flat_name, classname)
5816657Snate@binkert.org
5826657Snate@binkert.org        code += '// stop swig from creating/wrapping default ctor/dtor\n'
5836657Snate@binkert.org        code += '%%nodefault %s;\n' % classname
5846657Snate@binkert.org        code += 'class %s ' % classname
5856657Snate@binkert.org        if obj._base:
5866657Snate@binkert.org            code += ': public %s' % obj._base.cxx_class
5876657Snate@binkert.org        code += ' {};\n'
5886657Snate@binkert.org
5896657Snate@binkert.org        for ns in namespaces:
5906657Snate@binkert.org            new_code = 'namespace %s {\n' % ns
5916657Snate@binkert.org            new_code += code
5926657Snate@binkert.org            new_code += '}\n'
5936657Snate@binkert.org            code = new_code
5946657Snate@binkert.org
5956657Snate@binkert.org        print >>out, code
5966657Snate@binkert.org
5976657Snate@binkert.org    print >>out, '%%include "src/sim/sim_object_params.hh"' % obj
5986657Snate@binkert.org    for obj in ordered_objs:
5996657Snate@binkert.org        print >>out, '%%include "params/%s.hh"' % obj
6006657Snate@binkert.org
6016657Snate@binkert.orgparams_file = File('params/params.i')
6026657Snate@binkert.orgnames = sorted(sim_objects.keys())
6036657Snate@binkert.orgenv.Command(params_file, map(Value, names), buildParams)
6046657Snate@binkert.orgenv.Depends(params_file, params_hh_files + params_i_files + depends)
6056657Snate@binkert.orgSwigSource('m5.objects', params_file)
6066657Snate@binkert.org
6076657Snate@binkert.org# Build all swig modules
6086657Snate@binkert.orgfor swig in SwigSource.all:
6096657Snate@binkert.org    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
61010155Snilay@cs.wisc.edu                '$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
61110155Snilay@cs.wisc.edu                '-o ${TARGETS[0]} $SOURCES')
61210155Snilay@cs.wisc.edu    env.Depends(swig.py_source.tnode, swig.tnode)
61310155Snilay@cs.wisc.edu    env.Depends(swig.cc_source.tnode, swig.tnode)
61410155Snilay@cs.wisc.edu
61510155Snilay@cs.wisc.edu# Generate the main swig init file
61610155Snilay@cs.wisc.edudef makeSwigInit(target, source, env):
61710155Snilay@cs.wisc.edu    f = file(str(target[0]), 'w')
6186657Snate@binkert.org    print >>f, 'extern "C" {'
6196657Snate@binkert.org    for module in source:
6206657Snate@binkert.org        print >>f, '    void init_%s();' % module.get_contents()
6216657Snate@binkert.org    print >>f, '}'
6227839Snilay@cs.wisc.edu    print >>f, 'void initSwig() {'
6237839Snilay@cs.wisc.edu    for module in source:
6247839Snilay@cs.wisc.edu        print >>f, '    init_%s();' % module.get_contents()
6257839Snilay@cs.wisc.edu    print >>f, '}'
6266657Snate@binkert.org    f.close()
6276657Snate@binkert.org
6286657Snate@binkert.orgenv.Command('python/swig/init.cc',
6296657Snate@binkert.org            map(Value, sorted(s.module for s in SwigSource.all)),
6306657Snate@binkert.org            makeSwigInit)
6316657Snate@binkert.orgSource('python/swig/init.cc')
6326657Snate@binkert.org
6336657Snate@binkert.org# Generate traceflags.py
6346657Snate@binkert.orgdef traceFlagsPy(target, source, env):
6356657Snate@binkert.org    assert(len(target) == 1)
6366657Snate@binkert.org
6376657Snate@binkert.org    f = file(str(target[0]), 'w')
6386657Snate@binkert.org
6396657Snate@binkert.org    allFlags = []
6406657Snate@binkert.org    for s in source:
6416657Snate@binkert.org        val = eval(s.get_contents())
6427839Snilay@cs.wisc.edu        allFlags.append(val)
6437839Snilay@cs.wisc.edu
6447839Snilay@cs.wisc.edu    allFlags.sort()
6457839Snilay@cs.wisc.edu
6466657Snate@binkert.org    print >>f, 'basic = ['
6476657Snate@binkert.org    for flag, compound, desc in allFlags:
6486657Snate@binkert.org        if not compound:
6496657Snate@binkert.org            print >>f, "    '%s'," % flag
6506657Snate@binkert.org    print >>f, "    ]"
6516657Snate@binkert.org    print >>f
6526657Snate@binkert.org
6536657Snate@binkert.org    print >>f, 'compound = ['
6546657Snate@binkert.org    print >>f, "    'All',"
6556657Snate@binkert.org    for flag, compound, desc in allFlags:
6566657Snate@binkert.org        if compound:
6576657Snate@binkert.org            print >>f, "    '%s'," % flag
6586657Snate@binkert.org    print >>f, "    ]"
6596657Snate@binkert.org    print >>f
6606657Snate@binkert.org
6616657Snate@binkert.org    print >>f, "all = frozenset(basic + compound)"
6626657Snate@binkert.org    print >>f
6636657Snate@binkert.org
6646657Snate@binkert.org    print >>f, 'compoundMap = {'
6656657Snate@binkert.org    all = tuple([flag for flag,compound,desc in allFlags if not compound])
6666657Snate@binkert.org    print >>f, "    'All' : %s," % (all, )
6676657Snate@binkert.org    for flag, compound, desc in allFlags:
6686657Snate@binkert.org        if compound:
6696657Snate@binkert.org            print >>f, "    '%s' : %s," % (flag, compound)
6706657Snate@binkert.org    print >>f, "    }"
6716657Snate@binkert.org    print >>f
6726657Snate@binkert.org
6736657Snate@binkert.org    print >>f, 'descriptions = {'
6746657Snate@binkert.org    print >>f, "    'All' : 'All flags',"
6756657Snate@binkert.org    for flag, compound, desc in allFlags:
6766657Snate@binkert.org        print >>f, "    '%s' : '%s'," % (flag, desc)
6776657Snate@binkert.org    print >>f, "    }"
6786657Snate@binkert.org
6796657Snate@binkert.org    f.close()
6806657Snate@binkert.org
6816657Snate@binkert.orgdef traceFlagsCC(target, source, env):
6826657Snate@binkert.org    assert(len(target) == 1)
6836657Snate@binkert.org
6846657Snate@binkert.org    f = file(str(target[0]), 'w')
6856657Snate@binkert.org
6869692Snilay@cs.wisc.edu    allFlags = []
6879692Snilay@cs.wisc.edu    for s in source:
6886657Snate@binkert.org        val = eval(s.get_contents())
6899692Snilay@cs.wisc.edu        allFlags.append(val)
6906657Snate@binkert.org
6916657Snate@binkert.org    # file header
6926657Snate@binkert.org    print >>f, '''
6936657Snate@binkert.org/*
6946657Snate@binkert.org * DO NOT EDIT THIS FILE! Automatically generated
6957839Snilay@cs.wisc.edu */
6967839Snilay@cs.wisc.edu
6977839Snilay@cs.wisc.edu#include "base/traceflags.hh"
6987839Snilay@cs.wisc.edu
6997839Snilay@cs.wisc.eduusing namespace Trace;
7007839Snilay@cs.wisc.edu
7017839Snilay@cs.wisc.educonst char *Trace::flagStrings[] =
7027839Snilay@cs.wisc.edu{'''
7036657Snate@binkert.org
7046657Snate@binkert.org    # The string array is used by SimpleEnumParam to map the strings
7057055Snate@binkert.org    # provided by the user to enum values.
7066657Snate@binkert.org    for flag, compound, desc in allFlags:
7076657Snate@binkert.org        if not compound:
7086657Snate@binkert.org            print >>f, '    "%s",' % flag
7096657Snate@binkert.org
7106657Snate@binkert.org    print >>f, '    "All",'
7116657Snate@binkert.org    for flag, compound, desc in allFlags:
7126657Snate@binkert.org        if compound:
7136657Snate@binkert.org            print >>f, '    "%s",' % flag
7146657Snate@binkert.org
7156657Snate@binkert.org    print >>f, '};'
7166657Snate@binkert.org    print >>f
7176657Snate@binkert.org    print >>f, 'const int Trace::numFlagStrings = %d;' % (len(allFlags) + 1)
7186657Snate@binkert.org    print >>f
7196657Snate@binkert.org
7206657Snate@binkert.org    #
7216657Snate@binkert.org    # Now define the individual compound flag arrays.  There is an array
7226657Snate@binkert.org    # for each compound flag listing the component base flags.
7236657Snate@binkert.org    #
7246657Snate@binkert.org    all = tuple([flag for flag,compound,desc in allFlags if not compound])
7256657Snate@binkert.org    print >>f, 'static const Flags AllMap[] = {'
726    for flag, compound, desc in allFlags:
727        if not compound:
728            print >>f, "    %s," % flag
729    print >>f, '};'
730    print >>f
731
732    for flag, compound, desc in allFlags:
733        if not compound:
734            continue
735        print >>f, 'static const Flags %sMap[] = {' % flag
736        for flag in compound:
737            print >>f, "    %s," % flag
738        print >>f, "    (Flags)-1"
739        print >>f, '};'
740        print >>f
741
742    #
743    # Finally the compoundFlags[] array maps the compound flags
744    # to their individual arrays/
745    #
746    print >>f, 'const Flags *Trace::compoundFlags[] ='
747    print >>f, '{'
748    print >>f, '    AllMap,'
749    for flag, compound, desc in allFlags:
750        if compound:
751            print >>f, '    %sMap,' % flag
752    # file trailer
753    print >>f, '};'
754
755    f.close()
756
757def traceFlagsHH(target, source, env):
758    assert(len(target) == 1)
759
760    f = file(str(target[0]), 'w')
761
762    allFlags = []
763    for s in source:
764        val = eval(s.get_contents())
765        allFlags.append(val)
766
767    # file header boilerplate
768    print >>f, '''
769/*
770 * DO NOT EDIT THIS FILE!
771 *
772 * Automatically generated from traceflags.py
773 */
774
775#ifndef __BASE_TRACE_FLAGS_HH__
776#define __BASE_TRACE_FLAGS_HH__
777
778namespace Trace {
779
780enum Flags {'''
781
782    # Generate the enum.  Base flags come first, then compound flags.
783    idx = 0
784    for flag, compound, desc in allFlags:
785        if not compound:
786            print >>f, '    %s = %d,' % (flag, idx)
787            idx += 1
788
789    numBaseFlags = idx
790    print >>f, '    NumFlags = %d,' % idx
791
792    # put a comment in here to separate base from compound flags
793    print >>f, '''
794// The remaining enum values are *not* valid indices for Trace::flags.
795// They are "compound" flags, which correspond to sets of base
796// flags, and are used by changeFlag.'''
797
798    print >>f, '    All = %d,' % idx
799    idx += 1
800    for flag, compound, desc in allFlags:
801        if compound:
802            print >>f, '    %s = %d,' % (flag, idx)
803            idx += 1
804
805    numCompoundFlags = idx - numBaseFlags
806    print >>f, '    NumCompoundFlags = %d' % numCompoundFlags
807
808    # trailer boilerplate
809    print >>f, '''\
810}; // enum Flags
811
812// Array of strings for SimpleEnumParam
813extern const char *flagStrings[];
814extern const int numFlagStrings;
815
816// Array of arraay pointers: for each compound flag, gives the list of
817// base flags to set.  Inidividual flag arrays are terminated by -1.
818extern const Flags *compoundFlags[];
819
820/* namespace Trace */ }
821
822#endif // __BASE_TRACE_FLAGS_HH__
823'''
824
825    f.close()
826
827flags = map(Value, trace_flags.values())
828env.Command('base/traceflags.py', flags, traceFlagsPy)
829PySource('m5', 'base/traceflags.py')
830
831env.Command('base/traceflags.hh', flags, traceFlagsHH)
832env.Command('base/traceflags.cc', flags, traceFlagsCC)
833Source('base/traceflags.cc')
834
835# embed python files.  All .py files that have been indicated by a
836# PySource() call in a SConscript need to be embedded into the M5
837# library.  To do that, we compile the file to byte code, marshal the
838# byte code, compress it, and then generate an assembly file that
839# inserts the result into the data section with symbols indicating the
840# beginning, and end (and with the size at the end)
841def objectifyPyFile(target, source, env):
842    '''Action function to compile a .py into a code object, marshal
843    it, compress it, and stick it into an asm file so the code appears
844    as just bytes with a label in the data section'''
845
846    src = file(str(source[0]), 'r').read()
847    dst = file(str(target[0]), 'w')
848
849    pysource = PySource.tnodes[source[0]]
850    compiled = compile(src, pysource.debugname, 'exec')
851    marshalled = marshal.dumps(compiled)
852    compressed = zlib.compress(marshalled)
853    data = compressed
854
855    # Some C/C++ compilers prepend an underscore to global symbol
856    # names, so if they're going to do that, we need to prepend that
857    # leading underscore to globals in the assembly file.
858    if env['LEADING_UNDERSCORE']:
859        sym = '_' + pysource.symname
860    else:
861        sym = pysource.symname
862
863    step = 16
864    print >>dst, ".data"
865    print >>dst, ".globl %s_beg" % sym
866    print >>dst, ".globl %s_end" % sym
867    print >>dst, "%s_beg:" % sym
868    for i in xrange(0, len(data), step):
869        x = array.array('B', data[i:i+step])
870        print >>dst, ".byte", ','.join([str(d) for d in x])
871    print >>dst, "%s_end:" % sym
872    print >>dst, ".long %d" % len(marshalled)
873
874for source in PySource.all:
875    env.Command(source.assembly, source.tnode, objectifyPyFile)
876    Source(source.assembly)
877
878# Generate init_python.cc which creates a bunch of EmbeddedPyModule
879# structs that describe the embedded python code.  One such struct
880# contains information about the importer that python uses to get at
881# the embedded files, and then there's a list of all of the rest that
882# the importer uses to load the rest on demand.
883def pythonInit(target, source, env):
884    dst = file(str(target[0]), 'w')
885
886    def dump_mod(sym, endchar=','):
887        pysource = PySource.symnames[sym]
888        print >>dst, '    { "%s",' % pysource.arcname
889        print >>dst, '      "%s",' % pysource.modpath
890        print >>dst, '       %s_beg, %s_end,' % (sym, sym)
891        print >>dst, '       %s_end - %s_beg,' % (sym, sym)
892        print >>dst, '       *(int *)%s_end }%s'  % (sym, endchar)
893    
894    print >>dst, '#include "sim/init.hh"'
895
896    for sym in source:
897        sym = sym.get_contents()
898        print >>dst, "extern const char %s_beg[], %s_end[];" % (sym, sym)
899
900    print >>dst, "const EmbeddedPyModule embeddedPyImporter = "
901    dump_mod("PyEMB_importer", endchar=';');
902    print >>dst
903
904    print >>dst, "const EmbeddedPyModule embeddedPyModules[] = {"
905    for i,sym in enumerate(source):
906        sym = sym.get_contents()
907        if sym == "PyEMB_importer":
908            # Skip the importer since we've already exported it
909            continue
910        dump_mod(sym)
911    print >>dst, "    { 0, 0, 0, 0, 0, 0 }"
912    print >>dst, "};"
913
914
915env.Command('sim/init_python.cc',
916            map(Value, (s.symname for s in PySource.all)),
917            pythonInit)
918Source('sim/init_python.cc')
919
920########################################################################
921#
922# Define binaries.  Each different build type (debug, opt, etc.) gets
923# a slightly different build environment.
924#
925
926# List of constructed environments to pass back to SConstruct
927envList = []
928
929date_source = Source('base/date.cc', skip_lib=True)
930
931# Function to create a new build environment as clone of current
932# environment 'env' with modified object suffix and optional stripped
933# binary.  Additional keyword arguments are appended to corresponding
934# build environment vars.
935def makeEnv(label, objsfx, strip = False, **kwargs):
936    # SCons doesn't know to append a library suffix when there is a '.' in the
937    # name.  Use '_' instead.
938    libname = 'm5_' + label
939    exename = 'm5.' + label
940
941    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
942    new_env.Label = label
943    new_env.Append(**kwargs)
944
945    swig_env = new_env.Clone()
946    swig_env.Append(CCFLAGS='-Werror')
947    if env['GCC']:
948        swig_env.Append(CCFLAGS='-Wno-uninitialized')
949        swig_env.Append(CCFLAGS='-Wno-sign-compare')
950        swig_env.Append(CCFLAGS='-Wno-parentheses')
951
952    werror_env = new_env.Clone()
953    werror_env.Append(CCFLAGS='-Werror')
954
955    def make_obj(source, static, extra_deps = None):
956        '''This function adds the specified source to the correct
957        build environment, and returns the corresponding SCons Object
958        nodes'''
959
960        if source.swig:
961            env = swig_env
962        elif source.Werror:
963            env = werror_env
964        else:
965            env = new_env
966
967        if static:
968            obj = env.StaticObject(source.tnode)
969        else:
970            obj = env.SharedObject(source.tnode)
971
972        if extra_deps:
973            env.Depends(obj, extra_deps)
974
975        return obj
976
977    static_objs = [ make_obj(s, True) for s in Source.get(skip_lib=False)]
978    shared_objs = [ make_obj(s, False) for s in Source.get(skip_lib=False)]
979
980    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
981    static_objs.append(static_date)
982    
983    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
984    shared_objs.append(static_date)
985
986    # First make a library of everything but main() so other programs can
987    # link against m5.
988    static_lib = new_env.StaticLibrary(libname, static_objs)
989    shared_lib = new_env.SharedLibrary(libname, shared_objs)
990
991    for target, sources in unit_tests:
992        objs = [ make_obj(s, static=True) for s in sources ]
993        new_env.Program("unittest/%s.%s" % (target, label), objs + static_objs)
994
995    # Now link a stub with main() and the static library.
996    bin_objs = [make_obj(s, True) for s in Source.get(bin_only=True) ]
997    progname = exename
998    if strip:
999        progname += '.unstripped'
1000
1001    targets = new_env.Program(progname, bin_objs + static_objs)
1002
1003    if strip:
1004        if sys.platform == 'sunos5':
1005            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
1006        else:
1007            cmd = 'strip $SOURCE -o $TARGET'
1008        targets = new_env.Command(exename, progname, cmd)
1009            
1010    new_env.M5Binary = targets[0]
1011    envList.append(new_env)
1012
1013# Debug binary
1014ccflags = {}
1015if env['GCC']:
1016    if sys.platform == 'sunos5':
1017        ccflags['debug'] = '-gstabs+'
1018    else:
1019        ccflags['debug'] = '-ggdb3'
1020    ccflags['opt'] = '-g -O3'
1021    ccflags['fast'] = '-O3'
1022    ccflags['prof'] = '-O3 -g -pg'
1023elif env['SUNCC']:
1024    ccflags['debug'] = '-g0'
1025    ccflags['opt'] = '-g -O'
1026    ccflags['fast'] = '-fast'
1027    ccflags['prof'] = '-fast -g -pg'
1028elif env['ICC']:
1029    ccflags['debug'] = '-g -O0'
1030    ccflags['opt'] = '-g -O'
1031    ccflags['fast'] = '-fast'
1032    ccflags['prof'] = '-fast -g -pg'
1033else:
1034    print 'Unknown compiler, please fix compiler options'
1035    Exit(1)
1036
1037makeEnv('debug', '.do',
1038        CCFLAGS = Split(ccflags['debug']),
1039        CPPDEFINES = ['DEBUG', 'TRACING_ON=1'])
1040
1041# Optimized binary
1042makeEnv('opt', '.o',
1043        CCFLAGS = Split(ccflags['opt']),
1044        CPPDEFINES = ['TRACING_ON=1'])
1045
1046# "Fast" binary
1047makeEnv('fast', '.fo', strip = True,
1048        CCFLAGS = Split(ccflags['fast']),
1049        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'])
1050
1051# Profiled binary
1052makeEnv('prof', '.po',
1053        CCFLAGS = Split(ccflags['prof']),
1054        CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1055        LINKFLAGS = '-pg')
1056
1057Return('envList')
1058