SConscript revision 8889
11689SN/A# -*- mode:python -*-
22316SN/A
31689SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
41689SN/A# All rights reserved.
51689SN/A#
61689SN/A# Redistribution and use in source and binary forms, with or without
71689SN/A# modification, are permitted provided that the following conditions are
81689SN/A# met: redistributions of source code must retain the above copyright
91689SN/A# notice, this list of conditions and the following disclaimer;
101689SN/A# redistributions in binary form must reproduce the above copyright
111689SN/A# notice, this list of conditions and the following disclaimer in the
121689SN/A# documentation and/or other materials provided with the distribution;
131689SN/A# neither the name of the copyright holders nor the names of its
141689SN/A# contributors may be used to endorse or promote products derived from
151689SN/A# this software without specific prior written permission.
161689SN/A#
171689SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
181689SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
191689SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
201689SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
211689SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
221689SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
231689SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
241689SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
251689SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
261689SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
272665Ssaidi@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
282665Ssaidi@eecs.umich.edu#
291689SN/A# Authors: Nathan Binkert
301689SN/A
312292SN/Aimport array
322329SN/Aimport bisect
332292SN/Aimport imp
342292SN/Aimport marshal
351060SN/Aimport os
362316SN/Aimport re
372292SN/Aimport sys
381717SN/Aimport zlib
392292SN/A
402292SN/Afrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
412292SN/A
421060SN/Aimport SCons
431061SN/A
442292SN/A# This file defines how to build a particular configuration of gem5
452292SN/A# based on variable settings in the 'env' build environment.
462292SN/A
471060SN/AImport('*')
482292SN/A
491060SN/A# Children need to see the environment
501060SN/AExport('env')
511061SN/A
521060SN/Abuild_env = [(opt, env[opt]) for opt in export_vars]
532292SN/A
541062SN/Afrom m5.util import code_formatter, compareVersions
552316SN/A
562316SN/A########################################################################
572292SN/A# Code for adding source files of various types
582292SN/A#
592292SN/A# When specifying a source file of some type, a set of guards can be
602292SN/A# specified for that file.  When get() is used to find the files, if
612292SN/A# get specifies a set of filters, only files that match those filters
622292SN/A# will be accepted (unspecified filters on files are assumed to be
632292SN/A# false).  Current filters are:
642292SN/A#     main -- specifies the gem5 main() function
652292SN/A#     skip_lib -- do not put this file into the gem5 library
662292SN/A#     <unittest> -- unit tests use filters based on the unit test name
672292SN/A#
682292SN/A# A parent can now be specified for a source file and default filter
692669Sktlim@umich.edu# values will be retrieved recursively from parents (children override
702292SN/A# parents).
712292SN/A#
722292SN/Aclass SourceMeta(type):
732292SN/A    '''Meta class for source files that keeps track of all files of a
742292SN/A    particular type and has a get function for finding all functions
752292SN/A    of a certain type that match a set of guards'''
762292SN/A    def __init__(cls, name, bases, dict):
772307SN/A        super(SourceMeta, cls).__init__(name, bases, dict)
782678Sktlim@umich.edu        cls.all = []
792316SN/A        
802316SN/A    def get(cls, **guards):
812316SN/A        '''Find all files that match the specified guards.  If a source
822292SN/A        file does not specify a flag, the default is False'''
832292SN/A        for src in cls.all:
842292SN/A            for flag,value in guards.iteritems():
852292SN/A                # if the flag is found and has a different value, skip
862292SN/A                # this file
872292SN/A                if src.all_guards.get(flag, False) != value:
882292SN/A                    break
892292SN/A            else:
902292SN/A                yield src
912292SN/A
922292SN/Aclass SourceFile(object):
932292SN/A    '''Base object that encapsulates the notion of a source file.
942292SN/A    This includes, the source node, target node, various manipulations
952292SN/A    of those.  A source file also specifies a set of guards which
962292SN/A    describing which builds the source file applies to.  A parent can
972292SN/A    also be specified to get default guards from'''
982292SN/A    __metaclass__ = SourceMeta
992292SN/A    def __init__(self, source, parent=None, **guards):
1002292SN/A        self.guards = guards
1012292SN/A        self.parent = parent
1022292SN/A
1032292SN/A        tnode = source
1042292SN/A        if not isinstance(source, SCons.Node.FS.File):
1052292SN/A            tnode = File(source)
1062292SN/A
1072292SN/A        self.tnode = tnode
1082292SN/A        self.snode = tnode.srcnode()
1092292SN/A
1102292SN/A        for base in type(self).__mro__:
1112292SN/A            if issubclass(base, SourceFile):
1122292SN/A                base.all.append(self)
1132292SN/A
1142292SN/A    @property
1152292SN/A    def filename(self):
1162292SN/A        return str(self.tnode)
1172292SN/A
1182680Sktlim@umich.edu    @property
1192678Sktlim@umich.edu    def dirname(self):
1202292SN/A        return dirname(self.filename)
1212292SN/A
1222292SN/A    @property
1232292SN/A    def basename(self):
1242292SN/A        return basename(self.filename)
1252292SN/A
1262292SN/A    @property
1272292SN/A    def extname(self):
1282292SN/A        index = self.basename.rfind('.')
1292292SN/A        if index <= 0:
1302292SN/A            # dot files aren't extensions
1312292SN/A            return self.basename, None
1322292SN/A
1332292SN/A        return self.basename[:index], self.basename[index+1:]
1342292SN/A
1352292SN/A    @property
1362132SN/A    def all_guards(self):
1372301SN/A        '''find all guards for this object getting default values
1381062SN/A        recursively from its parents'''
1391062SN/A        guards = {}
1401062SN/A        if self.parent:
1411062SN/A            guards.update(self.parent.guards)
1421062SN/A        guards.update(self.guards)
1431062SN/A        return guards
1441062SN/A
1451062SN/A    def __lt__(self, other): return self.filename < other.filename
1461062SN/A    def __le__(self, other): return self.filename <= other.filename
1471062SN/A    def __gt__(self, other): return self.filename > other.filename
1481062SN/A    def __ge__(self, other): return self.filename >= other.filename
1491062SN/A    def __eq__(self, other): return self.filename == other.filename
1501062SN/A    def __ne__(self, other): return self.filename != other.filename
1511062SN/A        
1521062SN/Aclass Source(SourceFile):
1531062SN/A    '''Add a c/c++ source file to the build'''
1541062SN/A    def __init__(self, source, Werror=True, swig=False, **guards):
1551062SN/A        '''specify the source file, and any guards'''
1561062SN/A        super(Source, self).__init__(source, **guards)
1571062SN/A
1581062SN/A        self.Werror = Werror
1592292SN/A        self.swig = swig
1601062SN/A
1611062SN/Aclass PySource(SourceFile):
1621062SN/A    '''Add a python source file to the named package'''
1631062SN/A    invalid_sym_char = re.compile('[^A-z0-9_]')
1641062SN/A    modules = {}
1652301SN/A    tnodes = {}
1662316SN/A    symnames = {}
1672301SN/A    
1682301SN/A    def __init__(self, package, source, **guards):
1692301SN/A        '''specify the python package, the source file, and any guards'''
1702301SN/A        super(PySource, self).__init__(source, **guards)
1712301SN/A
1722301SN/A        modname,ext = self.extname
1732316SN/A        assert ext == 'py'
1742301SN/A
1752301SN/A        if package:
1762301SN/A            path = package.split('.')
1772301SN/A        else:
1782301SN/A            path = []
1792301SN/A
1802316SN/A        modpath = path[:]
1812301SN/A        if modname != '__init__':
1822301SN/A            modpath += [ modname ]
1832301SN/A        modpath = '.'.join(modpath)
1842301SN/A
1852301SN/A        arcpath = path + [ self.basename ]
1862301SN/A        abspath = self.snode.abspath
1872316SN/A        if not exists(abspath):
1882301SN/A            abspath = self.tnode.abspath
1892301SN/A
1902301SN/A        self.package = package
1912301SN/A        self.modname = modname
1922301SN/A        self.modpath = modpath
1932301SN/A        self.arcname = joinpath(*arcpath)
1942316SN/A        self.abspath = abspath
1952301SN/A        self.compiled = File(self.filename + 'c')
1962301SN/A        self.cpp = File(self.filename + '.cc')
1972301SN/A        self.symname = PySource.invalid_sym_char.sub('_', modpath)
1982301SN/A
1992301SN/A        PySource.modules[modpath] = self
2002301SN/A        PySource.tnodes[self.tnode] = self
2012316SN/A        PySource.symnames[self.symname] = self
2022301SN/A
2032301SN/Aclass SimObject(PySource):
2042301SN/A    '''Add a SimObject python file as a python source object and add
2052301SN/A    it to a list of sim object modules'''
2062301SN/A
2072301SN/A    fixed = False
2082301SN/A    modnames = []
2092301SN/A
2102301SN/A    def __init__(self, source, **guards):
2112301SN/A        '''Specify the source file and any guards (automatically in
2122301SN/A        the m5.objects package)'''
2132301SN/A        super(SimObject, self).__init__('m5.objects', source, **guards)
2142301SN/A        if self.fixed:
2152301SN/A            raise AttributeError, "Too late to call SimObject now."
2162301SN/A
2172301SN/A        bisect.insort_right(SimObject.modnames, self.modname)
2182301SN/A
2192301SN/Aclass SwigSource(SourceFile):
2202301SN/A    '''Add a swig file to build'''
2212316SN/A
2222301SN/A    def __init__(self, package, source, **guards):
2232301SN/A        '''Specify the python package, the source file, and any guards'''
2242301SN/A        super(SwigSource, self).__init__(source, **guards)
2252301SN/A
2262301SN/A        modname,ext = self.extname
2272301SN/A        assert ext == 'i'
2282316SN/A
2292301SN/A        self.module = modname
2302301SN/A        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
2312301SN/A        py_file = joinpath(self.dirname, modname + '.py')
2321062SN/A
2331062SN/A        self.cc_source = Source(cc_file, swig=True, parent=self)
2341062SN/A        self.py_source = PySource(package, py_file, parent=self)
2351062SN/A
2362292SN/Aclass UnitTest(object):
2371060SN/A    '''Create a UnitTest'''
2381060SN/A
2391060SN/A    all = []
2402292SN/A    def __init__(self, target, *sources):
2412292SN/A        '''Specify the target name and any sources.  Sources that are
2422292SN/A        not SourceFiles are evalued with Source().  All files are
2432292SN/A        guarded with a guard of the same name as the UnitTest
2442307SN/A        target.'''
2452316SN/A
2462316SN/A        srcs = []
2471060SN/A        for src in sources:
2481060SN/A            if not isinstance(src, SourceFile):
2491061SN/A                src = Source(src, skip_lib=True)
2501060SN/A            src.guards[target] = True
2512292SN/A            srcs.append(src)
2522292SN/A
2532292SN/A        self.sources = srcs
2542292SN/A        self.target = target
2552292SN/A        UnitTest.all.append(self)
2562292SN/A
2572292SN/A# Children should have access
2582292SN/AExport('Source')
2591060SN/AExport('PySource')
2601060SN/AExport('SimObject')
2611060SN/AExport('SwigSource')
2621060SN/AExport('UnitTest')
2631060SN/A
2641060SN/A########################################################################
2651060SN/A#
2661060SN/A# Debug Flags
2671060SN/A#
2681060SN/Adebug_flags = {}
2691060SN/Adef DebugFlag(name, desc=None):
2701061SN/A    if name in debug_flags:
2711060SN/A        raise AttributeError, "Flag %s already specified" % name
2722292SN/A    debug_flags[name] = (name, (), desc)
2732292SN/A
2742292SN/Adef CompoundFlag(name, flags, desc=None):
2752292SN/A    if name in debug_flags:
2762292SN/A        raise AttributeError, "Flag %s already specified" % name
2772292SN/A
2782292SN/A    compound = tuple(flags)
2792292SN/A    debug_flags[name] = (name, compound, desc)
2802292SN/A
2812292SN/AExport('DebugFlag')
2822292SN/AExport('CompoundFlag')
2832292SN/A
2841060SN/A########################################################################
2851060SN/A#
2861060SN/A# Set some compiler variables
2871060SN/A#
2881060SN/A
2891060SN/A# Include file paths are rooted in this directory.  SCons will
2901060SN/A# automatically expand '.' to refer to both the source directory and
2911060SN/A# the corresponding build directory to pick up generated include
2921061SN/A# files.
2931060SN/Aenv.Append(CPPPATH=Dir('.'))
2942292SN/A
2951060SN/Afor extra_dir in extras_dir_list:
2961060SN/A    env.Append(CPPPATH=Dir(extra_dir))
2971060SN/A
2981060SN/A# Workaround for bug in SCons version > 0.97d20071212
2991060SN/A# Scons bug id: 2006 gem5 Bug id: 308
3001060SN/Afor root, dirs, files in os.walk(base_dir, topdown=True):
3011060SN/A    Dir(root[len(base_dir) + 1:])
3021060SN/A
3031061SN/A########################################################################
3041060SN/A#
3052316SN/A# Walk the tree and execute all SConscripts in subdirectories
3062316SN/A#
3072316SN/A
3082316SN/Ahere = Dir('.').srcnode().abspath
3092316SN/Afor root, dirs, files in os.walk(base_dir, topdown=True):
3102316SN/A    if root == here:
3112316SN/A        # we don't want to recurse back into this SConscript
3122292SN/A        continue
3132292SN/A
3142292SN/A    if 'SConscript' in files:
3152292SN/A        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3162292SN/A        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3172292SN/A
3182292SN/Afor extra_dir in extras_dir_list:
3192292SN/A    prefix_len = len(dirname(extra_dir)) + 1
3202292SN/A    for root, dirs, files in os.walk(extra_dir, topdown=True):
3212292SN/A        # if build lives in the extras directory, don't walk down it
3222292SN/A        if 'build' in dirs:
3232292SN/A            dirs.remove('build')
3242292SN/A
3252292SN/A        if 'SConscript' in files:
3262292SN/A            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3272292SN/A            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3282292SN/A
3292292SN/Afor opt in export_vars:
3302292SN/A    env.ConfigFile(opt)
3312292SN/A
3322292SN/Adef makeTheISA(source, target, env):
3332292SN/A    isas = [ src.get_contents() for src in source ]
3342292SN/A    target_isa = env['TARGET_ISA']
3352292SN/A    def define(isa):
3362292SN/A        return isa.upper() + '_ISA'
3372292SN/A    
3382292SN/A    def namespace(isa):
3391060SN/A        return isa[0].upper() + isa[1:].lower() + 'ISA' 
3401060SN/A
3411060SN/A
3421060SN/A    code = code_formatter()
3431060SN/A    code('''\
3441061SN/A#ifndef __CONFIG_THE_ISA_HH__
3451060SN/A#define __CONFIG_THE_ISA_HH__
3462292SN/A
3471060SN/A''')
3482292SN/A
3492292SN/A    for i,isa in enumerate(isas):
3501060SN/A        code('#define $0 $1', define(isa), i + 1)
3512292SN/A
3522292SN/A    code('''
3532292SN/A
3542292SN/A#define THE_ISA ${{define(target_isa)}}
3551060SN/A#define TheISA ${{namespace(target_isa)}}
3561060SN/A
3572292SN/A#endif // __CONFIG_THE_ISA_HH__''')
3581060SN/A
3591060SN/A    code.write(str(target[0]))
3601061SN/A
3611060SN/Aenv.Command('config/the_isa.hh', map(Value, all_isa_list),
3622307SN/A            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
3631060SN/A
3642316SN/A########################################################################
3652316SN/A#
3662316SN/A# Prevent any SimObjects from being added after this point, they
3672316SN/A# should all have been added in the SConscripts above
3682316SN/A#
3692316SN/ASimObject.fixed = True
3702316SN/A
3712316SN/Aclass DictImporter(object):
3722316SN/A    '''This importer takes a dictionary of arbitrary module names that
3732307SN/A    map to arbitrary filenames.'''
3742307SN/A    def __init__(self, modules):
3752307SN/A        self.modules = modules
3762307SN/A        self.installed = set()
3772307SN/A
3782307SN/A    def __del__(self):
3792307SN/A        self.unload()
3802316SN/A
3812307SN/A    def unload(self):
3822307SN/A        import sys
3832307SN/A        for module in self.installed:
3842307SN/A            del sys.modules[module]
3852307SN/A        self.installed = set()
3862307SN/A
3872680Sktlim@umich.edu    def find_module(self, fullname, path):
3882307SN/A        if fullname == 'm5.defines':
3892307SN/A            return self
3902307SN/A
3912307SN/A        if fullname == 'm5.objects':
3922307SN/A            return self
3932307SN/A
3942307SN/A        if fullname.startswith('m5.internal'):
3952292SN/A            return None
3962132SN/A
3972316SN/A        source = self.modules.get(fullname, None)
3982316SN/A        if source is not None and fullname.startswith('m5.objects'):
3992316SN/A            return self
4002316SN/A
4012316SN/A        return None
4022316SN/A
4032316SN/A    def load_module(self, fullname):
4042316SN/A        mod = imp.new_module(fullname)
4052316SN/A        sys.modules[fullname] = mod
4062316SN/A        self.installed.add(fullname)
4072316SN/A
4082292SN/A        mod.__loader__ = self
4092292SN/A        if fullname == 'm5.objects':
4102292SN/A            mod.__path__ = fullname.split('.')
4112292SN/A            return mod
4122292SN/A
4132292SN/A        if fullname == 'm5.defines':
4142292SN/A            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
4152292SN/A            return mod
4162292SN/A
4172292SN/A        source = self.modules[fullname]
4182292SN/A        if source.modname == '__init__':
4192292SN/A            mod.__path__ = source.modpath
4202292SN/A        mod.__file__ = source.abspath
4212292SN/A
4222292SN/A        exec file(source.abspath, 'r') in mod.__dict__
4232292SN/A
4242292SN/A        return mod
4252292SN/A
4262292SN/Aimport m5.SimObject
4272292SN/Aimport m5.params
4282292SN/Afrom m5.util import code_formatter
4292292SN/A
4302292SN/Am5.SimObject.clear()
4312292SN/Am5.params.clear()
4322292SN/A
4332292SN/A# install the python importer so we can grab stuff from the source
4342292SN/A# tree itself.  We can't have SimObjects added after this point or
4352292SN/A# else we won't know about them for the rest of the stuff.
4362292SN/Aimporter = DictImporter(PySource.modules)
4372292SN/Asys.meta_path[0:0] = [ importer ]
4382292SN/A
4392292SN/A# import all sim objects so we can populate the all_objects list
4402292SN/A# make sure that we're working with a list, then let's sort it
4412292SN/Afor modname in SimObject.modnames:
4422292SN/A    exec('from m5.objects import %s' % modname)
4432292SN/A
4442292SN/A# we need to unload all of the currently imported modules so that they
4452292SN/A# will be re-imported the next time the sconscript is run
4462292SN/Aimporter.unload()
4472292SN/Asys.meta_path.remove(importer)
4482292SN/A
4492292SN/Asim_objects = m5.SimObject.allClasses
4502292SN/Aall_enums = m5.params.allEnums
4512292SN/A
4522292SN/A# Find param types that need to be explicitly wrapped with swig.
4532292SN/A# These will be recognized because the ParamDesc will have a
4542292SN/A# swig_decl() method.  Most param types are based on types that don't
4552292SN/A# need this, either because they're based on native types (like Int)
4562292SN/A# or because they're SimObjects (which get swigged independently).
4572292SN/A# For now the only things handled here are VectorParam types.
4582292SN/Aparams_to_swig = {}
4592292SN/Afor name,obj in sorted(sim_objects.iteritems()):
4602292SN/A    for param in obj._params.local.values():
4612292SN/A        # load the ptype attribute now because it depends on the
4622292SN/A        # current version of SimObject.allClasses, but when scons
4632292SN/A        # actually uses the value, all versions of
4642292SN/A        # SimObject.allClasses will have been loaded
4652292SN/A        param.ptype
4662292SN/A
4672292SN/A        if not hasattr(param, 'swig_decl'):
4682292SN/A            continue
4692292SN/A        pname = param.ptype_str
4702292SN/A        if pname not in params_to_swig:
4712292SN/A            params_to_swig[pname] = param
4722292SN/A
4732292SN/A########################################################################
4742292SN/A#
4752292SN/A# calculate extra dependencies
4762292SN/A#
4772292SN/Amodule_depends = ["m5", "m5.SimObject", "m5.params"]
4782292SN/Adepends = [ PySource.modules[dep].snode for dep in module_depends ]
4792292SN/A
4802292SN/A########################################################################
4812292SN/A#
4822292SN/A# Commands for the basic automatically generated python files
4832292SN/A#
4842292SN/A
4852680Sktlim@umich.edu# Generate Python file containing a dict specifying the current
4862292SN/A# buildEnv flags.
4872680Sktlim@umich.edudef makeDefinesPyFile(target, source, env):
4882292SN/A    build_env = source[0].get_contents()
4892680Sktlim@umich.edu
4902292SN/A    code = code_formatter()
4912292SN/A    code("""
4922292SN/Aimport m5.internal
4932292SN/Aimport m5.util
4942316SN/A
4952292SN/AbuildEnv = m5.util.SmartDict($build_env)
4962292SN/A
4972292SN/AcompileDate = m5.internal.core.compileDate
4982292SN/A_globals = globals()
4992292SN/Afor key,val in m5.internal.core.__dict__.iteritems():
5002292SN/A    if key.startswith('flag_'):
5012292SN/A        flag = key[5:]
5022292SN/A        _globals[flag] = val
5032292SN/Adel _globals
5042292SN/A""")
5052292SN/A    code.write(target[0].abspath)
5062292SN/A
5072292SN/Adefines_info = Value(build_env)
5082292SN/A# Generate a file with all of the compile options in it
5092292SN/Aenv.Command('python/m5/defines.py', defines_info,
5102292SN/A            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
5112292SN/APySource('m5', 'python/m5/defines.py')
5122292SN/A
5132292SN/A# Generate python file containing info about the M5 source code
5142292SN/Adef makeInfoPyFile(target, source, env):
5152292SN/A    code = code_formatter()
5162292SN/A    for src in source:
5172292SN/A        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
5182292SN/A        code('$src = ${{repr(data)}}')
5192292SN/A    code.write(str(target[0]))
5202292SN/A
5212292SN/A# Generate a file that wraps the basic top level files
5222292SN/Aenv.Command('python/m5/info.py',
5232292SN/A            [ '#/COPYING', '#/LICENSE', '#/README', ],
5242316SN/A            MakeAction(makeInfoPyFile, Transform("INFO")))
5252316SN/APySource('m5', 'python/m5/info.py')
5262292SN/A
5272316SN/A########################################################################
5282316SN/A#
5292316SN/A# Create all of the SimObject param headers and enum headers
5302316SN/A#
5312316SN/A
5322316SN/Adef createSimObjectParamStruct(target, source, env):
5332316SN/A    assert len(target) == 1 and len(source) == 1
5342316SN/A
5352316SN/A    name = str(source[0].get_contents())
5362316SN/A    obj = sim_objects[name]
5372316SN/A
5382316SN/A    code = code_formatter()
5392316SN/A    obj.cxx_param_decl(code)
5402316SN/A    code.write(target[0].abspath)
5412316SN/A
5422316SN/Adef createParamSwigWrapper(target, source, env):
5432316SN/A    assert len(target) == 1 and len(source) == 1
5442316SN/A
5452316SN/A    name = str(source[0].get_contents())
5462316SN/A    param = params_to_swig[name]
5472316SN/A
5482680Sktlim@umich.edu    code = code_formatter()
5492316SN/A    param.swig_decl(code)
5502316SN/A    code.write(target[0].abspath)
5512292SN/A
5522680Sktlim@umich.edudef createEnumStrings(target, source, env):
5532292SN/A    assert len(target) == 1 and len(source) == 1
5542292SN/A
5552292SN/A    name = str(source[0].get_contents())
5562316SN/A    obj = all_enums[name]
5572292SN/A
5582292SN/A    code = code_formatter()
5592292SN/A    obj.cxx_def(code)
5602680Sktlim@umich.edu    code.write(target[0].abspath)
5612292SN/A
5622292SN/Adef createEnumDecls(target, source, env):
5632292SN/A    assert len(target) == 1 and len(source) == 1
5642292SN/A
5652292SN/A    name = str(source[0].get_contents())
5662292SN/A    obj = all_enums[name]
5672292SN/A
5682292SN/A    code = code_formatter()
5692292SN/A    obj.cxx_decl(code)
5702292SN/A    code.write(target[0].abspath)
5712292SN/A
5722316SN/Adef createEnumSwigWrapper(target, source, env):
5732316SN/A    assert len(target) == 1 and len(source) == 1
5742316SN/A
5752316SN/A    name = str(source[0].get_contents())
5762316SN/A    obj = all_enums[name]
5772292SN/A
5782292SN/A    code = code_formatter()
5792316SN/A    obj.swig_decl(code)
5802316SN/A    code.write(target[0].abspath)
5812292SN/A
5822292SN/Adef createSimObjectSwigWrapper(target, source, env):
5832292SN/A    name = source[0].get_contents()
5842292SN/A    obj = sim_objects[name]
5852292SN/A
5862292SN/A    code = code_formatter()
5872292SN/A    obj.swig_decl(code)
5882292SN/A    code.write(target[0].abspath)
5892292SN/A
5902292SN/A# Generate all of the SimObject param C++ struct header files
5912292SN/Aparams_hh_files = []
5922292SN/Afor name,simobj in sorted(sim_objects.iteritems()):
5932292SN/A    py_source = PySource.modules[simobj.__module__]
5942292SN/A    extra_deps = [ py_source.tnode ]
5952292SN/A
5962292SN/A    hh_file = File('params/%s.hh' % name)
5972292SN/A    params_hh_files.append(hh_file)
5982292SN/A    env.Command(hh_file, Value(name),
5992292SN/A                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
6002292SN/A    env.Depends(hh_file, depends + extra_deps)
6012292SN/A
6022292SN/A# Generate any needed param SWIG wrapper files
6032292SN/Aparams_i_files = []
6042292SN/Afor name,param in params_to_swig.iteritems():
6052292SN/A    i_file = File('python/m5/internal/%s.i' % (param.swig_module_name()))
6062292SN/A    params_i_files.append(i_file)
6072292SN/A    env.Command(i_file, Value(name),
6082292SN/A                MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
6092292SN/A    env.Depends(i_file, depends)
6102292SN/A    SwigSource('m5.internal', i_file)
6112292SN/A
6122292SN/A# Generate all enum header files
6132292SN/Afor name,enum in sorted(all_enums.iteritems()):
6142292SN/A    py_source = PySource.modules[enum.__module__]
6152292SN/A    extra_deps = [ py_source.tnode ]
6162292SN/A
6172292SN/A    cc_file = File('enums/%s.cc' % name)
6182292SN/A    env.Command(cc_file, Value(name),
6192292SN/A                MakeAction(createEnumStrings, Transform("ENUM STR")))
6202292SN/A    env.Depends(cc_file, depends + extra_deps)
6212292SN/A    Source(cc_file)
6222292SN/A
6232292SN/A    hh_file = File('enums/%s.hh' % name)
6242292SN/A    env.Command(hh_file, Value(name),
6252292SN/A                MakeAction(createEnumDecls, Transform("ENUMDECL")))
6262292SN/A    env.Depends(hh_file, depends + extra_deps)
6272292SN/A
6282292SN/A    i_file = File('python/m5/internal/enum_%s.i' % name)
6292292SN/A    env.Command(i_file, Value(name),
6302316SN/A                MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
6312292SN/A    env.Depends(i_file, depends + extra_deps)
6322292SN/A    SwigSource('m5.internal', i_file)
6332292SN/A
6342292SN/A# Generate SimObject SWIG wrapper files
6352292SN/Afor name in sim_objects.iterkeys():
6362292SN/A    i_file = File('python/m5/internal/param_%s.i' % name)
6372292SN/A    env.Command(i_file, Value(name),
6382292SN/A                MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
6392292SN/A    env.Depends(i_file, depends)
6402292SN/A    SwigSource('m5.internal', i_file)
6412292SN/A
6421060SN/A# Generate the main swig init file
6431060SN/Adef makeEmbeddedSwigInit(target, source, env):
6441060SN/A    code = code_formatter()
6451060SN/A    module = source[0].get_contents()
6461858SN/A    code('''\
6472316SN/A#include "sim/init.hh"
6482316SN/A
6492316SN/Aextern "C" {
6502292SN/A    void init_${module}();
6511060SN/A}
6522292SN/A
6532292SN/AEmbeddedSwig embed_swig_${module}(init_${module});
6542680Sktlim@umich.edu''')
6552316SN/A    code.write(str(target[0]))
6562316SN/A    
6572316SN/A# Build all swig modules
6582292SN/Afor swig in SwigSource.all:
6591060SN/A    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
6602316SN/A                MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
6612316SN/A                '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
6622292SN/A    cc_file = str(swig.tnode)
6632292SN/A    init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
6642292SN/A    env.Command(init_file, Value(swig.module),
6652292SN/A                MakeAction(makeEmbeddedSwigInit, Transform("EMBED SW")))
6662292SN/A    Source(init_file, **swig.guards)
6672292SN/A
6682292SN/A#
6692292SN/A# Handle debug flags
6702292SN/A#
6712292SN/Adef makeDebugFlagCC(target, source, env):
6722292SN/A    assert(len(target) == 1 and len(source) == 1)
6732292SN/A
6742292SN/A    val = eval(source[0].get_contents())
6752292SN/A    name, compound, desc = val
6762292SN/A    compound = list(sorted(compound))
6772292SN/A
6782292SN/A    code = code_formatter()
6792292SN/A
6802292SN/A    # file header
6812292SN/A    code('''
6822292SN/A/*
6832292SN/A * DO NOT EDIT THIS FILE! Automatically generated
6842292SN/A */
6852292SN/A
6861060SN/A#include "base/debug.hh"
6871060SN/A''')
6881060SN/A
6891060SN/A    for flag in compound:
6902316SN/A        code('#include "debug/$flag.hh"')
6911060SN/A    code()
6921060SN/A    code('namespace Debug {')
6932292SN/A    code()
6941060SN/A
6952292SN/A    if not compound:
6962292SN/A        code('SimpleFlag $name("$name", "$desc");')
6972348SN/A    else:
6982307SN/A        code('CompoundFlag $name("$name", "$desc",')
6992316SN/A        code.indent()
7002316SN/A        last = len(compound) - 1
7012316SN/A        for i,flag in enumerate(compound):
7022292SN/A            if i != last:
7032292SN/A                code('$flag,')
7042292SN/A            else:
7052292SN/A                code('$flag);')
7062292SN/A        code.dedent()
7072292SN/A
7082292SN/A    code()
7091060SN/A    code('} // namespace Debug')
7102316SN/A
7112292SN/A    code.write(str(target[0]))
7122292SN/A
7132292SN/Adef makeDebugFlagHH(target, source, env):
7142292SN/A    assert(len(target) == 1 and len(source) == 1)
7152292SN/A
7162292SN/A    val = eval(source[0].get_contents())
7172292SN/A    name, compound, desc = val
7182292SN/A
7192348SN/A    code = code_formatter()
7202292SN/A
7212292SN/A    # file header boilerplate
7222292SN/A    code('''\
7232680Sktlim@umich.edu/*
7242292SN/A * DO NOT EDIT THIS FILE!
7252680Sktlim@umich.edu *
7262680Sktlim@umich.edu * Automatically generated by SCons
7272292SN/A */
7281061SN/A
7292292SN/A#ifndef __DEBUG_${name}_HH__
7302292SN/A#define __DEBUG_${name}_HH__
7312292SN/A
7322292SN/Anamespace Debug {
7332292SN/A''')
7342292SN/A
7351061SN/A    if compound:
7362292SN/A        code('class CompoundFlag;')
7372292SN/A    code('class SimpleFlag;')
7382292SN/A
7392292SN/A    if compound:
7401061SN/A        code('extern CompoundFlag $name;')
7412292SN/A        for flag in compound:
7422292SN/A            code('extern SimpleFlag $flag;')
7432292SN/A    else:
7441061SN/A        code('extern SimpleFlag $name;')
7452292SN/A
7461061SN/A    code('''
7472292SN/A}
7481061SN/A
7492292SN/A#endif // __DEBUG_${name}_HH__
7502292SN/A''')
7512292SN/A
7521062SN/A    code.write(str(target[0]))
7532292SN/A
7542292SN/Afor name,flag in sorted(debug_flags.iteritems()):
7552292SN/A    n, compound, desc = flag
7562292SN/A    assert n == name
7572292SN/A
7582292SN/A    env.Command('debug/%s.hh' % name, Value(flag),
7592292SN/A                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
7602292SN/A    env.Command('debug/%s.cc' % name, Value(flag),
7612292SN/A                MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
7622292SN/A    Source('debug/%s.cc' % name)
7632292SN/A
7642292SN/A# Embed python files.  All .py files that have been indicated by a
7652292SN/A# PySource() call in a SConscript need to be embedded into the M5
7662292SN/A# library.  To do that, we compile the file to byte code, marshal the
7672292SN/A# byte code, compress it, and then generate a c++ file that
7682292SN/A# inserts the result into an array.
7692292SN/Adef embedPyFile(target, source, env):
7702292SN/A    def c_str(string):
7712292SN/A        if string is None:
7722292SN/A            return "0"
7732292SN/A        return '"%s"' % string
7742292SN/A
7752292SN/A    '''Action function to compile a .py into a code object, marshal
7762292SN/A    it, compress it, and stick it into an asm file so the code appears
7772292SN/A    as just bytes with a label in the data section'''
7782292SN/A
7792316SN/A    src = file(str(source[0]), 'r').read()
7802292SN/A
7812292SN/A    pysource = PySource.tnodes[source[0]]
7822292SN/A    compiled = compile(src, pysource.abspath, 'exec')
7832292SN/A    marshalled = marshal.dumps(compiled)
7841062SN/A    compressed = zlib.compress(marshalled)
7852292SN/A    data = compressed
7861060SN/A    sym = pysource.symname
7871060SN/A
7882292SN/A    code = code_formatter()
7892292SN/A    code('''\
7902292SN/A#include "sim/init.hh"
7911061SN/A
7921060SN/Anamespace {
7931060SN/A
7941061SN/Aconst char data_${sym}[] = {
7951060SN/A''')
7961060SN/A    code.indent()
7971060SN/A    step = 16
7982292SN/A    for i in xrange(0, len(data), step):
7992292SN/A        x = array.array('B', data[i:i+step])
8002292SN/A        code(''.join('%d,' % d for d in x))
8012292SN/A    code.dedent()
8022292SN/A    
8032292SN/A    code('''};
8042292SN/A
8052292SN/AEmbeddedPython embedded_${sym}(
8062292SN/A    ${{c_str(pysource.arcname)}},
8072292SN/A    ${{c_str(pysource.abspath)}},
8082292SN/A    ${{c_str(pysource.modpath)}},
8092292SN/A    data_${sym},
8102292SN/A    ${{len(data)}},
8112292SN/A    ${{len(marshalled)}});
8122292SN/A
8132292SN/A} // anonymous namespace
8142292SN/A''')
8151060SN/A    code.write(str(target[0]))
8161060SN/A
8171060SN/Afor source in PySource.all:
8181061SN/A    env.Command(source.cpp, source.tnode, 
8191060SN/A                MakeAction(embedPyFile, Transform("EMBED PY")))
8202292SN/A    Source(source.cpp)
8211060SN/A
8221060SN/A########################################################################
8231060SN/A#
8242316SN/A# Define binaries.  Each different build type (debug, opt, etc.) gets
8252316SN/A# a slightly different build environment.
8262316SN/A#
8272316SN/A
8282316SN/A# List of constructed environments to pass back to SConstruct
8291060SN/AenvList = []
8301060SN/A
8312292SN/Adate_source = Source('base/date.cc', skip_lib=True)
8321060SN/A
8331060SN/A# Function to create a new build environment as clone of current
8341060SN/A# environment 'env' with modified object suffix and optional stripped
8352292SN/A# binary.  Additional keyword arguments are appended to corresponding
8362316SN/A# build environment vars.
8371060SN/Adef makeEnv(label, objsfx, strip = False, **kwargs):
8381060SN/A    # SCons doesn't know to append a library suffix when there is a '.' in the
8392292SN/A    # name.  Use '_' instead.
8402292SN/A    libname = 'gem5_' + label
8411060SN/A    exename = 'gem5.' + label
8422292SN/A    secondary_exename = 'm5.' + label
8432292SN/A
8442292SN/A    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
8452292SN/A    new_env.Label = label
8462292SN/A    new_env.Append(**kwargs)
8472292SN/A
8482292SN/A    swig_env = new_env.Clone()
8492292SN/A    swig_env.Append(CCFLAGS='-Werror')
8502292SN/A    if env['GCC']:
8512292SN/A        swig_env.Append(CCFLAGS='-Wno-uninitialized')
8522292SN/A        swig_env.Append(CCFLAGS='-Wno-sign-compare')
8532132SN/A        swig_env.Append(CCFLAGS='-Wno-parentheses')
8542316SN/A        swig_env.Append(CCFLAGS='-Wno-unused-label')
8552316SN/A        if compareVersions(env['GCC_VERSION'], '4.6.0') != -1:
8561060SN/A            swig_env.Append(CCFLAGS='-Wno-unused-but-set-variable')
8571060SN/A    if env['CLANG']:
8582292SN/A        swig_env.Append(CCFLAGS=['-Wno-unused-label'])
8591060SN/A
8601060SN/A
8612292SN/A    werror_env = new_env.Clone()
8621060SN/A    werror_env.Append(CCFLAGS='-Werror')
8631062SN/A
8641062SN/A    def make_obj(source, static, extra_deps = None):
8652292SN/A        '''This function adds the specified source to the correct
8662292SN/A        build environment, and returns the corresponding SCons Object
8671060SN/A        nodes'''
8682292SN/A
8692292SN/A        if source.swig:
8702292SN/A            env = swig_env
8711060SN/A        elif source.Werror:
8721060SN/A            env = werror_env
8731060SN/A        else:
8741061SN/A            env = new_env
8751061SN/A
8762292SN/A        if static:
8771060SN/A            obj = env.StaticObject(source.tnode)
8781060SN/A        else:
8791060SN/A            obj = env.SharedObject(source.tnode)
8801060SN/A
8811062SN/A        if extra_deps:
8821060SN/A            env.Depends(obj, extra_deps)
8831060SN/A
8842292SN/A        return obj
8852292SN/A
8862292SN/A    static_objs = \
8872292SN/A        [ make_obj(s, True) for s in Source.get(main=False, skip_lib=False) ]
8881060SN/A    shared_objs = \
8891062SN/A        [ make_obj(s, False) for s in Source.get(main=False, skip_lib=False) ]
8901062SN/A
8912292SN/A    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
8922292SN/A    static_objs.append(static_date)
8932292SN/A    
8942292SN/A    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
8951062SN/A    shared_objs.append(shared_date)
8962292SN/A
8972292SN/A    # First make a library of everything but main() so other programs can
8982307SN/A    # link against m5.
8992292SN/A    static_lib = new_env.StaticLibrary(libname, static_objs)
9002292SN/A    shared_lib = new_env.SharedLibrary(libname, shared_objs)
9012292SN/A
9022292SN/A    # Now link a stub with main() and the static library.
9032316SN/A    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
9042316SN/A
9052292SN/A    for test in UnitTest.all:
9062316SN/A        flags = { test.target : True }
9072316SN/A        test_sources = Source.get(**flags)
9082292SN/A        test_objs = [ make_obj(s, static=True) for s in test_sources ]
9092292SN/A        testname = "unittest/%s.%s" % (test.target, label)
9102690Sktlim@umich.edu        new_env.Program(testname, main_objs + test_objs + static_objs)
9112292SN/A
9122292SN/A    progname = exename
9132292SN/A    if strip:
9142292SN/A        progname += '.unstripped'
9152292SN/A
9162292SN/A    targets = new_env.Program(progname, main_objs + static_objs)
9172292SN/A
9181060SN/A    if strip:
9192292SN/A        if sys.platform == 'sunos5':
9202292SN/A            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
9212292SN/A        else:
9221060SN/A            cmd = 'strip $SOURCE -o $TARGET'
9231060SN/A        targets = new_env.Command(exename, progname,
9241060SN/A                    MakeAction(cmd, Transform("STRIP")))
9251060SN/A
9261062SN/A    new_env.Command(secondary_exename, exename,
9271063SN/A            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
9282292SN/A
9292307SN/A    new_env.M5Binary = targets[0]
9302307SN/A    envList.append(new_env)
9312349SN/A
9322307SN/A# Debug binary
9331060SN/Accflags = {}
9341060SN/Aif env['GCC'] or env['CLANG']:
9351061SN/A    if sys.platform == 'sunos5':
9361060SN/A        ccflags['debug'] = '-gstabs+'
9372292SN/A    else:
9381060SN/A        ccflags['debug'] = '-ggdb3'
9391060SN/A    ccflags['opt'] = '-g -O3'
9401060SN/A    ccflags['fast'] = '-O3'
9412292SN/A    ccflags['prof'] = '-O3 -g -pg'
9422292SN/Aelif env['SUNCC']:
9432316SN/A    ccflags['debug'] = '-g0'
9442316SN/A    ccflags['opt'] = '-g -O'
9451061SN/A    ccflags['fast'] = '-fast'
9461061SN/A    ccflags['prof'] = '-fast -g -pg'
9471061SN/Aelif env['ICC']:
9482292SN/A    ccflags['debug'] = '-g -O0'
9491062SN/A    ccflags['opt'] = '-g -O'
9502292SN/A    ccflags['fast'] = '-fast'
9511060SN/A    ccflags['prof'] = '-fast -g -pg'
9522292SN/Aelse:
9532348SN/A    print 'Unknown compiler, please fix compiler options'
9542292SN/A    Exit(1)
9552292SN/A
9562316SN/A
9572316SN/A# To speed things up, we only instantiate the build environments we
9582316SN/A# need.  We try to identify the needed environment for each target; if
9592316SN/A# we can't, we fall back on instantiating all the environments just to
9602316SN/A# be safe.
9612292SN/Atarget_types = ['debug', 'opt', 'fast', 'prof']
9622316SN/Aobj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof'}
9632316SN/A
9642316SN/Adef identifyTarget(t):
9652316SN/A    ext = t.split('.')[-1]
9662292SN/A    if ext in target_types:
9672292SN/A        return ext
9682292SN/A    if obj2target.has_key(ext):
9692292SN/A        return obj2target[ext]
9702292SN/A    match = re.search(r'/tests/([^/]+)/', t)
9712292SN/A    if match and match.group(1) in target_types:
9722292SN/A        return match.group(1)
9732292SN/A    return 'all'
9742292SN/A
9752292SN/Aneeded_envs = [identifyTarget(target) for target in BUILD_TARGETS]
9762292SN/Aif 'all' in needed_envs:
9772292SN/A    needed_envs += target_types
9781061SN/A
9791061SN/A# Debug binary
9801061SN/Aif 'debug' in needed_envs:
9811061SN/A    makeEnv('debug', '.do',
9821061SN/A            CCFLAGS = Split(ccflags['debug']),
9831062SN/A            CPPDEFINES = ['DEBUG', 'TRACING_ON=1'])
9841062SN/A
9851061SN/A# Optimized binary
9862292SN/Aif 'opt' in needed_envs:
9872292SN/A    makeEnv('opt', '.o',
9882292SN/A            CCFLAGS = Split(ccflags['opt']),
9892292SN/A            CPPDEFINES = ['TRACING_ON=1'])
9902292SN/A
9912316SN/A# "Fast" binary
9922292SN/Aif 'fast' in needed_envs:
9932292SN/A    makeEnv('fast', '.fo', strip = True,
9942292SN/A            CCFLAGS = Split(ccflags['fast']),
9952292SN/A            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'])
9962292SN/A
9972292SN/A# Profiled binary
9982292SN/Aif 'prof' in needed_envs:
9991061SN/A    makeEnv('prof', '.po',
10002292SN/A            CCFLAGS = Split(ccflags['prof']),
10011061SN/A            CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
10021061SN/A            LINKFLAGS = '-pg')
10031060SN/A
10041060SN/AReturn('envList')
10052316SN/A