SConstruct revision 12246
1955SN/A# -*- mode:python -*-
2955SN/A
312230Sgiacomo.travaglini@arm.com# Copyright (c) 2013, 2015-2017 ARM Limited
49812Sandreas.hansson@arm.com# All rights reserved.
59812Sandreas.hansson@arm.com#
69812Sandreas.hansson@arm.com# The license below extends only to copyright in the software and shall
79812Sandreas.hansson@arm.com# not be construed as granting a license to any other intellectual
89812Sandreas.hansson@arm.com# property including but not limited to intellectual property relating
99812Sandreas.hansson@arm.com# to a hardware implementation of the functionality of the software
109812Sandreas.hansson@arm.com# licensed hereunder.  You may use the software subject to the license
119812Sandreas.hansson@arm.com# terms below provided that you ensure that this notice is replicated
129812Sandreas.hansson@arm.com# unmodified and in its entirety in all distributions of the software,
139812Sandreas.hansson@arm.com# modified or unmodified, in source code or in binary form.
149812Sandreas.hansson@arm.com#
157816Ssteve.reinhardt@amd.com# Copyright (c) 2011 Advanced Micro Devices, Inc.
165871Snate@binkert.org# Copyright (c) 2009 The Hewlett-Packard Development Company
171762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
28955SN/A# contributors may be used to endorse or promote products derived from
29955SN/A# this software without specific prior written permission.
30955SN/A#
31955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422665Ssaidi@eecs.umich.edu#
432665Ssaidi@eecs.umich.edu# Authors: Steve Reinhardt
445863Snate@binkert.org#          Nathan Binkert
45955SN/A
46955SN/A###################################################
47955SN/A#
48955SN/A# SCons top-level build description (SConstruct) file.
49955SN/A#
508878Ssteve.reinhardt@amd.com# While in this directory ('gem5'), just type 'scons' to build the default
512632Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
528878Ssteve.reinhardt@amd.com# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532632Sstever@eecs.umich.edu# the optimized full-system version).
54955SN/A#
558878Ssteve.reinhardt@amd.com# You can build gem5 in a different directory as long as there is a
562632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572761Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582632Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612761Sstever@eecs.umich.edu#
622761Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
632761Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
648878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
658878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
662761Sstever@eecs.umich.edu#
672761Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
682761Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
692761Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
702761Sstever@eecs.umich.edu#   file.
718878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
728878Ssteve.reinhardt@amd.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732632Sstever@eecs.umich.edu#
742632Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
758878Ssteve.reinhardt@amd.com# 'gem5' directory (or use -u or -C to tell scons where to find this
768878Ssteve.reinhardt@amd.com# file), you can use 'scons -h' to print all the gem5-specific build
772632Sstever@eecs.umich.edu# options as well.
78955SN/A#
79955SN/A###################################################
80955SN/A
816654Snate@binkert.org# Global Python includes
8210196SCurtis.Dunham@arm.comimport itertools
83955SN/Aimport os
845396Ssaidi@eecs.umich.eduimport re
8511401Sandreas.sandberg@arm.comimport shutil
865863Snate@binkert.orgimport subprocess
875863Snate@binkert.orgimport sys
884202Sbinkertn@umich.edu
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
93955SN/A
946654Snate@binkert.org# SCons includes
955273Sstever@gmail.comimport SCons
965871Snate@binkert.orgimport SCons.Node
975273Sstever@gmail.com
986654Snate@binkert.orgfrom m5.util import compareVersions, readCommand
995396Ssaidi@eecs.umich.edu
1008120Sgblack@eecs.umich.eduhelp_texts = {
1018120Sgblack@eecs.umich.edu    "options" : "",
1028120Sgblack@eecs.umich.edu    "global_vars" : "",
1038120Sgblack@eecs.umich.edu    "local_vars" : ""
1048120Sgblack@eecs.umich.edu}
1058120Sgblack@eecs.umich.edu
1068120Sgblack@eecs.umich.eduExport("help_texts")
1078120Sgblack@eecs.umich.edu
1088879Ssteve.reinhardt@amd.com
1098879Ssteve.reinhardt@amd.com# There's a bug in scons in that (1) by default, the help texts from
1108879Ssteve.reinhardt@amd.com# AddOption() are supposed to be displayed when you type 'scons -h'
1118879Ssteve.reinhardt@amd.com# and (2) you can override the help displayed by 'scons -h' using the
1128879Ssteve.reinhardt@amd.com# Help() function, but these two features are incompatible: once
1138879Ssteve.reinhardt@amd.com# you've overridden the help text using Help(), there's no way to get
1148879Ssteve.reinhardt@amd.com# at the help texts from AddOptions.  See:
1158879Ssteve.reinhardt@amd.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1168879Ssteve.reinhardt@amd.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1178879Ssteve.reinhardt@amd.com# This hack lets us extract the help text from AddOptions and
1188879Ssteve.reinhardt@amd.com# re-inject it via Help().  Ideally someday this bug will be fixed and
1198879Ssteve.reinhardt@amd.com# we can just use AddOption directly.
1208879Ssteve.reinhardt@amd.comdef AddLocalOption(*args, **kwargs):
1218120Sgblack@eecs.umich.edu    col_width = 30
1228120Sgblack@eecs.umich.edu
1238120Sgblack@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
1358879Ssteve.reinhardt@amd.comAddLocalOption('--colors', dest='use_colors', action='store_true',
1368879Ssteve.reinhardt@amd.com               help="Add color to abbreviated scons output")
1378879Ssteve.reinhardt@amd.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1388879Ssteve.reinhardt@amd.com               help="Don't add color to abbreviated scons output")
13910458Sandreas.hansson@arm.comAddLocalOption('--with-cxx-config', dest='with_cxx_config',
14010458Sandreas.hansson@arm.com               action='store_true',
14110458Sandreas.hansson@arm.com               help="Build with support for C++-based configuration")
1428879Ssteve.reinhardt@amd.comAddLocalOption('--default', dest='default', type='string', action='store',
1438879Ssteve.reinhardt@amd.com               help='Override which build_opts file to use for defaults')
1448879Ssteve.reinhardt@amd.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1458879Ssteve.reinhardt@amd.com               help='Disable style checking hooks')
1469227Sandreas.hansson@arm.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1479227Sandreas.hansson@arm.com               help='Disable Link-Time Optimization for fast')
14812063Sgabeblack@google.comAddLocalOption('--force-lto', dest='force_lto', action='store_true',
14912063Sgabeblack@google.com               help='Use Link-Time Optimization instead of partial linking' +
15012063Sgabeblack@google.com                    ' when the compiler doesn\'t support using them together.')
1518879Ssteve.reinhardt@amd.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1528879Ssteve.reinhardt@amd.com               help='Update test reference outputs')
1538879Ssteve.reinhardt@amd.comAddLocalOption('--verbose', dest='verbose', action='store_true',
1548879Ssteve.reinhardt@amd.com               help='Print full tool command lines')
15510453SAndrew.Bardsley@arm.comAddLocalOption('--without-python', dest='without_python',
15610453SAndrew.Bardsley@arm.com               action='store_true',
15710453SAndrew.Bardsley@arm.com               help='Build without Python configuration support')
15810456SCurtis.Dunham@arm.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
15910456SCurtis.Dunham@arm.com               action='store_true',
16010456SCurtis.Dunham@arm.com               help='Disable linking against tcmalloc')
16110457Sandreas.hansson@arm.comAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
16210457Sandreas.hansson@arm.com               help='Build with Undefined Behavior Sanitizer if available')
16311342Sandreas.hansson@arm.comAddLocalOption('--with-asan', dest='with_asan', action='store_true',
16411342Sandreas.hansson@arm.com               help='Build with Address Sanitizer if available')
1658120Sgblack@eecs.umich.edu
16612063Sgabeblack@google.comif GetOption('no_lto') and GetOption('force_lto'):
16712063Sgabeblack@google.com    print '--no-lto and --force-lto are mutually exclusive'
16812063Sgabeblack@google.com    Exit(1)
16912063Sgabeblack@google.com
1705871Snate@binkert.org########################################################################
1715871Snate@binkert.org#
1726121Snate@binkert.org# Set up the main build environment.
1735871Snate@binkert.org#
1745871Snate@binkert.org########################################################################
1759926Sstan.czerniawski@arm.com
17612243Sgabeblack@google.commain = Environment()
1771533SN/A
17812246Sgabeblack@google.comfrom gem5_scons import Transform
17912246Sgabeblack@google.comfrom gem5_scons.util import get_termcap
18012246Sgabeblack@google.comtermcap = get_termcap()
18112246Sgabeblack@google.com
1829239Sandreas.hansson@arm.commain_dict_keys = main.Dictionary().keys()
1839239Sandreas.hansson@arm.com
1849239Sandreas.hansson@arm.com# Check that we have a C/C++ compiler
1859239Sandreas.hansson@arm.comif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1869239Sandreas.hansson@arm.com    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
1879239Sandreas.hansson@arm.com    Exit(1)
1889239Sandreas.hansson@arm.com
189955SN/A###################################################
190955SN/A#
1912632Sstever@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
1922632Sstever@eecs.umich.edu# the target(s).
193955SN/A#
194955SN/A###################################################
195955SN/A
196955SN/A# Find default configuration & binary.
1978878Ssteve.reinhardt@amd.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
198955SN/A
1992632Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
2002632Sstever@eecs.umich.edudef rfind(l, elt, offs = -1):
2012632Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
2022632Sstever@eecs.umich.edu        if l[i] == elt:
2032632Sstever@eecs.umich.edu            return i
2042632Sstever@eecs.umich.edu    raise ValueError, "element not found"
2052632Sstever@eecs.umich.edu
2068268Ssteve.reinhardt@amd.com# Take a list of paths (or SCons Nodes) and return a list with all
2078268Ssteve.reinhardt@amd.com# paths made absolute and ~-expanded.  Paths will be interpreted
2088268Ssteve.reinhardt@amd.com# relative to the launch directory unless a different root is provided
2098268Ssteve.reinhardt@amd.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
2108268Ssteve.reinhardt@amd.com    return [abspath(joinpath(root, expanduser(str(p))))
2118268Ssteve.reinhardt@amd.com            for p in path_list]
2128268Ssteve.reinhardt@amd.com
2132632Sstever@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
2142632Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
2152632Sstever@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2162632Sstever@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
2178268Ssteve.reinhardt@amd.com# follow 'build' in the build path.
2182632Sstever@eecs.umich.edu
2198268Ssteve.reinhardt@amd.com# The funky assignment to "[:]" is needed to replace the list contents
2208268Ssteve.reinhardt@amd.com# in place rather than reassign the symbol to a new list, which
2218268Ssteve.reinhardt@amd.com# doesn't work (obviously!).
2228268Ssteve.reinhardt@amd.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2233718Sstever@eecs.umich.edu
2242634Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
2252634Sstever@eecs.umich.edu# collected targets reference.
2265863Snate@binkert.orgvariant_paths = []
2272638Sstever@eecs.umich.edubuild_root = None
2288268Ssteve.reinhardt@amd.comfor t in BUILD_TARGETS:
2292632Sstever@eecs.umich.edu    path_dirs = t.split('/')
2302632Sstever@eecs.umich.edu    try:
2312632Sstever@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
2322632Sstever@eecs.umich.edu    except:
2332632Sstever@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
2341858SN/A        Exit(1)
2353716Sstever@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2362638Sstever@eecs.umich.edu    if not build_root:
2372638Sstever@eecs.umich.edu        build_root = this_build_root
2382638Sstever@eecs.umich.edu    else:
2392638Sstever@eecs.umich.edu        if this_build_root != build_root:
2402638Sstever@eecs.umich.edu            print "Error: build targets not under same build root\n"\
2412638Sstever@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
2422638Sstever@eecs.umich.edu            Exit(1)
2435863Snate@binkert.org    variant_path = joinpath('/',*path_dirs[:build_top+2])
2445863Snate@binkert.org    if variant_path not in variant_paths:
2455863Snate@binkert.org        variant_paths.append(variant_path)
246955SN/A
2475341Sstever@gmail.com# Make sure build_root exists (might not if this is the first build there)
2485341Sstever@gmail.comif not isdir(build_root):
2495863Snate@binkert.org    mkdir(build_root)
2507756SAli.Saidi@ARM.commain['BUILDROOT'] = build_root
2515341Sstever@gmail.com
2526121Snate@binkert.orgExport('main')
2534494Ssaidi@eecs.umich.edu
2546121Snate@binkert.orgmain.SConsignFile(joinpath(build_root, "sconsign"))
2551105SN/A
2562667Sstever@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
2572667Sstever@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
2582667Sstever@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
2592667Sstever@eecs.umich.edu# (soft) links work better.
2606121Snate@binkert.orgmain.SetOption('duplicate', 'soft-copy')
2612667Sstever@eecs.umich.edu
2625341Sstever@gmail.com#
2635863Snate@binkert.org# Set up global sticky variables... these are common to an entire build
2645341Sstever@gmail.com# tree (not specific to a particular build like ALPHA_SE)
2655341Sstever@gmail.com#
2665341Sstever@gmail.com
2678120Sgblack@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
2685341Sstever@gmail.com
2698120Sgblack@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2705341Sstever@gmail.com
2718120Sgblack@eecs.umich.eduglobal_vars.AddVariables(
2726121Snate@binkert.org    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2736121Snate@binkert.org    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2749396Sandreas.hansson@arm.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2755397Ssaidi@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
2765397Ssaidi@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2777727SAli.Saidi@ARM.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2788268Ssteve.reinhardt@amd.com    ('EXTRAS', 'Add extra directories to the compilation', '')
2796168Snate@binkert.org    )
2805341Sstever@gmail.com
2818120Sgblack@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
2828120Sgblack@eecs.umich.eduglobal_vars.Update(main)
2838120Sgblack@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
2846814Sgblack@eecs.umich.edu
2855863Snate@binkert.org# Save sticky variable settings back to current variables file
2868120Sgblack@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
2875341Sstever@gmail.com
2885863Snate@binkert.org# 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.
2906121Snate@binkert.orgbase_dir = main.srcdir.abspath
2916121Snate@binkert.orgif main['EXTRAS']:
2928268Ssteve.reinhardt@amd.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
2935742Snate@binkert.orgelse:
2945742Snate@binkert.org    extras_dir_list = []
2955341Sstever@gmail.com
2965742Snate@binkert.orgExport('base_dir')
2975742Snate@binkert.orgExport('extras_dir_list')
2985341Sstever@gmail.com
2996017Snate@binkert.org# the ext directory should be on the #includes path
3006121Snate@binkert.orgmain.Append(CPPPATH=[Dir('ext')])
3016017Snate@binkert.org
30212158Sandreas.sandberg@arm.com# Add shared top-level headers
30312158Sandreas.sandberg@arm.commain.Prepend(CPPPATH=Dir('include'))
30412158Sandreas.sandberg@arm.com
3058120Sgblack@eecs.umich.eduif GetOption('verbose'):
3067756SAli.Saidi@ARM.com    def MakeAction(action, string, *args, **kwargs):
3077756SAli.Saidi@ARM.com        return Action(action, *args, **kwargs)
3087756SAli.Saidi@ARM.comelse:
3097756SAli.Saidi@ARM.com    MakeAction = Action
3107816Ssteve.reinhardt@amd.com    main['CCCOMSTR']        = Transform("CC")
3117816Ssteve.reinhardt@amd.com    main['CXXCOMSTR']       = Transform("CXX")
3127816Ssteve.reinhardt@amd.com    main['ASCOMSTR']        = Transform("AS")
3137816Ssteve.reinhardt@amd.com    main['ARCOMSTR']        = Transform("AR", 0)
3147816Ssteve.reinhardt@amd.com    main['LINKCOMSTR']      = Transform("LINK", 0)
31511979Sgabeblack@google.com    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
3167816Ssteve.reinhardt@amd.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3177816Ssteve.reinhardt@amd.com    main['M4COMSTR']        = Transform("M4")
3187816Ssteve.reinhardt@amd.com    main['SHCCCOMSTR']      = Transform("SHCC")
3197816Ssteve.reinhardt@amd.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
3207756SAli.Saidi@ARM.comExport('MakeAction')
3217756SAli.Saidi@ARM.com
3229227Sandreas.hansson@arm.com# Initialize the Link-Time Optimization (LTO) flags
3239227Sandreas.hansson@arm.commain['LTO_CCFLAGS'] = []
3249227Sandreas.hansson@arm.commain['LTO_LDFLAGS'] = []
3259227Sandreas.hansson@arm.com
3269590Sandreas@sandberg.pp.se# According to the readme, tcmalloc works best if the compiler doesn't
3279590Sandreas@sandberg.pp.se# assume that we're using the builtin malloc and friends. These flags
3289590Sandreas@sandberg.pp.se# are compiler-specific, so we need to set them after we detect which
3299590Sandreas@sandberg.pp.se# compiler we're using.
3309590Sandreas@sandberg.pp.semain['TCMALLOC_CCFLAGS'] = []
3319590Sandreas@sandberg.pp.se
3326654Snate@binkert.orgCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3336654Snate@binkert.orgCXX_V = readCommand([main['CXX'],'-V'], exception=False)
3345871Snate@binkert.org
3356121Snate@binkert.orgmain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3368946Sandreas.hansson@arm.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
3379419Sandreas.hansson@arm.comif main['GCC'] + main['CLANG'] > 1:
3383940Ssaidi@eecs.umich.edu    print 'Error: How can we have two at the same time?'
3393918Ssaidi@eecs.umich.edu    Exit(1)
3403918Ssaidi@eecs.umich.edu
3411858SN/A# Set up default C++ compiler flags
3429556Sandreas.hansson@arm.comif main['GCC'] or main['CLANG']:
3439556Sandreas.hansson@arm.com    # As gcc and clang share many flags, do the common parts here
3449556Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-pipe'])
3459556Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
34611294Sandreas.hansson@arm.com    # Enable -Wall and -Wextra and then disable the few warnings that
34711294Sandreas.hansson@arm.com    # we consistently violate
34811294Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
34911294Sandreas.hansson@arm.com                         '-Wno-sign-compare', '-Wno-unused-parameter'])
35010878Sandreas.hansson@arm.com    # We always compile using C++11
35110878Sandreas.hansson@arm.com    main.Append(CXXFLAGS=['-std=c++11'])
35211811Sbaz21@cam.ac.uk    if sys.platform.startswith('freebsd'):
35311811Sbaz21@cam.ac.uk        main.Append(CCFLAGS=['-I/usr/local/include'])
35411811Sbaz21@cam.ac.uk        main.Append(CXXFLAGS=['-I/usr/local/include'])
35511982Sgabeblack@google.com
35611982Sgabeblack@google.com    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
35711982Sgabeblack@google.com    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
35811982Sgabeblack@google.com    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
35911992Sgabeblack@google.com    shared_partial_flags = ['-r', '-nostdlib']
36011982Sgabeblack@google.com    main.Append(PSHLINKFLAGS=shared_partial_flags)
36111982Sgabeblack@google.com    main.Append(PLINKFLAGS=shared_partial_flags)
3629556Sandreas.hansson@arm.comelse:
3639556Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
3649556Sandreas.hansson@arm.com    print "Don't know what compiler options to use for your compiler."
3659556Sandreas.hansson@arm.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
3669556Sandreas.hansson@arm.com    print termcap.Yellow + '       version:' + termcap.Normal,
3679556Sandreas.hansson@arm.com    if not CXX_version:
3689556Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
3699556Sandreas.hansson@arm.com               termcap.Normal
3709556Sandreas.hansson@arm.com    else:
3719556Sandreas.hansson@arm.com        print CXX_version.replace('\n', '<nl>')
3729556Sandreas.hansson@arm.com    print "       If you're trying to use a compiler other than GCC"
3739556Sandreas.hansson@arm.com    print "       or clang, there appears to be something wrong with your"
3749556Sandreas.hansson@arm.com    print "       environment."
3759556Sandreas.hansson@arm.com    print "       "
3769556Sandreas.hansson@arm.com    print "       If you are trying to use a compiler other than those listed"
3779556Sandreas.hansson@arm.com    print "       above you will need to ease fix SConstruct and "
3789556Sandreas.hansson@arm.com    print "       src/SConscript to support that compiler."
3799556Sandreas.hansson@arm.com    Exit(1)
3809556Sandreas.hansson@arm.com
3816121Snate@binkert.orgif main['GCC']:
38211500Sandreas.hansson@arm.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
38310238Sandreas.hansson@arm.com    # level of c++11 support. See
38410878Sandreas.hansson@arm.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
3859420Sandreas.hansson@arm.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
38611500Sandreas.hansson@arm.com    if compareVersions(gcc_version, "4.8") < 0:
38711500Sandreas.hansson@arm.com        print 'Error: gcc version 4.8 or newer required.'
3889420Sandreas.hansson@arm.com        print '       Installed version:', gcc_version
3899420Sandreas.hansson@arm.com        Exit(1)
3909420Sandreas.hansson@arm.com
3919420Sandreas.hansson@arm.com    main['GCC_VERSION'] = gcc_version
3929420Sandreas.hansson@arm.com
39312063Sgabeblack@google.com    if compareVersions(gcc_version, '4.9') >= 0:
39412063Sgabeblack@google.com        # Incremental linking with LTO is currently broken in gcc versions
39512063Sgabeblack@google.com        # 4.9 and above. A version where everything works completely hasn't
39612063Sgabeblack@google.com        # yet been identified.
39712063Sgabeblack@google.com        #
39812063Sgabeblack@google.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
39912063Sgabeblack@google.com        main['BROKEN_INCREMENTAL_LTO'] = True
40012063Sgabeblack@google.com    if compareVersions(gcc_version, '6.0') >= 0:
40112063Sgabeblack@google.com        # gcc versions 6.0 and greater accept an -flinker-output flag which
40212063Sgabeblack@google.com        # selects what type of output the linker should generate. This is
40312063Sgabeblack@google.com        # necessary for incremental lto to work, but is also broken in
40412063Sgabeblack@google.com        # current versions of gcc. It may not be necessary in future
40512063Sgabeblack@google.com        # versions. We add it here since it might be, and as a reminder that
40612063Sgabeblack@google.com        # it exists. It's excluded if lto is being forced.
40712063Sgabeblack@google.com        #
40812063Sgabeblack@google.com        # https://gcc.gnu.org/gcc-6/changes.html
40912063Sgabeblack@google.com        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
41012063Sgabeblack@google.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
41112063Sgabeblack@google.com        if not GetOption('force_lto'):
41212063Sgabeblack@google.com            main.Append(PSHLINKFLAGS='-flinker-output=rel')
41312063Sgabeblack@google.com            main.Append(PLINKFLAGS='-flinker-output=rel')
41412063Sgabeblack@google.com
41510264Sandreas.hansson@arm.com    # gcc from version 4.8 and above generates "rep; ret" instructions
41610264Sandreas.hansson@arm.com    # to avoid performance penalties on certain AMD chips. Older
41710264Sandreas.hansson@arm.com    # assemblers detect this as an error, "Error: expecting string
41810264Sandreas.hansson@arm.com    # instruction after `rep'"
41911925Sgabeblack@google.com    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
42011925Sgabeblack@google.com                                  '-o', '/dev/null'],
42111500Sandreas.hansson@arm.com                                 exception=False).split()
42210264Sandreas.hansson@arm.com
42311500Sandreas.hansson@arm.com    # version strings may contain extra distro-specific
42411500Sandreas.hansson@arm.com    # qualifiers, so play it safe and keep only what comes before
42511500Sandreas.hansson@arm.com    # the first hyphen
42611500Sandreas.hansson@arm.com    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
42710866Sandreas.hansson@arm.com
42811500Sandreas.hansson@arm.com    if not as_version or compareVersions(as_version, "2.23") < 0:
42911500Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + \
43011500Sandreas.hansson@arm.com            'Warning: This combination of gcc and binutils have' + \
43111500Sandreas.hansson@arm.com            ' known incompatibilities.\n' + \
43211500Sandreas.hansson@arm.com            '         If you encounter build problems, please update ' + \
43311500Sandreas.hansson@arm.com            'binutils to 2.23.' + \
43411500Sandreas.hansson@arm.com            termcap.Normal
43510264Sandreas.hansson@arm.com
43610457Sandreas.hansson@arm.com    # Make sure we warn if the user has requested to compile with the
43710457Sandreas.hansson@arm.com    # Undefined Benahvior Sanitizer and this version of gcc does not
43810457Sandreas.hansson@arm.com    # support it.
43910457Sandreas.hansson@arm.com    if GetOption('with_ubsan') and \
44010457Sandreas.hansson@arm.com            compareVersions(gcc_version, '4.9') < 0:
44110457Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + \
44210457Sandreas.hansson@arm.com            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
44310457Sandreas.hansson@arm.com            termcap.Normal
44410457Sandreas.hansson@arm.com
44512063Sgabeblack@google.com    disable_lto = GetOption('no_lto')
44612063Sgabeblack@google.com    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
44712063Sgabeblack@google.com            not GetOption('force_lto'):
44812063Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + \
44912063Sgabeblack@google.com            'Warning: Your compiler doesn\'t support incremental linking' + \
45012063Sgabeblack@google.com            ' and lto at the same time, so lto is being disabled. To force' + \
45112063Sgabeblack@google.com            ' lto on anyway, use the --force-lto option. That will disable' + \
45212063Sgabeblack@google.com            ' partial linking.' + \
45312063Sgabeblack@google.com            termcap.Normal
45412063Sgabeblack@google.com        disable_lto = True
45512063Sgabeblack@google.com
45610238Sandreas.hansson@arm.com    # Add the appropriate Link-Time Optimization (LTO) flags
45710238Sandreas.hansson@arm.com    # unless LTO is explicitly turned off. Note that these flags
45810238Sandreas.hansson@arm.com    # are only used by the fast target.
45912063Sgabeblack@google.com    if not disable_lto:
46010238Sandreas.hansson@arm.com        # Pass the LTO flag when compiling to produce GIMPLE
46110238Sandreas.hansson@arm.com        # output, we merely create the flags here and only append
46210416Sandreas.hansson@arm.com        # them later
46310238Sandreas.hansson@arm.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4649227Sandreas.hansson@arm.com
46510238Sandreas.hansson@arm.com        # Use the same amount of jobs for LTO as we are running
46610416Sandreas.hansson@arm.com        # scons with
46710416Sandreas.hansson@arm.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4689227Sandreas.hansson@arm.com
4699590Sandreas@sandberg.pp.se    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4709590Sandreas@sandberg.pp.se                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4719590Sandreas@sandberg.pp.se
47211497SMatteo.Andreozzi@arm.com    # add option to check for undeclared overrides
47311497SMatteo.Andreozzi@arm.com    if compareVersions(gcc_version, "5.0") > 0:
47411497SMatteo.Andreozzi@arm.com        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
47511497SMatteo.Andreozzi@arm.com
4768737Skoansin.tan@gmail.comelif main['CLANG']:
47710878Sandreas.hansson@arm.com    # Check for a supported version of clang, >= 3.1 is needed to
47811500Sandreas.hansson@arm.com    # support similar features as gcc 4.8. See
4799420Sandreas.hansson@arm.com    # http://clang.llvm.org/cxx_status.html for details
4808737Skoansin.tan@gmail.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
48110106SMitch.Hayenga@arm.com    clang_version_match = clang_version_re.search(CXX_version)
4828737Skoansin.tan@gmail.com    if (clang_version_match):
4838737Skoansin.tan@gmail.com        clang_version = clang_version_match.groups()[0]
48410878Sandreas.hansson@arm.com        if compareVersions(clang_version, "3.1") < 0:
48510878Sandreas.hansson@arm.com            print 'Error: clang version 3.1 or newer required.'
4868737Skoansin.tan@gmail.com            print '       Installed version:', clang_version
4878737Skoansin.tan@gmail.com            Exit(1)
4888737Skoansin.tan@gmail.com    else:
4898737Skoansin.tan@gmail.com        print 'Error: Unable to determine clang version.'
4908737Skoansin.tan@gmail.com        Exit(1)
4918737Skoansin.tan@gmail.com
49211294Sandreas.hansson@arm.com    # clang has a few additional warnings that we disable, extraneous
4939556Sandreas.hansson@arm.com    # parantheses are allowed due to Ruby's printing of the AST,
4949556Sandreas.hansson@arm.com    # finally self assignments are allowed as the generated CPU code
4959556Sandreas.hansson@arm.com    # is relying on this
49611294Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wno-parentheses',
49710278SAndreas.Sandberg@ARM.com                         '-Wno-self-assign',
49810278SAndreas.Sandberg@ARM.com                         # Some versions of libstdc++ (4.8?) seem to
49910278SAndreas.Sandberg@ARM.com                         # use struct hash and class hash
50010278SAndreas.Sandberg@ARM.com                         # interchangeably.
50110278SAndreas.Sandberg@ARM.com                         '-Wno-mismatched-tags',
50210278SAndreas.Sandberg@ARM.com                         ])
5039556Sandreas.hansson@arm.com
5049590Sandreas@sandberg.pp.se    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5059590Sandreas@sandberg.pp.se
5069420Sandreas.hansson@arm.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5079846Sandreas.hansson@arm.com    # opposed to libstdc++, as the later is dated.
5089846Sandreas.hansson@arm.com    if sys.platform == "darwin":
5099846Sandreas.hansson@arm.com        main.Append(CXXFLAGS=['-stdlib=libc++'])
5109846Sandreas.hansson@arm.com        main.Append(LIBS=['c++'])
5118946Sandreas.hansson@arm.com
51211811Sbaz21@cam.ac.uk    # On FreeBSD we need libthr.
51311811Sbaz21@cam.ac.uk    if sys.platform.startswith('freebsd'):
51411811Sbaz21@cam.ac.uk        main.Append(LIBS=['thr'])
51511811Sbaz21@cam.ac.uk
5163918Ssaidi@eecs.umich.eduelse:
5179068SAli.Saidi@ARM.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5189068SAli.Saidi@ARM.com    print "Don't know what compiler options to use for your compiler."
5199068SAli.Saidi@ARM.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5209068SAli.Saidi@ARM.com    print termcap.Yellow + '       version:' + termcap.Normal,
5219068SAli.Saidi@ARM.com    if not CXX_version:
5229068SAli.Saidi@ARM.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5239068SAli.Saidi@ARM.com               termcap.Normal
5249068SAli.Saidi@ARM.com    else:
5259068SAli.Saidi@ARM.com        print CXX_version.replace('\n', '<nl>')
5269419Sandreas.hansson@arm.com    print "       If you're trying to use a compiler other than GCC"
5279068SAli.Saidi@ARM.com    print "       or clang, there appears to be something wrong with your"
5289068SAli.Saidi@ARM.com    print "       environment."
5299068SAli.Saidi@ARM.com    print "       "
5309068SAli.Saidi@ARM.com    print "       If you are trying to use a compiler other than those listed"
5319068SAli.Saidi@ARM.com    print "       above you will need to ease fix SConstruct and "
5329068SAli.Saidi@ARM.com    print "       src/SConscript to support that compiler."
5333918Ssaidi@eecs.umich.edu    Exit(1)
5343918Ssaidi@eecs.umich.edu
5356157Snate@binkert.org# Set up common yacc/bison flags (needed for Ruby)
5366157Snate@binkert.orgmain['YACCFLAGS'] = '-d'
5376157Snate@binkert.orgmain['YACCHXXFILESUFFIX'] = '.hh'
5386157Snate@binkert.org
5395397Ssaidi@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
5405397Ssaidi@eecs.umich.edu# extra 'qdo' every time we run scons.
5416121Snate@binkert.orgif main['BATCH']:
5426121Snate@binkert.org    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5436121Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5446121Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5456121Snate@binkert.org    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5466121Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5475397Ssaidi@eecs.umich.edu
5481851SN/Aif sys.platform == 'cygwin':
5491851SN/A    # cygwin has some header file issues...
5507739Sgblack@eecs.umich.edu    main.Append(CCFLAGS=["-Wno-uninitialized"])
551955SN/A
5529396Sandreas.hansson@arm.com# Check for the protobuf compiler
5539396Sandreas.hansson@arm.comprotoc_version = readCommand([main['PROTOC'], '--version'],
5549396Sandreas.hansson@arm.com                             exception='').split()
5559396Sandreas.hansson@arm.com
5569396Sandreas.hansson@arm.com# First two words should be "libprotoc x.y.z"
5579396Sandreas.hansson@arm.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
5589396Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + \
5599396Sandreas.hansson@arm.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
5609396Sandreas.hansson@arm.com        '         Please install protobuf-compiler for tracing support.' + \
5619396Sandreas.hansson@arm.com        termcap.Normal
5629396Sandreas.hansson@arm.com    main['PROTOC'] = False
5639396Sandreas.hansson@arm.comelse:
5649396Sandreas.hansson@arm.com    # Based on the availability of the compress stream wrappers,
5659396Sandreas.hansson@arm.com    # require 2.1.0
5669396Sandreas.hansson@arm.com    min_protoc_version = '2.1.0'
5679396Sandreas.hansson@arm.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
5689477Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + \
5699477Sandreas.hansson@arm.com            'Warning: protoc version', min_protoc_version, \
5709477Sandreas.hansson@arm.com            'or newer required.\n' + \
5719477Sandreas.hansson@arm.com            '         Installed version:', protoc_version[1], \
5729477Sandreas.hansson@arm.com            termcap.Normal
5739477Sandreas.hansson@arm.com        main['PROTOC'] = False
5749477Sandreas.hansson@arm.com    else:
5759477Sandreas.hansson@arm.com        # Attempt to determine the appropriate include path and
5769477Sandreas.hansson@arm.com        # library path using pkg-config, that means we also need to
5779477Sandreas.hansson@arm.com        # check for pkg-config. Note that it is possible to use
5789477Sandreas.hansson@arm.com        # protobuf without the involvement of pkg-config. Later on we
5799477Sandreas.hansson@arm.com        # check go a library config check and at that point the test
5809477Sandreas.hansson@arm.com        # will fail if libprotobuf cannot be found.
5819477Sandreas.hansson@arm.com        if readCommand(['pkg-config', '--version'], exception=''):
5829477Sandreas.hansson@arm.com            try:
5839477Sandreas.hansson@arm.com                # Attempt to establish what linking flags to add for protobuf
5849477Sandreas.hansson@arm.com                # using pkg-config
5859477Sandreas.hansson@arm.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
5869477Sandreas.hansson@arm.com            except:
5879477Sandreas.hansson@arm.com                print termcap.Yellow + termcap.Bold + \
5889477Sandreas.hansson@arm.com                    'Warning: pkg-config could not get protobuf flags.' + \
5899477Sandreas.hansson@arm.com                    termcap.Normal
5909396Sandreas.hansson@arm.com
5912667Sstever@eecs.umich.edu
59210710Sandreas.hansson@arm.com# Check for 'timeout' from GNU coreutils. If present, regressions will
59310710Sandreas.hansson@arm.com# be run with a time limit. We require version 8.13 since we rely on
59410710Sandreas.hansson@arm.com# support for the '--foreground' option.
59511811Sbaz21@cam.ac.ukif sys.platform.startswith('freebsd'):
59611811Sbaz21@cam.ac.uk    timeout_lines = readCommand(['gtimeout', '--version'],
59711811Sbaz21@cam.ac.uk                                exception='').splitlines()
59811811Sbaz21@cam.ac.ukelse:
59911811Sbaz21@cam.ac.uk    timeout_lines = readCommand(['timeout', '--version'],
60011811Sbaz21@cam.ac.uk                                exception='').splitlines()
60110710Sandreas.hansson@arm.com# Get the first line and tokenize it
60210710Sandreas.hansson@arm.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
60310710Sandreas.hansson@arm.commain['TIMEOUT'] =  timeout_version and \
60410710Sandreas.hansson@arm.com    compareVersions(timeout_version[-1], '8.13') >= 0
60510384SCurtis.Dunham@arm.com
6069986Sandreas@sandberg.pp.se# Add a custom Check function to test for structure members.
6079986Sandreas@sandberg.pp.sedef CheckMember(context, include, decl, member, include_quotes="<>"):
6089986Sandreas@sandberg.pp.se    context.Message("Checking for member %s in %s..." %
6099986Sandreas@sandberg.pp.se                    (member, decl))
6109986Sandreas@sandberg.pp.se    text = """
6119986Sandreas@sandberg.pp.se#include %(header)s
6129986Sandreas@sandberg.pp.seint main(){
6139986Sandreas@sandberg.pp.se  %(decl)s test;
6149986Sandreas@sandberg.pp.se  (void)test.%(member)s;
6159986Sandreas@sandberg.pp.se  return 0;
6169986Sandreas@sandberg.pp.se};
6179986Sandreas@sandberg.pp.se""" % { "header" : include_quotes[0] + include + include_quotes[1],
6189986Sandreas@sandberg.pp.se        "decl" : decl,
6199986Sandreas@sandberg.pp.se        "member" : member,
6209986Sandreas@sandberg.pp.se        }
6219986Sandreas@sandberg.pp.se
6229986Sandreas@sandberg.pp.se    ret = context.TryCompile(text, extension=".cc")
6239986Sandreas@sandberg.pp.se    context.Result(ret)
6249986Sandreas@sandberg.pp.se    return ret
6259986Sandreas@sandberg.pp.se
6262638Sstever@eecs.umich.edu# Platform-specific configuration.  Note again that we assume that all
6272638Sstever@eecs.umich.edu# builds under a given build root run on the same host platform.
6286121Snate@binkert.orgconf = Configure(main,
6293716Sstever@eecs.umich.edu                 conf_dir = joinpath(build_root, '.scons_config'),
6305522Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
6319986Sandreas@sandberg.pp.se                 custom_tests = {
6329986Sandreas@sandberg.pp.se        'CheckMember' : CheckMember,
6339986Sandreas@sandberg.pp.se        })
6345522Snate@binkert.org
6355227Ssaidi@eecs.umich.edu# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6365227Ssaidi@eecs.umich.edutry:
6375227Ssaidi@eecs.umich.edu    import platform
6385227Ssaidi@eecs.umich.edu    uname = platform.uname()
6396654Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6406654Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6417769SAli.Saidi@ARM.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
6427769SAli.Saidi@ARM.com            main.Append(CFLAGS=['-arch', 'x86_64'])
6437769SAli.Saidi@ARM.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6447769SAli.Saidi@ARM.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
6455227Ssaidi@eecs.umich.eduexcept:
6465227Ssaidi@eecs.umich.edu    pass
6475227Ssaidi@eecs.umich.edu
6485204Sstever@gmail.com# Recent versions of scons substitute a "Null" object for Configure()
6495204Sstever@gmail.com# when configuration isn't necessary, e.g., if the "--help" option is
6505204Sstever@gmail.com# present.  Unfortuantely this Null object always returns false,
6515204Sstever@gmail.com# breaking all our configuration checks.  We replace it with our own
6525204Sstever@gmail.com# more optimistic null object that returns True instead.
6535204Sstever@gmail.comif not conf:
6545204Sstever@gmail.com    def NullCheck(*args, **kwargs):
6555204Sstever@gmail.com        return True
6565204Sstever@gmail.com
6575204Sstever@gmail.com    class NullConf:
6585204Sstever@gmail.com        def __init__(self, env):
6595204Sstever@gmail.com            self.env = env
6605204Sstever@gmail.com        def Finish(self):
6615204Sstever@gmail.com            return self.env
6625204Sstever@gmail.com        def __getattr__(self, mname):
6635204Sstever@gmail.com            return NullCheck
6645204Sstever@gmail.com
6656121Snate@binkert.org    conf = NullConf(main)
6665204Sstever@gmail.com
6677727SAli.Saidi@ARM.com# Cache build files in the supplied directory.
6687727SAli.Saidi@ARM.comif main['M5_BUILD_CACHE']:
6697727SAli.Saidi@ARM.com    print 'Using build cache located at', main['M5_BUILD_CACHE']
6707727SAli.Saidi@ARM.com    CacheDir(main['M5_BUILD_CACHE'])
6717727SAli.Saidi@ARM.com
67211988Sandreas.sandberg@arm.commain['USE_PYTHON'] = not GetOption('without_python')
67311988Sandreas.sandberg@arm.comif main['USE_PYTHON']:
67410453SAndrew.Bardsley@arm.com    # Find Python include and library directories for embedding the
67510453SAndrew.Bardsley@arm.com    # interpreter. We rely on python-config to resolve the appropriate
67610453SAndrew.Bardsley@arm.com    # includes and linker flags. ParseConfig does not seem to understand
67710453SAndrew.Bardsley@arm.com    # the more exotic linker flags such as -Xlinker and -export-dynamic so
67810453SAndrew.Bardsley@arm.com    # we add them explicitly below. If you want to link in an alternate
67910453SAndrew.Bardsley@arm.com    # version of python, see above for instructions on how to invoke
68010453SAndrew.Bardsley@arm.com    # scons with the appropriate PATH set.
68110453SAndrew.Bardsley@arm.com    #
68210453SAndrew.Bardsley@arm.com    # First we check if python2-config exists, else we use python-config
68310453SAndrew.Bardsley@arm.com    python_config = readCommand(['which', 'python2-config'],
68410160Sandreas.hansson@arm.com                                exception='').strip()
68510453SAndrew.Bardsley@arm.com    if not os.path.exists(python_config):
68610453SAndrew.Bardsley@arm.com        python_config = readCommand(['which', 'python-config'],
68710453SAndrew.Bardsley@arm.com                                    exception='').strip()
68810453SAndrew.Bardsley@arm.com    py_includes = readCommand([python_config, '--includes'],
68910453SAndrew.Bardsley@arm.com                              exception='').split()
69010453SAndrew.Bardsley@arm.com    # Strip the -I from the include folders before adding them to the
69110453SAndrew.Bardsley@arm.com    # CPPPATH
69210453SAndrew.Bardsley@arm.com    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
6939812Sandreas.hansson@arm.com
69410453SAndrew.Bardsley@arm.com    # Read the linker flags and split them into libraries and other link
69510453SAndrew.Bardsley@arm.com    # flags. The libraries are added later through the call the CheckLib.
69610453SAndrew.Bardsley@arm.com    py_ld_flags = readCommand([python_config, '--ldflags'],
69710453SAndrew.Bardsley@arm.com        exception='').split()
69810453SAndrew.Bardsley@arm.com    py_libs = []
69910453SAndrew.Bardsley@arm.com    for lib in py_ld_flags:
70010453SAndrew.Bardsley@arm.com         if not lib.startswith('-l'):
70110453SAndrew.Bardsley@arm.com             main.Append(LINKFLAGS=[lib])
70210453SAndrew.Bardsley@arm.com         else:
70310453SAndrew.Bardsley@arm.com             lib = lib[2:]
70410453SAndrew.Bardsley@arm.com             if lib not in py_libs:
70510453SAndrew.Bardsley@arm.com                 py_libs.append(lib)
7067727SAli.Saidi@ARM.com
70710453SAndrew.Bardsley@arm.com    # verify that this stuff works
70810453SAndrew.Bardsley@arm.com    if not conf.CheckHeader('Python.h', '<>'):
70910453SAndrew.Bardsley@arm.com        print "Error: can't find Python.h header in", py_includes
71010453SAndrew.Bardsley@arm.com        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
71110453SAndrew.Bardsley@arm.com        Exit(1)
7123118Sstever@eecs.umich.edu
71310453SAndrew.Bardsley@arm.com    for lib in py_libs:
71410453SAndrew.Bardsley@arm.com        if not conf.CheckLib(lib):
71510453SAndrew.Bardsley@arm.com            print "Error: can't find library %s required by python" % lib
71610453SAndrew.Bardsley@arm.com            Exit(1)
7173118Sstever@eecs.umich.edu
7183483Ssaidi@eecs.umich.edu# On Solaris you need to use libsocket for socket ops
7193494Ssaidi@eecs.umich.eduif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7203494Ssaidi@eecs.umich.edu   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7213483Ssaidi@eecs.umich.edu       print "Can't find library with socket calls (e.g. accept())"
7223483Ssaidi@eecs.umich.edu       Exit(1)
7233483Ssaidi@eecs.umich.edu
7243053Sstever@eecs.umich.edu# Check for zlib.  If the check passes, libz will be automatically
7253053Sstever@eecs.umich.edu# added to the LIBS environment variable.
7263918Ssaidi@eecs.umich.eduif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
7273053Sstever@eecs.umich.edu    print 'Error: did not find needed zlib compression library '\
7283053Sstever@eecs.umich.edu          'and/or zlib.h header file.'
7293053Sstever@eecs.umich.edu    print '       Please install zlib and try again.'
7303053Sstever@eecs.umich.edu    Exit(1)
7313053Sstever@eecs.umich.edu
7329396Sandreas.hansson@arm.com# If we have the protobuf compiler, also make sure we have the
7339396Sandreas.hansson@arm.com# development libraries. If the check passes, libprotobuf will be
7349396Sandreas.hansson@arm.com# automatically added to the LIBS environment variable. After
7359396Sandreas.hansson@arm.com# this, we can use the HAVE_PROTOBUF flag to determine if we have
7369396Sandreas.hansson@arm.com# got both protoc and libprotobuf available.
7379396Sandreas.hansson@arm.commain['HAVE_PROTOBUF'] = main['PROTOC'] and \
7389396Sandreas.hansson@arm.com    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
7399396Sandreas.hansson@arm.com                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
7409396Sandreas.hansson@arm.com
7419477Sandreas.hansson@arm.com# If we have the compiler but not the library, print another warning.
7429396Sandreas.hansson@arm.comif main['PROTOC'] and not main['HAVE_PROTOBUF']:
7439477Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + \
7449477Sandreas.hansson@arm.com        'Warning: did not find protocol buffer library and/or headers.\n' + \
7459477Sandreas.hansson@arm.com    '       Please install libprotobuf-dev for tracing support.' + \
7469477Sandreas.hansson@arm.com    termcap.Normal
7479396Sandreas.hansson@arm.com
7487840Snate@binkert.org# Check for librt.
7497865Sgblack@eecs.umich.eduhave_posix_clock = \
7507865Sgblack@eecs.umich.edu    conf.CheckLibWithHeader(None, 'time.h', 'C',
7517865Sgblack@eecs.umich.edu                            'clock_nanosleep(0,0,NULL,NULL);') or \
7527865Sgblack@eecs.umich.edu    conf.CheckLibWithHeader('rt', 'time.h', 'C',
7537865Sgblack@eecs.umich.edu                            'clock_nanosleep(0,0,NULL,NULL);')
7547840Snate@binkert.org
7559900Sandreas@sandberg.pp.sehave_posix_timers = \
7569900Sandreas@sandberg.pp.se    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
7579900Sandreas@sandberg.pp.se                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
7589900Sandreas@sandberg.pp.se
75910456SCurtis.Dunham@arm.comif not GetOption('without_tcmalloc'):
76010456SCurtis.Dunham@arm.com    if conf.CheckLib('tcmalloc'):
76110456SCurtis.Dunham@arm.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
76210456SCurtis.Dunham@arm.com    elif conf.CheckLib('tcmalloc_minimal'):
76310456SCurtis.Dunham@arm.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
76410456SCurtis.Dunham@arm.com    else:
76510456SCurtis.Dunham@arm.com        print termcap.Yellow + termcap.Bold + \
76610456SCurtis.Dunham@arm.com              "You can get a 12% performance improvement by "\
76710456SCurtis.Dunham@arm.com              "installing tcmalloc (libgoogle-perftools-dev package "\
76810456SCurtis.Dunham@arm.com              "on Ubuntu or RedHat)." + termcap.Normal
7699045SAli.Saidi@ARM.com
77011235Sandreas.sandberg@arm.com
77111235Sandreas.sandberg@arm.com# Detect back trace implementations. The last implementation in the
77211235Sandreas.sandberg@arm.com# list will be used by default.
77311235Sandreas.sandberg@arm.combacktrace_impls = [ "none" ]
77411235Sandreas.sandberg@arm.com
77511235Sandreas.sandberg@arm.comif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
77611235Sandreas.sandberg@arm.com                           'backtrace_symbols_fd((void*)0, 0, 0);'):
77711235Sandreas.sandberg@arm.com    backtrace_impls.append("glibc")
77811811Sbaz21@cam.ac.ukelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
77911811Sbaz21@cam.ac.uk                           'backtrace_symbols_fd((void*)0, 0, 0);'):
78011811Sbaz21@cam.ac.uk    # NetBSD and FreeBSD need libexecinfo.
78111811Sbaz21@cam.ac.uk    backtrace_impls.append("glibc")
78211811Sbaz21@cam.ac.uk    main.Append(LIBS=['execinfo'])
78311235Sandreas.sandberg@arm.com
78411235Sandreas.sandberg@arm.comif backtrace_impls[-1] == "none":
78511235Sandreas.sandberg@arm.com    default_backtrace_impl = "none"
78611235Sandreas.sandberg@arm.com    print termcap.Yellow + termcap.Bold + \
78711235Sandreas.sandberg@arm.com        "No suitable back trace implementation found." + \
78811235Sandreas.sandberg@arm.com        termcap.Normal
78911235Sandreas.sandberg@arm.com
7907840Snate@binkert.orgif not have_posix_clock:
7917840Snate@binkert.org    print "Can't find library for POSIX clocks."
7927840Snate@binkert.org
7931858SN/A# Check for <fenv.h> (C99 FP environment control)
7941858SN/Ahave_fenv = conf.CheckHeader('fenv.h', '<>')
7951858SN/Aif not have_fenv:
7961858SN/A    print "Warning: Header file <fenv.h> not found."
7971858SN/A    print "         This host has no IEEE FP rounding mode control."
7981858SN/A
79912230Sgiacomo.travaglini@arm.com# Check for <png.h> (libpng library needed if wanting to dump
80012230Sgiacomo.travaglini@arm.com# frame buffer image in png format)
80112230Sgiacomo.travaglini@arm.comhave_png = conf.CheckHeader('png.h', '<>')
80212230Sgiacomo.travaglini@arm.comif not have_png:
80312230Sgiacomo.travaglini@arm.com    print "Warning: Header file <png.h> not found."
80412230Sgiacomo.travaglini@arm.com    print "         This host has no libpng library."
80512230Sgiacomo.travaglini@arm.com    print "         Disabling support for PNG framebuffers."
80612230Sgiacomo.travaglini@arm.com
8079903Sandreas.hansson@arm.com# Check if we should enable KVM-based hardware virtualization. The API
8089903Sandreas.hansson@arm.com# we rely on exists since version 2.6.36 of the kernel, but somehow
8099903Sandreas.hansson@arm.com# the KVM_API_VERSION does not reflect the change. We test for one of
8109903Sandreas.hansson@arm.com# the types as a fall back.
81110841Sandreas.sandberg@arm.comhave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
8129651SAndreas.Sandberg@ARM.comif not have_kvm:
8139903Sandreas.hansson@arm.com    print "Info: Compatible header file <linux/kvm.h> not found, " \
8149651SAndreas.Sandberg@ARM.com        "disabling KVM support."
8159651SAndreas.Sandberg@ARM.com
81612056Sgabeblack@google.com# Check if the TUN/TAP driver is available.
81712056Sgabeblack@google.comhave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
81812056Sgabeblack@google.comif not have_tuntap:
81912056Sgabeblack@google.com    print "Info: Compatible header file <linux/if_tun.h> not found."
82012056Sgabeblack@google.com
82110841Sandreas.sandberg@arm.com# x86 needs support for xsave. We test for the structure here since we
82210841Sandreas.sandberg@arm.com# won't be able to run new tests by the time we know which ISA we're
82310841Sandreas.sandberg@arm.com# targeting.
82410841Sandreas.sandberg@arm.comhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
82510841Sandreas.sandberg@arm.com                                    '#include <linux/kvm.h>') != 0
82610841Sandreas.sandberg@arm.com
8279651SAndreas.Sandberg@ARM.com# Check if the requested target ISA is compatible with the host
8289651SAndreas.Sandberg@ARM.comdef is_isa_kvm_compatible(isa):
8299651SAndreas.Sandberg@ARM.com    try:
8309651SAndreas.Sandberg@ARM.com        import platform
8319651SAndreas.Sandberg@ARM.com        host_isa = platform.machine()
8329651SAndreas.Sandberg@ARM.com    except:
8339651SAndreas.Sandberg@ARM.com        print "Warning: Failed to determine host ISA."
8349651SAndreas.Sandberg@ARM.com        return False
8359651SAndreas.Sandberg@ARM.com
83610841Sandreas.sandberg@arm.com    if not have_posix_timers:
83710841Sandreas.sandberg@arm.com        print "Warning: Can not enable KVM, host seems to lack support " \
83810841Sandreas.sandberg@arm.com            "for POSIX timers"
83910841Sandreas.sandberg@arm.com        return False
84010841Sandreas.sandberg@arm.com
84110841Sandreas.sandberg@arm.com    if isa == "arm":
84210860Sandreas.sandberg@arm.com        return host_isa in ( "armv7l", "aarch64" )
84310841Sandreas.sandberg@arm.com    elif isa == "x86":
84410841Sandreas.sandberg@arm.com        if host_isa != "x86_64":
84510841Sandreas.sandberg@arm.com            return False
84610841Sandreas.sandberg@arm.com
84710841Sandreas.sandberg@arm.com        if not have_kvm_xsave:
84810841Sandreas.sandberg@arm.com            print "KVM on x86 requires xsave support in kernel headers."
84910841Sandreas.sandberg@arm.com            return False
85010841Sandreas.sandberg@arm.com
85110841Sandreas.sandberg@arm.com        return True
85210841Sandreas.sandberg@arm.com    else:
85310841Sandreas.sandberg@arm.com        return False
8549651SAndreas.Sandberg@ARM.com
8559651SAndreas.Sandberg@ARM.com
8569986Sandreas@sandberg.pp.se# Check if the exclude_host attribute is available. We want this to
8579986Sandreas@sandberg.pp.se# get accurate instruction counts in KVM.
8589986Sandreas@sandberg.pp.semain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
8599986Sandreas@sandberg.pp.se    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
8609986Sandreas@sandberg.pp.se
8619986Sandreas@sandberg.pp.se
8625863Snate@binkert.org######################################################################
8635863Snate@binkert.org#
8645863Snate@binkert.org# Finish the configuration
8655863Snate@binkert.org#
8666121Snate@binkert.orgmain = conf.Finish()
8671858SN/A
8685863Snate@binkert.org######################################################################
8695863Snate@binkert.org#
8705863Snate@binkert.org# Collect all non-global variables
8715863Snate@binkert.org#
8725863Snate@binkert.org
8732139SN/A# Define the universe of supported ISAs
8744202Sbinkertn@umich.eduall_isa_list = [ ]
87511308Santhony.gutierrez@amd.comall_gpu_isa_list = [ ]
8764202Sbinkertn@umich.eduExport('all_isa_list')
87711308Santhony.gutierrez@amd.comExport('all_gpu_isa_list')
8782139SN/A
8796994Snate@binkert.orgclass CpuModel(object):
8806994Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
8816994Snate@binkert.org    know about a particular CPU model.'''
8826994Snate@binkert.org
8836994Snate@binkert.org    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
8846994Snate@binkert.org    dict = {}
8856994Snate@binkert.org
8866994Snate@binkert.org    # Constructor.  Automatically adds models to CpuModel.dict.
88710319SAndreas.Sandberg@ARM.com    def __init__(self, name, default=False):
8886994Snate@binkert.org        self.name = name           # name of model
8896994Snate@binkert.org
8906994Snate@binkert.org        # This cpu is enabled by default
8916994Snate@binkert.org        self.default = default
8926994Snate@binkert.org
8936994Snate@binkert.org        # Add self to dict
8946994Snate@binkert.org        if name in CpuModel.dict:
8956994Snate@binkert.org            raise AttributeError, "CpuModel '%s' already registered" % name
8966994Snate@binkert.org        CpuModel.dict[name] = self
8976994Snate@binkert.org
8986994Snate@binkert.orgExport('CpuModel')
8992155SN/A
9005863Snate@binkert.org# Sticky variables get saved in the variables file so they persist from
9011869SN/A# one invocation to the next (unless overridden, in which case the new
9021869SN/A# value becomes sticky).
9035863Snate@binkert.orgsticky_vars = Variables(args=ARGUMENTS)
9045863Snate@binkert.orgExport('sticky_vars')
9054202Sbinkertn@umich.edu
9066108Snate@binkert.org# Sticky variables that should be exported
9076108Snate@binkert.orgexport_vars = []
9086108Snate@binkert.orgExport('export_vars')
9096108Snate@binkert.org
9109219Spower.jg@gmail.com# For Ruby
9119219Spower.jg@gmail.comall_protocols = []
9129219Spower.jg@gmail.comExport('all_protocols')
9139219Spower.jg@gmail.comprotocol_dirs = []
9149219Spower.jg@gmail.comExport('protocol_dirs')
9159219Spower.jg@gmail.comslicc_includes = []
9169219Spower.jg@gmail.comExport('slicc_includes')
9179219Spower.jg@gmail.com
9184202Sbinkertn@umich.edu# Walk the tree and execute all SConsopts scripts that wil add to the
9195863Snate@binkert.org# above variables
92010135SCurtis.Dunham@arm.comif GetOption('verbose'):
9218474Sgblack@eecs.umich.edu    print "Reading SConsopts"
9225742Snate@binkert.orgfor bdir in [ base_dir ] + extras_dir_list:
9238268Ssteve.reinhardt@amd.com    if not isdir(bdir):
9248268Ssteve.reinhardt@amd.com        print "Error: directory '%s' does not exist" % bdir
9258268Ssteve.reinhardt@amd.com        Exit(1)
9265742Snate@binkert.org    for root, dirs, files in os.walk(bdir):
9275341Sstever@gmail.com        if 'SConsopts' in files:
9288474Sgblack@eecs.umich.edu            if GetOption('verbose'):
9298474Sgblack@eecs.umich.edu                print "Reading", joinpath(root, 'SConsopts')
9305342Sstever@gmail.com            SConscript(joinpath(root, 'SConsopts'))
9314202Sbinkertn@umich.edu
9324202Sbinkertn@umich.eduall_isa_list.sort()
93311308Santhony.gutierrez@amd.comall_gpu_isa_list.sort()
9344202Sbinkertn@umich.edu
9355863Snate@binkert.orgsticky_vars.AddVariables(
9365863Snate@binkert.org    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
93711308Santhony.gutierrez@amd.com    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
9386994Snate@binkert.org    ListVariable('CPU_MODELS', 'CPU models',
9396994Snate@binkert.org                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
94010319SAndreas.Sandberg@ARM.com                 sorted(CpuModel.dict.keys())),
9415863Snate@binkert.org    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
9425863Snate@binkert.org                 False),
9435863Snate@binkert.org    BoolVariable('SS_COMPATIBLE_FP',
9445863Snate@binkert.org                 'Make floating-point results compatible with SimpleScalar',
9455863Snate@binkert.org                 False),
9465863Snate@binkert.org    BoolVariable('USE_SSE2',
9475863Snate@binkert.org                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
9485863Snate@binkert.org                 False),
9497840Snate@binkert.org    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
9505863Snate@binkert.org    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
95112230Sgiacomo.travaglini@arm.com    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
95212230Sgiacomo.travaglini@arm.com    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
95312230Sgiacomo.travaglini@arm.com                 False),
95412230Sgiacomo.travaglini@arm.com    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
95512230Sgiacomo.travaglini@arm.com                 have_kvm),
95612056Sgabeblack@google.com    BoolVariable('USE_TUNTAP',
95712056Sgabeblack@google.com                 'Enable using a tap device to bridge to the host network',
95812056Sgabeblack@google.com                 have_tuntap),
95911308Santhony.gutierrez@amd.com    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
9609219Spower.jg@gmail.com    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
9619219Spower.jg@gmail.com                  all_protocols),
96211235Sandreas.sandberg@arm.com    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
96311235Sandreas.sandberg@arm.com                 backtrace_impls[-1], backtrace_impls)
9641869SN/A    )
9651858SN/A
9665863Snate@binkert.org# These variables get exported to #defines in config/*.hh (see src/SConscript).
96711308Santhony.gutierrez@amd.comexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
96812061Sjason@lowepower.com                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
96912230Sgiacomo.travaglini@arm.com                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST',
97012230Sgiacomo.travaglini@arm.com                'USE_PNG']
9711858SN/A
972955SN/A###################################################
973955SN/A#
9741869SN/A# Define a SCons builder for configuration flag headers.
9751869SN/A#
9761869SN/A###################################################
9771869SN/A
9781869SN/A# This function generates a config header file that #defines the
9795863Snate@binkert.org# variable symbol to the current variable setting (0 or 1).  The source
9805863Snate@binkert.org# operands are the name of the variable and a Value node containing the
9815863Snate@binkert.org# value of the variable.
9821869SN/Adef build_config_file(target, source, env):
9835863Snate@binkert.org    (variable, value) = [s.get_contents() for s in source]
9841869SN/A    f = file(str(target[0]), 'w')
9855863Snate@binkert.org    print >> f, '#define', variable, value
9861869SN/A    f.close()
9871869SN/A    return None
9881869SN/A
9891869SN/A# Combine the two functions into a scons Action object.
9908483Sgblack@eecs.umich.educonfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
9911869SN/A
9921869SN/A# The emitter munges the source & target node lists to reflect what
9931869SN/A# we're really doing.
9941869SN/Adef config_emitter(target, source, env):
9955863Snate@binkert.org    # extract variable name from Builder arg
9965863Snate@binkert.org    variable = str(target[0])
9971869SN/A    # True target is config header file
9985863Snate@binkert.org    target = joinpath('config', variable.lower() + '.hh')
9995863Snate@binkert.org    val = env[variable]
10003356Sbinkertn@umich.edu    if isinstance(val, bool):
10013356Sbinkertn@umich.edu        # Force value to 0/1
10023356Sbinkertn@umich.edu        val = int(val)
10033356Sbinkertn@umich.edu    elif isinstance(val, str):
10043356Sbinkertn@umich.edu        val = '"' + val + '"'
10054781Snate@binkert.org
10065863Snate@binkert.org    # Sources are variable name & value (packaged in SCons Value nodes)
10075863Snate@binkert.org    return ([target], [Value(variable), Value(val)])
10081869SN/A
10091869SN/Aconfig_builder = Builder(emitter = config_emitter, action = config_action)
10101869SN/A
10116121Snate@binkert.orgmain.Append(BUILDERS = { 'ConfigFile' : config_builder })
10121869SN/A
101311982Sgabeblack@google.com###################################################
101411982Sgabeblack@google.com#
101511982Sgabeblack@google.com# Builders for static and shared partially linked object files.
101611982Sgabeblack@google.com#
101711982Sgabeblack@google.com###################################################
101811982Sgabeblack@google.com
101911982Sgabeblack@google.compartial_static_builder = Builder(action=SCons.Defaults.LinkAction,
102011982Sgabeblack@google.com                                 src_suffix='$OBJSUFFIX',
102111982Sgabeblack@google.com                                 src_builder=['StaticObject', 'Object'],
102211982Sgabeblack@google.com                                 LINKFLAGS='$PLINKFLAGS',
102311982Sgabeblack@google.com                                 LIBS='')
102411982Sgabeblack@google.com
102511982Sgabeblack@google.comdef partial_shared_emitter(target, source, env):
102611982Sgabeblack@google.com    for tgt in target:
102711982Sgabeblack@google.com        tgt.attributes.shared = 1
102811982Sgabeblack@google.com    return (target, source)
102911982Sgabeblack@google.compartial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
103011982Sgabeblack@google.com                                 emitter=partial_shared_emitter,
103111982Sgabeblack@google.com                                 src_suffix='$SHOBJSUFFIX',
103211982Sgabeblack@google.com                                 src_builder='SharedObject',
103311982Sgabeblack@google.com                                 SHLINKFLAGS='$PSHLINKFLAGS',
103411982Sgabeblack@google.com                                 LIBS='')
103511982Sgabeblack@google.com
103611982Sgabeblack@google.commain.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
103711982Sgabeblack@google.com                         'PartialStatic' : partial_static_builder })
103811982Sgabeblack@google.com
103911978Sgabeblack@google.com# builds in ext are shared across all configs in the build root.
104011978Sgabeblack@google.comext_dir = abspath(joinpath(str(main.root), 'ext'))
104112034Sgabeblack@google.comext_build_dirs = []
104211978Sgabeblack@google.comfor root, dirs, files in os.walk(ext_dir):
104311978Sgabeblack@google.com    if 'SConscript' in files:
104411978Sgabeblack@google.com        build_dir = os.path.relpath(root, ext_dir)
104512034Sgabeblack@google.com        ext_build_dirs.append(build_dir)
104611978Sgabeblack@google.com        main.SConscript(joinpath(root, 'SConscript'),
104711978Sgabeblack@google.com                        variant_dir=joinpath(build_root, build_dir))
104810915Sandreas.sandberg@arm.com
104911986Sandreas.sandberg@arm.commain.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
105011986Sandreas.sandberg@arm.com
10511869SN/A###################################################
10521869SN/A#
105312015Sgabeblack@google.com# This builder and wrapper method are used to set up a directory with
105412015Sgabeblack@google.com# switching headers. Those are headers which are in a generic location and
105512015Sgabeblack@google.com# that include more specific headers from a directory chosen at build time
105612015Sgabeblack@google.com# based on the current build settings.
10573546Sgblack@eecs.umich.edu#
10583546Sgblack@eecs.umich.edu###################################################
10593546Sgblack@eecs.umich.edu
106012015Sgabeblack@google.comdef build_switching_header(target, source, env):
106112015Sgabeblack@google.com    path = str(target[0])
106212015Sgabeblack@google.com    subdir = str(source[0])
106312015Sgabeblack@google.com    dp, fp = os.path.split(path)
106412015Sgabeblack@google.com    dp = os.path.relpath(os.path.realpath(dp),
106512015Sgabeblack@google.com                         os.path.realpath(env['BUILDDIR']))
106612015Sgabeblack@google.com    with open(path, 'w') as hdr:
106712015Sgabeblack@google.com        print >>hdr, '#include "%s/%s/%s"' % (dp, subdir, fp)
10683546Sgblack@eecs.umich.edu
106912015Sgabeblack@google.comswitching_header_action = MakeAction(build_switching_header,
107012015Sgabeblack@google.com                                     Transform('GENERATE'))
107110196SCurtis.Dunham@arm.com
107212015Sgabeblack@google.comswitching_header_builder = Builder(action=switching_header_action,
107312015Sgabeblack@google.com                                   source_factory=Value,
107412015Sgabeblack@google.com                                   single_source=True)
107512015Sgabeblack@google.com
107612015Sgabeblack@google.commain.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
107712015Sgabeblack@google.com
107812015Sgabeblack@google.comdef switching_headers(self, headers, source):
107912015Sgabeblack@google.com    for header in headers:
108012015Sgabeblack@google.com        self.SwitchingHeader(header, source)
108112015Sgabeblack@google.com
108212015Sgabeblack@google.commain.AddMethod(switching_headers, 'SwitchingHeaders')
10833546Sgblack@eecs.umich.edu
10843546Sgblack@eecs.umich.edu###################################################
10853546Sgblack@eecs.umich.edu#
1086955SN/A# Define build environments for selected configurations.
1087955SN/A#
1088955SN/A###################################################
1089955SN/A
10905863Snate@binkert.orgfor variant_path in variant_paths:
109110135SCurtis.Dunham@arm.com    if not GetOption('silent'):
109210135SCurtis.Dunham@arm.com        print "Building in", variant_path
10935343Sstever@gmail.com
10945343Sstever@gmail.com    # Make a copy of the build-root environment to use for this config.
10956121Snate@binkert.org    env = main.Clone()
10965863Snate@binkert.org    env['BUILDDIR'] = variant_path
10974773Snate@binkert.org
10985863Snate@binkert.org    # variant_dir is the tail component of build path, and is used to
10992632Sstever@eecs.umich.edu    # determine the build parameters (e.g., 'ALPHA_SE')
11005863Snate@binkert.org    (build_root, variant_dir) = splitpath(variant_path)
11012023SN/A
11025863Snate@binkert.org    # Set env variables according to the build directory config.
11035863Snate@binkert.org    sticky_vars.files = []
11045863Snate@binkert.org    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
11055863Snate@binkert.org    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
11065863Snate@binkert.org    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
11075863Snate@binkert.org    current_vars_file = joinpath(build_root, 'variables', variant_dir)
11085863Snate@binkert.org    if isfile(current_vars_file):
11095863Snate@binkert.org        sticky_vars.files.append(current_vars_file)
111010135SCurtis.Dunham@arm.com        if not GetOption('silent'):
111110135SCurtis.Dunham@arm.com            print "Using saved variables file %s" % current_vars_file
111212034Sgabeblack@google.com    elif variant_dir in ext_build_dirs:
111312034Sgabeblack@google.com        # Things in ext are built without a variant directory.
111412034Sgabeblack@google.com        continue
11152632Sstever@eecs.umich.edu    else:
11165863Snate@binkert.org        # Build dir-specific variables file doesn't exist.
11172023SN/A
11182632Sstever@eecs.umich.edu        # Make sure the directory is there so we can create it later
11195863Snate@binkert.org        opt_dir = dirname(current_vars_file)
11205342Sstever@gmail.com        if not isdir(opt_dir):
11215863Snate@binkert.org            mkdir(opt_dir)
11222632Sstever@eecs.umich.edu
11235863Snate@binkert.org        # Get default build variables from source tree.  Variables are
11245863Snate@binkert.org        # normally determined by name of $VARIANT_DIR, but can be
11258267Ssteve.reinhardt@amd.com        # overridden by '--default=' arg on command line.
11268120Sgblack@eecs.umich.edu        default = GetOption('default')
11278267Ssteve.reinhardt@amd.com        opts_dir = joinpath(main.root.abspath, 'build_opts')
11288267Ssteve.reinhardt@amd.com        if default:
11298267Ssteve.reinhardt@amd.com            default_vars_files = [joinpath(build_root, 'variables', default),
11308267Ssteve.reinhardt@amd.com                                  joinpath(opts_dir, default)]
11318267Ssteve.reinhardt@amd.com        else:
11328267Ssteve.reinhardt@amd.com            default_vars_files = [joinpath(opts_dir, variant_dir)]
11338267Ssteve.reinhardt@amd.com        existing_files = filter(isfile, default_vars_files)
11348267Ssteve.reinhardt@amd.com        if existing_files:
11358267Ssteve.reinhardt@amd.com            default_vars_file = existing_files[0]
11365863Snate@binkert.org            sticky_vars.files.append(default_vars_file)
11375863Snate@binkert.org            print "Variables file %s not found,\n  using defaults in %s" \
11385863Snate@binkert.org                  % (current_vars_file, default_vars_file)
11392632Sstever@eecs.umich.edu        else:
11408267Ssteve.reinhardt@amd.com            print "Error: cannot find variables file %s or " \
11418267Ssteve.reinhardt@amd.com                  "default file(s) %s" \
11428267Ssteve.reinhardt@amd.com                  % (current_vars_file, ' or '.join(default_vars_files))
11432632Sstever@eecs.umich.edu            Exit(1)
11441888SN/A
11455863Snate@binkert.org    # Apply current variable settings to env
11465863Snate@binkert.org    sticky_vars.Update(env)
11471858SN/A
11488120Sgblack@eecs.umich.edu    help_texts["local_vars"] += \
11498120Sgblack@eecs.umich.edu        "Build variables for %s:\n" % variant_dir \
11507756SAli.Saidi@ARM.com                 + sticky_vars.GenerateHelpText(env)
11512598SN/A
11525863Snate@binkert.org    # Process variable settings.
11531858SN/A
11541858SN/A    if not have_fenv and env['USE_FENV']:
11551858SN/A        print "Warning: <fenv.h> not available; " \
11565863Snate@binkert.org              "forcing USE_FENV to False in", variant_dir + "."
11571858SN/A        env['USE_FENV'] = False
11581858SN/A
11591858SN/A    if not env['USE_FENV']:
11605863Snate@binkert.org        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
11611871SN/A        print "         FP results may deviate slightly from other platforms."
11621858SN/A
116312230Sgiacomo.travaglini@arm.com    if not have_png and env['USE_PNG']:
116412230Sgiacomo.travaglini@arm.com        print "Warning: <png.h> not available; " \
116512230Sgiacomo.travaglini@arm.com              "forcing USE_PNG to False in", variant_dir + "."
116612230Sgiacomo.travaglini@arm.com        env['USE_PNG'] = False
116712230Sgiacomo.travaglini@arm.com
116812230Sgiacomo.travaglini@arm.com    if env['USE_PNG']:
116912230Sgiacomo.travaglini@arm.com        env.Append(LIBS=['png'])
117012230Sgiacomo.travaglini@arm.com
11711858SN/A    if env['EFENCE']:
11721858SN/A        env.Append(LIBS=['efence'])
11731858SN/A
11749651SAndreas.Sandberg@ARM.com    if env['USE_KVM']:
11759651SAndreas.Sandberg@ARM.com        if not have_kvm:
11769651SAndreas.Sandberg@ARM.com            print "Warning: Can not enable KVM, host seems to lack KVM support"
11779651SAndreas.Sandberg@ARM.com            env['USE_KVM'] = False
11789651SAndreas.Sandberg@ARM.com        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
11799651SAndreas.Sandberg@ARM.com            print "Info: KVM support disabled due to unsupported host and " \
11809651SAndreas.Sandberg@ARM.com                "target ISA combination"
11819651SAndreas.Sandberg@ARM.com            env['USE_KVM'] = False
11829651SAndreas.Sandberg@ARM.com
118312056Sgabeblack@google.com    if env['USE_TUNTAP']:
118412056Sgabeblack@google.com        if not have_tuntap:
118512056Sgabeblack@google.com            print "Warning: Can't connect EtherTap with a tap device."
118612056Sgabeblack@google.com            env['USE_TUNTAP'] = False
118712056Sgabeblack@google.com
118811798Santhony.gutierrez@amd.com    if env['BUILD_GPU']:
118911798Santhony.gutierrez@amd.com        env.Append(CPPDEFINES=['BUILD_GPU'])
119011798Santhony.gutierrez@amd.com
11919986Sandreas@sandberg.pp.se    # Warn about missing optional functionality
11929986Sandreas@sandberg.pp.se    if env['USE_KVM']:
11939986Sandreas@sandberg.pp.se        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
11949986Sandreas@sandberg.pp.se            print "Warning: perf_event headers lack support for the " \
11959986Sandreas@sandberg.pp.se                "exclude_host attribute. KVM instruction counts will " \
11969986Sandreas@sandberg.pp.se                "be inaccurate."
11979986Sandreas@sandberg.pp.se
11985863Snate@binkert.org    # Save sticky variable settings back to current variables file
11995863Snate@binkert.org    sticky_vars.Save(current_vars_file, env)
12001869SN/A
12011965SN/A    if env['USE_SSE2']:
12027739Sgblack@eecs.umich.edu        env.Append(CCFLAGS=['-msse2'])
12031965SN/A
12042761Sstever@eecs.umich.edu    # The src/SConscript file sets up the build rules in 'env' according
12055863Snate@binkert.org    # to the configured variables.  It returns a list of environments,
12061869SN/A    # one for each variant build (debug, opt, etc.)
120710196SCurtis.Dunham@arm.com    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
12081869SN/A
12098120Sgblack@eecs.umich.edu# base help text
12108120Sgblack@eecs.umich.eduHelp('''
12118120Sgblack@eecs.umich.eduUsage: scons [scons options] [build variables] [target(s)]
12128120Sgblack@eecs.umich.edu
12138120Sgblack@eecs.umich.eduExtra scons options:
12148120Sgblack@eecs.umich.edu%(options)s
12158120Sgblack@eecs.umich.edu
12168120Sgblack@eecs.umich.eduGlobal build variables:
12178120Sgblack@eecs.umich.edu%(global_vars)s
12188120Sgblack@eecs.umich.edu
12198120Sgblack@eecs.umich.edu%(local_vars)s
12208120Sgblack@eecs.umich.edu''' % help_texts)
1221