SConstruct revision 12061
1955SN/A# -*- mode:python -*-
2955SN/A
39812Sandreas.hansson@arm.com# Copyright (c) 2013, 2015, 2016 ARM Limited
49812Sandreas.hansson@arm.com# All rights reserved.
59812Sandreas.hansson@arm.com#
69812Sandreas.hansson@arm.com# The license below extends only to copyright in the software and shall
79812Sandreas.hansson@arm.com# not be construed as granting a license to any other intellectual
89812Sandreas.hansson@arm.com# property including but not limited to intellectual property relating
99812Sandreas.hansson@arm.com# to a hardware implementation of the functionality of the software
109812Sandreas.hansson@arm.com# licensed hereunder.  You may use the software subject to the license
119812Sandreas.hansson@arm.com# terms below provided that you ensure that this notice is replicated
129812Sandreas.hansson@arm.com# unmodified and in its entirety in all distributions of the software,
139812Sandreas.hansson@arm.com# modified or unmodified, in source code or in binary form.
149812Sandreas.hansson@arm.com#
157816Ssteve.reinhardt@amd.com# Copyright (c) 2011 Advanced Micro Devices, Inc.
165871Snate@binkert.org# Copyright (c) 2009 The Hewlett-Packard Development Company
171762SN/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
28955SN/A# contributors may be used to endorse or promote products derived from
29955SN/A# 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
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422665Ssaidi@eecs.umich.edu#
432665Ssaidi@eecs.umich.edu# Authors: Steve Reinhardt
445863Snate@binkert.org#          Nathan Binkert
45955SN/A
46955SN/A###################################################
47955SN/A#
48955SN/A# SCons top-level build description (SConstruct) file.
49955SN/A#
508878Ssteve.reinhardt@amd.com# While in this directory ('gem5'), just type 'scons' to build the default
512632Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
528878Ssteve.reinhardt@amd.com# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532632Sstever@eecs.umich.edu# the optimized full-system version).
54955SN/A#
558878Ssteve.reinhardt@amd.com# 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
572761Sstever@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:
612761Sstever@eecs.umich.edu#
622761Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
632761Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
648878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
658878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
662761Sstever@eecs.umich.edu#
672761Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
682761Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
692761Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
702761Sstever@eecs.umich.edu#   file.
718878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
728878Ssteve.reinhardt@amd.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732632Sstever@eecs.umich.edu#
742632Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
758878Ssteve.reinhardt@amd.com# 'gem5' directory (or use -u or -C to tell scons where to find this
768878Ssteve.reinhardt@amd.com# file), you can use 'scons -h' to print all the gem5-specific build
772632Sstever@eecs.umich.edu# options as well.
78955SN/A#
79955SN/A###################################################
80955SN/A
815863Snate@binkert.org# Check for recent-enough Python and SCons versions.
825863Snate@binkert.orgtry:
835863Snate@binkert.org    # Really old versions of scons only take two options for the
845863Snate@binkert.org    # function, so check once without the revision and once with the
855863Snate@binkert.org    # revision, the first instance will fail for stuff other than
865863Snate@binkert.org    # 0.98, and the second will fail for 0.98.0
875863Snate@binkert.org    EnsureSConsVersion(0, 98)
885863Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
895863Snate@binkert.orgexcept SystemExit, e:
905863Snate@binkert.org    print """
915863Snate@binkert.orgFor more details, see:
928878Ssteve.reinhardt@amd.com    http://gem5.org/Dependencies
935863Snate@binkert.org"""
945863Snate@binkert.org    raise
955863Snate@binkert.org
969812Sandreas.hansson@arm.com# We ensure the python version early because because python-config
979812Sandreas.hansson@arm.com# requires python 2.5
985863Snate@binkert.orgtry:
999812Sandreas.hansson@arm.com    EnsurePythonVersion(2, 5)
1005863Snate@binkert.orgexcept SystemExit, e:
1015863Snate@binkert.org    print """
1025863Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
1039812Sandreas.hansson@arm.comrearranging your PATH so that scons finds the non-default 'python' and
1049812Sandreas.hansson@arm.com'python-config' first.
1055863Snate@binkert.org
1065863Snate@binkert.orgFor more details, see:
1078878Ssteve.reinhardt@amd.com    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1085863Snate@binkert.org"""
1095863Snate@binkert.org    raise
1105863Snate@binkert.org
1116654Snate@binkert.org# Global Python includes
112955SN/Aimport itertools
1135396Ssaidi@eecs.umich.eduimport os
1145863Snate@binkert.orgimport re
1155863Snate@binkert.orgimport shutil
1164202Sbinkertn@umich.eduimport subprocess
1175863Snate@binkert.orgimport sys
1185863Snate@binkert.org
1195863Snate@binkert.orgfrom os import mkdir, environ
1205863Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
121955SN/Afrom os.path import exists,  isdir, isfile
1226654Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1235273Sstever@gmail.com
1245871Snate@binkert.org# SCons includes
1255273Sstever@gmail.comimport SCons
1266655Snate@binkert.orgimport SCons.Node
1278878Ssteve.reinhardt@amd.com
1286655Snate@binkert.orgextra_python_paths = [
1296655Snate@binkert.org    Dir('src/python').srcnode().abspath, # gem5 includes
1309219Spower.jg@gmail.com    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1316655Snate@binkert.org    ]
1325871Snate@binkert.org
1336654Snate@binkert.orgsys.path[1:1] = extra_python_paths
1348947Sandreas.hansson@arm.com
1355396Ssaidi@eecs.umich.edufrom m5.util import compareVersions, readCommand
1368120Sgblack@eecs.umich.edufrom m5.util.terminal import get_termcap
1378120Sgblack@eecs.umich.edu
1388120Sgblack@eecs.umich.eduhelp_texts = {
1398120Sgblack@eecs.umich.edu    "options" : "",
1408120Sgblack@eecs.umich.edu    "global_vars" : "",
1418120Sgblack@eecs.umich.edu    "local_vars" : ""
1428120Sgblack@eecs.umich.edu}
1438120Sgblack@eecs.umich.edu
1448879Ssteve.reinhardt@amd.comExport("help_texts")
1458879Ssteve.reinhardt@amd.com
1468879Ssteve.reinhardt@amd.com
1478879Ssteve.reinhardt@amd.com# There's a bug in scons in that (1) by default, the help texts from
1488879Ssteve.reinhardt@amd.com# AddOption() are supposed to be displayed when you type 'scons -h'
1498879Ssteve.reinhardt@amd.com# and (2) you can override the help displayed by 'scons -h' using the
1508879Ssteve.reinhardt@amd.com# Help() function, but these two features are incompatible: once
1518879Ssteve.reinhardt@amd.com# you've overridden the help text using Help(), there's no way to get
1528879Ssteve.reinhardt@amd.com# at the help texts from AddOptions.  See:
1538879Ssteve.reinhardt@amd.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1548879Ssteve.reinhardt@amd.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1558879Ssteve.reinhardt@amd.com# This hack lets us extract the help text from AddOptions and
1568879Ssteve.reinhardt@amd.com# re-inject it via Help().  Ideally someday this bug will be fixed and
1578120Sgblack@eecs.umich.edu# we can just use AddOption directly.
1588120Sgblack@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1598120Sgblack@eecs.umich.edu    col_width = 30
1608120Sgblack@eecs.umich.edu
1618120Sgblack@eecs.umich.edu    help = "  " + ", ".join(args)
1628120Sgblack@eecs.umich.edu    if "help" in kwargs:
1638120Sgblack@eecs.umich.edu        length = len(help)
1648120Sgblack@eecs.umich.edu        if length >= col_width:
1658120Sgblack@eecs.umich.edu            help += "\n" + " " * col_width
1668120Sgblack@eecs.umich.edu        else:
1678120Sgblack@eecs.umich.edu            help += " " * (col_width - length)
1688120Sgblack@eecs.umich.edu        help += kwargs["help"]
1698120Sgblack@eecs.umich.edu    help_texts["options"] += help + "\n"
1708120Sgblack@eecs.umich.edu
1718879Ssteve.reinhardt@amd.com    AddOption(*args, **kwargs)
1728879Ssteve.reinhardt@amd.com
1738879Ssteve.reinhardt@amd.comAddLocalOption('--colors', dest='use_colors', action='store_true',
1748879Ssteve.reinhardt@amd.com               help="Add color to abbreviated scons output")
1758879Ssteve.reinhardt@amd.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1768879Ssteve.reinhardt@amd.com               help="Don't add color to abbreviated scons output")
1778879Ssteve.reinhardt@amd.comAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1788879Ssteve.reinhardt@amd.com               action='store_true',
1799227Sandreas.hansson@arm.com               help="Build with support for C++-based configuration")
1809227Sandreas.hansson@arm.comAddLocalOption('--default', dest='default', type='string', action='store',
1818879Ssteve.reinhardt@amd.com               help='Override which build_opts file to use for defaults')
1828879Ssteve.reinhardt@amd.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1838879Ssteve.reinhardt@amd.com               help='Disable style checking hooks')
1848879Ssteve.reinhardt@amd.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1858120Sgblack@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1868947Sandreas.hansson@arm.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1877816Ssteve.reinhardt@amd.com               help='Update test reference outputs')
1885871Snate@binkert.orgAddLocalOption('--verbose', dest='verbose', action='store_true',
1895871Snate@binkert.org               help='Print full tool command lines')
1906121Snate@binkert.orgAddLocalOption('--without-python', dest='without_python',
1915871Snate@binkert.org               action='store_true',
1925871Snate@binkert.org               help='Build without Python configuration support')
1939119Sandreas.hansson@arm.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1949396Sandreas.hansson@arm.com               action='store_true',
1959396Sandreas.hansson@arm.com               help='Disable linking against tcmalloc')
196955SN/AAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1979416SAndreas.Sandberg@ARM.com               help='Build with Undefined Behavior Sanitizer if available')
1989416SAndreas.Sandberg@ARM.comAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1999416SAndreas.Sandberg@ARM.com               help='Build with Address Sanitizer if available')
2009416SAndreas.Sandberg@ARM.com
2019416SAndreas.Sandberg@ARM.comtermcap = get_termcap(GetOption('use_colors'))
2029416SAndreas.Sandberg@ARM.com
2039416SAndreas.Sandberg@ARM.com########################################################################
2045871Snate@binkert.org#
2055871Snate@binkert.org# Set up the main build environment.
2069416SAndreas.Sandberg@ARM.com#
2079416SAndreas.Sandberg@ARM.com########################################################################
2085871Snate@binkert.org
209955SN/A# export TERM so that clang reports errors in color
2106121Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2118881Smarc.orr@gmail.com                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2126121Snate@binkert.org                 'PYTHONPATH', 'RANLIB', 'TERM' ])
2136121Snate@binkert.org
2141533SN/Ause_prefixes = [
2159239Sandreas.hansson@arm.com    "ASAN_",           # address sanitizer symbolizer path and settings
2169239Sandreas.hansson@arm.com    "CCACHE_",         # ccache (caching compiler wrapper) configuration
2179239Sandreas.hansson@arm.com    "CCC_",            # clang static analyzer configuration
2189239Sandreas.hansson@arm.com    "DISTCC_",         # distcc (distributed compiler wrapper) configuration
2199239Sandreas.hansson@arm.com    "INCLUDE_SERVER_", # distcc pump server settings
2209239Sandreas.hansson@arm.com    "M5",              # M5 configuration (e.g., path to kernels)
2219239Sandreas.hansson@arm.com    ]
2229239Sandreas.hansson@arm.com
2239239Sandreas.hansson@arm.comuse_env = {}
2249239Sandreas.hansson@arm.comfor key,val in sorted(os.environ.iteritems()):
2259239Sandreas.hansson@arm.com    if key in use_vars or \
2269239Sandreas.hansson@arm.com            any([key.startswith(prefix) for prefix in use_prefixes]):
2276655Snate@binkert.org        use_env[key] = val
2286655Snate@binkert.org
2296655Snate@binkert.org# Tell scons to avoid implicit command dependencies to avoid issues
2306655Snate@binkert.org# with the param wrappes being compiled twice (see
2315871Snate@binkert.org# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2325871Snate@binkert.orgmain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2335863Snate@binkert.orgmain.Decider('MD5-timestamp')
2345871Snate@binkert.orgmain.root = Dir(".")         # The current directory (where this file lives).
2358878Ssteve.reinhardt@amd.commain.srcdir = Dir("src")     # The source directory
2365871Snate@binkert.org
2375871Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
2385871Snate@binkert.org
2395863Snate@binkert.org# Check that we have a C/C++ compiler
2406121Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2415863Snate@binkert.org    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2425871Snate@binkert.org    Exit(1)
2438336Ssteve.reinhardt@amd.com
2448336Ssteve.reinhardt@amd.com# add useful python code PYTHONPATH so it can be used by subprocesses
2458336Ssteve.reinhardt@amd.com# as well
2468336Ssteve.reinhardt@amd.commain.AppendENVPath('PYTHONPATH', extra_python_paths)
2474678Snate@binkert.org
2488336Ssteve.reinhardt@amd.com########################################################################
2498336Ssteve.reinhardt@amd.com#
2508336Ssteve.reinhardt@amd.com# Mercurial Stuff.
2514678Snate@binkert.org#
2524678Snate@binkert.org# If the gem5 directory is a mercurial repository, we should do some
2534678Snate@binkert.org# extra things.
2544678Snate@binkert.org#
2557827Snate@binkert.org########################################################################
2567827Snate@binkert.org
2578336Ssteve.reinhardt@amd.comhgdir = main.root.Dir(".hg")
2584678Snate@binkert.org
2598336Ssteve.reinhardt@amd.com
2608336Ssteve.reinhardt@amd.comstyle_message = """
2618336Ssteve.reinhardt@amd.comYou're missing the gem5 style hook, which automatically checks your code
2628336Ssteve.reinhardt@amd.comagainst the gem5 style rules on %s.
2638336Ssteve.reinhardt@amd.comThis script will now install the hook in your %s.
2648336Ssteve.reinhardt@amd.comPress enter to continue, or ctrl-c to abort: """
2655871Snate@binkert.org
2665871Snate@binkert.orgmercurial_style_message = """
2678336Ssteve.reinhardt@amd.comYou're missing the gem5 style hook, which automatically checks your code
2688336Ssteve.reinhardt@amd.comagainst the gem5 style rules on hg commit and qrefresh commands.
2698336Ssteve.reinhardt@amd.comThis script will now install the hook in your .hg/hgrc file.
2708336Ssteve.reinhardt@amd.comPress enter to continue, or ctrl-c to abort: """
2718336Ssteve.reinhardt@amd.com
2725871Snate@binkert.orggit_style_message = """
2738336Ssteve.reinhardt@amd.comYou're missing the gem5 style or commit message hook. These hooks help
2748336Ssteve.reinhardt@amd.comto ensure that your code follows gem5's style rules on git commit.
2758336Ssteve.reinhardt@amd.comThis script will now install the hook in your .git/hooks/ directory.
2768336Ssteve.reinhardt@amd.comPress enter to continue, or ctrl-c to abort: """
2778336Ssteve.reinhardt@amd.com
2784678Snate@binkert.orgmercurial_style_upgrade_message = """
2795871Snate@binkert.orgYour Mercurial style hooks are not up-to-date. This script will now
2804678Snate@binkert.orgtry to automatically update them. A backup of your hgrc will be saved
2818336Ssteve.reinhardt@amd.comin .hg/hgrc.old.
2828336Ssteve.reinhardt@amd.comPress enter to continue, or ctrl-c to abort: """
2838336Ssteve.reinhardt@amd.com
2848336Ssteve.reinhardt@amd.commercurial_style_hook = """
2858336Ssteve.reinhardt@amd.com# The following lines were automatically added by gem5/SConstruct
2868336Ssteve.reinhardt@amd.com# to provide the gem5 style-checking hooks
2878336Ssteve.reinhardt@amd.com[extensions]
2888336Ssteve.reinhardt@amd.comhgstyle = %s/util/hgstyle.py
2898336Ssteve.reinhardt@amd.com
2908336Ssteve.reinhardt@amd.com[hooks]
2918336Ssteve.reinhardt@amd.compretxncommit.style = python:hgstyle.check_style
2928336Ssteve.reinhardt@amd.compre-qrefresh.style = python:hgstyle.check_style
2938336Ssteve.reinhardt@amd.com# End of SConstruct additions
2948336Ssteve.reinhardt@amd.com
2958336Ssteve.reinhardt@amd.com""" % (main.root.abspath)
2968336Ssteve.reinhardt@amd.com
2978336Ssteve.reinhardt@amd.commercurial_lib_not_found = """
2985871Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2996121Snate@binkert.orgyou are a gem5 developer, please fix this and run the style
300955SN/Ahook. It is important.
301955SN/A"""
3022632Sstever@eecs.umich.edu
3032632Sstever@eecs.umich.edu# Check for style hook and prompt for installation if it's not there.
304955SN/A# Skip this if --ignore-style was specified, there's no interactive
305955SN/A# terminal to prompt, or no recognized revision control system can be
306955SN/A# found.
307955SN/Aignore_style = GetOption('ignore_style') or not sys.stdin.isatty()
3088878Ssteve.reinhardt@amd.com
309955SN/A# Try wire up Mercurial to the style hooks
3102632Sstever@eecs.umich.eduif not ignore_style and hgdir.exists():
3112632Sstever@eecs.umich.edu    style_hook = True
3122632Sstever@eecs.umich.edu    style_hooks = tuple()
3132632Sstever@eecs.umich.edu    hgrc = hgdir.File('hgrc')
3142632Sstever@eecs.umich.edu    hgrc_old = hgdir.File('hgrc.old')
3152632Sstever@eecs.umich.edu    try:
3162632Sstever@eecs.umich.edu        from mercurial import ui
3178268Ssteve.reinhardt@amd.com        ui = ui.ui()
3188268Ssteve.reinhardt@amd.com        ui.readconfig(hgrc.abspath)
3198268Ssteve.reinhardt@amd.com        style_hooks = (ui.config('hooks', 'pretxncommit.style', None),
3208268Ssteve.reinhardt@amd.com                       ui.config('hooks', 'pre-qrefresh.style', None))
3218268Ssteve.reinhardt@amd.com        style_hook = all(style_hooks)
3228268Ssteve.reinhardt@amd.com        style_extension = ui.config('extensions', 'style', None)
3238268Ssteve.reinhardt@amd.com    except ImportError:
3242632Sstever@eecs.umich.edu        print mercurial_lib_not_found
3252632Sstever@eecs.umich.edu
3262632Sstever@eecs.umich.edu    if "python:style.check_style" in style_hooks:
3272632Sstever@eecs.umich.edu        # Try to upgrade the style hooks
3288268Ssteve.reinhardt@amd.com        print mercurial_style_upgrade_message
3292632Sstever@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
3308268Ssteve.reinhardt@amd.com        try:
3318268Ssteve.reinhardt@amd.com            raw_input()
3328268Ssteve.reinhardt@amd.com        except:
3338268Ssteve.reinhardt@amd.com            print "Input exception, exiting scons.\n"
3343718Sstever@eecs.umich.edu            sys.exit(1)
3352634Sstever@eecs.umich.edu        shutil.copyfile(hgrc.abspath, hgrc_old.abspath)
3362634Sstever@eecs.umich.edu        re_style_hook = re.compile(r"^([^=#]+)\.style\s*=\s*([^#\s]+).*")
3375863Snate@binkert.org        re_style_extension = re.compile("style\s*=\s*([^#\s]+).*")
3382638Sstever@eecs.umich.edu        old, new = open(hgrc_old.abspath, 'r'), open(hgrc.abspath, 'w')
3398268Ssteve.reinhardt@amd.com        for l in old:
3402632Sstever@eecs.umich.edu            m_hook = re_style_hook.match(l)
3412632Sstever@eecs.umich.edu            m_ext = re_style_extension.match(l)
3422632Sstever@eecs.umich.edu            if m_hook:
3432632Sstever@eecs.umich.edu                hook, check = m_hook.groups()
3442632Sstever@eecs.umich.edu                if check != "python:style.check_style":
3451858SN/A                    print "Warning: %s.style is using a non-default " \
3463716Sstever@eecs.umich.edu                        "checker: %s" % (hook, check)
3472638Sstever@eecs.umich.edu                if hook not in ("pretxncommit", "pre-qrefresh"):
3482638Sstever@eecs.umich.edu                    print "Warning: Updating unknown style hook: %s" % hook
3492638Sstever@eecs.umich.edu
3502638Sstever@eecs.umich.edu                l = "%s.style = python:hgstyle.check_style\n" % hook
3512638Sstever@eecs.umich.edu            elif m_ext and m_ext.group(1) == style_extension:
3522638Sstever@eecs.umich.edu                l = "hgstyle = %s/util/hgstyle.py\n" % main.root.abspath
3532638Sstever@eecs.umich.edu
3545863Snate@binkert.org            new.write(l)
3555863Snate@binkert.org    elif not style_hook:
3565863Snate@binkert.org        print mercurial_style_message,
357955SN/A        # continue unless user does ctrl-c/ctrl-d etc.
3585341Sstever@gmail.com        try:
3595341Sstever@gmail.com            raw_input()
3605863Snate@binkert.org        except:
3617756SAli.Saidi@ARM.com            print "Input exception, exiting scons.\n"
3625341Sstever@gmail.com            sys.exit(1)
3636121Snate@binkert.org        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3644494Ssaidi@eecs.umich.edu        print "Adding style hook to", hgrc_path, "\n"
3656121Snate@binkert.org        try:
3661105SN/A            with open(hgrc_path, 'a') as f:
3672667Sstever@eecs.umich.edu                f.write(mercurial_style_hook)
3682667Sstever@eecs.umich.edu        except:
3692667Sstever@eecs.umich.edu            print "Error updating", hgrc_path
3702667Sstever@eecs.umich.edu            sys.exit(1)
3716121Snate@binkert.org
3722667Sstever@eecs.umich.edudef install_git_style_hooks():
3735341Sstever@gmail.com    try:
3745863Snate@binkert.org        gitdir = Dir(readCommand(
3755341Sstever@gmail.com            ["git", "rev-parse", "--git-dir"]).strip("\n"))
3765341Sstever@gmail.com    except Exception, e:
3775341Sstever@gmail.com        print "Warning: Failed to find git repo directory: %s" % e
3788120Sgblack@eecs.umich.edu        return
3795341Sstever@gmail.com
3808120Sgblack@eecs.umich.edu    git_hooks = gitdir.Dir("hooks")
3815341Sstever@gmail.com    def hook_exists(hook_name):
3828120Sgblack@eecs.umich.edu        hook = git_hooks.File(hook_name)
3836121Snate@binkert.org        return hook.exists()
3846121Snate@binkert.org
3858980Ssteve.reinhardt@amd.com    def hook_install(hook_name, script):
3869396Sandreas.hansson@arm.com        hook = git_hooks.File(hook_name)
3875397Ssaidi@eecs.umich.edu        if hook.exists():
3885397Ssaidi@eecs.umich.edu            print "Warning: Can't install %s, hook already exists." % hook_name
3897727SAli.Saidi@ARM.com            return
3908268Ssteve.reinhardt@amd.com
3916168Snate@binkert.org        if hook.islink():
3925341Sstever@gmail.com            print "Warning: Removing broken symlink for hook %s." % hook_name
3938120Sgblack@eecs.umich.edu            os.unlink(hook.get_abspath())
3948120Sgblack@eecs.umich.edu
3958120Sgblack@eecs.umich.edu        if not git_hooks.exists():
3966814Sgblack@eecs.umich.edu            mkdir(git_hooks.get_abspath())
3975863Snate@binkert.org            git_hooks.clear()
3988120Sgblack@eecs.umich.edu
3995341Sstever@gmail.com        abs_symlink_hooks = git_hooks.islink() and \
4005863Snate@binkert.org            os.path.isabs(os.readlink(git_hooks.get_abspath()))
4018268Ssteve.reinhardt@amd.com
4026121Snate@binkert.org        # Use a relative symlink if the hooks live in the source directory,
4036121Snate@binkert.org        # and the hooks directory is not a symlink to an absolute path.
4048268Ssteve.reinhardt@amd.com        if hook.is_under(main.root) and not abs_symlink_hooks:
4055742Snate@binkert.org            script_path = os.path.relpath(
4065742Snate@binkert.org                os.path.realpath(script.get_abspath()),
4075341Sstever@gmail.com                os.path.realpath(hook.Dir(".").get_abspath()))
4085742Snate@binkert.org        else:
4095742Snate@binkert.org            script_path = script.get_abspath()
4105341Sstever@gmail.com
4116017Snate@binkert.org        try:
4126121Snate@binkert.org            os.symlink(script_path, hook.get_abspath())
4136017Snate@binkert.org        except:
4147816Ssteve.reinhardt@amd.com            print "Error updating git %s hook" % hook_name
4157756SAli.Saidi@ARM.com            raise
4167756SAli.Saidi@ARM.com
4177756SAli.Saidi@ARM.com    if hook_exists("pre-commit") and hook_exists("commit-msg"):
4187756SAli.Saidi@ARM.com        return
4197756SAli.Saidi@ARM.com
4207756SAli.Saidi@ARM.com    print git_style_message,
4217756SAli.Saidi@ARM.com    try:
4227756SAli.Saidi@ARM.com        raw_input()
4237816Ssteve.reinhardt@amd.com    except:
4247816Ssteve.reinhardt@amd.com        print "Input exception, exiting scons.\n"
4257816Ssteve.reinhardt@amd.com        sys.exit(1)
4267816Ssteve.reinhardt@amd.com
4277816Ssteve.reinhardt@amd.com    git_style_script = File("util/git-pre-commit.py")
4287816Ssteve.reinhardt@amd.com    git_msg_script = File("ext/git-commit-msg")
4297816Ssteve.reinhardt@amd.com
4307816Ssteve.reinhardt@amd.com    hook_install("pre-commit", git_style_script)
4317816Ssteve.reinhardt@amd.com    hook_install("commit-msg", git_msg_script)
4327816Ssteve.reinhardt@amd.com
4337756SAli.Saidi@ARM.com# Try to wire up git to the style hooks
4347816Ssteve.reinhardt@amd.comif not ignore_style and main.root.Entry(".git").exists():
4357816Ssteve.reinhardt@amd.com    install_git_style_hooks()
4367816Ssteve.reinhardt@amd.com
4377816Ssteve.reinhardt@amd.com###################################################
4387816Ssteve.reinhardt@amd.com#
4397816Ssteve.reinhardt@amd.com# Figure out which configurations to set up based on the path(s) of
4407816Ssteve.reinhardt@amd.com# the target(s).
4417816Ssteve.reinhardt@amd.com#
4427816Ssteve.reinhardt@amd.com###################################################
4437816Ssteve.reinhardt@amd.com
4447816Ssteve.reinhardt@amd.com# Find default configuration & binary.
4457816Ssteve.reinhardt@amd.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
4467816Ssteve.reinhardt@amd.com
4477816Ssteve.reinhardt@amd.com# helper function: find last occurrence of element in list
4487816Ssteve.reinhardt@amd.comdef rfind(l, elt, offs = -1):
4497816Ssteve.reinhardt@amd.com    for i in range(len(l)+offs, 0, -1):
4507816Ssteve.reinhardt@amd.com        if l[i] == elt:
4517816Ssteve.reinhardt@amd.com            return i
4527816Ssteve.reinhardt@amd.com    raise ValueError, "element not found"
4537816Ssteve.reinhardt@amd.com
4547816Ssteve.reinhardt@amd.com# Take a list of paths (or SCons Nodes) and return a list with all
4557816Ssteve.reinhardt@amd.com# paths made absolute and ~-expanded.  Paths will be interpreted
4567816Ssteve.reinhardt@amd.com# relative to the launch directory unless a different root is provided
4577816Ssteve.reinhardt@amd.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
4587816Ssteve.reinhardt@amd.com    return [abspath(joinpath(root, expanduser(str(p))))
4597816Ssteve.reinhardt@amd.com            for p in path_list]
4607816Ssteve.reinhardt@amd.com
4617816Ssteve.reinhardt@amd.com# Each target must have 'build' in the interior of the path; the
4627816Ssteve.reinhardt@amd.com# directory below this will determine the build parameters.  For
4637816Ssteve.reinhardt@amd.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
4647816Ssteve.reinhardt@amd.com# recognize that ALPHA_SE specifies the configuration because it
4657816Ssteve.reinhardt@amd.com# follow 'build' in the build path.
4667816Ssteve.reinhardt@amd.com
4677816Ssteve.reinhardt@amd.com# The funky assignment to "[:]" is needed to replace the list contents
4687816Ssteve.reinhardt@amd.com# in place rather than reassign the symbol to a new list, which
4697816Ssteve.reinhardt@amd.com# doesn't work (obviously!).
4707816Ssteve.reinhardt@amd.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
4717816Ssteve.reinhardt@amd.com
4727816Ssteve.reinhardt@amd.com# Generate a list of the unique build roots and configs that the
4737816Ssteve.reinhardt@amd.com# collected targets reference.
4747816Ssteve.reinhardt@amd.comvariant_paths = []
4757816Ssteve.reinhardt@amd.combuild_root = None
4767816Ssteve.reinhardt@amd.comfor t in BUILD_TARGETS:
4777816Ssteve.reinhardt@amd.com    path_dirs = t.split('/')
4787816Ssteve.reinhardt@amd.com    try:
4797816Ssteve.reinhardt@amd.com        build_top = rfind(path_dirs, 'build', -2)
4807816Ssteve.reinhardt@amd.com    except:
4817816Ssteve.reinhardt@amd.com        print "Error: no non-leaf 'build' dir found on target path", t
4827816Ssteve.reinhardt@amd.com        Exit(1)
4837816Ssteve.reinhardt@amd.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
4847816Ssteve.reinhardt@amd.com    if not build_root:
4857816Ssteve.reinhardt@amd.com        build_root = this_build_root
4867816Ssteve.reinhardt@amd.com    else:
4877816Ssteve.reinhardt@amd.com        if this_build_root != build_root:
4887816Ssteve.reinhardt@amd.com            print "Error: build targets not under same build root\n"\
4897816Ssteve.reinhardt@amd.com                  "  %s\n  %s" % (build_root, this_build_root)
4907816Ssteve.reinhardt@amd.com            Exit(1)
4917816Ssteve.reinhardt@amd.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
4927816Ssteve.reinhardt@amd.com    if variant_path not in variant_paths:
4937816Ssteve.reinhardt@amd.com        variant_paths.append(variant_path)
4947816Ssteve.reinhardt@amd.com
4958947Sandreas.hansson@arm.com# Make sure build_root exists (might not if this is the first build there)
4968947Sandreas.hansson@arm.comif not isdir(build_root):
4977756SAli.Saidi@ARM.com    mkdir(build_root)
4988120Sgblack@eecs.umich.edumain['BUILDROOT'] = build_root
4997756SAli.Saidi@ARM.com
5007756SAli.Saidi@ARM.comExport('main')
5017756SAli.Saidi@ARM.com
5027756SAli.Saidi@ARM.commain.SConsignFile(joinpath(build_root, "sconsign"))
5037816Ssteve.reinhardt@amd.com
5047816Ssteve.reinhardt@amd.com# Default duplicate option is to use hard links, but this messes up
5057816Ssteve.reinhardt@amd.com# when you use emacs to edit a file in the target dir, as emacs moves
5067816Ssteve.reinhardt@amd.com# file to file~ then copies to file, breaking the link.  Symbolic
5077816Ssteve.reinhardt@amd.com# (soft) links work better.
5087816Ssteve.reinhardt@amd.commain.SetOption('duplicate', 'soft-copy')
5097816Ssteve.reinhardt@amd.com
5107816Ssteve.reinhardt@amd.com#
5117816Ssteve.reinhardt@amd.com# Set up global sticky variables... these are common to an entire build
5127816Ssteve.reinhardt@amd.com# tree (not specific to a particular build like ALPHA_SE)
5137756SAli.Saidi@ARM.com#
5147756SAli.Saidi@ARM.com
5159227Sandreas.hansson@arm.comglobal_vars_file = joinpath(build_root, 'variables.global')
5169227Sandreas.hansson@arm.com
5179227Sandreas.hansson@arm.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
5189227Sandreas.hansson@arm.com
5199590Sandreas@sandberg.pp.seglobal_vars.AddVariables(
5209590Sandreas@sandberg.pp.se    ('CC', 'C compiler', environ.get('CC', main['CC'])),
5219590Sandreas@sandberg.pp.se    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
5229590Sandreas@sandberg.pp.se    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
5239590Sandreas@sandberg.pp.se    ('BATCH', 'Use batch pool for build and tests', False),
5249590Sandreas@sandberg.pp.se    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
5256654Snate@binkert.org    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
5266654Snate@binkert.org    ('EXTRAS', 'Add extra directories to the compilation', '')
5275871Snate@binkert.org    )
5286121Snate@binkert.org
5298946Sandreas.hansson@arm.com# Update main environment with values from ARGUMENTS & global_vars_file
5309419Sandreas.hansson@arm.comglobal_vars.Update(main)
5313940Ssaidi@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
5323918Ssaidi@eecs.umich.edu
5333918Ssaidi@eecs.umich.edu# Save sticky variable settings back to current variables file
5341858SN/Aglobal_vars.Save(global_vars_file, main)
5359556Sandreas.hansson@arm.com
5369556Sandreas.hansson@arm.com# Parse EXTRAS variable to build list of all directories where we're
5379556Sandreas.hansson@arm.com# look for sources etc.  This list is exported as extras_dir_list.
5389556Sandreas.hansson@arm.combase_dir = main.srcdir.abspath
5399556Sandreas.hansson@arm.comif main['EXTRAS']:
5409556Sandreas.hansson@arm.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
5419556Sandreas.hansson@arm.comelse:
5429556Sandreas.hansson@arm.com    extras_dir_list = []
5439556Sandreas.hansson@arm.com
5449556Sandreas.hansson@arm.comExport('base_dir')
5459556Sandreas.hansson@arm.comExport('extras_dir_list')
5469556Sandreas.hansson@arm.com
5479556Sandreas.hansson@arm.com# the ext directory should be on the #includes path
5489556Sandreas.hansson@arm.commain.Append(CPPPATH=[Dir('ext')])
5499556Sandreas.hansson@arm.com
5509556Sandreas.hansson@arm.comdef strip_build_path(path, env):
5519556Sandreas.hansson@arm.com    path = str(path)
5529556Sandreas.hansson@arm.com    variant_base = env['BUILDROOT'] + os.path.sep
5539556Sandreas.hansson@arm.com    if path.startswith(variant_base):
5549556Sandreas.hansson@arm.com        path = path[len(variant_base):]
5559556Sandreas.hansson@arm.com    elif path.startswith('build/'):
5569556Sandreas.hansson@arm.com        path = path[6:]
5579556Sandreas.hansson@arm.com    return path
5589556Sandreas.hansson@arm.com
5599556Sandreas.hansson@arm.com# Generate a string of the form:
5609556Sandreas.hansson@arm.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
5619556Sandreas.hansson@arm.com# to print while building.
5629556Sandreas.hansson@arm.comclass Transform(object):
5639556Sandreas.hansson@arm.com    # all specific color settings should be here and nowhere else
5649556Sandreas.hansson@arm.com    tool_color = termcap.Normal
5659556Sandreas.hansson@arm.com    pfx_color = termcap.Yellow
5669556Sandreas.hansson@arm.com    srcs_color = termcap.Yellow + termcap.Bold
5676121Snate@binkert.org    arrow_color = termcap.Blue + termcap.Bold
5689420Sandreas.hansson@arm.com    tgts_color = termcap.Yellow + termcap.Bold
5699420Sandreas.hansson@arm.com
5709420Sandreas.hansson@arm.com    def __init__(self, tool, max_sources=99):
5719420Sandreas.hansson@arm.com        self.format = self.tool_color + (" [%8s] " % tool) \
5729420Sandreas.hansson@arm.com                      + self.pfx_color + "%s" \
5739420Sandreas.hansson@arm.com                      + self.srcs_color + "%s" \
5749420Sandreas.hansson@arm.com                      + self.arrow_color + " -> " \
5759420Sandreas.hansson@arm.com                      + self.tgts_color + "%s" \
5769420Sandreas.hansson@arm.com                      + termcap.Normal
5779420Sandreas.hansson@arm.com        self.max_sources = max_sources
5789420Sandreas.hansson@arm.com
5797618SAli.Saidi@arm.com    def __call__(self, target, source, env, for_signature=None):
5807618SAli.Saidi@arm.com        # truncate source list according to max_sources param
5817618SAli.Saidi@arm.com        source = source[0:self.max_sources]
5827739Sgblack@eecs.umich.edu        def strip(f):
5839227Sandreas.hansson@arm.com            return strip_build_path(str(f), env)
5849227Sandreas.hansson@arm.com        if len(source) > 0:
5859227Sandreas.hansson@arm.com            srcs = map(strip, source)
5869227Sandreas.hansson@arm.com        else:
5879227Sandreas.hansson@arm.com            srcs = ['']
5889227Sandreas.hansson@arm.com        tgts = map(strip, target)
5899227Sandreas.hansson@arm.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
5909227Sandreas.hansson@arm.com        # operation that has nothing to do with paths.
5919227Sandreas.hansson@arm.com        com_pfx = os.path.commonprefix(srcs + tgts)
5929227Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
5939227Sandreas.hansson@arm.com        if com_pfx:
5949227Sandreas.hansson@arm.com            # do some cleanup and sanity checking on common prefix
5959227Sandreas.hansson@arm.com            if com_pfx[-1] == ".":
5969227Sandreas.hansson@arm.com                # prefix matches all but file extension: ok
5979227Sandreas.hansson@arm.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
5989227Sandreas.hansson@arm.com                com_pfx = com_pfx[0:-1]
5999227Sandreas.hansson@arm.com            elif com_pfx[-1] == "/":
6009227Sandreas.hansson@arm.com                # common prefix is directory path: OK
6019590Sandreas@sandberg.pp.se                pass
6029590Sandreas@sandberg.pp.se            else:
6039590Sandreas@sandberg.pp.se                src0_len = len(srcs[0])
6048737Skoansin.tan@gmail.com                tgt0_len = len(tgts[0])
6059420Sandreas.hansson@arm.com                if src0_len == com_pfx_len:
6069420Sandreas.hansson@arm.com                    # source is a substring of target, OK
6079420Sandreas.hansson@arm.com                    pass
6088737Skoansin.tan@gmail.com                elif tgt0_len == com_pfx_len:
6098737Skoansin.tan@gmail.com                    # target is a substring of source, need to back up to
6108737Skoansin.tan@gmail.com                    # avoid empty string on RHS of arrow
6118737Skoansin.tan@gmail.com                    sep_idx = com_pfx.rfind(".")
6128737Skoansin.tan@gmail.com                    if sep_idx != -1:
6138737Skoansin.tan@gmail.com                        com_pfx = com_pfx[0:sep_idx]
6148737Skoansin.tan@gmail.com                    else:
6158737Skoansin.tan@gmail.com                        com_pfx = ''
6168737Skoansin.tan@gmail.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
6178737Skoansin.tan@gmail.com                    # still splitting at file extension: ok
6188737Skoansin.tan@gmail.com                    pass
6198737Skoansin.tan@gmail.com                else:
6209556Sandreas.hansson@arm.com                    # probably a fluke; ignore it
6219556Sandreas.hansson@arm.com                    com_pfx = ''
6229556Sandreas.hansson@arm.com        # recalculate length in case com_pfx was modified
6239556Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
6249556Sandreas.hansson@arm.com        def fmt(files):
6259556Sandreas.hansson@arm.com            f = map(lambda s: s[com_pfx_len:], files)
6269556Sandreas.hansson@arm.com            return ', '.join(f)
6279556Sandreas.hansson@arm.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
6289556Sandreas.hansson@arm.com
6299556Sandreas.hansson@arm.comExport('Transform')
6309590Sandreas@sandberg.pp.se
6319590Sandreas@sandberg.pp.se# enable the regression script to use the termcap
6329420Sandreas.hansson@arm.commain['TERMCAP'] = termcap
6339420Sandreas.hansson@arm.com
6349420Sandreas.hansson@arm.comif GetOption('verbose'):
6359420Sandreas.hansson@arm.com    def MakeAction(action, string, *args, **kwargs):
6369420Sandreas.hansson@arm.com        return Action(action, *args, **kwargs)
6379420Sandreas.hansson@arm.comelse:
6389420Sandreas.hansson@arm.com    MakeAction = Action
6399420Sandreas.hansson@arm.com    main['CCCOMSTR']        = Transform("CC")
6409420Sandreas.hansson@arm.com    main['CXXCOMSTR']       = Transform("CXX")
6419420Sandreas.hansson@arm.com    main['ASCOMSTR']        = Transform("AS")
6428946Sandreas.hansson@arm.com    main['ARCOMSTR']        = Transform("AR", 0)
6433918Ssaidi@eecs.umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
6449068SAli.Saidi@ARM.com    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
6459068SAli.Saidi@ARM.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
6469068SAli.Saidi@ARM.com    main['M4COMSTR']        = Transform("M4")
6479068SAli.Saidi@ARM.com    main['SHCCCOMSTR']      = Transform("SHCC")
6489068SAli.Saidi@ARM.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
6499068SAli.Saidi@ARM.comExport('MakeAction')
6509068SAli.Saidi@ARM.com
6519068SAli.Saidi@ARM.com# Initialize the Link-Time Optimization (LTO) flags
6529068SAli.Saidi@ARM.commain['LTO_CCFLAGS'] = []
6539419Sandreas.hansson@arm.commain['LTO_LDFLAGS'] = []
6549068SAli.Saidi@ARM.com
6559068SAli.Saidi@ARM.com# According to the readme, tcmalloc works best if the compiler doesn't
6569068SAli.Saidi@ARM.com# assume that we're using the builtin malloc and friends. These flags
6579068SAli.Saidi@ARM.com# are compiler-specific, so we need to set them after we detect which
6589068SAli.Saidi@ARM.com# compiler we're using.
6599068SAli.Saidi@ARM.commain['TCMALLOC_CCFLAGS'] = []
6603918Ssaidi@eecs.umich.edu
6613918Ssaidi@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
6626157Snate@binkert.orgCXX_V = readCommand([main['CXX'],'-V'], exception=False)
6636157Snate@binkert.org
6646157Snate@binkert.orgmain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
6656157Snate@binkert.orgmain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
6665397Ssaidi@eecs.umich.eduif main['GCC'] + main['CLANG'] > 1:
6675397Ssaidi@eecs.umich.edu    print 'Error: How can we have two at the same time?'
6686121Snate@binkert.org    Exit(1)
6696121Snate@binkert.org
6706121Snate@binkert.org# Set up default C++ compiler flags
6716121Snate@binkert.orgif main['GCC'] or main['CLANG']:
6726121Snate@binkert.org    # As gcc and clang share many flags, do the common parts here
6736121Snate@binkert.org    main.Append(CCFLAGS=['-pipe'])
6745397Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
6751851SN/A    # Enable -Wall and -Wextra and then disable the few warnings that
6761851SN/A    # we consistently violate
6777739Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
678955SN/A                         '-Wno-sign-compare', '-Wno-unused-parameter'])
6799396Sandreas.hansson@arm.com    # We always compile using C++11
6809396Sandreas.hansson@arm.com    main.Append(CXXFLAGS=['-std=c++11'])
6819396Sandreas.hansson@arm.com    if sys.platform.startswith('freebsd'):
6829396Sandreas.hansson@arm.com        main.Append(CCFLAGS=['-I/usr/local/include'])
6839396Sandreas.hansson@arm.com        main.Append(CXXFLAGS=['-I/usr/local/include'])
6849396Sandreas.hansson@arm.com
6859396Sandreas.hansson@arm.com    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
6869396Sandreas.hansson@arm.com    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
6879396Sandreas.hansson@arm.com    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
6889396Sandreas.hansson@arm.com    shared_partial_flags = ['-r', '-nostdlib']
6899396Sandreas.hansson@arm.com    main.Append(PSHLINKFLAGS=shared_partial_flags)
6909396Sandreas.hansson@arm.com    main.Append(PLINKFLAGS=shared_partial_flags)
6919396Sandreas.hansson@arm.comelse:
6929396Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6939396Sandreas.hansson@arm.com    print "Don't know what compiler options to use for your compiler."
6949396Sandreas.hansson@arm.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6959477Sandreas.hansson@arm.com    print termcap.Yellow + '       version:' + termcap.Normal,
6969477Sandreas.hansson@arm.com    if not CXX_version:
6979477Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6989477Sandreas.hansson@arm.com               termcap.Normal
6999477Sandreas.hansson@arm.com    else:
7009477Sandreas.hansson@arm.com        print CXX_version.replace('\n', '<nl>')
7019477Sandreas.hansson@arm.com    print "       If you're trying to use a compiler other than GCC"
7029477Sandreas.hansson@arm.com    print "       or clang, there appears to be something wrong with your"
7039477Sandreas.hansson@arm.com    print "       environment."
7049477Sandreas.hansson@arm.com    print "       "
7059477Sandreas.hansson@arm.com    print "       If you are trying to use a compiler other than those listed"
7069477Sandreas.hansson@arm.com    print "       above you will need to ease fix SConstruct and "
7079477Sandreas.hansson@arm.com    print "       src/SConscript to support that compiler."
7089477Sandreas.hansson@arm.com    Exit(1)
7099477Sandreas.hansson@arm.com
7109477Sandreas.hansson@arm.comif main['GCC']:
7119477Sandreas.hansson@arm.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
7129477Sandreas.hansson@arm.com    # level of c++11 support. See
7139477Sandreas.hansson@arm.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
7149477Sandreas.hansson@arm.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
7159477Sandreas.hansson@arm.com    if compareVersions(gcc_version, "4.8") < 0:
7169477Sandreas.hansson@arm.com        print 'Error: gcc version 4.8 or newer required.'
7179396Sandreas.hansson@arm.com        print '       Installed version:', gcc_version
7183053Sstever@eecs.umich.edu        Exit(1)
7196121Snate@binkert.org
7203053Sstever@eecs.umich.edu    main['GCC_VERSION'] = gcc_version
7213053Sstever@eecs.umich.edu
7223053Sstever@eecs.umich.edu    # gcc from version 4.8 and above generates "rep; ret" instructions
7233053Sstever@eecs.umich.edu    # to avoid performance penalties on certain AMD chips. Older
7243053Sstever@eecs.umich.edu    # assemblers detect this as an error, "Error: expecting string
7259072Sandreas.hansson@arm.com    # instruction after `rep'"
7263053Sstever@eecs.umich.edu    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
7274742Sstever@eecs.umich.edu                                  '-o', '/dev/null'],
7284742Sstever@eecs.umich.edu                                 exception=False).split()
7293053Sstever@eecs.umich.edu
7303053Sstever@eecs.umich.edu    # version strings may contain extra distro-specific
7313053Sstever@eecs.umich.edu    # qualifiers, so play it safe and keep only what comes before
7328960Ssteve.reinhardt@amd.com    # the first hyphen
7336654Snate@binkert.org    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
7343053Sstever@eecs.umich.edu
7353053Sstever@eecs.umich.edu    if not as_version or compareVersions(as_version, "2.23") < 0:
7363053Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
7373053Sstever@eecs.umich.edu            'Warning: This combination of gcc and binutils have' + \
7389740SAli.Saidi@ARM.com            ' known incompatibilities.\n' + \
7399585Sandreas@sandberg.pp.se            '         If you encounter build problems, please update ' + \
7409740SAli.Saidi@ARM.com            'binutils to 2.23.' + \
7419585Sandreas@sandberg.pp.se            termcap.Normal
7429585Sandreas@sandberg.pp.se
7439585Sandreas@sandberg.pp.se    # Make sure we warn if the user has requested to compile with the
7449585Sandreas@sandberg.pp.se    # Undefined Benahvior Sanitizer and this version of gcc does not
7459585Sandreas@sandberg.pp.se    # support it.
7469585Sandreas@sandberg.pp.se    if GetOption('with_ubsan') and \
7472667Sstever@eecs.umich.edu            compareVersions(gcc_version, '4.9') < 0:
7484554Sbinkertn@umich.edu        print termcap.Yellow + termcap.Bold + \
7496121Snate@binkert.org            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
7502667Sstever@eecs.umich.edu            termcap.Normal
7514554Sbinkertn@umich.edu
7524554Sbinkertn@umich.edu    # Add the appropriate Link-Time Optimization (LTO) flags
7534554Sbinkertn@umich.edu    # unless LTO is explicitly turned off. Note that these flags
7546121Snate@binkert.org    # are only used by the fast target.
7554554Sbinkertn@umich.edu    if not GetOption('no_lto'):
7564554Sbinkertn@umich.edu        # Pass the LTO flag when compiling to produce GIMPLE
7574554Sbinkertn@umich.edu        # output, we merely create the flags here and only append
7584781Snate@binkert.org        # them later
7594554Sbinkertn@umich.edu        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
7604554Sbinkertn@umich.edu
7612667Sstever@eecs.umich.edu        # Use the same amount of jobs for LTO as we are running
7624554Sbinkertn@umich.edu        # scons with
7634554Sbinkertn@umich.edu        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
7644554Sbinkertn@umich.edu
7654554Sbinkertn@umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
7662667Sstever@eecs.umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
7674554Sbinkertn@umich.edu
7682667Sstever@eecs.umich.edu    # add option to check for undeclared overrides
7694554Sbinkertn@umich.edu    if compareVersions(gcc_version, "5.0") > 0:
7706121Snate@binkert.org        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
7712667Sstever@eecs.umich.edu
7725522Snate@binkert.orgelif main['CLANG']:
7735522Snate@binkert.org    # Check for a supported version of clang, >= 3.1 is needed to
7745522Snate@binkert.org    # support similar features as gcc 4.8. See
7755522Snate@binkert.org    # http://clang.llvm.org/cxx_status.html for details
7765522Snate@binkert.org    clang_version_re = re.compile(".* version (\d+\.\d+)")
7775522Snate@binkert.org    clang_version_match = clang_version_re.search(CXX_version)
7785522Snate@binkert.org    if (clang_version_match):
7795522Snate@binkert.org        clang_version = clang_version_match.groups()[0]
7805522Snate@binkert.org        if compareVersions(clang_version, "3.1") < 0:
7815522Snate@binkert.org            print 'Error: clang version 3.1 or newer required.'
7825522Snate@binkert.org            print '       Installed version:', clang_version
7835522Snate@binkert.org            Exit(1)
7845522Snate@binkert.org    else:
7855522Snate@binkert.org        print 'Error: Unable to determine clang version.'
7865522Snate@binkert.org        Exit(1)
7875522Snate@binkert.org
7885522Snate@binkert.org    # clang has a few additional warnings that we disable, extraneous
7895522Snate@binkert.org    # parantheses are allowed due to Ruby's printing of the AST,
7905522Snate@binkert.org    # finally self assignments are allowed as the generated CPU code
7915522Snate@binkert.org    # is relying on this
7925522Snate@binkert.org    main.Append(CCFLAGS=['-Wno-parentheses',
7935522Snate@binkert.org                         '-Wno-self-assign',
7945522Snate@binkert.org                         # Some versions of libstdc++ (4.8?) seem to
7955522Snate@binkert.org                         # use struct hash and class hash
7965522Snate@binkert.org                         # interchangeably.
7975522Snate@binkert.org                         '-Wno-mismatched-tags',
7982638Sstever@eecs.umich.edu                         ])
7992638Sstever@eecs.umich.edu
8006121Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
8013716Sstever@eecs.umich.edu
8025522Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
8039420Sandreas.hansson@arm.com    # opposed to libstdc++, as the later is dated.
8045522Snate@binkert.org    if sys.platform == "darwin":
8055522Snate@binkert.org        main.Append(CXXFLAGS=['-stdlib=libc++'])
8065522Snate@binkert.org        main.Append(LIBS=['c++'])
8075522Snate@binkert.org
8081858SN/A    # On FreeBSD we need libthr.
8095227Ssaidi@eecs.umich.edu    if sys.platform.startswith('freebsd'):
8105227Ssaidi@eecs.umich.edu        main.Append(LIBS=['thr'])
8115227Ssaidi@eecs.umich.edu
8125227Ssaidi@eecs.umich.eduelse:
8136654Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
8146654Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
8157769SAli.Saidi@ARM.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
8167769SAli.Saidi@ARM.com    print termcap.Yellow + '       version:' + termcap.Normal,
8177769SAli.Saidi@ARM.com    if not CXX_version:
8187769SAli.Saidi@ARM.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
8195227Ssaidi@eecs.umich.edu               termcap.Normal
8205227Ssaidi@eecs.umich.edu    else:
8215227Ssaidi@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
8225204Sstever@gmail.com    print "       If you're trying to use a compiler other than GCC"
8235204Sstever@gmail.com    print "       or clang, there appears to be something wrong with your"
8245204Sstever@gmail.com    print "       environment."
8255204Sstever@gmail.com    print "       "
8265204Sstever@gmail.com    print "       If you are trying to use a compiler other than those listed"
8275204Sstever@gmail.com    print "       above you will need to ease fix SConstruct and "
8285204Sstever@gmail.com    print "       src/SConscript to support that compiler."
8295204Sstever@gmail.com    Exit(1)
8305204Sstever@gmail.com
8315204Sstever@gmail.com# Set up common yacc/bison flags (needed for Ruby)
8325204Sstever@gmail.commain['YACCFLAGS'] = '-d'
8335204Sstever@gmail.commain['YACCHXXFILESUFFIX'] = '.hh'
8345204Sstever@gmail.com
8355204Sstever@gmail.com# Do this after we save setting back, or else we'll tack on an
8365204Sstever@gmail.com# extra 'qdo' every time we run scons.
8375204Sstever@gmail.comif main['BATCH']:
8385204Sstever@gmail.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
8396121Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
8405204Sstever@gmail.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
8417727SAli.Saidi@ARM.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
8427727SAli.Saidi@ARM.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
8437727SAli.Saidi@ARM.com
8447727SAli.Saidi@ARM.comif sys.platform == 'cygwin':
8457727SAli.Saidi@ARM.com    # cygwin has some header file issues...
8469812Sandreas.hansson@arm.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
8479812Sandreas.hansson@arm.com
8489812Sandreas.hansson@arm.com# Check for the protobuf compiler
8499812Sandreas.hansson@arm.comprotoc_version = readCommand([main['PROTOC'], '--version'],
8509812Sandreas.hansson@arm.com                             exception='').split()
8519812Sandreas.hansson@arm.com
8529812Sandreas.hansson@arm.com# First two words should be "libprotoc x.y.z"
8539812Sandreas.hansson@arm.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
8549812Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + \
8559812Sandreas.hansson@arm.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
8569812Sandreas.hansson@arm.com        '         Please install protobuf-compiler for tracing support.' + \
8579812Sandreas.hansson@arm.com        termcap.Normal
8589812Sandreas.hansson@arm.com    main['PROTOC'] = False
8599812Sandreas.hansson@arm.comelse:
8609812Sandreas.hansson@arm.com    # Based on the availability of the compress stream wrappers,
8619812Sandreas.hansson@arm.com    # require 2.1.0
8629812Sandreas.hansson@arm.com    min_protoc_version = '2.1.0'
8639812Sandreas.hansson@arm.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
8649812Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + \
8659812Sandreas.hansson@arm.com            'Warning: protoc version', min_protoc_version, \
8669812Sandreas.hansson@arm.com            'or newer required.\n' + \
8679812Sandreas.hansson@arm.com            '         Installed version:', protoc_version[1], \
8689812Sandreas.hansson@arm.com            termcap.Normal
8699812Sandreas.hansson@arm.com        main['PROTOC'] = False
8707727SAli.Saidi@ARM.com    else:
8715863Snate@binkert.org        # Attempt to determine the appropriate include path and
8723118Sstever@eecs.umich.edu        # library path using pkg-config, that means we also need to
8735863Snate@binkert.org        # check for pkg-config. Note that it is possible to use
8749239Sandreas.hansson@arm.com        # protobuf without the involvement of pkg-config. Later on we
8753118Sstever@eecs.umich.edu        # check go a library config check and at that point the test
8763118Sstever@eecs.umich.edu        # will fail if libprotobuf cannot be found.
8775863Snate@binkert.org        if readCommand(['pkg-config', '--version'], exception=''):
8785863Snate@binkert.org            try:
8795863Snate@binkert.org                # Attempt to establish what linking flags to add for protobuf
8805863Snate@binkert.org                # using pkg-config
8813118Sstever@eecs.umich.edu                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
8823483Ssaidi@eecs.umich.edu            except:
8833494Ssaidi@eecs.umich.edu                print termcap.Yellow + termcap.Bold + \
8843494Ssaidi@eecs.umich.edu                    'Warning: pkg-config could not get protobuf flags.' + \
8853483Ssaidi@eecs.umich.edu                    termcap.Normal
8863483Ssaidi@eecs.umich.edu
8873483Ssaidi@eecs.umich.edu
8883053Sstever@eecs.umich.edu# Check for 'timeout' from GNU coreutils. If present, regressions will
8893053Sstever@eecs.umich.edu# be run with a time limit. We require version 8.13 since we rely on
8903918Ssaidi@eecs.umich.edu# support for the '--foreground' option.
8913053Sstever@eecs.umich.eduif sys.platform.startswith('freebsd'):
8923053Sstever@eecs.umich.edu    timeout_lines = readCommand(['gtimeout', '--version'],
8933053Sstever@eecs.umich.edu                                exception='').splitlines()
8943053Sstever@eecs.umich.eduelse:
8953053Sstever@eecs.umich.edu    timeout_lines = readCommand(['timeout', '--version'],
8969396Sandreas.hansson@arm.com                                exception='').splitlines()
8979396Sandreas.hansson@arm.com# Get the first line and tokenize it
8989396Sandreas.hansson@arm.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
8999396Sandreas.hansson@arm.commain['TIMEOUT'] =  timeout_version and \
9009396Sandreas.hansson@arm.com    compareVersions(timeout_version[-1], '8.13') >= 0
9019396Sandreas.hansson@arm.com
9029396Sandreas.hansson@arm.com# Add a custom Check function to test for structure members.
9039396Sandreas.hansson@arm.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
9049396Sandreas.hansson@arm.com    context.Message("Checking for member %s in %s..." %
9059477Sandreas.hansson@arm.com                    (member, decl))
9069396Sandreas.hansson@arm.com    text = """
9079477Sandreas.hansson@arm.com#include %(header)s
9089477Sandreas.hansson@arm.comint main(){
9099477Sandreas.hansson@arm.com  %(decl)s test;
9109477Sandreas.hansson@arm.com  (void)test.%(member)s;
9119396Sandreas.hansson@arm.com  return 0;
9127840Snate@binkert.org};
9137865Sgblack@eecs.umich.edu""" % { "header" : include_quotes[0] + include + include_quotes[1],
9147865Sgblack@eecs.umich.edu        "decl" : decl,
9157865Sgblack@eecs.umich.edu        "member" : member,
9167865Sgblack@eecs.umich.edu        }
9177865Sgblack@eecs.umich.edu
9187840Snate@binkert.org    ret = context.TryCompile(text, extension=".cc")
9199591Sandreas@sandberg.pp.se    context.Result(ret)
9209591Sandreas@sandberg.pp.se    return ret
9219591Sandreas@sandberg.pp.se
9229590Sandreas@sandberg.pp.se# Platform-specific configuration.  Note again that we assume that all
9239590Sandreas@sandberg.pp.se# builds under a given build root run on the same host platform.
9249045SAli.Saidi@ARM.comconf = Configure(main,
9259045SAli.Saidi@ARM.com                 conf_dir = joinpath(build_root, '.scons_config'),
9269071Sandreas.hansson@arm.com                 log_file = joinpath(build_root, 'scons_config.log'),
9279071Sandreas.hansson@arm.com                 custom_tests = {
9289045SAli.Saidi@ARM.com        'CheckMember' : CheckMember,
9297840Snate@binkert.org        })
9307840Snate@binkert.org
9317840Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
9321858SN/Atry:
9331858SN/A    import platform
9341858SN/A    uname = platform.uname()
9351858SN/A    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
9361858SN/A        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
9371858SN/A            main.Append(CCFLAGS=['-arch', 'x86_64'])
9389651SAndreas.Sandberg@ARM.com            main.Append(CFLAGS=['-arch', 'x86_64'])
9399651SAndreas.Sandberg@ARM.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
9409651SAndreas.Sandberg@ARM.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
9419651SAndreas.Sandberg@ARM.comexcept:
9429651SAndreas.Sandberg@ARM.com    pass
9439651SAndreas.Sandberg@ARM.com
9449651SAndreas.Sandberg@ARM.com# Recent versions of scons substitute a "Null" object for Configure()
9459651SAndreas.Sandberg@ARM.com# when configuration isn't necessary, e.g., if the "--help" option is
9469651SAndreas.Sandberg@ARM.com# present.  Unfortuantely this Null object always returns false,
9479657Sandreas.sandberg@arm.com# breaking all our configuration checks.  We replace it with our own
9489651SAndreas.Sandberg@ARM.com# more optimistic null object that returns True instead.
9499651SAndreas.Sandberg@ARM.comif not conf:
9509651SAndreas.Sandberg@ARM.com    def NullCheck(*args, **kwargs):
9519651SAndreas.Sandberg@ARM.com        return True
9529651SAndreas.Sandberg@ARM.com
9539651SAndreas.Sandberg@ARM.com    class NullConf:
9549651SAndreas.Sandberg@ARM.com        def __init__(self, env):
9559651SAndreas.Sandberg@ARM.com            self.env = env
9569651SAndreas.Sandberg@ARM.com        def Finish(self):
9579651SAndreas.Sandberg@ARM.com            return self.env
9589651SAndreas.Sandberg@ARM.com        def __getattr__(self, mname):
9595863Snate@binkert.org            return NullCheck
9605863Snate@binkert.org
9615863Snate@binkert.org    conf = NullConf(main)
9625863Snate@binkert.org
9636121Snate@binkert.org# Cache build files in the supplied directory.
9641858SN/Aif main['M5_BUILD_CACHE']:
9655863Snate@binkert.org    print 'Using build cache located at', main['M5_BUILD_CACHE']
9665863Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
9675863Snate@binkert.org
9685863Snate@binkert.orgmain['USE_PYTHON'] = not GetOption('without_python')
9695863Snate@binkert.orgif main['USE_PYTHON']:
9702139SN/A    # Find Python include and library directories for embedding the
9714202Sbinkertn@umich.edu    # interpreter. We rely on python-config to resolve the appropriate
9724202Sbinkertn@umich.edu    # includes and linker flags. ParseConfig does not seem to understand
9732139SN/A    # the more exotic linker flags such as -Xlinker and -export-dynamic so
9746994Snate@binkert.org    # we add them explicitly below. If you want to link in an alternate
9756994Snate@binkert.org    # version of python, see above for instructions on how to invoke
9766994Snate@binkert.org    # scons with the appropriate PATH set.
9776994Snate@binkert.org    #
9786994Snate@binkert.org    # First we check if python2-config exists, else we use python-config
9796994Snate@binkert.org    python_config = readCommand(['which', 'python2-config'],
9806994Snate@binkert.org                                exception='').strip()
9816994Snate@binkert.org    if not os.path.exists(python_config):
9826994Snate@binkert.org        python_config = readCommand(['which', 'python-config'],
9836994Snate@binkert.org                                    exception='').strip()
9846994Snate@binkert.org    py_includes = readCommand([python_config, '--includes'],
9856994Snate@binkert.org                              exception='').split()
9866994Snate@binkert.org    # Strip the -I from the include folders before adding them to the
9876994Snate@binkert.org    # CPPPATH
9886994Snate@binkert.org    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
9896994Snate@binkert.org
9906994Snate@binkert.org    # Read the linker flags and split them into libraries and other link
9916994Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
9926994Snate@binkert.org    py_ld_flags = readCommand([python_config, '--ldflags'],
9936994Snate@binkert.org        exception='').split()
9946994Snate@binkert.org    py_libs = []
9956994Snate@binkert.org    for lib in py_ld_flags:
9966994Snate@binkert.org         if not lib.startswith('-l'):
9976994Snate@binkert.org             main.Append(LINKFLAGS=[lib])
9986994Snate@binkert.org         else:
9996994Snate@binkert.org             lib = lib[2:]
10006994Snate@binkert.org             if lib not in py_libs:
10016994Snate@binkert.org                 py_libs.append(lib)
10022155SN/A
10035863Snate@binkert.org    # verify that this stuff works
10041869SN/A    if not conf.CheckHeader('Python.h', '<>'):
10051869SN/A        print "Error: can't find Python.h header in", py_includes
10065863Snate@binkert.org        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
10075863Snate@binkert.org        Exit(1)
10084202Sbinkertn@umich.edu
10096108Snate@binkert.org    for lib in py_libs:
10106108Snate@binkert.org        if not conf.CheckLib(lib):
10116108Snate@binkert.org            print "Error: can't find library %s required by python" % lib
10126108Snate@binkert.org            Exit(1)
10139219Spower.jg@gmail.com
10149219Spower.jg@gmail.com# On Solaris you need to use libsocket for socket ops
10159219Spower.jg@gmail.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10169219Spower.jg@gmail.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10179219Spower.jg@gmail.com       print "Can't find library with socket calls (e.g. accept())"
10189219Spower.jg@gmail.com       Exit(1)
10199219Spower.jg@gmail.com
10209219Spower.jg@gmail.com# Check for zlib.  If the check passes, libz will be automatically
10214202Sbinkertn@umich.edu# added to the LIBS environment variable.
10225863Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
10238474Sgblack@eecs.umich.edu    print 'Error: did not find needed zlib compression library '\
10248474Sgblack@eecs.umich.edu          'and/or zlib.h header file.'
10255742Snate@binkert.org    print '       Please install zlib and try again.'
10268268Ssteve.reinhardt@amd.com    Exit(1)
10278268Ssteve.reinhardt@amd.com
10288268Ssteve.reinhardt@amd.com# If we have the protobuf compiler, also make sure we have the
10295742Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
10305341Sstever@gmail.com# automatically added to the LIBS environment variable. After
10318474Sgblack@eecs.umich.edu# this, we can use the HAVE_PROTOBUF flag to determine if we have
10328474Sgblack@eecs.umich.edu# got both protoc and libprotobuf available.
10335342Sstever@gmail.commain['HAVE_PROTOBUF'] = main['PROTOC'] and \
10344202Sbinkertn@umich.edu    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
10354202Sbinkertn@umich.edu                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
10364202Sbinkertn@umich.edu
10375863Snate@binkert.org# If we have the compiler but not the library, print another warning.
10385863Snate@binkert.orgif main['PROTOC'] and not main['HAVE_PROTOBUF']:
10396994Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
10406994Snate@binkert.org        'Warning: did not find protocol buffer library and/or headers.\n' + \
10416994Snate@binkert.org    '       Please install libprotobuf-dev for tracing support.' + \
10425863Snate@binkert.org    termcap.Normal
10435863Snate@binkert.org
10445863Snate@binkert.org# Check for librt.
10455863Snate@binkert.orghave_posix_clock = \
10465863Snate@binkert.org    conf.CheckLibWithHeader(None, 'time.h', 'C',
10475863Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
10485863Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
10495863Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
10507840Snate@binkert.org
10515863Snate@binkert.orghave_posix_timers = \
10525952Ssaidi@eecs.umich.edu    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
10539651SAndreas.Sandberg@ARM.com                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
10549219Spower.jg@gmail.com
10559219Spower.jg@gmail.comif not GetOption('without_tcmalloc'):
10561869SN/A    if conf.CheckLib('tcmalloc'):
10571858SN/A        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
10585863Snate@binkert.org    elif conf.CheckLib('tcmalloc_minimal'):
10599420Sandreas.hansson@arm.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
10609420Sandreas.hansson@arm.com    else:
10611858SN/A        print termcap.Yellow + termcap.Bold + \
1062955SN/A              "You can get a 12% performance improvement by "\
1063955SN/A              "installing tcmalloc (libgoogle-perftools-dev package "\
10641869SN/A              "on Ubuntu or RedHat)." + termcap.Normal
10651869SN/A
10661869SN/A
10671869SN/A# Detect back trace implementations. The last implementation in the
10681869SN/A# list will be used by default.
10695863Snate@binkert.orgbacktrace_impls = [ "none" ]
10705863Snate@binkert.org
10715863Snate@binkert.orgif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
10721869SN/A                           'backtrace_symbols_fd((void*)0, 0, 0);'):
10735863Snate@binkert.org    backtrace_impls.append("glibc")
10741869SN/Aelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
10755863Snate@binkert.org                           'backtrace_symbols_fd((void*)0, 0, 0);'):
10761869SN/A    # NetBSD and FreeBSD need libexecinfo.
10771869SN/A    backtrace_impls.append("glibc")
10781869SN/A    main.Append(LIBS=['execinfo'])
10791869SN/A
10808483Sgblack@eecs.umich.eduif backtrace_impls[-1] == "none":
10811869SN/A    default_backtrace_impl = "none"
10821869SN/A    print termcap.Yellow + termcap.Bold + \
10831869SN/A        "No suitable back trace implementation found." + \
10841869SN/A        termcap.Normal
10855863Snate@binkert.org
10865863Snate@binkert.orgif not have_posix_clock:
10871869SN/A    print "Can't find library for POSIX clocks."
10885863Snate@binkert.org
10895863Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
10903356Sbinkertn@umich.eduhave_fenv = conf.CheckHeader('fenv.h', '<>')
10913356Sbinkertn@umich.eduif not have_fenv:
10923356Sbinkertn@umich.edu    print "Warning: Header file <fenv.h> not found."
10933356Sbinkertn@umich.edu    print "         This host has no IEEE FP rounding mode control."
10943356Sbinkertn@umich.edu
10954781Snate@binkert.org# Check if we should enable KVM-based hardware virtualization. The API
10965863Snate@binkert.org# we rely on exists since version 2.6.36 of the kernel, but somehow
10975863Snate@binkert.org# the KVM_API_VERSION does not reflect the change. We test for one of
10981869SN/A# the types as a fall back.
10991869SN/Ahave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
11001869SN/Aif not have_kvm:
11016121Snate@binkert.org    print "Info: Compatible header file <linux/kvm.h> not found, " \
11021869SN/A        "disabling KVM support."
11032638Sstever@eecs.umich.edu
11046121Snate@binkert.org# Check if the TUN/TAP driver is available.
11056121Snate@binkert.orghave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
11062638Sstever@eecs.umich.eduif not have_tuntap:
11075749Scws3k@cs.virginia.edu    print "Info: Compatible header file <linux/if_tun.h> not found."
11086121Snate@binkert.org
11096121Snate@binkert.org# x86 needs support for xsave. We test for the structure here since we
11105749Scws3k@cs.virginia.edu# won't be able to run new tests by the time we know which ISA we're
11119537Satgutier@umich.edu# targeting.
11129537Satgutier@umich.eduhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
11139537Satgutier@umich.edu                                    '#include <linux/kvm.h>') != 0
11149537Satgutier@umich.edu
11151869SN/A# Check if the requested target ISA is compatible with the host
11161869SN/Adef is_isa_kvm_compatible(isa):
11173546Sgblack@eecs.umich.edu    try:
11183546Sgblack@eecs.umich.edu        import platform
11193546Sgblack@eecs.umich.edu        host_isa = platform.machine()
11203546Sgblack@eecs.umich.edu    except:
11216121Snate@binkert.org        print "Warning: Failed to determine host ISA."
11225863Snate@binkert.org        return False
11233546Sgblack@eecs.umich.edu
11243546Sgblack@eecs.umich.edu    if not have_posix_timers:
11253546Sgblack@eecs.umich.edu        print "Warning: Can not enable KVM, host seems to lack support " \
11263546Sgblack@eecs.umich.edu            "for POSIX timers"
11274781Snate@binkert.org        return False
11284781Snate@binkert.org
11296658Snate@binkert.org    if isa == "arm":
11306658Snate@binkert.org        return host_isa in ( "armv7l", "aarch64" )
11314781Snate@binkert.org    elif isa == "x86":
11323546Sgblack@eecs.umich.edu        if host_isa != "x86_64":
11333546Sgblack@eecs.umich.edu            return False
11343546Sgblack@eecs.umich.edu
11353546Sgblack@eecs.umich.edu        if not have_kvm_xsave:
11367756SAli.Saidi@ARM.com            print "KVM on x86 requires xsave support in kernel headers."
11377816Ssteve.reinhardt@amd.com            return False
11383546Sgblack@eecs.umich.edu
11393546Sgblack@eecs.umich.edu        return True
11403546Sgblack@eecs.umich.edu    else:
11413546Sgblack@eecs.umich.edu        return False
11424202Sbinkertn@umich.edu
11433546Sgblack@eecs.umich.edu
11443546Sgblack@eecs.umich.edu# Check if the exclude_host attribute is available. We want this to
11453546Sgblack@eecs.umich.edu# get accurate instruction counts in KVM.
1146955SN/Amain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
1147955SN/A    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
1148955SN/A
1149955SN/A
11505863Snate@binkert.org######################################################################
11515863Snate@binkert.org#
11525343Sstever@gmail.com# Finish the configuration
11535343Sstever@gmail.com#
11546121Snate@binkert.orgmain = conf.Finish()
11555863Snate@binkert.org
11564773Snate@binkert.org######################################################################
11575863Snate@binkert.org#
11582632Sstever@eecs.umich.edu# Collect all non-global variables
11595863Snate@binkert.org#
11602023SN/A
11615863Snate@binkert.org# Define the universe of supported ISAs
11625863Snate@binkert.orgall_isa_list = [ ]
11635863Snate@binkert.orgall_gpu_isa_list = [ ]
11645863Snate@binkert.orgExport('all_isa_list')
11655863Snate@binkert.orgExport('all_gpu_isa_list')
11665863Snate@binkert.org
11675863Snate@binkert.orgclass CpuModel(object):
11685863Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
11695863Snate@binkert.org    know about a particular CPU model.'''
11702632Sstever@eecs.umich.edu
11715863Snate@binkert.org    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
11722023SN/A    dict = {}
11732632Sstever@eecs.umich.edu
11745863Snate@binkert.org    # Constructor.  Automatically adds models to CpuModel.dict.
11755342Sstever@gmail.com    def __init__(self, name, default=False):
11765863Snate@binkert.org        self.name = name           # name of model
11772632Sstever@eecs.umich.edu
11785863Snate@binkert.org        # This cpu is enabled by default
11795863Snate@binkert.org        self.default = default
11808267Ssteve.reinhardt@amd.com
11818120Sgblack@eecs.umich.edu        # Add self to dict
11828267Ssteve.reinhardt@amd.com        if name in CpuModel.dict:
11838267Ssteve.reinhardt@amd.com            raise AttributeError, "CpuModel '%s' already registered" % name
11848267Ssteve.reinhardt@amd.com        CpuModel.dict[name] = self
11858267Ssteve.reinhardt@amd.com
11868267Ssteve.reinhardt@amd.comExport('CpuModel')
11878267Ssteve.reinhardt@amd.com
11888267Ssteve.reinhardt@amd.com# Sticky variables get saved in the variables file so they persist from
11898267Ssteve.reinhardt@amd.com# one invocation to the next (unless overridden, in which case the new
11908267Ssteve.reinhardt@amd.com# value becomes sticky).
11915863Snate@binkert.orgsticky_vars = Variables(args=ARGUMENTS)
11925863Snate@binkert.orgExport('sticky_vars')
11935863Snate@binkert.org
11942632Sstever@eecs.umich.edu# Sticky variables that should be exported
11958267Ssteve.reinhardt@amd.comexport_vars = []
11968267Ssteve.reinhardt@amd.comExport('export_vars')
11978267Ssteve.reinhardt@amd.com
11982632Sstever@eecs.umich.edu# For Ruby
11991888SN/Aall_protocols = []
12005863Snate@binkert.orgExport('all_protocols')
12015863Snate@binkert.orgprotocol_dirs = []
12021858SN/AExport('protocol_dirs')
12038120Sgblack@eecs.umich.eduslicc_includes = []
12048120Sgblack@eecs.umich.eduExport('slicc_includes')
12057756SAli.Saidi@ARM.com
12062598SN/A# Walk the tree and execute all SConsopts scripts that wil add to the
12075863Snate@binkert.org# above variables
12081858SN/Aif GetOption('verbose'):
12091858SN/A    print "Reading SConsopts"
12101858SN/Afor bdir in [ base_dir ] + extras_dir_list:
12115863Snate@binkert.org    if not isdir(bdir):
12121858SN/A        print "Error: directory '%s' does not exist" % bdir
12131858SN/A        Exit(1)
12141858SN/A    for root, dirs, files in os.walk(bdir):
12155863Snate@binkert.org        if 'SConsopts' in files:
12161871SN/A            if GetOption('verbose'):
12171858SN/A                print "Reading", joinpath(root, 'SConsopts')
12181858SN/A            SConscript(joinpath(root, 'SConsopts'))
12191858SN/A
12201858SN/Aall_isa_list.sort()
12219651SAndreas.Sandberg@ARM.comall_gpu_isa_list.sort()
12229651SAndreas.Sandberg@ARM.com
12239651SAndreas.Sandberg@ARM.comsticky_vars.AddVariables(
12249651SAndreas.Sandberg@ARM.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
12259651SAndreas.Sandberg@ARM.com    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
12269651SAndreas.Sandberg@ARM.com    ListVariable('CPU_MODELS', 'CPU models',
12279651SAndreas.Sandberg@ARM.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
12289651SAndreas.Sandberg@ARM.com                 sorted(CpuModel.dict.keys())),
12299651SAndreas.Sandberg@ARM.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
12305863Snate@binkert.org                 False),
12315863Snate@binkert.org    BoolVariable('SS_COMPATIBLE_FP',
12321869SN/A                 'Make floating-point results compatible with SimpleScalar',
12331965SN/A                 False),
12347739Sgblack@eecs.umich.edu    BoolVariable('USE_SSE2',
12351965SN/A                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
12362761Sstever@eecs.umich.edu                 False),
12375863Snate@binkert.org    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
12381869SN/A    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
12395863Snate@binkert.org    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
12402667Sstever@eecs.umich.edu    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
12411869SN/A    BoolVariable('USE_TUNTAP',
12421869SN/A                 'Enable using a tap device to bridge to the host network',
12432929Sktlim@umich.edu                 have_tuntap),
12442929Sktlim@umich.edu    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
12455863Snate@binkert.org    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
12462929Sktlim@umich.edu                  all_protocols),
1247955SN/A    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
12488120Sgblack@eecs.umich.edu                 backtrace_impls[-1], backtrace_impls)
12498120Sgblack@eecs.umich.edu    )
12508120Sgblack@eecs.umich.edu
12518120Sgblack@eecs.umich.edu# These variables get exported to #defines in config/*.hh (see src/SConscript).
12528120Sgblack@eecs.umich.eduexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
12538120Sgblack@eecs.umich.edu                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
12548120Sgblack@eecs.umich.edu                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
12558120Sgblack@eecs.umich.edu
12568120Sgblack@eecs.umich.edu###################################################
12578120Sgblack@eecs.umich.edu#
12588120Sgblack@eecs.umich.edu# Define a SCons builder for configuration flag headers.
12598120Sgblack@eecs.umich.edu#
1260###################################################
1261
1262# This function generates a config header file that #defines the
1263# variable symbol to the current variable setting (0 or 1).  The source
1264# operands are the name of the variable and a Value node containing the
1265# value of the variable.
1266def build_config_file(target, source, env):
1267    (variable, value) = [s.get_contents() for s in source]
1268    f = file(str(target[0]), 'w')
1269    print >> f, '#define', variable, value
1270    f.close()
1271    return None
1272
1273# Combine the two functions into a scons Action object.
1274config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1275
1276# The emitter munges the source & target node lists to reflect what
1277# we're really doing.
1278def config_emitter(target, source, env):
1279    # extract variable name from Builder arg
1280    variable = str(target[0])
1281    # True target is config header file
1282    target = joinpath('config', variable.lower() + '.hh')
1283    val = env[variable]
1284    if isinstance(val, bool):
1285        # Force value to 0/1
1286        val = int(val)
1287    elif isinstance(val, str):
1288        val = '"' + val + '"'
1289
1290    # Sources are variable name & value (packaged in SCons Value nodes)
1291    return ([target], [Value(variable), Value(val)])
1292
1293config_builder = Builder(emitter = config_emitter, action = config_action)
1294
1295main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1296
1297###################################################
1298#
1299# Builders for static and shared partially linked object files.
1300#
1301###################################################
1302
1303partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1304                                 src_suffix='$OBJSUFFIX',
1305                                 src_builder=['StaticObject', 'Object'],
1306                                 LINKFLAGS='$PLINKFLAGS',
1307                                 LIBS='')
1308
1309def partial_shared_emitter(target, source, env):
1310    for tgt in target:
1311        tgt.attributes.shared = 1
1312    return (target, source)
1313partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1314                                 emitter=partial_shared_emitter,
1315                                 src_suffix='$SHOBJSUFFIX',
1316                                 src_builder='SharedObject',
1317                                 SHLINKFLAGS='$PSHLINKFLAGS',
1318                                 LIBS='')
1319
1320main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1321                         'PartialStatic' : partial_static_builder })
1322
1323# builds in ext are shared across all configs in the build root.
1324ext_dir = abspath(joinpath(str(main.root), 'ext'))
1325ext_build_dirs = []
1326for root, dirs, files in os.walk(ext_dir):
1327    if 'SConscript' in files:
1328        build_dir = os.path.relpath(root, ext_dir)
1329        ext_build_dirs.append(build_dir)
1330        main.SConscript(joinpath(root, 'SConscript'),
1331                        variant_dir=joinpath(build_root, build_dir))
1332
1333main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1334
1335###################################################
1336#
1337# This builder and wrapper method are used to set up a directory with
1338# switching headers. Those are headers which are in a generic location and
1339# that include more specific headers from a directory chosen at build time
1340# based on the current build settings.
1341#
1342###################################################
1343
1344def build_switching_header(target, source, env):
1345    path = str(target[0])
1346    subdir = str(source[0])
1347    dp, fp = os.path.split(path)
1348    dp = os.path.relpath(os.path.realpath(dp),
1349                         os.path.realpath(env['BUILDDIR']))
1350    with open(path, 'w') as hdr:
1351        print >>hdr, '#include "%s/%s/%s"' % (dp, subdir, fp)
1352
1353switching_header_action = MakeAction(build_switching_header,
1354                                     Transform('GENERATE'))
1355
1356switching_header_builder = Builder(action=switching_header_action,
1357                                   source_factory=Value,
1358                                   single_source=True)
1359
1360main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1361
1362def switching_headers(self, headers, source):
1363    for header in headers:
1364        self.SwitchingHeader(header, source)
1365
1366main.AddMethod(switching_headers, 'SwitchingHeaders')
1367
1368# all-isas -> all-deps -> all-environs -> all_targets
1369main.Alias('#all-isas', [])
1370main.Alias('#all-deps', '#all-isas')
1371
1372# Dummy target to ensure all environments are created before telling
1373# SCons what to actually make (the command line arguments).  We attach
1374# them to the dependence graph after the environments are complete.
1375ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1376def environsComplete(target, source, env):
1377    for t in ORIG_BUILD_TARGETS:
1378        main.Depends('#all-targets', t)
1379
1380# Each build/* switching_dir attaches its *-environs target to #all-environs.
1381main.Append(BUILDERS = {'CompleteEnvirons' :
1382                        Builder(action=MakeAction(environsComplete, None))})
1383main.CompleteEnvirons('#all-environs', [])
1384
1385def doNothing(**ignored): pass
1386main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1387
1388# The final target to which all the original targets ultimately get attached.
1389main.Dummy('#all-targets', '#all-environs')
1390BUILD_TARGETS[:] = ['#all-targets']
1391
1392###################################################
1393#
1394# Define build environments for selected configurations.
1395#
1396###################################################
1397
1398def variant_name(path):
1399    return os.path.basename(path).lower().replace('_', '-')
1400main['variant_name'] = variant_name
1401main['VARIANT_NAME'] = '${variant_name(BUILDDIR)}'
1402
1403for variant_path in variant_paths:
1404    if not GetOption('silent'):
1405        print "Building in", variant_path
1406
1407    # Make a copy of the build-root environment to use for this config.
1408    env = main.Clone()
1409    env['BUILDDIR'] = variant_path
1410
1411    # variant_dir is the tail component of build path, and is used to
1412    # determine the build parameters (e.g., 'ALPHA_SE')
1413    (build_root, variant_dir) = splitpath(variant_path)
1414
1415    # Set env variables according to the build directory config.
1416    sticky_vars.files = []
1417    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1418    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1419    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1420    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1421    if isfile(current_vars_file):
1422        sticky_vars.files.append(current_vars_file)
1423        if not GetOption('silent'):
1424            print "Using saved variables file %s" % current_vars_file
1425    elif variant_dir in ext_build_dirs:
1426        # Things in ext are built without a variant directory.
1427        continue
1428    else:
1429        # Build dir-specific variables file doesn't exist.
1430
1431        # Make sure the directory is there so we can create it later
1432        opt_dir = dirname(current_vars_file)
1433        if not isdir(opt_dir):
1434            mkdir(opt_dir)
1435
1436        # Get default build variables from source tree.  Variables are
1437        # normally determined by name of $VARIANT_DIR, but can be
1438        # overridden by '--default=' arg on command line.
1439        default = GetOption('default')
1440        opts_dir = joinpath(main.root.abspath, 'build_opts')
1441        if default:
1442            default_vars_files = [joinpath(build_root, 'variables', default),
1443                                  joinpath(opts_dir, default)]
1444        else:
1445            default_vars_files = [joinpath(opts_dir, variant_dir)]
1446        existing_files = filter(isfile, default_vars_files)
1447        if existing_files:
1448            default_vars_file = existing_files[0]
1449            sticky_vars.files.append(default_vars_file)
1450            print "Variables file %s not found,\n  using defaults in %s" \
1451                  % (current_vars_file, default_vars_file)
1452        else:
1453            print "Error: cannot find variables file %s or " \
1454                  "default file(s) %s" \
1455                  % (current_vars_file, ' or '.join(default_vars_files))
1456            Exit(1)
1457
1458    # Apply current variable settings to env
1459    sticky_vars.Update(env)
1460
1461    help_texts["local_vars"] += \
1462        "Build variables for %s:\n" % variant_dir \
1463                 + sticky_vars.GenerateHelpText(env)
1464
1465    # Process variable settings.
1466
1467    if not have_fenv and env['USE_FENV']:
1468        print "Warning: <fenv.h> not available; " \
1469              "forcing USE_FENV to False in", variant_dir + "."
1470        env['USE_FENV'] = False
1471
1472    if not env['USE_FENV']:
1473        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1474        print "         FP results may deviate slightly from other platforms."
1475
1476    if env['EFENCE']:
1477        env.Append(LIBS=['efence'])
1478
1479    if env['USE_KVM']:
1480        if not have_kvm:
1481            print "Warning: Can not enable KVM, host seems to lack KVM support"
1482            env['USE_KVM'] = False
1483        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1484            print "Info: KVM support disabled due to unsupported host and " \
1485                "target ISA combination"
1486            env['USE_KVM'] = False
1487
1488    if env['USE_TUNTAP']:
1489        if not have_tuntap:
1490            print "Warning: Can't connect EtherTap with a tap device."
1491            env['USE_TUNTAP'] = False
1492
1493    if env['BUILD_GPU']:
1494        env.Append(CPPDEFINES=['BUILD_GPU'])
1495
1496    # Warn about missing optional functionality
1497    if env['USE_KVM']:
1498        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1499            print "Warning: perf_event headers lack support for the " \
1500                "exclude_host attribute. KVM instruction counts will " \
1501                "be inaccurate."
1502
1503    # Save sticky variable settings back to current variables file
1504    sticky_vars.Save(current_vars_file, env)
1505
1506    if env['USE_SSE2']:
1507        env.Append(CCFLAGS=['-msse2'])
1508
1509    # The src/SConscript file sets up the build rules in 'env' according
1510    # to the configured variables.  It returns a list of environments,
1511    # one for each variant build (debug, opt, etc.)
1512    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1513
1514def pairwise(iterable):
1515    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1516    a, b = itertools.tee(iterable)
1517    b.next()
1518    return itertools.izip(a, b)
1519
1520variant_names = [variant_name(path) for path in variant_paths]
1521
1522# Create false dependencies so SCons will parse ISAs, establish
1523# dependencies, and setup the build Environments serially. Either
1524# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1525# greater than 1. It appears to be standard race condition stuff; it
1526# doesn't always fail, but usually, and the behaviors are different.
1527# Every time I tried to remove this, builds would fail in some
1528# creative new way. So, don't do that. You'll want to, though, because
1529# tests/SConscript takes a long time to make its Environments.
1530for t1, t2 in pairwise(sorted(variant_names)):
1531    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1532    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1533
1534# base help text
1535Help('''
1536Usage: scons [scons options] [build variables] [target(s)]
1537
1538Extra scons options:
1539%(options)s
1540
1541Global build variables:
1542%(global_vars)s
1543
1544%(local_vars)s
1545''' % help_texts)
1546