SConstruct revision 11927
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')
1939926Sstan.czerniawski@arm.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1949926Sstan.czerniawski@arm.com               action='store_true',
1959119Sandreas.hansson@arm.com               help='Disable linking against tcmalloc')
1969396Sandreas.hansson@arm.comAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1979926Sstan.czerniawski@arm.com               help='Build with Undefined Behavior Sanitizer if available')
198955SN/AAddLocalOption('--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########################################################################
2049416SAndreas.Sandberg@ARM.com#
2059416SAndreas.Sandberg@ARM.com# Set up the main build environment.
2065871Snate@binkert.org#
2075871Snate@binkert.org########################################################################
2089416SAndreas.Sandberg@ARM.com
2099416SAndreas.Sandberg@ARM.com# export TERM so that clang reports errors in color
2105871Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
211955SN/A                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2126121Snate@binkert.org                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
2138881Smarc.orr@gmail.com
2146121Snate@binkert.orguse_prefixes = [
2156121Snate@binkert.org    "ASAN_",           # address sanitizer symbolizer path and settings
2161533SN/A    "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]):
2279239Sandreas.hansson@arm.com        use_env[key] = val
2289239Sandreas.hansson@arm.com
2296655Snate@binkert.org# Tell scons to avoid implicit command dependencies to avoid issues
2306655Snate@binkert.org# with the param wrappes being compiled twice (see
2316655Snate@binkert.org# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2326655Snate@binkert.orgmain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2335871Snate@binkert.orgmain.Decider('MD5-timestamp')
2345871Snate@binkert.orgmain.root = Dir(".")         # The current directory (where this file lives).
2355863Snate@binkert.orgmain.srcdir = Dir("src")     # The source directory
2365871Snate@binkert.org
2378878Ssteve.reinhardt@amd.commain_dict_keys = main.Dictionary().keys()
2385871Snate@binkert.org
2395871Snate@binkert.org# Check that we have a C/C++ compiler
2405871Snate@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)"
2426121Snate@binkert.org    Exit(1)
2435863Snate@binkert.org
2445871Snate@binkert.org# 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)"
2478336Ssteve.reinhardt@amd.com    Exit(1)
2488336Ssteve.reinhardt@amd.com
2494678Snate@binkert.org# add useful python code PYTHONPATH so it can be used by subprocesses
2508336Ssteve.reinhardt@amd.com# as well
2518336Ssteve.reinhardt@amd.commain.AppendENVPath('PYTHONPATH', extra_python_paths)
2528336Ssteve.reinhardt@amd.com
2534678Snate@binkert.org########################################################################
2544678Snate@binkert.org#
2554678Snate@binkert.org# Mercurial Stuff.
2564678Snate@binkert.org#
2577827Snate@binkert.org# If the gem5 directory is a mercurial repository, we should do some
2587827Snate@binkert.org# extra things.
2598336Ssteve.reinhardt@amd.com#
2604678Snate@binkert.org########################################################################
2618336Ssteve.reinhardt@amd.com
2628336Ssteve.reinhardt@amd.comhgdir = main.root.Dir(".hg")
2638336Ssteve.reinhardt@amd.com
2648336Ssteve.reinhardt@amd.com
2658336Ssteve.reinhardt@amd.comstyle_message = """
2668336Ssteve.reinhardt@amd.comYou're missing the gem5 style hook, which automatically checks your code
2675871Snate@binkert.orgagainst the gem5 style rules on %s.
2685871Snate@binkert.orgThis 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 = """
2728336Ssteve.reinhardt@amd.comYou're missing the gem5 style hook, which automatically checks your code
2738336Ssteve.reinhardt@amd.comagainst the gem5 style rules on hg commit and qrefresh commands.
2745871Snate@binkert.orgThis script will now install the hook in your .hg/hgrc file.
2758336Ssteve.reinhardt@amd.comPress enter to continue, or ctrl-c to abort: """
2768336Ssteve.reinhardt@amd.com
2778336Ssteve.reinhardt@amd.comgit_style_message = """
2788336Ssteve.reinhardt@amd.comYou're missing the gem5 style or commit message hook. These hooks help
2798336Ssteve.reinhardt@amd.comto ensure that your code follows gem5's style rules on git commit.
2804678Snate@binkert.orgThis script will now install the hook in your .git/hooks/ directory.
2815871Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
2824678Snate@binkert.org
2838336Ssteve.reinhardt@amd.commercurial_style_upgrade_message = """
2848336Ssteve.reinhardt@amd.comYour Mercurial style hooks are not up-to-date. This script will now
2858336Ssteve.reinhardt@amd.comtry to automatically update them. A backup of your hgrc will be saved
2868336Ssteve.reinhardt@amd.comin .hg/hgrc.old.
2878336Ssteve.reinhardt@amd.comPress enter to continue, or ctrl-c to abort: """
2888336Ssteve.reinhardt@amd.com
2898336Ssteve.reinhardt@amd.commercurial_style_hook = """
2908336Ssteve.reinhardt@amd.com# The following lines were automatically added by gem5/SConstruct
2918336Ssteve.reinhardt@amd.com# to provide the gem5 style-checking hooks
2928336Ssteve.reinhardt@amd.com[extensions]
2938336Ssteve.reinhardt@amd.comhgstyle = %s/util/hgstyle.py
2948336Ssteve.reinhardt@amd.com
2958336Ssteve.reinhardt@amd.com[hooks]
2968336Ssteve.reinhardt@amd.compretxncommit.style = python:hgstyle.check_style
2978336Ssteve.reinhardt@amd.compre-qrefresh.style = python:hgstyle.check_style
2988336Ssteve.reinhardt@amd.com# End of SConstruct additions
2998336Ssteve.reinhardt@amd.com
3005871Snate@binkert.org""" % (main.root.abspath)
3016121Snate@binkert.org
302955SN/Amercurial_lib_not_found = """
303955SN/AMercurial libraries cannot be found, ignoring style hook.  If
3042632Sstever@eecs.umich.eduyou are a gem5 developer, please fix this and run the style
3052632Sstever@eecs.umich.eduhook. It is important.
306955SN/A"""
307955SN/A
308955SN/A# Check for style hook and prompt for installation if it's not there.
309955SN/A# Skip this if --ignore-style was specified, there's no interactive
3108878Ssteve.reinhardt@amd.com# terminal to prompt, or no recognized revision control system can be
311955SN/A# found.
3122632Sstever@eecs.umich.eduignore_style = GetOption('ignore_style') or not sys.stdin.isatty()
3132632Sstever@eecs.umich.edu
3142632Sstever@eecs.umich.edu# Try wire up Mercurial to the style hooks
3152632Sstever@eecs.umich.eduif not ignore_style and hgdir.exists():
3162632Sstever@eecs.umich.edu    style_hook = True
3172632Sstever@eecs.umich.edu    style_hooks = tuple()
3182632Sstever@eecs.umich.edu    hgrc = hgdir.File('hgrc')
3198268Ssteve.reinhardt@amd.com    hgrc_old = hgdir.File('hgrc.old')
3208268Ssteve.reinhardt@amd.com    try:
3218268Ssteve.reinhardt@amd.com        from mercurial import ui
3228268Ssteve.reinhardt@amd.com        ui = ui.ui()
3238268Ssteve.reinhardt@amd.com        ui.readconfig(hgrc.abspath)
3248268Ssteve.reinhardt@amd.com        style_hooks = (ui.config('hooks', 'pretxncommit.style', None),
3258268Ssteve.reinhardt@amd.com                       ui.config('hooks', 'pre-qrefresh.style', None))
3262632Sstever@eecs.umich.edu        style_hook = all(style_hooks)
3272632Sstever@eecs.umich.edu        style_extension = ui.config('extensions', 'style', None)
3282632Sstever@eecs.umich.edu    except ImportError:
3292632Sstever@eecs.umich.edu        print mercurial_lib_not_found
3308268Ssteve.reinhardt@amd.com
3312632Sstever@eecs.umich.edu    if "python:style.check_style" in style_hooks:
3328268Ssteve.reinhardt@amd.com        # Try to upgrade the style hooks
3338268Ssteve.reinhardt@amd.com        print mercurial_style_upgrade_message
3348268Ssteve.reinhardt@amd.com        # continue unless user does ctrl-c/ctrl-d etc.
3358268Ssteve.reinhardt@amd.com        try:
3363718Sstever@eecs.umich.edu            raw_input()
3372634Sstever@eecs.umich.edu        except:
3382634Sstever@eecs.umich.edu            print "Input exception, exiting scons.\n"
3395863Snate@binkert.org            sys.exit(1)
3402638Sstever@eecs.umich.edu        shutil.copyfile(hgrc.abspath, hgrc_old.abspath)
3418268Ssteve.reinhardt@amd.com        re_style_hook = re.compile(r"^([^=#]+)\.style\s*=\s*([^#\s]+).*")
3422632Sstever@eecs.umich.edu        re_style_extension = re.compile("style\s*=\s*([^#\s]+).*")
3432632Sstever@eecs.umich.edu        old, new = open(hgrc_old.abspath, 'r'), open(hgrc.abspath, 'w')
3442632Sstever@eecs.umich.edu        for l in old:
3452632Sstever@eecs.umich.edu            m_hook = re_style_hook.match(l)
3462632Sstever@eecs.umich.edu            m_ext = re_style_extension.match(l)
3471858SN/A            if m_hook:
3483716Sstever@eecs.umich.edu                hook, check = m_hook.groups()
3492638Sstever@eecs.umich.edu                if check != "python:style.check_style":
3502638Sstever@eecs.umich.edu                    print "Warning: %s.style is using a non-default " \
3512638Sstever@eecs.umich.edu                        "checker: %s" % (hook, check)
3522638Sstever@eecs.umich.edu                if hook not in ("pretxncommit", "pre-qrefresh"):
3532638Sstever@eecs.umich.edu                    print "Warning: Updating unknown style hook: %s" % hook
3542638Sstever@eecs.umich.edu
3552638Sstever@eecs.umich.edu                l = "%s.style = python:hgstyle.check_style\n" % hook
3565863Snate@binkert.org            elif m_ext and m_ext.group(1) == style_extension:
3575863Snate@binkert.org                l = "hgstyle = %s/util/hgstyle.py\n" % main.root.abspath
3585863Snate@binkert.org
359955SN/A            new.write(l)
3605341Sstever@gmail.com    elif not style_hook:
3615341Sstever@gmail.com        print mercurial_style_message,
3625863Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
3637756SAli.Saidi@ARM.com        try:
3645341Sstever@gmail.com            raw_input()
3656121Snate@binkert.org        except:
3664494Ssaidi@eecs.umich.edu            print "Input exception, exiting scons.\n"
3676121Snate@binkert.org            sys.exit(1)
3681105SN/A        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3692667Sstever@eecs.umich.edu        print "Adding style hook to", hgrc_path, "\n"
3702667Sstever@eecs.umich.edu        try:
3712667Sstever@eecs.umich.edu            with open(hgrc_path, 'a') as f:
3722667Sstever@eecs.umich.edu                f.write(mercurial_style_hook)
3736121Snate@binkert.org        except:
3742667Sstever@eecs.umich.edu            print "Error updating", hgrc_path
3755341Sstever@gmail.com            sys.exit(1)
3765863Snate@binkert.org
3775341Sstever@gmail.comdef install_git_style_hooks():
3785341Sstever@gmail.com    try:
3795341Sstever@gmail.com        gitdir = Dir(readCommand(
3808120Sgblack@eecs.umich.edu            ["git", "rev-parse", "--git-dir"]).strip("\n"))
3815341Sstever@gmail.com    except Exception, e:
3828120Sgblack@eecs.umich.edu        print "Warning: Failed to find git repo directory: %s" % e
3835341Sstever@gmail.com        return
3848120Sgblack@eecs.umich.edu
3856121Snate@binkert.org    git_hooks = gitdir.Dir("hooks")
3866121Snate@binkert.org    def hook_exists(hook_name):
3878980Ssteve.reinhardt@amd.com        hook = git_hooks.File(hook_name)
3889396Sandreas.hansson@arm.com        return hook.exists()
3895397Ssaidi@eecs.umich.edu
3905397Ssaidi@eecs.umich.edu    def hook_install(hook_name, script):
3917727SAli.Saidi@ARM.com        hook = git_hooks.File(hook_name)
3928268Ssteve.reinhardt@amd.com        if hook.exists():
3936168Snate@binkert.org            print "Warning: Can't install %s, hook already exists." % hook_name
3945341Sstever@gmail.com            return
3958120Sgblack@eecs.umich.edu
3968120Sgblack@eecs.umich.edu        if hook.islink():
3978120Sgblack@eecs.umich.edu            print "Warning: Removing broken symlink for hook %s." % hook_name
3986814Sgblack@eecs.umich.edu            os.unlink(hook.get_abspath())
3995863Snate@binkert.org
4008120Sgblack@eecs.umich.edu        if not git_hooks.exists():
4015341Sstever@gmail.com            mkdir(git_hooks.get_abspath())
4025863Snate@binkert.org
4038268Ssteve.reinhardt@amd.com        abs_symlink_hooks = git_hooks.islink() and \
4046121Snate@binkert.org            os.path.isabs(os.readlink(git_hooks.get_abspath()))
4056121Snate@binkert.org
4068268Ssteve.reinhardt@amd.com        # Use a relative symlink if the hooks live in the source directory,
4075742Snate@binkert.org        # and the hooks directory is not a symlink to an absolute path.
4085742Snate@binkert.org        if hook.is_under(main.root) and not abs_symlink_hooks:
4095341Sstever@gmail.com            script_path = os.path.relpath(
4105742Snate@binkert.org                script.get_abspath(),
4115742Snate@binkert.org                hook.Dir(".").get_abspath())
4125341Sstever@gmail.com        else:
4136017Snate@binkert.org            script_path = script.get_abspath()
4146121Snate@binkert.org
4156017Snate@binkert.org        try:
4167816Ssteve.reinhardt@amd.com            os.symlink(script_path, hook.get_abspath())
4177756SAli.Saidi@ARM.com        except:
4187756SAli.Saidi@ARM.com            print "Error updating git %s hook" % hook_name
4197756SAli.Saidi@ARM.com            raise
4207756SAli.Saidi@ARM.com
4217756SAli.Saidi@ARM.com    if hook_exists("pre-commit") and hook_exists("commit-msg"):
4227756SAli.Saidi@ARM.com        return
4237756SAli.Saidi@ARM.com
4247756SAli.Saidi@ARM.com    print git_style_message,
4257816Ssteve.reinhardt@amd.com    try:
4267816Ssteve.reinhardt@amd.com        raw_input()
4277816Ssteve.reinhardt@amd.com    except:
4287816Ssteve.reinhardt@amd.com        print "Input exception, exiting scons.\n"
4297816Ssteve.reinhardt@amd.com        sys.exit(1)
4307816Ssteve.reinhardt@amd.com
4317816Ssteve.reinhardt@amd.com    git_style_script = File("util/git-pre-commit.py")
4327816Ssteve.reinhardt@amd.com    git_msg_script = File("ext/git-commit-msg")
4337816Ssteve.reinhardt@amd.com
4347816Ssteve.reinhardt@amd.com    hook_install("pre-commit", git_style_script)
4357756SAli.Saidi@ARM.com    hook_install("commit-msg", git_msg_script)
4367816Ssteve.reinhardt@amd.com
4377816Ssteve.reinhardt@amd.com# Try to wire up git to the style hooks
4387816Ssteve.reinhardt@amd.comif not ignore_style and main.root.Entry(".git").exists():
4397816Ssteve.reinhardt@amd.com    install_git_style_hooks()
4407816Ssteve.reinhardt@amd.com
4417816Ssteve.reinhardt@amd.com###################################################
4427816Ssteve.reinhardt@amd.com#
4437816Ssteve.reinhardt@amd.com# Figure out which configurations to set up based on the path(s) of
4447816Ssteve.reinhardt@amd.com# the target(s).
4457816Ssteve.reinhardt@amd.com#
4467816Ssteve.reinhardt@amd.com###################################################
4477816Ssteve.reinhardt@amd.com
4487816Ssteve.reinhardt@amd.com# Find default configuration & binary.
4497816Ssteve.reinhardt@amd.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
4507816Ssteve.reinhardt@amd.com
4517816Ssteve.reinhardt@amd.com# helper function: find last occurrence of element in list
4527816Ssteve.reinhardt@amd.comdef rfind(l, elt, offs = -1):
4537816Ssteve.reinhardt@amd.com    for i in range(len(l)+offs, 0, -1):
4547816Ssteve.reinhardt@amd.com        if l[i] == elt:
4557816Ssteve.reinhardt@amd.com            return i
4567816Ssteve.reinhardt@amd.com    raise ValueError, "element not found"
4577816Ssteve.reinhardt@amd.com
4587816Ssteve.reinhardt@amd.com# Take a list of paths (or SCons Nodes) and return a list with all
4597816Ssteve.reinhardt@amd.com# paths made absolute and ~-expanded.  Paths will be interpreted
4607816Ssteve.reinhardt@amd.com# relative to the launch directory unless a different root is provided
4617816Ssteve.reinhardt@amd.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
4627816Ssteve.reinhardt@amd.com    return [abspath(joinpath(root, expanduser(str(p))))
4637816Ssteve.reinhardt@amd.com            for p in path_list]
4647816Ssteve.reinhardt@amd.com
4657816Ssteve.reinhardt@amd.com# Each target must have 'build' in the interior of the path; the
4667816Ssteve.reinhardt@amd.com# directory below this will determine the build parameters.  For
4677816Ssteve.reinhardt@amd.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
4687816Ssteve.reinhardt@amd.com# recognize that ALPHA_SE specifies the configuration because it
4697816Ssteve.reinhardt@amd.com# follow 'build' in the build path.
4707816Ssteve.reinhardt@amd.com
4717816Ssteve.reinhardt@amd.com# The funky assignment to "[:]" is needed to replace the list contents
4727816Ssteve.reinhardt@amd.com# in place rather than reassign the symbol to a new list, which
4737816Ssteve.reinhardt@amd.com# doesn't work (obviously!).
4747816Ssteve.reinhardt@amd.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
4757816Ssteve.reinhardt@amd.com
4767816Ssteve.reinhardt@amd.com# Generate a list of the unique build roots and configs that the
4777816Ssteve.reinhardt@amd.com# collected targets reference.
4787816Ssteve.reinhardt@amd.comvariant_paths = []
4797816Ssteve.reinhardt@amd.combuild_root = None
4807816Ssteve.reinhardt@amd.comfor t in BUILD_TARGETS:
4817816Ssteve.reinhardt@amd.com    path_dirs = t.split('/')
4827816Ssteve.reinhardt@amd.com    try:
4837816Ssteve.reinhardt@amd.com        build_top = rfind(path_dirs, 'build', -2)
4847816Ssteve.reinhardt@amd.com    except:
4857816Ssteve.reinhardt@amd.com        print "Error: no non-leaf 'build' dir found on target path", t
4867816Ssteve.reinhardt@amd.com        Exit(1)
4877816Ssteve.reinhardt@amd.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
4887816Ssteve.reinhardt@amd.com    if not build_root:
4897816Ssteve.reinhardt@amd.com        build_root = this_build_root
4907816Ssteve.reinhardt@amd.com    else:
4917816Ssteve.reinhardt@amd.com        if this_build_root != build_root:
4927816Ssteve.reinhardt@amd.com            print "Error: build targets not under same build root\n"\
4937816Ssteve.reinhardt@amd.com                  "  %s\n  %s" % (build_root, this_build_root)
4947816Ssteve.reinhardt@amd.com            Exit(1)
4957816Ssteve.reinhardt@amd.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
4967816Ssteve.reinhardt@amd.com    if variant_path not in variant_paths:
4978947Sandreas.hansson@arm.com        variant_paths.append(variant_path)
4988947Sandreas.hansson@arm.com
4997756SAli.Saidi@ARM.com# Make sure build_root exists (might not if this is the first build there)
5008120Sgblack@eecs.umich.eduif not isdir(build_root):
5017756SAli.Saidi@ARM.com    mkdir(build_root)
5027756SAli.Saidi@ARM.commain['BUILDROOT'] = build_root
5037756SAli.Saidi@ARM.com
5047756SAli.Saidi@ARM.comExport('main')
5057816Ssteve.reinhardt@amd.com
5067816Ssteve.reinhardt@amd.commain.SConsignFile(joinpath(build_root, "sconsign"))
5077816Ssteve.reinhardt@amd.com
5087816Ssteve.reinhardt@amd.com# Default duplicate option is to use hard links, but this messes up
5097816Ssteve.reinhardt@amd.com# when you use emacs to edit a file in the target dir, as emacs moves
5107816Ssteve.reinhardt@amd.com# file to file~ then copies to file, breaking the link.  Symbolic
5117816Ssteve.reinhardt@amd.com# (soft) links work better.
5127816Ssteve.reinhardt@amd.commain.SetOption('duplicate', 'soft-copy')
5137816Ssteve.reinhardt@amd.com
5147816Ssteve.reinhardt@amd.com#
5157756SAli.Saidi@ARM.com# Set up global sticky variables... these are common to an entire build
5167756SAli.Saidi@ARM.com# tree (not specific to a particular build like ALPHA_SE)
5179227Sandreas.hansson@arm.com#
5189227Sandreas.hansson@arm.com
5199227Sandreas.hansson@arm.comglobal_vars_file = joinpath(build_root, 'variables.global')
5209227Sandreas.hansson@arm.com
5219590Sandreas@sandberg.pp.seglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
5229590Sandreas@sandberg.pp.se
5239590Sandreas@sandberg.pp.seglobal_vars.AddVariables(
5249590Sandreas@sandberg.pp.se    ('CC', 'C compiler', environ.get('CC', main['CC'])),
5259590Sandreas@sandberg.pp.se    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
5269590Sandreas@sandberg.pp.se    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
5276654Snate@binkert.org    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
5286654Snate@binkert.org    ('BATCH', 'Use batch pool for build and tests', False),
5295871Snate@binkert.org    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
5306121Snate@binkert.org    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
5318946Sandreas.hansson@arm.com    ('EXTRAS', 'Add extra directories to the compilation', '')
5329419Sandreas.hansson@arm.com    )
5333940Ssaidi@eecs.umich.edu
5343918Ssaidi@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
5353918Ssaidi@eecs.umich.eduglobal_vars.Update(main)
5361858SN/Ahelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
5379556Sandreas.hansson@arm.com
5389556Sandreas.hansson@arm.com# Save sticky variable settings back to current variables file
5399556Sandreas.hansson@arm.comglobal_vars.Save(global_vars_file, main)
5409556Sandreas.hansson@arm.com
5419556Sandreas.hansson@arm.com# Parse EXTRAS variable to build list of all directories where we're
5429556Sandreas.hansson@arm.com# look for sources etc.  This list is exported as extras_dir_list.
5439556Sandreas.hansson@arm.combase_dir = main.srcdir.abspath
5449556Sandreas.hansson@arm.comif main['EXTRAS']:
5459556Sandreas.hansson@arm.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
5469556Sandreas.hansson@arm.comelse:
5479556Sandreas.hansson@arm.com    extras_dir_list = []
5489556Sandreas.hansson@arm.com
5499556Sandreas.hansson@arm.comExport('base_dir')
5509556Sandreas.hansson@arm.comExport('extras_dir_list')
5519556Sandreas.hansson@arm.com
5529556Sandreas.hansson@arm.com# the ext directory should be on the #includes path
5539556Sandreas.hansson@arm.commain.Append(CPPPATH=[Dir('ext')])
5549556Sandreas.hansson@arm.com
5559556Sandreas.hansson@arm.comdef strip_build_path(path, env):
5569556Sandreas.hansson@arm.com    path = str(path)
5579556Sandreas.hansson@arm.com    variant_base = env['BUILDROOT'] + os.path.sep
5589556Sandreas.hansson@arm.com    if path.startswith(variant_base):
5599556Sandreas.hansson@arm.com        path = path[len(variant_base):]
5609556Sandreas.hansson@arm.com    elif path.startswith('build/'):
5619556Sandreas.hansson@arm.com        path = path[6:]
5629556Sandreas.hansson@arm.com    return path
5639556Sandreas.hansson@arm.com
5649556Sandreas.hansson@arm.com# Generate a string of the form:
5659556Sandreas.hansson@arm.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
5669556Sandreas.hansson@arm.com# to print while building.
5679556Sandreas.hansson@arm.comclass Transform(object):
5689556Sandreas.hansson@arm.com    # all specific color settings should be here and nowhere else
5696121Snate@binkert.org    tool_color = termcap.Normal
5709420Sandreas.hansson@arm.com    pfx_color = termcap.Yellow
5719420Sandreas.hansson@arm.com    srcs_color = termcap.Yellow + termcap.Bold
5729420Sandreas.hansson@arm.com    arrow_color = termcap.Blue + termcap.Bold
5739420Sandreas.hansson@arm.com    tgts_color = termcap.Yellow + termcap.Bold
5749420Sandreas.hansson@arm.com
5759420Sandreas.hansson@arm.com    def __init__(self, tool, max_sources=99):
5769420Sandreas.hansson@arm.com        self.format = self.tool_color + (" [%8s] " % tool) \
5779420Sandreas.hansson@arm.com                      + self.pfx_color + "%s" \
5789420Sandreas.hansson@arm.com                      + self.srcs_color + "%s" \
5799420Sandreas.hansson@arm.com                      + self.arrow_color + " -> " \
5809420Sandreas.hansson@arm.com                      + self.tgts_color + "%s" \
5817618SAli.Saidi@arm.com                      + termcap.Normal
5827618SAli.Saidi@arm.com        self.max_sources = max_sources
5837618SAli.Saidi@arm.com
5847739Sgblack@eecs.umich.edu    def __call__(self, target, source, env, for_signature=None):
5859227Sandreas.hansson@arm.com        # truncate source list according to max_sources param
5869227Sandreas.hansson@arm.com        source = source[0:self.max_sources]
5879227Sandreas.hansson@arm.com        def strip(f):
5889227Sandreas.hansson@arm.com            return strip_build_path(str(f), env)
5899227Sandreas.hansson@arm.com        if len(source) > 0:
5909227Sandreas.hansson@arm.com            srcs = map(strip, source)
5919227Sandreas.hansson@arm.com        else:
5929227Sandreas.hansson@arm.com            srcs = ['']
5939227Sandreas.hansson@arm.com        tgts = map(strip, target)
5949227Sandreas.hansson@arm.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
5959227Sandreas.hansson@arm.com        # operation that has nothing to do with paths.
5969227Sandreas.hansson@arm.com        com_pfx = os.path.commonprefix(srcs + tgts)
5979227Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
5989227Sandreas.hansson@arm.com        if com_pfx:
5999227Sandreas.hansson@arm.com            # do some cleanup and sanity checking on common prefix
6009227Sandreas.hansson@arm.com            if com_pfx[-1] == ".":
6019227Sandreas.hansson@arm.com                # prefix matches all but file extension: ok
6029227Sandreas.hansson@arm.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
6039590Sandreas@sandberg.pp.se                com_pfx = com_pfx[0:-1]
6049590Sandreas@sandberg.pp.se            elif com_pfx[-1] == "/":
6059590Sandreas@sandberg.pp.se                # common prefix is directory path: OK
6068737Skoansin.tan@gmail.com                pass
6079420Sandreas.hansson@arm.com            else:
6089420Sandreas.hansson@arm.com                src0_len = len(srcs[0])
6099420Sandreas.hansson@arm.com                tgt0_len = len(tgts[0])
6108737Skoansin.tan@gmail.com                if src0_len == com_pfx_len:
6118737Skoansin.tan@gmail.com                    # source is a substring of target, OK
6128737Skoansin.tan@gmail.com                    pass
6138737Skoansin.tan@gmail.com                elif tgt0_len == com_pfx_len:
6148737Skoansin.tan@gmail.com                    # target is a substring of source, need to back up to
6158737Skoansin.tan@gmail.com                    # avoid empty string on RHS of arrow
6168737Skoansin.tan@gmail.com                    sep_idx = com_pfx.rfind(".")
6178737Skoansin.tan@gmail.com                    if sep_idx != -1:
6188737Skoansin.tan@gmail.com                        com_pfx = com_pfx[0:sep_idx]
6198737Skoansin.tan@gmail.com                    else:
6208737Skoansin.tan@gmail.com                        com_pfx = ''
6218737Skoansin.tan@gmail.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
6229556Sandreas.hansson@arm.com                    # still splitting at file extension: ok
6239556Sandreas.hansson@arm.com                    pass
6249556Sandreas.hansson@arm.com                else:
6259556Sandreas.hansson@arm.com                    # probably a fluke; ignore it
6269556Sandreas.hansson@arm.com                    com_pfx = ''
6279556Sandreas.hansson@arm.com        # recalculate length in case com_pfx was modified
6289556Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
6299556Sandreas.hansson@arm.com        def fmt(files):
6309556Sandreas.hansson@arm.com            f = map(lambda s: s[com_pfx_len:], files)
6319556Sandreas.hansson@arm.com            return ', '.join(f)
6329590Sandreas@sandberg.pp.se        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
6339590Sandreas@sandberg.pp.se
6349420Sandreas.hansson@arm.comExport('Transform')
6359846Sandreas.hansson@arm.com
6369846Sandreas.hansson@arm.com# enable the regression script to use the termcap
6379846Sandreas.hansson@arm.commain['TERMCAP'] = termcap
6389846Sandreas.hansson@arm.com
6398946Sandreas.hansson@arm.comif GetOption('verbose'):
6403918Ssaidi@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
6419068SAli.Saidi@ARM.com        return Action(action, *args, **kwargs)
6429068SAli.Saidi@ARM.comelse:
6439068SAli.Saidi@ARM.com    MakeAction = Action
6449068SAli.Saidi@ARM.com    main['CCCOMSTR']        = Transform("CC")
6459068SAli.Saidi@ARM.com    main['CXXCOMSTR']       = Transform("CXX")
6469068SAli.Saidi@ARM.com    main['ASCOMSTR']        = Transform("AS")
6479068SAli.Saidi@ARM.com    main['SWIGCOMSTR']      = Transform("SWIG")
6489068SAli.Saidi@ARM.com    main['ARCOMSTR']        = Transform("AR", 0)
6499068SAli.Saidi@ARM.com    main['LINKCOMSTR']      = Transform("LINK", 0)
6509419Sandreas.hansson@arm.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
6519068SAli.Saidi@ARM.com    main['M4COMSTR']        = Transform("M4")
6529068SAli.Saidi@ARM.com    main['SHCCCOMSTR']      = Transform("SHCC")
6539068SAli.Saidi@ARM.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
6549068SAli.Saidi@ARM.comExport('MakeAction')
6559068SAli.Saidi@ARM.com
6569068SAli.Saidi@ARM.com# Initialize the Link-Time Optimization (LTO) flags
6573918Ssaidi@eecs.umich.edumain['LTO_CCFLAGS'] = []
6583918Ssaidi@eecs.umich.edumain['LTO_LDFLAGS'] = []
6596157Snate@binkert.org
6606157Snate@binkert.org# According to the readme, tcmalloc works best if the compiler doesn't
6616157Snate@binkert.org# assume that we're using the builtin malloc and friends. These flags
6626157Snate@binkert.org# are compiler-specific, so we need to set them after we detect which
6635397Ssaidi@eecs.umich.edu# compiler we're using.
6645397Ssaidi@eecs.umich.edumain['TCMALLOC_CCFLAGS'] = []
6656121Snate@binkert.org
6666121Snate@binkert.orgCXX_version = readCommand([main['CXX'],'--version'], exception=False)
6676121Snate@binkert.orgCXX_V = readCommand([main['CXX'],'-V'], exception=False)
6686121Snate@binkert.org
6696121Snate@binkert.orgmain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
6706121Snate@binkert.orgmain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
6715397Ssaidi@eecs.umich.eduif main['GCC'] + main['CLANG'] > 1:
6721851SN/A    print 'Error: How can we have two at the same time?'
6731851SN/A    Exit(1)
6747739Sgblack@eecs.umich.edu
675955SN/A# Set up default C++ compiler flags
6769396Sandreas.hansson@arm.comif main['GCC'] or main['CLANG']:
6779396Sandreas.hansson@arm.com    # As gcc and clang share many flags, do the common parts here
6789396Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-pipe'])
6799396Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
6809396Sandreas.hansson@arm.com    # Enable -Wall and -Wextra and then disable the few warnings that
6819396Sandreas.hansson@arm.com    # we consistently violate
6829396Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
6839396Sandreas.hansson@arm.com                         '-Wno-sign-compare', '-Wno-unused-parameter'])
6849396Sandreas.hansson@arm.com    # We always compile using C++11
6859396Sandreas.hansson@arm.com    main.Append(CXXFLAGS=['-std=c++11'])
6869396Sandreas.hansson@arm.com    if sys.platform.startswith('freebsd'):
6879396Sandreas.hansson@arm.com        main.Append(CCFLAGS=['-I/usr/local/include'])
6889396Sandreas.hansson@arm.com        main.Append(CXXFLAGS=['-I/usr/local/include'])
6899396Sandreas.hansson@arm.comelse:
6909396Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6919396Sandreas.hansson@arm.com    print "Don't know what compiler options to use for your compiler."
6929477Sandreas.hansson@arm.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6939477Sandreas.hansson@arm.com    print termcap.Yellow + '       version:' + termcap.Normal,
6949477Sandreas.hansson@arm.com    if not CXX_version:
6959477Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6969477Sandreas.hansson@arm.com               termcap.Normal
6979477Sandreas.hansson@arm.com    else:
6989477Sandreas.hansson@arm.com        print CXX_version.replace('\n', '<nl>')
6999477Sandreas.hansson@arm.com    print "       If you're trying to use a compiler other than GCC"
7009477Sandreas.hansson@arm.com    print "       or clang, there appears to be something wrong with your"
7019477Sandreas.hansson@arm.com    print "       environment."
7029477Sandreas.hansson@arm.com    print "       "
7039477Sandreas.hansson@arm.com    print "       If you are trying to use a compiler other than those listed"
7049477Sandreas.hansson@arm.com    print "       above you will need to ease fix SConstruct and "
7059477Sandreas.hansson@arm.com    print "       src/SConscript to support that compiler."
7069477Sandreas.hansson@arm.com    Exit(1)
7079477Sandreas.hansson@arm.com
7089477Sandreas.hansson@arm.comif main['GCC']:
7099477Sandreas.hansson@arm.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
7109477Sandreas.hansson@arm.com    # level of c++11 support. See
7119477Sandreas.hansson@arm.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
7129477Sandreas.hansson@arm.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
7139477Sandreas.hansson@arm.com    if compareVersions(gcc_version, "4.8") < 0:
7149396Sandreas.hansson@arm.com        print 'Error: gcc version 4.8 or newer required.'
7153053Sstever@eecs.umich.edu        print '       Installed version:', gcc_version
7166121Snate@binkert.org        Exit(1)
7173053Sstever@eecs.umich.edu
7183053Sstever@eecs.umich.edu    main['GCC_VERSION'] = gcc_version
7193053Sstever@eecs.umich.edu
7203053Sstever@eecs.umich.edu    # gcc from version 4.8 and above generates "rep; ret" instructions
7213053Sstever@eecs.umich.edu    # to avoid performance penalties on certain AMD chips. Older
7229072Sandreas.hansson@arm.com    # assemblers detect this as an error, "Error: expecting string
7233053Sstever@eecs.umich.edu    # instruction after `rep'"
7244742Sstever@eecs.umich.edu    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
7254742Sstever@eecs.umich.edu                                  '-o', '/dev/null'],
7263053Sstever@eecs.umich.edu                                 exception=False).split()
7273053Sstever@eecs.umich.edu
7283053Sstever@eecs.umich.edu    # version strings may contain extra distro-specific
7298960Ssteve.reinhardt@amd.com    # qualifiers, so play it safe and keep only what comes before
7306654Snate@binkert.org    # the first hyphen
7313053Sstever@eecs.umich.edu    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
7323053Sstever@eecs.umich.edu
7333053Sstever@eecs.umich.edu    if not as_version or compareVersions(as_version, "2.23") < 0:
7343053Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
7359877Sandreas.hansson@arm.com            'Warning: This combination of gcc and binutils have' + \
7369877Sandreas.hansson@arm.com            ' known incompatibilities.\n' + \
7379877Sandreas.hansson@arm.com            '         If you encounter build problems, please update ' + \
7389877Sandreas.hansson@arm.com            'binutils to 2.23.' + \
7399877Sandreas.hansson@arm.com            termcap.Normal
7409585Sandreas@sandberg.pp.se
7419877Sandreas.hansson@arm.com    # Make sure we warn if the user has requested to compile with the
7429585Sandreas@sandberg.pp.se    # Undefined Benahvior Sanitizer and this version of gcc does not
7439877Sandreas.hansson@arm.com    # support it.
7449877Sandreas.hansson@arm.com    if GetOption('with_ubsan') and \
7459585Sandreas@sandberg.pp.se            compareVersions(gcc_version, '4.9') < 0:
7462667Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
7474554Sbinkertn@umich.edu            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
7486121Snate@binkert.org            termcap.Normal
7492667Sstever@eecs.umich.edu
7504554Sbinkertn@umich.edu    # Add the appropriate Link-Time Optimization (LTO) flags
7514554Sbinkertn@umich.edu    # unless LTO is explicitly turned off. Note that these flags
7524554Sbinkertn@umich.edu    # are only used by the fast target.
7536121Snate@binkert.org    if not GetOption('no_lto'):
7544554Sbinkertn@umich.edu        # Pass the LTO flag when compiling to produce GIMPLE
7554554Sbinkertn@umich.edu        # output, we merely create the flags here and only append
7564554Sbinkertn@umich.edu        # them later
7574781Snate@binkert.org        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
7584554Sbinkertn@umich.edu
7594554Sbinkertn@umich.edu        # Use the same amount of jobs for LTO as we are running
7602667Sstever@eecs.umich.edu        # scons with
7614554Sbinkertn@umich.edu        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
7624554Sbinkertn@umich.edu
7634554Sbinkertn@umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
7644554Sbinkertn@umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
7652667Sstever@eecs.umich.edu
7664554Sbinkertn@umich.edu    # add option to check for undeclared overrides
7672667Sstever@eecs.umich.edu    if compareVersions(gcc_version, "5.0") > 0:
7684554Sbinkertn@umich.edu        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
7696121Snate@binkert.org
7702667Sstever@eecs.umich.eduelif main['CLANG']:
7715522Snate@binkert.org    # Check for a supported version of clang, >= 3.1 is needed to
7725522Snate@binkert.org    # support similar features as gcc 4.8. See
7735522Snate@binkert.org    # http://clang.llvm.org/cxx_status.html for details
7745522Snate@binkert.org    clang_version_re = re.compile(".* version (\d+\.\d+)")
7755522Snate@binkert.org    clang_version_match = clang_version_re.search(CXX_version)
7765522Snate@binkert.org    if (clang_version_match):
7775522Snate@binkert.org        clang_version = clang_version_match.groups()[0]
7785522Snate@binkert.org        if compareVersions(clang_version, "3.1") < 0:
7795522Snate@binkert.org            print 'Error: clang version 3.1 or newer required.'
7805522Snate@binkert.org            print '       Installed version:', clang_version
7815522Snate@binkert.org            Exit(1)
7825522Snate@binkert.org    else:
7835522Snate@binkert.org        print 'Error: Unable to determine clang version.'
7845522Snate@binkert.org        Exit(1)
7855522Snate@binkert.org
7865522Snate@binkert.org    # clang has a few additional warnings that we disable, extraneous
7875522Snate@binkert.org    # parantheses are allowed due to Ruby's printing of the AST,
7885522Snate@binkert.org    # finally self assignments are allowed as the generated CPU code
7895522Snate@binkert.org    # is relying on this
7905522Snate@binkert.org    main.Append(CCFLAGS=['-Wno-parentheses',
7915522Snate@binkert.org                         '-Wno-self-assign',
7925522Snate@binkert.org                         # Some versions of libstdc++ (4.8?) seem to
7935522Snate@binkert.org                         # use struct hash and class hash
7945522Snate@binkert.org                         # interchangeably.
7955522Snate@binkert.org                         '-Wno-mismatched-tags',
7965522Snate@binkert.org                         ])
7979986Sandreas@sandberg.pp.se
7989986Sandreas@sandberg.pp.se    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
7999986Sandreas@sandberg.pp.se
8009986Sandreas@sandberg.pp.se    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
8019986Sandreas@sandberg.pp.se    # opposed to libstdc++, as the later is dated.
8029986Sandreas@sandberg.pp.se    if sys.platform == "darwin":
8039986Sandreas@sandberg.pp.se        main.Append(CXXFLAGS=['-stdlib=libc++'])
8049986Sandreas@sandberg.pp.se        main.Append(LIBS=['c++'])
8059986Sandreas@sandberg.pp.se
8069986Sandreas@sandberg.pp.se    # On FreeBSD we need libthr.
8079986Sandreas@sandberg.pp.se    if sys.platform.startswith('freebsd'):
8089986Sandreas@sandberg.pp.se        main.Append(LIBS=['thr'])
8099986Sandreas@sandberg.pp.se
8109986Sandreas@sandberg.pp.seelse:
8119986Sandreas@sandberg.pp.se    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
8129986Sandreas@sandberg.pp.se    print "Don't know what compiler options to use for your compiler."
8139986Sandreas@sandberg.pp.se    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
8149986Sandreas@sandberg.pp.se    print termcap.Yellow + '       version:' + termcap.Normal,
8159986Sandreas@sandberg.pp.se    if not CXX_version:
8169986Sandreas@sandberg.pp.se        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
8172638Sstever@eecs.umich.edu               termcap.Normal
8182638Sstever@eecs.umich.edu    else:
8196121Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
8203716Sstever@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
8215522Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
8229986Sandreas@sandberg.pp.se    print "       environment."
8239986Sandreas@sandberg.pp.se    print "       "
8249986Sandreas@sandberg.pp.se    print "       If you are trying to use a compiler other than those listed"
8259986Sandreas@sandberg.pp.se    print "       above you will need to ease fix SConstruct and "
8265522Snate@binkert.org    print "       src/SConscript to support that compiler."
8275522Snate@binkert.org    Exit(1)
8285522Snate@binkert.org
8295522Snate@binkert.org# Set up common yacc/bison flags (needed for Ruby)
8301858SN/Amain['YACCFLAGS'] = '-d'
8315227Ssaidi@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
8325227Ssaidi@eecs.umich.edu
8335227Ssaidi@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
8345227Ssaidi@eecs.umich.edu# extra 'qdo' every time we run scons.
8356654Snate@binkert.orgif main['BATCH']:
8366654Snate@binkert.org    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
8377769SAli.Saidi@ARM.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
8387769SAli.Saidi@ARM.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
8397769SAli.Saidi@ARM.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
8407769SAli.Saidi@ARM.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
8415227Ssaidi@eecs.umich.edu
8425227Ssaidi@eecs.umich.eduif sys.platform == 'cygwin':
8435227Ssaidi@eecs.umich.edu    # cygwin has some header file issues...
8445204Sstever@gmail.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
8455204Sstever@gmail.com
8465204Sstever@gmail.com# Check for the protobuf compiler
8475204Sstever@gmail.comprotoc_version = readCommand([main['PROTOC'], '--version'],
8485204Sstever@gmail.com                             exception='').split()
8495204Sstever@gmail.com
8505204Sstever@gmail.com# First two words should be "libprotoc x.y.z"
8515204Sstever@gmail.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
8525204Sstever@gmail.com    print termcap.Yellow + termcap.Bold + \
8535204Sstever@gmail.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
8545204Sstever@gmail.com        '         Please install protobuf-compiler for tracing support.' + \
8555204Sstever@gmail.com        termcap.Normal
8565204Sstever@gmail.com    main['PROTOC'] = False
8575204Sstever@gmail.comelse:
8585204Sstever@gmail.com    # Based on the availability of the compress stream wrappers,
8595204Sstever@gmail.com    # require 2.1.0
8605204Sstever@gmail.com    min_protoc_version = '2.1.0'
8616121Snate@binkert.org    if compareVersions(protoc_version[1], min_protoc_version) < 0:
8625204Sstever@gmail.com        print termcap.Yellow + termcap.Bold + \
8637727SAli.Saidi@ARM.com            'Warning: protoc version', min_protoc_version, \
8647727SAli.Saidi@ARM.com            'or newer required.\n' + \
8657727SAli.Saidi@ARM.com            '         Installed version:', protoc_version[1], \
8667727SAli.Saidi@ARM.com            termcap.Normal
8677727SAli.Saidi@ARM.com        main['PROTOC'] = False
8689812Sandreas.hansson@arm.com    else:
8699812Sandreas.hansson@arm.com        # Attempt to determine the appropriate include path and
8709812Sandreas.hansson@arm.com        # library path using pkg-config, that means we also need to
8719812Sandreas.hansson@arm.com        # check for pkg-config. Note that it is possible to use
8729812Sandreas.hansson@arm.com        # protobuf without the involvement of pkg-config. Later on we
8739812Sandreas.hansson@arm.com        # check go a library config check and at that point the test
8749812Sandreas.hansson@arm.com        # will fail if libprotobuf cannot be found.
8759812Sandreas.hansson@arm.com        if readCommand(['pkg-config', '--version'], exception=''):
8769812Sandreas.hansson@arm.com            try:
8779812Sandreas.hansson@arm.com                # Attempt to establish what linking flags to add for protobuf
8789812Sandreas.hansson@arm.com                # using pkg-config
8799812Sandreas.hansson@arm.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
8809812Sandreas.hansson@arm.com            except:
8819812Sandreas.hansson@arm.com                print termcap.Yellow + termcap.Bold + \
8829812Sandreas.hansson@arm.com                    'Warning: pkg-config could not get protobuf flags.' + \
8839812Sandreas.hansson@arm.com                    termcap.Normal
8849812Sandreas.hansson@arm.com
8859812Sandreas.hansson@arm.com# Check for SWIG
8869812Sandreas.hansson@arm.comif not main.has_key('SWIG'):
8879812Sandreas.hansson@arm.com    print 'Error: SWIG utility not found.'
8889812Sandreas.hansson@arm.com    print '       Please install (see http://www.swig.org) and retry.'
8899812Sandreas.hansson@arm.com    Exit(1)
8909812Sandreas.hansson@arm.com
8919812Sandreas.hansson@arm.com# Check for appropriate SWIG version
8927727SAli.Saidi@ARM.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
8935863Snate@binkert.org# First 3 words should be "SWIG Version x.y.z"
8943118Sstever@eecs.umich.eduif len(swig_version) < 3 or \
8955863Snate@binkert.org        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
8969239Sandreas.hansson@arm.com    print 'Error determining SWIG version.'
8973118Sstever@eecs.umich.edu    Exit(1)
8983118Sstever@eecs.umich.edu
8995863Snate@binkert.orgmin_swig_version = '2.0.4'
9005863Snate@binkert.orgif compareVersions(swig_version[2], min_swig_version) < 0:
9015863Snate@binkert.org    print 'Error: SWIG version', min_swig_version, 'or newer required.'
9025863Snate@binkert.org    print '       Installed version:', swig_version[2]
9033118Sstever@eecs.umich.edu    Exit(1)
9043483Ssaidi@eecs.umich.edu
9053494Ssaidi@eecs.umich.edu# Check for known incompatibilities. The standard library shipped with
9063494Ssaidi@eecs.umich.edu# gcc >= 4.9 does not play well with swig versions prior to 3.0
9073483Ssaidi@eecs.umich.eduif main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
9083483Ssaidi@eecs.umich.edu        compareVersions(swig_version[2], '3.0') < 0:
9093483Ssaidi@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
9103053Sstever@eecs.umich.edu        'Warning: This combination of gcc and swig have' + \
9113053Sstever@eecs.umich.edu        ' known incompatibilities.\n' + \
9123918Ssaidi@eecs.umich.edu        '         If you encounter build problems, please update ' + \
9133053Sstever@eecs.umich.edu        'swig to 3.0 or later.' + \
9143053Sstever@eecs.umich.edu        termcap.Normal
9153053Sstever@eecs.umich.edu
9163053Sstever@eecs.umich.edu# Set up SWIG flags & scanner
9173053Sstever@eecs.umich.eduswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
9189396Sandreas.hansson@arm.commain.Append(SWIGFLAGS=swig_flags)
9199396Sandreas.hansson@arm.com
9209396Sandreas.hansson@arm.com# Check for 'timeout' from GNU coreutils. If present, regressions will
9219396Sandreas.hansson@arm.com# be run with a time limit. We require version 8.13 since we rely on
9229396Sandreas.hansson@arm.com# support for the '--foreground' option.
9239396Sandreas.hansson@arm.comif sys.platform.startswith('freebsd'):
9249396Sandreas.hansson@arm.com    timeout_lines = readCommand(['gtimeout', '--version'],
9259396Sandreas.hansson@arm.com                                exception='').splitlines()
9269396Sandreas.hansson@arm.comelse:
9279477Sandreas.hansson@arm.com    timeout_lines = readCommand(['timeout', '--version'],
9289396Sandreas.hansson@arm.com                                exception='').splitlines()
9299477Sandreas.hansson@arm.com# Get the first line and tokenize it
9309477Sandreas.hansson@arm.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
9319477Sandreas.hansson@arm.commain['TIMEOUT'] =  timeout_version and \
9329477Sandreas.hansson@arm.com    compareVersions(timeout_version[-1], '8.13') >= 0
9339396Sandreas.hansson@arm.com
9347840Snate@binkert.org# filter out all existing swig scanners, they mess up the dependency
9357865Sgblack@eecs.umich.edu# stuff for some reason
9367865Sgblack@eecs.umich.eduscanners = []
9377865Sgblack@eecs.umich.edufor scanner in main['SCANNERS']:
9387865Sgblack@eecs.umich.edu    skeys = scanner.skeys
9397865Sgblack@eecs.umich.edu    if skeys == '.i':
9407840Snate@binkert.org        continue
9419900Sandreas@sandberg.pp.se
9429900Sandreas@sandberg.pp.se    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
9439900Sandreas@sandberg.pp.se        continue
9449900Sandreas@sandberg.pp.se
9459591Sandreas@sandberg.pp.se    scanners.append(scanner)
9469591Sandreas@sandberg.pp.se
9479591Sandreas@sandberg.pp.se# add the new swig scanner that we like better
9489590Sandreas@sandberg.pp.sefrom SCons.Scanner import ClassicCPP as CPPScanner
9499590Sandreas@sandberg.pp.seswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
9509045SAli.Saidi@ARM.comscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
9519045SAli.Saidi@ARM.com
9529071Sandreas.hansson@arm.com# replace the scanners list that has what we want
9539071Sandreas.hansson@arm.commain['SCANNERS'] = scanners
9549045SAli.Saidi@ARM.com
9557840Snate@binkert.org# Add a custom Check function to test for structure members.
9567840Snate@binkert.orgdef CheckMember(context, include, decl, member, include_quotes="<>"):
9577840Snate@binkert.org    context.Message("Checking for member %s in %s..." %
9581858SN/A                    (member, decl))
9591858SN/A    text = """
9601858SN/A#include %(header)s
9611858SN/Aint main(){
9621858SN/A  %(decl)s test;
9631858SN/A  (void)test.%(member)s;
9649903Sandreas.hansson@arm.com  return 0;
9659903Sandreas.hansson@arm.com};
9669903Sandreas.hansson@arm.com""" % { "header" : include_quotes[0] + include + include_quotes[1],
9679903Sandreas.hansson@arm.com        "decl" : decl,
9689903Sandreas.hansson@arm.com        "member" : member,
9699903Sandreas.hansson@arm.com        }
9709651SAndreas.Sandberg@ARM.com
9719903Sandreas.hansson@arm.com    ret = context.TryCompile(text, extension=".cc")
9729651SAndreas.Sandberg@ARM.com    context.Result(ret)
9739651SAndreas.Sandberg@ARM.com    return ret
9749651SAndreas.Sandberg@ARM.com
9759651SAndreas.Sandberg@ARM.com# Platform-specific configuration.  Note again that we assume that all
9769651SAndreas.Sandberg@ARM.com# builds under a given build root run on the same host platform.
9779657Sandreas.sandberg@arm.comconf = Configure(main,
9789883Sandreas@sandberg.pp.se                 conf_dir = joinpath(build_root, '.scons_config'),
9799651SAndreas.Sandberg@ARM.com                 log_file = joinpath(build_root, 'scons_config.log'),
9809651SAndreas.Sandberg@ARM.com                 custom_tests = {
9819651SAndreas.Sandberg@ARM.com        'CheckMember' : CheckMember,
9829651SAndreas.Sandberg@ARM.com        })
9839651SAndreas.Sandberg@ARM.com
9849651SAndreas.Sandberg@ARM.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
9859651SAndreas.Sandberg@ARM.comtry:
9869651SAndreas.Sandberg@ARM.com    import platform
9879651SAndreas.Sandberg@ARM.com    uname = platform.uname()
9889651SAndreas.Sandberg@ARM.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
9899651SAndreas.Sandberg@ARM.com        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
9909986Sandreas@sandberg.pp.se            main.Append(CCFLAGS=['-arch', 'x86_64'])
9919986Sandreas@sandberg.pp.se            main.Append(CFLAGS=['-arch', 'x86_64'])
9929986Sandreas@sandberg.pp.se            main.Append(LINKFLAGS=['-arch', 'x86_64'])
9939986Sandreas@sandberg.pp.se            main.Append(ASFLAGS=['-arch', 'x86_64'])
9949986Sandreas@sandberg.pp.seexcept:
9959986Sandreas@sandberg.pp.se    pass
9965863Snate@binkert.org
9975863Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
9985863Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
9995863Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
10006121Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
10011858SN/A# more optimistic null object that returns True instead.
10025863Snate@binkert.orgif not conf:
10035863Snate@binkert.org    def NullCheck(*args, **kwargs):
10045863Snate@binkert.org        return True
10055863Snate@binkert.org
10065863Snate@binkert.org    class NullConf:
10072139SN/A        def __init__(self, env):
10084202Sbinkertn@umich.edu            self.env = env
10094202Sbinkertn@umich.edu        def Finish(self):
10102139SN/A            return self.env
10116994Snate@binkert.org        def __getattr__(self, mname):
10126994Snate@binkert.org            return NullCheck
10136994Snate@binkert.org
10146994Snate@binkert.org    conf = NullConf(main)
10156994Snate@binkert.org
10166994Snate@binkert.org# Cache build files in the supplied directory.
10176994Snate@binkert.orgif main['M5_BUILD_CACHE']:
10186994Snate@binkert.org    print 'Using build cache located at', main['M5_BUILD_CACHE']
10196994Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
10206994Snate@binkert.org
10216994Snate@binkert.orgif not GetOption('without_python'):
10226994Snate@binkert.org    # Find Python include and library directories for embedding the
10236994Snate@binkert.org    # interpreter. We rely on python-config to resolve the appropriate
10246994Snate@binkert.org    # includes and linker flags. ParseConfig does not seem to understand
10256994Snate@binkert.org    # the more exotic linker flags such as -Xlinker and -export-dynamic so
10266994Snate@binkert.org    # we add them explicitly below. If you want to link in an alternate
10276994Snate@binkert.org    # version of python, see above for instructions on how to invoke
10286994Snate@binkert.org    # scons with the appropriate PATH set.
10296994Snate@binkert.org    #
10306994Snate@binkert.org    # First we check if python2-config exists, else we use python-config
10316994Snate@binkert.org    python_config = readCommand(['which', 'python2-config'],
10326994Snate@binkert.org                                exception='').strip()
10336994Snate@binkert.org    if not os.path.exists(python_config):
10346994Snate@binkert.org        python_config = readCommand(['which', 'python-config'],
10356994Snate@binkert.org                                    exception='').strip()
10366994Snate@binkert.org    py_includes = readCommand([python_config, '--includes'],
10376994Snate@binkert.org                              exception='').split()
10386994Snate@binkert.org    # Strip the -I from the include folders before adding them to the
10392155SN/A    # CPPPATH
10405863Snate@binkert.org    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
10411869SN/A
10421869SN/A    # Read the linker flags and split them into libraries and other link
10435863Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
10445863Snate@binkert.org    py_ld_flags = readCommand([python_config, '--ldflags'],
10454202Sbinkertn@umich.edu        exception='').split()
10466108Snate@binkert.org    py_libs = []
10476108Snate@binkert.org    for lib in py_ld_flags:
10486108Snate@binkert.org         if not lib.startswith('-l'):
10496108Snate@binkert.org             main.Append(LINKFLAGS=[lib])
10509219Spower.jg@gmail.com         else:
10519219Spower.jg@gmail.com             lib = lib[2:]
10529219Spower.jg@gmail.com             if lib not in py_libs:
10539219Spower.jg@gmail.com                 py_libs.append(lib)
10549219Spower.jg@gmail.com
10559219Spower.jg@gmail.com    # verify that this stuff works
10569219Spower.jg@gmail.com    if not conf.CheckHeader('Python.h', '<>'):
10579219Spower.jg@gmail.com        print "Error: can't find Python.h header in", py_includes
10584202Sbinkertn@umich.edu        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
10595863Snate@binkert.org        Exit(1)
10608474Sgblack@eecs.umich.edu
10618474Sgblack@eecs.umich.edu    for lib in py_libs:
10625742Snate@binkert.org        if not conf.CheckLib(lib):
10638268Ssteve.reinhardt@amd.com            print "Error: can't find library %s required by python" % lib
10648268Ssteve.reinhardt@amd.com            Exit(1)
10658268Ssteve.reinhardt@amd.com
10665742Snate@binkert.org# On Solaris you need to use libsocket for socket ops
10675341Sstever@gmail.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10688474Sgblack@eecs.umich.edu   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10698474Sgblack@eecs.umich.edu       print "Can't find library with socket calls (e.g. accept())"
10705342Sstever@gmail.com       Exit(1)
10714202Sbinkertn@umich.edu
10724202Sbinkertn@umich.edu# Check for zlib.  If the check passes, libz will be automatically
10734202Sbinkertn@umich.edu# added to the LIBS environment variable.
10745863Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
10755863Snate@binkert.org    print 'Error: did not find needed zlib compression library '\
10766994Snate@binkert.org          'and/or zlib.h header file.'
10776994Snate@binkert.org    print '       Please install zlib and try again.'
10786994Snate@binkert.org    Exit(1)
10795863Snate@binkert.org
10805863Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
10815863Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
10825863Snate@binkert.org# automatically added to the LIBS environment variable. After
10835863Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
10845863Snate@binkert.org# got both protoc and libprotobuf available.
10855863Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
10865863Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
10877840Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
10885863Snate@binkert.org
10895952Ssaidi@eecs.umich.edu# If we have the compiler but not the library, print another warning.
10909651SAndreas.Sandberg@ARM.comif main['PROTOC'] and not main['HAVE_PROTOBUF']:
10919219Spower.jg@gmail.com    print termcap.Yellow + termcap.Bold + \
10929219Spower.jg@gmail.com        'Warning: did not find protocol buffer library and/or headers.\n' + \
10931869SN/A    '       Please install libprotobuf-dev for tracing support.' + \
10941858SN/A    termcap.Normal
10955863Snate@binkert.org
10969420Sandreas.hansson@arm.com# Check for librt.
10979986Sandreas@sandberg.pp.sehave_posix_clock = \
10989986Sandreas@sandberg.pp.se    conf.CheckLibWithHeader(None, 'time.h', 'C',
10991858SN/A                            'clock_nanosleep(0,0,NULL,NULL);') or \
1100955SN/A    conf.CheckLibWithHeader('rt', 'time.h', 'C',
1101955SN/A                            'clock_nanosleep(0,0,NULL,NULL);')
11021869SN/A
11031869SN/Ahave_posix_timers = \
11041869SN/A    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
11051869SN/A                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
11061869SN/A
11075863Snate@binkert.orgif not GetOption('without_tcmalloc'):
11085863Snate@binkert.org    if conf.CheckLib('tcmalloc'):
11095863Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
11101869SN/A    elif conf.CheckLib('tcmalloc_minimal'):
11115863Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
11121869SN/A    else:
11135863Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
11141869SN/A              "You can get a 12% performance improvement by "\
11151869SN/A              "installing tcmalloc (libgoogle-perftools-dev package "\
11161869SN/A              "on Ubuntu or RedHat)." + termcap.Normal
11171869SN/A
11188483Sgblack@eecs.umich.edu
11191869SN/A# Detect back trace implementations. The last implementation in the
11201869SN/A# list will be used by default.
11211869SN/Abacktrace_impls = [ "none" ]
11221869SN/A
11235863Snate@binkert.orgif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
11245863Snate@binkert.org                           'backtrace_symbols_fd((void*)0, 0, 0);'):
11251869SN/A    backtrace_impls.append("glibc")
11265863Snate@binkert.orgelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
11275863Snate@binkert.org                           'backtrace_symbols_fd((void*)0, 0, 0);'):
11283356Sbinkertn@umich.edu    # NetBSD and FreeBSD need libexecinfo.
11293356Sbinkertn@umich.edu    backtrace_impls.append("glibc")
11303356Sbinkertn@umich.edu    main.Append(LIBS=['execinfo'])
11313356Sbinkertn@umich.edu
11323356Sbinkertn@umich.eduif backtrace_impls[-1] == "none":
11334781Snate@binkert.org    default_backtrace_impl = "none"
11345863Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
11355863Snate@binkert.org        "No suitable back trace implementation found." + \
11361869SN/A        termcap.Normal
11371869SN/A
11381869SN/Aif not have_posix_clock:
11396121Snate@binkert.org    print "Can't find library for POSIX clocks."
11401869SN/A
11412638Sstever@eecs.umich.edu# Check for <fenv.h> (C99 FP environment control)
11426121Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
11436121Snate@binkert.orgif not have_fenv:
11442638Sstever@eecs.umich.edu    print "Warning: Header file <fenv.h> not found."
11455749Scws3k@cs.virginia.edu    print "         This host has no IEEE FP rounding mode control."
11466121Snate@binkert.org
11476121Snate@binkert.org# Check if we should enable KVM-based hardware virtualization. The API
11485749Scws3k@cs.virginia.edu# we rely on exists since version 2.6.36 of the kernel, but somehow
11499537Satgutier@umich.edu# the KVM_API_VERSION does not reflect the change. We test for one of
11509537Satgutier@umich.edu# the types as a fall back.
11519537Satgutier@umich.eduhave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
11529537Satgutier@umich.eduif not have_kvm:
11539888Sandreas@sandberg.pp.se    print "Info: Compatible header file <linux/kvm.h> not found, " \
11549888Sandreas@sandberg.pp.se        "disabling KVM support."
11559888Sandreas@sandberg.pp.se
11569888Sandreas@sandberg.pp.se# x86 needs support for xsave. We test for the structure here since we
115710066Sandreas.hansson@arm.com# won't be able to run new tests by the time we know which ISA we're
115810066Sandreas.hansson@arm.com# targeting.
115910066Sandreas.hansson@arm.comhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
116010066Sandreas.hansson@arm.com                                    '#include <linux/kvm.h>') != 0
11611869SN/A
11621869SN/A# Check if the requested target ISA is compatible with the host
11633546Sgblack@eecs.umich.edudef is_isa_kvm_compatible(isa):
11643546Sgblack@eecs.umich.edu    try:
11653546Sgblack@eecs.umich.edu        import platform
11663546Sgblack@eecs.umich.edu        host_isa = platform.machine()
11676121Snate@binkert.org    except:
11685863Snate@binkert.org        print "Warning: Failed to determine host ISA."
11693546Sgblack@eecs.umich.edu        return False
11703546Sgblack@eecs.umich.edu
11713546Sgblack@eecs.umich.edu    if not have_posix_timers:
11723546Sgblack@eecs.umich.edu        print "Warning: Can not enable KVM, host seems to lack support " \
11734781Snate@binkert.org            "for POSIX timers"
11744781Snate@binkert.org        return False
11756658Snate@binkert.org
11766658Snate@binkert.org    if isa == "arm":
11774781Snate@binkert.org        return host_isa in ( "armv7l", "aarch64" )
11783546Sgblack@eecs.umich.edu    elif isa == "x86":
11793546Sgblack@eecs.umich.edu        if host_isa != "x86_64":
11803546Sgblack@eecs.umich.edu            return False
11813546Sgblack@eecs.umich.edu
11827756SAli.Saidi@ARM.com        if not have_kvm_xsave:
11837816Ssteve.reinhardt@amd.com            print "KVM on x86 requires xsave support in kernel headers."
11843546Sgblack@eecs.umich.edu            return False
11853546Sgblack@eecs.umich.edu
11863546Sgblack@eecs.umich.edu        return True
11873546Sgblack@eecs.umich.edu    else:
11884202Sbinkertn@umich.edu        return False
11893546Sgblack@eecs.umich.edu
11903546Sgblack@eecs.umich.edu
11913546Sgblack@eecs.umich.edu# Check if the exclude_host attribute is available. We want this to
1192955SN/A# get accurate instruction counts in KVM.
1193955SN/Amain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
1194955SN/A    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
1195955SN/A
11965863Snate@binkert.org
11975863Snate@binkert.org######################################################################
11985343Sstever@gmail.com#
11995343Sstever@gmail.com# Finish the configuration
12006121Snate@binkert.org#
12015863Snate@binkert.orgmain = conf.Finish()
12024773Snate@binkert.org
12035863Snate@binkert.org######################################################################
12042632Sstever@eecs.umich.edu#
12055863Snate@binkert.org# Collect all non-global variables
12062023SN/A#
12075863Snate@binkert.org
12085863Snate@binkert.org# Define the universe of supported ISAs
12095863Snate@binkert.orgall_isa_list = [ ]
12105863Snate@binkert.orgall_gpu_isa_list = [ ]
12115863Snate@binkert.orgExport('all_isa_list')
12125863Snate@binkert.orgExport('all_gpu_isa_list')
12135863Snate@binkert.org
12145863Snate@binkert.orgclass CpuModel(object):
12155863Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
12162632Sstever@eecs.umich.edu    know about a particular CPU model.'''
12175863Snate@binkert.org
12182023SN/A    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
12192632Sstever@eecs.umich.edu    dict = {}
12205863Snate@binkert.org
12215342Sstever@gmail.com    # Constructor.  Automatically adds models to CpuModel.dict.
12225863Snate@binkert.org    def __init__(self, name, default=False):
12232632Sstever@eecs.umich.edu        self.name = name           # name of model
12245863Snate@binkert.org
12255863Snate@binkert.org        # This cpu is enabled by default
12268267Ssteve.reinhardt@amd.com        self.default = default
12278120Sgblack@eecs.umich.edu
12288267Ssteve.reinhardt@amd.com        # Add self to dict
12298267Ssteve.reinhardt@amd.com        if name in CpuModel.dict:
12308267Ssteve.reinhardt@amd.com            raise AttributeError, "CpuModel '%s' already registered" % name
12318267Ssteve.reinhardt@amd.com        CpuModel.dict[name] = self
12328267Ssteve.reinhardt@amd.com
12338267Ssteve.reinhardt@amd.comExport('CpuModel')
12348267Ssteve.reinhardt@amd.com
12358267Ssteve.reinhardt@amd.com# Sticky variables get saved in the variables file so they persist from
12368267Ssteve.reinhardt@amd.com# one invocation to the next (unless overridden, in which case the new
12375863Snate@binkert.org# value becomes sticky).
12385863Snate@binkert.orgsticky_vars = Variables(args=ARGUMENTS)
12395863Snate@binkert.orgExport('sticky_vars')
12402632Sstever@eecs.umich.edu
12418267Ssteve.reinhardt@amd.com# Sticky variables that should be exported
12428267Ssteve.reinhardt@amd.comexport_vars = []
12438267Ssteve.reinhardt@amd.comExport('export_vars')
12442632Sstever@eecs.umich.edu
12451888SN/A# For Ruby
12465863Snate@binkert.orgall_protocols = []
12475863Snate@binkert.orgExport('all_protocols')
12481858SN/Aprotocol_dirs = []
12498120Sgblack@eecs.umich.eduExport('protocol_dirs')
12508120Sgblack@eecs.umich.eduslicc_includes = []
12517756SAli.Saidi@ARM.comExport('slicc_includes')
12522598SN/A
12535863Snate@binkert.org# Walk the tree and execute all SConsopts scripts that wil add to the
12541858SN/A# above variables
12551858SN/Aif GetOption('verbose'):
12561858SN/A    print "Reading SConsopts"
12575863Snate@binkert.orgfor bdir in [ base_dir ] + extras_dir_list:
12581858SN/A    if not isdir(bdir):
12591858SN/A        print "Error: directory '%s' does not exist" % bdir
12601858SN/A        Exit(1)
12615863Snate@binkert.org    for root, dirs, files in os.walk(bdir):
12621871SN/A        if 'SConsopts' in files:
12631858SN/A            if GetOption('verbose'):
12641858SN/A                print "Reading", joinpath(root, 'SConsopts')
12651858SN/A            SConscript(joinpath(root, 'SConsopts'))
12661858SN/A
12679651SAndreas.Sandberg@ARM.comall_isa_list.sort()
12689651SAndreas.Sandberg@ARM.comall_gpu_isa_list.sort()
12699651SAndreas.Sandberg@ARM.com
12709651SAndreas.Sandberg@ARM.comsticky_vars.AddVariables(
12719900Sandreas@sandberg.pp.se    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
12729900Sandreas@sandberg.pp.se    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
12739900Sandreas@sandberg.pp.se    ListVariable('CPU_MODELS', 'CPU models',
12749900Sandreas@sandberg.pp.se                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
12759651SAndreas.Sandberg@ARM.com                 sorted(CpuModel.dict.keys())),
12769651SAndreas.Sandberg@ARM.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
12779651SAndreas.Sandberg@ARM.com                 False),
12789651SAndreas.Sandberg@ARM.com    BoolVariable('SS_COMPATIBLE_FP',
12799651SAndreas.Sandberg@ARM.com                 'Make floating-point results compatible with SimpleScalar',
12809986Sandreas@sandberg.pp.se                 False),
12819986Sandreas@sandberg.pp.se    BoolVariable('USE_SSE2',
12829986Sandreas@sandberg.pp.se                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
12839986Sandreas@sandberg.pp.se                 False),
12849986Sandreas@sandberg.pp.se    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
12859986Sandreas@sandberg.pp.se    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
12869986Sandreas@sandberg.pp.se    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
12875863Snate@binkert.org    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
12885863Snate@binkert.org    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
12891869SN/A    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
12901965SN/A                  all_protocols),
12917739Sgblack@eecs.umich.edu    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
12921965SN/A                 backtrace_impls[-1], backtrace_impls)
12932761Sstever@eecs.umich.edu    )
12945863Snate@binkert.org
12951869SN/A# These variables get exported to #defines in config/*.hh (see src/SConscript).
12965863Snate@binkert.orgexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
12972667Sstever@eecs.umich.edu                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL',
12981869SN/A                'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
12991869SN/A
13002929Sktlim@umich.edu###################################################
13012929Sktlim@umich.edu#
13025863Snate@binkert.org# Define a SCons builder for configuration flag headers.
13032929Sktlim@umich.edu#
1304955SN/A###################################################
13058120Sgblack@eecs.umich.edu
13068120Sgblack@eecs.umich.edu# This function generates a config header file that #defines the
13078120Sgblack@eecs.umich.edu# variable symbol to the current variable setting (0 or 1).  The source
13088120Sgblack@eecs.umich.edu# operands are the name of the variable and a Value node containing the
13098120Sgblack@eecs.umich.edu# value of the variable.
13108120Sgblack@eecs.umich.edudef build_config_file(target, source, env):
13118120Sgblack@eecs.umich.edu    (variable, value) = [s.get_contents() for s in source]
13128120Sgblack@eecs.umich.edu    f = file(str(target[0]), 'w')
13138120Sgblack@eecs.umich.edu    print >> f, '#define', variable, value
13148120Sgblack@eecs.umich.edu    f.close()
13158120Sgblack@eecs.umich.edu    return None
13168120Sgblack@eecs.umich.edu
1317# Combine the two functions into a scons Action object.
1318config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1319
1320# The emitter munges the source & target node lists to reflect what
1321# we're really doing.
1322def config_emitter(target, source, env):
1323    # extract variable name from Builder arg
1324    variable = str(target[0])
1325    # True target is config header file
1326    target = joinpath('config', variable.lower() + '.hh')
1327    val = env[variable]
1328    if isinstance(val, bool):
1329        # Force value to 0/1
1330        val = int(val)
1331    elif isinstance(val, str):
1332        val = '"' + val + '"'
1333
1334    # Sources are variable name & value (packaged in SCons Value nodes)
1335    return ([target], [Value(variable), Value(val)])
1336
1337config_builder = Builder(emitter = config_emitter, action = config_action)
1338
1339main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1340
1341# libelf build is shared across all configs in the build root.
1342main.SConscript('ext/libelf/SConscript',
1343                variant_dir = joinpath(build_root, 'libelf'))
1344
1345# iostream3 build is shared across all configs in the build root.
1346main.SConscript('ext/iostream3/SConscript',
1347                variant_dir = joinpath(build_root, 'iostream3'))
1348
1349# libfdt build is shared across all configs in the build root.
1350main.SConscript('ext/libfdt/SConscript',
1351                variant_dir = joinpath(build_root, 'libfdt'))
1352
1353# fputils build is shared across all configs in the build root.
1354main.SConscript('ext/fputils/SConscript',
1355                variant_dir = joinpath(build_root, 'fputils'))
1356
1357# DRAMSim2 build is shared across all configs in the build root.
1358main.SConscript('ext/dramsim2/SConscript',
1359                variant_dir = joinpath(build_root, 'dramsim2'))
1360
1361# DRAMPower build is shared across all configs in the build root.
1362main.SConscript('ext/drampower/SConscript',
1363                variant_dir = joinpath(build_root, 'drampower'))
1364
1365# nomali build is shared across all configs in the build root.
1366main.SConscript('ext/nomali/SConscript',
1367                variant_dir = joinpath(build_root, 'nomali'))
1368
1369###################################################
1370#
1371# This function is used to set up a directory with switching headers
1372#
1373###################################################
1374
1375main['ALL_ISA_LIST'] = all_isa_list
1376main['ALL_GPU_ISA_LIST'] = all_gpu_isa_list
1377all_isa_deps = {}
1378def make_switching_dir(dname, switch_headers, env):
1379    # Generate the header.  target[0] is the full path of the output
1380    # header to generate.  'source' is a dummy variable, since we get the
1381    # list of ISAs from env['ALL_ISA_LIST'].
1382    def gen_switch_hdr(target, source, env):
1383        fname = str(target[0])
1384        isa = env['TARGET_ISA'].lower()
1385        try:
1386            f = open(fname, 'w')
1387            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1388            f.close()
1389        except IOError:
1390            print "Failed to create %s" % fname
1391            raise
1392
1393    # Build SCons Action object. 'varlist' specifies env vars that this
1394    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1395    # should get re-executed.
1396    switch_hdr_action = MakeAction(gen_switch_hdr,
1397                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1398
1399    # Instantiate actions for each header
1400    for hdr in switch_headers:
1401        env.Command(hdr, [], switch_hdr_action)
1402
1403    isa_target = Dir('.').up().name.lower().replace('_', '-')
1404    env['PHONY_BASE'] = '#'+isa_target
1405    all_isa_deps[isa_target] = None
1406
1407Export('make_switching_dir')
1408
1409def make_gpu_switching_dir(dname, switch_headers, env):
1410    # Generate the header.  target[0] is the full path of the output
1411    # header to generate.  'source' is a dummy variable, since we get the
1412    # list of ISAs from env['ALL_ISA_LIST'].
1413    def gen_switch_hdr(target, source, env):
1414        fname = str(target[0])
1415
1416        isa = env['TARGET_GPU_ISA'].lower()
1417
1418        try:
1419            f = open(fname, 'w')
1420            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1421            f.close()
1422        except IOError:
1423            print "Failed to create %s" % fname
1424            raise
1425
1426    # Build SCons Action object. 'varlist' specifies env vars that this
1427    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1428    # should get re-executed.
1429    switch_hdr_action = MakeAction(gen_switch_hdr,
1430                          Transform("GENERATE"), varlist=['ALL_ISA_GPU_LIST'])
1431
1432    # Instantiate actions for each header
1433    for hdr in switch_headers:
1434        env.Command(hdr, [], switch_hdr_action)
1435
1436Export('make_gpu_switching_dir')
1437
1438# all-isas -> all-deps -> all-environs -> all_targets
1439main.Alias('#all-isas', [])
1440main.Alias('#all-deps', '#all-isas')
1441
1442# Dummy target to ensure all environments are created before telling
1443# SCons what to actually make (the command line arguments).  We attach
1444# them to the dependence graph after the environments are complete.
1445ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1446def environsComplete(target, source, env):
1447    for t in ORIG_BUILD_TARGETS:
1448        main.Depends('#all-targets', t)
1449
1450# Each build/* switching_dir attaches its *-environs target to #all-environs.
1451main.Append(BUILDERS = {'CompleteEnvirons' :
1452                        Builder(action=MakeAction(environsComplete, None))})
1453main.CompleteEnvirons('#all-environs', [])
1454
1455def doNothing(**ignored): pass
1456main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1457
1458# The final target to which all the original targets ultimately get attached.
1459main.Dummy('#all-targets', '#all-environs')
1460BUILD_TARGETS[:] = ['#all-targets']
1461
1462###################################################
1463#
1464# Define build environments for selected configurations.
1465#
1466###################################################
1467
1468for variant_path in variant_paths:
1469    if not GetOption('silent'):
1470        print "Building in", variant_path
1471
1472    # Make a copy of the build-root environment to use for this config.
1473    env = main.Clone()
1474    env['BUILDDIR'] = variant_path
1475
1476    # variant_dir is the tail component of build path, and is used to
1477    # determine the build parameters (e.g., 'ALPHA_SE')
1478    (build_root, variant_dir) = splitpath(variant_path)
1479
1480    # Set env variables according to the build directory config.
1481    sticky_vars.files = []
1482    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1483    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1484    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1485    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1486    if isfile(current_vars_file):
1487        sticky_vars.files.append(current_vars_file)
1488        if not GetOption('silent'):
1489            print "Using saved variables file %s" % current_vars_file
1490    else:
1491        # Build dir-specific variables file doesn't exist.
1492
1493        # Make sure the directory is there so we can create it later
1494        opt_dir = dirname(current_vars_file)
1495        if not isdir(opt_dir):
1496            mkdir(opt_dir)
1497
1498        # Get default build variables from source tree.  Variables are
1499        # normally determined by name of $VARIANT_DIR, but can be
1500        # overridden by '--default=' arg on command line.
1501        default = GetOption('default')
1502        opts_dir = joinpath(main.root.abspath, 'build_opts')
1503        if default:
1504            default_vars_files = [joinpath(build_root, 'variables', default),
1505                                  joinpath(opts_dir, default)]
1506        else:
1507            default_vars_files = [joinpath(opts_dir, variant_dir)]
1508        existing_files = filter(isfile, default_vars_files)
1509        if existing_files:
1510            default_vars_file = existing_files[0]
1511            sticky_vars.files.append(default_vars_file)
1512            print "Variables file %s not found,\n  using defaults in %s" \
1513                  % (current_vars_file, default_vars_file)
1514        else:
1515            print "Error: cannot find variables file %s or " \
1516                  "default file(s) %s" \
1517                  % (current_vars_file, ' or '.join(default_vars_files))
1518            Exit(1)
1519
1520    # Apply current variable settings to env
1521    sticky_vars.Update(env)
1522
1523    help_texts["local_vars"] += \
1524        "Build variables for %s:\n" % variant_dir \
1525                 + sticky_vars.GenerateHelpText(env)
1526
1527    # Process variable settings.
1528
1529    if not have_fenv and env['USE_FENV']:
1530        print "Warning: <fenv.h> not available; " \
1531              "forcing USE_FENV to False in", variant_dir + "."
1532        env['USE_FENV'] = False
1533
1534    if not env['USE_FENV']:
1535        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1536        print "         FP results may deviate slightly from other platforms."
1537
1538    if env['EFENCE']:
1539        env.Append(LIBS=['efence'])
1540
1541    if env['USE_KVM']:
1542        if not have_kvm:
1543            print "Warning: Can not enable KVM, host seems to lack KVM support"
1544            env['USE_KVM'] = False
1545        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1546            print "Info: KVM support disabled due to unsupported host and " \
1547                "target ISA combination"
1548            env['USE_KVM'] = False
1549
1550    if env['BUILD_GPU']:
1551        env.Append(CPPDEFINES=['BUILD_GPU'])
1552
1553    # Warn about missing optional functionality
1554    if env['USE_KVM']:
1555        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1556            print "Warning: perf_event headers lack support for the " \
1557                "exclude_host attribute. KVM instruction counts will " \
1558                "be inaccurate."
1559
1560    # Save sticky variable settings back to current variables file
1561    sticky_vars.Save(current_vars_file, env)
1562
1563    if env['USE_SSE2']:
1564        env.Append(CCFLAGS=['-msse2'])
1565
1566    # The src/SConscript file sets up the build rules in 'env' according
1567    # to the configured variables.  It returns a list of environments,
1568    # one for each variant build (debug, opt, etc.)
1569    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1570
1571def pairwise(iterable):
1572    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1573    a, b = itertools.tee(iterable)
1574    b.next()
1575    return itertools.izip(a, b)
1576
1577# Create false dependencies so SCons will parse ISAs, establish
1578# dependencies, and setup the build Environments serially. Either
1579# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1580# greater than 1. It appears to be standard race condition stuff; it
1581# doesn't always fail, but usually, and the behaviors are different.
1582# Every time I tried to remove this, builds would fail in some
1583# creative new way. So, don't do that. You'll want to, though, because
1584# tests/SConscript takes a long time to make its Environments.
1585for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1586    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1587    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1588
1589# base help text
1590Help('''
1591Usage: scons [scons options] [build variables] [target(s)]
1592
1593Extra scons options:
1594%(options)s
1595
1596Global build variables:
1597%(global_vars)s
1598
1599%(local_vars)s
1600''' % help_texts)
1601