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"""
8112563Sgabeblack@google.com    raise
8212563Sgabeblack@google.com
836654Snate@binkert.org# We ensure the python version early because we have stuff that
8410196SCurtis.Dunham@arm.com# requires python 2.4
85955SN/Atry:
865396Ssaidi@eecs.umich.edu    EnsurePythonVersion(2, 4)
8711401Sandreas.sandberg@arm.comexcept SystemExit, e:
885863Snate@binkert.org    print """
895863Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
904202Sbinkertn@umich.edueither (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.
935863Snate@binkert.org
945863Snate@binkert.orgFor more details, see:
9513541Sandrea.mondelli@ucf.edu    http://m5sim.org/wiki/index.php/Using_a_non-default_Python_installation
96955SN/A"""
976654Snate@binkert.org    raise
985273Sstever@gmail.com
995871Snate@binkert.orgimport os
1005273Sstever@gmail.comimport re
1016654Snate@binkert.orgimport subprocess
1025396Ssaidi@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
1088120Sgblack@eecs.umich.edu
1098120Sgblack@eecs.umich.eduimport SCons
1108120Sgblack@eecs.umich.eduimport 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
1218879Ssteve.reinhardt@amd.com    exception = kwargs.pop('exception', None)
1228879Ssteve.reinhardt@amd.com    
1238879Ssteve.reinhardt@amd.com    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]
1358120Sgblack@eecs.umich.edu
1368120Sgblack@eecs.umich.edu# helper function: compare arrays or strings of version numbers.
1378120Sgblack@eecs.umich.edu# E.g., compare_version((1,3,25), (1,4,1)')
1388879Ssteve.reinhardt@amd.com# returns -1, 0, 1 if v1 is <, ==, > v2
1398879Ssteve.reinhardt@amd.comdef compare_versions(v1, v2):
1408879Ssteve.reinhardt@amd.com    def make_version_list(v):
1418879Ssteve.reinhardt@amd.com        if isinstance(v, (list,tuple)):
14210458Sandreas.hansson@arm.com            return v
14310458Sandreas.hansson@arm.com        elif isinstance(v, str):
14410458Sandreas.hansson@arm.com            return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
1458879Ssteve.reinhardt@amd.com        else:
1468879Ssteve.reinhardt@amd.com            raise TypeError
1478879Ssteve.reinhardt@amd.com
1488879Ssteve.reinhardt@amd.com    v1 = make_version_list(v1)
14913421Sciro.santilli@arm.com    v2 = make_version_list(v2)
15013421Sciro.santilli@arm.com    # Compare corresponding elements of lists
1519227Sandreas.hansson@arm.com    for n1,n2 in zip(v1, v2):
1529227Sandreas.hansson@arm.com        if n1 < n2: return -1
15312063Sgabeblack@google.com        if n1 > n2: return  1
15412063Sgabeblack@google.com    # all corresponding values are equal... see if one has extra values
15512063Sgabeblack@google.com    if len(v1) < len(v2): return -1
1568879Ssteve.reinhardt@amd.com    if len(v1) > len(v2): return  1
1578879Ssteve.reinhardt@amd.com    return 0
1588879Ssteve.reinhardt@amd.com
1598879Ssteve.reinhardt@amd.com########################################################################
16010453SAndrew.Bardsley@arm.com#
16110453SAndrew.Bardsley@arm.com# Set up the base build environment.
16210453SAndrew.Bardsley@arm.com#
16310456SCurtis.Dunham@arm.com########################################################################
16410456SCurtis.Dunham@arm.comuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH', 'PATH',
16510456SCurtis.Dunham@arm.com                 'RANLIB' ])
16610457Sandreas.hansson@arm.com
16710457Sandreas.hansson@arm.comuse_env = {}
16811342Sandreas.hansson@arm.comfor key,val in os.environ.iteritems():
16911342Sandreas.hansson@arm.com    if key in use_vars or key.startswith("M5"):
1708120Sgblack@eecs.umich.edu        use_env[key] = val
17112063Sgabeblack@google.com
17212563Sgabeblack@google.comenv = Environment(ENV=use_env)
17312063Sgabeblack@google.comenv.root = Dir(".")          # The current directory (where this file lives).
17412063Sgabeblack@google.comenv.srcdir = Dir("src")      # The source directory
1755871Snate@binkert.org
1765871Snate@binkert.org########################################################################
1776121Snate@binkert.org#
1785871Snate@binkert.org# Mercurial Stuff.
1795871Snate@binkert.org#
1809926Sstan.czerniawski@arm.com# If the M5 directory is a mercurial repository, we should do some
18112243Sgabeblack@google.com# extra things.
1821533SN/A#
18312246Sgabeblack@google.com########################################################################
18412246Sgabeblack@google.com
18512246Sgabeblack@google.comhgdir = env.root.Dir(".hg")
18612246Sgabeblack@google.com
1879239Sandreas.hansson@arm.commercurial_style_message = """
1889239Sandreas.hansson@arm.comYou're missing the M5 style hook.
1899239Sandreas.hansson@arm.comPlease install the hook so we can ensure that all code fits a common style.
1909239Sandreas.hansson@arm.com
19112563Sgabeblack@google.comAll you'd need to do is add the following lines to your repository .hg/hgrc
1929239Sandreas.hansson@arm.comor your personal .hgrc
1939239Sandreas.hansson@arm.com----------------
194955SN/A
195955SN/A[extensions]
1962632Sstever@eecs.umich.edustyle = %s/util/style.py
1972632Sstever@eecs.umich.edu
198955SN/A[hooks]
199955SN/Apretxncommit.style = python:style.check_whitespace
200955SN/A""" % (env.root)
201955SN/A
2028878Ssteve.reinhardt@amd.commercurial_bin_not_found = """
203955SN/AMercurial 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
2062632Sstever@eecs.umich.eduinstalling mercurial if you choose to post an error message
2072632Sstever@eecs.umich.edu"""
2082632Sstever@eecs.umich.edu
2092632Sstever@eecs.umich.edumercurial_lib_not_found = """
2102632Sstever@eecs.umich.eduMercurial 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.
2138268Ssteve.reinhardt@amd.com"""
2148268Ssteve.reinhardt@amd.com
2158268Ssteve.reinhardt@amd.comhg_info = "Unknown"
2168268Ssteve.reinhardt@amd.comif hgdir.exists():
2178268Ssteve.reinhardt@amd.com    # 1) Grab repository revision if we know it.
21813715Sandreas.sandberg@arm.com    cmd = "hg id -n -i -t -b"
21913715Sandreas.sandberg@arm.com    try:
22013715Sandreas.sandberg@arm.com        hg_info = read_command(cmd, cwd=env.root.abspath).strip()
22113715Sandreas.sandberg@arm.com    except OSError:
22213715Sandreas.sandberg@arm.com        print mercurial_bin_not_found
22313715Sandreas.sandberg@arm.com
22413715Sandreas.sandberg@arm.com    # 2) Ensure that the style hook is in place.
22513715Sandreas.sandberg@arm.com    try:
22613715Sandreas.sandberg@arm.com        ui = None
22713715Sandreas.sandberg@arm.com        if ARGUMENTS.get('IGNORE_STYLE') != 'True':
22813715Sandreas.sandberg@arm.com            from mercurial import ui
22913715Sandreas.sandberg@arm.com            ui = ui.ui()
23013715Sandreas.sandberg@arm.com    except ImportError:
2312632Sstever@eecs.umich.edu        print mercurial_lib_not_found
2322632Sstever@eecs.umich.edu
2332632Sstever@eecs.umich.edu    if ui is not None:
2342632Sstever@eecs.umich.edu        ui.readconfig(hgdir.File('hgrc').abspath)
2358268Ssteve.reinhardt@amd.com        style_hook = ui.config('hooks', 'pretxncommit.style', None)
2362632Sstever@eecs.umich.edu
2378268Ssteve.reinhardt@amd.com        if not style_hook:
2388268Ssteve.reinhardt@amd.com            print mercurial_style_message
2398268Ssteve.reinhardt@amd.com            sys.exit(1)
2408268Ssteve.reinhardt@amd.comelse:
2413718Sstever@eecs.umich.edu    print ".hg directory not found"
2422634Sstever@eecs.umich.eduenv['HG_INFO'] = hg_info
2432634Sstever@eecs.umich.edu
2445863Snate@binkert.org###################################################
2452638Sstever@eecs.umich.edu#
2468268Ssteve.reinhardt@amd.com# Figure out which configurations to set up based on the path(s) of
2472632Sstever@eecs.umich.edu# the target(s).
2482632Sstever@eecs.umich.edu#
2492632Sstever@eecs.umich.edu###################################################
2502632Sstever@eecs.umich.edu
25112563Sgabeblack@google.com# Find default configuration & binary.
2521858SN/ADefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
2533716Sstever@eecs.umich.edu
2542638Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
2552638Sstever@eecs.umich.edudef rfind(l, elt, offs = -1):
2562638Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
2572638Sstever@eecs.umich.edu        if l[i] == elt:
25812563Sgabeblack@google.com            return i
25912563Sgabeblack@google.com    raise ValueError, "element not found"
2602638Sstever@eecs.umich.edu
2615863Snate@binkert.org# Each target must have 'build' in the interior of the path; the
2625863Snate@binkert.org# 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
264955SN/A# recognize that ALPHA_SE specifies the configuration because it
2655341Sstever@gmail.com# follow 'build' in the bulid path.
2665341Sstever@gmail.com
2675863Snate@binkert.org# Generate absolute paths to targets so we can see where the build dir is
2687756SAli.Saidi@ARM.comif COMMAND_LINE_TARGETS:
2695341Sstever@gmail.com    # Ask SCons which directory it was invoked from
2706121Snate@binkert.org    launch_dir = GetLaunchDir()
2714494Ssaidi@eecs.umich.edu    # Make targets relative to invocation directory
2726121Snate@binkert.org    abs_targets = [ normpath(joinpath(launch_dir, str(x))) for x in \
2731105SN/A                    COMMAND_LINE_TARGETS]
2742667Sstever@eecs.umich.eduelse:
2752667Sstever@eecs.umich.edu    # Default targets are relative to root of tree
2762667Sstever@eecs.umich.edu    abs_targets = [ normpath(joinpath(ROOT, str(x))) for x in \
2772667Sstever@eecs.umich.edu                    DEFAULT_TARGETS]
2786121Snate@binkert.org
2792667Sstever@eecs.umich.edu
2805341Sstever@gmail.com# Generate a list of the unique build roots and configs that the
2815863Snate@binkert.org# collected targets reference.
2825341Sstever@gmail.comvariant_paths = []
2835341Sstever@gmail.combuild_root = None
2845341Sstever@gmail.comfor t in abs_targets:
2858120Sgblack@eecs.umich.edu    path_dirs = t.split('/')
2865341Sstever@gmail.com    try:
2878120Sgblack@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
2885341Sstever@gmail.com    except:
2898120Sgblack@eecs.umich.edu        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])
29213715Sandreas.sandberg@arm.com    if not build_root:
29313715Sandreas.sandberg@arm.com        build_root = this_build_root
2949396Sandreas.hansson@arm.com    else:
2955397Ssaidi@eecs.umich.edu        if this_build_root != build_root:
2965397Ssaidi@eecs.umich.edu            print "Error: build targets not under same build root\n"\
2977727SAli.Saidi@ARM.com                  "  %s\n  %s" % (build_root, this_build_root)
2988268Ssteve.reinhardt@amd.com            Exit(1)
2996168Snate@binkert.org    variant_path = joinpath('/',*path_dirs[:build_top+2])
3005341Sstever@gmail.com    if variant_path not in variant_paths:
3018120Sgblack@eecs.umich.edu        variant_paths.append(variant_path)
3028120Sgblack@eecs.umich.edu
3038120Sgblack@eecs.umich.edu# Make sure build_root exists (might not if this is the first build there)
3046814Sgblack@eecs.umich.eduif not isdir(build_root):
3055863Snate@binkert.org    mkdir(build_root)
3068120Sgblack@eecs.umich.edu
3075341Sstever@gmail.comExport('env')
3085863Snate@binkert.org
3098268Ssteve.reinhardt@amd.comenv.SConsignFile(joinpath(build_root, "sconsign"))
3106121Snate@binkert.org
3116121Snate@binkert.org# Default duplicate option is to use hard links, but this messes up
3128268Ssteve.reinhardt@amd.com# when you use emacs to edit a file in the target dir, as emacs moves
3135742Snate@binkert.org# file to file~ then copies to file, breaking the link.  Symbolic
3145742Snate@binkert.org# (soft) links work better.
3155341Sstever@gmail.comenv.SetOption('duplicate', 'soft-copy')
3165742Snate@binkert.org
3175742Snate@binkert.org#
3185341Sstever@gmail.com# Set up global sticky variables... these are common to an entire build
3196017Snate@binkert.org# tree (not specific to a particular build like ALPHA_SE)
3206121Snate@binkert.org#
3216017Snate@binkert.org
32212158Sandreas.sandberg@arm.com# Variable validators & converters for global sticky variables
32312158Sandreas.sandberg@arm.comdef PathListMakeAbsolute(val):
32412158Sandreas.sandberg@arm.com    if not val:
3258120Sgblack@eecs.umich.edu        return val
3267756SAli.Saidi@ARM.com    f = lambda p: abspath(expanduser(p))
3277756SAli.Saidi@ARM.com    return ':'.join(map(f, val.split(':')))
3287756SAli.Saidi@ARM.com
3297756SAli.Saidi@ARM.comdef PathListAllExist(key, val, env):
3307816Ssteve.reinhardt@amd.com    if not val:
3317816Ssteve.reinhardt@amd.com        return
3327816Ssteve.reinhardt@amd.com    paths = val.split(':')
3337816Ssteve.reinhardt@amd.com    for path in paths:
3347816Ssteve.reinhardt@amd.com        if not isdir(path):
33511979Sgabeblack@google.com            raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
3367816Ssteve.reinhardt@amd.com
3377816Ssteve.reinhardt@amd.comglobal_sticky_vars_file = joinpath(build_root, 'variables.global')
3387816Ssteve.reinhardt@amd.com
3397816Ssteve.reinhardt@amd.comglobal_sticky_vars = Variables(global_sticky_vars_file, args=ARGUMENTS)
3407756SAli.Saidi@ARM.com
3417756SAli.Saidi@ARM.comglobal_sticky_vars.AddVariables(
3429227Sandreas.hansson@arm.com    ('CC', 'C compiler', environ.get('CC', env['CC'])),
3439227Sandreas.hansson@arm.com    ('CXX', 'C++ compiler', environ.get('CXX', env['CXX'])),
3449227Sandreas.hansson@arm.com    ('BATCH', 'Use batch pool for build and tests', False),
3459227Sandreas.hansson@arm.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3469590Sandreas@sandberg.pp.se    ('EXTRAS', 'Add Extra directories to the compilation', '',
3479590Sandreas@sandberg.pp.se     PathListAllExist, PathListMakeAbsolute)
3489590Sandreas@sandberg.pp.se    )    
3499590Sandreas@sandberg.pp.se
3509590Sandreas@sandberg.pp.se# base help text
3519590Sandreas@sandberg.pp.sehelp_text = '''
3526654Snate@binkert.orgUsage: scons [scons options] [build options] [target(s)]
3536654Snate@binkert.org
3545871Snate@binkert.orgGlobal sticky options:
3556121Snate@binkert.org'''
3568946Sandreas.hansson@arm.com
3579419Sandreas.hansson@arm.comhelp_text += global_sticky_vars.GenerateHelpText(env)
35812563Sgabeblack@google.com
3593918Ssaidi@eecs.umich.edu# Update env with values from ARGUMENTS & file global_sticky_vars_file
3603918Ssaidi@eecs.umich.eduglobal_sticky_vars.Update(env)
3611858SN/A
3629556Sandreas.hansson@arm.com# Save sticky variable settings back to current variables file
3639556Sandreas.hansson@arm.comglobal_sticky_vars.Save(global_sticky_vars_file, env)
3649556Sandreas.hansson@arm.com
3659556Sandreas.hansson@arm.com# Parse EXTRAS variable to build list of all directories where we're
36611294Sandreas.hansson@arm.com# look for sources etc.  This list is exported as base_dir_list.
36711294Sandreas.hansson@arm.combase_dir = env.srcdir.abspath
36811294Sandreas.hansson@arm.comif env['EXTRAS']:
36911294Sandreas.hansson@arm.com    extras_dir_list = env['EXTRAS'].split(':')
37010878Sandreas.hansson@arm.comelse:
37110878Sandreas.hansson@arm.com    extras_dir_list = []
37211811Sbaz21@cam.ac.uk
37311811Sbaz21@cam.ac.ukExport('base_dir')
37411811Sbaz21@cam.ac.ukExport('extras_dir_list')
37511982Sgabeblack@google.com
37611982Sgabeblack@google.com# the ext directory should be on the #includes path
37711982Sgabeblack@google.comenv.Append(CPPPATH=[Dir('ext')])
37813421Sciro.santilli@arm.com
37913421Sciro.santilli@arm.com# M5_PLY is used by isa_parser.py to find the PLY package.
38011982Sgabeblack@google.comenv.Append(ENV = { 'M5_PLY' : Dir('ext/ply').abspath })
38111992Sgabeblack@google.com
38211982Sgabeblack@google.comCXX_version = read_command([env['CXX'],'--version'], exception=False)
38311982Sgabeblack@google.comCXX_V = read_command([env['CXX'],'-V'], exception=False)
38412305Sgabeblack@google.com
38512305Sgabeblack@google.comenv['GCC'] = CXX_version and CXX_version.find('g++') >= 0
38612305Sgabeblack@google.comenv['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
38712305Sgabeblack@google.comenv['ICC'] = CXX_V and CXX_V.find('Intel') >= 0
38812305Sgabeblack@google.comif env['GCC'] + env['SUNCC'] + env['ICC'] > 1:
38912305Sgabeblack@google.com    print 'Error: How can we have two at the same time?'
39012305Sgabeblack@google.com    Exit(1)
3919556Sandreas.hansson@arm.com
39212563Sgabeblack@google.com# Set up default C++ compiler flags
39312563Sgabeblack@google.comif env['GCC']:
39412563Sgabeblack@google.com    env.Append(CCFLAGS='-pipe')
39512563Sgabeblack@google.com    env.Append(CCFLAGS='-fno-strict-aliasing')
3969556Sandreas.hansson@arm.com    env.Append(CCFLAGS=Split('-Wall -Wno-sign-compare -Werror -Wundef'))
39712563Sgabeblack@google.com    env.Append(CXXFLAGS='-Wno-deprecated')
39812563Sgabeblack@google.comelif env['ICC']:
3999556Sandreas.hansson@arm.com    pass #Fix me... add warning flags once we clean up icc warnings
40012563Sgabeblack@google.comelif env['SUNCC']:
40112563Sgabeblack@google.com    env.Append(CCFLAGS='-Qoption ccfe')
40212563Sgabeblack@google.com    env.Append(CCFLAGS='-features=gcc')
40312563Sgabeblack@google.com    env.Append(CCFLAGS='-features=extensions')
40412563Sgabeblack@google.com    env.Append(CCFLAGS='-library=stlport4')
40512563Sgabeblack@google.com    env.Append(CCFLAGS='-xar')
40612563Sgabeblack@google.com    #env.Append(CCFLAGS='-instances=semiexplicit')
40712563Sgabeblack@google.comelse:
4089556Sandreas.hansson@arm.com    print 'Error: Don\'t know what compiler options to use for your compiler.'
4099556Sandreas.hansson@arm.com    print '       Please fix SConstruct and src/SConscript and try again.'
4106121Snate@binkert.org    Exit(1)
41111500Sandreas.hansson@arm.com
41210238Sandreas.hansson@arm.com# Do this after we save setting back, or else we'll tack on an
41310878Sandreas.hansson@arm.com# extra 'qdo' every time we run scons.
4149420Sandreas.hansson@arm.comif env['BATCH']:
41511500Sandreas.hansson@arm.com    env['CC']     = env['BATCH_CMD'] + ' ' + env['CC']
41612563Sgabeblack@google.com    env['CXX']    = env['BATCH_CMD'] + ' ' + env['CXX']
41712563Sgabeblack@google.com    env['AS']     = env['BATCH_CMD'] + ' ' + env['AS']
4189420Sandreas.hansson@arm.com    env['AR']     = env['BATCH_CMD'] + ' ' + env['AR']
4199420Sandreas.hansson@arm.com    env['RANLIB'] = env['BATCH_CMD'] + ' ' + env['RANLIB']
4209420Sandreas.hansson@arm.com
4219420Sandreas.hansson@arm.comif sys.platform == 'cygwin':
42212063Sgabeblack@google.com    # cygwin has some header file issues...
42312063Sgabeblack@google.com    env.Append(CCFLAGS=Split("-Wno-uninitialized"))
42412063Sgabeblack@google.com
42512063Sgabeblack@google.com# Check for SWIG
42612063Sgabeblack@google.comif not env.has_key('SWIG'):
42712063Sgabeblack@google.com    print 'Error: SWIG utility not found.'
42812063Sgabeblack@google.com    print '       Please install (see http://www.swig.org) and retry.'
42912063Sgabeblack@google.com    Exit(1)
43012063Sgabeblack@google.com
43112063Sgabeblack@google.com# Check for appropriate SWIG version
43212063Sgabeblack@google.comswig_version = read_command(('swig', '-version'), exception='').split()
43312063Sgabeblack@google.com# First 3 words should be "SWIG Version x.y.z"
43412063Sgabeblack@google.comif len(swig_version) < 3 or \
43512063Sgabeblack@google.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
43612063Sgabeblack@google.com    print 'Error determining SWIG version.'
43712063Sgabeblack@google.com    Exit(1)
43812063Sgabeblack@google.com
43912063Sgabeblack@google.commin_swig_version = '1.3.28'
44012063Sgabeblack@google.comif compare_versions(swig_version[2], min_swig_version) < 0:
44112063Sgabeblack@google.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
44212063Sgabeblack@google.com    print '       Installed version:', swig_version[2]
44312063Sgabeblack@google.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
44912563Sgabeblack@google.com# filter out all existing swig scanners, they mess up the dependency
45012563Sgabeblack@google.com# stuff for some reason
45112563Sgabeblack@google.comscanners = []
45210457Sandreas.hansson@arm.comfor scanner in env['SCANNERS']:
45312063Sgabeblack@google.com    skeys = scanner.skeys
45412063Sgabeblack@google.com    if skeys == '.i':
45512063Sgabeblack@google.com        continue
45612563Sgabeblack@google.com
45712563Sgabeblack@google.com    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
45812563Sgabeblack@google.com        continue
45912563Sgabeblack@google.com
46012563Sgabeblack@google.com    scanners.append(scanner)
46112563Sgabeblack@google.com
46212063Sgabeblack@google.com# add the new swig scanner that we like better
46312063Sgabeblack@google.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))
46610238Sandreas.hansson@arm.com
46712063Sgabeblack@google.com# replace the scanners list that has what we want
46810238Sandreas.hansson@arm.comenv['SCANNERS'] = scanners
46910238Sandreas.hansson@arm.com
47010416Sandreas.hansson@arm.com# Add a custom Check function to the Configure context so that we can
47110238Sandreas.hansson@arm.com# figure out if the compiler adds leading underscores to global
4729227Sandreas.hansson@arm.com# variables.  This is needed for the autogenerated asm files that we
47310238Sandreas.hansson@arm.com# use for embedding the python code.
47410416Sandreas.hansson@arm.comdef CheckLeading(context):
47510416Sandreas.hansson@arm.com    context.Message("Checking for leading underscore in global variables...")
4769227Sandreas.hansson@arm.com    # 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.
4799590Sandreas@sandberg.pp.se    # 3) Use the variable
48012304Sgabeblack@google.com    #
48112304Sgabeblack@google.com    # If the compiler prepends an underscore, this will successfully
48212304Sgabeblack@google.com    # link because the external symbol 'x' will be called '_x' which
48312688Sgiacomo.travaglini@arm.com    # was defined by the asm statement.  If the compiler does not
48412688Sgiacomo.travaglini@arm.com    # prepend an underscore, this will not successfully link because
48512688Sgiacomo.travaglini@arm.com    # '_x' will have been defined by assembly, while the C portion of
48613020Sshunhsingou@google.com    # the code will be trying to use 'x'
48712304Sgabeblack@google.com    ret = context.TryLink('''
48812688Sgiacomo.travaglini@arm.com        asm(".globl _x; _x: .byte 0");
48912688Sgiacomo.travaglini@arm.com        extern int x;
49013020Sshunhsingou@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
49512688Sgiacomo.travaglini@arm.com
49612688Sgiacomo.travaglini@arm.com# Platform-specific configuration.  Note again that we assume that all
49712688Sgiacomo.travaglini@arm.com# builds under a given build root run on the same host platform.
49812304Sgabeblack@google.comconf = Configure(env,
4998737Skoansin.tan@gmail.com                 conf_dir = joinpath(build_root, '.scons_config'),
50010878Sandreas.hansson@arm.com                 log_file = joinpath(build_root, 'scons_config.log'),
50111500Sandreas.hansson@arm.com                 custom_tests = { 'CheckLeading' : CheckLeading })
5029420Sandreas.hansson@arm.com
5038737Skoansin.tan@gmail.com# Check for leading underscores.  Don't really need to worry either
50410106SMitch.Hayenga@arm.com# way so don't need to check the return code.
5058737Skoansin.tan@gmail.comconf.CheckLeading()
5068737Skoansin.tan@gmail.com
50710878Sandreas.hansson@arm.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
50812563Sgabeblack@google.comtry:
50912563Sgabeblack@google.com    import platform
5108737Skoansin.tan@gmail.com    uname = platform.uname()
5118737Skoansin.tan@gmail.com    if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
51212563Sgabeblack@google.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')
51511294Sandreas.hansson@arm.com            env.Append(LINKFLAGS='-arch x86_64')
5169556Sandreas.hansson@arm.com            env.Append(ASFLAGS='-arch x86_64')
5179556Sandreas.hansson@arm.comexcept:
5189556Sandreas.hansson@arm.com    pass
51911294Sandreas.hansson@arm.com
52010278SAndreas.Sandberg@ARM.com# Recent versions of scons substitute a "Null" object for Configure()
52110278SAndreas.Sandberg@ARM.com# when configuration isn't necessary, e.g., if the "--help" option is
52210278SAndreas.Sandberg@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:
5269556Sandreas.hansson@arm.com    def NullCheck(*args, **kwargs):
5279590Sandreas@sandberg.pp.se        return True
5289590Sandreas@sandberg.pp.se
5299420Sandreas.hansson@arm.com    class NullConf:
5309846Sandreas.hansson@arm.com        def __init__(self, env):
5319846Sandreas.hansson@arm.com            self.env = env
5329846Sandreas.hansson@arm.com        def Finish(self):
5339846Sandreas.hansson@arm.com            return self.env
5348946Sandreas.hansson@arm.com        def __getattr__(self, mname):
53511811Sbaz21@cam.ac.uk            return NullCheck
53611811Sbaz21@cam.ac.uk
53711811Sbaz21@cam.ac.uk    conf = NullConf(env)
53811811Sbaz21@cam.ac.uk
53912304Sgabeblack@google.com# Find Python include and library directories for embedding the
54012304Sgabeblack@google.com# interpreter.  For consistency, we will use the same Python
54112304Sgabeblack@google.com# 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
54313020Sshunhsingou@google.com# to invoke scons with a different copy of the Python interpreter.
54413020Sshunhsingou@google.comfrom distutils import sysconfig
54512304Sgabeblack@google.com
54612304Sgabeblack@google.compy_getvar = sysconfig.get_config_var
54713020Sshunhsingou@google.com
54813020Sshunhsingou@google.compy_version = 'python' + py_getvar('VERSION')
54912304Sgabeblack@google.com
55012304Sgabeblack@google.compy_general_include = sysconfig.get_python_inc()
55113020Sshunhsingou@google.compy_platform_include = sysconfig.get_python_inc(plat_specific=True)
55213020Sshunhsingou@google.compy_includes = [ py_general_include ]
55312304Sgabeblack@google.comif py_platform_include != py_general_include:
55412304Sgabeblack@google.com    py_includes.append(py_platform_include)
5553918Ssaidi@eecs.umich.edu
55612563Sgabeblack@google.compy_lib_path = [ py_getvar('LIBDIR') ]
55712563Sgabeblack@google.com# add the prefix/lib/pythonX.Y/config dir, but only if there is no
55812563Sgabeblack@google.com# shared library in prefix/lib/.
55912563Sgabeblack@google.comif not py_getvar('Py_ENABLE_SHARED'):
5609068SAli.Saidi@ARM.com    py_lib_path.append('-L' + py_getvar('LIBPL'))
56112563Sgabeblack@google.com
56212563Sgabeblack@google.compy_libs = []
5639068SAli.Saidi@ARM.comfor lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
56412563Sgabeblack@google.com    if lib not in py_libs:
56512563Sgabeblack@google.com        py_libs.append(lib)
56612563Sgabeblack@google.compy_libs.append('-l' + py_version)
56712563Sgabeblack@google.com
56812563Sgabeblack@google.comenv.Append(CPPPATH=py_includes)
56912563Sgabeblack@google.comenv.Append(LIBPATH=py_lib_path)
57012563Sgabeblack@google.com
57112563Sgabeblack@google.com# verify that this stuff works
5723918Ssaidi@eecs.umich.eduif not conf.CheckHeader('Python.h', '<>'):
5733918Ssaidi@eecs.umich.edu    print "Error: can't find Python.h header in", py_includes
5746157Snate@binkert.org    Exit(1)
5756157Snate@binkert.org
5766157Snate@binkert.orgfor lib in py_libs:
5776157Snate@binkert.org    assert lib.startswith('-l')
5785397Ssaidi@eecs.umich.edu    lib = lib[2:]
5795397Ssaidi@eecs.umich.edu    if not conf.CheckLib(lib):
5806121Snate@binkert.org        print "Error: can't find library %s required by python" % lib
5816121Snate@binkert.org        Exit(1)
5826121Snate@binkert.org
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);'):
5865397Ssaidi@eecs.umich.edu       print "Can't find library with socket calls (e.g. accept())"
5871851SN/A       Exit(1)
5881851SN/A
5897739Sgblack@eecs.umich.edu# Check for zlib.  If the check passes, libz will be automatically
590955SN/A# added to the LIBS environment variable.
5919396Sandreas.hansson@arm.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
5929396Sandreas.hansson@arm.com    print 'Error: did not find needed zlib compression library '\
5939396Sandreas.hansson@arm.com          '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
59712563Sgabeblack@google.com# Check for <fenv.h> (C99 FP environment control)
59812563Sgabeblack@google.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
59912563Sgabeblack@google.comif not have_fenv:
60012563Sgabeblack@google.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#
60712563Sgabeblack@google.commysql_config = WhereIs('mysql_config')
60812563Sgabeblack@google.comhave_mysql = bool(mysql_config)
60912563Sgabeblack@google.com
61012563Sgabeblack@google.com# Check MySQL version.
61112563Sgabeblack@google.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'
62612563Sgabeblack@google.com    # This seems to work in all versions
62712563Sgabeblack@google.com    mysql_config_libs = mysql_config + ' --libs'
62812563Sgabeblack@google.com
6299396Sandreas.hansson@arm.com######################################################################
6302667Sstever@eecs.umich.edu#
63110710Sandreas.hansson@arm.com# Finish the configuration
63210710Sandreas.hansson@arm.com#
63310710Sandreas.hansson@arm.comenv = conf.Finish()
63411811Sbaz21@cam.ac.uk
63511811Sbaz21@cam.ac.uk######################################################################
63611811Sbaz21@cam.ac.uk#
63711811Sbaz21@cam.ac.uk# Collect all non-global variables
63811811Sbaz21@cam.ac.uk#
63911811Sbaz21@cam.ac.uk
64010710Sandreas.hansson@arm.comExport('env')
64110710Sandreas.hansson@arm.com
64210710Sandreas.hansson@arm.com# Define the universe of supported ISAs
64310710Sandreas.hansson@arm.comall_isa_list = [ ]
64410384SCurtis.Dunham@arm.comExport('all_isa_list')
6459986Sandreas@sandberg.pp.se
6469986Sandreas@sandberg.pp.se# Define the universe of supported CPU models
6479986Sandreas@sandberg.pp.seall_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):
6652638Sstever@eecs.umich.edu        if 'SConsopts' in files:
6662638Sstever@eecs.umich.edu            print "Reading", joinpath(root, 'SConsopts')
6676121Snate@binkert.org            SConscript(joinpath(root, 'SConsopts'))
6683716Sstever@eecs.umich.edu
6695522Snate@binkert.orgall_isa_list.sort()
6709986Sandreas@sandberg.pp.seall_cpu_list.sort()
6719986Sandreas@sandberg.pp.sedefault_cpus.sort()
6729986Sandreas@sandberg.pp.se
6735522Snate@binkert.orgsticky_vars.AddVariables(
6745227Ssaidi@eecs.umich.edu    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
6755227Ssaidi@eecs.umich.edu    BoolVariable('FULL_SYSTEM', 'Full-system support', False),
6765227Ssaidi@eecs.umich.edu    ListVariable('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
6775227Ssaidi@eecs.umich.edu    BoolVariable('NO_FAST_ALLOC', 'Disable fast object allocator', False),
6786654Snate@binkert.org    BoolVariable('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
6796654Snate@binkert.org                 False),
6807769SAli.Saidi@ARM.com    BoolVariable('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
6817769SAli.Saidi@ARM.com                 False),
6827769SAli.Saidi@ARM.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
6837769SAli.Saidi@ARM.com                 False),
6845227Ssaidi@eecs.umich.edu    BoolVariable('SS_COMPATIBLE_FP',
6855227Ssaidi@eecs.umich.edu                 'Make floating-point results compatible with SimpleScalar',
6865227Ssaidi@eecs.umich.edu                 False),
6875204Sstever@gmail.com    BoolVariable('USE_SSE2',
6885204Sstever@gmail.com                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
6895204Sstever@gmail.com                 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', \
7046121Snate@binkert.org                       'USE_CHECKER', 'TARGET_ISA', 'CP_ANNOTATE']
7055204Sstever@gmail.com
7067727SAli.Saidi@ARM.com###################################################
7077727SAli.Saidi@ARM.com#
70812563Sgabeblack@google.com# Define a SCons builder for configuration flag headers.
7097727SAli.Saidi@ARM.com#
7107727SAli.Saidi@ARM.com###################################################
71111988Sandreas.sandberg@arm.com
71211988Sandreas.sandberg@arm.com# This function generates a config header file that #defines the
71310453SAndrew.Bardsley@arm.com# variable symbol to the current variable setting (0 or 1).  The source
71410453SAndrew.Bardsley@arm.com# operands are the name of the variable and a Value node containing the
71510453SAndrew.Bardsley@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
72013715Sandreas.sandberg@arm.com    f.close()
72113715Sandreas.sandberg@arm.com    return None
72213715Sandreas.sandberg@arm.com
72313715Sandreas.sandberg@arm.com# Generate the message to be printed when building the config file.
72413715Sandreas.sandberg@arm.comdef build_config_file_string(target, source, env):
72513715Sandreas.sandberg@arm.com    (variable, value) = [s.get_contents() for s in source]
72613715Sandreas.sandberg@arm.com    return "Defining %s as %s in %s." % (variable, value, target[0])
72713715Sandreas.sandberg@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)
73013541Sandrea.mondelli@ucf.edu
73110453SAndrew.Bardsley@arm.com# The emitter munges the source & target node lists to reflect what
73210453SAndrew.Bardsley@arm.com# we're really doing.
73313541Sandrea.mondelli@ucf.edudef config_emitter(target, source, env):
73413541Sandrea.mondelli@ucf.edu    # 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 })
75112790Smatteo.fusi@bsc.es
75212790Smatteo.fusi@bsc.es# libelf build is shared across all configs in the build root.
75312790Smatteo.fusi@bsc.esenv.SConscript('ext/libelf/SConscript',
75412790Smatteo.fusi@bsc.es               variant_dir = joinpath(build_root, 'libelf'))
75512790Smatteo.fusi@bsc.es
75612790Smatteo.fusi@bsc.es# gzstream build is shared across all configs in the build root.
75712790Smatteo.fusi@bsc.esenv.SConscript('ext/gzstream/SConscript',
75810453SAndrew.Bardsley@arm.com               variant_dir = joinpath(build_root, 'gzstream'))
7593118Sstever@eecs.umich.edu
76010453SAndrew.Bardsley@arm.com###################################################
76110453SAndrew.Bardsley@arm.com#
76212563Sgabeblack@google.com# This function is used to set up a directory with switching headers
76310453SAndrew.Bardsley@arm.com#
7643118Sstever@eecs.umich.edu###################################################
7653483Ssaidi@eecs.umich.edu
7663494Ssaidi@eecs.umich.eduenv['ALL_ISA_LIST'] = all_isa_list
7673494Ssaidi@eecs.umich.edudef make_switching_dir(dname, switch_headers, env):
76812563Sgabeblack@google.com    # Generate the header.  target[0] is the full path of the output
7693483Ssaidi@eecs.umich.edu    # header to generate.  'source' is a dummy variable, since we get the
7703483Ssaidi@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])
7733918Ssaidi@eecs.umich.edu        bname = basename(fname)
77412563Sgabeblack@google.com        f = open(fname, 'w')
77512563Sgabeblack@google.com        f.write('#include "arch/isa_specific.hh"\n')
77612563Sgabeblack@google.com        cond = '#if'
7773053Sstever@eecs.umich.edu        for isa in all_isa_list:
7783053Sstever@eecs.umich.edu            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()
7839396Sandreas.hansson@arm.com        return 0
7849396Sandreas.hansson@arm.com
7859396Sandreas.hansson@arm.com    # String to print when generating header
7869396Sandreas.hansson@arm.com    def gen_switch_hdr_string(target, source, env):
7879396Sandreas.hansson@arm.com        return "Generating switch header " + str(target[0])
78812920Sgabeblack@google.com
78912920Sgabeblack@google.com    # Build SCons Action object. 'varlist' specifies env vars that this
79012920Sgabeblack@google.com    # action depends on; when env['ALL_ISA_LIST'] changes these actions
79112920Sgabeblack@google.com    # should get re-executed.
7929477Sandreas.hansson@arm.com    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
7939396Sandreas.hansson@arm.com                               varlist=['ALL_ISA_LIST'])
79412563Sgabeblack@google.com
79512563Sgabeblack@google.com    # Instantiate actions for each header
79612563Sgabeblack@google.com    for hdr in switch_headers:
79712563Sgabeblack@google.com        env.Command(hdr, [], switch_hdr_action)
7989396Sandreas.hansson@arm.comExport('make_switching_dir')
7997840Snate@binkert.org
8007865Sgblack@eecs.umich.edu###################################################
8017865Sgblack@eecs.umich.edu#
8027865Sgblack@eecs.umich.edu# Define build environments for selected configurations.
8037865Sgblack@eecs.umich.edu#
8047865Sgblack@eecs.umich.edu###################################################
8057840Snate@binkert.org
8069900Sandreas@sandberg.pp.se# rename base env
8079900Sandreas@sandberg.pp.sebase_env = env
8089900Sandreas@sandberg.pp.se
8099900Sandreas@sandberg.pp.sefor variant_path in variant_paths:
81010456SCurtis.Dunham@arm.com    print "Building in", variant_path
81110456SCurtis.Dunham@arm.com
81210456SCurtis.Dunham@arm.com    # Make a copy of the build-root environment to use for this config.
81310456SCurtis.Dunham@arm.com    env = base_env.Clone()
81410456SCurtis.Dunham@arm.com    env['BUILDDIR'] = variant_path
81510456SCurtis.Dunham@arm.com
81612563Sgabeblack@google.com    # variant_dir is the tail component of build path, and is used to
81712563Sgabeblack@google.com    # determine the build parameters (e.g., 'ALPHA_SE')
81812563Sgabeblack@google.com    (build_root, variant_dir) = splitpath(variant_path)
81912563Sgabeblack@google.com
8209045SAli.Saidi@ARM.com    # Set env variables according to the build directory config.
82111235Sandreas.sandberg@arm.com    sticky_vars.files = []
82211235Sandreas.sandberg@arm.com    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
82311235Sandreas.sandberg@arm.com    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
82411235Sandreas.sandberg@arm.com    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
82511235Sandreas.sandberg@arm.com    current_vars_file = joinpath(build_root, 'variables', variant_dir)
82612485Sjang.hanhwi@gmail.com    if isfile(current_vars_file):
82712485Sjang.hanhwi@gmail.com        sticky_vars.files.append(current_vars_file)
82812485Sjang.hanhwi@gmail.com        print "Using saved variables file %s" % current_vars_file
82911235Sandreas.sandberg@arm.com    else:
83011811Sbaz21@cam.ac.uk        # Build dir-specific variables file doesn't exist.
83112485Sjang.hanhwi@gmail.com
83211811Sbaz21@cam.ac.uk        # Make sure the directory is there so we can create it later
83311811Sbaz21@cam.ac.uk        opt_dir = dirname(current_vars_file)
83411811Sbaz21@cam.ac.uk        if not isdir(opt_dir):
83511235Sandreas.sandberg@arm.com            mkdir(opt_dir)
83611235Sandreas.sandberg@arm.com
83711235Sandreas.sandberg@arm.com        # Get default build variables from source tree.  Variables are
83812563Sgabeblack@google.com        # normally determined by name of $VARIANT_DIR, but can be
83912563Sgabeblack@google.com        # overriden by 'default=' arg on command line.
84012563Sgabeblack@google.com        default_vars_file = joinpath('build_opts',
84111235Sandreas.sandberg@arm.com                                     ARGUMENTS.get('default', variant_dir))
8427840Snate@binkert.org        if isfile(default_vars_file):
84312563Sgabeblack@google.com            sticky_vars.files.append(default_vars_file)
8447840Snate@binkert.org            print "Variables file %s not found,\n  using defaults in %s" \
8451858SN/A                  % (current_vars_file, default_vars_file)
8461858SN/A        else:
8471858SN/A            print "Error: cannot find variables file %s or %s" \
84812563Sgabeblack@google.com                  % (current_vars_file, default_vars_file)
84912563Sgabeblack@google.com            Exit(1)
8501858SN/A
85112230Sgiacomo.travaglini@arm.com    # Apply current variable settings to env
85212230Sgiacomo.travaglini@arm.com    sticky_vars.Update(env)
85312230Sgiacomo.travaglini@arm.com    nonsticky_vars.Update(env)
85412230Sgiacomo.travaglini@arm.com
85512563Sgabeblack@google.com    help_text += "\nSticky variables for %s:\n" % variant_dir \
85612563Sgabeblack@google.com                 + sticky_vars.GenerateHelpText(env) \
85712563Sgabeblack@google.com                 + "\nNon-sticky variables for %s:\n" % variant_dir \
85812230Sgiacomo.travaglini@arm.com                 + nonsticky_vars.GenerateHelpText(env)
8599903Sandreas.hansson@arm.com
8609903Sandreas.hansson@arm.com    # Process variable settings.
8619903Sandreas.hansson@arm.com
8629903Sandreas.hansson@arm.com    if not have_fenv and env['USE_FENV']:
86310841Sandreas.sandberg@arm.com        print "Warning: <fenv.h> not available; " \
8649651SAndreas.Sandberg@ARM.com              "forcing USE_FENV to False in", variant_dir + "."
86512563Sgabeblack@google.com        env['USE_FENV'] = False
86612563Sgabeblack@google.com
8679651SAndreas.Sandberg@ARM.com    if not env['USE_FENV']:
86812056Sgabeblack@google.com        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
86912056Sgabeblack@google.com        print "         FP results may deviate slightly from other platforms."
87012056Sgabeblack@google.com
87112563Sgabeblack@google.com    if env['EFENCE']:
87212056Sgabeblack@google.com        env.Append(LIBS=['efence'])
87310841Sandreas.sandberg@arm.com
87410841Sandreas.sandberg@arm.com    if env['USE_MYSQL']:
87510841Sandreas.sandberg@arm.com        if not have_mysql:
87610841Sandreas.sandberg@arm.com            print "Warning: MySQL not available; " \
87710841Sandreas.sandberg@arm.com                  "forcing USE_MYSQL to False in", variant_dir + "."
87810841Sandreas.sandberg@arm.com            env['USE_MYSQL'] = False
8799651SAndreas.Sandberg@ARM.com        else:
8809651SAndreas.Sandberg@ARM.com            print "Compiling in", variant_dir, "with MySQL support."
8819651SAndreas.Sandberg@ARM.com            env.ParseConfig(mysql_config_libs)
8829651SAndreas.Sandberg@ARM.com            env.ParseConfig(mysql_config_include)
8839651SAndreas.Sandberg@ARM.com
8849651SAndreas.Sandberg@ARM.com    # Save sticky variable settings back to current variables file
88512563Sgabeblack@google.com    sticky_vars.Save(current_vars_file, env)
8869651SAndreas.Sandberg@ARM.com
8879651SAndreas.Sandberg@ARM.com    if env['USE_SSE2']:
88810841Sandreas.sandberg@arm.com        env.Append(CCFLAGS='-msse2')
88912563Sgabeblack@google.com
89012563Sgabeblack@google.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,
89410860Sandreas.sandberg@arm.com                         exports = 'env')
89510841Sandreas.sandberg@arm.com
89610841Sandreas.sandberg@arm.com    # Set up the regression tests for each build.
89710841Sandreas.sandberg@arm.com    for e in envList:
89810841Sandreas.sandberg@arm.com        SConscript('tests/SConscript',
89910841Sandreas.sandberg@arm.com                   variant_dir = joinpath(variant_path, 'tests', e.Label),
90012563Sgabeblack@google.com                   exports = { 'env' : e }, duplicate = False)
90110841Sandreas.sandberg@arm.com
90210841Sandreas.sandberg@arm.comHelp(help_text)
90310841Sandreas.sandberg@arm.com