SConstruct revision 12688
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2013, 2015-2017 ARM Limited
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/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
282665Ssaidi@eecs.umich.edu# contributors may be used to endorse or promote products derived from
292665Ssaidi@eecs.umich.edu# 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
352632Sstever@eecs.umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
362632Sstever@eecs.umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
372632Sstever@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
382632Sstever@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
402632Sstever@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422761Sstever@eecs.umich.edu#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452632Sstever@eecs.umich.edu
462761Sstever@eecs.umich.edu###################################################
472761Sstever@eecs.umich.edu#
482761Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492632Sstever@eecs.umich.edu#
502632Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
522761Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532761Sstever@eecs.umich.edu# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# 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
572632Sstever@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:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
63955SN/A#   scons to search up the directory tree for this SConstruct file.
64955SN/A#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
65955SN/A#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
685396Ssaidi@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
694202Sbinkertn@umich.edu#   scons to chdir to the specified directory to find this SConstruct
705342Sstever@gmail.com#   file.
71955SN/A#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
725273Sstever@gmail.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
735273Sstever@gmail.com#
742656Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
752656Sstever@eecs.umich.edu# 'gem5' directory (or use -u or -C to tell scons where to find this
762656Sstever@eecs.umich.edu# file), you can use 'scons -h' to print all the gem5-specific build
772656Sstever@eecs.umich.edu# options as well.
782656Sstever@eecs.umich.edu#
792656Sstever@eecs.umich.edu###################################################
802656Sstever@eecs.umich.edu
812653Sstever@eecs.umich.edufrom __future__ import print_function
825227Ssaidi@eecs.umich.edu
835227Ssaidi@eecs.umich.edu# Global Python includes
845227Ssaidi@eecs.umich.eduimport itertools
855227Ssaidi@eecs.umich.eduimport os
865396Ssaidi@eecs.umich.eduimport re
875396Ssaidi@eecs.umich.eduimport shutil
885396Ssaidi@eecs.umich.eduimport subprocess
895396Ssaidi@eecs.umich.eduimport sys
905396Ssaidi@eecs.umich.edu
915396Ssaidi@eecs.umich.edufrom os import mkdir, environ
925396Ssaidi@eecs.umich.edufrom os.path import abspath, basename, dirname, expanduser, normpath
935396Ssaidi@eecs.umich.edufrom os.path import exists,  isdir, isfile
945588Ssaidi@eecs.umich.edufrom os.path import join as joinpath, split as splitpath
955396Ssaidi@eecs.umich.edu
965396Ssaidi@eecs.umich.edu# SCons includes
975396Ssaidi@eecs.umich.eduimport SCons
985396Ssaidi@eecs.umich.eduimport SCons.Node
995396Ssaidi@eecs.umich.edu
1005396Ssaidi@eecs.umich.edufrom m5.util import compareVersions, readCommand
1015396Ssaidi@eecs.umich.edu
1025396Ssaidi@eecs.umich.eduhelp_texts = {
1035396Ssaidi@eecs.umich.edu    "options" : "",
1045396Ssaidi@eecs.umich.edu    "global_vars" : "",
1055396Ssaidi@eecs.umich.edu    "local_vars" : ""
1065396Ssaidi@eecs.umich.edu}
1075396Ssaidi@eecs.umich.edu
1085396Ssaidi@eecs.umich.eduExport("help_texts")
1095396Ssaidi@eecs.umich.edu
1105396Ssaidi@eecs.umich.edu
1115396Ssaidi@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1125396Ssaidi@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1135396Ssaidi@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1145396Ssaidi@eecs.umich.edu# Help() function, but these two features are incompatible: once
1155396Ssaidi@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1165396Ssaidi@eecs.umich.edu# at the help texts from AddOptions.  See:
1175396Ssaidi@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1185396Ssaidi@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1195396Ssaidi@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1205396Ssaidi@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1215396Ssaidi@eecs.umich.edu# we can just use AddOption directly.
1225396Ssaidi@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1235396Ssaidi@eecs.umich.edu    col_width = 30
1245396Ssaidi@eecs.umich.edu
1255396Ssaidi@eecs.umich.edu    help = "  " + ", ".join(args)
1265396Ssaidi@eecs.umich.edu    if "help" in kwargs:
1275396Ssaidi@eecs.umich.edu        length = len(help)
1285396Ssaidi@eecs.umich.edu        if length >= col_width:
1295396Ssaidi@eecs.umich.edu            help += "\n" + " " * col_width
1305396Ssaidi@eecs.umich.edu        else:
1315396Ssaidi@eecs.umich.edu            help += " " * (col_width - length)
1325396Ssaidi@eecs.umich.edu        help += kwargs["help"]
1335396Ssaidi@eecs.umich.edu    help_texts["options"] += help + "\n"
1345396Ssaidi@eecs.umich.edu
1355396Ssaidi@eecs.umich.edu    AddOption(*args, **kwargs)
1365396Ssaidi@eecs.umich.edu
1375396Ssaidi@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1385396Ssaidi@eecs.umich.edu               help="Add color to abbreviated scons output")
1395396Ssaidi@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1405396Ssaidi@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1415396Ssaidi@eecs.umich.eduAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1425396Ssaidi@eecs.umich.edu               action='store_true',
1435396Ssaidi@eecs.umich.edu               help="Build with support for C++-based configuration")
1445396Ssaidi@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1455396Ssaidi@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1465396Ssaidi@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1474781Snate@binkert.org               help='Disable style checking hooks')
1481852SN/AAddLocalOption('--no-lto', dest='no_lto', action='store_true',
149955SN/A               help='Disable Link-Time Optimization for fast')
150955SN/AAddLocalOption('--force-lto', dest='force_lto', action='store_true',
151955SN/A               help='Use Link-Time Optimization instead of partial linking' +
1523717Sstever@eecs.umich.edu                    ' when the compiler doesn\'t support using them together.')
1533716Sstever@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
154955SN/A               help='Update test reference outputs')
1551533SN/AAddLocalOption('--verbose', dest='verbose', action='store_true',
1563716Sstever@eecs.umich.edu               help='Print full tool command lines')
1571533SN/AAddLocalOption('--without-python', dest='without_python',
1584678Snate@binkert.org               action='store_true',
1594678Snate@binkert.org               help='Build without Python configuration support')
1604678Snate@binkert.orgAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1614678Snate@binkert.org               action='store_true',
1624678Snate@binkert.org               help='Disable linking against tcmalloc')
1634678Snate@binkert.orgAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1644678Snate@binkert.org               help='Build with Undefined Behavior Sanitizer if available')
1654678Snate@binkert.orgAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1664678Snate@binkert.org               help='Build with Address Sanitizer if available')
1674678Snate@binkert.org
1684678Snate@binkert.orgif GetOption('no_lto') and GetOption('force_lto'):
1694678Snate@binkert.org    print('--no-lto and --force-lto are mutually exclusive')
1704678Snate@binkert.org    Exit(1)
1714678Snate@binkert.org
1724678Snate@binkert.org########################################################################
1734678Snate@binkert.org#
1744678Snate@binkert.org# Set up the main build environment.
1754678Snate@binkert.org#
1764678Snate@binkert.org########################################################################
1774678Snate@binkert.org
1784678Snate@binkert.orgmain = Environment()
1794973Ssaidi@eecs.umich.edu
1804678Snate@binkert.orgfrom gem5_scons import Transform
1814678Snate@binkert.orgfrom gem5_scons.util import get_termcap
1824678Snate@binkert.orgtermcap = get_termcap()
1834678Snate@binkert.org
1844678Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
1854678Snate@binkert.org
186955SN/A# Check that we have a C/C++ compiler
187955SN/Aif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1882632Sstever@eecs.umich.edu    print("No C++ compiler installed (package g++ on Ubuntu and RedHat)")
1892632Sstever@eecs.umich.edu    Exit(1)
190955SN/A
191955SN/A###################################################
192955SN/A#
193955SN/A# Figure out which configurations to set up based on the path(s) of
1942632Sstever@eecs.umich.edu# the target(s).
195955SN/A#
1962632Sstever@eecs.umich.edu###################################################
1972632Sstever@eecs.umich.edu
1982632Sstever@eecs.umich.edu# Find default configuration & binary.
1992632Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2002632Sstever@eecs.umich.edu
2012632Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
2022632Sstever@eecs.umich.edudef rfind(l, elt, offs = -1):
2032632Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
2042632Sstever@eecs.umich.edu        if l[i] == elt:
2052632Sstever@eecs.umich.edu            return i
2062632Sstever@eecs.umich.edu    raise ValueError, "element not found"
2072632Sstever@eecs.umich.edu
2082632Sstever@eecs.umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
2093718Sstever@eecs.umich.edu# paths made absolute and ~-expanded.  Paths will be interpreted
2103718Sstever@eecs.umich.edu# relative to the launch directory unless a different root is provided
2113718Sstever@eecs.umich.edudef makePathListAbsolute(path_list, root=GetLaunchDir()):
2123718Sstever@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
2133718Sstever@eecs.umich.edu            for p in path_list]
2143718Sstever@eecs.umich.edu
2153718Sstever@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
2163718Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
2173718Sstever@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2183718Sstever@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
2193718Sstever@eecs.umich.edu# follow 'build' in the build path.
2203718Sstever@eecs.umich.edu
2213718Sstever@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
2222634Sstever@eecs.umich.edu# in place rather than reassign the symbol to a new list, which
2232634Sstever@eecs.umich.edu# doesn't work (obviously!).
2242632Sstever@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2252638Sstever@eecs.umich.edu
2262632Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
2272632Sstever@eecs.umich.edu# collected targets reference.
2282632Sstever@eecs.umich.eduvariant_paths = []
2292632Sstever@eecs.umich.edubuild_root = None
2302632Sstever@eecs.umich.edufor t in BUILD_TARGETS:
2312632Sstever@eecs.umich.edu    path_dirs = t.split('/')
2321858SN/A    try:
2333716Sstever@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
2342638Sstever@eecs.umich.edu    except:
2352638Sstever@eecs.umich.edu        print("Error: no non-leaf 'build' dir found on target path", t)
2362638Sstever@eecs.umich.edu        Exit(1)
2372638Sstever@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2382638Sstever@eecs.umich.edu    if not build_root:
2392638Sstever@eecs.umich.edu        build_root = this_build_root
2402638Sstever@eecs.umich.edu    else:
2413716Sstever@eecs.umich.edu        if this_build_root != build_root:
2422634Sstever@eecs.umich.edu            print("Error: build targets not under same build root\n"
2432634Sstever@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root))
244955SN/A            Exit(1)
2455341Sstever@gmail.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
2465341Sstever@gmail.com    if variant_path not in variant_paths:
2475341Sstever@gmail.com        variant_paths.append(variant_path)
2485341Sstever@gmail.com
249955SN/A# Make sure build_root exists (might not if this is the first build there)
250955SN/Aif not isdir(build_root):
251955SN/A    mkdir(build_root)
252955SN/Amain['BUILDROOT'] = build_root
253955SN/A
254955SN/AExport('main')
255955SN/A
2561858SN/Amain.SConsignFile(joinpath(build_root, "sconsign"))
2571858SN/A
2582632Sstever@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
259955SN/A# when you use emacs to edit a file in the target dir, as emacs moves
2604494Ssaidi@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
2614494Ssaidi@eecs.umich.edu# (soft) links work better.
2623716Sstever@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
2631105SN/A
2642667Sstever@eecs.umich.edu#
2652667Sstever@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
2662667Sstever@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
2672667Sstever@eecs.umich.edu#
2682667Sstever@eecs.umich.edu
2692667Sstever@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
2701869SN/A
2711869SN/Aglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2721869SN/A
2731869SN/Aglobal_vars.AddVariables(
2741869SN/A    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2751065SN/A    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2765341Sstever@gmail.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2775341Sstever@gmail.com    ('BATCH', 'Use batch pool for build and tests', False),
2785341Sstever@gmail.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2795341Sstever@gmail.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2805341Sstever@gmail.com    ('EXTRAS', 'Add extra directories to the compilation', '')
2815341Sstever@gmail.com    )
2825341Sstever@gmail.com
2835341Sstever@gmail.com# Update main environment with values from ARGUMENTS & global_vars_file
2845341Sstever@gmail.comglobal_vars.Update(main)
2855341Sstever@gmail.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
2865341Sstever@gmail.com
2875341Sstever@gmail.com# Save sticky variable settings back to current variables file
2885341Sstever@gmail.comglobal_vars.Save(global_vars_file, main)
2895341Sstever@gmail.com
2905341Sstever@gmail.com# Parse EXTRAS variable to build list of all directories where we're
2915341Sstever@gmail.com# look for sources etc.  This list is exported as extras_dir_list.
2925341Sstever@gmail.combase_dir = main.srcdir.abspath
2935341Sstever@gmail.comif main['EXTRAS']:
2945341Sstever@gmail.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
2955341Sstever@gmail.comelse:
2965341Sstever@gmail.com    extras_dir_list = []
2975341Sstever@gmail.com
2985341Sstever@gmail.comExport('base_dir')
2995341Sstever@gmail.comExport('extras_dir_list')
3005341Sstever@gmail.com
3015341Sstever@gmail.com# the ext directory should be on the #includes path
3025341Sstever@gmail.commain.Append(CPPPATH=[Dir('ext')])
3035397Ssaidi@eecs.umich.edu
3045397Ssaidi@eecs.umich.edu# Add shared top-level headers
3055341Sstever@gmail.commain.Prepend(CPPPATH=Dir('include'))
3065341Sstever@gmail.com
3075341Sstever@gmail.comif GetOption('verbose'):
3085341Sstever@gmail.com    def MakeAction(action, string, *args, **kwargs):
3095341Sstever@gmail.com        return Action(action, *args, **kwargs)
3105341Sstever@gmail.comelse:
3115341Sstever@gmail.com    MakeAction = Action
3125341Sstever@gmail.com    main['CCCOMSTR']        = Transform("CC")
3135341Sstever@gmail.com    main['CXXCOMSTR']       = Transform("CXX")
3145341Sstever@gmail.com    main['ASCOMSTR']        = Transform("AS")
3155341Sstever@gmail.com    main['ARCOMSTR']        = Transform("AR", 0)
3165341Sstever@gmail.com    main['LINKCOMSTR']      = Transform("LINK", 0)
3175341Sstever@gmail.com    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
3185341Sstever@gmail.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3195341Sstever@gmail.com    main['M4COMSTR']        = Transform("M4")
3205341Sstever@gmail.com    main['SHCCCOMSTR']      = Transform("SHCC")
3215341Sstever@gmail.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
3225341Sstever@gmail.comExport('MakeAction')
3235341Sstever@gmail.com
3245341Sstever@gmail.com# Initialize the Link-Time Optimization (LTO) flags
3255341Sstever@gmail.commain['LTO_CCFLAGS'] = []
3265341Sstever@gmail.commain['LTO_LDFLAGS'] = []
3275742Snate@binkert.org
3285341Sstever@gmail.com# According to the readme, tcmalloc works best if the compiler doesn't
3295742Snate@binkert.org# assume that we're using the builtin malloc and friends. These flags
3305742Snate@binkert.org# are compiler-specific, so we need to set them after we detect which
3315742Snate@binkert.org# compiler we're using.
3325341Sstever@gmail.commain['TCMALLOC_CCFLAGS'] = []
3335742Snate@binkert.org
3345742Snate@binkert.orgCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3355341Sstever@gmail.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
3362632Sstever@eecs.umich.edu
3375199Sstever@gmail.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3384781Snate@binkert.orgmain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
3394781Snate@binkert.orgif main['GCC'] + main['CLANG'] > 1:
3405550Snate@binkert.org    print('Error: How can we have two at the same time?')
3414781Snate@binkert.org    Exit(1)
3424781Snate@binkert.org
3433918Ssaidi@eecs.umich.edu# Set up default C++ compiler flags
3444781Snate@binkert.orgif main['GCC'] or main['CLANG']:
3454781Snate@binkert.org    # As gcc and clang share many flags, do the common parts here
3463940Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
3473942Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
3483940Ssaidi@eecs.umich.edu    # Enable -Wall and -Wextra and then disable the few warnings that
3493918Ssaidi@eecs.umich.edu    # we consistently violate
3503918Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
351955SN/A                         '-Wno-sign-compare', '-Wno-unused-parameter'])
3521858SN/A    # We always compile using C++11
3533918Ssaidi@eecs.umich.edu    main.Append(CXXFLAGS=['-std=c++11'])
3543918Ssaidi@eecs.umich.edu    if sys.platform.startswith('freebsd'):
3553918Ssaidi@eecs.umich.edu        main.Append(CCFLAGS=['-I/usr/local/include'])
3563918Ssaidi@eecs.umich.edu        main.Append(CXXFLAGS=['-I/usr/local/include'])
3575571Snate@binkert.org
3583940Ssaidi@eecs.umich.edu    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3593940Ssaidi@eecs.umich.edu    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
3603918Ssaidi@eecs.umich.edu    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3613918Ssaidi@eecs.umich.edu    shared_partial_flags = ['-r', '-nostdlib']
3623918Ssaidi@eecs.umich.edu    main.Append(PSHLINKFLAGS=shared_partial_flags)
3633918Ssaidi@eecs.umich.edu    main.Append(PLINKFLAGS=shared_partial_flags)
3643918Ssaidi@eecs.umich.edu
3653918Ssaidi@eecs.umich.edu    # Treat warnings as errors but white list some warnings that we
3663918Ssaidi@eecs.umich.edu    # want to allow (e.g., deprecation warnings).
3673918Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-Werror',
3683918Ssaidi@eecs.umich.edu                         '-Wno-error=deprecated-declarations',
3693940Ssaidi@eecs.umich.edu                         '-Wno-error=deprecated',
3703918Ssaidi@eecs.umich.edu                        ])
3713918Ssaidi@eecs.umich.eduelse:
3725397Ssaidi@eecs.umich.edu    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
3735397Ssaidi@eecs.umich.edu    print("Don't know what compiler options to use for your compiler.")
3745397Ssaidi@eecs.umich.edu    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
3755708Ssaidi@eecs.umich.edu    print(termcap.Yellow + '       version:' + termcap.Normal, end = ' ')
3765708Ssaidi@eecs.umich.edu    if not CXX_version:
3775708Ssaidi@eecs.umich.edu        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
3785708Ssaidi@eecs.umich.edu              termcap.Normal)
3795708Ssaidi@eecs.umich.edu    else:
3805397Ssaidi@eecs.umich.edu        print(CXX_version.replace('\n', '<nl>'))
3811851SN/A    print("       If you're trying to use a compiler other than GCC")
3821851SN/A    print("       or clang, there appears to be something wrong with your")
3831858SN/A    print("       environment.")
3845200Sstever@gmail.com    print("       ")
385955SN/A    print("       If you are trying to use a compiler other than those listed")
3863053Sstever@eecs.umich.edu    print("       above you will need to ease fix SConstruct and ")
3873053Sstever@eecs.umich.edu    print("       src/SConscript to support that compiler.")
3883053Sstever@eecs.umich.edu    Exit(1)
3893053Sstever@eecs.umich.edu
3903053Sstever@eecs.umich.eduif main['GCC']:
3913053Sstever@eecs.umich.edu    # Check for a supported version of gcc. >= 4.8 is chosen for its
3923053Sstever@eecs.umich.edu    # level of c++11 support. See
3933053Sstever@eecs.umich.edu    # http://gcc.gnu.org/projects/cxx0x.html for details.
3943053Sstever@eecs.umich.edu    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
3954742Sstever@eecs.umich.edu    if compareVersions(gcc_version, "4.8") < 0:
3964742Sstever@eecs.umich.edu        print('Error: gcc version 4.8 or newer required.')
3973053Sstever@eecs.umich.edu        print('       Installed version: ', gcc_version)
3983053Sstever@eecs.umich.edu        Exit(1)
3993053Sstever@eecs.umich.edu
4003053Sstever@eecs.umich.edu    main['GCC_VERSION'] = gcc_version
4013053Sstever@eecs.umich.edu
4023053Sstever@eecs.umich.edu    if compareVersions(gcc_version, '4.9') >= 0:
4033053Sstever@eecs.umich.edu        # Incremental linking with LTO is currently broken in gcc versions
4043053Sstever@eecs.umich.edu        # 4.9 and above. A version where everything works completely hasn't
4053053Sstever@eecs.umich.edu        # yet been identified.
4062667Sstever@eecs.umich.edu        #
4074554Sbinkertn@umich.edu        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
4084554Sbinkertn@umich.edu        main['BROKEN_INCREMENTAL_LTO'] = True
4092667Sstever@eecs.umich.edu    if compareVersions(gcc_version, '6.0') >= 0:
4104554Sbinkertn@umich.edu        # gcc versions 6.0 and greater accept an -flinker-output flag which
4114554Sbinkertn@umich.edu        # selects what type of output the linker should generate. This is
4124554Sbinkertn@umich.edu        # necessary for incremental lto to work, but is also broken in
4134554Sbinkertn@umich.edu        # current versions of gcc. It may not be necessary in future
4144554Sbinkertn@umich.edu        # versions. We add it here since it might be, and as a reminder that
4154554Sbinkertn@umich.edu        # it exists. It's excluded if lto is being forced.
4164554Sbinkertn@umich.edu        #
4174781Snate@binkert.org        # https://gcc.gnu.org/gcc-6/changes.html
4184554Sbinkertn@umich.edu        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
4194554Sbinkertn@umich.edu        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
4202667Sstever@eecs.umich.edu        if not GetOption('force_lto'):
4214554Sbinkertn@umich.edu            main.Append(PSHLINKFLAGS='-flinker-output=rel')
4224554Sbinkertn@umich.edu            main.Append(PLINKFLAGS='-flinker-output=rel')
4234554Sbinkertn@umich.edu
4244554Sbinkertn@umich.edu    # gcc from version 4.8 and above generates "rep; ret" instructions
4252667Sstever@eecs.umich.edu    # to avoid performance penalties on certain AMD chips. Older
4264554Sbinkertn@umich.edu    # assemblers detect this as an error, "Error: expecting string
4272667Sstever@eecs.umich.edu    # instruction after `rep'"
4284554Sbinkertn@umich.edu    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
4294554Sbinkertn@umich.edu                                  '-o', '/dev/null'],
4302667Sstever@eecs.umich.edu                                 exception=False).split()
4315522Snate@binkert.org
4325522Snate@binkert.org    # version strings may contain extra distro-specific
4335522Snate@binkert.org    # qualifiers, so play it safe and keep only what comes before
4345522Snate@binkert.org    # the first hyphen
4355522Snate@binkert.org    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
4365522Snate@binkert.org
4375522Snate@binkert.org    if not as_version or compareVersions(as_version, "2.23") < 0:
4385522Snate@binkert.org        print(termcap.Yellow + termcap.Bold +
4395522Snate@binkert.org            'Warning: This combination of gcc and binutils have' +
4405522Snate@binkert.org            ' known incompatibilities.\n' +
4415522Snate@binkert.org            '         If you encounter build problems, please update ' +
4425522Snate@binkert.org            'binutils to 2.23.' +
4435522Snate@binkert.org            termcap.Normal)
4445522Snate@binkert.org
4455522Snate@binkert.org    # Make sure we warn if the user has requested to compile with the
4465522Snate@binkert.org    # Undefined Benahvior Sanitizer and this version of gcc does not
4475522Snate@binkert.org    # support it.
4485522Snate@binkert.org    if GetOption('with_ubsan') and \
4495522Snate@binkert.org            compareVersions(gcc_version, '4.9') < 0:
4505522Snate@binkert.org        print(termcap.Yellow + termcap.Bold +
4515522Snate@binkert.org            'Warning: UBSan is only supported using gcc 4.9 and later.' +
4525522Snate@binkert.org            termcap.Normal)
4535522Snate@binkert.org
4545522Snate@binkert.org    disable_lto = GetOption('no_lto')
4555522Snate@binkert.org    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
4565522Snate@binkert.org            not GetOption('force_lto'):
4572638Sstever@eecs.umich.edu        print(termcap.Yellow + termcap.Bold +
4582638Sstever@eecs.umich.edu            'Warning: Your compiler doesn\'t support incremental linking' +
4592638Sstever@eecs.umich.edu            ' and lto at the same time, so lto is being disabled. To force' +
4603716Sstever@eecs.umich.edu            ' lto on anyway, use the --force-lto option. That will disable' +
4615522Snate@binkert.org            ' partial linking.' +
4625522Snate@binkert.org            termcap.Normal)
4635522Snate@binkert.org        disable_lto = True
4645522Snate@binkert.org
4655522Snate@binkert.org    # Add the appropriate Link-Time Optimization (LTO) flags
4665522Snate@binkert.org    # unless LTO is explicitly turned off. Note that these flags
4671858SN/A    # are only used by the fast target.
4685227Ssaidi@eecs.umich.edu    if not disable_lto:
4695227Ssaidi@eecs.umich.edu        # Pass the LTO flag when compiling to produce GIMPLE
4705227Ssaidi@eecs.umich.edu        # output, we merely create the flags here and only append
4715227Ssaidi@eecs.umich.edu        # them later
4725227Ssaidi@eecs.umich.edu        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4735227Ssaidi@eecs.umich.edu
4745227Ssaidi@eecs.umich.edu        # Use the same amount of jobs for LTO as we are running
4755227Ssaidi@eecs.umich.edu        # scons with
4765227Ssaidi@eecs.umich.edu        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4775227Ssaidi@eecs.umich.edu
4785227Ssaidi@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4795227Ssaidi@eecs.umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4805227Ssaidi@eecs.umich.edu
4815227Ssaidi@eecs.umich.edu    # The address sanitizer is available for gcc >= 4.8
4825227Ssaidi@eecs.umich.edu    if GetOption('with_asan'):
4835204Sstever@gmail.com        if GetOption('with_ubsan') and \
4845204Sstever@gmail.com                compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4855204Sstever@gmail.com            main.Append(CCFLAGS=['-fsanitize=address,undefined',
4865204Sstever@gmail.com                                 '-fno-omit-frame-pointer'],
4875204Sstever@gmail.com                       LINKFLAGS='-fsanitize=address,undefined')
4885204Sstever@gmail.com        else:
4895204Sstever@gmail.com            main.Append(CCFLAGS=['-fsanitize=address',
4905204Sstever@gmail.com                                 '-fno-omit-frame-pointer'],
4915204Sstever@gmail.com                       LINKFLAGS='-fsanitize=address')
4925204Sstever@gmail.com    # Only gcc >= 4.9 supports UBSan, so check both the version
4935204Sstever@gmail.com    # and the command-line option before adding the compiler and
4945204Sstever@gmail.com    # linker flags.
4955204Sstever@gmail.com    elif GetOption('with_ubsan') and \
4965204Sstever@gmail.com            compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4975204Sstever@gmail.com        main.Append(CCFLAGS='-fsanitize=undefined')
4985204Sstever@gmail.com        main.Append(LINKFLAGS='-fsanitize=undefined')
4995204Sstever@gmail.com
5005204Sstever@gmail.comelif main['CLANG']:
5015204Sstever@gmail.com    # Check for a supported version of clang, >= 3.1 is needed to
5023118Sstever@eecs.umich.edu    # support similar features as gcc 4.8. See
5033118Sstever@eecs.umich.edu    # http://clang.llvm.org/cxx_status.html for details
5043118Sstever@eecs.umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
5053118Sstever@eecs.umich.edu    clang_version_match = clang_version_re.search(CXX_version)
5063118Sstever@eecs.umich.edu    if (clang_version_match):
5073118Sstever@eecs.umich.edu        clang_version = clang_version_match.groups()[0]
5083118Sstever@eecs.umich.edu        if compareVersions(clang_version, "3.1") < 0:
5093118Sstever@eecs.umich.edu            print('Error: clang version 3.1 or newer required.')
5103118Sstever@eecs.umich.edu            print('       Installed version:', clang_version)
5113118Sstever@eecs.umich.edu            Exit(1)
5123118Sstever@eecs.umich.edu    else:
5133716Sstever@eecs.umich.edu        print('Error: Unable to determine clang version.')
5143118Sstever@eecs.umich.edu        Exit(1)
5153118Sstever@eecs.umich.edu
5163118Sstever@eecs.umich.edu    # clang has a few additional warnings that we disable, extraneous
5173118Sstever@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
5183118Sstever@eecs.umich.edu    # finally self assignments are allowed as the generated CPU code
5193118Sstever@eecs.umich.edu    # is relying on this
5203118Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-parentheses',
5213118Sstever@eecs.umich.edu                         '-Wno-self-assign',
5223118Sstever@eecs.umich.edu                         # Some versions of libstdc++ (4.8?) seem to
5233716Sstever@eecs.umich.edu                         # use struct hash and class hash
5243118Sstever@eecs.umich.edu                         # interchangeably.
5253118Sstever@eecs.umich.edu                         '-Wno-mismatched-tags',
5263118Sstever@eecs.umich.edu                         ])
5273118Sstever@eecs.umich.edu
5283118Sstever@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5293118Sstever@eecs.umich.edu
5303118Sstever@eecs.umich.edu    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5313118Sstever@eecs.umich.edu    # opposed to libstdc++, as the later is dated.
5323118Sstever@eecs.umich.edu    if sys.platform == "darwin":
5333118Sstever@eecs.umich.edu        main.Append(CXXFLAGS=['-stdlib=libc++'])
5343483Ssaidi@eecs.umich.edu        main.Append(LIBS=['c++'])
5353494Ssaidi@eecs.umich.edu
5363494Ssaidi@eecs.umich.edu    # On FreeBSD we need libthr.
5373483Ssaidi@eecs.umich.edu    if sys.platform.startswith('freebsd'):
5383483Ssaidi@eecs.umich.edu        main.Append(LIBS=['thr'])
5393483Ssaidi@eecs.umich.edu
5403053Sstever@eecs.umich.edu    # We require clang >= 3.1, so there is no need to check any
5413053Sstever@eecs.umich.edu    # versions here.
5423918Ssaidi@eecs.umich.edu    if GetOption('with_ubsan'):
5433053Sstever@eecs.umich.edu        if GetOption('with_asan'):
5443053Sstever@eecs.umich.edu            env.Append(CCFLAGS=['-fsanitize=address,undefined',
5453053Sstever@eecs.umich.edu                                '-fno-omit-frame-pointer'],
5463053Sstever@eecs.umich.edu                       LINKFLAGS='-fsanitize=address,undefined')
5473053Sstever@eecs.umich.edu        else:
5481858SN/A            env.Append(CCFLAGS='-fsanitize=undefined',
5491858SN/A                       LINKFLAGS='-fsanitize=undefined')
5501858SN/A
5511858SN/A    elif GetOption('with_asan'):
5521858SN/A        env.Append(CCFLAGS=['-fsanitize=address',
5531858SN/A                            '-fno-omit-frame-pointer'],
5541859SN/A                   LINKFLAGS='-fsanitize=address')
5551858SN/A
5561858SN/Aelse:
5571858SN/A    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
5581859SN/A    print("Don't know what compiler options to use for your compiler.")
5591859SN/A    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
5601862SN/A    print(termcap.Yellow + '       version:' + termcap.Normal, end=' ')
5613053Sstever@eecs.umich.edu    if not CXX_version:
5623053Sstever@eecs.umich.edu        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
5633053Sstever@eecs.umich.edu              termcap.Normal)
5643053Sstever@eecs.umich.edu    else:
5651859SN/A        print(CXX_version.replace('\n', '<nl>'))
5661859SN/A    print("       If you're trying to use a compiler other than GCC")
5671859SN/A    print("       or clang, there appears to be something wrong with your")
5681859SN/A    print("       environment.")
5691859SN/A    print("       ")
5701859SN/A    print("       If you are trying to use a compiler other than those listed")
5711859SN/A    print("       above you will need to ease fix SConstruct and ")
5721859SN/A    print("       src/SConscript to support that compiler.")
5731862SN/A    Exit(1)
5741859SN/A
5751859SN/A# Set up common yacc/bison flags (needed for Ruby)
5761859SN/Amain['YACCFLAGS'] = '-d'
5771858SN/Amain['YACCHXXFILESUFFIX'] = '.hh'
5781858SN/A
5792139SN/A# Do this after we save setting back, or else we'll tack on an
5804202Sbinkertn@umich.edu# extra 'qdo' every time we run scons.
5814202Sbinkertn@umich.eduif main['BATCH']:
5822139SN/A    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5832155SN/A    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5844202Sbinkertn@umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5854202Sbinkertn@umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5864202Sbinkertn@umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5872155SN/A
5881869SN/Aif sys.platform == 'cygwin':
5891869SN/A    # cygwin has some header file issues...
5901869SN/A    main.Append(CCFLAGS=["-Wno-uninitialized"])
5911869SN/A
5924202Sbinkertn@umich.edu# Check for the protobuf compiler
5934202Sbinkertn@umich.eduprotoc_version = readCommand([main['PROTOC'], '--version'],
5944202Sbinkertn@umich.edu                             exception='').split()
5954202Sbinkertn@umich.edu
5964202Sbinkertn@umich.edu# First two words should be "libprotoc x.y.z"
5974202Sbinkertn@umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
5984202Sbinkertn@umich.edu    print(termcap.Yellow + termcap.Bold +
5994202Sbinkertn@umich.edu        'Warning: Protocol buffer compiler (protoc) not found.\n' +
6005742Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' +
6015742Snate@binkert.org        termcap.Normal)
6025341Sstever@gmail.com    main['PROTOC'] = False
6035342Sstever@gmail.comelse:
6045342Sstever@gmail.com    # Based on the availability of the compress stream wrappers,
6054202Sbinkertn@umich.edu    # require 2.1.0
6064202Sbinkertn@umich.edu    min_protoc_version = '2.1.0'
6074202Sbinkertn@umich.edu    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6084202Sbinkertn@umich.edu        print(termcap.Yellow + termcap.Bold +
6094202Sbinkertn@umich.edu            'Warning: protoc version', min_protoc_version,
6101869SN/A            'or newer required.\n' +
6114202Sbinkertn@umich.edu            '         Installed version:', protoc_version[1],
6121869SN/A            termcap.Normal)
6132508SN/A        main['PROTOC'] = False
6142508SN/A    else:
6152508SN/A        # Attempt to determine the appropriate include path and
6162508SN/A        # library path using pkg-config, that means we also need to
6174202Sbinkertn@umich.edu        # check for pkg-config. Note that it is possible to use
6181869SN/A        # protobuf without the involvement of pkg-config. Later on we
6195385Sstever@gmail.com        # check go a library config check and at that point the test
6205385Sstever@gmail.com        # will fail if libprotobuf cannot be found.
6215385Sstever@gmail.com        if readCommand(['pkg-config', '--version'], exception=''):
6225385Sstever@gmail.com            try:
6231869SN/A                # Attempt to establish what linking flags to add for protobuf
6241869SN/A                # using pkg-config
6251869SN/A                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6261869SN/A            except:
6271869SN/A                print(termcap.Yellow + termcap.Bold +
6281965SN/A                    'Warning: pkg-config could not get protobuf flags.' +
6291965SN/A                    termcap.Normal)
6301965SN/A
6311869SN/A
6321869SN/A# Check for 'timeout' from GNU coreutils. If present, regressions will
6332733Sktlim@umich.edu# be run with a time limit. We require version 8.13 since we rely on
6341869SN/A# support for the '--foreground' option.
6351858SN/Aif sys.platform.startswith('freebsd'):
6361869SN/A    timeout_lines = readCommand(['gtimeout', '--version'],
6371869SN/A                                exception='').splitlines()
6381869SN/Aelse:
6391858SN/A    timeout_lines = readCommand(['timeout', '--version'],
6402761Sstever@eecs.umich.edu                                exception='').splitlines()
6411869SN/A# Get the first line and tokenize it
6425385Sstever@gmail.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
6435385Sstever@gmail.commain['TIMEOUT'] =  timeout_version and \
6445522Snate@binkert.org    compareVersions(timeout_version[-1], '8.13') >= 0
6451869SN/A
6461869SN/A# Add a custom Check function to test for structure members.
6471869SN/Adef CheckMember(context, include, decl, member, include_quotes="<>"):
6481869SN/A    context.Message("Checking for member %s in %s..." %
6491869SN/A                    (member, decl))
6501869SN/A    text = """
6511858SN/A#include %(header)s
652955SN/Aint main(){
653955SN/A  %(decl)s test;
6541869SN/A  (void)test.%(member)s;
6551869SN/A  return 0;
6561869SN/A};
6571869SN/A""" % { "header" : include_quotes[0] + include + include_quotes[1],
6581869SN/A        "decl" : decl,
6591869SN/A        "member" : member,
6601869SN/A        }
6611869SN/A
6621869SN/A    ret = context.TryCompile(text, extension=".cc")
6631869SN/A    context.Result(ret)
6641869SN/A    return ret
6651869SN/A
6661869SN/A# Platform-specific configuration.  Note again that we assume that all
6671869SN/A# builds under a given build root run on the same host platform.
6681869SN/Aconf = Configure(main,
6691869SN/A                 conf_dir = joinpath(build_root, '.scons_config'),
6701869SN/A                 log_file = joinpath(build_root, 'scons_config.log'),
6711869SN/A                 custom_tests = {
6721869SN/A        'CheckMember' : CheckMember,
6731869SN/A        })
6741869SN/A
6751869SN/A# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6761869SN/Atry:
6771869SN/A    import platform
6781869SN/A    uname = platform.uname()
6791869SN/A    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6801869SN/A        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6811869SN/A            main.Append(CCFLAGS=['-arch', 'x86_64'])
6821869SN/A            main.Append(CFLAGS=['-arch', 'x86_64'])
6833716Sstever@eecs.umich.edu            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6843356Sbinkertn@umich.edu            main.Append(ASFLAGS=['-arch', 'x86_64'])
6853356Sbinkertn@umich.eduexcept:
6863356Sbinkertn@umich.edu    pass
6873356Sbinkertn@umich.edu
6883356Sbinkertn@umich.edu# Recent versions of scons substitute a "Null" object for Configure()
6893356Sbinkertn@umich.edu# when configuration isn't necessary, e.g., if the "--help" option is
6904781Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
6911869SN/A# breaking all our configuration checks.  We replace it with our own
6921869SN/A# more optimistic null object that returns True instead.
6931869SN/Aif not conf:
6941869SN/A    def NullCheck(*args, **kwargs):
6951869SN/A        return True
6961869SN/A
6971869SN/A    class NullConf:
6982655Sstever@eecs.umich.edu        def __init__(self, env):
6992655Sstever@eecs.umich.edu            self.env = env
7002655Sstever@eecs.umich.edu        def Finish(self):
7012655Sstever@eecs.umich.edu            return self.env
7022655Sstever@eecs.umich.edu        def __getattr__(self, mname):
7032655Sstever@eecs.umich.edu            return NullCheck
7042655Sstever@eecs.umich.edu
7052655Sstever@eecs.umich.edu    conf = NullConf(main)
7062655Sstever@eecs.umich.edu
7072655Sstever@eecs.umich.edu# Cache build files in the supplied directory.
7082655Sstever@eecs.umich.eduif main['M5_BUILD_CACHE']:
7092655Sstever@eecs.umich.edu    print('Using build cache located at', main['M5_BUILD_CACHE'])
7102655Sstever@eecs.umich.edu    CacheDir(main['M5_BUILD_CACHE'])
7112655Sstever@eecs.umich.edu
7122655Sstever@eecs.umich.edumain['USE_PYTHON'] = not GetOption('without_python')
7132655Sstever@eecs.umich.eduif main['USE_PYTHON']:
7142655Sstever@eecs.umich.edu    # Find Python include and library directories for embedding the
7152655Sstever@eecs.umich.edu    # interpreter. We rely on python-config to resolve the appropriate
7162655Sstever@eecs.umich.edu    # includes and linker flags. ParseConfig does not seem to understand
7172655Sstever@eecs.umich.edu    # the more exotic linker flags such as -Xlinker and -export-dynamic so
7182655Sstever@eecs.umich.edu    # we add them explicitly below. If you want to link in an alternate
7192655Sstever@eecs.umich.edu    # version of python, see above for instructions on how to invoke
7202655Sstever@eecs.umich.edu    # scons with the appropriate PATH set.
7212655Sstever@eecs.umich.edu    #
7222655Sstever@eecs.umich.edu    # First we check if python2-config exists, else we use python-config
7232655Sstever@eecs.umich.edu    python_config = readCommand(['which', 'python2-config'],
7242638Sstever@eecs.umich.edu                                exception='').strip()
7252638Sstever@eecs.umich.edu    if not os.path.exists(python_config):
7263716Sstever@eecs.umich.edu        python_config = readCommand(['which', 'python-config'],
7272638Sstever@eecs.umich.edu                                    exception='').strip()
7282638Sstever@eecs.umich.edu    py_includes = readCommand([python_config, '--includes'],
7291869SN/A                              exception='').split()
7301869SN/A    # Strip the -I from the include folders before adding them to the
7313546Sgblack@eecs.umich.edu    # CPPPATH
7323546Sgblack@eecs.umich.edu    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
7333546Sgblack@eecs.umich.edu
7343546Sgblack@eecs.umich.edu    # Read the linker flags and split them into libraries and other link
7354202Sbinkertn@umich.edu    # flags. The libraries are added later through the call the CheckLib.
7363546Sgblack@eecs.umich.edu    py_ld_flags = readCommand([python_config, '--ldflags'],
7373546Sgblack@eecs.umich.edu        exception='').split()
7383546Sgblack@eecs.umich.edu    py_libs = []
7393546Sgblack@eecs.umich.edu    for lib in py_ld_flags:
7403546Sgblack@eecs.umich.edu         if not lib.startswith('-l'):
7414781Snate@binkert.org             main.Append(LINKFLAGS=[lib])
7424781Snate@binkert.org         else:
7434781Snate@binkert.org             lib = lib[2:]
7444781Snate@binkert.org             if lib not in py_libs:
7454781Snate@binkert.org                 py_libs.append(lib)
7464781Snate@binkert.org
7474781Snate@binkert.org    # verify that this stuff works
7484781Snate@binkert.org    if not conf.CheckHeader('Python.h', '<>'):
7494781Snate@binkert.org        print("Error: can't find Python.h header in", py_includes)
7504781Snate@binkert.org        print("Install Python headers (package python-dev on " +
7514781Snate@binkert.org              "Ubuntu and RedHat)")
7524781Snate@binkert.org        Exit(1)
7533546Sgblack@eecs.umich.edu
7543546Sgblack@eecs.umich.edu    for lib in py_libs:
7553546Sgblack@eecs.umich.edu        if not conf.CheckLib(lib):
7564781Snate@binkert.org            print("Error: can't find library %s required by python" % lib)
7573546Sgblack@eecs.umich.edu            Exit(1)
7583546Sgblack@eecs.umich.edu
7593546Sgblack@eecs.umich.edu# On Solaris you need to use libsocket for socket ops
7603546Sgblack@eecs.umich.eduif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7613546Sgblack@eecs.umich.edu   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7623546Sgblack@eecs.umich.edu       print("Can't find library with socket calls (e.g. accept())")
7633546Sgblack@eecs.umich.edu       Exit(1)
7643546Sgblack@eecs.umich.edu
7653546Sgblack@eecs.umich.edu# Check for zlib.  If the check passes, libz will be automatically
7663546Sgblack@eecs.umich.edu# added to the LIBS environment variable.
7674202Sbinkertn@umich.eduif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
7683546Sgblack@eecs.umich.edu    print('Error: did not find needed zlib compression library '
7693546Sgblack@eecs.umich.edu          'and/or zlib.h header file.')
7703546Sgblack@eecs.umich.edu    print('       Please install zlib and try again.')
771955SN/A    Exit(1)
772955SN/A
773955SN/A# If we have the protobuf compiler, also make sure we have the
774955SN/A# development libraries. If the check passes, libprotobuf will be
7751858SN/A# automatically added to the LIBS environment variable. After
7761858SN/A# this, we can use the HAVE_PROTOBUF flag to determine if we have
7771858SN/A# got both protoc and libprotobuf available.
7782632Sstever@eecs.umich.edumain['HAVE_PROTOBUF'] = main['PROTOC'] and \
7792632Sstever@eecs.umich.edu    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
7805343Sstever@gmail.com                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
7815343Sstever@gmail.com
7825343Sstever@gmail.com# If we have the compiler but not the library, print another warning.
7834773Snate@binkert.orgif main['PROTOC'] and not main['HAVE_PROTOBUF']:
7844773Snate@binkert.org    print(termcap.Yellow + termcap.Bold +
7852632Sstever@eecs.umich.edu        'Warning: did not find protocol buffer library and/or headers.\n' +
7862632Sstever@eecs.umich.edu    '       Please install libprotobuf-dev for tracing support.' +
7872632Sstever@eecs.umich.edu    termcap.Normal)
7882023SN/A
7892632Sstever@eecs.umich.edu# Check for librt.
7902632Sstever@eecs.umich.eduhave_posix_clock = \
7912632Sstever@eecs.umich.edu    conf.CheckLibWithHeader(None, 'time.h', 'C',
7922632Sstever@eecs.umich.edu                            'clock_nanosleep(0,0,NULL,NULL);') or \
7932632Sstever@eecs.umich.edu    conf.CheckLibWithHeader('rt', 'time.h', 'C',
7943716Sstever@eecs.umich.edu                            'clock_nanosleep(0,0,NULL,NULL);')
7955342Sstever@gmail.com
7962632Sstever@eecs.umich.eduhave_posix_timers = \
7972632Sstever@eecs.umich.edu    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
7982632Sstever@eecs.umich.edu                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
7992632Sstever@eecs.umich.edu
8002023SN/Aif not GetOption('without_tcmalloc'):
8012632Sstever@eecs.umich.edu    if conf.CheckLib('tcmalloc'):
8022632Sstever@eecs.umich.edu        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
8035342Sstever@gmail.com    elif conf.CheckLib('tcmalloc_minimal'):
8041889SN/A        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
8052632Sstever@eecs.umich.edu    else:
8062632Sstever@eecs.umich.edu        print(termcap.Yellow + termcap.Bold +
8072632Sstever@eecs.umich.edu              "You can get a 12% performance improvement by "
8082632Sstever@eecs.umich.edu              "installing tcmalloc (libgoogle-perftools-dev package "
8093716Sstever@eecs.umich.edu              "on Ubuntu or RedHat)." + termcap.Normal)
8103716Sstever@eecs.umich.edu
8115342Sstever@gmail.com
8122632Sstever@eecs.umich.edu# Detect back trace implementations. The last implementation in the
8132632Sstever@eecs.umich.edu# list will be used by default.
8142632Sstever@eecs.umich.edubacktrace_impls = [ "none" ]
8152632Sstever@eecs.umich.edu
8162632Sstever@eecs.umich.edubacktrace_checker = 'char temp;' + \
8172632Sstever@eecs.umich.edu    ' backtrace_symbols_fd((void*)&temp, 0, 0);'
8182632Sstever@eecs.umich.eduif conf.CheckLibWithHeader(None, 'execinfo.h', 'C', backtrace_checker):
8191888SN/A    backtrace_impls.append("glibc")
8201888SN/Aelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
8211869SN/A                             backtrace_checker):
8221869SN/A    # NetBSD and FreeBSD need libexecinfo.
8231858SN/A    backtrace_impls.append("glibc")
8245341Sstever@gmail.com    main.Append(LIBS=['execinfo'])
8252598SN/A
8262598SN/Aif backtrace_impls[-1] == "none":
8272598SN/A    default_backtrace_impl = "none"
8282598SN/A    print(termcap.Yellow + termcap.Bold +
8291858SN/A        "No suitable back trace implementation found." +
8301858SN/A        termcap.Normal)
8311858SN/A
8321858SN/Aif not have_posix_clock:
8331858SN/A    print("Can't find library for POSIX clocks.")
8341858SN/A
8351858SN/A# Check for <fenv.h> (C99 FP environment control)
8361858SN/Ahave_fenv = conf.CheckHeader('fenv.h', '<>')
8371858SN/Aif not have_fenv:
8381871SN/A    print("Warning: Header file <fenv.h> not found.")
8391858SN/A    print("         This host has no IEEE FP rounding mode control.")
8401858SN/A
8411858SN/A# Check for <png.h> (libpng library needed if wanting to dump
8421858SN/A# frame buffer image in png format)
8431858SN/Ahave_png = conf.CheckHeader('png.h', '<>')
8441858SN/Aif not have_png:
8451858SN/A    print("Warning: Header file <png.h> not found.")
8461858SN/A    print("         This host has no libpng library.")
8471858SN/A    print("         Disabling support for PNG framebuffers.")
8481858SN/A
8491858SN/A# Check if we should enable KVM-based hardware virtualization. The API
8501859SN/A# we rely on exists since version 2.6.36 of the kernel, but somehow
8511859SN/A# the KVM_API_VERSION does not reflect the change. We test for one of
8521869SN/A# the types as a fall back.
8531888SN/Ahave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
8542632Sstever@eecs.umich.eduif not have_kvm:
8551869SN/A    print("Info: Compatible header file <linux/kvm.h> not found, "
8561965SN/A          "disabling KVM support.")
8571965SN/A
8581965SN/A# Check if the TUN/TAP driver is available.
8592761Sstever@eecs.umich.eduhave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
8601869SN/Aif not have_tuntap:
8611869SN/A    print("Info: Compatible header file <linux/if_tun.h> not found.")
8622632Sstever@eecs.umich.edu
8632667Sstever@eecs.umich.edu# x86 needs support for xsave. We test for the structure here since we
8641869SN/A# won't be able to run new tests by the time we know which ISA we're
8651869SN/A# targeting.
8662929Sktlim@umich.eduhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
8672929Sktlim@umich.edu                                    '#include <linux/kvm.h>') != 0
8683716Sstever@eecs.umich.edu
8692929Sktlim@umich.edu# Check if the requested target ISA is compatible with the host
870955SN/Adef is_isa_kvm_compatible(isa):
8712598SN/A    try:
8722598SN/A        import platform
8733546Sgblack@eecs.umich.edu        host_isa = platform.machine()
874955SN/A    except:
875955SN/A        print("Warning: Failed to determine host ISA.")
876955SN/A        return False
8771530SN/A
878955SN/A    if not have_posix_timers:
879955SN/A        print("Warning: Can not enable KVM, host seems to lack support "
880955SN/A              "for POSIX timers")
881        return False
882
883    if isa == "arm":
884        return host_isa in ( "armv7l", "aarch64" )
885    elif isa == "x86":
886        if host_isa != "x86_64":
887            return False
888
889        if not have_kvm_xsave:
890            print("KVM on x86 requires xsave support in kernel headers.")
891            return False
892
893        return True
894    else:
895        return False
896
897
898# Check if the exclude_host attribute is available. We want this to
899# get accurate instruction counts in KVM.
900main['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
901    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
902
903
904######################################################################
905#
906# Finish the configuration
907#
908main = conf.Finish()
909
910######################################################################
911#
912# Collect all non-global variables
913#
914
915# Define the universe of supported ISAs
916all_isa_list = [ ]
917all_gpu_isa_list = [ ]
918Export('all_isa_list')
919Export('all_gpu_isa_list')
920
921class CpuModel(object):
922    '''The CpuModel class encapsulates everything the ISA parser needs to
923    know about a particular CPU model.'''
924
925    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
926    dict = {}
927
928    # Constructor.  Automatically adds models to CpuModel.dict.
929    def __init__(self, name, default=False):
930        self.name = name           # name of model
931
932        # This cpu is enabled by default
933        self.default = default
934
935        # Add self to dict
936        if name in CpuModel.dict:
937            raise AttributeError, "CpuModel '%s' already registered" % name
938        CpuModel.dict[name] = self
939
940Export('CpuModel')
941
942# Sticky variables get saved in the variables file so they persist from
943# one invocation to the next (unless overridden, in which case the new
944# value becomes sticky).
945sticky_vars = Variables(args=ARGUMENTS)
946Export('sticky_vars')
947
948# Sticky variables that should be exported
949export_vars = []
950Export('export_vars')
951
952# For Ruby
953all_protocols = []
954Export('all_protocols')
955protocol_dirs = []
956Export('protocol_dirs')
957slicc_includes = []
958Export('slicc_includes')
959
960# Walk the tree and execute all SConsopts scripts that wil add to the
961# above variables
962if GetOption('verbose'):
963    print("Reading SConsopts")
964for bdir in [ base_dir ] + extras_dir_list:
965    if not isdir(bdir):
966        print("Error: directory '%s' does not exist" % bdir)
967        Exit(1)
968    for root, dirs, files in os.walk(bdir):
969        if 'SConsopts' in files:
970            if GetOption('verbose'):
971                print("Reading", joinpath(root, 'SConsopts'))
972            SConscript(joinpath(root, 'SConsopts'))
973
974all_isa_list.sort()
975all_gpu_isa_list.sort()
976
977sticky_vars.AddVariables(
978    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
979    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
980    ListVariable('CPU_MODELS', 'CPU models',
981                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
982                 sorted(CpuModel.dict.keys())),
983    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
984                 False),
985    BoolVariable('SS_COMPATIBLE_FP',
986                 'Make floating-point results compatible with SimpleScalar',
987                 False),
988    BoolVariable('USE_SSE2',
989                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
990                 False),
991    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
992    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
993    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
994    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
995                 False),
996    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
997                 have_kvm),
998    BoolVariable('USE_TUNTAP',
999                 'Enable using a tap device to bridge to the host network',
1000                 have_tuntap),
1001    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
1002    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1003                  all_protocols),
1004    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
1005                 backtrace_impls[-1], backtrace_impls)
1006    )
1007
1008# These variables get exported to #defines in config/*.hh (see src/SConscript).
1009export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
1010                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
1011                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST',
1012                'USE_PNG']
1013
1014###################################################
1015#
1016# Define a SCons builder for configuration flag headers.
1017#
1018###################################################
1019
1020# This function generates a config header file that #defines the
1021# variable symbol to the current variable setting (0 or 1).  The source
1022# operands are the name of the variable and a Value node containing the
1023# value of the variable.
1024def build_config_file(target, source, env):
1025    (variable, value) = [s.get_contents() for s in source]
1026    f = file(str(target[0]), 'w')
1027    print('#define', variable, value, file=f)
1028    f.close()
1029    return None
1030
1031# Combine the two functions into a scons Action object.
1032config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1033
1034# The emitter munges the source & target node lists to reflect what
1035# we're really doing.
1036def config_emitter(target, source, env):
1037    # extract variable name from Builder arg
1038    variable = str(target[0])
1039    # True target is config header file
1040    target = joinpath('config', variable.lower() + '.hh')
1041    val = env[variable]
1042    if isinstance(val, bool):
1043        # Force value to 0/1
1044        val = int(val)
1045    elif isinstance(val, str):
1046        val = '"' + val + '"'
1047
1048    # Sources are variable name & value (packaged in SCons Value nodes)
1049    return ([target], [Value(variable), Value(val)])
1050
1051config_builder = Builder(emitter = config_emitter, action = config_action)
1052
1053main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1054
1055###################################################
1056#
1057# Builders for static and shared partially linked object files.
1058#
1059###################################################
1060
1061partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1062                                 src_suffix='$OBJSUFFIX',
1063                                 src_builder=['StaticObject', 'Object'],
1064                                 LINKFLAGS='$PLINKFLAGS',
1065                                 LIBS='')
1066
1067def partial_shared_emitter(target, source, env):
1068    for tgt in target:
1069        tgt.attributes.shared = 1
1070    return (target, source)
1071partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1072                                 emitter=partial_shared_emitter,
1073                                 src_suffix='$SHOBJSUFFIX',
1074                                 src_builder='SharedObject',
1075                                 SHLINKFLAGS='$PSHLINKFLAGS',
1076                                 LIBS='')
1077
1078main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1079                         'PartialStatic' : partial_static_builder })
1080
1081# builds in ext are shared across all configs in the build root.
1082ext_dir = abspath(joinpath(str(main.root), 'ext'))
1083ext_build_dirs = []
1084for root, dirs, files in os.walk(ext_dir):
1085    if 'SConscript' in files:
1086        build_dir = os.path.relpath(root, ext_dir)
1087        ext_build_dirs.append(build_dir)
1088        main.SConscript(joinpath(root, 'SConscript'),
1089                        variant_dir=joinpath(build_root, build_dir))
1090
1091main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1092
1093###################################################
1094#
1095# This builder and wrapper method are used to set up a directory with
1096# switching headers. Those are headers which are in a generic location and
1097# that include more specific headers from a directory chosen at build time
1098# based on the current build settings.
1099#
1100###################################################
1101
1102def build_switching_header(target, source, env):
1103    path = str(target[0])
1104    subdir = str(source[0])
1105    dp, fp = os.path.split(path)
1106    dp = os.path.relpath(os.path.realpath(dp),
1107                         os.path.realpath(env['BUILDDIR']))
1108    with open(path, 'w') as hdr:
1109        print('#include "%s/%s/%s"' % (dp, subdir, fp), file=hdr)
1110
1111switching_header_action = MakeAction(build_switching_header,
1112                                     Transform('GENERATE'))
1113
1114switching_header_builder = Builder(action=switching_header_action,
1115                                   source_factory=Value,
1116                                   single_source=True)
1117
1118main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1119
1120def switching_headers(self, headers, source):
1121    for header in headers:
1122        self.SwitchingHeader(header, source)
1123
1124main.AddMethod(switching_headers, 'SwitchingHeaders')
1125
1126###################################################
1127#
1128# Define build environments for selected configurations.
1129#
1130###################################################
1131
1132for variant_path in variant_paths:
1133    if not GetOption('silent'):
1134        print("Building in", variant_path)
1135
1136    # Make a copy of the build-root environment to use for this config.
1137    env = main.Clone()
1138    env['BUILDDIR'] = variant_path
1139
1140    # variant_dir is the tail component of build path, and is used to
1141    # determine the build parameters (e.g., 'ALPHA_SE')
1142    (build_root, variant_dir) = splitpath(variant_path)
1143
1144    # Set env variables according to the build directory config.
1145    sticky_vars.files = []
1146    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1147    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1148    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1149    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1150    if isfile(current_vars_file):
1151        sticky_vars.files.append(current_vars_file)
1152        if not GetOption('silent'):
1153            print("Using saved variables file %s" % current_vars_file)
1154    elif variant_dir in ext_build_dirs:
1155        # Things in ext are built without a variant directory.
1156        continue
1157    else:
1158        # Build dir-specific variables file doesn't exist.
1159
1160        # Make sure the directory is there so we can create it later
1161        opt_dir = dirname(current_vars_file)
1162        if not isdir(opt_dir):
1163            mkdir(opt_dir)
1164
1165        # Get default build variables from source tree.  Variables are
1166        # normally determined by name of $VARIANT_DIR, but can be
1167        # overridden by '--default=' arg on command line.
1168        default = GetOption('default')
1169        opts_dir = joinpath(main.root.abspath, 'build_opts')
1170        if default:
1171            default_vars_files = [joinpath(build_root, 'variables', default),
1172                                  joinpath(opts_dir, default)]
1173        else:
1174            default_vars_files = [joinpath(opts_dir, variant_dir)]
1175        existing_files = filter(isfile, default_vars_files)
1176        if existing_files:
1177            default_vars_file = existing_files[0]
1178            sticky_vars.files.append(default_vars_file)
1179            print("Variables file %s not found,\n  using defaults in %s"
1180                  % (current_vars_file, default_vars_file))
1181        else:
1182            print("Error: cannot find variables file %s or "
1183                  "default file(s) %s"
1184                  % (current_vars_file, ' or '.join(default_vars_files)))
1185            Exit(1)
1186
1187    # Apply current variable settings to env
1188    sticky_vars.Update(env)
1189
1190    help_texts["local_vars"] += \
1191        "Build variables for %s:\n" % variant_dir \
1192                 + sticky_vars.GenerateHelpText(env)
1193
1194    # Process variable settings.
1195
1196    if not have_fenv and env['USE_FENV']:
1197        print("Warning: <fenv.h> not available; "
1198              "forcing USE_FENV to False in", variant_dir + ".")
1199        env['USE_FENV'] = False
1200
1201    if not env['USE_FENV']:
1202        print("Warning: No IEEE FP rounding mode control in",
1203              variant_dir + ".")
1204        print("         FP results may deviate slightly from other platforms.")
1205
1206    if not have_png and env['USE_PNG']:
1207        print("Warning: <png.h> not available; "
1208              "forcing USE_PNG to False in", variant_dir + ".")
1209        env['USE_PNG'] = False
1210
1211    if env['USE_PNG']:
1212        env.Append(LIBS=['png'])
1213
1214    if env['EFENCE']:
1215        env.Append(LIBS=['efence'])
1216
1217    if env['USE_KVM']:
1218        if not have_kvm:
1219            print("Warning: Can not enable KVM, host seems to "
1220                  "lack KVM support")
1221            env['USE_KVM'] = False
1222        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1223            print("Info: KVM support disabled due to unsupported host and "
1224                  "target ISA combination")
1225            env['USE_KVM'] = False
1226
1227    if env['USE_TUNTAP']:
1228        if not have_tuntap:
1229            print("Warning: Can't connect EtherTap with a tap device.")
1230            env['USE_TUNTAP'] = False
1231
1232    if env['BUILD_GPU']:
1233        env.Append(CPPDEFINES=['BUILD_GPU'])
1234
1235    # Warn about missing optional functionality
1236    if env['USE_KVM']:
1237        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1238            print("Warning: perf_event headers lack support for the "
1239                  "exclude_host attribute. KVM instruction counts will "
1240                  "be inaccurate.")
1241
1242    # Save sticky variable settings back to current variables file
1243    sticky_vars.Save(current_vars_file, env)
1244
1245    if env['USE_SSE2']:
1246        env.Append(CCFLAGS=['-msse2'])
1247
1248    # The src/SConscript file sets up the build rules in 'env' according
1249    # to the configured variables.  It returns a list of environments,
1250    # one for each variant build (debug, opt, etc.)
1251    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1252
1253# base help text
1254Help('''
1255Usage: scons [scons options] [build variables] [target(s)]
1256
1257Extra scons options:
1258%(options)s
1259
1260Global build variables:
1261%(global_vars)s
1262
1263%(local_vars)s
1264''' % help_texts)
1265