SConstruct revision 11982
1955SN/A# -*- mode:python -*-
2955SN/A
39812Sandreas.hansson@arm.com# Copyright (c) 2013, 2015, 2016 ARM Limited
49812Sandreas.hansson@arm.com# All rights reserved.
59812Sandreas.hansson@arm.com#
69812Sandreas.hansson@arm.com# The license below extends only to copyright in the software and shall
79812Sandreas.hansson@arm.com# not be construed as granting a license to any other intellectual
89812Sandreas.hansson@arm.com# property including but not limited to intellectual property relating
99812Sandreas.hansson@arm.com# to a hardware implementation of the functionality of the software
109812Sandreas.hansson@arm.com# licensed hereunder.  You may use the software subject to the license
119812Sandreas.hansson@arm.com# terms below provided that you ensure that this notice is replicated
129812Sandreas.hansson@arm.com# unmodified and in its entirety in all distributions of the software,
139812Sandreas.hansson@arm.com# modified or unmodified, in source code or in binary form.
149812Sandreas.hansson@arm.com#
157816Ssteve.reinhardt@amd.com# Copyright (c) 2011 Advanced Micro Devices, Inc.
165871Snate@binkert.org# Copyright (c) 2009 The Hewlett-Packard Development Company
171762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
28955SN/A# contributors may be used to endorse or promote products derived from
29955SN/A# this software without specific prior written permission.
30955SN/A#
31955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
35955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
36955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
37955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
38955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
40955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
41955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422665Ssaidi@eecs.umich.edu#
432665Ssaidi@eecs.umich.edu# Authors: Steve Reinhardt
445863Snate@binkert.org#          Nathan Binkert
45955SN/A
46955SN/A###################################################
47955SN/A#
48955SN/A# SCons top-level build description (SConstruct) file.
49955SN/A#
508878Ssteve.reinhardt@amd.com# While in this directory ('gem5'), just type 'scons' to build the default
512632Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
528878Ssteve.reinhardt@amd.com# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532632Sstever@eecs.umich.edu# the optimized full-system version).
54955SN/A#
558878Ssteve.reinhardt@amd.com# You can build gem5 in a different directory as long as there is a
562632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572761Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582632Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612761Sstever@eecs.umich.edu#
622761Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
632761Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
648878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
658878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
662761Sstever@eecs.umich.edu#
672761Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
682761Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
692761Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
702761Sstever@eecs.umich.edu#   file.
718878Ssteve.reinhardt@amd.com#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
728878Ssteve.reinhardt@amd.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732632Sstever@eecs.umich.edu#
742632Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
758878Ssteve.reinhardt@amd.com# 'gem5' directory (or use -u or -C to tell scons where to find this
768878Ssteve.reinhardt@amd.com# file), you can use 'scons -h' to print all the gem5-specific build
772632Sstever@eecs.umich.edu# options as well.
78955SN/A#
79955SN/A###################################################
80955SN/A
815863Snate@binkert.org# Check for recent-enough Python and SCons versions.
825863Snate@binkert.orgtry:
835863Snate@binkert.org    # Really old versions of scons only take two options for the
845863Snate@binkert.org    # function, so check once without the revision and once with the
855863Snate@binkert.org    # revision, the first instance will fail for stuff other than
865863Snate@binkert.org    # 0.98, and the second will fail for 0.98.0
875863Snate@binkert.org    EnsureSConsVersion(0, 98)
885863Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
895863Snate@binkert.orgexcept SystemExit, e:
905863Snate@binkert.org    print """
915863Snate@binkert.orgFor more details, see:
928878Ssteve.reinhardt@amd.com    http://gem5.org/Dependencies
935863Snate@binkert.org"""
945863Snate@binkert.org    raise
955863Snate@binkert.org
969812Sandreas.hansson@arm.com# We ensure the python version early because because python-config
979812Sandreas.hansson@arm.com# requires python 2.5
985863Snate@binkert.orgtry:
999812Sandreas.hansson@arm.com    EnsurePythonVersion(2, 5)
1005863Snate@binkert.orgexcept SystemExit, e:
1015863Snate@binkert.org    print """
1025863Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
1039812Sandreas.hansson@arm.comrearranging your PATH so that scons finds the non-default 'python' and
1049812Sandreas.hansson@arm.com'python-config' first.
1055863Snate@binkert.org
1065863Snate@binkert.orgFor more details, see:
1078878Ssteve.reinhardt@amd.com    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1085863Snate@binkert.org"""
1095863Snate@binkert.org    raise
1105863Snate@binkert.org
1116654Snate@binkert.org# Global Python includes
11210196SCurtis.Dunham@arm.comimport itertools
113955SN/Aimport os
1145396Ssaidi@eecs.umich.eduimport re
1155863Snate@binkert.orgimport shutil
1165863Snate@binkert.orgimport subprocess
1174202Sbinkertn@umich.eduimport sys
1185863Snate@binkert.org
1195863Snate@binkert.orgfrom os import mkdir, environ
1205863Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1215863Snate@binkert.orgfrom os.path import exists,  isdir, isfile
122955SN/Afrom os.path import join as joinpath, split as splitpath
1236654Snate@binkert.org
1245273Sstever@gmail.com# SCons includes
1255871Snate@binkert.orgimport SCons
1265273Sstever@gmail.comimport SCons.Node
1276655Snate@binkert.org
1288878Ssteve.reinhardt@amd.comextra_python_paths = [
1296655Snate@binkert.org    Dir('src/python').srcnode().abspath, # gem5 includes
1306655Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1319219Spower.jg@gmail.com    ]
1326655Snate@binkert.org
1335871Snate@binkert.orgsys.path[1:1] = extra_python_paths
1346654Snate@binkert.org
1358947Sandreas.hansson@arm.comfrom m5.util import compareVersions, readCommand
1365396Ssaidi@eecs.umich.edufrom m5.util.terminal import get_termcap
1378120Sgblack@eecs.umich.edu
1388120Sgblack@eecs.umich.eduhelp_texts = {
1398120Sgblack@eecs.umich.edu    "options" : "",
1408120Sgblack@eecs.umich.edu    "global_vars" : "",
1418120Sgblack@eecs.umich.edu    "local_vars" : ""
1428120Sgblack@eecs.umich.edu}
1438120Sgblack@eecs.umich.edu
1448120Sgblack@eecs.umich.eduExport("help_texts")
1458879Ssteve.reinhardt@amd.com
1468879Ssteve.reinhardt@amd.com
1478879Ssteve.reinhardt@amd.com# There's a bug in scons in that (1) by default, the help texts from
1488879Ssteve.reinhardt@amd.com# AddOption() are supposed to be displayed when you type 'scons -h'
1498879Ssteve.reinhardt@amd.com# and (2) you can override the help displayed by 'scons -h' using the
1508879Ssteve.reinhardt@amd.com# Help() function, but these two features are incompatible: once
1518879Ssteve.reinhardt@amd.com# you've overridden the help text using Help(), there's no way to get
1528879Ssteve.reinhardt@amd.com# at the help texts from AddOptions.  See:
1538879Ssteve.reinhardt@amd.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1548879Ssteve.reinhardt@amd.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1558879Ssteve.reinhardt@amd.com# This hack lets us extract the help text from AddOptions and
1568879Ssteve.reinhardt@amd.com# re-inject it via Help().  Ideally someday this bug will be fixed and
1578879Ssteve.reinhardt@amd.com# we can just use AddOption directly.
1588120Sgblack@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1598120Sgblack@eecs.umich.edu    col_width = 30
1608120Sgblack@eecs.umich.edu
1618120Sgblack@eecs.umich.edu    help = "  " + ", ".join(args)
1628120Sgblack@eecs.umich.edu    if "help" in kwargs:
1638120Sgblack@eecs.umich.edu        length = len(help)
1648120Sgblack@eecs.umich.edu        if length >= col_width:
1658120Sgblack@eecs.umich.edu            help += "\n" + " " * col_width
1668120Sgblack@eecs.umich.edu        else:
1678120Sgblack@eecs.umich.edu            help += " " * (col_width - length)
1688120Sgblack@eecs.umich.edu        help += kwargs["help"]
1698120Sgblack@eecs.umich.edu    help_texts["options"] += help + "\n"
1708120Sgblack@eecs.umich.edu
1718120Sgblack@eecs.umich.edu    AddOption(*args, **kwargs)
1728879Ssteve.reinhardt@amd.com
1738879Ssteve.reinhardt@amd.comAddLocalOption('--colors', dest='use_colors', action='store_true',
1748879Ssteve.reinhardt@amd.com               help="Add color to abbreviated scons output")
1758879Ssteve.reinhardt@amd.comAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1768879Ssteve.reinhardt@amd.com               help="Don't add color to abbreviated scons output")
1778879Ssteve.reinhardt@amd.comAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1788879Ssteve.reinhardt@amd.com               action='store_true',
1798879Ssteve.reinhardt@amd.com               help="Build with support for C++-based configuration")
1809227Sandreas.hansson@arm.comAddLocalOption('--default', dest='default', type='string', action='store',
1819227Sandreas.hansson@arm.com               help='Override which build_opts file to use for defaults')
1828879Ssteve.reinhardt@amd.comAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1838879Ssteve.reinhardt@amd.com               help='Disable style checking hooks')
1848879Ssteve.reinhardt@amd.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1858879Ssteve.reinhardt@amd.com               help='Disable Link-Time Optimization for fast')
18610453SAndrew.Bardsley@arm.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
18710453SAndrew.Bardsley@arm.com               help='Update test reference outputs')
18810453SAndrew.Bardsley@arm.comAddLocalOption('--verbose', dest='verbose', action='store_true',
18910456SCurtis.Dunham@arm.com               help='Print full tool command lines')
19010456SCurtis.Dunham@arm.comAddLocalOption('--without-python', dest='without_python',
19110456SCurtis.Dunham@arm.com               action='store_true',
1928120Sgblack@eecs.umich.edu               help='Build without Python configuration support')
1938947Sandreas.hansson@arm.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1947816Ssteve.reinhardt@amd.com               action='store_true',
1955871Snate@binkert.org               help='Disable linking against tcmalloc')
1965871Snate@binkert.orgAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1976121Snate@binkert.org               help='Build with Undefined Behavior Sanitizer if available')
1985871Snate@binkert.orgAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1995871Snate@binkert.org               help='Build with Address Sanitizer if available')
2009926Sstan.czerniawski@arm.com
2019926Sstan.czerniawski@arm.comtermcap = get_termcap(GetOption('use_colors'))
2029119Sandreas.hansson@arm.com
20310068Sandreas.hansson@arm.com########################################################################
20410068Sandreas.hansson@arm.com#
205955SN/A# Set up the main build environment.
2069416SAndreas.Sandberg@ARM.com#
2079416SAndreas.Sandberg@ARM.com########################################################################
2089416SAndreas.Sandberg@ARM.com
2099416SAndreas.Sandberg@ARM.com# export TERM so that clang reports errors in color
2109416SAndreas.Sandberg@ARM.comuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2119416SAndreas.Sandberg@ARM.com                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2129416SAndreas.Sandberg@ARM.com                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
2135871Snate@binkert.org
2145871Snate@binkert.orguse_prefixes = [
2159416SAndreas.Sandberg@ARM.com    "ASAN_",           # address sanitizer symbolizer path and settings
2169416SAndreas.Sandberg@ARM.com    "CCACHE_",         # ccache (caching compiler wrapper) configuration
2175871Snate@binkert.org    "CCC_",            # clang static analyzer configuration
218955SN/A    "DISTCC_",         # distcc (distributed compiler wrapper) configuration
2196121Snate@binkert.org    "INCLUDE_SERVER_", # distcc pump server settings
2208881Smarc.orr@gmail.com    "M5",              # M5 configuration (e.g., path to kernels)
2216121Snate@binkert.org    ]
2226121Snate@binkert.org
2231533SN/Ause_env = {}
2249239Sandreas.hansson@arm.comfor key,val in sorted(os.environ.iteritems()):
2259239Sandreas.hansson@arm.com    if key in use_vars or \
2269239Sandreas.hansson@arm.com            any([key.startswith(prefix) for prefix in use_prefixes]):
2279239Sandreas.hansson@arm.com        use_env[key] = val
2289239Sandreas.hansson@arm.com
2299239Sandreas.hansson@arm.com# Tell scons to avoid implicit command dependencies to avoid issues
2309239Sandreas.hansson@arm.com# with the param wrappes being compiled twice (see
2319239Sandreas.hansson@arm.com# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2329239Sandreas.hansson@arm.commain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2339239Sandreas.hansson@arm.commain.Decider('MD5-timestamp')
2349239Sandreas.hansson@arm.commain.root = Dir(".")         # The current directory (where this file lives).
2359239Sandreas.hansson@arm.commain.srcdir = Dir("src")     # The source directory
2366655Snate@binkert.org
2376655Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
2386655Snate@binkert.org
2396655Snate@binkert.org# Check that we have a C/C++ compiler
2405871Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2415871Snate@binkert.org    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2425863Snate@binkert.org    Exit(1)
2435871Snate@binkert.org
2448878Ssteve.reinhardt@amd.com# Check that swig is present
2455871Snate@binkert.orgif not 'SWIG' in main_dict_keys:
2465871Snate@binkert.org    print "swig is not installed (package swig on Ubuntu and RedHat)"
2475871Snate@binkert.org    Exit(1)
2485863Snate@binkert.org
2496121Snate@binkert.org# add useful python code PYTHONPATH so it can be used by subprocesses
2505863Snate@binkert.org# as well
2515871Snate@binkert.orgmain.AppendENVPath('PYTHONPATH', extra_python_paths)
2528336Ssteve.reinhardt@amd.com
2538336Ssteve.reinhardt@amd.com########################################################################
2548336Ssteve.reinhardt@amd.com#
2558336Ssteve.reinhardt@amd.com# Mercurial Stuff.
2564678Snate@binkert.org#
2578336Ssteve.reinhardt@amd.com# If the gem5 directory is a mercurial repository, we should do some
2588336Ssteve.reinhardt@amd.com# extra things.
2598336Ssteve.reinhardt@amd.com#
2604678Snate@binkert.org########################################################################
2614678Snate@binkert.org
2624678Snate@binkert.orghgdir = main.root.Dir(".hg")
2634678Snate@binkert.org
2647827Snate@binkert.org
2657827Snate@binkert.orgstyle_message = """
2668336Ssteve.reinhardt@amd.comYou're missing the gem5 style hook, which automatically checks your code
2674678Snate@binkert.orgagainst the gem5 style rules on %s.
2688336Ssteve.reinhardt@amd.comThis script will now install the hook in your %s.
2698336Ssteve.reinhardt@amd.comPress enter to continue, or ctrl-c to abort: """
2708336Ssteve.reinhardt@amd.com
2718336Ssteve.reinhardt@amd.commercurial_style_message = """
2728336Ssteve.reinhardt@amd.comYou're missing the gem5 style hook, which automatically checks your code
2738336Ssteve.reinhardt@amd.comagainst the gem5 style rules on hg commit and qrefresh commands.
2745871Snate@binkert.orgThis script will now install the hook in your .hg/hgrc file.
2755871Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
2768336Ssteve.reinhardt@amd.com
2778336Ssteve.reinhardt@amd.comgit_style_message = """
2788336Ssteve.reinhardt@amd.comYou're missing the gem5 style or commit message hook. These hooks help
2798336Ssteve.reinhardt@amd.comto ensure that your code follows gem5's style rules on git commit.
2808336Ssteve.reinhardt@amd.comThis script will now install the hook in your .git/hooks/ directory.
2815871Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
2828336Ssteve.reinhardt@amd.com
2838336Ssteve.reinhardt@amd.commercurial_style_upgrade_message = """
2848336Ssteve.reinhardt@amd.comYour Mercurial style hooks are not up-to-date. This script will now
2858336Ssteve.reinhardt@amd.comtry to automatically update them. A backup of your hgrc will be saved
2868336Ssteve.reinhardt@amd.comin .hg/hgrc.old.
2874678Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
2885871Snate@binkert.org
2894678Snate@binkert.orgmercurial_style_hook = """
2908336Ssteve.reinhardt@amd.com# The following lines were automatically added by gem5/SConstruct
2918336Ssteve.reinhardt@amd.com# to provide the gem5 style-checking hooks
2928336Ssteve.reinhardt@amd.com[extensions]
2938336Ssteve.reinhardt@amd.comhgstyle = %s/util/hgstyle.py
2948336Ssteve.reinhardt@amd.com
2958336Ssteve.reinhardt@amd.com[hooks]
2968336Ssteve.reinhardt@amd.compretxncommit.style = python:hgstyle.check_style
2978336Ssteve.reinhardt@amd.compre-qrefresh.style = python:hgstyle.check_style
2988336Ssteve.reinhardt@amd.com# End of SConstruct additions
2998336Ssteve.reinhardt@amd.com
3008336Ssteve.reinhardt@amd.com""" % (main.root.abspath)
3018336Ssteve.reinhardt@amd.com
3028336Ssteve.reinhardt@amd.commercurial_lib_not_found = """
3038336Ssteve.reinhardt@amd.comMercurial libraries cannot be found, ignoring style hook.  If
3048336Ssteve.reinhardt@amd.comyou are a gem5 developer, please fix this and run the style
3058336Ssteve.reinhardt@amd.comhook. It is important.
3068336Ssteve.reinhardt@amd.com"""
3075871Snate@binkert.org
3086121Snate@binkert.org# Check for style hook and prompt for installation if it's not there.
309955SN/A# Skip this if --ignore-style was specified, there's no interactive
310955SN/A# terminal to prompt, or no recognized revision control system can be
3112632Sstever@eecs.umich.edu# found.
3122632Sstever@eecs.umich.eduignore_style = GetOption('ignore_style') or not sys.stdin.isatty()
313955SN/A
314955SN/A# Try wire up Mercurial to the style hooks
315955SN/Aif not ignore_style and hgdir.exists():
316955SN/A    style_hook = True
3178878Ssteve.reinhardt@amd.com    style_hooks = tuple()
318955SN/A    hgrc = hgdir.File('hgrc')
3192632Sstever@eecs.umich.edu    hgrc_old = hgdir.File('hgrc.old')
3202632Sstever@eecs.umich.edu    try:
3212632Sstever@eecs.umich.edu        from mercurial import ui
3222632Sstever@eecs.umich.edu        ui = ui.ui()
3232632Sstever@eecs.umich.edu        ui.readconfig(hgrc.abspath)
3242632Sstever@eecs.umich.edu        style_hooks = (ui.config('hooks', 'pretxncommit.style', None),
3252632Sstever@eecs.umich.edu                       ui.config('hooks', 'pre-qrefresh.style', None))
3268268Ssteve.reinhardt@amd.com        style_hook = all(style_hooks)
3278268Ssteve.reinhardt@amd.com        style_extension = ui.config('extensions', 'style', None)
3288268Ssteve.reinhardt@amd.com    except ImportError:
3298268Ssteve.reinhardt@amd.com        print mercurial_lib_not_found
3308268Ssteve.reinhardt@amd.com
3318268Ssteve.reinhardt@amd.com    if "python:style.check_style" in style_hooks:
3328268Ssteve.reinhardt@amd.com        # Try to upgrade the style hooks
3332632Sstever@eecs.umich.edu        print mercurial_style_upgrade_message
3342632Sstever@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
3352632Sstever@eecs.umich.edu        try:
3362632Sstever@eecs.umich.edu            raw_input()
3378268Ssteve.reinhardt@amd.com        except:
3382632Sstever@eecs.umich.edu            print "Input exception, exiting scons.\n"
3398268Ssteve.reinhardt@amd.com            sys.exit(1)
3408268Ssteve.reinhardt@amd.com        shutil.copyfile(hgrc.abspath, hgrc_old.abspath)
3418268Ssteve.reinhardt@amd.com        re_style_hook = re.compile(r"^([^=#]+)\.style\s*=\s*([^#\s]+).*")
3428268Ssteve.reinhardt@amd.com        re_style_extension = re.compile("style\s*=\s*([^#\s]+).*")
3433718Sstever@eecs.umich.edu        old, new = open(hgrc_old.abspath, 'r'), open(hgrc.abspath, 'w')
3442634Sstever@eecs.umich.edu        for l in old:
3452634Sstever@eecs.umich.edu            m_hook = re_style_hook.match(l)
3465863Snate@binkert.org            m_ext = re_style_extension.match(l)
3472638Sstever@eecs.umich.edu            if m_hook:
3488268Ssteve.reinhardt@amd.com                hook, check = m_hook.groups()
3492632Sstever@eecs.umich.edu                if check != "python:style.check_style":
3502632Sstever@eecs.umich.edu                    print "Warning: %s.style is using a non-default " \
3512632Sstever@eecs.umich.edu                        "checker: %s" % (hook, check)
3522632Sstever@eecs.umich.edu                if hook not in ("pretxncommit", "pre-qrefresh"):
3532632Sstever@eecs.umich.edu                    print "Warning: Updating unknown style hook: %s" % hook
3541858SN/A
3553716Sstever@eecs.umich.edu                l = "%s.style = python:hgstyle.check_style\n" % hook
3562638Sstever@eecs.umich.edu            elif m_ext and m_ext.group(1) == style_extension:
3572638Sstever@eecs.umich.edu                l = "hgstyle = %s/util/hgstyle.py\n" % main.root.abspath
3582638Sstever@eecs.umich.edu
3592638Sstever@eecs.umich.edu            new.write(l)
3602638Sstever@eecs.umich.edu    elif not style_hook:
3612638Sstever@eecs.umich.edu        print mercurial_style_message,
3622638Sstever@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
3635863Snate@binkert.org        try:
3645863Snate@binkert.org            raw_input()
3655863Snate@binkert.org        except:
366955SN/A            print "Input exception, exiting scons.\n"
3675341Sstever@gmail.com            sys.exit(1)
3685341Sstever@gmail.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3695863Snate@binkert.org        print "Adding style hook to", hgrc_path, "\n"
3707756SAli.Saidi@ARM.com        try:
3715341Sstever@gmail.com            with open(hgrc_path, 'a') as f:
3726121Snate@binkert.org                f.write(mercurial_style_hook)
3734494Ssaidi@eecs.umich.edu        except:
3746121Snate@binkert.org            print "Error updating", hgrc_path
3751105SN/A            sys.exit(1)
3762667Sstever@eecs.umich.edu
3772667Sstever@eecs.umich.edudef install_git_style_hooks():
3782667Sstever@eecs.umich.edu    try:
3792667Sstever@eecs.umich.edu        gitdir = Dir(readCommand(
3806121Snate@binkert.org            ["git", "rev-parse", "--git-dir"]).strip("\n"))
3812667Sstever@eecs.umich.edu    except Exception, e:
3825341Sstever@gmail.com        print "Warning: Failed to find git repo directory: %s" % e
3835863Snate@binkert.org        return
3845341Sstever@gmail.com
3855341Sstever@gmail.com    git_hooks = gitdir.Dir("hooks")
3865341Sstever@gmail.com    def hook_exists(hook_name):
3878120Sgblack@eecs.umich.edu        hook = git_hooks.File(hook_name)
3885341Sstever@gmail.com        return hook.exists()
3898120Sgblack@eecs.umich.edu
3905341Sstever@gmail.com    def hook_install(hook_name, script):
3918120Sgblack@eecs.umich.edu        hook = git_hooks.File(hook_name)
3926121Snate@binkert.org        if hook.exists():
3936121Snate@binkert.org            print "Warning: Can't install %s, hook already exists." % hook_name
3948980Ssteve.reinhardt@amd.com            return
3959396Sandreas.hansson@arm.com
3965397Ssaidi@eecs.umich.edu        if hook.islink():
3975397Ssaidi@eecs.umich.edu            print "Warning: Removing broken symlink for hook %s." % hook_name
3987727SAli.Saidi@ARM.com            os.unlink(hook.get_abspath())
3998268Ssteve.reinhardt@amd.com
4006168Snate@binkert.org        if not git_hooks.exists():
4015341Sstever@gmail.com            mkdir(git_hooks.get_abspath())
4028120Sgblack@eecs.umich.edu            git_hooks.clear()
4038120Sgblack@eecs.umich.edu
4048120Sgblack@eecs.umich.edu        abs_symlink_hooks = git_hooks.islink() and \
4056814Sgblack@eecs.umich.edu            os.path.isabs(os.readlink(git_hooks.get_abspath()))
4065863Snate@binkert.org
4078120Sgblack@eecs.umich.edu        # Use a relative symlink if the hooks live in the source directory,
4085341Sstever@gmail.com        # and the hooks directory is not a symlink to an absolute path.
4095863Snate@binkert.org        if hook.is_under(main.root) and not abs_symlink_hooks:
4108268Ssteve.reinhardt@amd.com            script_path = os.path.relpath(
4116121Snate@binkert.org                os.path.realpath(script.get_abspath()),
4126121Snate@binkert.org                os.path.realpath(hook.Dir(".").get_abspath()))
4138268Ssteve.reinhardt@amd.com        else:
4145742Snate@binkert.org            script_path = script.get_abspath()
4155742Snate@binkert.org
4165341Sstever@gmail.com        try:
4175742Snate@binkert.org            os.symlink(script_path, hook.get_abspath())
4185742Snate@binkert.org        except:
4195341Sstever@gmail.com            print "Error updating git %s hook" % hook_name
4206017Snate@binkert.org            raise
4216121Snate@binkert.org
4226017Snate@binkert.org    if hook_exists("pre-commit") and hook_exists("commit-msg"):
4237816Ssteve.reinhardt@amd.com        return
4247756SAli.Saidi@ARM.com
4257756SAli.Saidi@ARM.com    print git_style_message,
4267756SAli.Saidi@ARM.com    try:
4277756SAli.Saidi@ARM.com        raw_input()
4287756SAli.Saidi@ARM.com    except:
4297756SAli.Saidi@ARM.com        print "Input exception, exiting scons.\n"
4307756SAli.Saidi@ARM.com        sys.exit(1)
4317756SAli.Saidi@ARM.com
4327816Ssteve.reinhardt@amd.com    git_style_script = File("util/git-pre-commit.py")
4337816Ssteve.reinhardt@amd.com    git_msg_script = File("ext/git-commit-msg")
4347816Ssteve.reinhardt@amd.com
4357816Ssteve.reinhardt@amd.com    hook_install("pre-commit", git_style_script)
4367816Ssteve.reinhardt@amd.com    hook_install("commit-msg", git_msg_script)
4377816Ssteve.reinhardt@amd.com
4387816Ssteve.reinhardt@amd.com# Try to wire up git to the style hooks
4397816Ssteve.reinhardt@amd.comif not ignore_style and main.root.Entry(".git").exists():
4407816Ssteve.reinhardt@amd.com    install_git_style_hooks()
4417816Ssteve.reinhardt@amd.com
4427756SAli.Saidi@ARM.com###################################################
4437816Ssteve.reinhardt@amd.com#
4447816Ssteve.reinhardt@amd.com# Figure out which configurations to set up based on the path(s) of
4457816Ssteve.reinhardt@amd.com# the target(s).
4467816Ssteve.reinhardt@amd.com#
4477816Ssteve.reinhardt@amd.com###################################################
4487816Ssteve.reinhardt@amd.com
4497816Ssteve.reinhardt@amd.com# Find default configuration & binary.
4507816Ssteve.reinhardt@amd.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
4517816Ssteve.reinhardt@amd.com
4527816Ssteve.reinhardt@amd.com# helper function: find last occurrence of element in list
4537816Ssteve.reinhardt@amd.comdef rfind(l, elt, offs = -1):
4547816Ssteve.reinhardt@amd.com    for i in range(len(l)+offs, 0, -1):
4557816Ssteve.reinhardt@amd.com        if l[i] == elt:
4567816Ssteve.reinhardt@amd.com            return i
4577816Ssteve.reinhardt@amd.com    raise ValueError, "element not found"
4587816Ssteve.reinhardt@amd.com
4597816Ssteve.reinhardt@amd.com# Take a list of paths (or SCons Nodes) and return a list with all
4607816Ssteve.reinhardt@amd.com# paths made absolute and ~-expanded.  Paths will be interpreted
4617816Ssteve.reinhardt@amd.com# relative to the launch directory unless a different root is provided
4627816Ssteve.reinhardt@amd.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
4637816Ssteve.reinhardt@amd.com    return [abspath(joinpath(root, expanduser(str(p))))
4647816Ssteve.reinhardt@amd.com            for p in path_list]
4657816Ssteve.reinhardt@amd.com
4667816Ssteve.reinhardt@amd.com# Each target must have 'build' in the interior of the path; the
4677816Ssteve.reinhardt@amd.com# directory below this will determine the build parameters.  For
4687816Ssteve.reinhardt@amd.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
4697816Ssteve.reinhardt@amd.com# recognize that ALPHA_SE specifies the configuration because it
4707816Ssteve.reinhardt@amd.com# follow 'build' in the build path.
4717816Ssteve.reinhardt@amd.com
4727816Ssteve.reinhardt@amd.com# The funky assignment to "[:]" is needed to replace the list contents
4737816Ssteve.reinhardt@amd.com# in place rather than reassign the symbol to a new list, which
4747816Ssteve.reinhardt@amd.com# doesn't work (obviously!).
4757816Ssteve.reinhardt@amd.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
4767816Ssteve.reinhardt@amd.com
4777816Ssteve.reinhardt@amd.com# Generate a list of the unique build roots and configs that the
4787816Ssteve.reinhardt@amd.com# collected targets reference.
4797816Ssteve.reinhardt@amd.comvariant_paths = []
4807816Ssteve.reinhardt@amd.combuild_root = None
4817816Ssteve.reinhardt@amd.comfor t in BUILD_TARGETS:
4827816Ssteve.reinhardt@amd.com    path_dirs = t.split('/')
4837816Ssteve.reinhardt@amd.com    try:
4847816Ssteve.reinhardt@amd.com        build_top = rfind(path_dirs, 'build', -2)
4857816Ssteve.reinhardt@amd.com    except:
4867816Ssteve.reinhardt@amd.com        print "Error: no non-leaf 'build' dir found on target path", t
4877816Ssteve.reinhardt@amd.com        Exit(1)
4887816Ssteve.reinhardt@amd.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
4897816Ssteve.reinhardt@amd.com    if not build_root:
4907816Ssteve.reinhardt@amd.com        build_root = this_build_root
4917816Ssteve.reinhardt@amd.com    else:
4927816Ssteve.reinhardt@amd.com        if this_build_root != build_root:
4937816Ssteve.reinhardt@amd.com            print "Error: build targets not under same build root\n"\
4947816Ssteve.reinhardt@amd.com                  "  %s\n  %s" % (build_root, this_build_root)
4957816Ssteve.reinhardt@amd.com            Exit(1)
4967816Ssteve.reinhardt@amd.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
4977816Ssteve.reinhardt@amd.com    if variant_path not in variant_paths:
4987816Ssteve.reinhardt@amd.com        variant_paths.append(variant_path)
4997816Ssteve.reinhardt@amd.com
5007816Ssteve.reinhardt@amd.com# Make sure build_root exists (might not if this is the first build there)
5017816Ssteve.reinhardt@amd.comif not isdir(build_root):
5027816Ssteve.reinhardt@amd.com    mkdir(build_root)
5037816Ssteve.reinhardt@amd.commain['BUILDROOT'] = build_root
5048947Sandreas.hansson@arm.com
5058947Sandreas.hansson@arm.comExport('main')
5067756SAli.Saidi@ARM.com
5078120Sgblack@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
5087756SAli.Saidi@ARM.com
5097756SAli.Saidi@ARM.com# Default duplicate option is to use hard links, but this messes up
5107756SAli.Saidi@ARM.com# when you use emacs to edit a file in the target dir, as emacs moves
5117756SAli.Saidi@ARM.com# file to file~ then copies to file, breaking the link.  Symbolic
5127816Ssteve.reinhardt@amd.com# (soft) links work better.
5137816Ssteve.reinhardt@amd.commain.SetOption('duplicate', 'soft-copy')
5147816Ssteve.reinhardt@amd.com
5157816Ssteve.reinhardt@amd.com#
5167816Ssteve.reinhardt@amd.com# Set up global sticky variables... these are common to an entire build
5177816Ssteve.reinhardt@amd.com# tree (not specific to a particular build like ALPHA_SE)
5187816Ssteve.reinhardt@amd.com#
5197816Ssteve.reinhardt@amd.com
5207816Ssteve.reinhardt@amd.comglobal_vars_file = joinpath(build_root, 'variables.global')
5217816Ssteve.reinhardt@amd.com
5227756SAli.Saidi@ARM.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
5237756SAli.Saidi@ARM.com
5249227Sandreas.hansson@arm.comglobal_vars.AddVariables(
5259227Sandreas.hansson@arm.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
5269227Sandreas.hansson@arm.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
5279227Sandreas.hansson@arm.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
5289590Sandreas@sandberg.pp.se    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
5299590Sandreas@sandberg.pp.se    ('BATCH', 'Use batch pool for build and tests', False),
5309590Sandreas@sandberg.pp.se    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
5319590Sandreas@sandberg.pp.se    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
5329590Sandreas@sandberg.pp.se    ('EXTRAS', 'Add extra directories to the compilation', '')
5339590Sandreas@sandberg.pp.se    )
5346654Snate@binkert.org
5356654Snate@binkert.org# Update main environment with values from ARGUMENTS & global_vars_file
5365871Snate@binkert.orgglobal_vars.Update(main)
5376121Snate@binkert.orghelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
5388946Sandreas.hansson@arm.com
5399419Sandreas.hansson@arm.com# Save sticky variable settings back to current variables file
5403940Ssaidi@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
5413918Ssaidi@eecs.umich.edu
5423918Ssaidi@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
5431858SN/A# look for sources etc.  This list is exported as extras_dir_list.
5449556Sandreas.hansson@arm.combase_dir = main.srcdir.abspath
5459556Sandreas.hansson@arm.comif main['EXTRAS']:
5469556Sandreas.hansson@arm.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
5479556Sandreas.hansson@arm.comelse:
5489556Sandreas.hansson@arm.com    extras_dir_list = []
5499556Sandreas.hansson@arm.com
5509556Sandreas.hansson@arm.comExport('base_dir')
5519556Sandreas.hansson@arm.comExport('extras_dir_list')
5529556Sandreas.hansson@arm.com
5539556Sandreas.hansson@arm.com# the ext directory should be on the #includes path
5549556Sandreas.hansson@arm.commain.Append(CPPPATH=[Dir('ext')])
5559556Sandreas.hansson@arm.com
5569556Sandreas.hansson@arm.comdef strip_build_path(path, env):
5579556Sandreas.hansson@arm.com    path = str(path)
5589556Sandreas.hansson@arm.com    variant_base = env['BUILDROOT'] + os.path.sep
5599556Sandreas.hansson@arm.com    if path.startswith(variant_base):
5609556Sandreas.hansson@arm.com        path = path[len(variant_base):]
5619556Sandreas.hansson@arm.com    elif path.startswith('build/'):
5629556Sandreas.hansson@arm.com        path = path[6:]
5639556Sandreas.hansson@arm.com    return path
5649556Sandreas.hansson@arm.com
5659556Sandreas.hansson@arm.com# Generate a string of the form:
5669556Sandreas.hansson@arm.com#   common/path/prefix/src1, src2 -> tgt1, tgt2
5679556Sandreas.hansson@arm.com# to print while building.
5689556Sandreas.hansson@arm.comclass Transform(object):
5699556Sandreas.hansson@arm.com    # all specific color settings should be here and nowhere else
5709556Sandreas.hansson@arm.com    tool_color = termcap.Normal
5719556Sandreas.hansson@arm.com    pfx_color = termcap.Yellow
5729556Sandreas.hansson@arm.com    srcs_color = termcap.Yellow + termcap.Bold
5739556Sandreas.hansson@arm.com    arrow_color = termcap.Blue + termcap.Bold
5749556Sandreas.hansson@arm.com    tgts_color = termcap.Yellow + termcap.Bold
5759556Sandreas.hansson@arm.com
5766121Snate@binkert.org    def __init__(self, tool, max_sources=99):
57710238Sandreas.hansson@arm.com        self.format = self.tool_color + (" [%8s] " % tool) \
57810238Sandreas.hansson@arm.com                      + self.pfx_color + "%s" \
57910238Sandreas.hansson@arm.com                      + self.srcs_color + "%s" \
58010238Sandreas.hansson@arm.com                      + self.arrow_color + " -> " \
5819420Sandreas.hansson@arm.com                      + self.tgts_color + "%s" \
58210238Sandreas.hansson@arm.com                      + termcap.Normal
58310238Sandreas.hansson@arm.com        self.max_sources = max_sources
5849420Sandreas.hansson@arm.com
5859420Sandreas.hansson@arm.com    def __call__(self, target, source, env, for_signature=None):
5869420Sandreas.hansson@arm.com        # truncate source list according to max_sources param
5879420Sandreas.hansson@arm.com        source = source[0:self.max_sources]
5889420Sandreas.hansson@arm.com        def strip(f):
58910264Sandreas.hansson@arm.com            return strip_build_path(str(f), env)
59010264Sandreas.hansson@arm.com        if len(source) > 0:
59110264Sandreas.hansson@arm.com            srcs = map(strip, source)
59210264Sandreas.hansson@arm.com        else:
59310264Sandreas.hansson@arm.com            srcs = ['']
59410264Sandreas.hansson@arm.com        tgts = map(strip, target)
59510264Sandreas.hansson@arm.com        # surprisingly, os.path.commonprefix is a dumb char-by-char string
59610264Sandreas.hansson@arm.com        # operation that has nothing to do with paths.
59710264Sandreas.hansson@arm.com        com_pfx = os.path.commonprefix(srcs + tgts)
59810264Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
59910264Sandreas.hansson@arm.com        if com_pfx:
60010264Sandreas.hansson@arm.com            # do some cleanup and sanity checking on common prefix
60110264Sandreas.hansson@arm.com            if com_pfx[-1] == ".":
60210264Sandreas.hansson@arm.com                # prefix matches all but file extension: ok
60310264Sandreas.hansson@arm.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
60410264Sandreas.hansson@arm.com                com_pfx = com_pfx[0:-1]
60510238Sandreas.hansson@arm.com            elif com_pfx[-1] == "/":
60610238Sandreas.hansson@arm.com                # common prefix is directory path: OK
60710238Sandreas.hansson@arm.com                pass
60810238Sandreas.hansson@arm.com            else:
60910238Sandreas.hansson@arm.com                src0_len = len(srcs[0])
61010238Sandreas.hansson@arm.com                tgt0_len = len(tgts[0])
61110416Sandreas.hansson@arm.com                if src0_len == com_pfx_len:
61210238Sandreas.hansson@arm.com                    # source is a substring of target, OK
6139227Sandreas.hansson@arm.com                    pass
61410238Sandreas.hansson@arm.com                elif tgt0_len == com_pfx_len:
61510416Sandreas.hansson@arm.com                    # target is a substring of source, need to back up to
61610416Sandreas.hansson@arm.com                    # avoid empty string on RHS of arrow
6179227Sandreas.hansson@arm.com                    sep_idx = com_pfx.rfind(".")
6189590Sandreas@sandberg.pp.se                    if sep_idx != -1:
6199590Sandreas@sandberg.pp.se                        com_pfx = com_pfx[0:sep_idx]
6209590Sandreas@sandberg.pp.se                    else:
6218737Skoansin.tan@gmail.com                        com_pfx = ''
62210238Sandreas.hansson@arm.com                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
62310238Sandreas.hansson@arm.com                    # still splitting at file extension: ok
6249420Sandreas.hansson@arm.com                    pass
6258737Skoansin.tan@gmail.com                else:
62610106SMitch.Hayenga@arm.com                    # probably a fluke; ignore it
6278737Skoansin.tan@gmail.com                    com_pfx = ''
6288737Skoansin.tan@gmail.com        # recalculate length in case com_pfx was modified
62910238Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
63010238Sandreas.hansson@arm.com        def fmt(files):
6318737Skoansin.tan@gmail.com            f = map(lambda s: s[com_pfx_len:], files)
6328737Skoansin.tan@gmail.com            return ', '.join(f)
6338737Skoansin.tan@gmail.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
6348737Skoansin.tan@gmail.com
6358737Skoansin.tan@gmail.comExport('Transform')
6368737Skoansin.tan@gmail.com
6379556Sandreas.hansson@arm.com# enable the regression script to use the termcap
6389556Sandreas.hansson@arm.commain['TERMCAP'] = termcap
6399556Sandreas.hansson@arm.com
6409556Sandreas.hansson@arm.comif GetOption('verbose'):
6419556Sandreas.hansson@arm.com    def MakeAction(action, string, *args, **kwargs):
6429556Sandreas.hansson@arm.com        return Action(action, *args, **kwargs)
6439556Sandreas.hansson@arm.comelse:
6449556Sandreas.hansson@arm.com    MakeAction = Action
64510278SAndreas.Sandberg@ARM.com    main['CCCOMSTR']        = Transform("CC")
64610278SAndreas.Sandberg@ARM.com    main['CXXCOMSTR']       = Transform("CXX")
64710278SAndreas.Sandberg@ARM.com    main['ASCOMSTR']        = Transform("AS")
64810278SAndreas.Sandberg@ARM.com    main['SWIGCOMSTR']      = Transform("SWIG")
64910278SAndreas.Sandberg@ARM.com    main['ARCOMSTR']        = Transform("AR", 0)
65010278SAndreas.Sandberg@ARM.com    main['LINKCOMSTR']      = Transform("LINK", 0)
6519556Sandreas.hansson@arm.com    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
6529590Sandreas@sandberg.pp.se    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
6539590Sandreas@sandberg.pp.se    main['M4COMSTR']        = Transform("M4")
6549420Sandreas.hansson@arm.com    main['SHCCCOMSTR']      = Transform("SHCC")
6559846Sandreas.hansson@arm.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
6569846Sandreas.hansson@arm.comExport('MakeAction')
6579846Sandreas.hansson@arm.com
6589846Sandreas.hansson@arm.com# Initialize the Link-Time Optimization (LTO) flags
6598946Sandreas.hansson@arm.commain['LTO_CCFLAGS'] = []
6603918Ssaidi@eecs.umich.edumain['LTO_LDFLAGS'] = []
6619068SAli.Saidi@ARM.com
6629068SAli.Saidi@ARM.com# According to the readme, tcmalloc works best if the compiler doesn't
6639068SAli.Saidi@ARM.com# assume that we're using the builtin malloc and friends. These flags
6649068SAli.Saidi@ARM.com# are compiler-specific, so we need to set them after we detect which
6659068SAli.Saidi@ARM.com# compiler we're using.
6669068SAli.Saidi@ARM.commain['TCMALLOC_CCFLAGS'] = []
6679068SAli.Saidi@ARM.com
6689068SAli.Saidi@ARM.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
6699068SAli.Saidi@ARM.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
6709419Sandreas.hansson@arm.com
6719068SAli.Saidi@ARM.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
6729068SAli.Saidi@ARM.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
6739068SAli.Saidi@ARM.comif main['GCC'] + main['CLANG'] > 1:
6749068SAli.Saidi@ARM.com    print 'Error: How can we have two at the same time?'
6759068SAli.Saidi@ARM.com    Exit(1)
6769068SAli.Saidi@ARM.com
6773918Ssaidi@eecs.umich.edu# Set up default C++ compiler flags
6783918Ssaidi@eecs.umich.eduif main['GCC'] or main['CLANG']:
6796157Snate@binkert.org    # As gcc and clang share many flags, do the common parts here
6806157Snate@binkert.org    main.Append(CCFLAGS=['-pipe'])
6816157Snate@binkert.org    main.Append(CCFLAGS=['-fno-strict-aliasing'])
6826157Snate@binkert.org    # Enable -Wall and -Wextra and then disable the few warnings that
6835397Ssaidi@eecs.umich.edu    # we consistently violate
6845397Ssaidi@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
6856121Snate@binkert.org                         '-Wno-sign-compare', '-Wno-unused-parameter'])
6866121Snate@binkert.org    # We always compile using C++11
6876121Snate@binkert.org    main.Append(CXXFLAGS=['-std=c++11'])
6886121Snate@binkert.org    if sys.platform.startswith('freebsd'):
6896121Snate@binkert.org        main.Append(CCFLAGS=['-I/usr/local/include'])
6906121Snate@binkert.org        main.Append(CXXFLAGS=['-I/usr/local/include'])
6915397Ssaidi@eecs.umich.edu
6921851SN/A    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
6931851SN/A    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
6947739Sgblack@eecs.umich.edu    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
695955SN/A    shared_partial_flags = ['-Wl,--relocatable', '-nostdlib']
6969396Sandreas.hansson@arm.com    main.Append(PSHLINKFLAGS=shared_partial_flags)
6979396Sandreas.hansson@arm.com    main.Append(PLINKFLAGS=shared_partial_flags)
6989396Sandreas.hansson@arm.comelse:
6999396Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
7009396Sandreas.hansson@arm.com    print "Don't know what compiler options to use for your compiler."
7019396Sandreas.hansson@arm.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
7029396Sandreas.hansson@arm.com    print termcap.Yellow + '       version:' + termcap.Normal,
7039396Sandreas.hansson@arm.com    if not CXX_version:
7049396Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
7059396Sandreas.hansson@arm.com               termcap.Normal
7069396Sandreas.hansson@arm.com    else:
7079396Sandreas.hansson@arm.com        print CXX_version.replace('\n', '<nl>')
7089396Sandreas.hansson@arm.com    print "       If you're trying to use a compiler other than GCC"
7099396Sandreas.hansson@arm.com    print "       or clang, there appears to be something wrong with your"
7109396Sandreas.hansson@arm.com    print "       environment."
7119396Sandreas.hansson@arm.com    print "       "
7129477Sandreas.hansson@arm.com    print "       If you are trying to use a compiler other than those listed"
7139477Sandreas.hansson@arm.com    print "       above you will need to ease fix SConstruct and "
7149477Sandreas.hansson@arm.com    print "       src/SConscript to support that compiler."
7159477Sandreas.hansson@arm.com    Exit(1)
7169477Sandreas.hansson@arm.com
7179477Sandreas.hansson@arm.comif main['GCC']:
7189477Sandreas.hansson@arm.com    # Check for a supported version of gcc. >= 4.8 is chosen for its
7199477Sandreas.hansson@arm.com    # level of c++11 support. See
7209477Sandreas.hansson@arm.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
7219477Sandreas.hansson@arm.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
7229477Sandreas.hansson@arm.com    if compareVersions(gcc_version, "4.8") < 0:
7239477Sandreas.hansson@arm.com        print 'Error: gcc version 4.8 or newer required.'
7249477Sandreas.hansson@arm.com        print '       Installed version:', gcc_version
7259477Sandreas.hansson@arm.com        Exit(1)
7269477Sandreas.hansson@arm.com
7279477Sandreas.hansson@arm.com    main['GCC_VERSION'] = gcc_version
7289477Sandreas.hansson@arm.com
7299477Sandreas.hansson@arm.com    # gcc from version 4.8 and above generates "rep; ret" instructions
7309477Sandreas.hansson@arm.com    # to avoid performance penalties on certain AMD chips. Older
7319477Sandreas.hansson@arm.com    # assemblers detect this as an error, "Error: expecting string
7329477Sandreas.hansson@arm.com    # instruction after `rep'"
7339477Sandreas.hansson@arm.com    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
7349396Sandreas.hansson@arm.com                                  '-o', '/dev/null'],
7353053Sstever@eecs.umich.edu                                 exception=False).split()
7366121Snate@binkert.org
7373053Sstever@eecs.umich.edu    # version strings may contain extra distro-specific
7383053Sstever@eecs.umich.edu    # qualifiers, so play it safe and keep only what comes before
7393053Sstever@eecs.umich.edu    # the first hyphen
7403053Sstever@eecs.umich.edu    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
7413053Sstever@eecs.umich.edu
7429072Sandreas.hansson@arm.com    if not as_version or compareVersions(as_version, "2.23") < 0:
7433053Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
7444742Sstever@eecs.umich.edu            'Warning: This combination of gcc and binutils have' + \
7454742Sstever@eecs.umich.edu            ' known incompatibilities.\n' + \
7463053Sstever@eecs.umich.edu            '         If you encounter build problems, please update ' + \
7473053Sstever@eecs.umich.edu            'binutils to 2.23.' + \
7483053Sstever@eecs.umich.edu            termcap.Normal
74910181SCurtis.Dunham@arm.com
7506654Snate@binkert.org    # Make sure we warn if the user has requested to compile with the
7513053Sstever@eecs.umich.edu    # Undefined Benahvior Sanitizer and this version of gcc does not
7523053Sstever@eecs.umich.edu    # support it.
7533053Sstever@eecs.umich.edu    if GetOption('with_ubsan') and \
7543053Sstever@eecs.umich.edu            compareVersions(gcc_version, '4.9') < 0:
75510425Sandreas.hansson@arm.com        print termcap.Yellow + termcap.Bold + \
75610425Sandreas.hansson@arm.com            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
75710425Sandreas.hansson@arm.com            termcap.Normal
75810425Sandreas.hansson@arm.com
75910425Sandreas.hansson@arm.com    # Add the appropriate Link-Time Optimization (LTO) flags
76010425Sandreas.hansson@arm.com    # unless LTO is explicitly turned off. Note that these flags
76110425Sandreas.hansson@arm.com    # are only used by the fast target.
76210425Sandreas.hansson@arm.com    if not GetOption('no_lto'):
76310425Sandreas.hansson@arm.com        # Pass the LTO flag when compiling to produce GIMPLE
76410425Sandreas.hansson@arm.com        # output, we merely create the flags here and only append
76510425Sandreas.hansson@arm.com        # them later
7662667Sstever@eecs.umich.edu        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
7674554Sbinkertn@umich.edu
7686121Snate@binkert.org        # Use the same amount of jobs for LTO as we are running
7692667Sstever@eecs.umich.edu        # scons with
77010384SCurtis.Dunham@arm.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
77110384SCurtis.Dunham@arm.com
77210384SCurtis.Dunham@arm.com    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
77310384SCurtis.Dunham@arm.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
77410384SCurtis.Dunham@arm.com
7754554Sbinkertn@umich.edu    # add option to check for undeclared overrides
7764554Sbinkertn@umich.edu    if compareVersions(gcc_version, "5.0") > 0:
7774554Sbinkertn@umich.edu        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
7786121Snate@binkert.org
7794554Sbinkertn@umich.eduelif main['CLANG']:
7804554Sbinkertn@umich.edu    # Check for a supported version of clang, >= 3.1 is needed to
7814554Sbinkertn@umich.edu    # support similar features as gcc 4.8. See
7824781Snate@binkert.org    # http://clang.llvm.org/cxx_status.html for details
7834554Sbinkertn@umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
7844554Sbinkertn@umich.edu    clang_version_match = clang_version_re.search(CXX_version)
7852667Sstever@eecs.umich.edu    if (clang_version_match):
7864554Sbinkertn@umich.edu        clang_version = clang_version_match.groups()[0]
7874554Sbinkertn@umich.edu        if compareVersions(clang_version, "3.1") < 0:
7884554Sbinkertn@umich.edu            print 'Error: clang version 3.1 or newer required.'
7894554Sbinkertn@umich.edu            print '       Installed version:', clang_version
7902667Sstever@eecs.umich.edu            Exit(1)
7914554Sbinkertn@umich.edu    else:
7922667Sstever@eecs.umich.edu        print 'Error: Unable to determine clang version.'
7934554Sbinkertn@umich.edu        Exit(1)
7946121Snate@binkert.org
7952667Sstever@eecs.umich.edu    # clang has a few additional warnings that we disable, extraneous
7965522Snate@binkert.org    # parantheses are allowed due to Ruby's printing of the AST,
7975522Snate@binkert.org    # finally self assignments are allowed as the generated CPU code
7985522Snate@binkert.org    # is relying on this
7995522Snate@binkert.org    main.Append(CCFLAGS=['-Wno-parentheses',
8005522Snate@binkert.org                         '-Wno-self-assign',
8015522Snate@binkert.org                         # Some versions of libstdc++ (4.8?) seem to
8025522Snate@binkert.org                         # use struct hash and class hash
8035522Snate@binkert.org                         # interchangeably.
8045522Snate@binkert.org                         '-Wno-mismatched-tags',
8055522Snate@binkert.org                         ])
8065522Snate@binkert.org
8075522Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
8085522Snate@binkert.org
8095522Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
8105522Snate@binkert.org    # opposed to libstdc++, as the later is dated.
8115522Snate@binkert.org    if sys.platform == "darwin":
8125522Snate@binkert.org        main.Append(CXXFLAGS=['-stdlib=libc++'])
8135522Snate@binkert.org        main.Append(LIBS=['c++'])
8145522Snate@binkert.org
8155522Snate@binkert.org    # On FreeBSD we need libthr.
8165522Snate@binkert.org    if sys.platform.startswith('freebsd'):
8175522Snate@binkert.org        main.Append(LIBS=['thr'])
8185522Snate@binkert.org
8195522Snate@binkert.orgelse:
8205522Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
8215522Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
8229986Sandreas@sandberg.pp.se    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
8239986Sandreas@sandberg.pp.se    print termcap.Yellow + '       version:' + termcap.Normal,
8249986Sandreas@sandberg.pp.se    if not CXX_version:
8259986Sandreas@sandberg.pp.se        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
8269986Sandreas@sandberg.pp.se               termcap.Normal
8279986Sandreas@sandberg.pp.se    else:
8289986Sandreas@sandberg.pp.se        print CXX_version.replace('\n', '<nl>')
8299986Sandreas@sandberg.pp.se    print "       If you're trying to use a compiler other than GCC"
8309986Sandreas@sandberg.pp.se    print "       or clang, there appears to be something wrong with your"
8319986Sandreas@sandberg.pp.se    print "       environment."
8329986Sandreas@sandberg.pp.se    print "       "
8339986Sandreas@sandberg.pp.se    print "       If you are trying to use a compiler other than those listed"
8349986Sandreas@sandberg.pp.se    print "       above you will need to ease fix SConstruct and "
8359986Sandreas@sandberg.pp.se    print "       src/SConscript to support that compiler."
8369986Sandreas@sandberg.pp.se    Exit(1)
8379986Sandreas@sandberg.pp.se
8389986Sandreas@sandberg.pp.se# Set up common yacc/bison flags (needed for Ruby)
8399986Sandreas@sandberg.pp.semain['YACCFLAGS'] = '-d'
8409986Sandreas@sandberg.pp.semain['YACCHXXFILESUFFIX'] = '.hh'
8419986Sandreas@sandberg.pp.se
8422638Sstever@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
8432638Sstever@eecs.umich.edu# extra 'qdo' every time we run scons.
8446121Snate@binkert.orgif main['BATCH']:
8453716Sstever@eecs.umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
8465522Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
8479986Sandreas@sandberg.pp.se    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
8489986Sandreas@sandberg.pp.se    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
8499986Sandreas@sandberg.pp.se    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
8509986Sandreas@sandberg.pp.se
8515522Snate@binkert.orgif sys.platform == 'cygwin':
8525522Snate@binkert.org    # cygwin has some header file issues...
8535522Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
8545522Snate@binkert.org
8551858SN/A# Check for the protobuf compiler
8565227Ssaidi@eecs.umich.eduprotoc_version = readCommand([main['PROTOC'], '--version'],
8575227Ssaidi@eecs.umich.edu                             exception='').split()
8585227Ssaidi@eecs.umich.edu
8595227Ssaidi@eecs.umich.edu# First two words should be "libprotoc x.y.z"
8606654Snate@binkert.orgif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
8616654Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
8627769SAli.Saidi@ARM.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
8637769SAli.Saidi@ARM.com        '         Please install protobuf-compiler for tracing support.' + \
8647769SAli.Saidi@ARM.com        termcap.Normal
8657769SAli.Saidi@ARM.com    main['PROTOC'] = False
8665227Ssaidi@eecs.umich.eduelse:
8675227Ssaidi@eecs.umich.edu    # Based on the availability of the compress stream wrappers,
8685227Ssaidi@eecs.umich.edu    # require 2.1.0
8695204Sstever@gmail.com    min_protoc_version = '2.1.0'
8705204Sstever@gmail.com    if compareVersions(protoc_version[1], min_protoc_version) < 0:
8715204Sstever@gmail.com        print termcap.Yellow + termcap.Bold + \
8725204Sstever@gmail.com            'Warning: protoc version', min_protoc_version, \
8735204Sstever@gmail.com            'or newer required.\n' + \
8745204Sstever@gmail.com            '         Installed version:', protoc_version[1], \
8755204Sstever@gmail.com            termcap.Normal
8765204Sstever@gmail.com        main['PROTOC'] = False
8775204Sstever@gmail.com    else:
8785204Sstever@gmail.com        # Attempt to determine the appropriate include path and
8795204Sstever@gmail.com        # library path using pkg-config, that means we also need to
8805204Sstever@gmail.com        # check for pkg-config. Note that it is possible to use
8815204Sstever@gmail.com        # protobuf without the involvement of pkg-config. Later on we
8825204Sstever@gmail.com        # check go a library config check and at that point the test
8835204Sstever@gmail.com        # will fail if libprotobuf cannot be found.
8845204Sstever@gmail.com        if readCommand(['pkg-config', '--version'], exception=''):
8855204Sstever@gmail.com            try:
8866121Snate@binkert.org                # Attempt to establish what linking flags to add for protobuf
8875204Sstever@gmail.com                # using pkg-config
8887727SAli.Saidi@ARM.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
8897727SAli.Saidi@ARM.com            except:
8907727SAli.Saidi@ARM.com                print termcap.Yellow + termcap.Bold + \
8917727SAli.Saidi@ARM.com                    'Warning: pkg-config could not get protobuf flags.' + \
8927727SAli.Saidi@ARM.com                    termcap.Normal
89310453SAndrew.Bardsley@arm.com
89410453SAndrew.Bardsley@arm.com# Check for SWIG
89510453SAndrew.Bardsley@arm.comif not main.has_key('SWIG'):
89610453SAndrew.Bardsley@arm.com    print 'Error: SWIG utility not found.'
89710453SAndrew.Bardsley@arm.com    print '       Please install (see http://www.swig.org) and retry.'
89810453SAndrew.Bardsley@arm.com    Exit(1)
89910453SAndrew.Bardsley@arm.com
90010453SAndrew.Bardsley@arm.com# Check for appropriate SWIG version
90110453SAndrew.Bardsley@arm.comswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
90210453SAndrew.Bardsley@arm.com# First 3 words should be "SWIG Version x.y.z"
90310453SAndrew.Bardsley@arm.comif len(swig_version) < 3 or \
90410160Sandreas.hansson@arm.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
90510453SAndrew.Bardsley@arm.com    print 'Error determining SWIG version.'
90610453SAndrew.Bardsley@arm.com    Exit(1)
90710453SAndrew.Bardsley@arm.com
90810453SAndrew.Bardsley@arm.commin_swig_version = '2.0.4'
90910453SAndrew.Bardsley@arm.comif compareVersions(swig_version[2], min_swig_version) < 0:
91010453SAndrew.Bardsley@arm.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
91110453SAndrew.Bardsley@arm.com    print '       Installed version:', swig_version[2]
91210453SAndrew.Bardsley@arm.com    Exit(1)
9139812Sandreas.hansson@arm.com
91410453SAndrew.Bardsley@arm.com# Check for known incompatibilities. The standard library shipped with
91510453SAndrew.Bardsley@arm.com# gcc >= 4.9 does not play well with swig versions prior to 3.0
91610453SAndrew.Bardsley@arm.comif main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
91710453SAndrew.Bardsley@arm.com        compareVersions(swig_version[2], '3.0') < 0:
91810453SAndrew.Bardsley@arm.com    print termcap.Yellow + termcap.Bold + \
91910453SAndrew.Bardsley@arm.com        'Warning: This combination of gcc and swig have' + \
92010453SAndrew.Bardsley@arm.com        ' known incompatibilities.\n' + \
92110453SAndrew.Bardsley@arm.com        '         If you encounter build problems, please update ' + \
92210453SAndrew.Bardsley@arm.com        'swig to 3.0 or later.' + \
92310453SAndrew.Bardsley@arm.com        termcap.Normal
92410453SAndrew.Bardsley@arm.com
92510453SAndrew.Bardsley@arm.com# Set up SWIG flags & scanner
9267727SAli.Saidi@ARM.comswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
92710453SAndrew.Bardsley@arm.commain.Append(SWIGFLAGS=swig_flags)
92810453SAndrew.Bardsley@arm.com
92910453SAndrew.Bardsley@arm.com# Check for 'timeout' from GNU coreutils. If present, regressions will
93010453SAndrew.Bardsley@arm.com# be run with a time limit. We require version 8.13 since we rely on
93110453SAndrew.Bardsley@arm.com# support for the '--foreground' option.
9323118Sstever@eecs.umich.eduif sys.platform.startswith('freebsd'):
93310453SAndrew.Bardsley@arm.com    timeout_lines = readCommand(['gtimeout', '--version'],
93410453SAndrew.Bardsley@arm.com                                exception='').splitlines()
93510453SAndrew.Bardsley@arm.comelse:
93610453SAndrew.Bardsley@arm.com    timeout_lines = readCommand(['timeout', '--version'],
9373118Sstever@eecs.umich.edu                                exception='').splitlines()
9383483Ssaidi@eecs.umich.edu# Get the first line and tokenize it
9393494Ssaidi@eecs.umich.edutimeout_version = timeout_lines[0].split() if timeout_lines else []
9403494Ssaidi@eecs.umich.edumain['TIMEOUT'] =  timeout_version and \
9413483Ssaidi@eecs.umich.edu    compareVersions(timeout_version[-1], '8.13') >= 0
9423483Ssaidi@eecs.umich.edu
9433483Ssaidi@eecs.umich.edu# filter out all existing swig scanners, they mess up the dependency
9443053Sstever@eecs.umich.edu# stuff for some reason
9453053Sstever@eecs.umich.eduscanners = []
9463918Ssaidi@eecs.umich.edufor scanner in main['SCANNERS']:
9473053Sstever@eecs.umich.edu    skeys = scanner.skeys
9483053Sstever@eecs.umich.edu    if skeys == '.i':
9493053Sstever@eecs.umich.edu        continue
9503053Sstever@eecs.umich.edu
9513053Sstever@eecs.umich.edu    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
9529396Sandreas.hansson@arm.com        continue
9539396Sandreas.hansson@arm.com
9549396Sandreas.hansson@arm.com    scanners.append(scanner)
9559396Sandreas.hansson@arm.com
9569396Sandreas.hansson@arm.com# add the new swig scanner that we like better
9579396Sandreas.hansson@arm.comfrom SCons.Scanner import ClassicCPP as CPPScanner
9589396Sandreas.hansson@arm.comswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
9599396Sandreas.hansson@arm.comscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
9609396Sandreas.hansson@arm.com
9619477Sandreas.hansson@arm.com# replace the scanners list that has what we want
9629396Sandreas.hansson@arm.commain['SCANNERS'] = scanners
9639477Sandreas.hansson@arm.com
9649477Sandreas.hansson@arm.com# Add a custom Check function to test for structure members.
9659477Sandreas.hansson@arm.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
9669477Sandreas.hansson@arm.com    context.Message("Checking for member %s in %s..." %
9679396Sandreas.hansson@arm.com                    (member, decl))
9687840Snate@binkert.org    text = """
9697865Sgblack@eecs.umich.edu#include %(header)s
9707865Sgblack@eecs.umich.eduint main(){
9717865Sgblack@eecs.umich.edu  %(decl)s test;
9727865Sgblack@eecs.umich.edu  (void)test.%(member)s;
9737865Sgblack@eecs.umich.edu  return 0;
9747840Snate@binkert.org};
9759900Sandreas@sandberg.pp.se""" % { "header" : include_quotes[0] + include + include_quotes[1],
9769900Sandreas@sandberg.pp.se        "decl" : decl,
9779900Sandreas@sandberg.pp.se        "member" : member,
9789900Sandreas@sandberg.pp.se        }
97910456SCurtis.Dunham@arm.com
98010456SCurtis.Dunham@arm.com    ret = context.TryCompile(text, extension=".cc")
98110456SCurtis.Dunham@arm.com    context.Result(ret)
98210456SCurtis.Dunham@arm.com    return ret
98310456SCurtis.Dunham@arm.com
98410456SCurtis.Dunham@arm.com# Platform-specific configuration.  Note again that we assume that all
98510456SCurtis.Dunham@arm.com# builds under a given build root run on the same host platform.
98610456SCurtis.Dunham@arm.comconf = Configure(main,
98710456SCurtis.Dunham@arm.com                 conf_dir = joinpath(build_root, '.scons_config'),
98810456SCurtis.Dunham@arm.com                 log_file = joinpath(build_root, 'scons_config.log'),
9899045SAli.Saidi@ARM.com                 custom_tests = {
9907840Snate@binkert.org        'CheckMember' : CheckMember,
9917840Snate@binkert.org        })
9927840Snate@binkert.org
9931858SN/A# Check if we should compile a 64 bit binary on Mac OS X/Darwin
9941858SN/Atry:
9951858SN/A    import platform
9961858SN/A    uname = platform.uname()
9971858SN/A    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
9981858SN/A        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
9999903Sandreas.hansson@arm.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
10009903Sandreas.hansson@arm.com            main.Append(CFLAGS=['-arch', 'x86_64'])
10019903Sandreas.hansson@arm.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
10029903Sandreas.hansson@arm.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
10039903Sandreas.hansson@arm.comexcept:
10049903Sandreas.hansson@arm.com    pass
10059651SAndreas.Sandberg@ARM.com
10069903Sandreas.hansson@arm.com# Recent versions of scons substitute a "Null" object for Configure()
10079651SAndreas.Sandberg@ARM.com# when configuration isn't necessary, e.g., if the "--help" option is
10089651SAndreas.Sandberg@ARM.com# present.  Unfortuantely this Null object always returns false,
10099651SAndreas.Sandberg@ARM.com# breaking all our configuration checks.  We replace it with our own
10109651SAndreas.Sandberg@ARM.com# more optimistic null object that returns True instead.
10119651SAndreas.Sandberg@ARM.comif not conf:
10129657Sandreas.sandberg@arm.com    def NullCheck(*args, **kwargs):
10139883Sandreas@sandberg.pp.se        return True
10149651SAndreas.Sandberg@ARM.com
10159651SAndreas.Sandberg@ARM.com    class NullConf:
10169651SAndreas.Sandberg@ARM.com        def __init__(self, env):
10179651SAndreas.Sandberg@ARM.com            self.env = env
10189651SAndreas.Sandberg@ARM.com        def Finish(self):
10199651SAndreas.Sandberg@ARM.com            return self.env
10209651SAndreas.Sandberg@ARM.com        def __getattr__(self, mname):
10219651SAndreas.Sandberg@ARM.com            return NullCheck
10229651SAndreas.Sandberg@ARM.com
10239651SAndreas.Sandberg@ARM.com    conf = NullConf(main)
10249651SAndreas.Sandberg@ARM.com
10259986Sandreas@sandberg.pp.se# Cache build files in the supplied directory.
10269986Sandreas@sandberg.pp.seif main['M5_BUILD_CACHE']:
10279986Sandreas@sandberg.pp.se    print 'Using build cache located at', main['M5_BUILD_CACHE']
10289986Sandreas@sandberg.pp.se    CacheDir(main['M5_BUILD_CACHE'])
10299986Sandreas@sandberg.pp.se
10309986Sandreas@sandberg.pp.seif not GetOption('without_python'):
10315863Snate@binkert.org    # Find Python include and library directories for embedding the
10325863Snate@binkert.org    # interpreter. We rely on python-config to resolve the appropriate
10335863Snate@binkert.org    # includes and linker flags. ParseConfig does not seem to understand
10345863Snate@binkert.org    # the more exotic linker flags such as -Xlinker and -export-dynamic so
10356121Snate@binkert.org    # we add them explicitly below. If you want to link in an alternate
10361858SN/A    # version of python, see above for instructions on how to invoke
10375863Snate@binkert.org    # scons with the appropriate PATH set.
10385863Snate@binkert.org    #
10395863Snate@binkert.org    # First we check if python2-config exists, else we use python-config
10405863Snate@binkert.org    python_config = readCommand(['which', 'python2-config'],
10415863Snate@binkert.org                                exception='').strip()
10422139SN/A    if not os.path.exists(python_config):
10434202Sbinkertn@umich.edu        python_config = readCommand(['which', 'python-config'],
10444202Sbinkertn@umich.edu                                    exception='').strip()
10452139SN/A    py_includes = readCommand([python_config, '--includes'],
10466994Snate@binkert.org                              exception='').split()
10476994Snate@binkert.org    # Strip the -I from the include folders before adding them to the
10486994Snate@binkert.org    # CPPPATH
10496994Snate@binkert.org    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
10506994Snate@binkert.org
10516994Snate@binkert.org    # Read the linker flags and split them into libraries and other link
10526994Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
10536994Snate@binkert.org    py_ld_flags = readCommand([python_config, '--ldflags'],
105410319SAndreas.Sandberg@ARM.com        exception='').split()
10556994Snate@binkert.org    py_libs = []
10566994Snate@binkert.org    for lib in py_ld_flags:
10576994Snate@binkert.org         if not lib.startswith('-l'):
10586994Snate@binkert.org             main.Append(LINKFLAGS=[lib])
10596994Snate@binkert.org         else:
10606994Snate@binkert.org             lib = lib[2:]
10616994Snate@binkert.org             if lib not in py_libs:
10626994Snate@binkert.org                 py_libs.append(lib)
10636994Snate@binkert.org
10646994Snate@binkert.org    # verify that this stuff works
10656994Snate@binkert.org    if not conf.CheckHeader('Python.h', '<>'):
10662155SN/A        print "Error: can't find Python.h header in", py_includes
10675863Snate@binkert.org        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
10681869SN/A        Exit(1)
10691869SN/A
10705863Snate@binkert.org    for lib in py_libs:
10715863Snate@binkert.org        if not conf.CheckLib(lib):
10724202Sbinkertn@umich.edu            print "Error: can't find library %s required by python" % lib
10736108Snate@binkert.org            Exit(1)
10746108Snate@binkert.org
10756108Snate@binkert.org# On Solaris you need to use libsocket for socket ops
10766108Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10779219Spower.jg@gmail.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10789219Spower.jg@gmail.com       print "Can't find library with socket calls (e.g. accept())"
10799219Spower.jg@gmail.com       Exit(1)
10809219Spower.jg@gmail.com
10819219Spower.jg@gmail.com# Check for zlib.  If the check passes, libz will be automatically
10829219Spower.jg@gmail.com# added to the LIBS environment variable.
10839219Spower.jg@gmail.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
10849219Spower.jg@gmail.com    print 'Error: did not find needed zlib compression library '\
10854202Sbinkertn@umich.edu          'and/or zlib.h header file.'
10865863Snate@binkert.org    print '       Please install zlib and try again.'
108710135SCurtis.Dunham@arm.com    Exit(1)
10888474Sgblack@eecs.umich.edu
10895742Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
10908268Ssteve.reinhardt@amd.com# development libraries. If the check passes, libprotobuf will be
10918268Ssteve.reinhardt@amd.com# automatically added to the LIBS environment variable. After
10928268Ssteve.reinhardt@amd.com# this, we can use the HAVE_PROTOBUF flag to determine if we have
10935742Snate@binkert.org# got both protoc and libprotobuf available.
10945341Sstever@gmail.commain['HAVE_PROTOBUF'] = main['PROTOC'] and \
10958474Sgblack@eecs.umich.edu    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
10968474Sgblack@eecs.umich.edu                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
10975342Sstever@gmail.com
10984202Sbinkertn@umich.edu# If we have the compiler but not the library, print another warning.
10994202Sbinkertn@umich.eduif main['PROTOC'] and not main['HAVE_PROTOBUF']:
11004202Sbinkertn@umich.edu    print termcap.Yellow + termcap.Bold + \
11015863Snate@binkert.org        'Warning: did not find protocol buffer library and/or headers.\n' + \
11025863Snate@binkert.org    '       Please install libprotobuf-dev for tracing support.' + \
11036994Snate@binkert.org    termcap.Normal
11046994Snate@binkert.org
110510319SAndreas.Sandberg@ARM.com# Check for librt.
11065863Snate@binkert.orghave_posix_clock = \
11075863Snate@binkert.org    conf.CheckLibWithHeader(None, 'time.h', 'C',
11085863Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
11095863Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
11105863Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
11115863Snate@binkert.org
11125863Snate@binkert.orghave_posix_timers = \
11135863Snate@binkert.org    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
11147840Snate@binkert.org                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
11155863Snate@binkert.org
11165952Ssaidi@eecs.umich.eduif not GetOption('without_tcmalloc'):
11179651SAndreas.Sandberg@ARM.com    if conf.CheckLib('tcmalloc'):
11189219Spower.jg@gmail.com        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
11199219Spower.jg@gmail.com    elif conf.CheckLib('tcmalloc_minimal'):
11201869SN/A        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
11211858SN/A    else:
11225863Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
11239420Sandreas.hansson@arm.com              "You can get a 12% performance improvement by "\
11249986Sandreas@sandberg.pp.se              "installing tcmalloc (libgoogle-perftools-dev package "\
11259986Sandreas@sandberg.pp.se              "on Ubuntu or RedHat)." + termcap.Normal
11261858SN/A
1127955SN/A
1128955SN/A# Detect back trace implementations. The last implementation in the
11291869SN/A# list will be used by default.
11301869SN/Abacktrace_impls = [ "none" ]
11311869SN/A
11321869SN/Aif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
11331869SN/A                           'backtrace_symbols_fd((void*)0, 0, 0);'):
11345863Snate@binkert.org    backtrace_impls.append("glibc")
11355863Snate@binkert.orgelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
11365863Snate@binkert.org                           'backtrace_symbols_fd((void*)0, 0, 0);'):
11371869SN/A    # NetBSD and FreeBSD need libexecinfo.
11385863Snate@binkert.org    backtrace_impls.append("glibc")
11391869SN/A    main.Append(LIBS=['execinfo'])
11405863Snate@binkert.org
11411869SN/Aif backtrace_impls[-1] == "none":
11421869SN/A    default_backtrace_impl = "none"
11431869SN/A    print termcap.Yellow + termcap.Bold + \
11441869SN/A        "No suitable back trace implementation found." + \
11458483Sgblack@eecs.umich.edu        termcap.Normal
11461869SN/A
11471869SN/Aif not have_posix_clock:
11481869SN/A    print "Can't find library for POSIX clocks."
11491869SN/A
11505863Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
11515863Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
11521869SN/Aif not have_fenv:
11535863Snate@binkert.org    print "Warning: Header file <fenv.h> not found."
11545863Snate@binkert.org    print "         This host has no IEEE FP rounding mode control."
11553356Sbinkertn@umich.edu
11563356Sbinkertn@umich.edu# Check if we should enable KVM-based hardware virtualization. The API
11573356Sbinkertn@umich.edu# we rely on exists since version 2.6.36 of the kernel, but somehow
11583356Sbinkertn@umich.edu# the KVM_API_VERSION does not reflect the change. We test for one of
11593356Sbinkertn@umich.edu# the types as a fall back.
11604781Snate@binkert.orghave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
11615863Snate@binkert.orgif not have_kvm:
11625863Snate@binkert.org    print "Info: Compatible header file <linux/kvm.h> not found, " \
11631869SN/A        "disabling KVM support."
11641869SN/A
11651869SN/A# x86 needs support for xsave. We test for the structure here since we
11666121Snate@binkert.org# won't be able to run new tests by the time we know which ISA we're
11671869SN/A# targeting.
11682638Sstever@eecs.umich.eduhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
11696121Snate@binkert.org                                    '#include <linux/kvm.h>') != 0
11706121Snate@binkert.org
11712638Sstever@eecs.umich.edu# Check if the requested target ISA is compatible with the host
11725749Scws3k@cs.virginia.edudef is_isa_kvm_compatible(isa):
11736121Snate@binkert.org    try:
11746121Snate@binkert.org        import platform
11755749Scws3k@cs.virginia.edu        host_isa = platform.machine()
11769537Satgutier@umich.edu    except:
11779537Satgutier@umich.edu        print "Warning: Failed to determine host ISA."
11789537Satgutier@umich.edu        return False
11799537Satgutier@umich.edu
11809888Sandreas@sandberg.pp.se    if not have_posix_timers:
11819888Sandreas@sandberg.pp.se        print "Warning: Can not enable KVM, host seems to lack support " \
11829888Sandreas@sandberg.pp.se            "for POSIX timers"
11839888Sandreas@sandberg.pp.se        return False
118410066Sandreas.hansson@arm.com
118510066Sandreas.hansson@arm.com    if isa == "arm":
118610066Sandreas.hansson@arm.com        return host_isa in ( "armv7l", "aarch64" )
118710066Sandreas.hansson@arm.com    elif isa == "x86":
118810428Sandreas.hansson@arm.com        if host_isa != "x86_64":
118910428Sandreas.hansson@arm.com            return False
119010428Sandreas.hansson@arm.com
119110428Sandreas.hansson@arm.com        if not have_kvm_xsave:
11921869SN/A            print "KVM on x86 requires xsave support in kernel headers."
11931869SN/A            return False
11943546Sgblack@eecs.umich.edu
11953546Sgblack@eecs.umich.edu        return True
11963546Sgblack@eecs.umich.edu    else:
11973546Sgblack@eecs.umich.edu        return False
11986121Snate@binkert.org
119910196SCurtis.Dunham@arm.com
12005863Snate@binkert.org# Check if the exclude_host attribute is available. We want this to
12013546Sgblack@eecs.umich.edu# get accurate instruction counts in KVM.
12023546Sgblack@eecs.umich.edumain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
12033546Sgblack@eecs.umich.edu    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
12043546Sgblack@eecs.umich.edu
12054781Snate@binkert.org
12066658Snate@binkert.org######################################################################
120710196SCurtis.Dunham@arm.com#
120810196SCurtis.Dunham@arm.com# Finish the configuration
120910196SCurtis.Dunham@arm.com#
121010196SCurtis.Dunham@arm.commain = conf.Finish()
121110196SCurtis.Dunham@arm.com
121210196SCurtis.Dunham@arm.com######################################################################
121310196SCurtis.Dunham@arm.com#
12143546Sgblack@eecs.umich.edu# Collect all non-global variables
12153546Sgblack@eecs.umich.edu#
12163546Sgblack@eecs.umich.edu
12173546Sgblack@eecs.umich.edu# Define the universe of supported ISAs
12187756SAli.Saidi@ARM.comall_isa_list = [ ]
12197816Ssteve.reinhardt@amd.comall_gpu_isa_list = [ ]
12203546Sgblack@eecs.umich.eduExport('all_isa_list')
12213546Sgblack@eecs.umich.eduExport('all_gpu_isa_list')
12223546Sgblack@eecs.umich.edu
12233546Sgblack@eecs.umich.educlass CpuModel(object):
122410196SCurtis.Dunham@arm.com    '''The CpuModel class encapsulates everything the ISA parser needs to
122510196SCurtis.Dunham@arm.com    know about a particular CPU model.'''
122610196SCurtis.Dunham@arm.com
122710196SCurtis.Dunham@arm.com    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
122810196SCurtis.Dunham@arm.com    dict = {}
12294202Sbinkertn@umich.edu
12303546Sgblack@eecs.umich.edu    # Constructor.  Automatically adds models to CpuModel.dict.
123110196SCurtis.Dunham@arm.com    def __init__(self, name, default=False):
123210196SCurtis.Dunham@arm.com        self.name = name           # name of model
123310196SCurtis.Dunham@arm.com
123410196SCurtis.Dunham@arm.com        # This cpu is enabled by default
123510196SCurtis.Dunham@arm.com        self.default = default
123610196SCurtis.Dunham@arm.com
123710196SCurtis.Dunham@arm.com        # Add self to dict
123810196SCurtis.Dunham@arm.com        if name in CpuModel.dict:
123910196SCurtis.Dunham@arm.com            raise AttributeError, "CpuModel '%s' already registered" % name
124010196SCurtis.Dunham@arm.com        CpuModel.dict[name] = self
124110196SCurtis.Dunham@arm.com
124210196SCurtis.Dunham@arm.comExport('CpuModel')
124310196SCurtis.Dunham@arm.com
124410196SCurtis.Dunham@arm.com# Sticky variables get saved in the variables file so they persist from
124510196SCurtis.Dunham@arm.com# one invocation to the next (unless overridden, in which case the new
124610196SCurtis.Dunham@arm.com# value becomes sticky).
124710196SCurtis.Dunham@arm.comsticky_vars = Variables(args=ARGUMENTS)
124810196SCurtis.Dunham@arm.comExport('sticky_vars')
124910196SCurtis.Dunham@arm.com
125010196SCurtis.Dunham@arm.com# Sticky variables that should be exported
125110196SCurtis.Dunham@arm.comexport_vars = []
125210196SCurtis.Dunham@arm.comExport('export_vars')
125310196SCurtis.Dunham@arm.com
125410196SCurtis.Dunham@arm.com# For Ruby
12553546Sgblack@eecs.umich.eduall_protocols = []
12563546Sgblack@eecs.umich.eduExport('all_protocols')
1257955SN/Aprotocol_dirs = []
1258955SN/AExport('protocol_dirs')
1259955SN/Aslicc_includes = []
1260955SN/AExport('slicc_includes')
12615863Snate@binkert.org
126210135SCurtis.Dunham@arm.com# Walk the tree and execute all SConsopts scripts that wil add to the
126310135SCurtis.Dunham@arm.com# above variables
12645343Sstever@gmail.comif GetOption('verbose'):
12655343Sstever@gmail.com    print "Reading SConsopts"
12666121Snate@binkert.orgfor bdir in [ base_dir ] + extras_dir_list:
12675863Snate@binkert.org    if not isdir(bdir):
12684773Snate@binkert.org        print "Error: directory '%s' does not exist" % bdir
12695863Snate@binkert.org        Exit(1)
12702632Sstever@eecs.umich.edu    for root, dirs, files in os.walk(bdir):
12715863Snate@binkert.org        if 'SConsopts' in files:
12722023SN/A            if GetOption('verbose'):
12735863Snate@binkert.org                print "Reading", joinpath(root, 'SConsopts')
12745863Snate@binkert.org            SConscript(joinpath(root, 'SConsopts'))
12755863Snate@binkert.org
12765863Snate@binkert.orgall_isa_list.sort()
12775863Snate@binkert.orgall_gpu_isa_list.sort()
12785863Snate@binkert.org
12795863Snate@binkert.orgsticky_vars.AddVariables(
12805863Snate@binkert.org    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
128110135SCurtis.Dunham@arm.com    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
128210135SCurtis.Dunham@arm.com    ListVariable('CPU_MODELS', 'CPU models',
12832632Sstever@eecs.umich.edu                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
12845863Snate@binkert.org                 sorted(CpuModel.dict.keys())),
12852023SN/A    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
12862632Sstever@eecs.umich.edu                 False),
12875863Snate@binkert.org    BoolVariable('SS_COMPATIBLE_FP',
12885342Sstever@gmail.com                 'Make floating-point results compatible with SimpleScalar',
12895863Snate@binkert.org                 False),
12902632Sstever@eecs.umich.edu    BoolVariable('USE_SSE2',
12915863Snate@binkert.org                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
12925863Snate@binkert.org                 False),
12938267Ssteve.reinhardt@amd.com    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
12948120Sgblack@eecs.umich.edu    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
12958267Ssteve.reinhardt@amd.com    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
12968267Ssteve.reinhardt@amd.com    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
12978267Ssteve.reinhardt@amd.com    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
12988267Ssteve.reinhardt@amd.com    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
12998267Ssteve.reinhardt@amd.com                  all_protocols),
13008267Ssteve.reinhardt@amd.com    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
13018267Ssteve.reinhardt@amd.com                 backtrace_impls[-1], backtrace_impls)
13028267Ssteve.reinhardt@amd.com    )
13038267Ssteve.reinhardt@amd.com
13045863Snate@binkert.org# These variables get exported to #defines in config/*.hh (see src/SConscript).
13055863Snate@binkert.orgexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
13065863Snate@binkert.org                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL',
13072632Sstever@eecs.umich.edu                'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
13088267Ssteve.reinhardt@amd.com
13098267Ssteve.reinhardt@amd.com###################################################
13108267Ssteve.reinhardt@amd.com#
13112632Sstever@eecs.umich.edu# Define a SCons builder for configuration flag headers.
13121888SN/A#
13135863Snate@binkert.org###################################################
13145863Snate@binkert.org
13151858SN/A# This function generates a config header file that #defines the
13168120Sgblack@eecs.umich.edu# variable symbol to the current variable setting (0 or 1).  The source
13178120Sgblack@eecs.umich.edu# operands are the name of the variable and a Value node containing the
13187756SAli.Saidi@ARM.com# value of the variable.
13192598SN/Adef build_config_file(target, source, env):
13205863Snate@binkert.org    (variable, value) = [s.get_contents() for s in source]
13211858SN/A    f = file(str(target[0]), 'w')
13221858SN/A    print >> f, '#define', variable, value
13231858SN/A    f.close()
13245863Snate@binkert.org    return None
13251858SN/A
13261858SN/A# Combine the two functions into a scons Action object.
13271858SN/Aconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
13285863Snate@binkert.org
13291871SN/A# The emitter munges the source & target node lists to reflect what
13301858SN/A# we're really doing.
13311858SN/Adef config_emitter(target, source, env):
13321858SN/A    # extract variable name from Builder arg
13331858SN/A    variable = str(target[0])
13349651SAndreas.Sandberg@ARM.com    # True target is config header file
13359651SAndreas.Sandberg@ARM.com    target = joinpath('config', variable.lower() + '.hh')
13369651SAndreas.Sandberg@ARM.com    val = env[variable]
13379651SAndreas.Sandberg@ARM.com    if isinstance(val, bool):
13389900Sandreas@sandberg.pp.se        # Force value to 0/1
13399900Sandreas@sandberg.pp.se        val = int(val)
13409900Sandreas@sandberg.pp.se    elif isinstance(val, str):
13419900Sandreas@sandberg.pp.se        val = '"' + val + '"'
13429651SAndreas.Sandberg@ARM.com
13439651SAndreas.Sandberg@ARM.com    # Sources are variable name & value (packaged in SCons Value nodes)
13449651SAndreas.Sandberg@ARM.com    return ([target], [Value(variable), Value(val)])
13459651SAndreas.Sandberg@ARM.com
13469651SAndreas.Sandberg@ARM.comconfig_builder = Builder(emitter = config_emitter, action = config_action)
13479986Sandreas@sandberg.pp.se
13489986Sandreas@sandberg.pp.semain.Append(BUILDERS = { 'ConfigFile' : config_builder })
13499986Sandreas@sandberg.pp.se
13509986Sandreas@sandberg.pp.se###################################################
13519986Sandreas@sandberg.pp.se#
13529986Sandreas@sandberg.pp.se# Builders for static and shared partially linked object files.
13539986Sandreas@sandberg.pp.se#
13545863Snate@binkert.org###################################################
13555863Snate@binkert.org
13561869SN/Apartial_static_builder = Builder(action=SCons.Defaults.LinkAction,
13571965SN/A                                 src_suffix='$OBJSUFFIX',
13587739Sgblack@eecs.umich.edu                                 src_builder=['StaticObject', 'Object'],
13591965SN/A                                 LINKFLAGS='$PLINKFLAGS',
13602761Sstever@eecs.umich.edu                                 LIBS='')
13615863Snate@binkert.org
13621869SN/Adef partial_shared_emitter(target, source, env):
136310196SCurtis.Dunham@arm.com    for tgt in target:
13641869SN/A        tgt.attributes.shared = 1
136510196SCurtis.Dunham@arm.com    return (target, source)
136610196SCurtis.Dunham@arm.compartial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
136710196SCurtis.Dunham@arm.com                                 emitter=partial_shared_emitter,
136810196SCurtis.Dunham@arm.com                                 src_suffix='$SHOBJSUFFIX',
136910196SCurtis.Dunham@arm.com                                 src_builder='SharedObject',
137010196SCurtis.Dunham@arm.com                                 SHLINKFLAGS='$PSHLINKFLAGS',
137110196SCurtis.Dunham@arm.com                                 LIBS='')
137210196SCurtis.Dunham@arm.com
137310196SCurtis.Dunham@arm.commain.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
137410196SCurtis.Dunham@arm.com                         'PartialStatic' : partial_static_builder })
137510196SCurtis.Dunham@arm.com
137610196SCurtis.Dunham@arm.com# builds in ext are shared across all configs in the build root.
137710196SCurtis.Dunham@arm.comext_dir = abspath(joinpath(str(main.root), 'ext'))
137810196SCurtis.Dunham@arm.comfor root, dirs, files in os.walk(ext_dir):
137910196SCurtis.Dunham@arm.com    if 'SConscript' in files:
138010196SCurtis.Dunham@arm.com        build_dir = os.path.relpath(root, ext_dir)
138110196SCurtis.Dunham@arm.com        main.SConscript(joinpath(root, 'SConscript'),
1382955SN/A                        variant_dir=joinpath(build_root, build_dir))
13838120Sgblack@eecs.umich.edu
13848120Sgblack@eecs.umich.edu###################################################
13858120Sgblack@eecs.umich.edu#
13868120Sgblack@eecs.umich.edu# This function is used to set up a directory with switching headers
13878120Sgblack@eecs.umich.edu#
13888120Sgblack@eecs.umich.edu###################################################
13898120Sgblack@eecs.umich.edu
13908120Sgblack@eecs.umich.edumain['ALL_ISA_LIST'] = all_isa_list
13918120Sgblack@eecs.umich.edumain['ALL_GPU_ISA_LIST'] = all_gpu_isa_list
13928120Sgblack@eecs.umich.eduall_isa_deps = {}
13938120Sgblack@eecs.umich.edudef make_switching_dir(dname, switch_headers, env):
13948120Sgblack@eecs.umich.edu    # Generate the header.  target[0] is the full path of the output
1395    # header to generate.  'source' is a dummy variable, since we get the
1396    # list of ISAs from env['ALL_ISA_LIST'].
1397    def gen_switch_hdr(target, source, env):
1398        fname = str(target[0])
1399        isa = env['TARGET_ISA'].lower()
1400        try:
1401            f = open(fname, 'w')
1402            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1403            f.close()
1404        except IOError:
1405            print "Failed to create %s" % fname
1406            raise
1407
1408    # Build SCons Action object. 'varlist' specifies env vars that this
1409    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1410    # should get re-executed.
1411    switch_hdr_action = MakeAction(gen_switch_hdr,
1412                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1413
1414    # Instantiate actions for each header
1415    for hdr in switch_headers:
1416        env.Command(hdr, [], switch_hdr_action)
1417
1418    isa_target = Dir('.').up().name.lower().replace('_', '-')
1419    env['PHONY_BASE'] = '#'+isa_target
1420    all_isa_deps[isa_target] = None
1421
1422Export('make_switching_dir')
1423
1424def make_gpu_switching_dir(dname, switch_headers, env):
1425    # Generate the header.  target[0] is the full path of the output
1426    # header to generate.  'source' is a dummy variable, since we get the
1427    # list of ISAs from env['ALL_ISA_LIST'].
1428    def gen_switch_hdr(target, source, env):
1429        fname = str(target[0])
1430
1431        isa = env['TARGET_GPU_ISA'].lower()
1432
1433        try:
1434            f = open(fname, 'w')
1435            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1436            f.close()
1437        except IOError:
1438            print "Failed to create %s" % fname
1439            raise
1440
1441    # Build SCons Action object. 'varlist' specifies env vars that this
1442    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1443    # should get re-executed.
1444    switch_hdr_action = MakeAction(gen_switch_hdr,
1445                          Transform("GENERATE"), varlist=['ALL_ISA_GPU_LIST'])
1446
1447    # Instantiate actions for each header
1448    for hdr in switch_headers:
1449        env.Command(hdr, [], switch_hdr_action)
1450
1451Export('make_gpu_switching_dir')
1452
1453# all-isas -> all-deps -> all-environs -> all_targets
1454main.Alias('#all-isas', [])
1455main.Alias('#all-deps', '#all-isas')
1456
1457# Dummy target to ensure all environments are created before telling
1458# SCons what to actually make (the command line arguments).  We attach
1459# them to the dependence graph after the environments are complete.
1460ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1461def environsComplete(target, source, env):
1462    for t in ORIG_BUILD_TARGETS:
1463        main.Depends('#all-targets', t)
1464
1465# Each build/* switching_dir attaches its *-environs target to #all-environs.
1466main.Append(BUILDERS = {'CompleteEnvirons' :
1467                        Builder(action=MakeAction(environsComplete, None))})
1468main.CompleteEnvirons('#all-environs', [])
1469
1470def doNothing(**ignored): pass
1471main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1472
1473# The final target to which all the original targets ultimately get attached.
1474main.Dummy('#all-targets', '#all-environs')
1475BUILD_TARGETS[:] = ['#all-targets']
1476
1477###################################################
1478#
1479# Define build environments for selected configurations.
1480#
1481###################################################
1482
1483for variant_path in variant_paths:
1484    if not GetOption('silent'):
1485        print "Building in", variant_path
1486
1487    # Make a copy of the build-root environment to use for this config.
1488    env = main.Clone()
1489    env['BUILDDIR'] = variant_path
1490
1491    # variant_dir is the tail component of build path, and is used to
1492    # determine the build parameters (e.g., 'ALPHA_SE')
1493    (build_root, variant_dir) = splitpath(variant_path)
1494
1495    # Set env variables according to the build directory config.
1496    sticky_vars.files = []
1497    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1498    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1499    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1500    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1501    if isfile(current_vars_file):
1502        sticky_vars.files.append(current_vars_file)
1503        if not GetOption('silent'):
1504            print "Using saved variables file %s" % current_vars_file
1505    else:
1506        # Build dir-specific variables file doesn't exist.
1507
1508        # Make sure the directory is there so we can create it later
1509        opt_dir = dirname(current_vars_file)
1510        if not isdir(opt_dir):
1511            mkdir(opt_dir)
1512
1513        # Get default build variables from source tree.  Variables are
1514        # normally determined by name of $VARIANT_DIR, but can be
1515        # overridden by '--default=' arg on command line.
1516        default = GetOption('default')
1517        opts_dir = joinpath(main.root.abspath, 'build_opts')
1518        if default:
1519            default_vars_files = [joinpath(build_root, 'variables', default),
1520                                  joinpath(opts_dir, default)]
1521        else:
1522            default_vars_files = [joinpath(opts_dir, variant_dir)]
1523        existing_files = filter(isfile, default_vars_files)
1524        if existing_files:
1525            default_vars_file = existing_files[0]
1526            sticky_vars.files.append(default_vars_file)
1527            print "Variables file %s not found,\n  using defaults in %s" \
1528                  % (current_vars_file, default_vars_file)
1529        else:
1530            print "Error: cannot find variables file %s or " \
1531                  "default file(s) %s" \
1532                  % (current_vars_file, ' or '.join(default_vars_files))
1533            Exit(1)
1534
1535    # Apply current variable settings to env
1536    sticky_vars.Update(env)
1537
1538    help_texts["local_vars"] += \
1539        "Build variables for %s:\n" % variant_dir \
1540                 + sticky_vars.GenerateHelpText(env)
1541
1542    # Process variable settings.
1543
1544    if not have_fenv and env['USE_FENV']:
1545        print "Warning: <fenv.h> not available; " \
1546              "forcing USE_FENV to False in", variant_dir + "."
1547        env['USE_FENV'] = False
1548
1549    if not env['USE_FENV']:
1550        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1551        print "         FP results may deviate slightly from other platforms."
1552
1553    if env['EFENCE']:
1554        env.Append(LIBS=['efence'])
1555
1556    if env['USE_KVM']:
1557        if not have_kvm:
1558            print "Warning: Can not enable KVM, host seems to lack KVM support"
1559            env['USE_KVM'] = False
1560        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1561            print "Info: KVM support disabled due to unsupported host and " \
1562                "target ISA combination"
1563            env['USE_KVM'] = False
1564
1565    if env['BUILD_GPU']:
1566        env.Append(CPPDEFINES=['BUILD_GPU'])
1567
1568    # Warn about missing optional functionality
1569    if env['USE_KVM']:
1570        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1571            print "Warning: perf_event headers lack support for the " \
1572                "exclude_host attribute. KVM instruction counts will " \
1573                "be inaccurate."
1574
1575    # Save sticky variable settings back to current variables file
1576    sticky_vars.Save(current_vars_file, env)
1577
1578    if env['USE_SSE2']:
1579        env.Append(CCFLAGS=['-msse2'])
1580
1581    # The src/SConscript file sets up the build rules in 'env' according
1582    # to the configured variables.  It returns a list of environments,
1583    # one for each variant build (debug, opt, etc.)
1584    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1585
1586def pairwise(iterable):
1587    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1588    a, b = itertools.tee(iterable)
1589    b.next()
1590    return itertools.izip(a, b)
1591
1592# Create false dependencies so SCons will parse ISAs, establish
1593# dependencies, and setup the build Environments serially. Either
1594# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1595# greater than 1. It appears to be standard race condition stuff; it
1596# doesn't always fail, but usually, and the behaviors are different.
1597# Every time I tried to remove this, builds would fail in some
1598# creative new way. So, don't do that. You'll want to, though, because
1599# tests/SConscript takes a long time to make its Environments.
1600for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1601    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1602    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1603
1604# base help text
1605Help('''
1606Usage: scons [scons options] [build variables] [target(s)]
1607
1608Extra scons options:
1609%(options)s
1610
1611Global build variables:
1612%(global_vars)s
1613
1614%(local_vars)s
1615''' % help_texts)
1616