SConstruct revision 9903
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2013 ARM Limited
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
282665Ssaidi@eecs.umich.edu# contributors may be used to endorse or promote products derived from
292665Ssaidi@eecs.umich.edu# this software without specific prior written permission.
30955SN/A#
31955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
352632Sstever@eecs.umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
362632Sstever@eecs.umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
372632Sstever@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
382632Sstever@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
402632Sstever@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422761Sstever@eecs.umich.edu#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452632Sstever@eecs.umich.edu
462761Sstever@eecs.umich.edu###################################################
472761Sstever@eecs.umich.edu#
482761Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492632Sstever@eecs.umich.edu#
502632Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
522761Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532761Sstever@eecs.umich.edu# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
562632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572632Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582632Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
63955SN/A#   scons to search up the directory tree for this SConstruct file.
64955SN/A#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
65955SN/A#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
684202Sbinkertn@umich.edu#   in a directory outside of the source tree.  The '-C' option tells
695342Sstever@gmail.com#   scons to chdir to the specified directory to find this SConstruct
70955SN/A#   file.
715273Sstever@gmail.com#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
725273Sstever@gmail.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732656Sstever@eecs.umich.edu#
742656Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
752656Sstever@eecs.umich.edu# 'gem5' directory (or use -u or -C to tell scons where to find this
762656Sstever@eecs.umich.edu# file), you can use 'scons -h' to print all the gem5-specific build
772656Sstever@eecs.umich.edu# options as well.
782656Sstever@eecs.umich.edu#
792656Sstever@eecs.umich.edu###################################################
802653Sstever@eecs.umich.edu
815227Ssaidi@eecs.umich.edu# Check for recent-enough Python and SCons versions.
825227Ssaidi@eecs.umich.edutry:
835227Ssaidi@eecs.umich.edu    # Really old versions of scons only take two options for the
845227Ssaidi@eecs.umich.edu    # function, so check once without the revision and once with the
852653Sstever@eecs.umich.edu    # revision, the first instance will fail for stuff other than
862653Sstever@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
872653Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98)
882653Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98, 1)
892653Sstever@eecs.umich.eduexcept SystemExit, e:
902653Sstever@eecs.umich.edu    print """
912653Sstever@eecs.umich.eduFor more details, see:
922653Sstever@eecs.umich.edu    http://gem5.org/Dependencies
932653Sstever@eecs.umich.edu"""
944781Snate@binkert.org    raise
951852SN/A
96955SN/A# We ensure the python version early because because python-config
97955SN/A# requires python 2.5
98955SN/Atry:
993717Sstever@eecs.umich.edu    EnsurePythonVersion(2, 5)
1003716Sstever@eecs.umich.eduexcept SystemExit, e:
101955SN/A    print """
1021533SN/AYou can use a non-default installation of the Python interpreter by
1033716Sstever@eecs.umich.edurearranging your PATH so that scons finds the non-default 'python' and
1041533SN/A'python-config' first.
1054678Snate@binkert.org
1064678Snate@binkert.orgFor more details, see:
1074678Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1084678Snate@binkert.org"""
1094678Snate@binkert.org    raise
1104678Snate@binkert.org
1114678Snate@binkert.org# Global Python includes
1124678Snate@binkert.orgimport os
1134678Snate@binkert.orgimport re
1144678Snate@binkert.orgimport subprocess
1154678Snate@binkert.orgimport sys
1164678Snate@binkert.org
1174678Snate@binkert.orgfrom os import mkdir, environ
1184678Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1194678Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1204678Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1214678Snate@binkert.org
1224678Snate@binkert.org# SCons includes
1234678Snate@binkert.orgimport SCons
1244678Snate@binkert.orgimport SCons.Node
1254678Snate@binkert.org
1264973Ssaidi@eecs.umich.eduextra_python_paths = [
1274678Snate@binkert.org    Dir('src/python').srcnode().abspath, # gem5 includes
1284678Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1294678Snate@binkert.org    ]
1304678Snate@binkert.org
1314678Snate@binkert.orgsys.path[1:1] = extra_python_paths
1324678Snate@binkert.org
133955SN/Afrom m5.util import compareVersions, readCommand
134955SN/Afrom m5.util.terminal import get_termcap
1352632Sstever@eecs.umich.edu
1362632Sstever@eecs.umich.eduhelp_texts = {
137955SN/A    "options" : "",
138955SN/A    "global_vars" : "",
139955SN/A    "local_vars" : ""
140955SN/A}
1412632Sstever@eecs.umich.edu
142955SN/AExport("help_texts")
1432632Sstever@eecs.umich.edu
1442632Sstever@eecs.umich.edu
1452632Sstever@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1462632Sstever@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1472632Sstever@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1482632Sstever@eecs.umich.edu# Help() function, but these two features are incompatible: once
1492632Sstever@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1503053Sstever@eecs.umich.edu# at the help texts from AddOptions.  See:
1513053Sstever@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1523053Sstever@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1533053Sstever@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1543053Sstever@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1553053Sstever@eecs.umich.edu# we can just use AddOption directly.
1563053Sstever@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1573053Sstever@eecs.umich.edu    col_width = 30
1583053Sstever@eecs.umich.edu
1593053Sstever@eecs.umich.edu    help = "  " + ", ".join(args)
1603053Sstever@eecs.umich.edu    if "help" in kwargs:
1613053Sstever@eecs.umich.edu        length = len(help)
1623053Sstever@eecs.umich.edu        if length >= col_width:
1633053Sstever@eecs.umich.edu            help += "\n" + " " * col_width
1643053Sstever@eecs.umich.edu        else:
1653053Sstever@eecs.umich.edu            help += " " * (col_width - length)
1662632Sstever@eecs.umich.edu        help += kwargs["help"]
1672632Sstever@eecs.umich.edu    help_texts["options"] += help + "\n"
1682632Sstever@eecs.umich.edu
1692632Sstever@eecs.umich.edu    AddOption(*args, **kwargs)
1702632Sstever@eecs.umich.edu
1712632Sstever@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1723718Sstever@eecs.umich.edu               help="Add color to abbreviated scons output")
1733718Sstever@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1743718Sstever@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1753718Sstever@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1763718Sstever@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1773718Sstever@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1783718Sstever@eecs.umich.edu               help='Disable style checking hooks')
1793718Sstever@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1803718Sstever@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1813718Sstever@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1823718Sstever@eecs.umich.edu               help='Update test reference outputs')
1833718Sstever@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1843718Sstever@eecs.umich.edu               help='Print full tool command lines')
1852634Sstever@eecs.umich.edu
1862634Sstever@eecs.umich.edutermcap = get_termcap(GetOption('use_colors'))
1872632Sstever@eecs.umich.edu
1882638Sstever@eecs.umich.edu########################################################################
1892632Sstever@eecs.umich.edu#
1902632Sstever@eecs.umich.edu# Set up the main build environment.
1912632Sstever@eecs.umich.edu#
1922632Sstever@eecs.umich.edu########################################################################
1932632Sstever@eecs.umich.eduuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
1942632Sstever@eecs.umich.edu                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PYTHONPATH',
1951858SN/A                 'RANLIB', 'SWIG' ])
1963716Sstever@eecs.umich.edu
1972638Sstever@eecs.umich.eduuse_prefixes = [
1982638Sstever@eecs.umich.edu    "M5",           # M5 configuration (e.g., path to kernels)
1992638Sstever@eecs.umich.edu    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
2002638Sstever@eecs.umich.edu    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2012638Sstever@eecs.umich.edu    "CCC_",         # clang static analyzer configuration
2022638Sstever@eecs.umich.edu    ]
2032638Sstever@eecs.umich.edu
2043716Sstever@eecs.umich.eduuse_env = {}
2052634Sstever@eecs.umich.edufor key,val in os.environ.iteritems():
2062634Sstever@eecs.umich.edu    if key in use_vars or \
207955SN/A            any([key.startswith(prefix) for prefix in use_prefixes]):
2085341Sstever@gmail.com        use_env[key] = val
2095341Sstever@gmail.com
2105341Sstever@gmail.commain = Environment(ENV=use_env)
2115341Sstever@gmail.commain.Decider('MD5-timestamp')
212955SN/Amain.root = Dir(".")         # The current directory (where this file lives).
213955SN/Amain.srcdir = Dir("src")     # The source directory
214955SN/A
215955SN/Amain_dict_keys = main.Dictionary().keys()
216955SN/A
217955SN/A# Check that we have a C/C++ compiler
218955SN/Aif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2191858SN/A    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2201858SN/A    Exit(1)
2212632Sstever@eecs.umich.edu
222955SN/A# Check that swig is present
2234494Ssaidi@eecs.umich.eduif not 'SWIG' in main_dict_keys:
2244494Ssaidi@eecs.umich.edu    print "swig is not installed (package swig on Ubuntu and RedHat)"
2253716Sstever@eecs.umich.edu    Exit(1)
2261105SN/A
2272667Sstever@eecs.umich.edu# add useful python code PYTHONPATH so it can be used by subprocesses
2282667Sstever@eecs.umich.edu# as well
2292667Sstever@eecs.umich.edumain.AppendENVPath('PYTHONPATH', extra_python_paths)
2302667Sstever@eecs.umich.edu
2312667Sstever@eecs.umich.edu########################################################################
2322667Sstever@eecs.umich.edu#
2331869SN/A# Mercurial Stuff.
2341869SN/A#
2351869SN/A# If the gem5 directory is a mercurial repository, we should do some
2361869SN/A# extra things.
2371869SN/A#
2381065SN/A########################################################################
2395341Sstever@gmail.com
2405341Sstever@gmail.comhgdir = main.root.Dir(".hg")
2415341Sstever@gmail.com
2425341Sstever@gmail.commercurial_style_message = """
2435341Sstever@gmail.comYou're missing the gem5 style hook, which automatically checks your code
2445341Sstever@gmail.comagainst the gem5 style rules on hg commit and qrefresh commands.  This
2455341Sstever@gmail.comscript will now install the hook in your .hg/hgrc file.
2465341Sstever@gmail.comPress enter to continue, or ctrl-c to abort: """
2475341Sstever@gmail.com
2485341Sstever@gmail.commercurial_style_hook = """
2495341Sstever@gmail.com# The following lines were automatically added by gem5/SConstruct
2505341Sstever@gmail.com# to provide the gem5 style-checking hooks
2515341Sstever@gmail.com[extensions]
2525341Sstever@gmail.comstyle = %s/util/style.py
2535341Sstever@gmail.com
2545341Sstever@gmail.com[hooks]
2555341Sstever@gmail.compretxncommit.style = python:style.check_style
2565341Sstever@gmail.compre-qrefresh.style = python:style.check_style
2575341Sstever@gmail.com# End of SConstruct additions
2585341Sstever@gmail.com
2595341Sstever@gmail.com""" % (main.root.abspath)
2605341Sstever@gmail.com
2615341Sstever@gmail.commercurial_lib_not_found = """
2625341Sstever@gmail.comMercurial libraries cannot be found, ignoring style hook.  If
2635341Sstever@gmail.comyou are a gem5 developer, please fix this and run the style
2645341Sstever@gmail.comhook. It is important.
2655341Sstever@gmail.com"""
2665341Sstever@gmail.com
2675341Sstever@gmail.com# Check for style hook and prompt for installation if it's not there.
2685341Sstever@gmail.com# Skip this if --ignore-style was specified, there's no .hg dir to
2695341Sstever@gmail.com# install a hook in, or there's no interactive terminal to prompt.
2705341Sstever@gmail.comif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2715341Sstever@gmail.com    style_hook = True
2725341Sstever@gmail.com    try:
2735341Sstever@gmail.com        from mercurial import ui
2745341Sstever@gmail.com        ui = ui.ui()
2755341Sstever@gmail.com        ui.readconfig(hgdir.File('hgrc').abspath)
2765341Sstever@gmail.com        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2775341Sstever@gmail.com                     ui.config('hooks', 'pre-qrefresh.style', None)
2785341Sstever@gmail.com    except ImportError:
2795341Sstever@gmail.com        print mercurial_lib_not_found
2805341Sstever@gmail.com
2815341Sstever@gmail.com    if not style_hook:
2825341Sstever@gmail.com        print mercurial_style_message,
2835341Sstever@gmail.com        # continue unless user does ctrl-c/ctrl-d etc.
2845341Sstever@gmail.com        try:
2855341Sstever@gmail.com            raw_input()
2865341Sstever@gmail.com        except:
2875341Sstever@gmail.com            print "Input exception, exiting scons.\n"
2885341Sstever@gmail.com            sys.exit(1)
2895341Sstever@gmail.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2905341Sstever@gmail.com        print "Adding style hook to", hgrc_path, "\n"
2915341Sstever@gmail.com        try:
2925341Sstever@gmail.com            hgrc = open(hgrc_path, 'a')
2935341Sstever@gmail.com            hgrc.write(mercurial_style_hook)
2942632Sstever@eecs.umich.edu            hgrc.close()
2955199Sstever@gmail.com        except:
2963918Ssaidi@eecs.umich.edu            print "Error updating", hgrc_path
2973918Ssaidi@eecs.umich.edu            sys.exit(1)
2983940Ssaidi@eecs.umich.edu
2994781Snate@binkert.org
3004781Snate@binkert.org###################################################
3013918Ssaidi@eecs.umich.edu#
3024781Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
3034781Snate@binkert.org# the target(s).
3043918Ssaidi@eecs.umich.edu#
3054781Snate@binkert.org###################################################
3064781Snate@binkert.org
3073940Ssaidi@eecs.umich.edu# Find default configuration & binary.
3083942Ssaidi@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3093940Ssaidi@eecs.umich.edu
3103918Ssaidi@eecs.umich.edu# helper function: find last occurrence of element in list
3113918Ssaidi@eecs.umich.edudef rfind(l, elt, offs = -1):
312955SN/A    for i in range(len(l)+offs, 0, -1):
3131858SN/A        if l[i] == elt:
3143918Ssaidi@eecs.umich.edu            return i
3153918Ssaidi@eecs.umich.edu    raise ValueError, "element not found"
3163918Ssaidi@eecs.umich.edu
3173918Ssaidi@eecs.umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
3183940Ssaidi@eecs.umich.edu# paths made absolute and ~-expanded.  Paths will be interpreted
3193940Ssaidi@eecs.umich.edu# relative to the launch directory unless a different root is provided
3203918Ssaidi@eecs.umich.edudef makePathListAbsolute(path_list, root=GetLaunchDir()):
3213918Ssaidi@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
3223918Ssaidi@eecs.umich.edu            for p in path_list]
3233918Ssaidi@eecs.umich.edu
3243918Ssaidi@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
3253918Ssaidi@eecs.umich.edu# directory below this will determine the build parameters.  For
3263918Ssaidi@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3273918Ssaidi@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
3283918Ssaidi@eecs.umich.edu# follow 'build' in the build path.
3293940Ssaidi@eecs.umich.edu
3303918Ssaidi@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
3313918Ssaidi@eecs.umich.edu# in place rather than reassign the symbol to a new list, which
3321851SN/A# doesn't work (obviously!).
3331851SN/ABUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3341858SN/A
3355200Sstever@gmail.com# Generate a list of the unique build roots and configs that the
336955SN/A# collected targets reference.
3373053Sstever@eecs.umich.eduvariant_paths = []
3383053Sstever@eecs.umich.edubuild_root = None
3393053Sstever@eecs.umich.edufor t in BUILD_TARGETS:
3403053Sstever@eecs.umich.edu    path_dirs = t.split('/')
3413053Sstever@eecs.umich.edu    try:
3423053Sstever@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
3433053Sstever@eecs.umich.edu    except:
3443053Sstever@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
3453053Sstever@eecs.umich.edu        Exit(1)
3464742Sstever@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3474742Sstever@eecs.umich.edu    if not build_root:
3483053Sstever@eecs.umich.edu        build_root = this_build_root
3493053Sstever@eecs.umich.edu    else:
3503053Sstever@eecs.umich.edu        if this_build_root != build_root:
3513053Sstever@eecs.umich.edu            print "Error: build targets not under same build root\n"\
3523053Sstever@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
3533053Sstever@eecs.umich.edu            Exit(1)
3543053Sstever@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
3553053Sstever@eecs.umich.edu    if variant_path not in variant_paths:
3563053Sstever@eecs.umich.edu        variant_paths.append(variant_path)
3572667Sstever@eecs.umich.edu
3584554Sbinkertn@umich.edu# Make sure build_root exists (might not if this is the first build there)
3594554Sbinkertn@umich.eduif not isdir(build_root):
3602667Sstever@eecs.umich.edu    mkdir(build_root)
3614554Sbinkertn@umich.edumain['BUILDROOT'] = build_root
3624554Sbinkertn@umich.edu
3634554Sbinkertn@umich.eduExport('main')
3644554Sbinkertn@umich.edu
3654554Sbinkertn@umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
3664554Sbinkertn@umich.edu
3674554Sbinkertn@umich.edu# Default duplicate option is to use hard links, but this messes up
3684781Snate@binkert.org# when you use emacs to edit a file in the target dir, as emacs moves
3694554Sbinkertn@umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
3704554Sbinkertn@umich.edu# (soft) links work better.
3712667Sstever@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
3724554Sbinkertn@umich.edu
3734554Sbinkertn@umich.edu#
3744554Sbinkertn@umich.edu# Set up global sticky variables... these are common to an entire build
3754554Sbinkertn@umich.edu# tree (not specific to a particular build like ALPHA_SE)
3762667Sstever@eecs.umich.edu#
3774554Sbinkertn@umich.edu
3782667Sstever@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
3794554Sbinkertn@umich.edu
3804554Sbinkertn@umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3812667Sstever@eecs.umich.edu
3822638Sstever@eecs.umich.eduglobal_vars.AddVariables(
3832638Sstever@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3842638Sstever@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3853716Sstever@eecs.umich.edu    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3863716Sstever@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3871858SN/A    ('BATCH', 'Use batch pool for build and tests', False),
3885227Ssaidi@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3895227Ssaidi@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3905227Ssaidi@eecs.umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
3915227Ssaidi@eecs.umich.edu    )
3925227Ssaidi@eecs.umich.edu
3935227Ssaidi@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
3945227Ssaidi@eecs.umich.eduglobal_vars.Update(main)
3955227Ssaidi@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3965227Ssaidi@eecs.umich.edu
3975227Ssaidi@eecs.umich.edu# Save sticky variable settings back to current variables file
3985227Ssaidi@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
3995227Ssaidi@eecs.umich.edu
4005274Ssaidi@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
4015227Ssaidi@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
4025227Ssaidi@eecs.umich.edubase_dir = main.srcdir.abspath
4035227Ssaidi@eecs.umich.eduif main['EXTRAS']:
4045204Sstever@gmail.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
4055204Sstever@gmail.comelse:
4065204Sstever@gmail.com    extras_dir_list = []
4075204Sstever@gmail.com
4085204Sstever@gmail.comExport('base_dir')
4095204Sstever@gmail.comExport('extras_dir_list')
4105204Sstever@gmail.com
4115204Sstever@gmail.com# the ext directory should be on the #includes path
4125204Sstever@gmail.commain.Append(CPPPATH=[Dir('ext')])
4135204Sstever@gmail.com
4145204Sstever@gmail.comdef strip_build_path(path, env):
4155204Sstever@gmail.com    path = str(path)
4165204Sstever@gmail.com    variant_base = env['BUILDROOT'] + os.path.sep
4175204Sstever@gmail.com    if path.startswith(variant_base):
4185204Sstever@gmail.com        path = path[len(variant_base):]
4195204Sstever@gmail.com    elif path.startswith('build/'):
4205204Sstever@gmail.com        path = path[6:]
4215204Sstever@gmail.com    return path
4225204Sstever@gmail.com
4233118Sstever@eecs.umich.edu# Generate a string of the form:
4243118Sstever@eecs.umich.edu#   common/path/prefix/src1, src2 -> tgt1, tgt2
4253118Sstever@eecs.umich.edu# to print while building.
4263118Sstever@eecs.umich.educlass Transform(object):
4273118Sstever@eecs.umich.edu    # all specific color settings should be here and nowhere else
4283118Sstever@eecs.umich.edu    tool_color = termcap.Normal
4293118Sstever@eecs.umich.edu    pfx_color = termcap.Yellow
4303118Sstever@eecs.umich.edu    srcs_color = termcap.Yellow + termcap.Bold
4313118Sstever@eecs.umich.edu    arrow_color = termcap.Blue + termcap.Bold
4323118Sstever@eecs.umich.edu    tgts_color = termcap.Yellow + termcap.Bold
4333118Sstever@eecs.umich.edu
4343716Sstever@eecs.umich.edu    def __init__(self, tool, max_sources=99):
4353118Sstever@eecs.umich.edu        self.format = self.tool_color + (" [%8s] " % tool) \
4363118Sstever@eecs.umich.edu                      + self.pfx_color + "%s" \
4373118Sstever@eecs.umich.edu                      + self.srcs_color + "%s" \
4383118Sstever@eecs.umich.edu                      + self.arrow_color + " -> " \
4393118Sstever@eecs.umich.edu                      + self.tgts_color + "%s" \
4403118Sstever@eecs.umich.edu                      + termcap.Normal
4413118Sstever@eecs.umich.edu        self.max_sources = max_sources
4423118Sstever@eecs.umich.edu
4433118Sstever@eecs.umich.edu    def __call__(self, target, source, env, for_signature=None):
4443716Sstever@eecs.umich.edu        # truncate source list according to max_sources param
4453118Sstever@eecs.umich.edu        source = source[0:self.max_sources]
4463118Sstever@eecs.umich.edu        def strip(f):
4473118Sstever@eecs.umich.edu            return strip_build_path(str(f), env)
4483118Sstever@eecs.umich.edu        if len(source) > 0:
4493118Sstever@eecs.umich.edu            srcs = map(strip, source)
4503118Sstever@eecs.umich.edu        else:
4513118Sstever@eecs.umich.edu            srcs = ['']
4523118Sstever@eecs.umich.edu        tgts = map(strip, target)
4533118Sstever@eecs.umich.edu        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4543118Sstever@eecs.umich.edu        # operation that has nothing to do with paths.
4553483Ssaidi@eecs.umich.edu        com_pfx = os.path.commonprefix(srcs + tgts)
4563494Ssaidi@eecs.umich.edu        com_pfx_len = len(com_pfx)
4573494Ssaidi@eecs.umich.edu        if com_pfx:
4583483Ssaidi@eecs.umich.edu            # do some cleanup and sanity checking on common prefix
4593483Ssaidi@eecs.umich.edu            if com_pfx[-1] == ".":
4603483Ssaidi@eecs.umich.edu                # prefix matches all but file extension: ok
4613053Sstever@eecs.umich.edu                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4623053Sstever@eecs.umich.edu                com_pfx = com_pfx[0:-1]
4633918Ssaidi@eecs.umich.edu            elif com_pfx[-1] == "/":
4643053Sstever@eecs.umich.edu                # common prefix is directory path: OK
4653053Sstever@eecs.umich.edu                pass
4663053Sstever@eecs.umich.edu            else:
4673053Sstever@eecs.umich.edu                src0_len = len(srcs[0])
4683053Sstever@eecs.umich.edu                tgt0_len = len(tgts[0])
4691858SN/A                if src0_len == com_pfx_len:
4701858SN/A                    # source is a substring of target, OK
4711858SN/A                    pass
4721858SN/A                elif tgt0_len == com_pfx_len:
4731858SN/A                    # target is a substring of source, need to back up to
4741858SN/A                    # avoid empty string on RHS of arrow
4751859SN/A                    sep_idx = com_pfx.rfind(".")
4761858SN/A                    if sep_idx != -1:
4771858SN/A                        com_pfx = com_pfx[0:sep_idx]
4781858SN/A                    else:
4791859SN/A                        com_pfx = ''
4801859SN/A                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4811862SN/A                    # still splitting at file extension: ok
4823053Sstever@eecs.umich.edu                    pass
4833053Sstever@eecs.umich.edu                else:
4843053Sstever@eecs.umich.edu                    # probably a fluke; ignore it
4853053Sstever@eecs.umich.edu                    com_pfx = ''
4861859SN/A        # recalculate length in case com_pfx was modified
4871859SN/A        com_pfx_len = len(com_pfx)
4881859SN/A        def fmt(files):
4891859SN/A            f = map(lambda s: s[com_pfx_len:], files)
4901859SN/A            return ', '.join(f)
4911859SN/A        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4921859SN/A
4931859SN/AExport('Transform')
4941862SN/A
4951859SN/A# enable the regression script to use the termcap
4961859SN/Amain['TERMCAP'] = termcap
4971859SN/A
4981858SN/Aif GetOption('verbose'):
4991858SN/A    def MakeAction(action, string, *args, **kwargs):
5002139SN/A        return Action(action, *args, **kwargs)
5014202Sbinkertn@umich.eduelse:
5024202Sbinkertn@umich.edu    MakeAction = Action
5032139SN/A    main['CCCOMSTR']        = Transform("CC")
5042155SN/A    main['CXXCOMSTR']       = Transform("CXX")
5054202Sbinkertn@umich.edu    main['ASCOMSTR']        = Transform("AS")
5064202Sbinkertn@umich.edu    main['SWIGCOMSTR']      = Transform("SWIG")
5074202Sbinkertn@umich.edu    main['ARCOMSTR']        = Transform("AR", 0)
5082155SN/A    main['LINKCOMSTR']      = Transform("LINK", 0)
5091869SN/A    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5101869SN/A    main['M4COMSTR']        = Transform("M4")
5111869SN/A    main['SHCCCOMSTR']      = Transform("SHCC")
5121869SN/A    main['SHCXXCOMSTR']     = Transform("SHCXX")
5134202Sbinkertn@umich.eduExport('MakeAction')
5144202Sbinkertn@umich.edu
5154202Sbinkertn@umich.edu# Initialize the Link-Time Optimization (LTO) flags
5164202Sbinkertn@umich.edumain['LTO_CCFLAGS'] = []
5174202Sbinkertn@umich.edumain['LTO_LDFLAGS'] = []
5184202Sbinkertn@umich.edu
5194202Sbinkertn@umich.edu# According to the readme, tcmalloc works best if the compiler doesn't
5204202Sbinkertn@umich.edu# assume that we're using the builtin malloc and friends. These flags
5215341Sstever@gmail.com# are compiler-specific, so we need to set them after we detect which
5225341Sstever@gmail.com# compiler we're using.
5235341Sstever@gmail.commain['TCMALLOC_CCFLAGS'] = []
5245342Sstever@gmail.com
5255342Sstever@gmail.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5264202Sbinkertn@umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5274202Sbinkertn@umich.edu
5284202Sbinkertn@umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5294202Sbinkertn@umich.edumain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5304202Sbinkertn@umich.eduif main['GCC'] + main['CLANG'] > 1:
5311869SN/A    print 'Error: How can we have two at the same time?'
5324202Sbinkertn@umich.edu    Exit(1)
5331869SN/A
5342508SN/A# Set up default C++ compiler flags
5352508SN/Aif main['GCC'] or main['CLANG']:
5362508SN/A    # As gcc and clang share many flags, do the common parts here
5372508SN/A    main.Append(CCFLAGS=['-pipe'])
5384202Sbinkertn@umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5391869SN/A    # Enable -Wall and then disable the few warnings that we
5401869SN/A    # consistently violate
5411869SN/A    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5421869SN/A    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
5431869SN/A    # actually use that name, so we stick with c++0x
5441869SN/A    main.Append(CXXFLAGS=['-std=c++0x'])
5451965SN/A    # Add selected sanity checks from -Wextra
5461965SN/A    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5471965SN/A                          '-Woverloaded-virtual'])
5481869SN/Aelse:
5491869SN/A    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5502733Sktlim@umich.edu    print "Don't know what compiler options to use for your compiler."
5511884SN/A    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5523356Sbinkertn@umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
5533356Sbinkertn@umich.edu    if not CXX_version:
5543356Sbinkertn@umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5554773Snate@binkert.org               termcap.Normal
5561869SN/A    else:
5571858SN/A        print CXX_version.replace('\n', '<nl>')
5581869SN/A    print "       If you're trying to use a compiler other than GCC"
5591869SN/A    print "       or clang, there appears to be something wrong with your"
5601869SN/A    print "       environment."
5611858SN/A    print "       "
5622761Sstever@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
5631869SN/A    print "       above you will need to ease fix SConstruct and "
5642733Sktlim@umich.edu    print "       src/SConscript to support that compiler."
5653584Ssaidi@eecs.umich.edu    Exit(1)
5661869SN/A
5671869SN/Aif main['GCC']:
5681869SN/A    # Check for a supported version of gcc, >= 4.4 is needed for c++0x
5691869SN/A    # support. See http://gcc.gnu.org/projects/cxx0x.html for details
5701869SN/A    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5711869SN/A    if compareVersions(gcc_version, "4.4") < 0:
5721858SN/A        print 'Error: gcc version 4.4 or newer required.'
573955SN/A        print '       Installed version:', gcc_version
574955SN/A        Exit(1)
5751869SN/A
5761869SN/A    main['GCC_VERSION'] = gcc_version
5771869SN/A
5781869SN/A    # Check for versions with bugs
5791869SN/A    if not compareVersions(gcc_version, '4.4.1') or \
5801869SN/A       not compareVersions(gcc_version, '4.4.2'):
5811869SN/A        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
5821869SN/A        main.Append(CCFLAGS=['-fno-tree-vectorize'])
5831869SN/A
5841869SN/A    # LTO support is only really working properly from 4.6 and beyond
5851869SN/A    if compareVersions(gcc_version, '4.6') >= 0:
5861869SN/A        # Add the appropriate Link-Time Optimization (LTO) flags
5871869SN/A        # unless LTO is explicitly turned off. Note that these flags
5881869SN/A        # are only used by the fast target.
5891869SN/A        if not GetOption('no_lto'):
5901869SN/A            # Pass the LTO flag when compiling to produce GIMPLE
5911869SN/A            # output, we merely create the flags here and only append
5921869SN/A            # them later/
5931869SN/A            main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
5941869SN/A
5951869SN/A            # Use the same amount of jobs for LTO as we are running
5961869SN/A            # scons with, we hardcode the use of the linker plugin
5971869SN/A            # which requires either gold or GNU ld >= 2.21
5981869SN/A            main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
5991869SN/A                                   '-fuse-linker-plugin']
6001869SN/A
6011869SN/A    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6021869SN/A                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6031869SN/A
6043716Sstever@eecs.umich.eduelif main['CLANG']:
6053356Sbinkertn@umich.edu    # Check for a supported version of clang, >= 2.9 is needed to
6063356Sbinkertn@umich.edu    # support similar features as gcc 4.4. See
6073356Sbinkertn@umich.edu    # http://clang.llvm.org/cxx_status.html for details
6083356Sbinkertn@umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
6093356Sbinkertn@umich.edu    clang_version_match = clang_version_re.match(CXX_version)
6103356Sbinkertn@umich.edu    if (clang_version_match):
6114781Snate@binkert.org        clang_version = clang_version_match.groups()[0]
6121869SN/A        if compareVersions(clang_version, "2.9") < 0:
6131869SN/A            print 'Error: clang version 2.9 or newer required.'
6141869SN/A            print '       Installed version:', clang_version
6151869SN/A            Exit(1)
6161869SN/A    else:
6171869SN/A        print 'Error: Unable to determine clang version.'
6181869SN/A        Exit(1)
6192655Sstever@eecs.umich.edu
6202655Sstever@eecs.umich.edu    # clang has a few additional warnings that we disable,
6212655Sstever@eecs.umich.edu    # tautological comparisons are allowed due to unsigned integers
6222655Sstever@eecs.umich.edu    # being compared to constants that happen to be 0, and extraneous
6232655Sstever@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
6242655Sstever@eecs.umich.edu    # finally self assignments are allowed as the generated CPU code
6252655Sstever@eecs.umich.edu    # is relying on this
6262655Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-tautological-compare',
6272655Sstever@eecs.umich.edu                         '-Wno-parentheses',
6282655Sstever@eecs.umich.edu                         '-Wno-self-assign'])
6292655Sstever@eecs.umich.edu
6302655Sstever@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6312655Sstever@eecs.umich.edu
6322655Sstever@eecs.umich.edu    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6332655Sstever@eecs.umich.edu    # opposed to libstdc++, as the later is dated.
6342655Sstever@eecs.umich.edu    if sys.platform == "darwin":
6352655Sstever@eecs.umich.edu        main.Append(CXXFLAGS=['-stdlib=libc++'])
6362655Sstever@eecs.umich.edu        main.Append(LIBS=['c++'])
6372655Sstever@eecs.umich.edu
6382655Sstever@eecs.umich.eduelse:
6392655Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6402655Sstever@eecs.umich.edu    print "Don't know what compiler options to use for your compiler."
6412655Sstever@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6422655Sstever@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
6432655Sstever@eecs.umich.edu    if not CXX_version:
6442655Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6452638Sstever@eecs.umich.edu               termcap.Normal
6462638Sstever@eecs.umich.edu    else:
6473716Sstever@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
6482638Sstever@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
6492638Sstever@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
6501869SN/A    print "       environment."
6511869SN/A    print "       "
6523546Sgblack@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
6533546Sgblack@eecs.umich.edu    print "       above you will need to ease fix SConstruct and "
6543546Sgblack@eecs.umich.edu    print "       src/SConscript to support that compiler."
6553546Sgblack@eecs.umich.edu    Exit(1)
6564202Sbinkertn@umich.edu
6573546Sgblack@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
6583546Sgblack@eecs.umich.edumain['YACCFLAGS'] = '-d'
6593546Sgblack@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
6603546Sgblack@eecs.umich.edu
6613546Sgblack@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
6624781Snate@binkert.org# extra 'qdo' every time we run scons.
6634781Snate@binkert.orgif main['BATCH']:
6644781Snate@binkert.org    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6654781Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6664781Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6674781Snate@binkert.org    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6684781Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6694781Snate@binkert.org
6704781Snate@binkert.orgif sys.platform == 'cygwin':
6714781Snate@binkert.org    # cygwin has some header file issues...
6724781Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
6734781Snate@binkert.org
6743546Sgblack@eecs.umich.edu# Check for the protobuf compiler
6753546Sgblack@eecs.umich.eduprotoc_version = readCommand([main['PROTOC'], '--version'],
6763546Sgblack@eecs.umich.edu                             exception='').split()
6774781Snate@binkert.org
6783546Sgblack@eecs.umich.edu# First two words should be "libprotoc x.y.z"
6793546Sgblack@eecs.umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6803546Sgblack@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
6813546Sgblack@eecs.umich.edu        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6823546Sgblack@eecs.umich.edu        '         Please install protobuf-compiler for tracing support.' + \
6833546Sgblack@eecs.umich.edu        termcap.Normal
6843546Sgblack@eecs.umich.edu    main['PROTOC'] = False
6853546Sgblack@eecs.umich.eduelse:
6863546Sgblack@eecs.umich.edu    # Based on the availability of the compress stream wrappers,
6873546Sgblack@eecs.umich.edu    # require 2.1.0
6884202Sbinkertn@umich.edu    min_protoc_version = '2.1.0'
6893546Sgblack@eecs.umich.edu    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6903546Sgblack@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
6913546Sgblack@eecs.umich.edu            'Warning: protoc version', min_protoc_version, \
692955SN/A            'or newer required.\n' + \
693955SN/A            '         Installed version:', protoc_version[1], \
694955SN/A            termcap.Normal
695955SN/A        main['PROTOC'] = False
6961858SN/A    else:
6971858SN/A        # Attempt to determine the appropriate include path and
6981858SN/A        # library path using pkg-config, that means we also need to
6992632Sstever@eecs.umich.edu        # check for pkg-config. Note that it is possible to use
7002632Sstever@eecs.umich.edu        # protobuf without the involvement of pkg-config. Later on we
7014773Snate@binkert.org        # check go a library config check and at that point the test
7024773Snate@binkert.org        # will fail if libprotobuf cannot be found.
7032632Sstever@eecs.umich.edu        if readCommand(['pkg-config', '--version'], exception=''):
7042632Sstever@eecs.umich.edu            try:
7052632Sstever@eecs.umich.edu                # Attempt to establish what linking flags to add for protobuf
7062634Sstever@eecs.umich.edu                # using pkg-config
7072638Sstever@eecs.umich.edu                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7082023SN/A            except:
7092632Sstever@eecs.umich.edu                print termcap.Yellow + termcap.Bold + \
7102632Sstever@eecs.umich.edu                    'Warning: pkg-config could not get protobuf flags.' + \
7112632Sstever@eecs.umich.edu                    termcap.Normal
7122632Sstever@eecs.umich.edu
7132632Sstever@eecs.umich.edu# Check for SWIG
7143716Sstever@eecs.umich.eduif not main.has_key('SWIG'):
7155342Sstever@gmail.com    print 'Error: SWIG utility not found.'
7162632Sstever@eecs.umich.edu    print '       Please install (see http://www.swig.org) and retry.'
7172632Sstever@eecs.umich.edu    Exit(1)
7182632Sstever@eecs.umich.edu
7192632Sstever@eecs.umich.edu# Check for appropriate SWIG version
7202023SN/Aswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7212632Sstever@eecs.umich.edu# First 3 words should be "SWIG Version x.y.z"
7222632Sstever@eecs.umich.eduif len(swig_version) < 3 or \
7235342Sstever@gmail.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7241889SN/A    print 'Error determining SWIG version.'
7252632Sstever@eecs.umich.edu    Exit(1)
7262632Sstever@eecs.umich.edu
7272632Sstever@eecs.umich.edumin_swig_version = '1.3.34'
7282632Sstever@eecs.umich.eduif compareVersions(swig_version[2], min_swig_version) < 0:
7293716Sstever@eecs.umich.edu    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7303716Sstever@eecs.umich.edu    print '       Installed version:', swig_version[2]
7315342Sstever@gmail.com    Exit(1)
7322632Sstever@eecs.umich.edu
7332632Sstever@eecs.umich.edu# Older versions of swig do not play well with more recent versions of
7342632Sstever@eecs.umich.edu# gcc due to assumptions on implicit includes (cstddef) and use of
7352632Sstever@eecs.umich.edu# namespaces
7362632Sstever@eecs.umich.eduif main['GCC'] and compareVersions(gcc_version, '4.6') > 0 and \
7372632Sstever@eecs.umich.edu        compareVersions(swig_version[2], '2') < 0:
7382632Sstever@eecs.umich.edu    print '\n' + termcap.Yellow + termcap.Bold + \
7391888SN/A        'Warning: SWIG 1.x cause issues with gcc 4.6 and later.\n' + \
7401888SN/A        termcap.Normal + \
7411869SN/A        'Use SWIG 2.x to avoid assumptions on implicit includes\n' + \
7421869SN/A        'and use of namespaces\n'
7431858SN/A
7445341Sstever@gmail.com# Set up SWIG flags & scanner
7452598SN/Aswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7462598SN/Amain.Append(SWIGFLAGS=swig_flags)
7472598SN/A
7482598SN/A# filter out all existing swig scanners, they mess up the dependency
7491858SN/A# stuff for some reason
7501858SN/Ascanners = []
7511858SN/Afor scanner in main['SCANNERS']:
7521858SN/A    skeys = scanner.skeys
7531858SN/A    if skeys == '.i':
7541858SN/A        continue
7551858SN/A
7561858SN/A    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
7571858SN/A        continue
7581871SN/A
7591858SN/A    scanners.append(scanner)
7601858SN/A
7611858SN/A# add the new swig scanner that we like better
7621858SN/Afrom SCons.Scanner import ClassicCPP as CPPScanner
7631858SN/Aswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
7641858SN/Ascanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
7651858SN/A
7661858SN/A# replace the scanners list that has what we want
7671858SN/Amain['SCANNERS'] = scanners
7681858SN/A
7691858SN/A# Add a custom Check function to the Configure context so that we can
7701859SN/A# figure out if the compiler adds leading underscores to global
7711859SN/A# variables.  This is needed for the autogenerated asm files that we
7721869SN/A# use for embedding the python code.
7731888SN/Adef CheckLeading(context):
7742632Sstever@eecs.umich.edu    context.Message("Checking for leading underscore in global variables...")
7751869SN/A    # 1) Define a global variable called x from asm so the C compiler
7761884SN/A    #    won't change the symbol at all.
7771884SN/A    # 2) Declare that variable.
7781884SN/A    # 3) Use the variable
7791884SN/A    #
7801884SN/A    # If the compiler prepends an underscore, this will successfully
7811884SN/A    # link because the external symbol 'x' will be called '_x' which
7821965SN/A    # was defined by the asm statement.  If the compiler does not
7831965SN/A    # prepend an underscore, this will not successfully link because
7841965SN/A    # '_x' will have been defined by assembly, while the C portion of
7852761Sstever@eecs.umich.edu    # the code will be trying to use 'x'
7861869SN/A    ret = context.TryLink('''
7871869SN/A        asm(".globl _x; _x: .byte 0");
7882632Sstever@eecs.umich.edu        extern int x;
7892667Sstever@eecs.umich.edu        int main() { return x; }
7901869SN/A        ''', extension=".c")
7911869SN/A    context.env.Append(LEADING_UNDERSCORE=ret)
7922929Sktlim@umich.edu    context.Result(ret)
7932929Sktlim@umich.edu    return ret
7943716Sstever@eecs.umich.edu
7952929Sktlim@umich.edu# Platform-specific configuration.  Note again that we assume that all
796955SN/A# builds under a given build root run on the same host platform.
7972598SN/Aconf = Configure(main,
7982598SN/A                 conf_dir = joinpath(build_root, '.scons_config'),
7993546Sgblack@eecs.umich.edu                 log_file = joinpath(build_root, 'scons_config.log'),
800955SN/A                 custom_tests = { 'CheckLeading' : CheckLeading })
801955SN/A
802955SN/A# Check for leading underscores.  Don't really need to worry either
8031530SN/A# way so don't need to check the return code.
804955SN/Aconf.CheckLeading()
805955SN/A
806955SN/A# Check if we should compile a 64 bit binary on Mac OS X/Darwin
807try:
808    import platform
809    uname = platform.uname()
810    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
811        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
812            main.Append(CCFLAGS=['-arch', 'x86_64'])
813            main.Append(CFLAGS=['-arch', 'x86_64'])
814            main.Append(LINKFLAGS=['-arch', 'x86_64'])
815            main.Append(ASFLAGS=['-arch', 'x86_64'])
816except:
817    pass
818
819# Recent versions of scons substitute a "Null" object for Configure()
820# when configuration isn't necessary, e.g., if the "--help" option is
821# present.  Unfortuantely this Null object always returns false,
822# breaking all our configuration checks.  We replace it with our own
823# more optimistic null object that returns True instead.
824if not conf:
825    def NullCheck(*args, **kwargs):
826        return True
827
828    class NullConf:
829        def __init__(self, env):
830            self.env = env
831        def Finish(self):
832            return self.env
833        def __getattr__(self, mname):
834            return NullCheck
835
836    conf = NullConf(main)
837
838# Cache build files in the supplied directory.
839if main['M5_BUILD_CACHE']:
840    print 'Using build cache located at', main['M5_BUILD_CACHE']
841    CacheDir(main['M5_BUILD_CACHE'])
842
843# Find Python include and library directories for embedding the
844# interpreter. We rely on python-config to resolve the appropriate
845# includes and linker flags. ParseConfig does not seem to understand
846# the more exotic linker flags such as -Xlinker and -export-dynamic so
847# we add them explicitly below. If you want to link in an alternate
848# version of python, see above for instructions on how to invoke
849# scons with the appropriate PATH set.
850py_includes = readCommand(['python-config', '--includes'],
851                          exception='').split()
852# Strip the -I from the include folders before adding them to the
853# CPPPATH
854main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
855
856# Read the linker flags and split them into libraries and other link
857# flags. The libraries are added later through the call the CheckLib.
858py_ld_flags = readCommand(['python-config', '--ldflags'], exception='').split()
859py_libs = []
860for lib in py_ld_flags:
861     if not lib.startswith('-l'):
862         main.Append(LINKFLAGS=[lib])
863     else:
864         lib = lib[2:]
865         if lib not in py_libs:
866             py_libs.append(lib)
867
868# verify that this stuff works
869if not conf.CheckHeader('Python.h', '<>'):
870    print "Error: can't find Python.h header in", py_includes
871    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
872    Exit(1)
873
874for lib in py_libs:
875    if not conf.CheckLib(lib):
876        print "Error: can't find library %s required by python" % lib
877        Exit(1)
878
879# On Solaris you need to use libsocket for socket ops
880if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
881   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
882       print "Can't find library with socket calls (e.g. accept())"
883       Exit(1)
884
885# Check for zlib.  If the check passes, libz will be automatically
886# added to the LIBS environment variable.
887if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
888    print 'Error: did not find needed zlib compression library '\
889          'and/or zlib.h header file.'
890    print '       Please install zlib and try again.'
891    Exit(1)
892
893# If we have the protobuf compiler, also make sure we have the
894# development libraries. If the check passes, libprotobuf will be
895# automatically added to the LIBS environment variable. After
896# this, we can use the HAVE_PROTOBUF flag to determine if we have
897# got both protoc and libprotobuf available.
898main['HAVE_PROTOBUF'] = main['PROTOC'] and \
899    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
900                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
901
902# If we have the compiler but not the library, print another warning.
903if main['PROTOC'] and not main['HAVE_PROTOBUF']:
904    print termcap.Yellow + termcap.Bold + \
905        'Warning: did not find protocol buffer library and/or headers.\n' + \
906    '       Please install libprotobuf-dev for tracing support.' + \
907    termcap.Normal
908
909# Check for librt.
910have_posix_clock = \
911    conf.CheckLibWithHeader(None, 'time.h', 'C',
912                            'clock_nanosleep(0,0,NULL,NULL);') or \
913    conf.CheckLibWithHeader('rt', 'time.h', 'C',
914                            'clock_nanosleep(0,0,NULL,NULL);')
915
916have_posix_timers = \
917    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
918                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
919
920if conf.CheckLib('tcmalloc'):
921    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
922elif conf.CheckLib('tcmalloc_minimal'):
923    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
924else:
925    print termcap.Yellow + termcap.Bold + \
926          "You can get a 12% performance improvement by installing tcmalloc "\
927          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
928          termcap.Normal
929
930if not have_posix_clock:
931    print "Can't find library for POSIX clocks."
932
933# Check for <fenv.h> (C99 FP environment control)
934have_fenv = conf.CheckHeader('fenv.h', '<>')
935if not have_fenv:
936    print "Warning: Header file <fenv.h> not found."
937    print "         This host has no IEEE FP rounding mode control."
938
939# Check if we should enable KVM-based hardware virtualization. The API
940# we rely on exists since version 2.6.36 of the kernel, but somehow
941# the KVM_API_VERSION does not reflect the change. We test for one of
942# the types as a fall back.
943have_kvm = conf.CheckHeader('linux/kvm.h', '<>') and \
944    conf.CheckTypeSize('struct kvm_xsave', '#include <linux/kvm.h>') != 0
945if not have_kvm:
946    print "Info: Compatible header file <linux/kvm.h> not found, " \
947        "disabling KVM support."
948
949# Check if the requested target ISA is compatible with the host
950def is_isa_kvm_compatible(isa):
951    isa_comp_table = {
952        "arm" : ( "armv7l" ),
953        "x86" : ( "x86_64" ),
954        }
955    try:
956        import platform
957        host_isa = platform.machine()
958    except:
959        print "Warning: Failed to determine host ISA."
960        return False
961
962    return host_isa in isa_comp_table.get(isa, [])
963
964
965######################################################################
966#
967# Finish the configuration
968#
969main = conf.Finish()
970
971######################################################################
972#
973# Collect all non-global variables
974#
975
976# Define the universe of supported ISAs
977all_isa_list = [ ]
978Export('all_isa_list')
979
980class CpuModel(object):
981    '''The CpuModel class encapsulates everything the ISA parser needs to
982    know about a particular CPU model.'''
983
984    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
985    dict = {}
986    list = []
987    defaults = []
988
989    # Constructor.  Automatically adds models to CpuModel.dict.
990    def __init__(self, name, filename, includes, strings, default=False):
991        self.name = name           # name of model
992        self.filename = filename   # filename for output exec code
993        self.includes = includes   # include files needed in exec file
994        # The 'strings' dict holds all the per-CPU symbols we can
995        # substitute into templates etc.
996        self.strings = strings
997
998        # This cpu is enabled by default
999        self.default = default
1000
1001        # Add self to dict
1002        if name in CpuModel.dict:
1003            raise AttributeError, "CpuModel '%s' already registered" % name
1004        CpuModel.dict[name] = self
1005        CpuModel.list.append(name)
1006
1007Export('CpuModel')
1008
1009# Sticky variables get saved in the variables file so they persist from
1010# one invocation to the next (unless overridden, in which case the new
1011# value becomes sticky).
1012sticky_vars = Variables(args=ARGUMENTS)
1013Export('sticky_vars')
1014
1015# Sticky variables that should be exported
1016export_vars = []
1017Export('export_vars')
1018
1019# For Ruby
1020all_protocols = []
1021Export('all_protocols')
1022protocol_dirs = []
1023Export('protocol_dirs')
1024slicc_includes = []
1025Export('slicc_includes')
1026
1027# Walk the tree and execute all SConsopts scripts that wil add to the
1028# above variables
1029if not GetOption('verbose'):
1030    print "Reading SConsopts"
1031for bdir in [ base_dir ] + extras_dir_list:
1032    if not isdir(bdir):
1033        print "Error: directory '%s' does not exist" % bdir
1034        Exit(1)
1035    for root, dirs, files in os.walk(bdir):
1036        if 'SConsopts' in files:
1037            if GetOption('verbose'):
1038                print "Reading", joinpath(root, 'SConsopts')
1039            SConscript(joinpath(root, 'SConsopts'))
1040
1041all_isa_list.sort()
1042
1043sticky_vars.AddVariables(
1044    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
1045    ListVariable('CPU_MODELS', 'CPU models',
1046                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
1047                 sorted(CpuModel.list)),
1048    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
1049                 False),
1050    BoolVariable('SS_COMPATIBLE_FP',
1051                 'Make floating-point results compatible with SimpleScalar',
1052                 False),
1053    BoolVariable('USE_SSE2',
1054                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
1055                 False),
1056    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1057    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
1058    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
1059    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
1060    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1061                  all_protocols),
1062    )
1063
1064# These variables get exported to #defines in config/*.hh (see src/SConscript).
1065export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
1066                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF']
1067
1068###################################################
1069#
1070# Define a SCons builder for configuration flag headers.
1071#
1072###################################################
1073
1074# This function generates a config header file that #defines the
1075# variable symbol to the current variable setting (0 or 1).  The source
1076# operands are the name of the variable and a Value node containing the
1077# value of the variable.
1078def build_config_file(target, source, env):
1079    (variable, value) = [s.get_contents() for s in source]
1080    f = file(str(target[0]), 'w')
1081    print >> f, '#define', variable, value
1082    f.close()
1083    return None
1084
1085# Combine the two functions into a scons Action object.
1086config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1087
1088# The emitter munges the source & target node lists to reflect what
1089# we're really doing.
1090def config_emitter(target, source, env):
1091    # extract variable name from Builder arg
1092    variable = str(target[0])
1093    # True target is config header file
1094    target = joinpath('config', variable.lower() + '.hh')
1095    val = env[variable]
1096    if isinstance(val, bool):
1097        # Force value to 0/1
1098        val = int(val)
1099    elif isinstance(val, str):
1100        val = '"' + val + '"'
1101
1102    # Sources are variable name & value (packaged in SCons Value nodes)
1103    return ([target], [Value(variable), Value(val)])
1104
1105config_builder = Builder(emitter = config_emitter, action = config_action)
1106
1107main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1108
1109# libelf build is shared across all configs in the build root.
1110main.SConscript('ext/libelf/SConscript',
1111                variant_dir = joinpath(build_root, 'libelf'))
1112
1113# gzstream build is shared across all configs in the build root.
1114main.SConscript('ext/gzstream/SConscript',
1115                variant_dir = joinpath(build_root, 'gzstream'))
1116
1117# libfdt build is shared across all configs in the build root.
1118main.SConscript('ext/libfdt/SConscript',
1119                variant_dir = joinpath(build_root, 'libfdt'))
1120
1121# fputils build is shared across all configs in the build root.
1122main.SConscript('ext/fputils/SConscript',
1123                variant_dir = joinpath(build_root, 'fputils'))
1124
1125###################################################
1126#
1127# This function is used to set up a directory with switching headers
1128#
1129###################################################
1130
1131main['ALL_ISA_LIST'] = all_isa_list
1132def make_switching_dir(dname, switch_headers, env):
1133    # Generate the header.  target[0] is the full path of the output
1134    # header to generate.  'source' is a dummy variable, since we get the
1135    # list of ISAs from env['ALL_ISA_LIST'].
1136    def gen_switch_hdr(target, source, env):
1137        fname = str(target[0])
1138        f = open(fname, 'w')
1139        isa = env['TARGET_ISA'].lower()
1140        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1141        f.close()
1142
1143    # Build SCons Action object. 'varlist' specifies env vars that this
1144    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1145    # should get re-executed.
1146    switch_hdr_action = MakeAction(gen_switch_hdr,
1147                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1148
1149    # Instantiate actions for each header
1150    for hdr in switch_headers:
1151        env.Command(hdr, [], switch_hdr_action)
1152Export('make_switching_dir')
1153
1154###################################################
1155#
1156# Define build environments for selected configurations.
1157#
1158###################################################
1159
1160for variant_path in variant_paths:
1161    print "Building in", variant_path
1162
1163    # Make a copy of the build-root environment to use for this config.
1164    env = main.Clone()
1165    env['BUILDDIR'] = variant_path
1166
1167    # variant_dir is the tail component of build path, and is used to
1168    # determine the build parameters (e.g., 'ALPHA_SE')
1169    (build_root, variant_dir) = splitpath(variant_path)
1170
1171    # Set env variables according to the build directory config.
1172    sticky_vars.files = []
1173    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1174    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1175    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1176    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1177    if isfile(current_vars_file):
1178        sticky_vars.files.append(current_vars_file)
1179        print "Using saved variables file %s" % current_vars_file
1180    else:
1181        # Build dir-specific variables file doesn't exist.
1182
1183        # Make sure the directory is there so we can create it later
1184        opt_dir = dirname(current_vars_file)
1185        if not isdir(opt_dir):
1186            mkdir(opt_dir)
1187
1188        # Get default build variables from source tree.  Variables are
1189        # normally determined by name of $VARIANT_DIR, but can be
1190        # overridden by '--default=' arg on command line.
1191        default = GetOption('default')
1192        opts_dir = joinpath(main.root.abspath, 'build_opts')
1193        if default:
1194            default_vars_files = [joinpath(build_root, 'variables', default),
1195                                  joinpath(opts_dir, default)]
1196        else:
1197            default_vars_files = [joinpath(opts_dir, variant_dir)]
1198        existing_files = filter(isfile, default_vars_files)
1199        if existing_files:
1200            default_vars_file = existing_files[0]
1201            sticky_vars.files.append(default_vars_file)
1202            print "Variables file %s not found,\n  using defaults in %s" \
1203                  % (current_vars_file, default_vars_file)
1204        else:
1205            print "Error: cannot find variables file %s or " \
1206                  "default file(s) %s" \
1207                  % (current_vars_file, ' or '.join(default_vars_files))
1208            Exit(1)
1209
1210    # Apply current variable settings to env
1211    sticky_vars.Update(env)
1212
1213    help_texts["local_vars"] += \
1214        "Build variables for %s:\n" % variant_dir \
1215                 + sticky_vars.GenerateHelpText(env)
1216
1217    # Process variable settings.
1218
1219    if not have_fenv and env['USE_FENV']:
1220        print "Warning: <fenv.h> not available; " \
1221              "forcing USE_FENV to False in", variant_dir + "."
1222        env['USE_FENV'] = False
1223
1224    if not env['USE_FENV']:
1225        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1226        print "         FP results may deviate slightly from other platforms."
1227
1228    if env['EFENCE']:
1229        env.Append(LIBS=['efence'])
1230
1231    if env['USE_KVM']:
1232        if not have_kvm:
1233            print "Warning: Can not enable KVM, host seems to lack KVM support"
1234            env['USE_KVM'] = False
1235        elif not have_posix_timers:
1236            print "Warning: Can not enable KVM, host seems to lack support " \
1237                "for POSIX timers"
1238            env['USE_KVM'] = False
1239        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1240            print "Info: KVM support disabled due to unsupported host and " \
1241                "target ISA combination"
1242            env['USE_KVM'] = False
1243
1244    # Save sticky variable settings back to current variables file
1245    sticky_vars.Save(current_vars_file, env)
1246
1247    if env['USE_SSE2']:
1248        env.Append(CCFLAGS=['-msse2'])
1249
1250    # The src/SConscript file sets up the build rules in 'env' according
1251    # to the configured variables.  It returns a list of environments,
1252    # one for each variant build (debug, opt, etc.)
1253    envList = SConscript('src/SConscript', variant_dir = variant_path,
1254                         exports = 'env')
1255
1256    # Set up the regression tests for each build.
1257    for e in envList:
1258        SConscript('tests/SConscript',
1259                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1260                   exports = { 'env' : e }, duplicate = False)
1261
1262# base help text
1263Help('''
1264Usage: scons [scons options] [build variables] [target(s)]
1265
1266Extra scons options:
1267%(options)s
1268
1269Global build variables:
1270%(global_vars)s
1271
1272%(local_vars)s
1273''' % help_texts)
1274