SConstruct revision 12304
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,
388878Ssteve.reinhardt@amd.com# 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
408878Ssteve.reinhardt@amd.com# (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#
438878Ssteve.reinhardt@amd.com# 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>'
528878Ssteve.reinhardt@amd.com# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
538878Ssteve.reinhardt@amd.com# 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.
598878Ssteve.reinhardt@amd.com#
608878Ssteve.reinhardt@amd.com# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
638878Ssteve.reinhardt@amd.com#   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
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###################################################
808878Ssteve.reinhardt@amd.com
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
968878Ssteve.reinhardt@amd.comimport 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
1168878Ssteve.reinhardt@amd.com#     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
1238947Sandreas.hansson@arm.com    help = "  " + ", ".join(args)
1245396Ssaidi@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
1338879Ssteve.reinhardt@amd.com    AddOption(*args, **kwargs)
1348879Ssteve.reinhardt@amd.com
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")
1398879Ssteve.reinhardt@amd.comAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1408879Ssteve.reinhardt@amd.com               action='store_true',
1418879Ssteve.reinhardt@amd.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')
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',
1608879Ssteve.reinhardt@amd.com               help='Disable linking against tcmalloc')
1618879Ssteve.reinhardt@amd.comAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1628879Ssteve.reinhardt@amd.com               help='Build with Undefined Behavior Sanitizer if available')
1638879Ssteve.reinhardt@amd.comAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1648879Ssteve.reinhardt@amd.com               help='Build with Address Sanitizer if available')
1658879Ssteve.reinhardt@amd.com
1668879Ssteve.reinhardt@amd.comif GetOption('no_lto') and GetOption('force_lto'):
1678879Ssteve.reinhardt@amd.com    print '--no-lto and --force-lto are mutually exclusive'
1688879Ssteve.reinhardt@amd.com    Exit(1)
1698879Ssteve.reinhardt@amd.com
1708879Ssteve.reinhardt@amd.com########################################################################
1718879Ssteve.reinhardt@amd.com#
1728120Sgblack@eecs.umich.edu# Set up the main build environment.
1738947Sandreas.hansson@arm.com#
1747816Ssteve.reinhardt@amd.com########################################################################
1755871Snate@binkert.org
1765871Snate@binkert.orgmain = Environment()
1776121Snate@binkert.org
1785871Snate@binkert.orgfrom gem5_scons import Transform
1795871Snate@binkert.orgfrom gem5_scons.util import get_termcap
1806003Snate@binkert.orgtermcap = get_termcap()
1818980Ssteve.reinhardt@amd.com
182955SN/Amain_dict_keys = main.Dictionary().keys()
1835871Snate@binkert.org
1845871Snate@binkert.org# Check that we have a C/C++ compiler
1855871Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1865871Snate@binkert.org    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
187955SN/A    Exit(1)
1886121Snate@binkert.org
1898881Smarc.orr@gmail.com###################################################
1906121Snate@binkert.org#
1916121Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
1921533SN/A# the target(s).
1936655Snate@binkert.org#
1946655Snate@binkert.org###################################################
1956655Snate@binkert.org
1966655Snate@binkert.org# Find default configuration & binary.
1975871Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
1985871Snate@binkert.org
1995863Snate@binkert.org# helper function: find last occurrence of element in list
2005871Snate@binkert.orgdef rfind(l, elt, offs = -1):
2018878Ssteve.reinhardt@amd.com    for i in range(len(l)+offs, 0, -1):
2025871Snate@binkert.org        if l[i] == elt:
2035871Snate@binkert.org            return i
2045871Snate@binkert.org    raise ValueError, "element not found"
2055863Snate@binkert.org
2066121Snate@binkert.org# Take a list of paths (or SCons Nodes) and return a list with all
2075863Snate@binkert.org# paths made absolute and ~-expanded.  Paths will be interpreted
2085871Snate@binkert.org# relative to the launch directory unless a different root is provided
2098336Ssteve.reinhardt@amd.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
2108336Ssteve.reinhardt@amd.com    return [abspath(joinpath(root, expanduser(str(p))))
2118336Ssteve.reinhardt@amd.com            for p in path_list]
2128336Ssteve.reinhardt@amd.com
2134678Snate@binkert.org# Each target must have 'build' in the interior of the path; the
2148336Ssteve.reinhardt@amd.com# directory below this will determine the build parameters.  For
2158336Ssteve.reinhardt@amd.com# 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.
2184678Snate@binkert.org
2194678Snate@binkert.org# The funky assignment to "[:]" is needed to replace the list contents
2204678Snate@binkert.org# in place rather than reassign the symbol to a new list, which
2217827Snate@binkert.org# doesn't work (obviously!).
2227827Snate@binkert.orgBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2238336Ssteve.reinhardt@amd.com
2244678Snate@binkert.org# Generate a list of the unique build roots and configs that the
2258336Ssteve.reinhardt@amd.com# 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)
2325871Snate@binkert.org    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:
2378336Ssteve.reinhardt@amd.com        build_root = this_build_root
2385871Snate@binkert.org    else:
2398336Ssteve.reinhardt@amd.com        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])
2444678Snate@binkert.org    if variant_path not in variant_paths:
2455871Snate@binkert.org        variant_paths.append(variant_path)
2464678Snate@binkert.org
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
2578336Ssteve.reinhardt@amd.com# when you use emacs to edit a file in the target dir, as emacs moves
2588336Ssteve.reinhardt@amd.com# file to file~ then copies to file, breaking the link.  Symbolic
2598336Ssteve.reinhardt@amd.com# (soft) links work better.
2608336Ssteve.reinhardt@amd.commain.SetOption('duplicate', 'soft-copy')
2618336Ssteve.reinhardt@amd.com
2628336Ssteve.reinhardt@amd.com#
2638336Ssteve.reinhardt@amd.com# Set up global sticky variables... these are common to an entire build
2645871Snate@binkert.org# tree (not specific to a particular build like ALPHA_SE)
2656121Snate@binkert.org#
266955SN/A
267955SN/Aglobal_vars_file = joinpath(build_root, 'variables.global')
2682632Sstever@eecs.umich.edu
2692632Sstever@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
270955SN/A
271955SN/Aglobal_vars.AddVariables(
272955SN/A    ('CC', 'C compiler', environ.get('CC', main['CC'])),
273955SN/A    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2748878Ssteve.reinhardt@amd.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
275955SN/A    ('BATCH', 'Use batch pool for build and tests', False),
2762632Sstever@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2772632Sstever@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2782632Sstever@eecs.umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
2792632Sstever@eecs.umich.edu    )
2802632Sstever@eecs.umich.edu
2812632Sstever@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
2822632Sstever@eecs.umich.eduglobal_vars.Update(main)
2838268Ssteve.reinhardt@amd.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
2848268Ssteve.reinhardt@amd.com
2858268Ssteve.reinhardt@amd.com# Save sticky variable settings back to current variables file
2868268Ssteve.reinhardt@amd.comglobal_vars.Save(global_vars_file, main)
2878268Ssteve.reinhardt@amd.com
2888268Ssteve.reinhardt@amd.com# 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.
2902632Sstever@eecs.umich.edubase_dir = main.srcdir.abspath
2912632Sstever@eecs.umich.eduif main['EXTRAS']:
2922632Sstever@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
2932632Sstever@eecs.umich.eduelse:
2948268Ssteve.reinhardt@amd.com    extras_dir_list = []
2952632Sstever@eecs.umich.edu
2968268Ssteve.reinhardt@amd.comExport('base_dir')
2978268Ssteve.reinhardt@amd.comExport('extras_dir_list')
2988268Ssteve.reinhardt@amd.com
2998268Ssteve.reinhardt@amd.com# the ext directory should be on the #includes path
3003718Sstever@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
3012634Sstever@eecs.umich.edu
3022634Sstever@eecs.umich.edu# Add shared top-level headers
3035863Snate@binkert.orgmain.Prepend(CPPPATH=Dir('include'))
3042638Sstever@eecs.umich.edu
3058268Ssteve.reinhardt@amd.comif GetOption('verbose'):
3062632Sstever@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
3072632Sstever@eecs.umich.edu        return Action(action, *args, **kwargs)
3082632Sstever@eecs.umich.eduelse:
3092632Sstever@eecs.umich.edu    MakeAction = Action
3102632Sstever@eecs.umich.edu    main['CCCOMSTR']        = Transform("CC")
3111858SN/A    main['CXXCOMSTR']       = Transform("CXX")
3123716Sstever@eecs.umich.edu    main['ASCOMSTR']        = Transform("AS")
3132638Sstever@eecs.umich.edu    main['ARCOMSTR']        = Transform("AR", 0)
3142638Sstever@eecs.umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
3152638Sstever@eecs.umich.edu    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
3162638Sstever@eecs.umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3172638Sstever@eecs.umich.edu    main['M4COMSTR']        = Transform("M4")
3182638Sstever@eecs.umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
3192638Sstever@eecs.umich.edu    main['SHCXXCOMSTR']     = Transform("SHCXX")
3205863Snate@binkert.orgExport('MakeAction')
3215863Snate@binkert.org
3225863Snate@binkert.org# Initialize the Link-Time Optimization (LTO) flags
323955SN/Amain['LTO_CCFLAGS'] = []
3245341Sstever@gmail.commain['LTO_LDFLAGS'] = []
3255341Sstever@gmail.com
3265863Snate@binkert.org# According to the readme, tcmalloc works best if the compiler doesn't
3277756SAli.Saidi@ARM.com# assume that we're using the builtin malloc and friends. These flags
3285341Sstever@gmail.com# are compiler-specific, so we need to set them after we detect which
3296121Snate@binkert.org# compiler we're using.
3304494Ssaidi@eecs.umich.edumain['TCMALLOC_CCFLAGS'] = []
3316121Snate@binkert.org
3321105SN/ACXX_version = readCommand([main['CXX'],'--version'], exception=False)
3332667Sstever@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
3342667Sstever@eecs.umich.edu
3352667Sstever@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3362667Sstever@eecs.umich.edumain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
3376121Snate@binkert.orgif main['GCC'] + main['CLANG'] > 1:
3382667Sstever@eecs.umich.edu    print 'Error: How can we have two at the same time?'
3395341Sstever@gmail.com    Exit(1)
3405863Snate@binkert.org
3415341Sstever@gmail.com# Set up default C++ compiler flags
3425341Sstever@gmail.comif main['GCC'] or main['CLANG']:
3435341Sstever@gmail.com    # As gcc and clang share many flags, do the common parts here
3448120Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
3455341Sstever@gmail.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
3468120Sgblack@eecs.umich.edu    # Enable -Wall and -Wextra and then disable the few warnings that
3475341Sstever@gmail.com    # we consistently violate
3488120Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
3496121Snate@binkert.org                         '-Wno-sign-compare', '-Wno-unused-parameter'])
3506121Snate@binkert.org    # We always compile using C++11
3518980Ssteve.reinhardt@amd.com    main.Append(CXXFLAGS=['-std=c++11'])
3525397Ssaidi@eecs.umich.edu    if sys.platform.startswith('freebsd'):
3535397Ssaidi@eecs.umich.edu        main.Append(CCFLAGS=['-I/usr/local/include'])
3547727SAli.Saidi@ARM.com        main.Append(CXXFLAGS=['-I/usr/local/include'])
3558268Ssteve.reinhardt@amd.com
3566168Snate@binkert.org    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3575341Sstever@gmail.com    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
3588120Sgblack@eecs.umich.edu    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3598120Sgblack@eecs.umich.edu    shared_partial_flags = ['-r', '-nostdlib']
3608120Sgblack@eecs.umich.edu    main.Append(PSHLINKFLAGS=shared_partial_flags)
3616814Sgblack@eecs.umich.edu    main.Append(PLINKFLAGS=shared_partial_flags)
3625863Snate@binkert.orgelse:
3638120Sgblack@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
3645341Sstever@gmail.com    print "Don't know what compiler options to use for your compiler."
3655863Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
3668268Ssteve.reinhardt@amd.com    print termcap.Yellow + '       version:' + termcap.Normal,
3676121Snate@binkert.org    if not CXX_version:
3686121Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
3698268Ssteve.reinhardt@amd.com               termcap.Normal
3705742Snate@binkert.org    else:
3715742Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
3725341Sstever@gmail.com    print "       If you're trying to use a compiler other than GCC"
3735742Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
3745742Snate@binkert.org    print "       environment."
3755341Sstever@gmail.com    print "       "
3766017Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
3776121Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
3786017Snate@binkert.org    print "       src/SConscript to support that compiler."
3797816Ssteve.reinhardt@amd.com    Exit(1)
3807756SAli.Saidi@ARM.com
3817756SAli.Saidi@ARM.comif main['GCC']:
3827756SAli.Saidi@ARM.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
3837756SAli.Saidi@ARM.com    # level of c++11 support. See
3847756SAli.Saidi@ARM.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
3857756SAli.Saidi@ARM.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
3867756SAli.Saidi@ARM.com    if compareVersions(gcc_version, "4.8") < 0:
3877756SAli.Saidi@ARM.com        print 'Error: gcc version 4.8 or newer required.'
3887816Ssteve.reinhardt@amd.com        print '       Installed version:', gcc_version
3897816Ssteve.reinhardt@amd.com        Exit(1)
3907816Ssteve.reinhardt@amd.com
3917816Ssteve.reinhardt@amd.com    main['GCC_VERSION'] = gcc_version
3927816Ssteve.reinhardt@amd.com
3937816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, '4.9') >= 0:
3947816Ssteve.reinhardt@amd.com        # Incremental linking with LTO is currently broken in gcc versions
3957816Ssteve.reinhardt@amd.com        # 4.9 and above. A version where everything works completely hasn't
3967816Ssteve.reinhardt@amd.com        # yet been identified.
3977816Ssteve.reinhardt@amd.com        #
3987756SAli.Saidi@ARM.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
3997816Ssteve.reinhardt@amd.com        main['BROKEN_INCREMENTAL_LTO'] = True
4007816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, '6.0') >= 0:
4017816Ssteve.reinhardt@amd.com        # gcc versions 6.0 and greater accept an -flinker-output flag which
4027816Ssteve.reinhardt@amd.com        # selects what type of output the linker should generate. This is
4037816Ssteve.reinhardt@amd.com        # necessary for incremental lto to work, but is also broken in
4047816Ssteve.reinhardt@amd.com        # current versions of gcc. It may not be necessary in future
4057816Ssteve.reinhardt@amd.com        # versions. We add it here since it might be, and as a reminder that
4067816Ssteve.reinhardt@amd.com        # it exists. It's excluded if lto is being forced.
4077816Ssteve.reinhardt@amd.com        #
4087816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/gcc-6/changes.html
4097816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
4107816Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
4117816Ssteve.reinhardt@amd.com        if not GetOption('force_lto'):
4127816Ssteve.reinhardt@amd.com            main.Append(PSHLINKFLAGS='-flinker-output=rel')
4137816Ssteve.reinhardt@amd.com            main.Append(PLINKFLAGS='-flinker-output=rel')
4147816Ssteve.reinhardt@amd.com
4157816Ssteve.reinhardt@amd.com    # gcc from version 4.8 and above generates "rep; ret" instructions
4167816Ssteve.reinhardt@amd.com    # to avoid performance penalties on certain AMD chips. Older
4177816Ssteve.reinhardt@amd.com    # assemblers detect this as an error, "Error: expecting string
4187816Ssteve.reinhardt@amd.com    # instruction after `rep'"
4197816Ssteve.reinhardt@amd.com    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
4207816Ssteve.reinhardt@amd.com                                  '-o', '/dev/null'],
4217816Ssteve.reinhardt@amd.com                                 exception=False).split()
4227816Ssteve.reinhardt@amd.com
4237816Ssteve.reinhardt@amd.com    # version strings may contain extra distro-specific
4247816Ssteve.reinhardt@amd.com    # qualifiers, so play it safe and keep only what comes before
4257816Ssteve.reinhardt@amd.com    # the first hyphen
4267816Ssteve.reinhardt@amd.com    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
4277816Ssteve.reinhardt@amd.com
4287816Ssteve.reinhardt@amd.com    if not as_version or compareVersions(as_version, "2.23") < 0:
4297816Ssteve.reinhardt@amd.com        print termcap.Yellow + termcap.Bold + \
4307816Ssteve.reinhardt@amd.com            'Warning: This combination of gcc and binutils have' + \
4317816Ssteve.reinhardt@amd.com            ' known incompatibilities.\n' + \
4327816Ssteve.reinhardt@amd.com            '         If you encounter build problems, please update ' + \
4337816Ssteve.reinhardt@amd.com            'binutils to 2.23.' + \
4347816Ssteve.reinhardt@amd.com            termcap.Normal
4357816Ssteve.reinhardt@amd.com
4367816Ssteve.reinhardt@amd.com    # Make sure we warn if the user has requested to compile with the
4377816Ssteve.reinhardt@amd.com    # Undefined Benahvior Sanitizer and this version of gcc does not
4387816Ssteve.reinhardt@amd.com    # support it.
4397816Ssteve.reinhardt@amd.com    if GetOption('with_ubsan') and \
4407816Ssteve.reinhardt@amd.com            compareVersions(gcc_version, '4.9') < 0:
4417816Ssteve.reinhardt@amd.com        print termcap.Yellow + termcap.Bold + \
4427816Ssteve.reinhardt@amd.com            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
4437816Ssteve.reinhardt@amd.com            termcap.Normal
4447816Ssteve.reinhardt@amd.com
4457816Ssteve.reinhardt@amd.com    disable_lto = GetOption('no_lto')
4467816Ssteve.reinhardt@amd.com    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
4477816Ssteve.reinhardt@amd.com            not GetOption('force_lto'):
4487816Ssteve.reinhardt@amd.com        print termcap.Yellow + termcap.Bold + \
4497816Ssteve.reinhardt@amd.com            'Warning: Your compiler doesn\'t support incremental linking' + \
4507816Ssteve.reinhardt@amd.com            ' and lto at the same time, so lto is being disabled. To force' + \
4517816Ssteve.reinhardt@amd.com            ' lto on anyway, use the --force-lto option. That will disable' + \
4527816Ssteve.reinhardt@amd.com            ' partial linking.' + \
4537816Ssteve.reinhardt@amd.com            termcap.Normal
4547816Ssteve.reinhardt@amd.com        disable_lto = True
4557816Ssteve.reinhardt@amd.com
4567816Ssteve.reinhardt@amd.com    # Add the appropriate Link-Time Optimization (LTO) flags
4577816Ssteve.reinhardt@amd.com    # unless LTO is explicitly turned off. Note that these flags
4587816Ssteve.reinhardt@amd.com    # are only used by the fast target.
4597816Ssteve.reinhardt@amd.com    if not disable_lto:
4608947Sandreas.hansson@arm.com        # Pass the LTO flag when compiling to produce GIMPLE
4618947Sandreas.hansson@arm.com        # output, we merely create the flags here and only append
4627756SAli.Saidi@ARM.com        # them later
4638120Sgblack@eecs.umich.edu        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4647756SAli.Saidi@ARM.com
4657756SAli.Saidi@ARM.com        # Use the same amount of jobs for LTO as we are running
4667756SAli.Saidi@ARM.com        # scons with
4677756SAli.Saidi@ARM.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4687816Ssteve.reinhardt@amd.com
4697816Ssteve.reinhardt@amd.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4707816Ssteve.reinhardt@amd.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4717816Ssteve.reinhardt@amd.com
4727816Ssteve.reinhardt@amd.com    # add option to check for undeclared overrides
4737816Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, "5.0") > 0:
4747816Ssteve.reinhardt@amd.com        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
4757816Ssteve.reinhardt@amd.com
4767816Ssteve.reinhardt@amd.com    # The address sanitizer is available for gcc >= 4.8
4777816Ssteve.reinhardt@amd.com    if GetOption('with_asan'):
4787756SAli.Saidi@ARM.com        if GetOption('with_ubsan') and \
4797756SAli.Saidi@ARM.com                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
4806654Snate@binkert.org            env.Append(CCFLAGS=['-fsanitize=address,undefined',
4816654Snate@binkert.org                                '-fno-omit-frame-pointer'],
4825871Snate@binkert.org                       LINKFLAGS='-fsanitize=address,undefined')
4836121Snate@binkert.org        else:
4846121Snate@binkert.org            env.Append(CCFLAGS=['-fsanitize=address',
4856121Snate@binkert.org                                '-fno-omit-frame-pointer'],
4868946Sandreas.hansson@arm.com                       LINKFLAGS='-fsanitize=address')
4878737Skoansin.tan@gmail.com    # Only gcc >= 4.9 supports UBSan, so check both the version
4883940Ssaidi@eecs.umich.edu    # and the command-line option before adding the compiler and
4893918Ssaidi@eecs.umich.edu    # linker flags.
4903918Ssaidi@eecs.umich.edu    elif GetOption('with_ubsan') and \
4911858SN/A            compareVersions(env['GCC_VERSION'], '4.9') >= 0:
4926121Snate@binkert.org        env.Append(CCFLAGS='-fsanitize=undefined')
4937739Sgblack@eecs.umich.edu        env.Append(LINKFLAGS='-fsanitize=undefined')
4947739Sgblack@eecs.umich.edu
4956143Snate@binkert.orgelif main['CLANG']:
4967618SAli.Saidi@arm.com    # Check for a supported version of clang, >= 3.1 is needed to
4977618SAli.Saidi@arm.com    # support similar features as gcc 4.8. See
4987618SAli.Saidi@arm.com    # http://clang.llvm.org/cxx_status.html for details
4997618SAli.Saidi@arm.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
5008614Sgblack@eecs.umich.edu    clang_version_match = clang_version_re.search(CXX_version)
5017618SAli.Saidi@arm.com    if (clang_version_match):
5027618SAli.Saidi@arm.com        clang_version = clang_version_match.groups()[0]
5037618SAli.Saidi@arm.com        if compareVersions(clang_version, "3.1") < 0:
5047739Sgblack@eecs.umich.edu            print 'Error: clang version 3.1 or newer required.'
5058946Sandreas.hansson@arm.com            print '       Installed version:', clang_version
5068946Sandreas.hansson@arm.com            Exit(1)
5076121Snate@binkert.org    else:
5083940Ssaidi@eecs.umich.edu        print 'Error: Unable to determine clang version.'
5096121Snate@binkert.org        Exit(1)
5107739Sgblack@eecs.umich.edu
5117739Sgblack@eecs.umich.edu    # clang has a few additional warnings that we disable, extraneous
5127739Sgblack@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
5137739Sgblack@eecs.umich.edu    # finally self assignments are allowed as the generated CPU code
5147739Sgblack@eecs.umich.edu    # is relying on this
5157739Sgblack@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-parentheses',
5168737Skoansin.tan@gmail.com                         '-Wno-self-assign',
5178737Skoansin.tan@gmail.com                         # Some versions of libstdc++ (4.8?) seem to
5188737Skoansin.tan@gmail.com                         # use struct hash and class hash
5198737Skoansin.tan@gmail.com                         # interchangeably.
5208737Skoansin.tan@gmail.com                         '-Wno-mismatched-tags',
5218737Skoansin.tan@gmail.com                         ])
5228737Skoansin.tan@gmail.com
5238737Skoansin.tan@gmail.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5248737Skoansin.tan@gmail.com
5258737Skoansin.tan@gmail.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5268737Skoansin.tan@gmail.com    # opposed to libstdc++, as the later is dated.
5278737Skoansin.tan@gmail.com    if sys.platform == "darwin":
5288737Skoansin.tan@gmail.com        main.Append(CXXFLAGS=['-stdlib=libc++'])
5298737Skoansin.tan@gmail.com        main.Append(LIBS=['c++'])
5308737Skoansin.tan@gmail.com
5318737Skoansin.tan@gmail.com    # On FreeBSD we need libthr.
5328737Skoansin.tan@gmail.com    if sys.platform.startswith('freebsd'):
5338737Skoansin.tan@gmail.com        main.Append(LIBS=['thr'])
5348946Sandreas.hansson@arm.com
5358946Sandreas.hansson@arm.com    # We require clang >= 3.1, so there is no need to check any
5368946Sandreas.hansson@arm.com    # versions here.
5378946Sandreas.hansson@arm.com    if GetOption('with_ubsan'):
5388946Sandreas.hansson@arm.com        if GetOption('with_asan'):
5398946Sandreas.hansson@arm.com            env.Append(CCFLAGS=['-fsanitize=address,undefined',
5403918Ssaidi@eecs.umich.edu                                '-fno-omit-frame-pointer'],
5413918Ssaidi@eecs.umich.edu                       LINKFLAGS='-fsanitize=address,undefined')
5423940Ssaidi@eecs.umich.edu        else:
5433918Ssaidi@eecs.umich.edu            env.Append(CCFLAGS='-fsanitize=undefined',
5443918Ssaidi@eecs.umich.edu                       LINKFLAGS='-fsanitize=undefined')
5456157Snate@binkert.org
5466157Snate@binkert.org    elif GetOption('with_asan'):
5476157Snate@binkert.org        env.Append(CCFLAGS=['-fsanitize=address',
5486157Snate@binkert.org                            '-fno-omit-frame-pointer'],
5495397Ssaidi@eecs.umich.edu                   LINKFLAGS='-fsanitize=address')
5505397Ssaidi@eecs.umich.edu
5516121Snate@binkert.orgelse:
5526121Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5536121Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
5546121Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5556121Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
5566121Snate@binkert.org    if not CXX_version:
5575397Ssaidi@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5581851SN/A               termcap.Normal
5591851SN/A    else:
5607739Sgblack@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
561955SN/A    print "       If you're trying to use a compiler other than GCC"
5623053Sstever@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
5636121Snate@binkert.org    print "       environment."
5643053Sstever@eecs.umich.edu    print "       "
5653053Sstever@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
5663053Sstever@eecs.umich.edu    print "       above you will need to ease fix SConstruct and "
5673053Sstever@eecs.umich.edu    print "       src/SConscript to support that compiler."
5683053Sstever@eecs.umich.edu    Exit(1)
5696654Snate@binkert.org
5703053Sstever@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
5714742Sstever@eecs.umich.edumain['YACCFLAGS'] = '-d'
5724742Sstever@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
5733053Sstever@eecs.umich.edu
5743053Sstever@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
5753053Sstever@eecs.umich.edu# extra 'qdo' every time we run scons.
5768960Ssteve.reinhardt@amd.comif main['BATCH']:
5776654Snate@binkert.org    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5783053Sstever@eecs.umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5793053Sstever@eecs.umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5803053Sstever@eecs.umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5813053Sstever@eecs.umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5822667Sstever@eecs.umich.edu
5834554Sbinkertn@umich.eduif sys.platform == 'cygwin':
5846121Snate@binkert.org    # cygwin has some header file issues...
5852667Sstever@eecs.umich.edu    main.Append(CCFLAGS=["-Wno-uninitialized"])
5864554Sbinkertn@umich.edu
5874554Sbinkertn@umich.edu# Check for the protobuf compiler
5884554Sbinkertn@umich.eduprotoc_version = readCommand([main['PROTOC'], '--version'],
5896121Snate@binkert.org                             exception='').split()
5904554Sbinkertn@umich.edu
5914554Sbinkertn@umich.edu# First two words should be "libprotoc x.y.z"
5924554Sbinkertn@umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
5934781Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
5944554Sbinkertn@umich.edu        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
5954554Sbinkertn@umich.edu        '         Please install protobuf-compiler for tracing support.' + \
5962667Sstever@eecs.umich.edu        termcap.Normal
5974554Sbinkertn@umich.edu    main['PROTOC'] = False
5984554Sbinkertn@umich.eduelse:
5994554Sbinkertn@umich.edu    # Based on the availability of the compress stream wrappers,
6004554Sbinkertn@umich.edu    # require 2.1.0
6012667Sstever@eecs.umich.edu    min_protoc_version = '2.1.0'
6024554Sbinkertn@umich.edu    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6032667Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
6044554Sbinkertn@umich.edu            'Warning: protoc version', min_protoc_version, \
6056121Snate@binkert.org            'or newer required.\n' + \
6062667Sstever@eecs.umich.edu            '         Installed version:', protoc_version[1], \
6075522Snate@binkert.org            termcap.Normal
6085522Snate@binkert.org        main['PROTOC'] = False
6095522Snate@binkert.org    else:
6105522Snate@binkert.org        # Attempt to determine the appropriate include path and
6115522Snate@binkert.org        # library path using pkg-config, that means we also need to
6125522Snate@binkert.org        # check for pkg-config. Note that it is possible to use
6135522Snate@binkert.org        # protobuf without the involvement of pkg-config. Later on we
6145522Snate@binkert.org        # check go a library config check and at that point the test
6155522Snate@binkert.org        # will fail if libprotobuf cannot be found.
6165522Snate@binkert.org        if readCommand(['pkg-config', '--version'], exception=''):
6175522Snate@binkert.org            try:
6185522Snate@binkert.org                # Attempt to establish what linking flags to add for protobuf
6195522Snate@binkert.org                # using pkg-config
6205522Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6215522Snate@binkert.org            except:
6225522Snate@binkert.org                print termcap.Yellow + termcap.Bold + \
6235522Snate@binkert.org                    'Warning: pkg-config could not get protobuf flags.' + \
6245522Snate@binkert.org                    termcap.Normal
6255522Snate@binkert.org
6265522Snate@binkert.org
6275522Snate@binkert.org# Check for 'timeout' from GNU coreutils. If present, regressions will
6285522Snate@binkert.org# be run with a time limit. We require version 8.13 since we rely on
6295522Snate@binkert.org# support for the '--foreground' option.
6305522Snate@binkert.orgif sys.platform.startswith('freebsd'):
6315522Snate@binkert.org    timeout_lines = readCommand(['gtimeout', '--version'],
6325522Snate@binkert.org                                exception='').splitlines()
6332638Sstever@eecs.umich.eduelse:
6342638Sstever@eecs.umich.edu    timeout_lines = readCommand(['timeout', '--version'],
6356121Snate@binkert.org                                exception='').splitlines()
6363716Sstever@eecs.umich.edu# Get the first line and tokenize it
6375522Snate@binkert.orgtimeout_version = timeout_lines[0].split() if timeout_lines else []
6385522Snate@binkert.orgmain['TIMEOUT'] =  timeout_version and \
6395522Snate@binkert.org    compareVersions(timeout_version[-1], '8.13') >= 0
6405522Snate@binkert.org
6415522Snate@binkert.org# Add a custom Check function to test for structure members.
6425522Snate@binkert.orgdef CheckMember(context, include, decl, member, include_quotes="<>"):
6431858SN/A    context.Message("Checking for member %s in %s..." %
6445227Ssaidi@eecs.umich.edu                    (member, decl))
6455227Ssaidi@eecs.umich.edu    text = """
6465227Ssaidi@eecs.umich.edu#include %(header)s
6475227Ssaidi@eecs.umich.eduint main(){
6486654Snate@binkert.org  %(decl)s test;
6496654Snate@binkert.org  (void)test.%(member)s;
6507769SAli.Saidi@ARM.com  return 0;
6517769SAli.Saidi@ARM.com};
6527769SAli.Saidi@ARM.com""" % { "header" : include_quotes[0] + include + include_quotes[1],
6537769SAli.Saidi@ARM.com        "decl" : decl,
6545227Ssaidi@eecs.umich.edu        "member" : member,
6555227Ssaidi@eecs.umich.edu        }
6565227Ssaidi@eecs.umich.edu
6575204Sstever@gmail.com    ret = context.TryCompile(text, extension=".cc")
6585204Sstever@gmail.com    context.Result(ret)
6595204Sstever@gmail.com    return ret
6605204Sstever@gmail.com
6615204Sstever@gmail.com# Platform-specific configuration.  Note again that we assume that all
6625204Sstever@gmail.com# builds under a given build root run on the same host platform.
6635204Sstever@gmail.comconf = Configure(main,
6645204Sstever@gmail.com                 conf_dir = joinpath(build_root, '.scons_config'),
6655204Sstever@gmail.com                 log_file = joinpath(build_root, 'scons_config.log'),
6665204Sstever@gmail.com                 custom_tests = {
6675204Sstever@gmail.com        'CheckMember' : CheckMember,
6685204Sstever@gmail.com        })
6695204Sstever@gmail.com
6705204Sstever@gmail.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6715204Sstever@gmail.comtry:
6725204Sstever@gmail.com    import platform
6735204Sstever@gmail.com    uname = platform.uname()
6746121Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6755204Sstever@gmail.com        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6763118Sstever@eecs.umich.edu            main.Append(CCFLAGS=['-arch', 'x86_64'])
6773118Sstever@eecs.umich.edu            main.Append(CFLAGS=['-arch', 'x86_64'])
6783118Sstever@eecs.umich.edu            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6793118Sstever@eecs.umich.edu            main.Append(ASFLAGS=['-arch', 'x86_64'])
6803118Sstever@eecs.umich.eduexcept:
6815863Snate@binkert.org    pass
6823118Sstever@eecs.umich.edu
6835863Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
6843118Sstever@eecs.umich.edu# when configuration isn't necessary, e.g., if the "--help" option is
6857457Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
6867457Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
6875863Snate@binkert.org# more optimistic null object that returns True instead.
6885863Snate@binkert.orgif not conf:
6895863Snate@binkert.org    def NullCheck(*args, **kwargs):
6905863Snate@binkert.org        return True
6915863Snate@binkert.org
6925863Snate@binkert.org    class NullConf:
6935863Snate@binkert.org        def __init__(self, env):
6946003Snate@binkert.org            self.env = env
6955863Snate@binkert.org        def Finish(self):
6965863Snate@binkert.org            return self.env
6975863Snate@binkert.org        def __getattr__(self, mname):
6986120Snate@binkert.org            return NullCheck
6995863Snate@binkert.org
7005863Snate@binkert.org    conf = NullConf(main)
7015863Snate@binkert.org
7028655Sandreas.hansson@arm.com# Cache build files in the supplied directory.
7038655Sandreas.hansson@arm.comif main['M5_BUILD_CACHE']:
7048655Sandreas.hansson@arm.com    print 'Using build cache located at', main['M5_BUILD_CACHE']
7058655Sandreas.hansson@arm.com    CacheDir(main['M5_BUILD_CACHE'])
7068655Sandreas.hansson@arm.com
7078655Sandreas.hansson@arm.commain['USE_PYTHON'] = not GetOption('without_python')
7088655Sandreas.hansson@arm.comif main['USE_PYTHON']:
7098655Sandreas.hansson@arm.com    # Find Python include and library directories for embedding the
7106120Snate@binkert.org    # interpreter. We rely on python-config to resolve the appropriate
7115863Snate@binkert.org    # includes and linker flags. ParseConfig does not seem to understand
7126121Snate@binkert.org    # the more exotic linker flags such as -Xlinker and -export-dynamic so
7136121Snate@binkert.org    # we add them explicitly below. If you want to link in an alternate
7145863Snate@binkert.org    # version of python, see above for instructions on how to invoke
7157727SAli.Saidi@ARM.com    # scons with the appropriate PATH set.
7167727SAli.Saidi@ARM.com    #
7177727SAli.Saidi@ARM.com    # First we check if python2-config exists, else we use python-config
7187727SAli.Saidi@ARM.com    python_config = readCommand(['which', 'python2-config'],
7197727SAli.Saidi@ARM.com                                exception='').strip()
7207727SAli.Saidi@ARM.com    if not os.path.exists(python_config):
7215863Snate@binkert.org        python_config = readCommand(['which', 'python-config'],
7223118Sstever@eecs.umich.edu                                    exception='').strip()
7235863Snate@binkert.org    py_includes = readCommand([python_config, '--includes'],
7243118Sstever@eecs.umich.edu                              exception='').split()
7253118Sstever@eecs.umich.edu    # Strip the -I from the include folders before adding them to the
7265863Snate@binkert.org    # CPPPATH
7275863Snate@binkert.org    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
7285863Snate@binkert.org
7295863Snate@binkert.org    # Read the linker flags and split them into libraries and other link
7303118Sstever@eecs.umich.edu    # flags. The libraries are added later through the call the CheckLib.
7313483Ssaidi@eecs.umich.edu    py_ld_flags = readCommand([python_config, '--ldflags'],
7323494Ssaidi@eecs.umich.edu        exception='').split()
7333494Ssaidi@eecs.umich.edu    py_libs = []
7343483Ssaidi@eecs.umich.edu    for lib in py_ld_flags:
7353483Ssaidi@eecs.umich.edu         if not lib.startswith('-l'):
7363483Ssaidi@eecs.umich.edu             main.Append(LINKFLAGS=[lib])
7373053Sstever@eecs.umich.edu         else:
7383053Sstever@eecs.umich.edu             lib = lib[2:]
7393918Ssaidi@eecs.umich.edu             if lib not in py_libs:
7403053Sstever@eecs.umich.edu                 py_libs.append(lib)
7413053Sstever@eecs.umich.edu
7423053Sstever@eecs.umich.edu    # verify that this stuff works
7433053Sstever@eecs.umich.edu    if not conf.CheckHeader('Python.h', '<>'):
7443053Sstever@eecs.umich.edu        print "Error: can't find Python.h header in", py_includes
7457840Snate@binkert.org        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
7467865Sgblack@eecs.umich.edu        Exit(1)
7477865Sgblack@eecs.umich.edu
7487865Sgblack@eecs.umich.edu    for lib in py_libs:
7497865Sgblack@eecs.umich.edu        if not conf.CheckLib(lib):
7507865Sgblack@eecs.umich.edu            print "Error: can't find library %s required by python" % lib
7517840Snate@binkert.org            Exit(1)
7529045SAli.Saidi@ARM.com
7539045SAli.Saidi@ARM.com# On Solaris you need to use libsocket for socket ops
7549045SAli.Saidi@ARM.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7559045SAli.Saidi@ARM.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7569045SAli.Saidi@ARM.com       print "Can't find library with socket calls (e.g. accept())"
7579045SAli.Saidi@ARM.com       Exit(1)
7589045SAli.Saidi@ARM.com
7599045SAli.Saidi@ARM.com# Check for zlib.  If the check passes, libz will be automatically
7607840Snate@binkert.org# added to the LIBS environment variable.
7617840Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
7627840Snate@binkert.org    print 'Error: did not find needed zlib compression library '\
7631858SN/A          'and/or zlib.h header file.'
7641858SN/A    print '       Please install zlib and try again.'
7651858SN/A    Exit(1)
7661858SN/A
7671858SN/A# If we have the protobuf compiler, also make sure we have the
7681858SN/A# development libraries. If the check passes, libprotobuf will be
7695863Snate@binkert.org# automatically added to the LIBS environment variable. After
7705863Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
7715863Snate@binkert.org# got both protoc and libprotobuf available.
7725863Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
7736121Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
7741858SN/A                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
7755863Snate@binkert.org
7765863Snate@binkert.org# If we have the compiler but not the library, print another warning.
7775863Snate@binkert.orgif main['PROTOC'] and not main['HAVE_PROTOBUF']:
7785863Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
7795863Snate@binkert.org        'Warning: did not find protocol buffer library and/or headers.\n' + \
7802139SN/A    '       Please install libprotobuf-dev for tracing support.' + \
7814202Sbinkertn@umich.edu    termcap.Normal
7824202Sbinkertn@umich.edu
7832139SN/A# Check for librt.
7846994Snate@binkert.orghave_posix_clock = \
7856994Snate@binkert.org    conf.CheckLibWithHeader(None, 'time.h', 'C',
7866994Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
7876994Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
7886994Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
7896994Snate@binkert.org
7906994Snate@binkert.orghave_posix_timers = \
7916994Snate@binkert.org    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
7926994Snate@binkert.org                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
7936994Snate@binkert.org
7946994Snate@binkert.orgif not GetOption('without_tcmalloc'):
7956994Snate@binkert.org    if conf.CheckLib('tcmalloc'):
7966994Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
7976994Snate@binkert.org    elif conf.CheckLib('tcmalloc_minimal'):
7986994Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
7996994Snate@binkert.org    else:
8006994Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
8016994Snate@binkert.org              "You can get a 12% performance improvement by "\
8026994Snate@binkert.org              "installing tcmalloc (libgoogle-perftools-dev package "\
8036994Snate@binkert.org              "on Ubuntu or RedHat)." + termcap.Normal
8046994Snate@binkert.org
8056994Snate@binkert.org
8066994Snate@binkert.org# Detect back trace implementations. The last implementation in the
8076994Snate@binkert.org# list will be used by default.
8086994Snate@binkert.orgbacktrace_impls = [ "none" ]
8096994Snate@binkert.org
8106994Snate@binkert.orgif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
8116994Snate@binkert.org                           'backtrace_symbols_fd((void*)0, 0, 0);'):
8122155SN/A    backtrace_impls.append("glibc")
8135863Snate@binkert.orgelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
8141869SN/A                           'backtrace_symbols_fd((void*)0, 0, 0);'):
8151869SN/A    # NetBSD and FreeBSD need libexecinfo.
8165863Snate@binkert.org    backtrace_impls.append("glibc")
8175863Snate@binkert.org    main.Append(LIBS=['execinfo'])
8184202Sbinkertn@umich.edu
8196108Snate@binkert.orgif backtrace_impls[-1] == "none":
8206108Snate@binkert.org    default_backtrace_impl = "none"
8216108Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
8226108Snate@binkert.org        "No suitable back trace implementation found." + \
8234202Sbinkertn@umich.edu        termcap.Normal
8245863Snate@binkert.org
8258474Sgblack@eecs.umich.eduif not have_posix_clock:
8268474Sgblack@eecs.umich.edu    print "Can't find library for POSIX clocks."
8275742Snate@binkert.org
8288268Ssteve.reinhardt@amd.com# Check for <fenv.h> (C99 FP environment control)
8298268Ssteve.reinhardt@amd.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
8308268Ssteve.reinhardt@amd.comif not have_fenv:
8315742Snate@binkert.org    print "Warning: Header file <fenv.h> not found."
8325341Sstever@gmail.com    print "         This host has no IEEE FP rounding mode control."
8338474Sgblack@eecs.umich.edu
8348474Sgblack@eecs.umich.edu# Check for <png.h> (libpng library needed if wanting to dump
8355342Sstever@gmail.com# frame buffer image in png format)
8364202Sbinkertn@umich.eduhave_png = conf.CheckHeader('png.h', '<>')
8374202Sbinkertn@umich.eduif not have_png:
8384202Sbinkertn@umich.edu    print "Warning: Header file <png.h> not found."
8395863Snate@binkert.org    print "         This host has no libpng library."
8405863Snate@binkert.org    print "         Disabling support for PNG framebuffers."
8416994Snate@binkert.org
8426994Snate@binkert.org# Check if we should enable KVM-based hardware virtualization. The API
8436994Snate@binkert.org# we rely on exists since version 2.6.36 of the kernel, but somehow
8445863Snate@binkert.org# the KVM_API_VERSION does not reflect the change. We test for one of
8455863Snate@binkert.org# the types as a fall back.
8465863Snate@binkert.orghave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
8475863Snate@binkert.orgif not have_kvm:
8485863Snate@binkert.org    print "Info: Compatible header file <linux/kvm.h> not found, " \
8495863Snate@binkert.org        "disabling KVM support."
8505863Snate@binkert.org
8515863Snate@binkert.org# Check if the TUN/TAP driver is available.
8527840Snate@binkert.orghave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
8535863Snate@binkert.orgif not have_tuntap:
8545952Ssaidi@eecs.umich.edu    print "Info: Compatible header file <linux/if_tun.h> not found."
8551869SN/A
8561858SN/A# x86 needs support for xsave. We test for the structure here since we
8575863Snate@binkert.org# won't be able to run new tests by the time we know which ISA we're
8589044SAli.Saidi@ARM.com# targeting.
8598805Sgblack@eecs.umich.eduhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
8601858SN/A                                    '#include <linux/kvm.h>') != 0
861955SN/A
862955SN/A# Check if the requested target ISA is compatible with the host
8631869SN/Adef is_isa_kvm_compatible(isa):
8641869SN/A    try:
8651869SN/A        import platform
8661869SN/A        host_isa = platform.machine()
8671869SN/A    except:
8685863Snate@binkert.org        print "Warning: Failed to determine host ISA."
8695863Snate@binkert.org        return False
8705863Snate@binkert.org
8711869SN/A    if not have_posix_timers:
8725863Snate@binkert.org        print "Warning: Can not enable KVM, host seems to lack support " \
8731869SN/A            "for POSIX timers"
8745863Snate@binkert.org        return False
8751869SN/A
8761869SN/A    if isa == "arm":
8771869SN/A        return host_isa in ( "armv7l", "aarch64" )
8781869SN/A    elif isa == "x86":
8798483Sgblack@eecs.umich.edu        if host_isa != "x86_64":
8801869SN/A            return False
8811869SN/A
8821869SN/A        if not have_kvm_xsave:
8831869SN/A            print "KVM on x86 requires xsave support in kernel headers."
8845863Snate@binkert.org            return False
8855863Snate@binkert.org
8861869SN/A        return True
8875863Snate@binkert.org    else:
8885863Snate@binkert.org        return False
8893356Sbinkertn@umich.edu
8903356Sbinkertn@umich.edu
8913356Sbinkertn@umich.edu# Check if the exclude_host attribute is available. We want this to
8923356Sbinkertn@umich.edu# get accurate instruction counts in KVM.
8933356Sbinkertn@umich.edumain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
8944781Snate@binkert.org    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
8955863Snate@binkert.org
8965863Snate@binkert.org
8971869SN/A######################################################################
8981869SN/A#
8991869SN/A# Finish the configuration
9006121Snate@binkert.org#
9011869SN/Amain = conf.Finish()
9022638Sstever@eecs.umich.edu
9036121Snate@binkert.org######################################################################
9046121Snate@binkert.org#
9052638Sstever@eecs.umich.edu# Collect all non-global variables
9065749Scws3k@cs.virginia.edu#
9076121Snate@binkert.org
9086121Snate@binkert.org# Define the universe of supported ISAs
9095749Scws3k@cs.virginia.eduall_isa_list = [ ]
9101869SN/Aall_gpu_isa_list = [ ]
9111869SN/AExport('all_isa_list')
9123546Sgblack@eecs.umich.eduExport('all_gpu_isa_list')
9133546Sgblack@eecs.umich.edu
9143546Sgblack@eecs.umich.educlass CpuModel(object):
9153546Sgblack@eecs.umich.edu    '''The CpuModel class encapsulates everything the ISA parser needs to
9166121Snate@binkert.org    know about a particular CPU model.'''
9175863Snate@binkert.org
9183546Sgblack@eecs.umich.edu    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9193546Sgblack@eecs.umich.edu    dict = {}
9203546Sgblack@eecs.umich.edu
9213546Sgblack@eecs.umich.edu    # Constructor.  Automatically adds models to CpuModel.dict.
9224781Snate@binkert.org    def __init__(self, name, default=False):
9234781Snate@binkert.org        self.name = name           # name of model
9246658Snate@binkert.org
9256658Snate@binkert.org        # This cpu is enabled by default
9264781Snate@binkert.org        self.default = default
9273546Sgblack@eecs.umich.edu
9283546Sgblack@eecs.umich.edu        # Add self to dict
9293546Sgblack@eecs.umich.edu        if name in CpuModel.dict:
9303546Sgblack@eecs.umich.edu            raise AttributeError, "CpuModel '%s' already registered" % name
9317756SAli.Saidi@ARM.com        CpuModel.dict[name] = self
9327816Ssteve.reinhardt@amd.com
9333546Sgblack@eecs.umich.eduExport('CpuModel')
9343546Sgblack@eecs.umich.edu
9353546Sgblack@eecs.umich.edu# Sticky variables get saved in the variables file so they persist from
9363546Sgblack@eecs.umich.edu# one invocation to the next (unless overridden, in which case the new
9374202Sbinkertn@umich.edu# value becomes sticky).
9383546Sgblack@eecs.umich.edusticky_vars = Variables(args=ARGUMENTS)
9393546Sgblack@eecs.umich.eduExport('sticky_vars')
9403546Sgblack@eecs.umich.edu
941955SN/A# Sticky variables that should be exported
942955SN/Aexport_vars = []
943955SN/AExport('export_vars')
944955SN/A
9455863Snate@binkert.org# For Ruby
9465863Snate@binkert.orgall_protocols = []
9475343Sstever@gmail.comExport('all_protocols')
9485343Sstever@gmail.comprotocol_dirs = []
9496121Snate@binkert.orgExport('protocol_dirs')
9505863Snate@binkert.orgslicc_includes = []
9514773Snate@binkert.orgExport('slicc_includes')
9525863Snate@binkert.org
9532632Sstever@eecs.umich.edu# Walk the tree and execute all SConsopts scripts that wil add to the
9545863Snate@binkert.org# above variables
9552023SN/Aif GetOption('verbose'):
9565863Snate@binkert.org    print "Reading SConsopts"
9575863Snate@binkert.orgfor bdir in [ base_dir ] + extras_dir_list:
9585863Snate@binkert.org    if not isdir(bdir):
9595863Snate@binkert.org        print "Error: directory '%s' does not exist" % bdir
9605863Snate@binkert.org        Exit(1)
9615863Snate@binkert.org    for root, dirs, files in os.walk(bdir):
9625863Snate@binkert.org        if 'SConsopts' in files:
9635863Snate@binkert.org            if GetOption('verbose'):
9645863Snate@binkert.org                print "Reading", joinpath(root, 'SConsopts')
9652632Sstever@eecs.umich.edu            SConscript(joinpath(root, 'SConsopts'))
9665863Snate@binkert.org
9672023SN/Aall_isa_list.sort()
9682632Sstever@eecs.umich.eduall_gpu_isa_list.sort()
9695863Snate@binkert.org
9705342Sstever@gmail.comsticky_vars.AddVariables(
9715863Snate@binkert.org    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
9722632Sstever@eecs.umich.edu    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
9735863Snate@binkert.org    ListVariable('CPU_MODELS', 'CPU models',
9745863Snate@binkert.org                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
9758267Ssteve.reinhardt@amd.com                 sorted(CpuModel.dict.keys())),
9768120Sgblack@eecs.umich.edu    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
9778267Ssteve.reinhardt@amd.com                 False),
9788267Ssteve.reinhardt@amd.com    BoolVariable('SS_COMPATIBLE_FP',
9798267Ssteve.reinhardt@amd.com                 'Make floating-point results compatible with SimpleScalar',
9808267Ssteve.reinhardt@amd.com                 False),
9818267Ssteve.reinhardt@amd.com    BoolVariable('USE_SSE2',
9828267Ssteve.reinhardt@amd.com                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
9838267Ssteve.reinhardt@amd.com                 False),
9848267Ssteve.reinhardt@amd.com    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
9858267Ssteve.reinhardt@amd.com    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
9865863Snate@binkert.org    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
9875863Snate@binkert.org    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
9885863Snate@binkert.org                 False),
9892632Sstever@eecs.umich.edu    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
9908267Ssteve.reinhardt@amd.com                 have_kvm),
9918267Ssteve.reinhardt@amd.com    BoolVariable('USE_TUNTAP',
9928267Ssteve.reinhardt@amd.com                 'Enable using a tap device to bridge to the host network',
9932632Sstever@eecs.umich.edu                 have_tuntap),
9941888SN/A    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
9955863Snate@binkert.org    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
9965863Snate@binkert.org                  all_protocols),
9971858SN/A    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
9988120Sgblack@eecs.umich.edu                 backtrace_impls[-1], backtrace_impls)
9998120Sgblack@eecs.umich.edu    )
10007756SAli.Saidi@ARM.com
10012598SN/A# These variables get exported to #defines in config/*.hh (see src/SConscript).
10025863Snate@binkert.orgexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
10031858SN/A                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
10041858SN/A                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST',
10051858SN/A                'USE_PNG']
10065863Snate@binkert.org
10071858SN/A###################################################
10081858SN/A#
10091858SN/A# Define a SCons builder for configuration flag headers.
10105863Snate@binkert.org#
10111871SN/A###################################################
10121858SN/A
10131858SN/A# This function generates a config header file that #defines the
10141858SN/A# variable symbol to the current variable setting (0 or 1).  The source
10151858SN/A# operands are the name of the variable and a Value node containing the
10165863Snate@binkert.org# value of the variable.
10175863Snate@binkert.orgdef build_config_file(target, source, env):
10181869SN/A    (variable, value) = [s.get_contents() for s in source]
10191965SN/A    f = file(str(target[0]), 'w')
10207739Sgblack@eecs.umich.edu    print >> f, '#define', variable, value
10211965SN/A    f.close()
10229045SAli.Saidi@ARM.com    return None
10239045SAli.Saidi@ARM.com
10249045SAli.Saidi@ARM.com# Combine the two functions into a scons Action object.
10252761Sstever@eecs.umich.educonfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
10265863Snate@binkert.org
10271869SN/A# The emitter munges the source & target node lists to reflect what
10285863Snate@binkert.org# we're really doing.
10292667Sstever@eecs.umich.edudef config_emitter(target, source, env):
10301869SN/A    # extract variable name from Builder arg
10311869SN/A    variable = str(target[0])
10322929Sktlim@umich.edu    # True target is config header file
10332929Sktlim@umich.edu    target = joinpath('config', variable.lower() + '.hh')
10345863Snate@binkert.org    val = env[variable]
10352929Sktlim@umich.edu    if isinstance(val, bool):
1036955SN/A        # Force value to 0/1
10378120Sgblack@eecs.umich.edu        val = int(val)
10388120Sgblack@eecs.umich.edu    elif isinstance(val, str):
10398120Sgblack@eecs.umich.edu        val = '"' + val + '"'
10408120Sgblack@eecs.umich.edu
10418120Sgblack@eecs.umich.edu    # Sources are variable name & value (packaged in SCons Value nodes)
10428120Sgblack@eecs.umich.edu    return ([target], [Value(variable), Value(val)])
10438120Sgblack@eecs.umich.edu
10448120Sgblack@eecs.umich.educonfig_builder = Builder(emitter = config_emitter, action = config_action)
10458120Sgblack@eecs.umich.edu
10468120Sgblack@eecs.umich.edumain.Append(BUILDERS = { 'ConfigFile' : config_builder })
10478120Sgblack@eecs.umich.edu
10488120Sgblack@eecs.umich.edu###################################################
1049#
1050# Builders for static and shared partially linked object files.
1051#
1052###################################################
1053
1054partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1055                                 src_suffix='$OBJSUFFIX',
1056                                 src_builder=['StaticObject', 'Object'],
1057                                 LINKFLAGS='$PLINKFLAGS',
1058                                 LIBS='')
1059
1060def partial_shared_emitter(target, source, env):
1061    for tgt in target:
1062        tgt.attributes.shared = 1
1063    return (target, source)
1064partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1065                                 emitter=partial_shared_emitter,
1066                                 src_suffix='$SHOBJSUFFIX',
1067                                 src_builder='SharedObject',
1068                                 SHLINKFLAGS='$PSHLINKFLAGS',
1069                                 LIBS='')
1070
1071main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1072                         'PartialStatic' : partial_static_builder })
1073
1074# builds in ext are shared across all configs in the build root.
1075ext_dir = abspath(joinpath(str(main.root), 'ext'))
1076ext_build_dirs = []
1077for root, dirs, files in os.walk(ext_dir):
1078    if 'SConscript' in files:
1079        build_dir = os.path.relpath(root, ext_dir)
1080        ext_build_dirs.append(build_dir)
1081        main.SConscript(joinpath(root, 'SConscript'),
1082                        variant_dir=joinpath(build_root, build_dir))
1083
1084main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1085
1086###################################################
1087#
1088# This builder and wrapper method are used to set up a directory with
1089# switching headers. Those are headers which are in a generic location and
1090# that include more specific headers from a directory chosen at build time
1091# based on the current build settings.
1092#
1093###################################################
1094
1095def build_switching_header(target, source, env):
1096    path = str(target[0])
1097    subdir = str(source[0])
1098    dp, fp = os.path.split(path)
1099    dp = os.path.relpath(os.path.realpath(dp),
1100                         os.path.realpath(env['BUILDDIR']))
1101    with open(path, 'w') as hdr:
1102        print >>hdr, '#include "%s/%s/%s"' % (dp, subdir, fp)
1103
1104switching_header_action = MakeAction(build_switching_header,
1105                                     Transform('GENERATE'))
1106
1107switching_header_builder = Builder(action=switching_header_action,
1108                                   source_factory=Value,
1109                                   single_source=True)
1110
1111main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1112
1113def switching_headers(self, headers, source):
1114    for header in headers:
1115        self.SwitchingHeader(header, source)
1116
1117main.AddMethod(switching_headers, 'SwitchingHeaders')
1118
1119###################################################
1120#
1121# Define build environments for selected configurations.
1122#
1123###################################################
1124
1125for variant_path in variant_paths:
1126    if not GetOption('silent'):
1127        print "Building in", variant_path
1128
1129    # Make a copy of the build-root environment to use for this config.
1130    env = main.Clone()
1131    env['BUILDDIR'] = variant_path
1132
1133    # variant_dir is the tail component of build path, and is used to
1134    # determine the build parameters (e.g., 'ALPHA_SE')
1135    (build_root, variant_dir) = splitpath(variant_path)
1136
1137    # Set env variables according to the build directory config.
1138    sticky_vars.files = []
1139    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1140    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1141    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1142    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1143    if isfile(current_vars_file):
1144        sticky_vars.files.append(current_vars_file)
1145        if not GetOption('silent'):
1146            print "Using saved variables file %s" % current_vars_file
1147    elif variant_dir in ext_build_dirs:
1148        # Things in ext are built without a variant directory.
1149        continue
1150    else:
1151        # Build dir-specific variables file doesn't exist.
1152
1153        # Make sure the directory is there so we can create it later
1154        opt_dir = dirname(current_vars_file)
1155        if not isdir(opt_dir):
1156            mkdir(opt_dir)
1157
1158        # Get default build variables from source tree.  Variables are
1159        # normally determined by name of $VARIANT_DIR, but can be
1160        # overridden by '--default=' arg on command line.
1161        default = GetOption('default')
1162        opts_dir = joinpath(main.root.abspath, 'build_opts')
1163        if default:
1164            default_vars_files = [joinpath(build_root, 'variables', default),
1165                                  joinpath(opts_dir, default)]
1166        else:
1167            default_vars_files = [joinpath(opts_dir, variant_dir)]
1168        existing_files = filter(isfile, default_vars_files)
1169        if existing_files:
1170            default_vars_file = existing_files[0]
1171            sticky_vars.files.append(default_vars_file)
1172            print "Variables file %s not found,\n  using defaults in %s" \
1173                  % (current_vars_file, default_vars_file)
1174        else:
1175            print "Error: cannot find variables file %s or " \
1176                  "default file(s) %s" \
1177                  % (current_vars_file, ' or '.join(default_vars_files))
1178            Exit(1)
1179
1180    # Apply current variable settings to env
1181    sticky_vars.Update(env)
1182
1183    help_texts["local_vars"] += \
1184        "Build variables for %s:\n" % variant_dir \
1185                 + sticky_vars.GenerateHelpText(env)
1186
1187    # Process variable settings.
1188
1189    if not have_fenv and env['USE_FENV']:
1190        print "Warning: <fenv.h> not available; " \
1191              "forcing USE_FENV to False in", variant_dir + "."
1192        env['USE_FENV'] = False
1193
1194    if not env['USE_FENV']:
1195        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1196        print "         FP results may deviate slightly from other platforms."
1197
1198    if not have_png and env['USE_PNG']:
1199        print "Warning: <png.h> not available; " \
1200              "forcing USE_PNG to False in", variant_dir + "."
1201        env['USE_PNG'] = False
1202
1203    if env['USE_PNG']:
1204        env.Append(LIBS=['png'])
1205
1206    if env['EFENCE']:
1207        env.Append(LIBS=['efence'])
1208
1209    if env['USE_KVM']:
1210        if not have_kvm:
1211            print "Warning: Can not enable KVM, host seems to lack KVM support"
1212            env['USE_KVM'] = False
1213        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1214            print "Info: KVM support disabled due to unsupported host and " \
1215                "target ISA combination"
1216            env['USE_KVM'] = False
1217
1218    if env['USE_TUNTAP']:
1219        if not have_tuntap:
1220            print "Warning: Can't connect EtherTap with a tap device."
1221            env['USE_TUNTAP'] = False
1222
1223    if env['BUILD_GPU']:
1224        env.Append(CPPDEFINES=['BUILD_GPU'])
1225
1226    # Warn about missing optional functionality
1227    if env['USE_KVM']:
1228        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1229            print "Warning: perf_event headers lack support for the " \
1230                "exclude_host attribute. KVM instruction counts will " \
1231                "be inaccurate."
1232
1233    # Save sticky variable settings back to current variables file
1234    sticky_vars.Save(current_vars_file, env)
1235
1236    if env['USE_SSE2']:
1237        env.Append(CCFLAGS=['-msse2'])
1238
1239    # The src/SConscript file sets up the build rules in 'env' according
1240    # to the configured variables.  It returns a list of environments,
1241    # one for each variant build (debug, opt, etc.)
1242    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1243
1244# base help text
1245Help('''
1246Usage: scons [scons options] [build variables] [target(s)]
1247
1248Extra scons options:
1249%(options)s
1250
1251Global build variables:
1252%(global_vars)s
1253
1254%(local_vars)s
1255''' % help_texts)
1256