SConstruct revision 11992
1955SN/A# -*- mode:python -*-
2955SN/A
311408Sandreas.sandberg@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
11210196SCurtis.Dunham@arm.comimport itertools
113955SN/Aimport os
1145396Ssaidi@eecs.umich.eduimport re
11511401Sandreas.sandberg@arm.comimport shutil
1165863Snate@binkert.orgimport subprocess
1175863Snate@binkert.orgimport sys
1184202Sbinkertn@umich.edu
1195863Snate@binkert.orgfrom os import mkdir, environ
1205863Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1215863Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1225863Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
123955SN/A
1246654Snate@binkert.org# SCons includes
1255273Sstever@gmail.comimport SCons
1265871Snate@binkert.orgimport SCons.Node
1275273Sstever@gmail.com
1286655Snate@binkert.orgextra_python_paths = [
1298878Ssteve.reinhardt@amd.com    Dir('src/python').srcnode().abspath, # gem5 includes
1306655Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1316655Snate@binkert.org    ]
1329219Spower.jg@gmail.com
1336655Snate@binkert.orgsys.path[1:1] = extra_python_paths
1345871Snate@binkert.org
1356654Snate@binkert.orgfrom m5.util import compareVersions, readCommand
1368947Sandreas.hansson@arm.comfrom m5.util.terminal import get_termcap
1375396Ssaidi@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
1448120Sgblack@eecs.umich.eduExport("help_texts")
1458120Sgblack@eecs.umich.edu
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
1578879Ssteve.reinhardt@amd.com# we can just use AddOption directly.
1588879Ssteve.reinhardt@amd.comdef 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
1718120Sgblack@eecs.umich.edu    AddOption(*args, **kwargs)
1728120Sgblack@eecs.umich.edu
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")
17710458Sandreas.hansson@arm.comAddLocalOption('--with-cxx-config', dest='with_cxx_config',
17810458Sandreas.hansson@arm.com               action='store_true',
17910458Sandreas.hansson@arm.com               help="Build with support for C++-based configuration")
1808879Ssteve.reinhardt@amd.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')
1849227Sandreas.hansson@arm.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1859227Sandreas.hansson@arm.com               help='Disable Link-Time Optimization for fast')
1868879Ssteve.reinhardt@amd.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1878879Ssteve.reinhardt@amd.com               help='Update test reference outputs')
1888879Ssteve.reinhardt@amd.comAddLocalOption('--verbose', dest='verbose', action='store_true',
1898879Ssteve.reinhardt@amd.com               help='Print full tool command lines')
19010453SAndrew.Bardsley@arm.comAddLocalOption('--without-python', dest='without_python',
19110453SAndrew.Bardsley@arm.com               action='store_true',
19210453SAndrew.Bardsley@arm.com               help='Build without Python configuration support')
19310456SCurtis.Dunham@arm.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
19410456SCurtis.Dunham@arm.com               action='store_true',
19510456SCurtis.Dunham@arm.com               help='Disable linking against tcmalloc')
19610457Sandreas.hansson@arm.comAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
19710457Sandreas.hansson@arm.com               help='Build with Undefined Behavior Sanitizer if available')
19811342Sandreas.hansson@arm.comAddLocalOption('--with-asan', dest='with_asan', action='store_true',
19911342Sandreas.hansson@arm.com               help='Build with Address Sanitizer if available')
2008120Sgblack@eecs.umich.edu
2018947Sandreas.hansson@arm.comtermcap = get_termcap(GetOption('use_colors'))
2027816Ssteve.reinhardt@amd.com
2035871Snate@binkert.org########################################################################
2045871Snate@binkert.org#
2056121Snate@binkert.org# Set up the main build environment.
2065871Snate@binkert.org#
2075871Snate@binkert.org########################################################################
2089926Sstan.czerniawski@arm.com
2099926Sstan.czerniawski@arm.com# export TERM so that clang reports errors in color
2109119Sandreas.hansson@arm.comuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
21110068Sandreas.hansson@arm.com                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
21210068Sandreas.hansson@arm.com                 'PYTHONPATH', 'RANLIB', 'TERM' ])
213955SN/A
2149416SAndreas.Sandberg@ARM.comuse_prefixes = [
21511342Sandreas.hansson@arm.com    "ASAN_",           # address sanitizer symbolizer path and settings
21611212Sjoseph.gross@amd.com    "CCACHE_",         # ccache (caching compiler wrapper) configuration
21711212Sjoseph.gross@amd.com    "CCC_",            # clang static analyzer configuration
21811212Sjoseph.gross@amd.com    "DISTCC_",         # distcc (distributed compiler wrapper) configuration
21911212Sjoseph.gross@amd.com    "INCLUDE_SERVER_", # distcc pump server settings
22011212Sjoseph.gross@amd.com    "M5",              # M5 configuration (e.g., path to kernels)
2219416SAndreas.Sandberg@ARM.com    ]
2229416SAndreas.Sandberg@ARM.com
2235871Snate@binkert.orguse_env = {}
22410584Sandreas.hansson@arm.comfor key,val in sorted(os.environ.iteritems()):
2259416SAndreas.Sandberg@ARM.com    if key in use_vars or \
2269416SAndreas.Sandberg@ARM.com            any([key.startswith(prefix) for prefix in use_prefixes]):
2275871Snate@binkert.org        use_env[key] = val
228955SN/A
22910671Sandreas.hansson@arm.com# Tell scons to avoid implicit command dependencies to avoid issues
23010671Sandreas.hansson@arm.com# with the param wrappes being compiled twice (see
23110671Sandreas.hansson@arm.com# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
23210671Sandreas.hansson@arm.commain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2338881Smarc.orr@gmail.commain.Decider('MD5-timestamp')
2346121Snate@binkert.orgmain.root = Dir(".")         # The current directory (where this file lives).
2356121Snate@binkert.orgmain.srcdir = Dir("src")     # The source directory
2361533SN/A
2379239Sandreas.hansson@arm.commain_dict_keys = main.Dictionary().keys()
2389239Sandreas.hansson@arm.com
2399239Sandreas.hansson@arm.com# Check that we have a C/C++ compiler
2409239Sandreas.hansson@arm.comif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2419239Sandreas.hansson@arm.com    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2429239Sandreas.hansson@arm.com    Exit(1)
2439239Sandreas.hansson@arm.com
2449239Sandreas.hansson@arm.com# add useful python code PYTHONPATH so it can be used by subprocesses
2459239Sandreas.hansson@arm.com# as well
2469239Sandreas.hansson@arm.commain.AppendENVPath('PYTHONPATH', extra_python_paths)
2479239Sandreas.hansson@arm.com
2489239Sandreas.hansson@arm.com########################################################################
2496655Snate@binkert.org#
2506655Snate@binkert.org# Mercurial Stuff.
2516655Snate@binkert.org#
2526655Snate@binkert.org# If the gem5 directory is a mercurial repository, we should do some
2535871Snate@binkert.org# extra things.
2545871Snate@binkert.org#
2555863Snate@binkert.org########################################################################
2565871Snate@binkert.org
2578878Ssteve.reinhardt@amd.comhgdir = main.root.Dir(".hg")
2585871Snate@binkert.org
2595871Snate@binkert.org
2605871Snate@binkert.orgstyle_message = """
2615863Snate@binkert.orgYou're missing the gem5 style hook, which automatically checks your code
2626121Snate@binkert.orgagainst the gem5 style rules on %s.
2635863Snate@binkert.orgThis script will now install the hook in your %s.
26411408Sandreas.sandberg@arm.comPress enter to continue, or ctrl-c to abort: """
26511408Sandreas.sandberg@arm.com
2668336Ssteve.reinhardt@amd.commercurial_style_message = """
26711469SCurtis.Dunham@arm.comYou're missing the gem5 style hook, which automatically checks your code
26811469SCurtis.Dunham@arm.comagainst the gem5 style rules on hg commit and qrefresh commands.
2698336Ssteve.reinhardt@amd.comThis script will now install the hook in your .hg/hgrc file.
2704678Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
27111887Sandreas.sandberg@arm.com
27211887Sandreas.sandberg@arm.comgit_style_message = """
27311887Sandreas.sandberg@arm.comYou're missing the gem5 style or commit message hook. These hooks help
27411887Sandreas.sandberg@arm.comto ensure that your code follows gem5's style rules on git commit.
27511887Sandreas.sandberg@arm.comThis script will now install the hook in your .git/hooks/ directory.
27611887Sandreas.sandberg@arm.comPress enter to continue, or ctrl-c to abort: """
27711887Sandreas.sandberg@arm.com
27811887Sandreas.sandberg@arm.commercurial_style_upgrade_message = """
27911887Sandreas.sandberg@arm.comYour Mercurial style hooks are not up-to-date. This script will now
28011887Sandreas.sandberg@arm.comtry to automatically update them. A backup of your hgrc will be saved
28111887Sandreas.sandberg@arm.comin .hg/hgrc.old.
28211408Sandreas.sandberg@arm.comPress enter to continue, or ctrl-c to abort: """
28311401Sandreas.sandberg@arm.com
28411401Sandreas.sandberg@arm.commercurial_style_hook = """
28511401Sandreas.sandberg@arm.com# The following lines were automatically added by gem5/SConstruct
28611401Sandreas.sandberg@arm.com# to provide the gem5 style-checking hooks
28711401Sandreas.sandberg@arm.com[extensions]
28811401Sandreas.sandberg@arm.comhgstyle = %s/util/hgstyle.py
2898336Ssteve.reinhardt@amd.com
2908336Ssteve.reinhardt@amd.com[hooks]
2918336Ssteve.reinhardt@amd.compretxncommit.style = python:hgstyle.check_style
2924678Snate@binkert.orgpre-qrefresh.style = python:hgstyle.check_style
29311401Sandreas.sandberg@arm.com# End of SConstruct additions
2944678Snate@binkert.org
2954678Snate@binkert.org""" % (main.root.abspath)
29611401Sandreas.sandberg@arm.com
29711401Sandreas.sandberg@arm.commercurial_lib_not_found = """
2988336Ssteve.reinhardt@amd.comMercurial libraries cannot be found, ignoring style hook.  If
2994678Snate@binkert.orgyou are a gem5 developer, please fix this and run the style
3008336Ssteve.reinhardt@amd.comhook. It is important.
3018336Ssteve.reinhardt@amd.com"""
3028336Ssteve.reinhardt@amd.com
3038336Ssteve.reinhardt@amd.com# Check for style hook and prompt for installation if it's not there.
3048336Ssteve.reinhardt@amd.com# Skip this if --ignore-style was specified, there's no interactive
3058336Ssteve.reinhardt@amd.com# terminal to prompt, or no recognized revision control system can be
3065871Snate@binkert.org# found.
3075871Snate@binkert.orgignore_style = GetOption('ignore_style') or not sys.stdin.isatty()
3088336Ssteve.reinhardt@amd.com
30911408Sandreas.sandberg@arm.com# Try wire up Mercurial to the style hooks
31011408Sandreas.sandberg@arm.comif not ignore_style and hgdir.exists():
31111408Sandreas.sandberg@arm.com    style_hook = True
31211408Sandreas.sandberg@arm.com    style_hooks = tuple()
31311408Sandreas.sandberg@arm.com    hgrc = hgdir.File('hgrc')
31411408Sandreas.sandberg@arm.com    hgrc_old = hgdir.File('hgrc.old')
31511408Sandreas.sandberg@arm.com    try:
3168336Ssteve.reinhardt@amd.com        from mercurial import ui
31711401Sandreas.sandberg@arm.com        ui = ui.ui()
31811401Sandreas.sandberg@arm.com        ui.readconfig(hgrc.abspath)
31911401Sandreas.sandberg@arm.com        style_hooks = (ui.config('hooks', 'pretxncommit.style', None),
3205871Snate@binkert.org                       ui.config('hooks', 'pre-qrefresh.style', None))
3218336Ssteve.reinhardt@amd.com        style_hook = all(style_hooks)
3228336Ssteve.reinhardt@amd.com        style_extension = ui.config('extensions', 'style', None)
32311401Sandreas.sandberg@arm.com    except ImportError:
32411401Sandreas.sandberg@arm.com        print mercurial_lib_not_found
32511401Sandreas.sandberg@arm.com
32611401Sandreas.sandberg@arm.com    if "python:style.check_style" in style_hooks:
32711401Sandreas.sandberg@arm.com        # Try to upgrade the style hooks
3284678Snate@binkert.org        print mercurial_style_upgrade_message
3295871Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
3304678Snate@binkert.org        try:
33111401Sandreas.sandberg@arm.com            raw_input()
33211401Sandreas.sandberg@arm.com        except:
33311401Sandreas.sandberg@arm.com            print "Input exception, exiting scons.\n"
33411401Sandreas.sandberg@arm.com            sys.exit(1)
33511401Sandreas.sandberg@arm.com        shutil.copyfile(hgrc.abspath, hgrc_old.abspath)
33611401Sandreas.sandberg@arm.com        re_style_hook = re.compile(r"^([^=#]+)\.style\s*=\s*([^#\s]+).*")
33711401Sandreas.sandberg@arm.com        re_style_extension = re.compile("style\s*=\s*([^#\s]+).*")
33811401Sandreas.sandberg@arm.com        old, new = open(hgrc_old.abspath, 'r'), open(hgrc.abspath, 'w')
33911401Sandreas.sandberg@arm.com        for l in old:
34011401Sandreas.sandberg@arm.com            m_hook = re_style_hook.match(l)
34111401Sandreas.sandberg@arm.com            m_ext = re_style_extension.match(l)
34211401Sandreas.sandberg@arm.com            if m_hook:
34311450Sandreas.sandberg@arm.com                hook, check = m_hook.groups()
34411450Sandreas.sandberg@arm.com                if check != "python:style.check_style":
34511450Sandreas.sandberg@arm.com                    print "Warning: %s.style is using a non-default " \
34611450Sandreas.sandberg@arm.com                        "checker: %s" % (hook, check)
34711450Sandreas.sandberg@arm.com                if hook not in ("pretxncommit", "pre-qrefresh"):
34811450Sandreas.sandberg@arm.com                    print "Warning: Updating unknown style hook: %s" % hook
34911450Sandreas.sandberg@arm.com
35011450Sandreas.sandberg@arm.com                l = "%s.style = python:hgstyle.check_style\n" % hook
35111450Sandreas.sandberg@arm.com            elif m_ext and m_ext.group(1) == style_extension:
35211450Sandreas.sandberg@arm.com                l = "hgstyle = %s/util/hgstyle.py\n" % main.root.abspath
35311450Sandreas.sandberg@arm.com
35411401Sandreas.sandberg@arm.com            new.write(l)
35511450Sandreas.sandberg@arm.com    elif not style_hook:
35611450Sandreas.sandberg@arm.com        print mercurial_style_message,
35711450Sandreas.sandberg@arm.com        # continue unless user does ctrl-c/ctrl-d etc.
35811401Sandreas.sandberg@arm.com        try:
35911450Sandreas.sandberg@arm.com            raw_input()
36011401Sandreas.sandberg@arm.com        except:
3618336Ssteve.reinhardt@amd.com            print "Input exception, exiting scons.\n"
3628336Ssteve.reinhardt@amd.com            sys.exit(1)
3638336Ssteve.reinhardt@amd.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3648336Ssteve.reinhardt@amd.com        print "Adding style hook to", hgrc_path, "\n"
3658336Ssteve.reinhardt@amd.com        try:
3668336Ssteve.reinhardt@amd.com            with open(hgrc_path, 'a') as f:
3678336Ssteve.reinhardt@amd.com                f.write(mercurial_style_hook)
3688336Ssteve.reinhardt@amd.com        except:
3698336Ssteve.reinhardt@amd.com            print "Error updating", hgrc_path
3708336Ssteve.reinhardt@amd.com            sys.exit(1)
37111401Sandreas.sandberg@arm.com
37211401Sandreas.sandberg@arm.comdef install_git_style_hooks():
3738336Ssteve.reinhardt@amd.com    try:
3748336Ssteve.reinhardt@amd.com        gitdir = Dir(readCommand(
3758336Ssteve.reinhardt@amd.com            ["git", "rev-parse", "--git-dir"]).strip("\n"))
3765871Snate@binkert.org    except Exception, e:
37711476Sandreas.sandberg@arm.com        print "Warning: Failed to find git repo directory: %s" % e
37811476Sandreas.sandberg@arm.com        return
37911476Sandreas.sandberg@arm.com
38011476Sandreas.sandberg@arm.com    git_hooks = gitdir.Dir("hooks")
38111476Sandreas.sandberg@arm.com    def hook_exists(hook_name):
38211476Sandreas.sandberg@arm.com        hook = git_hooks.File(hook_name)
38311476Sandreas.sandberg@arm.com        return hook.exists()
38411476Sandreas.sandberg@arm.com
38511476Sandreas.sandberg@arm.com    def hook_install(hook_name, script):
38611887Sandreas.sandberg@arm.com        hook = git_hooks.File(hook_name)
38711887Sandreas.sandberg@arm.com        if hook.exists():
38811887Sandreas.sandberg@arm.com            print "Warning: Can't install %s, hook already exists." % hook_name
38911408Sandreas.sandberg@arm.com            return
39011887Sandreas.sandberg@arm.com
39111887Sandreas.sandberg@arm.com        if hook.islink():
39211887Sandreas.sandberg@arm.com            print "Warning: Removing broken symlink for hook %s." % hook_name
39311887Sandreas.sandberg@arm.com            os.unlink(hook.get_abspath())
39411887Sandreas.sandberg@arm.com
39511887Sandreas.sandberg@arm.com        if not git_hooks.exists():
39611926Sgabeblack@google.com            mkdir(git_hooks.get_abspath())
39711926Sgabeblack@google.com            git_hooks.clear()
39811926Sgabeblack@google.com
39911926Sgabeblack@google.com        abs_symlink_hooks = git_hooks.islink() and \
40011887Sandreas.sandberg@arm.com            os.path.isabs(os.readlink(git_hooks.get_abspath()))
40111887Sandreas.sandberg@arm.com
40211944Sandreas.sandberg@arm.com        # Use a relative symlink if the hooks live in the source directory,
40311887Sandreas.sandberg@arm.com        # and the hooks directory is not a symlink to an absolute path.
40411927Sgabeblack@google.com        if hook.is_under(main.root) and not abs_symlink_hooks:
40511927Sgabeblack@google.com            script_path = os.path.relpath(
40611927Sgabeblack@google.com                os.path.realpath(script.get_abspath()),
40711927Sgabeblack@google.com                os.path.realpath(hook.Dir(".").get_abspath()))
40811927Sgabeblack@google.com        else:
40911927Sgabeblack@google.com            script_path = script.get_abspath()
41011887Sandreas.sandberg@arm.com
41111928Sgabeblack@google.com        try:
41211928Sgabeblack@google.com            os.symlink(script_path, hook.get_abspath())
41311887Sandreas.sandberg@arm.com        except:
41411887Sandreas.sandberg@arm.com            print "Error updating git %s hook" % hook_name
41511887Sandreas.sandberg@arm.com            raise
41611887Sandreas.sandberg@arm.com
41711887Sandreas.sandberg@arm.com    if hook_exists("pre-commit") and hook_exists("commit-msg"):
41811887Sandreas.sandberg@arm.com        return
41911887Sandreas.sandberg@arm.com
42011887Sandreas.sandberg@arm.com    print git_style_message,
42111887Sandreas.sandberg@arm.com    try:
42211887Sandreas.sandberg@arm.com        raw_input()
42311476Sandreas.sandberg@arm.com    except:
42411476Sandreas.sandberg@arm.com        print "Input exception, exiting scons.\n"
42511408Sandreas.sandberg@arm.com        sys.exit(1)
42611408Sandreas.sandberg@arm.com
42711408Sandreas.sandberg@arm.com    git_style_script = File("util/git-pre-commit.py")
42811408Sandreas.sandberg@arm.com    git_msg_script = File("ext/git-commit-msg")
42911408Sandreas.sandberg@arm.com
43011408Sandreas.sandberg@arm.com    hook_install("pre-commit", git_style_script)
43111408Sandreas.sandberg@arm.com    hook_install("commit-msg", git_msg_script)
43211887Sandreas.sandberg@arm.com
43311887Sandreas.sandberg@arm.com# Try to wire up git to the style hooks
43411476Sandreas.sandberg@arm.comif not ignore_style and main.root.Entry(".git").exists():
43511887Sandreas.sandberg@arm.com    install_git_style_hooks()
43611887Sandreas.sandberg@arm.com
43711476Sandreas.sandberg@arm.com###################################################
43811476Sandreas.sandberg@arm.com#
43911476Sandreas.sandberg@arm.com# Figure out which configurations to set up based on the path(s) of
44011476Sandreas.sandberg@arm.com# the target(s).
4416121Snate@binkert.org#
442955SN/A###################################################
443955SN/A
4442632Sstever@eecs.umich.edu# Find default configuration & binary.
4452632Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
446955SN/A
447955SN/A# helper function: find last occurrence of element in list
448955SN/Adef rfind(l, elt, offs = -1):
449955SN/A    for i in range(len(l)+offs, 0, -1):
4508878Ssteve.reinhardt@amd.com        if l[i] == elt:
451955SN/A            return i
4522632Sstever@eecs.umich.edu    raise ValueError, "element not found"
4532632Sstever@eecs.umich.edu
4542632Sstever@eecs.umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
4552632Sstever@eecs.umich.edu# paths made absolute and ~-expanded.  Paths will be interpreted
4562632Sstever@eecs.umich.edu# relative to the launch directory unless a different root is provided
4572632Sstever@eecs.umich.edudef makePathListAbsolute(path_list, root=GetLaunchDir()):
4582632Sstever@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
4598268Ssteve.reinhardt@amd.com            for p in path_list]
4608268Ssteve.reinhardt@amd.com
4618268Ssteve.reinhardt@amd.com# Each target must have 'build' in the interior of the path; the
4628268Ssteve.reinhardt@amd.com# directory below this will determine the build parameters.  For
4638268Ssteve.reinhardt@amd.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
4648268Ssteve.reinhardt@amd.com# recognize that ALPHA_SE specifies the configuration because it
4658268Ssteve.reinhardt@amd.com# follow 'build' in the build path.
4662632Sstever@eecs.umich.edu
4672632Sstever@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
4682632Sstever@eecs.umich.edu# in place rather than reassign the symbol to a new list, which
4692632Sstever@eecs.umich.edu# doesn't work (obviously!).
4708268Ssteve.reinhardt@amd.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
4712632Sstever@eecs.umich.edu
4728268Ssteve.reinhardt@amd.com# Generate a list of the unique build roots and configs that the
4738268Ssteve.reinhardt@amd.com# collected targets reference.
4748268Ssteve.reinhardt@amd.comvariant_paths = []
4758268Ssteve.reinhardt@amd.combuild_root = None
4763718Sstever@eecs.umich.edufor t in BUILD_TARGETS:
4772634Sstever@eecs.umich.edu    path_dirs = t.split('/')
4782634Sstever@eecs.umich.edu    try:
4795863Snate@binkert.org        build_top = rfind(path_dirs, 'build', -2)
4802638Sstever@eecs.umich.edu    except:
4818268Ssteve.reinhardt@amd.com        print "Error: no non-leaf 'build' dir found on target path", t
4822632Sstever@eecs.umich.edu        Exit(1)
4832632Sstever@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
4842632Sstever@eecs.umich.edu    if not build_root:
4852632Sstever@eecs.umich.edu        build_root = this_build_root
4862632Sstever@eecs.umich.edu    else:
4871858SN/A        if this_build_root != build_root:
4883716Sstever@eecs.umich.edu            print "Error: build targets not under same build root\n"\
4892638Sstever@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
4902638Sstever@eecs.umich.edu            Exit(1)
4912638Sstever@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
4922638Sstever@eecs.umich.edu    if variant_path not in variant_paths:
4932638Sstever@eecs.umich.edu        variant_paths.append(variant_path)
4942638Sstever@eecs.umich.edu
4952638Sstever@eecs.umich.edu# Make sure build_root exists (might not if this is the first build there)
4965863Snate@binkert.orgif not isdir(build_root):
4975863Snate@binkert.org    mkdir(build_root)
4985863Snate@binkert.orgmain['BUILDROOT'] = build_root
499955SN/A
5005341Sstever@gmail.comExport('main')
5015341Sstever@gmail.com
5025863Snate@binkert.orgmain.SConsignFile(joinpath(build_root, "sconsign"))
5037756SAli.Saidi@ARM.com
5045341Sstever@gmail.com# Default duplicate option is to use hard links, but this messes up
5056121Snate@binkert.org# when you use emacs to edit a file in the target dir, as emacs moves
5064494Ssaidi@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
5076121Snate@binkert.org# (soft) links work better.
5081105SN/Amain.SetOption('duplicate', 'soft-copy')
5092667Sstever@eecs.umich.edu
5102667Sstever@eecs.umich.edu#
5112667Sstever@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
5122667Sstever@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
5136121Snate@binkert.org#
5142667Sstever@eecs.umich.edu
5155341Sstever@gmail.comglobal_vars_file = joinpath(build_root, 'variables.global')
5165863Snate@binkert.org
5175341Sstever@gmail.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
5185341Sstever@gmail.com
5195341Sstever@gmail.comglobal_vars.AddVariables(
5208120Sgblack@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
5215341Sstever@gmail.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
5228120Sgblack@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
5235341Sstever@gmail.com    ('BATCH', 'Use batch pool for build and tests', False),
5248120Sgblack@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
5256121Snate@binkert.org    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
5266121Snate@binkert.org    ('EXTRAS', 'Add extra directories to the compilation', '')
5278980Ssteve.reinhardt@amd.com    )
5289396Sandreas.hansson@arm.com
5295397Ssaidi@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
5305397Ssaidi@eecs.umich.eduglobal_vars.Update(main)
5317727SAli.Saidi@ARM.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
5328268Ssteve.reinhardt@amd.com
5336168Snate@binkert.org# Save sticky variable settings back to current variables file
5345341Sstever@gmail.comglobal_vars.Save(global_vars_file, main)
5358120Sgblack@eecs.umich.edu
5368120Sgblack@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
5378120Sgblack@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
5386814Sgblack@eecs.umich.edubase_dir = main.srcdir.abspath
5395863Snate@binkert.orgif main['EXTRAS']:
5408120Sgblack@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
5415341Sstever@gmail.comelse:
5425863Snate@binkert.org    extras_dir_list = []
5438268Ssteve.reinhardt@amd.com
5446121Snate@binkert.orgExport('base_dir')
5456121Snate@binkert.orgExport('extras_dir_list')
5468268Ssteve.reinhardt@amd.com
5475742Snate@binkert.org# the ext directory should be on the #includes path
5485742Snate@binkert.orgmain.Append(CPPPATH=[Dir('ext')])
5495341Sstever@gmail.com
5505742Snate@binkert.orgdef strip_build_path(path, env):
5515742Snate@binkert.org    path = str(path)
5525341Sstever@gmail.com    variant_base = env['BUILDROOT'] + os.path.sep
5536017Snate@binkert.org    if path.startswith(variant_base):
5546121Snate@binkert.org        path = path[len(variant_base):]
5556017Snate@binkert.org    elif path.startswith('build/'):
5567816Ssteve.reinhardt@amd.com        path = path[6:]
5577756SAli.Saidi@ARM.com    return path
5587756SAli.Saidi@ARM.com
5597756SAli.Saidi@ARM.com# Generate a string of the form:
5607756SAli.Saidi@ARM.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
5617756SAli.Saidi@ARM.com# to print while building.
5627756SAli.Saidi@ARM.comclass Transform(object):
5637756SAli.Saidi@ARM.com    # all specific color settings should be here and nowhere else
5647756SAli.Saidi@ARM.com    tool_color = termcap.Normal
5657816Ssteve.reinhardt@amd.com    pfx_color = termcap.Yellow
5667816Ssteve.reinhardt@amd.com    srcs_color = termcap.Yellow + termcap.Bold
5677816Ssteve.reinhardt@amd.com    arrow_color = termcap.Blue + termcap.Bold
5687816Ssteve.reinhardt@amd.com    tgts_color = termcap.Yellow + termcap.Bold
5697816Ssteve.reinhardt@amd.com
5707816Ssteve.reinhardt@amd.com    def __init__(self, tool, max_sources=99):
5717816Ssteve.reinhardt@amd.com        self.format = self.tool_color + (" [%8s] " % tool) \
5727816Ssteve.reinhardt@amd.com                      + self.pfx_color + "%s" \
5737816Ssteve.reinhardt@amd.com                      + self.srcs_color + "%s" \
5747816Ssteve.reinhardt@amd.com                      + self.arrow_color + " -> " \
5757756SAli.Saidi@ARM.com                      + self.tgts_color + "%s" \
5767816Ssteve.reinhardt@amd.com                      + termcap.Normal
5777816Ssteve.reinhardt@amd.com        self.max_sources = max_sources
5787816Ssteve.reinhardt@amd.com
5797816Ssteve.reinhardt@amd.com    def __call__(self, target, source, env, for_signature=None):
5807816Ssteve.reinhardt@amd.com        # truncate source list according to max_sources param
5817816Ssteve.reinhardt@amd.com        source = source[0:self.max_sources]
5827816Ssteve.reinhardt@amd.com        def strip(f):
5837816Ssteve.reinhardt@amd.com            return strip_build_path(str(f), env)
5847816Ssteve.reinhardt@amd.com        if len(source) > 0:
5857816Ssteve.reinhardt@amd.com            srcs = map(strip, source)
5867816Ssteve.reinhardt@amd.com        else:
5877816Ssteve.reinhardt@amd.com            srcs = ['']
5887816Ssteve.reinhardt@amd.com        tgts = map(strip, target)
5897816Ssteve.reinhardt@amd.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
5907816Ssteve.reinhardt@amd.com        # operation that has nothing to do with paths.
5917816Ssteve.reinhardt@amd.com        com_pfx = os.path.commonprefix(srcs + tgts)
5927816Ssteve.reinhardt@amd.com        com_pfx_len = len(com_pfx)
5937816Ssteve.reinhardt@amd.com        if com_pfx:
5947816Ssteve.reinhardt@amd.com            # do some cleanup and sanity checking on common prefix
5957816Ssteve.reinhardt@amd.com            if com_pfx[-1] == ".":
5967816Ssteve.reinhardt@amd.com                # prefix matches all but file extension: ok
5977816Ssteve.reinhardt@amd.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
5987816Ssteve.reinhardt@amd.com                com_pfx = com_pfx[0:-1]
5997816Ssteve.reinhardt@amd.com            elif com_pfx[-1] == "/":
6007816Ssteve.reinhardt@amd.com                # common prefix is directory path: OK
6017816Ssteve.reinhardt@amd.com                pass
6027816Ssteve.reinhardt@amd.com            else:
6037816Ssteve.reinhardt@amd.com                src0_len = len(srcs[0])
6047816Ssteve.reinhardt@amd.com                tgt0_len = len(tgts[0])
6057816Ssteve.reinhardt@amd.com                if src0_len == com_pfx_len:
6067816Ssteve.reinhardt@amd.com                    # source is a substring of target, OK
6077816Ssteve.reinhardt@amd.com                    pass
6087816Ssteve.reinhardt@amd.com                elif tgt0_len == com_pfx_len:
6097816Ssteve.reinhardt@amd.com                    # target is a substring of source, need to back up to
6107816Ssteve.reinhardt@amd.com                    # avoid empty string on RHS of arrow
6117816Ssteve.reinhardt@amd.com                    sep_idx = com_pfx.rfind(".")
6127816Ssteve.reinhardt@amd.com                    if sep_idx != -1:
6137816Ssteve.reinhardt@amd.com                        com_pfx = com_pfx[0:sep_idx]
6147816Ssteve.reinhardt@amd.com                    else:
6157816Ssteve.reinhardt@amd.com                        com_pfx = ''
6167816Ssteve.reinhardt@amd.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
6177816Ssteve.reinhardt@amd.com                    # still splitting at file extension: ok
6187816Ssteve.reinhardt@amd.com                    pass
6197816Ssteve.reinhardt@amd.com                else:
6207816Ssteve.reinhardt@amd.com                    # probably a fluke; ignore it
6217816Ssteve.reinhardt@amd.com                    com_pfx = ''
6227816Ssteve.reinhardt@amd.com        # recalculate length in case com_pfx was modified
6237816Ssteve.reinhardt@amd.com        com_pfx_len = len(com_pfx)
6247816Ssteve.reinhardt@amd.com        def fmt(files):
6257816Ssteve.reinhardt@amd.com            f = map(lambda s: s[com_pfx_len:], files)
6267816Ssteve.reinhardt@amd.com            return ', '.join(f)
6277816Ssteve.reinhardt@amd.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
6287816Ssteve.reinhardt@amd.com
6297816Ssteve.reinhardt@amd.comExport('Transform')
6307816Ssteve.reinhardt@amd.com
6317816Ssteve.reinhardt@amd.com# enable the regression script to use the termcap
6327816Ssteve.reinhardt@amd.commain['TERMCAP'] = termcap
6337816Ssteve.reinhardt@amd.com
6347816Ssteve.reinhardt@amd.comif GetOption('verbose'):
6357816Ssteve.reinhardt@amd.com    def MakeAction(action, string, *args, **kwargs):
6367816Ssteve.reinhardt@amd.com        return Action(action, *args, **kwargs)
6378947Sandreas.hansson@arm.comelse:
6388947Sandreas.hansson@arm.com    MakeAction = Action
6397756SAli.Saidi@ARM.com    main['CCCOMSTR']        = Transform("CC")
6408120Sgblack@eecs.umich.edu    main['CXXCOMSTR']       = Transform("CXX")
6417756SAli.Saidi@ARM.com    main['ASCOMSTR']        = Transform("AS")
6427756SAli.Saidi@ARM.com    main['ARCOMSTR']        = Transform("AR", 0)
6437756SAli.Saidi@ARM.com    main['LINKCOMSTR']      = Transform("LINK", 0)
6447756SAli.Saidi@ARM.com    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
6457816Ssteve.reinhardt@amd.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
6467816Ssteve.reinhardt@amd.com    main['M4COMSTR']        = Transform("M4")
6477816Ssteve.reinhardt@amd.com    main['SHCCCOMSTR']      = Transform("SHCC")
6487816Ssteve.reinhardt@amd.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
6497816Ssteve.reinhardt@amd.comExport('MakeAction')
6507816Ssteve.reinhardt@amd.com
65111979Sgabeblack@google.com# Initialize the Link-Time Optimization (LTO) flags
6527816Ssteve.reinhardt@amd.commain['LTO_CCFLAGS'] = []
6537816Ssteve.reinhardt@amd.commain['LTO_LDFLAGS'] = []
6547816Ssteve.reinhardt@amd.com
6557816Ssteve.reinhardt@amd.com# According to the readme, tcmalloc works best if the compiler doesn't
6567756SAli.Saidi@ARM.com# assume that we're using the builtin malloc and friends. These flags
6577756SAli.Saidi@ARM.com# are compiler-specific, so we need to set them after we detect which
6589227Sandreas.hansson@arm.com# compiler we're using.
6599227Sandreas.hansson@arm.commain['TCMALLOC_CCFLAGS'] = []
6609227Sandreas.hansson@arm.com
6619227Sandreas.hansson@arm.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
6629590Sandreas@sandberg.pp.seCXX_V = readCommand([main['CXX'],'-V'], exception=False)
6639590Sandreas@sandberg.pp.se
6649590Sandreas@sandberg.pp.semain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
6659590Sandreas@sandberg.pp.semain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
6669590Sandreas@sandberg.pp.seif main['GCC'] + main['CLANG'] > 1:
6679590Sandreas@sandberg.pp.se    print 'Error: How can we have two at the same time?'
6686654Snate@binkert.org    Exit(1)
6696654Snate@binkert.org
6705871Snate@binkert.org# Set up default C++ compiler flags
6716121Snate@binkert.orgif main['GCC'] or main['CLANG']:
6728946Sandreas.hansson@arm.com    # As gcc and clang share many flags, do the common parts here
6739419Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-pipe'])
6743940Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
6753918Ssaidi@eecs.umich.edu    # Enable -Wall and -Wextra and then disable the few warnings that
6763918Ssaidi@eecs.umich.edu    # we consistently violate
6771858SN/A    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
6789556Sandreas.hansson@arm.com                         '-Wno-sign-compare', '-Wno-unused-parameter'])
6799556Sandreas.hansson@arm.com    # We always compile using C++11
6809556Sandreas.hansson@arm.com    main.Append(CXXFLAGS=['-std=c++11'])
6819556Sandreas.hansson@arm.com    if sys.platform.startswith('freebsd'):
68211294Sandreas.hansson@arm.com        main.Append(CCFLAGS=['-I/usr/local/include'])
68311294Sandreas.hansson@arm.com        main.Append(CXXFLAGS=['-I/usr/local/include'])
68411294Sandreas.hansson@arm.com
68511294Sandreas.hansson@arm.com    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
68610878Sandreas.hansson@arm.com    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
68710878Sandreas.hansson@arm.com    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
68811811Sbaz21@cam.ac.uk    shared_partial_flags = ['-r', '-nostdlib']
68911811Sbaz21@cam.ac.uk    main.Append(PSHLINKFLAGS=shared_partial_flags)
69011811Sbaz21@cam.ac.uk    main.Append(PLINKFLAGS=shared_partial_flags)
69111982Sgabeblack@google.comelse:
69211982Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
69311982Sgabeblack@google.com    print "Don't know what compiler options to use for your compiler."
69411982Sgabeblack@google.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
69511982Sgabeblack@google.com    print termcap.Yellow + '       version:' + termcap.Normal,
69611982Sgabeblack@google.com    if not CXX_version:
69711982Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6989556Sandreas.hansson@arm.com               termcap.Normal
6999556Sandreas.hansson@arm.com    else:
7009556Sandreas.hansson@arm.com        print CXX_version.replace('\n', '<nl>')
7019556Sandreas.hansson@arm.com    print "       If you're trying to use a compiler other than GCC"
7029556Sandreas.hansson@arm.com    print "       or clang, there appears to be something wrong with your"
7039556Sandreas.hansson@arm.com    print "       environment."
7049556Sandreas.hansson@arm.com    print "       "
7059556Sandreas.hansson@arm.com    print "       If you are trying to use a compiler other than those listed"
7069556Sandreas.hansson@arm.com    print "       above you will need to ease fix SConstruct and "
7079556Sandreas.hansson@arm.com    print "       src/SConscript to support that compiler."
7089556Sandreas.hansson@arm.com    Exit(1)
7099556Sandreas.hansson@arm.com
7109556Sandreas.hansson@arm.comif main['GCC']:
7119556Sandreas.hansson@arm.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
7129556Sandreas.hansson@arm.com    # level of c++11 support. See
7139556Sandreas.hansson@arm.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
7149556Sandreas.hansson@arm.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
7159556Sandreas.hansson@arm.com    if compareVersions(gcc_version, "4.8") < 0:
7169556Sandreas.hansson@arm.com        print 'Error: gcc version 4.8 or newer required.'
7176121Snate@binkert.org        print '       Installed version:', gcc_version
71811500Sandreas.hansson@arm.com        Exit(1)
71910238Sandreas.hansson@arm.com
72010878Sandreas.hansson@arm.com    main['GCC_VERSION'] = gcc_version
7219420Sandreas.hansson@arm.com
72211500Sandreas.hansson@arm.com    # gcc from version 4.8 and above generates "rep; ret" instructions
72311500Sandreas.hansson@arm.com    # to avoid performance penalties on certain AMD chips. Older
7249420Sandreas.hansson@arm.com    # assemblers detect this as an error, "Error: expecting string
7259420Sandreas.hansson@arm.com    # instruction after `rep'"
7269420Sandreas.hansson@arm.com    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
7279420Sandreas.hansson@arm.com                                  '-o', '/dev/null'],
7289420Sandreas.hansson@arm.com                                 exception=False).split()
72910264Sandreas.hansson@arm.com
73010264Sandreas.hansson@arm.com    # version strings may contain extra distro-specific
73110264Sandreas.hansson@arm.com    # qualifiers, so play it safe and keep only what comes before
73210264Sandreas.hansson@arm.com    # the first hyphen
73311925Sgabeblack@google.com    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
73411925Sgabeblack@google.com
73511500Sandreas.hansson@arm.com    if not as_version or compareVersions(as_version, "2.23") < 0:
73610264Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + \
73711500Sandreas.hansson@arm.com            'Warning: This combination of gcc and binutils have' + \
73811500Sandreas.hansson@arm.com            ' known incompatibilities.\n' + \
73911500Sandreas.hansson@arm.com            '         If you encounter build problems, please update ' + \
74011500Sandreas.hansson@arm.com            'binutils to 2.23.' + \
74110866Sandreas.hansson@arm.com            termcap.Normal
74211500Sandreas.hansson@arm.com
74311500Sandreas.hansson@arm.com    # Make sure we warn if the user has requested to compile with the
74411500Sandreas.hansson@arm.com    # Undefined Benahvior Sanitizer and this version of gcc does not
74511500Sandreas.hansson@arm.com    # support it.
74611500Sandreas.hansson@arm.com    if GetOption('with_ubsan') and \
74711500Sandreas.hansson@arm.com            compareVersions(gcc_version, '4.9') < 0:
74811500Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + \
74910264Sandreas.hansson@arm.com            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
75010457Sandreas.hansson@arm.com            termcap.Normal
75110457Sandreas.hansson@arm.com
75210457Sandreas.hansson@arm.com    # Add the appropriate Link-Time Optimization (LTO) flags
75310457Sandreas.hansson@arm.com    # unless LTO is explicitly turned off. Note that these flags
75410457Sandreas.hansson@arm.com    # are only used by the fast target.
75510457Sandreas.hansson@arm.com    if not GetOption('no_lto'):
75610457Sandreas.hansson@arm.com        # Pass the LTO flag when compiling to produce GIMPLE
75710457Sandreas.hansson@arm.com        # output, we merely create the flags here and only append
75810457Sandreas.hansson@arm.com        # them later
75910238Sandreas.hansson@arm.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
76010238Sandreas.hansson@arm.com
76110238Sandreas.hansson@arm.com        # Use the same amount of jobs for LTO as we are running
76210238Sandreas.hansson@arm.com        # scons with
76310238Sandreas.hansson@arm.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
76410238Sandreas.hansson@arm.com
76510416Sandreas.hansson@arm.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
76610238Sandreas.hansson@arm.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
7679227Sandreas.hansson@arm.com
76810238Sandreas.hansson@arm.com    # add option to check for undeclared overrides
76910416Sandreas.hansson@arm.com    if compareVersions(gcc_version, "5.0") > 0:
77010416Sandreas.hansson@arm.com        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
7719227Sandreas.hansson@arm.com
7729590Sandreas@sandberg.pp.seelif main['CLANG']:
7739590Sandreas@sandberg.pp.se    # Check for a supported version of clang, >= 3.1 is needed to
7749590Sandreas@sandberg.pp.se    # support similar features as gcc 4.8. See
77511497SMatteo.Andreozzi@arm.com    # http://clang.llvm.org/cxx_status.html for details
77611497SMatteo.Andreozzi@arm.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
77711497SMatteo.Andreozzi@arm.com    clang_version_match = clang_version_re.search(CXX_version)
77811497SMatteo.Andreozzi@arm.com    if (clang_version_match):
7798737Skoansin.tan@gmail.com        clang_version = clang_version_match.groups()[0]
78010878Sandreas.hansson@arm.com        if compareVersions(clang_version, "3.1") < 0:
78111500Sandreas.hansson@arm.com            print 'Error: clang version 3.1 or newer required.'
7829420Sandreas.hansson@arm.com            print '       Installed version:', clang_version
7838737Skoansin.tan@gmail.com            Exit(1)
78410106SMitch.Hayenga@arm.com    else:
7858737Skoansin.tan@gmail.com        print 'Error: Unable to determine clang version.'
7868737Skoansin.tan@gmail.com        Exit(1)
78710878Sandreas.hansson@arm.com
78810878Sandreas.hansson@arm.com    # clang has a few additional warnings that we disable, extraneous
7898737Skoansin.tan@gmail.com    # parantheses are allowed due to Ruby's printing of the AST,
7908737Skoansin.tan@gmail.com    # finally self assignments are allowed as the generated CPU code
7918737Skoansin.tan@gmail.com    # is relying on this
7928737Skoansin.tan@gmail.com    main.Append(CCFLAGS=['-Wno-parentheses',
7938737Skoansin.tan@gmail.com                         '-Wno-self-assign',
7948737Skoansin.tan@gmail.com                         # Some versions of libstdc++ (4.8?) seem to
79511294Sandreas.hansson@arm.com                         # use struct hash and class hash
7969556Sandreas.hansson@arm.com                         # interchangeably.
7979556Sandreas.hansson@arm.com                         '-Wno-mismatched-tags',
7989556Sandreas.hansson@arm.com                         ])
79911294Sandreas.hansson@arm.com
80010278SAndreas.Sandberg@ARM.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
80110278SAndreas.Sandberg@ARM.com
80210278SAndreas.Sandberg@ARM.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
80310278SAndreas.Sandberg@ARM.com    # opposed to libstdc++, as the later is dated.
80410278SAndreas.Sandberg@ARM.com    if sys.platform == "darwin":
80510278SAndreas.Sandberg@ARM.com        main.Append(CXXFLAGS=['-stdlib=libc++'])
8069556Sandreas.hansson@arm.com        main.Append(LIBS=['c++'])
8079590Sandreas@sandberg.pp.se
8089590Sandreas@sandberg.pp.se    # On FreeBSD we need libthr.
8099420Sandreas.hansson@arm.com    if sys.platform.startswith('freebsd'):
8109846Sandreas.hansson@arm.com        main.Append(LIBS=['thr'])
8119846Sandreas.hansson@arm.com
8129846Sandreas.hansson@arm.comelse:
8139846Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
8148946Sandreas.hansson@arm.com    print "Don't know what compiler options to use for your compiler."
81511811Sbaz21@cam.ac.uk    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
81611811Sbaz21@cam.ac.uk    print termcap.Yellow + '       version:' + termcap.Normal,
81711811Sbaz21@cam.ac.uk    if not CXX_version:
81811811Sbaz21@cam.ac.uk        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
8193918Ssaidi@eecs.umich.edu               termcap.Normal
8209068SAli.Saidi@ARM.com    else:
8219068SAli.Saidi@ARM.com        print CXX_version.replace('\n', '<nl>')
8229068SAli.Saidi@ARM.com    print "       If you're trying to use a compiler other than GCC"
8239068SAli.Saidi@ARM.com    print "       or clang, there appears to be something wrong with your"
8249068SAli.Saidi@ARM.com    print "       environment."
8259068SAli.Saidi@ARM.com    print "       "
8269068SAli.Saidi@ARM.com    print "       If you are trying to use a compiler other than those listed"
8279068SAli.Saidi@ARM.com    print "       above you will need to ease fix SConstruct and "
8289068SAli.Saidi@ARM.com    print "       src/SConscript to support that compiler."
8299419Sandreas.hansson@arm.com    Exit(1)
8309068SAli.Saidi@ARM.com
8319068SAli.Saidi@ARM.com# Set up common yacc/bison flags (needed for Ruby)
8329068SAli.Saidi@ARM.commain['YACCFLAGS'] = '-d'
8339068SAli.Saidi@ARM.commain['YACCHXXFILESUFFIX'] = '.hh'
8349068SAli.Saidi@ARM.com
8359068SAli.Saidi@ARM.com# Do this after we save setting back, or else we'll tack on an
8363918Ssaidi@eecs.umich.edu# extra 'qdo' every time we run scons.
8373918Ssaidi@eecs.umich.eduif main['BATCH']:
8386157Snate@binkert.org    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
8396157Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
8406157Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
8416157Snate@binkert.org    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
8425397Ssaidi@eecs.umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
8435397Ssaidi@eecs.umich.edu
8446121Snate@binkert.orgif sys.platform == 'cygwin':
8456121Snate@binkert.org    # cygwin has some header file issues...
8466121Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
8476121Snate@binkert.org
8486121Snate@binkert.org# Check for the protobuf compiler
8496121Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
8505397Ssaidi@eecs.umich.edu                             exception='').split()
8511851SN/A
8521851SN/A# First two words should be "libprotoc x.y.z"
8537739Sgblack@eecs.umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
854955SN/A    print termcap.Yellow + termcap.Bold + \
8559396Sandreas.hansson@arm.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
8569396Sandreas.hansson@arm.com        '         Please install protobuf-compiler for tracing support.' + \
8579396Sandreas.hansson@arm.com        termcap.Normal
8589396Sandreas.hansson@arm.com    main['PROTOC'] = False
8599396Sandreas.hansson@arm.comelse:
8609396Sandreas.hansson@arm.com    # Based on the availability of the compress stream wrappers,
8619396Sandreas.hansson@arm.com    # require 2.1.0
8629396Sandreas.hansson@arm.com    min_protoc_version = '2.1.0'
8639396Sandreas.hansson@arm.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
8649396Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + \
8659396Sandreas.hansson@arm.com            'Warning: protoc version', min_protoc_version, \
8669396Sandreas.hansson@arm.com            'or newer required.\n' + \
8679396Sandreas.hansson@arm.com            '         Installed version:', protoc_version[1], \
8689396Sandreas.hansson@arm.com            termcap.Normal
8699396Sandreas.hansson@arm.com        main['PROTOC'] = False
8709396Sandreas.hansson@arm.com    else:
8719477Sandreas.hansson@arm.com        # Attempt to determine the appropriate include path and
8729477Sandreas.hansson@arm.com        # library path using pkg-config, that means we also need to
8739477Sandreas.hansson@arm.com        # check for pkg-config. Note that it is possible to use
8749477Sandreas.hansson@arm.com        # protobuf without the involvement of pkg-config. Later on we
8759477Sandreas.hansson@arm.com        # check go a library config check and at that point the test
8769477Sandreas.hansson@arm.com        # will fail if libprotobuf cannot be found.
8779477Sandreas.hansson@arm.com        if readCommand(['pkg-config', '--version'], exception=''):
8789477Sandreas.hansson@arm.com            try:
8799477Sandreas.hansson@arm.com                # Attempt to establish what linking flags to add for protobuf
8809477Sandreas.hansson@arm.com                # using pkg-config
8819477Sandreas.hansson@arm.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
8829477Sandreas.hansson@arm.com            except:
8839477Sandreas.hansson@arm.com                print termcap.Yellow + termcap.Bold + \
8849477Sandreas.hansson@arm.com                    'Warning: pkg-config could not get protobuf flags.' + \
8859477Sandreas.hansson@arm.com                    termcap.Normal
8869477Sandreas.hansson@arm.com
8879477Sandreas.hansson@arm.com
8889477Sandreas.hansson@arm.com# Check for 'timeout' from GNU coreutils. If present, regressions will
8899477Sandreas.hansson@arm.com# be run with a time limit. We require version 8.13 since we rely on
8909477Sandreas.hansson@arm.com# support for the '--foreground' option.
8919477Sandreas.hansson@arm.comif sys.platform.startswith('freebsd'):
8929477Sandreas.hansson@arm.com    timeout_lines = readCommand(['gtimeout', '--version'],
8939396Sandreas.hansson@arm.com                                exception='').splitlines()
8943053Sstever@eecs.umich.eduelse:
8956121Snate@binkert.org    timeout_lines = readCommand(['timeout', '--version'],
8963053Sstever@eecs.umich.edu                                exception='').splitlines()
8973053Sstever@eecs.umich.edu# Get the first line and tokenize it
8983053Sstever@eecs.umich.edutimeout_version = timeout_lines[0].split() if timeout_lines else []
8993053Sstever@eecs.umich.edumain['TIMEOUT'] =  timeout_version and \
9003053Sstever@eecs.umich.edu    compareVersions(timeout_version[-1], '8.13') >= 0
9019072Sandreas.hansson@arm.com
9023053Sstever@eecs.umich.edu# Add a custom Check function to test for structure members.
9034742Sstever@eecs.umich.edudef CheckMember(context, include, decl, member, include_quotes="<>"):
9044742Sstever@eecs.umich.edu    context.Message("Checking for member %s in %s..." %
9053053Sstever@eecs.umich.edu                    (member, decl))
9063053Sstever@eecs.umich.edu    text = """
9073053Sstever@eecs.umich.edu#include %(header)s
90810181SCurtis.Dunham@arm.comint main(){
9096654Snate@binkert.org  %(decl)s test;
9103053Sstever@eecs.umich.edu  (void)test.%(member)s;
9113053Sstever@eecs.umich.edu  return 0;
9123053Sstever@eecs.umich.edu};
9133053Sstever@eecs.umich.edu""" % { "header" : include_quotes[0] + include + include_quotes[1],
91410425Sandreas.hansson@arm.com        "decl" : decl,
91510425Sandreas.hansson@arm.com        "member" : member,
91610425Sandreas.hansson@arm.com        }
91710425Sandreas.hansson@arm.com
91810425Sandreas.hansson@arm.com    ret = context.TryCompile(text, extension=".cc")
91910425Sandreas.hansson@arm.com    context.Result(ret)
92010425Sandreas.hansson@arm.com    return ret
92110425Sandreas.hansson@arm.com
92210425Sandreas.hansson@arm.com# Platform-specific configuration.  Note again that we assume that all
92310425Sandreas.hansson@arm.com# builds under a given build root run on the same host platform.
92410425Sandreas.hansson@arm.comconf = Configure(main,
9252667Sstever@eecs.umich.edu                 conf_dir = joinpath(build_root, '.scons_config'),
9264554Sbinkertn@umich.edu                 log_file = joinpath(build_root, 'scons_config.log'),
9276121Snate@binkert.org                 custom_tests = {
9282667Sstever@eecs.umich.edu        'CheckMember' : CheckMember,
92910710Sandreas.hansson@arm.com        })
93010710Sandreas.hansson@arm.com
93110710Sandreas.hansson@arm.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
93211811Sbaz21@cam.ac.uktry:
93311811Sbaz21@cam.ac.uk    import platform
93411811Sbaz21@cam.ac.uk    uname = platform.uname()
93511811Sbaz21@cam.ac.uk    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
93611811Sbaz21@cam.ac.uk        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
93711811Sbaz21@cam.ac.uk            main.Append(CCFLAGS=['-arch', 'x86_64'])
93810710Sandreas.hansson@arm.com            main.Append(CFLAGS=['-arch', 'x86_64'])
93910710Sandreas.hansson@arm.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
94010710Sandreas.hansson@arm.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
94110710Sandreas.hansson@arm.comexcept:
94210384SCurtis.Dunham@arm.com    pass
9434554Sbinkertn@umich.edu
9444554Sbinkertn@umich.edu# Recent versions of scons substitute a "Null" object for Configure()
9454554Sbinkertn@umich.edu# when configuration isn't necessary, e.g., if the "--help" option is
9466121Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
9474554Sbinkertn@umich.edu# breaking all our configuration checks.  We replace it with our own
9484554Sbinkertn@umich.edu# more optimistic null object that returns True instead.
9494554Sbinkertn@umich.eduif not conf:
9504781Snate@binkert.org    def NullCheck(*args, **kwargs):
9514554Sbinkertn@umich.edu        return True
9524554Sbinkertn@umich.edu
9532667Sstever@eecs.umich.edu    class NullConf:
9544554Sbinkertn@umich.edu        def __init__(self, env):
9554554Sbinkertn@umich.edu            self.env = env
9564554Sbinkertn@umich.edu        def Finish(self):
9574554Sbinkertn@umich.edu            return self.env
9582667Sstever@eecs.umich.edu        def __getattr__(self, mname):
9594554Sbinkertn@umich.edu            return NullCheck
9602667Sstever@eecs.umich.edu
9614554Sbinkertn@umich.edu    conf = NullConf(main)
9626121Snate@binkert.org
9632667Sstever@eecs.umich.edu# Cache build files in the supplied directory.
9649986Sandreas@sandberg.pp.seif main['M5_BUILD_CACHE']:
9659986Sandreas@sandberg.pp.se    print 'Using build cache located at', main['M5_BUILD_CACHE']
9669986Sandreas@sandberg.pp.se    CacheDir(main['M5_BUILD_CACHE'])
9679986Sandreas@sandberg.pp.se
9689986Sandreas@sandberg.pp.semain['USE_PYTHON'] = not GetOption('without_python')
9699986Sandreas@sandberg.pp.seif main['USE_PYTHON']:
9709986Sandreas@sandberg.pp.se    # Find Python include and library directories for embedding the
9719986Sandreas@sandberg.pp.se    # interpreter. We rely on python-config to resolve the appropriate
9729986Sandreas@sandberg.pp.se    # includes and linker flags. ParseConfig does not seem to understand
9739986Sandreas@sandberg.pp.se    # the more exotic linker flags such as -Xlinker and -export-dynamic so
9749986Sandreas@sandberg.pp.se    # we add them explicitly below. If you want to link in an alternate
9759986Sandreas@sandberg.pp.se    # version of python, see above for instructions on how to invoke
9769986Sandreas@sandberg.pp.se    # scons with the appropriate PATH set.
9779986Sandreas@sandberg.pp.se    #
9789986Sandreas@sandberg.pp.se    # First we check if python2-config exists, else we use python-config
9799986Sandreas@sandberg.pp.se    python_config = readCommand(['which', 'python2-config'],
9809986Sandreas@sandberg.pp.se                                exception='').strip()
9819986Sandreas@sandberg.pp.se    if not os.path.exists(python_config):
9829986Sandreas@sandberg.pp.se        python_config = readCommand(['which', 'python-config'],
9839986Sandreas@sandberg.pp.se                                    exception='').strip()
9842638Sstever@eecs.umich.edu    py_includes = readCommand([python_config, '--includes'],
9852638Sstever@eecs.umich.edu                              exception='').split()
9866121Snate@binkert.org    # Strip the -I from the include folders before adding them to the
9873716Sstever@eecs.umich.edu    # CPPPATH
9885522Snate@binkert.org    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
9899986Sandreas@sandberg.pp.se
9909986Sandreas@sandberg.pp.se    # Read the linker flags and split them into libraries and other link
9919986Sandreas@sandberg.pp.se    # flags. The libraries are added later through the call the CheckLib.
9925522Snate@binkert.org    py_ld_flags = readCommand([python_config, '--ldflags'],
9935227Ssaidi@eecs.umich.edu        exception='').split()
9945227Ssaidi@eecs.umich.edu    py_libs = []
9955227Ssaidi@eecs.umich.edu    for lib in py_ld_flags:
9965227Ssaidi@eecs.umich.edu         if not lib.startswith('-l'):
9976654Snate@binkert.org             main.Append(LINKFLAGS=[lib])
9986654Snate@binkert.org         else:
9997769SAli.Saidi@ARM.com             lib = lib[2:]
10007769SAli.Saidi@ARM.com             if lib not in py_libs:
10017769SAli.Saidi@ARM.com                 py_libs.append(lib)
10027769SAli.Saidi@ARM.com
10035227Ssaidi@eecs.umich.edu    # verify that this stuff works
10045227Ssaidi@eecs.umich.edu    if not conf.CheckHeader('Python.h', '<>'):
10055227Ssaidi@eecs.umich.edu        print "Error: can't find Python.h header in", py_includes
10065204Sstever@gmail.com        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
10075204Sstever@gmail.com        Exit(1)
10085204Sstever@gmail.com
10095204Sstever@gmail.com    for lib in py_libs:
10105204Sstever@gmail.com        if not conf.CheckLib(lib):
10115204Sstever@gmail.com            print "Error: can't find library %s required by python" % lib
10125204Sstever@gmail.com            Exit(1)
10135204Sstever@gmail.com
10145204Sstever@gmail.com# On Solaris you need to use libsocket for socket ops
10155204Sstever@gmail.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10165204Sstever@gmail.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10175204Sstever@gmail.com       print "Can't find library with socket calls (e.g. accept())"
10185204Sstever@gmail.com       Exit(1)
10195204Sstever@gmail.com
10205204Sstever@gmail.com# Check for zlib.  If the check passes, libz will be automatically
10215204Sstever@gmail.com# added to the LIBS environment variable.
10225204Sstever@gmail.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
10236121Snate@binkert.org    print 'Error: did not find needed zlib compression library '\
10245204Sstever@gmail.com          'and/or zlib.h header file.'
10257727SAli.Saidi@ARM.com    print '       Please install zlib and try again.'
10267727SAli.Saidi@ARM.com    Exit(1)
10277727SAli.Saidi@ARM.com
10287727SAli.Saidi@ARM.com# If we have the protobuf compiler, also make sure we have the
10297727SAli.Saidi@ARM.com# development libraries. If the check passes, libprotobuf will be
103010453SAndrew.Bardsley@arm.com# automatically added to the LIBS environment variable. After
103110453SAndrew.Bardsley@arm.com# this, we can use the HAVE_PROTOBUF flag to determine if we have
103210453SAndrew.Bardsley@arm.com# got both protoc and libprotobuf available.
103310453SAndrew.Bardsley@arm.commain['HAVE_PROTOBUF'] = main['PROTOC'] and \
103410453SAndrew.Bardsley@arm.com    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
103510453SAndrew.Bardsley@arm.com                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
103610453SAndrew.Bardsley@arm.com
103710453SAndrew.Bardsley@arm.com# If we have the compiler but not the library, print another warning.
103810453SAndrew.Bardsley@arm.comif main['PROTOC'] and not main['HAVE_PROTOBUF']:
103910453SAndrew.Bardsley@arm.com    print termcap.Yellow + termcap.Bold + \
104010453SAndrew.Bardsley@arm.com        'Warning: did not find protocol buffer library and/or headers.\n' + \
104110160Sandreas.hansson@arm.com    '       Please install libprotobuf-dev for tracing support.' + \
104210453SAndrew.Bardsley@arm.com    termcap.Normal
104310453SAndrew.Bardsley@arm.com
104410453SAndrew.Bardsley@arm.com# Check for librt.
104510453SAndrew.Bardsley@arm.comhave_posix_clock = \
104610453SAndrew.Bardsley@arm.com    conf.CheckLibWithHeader(None, 'time.h', 'C',
104710453SAndrew.Bardsley@arm.com                            'clock_nanosleep(0,0,NULL,NULL);') or \
104810453SAndrew.Bardsley@arm.com    conf.CheckLibWithHeader('rt', 'time.h', 'C',
104910453SAndrew.Bardsley@arm.com                            'clock_nanosleep(0,0,NULL,NULL);')
10509812Sandreas.hansson@arm.com
105110453SAndrew.Bardsley@arm.comhave_posix_timers = \
105210453SAndrew.Bardsley@arm.com    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
105310453SAndrew.Bardsley@arm.com                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
105410453SAndrew.Bardsley@arm.com
105510453SAndrew.Bardsley@arm.comif not GetOption('without_tcmalloc'):
105610453SAndrew.Bardsley@arm.com    if conf.CheckLib('tcmalloc'):
105710453SAndrew.Bardsley@arm.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
105810453SAndrew.Bardsley@arm.com    elif conf.CheckLib('tcmalloc_minimal'):
105910453SAndrew.Bardsley@arm.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
106010453SAndrew.Bardsley@arm.com    else:
106110453SAndrew.Bardsley@arm.com        print termcap.Yellow + termcap.Bold + \
106210453SAndrew.Bardsley@arm.com              "You can get a 12% performance improvement by "\
10637727SAli.Saidi@ARM.com              "installing tcmalloc (libgoogle-perftools-dev package "\
106410453SAndrew.Bardsley@arm.com              "on Ubuntu or RedHat)." + termcap.Normal
106510453SAndrew.Bardsley@arm.com
106610453SAndrew.Bardsley@arm.com
106710453SAndrew.Bardsley@arm.com# Detect back trace implementations. The last implementation in the
106810453SAndrew.Bardsley@arm.com# list will be used by default.
10693118Sstever@eecs.umich.edubacktrace_impls = [ "none" ]
107010453SAndrew.Bardsley@arm.com
107110453SAndrew.Bardsley@arm.comif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
107210453SAndrew.Bardsley@arm.com                           'backtrace_symbols_fd((void*)0, 0, 0);'):
107310453SAndrew.Bardsley@arm.com    backtrace_impls.append("glibc")
10743118Sstever@eecs.umich.eduelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
10753483Ssaidi@eecs.umich.edu                           'backtrace_symbols_fd((void*)0, 0, 0);'):
10763494Ssaidi@eecs.umich.edu    # NetBSD and FreeBSD need libexecinfo.
10773494Ssaidi@eecs.umich.edu    backtrace_impls.append("glibc")
10783483Ssaidi@eecs.umich.edu    main.Append(LIBS=['execinfo'])
10793483Ssaidi@eecs.umich.edu
10803483Ssaidi@eecs.umich.eduif backtrace_impls[-1] == "none":
10813053Sstever@eecs.umich.edu    default_backtrace_impl = "none"
10823053Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
10833918Ssaidi@eecs.umich.edu        "No suitable back trace implementation found." + \
10843053Sstever@eecs.umich.edu        termcap.Normal
10853053Sstever@eecs.umich.edu
10863053Sstever@eecs.umich.eduif not have_posix_clock:
10873053Sstever@eecs.umich.edu    print "Can't find library for POSIX clocks."
10883053Sstever@eecs.umich.edu
10899396Sandreas.hansson@arm.com# Check for <fenv.h> (C99 FP environment control)
10909396Sandreas.hansson@arm.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
10919396Sandreas.hansson@arm.comif not have_fenv:
10929396Sandreas.hansson@arm.com    print "Warning: Header file <fenv.h> not found."
10939396Sandreas.hansson@arm.com    print "         This host has no IEEE FP rounding mode control."
10949396Sandreas.hansson@arm.com
10959396Sandreas.hansson@arm.com# Check if we should enable KVM-based hardware virtualization. The API
10969396Sandreas.hansson@arm.com# we rely on exists since version 2.6.36 of the kernel, but somehow
10979396Sandreas.hansson@arm.com# the KVM_API_VERSION does not reflect the change. We test for one of
10989477Sandreas.hansson@arm.com# the types as a fall back.
10999396Sandreas.hansson@arm.comhave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
11009477Sandreas.hansson@arm.comif not have_kvm:
11019477Sandreas.hansson@arm.com    print "Info: Compatible header file <linux/kvm.h> not found, " \
11029477Sandreas.hansson@arm.com        "disabling KVM support."
11039477Sandreas.hansson@arm.com
11049396Sandreas.hansson@arm.com# x86 needs support for xsave. We test for the structure here since we
11057840Snate@binkert.org# won't be able to run new tests by the time we know which ISA we're
11067865Sgblack@eecs.umich.edu# targeting.
11077865Sgblack@eecs.umich.eduhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
11087865Sgblack@eecs.umich.edu                                    '#include <linux/kvm.h>') != 0
11097865Sgblack@eecs.umich.edu
11107865Sgblack@eecs.umich.edu# Check if the requested target ISA is compatible with the host
11117840Snate@binkert.orgdef is_isa_kvm_compatible(isa):
11129900Sandreas@sandberg.pp.se    try:
11139900Sandreas@sandberg.pp.se        import platform
11149900Sandreas@sandberg.pp.se        host_isa = platform.machine()
11159900Sandreas@sandberg.pp.se    except:
111610456SCurtis.Dunham@arm.com        print "Warning: Failed to determine host ISA."
111710456SCurtis.Dunham@arm.com        return False
111810456SCurtis.Dunham@arm.com
111910456SCurtis.Dunham@arm.com    if not have_posix_timers:
112010456SCurtis.Dunham@arm.com        print "Warning: Can not enable KVM, host seems to lack support " \
112110456SCurtis.Dunham@arm.com            "for POSIX timers"
112210456SCurtis.Dunham@arm.com        return False
112310456SCurtis.Dunham@arm.com
112410456SCurtis.Dunham@arm.com    if isa == "arm":
112510456SCurtis.Dunham@arm.com        return host_isa in ( "armv7l", "aarch64" )
11269045SAli.Saidi@ARM.com    elif isa == "x86":
112711235Sandreas.sandberg@arm.com        if host_isa != "x86_64":
112811235Sandreas.sandberg@arm.com            return False
112911235Sandreas.sandberg@arm.com
113011235Sandreas.sandberg@arm.com        if not have_kvm_xsave:
113111235Sandreas.sandberg@arm.com            print "KVM on x86 requires xsave support in kernel headers."
113211235Sandreas.sandberg@arm.com            return False
113311235Sandreas.sandberg@arm.com
113411235Sandreas.sandberg@arm.com        return True
113511811Sbaz21@cam.ac.uk    else:
113611811Sbaz21@cam.ac.uk        return False
113711811Sbaz21@cam.ac.uk
113811811Sbaz21@cam.ac.uk
113911811Sbaz21@cam.ac.uk# Check if the exclude_host attribute is available. We want this to
114011235Sandreas.sandberg@arm.com# get accurate instruction counts in KVM.
114111235Sandreas.sandberg@arm.commain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
114211235Sandreas.sandberg@arm.com    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
114311235Sandreas.sandberg@arm.com
114411235Sandreas.sandberg@arm.com
114511235Sandreas.sandberg@arm.com######################################################################
114611235Sandreas.sandberg@arm.com#
11477840Snate@binkert.org# Finish the configuration
11487840Snate@binkert.org#
11497840Snate@binkert.orgmain = conf.Finish()
11501858SN/A
11511858SN/A######################################################################
11521858SN/A#
11531858SN/A# Collect all non-global variables
11541858SN/A#
11551858SN/A
11569903Sandreas.hansson@arm.com# Define the universe of supported ISAs
11579903Sandreas.hansson@arm.comall_isa_list = [ ]
11589903Sandreas.hansson@arm.comall_gpu_isa_list = [ ]
11599903Sandreas.hansson@arm.comExport('all_isa_list')
116010841Sandreas.sandberg@arm.comExport('all_gpu_isa_list')
11619651SAndreas.Sandberg@ARM.com
11629903Sandreas.hansson@arm.comclass CpuModel(object):
11639651SAndreas.Sandberg@ARM.com    '''The CpuModel class encapsulates everything the ISA parser needs to
11649651SAndreas.Sandberg@ARM.com    know about a particular CPU model.'''
116510841Sandreas.sandberg@arm.com
116610841Sandreas.sandberg@arm.com    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
116710841Sandreas.sandberg@arm.com    dict = {}
116810841Sandreas.sandberg@arm.com
116910841Sandreas.sandberg@arm.com    # Constructor.  Automatically adds models to CpuModel.dict.
117010841Sandreas.sandberg@arm.com    def __init__(self, name, default=False):
11719651SAndreas.Sandberg@ARM.com        self.name = name           # name of model
11729651SAndreas.Sandberg@ARM.com
11739651SAndreas.Sandberg@ARM.com        # This cpu is enabled by default
11749651SAndreas.Sandberg@ARM.com        self.default = default
11759651SAndreas.Sandberg@ARM.com
11769651SAndreas.Sandberg@ARM.com        # Add self to dict
11779651SAndreas.Sandberg@ARM.com        if name in CpuModel.dict:
11789651SAndreas.Sandberg@ARM.com            raise AttributeError, "CpuModel '%s' already registered" % name
11799651SAndreas.Sandberg@ARM.com        CpuModel.dict[name] = self
118010841Sandreas.sandberg@arm.com
118110841Sandreas.sandberg@arm.comExport('CpuModel')
118210841Sandreas.sandberg@arm.com
118310841Sandreas.sandberg@arm.com# Sticky variables get saved in the variables file so they persist from
118410841Sandreas.sandberg@arm.com# one invocation to the next (unless overridden, in which case the new
118510841Sandreas.sandberg@arm.com# value becomes sticky).
118610860Sandreas.sandberg@arm.comsticky_vars = Variables(args=ARGUMENTS)
118710841Sandreas.sandberg@arm.comExport('sticky_vars')
118810841Sandreas.sandberg@arm.com
118910841Sandreas.sandberg@arm.com# Sticky variables that should be exported
119010841Sandreas.sandberg@arm.comexport_vars = []
119110841Sandreas.sandberg@arm.comExport('export_vars')
119210841Sandreas.sandberg@arm.com
119310841Sandreas.sandberg@arm.com# For Ruby
119410841Sandreas.sandberg@arm.comall_protocols = []
119510841Sandreas.sandberg@arm.comExport('all_protocols')
119610841Sandreas.sandberg@arm.comprotocol_dirs = []
119710841Sandreas.sandberg@arm.comExport('protocol_dirs')
11989651SAndreas.Sandberg@ARM.comslicc_includes = []
11999651SAndreas.Sandberg@ARM.comExport('slicc_includes')
12009986Sandreas@sandberg.pp.se
12019986Sandreas@sandberg.pp.se# Walk the tree and execute all SConsopts scripts that wil add to the
12029986Sandreas@sandberg.pp.se# above variables
12039986Sandreas@sandberg.pp.seif GetOption('verbose'):
12049986Sandreas@sandberg.pp.se    print "Reading SConsopts"
12059986Sandreas@sandberg.pp.sefor bdir in [ base_dir ] + extras_dir_list:
12065863Snate@binkert.org    if not isdir(bdir):
12075863Snate@binkert.org        print "Error: directory '%s' does not exist" % bdir
12085863Snate@binkert.org        Exit(1)
12095863Snate@binkert.org    for root, dirs, files in os.walk(bdir):
12106121Snate@binkert.org        if 'SConsopts' in files:
12111858SN/A            if GetOption('verbose'):
12125863Snate@binkert.org                print "Reading", joinpath(root, 'SConsopts')
12135863Snate@binkert.org            SConscript(joinpath(root, 'SConsopts'))
12145863Snate@binkert.org
12155863Snate@binkert.orgall_isa_list.sort()
12165863Snate@binkert.orgall_gpu_isa_list.sort()
12172139SN/A
12184202Sbinkertn@umich.edusticky_vars.AddVariables(
121911308Santhony.gutierrez@amd.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
12204202Sbinkertn@umich.edu    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
122111308Santhony.gutierrez@amd.com    ListVariable('CPU_MODELS', 'CPU models',
12222139SN/A                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
12236994Snate@binkert.org                 sorted(CpuModel.dict.keys())),
12246994Snate@binkert.org    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
12256994Snate@binkert.org                 False),
12266994Snate@binkert.org    BoolVariable('SS_COMPATIBLE_FP',
12276994Snate@binkert.org                 'Make floating-point results compatible with SimpleScalar',
12286994Snate@binkert.org                 False),
12296994Snate@binkert.org    BoolVariable('USE_SSE2',
12306994Snate@binkert.org                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
123110319SAndreas.Sandberg@ARM.com                 False),
12326994Snate@binkert.org    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
12336994Snate@binkert.org    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
12346994Snate@binkert.org    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
12356994Snate@binkert.org    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
12366994Snate@binkert.org    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
12376994Snate@binkert.org    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
12386994Snate@binkert.org                  all_protocols),
12396994Snate@binkert.org    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
12406994Snate@binkert.org                 backtrace_impls[-1], backtrace_impls)
12416994Snate@binkert.org    )
12426994Snate@binkert.org
12432155SN/A# These variables get exported to #defines in config/*.hh (see src/SConscript).
12445863Snate@binkert.orgexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
12451869SN/A                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL',
12461869SN/A                'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
12475863Snate@binkert.org
12485863Snate@binkert.org###################################################
12494202Sbinkertn@umich.edu#
12506108Snate@binkert.org# Define a SCons builder for configuration flag headers.
12516108Snate@binkert.org#
12526108Snate@binkert.org###################################################
12536108Snate@binkert.org
12549219Spower.jg@gmail.com# This function generates a config header file that #defines the
12559219Spower.jg@gmail.com# variable symbol to the current variable setting (0 or 1).  The source
12569219Spower.jg@gmail.com# operands are the name of the variable and a Value node containing the
12579219Spower.jg@gmail.com# value of the variable.
12589219Spower.jg@gmail.comdef build_config_file(target, source, env):
12599219Spower.jg@gmail.com    (variable, value) = [s.get_contents() for s in source]
12609219Spower.jg@gmail.com    f = file(str(target[0]), 'w')
12619219Spower.jg@gmail.com    print >> f, '#define', variable, value
12624202Sbinkertn@umich.edu    f.close()
12635863Snate@binkert.org    return None
126410135SCurtis.Dunham@arm.com
12658474Sgblack@eecs.umich.edu# Combine the two functions into a scons Action object.
12665742Snate@binkert.orgconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
12678268Ssteve.reinhardt@amd.com
12688268Ssteve.reinhardt@amd.com# The emitter munges the source & target node lists to reflect what
12698268Ssteve.reinhardt@amd.com# we're really doing.
12705742Snate@binkert.orgdef config_emitter(target, source, env):
12715341Sstever@gmail.com    # extract variable name from Builder arg
12728474Sgblack@eecs.umich.edu    variable = str(target[0])
12738474Sgblack@eecs.umich.edu    # True target is config header file
12745342Sstever@gmail.com    target = joinpath('config', variable.lower() + '.hh')
12754202Sbinkertn@umich.edu    val = env[variable]
12764202Sbinkertn@umich.edu    if isinstance(val, bool):
127711308Santhony.gutierrez@amd.com        # Force value to 0/1
12784202Sbinkertn@umich.edu        val = int(val)
12795863Snate@binkert.org    elif isinstance(val, str):
12805863Snate@binkert.org        val = '"' + val + '"'
128111308Santhony.gutierrez@amd.com
12826994Snate@binkert.org    # Sources are variable name & value (packaged in SCons Value nodes)
12836994Snate@binkert.org    return ([target], [Value(variable), Value(val)])
128410319SAndreas.Sandberg@ARM.com
12855863Snate@binkert.orgconfig_builder = Builder(emitter = config_emitter, action = config_action)
12865863Snate@binkert.org
12875863Snate@binkert.orgmain.Append(BUILDERS = { 'ConfigFile' : config_builder })
12885863Snate@binkert.org
12895863Snate@binkert.org###################################################
12905863Snate@binkert.org#
12915863Snate@binkert.org# Builders for static and shared partially linked object files.
12925863Snate@binkert.org#
12937840Snate@binkert.org###################################################
12945863Snate@binkert.org
12955952Ssaidi@eecs.umich.edupartial_static_builder = Builder(action=SCons.Defaults.LinkAction,
12969651SAndreas.Sandberg@ARM.com                                 src_suffix='$OBJSUFFIX',
129711308Santhony.gutierrez@amd.com                                 src_builder=['StaticObject', 'Object'],
12989219Spower.jg@gmail.com                                 LINKFLAGS='$PLINKFLAGS',
12999219Spower.jg@gmail.com                                 LIBS='')
130011235Sandreas.sandberg@arm.com
130111235Sandreas.sandberg@arm.comdef partial_shared_emitter(target, source, env):
13021869SN/A    for tgt in target:
13031858SN/A        tgt.attributes.shared = 1
13045863Snate@binkert.org    return (target, source)
130511308Santhony.gutierrez@amd.compartial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
130611308Santhony.gutierrez@amd.com                                 emitter=partial_shared_emitter,
130711308Santhony.gutierrez@amd.com                                 src_suffix='$SHOBJSUFFIX',
13081858SN/A                                 src_builder='SharedObject',
1309955SN/A                                 SHLINKFLAGS='$PSHLINKFLAGS',
1310955SN/A                                 LIBS='')
13111869SN/A
13121869SN/Amain.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
13131869SN/A                         'PartialStatic' : partial_static_builder })
13141869SN/A
13151869SN/A# builds in ext are shared across all configs in the build root.
13165863Snate@binkert.orgext_dir = abspath(joinpath(str(main.root), 'ext'))
13175863Snate@binkert.orgfor root, dirs, files in os.walk(ext_dir):
13185863Snate@binkert.org    if 'SConscript' in files:
13191869SN/A        build_dir = os.path.relpath(root, ext_dir)
13205863Snate@binkert.org        main.SConscript(joinpath(root, 'SConscript'),
13211869SN/A                        variant_dir=joinpath(build_root, build_dir))
13225863Snate@binkert.org
13231869SN/Amain.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
13241869SN/A
13251869SN/A###################################################
13261869SN/A#
13278483Sgblack@eecs.umich.edu# This function is used to set up a directory with switching headers
13281869SN/A#
13291869SN/A###################################################
13301869SN/A
13311869SN/Amain['ALL_ISA_LIST'] = all_isa_list
13325863Snate@binkert.orgmain['ALL_GPU_ISA_LIST'] = all_gpu_isa_list
13335863Snate@binkert.orgall_isa_deps = {}
13341869SN/Adef make_switching_dir(dname, switch_headers, env):
13355863Snate@binkert.org    # Generate the header.  target[0] is the full path of the output
13365863Snate@binkert.org    # header to generate.  'source' is a dummy variable, since we get the
13373356Sbinkertn@umich.edu    # list of ISAs from env['ALL_ISA_LIST'].
13383356Sbinkertn@umich.edu    def gen_switch_hdr(target, source, env):
13393356Sbinkertn@umich.edu        fname = str(target[0])
13403356Sbinkertn@umich.edu        isa = env['TARGET_ISA'].lower()
13413356Sbinkertn@umich.edu        try:
13424781Snate@binkert.org            f = open(fname, 'w')
13435863Snate@binkert.org            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
13445863Snate@binkert.org            f.close()
13451869SN/A        except IOError:
13461869SN/A            print "Failed to create %s" % fname
13471869SN/A            raise
13486121Snate@binkert.org
13491869SN/A    # Build SCons Action object. 'varlist' specifies env vars that this
135011982Sgabeblack@google.com    # action depends on; when env['ALL_ISA_LIST'] changes these actions
135111982Sgabeblack@google.com    # should get re-executed.
135211982Sgabeblack@google.com    switch_hdr_action = MakeAction(gen_switch_hdr,
135311982Sgabeblack@google.com                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
135411982Sgabeblack@google.com
135511982Sgabeblack@google.com    # Instantiate actions for each header
135611982Sgabeblack@google.com    for hdr in switch_headers:
135711982Sgabeblack@google.com        env.Command(hdr, [], switch_hdr_action)
135811982Sgabeblack@google.com
135911982Sgabeblack@google.com    isa_target = Dir('.').up().name.lower().replace('_', '-')
136011982Sgabeblack@google.com    env['PHONY_BASE'] = '#'+isa_target
136111982Sgabeblack@google.com    all_isa_deps[isa_target] = None
136211982Sgabeblack@google.com
136311982Sgabeblack@google.comExport('make_switching_dir')
136411982Sgabeblack@google.com
136511982Sgabeblack@google.comdef make_gpu_switching_dir(dname, switch_headers, env):
136611982Sgabeblack@google.com    # Generate the header.  target[0] is the full path of the output
136711982Sgabeblack@google.com    # header to generate.  'source' is a dummy variable, since we get the
136811982Sgabeblack@google.com    # list of ISAs from env['ALL_ISA_LIST'].
136911982Sgabeblack@google.com    def gen_switch_hdr(target, source, env):
137011982Sgabeblack@google.com        fname = str(target[0])
137111982Sgabeblack@google.com
137211982Sgabeblack@google.com        isa = env['TARGET_GPU_ISA'].lower()
137311982Sgabeblack@google.com
137411982Sgabeblack@google.com        try:
137511982Sgabeblack@google.com            f = open(fname, 'w')
137611978Sgabeblack@google.com            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
137711978Sgabeblack@google.com            f.close()
137811978Sgabeblack@google.com        except IOError:
137911978Sgabeblack@google.com            print "Failed to create %s" % fname
138011978Sgabeblack@google.com            raise
138111978Sgabeblack@google.com
138211978Sgabeblack@google.com    # Build SCons Action object. 'varlist' specifies env vars that this
138310915Sandreas.sandberg@arm.com    # action depends on; when env['ALL_ISA_LIST'] changes these actions
138411986Sandreas.sandberg@arm.com    # should get re-executed.
138511986Sandreas.sandberg@arm.com    switch_hdr_action = MakeAction(gen_switch_hdr,
13861869SN/A                          Transform("GENERATE"), varlist=['ALL_ISA_GPU_LIST'])
13871869SN/A
13883546Sgblack@eecs.umich.edu    # Instantiate actions for each header
13893546Sgblack@eecs.umich.edu    for hdr in switch_headers:
13903546Sgblack@eecs.umich.edu        env.Command(hdr, [], switch_hdr_action)
13913546Sgblack@eecs.umich.edu
13926121Snate@binkert.orgExport('make_gpu_switching_dir')
139311308Santhony.gutierrez@amd.com
139410196SCurtis.Dunham@arm.com# all-isas -> all-deps -> all-environs -> all_targets
13955863Snate@binkert.orgmain.Alias('#all-isas', [])
13963546Sgblack@eecs.umich.edumain.Alias('#all-deps', '#all-isas')
13973546Sgblack@eecs.umich.edu
13983546Sgblack@eecs.umich.edu# Dummy target to ensure all environments are created before telling
13993546Sgblack@eecs.umich.edu# SCons what to actually make (the command line arguments).  We attach
14004781Snate@binkert.org# them to the dependence graph after the environments are complete.
14016658Snate@binkert.orgORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
140210196SCurtis.Dunham@arm.comdef environsComplete(target, source, env):
140310196SCurtis.Dunham@arm.com    for t in ORIG_BUILD_TARGETS:
140410196SCurtis.Dunham@arm.com        main.Depends('#all-targets', t)
140510196SCurtis.Dunham@arm.com
140610196SCurtis.Dunham@arm.com# Each build/* switching_dir attaches its *-environs target to #all-environs.
140710196SCurtis.Dunham@arm.commain.Append(BUILDERS = {'CompleteEnvirons' :
140810196SCurtis.Dunham@arm.com                        Builder(action=MakeAction(environsComplete, None))})
14093546Sgblack@eecs.umich.edumain.CompleteEnvirons('#all-environs', [])
14103546Sgblack@eecs.umich.edu
14113546Sgblack@eecs.umich.edudef doNothing(**ignored): pass
14123546Sgblack@eecs.umich.edumain.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
14137756SAli.Saidi@ARM.com
14147816Ssteve.reinhardt@amd.com# The final target to which all the original targets ultimately get attached.
14153546Sgblack@eecs.umich.edumain.Dummy('#all-targets', '#all-environs')
14163546Sgblack@eecs.umich.eduBUILD_TARGETS[:] = ['#all-targets']
14173546Sgblack@eecs.umich.edu
14183546Sgblack@eecs.umich.edu###################################################
141910196SCurtis.Dunham@arm.com#
142010196SCurtis.Dunham@arm.com# Define build environments for selected configurations.
142110196SCurtis.Dunham@arm.com#
142210196SCurtis.Dunham@arm.com###################################################
142310196SCurtis.Dunham@arm.com
14244202Sbinkertn@umich.edufor variant_path in variant_paths:
14253546Sgblack@eecs.umich.edu    if not GetOption('silent'):
142611308Santhony.gutierrez@amd.com        print "Building in", variant_path
142711308Santhony.gutierrez@amd.com
142811308Santhony.gutierrez@amd.com    # Make a copy of the build-root environment to use for this config.
142911308Santhony.gutierrez@amd.com    env = main.Clone()
143011308Santhony.gutierrez@amd.com    env['BUILDDIR'] = variant_path
143111308Santhony.gutierrez@amd.com
143211308Santhony.gutierrez@amd.com    # variant_dir is the tail component of build path, and is used to
143311308Santhony.gutierrez@amd.com    # determine the build parameters (e.g., 'ALPHA_SE')
143411308Santhony.gutierrez@amd.com    (build_root, variant_dir) = splitpath(variant_path)
143511308Santhony.gutierrez@amd.com
143611308Santhony.gutierrez@amd.com    # Set env variables according to the build directory config.
143711308Santhony.gutierrez@amd.com    sticky_vars.files = []
143811308Santhony.gutierrez@amd.com    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
143911308Santhony.gutierrez@amd.com    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
144011308Santhony.gutierrez@amd.com    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
144111308Santhony.gutierrez@amd.com    current_vars_file = joinpath(build_root, 'variables', variant_dir)
144211308Santhony.gutierrez@amd.com    if isfile(current_vars_file):
144311308Santhony.gutierrez@amd.com        sticky_vars.files.append(current_vars_file)
144411308Santhony.gutierrez@amd.com        if not GetOption('silent'):
144511308Santhony.gutierrez@amd.com            print "Using saved variables file %s" % current_vars_file
144611308Santhony.gutierrez@amd.com    else:
144711308Santhony.gutierrez@amd.com        # Build dir-specific variables file doesn't exist.
144811308Santhony.gutierrez@amd.com
144911308Santhony.gutierrez@amd.com        # Make sure the directory is there so we can create it later
145011308Santhony.gutierrez@amd.com        opt_dir = dirname(current_vars_file)
145111308Santhony.gutierrez@amd.com        if not isdir(opt_dir):
145211308Santhony.gutierrez@amd.com            mkdir(opt_dir)
145311308Santhony.gutierrez@amd.com
145411308Santhony.gutierrez@amd.com        # Get default build variables from source tree.  Variables are
145510196SCurtis.Dunham@arm.com        # normally determined by name of $VARIANT_DIR, but can be
145610196SCurtis.Dunham@arm.com        # overridden by '--default=' arg on command line.
145710196SCurtis.Dunham@arm.com        default = GetOption('default')
145810196SCurtis.Dunham@arm.com        opts_dir = joinpath(main.root.abspath, 'build_opts')
145910196SCurtis.Dunham@arm.com        if default:
146010196SCurtis.Dunham@arm.com            default_vars_files = [joinpath(build_root, 'variables', default),
146110196SCurtis.Dunham@arm.com                                  joinpath(opts_dir, default)]
146210196SCurtis.Dunham@arm.com        else:
146310196SCurtis.Dunham@arm.com            default_vars_files = [joinpath(opts_dir, variant_dir)]
146410196SCurtis.Dunham@arm.com        existing_files = filter(isfile, default_vars_files)
146510196SCurtis.Dunham@arm.com        if existing_files:
146610196SCurtis.Dunham@arm.com            default_vars_file = existing_files[0]
146710196SCurtis.Dunham@arm.com            sticky_vars.files.append(default_vars_file)
146810196SCurtis.Dunham@arm.com            print "Variables file %s not found,\n  using defaults in %s" \
146910196SCurtis.Dunham@arm.com                  % (current_vars_file, default_vars_file)
147010196SCurtis.Dunham@arm.com        else:
147110196SCurtis.Dunham@arm.com            print "Error: cannot find variables file %s or " \
147210196SCurtis.Dunham@arm.com                  "default file(s) %s" \
147310196SCurtis.Dunham@arm.com                  % (current_vars_file, ' or '.join(default_vars_files))
147410196SCurtis.Dunham@arm.com            Exit(1)
147510196SCurtis.Dunham@arm.com
147610196SCurtis.Dunham@arm.com    # Apply current variable settings to env
147710196SCurtis.Dunham@arm.com    sticky_vars.Update(env)
147810196SCurtis.Dunham@arm.com
14793546Sgblack@eecs.umich.edu    help_texts["local_vars"] += \
14803546Sgblack@eecs.umich.edu        "Build variables for %s:\n" % variant_dir \
1481955SN/A                 + sticky_vars.GenerateHelpText(env)
1482955SN/A
1483955SN/A    # Process variable settings.
1484955SN/A
14855863Snate@binkert.org    if not have_fenv and env['USE_FENV']:
148610135SCurtis.Dunham@arm.com        print "Warning: <fenv.h> not available; " \
148710135SCurtis.Dunham@arm.com              "forcing USE_FENV to False in", variant_dir + "."
14885343Sstever@gmail.com        env['USE_FENV'] = False
14895343Sstever@gmail.com
14906121Snate@binkert.org    if not env['USE_FENV']:
14915863Snate@binkert.org        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
14924773Snate@binkert.org        print "         FP results may deviate slightly from other platforms."
14935863Snate@binkert.org
14942632Sstever@eecs.umich.edu    if env['EFENCE']:
14955863Snate@binkert.org        env.Append(LIBS=['efence'])
14962023SN/A
14975863Snate@binkert.org    if env['USE_KVM']:
14985863Snate@binkert.org        if not have_kvm:
14995863Snate@binkert.org            print "Warning: Can not enable KVM, host seems to lack KVM support"
15005863Snate@binkert.org            env['USE_KVM'] = False
15015863Snate@binkert.org        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
15025863Snate@binkert.org            print "Info: KVM support disabled due to unsupported host and " \
15035863Snate@binkert.org                "target ISA combination"
15045863Snate@binkert.org            env['USE_KVM'] = False
150510135SCurtis.Dunham@arm.com
150610135SCurtis.Dunham@arm.com    if env['BUILD_GPU']:
15072632Sstever@eecs.umich.edu        env.Append(CPPDEFINES=['BUILD_GPU'])
15085863Snate@binkert.org
15092023SN/A    # Warn about missing optional functionality
15102632Sstever@eecs.umich.edu    if env['USE_KVM']:
15115863Snate@binkert.org        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
15125342Sstever@gmail.com            print "Warning: perf_event headers lack support for the " \
15135863Snate@binkert.org                "exclude_host attribute. KVM instruction counts will " \
15142632Sstever@eecs.umich.edu                "be inaccurate."
15155863Snate@binkert.org
15165863Snate@binkert.org    # Save sticky variable settings back to current variables file
15178267Ssteve.reinhardt@amd.com    sticky_vars.Save(current_vars_file, env)
15188120Sgblack@eecs.umich.edu
15198267Ssteve.reinhardt@amd.com    if env['USE_SSE2']:
15208267Ssteve.reinhardt@amd.com        env.Append(CCFLAGS=['-msse2'])
15218267Ssteve.reinhardt@amd.com
15228267Ssteve.reinhardt@amd.com    # The src/SConscript file sets up the build rules in 'env' according
15238267Ssteve.reinhardt@amd.com    # to the configured variables.  It returns a list of environments,
15248267Ssteve.reinhardt@amd.com    # one for each variant build (debug, opt, etc.)
15258267Ssteve.reinhardt@amd.com    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
15268267Ssteve.reinhardt@amd.com
15278267Ssteve.reinhardt@amd.comdef pairwise(iterable):
15285863Snate@binkert.org    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
15295863Snate@binkert.org    a, b = itertools.tee(iterable)
15305863Snate@binkert.org    b.next()
15312632Sstever@eecs.umich.edu    return itertools.izip(a, b)
15328267Ssteve.reinhardt@amd.com
15338267Ssteve.reinhardt@amd.com# Create false dependencies so SCons will parse ISAs, establish
15348267Ssteve.reinhardt@amd.com# dependencies, and setup the build Environments serially. Either
15352632Sstever@eecs.umich.edu# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
15361888SN/A# greater than 1. It appears to be standard race condition stuff; it
15375863Snate@binkert.org# doesn't always fail, but usually, and the behaviors are different.
15385863Snate@binkert.org# Every time I tried to remove this, builds would fail in some
15391858SN/A# creative new way. So, don't do that. You'll want to, though, because
15408120Sgblack@eecs.umich.edu# tests/SConscript takes a long time to make its Environments.
15418120Sgblack@eecs.umich.edufor t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
15427756SAli.Saidi@ARM.com    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
15432598SN/A    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
15445863Snate@binkert.org
15451858SN/A# base help text
15461858SN/AHelp('''
15471858SN/AUsage: scons [scons options] [build variables] [target(s)]
15485863Snate@binkert.org
15491858SN/AExtra scons options:
15501858SN/A%(options)s
15511858SN/A
15525863Snate@binkert.orgGlobal build variables:
15531871SN/A%(global_vars)s
15541858SN/A
15551858SN/A%(local_vars)s
15561858SN/A''' % help_texts)
15571858SN/A