SConstruct revision 13715
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.comfrom __future__ import print_function
8212563Sgabeblack@google.com
836654Snate@binkert.org# Global Python includes
8410196SCurtis.Dunham@arm.comimport itertools
85955SN/Aimport os
865396Ssaidi@eecs.umich.eduimport re
8711401Sandreas.sandberg@arm.comimport shutil
885863Snate@binkert.orgimport subprocess
895863Snate@binkert.orgimport sys
904202Sbinkertn@umich.edu
915863Snate@binkert.orgfrom os import mkdir, environ
925863Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
935863Snate@binkert.orgfrom os.path import exists,  isdir, isfile
945863Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
9513541Sandrea.mondelli@ucf.edufrom re import match
96955SN/A
976654Snate@binkert.org# SCons includes
985273Sstever@gmail.comimport SCons
995871Snate@binkert.orgimport SCons.Node
1005273Sstever@gmail.com
1016654Snate@binkert.orgfrom m5.util import compareVersions, readCommand
1025396Ssaidi@eecs.umich.edu
1038120Sgblack@eecs.umich.eduhelp_texts = {
1048120Sgblack@eecs.umich.edu    "options" : "",
1058120Sgblack@eecs.umich.edu    "global_vars" : "",
1068120Sgblack@eecs.umich.edu    "local_vars" : ""
1078120Sgblack@eecs.umich.edu}
1088120Sgblack@eecs.umich.edu
1098120Sgblack@eecs.umich.eduExport("help_texts")
1108120Sgblack@eecs.umich.edu
1118879Ssteve.reinhardt@amd.com
1128879Ssteve.reinhardt@amd.com# There's a bug in scons in that (1) by default, the help texts from
1138879Ssteve.reinhardt@amd.com# AddOption() are supposed to be displayed when you type 'scons -h'
1148879Ssteve.reinhardt@amd.com# and (2) you can override the help displayed by 'scons -h' using the
1158879Ssteve.reinhardt@amd.com# Help() function, but these two features are incompatible: once
1168879Ssteve.reinhardt@amd.com# you've overridden the help text using Help(), there's no way to get
1178879Ssteve.reinhardt@amd.com# at the help texts from AddOptions.  See:
1188879Ssteve.reinhardt@amd.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1198879Ssteve.reinhardt@amd.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1208879Ssteve.reinhardt@amd.com# This hack lets us extract the help text from AddOptions and
1218879Ssteve.reinhardt@amd.com# re-inject it via Help().  Ideally someday this bug will be fixed and
1228879Ssteve.reinhardt@amd.com# we can just use AddOption directly.
1238879Ssteve.reinhardt@amd.comdef AddLocalOption(*args, **kwargs):
1248120Sgblack@eecs.umich.edu    col_width = 30
1258120Sgblack@eecs.umich.edu
1268120Sgblack@eecs.umich.edu    help = "  " + ", ".join(args)
1278120Sgblack@eecs.umich.edu    if "help" in kwargs:
1288120Sgblack@eecs.umich.edu        length = len(help)
1298120Sgblack@eecs.umich.edu        if length >= col_width:
1308120Sgblack@eecs.umich.edu            help += "\n" + " " * col_width
1318120Sgblack@eecs.umich.edu        else:
1328120Sgblack@eecs.umich.edu            help += " " * (col_width - length)
1338120Sgblack@eecs.umich.edu        help += kwargs["help"]
1348120Sgblack@eecs.umich.edu    help_texts["options"] += help + "\n"
1358120Sgblack@eecs.umich.edu
1368120Sgblack@eecs.umich.edu    AddOption(*args, **kwargs)
1378120Sgblack@eecs.umich.edu
1388879Ssteve.reinhardt@amd.comAddLocalOption('--colors', dest='use_colors', action='store_true',
1398879Ssteve.reinhardt@amd.com               help="Add color to abbreviated scons output")
1408879Ssteve.reinhardt@amd.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1418879Ssteve.reinhardt@amd.com               help="Don't add color to abbreviated scons output")
14210458Sandreas.hansson@arm.comAddLocalOption('--with-cxx-config', dest='with_cxx_config',
14310458Sandreas.hansson@arm.com               action='store_true',
14410458Sandreas.hansson@arm.com               help="Build with support for C++-based configuration")
1458879Ssteve.reinhardt@amd.comAddLocalOption('--default', dest='default', type='string', action='store',
1468879Ssteve.reinhardt@amd.com               help='Override which build_opts file to use for defaults')
1478879Ssteve.reinhardt@amd.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1488879Ssteve.reinhardt@amd.com               help='Disable style checking hooks')
14913421Sciro.santilli@arm.comAddLocalOption('--gold-linker', dest='gold_linker', action='store_true',
15013421Sciro.santilli@arm.com               help='Use the gold linker')
1519227Sandreas.hansson@arm.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1529227Sandreas.hansson@arm.com               help='Disable Link-Time Optimization for fast')
15312063Sgabeblack@google.comAddLocalOption('--force-lto', dest='force_lto', action='store_true',
15412063Sgabeblack@google.com               help='Use Link-Time Optimization instead of partial linking' +
15512063Sgabeblack@google.com                    ' when the compiler doesn\'t support using them together.')
1568879Ssteve.reinhardt@amd.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1578879Ssteve.reinhardt@amd.com               help='Update test reference outputs')
1588879Ssteve.reinhardt@amd.comAddLocalOption('--verbose', dest='verbose', action='store_true',
1598879Ssteve.reinhardt@amd.com               help='Print full tool command lines')
16010453SAndrew.Bardsley@arm.comAddLocalOption('--without-python', dest='without_python',
16110453SAndrew.Bardsley@arm.com               action='store_true',
16210453SAndrew.Bardsley@arm.com               help='Build without Python configuration support')
16310456SCurtis.Dunham@arm.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
16410456SCurtis.Dunham@arm.com               action='store_true',
16510456SCurtis.Dunham@arm.com               help='Disable linking against tcmalloc')
16610457Sandreas.hansson@arm.comAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
16710457Sandreas.hansson@arm.com               help='Build with Undefined Behavior Sanitizer if available')
16811342Sandreas.hansson@arm.comAddLocalOption('--with-asan', dest='with_asan', action='store_true',
16911342Sandreas.hansson@arm.com               help='Build with Address Sanitizer if available')
1708120Sgblack@eecs.umich.edu
17112063Sgabeblack@google.comif GetOption('no_lto') and GetOption('force_lto'):
17212563Sgabeblack@google.com    print('--no-lto and --force-lto are mutually exclusive')
17312063Sgabeblack@google.com    Exit(1)
17412063Sgabeblack@google.com
1755871Snate@binkert.org########################################################################
1765871Snate@binkert.org#
1776121Snate@binkert.org# Set up the main build environment.
1785871Snate@binkert.org#
1795871Snate@binkert.org########################################################################
1809926Sstan.czerniawski@arm.com
18112243Sgabeblack@google.commain = Environment()
1821533SN/A
18312246Sgabeblack@google.comfrom gem5_scons import Transform
18412246Sgabeblack@google.comfrom gem5_scons.util import get_termcap
18512246Sgabeblack@google.comtermcap = get_termcap()
18612246Sgabeblack@google.com
1879239Sandreas.hansson@arm.commain_dict_keys = main.Dictionary().keys()
1889239Sandreas.hansson@arm.com
1899239Sandreas.hansson@arm.com# Check that we have a C/C++ compiler
1909239Sandreas.hansson@arm.comif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
19112563Sgabeblack@google.com    print("No C++ compiler installed (package g++ on Ubuntu and RedHat)")
1929239Sandreas.hansson@arm.com    Exit(1)
1939239Sandreas.hansson@arm.com
194955SN/A###################################################
195955SN/A#
1962632Sstever@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
1972632Sstever@eecs.umich.edu# the target(s).
198955SN/A#
199955SN/A###################################################
200955SN/A
201955SN/A# Find default configuration & binary.
2028878Ssteve.reinhardt@amd.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
203955SN/A
2042632Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
2052632Sstever@eecs.umich.edudef rfind(l, elt, offs = -1):
2062632Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
2072632Sstever@eecs.umich.edu        if l[i] == elt:
2082632Sstever@eecs.umich.edu            return i
2092632Sstever@eecs.umich.edu    raise ValueError, "element not found"
2102632Sstever@eecs.umich.edu
2118268Ssteve.reinhardt@amd.com# Take a list of paths (or SCons Nodes) and return a list with all
2128268Ssteve.reinhardt@amd.com# paths made absolute and ~-expanded.  Paths will be interpreted
2138268Ssteve.reinhardt@amd.com# relative to the launch directory unless a different root is provided
2148268Ssteve.reinhardt@amd.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
2158268Ssteve.reinhardt@amd.com    return [abspath(joinpath(root, expanduser(str(p))))
2168268Ssteve.reinhardt@amd.com            for p in path_list]
2178268Ssteve.reinhardt@amd.com
2182632Sstever@eecs.umich.edudef find_first_prog(prog_names):
2192632Sstever@eecs.umich.edu    """Find the absolute path to the first existing binary in prog_names"""
2202632Sstever@eecs.umich.edu
2212632Sstever@eecs.umich.edu    if not isinstance(prog_names, (list, tuple)):
2228268Ssteve.reinhardt@amd.com        prog_names = [ prog_names ]
2232632Sstever@eecs.umich.edu
2248268Ssteve.reinhardt@amd.com    for p in prog_names:
2258268Ssteve.reinhardt@amd.com        p = main.WhereIs(p)
2268268Ssteve.reinhardt@amd.com        if p is not None:
2278268Ssteve.reinhardt@amd.com            return p
2283718Sstever@eecs.umich.edu
2292634Sstever@eecs.umich.edu    return None
2302634Sstever@eecs.umich.edu
2315863Snate@binkert.org# Each target must have 'build' in the interior of the path; the
2322638Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
2338268Ssteve.reinhardt@amd.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2342632Sstever@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
2352632Sstever@eecs.umich.edu# follow 'build' in the build path.
2362632Sstever@eecs.umich.edu
2372632Sstever@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
23812563Sgabeblack@google.com# in place rather than reassign the symbol to a new list, which
2391858SN/A# doesn't work (obviously!).
2403716Sstever@eecs.umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2412638Sstever@eecs.umich.edu
2422638Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
2432638Sstever@eecs.umich.edu# collected targets reference.
2442638Sstever@eecs.umich.eduvariant_paths = []
24512563Sgabeblack@google.combuild_root = None
24612563Sgabeblack@google.comfor t in BUILD_TARGETS:
2472638Sstever@eecs.umich.edu    path_dirs = t.split('/')
2485863Snate@binkert.org    try:
2495863Snate@binkert.org        build_top = rfind(path_dirs, 'build', -2)
2505863Snate@binkert.org    except:
251955SN/A        print("Error: no non-leaf 'build' dir found on target path", t)
2525341Sstever@gmail.com        Exit(1)
2535341Sstever@gmail.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2545863Snate@binkert.org    if not build_root:
2557756SAli.Saidi@ARM.com        build_root = this_build_root
2565341Sstever@gmail.com    else:
2576121Snate@binkert.org        if this_build_root != build_root:
2584494Ssaidi@eecs.umich.edu            print("Error: build targets not under same build root\n"
2596121Snate@binkert.org                  "  %s\n  %s" % (build_root, this_build_root))
2601105SN/A            Exit(1)
2612667Sstever@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
2622667Sstever@eecs.umich.edu    if variant_path not in variant_paths:
2632667Sstever@eecs.umich.edu        variant_paths.append(variant_path)
2642667Sstever@eecs.umich.edu
2656121Snate@binkert.org# Make sure build_root exists (might not if this is the first build there)
2662667Sstever@eecs.umich.eduif not isdir(build_root):
2675341Sstever@gmail.com    mkdir(build_root)
2685863Snate@binkert.orgmain['BUILDROOT'] = build_root
2695341Sstever@gmail.com
2705341Sstever@gmail.comExport('main')
2715341Sstever@gmail.com
2728120Sgblack@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
2735341Sstever@gmail.com
2748120Sgblack@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
2755341Sstever@gmail.com# when you use emacs to edit a file in the target dir, as emacs moves
2768120Sgblack@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
2776121Snate@binkert.org# (soft) links work better.
2786121Snate@binkert.orgmain.SetOption('duplicate', 'soft-copy')
2799396Sandreas.hansson@arm.com
2805397Ssaidi@eecs.umich.edu#
2815397Ssaidi@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
2827727SAli.Saidi@ARM.com# tree (not specific to a particular build like ALPHA_SE)
2838268Ssteve.reinhardt@amd.com#
2846168Snate@binkert.org
2855341Sstever@gmail.comglobal_vars_file = joinpath(build_root, 'variables.global')
2868120Sgblack@eecs.umich.edu
2878120Sgblack@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2888120Sgblack@eecs.umich.edu
2896814Sgblack@eecs.umich.eduglobal_vars.AddVariables(
2905863Snate@binkert.org    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2918120Sgblack@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2925341Sstever@gmail.com    ('PYTHON_CONFIG', 'Python config binary to use',
2935863Snate@binkert.org     [ 'python2.7-config', 'python-config' ]),
2948268Ssteve.reinhardt@amd.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2956121Snate@binkert.org    ('BATCH', 'Use batch pool for build and tests', False),
2966121Snate@binkert.org    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2978268Ssteve.reinhardt@amd.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2985742Snate@binkert.org    ('EXTRAS', 'Add extra directories to the compilation', '')
2995742Snate@binkert.org    )
3005341Sstever@gmail.com
3015742Snate@binkert.org# Update main environment with values from ARGUMENTS & global_vars_file
3025742Snate@binkert.orgglobal_vars.Update(main)
3035341Sstever@gmail.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3046017Snate@binkert.org
3056121Snate@binkert.org# Save sticky variable settings back to current variables file
3066017Snate@binkert.orgglobal_vars.Save(global_vars_file, main)
30712158Sandreas.sandberg@arm.com
30812158Sandreas.sandberg@arm.com# Parse EXTRAS variable to build list of all directories where we're
30912158Sandreas.sandberg@arm.com# look for sources etc.  This list is exported as extras_dir_list.
3108120Sgblack@eecs.umich.edubase_dir = main.srcdir.abspath
3117756SAli.Saidi@ARM.comif main['EXTRAS']:
3127756SAli.Saidi@ARM.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
3137756SAli.Saidi@ARM.comelse:
3147756SAli.Saidi@ARM.com    extras_dir_list = []
3157816Ssteve.reinhardt@amd.com
3167816Ssteve.reinhardt@amd.comExport('base_dir')
3177816Ssteve.reinhardt@amd.comExport('extras_dir_list')
3187816Ssteve.reinhardt@amd.com
3197816Ssteve.reinhardt@amd.com# the ext directory should be on the #includes path
32011979Sgabeblack@google.commain.Append(CPPPATH=[Dir('ext')])
3217816Ssteve.reinhardt@amd.com
3227816Ssteve.reinhardt@amd.com# Add shared top-level headers
3237816Ssteve.reinhardt@amd.commain.Prepend(CPPPATH=Dir('include'))
3247816Ssteve.reinhardt@amd.com
3257756SAli.Saidi@ARM.comif GetOption('verbose'):
3267756SAli.Saidi@ARM.com    def MakeAction(action, string, *args, **kwargs):
3279227Sandreas.hansson@arm.com        return Action(action, *args, **kwargs)
3289227Sandreas.hansson@arm.comelse:
3299227Sandreas.hansson@arm.com    MakeAction = Action
3309227Sandreas.hansson@arm.com    main['CCCOMSTR']        = Transform("CC")
3319590Sandreas@sandberg.pp.se    main['CXXCOMSTR']       = Transform("CXX")
3329590Sandreas@sandberg.pp.se    main['ASCOMSTR']        = Transform("AS")
3339590Sandreas@sandberg.pp.se    main['ARCOMSTR']        = Transform("AR", 0)
3349590Sandreas@sandberg.pp.se    main['LINKCOMSTR']      = Transform("LINK", 0)
3359590Sandreas@sandberg.pp.se    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
3369590Sandreas@sandberg.pp.se    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3376654Snate@binkert.org    main['M4COMSTR']        = Transform("M4")
3386654Snate@binkert.org    main['SHCCCOMSTR']      = Transform("SHCC")
3395871Snate@binkert.org    main['SHCXXCOMSTR']     = Transform("SHCXX")
3406121Snate@binkert.orgExport('MakeAction')
3418946Sandreas.hansson@arm.com
3429419Sandreas.hansson@arm.com# Initialize the Link-Time Optimization (LTO) flags
34312563Sgabeblack@google.commain['LTO_CCFLAGS'] = []
3443918Ssaidi@eecs.umich.edumain['LTO_LDFLAGS'] = []
3453918Ssaidi@eecs.umich.edu
3461858SN/A# According to the readme, tcmalloc works best if the compiler doesn't
3479556Sandreas.hansson@arm.com# assume that we're using the builtin malloc and friends. These flags
3489556Sandreas.hansson@arm.com# are compiler-specific, so we need to set them after we detect which
3499556Sandreas.hansson@arm.com# compiler we're using.
3509556Sandreas.hansson@arm.commain['TCMALLOC_CCFLAGS'] = []
35111294Sandreas.hansson@arm.com
35211294Sandreas.hansson@arm.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
35311294Sandreas.hansson@arm.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
35411294Sandreas.hansson@arm.com
35510878Sandreas.hansson@arm.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
35610878Sandreas.hansson@arm.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
35711811Sbaz21@cam.ac.ukif main['GCC'] + main['CLANG'] > 1:
35811811Sbaz21@cam.ac.uk    print('Error: How can we have two at the same time?')
35911811Sbaz21@cam.ac.uk    Exit(1)
36011982Sgabeblack@google.com
36111982Sgabeblack@google.com# Set up default C++ compiler flags
36211982Sgabeblack@google.comif main['GCC'] or main['CLANG']:
36313421Sciro.santilli@arm.com    # As gcc and clang share many flags, do the common parts here
36413421Sciro.santilli@arm.com    main.Append(CCFLAGS=['-pipe'])
36511982Sgabeblack@google.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
36611992Sgabeblack@google.com    # Enable -Wall and -Wextra and then disable the few warnings that
36711982Sgabeblack@google.com    # we consistently violate
36811982Sgabeblack@google.com    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
36912305Sgabeblack@google.com                         '-Wno-sign-compare', '-Wno-unused-parameter'])
37012305Sgabeblack@google.com    # We always compile using C++11
37112305Sgabeblack@google.com    main.Append(CXXFLAGS=['-std=c++11'])
37212305Sgabeblack@google.com    if sys.platform.startswith('freebsd'):
37312305Sgabeblack@google.com        main.Append(CCFLAGS=['-I/usr/local/include'])
37412305Sgabeblack@google.com        main.Append(CXXFLAGS=['-I/usr/local/include'])
37512305Sgabeblack@google.com
3769556Sandreas.hansson@arm.com    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
37712563Sgabeblack@google.com    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
37812563Sgabeblack@google.com    if GetOption('gold_linker'):
37912563Sgabeblack@google.com        main.Append(LINKFLAGS='-fuse-ld=gold')
38012563Sgabeblack@google.com    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3819556Sandreas.hansson@arm.com    shared_partial_flags = ['-r', '-nostdlib']
38212563Sgabeblack@google.com    main.Append(PSHLINKFLAGS=shared_partial_flags)
38312563Sgabeblack@google.com    main.Append(PLINKFLAGS=shared_partial_flags)
3849556Sandreas.hansson@arm.com
38512563Sgabeblack@google.com    # Treat warnings as errors but white list some warnings that we
38612563Sgabeblack@google.com    # want to allow (e.g., deprecation warnings).
38712563Sgabeblack@google.com    main.Append(CCFLAGS=['-Werror',
38812563Sgabeblack@google.com                         '-Wno-error=deprecated-declarations',
38912563Sgabeblack@google.com                         '-Wno-error=deprecated',
39012563Sgabeblack@google.com                        ])
39112563Sgabeblack@google.comelse:
39212563Sgabeblack@google.com    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
3939556Sandreas.hansson@arm.com    print("Don't know what compiler options to use for your compiler.")
3949556Sandreas.hansson@arm.com    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
3956121Snate@binkert.org    print(termcap.Yellow + '       version:' + termcap.Normal, end = ' ')
39611500Sandreas.hansson@arm.com    if not CXX_version:
39710238Sandreas.hansson@arm.com        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
39810878Sandreas.hansson@arm.com              termcap.Normal)
3999420Sandreas.hansson@arm.com    else:
40011500Sandreas.hansson@arm.com        print(CXX_version.replace('\n', '<nl>'))
40112563Sgabeblack@google.com    print("       If you're trying to use a compiler other than GCC")
40212563Sgabeblack@google.com    print("       or clang, there appears to be something wrong with your")
4039420Sandreas.hansson@arm.com    print("       environment.")
4049420Sandreas.hansson@arm.com    print("       ")
4059420Sandreas.hansson@arm.com    print("       If you are trying to use a compiler other than those listed")
4069420Sandreas.hansson@arm.com    print("       above you will need to ease fix SConstruct and ")
40712063Sgabeblack@google.com    print("       src/SConscript to support that compiler.")
40812063Sgabeblack@google.com    Exit(1)
40912063Sgabeblack@google.com
41012063Sgabeblack@google.comif main['GCC']:
41112063Sgabeblack@google.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
41212063Sgabeblack@google.com    # level of c++11 support. See
41312063Sgabeblack@google.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
41412063Sgabeblack@google.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
41512063Sgabeblack@google.com    if compareVersions(gcc_version, "4.8") < 0:
41612063Sgabeblack@google.com        print('Error: gcc version 4.8 or newer required.')
41712063Sgabeblack@google.com        print('       Installed version: ', gcc_version)
41812063Sgabeblack@google.com        Exit(1)
41912063Sgabeblack@google.com
42012063Sgabeblack@google.com    main['GCC_VERSION'] = gcc_version
42112063Sgabeblack@google.com
42212063Sgabeblack@google.com    if compareVersions(gcc_version, '4.9') >= 0:
42312063Sgabeblack@google.com        # Incremental linking with LTO is currently broken in gcc versions
42412063Sgabeblack@google.com        # 4.9 and above. A version where everything works completely hasn't
42512063Sgabeblack@google.com        # yet been identified.
42612063Sgabeblack@google.com        #
42712063Sgabeblack@google.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
42812063Sgabeblack@google.com        main['BROKEN_INCREMENTAL_LTO'] = True
42910457Sandreas.hansson@arm.com    if compareVersions(gcc_version, '6.0') >= 0:
43010457Sandreas.hansson@arm.com        # gcc versions 6.0 and greater accept an -flinker-output flag which
43110457Sandreas.hansson@arm.com        # selects what type of output the linker should generate. This is
43210457Sandreas.hansson@arm.com        # necessary for incremental lto to work, but is also broken in
43310457Sandreas.hansson@arm.com        # current versions of gcc. It may not be necessary in future
43412563Sgabeblack@google.com        # versions. We add it here since it might be, and as a reminder that
43512563Sgabeblack@google.com        # it exists. It's excluded if lto is being forced.
43612563Sgabeblack@google.com        #
43710457Sandreas.hansson@arm.com        # https://gcc.gnu.org/gcc-6/changes.html
43812063Sgabeblack@google.com        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
43912063Sgabeblack@google.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
44012063Sgabeblack@google.com        if not GetOption('force_lto'):
44112563Sgabeblack@google.com            main.Append(PSHLINKFLAGS='-flinker-output=rel')
44212563Sgabeblack@google.com            main.Append(PLINKFLAGS='-flinker-output=rel')
44312563Sgabeblack@google.com
44412563Sgabeblack@google.com    # Make sure we warn if the user has requested to compile with the
44512563Sgabeblack@google.com    # Undefined Benahvior Sanitizer and this version of gcc does not
44612563Sgabeblack@google.com    # support it.
44712063Sgabeblack@google.com    if GetOption('with_ubsan') and \
44812063Sgabeblack@google.com            compareVersions(gcc_version, '4.9') < 0:
44910238Sandreas.hansson@arm.com        print(termcap.Yellow + termcap.Bold +
45010238Sandreas.hansson@arm.com            'Warning: UBSan is only supported using gcc 4.9 and later.' +
45110238Sandreas.hansson@arm.com            termcap.Normal)
45212063Sgabeblack@google.com
45310238Sandreas.hansson@arm.com    disable_lto = GetOption('no_lto')
45410238Sandreas.hansson@arm.com    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
45510416Sandreas.hansson@arm.com            not GetOption('force_lto'):
45610238Sandreas.hansson@arm.com        print(termcap.Yellow + termcap.Bold +
4579227Sandreas.hansson@arm.com            'Warning: Your compiler doesn\'t support incremental linking' +
45810238Sandreas.hansson@arm.com            ' and lto at the same time, so lto is being disabled. To force' +
45910416Sandreas.hansson@arm.com            ' lto on anyway, use the --force-lto option. That will disable' +
46010416Sandreas.hansson@arm.com            ' partial linking.' +
4619227Sandreas.hansson@arm.com            termcap.Normal)
4629590Sandreas@sandberg.pp.se        disable_lto = True
4639590Sandreas@sandberg.pp.se
4649590Sandreas@sandberg.pp.se    # Add the appropriate Link-Time Optimization (LTO) flags
46512304Sgabeblack@google.com    # unless LTO is explicitly turned off. Note that these flags
46612304Sgabeblack@google.com    # are only used by the fast target.
46712304Sgabeblack@google.com    if not disable_lto:
46812688Sgiacomo.travaglini@arm.com        # Pass the LTO flag when compiling to produce GIMPLE
46912688Sgiacomo.travaglini@arm.com        # output, we merely create the flags here and only append
47012688Sgiacomo.travaglini@arm.com        # them later
47113020Sshunhsingou@google.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
47212304Sgabeblack@google.com
47312688Sgiacomo.travaglini@arm.com        # Use the same amount of jobs for LTO as we are running
47412688Sgiacomo.travaglini@arm.com        # scons with
47513020Sshunhsingou@google.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
47612304Sgabeblack@google.com
47712304Sgabeblack@google.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
47812304Sgabeblack@google.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
47912304Sgabeblack@google.com
48012688Sgiacomo.travaglini@arm.com    # The address sanitizer is available for gcc >= 4.8
48112688Sgiacomo.travaglini@arm.com    if GetOption('with_asan'):
48212688Sgiacomo.travaglini@arm.com        if GetOption('with_ubsan') and \
48312304Sgabeblack@google.com                compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4848737Skoansin.tan@gmail.com            main.Append(CCFLAGS=['-fsanitize=address,undefined',
48510878Sandreas.hansson@arm.com                                 '-fno-omit-frame-pointer'],
48611500Sandreas.hansson@arm.com                        LINKFLAGS='-fsanitize=address,undefined')
4879420Sandreas.hansson@arm.com        else:
4888737Skoansin.tan@gmail.com            main.Append(CCFLAGS=['-fsanitize=address',
48910106SMitch.Hayenga@arm.com                                 '-fno-omit-frame-pointer'],
4908737Skoansin.tan@gmail.com                        LINKFLAGS='-fsanitize=address')
4918737Skoansin.tan@gmail.com    # Only gcc >= 4.9 supports UBSan, so check both the version
49210878Sandreas.hansson@arm.com    # and the command-line option before adding the compiler and
49312563Sgabeblack@google.com    # linker flags.
49412563Sgabeblack@google.com    elif GetOption('with_ubsan') and \
4958737Skoansin.tan@gmail.com            compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4968737Skoansin.tan@gmail.com        main.Append(CCFLAGS='-fsanitize=undefined')
49712563Sgabeblack@google.com        main.Append(LINKFLAGS='-fsanitize=undefined')
4988737Skoansin.tan@gmail.com
4998737Skoansin.tan@gmail.comelif main['CLANG']:
50011294Sandreas.hansson@arm.com    # Check for a supported version of clang, >= 3.1 is needed to
5019556Sandreas.hansson@arm.com    # support similar features as gcc 4.8. See
5029556Sandreas.hansson@arm.com    # http://clang.llvm.org/cxx_status.html for details
5039556Sandreas.hansson@arm.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
50411294Sandreas.hansson@arm.com    clang_version_match = clang_version_re.search(CXX_version)
50510278SAndreas.Sandberg@ARM.com    if (clang_version_match):
50610278SAndreas.Sandberg@ARM.com        clang_version = clang_version_match.groups()[0]
50710278SAndreas.Sandberg@ARM.com        if compareVersions(clang_version, "3.1") < 0:
50810278SAndreas.Sandberg@ARM.com            print('Error: clang version 3.1 or newer required.')
50910278SAndreas.Sandberg@ARM.com            print('       Installed version:', clang_version)
51010278SAndreas.Sandberg@ARM.com            Exit(1)
5119556Sandreas.hansson@arm.com    else:
5129590Sandreas@sandberg.pp.se        print('Error: Unable to determine clang version.')
5139590Sandreas@sandberg.pp.se        Exit(1)
5149420Sandreas.hansson@arm.com
5159846Sandreas.hansson@arm.com    # clang has a few additional warnings that we disable, extraneous
5169846Sandreas.hansson@arm.com    # parantheses are allowed due to Ruby's printing of the AST,
5179846Sandreas.hansson@arm.com    # finally self assignments are allowed as the generated CPU code
5189846Sandreas.hansson@arm.com    # is relying on this
5198946Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wno-parentheses',
52011811Sbaz21@cam.ac.uk                         '-Wno-self-assign',
52111811Sbaz21@cam.ac.uk                         # Some versions of libstdc++ (4.8?) seem to
52211811Sbaz21@cam.ac.uk                         # use struct hash and class hash
52311811Sbaz21@cam.ac.uk                         # interchangeably.
52412304Sgabeblack@google.com                         '-Wno-mismatched-tags',
52512304Sgabeblack@google.com                         ])
52612304Sgabeblack@google.com
52712304Sgabeblack@google.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
52813020Sshunhsingou@google.com
52913020Sshunhsingou@google.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
53012304Sgabeblack@google.com    # opposed to libstdc++, as the later is dated.
53112304Sgabeblack@google.com    if sys.platform == "darwin":
53213020Sshunhsingou@google.com        main.Append(CXXFLAGS=['-stdlib=libc++'])
53313020Sshunhsingou@google.com        main.Append(LIBS=['c++'])
53412304Sgabeblack@google.com
53512304Sgabeblack@google.com    # On FreeBSD we need libthr.
53613020Sshunhsingou@google.com    if sys.platform.startswith('freebsd'):
53713020Sshunhsingou@google.com        main.Append(LIBS=['thr'])
53812304Sgabeblack@google.com
53912304Sgabeblack@google.com    # We require clang >= 3.1, so there is no need to check any
5403918Ssaidi@eecs.umich.edu    # versions here.
54112563Sgabeblack@google.com    if GetOption('with_ubsan'):
54212563Sgabeblack@google.com        if GetOption('with_asan'):
54312563Sgabeblack@google.com            main.Append(CCFLAGS=['-fsanitize=address,undefined',
54412563Sgabeblack@google.com                                 '-fno-omit-frame-pointer'],
5459068SAli.Saidi@ARM.com                       LINKFLAGS='-fsanitize=address,undefined')
54612563Sgabeblack@google.com        else:
54712563Sgabeblack@google.com            main.Append(CCFLAGS='-fsanitize=undefined',
5489068SAli.Saidi@ARM.com                        LINKFLAGS='-fsanitize=undefined')
54912563Sgabeblack@google.com
55012563Sgabeblack@google.com    elif GetOption('with_asan'):
55112563Sgabeblack@google.com        main.Append(CCFLAGS=['-fsanitize=address',
55212563Sgabeblack@google.com                             '-fno-omit-frame-pointer'],
55312563Sgabeblack@google.com                   LINKFLAGS='-fsanitize=address')
55412563Sgabeblack@google.com
55512563Sgabeblack@google.comelse:
55612563Sgabeblack@google.com    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
5573918Ssaidi@eecs.umich.edu    print("Don't know what compiler options to use for your compiler.")
5583918Ssaidi@eecs.umich.edu    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
5596157Snate@binkert.org    print(termcap.Yellow + '       version:' + termcap.Normal, end=' ')
5606157Snate@binkert.org    if not CXX_version:
5616157Snate@binkert.org        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
5626157Snate@binkert.org              termcap.Normal)
5635397Ssaidi@eecs.umich.edu    else:
5645397Ssaidi@eecs.umich.edu        print(CXX_version.replace('\n', '<nl>'))
5656121Snate@binkert.org    print("       If you're trying to use a compiler other than GCC")
5666121Snate@binkert.org    print("       or clang, there appears to be something wrong with your")
5676121Snate@binkert.org    print("       environment.")
5686121Snate@binkert.org    print("       ")
5696121Snate@binkert.org    print("       If you are trying to use a compiler other than those listed")
5706121Snate@binkert.org    print("       above you will need to ease fix SConstruct and ")
5715397Ssaidi@eecs.umich.edu    print("       src/SConscript to support that compiler.")
5721851SN/A    Exit(1)
5731851SN/A
5747739Sgblack@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
575955SN/Amain['YACCFLAGS'] = '-d'
5769396Sandreas.hansson@arm.commain['YACCHXXFILESUFFIX'] = '.hh'
5779396Sandreas.hansson@arm.com
5789396Sandreas.hansson@arm.com# Do this after we save setting back, or else we'll tack on an
5799396Sandreas.hansson@arm.com# extra 'qdo' every time we run scons.
5809396Sandreas.hansson@arm.comif main['BATCH']:
5819396Sandreas.hansson@arm.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
58212563Sgabeblack@google.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
58312563Sgabeblack@google.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
58412563Sgabeblack@google.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
58512563Sgabeblack@google.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
5869396Sandreas.hansson@arm.com
5879396Sandreas.hansson@arm.comif sys.platform == 'cygwin':
5889396Sandreas.hansson@arm.com    # cygwin has some header file issues...
5899396Sandreas.hansson@arm.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
5909396Sandreas.hansson@arm.com
5919396Sandreas.hansson@arm.com# Check for the protobuf compiler
59212563Sgabeblack@google.comprotoc_version = readCommand([main['PROTOC'], '--version'],
59312563Sgabeblack@google.com                             exception='').split()
59412563Sgabeblack@google.com
59512563Sgabeblack@google.com# First two words should be "libprotoc x.y.z"
59612563Sgabeblack@google.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
5979477Sandreas.hansson@arm.com    print(termcap.Yellow + termcap.Bold +
5989477Sandreas.hansson@arm.com        'Warning: Protocol buffer compiler (protoc) not found.\n' +
5999477Sandreas.hansson@arm.com        '         Please install protobuf-compiler for tracing support.' +
6009477Sandreas.hansson@arm.com        termcap.Normal)
6019477Sandreas.hansson@arm.com    main['PROTOC'] = False
6029477Sandreas.hansson@arm.comelse:
6039477Sandreas.hansson@arm.com    # Based on the availability of the compress stream wrappers,
6049477Sandreas.hansson@arm.com    # require 2.1.0
6059477Sandreas.hansson@arm.com    min_protoc_version = '2.1.0'
6069477Sandreas.hansson@arm.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6079477Sandreas.hansson@arm.com        print(termcap.Yellow + termcap.Bold +
6089477Sandreas.hansson@arm.com            'Warning: protoc version', min_protoc_version,
6099477Sandreas.hansson@arm.com            'or newer required.\n' +
6109477Sandreas.hansson@arm.com            '         Installed version:', protoc_version[1],
61112563Sgabeblack@google.com            termcap.Normal)
61212563Sgabeblack@google.com        main['PROTOC'] = False
61312563Sgabeblack@google.com    else:
6149396Sandreas.hansson@arm.com        # Attempt to determine the appropriate include path and
6152667Sstever@eecs.umich.edu        # library path using pkg-config, that means we also need to
61610710Sandreas.hansson@arm.com        # check for pkg-config. Note that it is possible to use
61710710Sandreas.hansson@arm.com        # protobuf without the involvement of pkg-config. Later on we
61810710Sandreas.hansson@arm.com        # check go a library config check and at that point the test
61911811Sbaz21@cam.ac.uk        # will fail if libprotobuf cannot be found.
62011811Sbaz21@cam.ac.uk        if readCommand(['pkg-config', '--version'], exception=''):
62111811Sbaz21@cam.ac.uk            try:
62211811Sbaz21@cam.ac.uk                # Attempt to establish what linking flags to add for protobuf
62311811Sbaz21@cam.ac.uk                # using pkg-config
62411811Sbaz21@cam.ac.uk                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
62510710Sandreas.hansson@arm.com            except:
62610710Sandreas.hansson@arm.com                print(termcap.Yellow + termcap.Bold +
62710710Sandreas.hansson@arm.com                    'Warning: pkg-config could not get protobuf flags.' +
62810710Sandreas.hansson@arm.com                    termcap.Normal)
62910384SCurtis.Dunham@arm.com
6309986Sandreas@sandberg.pp.se
6319986Sandreas@sandberg.pp.se# Check for 'timeout' from GNU coreutils. If present, regressions will
6329986Sandreas@sandberg.pp.se# be run with a time limit. We require version 8.13 since we rely on
6339986Sandreas@sandberg.pp.se# support for the '--foreground' option.
6349986Sandreas@sandberg.pp.seif sys.platform.startswith('freebsd'):
6359986Sandreas@sandberg.pp.se    timeout_lines = readCommand(['gtimeout', '--version'],
6369986Sandreas@sandberg.pp.se                                exception='').splitlines()
6379986Sandreas@sandberg.pp.seelse:
6389986Sandreas@sandberg.pp.se    timeout_lines = readCommand(['timeout', '--version'],
6399986Sandreas@sandberg.pp.se                                exception='').splitlines()
6409986Sandreas@sandberg.pp.se# Get the first line and tokenize it
6419986Sandreas@sandberg.pp.setimeout_version = timeout_lines[0].split() if timeout_lines else []
6429986Sandreas@sandberg.pp.semain['TIMEOUT'] =  timeout_version and \
6439986Sandreas@sandberg.pp.se    compareVersions(timeout_version[-1], '8.13') >= 0
6449986Sandreas@sandberg.pp.se
6459986Sandreas@sandberg.pp.se# Add a custom Check function to test for structure members.
6469986Sandreas@sandberg.pp.sedef CheckMember(context, include, decl, member, include_quotes="<>"):
6479986Sandreas@sandberg.pp.se    context.Message("Checking for member %s in %s..." %
6489986Sandreas@sandberg.pp.se                    (member, decl))
6499986Sandreas@sandberg.pp.se    text = """
6502638Sstever@eecs.umich.edu#include %(header)s
6512638Sstever@eecs.umich.eduint main(){
6526121Snate@binkert.org  %(decl)s test;
6533716Sstever@eecs.umich.edu  (void)test.%(member)s;
6545522Snate@binkert.org  return 0;
6559986Sandreas@sandberg.pp.se};
6569986Sandreas@sandberg.pp.se""" % { "header" : include_quotes[0] + include + include_quotes[1],
6579986Sandreas@sandberg.pp.se        "decl" : decl,
6585522Snate@binkert.org        "member" : member,
6595227Ssaidi@eecs.umich.edu        }
6605227Ssaidi@eecs.umich.edu
6615227Ssaidi@eecs.umich.edu    ret = context.TryCompile(text, extension=".cc")
6625227Ssaidi@eecs.umich.edu    context.Result(ret)
6636654Snate@binkert.org    return ret
6646654Snate@binkert.org
6657769SAli.Saidi@ARM.com# Platform-specific configuration.  Note again that we assume that all
6667769SAli.Saidi@ARM.com# builds under a given build root run on the same host platform.
6677769SAli.Saidi@ARM.comconf = Configure(main,
6687769SAli.Saidi@ARM.com                 conf_dir = joinpath(build_root, '.scons_config'),
6695227Ssaidi@eecs.umich.edu                 log_file = joinpath(build_root, 'scons_config.log'),
6705227Ssaidi@eecs.umich.edu                 custom_tests = {
6715227Ssaidi@eecs.umich.edu        'CheckMember' : CheckMember,
6725204Sstever@gmail.com        })
6735204Sstever@gmail.com
6745204Sstever@gmail.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6755204Sstever@gmail.comtry:
6765204Sstever@gmail.com    import platform
6775204Sstever@gmail.com    uname = platform.uname()
6785204Sstever@gmail.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6795204Sstever@gmail.com        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6805204Sstever@gmail.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
6815204Sstever@gmail.com            main.Append(CFLAGS=['-arch', 'x86_64'])
6825204Sstever@gmail.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6835204Sstever@gmail.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
6845204Sstever@gmail.comexcept:
6855204Sstever@gmail.com    pass
6865204Sstever@gmail.com
6875204Sstever@gmail.com# Recent versions of scons substitute a "Null" object for Configure()
6885204Sstever@gmail.com# when configuration isn't necessary, e.g., if the "--help" option is
6896121Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
6905204Sstever@gmail.com# breaking all our configuration checks.  We replace it with our own
6917727SAli.Saidi@ARM.com# more optimistic null object that returns True instead.
6927727SAli.Saidi@ARM.comif not conf:
69312563Sgabeblack@google.com    def NullCheck(*args, **kwargs):
6947727SAli.Saidi@ARM.com        return True
6957727SAli.Saidi@ARM.com
69611988Sandreas.sandberg@arm.com    class NullConf:
69711988Sandreas.sandberg@arm.com        def __init__(self, env):
69810453SAndrew.Bardsley@arm.com            self.env = env
69910453SAndrew.Bardsley@arm.com        def Finish(self):
70010453SAndrew.Bardsley@arm.com            return self.env
70110453SAndrew.Bardsley@arm.com        def __getattr__(self, mname):
70210453SAndrew.Bardsley@arm.com            return NullCheck
70310453SAndrew.Bardsley@arm.com
70410453SAndrew.Bardsley@arm.com    conf = NullConf(main)
70510453SAndrew.Bardsley@arm.com
70610453SAndrew.Bardsley@arm.com# Cache build files in the supplied directory.
70710453SAndrew.Bardsley@arm.comif main['M5_BUILD_CACHE']:
70810160Sandreas.hansson@arm.com    print('Using build cache located at', main['M5_BUILD_CACHE'])
70910453SAndrew.Bardsley@arm.com    CacheDir(main['M5_BUILD_CACHE'])
71010453SAndrew.Bardsley@arm.com
71110453SAndrew.Bardsley@arm.commain['USE_PYTHON'] = not GetOption('without_python')
71210453SAndrew.Bardsley@arm.comif main['USE_PYTHON']:
71310453SAndrew.Bardsley@arm.com    # Find Python include and library directories for embedding the
71413541Sandrea.mondelli@ucf.edu    # interpreter. We rely on python-config to resolve the appropriate
71510453SAndrew.Bardsley@arm.com    # includes and linker flags. ParseConfig does not seem to understand
71610453SAndrew.Bardsley@arm.com    # the more exotic linker flags such as -Xlinker and -export-dynamic so
71713541Sandrea.mondelli@ucf.edu    # we add them explicitly below. If you want to link in an alternate
71813541Sandrea.mondelli@ucf.edu    # version of python, see above for instructions on how to invoke
7199812Sandreas.hansson@arm.com    # scons with the appropriate PATH set.
72010453SAndrew.Bardsley@arm.com
72110453SAndrew.Bardsley@arm.com    python_config = find_first_prog(main['PYTHON_CONFIG'])
72210453SAndrew.Bardsley@arm.com    if python_config is None:
72310453SAndrew.Bardsley@arm.com        print("Error: can't find a suitable python-config, tried %s" % \
72410453SAndrew.Bardsley@arm.com              main['PYTHON_CONFIG'])
72510453SAndrew.Bardsley@arm.com        Exit(1)
72610453SAndrew.Bardsley@arm.com
72710453SAndrew.Bardsley@arm.com    print("Info: Using Python config: %s" % (python_config, ))
72810453SAndrew.Bardsley@arm.com    py_includes = readCommand([python_config, '--includes'],
72910453SAndrew.Bardsley@arm.com                              exception='').split()
73010453SAndrew.Bardsley@arm.com    py_includes = filter(lambda s: match(r'.*\/include\/.*',s), py_includes)
73110453SAndrew.Bardsley@arm.com    # Strip the -I from the include folders before adding them to the
7327727SAli.Saidi@ARM.com    # CPPPATH
73310453SAndrew.Bardsley@arm.com    py_includes = map(lambda s: s[2:] if s.startswith('-I') else s, py_includes)
73410453SAndrew.Bardsley@arm.com    main.Append(CPPPATH=py_includes)
73512790Smatteo.fusi@bsc.es
73612790Smatteo.fusi@bsc.es    # Read the linker flags and split them into libraries and other link
73712790Smatteo.fusi@bsc.es    # flags. The libraries are added later through the call the CheckLib.
73812790Smatteo.fusi@bsc.es    py_ld_flags = readCommand([python_config, '--ldflags'],
73912790Smatteo.fusi@bsc.es        exception='').split()
74012790Smatteo.fusi@bsc.es    py_libs = []
74112790Smatteo.fusi@bsc.es    for lib in py_ld_flags:
74210453SAndrew.Bardsley@arm.com         if not lib.startswith('-l'):
7433118Sstever@eecs.umich.edu             main.Append(LINKFLAGS=[lib])
74410453SAndrew.Bardsley@arm.com         else:
74510453SAndrew.Bardsley@arm.com             lib = lib[2:]
74612563Sgabeblack@google.com             if lib not in py_libs:
74710453SAndrew.Bardsley@arm.com                 py_libs.append(lib)
7483118Sstever@eecs.umich.edu
7493483Ssaidi@eecs.umich.edu    # verify that this stuff works
7503494Ssaidi@eecs.umich.edu    if not conf.CheckHeader('Python.h', '<>'):
7513494Ssaidi@eecs.umich.edu        print("Error: Check failed for Python.h header in", py_includes)
75212563Sgabeblack@google.com        print("Two possible reasons:")
7533483Ssaidi@eecs.umich.edu        print("1. Python headers are not installed (You can install the "
7543483Ssaidi@eecs.umich.edu              "package python-dev on Ubuntu and RedHat)")
7553053Sstever@eecs.umich.edu        print("2. SCons is using a wrong C compiler. This can happen if "
7563053Sstever@eecs.umich.edu              "CC has the wrong value.")
7573918Ssaidi@eecs.umich.edu        print("CC = %s" % main['CC'])
75812563Sgabeblack@google.com        Exit(1)
75912563Sgabeblack@google.com
76012563Sgabeblack@google.com    for lib in py_libs:
7613053Sstever@eecs.umich.edu        if not conf.CheckLib(lib):
7623053Sstever@eecs.umich.edu            print("Error: can't find library %s required by python" % lib)
7639396Sandreas.hansson@arm.com            Exit(1)
7649396Sandreas.hansson@arm.com
7659396Sandreas.hansson@arm.com# On Solaris you need to use libsocket for socket ops
7669396Sandreas.hansson@arm.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7679396Sandreas.hansson@arm.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7689396Sandreas.hansson@arm.com       print("Can't find library with socket calls (e.g. accept())")
7699396Sandreas.hansson@arm.com       Exit(1)
7709396Sandreas.hansson@arm.com
7719396Sandreas.hansson@arm.com# Check for zlib.  If the check passes, libz will be automatically
77212920Sgabeblack@google.com# added to the LIBS environment variable.
77312920Sgabeblack@google.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
77412920Sgabeblack@google.com    print('Error: did not find needed zlib compression library '
77512920Sgabeblack@google.com          'and/or zlib.h header file.')
7769477Sandreas.hansson@arm.com    print('       Please install zlib and try again.')
7779396Sandreas.hansson@arm.com    Exit(1)
77812563Sgabeblack@google.com
77912563Sgabeblack@google.com# If we have the protobuf compiler, also make sure we have the
78012563Sgabeblack@google.com# development libraries. If the check passes, libprotobuf will be
78112563Sgabeblack@google.com# automatically added to the LIBS environment variable. After
7829396Sandreas.hansson@arm.com# this, we can use the HAVE_PROTOBUF flag to determine if we have
7837840Snate@binkert.org# got both protoc and libprotobuf available.
7847865Sgblack@eecs.umich.edumain['HAVE_PROTOBUF'] = main['PROTOC'] and \
7857865Sgblack@eecs.umich.edu    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
7867865Sgblack@eecs.umich.edu                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
7877865Sgblack@eecs.umich.edu
7887865Sgblack@eecs.umich.edu# Valgrind gets much less confused if you tell it when you're using
7897840Snate@binkert.org# alternative stacks.
7909900Sandreas@sandberg.pp.semain['HAVE_VALGRIND'] = conf.CheckCHeader('valgrind/valgrind.h')
7919900Sandreas@sandberg.pp.se
7929900Sandreas@sandberg.pp.se# If we have the compiler but not the library, print another warning.
7939900Sandreas@sandberg.pp.seif main['PROTOC'] and not main['HAVE_PROTOBUF']:
79410456SCurtis.Dunham@arm.com    print(termcap.Yellow + termcap.Bold +
79510456SCurtis.Dunham@arm.com        'Warning: did not find protocol buffer library and/or headers.\n' +
79610456SCurtis.Dunham@arm.com    '       Please install libprotobuf-dev for tracing support.' +
79710456SCurtis.Dunham@arm.com    termcap.Normal)
79810456SCurtis.Dunham@arm.com
79910456SCurtis.Dunham@arm.com# Check for librt.
80012563Sgabeblack@google.comhave_posix_clock = \
80112563Sgabeblack@google.com    conf.CheckLibWithHeader(None, 'time.h', 'C',
80212563Sgabeblack@google.com                            'clock_nanosleep(0,0,NULL,NULL);') or \
80312563Sgabeblack@google.com    conf.CheckLibWithHeader('rt', 'time.h', 'C',
8049045SAli.Saidi@ARM.com                            'clock_nanosleep(0,0,NULL,NULL);')
80511235Sandreas.sandberg@arm.com
80611235Sandreas.sandberg@arm.comhave_posix_timers = \
80711235Sandreas.sandberg@arm.com    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
80811235Sandreas.sandberg@arm.com                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
80911235Sandreas.sandberg@arm.com
81012485Sjang.hanhwi@gmail.comif not GetOption('without_tcmalloc'):
81112485Sjang.hanhwi@gmail.com    if conf.CheckLib('tcmalloc'):
81212485Sjang.hanhwi@gmail.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
81311235Sandreas.sandberg@arm.com    elif conf.CheckLib('tcmalloc_minimal'):
81411811Sbaz21@cam.ac.uk        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
81512485Sjang.hanhwi@gmail.com    else:
81611811Sbaz21@cam.ac.uk        print(termcap.Yellow + termcap.Bold +
81711811Sbaz21@cam.ac.uk              "You can get a 12% performance improvement by "
81811811Sbaz21@cam.ac.uk              "installing tcmalloc (libgoogle-perftools-dev package "
81911235Sandreas.sandberg@arm.com              "on Ubuntu or RedHat)." + termcap.Normal)
82011235Sandreas.sandberg@arm.com
82111235Sandreas.sandberg@arm.com
82212563Sgabeblack@google.com# Detect back trace implementations. The last implementation in the
82312563Sgabeblack@google.com# list will be used by default.
82412563Sgabeblack@google.combacktrace_impls = [ "none" ]
82511235Sandreas.sandberg@arm.com
8267840Snate@binkert.orgbacktrace_checker = 'char temp;' + \
82712563Sgabeblack@google.com    ' backtrace_symbols_fd((void*)&temp, 0, 0);'
8287840Snate@binkert.orgif conf.CheckLibWithHeader(None, 'execinfo.h', 'C', backtrace_checker):
8291858SN/A    backtrace_impls.append("glibc")
8301858SN/Aelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
8311858SN/A                             backtrace_checker):
83212563Sgabeblack@google.com    # NetBSD and FreeBSD need libexecinfo.
83312563Sgabeblack@google.com    backtrace_impls.append("glibc")
8341858SN/A    main.Append(LIBS=['execinfo'])
83512230Sgiacomo.travaglini@arm.com
83612230Sgiacomo.travaglini@arm.comif backtrace_impls[-1] == "none":
83712230Sgiacomo.travaglini@arm.com    default_backtrace_impl = "none"
83812230Sgiacomo.travaglini@arm.com    print(termcap.Yellow + termcap.Bold +
83912563Sgabeblack@google.com        "No suitable back trace implementation found." +
84012563Sgabeblack@google.com        termcap.Normal)
84112563Sgabeblack@google.com
84212230Sgiacomo.travaglini@arm.comif not have_posix_clock:
8439903Sandreas.hansson@arm.com    print("Can't find library for POSIX clocks.")
8449903Sandreas.hansson@arm.com
8459903Sandreas.hansson@arm.com# Check for <fenv.h> (C99 FP environment control)
8469903Sandreas.hansson@arm.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
84710841Sandreas.sandberg@arm.comif not have_fenv:
8489651SAndreas.Sandberg@ARM.com    print("Warning: Header file <fenv.h> not found.")
84912563Sgabeblack@google.com    print("         This host has no IEEE FP rounding mode control.")
85012563Sgabeblack@google.com
8519651SAndreas.Sandberg@ARM.com# Check for <png.h> (libpng library needed if wanting to dump
85212056Sgabeblack@google.com# frame buffer image in png format)
85312056Sgabeblack@google.comhave_png = conf.CheckHeader('png.h', '<>')
85412056Sgabeblack@google.comif not have_png:
85512563Sgabeblack@google.com    print("Warning: Header file <png.h> not found.")
85612056Sgabeblack@google.com    print("         This host has no libpng library.")
85710841Sandreas.sandberg@arm.com    print("         Disabling support for PNG framebuffers.")
85810841Sandreas.sandberg@arm.com
85910841Sandreas.sandberg@arm.com# Check if we should enable KVM-based hardware virtualization. The API
86010841Sandreas.sandberg@arm.com# we rely on exists since version 2.6.36 of the kernel, but somehow
86110841Sandreas.sandberg@arm.com# the KVM_API_VERSION does not reflect the change. We test for one of
86210841Sandreas.sandberg@arm.com# the types as a fall back.
8639651SAndreas.Sandberg@ARM.comhave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
8649651SAndreas.Sandberg@ARM.comif not have_kvm:
8659651SAndreas.Sandberg@ARM.com    print("Info: Compatible header file <linux/kvm.h> not found, "
8669651SAndreas.Sandberg@ARM.com          "disabling KVM support.")
8679651SAndreas.Sandberg@ARM.com
8689651SAndreas.Sandberg@ARM.com# Check if the TUN/TAP driver is available.
86912563Sgabeblack@google.comhave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
8709651SAndreas.Sandberg@ARM.comif not have_tuntap:
8719651SAndreas.Sandberg@ARM.com    print("Info: Compatible header file <linux/if_tun.h> not found.")
87210841Sandreas.sandberg@arm.com
87312563Sgabeblack@google.com# x86 needs support for xsave. We test for the structure here since we
87412563Sgabeblack@google.com# won't be able to run new tests by the time we know which ISA we're
87510841Sandreas.sandberg@arm.com# targeting.
87610841Sandreas.sandberg@arm.comhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
87710841Sandreas.sandberg@arm.com                                    '#include <linux/kvm.h>') != 0
87810860Sandreas.sandberg@arm.com
87910841Sandreas.sandberg@arm.com# Check if the requested target ISA is compatible with the host
88010841Sandreas.sandberg@arm.comdef is_isa_kvm_compatible(isa):
88110841Sandreas.sandberg@arm.com    try:
88210841Sandreas.sandberg@arm.com        import platform
88310841Sandreas.sandberg@arm.com        host_isa = platform.machine()
88412563Sgabeblack@google.com    except:
88510841Sandreas.sandberg@arm.com        print("Warning: Failed to determine host ISA.")
88610841Sandreas.sandberg@arm.com        return False
88710841Sandreas.sandberg@arm.com
88810841Sandreas.sandberg@arm.com    if not have_posix_timers:
88910841Sandreas.sandberg@arm.com        print("Warning: Can not enable KVM, host seems to lack support "
8909651SAndreas.Sandberg@ARM.com              "for POSIX timers")
8919651SAndreas.Sandberg@ARM.com        return False
8929986Sandreas@sandberg.pp.se
8939986Sandreas@sandberg.pp.se    if isa == "arm":
8949986Sandreas@sandberg.pp.se        return host_isa in ( "armv7l", "aarch64" )
8959986Sandreas@sandberg.pp.se    elif isa == "x86":
8969986Sandreas@sandberg.pp.se        if host_isa != "x86_64":
8979986Sandreas@sandberg.pp.se            return False
8985863Snate@binkert.org
8995863Snate@binkert.org        if not have_kvm_xsave:
9005863Snate@binkert.org            print("KVM on x86 requires xsave support in kernel headers.")
9015863Snate@binkert.org            return False
9026121Snate@binkert.org
9031858SN/A        return True
9045863Snate@binkert.org    else:
9055863Snate@binkert.org        return False
9065863Snate@binkert.org
9075863Snate@binkert.org
9085863Snate@binkert.org# Check if the exclude_host attribute is available. We want this to
9092139SN/A# get accurate instruction counts in KVM.
9104202Sbinkertn@umich.edumain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
91111308Santhony.gutierrez@amd.com    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
9124202Sbinkertn@umich.edu
91311308Santhony.gutierrez@amd.com
9142139SN/A######################################################################
9156994Snate@binkert.org#
9166994Snate@binkert.org# Finish the configuration
9176994Snate@binkert.org#
9186994Snate@binkert.orgmain = conf.Finish()
9196994Snate@binkert.org
9206994Snate@binkert.org######################################################################
9216994Snate@binkert.org#
9226994Snate@binkert.org# Collect all non-global variables
92310319SAndreas.Sandberg@ARM.com#
9246994Snate@binkert.org
9256994Snate@binkert.org# Define the universe of supported ISAs
9266994Snate@binkert.orgall_isa_list = [ ]
9276994Snate@binkert.orgall_gpu_isa_list = [ ]
9286994Snate@binkert.orgExport('all_isa_list')
9296994Snate@binkert.orgExport('all_gpu_isa_list')
9306994Snate@binkert.org
9316994Snate@binkert.orgclass CpuModel(object):
9326994Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
9336994Snate@binkert.org    know about a particular CPU model.'''
9346994Snate@binkert.org
9352155SN/A    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9365863Snate@binkert.org    dict = {}
9371869SN/A
9381869SN/A    # Constructor.  Automatically adds models to CpuModel.dict.
9395863Snate@binkert.org    def __init__(self, name, default=False):
9405863Snate@binkert.org        self.name = name           # name of model
9414202Sbinkertn@umich.edu
9426108Snate@binkert.org        # This cpu is enabled by default
9436108Snate@binkert.org        self.default = default
9446108Snate@binkert.org
9456108Snate@binkert.org        # Add self to dict
9469219Spower.jg@gmail.com        if name in CpuModel.dict:
9479219Spower.jg@gmail.com            raise AttributeError, "CpuModel '%s' already registered" % name
9489219Spower.jg@gmail.com        CpuModel.dict[name] = self
9499219Spower.jg@gmail.com
9509219Spower.jg@gmail.comExport('CpuModel')
9519219Spower.jg@gmail.com
9529219Spower.jg@gmail.com# Sticky variables get saved in the variables file so they persist from
9539219Spower.jg@gmail.com# one invocation to the next (unless overridden, in which case the new
9544202Sbinkertn@umich.edu# value becomes sticky).
9555863Snate@binkert.orgsticky_vars = Variables(args=ARGUMENTS)
95610135SCurtis.Dunham@arm.comExport('sticky_vars')
95712563Sgabeblack@google.com
9585742Snate@binkert.org# Sticky variables that should be exported
9598268Ssteve.reinhardt@amd.comexport_vars = []
96012563Sgabeblack@google.comExport('export_vars')
9618268Ssteve.reinhardt@amd.com
9625742Snate@binkert.org# For Ruby
9635341Sstever@gmail.comall_protocols = []
9648474Sgblack@eecs.umich.eduExport('all_protocols')
96512563Sgabeblack@google.comprotocol_dirs = []
9665342Sstever@gmail.comExport('protocol_dirs')
9674202Sbinkertn@umich.eduslicc_includes = []
9684202Sbinkertn@umich.eduExport('slicc_includes')
96911308Santhony.gutierrez@amd.com
9704202Sbinkertn@umich.edu# Walk the tree and execute all SConsopts scripts that wil add to the
9715863Snate@binkert.org# above variables
9725863Snate@binkert.orgif GetOption('verbose'):
97311308Santhony.gutierrez@amd.com    print("Reading SConsopts")
9746994Snate@binkert.orgfor bdir in [ base_dir ] + extras_dir_list:
9756994Snate@binkert.org    if not isdir(bdir):
97610319SAndreas.Sandberg@ARM.com        print("Error: directory '%s' does not exist" % bdir)
9775863Snate@binkert.org        Exit(1)
9785863Snate@binkert.org    for root, dirs, files in os.walk(bdir):
9795863Snate@binkert.org        if 'SConsopts' in files:
9805863Snate@binkert.org            if GetOption('verbose'):
9815863Snate@binkert.org                print("Reading", joinpath(root, 'SConsopts'))
9825863Snate@binkert.org            SConscript(joinpath(root, 'SConsopts'))
9835863Snate@binkert.org
9845863Snate@binkert.orgall_isa_list.sort()
9857840Snate@binkert.orgall_gpu_isa_list.sort()
9865863Snate@binkert.org
98712230Sgiacomo.travaglini@arm.comsticky_vars.AddVariables(
98812230Sgiacomo.travaglini@arm.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
98912230Sgiacomo.travaglini@arm.com    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
99012230Sgiacomo.travaglini@arm.com    ListVariable('CPU_MODELS', 'CPU models',
99112230Sgiacomo.travaglini@arm.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
99212056Sgabeblack@google.com                 sorted(CpuModel.dict.keys())),
99312056Sgabeblack@google.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
99412056Sgabeblack@google.com                 False),
99511308Santhony.gutierrez@amd.com    BoolVariable('SS_COMPATIBLE_FP',
9969219Spower.jg@gmail.com                 'Make floating-point results compatible with SimpleScalar',
9979219Spower.jg@gmail.com                 False),
99811235Sandreas.sandberg@arm.com    BoolVariable('USE_SSE2',
99911235Sandreas.sandberg@arm.com                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
10001869SN/A                 False),
10011858SN/A    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
10025863Snate@binkert.org    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
100311308Santhony.gutierrez@amd.com    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
100412061Sjason@lowepower.com    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
100512920Sgabeblack@google.com                 False),
100612920Sgabeblack@google.com    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
10071858SN/A                 have_kvm),
1008955SN/A    BoolVariable('USE_TUNTAP',
1009955SN/A                 'Enable using a tap device to bridge to the host network',
10101869SN/A                 have_tuntap),
10111869SN/A    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
10121869SN/A    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
10131869SN/A                  all_protocols),
10141869SN/A    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
10155863Snate@binkert.org                 backtrace_impls[-1], backtrace_impls)
10165863Snate@binkert.org    )
10175863Snate@binkert.org
10181869SN/A# These variables get exported to #defines in config/*.hh (see src/SConscript).
10195863Snate@binkert.orgexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
10201869SN/A                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
102112563Sgabeblack@google.com                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_VALGRIND',
10221869SN/A                'HAVE_PERF_ATTR_EXCLUDE_HOST', 'USE_PNG']
10231869SN/A
10241869SN/A###################################################
10251869SN/A#
10268483Sgblack@eecs.umich.edu# Define a SCons builder for configuration flag headers.
10271869SN/A#
10281869SN/A###################################################
10291869SN/A
10301869SN/A# This function generates a config header file that #defines the
10315863Snate@binkert.org# variable symbol to the current variable setting (0 or 1).  The source
10325863Snate@binkert.org# operands are the name of the variable and a Value node containing the
10331869SN/A# value of the variable.
10345863Snate@binkert.orgdef build_config_file(target, source, env):
10355863Snate@binkert.org    (variable, value) = [s.get_contents() for s in source]
10363356Sbinkertn@umich.edu    f = file(str(target[0]), 'w')
10373356Sbinkertn@umich.edu    print('#define', variable, value, file=f)
10383356Sbinkertn@umich.edu    f.close()
10393356Sbinkertn@umich.edu    return None
10403356Sbinkertn@umich.edu
10414781Snate@binkert.org# Combine the two functions into a scons Action object.
10425863Snate@binkert.orgconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
10435863Snate@binkert.org
10441869SN/A# The emitter munges the source & target node lists to reflect what
10451869SN/A# we're really doing.
10461869SN/Adef config_emitter(target, source, env):
10476121Snate@binkert.org    # extract variable name from Builder arg
10481869SN/A    variable = str(target[0])
104911982Sgabeblack@google.com    # True target is config header file
105011982Sgabeblack@google.com    target = joinpath('config', variable.lower() + '.hh')
105111982Sgabeblack@google.com    val = env[variable]
105211982Sgabeblack@google.com    if isinstance(val, bool):
105311982Sgabeblack@google.com        # Force value to 0/1
105411982Sgabeblack@google.com        val = int(val)
105511982Sgabeblack@google.com    elif isinstance(val, str):
105611982Sgabeblack@google.com        val = '"' + val + '"'
105711982Sgabeblack@google.com
105811982Sgabeblack@google.com    # Sources are variable name & value (packaged in SCons Value nodes)
105911982Sgabeblack@google.com    return ([target], [Value(variable), Value(val)])
106011982Sgabeblack@google.com
106111982Sgabeblack@google.comconfig_builder = Builder(emitter = config_emitter, action = config_action)
106211982Sgabeblack@google.com
106311982Sgabeblack@google.commain.Append(BUILDERS = { 'ConfigFile' : config_builder })
106411982Sgabeblack@google.com
106511982Sgabeblack@google.com###################################################
106611982Sgabeblack@google.com#
106711982Sgabeblack@google.com# Builders for static and shared partially linked object files.
106811982Sgabeblack@google.com#
106911982Sgabeblack@google.com###################################################
107011982Sgabeblack@google.com
107111982Sgabeblack@google.compartial_static_builder = Builder(action=SCons.Defaults.LinkAction,
107211982Sgabeblack@google.com                                 src_suffix='$OBJSUFFIX',
107311982Sgabeblack@google.com                                 src_builder=['StaticObject', 'Object'],
107411982Sgabeblack@google.com                                 LINKFLAGS='$PLINKFLAGS',
107511978Sgabeblack@google.com                                 LIBS='')
107611978Sgabeblack@google.com
107712034Sgabeblack@google.comdef partial_shared_emitter(target, source, env):
107811978Sgabeblack@google.com    for tgt in target:
107911978Sgabeblack@google.com        tgt.attributes.shared = 1
108011978Sgabeblack@google.com    return (target, source)
108112034Sgabeblack@google.compartial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
108211978Sgabeblack@google.com                                 emitter=partial_shared_emitter,
108311978Sgabeblack@google.com                                 src_suffix='$SHOBJSUFFIX',
108410915Sandreas.sandberg@arm.com                                 src_builder='SharedObject',
108513577Sciro.santilli@arm.com                                 SHLINKFLAGS='$PSHLINKFLAGS',
108613577Sciro.santilli@arm.com                                 LIBS='')
108713577Sciro.santilli@arm.com
108811986Sandreas.sandberg@arm.commain.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
108911986Sandreas.sandberg@arm.com                         'PartialStatic' : partial_static_builder })
10901869SN/A
10911869SN/Adef add_local_rpath(env, *targets):
109212015Sgabeblack@google.com    '''Set up an RPATH for a library which lives in the build directory.
109312015Sgabeblack@google.com
109412015Sgabeblack@google.com    The construction environment variable BIN_RPATH_PREFIX should be set to
109512015Sgabeblack@google.com    the relative path of the build directory starting from the location of the
10963546Sgblack@eecs.umich.edu    binary.'''
10973546Sgblack@eecs.umich.edu    for target in targets:
10983546Sgblack@eecs.umich.edu        target = env.Entry(target)
109912015Sgabeblack@google.com        if not target.isdir():
110012015Sgabeblack@google.com            target = target.dir
110112015Sgabeblack@google.com        relpath = os.path.relpath(target.abspath, env['BUILDDIR'])
110212015Sgabeblack@google.com        components = [
110312015Sgabeblack@google.com            '\\$$ORIGIN',
110412015Sgabeblack@google.com            '${BIN_RPATH_PREFIX}',
110512015Sgabeblack@google.com            relpath
110612563Sgabeblack@google.com        ]
11073546Sgblack@eecs.umich.edu        env.Append(RPATH=[env.Literal(os.path.join(*components))])
110812015Sgabeblack@google.com
110912015Sgabeblack@google.comif sys.platform != "darwin":
111010196SCurtis.Dunham@arm.com    main.Append(LINKFLAGS=Split('-z origin'))
111112015Sgabeblack@google.com
111212015Sgabeblack@google.commain.AddMethod(add_local_rpath, 'AddLocalRPATH')
111312015Sgabeblack@google.com
111412015Sgabeblack@google.com# builds in ext are shared across all configs in the build root.
111512015Sgabeblack@google.comext_dir = abspath(joinpath(str(main.root), 'ext'))
111612015Sgabeblack@google.comext_build_dirs = []
111712015Sgabeblack@google.comfor root, dirs, files in os.walk(ext_dir):
111812015Sgabeblack@google.com    if 'SConscript' in files:
111912015Sgabeblack@google.com        build_dir = os.path.relpath(root, ext_dir)
112012015Sgabeblack@google.com        ext_build_dirs.append(build_dir)
112112015Sgabeblack@google.com        main.SConscript(joinpath(root, 'SConscript'),
11223546Sgblack@eecs.umich.edu                        variant_dir=joinpath(build_root, build_dir))
11233546Sgblack@eecs.umich.edu
11243546Sgblack@eecs.umich.edugdb_xml_dir = joinpath(ext_dir, 'gdb-xml')
1125955SN/AExport('gdb_xml_dir')
1126955SN/A
1127955SN/Amain.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1128955SN/A
11295863Snate@binkert.org###################################################
113010135SCurtis.Dunham@arm.com#
113112563Sgabeblack@google.com# This builder and wrapper method are used to set up a directory with
11325343Sstever@gmail.com# switching headers. Those are headers which are in a generic location and
11335343Sstever@gmail.com# that include more specific headers from a directory chosen at build time
11346121Snate@binkert.org# based on the current build settings.
11355863Snate@binkert.org#
11364773Snate@binkert.org###################################################
11375863Snate@binkert.org
11382632Sstever@eecs.umich.edudef build_switching_header(target, source, env):
11395863Snate@binkert.org    path = str(target[0])
11402023SN/A    subdir = str(source[0])
11415863Snate@binkert.org    dp, fp = os.path.split(path)
11425863Snate@binkert.org    dp = os.path.relpath(os.path.realpath(dp),
11435863Snate@binkert.org                         os.path.realpath(env['BUILDDIR']))
11445863Snate@binkert.org    with open(path, 'w') as hdr:
11455863Snate@binkert.org        print('#include "%s/%s/%s"' % (dp, subdir, fp), file=hdr)
11465863Snate@binkert.org
11475863Snate@binkert.orgswitching_header_action = MakeAction(build_switching_header,
11485863Snate@binkert.org                                     Transform('GENERATE'))
114910135SCurtis.Dunham@arm.com
115012563Sgabeblack@google.comswitching_header_builder = Builder(action=switching_header_action,
115112034Sgabeblack@google.com                                   source_factory=Value,
115212034Sgabeblack@google.com                                   single_source=True)
115312034Sgabeblack@google.com
11542632Sstever@eecs.umich.edumain.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
11555863Snate@binkert.org
11562023SN/Adef switching_headers(self, headers, source):
11572632Sstever@eecs.umich.edu    for header in headers:
11585863Snate@binkert.org        self.SwitchingHeader(header, source)
11595342Sstever@gmail.com
11605863Snate@binkert.orgmain.AddMethod(switching_headers, 'SwitchingHeaders')
11612632Sstever@eecs.umich.edu
11625863Snate@binkert.org###################################################
11635863Snate@binkert.org#
11648267Ssteve.reinhardt@amd.com# Define build environments for selected configurations.
11658120Sgblack@eecs.umich.edu#
11668267Ssteve.reinhardt@amd.com###################################################
11678267Ssteve.reinhardt@amd.com
11688267Ssteve.reinhardt@amd.comfor variant_path in variant_paths:
11698267Ssteve.reinhardt@amd.com    if not GetOption('silent'):
11708267Ssteve.reinhardt@amd.com        print("Building in", variant_path)
11718267Ssteve.reinhardt@amd.com
11728267Ssteve.reinhardt@amd.com    # Make a copy of the build-root environment to use for this config.
11738267Ssteve.reinhardt@amd.com    env = main.Clone()
11748267Ssteve.reinhardt@amd.com    env['BUILDDIR'] = variant_path
11755863Snate@binkert.org
117612563Sgabeblack@google.com    # variant_dir is the tail component of build path, and is used to
117712563Sgabeblack@google.com    # determine the build parameters (e.g., 'ALPHA_SE')
11782632Sstever@eecs.umich.edu    (build_root, variant_dir) = splitpath(variant_path)
117912563Sgabeblack@google.com
118012563Sgabeblack@google.com    # Set env variables according to the build directory config.
118112563Sgabeblack@google.com    sticky_vars.files = []
11822632Sstever@eecs.umich.edu    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
11831888SN/A    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
11845863Snate@binkert.org    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
11855863Snate@binkert.org    current_vars_file = joinpath(build_root, 'variables', variant_dir)
11861858SN/A    if isfile(current_vars_file):
11878120Sgblack@eecs.umich.edu        sticky_vars.files.append(current_vars_file)
11888120Sgblack@eecs.umich.edu        if not GetOption('silent'):
11897756SAli.Saidi@ARM.com            print("Using saved variables file %s" % current_vars_file)
11902598SN/A    elif variant_dir in ext_build_dirs:
11915863Snate@binkert.org        # Things in ext are built without a variant directory.
11921858SN/A        continue
11931858SN/A    else:
119412563Sgabeblack@google.com        # Build dir-specific variables file doesn't exist.
119512563Sgabeblack@google.com
11961858SN/A        # Make sure the directory is there so we can create it later
11971858SN/A        opt_dir = dirname(current_vars_file)
11981858SN/A        if not isdir(opt_dir):
119912563Sgabeblack@google.com            mkdir(opt_dir)
120012563Sgabeblack@google.com
120112563Sgabeblack@google.com        # Get default build variables from source tree.  Variables are
12021858SN/A        # normally determined by name of $VARIANT_DIR, but can be
120312230Sgiacomo.travaglini@arm.com        # overridden by '--default=' arg on command line.
120412563Sgabeblack@google.com        default = GetOption('default')
120512563Sgabeblack@google.com        opts_dir = joinpath(main.root.abspath, 'build_opts')
120612230Sgiacomo.travaglini@arm.com        if default:
120712230Sgiacomo.travaglini@arm.com            default_vars_files = [joinpath(build_root, 'variables', default),
120812230Sgiacomo.travaglini@arm.com                                  joinpath(opts_dir, default)]
120912230Sgiacomo.travaglini@arm.com        else:
121012230Sgiacomo.travaglini@arm.com            default_vars_files = [joinpath(opts_dir, variant_dir)]
12111858SN/A        existing_files = filter(isfile, default_vars_files)
12121858SN/A        if existing_files:
12131858SN/A            default_vars_file = existing_files[0]
12149651SAndreas.Sandberg@ARM.com            sticky_vars.files.append(default_vars_file)
12159651SAndreas.Sandberg@ARM.com            print("Variables file %s not found,\n  using defaults in %s"
121612563Sgabeblack@google.com                  % (current_vars_file, default_vars_file))
121712563Sgabeblack@google.com        else:
12189651SAndreas.Sandberg@ARM.com            print("Error: cannot find variables file %s or "
12199651SAndreas.Sandberg@ARM.com                  "default file(s) %s"
122012563Sgabeblack@google.com                  % (current_vars_file, ' or '.join(default_vars_files)))
122112563Sgabeblack@google.com            Exit(1)
12229651SAndreas.Sandberg@ARM.com
12239651SAndreas.Sandberg@ARM.com    # Apply current variable settings to env
122412056Sgabeblack@google.com    sticky_vars.Update(env)
122512056Sgabeblack@google.com
122612563Sgabeblack@google.com    help_texts["local_vars"] += \
122712056Sgabeblack@google.com        "Build variables for %s:\n" % variant_dir \
122812056Sgabeblack@google.com                 + sticky_vars.GenerateHelpText(env)
122911798Santhony.gutierrez@amd.com
123011798Santhony.gutierrez@amd.com    # Process variable settings.
123111798Santhony.gutierrez@amd.com
12329986Sandreas@sandberg.pp.se    if not have_fenv and env['USE_FENV']:
12339986Sandreas@sandberg.pp.se        print("Warning: <fenv.h> not available; "
12349986Sandreas@sandberg.pp.se              "forcing USE_FENV to False in", variant_dir + ".")
123512563Sgabeblack@google.com        env['USE_FENV'] = False
123612563Sgabeblack@google.com
123712563Sgabeblack@google.com    if not env['USE_FENV']:
12389986Sandreas@sandberg.pp.se        print("Warning: No IEEE FP rounding mode control in",
12395863Snate@binkert.org              variant_dir + ".")
12405863Snate@binkert.org        print("         FP results may deviate slightly from other platforms.")
12411869SN/A
12421965SN/A    if not have_png and env['USE_PNG']:
12437739Sgblack@eecs.umich.edu        print("Warning: <png.h> not available; "
12441965SN/A              "forcing USE_PNG to False in", variant_dir + ".")
12452761Sstever@eecs.umich.edu        env['USE_PNG'] = False
12465863Snate@binkert.org
12471869SN/A    if env['USE_PNG']:
124810196SCurtis.Dunham@arm.com        env.Append(LIBS=['png'])
12491869SN/A
12508120Sgblack@eecs.umich.edu    if env['EFENCE']:
12518120Sgblack@eecs.umich.edu        env.Append(LIBS=['efence'])
12528120Sgblack@eecs.umich.edu
12538120Sgblack@eecs.umich.edu    if env['USE_KVM']:
12548120Sgblack@eecs.umich.edu        if not have_kvm:
12558120Sgblack@eecs.umich.edu            print("Warning: Can not enable KVM, host seems to "
12568120Sgblack@eecs.umich.edu                  "lack KVM support")
12578120Sgblack@eecs.umich.edu            env['USE_KVM'] = False
12588120Sgblack@eecs.umich.edu        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
12598120Sgblack@eecs.umich.edu            print("Info: KVM support disabled due to unsupported host and "
12608120Sgblack@eecs.umich.edu                  "target ISA combination")
12618120Sgblack@eecs.umich.edu            env['USE_KVM'] = False
1262
1263    if env['USE_TUNTAP']:
1264        if not have_tuntap:
1265            print("Warning: Can't connect EtherTap with a tap device.")
1266            env['USE_TUNTAP'] = False
1267
1268    if env['BUILD_GPU']:
1269        env.Append(CPPDEFINES=['BUILD_GPU'])
1270
1271    # Warn about missing optional functionality
1272    if env['USE_KVM']:
1273        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1274            print("Warning: perf_event headers lack support for the "
1275                  "exclude_host attribute. KVM instruction counts will "
1276                  "be inaccurate.")
1277
1278    # Save sticky variable settings back to current variables file
1279    sticky_vars.Save(current_vars_file, env)
1280
1281    if env['USE_SSE2']:
1282        env.Append(CCFLAGS=['-msse2'])
1283
1284    # The src/SConscript file sets up the build rules in 'env' according
1285    # to the configured variables.  It returns a list of environments,
1286    # one for each variant build (debug, opt, etc.)
1287    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1288
1289# base help text
1290Help('''
1291Usage: scons [scons options] [build variables] [target(s)]
1292
1293Extra scons options:
1294%(options)s
1295
1296Global build variables:
1297%(global_vars)s
1298
1299%(local_vars)s
1300''' % help_texts)
1301