SConstruct revision 12790:9cfb7f1c50b6
1955SN/A# -*- mode:python -*-
2955SN/A
310841Sandreas.sandberg@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
815863Snate@binkert.orgfrom __future__ import print_function
825863Snate@binkert.org
835863Snate@binkert.org# Global Python includes
845863Snate@binkert.orgimport itertools
855863Snate@binkert.orgimport os
865863Snate@binkert.orgimport re
875863Snate@binkert.orgimport shutil
885863Snate@binkert.orgimport subprocess
895863Snate@binkert.orgimport sys
905863Snate@binkert.org
915863Snate@binkert.orgfrom os import mkdir, environ
928878Ssteve.reinhardt@amd.comfrom 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
955863Snate@binkert.org
969812Sandreas.hansson@arm.com# SCons includes
979812Sandreas.hansson@arm.comimport SCons
985863Snate@binkert.orgimport SCons.Node
999812Sandreas.hansson@arm.com
1005863Snate@binkert.orgfrom m5.util import compareVersions, readCommand
1015863Snate@binkert.org
1025863Snate@binkert.orghelp_texts = {
1039812Sandreas.hansson@arm.com    "options" : "",
1049812Sandreas.hansson@arm.com    "global_vars" : "",
1055863Snate@binkert.org    "local_vars" : ""
1065863Snate@binkert.org}
1078878Ssteve.reinhardt@amd.com
1085863Snate@binkert.orgExport("help_texts")
1095863Snate@binkert.org
1105863Snate@binkert.org
1116654Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
11210196SCurtis.Dunham@arm.com# AddOption() are supposed to be displayed when you type 'scons -h'
113955SN/A# and (2) you can override the help displayed by 'scons -h' using the
1145396Ssaidi@eecs.umich.edu# Help() function, but these two features are incompatible: once
1155863Snate@binkert.org# you've overridden the help text using Help(), there's no way to get
1165863Snate@binkert.org# at the help texts from AddOptions.  See:
1174202Sbinkertn@umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1185863Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1195863Snate@binkert.org# This hack lets us extract the help text from AddOptions and
1205863Snate@binkert.org# re-inject it via Help().  Ideally someday this bug will be fixed and
1215863Snate@binkert.org# we can just use AddOption directly.
122955SN/Adef AddLocalOption(*args, **kwargs):
1236654Snate@binkert.org    col_width = 30
1245273Sstever@gmail.com
1255871Snate@binkert.org    help = "  " + ", ".join(args)
1265273Sstever@gmail.com    if "help" in kwargs:
1276655Snate@binkert.org        length = len(help)
1288878Ssteve.reinhardt@amd.com        if length >= col_width:
1296655Snate@binkert.org            help += "\n" + " " * col_width
1306655Snate@binkert.org        else:
1319219Spower.jg@gmail.com            help += " " * (col_width - length)
1326655Snate@binkert.org        help += kwargs["help"]
1335871Snate@binkert.org    help_texts["options"] += help + "\n"
1346654Snate@binkert.org
1358947Sandreas.hansson@arm.com    AddOption(*args, **kwargs)
1365396Ssaidi@eecs.umich.edu
1378120Sgblack@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1388120Sgblack@eecs.umich.edu               help="Add color to abbreviated scons output")
1398120Sgblack@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1408120Sgblack@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1418120Sgblack@eecs.umich.eduAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1428120Sgblack@eecs.umich.edu               action='store_true',
1438120Sgblack@eecs.umich.edu               help="Build with support for C++-based configuration")
1448120Sgblack@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1458879Ssteve.reinhardt@amd.com               help='Override which build_opts file to use for defaults')
1468879Ssteve.reinhardt@amd.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1478879Ssteve.reinhardt@amd.com               help='Disable style checking hooks')
1488879Ssteve.reinhardt@amd.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1498879Ssteve.reinhardt@amd.com               help='Disable Link-Time Optimization for fast')
1508879Ssteve.reinhardt@amd.comAddLocalOption('--force-lto', dest='force_lto', action='store_true',
1518879Ssteve.reinhardt@amd.com               help='Use Link-Time Optimization instead of partial linking' +
1528879Ssteve.reinhardt@amd.com                    ' when the compiler doesn\'t support using them together.')
1538879Ssteve.reinhardt@amd.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1548879Ssteve.reinhardt@amd.com               help='Update test reference outputs')
1558879Ssteve.reinhardt@amd.comAddLocalOption('--verbose', dest='verbose', action='store_true',
1568879Ssteve.reinhardt@amd.com               help='Print full tool command lines')
1578879Ssteve.reinhardt@amd.comAddLocalOption('--without-python', dest='without_python',
1588120Sgblack@eecs.umich.edu               action='store_true',
1598120Sgblack@eecs.umich.edu               help='Build without Python configuration support')
1608120Sgblack@eecs.umich.eduAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1618120Sgblack@eecs.umich.edu               action='store_true',
1628120Sgblack@eecs.umich.edu               help='Disable linking against tcmalloc')
1638120Sgblack@eecs.umich.eduAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1648120Sgblack@eecs.umich.edu               help='Build with Undefined Behavior Sanitizer if available')
1658120Sgblack@eecs.umich.eduAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1668120Sgblack@eecs.umich.edu               help='Build with Address Sanitizer if available')
1678120Sgblack@eecs.umich.edu
1688120Sgblack@eecs.umich.eduif GetOption('no_lto') and GetOption('force_lto'):
1698120Sgblack@eecs.umich.edu    print('--no-lto and --force-lto are mutually exclusive')
1708120Sgblack@eecs.umich.edu    Exit(1)
1718120Sgblack@eecs.umich.edu
1728879Ssteve.reinhardt@amd.com########################################################################
1738879Ssteve.reinhardt@amd.com#
1748879Ssteve.reinhardt@amd.com# Set up the main build environment.
1758879Ssteve.reinhardt@amd.com#
17610458Sandreas.hansson@arm.com########################################################################
17710458Sandreas.hansson@arm.com
17810458Sandreas.hansson@arm.commain = Environment()
1798879Ssteve.reinhardt@amd.com
1808879Ssteve.reinhardt@amd.comfrom gem5_scons import Transform
1818879Ssteve.reinhardt@amd.comfrom gem5_scons.util import get_termcap
1828879Ssteve.reinhardt@amd.comtermcap = get_termcap()
1839227Sandreas.hansson@arm.com
1849227Sandreas.hansson@arm.commain_dict_keys = main.Dictionary().keys()
1858879Ssteve.reinhardt@amd.com
1868879Ssteve.reinhardt@amd.com# Check that we have a C/C++ compiler
1878879Ssteve.reinhardt@amd.comif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1888879Ssteve.reinhardt@amd.com    print("No C++ compiler installed (package g++ on Ubuntu and RedHat)")
18910453SAndrew.Bardsley@arm.com    Exit(1)
19010453SAndrew.Bardsley@arm.com
19110453SAndrew.Bardsley@arm.com###################################################
19210456SCurtis.Dunham@arm.com#
19310456SCurtis.Dunham@arm.com# Figure out which configurations to set up based on the path(s) of
19410456SCurtis.Dunham@arm.com# the target(s).
19510457Sandreas.hansson@arm.com#
19610457Sandreas.hansson@arm.com###################################################
1978120Sgblack@eecs.umich.edu
1988947Sandreas.hansson@arm.com# Find default configuration & binary.
1997816Ssteve.reinhardt@amd.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2005871Snate@binkert.org
2015871Snate@binkert.org# helper function: find last occurrence of element in list
2026121Snate@binkert.orgdef rfind(l, elt, offs = -1):
2035871Snate@binkert.org    for i in range(len(l)+offs, 0, -1):
2045871Snate@binkert.org        if l[i] == elt:
2059926Sstan.czerniawski@arm.com            return i
2069926Sstan.czerniawski@arm.com    raise ValueError, "element not found"
2079119Sandreas.hansson@arm.com
20810068Sandreas.hansson@arm.com# Take a list of paths (or SCons Nodes) and return a list with all
20910068Sandreas.hansson@arm.com# paths made absolute and ~-expanded.  Paths will be interpreted
210955SN/A# relative to the launch directory unless a different root is provided
2119416SAndreas.Sandberg@ARM.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
2129416SAndreas.Sandberg@ARM.com    return [abspath(joinpath(root, expanduser(str(p))))
2139416SAndreas.Sandberg@ARM.com            for p in path_list]
2149416SAndreas.Sandberg@ARM.com
2159416SAndreas.Sandberg@ARM.com# Each target must have 'build' in the interior of the path; the
2169416SAndreas.Sandberg@ARM.com# directory below this will determine the build parameters.  For
2179416SAndreas.Sandberg@ARM.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2185871Snate@binkert.org# recognize that ALPHA_SE specifies the configuration because it
21910584Sandreas.hansson@arm.com# follow 'build' in the build path.
2209416SAndreas.Sandberg@ARM.com
2219416SAndreas.Sandberg@ARM.com# The funky assignment to "[:]" is needed to replace the list contents
2225871Snate@binkert.org# in place rather than reassign the symbol to a new list, which
223955SN/A# doesn't work (obviously!).
22410671Sandreas.hansson@arm.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
22510671Sandreas.hansson@arm.com
22610671Sandreas.hansson@arm.com# Generate a list of the unique build roots and configs that the
22710671Sandreas.hansson@arm.com# collected targets reference.
2288881Smarc.orr@gmail.comvariant_paths = []
2296121Snate@binkert.orgbuild_root = None
2306121Snate@binkert.orgfor t in BUILD_TARGETS:
2311533SN/A    path_dirs = t.split('/')
2329239Sandreas.hansson@arm.com    try:
2339239Sandreas.hansson@arm.com        build_top = rfind(path_dirs, 'build', -2)
2349239Sandreas.hansson@arm.com    except:
2359239Sandreas.hansson@arm.com        print("Error: no non-leaf 'build' dir found on target path", t)
2369239Sandreas.hansson@arm.com        Exit(1)
2379239Sandreas.hansson@arm.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2389239Sandreas.hansson@arm.com    if not build_root:
2399239Sandreas.hansson@arm.com        build_root = this_build_root
2409239Sandreas.hansson@arm.com    else:
2419239Sandreas.hansson@arm.com        if this_build_root != build_root:
2429239Sandreas.hansson@arm.com            print("Error: build targets not under same build root\n"
2439239Sandreas.hansson@arm.com                  "  %s\n  %s" % (build_root, this_build_root))
2446655Snate@binkert.org            Exit(1)
2456655Snate@binkert.org    variant_path = joinpath('/',*path_dirs[:build_top+2])
2466655Snate@binkert.org    if variant_path not in variant_paths:
2476655Snate@binkert.org        variant_paths.append(variant_path)
2485871Snate@binkert.org
2495871Snate@binkert.org# Make sure build_root exists (might not if this is the first build there)
2505863Snate@binkert.orgif not isdir(build_root):
2515871Snate@binkert.org    mkdir(build_root)
2528878Ssteve.reinhardt@amd.commain['BUILDROOT'] = build_root
2535871Snate@binkert.org
2545871Snate@binkert.orgExport('main')
2555871Snate@binkert.org
2565863Snate@binkert.orgmain.SConsignFile(joinpath(build_root, "sconsign"))
2576121Snate@binkert.org
2585863Snate@binkert.org# Default duplicate option is to use hard links, but this messes up
2595871Snate@binkert.org# when you use emacs to edit a file in the target dir, as emacs moves
2608336Ssteve.reinhardt@amd.com# file to file~ then copies to file, breaking the link.  Symbolic
2618336Ssteve.reinhardt@amd.com# (soft) links work better.
2628336Ssteve.reinhardt@amd.commain.SetOption('duplicate', 'soft-copy')
2638336Ssteve.reinhardt@amd.com
2644678Snate@binkert.org#
2658336Ssteve.reinhardt@amd.com# Set up global sticky variables... these are common to an entire build
2668336Ssteve.reinhardt@amd.com# tree (not specific to a particular build like ALPHA_SE)
2678336Ssteve.reinhardt@amd.com#
2684678Snate@binkert.org
2694678Snate@binkert.orgglobal_vars_file = joinpath(build_root, 'variables.global')
2704678Snate@binkert.org
2714678Snate@binkert.orgglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2727827Snate@binkert.org
2737827Snate@binkert.orgglobal_vars.AddVariables(
2748336Ssteve.reinhardt@amd.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2754678Snate@binkert.org    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2768336Ssteve.reinhardt@amd.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2778336Ssteve.reinhardt@amd.com    ('BATCH', 'Use batch pool for build and tests', False),
2788336Ssteve.reinhardt@amd.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2798336Ssteve.reinhardt@amd.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2808336Ssteve.reinhardt@amd.com    ('EXTRAS', 'Add extra directories to the compilation', '')
2818336Ssteve.reinhardt@amd.com    )
2825871Snate@binkert.org
2835871Snate@binkert.org# Update main environment with values from ARGUMENTS & global_vars_file
2848336Ssteve.reinhardt@amd.comglobal_vars.Update(main)
2858336Ssteve.reinhardt@amd.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
2868336Ssteve.reinhardt@amd.com
2878336Ssteve.reinhardt@amd.com# Save sticky variable settings back to current variables file
2888336Ssteve.reinhardt@amd.comglobal_vars.Save(global_vars_file, main)
2895871Snate@binkert.org
2908336Ssteve.reinhardt@amd.com# Parse EXTRAS variable to build list of all directories where we're
2918336Ssteve.reinhardt@amd.com# look for sources etc.  This list is exported as extras_dir_list.
2928336Ssteve.reinhardt@amd.combase_dir = main.srcdir.abspath
2938336Ssteve.reinhardt@amd.comif main['EXTRAS']:
2948336Ssteve.reinhardt@amd.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
2954678Snate@binkert.orgelse:
2965871Snate@binkert.org    extras_dir_list = []
2974678Snate@binkert.org
2988336Ssteve.reinhardt@amd.comExport('base_dir')
2998336Ssteve.reinhardt@amd.comExport('extras_dir_list')
3008336Ssteve.reinhardt@amd.com
3018336Ssteve.reinhardt@amd.com# the ext directory should be on the #includes path
3028336Ssteve.reinhardt@amd.commain.Append(CPPPATH=[Dir('ext')])
3038336Ssteve.reinhardt@amd.com
3048336Ssteve.reinhardt@amd.com# Add shared top-level headers
3058336Ssteve.reinhardt@amd.commain.Prepend(CPPPATH=Dir('include'))
3068336Ssteve.reinhardt@amd.com
3078336Ssteve.reinhardt@amd.comif GetOption('verbose'):
3088336Ssteve.reinhardt@amd.com    def MakeAction(action, string, *args, **kwargs):
3098336Ssteve.reinhardt@amd.com        return Action(action, *args, **kwargs)
3108336Ssteve.reinhardt@amd.comelse:
3118336Ssteve.reinhardt@amd.com    MakeAction = Action
3128336Ssteve.reinhardt@amd.com    main['CCCOMSTR']        = Transform("CC")
3138336Ssteve.reinhardt@amd.com    main['CXXCOMSTR']       = Transform("CXX")
3148336Ssteve.reinhardt@amd.com    main['ASCOMSTR']        = Transform("AS")
3155871Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
3166121Snate@binkert.org    main['LINKCOMSTR']      = Transform("LINK", 0)
317955SN/A    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
318955SN/A    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
3192632Sstever@eecs.umich.edu    main['M4COMSTR']        = Transform("M4")
3202632Sstever@eecs.umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
321955SN/A    main['SHCXXCOMSTR']     = Transform("SHCXX")
322955SN/AExport('MakeAction')
323955SN/A
324955SN/A# Initialize the Link-Time Optimization (LTO) flags
3258878Ssteve.reinhardt@amd.commain['LTO_CCFLAGS'] = []
326955SN/Amain['LTO_LDFLAGS'] = []
3272632Sstever@eecs.umich.edu
3282632Sstever@eecs.umich.edu# According to the readme, tcmalloc works best if the compiler doesn't
3292632Sstever@eecs.umich.edu# assume that we're using the builtin malloc and friends. These flags
3302632Sstever@eecs.umich.edu# are compiler-specific, so we need to set them after we detect which
3312632Sstever@eecs.umich.edu# compiler we're using.
3322632Sstever@eecs.umich.edumain['TCMALLOC_CCFLAGS'] = []
3332632Sstever@eecs.umich.edu
3348268Ssteve.reinhardt@amd.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3358268Ssteve.reinhardt@amd.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
3368268Ssteve.reinhardt@amd.com
3378268Ssteve.reinhardt@amd.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3388268Ssteve.reinhardt@amd.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
3398268Ssteve.reinhardt@amd.comif main['GCC'] + main['CLANG'] > 1:
3408268Ssteve.reinhardt@amd.com    print('Error: How can we have two at the same time?')
3412632Sstever@eecs.umich.edu    Exit(1)
3422632Sstever@eecs.umich.edu
3432632Sstever@eecs.umich.edu# Set up default C++ compiler flags
3442632Sstever@eecs.umich.eduif main['GCC'] or main['CLANG']:
3458268Ssteve.reinhardt@amd.com    # As gcc and clang share many flags, do the common parts here
3462632Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
3478268Ssteve.reinhardt@amd.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
3488268Ssteve.reinhardt@amd.com    # Enable -Wall and -Wextra and then disable the few warnings that
3498268Ssteve.reinhardt@amd.com    # we consistently violate
3508268Ssteve.reinhardt@amd.com    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
3513718Sstever@eecs.umich.edu                         '-Wno-sign-compare', '-Wno-unused-parameter'])
3522634Sstever@eecs.umich.edu    # We always compile using C++11
3532634Sstever@eecs.umich.edu    main.Append(CXXFLAGS=['-std=c++11'])
3545863Snate@binkert.org    if sys.platform.startswith('freebsd'):
3552638Sstever@eecs.umich.edu        main.Append(CCFLAGS=['-I/usr/local/include'])
3568268Ssteve.reinhardt@amd.com        main.Append(CXXFLAGS=['-I/usr/local/include'])
3572632Sstever@eecs.umich.edu
3582632Sstever@eecs.umich.edu    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
3592632Sstever@eecs.umich.edu    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
3602632Sstever@eecs.umich.edu    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
3612632Sstever@eecs.umich.edu    shared_partial_flags = ['-r', '-nostdlib']
3621858SN/A    main.Append(PSHLINKFLAGS=shared_partial_flags)
3633716Sstever@eecs.umich.edu    main.Append(PLINKFLAGS=shared_partial_flags)
3642638Sstever@eecs.umich.edu
3652638Sstever@eecs.umich.edu    # Treat warnings as errors but white list some warnings that we
3662638Sstever@eecs.umich.edu    # want to allow (e.g., deprecation warnings).
3672638Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Werror',
3682638Sstever@eecs.umich.edu                         '-Wno-error=deprecated-declarations',
3692638Sstever@eecs.umich.edu                         '-Wno-error=deprecated',
3702638Sstever@eecs.umich.edu                        ])
3715863Snate@binkert.orgelse:
3725863Snate@binkert.org    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
3735863Snate@binkert.org    print("Don't know what compiler options to use for your compiler.")
374955SN/A    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
3755341Sstever@gmail.com    print(termcap.Yellow + '       version:' + termcap.Normal, end = ' ')
3765341Sstever@gmail.com    if not CXX_version:
3775863Snate@binkert.org        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
3787756SAli.Saidi@ARM.com              termcap.Normal)
3795341Sstever@gmail.com    else:
3806121Snate@binkert.org        print(CXX_version.replace('\n', '<nl>'))
3814494Ssaidi@eecs.umich.edu    print("       If you're trying to use a compiler other than GCC")
3826121Snate@binkert.org    print("       or clang, there appears to be something wrong with your")
3831105SN/A    print("       environment.")
3842667Sstever@eecs.umich.edu    print("       ")
3852667Sstever@eecs.umich.edu    print("       If you are trying to use a compiler other than those listed")
3862667Sstever@eecs.umich.edu    print("       above you will need to ease fix SConstruct and ")
3872667Sstever@eecs.umich.edu    print("       src/SConscript to support that compiler.")
3886121Snate@binkert.org    Exit(1)
3892667Sstever@eecs.umich.edu
3905341Sstever@gmail.comif main['GCC']:
3915863Snate@binkert.org    # Check for a supported version of gcc. >= 4.8 is chosen for its
3925341Sstever@gmail.com    # level of c++11 support. See
3935341Sstever@gmail.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
3945341Sstever@gmail.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
3958120Sgblack@eecs.umich.edu    if compareVersions(gcc_version, "4.8") < 0:
3965341Sstever@gmail.com        print('Error: gcc version 4.8 or newer required.')
3978120Sgblack@eecs.umich.edu        print('       Installed version: ', gcc_version)
3985341Sstever@gmail.com        Exit(1)
3998120Sgblack@eecs.umich.edu
4006121Snate@binkert.org    main['GCC_VERSION'] = gcc_version
4016121Snate@binkert.org
4028980Ssteve.reinhardt@amd.com    if compareVersions(gcc_version, '4.9') >= 0:
4039396Sandreas.hansson@arm.com        # Incremental linking with LTO is currently broken in gcc versions
4045397Ssaidi@eecs.umich.edu        # 4.9 and above. A version where everything works completely hasn't
4055397Ssaidi@eecs.umich.edu        # yet been identified.
4067727SAli.Saidi@ARM.com        #
4078268Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
4086168Snate@binkert.org        main['BROKEN_INCREMENTAL_LTO'] = True
4095341Sstever@gmail.com    if compareVersions(gcc_version, '6.0') >= 0:
4108120Sgblack@eecs.umich.edu        # gcc versions 6.0 and greater accept an -flinker-output flag which
4118120Sgblack@eecs.umich.edu        # selects what type of output the linker should generate. This is
4128120Sgblack@eecs.umich.edu        # necessary for incremental lto to work, but is also broken in
4136814Sgblack@eecs.umich.edu        # current versions of gcc. It may not be necessary in future
4145863Snate@binkert.org        # versions. We add it here since it might be, and as a reminder that
4158120Sgblack@eecs.umich.edu        # it exists. It's excluded if lto is being forced.
4165341Sstever@gmail.com        #
4175863Snate@binkert.org        # https://gcc.gnu.org/gcc-6/changes.html
4188268Ssteve.reinhardt@amd.com        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
4196121Snate@binkert.org        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
4206121Snate@binkert.org        if not GetOption('force_lto'):
4218268Ssteve.reinhardt@amd.com            main.Append(PSHLINKFLAGS='-flinker-output=rel')
4225742Snate@binkert.org            main.Append(PLINKFLAGS='-flinker-output=rel')
4235742Snate@binkert.org
4245341Sstever@gmail.com    # gcc from version 4.8 and above generates "rep; ret" instructions
4255742Snate@binkert.org    # to avoid performance penalties on certain AMD chips. Older
4265742Snate@binkert.org    # assemblers detect this as an error, "Error: expecting string
4275341Sstever@gmail.com    # instruction after `rep'"
4286017Snate@binkert.org    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
4296121Snate@binkert.org                                  '-o', '/dev/null'],
4306017Snate@binkert.org                                 exception=False).split()
4317816Ssteve.reinhardt@amd.com
4327756SAli.Saidi@ARM.com    # version strings may contain extra distro-specific
4337756SAli.Saidi@ARM.com    # qualifiers, so play it safe and keep only what comes before
4347756SAli.Saidi@ARM.com    # the first hyphen
4357756SAli.Saidi@ARM.com    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
4367756SAli.Saidi@ARM.com
4377756SAli.Saidi@ARM.com    if not as_version or compareVersions(as_version, "2.23") < 0:
4387756SAli.Saidi@ARM.com        print(termcap.Yellow + termcap.Bold +
4397756SAli.Saidi@ARM.com            'Warning: This combination of gcc and binutils have' +
4407816Ssteve.reinhardt@amd.com            ' known incompatibilities.\n' +
4417816Ssteve.reinhardt@amd.com            '         If you encounter build problems, please update ' +
4427816Ssteve.reinhardt@amd.com            'binutils to 2.23.' +
4437816Ssteve.reinhardt@amd.com            termcap.Normal)
4447816Ssteve.reinhardt@amd.com
4457816Ssteve.reinhardt@amd.com    # Make sure we warn if the user has requested to compile with the
4467816Ssteve.reinhardt@amd.com    # Undefined Benahvior Sanitizer and this version of gcc does not
4477816Ssteve.reinhardt@amd.com    # support it.
4487816Ssteve.reinhardt@amd.com    if GetOption('with_ubsan') and \
4497816Ssteve.reinhardt@amd.com            compareVersions(gcc_version, '4.9') < 0:
4507756SAli.Saidi@ARM.com        print(termcap.Yellow + termcap.Bold +
4517816Ssteve.reinhardt@amd.com            'Warning: UBSan is only supported using gcc 4.9 and later.' +
4527816Ssteve.reinhardt@amd.com            termcap.Normal)
4537816Ssteve.reinhardt@amd.com
4547816Ssteve.reinhardt@amd.com    disable_lto = GetOption('no_lto')
4557816Ssteve.reinhardt@amd.com    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
4567816Ssteve.reinhardt@amd.com            not GetOption('force_lto'):
4577816Ssteve.reinhardt@amd.com        print(termcap.Yellow + termcap.Bold +
4587816Ssteve.reinhardt@amd.com            'Warning: Your compiler doesn\'t support incremental linking' +
4597816Ssteve.reinhardt@amd.com            ' and lto at the same time, so lto is being disabled. To force' +
4607816Ssteve.reinhardt@amd.com            ' lto on anyway, use the --force-lto option. That will disable' +
4617816Ssteve.reinhardt@amd.com            ' partial linking.' +
4627816Ssteve.reinhardt@amd.com            termcap.Normal)
4637816Ssteve.reinhardt@amd.com        disable_lto = True
4647816Ssteve.reinhardt@amd.com
4657816Ssteve.reinhardt@amd.com    # Add the appropriate Link-Time Optimization (LTO) flags
4667816Ssteve.reinhardt@amd.com    # unless LTO is explicitly turned off. Note that these flags
4677816Ssteve.reinhardt@amd.com    # are only used by the fast target.
4687816Ssteve.reinhardt@amd.com    if not disable_lto:
4697816Ssteve.reinhardt@amd.com        # Pass the LTO flag when compiling to produce GIMPLE
4707816Ssteve.reinhardt@amd.com        # output, we merely create the flags here and only append
4717816Ssteve.reinhardt@amd.com        # them later
4727816Ssteve.reinhardt@amd.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4737816Ssteve.reinhardt@amd.com
4747816Ssteve.reinhardt@amd.com        # Use the same amount of jobs for LTO as we are running
4757816Ssteve.reinhardt@amd.com        # scons with
4767816Ssteve.reinhardt@amd.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
4777816Ssteve.reinhardt@amd.com
4787816Ssteve.reinhardt@amd.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
4797816Ssteve.reinhardt@amd.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
4807816Ssteve.reinhardt@amd.com
4817816Ssteve.reinhardt@amd.com    # The address sanitizer is available for gcc >= 4.8
4827816Ssteve.reinhardt@amd.com    if GetOption('with_asan'):
4837816Ssteve.reinhardt@amd.com        if GetOption('with_ubsan') and \
4847816Ssteve.reinhardt@amd.com                compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4857816Ssteve.reinhardt@amd.com            main.Append(CCFLAGS=['-fsanitize=address,undefined',
4867816Ssteve.reinhardt@amd.com                                 '-fno-omit-frame-pointer'],
4877816Ssteve.reinhardt@amd.com                       LINKFLAGS='-fsanitize=address,undefined')
4887816Ssteve.reinhardt@amd.com        else:
4897816Ssteve.reinhardt@amd.com            main.Append(CCFLAGS=['-fsanitize=address',
4907816Ssteve.reinhardt@amd.com                                 '-fno-omit-frame-pointer'],
4917816Ssteve.reinhardt@amd.com                       LINKFLAGS='-fsanitize=address')
4927816Ssteve.reinhardt@amd.com    # Only gcc >= 4.9 supports UBSan, so check both the version
4937816Ssteve.reinhardt@amd.com    # and the command-line option before adding the compiler and
4947816Ssteve.reinhardt@amd.com    # linker flags.
4957816Ssteve.reinhardt@amd.com    elif GetOption('with_ubsan') and \
4967816Ssteve.reinhardt@amd.com            compareVersions(main['GCC_VERSION'], '4.9') >= 0:
4977816Ssteve.reinhardt@amd.com        main.Append(CCFLAGS='-fsanitize=undefined')
4987816Ssteve.reinhardt@amd.com        main.Append(LINKFLAGS='-fsanitize=undefined')
4997816Ssteve.reinhardt@amd.com
5007816Ssteve.reinhardt@amd.comelif main['CLANG']:
5017816Ssteve.reinhardt@amd.com    # Check for a supported version of clang, >= 3.1 is needed to
5027816Ssteve.reinhardt@amd.com    # support similar features as gcc 4.8. See
5037816Ssteve.reinhardt@amd.com    # http://clang.llvm.org/cxx_status.html for details
5047816Ssteve.reinhardt@amd.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
5057816Ssteve.reinhardt@amd.com    clang_version_match = clang_version_re.search(CXX_version)
5067816Ssteve.reinhardt@amd.com    if (clang_version_match):
5077816Ssteve.reinhardt@amd.com        clang_version = clang_version_match.groups()[0]
5087816Ssteve.reinhardt@amd.com        if compareVersions(clang_version, "3.1") < 0:
5097816Ssteve.reinhardt@amd.com            print('Error: clang version 3.1 or newer required.')
5107816Ssteve.reinhardt@amd.com            print('       Installed version:', clang_version)
5117816Ssteve.reinhardt@amd.com            Exit(1)
5128947Sandreas.hansson@arm.com    else:
5138947Sandreas.hansson@arm.com        print('Error: Unable to determine clang version.')
5147756SAli.Saidi@ARM.com        Exit(1)
5158120Sgblack@eecs.umich.edu
5167756SAli.Saidi@ARM.com    # clang has a few additional warnings that we disable, extraneous
5177756SAli.Saidi@ARM.com    # parantheses are allowed due to Ruby's printing of the AST,
5187756SAli.Saidi@ARM.com    # finally self assignments are allowed as the generated CPU code
5197756SAli.Saidi@ARM.com    # is relying on this
5207816Ssteve.reinhardt@amd.com    main.Append(CCFLAGS=['-Wno-parentheses',
5217816Ssteve.reinhardt@amd.com                         '-Wno-self-assign',
5227816Ssteve.reinhardt@amd.com                         # Some versions of libstdc++ (4.8?) seem to
5237816Ssteve.reinhardt@amd.com                         # use struct hash and class hash
5247816Ssteve.reinhardt@amd.com                         # interchangeably.
5257816Ssteve.reinhardt@amd.com                         '-Wno-mismatched-tags',
5267816Ssteve.reinhardt@amd.com                         ])
5277816Ssteve.reinhardt@amd.com
5287816Ssteve.reinhardt@amd.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5297816Ssteve.reinhardt@amd.com
5307756SAli.Saidi@ARM.com    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5317756SAli.Saidi@ARM.com    # opposed to libstdc++, as the later is dated.
5329227Sandreas.hansson@arm.com    if sys.platform == "darwin":
5339227Sandreas.hansson@arm.com        main.Append(CXXFLAGS=['-stdlib=libc++'])
5349227Sandreas.hansson@arm.com        main.Append(LIBS=['c++'])
5359227Sandreas.hansson@arm.com
5369590Sandreas@sandberg.pp.se    # On FreeBSD we need libthr.
5379590Sandreas@sandberg.pp.se    if sys.platform.startswith('freebsd'):
5389590Sandreas@sandberg.pp.se        main.Append(LIBS=['thr'])
5399590Sandreas@sandberg.pp.se
5409590Sandreas@sandberg.pp.se    # We require clang >= 3.1, so there is no need to check any
5419590Sandreas@sandberg.pp.se    # versions here.
5426654Snate@binkert.org    if GetOption('with_ubsan'):
5436654Snate@binkert.org        if GetOption('with_asan'):
5445871Snate@binkert.org            env.Append(CCFLAGS=['-fsanitize=address,undefined',
5456121Snate@binkert.org                                '-fno-omit-frame-pointer'],
5468946Sandreas.hansson@arm.com                       LINKFLAGS='-fsanitize=address,undefined')
5479419Sandreas.hansson@arm.com        else:
5483940Ssaidi@eecs.umich.edu            env.Append(CCFLAGS='-fsanitize=undefined',
5493918Ssaidi@eecs.umich.edu                       LINKFLAGS='-fsanitize=undefined')
5503918Ssaidi@eecs.umich.edu
5511858SN/A    elif GetOption('with_asan'):
5529556Sandreas.hansson@arm.com        env.Append(CCFLAGS=['-fsanitize=address',
5539556Sandreas.hansson@arm.com                            '-fno-omit-frame-pointer'],
5549556Sandreas.hansson@arm.com                   LINKFLAGS='-fsanitize=address')
5559556Sandreas.hansson@arm.com
5569556Sandreas.hansson@arm.comelse:
5579556Sandreas.hansson@arm.com    print(termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal, end=' ')
5589556Sandreas.hansson@arm.com    print("Don't know what compiler options to use for your compiler.")
5599556Sandreas.hansson@arm.com    print(termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX'])
5609556Sandreas.hansson@arm.com    print(termcap.Yellow + '       version:' + termcap.Normal, end=' ')
5619556Sandreas.hansson@arm.com    if not CXX_version:
5629556Sandreas.hansson@arm.com        print(termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +
5639556Sandreas.hansson@arm.com              termcap.Normal)
5649556Sandreas.hansson@arm.com    else:
5659556Sandreas.hansson@arm.com        print(CXX_version.replace('\n', '<nl>'))
5669556Sandreas.hansson@arm.com    print("       If you're trying to use a compiler other than GCC")
5679556Sandreas.hansson@arm.com    print("       or clang, there appears to be something wrong with your")
5689556Sandreas.hansson@arm.com    print("       environment.")
5699556Sandreas.hansson@arm.com    print("       ")
5709556Sandreas.hansson@arm.com    print("       If you are trying to use a compiler other than those listed")
5719556Sandreas.hansson@arm.com    print("       above you will need to ease fix SConstruct and ")
5729556Sandreas.hansson@arm.com    print("       src/SConscript to support that compiler.")
5739556Sandreas.hansson@arm.com    Exit(1)
5749556Sandreas.hansson@arm.com
5759556Sandreas.hansson@arm.com# Set up common yacc/bison flags (needed for Ruby)
5769556Sandreas.hansson@arm.commain['YACCFLAGS'] = '-d'
5779556Sandreas.hansson@arm.commain['YACCHXXFILESUFFIX'] = '.hh'
5789556Sandreas.hansson@arm.com
5799556Sandreas.hansson@arm.com# Do this after we save setting back, or else we'll tack on an
5809556Sandreas.hansson@arm.com# extra 'qdo' every time we run scons.
5819556Sandreas.hansson@arm.comif main['BATCH']:
5829556Sandreas.hansson@arm.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
5839556Sandreas.hansson@arm.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
5846121Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
58510238Sandreas.hansson@arm.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
58610238Sandreas.hansson@arm.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
58710238Sandreas.hansson@arm.com
58810238Sandreas.hansson@arm.comif sys.platform == 'cygwin':
5899420Sandreas.hansson@arm.com    # cygwin has some header file issues...
59010238Sandreas.hansson@arm.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
59110238Sandreas.hansson@arm.com
5929420Sandreas.hansson@arm.com# Check for the protobuf compiler
5939420Sandreas.hansson@arm.comprotoc_version = readCommand([main['PROTOC'], '--version'],
5949420Sandreas.hansson@arm.com                             exception='').split()
5959420Sandreas.hansson@arm.com
5969420Sandreas.hansson@arm.com# First two words should be "libprotoc x.y.z"
59710264Sandreas.hansson@arm.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
59810264Sandreas.hansson@arm.com    print(termcap.Yellow + termcap.Bold +
59910264Sandreas.hansson@arm.com        'Warning: Protocol buffer compiler (protoc) not found.\n' +
60010264Sandreas.hansson@arm.com        '         Please install protobuf-compiler for tracing support.' +
60110264Sandreas.hansson@arm.com        termcap.Normal)
60210264Sandreas.hansson@arm.com    main['PROTOC'] = False
60310264Sandreas.hansson@arm.comelse:
60410264Sandreas.hansson@arm.com    # Based on the availability of the compress stream wrappers,
60510264Sandreas.hansson@arm.com    # require 2.1.0
60610264Sandreas.hansson@arm.com    min_protoc_version = '2.1.0'
60710264Sandreas.hansson@arm.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
60810264Sandreas.hansson@arm.com        print(termcap.Yellow + termcap.Bold +
60910264Sandreas.hansson@arm.com            'Warning: protoc version', min_protoc_version,
61010264Sandreas.hansson@arm.com            'or newer required.\n' +
61110264Sandreas.hansson@arm.com            '         Installed version:', protoc_version[1],
61210264Sandreas.hansson@arm.com            termcap.Normal)
61310457Sandreas.hansson@arm.com        main['PROTOC'] = False
61410457Sandreas.hansson@arm.com    else:
61510457Sandreas.hansson@arm.com        # Attempt to determine the appropriate include path and
61610457Sandreas.hansson@arm.com        # library path using pkg-config, that means we also need to
61710457Sandreas.hansson@arm.com        # check for pkg-config. Note that it is possible to use
61810457Sandreas.hansson@arm.com        # protobuf without the involvement of pkg-config. Later on we
61910457Sandreas.hansson@arm.com        # check go a library config check and at that point the test
62010457Sandreas.hansson@arm.com        # will fail if libprotobuf cannot be found.
62110457Sandreas.hansson@arm.com        if readCommand(['pkg-config', '--version'], exception=''):
62210238Sandreas.hansson@arm.com            try:
62310238Sandreas.hansson@arm.com                # Attempt to establish what linking flags to add for protobuf
62410238Sandreas.hansson@arm.com                # using pkg-config
62510238Sandreas.hansson@arm.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
62610238Sandreas.hansson@arm.com            except:
62710238Sandreas.hansson@arm.com                print(termcap.Yellow + termcap.Bold +
62810416Sandreas.hansson@arm.com                    'Warning: pkg-config could not get protobuf flags.' +
62910238Sandreas.hansson@arm.com                    termcap.Normal)
6309227Sandreas.hansson@arm.com
63110238Sandreas.hansson@arm.com
63210416Sandreas.hansson@arm.com# Check for 'timeout' from GNU coreutils. If present, regressions will
63310416Sandreas.hansson@arm.com# be run with a time limit. We require version 8.13 since we rely on
6349227Sandreas.hansson@arm.com# support for the '--foreground' option.
6359590Sandreas@sandberg.pp.seif sys.platform.startswith('freebsd'):
6369590Sandreas@sandberg.pp.se    timeout_lines = readCommand(['gtimeout', '--version'],
6379590Sandreas@sandberg.pp.se                                exception='').splitlines()
6388737Skoansin.tan@gmail.comelse:
63910238Sandreas.hansson@arm.com    timeout_lines = readCommand(['timeout', '--version'],
64010238Sandreas.hansson@arm.com                                exception='').splitlines()
6419420Sandreas.hansson@arm.com# Get the first line and tokenize it
6428737Skoansin.tan@gmail.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
64310106SMitch.Hayenga@arm.commain['TIMEOUT'] =  timeout_version and \
6448737Skoansin.tan@gmail.com    compareVersions(timeout_version[-1], '8.13') >= 0
6458737Skoansin.tan@gmail.com
64610238Sandreas.hansson@arm.com# Add a custom Check function to test for structure members.
64710238Sandreas.hansson@arm.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
6488737Skoansin.tan@gmail.com    context.Message("Checking for member %s in %s..." %
6498737Skoansin.tan@gmail.com                    (member, decl))
6508737Skoansin.tan@gmail.com    text = """
6518737Skoansin.tan@gmail.com#include %(header)s
6528737Skoansin.tan@gmail.comint main(){
6538737Skoansin.tan@gmail.com  %(decl)s test;
6549556Sandreas.hansson@arm.com  (void)test.%(member)s;
6559556Sandreas.hansson@arm.com  return 0;
6569556Sandreas.hansson@arm.com};
6579556Sandreas.hansson@arm.com""" % { "header" : include_quotes[0] + include + include_quotes[1],
6589556Sandreas.hansson@arm.com        "decl" : decl,
6599556Sandreas.hansson@arm.com        "member" : member,
6609556Sandreas.hansson@arm.com        }
6619556Sandreas.hansson@arm.com
66210278SAndreas.Sandberg@ARM.com    ret = context.TryCompile(text, extension=".cc")
66310278SAndreas.Sandberg@ARM.com    context.Result(ret)
66410278SAndreas.Sandberg@ARM.com    return ret
66510278SAndreas.Sandberg@ARM.com
66610278SAndreas.Sandberg@ARM.com# Platform-specific configuration.  Note again that we assume that all
66710278SAndreas.Sandberg@ARM.com# builds under a given build root run on the same host platform.
6689556Sandreas.hansson@arm.comconf = Configure(main,
6699590Sandreas@sandberg.pp.se                 conf_dir = joinpath(build_root, '.scons_config'),
6709590Sandreas@sandberg.pp.se                 log_file = joinpath(build_root, 'scons_config.log'),
6719420Sandreas.hansson@arm.com                 custom_tests = {
6729846Sandreas.hansson@arm.com        'CheckMember' : CheckMember,
6739846Sandreas.hansson@arm.com        })
6749846Sandreas.hansson@arm.com
6759846Sandreas.hansson@arm.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
6768946Sandreas.hansson@arm.comtry:
6773918Ssaidi@eecs.umich.edu    import platform
6789068SAli.Saidi@ARM.com    uname = platform.uname()
6799068SAli.Saidi@ARM.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
6809068SAli.Saidi@ARM.com        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
6819068SAli.Saidi@ARM.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
6829068SAli.Saidi@ARM.com            main.Append(CFLAGS=['-arch', 'x86_64'])
6839068SAli.Saidi@ARM.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
6849068SAli.Saidi@ARM.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
6859068SAli.Saidi@ARM.comexcept:
6869068SAli.Saidi@ARM.com    pass
6879419Sandreas.hansson@arm.com
6889068SAli.Saidi@ARM.com# Recent versions of scons substitute a "Null" object for Configure()
6899068SAli.Saidi@ARM.com# when configuration isn't necessary, e.g., if the "--help" option is
6909068SAli.Saidi@ARM.com# present.  Unfortuantely this Null object always returns false,
6919068SAli.Saidi@ARM.com# breaking all our configuration checks.  We replace it with our own
6929068SAli.Saidi@ARM.com# more optimistic null object that returns True instead.
6939068SAli.Saidi@ARM.comif not conf:
6943918Ssaidi@eecs.umich.edu    def NullCheck(*args, **kwargs):
6953918Ssaidi@eecs.umich.edu        return True
6966157Snate@binkert.org
6976157Snate@binkert.org    class NullConf:
6986157Snate@binkert.org        def __init__(self, env):
6996157Snate@binkert.org            self.env = env
7005397Ssaidi@eecs.umich.edu        def Finish(self):
7015397Ssaidi@eecs.umich.edu            return self.env
7026121Snate@binkert.org        def __getattr__(self, mname):
7036121Snate@binkert.org            return NullCheck
7046121Snate@binkert.org
7056121Snate@binkert.org    conf = NullConf(main)
7066121Snate@binkert.org
7076121Snate@binkert.org# Cache build files in the supplied directory.
7085397Ssaidi@eecs.umich.eduif main['M5_BUILD_CACHE']:
7091851SN/A    print('Using build cache located at', main['M5_BUILD_CACHE'])
7101851SN/A    CacheDir(main['M5_BUILD_CACHE'])
7117739Sgblack@eecs.umich.edu
712955SN/Amain['USE_PYTHON'] = not GetOption('without_python')
7139396Sandreas.hansson@arm.comif main['USE_PYTHON']:
7149396Sandreas.hansson@arm.com    # Find Python include and library directories for embedding the
7159396Sandreas.hansson@arm.com    # interpreter. We rely on python-config to resolve the appropriate
7169396Sandreas.hansson@arm.com    # includes and linker flags. ParseConfig does not seem to understand
7179396Sandreas.hansson@arm.com    # the more exotic linker flags such as -Xlinker and -export-dynamic so
7189396Sandreas.hansson@arm.com    # we add them explicitly below. If you want to link in an alternate
7199396Sandreas.hansson@arm.com    # version of python, see above for instructions on how to invoke
7209396Sandreas.hansson@arm.com    # scons with the appropriate PATH set.
7219396Sandreas.hansson@arm.com    #
7229396Sandreas.hansson@arm.com    # First we check if python2-config exists, else we use python-config
7239396Sandreas.hansson@arm.com    python_config = readCommand(['which', 'python2-config'],
7249396Sandreas.hansson@arm.com                                exception='').strip()
7259396Sandreas.hansson@arm.com    if not os.path.exists(python_config):
7269396Sandreas.hansson@arm.com        python_config = readCommand(['which', 'python-config'],
7279396Sandreas.hansson@arm.com                                    exception='').strip()
7289396Sandreas.hansson@arm.com    py_includes = readCommand([python_config, '--includes'],
7299477Sandreas.hansson@arm.com                              exception='').split()
7309477Sandreas.hansson@arm.com    # Strip the -I from the include folders before adding them to the
7319477Sandreas.hansson@arm.com    # CPPPATH
7329477Sandreas.hansson@arm.com    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
7339477Sandreas.hansson@arm.com
7349477Sandreas.hansson@arm.com    # Read the linker flags and split them into libraries and other link
7359477Sandreas.hansson@arm.com    # flags. The libraries are added later through the call the CheckLib.
7369477Sandreas.hansson@arm.com    py_ld_flags = readCommand([python_config, '--ldflags'],
7379477Sandreas.hansson@arm.com        exception='').split()
7389477Sandreas.hansson@arm.com    py_libs = []
7399477Sandreas.hansson@arm.com    for lib in py_ld_flags:
7409477Sandreas.hansson@arm.com         if not lib.startswith('-l'):
7419477Sandreas.hansson@arm.com             main.Append(LINKFLAGS=[lib])
7429477Sandreas.hansson@arm.com         else:
7439477Sandreas.hansson@arm.com             lib = lib[2:]
7449477Sandreas.hansson@arm.com             if lib not in py_libs:
7459477Sandreas.hansson@arm.com                 py_libs.append(lib)
7469477Sandreas.hansson@arm.com
7479477Sandreas.hansson@arm.com    # verify that this stuff works
7489477Sandreas.hansson@arm.com    if not conf.CheckHeader('Python.h', '<>'):
7499477Sandreas.hansson@arm.com        print("Error: Check failed for Python.h header in", py_includes)
7509477Sandreas.hansson@arm.com        print("Two possible reasons:")
7519396Sandreas.hansson@arm.com        print("1. Python headers are not installed (You can install the "
7523053Sstever@eecs.umich.edu              "package python-dev on Ubuntu and RedHat)")
7536121Snate@binkert.org        print("2. SCons is using a wrong C compiler. This can happen if "
7543053Sstever@eecs.umich.edu              "CC has the wrong value.")
7553053Sstever@eecs.umich.edu        print("CC = %s" % main['CC'])
7563053Sstever@eecs.umich.edu        Exit(1)
7573053Sstever@eecs.umich.edu
7583053Sstever@eecs.umich.edu    for lib in py_libs:
7599072Sandreas.hansson@arm.com        if not conf.CheckLib(lib):
7603053Sstever@eecs.umich.edu            print("Error: can't find library %s required by python" % lib)
7614742Sstever@eecs.umich.edu            Exit(1)
7624742Sstever@eecs.umich.edu
7633053Sstever@eecs.umich.edu# On Solaris you need to use libsocket for socket ops
7643053Sstever@eecs.umich.eduif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
7653053Sstever@eecs.umich.edu   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
76610181SCurtis.Dunham@arm.com       print("Can't find library with socket calls (e.g. accept())")
7676654Snate@binkert.org       Exit(1)
7683053Sstever@eecs.umich.edu
7693053Sstever@eecs.umich.edu# Check for zlib.  If the check passes, libz will be automatically
7703053Sstever@eecs.umich.edu# added to the LIBS environment variable.
7713053Sstever@eecs.umich.eduif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
77210425Sandreas.hansson@arm.com    print('Error: did not find needed zlib compression library '
77310425Sandreas.hansson@arm.com          'and/or zlib.h header file.')
77410425Sandreas.hansson@arm.com    print('       Please install zlib and try again.')
77510425Sandreas.hansson@arm.com    Exit(1)
77610425Sandreas.hansson@arm.com
77710425Sandreas.hansson@arm.com# If we have the protobuf compiler, also make sure we have the
77810425Sandreas.hansson@arm.com# development libraries. If the check passes, libprotobuf will be
77910425Sandreas.hansson@arm.com# automatically added to the LIBS environment variable. After
78010425Sandreas.hansson@arm.com# this, we can use the HAVE_PROTOBUF flag to determine if we have
78110425Sandreas.hansson@arm.com# got both protoc and libprotobuf available.
78210425Sandreas.hansson@arm.commain['HAVE_PROTOBUF'] = main['PROTOC'] and \
7832667Sstever@eecs.umich.edu    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
7844554Sbinkertn@umich.edu                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
7856121Snate@binkert.org
7862667Sstever@eecs.umich.edu# If we have the compiler but not the library, print another warning.
78710710Sandreas.hansson@arm.comif main['PROTOC'] and not main['HAVE_PROTOBUF']:
78810710Sandreas.hansson@arm.com    print(termcap.Yellow + termcap.Bold +
78910710Sandreas.hansson@arm.com        'Warning: did not find protocol buffer library and/or headers.\n' +
79010710Sandreas.hansson@arm.com    '       Please install libprotobuf-dev for tracing support.' +
79110710Sandreas.hansson@arm.com    termcap.Normal)
79210710Sandreas.hansson@arm.com
79310710Sandreas.hansson@arm.com# Check for librt.
79410710Sandreas.hansson@arm.comhave_posix_clock = \
79510710Sandreas.hansson@arm.com    conf.CheckLibWithHeader(None, 'time.h', 'C',
79610384SCurtis.Dunham@arm.com                            'clock_nanosleep(0,0,NULL,NULL);') or \
7974554Sbinkertn@umich.edu    conf.CheckLibWithHeader('rt', 'time.h', 'C',
7984554Sbinkertn@umich.edu                            'clock_nanosleep(0,0,NULL,NULL);')
7994554Sbinkertn@umich.edu
8006121Snate@binkert.orghave_posix_timers = \
8014554Sbinkertn@umich.edu    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
8024554Sbinkertn@umich.edu                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
8034554Sbinkertn@umich.edu
8044781Snate@binkert.orgif not GetOption('without_tcmalloc'):
8054554Sbinkertn@umich.edu    if conf.CheckLib('tcmalloc'):
8064554Sbinkertn@umich.edu        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
8072667Sstever@eecs.umich.edu    elif conf.CheckLib('tcmalloc_minimal'):
8084554Sbinkertn@umich.edu        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
8094554Sbinkertn@umich.edu    else:
8104554Sbinkertn@umich.edu        print(termcap.Yellow + termcap.Bold +
8114554Sbinkertn@umich.edu              "You can get a 12% performance improvement by "
8122667Sstever@eecs.umich.edu              "installing tcmalloc (libgoogle-perftools-dev package "
8134554Sbinkertn@umich.edu              "on Ubuntu or RedHat)." + termcap.Normal)
8142667Sstever@eecs.umich.edu
8154554Sbinkertn@umich.edu
8166121Snate@binkert.org# Detect back trace implementations. The last implementation in the
8172667Sstever@eecs.umich.edu# list will be used by default.
8185522Snate@binkert.orgbacktrace_impls = [ "none" ]
8195522Snate@binkert.org
8205522Snate@binkert.orgbacktrace_checker = 'char temp;' + \
8215522Snate@binkert.org    ' backtrace_symbols_fd((void*)&temp, 0, 0);'
8225522Snate@binkert.orgif conf.CheckLibWithHeader(None, 'execinfo.h', 'C', backtrace_checker):
8235522Snate@binkert.org    backtrace_impls.append("glibc")
8245522Snate@binkert.orgelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
8255522Snate@binkert.org                             backtrace_checker):
8265522Snate@binkert.org    # NetBSD and FreeBSD need libexecinfo.
8275522Snate@binkert.org    backtrace_impls.append("glibc")
8285522Snate@binkert.org    main.Append(LIBS=['execinfo'])
8295522Snate@binkert.org
8305522Snate@binkert.orgif backtrace_impls[-1] == "none":
8315522Snate@binkert.org    default_backtrace_impl = "none"
8325522Snate@binkert.org    print(termcap.Yellow + termcap.Bold +
8335522Snate@binkert.org        "No suitable back trace implementation found." +
8345522Snate@binkert.org        termcap.Normal)
8355522Snate@binkert.org
8365522Snate@binkert.orgif not have_posix_clock:
8375522Snate@binkert.org    print("Can't find library for POSIX clocks.")
8385522Snate@binkert.org
8395522Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
8405522Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
8415522Snate@binkert.orgif not have_fenv:
8425522Snate@binkert.org    print("Warning: Header file <fenv.h> not found.")
8435522Snate@binkert.org    print("         This host has no IEEE FP rounding mode control.")
8449986Sandreas@sandberg.pp.se
8459986Sandreas@sandberg.pp.se# Check for <png.h> (libpng library needed if wanting to dump
8469986Sandreas@sandberg.pp.se# frame buffer image in png format)
8479986Sandreas@sandberg.pp.sehave_png = conf.CheckHeader('png.h', '<>')
8489986Sandreas@sandberg.pp.seif not have_png:
8499986Sandreas@sandberg.pp.se    print("Warning: Header file <png.h> not found.")
8509986Sandreas@sandberg.pp.se    print("         This host has no libpng library.")
8519986Sandreas@sandberg.pp.se    print("         Disabling support for PNG framebuffers.")
8529986Sandreas@sandberg.pp.se
8539986Sandreas@sandberg.pp.se# Check if we should enable KVM-based hardware virtualization. The API
8549986Sandreas@sandberg.pp.se# we rely on exists since version 2.6.36 of the kernel, but somehow
8559986Sandreas@sandberg.pp.se# the KVM_API_VERSION does not reflect the change. We test for one of
8569986Sandreas@sandberg.pp.se# the types as a fall back.
8579986Sandreas@sandberg.pp.sehave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
8589986Sandreas@sandberg.pp.seif not have_kvm:
8599986Sandreas@sandberg.pp.se    print("Info: Compatible header file <linux/kvm.h> not found, "
8609986Sandreas@sandberg.pp.se          "disabling KVM support.")
8619986Sandreas@sandberg.pp.se
8629986Sandreas@sandberg.pp.se# Check if the TUN/TAP driver is available.
8639986Sandreas@sandberg.pp.sehave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
8642638Sstever@eecs.umich.eduif not have_tuntap:
8652638Sstever@eecs.umich.edu    print("Info: Compatible header file <linux/if_tun.h> not found.")
8666121Snate@binkert.org
8673716Sstever@eecs.umich.edu# x86 needs support for xsave. We test for the structure here since we
8685522Snate@binkert.org# won't be able to run new tests by the time we know which ISA we're
8699986Sandreas@sandberg.pp.se# targeting.
8709986Sandreas@sandberg.pp.sehave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
8719986Sandreas@sandberg.pp.se                                    '#include <linux/kvm.h>') != 0
8729986Sandreas@sandberg.pp.se
8735522Snate@binkert.org# Check if the requested target ISA is compatible with the host
8745522Snate@binkert.orgdef is_isa_kvm_compatible(isa):
8755522Snate@binkert.org    try:
8765522Snate@binkert.org        import platform
8771858SN/A        host_isa = platform.machine()
8785227Ssaidi@eecs.umich.edu    except:
8795227Ssaidi@eecs.umich.edu        print("Warning: Failed to determine host ISA.")
8805227Ssaidi@eecs.umich.edu        return False
8815227Ssaidi@eecs.umich.edu
8826654Snate@binkert.org    if not have_posix_timers:
8836654Snate@binkert.org        print("Warning: Can not enable KVM, host seems to lack support "
8847769SAli.Saidi@ARM.com              "for POSIX timers")
8857769SAli.Saidi@ARM.com        return False
8867769SAli.Saidi@ARM.com
8877769SAli.Saidi@ARM.com    if isa == "arm":
8885227Ssaidi@eecs.umich.edu        return host_isa in ( "armv7l", "aarch64" )
8895227Ssaidi@eecs.umich.edu    elif isa == "x86":
8905227Ssaidi@eecs.umich.edu        if host_isa != "x86_64":
8915204Sstever@gmail.com            return False
8925204Sstever@gmail.com
8935204Sstever@gmail.com        if not have_kvm_xsave:
8945204Sstever@gmail.com            print("KVM on x86 requires xsave support in kernel headers.")
8955204Sstever@gmail.com            return False
8965204Sstever@gmail.com
8975204Sstever@gmail.com        return True
8985204Sstever@gmail.com    else:
8995204Sstever@gmail.com        return False
9005204Sstever@gmail.com
9015204Sstever@gmail.com
9025204Sstever@gmail.com# Check if the exclude_host attribute is available. We want this to
9035204Sstever@gmail.com# get accurate instruction counts in KVM.
9045204Sstever@gmail.commain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
9055204Sstever@gmail.com    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
9065204Sstever@gmail.com
9075204Sstever@gmail.com
9086121Snate@binkert.org######################################################################
9095204Sstever@gmail.com#
9107727SAli.Saidi@ARM.com# Finish the configuration
9117727SAli.Saidi@ARM.com#
9127727SAli.Saidi@ARM.commain = conf.Finish()
9137727SAli.Saidi@ARM.com
9147727SAli.Saidi@ARM.com######################################################################
91510453SAndrew.Bardsley@arm.com#
91610453SAndrew.Bardsley@arm.com# Collect all non-global variables
91710453SAndrew.Bardsley@arm.com#
91810453SAndrew.Bardsley@arm.com
91910453SAndrew.Bardsley@arm.com# Define the universe of supported ISAs
92010453SAndrew.Bardsley@arm.comall_isa_list = [ ]
92110453SAndrew.Bardsley@arm.comall_gpu_isa_list = [ ]
92210453SAndrew.Bardsley@arm.comExport('all_isa_list')
92310453SAndrew.Bardsley@arm.comExport('all_gpu_isa_list')
92410453SAndrew.Bardsley@arm.com
92510453SAndrew.Bardsley@arm.comclass CpuModel(object):
92610160Sandreas.hansson@arm.com    '''The CpuModel class encapsulates everything the ISA parser needs to
92710453SAndrew.Bardsley@arm.com    know about a particular CPU model.'''
92810453SAndrew.Bardsley@arm.com
92910453SAndrew.Bardsley@arm.com    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
93010453SAndrew.Bardsley@arm.com    dict = {}
93110453SAndrew.Bardsley@arm.com
93210453SAndrew.Bardsley@arm.com    # Constructor.  Automatically adds models to CpuModel.dict.
93310453SAndrew.Bardsley@arm.com    def __init__(self, name, default=False):
93410453SAndrew.Bardsley@arm.com        self.name = name           # name of model
9359812Sandreas.hansson@arm.com
93610453SAndrew.Bardsley@arm.com        # This cpu is enabled by default
93710453SAndrew.Bardsley@arm.com        self.default = default
93810453SAndrew.Bardsley@arm.com
93910453SAndrew.Bardsley@arm.com        # Add self to dict
94010453SAndrew.Bardsley@arm.com        if name in CpuModel.dict:
94110453SAndrew.Bardsley@arm.com            raise AttributeError, "CpuModel '%s' already registered" % name
94210453SAndrew.Bardsley@arm.com        CpuModel.dict[name] = self
94310453SAndrew.Bardsley@arm.com
94410453SAndrew.Bardsley@arm.comExport('CpuModel')
94510453SAndrew.Bardsley@arm.com
94610453SAndrew.Bardsley@arm.com# Sticky variables get saved in the variables file so they persist from
94710453SAndrew.Bardsley@arm.com# one invocation to the next (unless overridden, in which case the new
9487727SAli.Saidi@ARM.com# value becomes sticky).
94910453SAndrew.Bardsley@arm.comsticky_vars = Variables(args=ARGUMENTS)
95010453SAndrew.Bardsley@arm.comExport('sticky_vars')
95110453SAndrew.Bardsley@arm.com
95210453SAndrew.Bardsley@arm.com# Sticky variables that should be exported
95310453SAndrew.Bardsley@arm.comexport_vars = []
9543118Sstever@eecs.umich.eduExport('export_vars')
95510453SAndrew.Bardsley@arm.com
95610453SAndrew.Bardsley@arm.com# For Ruby
95710453SAndrew.Bardsley@arm.comall_protocols = []
95810453SAndrew.Bardsley@arm.comExport('all_protocols')
9593118Sstever@eecs.umich.eduprotocol_dirs = []
9603483Ssaidi@eecs.umich.eduExport('protocol_dirs')
9613494Ssaidi@eecs.umich.eduslicc_includes = []
9623494Ssaidi@eecs.umich.eduExport('slicc_includes')
9633483Ssaidi@eecs.umich.edu
9643483Ssaidi@eecs.umich.edu# Walk the tree and execute all SConsopts scripts that wil add to the
9653483Ssaidi@eecs.umich.edu# above variables
9663053Sstever@eecs.umich.eduif GetOption('verbose'):
9673053Sstever@eecs.umich.edu    print("Reading SConsopts")
9683918Ssaidi@eecs.umich.edufor bdir in [ base_dir ] + extras_dir_list:
9693053Sstever@eecs.umich.edu    if not isdir(bdir):
9703053Sstever@eecs.umich.edu        print("Error: directory '%s' does not exist" % bdir)
9713053Sstever@eecs.umich.edu        Exit(1)
9723053Sstever@eecs.umich.edu    for root, dirs, files in os.walk(bdir):
9733053Sstever@eecs.umich.edu        if 'SConsopts' in files:
9749396Sandreas.hansson@arm.com            if GetOption('verbose'):
9759396Sandreas.hansson@arm.com                print("Reading", joinpath(root, 'SConsopts'))
9769396Sandreas.hansson@arm.com            SConscript(joinpath(root, 'SConsopts'))
9779396Sandreas.hansson@arm.com
9789396Sandreas.hansson@arm.comall_isa_list.sort()
9799396Sandreas.hansson@arm.comall_gpu_isa_list.sort()
9809396Sandreas.hansson@arm.com
9819396Sandreas.hansson@arm.comsticky_vars.AddVariables(
9829396Sandreas.hansson@arm.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
9839477Sandreas.hansson@arm.com    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
9849396Sandreas.hansson@arm.com    ListVariable('CPU_MODELS', 'CPU models',
9859477Sandreas.hansson@arm.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
9869477Sandreas.hansson@arm.com                 sorted(CpuModel.dict.keys())),
9879477Sandreas.hansson@arm.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
9889477Sandreas.hansson@arm.com                 False),
9899396Sandreas.hansson@arm.com    BoolVariable('SS_COMPATIBLE_FP',
9907840Snate@binkert.org                 'Make floating-point results compatible with SimpleScalar',
9917865Sgblack@eecs.umich.edu                 False),
9927865Sgblack@eecs.umich.edu    BoolVariable('USE_SSE2',
9937865Sgblack@eecs.umich.edu                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
9947865Sgblack@eecs.umich.edu                 False),
9957865Sgblack@eecs.umich.edu    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
9967840Snate@binkert.org    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
9979900Sandreas@sandberg.pp.se    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
9989900Sandreas@sandberg.pp.se    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
9999900Sandreas@sandberg.pp.se                 False),
10009900Sandreas@sandberg.pp.se    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
100110456SCurtis.Dunham@arm.com                 have_kvm),
100210456SCurtis.Dunham@arm.com    BoolVariable('USE_TUNTAP',
100310456SCurtis.Dunham@arm.com                 'Enable using a tap device to bridge to the host network',
100410456SCurtis.Dunham@arm.com                 have_tuntap),
100510456SCurtis.Dunham@arm.com    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
100610456SCurtis.Dunham@arm.com    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
100710456SCurtis.Dunham@arm.com                  all_protocols),
100810456SCurtis.Dunham@arm.com    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
100910456SCurtis.Dunham@arm.com                 backtrace_impls[-1], backtrace_impls)
101010456SCurtis.Dunham@arm.com    )
10119045SAli.Saidi@ARM.com
10127840Snate@binkert.org# These variables get exported to #defines in config/*.hh (see src/SConscript).
10137840Snate@binkert.orgexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
10147840Snate@binkert.org                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
10151858SN/A                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST',
10161858SN/A                'USE_PNG']
10171858SN/A
10181858SN/A###################################################
10191858SN/A#
10201858SN/A# Define a SCons builder for configuration flag headers.
10219903Sandreas.hansson@arm.com#
10229903Sandreas.hansson@arm.com###################################################
10239903Sandreas.hansson@arm.com
10249903Sandreas.hansson@arm.com# This function generates a config header file that #defines the
102510841Sandreas.sandberg@arm.com# variable symbol to the current variable setting (0 or 1).  The source
10269651SAndreas.Sandberg@ARM.com# operands are the name of the variable and a Value node containing the
10279903Sandreas.hansson@arm.com# value of the variable.
10289651SAndreas.Sandberg@ARM.comdef build_config_file(target, source, env):
10299651SAndreas.Sandberg@ARM.com    (variable, value) = [s.get_contents() for s in source]
103010841Sandreas.sandberg@arm.com    f = file(str(target[0]), 'w')
103110841Sandreas.sandberg@arm.com    print('#define', variable, value, file=f)
103210841Sandreas.sandberg@arm.com    f.close()
103310841Sandreas.sandberg@arm.com    return None
103410841Sandreas.sandberg@arm.com
103510841Sandreas.sandberg@arm.com# Combine the two functions into a scons Action object.
10369651SAndreas.Sandberg@ARM.comconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
10379651SAndreas.Sandberg@ARM.com
10389651SAndreas.Sandberg@ARM.com# The emitter munges the source & target node lists to reflect what
10399651SAndreas.Sandberg@ARM.com# we're really doing.
10409651SAndreas.Sandberg@ARM.comdef config_emitter(target, source, env):
10419651SAndreas.Sandberg@ARM.com    # extract variable name from Builder arg
10429651SAndreas.Sandberg@ARM.com    variable = str(target[0])
10439651SAndreas.Sandberg@ARM.com    # True target is config header file
10449651SAndreas.Sandberg@ARM.com    target = joinpath('config', variable.lower() + '.hh')
104510841Sandreas.sandberg@arm.com    val = env[variable]
104610841Sandreas.sandberg@arm.com    if isinstance(val, bool):
104710841Sandreas.sandberg@arm.com        # Force value to 0/1
104810841Sandreas.sandberg@arm.com        val = int(val)
104910841Sandreas.sandberg@arm.com    elif isinstance(val, str):
105010841Sandreas.sandberg@arm.com        val = '"' + val + '"'
105110860Sandreas.sandberg@arm.com
105210841Sandreas.sandberg@arm.com    # Sources are variable name & value (packaged in SCons Value nodes)
105310841Sandreas.sandberg@arm.com    return ([target], [Value(variable), Value(val)])
105410841Sandreas.sandberg@arm.com
105510841Sandreas.sandberg@arm.comconfig_builder = Builder(emitter = config_emitter, action = config_action)
105610841Sandreas.sandberg@arm.com
105710841Sandreas.sandberg@arm.commain.Append(BUILDERS = { 'ConfigFile' : config_builder })
105810841Sandreas.sandberg@arm.com
105910841Sandreas.sandberg@arm.com###################################################
106010841Sandreas.sandberg@arm.com#
106110841Sandreas.sandberg@arm.com# Builders for static and shared partially linked object files.
106210841Sandreas.sandberg@arm.com#
10639651SAndreas.Sandberg@ARM.com###################################################
10649651SAndreas.Sandberg@ARM.com
10659986Sandreas@sandberg.pp.separtial_static_builder = Builder(action=SCons.Defaults.LinkAction,
10669986Sandreas@sandberg.pp.se                                 src_suffix='$OBJSUFFIX',
10679986Sandreas@sandberg.pp.se                                 src_builder=['StaticObject', 'Object'],
10689986Sandreas@sandberg.pp.se                                 LINKFLAGS='$PLINKFLAGS',
10699986Sandreas@sandberg.pp.se                                 LIBS='')
10709986Sandreas@sandberg.pp.se
10715863Snate@binkert.orgdef partial_shared_emitter(target, source, env):
10725863Snate@binkert.org    for tgt in target:
10735863Snate@binkert.org        tgt.attributes.shared = 1
10745863Snate@binkert.org    return (target, source)
10756121Snate@binkert.orgpartial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
10761858SN/A                                 emitter=partial_shared_emitter,
10775863Snate@binkert.org                                 src_suffix='$SHOBJSUFFIX',
10785863Snate@binkert.org                                 src_builder='SharedObject',
10795863Snate@binkert.org                                 SHLINKFLAGS='$PSHLINKFLAGS',
10805863Snate@binkert.org                                 LIBS='')
10815863Snate@binkert.org
10822139SN/Amain.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
10834202Sbinkertn@umich.edu                         'PartialStatic' : partial_static_builder })
10844202Sbinkertn@umich.edu
10852139SN/A# builds in ext are shared across all configs in the build root.
10866994Snate@binkert.orgext_dir = abspath(joinpath(str(main.root), 'ext'))
10876994Snate@binkert.orgext_build_dirs = []
10886994Snate@binkert.orgfor root, dirs, files in os.walk(ext_dir):
10896994Snate@binkert.org    if 'SConscript' in files:
10906994Snate@binkert.org        build_dir = os.path.relpath(root, ext_dir)
10916994Snate@binkert.org        ext_build_dirs.append(build_dir)
10926994Snate@binkert.org        main.SConscript(joinpath(root, 'SConscript'),
10936994Snate@binkert.org                        variant_dir=joinpath(build_root, build_dir))
109410319SAndreas.Sandberg@ARM.com
10956994Snate@binkert.orgmain.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
10966994Snate@binkert.org
10976994Snate@binkert.org###################################################
10986994Snate@binkert.org#
10996994Snate@binkert.org# This builder and wrapper method are used to set up a directory with
11006994Snate@binkert.org# switching headers. Those are headers which are in a generic location and
11016994Snate@binkert.org# that include more specific headers from a directory chosen at build time
11026994Snate@binkert.org# based on the current build settings.
11036994Snate@binkert.org#
11046994Snate@binkert.org###################################################
11056994Snate@binkert.org
11062155SN/Adef build_switching_header(target, source, env):
11075863Snate@binkert.org    path = str(target[0])
11081869SN/A    subdir = str(source[0])
11091869SN/A    dp, fp = os.path.split(path)
11105863Snate@binkert.org    dp = os.path.relpath(os.path.realpath(dp),
11115863Snate@binkert.org                         os.path.realpath(env['BUILDDIR']))
11124202Sbinkertn@umich.edu    with open(path, 'w') as hdr:
11136108Snate@binkert.org        print('#include "%s/%s/%s"' % (dp, subdir, fp), file=hdr)
11146108Snate@binkert.org
11156108Snate@binkert.orgswitching_header_action = MakeAction(build_switching_header,
11166108Snate@binkert.org                                     Transform('GENERATE'))
11179219Spower.jg@gmail.com
11189219Spower.jg@gmail.comswitching_header_builder = Builder(action=switching_header_action,
11199219Spower.jg@gmail.com                                   source_factory=Value,
11209219Spower.jg@gmail.com                                   single_source=True)
11219219Spower.jg@gmail.com
11229219Spower.jg@gmail.commain.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
11239219Spower.jg@gmail.com
11249219Spower.jg@gmail.comdef switching_headers(self, headers, source):
11254202Sbinkertn@umich.edu    for header in headers:
11265863Snate@binkert.org        self.SwitchingHeader(header, source)
112710135SCurtis.Dunham@arm.com
11288474Sgblack@eecs.umich.edumain.AddMethod(switching_headers, 'SwitchingHeaders')
11295742Snate@binkert.org
11308268Ssteve.reinhardt@amd.com###################################################
11318268Ssteve.reinhardt@amd.com#
11328268Ssteve.reinhardt@amd.com# Define build environments for selected configurations.
11335742Snate@binkert.org#
11345341Sstever@gmail.com###################################################
11358474Sgblack@eecs.umich.edu
11368474Sgblack@eecs.umich.edufor variant_path in variant_paths:
11375342Sstever@gmail.com    if not GetOption('silent'):
11384202Sbinkertn@umich.edu        print("Building in", variant_path)
11394202Sbinkertn@umich.edu
11404202Sbinkertn@umich.edu    # Make a copy of the build-root environment to use for this config.
11415863Snate@binkert.org    env = main.Clone()
11425863Snate@binkert.org    env['BUILDDIR'] = variant_path
11436994Snate@binkert.org
11446994Snate@binkert.org    # variant_dir is the tail component of build path, and is used to
114510319SAndreas.Sandberg@ARM.com    # determine the build parameters (e.g., 'ALPHA_SE')
11465863Snate@binkert.org    (build_root, variant_dir) = splitpath(variant_path)
11475863Snate@binkert.org
11485863Snate@binkert.org    # Set env variables according to the build directory config.
11495863Snate@binkert.org    sticky_vars.files = []
11505863Snate@binkert.org    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
11515863Snate@binkert.org    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
11525863Snate@binkert.org    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
11535863Snate@binkert.org    current_vars_file = joinpath(build_root, 'variables', variant_dir)
11547840Snate@binkert.org    if isfile(current_vars_file):
11555863Snate@binkert.org        sticky_vars.files.append(current_vars_file)
11565952Ssaidi@eecs.umich.edu        if not GetOption('silent'):
11579651SAndreas.Sandberg@ARM.com            print("Using saved variables file %s" % current_vars_file)
11589219Spower.jg@gmail.com    elif variant_dir in ext_build_dirs:
11599219Spower.jg@gmail.com        # Things in ext are built without a variant directory.
11601869SN/A        continue
11611858SN/A    else:
11625863Snate@binkert.org        # Build dir-specific variables file doesn't exist.
11639420Sandreas.hansson@arm.com
116410607Sgabeblack@google.com        # Make sure the directory is there so we can create it later
11659986Sandreas@sandberg.pp.se        opt_dir = dirname(current_vars_file)
11661858SN/A        if not isdir(opt_dir):
1167955SN/A            mkdir(opt_dir)
1168955SN/A
11691869SN/A        # Get default build variables from source tree.  Variables are
11701869SN/A        # normally determined by name of $VARIANT_DIR, but can be
11711869SN/A        # overridden by '--default=' arg on command line.
11721869SN/A        default = GetOption('default')
11731869SN/A        opts_dir = joinpath(main.root.abspath, 'build_opts')
11745863Snate@binkert.org        if default:
11755863Snate@binkert.org            default_vars_files = [joinpath(build_root, 'variables', default),
11765863Snate@binkert.org                                  joinpath(opts_dir, default)]
11771869SN/A        else:
11785863Snate@binkert.org            default_vars_files = [joinpath(opts_dir, variant_dir)]
11791869SN/A        existing_files = filter(isfile, default_vars_files)
11805863Snate@binkert.org        if existing_files:
11811869SN/A            default_vars_file = existing_files[0]
11821869SN/A            sticky_vars.files.append(default_vars_file)
11831869SN/A            print("Variables file %s not found,\n  using defaults in %s"
11841869SN/A                  % (current_vars_file, default_vars_file))
11858483Sgblack@eecs.umich.edu        else:
11861869SN/A            print("Error: cannot find variables file %s or "
11871869SN/A                  "default file(s) %s"
11881869SN/A                  % (current_vars_file, ' or '.join(default_vars_files)))
11891869SN/A            Exit(1)
11905863Snate@binkert.org
11915863Snate@binkert.org    # Apply current variable settings to env
11921869SN/A    sticky_vars.Update(env)
11935863Snate@binkert.org
11945863Snate@binkert.org    help_texts["local_vars"] += \
11953356Sbinkertn@umich.edu        "Build variables for %s:\n" % variant_dir \
11963356Sbinkertn@umich.edu                 + sticky_vars.GenerateHelpText(env)
11973356Sbinkertn@umich.edu
11983356Sbinkertn@umich.edu    # Process variable settings.
11993356Sbinkertn@umich.edu
12004781Snate@binkert.org    if not have_fenv and env['USE_FENV']:
12015863Snate@binkert.org        print("Warning: <fenv.h> not available; "
12025863Snate@binkert.org              "forcing USE_FENV to False in", variant_dir + ".")
12031869SN/A        env['USE_FENV'] = False
12041869SN/A
12051869SN/A    if not env['USE_FENV']:
12066121Snate@binkert.org        print("Warning: No IEEE FP rounding mode control in",
12071869SN/A              variant_dir + ".")
12082638Sstever@eecs.umich.edu        print("         FP results may deviate slightly from other platforms.")
12096121Snate@binkert.org
12106121Snate@binkert.org    if not have_png and env['USE_PNG']:
12112638Sstever@eecs.umich.edu        print("Warning: <png.h> not available; "
12125749Scws3k@cs.virginia.edu              "forcing USE_PNG to False in", variant_dir + ".")
12136121Snate@binkert.org        env['USE_PNG'] = False
12146121Snate@binkert.org
12155749Scws3k@cs.virginia.edu    if env['USE_PNG']:
12169537Satgutier@umich.edu        env.Append(LIBS=['png'])
12179537Satgutier@umich.edu
12189537Satgutier@umich.edu    if env['EFENCE']:
12199537Satgutier@umich.edu        env.Append(LIBS=['efence'])
12209888Sandreas@sandberg.pp.se
12219888Sandreas@sandberg.pp.se    if env['USE_KVM']:
12229888Sandreas@sandberg.pp.se        if not have_kvm:
12239888Sandreas@sandberg.pp.se            print("Warning: Can not enable KVM, host seems to "
122410066Sandreas.hansson@arm.com                  "lack KVM support")
122510066Sandreas.hansson@arm.com            env['USE_KVM'] = False
122610066Sandreas.hansson@arm.com        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
122710066Sandreas.hansson@arm.com            print("Info: KVM support disabled due to unsupported host and "
122810428Sandreas.hansson@arm.com                  "target ISA combination")
122910428Sandreas.hansson@arm.com            env['USE_KVM'] = False
123010428Sandreas.hansson@arm.com
123110428Sandreas.hansson@arm.com    if env['USE_TUNTAP']:
12321869SN/A        if not have_tuntap:
12331869SN/A            print("Warning: Can't connect EtherTap with a tap device.")
12343546Sgblack@eecs.umich.edu            env['USE_TUNTAP'] = False
12353546Sgblack@eecs.umich.edu
12363546Sgblack@eecs.umich.edu    if env['BUILD_GPU']:
12373546Sgblack@eecs.umich.edu        env.Append(CPPDEFINES=['BUILD_GPU'])
12386121Snate@binkert.org
123910196SCurtis.Dunham@arm.com    # Warn about missing optional functionality
12405863Snate@binkert.org    if env['USE_KVM']:
12413546Sgblack@eecs.umich.edu        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
12423546Sgblack@eecs.umich.edu            print("Warning: perf_event headers lack support for the "
12433546Sgblack@eecs.umich.edu                  "exclude_host attribute. KVM instruction counts will "
12443546Sgblack@eecs.umich.edu                  "be inaccurate.")
12454781Snate@binkert.org
12466658Snate@binkert.org    # Save sticky variable settings back to current variables file
124710196SCurtis.Dunham@arm.com    sticky_vars.Save(current_vars_file, env)
124810196SCurtis.Dunham@arm.com
124910196SCurtis.Dunham@arm.com    if env['USE_SSE2']:
125010196SCurtis.Dunham@arm.com        env.Append(CCFLAGS=['-msse2'])
125110196SCurtis.Dunham@arm.com
125210196SCurtis.Dunham@arm.com    # The src/SConscript file sets up the build rules in 'env' according
125310196SCurtis.Dunham@arm.com    # to the configured variables.  It returns a list of environments,
12543546Sgblack@eecs.umich.edu    # one for each variant build (debug, opt, etc.)
12553546Sgblack@eecs.umich.edu    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
12563546Sgblack@eecs.umich.edu
12573546Sgblack@eecs.umich.edu# base help text
12587756SAli.Saidi@ARM.comHelp('''
12597816Ssteve.reinhardt@amd.comUsage: scons [scons options] [build variables] [target(s)]
12603546Sgblack@eecs.umich.edu
12613546Sgblack@eecs.umich.eduExtra scons options:
12623546Sgblack@eecs.umich.edu%(options)s
12633546Sgblack@eecs.umich.edu
126410196SCurtis.Dunham@arm.comGlobal build variables:
126510196SCurtis.Dunham@arm.com%(global_vars)s
126610196SCurtis.Dunham@arm.com
126710196SCurtis.Dunham@arm.com%(local_vars)s
126810196SCurtis.Dunham@arm.com''' % help_texts)
12694202Sbinkertn@umich.edu