SConstruct revision 12305
1955SN/A# -*- mode:python -*-
2955SN/A
37816Ssteve.reinhardt@amd.com# Copyright (c) 2013, 2015-2017 ARM Limited
45871Snate@binkert.org# All rights reserved.
51762SN/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
29955SN/A# this software without specific prior written permission.
302665Ssaidi@eecs.umich.edu#
312665Ssaidi@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
325863Snate@binkert.org# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
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
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42955SN/A#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452761Sstever@eecs.umich.edu
462632Sstever@eecs.umich.edu###################################################
472632Sstever@eecs.umich.edu#
482632Sstever@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
512761Sstever@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
532632Sstever@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
582761Sstever@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
652632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
68955SN/A#   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
995863Snate@binkert.org
1006654Snate@binkert.orghelp_texts = {
101955SN/A    "options" : "",
1025396Ssaidi@eecs.umich.edu    "global_vars" : "",
1035863Snate@binkert.org    "local_vars" : ""
1045863Snate@binkert.org}
1054202Sbinkertn@umich.edu
1065863Snate@binkert.orgExport("help_texts")
1075863Snate@binkert.org
1085863Snate@binkert.org
1095863Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
110955SN/A# AddOption() are supposed to be displayed when you type 'scons -h'
1116654Snate@binkert.org# and (2) you can override the help displayed by 'scons -h' using the
1125273Sstever@gmail.com# Help() function, but these two features are incompatible: once
1135871Snate@binkert.org# you've overridden the help text using Help(), there's no way to get
1145273Sstever@gmail.com# at the help texts from AddOptions.  See:
1156655Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1166655Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1176655Snate@binkert.org# This hack lets us extract the help text from AddOptions and
1186655Snate@binkert.org# re-inject it via Help().  Ideally someday this bug will be fixed and
1196655Snate@binkert.org# we can just use AddOption directly.
1206655Snate@binkert.orgdef AddLocalOption(*args, **kwargs):
1215871Snate@binkert.org    col_width = 30
1226654Snate@binkert.org
1235396Ssaidi@eecs.umich.edu    help = "  " + ", ".join(args)
1248120Sgblack@eecs.umich.edu    if "help" in kwargs:
1258120Sgblack@eecs.umich.edu        length = len(help)
1268120Sgblack@eecs.umich.edu        if length >= col_width:
1278120Sgblack@eecs.umich.edu            help += "\n" + " " * col_width
1288120Sgblack@eecs.umich.edu        else:
1298120Sgblack@eecs.umich.edu            help += " " * (col_width - length)
1308120Sgblack@eecs.umich.edu        help += kwargs["help"]
1318120Sgblack@eecs.umich.edu    help_texts["options"] += help + "\n"
1328120Sgblack@eecs.umich.edu
1338120Sgblack@eecs.umich.edu    AddOption(*args, **kwargs)
1348120Sgblack@eecs.umich.edu
1358120Sgblack@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1368120Sgblack@eecs.umich.edu               help="Add color to abbreviated scons output")
1378120Sgblack@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1388120Sgblack@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1398120Sgblack@eecs.umich.eduAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1408120Sgblack@eecs.umich.edu               action='store_true',
1418120Sgblack@eecs.umich.edu               help="Build with support for C++-based configuration")
1428120Sgblack@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1438120Sgblack@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1448120Sgblack@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1458120Sgblack@eecs.umich.edu               help='Disable style checking hooks')
1468120Sgblack@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1478120Sgblack@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1488120Sgblack@eecs.umich.eduAddLocalOption('--force-lto', dest='force_lto', action='store_true',
1498120Sgblack@eecs.umich.edu               help='Use Link-Time Optimization instead of partial linking' +
1508120Sgblack@eecs.umich.edu                    ' when the compiler doesn\'t support using them together.')
1518120Sgblack@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1528120Sgblack@eecs.umich.edu               help='Update test reference outputs')
1538120Sgblack@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1548120Sgblack@eecs.umich.edu               help='Print full tool command lines')
1558120Sgblack@eecs.umich.eduAddLocalOption('--without-python', dest='without_python',
1568120Sgblack@eecs.umich.edu               action='store_true',
1578120Sgblack@eecs.umich.edu               help='Build without Python configuration support')
1588120Sgblack@eecs.umich.eduAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1598120Sgblack@eecs.umich.edu               action='store_true',
1607816Ssteve.reinhardt@amd.com               help='Disable linking against tcmalloc')
1617816Ssteve.reinhardt@amd.comAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1627816Ssteve.reinhardt@amd.com               help='Build with Undefined Behavior Sanitizer if available')
1637816Ssteve.reinhardt@amd.comAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1647816Ssteve.reinhardt@amd.com               help='Build with Address Sanitizer if available')
1657816Ssteve.reinhardt@amd.com
1667816Ssteve.reinhardt@amd.comif GetOption('no_lto') and GetOption('force_lto'):
1677816Ssteve.reinhardt@amd.com    print '--no-lto and --force-lto are mutually exclusive'
1687816Ssteve.reinhardt@amd.com    Exit(1)
1695871Snate@binkert.org
1705871Snate@binkert.org########################################################################
1716121Snate@binkert.org#
1725871Snate@binkert.org# Set up the main build environment.
1735871Snate@binkert.org#
1746003Snate@binkert.org########################################################################
1756655Snate@binkert.org
176955SN/Amain = Environment()
1775871Snate@binkert.org
1785871Snate@binkert.orgfrom gem5_scons import Transform
1795871Snate@binkert.orgfrom gem5_scons.util import get_termcap
1805871Snate@binkert.orgtermcap = get_termcap()
181955SN/A
1826121Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
1836121Snate@binkert.org
1846121Snate@binkert.org# Check that we have a C/C++ compiler
1851533SN/Aif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1866655Snate@binkert.org    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
1876655Snate@binkert.org    Exit(1)
1886655Snate@binkert.org
1896655Snate@binkert.org###################################################
1905871Snate@binkert.org#
1915871Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
1925863Snate@binkert.org# the target(s).
1935871Snate@binkert.org#
1945871Snate@binkert.org###################################################
1955871Snate@binkert.org
1965871Snate@binkert.org# Find default configuration & binary.
1975871Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
1985863Snate@binkert.org
1996121Snate@binkert.org# helper function: find last occurrence of element in list
2005863Snate@binkert.orgdef rfind(l, elt, offs = -1):
2015871Snate@binkert.org    for i in range(len(l)+offs, 0, -1):
2028336Ssteve.reinhardt@amd.com        if l[i] == elt:
2038336Ssteve.reinhardt@amd.com            return i
2048336Ssteve.reinhardt@amd.com    raise ValueError, "element not found"
2058336Ssteve.reinhardt@amd.com
2064678Snate@binkert.org# Take a list of paths (or SCons Nodes) and return a list with all
2078336Ssteve.reinhardt@amd.com# paths made absolute and ~-expanded.  Paths will be interpreted
2088336Ssteve.reinhardt@amd.com# relative to the launch directory unless a different root is provided
2098336Ssteve.reinhardt@amd.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
2104678Snate@binkert.org    return [abspath(joinpath(root, expanduser(str(p))))
2114678Snate@binkert.org            for p in path_list]
2124678Snate@binkert.org
2134678Snate@binkert.org# Each target must have 'build' in the interior of the path; the
2147827Snate@binkert.org# directory below this will determine the build parameters.  For
2157827Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2168336Ssteve.reinhardt@amd.com# recognize that ALPHA_SE specifies the configuration because it
2174678Snate@binkert.org# follow 'build' in the build path.
2188336Ssteve.reinhardt@amd.com
2198336Ssteve.reinhardt@amd.com# The funky assignment to "[:]" is needed to replace the list contents
2208336Ssteve.reinhardt@amd.com# in place rather than reassign the symbol to a new list, which
2218336Ssteve.reinhardt@amd.com# doesn't work (obviously!).
2228336Ssteve.reinhardt@amd.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2238336Ssteve.reinhardt@amd.com
2245871Snate@binkert.org# Generate a list of the unique build roots and configs that the
2255871Snate@binkert.org# collected targets reference.
2268336Ssteve.reinhardt@amd.comvariant_paths = []
2278336Ssteve.reinhardt@amd.combuild_root = None
2288336Ssteve.reinhardt@amd.comfor t in BUILD_TARGETS:
2298336Ssteve.reinhardt@amd.com    path_dirs = t.split('/')
2308336Ssteve.reinhardt@amd.com    try:
2315871Snate@binkert.org        build_top = rfind(path_dirs, 'build', -2)
2328336Ssteve.reinhardt@amd.com    except:
2338336Ssteve.reinhardt@amd.com        print "Error: no non-leaf 'build' dir found on target path", t
2348336Ssteve.reinhardt@amd.com        Exit(1)
2358336Ssteve.reinhardt@amd.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2368336Ssteve.reinhardt@amd.com    if not build_root:
2374678Snate@binkert.org        build_root = this_build_root
2385871Snate@binkert.org    else:
2394678Snate@binkert.org        if this_build_root != build_root:
2408336Ssteve.reinhardt@amd.com            print "Error: build targets not under same build root\n"\
2418336Ssteve.reinhardt@amd.com                  "  %s\n  %s" % (build_root, this_build_root)
2428336Ssteve.reinhardt@amd.com            Exit(1)
2438336Ssteve.reinhardt@amd.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
2448336Ssteve.reinhardt@amd.com    if variant_path not in variant_paths:
2458336Ssteve.reinhardt@amd.com        variant_paths.append(variant_path)
2468336Ssteve.reinhardt@amd.com
2478336Ssteve.reinhardt@amd.com# Make sure build_root exists (might not if this is the first build there)
2488336Ssteve.reinhardt@amd.comif not isdir(build_root):
2498336Ssteve.reinhardt@amd.com    mkdir(build_root)
2508336Ssteve.reinhardt@amd.commain['BUILDROOT'] = build_root
2518336Ssteve.reinhardt@amd.com
2528336Ssteve.reinhardt@amd.comExport('main')
2538336Ssteve.reinhardt@amd.com
2548336Ssteve.reinhardt@amd.commain.SConsignFile(joinpath(build_root, "sconsign"))
2558336Ssteve.reinhardt@amd.com
2568336Ssteve.reinhardt@amd.com# Default duplicate option is to use hard links, but this messes up
2575871Snate@binkert.org# when you use emacs to edit a file in the target dir, as emacs moves
2586121Snate@binkert.org# file to file~ then copies to file, breaking the link.  Symbolic
259955SN/A# (soft) links work better.
260955SN/Amain.SetOption('duplicate', 'soft-copy')
2612632Sstever@eecs.umich.edu
2622632Sstever@eecs.umich.edu#
263955SN/A# Set up global sticky variables... these are common to an entire build
264955SN/A# tree (not specific to a particular build like ALPHA_SE)
265955SN/A#
266955SN/A
2675863Snate@binkert.orgglobal_vars_file = joinpath(build_root, 'variables.global')
268955SN/A
2692632Sstever@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2702632Sstever@eecs.umich.edu
2712632Sstever@eecs.umich.eduglobal_vars.AddVariables(
2722632Sstever@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2732632Sstever@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2742632Sstever@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2752632Sstever@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
2768268Ssteve.reinhardt@amd.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2778268Ssteve.reinhardt@amd.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2788268Ssteve.reinhardt@amd.com    ('EXTRAS', 'Add extra directories to the compilation', '')
2798268Ssteve.reinhardt@amd.com    )
2808268Ssteve.reinhardt@amd.com
2818268Ssteve.reinhardt@amd.com# Update main environment with values from ARGUMENTS & global_vars_file
2828268Ssteve.reinhardt@amd.comglobal_vars.Update(main)
2832632Sstever@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)
2878268Ssteve.reinhardt@amd.com
2882632Sstever@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
2898268Ssteve.reinhardt@amd.com# look for sources etc.  This list is exported as extras_dir_list.
2908268Ssteve.reinhardt@amd.combase_dir = main.srcdir.abspath
2918268Ssteve.reinhardt@amd.comif main['EXTRAS']:
2928268Ssteve.reinhardt@amd.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
2933718Sstever@eecs.umich.eduelse:
2942634Sstever@eecs.umich.edu    extras_dir_list = []
2952634Sstever@eecs.umich.edu
2965863Snate@binkert.orgExport('base_dir')
2972638Sstever@eecs.umich.eduExport('extras_dir_list')
2988268Ssteve.reinhardt@amd.com
2992632Sstever@eecs.umich.edu# the ext directory should be on the #includes path
3002632Sstever@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
3012632Sstever@eecs.umich.edu
3022632Sstever@eecs.umich.edu# Add shared top-level headers
3032632Sstever@eecs.umich.edumain.Prepend(CPPPATH=Dir('include'))
3041858SN/A
3053716Sstever@eecs.umich.eduif GetOption('verbose'):
3062638Sstever@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
3072638Sstever@eecs.umich.edu        return Action(action, *args, **kwargs)
3082638Sstever@eecs.umich.eduelse:
3092638Sstever@eecs.umich.edu    MakeAction = Action
3102638Sstever@eecs.umich.edu    main['CCCOMSTR']        = Transform("CC")
3112638Sstever@eecs.umich.edu    main['CXXCOMSTR']       = Transform("CXX")
3122638Sstever@eecs.umich.edu    main['ASCOMSTR']        = Transform("AS")
3135863Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
3145863Snate@binkert.org    main['LINKCOMSTR']      = Transform("LINK", 0)
3155863Snate@binkert.org    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
316955SN/A    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3175341Sstever@gmail.com    main['M4COMSTR']        = Transform("M4")
3185341Sstever@gmail.com    main['SHCCCOMSTR']      = Transform("SHCC")
3195863Snate@binkert.org    main['SHCXXCOMSTR']     = Transform("SHCXX")
3207756SAli.Saidi@ARM.comExport('MakeAction')
3215341Sstever@gmail.com
3226121Snate@binkert.org# Initialize the Link-Time Optimization (LTO) flags
3234494Ssaidi@eecs.umich.edumain['LTO_CCFLAGS'] = []
3246121Snate@binkert.orgmain['LTO_LDFLAGS'] = []
3251105SN/A
3262667Sstever@eecs.umich.edu# According to the readme, tcmalloc works best if the compiler doesn't
3272667Sstever@eecs.umich.edu# assume that we're using the builtin malloc and friends. These flags
3282667Sstever@eecs.umich.edu# are compiler-specific, so we need to set them after we detect which
3292667Sstever@eecs.umich.edu# compiler we're using.
3306121Snate@binkert.orgmain['TCMALLOC_CCFLAGS'] = []
3312667Sstever@eecs.umich.edu
3325341Sstever@gmail.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3335863Snate@binkert.orgCXX_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
3378120Sgblack@eecs.umich.eduif main['GCC'] + main['CLANG'] > 1:
3385341Sstever@gmail.com    print 'Error: How can we have two at the same time?'
3398120Sgblack@eecs.umich.edu    Exit(1)
3405341Sstever@gmail.com
3418120Sgblack@eecs.umich.edu# Set up default C++ compiler flags
3426121Snate@binkert.orgif main['GCC'] or main['CLANG']:
3436121Snate@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'])
3467727SAli.Saidi@ARM.com    # Enable -Wall and -Wextra and then disable the few warnings that
3478268Ssteve.reinhardt@amd.com    # we consistently violate
3486168Snate@binkert.org    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
3495341Sstever@gmail.com                         '-Wno-sign-compare', '-Wno-unused-parameter'])
3508120Sgblack@eecs.umich.edu    # We always compile using C++11
3518120Sgblack@eecs.umich.edu    main.Append(CXXFLAGS=['-std=c++11'])
3528120Sgblack@eecs.umich.edu    if sys.platform.startswith('freebsd'):
3536814Sgblack@eecs.umich.edu        main.Append(CCFLAGS=['-I/usr/local/include'])
3545863Snate@binkert.org        main.Append(CXXFLAGS=['-I/usr/local/include'])
3558120Sgblack@eecs.umich.edu
3565341Sstever@gmail.com    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3575863Snate@binkert.org    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
3588268Ssteve.reinhardt@amd.com    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3596121Snate@binkert.org    shared_partial_flags = ['-r', '-nostdlib']
3606121Snate@binkert.org    main.Append(PSHLINKFLAGS=shared_partial_flags)
3618268Ssteve.reinhardt@amd.com    main.Append(PLINKFLAGS=shared_partial_flags)
3625742Snate@binkert.org
3635742Snate@binkert.org    # Treat warnings as errors but white list some warnings that we
3645341Sstever@gmail.com    # want to allow (e.g., deprecation warnings).
3655742Snate@binkert.org    main.Append(CCFLAGS=['-Werror',
3665742Snate@binkert.org                         '-Wno-error=deprecated-declarations',
3675341Sstever@gmail.com                         '-Wno-error=deprecated',
3686017Snate@binkert.org                        ])
3696121Snate@binkert.orgelse:
3706017Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
3717816Ssteve.reinhardt@amd.com    print "Don't know what compiler options to use for your compiler."
3727756SAli.Saidi@ARM.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
3737756SAli.Saidi@ARM.com    print termcap.Yellow + '       version:' + termcap.Normal,
3747756SAli.Saidi@ARM.com    if not CXX_version:
3757756SAli.Saidi@ARM.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
3767756SAli.Saidi@ARM.com               termcap.Normal
3777756SAli.Saidi@ARM.com    else:
3787756SAli.Saidi@ARM.com        print CXX_version.replace('\n', '<nl>')
3797756SAli.Saidi@ARM.com    print "       If you're trying to use a compiler other than GCC"
3807816Ssteve.reinhardt@amd.com    print "       or clang, there appears to be something wrong with your"
3817816Ssteve.reinhardt@amd.com    print "       environment."
3827816Ssteve.reinhardt@amd.com    print "       "
3837816Ssteve.reinhardt@amd.com    print "       If you are trying to use a compiler other than those listed"
3847816Ssteve.reinhardt@amd.com    print "       above you will need to ease fix SConstruct and "
3857816Ssteve.reinhardt@amd.com    print "       src/SConscript to support that compiler."
3867816Ssteve.reinhardt@amd.com    Exit(1)
3877816Ssteve.reinhardt@amd.com
3887816Ssteve.reinhardt@amd.comif main['GCC']:
3897816Ssteve.reinhardt@amd.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
3907756SAli.Saidi@ARM.com    # level of c++11 support. See
3917816Ssteve.reinhardt@amd.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
3927816Ssteve.reinhardt@amd.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
3937816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, "4.8") < 0:
3947816Ssteve.reinhardt@amd.com        print 'Error: gcc version 4.8 or newer required.'
3957816Ssteve.reinhardt@amd.com        print '       Installed version:', gcc_version
3967816Ssteve.reinhardt@amd.com        Exit(1)
3977816Ssteve.reinhardt@amd.com
3987816Ssteve.reinhardt@amd.com    main['GCC_VERSION'] = gcc_version
3997816Ssteve.reinhardt@amd.com
4007816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, '4.9') >= 0:
4017816Ssteve.reinhardt@amd.com        # Incremental linking with LTO is currently broken in gcc versions
4027816Ssteve.reinhardt@amd.com        # 4.9 and above. A version where everything works completely hasn't
4037816Ssteve.reinhardt@amd.com        # yet been identified.
4047816Ssteve.reinhardt@amd.com        #
4057816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
4067816Ssteve.reinhardt@amd.com        main['BROKEN_INCREMENTAL_LTO'] = True
4077816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, '6.0') >= 0:
4087816Ssteve.reinhardt@amd.com        # gcc versions 6.0 and greater accept an -flinker-output flag which
4097816Ssteve.reinhardt@amd.com        # selects what type of output the linker should generate. This is
4107816Ssteve.reinhardt@amd.com        # necessary for incremental lto to work, but is also broken in
4117816Ssteve.reinhardt@amd.com        # current versions of gcc. It may not be necessary in future
4127816Ssteve.reinhardt@amd.com        # versions. We add it here since it might be, and as a reminder that
4137816Ssteve.reinhardt@amd.com        # it exists. It's excluded if lto is being forced.
4147816Ssteve.reinhardt@amd.com        #
4157816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/gcc-6/changes.html
4167816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
4177816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
4187816Ssteve.reinhardt@amd.com        if not GetOption('force_lto'):
4197816Ssteve.reinhardt@amd.com            main.Append(PSHLINKFLAGS='-flinker-output=rel')
4207816Ssteve.reinhardt@amd.com            main.Append(PLINKFLAGS='-flinker-output=rel')
4217816Ssteve.reinhardt@amd.com
4227816Ssteve.reinhardt@amd.com    # gcc from version 4.8 and above generates "rep; ret" instructions
4237816Ssteve.reinhardt@amd.com    # to avoid performance penalties on certain AMD chips. Older
4247816Ssteve.reinhardt@amd.com    # assemblers detect this as an error, "Error: expecting string
4257816Ssteve.reinhardt@amd.com    # instruction after `rep'"
4267816Ssteve.reinhardt@amd.com    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
4277816Ssteve.reinhardt@amd.com                                  '-o', '/dev/null'],
4287816Ssteve.reinhardt@amd.com                                 exception=False).split()
4297816Ssteve.reinhardt@amd.com
4307816Ssteve.reinhardt@amd.com    # version strings may contain extra distro-specific
4317816Ssteve.reinhardt@amd.com    # qualifiers, so play it safe and keep only what comes before
4327816Ssteve.reinhardt@amd.com    # the first hyphen
4337816Ssteve.reinhardt@amd.com    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
4347816Ssteve.reinhardt@amd.com
4357816Ssteve.reinhardt@amd.com    if not as_version or compareVersions(as_version, "2.23") < 0:
4367816Ssteve.reinhardt@amd.com        print termcap.Yellow + termcap.Bold + \
4377816Ssteve.reinhardt@amd.com            'Warning: This combination of gcc and binutils have' + \
4387816Ssteve.reinhardt@amd.com            ' known incompatibilities.\n' + \
4397816Ssteve.reinhardt@amd.com            '         If you encounter build problems, please update ' + \
4407816Ssteve.reinhardt@amd.com            'binutils to 2.23.' + \
4417816Ssteve.reinhardt@amd.com            termcap.Normal
4427816Ssteve.reinhardt@amd.com
4437816Ssteve.reinhardt@amd.com    # Make sure we warn if the user has requested to compile with the
4447816Ssteve.reinhardt@amd.com    # Undefined Benahvior Sanitizer and this version of gcc does not
4457816Ssteve.reinhardt@amd.com    # support it.
4467816Ssteve.reinhardt@amd.com    if GetOption('with_ubsan') and \
4477816Ssteve.reinhardt@amd.com            compareVersions(gcc_version, '4.9') < 0:
4487816Ssteve.reinhardt@amd.com        print termcap.Yellow + termcap.Bold + \
4497816Ssteve.reinhardt@amd.com            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
4507816Ssteve.reinhardt@amd.com            termcap.Normal
4517816Ssteve.reinhardt@amd.com
4527756SAli.Saidi@ARM.com    disable_lto = GetOption('no_lto')
4538120Sgblack@eecs.umich.edu    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
4547756SAli.Saidi@ARM.com            not GetOption('force_lto'):
4557756SAli.Saidi@ARM.com        print termcap.Yellow + termcap.Bold + \
4567756SAli.Saidi@ARM.com            'Warning: Your compiler doesn\'t support incremental linking' + \
4577756SAli.Saidi@ARM.com            ' and lto at the same time, so lto is being disabled. To force' + \
4587816Ssteve.reinhardt@amd.com            ' lto on anyway, use the --force-lto option. That will disable' + \
4597816Ssteve.reinhardt@amd.com            ' partial linking.' + \
4607816Ssteve.reinhardt@amd.com            termcap.Normal
4617816Ssteve.reinhardt@amd.com        disable_lto = True
4627816Ssteve.reinhardt@amd.com
4637816Ssteve.reinhardt@amd.com    # Add the appropriate Link-Time Optimization (LTO) flags
4647816Ssteve.reinhardt@amd.com    # unless LTO is explicitly turned off. Note that these flags
4657816Ssteve.reinhardt@amd.com    # are only used by the fast target.
4667816Ssteve.reinhardt@amd.com    if not disable_lto:
4677816Ssteve.reinhardt@amd.com        # Pass the LTO flag when compiling to produce GIMPLE
4687756SAli.Saidi@ARM.com        # output, we merely create the flags here and only append
4697756SAli.Saidi@ARM.com        # them later
4706654Snate@binkert.org        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4716654Snate@binkert.org
4725871Snate@binkert.org        # Use the same amount of jobs for LTO as we are running
4736121Snate@binkert.org        # scons with
4746121Snate@binkert.org        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4756121Snate@binkert.org
4766121Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4773940Ssaidi@eecs.umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4783918Ssaidi@eecs.umich.edu
4793918Ssaidi@eecs.umich.edu    # add option to check for undeclared overrides
4801858SN/A    if compareVersions(gcc_version, "5.0") > 0:
4816121Snate@binkert.org        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
4827739Sgblack@eecs.umich.edu
4837739Sgblack@eecs.umich.edu    # The address sanitizer is available for gcc >= 4.8
4846143Snate@binkert.org    if GetOption('with_asan'):
4857739Sgblack@eecs.umich.edu        if GetOption('with_ubsan') and \
4867618SAli.Saidi@arm.com                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
4877618SAli.Saidi@arm.com            env.Append(CCFLAGS=['-fsanitize=address,undefined',
4887618SAli.Saidi@arm.com                                '-fno-omit-frame-pointer'],
4897618SAli.Saidi@arm.com                       LINKFLAGS='-fsanitize=address,undefined')
4907618SAli.Saidi@arm.com        else:
4917618SAli.Saidi@arm.com            env.Append(CCFLAGS=['-fsanitize=address',
4927618SAli.Saidi@arm.com                                '-fno-omit-frame-pointer'],
4937739Sgblack@eecs.umich.edu                       LINKFLAGS='-fsanitize=address')
4946121Snate@binkert.org    # Only gcc >= 4.9 supports UBSan, so check both the version
4953940Ssaidi@eecs.umich.edu    # and the command-line option before adding the compiler and
4966121Snate@binkert.org    # linker flags.
4977739Sgblack@eecs.umich.edu    elif GetOption('with_ubsan') and \
4987739Sgblack@eecs.umich.edu            compareVersions(env['GCC_VERSION'], '4.9') >= 0:
4997739Sgblack@eecs.umich.edu        env.Append(CCFLAGS='-fsanitize=undefined')
5007739Sgblack@eecs.umich.edu        env.Append(LINKFLAGS='-fsanitize=undefined')
5017739Sgblack@eecs.umich.edu
5027739Sgblack@eecs.umich.eduelif main['CLANG']:
5033918Ssaidi@eecs.umich.edu    # Check for a supported version of clang, >= 3.1 is needed to
5043918Ssaidi@eecs.umich.edu    # support similar features as gcc 4.8. See
5053940Ssaidi@eecs.umich.edu    # http://clang.llvm.org/cxx_status.html for details
5063918Ssaidi@eecs.umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
5073918Ssaidi@eecs.umich.edu    clang_version_match = clang_version_re.search(CXX_version)
5086157Snate@binkert.org    if (clang_version_match):
5096157Snate@binkert.org        clang_version = clang_version_match.groups()[0]
5106157Snate@binkert.org        if compareVersions(clang_version, "3.1") < 0:
5116157Snate@binkert.org            print 'Error: clang version 3.1 or newer required.'
5125397Ssaidi@eecs.umich.edu            print '       Installed version:', clang_version
5135397Ssaidi@eecs.umich.edu            Exit(1)
5146121Snate@binkert.org    else:
5156121Snate@binkert.org        print 'Error: Unable to determine clang version.'
5166121Snate@binkert.org        Exit(1)
5176121Snate@binkert.org
5186121Snate@binkert.org    # clang has a few additional warnings that we disable, extraneous
5196121Snate@binkert.org    # parantheses are allowed due to Ruby's printing of the AST,
5205397Ssaidi@eecs.umich.edu    # finally self assignments are allowed as the generated CPU code
5211851SN/A    # is relying on this
5221851SN/A    main.Append(CCFLAGS=['-Wno-parentheses',
5237739Sgblack@eecs.umich.edu                         '-Wno-self-assign',
524955SN/A                         # Some versions of libstdc++ (4.8?) seem to
5253053Sstever@eecs.umich.edu                         # use struct hash and class hash
5266121Snate@binkert.org                         # interchangeably.
5273053Sstever@eecs.umich.edu                         '-Wno-mismatched-tags',
5283053Sstever@eecs.umich.edu                         ])
5293053Sstever@eecs.umich.edu
5303053Sstever@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5313053Sstever@eecs.umich.edu
5326654Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5333053Sstever@eecs.umich.edu    # opposed to libstdc++, as the later is dated.
5344742Sstever@eecs.umich.edu    if sys.platform == "darwin":
5354742Sstever@eecs.umich.edu        main.Append(CXXFLAGS=['-stdlib=libc++'])
5363053Sstever@eecs.umich.edu        main.Append(LIBS=['c++'])
5373053Sstever@eecs.umich.edu
5383053Sstever@eecs.umich.edu    # On FreeBSD we need libthr.
5393053Sstever@eecs.umich.edu    if sys.platform.startswith('freebsd'):
5406654Snate@binkert.org        main.Append(LIBS=['thr'])
5413053Sstever@eecs.umich.edu
5423053Sstever@eecs.umich.edu    # We require clang >= 3.1, so there is no need to check any
5433053Sstever@eecs.umich.edu    # versions here.
5443053Sstever@eecs.umich.edu    if GetOption('with_ubsan'):
5452667Sstever@eecs.umich.edu        if GetOption('with_asan'):
5464554Sbinkertn@umich.edu            env.Append(CCFLAGS=['-fsanitize=address,undefined',
5476121Snate@binkert.org                                '-fno-omit-frame-pointer'],
5482667Sstever@eecs.umich.edu                       LINKFLAGS='-fsanitize=address,undefined')
5494554Sbinkertn@umich.edu        else:
5504554Sbinkertn@umich.edu            env.Append(CCFLAGS='-fsanitize=undefined',
5514554Sbinkertn@umich.edu                       LINKFLAGS='-fsanitize=undefined')
5526121Snate@binkert.org
5534554Sbinkertn@umich.edu    elif GetOption('with_asan'):
5544554Sbinkertn@umich.edu        env.Append(CCFLAGS=['-fsanitize=address',
5554554Sbinkertn@umich.edu                            '-fno-omit-frame-pointer'],
5564781Snate@binkert.org                   LINKFLAGS='-fsanitize=address')
5574554Sbinkertn@umich.edu
5584554Sbinkertn@umich.eduelse:
5592667Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5604554Sbinkertn@umich.edu    print "Don't know what compiler options to use for your compiler."
5614554Sbinkertn@umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5624554Sbinkertn@umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
5634554Sbinkertn@umich.edu    if not CXX_version:
5642667Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5654554Sbinkertn@umich.edu               termcap.Normal
5662667Sstever@eecs.umich.edu    else:
5674554Sbinkertn@umich.edu        print CXX_version.replace('\n', '<nl>')
5686121Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
5692667Sstever@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
5705522Snate@binkert.org    print "       environment."
5715522Snate@binkert.org    print "       "
5725522Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
5735522Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
5745522Snate@binkert.org    print "       src/SConscript to support that compiler."
5755522Snate@binkert.org    Exit(1)
5765522Snate@binkert.org
5775522Snate@binkert.org# Set up common yacc/bison flags (needed for Ruby)
5785522Snate@binkert.orgmain['YACCFLAGS'] = '-d'
5795522Snate@binkert.orgmain['YACCHXXFILESUFFIX'] = '.hh'
5805522Snate@binkert.org
5815522Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
5825522Snate@binkert.org# extra 'qdo' every time we run scons.
5835522Snate@binkert.orgif main['BATCH']:
5845522Snate@binkert.org    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5855522Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5865522Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5875522Snate@binkert.org    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5885522Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5895522Snate@binkert.org
5905522Snate@binkert.orgif sys.platform == 'cygwin':
5915522Snate@binkert.org    # cygwin has some header file issues...
5925522Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
5935522Snate@binkert.org
5945522Snate@binkert.org# Check for the protobuf compiler
5955522Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
5962638Sstever@eecs.umich.edu                             exception='').split()
5972638Sstever@eecs.umich.edu
5986121Snate@binkert.org# First two words should be "libprotoc x.y.z"
5993716Sstever@eecs.umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6005522Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
6015522Snate@binkert.org        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6025522Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' + \
6035522Snate@binkert.org        termcap.Normal
6045522Snate@binkert.org    main['PROTOC'] = False
6055522Snate@binkert.orgelse:
6061858SN/A    # Based on the availability of the compress stream wrappers,
6075227Ssaidi@eecs.umich.edu    # require 2.1.0
6085227Ssaidi@eecs.umich.edu    min_protoc_version = '2.1.0'
6095227Ssaidi@eecs.umich.edu    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6105227Ssaidi@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
6116654Snate@binkert.org            'Warning: protoc version', min_protoc_version, \
6126654Snate@binkert.org            'or newer required.\n' + \
6137769SAli.Saidi@ARM.com            '         Installed version:', protoc_version[1], \
6147769SAli.Saidi@ARM.com            termcap.Normal
6157769SAli.Saidi@ARM.com        main['PROTOC'] = False
6167769SAli.Saidi@ARM.com    else:
6175227Ssaidi@eecs.umich.edu        # Attempt to determine the appropriate include path and
6185227Ssaidi@eecs.umich.edu        # library path using pkg-config, that means we also need to
6195227Ssaidi@eecs.umich.edu        # check for pkg-config. Note that it is possible to use
6205204Sstever@gmail.com        # protobuf without the involvement of pkg-config. Later on we
6215204Sstever@gmail.com        # check go a library config check and at that point the test
6225204Sstever@gmail.com        # will fail if libprotobuf cannot be found.
6235204Sstever@gmail.com        if readCommand(['pkg-config', '--version'], exception=''):
6245204Sstever@gmail.com            try:
6255204Sstever@gmail.com                # Attempt to establish what linking flags to add for protobuf
6265204Sstever@gmail.com                # using pkg-config
6275204Sstever@gmail.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6285204Sstever@gmail.com            except:
6295204Sstever@gmail.com                print termcap.Yellow + termcap.Bold + \
6305204Sstever@gmail.com                    'Warning: pkg-config could not get protobuf flags.' + \
6315204Sstever@gmail.com                    termcap.Normal
6325204Sstever@gmail.com
6335204Sstever@gmail.com
6345204Sstever@gmail.com# Check for 'timeout' from GNU coreutils. If present, regressions will
6355204Sstever@gmail.com# be run with a time limit. We require version 8.13 since we rely on
6365204Sstever@gmail.com# support for the '--foreground' option.
6376121Snate@binkert.orgif sys.platform.startswith('freebsd'):
6385204Sstever@gmail.com    timeout_lines = readCommand(['gtimeout', '--version'],
6393118Sstever@eecs.umich.edu                                exception='').splitlines()
6403118Sstever@eecs.umich.eduelse:
6413118Sstever@eecs.umich.edu    timeout_lines = readCommand(['timeout', '--version'],
6423118Sstever@eecs.umich.edu                                exception='').splitlines()
6433118Sstever@eecs.umich.edu# Get the first line and tokenize it
6445863Snate@binkert.orgtimeout_version = timeout_lines[0].split() if timeout_lines else []
6453118Sstever@eecs.umich.edumain['TIMEOUT'] =  timeout_version and \
6465863Snate@binkert.org    compareVersions(timeout_version[-1], '8.13') >= 0
6473118Sstever@eecs.umich.edu
6487457Snate@binkert.org# Add a custom Check function to test for structure members.
6497457Snate@binkert.orgdef CheckMember(context, include, decl, member, include_quotes="<>"):
6505863Snate@binkert.org    context.Message("Checking for member %s in %s..." %
6515863Snate@binkert.org                    (member, decl))
6525863Snate@binkert.org    text = """
6535863Snate@binkert.org#include %(header)s
6545863Snate@binkert.orgint main(){
6555863Snate@binkert.org  %(decl)s test;
6565863Snate@binkert.org  (void)test.%(member)s;
6576003Snate@binkert.org  return 0;
6585863Snate@binkert.org};
6595863Snate@binkert.org""" % { "header" : include_quotes[0] + include + include_quotes[1],
6605863Snate@binkert.org        "decl" : decl,
6616120Snate@binkert.org        "member" : member,
6625863Snate@binkert.org        }
6635863Snate@binkert.org
6645863Snate@binkert.org    ret = context.TryCompile(text, extension=".cc")
6656120Snate@binkert.org    context.Result(ret)
6666120Snate@binkert.org    return ret
6675863Snate@binkert.org
6685863Snate@binkert.org# Platform-specific configuration.  Note again that we assume that all
6696120Snate@binkert.org# builds under a given build root run on the same host platform.
6705863Snate@binkert.orgconf = Configure(main,
6716121Snate@binkert.org                 conf_dir = joinpath(build_root, '.scons_config'),
6726121Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
6735863Snate@binkert.org                 custom_tests = {
6747727SAli.Saidi@ARM.com        'CheckMember' : CheckMember,
6757727SAli.Saidi@ARM.com        })
6767727SAli.Saidi@ARM.com
6777727SAli.Saidi@ARM.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6787727SAli.Saidi@ARM.comtry:
6797727SAli.Saidi@ARM.com    import platform
6805863Snate@binkert.org    uname = platform.uname()
6813118Sstever@eecs.umich.edu    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6825863Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6833118Sstever@eecs.umich.edu            main.Append(CCFLAGS=['-arch', 'x86_64'])
6843118Sstever@eecs.umich.edu            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
6893118Sstever@eecs.umich.edu
6903483Ssaidi@eecs.umich.edu# Recent versions of scons substitute a "Null" object for Configure()
6913494Ssaidi@eecs.umich.edu# when configuration isn't necessary, e.g., if the "--help" option is
6923494Ssaidi@eecs.umich.edu# present.  Unfortuantely this Null object always returns false,
6933483Ssaidi@eecs.umich.edu# breaking all our configuration checks.  We replace it with our own
6943483Ssaidi@eecs.umich.edu# more optimistic null object that returns True instead.
6953483Ssaidi@eecs.umich.eduif not conf:
6963053Sstever@eecs.umich.edu    def NullCheck(*args, **kwargs):
6973053Sstever@eecs.umich.edu        return True
6983918Ssaidi@eecs.umich.edu
6993053Sstever@eecs.umich.edu    class NullConf:
7003053Sstever@eecs.umich.edu        def __init__(self, env):
7013053Sstever@eecs.umich.edu            self.env = env
7023053Sstever@eecs.umich.edu        def Finish(self):
7033053Sstever@eecs.umich.edu            return self.env
7047840Snate@binkert.org        def __getattr__(self, mname):
7057865Sgblack@eecs.umich.edu            return NullCheck
7067865Sgblack@eecs.umich.edu
7077865Sgblack@eecs.umich.edu    conf = NullConf(main)
7087865Sgblack@eecs.umich.edu
7097865Sgblack@eecs.umich.edu# Cache build files in the supplied directory.
7107840Snate@binkert.orgif main['M5_BUILD_CACHE']:
7117840Snate@binkert.org    print 'Using build cache located at', main['M5_BUILD_CACHE']
7127840Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
7137840Snate@binkert.org
7141858SN/Amain['USE_PYTHON'] = not GetOption('without_python')
7151858SN/Aif main['USE_PYTHON']:
7161858SN/A    # Find Python include and library directories for embedding the
7171858SN/A    # interpreter. We rely on python-config to resolve the appropriate
7181858SN/A    # includes and linker flags. ParseConfig does not seem to understand
7191858SN/A    # the more exotic linker flags such as -Xlinker and -export-dynamic so
7205863Snate@binkert.org    # we add them explicitly below. If you want to link in an alternate
7215863Snate@binkert.org    # version of python, see above for instructions on how to invoke
7225863Snate@binkert.org    # scons with the appropriate PATH set.
7235863Snate@binkert.org    #
7246121Snate@binkert.org    # First we check if python2-config exists, else we use python-config
7251858SN/A    python_config = readCommand(['which', 'python2-config'],
7265863Snate@binkert.org                                exception='').strip()
7275863Snate@binkert.org    if not os.path.exists(python_config):
7285863Snate@binkert.org        python_config = readCommand(['which', 'python-config'],
7295863Snate@binkert.org                                    exception='').strip()
7305863Snate@binkert.org    py_includes = readCommand([python_config, '--includes'],
7312139SN/A                              exception='').split()
7324202Sbinkertn@umich.edu    # Strip the -I from the include folders before adding them to the
7334202Sbinkertn@umich.edu    # CPPPATH
7342139SN/A    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
7356994Snate@binkert.org
7366994Snate@binkert.org    # Read the linker flags and split them into libraries and other link
7376994Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
7386994Snate@binkert.org    py_ld_flags = readCommand([python_config, '--ldflags'],
7396994Snate@binkert.org        exception='').split()
7406994Snate@binkert.org    py_libs = []
7416994Snate@binkert.org    for lib in py_ld_flags:
7426994Snate@binkert.org         if not lib.startswith('-l'):
7436994Snate@binkert.org             main.Append(LINKFLAGS=[lib])
7446994Snate@binkert.org         else:
7456994Snate@binkert.org             lib = lib[2:]
7466994Snate@binkert.org             if lib not in py_libs:
7476994Snate@binkert.org                 py_libs.append(lib)
7486994Snate@binkert.org
7496994Snate@binkert.org    # verify that this stuff works
7506994Snate@binkert.org    if not conf.CheckHeader('Python.h', '<>'):
7516994Snate@binkert.org        print "Error: can't find Python.h header in", py_includes
7526994Snate@binkert.org        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
7536994Snate@binkert.org        Exit(1)
7546994Snate@binkert.org
7556994Snate@binkert.org    for lib in py_libs:
7566994Snate@binkert.org        if not conf.CheckLib(lib):
7576994Snate@binkert.org            print "Error: can't find library %s required by python" % lib
7586994Snate@binkert.org            Exit(1)
7596994Snate@binkert.org
7606994Snate@binkert.org# On Solaris you need to use libsocket for socket ops
7616994Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7626994Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7632155SN/A       print "Can't find library with socket calls (e.g. accept())"
7645863Snate@binkert.org       Exit(1)
7651869SN/A
7661869SN/A# Check for zlib.  If the check passes, libz will be automatically
7675863Snate@binkert.org# added to the LIBS environment variable.
7685863Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
7694202Sbinkertn@umich.edu    print 'Error: did not find needed zlib compression library '\
7706108Snate@binkert.org          'and/or zlib.h header file.'
7716108Snate@binkert.org    print '       Please install zlib and try again.'
7726108Snate@binkert.org    Exit(1)
7736108Snate@binkert.org
7744202Sbinkertn@umich.edu# If we have the protobuf compiler, also make sure we have the
7755863Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
7768474Sgblack@eecs.umich.edu# automatically added to the LIBS environment variable. After
7778474Sgblack@eecs.umich.edu# this, we can use the HAVE_PROTOBUF flag to determine if we have
7785742Snate@binkert.org# got both protoc and libprotobuf available.
7798268Ssteve.reinhardt@amd.commain['HAVE_PROTOBUF'] = main['PROTOC'] and \
7808268Ssteve.reinhardt@amd.com    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
7818268Ssteve.reinhardt@amd.com                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
7825742Snate@binkert.org
7835341Sstever@gmail.com# If we have the compiler but not the library, print another warning.
7848474Sgblack@eecs.umich.eduif main['PROTOC'] and not main['HAVE_PROTOBUF']:
7858474Sgblack@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
7865342Sstever@gmail.com        'Warning: did not find protocol buffer library and/or headers.\n' + \
7874202Sbinkertn@umich.edu    '       Please install libprotobuf-dev for tracing support.' + \
7884202Sbinkertn@umich.edu    termcap.Normal
7894202Sbinkertn@umich.edu
7905863Snate@binkert.org# Check for librt.
7915863Snate@binkert.orghave_posix_clock = \
7925863Snate@binkert.org    conf.CheckLibWithHeader(None, 'time.h', 'C',
7936994Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
7946994Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
7956994Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
7965863Snate@binkert.org
7978152Ssteve.reinhardt@amd.comhave_posix_timers = \
7988152Ssteve.reinhardt@amd.com    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
7995863Snate@binkert.org                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
8005863Snate@binkert.org
8015863Snate@binkert.orgif not GetOption('without_tcmalloc'):
8025863Snate@binkert.org    if conf.CheckLib('tcmalloc'):
8035863Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
8045863Snate@binkert.org    elif conf.CheckLib('tcmalloc_minimal'):
8055863Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
8065863Snate@binkert.org    else:
8075863Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
8085863Snate@binkert.org              "You can get a 12% performance improvement by "\
8097840Snate@binkert.org              "installing tcmalloc (libgoogle-perftools-dev package "\
8105863Snate@binkert.org              "on Ubuntu or RedHat)." + termcap.Normal
8115863Snate@binkert.org
8125952Ssaidi@eecs.umich.edu
8131869SN/A# Detect back trace implementations. The last implementation in the
8141858SN/A# list will be used by default.
8155863Snate@binkert.orgbacktrace_impls = [ "none" ]
8168297Snate@binkert.org
8178152Ssteve.reinhardt@amd.comif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
8187840Snate@binkert.org                           'backtrace_symbols_fd((void*)0, 0, 0);'):
8197840Snate@binkert.org    backtrace_impls.append("glibc")
8201858SN/Aelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
821955SN/A                           'backtrace_symbols_fd((void*)0, 0, 0);'):
822955SN/A    # NetBSD and FreeBSD need libexecinfo.
8231869SN/A    backtrace_impls.append("glibc")
8241869SN/A    main.Append(LIBS=['execinfo'])
8251869SN/A
8261869SN/Aif backtrace_impls[-1] == "none":
8271869SN/A    default_backtrace_impl = "none"
8285863Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
8295863Snate@binkert.org        "No suitable back trace implementation found." + \
8305863Snate@binkert.org        termcap.Normal
8311869SN/A
8325863Snate@binkert.orgif not have_posix_clock:
8331869SN/A    print "Can't find library for POSIX clocks."
8345863Snate@binkert.org
8351869SN/A# Check for <fenv.h> (C99 FP environment control)
8361869SN/Ahave_fenv = conf.CheckHeader('fenv.h', '<>')
8371869SN/Aif not have_fenv:
8381869SN/A    print "Warning: Header file <fenv.h> not found."
8398483Sgblack@eecs.umich.edu    print "         This host has no IEEE FP rounding mode control."
8401869SN/A
8411869SN/A# Check for <png.h> (libpng library needed if wanting to dump
8421869SN/A# frame buffer image in png format)
8431869SN/Ahave_png = conf.CheckHeader('png.h', '<>')
8445863Snate@binkert.orgif not have_png:
8455863Snate@binkert.org    print "Warning: Header file <png.h> not found."
8461869SN/A    print "         This host has no libpng library."
8475863Snate@binkert.org    print "         Disabling support for PNG framebuffers."
8485863Snate@binkert.org
8493356Sbinkertn@umich.edu# Check if we should enable KVM-based hardware virtualization. The API
8503356Sbinkertn@umich.edu# we rely on exists since version 2.6.36 of the kernel, but somehow
8513356Sbinkertn@umich.edu# the KVM_API_VERSION does not reflect the change. We test for one of
8523356Sbinkertn@umich.edu# the types as a fall back.
8533356Sbinkertn@umich.eduhave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
8544781Snate@binkert.orgif not have_kvm:
8555863Snate@binkert.org    print "Info: Compatible header file <linux/kvm.h> not found, " \
8565863Snate@binkert.org        "disabling KVM support."
8571869SN/A
8581869SN/A# Check if the TUN/TAP driver is available.
8591869SN/Ahave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
8606121Snate@binkert.orgif not have_tuntap:
8611869SN/A    print "Info: Compatible header file <linux/if_tun.h> not found."
8622638Sstever@eecs.umich.edu
8636121Snate@binkert.org# x86 needs support for xsave. We test for the structure here since we
8646121Snate@binkert.org# won't be able to run new tests by the time we know which ISA we're
8652638Sstever@eecs.umich.edu# targeting.
8665749Scws3k@cs.virginia.eduhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
8676121Snate@binkert.org                                    '#include <linux/kvm.h>') != 0
8686121Snate@binkert.org
8695749Scws3k@cs.virginia.edu# Check if the requested target ISA is compatible with the host
8701869SN/Adef is_isa_kvm_compatible(isa):
8711869SN/A    try:
8723546Sgblack@eecs.umich.edu        import platform
8733546Sgblack@eecs.umich.edu        host_isa = platform.machine()
8743546Sgblack@eecs.umich.edu    except:
8753546Sgblack@eecs.umich.edu        print "Warning: Failed to determine host ISA."
8766121Snate@binkert.org        return False
8775863Snate@binkert.org
8783546Sgblack@eecs.umich.edu    if not have_posix_timers:
8793546Sgblack@eecs.umich.edu        print "Warning: Can not enable KVM, host seems to lack support " \
8803546Sgblack@eecs.umich.edu            "for POSIX timers"
8813546Sgblack@eecs.umich.edu        return False
8824781Snate@binkert.org
8834781Snate@binkert.org    if isa == "arm":
8846658Snate@binkert.org        return host_isa in ( "armv7l", "aarch64" )
8856658Snate@binkert.org    elif isa == "x86":
8864781Snate@binkert.org        if host_isa != "x86_64":
8873546Sgblack@eecs.umich.edu            return False
8883546Sgblack@eecs.umich.edu
8893546Sgblack@eecs.umich.edu        if not have_kvm_xsave:
8903546Sgblack@eecs.umich.edu            print "KVM on x86 requires xsave support in kernel headers."
8917756SAli.Saidi@ARM.com            return False
8927816Ssteve.reinhardt@amd.com
8933546Sgblack@eecs.umich.edu        return True
8943546Sgblack@eecs.umich.edu    else:
8953546Sgblack@eecs.umich.edu        return False
8963546Sgblack@eecs.umich.edu
8974202Sbinkertn@umich.edu
8983546Sgblack@eecs.umich.edu# Check if the exclude_host attribute is available. We want this to
8993546Sgblack@eecs.umich.edu# get accurate instruction counts in KVM.
9003546Sgblack@eecs.umich.edumain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
901955SN/A    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
902955SN/A
903955SN/A
904955SN/A######################################################################
9055863Snate@binkert.org#
9065863Snate@binkert.org# Finish the configuration
9075343Sstever@gmail.com#
9085343Sstever@gmail.commain = conf.Finish()
9096121Snate@binkert.org
9105863Snate@binkert.org######################################################################
9114773Snate@binkert.org#
9125863Snate@binkert.org# Collect all non-global variables
9132632Sstever@eecs.umich.edu#
9145863Snate@binkert.org
9152023SN/A# Define the universe of supported ISAs
9165863Snate@binkert.orgall_isa_list = [ ]
9175863Snate@binkert.orgall_gpu_isa_list = [ ]
9185863Snate@binkert.orgExport('all_isa_list')
9195863Snate@binkert.orgExport('all_gpu_isa_list')
9205863Snate@binkert.org
9215863Snate@binkert.orgclass CpuModel(object):
9225863Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
9235863Snate@binkert.org    know about a particular CPU model.'''
9245863Snate@binkert.org
9252632Sstever@eecs.umich.edu    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9265863Snate@binkert.org    dict = {}
9272023SN/A
9282632Sstever@eecs.umich.edu    # Constructor.  Automatically adds models to CpuModel.dict.
9295863Snate@binkert.org    def __init__(self, name, default=False):
9305342Sstever@gmail.com        self.name = name           # name of model
9315863Snate@binkert.org
9322632Sstever@eecs.umich.edu        # This cpu is enabled by default
9335863Snate@binkert.org        self.default = default
9345863Snate@binkert.org
9358267Ssteve.reinhardt@amd.com        # Add self to dict
9368120Sgblack@eecs.umich.edu        if name in CpuModel.dict:
9378267Ssteve.reinhardt@amd.com            raise AttributeError, "CpuModel '%s' already registered" % name
9388267Ssteve.reinhardt@amd.com        CpuModel.dict[name] = self
9398267Ssteve.reinhardt@amd.com
9408267Ssteve.reinhardt@amd.comExport('CpuModel')
9418267Ssteve.reinhardt@amd.com
9428267Ssteve.reinhardt@amd.com# Sticky variables get saved in the variables file so they persist from
9438267Ssteve.reinhardt@amd.com# one invocation to the next (unless overridden, in which case the new
9448267Ssteve.reinhardt@amd.com# value becomes sticky).
9458267Ssteve.reinhardt@amd.comsticky_vars = Variables(args=ARGUMENTS)
9465863Snate@binkert.orgExport('sticky_vars')
9475863Snate@binkert.org
9485863Snate@binkert.org# Sticky variables that should be exported
9492632Sstever@eecs.umich.eduexport_vars = []
9508267Ssteve.reinhardt@amd.comExport('export_vars')
9518267Ssteve.reinhardt@amd.com
9528267Ssteve.reinhardt@amd.com# For Ruby
9532632Sstever@eecs.umich.eduall_protocols = []
9541888SN/AExport('all_protocols')
9555863Snate@binkert.orgprotocol_dirs = []
9565863Snate@binkert.orgExport('protocol_dirs')
9571858SN/Aslicc_includes = []
9588120Sgblack@eecs.umich.eduExport('slicc_includes')
9598120Sgblack@eecs.umich.edu
9607756SAli.Saidi@ARM.com# Walk the tree and execute all SConsopts scripts that wil add to the
9612598SN/A# above variables
9625863Snate@binkert.orgif GetOption('verbose'):
9631858SN/A    print "Reading SConsopts"
9641858SN/Afor bdir in [ base_dir ] + extras_dir_list:
9651858SN/A    if not isdir(bdir):
9665863Snate@binkert.org        print "Error: directory '%s' does not exist" % bdir
9671858SN/A        Exit(1)
9681858SN/A    for root, dirs, files in os.walk(bdir):
9691858SN/A        if 'SConsopts' in files:
9705863Snate@binkert.org            if GetOption('verbose'):
9711871SN/A                print "Reading", joinpath(root, 'SConsopts')
9721858SN/A            SConscript(joinpath(root, 'SConsopts'))
9731858SN/A
9741858SN/Aall_isa_list.sort()
9751858SN/Aall_gpu_isa_list.sort()
9765863Snate@binkert.org
9775863Snate@binkert.orgsticky_vars.AddVariables(
9781869SN/A    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
9791965SN/A    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
9807739Sgblack@eecs.umich.edu    ListVariable('CPU_MODELS', 'CPU models',
9811965SN/A                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
9828482Snilay@cs.wisc.edu                 sorted(CpuModel.dict.keys())),
9838482Snilay@cs.wisc.edu    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
9848482Snilay@cs.wisc.edu                 False),
9858482Snilay@cs.wisc.edu    BoolVariable('SS_COMPATIBLE_FP',
9868482Snilay@cs.wisc.edu                 'Make floating-point results compatible with SimpleScalar',
9872761Sstever@eecs.umich.edu                 False),
9885863Snate@binkert.org    BoolVariable('USE_SSE2',
9891869SN/A                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
9905863Snate@binkert.org                 False),
9912667Sstever@eecs.umich.edu    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
9921869SN/A    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
9931869SN/A    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
9942929Sktlim@umich.edu    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
9952929Sktlim@umich.edu                 False),
9965863Snate@binkert.org    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
9972929Sktlim@umich.edu                 have_kvm),
998955SN/A    BoolVariable('USE_TUNTAP',
9998120Sgblack@eecs.umich.edu                 'Enable using a tap device to bridge to the host network',
10008120Sgblack@eecs.umich.edu                 have_tuntap),
10018120Sgblack@eecs.umich.edu    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
10028120Sgblack@eecs.umich.edu    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
10038120Sgblack@eecs.umich.edu                  all_protocols),
10048120Sgblack@eecs.umich.edu    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
10058120Sgblack@eecs.umich.edu                 backtrace_impls[-1], backtrace_impls)
10068120Sgblack@eecs.umich.edu    )
10078120Sgblack@eecs.umich.edu
10088120Sgblack@eecs.umich.edu# These variables get exported to #defines in config/*.hh (see src/SConscript).
10098120Sgblack@eecs.umich.eduexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
10108120Sgblack@eecs.umich.edu                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
1011                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST',
1012                'USE_PNG']
1013
1014###################################################
1015#
1016# Define a SCons builder for configuration flag headers.
1017#
1018###################################################
1019
1020# This function generates a config header file that #defines the
1021# variable symbol to the current variable setting (0 or 1).  The source
1022# operands are the name of the variable and a Value node containing the
1023# value of the variable.
1024def build_config_file(target, source, env):
1025    (variable, value) = [s.get_contents() for s in source]
1026    f = file(str(target[0]), 'w')
1027    print >> f, '#define', variable, value
1028    f.close()
1029    return None
1030
1031# Combine the two functions into a scons Action object.
1032config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1033
1034# The emitter munges the source & target node lists to reflect what
1035# we're really doing.
1036def config_emitter(target, source, env):
1037    # extract variable name from Builder arg
1038    variable = str(target[0])
1039    # True target is config header file
1040    target = joinpath('config', variable.lower() + '.hh')
1041    val = env[variable]
1042    if isinstance(val, bool):
1043        # Force value to 0/1
1044        val = int(val)
1045    elif isinstance(val, str):
1046        val = '"' + val + '"'
1047
1048    # Sources are variable name & value (packaged in SCons Value nodes)
1049    return ([target], [Value(variable), Value(val)])
1050
1051config_builder = Builder(emitter = config_emitter, action = config_action)
1052
1053main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1054
1055###################################################
1056#
1057# Builders for static and shared partially linked object files.
1058#
1059###################################################
1060
1061partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1062                                 src_suffix='$OBJSUFFIX',
1063                                 src_builder=['StaticObject', 'Object'],
1064                                 LINKFLAGS='$PLINKFLAGS',
1065                                 LIBS='')
1066
1067def partial_shared_emitter(target, source, env):
1068    for tgt in target:
1069        tgt.attributes.shared = 1
1070    return (target, source)
1071partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1072                                 emitter=partial_shared_emitter,
1073                                 src_suffix='$SHOBJSUFFIX',
1074                                 src_builder='SharedObject',
1075                                 SHLINKFLAGS='$PSHLINKFLAGS',
1076                                 LIBS='')
1077
1078main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1079                         'PartialStatic' : partial_static_builder })
1080
1081# builds in ext are shared across all configs in the build root.
1082ext_dir = abspath(joinpath(str(main.root), 'ext'))
1083ext_build_dirs = []
1084for root, dirs, files in os.walk(ext_dir):
1085    if 'SConscript' in files:
1086        build_dir = os.path.relpath(root, ext_dir)
1087        ext_build_dirs.append(build_dir)
1088        main.SConscript(joinpath(root, 'SConscript'),
1089                        variant_dir=joinpath(build_root, build_dir))
1090
1091main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1092
1093###################################################
1094#
1095# This builder and wrapper method are used to set up a directory with
1096# switching headers. Those are headers which are in a generic location and
1097# that include more specific headers from a directory chosen at build time
1098# based on the current build settings.
1099#
1100###################################################
1101
1102def build_switching_header(target, source, env):
1103    path = str(target[0])
1104    subdir = str(source[0])
1105    dp, fp = os.path.split(path)
1106    dp = os.path.relpath(os.path.realpath(dp),
1107                         os.path.realpath(env['BUILDDIR']))
1108    with open(path, 'w') as hdr:
1109        print >>hdr, '#include "%s/%s/%s"' % (dp, subdir, fp)
1110
1111switching_header_action = MakeAction(build_switching_header,
1112                                     Transform('GENERATE'))
1113
1114switching_header_builder = Builder(action=switching_header_action,
1115                                   source_factory=Value,
1116                                   single_source=True)
1117
1118main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1119
1120def switching_headers(self, headers, source):
1121    for header in headers:
1122        self.SwitchingHeader(header, source)
1123
1124main.AddMethod(switching_headers, 'SwitchingHeaders')
1125
1126###################################################
1127#
1128# Define build environments for selected configurations.
1129#
1130###################################################
1131
1132for variant_path in variant_paths:
1133    if not GetOption('silent'):
1134        print "Building in", variant_path
1135
1136    # Make a copy of the build-root environment to use for this config.
1137    env = main.Clone()
1138    env['BUILDDIR'] = variant_path
1139
1140    # variant_dir is the tail component of build path, and is used to
1141    # determine the build parameters (e.g., 'ALPHA_SE')
1142    (build_root, variant_dir) = splitpath(variant_path)
1143
1144    # Set env variables according to the build directory config.
1145    sticky_vars.files = []
1146    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1147    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1148    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1149    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1150    if isfile(current_vars_file):
1151        sticky_vars.files.append(current_vars_file)
1152        if not GetOption('silent'):
1153            print "Using saved variables file %s" % current_vars_file
1154    elif variant_dir in ext_build_dirs:
1155        # Things in ext are built without a variant directory.
1156        continue
1157    else:
1158        # Build dir-specific variables file doesn't exist.
1159
1160        # Make sure the directory is there so we can create it later
1161        opt_dir = dirname(current_vars_file)
1162        if not isdir(opt_dir):
1163            mkdir(opt_dir)
1164
1165        # Get default build variables from source tree.  Variables are
1166        # normally determined by name of $VARIANT_DIR, but can be
1167        # overridden by '--default=' arg on command line.
1168        default = GetOption('default')
1169        opts_dir = joinpath(main.root.abspath, 'build_opts')
1170        if default:
1171            default_vars_files = [joinpath(build_root, 'variables', default),
1172                                  joinpath(opts_dir, default)]
1173        else:
1174            default_vars_files = [joinpath(opts_dir, variant_dir)]
1175        existing_files = filter(isfile, default_vars_files)
1176        if existing_files:
1177            default_vars_file = existing_files[0]
1178            sticky_vars.files.append(default_vars_file)
1179            print "Variables file %s not found,\n  using defaults in %s" \
1180                  % (current_vars_file, default_vars_file)
1181        else:
1182            print "Error: cannot find variables file %s or " \
1183                  "default file(s) %s" \
1184                  % (current_vars_file, ' or '.join(default_vars_files))
1185            Exit(1)
1186
1187    # Apply current variable settings to env
1188    sticky_vars.Update(env)
1189
1190    help_texts["local_vars"] += \
1191        "Build variables for %s:\n" % variant_dir \
1192                 + sticky_vars.GenerateHelpText(env)
1193
1194    # Process variable settings.
1195
1196    if not have_fenv and env['USE_FENV']:
1197        print "Warning: <fenv.h> not available; " \
1198              "forcing USE_FENV to False in", variant_dir + "."
1199        env['USE_FENV'] = False
1200
1201    if not env['USE_FENV']:
1202        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1203        print "         FP results may deviate slightly from other platforms."
1204
1205    if not have_png and env['USE_PNG']:
1206        print "Warning: <png.h> not available; " \
1207              "forcing USE_PNG to False in", variant_dir + "."
1208        env['USE_PNG'] = False
1209
1210    if env['USE_PNG']:
1211        env.Append(LIBS=['png'])
1212
1213    if env['EFENCE']:
1214        env.Append(LIBS=['efence'])
1215
1216    if env['USE_KVM']:
1217        if not have_kvm:
1218            print "Warning: Can not enable KVM, host seems to lack KVM support"
1219            env['USE_KVM'] = False
1220        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1221            print "Info: KVM support disabled due to unsupported host and " \
1222                "target ISA combination"
1223            env['USE_KVM'] = False
1224
1225    if env['USE_TUNTAP']:
1226        if not have_tuntap:
1227            print "Warning: Can't connect EtherTap with a tap device."
1228            env['USE_TUNTAP'] = False
1229
1230    if env['BUILD_GPU']:
1231        env.Append(CPPDEFINES=['BUILD_GPU'])
1232
1233    # Warn about missing optional functionality
1234    if env['USE_KVM']:
1235        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1236            print "Warning: perf_event headers lack support for the " \
1237                "exclude_host attribute. KVM instruction counts will " \
1238                "be inaccurate."
1239
1240    # Save sticky variable settings back to current variables file
1241    sticky_vars.Save(current_vars_file, env)
1242
1243    if env['USE_SSE2']:
1244        env.Append(CCFLAGS=['-msse2'])
1245
1246    # The src/SConscript file sets up the build rules in 'env' according
1247    # to the configured variables.  It returns a list of environments,
1248    # one for each variant build (debug, opt, etc.)
1249    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1250
1251# base help text
1252Help('''
1253Usage: scons [scons options] [build variables] [target(s)]
1254
1255Extra scons options:
1256%(options)s
1257
1258Global build variables:
1259%(global_vars)s
1260
1261%(local_vars)s
1262''' % help_texts)
1263