SConstruct revision 7865
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
4955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
5955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
6955SN/A# All rights reserved.
7955SN/A#
8955SN/A# Redistribution and use in source and binary forms, with or without
9955SN/A# modification, are permitted provided that the following conditions are
10955SN/A# met: redistributions of source code must retain the above copyright
11955SN/A# notice, this list of conditions and the following disclaimer;
12955SN/A# redistributions in binary form must reproduce the above copyright
13955SN/A# notice, this list of conditions and the following disclaimer in the
14955SN/A# documentation and/or other materials provided with the distribution;
15955SN/A# neither the name of the copyright holders nor the names of its
16955SN/A# contributors may be used to endorse or promote products derived from
17955SN/A# this software without specific prior written permission.
18955SN/A#
19955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
282665Ssaidi@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
292665Ssaidi@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30955SN/A#
31955SN/A# Authors: Steve Reinhardt
32955SN/A#          Nathan Binkert
33955SN/A
34955SN/A###################################################
352632Sstever@eecs.umich.edu#
362632Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
372632Sstever@eecs.umich.edu#
382632Sstever@eecs.umich.edu# While in this directory ('m5'), just type 'scons' to build the default
39955SN/A# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
402632Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
412632Sstever@eecs.umich.edu# the optimized full-system version).
422632Sstever@eecs.umich.edu#
432632Sstever@eecs.umich.edu# You can build M5 in a different directory as long as there is a
442632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
452632Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
462632Sstever@eecs.umich.edu# built for the same host system.
472632Sstever@eecs.umich.edu#
482632Sstever@eecs.umich.edu# Examples:
492632Sstever@eecs.umich.edu#
502632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
512632Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
522632Sstever@eecs.umich.edu#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
532632Sstever@eecs.umich.edu#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
542632Sstever@eecs.umich.edu#
552632Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
562632Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
572632Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
582632Sstever@eecs.umich.edu#   file.
592632Sstever@eecs.umich.edu#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
60955SN/A#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
61955SN/A#
62955SN/A# You can use 'scons -H' to print scons options.  If you're in this
63955SN/A# 'm5' directory (or use -u or -C to tell scons where to find this
64955SN/A# file), you can use 'scons -h' to print all the M5-specific build
65955SN/A# options as well.
66955SN/A#
672656Sstever@eecs.umich.edu###################################################
682656Sstever@eecs.umich.edu
692656Sstever@eecs.umich.edu# Check for recent-enough Python and SCons versions.
702656Sstever@eecs.umich.edutry:
712656Sstever@eecs.umich.edu    # Really old versions of scons only take two options for the
722656Sstever@eecs.umich.edu    # function, so check once without the revision and once with the
732656Sstever@eecs.umich.edu    # revision, the first instance will fail for stuff other than
742653Sstever@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
752653Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98)
762653Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98, 1)
772653Sstever@eecs.umich.eduexcept SystemExit, e:
782653Sstever@eecs.umich.edu    print """
792653Sstever@eecs.umich.eduFor more details, see:
802653Sstever@eecs.umich.edu    http://m5sim.org/wiki/index.php/Compiling_M5
812653Sstever@eecs.umich.edu"""
822653Sstever@eecs.umich.edu    raise
832653Sstever@eecs.umich.edu
842653Sstever@eecs.umich.edu# We ensure the python version early because we have stuff that
851852SN/A# requires python 2.4
86955SN/Atry:
87955SN/A    EnsurePythonVersion(2, 4)
88955SN/Aexcept SystemExit, e:
892632Sstever@eecs.umich.edu    print """
902632Sstever@eecs.umich.eduYou can use a non-default installation of the Python interpreter by
91955SN/Aeither (1) rearranging your PATH so that scons finds the non-default
921533SN/A'python' first or (2) explicitly invoking an alternative interpreter
932632Sstever@eecs.umich.eduon the scons script.
941533SN/A
95955SN/AFor more details, see:
96955SN/A    http://m5sim.org/wiki/index.php/Using_a_non-default_Python_installation
972632Sstever@eecs.umich.edu"""
982632Sstever@eecs.umich.edu    raise
99955SN/A
100955SN/A# Global Python includes
101955SN/Aimport os
102955SN/Aimport re
1032632Sstever@eecs.umich.eduimport subprocess
104955SN/Aimport sys
1052632Sstever@eecs.umich.edu
106955SN/Afrom os import mkdir, environ
107955SN/Afrom os.path import abspath, basename, dirname, expanduser, normpath
1082632Sstever@eecs.umich.edufrom os.path import exists,  isdir, isfile
1092632Sstever@eecs.umich.edufrom os.path import join as joinpath, split as splitpath
1102632Sstever@eecs.umich.edu
1112632Sstever@eecs.umich.edu# SCons includes
1122632Sstever@eecs.umich.eduimport SCons
1132632Sstever@eecs.umich.eduimport SCons.Node
1142632Sstever@eecs.umich.edu
1152632Sstever@eecs.umich.eduextra_python_paths = [
1162632Sstever@eecs.umich.edu    Dir('src/python').srcnode().abspath, # M5 includes
1172632Sstever@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1182632Sstever@eecs.umich.edu    ]
1192632Sstever@eecs.umich.edu    
1202632Sstever@eecs.umich.edusys.path[1:1] = extra_python_paths
1212632Sstever@eecs.umich.edu
1222632Sstever@eecs.umich.edufrom m5.util import compareVersions, readCommand
1232632Sstever@eecs.umich.edu
1242632Sstever@eecs.umich.eduAddOption('--colors', dest='use_colors', action='store_true')
1252634Sstever@eecs.umich.eduAddOption('--no-colors', dest='use_colors', action='store_false')
1262634Sstever@eecs.umich.eduuse_colors = GetOption('use_colors')
1272632Sstever@eecs.umich.edu
1282638Sstever@eecs.umich.eduif use_colors:
1292632Sstever@eecs.umich.edu    from m5.util.terminal import termcap
1302632Sstever@eecs.umich.eduelif use_colors is None:
1312632Sstever@eecs.umich.edu    # option unspecified; default behavior is to use colors iff isatty
1322632Sstever@eecs.umich.edu    from m5.util.terminal import tty_termcap as termcap
1332632Sstever@eecs.umich.eduelse:
1342632Sstever@eecs.umich.edu    from m5.util.terminal import no_termcap as termcap
1351858SN/A
1362638Sstever@eecs.umich.edu########################################################################
1372638Sstever@eecs.umich.edu#
1382638Sstever@eecs.umich.edu# Set up the main build environment.
1392638Sstever@eecs.umich.edu#
1402638Sstever@eecs.umich.edu########################################################################
1412638Sstever@eecs.umich.eduuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH', 'PATH',
1422638Sstever@eecs.umich.edu                 'PYTHONPATH', 'RANLIB' ])
1432638Sstever@eecs.umich.edu
1442634Sstever@eecs.umich.eduuse_env = {}
1452634Sstever@eecs.umich.edufor key,val in os.environ.iteritems():
1462634Sstever@eecs.umich.edu    if key in use_vars or key.startswith("M5"):
147955SN/A        use_env[key] = val
148955SN/A
149955SN/Amain = Environment(ENV=use_env)
150955SN/Amain.root = Dir(".")         # The current directory (where this file lives).
151955SN/Amain.srcdir = Dir("src")     # The source directory
152955SN/A
153955SN/A# add useful python code PYTHONPATH so it can be used by subprocesses
154955SN/A# as well
1551858SN/Amain.AppendENVPath('PYTHONPATH', extra_python_paths)
1561858SN/A
1572632Sstever@eecs.umich.edu########################################################################
158955SN/A#
1591858SN/A# Mercurial Stuff.
1601105SN/A#
1612667Sstever@eecs.umich.edu# If the M5 directory is a mercurial repository, we should do some
1622667Sstever@eecs.umich.edu# extra things.
1632667Sstever@eecs.umich.edu#
1642667Sstever@eecs.umich.edu########################################################################
1652667Sstever@eecs.umich.edu
1662667Sstever@eecs.umich.eduhgdir = main.root.Dir(".hg")
1671869SN/A
1681869SN/Amercurial_style_message = """
1691869SN/AYou're missing the M5 style hook.
1701869SN/APlease install the hook so we can ensure that all code fits a common style.
1711869SN/A
1721065SN/AAll you'd need to do is add the following lines to your repository .hg/hgrc
1732632Sstever@eecs.umich.eduor your personal .hgrc
1742632Sstever@eecs.umich.edu----------------
175955SN/A
1761858SN/A[extensions]
1771858SN/Astyle = %s/util/style.py
1781858SN/A
1791858SN/A[hooks]
1801851SN/Apretxncommit.style = python:style.check_style
1811851SN/Apre-qrefresh.style = python:style.check_style
1821858SN/A""" % (main.root)
1832632Sstever@eecs.umich.edu
184955SN/Amercurial_bin_not_found = """
1852656Sstever@eecs.umich.eduMercurial binary cannot be found, unfortunately this means that we
1862656Sstever@eecs.umich.educannot easily determine the version of M5 that you are running and
1872656Sstever@eecs.umich.eduthis makes error messages more difficult to collect.  Please consider
1882656Sstever@eecs.umich.eduinstalling mercurial if you choose to post an error message
1892656Sstever@eecs.umich.edu"""
1902656Sstever@eecs.umich.edu
1912656Sstever@eecs.umich.edumercurial_lib_not_found = """
1922656Sstever@eecs.umich.eduMercurial libraries cannot be found, ignoring style hook
1932656Sstever@eecs.umich.eduIf you are actually a M5 developer, please fix this and
1942656Sstever@eecs.umich.edurun the style hook. It is important.
1952656Sstever@eecs.umich.edu"""
1962656Sstever@eecs.umich.edu
1972656Sstever@eecs.umich.eduhg_info = "Unknown"
1982656Sstever@eecs.umich.eduif hgdir.exists():
1992656Sstever@eecs.umich.edu    # 1) Grab repository revision if we know it.
2002656Sstever@eecs.umich.edu    cmd = "hg id -n -i -t -b"
2012655Sstever@eecs.umich.edu    try:
2022667Sstever@eecs.umich.edu        hg_info = readCommand(cmd, cwd=main.root.abspath).strip()
2032667Sstever@eecs.umich.edu    except OSError:
2042667Sstever@eecs.umich.edu        print mercurial_bin_not_found
2052667Sstever@eecs.umich.edu
2062667Sstever@eecs.umich.edu    # 2) Ensure that the style hook is in place.
2072667Sstever@eecs.umich.edu    try:
2082667Sstever@eecs.umich.edu        ui = None
2092667Sstever@eecs.umich.edu        if ARGUMENTS.get('IGNORE_STYLE') != 'True':
2102667Sstever@eecs.umich.edu            from mercurial import ui
2112667Sstever@eecs.umich.edu            ui = ui.ui()
2122667Sstever@eecs.umich.edu    except ImportError:
2132667Sstever@eecs.umich.edu        print mercurial_lib_not_found
2142667Sstever@eecs.umich.edu
2152655Sstever@eecs.umich.edu    if ui is not None:
2161858SN/A        ui.readconfig(hgdir.File('hgrc').abspath)
2171858SN/A        style_hook = ui.config('hooks', 'pretxncommit.style', None)
2182638Sstever@eecs.umich.edu
2192638Sstever@eecs.umich.edu        if not style_hook:
2202638Sstever@eecs.umich.edu            print mercurial_style_message
2212638Sstever@eecs.umich.edu            sys.exit(1)
2222638Sstever@eecs.umich.eduelse:
2231858SN/A    print ".hg directory not found"
2241858SN/A
2251858SN/Amain['HG_INFO'] = hg_info
2261858SN/A
2271858SN/A###################################################
2281858SN/A#
2291858SN/A# Figure out which configurations to set up based on the path(s) of
2301859SN/A# the target(s).
2311858SN/A#
2321858SN/A###################################################
2331858SN/A
2341859SN/A# Find default configuration & binary.
2351859SN/ADefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
2361862SN/A
2371862SN/A# helper function: find last occurrence of element in list
2381862SN/Adef rfind(l, elt, offs = -1):
2391862SN/A    for i in range(len(l)+offs, 0, -1):
2401859SN/A        if l[i] == elt:
2411859SN/A            return i
2421963SN/A    raise ValueError, "element not found"
2431963SN/A
2441859SN/A# Each target must have 'build' in the interior of the path; the
2451859SN/A# directory below this will determine the build parameters.  For
2461859SN/A# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2471859SN/A# recognize that ALPHA_SE specifies the configuration because it
2481859SN/A# follow 'build' in the bulid path.
2491859SN/A
2501859SN/A# Generate absolute paths to targets so we can see where the build dir is
2511859SN/Aif COMMAND_LINE_TARGETS:
2521862SN/A    # Ask SCons which directory it was invoked from
2531859SN/A    launch_dir = GetLaunchDir()
2541859SN/A    # Make targets relative to invocation directory
2551859SN/A    abs_targets = [ normpath(joinpath(launch_dir, str(x))) for x in \
2561858SN/A                    COMMAND_LINE_TARGETS]
2571858SN/Aelse:
2582139SN/A    # Default targets are relative to root of tree
2592139SN/A    abs_targets = [ normpath(joinpath(main.root.abspath, str(x))) for x in \
2602139SN/A                    DEFAULT_TARGETS]
2612155SN/A
2622623SN/A
2632637Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
2642155SN/A# collected targets reference.
2651869SN/Avariant_paths = []
2661869SN/Abuild_root = None
2671869SN/Afor t in abs_targets:
2681869SN/A    path_dirs = t.split('/')
2691869SN/A    try:
2702139SN/A        build_top = rfind(path_dirs, 'build', -2)
2711869SN/A    except:
2722508SN/A        print "Error: no non-leaf 'build' dir found on target path", t
2732508SN/A        Exit(1)
2742508SN/A    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2752508SN/A    if not build_root:
2762635Sstever@eecs.umich.edu        build_root = this_build_root
2772635Sstever@eecs.umich.edu    else:
2781869SN/A        if this_build_root != build_root:
2791869SN/A            print "Error: build targets not under same build root\n"\
2801869SN/A                  "  %s\n  %s" % (build_root, this_build_root)
2811869SN/A            Exit(1)
2821869SN/A    variant_path = joinpath('/',*path_dirs[:build_top+2])
2831869SN/A    if variant_path not in variant_paths:
2841869SN/A        variant_paths.append(variant_path)
2851869SN/A
2861965SN/A# Make sure build_root exists (might not if this is the first build there)
2871965SN/Aif not isdir(build_root):
2881965SN/A    mkdir(build_root)
2891869SN/Amain['BUILDROOT'] = build_root
2901869SN/A
2911869SN/AExport('main')
2921869SN/A
2931884SN/Amain.SConsignFile(joinpath(build_root, "sconsign"))
2941884SN/A
2951884SN/A# Default duplicate option is to use hard links, but this messes up
2961869SN/A# when you use emacs to edit a file in the target dir, as emacs moves
2971858SN/A# file to file~ then copies to file, breaking the link.  Symbolic
2981869SN/A# (soft) links work better.
2991869SN/Amain.SetOption('duplicate', 'soft-copy')
3001869SN/A
3011869SN/A#
3021869SN/A# Set up global sticky variables... these are common to an entire build
3031858SN/A# tree (not specific to a particular build like ALPHA_SE)
3041869SN/A#
3051869SN/A
3061869SN/A# Variable validators & converters for global sticky variables
3071869SN/Adef PathListMakeAbsolute(val):
3081869SN/A    if not val:
3091869SN/A        return val
3101869SN/A    f = lambda p: abspath(expanduser(p))
3111869SN/A    return ':'.join(map(f, val.split(':')))
3121869SN/A
3131869SN/Adef PathListAllExist(key, val, env):
3141858SN/A    if not val:
315955SN/A        return
316955SN/A    paths = val.split(':')
3171869SN/A    for path in paths:
3181869SN/A        if not isdir(path):
3191869SN/A            raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
3201869SN/A
3211869SN/Aglobal_sticky_vars_file = joinpath(build_root, 'variables.global')
3221869SN/A
3231869SN/Aglobal_sticky_vars = Variables(global_sticky_vars_file, args=ARGUMENTS)
3241869SN/Aglobal_nonsticky_vars = Variables(args=ARGUMENTS)
3251869SN/A
3261869SN/Aglobal_sticky_vars.AddVariables(
3271869SN/A    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3281869SN/A    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3291869SN/A    ('BATCH', 'Use batch pool for build and tests', False),
3301869SN/A    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3311869SN/A    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3321869SN/A    ('EXTRAS', 'Add Extra directories to the compilation', '',
3331869SN/A     PathListAllExist, PathListMakeAbsolute),
3341869SN/A    )
3351869SN/A
3361869SN/Aglobal_nonsticky_vars.AddVariables(
3371869SN/A    ('VERBOSE', 'Print full tool command lines', False),
3381869SN/A    ('update_ref', 'Update test reference outputs', False)
3391869SN/A    )
3401869SN/A
3411869SN/A
3421869SN/A# base help text
3431869SN/Ahelp_text = '''
3441869SN/AUsage: scons [scons options] [build options] [target(s)]
3451869SN/A
3461869SN/AGlobal sticky options:
3471869SN/A'''
3481869SN/A
3491869SN/A# Update main environment with values from ARGUMENTS & global_sticky_vars_file
3501869SN/Aglobal_sticky_vars.Update(main)
3511869SN/Aglobal_nonsticky_vars.Update(main)
3521869SN/A
3531869SN/Ahelp_text += global_sticky_vars.GenerateHelpText(main)
3541869SN/Ahelp_text += global_nonsticky_vars.GenerateHelpText(main)
3551869SN/A
3562655Sstever@eecs.umich.edu# Save sticky variable settings back to current variables file
3572655Sstever@eecs.umich.eduglobal_sticky_vars.Save(global_sticky_vars_file, main)
3582655Sstever@eecs.umich.edu
3592655Sstever@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
3602655Sstever@eecs.umich.edu# look for sources etc.  This list is exported as base_dir_list.
3612655Sstever@eecs.umich.edubase_dir = main.srcdir.abspath
3622655Sstever@eecs.umich.eduif main['EXTRAS']:
3632655Sstever@eecs.umich.edu    extras_dir_list = main['EXTRAS'].split(':')
3642655Sstever@eecs.umich.eduelse:
3652655Sstever@eecs.umich.edu    extras_dir_list = []
3662655Sstever@eecs.umich.edu
3672655Sstever@eecs.umich.eduExport('base_dir')
3682655Sstever@eecs.umich.eduExport('extras_dir_list')
3692655Sstever@eecs.umich.edu
3702655Sstever@eecs.umich.edu# the ext directory should be on the #includes path
3712655Sstever@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
3722655Sstever@eecs.umich.edu
3732655Sstever@eecs.umich.edudef strip_build_path(path, env):
3742655Sstever@eecs.umich.edu    path = str(path)
3752655Sstever@eecs.umich.edu    variant_base = env['BUILDROOT'] + os.path.sep
3762655Sstever@eecs.umich.edu    if path.startswith(variant_base):
3772655Sstever@eecs.umich.edu        path = path[len(variant_base):]
3782655Sstever@eecs.umich.edu    elif path.startswith('build/'):
3792655Sstever@eecs.umich.edu        path = path[6:]
3802655Sstever@eecs.umich.edu    return path
3812655Sstever@eecs.umich.edu
3822634Sstever@eecs.umich.edu# Generate a string of the form:
3832634Sstever@eecs.umich.edu#   common/path/prefix/src1, src2 -> tgt1, tgt2
3842634Sstever@eecs.umich.edu# to print while building.
3852634Sstever@eecs.umich.educlass Transform(object):
3862634Sstever@eecs.umich.edu    # all specific color settings should be here and nowhere else
3872634Sstever@eecs.umich.edu    tool_color = termcap.Normal
3882638Sstever@eecs.umich.edu    pfx_color = termcap.Yellow
3892638Sstever@eecs.umich.edu    srcs_color = termcap.Yellow + termcap.Bold
3902638Sstever@eecs.umich.edu    arrow_color = termcap.Blue + termcap.Bold
3912638Sstever@eecs.umich.edu    tgts_color = termcap.Yellow + termcap.Bold
3922638Sstever@eecs.umich.edu
3931869SN/A    def __init__(self, tool, max_sources=99):
3941869SN/A        self.format = self.tool_color + (" [%8s] " % tool) \
395955SN/A                      + self.pfx_color + "%s" \
396955SN/A                      + self.srcs_color + "%s" \
397955SN/A                      + self.arrow_color + " -> " \
398955SN/A                      + self.tgts_color + "%s" \
3991858SN/A                      + termcap.Normal
4001858SN/A        self.max_sources = max_sources
4011858SN/A
4022632Sstever@eecs.umich.edu    def __call__(self, target, source, env, for_signature=None):
4032632Sstever@eecs.umich.edu        # truncate source list according to max_sources param
4042632Sstever@eecs.umich.edu        source = source[0:self.max_sources]
4052632Sstever@eecs.umich.edu        def strip(f):
4062632Sstever@eecs.umich.edu            return strip_build_path(str(f), env)
4072634Sstever@eecs.umich.edu        if len(source) > 0:
4082638Sstever@eecs.umich.edu            srcs = map(strip, source)
4092023SN/A        else:
4102632Sstever@eecs.umich.edu            srcs = ['']
4112632Sstever@eecs.umich.edu        tgts = map(strip, target)
4122632Sstever@eecs.umich.edu        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4132632Sstever@eecs.umich.edu        # operation that has nothing to do with paths.
4142632Sstever@eecs.umich.edu        com_pfx = os.path.commonprefix(srcs + tgts)
4152632Sstever@eecs.umich.edu        com_pfx_len = len(com_pfx)
4162632Sstever@eecs.umich.edu        if com_pfx:
4172632Sstever@eecs.umich.edu            # do some cleanup and sanity checking on common prefix
4182632Sstever@eecs.umich.edu            if com_pfx[-1] == ".":
4192632Sstever@eecs.umich.edu                # prefix matches all but file extension: ok
4202632Sstever@eecs.umich.edu                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4212023SN/A                com_pfx = com_pfx[0:-1]
4222632Sstever@eecs.umich.edu            elif com_pfx[-1] == "/":
4232632Sstever@eecs.umich.edu                # common prefix is directory path: OK
4241889SN/A                pass
4251889SN/A            else:
4262632Sstever@eecs.umich.edu                src0_len = len(srcs[0])
4272632Sstever@eecs.umich.edu                tgt0_len = len(tgts[0])
4282632Sstever@eecs.umich.edu                if src0_len == com_pfx_len:
4292632Sstever@eecs.umich.edu                    # source is a substring of target, OK
4302632Sstever@eecs.umich.edu                    pass
4312632Sstever@eecs.umich.edu                elif tgt0_len == com_pfx_len:
4322632Sstever@eecs.umich.edu                    # target is a substring of source, need to back up to
4332632Sstever@eecs.umich.edu                    # avoid empty string on RHS of arrow
4342632Sstever@eecs.umich.edu                    sep_idx = com_pfx.rfind(".")
4352632Sstever@eecs.umich.edu                    if sep_idx != -1:
4362632Sstever@eecs.umich.edu                        com_pfx = com_pfx[0:sep_idx]
4372632Sstever@eecs.umich.edu                    else:
4382632Sstever@eecs.umich.edu                        com_pfx = ''
4392632Sstever@eecs.umich.edu                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4401888SN/A                    # still splitting at file extension: ok
4411888SN/A                    pass
4421869SN/A                else:
4431869SN/A                    # probably a fluke; ignore it
4441858SN/A                    com_pfx = ''
4452598SN/A        # recalculate length in case com_pfx was modified
4462598SN/A        com_pfx_len = len(com_pfx)
4472598SN/A        def fmt(files):
4482598SN/A            f = map(lambda s: s[com_pfx_len:], files)
4492598SN/A            return ', '.join(f)
4501858SN/A        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4511858SN/A
4521858SN/AExport('Transform')
4531858SN/A
4541858SN/A
4551858SN/Aif main['VERBOSE']:
4561858SN/A    def MakeAction(action, string, *args, **kwargs):
4571858SN/A        return Action(action, *args, **kwargs)
4581858SN/Aelse:
4591871SN/A    MakeAction = Action
4601858SN/A    main['CCCOMSTR']        = Transform("CC")
4611858SN/A    main['CXXCOMSTR']       = Transform("CXX")
4621858SN/A    main['ASCOMSTR']        = Transform("AS")
4631858SN/A    main['SWIGCOMSTR']      = Transform("SWIG")
4641858SN/A    main['ARCOMSTR']        = Transform("AR", 0)
4651858SN/A    main['LINKCOMSTR']      = Transform("LINK", 0)
4661858SN/A    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
4671858SN/A    main['M4COMSTR']        = Transform("M4")
4681858SN/A    main['SHCCCOMSTR']      = Transform("SHCC")
4691858SN/A    main['SHCXXCOMSTR']     = Transform("SHCXX")
4701858SN/AExport('MakeAction')
4711859SN/A
4721859SN/ACXX_version = readCommand([main['CXX'],'--version'], exception=False)
4731869SN/ACXX_V = readCommand([main['CXX'],'-V'], exception=False)
4741888SN/A
4752632Sstever@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
4761869SN/Amain['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
4771884SN/Amain['ICC'] = CXX_V and CXX_V.find('Intel') >= 0
4781884SN/Aif main['GCC'] + main['SUNCC'] + main['ICC'] > 1:
4791884SN/A    print 'Error: How can we have two at the same time?'
4801884SN/A    Exit(1)
4811884SN/A
4821884SN/A# Set up default C++ compiler flags
4831965SN/Aif main['GCC']:
4841965SN/A    main.Append(CCFLAGS=['-pipe'])
4851965SN/A    main.Append(CCFLAGS=['-fno-strict-aliasing'])
486955SN/A    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
4871869SN/A    main.Append(CXXFLAGS=['-Wno-deprecated'])
4881869SN/A    # Read the GCC version to check for versions with bugs
4892632Sstever@eecs.umich.edu    # Note CCVERSION doesn't work here because it is run with the CC
4902667Sstever@eecs.umich.edu    # before we override it from the command line
4911869SN/A    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
4921869SN/A    if not compareVersions(gcc_version, '4.4.1') or \
4932632Sstever@eecs.umich.edu       not compareVersions(gcc_version, '4.4.2'):
4942632Sstever@eecs.umich.edu        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
4952632Sstever@eecs.umich.edu        main.Append(CCFLAGS=['-fno-tree-vectorize'])
4962632Sstever@eecs.umich.eduelif main['ICC']:
497955SN/A    pass #Fix me... add warning flags once we clean up icc warnings
4982598SN/Aelif main['SUNCC']:
4992598SN/A    main.Append(CCFLAGS=['-Qoption ccfe'])
500955SN/A    main.Append(CCFLAGS=['-features=gcc'])
501955SN/A    main.Append(CCFLAGS=['-features=extensions'])
502955SN/A    main.Append(CCFLAGS=['-library=stlport4'])
5031530SN/A    main.Append(CCFLAGS=['-xar'])
504955SN/A    #main.Append(CCFLAGS=['-instances=semiexplicit'])
505955SN/Aelse:
506955SN/A    print 'Error: Don\'t know what compiler options to use for your compiler.'
507    print '       Please fix SConstruct and src/SConscript and try again.'
508    Exit(1)
509
510# Set up common yacc/bison flags (needed for Ruby)
511main['YACCFLAGS'] = '-d'
512main['YACCHXXFILESUFFIX'] = '.hh'
513
514# Do this after we save setting back, or else we'll tack on an
515# extra 'qdo' every time we run scons.
516if main['BATCH']:
517    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
518    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
519    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
520    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
521    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
522
523if sys.platform == 'cygwin':
524    # cygwin has some header file issues...
525    main.Append(CCFLAGS=["-Wno-uninitialized"])
526
527# Check for SWIG
528if not main.has_key('SWIG'):
529    print 'Error: SWIG utility not found.'
530    print '       Please install (see http://www.swig.org) and retry.'
531    Exit(1)
532
533# Check for appropriate SWIG version
534swig_version = readCommand(('swig', '-version'), exception='').split()
535# First 3 words should be "SWIG Version x.y.z"
536if len(swig_version) < 3 or \
537        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
538    print 'Error determining SWIG version.'
539    Exit(1)
540
541min_swig_version = '1.3.28'
542if compareVersions(swig_version[2], min_swig_version) < 0:
543    print 'Error: SWIG version', min_swig_version, 'or newer required.'
544    print '       Installed version:', swig_version[2]
545    Exit(1)
546
547# Set up SWIG flags & scanner
548swig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
549main.Append(SWIGFLAGS=swig_flags)
550
551# filter out all existing swig scanners, they mess up the dependency
552# stuff for some reason
553scanners = []
554for scanner in main['SCANNERS']:
555    skeys = scanner.skeys
556    if skeys == '.i':
557        continue
558
559    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
560        continue
561
562    scanners.append(scanner)
563
564# add the new swig scanner that we like better
565from SCons.Scanner import ClassicCPP as CPPScanner
566swig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
567scanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
568
569# replace the scanners list that has what we want
570main['SCANNERS'] = scanners
571
572# Add a custom Check function to the Configure context so that we can
573# figure out if the compiler adds leading underscores to global
574# variables.  This is needed for the autogenerated asm files that we
575# use for embedding the python code.
576def CheckLeading(context):
577    context.Message("Checking for leading underscore in global variables...")
578    # 1) Define a global variable called x from asm so the C compiler
579    #    won't change the symbol at all.
580    # 2) Declare that variable.
581    # 3) Use the variable
582    #
583    # If the compiler prepends an underscore, this will successfully
584    # link because the external symbol 'x' will be called '_x' which
585    # was defined by the asm statement.  If the compiler does not
586    # prepend an underscore, this will not successfully link because
587    # '_x' will have been defined by assembly, while the C portion of
588    # the code will be trying to use 'x'
589    ret = context.TryLink('''
590        asm(".globl _x; _x: .byte 0");
591        extern int x;
592        int main() { return x; }
593        ''', extension=".c")
594    context.env.Append(LEADING_UNDERSCORE=ret)
595    context.Result(ret)
596    return ret
597
598# Platform-specific configuration.  Note again that we assume that all
599# builds under a given build root run on the same host platform.
600conf = Configure(main,
601                 conf_dir = joinpath(build_root, '.scons_config'),
602                 log_file = joinpath(build_root, 'scons_config.log'),
603                 custom_tests = { 'CheckLeading' : CheckLeading })
604
605# Check for leading underscores.  Don't really need to worry either
606# way so don't need to check the return code.
607conf.CheckLeading()
608
609# Check if we should compile a 64 bit binary on Mac OS X/Darwin
610try:
611    import platform
612    uname = platform.uname()
613    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
614        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
615            main.Append(CCFLAGS=['-arch', 'x86_64'])
616            main.Append(CFLAGS=['-arch', 'x86_64'])
617            main.Append(LINKFLAGS=['-arch', 'x86_64'])
618            main.Append(ASFLAGS=['-arch', 'x86_64'])
619except:
620    pass
621
622# Recent versions of scons substitute a "Null" object for Configure()
623# when configuration isn't necessary, e.g., if the "--help" option is
624# present.  Unfortuantely this Null object always returns false,
625# breaking all our configuration checks.  We replace it with our own
626# more optimistic null object that returns True instead.
627if not conf:
628    def NullCheck(*args, **kwargs):
629        return True
630
631    class NullConf:
632        def __init__(self, env):
633            self.env = env
634        def Finish(self):
635            return self.env
636        def __getattr__(self, mname):
637            return NullCheck
638
639    conf = NullConf(main)
640
641# Find Python include and library directories for embedding the
642# interpreter.  For consistency, we will use the same Python
643# installation used to run scons (and thus this script).  If you want
644# to link in an alternate version, see above for instructions on how
645# to invoke scons with a different copy of the Python interpreter.
646from distutils import sysconfig
647
648py_getvar = sysconfig.get_config_var
649
650py_debug = getattr(sys, 'pydebug', False)
651py_version = 'python' + py_getvar('VERSION') + (py_debug and "_d" or "")
652
653py_general_include = sysconfig.get_python_inc()
654py_platform_include = sysconfig.get_python_inc(plat_specific=True)
655py_includes = [ py_general_include ]
656if py_platform_include != py_general_include:
657    py_includes.append(py_platform_include)
658
659py_lib_path = [ py_getvar('LIBDIR') ]
660# add the prefix/lib/pythonX.Y/config dir, but only if there is no
661# shared library in prefix/lib/.
662if not py_getvar('Py_ENABLE_SHARED'):
663    py_lib_path.append(py_getvar('LIBPL'))
664
665py_libs = []
666for lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
667    assert lib.startswith('-l')
668    lib = lib[2:]   
669    if lib not in py_libs:
670        py_libs.append(lib)
671py_libs.append(py_version)
672
673main.Append(CPPPATH=py_includes)
674main.Append(LIBPATH=py_lib_path)
675
676# Cache build files in the supplied directory.
677if main['M5_BUILD_CACHE']:
678    print 'Using build cache located at', main['M5_BUILD_CACHE']
679    CacheDir(main['M5_BUILD_CACHE'])
680
681
682# verify that this stuff works
683if not conf.CheckHeader('Python.h', '<>'):
684    print "Error: can't find Python.h header in", py_includes
685    Exit(1)
686
687for lib in py_libs:
688    if not conf.CheckLib(lib):
689        print "Error: can't find library %s required by python" % lib
690        Exit(1)
691
692# On Solaris you need to use libsocket for socket ops
693if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
694   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
695       print "Can't find library with socket calls (e.g. accept())"
696       Exit(1)
697
698# Check for zlib.  If the check passes, libz will be automatically
699# added to the LIBS environment variable.
700if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
701    print 'Error: did not find needed zlib compression library '\
702          'and/or zlib.h header file.'
703    print '       Please install zlib and try again.'
704    Exit(1)
705
706# Check for librt.
707have_posix_clock = \
708    conf.CheckLibWithHeader(None, 'time.h', 'C',
709                            'clock_nanosleep(0,0,NULL,NULL);') or \
710    conf.CheckLibWithHeader('rt', 'time.h', 'C',
711                            'clock_nanosleep(0,0,NULL,NULL);')
712
713if not have_posix_clock:
714    print "Can't find library for POSIX clocks."
715
716# Check for <fenv.h> (C99 FP environment control)
717have_fenv = conf.CheckHeader('fenv.h', '<>')
718if not have_fenv:
719    print "Warning: Header file <fenv.h> not found."
720    print "         This host has no IEEE FP rounding mode control."
721
722######################################################################
723#
724# Check for mysql.
725#
726mysql_config = WhereIs('mysql_config')
727have_mysql = bool(mysql_config)
728
729# Check MySQL version.
730if have_mysql:
731    mysql_version = readCommand(mysql_config + ' --version')
732    min_mysql_version = '4.1'
733    if compareVersions(mysql_version, min_mysql_version) < 0:
734        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
735        print '         Version', mysql_version, 'detected.'
736        have_mysql = False
737
738# Set up mysql_config commands.
739if have_mysql:
740    mysql_config_include = mysql_config + ' --include'
741    if os.system(mysql_config_include + ' > /dev/null') != 0:
742        # older mysql_config versions don't support --include, use
743        # --cflags instead
744        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
745    # This seems to work in all versions
746    mysql_config_libs = mysql_config + ' --libs'
747
748######################################################################
749#
750# Finish the configuration
751#
752main = conf.Finish()
753
754######################################################################
755#
756# Collect all non-global variables
757#
758
759# Define the universe of supported ISAs
760all_isa_list = [ ]
761Export('all_isa_list')
762
763class CpuModel(object):
764    '''The CpuModel class encapsulates everything the ISA parser needs to
765    know about a particular CPU model.'''
766
767    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
768    dict = {}
769    list = []
770    defaults = []
771
772    # Constructor.  Automatically adds models to CpuModel.dict.
773    def __init__(self, name, filename, includes, strings, default=False):
774        self.name = name           # name of model
775        self.filename = filename   # filename for output exec code
776        self.includes = includes   # include files needed in exec file
777        # The 'strings' dict holds all the per-CPU symbols we can
778        # substitute into templates etc.
779        self.strings = strings
780
781        # This cpu is enabled by default
782        self.default = default
783
784        # Add self to dict
785        if name in CpuModel.dict:
786            raise AttributeError, "CpuModel '%s' already registered" % name
787        CpuModel.dict[name] = self
788        CpuModel.list.append(name)
789
790Export('CpuModel')
791
792# Sticky variables get saved in the variables file so they persist from
793# one invocation to the next (unless overridden, in which case the new
794# value becomes sticky).
795sticky_vars = Variables(args=ARGUMENTS)
796Export('sticky_vars')
797
798# Sticky variables that should be exported
799export_vars = []
800Export('export_vars')
801
802# Walk the tree and execute all SConsopts scripts that wil add to the
803# above variables
804for bdir in [ base_dir ] + extras_dir_list:
805    for root, dirs, files in os.walk(bdir):
806        if 'SConsopts' in files:
807            print "Reading", joinpath(root, 'SConsopts')
808            SConscript(joinpath(root, 'SConsopts'))
809
810all_isa_list.sort()
811
812sticky_vars.AddVariables(
813    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
814    BoolVariable('FULL_SYSTEM', 'Full-system support', False),
815    ListVariable('CPU_MODELS', 'CPU models',
816                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
817                 sorted(CpuModel.list)),
818    BoolVariable('NO_FAST_ALLOC', 'Disable fast object allocator', False),
819    BoolVariable('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
820                 False),
821    BoolVariable('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
822                 False),
823    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
824                 False),
825    BoolVariable('SS_COMPATIBLE_FP',
826                 'Make floating-point results compatible with SimpleScalar',
827                 False),
828    BoolVariable('USE_SSE2',
829                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
830                 False),
831    BoolVariable('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
832    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
833    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
834    BoolVariable('USE_CHECKER', 'Use checker for detailed CPU models', False),
835    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
836    BoolVariable('RUBY', 'Build with Ruby', False),
837    )
838
839# These variables get exported to #defines in config/*.hh (see src/SConscript).
840export_vars += ['FULL_SYSTEM', 'USE_FENV', 'USE_MYSQL',
841                'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', 'FAST_ALLOC_STATS',
842                'SS_COMPATIBLE_FP', 'USE_CHECKER', 'TARGET_ISA', 'CP_ANNOTATE',
843                'USE_POSIX_CLOCK' ]
844
845###################################################
846#
847# Define a SCons builder for configuration flag headers.
848#
849###################################################
850
851# This function generates a config header file that #defines the
852# variable symbol to the current variable setting (0 or 1).  The source
853# operands are the name of the variable and a Value node containing the
854# value of the variable.
855def build_config_file(target, source, env):
856    (variable, value) = [s.get_contents() for s in source]
857    f = file(str(target[0]), 'w')
858    print >> f, '#define', variable, value
859    f.close()
860    return None
861
862# Generate the message to be printed when building the config file.
863def build_config_file_string(target, source, env):
864    (variable, value) = [s.get_contents() for s in source]
865    return "Defining %s as %s in %s." % (variable, value, target[0])
866
867# Combine the two functions into a scons Action object.
868config_action = Action(build_config_file, build_config_file_string)
869
870# The emitter munges the source & target node lists to reflect what
871# we're really doing.
872def config_emitter(target, source, env):
873    # extract variable name from Builder arg
874    variable = str(target[0])
875    # True target is config header file
876    target = joinpath('config', variable.lower() + '.hh')
877    val = env[variable]
878    if isinstance(val, bool):
879        # Force value to 0/1
880        val = int(val)
881    elif isinstance(val, str):
882        val = '"' + val + '"'
883
884    # Sources are variable name & value (packaged in SCons Value nodes)
885    return ([target], [Value(variable), Value(val)])
886
887config_builder = Builder(emitter = config_emitter, action = config_action)
888
889main.Append(BUILDERS = { 'ConfigFile' : config_builder })
890
891# libelf build is shared across all configs in the build root.
892main.SConscript('ext/libelf/SConscript',
893                variant_dir = joinpath(build_root, 'libelf'))
894
895# gzstream build is shared across all configs in the build root.
896main.SConscript('ext/gzstream/SConscript',
897                variant_dir = joinpath(build_root, 'gzstream'))
898
899###################################################
900#
901# This function is used to set up a directory with switching headers
902#
903###################################################
904
905main['ALL_ISA_LIST'] = all_isa_list
906def make_switching_dir(dname, switch_headers, env):
907    # Generate the header.  target[0] is the full path of the output
908    # header to generate.  'source' is a dummy variable, since we get the
909    # list of ISAs from env['ALL_ISA_LIST'].
910    def gen_switch_hdr(target, source, env):
911        fname = str(target[0])
912        f = open(fname, 'w')
913        isa = env['TARGET_ISA'].lower()
914        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
915        f.close()
916
917    # Build SCons Action object. 'varlist' specifies env vars that this
918    # action depends on; when env['ALL_ISA_LIST'] changes these actions
919    # should get re-executed.
920    switch_hdr_action = MakeAction(gen_switch_hdr,
921                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
922
923    # Instantiate actions for each header
924    for hdr in switch_headers:
925        env.Command(hdr, [], switch_hdr_action)
926Export('make_switching_dir')
927
928###################################################
929#
930# Define build environments for selected configurations.
931#
932###################################################
933
934for variant_path in variant_paths:
935    print "Building in", variant_path
936
937    # Make a copy of the build-root environment to use for this config.
938    env = main.Clone()
939    env['BUILDDIR'] = variant_path
940
941    # variant_dir is the tail component of build path, and is used to
942    # determine the build parameters (e.g., 'ALPHA_SE')
943    (build_root, variant_dir) = splitpath(variant_path)
944
945    # Set env variables according to the build directory config.
946    sticky_vars.files = []
947    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
948    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
949    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
950    current_vars_file = joinpath(build_root, 'variables', variant_dir)
951    if isfile(current_vars_file):
952        sticky_vars.files.append(current_vars_file)
953        print "Using saved variables file %s" % current_vars_file
954    else:
955        # Build dir-specific variables file doesn't exist.
956
957        # Make sure the directory is there so we can create it later
958        opt_dir = dirname(current_vars_file)
959        if not isdir(opt_dir):
960            mkdir(opt_dir)
961
962        # Get default build variables from source tree.  Variables are
963        # normally determined by name of $VARIANT_DIR, but can be
964        # overriden by 'default=' arg on command line.
965        default_vars_file = joinpath('build_opts',
966                                     ARGUMENTS.get('default', variant_dir))
967        if isfile(default_vars_file):
968            sticky_vars.files.append(default_vars_file)
969            print "Variables file %s not found,\n  using defaults in %s" \
970                  % (current_vars_file, default_vars_file)
971        else:
972            print "Error: cannot find variables file %s or %s" \
973                  % (current_vars_file, default_vars_file)
974            Exit(1)
975
976    # Apply current variable settings to env
977    sticky_vars.Update(env)
978
979    help_text += "\nSticky variables for %s:\n" % variant_dir \
980                 + sticky_vars.GenerateHelpText(env)
981
982    # Process variable settings.
983
984    if not have_fenv and env['USE_FENV']:
985        print "Warning: <fenv.h> not available; " \
986              "forcing USE_FENV to False in", variant_dir + "."
987        env['USE_FENV'] = False
988
989    if not env['USE_FENV']:
990        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
991        print "         FP results may deviate slightly from other platforms."
992
993    if env['EFENCE']:
994        env.Append(LIBS=['efence'])
995
996    if env['USE_MYSQL']:
997        if not have_mysql:
998            print "Warning: MySQL not available; " \
999                  "forcing USE_MYSQL to False in", variant_dir + "."
1000            env['USE_MYSQL'] = False
1001        else:
1002            print "Compiling in", variant_dir, "with MySQL support."
1003            env.ParseConfig(mysql_config_libs)
1004            env.ParseConfig(mysql_config_include)
1005
1006    # Save sticky variable settings back to current variables file
1007    sticky_vars.Save(current_vars_file, env)
1008
1009    if env['USE_SSE2']:
1010        env.Append(CCFLAGS=['-msse2'])
1011
1012    # The src/SConscript file sets up the build rules in 'env' according
1013    # to the configured variables.  It returns a list of environments,
1014    # one for each variant build (debug, opt, etc.)
1015    envList = SConscript('src/SConscript', variant_dir = variant_path,
1016                         exports = 'env')
1017
1018    # Set up the regression tests for each build.
1019    for e in envList:
1020        SConscript('tests/SConscript',
1021                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1022                   exports = { 'env' : e }, duplicate = False)
1023
1024Help(help_text)
1025