SConstruct revision 6017
1955SN/A# -*- mode:python -*-
2955SN/A
312230Sgiacomo.travaglini@arm.com# Copyright (c) 2009 The Hewlett-Packard Development Company
49812Sandreas.hansson@arm.com# Copyright (c) 2004-2005 The Regents of The University of Michigan
59812Sandreas.hansson@arm.com# All rights reserved.
69812Sandreas.hansson@arm.com#
79812Sandreas.hansson@arm.com# Redistribution and use in source and binary forms, with or without
89812Sandreas.hansson@arm.com# modification, are permitted provided that the following conditions are
99812Sandreas.hansson@arm.com# met: redistributions of source code must retain the above copyright
109812Sandreas.hansson@arm.com# notice, this list of conditions and the following disclaimer;
119812Sandreas.hansson@arm.com# redistributions in binary form must reproduce the above copyright
129812Sandreas.hansson@arm.com# notice, this list of conditions and the following disclaimer in the
139812Sandreas.hansson@arm.com# documentation and/or other materials provided with the distribution;
149812Sandreas.hansson@arm.com# neither the name of the copyright holders nor the names of its
157816Ssteve.reinhardt@amd.com# contributors may be used to endorse or promote products derived from
165871Snate@binkert.org# this software without specific prior written permission.
171762SN/A#
18955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29955SN/A#
30955SN/A# Authors: Steve Reinhardt
31955SN/A#          Nathan Binkert
32955SN/A
33955SN/A###################################################
34955SN/A#
35955SN/A# SCons top-level build description (SConstruct) file.
36955SN/A#
37955SN/A# While in this directory ('m5'), just type 'scons' to build the default
38955SN/A# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
39955SN/A# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
40955SN/A# the optimized full-system version).
41955SN/A#
422665Ssaidi@eecs.umich.edu# You can build M5 in a different directory as long as there is a
432665Ssaidi@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
445863Snate@binkert.org# expects that all configs under the same build directory are being
45955SN/A# built for the same host system.
46955SN/A#
47955SN/A# Examples:
48955SN/A#
49955SN/A#   The following two commands are equivalent.  The '-u' option tells
508878Ssteve.reinhardt@amd.com#   scons to search up the directory tree for this SConstruct file.
512632Sstever@eecs.umich.edu#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
528878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
532632Sstever@eecs.umich.edu#
54955SN/A#   The following two commands are equivalent and demonstrate building
558878Ssteve.reinhardt@amd.com#   in a directory outside of the source tree.  The '-C' option tells
562632Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
572761Sstever@eecs.umich.edu#   file.
582632Sstever@eecs.umich.edu#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
592632Sstever@eecs.umich.edu#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
602632Sstever@eecs.umich.edu#
612761Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
622761Sstever@eecs.umich.edu# 'm5' directory (or use -u or -C to tell scons where to find this
632761Sstever@eecs.umich.edu# file), you can use 'scons -h' to print all the M5-specific build
648878Ssteve.reinhardt@amd.com# options as well.
658878Ssteve.reinhardt@amd.com#
662761Sstever@eecs.umich.edu###################################################
672761Sstever@eecs.umich.edu
682761Sstever@eecs.umich.edu# Check for recent-enough Python and SCons versions.
692761Sstever@eecs.umich.edutry:
702761Sstever@eecs.umich.edu    # Really old versions of scons only take two options for the
718878Ssteve.reinhardt@amd.com    # function, so check once without the revision and once with the
728878Ssteve.reinhardt@amd.com    # revision, the first instance will fail for stuff other than
732632Sstever@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
742632Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98)
758878Ssteve.reinhardt@amd.com    EnsureSConsVersion(0, 98, 1)
768878Ssteve.reinhardt@amd.comexcept SystemExit, e:
772632Sstever@eecs.umich.edu    print """
78955SN/AFor more details, see:
79955SN/A    http://m5sim.org/wiki/index.php/Compiling_M5
80955SN/A"""
816654Snate@binkert.org    raise
8210196SCurtis.Dunham@arm.com
83955SN/A# We ensure the python version early because we have stuff that
845396Ssaidi@eecs.umich.edu# requires python 2.4
8511401Sandreas.sandberg@arm.comtry:
865863Snate@binkert.org    EnsurePythonVersion(2, 4)
875863Snate@binkert.orgexcept SystemExit, e:
884202Sbinkertn@umich.edu    print """
895863Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
905863Snate@binkert.orgeither (1) rearranging your PATH so that scons finds the non-default
915863Snate@binkert.org'python' first or (2) explicitly invoking an alternative interpreter
925863Snate@binkert.orgon the scons script.
93955SN/A
946654Snate@binkert.orgFor more details, see:
955273Sstever@gmail.com    http://m5sim.org/wiki/index.php/Using_a_non-default_Python_installation
965871Snate@binkert.org"""
975273Sstever@gmail.com    raise
986654Snate@binkert.org
995396Ssaidi@eecs.umich.eduimport os
1008120Sgblack@eecs.umich.eduimport re
1018120Sgblack@eecs.umich.eduimport subprocess
1028120Sgblack@eecs.umich.eduimport sys
1038120Sgblack@eecs.umich.edu
1048120Sgblack@eecs.umich.edufrom os import mkdir, environ
1058120Sgblack@eecs.umich.edufrom os.path import abspath, basename, dirname, expanduser, normpath
1068120Sgblack@eecs.umich.edufrom os.path import exists,  isdir, isfile
1078120Sgblack@eecs.umich.edufrom os.path import join as joinpath, split as splitpath
1088879Ssteve.reinhardt@amd.com
1098879Ssteve.reinhardt@amd.comimport SCons
1108879Ssteve.reinhardt@amd.comimport SCons.Node
1118879Ssteve.reinhardt@amd.com
1128879Ssteve.reinhardt@amd.comdef read_command(cmd, **kwargs):
1138879Ssteve.reinhardt@amd.com    """run the command cmd, read the results and return them
1148879Ssteve.reinhardt@amd.com    this is sorta like `cmd` in shell"""
1158879Ssteve.reinhardt@amd.com    from subprocess import Popen, PIPE, STDOUT
1168879Ssteve.reinhardt@amd.com
1178879Ssteve.reinhardt@amd.com    if isinstance(cmd, str):
1188879Ssteve.reinhardt@amd.com        cmd = cmd.split()
1198879Ssteve.reinhardt@amd.com
1208879Ssteve.reinhardt@amd.com    no_exception = 'exception' in kwargs
1218120Sgblack@eecs.umich.edu    exception = kwargs.pop('exception', None)
1228120Sgblack@eecs.umich.edu    
1238120Sgblack@eecs.umich.edu    kwargs.setdefault('shell', False)
1248120Sgblack@eecs.umich.edu    kwargs.setdefault('stdout', PIPE)
1258120Sgblack@eecs.umich.edu    kwargs.setdefault('stderr', STDOUT)
1268120Sgblack@eecs.umich.edu    kwargs.setdefault('close_fds', True)
1278120Sgblack@eecs.umich.edu    try:
1288120Sgblack@eecs.umich.edu        subp = Popen(cmd, **kwargs)
1298120Sgblack@eecs.umich.edu    except Exception, e:
1308120Sgblack@eecs.umich.edu        if no_exception:
1318120Sgblack@eecs.umich.edu            return exception
1328120Sgblack@eecs.umich.edu        raise
1338120Sgblack@eecs.umich.edu
1348120Sgblack@eecs.umich.edu    return subp.communicate()[0]
1358879Ssteve.reinhardt@amd.com
1368879Ssteve.reinhardt@amd.com# helper function: compare arrays or strings of version numbers.
1378879Ssteve.reinhardt@amd.com# E.g., compare_version((1,3,25), (1,4,1)')
1388879Ssteve.reinhardt@amd.com# returns -1, 0, 1 if v1 is <, ==, > v2
13910458Sandreas.hansson@arm.comdef compare_versions(v1, v2):
14010458Sandreas.hansson@arm.com    def make_version_list(v):
14110458Sandreas.hansson@arm.com        if isinstance(v, (list,tuple)):
1428879Ssteve.reinhardt@amd.com            return v
1438879Ssteve.reinhardt@amd.com        elif isinstance(v, str):
1448879Ssteve.reinhardt@amd.com            return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
1458879Ssteve.reinhardt@amd.com        else:
1469227Sandreas.hansson@arm.com            raise TypeError
1479227Sandreas.hansson@arm.com
14812063Sgabeblack@google.com    v1 = make_version_list(v1)
14912063Sgabeblack@google.com    v2 = make_version_list(v2)
15012063Sgabeblack@google.com    # Compare corresponding elements of lists
1518879Ssteve.reinhardt@amd.com    for n1,n2 in zip(v1, v2):
1528879Ssteve.reinhardt@amd.com        if n1 < n2: return -1
1538879Ssteve.reinhardt@amd.com        if n1 > n2: return  1
1548879Ssteve.reinhardt@amd.com    # all corresponding values are equal... see if one has extra values
15510453SAndrew.Bardsley@arm.com    if len(v1) < len(v2): return -1
15610453SAndrew.Bardsley@arm.com    if len(v1) > len(v2): return  1
15710453SAndrew.Bardsley@arm.com    return 0
15810456SCurtis.Dunham@arm.com
15910456SCurtis.Dunham@arm.com########################################################################
16010456SCurtis.Dunham@arm.com#
16110457Sandreas.hansson@arm.com# Set up the base build environment.
16210457Sandreas.hansson@arm.com#
16311342Sandreas.hansson@arm.com########################################################################
16411342Sandreas.hansson@arm.comuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH', 'PATH',
1658120Sgblack@eecs.umich.edu                 'RANLIB' ])
16612063Sgabeblack@google.com
16712063Sgabeblack@google.comuse_env = {}
16812063Sgabeblack@google.comfor key,val in os.environ.iteritems():
16912063Sgabeblack@google.com    if key in use_vars or key.startswith("M5"):
1705871Snate@binkert.org        use_env[key] = val
1715871Snate@binkert.org
1726121Snate@binkert.orgenv = Environment(ENV=use_env)
1735871Snate@binkert.orgenv.root = Dir(".")          # The current directory (where this file lives).
1745871Snate@binkert.orgenv.srcdir = Dir("src")      # The source directory
1759926Sstan.czerniawski@arm.com
17612243Sgabeblack@google.com########################################################################
1771533SN/A#
17812246Sgabeblack@google.com# Mercurial Stuff.
17912246Sgabeblack@google.com#
18012246Sgabeblack@google.com# If the M5 directory is a mercurial repository, we should do some
18112246Sgabeblack@google.com# extra things.
1829239Sandreas.hansson@arm.com#
1839239Sandreas.hansson@arm.com########################################################################
1849239Sandreas.hansson@arm.com
1859239Sandreas.hansson@arm.comhgdir = env.root.Dir(".hg")
1869239Sandreas.hansson@arm.com
1879239Sandreas.hansson@arm.commercurial_style_message = """
1889239Sandreas.hansson@arm.comYou're missing the M5 style hook.
189955SN/APlease install the hook so we can ensure that all code fits a common style.
190955SN/A
1912632Sstever@eecs.umich.eduAll you'd need to do is add the following lines to your repository .hg/hgrc
1922632Sstever@eecs.umich.eduor your personal .hgrc
193955SN/A----------------
194955SN/A
195955SN/A[extensions]
196955SN/Astyle = %s/util/style.py
1978878Ssteve.reinhardt@amd.com
198955SN/A[hooks]
1992632Sstever@eecs.umich.edupretxncommit.style = python:style.check_whitespace
2002632Sstever@eecs.umich.edu""" % (env.root)
2012632Sstever@eecs.umich.edu
2022632Sstever@eecs.umich.edumercurial_bin_not_found = """
2032632Sstever@eecs.umich.eduMercurial binary cannot be found, unfortunately this means that we
2042632Sstever@eecs.umich.educannot easily determine the version of M5 that you are running and
2052632Sstever@eecs.umich.eduthis makes error messages more difficult to collect.  Please consider
2068268Ssteve.reinhardt@amd.cominstalling mercurial if you choose to post an error message
2078268Ssteve.reinhardt@amd.com"""
2088268Ssteve.reinhardt@amd.com
2098268Ssteve.reinhardt@amd.commercurial_lib_not_found = """
2108268Ssteve.reinhardt@amd.comMercurial libraries cannot be found, ignoring style hook
2118268Ssteve.reinhardt@amd.comIf you are actually a M5 developer, please fix this and
2128268Ssteve.reinhardt@amd.comrun the style hook. It is important.
2132632Sstever@eecs.umich.edu"""
2142632Sstever@eecs.umich.edu
2152632Sstever@eecs.umich.eduhg_info = "Unknown"
2162632Sstever@eecs.umich.eduif hgdir.exists():
2178268Ssteve.reinhardt@amd.com    # 1) Grab repository revision if we know it.
2182632Sstever@eecs.umich.edu    cmd = "hg id -n -i -t -b"
2198268Ssteve.reinhardt@amd.com    try:
2208268Ssteve.reinhardt@amd.com        hg_info = read_command(cmd, cwd=env.root.abspath).strip()
2218268Ssteve.reinhardt@amd.com    except OSError:
2228268Ssteve.reinhardt@amd.com        print mercurial_bin_not_found
2233718Sstever@eecs.umich.edu
2242634Sstever@eecs.umich.edu    # 2) Ensure that the style hook is in place.
2252634Sstever@eecs.umich.edu    try:
2265863Snate@binkert.org        ui = None
2272638Sstever@eecs.umich.edu        if ARGUMENTS.get('IGNORE_STYLE') != 'True':
2288268Ssteve.reinhardt@amd.com            from mercurial import ui
2292632Sstever@eecs.umich.edu            ui = ui.ui()
2302632Sstever@eecs.umich.edu    except ImportError:
2312632Sstever@eecs.umich.edu        print mercurial_lib_not_found
2322632Sstever@eecs.umich.edu
2332632Sstever@eecs.umich.edu    if ui is not None:
2341858SN/A        ui.readconfig(hgdir.File('hgrc').abspath)
2353716Sstever@eecs.umich.edu        style_hook = ui.config('hooks', 'pretxncommit.style', None)
2362638Sstever@eecs.umich.edu
2372638Sstever@eecs.umich.edu        if not style_hook:
2382638Sstever@eecs.umich.edu            print mercurial_style_message
2392638Sstever@eecs.umich.edu            sys.exit(1)
2402638Sstever@eecs.umich.eduelse:
2412638Sstever@eecs.umich.edu    print ".hg directory not found"
2422638Sstever@eecs.umich.eduenv['HG_INFO'] = hg_info
2435863Snate@binkert.org
2445863Snate@binkert.org###################################################
2455863Snate@binkert.org#
246955SN/A# Figure out which configurations to set up based on the path(s) of
2475341Sstever@gmail.com# the target(s).
2485341Sstever@gmail.com#
2495863Snate@binkert.org###################################################
2507756SAli.Saidi@ARM.com
2515341Sstever@gmail.com# Find default configuration & binary.
2526121Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
2534494Ssaidi@eecs.umich.edu
2546121Snate@binkert.org# helper function: find last occurrence of element in list
2551105SN/Adef rfind(l, elt, offs = -1):
2562667Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
2572667Sstever@eecs.umich.edu        if l[i] == elt:
2582667Sstever@eecs.umich.edu            return i
2592667Sstever@eecs.umich.edu    raise ValueError, "element not found"
2606121Snate@binkert.org
2612667Sstever@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
2625341Sstever@gmail.com# directory below this will determine the build parameters.  For
2635863Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2645341Sstever@gmail.com# recognize that ALPHA_SE specifies the configuration because it
2655341Sstever@gmail.com# follow 'build' in the bulid path.
2665341Sstever@gmail.com
2678120Sgblack@eecs.umich.edu# Generate absolute paths to targets so we can see where the build dir is
2685341Sstever@gmail.comif COMMAND_LINE_TARGETS:
2698120Sgblack@eecs.umich.edu    # Ask SCons which directory it was invoked from
2705341Sstever@gmail.com    launch_dir = GetLaunchDir()
2718120Sgblack@eecs.umich.edu    # Make targets relative to invocation directory
2726121Snate@binkert.org    abs_targets = [ normpath(joinpath(launch_dir, str(x))) for x in \
2736121Snate@binkert.org                    COMMAND_LINE_TARGETS]
2749396Sandreas.hansson@arm.comelse:
2755397Ssaidi@eecs.umich.edu    # Default targets are relative to root of tree
2765397Ssaidi@eecs.umich.edu    abs_targets = [ normpath(joinpath(ROOT, str(x))) for x in \
2777727SAli.Saidi@ARM.com                    DEFAULT_TARGETS]
2788268Ssteve.reinhardt@amd.com
2796168Snate@binkert.org
2805341Sstever@gmail.com# Generate a list of the unique build roots and configs that the
2818120Sgblack@eecs.umich.edu# collected targets reference.
2828120Sgblack@eecs.umich.eduvariant_paths = []
2838120Sgblack@eecs.umich.edubuild_root = None
2846814Sgblack@eecs.umich.edufor t in abs_targets:
2855863Snate@binkert.org    path_dirs = t.split('/')
2868120Sgblack@eecs.umich.edu    try:
2875341Sstever@gmail.com        build_top = rfind(path_dirs, 'build', -2)
2885863Snate@binkert.org    except:
2898268Ssteve.reinhardt@amd.com        print "Error: no non-leaf 'build' dir found on target path", t
2906121Snate@binkert.org        Exit(1)
2916121Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2928268Ssteve.reinhardt@amd.com    if not build_root:
2935742Snate@binkert.org        build_root = this_build_root
2945742Snate@binkert.org    else:
2955341Sstever@gmail.com        if this_build_root != build_root:
2965742Snate@binkert.org            print "Error: build targets not under same build root\n"\
2975742Snate@binkert.org                  "  %s\n  %s" % (build_root, this_build_root)
2985341Sstever@gmail.com            Exit(1)
2996017Snate@binkert.org    variant_path = joinpath('/',*path_dirs[:build_top+2])
3006121Snate@binkert.org    if variant_path not in variant_paths:
3016017Snate@binkert.org        variant_paths.append(variant_path)
30212158Sandreas.sandberg@arm.com
30312158Sandreas.sandberg@arm.com# Make sure build_root exists (might not if this is the first build there)
30412158Sandreas.sandberg@arm.comif not isdir(build_root):
3058120Sgblack@eecs.umich.edu    mkdir(build_root)
3067756SAli.Saidi@ARM.com
3077756SAli.Saidi@ARM.comExport('env')
3087756SAli.Saidi@ARM.com
3097756SAli.Saidi@ARM.comenv.SConsignFile(joinpath(build_root, "sconsign"))
3107816Ssteve.reinhardt@amd.com
3117816Ssteve.reinhardt@amd.com# Default duplicate option is to use hard links, but this messes up
3127816Ssteve.reinhardt@amd.com# when you use emacs to edit a file in the target dir, as emacs moves
3137816Ssteve.reinhardt@amd.com# file to file~ then copies to file, breaking the link.  Symbolic
3147816Ssteve.reinhardt@amd.com# (soft) links work better.
31511979Sgabeblack@google.comenv.SetOption('duplicate', 'soft-copy')
3167816Ssteve.reinhardt@amd.com
3177816Ssteve.reinhardt@amd.com#
3187816Ssteve.reinhardt@amd.com# Set up global sticky variables... these are common to an entire build
3197816Ssteve.reinhardt@amd.com# tree (not specific to a particular build like ALPHA_SE)
3207756SAli.Saidi@ARM.com#
3217756SAli.Saidi@ARM.com
3229227Sandreas.hansson@arm.com# Variable validators & converters for global sticky variables
3239227Sandreas.hansson@arm.comdef PathListMakeAbsolute(val):
3249227Sandreas.hansson@arm.com    if not val:
3259227Sandreas.hansson@arm.com        return val
3269590Sandreas@sandberg.pp.se    f = lambda p: abspath(expanduser(p))
3279590Sandreas@sandberg.pp.se    return ':'.join(map(f, val.split(':')))
3289590Sandreas@sandberg.pp.se
3299590Sandreas@sandberg.pp.sedef PathListAllExist(key, val, env):
3309590Sandreas@sandberg.pp.se    if not val:
3319590Sandreas@sandberg.pp.se        return
3326654Snate@binkert.org    paths = val.split(':')
3336654Snate@binkert.org    for path in paths:
3345871Snate@binkert.org        if not isdir(path):
3356121Snate@binkert.org            raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
3368946Sandreas.hansson@arm.com
3379419Sandreas.hansson@arm.comglobal_sticky_vars_file = joinpath(build_root, 'variables.global')
3383940Ssaidi@eecs.umich.edu
3393918Ssaidi@eecs.umich.eduglobal_sticky_vars = Variables(global_sticky_vars_file, args=ARGUMENTS)
3403918Ssaidi@eecs.umich.edu
3411858SN/Aglobal_sticky_vars.AddVariables(
3429556Sandreas.hansson@arm.com    ('CC', 'C compiler', environ.get('CC', env['CC'])),
3439556Sandreas.hansson@arm.com    ('CXX', 'C++ compiler', environ.get('CXX', env['CXX'])),
3449556Sandreas.hansson@arm.com    ('BATCH', 'Use batch pool for build and tests', False),
3459556Sandreas.hansson@arm.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
34611294Sandreas.hansson@arm.com    ('EXTRAS', 'Add Extra directories to the compilation', '',
34711294Sandreas.hansson@arm.com     PathListAllExist, PathListMakeAbsolute)
34811294Sandreas.hansson@arm.com    )    
34911294Sandreas.hansson@arm.com
35010878Sandreas.hansson@arm.com# base help text
35110878Sandreas.hansson@arm.comhelp_text = '''
35211811Sbaz21@cam.ac.ukUsage: scons [scons options] [build options] [target(s)]
35311811Sbaz21@cam.ac.uk
35411811Sbaz21@cam.ac.ukGlobal sticky options:
35511982Sgabeblack@google.com'''
35611982Sgabeblack@google.com
35711982Sgabeblack@google.comhelp_text += global_sticky_vars.GenerateHelpText(env)
35811982Sgabeblack@google.com
35911992Sgabeblack@google.com# Update env with values from ARGUMENTS & file global_sticky_vars_file
36011982Sgabeblack@google.comglobal_sticky_vars.Update(env)
36111982Sgabeblack@google.com
36212305Sgabeblack@google.com# Save sticky variable settings back to current variables file
36312305Sgabeblack@google.comglobal_sticky_vars.Save(global_sticky_vars_file, env)
36412305Sgabeblack@google.com
36512305Sgabeblack@google.com# Parse EXTRAS variable to build list of all directories where we're
36612305Sgabeblack@google.com# look for sources etc.  This list is exported as base_dir_list.
36712305Sgabeblack@google.combase_dir = env.srcdir.abspath
36812305Sgabeblack@google.comif env['EXTRAS']:
3699556Sandreas.hansson@arm.com    extras_dir_list = env['EXTRAS'].split(':')
3709556Sandreas.hansson@arm.comelse:
3719556Sandreas.hansson@arm.com    extras_dir_list = []
3729556Sandreas.hansson@arm.com
3739556Sandreas.hansson@arm.comExport('base_dir')
3749556Sandreas.hansson@arm.comExport('extras_dir_list')
3759556Sandreas.hansson@arm.com
3769556Sandreas.hansson@arm.com# the ext directory should be on the #includes path
3779556Sandreas.hansson@arm.comenv.Append(CPPPATH=[Dir('ext')])
3789556Sandreas.hansson@arm.com
3799556Sandreas.hansson@arm.com# M5_PLY is used by isa_parser.py to find the PLY package.
3809556Sandreas.hansson@arm.comenv.Append(ENV = { 'M5_PLY' : Dir('ext/ply').abspath })
3819556Sandreas.hansson@arm.com
3829556Sandreas.hansson@arm.comCXX_version = read_command([env['CXX'],'--version'], exception=False)
3839556Sandreas.hansson@arm.comCXX_V = read_command([env['CXX'],'-V'], exception=False)
3849556Sandreas.hansson@arm.com
3859556Sandreas.hansson@arm.comenv['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3869556Sandreas.hansson@arm.comenv['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
3879556Sandreas.hansson@arm.comenv['ICC'] = CXX_V and CXX_V.find('Intel') >= 0
3886121Snate@binkert.orgif env['GCC'] + env['SUNCC'] + env['ICC'] > 1:
38911500Sandreas.hansson@arm.com    print 'Error: How can we have two at the same time?'
39010238Sandreas.hansson@arm.com    Exit(1)
39110878Sandreas.hansson@arm.com
3929420Sandreas.hansson@arm.com# Set up default C++ compiler flags
39311500Sandreas.hansson@arm.comif env['GCC']:
39411500Sandreas.hansson@arm.com    env.Append(CCFLAGS='-pipe')
3959420Sandreas.hansson@arm.com    env.Append(CCFLAGS='-fno-strict-aliasing')
3969420Sandreas.hansson@arm.com    env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
3979420Sandreas.hansson@arm.com    env.Append(CXXFLAGS='-Wno-deprecated')
3989420Sandreas.hansson@arm.comelif env['ICC']:
3999420Sandreas.hansson@arm.com    pass #Fix me... add warning flags once we clean up icc warnings
40012063Sgabeblack@google.comelif env['SUNCC']:
40112063Sgabeblack@google.com    env.Append(CCFLAGS='-Qoption ccfe')
40212063Sgabeblack@google.com    env.Append(CCFLAGS='-features=gcc')
40312063Sgabeblack@google.com    env.Append(CCFLAGS='-features=extensions')
40412063Sgabeblack@google.com    env.Append(CCFLAGS='-library=stlport4')
40512063Sgabeblack@google.com    env.Append(CCFLAGS='-xar')
40612063Sgabeblack@google.com    #env.Append(CCFLAGS='-instances=semiexplicit')
40712063Sgabeblack@google.comelse:
40812063Sgabeblack@google.com    print 'Error: Don\'t know what compiler options to use for your compiler.'
40912063Sgabeblack@google.com    print '       Please fix SConstruct and src/SConscript and try again.'
41012063Sgabeblack@google.com    Exit(1)
41112063Sgabeblack@google.com
41212063Sgabeblack@google.com# Do this after we save setting back, or else we'll tack on an
41312063Sgabeblack@google.com# extra 'qdo' every time we run scons.
41412063Sgabeblack@google.comif env['BATCH']:
41512063Sgabeblack@google.com    env['CC']     = env['BATCH_CMD'] + ' ' + env['CC']
41612063Sgabeblack@google.com    env['CXX']    = env['BATCH_CMD'] + ' ' + env['CXX']
41712063Sgabeblack@google.com    env['AS']     = env['BATCH_CMD'] + ' ' + env['AS']
41812063Sgabeblack@google.com    env['AR']     = env['BATCH_CMD'] + ' ' + env['AR']
41912063Sgabeblack@google.com    env['RANLIB'] = env['BATCH_CMD'] + ' ' + env['RANLIB']
42012063Sgabeblack@google.com
42112063Sgabeblack@google.comif sys.platform == 'cygwin':
42210264Sandreas.hansson@arm.com    # cygwin has some header file issues...
42310264Sandreas.hansson@arm.com    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
42410264Sandreas.hansson@arm.com
42510264Sandreas.hansson@arm.com# Check for SWIG
42611925Sgabeblack@google.comif not env.has_key('SWIG'):
42711925Sgabeblack@google.com    print 'Error: SWIG utility not found.'
42811500Sandreas.hansson@arm.com    print '       Please install (see http://www.swig.org) and retry.'
42910264Sandreas.hansson@arm.com    Exit(1)
43011500Sandreas.hansson@arm.com
43111500Sandreas.hansson@arm.com# Check for appropriate SWIG version
43211500Sandreas.hansson@arm.comswig_version = read_command(('swig', '-version'), exception='').split()
43311500Sandreas.hansson@arm.com# First 3 words should be "SWIG Version x.y.z"
43410866Sandreas.hansson@arm.comif len(swig_version) < 3 or \
43511500Sandreas.hansson@arm.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
43611500Sandreas.hansson@arm.com    print 'Error determining SWIG version.'
43711500Sandreas.hansson@arm.com    Exit(1)
43811500Sandreas.hansson@arm.com
43911500Sandreas.hansson@arm.commin_swig_version = '1.3.28'
44011500Sandreas.hansson@arm.comif compare_versions(swig_version[2], min_swig_version) < 0:
44111500Sandreas.hansson@arm.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
44210264Sandreas.hansson@arm.com    print '       Installed version:', swig_version[2]
44310457Sandreas.hansson@arm.com    Exit(1)
44410457Sandreas.hansson@arm.com
44510457Sandreas.hansson@arm.com# Set up SWIG flags & scanner
44610457Sandreas.hansson@arm.comswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
44710457Sandreas.hansson@arm.comenv.Append(SWIGFLAGS=swig_flags)
44810457Sandreas.hansson@arm.com
44910457Sandreas.hansson@arm.com# filter out all existing swig scanners, they mess up the dependency
45010457Sandreas.hansson@arm.com# stuff for some reason
45110457Sandreas.hansson@arm.comscanners = []
45212063Sgabeblack@google.comfor scanner in env['SCANNERS']:
45312063Sgabeblack@google.com    skeys = scanner.skeys
45412063Sgabeblack@google.com    if skeys == '.i':
45512063Sgabeblack@google.com        continue
45612063Sgabeblack@google.com
45712063Sgabeblack@google.com    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
45812063Sgabeblack@google.com        continue
45912063Sgabeblack@google.com
46012063Sgabeblack@google.com    scanners.append(scanner)
46112063Sgabeblack@google.com
46212063Sgabeblack@google.com# add the new swig scanner that we like better
46310238Sandreas.hansson@arm.comfrom SCons.Scanner import ClassicCPP as CPPScanner
46410238Sandreas.hansson@arm.comswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
46510238Sandreas.hansson@arm.comscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
46612063Sgabeblack@google.com
46710238Sandreas.hansson@arm.com# replace the scanners list that has what we want
46810238Sandreas.hansson@arm.comenv['SCANNERS'] = scanners
46910416Sandreas.hansson@arm.com
47010238Sandreas.hansson@arm.com# Add a custom Check function to the Configure context so that we can
4719227Sandreas.hansson@arm.com# figure out if the compiler adds leading underscores to global
47210238Sandreas.hansson@arm.com# variables.  This is needed for the autogenerated asm files that we
47310416Sandreas.hansson@arm.com# use for embedding the python code.
47410416Sandreas.hansson@arm.comdef CheckLeading(context):
4759227Sandreas.hansson@arm.com    context.Message("Checking for leading underscore in global variables...")
4769590Sandreas@sandberg.pp.se    # 1) Define a global variable called x from asm so the C compiler
4779590Sandreas@sandberg.pp.se    #    won't change the symbol at all.
4789590Sandreas@sandberg.pp.se    # 2) Declare that variable.
47911497SMatteo.Andreozzi@arm.com    # 3) Use the variable
48011497SMatteo.Andreozzi@arm.com    #
48111497SMatteo.Andreozzi@arm.com    # If the compiler prepends an underscore, this will successfully
48211497SMatteo.Andreozzi@arm.com    # link because the external symbol 'x' will be called '_x' which
48312304Sgabeblack@google.com    # was defined by the asm statement.  If the compiler does not
48412304Sgabeblack@google.com    # prepend an underscore, this will not successfully link because
48512304Sgabeblack@google.com    # '_x' will have been defined by assembly, while the C portion of
48612304Sgabeblack@google.com    # the code will be trying to use 'x'
48712304Sgabeblack@google.com    ret = context.TryLink('''
48812304Sgabeblack@google.com        asm(".globl _x; _x: .byte 0");
48912304Sgabeblack@google.com        extern int x;
49012304Sgabeblack@google.com        int main() { return x; }
49112304Sgabeblack@google.com        ''', extension=".c")
49212304Sgabeblack@google.com    context.env.Append(LEADING_UNDERSCORE=ret)
49312304Sgabeblack@google.com    context.Result(ret)
49412304Sgabeblack@google.com    return ret
49512304Sgabeblack@google.com
49612304Sgabeblack@google.com# Platform-specific configuration.  Note again that we assume that all
49712304Sgabeblack@google.com# builds under a given build root run on the same host platform.
49812304Sgabeblack@google.comconf = Configure(env,
49912304Sgabeblack@google.com                 conf_dir = joinpath(build_root, '.scons_config'),
50012304Sgabeblack@google.com                 log_file = joinpath(build_root, 'scons_config.log'),
50112304Sgabeblack@google.com                 custom_tests = { 'CheckLeading' : CheckLeading })
5028737Skoansin.tan@gmail.com
50310878Sandreas.hansson@arm.com# Check for leading underscores.  Don't really need to worry either
50411500Sandreas.hansson@arm.com# way so don't need to check the return code.
5059420Sandreas.hansson@arm.comconf.CheckLeading()
5068737Skoansin.tan@gmail.com
50710106SMitch.Hayenga@arm.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
5088737Skoansin.tan@gmail.comtry:
5098737Skoansin.tan@gmail.com    import platform
51010878Sandreas.hansson@arm.com    uname = platform.uname()
51110878Sandreas.hansson@arm.com    if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
5128737Skoansin.tan@gmail.com        if int(read_command('sysctl -n hw.cpu64bit_capable')[0]):
5138737Skoansin.tan@gmail.com            env.Append(CCFLAGS='-arch x86_64')
5148737Skoansin.tan@gmail.com            env.Append(CFLAGS='-arch x86_64')
5158737Skoansin.tan@gmail.com            env.Append(LINKFLAGS='-arch x86_64')
5168737Skoansin.tan@gmail.com            env.Append(ASFLAGS='-arch x86_64')
5178737Skoansin.tan@gmail.comexcept:
51811294Sandreas.hansson@arm.com    pass
5199556Sandreas.hansson@arm.com
5209556Sandreas.hansson@arm.com# Recent versions of scons substitute a "Null" object for Configure()
5219556Sandreas.hansson@arm.com# when configuration isn't necessary, e.g., if the "--help" option is
52211294Sandreas.hansson@arm.com# present.  Unfortuantely this Null object always returns false,
52310278SAndreas.Sandberg@ARM.com# breaking all our configuration checks.  We replace it with our own
52410278SAndreas.Sandberg@ARM.com# more optimistic null object that returns True instead.
52510278SAndreas.Sandberg@ARM.comif not conf:
52610278SAndreas.Sandberg@ARM.com    def NullCheck(*args, **kwargs):
52710278SAndreas.Sandberg@ARM.com        return True
52810278SAndreas.Sandberg@ARM.com
5299556Sandreas.hansson@arm.com    class NullConf:
5309590Sandreas@sandberg.pp.se        def __init__(self, env):
5319590Sandreas@sandberg.pp.se            self.env = env
5329420Sandreas.hansson@arm.com        def Finish(self):
5339846Sandreas.hansson@arm.com            return self.env
5349846Sandreas.hansson@arm.com        def __getattr__(self, mname):
5359846Sandreas.hansson@arm.com            return NullCheck
5369846Sandreas.hansson@arm.com
5378946Sandreas.hansson@arm.com    conf = NullConf(env)
53811811Sbaz21@cam.ac.uk
53911811Sbaz21@cam.ac.uk# Find Python include and library directories for embedding the
54011811Sbaz21@cam.ac.uk# interpreter.  For consistency, we will use the same Python
54111811Sbaz21@cam.ac.uk# installation used to run scons (and thus this script).  If you want
54212304Sgabeblack@google.com# to link in an alternate version, see above for instructions on how
54312304Sgabeblack@google.com# to invoke scons with a different copy of the Python interpreter.
54412304Sgabeblack@google.comfrom distutils import sysconfig
54512304Sgabeblack@google.com
54612304Sgabeblack@google.compy_getvar = sysconfig.get_config_var
54712304Sgabeblack@google.com
54812304Sgabeblack@google.compy_version = 'python' + py_getvar('VERSION')
54912304Sgabeblack@google.com
55012304Sgabeblack@google.compy_general_include = sysconfig.get_python_inc()
55112304Sgabeblack@google.compy_platform_include = sysconfig.get_python_inc(plat_specific=True)
55212304Sgabeblack@google.compy_includes = [ py_general_include ]
55312304Sgabeblack@google.comif py_platform_include != py_general_include:
55412304Sgabeblack@google.com    py_includes.append(py_platform_include)
55512304Sgabeblack@google.com
55612304Sgabeblack@google.compy_lib_path = [ py_getvar('LIBDIR') ]
55712304Sgabeblack@google.com# add the prefix/lib/pythonX.Y/config dir, but only if there is no
5583918Ssaidi@eecs.umich.edu# shared library in prefix/lib/.
5599068SAli.Saidi@ARM.comif not py_getvar('Py_ENABLE_SHARED'):
5609068SAli.Saidi@ARM.com    py_lib_path.append('-L' + py_getvar('LIBPL'))
5619068SAli.Saidi@ARM.com
5629068SAli.Saidi@ARM.compy_libs = []
5639068SAli.Saidi@ARM.comfor lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
5649068SAli.Saidi@ARM.com    if lib not in py_libs:
5659068SAli.Saidi@ARM.com        py_libs.append(lib)
5669068SAli.Saidi@ARM.compy_libs.append('-l' + py_version)
5679068SAli.Saidi@ARM.com
5689419Sandreas.hansson@arm.comenv.Append(CPPPATH=py_includes)
5699068SAli.Saidi@ARM.comenv.Append(LIBPATH=py_lib_path)
5709068SAli.Saidi@ARM.com
5719068SAli.Saidi@ARM.com# verify that this stuff works
5729068SAli.Saidi@ARM.comif not conf.CheckHeader('Python.h', '<>'):
5739068SAli.Saidi@ARM.com    print "Error: can't find Python.h header in", py_includes
5749068SAli.Saidi@ARM.com    Exit(1)
5753918Ssaidi@eecs.umich.edu
5763918Ssaidi@eecs.umich.edufor lib in py_libs:
5776157Snate@binkert.org    assert lib.startswith('-l')
5786157Snate@binkert.org    lib = lib[2:]
5796157Snate@binkert.org    if not conf.CheckLib(lib):
5806157Snate@binkert.org        print "Error: can't find library %s required by python" % lib
5815397Ssaidi@eecs.umich.edu        Exit(1)
5825397Ssaidi@eecs.umich.edu
5836121Snate@binkert.org# On Solaris you need to use libsocket for socket ops
5846121Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
5856121Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
5866121Snate@binkert.org       print "Can't find library with socket calls (e.g. accept())"
5876121Snate@binkert.org       Exit(1)
5886121Snate@binkert.org
5895397Ssaidi@eecs.umich.edu# Check for zlib.  If the check passes, libz will be automatically
5901851SN/A# added to the LIBS environment variable.
5911851SN/Aif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
5927739Sgblack@eecs.umich.edu    print 'Error: did not find needed zlib compression library '\
593955SN/A          'and/or zlib.h header file.'
5949396Sandreas.hansson@arm.com    print '       Please install zlib and try again.'
5959396Sandreas.hansson@arm.com    Exit(1)
5969396Sandreas.hansson@arm.com
5979396Sandreas.hansson@arm.com# Check for <fenv.h> (C99 FP environment control)
5989396Sandreas.hansson@arm.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
5999396Sandreas.hansson@arm.comif not have_fenv:
6009396Sandreas.hansson@arm.com    print "Warning: Header file <fenv.h> not found."
6019396Sandreas.hansson@arm.com    print "         This host has no IEEE FP rounding mode control."
6029396Sandreas.hansson@arm.com
6039396Sandreas.hansson@arm.com######################################################################
6049396Sandreas.hansson@arm.com#
6059396Sandreas.hansson@arm.com# Check for mysql.
6069396Sandreas.hansson@arm.com#
6079396Sandreas.hansson@arm.commysql_config = WhereIs('mysql_config')
6089396Sandreas.hansson@arm.comhave_mysql = bool(mysql_config)
6099396Sandreas.hansson@arm.com
6109477Sandreas.hansson@arm.com# Check MySQL version.
6119477Sandreas.hansson@arm.comif have_mysql:
6129477Sandreas.hansson@arm.com    mysql_version = read_command(mysql_config + ' --version')
6139477Sandreas.hansson@arm.com    min_mysql_version = '4.1'
6149477Sandreas.hansson@arm.com    if compare_versions(mysql_version, min_mysql_version) < 0:
6159477Sandreas.hansson@arm.com        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
6169477Sandreas.hansson@arm.com        print '         Version', mysql_version, 'detected.'
6179477Sandreas.hansson@arm.com        have_mysql = False
6189477Sandreas.hansson@arm.com
6199477Sandreas.hansson@arm.com# Set up mysql_config commands.
6209477Sandreas.hansson@arm.comif have_mysql:
6219477Sandreas.hansson@arm.com    mysql_config_include = mysql_config + ' --include'
6229477Sandreas.hansson@arm.com    if os.system(mysql_config_include + ' > /dev/null') != 0:
6239477Sandreas.hansson@arm.com        # older mysql_config versions don't support --include, use
6249477Sandreas.hansson@arm.com        # --cflags instead
6259477Sandreas.hansson@arm.com        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
6269477Sandreas.hansson@arm.com    # This seems to work in all versions
6279477Sandreas.hansson@arm.com    mysql_config_libs = mysql_config + ' --libs'
6289477Sandreas.hansson@arm.com
6299477Sandreas.hansson@arm.com######################################################################
6309477Sandreas.hansson@arm.com#
6319477Sandreas.hansson@arm.com# Finish the configuration
6329396Sandreas.hansson@arm.com#
6332667Sstever@eecs.umich.eduenv = conf.Finish()
63410710Sandreas.hansson@arm.com
63510710Sandreas.hansson@arm.com######################################################################
63610710Sandreas.hansson@arm.com#
63711811Sbaz21@cam.ac.uk# Collect all non-global variables
63811811Sbaz21@cam.ac.uk#
63911811Sbaz21@cam.ac.uk
64011811Sbaz21@cam.ac.ukExport('env')
64111811Sbaz21@cam.ac.uk
64211811Sbaz21@cam.ac.uk# Define the universe of supported ISAs
64310710Sandreas.hansson@arm.comall_isa_list = [ ]
64410710Sandreas.hansson@arm.comExport('all_isa_list')
64510710Sandreas.hansson@arm.com
64610710Sandreas.hansson@arm.com# Define the universe of supported CPU models
64710384SCurtis.Dunham@arm.comall_cpu_list = [ ]
6489986Sandreas@sandberg.pp.sedefault_cpus = [ ]
6499986Sandreas@sandberg.pp.seExport('all_cpu_list', 'default_cpus')
6509986Sandreas@sandberg.pp.se
6519986Sandreas@sandberg.pp.se# Sticky variables get saved in the variables file so they persist from
6529986Sandreas@sandberg.pp.se# one invocation to the next (unless overridden, in which case the new
6539986Sandreas@sandberg.pp.se# value becomes sticky).
6549986Sandreas@sandberg.pp.sesticky_vars = Variables(args=ARGUMENTS)
6559986Sandreas@sandberg.pp.seExport('sticky_vars')
6569986Sandreas@sandberg.pp.se
6579986Sandreas@sandberg.pp.se# Non-sticky variables only apply to the current build.
6589986Sandreas@sandberg.pp.senonsticky_vars = Variables(args=ARGUMENTS)
6599986Sandreas@sandberg.pp.seExport('nonsticky_vars')
6609986Sandreas@sandberg.pp.se
6619986Sandreas@sandberg.pp.se# Walk the tree and execute all SConsopts scripts that wil add to the
6629986Sandreas@sandberg.pp.se# above variables
6639986Sandreas@sandberg.pp.sefor bdir in [ base_dir ] + extras_dir_list:
6649986Sandreas@sandberg.pp.se    for root, dirs, files in os.walk(bdir):
6659986Sandreas@sandberg.pp.se        if 'SConsopts' in files:
6669986Sandreas@sandberg.pp.se            print "Reading", joinpath(root, 'SConsopts')
6679986Sandreas@sandberg.pp.se            SConscript(joinpath(root, 'SConsopts'))
6682638Sstever@eecs.umich.edu
6692638Sstever@eecs.umich.eduall_isa_list.sort()
6706121Snate@binkert.orgall_cpu_list.sort()
6713716Sstever@eecs.umich.edudefault_cpus.sort()
6725522Snate@binkert.org
6739986Sandreas@sandberg.pp.sesticky_vars.AddVariables(
6749986Sandreas@sandberg.pp.se    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
6759986Sandreas@sandberg.pp.se    BoolVariable('FULL_SYSTEM', 'Full-system support', False),
6765522Snate@binkert.org    ListVariable('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
6775227Ssaidi@eecs.umich.edu    BoolVariable('NO_FAST_ALLOC', 'Disable fast object allocator', False),
6785227Ssaidi@eecs.umich.edu    BoolVariable('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
6795227Ssaidi@eecs.umich.edu                 False),
6805227Ssaidi@eecs.umich.edu    BoolVariable('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
6816654Snate@binkert.org                 False),
6826654Snate@binkert.org    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
6837769SAli.Saidi@ARM.com                 False),
6847769SAli.Saidi@ARM.com    BoolVariable('SS_COMPATIBLE_FP',
6857769SAli.Saidi@ARM.com                 'Make floating-point results compatible with SimpleScalar',
6867769SAli.Saidi@ARM.com                 False),
6875227Ssaidi@eecs.umich.edu    BoolVariable('USE_SSE2',
6885227Ssaidi@eecs.umich.edu                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
6895227Ssaidi@eecs.umich.edu                 False),
6905204Sstever@gmail.com    BoolVariable('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
6915204Sstever@gmail.com    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
6925204Sstever@gmail.com    BoolVariable('USE_CHECKER', 'Use checker for detailed CPU models', False),
6935204Sstever@gmail.com    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
6945204Sstever@gmail.com    )
6955204Sstever@gmail.com
6965204Sstever@gmail.comnonsticky_vars.AddVariables(
6975204Sstever@gmail.com    BoolVariable('update_ref', 'Update test reference outputs', False)
6985204Sstever@gmail.com    )
6995204Sstever@gmail.com
7005204Sstever@gmail.com# These variables get exported to #defines in config/*.hh (see src/SConscript).
7015204Sstever@gmail.comenv.ExportVariables = ['FULL_SYSTEM', 'ALPHA_TLASER', 'USE_FENV', \
7025204Sstever@gmail.com                       'USE_MYSQL', 'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', \
7035204Sstever@gmail.com                       'FAST_ALLOC_STATS', 'SS_COMPATIBLE_FP', \
7045204Sstever@gmail.com                       'USE_CHECKER', 'TARGET_ISA', 'CP_ANNOTATE']
7055204Sstever@gmail.com
7065204Sstever@gmail.com###################################################
7076121Snate@binkert.org#
7085204Sstever@gmail.com# Define a SCons builder for configuration flag headers.
7097727SAli.Saidi@ARM.com#
7107727SAli.Saidi@ARM.com###################################################
7117727SAli.Saidi@ARM.com
7127727SAli.Saidi@ARM.com# This function generates a config header file that #defines the
7137727SAli.Saidi@ARM.com# variable symbol to the current variable setting (0 or 1).  The source
71411988Sandreas.sandberg@arm.com# operands are the name of the variable and a Value node containing the
71511988Sandreas.sandberg@arm.com# value of the variable.
71610453SAndrew.Bardsley@arm.comdef build_config_file(target, source, env):
71710453SAndrew.Bardsley@arm.com    (variable, value) = [s.get_contents() for s in source]
71810453SAndrew.Bardsley@arm.com    f = file(str(target[0]), 'w')
71910453SAndrew.Bardsley@arm.com    print >> f, '#define', variable, value
72010453SAndrew.Bardsley@arm.com    f.close()
72110453SAndrew.Bardsley@arm.com    return None
72210453SAndrew.Bardsley@arm.com
72310453SAndrew.Bardsley@arm.com# Generate the message to be printed when building the config file.
72410453SAndrew.Bardsley@arm.comdef build_config_file_string(target, source, env):
72510453SAndrew.Bardsley@arm.com    (variable, value) = [s.get_contents() for s in source]
72610160Sandreas.hansson@arm.com    return "Defining %s as %s in %s." % (variable, value, target[0])
72710453SAndrew.Bardsley@arm.com
72810453SAndrew.Bardsley@arm.com# Combine the two functions into a scons Action object.
72910453SAndrew.Bardsley@arm.comconfig_action = Action(build_config_file, build_config_file_string)
73010453SAndrew.Bardsley@arm.com
73110453SAndrew.Bardsley@arm.com# The emitter munges the source & target node lists to reflect what
73210453SAndrew.Bardsley@arm.com# we're really doing.
73310453SAndrew.Bardsley@arm.comdef config_emitter(target, source, env):
73410453SAndrew.Bardsley@arm.com    # extract variable name from Builder arg
7359812Sandreas.hansson@arm.com    variable = str(target[0])
73610453SAndrew.Bardsley@arm.com    # True target is config header file
73710453SAndrew.Bardsley@arm.com    target = joinpath('config', variable.lower() + '.hh')
73810453SAndrew.Bardsley@arm.com    val = env[variable]
73910453SAndrew.Bardsley@arm.com    if isinstance(val, bool):
74010453SAndrew.Bardsley@arm.com        # Force value to 0/1
74110453SAndrew.Bardsley@arm.com        val = int(val)
74210453SAndrew.Bardsley@arm.com    elif isinstance(val, str):
74310453SAndrew.Bardsley@arm.com        val = '"' + val + '"'
74410453SAndrew.Bardsley@arm.com
74510453SAndrew.Bardsley@arm.com    # Sources are variable name & value (packaged in SCons Value nodes)
74610453SAndrew.Bardsley@arm.com    return ([target], [Value(variable), Value(val)])
74710453SAndrew.Bardsley@arm.com
7487727SAli.Saidi@ARM.comconfig_builder = Builder(emitter = config_emitter, action = config_action)
74910453SAndrew.Bardsley@arm.com
75010453SAndrew.Bardsley@arm.comenv.Append(BUILDERS = { 'ConfigFile' : config_builder })
75110453SAndrew.Bardsley@arm.com
75210453SAndrew.Bardsley@arm.com# libelf build is shared across all configs in the build root.
75310453SAndrew.Bardsley@arm.comenv.SConscript('ext/libelf/SConscript',
7543118Sstever@eecs.umich.edu               variant_dir = joinpath(build_root, 'libelf'))
75510453SAndrew.Bardsley@arm.com
75610453SAndrew.Bardsley@arm.com# gzstream build is shared across all configs in the build root.
75710453SAndrew.Bardsley@arm.comenv.SConscript('ext/gzstream/SConscript',
75810453SAndrew.Bardsley@arm.com               variant_dir = joinpath(build_root, 'gzstream'))
7593118Sstever@eecs.umich.edu
7603483Ssaidi@eecs.umich.edu###################################################
7613494Ssaidi@eecs.umich.edu#
7623494Ssaidi@eecs.umich.edu# This function is used to set up a directory with switching headers
7633483Ssaidi@eecs.umich.edu#
7643483Ssaidi@eecs.umich.edu###################################################
7653483Ssaidi@eecs.umich.edu
7663053Sstever@eecs.umich.eduenv['ALL_ISA_LIST'] = all_isa_list
7673053Sstever@eecs.umich.edudef make_switching_dir(dname, switch_headers, env):
7683918Ssaidi@eecs.umich.edu    # Generate the header.  target[0] is the full path of the output
7693053Sstever@eecs.umich.edu    # header to generate.  'source' is a dummy variable, since we get the
7703053Sstever@eecs.umich.edu    # list of ISAs from env['ALL_ISA_LIST'].
7713053Sstever@eecs.umich.edu    def gen_switch_hdr(target, source, env):
7723053Sstever@eecs.umich.edu        fname = str(target[0])
7733053Sstever@eecs.umich.edu        bname = basename(fname)
7749396Sandreas.hansson@arm.com        f = open(fname, 'w')
7759396Sandreas.hansson@arm.com        f.write('#include "arch/isa_specific.hh"\n')
7769396Sandreas.hansson@arm.com        cond = '#if'
7779396Sandreas.hansson@arm.com        for isa in all_isa_list:
7789396Sandreas.hansson@arm.com            f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
7799396Sandreas.hansson@arm.com                    % (cond, isa.upper(), dname, isa, bname))
7809396Sandreas.hansson@arm.com            cond = '#elif'
7819396Sandreas.hansson@arm.com        f.write('#else\n#error "THE_ISA not set"\n#endif\n')
7829396Sandreas.hansson@arm.com        f.close()
7839477Sandreas.hansson@arm.com        return 0
7849396Sandreas.hansson@arm.com
7859477Sandreas.hansson@arm.com    # String to print when generating header
7869477Sandreas.hansson@arm.com    def gen_switch_hdr_string(target, source, env):
7879477Sandreas.hansson@arm.com        return "Generating switch header " + str(target[0])
7889477Sandreas.hansson@arm.com
7899396Sandreas.hansson@arm.com    # Build SCons Action object. 'varlist' specifies env vars that this
7907840Snate@binkert.org    # action depends on; when env['ALL_ISA_LIST'] changes these actions
7917865Sgblack@eecs.umich.edu    # should get re-executed.
7927865Sgblack@eecs.umich.edu    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
7937865Sgblack@eecs.umich.edu                               varlist=['ALL_ISA_LIST'])
7947865Sgblack@eecs.umich.edu
7957865Sgblack@eecs.umich.edu    # Instantiate actions for each header
7967840Snate@binkert.org    for hdr in switch_headers:
7979900Sandreas@sandberg.pp.se        env.Command(hdr, [], switch_hdr_action)
7989900Sandreas@sandberg.pp.seExport('make_switching_dir')
7999900Sandreas@sandberg.pp.se
8009900Sandreas@sandberg.pp.se###################################################
80110456SCurtis.Dunham@arm.com#
80210456SCurtis.Dunham@arm.com# Define build environments for selected configurations.
80310456SCurtis.Dunham@arm.com#
80410456SCurtis.Dunham@arm.com###################################################
80510456SCurtis.Dunham@arm.com
80610456SCurtis.Dunham@arm.com# rename base env
80710456SCurtis.Dunham@arm.combase_env = env
80810456SCurtis.Dunham@arm.com
80910456SCurtis.Dunham@arm.comfor variant_path in variant_paths:
81010456SCurtis.Dunham@arm.com    print "Building in", variant_path
8119045SAli.Saidi@ARM.com
81211235Sandreas.sandberg@arm.com    # Make a copy of the build-root environment to use for this config.
81311235Sandreas.sandberg@arm.com    env = base_env.Clone()
81411235Sandreas.sandberg@arm.com    env['BUILDDIR'] = variant_path
81511235Sandreas.sandberg@arm.com
81611235Sandreas.sandberg@arm.com    # variant_dir is the tail component of build path, and is used to
81712485Sjang.hanhwi@gmail.com    # determine the build parameters (e.g., 'ALPHA_SE')
81812485Sjang.hanhwi@gmail.com    (build_root, variant_dir) = splitpath(variant_path)
81912485Sjang.hanhwi@gmail.com
82011235Sandreas.sandberg@arm.com    # Set env variables according to the build directory config.
82111811Sbaz21@cam.ac.uk    sticky_vars.files = []
82212485Sjang.hanhwi@gmail.com    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
82311811Sbaz21@cam.ac.uk    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
82411811Sbaz21@cam.ac.uk    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
82511811Sbaz21@cam.ac.uk    current_vars_file = joinpath(build_root, 'variables', variant_dir)
82611235Sandreas.sandberg@arm.com    if isfile(current_vars_file):
82711235Sandreas.sandberg@arm.com        sticky_vars.files.append(current_vars_file)
82811235Sandreas.sandberg@arm.com        print "Using saved variables file %s" % current_vars_file
82911235Sandreas.sandberg@arm.com    else:
83011235Sandreas.sandberg@arm.com        # Build dir-specific variables file doesn't exist.
83111235Sandreas.sandberg@arm.com
83211235Sandreas.sandberg@arm.com        # Make sure the directory is there so we can create it later
8337840Snate@binkert.org        opt_dir = dirname(current_vars_file)
8347840Snate@binkert.org        if not isdir(opt_dir):
8357840Snate@binkert.org            mkdir(opt_dir)
8361858SN/A
8371858SN/A        # Get default build variables from source tree.  Variables are
8381858SN/A        # normally determined by name of $VARIANT_DIR, but can be
8391858SN/A        # overriden by 'default=' arg on command line.
8401858SN/A        default_vars_file = joinpath('build_opts',
8411858SN/A                                     ARGUMENTS.get('default', variant_dir))
84212230Sgiacomo.travaglini@arm.com        if isfile(default_vars_file):
84312230Sgiacomo.travaglini@arm.com            sticky_vars.files.append(default_vars_file)
84412230Sgiacomo.travaglini@arm.com            print "Variables file %s not found,\n  using defaults in %s" \
84512230Sgiacomo.travaglini@arm.com                  % (current_vars_file, default_vars_file)
84612230Sgiacomo.travaglini@arm.com        else:
84712230Sgiacomo.travaglini@arm.com            print "Error: cannot find variables file %s or %s" \
84812230Sgiacomo.travaglini@arm.com                  % (current_vars_file, default_vars_file)
84912230Sgiacomo.travaglini@arm.com            Exit(1)
8509903Sandreas.hansson@arm.com
8519903Sandreas.hansson@arm.com    # Apply current variable settings to env
8529903Sandreas.hansson@arm.com    sticky_vars.Update(env)
8539903Sandreas.hansson@arm.com    nonsticky_vars.Update(env)
85410841Sandreas.sandberg@arm.com
8559651SAndreas.Sandberg@ARM.com    help_text += "\nSticky variables for %s:\n" % variant_dir \
8569903Sandreas.hansson@arm.com                 + sticky_vars.GenerateHelpText(env) \
8579651SAndreas.Sandberg@ARM.com                 + "\nNon-sticky variables for %s:\n" % variant_dir \
8589651SAndreas.Sandberg@ARM.com                 + nonsticky_vars.GenerateHelpText(env)
85912056Sgabeblack@google.com
86012056Sgabeblack@google.com    # Process variable settings.
86112056Sgabeblack@google.com
86212056Sgabeblack@google.com    if not have_fenv and env['USE_FENV']:
86312056Sgabeblack@google.com        print "Warning: <fenv.h> not available; " \
86410841Sandreas.sandberg@arm.com              "forcing USE_FENV to False in", variant_dir + "."
86510841Sandreas.sandberg@arm.com        env['USE_FENV'] = False
86610841Sandreas.sandberg@arm.com
86710841Sandreas.sandberg@arm.com    if not env['USE_FENV']:
86810841Sandreas.sandberg@arm.com        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
86910841Sandreas.sandberg@arm.com        print "         FP results may deviate slightly from other platforms."
8709651SAndreas.Sandberg@ARM.com
8719651SAndreas.Sandberg@ARM.com    if env['EFENCE']:
8729651SAndreas.Sandberg@ARM.com        env.Append(LIBS=['efence'])
8739651SAndreas.Sandberg@ARM.com
8749651SAndreas.Sandberg@ARM.com    if env['USE_MYSQL']:
8759651SAndreas.Sandberg@ARM.com        if not have_mysql:
8769651SAndreas.Sandberg@ARM.com            print "Warning: MySQL not available; " \
8779651SAndreas.Sandberg@ARM.com                  "forcing USE_MYSQL to False in", variant_dir + "."
8789651SAndreas.Sandberg@ARM.com            env['USE_MYSQL'] = False
87910841Sandreas.sandberg@arm.com        else:
88010841Sandreas.sandberg@arm.com            print "Compiling in", variant_dir, "with MySQL support."
88110841Sandreas.sandberg@arm.com            env.ParseConfig(mysql_config_libs)
88210841Sandreas.sandberg@arm.com            env.ParseConfig(mysql_config_include)
88310841Sandreas.sandberg@arm.com
88410841Sandreas.sandberg@arm.com    # Save sticky variable settings back to current variables file
88510860Sandreas.sandberg@arm.com    sticky_vars.Save(current_vars_file, env)
88610841Sandreas.sandberg@arm.com
88710841Sandreas.sandberg@arm.com    if env['USE_SSE2']:
88810841Sandreas.sandberg@arm.com        env.Append(CCFLAGS='-msse2')
88910841Sandreas.sandberg@arm.com
89010841Sandreas.sandberg@arm.com    # The src/SConscript file sets up the build rules in 'env' according
89110841Sandreas.sandberg@arm.com    # to the configured variables.  It returns a list of environments,
89210841Sandreas.sandberg@arm.com    # one for each variant build (debug, opt, etc.)
89310841Sandreas.sandberg@arm.com    envList = SConscript('src/SConscript', variant_dir = variant_path,
89410841Sandreas.sandberg@arm.com                         exports = 'env')
89510841Sandreas.sandberg@arm.com
89610841Sandreas.sandberg@arm.com    # Set up the regression tests for each build.
8979651SAndreas.Sandberg@ARM.com    for e in envList:
8989651SAndreas.Sandberg@ARM.com        SConscript('tests/SConscript',
8999986Sandreas@sandberg.pp.se                   variant_dir = joinpath(variant_path, 'tests', e.Label),
9009986Sandreas@sandberg.pp.se                   exports = { 'env' : e }, duplicate = False)
9019986Sandreas@sandberg.pp.se
9029986Sandreas@sandberg.pp.seHelp(help_text)
9039986Sandreas@sandberg.pp.se