SConscript revision 11542
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# Redistribution and use in source and binary forms, with or without
7955SN/A# modification, are permitted provided that the following conditions are
8955SN/A# met: redistributions of source code must retain the above copyright
9955SN/A# notice, this list of conditions and the following disclaimer;
10955SN/A# redistributions in binary form must reproduce the above copyright
11955SN/A# notice, this list of conditions and the following disclaimer in the
12955SN/A# documentation and/or other materials provided with the distribution;
13955SN/A# neither the name of the copyright holders nor the names of its
14955SN/A# contributors may be used to endorse or promote products derived from
15955SN/A# this software without specific prior written permission.
16955SN/A#
17955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
20955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
21955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
22955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
23955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
282665Ssaidi@eecs.umich.edu#
294762Snate@binkert.org# Authors: Nathan Binkert
30955SN/A
315522Snate@binkert.orgimport array
326143Snate@binkert.orgimport bisect
334762Snate@binkert.orgimport imp
345522Snate@binkert.orgimport marshal
35955SN/Aimport os
365522Snate@binkert.orgimport re
37955SN/Aimport sys
385522Snate@binkert.orgimport zlib
394202Sbinkertn@umich.edu
405742Snate@binkert.orgfrom os.path import basename, dirname, exists, isdir, isfile, join as joinpath
41955SN/A
424381Sbinkertn@umich.eduimport SCons
434381Sbinkertn@umich.edu
448334Snate@binkert.org# This file defines how to build a particular configuration of gem5
45955SN/A# based on variable settings in the 'env' build environment.
46955SN/A
474202Sbinkertn@umich.eduImport('*')
48955SN/A
494382Sbinkertn@umich.edu# Children need to see the environment
504382Sbinkertn@umich.eduExport('env')
514382Sbinkertn@umich.edu
526654Snate@binkert.orgbuild_env = [(opt, env[opt]) for opt in export_vars]
535517Snate@binkert.org
548614Sgblack@eecs.umich.edufrom m5.util import code_formatter, compareVersions
557674Snate@binkert.org
566143Snate@binkert.org########################################################################
576143Snate@binkert.org# Code for adding source files of various types
586143Snate@binkert.org#
598233Snate@binkert.org# When specifying a source file of some type, a set of guards can be
608233Snate@binkert.org# specified for that file.  When get() is used to find the files, if
618233Snate@binkert.org# get specifies a set of filters, only files that match those filters
628233Snate@binkert.org# will be accepted (unspecified filters on files are assumed to be
638233Snate@binkert.org# false).  Current filters are:
648334Snate@binkert.org#     main -- specifies the gem5 main() function
658334Snate@binkert.org#     skip_lib -- do not put this file into the gem5 library
668233Snate@binkert.org#     skip_no_python -- do not put this file into a no_python library
678233Snate@binkert.org#       as it embeds compiled Python
688233Snate@binkert.org#     <unittest> -- unit tests use filters based on the unit test name
698233Snate@binkert.org#
708233Snate@binkert.org# A parent can now be specified for a source file and default filter
718233Snate@binkert.org# values will be retrieved recursively from parents (children override
726143Snate@binkert.org# parents).
738233Snate@binkert.org#
748233Snate@binkert.orgclass SourceMeta(type):
758233Snate@binkert.org    '''Meta class for source files that keeps track of all files of a
766143Snate@binkert.org    particular type and has a get function for finding all functions
776143Snate@binkert.org    of a certain type that match a set of guards'''
786143Snate@binkert.org    def __init__(cls, name, bases, dict):
796143Snate@binkert.org        super(SourceMeta, cls).__init__(name, bases, dict)
808233Snate@binkert.org        cls.all = []
818233Snate@binkert.org
828233Snate@binkert.org    def get(cls, **guards):
836143Snate@binkert.org        '''Find all files that match the specified guards.  If a source
848233Snate@binkert.org        file does not specify a flag, the default is False'''
858233Snate@binkert.org        for src in cls.all:
868233Snate@binkert.org            for flag,value in guards.iteritems():
878233Snate@binkert.org                # if the flag is found and has a different value, skip
886143Snate@binkert.org                # this file
896143Snate@binkert.org                if src.all_guards.get(flag, False) != value:
906143Snate@binkert.org                    break
914762Snate@binkert.org            else:
926143Snate@binkert.org                yield src
938233Snate@binkert.org
948233Snate@binkert.orgclass SourceFile(object):
958233Snate@binkert.org    '''Base object that encapsulates the notion of a source file.
968233Snate@binkert.org    This includes, the source node, target node, various manipulations
978233Snate@binkert.org    of those.  A source file also specifies a set of guards which
986143Snate@binkert.org    describing which builds the source file applies to.  A parent can
998233Snate@binkert.org    also be specified to get default guards from'''
1008233Snate@binkert.org    __metaclass__ = SourceMeta
1018233Snate@binkert.org    def __init__(self, source, parent=None, **guards):
1028233Snate@binkert.org        self.guards = guards
1036143Snate@binkert.org        self.parent = parent
1046143Snate@binkert.org
1056143Snate@binkert.org        tnode = source
1066143Snate@binkert.org        if not isinstance(source, SCons.Node.FS.File):
1076143Snate@binkert.org            tnode = File(source)
1086143Snate@binkert.org
1096143Snate@binkert.org        self.tnode = tnode
1106143Snate@binkert.org        self.snode = tnode.srcnode()
1116143Snate@binkert.org
1127065Snate@binkert.org        for base in type(self).__mro__:
1136143Snate@binkert.org            if issubclass(base, SourceFile):
1148233Snate@binkert.org                base.all.append(self)
1158233Snate@binkert.org
1168233Snate@binkert.org    @property
1178233Snate@binkert.org    def filename(self):
1188233Snate@binkert.org        return str(self.tnode)
1198233Snate@binkert.org
1208233Snate@binkert.org    @property
1218233Snate@binkert.org    def dirname(self):
1228233Snate@binkert.org        return dirname(self.filename)
1238233Snate@binkert.org
1248233Snate@binkert.org    @property
1258233Snate@binkert.org    def basename(self):
1268233Snate@binkert.org        return basename(self.filename)
1278233Snate@binkert.org
1288233Snate@binkert.org    @property
1298233Snate@binkert.org    def extname(self):
1308233Snate@binkert.org        index = self.basename.rfind('.')
1318233Snate@binkert.org        if index <= 0:
1328233Snate@binkert.org            # dot files aren't extensions
1338233Snate@binkert.org            return self.basename, None
1348233Snate@binkert.org
1358233Snate@binkert.org        return self.basename[:index], self.basename[index+1:]
1368233Snate@binkert.org
1378233Snate@binkert.org    @property
1388233Snate@binkert.org    def all_guards(self):
1398233Snate@binkert.org        '''find all guards for this object getting default values
1408233Snate@binkert.org        recursively from its parents'''
1418233Snate@binkert.org        guards = {}
1428233Snate@binkert.org        if self.parent:
1438233Snate@binkert.org            guards.update(self.parent.guards)
1448233Snate@binkert.org        guards.update(self.guards)
1456143Snate@binkert.org        return guards
1466143Snate@binkert.org
1476143Snate@binkert.org    def __lt__(self, other): return self.filename < other.filename
1486143Snate@binkert.org    def __le__(self, other): return self.filename <= other.filename
1496143Snate@binkert.org    def __gt__(self, other): return self.filename > other.filename
1506143Snate@binkert.org    def __ge__(self, other): return self.filename >= other.filename
1519982Satgutier@umich.edu    def __eq__(self, other): return self.filename == other.filename
1526143Snate@binkert.org    def __ne__(self, other): return self.filename != other.filename
1536143Snate@binkert.org
1548945Ssteve.reinhardt@amd.com    @staticmethod
1558233Snate@binkert.org    def done():
1568233Snate@binkert.org        def disabled(cls, name, *ignored):
1576143Snate@binkert.org            raise RuntimeError("Additional SourceFile '%s'" % name,\
1588945Ssteve.reinhardt@amd.com                  "declared, but targets deps are already fixed.")
1596143Snate@binkert.org        SourceFile.__init__ = disabled
1606143Snate@binkert.org
1616143Snate@binkert.org
1626143Snate@binkert.orgclass Source(SourceFile):
1635522Snate@binkert.org    '''Add a c/c++ source file to the build'''
1646143Snate@binkert.org    def __init__(self, source, Werror=True, swig=False, **guards):
1656143Snate@binkert.org        '''specify the source file, and any guards'''
1666143Snate@binkert.org        super(Source, self).__init__(source, **guards)
1679982Satgutier@umich.edu
1688233Snate@binkert.org        self.Werror = Werror
1698233Snate@binkert.org        self.swig = swig
1708233Snate@binkert.org
1716143Snate@binkert.orgclass PySource(SourceFile):
1726143Snate@binkert.org    '''Add a python source file to the named package'''
1736143Snate@binkert.org    invalid_sym_char = re.compile('[^A-z0-9_]')
1746143Snate@binkert.org    modules = {}
1755522Snate@binkert.org    tnodes = {}
1765522Snate@binkert.org    symnames = {}
1775522Snate@binkert.org
1785522Snate@binkert.org    def __init__(self, package, source, **guards):
1795604Snate@binkert.org        '''specify the python package, the source file, and any guards'''
1805604Snate@binkert.org        super(PySource, self).__init__(source, **guards)
1816143Snate@binkert.org
1826143Snate@binkert.org        modname,ext = self.extname
1834762Snate@binkert.org        assert ext == 'py'
1844762Snate@binkert.org
1856143Snate@binkert.org        if package:
1866727Ssteve.reinhardt@amd.com            path = package.split('.')
1876727Ssteve.reinhardt@amd.com        else:
1886727Ssteve.reinhardt@amd.com            path = []
1894762Snate@binkert.org
1906143Snate@binkert.org        modpath = path[:]
1916143Snate@binkert.org        if modname != '__init__':
1926143Snate@binkert.org            modpath += [ modname ]
1936143Snate@binkert.org        modpath = '.'.join(modpath)
1946727Ssteve.reinhardt@amd.com
1956143Snate@binkert.org        arcpath = path + [ self.basename ]
1967674Snate@binkert.org        abspath = self.snode.abspath
1977674Snate@binkert.org        if not exists(abspath):
1985604Snate@binkert.org            abspath = self.tnode.abspath
1996143Snate@binkert.org
2006143Snate@binkert.org        self.package = package
2016143Snate@binkert.org        self.modname = modname
2024762Snate@binkert.org        self.modpath = modpath
2036143Snate@binkert.org        self.arcname = joinpath(*arcpath)
2044762Snate@binkert.org        self.abspath = abspath
2054762Snate@binkert.org        self.compiled = File(self.filename + 'c')
2064762Snate@binkert.org        self.cpp = File(self.filename + '.cc')
2076143Snate@binkert.org        self.symname = PySource.invalid_sym_char.sub('_', modpath)
2086143Snate@binkert.org
2094762Snate@binkert.org        PySource.modules[modpath] = self
2108233Snate@binkert.org        PySource.tnodes[self.tnode] = self
2118233Snate@binkert.org        PySource.symnames[self.symname] = self
2128233Snate@binkert.org
2138233Snate@binkert.orgclass SimObject(PySource):
2146143Snate@binkert.org    '''Add a SimObject python file as a python source object and add
2156143Snate@binkert.org    it to a list of sim object modules'''
2164762Snate@binkert.org
2176143Snate@binkert.org    fixed = False
2184762Snate@binkert.org    modnames = []
2196143Snate@binkert.org
2204762Snate@binkert.org    def __init__(self, source, **guards):
2216143Snate@binkert.org        '''Specify the source file and any guards (automatically in
2228233Snate@binkert.org        the m5.objects package)'''
2238233Snate@binkert.org        super(SimObject, self).__init__('m5.objects', source, **guards)
2248233Snate@binkert.org        if self.fixed:
2256143Snate@binkert.org            raise AttributeError, "Too late to call SimObject now."
2266143Snate@binkert.org
2276143Snate@binkert.org        bisect.insort_right(SimObject.modnames, self.modname)
2286143Snate@binkert.org
2296143Snate@binkert.orgclass SwigSource(SourceFile):
2306143Snate@binkert.org    '''Add a swig file to build'''
2316143Snate@binkert.org
2326143Snate@binkert.org    def __init__(self, package, source, **guards):
2338233Snate@binkert.org        '''Specify the python package, the source file, and any guards'''
2348233Snate@binkert.org        super(SwigSource, self).__init__(source, skip_no_python=True, **guards)
235955SN/A
2369396Sandreas.hansson@arm.com        modname,ext = self.extname
2379396Sandreas.hansson@arm.com        assert ext == 'i'
2389396Sandreas.hansson@arm.com
2399396Sandreas.hansson@arm.com        self.module = modname
2409396Sandreas.hansson@arm.com        cc_file = joinpath(self.dirname, modname + '_wrap.cc')
2419396Sandreas.hansson@arm.com        py_file = joinpath(self.dirname, modname + '.py')
2429396Sandreas.hansson@arm.com
2439396Sandreas.hansson@arm.com        self.cc_source = Source(cc_file, swig=True, parent=self, **guards)
2449396Sandreas.hansson@arm.com        self.py_source = PySource(package, py_file, parent=self, **guards)
2459396Sandreas.hansson@arm.com
2469396Sandreas.hansson@arm.comclass ProtoBuf(SourceFile):
2479396Sandreas.hansson@arm.com    '''Add a Protocol Buffer to build'''
2489396Sandreas.hansson@arm.com
2499930Sandreas.hansson@arm.com    def __init__(self, source, **guards):
2509930Sandreas.hansson@arm.com        '''Specify the source file, and any guards'''
2519396Sandreas.hansson@arm.com        super(ProtoBuf, self).__init__(source, **guards)
2528235Snate@binkert.org
2538235Snate@binkert.org        # Get the file name and the extension
2546143Snate@binkert.org        modname,ext = self.extname
2558235Snate@binkert.org        assert ext == 'proto'
2569003SAli.Saidi@ARM.com
2578235Snate@binkert.org        # Currently, we stick to generating the C++ headers, so we
2588235Snate@binkert.org        # only need to track the source and header.
2598235Snate@binkert.org        self.cc_file = File(modname + '.pb.cc')
2608235Snate@binkert.org        self.hh_file = File(modname + '.pb.h')
2618235Snate@binkert.org
2628235Snate@binkert.orgclass UnitTest(object):
2638235Snate@binkert.org    '''Create a UnitTest'''
2648235Snate@binkert.org
2658235Snate@binkert.org    all = []
2668235Snate@binkert.org    def __init__(self, target, *sources, **kwargs):
2678235Snate@binkert.org        '''Specify the target name and any sources.  Sources that are
2688235Snate@binkert.org        not SourceFiles are evalued with Source().  All files are
2698235Snate@binkert.org        guarded with a guard of the same name as the UnitTest
2708235Snate@binkert.org        target.'''
2719003SAli.Saidi@ARM.com
2728235Snate@binkert.org        srcs = []
2735584Snate@binkert.org        for src in sources:
2744382Sbinkertn@umich.edu            if not isinstance(src, SourceFile):
2754202Sbinkertn@umich.edu                src = Source(src, skip_lib=True)
2764382Sbinkertn@umich.edu            src.guards[target] = True
2774382Sbinkertn@umich.edu            srcs.append(src)
2784382Sbinkertn@umich.edu
2799396Sandreas.hansson@arm.com        self.sources = srcs
2805584Snate@binkert.org        self.target = target
2814382Sbinkertn@umich.edu        self.main = kwargs.get('main', False)
2824382Sbinkertn@umich.edu        UnitTest.all.append(self)
2834382Sbinkertn@umich.edu
2848232Snate@binkert.org# Children should have access
2855192Ssaidi@eecs.umich.eduExport('Source')
2868232Snate@binkert.orgExport('PySource')
2878232Snate@binkert.orgExport('SimObject')
2888232Snate@binkert.orgExport('SwigSource')
2895192Ssaidi@eecs.umich.eduExport('ProtoBuf')
2908232Snate@binkert.orgExport('UnitTest')
2915192Ssaidi@eecs.umich.edu
2925799Snate@binkert.org########################################################################
2938232Snate@binkert.org#
2945192Ssaidi@eecs.umich.edu# Debug Flags
2955192Ssaidi@eecs.umich.edu#
2965192Ssaidi@eecs.umich.edudebug_flags = {}
2978232Snate@binkert.orgdef DebugFlag(name, desc=None):
2985192Ssaidi@eecs.umich.edu    if name in debug_flags:
2998232Snate@binkert.org        raise AttributeError, "Flag %s already specified" % name
3005192Ssaidi@eecs.umich.edu    debug_flags[name] = (name, (), desc)
3015192Ssaidi@eecs.umich.edu
3025192Ssaidi@eecs.umich.edudef CompoundFlag(name, flags, desc=None):
3035192Ssaidi@eecs.umich.edu    if name in debug_flags:
3044382Sbinkertn@umich.edu        raise AttributeError, "Flag %s already specified" % name
3054382Sbinkertn@umich.edu
3064382Sbinkertn@umich.edu    compound = tuple(flags)
3072667Sstever@eecs.umich.edu    debug_flags[name] = (name, compound, desc)
3082667Sstever@eecs.umich.edu
3092667Sstever@eecs.umich.eduExport('DebugFlag')
3102667Sstever@eecs.umich.eduExport('CompoundFlag')
3112667Sstever@eecs.umich.edu
3122667Sstever@eecs.umich.edu########################################################################
3135742Snate@binkert.org#
3145742Snate@binkert.org# Set some compiler variables
3155742Snate@binkert.org#
3165793Snate@binkert.org
3178334Snate@binkert.org# Include file paths are rooted in this directory.  SCons will
3185793Snate@binkert.org# automatically expand '.' to refer to both the source directory and
3195793Snate@binkert.org# the corresponding build directory to pick up generated include
3205793Snate@binkert.org# files.
3214382Sbinkertn@umich.eduenv.Append(CPPPATH=Dir('.'))
3224762Snate@binkert.org
3235344Sstever@gmail.comfor extra_dir in extras_dir_list:
3244382Sbinkertn@umich.edu    env.Append(CPPPATH=Dir(extra_dir))
3255341Sstever@gmail.com
3265742Snate@binkert.org# Workaround for bug in SCons version > 0.97d20071212
3275742Snate@binkert.org# Scons bug id: 2006 gem5 Bug id: 308
3285742Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3295742Snate@binkert.org    Dir(root[len(base_dir) + 1:])
3305742Snate@binkert.org
3314762Snate@binkert.org########################################################################
3325742Snate@binkert.org#
3335742Snate@binkert.org# Walk the tree and execute all SConscripts in subdirectories
3347722Sgblack@eecs.umich.edu#
3355742Snate@binkert.org
3365742Snate@binkert.orghere = Dir('.').srcnode().abspath
3375742Snate@binkert.orgfor root, dirs, files in os.walk(base_dir, topdown=True):
3389930Sandreas.hansson@arm.com    if root == here:
3399930Sandreas.hansson@arm.com        # we don't want to recurse back into this SConscript
3409930Sandreas.hansson@arm.com        continue
3419930Sandreas.hansson@arm.com
3429930Sandreas.hansson@arm.com    if 'SConscript' in files:
3435742Snate@binkert.org        build_dir = joinpath(env['BUILDDIR'], root[len(base_dir) + 1:])
3448242Sbradley.danofsky@amd.com        SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3458242Sbradley.danofsky@amd.com
3468242Sbradley.danofsky@amd.comfor extra_dir in extras_dir_list:
3478242Sbradley.danofsky@amd.com    prefix_len = len(dirname(extra_dir)) + 1
3485341Sstever@gmail.com
3495742Snate@binkert.org    # Also add the corresponding build directory to pick up generated
3507722Sgblack@eecs.umich.edu    # include files.
3514773Snate@binkert.org    env.Append(CPPPATH=Dir(joinpath(env['BUILDDIR'], extra_dir[prefix_len:])))
3526108Snate@binkert.org
3531858SN/A    for root, dirs, files in os.walk(extra_dir, topdown=True):
3541085SN/A        # if build lives in the extras directory, don't walk down it
3556658Snate@binkert.org        if 'build' in dirs:
3566658Snate@binkert.org            dirs.remove('build')
3577673Snate@binkert.org
3586658Snate@binkert.org        if 'SConscript' in files:
3596658Snate@binkert.org            build_dir = joinpath(env['BUILDDIR'], root[prefix_len:])
3606658Snate@binkert.org            SConscript(joinpath(root, 'SConscript'), variant_dir=build_dir)
3616658Snate@binkert.org
3626658Snate@binkert.orgfor opt in export_vars:
3636658Snate@binkert.org    env.ConfigFile(opt)
3646658Snate@binkert.org
3657673Snate@binkert.orgdef makeTheISA(source, target, env):
3667673Snate@binkert.org    isas = [ src.get_contents() for src in source ]
3677673Snate@binkert.org    target_isa = env['TARGET_ISA']
3687673Snate@binkert.org    def define(isa):
3697673Snate@binkert.org        return isa.upper() + '_ISA'
3707673Snate@binkert.org
3717673Snate@binkert.org    def namespace(isa):
3726658Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
3737673Snate@binkert.org
3747673Snate@binkert.org
3757673Snate@binkert.org    code = code_formatter()
3767673Snate@binkert.org    code('''\
3777673Snate@binkert.org#ifndef __CONFIG_THE_ISA_HH__
3787673Snate@binkert.org#define __CONFIG_THE_ISA_HH__
3799048SAli.Saidi@ARM.com
3807673Snate@binkert.org''')
3817673Snate@binkert.org
3827673Snate@binkert.org    # create defines for the preprocessing and compile-time determination
3837673Snate@binkert.org    for i,isa in enumerate(isas):
3846658Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
3857756SAli.Saidi@ARM.com    code()
3867816Ssteve.reinhardt@amd.com
3876658Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
3884382Sbinkertn@umich.edu    # reuse the same name as the namespaces
3894382Sbinkertn@umich.edu    code('enum class Arch {')
3904762Snate@binkert.org    for i,isa in enumerate(isas):
3914762Snate@binkert.org        if i + 1 == len(isas):
3924762Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
3936654Snate@binkert.org        else:
3946654Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
3955517Snate@binkert.org    code('};')
3965517Snate@binkert.org
3975517Snate@binkert.org    code('''
3985517Snate@binkert.org
3995517Snate@binkert.org#define THE_ISA ${{define(target_isa)}}
4005517Snate@binkert.org#define TheISA ${{namespace(target_isa)}}
4015517Snate@binkert.org#define THE_ISA_STR "${{target_isa}}"
4025517Snate@binkert.org
4035517Snate@binkert.org#endif // __CONFIG_THE_ISA_HH__''')
4045517Snate@binkert.org
4055517Snate@binkert.org    code.write(str(target[0]))
4065517Snate@binkert.org
4075517Snate@binkert.orgenv.Command('config/the_isa.hh', map(Value, all_isa_list),
4085517Snate@binkert.org            MakeAction(makeTheISA, Transform("CFG ISA", 0)))
4095517Snate@binkert.org
4105517Snate@binkert.orgdef makeTheGPUISA(source, target, env):
4115517Snate@binkert.org    isas = [ src.get_contents() for src in source ]
4126654Snate@binkert.org    target_gpu_isa = env['TARGET_GPU_ISA']
4135517Snate@binkert.org    def define(isa):
4145517Snate@binkert.org        return isa.upper() + '_ISA'
4155517Snate@binkert.org
4165517Snate@binkert.org    def namespace(isa):
4175517Snate@binkert.org        return isa[0].upper() + isa[1:].lower() + 'ISA'
4185517Snate@binkert.org
4195517Snate@binkert.org
4205517Snate@binkert.org    code = code_formatter()
4216143Snate@binkert.org    code('''\
4226654Snate@binkert.org#ifndef __CONFIG_THE_GPU_ISA_HH__
4235517Snate@binkert.org#define __CONFIG_THE_GPU_ISA_HH__
4245517Snate@binkert.org
4255517Snate@binkert.org''')
4265517Snate@binkert.org
4275517Snate@binkert.org    # create defines for the preprocessing and compile-time determination
4285517Snate@binkert.org    for i,isa in enumerate(isas):
4295517Snate@binkert.org        code('#define $0 $1', define(isa), i + 1)
4305517Snate@binkert.org    code()
4315517Snate@binkert.org
4325517Snate@binkert.org    # create an enum for any run-time determination of the ISA, we
4335517Snate@binkert.org    # reuse the same name as the namespaces
4345517Snate@binkert.org    code('enum class GPUArch {')
4355517Snate@binkert.org    for i,isa in enumerate(isas):
4365517Snate@binkert.org        if i + 1 == len(isas):
4376654Snate@binkert.org            code('  $0 = $1', namespace(isa), define(isa))
4386654Snate@binkert.org        else:
4395517Snate@binkert.org            code('  $0 = $1,', namespace(isa), define(isa))
4405517Snate@binkert.org    code('};')
4416143Snate@binkert.org
4426143Snate@binkert.org    code('''
4436143Snate@binkert.org
4446727Ssteve.reinhardt@amd.com#define THE_GPU_ISA ${{define(target_gpu_isa)}}
4455517Snate@binkert.org#define TheGpuISA ${{namespace(target_gpu_isa)}}
4466727Ssteve.reinhardt@amd.com#define THE_GPU_ISA_STR "${{target_gpu_isa}}"
4475517Snate@binkert.org
4485517Snate@binkert.org#endif // __CONFIG_THE_GPU_ISA_HH__''')
4495517Snate@binkert.org
4506654Snate@binkert.org    code.write(str(target[0]))
4516654Snate@binkert.org
4527673Snate@binkert.orgenv.Command('config/the_gpu_isa.hh', map(Value, all_gpu_isa_list),
4536654Snate@binkert.org            MakeAction(makeTheGPUISA, Transform("CFG ISA", 0)))
4546654Snate@binkert.org
4556654Snate@binkert.org########################################################################
4566654Snate@binkert.org#
4575517Snate@binkert.org# Prevent any SimObjects from being added after this point, they
4585517Snate@binkert.org# should all have been added in the SConscripts above
4595517Snate@binkert.org#
4606143Snate@binkert.orgSimObject.fixed = True
4615517Snate@binkert.org
4624762Snate@binkert.orgclass DictImporter(object):
4635517Snate@binkert.org    '''This importer takes a dictionary of arbitrary module names that
4645517Snate@binkert.org    map to arbitrary filenames.'''
4656143Snate@binkert.org    def __init__(self, modules):
4666143Snate@binkert.org        self.modules = modules
4675517Snate@binkert.org        self.installed = set()
4685517Snate@binkert.org
4695517Snate@binkert.org    def __del__(self):
4705517Snate@binkert.org        self.unload()
4715517Snate@binkert.org
4725517Snate@binkert.org    def unload(self):
4735517Snate@binkert.org        import sys
4745517Snate@binkert.org        for module in self.installed:
4755517Snate@binkert.org            del sys.modules[module]
4769338SAndreas.Sandberg@arm.com        self.installed = set()
4779338SAndreas.Sandberg@arm.com
4789338SAndreas.Sandberg@arm.com    def find_module(self, fullname, path):
4799338SAndreas.Sandberg@arm.com        if fullname == 'm5.defines':
4809338SAndreas.Sandberg@arm.com            return self
4819338SAndreas.Sandberg@arm.com
4828596Ssteve.reinhardt@amd.com        if fullname == 'm5.objects':
4838596Ssteve.reinhardt@amd.com            return self
4848596Ssteve.reinhardt@amd.com
4858596Ssteve.reinhardt@amd.com        if fullname.startswith('m5.internal'):
4868596Ssteve.reinhardt@amd.com            return None
4878596Ssteve.reinhardt@amd.com
4888596Ssteve.reinhardt@amd.com        source = self.modules.get(fullname, None)
4896143Snate@binkert.org        if source is not None and fullname.startswith('m5.objects'):
4905517Snate@binkert.org            return self
4916654Snate@binkert.org
4926654Snate@binkert.org        return None
4936654Snate@binkert.org
4946654Snate@binkert.org    def load_module(self, fullname):
4956654Snate@binkert.org        mod = imp.new_module(fullname)
4966654Snate@binkert.org        sys.modules[fullname] = mod
4975517Snate@binkert.org        self.installed.add(fullname)
4985517Snate@binkert.org
4995517Snate@binkert.org        mod.__loader__ = self
5008596Ssteve.reinhardt@amd.com        if fullname == 'm5.objects':
5018596Ssteve.reinhardt@amd.com            mod.__path__ = fullname.split('.')
5024762Snate@binkert.org            return mod
5034762Snate@binkert.org
5044762Snate@binkert.org        if fullname == 'm5.defines':
5054762Snate@binkert.org            mod.__dict__['buildEnv'] = m5.util.SmartDict(build_env)
5064762Snate@binkert.org            return mod
5074762Snate@binkert.org
5087675Snate@binkert.org        source = self.modules[fullname]
5094762Snate@binkert.org        if source.modname == '__init__':
5104762Snate@binkert.org            mod.__path__ = source.modpath
5114762Snate@binkert.org        mod.__file__ = source.abspath
5124762Snate@binkert.org
5134382Sbinkertn@umich.edu        exec file(source.abspath, 'r') in mod.__dict__
5144382Sbinkertn@umich.edu
5155517Snate@binkert.org        return mod
5166654Snate@binkert.org
5175517Snate@binkert.orgimport m5.SimObject
5188126Sgblack@eecs.umich.eduimport m5.params
5196654Snate@binkert.orgfrom m5.util import code_formatter
5207673Snate@binkert.org
5216654Snate@binkert.orgm5.SimObject.clear()
5226654Snate@binkert.orgm5.params.clear()
5236654Snate@binkert.org
5246654Snate@binkert.org# install the python importer so we can grab stuff from the source
5256654Snate@binkert.org# tree itself.  We can't have SimObjects added after this point or
5266654Snate@binkert.org# else we won't know about them for the rest of the stuff.
5276654Snate@binkert.orgimporter = DictImporter(PySource.modules)
5286669Snate@binkert.orgsys.meta_path[0:0] = [ importer ]
5296669Snate@binkert.org
5306669Snate@binkert.org# import all sim objects so we can populate the all_objects list
5316669Snate@binkert.org# make sure that we're working with a list, then let's sort it
5326669Snate@binkert.orgfor modname in SimObject.modnames:
5336669Snate@binkert.org    exec('from m5.objects import %s' % modname)
5346654Snate@binkert.org
5357673Snate@binkert.org# we need to unload all of the currently imported modules so that they
5365517Snate@binkert.org# will be re-imported the next time the sconscript is run
5378126Sgblack@eecs.umich.eduimporter.unload()
5385798Snate@binkert.orgsys.meta_path.remove(importer)
5397756SAli.Saidi@ARM.com
5407816Ssteve.reinhardt@amd.comsim_objects = m5.SimObject.allClasses
5415798Snate@binkert.orgall_enums = m5.params.allEnums
5425798Snate@binkert.org
5435517Snate@binkert.orgif m5.SimObject.noCxxHeader:
5445517Snate@binkert.org    print >> sys.stderr, \
5457673Snate@binkert.org        "warning: At least one SimObject lacks a header specification. " \
5465517Snate@binkert.org        "This can cause unexpected results in the generated SWIG " \
5475517Snate@binkert.org        "wrappers."
5487673Snate@binkert.org
5497673Snate@binkert.org# Find param types that need to be explicitly wrapped with swig.
5505517Snate@binkert.org# These will be recognized because the ParamDesc will have a
5515798Snate@binkert.org# swig_decl() method.  Most param types are based on types that don't
5525798Snate@binkert.org# need this, either because they're based on native types (like Int)
5538333Snate@binkert.org# or because they're SimObjects (which get swigged independently).
5547816Ssteve.reinhardt@amd.com# For now the only things handled here are VectorParam types.
5555798Snate@binkert.orgparams_to_swig = {}
5565798Snate@binkert.orgfor name,obj in sorted(sim_objects.iteritems()):
5574762Snate@binkert.org    for param in obj._params.local.values():
5584762Snate@binkert.org        # load the ptype attribute now because it depends on the
5594762Snate@binkert.org        # current version of SimObject.allClasses, but when scons
5604762Snate@binkert.org        # actually uses the value, all versions of
5614762Snate@binkert.org        # SimObject.allClasses will have been loaded
5628596Ssteve.reinhardt@amd.com        param.ptype
5635517Snate@binkert.org
5645517Snate@binkert.org        if not hasattr(param, 'swig_decl'):
5655517Snate@binkert.org            continue
5665517Snate@binkert.org        pname = param.ptype_str
5675517Snate@binkert.org        if pname not in params_to_swig:
5687673Snate@binkert.org            params_to_swig[pname] = param
5698596Ssteve.reinhardt@amd.com
5707673Snate@binkert.org########################################################################
5715517Snate@binkert.org#
5728596Ssteve.reinhardt@amd.com# calculate extra dependencies
5735517Snate@binkert.org#
5745517Snate@binkert.orgmodule_depends = ["m5", "m5.SimObject", "m5.params"]
5755517Snate@binkert.orgdepends = [ PySource.modules[dep].snode for dep in module_depends ]
5768596Ssteve.reinhardt@amd.comdepends.sort(key = lambda x: x.name)
5775517Snate@binkert.org
5787673Snate@binkert.org########################################################################
5797673Snate@binkert.org#
5807673Snate@binkert.org# Commands for the basic automatically generated python files
5815517Snate@binkert.org#
5825517Snate@binkert.org
5835517Snate@binkert.org# Generate Python file containing a dict specifying the current
5845517Snate@binkert.org# buildEnv flags.
5855517Snate@binkert.orgdef makeDefinesPyFile(target, source, env):
5865517Snate@binkert.org    build_env = source[0].get_contents()
5875517Snate@binkert.org
5887673Snate@binkert.org    code = code_formatter()
5897673Snate@binkert.org    code("""
5907673Snate@binkert.orgimport m5.internal
5915517Snate@binkert.orgimport m5.util
5928596Ssteve.reinhardt@amd.com
5935517Snate@binkert.orgbuildEnv = m5.util.SmartDict($build_env)
5945517Snate@binkert.org
5955517Snate@binkert.orgcompileDate = m5.internal.core.compileDate
5965517Snate@binkert.org_globals = globals()
5975517Snate@binkert.orgfor key,val in m5.internal.core.__dict__.iteritems():
5987673Snate@binkert.org    if key.startswith('flag_'):
5997673Snate@binkert.org        flag = key[5:]
6007673Snate@binkert.org        _globals[flag] = val
6015517Snate@binkert.orgdel _globals
6028596Ssteve.reinhardt@amd.com""")
6037675Snate@binkert.org    code.write(target[0].abspath)
6047675Snate@binkert.org
6057675Snate@binkert.orgdefines_info = Value(build_env)
6067675Snate@binkert.org# Generate a file with all of the compile options in it
6077675Snate@binkert.orgenv.Command('python/m5/defines.py', defines_info,
6087675Snate@binkert.org            MakeAction(makeDefinesPyFile, Transform("DEFINES", 0)))
6098596Ssteve.reinhardt@amd.comPySource('m5', 'python/m5/defines.py')
6107675Snate@binkert.org
6117675Snate@binkert.org# Generate python file containing info about the M5 source code
6128596Ssteve.reinhardt@amd.comdef makeInfoPyFile(target, source, env):
6138596Ssteve.reinhardt@amd.com    code = code_formatter()
6148596Ssteve.reinhardt@amd.com    for src in source:
6158596Ssteve.reinhardt@amd.com        data = ''.join(file(src.srcnode().abspath, 'r').xreadlines())
6168596Ssteve.reinhardt@amd.com        code('$src = ${{repr(data)}}')
6178596Ssteve.reinhardt@amd.com    code.write(str(target[0]))
6188596Ssteve.reinhardt@amd.com
6198596Ssteve.reinhardt@amd.com# Generate a file that wraps the basic top level files
6208596Ssteve.reinhardt@amd.comenv.Command('python/m5/info.py',
6214762Snate@binkert.org            [ '#/COPYING', '#/LICENSE', '#/README', ],
6226143Snate@binkert.org            MakeAction(makeInfoPyFile, Transform("INFO")))
6236143Snate@binkert.orgPySource('m5', 'python/m5/info.py')
6246143Snate@binkert.org
6254762Snate@binkert.org########################################################################
6264762Snate@binkert.org#
6274762Snate@binkert.org# Create all of the SimObject param headers and enum headers
6287756SAli.Saidi@ARM.com#
6298596Ssteve.reinhardt@amd.com
6304762Snate@binkert.orgdef createSimObjectParamStruct(target, source, env):
6314762Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6328596Ssteve.reinhardt@amd.com
6335463Snate@binkert.org    name = str(source[0].get_contents())
6348596Ssteve.reinhardt@amd.com    obj = sim_objects[name]
6358596Ssteve.reinhardt@amd.com
6365463Snate@binkert.org    code = code_formatter()
6377756SAli.Saidi@ARM.com    obj.cxx_param_decl(code)
6388596Ssteve.reinhardt@amd.com    code.write(target[0].abspath)
6394762Snate@binkert.org
6407677Snate@binkert.orgdef createSimObjectCxxConfig(is_header):
6414762Snate@binkert.org    def body(target, source, env):
6424762Snate@binkert.org        assert len(target) == 1 and len(source) == 1
6436143Snate@binkert.org
6446143Snate@binkert.org        name = str(source[0].get_contents())
6456143Snate@binkert.org        obj = sim_objects[name]
6464762Snate@binkert.org
6474762Snate@binkert.org        code = code_formatter()
6487756SAli.Saidi@ARM.com        obj.cxx_config_param_file(code, is_header)
6497816Ssteve.reinhardt@amd.com        code.write(target[0].abspath)
6504762Snate@binkert.org    return body
6514762Snate@binkert.org
6524762Snate@binkert.orgdef createParamSwigWrapper(target, source, env):
6534762Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6547756SAli.Saidi@ARM.com
6558596Ssteve.reinhardt@amd.com    name = str(source[0].get_contents())
6564762Snate@binkert.org    param = params_to_swig[name]
6574762Snate@binkert.org
6587677Snate@binkert.org    code = code_formatter()
6597756SAli.Saidi@ARM.com    param.swig_decl(code)
6608596Ssteve.reinhardt@amd.com    code.write(target[0].abspath)
6617675Snate@binkert.org
6627677Snate@binkert.orgdef createEnumStrings(target, source, env):
6635517Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6648596Ssteve.reinhardt@amd.com
6659248SAndreas.Sandberg@arm.com    name = str(source[0].get_contents())
6669248SAndreas.Sandberg@arm.com    obj = all_enums[name]
6679248SAndreas.Sandberg@arm.com
6689248SAndreas.Sandberg@arm.com    code = code_formatter()
6698596Ssteve.reinhardt@amd.com    obj.cxx_def(code)
6708596Ssteve.reinhardt@amd.com    code.write(target[0].abspath)
6718596Ssteve.reinhardt@amd.com
6729248SAndreas.Sandberg@arm.comdef createEnumDecls(target, source, env):
6738596Ssteve.reinhardt@amd.com    assert len(target) == 1 and len(source) == 1
6744762Snate@binkert.org
6757674Snate@binkert.org    name = str(source[0].get_contents())
6767674Snate@binkert.org    obj = all_enums[name]
6777674Snate@binkert.org
6787674Snate@binkert.org    code = code_formatter()
6797674Snate@binkert.org    obj.cxx_decl(code)
6807674Snate@binkert.org    code.write(target[0].abspath)
6817674Snate@binkert.org
6827674Snate@binkert.orgdef createEnumSwigWrapper(target, source, env):
6837674Snate@binkert.org    assert len(target) == 1 and len(source) == 1
6847674Snate@binkert.org
6857674Snate@binkert.org    name = str(source[0].get_contents())
6867674Snate@binkert.org    obj = all_enums[name]
6877674Snate@binkert.org
6887674Snate@binkert.org    code = code_formatter()
6897674Snate@binkert.org    obj.swig_decl(code)
6904762Snate@binkert.org    code.write(target[0].abspath)
6916143Snate@binkert.org
6926143Snate@binkert.orgdef createSimObjectSwigWrapper(target, source, env):
6937756SAli.Saidi@ARM.com    name = source[0].get_contents()
6947816Ssteve.reinhardt@amd.com    obj = sim_objects[name]
6958235Snate@binkert.org
6968596Ssteve.reinhardt@amd.com    code = code_formatter()
6977756SAli.Saidi@ARM.com    obj.swig_decl(code)
6987816Ssteve.reinhardt@amd.com    code.write(target[0].abspath)
6998235Snate@binkert.org
7004382Sbinkertn@umich.edu# dummy target for generated code
7019396Sandreas.hansson@arm.com# we start out with all the Source files so they get copied to build/*/ also.
7029396Sandreas.hansson@arm.comSWIG = env.Dummy('swig', [s.tnode for s in Source.get()])
7039396Sandreas.hansson@arm.com
7049396Sandreas.hansson@arm.com# Generate all of the SimObject param C++ struct header files
7059396Sandreas.hansson@arm.comparams_hh_files = []
7069396Sandreas.hansson@arm.comfor name,simobj in sorted(sim_objects.iteritems()):
7079396Sandreas.hansson@arm.com    py_source = PySource.modules[simobj.__module__]
7089396Sandreas.hansson@arm.com    extra_deps = [ py_source.tnode ]
7099396Sandreas.hansson@arm.com
7109396Sandreas.hansson@arm.com    hh_file = File('params/%s.hh' % name)
7119396Sandreas.hansson@arm.com    params_hh_files.append(hh_file)
7129396Sandreas.hansson@arm.com    env.Command(hh_file, Value(name),
7139396Sandreas.hansson@arm.com                MakeAction(createSimObjectParamStruct, Transform("SO PARAM")))
7149396Sandreas.hansson@arm.com    env.Depends(hh_file, depends + extra_deps)
7159396Sandreas.hansson@arm.com    env.Depends(SWIG, hh_file)
7169396Sandreas.hansson@arm.com
7179396Sandreas.hansson@arm.com# C++ parameter description files
7189396Sandreas.hansson@arm.comif GetOption('with_cxx_config'):
7198232Snate@binkert.org    for name,simobj in sorted(sim_objects.iteritems()):
7208232Snate@binkert.org        py_source = PySource.modules[simobj.__module__]
7218232Snate@binkert.org        extra_deps = [ py_source.tnode ]
7228232Snate@binkert.org
7238232Snate@binkert.org        cxx_config_hh_file = File('cxx_config/%s.hh' % name)
7246229Snate@binkert.org        cxx_config_cc_file = File('cxx_config/%s.cc' % name)
7258232Snate@binkert.org        env.Command(cxx_config_hh_file, Value(name),
7268232Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(True),
7278232Snate@binkert.org                    Transform("CXXCPRHH")))
7286229Snate@binkert.org        env.Command(cxx_config_cc_file, Value(name),
7297673Snate@binkert.org                    MakeAction(createSimObjectCxxConfig(False),
7305517Snate@binkert.org                    Transform("CXXCPRCC")))
7315517Snate@binkert.org        env.Depends(cxx_config_hh_file, depends + extra_deps +
7327673Snate@binkert.org                    [File('params/%s.hh' % name), File('sim/cxx_config.hh')])
7335517Snate@binkert.org        env.Depends(cxx_config_cc_file, depends + extra_deps +
7345517Snate@binkert.org                    [cxx_config_hh_file])
7355517Snate@binkert.org        Source(cxx_config_cc_file)
7365517Snate@binkert.org
7378232Snate@binkert.org    cxx_config_init_cc_file = File('cxx_config/init.cc')
7387673Snate@binkert.org
7397673Snate@binkert.org    def createCxxConfigInitCC(target, source, env):
7408232Snate@binkert.org        assert len(target) == 1 and len(source) == 1
7418232Snate@binkert.org
7428232Snate@binkert.org        code = code_formatter()
7438232Snate@binkert.org
7447673Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
7455517Snate@binkert.org            if not hasattr(simobj, 'abstract') or not simobj.abstract:
7468232Snate@binkert.org                code('#include "cxx_config/${name}.hh"')
7478232Snate@binkert.org        code()
7488232Snate@binkert.org        code('void cxxConfigInit()')
7498232Snate@binkert.org        code('{')
7507673Snate@binkert.org        code.indent()
7518232Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems()):
7528232Snate@binkert.org            not_abstract = not hasattr(simobj, 'abstract') or \
7538232Snate@binkert.org                not simobj.abstract
7548232Snate@binkert.org            if not_abstract and 'type' in simobj.__dict__:
7558232Snate@binkert.org                code('cxx_config_directory["${name}"] = '
7568232Snate@binkert.org                     '${name}CxxConfigParams::makeDirectoryEntry();')
7577673Snate@binkert.org        code.dedent()
7585517Snate@binkert.org        code('}')
7598232Snate@binkert.org        code.write(target[0].abspath)
7608232Snate@binkert.org
7615517Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
7627673Snate@binkert.org    extra_deps = [ py_source.tnode ]
7635517Snate@binkert.org    env.Command(cxx_config_init_cc_file, Value(name),
7648232Snate@binkert.org        MakeAction(createCxxConfigInitCC, Transform("CXXCINIT")))
7658232Snate@binkert.org    cxx_param_hh_files = ["cxx_config/%s.hh" % simobj
7665517Snate@binkert.org        for name,simobj in sorted(sim_objects.iteritems())
7678232Snate@binkert.org        if not hasattr(simobj, 'abstract') or not simobj.abstract]
7688232Snate@binkert.org    Depends(cxx_config_init_cc_file, cxx_param_hh_files +
7698232Snate@binkert.org            [File('sim/cxx_config.hh')])
7707673Snate@binkert.org    Source(cxx_config_init_cc_file)
7715517Snate@binkert.org
7725517Snate@binkert.org# Generate any needed param SWIG wrapper files
7737673Snate@binkert.orgparams_i_files = []
7745517Snate@binkert.orgfor name,param in sorted(params_to_swig.iteritems()):
7755517Snate@binkert.org    i_file = File('python/m5/internal/%s.i' % (param.swig_module_name()))
7765517Snate@binkert.org    params_i_files.append(i_file)
7778232Snate@binkert.org    env.Command(i_file, Value(name),
7785517Snate@binkert.org                MakeAction(createParamSwigWrapper, Transform("SW PARAM")))
7795517Snate@binkert.org    env.Depends(i_file, depends)
7808232Snate@binkert.org    env.Depends(SWIG, i_file)
7818232Snate@binkert.org    SwigSource('m5.internal', i_file)
7825517Snate@binkert.org
7838232Snate@binkert.org# Generate all enum header files
7848232Snate@binkert.orgfor name,enum in sorted(all_enums.iteritems()):
7855517Snate@binkert.org    py_source = PySource.modules[enum.__module__]
7868232Snate@binkert.org    extra_deps = [ py_source.tnode ]
7878232Snate@binkert.org
7888232Snate@binkert.org    cc_file = File('enums/%s.cc' % name)
7895517Snate@binkert.org    env.Command(cc_file, Value(name),
7908232Snate@binkert.org                MakeAction(createEnumStrings, Transform("ENUM STR")))
7918232Snate@binkert.org    env.Depends(cc_file, depends + extra_deps)
7928232Snate@binkert.org    env.Depends(SWIG, cc_file)
7938232Snate@binkert.org    Source(cc_file)
7948232Snate@binkert.org
7958232Snate@binkert.org    hh_file = File('enums/%s.hh' % name)
7965517Snate@binkert.org    env.Command(hh_file, Value(name),
7978232Snate@binkert.org                MakeAction(createEnumDecls, Transform("ENUMDECL")))
7988232Snate@binkert.org    env.Depends(hh_file, depends + extra_deps)
7995517Snate@binkert.org    env.Depends(SWIG, hh_file)
8008232Snate@binkert.org
8017673Snate@binkert.org    i_file = File('python/m5/internal/enum_%s.i' % name)
8025517Snate@binkert.org    env.Command(i_file, Value(name),
8037673Snate@binkert.org                MakeAction(createEnumSwigWrapper, Transform("ENUMSWIG")))
8045517Snate@binkert.org    env.Depends(i_file, depends + extra_deps)
8058232Snate@binkert.org    env.Depends(SWIG, i_file)
8068232Snate@binkert.org    SwigSource('m5.internal', i_file)
8078232Snate@binkert.org
8085192Ssaidi@eecs.umich.edu# Generate SimObject SWIG wrapper files
8098232Snate@binkert.orgfor name,simobj in sorted(sim_objects.iteritems()):
8108232Snate@binkert.org    py_source = PySource.modules[simobj.__module__]
8118232Snate@binkert.org    extra_deps = [ py_source.tnode ]
8128232Snate@binkert.org    i_file = File('python/m5/internal/param_%s.i' % name)
8138232Snate@binkert.org    env.Command(i_file, Value(name),
8145192Ssaidi@eecs.umich.edu                MakeAction(createSimObjectSwigWrapper, Transform("SO SWIG")))
8157674Snate@binkert.org    env.Depends(i_file, depends + extra_deps)
8165522Snate@binkert.org    SwigSource('m5.internal', i_file)
8175522Snate@binkert.org
8187674Snate@binkert.org# Generate the main swig init file
8197674Snate@binkert.orgdef makeEmbeddedSwigInit(target, source, env):
8207674Snate@binkert.org    code = code_formatter()
8217674Snate@binkert.org    module = source[0].get_contents()
8227674Snate@binkert.org    code('''\
8237674Snate@binkert.org#include "sim/init.hh"
8247674Snate@binkert.org
8257674Snate@binkert.orgextern "C" {
8265522Snate@binkert.org    void init_${module}();
8275522Snate@binkert.org}
8285522Snate@binkert.org
8295517Snate@binkert.orgEmbeddedSwig embed_swig_${module}(init_${module});
8305522Snate@binkert.org''')
8315517Snate@binkert.org    code.write(str(target[0]))
8326143Snate@binkert.org
8336727Ssteve.reinhardt@amd.com# Build all swig modules
8345522Snate@binkert.orgfor swig in SwigSource.all:
8355522Snate@binkert.org    env.Command([swig.cc_source.tnode, swig.py_source.tnode], swig.tnode,
8365522Snate@binkert.org                MakeAction('$SWIG $SWIGFLAGS -outdir ${TARGETS[1].dir} '
8377674Snate@binkert.org                '-o ${TARGETS[0]} $SOURCES', Transform("SWIG")))
8385517Snate@binkert.org    cc_file = str(swig.tnode)
8397673Snate@binkert.org    init_file = '%s/%s_init.cc' % (dirname(cc_file), basename(cc_file))
8407673Snate@binkert.org    env.Command(init_file, Value(swig.module),
8417674Snate@binkert.org                MakeAction(makeEmbeddedSwigInit, Transform("EMBED SW")))
8427673Snate@binkert.org    env.Depends(SWIG, init_file)
8437674Snate@binkert.org    Source(init_file, **swig.guards)
8447674Snate@binkert.org
8458946Sandreas.hansson@arm.com# Build all protocol buffers if we have got protoc and protobuf available
8467674Snate@binkert.orgif env['HAVE_PROTOBUF']:
8477674Snate@binkert.org    for proto in ProtoBuf.all:
8487674Snate@binkert.org        # Use both the source and header as the target, and the .proto
8495522Snate@binkert.org        # file as the source. When executing the protoc compiler, also
8505522Snate@binkert.org        # specify the proto_path to avoid having the generated files
8517674Snate@binkert.org        # include the path.
8527674Snate@binkert.org        env.Command([proto.cc_file, proto.hh_file], proto.tnode,
8537674Snate@binkert.org                    MakeAction('$PROTOC --cpp_out ${TARGET.dir} '
8547674Snate@binkert.org                               '--proto_path ${SOURCE.dir} $SOURCE',
8557673Snate@binkert.org                               Transform("PROTOC")))
8567674Snate@binkert.org
8577674Snate@binkert.org        env.Depends(SWIG, [proto.cc_file, proto.hh_file])
8587674Snate@binkert.org        # Add the C++ source file
8597674Snate@binkert.org        Source(proto.cc_file, **proto.guards)
8607674Snate@binkert.orgelif ProtoBuf.all:
8617674Snate@binkert.org    print 'Got protobuf to build, but lacks support!'
8627674Snate@binkert.org    Exit(1)
8637674Snate@binkert.org
8647811Ssteve.reinhardt@amd.com#
8657674Snate@binkert.org# Handle debug flags
8667673Snate@binkert.org#
8675522Snate@binkert.orgdef makeDebugFlagCC(target, source, env):
8686143Snate@binkert.org    assert(len(target) == 1 and len(source) == 1)
8697756SAli.Saidi@ARM.com
8707816Ssteve.reinhardt@amd.com    code = code_formatter()
8717674Snate@binkert.org
8724382Sbinkertn@umich.edu    # delay definition of CompoundFlags until after all the definition
8734382Sbinkertn@umich.edu    # of all constituent SimpleFlags
8744382Sbinkertn@umich.edu    comp_code = code_formatter()
8754382Sbinkertn@umich.edu
8764382Sbinkertn@umich.edu    # file header
8774382Sbinkertn@umich.edu    code('''
8784382Sbinkertn@umich.edu/*
8794382Sbinkertn@umich.edu * DO NOT EDIT THIS FILE! Automatically generated by SCons.
8804382Sbinkertn@umich.edu */
8814382Sbinkertn@umich.edu
8826143Snate@binkert.org#include "base/debug.hh"
883955SN/A
8842655Sstever@eecs.umich.edunamespace Debug {
8852655Sstever@eecs.umich.edu
8862655Sstever@eecs.umich.edu''')
8872655Sstever@eecs.umich.edu
8882655Sstever@eecs.umich.edu    for name, flag in sorted(source[0].read().iteritems()):
8895601Snate@binkert.org        n, compound, desc = flag
8905601Snate@binkert.org        assert n == name
8918334Snate@binkert.org
8928334Snate@binkert.org        if not compound:
8938334Snate@binkert.org            code('SimpleFlag $name("$name", "$desc");')
8945522Snate@binkert.org        else:
8955863Snate@binkert.org            comp_code('CompoundFlag $name("$name", "$desc",')
8965601Snate@binkert.org            comp_code.indent()
8975601Snate@binkert.org            last = len(compound) - 1
8985601Snate@binkert.org            for i,flag in enumerate(compound):
8995863Snate@binkert.org                if i != last:
9009556Sandreas.hansson@arm.com                    comp_code('&$flag,')
9019556Sandreas.hansson@arm.com                else:
9029556Sandreas.hansson@arm.com                    comp_code('&$flag);')
9039556Sandreas.hansson@arm.com            comp_code.dedent()
9049556Sandreas.hansson@arm.com
9059556Sandreas.hansson@arm.com    code.append(comp_code)
9069556Sandreas.hansson@arm.com    code()
9079556Sandreas.hansson@arm.com    code('} // namespace Debug')
9089556Sandreas.hansson@arm.com
9095559Snate@binkert.org    code.write(str(target[0]))
9109556Sandreas.hansson@arm.com
9119618Ssteve.reinhardt@amd.comdef makeDebugFlagHH(target, source, env):
9129618Ssteve.reinhardt@amd.com    assert(len(target) == 1 and len(source) == 1)
9139618Ssteve.reinhardt@amd.com
9149618Ssteve.reinhardt@amd.com    val = eval(source[0].get_contents())
9159556Sandreas.hansson@arm.com    name, compound, desc = val
9168946Sandreas.hansson@arm.com
9178614Sgblack@eecs.umich.edu    code = code_formatter()
9189554Sandreas.hansson@arm.com
9199556Sandreas.hansson@arm.com    # file header boilerplate
9209556Sandreas.hansson@arm.com    code('''\
9219556Sandreas.hansson@arm.com/*
9229556Sandreas.hansson@arm.com * DO NOT EDIT THIS FILE! Automatically generated by SCons.
9239555Sandreas.hansson@arm.com */
9249555Sandreas.hansson@arm.com
9259556Sandreas.hansson@arm.com#ifndef __DEBUG_${name}_HH__
9268737Skoansin.tan@gmail.com#define __DEBUG_${name}_HH__
9279556Sandreas.hansson@arm.com
9289556Sandreas.hansson@arm.comnamespace Debug {
9299556Sandreas.hansson@arm.com''')
9309554Sandreas.hansson@arm.com
9318945Ssteve.reinhardt@amd.com    if compound:
9328945Ssteve.reinhardt@amd.com        code('class CompoundFlag;')
9338945Ssteve.reinhardt@amd.com    code('class SimpleFlag;')
9346143Snate@binkert.org
9356143Snate@binkert.org    if compound:
9366143Snate@binkert.org        code('extern CompoundFlag $name;')
9376143Snate@binkert.org        for flag in compound:
9386143Snate@binkert.org            code('extern SimpleFlag $flag;')
9396143Snate@binkert.org    else:
9406143Snate@binkert.org        code('extern SimpleFlag $name;')
9418945Ssteve.reinhardt@amd.com
9428945Ssteve.reinhardt@amd.com    code('''
9436143Snate@binkert.org}
9446143Snate@binkert.org
9456143Snate@binkert.org#endif // __DEBUG_${name}_HH__
9466143Snate@binkert.org''')
9476143Snate@binkert.org
9486143Snate@binkert.org    code.write(str(target[0]))
9496143Snate@binkert.org
9506143Snate@binkert.orgfor name,flag in sorted(debug_flags.iteritems()):
9516143Snate@binkert.org    n, compound, desc = flag
9526143Snate@binkert.org    assert n == name
9536143Snate@binkert.org
9546143Snate@binkert.org    hh_file = 'debug/%s.hh' % name
9556143Snate@binkert.org    env.Command(hh_file, Value(flag),
9568594Snate@binkert.org                MakeAction(makeDebugFlagHH, Transform("TRACING", 0)))
9578594Snate@binkert.org    env.Depends(SWIG, hh_file)
9588594Snate@binkert.org
9598594Snate@binkert.orgenv.Command('debug/flags.cc', Value(debug_flags),
9606143Snate@binkert.org            MakeAction(makeDebugFlagCC, Transform("TRACING", 0)))
9616143Snate@binkert.orgenv.Depends(SWIG, 'debug/flags.cc')
9626143Snate@binkert.orgSource('debug/flags.cc')
9636143Snate@binkert.org
9646143Snate@binkert.org# version tags
9656240Snate@binkert.orgtags = \
9665554Snate@binkert.orgenv.Command('sim/tags.cc', None,
9675522Snate@binkert.org            MakeAction('util/cpt_upgrader.py --get-cc-file > $TARGET',
9685522Snate@binkert.org                       Transform("VER TAGS")))
9695797Snate@binkert.orgenv.AlwaysBuild(tags)
9705797Snate@binkert.org
9715522Snate@binkert.org# Embed python files.  All .py files that have been indicated by a
9725601Snate@binkert.org# PySource() call in a SConscript need to be embedded into the M5
9738233Snate@binkert.org# library.  To do that, we compile the file to byte code, marshal the
9748233Snate@binkert.org# byte code, compress it, and then generate a c++ file that
9758235Snate@binkert.org# inserts the result into an array.
9768235Snate@binkert.orgdef embedPyFile(target, source, env):
9778235Snate@binkert.org    def c_str(string):
9788235Snate@binkert.org        if string is None:
9799003SAli.Saidi@ARM.com            return "0"
9809003SAli.Saidi@ARM.com        return '"%s"' % string
9818235Snate@binkert.org
9828942Sgblack@eecs.umich.edu    '''Action function to compile a .py into a code object, marshal
9838235Snate@binkert.org    it, compress it, and stick it into an asm file so the code appears
9846143Snate@binkert.org    as just bytes with a label in the data section'''
9852655Sstever@eecs.umich.edu
9866143Snate@binkert.org    src = file(str(source[0]), 'r').read()
9876143Snate@binkert.org
9888233Snate@binkert.org    pysource = PySource.tnodes[source[0]]
9896143Snate@binkert.org    compiled = compile(src, pysource.abspath, 'exec')
9906143Snate@binkert.org    marshalled = marshal.dumps(compiled)
9914007Ssaidi@eecs.umich.edu    compressed = zlib.compress(marshalled)
9924596Sbinkertn@umich.edu    data = compressed
9934007Ssaidi@eecs.umich.edu    sym = pysource.symname
9944596Sbinkertn@umich.edu
9957756SAli.Saidi@ARM.com    code = code_formatter()
9967816Ssteve.reinhardt@amd.com    code('''\
9978334Snate@binkert.org#include "sim/init.hh"
9988334Snate@binkert.org
9998334Snate@binkert.orgnamespace {
10008334Snate@binkert.org
10015601Snate@binkert.orgconst uint8_t data_${sym}[] = {
10025601Snate@binkert.org''')
10032655Sstever@eecs.umich.edu    code.indent()
10049225Sandreas.hansson@arm.com    step = 16
10059225Sandreas.hansson@arm.com    for i in xrange(0, len(data), step):
10069226Sandreas.hansson@arm.com        x = array.array('B', data[i:i+step])
10079226Sandreas.hansson@arm.com        code(''.join('%d,' % d for d in x))
10089225Sandreas.hansson@arm.com    code.dedent()
10099226Sandreas.hansson@arm.com
10109226Sandreas.hansson@arm.com    code('''};
10119226Sandreas.hansson@arm.com
10129226Sandreas.hansson@arm.comEmbeddedPython embedded_${sym}(
10139226Sandreas.hansson@arm.com    ${{c_str(pysource.arcname)}},
10149226Sandreas.hansson@arm.com    ${{c_str(pysource.abspath)}},
10159225Sandreas.hansson@arm.com    ${{c_str(pysource.modpath)}},
10169227Sandreas.hansson@arm.com    data_${sym},
10179227Sandreas.hansson@arm.com    ${{len(data)}},
10189227Sandreas.hansson@arm.com    ${{len(marshalled)}});
10199227Sandreas.hansson@arm.com
10208946Sandreas.hansson@arm.com} // anonymous namespace
10213918Ssaidi@eecs.umich.edu''')
10229225Sandreas.hansson@arm.com    code.write(str(target[0]))
10233918Ssaidi@eecs.umich.edu
10249225Sandreas.hansson@arm.comfor source in PySource.all:
10259225Sandreas.hansson@arm.com    env.Command(source.cpp, source.tnode,
10269227Sandreas.hansson@arm.com                MakeAction(embedPyFile, Transform("EMBED PY")))
10279227Sandreas.hansson@arm.com    env.Depends(SWIG, source.cpp)
10289227Sandreas.hansson@arm.com    Source(source.cpp, skip_no_python=True)
10299226Sandreas.hansson@arm.com
10309225Sandreas.hansson@arm.com########################################################################
10319227Sandreas.hansson@arm.com#
10329227Sandreas.hansson@arm.com# Define binaries.  Each different build type (debug, opt, etc.) gets
10339227Sandreas.hansson@arm.com# a slightly different build environment.
10349227Sandreas.hansson@arm.com#
10358946Sandreas.hansson@arm.com
10369225Sandreas.hansson@arm.com# List of constructed environments to pass back to SConstruct
10379226Sandreas.hansson@arm.comdate_source = Source('base/date.cc', skip_lib=True)
10389226Sandreas.hansson@arm.com
10399226Sandreas.hansson@arm.com# Capture this directory for the closure makeEnv, otherwise when it is
10403515Ssaidi@eecs.umich.edu# called, it won't know what directory it should use.
10413918Ssaidi@eecs.umich.eduvariant_dir = Dir('.').path
10424762Snate@binkert.orgdef variant(*path):
10433515Ssaidi@eecs.umich.edu    return os.path.join(variant_dir, *path)
10448881Smarc.orr@gmail.comdef variantd(*path):
10458881Smarc.orr@gmail.com    return variant(*path)+'/'
10468881Smarc.orr@gmail.com
10478881Smarc.orr@gmail.com# Function to create a new build environment as clone of current
10488881Smarc.orr@gmail.com# environment 'env' with modified object suffix and optional stripped
10499226Sandreas.hansson@arm.com# binary.  Additional keyword arguments are appended to corresponding
10509226Sandreas.hansson@arm.com# build environment vars.
10519226Sandreas.hansson@arm.comdef makeEnv(env, label, objsfx, strip = False, **kwargs):
10528881Smarc.orr@gmail.com    # SCons doesn't know to append a library suffix when there is a '.' in the
10538881Smarc.orr@gmail.com    # name.  Use '_' instead.
10548881Smarc.orr@gmail.com    libname = variant('gem5_' + label)
10558881Smarc.orr@gmail.com    exename = variant('gem5.' + label)
10568881Smarc.orr@gmail.com    secondary_exename = variant('m5.' + label)
10578881Smarc.orr@gmail.com
10588881Smarc.orr@gmail.com    new_env = env.Clone(OBJSUFFIX=objsfx, SHOBJSUFFIX=objsfx + 's')
10598881Smarc.orr@gmail.com    new_env.Label = label
10608881Smarc.orr@gmail.com    new_env.Append(**kwargs)
10618881Smarc.orr@gmail.com
10628881Smarc.orr@gmail.com    swig_env = new_env.Clone()
10638881Smarc.orr@gmail.com
10648881Smarc.orr@gmail.com    # Both gcc and clang have issues with unused labels and values in
10658881Smarc.orr@gmail.com    # the SWIG generated code
10668881Smarc.orr@gmail.com    swig_env.Append(CCFLAGS=['-Wno-unused-label', '-Wno-unused-value'])
10678881Smarc.orr@gmail.com
10688881Smarc.orr@gmail.com    if env['GCC']:
10698881Smarc.orr@gmail.com        # Depending on the SWIG version, we also need to supress
10708881Smarc.orr@gmail.com        # warnings about uninitialized variables and missing field
10718881Smarc.orr@gmail.com        # initializers.
10729225Sandreas.hansson@arm.com        swig_env.Append(CCFLAGS=['-Wno-uninitialized',
10739225Sandreas.hansson@arm.com                                 '-Wno-missing-field-initializers',
1074955SN/A                                 '-Wno-unused-but-set-variable',
1075955SN/A                                 '-Wno-maybe-uninitialized',
10768881Smarc.orr@gmail.com                                 '-Wno-type-limits'])
10778881Smarc.orr@gmail.com
10788881Smarc.orr@gmail.com        # Only gcc >= 4.9 supports UBSan, so check both the version
10799225Sandreas.hansson@arm.com        # and the command-line option before adding the compiler and
10809225Sandreas.hansson@arm.com        # linker flags.
1081955SN/A        if GetOption('with_ubsan') and \
1082955SN/A                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
10838881Smarc.orr@gmail.com            new_env.Append(CCFLAGS='-fsanitize=undefined')
10848881Smarc.orr@gmail.com            new_env.Append(LINKFLAGS='-fsanitize=undefined')
10858881Smarc.orr@gmail.com
10869225Sandreas.hansson@arm.com        # The address sanitizer is available for gcc >= 4.8
10879225Sandreas.hansson@arm.com        if GetOption('with_asan'):
1088955SN/A            new_env.Append(CCFLAGS=['-fsanitize=address',
10899226Sandreas.hansson@arm.com                                    '-fno-omit-frame-pointer'])
10908881Smarc.orr@gmail.com            new_env.Append(LINKFLAGS='-fsanitize=address')
10918881Smarc.orr@gmail.com
10928881Smarc.orr@gmail.com    if env['CLANG']:
10938881Smarc.orr@gmail.com        swig_env.Append(CCFLAGS=['-Wno-sometimes-uninitialized',
10949225Sandreas.hansson@arm.com                                 '-Wno-deprecated-register',
10951869SN/A                                 '-Wno-tautological-compare'])
10969226Sandreas.hansson@arm.com
10979226Sandreas.hansson@arm.com        # We require clang >= 3.1, so there is no need to check any
10989226Sandreas.hansson@arm.com        # versions here.
10999226Sandreas.hansson@arm.com        if GetOption('with_ubsan'):
11009226Sandreas.hansson@arm.com            new_env.Append(CCFLAGS='-fsanitize=undefined')
11019226Sandreas.hansson@arm.com            new_env.Append(LINKFLAGS='-fsanitize=undefined')
11029226Sandreas.hansson@arm.com
11031869SN/A        if GetOption('with_asan'):
1104            new_env.Append(CCFLAGS=['-fsanitize=address',
1105                                    '-fno-omit-frame-pointer'])
1106            new_env.Append(LINKFLAGS='-fsanitize=address')
1107
1108    werror_env = new_env.Clone()
1109    # Treat warnings as errors but white list some warnings that we
1110    # want to allow (e.g., deprecation warnings).
1111    werror_env.Append(CCFLAGS=['-Werror',
1112                               '-Wno-error=deprecated-declarations',
1113                               '-Wno-error=deprecated',
1114                               ])
1115
1116    def make_obj(source, static, extra_deps = None):
1117        '''This function adds the specified source to the correct
1118        build environment, and returns the corresponding SCons Object
1119        nodes'''
1120
1121        if source.swig:
1122            env = swig_env
1123        elif source.Werror:
1124            env = werror_env
1125        else:
1126            env = new_env
1127
1128        if static:
1129            obj = env.StaticObject(source.tnode)
1130        else:
1131            obj = env.SharedObject(source.tnode)
1132
1133        if extra_deps:
1134            env.Depends(obj, extra_deps)
1135
1136        return obj
1137
1138    lib_guards = {'main': False, 'skip_lib': False}
1139
1140    # Without Python, leave out all SWIG and Python content from the
1141    # library builds.  The option doesn't affect gem5 built as a program
1142    if GetOption('without_python'):
1143        lib_guards['skip_no_python'] = False
1144
1145    static_objs = [ make_obj(s, True) for s in Source.get(**lib_guards) ]
1146    shared_objs = [ make_obj(s, False) for s in Source.get(**lib_guards) ]
1147
1148    static_date = make_obj(date_source, static=True, extra_deps=static_objs)
1149    static_objs.append(static_date)
1150
1151    shared_date = make_obj(date_source, static=False, extra_deps=shared_objs)
1152    shared_objs.append(shared_date)
1153
1154    # First make a library of everything but main() so other programs can
1155    # link against m5.
1156    static_lib = new_env.StaticLibrary(libname, static_objs)
1157    shared_lib = new_env.SharedLibrary(libname, shared_objs)
1158
1159    # Now link a stub with main() and the static library.
1160    main_objs = [ make_obj(s, True) for s in Source.get(main=True) ]
1161
1162    for test in UnitTest.all:
1163        flags = { test.target : True }
1164        test_sources = Source.get(**flags)
1165        test_objs = [ make_obj(s, static=True) for s in test_sources ]
1166        if test.main:
1167            test_objs += main_objs
1168        path = variant('unittest/%s.%s' % (test.target, label))
1169        new_env.Program(path, test_objs + static_objs)
1170
1171    progname = exename
1172    if strip:
1173        progname += '.unstripped'
1174
1175    targets = new_env.Program(progname, main_objs + static_objs)
1176
1177    if strip:
1178        if sys.platform == 'sunos5':
1179            cmd = 'cp $SOURCE $TARGET; strip $TARGET'
1180        else:
1181            cmd = 'strip $SOURCE -o $TARGET'
1182        targets = new_env.Command(exename, progname,
1183                    MakeAction(cmd, Transform("STRIP")))
1184
1185    new_env.Command(secondary_exename, exename,
1186            MakeAction('ln $SOURCE $TARGET', Transform("HARDLINK")))
1187
1188    new_env.M5Binary = targets[0]
1189    return new_env
1190
1191# Start out with the compiler flags common to all compilers,
1192# i.e. they all use -g for opt and -g -pg for prof
1193ccflags = {'debug' : [], 'opt' : ['-g'], 'fast' : [], 'prof' : ['-g', '-pg'],
1194           'perf' : ['-g']}
1195
1196# Start out with the linker flags common to all linkers, i.e. -pg for
1197# prof, and -lprofiler for perf. The -lprofile flag is surrounded by
1198# no-as-needed and as-needed as the binutils linker is too clever and
1199# simply doesn't link to the library otherwise.
1200ldflags = {'debug' : [], 'opt' : [], 'fast' : [], 'prof' : ['-pg'],
1201           'perf' : ['-Wl,--no-as-needed', '-lprofiler', '-Wl,--as-needed']}
1202
1203# For Link Time Optimization, the optimisation flags used to compile
1204# individual files are decoupled from those used at link time
1205# (i.e. you can compile with -O3 and perform LTO with -O0), so we need
1206# to also update the linker flags based on the target.
1207if env['GCC']:
1208    if sys.platform == 'sunos5':
1209        ccflags['debug'] += ['-gstabs+']
1210    else:
1211        ccflags['debug'] += ['-ggdb3']
1212    ldflags['debug'] += ['-O0']
1213    # opt, fast, prof and perf all share the same cc flags, also add
1214    # the optimization to the ldflags as LTO defers the optimization
1215    # to link time
1216    for target in ['opt', 'fast', 'prof', 'perf']:
1217        ccflags[target] += ['-O3']
1218        ldflags[target] += ['-O3']
1219
1220    ccflags['fast'] += env['LTO_CCFLAGS']
1221    ldflags['fast'] += env['LTO_LDFLAGS']
1222elif env['CLANG']:
1223    ccflags['debug'] += ['-g', '-O0']
1224    # opt, fast, prof and perf all share the same cc flags
1225    for target in ['opt', 'fast', 'prof', 'perf']:
1226        ccflags[target] += ['-O3']
1227else:
1228    print 'Unknown compiler, please fix compiler options'
1229    Exit(1)
1230
1231
1232# To speed things up, we only instantiate the build environments we
1233# need.  We try to identify the needed environment for each target; if
1234# we can't, we fall back on instantiating all the environments just to
1235# be safe.
1236target_types = ['debug', 'opt', 'fast', 'prof', 'perf']
1237obj2target = {'do': 'debug', 'o': 'opt', 'fo': 'fast', 'po': 'prof',
1238              'gpo' : 'perf'}
1239
1240def identifyTarget(t):
1241    ext = t.split('.')[-1]
1242    if ext in target_types:
1243        return ext
1244    if obj2target.has_key(ext):
1245        return obj2target[ext]
1246    match = re.search(r'/tests/([^/]+)/', t)
1247    if match and match.group(1) in target_types:
1248        return match.group(1)
1249    return 'all'
1250
1251needed_envs = [identifyTarget(target) for target in BUILD_TARGETS]
1252if 'all' in needed_envs:
1253    needed_envs += target_types
1254
1255def makeEnvirons(target, source, env):
1256    # cause any later Source() calls to be fatal, as a diagnostic.
1257    Source.done()
1258
1259    envList = []
1260
1261    # Debug binary
1262    if 'debug' in needed_envs:
1263        envList.append(
1264            makeEnv(env, 'debug', '.do',
1265                    CCFLAGS = Split(ccflags['debug']),
1266                    CPPDEFINES = ['DEBUG', 'TRACING_ON=1'],
1267                    LINKFLAGS = Split(ldflags['debug'])))
1268
1269    # Optimized binary
1270    if 'opt' in needed_envs:
1271        envList.append(
1272            makeEnv(env, 'opt', '.o',
1273                    CCFLAGS = Split(ccflags['opt']),
1274                    CPPDEFINES = ['TRACING_ON=1'],
1275                    LINKFLAGS = Split(ldflags['opt'])))
1276
1277    # "Fast" binary
1278    if 'fast' in needed_envs:
1279        envList.append(
1280            makeEnv(env, 'fast', '.fo', strip = True,
1281                    CCFLAGS = Split(ccflags['fast']),
1282                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1283                    LINKFLAGS = Split(ldflags['fast'])))
1284
1285    # Profiled binary using gprof
1286    if 'prof' in needed_envs:
1287        envList.append(
1288            makeEnv(env, 'prof', '.po',
1289                    CCFLAGS = Split(ccflags['prof']),
1290                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1291                    LINKFLAGS = Split(ldflags['prof'])))
1292
1293    # Profiled binary using google-pprof
1294    if 'perf' in needed_envs:
1295        envList.append(
1296            makeEnv(env, 'perf', '.gpo',
1297                    CCFLAGS = Split(ccflags['perf']),
1298                    CPPDEFINES = ['NDEBUG', 'TRACING_ON=0'],
1299                    LINKFLAGS = Split(ldflags['perf'])))
1300
1301    # Set up the regression tests for each build.
1302    for e in envList:
1303        SConscript(os.path.join(env.root.abspath, 'tests', 'SConscript'),
1304                   variant_dir = variantd('tests', e.Label),
1305                   exports = { 'env' : e }, duplicate = False)
1306
1307# The MakeEnvirons Builder defers the full dependency collection until
1308# after processing the ISA definition (due to dynamically generated
1309# source files).  Add this dependency to all targets so they will wait
1310# until the environments are completely set up.  Otherwise, a second
1311# process (e.g. -j2 or higher) will try to compile the requested target,
1312# not know how, and fail.
1313env.Append(BUILDERS = {'MakeEnvirons' :
1314                        Builder(action=MakeAction(makeEnvirons,
1315                                                  Transform("ENVIRONS", 1)))})
1316
1317isa_target = env['PHONY_BASE'] + '-deps'
1318environs   = env['PHONY_BASE'] + '-environs'
1319env.Depends('#all-deps',     isa_target)
1320env.Depends('#all-environs', environs)
1321env.ScanISA(isa_target, File('arch/%s/generated/inc.d' % env['TARGET_ISA']))
1322envSetup = env.MakeEnvirons(environs, isa_target)
1323
1324# make sure no -deps targets occur before all ISAs are complete
1325env.Depends(isa_target, '#all-isas')
1326# likewise for -environs targets and all the -deps targets
1327env.Depends(environs, '#all-deps')
1328