SConstruct revision 10860
1955SN/A# -*- mode:python -*-
2955SN/A
312230Sgiacomo.travaglini@arm.com# Copyright (c) 2013, 2015 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)
10013758Sgabeblack@google.comexcept SystemExit, e:
1015273Sstever@gmail.com    print """
1026654Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
1035396Ssaidi@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
1118120Sgblack@eecs.umich.edu# Global Python includes
1128879Ssteve.reinhardt@amd.comimport itertools
1138879Ssteve.reinhardt@amd.comimport os
1148879Ssteve.reinhardt@amd.comimport re
1158879Ssteve.reinhardt@amd.comimport subprocess
1168879Ssteve.reinhardt@amd.comimport sys
1178879Ssteve.reinhardt@amd.com
1188879Ssteve.reinhardt@amd.comfrom os import mkdir, environ
1198879Ssteve.reinhardt@amd.comfrom os.path import abspath, basename, dirname, expanduser, normpath
1208879Ssteve.reinhardt@amd.comfrom os.path import exists,  isdir, isfile
1218879Ssteve.reinhardt@amd.comfrom os.path import join as joinpath, split as splitpath
1228879Ssteve.reinhardt@amd.com
1238879Ssteve.reinhardt@amd.com# SCons includes
1248879Ssteve.reinhardt@amd.comimport SCons
1258120Sgblack@eecs.umich.eduimport SCons.Node
1268120Sgblack@eecs.umich.edu
1278120Sgblack@eecs.umich.eduextra_python_paths = [
1288120Sgblack@eecs.umich.edu    Dir('src/python').srcnode().abspath, # gem5 includes
1298120Sgblack@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1308120Sgblack@eecs.umich.edu    ]
1318120Sgblack@eecs.umich.edu
1328120Sgblack@eecs.umich.edusys.path[1:1] = extra_python_paths
1338120Sgblack@eecs.umich.edu
1348120Sgblack@eecs.umich.edufrom m5.util import compareVersions, readCommand
1358120Sgblack@eecs.umich.edufrom m5.util.terminal import get_termcap
1368120Sgblack@eecs.umich.edu
1378120Sgblack@eecs.umich.eduhelp_texts = {
1388120Sgblack@eecs.umich.edu    "options" : "",
1398879Ssteve.reinhardt@amd.com    "global_vars" : "",
1408879Ssteve.reinhardt@amd.com    "local_vars" : ""
1418879Ssteve.reinhardt@amd.com}
1428879Ssteve.reinhardt@amd.com
14310458Sandreas.hansson@arm.comExport("help_texts")
14410458Sandreas.hansson@arm.com
14510458Sandreas.hansson@arm.com
1468879Ssteve.reinhardt@amd.com# There's a bug in scons in that (1) by default, the help texts from
1478879Ssteve.reinhardt@amd.com# AddOption() are supposed to be displayed when you type 'scons -h'
1488879Ssteve.reinhardt@amd.com# and (2) you can override the help displayed by 'scons -h' using the
1498879Ssteve.reinhardt@amd.com# Help() function, but these two features are incompatible: once
15013421Sciro.santilli@arm.com# you've overridden the help text using Help(), there's no way to get
15113421Sciro.santilli@arm.com# at the help texts from AddOptions.  See:
1529227Sandreas.hansson@arm.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1539227Sandreas.hansson@arm.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
15412063Sgabeblack@google.com# This hack lets us extract the help text from AddOptions and
15512063Sgabeblack@google.com# re-inject it via Help().  Ideally someday this bug will be fixed and
15612063Sgabeblack@google.com# we can just use AddOption directly.
1578879Ssteve.reinhardt@amd.comdef AddLocalOption(*args, **kwargs):
1588879Ssteve.reinhardt@amd.com    col_width = 30
1598879Ssteve.reinhardt@amd.com
1608879Ssteve.reinhardt@amd.com    help = "  " + ", ".join(args)
16110453SAndrew.Bardsley@arm.com    if "help" in kwargs:
16210453SAndrew.Bardsley@arm.com        length = len(help)
16310453SAndrew.Bardsley@arm.com        if length >= col_width:
16410456SCurtis.Dunham@arm.com            help += "\n" + " " * col_width
16510456SCurtis.Dunham@arm.com        else:
16610456SCurtis.Dunham@arm.com            help += " " * (col_width - length)
16710457Sandreas.hansson@arm.com        help += kwargs["help"]
16810457Sandreas.hansson@arm.com    help_texts["options"] += help + "\n"
16911342Sandreas.hansson@arm.com
17011342Sandreas.hansson@arm.com    AddOption(*args, **kwargs)
1718120Sgblack@eecs.umich.edu
17212063Sgabeblack@google.comAddLocalOption('--colors', dest='use_colors', action='store_true',
17312563Sgabeblack@google.com               help="Add color to abbreviated scons output")
17412063Sgabeblack@google.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
17512063Sgabeblack@google.com               help="Don't add color to abbreviated scons output")
1765871Snate@binkert.orgAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1775871Snate@binkert.org               action='store_true',
1786121Snate@binkert.org               help="Build with support for C++-based configuration")
1795871Snate@binkert.orgAddLocalOption('--default', dest='default', type='string', action='store',
1805871Snate@binkert.org               help='Override which build_opts file to use for defaults')
1819926Sstan.czerniawski@arm.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
18212243Sgabeblack@google.com               help='Disable style checking hooks')
1831533SN/AAddLocalOption('--no-lto', dest='no_lto', action='store_true',
18412246Sgabeblack@google.com               help='Disable Link-Time Optimization for fast')
18512246Sgabeblack@google.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
18612246Sgabeblack@google.com               help='Update test reference outputs')
18712246Sgabeblack@google.comAddLocalOption('--verbose', dest='verbose', action='store_true',
1889239Sandreas.hansson@arm.com               help='Print full tool command lines')
1899239Sandreas.hansson@arm.comAddLocalOption('--without-python', dest='without_python',
1909239Sandreas.hansson@arm.com               action='store_true',
1919239Sandreas.hansson@arm.com               help='Build without Python configuration support')
19212563Sgabeblack@google.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1939239Sandreas.hansson@arm.com               action='store_true',
1949239Sandreas.hansson@arm.com               help='Disable linking against tcmalloc')
195955SN/AAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
196955SN/A               help='Build with Undefined Behavior Sanitizer if available')
1972632Sstever@eecs.umich.edu
1982632Sstever@eecs.umich.edutermcap = get_termcap(GetOption('use_colors'))
199955SN/A
200955SN/A########################################################################
201955SN/A#
202955SN/A# Set up the main build environment.
2038878Ssteve.reinhardt@amd.com#
204955SN/A########################################################################
2052632Sstever@eecs.umich.edu
2062632Sstever@eecs.umich.edu# export TERM so that clang reports errors in color
2072632Sstever@eecs.umich.eduuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2082632Sstever@eecs.umich.edu                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2092632Sstever@eecs.umich.edu                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
2102632Sstever@eecs.umich.edu
2112632Sstever@eecs.umich.eduuse_prefixes = [
2128268Ssteve.reinhardt@amd.com    "M5",           # M5 configuration (e.g., path to kernels)
2138268Ssteve.reinhardt@amd.com    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
2148268Ssteve.reinhardt@amd.com    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2158268Ssteve.reinhardt@amd.com    "CCC_",         # clang static analyzer configuration
2168268Ssteve.reinhardt@amd.com    ]
2178268Ssteve.reinhardt@amd.com
2188268Ssteve.reinhardt@amd.comuse_env = {}
21913715Sandreas.sandberg@arm.comfor key,val in sorted(os.environ.iteritems()):
22013715Sandreas.sandberg@arm.com    if key in use_vars or \
22113715Sandreas.sandberg@arm.com            any([key.startswith(prefix) for prefix in use_prefixes]):
22213715Sandreas.sandberg@arm.com        use_env[key] = val
22313715Sandreas.sandberg@arm.com
22413715Sandreas.sandberg@arm.com# Tell scons to avoid implicit command dependencies to avoid issues
22513715Sandreas.sandberg@arm.com# with the param wrappes being compiled twice (see
22613715Sandreas.sandberg@arm.com# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
22713715Sandreas.sandberg@arm.commain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
22813715Sandreas.sandberg@arm.commain.Decider('MD5-timestamp')
22913715Sandreas.sandberg@arm.commain.root = Dir(".")         # The current directory (where this file lives).
23013715Sandreas.sandberg@arm.commain.srcdir = Dir("src")     # The source directory
23113715Sandreas.sandberg@arm.com
2322632Sstever@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
2332632Sstever@eecs.umich.edu
2342632Sstever@eecs.umich.edu# Check that we have a C/C++ compiler
2352632Sstever@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2368268Ssteve.reinhardt@amd.com    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2372632Sstever@eecs.umich.edu    Exit(1)
2388268Ssteve.reinhardt@amd.com
2398268Ssteve.reinhardt@amd.com# Check that swig is present
2408268Ssteve.reinhardt@amd.comif not 'SWIG' in main_dict_keys:
2418268Ssteve.reinhardt@amd.com    print "swig is not installed (package swig on Ubuntu and RedHat)"
2423718Sstever@eecs.umich.edu    Exit(1)
2432634Sstever@eecs.umich.edu
2442634Sstever@eecs.umich.edu# add useful python code PYTHONPATH so it can be used by subprocesses
2455863Snate@binkert.org# as well
2462638Sstever@eecs.umich.edumain.AppendENVPath('PYTHONPATH', extra_python_paths)
2478268Ssteve.reinhardt@amd.com
2482632Sstever@eecs.umich.edu########################################################################
2492632Sstever@eecs.umich.edu#
2502632Sstever@eecs.umich.edu# Mercurial Stuff.
2512632Sstever@eecs.umich.edu#
25212563Sgabeblack@google.com# If the gem5 directory is a mercurial repository, we should do some
2531858SN/A# extra things.
2543716Sstever@eecs.umich.edu#
2552638Sstever@eecs.umich.edu########################################################################
2562638Sstever@eecs.umich.edu
2572638Sstever@eecs.umich.eduhgdir = main.root.Dir(".hg")
2582638Sstever@eecs.umich.edu
25912563Sgabeblack@google.commercurial_style_message = """
26012563Sgabeblack@google.comYou're missing the gem5 style hook, which automatically checks your code
2612638Sstever@eecs.umich.eduagainst the gem5 style rules on hg commit and qrefresh commands.  This
2625863Snate@binkert.orgscript will now install the hook in your .hg/hgrc file.
2635863Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
2645863Snate@binkert.org
265955SN/Amercurial_style_hook = """
2665341Sstever@gmail.com# The following lines were automatically added by gem5/SConstruct
2675341Sstever@gmail.com# to provide the gem5 style-checking hooks
2685863Snate@binkert.org[extensions]
2697756SAli.Saidi@ARM.comstyle = %s/util/style.py
2705341Sstever@gmail.com
2716121Snate@binkert.org[hooks]
2724494Ssaidi@eecs.umich.edupretxncommit.style = python:style.check_style
2736121Snate@binkert.orgpre-qrefresh.style = python:style.check_style
2741105SN/A# End of SConstruct additions
2752667Sstever@eecs.umich.edu
2762667Sstever@eecs.umich.edu""" % (main.root.abspath)
2772667Sstever@eecs.umich.edu
2782667Sstever@eecs.umich.edumercurial_lib_not_found = """
2796121Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2802667Sstever@eecs.umich.eduyou are a gem5 developer, please fix this and run the style
2815341Sstever@gmail.comhook. It is important.
2825863Snate@binkert.org"""
2835341Sstever@gmail.com
2845341Sstever@gmail.com# Check for style hook and prompt for installation if it's not there.
2855341Sstever@gmail.com# Skip this if --ignore-style was specified, there's no .hg dir to
2868120Sgblack@eecs.umich.edu# install a hook in, or there's no interactive terminal to prompt.
2875341Sstever@gmail.comif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2888120Sgblack@eecs.umich.edu    style_hook = True
2895341Sstever@gmail.com    try:
2908120Sgblack@eecs.umich.edu        from mercurial import ui
2916121Snate@binkert.org        ui = ui.ui()
2926121Snate@binkert.org        ui.readconfig(hgdir.File('hgrc').abspath)
29313715Sandreas.sandberg@arm.com        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
29413715Sandreas.sandberg@arm.com                     ui.config('hooks', 'pre-qrefresh.style', None)
2959396Sandreas.hansson@arm.com    except ImportError:
2965397Ssaidi@eecs.umich.edu        print mercurial_lib_not_found
2975397Ssaidi@eecs.umich.edu
2987727SAli.Saidi@ARM.com    if not style_hook:
2998268Ssteve.reinhardt@amd.com        print mercurial_style_message,
3006168Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
3015341Sstever@gmail.com        try:
3028120Sgblack@eecs.umich.edu            raw_input()
3038120Sgblack@eecs.umich.edu        except:
3048120Sgblack@eecs.umich.edu            print "Input exception, exiting scons.\n"
3056814Sgblack@eecs.umich.edu            sys.exit(1)
3065863Snate@binkert.org        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3078120Sgblack@eecs.umich.edu        print "Adding style hook to", hgrc_path, "\n"
3085341Sstever@gmail.com        try:
3095863Snate@binkert.org            hgrc = open(hgrc_path, 'a')
3108268Ssteve.reinhardt@amd.com            hgrc.write(mercurial_style_hook)
3116121Snate@binkert.org            hgrc.close()
3126121Snate@binkert.org        except:
3138268Ssteve.reinhardt@amd.com            print "Error updating", hgrc_path
3145742Snate@binkert.org            sys.exit(1)
3155742Snate@binkert.org
3165341Sstever@gmail.com
3175742Snate@binkert.org###################################################
3185742Snate@binkert.org#
3195341Sstever@gmail.com# Figure out which configurations to set up based on the path(s) of
3206017Snate@binkert.org# the target(s).
3216121Snate@binkert.org#
3226017Snate@binkert.org###################################################
32312158Sandreas.sandberg@arm.com
32412158Sandreas.sandberg@arm.com# Find default configuration & binary.
32512158Sandreas.sandberg@arm.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3268120Sgblack@eecs.umich.edu
3277756SAli.Saidi@ARM.com# helper function: find last occurrence of element in list
3287756SAli.Saidi@ARM.comdef rfind(l, elt, offs = -1):
3297756SAli.Saidi@ARM.com    for i in range(len(l)+offs, 0, -1):
3307756SAli.Saidi@ARM.com        if l[i] == elt:
3317816Ssteve.reinhardt@amd.com            return i
3327816Ssteve.reinhardt@amd.com    raise ValueError, "element not found"
3337816Ssteve.reinhardt@amd.com
3347816Ssteve.reinhardt@amd.com# Take a list of paths (or SCons Nodes) and return a list with all
3357816Ssteve.reinhardt@amd.com# paths made absolute and ~-expanded.  Paths will be interpreted
33611979Sgabeblack@google.com# relative to the launch directory unless a different root is provided
3377816Ssteve.reinhardt@amd.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3387816Ssteve.reinhardt@amd.com    return [abspath(joinpath(root, expanduser(str(p))))
3397816Ssteve.reinhardt@amd.com            for p in path_list]
3407816Ssteve.reinhardt@amd.com
3417756SAli.Saidi@ARM.com# Each target must have 'build' in the interior of the path; the
3427756SAli.Saidi@ARM.com# directory below this will determine the build parameters.  For
3439227Sandreas.hansson@arm.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3449227Sandreas.hansson@arm.com# recognize that ALPHA_SE specifies the configuration because it
3459227Sandreas.hansson@arm.com# follow 'build' in the build path.
3469227Sandreas.hansson@arm.com
3479590Sandreas@sandberg.pp.se# The funky assignment to "[:]" is needed to replace the list contents
3489590Sandreas@sandberg.pp.se# in place rather than reassign the symbol to a new list, which
3499590Sandreas@sandberg.pp.se# doesn't work (obviously!).
3509590Sandreas@sandberg.pp.seBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3519590Sandreas@sandberg.pp.se
3529590Sandreas@sandberg.pp.se# Generate a list of the unique build roots and configs that the
3536654Snate@binkert.org# collected targets reference.
3546654Snate@binkert.orgvariant_paths = []
3555871Snate@binkert.orgbuild_root = None
3566121Snate@binkert.orgfor t in BUILD_TARGETS:
3578946Sandreas.hansson@arm.com    path_dirs = t.split('/')
3589419Sandreas.hansson@arm.com    try:
35912563Sgabeblack@google.com        build_top = rfind(path_dirs, 'build', -2)
3603918Ssaidi@eecs.umich.edu    except:
3613918Ssaidi@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
3621858SN/A        Exit(1)
3639556Sandreas.hansson@arm.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3649556Sandreas.hansson@arm.com    if not build_root:
3659556Sandreas.hansson@arm.com        build_root = this_build_root
3669556Sandreas.hansson@arm.com    else:
36711294Sandreas.hansson@arm.com        if this_build_root != build_root:
36811294Sandreas.hansson@arm.com            print "Error: build targets not under same build root\n"\
36911294Sandreas.hansson@arm.com                  "  %s\n  %s" % (build_root, this_build_root)
37011294Sandreas.hansson@arm.com            Exit(1)
37110878Sandreas.hansson@arm.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
37210878Sandreas.hansson@arm.com    if variant_path not in variant_paths:
37311811Sbaz21@cam.ac.uk        variant_paths.append(variant_path)
37411811Sbaz21@cam.ac.uk
37511811Sbaz21@cam.ac.uk# Make sure build_root exists (might not if this is the first build there)
37611982Sgabeblack@google.comif not isdir(build_root):
37711982Sgabeblack@google.com    mkdir(build_root)
37811982Sgabeblack@google.commain['BUILDROOT'] = build_root
37913421Sciro.santilli@arm.com
38013421Sciro.santilli@arm.comExport('main')
38111982Sgabeblack@google.com
38211992Sgabeblack@google.commain.SConsignFile(joinpath(build_root, "sconsign"))
38311982Sgabeblack@google.com
38411982Sgabeblack@google.com# Default duplicate option is to use hard links, but this messes up
38512305Sgabeblack@google.com# when you use emacs to edit a file in the target dir, as emacs moves
38612305Sgabeblack@google.com# file to file~ then copies to file, breaking the link.  Symbolic
38712305Sgabeblack@google.com# (soft) links work better.
38812305Sgabeblack@google.commain.SetOption('duplicate', 'soft-copy')
38912305Sgabeblack@google.com
39012305Sgabeblack@google.com#
39112305Sgabeblack@google.com# Set up global sticky variables... these are common to an entire build
3929556Sandreas.hansson@arm.com# tree (not specific to a particular build like ALPHA_SE)
39312563Sgabeblack@google.com#
39412563Sgabeblack@google.com
39512563Sgabeblack@google.comglobal_vars_file = joinpath(build_root, 'variables.global')
39612563Sgabeblack@google.com
3979556Sandreas.hansson@arm.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
39812563Sgabeblack@google.com
39912563Sgabeblack@google.comglobal_vars.AddVariables(
4009556Sandreas.hansson@arm.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
40112563Sgabeblack@google.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
40212563Sgabeblack@google.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
40312563Sgabeblack@google.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
40412563Sgabeblack@google.com    ('BATCH', 'Use batch pool for build and tests', False),
40512563Sgabeblack@google.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
40612563Sgabeblack@google.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
40712563Sgabeblack@google.com    ('EXTRAS', 'Add extra directories to the compilation', '')
40812563Sgabeblack@google.com    )
4099556Sandreas.hansson@arm.com
4109556Sandreas.hansson@arm.com# Update main environment with values from ARGUMENTS & global_vars_file
4116121Snate@binkert.orgglobal_vars.Update(main)
41211500Sandreas.hansson@arm.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
41310238Sandreas.hansson@arm.com
41410878Sandreas.hansson@arm.com# Save sticky variable settings back to current variables file
4159420Sandreas.hansson@arm.comglobal_vars.Save(global_vars_file, main)
41611500Sandreas.hansson@arm.com
41712563Sgabeblack@google.com# Parse EXTRAS variable to build list of all directories where we're
41812563Sgabeblack@google.com# look for sources etc.  This list is exported as extras_dir_list.
4199420Sandreas.hansson@arm.combase_dir = main.srcdir.abspath
4209420Sandreas.hansson@arm.comif main['EXTRAS']:
4219420Sandreas.hansson@arm.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
4229420Sandreas.hansson@arm.comelse:
42312063Sgabeblack@google.com    extras_dir_list = []
42412063Sgabeblack@google.com
42512063Sgabeblack@google.comExport('base_dir')
42612063Sgabeblack@google.comExport('extras_dir_list')
42712063Sgabeblack@google.com
42812063Sgabeblack@google.com# the ext directory should be on the #includes path
42912063Sgabeblack@google.commain.Append(CPPPATH=[Dir('ext')])
43012063Sgabeblack@google.com
43112063Sgabeblack@google.comdef strip_build_path(path, env):
43212063Sgabeblack@google.com    path = str(path)
43312063Sgabeblack@google.com    variant_base = env['BUILDROOT'] + os.path.sep
43412063Sgabeblack@google.com    if path.startswith(variant_base):
43512063Sgabeblack@google.com        path = path[len(variant_base):]
43612063Sgabeblack@google.com    elif path.startswith('build/'):
43712063Sgabeblack@google.com        path = path[6:]
43812063Sgabeblack@google.com    return path
43912063Sgabeblack@google.com
44012063Sgabeblack@google.com# Generate a string of the form:
44112063Sgabeblack@google.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
44212063Sgabeblack@google.com# to print while building.
44312063Sgabeblack@google.comclass Transform(object):
44412063Sgabeblack@google.com    # all specific color settings should be here and nowhere else
44510457Sandreas.hansson@arm.com    tool_color = termcap.Normal
44610457Sandreas.hansson@arm.com    pfx_color = termcap.Yellow
44710457Sandreas.hansson@arm.com    srcs_color = termcap.Yellow + termcap.Bold
44810457Sandreas.hansson@arm.com    arrow_color = termcap.Blue + termcap.Bold
44910457Sandreas.hansson@arm.com    tgts_color = termcap.Yellow + termcap.Bold
45012563Sgabeblack@google.com
45112563Sgabeblack@google.com    def __init__(self, tool, max_sources=99):
45212563Sgabeblack@google.com        self.format = self.tool_color + (" [%8s] " % tool) \
45310457Sandreas.hansson@arm.com                      + self.pfx_color + "%s" \
45412063Sgabeblack@google.com                      + self.srcs_color + "%s" \
45512063Sgabeblack@google.com                      + self.arrow_color + " -> " \
45612063Sgabeblack@google.com                      + self.tgts_color + "%s" \
45712563Sgabeblack@google.com                      + termcap.Normal
45812563Sgabeblack@google.com        self.max_sources = max_sources
45912563Sgabeblack@google.com
46012563Sgabeblack@google.com    def __call__(self, target, source, env, for_signature=None):
46112563Sgabeblack@google.com        # truncate source list according to max_sources param
46212563Sgabeblack@google.com        source = source[0:self.max_sources]
46312063Sgabeblack@google.com        def strip(f):
46412063Sgabeblack@google.com            return strip_build_path(str(f), env)
46510238Sandreas.hansson@arm.com        if len(source) > 0:
46610238Sandreas.hansson@arm.com            srcs = map(strip, source)
46710238Sandreas.hansson@arm.com        else:
46812063Sgabeblack@google.com            srcs = ['']
46910238Sandreas.hansson@arm.com        tgts = map(strip, target)
47010238Sandreas.hansson@arm.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
47110416Sandreas.hansson@arm.com        # operation that has nothing to do with paths.
47210238Sandreas.hansson@arm.com        com_pfx = os.path.commonprefix(srcs + tgts)
4739227Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
47410238Sandreas.hansson@arm.com        if com_pfx:
47510416Sandreas.hansson@arm.com            # do some cleanup and sanity checking on common prefix
47610416Sandreas.hansson@arm.com            if com_pfx[-1] == ".":
4779227Sandreas.hansson@arm.com                # prefix matches all but file extension: ok
4789590Sandreas@sandberg.pp.se                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4799590Sandreas@sandberg.pp.se                com_pfx = com_pfx[0:-1]
4809590Sandreas@sandberg.pp.se            elif com_pfx[-1] == "/":
48112304Sgabeblack@google.com                # common prefix is directory path: OK
48212304Sgabeblack@google.com                pass
48312304Sgabeblack@google.com            else:
48412688Sgiacomo.travaglini@arm.com                src0_len = len(srcs[0])
48512688Sgiacomo.travaglini@arm.com                tgt0_len = len(tgts[0])
48612688Sgiacomo.travaglini@arm.com                if src0_len == com_pfx_len:
48713020Sshunhsingou@google.com                    # source is a substring of target, OK
48812304Sgabeblack@google.com                    pass
48912688Sgiacomo.travaglini@arm.com                elif tgt0_len == com_pfx_len:
49012688Sgiacomo.travaglini@arm.com                    # target is a substring of source, need to back up to
49113020Sshunhsingou@google.com                    # avoid empty string on RHS of arrow
49212304Sgabeblack@google.com                    sep_idx = com_pfx.rfind(".")
49312304Sgabeblack@google.com                    if sep_idx != -1:
49412304Sgabeblack@google.com                        com_pfx = com_pfx[0:sep_idx]
49512304Sgabeblack@google.com                    else:
49612688Sgiacomo.travaglini@arm.com                        com_pfx = ''
49712688Sgiacomo.travaglini@arm.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
49812688Sgiacomo.travaglini@arm.com                    # still splitting at file extension: ok
49912304Sgabeblack@google.com                    pass
5008737Skoansin.tan@gmail.com                else:
50110878Sandreas.hansson@arm.com                    # probably a fluke; ignore it
50211500Sandreas.hansson@arm.com                    com_pfx = ''
5039420Sandreas.hansson@arm.com        # recalculate length in case com_pfx was modified
5048737Skoansin.tan@gmail.com        com_pfx_len = len(com_pfx)
50510106SMitch.Hayenga@arm.com        def fmt(files):
5068737Skoansin.tan@gmail.com            f = map(lambda s: s[com_pfx_len:], files)
5078737Skoansin.tan@gmail.com            return ', '.join(f)
50810878Sandreas.hansson@arm.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
50912563Sgabeblack@google.com
51012563Sgabeblack@google.comExport('Transform')
5118737Skoansin.tan@gmail.com
5128737Skoansin.tan@gmail.com# enable the regression script to use the termcap
51312563Sgabeblack@google.commain['TERMCAP'] = termcap
5148737Skoansin.tan@gmail.com
5158737Skoansin.tan@gmail.comif GetOption('verbose'):
51611294Sandreas.hansson@arm.com    def MakeAction(action, string, *args, **kwargs):
5179556Sandreas.hansson@arm.com        return Action(action, *args, **kwargs)
5189556Sandreas.hansson@arm.comelse:
5199556Sandreas.hansson@arm.com    MakeAction = Action
52011294Sandreas.hansson@arm.com    main['CCCOMSTR']        = Transform("CC")
52110278SAndreas.Sandberg@ARM.com    main['CXXCOMSTR']       = Transform("CXX")
52210278SAndreas.Sandberg@ARM.com    main['ASCOMSTR']        = Transform("AS")
52310278SAndreas.Sandberg@ARM.com    main['SWIGCOMSTR']      = Transform("SWIG")
52410278SAndreas.Sandberg@ARM.com    main['ARCOMSTR']        = Transform("AR", 0)
52510278SAndreas.Sandberg@ARM.com    main['LINKCOMSTR']      = Transform("LINK", 0)
52610278SAndreas.Sandberg@ARM.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5279556Sandreas.hansson@arm.com    main['M4COMSTR']        = Transform("M4")
5289590Sandreas@sandberg.pp.se    main['SHCCCOMSTR']      = Transform("SHCC")
5299590Sandreas@sandberg.pp.se    main['SHCXXCOMSTR']     = Transform("SHCXX")
5309420Sandreas.hansson@arm.comExport('MakeAction')
5319846Sandreas.hansson@arm.com
5329846Sandreas.hansson@arm.com# Initialize the Link-Time Optimization (LTO) flags
5339846Sandreas.hansson@arm.commain['LTO_CCFLAGS'] = []
5349846Sandreas.hansson@arm.commain['LTO_LDFLAGS'] = []
5358946Sandreas.hansson@arm.com
53611811Sbaz21@cam.ac.uk# According to the readme, tcmalloc works best if the compiler doesn't
53711811Sbaz21@cam.ac.uk# assume that we're using the builtin malloc and friends. These flags
53811811Sbaz21@cam.ac.uk# are compiler-specific, so we need to set them after we detect which
53911811Sbaz21@cam.ac.uk# compiler we're using.
54012304Sgabeblack@google.commain['TCMALLOC_CCFLAGS'] = []
54112304Sgabeblack@google.com
54212304Sgabeblack@google.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
54312304Sgabeblack@google.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
54413020Sshunhsingou@google.com
54513020Sshunhsingou@google.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
54612304Sgabeblack@google.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
54712304Sgabeblack@google.comif main['GCC'] + main['CLANG'] > 1:
54813020Sshunhsingou@google.com    print 'Error: How can we have two at the same time?'
54913020Sshunhsingou@google.com    Exit(1)
55012304Sgabeblack@google.com
55112304Sgabeblack@google.com# Set up default C++ compiler flags
55213020Sshunhsingou@google.comif main['GCC'] or main['CLANG']:
55313020Sshunhsingou@google.com    # As gcc and clang share many flags, do the common parts here
55412304Sgabeblack@google.com    main.Append(CCFLAGS=['-pipe'])
55512304Sgabeblack@google.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5563918Ssaidi@eecs.umich.edu    # Enable -Wall and then disable the few warnings that we
55712563Sgabeblack@google.com    # consistently violate
55812563Sgabeblack@google.com    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
55912563Sgabeblack@google.com    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
56012563Sgabeblack@google.com    # actually use that name, so we stick with c++0x
5619068SAli.Saidi@ARM.com    main.Append(CXXFLAGS=['-std=c++0x'])
56212563Sgabeblack@google.com    # Add selected sanity checks from -Wextra
56312563Sgabeblack@google.com    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5649068SAli.Saidi@ARM.com                          '-Woverloaded-virtual'])
56512563Sgabeblack@google.comelse:
56612563Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
56712563Sgabeblack@google.com    print "Don't know what compiler options to use for your compiler."
56812563Sgabeblack@google.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
56912563Sgabeblack@google.com    print termcap.Yellow + '       version:' + termcap.Normal,
57012563Sgabeblack@google.com    if not CXX_version:
57112563Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
57212563Sgabeblack@google.com               termcap.Normal
5733918Ssaidi@eecs.umich.edu    else:
5743918Ssaidi@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
5756157Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
5766157Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
5776157Snate@binkert.org    print "       environment."
5786157Snate@binkert.org    print "       "
5795397Ssaidi@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
5805397Ssaidi@eecs.umich.edu    print "       above you will need to ease fix SConstruct and "
5816121Snate@binkert.org    print "       src/SConscript to support that compiler."
5826121Snate@binkert.org    Exit(1)
5836121Snate@binkert.org
5846121Snate@binkert.orgif main['GCC']:
5856121Snate@binkert.org    # Check for a supported version of gcc. >= 4.6 is chosen for its
5866121Snate@binkert.org    # level of c++11 support. See
5875397Ssaidi@eecs.umich.edu    # http://gcc.gnu.org/projects/cxx0x.html for details. 4.6 is also
5881851SN/A    # the first version with proper LTO support.
5891851SN/A    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5907739Sgblack@eecs.umich.edu    if compareVersions(gcc_version, "4.6") < 0:
591955SN/A        print 'Error: gcc version 4.6 or newer required.'
5929396Sandreas.hansson@arm.com        print '       Installed version:', gcc_version
5939396Sandreas.hansson@arm.com        Exit(1)
5949396Sandreas.hansson@arm.com
5959396Sandreas.hansson@arm.com    main['GCC_VERSION'] = gcc_version
5969396Sandreas.hansson@arm.com
5979396Sandreas.hansson@arm.com    # gcc from version 4.8 and above generates "rep; ret" instructions
59812563Sgabeblack@google.com    # to avoid performance penalties on certain AMD chips. Older
59912563Sgabeblack@google.com    # assemblers detect this as an error, "Error: expecting string
60012563Sgabeblack@google.com    # instruction after `rep'"
60112563Sgabeblack@google.com    if compareVersions(gcc_version, "4.8") > 0:
6029396Sandreas.hansson@arm.com        as_version = readCommand([main['AS'], '-v', '/dev/null'],
6039396Sandreas.hansson@arm.com                                 exception=False).split()
6049396Sandreas.hansson@arm.com
6059396Sandreas.hansson@arm.com        if not as_version or compareVersions(as_version[-1], "2.23") < 0:
6069396Sandreas.hansson@arm.com            print termcap.Yellow + termcap.Bold + \
6079396Sandreas.hansson@arm.com                'Warning: This combination of gcc and binutils have' + \
60812563Sgabeblack@google.com                ' known incompatibilities.\n' + \
60912563Sgabeblack@google.com                '         If you encounter build problems, please update ' + \
61012563Sgabeblack@google.com                'binutils to 2.23.' + \
61112563Sgabeblack@google.com                termcap.Normal
61212563Sgabeblack@google.com
6139477Sandreas.hansson@arm.com    # Make sure we warn if the user has requested to compile with the
6149477Sandreas.hansson@arm.com    # Undefined Benahvior Sanitizer and this version of gcc does not
6159477Sandreas.hansson@arm.com    # support it.
6169477Sandreas.hansson@arm.com    if GetOption('with_ubsan') and \
6179477Sandreas.hansson@arm.com            compareVersions(gcc_version, '4.9') < 0:
6189477Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + \
6199477Sandreas.hansson@arm.com            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
6209477Sandreas.hansson@arm.com            termcap.Normal
6219477Sandreas.hansson@arm.com
6229477Sandreas.hansson@arm.com    # Add the appropriate Link-Time Optimization (LTO) flags
6239477Sandreas.hansson@arm.com    # unless LTO is explicitly turned off. Note that these flags
6249477Sandreas.hansson@arm.com    # are only used by the fast target.
6259477Sandreas.hansson@arm.com    if not GetOption('no_lto'):
6269477Sandreas.hansson@arm.com        # Pass the LTO flag when compiling to produce GIMPLE
62712563Sgabeblack@google.com        # output, we merely create the flags here and only append
62812563Sgabeblack@google.com        # them later
62912563Sgabeblack@google.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6309396Sandreas.hansson@arm.com
6312667Sstever@eecs.umich.edu        # Use the same amount of jobs for LTO as we are running
63210710Sandreas.hansson@arm.com        # scons with
63310710Sandreas.hansson@arm.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
63410710Sandreas.hansson@arm.com
63511811Sbaz21@cam.ac.uk    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
63611811Sbaz21@cam.ac.uk                                  '-fno-builtin-realloc', '-fno-builtin-free'])
63711811Sbaz21@cam.ac.uk
63811811Sbaz21@cam.ac.ukelif main['CLANG']:
63911811Sbaz21@cam.ac.uk    # Check for a supported version of clang, >= 3.0 is needed to
64011811Sbaz21@cam.ac.uk    # support similar features as gcc 4.6. See
64110710Sandreas.hansson@arm.com    # http://clang.llvm.org/cxx_status.html for details
64210710Sandreas.hansson@arm.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
64310710Sandreas.hansson@arm.com    clang_version_match = clang_version_re.search(CXX_version)
64410710Sandreas.hansson@arm.com    if (clang_version_match):
64510384SCurtis.Dunham@arm.com        clang_version = clang_version_match.groups()[0]
6469986Sandreas@sandberg.pp.se        if compareVersions(clang_version, "3.0") < 0:
6479986Sandreas@sandberg.pp.se            print 'Error: clang version 3.0 or newer required.'
6489986Sandreas@sandberg.pp.se            print '       Installed version:', clang_version
6499986Sandreas@sandberg.pp.se            Exit(1)
6509986Sandreas@sandberg.pp.se    else:
6519986Sandreas@sandberg.pp.se        print 'Error: Unable to determine clang version.'
6529986Sandreas@sandberg.pp.se        Exit(1)
6539986Sandreas@sandberg.pp.se
6549986Sandreas@sandberg.pp.se    # clang has a few additional warnings that we disable,
6559986Sandreas@sandberg.pp.se    # tautological comparisons are allowed due to unsigned integers
6569986Sandreas@sandberg.pp.se    # being compared to constants that happen to be 0, and extraneous
6579986Sandreas@sandberg.pp.se    # parantheses are allowed due to Ruby's printing of the AST,
6589986Sandreas@sandberg.pp.se    # finally self assignments are allowed as the generated CPU code
6599986Sandreas@sandberg.pp.se    # is relying on this
6609986Sandreas@sandberg.pp.se    main.Append(CCFLAGS=['-Wno-tautological-compare',
6619986Sandreas@sandberg.pp.se                         '-Wno-parentheses',
6629986Sandreas@sandberg.pp.se                         '-Wno-self-assign',
6639986Sandreas@sandberg.pp.se                         # Some versions of libstdc++ (4.8?) seem to
6649986Sandreas@sandberg.pp.se                         # use struct hash and class hash
6659986Sandreas@sandberg.pp.se                         # interchangeably.
6662638Sstever@eecs.umich.edu                         '-Wno-mismatched-tags',
6672638Sstever@eecs.umich.edu                         ])
6686121Snate@binkert.org
6693716Sstever@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6705522Snate@binkert.org
6719986Sandreas@sandberg.pp.se    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6729986Sandreas@sandberg.pp.se    # opposed to libstdc++, as the later is dated.
6739986Sandreas@sandberg.pp.se    if sys.platform == "darwin":
6745522Snate@binkert.org        main.Append(CXXFLAGS=['-stdlib=libc++'])
6755227Ssaidi@eecs.umich.edu        main.Append(LIBS=['c++'])
6765227Ssaidi@eecs.umich.edu
6775227Ssaidi@eecs.umich.eduelse:
6785227Ssaidi@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6796654Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
6806654Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6817769SAli.Saidi@ARM.com    print termcap.Yellow + '       version:' + termcap.Normal,
6827769SAli.Saidi@ARM.com    if not CXX_version:
6837769SAli.Saidi@ARM.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6847769SAli.Saidi@ARM.com               termcap.Normal
6855227Ssaidi@eecs.umich.edu    else:
6865227Ssaidi@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
6875227Ssaidi@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
6885204Sstever@gmail.com    print "       or clang, there appears to be something wrong with your"
6895204Sstever@gmail.com    print "       environment."
6905204Sstever@gmail.com    print "       "
6915204Sstever@gmail.com    print "       If you are trying to use a compiler other than those listed"
6925204Sstever@gmail.com    print "       above you will need to ease fix SConstruct and "
6935204Sstever@gmail.com    print "       src/SConscript to support that compiler."
6945204Sstever@gmail.com    Exit(1)
6955204Sstever@gmail.com
6965204Sstever@gmail.com# Set up common yacc/bison flags (needed for Ruby)
6975204Sstever@gmail.commain['YACCFLAGS'] = '-d'
6985204Sstever@gmail.commain['YACCHXXFILESUFFIX'] = '.hh'
6995204Sstever@gmail.com
7005204Sstever@gmail.com# Do this after we save setting back, or else we'll tack on an
7015204Sstever@gmail.com# extra 'qdo' every time we run scons.
7025204Sstever@gmail.comif main['BATCH']:
7035204Sstever@gmail.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
7045204Sstever@gmail.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
7056121Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
7065204Sstever@gmail.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
7077727SAli.Saidi@ARM.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
7087727SAli.Saidi@ARM.com
70912563Sgabeblack@google.comif sys.platform == 'cygwin':
7107727SAli.Saidi@ARM.com    # cygwin has some header file issues...
7117727SAli.Saidi@ARM.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
71211988Sandreas.sandberg@arm.com
71311988Sandreas.sandberg@arm.com# Check for the protobuf compiler
71410453SAndrew.Bardsley@arm.comprotoc_version = readCommand([main['PROTOC'], '--version'],
71510453SAndrew.Bardsley@arm.com                             exception='').split()
71610453SAndrew.Bardsley@arm.com
71710453SAndrew.Bardsley@arm.com# First two words should be "libprotoc x.y.z"
71810453SAndrew.Bardsley@arm.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
71910453SAndrew.Bardsley@arm.com    print termcap.Yellow + termcap.Bold + \
72010453SAndrew.Bardsley@arm.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
72113715Sandreas.sandberg@arm.com        '         Please install protobuf-compiler for tracing support.' + \
72213715Sandreas.sandberg@arm.com        termcap.Normal
72313715Sandreas.sandberg@arm.com    main['PROTOC'] = False
72413715Sandreas.sandberg@arm.comelse:
72513715Sandreas.sandberg@arm.com    # Based on the availability of the compress stream wrappers,
72613715Sandreas.sandberg@arm.com    # require 2.1.0
72713715Sandreas.sandberg@arm.com    min_protoc_version = '2.1.0'
72813715Sandreas.sandberg@arm.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
72910453SAndrew.Bardsley@arm.com        print termcap.Yellow + termcap.Bold + \
73010453SAndrew.Bardsley@arm.com            'Warning: protoc version', min_protoc_version, \
73113541Sandrea.mondelli@ucf.edu            'or newer required.\n' + \
73210453SAndrew.Bardsley@arm.com            '         Installed version:', protoc_version[1], \
73310453SAndrew.Bardsley@arm.com            termcap.Normal
73413541Sandrea.mondelli@ucf.edu        main['PROTOC'] = False
73513541Sandrea.mondelli@ucf.edu    else:
7369812Sandreas.hansson@arm.com        # Attempt to determine the appropriate include path and
73710453SAndrew.Bardsley@arm.com        # library path using pkg-config, that means we also need to
73810453SAndrew.Bardsley@arm.com        # check for pkg-config. Note that it is possible to use
73910453SAndrew.Bardsley@arm.com        # protobuf without the involvement of pkg-config. Later on we
74010453SAndrew.Bardsley@arm.com        # check go a library config check and at that point the test
74110453SAndrew.Bardsley@arm.com        # will fail if libprotobuf cannot be found.
74210453SAndrew.Bardsley@arm.com        if readCommand(['pkg-config', '--version'], exception=''):
74310453SAndrew.Bardsley@arm.com            try:
74410453SAndrew.Bardsley@arm.com                # Attempt to establish what linking flags to add for protobuf
74510453SAndrew.Bardsley@arm.com                # using pkg-config
74610453SAndrew.Bardsley@arm.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
74710453SAndrew.Bardsley@arm.com            except:
74810453SAndrew.Bardsley@arm.com                print termcap.Yellow + termcap.Bold + \
7497727SAli.Saidi@ARM.com                    'Warning: pkg-config could not get protobuf flags.' + \
75010453SAndrew.Bardsley@arm.com                    termcap.Normal
75110453SAndrew.Bardsley@arm.com
75212790Smatteo.fusi@bsc.es# Check for SWIG
75312790Smatteo.fusi@bsc.esif not main.has_key('SWIG'):
75412790Smatteo.fusi@bsc.es    print 'Error: SWIG utility not found.'
75512790Smatteo.fusi@bsc.es    print '       Please install (see http://www.swig.org) and retry.'
75612790Smatteo.fusi@bsc.es    Exit(1)
75712790Smatteo.fusi@bsc.es
75812790Smatteo.fusi@bsc.es# Check for appropriate SWIG version
75910453SAndrew.Bardsley@arm.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7603118Sstever@eecs.umich.edu# First 3 words should be "SWIG Version x.y.z"
76110453SAndrew.Bardsley@arm.comif len(swig_version) < 3 or \
76210453SAndrew.Bardsley@arm.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
76312563Sgabeblack@google.com    print 'Error determining SWIG version.'
76410453SAndrew.Bardsley@arm.com    Exit(1)
7653118Sstever@eecs.umich.edu
7663483Ssaidi@eecs.umich.edumin_swig_version = '2.0.4'
7673494Ssaidi@eecs.umich.eduif compareVersions(swig_version[2], min_swig_version) < 0:
7683494Ssaidi@eecs.umich.edu    print 'Error: SWIG version', min_swig_version, 'or newer required.'
76912563Sgabeblack@google.com    print '       Installed version:', swig_version[2]
7703483Ssaidi@eecs.umich.edu    Exit(1)
7713483Ssaidi@eecs.umich.edu
7723053Sstever@eecs.umich.edu# Check for known incompatibilities. The standard library shipped with
7733053Sstever@eecs.umich.edu# gcc >= 4.9 does not play well with swig versions prior to 3.0
7743918Ssaidi@eecs.umich.eduif main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
77512563Sgabeblack@google.com        compareVersions(swig_version[2], '3.0') < 0:
77612563Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + \
77712563Sgabeblack@google.com        'Warning: This combination of gcc and swig have' + \
7783053Sstever@eecs.umich.edu        ' known incompatibilities.\n' + \
7793053Sstever@eecs.umich.edu        '         If you encounter build problems, please update ' + \
7809396Sandreas.hansson@arm.com        'swig to 3.0 or later.' + \
7819396Sandreas.hansson@arm.com        termcap.Normal
7829396Sandreas.hansson@arm.com
7839396Sandreas.hansson@arm.com# Set up SWIG flags & scanner
7849396Sandreas.hansson@arm.comswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7859396Sandreas.hansson@arm.commain.Append(SWIGFLAGS=swig_flags)
7869396Sandreas.hansson@arm.com
7879396Sandreas.hansson@arm.com# Check for 'timeout' from GNU coreutils. If present, regressions will
7889396Sandreas.hansson@arm.com# be run with a time limit. We require version 8.13 since we rely on
78912920Sgabeblack@google.com# support for the '--foreground' option.
79012920Sgabeblack@google.comtimeout_lines = readCommand(['timeout', '--version'],
79112920Sgabeblack@google.com                            exception='').splitlines()
79212920Sgabeblack@google.com# Get the first line and tokenize it
7939477Sandreas.hansson@arm.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
7949396Sandreas.hansson@arm.commain['TIMEOUT'] =  timeout_version and \
79512563Sgabeblack@google.com    compareVersions(timeout_version[-1], '8.13') >= 0
79612563Sgabeblack@google.com
79712563Sgabeblack@google.com# filter out all existing swig scanners, they mess up the dependency
79812563Sgabeblack@google.com# stuff for some reason
7999396Sandreas.hansson@arm.comscanners = []
8007840Snate@binkert.orgfor scanner in main['SCANNERS']:
8017865Sgblack@eecs.umich.edu    skeys = scanner.skeys
8027865Sgblack@eecs.umich.edu    if skeys == '.i':
8037865Sgblack@eecs.umich.edu        continue
8047865Sgblack@eecs.umich.edu
8057865Sgblack@eecs.umich.edu    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
8067840Snate@binkert.org        continue
8079900Sandreas@sandberg.pp.se
8089900Sandreas@sandberg.pp.se    scanners.append(scanner)
8099900Sandreas@sandberg.pp.se
8109900Sandreas@sandberg.pp.se# add the new swig scanner that we like better
81110456SCurtis.Dunham@arm.comfrom SCons.Scanner import ClassicCPP as CPPScanner
81210456SCurtis.Dunham@arm.comswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
81310456SCurtis.Dunham@arm.comscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
81410456SCurtis.Dunham@arm.com
81510456SCurtis.Dunham@arm.com# replace the scanners list that has what we want
81610456SCurtis.Dunham@arm.commain['SCANNERS'] = scanners
81712563Sgabeblack@google.com
81812563Sgabeblack@google.com# Add a custom Check function to the Configure context so that we can
81912563Sgabeblack@google.com# figure out if the compiler adds leading underscores to global
82012563Sgabeblack@google.com# variables.  This is needed for the autogenerated asm files that we
8219045SAli.Saidi@ARM.com# use for embedding the python code.
82211235Sandreas.sandberg@arm.comdef CheckLeading(context):
82311235Sandreas.sandberg@arm.com    context.Message("Checking for leading underscore in global variables...")
82411235Sandreas.sandberg@arm.com    # 1) Define a global variable called x from asm so the C compiler
82511235Sandreas.sandberg@arm.com    #    won't change the symbol at all.
82611235Sandreas.sandberg@arm.com    # 2) Declare that variable.
82712485Sjang.hanhwi@gmail.com    # 3) Use the variable
82812485Sjang.hanhwi@gmail.com    #
82912485Sjang.hanhwi@gmail.com    # If the compiler prepends an underscore, this will successfully
83011235Sandreas.sandberg@arm.com    # link because the external symbol 'x' will be called '_x' which
83111811Sbaz21@cam.ac.uk    # was defined by the asm statement.  If the compiler does not
83212485Sjang.hanhwi@gmail.com    # prepend an underscore, this will not successfully link because
83311811Sbaz21@cam.ac.uk    # '_x' will have been defined by assembly, while the C portion of
83411811Sbaz21@cam.ac.uk    # the code will be trying to use 'x'
83511811Sbaz21@cam.ac.uk    ret = context.TryLink('''
83611235Sandreas.sandberg@arm.com        asm(".globl _x; _x: .byte 0");
83711235Sandreas.sandberg@arm.com        extern int x;
83811235Sandreas.sandberg@arm.com        int main() { return x; }
83912563Sgabeblack@google.com        ''', extension=".c")
84012563Sgabeblack@google.com    context.env.Append(LEADING_UNDERSCORE=ret)
84112563Sgabeblack@google.com    context.Result(ret)
84211235Sandreas.sandberg@arm.com    return ret
8437840Snate@binkert.org
84412563Sgabeblack@google.com# Add a custom Check function to test for structure members.
8457840Snate@binkert.orgdef CheckMember(context, include, decl, member, include_quotes="<>"):
8461858SN/A    context.Message("Checking for member %s in %s..." %
8471858SN/A                    (member, decl))
8481858SN/A    text = """
84912563Sgabeblack@google.com#include %(header)s
85012563Sgabeblack@google.comint main(){
8511858SN/A  %(decl)s test;
85212230Sgiacomo.travaglini@arm.com  (void)test.%(member)s;
85312230Sgiacomo.travaglini@arm.com  return 0;
85412230Sgiacomo.travaglini@arm.com};
85512230Sgiacomo.travaglini@arm.com""" % { "header" : include_quotes[0] + include + include_quotes[1],
85612563Sgabeblack@google.com        "decl" : decl,
85712563Sgabeblack@google.com        "member" : member,
85812563Sgabeblack@google.com        }
85912230Sgiacomo.travaglini@arm.com
8609903Sandreas.hansson@arm.com    ret = context.TryCompile(text, extension=".cc")
8619903Sandreas.hansson@arm.com    context.Result(ret)
8629903Sandreas.hansson@arm.com    return ret
8639903Sandreas.hansson@arm.com
86410841Sandreas.sandberg@arm.com# Platform-specific configuration.  Note again that we assume that all
8659651SAndreas.Sandberg@ARM.com# builds under a given build root run on the same host platform.
86612563Sgabeblack@google.comconf = Configure(main,
86712563Sgabeblack@google.com                 conf_dir = joinpath(build_root, '.scons_config'),
8689651SAndreas.Sandberg@ARM.com                 log_file = joinpath(build_root, 'scons_config.log'),
86912056Sgabeblack@google.com                 custom_tests = {
87012056Sgabeblack@google.com        'CheckLeading' : CheckLeading,
87112056Sgabeblack@google.com        'CheckMember' : CheckMember,
87212563Sgabeblack@google.com        })
87312056Sgabeblack@google.com
87410841Sandreas.sandberg@arm.com# Check for leading underscores.  Don't really need to worry either
87510841Sandreas.sandberg@arm.com# way so don't need to check the return code.
87610841Sandreas.sandberg@arm.comconf.CheckLeading()
87710841Sandreas.sandberg@arm.com
87810841Sandreas.sandberg@arm.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
87910841Sandreas.sandberg@arm.comtry:
8809651SAndreas.Sandberg@ARM.com    import platform
8819651SAndreas.Sandberg@ARM.com    uname = platform.uname()
8829651SAndreas.Sandberg@ARM.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
8839651SAndreas.Sandberg@ARM.com        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
8849651SAndreas.Sandberg@ARM.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
8859651SAndreas.Sandberg@ARM.com            main.Append(CFLAGS=['-arch', 'x86_64'])
88612563Sgabeblack@google.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
8879651SAndreas.Sandberg@ARM.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
8889651SAndreas.Sandberg@ARM.comexcept:
88910841Sandreas.sandberg@arm.com    pass
89012563Sgabeblack@google.com
89112563Sgabeblack@google.com# Recent versions of scons substitute a "Null" object for Configure()
89210841Sandreas.sandberg@arm.com# when configuration isn't necessary, e.g., if the "--help" option is
89310841Sandreas.sandberg@arm.com# present.  Unfortuantely this Null object always returns false,
89410841Sandreas.sandberg@arm.com# breaking all our configuration checks.  We replace it with our own
89510860Sandreas.sandberg@arm.com# more optimistic null object that returns True instead.
89610841Sandreas.sandberg@arm.comif not conf:
89710841Sandreas.sandberg@arm.com    def NullCheck(*args, **kwargs):
89810841Sandreas.sandberg@arm.com        return True
89910841Sandreas.sandberg@arm.com
90010841Sandreas.sandberg@arm.com    class NullConf:
90112563Sgabeblack@google.com        def __init__(self, env):
90210841Sandreas.sandberg@arm.com            self.env = env
90310841Sandreas.sandberg@arm.com        def Finish(self):
90410841Sandreas.sandberg@arm.com            return self.env
90510841Sandreas.sandberg@arm.com        def __getattr__(self, mname):
90610841Sandreas.sandberg@arm.com            return NullCheck
9079651SAndreas.Sandberg@ARM.com
9089651SAndreas.Sandberg@ARM.com    conf = NullConf(main)
9099986Sandreas@sandberg.pp.se
9109986Sandreas@sandberg.pp.se# Cache build files in the supplied directory.
9119986Sandreas@sandberg.pp.seif main['M5_BUILD_CACHE']:
9129986Sandreas@sandberg.pp.se    print 'Using build cache located at', main['M5_BUILD_CACHE']
9139986Sandreas@sandberg.pp.se    CacheDir(main['M5_BUILD_CACHE'])
9149986Sandreas@sandberg.pp.se
9155863Snate@binkert.orgif not GetOption('without_python'):
9165863Snate@binkert.org    # Find Python include and library directories for embedding the
9175863Snate@binkert.org    # interpreter. We rely on python-config to resolve the appropriate
9185863Snate@binkert.org    # includes and linker flags. ParseConfig does not seem to understand
9196121Snate@binkert.org    # the more exotic linker flags such as -Xlinker and -export-dynamic so
9201858SN/A    # we add them explicitly below. If you want to link in an alternate
9215863Snate@binkert.org    # version of python, see above for instructions on how to invoke
9225863Snate@binkert.org    # scons with the appropriate PATH set.
9235863Snate@binkert.org    #
9245863Snate@binkert.org    # First we check if python2-config exists, else we use python-config
9255863Snate@binkert.org    python_config = readCommand(['which', 'python2-config'],
9262139SN/A                                exception='').strip()
9274202Sbinkertn@umich.edu    if not os.path.exists(python_config):
92811308Santhony.gutierrez@amd.com        python_config = readCommand(['which', 'python-config'],
9294202Sbinkertn@umich.edu                                    exception='').strip()
93011308Santhony.gutierrez@amd.com    py_includes = readCommand([python_config, '--includes'],
9312139SN/A                              exception='').split()
9326994Snate@binkert.org    # Strip the -I from the include folders before adding them to the
9336994Snate@binkert.org    # CPPPATH
9346994Snate@binkert.org    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
9356994Snate@binkert.org
9366994Snate@binkert.org    # Read the linker flags and split them into libraries and other link
9376994Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
9386994Snate@binkert.org    py_ld_flags = readCommand([python_config, '--ldflags'],
9396994Snate@binkert.org        exception='').split()
94010319SAndreas.Sandberg@ARM.com    py_libs = []
9416994Snate@binkert.org    for lib in py_ld_flags:
9426994Snate@binkert.org         if not lib.startswith('-l'):
9436994Snate@binkert.org             main.Append(LINKFLAGS=[lib])
9446994Snate@binkert.org         else:
9456994Snate@binkert.org             lib = lib[2:]
9466994Snate@binkert.org             if lib not in py_libs:
9476994Snate@binkert.org                 py_libs.append(lib)
9486994Snate@binkert.org
9496994Snate@binkert.org    # verify that this stuff works
9506994Snate@binkert.org    if not conf.CheckHeader('Python.h', '<>'):
9516994Snate@binkert.org        print "Error: can't find Python.h header in", py_includes
9522155SN/A        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
9535863Snate@binkert.org        Exit(1)
9541869SN/A
9551869SN/A    for lib in py_libs:
9565863Snate@binkert.org        if not conf.CheckLib(lib):
9575863Snate@binkert.org            print "Error: can't find library %s required by python" % lib
9584202Sbinkertn@umich.edu            Exit(1)
9596108Snate@binkert.org
9606108Snate@binkert.org# On Solaris you need to use libsocket for socket ops
9616108Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
9626108Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
9639219Spower.jg@gmail.com       print "Can't find library with socket calls (e.g. accept())"
9649219Spower.jg@gmail.com       Exit(1)
9659219Spower.jg@gmail.com
9669219Spower.jg@gmail.com# Check for zlib.  If the check passes, libz will be automatically
9679219Spower.jg@gmail.com# added to the LIBS environment variable.
9689219Spower.jg@gmail.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
9699219Spower.jg@gmail.com    print 'Error: did not find needed zlib compression library '\
9709219Spower.jg@gmail.com          'and/or zlib.h header file.'
9714202Sbinkertn@umich.edu    print '       Please install zlib and try again.'
9725863Snate@binkert.org    Exit(1)
97310135SCurtis.Dunham@arm.com
97412563Sgabeblack@google.com# If we have the protobuf compiler, also make sure we have the
9755742Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
9768268Ssteve.reinhardt@amd.com# automatically added to the LIBS environment variable. After
97712563Sgabeblack@google.com# this, we can use the HAVE_PROTOBUF flag to determine if we have
9788268Ssteve.reinhardt@amd.com# got both protoc and libprotobuf available.
9795742Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
9805341Sstever@gmail.com    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
9818474Sgblack@eecs.umich.edu                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
98212563Sgabeblack@google.com
9835342Sstever@gmail.com# If we have the compiler but not the library, print another warning.
9844202Sbinkertn@umich.eduif main['PROTOC'] and not main['HAVE_PROTOBUF']:
9854202Sbinkertn@umich.edu    print termcap.Yellow + termcap.Bold + \
98611308Santhony.gutierrez@amd.com        'Warning: did not find protocol buffer library and/or headers.\n' + \
9874202Sbinkertn@umich.edu    '       Please install libprotobuf-dev for tracing support.' + \
9885863Snate@binkert.org    termcap.Normal
9895863Snate@binkert.org
99011308Santhony.gutierrez@amd.com# Check for librt.
9916994Snate@binkert.orghave_posix_clock = \
9926994Snate@binkert.org    conf.CheckLibWithHeader(None, 'time.h', 'C',
99310319SAndreas.Sandberg@ARM.com                            'clock_nanosleep(0,0,NULL,NULL);') or \
9945863Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
9955863Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
9965863Snate@binkert.org
9975863Snate@binkert.orghave_posix_timers = \
9985863Snate@binkert.org    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
9995863Snate@binkert.org                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
10005863Snate@binkert.org
10015863Snate@binkert.orgif not GetOption('without_tcmalloc'):
10027840Snate@binkert.org    if conf.CheckLib('tcmalloc'):
10035863Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
100412230Sgiacomo.travaglini@arm.com    elif conf.CheckLib('tcmalloc_minimal'):
100512230Sgiacomo.travaglini@arm.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
100612230Sgiacomo.travaglini@arm.com    else:
100712230Sgiacomo.travaglini@arm.com        print termcap.Yellow + termcap.Bold + \
100812230Sgiacomo.travaglini@arm.com              "You can get a 12% performance improvement by "\
100912056Sgabeblack@google.com              "installing tcmalloc (libgoogle-perftools-dev package "\
101012056Sgabeblack@google.com              "on Ubuntu or RedHat)." + termcap.Normal
101112056Sgabeblack@google.com
101211308Santhony.gutierrez@amd.comif not have_posix_clock:
10139219Spower.jg@gmail.com    print "Can't find library for POSIX clocks."
10149219Spower.jg@gmail.com
101511235Sandreas.sandberg@arm.com# Check for <fenv.h> (C99 FP environment control)
101614037Sjohnathan.alsop@amd.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
101714037Sjohnathan.alsop@amd.comif not have_fenv:
101814037Sjohnathan.alsop@amd.com    print "Warning: Header file <fenv.h> not found."
10191869SN/A    print "         This host has no IEEE FP rounding mode control."
10201858SN/A
10215863Snate@binkert.org# Check if we should enable KVM-based hardware virtualization. The API
102211308Santhony.gutierrez@amd.com# we rely on exists since version 2.6.36 of the kernel, but somehow
102312061Sjason@lowepower.com# the KVM_API_VERSION does not reflect the change. We test for one of
102412920Sgabeblack@google.com# the types as a fall back.
102514037Sjohnathan.alsop@amd.comhave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
102614037Sjohnathan.alsop@amd.comif not have_kvm:
10271858SN/A    print "Info: Compatible header file <linux/kvm.h> not found, " \
1028955SN/A        "disabling KVM support."
1029955SN/A
10301869SN/A# x86 needs support for xsave. We test for the structure here since we
10311869SN/A# won't be able to run new tests by the time we know which ISA we're
10321869SN/A# targeting.
10331869SN/Ahave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
10341869SN/A                                    '#include <linux/kvm.h>') != 0
10355863Snate@binkert.org
10365863Snate@binkert.org# Check if the requested target ISA is compatible with the host
10375863Snate@binkert.orgdef is_isa_kvm_compatible(isa):
10381869SN/A    try:
10395863Snate@binkert.org        import platform
10401869SN/A        host_isa = platform.machine()
104112563Sgabeblack@google.com    except:
10421869SN/A        print "Warning: Failed to determine host ISA."
10431869SN/A        return False
10441869SN/A
10451869SN/A    if not have_posix_timers:
10468483Sgblack@eecs.umich.edu        print "Warning: Can not enable KVM, host seems to lack support " \
10471869SN/A            "for POSIX timers"
10481869SN/A        return False
10491869SN/A
10501869SN/A    if isa == "arm":
10515863Snate@binkert.org        return host_isa in ( "armv7l", "aarch64" )
10525863Snate@binkert.org    elif isa == "x86":
10531869SN/A        if host_isa != "x86_64":
10545863Snate@binkert.org            return False
10555863Snate@binkert.org
10563356Sbinkertn@umich.edu        if not have_kvm_xsave:
10573356Sbinkertn@umich.edu            print "KVM on x86 requires xsave support in kernel headers."
10583356Sbinkertn@umich.edu            return False
10593356Sbinkertn@umich.edu
10603356Sbinkertn@umich.edu        return True
10614781Snate@binkert.org    else:
10625863Snate@binkert.org        return False
10635863Snate@binkert.org
10641869SN/A
10651869SN/A# Check if the exclude_host attribute is available. We want this to
10661869SN/A# get accurate instruction counts in KVM.
10676121Snate@binkert.orgmain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
10681869SN/A    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
106911982Sgabeblack@google.com
107011982Sgabeblack@google.com
107111982Sgabeblack@google.com######################################################################
107211982Sgabeblack@google.com#
107311982Sgabeblack@google.com# Finish the configuration
107411982Sgabeblack@google.com#
107511982Sgabeblack@google.commain = conf.Finish()
107611982Sgabeblack@google.com
107711982Sgabeblack@google.com######################################################################
107811982Sgabeblack@google.com#
107911982Sgabeblack@google.com# Collect all non-global variables
108011982Sgabeblack@google.com#
108111982Sgabeblack@google.com
108211982Sgabeblack@google.com# Define the universe of supported ISAs
108311982Sgabeblack@google.comall_isa_list = [ ]
108411982Sgabeblack@google.comExport('all_isa_list')
108511982Sgabeblack@google.com
108611982Sgabeblack@google.comclass CpuModel(object):
108711982Sgabeblack@google.com    '''The CpuModel class encapsulates everything the ISA parser needs to
108811982Sgabeblack@google.com    know about a particular CPU model.'''
108911982Sgabeblack@google.com
109011982Sgabeblack@google.com    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
109111982Sgabeblack@google.com    dict = {}
109211982Sgabeblack@google.com
109311982Sgabeblack@google.com    # Constructor.  Automatically adds models to CpuModel.dict.
109411982Sgabeblack@google.com    def __init__(self, name, default=False):
109513706Sgabeblack@google.com        self.name = name           # name of model
109613706Sgabeblack@google.com
109713706Sgabeblack@google.com        # This cpu is enabled by default
109813706Sgabeblack@google.com        self.default = default
109913706Sgabeblack@google.com
110013706Sgabeblack@google.com        # Add self to dict
110113706Sgabeblack@google.com        if name in CpuModel.dict:
110213706Sgabeblack@google.com            raise AttributeError, "CpuModel '%s' already registered" % name
110313758Sgabeblack@google.com        CpuModel.dict[name] = self
110413706Sgabeblack@google.com
110513706Sgabeblack@google.comExport('CpuModel')
110613706Sgabeblack@google.com
110713706Sgabeblack@google.com# Sticky variables get saved in the variables file so they persist from
110813706Sgabeblack@google.com# one invocation to the next (unless overridden, in which case the new
110913706Sgabeblack@google.com# value becomes sticky).
111013706Sgabeblack@google.comsticky_vars = Variables(args=ARGUMENTS)
111113706Sgabeblack@google.comExport('sticky_vars')
111213706Sgabeblack@google.com
111313713SAndrea.Mondelli@ucf.edu# Sticky variables that should be exported
111413713SAndrea.Mondelli@ucf.eduexport_vars = []
111513713SAndrea.Mondelli@ucf.eduExport('export_vars')
111613706Sgabeblack@google.com
111713706Sgabeblack@google.com# For Ruby
111811978Sgabeblack@google.comall_protocols = []
111911978Sgabeblack@google.comExport('all_protocols')
112012034Sgabeblack@google.comprotocol_dirs = []
112111978Sgabeblack@google.comExport('protocol_dirs')
112211978Sgabeblack@google.comslicc_includes = []
112311978Sgabeblack@google.comExport('slicc_includes')
112412034Sgabeblack@google.com
112511978Sgabeblack@google.com# Walk the tree and execute all SConsopts scripts that wil add to the
112611978Sgabeblack@google.com# above variables
112710915Sandreas.sandberg@arm.comif GetOption('verbose'):
112813577Sciro.santilli@arm.com    print "Reading SConsopts"
112913577Sciro.santilli@arm.comfor bdir in [ base_dir ] + extras_dir_list:
113013577Sciro.santilli@arm.com    if not isdir(bdir):
113111986Sandreas.sandberg@arm.com        print "Error: directory '%s' does not exist" % bdir
113211986Sandreas.sandberg@arm.com        Exit(1)
11331869SN/A    for root, dirs, files in os.walk(bdir):
11341869SN/A        if 'SConsopts' in files:
113512015Sgabeblack@google.com            if GetOption('verbose'):
113612015Sgabeblack@google.com                print "Reading", joinpath(root, 'SConsopts')
113712015Sgabeblack@google.com            SConscript(joinpath(root, 'SConsopts'))
113812015Sgabeblack@google.com
11393546Sgblack@eecs.umich.eduall_isa_list.sort()
11403546Sgblack@eecs.umich.edu
11413546Sgblack@eecs.umich.edusticky_vars.AddVariables(
114212015Sgabeblack@google.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
114312015Sgabeblack@google.com    ListVariable('CPU_MODELS', 'CPU models',
114412015Sgabeblack@google.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
114512015Sgabeblack@google.com                 sorted(CpuModel.dict.keys())),
114612015Sgabeblack@google.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
114712015Sgabeblack@google.com                 False),
114812015Sgabeblack@google.com    BoolVariable('SS_COMPATIBLE_FP',
114912563Sgabeblack@google.com                 'Make floating-point results compatible with SimpleScalar',
11503546Sgblack@eecs.umich.edu                 False),
115112015Sgabeblack@google.com    BoolVariable('USE_SSE2',
115212015Sgabeblack@google.com                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
115310196SCurtis.Dunham@arm.com                 False),
115412015Sgabeblack@google.com    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
115512015Sgabeblack@google.com    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
115612015Sgabeblack@google.com    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
115712015Sgabeblack@google.com    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
115812015Sgabeblack@google.com    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
115912015Sgabeblack@google.com                  all_protocols),
116012015Sgabeblack@google.com    )
116112015Sgabeblack@google.com
116212015Sgabeblack@google.com# These variables get exported to #defines in config/*.hh (see src/SConscript).
116312015Sgabeblack@google.comexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
116412015Sgabeblack@google.com                'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL', 'HAVE_PROTOBUF',
11653546Sgblack@eecs.umich.edu                'HAVE_PERF_ATTR_EXCLUDE_HOST']
11663546Sgblack@eecs.umich.edu
11673546Sgblack@eecs.umich.edu###################################################
1168955SN/A#
1169955SN/A# Define a SCons builder for configuration flag headers.
1170955SN/A#
1171955SN/A###################################################
11725863Snate@binkert.org
117310135SCurtis.Dunham@arm.com# This function generates a config header file that #defines the
117412563Sgabeblack@google.com# variable symbol to the current variable setting (0 or 1).  The source
11755343Sstever@gmail.com# operands are the name of the variable and a Value node containing the
11765343Sstever@gmail.com# value of the variable.
11776121Snate@binkert.orgdef build_config_file(target, source, env):
11785863Snate@binkert.org    (variable, value) = [s.get_contents() for s in source]
11794773Snate@binkert.org    f = file(str(target[0]), 'w')
11805863Snate@binkert.org    print >> f, '#define', variable, value
11812632Sstever@eecs.umich.edu    f.close()
11825863Snate@binkert.org    return None
11832023SN/A
11845863Snate@binkert.org# Combine the two functions into a scons Action object.
11855863Snate@binkert.orgconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
11865863Snate@binkert.org
11875863Snate@binkert.org# The emitter munges the source & target node lists to reflect what
11885863Snate@binkert.org# we're really doing.
11895863Snate@binkert.orgdef config_emitter(target, source, env):
11905863Snate@binkert.org    # extract variable name from Builder arg
11915863Snate@binkert.org    variable = str(target[0])
119210135SCurtis.Dunham@arm.com    # True target is config header file
119312563Sgabeblack@google.com    target = joinpath('config', variable.lower() + '.hh')
119412034Sgabeblack@google.com    val = env[variable]
119512034Sgabeblack@google.com    if isinstance(val, bool):
119612034Sgabeblack@google.com        # Force value to 0/1
11972632Sstever@eecs.umich.edu        val = int(val)
11985863Snate@binkert.org    elif isinstance(val, str):
11992023SN/A        val = '"' + val + '"'
12002632Sstever@eecs.umich.edu
12015863Snate@binkert.org    # Sources are variable name & value (packaged in SCons Value nodes)
12025342Sstever@gmail.com    return ([target], [Value(variable), Value(val)])
12035863Snate@binkert.org
12042632Sstever@eecs.umich.educonfig_builder = Builder(emitter = config_emitter, action = config_action)
12055863Snate@binkert.org
12065863Snate@binkert.orgmain.Append(BUILDERS = { 'ConfigFile' : config_builder })
12078267Ssteve.reinhardt@amd.com
12088120Sgblack@eecs.umich.edu# libelf build is shared across all configs in the build root.
12098267Ssteve.reinhardt@amd.commain.SConscript('ext/libelf/SConscript',
12108267Ssteve.reinhardt@amd.com                variant_dir = joinpath(build_root, 'libelf'))
12118267Ssteve.reinhardt@amd.com
12128267Ssteve.reinhardt@amd.com# gzstream build is shared across all configs in the build root.
12138267Ssteve.reinhardt@amd.commain.SConscript('ext/gzstream/SConscript',
12148267Ssteve.reinhardt@amd.com                variant_dir = joinpath(build_root, 'gzstream'))
12158267Ssteve.reinhardt@amd.com
12168267Ssteve.reinhardt@amd.com# libfdt build is shared across all configs in the build root.
12178267Ssteve.reinhardt@amd.commain.SConscript('ext/libfdt/SConscript',
12185863Snate@binkert.org                variant_dir = joinpath(build_root, 'libfdt'))
121912563Sgabeblack@google.com
122012563Sgabeblack@google.com# fputils build is shared across all configs in the build root.
12212632Sstever@eecs.umich.edumain.SConscript('ext/fputils/SConscript',
122212563Sgabeblack@google.com                variant_dir = joinpath(build_root, 'fputils'))
122312563Sgabeblack@google.com
122412563Sgabeblack@google.com# DRAMSim2 build is shared across all configs in the build root.
12252632Sstever@eecs.umich.edumain.SConscript('ext/dramsim2/SConscript',
12261888SN/A                variant_dir = joinpath(build_root, 'dramsim2'))
12275863Snate@binkert.org
12285863Snate@binkert.org# DRAMPower build is shared across all configs in the build root.
12291858SN/Amain.SConscript('ext/drampower/SConscript',
12308120Sgblack@eecs.umich.edu                variant_dir = joinpath(build_root, 'drampower'))
12318120Sgblack@eecs.umich.edu
12327756SAli.Saidi@ARM.com###################################################
12332598SN/A#
12345863Snate@binkert.org# This function is used to set up a directory with switching headers
12351858SN/A#
12361858SN/A###################################################
123712563Sgabeblack@google.com
123812563Sgabeblack@google.commain['ALL_ISA_LIST'] = all_isa_list
12391858SN/Aall_isa_deps = {}
12401858SN/Adef make_switching_dir(dname, switch_headers, env):
12411858SN/A    # Generate the header.  target[0] is the full path of the output
124212563Sgabeblack@google.com    # header to generate.  'source' is a dummy variable, since we get the
124312563Sgabeblack@google.com    # list of ISAs from env['ALL_ISA_LIST'].
124412563Sgabeblack@google.com    def gen_switch_hdr(target, source, env):
12451858SN/A        fname = str(target[0])
124612230Sgiacomo.travaglini@arm.com        isa = env['TARGET_ISA'].lower()
124712563Sgabeblack@google.com        try:
124812563Sgabeblack@google.com            f = open(fname, 'w')
124912230Sgiacomo.travaglini@arm.com            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
125012230Sgiacomo.travaglini@arm.com            f.close()
125112230Sgiacomo.travaglini@arm.com        except IOError:
125212230Sgiacomo.travaglini@arm.com            print "Failed to create %s" % fname
125312230Sgiacomo.travaglini@arm.com            raise
12541858SN/A
12551858SN/A    # Build SCons Action object. 'varlist' specifies env vars that this
12561858SN/A    # action depends on; when env['ALL_ISA_LIST'] changes these actions
12579651SAndreas.Sandberg@ARM.com    # should get re-executed.
12589651SAndreas.Sandberg@ARM.com    switch_hdr_action = MakeAction(gen_switch_hdr,
125912563Sgabeblack@google.com                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
126012563Sgabeblack@google.com
12619651SAndreas.Sandberg@ARM.com    # Instantiate actions for each header
12629651SAndreas.Sandberg@ARM.com    for hdr in switch_headers:
126312563Sgabeblack@google.com        env.Command(hdr, [], switch_hdr_action)
126412563Sgabeblack@google.com
12659651SAndreas.Sandberg@ARM.com    isa_target = Dir('.').up().name.lower().replace('_', '-')
12669651SAndreas.Sandberg@ARM.com    env['PHONY_BASE'] = '#'+isa_target
126712056Sgabeblack@google.com    all_isa_deps[isa_target] = None
126812056Sgabeblack@google.com
126912563Sgabeblack@google.comExport('make_switching_dir')
127012056Sgabeblack@google.com
127112056Sgabeblack@google.com# all-isas -> all-deps -> all-environs -> all_targets
127211798Santhony.gutierrez@amd.commain.Alias('#all-isas', [])
127311798Santhony.gutierrez@amd.commain.Alias('#all-deps', '#all-isas')
127411798Santhony.gutierrez@amd.com
12759986Sandreas@sandberg.pp.se# Dummy target to ensure all environments are created before telling
12769986Sandreas@sandberg.pp.se# SCons what to actually make (the command line arguments).  We attach
12779986Sandreas@sandberg.pp.se# them to the dependence graph after the environments are complete.
127812563Sgabeblack@google.comORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
127912563Sgabeblack@google.comdef environsComplete(target, source, env):
128012563Sgabeblack@google.com    for t in ORIG_BUILD_TARGETS:
12819986Sandreas@sandberg.pp.se        main.Depends('#all-targets', t)
12825863Snate@binkert.org
12835863Snate@binkert.org# Each build/* switching_dir attaches its *-environs target to #all-environs.
12841869SN/Amain.Append(BUILDERS = {'CompleteEnvirons' :
12851965SN/A                        Builder(action=MakeAction(environsComplete, None))})
12867739Sgblack@eecs.umich.edumain.CompleteEnvirons('#all-environs', [])
12871965SN/A
12882761Sstever@eecs.umich.edudef doNothing(**ignored): pass
12895863Snate@binkert.orgmain.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
12901869SN/A
129110196SCurtis.Dunham@arm.com# The final target to which all the original targets ultimately get attached.
12921869SN/Amain.Dummy('#all-targets', '#all-environs')
12938120Sgblack@eecs.umich.eduBUILD_TARGETS[:] = ['#all-targets']
12948120Sgblack@eecs.umich.edu
12958120Sgblack@eecs.umich.edu###################################################
12968120Sgblack@eecs.umich.edu#
12978120Sgblack@eecs.umich.edu# Define build environments for selected configurations.
12988120Sgblack@eecs.umich.edu#
12998120Sgblack@eecs.umich.edu###################################################
13008120Sgblack@eecs.umich.edu
13018120Sgblack@eecs.umich.edufor variant_path in variant_paths:
13028120Sgblack@eecs.umich.edu    if not GetOption('silent'):
13038120Sgblack@eecs.umich.edu        print "Building in", variant_path
13048120Sgblack@eecs.umich.edu
1305    # Make a copy of the build-root environment to use for this config.
1306    env = main.Clone()
1307    env['BUILDDIR'] = variant_path
1308
1309    # variant_dir is the tail component of build path, and is used to
1310    # determine the build parameters (e.g., 'ALPHA_SE')
1311    (build_root, variant_dir) = splitpath(variant_path)
1312
1313    # Set env variables according to the build directory config.
1314    sticky_vars.files = []
1315    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1316    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1317    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1318    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1319    if isfile(current_vars_file):
1320        sticky_vars.files.append(current_vars_file)
1321        if not GetOption('silent'):
1322            print "Using saved variables file %s" % current_vars_file
1323    else:
1324        # Build dir-specific variables file doesn't exist.
1325
1326        # Make sure the directory is there so we can create it later
1327        opt_dir = dirname(current_vars_file)
1328        if not isdir(opt_dir):
1329            mkdir(opt_dir)
1330
1331        # Get default build variables from source tree.  Variables are
1332        # normally determined by name of $VARIANT_DIR, but can be
1333        # overridden by '--default=' arg on command line.
1334        default = GetOption('default')
1335        opts_dir = joinpath(main.root.abspath, 'build_opts')
1336        if default:
1337            default_vars_files = [joinpath(build_root, 'variables', default),
1338                                  joinpath(opts_dir, default)]
1339        else:
1340            default_vars_files = [joinpath(opts_dir, variant_dir)]
1341        existing_files = filter(isfile, default_vars_files)
1342        if existing_files:
1343            default_vars_file = existing_files[0]
1344            sticky_vars.files.append(default_vars_file)
1345            print "Variables file %s not found,\n  using defaults in %s" \
1346                  % (current_vars_file, default_vars_file)
1347        else:
1348            print "Error: cannot find variables file %s or " \
1349                  "default file(s) %s" \
1350                  % (current_vars_file, ' or '.join(default_vars_files))
1351            Exit(1)
1352
1353    # Apply current variable settings to env
1354    sticky_vars.Update(env)
1355
1356    help_texts["local_vars"] += \
1357        "Build variables for %s:\n" % variant_dir \
1358                 + sticky_vars.GenerateHelpText(env)
1359
1360    # Process variable settings.
1361
1362    if not have_fenv and env['USE_FENV']:
1363        print "Warning: <fenv.h> not available; " \
1364              "forcing USE_FENV to False in", variant_dir + "."
1365        env['USE_FENV'] = False
1366
1367    if not env['USE_FENV']:
1368        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1369        print "         FP results may deviate slightly from other platforms."
1370
1371    if env['EFENCE']:
1372        env.Append(LIBS=['efence'])
1373
1374    if env['USE_KVM']:
1375        if not have_kvm:
1376            print "Warning: Can not enable KVM, host seems to lack KVM support"
1377            env['USE_KVM'] = False
1378        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1379            print "Info: KVM support disabled due to unsupported host and " \
1380                "target ISA combination"
1381            env['USE_KVM'] = False
1382
1383    # Warn about missing optional functionality
1384    if env['USE_KVM']:
1385        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1386            print "Warning: perf_event headers lack support for the " \
1387                "exclude_host attribute. KVM instruction counts will " \
1388                "be inaccurate."
1389
1390    # Save sticky variable settings back to current variables file
1391    sticky_vars.Save(current_vars_file, env)
1392
1393    if env['USE_SSE2']:
1394        env.Append(CCFLAGS=['-msse2'])
1395
1396    # The src/SConscript file sets up the build rules in 'env' according
1397    # to the configured variables.  It returns a list of environments,
1398    # one for each variant build (debug, opt, etc.)
1399    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1400
1401def pairwise(iterable):
1402    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1403    a, b = itertools.tee(iterable)
1404    b.next()
1405    return itertools.izip(a, b)
1406
1407# Create false dependencies so SCons will parse ISAs, establish
1408# dependencies, and setup the build Environments serially. Either
1409# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1410# greater than 1. It appears to be standard race condition stuff; it
1411# doesn't always fail, but usually, and the behaviors are different.
1412# Every time I tried to remove this, builds would fail in some
1413# creative new way. So, don't do that. You'll want to, though, because
1414# tests/SConscript takes a long time to make its Environments.
1415for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1416    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1417    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1418
1419# base help text
1420Help('''
1421Usage: scons [scons options] [build variables] [target(s)]
1422
1423Extra scons options:
1424%(options)s
1425
1426Global build variables:
1427%(global_vars)s
1428
1429%(local_vars)s
1430''' % help_texts)
1431