SConstruct revision 12245:ad6fa75d2aba
1955SN/A# -*- mode:python -*-
2955SN/A
312230Sgiacomo.travaglini@arm.com# Copyright (c) 2013, 2015-2017 ARM Limited
49812Sandreas.hansson@arm.com# All rights reserved.
59812Sandreas.hansson@arm.com#
69812Sandreas.hansson@arm.com# The license below extends only to copyright in the software and shall
79812Sandreas.hansson@arm.com# not be construed as granting a license to any other intellectual
89812Sandreas.hansson@arm.com# property including but not limited to intellectual property relating
99812Sandreas.hansson@arm.com# to a hardware implementation of the functionality of the software
109812Sandreas.hansson@arm.com# licensed hereunder.  You may use the software subject to the license
119812Sandreas.hansson@arm.com# terms below provided that you ensure that this notice is replicated
129812Sandreas.hansson@arm.com# unmodified and in its entirety in all distributions of the software,
139812Sandreas.hansson@arm.com# modified or unmodified, in source code or in binary form.
149812Sandreas.hansson@arm.com#
157816Ssteve.reinhardt@amd.com# Copyright (c) 2011 Advanced Micro Devices, Inc.
165871Snate@binkert.org# Copyright (c) 2009 The Hewlett-Packard Development Company
171762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
28955SN/A# contributors may be used to endorse or promote products derived from
29955SN/A# this software without specific prior written permission.
30955SN/A#
31955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422665Ssaidi@eecs.umich.edu#
432665Ssaidi@eecs.umich.edu# Authors: Steve Reinhardt
445863Snate@binkert.org#          Nathan Binkert
45955SN/A
46955SN/A###################################################
47955SN/A#
48955SN/A# SCons top-level build description (SConstruct) file.
49955SN/A#
508878Ssteve.reinhardt@amd.com# While in this directory ('gem5'), just type 'scons' to build the default
512632Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
528878Ssteve.reinhardt@amd.com# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532632Sstever@eecs.umich.edu# the optimized full-system version).
54955SN/A#
558878Ssteve.reinhardt@amd.com# You can build gem5 in a different directory as long as there is a
562632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572761Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582632Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612761Sstever@eecs.umich.edu#
622761Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
632761Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
648878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
658878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
662761Sstever@eecs.umich.edu#
672761Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
682761Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
692761Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
702761Sstever@eecs.umich.edu#   file.
718878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
728878Ssteve.reinhardt@amd.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732632Sstever@eecs.umich.edu#
742632Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
758878Ssteve.reinhardt@amd.com# 'gem5' directory (or use -u or -C to tell scons where to find this
768878Ssteve.reinhardt@amd.com# file), you can use 'scons -h' to print all the gem5-specific build
772632Sstever@eecs.umich.edu# options as well.
78955SN/A#
79955SN/A###################################################
80955SN/A
816654Snate@binkert.org# Global Python includes
8210196SCurtis.Dunham@arm.comimport itertools
83955SN/Aimport os
845396Ssaidi@eecs.umich.eduimport re
8511401Sandreas.sandberg@arm.comimport shutil
865863Snate@binkert.orgimport subprocess
875863Snate@binkert.orgimport sys
884202Sbinkertn@umich.edu
895863Snate@binkert.orgfrom os import mkdir, environ
905863Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
915863Snate@binkert.orgfrom os.path import exists,  isdir, isfile
925863Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
93955SN/A
946654Snate@binkert.org# SCons includes
955273Sstever@gmail.comimport SCons
965871Snate@binkert.orgimport SCons.Node
975273Sstever@gmail.com
986654Snate@binkert.orgfrom m5.util import compareVersions, readCommand
995396Ssaidi@eecs.umich.edufrom m5.util.terminal import get_termcap
1008120Sgblack@eecs.umich.edu
1018120Sgblack@eecs.umich.eduhelp_texts = {
1028120Sgblack@eecs.umich.edu    "options" : "",
1038120Sgblack@eecs.umich.edu    "global_vars" : "",
1048120Sgblack@eecs.umich.edu    "local_vars" : ""
1058120Sgblack@eecs.umich.edu}
1068120Sgblack@eecs.umich.edu
1078120Sgblack@eecs.umich.eduExport("help_texts")
1088879Ssteve.reinhardt@amd.com
1098879Ssteve.reinhardt@amd.com
1108879Ssteve.reinhardt@amd.com# There's a bug in scons in that (1) by default, the help texts from
1118879Ssteve.reinhardt@amd.com# AddOption() are supposed to be displayed when you type 'scons -h'
1128879Ssteve.reinhardt@amd.com# and (2) you can override the help displayed by 'scons -h' using the
1138879Ssteve.reinhardt@amd.com# Help() function, but these two features are incompatible: once
1148879Ssteve.reinhardt@amd.com# you've overridden the help text using Help(), there's no way to get
1158879Ssteve.reinhardt@amd.com# at the help texts from AddOptions.  See:
1168879Ssteve.reinhardt@amd.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1178879Ssteve.reinhardt@amd.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1188879Ssteve.reinhardt@amd.com# This hack lets us extract the help text from AddOptions and
1198879Ssteve.reinhardt@amd.com# re-inject it via Help().  Ideally someday this bug will be fixed and
1208879Ssteve.reinhardt@amd.com# we can just use AddOption directly.
1218120Sgblack@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1228120Sgblack@eecs.umich.edu    col_width = 30
1238120Sgblack@eecs.umich.edu
1248120Sgblack@eecs.umich.edu    help = "  " + ", ".join(args)
1258120Sgblack@eecs.umich.edu    if "help" in kwargs:
1268120Sgblack@eecs.umich.edu        length = len(help)
1278120Sgblack@eecs.umich.edu        if length >= col_width:
1288120Sgblack@eecs.umich.edu            help += "\n" + " " * col_width
1298120Sgblack@eecs.umich.edu        else:
1308120Sgblack@eecs.umich.edu            help += " " * (col_width - length)
1318120Sgblack@eecs.umich.edu        help += kwargs["help"]
1328120Sgblack@eecs.umich.edu    help_texts["options"] += help + "\n"
1338120Sgblack@eecs.umich.edu
1348120Sgblack@eecs.umich.edu    AddOption(*args, **kwargs)
1358879Ssteve.reinhardt@amd.com
1368879Ssteve.reinhardt@amd.comAddLocalOption('--colors', dest='use_colors', action='store_true',
1378879Ssteve.reinhardt@amd.com               help="Add color to abbreviated scons output")
1388879Ssteve.reinhardt@amd.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
13910458Sandreas.hansson@arm.com               help="Don't add color to abbreviated scons output")
14010458Sandreas.hansson@arm.comAddLocalOption('--with-cxx-config', dest='with_cxx_config',
14110458Sandreas.hansson@arm.com               action='store_true',
1428879Ssteve.reinhardt@amd.com               help="Build with support for C++-based configuration")
1438879Ssteve.reinhardt@amd.comAddLocalOption('--default', dest='default', type='string', action='store',
1448879Ssteve.reinhardt@amd.com               help='Override which build_opts file to use for defaults')
1458879Ssteve.reinhardt@amd.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1469227Sandreas.hansson@arm.com               help='Disable style checking hooks')
1479227Sandreas.hansson@arm.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
14812063Sgabeblack@google.com               help='Disable Link-Time Optimization for fast')
14912063Sgabeblack@google.comAddLocalOption('--force-lto', dest='force_lto', action='store_true',
15012063Sgabeblack@google.com               help='Use Link-Time Optimization instead of partial linking' +
1518879Ssteve.reinhardt@amd.com                    ' when the compiler doesn\'t support using them together.')
1528879Ssteve.reinhardt@amd.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1538879Ssteve.reinhardt@amd.com               help='Update test reference outputs')
1548879Ssteve.reinhardt@amd.comAddLocalOption('--verbose', dest='verbose', action='store_true',
15510453SAndrew.Bardsley@arm.com               help='Print full tool command lines')
15610453SAndrew.Bardsley@arm.comAddLocalOption('--without-python', dest='without_python',
15710453SAndrew.Bardsley@arm.com               action='store_true',
15810456SCurtis.Dunham@arm.com               help='Build without Python configuration support')
15910456SCurtis.Dunham@arm.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
16010456SCurtis.Dunham@arm.com               action='store_true',
16110457Sandreas.hansson@arm.com               help='Disable linking against tcmalloc')
16210457Sandreas.hansson@arm.comAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
16311342Sandreas.hansson@arm.com               help='Build with Undefined Behavior Sanitizer if available')
16411342Sandreas.hansson@arm.comAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1658120Sgblack@eecs.umich.edu               help='Build with Address Sanitizer if available')
16612063Sgabeblack@google.com
16712063Sgabeblack@google.comif GetOption('no_lto') and GetOption('force_lto'):
16812063Sgabeblack@google.com    print '--no-lto and --force-lto are mutually exclusive'
16912063Sgabeblack@google.com    Exit(1)
1705871Snate@binkert.org
1715871Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
1726121Snate@binkert.org
1735871Snate@binkert.org########################################################################
1745871Snate@binkert.org#
1759926Sstan.czerniawski@arm.com# Set up the main build environment.
17612243Sgabeblack@google.com#
1771533SN/A########################################################################
17812246Sgabeblack@google.com
17912246Sgabeblack@google.commain = Environment()
18012246Sgabeblack@google.com
18112246Sgabeblack@google.commain_dict_keys = main.Dictionary().keys()
1829239Sandreas.hansson@arm.com
1839239Sandreas.hansson@arm.com# Check that we have a C/C++ compiler
1849239Sandreas.hansson@arm.comif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
1859239Sandreas.hansson@arm.com    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
1869239Sandreas.hansson@arm.com    Exit(1)
1879239Sandreas.hansson@arm.com
1889239Sandreas.hansson@arm.com###################################################
189955SN/A#
190955SN/A# Figure out which configurations to set up based on the path(s) of
1912632Sstever@eecs.umich.edu# the target(s).
1922632Sstever@eecs.umich.edu#
193955SN/A###################################################
194955SN/A
195955SN/A# Find default configuration & binary.
196955SN/ADefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
1978878Ssteve.reinhardt@amd.com
198955SN/A# helper function: find last occurrence of element in list
1992632Sstever@eecs.umich.edudef rfind(l, elt, offs = -1):
2002632Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
2012632Sstever@eecs.umich.edu        if l[i] == elt:
2022632Sstever@eecs.umich.edu            return i
2032632Sstever@eecs.umich.edu    raise ValueError, "element not found"
2042632Sstever@eecs.umich.edu
2052632Sstever@eecs.umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
2068268Ssteve.reinhardt@amd.com# paths made absolute and ~-expanded.  Paths will be interpreted
2078268Ssteve.reinhardt@amd.com# relative to the launch directory unless a different root is provided
2088268Ssteve.reinhardt@amd.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
2098268Ssteve.reinhardt@amd.com    return [abspath(joinpath(root, expanduser(str(p))))
2108268Ssteve.reinhardt@amd.com            for p in path_list]
2118268Ssteve.reinhardt@amd.com
2128268Ssteve.reinhardt@amd.com# Each target must have 'build' in the interior of the path; the
2132632Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
2142632Sstever@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2152632Sstever@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
2162632Sstever@eecs.umich.edu# follow 'build' in the build path.
2178268Ssteve.reinhardt@amd.com
2182632Sstever@eecs.umich.edu# The funky assignment to "[:]" is needed to replace the list contents
2198268Ssteve.reinhardt@amd.com# in place rather than reassign the symbol to a new list, which
2208268Ssteve.reinhardt@amd.com# doesn't work (obviously!).
2218268Ssteve.reinhardt@amd.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
2228268Ssteve.reinhardt@amd.com
2233718Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
2242634Sstever@eecs.umich.edu# collected targets reference.
2252634Sstever@eecs.umich.eduvariant_paths = []
2265863Snate@binkert.orgbuild_root = None
2272638Sstever@eecs.umich.edufor t in BUILD_TARGETS:
2288268Ssteve.reinhardt@amd.com    path_dirs = t.split('/')
2292632Sstever@eecs.umich.edu    try:
2302632Sstever@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
2312632Sstever@eecs.umich.edu    except:
2322632Sstever@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
2332632Sstever@eecs.umich.edu        Exit(1)
2341858SN/A    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2353716Sstever@eecs.umich.edu    if not build_root:
2362638Sstever@eecs.umich.edu        build_root = this_build_root
2372638Sstever@eecs.umich.edu    else:
2382638Sstever@eecs.umich.edu        if this_build_root != build_root:
2392638Sstever@eecs.umich.edu            print "Error: build targets not under same build root\n"\
2402638Sstever@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
2412638Sstever@eecs.umich.edu            Exit(1)
2422638Sstever@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
2435863Snate@binkert.org    if variant_path not in variant_paths:
2445863Snate@binkert.org        variant_paths.append(variant_path)
2455863Snate@binkert.org
246955SN/A# Make sure build_root exists (might not if this is the first build there)
2475341Sstever@gmail.comif not isdir(build_root):
2485341Sstever@gmail.com    mkdir(build_root)
2495863Snate@binkert.orgmain['BUILDROOT'] = build_root
2507756SAli.Saidi@ARM.com
2515341Sstever@gmail.comExport('main')
2526121Snate@binkert.org
2534494Ssaidi@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
2546121Snate@binkert.org
2551105SN/A# Default duplicate option is to use hard links, but this messes up
2562667Sstever@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
2572667Sstever@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
2582667Sstever@eecs.umich.edu# (soft) links work better.
2592667Sstever@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
2606121Snate@binkert.org
2612667Sstever@eecs.umich.edu#
2625341Sstever@gmail.com# Set up global sticky variables... these are common to an entire build
2635863Snate@binkert.org# tree (not specific to a particular build like ALPHA_SE)
2645341Sstever@gmail.com#
2655341Sstever@gmail.com
2665341Sstever@gmail.comglobal_vars_file = joinpath(build_root, 'variables.global')
2678120Sgblack@eecs.umich.edu
2685341Sstever@gmail.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
2698120Sgblack@eecs.umich.edu
2705341Sstever@gmail.comglobal_vars.AddVariables(
2718120Sgblack@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
2726121Snate@binkert.org    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
2736121Snate@binkert.org    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
2749396Sandreas.hansson@arm.com    ('BATCH', 'Use batch pool for build and tests', False),
2755397Ssaidi@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
2765397Ssaidi@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
2777727SAli.Saidi@ARM.com    ('EXTRAS', 'Add extra directories to the compilation', '')
2788268Ssteve.reinhardt@amd.com    )
2796168Snate@binkert.org
2805341Sstever@gmail.com# Update main environment with values from ARGUMENTS & global_vars_file
2818120Sgblack@eecs.umich.eduglobal_vars.Update(main)
2828120Sgblack@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
2838120Sgblack@eecs.umich.edu
2846814Sgblack@eecs.umich.edu# Save sticky variable settings back to current variables file
2855863Snate@binkert.orgglobal_vars.Save(global_vars_file, main)
2868120Sgblack@eecs.umich.edu
2875341Sstever@gmail.com# Parse EXTRAS variable to build list of all directories where we're
2885863Snate@binkert.org# look for sources etc.  This list is exported as extras_dir_list.
2898268Ssteve.reinhardt@amd.combase_dir = main.srcdir.abspath
2906121Snate@binkert.orgif main['EXTRAS']:
2916121Snate@binkert.org    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
2928268Ssteve.reinhardt@amd.comelse:
2935742Snate@binkert.org    extras_dir_list = []
2945742Snate@binkert.org
2955341Sstever@gmail.comExport('base_dir')
2965742Snate@binkert.orgExport('extras_dir_list')
2975742Snate@binkert.org
2985341Sstever@gmail.com# the ext directory should be on the #includes path
2996017Snate@binkert.orgmain.Append(CPPPATH=[Dir('ext')])
3006121Snate@binkert.org
3016017Snate@binkert.org# Add shared top-level headers
30212158Sandreas.sandberg@arm.commain.Prepend(CPPPATH=Dir('include'))
30312158Sandreas.sandberg@arm.com
30412158Sandreas.sandberg@arm.comdef strip_build_path(path, env):
3058120Sgblack@eecs.umich.edu    path = str(path)
3067756SAli.Saidi@ARM.com    variant_base = env['BUILDROOT'] + os.path.sep
3077756SAli.Saidi@ARM.com    if path.startswith(variant_base):
3087756SAli.Saidi@ARM.com        path = path[len(variant_base):]
3097756SAli.Saidi@ARM.com    elif path.startswith('build/'):
3107816Ssteve.reinhardt@amd.com        path = path[6:]
3117816Ssteve.reinhardt@amd.com    return path
3127816Ssteve.reinhardt@amd.com
3137816Ssteve.reinhardt@amd.com# Generate a string of the form:
3147816Ssteve.reinhardt@amd.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
31511979Sgabeblack@google.com# to print while building.
3167816Ssteve.reinhardt@amd.comclass Transform(object):
3177816Ssteve.reinhardt@amd.com    # all specific color settings should be here and nowhere else
3187816Ssteve.reinhardt@amd.com    tool_color = termcap.Normal
3197816Ssteve.reinhardt@amd.com    pfx_color = termcap.Yellow
3207756SAli.Saidi@ARM.com    srcs_color = termcap.Yellow + termcap.Bold
3217756SAli.Saidi@ARM.com    arrow_color = termcap.Blue + termcap.Bold
3229227Sandreas.hansson@arm.com    tgts_color = termcap.Yellow + termcap.Bold
3239227Sandreas.hansson@arm.com
3249227Sandreas.hansson@arm.com    def __init__(self, tool, max_sources=99):
3259227Sandreas.hansson@arm.com        self.format = self.tool_color + (" [%8s] " % tool) \
3269590Sandreas@sandberg.pp.se                      + self.pfx_color + "%s" \
3279590Sandreas@sandberg.pp.se                      + self.srcs_color + "%s" \
3289590Sandreas@sandberg.pp.se                      + self.arrow_color + " -> " \
3299590Sandreas@sandberg.pp.se                      + self.tgts_color + "%s" \
3309590Sandreas@sandberg.pp.se                      + termcap.Normal
3319590Sandreas@sandberg.pp.se        self.max_sources = max_sources
3326654Snate@binkert.org
3336654Snate@binkert.org    def __call__(self, target, source, env, for_signature=None):
3345871Snate@binkert.org        # truncate source list according to max_sources param
3356121Snate@binkert.org        source = source[0:self.max_sources]
3368946Sandreas.hansson@arm.com        def strip(f):
3379419Sandreas.hansson@arm.com            return strip_build_path(str(f), env)
3383940Ssaidi@eecs.umich.edu        if len(source) > 0:
3393918Ssaidi@eecs.umich.edu            srcs = map(strip, source)
3403918Ssaidi@eecs.umich.edu        else:
3411858SN/A            srcs = ['']
3429556Sandreas.hansson@arm.com        tgts = map(strip, target)
3439556Sandreas.hansson@arm.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
3449556Sandreas.hansson@arm.com        # operation that has nothing to do with paths.
3459556Sandreas.hansson@arm.com        com_pfx = os.path.commonprefix(srcs + tgts)
34611294Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
34711294Sandreas.hansson@arm.com        if com_pfx:
34811294Sandreas.hansson@arm.com            # do some cleanup and sanity checking on common prefix
34911294Sandreas.hansson@arm.com            if com_pfx[-1] == ".":
35010878Sandreas.hansson@arm.com                # prefix matches all but file extension: ok
35110878Sandreas.hansson@arm.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
35211811Sbaz21@cam.ac.uk                com_pfx = com_pfx[0:-1]
35311811Sbaz21@cam.ac.uk            elif com_pfx[-1] == "/":
35411811Sbaz21@cam.ac.uk                # common prefix is directory path: OK
35511982Sgabeblack@google.com                pass
35611982Sgabeblack@google.com            else:
35711982Sgabeblack@google.com                src0_len = len(srcs[0])
35811982Sgabeblack@google.com                tgt0_len = len(tgts[0])
35911992Sgabeblack@google.com                if src0_len == com_pfx_len:
36011982Sgabeblack@google.com                    # source is a substring of target, OK
36111982Sgabeblack@google.com                    pass
36212305Sgabeblack@google.com                elif tgt0_len == com_pfx_len:
36312305Sgabeblack@google.com                    # target is a substring of source, need to back up to
36412305Sgabeblack@google.com                    # avoid empty string on RHS of arrow
36512305Sgabeblack@google.com                    sep_idx = com_pfx.rfind(".")
36612305Sgabeblack@google.com                    if sep_idx != -1:
36712305Sgabeblack@google.com                        com_pfx = com_pfx[0:sep_idx]
36812305Sgabeblack@google.com                    else:
3699556Sandreas.hansson@arm.com                        com_pfx = ''
3709556Sandreas.hansson@arm.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
3719556Sandreas.hansson@arm.com                    # still splitting at file extension: ok
3729556Sandreas.hansson@arm.com                    pass
3739556Sandreas.hansson@arm.com                else:
3749556Sandreas.hansson@arm.com                    # probably a fluke; ignore it
3759556Sandreas.hansson@arm.com                    com_pfx = ''
3769556Sandreas.hansson@arm.com        # recalculate length in case com_pfx was modified
3779556Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
3789556Sandreas.hansson@arm.com        def fmt(files):
3799556Sandreas.hansson@arm.com            f = map(lambda s: s[com_pfx_len:], files)
3809556Sandreas.hansson@arm.com            return ', '.join(f)
3819556Sandreas.hansson@arm.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
3829556Sandreas.hansson@arm.com
3839556Sandreas.hansson@arm.comExport('Transform')
3849556Sandreas.hansson@arm.com
3859556Sandreas.hansson@arm.com# enable the regression script to use the termcap
3869556Sandreas.hansson@arm.commain['TERMCAP'] = termcap
3879556Sandreas.hansson@arm.com
3886121Snate@binkert.orgif GetOption('verbose'):
38911500Sandreas.hansson@arm.com    def MakeAction(action, string, *args, **kwargs):
39010238Sandreas.hansson@arm.com        return Action(action, *args, **kwargs)
39110878Sandreas.hansson@arm.comelse:
3929420Sandreas.hansson@arm.com    MakeAction = Action
39311500Sandreas.hansson@arm.com    main['CCCOMSTR']        = Transform("CC")
39411500Sandreas.hansson@arm.com    main['CXXCOMSTR']       = Transform("CXX")
3959420Sandreas.hansson@arm.com    main['ASCOMSTR']        = Transform("AS")
3969420Sandreas.hansson@arm.com    main['ARCOMSTR']        = Transform("AR", 0)
3979420Sandreas.hansson@arm.com    main['LINKCOMSTR']      = Transform("LINK", 0)
3989420Sandreas.hansson@arm.com    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
3999420Sandreas.hansson@arm.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
40012063Sgabeblack@google.com    main['M4COMSTR']        = Transform("M4")
40112063Sgabeblack@google.com    main['SHCCCOMSTR']      = Transform("SHCC")
40212063Sgabeblack@google.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
40312063Sgabeblack@google.comExport('MakeAction')
40412063Sgabeblack@google.com
40512063Sgabeblack@google.com# Initialize the Link-Time Optimization (LTO) flags
40612063Sgabeblack@google.commain['LTO_CCFLAGS'] = []
40712063Sgabeblack@google.commain['LTO_LDFLAGS'] = []
40812063Sgabeblack@google.com
40912063Sgabeblack@google.com# According to the readme, tcmalloc works best if the compiler doesn't
41012063Sgabeblack@google.com# assume that we're using the builtin malloc and friends. These flags
41112063Sgabeblack@google.com# are compiler-specific, so we need to set them after we detect which
41212063Sgabeblack@google.com# compiler we're using.
41312063Sgabeblack@google.commain['TCMALLOC_CCFLAGS'] = []
41412063Sgabeblack@google.com
41512063Sgabeblack@google.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
41612063Sgabeblack@google.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
41712063Sgabeblack@google.com
41812063Sgabeblack@google.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
41912063Sgabeblack@google.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
42012063Sgabeblack@google.comif main['GCC'] + main['CLANG'] > 1:
42112063Sgabeblack@google.com    print 'Error: How can we have two at the same time?'
42210264Sandreas.hansson@arm.com    Exit(1)
42310264Sandreas.hansson@arm.com
42410264Sandreas.hansson@arm.com# Set up default C++ compiler flags
42510264Sandreas.hansson@arm.comif main['GCC'] or main['CLANG']:
42611925Sgabeblack@google.com    # As gcc and clang share many flags, do the common parts here
42711925Sgabeblack@google.com    main.Append(CCFLAGS=['-pipe'])
42811500Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
42910264Sandreas.hansson@arm.com    # Enable -Wall and -Wextra and then disable the few warnings that
43011500Sandreas.hansson@arm.com    # we consistently violate
43111500Sandreas.hansson@arm.com    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
43211500Sandreas.hansson@arm.com                         '-Wno-sign-compare', '-Wno-unused-parameter'])
43311500Sandreas.hansson@arm.com    # We always compile using C++11
43410866Sandreas.hansson@arm.com    main.Append(CXXFLAGS=['-std=c++11'])
43511500Sandreas.hansson@arm.com    if sys.platform.startswith('freebsd'):
43611500Sandreas.hansson@arm.com        main.Append(CCFLAGS=['-I/usr/local/include'])
43711500Sandreas.hansson@arm.com        main.Append(CXXFLAGS=['-I/usr/local/include'])
43811500Sandreas.hansson@arm.com
43911500Sandreas.hansson@arm.com    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
44011500Sandreas.hansson@arm.com    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
44111500Sandreas.hansson@arm.com    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
44210264Sandreas.hansson@arm.com    shared_partial_flags = ['-r', '-nostdlib']
44310457Sandreas.hansson@arm.com    main.Append(PSHLINKFLAGS=shared_partial_flags)
44410457Sandreas.hansson@arm.com    main.Append(PLINKFLAGS=shared_partial_flags)
44510457Sandreas.hansson@arm.comelse:
44610457Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
44710457Sandreas.hansson@arm.com    print "Don't know what compiler options to use for your compiler."
44810457Sandreas.hansson@arm.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
44910457Sandreas.hansson@arm.com    print termcap.Yellow + '       version:' + termcap.Normal,
45010457Sandreas.hansson@arm.com    if not CXX_version:
45110457Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
45212063Sgabeblack@google.com               termcap.Normal
45312063Sgabeblack@google.com    else:
45412063Sgabeblack@google.com        print CXX_version.replace('\n', '<nl>')
45512063Sgabeblack@google.com    print "       If you're trying to use a compiler other than GCC"
45612063Sgabeblack@google.com    print "       or clang, there appears to be something wrong with your"
45712063Sgabeblack@google.com    print "       environment."
45812063Sgabeblack@google.com    print "       "
45912063Sgabeblack@google.com    print "       If you are trying to use a compiler other than those listed"
46012063Sgabeblack@google.com    print "       above you will need to ease fix SConstruct and "
46112063Sgabeblack@google.com    print "       src/SConscript to support that compiler."
46212063Sgabeblack@google.com    Exit(1)
46310238Sandreas.hansson@arm.com
46410238Sandreas.hansson@arm.comif main['GCC']:
46510238Sandreas.hansson@arm.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
46612063Sgabeblack@google.com    # level of c++11 support. See
46710238Sandreas.hansson@arm.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
46810238Sandreas.hansson@arm.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
46910416Sandreas.hansson@arm.com    if compareVersions(gcc_version, "4.8") < 0:
47010238Sandreas.hansson@arm.com        print 'Error: gcc version 4.8 or newer required.'
4719227Sandreas.hansson@arm.com        print '       Installed version:', gcc_version
47210238Sandreas.hansson@arm.com        Exit(1)
47310416Sandreas.hansson@arm.com
47410416Sandreas.hansson@arm.com    main['GCC_VERSION'] = gcc_version
4759227Sandreas.hansson@arm.com
4769590Sandreas@sandberg.pp.se    if compareVersions(gcc_version, '4.9') >= 0:
4779590Sandreas@sandberg.pp.se        # Incremental linking with LTO is currently broken in gcc versions
4789590Sandreas@sandberg.pp.se        # 4.9 and above. A version where everything works completely hasn't
47911497SMatteo.Andreozzi@arm.com        # yet been identified.
48011497SMatteo.Andreozzi@arm.com        #
48111497SMatteo.Andreozzi@arm.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
48211497SMatteo.Andreozzi@arm.com        main['BROKEN_INCREMENTAL_LTO'] = True
48312304Sgabeblack@google.com    if compareVersions(gcc_version, '6.0') >= 0:
48412304Sgabeblack@google.com        # gcc versions 6.0 and greater accept an -flinker-output flag which
48512304Sgabeblack@google.com        # selects what type of output the linker should generate. This is
48612304Sgabeblack@google.com        # necessary for incremental lto to work, but is also broken in
48712304Sgabeblack@google.com        # current versions of gcc. It may not be necessary in future
48812304Sgabeblack@google.com        # versions. We add it here since it might be, and as a reminder that
48912304Sgabeblack@google.com        # it exists. It's excluded if lto is being forced.
49012304Sgabeblack@google.com        #
49112304Sgabeblack@google.com        # https://gcc.gnu.org/gcc-6/changes.html
49212304Sgabeblack@google.com        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
49312304Sgabeblack@google.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
49412304Sgabeblack@google.com        if not GetOption('force_lto'):
49512304Sgabeblack@google.com            main.Append(PSHLINKFLAGS='-flinker-output=rel')
49612304Sgabeblack@google.com            main.Append(PLINKFLAGS='-flinker-output=rel')
49712304Sgabeblack@google.com
49812304Sgabeblack@google.com    # gcc from version 4.8 and above generates "rep; ret" instructions
49912304Sgabeblack@google.com    # to avoid performance penalties on certain AMD chips. Older
50012304Sgabeblack@google.com    # assemblers detect this as an error, "Error: expecting string
50112304Sgabeblack@google.com    # instruction after `rep'"
5028737Skoansin.tan@gmail.com    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
50310878Sandreas.hansson@arm.com                                  '-o', '/dev/null'],
50411500Sandreas.hansson@arm.com                                 exception=False).split()
5059420Sandreas.hansson@arm.com
5068737Skoansin.tan@gmail.com    # version strings may contain extra distro-specific
50710106SMitch.Hayenga@arm.com    # qualifiers, so play it safe and keep only what comes before
5088737Skoansin.tan@gmail.com    # the first hyphen
5098737Skoansin.tan@gmail.com    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
51010878Sandreas.hansson@arm.com
51110878Sandreas.hansson@arm.com    if not as_version or compareVersions(as_version, "2.23") < 0:
5128737Skoansin.tan@gmail.com        print termcap.Yellow + termcap.Bold + \
5138737Skoansin.tan@gmail.com            'Warning: This combination of gcc and binutils have' + \
5148737Skoansin.tan@gmail.com            ' known incompatibilities.\n' + \
5158737Skoansin.tan@gmail.com            '         If you encounter build problems, please update ' + \
5168737Skoansin.tan@gmail.com            'binutils to 2.23.' + \
5178737Skoansin.tan@gmail.com            termcap.Normal
51811294Sandreas.hansson@arm.com
5199556Sandreas.hansson@arm.com    # Make sure we warn if the user has requested to compile with the
5209556Sandreas.hansson@arm.com    # Undefined Benahvior Sanitizer and this version of gcc does not
5219556Sandreas.hansson@arm.com    # support it.
52211294Sandreas.hansson@arm.com    if GetOption('with_ubsan') and \
52310278SAndreas.Sandberg@ARM.com            compareVersions(gcc_version, '4.9') < 0:
52410278SAndreas.Sandberg@ARM.com        print termcap.Yellow + termcap.Bold + \
52510278SAndreas.Sandberg@ARM.com            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
52610278SAndreas.Sandberg@ARM.com            termcap.Normal
52710278SAndreas.Sandberg@ARM.com
52810278SAndreas.Sandberg@ARM.com    disable_lto = GetOption('no_lto')
5299556Sandreas.hansson@arm.com    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
5309590Sandreas@sandberg.pp.se            not GetOption('force_lto'):
5319590Sandreas@sandberg.pp.se        print termcap.Yellow + termcap.Bold + \
5329420Sandreas.hansson@arm.com            'Warning: Your compiler doesn\'t support incremental linking' + \
5339846Sandreas.hansson@arm.com            ' and lto at the same time, so lto is being disabled. To force' + \
5349846Sandreas.hansson@arm.com            ' lto on anyway, use the --force-lto option. That will disable' + \
5359846Sandreas.hansson@arm.com            ' partial linking.' + \
5369846Sandreas.hansson@arm.com            termcap.Normal
5378946Sandreas.hansson@arm.com        disable_lto = True
53811811Sbaz21@cam.ac.uk
53911811Sbaz21@cam.ac.uk    # Add the appropriate Link-Time Optimization (LTO) flags
54011811Sbaz21@cam.ac.uk    # unless LTO is explicitly turned off. Note that these flags
54111811Sbaz21@cam.ac.uk    # are only used by the fast target.
54212304Sgabeblack@google.com    if not disable_lto:
54312304Sgabeblack@google.com        # Pass the LTO flag when compiling to produce GIMPLE
54412304Sgabeblack@google.com        # output, we merely create the flags here and only append
54512304Sgabeblack@google.com        # them later
54612304Sgabeblack@google.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
54712304Sgabeblack@google.com
54812304Sgabeblack@google.com        # Use the same amount of jobs for LTO as we are running
54912304Sgabeblack@google.com        # scons with
55012304Sgabeblack@google.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
55112304Sgabeblack@google.com
55212304Sgabeblack@google.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
55312304Sgabeblack@google.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
55412304Sgabeblack@google.com
55512304Sgabeblack@google.com    # add option to check for undeclared overrides
55612304Sgabeblack@google.com    if compareVersions(gcc_version, "5.0") > 0:
55712304Sgabeblack@google.com        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
5583918Ssaidi@eecs.umich.edu
5599068SAli.Saidi@ARM.comelif main['CLANG']:
5609068SAli.Saidi@ARM.com    # Check for a supported version of clang, >= 3.1 is needed to
5619068SAli.Saidi@ARM.com    # support similar features as gcc 4.8. See
5629068SAli.Saidi@ARM.com    # http://clang.llvm.org/cxx_status.html for details
5639068SAli.Saidi@ARM.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
5649068SAli.Saidi@ARM.com    clang_version_match = clang_version_re.search(CXX_version)
5659068SAli.Saidi@ARM.com    if (clang_version_match):
5669068SAli.Saidi@ARM.com        clang_version = clang_version_match.groups()[0]
5679068SAli.Saidi@ARM.com        if compareVersions(clang_version, "3.1") < 0:
5689419Sandreas.hansson@arm.com            print 'Error: clang version 3.1 or newer required.'
5699068SAli.Saidi@ARM.com            print '       Installed version:', clang_version
5709068SAli.Saidi@ARM.com            Exit(1)
5719068SAli.Saidi@ARM.com    else:
5729068SAli.Saidi@ARM.com        print 'Error: Unable to determine clang version.'
5739068SAli.Saidi@ARM.com        Exit(1)
5749068SAli.Saidi@ARM.com
5753918Ssaidi@eecs.umich.edu    # clang has a few additional warnings that we disable, extraneous
5763918Ssaidi@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
5776157Snate@binkert.org    # finally self assignments are allowed as the generated CPU code
5786157Snate@binkert.org    # is relying on this
5796157Snate@binkert.org    main.Append(CCFLAGS=['-Wno-parentheses',
5806157Snate@binkert.org                         '-Wno-self-assign',
5815397Ssaidi@eecs.umich.edu                         # Some versions of libstdc++ (4.8?) seem to
5825397Ssaidi@eecs.umich.edu                         # use struct hash and class hash
5836121Snate@binkert.org                         # interchangeably.
5846121Snate@binkert.org                         '-Wno-mismatched-tags',
5856121Snate@binkert.org                         ])
5866121Snate@binkert.org
5876121Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
5886121Snate@binkert.org
5895397Ssaidi@eecs.umich.edu    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5901851SN/A    # opposed to libstdc++, as the later is dated.
5911851SN/A    if sys.platform == "darwin":
5927739Sgblack@eecs.umich.edu        main.Append(CXXFLAGS=['-stdlib=libc++'])
593955SN/A        main.Append(LIBS=['c++'])
5949396Sandreas.hansson@arm.com
5959396Sandreas.hansson@arm.com    # On FreeBSD we need libthr.
5969396Sandreas.hansson@arm.com    if sys.platform.startswith('freebsd'):
5979396Sandreas.hansson@arm.com        main.Append(LIBS=['thr'])
5989396Sandreas.hansson@arm.com
5999396Sandreas.hansson@arm.comelse:
6009396Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6019396Sandreas.hansson@arm.com    print "Don't know what compiler options to use for your compiler."
6029396Sandreas.hansson@arm.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6039396Sandreas.hansson@arm.com    print termcap.Yellow + '       version:' + termcap.Normal,
6049396Sandreas.hansson@arm.com    if not CXX_version:
6059396Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6069396Sandreas.hansson@arm.com               termcap.Normal
6079396Sandreas.hansson@arm.com    else:
6089396Sandreas.hansson@arm.com        print CXX_version.replace('\n', '<nl>')
6099396Sandreas.hansson@arm.com    print "       If you're trying to use a compiler other than GCC"
6109477Sandreas.hansson@arm.com    print "       or clang, there appears to be something wrong with your"
6119477Sandreas.hansson@arm.com    print "       environment."
6129477Sandreas.hansson@arm.com    print "       "
6139477Sandreas.hansson@arm.com    print "       If you are trying to use a compiler other than those listed"
6149477Sandreas.hansson@arm.com    print "       above you will need to ease fix SConstruct and "
6159477Sandreas.hansson@arm.com    print "       src/SConscript to support that compiler."
6169477Sandreas.hansson@arm.com    Exit(1)
6179477Sandreas.hansson@arm.com
6189477Sandreas.hansson@arm.com# Set up common yacc/bison flags (needed for Ruby)
6199477Sandreas.hansson@arm.commain['YACCFLAGS'] = '-d'
6209477Sandreas.hansson@arm.commain['YACCHXXFILESUFFIX'] = '.hh'
6219477Sandreas.hansson@arm.com
6229477Sandreas.hansson@arm.com# Do this after we save setting back, or else we'll tack on an
6239477Sandreas.hansson@arm.com# extra 'qdo' every time we run scons.
6249477Sandreas.hansson@arm.comif main['BATCH']:
6259477Sandreas.hansson@arm.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6269477Sandreas.hansson@arm.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6279477Sandreas.hansson@arm.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6289477Sandreas.hansson@arm.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6299477Sandreas.hansson@arm.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6309477Sandreas.hansson@arm.com
6319477Sandreas.hansson@arm.comif sys.platform == 'cygwin':
6329396Sandreas.hansson@arm.com    # cygwin has some header file issues...
6332667Sstever@eecs.umich.edu    main.Append(CCFLAGS=["-Wno-uninitialized"])
63410710Sandreas.hansson@arm.com
63510710Sandreas.hansson@arm.com# Check for the protobuf compiler
63610710Sandreas.hansson@arm.comprotoc_version = readCommand([main['PROTOC'], '--version'],
63711811Sbaz21@cam.ac.uk                             exception='').split()
63811811Sbaz21@cam.ac.uk
63911811Sbaz21@cam.ac.uk# First two words should be "libprotoc x.y.z"
64011811Sbaz21@cam.ac.ukif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
64111811Sbaz21@cam.ac.uk    print termcap.Yellow + termcap.Bold + \
64211811Sbaz21@cam.ac.uk        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
64310710Sandreas.hansson@arm.com        '         Please install protobuf-compiler for tracing support.' + \
64410710Sandreas.hansson@arm.com        termcap.Normal
64510710Sandreas.hansson@arm.com    main['PROTOC'] = False
64610710Sandreas.hansson@arm.comelse:
64710384SCurtis.Dunham@arm.com    # Based on the availability of the compress stream wrappers,
6489986Sandreas@sandberg.pp.se    # require 2.1.0
6499986Sandreas@sandberg.pp.se    min_protoc_version = '2.1.0'
6509986Sandreas@sandberg.pp.se    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6519986Sandreas@sandberg.pp.se        print termcap.Yellow + termcap.Bold + \
6529986Sandreas@sandberg.pp.se            'Warning: protoc version', min_protoc_version, \
6539986Sandreas@sandberg.pp.se            'or newer required.\n' + \
6549986Sandreas@sandberg.pp.se            '         Installed version:', protoc_version[1], \
6559986Sandreas@sandberg.pp.se            termcap.Normal
6569986Sandreas@sandberg.pp.se        main['PROTOC'] = False
6579986Sandreas@sandberg.pp.se    else:
6589986Sandreas@sandberg.pp.se        # Attempt to determine the appropriate include path and
6599986Sandreas@sandberg.pp.se        # library path using pkg-config, that means we also need to
6609986Sandreas@sandberg.pp.se        # check for pkg-config. Note that it is possible to use
6619986Sandreas@sandberg.pp.se        # protobuf without the involvement of pkg-config. Later on we
6629986Sandreas@sandberg.pp.se        # check go a library config check and at that point the test
6639986Sandreas@sandberg.pp.se        # will fail if libprotobuf cannot be found.
6649986Sandreas@sandberg.pp.se        if readCommand(['pkg-config', '--version'], exception=''):
6659986Sandreas@sandberg.pp.se            try:
6669986Sandreas@sandberg.pp.se                # Attempt to establish what linking flags to add for protobuf
6679986Sandreas@sandberg.pp.se                # using pkg-config
6682638Sstever@eecs.umich.edu                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6692638Sstever@eecs.umich.edu            except:
6706121Snate@binkert.org                print termcap.Yellow + termcap.Bold + \
6713716Sstever@eecs.umich.edu                    'Warning: pkg-config could not get protobuf flags.' + \
6725522Snate@binkert.org                    termcap.Normal
6739986Sandreas@sandberg.pp.se
6749986Sandreas@sandberg.pp.se
6759986Sandreas@sandberg.pp.se# Check for 'timeout' from GNU coreutils. If present, regressions will
6765522Snate@binkert.org# be run with a time limit. We require version 8.13 since we rely on
6775227Ssaidi@eecs.umich.edu# support for the '--foreground' option.
6785227Ssaidi@eecs.umich.eduif sys.platform.startswith('freebsd'):
6795227Ssaidi@eecs.umich.edu    timeout_lines = readCommand(['gtimeout', '--version'],
6805227Ssaidi@eecs.umich.edu                                exception='').splitlines()
6816654Snate@binkert.orgelse:
6826654Snate@binkert.org    timeout_lines = readCommand(['timeout', '--version'],
6837769SAli.Saidi@ARM.com                                exception='').splitlines()
6847769SAli.Saidi@ARM.com# Get the first line and tokenize it
6857769SAli.Saidi@ARM.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
6867769SAli.Saidi@ARM.commain['TIMEOUT'] =  timeout_version and \
6875227Ssaidi@eecs.umich.edu    compareVersions(timeout_version[-1], '8.13') >= 0
6885227Ssaidi@eecs.umich.edu
6895227Ssaidi@eecs.umich.edu# Add a custom Check function to test for structure members.
6905204Sstever@gmail.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
6915204Sstever@gmail.com    context.Message("Checking for member %s in %s..." %
6925204Sstever@gmail.com                    (member, decl))
6935204Sstever@gmail.com    text = """
6945204Sstever@gmail.com#include %(header)s
6955204Sstever@gmail.comint main(){
6965204Sstever@gmail.com  %(decl)s test;
6975204Sstever@gmail.com  (void)test.%(member)s;
6985204Sstever@gmail.com  return 0;
6995204Sstever@gmail.com};
7005204Sstever@gmail.com""" % { "header" : include_quotes[0] + include + include_quotes[1],
7015204Sstever@gmail.com        "decl" : decl,
7025204Sstever@gmail.com        "member" : member,
7035204Sstever@gmail.com        }
7045204Sstever@gmail.com
7055204Sstever@gmail.com    ret = context.TryCompile(text, extension=".cc")
7065204Sstever@gmail.com    context.Result(ret)
7076121Snate@binkert.org    return ret
7085204Sstever@gmail.com
7097727SAli.Saidi@ARM.com# Platform-specific configuration.  Note again that we assume that all
7107727SAli.Saidi@ARM.com# builds under a given build root run on the same host platform.
7117727SAli.Saidi@ARM.comconf = Configure(main,
7127727SAli.Saidi@ARM.com                 conf_dir = joinpath(build_root, '.scons_config'),
7137727SAli.Saidi@ARM.com                 log_file = joinpath(build_root, 'scons_config.log'),
71411988Sandreas.sandberg@arm.com                 custom_tests = {
71511988Sandreas.sandberg@arm.com        'CheckMember' : CheckMember,
71610453SAndrew.Bardsley@arm.com        })
71710453SAndrew.Bardsley@arm.com
71810453SAndrew.Bardsley@arm.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
71910453SAndrew.Bardsley@arm.comtry:
72010453SAndrew.Bardsley@arm.com    import platform
72110453SAndrew.Bardsley@arm.com    uname = platform.uname()
72210453SAndrew.Bardsley@arm.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
72310453SAndrew.Bardsley@arm.com        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
72410453SAndrew.Bardsley@arm.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
72510453SAndrew.Bardsley@arm.com            main.Append(CFLAGS=['-arch', 'x86_64'])
72610160Sandreas.hansson@arm.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
72710453SAndrew.Bardsley@arm.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
72810453SAndrew.Bardsley@arm.comexcept:
72910453SAndrew.Bardsley@arm.com    pass
73010453SAndrew.Bardsley@arm.com
73110453SAndrew.Bardsley@arm.com# Recent versions of scons substitute a "Null" object for Configure()
73210453SAndrew.Bardsley@arm.com# when configuration isn't necessary, e.g., if the "--help" option is
73310453SAndrew.Bardsley@arm.com# present.  Unfortuantely this Null object always returns false,
73410453SAndrew.Bardsley@arm.com# breaking all our configuration checks.  We replace it with our own
7359812Sandreas.hansson@arm.com# more optimistic null object that returns True instead.
73610453SAndrew.Bardsley@arm.comif not conf:
73710453SAndrew.Bardsley@arm.com    def NullCheck(*args, **kwargs):
73810453SAndrew.Bardsley@arm.com        return True
73910453SAndrew.Bardsley@arm.com
74010453SAndrew.Bardsley@arm.com    class NullConf:
74110453SAndrew.Bardsley@arm.com        def __init__(self, env):
74210453SAndrew.Bardsley@arm.com            self.env = env
74310453SAndrew.Bardsley@arm.com        def Finish(self):
74410453SAndrew.Bardsley@arm.com            return self.env
74510453SAndrew.Bardsley@arm.com        def __getattr__(self, mname):
74610453SAndrew.Bardsley@arm.com            return NullCheck
74710453SAndrew.Bardsley@arm.com
7487727SAli.Saidi@ARM.com    conf = NullConf(main)
74910453SAndrew.Bardsley@arm.com
75010453SAndrew.Bardsley@arm.com# Cache build files in the supplied directory.
75110453SAndrew.Bardsley@arm.comif main['M5_BUILD_CACHE']:
75210453SAndrew.Bardsley@arm.com    print 'Using build cache located at', main['M5_BUILD_CACHE']
75310453SAndrew.Bardsley@arm.com    CacheDir(main['M5_BUILD_CACHE'])
7543118Sstever@eecs.umich.edu
75510453SAndrew.Bardsley@arm.commain['USE_PYTHON'] = not GetOption('without_python')
75610453SAndrew.Bardsley@arm.comif main['USE_PYTHON']:
75710453SAndrew.Bardsley@arm.com    # Find Python include and library directories for embedding the
75810453SAndrew.Bardsley@arm.com    # interpreter. We rely on python-config to resolve the appropriate
7593118Sstever@eecs.umich.edu    # includes and linker flags. ParseConfig does not seem to understand
7603483Ssaidi@eecs.umich.edu    # the more exotic linker flags such as -Xlinker and -export-dynamic so
7613494Ssaidi@eecs.umich.edu    # we add them explicitly below. If you want to link in an alternate
7623494Ssaidi@eecs.umich.edu    # version of python, see above for instructions on how to invoke
7633483Ssaidi@eecs.umich.edu    # scons with the appropriate PATH set.
7643483Ssaidi@eecs.umich.edu    #
7653483Ssaidi@eecs.umich.edu    # First we check if python2-config exists, else we use python-config
7663053Sstever@eecs.umich.edu    python_config = readCommand(['which', 'python2-config'],
7673053Sstever@eecs.umich.edu                                exception='').strip()
7683918Ssaidi@eecs.umich.edu    if not os.path.exists(python_config):
7693053Sstever@eecs.umich.edu        python_config = readCommand(['which', 'python-config'],
7703053Sstever@eecs.umich.edu                                    exception='').strip()
7713053Sstever@eecs.umich.edu    py_includes = readCommand([python_config, '--includes'],
7723053Sstever@eecs.umich.edu                              exception='').split()
7733053Sstever@eecs.umich.edu    # Strip the -I from the include folders before adding them to the
7749396Sandreas.hansson@arm.com    # CPPPATH
7759396Sandreas.hansson@arm.com    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
7769396Sandreas.hansson@arm.com
7779396Sandreas.hansson@arm.com    # Read the linker flags and split them into libraries and other link
7789396Sandreas.hansson@arm.com    # flags. The libraries are added later through the call the CheckLib.
7799396Sandreas.hansson@arm.com    py_ld_flags = readCommand([python_config, '--ldflags'],
7809396Sandreas.hansson@arm.com        exception='').split()
7819396Sandreas.hansson@arm.com    py_libs = []
7829396Sandreas.hansson@arm.com    for lib in py_ld_flags:
7839477Sandreas.hansson@arm.com         if not lib.startswith('-l'):
7849396Sandreas.hansson@arm.com             main.Append(LINKFLAGS=[lib])
7859477Sandreas.hansson@arm.com         else:
7869477Sandreas.hansson@arm.com             lib = lib[2:]
7879477Sandreas.hansson@arm.com             if lib not in py_libs:
7889477Sandreas.hansson@arm.com                 py_libs.append(lib)
7899396Sandreas.hansson@arm.com
7907840Snate@binkert.org    # verify that this stuff works
7917865Sgblack@eecs.umich.edu    if not conf.CheckHeader('Python.h', '<>'):
7927865Sgblack@eecs.umich.edu        print "Error: can't find Python.h header in", py_includes
7937865Sgblack@eecs.umich.edu        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
7947865Sgblack@eecs.umich.edu        Exit(1)
7957865Sgblack@eecs.umich.edu
7967840Snate@binkert.org    for lib in py_libs:
7979900Sandreas@sandberg.pp.se        if not conf.CheckLib(lib):
7989900Sandreas@sandberg.pp.se            print "Error: can't find library %s required by python" % lib
7999900Sandreas@sandberg.pp.se            Exit(1)
8009900Sandreas@sandberg.pp.se
80110456SCurtis.Dunham@arm.com# On Solaris you need to use libsocket for socket ops
80210456SCurtis.Dunham@arm.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
80310456SCurtis.Dunham@arm.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
80410456SCurtis.Dunham@arm.com       print "Can't find library with socket calls (e.g. accept())"
80510456SCurtis.Dunham@arm.com       Exit(1)
80610456SCurtis.Dunham@arm.com
80710456SCurtis.Dunham@arm.com# Check for zlib.  If the check passes, libz will be automatically
80810456SCurtis.Dunham@arm.com# added to the LIBS environment variable.
80910456SCurtis.Dunham@arm.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
81010456SCurtis.Dunham@arm.com    print 'Error: did not find needed zlib compression library '\
8119045SAli.Saidi@ARM.com          'and/or zlib.h header file.'
81211235Sandreas.sandberg@arm.com    print '       Please install zlib and try again.'
81311235Sandreas.sandberg@arm.com    Exit(1)
81411235Sandreas.sandberg@arm.com
81511235Sandreas.sandberg@arm.com# If we have the protobuf compiler, also make sure we have the
81611235Sandreas.sandberg@arm.com# development libraries. If the check passes, libprotobuf will be
81711235Sandreas.sandberg@arm.com# automatically added to the LIBS environment variable. After
81811235Sandreas.sandberg@arm.com# this, we can use the HAVE_PROTOBUF flag to determine if we have
81911235Sandreas.sandberg@arm.com# got both protoc and libprotobuf available.
82011811Sbaz21@cam.ac.ukmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
82111811Sbaz21@cam.ac.uk    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
82211811Sbaz21@cam.ac.uk                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
82311811Sbaz21@cam.ac.uk
82411811Sbaz21@cam.ac.uk# If we have the compiler but not the library, print another warning.
82511235Sandreas.sandberg@arm.comif main['PROTOC'] and not main['HAVE_PROTOBUF']:
82611235Sandreas.sandberg@arm.com    print termcap.Yellow + termcap.Bold + \
82711235Sandreas.sandberg@arm.com        'Warning: did not find protocol buffer library and/or headers.\n' + \
82811235Sandreas.sandberg@arm.com    '       Please install libprotobuf-dev for tracing support.' + \
82911235Sandreas.sandberg@arm.com    termcap.Normal
83011235Sandreas.sandberg@arm.com
83111235Sandreas.sandberg@arm.com# Check for librt.
8327840Snate@binkert.orghave_posix_clock = \
8337840Snate@binkert.org    conf.CheckLibWithHeader(None, 'time.h', 'C',
8347840Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
8351858SN/A    conf.CheckLibWithHeader('rt', 'time.h', 'C',
8361858SN/A                            'clock_nanosleep(0,0,NULL,NULL);')
8371858SN/A
8381858SN/Ahave_posix_timers = \
8391858SN/A    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
8401858SN/A                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
84112230Sgiacomo.travaglini@arm.com
84212230Sgiacomo.travaglini@arm.comif not GetOption('without_tcmalloc'):
84312230Sgiacomo.travaglini@arm.com    if conf.CheckLib('tcmalloc'):
84412230Sgiacomo.travaglini@arm.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
84512230Sgiacomo.travaglini@arm.com    elif conf.CheckLib('tcmalloc_minimal'):
84612230Sgiacomo.travaglini@arm.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
84712230Sgiacomo.travaglini@arm.com    else:
84812230Sgiacomo.travaglini@arm.com        print termcap.Yellow + termcap.Bold + \
8499903Sandreas.hansson@arm.com              "You can get a 12% performance improvement by "\
8509903Sandreas.hansson@arm.com              "installing tcmalloc (libgoogle-perftools-dev package "\
8519903Sandreas.hansson@arm.com              "on Ubuntu or RedHat)." + termcap.Normal
8529903Sandreas.hansson@arm.com
85310841Sandreas.sandberg@arm.com
8549651SAndreas.Sandberg@ARM.com# Detect back trace implementations. The last implementation in the
8559903Sandreas.hansson@arm.com# list will be used by default.
8569651SAndreas.Sandberg@ARM.combacktrace_impls = [ "none" ]
8579651SAndreas.Sandberg@ARM.com
85812056Sgabeblack@google.comif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
85912056Sgabeblack@google.com                           'backtrace_symbols_fd((void*)0, 0, 0);'):
86012056Sgabeblack@google.com    backtrace_impls.append("glibc")
86112056Sgabeblack@google.comelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
86212056Sgabeblack@google.com                           'backtrace_symbols_fd((void*)0, 0, 0);'):
86310841Sandreas.sandberg@arm.com    # NetBSD and FreeBSD need libexecinfo.
86410841Sandreas.sandberg@arm.com    backtrace_impls.append("glibc")
86510841Sandreas.sandberg@arm.com    main.Append(LIBS=['execinfo'])
86610841Sandreas.sandberg@arm.com
86710841Sandreas.sandberg@arm.comif backtrace_impls[-1] == "none":
86810841Sandreas.sandberg@arm.com    default_backtrace_impl = "none"
8699651SAndreas.Sandberg@ARM.com    print termcap.Yellow + termcap.Bold + \
8709651SAndreas.Sandberg@ARM.com        "No suitable back trace implementation found." + \
8719651SAndreas.Sandberg@ARM.com        termcap.Normal
8729651SAndreas.Sandberg@ARM.com
8739651SAndreas.Sandberg@ARM.comif not have_posix_clock:
8749651SAndreas.Sandberg@ARM.com    print "Can't find library for POSIX clocks."
8759651SAndreas.Sandberg@ARM.com
8769651SAndreas.Sandberg@ARM.com# Check for <fenv.h> (C99 FP environment control)
8779651SAndreas.Sandberg@ARM.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
87810841Sandreas.sandberg@arm.comif not have_fenv:
87910841Sandreas.sandberg@arm.com    print "Warning: Header file <fenv.h> not found."
88010841Sandreas.sandberg@arm.com    print "         This host has no IEEE FP rounding mode control."
88110841Sandreas.sandberg@arm.com
88210841Sandreas.sandberg@arm.com# Check for <png.h> (libpng library needed if wanting to dump
88310841Sandreas.sandberg@arm.com# frame buffer image in png format)
88410860Sandreas.sandberg@arm.comhave_png = conf.CheckHeader('png.h', '<>')
88510841Sandreas.sandberg@arm.comif not have_png:
88610841Sandreas.sandberg@arm.com    print "Warning: Header file <png.h> not found."
88710841Sandreas.sandberg@arm.com    print "         This host has no libpng library."
88810841Sandreas.sandberg@arm.com    print "         Disabling support for PNG framebuffers."
88910841Sandreas.sandberg@arm.com
89010841Sandreas.sandberg@arm.com# Check if we should enable KVM-based hardware virtualization. The API
89110841Sandreas.sandberg@arm.com# we rely on exists since version 2.6.36 of the kernel, but somehow
89210841Sandreas.sandberg@arm.com# the KVM_API_VERSION does not reflect the change. We test for one of
89310841Sandreas.sandberg@arm.com# the types as a fall back.
89410841Sandreas.sandberg@arm.comhave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
89510841Sandreas.sandberg@arm.comif not have_kvm:
8969651SAndreas.Sandberg@ARM.com    print "Info: Compatible header file <linux/kvm.h> not found, " \
8979651SAndreas.Sandberg@ARM.com        "disabling KVM support."
8989986Sandreas@sandberg.pp.se
8999986Sandreas@sandberg.pp.se# Check if the TUN/TAP driver is available.
9009986Sandreas@sandberg.pp.sehave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
9019986Sandreas@sandberg.pp.seif not have_tuntap:
9029986Sandreas@sandberg.pp.se    print "Info: Compatible header file <linux/if_tun.h> not found."
9039986Sandreas@sandberg.pp.se
9045863Snate@binkert.org# x86 needs support for xsave. We test for the structure here since we
9055863Snate@binkert.org# won't be able to run new tests by the time we know which ISA we're
9065863Snate@binkert.org# targeting.
9075863Snate@binkert.orghave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
9086121Snate@binkert.org                                    '#include <linux/kvm.h>') != 0
9091858SN/A
9105863Snate@binkert.org# Check if the requested target ISA is compatible with the host
9115863Snate@binkert.orgdef is_isa_kvm_compatible(isa):
9125863Snate@binkert.org    try:
9135863Snate@binkert.org        import platform
9145863Snate@binkert.org        host_isa = platform.machine()
9152139SN/A    except:
9164202Sbinkertn@umich.edu        print "Warning: Failed to determine host ISA."
91711308Santhony.gutierrez@amd.com        return False
9184202Sbinkertn@umich.edu
91911308Santhony.gutierrez@amd.com    if not have_posix_timers:
9202139SN/A        print "Warning: Can not enable KVM, host seems to lack support " \
9216994Snate@binkert.org            "for POSIX timers"
9226994Snate@binkert.org        return False
9236994Snate@binkert.org
9246994Snate@binkert.org    if isa == "arm":
9256994Snate@binkert.org        return host_isa in ( "armv7l", "aarch64" )
9266994Snate@binkert.org    elif isa == "x86":
9276994Snate@binkert.org        if host_isa != "x86_64":
9286994Snate@binkert.org            return False
92910319SAndreas.Sandberg@ARM.com
9306994Snate@binkert.org        if not have_kvm_xsave:
9316994Snate@binkert.org            print "KVM on x86 requires xsave support in kernel headers."
9326994Snate@binkert.org            return False
9336994Snate@binkert.org
9346994Snate@binkert.org        return True
9356994Snate@binkert.org    else:
9366994Snate@binkert.org        return False
9376994Snate@binkert.org
9386994Snate@binkert.org
9396994Snate@binkert.org# Check if the exclude_host attribute is available. We want this to
9406994Snate@binkert.org# get accurate instruction counts in KVM.
9412155SN/Amain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
9425863Snate@binkert.org    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
9431869SN/A
9441869SN/A
9455863Snate@binkert.org######################################################################
9465863Snate@binkert.org#
9474202Sbinkertn@umich.edu# Finish the configuration
9486108Snate@binkert.org#
9496108Snate@binkert.orgmain = conf.Finish()
9506108Snate@binkert.org
9516108Snate@binkert.org######################################################################
9529219Spower.jg@gmail.com#
9539219Spower.jg@gmail.com# Collect all non-global variables
9549219Spower.jg@gmail.com#
9559219Spower.jg@gmail.com
9569219Spower.jg@gmail.com# Define the universe of supported ISAs
9579219Spower.jg@gmail.comall_isa_list = [ ]
9589219Spower.jg@gmail.comall_gpu_isa_list = [ ]
9599219Spower.jg@gmail.comExport('all_isa_list')
9604202Sbinkertn@umich.eduExport('all_gpu_isa_list')
9615863Snate@binkert.org
96210135SCurtis.Dunham@arm.comclass CpuModel(object):
9638474Sgblack@eecs.umich.edu    '''The CpuModel class encapsulates everything the ISA parser needs to
9645742Snate@binkert.org    know about a particular CPU model.'''
9658268Ssteve.reinhardt@amd.com
9668268Ssteve.reinhardt@amd.com    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9678268Ssteve.reinhardt@amd.com    dict = {}
9685742Snate@binkert.org
9695341Sstever@gmail.com    # Constructor.  Automatically adds models to CpuModel.dict.
9708474Sgblack@eecs.umich.edu    def __init__(self, name, default=False):
9718474Sgblack@eecs.umich.edu        self.name = name           # name of model
9725342Sstever@gmail.com
9734202Sbinkertn@umich.edu        # This cpu is enabled by default
9744202Sbinkertn@umich.edu        self.default = default
97511308Santhony.gutierrez@amd.com
9764202Sbinkertn@umich.edu        # Add self to dict
9775863Snate@binkert.org        if name in CpuModel.dict:
9785863Snate@binkert.org            raise AttributeError, "CpuModel '%s' already registered" % name
97911308Santhony.gutierrez@amd.com        CpuModel.dict[name] = self
9806994Snate@binkert.org
9816994Snate@binkert.orgExport('CpuModel')
98210319SAndreas.Sandberg@ARM.com
9835863Snate@binkert.org# Sticky variables get saved in the variables file so they persist from
9845863Snate@binkert.org# one invocation to the next (unless overridden, in which case the new
9855863Snate@binkert.org# value becomes sticky).
9865863Snate@binkert.orgsticky_vars = Variables(args=ARGUMENTS)
9875863Snate@binkert.orgExport('sticky_vars')
9885863Snate@binkert.org
9895863Snate@binkert.org# Sticky variables that should be exported
9905863Snate@binkert.orgexport_vars = []
9917840Snate@binkert.orgExport('export_vars')
9925863Snate@binkert.org
99312230Sgiacomo.travaglini@arm.com# For Ruby
99412230Sgiacomo.travaglini@arm.comall_protocols = []
99512230Sgiacomo.travaglini@arm.comExport('all_protocols')
99612230Sgiacomo.travaglini@arm.comprotocol_dirs = []
99712230Sgiacomo.travaglini@arm.comExport('protocol_dirs')
99812056Sgabeblack@google.comslicc_includes = []
99912056Sgabeblack@google.comExport('slicc_includes')
100012056Sgabeblack@google.com
100111308Santhony.gutierrez@amd.com# Walk the tree and execute all SConsopts scripts that wil add to the
10029219Spower.jg@gmail.com# above variables
10039219Spower.jg@gmail.comif GetOption('verbose'):
100411235Sandreas.sandberg@arm.com    print "Reading SConsopts"
100511235Sandreas.sandberg@arm.comfor bdir in [ base_dir ] + extras_dir_list:
10061869SN/A    if not isdir(bdir):
10071858SN/A        print "Error: directory '%s' does not exist" % bdir
10085863Snate@binkert.org        Exit(1)
100911308Santhony.gutierrez@amd.com    for root, dirs, files in os.walk(bdir):
101012061Sjason@lowepower.com        if 'SConsopts' in files:
101112230Sgiacomo.travaglini@arm.com            if GetOption('verbose'):
101212230Sgiacomo.travaglini@arm.com                print "Reading", joinpath(root, 'SConsopts')
10131858SN/A            SConscript(joinpath(root, 'SConsopts'))
1014955SN/A
1015955SN/Aall_isa_list.sort()
10161869SN/Aall_gpu_isa_list.sort()
10171869SN/A
10181869SN/Asticky_vars.AddVariables(
10191869SN/A    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
10201869SN/A    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
10215863Snate@binkert.org    ListVariable('CPU_MODELS', 'CPU models',
10225863Snate@binkert.org                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
10235863Snate@binkert.org                 sorted(CpuModel.dict.keys())),
10241869SN/A    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
10255863Snate@binkert.org                 False),
10261869SN/A    BoolVariable('SS_COMPATIBLE_FP',
10275863Snate@binkert.org                 'Make floating-point results compatible with SimpleScalar',
10281869SN/A                 False),
10291869SN/A    BoolVariable('USE_SSE2',
10301869SN/A                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
10311869SN/A                 False),
10328483Sgblack@eecs.umich.edu    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
10331869SN/A    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
10341869SN/A    BoolVariable('USE_PNG',  'Enable support for PNG images', have_png),
10351869SN/A    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability',
10361869SN/A                 False),
10375863Snate@binkert.org    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models',
10385863Snate@binkert.org                 have_kvm),
10391869SN/A    BoolVariable('USE_TUNTAP',
10405863Snate@binkert.org                 'Enable using a tap device to bridge to the host network',
10415863Snate@binkert.org                 have_tuntap),
10423356Sbinkertn@umich.edu    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
10433356Sbinkertn@umich.edu    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
10443356Sbinkertn@umich.edu                  all_protocols),
10453356Sbinkertn@umich.edu    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
10463356Sbinkertn@umich.edu                 backtrace_impls[-1], backtrace_impls)
10474781Snate@binkert.org    )
10485863Snate@binkert.org
10495863Snate@binkert.org# These variables get exported to #defines in config/*.hh (see src/SConscript).
10501869SN/Aexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
10511869SN/A                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
10521869SN/A                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST',
10536121Snate@binkert.org                'USE_PNG']
10541869SN/A
105511982Sgabeblack@google.com###################################################
105611982Sgabeblack@google.com#
105711982Sgabeblack@google.com# Define a SCons builder for configuration flag headers.
105811982Sgabeblack@google.com#
105911982Sgabeblack@google.com###################################################
106011982Sgabeblack@google.com
106111982Sgabeblack@google.com# This function generates a config header file that #defines the
106211982Sgabeblack@google.com# variable symbol to the current variable setting (0 or 1).  The source
106311982Sgabeblack@google.com# operands are the name of the variable and a Value node containing the
106411982Sgabeblack@google.com# value of the variable.
106511982Sgabeblack@google.comdef build_config_file(target, source, env):
106611982Sgabeblack@google.com    (variable, value) = [s.get_contents() for s in source]
106711982Sgabeblack@google.com    f = file(str(target[0]), 'w')
106811982Sgabeblack@google.com    print >> f, '#define', variable, value
106911982Sgabeblack@google.com    f.close()
107011982Sgabeblack@google.com    return None
107111982Sgabeblack@google.com
107211982Sgabeblack@google.com# Combine the two functions into a scons Action object.
107311982Sgabeblack@google.comconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
107411982Sgabeblack@google.com
107511982Sgabeblack@google.com# The emitter munges the source & target node lists to reflect what
107611982Sgabeblack@google.com# we're really doing.
107711982Sgabeblack@google.comdef config_emitter(target, source, env):
107811982Sgabeblack@google.com    # extract variable name from Builder arg
107911982Sgabeblack@google.com    variable = str(target[0])
108011982Sgabeblack@google.com    # True target is config header file
108111978Sgabeblack@google.com    target = joinpath('config', variable.lower() + '.hh')
108211978Sgabeblack@google.com    val = env[variable]
108312034Sgabeblack@google.com    if isinstance(val, bool):
108411978Sgabeblack@google.com        # Force value to 0/1
108511978Sgabeblack@google.com        val = int(val)
108611978Sgabeblack@google.com    elif isinstance(val, str):
108712034Sgabeblack@google.com        val = '"' + val + '"'
108811978Sgabeblack@google.com
108911978Sgabeblack@google.com    # Sources are variable name & value (packaged in SCons Value nodes)
109010915Sandreas.sandberg@arm.com    return ([target], [Value(variable), Value(val)])
109111986Sandreas.sandberg@arm.com
109211986Sandreas.sandberg@arm.comconfig_builder = Builder(emitter = config_emitter, action = config_action)
10931869SN/A
10941869SN/Amain.Append(BUILDERS = { 'ConfigFile' : config_builder })
109512015Sgabeblack@google.com
109612015Sgabeblack@google.com###################################################
109712015Sgabeblack@google.com#
109812015Sgabeblack@google.com# Builders for static and shared partially linked object files.
10993546Sgblack@eecs.umich.edu#
11003546Sgblack@eecs.umich.edu###################################################
11013546Sgblack@eecs.umich.edu
110212015Sgabeblack@google.compartial_static_builder = Builder(action=SCons.Defaults.LinkAction,
110312015Sgabeblack@google.com                                 src_suffix='$OBJSUFFIX',
110412015Sgabeblack@google.com                                 src_builder=['StaticObject', 'Object'],
110512015Sgabeblack@google.com                                 LINKFLAGS='$PLINKFLAGS',
110612015Sgabeblack@google.com                                 LIBS='')
110712015Sgabeblack@google.com
110812015Sgabeblack@google.comdef partial_shared_emitter(target, source, env):
110912015Sgabeblack@google.com    for tgt in target:
11103546Sgblack@eecs.umich.edu        tgt.attributes.shared = 1
111112015Sgabeblack@google.com    return (target, source)
111212015Sgabeblack@google.compartial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
111310196SCurtis.Dunham@arm.com                                 emitter=partial_shared_emitter,
111412015Sgabeblack@google.com                                 src_suffix='$SHOBJSUFFIX',
111512015Sgabeblack@google.com                                 src_builder='SharedObject',
111612015Sgabeblack@google.com                                 SHLINKFLAGS='$PSHLINKFLAGS',
111712015Sgabeblack@google.com                                 LIBS='')
111812015Sgabeblack@google.com
111912015Sgabeblack@google.commain.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
112012015Sgabeblack@google.com                         'PartialStatic' : partial_static_builder })
112112015Sgabeblack@google.com
112212015Sgabeblack@google.com# builds in ext are shared across all configs in the build root.
112312015Sgabeblack@google.comext_dir = abspath(joinpath(str(main.root), 'ext'))
112412015Sgabeblack@google.comext_build_dirs = []
11253546Sgblack@eecs.umich.edufor root, dirs, files in os.walk(ext_dir):
11263546Sgblack@eecs.umich.edu    if 'SConscript' in files:
11273546Sgblack@eecs.umich.edu        build_dir = os.path.relpath(root, ext_dir)
1128955SN/A        ext_build_dirs.append(build_dir)
1129955SN/A        main.SConscript(joinpath(root, 'SConscript'),
1130955SN/A                        variant_dir=joinpath(build_root, build_dir))
1131955SN/A
11325863Snate@binkert.orgmain.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
113310135SCurtis.Dunham@arm.com
113410135SCurtis.Dunham@arm.com###################################################
11355343Sstever@gmail.com#
11365343Sstever@gmail.com# This builder and wrapper method are used to set up a directory with
11376121Snate@binkert.org# switching headers. Those are headers which are in a generic location and
11385863Snate@binkert.org# that include more specific headers from a directory chosen at build time
11394773Snate@binkert.org# based on the current build settings.
11405863Snate@binkert.org#
11412632Sstever@eecs.umich.edu###################################################
11425863Snate@binkert.org
11432023SN/Adef build_switching_header(target, source, env):
11445863Snate@binkert.org    path = str(target[0])
11455863Snate@binkert.org    subdir = str(source[0])
11465863Snate@binkert.org    dp, fp = os.path.split(path)
11475863Snate@binkert.org    dp = os.path.relpath(os.path.realpath(dp),
11485863Snate@binkert.org                         os.path.realpath(env['BUILDDIR']))
11495863Snate@binkert.org    with open(path, 'w') as hdr:
11505863Snate@binkert.org        print >>hdr, '#include "%s/%s/%s"' % (dp, subdir, fp)
11515863Snate@binkert.org
115210135SCurtis.Dunham@arm.comswitching_header_action = MakeAction(build_switching_header,
115310135SCurtis.Dunham@arm.com                                     Transform('GENERATE'))
115412034Sgabeblack@google.com
115512034Sgabeblack@google.comswitching_header_builder = Builder(action=switching_header_action,
115612034Sgabeblack@google.com                                   source_factory=Value,
11572632Sstever@eecs.umich.edu                                   single_source=True)
11585863Snate@binkert.org
11592023SN/Amain.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
11602632Sstever@eecs.umich.edu
11615863Snate@binkert.orgdef switching_headers(self, headers, source):
11625342Sstever@gmail.com    for header in headers:
11635863Snate@binkert.org        self.SwitchingHeader(header, source)
11642632Sstever@eecs.umich.edu
11655863Snate@binkert.orgmain.AddMethod(switching_headers, 'SwitchingHeaders')
11665863Snate@binkert.org
11678267Ssteve.reinhardt@amd.com###################################################
11688120Sgblack@eecs.umich.edu#
11698267Ssteve.reinhardt@amd.com# Define build environments for selected configurations.
11708267Ssteve.reinhardt@amd.com#
11718267Ssteve.reinhardt@amd.com###################################################
11728267Ssteve.reinhardt@amd.com
11738267Ssteve.reinhardt@amd.comfor variant_path in variant_paths:
11748267Ssteve.reinhardt@amd.com    if not GetOption('silent'):
11758267Ssteve.reinhardt@amd.com        print "Building in", variant_path
11768267Ssteve.reinhardt@amd.com
11778267Ssteve.reinhardt@amd.com    # Make a copy of the build-root environment to use for this config.
11785863Snate@binkert.org    env = main.Clone()
11795863Snate@binkert.org    env['BUILDDIR'] = variant_path
11805863Snate@binkert.org
11812632Sstever@eecs.umich.edu    # variant_dir is the tail component of build path, and is used to
11828267Ssteve.reinhardt@amd.com    # determine the build parameters (e.g., 'ALPHA_SE')
11838267Ssteve.reinhardt@amd.com    (build_root, variant_dir) = splitpath(variant_path)
11848267Ssteve.reinhardt@amd.com
11852632Sstever@eecs.umich.edu    # Set env variables according to the build directory config.
11861888SN/A    sticky_vars.files = []
11875863Snate@binkert.org    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
11885863Snate@binkert.org    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
11891858SN/A    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
11908120Sgblack@eecs.umich.edu    current_vars_file = joinpath(build_root, 'variables', variant_dir)
11918120Sgblack@eecs.umich.edu    if isfile(current_vars_file):
11927756SAli.Saidi@ARM.com        sticky_vars.files.append(current_vars_file)
11932598SN/A        if not GetOption('silent'):
11945863Snate@binkert.org            print "Using saved variables file %s" % current_vars_file
11951858SN/A    elif variant_dir in ext_build_dirs:
11961858SN/A        # Things in ext are built without a variant directory.
11971858SN/A        continue
11985863Snate@binkert.org    else:
11991858SN/A        # Build dir-specific variables file doesn't exist.
12001858SN/A
12011858SN/A        # Make sure the directory is there so we can create it later
12025863Snate@binkert.org        opt_dir = dirname(current_vars_file)
12031871SN/A        if not isdir(opt_dir):
12041858SN/A            mkdir(opt_dir)
120512230Sgiacomo.travaglini@arm.com
120612230Sgiacomo.travaglini@arm.com        # Get default build variables from source tree.  Variables are
120712230Sgiacomo.travaglini@arm.com        # normally determined by name of $VARIANT_DIR, but can be
120812230Sgiacomo.travaglini@arm.com        # overridden by '--default=' arg on command line.
120912230Sgiacomo.travaglini@arm.com        default = GetOption('default')
121012230Sgiacomo.travaglini@arm.com        opts_dir = joinpath(main.root.abspath, 'build_opts')
121112230Sgiacomo.travaglini@arm.com        if default:
121212230Sgiacomo.travaglini@arm.com            default_vars_files = [joinpath(build_root, 'variables', default),
12131858SN/A                                  joinpath(opts_dir, default)]
12141858SN/A        else:
12151858SN/A            default_vars_files = [joinpath(opts_dir, variant_dir)]
12169651SAndreas.Sandberg@ARM.com        existing_files = filter(isfile, default_vars_files)
12179651SAndreas.Sandberg@ARM.com        if existing_files:
12189651SAndreas.Sandberg@ARM.com            default_vars_file = existing_files[0]
12199651SAndreas.Sandberg@ARM.com            sticky_vars.files.append(default_vars_file)
12209651SAndreas.Sandberg@ARM.com            print "Variables file %s not found,\n  using defaults in %s" \
12219651SAndreas.Sandberg@ARM.com                  % (current_vars_file, default_vars_file)
12229651SAndreas.Sandberg@ARM.com        else:
12239651SAndreas.Sandberg@ARM.com            print "Error: cannot find variables file %s or " \
12249651SAndreas.Sandberg@ARM.com                  "default file(s) %s" \
122512056Sgabeblack@google.com                  % (current_vars_file, ' or '.join(default_vars_files))
122612056Sgabeblack@google.com            Exit(1)
122712056Sgabeblack@google.com
122812056Sgabeblack@google.com    # Apply current variable settings to env
122912056Sgabeblack@google.com    sticky_vars.Update(env)
123011798Santhony.gutierrez@amd.com
123111798Santhony.gutierrez@amd.com    help_texts["local_vars"] += \
123211798Santhony.gutierrez@amd.com        "Build variables for %s:\n" % variant_dir \
12339986Sandreas@sandberg.pp.se                 + sticky_vars.GenerateHelpText(env)
12349986Sandreas@sandberg.pp.se
12359986Sandreas@sandberg.pp.se    # Process variable settings.
12369986Sandreas@sandberg.pp.se
12379986Sandreas@sandberg.pp.se    if not have_fenv and env['USE_FENV']:
12389986Sandreas@sandberg.pp.se        print "Warning: <fenv.h> not available; " \
12399986Sandreas@sandberg.pp.se              "forcing USE_FENV to False in", variant_dir + "."
12405863Snate@binkert.org        env['USE_FENV'] = False
12415863Snate@binkert.org
12421869SN/A    if not env['USE_FENV']:
12431965SN/A        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
12447739Sgblack@eecs.umich.edu        print "         FP results may deviate slightly from other platforms."
12451965SN/A
12462761Sstever@eecs.umich.edu    if not have_png and env['USE_PNG']:
12475863Snate@binkert.org        print "Warning: <png.h> not available; " \
12481869SN/A              "forcing USE_PNG to False in", variant_dir + "."
124910196SCurtis.Dunham@arm.com        env['USE_PNG'] = False
12501869SN/A
12518120Sgblack@eecs.umich.edu    if env['USE_PNG']:
12528120Sgblack@eecs.umich.edu        env.Append(LIBS=['png'])
12538120Sgblack@eecs.umich.edu
12548120Sgblack@eecs.umich.edu    if env['EFENCE']:
12558120Sgblack@eecs.umich.edu        env.Append(LIBS=['efence'])
12568120Sgblack@eecs.umich.edu
12578120Sgblack@eecs.umich.edu    if env['USE_KVM']:
12588120Sgblack@eecs.umich.edu        if not have_kvm:
12598120Sgblack@eecs.umich.edu            print "Warning: Can not enable KVM, host seems to lack KVM support"
12608120Sgblack@eecs.umich.edu            env['USE_KVM'] = False
12618120Sgblack@eecs.umich.edu        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
12628120Sgblack@eecs.umich.edu            print "Info: KVM support disabled due to unsupported host and " \
1263                "target ISA combination"
1264            env['USE_KVM'] = False
1265
1266    if env['USE_TUNTAP']:
1267        if not have_tuntap:
1268            print "Warning: Can't connect EtherTap with a tap device."
1269            env['USE_TUNTAP'] = False
1270
1271    if env['BUILD_GPU']:
1272        env.Append(CPPDEFINES=['BUILD_GPU'])
1273
1274    # Warn about missing optional functionality
1275    if env['USE_KVM']:
1276        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1277            print "Warning: perf_event headers lack support for the " \
1278                "exclude_host attribute. KVM instruction counts will " \
1279                "be inaccurate."
1280
1281    # Save sticky variable settings back to current variables file
1282    sticky_vars.Save(current_vars_file, env)
1283
1284    if env['USE_SSE2']:
1285        env.Append(CCFLAGS=['-msse2'])
1286
1287    # The src/SConscript file sets up the build rules in 'env' according
1288    # to the configured variables.  It returns a list of environments,
1289    # one for each variant build (debug, opt, etc.)
1290    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1291
1292# base help text
1293Help('''
1294Usage: scons [scons options] [build variables] [target(s)]
1295
1296Extra scons options:
1297%(options)s
1298
1299Global build variables:
1300%(global_vars)s
1301
1302%(local_vars)s
1303''' % help_texts)
1304