SConstruct revision 10278:362875aec1ba
1955SN/A# -*- mode:python -*-
2955SN/A
312230Sgiacomo.travaglini@arm.com# Copyright (c) 2013 ARM Limited
49812Sandreas.hansson@arm.com# All rights reserved.
59812Sandreas.hansson@arm.com#
69812Sandreas.hansson@arm.com# The license below extends only to copyright in the software and shall
79812Sandreas.hansson@arm.com# not be construed as granting a license to any other intellectual
89812Sandreas.hansson@arm.com# property including but not limited to intellectual property relating
99812Sandreas.hansson@arm.com# to a hardware implementation of the functionality of the software
109812Sandreas.hansson@arm.com# licensed hereunder.  You may use the software subject to the license
119812Sandreas.hansson@arm.com# terms below provided that you ensure that this notice is replicated
129812Sandreas.hansson@arm.com# unmodified and in its entirety in all distributions of the software,
139812Sandreas.hansson@arm.com# modified or unmodified, in source code or in binary form.
149812Sandreas.hansson@arm.com#
157816Ssteve.reinhardt@amd.com# Copyright (c) 2011 Advanced Micro Devices, Inc.
165871Snate@binkert.org# Copyright (c) 2009 The Hewlett-Packard Development Company
171762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
28955SN/A# contributors may be used to endorse or promote products derived from
29955SN/A# this software without specific prior written permission.
30955SN/A#
31955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422665Ssaidi@eecs.umich.edu#
432665Ssaidi@eecs.umich.edu# Authors: Steve Reinhardt
445863Snate@binkert.org#          Nathan Binkert
45955SN/A
46955SN/A###################################################
47955SN/A#
48955SN/A# SCons top-level build description (SConstruct) file.
49955SN/A#
508878Ssteve.reinhardt@amd.com# While in this directory ('gem5'), just type 'scons' to build the default
512632Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
528878Ssteve.reinhardt@amd.com# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532632Sstever@eecs.umich.edu# the optimized full-system version).
54955SN/A#
558878Ssteve.reinhardt@amd.com# You can build gem5 in a different directory as long as there is a
562632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572761Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582632Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612761Sstever@eecs.umich.edu#
622761Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
632761Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
648878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
658878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
662761Sstever@eecs.umich.edu#
672761Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
682761Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
692761Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
702761Sstever@eecs.umich.edu#   file.
718878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
728878Ssteve.reinhardt@amd.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732632Sstever@eecs.umich.edu#
742632Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
758878Ssteve.reinhardt@amd.com# 'gem5' directory (or use -u or -C to tell scons where to find this
768878Ssteve.reinhardt@amd.com# file), you can use 'scons -h' to print all the gem5-specific build
772632Sstever@eecs.umich.edu# options as well.
78955SN/A#
79955SN/A###################################################
80955SN/A
8112563Sgabeblack@google.com# Check for recent-enough Python and SCons versions.
8212563Sgabeblack@google.comtry:
836654Snate@binkert.org    # Really old versions of scons only take two options for the
8410196SCurtis.Dunham@arm.com    # function, so check once without the revision and once with the
85955SN/A    # revision, the first instance will fail for stuff other than
865396Ssaidi@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
8711401Sandreas.sandberg@arm.com    EnsureSConsVersion(0, 98)
885863Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
895863Snate@binkert.orgexcept SystemExit, e:
904202Sbinkertn@umich.edu    print """
915863Snate@binkert.orgFor more details, see:
925863Snate@binkert.org    http://gem5.org/Dependencies
935863Snate@binkert.org"""
945863Snate@binkert.org    raise
95955SN/A
966654Snate@binkert.org# We ensure the python version early because because python-config
975273Sstever@gmail.com# requires python 2.5
985871Snate@binkert.orgtry:
995273Sstever@gmail.com    EnsurePythonVersion(2, 5)
1006654Snate@binkert.orgexcept SystemExit, e:
1015396Ssaidi@eecs.umich.edu    print """
1028120Sgblack@eecs.umich.eduYou can use a non-default installation of the Python interpreter by
1038120Sgblack@eecs.umich.edurearranging your PATH so that scons finds the non-default 'python' and
1048120Sgblack@eecs.umich.edu'python-config' first.
1058120Sgblack@eecs.umich.edu
1068120Sgblack@eecs.umich.eduFor more details, see:
1078120Sgblack@eecs.umich.edu    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1088120Sgblack@eecs.umich.edu"""
1098120Sgblack@eecs.umich.edu    raise
1108879Ssteve.reinhardt@amd.com
1118879Ssteve.reinhardt@amd.com# Global Python includes
1128879Ssteve.reinhardt@amd.comimport itertools
1138879Ssteve.reinhardt@amd.comimport os
1148879Ssteve.reinhardt@amd.comimport re
1158879Ssteve.reinhardt@amd.comimport subprocess
1168879Ssteve.reinhardt@amd.comimport sys
1178879Ssteve.reinhardt@amd.com
1188879Ssteve.reinhardt@amd.comfrom os import mkdir, environ
1198879Ssteve.reinhardt@amd.comfrom os.path import abspath, basename, dirname, expanduser, normpath
1208879Ssteve.reinhardt@amd.comfrom os.path import exists,  isdir, isfile
1218879Ssteve.reinhardt@amd.comfrom os.path import join as joinpath, split as splitpath
1228879Ssteve.reinhardt@amd.com
1238120Sgblack@eecs.umich.edu# SCons includes
1248120Sgblack@eecs.umich.eduimport SCons
1258120Sgblack@eecs.umich.eduimport SCons.Node
1268120Sgblack@eecs.umich.edu
1278120Sgblack@eecs.umich.eduextra_python_paths = [
1288120Sgblack@eecs.umich.edu    Dir('src/python').srcnode().abspath, # gem5 includes
1298120Sgblack@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1308120Sgblack@eecs.umich.edu    ]
1318120Sgblack@eecs.umich.edu
1328120Sgblack@eecs.umich.edusys.path[1:1] = extra_python_paths
1338120Sgblack@eecs.umich.edu
1348120Sgblack@eecs.umich.edufrom m5.util import compareVersions, readCommand
1358120Sgblack@eecs.umich.edufrom m5.util.terminal import get_termcap
1368120Sgblack@eecs.umich.edu
1378879Ssteve.reinhardt@amd.comhelp_texts = {
1388879Ssteve.reinhardt@amd.com    "options" : "",
1398879Ssteve.reinhardt@amd.com    "global_vars" : "",
1408879Ssteve.reinhardt@amd.com    "local_vars" : ""
14110458Sandreas.hansson@arm.com}
14210458Sandreas.hansson@arm.com
14310458Sandreas.hansson@arm.comExport("help_texts")
1448879Ssteve.reinhardt@amd.com
1458879Ssteve.reinhardt@amd.com
1468879Ssteve.reinhardt@amd.com# There's a bug in scons in that (1) by default, the help texts from
1478879Ssteve.reinhardt@amd.com# AddOption() are supposed to be displayed when you type 'scons -h'
1489227Sandreas.hansson@arm.com# and (2) you can override the help displayed by 'scons -h' using the
1499227Sandreas.hansson@arm.com# Help() function, but these two features are incompatible: once
15012063Sgabeblack@google.com# you've overridden the help text using Help(), there's no way to get
15112063Sgabeblack@google.com# at the help texts from AddOptions.  See:
15212063Sgabeblack@google.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1538879Ssteve.reinhardt@amd.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1548879Ssteve.reinhardt@amd.com# This hack lets us extract the help text from AddOptions and
1558879Ssteve.reinhardt@amd.com# re-inject it via Help().  Ideally someday this bug will be fixed and
1568879Ssteve.reinhardt@amd.com# we can just use AddOption directly.
15710453SAndrew.Bardsley@arm.comdef AddLocalOption(*args, **kwargs):
15810453SAndrew.Bardsley@arm.com    col_width = 30
15910453SAndrew.Bardsley@arm.com
16010456SCurtis.Dunham@arm.com    help = "  " + ", ".join(args)
16110456SCurtis.Dunham@arm.com    if "help" in kwargs:
16210456SCurtis.Dunham@arm.com        length = len(help)
16310457Sandreas.hansson@arm.com        if length >= col_width:
16410457Sandreas.hansson@arm.com            help += "\n" + " " * col_width
16511342Sandreas.hansson@arm.com        else:
16611342Sandreas.hansson@arm.com            help += " " * (col_width - length)
1678120Sgblack@eecs.umich.edu        help += kwargs["help"]
16812063Sgabeblack@google.com    help_texts["options"] += help + "\n"
16912563Sgabeblack@google.com
17012063Sgabeblack@google.com    AddOption(*args, **kwargs)
17112063Sgabeblack@google.com
1725871Snate@binkert.orgAddLocalOption('--colors', dest='use_colors', action='store_true',
1735871Snate@binkert.org               help="Add color to abbreviated scons output")
1746121Snate@binkert.orgAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1755871Snate@binkert.org               help="Don't add color to abbreviated scons output")
1765871Snate@binkert.orgAddLocalOption('--default', dest='default', type='string', action='store',
1779926Sstan.czerniawski@arm.com               help='Override which build_opts file to use for defaults')
17812243Sgabeblack@google.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1791533SN/A               help='Disable style checking hooks')
18012246Sgabeblack@google.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
18112246Sgabeblack@google.com               help='Disable Link-Time Optimization for fast')
18212246Sgabeblack@google.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
18312246Sgabeblack@google.com               help='Update test reference outputs')
1849239Sandreas.hansson@arm.comAddLocalOption('--verbose', dest='verbose', action='store_true',
1859239Sandreas.hansson@arm.com               help='Print full tool command lines')
1869239Sandreas.hansson@arm.com
1879239Sandreas.hansson@arm.comtermcap = get_termcap(GetOption('use_colors'))
18812563Sgabeblack@google.com
1899239Sandreas.hansson@arm.com########################################################################
1909239Sandreas.hansson@arm.com#
191955SN/A# Set up the main build environment.
192955SN/A#
1932632Sstever@eecs.umich.edu########################################################################
1942632Sstever@eecs.umich.edu
195955SN/A# export TERM so that clang reports errors in color
196955SN/Ause_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
197955SN/A                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
198955SN/A                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
1998878Ssteve.reinhardt@amd.com
200955SN/Ause_prefixes = [
2012632Sstever@eecs.umich.edu    "M5",           # M5 configuration (e.g., path to kernels)
2022632Sstever@eecs.umich.edu    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
2032632Sstever@eecs.umich.edu    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2042632Sstever@eecs.umich.edu    "CCC_",         # clang static analyzer configuration
2052632Sstever@eecs.umich.edu    ]
2062632Sstever@eecs.umich.edu
2072632Sstever@eecs.umich.eduuse_env = {}
2088268Ssteve.reinhardt@amd.comfor key,val in os.environ.iteritems():
2098268Ssteve.reinhardt@amd.com    if key in use_vars or \
2108268Ssteve.reinhardt@amd.com            any([key.startswith(prefix) for prefix in use_prefixes]):
2118268Ssteve.reinhardt@amd.com        use_env[key] = val
2128268Ssteve.reinhardt@amd.com
2138268Ssteve.reinhardt@amd.commain = Environment(ENV=use_env)
2148268Ssteve.reinhardt@amd.commain.Decider('MD5-timestamp')
2152632Sstever@eecs.umich.edumain.root = Dir(".")         # The current directory (where this file lives).
2162632Sstever@eecs.umich.edumain.srcdir = Dir("src")     # The source directory
2172632Sstever@eecs.umich.edu
2182632Sstever@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
2198268Ssteve.reinhardt@amd.com
2202632Sstever@eecs.umich.edu# Check that we have a C/C++ compiler
2218268Ssteve.reinhardt@amd.comif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2228268Ssteve.reinhardt@amd.com    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2238268Ssteve.reinhardt@amd.com    Exit(1)
2248268Ssteve.reinhardt@amd.com
2253718Sstever@eecs.umich.edu# Check that swig is present
2262634Sstever@eecs.umich.eduif not 'SWIG' in main_dict_keys:
2272634Sstever@eecs.umich.edu    print "swig is not installed (package swig on Ubuntu and RedHat)"
2285863Snate@binkert.org    Exit(1)
2292638Sstever@eecs.umich.edu
2308268Ssteve.reinhardt@amd.com# add useful python code PYTHONPATH so it can be used by subprocesses
2312632Sstever@eecs.umich.edu# as well
2322632Sstever@eecs.umich.edumain.AppendENVPath('PYTHONPATH', extra_python_paths)
2332632Sstever@eecs.umich.edu
2342632Sstever@eecs.umich.edu########################################################################
23512563Sgabeblack@google.com#
2361858SN/A# Mercurial Stuff.
2373716Sstever@eecs.umich.edu#
2382638Sstever@eecs.umich.edu# If the gem5 directory is a mercurial repository, we should do some
2392638Sstever@eecs.umich.edu# extra things.
2402638Sstever@eecs.umich.edu#
2412638Sstever@eecs.umich.edu########################################################################
24212563Sgabeblack@google.com
24312563Sgabeblack@google.comhgdir = main.root.Dir(".hg")
2442638Sstever@eecs.umich.edu
2455863Snate@binkert.orgmercurial_style_message = """
2465863Snate@binkert.orgYou're missing the gem5 style hook, which automatically checks your code
2475863Snate@binkert.orgagainst the gem5 style rules on hg commit and qrefresh commands.  This
248955SN/Ascript will now install the hook in your .hg/hgrc file.
2495341Sstever@gmail.comPress enter to continue, or ctrl-c to abort: """
2505341Sstever@gmail.com
2515863Snate@binkert.orgmercurial_style_hook = """
2527756SAli.Saidi@ARM.com# The following lines were automatically added by gem5/SConstruct
2535341Sstever@gmail.com# to provide the gem5 style-checking hooks
2546121Snate@binkert.org[extensions]
2554494Ssaidi@eecs.umich.edustyle = %s/util/style.py
2566121Snate@binkert.org
2571105SN/A[hooks]
2582667Sstever@eecs.umich.edupretxncommit.style = python:style.check_style
2592667Sstever@eecs.umich.edupre-qrefresh.style = python:style.check_style
2602667Sstever@eecs.umich.edu# End of SConstruct additions
2612667Sstever@eecs.umich.edu
2626121Snate@binkert.org""" % (main.root.abspath)
2632667Sstever@eecs.umich.edu
2645341Sstever@gmail.commercurial_lib_not_found = """
2655863Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2665341Sstever@gmail.comyou are a gem5 developer, please fix this and run the style
2675341Sstever@gmail.comhook. It is important.
2685341Sstever@gmail.com"""
2698120Sgblack@eecs.umich.edu
2705341Sstever@gmail.com# Check for style hook and prompt for installation if it's not there.
2718120Sgblack@eecs.umich.edu# Skip this if --ignore-style was specified, there's no .hg dir to
2725341Sstever@gmail.com# install a hook in, or there's no interactive terminal to prompt.
2738120Sgblack@eecs.umich.eduif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2746121Snate@binkert.org    style_hook = True
2756121Snate@binkert.org    try:
2769396Sandreas.hansson@arm.com        from mercurial import ui
2775397Ssaidi@eecs.umich.edu        ui = ui.ui()
2785397Ssaidi@eecs.umich.edu        ui.readconfig(hgdir.File('hgrc').abspath)
2797727SAli.Saidi@ARM.com        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2808268Ssteve.reinhardt@amd.com                     ui.config('hooks', 'pre-qrefresh.style', None)
2816168Snate@binkert.org    except ImportError:
2825341Sstever@gmail.com        print mercurial_lib_not_found
2838120Sgblack@eecs.umich.edu
2848120Sgblack@eecs.umich.edu    if not style_hook:
2858120Sgblack@eecs.umich.edu        print mercurial_style_message,
2866814Sgblack@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
2875863Snate@binkert.org        try:
2888120Sgblack@eecs.umich.edu            raw_input()
2895341Sstever@gmail.com        except:
2905863Snate@binkert.org            print "Input exception, exiting scons.\n"
2918268Ssteve.reinhardt@amd.com            sys.exit(1)
2926121Snate@binkert.org        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2936121Snate@binkert.org        print "Adding style hook to", hgrc_path, "\n"
2948268Ssteve.reinhardt@amd.com        try:
2955742Snate@binkert.org            hgrc = open(hgrc_path, 'a')
2965742Snate@binkert.org            hgrc.write(mercurial_style_hook)
2975341Sstever@gmail.com            hgrc.close()
2985742Snate@binkert.org        except:
2995742Snate@binkert.org            print "Error updating", hgrc_path
3005341Sstever@gmail.com            sys.exit(1)
3016017Snate@binkert.org
3026121Snate@binkert.org
3036017Snate@binkert.org###################################################
30412158Sandreas.sandberg@arm.com#
30512158Sandreas.sandberg@arm.com# Figure out which configurations to set up based on the path(s) of
30612158Sandreas.sandberg@arm.com# the target(s).
3078120Sgblack@eecs.umich.edu#
3087756SAli.Saidi@ARM.com###################################################
3097756SAli.Saidi@ARM.com
3107756SAli.Saidi@ARM.com# Find default configuration & binary.
3117756SAli.Saidi@ARM.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3127816Ssteve.reinhardt@amd.com
3137816Ssteve.reinhardt@amd.com# helper function: find last occurrence of element in list
3147816Ssteve.reinhardt@amd.comdef rfind(l, elt, offs = -1):
3157816Ssteve.reinhardt@amd.com    for i in range(len(l)+offs, 0, -1):
3167816Ssteve.reinhardt@amd.com        if l[i] == elt:
31711979Sgabeblack@google.com            return i
3187816Ssteve.reinhardt@amd.com    raise ValueError, "element not found"
3197816Ssteve.reinhardt@amd.com
3207816Ssteve.reinhardt@amd.com# Take a list of paths (or SCons Nodes) and return a list with all
3217816Ssteve.reinhardt@amd.com# paths made absolute and ~-expanded.  Paths will be interpreted
3227756SAli.Saidi@ARM.com# relative to the launch directory unless a different root is provided
3237756SAli.Saidi@ARM.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3249227Sandreas.hansson@arm.com    return [abspath(joinpath(root, expanduser(str(p))))
3259227Sandreas.hansson@arm.com            for p in path_list]
3269227Sandreas.hansson@arm.com
3279227Sandreas.hansson@arm.com# Each target must have 'build' in the interior of the path; the
3289590Sandreas@sandberg.pp.se# directory below this will determine the build parameters.  For
3299590Sandreas@sandberg.pp.se# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3309590Sandreas@sandberg.pp.se# recognize that ALPHA_SE specifies the configuration because it
3319590Sandreas@sandberg.pp.se# follow 'build' in the build path.
3329590Sandreas@sandberg.pp.se
3339590Sandreas@sandberg.pp.se# The funky assignment to "[:]" is needed to replace the list contents
3346654Snate@binkert.org# in place rather than reassign the symbol to a new list, which
3356654Snate@binkert.org# doesn't work (obviously!).
3365871Snate@binkert.orgBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3376121Snate@binkert.org
3388946Sandreas.hansson@arm.com# Generate a list of the unique build roots and configs that the
3399419Sandreas.hansson@arm.com# collected targets reference.
34012563Sgabeblack@google.comvariant_paths = []
3413918Ssaidi@eecs.umich.edubuild_root = None
3423918Ssaidi@eecs.umich.edufor t in BUILD_TARGETS:
3431858SN/A    path_dirs = t.split('/')
3449556Sandreas.hansson@arm.com    try:
3459556Sandreas.hansson@arm.com        build_top = rfind(path_dirs, 'build', -2)
3469556Sandreas.hansson@arm.com    except:
3479556Sandreas.hansson@arm.com        print "Error: no non-leaf 'build' dir found on target path", t
34811294Sandreas.hansson@arm.com        Exit(1)
34911294Sandreas.hansson@arm.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
35011294Sandreas.hansson@arm.com    if not build_root:
35111294Sandreas.hansson@arm.com        build_root = this_build_root
35210878Sandreas.hansson@arm.com    else:
35310878Sandreas.hansson@arm.com        if this_build_root != build_root:
35411811Sbaz21@cam.ac.uk            print "Error: build targets not under same build root\n"\
35511811Sbaz21@cam.ac.uk                  "  %s\n  %s" % (build_root, this_build_root)
35611811Sbaz21@cam.ac.uk            Exit(1)
35711982Sgabeblack@google.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
35811982Sgabeblack@google.com    if variant_path not in variant_paths:
35911982Sgabeblack@google.com        variant_paths.append(variant_path)
36011982Sgabeblack@google.com
36111992Sgabeblack@google.com# Make sure build_root exists (might not if this is the first build there)
36211982Sgabeblack@google.comif not isdir(build_root):
36311982Sgabeblack@google.com    mkdir(build_root)
36412305Sgabeblack@google.commain['BUILDROOT'] = build_root
36512305Sgabeblack@google.com
36612305Sgabeblack@google.comExport('main')
36712305Sgabeblack@google.com
36812305Sgabeblack@google.commain.SConsignFile(joinpath(build_root, "sconsign"))
36912305Sgabeblack@google.com
37012305Sgabeblack@google.com# Default duplicate option is to use hard links, but this messes up
3719556Sandreas.hansson@arm.com# when you use emacs to edit a file in the target dir, as emacs moves
37212563Sgabeblack@google.com# file to file~ then copies to file, breaking the link.  Symbolic
37312563Sgabeblack@google.com# (soft) links work better.
37412563Sgabeblack@google.commain.SetOption('duplicate', 'soft-copy')
37512563Sgabeblack@google.com
3769556Sandreas.hansson@arm.com#
37712563Sgabeblack@google.com# Set up global sticky variables... these are common to an entire build
37812563Sgabeblack@google.com# tree (not specific to a particular build like ALPHA_SE)
3799556Sandreas.hansson@arm.com#
38012563Sgabeblack@google.com
38112563Sgabeblack@google.comglobal_vars_file = joinpath(build_root, 'variables.global')
38212563Sgabeblack@google.com
38312563Sgabeblack@google.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
38412563Sgabeblack@google.com
38512563Sgabeblack@google.comglobal_vars.AddVariables(
38612563Sgabeblack@google.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
38712563Sgabeblack@google.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3889556Sandreas.hansson@arm.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3899556Sandreas.hansson@arm.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3906121Snate@binkert.org    ('BATCH', 'Use batch pool for build and tests', False),
39111500Sandreas.hansson@arm.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
39210238Sandreas.hansson@arm.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
39310878Sandreas.hansson@arm.com    ('EXTRAS', 'Add extra directories to the compilation', '')
3949420Sandreas.hansson@arm.com    )
39511500Sandreas.hansson@arm.com
39612563Sgabeblack@google.com# Update main environment with values from ARGUMENTS & global_vars_file
39712563Sgabeblack@google.comglobal_vars.Update(main)
3989420Sandreas.hansson@arm.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3999420Sandreas.hansson@arm.com
4009420Sandreas.hansson@arm.com# Save sticky variable settings back to current variables file
4019420Sandreas.hansson@arm.comglobal_vars.Save(global_vars_file, main)
40212063Sgabeblack@google.com
40312063Sgabeblack@google.com# Parse EXTRAS variable to build list of all directories where we're
40412063Sgabeblack@google.com# look for sources etc.  This list is exported as extras_dir_list.
40512063Sgabeblack@google.combase_dir = main.srcdir.abspath
40612063Sgabeblack@google.comif main['EXTRAS']:
40712063Sgabeblack@google.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
40812063Sgabeblack@google.comelse:
40912063Sgabeblack@google.com    extras_dir_list = []
41012063Sgabeblack@google.com
41112063Sgabeblack@google.comExport('base_dir')
41212063Sgabeblack@google.comExport('extras_dir_list')
41312063Sgabeblack@google.com
41412063Sgabeblack@google.com# the ext directory should be on the #includes path
41512063Sgabeblack@google.commain.Append(CPPPATH=[Dir('ext')])
41612063Sgabeblack@google.com
41712063Sgabeblack@google.comdef strip_build_path(path, env):
41812063Sgabeblack@google.com    path = str(path)
41912063Sgabeblack@google.com    variant_base = env['BUILDROOT'] + os.path.sep
42012063Sgabeblack@google.com    if path.startswith(variant_base):
42112063Sgabeblack@google.com        path = path[len(variant_base):]
42212063Sgabeblack@google.com    elif path.startswith('build/'):
42312063Sgabeblack@google.com        path = path[6:]
42410264Sandreas.hansson@arm.com    return path
42510264Sandreas.hansson@arm.com
42610264Sandreas.hansson@arm.com# Generate a string of the form:
42710264Sandreas.hansson@arm.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
42811925Sgabeblack@google.com# to print while building.
42911925Sgabeblack@google.comclass Transform(object):
43011500Sandreas.hansson@arm.com    # all specific color settings should be here and nowhere else
43110264Sandreas.hansson@arm.com    tool_color = termcap.Normal
43211500Sandreas.hansson@arm.com    pfx_color = termcap.Yellow
43311500Sandreas.hansson@arm.com    srcs_color = termcap.Yellow + termcap.Bold
43411500Sandreas.hansson@arm.com    arrow_color = termcap.Blue + termcap.Bold
43511500Sandreas.hansson@arm.com    tgts_color = termcap.Yellow + termcap.Bold
43610866Sandreas.hansson@arm.com
43711500Sandreas.hansson@arm.com    def __init__(self, tool, max_sources=99):
43812563Sgabeblack@google.com        self.format = self.tool_color + (" [%8s] " % tool) \
43912563Sgabeblack@google.com                      + self.pfx_color + "%s" \
44012563Sgabeblack@google.com                      + self.srcs_color + "%s" \
44112563Sgabeblack@google.com                      + self.arrow_color + " -> " \
44212563Sgabeblack@google.com                      + self.tgts_color + "%s" \
44312563Sgabeblack@google.com                      + termcap.Normal
44410264Sandreas.hansson@arm.com        self.max_sources = max_sources
44510457Sandreas.hansson@arm.com
44610457Sandreas.hansson@arm.com    def __call__(self, target, source, env, for_signature=None):
44710457Sandreas.hansson@arm.com        # truncate source list according to max_sources param
44810457Sandreas.hansson@arm.com        source = source[0:self.max_sources]
44910457Sandreas.hansson@arm.com        def strip(f):
45012563Sgabeblack@google.com            return strip_build_path(str(f), env)
45112563Sgabeblack@google.com        if len(source) > 0:
45212563Sgabeblack@google.com            srcs = map(strip, source)
45310457Sandreas.hansson@arm.com        else:
45412063Sgabeblack@google.com            srcs = ['']
45512063Sgabeblack@google.com        tgts = map(strip, target)
45612063Sgabeblack@google.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
45712563Sgabeblack@google.com        # operation that has nothing to do with paths.
45812563Sgabeblack@google.com        com_pfx = os.path.commonprefix(srcs + tgts)
45912563Sgabeblack@google.com        com_pfx_len = len(com_pfx)
46012563Sgabeblack@google.com        if com_pfx:
46112563Sgabeblack@google.com            # do some cleanup and sanity checking on common prefix
46212563Sgabeblack@google.com            if com_pfx[-1] == ".":
46312063Sgabeblack@google.com                # prefix matches all but file extension: ok
46412063Sgabeblack@google.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
46510238Sandreas.hansson@arm.com                com_pfx = com_pfx[0:-1]
46610238Sandreas.hansson@arm.com            elif com_pfx[-1] == "/":
46710238Sandreas.hansson@arm.com                # common prefix is directory path: OK
46812063Sgabeblack@google.com                pass
46910238Sandreas.hansson@arm.com            else:
47010238Sandreas.hansson@arm.com                src0_len = len(srcs[0])
47110416Sandreas.hansson@arm.com                tgt0_len = len(tgts[0])
47210238Sandreas.hansson@arm.com                if src0_len == com_pfx_len:
4739227Sandreas.hansson@arm.com                    # source is a substring of target, OK
47410238Sandreas.hansson@arm.com                    pass
47510416Sandreas.hansson@arm.com                elif tgt0_len == com_pfx_len:
47610416Sandreas.hansson@arm.com                    # target is a substring of source, need to back up to
4779227Sandreas.hansson@arm.com                    # avoid empty string on RHS of arrow
4789590Sandreas@sandberg.pp.se                    sep_idx = com_pfx.rfind(".")
4799590Sandreas@sandberg.pp.se                    if sep_idx != -1:
4809590Sandreas@sandberg.pp.se                        com_pfx = com_pfx[0:sep_idx]
48112304Sgabeblack@google.com                    else:
48212304Sgabeblack@google.com                        com_pfx = ''
48312304Sgabeblack@google.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
48412688Sgiacomo.travaglini@arm.com                    # still splitting at file extension: ok
48512688Sgiacomo.travaglini@arm.com                    pass
48612688Sgiacomo.travaglini@arm.com                else:
48712304Sgabeblack@google.com                    # probably a fluke; ignore it
48812304Sgabeblack@google.com                    com_pfx = ''
48912688Sgiacomo.travaglini@arm.com        # recalculate length in case com_pfx was modified
49012688Sgiacomo.travaglini@arm.com        com_pfx_len = len(com_pfx)
49112304Sgabeblack@google.com        def fmt(files):
49212304Sgabeblack@google.com            f = map(lambda s: s[com_pfx_len:], files)
49312304Sgabeblack@google.com            return ', '.join(f)
49412304Sgabeblack@google.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
49512304Sgabeblack@google.com
49612688Sgiacomo.travaglini@arm.comExport('Transform')
49712688Sgiacomo.travaglini@arm.com
49812688Sgiacomo.travaglini@arm.com# enable the regression script to use the termcap
49912304Sgabeblack@google.commain['TERMCAP'] = termcap
5008737Skoansin.tan@gmail.com
50110878Sandreas.hansson@arm.comif GetOption('verbose'):
50211500Sandreas.hansson@arm.com    def MakeAction(action, string, *args, **kwargs):
5039420Sandreas.hansson@arm.com        return Action(action, *args, **kwargs)
5048737Skoansin.tan@gmail.comelse:
50510106SMitch.Hayenga@arm.com    MakeAction = Action
5068737Skoansin.tan@gmail.com    main['CCCOMSTR']        = Transform("CC")
5078737Skoansin.tan@gmail.com    main['CXXCOMSTR']       = Transform("CXX")
50810878Sandreas.hansson@arm.com    main['ASCOMSTR']        = Transform("AS")
50912563Sgabeblack@google.com    main['SWIGCOMSTR']      = Transform("SWIG")
51012563Sgabeblack@google.com    main['ARCOMSTR']        = Transform("AR", 0)
5118737Skoansin.tan@gmail.com    main['LINKCOMSTR']      = Transform("LINK", 0)
5128737Skoansin.tan@gmail.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
51312563Sgabeblack@google.com    main['M4COMSTR']        = Transform("M4")
5148737Skoansin.tan@gmail.com    main['SHCCCOMSTR']      = Transform("SHCC")
5158737Skoansin.tan@gmail.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
51611294Sandreas.hansson@arm.comExport('MakeAction')
5179556Sandreas.hansson@arm.com
5189556Sandreas.hansson@arm.com# Initialize the Link-Time Optimization (LTO) flags
5199556Sandreas.hansson@arm.commain['LTO_CCFLAGS'] = []
52011294Sandreas.hansson@arm.commain['LTO_LDFLAGS'] = []
52110278SAndreas.Sandberg@ARM.com
52210278SAndreas.Sandberg@ARM.com# According to the readme, tcmalloc works best if the compiler doesn't
52310278SAndreas.Sandberg@ARM.com# assume that we're using the builtin malloc and friends. These flags
52410278SAndreas.Sandberg@ARM.com# are compiler-specific, so we need to set them after we detect which
52510278SAndreas.Sandberg@ARM.com# compiler we're using.
52610278SAndreas.Sandberg@ARM.commain['TCMALLOC_CCFLAGS'] = []
5279556Sandreas.hansson@arm.com
5289590Sandreas@sandberg.pp.seCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5299590Sandreas@sandberg.pp.seCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5309420Sandreas.hansson@arm.com
5319846Sandreas.hansson@arm.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5329846Sandreas.hansson@arm.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5339846Sandreas.hansson@arm.comif main['GCC'] + main['CLANG'] > 1:
5349846Sandreas.hansson@arm.com    print 'Error: How can we have two at the same time?'
5358946Sandreas.hansson@arm.com    Exit(1)
53611811Sbaz21@cam.ac.uk
53711811Sbaz21@cam.ac.uk# Set up default C++ compiler flags
53811811Sbaz21@cam.ac.ukif main['GCC'] or main['CLANG']:
53911811Sbaz21@cam.ac.uk    # As gcc and clang share many flags, do the common parts here
54012304Sgabeblack@google.com    main.Append(CCFLAGS=['-pipe'])
54112304Sgabeblack@google.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
54212304Sgabeblack@google.com    # Enable -Wall and then disable the few warnings that we
54312304Sgabeblack@google.com    # consistently violate
54412304Sgabeblack@google.com    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
54512304Sgabeblack@google.com    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
54612304Sgabeblack@google.com    # actually use that name, so we stick with c++0x
54712304Sgabeblack@google.com    main.Append(CXXFLAGS=['-std=c++0x'])
54812304Sgabeblack@google.com    # Add selected sanity checks from -Wextra
54912304Sgabeblack@google.com    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
55012304Sgabeblack@google.com                          '-Woverloaded-virtual'])
55112304Sgabeblack@google.comelse:
55212304Sgabeblack@google.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
55312304Sgabeblack@google.com    print "Don't know what compiler options to use for your compiler."
55412304Sgabeblack@google.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
55512304Sgabeblack@google.com    print termcap.Yellow + '       version:' + termcap.Normal,
5563918Ssaidi@eecs.umich.edu    if not CXX_version:
55712563Sgabeblack@google.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
55812563Sgabeblack@google.com               termcap.Normal
55912563Sgabeblack@google.com    else:
56012563Sgabeblack@google.com        print CXX_version.replace('\n', '<nl>')
5619068SAli.Saidi@ARM.com    print "       If you're trying to use a compiler other than GCC"
56212563Sgabeblack@google.com    print "       or clang, there appears to be something wrong with your"
56312563Sgabeblack@google.com    print "       environment."
5649068SAli.Saidi@ARM.com    print "       "
56512563Sgabeblack@google.com    print "       If you are trying to use a compiler other than those listed"
56612563Sgabeblack@google.com    print "       above you will need to ease fix SConstruct and "
56712563Sgabeblack@google.com    print "       src/SConscript to support that compiler."
56812563Sgabeblack@google.com    Exit(1)
56912563Sgabeblack@google.com
57012563Sgabeblack@google.comif main['GCC']:
57112563Sgabeblack@google.com    # Check for a supported version of gcc. >= 4.6 is chosen for its
57212563Sgabeblack@google.com    # level of c++11 support. See
5733918Ssaidi@eecs.umich.edu    # http://gcc.gnu.org/projects/cxx0x.html for details. 4.6 is also
5743918Ssaidi@eecs.umich.edu    # the first version with proper LTO support.
5756157Snate@binkert.org    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5766157Snate@binkert.org    if compareVersions(gcc_version, "4.6") < 0:
5776157Snate@binkert.org        print 'Error: gcc version 4.6 or newer required.'
5786157Snate@binkert.org        print '       Installed version:', gcc_version
5795397Ssaidi@eecs.umich.edu        Exit(1)
5805397Ssaidi@eecs.umich.edu
5816121Snate@binkert.org    main['GCC_VERSION'] = gcc_version
5826121Snate@binkert.org
5836121Snate@binkert.org    # gcc from version 4.8 and above generates "rep; ret" instructions
5846121Snate@binkert.org    # to avoid performance penalties on certain AMD chips. Older
5856121Snate@binkert.org    # assemblers detect this as an error, "Error: expecting string
5866121Snate@binkert.org    # instruction after `rep'"
5875397Ssaidi@eecs.umich.edu    if compareVersions(gcc_version, "4.8") > 0:
5881851SN/A        as_version = readCommand([main['AS'], '-v', '/dev/null'],
5891851SN/A                                 exception=False).split()
5907739Sgblack@eecs.umich.edu
591955SN/A        if not as_version or compareVersions(as_version[-1], "2.23") < 0:
5929396Sandreas.hansson@arm.com            print termcap.Yellow + termcap.Bold + \
5939396Sandreas.hansson@arm.com                'Warning: This combination of gcc and binutils have' + \
5949396Sandreas.hansson@arm.com                ' known incompatibilities.\n' + \
5959396Sandreas.hansson@arm.com                '         If you encounter build problems, please update ' + \
5969396Sandreas.hansson@arm.com                'binutils to 2.23.' + \
5979396Sandreas.hansson@arm.com                termcap.Normal
59812563Sgabeblack@google.com
59912563Sgabeblack@google.com    # Add the appropriate Link-Time Optimization (LTO) flags
60012563Sgabeblack@google.com    # unless LTO is explicitly turned off. Note that these flags
60112563Sgabeblack@google.com    # are only used by the fast target.
6029396Sandreas.hansson@arm.com    if not GetOption('no_lto'):
6039396Sandreas.hansson@arm.com        # Pass the LTO flag when compiling to produce GIMPLE
6049396Sandreas.hansson@arm.com        # output, we merely create the flags here and only append
6059396Sandreas.hansson@arm.com        # them later/
6069396Sandreas.hansson@arm.com        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6079396Sandreas.hansson@arm.com
60812563Sgabeblack@google.com        # Use the same amount of jobs for LTO as we are running
60912563Sgabeblack@google.com        # scons with, we hardcode the use of the linker plugin
61012563Sgabeblack@google.com        # which requires either gold or GNU ld >= 2.21
61112563Sgabeblack@google.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
61212563Sgabeblack@google.com                               '-fuse-linker-plugin']
6139477Sandreas.hansson@arm.com
6149477Sandreas.hansson@arm.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6159477Sandreas.hansson@arm.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6169477Sandreas.hansson@arm.com
6179477Sandreas.hansson@arm.comelif main['CLANG']:
6189477Sandreas.hansson@arm.com    # Check for a supported version of clang, >= 3.0 is needed to
6199477Sandreas.hansson@arm.com    # support similar features as gcc 4.6. See
6209477Sandreas.hansson@arm.com    # http://clang.llvm.org/cxx_status.html for details
6219477Sandreas.hansson@arm.com    clang_version_re = re.compile(".* version (\d+\.\d+)")
6229477Sandreas.hansson@arm.com    clang_version_match = clang_version_re.search(CXX_version)
6239477Sandreas.hansson@arm.com    if (clang_version_match):
6249477Sandreas.hansson@arm.com        clang_version = clang_version_match.groups()[0]
6259477Sandreas.hansson@arm.com        if compareVersions(clang_version, "3.0") < 0:
6269477Sandreas.hansson@arm.com            print 'Error: clang version 3.0 or newer required.'
62712563Sgabeblack@google.com            print '       Installed version:', clang_version
62812563Sgabeblack@google.com            Exit(1)
62912563Sgabeblack@google.com    else:
6309396Sandreas.hansson@arm.com        print 'Error: Unable to determine clang version.'
6312667Sstever@eecs.umich.edu        Exit(1)
63210710Sandreas.hansson@arm.com
63310710Sandreas.hansson@arm.com    # clang has a few additional warnings that we disable,
63410710Sandreas.hansson@arm.com    # tautological comparisons are allowed due to unsigned integers
63511811Sbaz21@cam.ac.uk    # being compared to constants that happen to be 0, and extraneous
63611811Sbaz21@cam.ac.uk    # parantheses are allowed due to Ruby's printing of the AST,
63711811Sbaz21@cam.ac.uk    # finally self assignments are allowed as the generated CPU code
63811811Sbaz21@cam.ac.uk    # is relying on this
63911811Sbaz21@cam.ac.uk    main.Append(CCFLAGS=['-Wno-tautological-compare',
64011811Sbaz21@cam.ac.uk                         '-Wno-parentheses',
64110710Sandreas.hansson@arm.com                         '-Wno-self-assign',
64210710Sandreas.hansson@arm.com                         # Some versions of libstdc++ (4.8?) seem to
64310710Sandreas.hansson@arm.com                         # use struct hash and class hash
64410710Sandreas.hansson@arm.com                         # interchangeably.
64510384SCurtis.Dunham@arm.com                         '-Wno-mismatched-tags',
6469986Sandreas@sandberg.pp.se                         ])
6479986Sandreas@sandberg.pp.se
6489986Sandreas@sandberg.pp.se    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6499986Sandreas@sandberg.pp.se
6509986Sandreas@sandberg.pp.se    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6519986Sandreas@sandberg.pp.se    # opposed to libstdc++, as the later is dated.
6529986Sandreas@sandberg.pp.se    if sys.platform == "darwin":
6539986Sandreas@sandberg.pp.se        main.Append(CXXFLAGS=['-stdlib=libc++'])
6549986Sandreas@sandberg.pp.se        main.Append(LIBS=['c++'])
6559986Sandreas@sandberg.pp.se
6569986Sandreas@sandberg.pp.seelse:
6579986Sandreas@sandberg.pp.se    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6589986Sandreas@sandberg.pp.se    print "Don't know what compiler options to use for your compiler."
6599986Sandreas@sandberg.pp.se    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6609986Sandreas@sandberg.pp.se    print termcap.Yellow + '       version:' + termcap.Normal,
6619986Sandreas@sandberg.pp.se    if not CXX_version:
6629986Sandreas@sandberg.pp.se        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6639986Sandreas@sandberg.pp.se               termcap.Normal
6649986Sandreas@sandberg.pp.se    else:
6659986Sandreas@sandberg.pp.se        print CXX_version.replace('\n', '<nl>')
6662638Sstever@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
6672638Sstever@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
6686121Snate@binkert.org    print "       environment."
6693716Sstever@eecs.umich.edu    print "       "
6705522Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
6719986Sandreas@sandberg.pp.se    print "       above you will need to ease fix SConstruct and "
6729986Sandreas@sandberg.pp.se    print "       src/SConscript to support that compiler."
6739986Sandreas@sandberg.pp.se    Exit(1)
6745522Snate@binkert.org
6755227Ssaidi@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
6765227Ssaidi@eecs.umich.edumain['YACCFLAGS'] = '-d'
6775227Ssaidi@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
6785227Ssaidi@eecs.umich.edu
6796654Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
6806654Snate@binkert.org# extra 'qdo' every time we run scons.
6817769SAli.Saidi@ARM.comif main['BATCH']:
6827769SAli.Saidi@ARM.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6837769SAli.Saidi@ARM.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6847769SAli.Saidi@ARM.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6855227Ssaidi@eecs.umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6865227Ssaidi@eecs.umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6875227Ssaidi@eecs.umich.edu
6885204Sstever@gmail.comif sys.platform == 'cygwin':
6895204Sstever@gmail.com    # cygwin has some header file issues...
6905204Sstever@gmail.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
6915204Sstever@gmail.com
6925204Sstever@gmail.com# Check for the protobuf compiler
6935204Sstever@gmail.comprotoc_version = readCommand([main['PROTOC'], '--version'],
6945204Sstever@gmail.com                             exception='').split()
6955204Sstever@gmail.com
6965204Sstever@gmail.com# First two words should be "libprotoc x.y.z"
6975204Sstever@gmail.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6985204Sstever@gmail.com    print termcap.Yellow + termcap.Bold + \
6995204Sstever@gmail.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
7005204Sstever@gmail.com        '         Please install protobuf-compiler for tracing support.' + \
7015204Sstever@gmail.com        termcap.Normal
7025204Sstever@gmail.com    main['PROTOC'] = False
7035204Sstever@gmail.comelse:
7045204Sstever@gmail.com    # Based on the availability of the compress stream wrappers,
7056121Snate@binkert.org    # require 2.1.0
7065204Sstever@gmail.com    min_protoc_version = '2.1.0'
7077727SAli.Saidi@ARM.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
7087727SAli.Saidi@ARM.com        print termcap.Yellow + termcap.Bold + \
70912563Sgabeblack@google.com            'Warning: protoc version', min_protoc_version, \
7107727SAli.Saidi@ARM.com            'or newer required.\n' + \
7117727SAli.Saidi@ARM.com            '         Installed version:', protoc_version[1], \
71211988Sandreas.sandberg@arm.com            termcap.Normal
71311988Sandreas.sandberg@arm.com        main['PROTOC'] = False
71410453SAndrew.Bardsley@arm.com    else:
71510453SAndrew.Bardsley@arm.com        # Attempt to determine the appropriate include path and
71610453SAndrew.Bardsley@arm.com        # library path using pkg-config, that means we also need to
71710453SAndrew.Bardsley@arm.com        # check for pkg-config. Note that it is possible to use
71810453SAndrew.Bardsley@arm.com        # protobuf without the involvement of pkg-config. Later on we
71910453SAndrew.Bardsley@arm.com        # check go a library config check and at that point the test
72010453SAndrew.Bardsley@arm.com        # will fail if libprotobuf cannot be found.
72110453SAndrew.Bardsley@arm.com        if readCommand(['pkg-config', '--version'], exception=''):
72210453SAndrew.Bardsley@arm.com            try:
72310453SAndrew.Bardsley@arm.com                # Attempt to establish what linking flags to add for protobuf
72410160Sandreas.hansson@arm.com                # using pkg-config
72510453SAndrew.Bardsley@arm.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
72610453SAndrew.Bardsley@arm.com            except:
72710453SAndrew.Bardsley@arm.com                print termcap.Yellow + termcap.Bold + \
72810453SAndrew.Bardsley@arm.com                    'Warning: pkg-config could not get protobuf flags.' + \
72910453SAndrew.Bardsley@arm.com                    termcap.Normal
73010453SAndrew.Bardsley@arm.com
73110453SAndrew.Bardsley@arm.com# Check for SWIG
73210453SAndrew.Bardsley@arm.comif not main.has_key('SWIG'):
7339812Sandreas.hansson@arm.com    print 'Error: SWIG utility not found.'
73410453SAndrew.Bardsley@arm.com    print '       Please install (see http://www.swig.org) and retry.'
73510453SAndrew.Bardsley@arm.com    Exit(1)
73610453SAndrew.Bardsley@arm.com
73710453SAndrew.Bardsley@arm.com# Check for appropriate SWIG version
73810453SAndrew.Bardsley@arm.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
73910453SAndrew.Bardsley@arm.com# First 3 words should be "SWIG Version x.y.z"
74010453SAndrew.Bardsley@arm.comif len(swig_version) < 3 or \
74110453SAndrew.Bardsley@arm.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
74210453SAndrew.Bardsley@arm.com    print 'Error determining SWIG version.'
74310453SAndrew.Bardsley@arm.com    Exit(1)
74410453SAndrew.Bardsley@arm.com
74510453SAndrew.Bardsley@arm.commin_swig_version = '2.0.4'
7467727SAli.Saidi@ARM.comif compareVersions(swig_version[2], min_swig_version) < 0:
74710453SAndrew.Bardsley@arm.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
74810453SAndrew.Bardsley@arm.com    print '       Installed version:', swig_version[2]
74912563Sgabeblack@google.com    Exit(1)
75012563Sgabeblack@google.com
75112563Sgabeblack@google.com# Set up SWIG flags & scanner
75210453SAndrew.Bardsley@arm.comswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7533118Sstever@eecs.umich.edumain.Append(SWIGFLAGS=swig_flags)
75410453SAndrew.Bardsley@arm.com
75510453SAndrew.Bardsley@arm.com# filter out all existing swig scanners, they mess up the dependency
75612563Sgabeblack@google.com# stuff for some reason
75710453SAndrew.Bardsley@arm.comscanners = []
7583118Sstever@eecs.umich.edufor scanner in main['SCANNERS']:
7593483Ssaidi@eecs.umich.edu    skeys = scanner.skeys
7603494Ssaidi@eecs.umich.edu    if skeys == '.i':
7613494Ssaidi@eecs.umich.edu        continue
76212563Sgabeblack@google.com
7633483Ssaidi@eecs.umich.edu    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
7643483Ssaidi@eecs.umich.edu        continue
7653053Sstever@eecs.umich.edu
7663053Sstever@eecs.umich.edu    scanners.append(scanner)
7673918Ssaidi@eecs.umich.edu
76812563Sgabeblack@google.com# add the new swig scanner that we like better
76912563Sgabeblack@google.comfrom SCons.Scanner import ClassicCPP as CPPScanner
77012563Sgabeblack@google.comswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
7713053Sstever@eecs.umich.eduscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
7723053Sstever@eecs.umich.edu
7739396Sandreas.hansson@arm.com# replace the scanners list that has what we want
7749396Sandreas.hansson@arm.commain['SCANNERS'] = scanners
7759396Sandreas.hansson@arm.com
7769396Sandreas.hansson@arm.com# Add a custom Check function to the Configure context so that we can
7779396Sandreas.hansson@arm.com# figure out if the compiler adds leading underscores to global
7789396Sandreas.hansson@arm.com# variables.  This is needed for the autogenerated asm files that we
7799396Sandreas.hansson@arm.com# use for embedding the python code.
7809396Sandreas.hansson@arm.comdef CheckLeading(context):
7819396Sandreas.hansson@arm.com    context.Message("Checking for leading underscore in global variables...")
7829477Sandreas.hansson@arm.com    # 1) Define a global variable called x from asm so the C compiler
7839396Sandreas.hansson@arm.com    #    won't change the symbol at all.
78412563Sgabeblack@google.com    # 2) Declare that variable.
78512563Sgabeblack@google.com    # 3) Use the variable
78612563Sgabeblack@google.com    #
78712563Sgabeblack@google.com    # If the compiler prepends an underscore, this will successfully
7889396Sandreas.hansson@arm.com    # link because the external symbol 'x' will be called '_x' which
7897840Snate@binkert.org    # was defined by the asm statement.  If the compiler does not
7907865Sgblack@eecs.umich.edu    # prepend an underscore, this will not successfully link because
7917865Sgblack@eecs.umich.edu    # '_x' will have been defined by assembly, while the C portion of
7927865Sgblack@eecs.umich.edu    # the code will be trying to use 'x'
7937865Sgblack@eecs.umich.edu    ret = context.TryLink('''
7947865Sgblack@eecs.umich.edu        asm(".globl _x; _x: .byte 0");
7957840Snate@binkert.org        extern int x;
7969900Sandreas@sandberg.pp.se        int main() { return x; }
7979900Sandreas@sandberg.pp.se        ''', extension=".c")
7989900Sandreas@sandberg.pp.se    context.env.Append(LEADING_UNDERSCORE=ret)
7999900Sandreas@sandberg.pp.se    context.Result(ret)
80010456SCurtis.Dunham@arm.com    return ret
80110456SCurtis.Dunham@arm.com
80210456SCurtis.Dunham@arm.com# Add a custom Check function to test for structure members.
80310456SCurtis.Dunham@arm.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
80410456SCurtis.Dunham@arm.com    context.Message("Checking for member %s in %s..." %
80510456SCurtis.Dunham@arm.com                    (member, decl))
80612563Sgabeblack@google.com    text = """
80712563Sgabeblack@google.com#include %(header)s
80812563Sgabeblack@google.comint main(){
80912563Sgabeblack@google.com  %(decl)s test;
8109045SAli.Saidi@ARM.com  (void)test.%(member)s;
81111235Sandreas.sandberg@arm.com  return 0;
81211235Sandreas.sandberg@arm.com};
81311235Sandreas.sandberg@arm.com""" % { "header" : include_quotes[0] + include + include_quotes[1],
81411235Sandreas.sandberg@arm.com        "decl" : decl,
81511235Sandreas.sandberg@arm.com        "member" : member,
81612485Sjang.hanhwi@gmail.com        }
81712485Sjang.hanhwi@gmail.com
81812485Sjang.hanhwi@gmail.com    ret = context.TryCompile(text, extension=".cc")
81911235Sandreas.sandberg@arm.com    context.Result(ret)
82011811Sbaz21@cam.ac.uk    return ret
82112485Sjang.hanhwi@gmail.com
82211811Sbaz21@cam.ac.uk# Platform-specific configuration.  Note again that we assume that all
82311811Sbaz21@cam.ac.uk# builds under a given build root run on the same host platform.
82411811Sbaz21@cam.ac.ukconf = Configure(main,
82511235Sandreas.sandberg@arm.com                 conf_dir = joinpath(build_root, '.scons_config'),
82611235Sandreas.sandberg@arm.com                 log_file = joinpath(build_root, 'scons_config.log'),
82711235Sandreas.sandberg@arm.com                 custom_tests = {
82812563Sgabeblack@google.com        'CheckLeading' : CheckLeading,
82912563Sgabeblack@google.com        'CheckMember' : CheckMember,
83012563Sgabeblack@google.com        })
83111235Sandreas.sandberg@arm.com
8327840Snate@binkert.org# Check for leading underscores.  Don't really need to worry either
83312563Sgabeblack@google.com# way so don't need to check the return code.
8347840Snate@binkert.orgconf.CheckLeading()
8351858SN/A
8361858SN/A# Check if we should compile a 64 bit binary on Mac OS X/Darwin
8371858SN/Atry:
83812563Sgabeblack@google.com    import platform
83912563Sgabeblack@google.com    uname = platform.uname()
8401858SN/A    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
84112230Sgiacomo.travaglini@arm.com        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
84212230Sgiacomo.travaglini@arm.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
84312230Sgiacomo.travaglini@arm.com            main.Append(CFLAGS=['-arch', 'x86_64'])
84412230Sgiacomo.travaglini@arm.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
84512563Sgabeblack@google.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
84612563Sgabeblack@google.comexcept:
84712563Sgabeblack@google.com    pass
84812230Sgiacomo.travaglini@arm.com
8499903Sandreas.hansson@arm.com# Recent versions of scons substitute a "Null" object for Configure()
8509903Sandreas.hansson@arm.com# when configuration isn't necessary, e.g., if the "--help" option is
8519903Sandreas.hansson@arm.com# present.  Unfortuantely this Null object always returns false,
8529903Sandreas.hansson@arm.com# breaking all our configuration checks.  We replace it with our own
85310841Sandreas.sandberg@arm.com# more optimistic null object that returns True instead.
8549651SAndreas.Sandberg@ARM.comif not conf:
85512563Sgabeblack@google.com    def NullCheck(*args, **kwargs):
85612563Sgabeblack@google.com        return True
8579651SAndreas.Sandberg@ARM.com
85812056Sgabeblack@google.com    class NullConf:
85912056Sgabeblack@google.com        def __init__(self, env):
86012056Sgabeblack@google.com            self.env = env
86112563Sgabeblack@google.com        def Finish(self):
86212056Sgabeblack@google.com            return self.env
86310841Sandreas.sandberg@arm.com        def __getattr__(self, mname):
86410841Sandreas.sandberg@arm.com            return NullCheck
86510841Sandreas.sandberg@arm.com
86610841Sandreas.sandberg@arm.com    conf = NullConf(main)
86710841Sandreas.sandberg@arm.com
86810841Sandreas.sandberg@arm.com# Cache build files in the supplied directory.
8699651SAndreas.Sandberg@ARM.comif main['M5_BUILD_CACHE']:
8709651SAndreas.Sandberg@ARM.com    print 'Using build cache located at', main['M5_BUILD_CACHE']
8719651SAndreas.Sandberg@ARM.com    CacheDir(main['M5_BUILD_CACHE'])
8729651SAndreas.Sandberg@ARM.com
8739651SAndreas.Sandberg@ARM.com# Find Python include and library directories for embedding the
8749651SAndreas.Sandberg@ARM.com# interpreter. We rely on python-config to resolve the appropriate
87512563Sgabeblack@google.com# includes and linker flags. ParseConfig does not seem to understand
8769651SAndreas.Sandberg@ARM.com# the more exotic linker flags such as -Xlinker and -export-dynamic so
8779651SAndreas.Sandberg@ARM.com# we add them explicitly below. If you want to link in an alternate
87810841Sandreas.sandberg@arm.com# version of python, see above for instructions on how to invoke
87912563Sgabeblack@google.com# scons with the appropriate PATH set.
88012563Sgabeblack@google.com#
88110841Sandreas.sandberg@arm.com# First we check if python2-config exists, else we use python-config
88210841Sandreas.sandberg@arm.compython_config = readCommand(['which', 'python2-config'], exception='').strip()
88310841Sandreas.sandberg@arm.comif not os.path.exists(python_config):
88410860Sandreas.sandberg@arm.com    python_config = readCommand(['which', 'python-config'],
88510841Sandreas.sandberg@arm.com                                exception='').strip()
88610841Sandreas.sandberg@arm.compy_includes = readCommand([python_config, '--includes'],
88710841Sandreas.sandberg@arm.com                          exception='').split()
88810841Sandreas.sandberg@arm.com# Strip the -I from the include folders before adding them to the
88910841Sandreas.sandberg@arm.com# CPPPATH
89012563Sgabeblack@google.commain.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
89110841Sandreas.sandberg@arm.com
89210841Sandreas.sandberg@arm.com# Read the linker flags and split them into libraries and other link
89310841Sandreas.sandberg@arm.com# flags. The libraries are added later through the call the CheckLib.
89410841Sandreas.sandberg@arm.compy_ld_flags = readCommand([python_config, '--ldflags'], exception='').split()
89510841Sandreas.sandberg@arm.compy_libs = []
8969651SAndreas.Sandberg@ARM.comfor lib in py_ld_flags:
8979651SAndreas.Sandberg@ARM.com     if not lib.startswith('-l'):
8989986Sandreas@sandberg.pp.se         main.Append(LINKFLAGS=[lib])
8999986Sandreas@sandberg.pp.se     else:
9009986Sandreas@sandberg.pp.se         lib = lib[2:]
9019986Sandreas@sandberg.pp.se         if lib not in py_libs:
9029986Sandreas@sandberg.pp.se             py_libs.append(lib)
9039986Sandreas@sandberg.pp.se
9045863Snate@binkert.org# verify that this stuff works
9055863Snate@binkert.orgif not conf.CheckHeader('Python.h', '<>'):
9065863Snate@binkert.org    print "Error: can't find Python.h header in", py_includes
9075863Snate@binkert.org    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
9086121Snate@binkert.org    Exit(1)
9091858SN/A
9105863Snate@binkert.orgfor lib in py_libs:
9115863Snate@binkert.org    if not conf.CheckLib(lib):
9125863Snate@binkert.org        print "Error: can't find library %s required by python" % lib
9135863Snate@binkert.org        Exit(1)
9145863Snate@binkert.org
9152139SN/A# On Solaris you need to use libsocket for socket ops
9164202Sbinkertn@umich.eduif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
91711308Santhony.gutierrez@amd.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
9184202Sbinkertn@umich.edu       print "Can't find library with socket calls (e.g. accept())"
91911308Santhony.gutierrez@amd.com       Exit(1)
9202139SN/A
9216994Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
9226994Snate@binkert.org# added to the LIBS environment variable.
9236994Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
9246994Snate@binkert.org    print 'Error: did not find needed zlib compression library '\
9256994Snate@binkert.org          'and/or zlib.h header file.'
9266994Snate@binkert.org    print '       Please install zlib and try again.'
9276994Snate@binkert.org    Exit(1)
9286994Snate@binkert.org
92910319SAndreas.Sandberg@ARM.com# If we have the protobuf compiler, also make sure we have the
9306994Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
9316994Snate@binkert.org# automatically added to the LIBS environment variable. After
9326994Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
9336994Snate@binkert.org# got both protoc and libprotobuf available.
9346994Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
9356994Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
9366994Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
9376994Snate@binkert.org
9386994Snate@binkert.org# If we have the compiler but not the library, print another warning.
9396994Snate@binkert.orgif main['PROTOC'] and not main['HAVE_PROTOBUF']:
9406994Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
9412155SN/A        'Warning: did not find protocol buffer library and/or headers.\n' + \
9425863Snate@binkert.org    '       Please install libprotobuf-dev for tracing support.' + \
9431869SN/A    termcap.Normal
9441869SN/A
9455863Snate@binkert.org# Check for librt.
9465863Snate@binkert.orghave_posix_clock = \
9474202Sbinkertn@umich.edu    conf.CheckLibWithHeader(None, 'time.h', 'C',
9486108Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
9496108Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
9506108Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
9516108Snate@binkert.org
9529219Spower.jg@gmail.comhave_posix_timers = \
9539219Spower.jg@gmail.com    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
9549219Spower.jg@gmail.com                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
9559219Spower.jg@gmail.com
9569219Spower.jg@gmail.comif conf.CheckLib('tcmalloc'):
9579219Spower.jg@gmail.com    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9589219Spower.jg@gmail.comelif conf.CheckLib('tcmalloc_minimal'):
9599219Spower.jg@gmail.com    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
9604202Sbinkertn@umich.eduelse:
9615863Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
96210135SCurtis.Dunham@arm.com          "You can get a 12% performance improvement by installing tcmalloc "\
96312563Sgabeblack@google.com          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
9645742Snate@binkert.org          termcap.Normal
9658268Ssteve.reinhardt@amd.com
96612563Sgabeblack@google.comif not have_posix_clock:
9678268Ssteve.reinhardt@amd.com    print "Can't find library for POSIX clocks."
9685742Snate@binkert.org
9695341Sstever@gmail.com# Check for <fenv.h> (C99 FP environment control)
9708474Sgblack@eecs.umich.eduhave_fenv = conf.CheckHeader('fenv.h', '<>')
97112563Sgabeblack@google.comif not have_fenv:
9725342Sstever@gmail.com    print "Warning: Header file <fenv.h> not found."
9734202Sbinkertn@umich.edu    print "         This host has no IEEE FP rounding mode control."
9744202Sbinkertn@umich.edu
97511308Santhony.gutierrez@amd.com# Check if we should enable KVM-based hardware virtualization. The API
9764202Sbinkertn@umich.edu# we rely on exists since version 2.6.36 of the kernel, but somehow
9775863Snate@binkert.org# the KVM_API_VERSION does not reflect the change. We test for one of
9785863Snate@binkert.org# the types as a fall back.
97911308Santhony.gutierrez@amd.comhave_kvm = conf.CheckHeader('linux/kvm.h', '<>') and \
9806994Snate@binkert.org    conf.CheckTypeSize('struct kvm_xsave', '#include <linux/kvm.h>') != 0
9816994Snate@binkert.orgif not have_kvm:
98210319SAndreas.Sandberg@ARM.com    print "Info: Compatible header file <linux/kvm.h> not found, " \
9835863Snate@binkert.org        "disabling KVM support."
9845863Snate@binkert.org
9855863Snate@binkert.org# Check if the requested target ISA is compatible with the host
9865863Snate@binkert.orgdef is_isa_kvm_compatible(isa):
9875863Snate@binkert.org    isa_comp_table = {
9885863Snate@binkert.org        "arm" : ( "armv7l" ),
9895863Snate@binkert.org        "x86" : ( "x86_64" ),
9905863Snate@binkert.org        }
9917840Snate@binkert.org    try:
9925863Snate@binkert.org        import platform
99312230Sgiacomo.travaglini@arm.com        host_isa = platform.machine()
99412230Sgiacomo.travaglini@arm.com    except:
99512230Sgiacomo.travaglini@arm.com        print "Warning: Failed to determine host ISA."
99612230Sgiacomo.travaglini@arm.com        return False
99712230Sgiacomo.travaglini@arm.com
99812056Sgabeblack@google.com    return host_isa in isa_comp_table.get(isa, [])
99912056Sgabeblack@google.com
100012056Sgabeblack@google.com
100111308Santhony.gutierrez@amd.com# Check if the exclude_host attribute is available. We want this to
10029219Spower.jg@gmail.com# get accurate instruction counts in KVM.
10039219Spower.jg@gmail.commain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
100411235Sandreas.sandberg@arm.com    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
100511235Sandreas.sandberg@arm.com
10061869SN/A
10071858SN/A######################################################################
10085863Snate@binkert.org#
100911308Santhony.gutierrez@amd.com# Finish the configuration
101012061Sjason@lowepower.com#
101112230Sgiacomo.travaglini@arm.commain = conf.Finish()
101212230Sgiacomo.travaglini@arm.com
10131858SN/A######################################################################
1014955SN/A#
1015955SN/A# Collect all non-global variables
10161869SN/A#
10171869SN/A
10181869SN/A# Define the universe of supported ISAs
10191869SN/Aall_isa_list = [ ]
10201869SN/AExport('all_isa_list')
10215863Snate@binkert.org
10225863Snate@binkert.orgclass CpuModel(object):
10235863Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
10241869SN/A    know about a particular CPU model.'''
10255863Snate@binkert.org
10261869SN/A    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
102712563Sgabeblack@google.com    dict = {}
10281869SN/A    list = []
10291869SN/A    defaults = []
10301869SN/A
10311869SN/A    # Constructor.  Automatically adds models to CpuModel.dict.
10328483Sgblack@eecs.umich.edu    def __init__(self, name, filename, includes, strings, default=False):
10331869SN/A        self.name = name           # name of model
10341869SN/A        self.filename = filename   # filename for output exec code
10351869SN/A        self.includes = includes   # include files needed in exec file
10361869SN/A        # The 'strings' dict holds all the per-CPU symbols we can
10375863Snate@binkert.org        # substitute into templates etc.
10385863Snate@binkert.org        self.strings = strings
10391869SN/A
10405863Snate@binkert.org        # This cpu is enabled by default
10415863Snate@binkert.org        self.default = default
10423356Sbinkertn@umich.edu
10433356Sbinkertn@umich.edu        # Add self to dict
10443356Sbinkertn@umich.edu        if name in CpuModel.dict:
10453356Sbinkertn@umich.edu            raise AttributeError, "CpuModel '%s' already registered" % name
10463356Sbinkertn@umich.edu        CpuModel.dict[name] = self
10474781Snate@binkert.org        CpuModel.list.append(name)
10485863Snate@binkert.org
10495863Snate@binkert.orgExport('CpuModel')
10501869SN/A
10511869SN/A# Sticky variables get saved in the variables file so they persist from
10521869SN/A# one invocation to the next (unless overridden, in which case the new
10536121Snate@binkert.org# value becomes sticky).
10541869SN/Asticky_vars = Variables(args=ARGUMENTS)
105511982Sgabeblack@google.comExport('sticky_vars')
105611982Sgabeblack@google.com
105711982Sgabeblack@google.com# Sticky variables that should be exported
105811982Sgabeblack@google.comexport_vars = []
105911982Sgabeblack@google.comExport('export_vars')
106011982Sgabeblack@google.com
106111982Sgabeblack@google.com# For Ruby
106211982Sgabeblack@google.comall_protocols = []
106311982Sgabeblack@google.comExport('all_protocols')
106411982Sgabeblack@google.comprotocol_dirs = []
106511982Sgabeblack@google.comExport('protocol_dirs')
106611982Sgabeblack@google.comslicc_includes = []
106711982Sgabeblack@google.comExport('slicc_includes')
106811982Sgabeblack@google.com
106911982Sgabeblack@google.com# Walk the tree and execute all SConsopts scripts that wil add to the
107011982Sgabeblack@google.com# above variables
107111982Sgabeblack@google.comif GetOption('verbose'):
107211982Sgabeblack@google.com    print "Reading SConsopts"
107311982Sgabeblack@google.comfor bdir in [ base_dir ] + extras_dir_list:
107411982Sgabeblack@google.com    if not isdir(bdir):
107511982Sgabeblack@google.com        print "Error: directory '%s' does not exist" % bdir
107611982Sgabeblack@google.com        Exit(1)
107711982Sgabeblack@google.com    for root, dirs, files in os.walk(bdir):
107811982Sgabeblack@google.com        if 'SConsopts' in files:
107911982Sgabeblack@google.com            if GetOption('verbose'):
108011982Sgabeblack@google.com                print "Reading", joinpath(root, 'SConsopts')
108111978Sgabeblack@google.com            SConscript(joinpath(root, 'SConsopts'))
108211978Sgabeblack@google.com
108312034Sgabeblack@google.comall_isa_list.sort()
108411978Sgabeblack@google.com
108511978Sgabeblack@google.comsticky_vars.AddVariables(
108611978Sgabeblack@google.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
108712034Sgabeblack@google.com    ListVariable('CPU_MODELS', 'CPU models',
108811978Sgabeblack@google.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
108911978Sgabeblack@google.com                 sorted(CpuModel.list)),
109010915Sandreas.sandberg@arm.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
109111986Sandreas.sandberg@arm.com                 False),
109211986Sandreas.sandberg@arm.com    BoolVariable('SS_COMPATIBLE_FP',
10931869SN/A                 'Make floating-point results compatible with SimpleScalar',
10941869SN/A                 False),
109512015Sgabeblack@google.com    BoolVariable('USE_SSE2',
109612015Sgabeblack@google.com                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
109712015Sgabeblack@google.com                 False),
109812015Sgabeblack@google.com    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
10993546Sgblack@eecs.umich.edu    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
11003546Sgblack@eecs.umich.edu    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
11013546Sgblack@eecs.umich.edu    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
110212015Sgabeblack@google.com    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
110312015Sgabeblack@google.com                  all_protocols),
110412015Sgabeblack@google.com    )
110512015Sgabeblack@google.com
110612015Sgabeblack@google.com# These variables get exported to #defines in config/*.hh (see src/SConscript).
110712015Sgabeblack@google.comexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
110812015Sgabeblack@google.com                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF',
110912563Sgabeblack@google.com                'HAVE_PERF_ATTR_EXCLUDE_HOST']
11103546Sgblack@eecs.umich.edu
111112015Sgabeblack@google.com###################################################
111212015Sgabeblack@google.com#
111310196SCurtis.Dunham@arm.com# Define a SCons builder for configuration flag headers.
111412015Sgabeblack@google.com#
111512015Sgabeblack@google.com###################################################
111612015Sgabeblack@google.com
111712015Sgabeblack@google.com# This function generates a config header file that #defines the
111812015Sgabeblack@google.com# variable symbol to the current variable setting (0 or 1).  The source
111912015Sgabeblack@google.com# operands are the name of the variable and a Value node containing the
112012015Sgabeblack@google.com# value of the variable.
112112015Sgabeblack@google.comdef build_config_file(target, source, env):
112212015Sgabeblack@google.com    (variable, value) = [s.get_contents() for s in source]
112312015Sgabeblack@google.com    f = file(str(target[0]), 'w')
112412015Sgabeblack@google.com    print >> f, '#define', variable, value
11253546Sgblack@eecs.umich.edu    f.close()
11263546Sgblack@eecs.umich.edu    return None
11273546Sgblack@eecs.umich.edu
1128955SN/A# Combine the two functions into a scons Action object.
1129955SN/Aconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1130955SN/A
1131955SN/A# The emitter munges the source & target node lists to reflect what
11325863Snate@binkert.org# we're really doing.
113310135SCurtis.Dunham@arm.comdef config_emitter(target, source, env):
113412563Sgabeblack@google.com    # extract variable name from Builder arg
11355343Sstever@gmail.com    variable = str(target[0])
11365343Sstever@gmail.com    # True target is config header file
11376121Snate@binkert.org    target = joinpath('config', variable.lower() + '.hh')
11385863Snate@binkert.org    val = env[variable]
11394773Snate@binkert.org    if isinstance(val, bool):
11405863Snate@binkert.org        # Force value to 0/1
11412632Sstever@eecs.umich.edu        val = int(val)
11425863Snate@binkert.org    elif isinstance(val, str):
11432023SN/A        val = '"' + val + '"'
11445863Snate@binkert.org
11455863Snate@binkert.org    # Sources are variable name & value (packaged in SCons Value nodes)
11465863Snate@binkert.org    return ([target], [Value(variable), Value(val)])
11475863Snate@binkert.org
11485863Snate@binkert.orgconfig_builder = Builder(emitter = config_emitter, action = config_action)
11495863Snate@binkert.org
11505863Snate@binkert.orgmain.Append(BUILDERS = { 'ConfigFile' : config_builder })
11515863Snate@binkert.org
115210135SCurtis.Dunham@arm.com# libelf build is shared across all configs in the build root.
115312563Sgabeblack@google.commain.SConscript('ext/libelf/SConscript',
115412034Sgabeblack@google.com                variant_dir = joinpath(build_root, 'libelf'))
115512034Sgabeblack@google.com
115612034Sgabeblack@google.com# gzstream build is shared across all configs in the build root.
11572632Sstever@eecs.umich.edumain.SConscript('ext/gzstream/SConscript',
11585863Snate@binkert.org                variant_dir = joinpath(build_root, 'gzstream'))
11592023SN/A
11602632Sstever@eecs.umich.edu# libfdt build is shared across all configs in the build root.
11615863Snate@binkert.orgmain.SConscript('ext/libfdt/SConscript',
11625342Sstever@gmail.com                variant_dir = joinpath(build_root, 'libfdt'))
11635863Snate@binkert.org
11642632Sstever@eecs.umich.edu# fputils build is shared across all configs in the build root.
11655863Snate@binkert.orgmain.SConscript('ext/fputils/SConscript',
11665863Snate@binkert.org                variant_dir = joinpath(build_root, 'fputils'))
11678267Ssteve.reinhardt@amd.com
11688120Sgblack@eecs.umich.edu# DRAMSim2 build is shared across all configs in the build root.
11698267Ssteve.reinhardt@amd.commain.SConscript('ext/dramsim2/SConscript',
11708267Ssteve.reinhardt@amd.com                variant_dir = joinpath(build_root, 'dramsim2'))
11718267Ssteve.reinhardt@amd.com
11728267Ssteve.reinhardt@amd.com###################################################
11738267Ssteve.reinhardt@amd.com#
11748267Ssteve.reinhardt@amd.com# This function is used to set up a directory with switching headers
11758267Ssteve.reinhardt@amd.com#
11768267Ssteve.reinhardt@amd.com###################################################
11778267Ssteve.reinhardt@amd.com
11785863Snate@binkert.orgmain['ALL_ISA_LIST'] = all_isa_list
117912563Sgabeblack@google.comall_isa_deps = {}
118012563Sgabeblack@google.comdef make_switching_dir(dname, switch_headers, env):
11812632Sstever@eecs.umich.edu    # Generate the header.  target[0] is the full path of the output
118212563Sgabeblack@google.com    # header to generate.  'source' is a dummy variable, since we get the
118312563Sgabeblack@google.com    # list of ISAs from env['ALL_ISA_LIST'].
118412563Sgabeblack@google.com    def gen_switch_hdr(target, source, env):
11852632Sstever@eecs.umich.edu        fname = str(target[0])
11861888SN/A        isa = env['TARGET_ISA'].lower()
11875863Snate@binkert.org        try:
11885863Snate@binkert.org            f = open(fname, 'w')
11891858SN/A            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
11908120Sgblack@eecs.umich.edu            f.close()
11918120Sgblack@eecs.umich.edu        except IOError:
11927756SAli.Saidi@ARM.com            print "Failed to create %s" % fname
11932598SN/A            raise
11945863Snate@binkert.org
11951858SN/A    # Build SCons Action object. 'varlist' specifies env vars that this
11961858SN/A    # action depends on; when env['ALL_ISA_LIST'] changes these actions
119712563Sgabeblack@google.com    # should get re-executed.
119812563Sgabeblack@google.com    switch_hdr_action = MakeAction(gen_switch_hdr,
11991858SN/A                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
12001858SN/A
12011858SN/A    # Instantiate actions for each header
120212563Sgabeblack@google.com    for hdr in switch_headers:
120312563Sgabeblack@google.com        env.Command(hdr, [], switch_hdr_action)
120412563Sgabeblack@google.com
12051858SN/A    isa_target = Dir('.').up().name.lower().replace('_', '-')
120612230Sgiacomo.travaglini@arm.com    env['PHONY_BASE'] = '#'+isa_target
120712563Sgabeblack@google.com    all_isa_deps[isa_target] = None
120812563Sgabeblack@google.com
120912230Sgiacomo.travaglini@arm.comExport('make_switching_dir')
121012230Sgiacomo.travaglini@arm.com
121112230Sgiacomo.travaglini@arm.com# all-isas -> all-deps -> all-environs -> all_targets
121212230Sgiacomo.travaglini@arm.commain.Alias('#all-isas', [])
121312230Sgiacomo.travaglini@arm.commain.Alias('#all-deps', '#all-isas')
12141858SN/A
12151858SN/A# Dummy target to ensure all environments are created before telling
12161858SN/A# SCons what to actually make (the command line arguments).  We attach
12179651SAndreas.Sandberg@ARM.com# them to the dependence graph after the environments are complete.
12189651SAndreas.Sandberg@ARM.comORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
121912563Sgabeblack@google.comdef environsComplete(target, source, env):
122012563Sgabeblack@google.com    for t in ORIG_BUILD_TARGETS:
12219651SAndreas.Sandberg@ARM.com        main.Depends('#all-targets', t)
12229651SAndreas.Sandberg@ARM.com
122312563Sgabeblack@google.com# Each build/* switching_dir attaches its *-environs target to #all-environs.
122412563Sgabeblack@google.commain.Append(BUILDERS = {'CompleteEnvirons' :
12259651SAndreas.Sandberg@ARM.com                        Builder(action=MakeAction(environsComplete, None))})
12269651SAndreas.Sandberg@ARM.commain.CompleteEnvirons('#all-environs', [])
122712056Sgabeblack@google.com
122812056Sgabeblack@google.comdef doNothing(**ignored): pass
122912563Sgabeblack@google.commain.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
123012056Sgabeblack@google.com
123112056Sgabeblack@google.com# The final target to which all the original targets ultimately get attached.
123211798Santhony.gutierrez@amd.commain.Dummy('#all-targets', '#all-environs')
123311798Santhony.gutierrez@amd.comBUILD_TARGETS[:] = ['#all-targets']
123411798Santhony.gutierrez@amd.com
12359986Sandreas@sandberg.pp.se###################################################
12369986Sandreas@sandberg.pp.se#
12379986Sandreas@sandberg.pp.se# Define build environments for selected configurations.
123812563Sgabeblack@google.com#
123912563Sgabeblack@google.com###################################################
124012563Sgabeblack@google.com
12419986Sandreas@sandberg.pp.sefor variant_path in variant_paths:
12425863Snate@binkert.org    if not GetOption('silent'):
12435863Snate@binkert.org        print "Building in", variant_path
12441869SN/A
12451965SN/A    # Make a copy of the build-root environment to use for this config.
12467739Sgblack@eecs.umich.edu    env = main.Clone()
12471965SN/A    env['BUILDDIR'] = variant_path
12482761Sstever@eecs.umich.edu
12495863Snate@binkert.org    # variant_dir is the tail component of build path, and is used to
12501869SN/A    # determine the build parameters (e.g., 'ALPHA_SE')
125110196SCurtis.Dunham@arm.com    (build_root, variant_dir) = splitpath(variant_path)
12521869SN/A
12538120Sgblack@eecs.umich.edu    # Set env variables according to the build directory config.
12548120Sgblack@eecs.umich.edu    sticky_vars.files = []
12558120Sgblack@eecs.umich.edu    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
12568120Sgblack@eecs.umich.edu    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
12578120Sgblack@eecs.umich.edu    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
12588120Sgblack@eecs.umich.edu    current_vars_file = joinpath(build_root, 'variables', variant_dir)
12598120Sgblack@eecs.umich.edu    if isfile(current_vars_file):
12608120Sgblack@eecs.umich.edu        sticky_vars.files.append(current_vars_file)
12618120Sgblack@eecs.umich.edu        if not GetOption('silent'):
12628120Sgblack@eecs.umich.edu            print "Using saved variables file %s" % current_vars_file
12638120Sgblack@eecs.umich.edu    else:
12648120Sgblack@eecs.umich.edu        # Build dir-specific variables file doesn't exist.
1265
1266        # Make sure the directory is there so we can create it later
1267        opt_dir = dirname(current_vars_file)
1268        if not isdir(opt_dir):
1269            mkdir(opt_dir)
1270
1271        # Get default build variables from source tree.  Variables are
1272        # normally determined by name of $VARIANT_DIR, but can be
1273        # overridden by '--default=' arg on command line.
1274        default = GetOption('default')
1275        opts_dir = joinpath(main.root.abspath, 'build_opts')
1276        if default:
1277            default_vars_files = [joinpath(build_root, 'variables', default),
1278                                  joinpath(opts_dir, default)]
1279        else:
1280            default_vars_files = [joinpath(opts_dir, variant_dir)]
1281        existing_files = filter(isfile, default_vars_files)
1282        if existing_files:
1283            default_vars_file = existing_files[0]
1284            sticky_vars.files.append(default_vars_file)
1285            print "Variables file %s not found,\n  using defaults in %s" \
1286                  % (current_vars_file, default_vars_file)
1287        else:
1288            print "Error: cannot find variables file %s or " \
1289                  "default file(s) %s" \
1290                  % (current_vars_file, ' or '.join(default_vars_files))
1291            Exit(1)
1292
1293    # Apply current variable settings to env
1294    sticky_vars.Update(env)
1295
1296    help_texts["local_vars"] += \
1297        "Build variables for %s:\n" % variant_dir \
1298                 + sticky_vars.GenerateHelpText(env)
1299
1300    # Process variable settings.
1301
1302    if not have_fenv and env['USE_FENV']:
1303        print "Warning: <fenv.h> not available; " \
1304              "forcing USE_FENV to False in", variant_dir + "."
1305        env['USE_FENV'] = False
1306
1307    if not env['USE_FENV']:
1308        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1309        print "         FP results may deviate slightly from other platforms."
1310
1311    if env['EFENCE']:
1312        env.Append(LIBS=['efence'])
1313
1314    if env['USE_KVM']:
1315        if not have_kvm:
1316            print "Warning: Can not enable KVM, host seems to lack KVM support"
1317            env['USE_KVM'] = False
1318        elif not have_posix_timers:
1319            print "Warning: Can not enable KVM, host seems to lack support " \
1320                "for POSIX timers"
1321            env['USE_KVM'] = False
1322        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1323            print "Info: KVM support disabled due to unsupported host and " \
1324                "target ISA combination"
1325            env['USE_KVM'] = False
1326
1327    # Warn about missing optional functionality
1328    if env['USE_KVM']:
1329        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1330            print "Warning: perf_event headers lack support for the " \
1331                "exclude_host attribute. KVM instruction counts will " \
1332                "be inaccurate."
1333
1334    # Save sticky variable settings back to current variables file
1335    sticky_vars.Save(current_vars_file, env)
1336
1337    if env['USE_SSE2']:
1338        env.Append(CCFLAGS=['-msse2'])
1339
1340    # The src/SConscript file sets up the build rules in 'env' according
1341    # to the configured variables.  It returns a list of environments,
1342    # one for each variant build (debug, opt, etc.)
1343    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1344
1345def pairwise(iterable):
1346    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1347    a, b = itertools.tee(iterable)
1348    b.next()
1349    return itertools.izip(a, b)
1350
1351# Create false dependencies so SCons will parse ISAs, establish
1352# dependencies, and setup the build Environments serially. Either
1353# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1354# greater than 1. It appears to be standard race condition stuff; it
1355# doesn't always fail, but usually, and the behaviors are different.
1356# Every time I tried to remove this, builds would fail in some
1357# creative new way. So, don't do that. You'll want to, though, because
1358# tests/SConscript takes a long time to make its Environments.
1359for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1360    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1361    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1362
1363# base help text
1364Help('''
1365Usage: scons [scons options] [build variables] [target(s)]
1366
1367Extra scons options:
1368%(options)s
1369
1370Global build variables:
1371%(global_vars)s
1372
1373%(local_vars)s
1374''' % help_texts)
1375