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