SConstruct revision 11798
1955SN/A# -*- mode:python -*-
2955SN/A
312230Sgiacomo.travaglini@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
8112563Sgabeblack@google.com# Check for recent-enough Python and SCons versions.
8212563Sgabeblack@google.comtry:
836654Snate@binkert.org    # Really old versions of scons only take two options for the
8410196SCurtis.Dunham@arm.com    # function, so check once without the revision and once with the
85955SN/A    # revision, the first instance will fail for stuff other than
865396Ssaidi@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
8711401Sandreas.sandberg@arm.com    EnsureSConsVersion(0, 98)
885863Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
895863Snate@binkert.orgexcept SystemExit, e:
904202Sbinkertn@umich.edu    print """
915863Snate@binkert.orgFor more details, see:
925863Snate@binkert.org    http://gem5.org/Dependencies
935863Snate@binkert.org"""
945863Snate@binkert.org    raise
9513541Sandrea.mondelli@ucf.edu
96955SN/A# We ensure the python version early because because python-config
976654Snate@binkert.org# requires python 2.5
985273Sstever@gmail.comtry:
995871Snate@binkert.org    EnsurePythonVersion(2, 5)
1005273Sstever@gmail.comexcept SystemExit, e:
1016654Snate@binkert.org    print """
1025396Ssaidi@eecs.umich.eduYou can use a non-default installation of the Python interpreter by
1038120Sgblack@eecs.umich.edurearranging your PATH so that scons finds the non-default 'python' and
1048120Sgblack@eecs.umich.edu'python-config' first.
1058120Sgblack@eecs.umich.edu
1068120Sgblack@eecs.umich.eduFor more details, see:
1078120Sgblack@eecs.umich.edu    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1088120Sgblack@eecs.umich.edu"""
1098120Sgblack@eecs.umich.edu    raise
1108120Sgblack@eecs.umich.edu
1118879Ssteve.reinhardt@amd.com# Global Python includes
1128879Ssteve.reinhardt@amd.comimport itertools
1138879Ssteve.reinhardt@amd.comimport os
1148879Ssteve.reinhardt@amd.comimport re
1158879Ssteve.reinhardt@amd.comimport shutil
1168879Ssteve.reinhardt@amd.comimport subprocess
1178879Ssteve.reinhardt@amd.comimport sys
1188879Ssteve.reinhardt@amd.com
1198879Ssteve.reinhardt@amd.comfrom os import mkdir, environ
1208879Ssteve.reinhardt@amd.comfrom os.path import abspath, basename, dirname, expanduser, normpath
1218879Ssteve.reinhardt@amd.comfrom os.path import exists,  isdir, isfile
1228879Ssteve.reinhardt@amd.comfrom os.path import join as joinpath, split as splitpath
1238879Ssteve.reinhardt@amd.com
1248120Sgblack@eecs.umich.edu# SCons includes
1258120Sgblack@eecs.umich.eduimport SCons
1268120Sgblack@eecs.umich.eduimport SCons.Node
1278120Sgblack@eecs.umich.edu
1288120Sgblack@eecs.umich.eduextra_python_paths = [
1298120Sgblack@eecs.umich.edu    Dir('src/python').srcnode().abspath, # gem5 includes
1308120Sgblack@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1318120Sgblack@eecs.umich.edu    ]
1328120Sgblack@eecs.umich.edu
1338120Sgblack@eecs.umich.edusys.path[1:1] = extra_python_paths
1348120Sgblack@eecs.umich.edu
1358120Sgblack@eecs.umich.edufrom m5.util import compareVersions, readCommand
1368120Sgblack@eecs.umich.edufrom m5.util.terminal import get_termcap
1378120Sgblack@eecs.umich.edu
1388879Ssteve.reinhardt@amd.comhelp_texts = {
1398879Ssteve.reinhardt@amd.com    "options" : "",
1408879Ssteve.reinhardt@amd.com    "global_vars" : "",
1418879Ssteve.reinhardt@amd.com    "local_vars" : ""
14210458Sandreas.hansson@arm.com}
14310458Sandreas.hansson@arm.com
14410458Sandreas.hansson@arm.comExport("help_texts")
1458879Ssteve.reinhardt@amd.com
1468879Ssteve.reinhardt@amd.com
1478879Ssteve.reinhardt@amd.com# There's a bug in scons in that (1) by default, the help texts from
1488879Ssteve.reinhardt@amd.com# AddOption() are supposed to be displayed when you type 'scons -h'
14913421Sciro.santilli@arm.com# and (2) you can override the help displayed by 'scons -h' using the
15013421Sciro.santilli@arm.com# Help() function, but these two features are incompatible: once
1519227Sandreas.hansson@arm.com# you've overridden the help text using Help(), there's no way to get
1529227Sandreas.hansson@arm.com# at the help texts from AddOptions.  See:
15312063Sgabeblack@google.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
15412063Sgabeblack@google.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
15512063Sgabeblack@google.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):
1598879Ssteve.reinhardt@amd.com    col_width = 30
16010453SAndrew.Bardsley@arm.com
16110453SAndrew.Bardsley@arm.com    help = "  " + ", ".join(args)
16210453SAndrew.Bardsley@arm.com    if "help" in kwargs:
16310456SCurtis.Dunham@arm.com        length = len(help)
16410456SCurtis.Dunham@arm.com        if length >= col_width:
16510456SCurtis.Dunham@arm.com            help += "\n" + " " * col_width
16610457Sandreas.hansson@arm.com        else:
16710457Sandreas.hansson@arm.com            help += " " * (col_width - length)
16811342Sandreas.hansson@arm.com        help += kwargs["help"]
16911342Sandreas.hansson@arm.com    help_texts["options"] += help + "\n"
1708120Sgblack@eecs.umich.edu
17112063Sgabeblack@google.com    AddOption(*args, **kwargs)
17212563Sgabeblack@google.com
17312063Sgabeblack@google.comAddLocalOption('--colors', dest='use_colors', action='store_true',
17412063Sgabeblack@google.com               help="Add color to abbreviated scons output")
1755871Snate@binkert.orgAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1765871Snate@binkert.org               help="Don't add color to abbreviated scons output")
1776121Snate@binkert.orgAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1785871Snate@binkert.org               action='store_true',
1795871Snate@binkert.org               help="Build with support for C++-based configuration")
1809926Sstan.czerniawski@arm.comAddLocalOption('--default', dest='default', type='string', action='store',
18112243Sgabeblack@google.com               help='Override which build_opts file to use for defaults')
1821533SN/AAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
18312246Sgabeblack@google.com               help='Disable style checking hooks')
18412246Sgabeblack@google.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
18512246Sgabeblack@google.com               help='Disable Link-Time Optimization for fast')
18612246Sgabeblack@google.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1879239Sandreas.hansson@arm.com               help='Update test reference outputs')
1889239Sandreas.hansson@arm.comAddLocalOption('--verbose', dest='verbose', action='store_true',
1899239Sandreas.hansson@arm.com               help='Print full tool command lines')
1909239Sandreas.hansson@arm.comAddLocalOption('--without-python', dest='without_python',
19112563Sgabeblack@google.com               action='store_true',
1929239Sandreas.hansson@arm.com               help='Build without Python configuration support')
1939239Sandreas.hansson@arm.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
194955SN/A               action='store_true',
195955SN/A               help='Disable linking against tcmalloc')
1962632Sstever@eecs.umich.eduAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1972632Sstever@eecs.umich.edu               help='Build with Undefined Behavior Sanitizer if available')
198955SN/AAddLocalOption('--with-asan', dest='with_asan', action='store_true',
199955SN/A               help='Build with Address Sanitizer if available')
200955SN/A
201955SN/Atermcap = get_termcap(GetOption('use_colors'))
2028878Ssteve.reinhardt@amd.com
203955SN/A########################################################################
2042632Sstever@eecs.umich.edu#
2052632Sstever@eecs.umich.edu# Set up the main build environment.
2062632Sstever@eecs.umich.edu#
2072632Sstever@eecs.umich.edu########################################################################
2082632Sstever@eecs.umich.edu
2092632Sstever@eecs.umich.edu# export TERM so that clang reports errors in color
2102632Sstever@eecs.umich.eduuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2118268Ssteve.reinhardt@amd.com                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2128268Ssteve.reinhardt@amd.com                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
2138268Ssteve.reinhardt@amd.com
2148268Ssteve.reinhardt@amd.comuse_prefixes = [
2158268Ssteve.reinhardt@amd.com    "ASAN_",           # address sanitizer symbolizer path and settings
2168268Ssteve.reinhardt@amd.com    "CCACHE_",         # ccache (caching compiler wrapper) configuration
2178268Ssteve.reinhardt@amd.com    "CCC_",            # clang static analyzer configuration
2182632Sstever@eecs.umich.edu    "DISTCC_",         # distcc (distributed compiler wrapper) configuration
2192632Sstever@eecs.umich.edu    "INCLUDE_SERVER_", # distcc pump server settings
2202632Sstever@eecs.umich.edu    "M5",              # M5 configuration (e.g., path to kernels)
2212632Sstever@eecs.umich.edu    ]
2228268Ssteve.reinhardt@amd.com
2232632Sstever@eecs.umich.eduuse_env = {}
2248268Ssteve.reinhardt@amd.comfor key,val in sorted(os.environ.iteritems()):
2258268Ssteve.reinhardt@amd.com    if key in use_vars or \
2268268Ssteve.reinhardt@amd.com            any([key.startswith(prefix) for prefix in use_prefixes]):
2278268Ssteve.reinhardt@amd.com        use_env[key] = val
2283718Sstever@eecs.umich.edu
2292634Sstever@eecs.umich.edu# Tell scons to avoid implicit command dependencies to avoid issues
2302634Sstever@eecs.umich.edu# with the param wrappes being compiled twice (see
2315863Snate@binkert.org# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2322638Sstever@eecs.umich.edumain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2338268Ssteve.reinhardt@amd.commain.Decider('MD5-timestamp')
2342632Sstever@eecs.umich.edumain.root = Dir(".")         # The current directory (where this file lives).
2352632Sstever@eecs.umich.edumain.srcdir = Dir("src")     # The source directory
2362632Sstever@eecs.umich.edu
2372632Sstever@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
23812563Sgabeblack@google.com
2391858SN/A# Check that we have a C/C++ compiler
2403716Sstever@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2412638Sstever@eecs.umich.edu    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2422638Sstever@eecs.umich.edu    Exit(1)
2432638Sstever@eecs.umich.edu
2442638Sstever@eecs.umich.edu# Check that swig is present
24512563Sgabeblack@google.comif not 'SWIG' in main_dict_keys:
24612563Sgabeblack@google.com    print "swig is not installed (package swig on Ubuntu and RedHat)"
2472638Sstever@eecs.umich.edu    Exit(1)
2485863Snate@binkert.org
2495863Snate@binkert.org# add useful python code PYTHONPATH so it can be used by subprocesses
2505863Snate@binkert.org# as well
251955SN/Amain.AppendENVPath('PYTHONPATH', extra_python_paths)
2525341Sstever@gmail.com
2535341Sstever@gmail.com########################################################################
2545863Snate@binkert.org#
2557756SAli.Saidi@ARM.com# Mercurial Stuff.
2565341Sstever@gmail.com#
2576121Snate@binkert.org# If the gem5 directory is a mercurial repository, we should do some
2584494Ssaidi@eecs.umich.edu# extra things.
2596121Snate@binkert.org#
2601105SN/A########################################################################
2612667Sstever@eecs.umich.edu
2622667Sstever@eecs.umich.eduhgdir = main.root.Dir(".hg")
2632667Sstever@eecs.umich.edu
2642667Sstever@eecs.umich.edu
2656121Snate@binkert.orgstyle_message = """
2662667Sstever@eecs.umich.eduYou're missing the gem5 style hook, which automatically checks your code
2675341Sstever@gmail.comagainst the gem5 style rules on %s.
2685863Snate@binkert.orgThis script will now install the hook in your %s.
2695341Sstever@gmail.comPress enter to continue, or ctrl-c to abort: """
2705341Sstever@gmail.com
2715341Sstever@gmail.commercurial_style_message = style_message % ("hg commit and qrefresh commands",
2728120Sgblack@eecs.umich.edu                                           ".hg/hgrc file")
2735341Sstever@gmail.comgit_style_message = style_message % ("'git commit'",
2748120Sgblack@eecs.umich.edu                                     ".git/hooks/ directory")
2755341Sstever@gmail.com
2768120Sgblack@eecs.umich.edumercurial_style_upgrade_message = """
2776121Snate@binkert.orgYour Mercurial style hooks are not up-to-date. This script will now
2786121Snate@binkert.orgtry to automatically update them. A backup of your hgrc will be saved
2799396Sandreas.hansson@arm.comin .hg/hgrc.old.
2805397Ssaidi@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2815397Ssaidi@eecs.umich.edu
2827727SAli.Saidi@ARM.commercurial_style_hook = """
2838268Ssteve.reinhardt@amd.com# The following lines were automatically added by gem5/SConstruct
2846168Snate@binkert.org# to provide the gem5 style-checking hooks
2855341Sstever@gmail.com[extensions]
2868120Sgblack@eecs.umich.eduhgstyle = %s/util/hgstyle.py
2878120Sgblack@eecs.umich.edu
2888120Sgblack@eecs.umich.edu[hooks]
2896814Sgblack@eecs.umich.edupretxncommit.style = python:hgstyle.check_style
2905863Snate@binkert.orgpre-qrefresh.style = python:hgstyle.check_style
2918120Sgblack@eecs.umich.edu# End of SConstruct additions
2925341Sstever@gmail.com
2935863Snate@binkert.org""" % (main.root.abspath)
2948268Ssteve.reinhardt@amd.com
2956121Snate@binkert.orgmercurial_lib_not_found = """
2966121Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2978268Ssteve.reinhardt@amd.comyou are a gem5 developer, please fix this and run the style
2985742Snate@binkert.orghook. It is important.
2995742Snate@binkert.org"""
3005341Sstever@gmail.com
3015742Snate@binkert.org# Check for style hook and prompt for installation if it's not there.
3025742Snate@binkert.org# Skip this if --ignore-style was specified, there's no interactive
3035341Sstever@gmail.com# terminal to prompt, or no recognized revision control system can be
3046017Snate@binkert.org# found.
3056121Snate@binkert.orgignore_style = GetOption('ignore_style') or not sys.stdin.isatty()
3066017Snate@binkert.org
30712158Sandreas.sandberg@arm.com# Try wire up Mercurial to the style hooks
30812158Sandreas.sandberg@arm.comif not ignore_style and hgdir.exists():
30912158Sandreas.sandberg@arm.com    style_hook = True
3108120Sgblack@eecs.umich.edu    style_hooks = tuple()
3117756SAli.Saidi@ARM.com    hgrc = hgdir.File('hgrc')
3127756SAli.Saidi@ARM.com    hgrc_old = hgdir.File('hgrc.old')
3137756SAli.Saidi@ARM.com    try:
3147756SAli.Saidi@ARM.com        from mercurial import ui
3157816Ssteve.reinhardt@amd.com        ui = ui.ui()
3167816Ssteve.reinhardt@amd.com        ui.readconfig(hgrc.abspath)
3177816Ssteve.reinhardt@amd.com        style_hooks = (ui.config('hooks', 'pretxncommit.style', None),
3187816Ssteve.reinhardt@amd.com                       ui.config('hooks', 'pre-qrefresh.style', None))
3197816Ssteve.reinhardt@amd.com        style_hook = all(style_hooks)
32011979Sgabeblack@google.com        style_extension = ui.config('extensions', 'style', None)
3217816Ssteve.reinhardt@amd.com    except ImportError:
3227816Ssteve.reinhardt@amd.com        print mercurial_lib_not_found
3237816Ssteve.reinhardt@amd.com
3247816Ssteve.reinhardt@amd.com    if "python:style.check_style" in style_hooks:
3257756SAli.Saidi@ARM.com        # Try to upgrade the style hooks
3267756SAli.Saidi@ARM.com        print mercurial_style_upgrade_message
3279227Sandreas.hansson@arm.com        # continue unless user does ctrl-c/ctrl-d etc.
3289227Sandreas.hansson@arm.com        try:
3299227Sandreas.hansson@arm.com            raw_input()
3309227Sandreas.hansson@arm.com        except:
3319590Sandreas@sandberg.pp.se            print "Input exception, exiting scons.\n"
3329590Sandreas@sandberg.pp.se            sys.exit(1)
3339590Sandreas@sandberg.pp.se        shutil.copyfile(hgrc.abspath, hgrc_old.abspath)
3349590Sandreas@sandberg.pp.se        re_style_hook = re.compile(r"^([^=#]+)\.style\s*=\s*([^#\s]+).*")
3359590Sandreas@sandberg.pp.se        re_style_extension = re.compile("style\s*=\s*([^#\s]+).*")
3369590Sandreas@sandberg.pp.se        old, new = open(hgrc_old.abspath, 'r'), open(hgrc.abspath, 'w')
3376654Snate@binkert.org        for l in old:
3386654Snate@binkert.org            m_hook = re_style_hook.match(l)
3395871Snate@binkert.org            m_ext = re_style_extension.match(l)
3406121Snate@binkert.org            if m_hook:
3418946Sandreas.hansson@arm.com                hook, check = m_hook.groups()
3429419Sandreas.hansson@arm.com                if check != "python:style.check_style":
34312563Sgabeblack@google.com                    print "Warning: %s.style is using a non-default " \
3443918Ssaidi@eecs.umich.edu                        "checker: %s" % (hook, check)
3453918Ssaidi@eecs.umich.edu                if hook not in ("pretxncommit", "pre-qrefresh"):
3461858SN/A                    print "Warning: Updating unknown style hook: %s" % hook
3479556Sandreas.hansson@arm.com
3489556Sandreas.hansson@arm.com                l = "%s.style = python:hgstyle.check_style\n" % hook
3499556Sandreas.hansson@arm.com            elif m_ext and m_ext.group(1) == style_extension:
3509556Sandreas.hansson@arm.com                l = "hgstyle = %s/util/hgstyle.py\n" % main.root.abspath
35111294Sandreas.hansson@arm.com
35211294Sandreas.hansson@arm.com            new.write(l)
35311294Sandreas.hansson@arm.com    elif not style_hook:
35411294Sandreas.hansson@arm.com        print mercurial_style_message,
35510878Sandreas.hansson@arm.com        # continue unless user does ctrl-c/ctrl-d etc.
35610878Sandreas.hansson@arm.com        try:
35711811Sbaz21@cam.ac.uk            raw_input()
35811811Sbaz21@cam.ac.uk        except:
35911811Sbaz21@cam.ac.uk            print "Input exception, exiting scons.\n"
36011982Sgabeblack@google.com            sys.exit(1)
36111982Sgabeblack@google.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
36211982Sgabeblack@google.com        print "Adding style hook to", hgrc_path, "\n"
36313421Sciro.santilli@arm.com        try:
36413421Sciro.santilli@arm.com            with open(hgrc_path, 'a') as f:
36511982Sgabeblack@google.com                f.write(mercurial_style_hook)
36611992Sgabeblack@google.com        except:
36711982Sgabeblack@google.com            print "Error updating", hgrc_path
36811982Sgabeblack@google.com            sys.exit(1)
36912305Sgabeblack@google.com
37012305Sgabeblack@google.comdef install_git_style_hooks():
37112305Sgabeblack@google.com    try:
37212305Sgabeblack@google.com        gitdir = Dir(readCommand(
37312305Sgabeblack@google.com            ["git", "rev-parse", "--git-dir"]).strip("\n"))
37412305Sgabeblack@google.com    except Exception, e:
37512305Sgabeblack@google.com        print "Warning: Failed to find git repo directory: %s" % e
3769556Sandreas.hansson@arm.com        return
37712563Sgabeblack@google.com
37812563Sgabeblack@google.com    git_hooks = gitdir.Dir("hooks")
37912563Sgabeblack@google.com    git_pre_commit_hook = git_hooks.File("pre-commit")
38012563Sgabeblack@google.com    git_style_script = File("util/git-pre-commit.py")
3819556Sandreas.hansson@arm.com
38212563Sgabeblack@google.com    if git_pre_commit_hook.exists():
38312563Sgabeblack@google.com        return
3849556Sandreas.hansson@arm.com
38512563Sgabeblack@google.com    print git_style_message,
38612563Sgabeblack@google.com    try:
38712563Sgabeblack@google.com        raw_input()
38812563Sgabeblack@google.com    except:
38912563Sgabeblack@google.com        print "Input exception, exiting scons.\n"
39012563Sgabeblack@google.com        sys.exit(1)
39112563Sgabeblack@google.com
39212563Sgabeblack@google.com    if not git_hooks.exists():
3939556Sandreas.hansson@arm.com        mkdir(git_hooks.get_abspath())
3949556Sandreas.hansson@arm.com
3956121Snate@binkert.org    # Use a relative symlink if the hooks live in the source directory
39611500Sandreas.hansson@arm.com    if git_pre_commit_hook.is_under(main.root):
39710238Sandreas.hansson@arm.com        script_path = os.path.relpath(
39810878Sandreas.hansson@arm.com            git_style_script.get_abspath(),
3999420Sandreas.hansson@arm.com            git_pre_commit_hook.Dir(".").get_abspath())
40011500Sandreas.hansson@arm.com    else:
40112563Sgabeblack@google.com        script_path = git_style_script.get_abspath()
40212563Sgabeblack@google.com
4039420Sandreas.hansson@arm.com    try:
4049420Sandreas.hansson@arm.com        os.symlink(script_path, git_pre_commit_hook.get_abspath())
4059420Sandreas.hansson@arm.com    except:
4069420Sandreas.hansson@arm.com        print "Error updating git pre-commit hook"
40712063Sgabeblack@google.com        raise
40812063Sgabeblack@google.com
40912063Sgabeblack@google.com# Try to wire up git to the style hooks
41012063Sgabeblack@google.comif not ignore_style and main.root.Entry(".git").exists():
41112063Sgabeblack@google.com    install_git_style_hooks()
41212063Sgabeblack@google.com
41312063Sgabeblack@google.com###################################################
41412063Sgabeblack@google.com#
41512063Sgabeblack@google.com# Figure out which configurations to set up based on the path(s) of
41612063Sgabeblack@google.com# the target(s).
41712063Sgabeblack@google.com#
41812063Sgabeblack@google.com###################################################
41912063Sgabeblack@google.com
42012063Sgabeblack@google.com# Find default configuration & binary.
42112063Sgabeblack@google.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
42212063Sgabeblack@google.com
42312063Sgabeblack@google.com# helper function: find last occurrence of element in list
42412063Sgabeblack@google.comdef rfind(l, elt, offs = -1):
42512063Sgabeblack@google.com    for i in range(len(l)+offs, 0, -1):
42612063Sgabeblack@google.com        if l[i] == elt:
42712063Sgabeblack@google.com            return i
42812063Sgabeblack@google.com    raise ValueError, "element not found"
42910457Sandreas.hansson@arm.com
43010457Sandreas.hansson@arm.com# Take a list of paths (or SCons Nodes) and return a list with all
43110457Sandreas.hansson@arm.com# paths made absolute and ~-expanded.  Paths will be interpreted
43210457Sandreas.hansson@arm.com# relative to the launch directory unless a different root is provided
43310457Sandreas.hansson@arm.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
43412563Sgabeblack@google.com    return [abspath(joinpath(root, expanduser(str(p))))
43512563Sgabeblack@google.com            for p in path_list]
43612563Sgabeblack@google.com
43710457Sandreas.hansson@arm.com# Each target must have 'build' in the interior of the path; the
43812063Sgabeblack@google.com# directory below this will determine the build parameters.  For
43912063Sgabeblack@google.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
44012063Sgabeblack@google.com# recognize that ALPHA_SE specifies the configuration because it
44112563Sgabeblack@google.com# follow 'build' in the build path.
44212563Sgabeblack@google.com
44312563Sgabeblack@google.com# The funky assignment to "[:]" is needed to replace the list contents
44412563Sgabeblack@google.com# in place rather than reassign the symbol to a new list, which
44512563Sgabeblack@google.com# doesn't work (obviously!).
44612563Sgabeblack@google.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
44712063Sgabeblack@google.com
44812063Sgabeblack@google.com# Generate a list of the unique build roots and configs that the
44910238Sandreas.hansson@arm.com# collected targets reference.
45010238Sandreas.hansson@arm.comvariant_paths = []
45110238Sandreas.hansson@arm.combuild_root = None
45212063Sgabeblack@google.comfor t in BUILD_TARGETS:
45310238Sandreas.hansson@arm.com    path_dirs = t.split('/')
45410238Sandreas.hansson@arm.com    try:
45510416Sandreas.hansson@arm.com        build_top = rfind(path_dirs, 'build', -2)
45610238Sandreas.hansson@arm.com    except:
4579227Sandreas.hansson@arm.com        print "Error: no non-leaf 'build' dir found on target path", t
45810238Sandreas.hansson@arm.com        Exit(1)
45910416Sandreas.hansson@arm.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
46010416Sandreas.hansson@arm.com    if not build_root:
4619227Sandreas.hansson@arm.com        build_root = this_build_root
4629590Sandreas@sandberg.pp.se    else:
4639590Sandreas@sandberg.pp.se        if this_build_root != build_root:
4649590Sandreas@sandberg.pp.se            print "Error: build targets not under same build root\n"\
46512304Sgabeblack@google.com                  "  %s\n  %s" % (build_root, this_build_root)
46612304Sgabeblack@google.com            Exit(1)
46712304Sgabeblack@google.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
46812688Sgiacomo.travaglini@arm.com    if variant_path not in variant_paths:
46912688Sgiacomo.travaglini@arm.com        variant_paths.append(variant_path)
47012688Sgiacomo.travaglini@arm.com
47113020Sshunhsingou@google.com# Make sure build_root exists (might not if this is the first build there)
47212304Sgabeblack@google.comif not isdir(build_root):
47312688Sgiacomo.travaglini@arm.com    mkdir(build_root)
47412688Sgiacomo.travaglini@arm.commain['BUILDROOT'] = build_root
47513020Sshunhsingou@google.com
47612304Sgabeblack@google.comExport('main')
47712304Sgabeblack@google.com
47812304Sgabeblack@google.commain.SConsignFile(joinpath(build_root, "sconsign"))
47912304Sgabeblack@google.com
48012688Sgiacomo.travaglini@arm.com# Default duplicate option is to use hard links, but this messes up
48112688Sgiacomo.travaglini@arm.com# when you use emacs to edit a file in the target dir, as emacs moves
48212688Sgiacomo.travaglini@arm.com# file to file~ then copies to file, breaking the link.  Symbolic
48312304Sgabeblack@google.com# (soft) links work better.
4848737Skoansin.tan@gmail.commain.SetOption('duplicate', 'soft-copy')
48510878Sandreas.hansson@arm.com
48611500Sandreas.hansson@arm.com#
4879420Sandreas.hansson@arm.com# Set up global sticky variables... these are common to an entire build
4888737Skoansin.tan@gmail.com# tree (not specific to a particular build like ALPHA_SE)
48910106SMitch.Hayenga@arm.com#
4908737Skoansin.tan@gmail.com
4918737Skoansin.tan@gmail.comglobal_vars_file = joinpath(build_root, 'variables.global')
49210878Sandreas.hansson@arm.com
49312563Sgabeblack@google.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
49412563Sgabeblack@google.com
4958737Skoansin.tan@gmail.comglobal_vars.AddVariables(
4968737Skoansin.tan@gmail.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
49712563Sgabeblack@google.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
4988737Skoansin.tan@gmail.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
4998737Skoansin.tan@gmail.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
50011294Sandreas.hansson@arm.com    ('BATCH', 'Use batch pool for build and tests', False),
5019556Sandreas.hansson@arm.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
5029556Sandreas.hansson@arm.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
5039556Sandreas.hansson@arm.com    ('EXTRAS', 'Add extra directories to the compilation', '')
50411294Sandreas.hansson@arm.com    )
50510278SAndreas.Sandberg@ARM.com
50610278SAndreas.Sandberg@ARM.com# Update main environment with values from ARGUMENTS & global_vars_file
50710278SAndreas.Sandberg@ARM.comglobal_vars.Update(main)
50810278SAndreas.Sandberg@ARM.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
50910278SAndreas.Sandberg@ARM.com
51010278SAndreas.Sandberg@ARM.com# Save sticky variable settings back to current variables file
5119556Sandreas.hansson@arm.comglobal_vars.Save(global_vars_file, main)
5129590Sandreas@sandberg.pp.se
5139590Sandreas@sandberg.pp.se# Parse EXTRAS variable to build list of all directories where we're
5149420Sandreas.hansson@arm.com# look for sources etc.  This list is exported as extras_dir_list.
5159846Sandreas.hansson@arm.combase_dir = main.srcdir.abspath
5169846Sandreas.hansson@arm.comif main['EXTRAS']:
5179846Sandreas.hansson@arm.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
5189846Sandreas.hansson@arm.comelse:
5198946Sandreas.hansson@arm.com    extras_dir_list = []
52011811Sbaz21@cam.ac.uk
52111811Sbaz21@cam.ac.ukExport('base_dir')
52211811Sbaz21@cam.ac.ukExport('extras_dir_list')
52311811Sbaz21@cam.ac.uk
52412304Sgabeblack@google.com# the ext directory should be on the #includes path
52512304Sgabeblack@google.commain.Append(CPPPATH=[Dir('ext')])
52612304Sgabeblack@google.com
52712304Sgabeblack@google.comdef strip_build_path(path, env):
52813020Sshunhsingou@google.com    path = str(path)
52913020Sshunhsingou@google.com    variant_base = env['BUILDROOT'] + os.path.sep
53012304Sgabeblack@google.com    if path.startswith(variant_base):
53112304Sgabeblack@google.com        path = path[len(variant_base):]
53213020Sshunhsingou@google.com    elif path.startswith('build/'):
53313020Sshunhsingou@google.com        path = path[6:]
53412304Sgabeblack@google.com    return path
53512304Sgabeblack@google.com
53613020Sshunhsingou@google.com# Generate a string of the form:
53713020Sshunhsingou@google.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
53812304Sgabeblack@google.com# to print while building.
53912304Sgabeblack@google.comclass Transform(object):
5403918Ssaidi@eecs.umich.edu    # all specific color settings should be here and nowhere else
54112563Sgabeblack@google.com    tool_color = termcap.Normal
54212563Sgabeblack@google.com    pfx_color = termcap.Yellow
54312563Sgabeblack@google.com    srcs_color = termcap.Yellow + termcap.Bold
54412563Sgabeblack@google.com    arrow_color = termcap.Blue + termcap.Bold
5459068SAli.Saidi@ARM.com    tgts_color = termcap.Yellow + termcap.Bold
54612563Sgabeblack@google.com
54712563Sgabeblack@google.com    def __init__(self, tool, max_sources=99):
5489068SAli.Saidi@ARM.com        self.format = self.tool_color + (" [%8s] " % tool) \
54912563Sgabeblack@google.com                      + self.pfx_color + "%s" \
55012563Sgabeblack@google.com                      + self.srcs_color + "%s" \
55112563Sgabeblack@google.com                      + self.arrow_color + " -> " \
55212563Sgabeblack@google.com                      + self.tgts_color + "%s" \
55312563Sgabeblack@google.com                      + termcap.Normal
55412563Sgabeblack@google.com        self.max_sources = max_sources
55512563Sgabeblack@google.com
55612563Sgabeblack@google.com    def __call__(self, target, source, env, for_signature=None):
5573918Ssaidi@eecs.umich.edu        # truncate source list according to max_sources param
5583918Ssaidi@eecs.umich.edu        source = source[0:self.max_sources]
5596157Snate@binkert.org        def strip(f):
5606157Snate@binkert.org            return strip_build_path(str(f), env)
5616157Snate@binkert.org        if len(source) > 0:
5626157Snate@binkert.org            srcs = map(strip, source)
5635397Ssaidi@eecs.umich.edu        else:
5645397Ssaidi@eecs.umich.edu            srcs = ['']
5656121Snate@binkert.org        tgts = map(strip, target)
5666121Snate@binkert.org        # surprisingly, os.path.commonprefix is a dumb char-by-char string
5676121Snate@binkert.org        # operation that has nothing to do with paths.
5686121Snate@binkert.org        com_pfx = os.path.commonprefix(srcs + tgts)
5696121Snate@binkert.org        com_pfx_len = len(com_pfx)
5706121Snate@binkert.org        if com_pfx:
5715397Ssaidi@eecs.umich.edu            # do some cleanup and sanity checking on common prefix
5721851SN/A            if com_pfx[-1] == ".":
5731851SN/A                # prefix matches all but file extension: ok
5747739Sgblack@eecs.umich.edu                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
575955SN/A                com_pfx = com_pfx[0:-1]
5769396Sandreas.hansson@arm.com            elif com_pfx[-1] == "/":
5779396Sandreas.hansson@arm.com                # common prefix is directory path: OK
5789396Sandreas.hansson@arm.com                pass
5799396Sandreas.hansson@arm.com            else:
5809396Sandreas.hansson@arm.com                src0_len = len(srcs[0])
5819396Sandreas.hansson@arm.com                tgt0_len = len(tgts[0])
58212563Sgabeblack@google.com                if src0_len == com_pfx_len:
58312563Sgabeblack@google.com                    # source is a substring of target, OK
58412563Sgabeblack@google.com                    pass
58512563Sgabeblack@google.com                elif tgt0_len == com_pfx_len:
5869396Sandreas.hansson@arm.com                    # target is a substring of source, need to back up to
5879396Sandreas.hansson@arm.com                    # avoid empty string on RHS of arrow
5889396Sandreas.hansson@arm.com                    sep_idx = com_pfx.rfind(".")
5899396Sandreas.hansson@arm.com                    if sep_idx != -1:
5909396Sandreas.hansson@arm.com                        com_pfx = com_pfx[0:sep_idx]
5919396Sandreas.hansson@arm.com                    else:
59212563Sgabeblack@google.com                        com_pfx = ''
59312563Sgabeblack@google.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
59412563Sgabeblack@google.com                    # still splitting at file extension: ok
59512563Sgabeblack@google.com                    pass
59612563Sgabeblack@google.com                else:
5979477Sandreas.hansson@arm.com                    # probably a fluke; ignore it
5989477Sandreas.hansson@arm.com                    com_pfx = ''
5999477Sandreas.hansson@arm.com        # recalculate length in case com_pfx was modified
6009477Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
6019477Sandreas.hansson@arm.com        def fmt(files):
6029477Sandreas.hansson@arm.com            f = map(lambda s: s[com_pfx_len:], files)
6039477Sandreas.hansson@arm.com            return ', '.join(f)
6049477Sandreas.hansson@arm.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
6059477Sandreas.hansson@arm.com
6069477Sandreas.hansson@arm.comExport('Transform')
6079477Sandreas.hansson@arm.com
6089477Sandreas.hansson@arm.com# enable the regression script to use the termcap
6099477Sandreas.hansson@arm.commain['TERMCAP'] = termcap
6109477Sandreas.hansson@arm.com
61112563Sgabeblack@google.comif GetOption('verbose'):
61212563Sgabeblack@google.com    def MakeAction(action, string, *args, **kwargs):
61312563Sgabeblack@google.com        return Action(action, *args, **kwargs)
6149396Sandreas.hansson@arm.comelse:
6152667Sstever@eecs.umich.edu    MakeAction = Action
61610710Sandreas.hansson@arm.com    main['CCCOMSTR']        = Transform("CC")
61710710Sandreas.hansson@arm.com    main['CXXCOMSTR']       = Transform("CXX")
61810710Sandreas.hansson@arm.com    main['ASCOMSTR']        = Transform("AS")
61911811Sbaz21@cam.ac.uk    main['SWIGCOMSTR']      = Transform("SWIG")
62011811Sbaz21@cam.ac.uk    main['ARCOMSTR']        = Transform("AR", 0)
62111811Sbaz21@cam.ac.uk    main['LINKCOMSTR']      = Transform("LINK", 0)
62211811Sbaz21@cam.ac.uk    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
62311811Sbaz21@cam.ac.uk    main['M4COMSTR']        = Transform("M4")
62411811Sbaz21@cam.ac.uk    main['SHCCCOMSTR']      = Transform("SHCC")
62510710Sandreas.hansson@arm.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
62610710Sandreas.hansson@arm.comExport('MakeAction')
62710710Sandreas.hansson@arm.com
62810710Sandreas.hansson@arm.com# Initialize the Link-Time Optimization (LTO) flags
62910384SCurtis.Dunham@arm.commain['LTO_CCFLAGS'] = []
6309986Sandreas@sandberg.pp.semain['LTO_LDFLAGS'] = []
6319986Sandreas@sandberg.pp.se
6329986Sandreas@sandberg.pp.se# According to the readme, tcmalloc works best if the compiler doesn't
6339986Sandreas@sandberg.pp.se# assume that we're using the builtin malloc and friends. These flags
6349986Sandreas@sandberg.pp.se# are compiler-specific, so we need to set them after we detect which
6359986Sandreas@sandberg.pp.se# compiler we're using.
6369986Sandreas@sandberg.pp.semain['TCMALLOC_CCFLAGS'] = []
6379986Sandreas@sandberg.pp.se
6389986Sandreas@sandberg.pp.seCXX_version = readCommand([main['CXX'],'--version'], exception=False)
6399986Sandreas@sandberg.pp.seCXX_V = readCommand([main['CXX'],'-V'], exception=False)
6409986Sandreas@sandberg.pp.se
6419986Sandreas@sandberg.pp.semain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
6429986Sandreas@sandberg.pp.semain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
6439986Sandreas@sandberg.pp.seif main['GCC'] + main['CLANG'] > 1:
6449986Sandreas@sandberg.pp.se    print 'Error: How can we have two at the same time?'
6459986Sandreas@sandberg.pp.se    Exit(1)
6469986Sandreas@sandberg.pp.se
6479986Sandreas@sandberg.pp.se# Set up default C++ compiler flags
6489986Sandreas@sandberg.pp.seif main['GCC'] or main['CLANG']:
6499986Sandreas@sandberg.pp.se    # As gcc and clang share many flags, do the common parts here
6502638Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
6512638Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
6526121Snate@binkert.org    # Enable -Wall and -Wextra and then disable the few warnings that
6533716Sstever@eecs.umich.edu    # we consistently violate
6545522Snate@binkert.org    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
6559986Sandreas@sandberg.pp.se                         '-Wno-sign-compare', '-Wno-unused-parameter'])
6569986Sandreas@sandberg.pp.se    # We always compile using C++11
6579986Sandreas@sandberg.pp.se    main.Append(CXXFLAGS=['-std=c++11'])
6585522Snate@binkert.orgelse:
6595227Ssaidi@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6605227Ssaidi@eecs.umich.edu    print "Don't know what compiler options to use for your compiler."
6615227Ssaidi@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6625227Ssaidi@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
6636654Snate@binkert.org    if not CXX_version:
6646654Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6657769SAli.Saidi@ARM.com               termcap.Normal
6667769SAli.Saidi@ARM.com    else:
6677769SAli.Saidi@ARM.com        print CXX_version.replace('\n', '<nl>')
6687769SAli.Saidi@ARM.com    print "       If you're trying to use a compiler other than GCC"
6695227Ssaidi@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
6705227Ssaidi@eecs.umich.edu    print "       environment."
6715227Ssaidi@eecs.umich.edu    print "       "
6725204Sstever@gmail.com    print "       If you are trying to use a compiler other than those listed"
6735204Sstever@gmail.com    print "       above you will need to ease fix SConstruct and "
6745204Sstever@gmail.com    print "       src/SConscript to support that compiler."
6755204Sstever@gmail.com    Exit(1)
6765204Sstever@gmail.com
6775204Sstever@gmail.comif main['GCC']:
6785204Sstever@gmail.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
6795204Sstever@gmail.com    # level of c++11 support. See
6805204Sstever@gmail.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
6815204Sstever@gmail.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
6825204Sstever@gmail.com    if compareVersions(gcc_version, "4.8") < 0:
6835204Sstever@gmail.com        print 'Error: gcc version 4.8 or newer required.'
6845204Sstever@gmail.com        print '       Installed version:', gcc_version
6855204Sstever@gmail.com        Exit(1)
6865204Sstever@gmail.com
6875204Sstever@gmail.com    main['GCC_VERSION'] = gcc_version
6885204Sstever@gmail.com
6896121Snate@binkert.org    # gcc from version 4.8 and above generates "rep; ret" instructions
6905204Sstever@gmail.com    # to avoid performance penalties on certain AMD chips. Older
6917727SAli.Saidi@ARM.com    # assemblers detect this as an error, "Error: expecting string
6927727SAli.Saidi@ARM.com    # instruction after `rep'"
69312563Sgabeblack@google.com    as_version_raw = readCommand([main['AS'], '-v', '/dev/null'],
6947727SAli.Saidi@ARM.com                                 exception=False).split()
6957727SAli.Saidi@ARM.com
69611988Sandreas.sandberg@arm.com    # version strings may contain extra distro-specific
69711988Sandreas.sandberg@arm.com    # qualifiers, so play it safe and keep only what comes before
69810453SAndrew.Bardsley@arm.com    # the first hyphen
69910453SAndrew.Bardsley@arm.com    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
70010453SAndrew.Bardsley@arm.com
70110453SAndrew.Bardsley@arm.com    if not as_version or compareVersions(as_version, "2.23") < 0:
70210453SAndrew.Bardsley@arm.com        print termcap.Yellow + termcap.Bold + \
70310453SAndrew.Bardsley@arm.com            'Warning: This combination of gcc and binutils have' + \
70410453SAndrew.Bardsley@arm.com            ' known incompatibilities.\n' + \
70510453SAndrew.Bardsley@arm.com            '         If you encounter build problems, please update ' + \
70610453SAndrew.Bardsley@arm.com            'binutils to 2.23.' + \
70710453SAndrew.Bardsley@arm.com            termcap.Normal
70810160Sandreas.hansson@arm.com
70910453SAndrew.Bardsley@arm.com    # Make sure we warn if the user has requested to compile with the
71010453SAndrew.Bardsley@arm.com    # Undefined Benahvior Sanitizer and this version of gcc does not
71110453SAndrew.Bardsley@arm.com    # support it.
71210453SAndrew.Bardsley@arm.com    if GetOption('with_ubsan') and \
71310453SAndrew.Bardsley@arm.com            compareVersions(gcc_version, '4.9') < 0:
71413541Sandrea.mondelli@ucf.edu        print termcap.Yellow + termcap.Bold + \
71510453SAndrew.Bardsley@arm.com            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
71610453SAndrew.Bardsley@arm.com            termcap.Normal
71713541Sandrea.mondelli@ucf.edu
71813541Sandrea.mondelli@ucf.edu    # Add the appropriate Link-Time Optimization (LTO) flags
7199812Sandreas.hansson@arm.com    # unless LTO is explicitly turned off. Note that these flags
72010453SAndrew.Bardsley@arm.com    # are only used by the fast target.
72110453SAndrew.Bardsley@arm.com    if not GetOption('no_lto'):
72210453SAndrew.Bardsley@arm.com        # Pass the LTO flag when compiling to produce GIMPLE
72310453SAndrew.Bardsley@arm.com        # output, we merely create the flags here and only append
72410453SAndrew.Bardsley@arm.com        # them later
72510453SAndrew.Bardsley@arm.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
72610453SAndrew.Bardsley@arm.com
72710453SAndrew.Bardsley@arm.com        # Use the same amount of jobs for LTO as we are running
72810453SAndrew.Bardsley@arm.com        # scons with
72910453SAndrew.Bardsley@arm.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
73010453SAndrew.Bardsley@arm.com
73110453SAndrew.Bardsley@arm.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
7327727SAli.Saidi@ARM.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
73310453SAndrew.Bardsley@arm.com
73410453SAndrew.Bardsley@arm.com    # add option to check for undeclared overrides
73512790Smatteo.fusi@bsc.es    if compareVersions(gcc_version, "5.0") > 0:
73612790Smatteo.fusi@bsc.es        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
73712790Smatteo.fusi@bsc.es
73812790Smatteo.fusi@bsc.eselif main['CLANG']:
73912790Smatteo.fusi@bsc.es    # Check for a supported version of clang, >= 3.1 is needed to
74012790Smatteo.fusi@bsc.es    # support similar features as gcc 4.8. See
74112790Smatteo.fusi@bsc.es    # http://clang.llvm.org/cxx_status.html for details
74210453SAndrew.Bardsley@arm.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
7433118Sstever@eecs.umich.edu    clang_version_match = clang_version_re.search(CXX_version)
74410453SAndrew.Bardsley@arm.com    if (clang_version_match):
74510453SAndrew.Bardsley@arm.com        clang_version = clang_version_match.groups()[0]
74612563Sgabeblack@google.com        if compareVersions(clang_version, "3.1") < 0:
74710453SAndrew.Bardsley@arm.com            print 'Error: clang version 3.1 or newer required.'
7483118Sstever@eecs.umich.edu            print '       Installed version:', clang_version
7493483Ssaidi@eecs.umich.edu            Exit(1)
7503494Ssaidi@eecs.umich.edu    else:
7513494Ssaidi@eecs.umich.edu        print 'Error: Unable to determine clang version.'
75212563Sgabeblack@google.com        Exit(1)
7533483Ssaidi@eecs.umich.edu
7543483Ssaidi@eecs.umich.edu    # clang has a few additional warnings that we disable, extraneous
7553053Sstever@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
7563053Sstever@eecs.umich.edu    # finally self assignments are allowed as the generated CPU code
7573918Ssaidi@eecs.umich.edu    # is relying on this
75812563Sgabeblack@google.com    main.Append(CCFLAGS=['-Wno-parentheses',
75912563Sgabeblack@google.com                         '-Wno-self-assign',
76012563Sgabeblack@google.com                         # Some versions of libstdc++ (4.8?) seem to
7613053Sstever@eecs.umich.edu                         # use struct hash and class hash
7623053Sstever@eecs.umich.edu                         # interchangeably.
7639396Sandreas.hansson@arm.com                         '-Wno-mismatched-tags',
7649396Sandreas.hansson@arm.com                         ])
7659396Sandreas.hansson@arm.com
7669396Sandreas.hansson@arm.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
7679396Sandreas.hansson@arm.com
7689396Sandreas.hansson@arm.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
7699396Sandreas.hansson@arm.com    # opposed to libstdc++, as the later is dated.
7709396Sandreas.hansson@arm.com    if sys.platform == "darwin":
7719396Sandreas.hansson@arm.com        main.Append(CXXFLAGS=['-stdlib=libc++'])
77212920Sgabeblack@google.com        main.Append(LIBS=['c++'])
77312920Sgabeblack@google.com
77412920Sgabeblack@google.comelse:
77512920Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
7769477Sandreas.hansson@arm.com    print "Don't know what compiler options to use for your compiler."
7779396Sandreas.hansson@arm.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
77812563Sgabeblack@google.com    print termcap.Yellow + '       version:' + termcap.Normal,
77912563Sgabeblack@google.com    if not CXX_version:
78012563Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
78112563Sgabeblack@google.com               termcap.Normal
7829396Sandreas.hansson@arm.com    else:
7837840Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
7847865Sgblack@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
7857865Sgblack@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
7867865Sgblack@eecs.umich.edu    print "       environment."
7877865Sgblack@eecs.umich.edu    print "       "
7887865Sgblack@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
7897840Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
7909900Sandreas@sandberg.pp.se    print "       src/SConscript to support that compiler."
7919900Sandreas@sandberg.pp.se    Exit(1)
7929900Sandreas@sandberg.pp.se
7939900Sandreas@sandberg.pp.se# Set up common yacc/bison flags (needed for Ruby)
79410456SCurtis.Dunham@arm.commain['YACCFLAGS'] = '-d'
79510456SCurtis.Dunham@arm.commain['YACCHXXFILESUFFIX'] = '.hh'
79610456SCurtis.Dunham@arm.com
79710456SCurtis.Dunham@arm.com# Do this after we save setting back, or else we'll tack on an
79810456SCurtis.Dunham@arm.com# extra 'qdo' every time we run scons.
79910456SCurtis.Dunham@arm.comif main['BATCH']:
80012563Sgabeblack@google.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
80112563Sgabeblack@google.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
80212563Sgabeblack@google.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
80312563Sgabeblack@google.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
8049045SAli.Saidi@ARM.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
80511235Sandreas.sandberg@arm.com
80611235Sandreas.sandberg@arm.comif sys.platform == 'cygwin':
80711235Sandreas.sandberg@arm.com    # cygwin has some header file issues...
80811235Sandreas.sandberg@arm.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
80911235Sandreas.sandberg@arm.com
81012485Sjang.hanhwi@gmail.com# Check for the protobuf compiler
81112485Sjang.hanhwi@gmail.comprotoc_version = readCommand([main['PROTOC'], '--version'],
81212485Sjang.hanhwi@gmail.com                             exception='').split()
81311235Sandreas.sandberg@arm.com
81411811Sbaz21@cam.ac.uk# First two words should be "libprotoc x.y.z"
81512485Sjang.hanhwi@gmail.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
81611811Sbaz21@cam.ac.uk    print termcap.Yellow + termcap.Bold + \
81711811Sbaz21@cam.ac.uk        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
81811811Sbaz21@cam.ac.uk        '         Please install protobuf-compiler for tracing support.' + \
81911235Sandreas.sandberg@arm.com        termcap.Normal
82011235Sandreas.sandberg@arm.com    main['PROTOC'] = False
82111235Sandreas.sandberg@arm.comelse:
82212563Sgabeblack@google.com    # Based on the availability of the compress stream wrappers,
82312563Sgabeblack@google.com    # require 2.1.0
82412563Sgabeblack@google.com    min_protoc_version = '2.1.0'
82511235Sandreas.sandberg@arm.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
8267840Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
82712563Sgabeblack@google.com            'Warning: protoc version', min_protoc_version, \
8287840Snate@binkert.org            'or newer required.\n' + \
8291858SN/A            '         Installed version:', protoc_version[1], \
8301858SN/A            termcap.Normal
8311858SN/A        main['PROTOC'] = False
83212563Sgabeblack@google.com    else:
83312563Sgabeblack@google.com        # Attempt to determine the appropriate include path and
8341858SN/A        # library path using pkg-config, that means we also need to
83512230Sgiacomo.travaglini@arm.com        # check for pkg-config. Note that it is possible to use
83612230Sgiacomo.travaglini@arm.com        # protobuf without the involvement of pkg-config. Later on we
83712230Sgiacomo.travaglini@arm.com        # check go a library config check and at that point the test
83812230Sgiacomo.travaglini@arm.com        # will fail if libprotobuf cannot be found.
83912563Sgabeblack@google.com        if readCommand(['pkg-config', '--version'], exception=''):
84012563Sgabeblack@google.com            try:
84112563Sgabeblack@google.com                # Attempt to establish what linking flags to add for protobuf
84212230Sgiacomo.travaglini@arm.com                # using pkg-config
8439903Sandreas.hansson@arm.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
8449903Sandreas.hansson@arm.com            except:
8459903Sandreas.hansson@arm.com                print termcap.Yellow + termcap.Bold + \
8469903Sandreas.hansson@arm.com                    'Warning: pkg-config could not get protobuf flags.' + \
84710841Sandreas.sandberg@arm.com                    termcap.Normal
8489651SAndreas.Sandberg@ARM.com
84912563Sgabeblack@google.com# Check for SWIG
85012563Sgabeblack@google.comif not main.has_key('SWIG'):
8519651SAndreas.Sandberg@ARM.com    print 'Error: SWIG utility not found.'
85212056Sgabeblack@google.com    print '       Please install (see http://www.swig.org) and retry.'
85312056Sgabeblack@google.com    Exit(1)
85412056Sgabeblack@google.com
85512563Sgabeblack@google.com# Check for appropriate SWIG version
85612056Sgabeblack@google.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
85710841Sandreas.sandberg@arm.com# First 3 words should be "SWIG Version x.y.z"
85810841Sandreas.sandberg@arm.comif len(swig_version) < 3 or \
85910841Sandreas.sandberg@arm.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
86010841Sandreas.sandberg@arm.com    print 'Error determining SWIG version.'
86110841Sandreas.sandberg@arm.com    Exit(1)
86210841Sandreas.sandberg@arm.com
8639651SAndreas.Sandberg@ARM.commin_swig_version = '2.0.4'
8649651SAndreas.Sandberg@ARM.comif compareVersions(swig_version[2], min_swig_version) < 0:
8659651SAndreas.Sandberg@ARM.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
8669651SAndreas.Sandberg@ARM.com    print '       Installed version:', swig_version[2]
8679651SAndreas.Sandberg@ARM.com    Exit(1)
8689651SAndreas.Sandberg@ARM.com
86912563Sgabeblack@google.com# Check for known incompatibilities. The standard library shipped with
8709651SAndreas.Sandberg@ARM.com# gcc >= 4.9 does not play well with swig versions prior to 3.0
8719651SAndreas.Sandberg@ARM.comif main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
87210841Sandreas.sandberg@arm.com        compareVersions(swig_version[2], '3.0') < 0:
87312563Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + \
87412563Sgabeblack@google.com        'Warning: This combination of gcc and swig have' + \
87510841Sandreas.sandberg@arm.com        ' known incompatibilities.\n' + \
87610841Sandreas.sandberg@arm.com        '         If you encounter build problems, please update ' + \
87710841Sandreas.sandberg@arm.com        'swig to 3.0 or later.' + \
87810860Sandreas.sandberg@arm.com        termcap.Normal
87910841Sandreas.sandberg@arm.com
88010841Sandreas.sandberg@arm.com# Set up SWIG flags & scanner
88110841Sandreas.sandberg@arm.comswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
88210841Sandreas.sandberg@arm.commain.Append(SWIGFLAGS=swig_flags)
88310841Sandreas.sandberg@arm.com
88412563Sgabeblack@google.com# Check for 'timeout' from GNU coreutils. If present, regressions will
88510841Sandreas.sandberg@arm.com# be run with a time limit. We require version 8.13 since we rely on
88610841Sandreas.sandberg@arm.com# support for the '--foreground' option.
88710841Sandreas.sandberg@arm.comtimeout_lines = readCommand(['timeout', '--version'],
88810841Sandreas.sandberg@arm.com                            exception='').splitlines()
88910841Sandreas.sandberg@arm.com# Get the first line and tokenize it
8909651SAndreas.Sandberg@ARM.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
8919651SAndreas.Sandberg@ARM.commain['TIMEOUT'] =  timeout_version and \
8929986Sandreas@sandberg.pp.se    compareVersions(timeout_version[-1], '8.13') >= 0
8939986Sandreas@sandberg.pp.se
8949986Sandreas@sandberg.pp.se# filter out all existing swig scanners, they mess up the dependency
8959986Sandreas@sandberg.pp.se# stuff for some reason
8969986Sandreas@sandberg.pp.sescanners = []
8979986Sandreas@sandberg.pp.sefor scanner in main['SCANNERS']:
8985863Snate@binkert.org    skeys = scanner.skeys
8995863Snate@binkert.org    if skeys == '.i':
9005863Snate@binkert.org        continue
9015863Snate@binkert.org
9026121Snate@binkert.org    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
9031858SN/A        continue
9045863Snate@binkert.org
9055863Snate@binkert.org    scanners.append(scanner)
9065863Snate@binkert.org
9075863Snate@binkert.org# add the new swig scanner that we like better
9085863Snate@binkert.orgfrom SCons.Scanner import ClassicCPP as CPPScanner
9092139SN/Aswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
9104202Sbinkertn@umich.eduscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
91111308Santhony.gutierrez@amd.com
9124202Sbinkertn@umich.edu# replace the scanners list that has what we want
91311308Santhony.gutierrez@amd.commain['SCANNERS'] = scanners
9142139SN/A
9156994Snate@binkert.org# Add a custom Check function to test for structure members.
9166994Snate@binkert.orgdef CheckMember(context, include, decl, member, include_quotes="<>"):
9176994Snate@binkert.org    context.Message("Checking for member %s in %s..." %
9186994Snate@binkert.org                    (member, decl))
9196994Snate@binkert.org    text = """
9206994Snate@binkert.org#include %(header)s
9216994Snate@binkert.orgint main(){
9226994Snate@binkert.org  %(decl)s test;
92310319SAndreas.Sandberg@ARM.com  (void)test.%(member)s;
9246994Snate@binkert.org  return 0;
9256994Snate@binkert.org};
9266994Snate@binkert.org""" % { "header" : include_quotes[0] + include + include_quotes[1],
9276994Snate@binkert.org        "decl" : decl,
9286994Snate@binkert.org        "member" : member,
9296994Snate@binkert.org        }
9306994Snate@binkert.org
9316994Snate@binkert.org    ret = context.TryCompile(text, extension=".cc")
9326994Snate@binkert.org    context.Result(ret)
9336994Snate@binkert.org    return ret
9346994Snate@binkert.org
9352155SN/A# Platform-specific configuration.  Note again that we assume that all
9365863Snate@binkert.org# builds under a given build root run on the same host platform.
9371869SN/Aconf = Configure(main,
9381869SN/A                 conf_dir = joinpath(build_root, '.scons_config'),
9395863Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
9405863Snate@binkert.org                 custom_tests = {
9414202Sbinkertn@umich.edu        'CheckMember' : CheckMember,
9426108Snate@binkert.org        })
9436108Snate@binkert.org
9446108Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
9456108Snate@binkert.orgtry:
9469219Spower.jg@gmail.com    import platform
9479219Spower.jg@gmail.com    uname = platform.uname()
9489219Spower.jg@gmail.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
9499219Spower.jg@gmail.com        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
9509219Spower.jg@gmail.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
9519219Spower.jg@gmail.com            main.Append(CFLAGS=['-arch', 'x86_64'])
9529219Spower.jg@gmail.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
9539219Spower.jg@gmail.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
9544202Sbinkertn@umich.eduexcept:
9555863Snate@binkert.org    pass
95610135SCurtis.Dunham@arm.com
95712563Sgabeblack@google.com# Recent versions of scons substitute a "Null" object for Configure()
9585742Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
9598268Ssteve.reinhardt@amd.com# present.  Unfortuantely this Null object always returns false,
96012563Sgabeblack@google.com# breaking all our configuration checks.  We replace it with our own
9618268Ssteve.reinhardt@amd.com# more optimistic null object that returns True instead.
9625742Snate@binkert.orgif not conf:
9635341Sstever@gmail.com    def NullCheck(*args, **kwargs):
9648474Sgblack@eecs.umich.edu        return True
96512563Sgabeblack@google.com
9665342Sstever@gmail.com    class NullConf:
9674202Sbinkertn@umich.edu        def __init__(self, env):
9684202Sbinkertn@umich.edu            self.env = env
96911308Santhony.gutierrez@amd.com        def Finish(self):
9704202Sbinkertn@umich.edu            return self.env
9715863Snate@binkert.org        def __getattr__(self, mname):
9725863Snate@binkert.org            return NullCheck
97311308Santhony.gutierrez@amd.com
9746994Snate@binkert.org    conf = NullConf(main)
9756994Snate@binkert.org
97610319SAndreas.Sandberg@ARM.com# Cache build files in the supplied directory.
9775863Snate@binkert.orgif main['M5_BUILD_CACHE']:
9785863Snate@binkert.org    print 'Using build cache located at', main['M5_BUILD_CACHE']
9795863Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
9805863Snate@binkert.org
9815863Snate@binkert.orgif not GetOption('without_python'):
9825863Snate@binkert.org    # Find Python include and library directories for embedding the
9835863Snate@binkert.org    # interpreter. We rely on python-config to resolve the appropriate
9845863Snate@binkert.org    # includes and linker flags. ParseConfig does not seem to understand
9857840Snate@binkert.org    # the more exotic linker flags such as -Xlinker and -export-dynamic so
9865863Snate@binkert.org    # we add them explicitly below. If you want to link in an alternate
98712230Sgiacomo.travaglini@arm.com    # version of python, see above for instructions on how to invoke
98812230Sgiacomo.travaglini@arm.com    # scons with the appropriate PATH set.
98912230Sgiacomo.travaglini@arm.com    #
99012230Sgiacomo.travaglini@arm.com    # First we check if python2-config exists, else we use python-config
99112230Sgiacomo.travaglini@arm.com    python_config = readCommand(['which', 'python2-config'],
99212056Sgabeblack@google.com                                exception='').strip()
99312056Sgabeblack@google.com    if not os.path.exists(python_config):
99412056Sgabeblack@google.com        python_config = readCommand(['which', 'python-config'],
99511308Santhony.gutierrez@amd.com                                    exception='').strip()
9969219Spower.jg@gmail.com    py_includes = readCommand([python_config, '--includes'],
9979219Spower.jg@gmail.com                              exception='').split()
99811235Sandreas.sandberg@arm.com    # Strip the -I from the include folders before adding them to the
99911235Sandreas.sandberg@arm.com    # CPPPATH
10001869SN/A    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
10011858SN/A
10025863Snate@binkert.org    # Read the linker flags and split them into libraries and other link
100311308Santhony.gutierrez@amd.com    # flags. The libraries are added later through the call the CheckLib.
100412061Sjason@lowepower.com    py_ld_flags = readCommand([python_config, '--ldflags'],
100512920Sgabeblack@google.com        exception='').split()
100612920Sgabeblack@google.com    py_libs = []
10071858SN/A    for lib in py_ld_flags:
1008955SN/A         if not lib.startswith('-l'):
1009955SN/A             main.Append(LINKFLAGS=[lib])
10101869SN/A         else:
10111869SN/A             lib = lib[2:]
10121869SN/A             if lib not in py_libs:
10131869SN/A                 py_libs.append(lib)
10141869SN/A
10155863Snate@binkert.org    # verify that this stuff works
10165863Snate@binkert.org    if not conf.CheckHeader('Python.h', '<>'):
10175863Snate@binkert.org        print "Error: can't find Python.h header in", py_includes
10181869SN/A        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
10195863Snate@binkert.org        Exit(1)
10201869SN/A
102112563Sgabeblack@google.com    for lib in py_libs:
10221869SN/A        if not conf.CheckLib(lib):
10231869SN/A            print "Error: can't find library %s required by python" % lib
10241869SN/A            Exit(1)
10251869SN/A
10268483Sgblack@eecs.umich.edu# On Solaris you need to use libsocket for socket ops
10271869SN/Aif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10281869SN/A   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10291869SN/A       print "Can't find library with socket calls (e.g. accept())"
10301869SN/A       Exit(1)
10315863Snate@binkert.org
10325863Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
10331869SN/A# added to the LIBS environment variable.
10345863Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
10355863Snate@binkert.org    print 'Error: did not find needed zlib compression library '\
10363356Sbinkertn@umich.edu          'and/or zlib.h header file.'
10373356Sbinkertn@umich.edu    print '       Please install zlib and try again.'
10383356Sbinkertn@umich.edu    Exit(1)
10393356Sbinkertn@umich.edu
10403356Sbinkertn@umich.edu# If we have the protobuf compiler, also make sure we have the
10414781Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
10425863Snate@binkert.org# automatically added to the LIBS environment variable. After
10435863Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
10441869SN/A# got both protoc and libprotobuf available.
10451869SN/Amain['HAVE_PROTOBUF'] = main['PROTOC'] and \
10461869SN/A    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
10476121Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
10481869SN/A
104911982Sgabeblack@google.com# If we have the compiler but not the library, print another warning.
105011982Sgabeblack@google.comif main['PROTOC'] and not main['HAVE_PROTOBUF']:
105111982Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + \
105211982Sgabeblack@google.com        'Warning: did not find protocol buffer library and/or headers.\n' + \
105311982Sgabeblack@google.com    '       Please install libprotobuf-dev for tracing support.' + \
105411982Sgabeblack@google.com    termcap.Normal
105511982Sgabeblack@google.com
105611982Sgabeblack@google.com# Check for librt.
105711982Sgabeblack@google.comhave_posix_clock = \
105811982Sgabeblack@google.com    conf.CheckLibWithHeader(None, 'time.h', 'C',
105911982Sgabeblack@google.com                            'clock_nanosleep(0,0,NULL,NULL);') or \
106011982Sgabeblack@google.com    conf.CheckLibWithHeader('rt', 'time.h', 'C',
106111982Sgabeblack@google.com                            'clock_nanosleep(0,0,NULL,NULL);')
106211982Sgabeblack@google.com
106311982Sgabeblack@google.comhave_posix_timers = \
106411982Sgabeblack@google.com    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
106511982Sgabeblack@google.com                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
106611982Sgabeblack@google.com
106711982Sgabeblack@google.comif not GetOption('without_tcmalloc'):
106811982Sgabeblack@google.com    if conf.CheckLib('tcmalloc'):
106911982Sgabeblack@google.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
107011982Sgabeblack@google.com    elif conf.CheckLib('tcmalloc_minimal'):
107111982Sgabeblack@google.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
107211982Sgabeblack@google.com    else:
107311982Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + \
107411982Sgabeblack@google.com              "You can get a 12% performance improvement by "\
107511978Sgabeblack@google.com              "installing tcmalloc (libgoogle-perftools-dev package "\
107611978Sgabeblack@google.com              "on Ubuntu or RedHat)." + termcap.Normal
107712034Sgabeblack@google.com
107811978Sgabeblack@google.com
107911978Sgabeblack@google.com# Detect back trace implementations. The last implementation in the
108011978Sgabeblack@google.com# list will be used by default.
108112034Sgabeblack@google.combacktrace_impls = [ "none" ]
108211978Sgabeblack@google.com
108311978Sgabeblack@google.comif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
108410915Sandreas.sandberg@arm.com                           'backtrace_symbols_fd((void*)0, 0, 0);'):
108513577Sciro.santilli@arm.com    backtrace_impls.append("glibc")
108613577Sciro.santilli@arm.com
108713577Sciro.santilli@arm.comif backtrace_impls[-1] == "none":
108811986Sandreas.sandberg@arm.com    default_backtrace_impl = "none"
108911986Sandreas.sandberg@arm.com    print termcap.Yellow + termcap.Bold + \
10901869SN/A        "No suitable back trace implementation found." + \
10911869SN/A        termcap.Normal
109212015Sgabeblack@google.com
109312015Sgabeblack@google.comif not have_posix_clock:
109412015Sgabeblack@google.com    print "Can't find library for POSIX clocks."
109512015Sgabeblack@google.com
10963546Sgblack@eecs.umich.edu# Check for <fenv.h> (C99 FP environment control)
10973546Sgblack@eecs.umich.eduhave_fenv = conf.CheckHeader('fenv.h', '<>')
10983546Sgblack@eecs.umich.eduif not have_fenv:
109912015Sgabeblack@google.com    print "Warning: Header file <fenv.h> not found."
110012015Sgabeblack@google.com    print "         This host has no IEEE FP rounding mode control."
110112015Sgabeblack@google.com
110212015Sgabeblack@google.com# Check if we should enable KVM-based hardware virtualization. The API
110312015Sgabeblack@google.com# we rely on exists since version 2.6.36 of the kernel, but somehow
110412015Sgabeblack@google.com# the KVM_API_VERSION does not reflect the change. We test for one of
110512015Sgabeblack@google.com# the types as a fall back.
110612563Sgabeblack@google.comhave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
11073546Sgblack@eecs.umich.eduif not have_kvm:
110812015Sgabeblack@google.com    print "Info: Compatible header file <linux/kvm.h> not found, " \
110912015Sgabeblack@google.com        "disabling KVM support."
111010196SCurtis.Dunham@arm.com
111112015Sgabeblack@google.com# x86 needs support for xsave. We test for the structure here since we
111212015Sgabeblack@google.com# won't be able to run new tests by the time we know which ISA we're
111312015Sgabeblack@google.com# targeting.
111412015Sgabeblack@google.comhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
111512015Sgabeblack@google.com                                    '#include <linux/kvm.h>') != 0
111612015Sgabeblack@google.com
111712015Sgabeblack@google.com# Check if the requested target ISA is compatible with the host
111812015Sgabeblack@google.comdef is_isa_kvm_compatible(isa):
111912015Sgabeblack@google.com    try:
112012015Sgabeblack@google.com        import platform
112112015Sgabeblack@google.com        host_isa = platform.machine()
11223546Sgblack@eecs.umich.edu    except:
11233546Sgblack@eecs.umich.edu        print "Warning: Failed to determine host ISA."
11243546Sgblack@eecs.umich.edu        return False
1125955SN/A
1126955SN/A    if not have_posix_timers:
1127955SN/A        print "Warning: Can not enable KVM, host seems to lack support " \
1128955SN/A            "for POSIX timers"
11295863Snate@binkert.org        return False
113010135SCurtis.Dunham@arm.com
113112563Sgabeblack@google.com    if isa == "arm":
11325343Sstever@gmail.com        return host_isa in ( "armv7l", "aarch64" )
11335343Sstever@gmail.com    elif isa == "x86":
11346121Snate@binkert.org        if host_isa != "x86_64":
11355863Snate@binkert.org            return False
11364773Snate@binkert.org
11375863Snate@binkert.org        if not have_kvm_xsave:
11382632Sstever@eecs.umich.edu            print "KVM on x86 requires xsave support in kernel headers."
11395863Snate@binkert.org            return False
11402023SN/A
11415863Snate@binkert.org        return True
11425863Snate@binkert.org    else:
11435863Snate@binkert.org        return False
11445863Snate@binkert.org
11455863Snate@binkert.org
11465863Snate@binkert.org# Check if the exclude_host attribute is available. We want this to
11475863Snate@binkert.org# get accurate instruction counts in KVM.
11485863Snate@binkert.orgmain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
114910135SCurtis.Dunham@arm.com    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
115012563Sgabeblack@google.com
115112034Sgabeblack@google.com
115212034Sgabeblack@google.com######################################################################
115312034Sgabeblack@google.com#
11542632Sstever@eecs.umich.edu# Finish the configuration
11555863Snate@binkert.org#
11562023SN/Amain = conf.Finish()
11572632Sstever@eecs.umich.edu
11585863Snate@binkert.org######################################################################
11595342Sstever@gmail.com#
11605863Snate@binkert.org# Collect all non-global variables
11612632Sstever@eecs.umich.edu#
11625863Snate@binkert.org
11635863Snate@binkert.org# Define the universe of supported ISAs
11648267Ssteve.reinhardt@amd.comall_isa_list = [ ]
11658120Sgblack@eecs.umich.eduall_gpu_isa_list = [ ]
11668267Ssteve.reinhardt@amd.comExport('all_isa_list')
11678267Ssteve.reinhardt@amd.comExport('all_gpu_isa_list')
11688267Ssteve.reinhardt@amd.com
11698267Ssteve.reinhardt@amd.comclass CpuModel(object):
11708267Ssteve.reinhardt@amd.com    '''The CpuModel class encapsulates everything the ISA parser needs to
11718267Ssteve.reinhardt@amd.com    know about a particular CPU model.'''
11728267Ssteve.reinhardt@amd.com
11738267Ssteve.reinhardt@amd.com    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
11748267Ssteve.reinhardt@amd.com    dict = {}
11755863Snate@binkert.org
117612563Sgabeblack@google.com    # Constructor.  Automatically adds models to CpuModel.dict.
117712563Sgabeblack@google.com    def __init__(self, name, default=False):
11782632Sstever@eecs.umich.edu        self.name = name           # name of model
117912563Sgabeblack@google.com
118012563Sgabeblack@google.com        # This cpu is enabled by default
118112563Sgabeblack@google.com        self.default = default
11822632Sstever@eecs.umich.edu
11831888SN/A        # Add self to dict
11845863Snate@binkert.org        if name in CpuModel.dict:
11855863Snate@binkert.org            raise AttributeError, "CpuModel '%s' already registered" % name
11861858SN/A        CpuModel.dict[name] = self
11878120Sgblack@eecs.umich.edu
11888120Sgblack@eecs.umich.eduExport('CpuModel')
11897756SAli.Saidi@ARM.com
11902598SN/A# Sticky variables get saved in the variables file so they persist from
11915863Snate@binkert.org# one invocation to the next (unless overridden, in which case the new
11921858SN/A# value becomes sticky).
11931858SN/Asticky_vars = Variables(args=ARGUMENTS)
119412563Sgabeblack@google.comExport('sticky_vars')
119512563Sgabeblack@google.com
11961858SN/A# Sticky variables that should be exported
11971858SN/Aexport_vars = []
11981858SN/AExport('export_vars')
119912563Sgabeblack@google.com
120012563Sgabeblack@google.com# For Ruby
120112563Sgabeblack@google.comall_protocols = []
12021858SN/AExport('all_protocols')
120312230Sgiacomo.travaglini@arm.comprotocol_dirs = []
120412563Sgabeblack@google.comExport('protocol_dirs')
120512563Sgabeblack@google.comslicc_includes = []
120612230Sgiacomo.travaglini@arm.comExport('slicc_includes')
120712230Sgiacomo.travaglini@arm.com
120812230Sgiacomo.travaglini@arm.com# Walk the tree and execute all SConsopts scripts that wil add to the
120912230Sgiacomo.travaglini@arm.com# above variables
121012230Sgiacomo.travaglini@arm.comif GetOption('verbose'):
12111858SN/A    print "Reading SConsopts"
12121858SN/Afor bdir in [ base_dir ] + extras_dir_list:
12131858SN/A    if not isdir(bdir):
12149651SAndreas.Sandberg@ARM.com        print "Error: directory '%s' does not exist" % bdir
12159651SAndreas.Sandberg@ARM.com        Exit(1)
121612563Sgabeblack@google.com    for root, dirs, files in os.walk(bdir):
121712563Sgabeblack@google.com        if 'SConsopts' in files:
12189651SAndreas.Sandberg@ARM.com            if GetOption('verbose'):
12199651SAndreas.Sandberg@ARM.com                print "Reading", joinpath(root, 'SConsopts')
122012563Sgabeblack@google.com            SConscript(joinpath(root, 'SConsopts'))
122112563Sgabeblack@google.com
12229651SAndreas.Sandberg@ARM.comall_isa_list.sort()
12239651SAndreas.Sandberg@ARM.comall_gpu_isa_list.sort()
122412056Sgabeblack@google.com
122512056Sgabeblack@google.comsticky_vars.AddVariables(
122612563Sgabeblack@google.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
122712056Sgabeblack@google.com    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
122812056Sgabeblack@google.com    ListVariable('CPU_MODELS', 'CPU models',
122911798Santhony.gutierrez@amd.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
123011798Santhony.gutierrez@amd.com                 sorted(CpuModel.dict.keys())),
123111798Santhony.gutierrez@amd.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
12329986Sandreas@sandberg.pp.se                 False),
12339986Sandreas@sandberg.pp.se    BoolVariable('SS_COMPATIBLE_FP',
12349986Sandreas@sandberg.pp.se                 'Make floating-point results compatible with SimpleScalar',
123512563Sgabeblack@google.com                 False),
123612563Sgabeblack@google.com    BoolVariable('USE_SSE2',
123712563Sgabeblack@google.com                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
12389986Sandreas@sandberg.pp.se                 False),
12395863Snate@binkert.org    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
12405863Snate@binkert.org    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
12411869SN/A    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
12421965SN/A    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
12437739Sgblack@eecs.umich.edu    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
12441965SN/A    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
12452761Sstever@eecs.umich.edu                  all_protocols),
12465863Snate@binkert.org    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
12471869SN/A                 backtrace_impls[-1], backtrace_impls)
124810196SCurtis.Dunham@arm.com    )
12491869SN/A
12508120Sgblack@eecs.umich.edu# These variables get exported to #defines in config/*.hh (see src/SConscript).
12518120Sgblack@eecs.umich.eduexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
12528120Sgblack@eecs.umich.edu                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL',
12538120Sgblack@eecs.umich.edu                'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
12548120Sgblack@eecs.umich.edu
12558120Sgblack@eecs.umich.edu###################################################
12568120Sgblack@eecs.umich.edu#
12578120Sgblack@eecs.umich.edu# Define a SCons builder for configuration flag headers.
12588120Sgblack@eecs.umich.edu#
12598120Sgblack@eecs.umich.edu###################################################
12608120Sgblack@eecs.umich.edu
12618120Sgblack@eecs.umich.edu# This function generates a config header file that #defines the
1262# variable symbol to the current variable setting (0 or 1).  The source
1263# operands are the name of the variable and a Value node containing the
1264# value of the variable.
1265def build_config_file(target, source, env):
1266    (variable, value) = [s.get_contents() for s in source]
1267    f = file(str(target[0]), 'w')
1268    print >> f, '#define', variable, value
1269    f.close()
1270    return None
1271
1272# Combine the two functions into a scons Action object.
1273config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1274
1275# The emitter munges the source & target node lists to reflect what
1276# we're really doing.
1277def config_emitter(target, source, env):
1278    # extract variable name from Builder arg
1279    variable = str(target[0])
1280    # True target is config header file
1281    target = joinpath('config', variable.lower() + '.hh')
1282    val = env[variable]
1283    if isinstance(val, bool):
1284        # Force value to 0/1
1285        val = int(val)
1286    elif isinstance(val, str):
1287        val = '"' + val + '"'
1288
1289    # Sources are variable name & value (packaged in SCons Value nodes)
1290    return ([target], [Value(variable), Value(val)])
1291
1292config_builder = Builder(emitter = config_emitter, action = config_action)
1293
1294main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1295
1296# libelf build is shared across all configs in the build root.
1297main.SConscript('ext/libelf/SConscript',
1298                variant_dir = joinpath(build_root, 'libelf'))
1299
1300# iostream3 build is shared across all configs in the build root.
1301main.SConscript('ext/iostream3/SConscript',
1302                variant_dir = joinpath(build_root, 'iostream3'))
1303
1304# libfdt build is shared across all configs in the build root.
1305main.SConscript('ext/libfdt/SConscript',
1306                variant_dir = joinpath(build_root, 'libfdt'))
1307
1308# fputils build is shared across all configs in the build root.
1309main.SConscript('ext/fputils/SConscript',
1310                variant_dir = joinpath(build_root, 'fputils'))
1311
1312# DRAMSim2 build is shared across all configs in the build root.
1313main.SConscript('ext/dramsim2/SConscript',
1314                variant_dir = joinpath(build_root, 'dramsim2'))
1315
1316# DRAMPower build is shared across all configs in the build root.
1317main.SConscript('ext/drampower/SConscript',
1318                variant_dir = joinpath(build_root, 'drampower'))
1319
1320# nomali build is shared across all configs in the build root.
1321main.SConscript('ext/nomali/SConscript',
1322                variant_dir = joinpath(build_root, 'nomali'))
1323
1324###################################################
1325#
1326# This function is used to set up a directory with switching headers
1327#
1328###################################################
1329
1330main['ALL_ISA_LIST'] = all_isa_list
1331main['ALL_GPU_ISA_LIST'] = all_gpu_isa_list
1332all_isa_deps = {}
1333def make_switching_dir(dname, switch_headers, env):
1334    # Generate the header.  target[0] is the full path of the output
1335    # header to generate.  'source' is a dummy variable, since we get the
1336    # list of ISAs from env['ALL_ISA_LIST'].
1337    def gen_switch_hdr(target, source, env):
1338        fname = str(target[0])
1339        isa = env['TARGET_ISA'].lower()
1340        try:
1341            f = open(fname, 'w')
1342            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1343            f.close()
1344        except IOError:
1345            print "Failed to create %s" % fname
1346            raise
1347
1348    # Build SCons Action object. 'varlist' specifies env vars that this
1349    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1350    # should get re-executed.
1351    switch_hdr_action = MakeAction(gen_switch_hdr,
1352                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1353
1354    # Instantiate actions for each header
1355    for hdr in switch_headers:
1356        env.Command(hdr, [], switch_hdr_action)
1357
1358    isa_target = Dir('.').up().name.lower().replace('_', '-')
1359    env['PHONY_BASE'] = '#'+isa_target
1360    all_isa_deps[isa_target] = None
1361
1362Export('make_switching_dir')
1363
1364def make_gpu_switching_dir(dname, switch_headers, env):
1365    # Generate the header.  target[0] is the full path of the output
1366    # header to generate.  'source' is a dummy variable, since we get the
1367    # list of ISAs from env['ALL_ISA_LIST'].
1368    def gen_switch_hdr(target, source, env):
1369        fname = str(target[0])
1370
1371        isa = env['TARGET_GPU_ISA'].lower()
1372
1373        try:
1374            f = open(fname, 'w')
1375            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1376            f.close()
1377        except IOError:
1378            print "Failed to create %s" % fname
1379            raise
1380
1381    # Build SCons Action object. 'varlist' specifies env vars that this
1382    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1383    # should get re-executed.
1384    switch_hdr_action = MakeAction(gen_switch_hdr,
1385                          Transform("GENERATE"), varlist=['ALL_ISA_GPU_LIST'])
1386
1387    # Instantiate actions for each header
1388    for hdr in switch_headers:
1389        env.Command(hdr, [], switch_hdr_action)
1390
1391Export('make_gpu_switching_dir')
1392
1393# all-isas -> all-deps -> all-environs -> all_targets
1394main.Alias('#all-isas', [])
1395main.Alias('#all-deps', '#all-isas')
1396
1397# Dummy target to ensure all environments are created before telling
1398# SCons what to actually make (the command line arguments).  We attach
1399# them to the dependence graph after the environments are complete.
1400ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1401def environsComplete(target, source, env):
1402    for t in ORIG_BUILD_TARGETS:
1403        main.Depends('#all-targets', t)
1404
1405# Each build/* switching_dir attaches its *-environs target to #all-environs.
1406main.Append(BUILDERS = {'CompleteEnvirons' :
1407                        Builder(action=MakeAction(environsComplete, None))})
1408main.CompleteEnvirons('#all-environs', [])
1409
1410def doNothing(**ignored): pass
1411main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1412
1413# The final target to which all the original targets ultimately get attached.
1414main.Dummy('#all-targets', '#all-environs')
1415BUILD_TARGETS[:] = ['#all-targets']
1416
1417###################################################
1418#
1419# Define build environments for selected configurations.
1420#
1421###################################################
1422
1423for variant_path in variant_paths:
1424    if not GetOption('silent'):
1425        print "Building in", variant_path
1426
1427    # Make a copy of the build-root environment to use for this config.
1428    env = main.Clone()
1429    env['BUILDDIR'] = variant_path
1430
1431    # variant_dir is the tail component of build path, and is used to
1432    # determine the build parameters (e.g., 'ALPHA_SE')
1433    (build_root, variant_dir) = splitpath(variant_path)
1434
1435    # Set env variables according to the build directory config.
1436    sticky_vars.files = []
1437    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1438    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1439    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1440    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1441    if isfile(current_vars_file):
1442        sticky_vars.files.append(current_vars_file)
1443        if not GetOption('silent'):
1444            print "Using saved variables file %s" % current_vars_file
1445    else:
1446        # Build dir-specific variables file doesn't exist.
1447
1448        # Make sure the directory is there so we can create it later
1449        opt_dir = dirname(current_vars_file)
1450        if not isdir(opt_dir):
1451            mkdir(opt_dir)
1452
1453        # Get default build variables from source tree.  Variables are
1454        # normally determined by name of $VARIANT_DIR, but can be
1455        # overridden by '--default=' arg on command line.
1456        default = GetOption('default')
1457        opts_dir = joinpath(main.root.abspath, 'build_opts')
1458        if default:
1459            default_vars_files = [joinpath(build_root, 'variables', default),
1460                                  joinpath(opts_dir, default)]
1461        else:
1462            default_vars_files = [joinpath(opts_dir, variant_dir)]
1463        existing_files = filter(isfile, default_vars_files)
1464        if existing_files:
1465            default_vars_file = existing_files[0]
1466            sticky_vars.files.append(default_vars_file)
1467            print "Variables file %s not found,\n  using defaults in %s" \
1468                  % (current_vars_file, default_vars_file)
1469        else:
1470            print "Error: cannot find variables file %s or " \
1471                  "default file(s) %s" \
1472                  % (current_vars_file, ' or '.join(default_vars_files))
1473            Exit(1)
1474
1475    # Apply current variable settings to env
1476    sticky_vars.Update(env)
1477
1478    help_texts["local_vars"] += \
1479        "Build variables for %s:\n" % variant_dir \
1480                 + sticky_vars.GenerateHelpText(env)
1481
1482    # Process variable settings.
1483
1484    if not have_fenv and env['USE_FENV']:
1485        print "Warning: <fenv.h> not available; " \
1486              "forcing USE_FENV to False in", variant_dir + "."
1487        env['USE_FENV'] = False
1488
1489    if not env['USE_FENV']:
1490        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1491        print "         FP results may deviate slightly from other platforms."
1492
1493    if env['EFENCE']:
1494        env.Append(LIBS=['efence'])
1495
1496    if env['USE_KVM']:
1497        if not have_kvm:
1498            print "Warning: Can not enable KVM, host seems to lack KVM support"
1499            env['USE_KVM'] = False
1500        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1501            print "Info: KVM support disabled due to unsupported host and " \
1502                "target ISA combination"
1503            env['USE_KVM'] = False
1504
1505    if env['BUILD_GPU']:
1506        env.Append(CPPDEFINES=['BUILD_GPU'])
1507
1508    # Warn about missing optional functionality
1509    if env['USE_KVM']:
1510        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1511            print "Warning: perf_event headers lack support for the " \
1512                "exclude_host attribute. KVM instruction counts will " \
1513                "be inaccurate."
1514
1515    # Save sticky variable settings back to current variables file
1516    sticky_vars.Save(current_vars_file, env)
1517
1518    if env['USE_SSE2']:
1519        env.Append(CCFLAGS=['-msse2'])
1520
1521    # The src/SConscript file sets up the build rules in 'env' according
1522    # to the configured variables.  It returns a list of environments,
1523    # one for each variant build (debug, opt, etc.)
1524    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1525
1526def pairwise(iterable):
1527    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1528    a, b = itertools.tee(iterable)
1529    b.next()
1530    return itertools.izip(a, b)
1531
1532# Create false dependencies so SCons will parse ISAs, establish
1533# dependencies, and setup the build Environments serially. Either
1534# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1535# greater than 1. It appears to be standard race condition stuff; it
1536# doesn't always fail, but usually, and the behaviors are different.
1537# Every time I tried to remove this, builds would fail in some
1538# creative new way. So, don't do that. You'll want to, though, because
1539# tests/SConscript takes a long time to make its Environments.
1540for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1541    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1542    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1543
1544# base help text
1545Help('''
1546Usage: scons [scons options] [build variables] [target(s)]
1547
1548Extra scons options:
1549%(options)s
1550
1551Global build variables:
1552%(global_vars)s
1553
1554%(local_vars)s
1555''' % help_texts)
1556