SConstruct revision 12485
1955SN/A# -*- mode:python -*-
2955SN/A
35871Snate@binkert.org# Copyright (c) 2013, 2015-2017 ARM Limited
41762SN/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
28955SN/A# contributors may be used to endorse or promote products derived from
292665Ssaidi@eecs.umich.edu# this software without specific prior written permission.
302665Ssaidi@eecs.umich.edu#
315863Snate@binkert.org# 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
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
392632Sstever@eecs.umich.edu# 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
41955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422632Sstever@eecs.umich.edu#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442761Sstever@eecs.umich.edu#          Nathan Binkert
452632Sstever@eecs.umich.edu
462632Sstever@eecs.umich.edu###################################################
472632Sstever@eecs.umich.edu#
482761Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492761Sstever@eecs.umich.edu#
502761Sstever@eecs.umich.edu# 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>'
522632Sstever@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
562761Sstever@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:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
632632Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
642632Sstever@eecs.umich.edu#   % 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
685863Snate@binkert.org#   in a directory outside of the source tree.  The '-C' option tells
695863Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
705863Snate@binkert.org#   file.
715863Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
725863Snate@binkert.org#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
735863Snate@binkert.org#
745863Snate@binkert.org# You can use 'scons -H' to print scons options.  If you're in this
755863Snate@binkert.org# 'gem5' directory (or use -u or -C to tell scons where to find this
765863Snate@binkert.org# file), you can use 'scons -h' to print all the gem5-specific build
775863Snate@binkert.org# options as well.
785863Snate@binkert.org#
795863Snate@binkert.org###################################################
805863Snate@binkert.org
815863Snate@binkert.org# Global Python includes
825863Snate@binkert.orgimport itertools
835863Snate@binkert.orgimport os
845863Snate@binkert.orgimport re
855863Snate@binkert.orgimport shutil
865863Snate@binkert.orgimport subprocess
875863Snate@binkert.orgimport sys
885863Snate@binkert.org
895863Snate@binkert.orgfrom os import mkdir, environ
905863Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
915863Snate@binkert.orgfrom os.path import exists,  isdir, isfile
925863Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
935863Snate@binkert.org
945863Snate@binkert.org# SCons includes
955863Snate@binkert.orgimport SCons
965863Snate@binkert.orgimport SCons.Node
975863Snate@binkert.org
985863Snate@binkert.orgfrom m5.util import compareVersions, readCommand
99955SN/A
1005396Ssaidi@eecs.umich.eduhelp_texts = {
1015863Snate@binkert.org    "options" : "",
1025863Snate@binkert.org    "global_vars" : "",
1034202Sbinkertn@umich.edu    "local_vars" : ""
1045863Snate@binkert.org}
1055863Snate@binkert.org
1065863Snate@binkert.orgExport("help_texts")
1075863Snate@binkert.org
108955SN/A
1095273Sstever@gmail.com# There's a bug in scons in that (1) by default, the help texts from
1105871Snate@binkert.org# AddOption() are supposed to be displayed when you type 'scons -h'
1115273Sstever@gmail.com# and (2) you can override the help displayed by 'scons -h' using the
1125871Snate@binkert.org# Help() function, but these two features are incompatible: once
1135863Snate@binkert.org# you've overridden the help text using Help(), there's no way to get
1145863Snate@binkert.org# at the help texts from AddOptions.  See:
1155863Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1165871Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1175872Snate@binkert.org# This hack lets us extract the help text from AddOptions and
1185872Snate@binkert.org# re-inject it via Help().  Ideally someday this bug will be fixed and
1195872Snate@binkert.org# we can just use AddOption directly.
1205871Snate@binkert.orgdef AddLocalOption(*args, **kwargs):
1215871Snate@binkert.org    col_width = 30
1225871Snate@binkert.org
1235871Snate@binkert.org    help = "  " + ", ".join(args)
1245871Snate@binkert.org    if "help" in kwargs:
1255871Snate@binkert.org        length = len(help)
1265871Snate@binkert.org        if length >= col_width:
1275871Snate@binkert.org            help += "\n" + " " * col_width
1285871Snate@binkert.org        else:
1295871Snate@binkert.org            help += " " * (col_width - length)
1305871Snate@binkert.org        help += kwargs["help"]
1315871Snate@binkert.org    help_texts["options"] += help + "\n"
1325871Snate@binkert.org
1335871Snate@binkert.org    AddOption(*args, **kwargs)
1345863Snate@binkert.org
1355227Ssaidi@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1365396Ssaidi@eecs.umich.edu               help="Add color to abbreviated scons output")
1375396Ssaidi@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1385396Ssaidi@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1395396Ssaidi@eecs.umich.eduAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1405396Ssaidi@eecs.umich.edu               action='store_true',
1415396Ssaidi@eecs.umich.edu               help="Build with support for C++-based configuration")
1425396Ssaidi@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1435396Ssaidi@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1445588Ssaidi@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1455396Ssaidi@eecs.umich.edu               help='Disable style checking hooks')
1465396Ssaidi@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1475396Ssaidi@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1485396Ssaidi@eecs.umich.eduAddLocalOption('--force-lto', dest='force_lto', action='store_true',
1495396Ssaidi@eecs.umich.edu               help='Use Link-Time Optimization instead of partial linking' +
1505396Ssaidi@eecs.umich.edu                    ' when the compiler doesn\'t support using them together.')
1515396Ssaidi@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1525396Ssaidi@eecs.umich.edu               help='Update test reference outputs')
1535396Ssaidi@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1545396Ssaidi@eecs.umich.edu               help='Print full tool command lines')
1555396Ssaidi@eecs.umich.eduAddLocalOption('--without-python', dest='without_python',
1565396Ssaidi@eecs.umich.edu               action='store_true',
1575396Ssaidi@eecs.umich.edu               help='Build without Python configuration support')
1585396Ssaidi@eecs.umich.eduAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1595871Snate@binkert.org               action='store_true',
1605871Snate@binkert.org               help='Disable linking against tcmalloc')
1615871Snate@binkert.orgAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1625871Snate@binkert.org               help='Build with Undefined Behavior Sanitizer if available')
1635871Snate@binkert.orgAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1646003Snate@binkert.org               help='Build with Address Sanitizer if available')
1656003Snate@binkert.org
166955SN/Aif GetOption('no_lto') and GetOption('force_lto'):
1675871Snate@binkert.org    print '--no-lto and --force-lto are mutually exclusive'
1685871Snate@binkert.org    Exit(1)
1695871Snate@binkert.org
1705871Snate@binkert.org########################################################################
171955SN/A#
1725871Snate@binkert.org# Set up the main build environment.
1735871Snate@binkert.org#
1745871Snate@binkert.org########################################################################
1751533SN/A
1765871Snate@binkert.orgmain = Environment()
1775871Snate@binkert.org
1785863Snate@binkert.orgfrom gem5_scons import Transform
1795871Snate@binkert.orgfrom gem5_scons.util import get_termcap
1805871Snate@binkert.orgtermcap = get_termcap()
1815871Snate@binkert.org
1825871Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
1835871Snate@binkert.org
1845863Snate@binkert.org# Check that we have a C/C++ compiler
1855871Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1865863Snate@binkert.org    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
1875871Snate@binkert.org    Exit(1)
1884678Snate@binkert.org
1894678Snate@binkert.org###################################################
1904678Snate@binkert.org#
1914678Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
1924678Snate@binkert.org# the target(s).
1934678Snate@binkert.org#
1944678Snate@binkert.org###################################################
1954678Snate@binkert.org
1964678Snate@binkert.org# Find default configuration & binary.
1974678Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
1984678Snate@binkert.org
1994678Snate@binkert.org# helper function: find last occurrence of element in list
2005871Snate@binkert.orgdef rfind(l, elt, offs = -1):
2014678Snate@binkert.org    for i in range(len(l)+offs, 0, -1):
2025871Snate@binkert.org        if l[i] == elt:
2035871Snate@binkert.org            return i
2045871Snate@binkert.org    raise ValueError, "element not found"
2055871Snate@binkert.org
2065871Snate@binkert.org# Take a list of paths (or SCons Nodes) and return a list with all
2075871Snate@binkert.org# paths made absolute and ~-expanded.  Paths will be interpreted
2085871Snate@binkert.org# relative to the launch directory unless a different root is provided
2095871Snate@binkert.orgdef makePathListAbsolute(path_list, root=GetLaunchDir()):
2105871Snate@binkert.org    return [abspath(joinpath(root, expanduser(str(p))))
2115871Snate@binkert.org            for p in path_list]
2125871Snate@binkert.org
2135871Snate@binkert.org# Each target must have 'build' in the interior of the path; the
2145871Snate@binkert.org# directory below this will determine the build parameters.  For
2155990Ssaidi@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2165871Snate@binkert.org# recognize that ALPHA_SE specifies the configuration because it
2175871Snate@binkert.org# follow 'build' in the build path.
2185871Snate@binkert.org
2194678Snate@binkert.org# The funky assignment to "[:]" is needed to replace the list contents
2205871Snate@binkert.org# in place rather than reassign the symbol to a new list, which
2215871Snate@binkert.org# doesn't work (obviously!).
2225871Snate@binkert.orgBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2235871Snate@binkert.org
2245871Snate@binkert.org# Generate a list of the unique build roots and configs that the
2255871Snate@binkert.org# collected targets reference.
2265871Snate@binkert.orgvariant_paths = []
2275871Snate@binkert.orgbuild_root = None
2285871Snate@binkert.orgfor t in BUILD_TARGETS:
2295871Snate@binkert.org    path_dirs = t.split('/')
2304678Snate@binkert.org    try:
2315871Snate@binkert.org        build_top = rfind(path_dirs, 'build', -2)
2324678Snate@binkert.org    except:
2335871Snate@binkert.org        print "Error: no non-leaf 'build' dir found on target path", t
2345871Snate@binkert.org        Exit(1)
2355871Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2365871Snate@binkert.org    if not build_root:
2375871Snate@binkert.org        build_root = this_build_root
2385871Snate@binkert.org    else:
2395871Snate@binkert.org        if this_build_root != build_root:
2405871Snate@binkert.org            print "Error: build targets not under same build root\n"\
2415871Snate@binkert.org                  "  %s\n  %s" % (build_root, this_build_root)
2425990Ssaidi@eecs.umich.edu            Exit(1)
2435863Snate@binkert.org    variant_path = joinpath('/',*path_dirs[:build_top+2])
244955SN/A    if variant_path not in variant_paths:
245955SN/A        variant_paths.append(variant_path)
2462632Sstever@eecs.umich.edu
2472632Sstever@eecs.umich.edu# Make sure build_root exists (might not if this is the first build there)
248955SN/Aif not isdir(build_root):
249955SN/A    mkdir(build_root)
250955SN/Amain['BUILDROOT'] = build_root
251955SN/A
2525863Snate@binkert.orgExport('main')
253955SN/A
2542632Sstever@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
2552632Sstever@eecs.umich.edu
2562632Sstever@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
2572632Sstever@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
2582632Sstever@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
2592632Sstever@eecs.umich.edu# (soft) links work better.
2602632Sstever@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
2612632Sstever@eecs.umich.edu
2622632Sstever@eecs.umich.edu#
2632632Sstever@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
2642632Sstever@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
2652632Sstever@eecs.umich.edu#
2662632Sstever@eecs.umich.edu
2673718Sstever@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
2683718Sstever@eecs.umich.edu
2693718Sstever@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2703718Sstever@eecs.umich.edu
2713718Sstever@eecs.umich.eduglobal_vars.AddVariables(
2725863Snate@binkert.org    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2735863Snate@binkert.org    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2743718Sstever@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2753718Sstever@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
2765863Snate@binkert.org    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2775863Snate@binkert.org    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2783718Sstever@eecs.umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
2793718Sstever@eecs.umich.edu    )
2802634Sstever@eecs.umich.edu
2812634Sstever@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
2825863Snate@binkert.orgglobal_vars.Update(main)
2832638Sstever@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
2842632Sstever@eecs.umich.edu
2852632Sstever@eecs.umich.edu# Save sticky variable settings back to current variables file
2862632Sstever@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
2872632Sstever@eecs.umich.edu
2882632Sstever@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
2892632Sstever@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
2901858SN/Abase_dir = main.srcdir.abspath
2913716Sstever@eecs.umich.eduif main['EXTRAS']:
2922638Sstever@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
2932638Sstever@eecs.umich.eduelse:
2942638Sstever@eecs.umich.edu    extras_dir_list = []
2952638Sstever@eecs.umich.edu
2962638Sstever@eecs.umich.eduExport('base_dir')
2972638Sstever@eecs.umich.eduExport('extras_dir_list')
2982638Sstever@eecs.umich.edu
2995863Snate@binkert.org# the ext directory should be on the #includes path
3005863Snate@binkert.orgmain.Append(CPPPATH=[Dir('ext')])
3015863Snate@binkert.org
302955SN/A# Add shared top-level headers
3035341Sstever@gmail.commain.Prepend(CPPPATH=Dir('include'))
3045341Sstever@gmail.com
3055863Snate@binkert.orgif GetOption('verbose'):
3065341Sstever@gmail.com    def MakeAction(action, string, *args, **kwargs):
3074494Ssaidi@eecs.umich.edu        return Action(action, *args, **kwargs)
3084494Ssaidi@eecs.umich.eduelse:
3095863Snate@binkert.org    MakeAction = Action
3101105SN/A    main['CCCOMSTR']        = Transform("CC")
3112667Sstever@eecs.umich.edu    main['CXXCOMSTR']       = Transform("CXX")
3122667Sstever@eecs.umich.edu    main['ASCOMSTR']        = Transform("AS")
3132667Sstever@eecs.umich.edu    main['ARCOMSTR']        = Transform("AR", 0)
3142667Sstever@eecs.umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
3152667Sstever@eecs.umich.edu    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
3162667Sstever@eecs.umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3175341Sstever@gmail.com    main['M4COMSTR']        = Transform("M4")
3185863Snate@binkert.org    main['SHCCCOMSTR']      = Transform("SHCC")
3195341Sstever@gmail.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
3205341Sstever@gmail.comExport('MakeAction')
3215341Sstever@gmail.com
3225863Snate@binkert.org# Initialize the Link-Time Optimization (LTO) flags
3235341Sstever@gmail.commain['LTO_CCFLAGS'] = []
3245341Sstever@gmail.commain['LTO_LDFLAGS'] = []
3255341Sstever@gmail.com
3265863Snate@binkert.org# According to the readme, tcmalloc works best if the compiler doesn't
3275341Sstever@gmail.com# assume that we're using the builtin malloc and friends. These flags
3285341Sstever@gmail.com# are compiler-specific, so we need to set them after we detect which
3295341Sstever@gmail.com# compiler we're using.
3305341Sstever@gmail.commain['TCMALLOC_CCFLAGS'] = []
3315341Sstever@gmail.com
3325341Sstever@gmail.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3335341Sstever@gmail.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
3345341Sstever@gmail.com
3355341Sstever@gmail.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3365341Sstever@gmail.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
3375863Snate@binkert.orgif main['GCC'] + main['CLANG'] > 1:
3385341Sstever@gmail.com    print 'Error: How can we have two at the same time?'
3395863Snate@binkert.org    Exit(1)
3405341Sstever@gmail.com
3415863Snate@binkert.org# Set up default C++ compiler flags
3425863Snate@binkert.orgif main['GCC'] or main['CLANG']:
3435863Snate@binkert.org    # As gcc and clang share many flags, do the common parts here
3445397Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
3455397Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
3465341Sstever@gmail.com    # Enable -Wall and -Wextra and then disable the few warnings that
3475341Sstever@gmail.com    # we consistently violate
3485341Sstever@gmail.com    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
3495341Sstever@gmail.com                         '-Wno-sign-compare', '-Wno-unused-parameter'])
3505341Sstever@gmail.com    # We always compile using C++11
3515341Sstever@gmail.com    main.Append(CXXFLAGS=['-std=c++11'])
3525341Sstever@gmail.com    if sys.platform.startswith('freebsd'):
3535341Sstever@gmail.com        main.Append(CCFLAGS=['-I/usr/local/include'])
3545863Snate@binkert.org        main.Append(CXXFLAGS=['-I/usr/local/include'])
3555341Sstever@gmail.com
3565341Sstever@gmail.com    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3575863Snate@binkert.org    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
3585341Sstever@gmail.com    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3595863Snate@binkert.org    shared_partial_flags = ['-r', '-nostdlib']
3605863Snate@binkert.org    main.Append(PSHLINKFLAGS=shared_partial_flags)
3615341Sstever@gmail.com    main.Append(PLINKFLAGS=shared_partial_flags)
3625863Snate@binkert.org
3635863Snate@binkert.org    # Treat warnings as errors but white list some warnings that we
3645341Sstever@gmail.com    # want to allow (e.g., deprecation warnings).
3655863Snate@binkert.org    main.Append(CCFLAGS=['-Werror',
3665341Sstever@gmail.com                         '-Wno-error=deprecated-declarations',
3675871Snate@binkert.org                         '-Wno-error=deprecated',
3685341Sstever@gmail.com                        ])
3695742Snate@binkert.orgelse:
3705742Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
3715742Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
3725341Sstever@gmail.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
3735742Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
3745742Snate@binkert.org    if not CXX_version:
3755341Sstever@gmail.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
3766017Snate@binkert.org               termcap.Normal
3776017Snate@binkert.org    else:
3786017Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
3792632Sstever@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
3806016Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
3815871Snate@binkert.org    print "       environment."
3825871Snate@binkert.org    print "       "
3835871Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
3845871Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
3855871Snate@binkert.org    print "       src/SConscript to support that compiler."
3865871Snate@binkert.org    Exit(1)
3875871Snate@binkert.org
3883942Ssaidi@eecs.umich.eduif main['GCC']:
3893940Ssaidi@eecs.umich.edu    # Check for a supported version of gcc. >= 4.8 is chosen for its
3903918Ssaidi@eecs.umich.edu    # level of c++11 support. See
3913918Ssaidi@eecs.umich.edu    # http://gcc.gnu.org/projects/cxx0x.html for details.
3921858SN/A    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
3933918Ssaidi@eecs.umich.edu    if compareVersions(gcc_version, "4.8") < 0:
3943918Ssaidi@eecs.umich.edu        print 'Error: gcc version 4.8 or newer required.'
3953918Ssaidi@eecs.umich.edu        print '       Installed version:', gcc_version
3963918Ssaidi@eecs.umich.edu        Exit(1)
3975571Snate@binkert.org
3983940Ssaidi@eecs.umich.edu    main['GCC_VERSION'] = gcc_version
3993940Ssaidi@eecs.umich.edu
4003918Ssaidi@eecs.umich.edu    if compareVersions(gcc_version, '4.9') >= 0:
4013918Ssaidi@eecs.umich.edu        # Incremental linking with LTO is currently broken in gcc versions
4023918Ssaidi@eecs.umich.edu        # 4.9 and above. A version where everything works completely hasn't
4033918Ssaidi@eecs.umich.edu        # yet been identified.
4043918Ssaidi@eecs.umich.edu        #
4053918Ssaidi@eecs.umich.edu        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
4065871Snate@binkert.org        main['BROKEN_INCREMENTAL_LTO'] = True
4073918Ssaidi@eecs.umich.edu    if compareVersions(gcc_version, '6.0') >= 0:
4083918Ssaidi@eecs.umich.edu        # gcc versions 6.0 and greater accept an -flinker-output flag which
4093940Ssaidi@eecs.umich.edu        # selects what type of output the linker should generate. This is
4103918Ssaidi@eecs.umich.edu        # necessary for incremental lto to work, but is also broken in
4113918Ssaidi@eecs.umich.edu        # current versions of gcc. It may not be necessary in future
4125397Ssaidi@eecs.umich.edu        # versions. We add it here since it might be, and as a reminder that
4135397Ssaidi@eecs.umich.edu        # it exists. It's excluded if lto is being forced.
4145397Ssaidi@eecs.umich.edu        #
4155708Ssaidi@eecs.umich.edu        # https://gcc.gnu.org/gcc-6/changes.html
4165708Ssaidi@eecs.umich.edu        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
4175708Ssaidi@eecs.umich.edu        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
4185708Ssaidi@eecs.umich.edu        if not GetOption('force_lto'):
4195708Ssaidi@eecs.umich.edu            main.Append(PSHLINKFLAGS='-flinker-output=rel')
4205397Ssaidi@eecs.umich.edu            main.Append(PLINKFLAGS='-flinker-output=rel')
4211851SN/A
4221851SN/A    # gcc from version 4.8 and above generates "rep; ret" instructions
4231858SN/A    # to avoid performance penalties on certain AMD chips. Older
424955SN/A    # assemblers detect this as an error, "Error: expecting string
4253053Sstever@eecs.umich.edu    # instruction after `rep'"
4263053Sstever@eecs.umich.edu    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
4273053Sstever@eecs.umich.edu                                  '-o', '/dev/null'],
4283053Sstever@eecs.umich.edu                                 exception=False).split()
4293053Sstever@eecs.umich.edu
4303053Sstever@eecs.umich.edu    # version strings may contain extra distro-specific
4313053Sstever@eecs.umich.edu    # qualifiers, so play it safe and keep only what comes before
4325871Snate@binkert.org    # the first hyphen
4333053Sstever@eecs.umich.edu    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
4344742Sstever@eecs.umich.edu
4354742Sstever@eecs.umich.edu    if not as_version or compareVersions(as_version, "2.23") < 0:
4363053Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
4373053Sstever@eecs.umich.edu            'Warning: This combination of gcc and binutils have' + \
4383053Sstever@eecs.umich.edu            ' known incompatibilities.\n' + \
4393053Sstever@eecs.umich.edu            '         If you encounter build problems, please update ' + \
4403053Sstever@eecs.umich.edu            'binutils to 2.23.' + \
4413053Sstever@eecs.umich.edu            termcap.Normal
4423053Sstever@eecs.umich.edu
4433053Sstever@eecs.umich.edu    # Make sure we warn if the user has requested to compile with the
4443053Sstever@eecs.umich.edu    # Undefined Benahvior Sanitizer and this version of gcc does not
4452667Sstever@eecs.umich.edu    # support it.
4464554Sbinkertn@umich.edu    if GetOption('with_ubsan') and \
4474554Sbinkertn@umich.edu            compareVersions(gcc_version, '4.9') < 0:
4482667Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
4494554Sbinkertn@umich.edu            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
4504554Sbinkertn@umich.edu            termcap.Normal
4514554Sbinkertn@umich.edu
4524554Sbinkertn@umich.edu    disable_lto = GetOption('no_lto')
4534554Sbinkertn@umich.edu    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
4544554Sbinkertn@umich.edu            not GetOption('force_lto'):
4554554Sbinkertn@umich.edu        print termcap.Yellow + termcap.Bold + \
4564781Snate@binkert.org            'Warning: Your compiler doesn\'t support incremental linking' + \
4574554Sbinkertn@umich.edu            ' and lto at the same time, so lto is being disabled. To force' + \
4584554Sbinkertn@umich.edu            ' lto on anyway, use the --force-lto option. That will disable' + \
4592667Sstever@eecs.umich.edu            ' partial linking.' + \
4604554Sbinkertn@umich.edu            termcap.Normal
4614554Sbinkertn@umich.edu        disable_lto = True
4624554Sbinkertn@umich.edu
4634554Sbinkertn@umich.edu    # Add the appropriate Link-Time Optimization (LTO) flags
4642667Sstever@eecs.umich.edu    # unless LTO is explicitly turned off. Note that these flags
4654554Sbinkertn@umich.edu    # are only used by the fast target.
4662667Sstever@eecs.umich.edu    if not disable_lto:
4674554Sbinkertn@umich.edu        # Pass the LTO flag when compiling to produce GIMPLE
4684554Sbinkertn@umich.edu        # output, we merely create the flags here and only append
4692667Sstever@eecs.umich.edu        # them later
4705522Snate@binkert.org        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4715522Snate@binkert.org
4725522Snate@binkert.org        # Use the same amount of jobs for LTO as we are running
4735522Snate@binkert.org        # scons with
4745522Snate@binkert.org        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4755522Snate@binkert.org
4765522Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4775522Snate@binkert.org                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4785522Snate@binkert.org
4795522Snate@binkert.org    # add option to check for undeclared overrides
4805522Snate@binkert.org    if compareVersions(gcc_version, "5.0") > 0:
4815522Snate@binkert.org        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
4825522Snate@binkert.org
4835522Snate@binkert.org    # The address sanitizer is available for gcc >= 4.8
4845522Snate@binkert.org    if GetOption('with_asan'):
4855522Snate@binkert.org        if GetOption('with_ubsan') and \
4865522Snate@binkert.org                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
4875522Snate@binkert.org            env.Append(CCFLAGS=['-fsanitize=address,undefined',
4885522Snate@binkert.org                                '-fno-omit-frame-pointer'],
4895522Snate@binkert.org                       LINKFLAGS='-fsanitize=address,undefined')
4905522Snate@binkert.org        else:
4915522Snate@binkert.org            env.Append(CCFLAGS=['-fsanitize=address',
4925522Snate@binkert.org                                '-fno-omit-frame-pointer'],
4935522Snate@binkert.org                       LINKFLAGS='-fsanitize=address')
4945522Snate@binkert.org    # Only gcc >= 4.9 supports UBSan, so check both the version
4955522Snate@binkert.org    # and the command-line option before adding the compiler and
4962638Sstever@eecs.umich.edu    # linker flags.
4972638Sstever@eecs.umich.edu    elif GetOption('with_ubsan') and \
4982638Sstever@eecs.umich.edu            compareVersions(env['GCC_VERSION'], '4.9') >= 0:
4993716Sstever@eecs.umich.edu        env.Append(CCFLAGS='-fsanitize=undefined')
5005522Snate@binkert.org        env.Append(LINKFLAGS='-fsanitize=undefined')
5015522Snate@binkert.org
5025522Snate@binkert.orgelif main['CLANG']:
5035522Snate@binkert.org    # Check for a supported version of clang, >= 3.1 is needed to
5045522Snate@binkert.org    # support similar features as gcc 4.8. See
5055522Snate@binkert.org    # http://clang.llvm.org/cxx_status.html for details
5061858SN/A    clang_version_re = re.compile(".* version (\d+\.\d+)")
5075227Ssaidi@eecs.umich.edu    clang_version_match = clang_version_re.search(CXX_version)
5085227Ssaidi@eecs.umich.edu    if (clang_version_match):
5095227Ssaidi@eecs.umich.edu        clang_version = clang_version_match.groups()[0]
5105227Ssaidi@eecs.umich.edu        if compareVersions(clang_version, "3.1") < 0:
5115227Ssaidi@eecs.umich.edu            print 'Error: clang version 3.1 or newer required.'
5125863Snate@binkert.org            print '       Installed version:', clang_version
5135227Ssaidi@eecs.umich.edu            Exit(1)
5145227Ssaidi@eecs.umich.edu    else:
5155227Ssaidi@eecs.umich.edu        print 'Error: Unable to determine clang version.'
5165227Ssaidi@eecs.umich.edu        Exit(1)
5175227Ssaidi@eecs.umich.edu
5185227Ssaidi@eecs.umich.edu    # clang has a few additional warnings that we disable, extraneous
5195227Ssaidi@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
5205204Sstever@gmail.com    # finally self assignments are allowed as the generated CPU code
5215204Sstever@gmail.com    # is relying on this
5225204Sstever@gmail.com    main.Append(CCFLAGS=['-Wno-parentheses',
5235204Sstever@gmail.com                         '-Wno-self-assign',
5245204Sstever@gmail.com                         # Some versions of libstdc++ (4.8?) seem to
5255204Sstever@gmail.com                         # use struct hash and class hash
5265204Sstever@gmail.com                         # interchangeably.
5275204Sstever@gmail.com                         '-Wno-mismatched-tags',
5285204Sstever@gmail.com                         ])
5295204Sstever@gmail.com
5305204Sstever@gmail.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5315204Sstever@gmail.com
5325204Sstever@gmail.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5335204Sstever@gmail.com    # opposed to libstdc++, as the later is dated.
5345204Sstever@gmail.com    if sys.platform == "darwin":
5355204Sstever@gmail.com        main.Append(CXXFLAGS=['-stdlib=libc++'])
5365204Sstever@gmail.com        main.Append(LIBS=['c++'])
5375204Sstever@gmail.com
5385204Sstever@gmail.com    # On FreeBSD we need libthr.
5393118Sstever@eecs.umich.edu    if sys.platform.startswith('freebsd'):
5403118Sstever@eecs.umich.edu        main.Append(LIBS=['thr'])
5413118Sstever@eecs.umich.edu
5423118Sstever@eecs.umich.edu    # We require clang >= 3.1, so there is no need to check any
5433118Sstever@eecs.umich.edu    # versions here.
5445863Snate@binkert.org    if GetOption('with_ubsan'):
5453118Sstever@eecs.umich.edu        if GetOption('with_asan'):
5465863Snate@binkert.org            env.Append(CCFLAGS=['-fsanitize=address,undefined',
5473118Sstever@eecs.umich.edu                                '-fno-omit-frame-pointer'],
5485863Snate@binkert.org                       LINKFLAGS='-fsanitize=address,undefined')
5495863Snate@binkert.org        else:
5505863Snate@binkert.org            env.Append(CCFLAGS='-fsanitize=undefined',
5515863Snate@binkert.org                       LINKFLAGS='-fsanitize=undefined')
5525863Snate@binkert.org
5535863Snate@binkert.org    elif GetOption('with_asan'):
5545863Snate@binkert.org        env.Append(CCFLAGS=['-fsanitize=address',
5555863Snate@binkert.org                            '-fno-omit-frame-pointer'],
5566003Snate@binkert.org                   LINKFLAGS='-fsanitize=address')
5575863Snate@binkert.org
5585863Snate@binkert.orgelse:
5595863Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5605863Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
5615863Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5625863Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
5635863Snate@binkert.org    if not CXX_version:
5645863Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5655863Snate@binkert.org               termcap.Normal
5665863Snate@binkert.org    else:
5675863Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
5685863Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
5695863Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
5705863Snate@binkert.org    print "       environment."
5715863Snate@binkert.org    print "       "
5723118Sstever@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
5735863Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
5743118Sstever@eecs.umich.edu    print "       src/SConscript to support that compiler."
5753118Sstever@eecs.umich.edu    Exit(1)
5765863Snate@binkert.org
5775863Snate@binkert.org# Set up common yacc/bison flags (needed for Ruby)
5785863Snate@binkert.orgmain['YACCFLAGS'] = '-d'
5795863Snate@binkert.orgmain['YACCHXXFILESUFFIX'] = '.hh'
5805863Snate@binkert.org
5815863Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
5823118Sstever@eecs.umich.edu# extra 'qdo' every time we run scons.
5833483Ssaidi@eecs.umich.eduif main['BATCH']:
5843494Ssaidi@eecs.umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5853494Ssaidi@eecs.umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5863483Ssaidi@eecs.umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5873483Ssaidi@eecs.umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5883483Ssaidi@eecs.umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5893053Sstever@eecs.umich.edu
5903053Sstever@eecs.umich.eduif sys.platform == 'cygwin':
5913918Ssaidi@eecs.umich.edu    # cygwin has some header file issues...
5923053Sstever@eecs.umich.edu    main.Append(CCFLAGS=["-Wno-uninitialized"])
5933053Sstever@eecs.umich.edu
5943053Sstever@eecs.umich.edu# Check for the protobuf compiler
5953053Sstever@eecs.umich.eduprotoc_version = readCommand([main['PROTOC'], '--version'],
5963053Sstever@eecs.umich.edu                             exception='').split()
5971858SN/A
5981858SN/A# First two words should be "libprotoc x.y.z"
5991858SN/Aif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6001858SN/A    print termcap.Yellow + termcap.Bold + \
6011858SN/A        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6021858SN/A        '         Please install protobuf-compiler for tracing support.' + \
6035863Snate@binkert.org        termcap.Normal
6045863Snate@binkert.org    main['PROTOC'] = False
6051859SN/Aelse:
6065863Snate@binkert.org    # Based on the availability of the compress stream wrappers,
6071858SN/A    # require 2.1.0
6085863Snate@binkert.org    min_protoc_version = '2.1.0'
6091858SN/A    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6101859SN/A        print termcap.Yellow + termcap.Bold + \
6111859SN/A            'Warning: protoc version', min_protoc_version, \
6125863Snate@binkert.org            'or newer required.\n' + \
6133053Sstever@eecs.umich.edu            '         Installed version:', protoc_version[1], \
6143053Sstever@eecs.umich.edu            termcap.Normal
6153053Sstever@eecs.umich.edu        main['PROTOC'] = False
6163053Sstever@eecs.umich.edu    else:
6171859SN/A        # Attempt to determine the appropriate include path and
6181859SN/A        # library path using pkg-config, that means we also need to
6191859SN/A        # check for pkg-config. Note that it is possible to use
6201859SN/A        # protobuf without the involvement of pkg-config. Later on we
6211859SN/A        # check go a library config check and at that point the test
6221859SN/A        # will fail if libprotobuf cannot be found.
6231859SN/A        if readCommand(['pkg-config', '--version'], exception=''):
6241859SN/A            try:
6251862SN/A                # Attempt to establish what linking flags to add for protobuf
6261859SN/A                # using pkg-config
6271859SN/A                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6281859SN/A            except:
6295863Snate@binkert.org                print termcap.Yellow + termcap.Bold + \
6305863Snate@binkert.org                    'Warning: pkg-config could not get protobuf flags.' + \
6315863Snate@binkert.org                    termcap.Normal
6325863Snate@binkert.org
6331858SN/A
6341858SN/A# Check for 'timeout' from GNU coreutils. If present, regressions will
6355863Snate@binkert.org# be run with a time limit. We require version 8.13 since we rely on
6365863Snate@binkert.org# support for the '--foreground' option.
6375863Snate@binkert.orgif sys.platform.startswith('freebsd'):
6385863Snate@binkert.org    timeout_lines = readCommand(['gtimeout', '--version'],
6395863Snate@binkert.org                                exception='').splitlines()
6405871Snate@binkert.orgelse:
6415871Snate@binkert.org    timeout_lines = readCommand(['timeout', '--version'],
6422139SN/A                                exception='').splitlines()
6434202Sbinkertn@umich.edu# Get the first line and tokenize it
6444202Sbinkertn@umich.edutimeout_version = timeout_lines[0].split() if timeout_lines else []
6452139SN/Amain['TIMEOUT'] =  timeout_version and \
6462155SN/A    compareVersions(timeout_version[-1], '8.13') >= 0
6474202Sbinkertn@umich.edu
6484202Sbinkertn@umich.edu# Add a custom Check function to test for structure members.
6494202Sbinkertn@umich.edudef CheckMember(context, include, decl, member, include_quotes="<>"):
6502155SN/A    context.Message("Checking for member %s in %s..." %
6515863Snate@binkert.org                    (member, decl))
6521869SN/A    text = """
6531869SN/A#include %(header)s
6545863Snate@binkert.orgint main(){
6555863Snate@binkert.org  %(decl)s test;
6564202Sbinkertn@umich.edu  (void)test.%(member)s;
6575863Snate@binkert.org  return 0;
6585863Snate@binkert.org};
6595863Snate@binkert.org""" % { "header" : include_quotes[0] + include + include_quotes[1],
6604202Sbinkertn@umich.edu        "decl" : decl,
6614202Sbinkertn@umich.edu        "member" : member,
6625863Snate@binkert.org        }
6635742Snate@binkert.org
6645742Snate@binkert.org    ret = context.TryCompile(text, extension=".cc")
6655341Sstever@gmail.com    context.Result(ret)
6665342Sstever@gmail.com    return ret
6675342Sstever@gmail.com
6684202Sbinkertn@umich.edu# Platform-specific configuration.  Note again that we assume that all
6694202Sbinkertn@umich.edu# builds under a given build root run on the same host platform.
6704202Sbinkertn@umich.educonf = Configure(main,
6714202Sbinkertn@umich.edu                 conf_dir = joinpath(build_root, '.scons_config'),
6724202Sbinkertn@umich.edu                 log_file = joinpath(build_root, 'scons_config.log'),
6735863Snate@binkert.org                 custom_tests = {
6745863Snate@binkert.org        'CheckMember' : CheckMember,
6755863Snate@binkert.org        })
6765863Snate@binkert.org
6775863Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6785863Snate@binkert.orgtry:
6795863Snate@binkert.org    import platform
6805863Snate@binkert.org    uname = platform.uname()
6815863Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6825863Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6835863Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
6845863Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
6855863Snate@binkert.org            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6865863Snate@binkert.org            main.Append(ASFLAGS=['-arch', 'x86_64'])
6875863Snate@binkert.orgexcept:
6885863Snate@binkert.org    pass
6895863Snate@binkert.org
6905863Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
6915863Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
6925863Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
6935952Ssaidi@eecs.umich.edu# breaking all our configuration checks.  We replace it with our own
6941869SN/A# more optimistic null object that returns True instead.
6951858SN/Aif not conf:
6965863Snate@binkert.org    def NullCheck(*args, **kwargs):
6975863Snate@binkert.org        return True
6981869SN/A
6991858SN/A    class NullConf:
7005863Snate@binkert.org        def __init__(self, env):
7015863Snate@binkert.org            self.env = env
7025863Snate@binkert.org        def Finish(self):
7035863Snate@binkert.org            return self.env
7045952Ssaidi@eecs.umich.edu        def __getattr__(self, mname):
7051858SN/A            return NullCheck
706955SN/A
707955SN/A    conf = NullConf(main)
7081869SN/A
7091869SN/A# Cache build files in the supplied directory.
7101869SN/Aif main['M5_BUILD_CACHE']:
7111869SN/A    print 'Using build cache located at', main['M5_BUILD_CACHE']
7121869SN/A    CacheDir(main['M5_BUILD_CACHE'])
7135863Snate@binkert.org
7145863Snate@binkert.orgmain['USE_PYTHON'] = not GetOption('without_python')
7155863Snate@binkert.orgif main['USE_PYTHON']:
7161869SN/A    # Find Python include and library directories for embedding the
7175863Snate@binkert.org    # interpreter. We rely on python-config to resolve the appropriate
7181869SN/A    # includes and linker flags. ParseConfig does not seem to understand
7195863Snate@binkert.org    # the more exotic linker flags such as -Xlinker and -export-dynamic so
7201869SN/A    # we add them explicitly below. If you want to link in an alternate
7211869SN/A    # version of python, see above for instructions on how to invoke
7221869SN/A    # scons with the appropriate PATH set.
7231869SN/A    #
7241869SN/A    # First we check if python2-config exists, else we use python-config
7255863Snate@binkert.org    python_config = readCommand(['which', 'python2-config'],
7265863Snate@binkert.org                                exception='').strip()
7271869SN/A    if not os.path.exists(python_config):
7281869SN/A        python_config = readCommand(['which', 'python-config'],
7291869SN/A                                    exception='').strip()
7301869SN/A    py_includes = readCommand([python_config, '--includes'],
7311869SN/A                              exception='').split()
7321869SN/A    # Strip the -I from the include folders before adding them to the
7331869SN/A    # CPPPATH
7345863Snate@binkert.org    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
7355863Snate@binkert.org
7361869SN/A    # Read the linker flags and split them into libraries and other link
7375863Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
7385863Snate@binkert.org    py_ld_flags = readCommand([python_config, '--ldflags'],
7393356Sbinkertn@umich.edu        exception='').split()
7403356Sbinkertn@umich.edu    py_libs = []
7413356Sbinkertn@umich.edu    for lib in py_ld_flags:
7423356Sbinkertn@umich.edu         if not lib.startswith('-l'):
7433356Sbinkertn@umich.edu             main.Append(LINKFLAGS=[lib])
7444781Snate@binkert.org         else:
7455863Snate@binkert.org             lib = lib[2:]
7465863Snate@binkert.org             if lib not in py_libs:
7471869SN/A                 py_libs.append(lib)
7481869SN/A
7491869SN/A    # verify that this stuff works
7501869SN/A    if not conf.CheckHeader('Python.h', '<>'):
7511869SN/A        print "Error: can't find Python.h header in", py_includes
7522638Sstever@eecs.umich.edu        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
7532638Sstever@eecs.umich.edu        Exit(1)
7545871Snate@binkert.org
7552638Sstever@eecs.umich.edu    for lib in py_libs:
7565749Scws3k@cs.virginia.edu        if not conf.CheckLib(lib):
7575749Scws3k@cs.virginia.edu            print "Error: can't find library %s required by python" % lib
7585871Snate@binkert.org            Exit(1)
7595749Scws3k@cs.virginia.edu
7601869SN/A# On Solaris you need to use libsocket for socket ops
7611869SN/Aif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7623546Sgblack@eecs.umich.edu   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7633546Sgblack@eecs.umich.edu       print "Can't find library with socket calls (e.g. accept())"
7643546Sgblack@eecs.umich.edu       Exit(1)
7653546Sgblack@eecs.umich.edu
7664202Sbinkertn@umich.edu# Check for zlib.  If the check passes, libz will be automatically
7675863Snate@binkert.org# added to the LIBS environment variable.
7683546Sgblack@eecs.umich.eduif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
7693546Sgblack@eecs.umich.edu    print 'Error: did not find needed zlib compression library '\
7703546Sgblack@eecs.umich.edu          'and/or zlib.h header file.'
7713546Sgblack@eecs.umich.edu    print '       Please install zlib and try again.'
7724781Snate@binkert.org    Exit(1)
7735863Snate@binkert.org
7744781Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
7754781Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
7764781Snate@binkert.org# automatically added to the LIBS environment variable. After
7774781Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
7784781Snate@binkert.org# got both protoc and libprotobuf available.
7795863Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
7804781Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
7814781Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
7824781Snate@binkert.org
7834781Snate@binkert.org# If we have the compiler but not the library, print another warning.
7843546Sgblack@eecs.umich.eduif main['PROTOC'] and not main['HAVE_PROTOBUF']:
7853546Sgblack@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
7863546Sgblack@eecs.umich.edu        'Warning: did not find protocol buffer library and/or headers.\n' + \
7874781Snate@binkert.org    '       Please install libprotobuf-dev for tracing support.' + \
7883546Sgblack@eecs.umich.edu    termcap.Normal
7893546Sgblack@eecs.umich.edu
7903546Sgblack@eecs.umich.edu# Check for librt.
7913546Sgblack@eecs.umich.eduhave_posix_clock = \
7923546Sgblack@eecs.umich.edu    conf.CheckLibWithHeader(None, 'time.h', 'C',
7933546Sgblack@eecs.umich.edu                            'clock_nanosleep(0,0,NULL,NULL);') or \
7943546Sgblack@eecs.umich.edu    conf.CheckLibWithHeader('rt', 'time.h', 'C',
7953546Sgblack@eecs.umich.edu                            'clock_nanosleep(0,0,NULL,NULL);')
7963546Sgblack@eecs.umich.edu
7973546Sgblack@eecs.umich.eduhave_posix_timers = \
7984202Sbinkertn@umich.edu    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
7993546Sgblack@eecs.umich.edu                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
8003546Sgblack@eecs.umich.edu
8013546Sgblack@eecs.umich.eduif not GetOption('without_tcmalloc'):
802955SN/A    if conf.CheckLib('tcmalloc'):
803955SN/A        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
804955SN/A    elif conf.CheckLib('tcmalloc_minimal'):
805955SN/A        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
8061858SN/A    else:
8071858SN/A        print termcap.Yellow + termcap.Bold + \
8081858SN/A              "You can get a 12% performance improvement by "\
8095863Snate@binkert.org              "installing tcmalloc (libgoogle-perftools-dev package "\
8105863Snate@binkert.org              "on Ubuntu or RedHat)." + termcap.Normal
8115343Sstever@gmail.com
8125343Sstever@gmail.com
8135863Snate@binkert.org# Detect back trace implementations. The last implementation in the
8145863Snate@binkert.org# list will be used by default.
8154773Snate@binkert.orgbacktrace_impls = [ "none" ]
8165863Snate@binkert.org
8172632Sstever@eecs.umich.edubacktrace_checker = 'char temp;' + \
8185863Snate@binkert.org    ' backtrace_symbols_fd((void*)&temp, 0, 0);'
8192023SN/Aif conf.CheckLibWithHeader(None, 'execinfo.h', 'C', backtrace_checker):
8205863Snate@binkert.org    backtrace_impls.append("glibc")
8215863Snate@binkert.orgelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
8225863Snate@binkert.org                             backtrace_checker):
8235863Snate@binkert.org    # NetBSD and FreeBSD need libexecinfo.
8245863Snate@binkert.org    backtrace_impls.append("glibc")
8255863Snate@binkert.org    main.Append(LIBS=['execinfo'])
8265863Snate@binkert.org
8275863Snate@binkert.orgif backtrace_impls[-1] == "none":
8285863Snate@binkert.org    default_backtrace_impl = "none"
8292632Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
8305863Snate@binkert.org        "No suitable back trace implementation found." + \
8312023SN/A        termcap.Normal
8322632Sstever@eecs.umich.edu
8335863Snate@binkert.orgif not have_posix_clock:
8345342Sstever@gmail.com    print "Can't find library for POSIX clocks."
8355863Snate@binkert.org
8362632Sstever@eecs.umich.edu# Check for <fenv.h> (C99 FP environment control)
8375863Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
8385863Snate@binkert.orgif not have_fenv:
8392632Sstever@eecs.umich.edu    print "Warning: Header file <fenv.h> not found."
8405863Snate@binkert.org    print "         This host has no IEEE FP rounding mode control."
8415863Snate@binkert.org
8425863Snate@binkert.org# Check for <png.h> (libpng library needed if wanting to dump
8435863Snate@binkert.org# frame buffer image in png format)
8445863Snate@binkert.orghave_png = conf.CheckHeader('png.h', '<>')
8455863Snate@binkert.orgif not have_png:
8462632Sstever@eecs.umich.edu    print "Warning: Header file <png.h> not found."
8475863Snate@binkert.org    print "         This host has no libpng library."
8485863Snate@binkert.org    print "         Disabling support for PNG framebuffers."
8492632Sstever@eecs.umich.edu
8501888SN/A# Check if we should enable KVM-based hardware virtualization. The API
8515863Snate@binkert.org# we rely on exists since version 2.6.36 of the kernel, but somehow
8525863Snate@binkert.org# the KVM_API_VERSION does not reflect the change. We test for one of
8535863Snate@binkert.org# the types as a fall back.
8541858SN/Ahave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
8555863Snate@binkert.orgif not have_kvm:
8565863Snate@binkert.org    print "Info: Compatible header file <linux/kvm.h> not found, " \
8575863Snate@binkert.org        "disabling KVM support."
8585863Snate@binkert.org
8592598SN/A# Check if the TUN/TAP driver is available.
8605863Snate@binkert.orghave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
8611858SN/Aif not have_tuntap:
8621858SN/A    print "Info: Compatible header file <linux/if_tun.h> not found."
8631858SN/A
8645863Snate@binkert.org# x86 needs support for xsave. We test for the structure here since we
8651858SN/A# won't be able to run new tests by the time we know which ISA we're
8661858SN/A# targeting.
8671858SN/Ahave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
8685863Snate@binkert.org                                    '#include <linux/kvm.h>') != 0
8691871SN/A
8701858SN/A# Check if the requested target ISA is compatible with the host
8711858SN/Adef is_isa_kvm_compatible(isa):
8721858SN/A    try:
8731858SN/A        import platform
8741858SN/A        host_isa = platform.machine()
8751858SN/A    except:
8761858SN/A        print "Warning: Failed to determine host ISA."
8775863Snate@binkert.org        return False
8781858SN/A
8791858SN/A    if not have_posix_timers:
8805863Snate@binkert.org        print "Warning: Can not enable KVM, host seems to lack support " \
8811859SN/A            "for POSIX timers"
8821859SN/A        return False
8831869SN/A
8845863Snate@binkert.org    if isa == "arm":
8855863Snate@binkert.org        return host_isa in ( "armv7l", "aarch64" )
8861869SN/A    elif isa == "x86":
8871965SN/A        if host_isa != "x86_64":
8881965SN/A            return False
8891965SN/A
8902761Sstever@eecs.umich.edu        if not have_kvm_xsave:
8915863Snate@binkert.org            print "KVM on x86 requires xsave support in kernel headers."
8921869SN/A            return False
8935863Snate@binkert.org
8942667Sstever@eecs.umich.edu        return True
8951869SN/A    else:
8961869SN/A        return False
8972929Sktlim@umich.edu
8982929Sktlim@umich.edu
8995863Snate@binkert.org# Check if the exclude_host attribute is available. We want this to
9002929Sktlim@umich.edu# get accurate instruction counts in KVM.
901955SN/Amain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
9022598SN/A    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
903
904
905######################################################################
906#
907# Finish the configuration
908#
909main = conf.Finish()
910
911######################################################################
912#
913# Collect all non-global variables
914#
915
916# Define the universe of supported ISAs
917all_isa_list = [ ]
918all_gpu_isa_list = [ ]
919Export('all_isa_list')
920Export('all_gpu_isa_list')
921
922class CpuModel(object):
923    '''The CpuModel class encapsulates everything the ISA parser needs to
924    know about a particular CPU model.'''
925
926    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
927    dict = {}
928
929    # Constructor.  Automatically adds models to CpuModel.dict.
930    def __init__(self, name, default=False):
931        self.name = name           # name of model
932
933        # This cpu is enabled by default
934        self.default = default
935
936        # Add self to dict
937        if name in CpuModel.dict:
938            raise AttributeError, "CpuModel '%s' already registered" % name
939        CpuModel.dict[name] = self
940
941Export('CpuModel')
942
943# Sticky variables get saved in the variables file so they persist from
944# one invocation to the next (unless overridden, in which case the new
945# value becomes sticky).
946sticky_vars = Variables(args=ARGUMENTS)
947Export('sticky_vars')
948
949# Sticky variables that should be exported
950export_vars = []
951Export('export_vars')
952
953# For Ruby
954all_protocols = []
955Export('all_protocols')
956protocol_dirs = []
957Export('protocol_dirs')
958slicc_includes = []
959Export('slicc_includes')
960
961# Walk the tree and execute all SConsopts scripts that wil add to the
962# above variables
963if GetOption('verbose'):
964    print "Reading SConsopts"
965for bdir in [ base_dir ] + extras_dir_list:
966    if not isdir(bdir):
967        print "Error: directory '%s' does not exist" % bdir
968        Exit(1)
969    for root, dirs, files in os.walk(bdir):
970        if 'SConsopts' in files:
971            if GetOption('verbose'):
972                print "Reading", joinpath(root, 'SConsopts')
973            SConscript(joinpath(root, 'SConsopts'))
974
975all_isa_list.sort()
976all_gpu_isa_list.sort()
977
978sticky_vars.AddVariables(
979    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
980    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
981    ListVariable('CPU_MODELS', 'CPU models',
982                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
983                 sorted(CpuModel.dict.keys())),
984    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
985                 False),
986    BoolVariable('SS_COMPATIBLE_FP',
987                 'Make floating-point results compatible with SimpleScalar',
988                 False),
989    BoolVariable('USE_SSE2',
990                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
991                 False),
992    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
993    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
994    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
995    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
996                 False),
997    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
998                 have_kvm),
999    BoolVariable('USE_TUNTAP',
1000                 'Enable using a tap device to bridge to the host network',
1001                 have_tuntap),
1002    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
1003    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1004                  all_protocols),
1005    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
1006                 backtrace_impls[-1], backtrace_impls)
1007    )
1008
1009# These variables get exported to #defines in config/*.hh (see src/SConscript).
1010export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
1011                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
1012                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST',
1013                'USE_PNG']
1014
1015###################################################
1016#
1017# Define a SCons builder for configuration flag headers.
1018#
1019###################################################
1020
1021# This function generates a config header file that #defines the
1022# variable symbol to the current variable setting (0 or 1).  The source
1023# operands are the name of the variable and a Value node containing the
1024# value of the variable.
1025def build_config_file(target, source, env):
1026    (variable, value) = [s.get_contents() for s in source]
1027    f = file(str(target[0]), 'w')
1028    print >> f, '#define', variable, value
1029    f.close()
1030    return None
1031
1032# Combine the two functions into a scons Action object.
1033config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1034
1035# The emitter munges the source & target node lists to reflect what
1036# we're really doing.
1037def config_emitter(target, source, env):
1038    # extract variable name from Builder arg
1039    variable = str(target[0])
1040    # True target is config header file
1041    target = joinpath('config', variable.lower() + '.hh')
1042    val = env[variable]
1043    if isinstance(val, bool):
1044        # Force value to 0/1
1045        val = int(val)
1046    elif isinstance(val, str):
1047        val = '"' + val + '"'
1048
1049    # Sources are variable name & value (packaged in SCons Value nodes)
1050    return ([target], [Value(variable), Value(val)])
1051
1052config_builder = Builder(emitter = config_emitter, action = config_action)
1053
1054main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1055
1056###################################################
1057#
1058# Builders for static and shared partially linked object files.
1059#
1060###################################################
1061
1062partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1063                                 src_suffix='$OBJSUFFIX',
1064                                 src_builder=['StaticObject', 'Object'],
1065                                 LINKFLAGS='$PLINKFLAGS',
1066                                 LIBS='')
1067
1068def partial_shared_emitter(target, source, env):
1069    for tgt in target:
1070        tgt.attributes.shared = 1
1071    return (target, source)
1072partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1073                                 emitter=partial_shared_emitter,
1074                                 src_suffix='$SHOBJSUFFIX',
1075                                 src_builder='SharedObject',
1076                                 SHLINKFLAGS='$PSHLINKFLAGS',
1077                                 LIBS='')
1078
1079main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1080                         'PartialStatic' : partial_static_builder })
1081
1082# builds in ext are shared across all configs in the build root.
1083ext_dir = abspath(joinpath(str(main.root), 'ext'))
1084ext_build_dirs = []
1085for root, dirs, files in os.walk(ext_dir):
1086    if 'SConscript' in files:
1087        build_dir = os.path.relpath(root, ext_dir)
1088        ext_build_dirs.append(build_dir)
1089        main.SConscript(joinpath(root, 'SConscript'),
1090                        variant_dir=joinpath(build_root, build_dir))
1091
1092main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1093
1094###################################################
1095#
1096# This builder and wrapper method are used to set up a directory with
1097# switching headers. Those are headers which are in a generic location and
1098# that include more specific headers from a directory chosen at build time
1099# based on the current build settings.
1100#
1101###################################################
1102
1103def build_switching_header(target, source, env):
1104    path = str(target[0])
1105    subdir = str(source[0])
1106    dp, fp = os.path.split(path)
1107    dp = os.path.relpath(os.path.realpath(dp),
1108                         os.path.realpath(env['BUILDDIR']))
1109    with open(path, 'w') as hdr:
1110        print >>hdr, '#include "%s/%s/%s"' % (dp, subdir, fp)
1111
1112switching_header_action = MakeAction(build_switching_header,
1113                                     Transform('GENERATE'))
1114
1115switching_header_builder = Builder(action=switching_header_action,
1116                                   source_factory=Value,
1117                                   single_source=True)
1118
1119main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1120
1121def switching_headers(self, headers, source):
1122    for header in headers:
1123        self.SwitchingHeader(header, source)
1124
1125main.AddMethod(switching_headers, 'SwitchingHeaders')
1126
1127###################################################
1128#
1129# Define build environments for selected configurations.
1130#
1131###################################################
1132
1133for variant_path in variant_paths:
1134    if not GetOption('silent'):
1135        print "Building in", variant_path
1136
1137    # Make a copy of the build-root environment to use for this config.
1138    env = main.Clone()
1139    env['BUILDDIR'] = variant_path
1140
1141    # variant_dir is the tail component of build path, and is used to
1142    # determine the build parameters (e.g., 'ALPHA_SE')
1143    (build_root, variant_dir) = splitpath(variant_path)
1144
1145    # Set env variables according to the build directory config.
1146    sticky_vars.files = []
1147    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1148    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1149    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1150    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1151    if isfile(current_vars_file):
1152        sticky_vars.files.append(current_vars_file)
1153        if not GetOption('silent'):
1154            print "Using saved variables file %s" % current_vars_file
1155    elif variant_dir in ext_build_dirs:
1156        # Things in ext are built without a variant directory.
1157        continue
1158    else:
1159        # Build dir-specific variables file doesn't exist.
1160
1161        # Make sure the directory is there so we can create it later
1162        opt_dir = dirname(current_vars_file)
1163        if not isdir(opt_dir):
1164            mkdir(opt_dir)
1165
1166        # Get default build variables from source tree.  Variables are
1167        # normally determined by name of $VARIANT_DIR, but can be
1168        # overridden by '--default=' arg on command line.
1169        default = GetOption('default')
1170        opts_dir = joinpath(main.root.abspath, 'build_opts')
1171        if default:
1172            default_vars_files = [joinpath(build_root, 'variables', default),
1173                                  joinpath(opts_dir, default)]
1174        else:
1175            default_vars_files = [joinpath(opts_dir, variant_dir)]
1176        existing_files = filter(isfile, default_vars_files)
1177        if existing_files:
1178            default_vars_file = existing_files[0]
1179            sticky_vars.files.append(default_vars_file)
1180            print "Variables file %s not found,\n  using defaults in %s" \
1181                  % (current_vars_file, default_vars_file)
1182        else:
1183            print "Error: cannot find variables file %s or " \
1184                  "default file(s) %s" \
1185                  % (current_vars_file, ' or '.join(default_vars_files))
1186            Exit(1)
1187
1188    # Apply current variable settings to env
1189    sticky_vars.Update(env)
1190
1191    help_texts["local_vars"] += \
1192        "Build variables for %s:\n" % variant_dir \
1193                 + sticky_vars.GenerateHelpText(env)
1194
1195    # Process variable settings.
1196
1197    if not have_fenv and env['USE_FENV']:
1198        print "Warning: <fenv.h> not available; " \
1199              "forcing USE_FENV to False in", variant_dir + "."
1200        env['USE_FENV'] = False
1201
1202    if not env['USE_FENV']:
1203        print "Warning: No IEEE FP rounding mode control in", 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 lack KVM support"
1220            env['USE_KVM'] = False
1221        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1222            print "Info: KVM support disabled due to unsupported host and " \
1223                "target ISA combination"
1224            env['USE_KVM'] = False
1225
1226    if env['USE_TUNTAP']:
1227        if not have_tuntap:
1228            print "Warning: Can't connect EtherTap with a tap device."
1229            env['USE_TUNTAP'] = False
1230
1231    if env['BUILD_GPU']:
1232        env.Append(CPPDEFINES=['BUILD_GPU'])
1233
1234    # Warn about missing optional functionality
1235    if env['USE_KVM']:
1236        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1237            print "Warning: perf_event headers lack support for the " \
1238                "exclude_host attribute. KVM instruction counts will " \
1239                "be inaccurate."
1240
1241    # Save sticky variable settings back to current variables file
1242    sticky_vars.Save(current_vars_file, env)
1243
1244    if env['USE_SSE2']:
1245        env.Append(CCFLAGS=['-msse2'])
1246
1247    # The src/SConscript file sets up the build rules in 'env' according
1248    # to the configured variables.  It returns a list of environments,
1249    # one for each variant build (debug, opt, etc.)
1250    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1251
1252# base help text
1253Help('''
1254Usage: scons [scons options] [build variables] [target(s)]
1255
1256Extra scons options:
1257%(options)s
1258
1259Global build variables:
1260%(global_vars)s
1261
1262%(local_vars)s
1263''' % help_texts)
1264