SConstruct revision 12485
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
8112563Sgabeblack@google.com# Global Python includes
8212563Sgabeblack@google.comimport itertools
836654Snate@binkert.orgimport os
8410196SCurtis.Dunham@arm.comimport re
85955SN/Aimport shutil
865396Ssaidi@eecs.umich.eduimport subprocess
8711401Sandreas.sandberg@arm.comimport sys
885863Snate@binkert.org
895863Snate@binkert.orgfrom os import mkdir, environ
904202Sbinkertn@umich.edufrom 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
9513541Sandrea.mondelli@ucf.eduimport SCons
96955SN/Aimport SCons.Node
976654Snate@binkert.org
985273Sstever@gmail.comfrom m5.util import compareVersions, readCommand
995871Snate@binkert.org
1005273Sstever@gmail.comhelp_texts = {
1016654Snate@binkert.org    "options" : "",
1025396Ssaidi@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
1088120Sgblack@eecs.umich.edu
1098120Sgblack@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1108120Sgblack@eecs.umich.edu# 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):
1218879Ssteve.reinhardt@amd.com    col_width = 30
1228879Ssteve.reinhardt@amd.com
1238879Ssteve.reinhardt@amd.com    help = "  " + ", ".join(args)
1248120Sgblack@eecs.umich.edu    if "help" in kwargs:
1258120Sgblack@eecs.umich.edu        length = len(help)
1268120Sgblack@eecs.umich.edu        if length >= col_width:
1278120Sgblack@eecs.umich.edu            help += "\n" + " " * col_width
1288120Sgblack@eecs.umich.edu        else:
1298120Sgblack@eecs.umich.edu            help += " " * (col_width - length)
1308120Sgblack@eecs.umich.edu        help += kwargs["help"]
1318120Sgblack@eecs.umich.edu    help_texts["options"] += help + "\n"
1328120Sgblack@eecs.umich.edu
1338120Sgblack@eecs.umich.edu    AddOption(*args, **kwargs)
1348120Sgblack@eecs.umich.edu
1358120Sgblack@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1368120Sgblack@eecs.umich.edu               help="Add color to abbreviated scons output")
1378120Sgblack@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
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")
14210458Sandreas.hansson@arm.comAddLocalOption('--default', dest='default', type='string', action='store',
14310458Sandreas.hansson@arm.com               help='Override which build_opts file to use for defaults')
14410458Sandreas.hansson@arm.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1458879Ssteve.reinhardt@amd.com               help='Disable style checking hooks')
1468879Ssteve.reinhardt@amd.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1478879Ssteve.reinhardt@amd.com               help='Disable Link-Time Optimization for fast')
1488879Ssteve.reinhardt@amd.comAddLocalOption('--force-lto', dest='force_lto', action='store_true',
14913421Sciro.santilli@arm.com               help='Use Link-Time Optimization instead of partial linking' +
15013421Sciro.santilli@arm.com                    ' when the compiler doesn\'t support using them together.')
1519227Sandreas.hansson@arm.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1529227Sandreas.hansson@arm.com               help='Update test reference outputs')
15312063Sgabeblack@google.comAddLocalOption('--verbose', dest='verbose', action='store_true',
15412063Sgabeblack@google.com               help='Print full tool command lines')
15512063Sgabeblack@google.comAddLocalOption('--without-python', dest='without_python',
1568879Ssteve.reinhardt@amd.com               action='store_true',
1578879Ssteve.reinhardt@amd.com               help='Build without Python configuration support')
1588879Ssteve.reinhardt@amd.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1598879Ssteve.reinhardt@amd.com               action='store_true',
16010453SAndrew.Bardsley@arm.com               help='Disable linking against tcmalloc')
16110453SAndrew.Bardsley@arm.comAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
16210453SAndrew.Bardsley@arm.com               help='Build with Undefined Behavior Sanitizer if available')
16310456SCurtis.Dunham@arm.comAddLocalOption('--with-asan', dest='with_asan', action='store_true',
16410456SCurtis.Dunham@arm.com               help='Build with Address Sanitizer if available')
16510456SCurtis.Dunham@arm.com
16610457Sandreas.hansson@arm.comif GetOption('no_lto') and GetOption('force_lto'):
16710457Sandreas.hansson@arm.com    print '--no-lto and --force-lto are mutually exclusive'
16811342Sandreas.hansson@arm.com    Exit(1)
16911342Sandreas.hansson@arm.com
1708120Sgblack@eecs.umich.edu########################################################################
17112063Sgabeblack@google.com#
17212563Sgabeblack@google.com# Set up the main build environment.
17312063Sgabeblack@google.com#
17412063Sgabeblack@google.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
1809926Sstan.czerniawski@arm.comtermcap = get_termcap()
18112243Sgabeblack@google.com
1821533SN/Amain_dict_keys = main.Dictionary().keys()
18312246Sgabeblack@google.com
18412246Sgabeblack@google.com# Check that we have a C/C++ compiler
18512246Sgabeblack@google.comif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
18612246Sgabeblack@google.com    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
1879239Sandreas.hansson@arm.com    Exit(1)
1889239Sandreas.hansson@arm.com
1899239Sandreas.hansson@arm.com###################################################
1909239Sandreas.hansson@arm.com#
19112563Sgabeblack@google.com# Figure out which configurations to set up based on the path(s) of
1929239Sandreas.hansson@arm.com# the target(s).
1939239Sandreas.hansson@arm.com#
194955SN/A###################################################
195955SN/A
1962632Sstever@eecs.umich.edu# Find default configuration & binary.
1972632Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
198955SN/A
199955SN/A# helper function: find last occurrence of element in list
200955SN/Adef rfind(l, elt, offs = -1):
201955SN/A    for i in range(len(l)+offs, 0, -1):
2028878Ssteve.reinhardt@amd.com        if l[i] == elt:
203955SN/A            return i
2042632Sstever@eecs.umich.edu    raise ValueError, "element not found"
2052632Sstever@eecs.umich.edu
2062632Sstever@eecs.umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
2072632Sstever@eecs.umich.edu# paths made absolute and ~-expanded.  Paths will be interpreted
2082632Sstever@eecs.umich.edu# relative to the launch directory unless a different root is provided
2092632Sstever@eecs.umich.edudef makePathListAbsolute(path_list, root=GetLaunchDir()):
2102632Sstever@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
2118268Ssteve.reinhardt@amd.com            for p in path_list]
2128268Ssteve.reinhardt@amd.com
2138268Ssteve.reinhardt@amd.com# Each target must have 'build' in the interior of the path; the
2148268Ssteve.reinhardt@amd.com# directory below this will determine the build parameters.  For
2158268Ssteve.reinhardt@amd.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2168268Ssteve.reinhardt@amd.com# recognize that ALPHA_SE specifies the configuration because it
2178268Ssteve.reinhardt@amd.com# follow 'build' in the build path.
21813715Sandreas.sandberg@arm.com
21913715Sandreas.sandberg@arm.com# The funky assignment to "[:]" is needed to replace the list contents
22013715Sandreas.sandberg@arm.com# in place rather than reassign the symbol to a new list, which
22113715Sandreas.sandberg@arm.com# doesn't work (obviously!).
22213715Sandreas.sandberg@arm.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
22313715Sandreas.sandberg@arm.com
22413715Sandreas.sandberg@arm.com# Generate a list of the unique build roots and configs that the
22513715Sandreas.sandberg@arm.com# collected targets reference.
22613715Sandreas.sandberg@arm.comvariant_paths = []
22713715Sandreas.sandberg@arm.combuild_root = None
22813715Sandreas.sandberg@arm.comfor t in BUILD_TARGETS:
22913715Sandreas.sandberg@arm.com    path_dirs = t.split('/')
23013715Sandreas.sandberg@arm.com    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
2342632Sstever@eecs.umich.edu        Exit(1)
2358268Ssteve.reinhardt@amd.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2362632Sstever@eecs.umich.edu    if not build_root:
2378268Ssteve.reinhardt@amd.com        build_root = this_build_root
2388268Ssteve.reinhardt@amd.com    else:
2398268Ssteve.reinhardt@amd.com        if this_build_root != build_root:
2408268Ssteve.reinhardt@amd.com            print "Error: build targets not under same build root\n"\
2413718Sstever@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
2422634Sstever@eecs.umich.edu            Exit(1)
2432634Sstever@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
2445863Snate@binkert.org    if variant_path not in variant_paths:
2452638Sstever@eecs.umich.edu        variant_paths.append(variant_path)
2468268Ssteve.reinhardt@amd.com
2472632Sstever@eecs.umich.edu# Make sure build_root exists (might not if this is the first build there)
2482632Sstever@eecs.umich.eduif not isdir(build_root):
2492632Sstever@eecs.umich.edu    mkdir(build_root)
2502632Sstever@eecs.umich.edumain['BUILDROOT'] = build_root
25112563Sgabeblack@google.com
2521858SN/AExport('main')
2533716Sstever@eecs.umich.edu
2542638Sstever@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
2552638Sstever@eecs.umich.edu
2562638Sstever@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
2572638Sstever@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
25812563Sgabeblack@google.com# file to file~ then copies to file, breaking the link.  Symbolic
25912563Sgabeblack@google.com# (soft) links work better.
2602638Sstever@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
2615863Snate@binkert.org
2625863Snate@binkert.org#
2635863Snate@binkert.org# Set up global sticky variables... these are common to an entire build
264955SN/A# tree (not specific to a particular build like ALPHA_SE)
2655341Sstever@gmail.com#
2665341Sstever@gmail.com
2675863Snate@binkert.orgglobal_vars_file = joinpath(build_root, 'variables.global')
2687756SAli.Saidi@ARM.com
2695341Sstever@gmail.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2706121Snate@binkert.org
2714494Ssaidi@eecs.umich.eduglobal_vars.AddVariables(
2726121Snate@binkert.org    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2731105SN/A    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2742667Sstever@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2752667Sstever@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
2762667Sstever@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2772667Sstever@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2786121Snate@binkert.org    ('EXTRAS', 'Add extra directories to the compilation', '')
2792667Sstever@eecs.umich.edu    )
2805341Sstever@gmail.com
2815863Snate@binkert.org# Update main environment with values from ARGUMENTS & global_vars_file
2825341Sstever@gmail.comglobal_vars.Update(main)
2835341Sstever@gmail.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
2845341Sstever@gmail.com
2858120Sgblack@eecs.umich.edu# Save sticky variable settings back to current variables file
2865341Sstever@gmail.comglobal_vars.Save(global_vars_file, main)
2878120Sgblack@eecs.umich.edu
2885341Sstever@gmail.com# Parse EXTRAS variable to build list of all directories where we're
2898120Sgblack@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
2906121Snate@binkert.orgbase_dir = main.srcdir.abspath
2916121Snate@binkert.orgif main['EXTRAS']:
29213715Sandreas.sandberg@arm.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
29313715Sandreas.sandberg@arm.comelse:
2949396Sandreas.hansson@arm.com    extras_dir_list = []
2955397Ssaidi@eecs.umich.edu
2965397Ssaidi@eecs.umich.eduExport('base_dir')
2977727SAli.Saidi@ARM.comExport('extras_dir_list')
2988268Ssteve.reinhardt@amd.com
2996168Snate@binkert.org# the ext directory should be on the #includes path
3005341Sstever@gmail.commain.Append(CPPPATH=[Dir('ext')])
3018120Sgblack@eecs.umich.edu
3028120Sgblack@eecs.umich.edu# Add shared top-level headers
3038120Sgblack@eecs.umich.edumain.Prepend(CPPPATH=Dir('include'))
3046814Sgblack@eecs.umich.edu
3055863Snate@binkert.orgif GetOption('verbose'):
3068120Sgblack@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
3075341Sstever@gmail.com        return Action(action, *args, **kwargs)
3085863Snate@binkert.orgelse:
3098268Ssteve.reinhardt@amd.com    MakeAction = Action
3106121Snate@binkert.org    main['CCCOMSTR']        = Transform("CC")
3116121Snate@binkert.org    main['CXXCOMSTR']       = Transform("CXX")
3128268Ssteve.reinhardt@amd.com    main['ASCOMSTR']        = Transform("AS")
3135742Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
3145742Snate@binkert.org    main['LINKCOMSTR']      = Transform("LINK", 0)
3155341Sstever@gmail.com    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
3165742Snate@binkert.org    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3175742Snate@binkert.org    main['M4COMSTR']        = Transform("M4")
3185341Sstever@gmail.com    main['SHCCCOMSTR']      = Transform("SHCC")
3196017Snate@binkert.org    main['SHCXXCOMSTR']     = Transform("SHCXX")
3206121Snate@binkert.orgExport('MakeAction')
3216017Snate@binkert.org
32212158Sandreas.sandberg@arm.com# Initialize the Link-Time Optimization (LTO) flags
32312158Sandreas.sandberg@arm.commain['LTO_CCFLAGS'] = []
32412158Sandreas.sandberg@arm.commain['LTO_LDFLAGS'] = []
3258120Sgblack@eecs.umich.edu
3267756SAli.Saidi@ARM.com# 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
3287756SAli.Saidi@ARM.com# are compiler-specific, so we need to set them after we detect which
3297756SAli.Saidi@ARM.com# compiler we're using.
3307816Ssteve.reinhardt@amd.commain['TCMALLOC_CCFLAGS'] = []
3317816Ssteve.reinhardt@amd.com
3327816Ssteve.reinhardt@amd.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3337816Ssteve.reinhardt@amd.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
3347816Ssteve.reinhardt@amd.com
33511979Sgabeblack@google.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3367816Ssteve.reinhardt@amd.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
3377816Ssteve.reinhardt@amd.comif main['GCC'] + main['CLANG'] > 1:
3387816Ssteve.reinhardt@amd.com    print 'Error: How can we have two at the same time?'
3397816Ssteve.reinhardt@amd.com    Exit(1)
3407756SAli.Saidi@ARM.com
3417756SAli.Saidi@ARM.com# Set up default C++ compiler flags
3429227Sandreas.hansson@arm.comif main['GCC'] or main['CLANG']:
3439227Sandreas.hansson@arm.com    # As gcc and clang share many flags, do the common parts here
3449227Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-pipe'])
3459227Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
3469590Sandreas@sandberg.pp.se    # Enable -Wall and -Wextra and then disable the few warnings that
3479590Sandreas@sandberg.pp.se    # we consistently violate
3489590Sandreas@sandberg.pp.se    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
3499590Sandreas@sandberg.pp.se                         '-Wno-sign-compare', '-Wno-unused-parameter'])
3509590Sandreas@sandberg.pp.se    # We always compile using C++11
3519590Sandreas@sandberg.pp.se    main.Append(CXXFLAGS=['-std=c++11'])
3526654Snate@binkert.org    if sys.platform.startswith('freebsd'):
3536654Snate@binkert.org        main.Append(CCFLAGS=['-I/usr/local/include'])
3545871Snate@binkert.org        main.Append(CXXFLAGS=['-I/usr/local/include'])
3556121Snate@binkert.org
3568946Sandreas.hansson@arm.com    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3579419Sandreas.hansson@arm.com    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
35812563Sgabeblack@google.com    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3593918Ssaidi@eecs.umich.edu    shared_partial_flags = ['-r', '-nostdlib']
3603918Ssaidi@eecs.umich.edu    main.Append(PSHLINKFLAGS=shared_partial_flags)
3611858SN/A    main.Append(PLINKFLAGS=shared_partial_flags)
3629556Sandreas.hansson@arm.com
3639556Sandreas.hansson@arm.com    # Treat warnings as errors but white list some warnings that we
3649556Sandreas.hansson@arm.com    # want to allow (e.g., deprecation warnings).
3659556Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Werror',
36611294Sandreas.hansson@arm.com                         '-Wno-error=deprecated-declarations',
36711294Sandreas.hansson@arm.com                         '-Wno-error=deprecated',
36811294Sandreas.hansson@arm.com                        ])
36911294Sandreas.hansson@arm.comelse:
37010878Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
37110878Sandreas.hansson@arm.com    print "Don't know what compiler options to use for your compiler."
37211811Sbaz21@cam.ac.uk    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
37311811Sbaz21@cam.ac.uk    print termcap.Yellow + '       version:' + termcap.Normal,
37411811Sbaz21@cam.ac.uk    if not CXX_version:
37511982Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
37611982Sgabeblack@google.com               termcap.Normal
37711982Sgabeblack@google.com    else:
37813421Sciro.santilli@arm.com        print CXX_version.replace('\n', '<nl>')
37913421Sciro.santilli@arm.com    print "       If you're trying to use a compiler other than GCC"
38011982Sgabeblack@google.com    print "       or clang, there appears to be something wrong with your"
38111992Sgabeblack@google.com    print "       environment."
38211982Sgabeblack@google.com    print "       "
38311982Sgabeblack@google.com    print "       If you are trying to use a compiler other than those listed"
38412305Sgabeblack@google.com    print "       above you will need to ease fix SConstruct and "
38512305Sgabeblack@google.com    print "       src/SConscript to support that compiler."
38612305Sgabeblack@google.com    Exit(1)
38712305Sgabeblack@google.com
38812305Sgabeblack@google.comif main['GCC']:
38912305Sgabeblack@google.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
39012305Sgabeblack@google.com    # level of c++11 support. See
3919556Sandreas.hansson@arm.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
39212563Sgabeblack@google.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
39312563Sgabeblack@google.com    if compareVersions(gcc_version, "4.8") < 0:
39412563Sgabeblack@google.com        print 'Error: gcc version 4.8 or newer required.'
39512563Sgabeblack@google.com        print '       Installed version:', gcc_version
3969556Sandreas.hansson@arm.com        Exit(1)
39712563Sgabeblack@google.com
39812563Sgabeblack@google.com    main['GCC_VERSION'] = gcc_version
3999556Sandreas.hansson@arm.com
40012563Sgabeblack@google.com    if compareVersions(gcc_version, '4.9') >= 0:
40112563Sgabeblack@google.com        # Incremental linking with LTO is currently broken in gcc versions
40212563Sgabeblack@google.com        # 4.9 and above. A version where everything works completely hasn't
40312563Sgabeblack@google.com        # yet been identified.
40412563Sgabeblack@google.com        #
40512563Sgabeblack@google.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
40612563Sgabeblack@google.com        main['BROKEN_INCREMENTAL_LTO'] = True
40712563Sgabeblack@google.com    if compareVersions(gcc_version, '6.0') >= 0:
4089556Sandreas.hansson@arm.com        # gcc versions 6.0 and greater accept an -flinker-output flag which
4099556Sandreas.hansson@arm.com        # selects what type of output the linker should generate. This is
4106121Snate@binkert.org        # necessary for incremental lto to work, but is also broken in
41111500Sandreas.hansson@arm.com        # current versions of gcc. It may not be necessary in future
41210238Sandreas.hansson@arm.com        # versions. We add it here since it might be, and as a reminder that
41310878Sandreas.hansson@arm.com        # it exists. It's excluded if lto is being forced.
4149420Sandreas.hansson@arm.com        #
41511500Sandreas.hansson@arm.com        # https://gcc.gnu.org/gcc-6/changes.html
41612563Sgabeblack@google.com        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
41712563Sgabeblack@google.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
4189420Sandreas.hansson@arm.com        if not GetOption('force_lto'):
4199420Sandreas.hansson@arm.com            main.Append(PSHLINKFLAGS='-flinker-output=rel')
4209420Sandreas.hansson@arm.com            main.Append(PLINKFLAGS='-flinker-output=rel')
4219420Sandreas.hansson@arm.com
42212063Sgabeblack@google.com    # gcc from version 4.8 and above generates "rep; ret" instructions
42312063Sgabeblack@google.com    # to avoid performance penalties on certain AMD chips. Older
42412063Sgabeblack@google.com    # assemblers detect this as an error, "Error: expecting string
42512063Sgabeblack@google.com    # instruction after `rep'"
42612063Sgabeblack@google.com    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
42712063Sgabeblack@google.com                                  '-o', '/dev/null'],
42812063Sgabeblack@google.com                                 exception=False).split()
42912063Sgabeblack@google.com
43012063Sgabeblack@google.com    # version strings may contain extra distro-specific
43112063Sgabeblack@google.com    # qualifiers, so play it safe and keep only what comes before
43212063Sgabeblack@google.com    # the first hyphen
43312063Sgabeblack@google.com    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
43412063Sgabeblack@google.com
43512063Sgabeblack@google.com    if not as_version or compareVersions(as_version, "2.23") < 0:
43612063Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + \
43712063Sgabeblack@google.com            'Warning: This combination of gcc and binutils have' + \
43812063Sgabeblack@google.com            ' known incompatibilities.\n' + \
43912063Sgabeblack@google.com            '         If you encounter build problems, please update ' + \
44012063Sgabeblack@google.com            'binutils to 2.23.' + \
44112063Sgabeblack@google.com            termcap.Normal
44212063Sgabeblack@google.com
44312063Sgabeblack@google.com    # Make sure we warn if the user has requested to compile with the
44410457Sandreas.hansson@arm.com    # Undefined Benahvior Sanitizer and this version of gcc does not
44510457Sandreas.hansson@arm.com    # support it.
44610457Sandreas.hansson@arm.com    if GetOption('with_ubsan') and \
44710457Sandreas.hansson@arm.com            compareVersions(gcc_version, '4.9') < 0:
44810457Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + \
44912563Sgabeblack@google.com            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
45012563Sgabeblack@google.com            termcap.Normal
45112563Sgabeblack@google.com
45210457Sandreas.hansson@arm.com    disable_lto = GetOption('no_lto')
45312063Sgabeblack@google.com    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
45412063Sgabeblack@google.com            not GetOption('force_lto'):
45512063Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + \
45612563Sgabeblack@google.com            'Warning: Your compiler doesn\'t support incremental linking' + \
45712563Sgabeblack@google.com            ' and lto at the same time, so lto is being disabled. To force' + \
45812563Sgabeblack@google.com            ' lto on anyway, use the --force-lto option. That will disable' + \
45912563Sgabeblack@google.com            ' partial linking.' + \
46012563Sgabeblack@google.com            termcap.Normal
46112563Sgabeblack@google.com        disable_lto = True
46212063Sgabeblack@google.com
46312063Sgabeblack@google.com    # Add the appropriate Link-Time Optimization (LTO) flags
46410238Sandreas.hansson@arm.com    # unless LTO is explicitly turned off. Note that these flags
46510238Sandreas.hansson@arm.com    # are only used by the fast target.
46610238Sandreas.hansson@arm.com    if not disable_lto:
46712063Sgabeblack@google.com        # Pass the LTO flag when compiling to produce GIMPLE
46810238Sandreas.hansson@arm.com        # output, we merely create the flags here and only append
46910238Sandreas.hansson@arm.com        # them later
47010416Sandreas.hansson@arm.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
47110238Sandreas.hansson@arm.com
4729227Sandreas.hansson@arm.com        # Use the same amount of jobs for LTO as we are running
47310238Sandreas.hansson@arm.com        # scons with
47410416Sandreas.hansson@arm.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
47510416Sandreas.hansson@arm.com
4769227Sandreas.hansson@arm.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4779590Sandreas@sandberg.pp.se                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4789590Sandreas@sandberg.pp.se
4799590Sandreas@sandberg.pp.se    # add option to check for undeclared overrides
48012304Sgabeblack@google.com    if compareVersions(gcc_version, "5.0") > 0:
48112304Sgabeblack@google.com        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
48212304Sgabeblack@google.com
48312688Sgiacomo.travaglini@arm.com    # The address sanitizer is available for gcc >= 4.8
48412688Sgiacomo.travaglini@arm.com    if GetOption('with_asan'):
48512688Sgiacomo.travaglini@arm.com        if GetOption('with_ubsan') and \
48613020Sshunhsingou@google.com                compareVersions(env['GCC_VERSION'], '4.9') >= 0:
48712304Sgabeblack@google.com            env.Append(CCFLAGS=['-fsanitize=address,undefined',
48812688Sgiacomo.travaglini@arm.com                                '-fno-omit-frame-pointer'],
48912688Sgiacomo.travaglini@arm.com                       LINKFLAGS='-fsanitize=address,undefined')
49013020Sshunhsingou@google.com        else:
49112304Sgabeblack@google.com            env.Append(CCFLAGS=['-fsanitize=address',
49212304Sgabeblack@google.com                                '-fno-omit-frame-pointer'],
49312304Sgabeblack@google.com                       LINKFLAGS='-fsanitize=address')
49412304Sgabeblack@google.com    # Only gcc >= 4.9 supports UBSan, so check both the version
49512688Sgiacomo.travaglini@arm.com    # and the command-line option before adding the compiler and
49612688Sgiacomo.travaglini@arm.com    # linker flags.
49712688Sgiacomo.travaglini@arm.com    elif GetOption('with_ubsan') and \
49812304Sgabeblack@google.com            compareVersions(env['GCC_VERSION'], '4.9') >= 0:
4998737Skoansin.tan@gmail.com        env.Append(CCFLAGS='-fsanitize=undefined')
50010878Sandreas.hansson@arm.com        env.Append(LINKFLAGS='-fsanitize=undefined')
50111500Sandreas.hansson@arm.com
5029420Sandreas.hansson@arm.comelif main['CLANG']:
5038737Skoansin.tan@gmail.com    # Check for a supported version of clang, >= 3.1 is needed to
50410106SMitch.Hayenga@arm.com    # support similar features as gcc 4.8. See
5058737Skoansin.tan@gmail.com    # http://clang.llvm.org/cxx_status.html for details
5068737Skoansin.tan@gmail.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
50710878Sandreas.hansson@arm.com    clang_version_match = clang_version_re.search(CXX_version)
50812563Sgabeblack@google.com    if (clang_version_match):
50912563Sgabeblack@google.com        clang_version = clang_version_match.groups()[0]
5108737Skoansin.tan@gmail.com        if compareVersions(clang_version, "3.1") < 0:
5118737Skoansin.tan@gmail.com            print 'Error: clang version 3.1 or newer required.'
51212563Sgabeblack@google.com            print '       Installed version:', clang_version
5138737Skoansin.tan@gmail.com            Exit(1)
5148737Skoansin.tan@gmail.com    else:
51511294Sandreas.hansson@arm.com        print 'Error: Unable to determine clang version.'
5169556Sandreas.hansson@arm.com        Exit(1)
5179556Sandreas.hansson@arm.com
5189556Sandreas.hansson@arm.com    # clang has a few additional warnings that we disable, extraneous
51911294Sandreas.hansson@arm.com    # parantheses are allowed due to Ruby's printing of the AST,
52010278SAndreas.Sandberg@ARM.com    # finally self assignments are allowed as the generated CPU code
52110278SAndreas.Sandberg@ARM.com    # is relying on this
52210278SAndreas.Sandberg@ARM.com    main.Append(CCFLAGS=['-Wno-parentheses',
52310278SAndreas.Sandberg@ARM.com                         '-Wno-self-assign',
52410278SAndreas.Sandberg@ARM.com                         # Some versions of libstdc++ (4.8?) seem to
52510278SAndreas.Sandberg@ARM.com                         # use struct hash and class hash
5269556Sandreas.hansson@arm.com                         # interchangeably.
5279590Sandreas@sandberg.pp.se                         '-Wno-mismatched-tags',
5289590Sandreas@sandberg.pp.se                         ])
5299420Sandreas.hansson@arm.com
5309846Sandreas.hansson@arm.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5319846Sandreas.hansson@arm.com
5329846Sandreas.hansson@arm.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5339846Sandreas.hansson@arm.com    # opposed to libstdc++, as the later is dated.
5348946Sandreas.hansson@arm.com    if sys.platform == "darwin":
53511811Sbaz21@cam.ac.uk        main.Append(CXXFLAGS=['-stdlib=libc++'])
53611811Sbaz21@cam.ac.uk        main.Append(LIBS=['c++'])
53711811Sbaz21@cam.ac.uk
53811811Sbaz21@cam.ac.uk    # On FreeBSD we need libthr.
53912304Sgabeblack@google.com    if sys.platform.startswith('freebsd'):
54012304Sgabeblack@google.com        main.Append(LIBS=['thr'])
54112304Sgabeblack@google.com
54212304Sgabeblack@google.com    # We require clang >= 3.1, so there is no need to check any
54313020Sshunhsingou@google.com    # versions here.
54413020Sshunhsingou@google.com    if GetOption('with_ubsan'):
54512304Sgabeblack@google.com        if GetOption('with_asan'):
54612304Sgabeblack@google.com            env.Append(CCFLAGS=['-fsanitize=address,undefined',
54713020Sshunhsingou@google.com                                '-fno-omit-frame-pointer'],
54813020Sshunhsingou@google.com                       LINKFLAGS='-fsanitize=address,undefined')
54912304Sgabeblack@google.com        else:
55012304Sgabeblack@google.com            env.Append(CCFLAGS='-fsanitize=undefined',
55113020Sshunhsingou@google.com                       LINKFLAGS='-fsanitize=undefined')
55213020Sshunhsingou@google.com
55312304Sgabeblack@google.com    elif GetOption('with_asan'):
55412304Sgabeblack@google.com        env.Append(CCFLAGS=['-fsanitize=address',
5553918Ssaidi@eecs.umich.edu                            '-fno-omit-frame-pointer'],
55612563Sgabeblack@google.com                   LINKFLAGS='-fsanitize=address')
55712563Sgabeblack@google.com
55812563Sgabeblack@google.comelse:
55912563Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5609068SAli.Saidi@ARM.com    print "Don't know what compiler options to use for your compiler."
56112563Sgabeblack@google.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
56212563Sgabeblack@google.com    print termcap.Yellow + '       version:' + termcap.Normal,
5639068SAli.Saidi@ARM.com    if not CXX_version:
56412563Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
56512563Sgabeblack@google.com               termcap.Normal
56612563Sgabeblack@google.com    else:
56712563Sgabeblack@google.com        print CXX_version.replace('\n', '<nl>')
56812563Sgabeblack@google.com    print "       If you're trying to use a compiler other than GCC"
56912563Sgabeblack@google.com    print "       or clang, there appears to be something wrong with your"
57012563Sgabeblack@google.com    print "       environment."
57112563Sgabeblack@google.com    print "       "
5723918Ssaidi@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
5733918Ssaidi@eecs.umich.edu    print "       above you will need to ease fix SConstruct and "
5746157Snate@binkert.org    print "       src/SConscript to support that compiler."
5756157Snate@binkert.org    Exit(1)
5766157Snate@binkert.org
5776157Snate@binkert.org# Set up common yacc/bison flags (needed for Ruby)
5785397Ssaidi@eecs.umich.edumain['YACCFLAGS'] = '-d'
5795397Ssaidi@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
5806121Snate@binkert.org
5816121Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
5826121Snate@binkert.org# extra 'qdo' every time we run scons.
5836121Snate@binkert.orgif main['BATCH']:
5846121Snate@binkert.org    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5856121Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5865397Ssaidi@eecs.umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
5871851SN/A    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
5881851SN/A    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5897739Sgblack@eecs.umich.edu
590955SN/Aif sys.platform == 'cygwin':
5919396Sandreas.hansson@arm.com    # cygwin has some header file issues...
5929396Sandreas.hansson@arm.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
5939396Sandreas.hansson@arm.com
5949396Sandreas.hansson@arm.com# Check for the protobuf compiler
5959396Sandreas.hansson@arm.comprotoc_version = readCommand([main['PROTOC'], '--version'],
5969396Sandreas.hansson@arm.com                             exception='').split()
59712563Sgabeblack@google.com
59812563Sgabeblack@google.com# First two words should be "libprotoc x.y.z"
59912563Sgabeblack@google.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
60012563Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + \
6019396Sandreas.hansson@arm.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6029396Sandreas.hansson@arm.com        '         Please install protobuf-compiler for tracing support.' + \
6039396Sandreas.hansson@arm.com        termcap.Normal
6049396Sandreas.hansson@arm.com    main['PROTOC'] = False
6059396Sandreas.hansson@arm.comelse:
6069396Sandreas.hansson@arm.com    # Based on the availability of the compress stream wrappers,
60712563Sgabeblack@google.com    # require 2.1.0
60812563Sgabeblack@google.com    min_protoc_version = '2.1.0'
60912563Sgabeblack@google.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
61012563Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + \
61112563Sgabeblack@google.com            'Warning: protoc version', min_protoc_version, \
6129477Sandreas.hansson@arm.com            'or newer required.\n' + \
6139477Sandreas.hansson@arm.com            '         Installed version:', protoc_version[1], \
6149477Sandreas.hansson@arm.com            termcap.Normal
6159477Sandreas.hansson@arm.com        main['PROTOC'] = False
6169477Sandreas.hansson@arm.com    else:
6179477Sandreas.hansson@arm.com        # Attempt to determine the appropriate include path and
6189477Sandreas.hansson@arm.com        # library path using pkg-config, that means we also need to
6199477Sandreas.hansson@arm.com        # check for pkg-config. Note that it is possible to use
6209477Sandreas.hansson@arm.com        # protobuf without the involvement of pkg-config. Later on we
6219477Sandreas.hansson@arm.com        # check go a library config check and at that point the test
6229477Sandreas.hansson@arm.com        # will fail if libprotobuf cannot be found.
6239477Sandreas.hansson@arm.com        if readCommand(['pkg-config', '--version'], exception=''):
6249477Sandreas.hansson@arm.com            try:
6259477Sandreas.hansson@arm.com                # Attempt to establish what linking flags to add for protobuf
62612563Sgabeblack@google.com                # using pkg-config
62712563Sgabeblack@google.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
62812563Sgabeblack@google.com            except:
6299396Sandreas.hansson@arm.com                print termcap.Yellow + termcap.Bold + \
6302667Sstever@eecs.umich.edu                    'Warning: pkg-config could not get protobuf flags.' + \
63110710Sandreas.hansson@arm.com                    termcap.Normal
63210710Sandreas.hansson@arm.com
63310710Sandreas.hansson@arm.com
63411811Sbaz21@cam.ac.uk# Check for 'timeout' from GNU coreutils. If present, regressions will
63511811Sbaz21@cam.ac.uk# be run with a time limit. We require version 8.13 since we rely on
63611811Sbaz21@cam.ac.uk# support for the '--foreground' option.
63711811Sbaz21@cam.ac.ukif sys.platform.startswith('freebsd'):
63811811Sbaz21@cam.ac.uk    timeout_lines = readCommand(['gtimeout', '--version'],
63911811Sbaz21@cam.ac.uk                                exception='').splitlines()
64010710Sandreas.hansson@arm.comelse:
64110710Sandreas.hansson@arm.com    timeout_lines = readCommand(['timeout', '--version'],
64210710Sandreas.hansson@arm.com                                exception='').splitlines()
64310710Sandreas.hansson@arm.com# Get the first line and tokenize it
64410384SCurtis.Dunham@arm.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
6459986Sandreas@sandberg.pp.semain['TIMEOUT'] =  timeout_version and \
6469986Sandreas@sandberg.pp.se    compareVersions(timeout_version[-1], '8.13') >= 0
6479986Sandreas@sandberg.pp.se
6489986Sandreas@sandberg.pp.se# Add a custom Check function to test for structure members.
6499986Sandreas@sandberg.pp.sedef CheckMember(context, include, decl, member, include_quotes="<>"):
6509986Sandreas@sandberg.pp.se    context.Message("Checking for member %s in %s..." %
6519986Sandreas@sandberg.pp.se                    (member, decl))
6529986Sandreas@sandberg.pp.se    text = """
6539986Sandreas@sandberg.pp.se#include %(header)s
6549986Sandreas@sandberg.pp.seint main(){
6559986Sandreas@sandberg.pp.se  %(decl)s test;
6569986Sandreas@sandberg.pp.se  (void)test.%(member)s;
6579986Sandreas@sandberg.pp.se  return 0;
6589986Sandreas@sandberg.pp.se};
6599986Sandreas@sandberg.pp.se""" % { "header" : include_quotes[0] + include + include_quotes[1],
6609986Sandreas@sandberg.pp.se        "decl" : decl,
6619986Sandreas@sandberg.pp.se        "member" : member,
6629986Sandreas@sandberg.pp.se        }
6639986Sandreas@sandberg.pp.se
6649986Sandreas@sandberg.pp.se    ret = context.TryCompile(text, extension=".cc")
6652638Sstever@eecs.umich.edu    context.Result(ret)
6662638Sstever@eecs.umich.edu    return ret
6676121Snate@binkert.org
6683716Sstever@eecs.umich.edu# Platform-specific configuration.  Note again that we assume that all
6695522Snate@binkert.org# builds under a given build root run on the same host platform.
6709986Sandreas@sandberg.pp.seconf = Configure(main,
6719986Sandreas@sandberg.pp.se                 conf_dir = joinpath(build_root, '.scons_config'),
6729986Sandreas@sandberg.pp.se                 log_file = joinpath(build_root, 'scons_config.log'),
6735522Snate@binkert.org                 custom_tests = {
6745227Ssaidi@eecs.umich.edu        'CheckMember' : CheckMember,
6755227Ssaidi@eecs.umich.edu        })
6765227Ssaidi@eecs.umich.edu
6775227Ssaidi@eecs.umich.edu# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6786654Snate@binkert.orgtry:
6796654Snate@binkert.org    import platform
6807769SAli.Saidi@ARM.com    uname = platform.uname()
6817769SAli.Saidi@ARM.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6827769SAli.Saidi@ARM.com        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6837769SAli.Saidi@ARM.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
6845227Ssaidi@eecs.umich.edu            main.Append(CFLAGS=['-arch', 'x86_64'])
6855227Ssaidi@eecs.umich.edu            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6865227Ssaidi@eecs.umich.edu            main.Append(ASFLAGS=['-arch', 'x86_64'])
6875204Sstever@gmail.comexcept:
6885204Sstever@gmail.com    pass
6895204Sstever@gmail.com
6905204Sstever@gmail.com# Recent versions of scons substitute a "Null" object for Configure()
6915204Sstever@gmail.com# when configuration isn't necessary, e.g., if the "--help" option is
6925204Sstever@gmail.com# present.  Unfortuantely this Null object always returns false,
6935204Sstever@gmail.com# breaking all our configuration checks.  We replace it with our own
6945204Sstever@gmail.com# more optimistic null object that returns True instead.
6955204Sstever@gmail.comif not conf:
6965204Sstever@gmail.com    def NullCheck(*args, **kwargs):
6975204Sstever@gmail.com        return True
6985204Sstever@gmail.com
6995204Sstever@gmail.com    class NullConf:
7005204Sstever@gmail.com        def __init__(self, env):
7015204Sstever@gmail.com            self.env = env
7025204Sstever@gmail.com        def Finish(self):
7035204Sstever@gmail.com            return self.env
7046121Snate@binkert.org        def __getattr__(self, mname):
7055204Sstever@gmail.com            return NullCheck
7067727SAli.Saidi@ARM.com
7077727SAli.Saidi@ARM.com    conf = NullConf(main)
70812563Sgabeblack@google.com
7097727SAli.Saidi@ARM.com# Cache build files in the supplied directory.
7107727SAli.Saidi@ARM.comif main['M5_BUILD_CACHE']:
71111988Sandreas.sandberg@arm.com    print 'Using build cache located at', main['M5_BUILD_CACHE']
71211988Sandreas.sandberg@arm.com    CacheDir(main['M5_BUILD_CACHE'])
71310453SAndrew.Bardsley@arm.com
71410453SAndrew.Bardsley@arm.commain['USE_PYTHON'] = not GetOption('without_python')
71510453SAndrew.Bardsley@arm.comif main['USE_PYTHON']:
71610453SAndrew.Bardsley@arm.com    # Find Python include and library directories for embedding the
71710453SAndrew.Bardsley@arm.com    # interpreter. We rely on python-config to resolve the appropriate
71810453SAndrew.Bardsley@arm.com    # includes and linker flags. ParseConfig does not seem to understand
71910453SAndrew.Bardsley@arm.com    # the more exotic linker flags such as -Xlinker and -export-dynamic so
72013715Sandreas.sandberg@arm.com    # we add them explicitly below. If you want to link in an alternate
72113715Sandreas.sandberg@arm.com    # version of python, see above for instructions on how to invoke
72213715Sandreas.sandberg@arm.com    # scons with the appropriate PATH set.
72313715Sandreas.sandberg@arm.com    #
72413715Sandreas.sandberg@arm.com    # First we check if python2-config exists, else we use python-config
72513715Sandreas.sandberg@arm.com    python_config = readCommand(['which', 'python2-config'],
72613715Sandreas.sandberg@arm.com                                exception='').strip()
72713715Sandreas.sandberg@arm.com    if not os.path.exists(python_config):
72810453SAndrew.Bardsley@arm.com        python_config = readCommand(['which', 'python-config'],
72910453SAndrew.Bardsley@arm.com                                    exception='').strip()
73013541Sandrea.mondelli@ucf.edu    py_includes = readCommand([python_config, '--includes'],
73110453SAndrew.Bardsley@arm.com                              exception='').split()
73210453SAndrew.Bardsley@arm.com    # Strip the -I from the include folders before adding them to the
73313541Sandrea.mondelli@ucf.edu    # CPPPATH
73413541Sandrea.mondelli@ucf.edu    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
7359812Sandreas.hansson@arm.com
73610453SAndrew.Bardsley@arm.com    # Read the linker flags and split them into libraries and other link
73710453SAndrew.Bardsley@arm.com    # flags. The libraries are added later through the call the CheckLib.
73810453SAndrew.Bardsley@arm.com    py_ld_flags = readCommand([python_config, '--ldflags'],
73910453SAndrew.Bardsley@arm.com        exception='').split()
74010453SAndrew.Bardsley@arm.com    py_libs = []
74110453SAndrew.Bardsley@arm.com    for lib in py_ld_flags:
74210453SAndrew.Bardsley@arm.com         if not lib.startswith('-l'):
74310453SAndrew.Bardsley@arm.com             main.Append(LINKFLAGS=[lib])
74410453SAndrew.Bardsley@arm.com         else:
74510453SAndrew.Bardsley@arm.com             lib = lib[2:]
74610453SAndrew.Bardsley@arm.com             if lib not in py_libs:
74710453SAndrew.Bardsley@arm.com                 py_libs.append(lib)
7487727SAli.Saidi@ARM.com
74910453SAndrew.Bardsley@arm.com    # verify that this stuff works
75010453SAndrew.Bardsley@arm.com    if not conf.CheckHeader('Python.h', '<>'):
75112790Smatteo.fusi@bsc.es        print "Error: can't find Python.h header in", py_includes
75212790Smatteo.fusi@bsc.es        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
75312790Smatteo.fusi@bsc.es        Exit(1)
75412790Smatteo.fusi@bsc.es
75512790Smatteo.fusi@bsc.es    for lib in py_libs:
75612790Smatteo.fusi@bsc.es        if not conf.CheckLib(lib):
75712790Smatteo.fusi@bsc.es            print "Error: can't find library %s required by python" % lib
75810453SAndrew.Bardsley@arm.com            Exit(1)
7593118Sstever@eecs.umich.edu
76010453SAndrew.Bardsley@arm.com# On Solaris you need to use libsocket for socket ops
76110453SAndrew.Bardsley@arm.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
76212563Sgabeblack@google.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
76310453SAndrew.Bardsley@arm.com       print "Can't find library with socket calls (e.g. accept())"
7643118Sstever@eecs.umich.edu       Exit(1)
7653483Ssaidi@eecs.umich.edu
7663494Ssaidi@eecs.umich.edu# Check for zlib.  If the check passes, libz will be automatically
7673494Ssaidi@eecs.umich.edu# added to the LIBS environment variable.
76812563Sgabeblack@google.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
7693483Ssaidi@eecs.umich.edu    print 'Error: did not find needed zlib compression library '\
7703483Ssaidi@eecs.umich.edu          'and/or zlib.h header file.'
7713053Sstever@eecs.umich.edu    print '       Please install zlib and try again.'
7723053Sstever@eecs.umich.edu    Exit(1)
7733918Ssaidi@eecs.umich.edu
77412563Sgabeblack@google.com# If we have the protobuf compiler, also make sure we have the
77512563Sgabeblack@google.com# development libraries. If the check passes, libprotobuf will be
77612563Sgabeblack@google.com# automatically added to the LIBS environment variable. After
7773053Sstever@eecs.umich.edu# this, we can use the HAVE_PROTOBUF flag to determine if we have
7783053Sstever@eecs.umich.edu# got both protoc and libprotobuf available.
7799396Sandreas.hansson@arm.commain['HAVE_PROTOBUF'] = main['PROTOC'] and \
7809396Sandreas.hansson@arm.com    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
7819396Sandreas.hansson@arm.com                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
7829396Sandreas.hansson@arm.com
7839396Sandreas.hansson@arm.com# If we have the compiler but not the library, print another warning.
7849396Sandreas.hansson@arm.comif main['PROTOC'] and not main['HAVE_PROTOBUF']:
7859396Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + \
7869396Sandreas.hansson@arm.com        'Warning: did not find protocol buffer library and/or headers.\n' + \
7879396Sandreas.hansson@arm.com    '       Please install libprotobuf-dev for tracing support.' + \
78812920Sgabeblack@google.com    termcap.Normal
78912920Sgabeblack@google.com
79012920Sgabeblack@google.com# Check for librt.
79112920Sgabeblack@google.comhave_posix_clock = \
7929477Sandreas.hansson@arm.com    conf.CheckLibWithHeader(None, 'time.h', 'C',
7939396Sandreas.hansson@arm.com                            'clock_nanosleep(0,0,NULL,NULL);') or \
79412563Sgabeblack@google.com    conf.CheckLibWithHeader('rt', 'time.h', 'C',
79512563Sgabeblack@google.com                            'clock_nanosleep(0,0,NULL,NULL);')
79612563Sgabeblack@google.com
79712563Sgabeblack@google.comhave_posix_timers = \
7989396Sandreas.hansson@arm.com    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
7997840Snate@binkert.org                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
8007865Sgblack@eecs.umich.edu
8017865Sgblack@eecs.umich.eduif not GetOption('without_tcmalloc'):
8027865Sgblack@eecs.umich.edu    if conf.CheckLib('tcmalloc'):
8037865Sgblack@eecs.umich.edu        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
8047865Sgblack@eecs.umich.edu    elif conf.CheckLib('tcmalloc_minimal'):
8057840Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
8069900Sandreas@sandberg.pp.se    else:
8079900Sandreas@sandberg.pp.se        print termcap.Yellow + termcap.Bold + \
8089900Sandreas@sandberg.pp.se              "You can get a 12% performance improvement by "\
8099900Sandreas@sandberg.pp.se              "installing tcmalloc (libgoogle-perftools-dev package "\
81010456SCurtis.Dunham@arm.com              "on Ubuntu or RedHat)." + termcap.Normal
81110456SCurtis.Dunham@arm.com
81210456SCurtis.Dunham@arm.com
81310456SCurtis.Dunham@arm.com# Detect back trace implementations. The last implementation in the
81410456SCurtis.Dunham@arm.com# list will be used by default.
81510456SCurtis.Dunham@arm.combacktrace_impls = [ "none" ]
81612563Sgabeblack@google.com
81712563Sgabeblack@google.combacktrace_checker = 'char temp;' + \
81812563Sgabeblack@google.com    ' backtrace_symbols_fd((void*)&temp, 0, 0);'
81912563Sgabeblack@google.comif conf.CheckLibWithHeader(None, 'execinfo.h', 'C', backtrace_checker):
8209045SAli.Saidi@ARM.com    backtrace_impls.append("glibc")
82111235Sandreas.sandberg@arm.comelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
82211235Sandreas.sandberg@arm.com                             backtrace_checker):
82311235Sandreas.sandberg@arm.com    # NetBSD and FreeBSD need libexecinfo.
82411235Sandreas.sandberg@arm.com    backtrace_impls.append("glibc")
82511235Sandreas.sandberg@arm.com    main.Append(LIBS=['execinfo'])
82612485Sjang.hanhwi@gmail.com
82712485Sjang.hanhwi@gmail.comif backtrace_impls[-1] == "none":
82812485Sjang.hanhwi@gmail.com    default_backtrace_impl = "none"
82911235Sandreas.sandberg@arm.com    print termcap.Yellow + termcap.Bold + \
83011811Sbaz21@cam.ac.uk        "No suitable back trace implementation found." + \
83112485Sjang.hanhwi@gmail.com        termcap.Normal
83211811Sbaz21@cam.ac.uk
83311811Sbaz21@cam.ac.ukif not have_posix_clock:
83411811Sbaz21@cam.ac.uk    print "Can't find library for POSIX clocks."
83511235Sandreas.sandberg@arm.com
83611235Sandreas.sandberg@arm.com# Check for <fenv.h> (C99 FP environment control)
83711235Sandreas.sandberg@arm.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
83812563Sgabeblack@google.comif not have_fenv:
83912563Sgabeblack@google.com    print "Warning: Header file <fenv.h> not found."
84012563Sgabeblack@google.com    print "         This host has no IEEE FP rounding mode control."
84111235Sandreas.sandberg@arm.com
8427840Snate@binkert.org# Check for <png.h> (libpng library needed if wanting to dump
84312563Sgabeblack@google.com# frame buffer image in png format)
8447840Snate@binkert.orghave_png = conf.CheckHeader('png.h', '<>')
8451858SN/Aif not have_png:
8461858SN/A    print "Warning: Header file <png.h> not found."
8471858SN/A    print "         This host has no libpng library."
84812563Sgabeblack@google.com    print "         Disabling support for PNG framebuffers."
84912563Sgabeblack@google.com
8501858SN/A# Check if we should enable KVM-based hardware virtualization. The API
85112230Sgiacomo.travaglini@arm.com# we rely on exists since version 2.6.36 of the kernel, but somehow
85212230Sgiacomo.travaglini@arm.com# the KVM_API_VERSION does not reflect the change. We test for one of
85312230Sgiacomo.travaglini@arm.com# the types as a fall back.
85412230Sgiacomo.travaglini@arm.comhave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
85512563Sgabeblack@google.comif not have_kvm:
85612563Sgabeblack@google.com    print "Info: Compatible header file <linux/kvm.h> not found, " \
85712563Sgabeblack@google.com        "disabling KVM support."
85812230Sgiacomo.travaglini@arm.com
8599903Sandreas.hansson@arm.com# Check if the TUN/TAP driver is available.
8609903Sandreas.hansson@arm.comhave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
8619903Sandreas.hansson@arm.comif not have_tuntap:
8629903Sandreas.hansson@arm.com    print "Info: Compatible header file <linux/if_tun.h> not found."
86310841Sandreas.sandberg@arm.com
8649651SAndreas.Sandberg@ARM.com# x86 needs support for xsave. We test for the structure here since we
86512563Sgabeblack@google.com# won't be able to run new tests by the time we know which ISA we're
86612563Sgabeblack@google.com# targeting.
8679651SAndreas.Sandberg@ARM.comhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
86812056Sgabeblack@google.com                                    '#include <linux/kvm.h>') != 0
86912056Sgabeblack@google.com
87012056Sgabeblack@google.com# Check if the requested target ISA is compatible with the host
87112563Sgabeblack@google.comdef is_isa_kvm_compatible(isa):
87212056Sgabeblack@google.com    try:
87310841Sandreas.sandberg@arm.com        import platform
87410841Sandreas.sandberg@arm.com        host_isa = platform.machine()
87510841Sandreas.sandberg@arm.com    except:
87610841Sandreas.sandberg@arm.com        print "Warning: Failed to determine host ISA."
87710841Sandreas.sandberg@arm.com        return False
87810841Sandreas.sandberg@arm.com
8799651SAndreas.Sandberg@ARM.com    if not have_posix_timers:
8809651SAndreas.Sandberg@ARM.com        print "Warning: Can not enable KVM, host seems to lack support " \
8819651SAndreas.Sandberg@ARM.com            "for POSIX timers"
8829651SAndreas.Sandberg@ARM.com        return False
8839651SAndreas.Sandberg@ARM.com
8849651SAndreas.Sandberg@ARM.com    if isa == "arm":
88512563Sgabeblack@google.com        return host_isa in ( "armv7l", "aarch64" )
8869651SAndreas.Sandberg@ARM.com    elif isa == "x86":
8879651SAndreas.Sandberg@ARM.com        if host_isa != "x86_64":
88810841Sandreas.sandberg@arm.com            return False
88912563Sgabeblack@google.com
89012563Sgabeblack@google.com        if not have_kvm_xsave:
89110841Sandreas.sandberg@arm.com            print "KVM on x86 requires xsave support in kernel headers."
89210841Sandreas.sandberg@arm.com            return False
89310841Sandreas.sandberg@arm.com
89410860Sandreas.sandberg@arm.com        return True
89510841Sandreas.sandberg@arm.com    else:
89610841Sandreas.sandberg@arm.com        return False
89710841Sandreas.sandberg@arm.com
89810841Sandreas.sandberg@arm.com
89910841Sandreas.sandberg@arm.com# Check if the exclude_host attribute is available. We want this to
90012563Sgabeblack@google.com# get accurate instruction counts in KVM.
90110841Sandreas.sandberg@arm.commain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
90210841Sandreas.sandberg@arm.com    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
90310841Sandreas.sandberg@arm.com
90410841Sandreas.sandberg@arm.com
90510841Sandreas.sandberg@arm.com######################################################################
9069651SAndreas.Sandberg@ARM.com#
9079651SAndreas.Sandberg@ARM.com# Finish the configuration
9089986Sandreas@sandberg.pp.se#
9099986Sandreas@sandberg.pp.semain = conf.Finish()
9109986Sandreas@sandberg.pp.se
9119986Sandreas@sandberg.pp.se######################################################################
9129986Sandreas@sandberg.pp.se#
9139986Sandreas@sandberg.pp.se# Collect all non-global variables
9145863Snate@binkert.org#
9155863Snate@binkert.org
9165863Snate@binkert.org# Define the universe of supported ISAs
9175863Snate@binkert.orgall_isa_list = [ ]
9186121Snate@binkert.orgall_gpu_isa_list = [ ]
9191858SN/AExport('all_isa_list')
9205863Snate@binkert.orgExport('all_gpu_isa_list')
9215863Snate@binkert.org
9225863Snate@binkert.orgclass CpuModel(object):
9235863Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
9245863Snate@binkert.org    know about a particular CPU model.'''
9252139SN/A
9264202Sbinkertn@umich.edu    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
92711308Santhony.gutierrez@amd.com    dict = {}
9284202Sbinkertn@umich.edu
92911308Santhony.gutierrez@amd.com    # Constructor.  Automatically adds models to CpuModel.dict.
9302139SN/A    def __init__(self, name, default=False):
9316994Snate@binkert.org        self.name = name           # name of model
9326994Snate@binkert.org
9336994Snate@binkert.org        # This cpu is enabled by default
9346994Snate@binkert.org        self.default = default
9356994Snate@binkert.org
9366994Snate@binkert.org        # Add self to dict
9376994Snate@binkert.org        if name in CpuModel.dict:
9386994Snate@binkert.org            raise AttributeError, "CpuModel '%s' already registered" % name
93910319SAndreas.Sandberg@ARM.com        CpuModel.dict[name] = self
9406994Snate@binkert.org
9416994Snate@binkert.orgExport('CpuModel')
9426994Snate@binkert.org
9436994Snate@binkert.org# Sticky variables get saved in the variables file so they persist from
9446994Snate@binkert.org# one invocation to the next (unless overridden, in which case the new
9456994Snate@binkert.org# value becomes sticky).
9466994Snate@binkert.orgsticky_vars = Variables(args=ARGUMENTS)
9476994Snate@binkert.orgExport('sticky_vars')
9486994Snate@binkert.org
9496994Snate@binkert.org# Sticky variables that should be exported
9506994Snate@binkert.orgexport_vars = []
9512155SN/AExport('export_vars')
9525863Snate@binkert.org
9531869SN/A# For Ruby
9541869SN/Aall_protocols = []
9555863Snate@binkert.orgExport('all_protocols')
9565863Snate@binkert.orgprotocol_dirs = []
9574202Sbinkertn@umich.eduExport('protocol_dirs')
9586108Snate@binkert.orgslicc_includes = []
9596108Snate@binkert.orgExport('slicc_includes')
9606108Snate@binkert.org
9616108Snate@binkert.org# Walk the tree and execute all SConsopts scripts that wil add to the
9629219Spower.jg@gmail.com# above variables
9639219Spower.jg@gmail.comif GetOption('verbose'):
9649219Spower.jg@gmail.com    print "Reading SConsopts"
9659219Spower.jg@gmail.comfor bdir in [ base_dir ] + extras_dir_list:
9669219Spower.jg@gmail.com    if not isdir(bdir):
9679219Spower.jg@gmail.com        print "Error: directory '%s' does not exist" % bdir
9689219Spower.jg@gmail.com        Exit(1)
9699219Spower.jg@gmail.com    for root, dirs, files in os.walk(bdir):
9704202Sbinkertn@umich.edu        if 'SConsopts' in files:
9715863Snate@binkert.org            if GetOption('verbose'):
97210135SCurtis.Dunham@arm.com                print "Reading", joinpath(root, 'SConsopts')
97312563Sgabeblack@google.com            SConscript(joinpath(root, 'SConsopts'))
9745742Snate@binkert.org
9758268Ssteve.reinhardt@amd.comall_isa_list.sort()
97612563Sgabeblack@google.comall_gpu_isa_list.sort()
9778268Ssteve.reinhardt@amd.com
9785742Snate@binkert.orgsticky_vars.AddVariables(
9795341Sstever@gmail.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
9808474Sgblack@eecs.umich.edu    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
98112563Sgabeblack@google.com    ListVariable('CPU_MODELS', 'CPU models',
9825342Sstever@gmail.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
9834202Sbinkertn@umich.edu                 sorted(CpuModel.dict.keys())),
9844202Sbinkertn@umich.edu    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
98511308Santhony.gutierrez@amd.com                 False),
9864202Sbinkertn@umich.edu    BoolVariable('SS_COMPATIBLE_FP',
9875863Snate@binkert.org                 'Make floating-point results compatible with SimpleScalar',
9885863Snate@binkert.org                 False),
98911308Santhony.gutierrez@amd.com    BoolVariable('USE_SSE2',
9906994Snate@binkert.org                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
9916994Snate@binkert.org                 False),
99210319SAndreas.Sandberg@ARM.com    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
9935863Snate@binkert.org    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
9945863Snate@binkert.org    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
9955863Snate@binkert.org    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
9965863Snate@binkert.org                 False),
9975863Snate@binkert.org    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
9985863Snate@binkert.org                 have_kvm),
9995863Snate@binkert.org    BoolVariable('USE_TUNTAP',
10005863Snate@binkert.org                 'Enable using a tap device to bridge to the host network',
10017840Snate@binkert.org                 have_tuntap),
10025863Snate@binkert.org    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
100312230Sgiacomo.travaglini@arm.com    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
100412230Sgiacomo.travaglini@arm.com                  all_protocols),
100512230Sgiacomo.travaglini@arm.com    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
100612230Sgiacomo.travaglini@arm.com                 backtrace_impls[-1], backtrace_impls)
100712230Sgiacomo.travaglini@arm.com    )
100812056Sgabeblack@google.com
100912056Sgabeblack@google.com# These variables get exported to #defines in config/*.hh (see src/SConscript).
101012056Sgabeblack@google.comexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
101111308Santhony.gutierrez@amd.com                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
10129219Spower.jg@gmail.com                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST',
10139219Spower.jg@gmail.com                'USE_PNG']
101411235Sandreas.sandberg@arm.com
101511235Sandreas.sandberg@arm.com###################################################
10161869SN/A#
10171858SN/A# Define a SCons builder for configuration flag headers.
10185863Snate@binkert.org#
101911308Santhony.gutierrez@amd.com###################################################
102012061Sjason@lowepower.com
102112920Sgabeblack@google.com# This function generates a config header file that #defines the
102212920Sgabeblack@google.com# variable symbol to the current variable setting (0 or 1).  The source
10231858SN/A# operands are the name of the variable and a Value node containing the
1024955SN/A# value of the variable.
1025955SN/Adef build_config_file(target, source, env):
10261869SN/A    (variable, value) = [s.get_contents() for s in source]
10271869SN/A    f = file(str(target[0]), 'w')
10281869SN/A    print >> f, '#define', variable, value
10291869SN/A    f.close()
10301869SN/A    return None
10315863Snate@binkert.org
10325863Snate@binkert.org# Combine the two functions into a scons Action object.
10335863Snate@binkert.orgconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
10341869SN/A
10355863Snate@binkert.org# The emitter munges the source & target node lists to reflect what
10361869SN/A# we're really doing.
103712563Sgabeblack@google.comdef config_emitter(target, source, env):
10381869SN/A    # extract variable name from Builder arg
10391869SN/A    variable = str(target[0])
10401869SN/A    # True target is config header file
10411869SN/A    target = joinpath('config', variable.lower() + '.hh')
10428483Sgblack@eecs.umich.edu    val = env[variable]
10431869SN/A    if isinstance(val, bool):
10441869SN/A        # Force value to 0/1
10451869SN/A        val = int(val)
10461869SN/A    elif isinstance(val, str):
10475863Snate@binkert.org        val = '"' + val + '"'
10485863Snate@binkert.org
10491869SN/A    # Sources are variable name & value (packaged in SCons Value nodes)
10505863Snate@binkert.org    return ([target], [Value(variable), Value(val)])
10515863Snate@binkert.org
10523356Sbinkertn@umich.educonfig_builder = Builder(emitter = config_emitter, action = config_action)
10533356Sbinkertn@umich.edu
10543356Sbinkertn@umich.edumain.Append(BUILDERS = { 'ConfigFile' : config_builder })
10553356Sbinkertn@umich.edu
10563356Sbinkertn@umich.edu###################################################
10574781Snate@binkert.org#
10585863Snate@binkert.org# Builders for static and shared partially linked object files.
10595863Snate@binkert.org#
10601869SN/A###################################################
10611869SN/A
10621869SN/Apartial_static_builder = Builder(action=SCons.Defaults.LinkAction,
10636121Snate@binkert.org                                 src_suffix='$OBJSUFFIX',
10641869SN/A                                 src_builder=['StaticObject', 'Object'],
106511982Sgabeblack@google.com                                 LINKFLAGS='$PLINKFLAGS',
106611982Sgabeblack@google.com                                 LIBS='')
106711982Sgabeblack@google.com
106811982Sgabeblack@google.comdef partial_shared_emitter(target, source, env):
106911982Sgabeblack@google.com    for tgt in target:
107011982Sgabeblack@google.com        tgt.attributes.shared = 1
107111982Sgabeblack@google.com    return (target, source)
107211982Sgabeblack@google.compartial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
107311982Sgabeblack@google.com                                 emitter=partial_shared_emitter,
107411982Sgabeblack@google.com                                 src_suffix='$SHOBJSUFFIX',
107511982Sgabeblack@google.com                                 src_builder='SharedObject',
107611982Sgabeblack@google.com                                 SHLINKFLAGS='$PSHLINKFLAGS',
107711982Sgabeblack@google.com                                 LIBS='')
107811982Sgabeblack@google.com
107911982Sgabeblack@google.commain.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
108011982Sgabeblack@google.com                         'PartialStatic' : partial_static_builder })
108111982Sgabeblack@google.com
108211982Sgabeblack@google.com# builds in ext are shared across all configs in the build root.
108311982Sgabeblack@google.comext_dir = abspath(joinpath(str(main.root), 'ext'))
108411982Sgabeblack@google.comext_build_dirs = []
108511982Sgabeblack@google.comfor root, dirs, files in os.walk(ext_dir):
108611982Sgabeblack@google.com    if 'SConscript' in files:
108711982Sgabeblack@google.com        build_dir = os.path.relpath(root, ext_dir)
108811982Sgabeblack@google.com        ext_build_dirs.append(build_dir)
108911982Sgabeblack@google.com        main.SConscript(joinpath(root, 'SConscript'),
109011982Sgabeblack@google.com                        variant_dir=joinpath(build_root, build_dir))
109113706Sgabeblack@google.com
109213706Sgabeblack@google.commain.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
109313706Sgabeblack@google.com
109413706Sgabeblack@google.com###################################################
109513706Sgabeblack@google.com#
109613706Sgabeblack@google.com# This builder and wrapper method are used to set up a directory with
109713706Sgabeblack@google.com# switching headers. Those are headers which are in a generic location and
109813706Sgabeblack@google.com# that include more specific headers from a directory chosen at build time
109913706Sgabeblack@google.com# based on the current build settings.
110013706Sgabeblack@google.com#
110113706Sgabeblack@google.com###################################################
110213706Sgabeblack@google.com
110313706Sgabeblack@google.comdef build_switching_header(target, source, env):
110413706Sgabeblack@google.com    path = str(target[0])
110513706Sgabeblack@google.com    subdir = str(source[0])
110613706Sgabeblack@google.com    dp, fp = os.path.split(path)
110713706Sgabeblack@google.com    dp = os.path.relpath(os.path.realpath(dp),
110813706Sgabeblack@google.com                         os.path.realpath(env['BUILDDIR']))
110913713SAndrea.Mondelli@ucf.edu    with open(path, 'w') as hdr:
111013713SAndrea.Mondelli@ucf.edu        print >>hdr, '#include "%s/%s/%s"' % (dp, subdir, fp)
111113713SAndrea.Mondelli@ucf.edu
111213706Sgabeblack@google.comswitching_header_action = MakeAction(build_switching_header,
111313706Sgabeblack@google.com                                     Transform('GENERATE'))
111411978Sgabeblack@google.com
111511978Sgabeblack@google.comswitching_header_builder = Builder(action=switching_header_action,
111612034Sgabeblack@google.com                                   source_factory=Value,
111711978Sgabeblack@google.com                                   single_source=True)
111811978Sgabeblack@google.com
111911978Sgabeblack@google.commain.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
112012034Sgabeblack@google.com
112111978Sgabeblack@google.comdef switching_headers(self, headers, source):
112211978Sgabeblack@google.com    for header in headers:
112310915Sandreas.sandberg@arm.com        self.SwitchingHeader(header, source)
112413577Sciro.santilli@arm.com
112513577Sciro.santilli@arm.commain.AddMethod(switching_headers, 'SwitchingHeaders')
112613577Sciro.santilli@arm.com
112711986Sandreas.sandberg@arm.com###################################################
112811986Sandreas.sandberg@arm.com#
11291869SN/A# Define build environments for selected configurations.
11301869SN/A#
113112015Sgabeblack@google.com###################################################
113212015Sgabeblack@google.com
113312015Sgabeblack@google.comfor variant_path in variant_paths:
113412015Sgabeblack@google.com    if not GetOption('silent'):
11353546Sgblack@eecs.umich.edu        print "Building in", variant_path
11363546Sgblack@eecs.umich.edu
11373546Sgblack@eecs.umich.edu    # Make a copy of the build-root environment to use for this config.
113812015Sgabeblack@google.com    env = main.Clone()
113912015Sgabeblack@google.com    env['BUILDDIR'] = variant_path
114012015Sgabeblack@google.com
114112015Sgabeblack@google.com    # variant_dir is the tail component of build path, and is used to
114212015Sgabeblack@google.com    # determine the build parameters (e.g., 'ALPHA_SE')
114312015Sgabeblack@google.com    (build_root, variant_dir) = splitpath(variant_path)
114412015Sgabeblack@google.com
114512563Sgabeblack@google.com    # Set env variables according to the build directory config.
11463546Sgblack@eecs.umich.edu    sticky_vars.files = []
114712015Sgabeblack@google.com    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
114812015Sgabeblack@google.com    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
114910196SCurtis.Dunham@arm.com    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
115012015Sgabeblack@google.com    current_vars_file = joinpath(build_root, 'variables', variant_dir)
115112015Sgabeblack@google.com    if isfile(current_vars_file):
115212015Sgabeblack@google.com        sticky_vars.files.append(current_vars_file)
115312015Sgabeblack@google.com        if not GetOption('silent'):
115412015Sgabeblack@google.com            print "Using saved variables file %s" % current_vars_file
115512015Sgabeblack@google.com    elif variant_dir in ext_build_dirs:
115612015Sgabeblack@google.com        # Things in ext are built without a variant directory.
115712015Sgabeblack@google.com        continue
115812015Sgabeblack@google.com    else:
115912015Sgabeblack@google.com        # Build dir-specific variables file doesn't exist.
116012015Sgabeblack@google.com
11613546Sgblack@eecs.umich.edu        # Make sure the directory is there so we can create it later
11623546Sgblack@eecs.umich.edu        opt_dir = dirname(current_vars_file)
11633546Sgblack@eecs.umich.edu        if not isdir(opt_dir):
1164955SN/A            mkdir(opt_dir)
1165955SN/A
1166955SN/A        # Get default build variables from source tree.  Variables are
1167955SN/A        # normally determined by name of $VARIANT_DIR, but can be
11685863Snate@binkert.org        # overridden by '--default=' arg on command line.
116910135SCurtis.Dunham@arm.com        default = GetOption('default')
117012563Sgabeblack@google.com        opts_dir = joinpath(main.root.abspath, 'build_opts')
11715343Sstever@gmail.com        if default:
11725343Sstever@gmail.com            default_vars_files = [joinpath(build_root, 'variables', default),
11736121Snate@binkert.org                                  joinpath(opts_dir, default)]
11745863Snate@binkert.org        else:
11754773Snate@binkert.org            default_vars_files = [joinpath(opts_dir, variant_dir)]
11765863Snate@binkert.org        existing_files = filter(isfile, default_vars_files)
11772632Sstever@eecs.umich.edu        if existing_files:
11785863Snate@binkert.org            default_vars_file = existing_files[0]
11792023SN/A            sticky_vars.files.append(default_vars_file)
11805863Snate@binkert.org            print "Variables file %s not found,\n  using defaults in %s" \
11815863Snate@binkert.org                  % (current_vars_file, default_vars_file)
11825863Snate@binkert.org        else:
11835863Snate@binkert.org            print "Error: cannot find variables file %s or " \
11845863Snate@binkert.org                  "default file(s) %s" \
11855863Snate@binkert.org                  % (current_vars_file, ' or '.join(default_vars_files))
11865863Snate@binkert.org            Exit(1)
11875863Snate@binkert.org
118810135SCurtis.Dunham@arm.com    # Apply current variable settings to env
118912563Sgabeblack@google.com    sticky_vars.Update(env)
119012034Sgabeblack@google.com
119112034Sgabeblack@google.com    help_texts["local_vars"] += \
119212034Sgabeblack@google.com        "Build variables for %s:\n" % variant_dir \
11932632Sstever@eecs.umich.edu                 + sticky_vars.GenerateHelpText(env)
11945863Snate@binkert.org
11952023SN/A    # Process variable settings.
11962632Sstever@eecs.umich.edu
11975863Snate@binkert.org    if not have_fenv and env['USE_FENV']:
11985342Sstever@gmail.com        print "Warning: <fenv.h> not available; " \
11995863Snate@binkert.org              "forcing USE_FENV to False in", variant_dir + "."
12002632Sstever@eecs.umich.edu        env['USE_FENV'] = False
12015863Snate@binkert.org
12025863Snate@binkert.org    if not env['USE_FENV']:
12038267Ssteve.reinhardt@amd.com        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
12048120Sgblack@eecs.umich.edu        print "         FP results may deviate slightly from other platforms."
12058267Ssteve.reinhardt@amd.com
12068267Ssteve.reinhardt@amd.com    if not have_png and env['USE_PNG']:
12078267Ssteve.reinhardt@amd.com        print "Warning: <png.h> not available; " \
12088267Ssteve.reinhardt@amd.com              "forcing USE_PNG to False in", variant_dir + "."
12098267Ssteve.reinhardt@amd.com        env['USE_PNG'] = False
12108267Ssteve.reinhardt@amd.com
12118267Ssteve.reinhardt@amd.com    if env['USE_PNG']:
12128267Ssteve.reinhardt@amd.com        env.Append(LIBS=['png'])
12138267Ssteve.reinhardt@amd.com
12145863Snate@binkert.org    if env['EFENCE']:
121512563Sgabeblack@google.com        env.Append(LIBS=['efence'])
121612563Sgabeblack@google.com
12172632Sstever@eecs.umich.edu    if env['USE_KVM']:
121812563Sgabeblack@google.com        if not have_kvm:
121912563Sgabeblack@google.com            print "Warning: Can not enable KVM, host seems to lack KVM support"
122012563Sgabeblack@google.com            env['USE_KVM'] = False
12212632Sstever@eecs.umich.edu        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
12221888SN/A            print "Info: KVM support disabled due to unsupported host and " \
12235863Snate@binkert.org                "target ISA combination"
12245863Snate@binkert.org            env['USE_KVM'] = False
12251858SN/A
12268120Sgblack@eecs.umich.edu    if env['USE_TUNTAP']:
12278120Sgblack@eecs.umich.edu        if not have_tuntap:
12287756SAli.Saidi@ARM.com            print "Warning: Can't connect EtherTap with a tap device."
12292598SN/A            env['USE_TUNTAP'] = False
12305863Snate@binkert.org
12311858SN/A    if env['BUILD_GPU']:
12321858SN/A        env.Append(CPPDEFINES=['BUILD_GPU'])
123312563Sgabeblack@google.com
123412563Sgabeblack@google.com    # Warn about missing optional functionality
12351858SN/A    if env['USE_KVM']:
12361858SN/A        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
12371858SN/A            print "Warning: perf_event headers lack support for the " \
123812563Sgabeblack@google.com                "exclude_host attribute. KVM instruction counts will " \
123912563Sgabeblack@google.com                "be inaccurate."
124012563Sgabeblack@google.com
12411858SN/A    # Save sticky variable settings back to current variables file
124212230Sgiacomo.travaglini@arm.com    sticky_vars.Save(current_vars_file, env)
124312563Sgabeblack@google.com
124412563Sgabeblack@google.com    if env['USE_SSE2']:
124512230Sgiacomo.travaglini@arm.com        env.Append(CCFLAGS=['-msse2'])
124612230Sgiacomo.travaglini@arm.com
124712230Sgiacomo.travaglini@arm.com    # The src/SConscript file sets up the build rules in 'env' according
124812230Sgiacomo.travaglini@arm.com    # to the configured variables.  It returns a list of environments,
124912230Sgiacomo.travaglini@arm.com    # one for each variant build (debug, opt, etc.)
12501858SN/A    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
12511858SN/A
12521858SN/A# base help text
12539651SAndreas.Sandberg@ARM.comHelp('''
12549651SAndreas.Sandberg@ARM.comUsage: scons [scons options] [build variables] [target(s)]
125512563Sgabeblack@google.com
125612563Sgabeblack@google.comExtra scons options:
12579651SAndreas.Sandberg@ARM.com%(options)s
12589651SAndreas.Sandberg@ARM.com
125912563Sgabeblack@google.comGlobal build variables:
126012563Sgabeblack@google.com%(global_vars)s
12619651SAndreas.Sandberg@ARM.com
12629651SAndreas.Sandberg@ARM.com%(local_vars)s
126312056Sgabeblack@google.com''' % help_texts)
126412056Sgabeblack@google.com