SConstruct revision 11500
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', 'SWIG', '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# Check that swig is present
2458336Ssteve.reinhardt@amd.comif not 'SWIG' in main_dict_keys:
2468336Ssteve.reinhardt@amd.com    print "swig is not installed (package swig on Ubuntu and RedHat)"
2474678Snate@binkert.org    Exit(1)
2488336Ssteve.reinhardt@amd.com
2498336Ssteve.reinhardt@amd.com# add useful python code PYTHONPATH so it can be used by subprocesses
2508336Ssteve.reinhardt@amd.com# as well
2514678Snate@binkert.orgmain.AppendENVPath('PYTHONPATH', extra_python_paths)
2524678Snate@binkert.org
2534678Snate@binkert.org########################################################################
2544678Snate@binkert.org#
2557827Snate@binkert.org# Mercurial Stuff.
2567827Snate@binkert.org#
2578336Ssteve.reinhardt@amd.com# If the gem5 directory is a mercurial repository, we should do some
2584678Snate@binkert.org# extra things.
2598336Ssteve.reinhardt@amd.com#
2608336Ssteve.reinhardt@amd.com########################################################################
2618336Ssteve.reinhardt@amd.com
2628336Ssteve.reinhardt@amd.comhgdir = main.root.Dir(".hg")
2638336Ssteve.reinhardt@amd.com
2648336Ssteve.reinhardt@amd.com
2655871Snate@binkert.orgstyle_message = """
2665871Snate@binkert.orgYou're missing the gem5 style hook, which automatically checks your code
2678336Ssteve.reinhardt@amd.comagainst the gem5 style rules on %s.
2688336Ssteve.reinhardt@amd.comThis script will now install the hook in your %s.
2698336Ssteve.reinhardt@amd.comPress enter to continue, or ctrl-c to abort: """
2708336Ssteve.reinhardt@amd.com
2718336Ssteve.reinhardt@amd.commercurial_style_message = style_message % ("hg commit and qrefresh commands",
2725871Snate@binkert.org                                           ".hg/hgrc file")
2738336Ssteve.reinhardt@amd.comgit_style_message = style_message % ("'git commit'",
2748336Ssteve.reinhardt@amd.com                                     ".git/hooks/ directory")
2758336Ssteve.reinhardt@amd.com
2768336Ssteve.reinhardt@amd.commercurial_style_upgrade_message = """
2778336Ssteve.reinhardt@amd.comYour Mercurial style hooks are not up-to-date. This script will now
2784678Snate@binkert.orgtry to automatically update them. A backup of your hgrc will be saved
2795871Snate@binkert.orgin .hg/hgrc.old.
2804678Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
2818336Ssteve.reinhardt@amd.com
2828336Ssteve.reinhardt@amd.commercurial_style_hook = """
2838336Ssteve.reinhardt@amd.com# The following lines were automatically added by gem5/SConstruct
2848336Ssteve.reinhardt@amd.com# to provide the gem5 style-checking hooks
2858336Ssteve.reinhardt@amd.com[extensions]
2868336Ssteve.reinhardt@amd.comhgstyle = %s/util/hgstyle.py
2878336Ssteve.reinhardt@amd.com
2888336Ssteve.reinhardt@amd.com[hooks]
2898336Ssteve.reinhardt@amd.compretxncommit.style = python:hgstyle.check_style
2908336Ssteve.reinhardt@amd.compre-qrefresh.style = python:hgstyle.check_style
2918336Ssteve.reinhardt@amd.com# End of SConstruct additions
2928336Ssteve.reinhardt@amd.com
2938336Ssteve.reinhardt@amd.com""" % (main.root.abspath)
2948336Ssteve.reinhardt@amd.com
2958336Ssteve.reinhardt@amd.commercurial_lib_not_found = """
2968336Ssteve.reinhardt@amd.comMercurial libraries cannot be found, ignoring style hook.  If
2978336Ssteve.reinhardt@amd.comyou are a gem5 developer, please fix this and run the style
2985871Snate@binkert.orghook. It is important.
2996121Snate@binkert.org"""
300955SN/A
301955SN/A# Check for style hook and prompt for installation if it's not there.
3022632Sstever@eecs.umich.edu# Skip this if --ignore-style was specified, there's no interactive
3032632Sstever@eecs.umich.edu# terminal to prompt, or no recognized revision control system can be
304955SN/A# found.
305955SN/Aignore_style = GetOption('ignore_style') or not sys.stdin.isatty()
306955SN/A
307955SN/A# Try wire up Mercurial to the style hooks
3088878Ssteve.reinhardt@amd.comif not ignore_style and hgdir.exists():
309955SN/A    style_hook = True
3102632Sstever@eecs.umich.edu    style_hooks = tuple()
3112632Sstever@eecs.umich.edu    hgrc = hgdir.File('hgrc')
3122632Sstever@eecs.umich.edu    hgrc_old = hgdir.File('hgrc.old')
3132632Sstever@eecs.umich.edu    try:
3142632Sstever@eecs.umich.edu        from mercurial import ui
3152632Sstever@eecs.umich.edu        ui = ui.ui()
3162632Sstever@eecs.umich.edu        ui.readconfig(hgrc.abspath)
3178268Ssteve.reinhardt@amd.com        style_hooks = (ui.config('hooks', 'pretxncommit.style', None),
3188268Ssteve.reinhardt@amd.com                       ui.config('hooks', 'pre-qrefresh.style', None))
3198268Ssteve.reinhardt@amd.com        style_hook = all(style_hooks)
3208268Ssteve.reinhardt@amd.com        style_extension = ui.config('extensions', 'style', None)
3218268Ssteve.reinhardt@amd.com    except ImportError:
3228268Ssteve.reinhardt@amd.com        print mercurial_lib_not_found
3238268Ssteve.reinhardt@amd.com
3242632Sstever@eecs.umich.edu    if "python:style.check_style" in style_hooks:
3252632Sstever@eecs.umich.edu        # Try to upgrade the style hooks
3262632Sstever@eecs.umich.edu        print mercurial_style_upgrade_message
3272632Sstever@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
3288268Ssteve.reinhardt@amd.com        try:
3292632Sstever@eecs.umich.edu            raw_input()
3308268Ssteve.reinhardt@amd.com        except:
3318268Ssteve.reinhardt@amd.com            print "Input exception, exiting scons.\n"
3328268Ssteve.reinhardt@amd.com            sys.exit(1)
3338268Ssteve.reinhardt@amd.com        shutil.copyfile(hgrc.abspath, hgrc_old.abspath)
3343718Sstever@eecs.umich.edu        re_style_hook = re.compile(r"^([^=#]+)\.style\s*=\s*([^#\s]+).*")
3352634Sstever@eecs.umich.edu        re_style_extension = re.compile("style\s*=\s*([^#\s]+).*")
3362634Sstever@eecs.umich.edu        old, new = open(hgrc_old.abspath, 'r'), open(hgrc.abspath, 'w')
3375863Snate@binkert.org        for l in old:
3382638Sstever@eecs.umich.edu            m_hook = re_style_hook.match(l)
3398268Ssteve.reinhardt@amd.com            m_ext = re_style_extension.match(l)
3402632Sstever@eecs.umich.edu            if m_hook:
3412632Sstever@eecs.umich.edu                hook, check = m_hook.groups()
3422632Sstever@eecs.umich.edu                if check != "python:style.check_style":
3432632Sstever@eecs.umich.edu                    print "Warning: %s.style is using a non-default " \
3442632Sstever@eecs.umich.edu                        "checker: %s" % (hook, check)
3451858SN/A                if hook not in ("pretxncommit", "pre-qrefresh"):
3463716Sstever@eecs.umich.edu                    print "Warning: Updating unknown style hook: %s" % hook
3472638Sstever@eecs.umich.edu
3482638Sstever@eecs.umich.edu                l = "%s.style = python:hgstyle.check_style\n" % hook
3492638Sstever@eecs.umich.edu            elif m_ext and m_ext.group(1) == style_extension:
3502638Sstever@eecs.umich.edu                l = "hgstyle = %s/util/hgstyle.py\n" % main.root.abspath
3512638Sstever@eecs.umich.edu
3522638Sstever@eecs.umich.edu            new.write(l)
3532638Sstever@eecs.umich.edu    elif not style_hook:
3545863Snate@binkert.org        print mercurial_style_message,
3555863Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
3565863Snate@binkert.org        try:
357955SN/A            raw_input()
3585341Sstever@gmail.com        except:
3595341Sstever@gmail.com            print "Input exception, exiting scons.\n"
3605863Snate@binkert.org            sys.exit(1)
3617756SAli.Saidi@ARM.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3625341Sstever@gmail.com        print "Adding style hook to", hgrc_path, "\n"
3636121Snate@binkert.org        try:
3644494Ssaidi@eecs.umich.edu            with open(hgrc_path, 'a') as f:
3656121Snate@binkert.org                f.write(mercurial_style_hook)
3661105SN/A        except:
3672667Sstever@eecs.umich.edu            print "Error updating", hgrc_path
3682667Sstever@eecs.umich.edu            sys.exit(1)
3692667Sstever@eecs.umich.edu
3702667Sstever@eecs.umich.edudef install_git_style_hooks():
3716121Snate@binkert.org    try:
3722667Sstever@eecs.umich.edu        gitdir = Dir(readCommand(
3735341Sstever@gmail.com            ["git", "rev-parse", "--git-dir"]).strip("\n"))
3745863Snate@binkert.org    except Exception, e:
3755341Sstever@gmail.com        print "Warning: Failed to find git repo directory: %s" % e
3765341Sstever@gmail.com        return
3775341Sstever@gmail.com
3788120Sgblack@eecs.umich.edu    git_hooks = gitdir.Dir("hooks")
3795341Sstever@gmail.com    git_pre_commit_hook = git_hooks.File("pre-commit")
3808120Sgblack@eecs.umich.edu    git_style_script = File("util/git-pre-commit.py")
3815341Sstever@gmail.com
3828120Sgblack@eecs.umich.edu    if git_pre_commit_hook.exists():
3836121Snate@binkert.org        return
3846121Snate@binkert.org
3858980Ssteve.reinhardt@amd.com    print git_style_message,
3869396Sandreas.hansson@arm.com    try:
3875397Ssaidi@eecs.umich.edu        raw_input()
3885397Ssaidi@eecs.umich.edu    except:
3897727SAli.Saidi@ARM.com        print "Input exception, exiting scons.\n"
3908268Ssteve.reinhardt@amd.com        sys.exit(1)
3916168Snate@binkert.org
3925341Sstever@gmail.com    if not git_hooks.exists():
3938120Sgblack@eecs.umich.edu        mkdir(git_hooks.get_abspath())
3948120Sgblack@eecs.umich.edu
3958120Sgblack@eecs.umich.edu    # Use a relative symlink if the hooks live in the source directory
3966814Sgblack@eecs.umich.edu    if git_pre_commit_hook.is_under(main.root):
3975863Snate@binkert.org        script_path = os.path.relpath(
3988120Sgblack@eecs.umich.edu            git_style_script.get_abspath(),
3995341Sstever@gmail.com            git_pre_commit_hook.Dir(".").get_abspath())
4005863Snate@binkert.org    else:
4018268Ssteve.reinhardt@amd.com        script_path = git_style_script.get_abspath()
4026121Snate@binkert.org
4036121Snate@binkert.org    try:
4048268Ssteve.reinhardt@amd.com        os.symlink(script_path, git_pre_commit_hook.get_abspath())
4055742Snate@binkert.org    except:
4065742Snate@binkert.org        print "Error updating git pre-commit hook"
4075341Sstever@gmail.com        raise
4085742Snate@binkert.org
4095742Snate@binkert.org# Try to wire up git to the style hooks
4105341Sstever@gmail.comif not ignore_style and main.root.Entry(".git").exists():
4116017Snate@binkert.org    install_git_style_hooks()
4126121Snate@binkert.org
4136017Snate@binkert.org###################################################
4147816Ssteve.reinhardt@amd.com#
4157756SAli.Saidi@ARM.com# Figure out which configurations to set up based on the path(s) of
4167756SAli.Saidi@ARM.com# the target(s).
4177756SAli.Saidi@ARM.com#
4187756SAli.Saidi@ARM.com###################################################
4197756SAli.Saidi@ARM.com
4207756SAli.Saidi@ARM.com# Find default configuration & binary.
4217756SAli.Saidi@ARM.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
4227756SAli.Saidi@ARM.com
4237816Ssteve.reinhardt@amd.com# helper function: find last occurrence of element in list
4247816Ssteve.reinhardt@amd.comdef rfind(l, elt, offs = -1):
4257816Ssteve.reinhardt@amd.com    for i in range(len(l)+offs, 0, -1):
4267816Ssteve.reinhardt@amd.com        if l[i] == elt:
4277816Ssteve.reinhardt@amd.com            return i
4287816Ssteve.reinhardt@amd.com    raise ValueError, "element not found"
4297816Ssteve.reinhardt@amd.com
4307816Ssteve.reinhardt@amd.com# Take a list of paths (or SCons Nodes) and return a list with all
4317816Ssteve.reinhardt@amd.com# paths made absolute and ~-expanded.  Paths will be interpreted
4327816Ssteve.reinhardt@amd.com# relative to the launch directory unless a different root is provided
4337756SAli.Saidi@ARM.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
4347816Ssteve.reinhardt@amd.com    return [abspath(joinpath(root, expanduser(str(p))))
4357816Ssteve.reinhardt@amd.com            for p in path_list]
4367816Ssteve.reinhardt@amd.com
4377816Ssteve.reinhardt@amd.com# Each target must have 'build' in the interior of the path; the
4387816Ssteve.reinhardt@amd.com# directory below this will determine the build parameters.  For
4397816Ssteve.reinhardt@amd.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
4407816Ssteve.reinhardt@amd.com# recognize that ALPHA_SE specifies the configuration because it
4417816Ssteve.reinhardt@amd.com# follow 'build' in the build path.
4427816Ssteve.reinhardt@amd.com
4437816Ssteve.reinhardt@amd.com# The funky assignment to "[:]" is needed to replace the list contents
4447816Ssteve.reinhardt@amd.com# in place rather than reassign the symbol to a new list, which
4457816Ssteve.reinhardt@amd.com# doesn't work (obviously!).
4467816Ssteve.reinhardt@amd.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
4477816Ssteve.reinhardt@amd.com
4487816Ssteve.reinhardt@amd.com# Generate a list of the unique build roots and configs that the
4497816Ssteve.reinhardt@amd.com# collected targets reference.
4507816Ssteve.reinhardt@amd.comvariant_paths = []
4517816Ssteve.reinhardt@amd.combuild_root = None
4527816Ssteve.reinhardt@amd.comfor t in BUILD_TARGETS:
4537816Ssteve.reinhardt@amd.com    path_dirs = t.split('/')
4547816Ssteve.reinhardt@amd.com    try:
4557816Ssteve.reinhardt@amd.com        build_top = rfind(path_dirs, 'build', -2)
4567816Ssteve.reinhardt@amd.com    except:
4577816Ssteve.reinhardt@amd.com        print "Error: no non-leaf 'build' dir found on target path", t
4587816Ssteve.reinhardt@amd.com        Exit(1)
4597816Ssteve.reinhardt@amd.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
4607816Ssteve.reinhardt@amd.com    if not build_root:
4617816Ssteve.reinhardt@amd.com        build_root = this_build_root
4627816Ssteve.reinhardt@amd.com    else:
4637816Ssteve.reinhardt@amd.com        if this_build_root != build_root:
4647816Ssteve.reinhardt@amd.com            print "Error: build targets not under same build root\n"\
4657816Ssteve.reinhardt@amd.com                  "  %s\n  %s" % (build_root, this_build_root)
4667816Ssteve.reinhardt@amd.com            Exit(1)
4677816Ssteve.reinhardt@amd.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
4687816Ssteve.reinhardt@amd.com    if variant_path not in variant_paths:
4697816Ssteve.reinhardt@amd.com        variant_paths.append(variant_path)
4707816Ssteve.reinhardt@amd.com
4717816Ssteve.reinhardt@amd.com# Make sure build_root exists (might not if this is the first build there)
4727816Ssteve.reinhardt@amd.comif not isdir(build_root):
4737816Ssteve.reinhardt@amd.com    mkdir(build_root)
4747816Ssteve.reinhardt@amd.commain['BUILDROOT'] = build_root
4757816Ssteve.reinhardt@amd.com
4767816Ssteve.reinhardt@amd.comExport('main')
4777816Ssteve.reinhardt@amd.com
4787816Ssteve.reinhardt@amd.commain.SConsignFile(joinpath(build_root, "sconsign"))
4797816Ssteve.reinhardt@amd.com
4807816Ssteve.reinhardt@amd.com# Default duplicate option is to use hard links, but this messes up
4817816Ssteve.reinhardt@amd.com# when you use emacs to edit a file in the target dir, as emacs moves
4827816Ssteve.reinhardt@amd.com# file to file~ then copies to file, breaking the link.  Symbolic
4837816Ssteve.reinhardt@amd.com# (soft) links work better.
4847816Ssteve.reinhardt@amd.commain.SetOption('duplicate', 'soft-copy')
4857816Ssteve.reinhardt@amd.com
4867816Ssteve.reinhardt@amd.com#
4877816Ssteve.reinhardt@amd.com# Set up global sticky variables... these are common to an entire build
4887816Ssteve.reinhardt@amd.com# tree (not specific to a particular build like ALPHA_SE)
4897816Ssteve.reinhardt@amd.com#
4907816Ssteve.reinhardt@amd.com
4917816Ssteve.reinhardt@amd.comglobal_vars_file = joinpath(build_root, 'variables.global')
4927816Ssteve.reinhardt@amd.com
4937816Ssteve.reinhardt@amd.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
4947816Ssteve.reinhardt@amd.com
4958947Sandreas.hansson@arm.comglobal_vars.AddVariables(
4968947Sandreas.hansson@arm.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
4977756SAli.Saidi@ARM.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
4988120Sgblack@eecs.umich.edu    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
4997756SAli.Saidi@ARM.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
5007756SAli.Saidi@ARM.com    ('BATCH', 'Use batch pool for build and tests', False),
5017756SAli.Saidi@ARM.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
5027756SAli.Saidi@ARM.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
5037816Ssteve.reinhardt@amd.com    ('EXTRAS', 'Add extra directories to the compilation', '')
5047816Ssteve.reinhardt@amd.com    )
5057816Ssteve.reinhardt@amd.com
5067816Ssteve.reinhardt@amd.com# Update main environment with values from ARGUMENTS & global_vars_file
5077816Ssteve.reinhardt@amd.comglobal_vars.Update(main)
5087816Ssteve.reinhardt@amd.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
5097816Ssteve.reinhardt@amd.com
5107816Ssteve.reinhardt@amd.com# Save sticky variable settings back to current variables file
5117816Ssteve.reinhardt@amd.comglobal_vars.Save(global_vars_file, main)
5127816Ssteve.reinhardt@amd.com
5137756SAli.Saidi@ARM.com# Parse EXTRAS variable to build list of all directories where we're
5147756SAli.Saidi@ARM.com# look for sources etc.  This list is exported as extras_dir_list.
5159227Sandreas.hansson@arm.combase_dir = main.srcdir.abspath
5169227Sandreas.hansson@arm.comif main['EXTRAS']:
5179227Sandreas.hansson@arm.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
5189227Sandreas.hansson@arm.comelse:
5199590Sandreas@sandberg.pp.se    extras_dir_list = []
5209590Sandreas@sandberg.pp.se
5219590Sandreas@sandberg.pp.seExport('base_dir')
5229590Sandreas@sandberg.pp.seExport('extras_dir_list')
5239590Sandreas@sandberg.pp.se
5249590Sandreas@sandberg.pp.se# the ext directory should be on the #includes path
5256654Snate@binkert.orgmain.Append(CPPPATH=[Dir('ext')])
5266654Snate@binkert.org
5275871Snate@binkert.orgdef strip_build_path(path, env):
5286121Snate@binkert.org    path = str(path)
5298946Sandreas.hansson@arm.com    variant_base = env['BUILDROOT'] + os.path.sep
5309419Sandreas.hansson@arm.com    if path.startswith(variant_base):
5313940Ssaidi@eecs.umich.edu        path = path[len(variant_base):]
5323918Ssaidi@eecs.umich.edu    elif path.startswith('build/'):
5333918Ssaidi@eecs.umich.edu        path = path[6:]
5341858SN/A    return path
5359556Sandreas.hansson@arm.com
5369556Sandreas.hansson@arm.com# Generate a string of the form:
5379556Sandreas.hansson@arm.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
5389556Sandreas.hansson@arm.com# to print while building.
5399556Sandreas.hansson@arm.comclass Transform(object):
5409556Sandreas.hansson@arm.com    # all specific color settings should be here and nowhere else
5419556Sandreas.hansson@arm.com    tool_color = termcap.Normal
5429556Sandreas.hansson@arm.com    pfx_color = termcap.Yellow
5439556Sandreas.hansson@arm.com    srcs_color = termcap.Yellow + termcap.Bold
5449556Sandreas.hansson@arm.com    arrow_color = termcap.Blue + termcap.Bold
5459556Sandreas.hansson@arm.com    tgts_color = termcap.Yellow + termcap.Bold
5469556Sandreas.hansson@arm.com
5479556Sandreas.hansson@arm.com    def __init__(self, tool, max_sources=99):
5489556Sandreas.hansson@arm.com        self.format = self.tool_color + (" [%8s] " % tool) \
5499556Sandreas.hansson@arm.com                      + self.pfx_color + "%s" \
5509556Sandreas.hansson@arm.com                      + self.srcs_color + "%s" \
5519556Sandreas.hansson@arm.com                      + self.arrow_color + " -> " \
5529556Sandreas.hansson@arm.com                      + self.tgts_color + "%s" \
5539556Sandreas.hansson@arm.com                      + termcap.Normal
5549556Sandreas.hansson@arm.com        self.max_sources = max_sources
5559556Sandreas.hansson@arm.com
5569556Sandreas.hansson@arm.com    def __call__(self, target, source, env, for_signature=None):
5579556Sandreas.hansson@arm.com        # truncate source list according to max_sources param
5589556Sandreas.hansson@arm.com        source = source[0:self.max_sources]
5599556Sandreas.hansson@arm.com        def strip(f):
5609556Sandreas.hansson@arm.com            return strip_build_path(str(f), env)
5619556Sandreas.hansson@arm.com        if len(source) > 0:
5629556Sandreas.hansson@arm.com            srcs = map(strip, source)
5639556Sandreas.hansson@arm.com        else:
5649556Sandreas.hansson@arm.com            srcs = ['']
5659556Sandreas.hansson@arm.com        tgts = map(strip, target)
5669556Sandreas.hansson@arm.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
5676121Snate@binkert.org        # operation that has nothing to do with paths.
5689420Sandreas.hansson@arm.com        com_pfx = os.path.commonprefix(srcs + tgts)
5699420Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
5709420Sandreas.hansson@arm.com        if com_pfx:
5719420Sandreas.hansson@arm.com            # do some cleanup and sanity checking on common prefix
5729420Sandreas.hansson@arm.com            if com_pfx[-1] == ".":
5739420Sandreas.hansson@arm.com                # prefix matches all but file extension: ok
5749420Sandreas.hansson@arm.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
5759420Sandreas.hansson@arm.com                com_pfx = com_pfx[0:-1]
5769420Sandreas.hansson@arm.com            elif com_pfx[-1] == "/":
5779420Sandreas.hansson@arm.com                # common prefix is directory path: OK
5789420Sandreas.hansson@arm.com                pass
5797618SAli.Saidi@arm.com            else:
5807618SAli.Saidi@arm.com                src0_len = len(srcs[0])
5817618SAli.Saidi@arm.com                tgt0_len = len(tgts[0])
5827739Sgblack@eecs.umich.edu                if src0_len == com_pfx_len:
5839227Sandreas.hansson@arm.com                    # source is a substring of target, OK
5849227Sandreas.hansson@arm.com                    pass
5859227Sandreas.hansson@arm.com                elif tgt0_len == com_pfx_len:
5869227Sandreas.hansson@arm.com                    # target is a substring of source, need to back up to
5879227Sandreas.hansson@arm.com                    # avoid empty string on RHS of arrow
5889227Sandreas.hansson@arm.com                    sep_idx = com_pfx.rfind(".")
5899227Sandreas.hansson@arm.com                    if sep_idx != -1:
5909227Sandreas.hansson@arm.com                        com_pfx = com_pfx[0:sep_idx]
5919227Sandreas.hansson@arm.com                    else:
5929227Sandreas.hansson@arm.com                        com_pfx = ''
5939227Sandreas.hansson@arm.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
5949227Sandreas.hansson@arm.com                    # still splitting at file extension: ok
5959227Sandreas.hansson@arm.com                    pass
5969227Sandreas.hansson@arm.com                else:
5979227Sandreas.hansson@arm.com                    # probably a fluke; ignore it
5989227Sandreas.hansson@arm.com                    com_pfx = ''
5999227Sandreas.hansson@arm.com        # recalculate length in case com_pfx was modified
6009227Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
6019590Sandreas@sandberg.pp.se        def fmt(files):
6029590Sandreas@sandberg.pp.se            f = map(lambda s: s[com_pfx_len:], files)
6039590Sandreas@sandberg.pp.se            return ', '.join(f)
6048737Skoansin.tan@gmail.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
6059420Sandreas.hansson@arm.com
6069420Sandreas.hansson@arm.comExport('Transform')
6079420Sandreas.hansson@arm.com
6088737Skoansin.tan@gmail.com# enable the regression script to use the termcap
6098737Skoansin.tan@gmail.commain['TERMCAP'] = termcap
6108737Skoansin.tan@gmail.com
6118737Skoansin.tan@gmail.comif GetOption('verbose'):
6128737Skoansin.tan@gmail.com    def MakeAction(action, string, *args, **kwargs):
6138737Skoansin.tan@gmail.com        return Action(action, *args, **kwargs)
6148737Skoansin.tan@gmail.comelse:
6158737Skoansin.tan@gmail.com    MakeAction = Action
6168737Skoansin.tan@gmail.com    main['CCCOMSTR']        = Transform("CC")
6178737Skoansin.tan@gmail.com    main['CXXCOMSTR']       = Transform("CXX")
6188737Skoansin.tan@gmail.com    main['ASCOMSTR']        = Transform("AS")
6198737Skoansin.tan@gmail.com    main['SWIGCOMSTR']      = Transform("SWIG")
6209556Sandreas.hansson@arm.com    main['ARCOMSTR']        = Transform("AR", 0)
6219556Sandreas.hansson@arm.com    main['LINKCOMSTR']      = Transform("LINK", 0)
6229556Sandreas.hansson@arm.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
6239556Sandreas.hansson@arm.com    main['M4COMSTR']        = Transform("M4")
6249556Sandreas.hansson@arm.com    main['SHCCCOMSTR']      = Transform("SHCC")
6259556Sandreas.hansson@arm.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
6269556Sandreas.hansson@arm.comExport('MakeAction')
6279556Sandreas.hansson@arm.com
6289556Sandreas.hansson@arm.com# Initialize the Link-Time Optimization (LTO) flags
6299556Sandreas.hansson@arm.commain['LTO_CCFLAGS'] = []
6309590Sandreas@sandberg.pp.semain['LTO_LDFLAGS'] = []
6319590Sandreas@sandberg.pp.se
6329420Sandreas.hansson@arm.com# According to the readme, tcmalloc works best if the compiler doesn't
6339846Sandreas.hansson@arm.com# assume that we're using the builtin malloc and friends. These flags
6349846Sandreas.hansson@arm.com# are compiler-specific, so we need to set them after we detect which
6359846Sandreas.hansson@arm.com# compiler we're using.
6369846Sandreas.hansson@arm.commain['TCMALLOC_CCFLAGS'] = []
6378946Sandreas.hansson@arm.com
6383918Ssaidi@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
6399068SAli.Saidi@ARM.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
6409068SAli.Saidi@ARM.com
6419068SAli.Saidi@ARM.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
6429068SAli.Saidi@ARM.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
6439068SAli.Saidi@ARM.comif main['GCC'] + main['CLANG'] > 1:
6449068SAli.Saidi@ARM.com    print 'Error: How can we have two at the same time?'
6459068SAli.Saidi@ARM.com    Exit(1)
6469068SAli.Saidi@ARM.com
6479068SAli.Saidi@ARM.com# Set up default C++ compiler flags
6489419Sandreas.hansson@arm.comif main['GCC'] or main['CLANG']:
6499068SAli.Saidi@ARM.com    # As gcc and clang share many flags, do the common parts here
6509068SAli.Saidi@ARM.com    main.Append(CCFLAGS=['-pipe'])
6519068SAli.Saidi@ARM.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
6529068SAli.Saidi@ARM.com    # Enable -Wall and -Wextra and then disable the few warnings that
6539068SAli.Saidi@ARM.com    # we consistently violate
6549068SAli.Saidi@ARM.com    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
6553918Ssaidi@eecs.umich.edu                         '-Wno-sign-compare', '-Wno-unused-parameter'])
6563918Ssaidi@eecs.umich.edu    # We always compile using C++11
6576157Snate@binkert.org    main.Append(CXXFLAGS=['-std=c++11'])
6586157Snate@binkert.orgelse:
6596157Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6606157Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
6615397Ssaidi@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6625397Ssaidi@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
6636121Snate@binkert.org    if not CXX_version:
6646121Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6656121Snate@binkert.org               termcap.Normal
6666121Snate@binkert.org    else:
6676121Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
6686121Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
6695397Ssaidi@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
6701851SN/A    print "       environment."
6711851SN/A    print "       "
6727739Sgblack@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
673955SN/A    print "       above you will need to ease fix SConstruct and "
6749396Sandreas.hansson@arm.com    print "       src/SConscript to support that compiler."
6759396Sandreas.hansson@arm.com    Exit(1)
6769396Sandreas.hansson@arm.com
6779396Sandreas.hansson@arm.comif main['GCC']:
6789396Sandreas.hansson@arm.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
6799396Sandreas.hansson@arm.com    # level of c++11 support. See
6809396Sandreas.hansson@arm.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
6819396Sandreas.hansson@arm.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
6829396Sandreas.hansson@arm.com    if compareVersions(gcc_version, "4.8") < 0:
6839396Sandreas.hansson@arm.com        print 'Error: gcc version 4.8 or newer required.'
6849396Sandreas.hansson@arm.com        print '       Installed version:', gcc_version
6859396Sandreas.hansson@arm.com        Exit(1)
6869396Sandreas.hansson@arm.com
6879396Sandreas.hansson@arm.com    main['GCC_VERSION'] = gcc_version
6889396Sandreas.hansson@arm.com
6899396Sandreas.hansson@arm.com    # gcc from version 4.8 and above generates "rep; ret" instructions
6909477Sandreas.hansson@arm.com    # to avoid performance penalties on certain AMD chips. Older
6919477Sandreas.hansson@arm.com    # assemblers detect this as an error, "Error: expecting string
6929477Sandreas.hansson@arm.com    # instruction after `rep'"
6939477Sandreas.hansson@arm.com    as_version_raw = readCommand([main['AS'], '-v', '/dev/null'],
6949477Sandreas.hansson@arm.com                                 exception=False).split()
6959477Sandreas.hansson@arm.com
6969477Sandreas.hansson@arm.com    # version strings may contain extra distro-specific
6979477Sandreas.hansson@arm.com    # qualifiers, so play it safe and keep only what comes before
6989477Sandreas.hansson@arm.com    # the first hyphen
6999477Sandreas.hansson@arm.com    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
7009477Sandreas.hansson@arm.com
7019477Sandreas.hansson@arm.com    if not as_version or compareVersions(as_version, "2.23") < 0:
7029477Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + \
7039477Sandreas.hansson@arm.com            'Warning: This combination of gcc and binutils have' + \
7049477Sandreas.hansson@arm.com            ' known incompatibilities.\n' + \
7059477Sandreas.hansson@arm.com            '         If you encounter build problems, please update ' + \
7069477Sandreas.hansson@arm.com            'binutils to 2.23.' + \
7079477Sandreas.hansson@arm.com            termcap.Normal
7089477Sandreas.hansson@arm.com
7099477Sandreas.hansson@arm.com    # Make sure we warn if the user has requested to compile with the
7109477Sandreas.hansson@arm.com    # Undefined Benahvior Sanitizer and this version of gcc does not
7119477Sandreas.hansson@arm.com    # support it.
7129396Sandreas.hansson@arm.com    if GetOption('with_ubsan') and \
7133053Sstever@eecs.umich.edu            compareVersions(gcc_version, '4.9') < 0:
7146121Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
7153053Sstever@eecs.umich.edu            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
7163053Sstever@eecs.umich.edu            termcap.Normal
7173053Sstever@eecs.umich.edu
7183053Sstever@eecs.umich.edu    # Add the appropriate Link-Time Optimization (LTO) flags
7193053Sstever@eecs.umich.edu    # unless LTO is explicitly turned off. Note that these flags
7209072Sandreas.hansson@arm.com    # are only used by the fast target.
7213053Sstever@eecs.umich.edu    if not GetOption('no_lto'):
7224742Sstever@eecs.umich.edu        # Pass the LTO flag when compiling to produce GIMPLE
7234742Sstever@eecs.umich.edu        # output, we merely create the flags here and only append
7243053Sstever@eecs.umich.edu        # them later
7253053Sstever@eecs.umich.edu        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
7263053Sstever@eecs.umich.edu
7278960Ssteve.reinhardt@amd.com        # Use the same amount of jobs for LTO as we are running
7286654Snate@binkert.org        # scons with
7293053Sstever@eecs.umich.edu        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
7303053Sstever@eecs.umich.edu
7313053Sstever@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
7323053Sstever@eecs.umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
7339877Sandreas.hansson@arm.com
7349877Sandreas.hansson@arm.com    # add option to check for undeclared overrides
7359877Sandreas.hansson@arm.com    if compareVersions(gcc_version, "5.0") > 0:
7369877Sandreas.hansson@arm.com        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
7379877Sandreas.hansson@arm.com
7389585Sandreas@sandberg.pp.seelif main['CLANG']:
7399877Sandreas.hansson@arm.com    # Check for a supported version of clang, >= 3.1 is needed to
7409585Sandreas@sandberg.pp.se    # support similar features as gcc 4.8. See
7419877Sandreas.hansson@arm.com    # http://clang.llvm.org/cxx_status.html for details
7429877Sandreas.hansson@arm.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
7439585Sandreas@sandberg.pp.se    clang_version_match = clang_version_re.search(CXX_version)
7442667Sstever@eecs.umich.edu    if (clang_version_match):
7454554Sbinkertn@umich.edu        clang_version = clang_version_match.groups()[0]
7466121Snate@binkert.org        if compareVersions(clang_version, "3.1") < 0:
7472667Sstever@eecs.umich.edu            print 'Error: clang version 3.1 or newer required.'
7484554Sbinkertn@umich.edu            print '       Installed version:', clang_version
7494554Sbinkertn@umich.edu            Exit(1)
7504554Sbinkertn@umich.edu    else:
7516121Snate@binkert.org        print 'Error: Unable to determine clang version.'
7524554Sbinkertn@umich.edu        Exit(1)
7534554Sbinkertn@umich.edu
7544554Sbinkertn@umich.edu    # clang has a few additional warnings that we disable, extraneous
7554781Snate@binkert.org    # parantheses are allowed due to Ruby's printing of the AST,
7564554Sbinkertn@umich.edu    # finally self assignments are allowed as the generated CPU code
7574554Sbinkertn@umich.edu    # is relying on this
7582667Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-parentheses',
7594554Sbinkertn@umich.edu                         '-Wno-self-assign',
7604554Sbinkertn@umich.edu                         # Some versions of libstdc++ (4.8?) seem to
7614554Sbinkertn@umich.edu                         # use struct hash and class hash
7624554Sbinkertn@umich.edu                         # interchangeably.
7632667Sstever@eecs.umich.edu                         '-Wno-mismatched-tags',
7644554Sbinkertn@umich.edu                         ])
7652667Sstever@eecs.umich.edu
7664554Sbinkertn@umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
7676121Snate@binkert.org
7682667Sstever@eecs.umich.edu    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
7695522Snate@binkert.org    # opposed to libstdc++, as the later is dated.
7705522Snate@binkert.org    if sys.platform == "darwin":
7715522Snate@binkert.org        main.Append(CXXFLAGS=['-stdlib=libc++'])
7725522Snate@binkert.org        main.Append(LIBS=['c++'])
7735522Snate@binkert.org
7745522Snate@binkert.orgelse:
7755522Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
7765522Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
7775522Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
7785522Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
7795522Snate@binkert.org    if not CXX_version:
7805522Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
7815522Snate@binkert.org               termcap.Normal
7825522Snate@binkert.org    else:
7835522Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
7845522Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
7855522Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
7865522Snate@binkert.org    print "       environment."
7875522Snate@binkert.org    print "       "
7885522Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
7895522Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
7905522Snate@binkert.org    print "       src/SConscript to support that compiler."
7915522Snate@binkert.org    Exit(1)
7925522Snate@binkert.org
7935522Snate@binkert.org# Set up common yacc/bison flags (needed for Ruby)
7945522Snate@binkert.orgmain['YACCFLAGS'] = '-d'
7952638Sstever@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
7962638Sstever@eecs.umich.edu
7976121Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
7983716Sstever@eecs.umich.edu# extra 'qdo' every time we run scons.
7995522Snate@binkert.orgif main['BATCH']:
8009420Sandreas.hansson@arm.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
8015522Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
8025522Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
8035522Snate@binkert.org    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
8045522Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
8051858SN/A
8065227Ssaidi@eecs.umich.eduif sys.platform == 'cygwin':
8075227Ssaidi@eecs.umich.edu    # cygwin has some header file issues...
8085227Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=["-Wno-uninitialized"])
8095227Ssaidi@eecs.umich.edu
8106654Snate@binkert.org# Check for the protobuf compiler
8116654Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
8127769SAli.Saidi@ARM.com                             exception='').split()
8137769SAli.Saidi@ARM.com
8147769SAli.Saidi@ARM.com# First two words should be "libprotoc x.y.z"
8157769SAli.Saidi@ARM.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
8165227Ssaidi@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
8175227Ssaidi@eecs.umich.edu        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
8185227Ssaidi@eecs.umich.edu        '         Please install protobuf-compiler for tracing support.' + \
8195204Sstever@gmail.com        termcap.Normal
8205204Sstever@gmail.com    main['PROTOC'] = False
8215204Sstever@gmail.comelse:
8225204Sstever@gmail.com    # Based on the availability of the compress stream wrappers,
8235204Sstever@gmail.com    # require 2.1.0
8245204Sstever@gmail.com    min_protoc_version = '2.1.0'
8255204Sstever@gmail.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
8265204Sstever@gmail.com        print termcap.Yellow + termcap.Bold + \
8275204Sstever@gmail.com            'Warning: protoc version', min_protoc_version, \
8285204Sstever@gmail.com            'or newer required.\n' + \
8295204Sstever@gmail.com            '         Installed version:', protoc_version[1], \
8305204Sstever@gmail.com            termcap.Normal
8315204Sstever@gmail.com        main['PROTOC'] = False
8325204Sstever@gmail.com    else:
8335204Sstever@gmail.com        # Attempt to determine the appropriate include path and
8345204Sstever@gmail.com        # library path using pkg-config, that means we also need to
8355204Sstever@gmail.com        # check for pkg-config. Note that it is possible to use
8366121Snate@binkert.org        # protobuf without the involvement of pkg-config. Later on we
8375204Sstever@gmail.com        # check go a library config check and at that point the test
8387727SAli.Saidi@ARM.com        # will fail if libprotobuf cannot be found.
8397727SAli.Saidi@ARM.com        if readCommand(['pkg-config', '--version'], exception=''):
8407727SAli.Saidi@ARM.com            try:
8417727SAli.Saidi@ARM.com                # Attempt to establish what linking flags to add for protobuf
8427727SAli.Saidi@ARM.com                # using pkg-config
8439812Sandreas.hansson@arm.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
8449812Sandreas.hansson@arm.com            except:
8459812Sandreas.hansson@arm.com                print termcap.Yellow + termcap.Bold + \
8469812Sandreas.hansson@arm.com                    'Warning: pkg-config could not get protobuf flags.' + \
8479812Sandreas.hansson@arm.com                    termcap.Normal
8489812Sandreas.hansson@arm.com
8499812Sandreas.hansson@arm.com# Check for SWIG
8509812Sandreas.hansson@arm.comif not main.has_key('SWIG'):
8519812Sandreas.hansson@arm.com    print 'Error: SWIG utility not found.'
8529812Sandreas.hansson@arm.com    print '       Please install (see http://www.swig.org) and retry.'
8539812Sandreas.hansson@arm.com    Exit(1)
8549812Sandreas.hansson@arm.com
8559812Sandreas.hansson@arm.com# Check for appropriate SWIG version
8569812Sandreas.hansson@arm.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
8579812Sandreas.hansson@arm.com# First 3 words should be "SWIG Version x.y.z"
8589812Sandreas.hansson@arm.comif len(swig_version) < 3 or \
8599812Sandreas.hansson@arm.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
8609812Sandreas.hansson@arm.com    print 'Error determining SWIG version.'
8619812Sandreas.hansson@arm.com    Exit(1)
8629812Sandreas.hansson@arm.com
8639812Sandreas.hansson@arm.commin_swig_version = '2.0.4'
8649812Sandreas.hansson@arm.comif compareVersions(swig_version[2], min_swig_version) < 0:
8659812Sandreas.hansson@arm.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
8669812Sandreas.hansson@arm.com    print '       Installed version:', swig_version[2]
8677727SAli.Saidi@ARM.com    Exit(1)
8685863Snate@binkert.org
8693118Sstever@eecs.umich.edu# Check for known incompatibilities. The standard library shipped with
8705863Snate@binkert.org# gcc >= 4.9 does not play well with swig versions prior to 3.0
8719239Sandreas.hansson@arm.comif main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
8723118Sstever@eecs.umich.edu        compareVersions(swig_version[2], '3.0') < 0:
8733118Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
8745863Snate@binkert.org        'Warning: This combination of gcc and swig have' + \
8755863Snate@binkert.org        ' known incompatibilities.\n' + \
8765863Snate@binkert.org        '         If you encounter build problems, please update ' + \
8775863Snate@binkert.org        'swig to 3.0 or later.' + \
8783118Sstever@eecs.umich.edu        termcap.Normal
8793483Ssaidi@eecs.umich.edu
8803494Ssaidi@eecs.umich.edu# Set up SWIG flags & scanner
8813494Ssaidi@eecs.umich.eduswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
8823483Ssaidi@eecs.umich.edumain.Append(SWIGFLAGS=swig_flags)
8833483Ssaidi@eecs.umich.edu
8843483Ssaidi@eecs.umich.edu# Check for 'timeout' from GNU coreutils. If present, regressions will
8853053Sstever@eecs.umich.edu# be run with a time limit. We require version 8.13 since we rely on
8863053Sstever@eecs.umich.edu# support for the '--foreground' option.
8873918Ssaidi@eecs.umich.edutimeout_lines = readCommand(['timeout', '--version'],
8883053Sstever@eecs.umich.edu                            exception='').splitlines()
8893053Sstever@eecs.umich.edu# Get the first line and tokenize it
8903053Sstever@eecs.umich.edutimeout_version = timeout_lines[0].split() if timeout_lines else []
8913053Sstever@eecs.umich.edumain['TIMEOUT'] =  timeout_version and \
8923053Sstever@eecs.umich.edu    compareVersions(timeout_version[-1], '8.13') >= 0
8939396Sandreas.hansson@arm.com
8949396Sandreas.hansson@arm.com# filter out all existing swig scanners, they mess up the dependency
8959396Sandreas.hansson@arm.com# stuff for some reason
8969396Sandreas.hansson@arm.comscanners = []
8979396Sandreas.hansson@arm.comfor scanner in main['SCANNERS']:
8989396Sandreas.hansson@arm.com    skeys = scanner.skeys
8999396Sandreas.hansson@arm.com    if skeys == '.i':
9009396Sandreas.hansson@arm.com        continue
9019396Sandreas.hansson@arm.com
9029477Sandreas.hansson@arm.com    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
9039396Sandreas.hansson@arm.com        continue
9049477Sandreas.hansson@arm.com
9059477Sandreas.hansson@arm.com    scanners.append(scanner)
9069477Sandreas.hansson@arm.com
9079477Sandreas.hansson@arm.com# add the new swig scanner that we like better
9089396Sandreas.hansson@arm.comfrom SCons.Scanner import ClassicCPP as CPPScanner
9097840Snate@binkert.orgswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
9107865Sgblack@eecs.umich.eduscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
9117865Sgblack@eecs.umich.edu
9127865Sgblack@eecs.umich.edu# replace the scanners list that has what we want
9137865Sgblack@eecs.umich.edumain['SCANNERS'] = scanners
9147865Sgblack@eecs.umich.edu
9157840Snate@binkert.org# Add a custom Check function to test for structure members.
9169900Sandreas@sandberg.pp.sedef CheckMember(context, include, decl, member, include_quotes="<>"):
9179900Sandreas@sandberg.pp.se    context.Message("Checking for member %s in %s..." %
9189900Sandreas@sandberg.pp.se                    (member, decl))
9199900Sandreas@sandberg.pp.se    text = """
9209591Sandreas@sandberg.pp.se#include %(header)s
9219591Sandreas@sandberg.pp.seint main(){
9229591Sandreas@sandberg.pp.se  %(decl)s test;
9239590Sandreas@sandberg.pp.se  (void)test.%(member)s;
9249590Sandreas@sandberg.pp.se  return 0;
9259045SAli.Saidi@ARM.com};
9269045SAli.Saidi@ARM.com""" % { "header" : include_quotes[0] + include + include_quotes[1],
9279071Sandreas.hansson@arm.com        "decl" : decl,
9289071Sandreas.hansson@arm.com        "member" : member,
9299045SAli.Saidi@ARM.com        }
9307840Snate@binkert.org
9317840Snate@binkert.org    ret = context.TryCompile(text, extension=".cc")
9327840Snate@binkert.org    context.Result(ret)
9331858SN/A    return ret
9341858SN/A
9351858SN/A# Platform-specific configuration.  Note again that we assume that all
9361858SN/A# builds under a given build root run on the same host platform.
9371858SN/Aconf = Configure(main,
9381858SN/A                 conf_dir = joinpath(build_root, '.scons_config'),
9399651SAndreas.Sandberg@ARM.com                 log_file = joinpath(build_root, 'scons_config.log'),
9409651SAndreas.Sandberg@ARM.com                 custom_tests = {
9419651SAndreas.Sandberg@ARM.com        'CheckMember' : CheckMember,
9429651SAndreas.Sandberg@ARM.com        })
9439651SAndreas.Sandberg@ARM.com
9449651SAndreas.Sandberg@ARM.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
9459651SAndreas.Sandberg@ARM.comtry:
9469651SAndreas.Sandberg@ARM.com    import platform
9479651SAndreas.Sandberg@ARM.com    uname = platform.uname()
9489657Sandreas.sandberg@arm.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
9499883Sandreas@sandberg.pp.se        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
9509651SAndreas.Sandberg@ARM.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
9519651SAndreas.Sandberg@ARM.com            main.Append(CFLAGS=['-arch', 'x86_64'])
9529651SAndreas.Sandberg@ARM.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
9539651SAndreas.Sandberg@ARM.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
9549651SAndreas.Sandberg@ARM.comexcept:
9559651SAndreas.Sandberg@ARM.com    pass
9569651SAndreas.Sandberg@ARM.com
9579651SAndreas.Sandberg@ARM.com# Recent versions of scons substitute a "Null" object for Configure()
9589651SAndreas.Sandberg@ARM.com# when configuration isn't necessary, e.g., if the "--help" option is
9599651SAndreas.Sandberg@ARM.com# present.  Unfortuantely this Null object always returns false,
9609651SAndreas.Sandberg@ARM.com# breaking all our configuration checks.  We replace it with our own
9615863Snate@binkert.org# more optimistic null object that returns True instead.
9625863Snate@binkert.orgif not conf:
9635863Snate@binkert.org    def NullCheck(*args, **kwargs):
9645863Snate@binkert.org        return True
9656121Snate@binkert.org
9661858SN/A    class NullConf:
9675863Snate@binkert.org        def __init__(self, env):
9685863Snate@binkert.org            self.env = env
9695863Snate@binkert.org        def Finish(self):
9705863Snate@binkert.org            return self.env
9715863Snate@binkert.org        def __getattr__(self, mname):
9722139SN/A            return NullCheck
9734202Sbinkertn@umich.edu
9744202Sbinkertn@umich.edu    conf = NullConf(main)
9752139SN/A
9766994Snate@binkert.org# Cache build files in the supplied directory.
9776994Snate@binkert.orgif main['M5_BUILD_CACHE']:
9786994Snate@binkert.org    print 'Using build cache located at', main['M5_BUILD_CACHE']
9796994Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
9806994Snate@binkert.org
9816994Snate@binkert.orgif not GetOption('without_python'):
9826994Snate@binkert.org    # Find Python include and library directories for embedding the
9836994Snate@binkert.org    # interpreter. We rely on python-config to resolve the appropriate
9846994Snate@binkert.org    # includes and linker flags. ParseConfig does not seem to understand
9856994Snate@binkert.org    # the more exotic linker flags such as -Xlinker and -export-dynamic so
9866994Snate@binkert.org    # we add them explicitly below. If you want to link in an alternate
9876994Snate@binkert.org    # version of python, see above for instructions on how to invoke
9886994Snate@binkert.org    # scons with the appropriate PATH set.
9896994Snate@binkert.org    #
9906994Snate@binkert.org    # First we check if python2-config exists, else we use python-config
9916994Snate@binkert.org    python_config = readCommand(['which', 'python2-config'],
9926994Snate@binkert.org                                exception='').strip()
9936994Snate@binkert.org    if not os.path.exists(python_config):
9946994Snate@binkert.org        python_config = readCommand(['which', 'python-config'],
9956994Snate@binkert.org                                    exception='').strip()
9966994Snate@binkert.org    py_includes = readCommand([python_config, '--includes'],
9976994Snate@binkert.org                              exception='').split()
9986994Snate@binkert.org    # Strip the -I from the include folders before adding them to the
9996994Snate@binkert.org    # CPPPATH
10006994Snate@binkert.org    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
10016994Snate@binkert.org
10026994Snate@binkert.org    # Read the linker flags and split them into libraries and other link
10036994Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
10042155SN/A    py_ld_flags = readCommand([python_config, '--ldflags'],
10055863Snate@binkert.org        exception='').split()
10061869SN/A    py_libs = []
10071869SN/A    for lib in py_ld_flags:
10085863Snate@binkert.org         if not lib.startswith('-l'):
10095863Snate@binkert.org             main.Append(LINKFLAGS=[lib])
10104202Sbinkertn@umich.edu         else:
10116108Snate@binkert.org             lib = lib[2:]
10126108Snate@binkert.org             if lib not in py_libs:
10136108Snate@binkert.org                 py_libs.append(lib)
10146108Snate@binkert.org
10159219Spower.jg@gmail.com    # verify that this stuff works
10169219Spower.jg@gmail.com    if not conf.CheckHeader('Python.h', '<>'):
10179219Spower.jg@gmail.com        print "Error: can't find Python.h header in", py_includes
10189219Spower.jg@gmail.com        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
10199219Spower.jg@gmail.com        Exit(1)
10209219Spower.jg@gmail.com
10219219Spower.jg@gmail.com    for lib in py_libs:
10229219Spower.jg@gmail.com        if not conf.CheckLib(lib):
10234202Sbinkertn@umich.edu            print "Error: can't find library %s required by python" % lib
10245863Snate@binkert.org            Exit(1)
10258474Sgblack@eecs.umich.edu
10268474Sgblack@eecs.umich.edu# On Solaris you need to use libsocket for socket ops
10275742Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10288268Ssteve.reinhardt@amd.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10298268Ssteve.reinhardt@amd.com       print "Can't find library with socket calls (e.g. accept())"
10308268Ssteve.reinhardt@amd.com       Exit(1)
10315742Snate@binkert.org
10325341Sstever@gmail.com# Check for zlib.  If the check passes, libz will be automatically
10338474Sgblack@eecs.umich.edu# added to the LIBS environment variable.
10348474Sgblack@eecs.umich.eduif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
10355342Sstever@gmail.com    print 'Error: did not find needed zlib compression library '\
10364202Sbinkertn@umich.edu          'and/or zlib.h header file.'
10374202Sbinkertn@umich.edu    print '       Please install zlib and try again.'
10384202Sbinkertn@umich.edu    Exit(1)
10395863Snate@binkert.org
10405863Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
10416994Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
10426994Snate@binkert.org# automatically added to the LIBS environment variable. After
10436994Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
10445863Snate@binkert.org# got both protoc and libprotobuf available.
10455863Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
10465863Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
10475863Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
10485863Snate@binkert.org
10495863Snate@binkert.org# If we have the compiler but not the library, print another warning.
10505863Snate@binkert.orgif main['PROTOC'] and not main['HAVE_PROTOBUF']:
10515863Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
10527840Snate@binkert.org        'Warning: did not find protocol buffer library and/or headers.\n' + \
10535863Snate@binkert.org    '       Please install libprotobuf-dev for tracing support.' + \
10545952Ssaidi@eecs.umich.edu    termcap.Normal
10559651SAndreas.Sandberg@ARM.com
10569219Spower.jg@gmail.com# Check for librt.
10579219Spower.jg@gmail.comhave_posix_clock = \
10581869SN/A    conf.CheckLibWithHeader(None, 'time.h', 'C',
10591858SN/A                            'clock_nanosleep(0,0,NULL,NULL);') or \
10605863Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
10619420Sandreas.hansson@arm.com                            'clock_nanosleep(0,0,NULL,NULL);')
10629420Sandreas.hansson@arm.com
10631858SN/Ahave_posix_timers = \
1064955SN/A    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
1065955SN/A                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
10661869SN/A
10671869SN/Aif not GetOption('without_tcmalloc'):
10681869SN/A    if conf.CheckLib('tcmalloc'):
10691869SN/A        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
10701869SN/A    elif conf.CheckLib('tcmalloc_minimal'):
10715863Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
10725863Snate@binkert.org    else:
10735863Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
10741869SN/A              "You can get a 12% performance improvement by "\
10755863Snate@binkert.org              "installing tcmalloc (libgoogle-perftools-dev package "\
10761869SN/A              "on Ubuntu or RedHat)." + termcap.Normal
10775863Snate@binkert.org
10781869SN/A
10791869SN/A# Detect back trace implementations. The last implementation in the
10801869SN/A# list will be used by default.
10811869SN/Abacktrace_impls = [ "none" ]
10828483Sgblack@eecs.umich.edu
10831869SN/Aif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
10841869SN/A                           'backtrace_symbols_fd((void*)0, 0, 0);'):
10851869SN/A    backtrace_impls.append("glibc")
10861869SN/A
10875863Snate@binkert.orgif backtrace_impls[-1] == "none":
10885863Snate@binkert.org    default_backtrace_impl = "none"
10891869SN/A    print termcap.Yellow + termcap.Bold + \
10905863Snate@binkert.org        "No suitable back trace implementation found." + \
10915863Snate@binkert.org        termcap.Normal
10923356Sbinkertn@umich.edu
10933356Sbinkertn@umich.eduif not have_posix_clock:
10943356Sbinkertn@umich.edu    print "Can't find library for POSIX clocks."
10953356Sbinkertn@umich.edu
10963356Sbinkertn@umich.edu# Check for <fenv.h> (C99 FP environment control)
10974781Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
10985863Snate@binkert.orgif not have_fenv:
10995863Snate@binkert.org    print "Warning: Header file <fenv.h> not found."
11001869SN/A    print "         This host has no IEEE FP rounding mode control."
11011869SN/A
11021869SN/A# Check if we should enable KVM-based hardware virtualization. The API
11036121Snate@binkert.org# we rely on exists since version 2.6.36 of the kernel, but somehow
11041869SN/A# the KVM_API_VERSION does not reflect the change. We test for one of
11052638Sstever@eecs.umich.edu# the types as a fall back.
11066121Snate@binkert.orghave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
11076121Snate@binkert.orgif not have_kvm:
11082638Sstever@eecs.umich.edu    print "Info: Compatible header file <linux/kvm.h> not found, " \
11095749Scws3k@cs.virginia.edu        "disabling KVM support."
11106121Snate@binkert.org
11116121Snate@binkert.org# x86 needs support for xsave. We test for the structure here since we
11125749Scws3k@cs.virginia.edu# won't be able to run new tests by the time we know which ISA we're
11139537Satgutier@umich.edu# targeting.
11149537Satgutier@umich.eduhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
11159537Satgutier@umich.edu                                    '#include <linux/kvm.h>') != 0
11169537Satgutier@umich.edu
11179888Sandreas@sandberg.pp.se# Check if the requested target ISA is compatible with the host
11189888Sandreas@sandberg.pp.sedef is_isa_kvm_compatible(isa):
11199888Sandreas@sandberg.pp.se    try:
11209888Sandreas@sandberg.pp.se        import platform
11211869SN/A        host_isa = platform.machine()
11221869SN/A    except:
11233546Sgblack@eecs.umich.edu        print "Warning: Failed to determine host ISA."
11243546Sgblack@eecs.umich.edu        return False
11253546Sgblack@eecs.umich.edu
11263546Sgblack@eecs.umich.edu    if not have_posix_timers:
11276121Snate@binkert.org        print "Warning: Can not enable KVM, host seems to lack support " \
11285863Snate@binkert.org            "for POSIX timers"
11293546Sgblack@eecs.umich.edu        return False
11303546Sgblack@eecs.umich.edu
11313546Sgblack@eecs.umich.edu    if isa == "arm":
11323546Sgblack@eecs.umich.edu        return host_isa in ( "armv7l", "aarch64" )
11334781Snate@binkert.org    elif isa == "x86":
11344781Snate@binkert.org        if host_isa != "x86_64":
11356658Snate@binkert.org            return False
11366658Snate@binkert.org
11374781Snate@binkert.org        if not have_kvm_xsave:
11383546Sgblack@eecs.umich.edu            print "KVM on x86 requires xsave support in kernel headers."
11393546Sgblack@eecs.umich.edu            return False
11403546Sgblack@eecs.umich.edu
11413546Sgblack@eecs.umich.edu        return True
11427756SAli.Saidi@ARM.com    else:
11437816Ssteve.reinhardt@amd.com        return False
11443546Sgblack@eecs.umich.edu
11453546Sgblack@eecs.umich.edu
11463546Sgblack@eecs.umich.edu# Check if the exclude_host attribute is available. We want this to
11473546Sgblack@eecs.umich.edu# get accurate instruction counts in KVM.
11484202Sbinkertn@umich.edumain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
11493546Sgblack@eecs.umich.edu    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
11503546Sgblack@eecs.umich.edu
11513546Sgblack@eecs.umich.edu
1152955SN/A######################################################################
1153955SN/A#
1154955SN/A# Finish the configuration
1155955SN/A#
11565863Snate@binkert.orgmain = conf.Finish()
11575863Snate@binkert.org
11585343Sstever@gmail.com######################################################################
11595343Sstever@gmail.com#
11606121Snate@binkert.org# Collect all non-global variables
11615863Snate@binkert.org#
11624773Snate@binkert.org
11635863Snate@binkert.org# Define the universe of supported ISAs
11642632Sstever@eecs.umich.eduall_isa_list = [ ]
11655863Snate@binkert.orgall_gpu_isa_list = [ ]
11662023SN/AExport('all_isa_list')
11675863Snate@binkert.orgExport('all_gpu_isa_list')
11685863Snate@binkert.org
11695863Snate@binkert.orgclass CpuModel(object):
11705863Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
11715863Snate@binkert.org    know about a particular CPU model.'''
11725863Snate@binkert.org
11735863Snate@binkert.org    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
11745863Snate@binkert.org    dict = {}
11755863Snate@binkert.org
11762632Sstever@eecs.umich.edu    # Constructor.  Automatically adds models to CpuModel.dict.
11775863Snate@binkert.org    def __init__(self, name, default=False):
11782023SN/A        self.name = name           # name of model
11792632Sstever@eecs.umich.edu
11805863Snate@binkert.org        # This cpu is enabled by default
11815342Sstever@gmail.com        self.default = default
11825863Snate@binkert.org
11832632Sstever@eecs.umich.edu        # Add self to dict
11845863Snate@binkert.org        if name in CpuModel.dict:
11855863Snate@binkert.org            raise AttributeError, "CpuModel '%s' already registered" % name
11868267Ssteve.reinhardt@amd.com        CpuModel.dict[name] = self
11878120Sgblack@eecs.umich.edu
11888267Ssteve.reinhardt@amd.comExport('CpuModel')
11898267Ssteve.reinhardt@amd.com
11908267Ssteve.reinhardt@amd.com# Sticky variables get saved in the variables file so they persist from
11918267Ssteve.reinhardt@amd.com# one invocation to the next (unless overridden, in which case the new
11928267Ssteve.reinhardt@amd.com# value becomes sticky).
11938267Ssteve.reinhardt@amd.comsticky_vars = Variables(args=ARGUMENTS)
11948267Ssteve.reinhardt@amd.comExport('sticky_vars')
11958267Ssteve.reinhardt@amd.com
11968267Ssteve.reinhardt@amd.com# Sticky variables that should be exported
11975863Snate@binkert.orgexport_vars = []
11985863Snate@binkert.orgExport('export_vars')
11995863Snate@binkert.org
12002632Sstever@eecs.umich.edu# For Ruby
12018267Ssteve.reinhardt@amd.comall_protocols = []
12028267Ssteve.reinhardt@amd.comExport('all_protocols')
12038267Ssteve.reinhardt@amd.comprotocol_dirs = []
12042632Sstever@eecs.umich.eduExport('protocol_dirs')
12051888SN/Aslicc_includes = []
12065863Snate@binkert.orgExport('slicc_includes')
12075863Snate@binkert.org
12081858SN/A# Walk the tree and execute all SConsopts scripts that wil add to the
12098120Sgblack@eecs.umich.edu# above variables
12108120Sgblack@eecs.umich.eduif GetOption('verbose'):
12117756SAli.Saidi@ARM.com    print "Reading SConsopts"
12122598SN/Afor bdir in [ base_dir ] + extras_dir_list:
12135863Snate@binkert.org    if not isdir(bdir):
12141858SN/A        print "Error: directory '%s' does not exist" % bdir
12151858SN/A        Exit(1)
12161858SN/A    for root, dirs, files in os.walk(bdir):
12175863Snate@binkert.org        if 'SConsopts' in files:
12181858SN/A            if GetOption('verbose'):
12191858SN/A                print "Reading", joinpath(root, 'SConsopts')
12201858SN/A            SConscript(joinpath(root, 'SConsopts'))
12215863Snate@binkert.org
12221871SN/Aall_isa_list.sort()
12231858SN/Aall_gpu_isa_list.sort()
12241858SN/A
12251858SN/Asticky_vars.AddVariables(
12261858SN/A    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
12279651SAndreas.Sandberg@ARM.com    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
12289651SAndreas.Sandberg@ARM.com    ListVariable('CPU_MODELS', 'CPU models',
12299651SAndreas.Sandberg@ARM.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
12309651SAndreas.Sandberg@ARM.com                 sorted(CpuModel.dict.keys())),
12319900Sandreas@sandberg.pp.se    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
12329900Sandreas@sandberg.pp.se                 False),
12339900Sandreas@sandberg.pp.se    BoolVariable('SS_COMPATIBLE_FP',
12349900Sandreas@sandberg.pp.se                 'Make floating-point results compatible with SimpleScalar',
12359651SAndreas.Sandberg@ARM.com                 False),
12369651SAndreas.Sandberg@ARM.com    BoolVariable('USE_SSE2',
12379651SAndreas.Sandberg@ARM.com                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
12389651SAndreas.Sandberg@ARM.com                 False),
12399651SAndreas.Sandberg@ARM.com    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
12405863Snate@binkert.org    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
12415863Snate@binkert.org    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
12421869SN/A    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
12431965SN/A    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
12447739Sgblack@eecs.umich.edu    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
12451965SN/A                  all_protocols),
12462761Sstever@eecs.umich.edu    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
12475863Snate@binkert.org                 backtrace_impls[-1], backtrace_impls)
12481869SN/A    )
12495863Snate@binkert.org
12502667Sstever@eecs.umich.edu# These variables get exported to #defines in config/*.hh (see src/SConscript).
12511869SN/Aexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
12521869SN/A                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL',
12532929Sktlim@umich.edu                'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
12542929Sktlim@umich.edu
12555863Snate@binkert.org###################################################
12562929Sktlim@umich.edu#
1257955SN/A# Define a SCons builder for configuration flag headers.
12588120Sgblack@eecs.umich.edu#
12598120Sgblack@eecs.umich.edu###################################################
12608120Sgblack@eecs.umich.edu
12618120Sgblack@eecs.umich.edu# This function generates a config header file that #defines the
12628120Sgblack@eecs.umich.edu# variable symbol to the current variable setting (0 or 1).  The source
12638120Sgblack@eecs.umich.edu# operands are the name of the variable and a Value node containing the
12648120Sgblack@eecs.umich.edu# value of the variable.
12658120Sgblack@eecs.umich.edudef build_config_file(target, source, env):
12668120Sgblack@eecs.umich.edu    (variable, value) = [s.get_contents() for s in source]
12678120Sgblack@eecs.umich.edu    f = file(str(target[0]), 'w')
12688120Sgblack@eecs.umich.edu    print >> f, '#define', variable, value
12698120Sgblack@eecs.umich.edu    f.close()
1270    return None
1271
1272# Combine the two functions into a scons Action object.
1273config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1274
1275# The emitter munges the source & target node lists to reflect what
1276# we're really doing.
1277def config_emitter(target, source, env):
1278    # extract variable name from Builder arg
1279    variable = str(target[0])
1280    # True target is config header file
1281    target = joinpath('config', variable.lower() + '.hh')
1282    val = env[variable]
1283    if isinstance(val, bool):
1284        # Force value to 0/1
1285        val = int(val)
1286    elif isinstance(val, str):
1287        val = '"' + val + '"'
1288
1289    # Sources are variable name & value (packaged in SCons Value nodes)
1290    return ([target], [Value(variable), Value(val)])
1291
1292config_builder = Builder(emitter = config_emitter, action = config_action)
1293
1294main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1295
1296# libelf build is shared across all configs in the build root.
1297main.SConscript('ext/libelf/SConscript',
1298                variant_dir = joinpath(build_root, 'libelf'))
1299
1300# iostream3 build is shared across all configs in the build root.
1301main.SConscript('ext/iostream3/SConscript',
1302                variant_dir = joinpath(build_root, 'iostream3'))
1303
1304# libfdt build is shared across all configs in the build root.
1305main.SConscript('ext/libfdt/SConscript',
1306                variant_dir = joinpath(build_root, 'libfdt'))
1307
1308# fputils build is shared across all configs in the build root.
1309main.SConscript('ext/fputils/SConscript',
1310                variant_dir = joinpath(build_root, 'fputils'))
1311
1312# DRAMSim2 build is shared across all configs in the build root.
1313main.SConscript('ext/dramsim2/SConscript',
1314                variant_dir = joinpath(build_root, 'dramsim2'))
1315
1316# DRAMPower build is shared across all configs in the build root.
1317main.SConscript('ext/drampower/SConscript',
1318                variant_dir = joinpath(build_root, 'drampower'))
1319
1320# nomali build is shared across all configs in the build root.
1321main.SConscript('ext/nomali/SConscript',
1322                variant_dir = joinpath(build_root, 'nomali'))
1323
1324###################################################
1325#
1326# This function is used to set up a directory with switching headers
1327#
1328###################################################
1329
1330main['ALL_ISA_LIST'] = all_isa_list
1331main['ALL_GPU_ISA_LIST'] = all_gpu_isa_list
1332all_isa_deps = {}
1333def make_switching_dir(dname, switch_headers, env):
1334    # Generate the header.  target[0] is the full path of the output
1335    # header to generate.  'source' is a dummy variable, since we get the
1336    # list of ISAs from env['ALL_ISA_LIST'].
1337    def gen_switch_hdr(target, source, env):
1338        fname = str(target[0])
1339        isa = env['TARGET_ISA'].lower()
1340        try:
1341            f = open(fname, 'w')
1342            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1343            f.close()
1344        except IOError:
1345            print "Failed to create %s" % fname
1346            raise
1347
1348    # Build SCons Action object. 'varlist' specifies env vars that this
1349    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1350    # should get re-executed.
1351    switch_hdr_action = MakeAction(gen_switch_hdr,
1352                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1353
1354    # Instantiate actions for each header
1355    for hdr in switch_headers:
1356        env.Command(hdr, [], switch_hdr_action)
1357
1358    isa_target = Dir('.').up().name.lower().replace('_', '-')
1359    env['PHONY_BASE'] = '#'+isa_target
1360    all_isa_deps[isa_target] = None
1361
1362Export('make_switching_dir')
1363
1364def make_gpu_switching_dir(dname, switch_headers, env):
1365    # Generate the header.  target[0] is the full path of the output
1366    # header to generate.  'source' is a dummy variable, since we get the
1367    # list of ISAs from env['ALL_ISA_LIST'].
1368    def gen_switch_hdr(target, source, env):
1369        fname = str(target[0])
1370
1371        isa = env['TARGET_GPU_ISA'].lower()
1372
1373        try:
1374            f = open(fname, 'w')
1375            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1376            f.close()
1377        except IOError:
1378            print "Failed to create %s" % fname
1379            raise
1380
1381    # Build SCons Action object. 'varlist' specifies env vars that this
1382    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1383    # should get re-executed.
1384    switch_hdr_action = MakeAction(gen_switch_hdr,
1385                          Transform("GENERATE"), varlist=['ALL_ISA_GPU_LIST'])
1386
1387    # Instantiate actions for each header
1388    for hdr in switch_headers:
1389        env.Command(hdr, [], switch_hdr_action)
1390
1391Export('make_gpu_switching_dir')
1392
1393# all-isas -> all-deps -> all-environs -> all_targets
1394main.Alias('#all-isas', [])
1395main.Alias('#all-deps', '#all-isas')
1396
1397# Dummy target to ensure all environments are created before telling
1398# SCons what to actually make (the command line arguments).  We attach
1399# them to the dependence graph after the environments are complete.
1400ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1401def environsComplete(target, source, env):
1402    for t in ORIG_BUILD_TARGETS:
1403        main.Depends('#all-targets', t)
1404
1405# Each build/* switching_dir attaches its *-environs target to #all-environs.
1406main.Append(BUILDERS = {'CompleteEnvirons' :
1407                        Builder(action=MakeAction(environsComplete, None))})
1408main.CompleteEnvirons('#all-environs', [])
1409
1410def doNothing(**ignored): pass
1411main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1412
1413# The final target to which all the original targets ultimately get attached.
1414main.Dummy('#all-targets', '#all-environs')
1415BUILD_TARGETS[:] = ['#all-targets']
1416
1417###################################################
1418#
1419# Define build environments for selected configurations.
1420#
1421###################################################
1422
1423for variant_path in variant_paths:
1424    if not GetOption('silent'):
1425        print "Building in", variant_path
1426
1427    # Make a copy of the build-root environment to use for this config.
1428    env = main.Clone()
1429    env['BUILDDIR'] = variant_path
1430
1431    # variant_dir is the tail component of build path, and is used to
1432    # determine the build parameters (e.g., 'ALPHA_SE')
1433    (build_root, variant_dir) = splitpath(variant_path)
1434
1435    # Set env variables according to the build directory config.
1436    sticky_vars.files = []
1437    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1438    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1439    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1440    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1441    if isfile(current_vars_file):
1442        sticky_vars.files.append(current_vars_file)
1443        if not GetOption('silent'):
1444            print "Using saved variables file %s" % current_vars_file
1445    else:
1446        # Build dir-specific variables file doesn't exist.
1447
1448        # Make sure the directory is there so we can create it later
1449        opt_dir = dirname(current_vars_file)
1450        if not isdir(opt_dir):
1451            mkdir(opt_dir)
1452
1453        # Get default build variables from source tree.  Variables are
1454        # normally determined by name of $VARIANT_DIR, but can be
1455        # overridden by '--default=' arg on command line.
1456        default = GetOption('default')
1457        opts_dir = joinpath(main.root.abspath, 'build_opts')
1458        if default:
1459            default_vars_files = [joinpath(build_root, 'variables', default),
1460                                  joinpath(opts_dir, default)]
1461        else:
1462            default_vars_files = [joinpath(opts_dir, variant_dir)]
1463        existing_files = filter(isfile, default_vars_files)
1464        if existing_files:
1465            default_vars_file = existing_files[0]
1466            sticky_vars.files.append(default_vars_file)
1467            print "Variables file %s not found,\n  using defaults in %s" \
1468                  % (current_vars_file, default_vars_file)
1469        else:
1470            print "Error: cannot find variables file %s or " \
1471                  "default file(s) %s" \
1472                  % (current_vars_file, ' or '.join(default_vars_files))
1473            Exit(1)
1474
1475    # Apply current variable settings to env
1476    sticky_vars.Update(env)
1477
1478    help_texts["local_vars"] += \
1479        "Build variables for %s:\n" % variant_dir \
1480                 + sticky_vars.GenerateHelpText(env)
1481
1482    # Process variable settings.
1483
1484    if not have_fenv and env['USE_FENV']:
1485        print "Warning: <fenv.h> not available; " \
1486              "forcing USE_FENV to False in", variant_dir + "."
1487        env['USE_FENV'] = False
1488
1489    if not env['USE_FENV']:
1490        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1491        print "         FP results may deviate slightly from other platforms."
1492
1493    if env['EFENCE']:
1494        env.Append(LIBS=['efence'])
1495
1496    if env['USE_KVM']:
1497        if not have_kvm:
1498            print "Warning: Can not enable KVM, host seems to lack KVM support"
1499            env['USE_KVM'] = False
1500        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1501            print "Info: KVM support disabled due to unsupported host and " \
1502                "target ISA combination"
1503            env['USE_KVM'] = False
1504
1505    # Warn about missing optional functionality
1506    if env['USE_KVM']:
1507        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1508            print "Warning: perf_event headers lack support for the " \
1509                "exclude_host attribute. KVM instruction counts will " \
1510                "be inaccurate."
1511
1512    # Save sticky variable settings back to current variables file
1513    sticky_vars.Save(current_vars_file, env)
1514
1515    if env['USE_SSE2']:
1516        env.Append(CCFLAGS=['-msse2'])
1517
1518    # The src/SConscript file sets up the build rules in 'env' according
1519    # to the configured variables.  It returns a list of environments,
1520    # one for each variant build (debug, opt, etc.)
1521    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1522
1523def pairwise(iterable):
1524    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1525    a, b = itertools.tee(iterable)
1526    b.next()
1527    return itertools.izip(a, b)
1528
1529# Create false dependencies so SCons will parse ISAs, establish
1530# dependencies, and setup the build Environments serially. Either
1531# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1532# greater than 1. It appears to be standard race condition stuff; it
1533# doesn't always fail, but usually, and the behaviors are different.
1534# Every time I tried to remove this, builds would fail in some
1535# creative new way. So, don't do that. You'll want to, though, because
1536# tests/SConscript takes a long time to make its Environments.
1537for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1538    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1539    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1540
1541# base help text
1542Help('''
1543Usage: scons [scons options] [build variables] [target(s)]
1544
1545Extra scons options:
1546%(options)s
1547
1548Global build variables:
1549%(global_vars)s
1550
1551%(local_vars)s
1552''' % help_texts)
1553