SConstruct revision 12178
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2013, 2015, 2016 ARM Limited
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/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
282665Ssaidi@eecs.umich.edu# contributors may be used to endorse or promote products derived from
292665Ssaidi@eecs.umich.edu# 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
352632Sstever@eecs.umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
362632Sstever@eecs.umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
372632Sstever@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
382632Sstever@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
402632Sstever@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422761Sstever@eecs.umich.edu#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452632Sstever@eecs.umich.edu
462761Sstever@eecs.umich.edu###################################################
472761Sstever@eecs.umich.edu#
482761Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492632Sstever@eecs.umich.edu#
502632Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
522761Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532761Sstever@eecs.umich.edu# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# 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
572632Sstever@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:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
63955SN/A#   scons to search up the directory tree for this SConstruct file.
64955SN/A#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
65955SN/A#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
684202Sbinkertn@umich.edu#   in a directory outside of the source tree.  The '-C' option tells
694678Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
70955SN/A#   file.
715273Sstever@gmail.com#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
725273Sstever@gmail.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732656Sstever@eecs.umich.edu#
742656Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
752656Sstever@eecs.umich.edu# 'gem5' directory (or use -u or -C to tell scons where to find this
762656Sstever@eecs.umich.edu# file), you can use 'scons -h' to print all the gem5-specific build
772656Sstever@eecs.umich.edu# options as well.
782656Sstever@eecs.umich.edu#
792656Sstever@eecs.umich.edu###################################################
802653Sstever@eecs.umich.edu
815227Ssaidi@eecs.umich.edu# Check for recent-enough Python and SCons versions.
825227Ssaidi@eecs.umich.edutry:
835227Ssaidi@eecs.umich.edu    # Really old versions of scons only take two options for the
845227Ssaidi@eecs.umich.edu    # function, so check once without the revision and once with the
852653Sstever@eecs.umich.edu    # revision, the first instance will fail for stuff other than
862653Sstever@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
872653Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98)
882653Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98, 1)
892653Sstever@eecs.umich.eduexcept SystemExit, e:
902653Sstever@eecs.umich.edu    print """
912653Sstever@eecs.umich.eduFor more details, see:
922653Sstever@eecs.umich.edu    http://gem5.org/Dependencies
932653Sstever@eecs.umich.edu"""
944781Snate@binkert.org    raise
951852SN/A
96955SN/A# pybind11 requires python 2.7
97955SN/Atry:
98955SN/A    EnsurePythonVersion(2, 7)
993717Sstever@eecs.umich.eduexcept SystemExit, e:
1003716Sstever@eecs.umich.edu    print """
101955SN/AYou can use a non-default installation of the Python interpreter by
1021533SN/Arearranging your PATH so that scons finds the non-default 'python' and
1033716Sstever@eecs.umich.edu'python-config' first.
1041533SN/A
1054678Snate@binkert.orgFor more details, see:
1064678Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1074678Snate@binkert.org"""
1084678Snate@binkert.org    raise
1094678Snate@binkert.org
1104678Snate@binkert.org# Global Python includes
1114678Snate@binkert.orgimport itertools
1124678Snate@binkert.orgimport os
1134678Snate@binkert.orgimport re
1144678Snate@binkert.orgimport shutil
1154678Snate@binkert.orgimport subprocess
1164678Snate@binkert.orgimport sys
1174678Snate@binkert.org
1184678Snate@binkert.orgfrom os import mkdir, environ
1194678Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1204678Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1214678Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1224678Snate@binkert.org
1234678Snate@binkert.org# SCons includes
1244678Snate@binkert.orgimport SCons
1254678Snate@binkert.orgimport SCons.Node
1264973Ssaidi@eecs.umich.edu
1274678Snate@binkert.orgextra_python_paths = [
1284678Snate@binkert.org    Dir('src/python').srcnode().abspath, # gem5 includes
1294678Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1304678Snate@binkert.org    ]
1314678Snate@binkert.org
1324678Snate@binkert.orgsys.path[1:1] = extra_python_paths
133955SN/A
134955SN/Afrom m5.util import compareVersions, readCommand
1352632Sstever@eecs.umich.edufrom m5.util.terminal import get_termcap
1362632Sstever@eecs.umich.edu
137955SN/Ahelp_texts = {
138955SN/A    "options" : "",
139955SN/A    "global_vars" : "",
140955SN/A    "local_vars" : ""
1412632Sstever@eecs.umich.edu}
142955SN/A
1432632Sstever@eecs.umich.eduExport("help_texts")
1442632Sstever@eecs.umich.edu
1452632Sstever@eecs.umich.edu
1462632Sstever@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1472632Sstever@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1482632Sstever@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1492632Sstever@eecs.umich.edu# Help() function, but these two features are incompatible: once
1503053Sstever@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1513053Sstever@eecs.umich.edu# at the help texts from AddOptions.  See:
1523053Sstever@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1533053Sstever@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1543053Sstever@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1553053Sstever@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1563053Sstever@eecs.umich.edu# we can just use AddOption directly.
1573053Sstever@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1583053Sstever@eecs.umich.edu    col_width = 30
1593053Sstever@eecs.umich.edu
1603053Sstever@eecs.umich.edu    help = "  " + ", ".join(args)
1613053Sstever@eecs.umich.edu    if "help" in kwargs:
1623053Sstever@eecs.umich.edu        length = len(help)
1633053Sstever@eecs.umich.edu        if length >= col_width:
1643053Sstever@eecs.umich.edu            help += "\n" + " " * col_width
1653053Sstever@eecs.umich.edu        else:
1662632Sstever@eecs.umich.edu            help += " " * (col_width - length)
1672632Sstever@eecs.umich.edu        help += kwargs["help"]
1682632Sstever@eecs.umich.edu    help_texts["options"] += help + "\n"
1692632Sstever@eecs.umich.edu
1702632Sstever@eecs.umich.edu    AddOption(*args, **kwargs)
1712632Sstever@eecs.umich.edu
1723718Sstever@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1733718Sstever@eecs.umich.edu               help="Add color to abbreviated scons output")
1743718Sstever@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1753718Sstever@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1763718Sstever@eecs.umich.eduAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1773718Sstever@eecs.umich.edu               action='store_true',
1783718Sstever@eecs.umich.edu               help="Build with support for C++-based configuration")
1793718Sstever@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1803718Sstever@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1813718Sstever@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1823718Sstever@eecs.umich.edu               help='Disable style checking hooks')
1833718Sstever@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1843718Sstever@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1852634Sstever@eecs.umich.eduAddLocalOption('--force-lto', dest='force_lto', action='store_true',
1862634Sstever@eecs.umich.edu               help='Use Link-Time Optimization instead of partial linking' +
1872632Sstever@eecs.umich.edu                    ' when the compiler doesn\'t support using them together.')
1882638Sstever@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1892632Sstever@eecs.umich.edu               help='Update test reference outputs')
1902632Sstever@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1912632Sstever@eecs.umich.edu               help='Print full tool command lines')
1922632Sstever@eecs.umich.eduAddLocalOption('--without-python', dest='without_python',
1932632Sstever@eecs.umich.edu               action='store_true',
1942632Sstever@eecs.umich.edu               help='Build without Python configuration support')
1951858SN/AAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1963716Sstever@eecs.umich.edu               action='store_true',
1972638Sstever@eecs.umich.edu               help='Disable linking against tcmalloc')
1982638Sstever@eecs.umich.eduAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1992638Sstever@eecs.umich.edu               help='Build with Undefined Behavior Sanitizer if available')
2002638Sstever@eecs.umich.eduAddLocalOption('--with-asan', dest='with_asan', action='store_true',
2012638Sstever@eecs.umich.edu               help='Build with Address Sanitizer if available')
2022638Sstever@eecs.umich.edu
2032638Sstever@eecs.umich.eduif GetOption('no_lto') and GetOption('force_lto'):
2043716Sstever@eecs.umich.edu    print '--no-lto and --force-lto are mutually exclusive'
2052634Sstever@eecs.umich.edu    Exit(1)
2062634Sstever@eecs.umich.edu
207955SN/Atermcap = get_termcap(GetOption('use_colors'))
208955SN/A
209955SN/A########################################################################
210955SN/A#
211955SN/A# Set up the main build environment.
212955SN/A#
213955SN/A########################################################################
214955SN/A
2151858SN/A# export TERM so that clang reports errors in color
2161858SN/Ause_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2172632Sstever@eecs.umich.edu                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
218955SN/A                 'PYTHONPATH', 'RANLIB', 'TERM' ])
2194781Snate@binkert.org
2203643Ssaidi@eecs.umich.eduuse_prefixes = [
2213643Ssaidi@eecs.umich.edu    "ASAN_",           # address sanitizer symbolizer path and settings
2223643Ssaidi@eecs.umich.edu    "CCACHE_",         # ccache (caching compiler wrapper) configuration
2233643Ssaidi@eecs.umich.edu    "CCC_",            # clang static analyzer configuration
2243643Ssaidi@eecs.umich.edu    "DISTCC_",         # distcc (distributed compiler wrapper) configuration
2253643Ssaidi@eecs.umich.edu    "INCLUDE_SERVER_", # distcc pump server settings
2263643Ssaidi@eecs.umich.edu    "M5",              # M5 configuration (e.g., path to kernels)
2274494Ssaidi@eecs.umich.edu    ]
2284494Ssaidi@eecs.umich.edu
2293716Sstever@eecs.umich.eduuse_env = {}
2301105SN/Afor key,val in sorted(os.environ.iteritems()):
2312667Sstever@eecs.umich.edu    if key in use_vars or \
2322667Sstever@eecs.umich.edu            any([key.startswith(prefix) for prefix in use_prefixes]):
2332667Sstever@eecs.umich.edu        use_env[key] = val
2342667Sstever@eecs.umich.edu
2352667Sstever@eecs.umich.edu# Tell scons to avoid implicit command dependencies to avoid issues
2362667Sstever@eecs.umich.edu# with the param wrappes being compiled twice (see
2371869SN/A# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2381869SN/Amain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2391869SN/Amain.Decider('MD5-timestamp')
2401869SN/Amain.root = Dir(".")         # The current directory (where this file lives).
2411869SN/Amain.srcdir = Dir("src")     # The source directory
2421065SN/A
2432632Sstever@eecs.umich.edumain_dict_keys = main.Dictionary().keys()
2445199Sstever@gmail.com
2453918Ssaidi@eecs.umich.edu# Check that we have a C/C++ compiler
2463918Ssaidi@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2473940Ssaidi@eecs.umich.edu    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2484781Snate@binkert.org    Exit(1)
2494781Snate@binkert.org
2503918Ssaidi@eecs.umich.edu# add useful python code PYTHONPATH so it can be used by subprocesses
2514781Snate@binkert.org# as well
2524781Snate@binkert.orgmain.AppendENVPath('PYTHONPATH', extra_python_paths)
2533918Ssaidi@eecs.umich.edu
2544781Snate@binkert.org########################################################################
2554781Snate@binkert.org#
2563940Ssaidi@eecs.umich.edu# Mercurial Stuff.
2573942Ssaidi@eecs.umich.edu#
2583940Ssaidi@eecs.umich.edu# If the gem5 directory is a mercurial repository, we should do some
2593918Ssaidi@eecs.umich.edu# extra things.
2603918Ssaidi@eecs.umich.edu#
261955SN/A########################################################################
2621858SN/A
2633918Ssaidi@eecs.umich.eduhgdir = main.root.Dir(".hg")
2643918Ssaidi@eecs.umich.edu
2653918Ssaidi@eecs.umich.edu
2663918Ssaidi@eecs.umich.edustyle_message = """
2673940Ssaidi@eecs.umich.eduYou're missing the gem5 style hook, which automatically checks your code
2683940Ssaidi@eecs.umich.eduagainst the gem5 style rules on %s.
2693918Ssaidi@eecs.umich.eduThis script will now install the hook in your %s.
2703918Ssaidi@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2713918Ssaidi@eecs.umich.edu
2723918Ssaidi@eecs.umich.edumercurial_style_message = """
2733918Ssaidi@eecs.umich.eduYou're missing the gem5 style hook, which automatically checks your code
2743918Ssaidi@eecs.umich.eduagainst the gem5 style rules on hg commit and qrefresh commands.
2753918Ssaidi@eecs.umich.eduThis script will now install the hook in your .hg/hgrc file.
2763918Ssaidi@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2773918Ssaidi@eecs.umich.edu
2783940Ssaidi@eecs.umich.edugit_style_message = """
2793918Ssaidi@eecs.umich.eduYou're missing the gem5 style or commit message hook. These hooks help
2803918Ssaidi@eecs.umich.eduto ensure that your code follows gem5's style rules on git commit.
2811851SN/AThis script will now install the hook in your .git/hooks/ directory.
2821851SN/APress enter to continue, or ctrl-c to abort: """
2831858SN/A
2845200Sstever@gmail.commercurial_style_upgrade_message = """
285955SN/AYour Mercurial style hooks are not up-to-date. This script will now
2863053Sstever@eecs.umich.edutry to automatically update them. A backup of your hgrc will be saved
2873053Sstever@eecs.umich.eduin .hg/hgrc.old.
2883053Sstever@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2893053Sstever@eecs.umich.edu
2903053Sstever@eecs.umich.edumercurial_style_hook = """
2913053Sstever@eecs.umich.edu# The following lines were automatically added by gem5/SConstruct
2923053Sstever@eecs.umich.edu# to provide the gem5 style-checking hooks
2933053Sstever@eecs.umich.edu[extensions]
2943053Sstever@eecs.umich.eduhgstyle = %s/util/hgstyle.py
2954742Sstever@eecs.umich.edu
2964742Sstever@eecs.umich.edu[hooks]
2973053Sstever@eecs.umich.edupretxncommit.style = python:hgstyle.check_style
2983053Sstever@eecs.umich.edupre-qrefresh.style = python:hgstyle.check_style
2993053Sstever@eecs.umich.edu# End of SConstruct additions
3003053Sstever@eecs.umich.edu
3013053Sstever@eecs.umich.edu""" % (main.root.abspath)
3023053Sstever@eecs.umich.edu
3033053Sstever@eecs.umich.edumercurial_lib_not_found = """
3043053Sstever@eecs.umich.eduMercurial libraries cannot be found, ignoring style hook.  If
3053053Sstever@eecs.umich.eduyou are a gem5 developer, please fix this and run the style
3062667Sstever@eecs.umich.eduhook. It is important.
3074554Sbinkertn@umich.edu"""
3084554Sbinkertn@umich.edu
3092667Sstever@eecs.umich.edu# Check for style hook and prompt for installation if it's not there.
3104554Sbinkertn@umich.edu# Skip this if --ignore-style was specified, there's no interactive
3114554Sbinkertn@umich.edu# terminal to prompt, or no recognized revision control system can be
3124554Sbinkertn@umich.edu# found.
3134554Sbinkertn@umich.eduignore_style = GetOption('ignore_style') or not sys.stdin.isatty()
3144554Sbinkertn@umich.edu
3154554Sbinkertn@umich.edu# Try wire up Mercurial to the style hooks
3164554Sbinkertn@umich.eduif not ignore_style and hgdir.exists():
3174781Snate@binkert.org    style_hook = True
3184554Sbinkertn@umich.edu    style_hooks = tuple()
3194554Sbinkertn@umich.edu    hgrc = hgdir.File('hgrc')
3202667Sstever@eecs.umich.edu    hgrc_old = hgdir.File('hgrc.old')
3214554Sbinkertn@umich.edu    try:
3224554Sbinkertn@umich.edu        from mercurial import ui
3234554Sbinkertn@umich.edu        ui = ui.ui()
3244554Sbinkertn@umich.edu        ui.readconfig(hgrc.abspath)
3252667Sstever@eecs.umich.edu        style_hooks = (ui.config('hooks', 'pretxncommit.style', None),
3264554Sbinkertn@umich.edu                       ui.config('hooks', 'pre-qrefresh.style', None))
3272667Sstever@eecs.umich.edu        style_hook = all(style_hooks)
3284554Sbinkertn@umich.edu        style_extension = ui.config('extensions', 'style', None)
3294554Sbinkertn@umich.edu    except ImportError:
3302667Sstever@eecs.umich.edu        print mercurial_lib_not_found
3312638Sstever@eecs.umich.edu
3322638Sstever@eecs.umich.edu    if "python:style.check_style" in style_hooks:
3332638Sstever@eecs.umich.edu        # Try to upgrade the style hooks
3343716Sstever@eecs.umich.edu        print mercurial_style_upgrade_message
3353716Sstever@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
3361858SN/A        try:
3375227Ssaidi@eecs.umich.edu            raw_input()
3385227Ssaidi@eecs.umich.edu        except:
3395227Ssaidi@eecs.umich.edu            print "Input exception, exiting scons.\n"
3405227Ssaidi@eecs.umich.edu            sys.exit(1)
3415227Ssaidi@eecs.umich.edu        shutil.copyfile(hgrc.abspath, hgrc_old.abspath)
3425227Ssaidi@eecs.umich.edu        re_style_hook = re.compile(r"^([^=#]+)\.style\s*=\s*([^#\s]+).*")
3435227Ssaidi@eecs.umich.edu        re_style_extension = re.compile("style\s*=\s*([^#\s]+).*")
3445227Ssaidi@eecs.umich.edu        old, new = open(hgrc_old.abspath, 'r'), open(hgrc.abspath, 'w')
3455227Ssaidi@eecs.umich.edu        for l in old:
3465227Ssaidi@eecs.umich.edu            m_hook = re_style_hook.match(l)
3475227Ssaidi@eecs.umich.edu            m_ext = re_style_extension.match(l)
3485227Ssaidi@eecs.umich.edu            if m_hook:
3495274Ssaidi@eecs.umich.edu                hook, check = m_hook.groups()
3505227Ssaidi@eecs.umich.edu                if check != "python:style.check_style":
3515227Ssaidi@eecs.umich.edu                    print "Warning: %s.style is using a non-default " \
3525227Ssaidi@eecs.umich.edu                        "checker: %s" % (hook, check)
3535204Sstever@gmail.com                if hook not in ("pretxncommit", "pre-qrefresh"):
3545204Sstever@gmail.com                    print "Warning: Updating unknown style hook: %s" % hook
3555204Sstever@gmail.com
3565204Sstever@gmail.com                l = "%s.style = python:hgstyle.check_style\n" % hook
3575204Sstever@gmail.com            elif m_ext and m_ext.group(1) == style_extension:
3585204Sstever@gmail.com                l = "hgstyle = %s/util/hgstyle.py\n" % main.root.abspath
3595204Sstever@gmail.com
3605204Sstever@gmail.com            new.write(l)
3615204Sstever@gmail.com    elif not style_hook:
3625204Sstever@gmail.com        print mercurial_style_message,
3635204Sstever@gmail.com        # continue unless user does ctrl-c/ctrl-d etc.
3645204Sstever@gmail.com        try:
3655204Sstever@gmail.com            raw_input()
3665204Sstever@gmail.com        except:
3675204Sstever@gmail.com            print "Input exception, exiting scons.\n"
3685204Sstever@gmail.com            sys.exit(1)
3695204Sstever@gmail.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3705204Sstever@gmail.com        print "Adding style hook to", hgrc_path, "\n"
3715204Sstever@gmail.com        try:
3723118Sstever@eecs.umich.edu            with open(hgrc_path, 'a') as f:
3733118Sstever@eecs.umich.edu                f.write(mercurial_style_hook)
3743118Sstever@eecs.umich.edu        except:
3753118Sstever@eecs.umich.edu            print "Error updating", hgrc_path
3763118Sstever@eecs.umich.edu            sys.exit(1)
3773118Sstever@eecs.umich.edu
3783118Sstever@eecs.umich.edudef install_git_style_hooks():
3793118Sstever@eecs.umich.edu    try:
3803118Sstever@eecs.umich.edu        gitdir = Dir(readCommand(
3813118Sstever@eecs.umich.edu            ["git", "rev-parse", "--git-dir"]).strip("\n"))
3823118Sstever@eecs.umich.edu    except Exception, e:
3833716Sstever@eecs.umich.edu        print "Warning: Failed to find git repo directory: %s" % e
3843118Sstever@eecs.umich.edu        return
3853118Sstever@eecs.umich.edu
3863118Sstever@eecs.umich.edu    git_hooks = gitdir.Dir("hooks")
3873118Sstever@eecs.umich.edu    def hook_exists(hook_name):
3883118Sstever@eecs.umich.edu        hook = git_hooks.File(hook_name)
3893118Sstever@eecs.umich.edu        return hook.exists()
3903118Sstever@eecs.umich.edu
3913118Sstever@eecs.umich.edu    def hook_install(hook_name, script):
3923118Sstever@eecs.umich.edu        hook = git_hooks.File(hook_name)
3933716Sstever@eecs.umich.edu        if hook.exists():
3943118Sstever@eecs.umich.edu            print "Warning: Can't install %s, hook already exists." % hook_name
3953118Sstever@eecs.umich.edu            return
3963118Sstever@eecs.umich.edu
3973118Sstever@eecs.umich.edu        if hook.islink():
3983118Sstever@eecs.umich.edu            print "Warning: Removing broken symlink for hook %s." % hook_name
3993118Sstever@eecs.umich.edu            os.unlink(hook.get_abspath())
4003118Sstever@eecs.umich.edu
4013118Sstever@eecs.umich.edu        if not git_hooks.exists():
4023118Sstever@eecs.umich.edu            mkdir(git_hooks.get_abspath())
4033118Sstever@eecs.umich.edu            git_hooks.clear()
4043483Ssaidi@eecs.umich.edu
4053494Ssaidi@eecs.umich.edu        abs_symlink_hooks = git_hooks.islink() and \
4063494Ssaidi@eecs.umich.edu            os.path.isabs(os.readlink(git_hooks.get_abspath()))
4073483Ssaidi@eecs.umich.edu
4083483Ssaidi@eecs.umich.edu        # Use a relative symlink if the hooks live in the source directory,
4093483Ssaidi@eecs.umich.edu        # and the hooks directory is not a symlink to an absolute path.
4103053Sstever@eecs.umich.edu        if hook.is_under(main.root) and not abs_symlink_hooks:
4113053Sstever@eecs.umich.edu            script_path = os.path.relpath(
4123918Ssaidi@eecs.umich.edu                os.path.realpath(script.get_abspath()),
4133053Sstever@eecs.umich.edu                os.path.realpath(hook.Dir(".").get_abspath()))
4143053Sstever@eecs.umich.edu        else:
4153053Sstever@eecs.umich.edu            script_path = script.get_abspath()
4163053Sstever@eecs.umich.edu
4173053Sstever@eecs.umich.edu        try:
4181858SN/A            os.symlink(script_path, hook.get_abspath())
4191858SN/A        except:
4201858SN/A            print "Error updating git %s hook" % hook_name
4211858SN/A            raise
4221858SN/A
4231858SN/A    if hook_exists("pre-commit") and hook_exists("commit-msg"):
4241859SN/A        return
4251858SN/A
4261858SN/A    print git_style_message,
4271858SN/A    try:
4281859SN/A        raw_input()
4291859SN/A    except:
4301862SN/A        print "Input exception, exiting scons.\n"
4313053Sstever@eecs.umich.edu        sys.exit(1)
4323053Sstever@eecs.umich.edu
4333053Sstever@eecs.umich.edu    git_style_script = File("util/git-pre-commit.py")
4343053Sstever@eecs.umich.edu    git_msg_script = File("ext/git-commit-msg")
4351859SN/A
4361859SN/A    hook_install("pre-commit", git_style_script)
4371859SN/A    hook_install("commit-msg", git_msg_script)
4381859SN/A
4391859SN/A# Try to wire up git to the style hooks
4401859SN/Aif not ignore_style and main.root.Entry(".git").exists():
4411859SN/A    install_git_style_hooks()
4421859SN/A
4431862SN/A###################################################
4441859SN/A#
4451859SN/A# Figure out which configurations to set up based on the path(s) of
4461859SN/A# the target(s).
4471858SN/A#
4481858SN/A###################################################
4492139SN/A
4504202Sbinkertn@umich.edu# Find default configuration & binary.
4514202Sbinkertn@umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
4522139SN/A
4532155SN/A# helper function: find last occurrence of element in list
4544202Sbinkertn@umich.edudef rfind(l, elt, offs = -1):
4554202Sbinkertn@umich.edu    for i in range(len(l)+offs, 0, -1):
4564202Sbinkertn@umich.edu        if l[i] == elt:
4572155SN/A            return i
4581869SN/A    raise ValueError, "element not found"
4591869SN/A
4601869SN/A# Take a list of paths (or SCons Nodes) and return a list with all
4611869SN/A# paths made absolute and ~-expanded.  Paths will be interpreted
4624202Sbinkertn@umich.edu# relative to the launch directory unless a different root is provided
4634202Sbinkertn@umich.edudef makePathListAbsolute(path_list, root=GetLaunchDir()):
4644202Sbinkertn@umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
4654202Sbinkertn@umich.edu            for p in path_list]
4664202Sbinkertn@umich.edu
4674202Sbinkertn@umich.edu# Each target must have 'build' in the interior of the path; the
4684202Sbinkertn@umich.edu# directory below this will determine the build parameters.  For
4694202Sbinkertn@umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
4704202Sbinkertn@umich.edu# recognize that ALPHA_SE specifies the configuration because it
4714202Sbinkertn@umich.edu# follow 'build' in the build path.
4724202Sbinkertn@umich.edu
4734202Sbinkertn@umich.edu# The funky assignment to "[:]" is needed to replace the list contents
4744202Sbinkertn@umich.edu# in place rather than reassign the symbol to a new list, which
4754202Sbinkertn@umich.edu# doesn't work (obviously!).
4764202Sbinkertn@umich.eduBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
4774202Sbinkertn@umich.edu
4785273Sstever@gmail.com# Generate a list of the unique build roots and configs that the
4795273Sstever@gmail.com# collected targets reference.
4805273Sstever@gmail.comvariant_paths = []
4815273Sstever@gmail.combuild_root = None
4825273Sstever@gmail.comfor t in BUILD_TARGETS:
4835273Sstever@gmail.com    path_dirs = t.split('/')
4845273Sstever@gmail.com    try:
4854775Snate@binkert.org        build_top = rfind(path_dirs, 'build', -2)
4864775Snate@binkert.org    except:
4874773Snate@binkert.org        print "Error: no non-leaf 'build' dir found on target path", t
4884773Snate@binkert.org        Exit(1)
4894773Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
4905273Sstever@gmail.com    if not build_root:
4914773Snate@binkert.org        build_root = this_build_root
4921869SN/A    else:
4934202Sbinkertn@umich.edu        if this_build_root != build_root:
4941869SN/A            print "Error: build targets not under same build root\n"\
4952508SN/A                  "  %s\n  %s" % (build_root, this_build_root)
4962508SN/A            Exit(1)
4972508SN/A    variant_path = joinpath('/',*path_dirs[:build_top+2])
4982508SN/A    if variant_path not in variant_paths:
4994202Sbinkertn@umich.edu        variant_paths.append(variant_path)
5001869SN/A
5011869SN/A# Make sure build_root exists (might not if this is the first build there)
5021869SN/Aif not isdir(build_root):
5031869SN/A    mkdir(build_root)
5041869SN/Amain['BUILDROOT'] = build_root
5051869SN/A
5061965SN/AExport('main')
5071965SN/A
5081965SN/Amain.SConsignFile(joinpath(build_root, "sconsign"))
5091869SN/A
5101869SN/A# Default duplicate option is to use hard links, but this messes up
5112733Sktlim@umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
5121869SN/A# file to file~ then copies to file, breaking the link.  Symbolic
5131884SN/A# (soft) links work better.
5141884SN/Amain.SetOption('duplicate', 'soft-copy')
5153356Sbinkertn@umich.edu
5163356Sbinkertn@umich.edu#
5173356Sbinkertn@umich.edu# Set up global sticky variables... these are common to an entire build
5184773Snate@binkert.org# tree (not specific to a particular build like ALPHA_SE)
5194773Snate@binkert.org#
5205273Sstever@gmail.com
5211869SN/Aglobal_vars_file = joinpath(build_root, 'variables.global')
5221858SN/A
5231869SN/Aglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
5241869SN/A
5251869SN/Aglobal_vars.AddVariables(
5261858SN/A    ('CC', 'C compiler', environ.get('CC', main['CC'])),
5272761Sstever@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
5281869SN/A    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
5292733Sktlim@umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
5303584Ssaidi@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
5311869SN/A    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
5321869SN/A    ('EXTRAS', 'Add extra directories to the compilation', '')
5331869SN/A    )
5341869SN/A
5351869SN/A# Update main environment with values from ARGUMENTS & global_vars_file
5361869SN/Aglobal_vars.Update(main)
5371858SN/Ahelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
538955SN/A
539955SN/A# Save sticky variable settings back to current variables file
5401869SN/Aglobal_vars.Save(global_vars_file, main)
5411869SN/A
5421869SN/A# Parse EXTRAS variable to build list of all directories where we're
5431869SN/A# look for sources etc.  This list is exported as extras_dir_list.
5441869SN/Abase_dir = main.srcdir.abspath
5451869SN/Aif main['EXTRAS']:
5461869SN/A    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
5471869SN/Aelse:
5481869SN/A    extras_dir_list = []
5491869SN/A
5501869SN/AExport('base_dir')
5511869SN/AExport('extras_dir_list')
5521869SN/A
5531869SN/A# the ext directory should be on the #includes path
5541869SN/Amain.Append(CPPPATH=[Dir('ext')])
5551869SN/A
5561869SN/A# Add shared top-level headers
5571869SN/Amain.Prepend(CPPPATH=Dir('include'))
5581869SN/A
5591869SN/Adef strip_build_path(path, env):
5601869SN/A    path = str(path)
5611869SN/A    variant_base = env['BUILDROOT'] + os.path.sep
5621869SN/A    if path.startswith(variant_base):
5631869SN/A        path = path[len(variant_base):]
5641869SN/A    elif path.startswith('build/'):
5651869SN/A        path = path[6:]
5661869SN/A    return path
5671869SN/A
5681869SN/A# Generate a string of the form:
5693716Sstever@eecs.umich.edu#   common/path/prefix/src1, src2 -> tgt1, tgt2
5703356Sbinkertn@umich.edu# to print while building.
5713356Sbinkertn@umich.educlass Transform(object):
5723356Sbinkertn@umich.edu    # all specific color settings should be here and nowhere else
5733356Sbinkertn@umich.edu    tool_color = termcap.Normal
5743356Sbinkertn@umich.edu    pfx_color = termcap.Yellow
5753356Sbinkertn@umich.edu    srcs_color = termcap.Yellow + termcap.Bold
5764781Snate@binkert.org    arrow_color = termcap.Blue + termcap.Bold
5771869SN/A    tgts_color = termcap.Yellow + termcap.Bold
5781869SN/A
5791869SN/A    def __init__(self, tool, max_sources=99):
5801869SN/A        self.format = self.tool_color + (" [%8s] " % tool) \
5811869SN/A                      + self.pfx_color + "%s" \
5821869SN/A                      + self.srcs_color + "%s" \
5831869SN/A                      + self.arrow_color + " -> " \
5842655Sstever@eecs.umich.edu                      + self.tgts_color + "%s" \
5852655Sstever@eecs.umich.edu                      + termcap.Normal
5862655Sstever@eecs.umich.edu        self.max_sources = max_sources
5872655Sstever@eecs.umich.edu
5882655Sstever@eecs.umich.edu    def __call__(self, target, source, env, for_signature=None):
5892655Sstever@eecs.umich.edu        # truncate source list according to max_sources param
5902655Sstever@eecs.umich.edu        source = source[0:self.max_sources]
5912655Sstever@eecs.umich.edu        def strip(f):
5922655Sstever@eecs.umich.edu            return strip_build_path(str(f), env)
5932655Sstever@eecs.umich.edu        if len(source) > 0:
5942655Sstever@eecs.umich.edu            srcs = map(strip, source)
5952655Sstever@eecs.umich.edu        else:
5962655Sstever@eecs.umich.edu            srcs = ['']
5972655Sstever@eecs.umich.edu        tgts = map(strip, target)
5982655Sstever@eecs.umich.edu        # surprisingly, os.path.commonprefix is a dumb char-by-char string
5992655Sstever@eecs.umich.edu        # operation that has nothing to do with paths.
6002655Sstever@eecs.umich.edu        com_pfx = os.path.commonprefix(srcs + tgts)
6012655Sstever@eecs.umich.edu        com_pfx_len = len(com_pfx)
6022655Sstever@eecs.umich.edu        if com_pfx:
6032655Sstever@eecs.umich.edu            # do some cleanup and sanity checking on common prefix
6042655Sstever@eecs.umich.edu            if com_pfx[-1] == ".":
6052655Sstever@eecs.umich.edu                # prefix matches all but file extension: ok
6062655Sstever@eecs.umich.edu                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
6072655Sstever@eecs.umich.edu                com_pfx = com_pfx[0:-1]
6082655Sstever@eecs.umich.edu            elif com_pfx[-1] == "/":
6092655Sstever@eecs.umich.edu                # common prefix is directory path: OK
6102634Sstever@eecs.umich.edu                pass
6112634Sstever@eecs.umich.edu            else:
6122634Sstever@eecs.umich.edu                src0_len = len(srcs[0])
6132634Sstever@eecs.umich.edu                tgt0_len = len(tgts[0])
6142634Sstever@eecs.umich.edu                if src0_len == com_pfx_len:
6152634Sstever@eecs.umich.edu                    # source is a substring of target, OK
6162638Sstever@eecs.umich.edu                    pass
6172638Sstever@eecs.umich.edu                elif tgt0_len == com_pfx_len:
6183716Sstever@eecs.umich.edu                    # target is a substring of source, need to back up to
6192638Sstever@eecs.umich.edu                    # avoid empty string on RHS of arrow
6202638Sstever@eecs.umich.edu                    sep_idx = com_pfx.rfind(".")
6211869SN/A                    if sep_idx != -1:
6221869SN/A                        com_pfx = com_pfx[0:sep_idx]
6233546Sgblack@eecs.umich.edu                    else:
6243546Sgblack@eecs.umich.edu                        com_pfx = ''
6253546Sgblack@eecs.umich.edu                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
6263546Sgblack@eecs.umich.edu                    # still splitting at file extension: ok
6274202Sbinkertn@umich.edu                    pass
6283546Sgblack@eecs.umich.edu                else:
6293546Sgblack@eecs.umich.edu                    # probably a fluke; ignore it
6303546Sgblack@eecs.umich.edu                    com_pfx = ''
6313546Sgblack@eecs.umich.edu        # recalculate length in case com_pfx was modified
6323546Sgblack@eecs.umich.edu        com_pfx_len = len(com_pfx)
6334781Snate@binkert.org        def fmt(files):
6344781Snate@binkert.org            f = map(lambda s: s[com_pfx_len:], files)
6354781Snate@binkert.org            return ', '.join(f)
6364781Snate@binkert.org        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
6374781Snate@binkert.org
6384781Snate@binkert.orgExport('Transform')
6394781Snate@binkert.org
6404781Snate@binkert.org# enable the regression script to use the termcap
6414781Snate@binkert.orgmain['TERMCAP'] = termcap
6424781Snate@binkert.org
6434781Snate@binkert.orgif GetOption('verbose'):
6444781Snate@binkert.org    def MakeAction(action, string, *args, **kwargs):
6453546Sgblack@eecs.umich.edu        return Action(action, *args, **kwargs)
6463546Sgblack@eecs.umich.eduelse:
6473546Sgblack@eecs.umich.edu    MakeAction = Action
6484781Snate@binkert.org    main['CCCOMSTR']        = Transform("CC")
6493546Sgblack@eecs.umich.edu    main['CXXCOMSTR']       = Transform("CXX")
6503546Sgblack@eecs.umich.edu    main['ASCOMSTR']        = Transform("AS")
6513546Sgblack@eecs.umich.edu    main['ARCOMSTR']        = Transform("AR", 0)
6523546Sgblack@eecs.umich.edu    main['LINKCOMSTR']      = Transform("LINK", 0)
6533546Sgblack@eecs.umich.edu    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
6543546Sgblack@eecs.umich.edu    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
6553546Sgblack@eecs.umich.edu    main['M4COMSTR']        = Transform("M4")
6563546Sgblack@eecs.umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
6573546Sgblack@eecs.umich.edu    main['SHCXXCOMSTR']     = Transform("SHCXX")
6583546Sgblack@eecs.umich.eduExport('MakeAction')
6594202Sbinkertn@umich.edu
6603546Sgblack@eecs.umich.edu# Initialize the Link-Time Optimization (LTO) flags
6613546Sgblack@eecs.umich.edumain['LTO_CCFLAGS'] = []
6623546Sgblack@eecs.umich.edumain['LTO_LDFLAGS'] = []
663955SN/A
664955SN/A# According to the readme, tcmalloc works best if the compiler doesn't
665955SN/A# assume that we're using the builtin malloc and friends. These flags
666955SN/A# are compiler-specific, so we need to set them after we detect which
6671858SN/A# compiler we're using.
6681858SN/Amain['TCMALLOC_CCFLAGS'] = []
6691858SN/A
6702632Sstever@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
6712632Sstever@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
6724773Snate@binkert.org
6734773Snate@binkert.orgmain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
6742632Sstever@eecs.umich.edumain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
6752632Sstever@eecs.umich.eduif main['GCC'] + main['CLANG'] > 1:
6762632Sstever@eecs.umich.edu    print 'Error: How can we have two at the same time?'
6772634Sstever@eecs.umich.edu    Exit(1)
6782638Sstever@eecs.umich.edu
6792023SN/A# Set up default C++ compiler flags
6802632Sstever@eecs.umich.eduif main['GCC'] or main['CLANG']:
6812632Sstever@eecs.umich.edu    # As gcc and clang share many flags, do the common parts here
6822632Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-pipe'])
6832632Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-fno-strict-aliasing'])
6842632Sstever@eecs.umich.edu    # Enable -Wall and -Wextra and then disable the few warnings that
6853716Sstever@eecs.umich.edu    # we consistently violate
6862632Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
6872632Sstever@eecs.umich.edu                         '-Wno-sign-compare', '-Wno-unused-parameter'])
6882632Sstever@eecs.umich.edu    # We always compile using C++11
6892632Sstever@eecs.umich.edu    main.Append(CXXFLAGS=['-std=c++11'])
6902632Sstever@eecs.umich.edu    if sys.platform.startswith('freebsd'):
6912023SN/A        main.Append(CCFLAGS=['-I/usr/local/include'])
6922632Sstever@eecs.umich.edu        main.Append(CXXFLAGS=['-I/usr/local/include'])
6932632Sstever@eecs.umich.edu
6941889SN/A    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
6951889SN/A    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
6962632Sstever@eecs.umich.edu    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
6972632Sstever@eecs.umich.edu    shared_partial_flags = ['-r', '-nostdlib']
6982632Sstever@eecs.umich.edu    main.Append(PSHLINKFLAGS=shared_partial_flags)
6992632Sstever@eecs.umich.edu    main.Append(PLINKFLAGS=shared_partial_flags)
7003716Sstever@eecs.umich.eduelse:
7013716Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
7022632Sstever@eecs.umich.edu    print "Don't know what compiler options to use for your compiler."
7032632Sstever@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
7042632Sstever@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
7052632Sstever@eecs.umich.edu    if not CXX_version:
7062632Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
7072632Sstever@eecs.umich.edu               termcap.Normal
7082632Sstever@eecs.umich.edu    else:
7092632Sstever@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
7101888SN/A    print "       If you're trying to use a compiler other than GCC"
7111888SN/A    print "       or clang, there appears to be something wrong with your"
7121869SN/A    print "       environment."
7131869SN/A    print "       "
7141858SN/A    print "       If you are trying to use a compiler other than those listed"
7152598SN/A    print "       above you will need to ease fix SConstruct and "
7162598SN/A    print "       src/SConscript to support that compiler."
7172598SN/A    Exit(1)
7182598SN/A
7192598SN/Aif main['GCC']:
7201858SN/A    # Check for a supported version of gcc. >= 4.8 is chosen for its
7211858SN/A    # level of c++11 support. See
7221858SN/A    # http://gcc.gnu.org/projects/cxx0x.html for details.
7231858SN/A    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
7241858SN/A    if compareVersions(gcc_version, "4.8") < 0:
7251858SN/A        print 'Error: gcc version 4.8 or newer required.'
7261858SN/A        print '       Installed version:', gcc_version
7271858SN/A        Exit(1)
7281858SN/A
7291871SN/A    main['GCC_VERSION'] = gcc_version
7301858SN/A
7311858SN/A    if compareVersions(gcc_version, '4.9') >= 0:
7321858SN/A        # Incremental linking with LTO is currently broken in gcc versions
7331858SN/A        # 4.9 and above. A version where everything works completely hasn't
7341858SN/A        # yet been identified.
7351858SN/A        #
7361858SN/A        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
7371858SN/A        main['BROKEN_INCREMENTAL_LTO'] = True
7381858SN/A    if compareVersions(gcc_version, '6.0') >= 0:
7391858SN/A        # gcc versions 6.0 and greater accept an -flinker-output flag which
7401858SN/A        # selects what type of output the linker should generate. This is
7411859SN/A        # necessary for incremental lto to work, but is also broken in
7421859SN/A        # current versions of gcc. It may not be necessary in future
7431869SN/A        # versions. We add it here since it might be, and as a reminder that
7441888SN/A        # it exists. It's excluded if lto is being forced.
7452632Sstever@eecs.umich.edu        #
7461869SN/A        # https://gcc.gnu.org/gcc-6/changes.html
7471884SN/A        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
7481884SN/A        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
7491884SN/A        if not GetOption('force_lto'):
7501884SN/A            main.Append(PSHLINKFLAGS='-flinker-output=rel')
7511884SN/A            main.Append(PLINKFLAGS='-flinker-output=rel')
7521884SN/A
7531965SN/A    # gcc from version 4.8 and above generates "rep; ret" instructions
7541965SN/A    # to avoid performance penalties on certain AMD chips. Older
7551965SN/A    # assemblers detect this as an error, "Error: expecting string
7562761Sstever@eecs.umich.edu    # instruction after `rep'"
7571869SN/A    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
7581869SN/A                                  '-o', '/dev/null'],
7592632Sstever@eecs.umich.edu                                 exception=False).split()
7602667Sstever@eecs.umich.edu
7611869SN/A    # version strings may contain extra distro-specific
7621869SN/A    # qualifiers, so play it safe and keep only what comes before
7632929Sktlim@umich.edu    # the first hyphen
7642929Sktlim@umich.edu    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
7653716Sstever@eecs.umich.edu
7662929Sktlim@umich.edu    if not as_version or compareVersions(as_version, "2.23") < 0:
767955SN/A        print termcap.Yellow + termcap.Bold + \
7682598SN/A            'Warning: This combination of gcc and binutils have' + \
7692598SN/A            ' known incompatibilities.\n' + \
7703546Sgblack@eecs.umich.edu            '         If you encounter build problems, please update ' + \
771955SN/A            'binutils to 2.23.' + \
772955SN/A            termcap.Normal
773955SN/A
7741530SN/A    # Make sure we warn if the user has requested to compile with the
775955SN/A    # Undefined Benahvior Sanitizer and this version of gcc does not
776955SN/A    # support it.
777955SN/A    if GetOption('with_ubsan') and \
778            compareVersions(gcc_version, '4.9') < 0:
779        print termcap.Yellow + termcap.Bold + \
780            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
781            termcap.Normal
782
783    disable_lto = GetOption('no_lto')
784    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
785            not GetOption('force_lto'):
786        print termcap.Yellow + termcap.Bold + \
787            'Warning: Your compiler doesn\'t support incremental linking' + \
788            ' and lto at the same time, so lto is being disabled. To force' + \
789            ' lto on anyway, use the --force-lto option. That will disable' + \
790            ' partial linking.' + \
791            termcap.Normal
792        disable_lto = True
793
794    # Add the appropriate Link-Time Optimization (LTO) flags
795    # unless LTO is explicitly turned off. Note that these flags
796    # are only used by the fast target.
797    if not disable_lto:
798        # Pass the LTO flag when compiling to produce GIMPLE
799        # output, we merely create the flags here and only append
800        # them later
801        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
802
803        # Use the same amount of jobs for LTO as we are running
804        # scons with
805        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
806
807    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
808                                  '-fno-builtin-realloc', '-fno-builtin-free'])
809
810    # add option to check for undeclared overrides
811    if compareVersions(gcc_version, "5.0") > 0:
812        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
813
814elif main['CLANG']:
815    # Check for a supported version of clang, >= 3.1 is needed to
816    # support similar features as gcc 4.8. See
817    # http://clang.llvm.org/cxx_status.html for details
818    clang_version_re = re.compile(".* version (\d+\.\d+)")
819    clang_version_match = clang_version_re.search(CXX_version)
820    if (clang_version_match):
821        clang_version = clang_version_match.groups()[0]
822        if compareVersions(clang_version, "3.1") < 0:
823            print 'Error: clang version 3.1 or newer required.'
824            print '       Installed version:', clang_version
825            Exit(1)
826    else:
827        print 'Error: Unable to determine clang version.'
828        Exit(1)
829
830    # clang has a few additional warnings that we disable, extraneous
831    # parantheses are allowed due to Ruby's printing of the AST,
832    # finally self assignments are allowed as the generated CPU code
833    # is relying on this
834    main.Append(CCFLAGS=['-Wno-parentheses',
835                         '-Wno-self-assign',
836                         # Some versions of libstdc++ (4.8?) seem to
837                         # use struct hash and class hash
838                         # interchangeably.
839                         '-Wno-mismatched-tags',
840                         ])
841
842    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
843
844    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
845    # opposed to libstdc++, as the later is dated.
846    if sys.platform == "darwin":
847        main.Append(CXXFLAGS=['-stdlib=libc++'])
848        main.Append(LIBS=['c++'])
849
850    # On FreeBSD we need libthr.
851    if sys.platform.startswith('freebsd'):
852        main.Append(LIBS=['thr'])
853
854else:
855    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
856    print "Don't know what compiler options to use for your compiler."
857    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
858    print termcap.Yellow + '       version:' + termcap.Normal,
859    if not CXX_version:
860        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
861               termcap.Normal
862    else:
863        print CXX_version.replace('\n', '<nl>')
864    print "       If you're trying to use a compiler other than GCC"
865    print "       or clang, there appears to be something wrong with your"
866    print "       environment."
867    print "       "
868    print "       If you are trying to use a compiler other than those listed"
869    print "       above you will need to ease fix SConstruct and "
870    print "       src/SConscript to support that compiler."
871    Exit(1)
872
873# Set up common yacc/bison flags (needed for Ruby)
874main['YACCFLAGS'] = '-d'
875main['YACCHXXFILESUFFIX'] = '.hh'
876
877# Do this after we save setting back, or else we'll tack on an
878# extra 'qdo' every time we run scons.
879if main['BATCH']:
880    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
881    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
882    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
883    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
884    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
885
886if sys.platform == 'cygwin':
887    # cygwin has some header file issues...
888    main.Append(CCFLAGS=["-Wno-uninitialized"])
889
890# Check for the protobuf compiler
891protoc_version = readCommand([main['PROTOC'], '--version'],
892                             exception='').split()
893
894# First two words should be "libprotoc x.y.z"
895if len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
896    print termcap.Yellow + termcap.Bold + \
897        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
898        '         Please install protobuf-compiler for tracing support.' + \
899        termcap.Normal
900    main['PROTOC'] = False
901else:
902    # Based on the availability of the compress stream wrappers,
903    # require 2.1.0
904    min_protoc_version = '2.1.0'
905    if compareVersions(protoc_version[1], min_protoc_version) < 0:
906        print termcap.Yellow + termcap.Bold + \
907            'Warning: protoc version', min_protoc_version, \
908            'or newer required.\n' + \
909            '         Installed version:', protoc_version[1], \
910            termcap.Normal
911        main['PROTOC'] = False
912    else:
913        # Attempt to determine the appropriate include path and
914        # library path using pkg-config, that means we also need to
915        # check for pkg-config. Note that it is possible to use
916        # protobuf without the involvement of pkg-config. Later on we
917        # check go a library config check and at that point the test
918        # will fail if libprotobuf cannot be found.
919        if readCommand(['pkg-config', '--version'], exception=''):
920            try:
921                # Attempt to establish what linking flags to add for protobuf
922                # using pkg-config
923                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
924            except:
925                print termcap.Yellow + termcap.Bold + \
926                    'Warning: pkg-config could not get protobuf flags.' + \
927                    termcap.Normal
928
929
930# Check for 'timeout' from GNU coreutils. If present, regressions will
931# be run with a time limit. We require version 8.13 since we rely on
932# support for the '--foreground' option.
933if sys.platform.startswith('freebsd'):
934    timeout_lines = readCommand(['gtimeout', '--version'],
935                                exception='').splitlines()
936else:
937    timeout_lines = readCommand(['timeout', '--version'],
938                                exception='').splitlines()
939# Get the first line and tokenize it
940timeout_version = timeout_lines[0].split() if timeout_lines else []
941main['TIMEOUT'] =  timeout_version and \
942    compareVersions(timeout_version[-1], '8.13') >= 0
943
944# Add a custom Check function to test for structure members.
945def CheckMember(context, include, decl, member, include_quotes="<>"):
946    context.Message("Checking for member %s in %s..." %
947                    (member, decl))
948    text = """
949#include %(header)s
950int main(){
951  %(decl)s test;
952  (void)test.%(member)s;
953  return 0;
954};
955""" % { "header" : include_quotes[0] + include + include_quotes[1],
956        "decl" : decl,
957        "member" : member,
958        }
959
960    ret = context.TryCompile(text, extension=".cc")
961    context.Result(ret)
962    return ret
963
964# Platform-specific configuration.  Note again that we assume that all
965# builds under a given build root run on the same host platform.
966conf = Configure(main,
967                 conf_dir = joinpath(build_root, '.scons_config'),
968                 log_file = joinpath(build_root, 'scons_config.log'),
969                 custom_tests = {
970        'CheckMember' : CheckMember,
971        })
972
973# Check if we should compile a 64 bit binary on Mac OS X/Darwin
974try:
975    import platform
976    uname = platform.uname()
977    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
978        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
979            main.Append(CCFLAGS=['-arch', 'x86_64'])
980            main.Append(CFLAGS=['-arch', 'x86_64'])
981            main.Append(LINKFLAGS=['-arch', 'x86_64'])
982            main.Append(ASFLAGS=['-arch', 'x86_64'])
983except:
984    pass
985
986# Recent versions of scons substitute a "Null" object for Configure()
987# when configuration isn't necessary, e.g., if the "--help" option is
988# present.  Unfortuantely this Null object always returns false,
989# breaking all our configuration checks.  We replace it with our own
990# more optimistic null object that returns True instead.
991if not conf:
992    def NullCheck(*args, **kwargs):
993        return True
994
995    class NullConf:
996        def __init__(self, env):
997            self.env = env
998        def Finish(self):
999            return self.env
1000        def __getattr__(self, mname):
1001            return NullCheck
1002
1003    conf = NullConf(main)
1004
1005# Cache build files in the supplied directory.
1006if main['M5_BUILD_CACHE']:
1007    print 'Using build cache located at', main['M5_BUILD_CACHE']
1008    CacheDir(main['M5_BUILD_CACHE'])
1009
1010main['USE_PYTHON'] = not GetOption('without_python')
1011if main['USE_PYTHON']:
1012    # Find Python include and library directories for embedding the
1013    # interpreter. We rely on python-config to resolve the appropriate
1014    # includes and linker flags. ParseConfig does not seem to understand
1015    # the more exotic linker flags such as -Xlinker and -export-dynamic so
1016    # we add them explicitly below. If you want to link in an alternate
1017    # version of python, see above for instructions on how to invoke
1018    # scons with the appropriate PATH set.
1019    #
1020    # First we check if python2-config exists, else we use python-config
1021    python_config = readCommand(['which', 'python2-config'],
1022                                exception='').strip()
1023    if not os.path.exists(python_config):
1024        python_config = readCommand(['which', 'python-config'],
1025                                    exception='').strip()
1026    py_includes = readCommand([python_config, '--includes'],
1027                              exception='').split()
1028    # Strip the -I from the include folders before adding them to the
1029    # CPPPATH
1030    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
1031
1032    # Read the linker flags and split them into libraries and other link
1033    # flags. The libraries are added later through the call the CheckLib.
1034    py_ld_flags = readCommand([python_config, '--ldflags'],
1035        exception='').split()
1036    py_libs = []
1037    for lib in py_ld_flags:
1038         if not lib.startswith('-l'):
1039             main.Append(LINKFLAGS=[lib])
1040         else:
1041             lib = lib[2:]
1042             if lib not in py_libs:
1043                 py_libs.append(lib)
1044
1045    # verify that this stuff works
1046    if not conf.CheckHeader('Python.h', '<>'):
1047        print "Error: can't find Python.h header in", py_includes
1048        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
1049        Exit(1)
1050
1051    for lib in py_libs:
1052        if not conf.CheckLib(lib):
1053            print "Error: can't find library %s required by python" % lib
1054            Exit(1)
1055
1056# On Solaris you need to use libsocket for socket ops
1057if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
1058   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
1059       print "Can't find library with socket calls (e.g. accept())"
1060       Exit(1)
1061
1062# Check for zlib.  If the check passes, libz will be automatically
1063# added to the LIBS environment variable.
1064if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
1065    print 'Error: did not find needed zlib compression library '\
1066          'and/or zlib.h header file.'
1067    print '       Please install zlib and try again.'
1068    Exit(1)
1069
1070# If we have the protobuf compiler, also make sure we have the
1071# development libraries. If the check passes, libprotobuf will be
1072# automatically added to the LIBS environment variable. After
1073# this, we can use the HAVE_PROTOBUF flag to determine if we have
1074# got both protoc and libprotobuf available.
1075main['HAVE_PROTOBUF'] = main['PROTOC'] and \
1076    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
1077                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
1078
1079# If we have the compiler but not the library, print another warning.
1080if main['PROTOC'] and not main['HAVE_PROTOBUF']:
1081    print termcap.Yellow + termcap.Bold + \
1082        'Warning: did not find protocol buffer library and/or headers.\n' + \
1083    '       Please install libprotobuf-dev for tracing support.' + \
1084    termcap.Normal
1085
1086# Check for librt.
1087have_posix_clock = \
1088    conf.CheckLibWithHeader(None, 'time.h', 'C',
1089                            'clock_nanosleep(0,0,NULL,NULL);') or \
1090    conf.CheckLibWithHeader('rt', 'time.h', 'C',
1091                            'clock_nanosleep(0,0,NULL,NULL);')
1092
1093have_posix_timers = \
1094    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
1095                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
1096
1097if not GetOption('without_tcmalloc'):
1098    if conf.CheckLib('tcmalloc'):
1099        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
1100    elif conf.CheckLib('tcmalloc_minimal'):
1101        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
1102    else:
1103        print termcap.Yellow + termcap.Bold + \
1104              "You can get a 12% performance improvement by "\
1105              "installing tcmalloc (libgoogle-perftools-dev package "\
1106              "on Ubuntu or RedHat)." + termcap.Normal
1107
1108
1109# Detect back trace implementations. The last implementation in the
1110# list will be used by default.
1111backtrace_impls = [ "none" ]
1112
1113if conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
1114                           'backtrace_symbols_fd((void*)0, 0, 0);'):
1115    backtrace_impls.append("glibc")
1116elif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
1117                           'backtrace_symbols_fd((void*)0, 0, 0);'):
1118    # NetBSD and FreeBSD need libexecinfo.
1119    backtrace_impls.append("glibc")
1120    main.Append(LIBS=['execinfo'])
1121
1122if backtrace_impls[-1] == "none":
1123    default_backtrace_impl = "none"
1124    print termcap.Yellow + termcap.Bold + \
1125        "No suitable back trace implementation found." + \
1126        termcap.Normal
1127
1128if not have_posix_clock:
1129    print "Can't find library for POSIX clocks."
1130
1131# Check for <fenv.h> (C99 FP environment control)
1132have_fenv = conf.CheckHeader('fenv.h', '<>')
1133if not have_fenv:
1134    print "Warning: Header file <fenv.h> not found."
1135    print "         This host has no IEEE FP rounding mode control."
1136
1137# Check if we should enable KVM-based hardware virtualization. The API
1138# we rely on exists since version 2.6.36 of the kernel, but somehow
1139# the KVM_API_VERSION does not reflect the change. We test for one of
1140# the types as a fall back.
1141have_kvm = conf.CheckHeader('linux/kvm.h', '<>')
1142if not have_kvm:
1143    print "Info: Compatible header file <linux/kvm.h> not found, " \
1144        "disabling KVM support."
1145
1146# Check if the TUN/TAP driver is available.
1147have_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
1148if not have_tuntap:
1149    print "Info: Compatible header file <linux/if_tun.h> not found."
1150
1151# x86 needs support for xsave. We test for the structure here since we
1152# won't be able to run new tests by the time we know which ISA we're
1153# targeting.
1154have_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
1155                                    '#include <linux/kvm.h>') != 0
1156
1157# Check if the requested target ISA is compatible with the host
1158def is_isa_kvm_compatible(isa):
1159    try:
1160        import platform
1161        host_isa = platform.machine()
1162    except:
1163        print "Warning: Failed to determine host ISA."
1164        return False
1165
1166    if not have_posix_timers:
1167        print "Warning: Can not enable KVM, host seems to lack support " \
1168            "for POSIX timers"
1169        return False
1170
1171    if isa == "arm":
1172        return host_isa in ( "armv7l", "aarch64" )
1173    elif isa == "x86":
1174        if host_isa != "x86_64":
1175            return False
1176
1177        if not have_kvm_xsave:
1178            print "KVM on x86 requires xsave support in kernel headers."
1179            return False
1180
1181        return True
1182    else:
1183        return False
1184
1185
1186# Check if the exclude_host attribute is available. We want this to
1187# get accurate instruction counts in KVM.
1188main['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
1189    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
1190
1191
1192######################################################################
1193#
1194# Finish the configuration
1195#
1196main = conf.Finish()
1197
1198######################################################################
1199#
1200# Collect all non-global variables
1201#
1202
1203# Define the universe of supported ISAs
1204all_isa_list = [ ]
1205all_gpu_isa_list = [ ]
1206Export('all_isa_list')
1207Export('all_gpu_isa_list')
1208
1209class CpuModel(object):
1210    '''The CpuModel class encapsulates everything the ISA parser needs to
1211    know about a particular CPU model.'''
1212
1213    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
1214    dict = {}
1215
1216    # Constructor.  Automatically adds models to CpuModel.dict.
1217    def __init__(self, name, default=False):
1218        self.name = name           # name of model
1219
1220        # This cpu is enabled by default
1221        self.default = default
1222
1223        # Add self to dict
1224        if name in CpuModel.dict:
1225            raise AttributeError, "CpuModel '%s' already registered" % name
1226        CpuModel.dict[name] = self
1227
1228Export('CpuModel')
1229
1230# Sticky variables get saved in the variables file so they persist from
1231# one invocation to the next (unless overridden, in which case the new
1232# value becomes sticky).
1233sticky_vars = Variables(args=ARGUMENTS)
1234Export('sticky_vars')
1235
1236# Sticky variables that should be exported
1237export_vars = []
1238Export('export_vars')
1239
1240# For Ruby
1241all_protocols = []
1242Export('all_protocols')
1243protocol_dirs = []
1244Export('protocol_dirs')
1245slicc_includes = []
1246Export('slicc_includes')
1247
1248# Walk the tree and execute all SConsopts scripts that wil add to the
1249# above variables
1250if GetOption('verbose'):
1251    print "Reading SConsopts"
1252for bdir in [ base_dir ] + extras_dir_list:
1253    if not isdir(bdir):
1254        print "Error: directory '%s' does not exist" % bdir
1255        Exit(1)
1256    for root, dirs, files in os.walk(bdir):
1257        if 'SConsopts' in files:
1258            if GetOption('verbose'):
1259                print "Reading", joinpath(root, 'SConsopts')
1260            SConscript(joinpath(root, 'SConsopts'))
1261
1262all_isa_list.sort()
1263all_gpu_isa_list.sort()
1264
1265sticky_vars.AddVariables(
1266    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
1267    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
1268    ListVariable('CPU_MODELS', 'CPU models',
1269                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
1270                 sorted(CpuModel.dict.keys())),
1271    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
1272                 False),
1273    BoolVariable('SS_COMPATIBLE_FP',
1274                 'Make floating-point results compatible with SimpleScalar',
1275                 False),
1276    BoolVariable('USE_SSE2',
1277                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
1278                 False),
1279    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1280    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
1281    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
1282    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
1283    BoolVariable('USE_TUNTAP',
1284                 'Enable using a tap device to bridge to the host network',
1285                 have_tuntap),
1286    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
1287    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1288                  all_protocols),
1289    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
1290                 backtrace_impls[-1], backtrace_impls)
1291    )
1292
1293# These variables get exported to #defines in config/*.hh (see src/SConscript).
1294export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
1295                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
1296                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
1297
1298###################################################
1299#
1300# Define a SCons builder for configuration flag headers.
1301#
1302###################################################
1303
1304# This function generates a config header file that #defines the
1305# variable symbol to the current variable setting (0 or 1).  The source
1306# operands are the name of the variable and a Value node containing the
1307# value of the variable.
1308def build_config_file(target, source, env):
1309    (variable, value) = [s.get_contents() for s in source]
1310    f = file(str(target[0]), 'w')
1311    print >> f, '#define', variable, value
1312    f.close()
1313    return None
1314
1315# Combine the two functions into a scons Action object.
1316config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1317
1318# The emitter munges the source & target node lists to reflect what
1319# we're really doing.
1320def config_emitter(target, source, env):
1321    # extract variable name from Builder arg
1322    variable = str(target[0])
1323    # True target is config header file
1324    target = joinpath('config', variable.lower() + '.hh')
1325    val = env[variable]
1326    if isinstance(val, bool):
1327        # Force value to 0/1
1328        val = int(val)
1329    elif isinstance(val, str):
1330        val = '"' + val + '"'
1331
1332    # Sources are variable name & value (packaged in SCons Value nodes)
1333    return ([target], [Value(variable), Value(val)])
1334
1335config_builder = Builder(emitter = config_emitter, action = config_action)
1336
1337main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1338
1339###################################################
1340#
1341# Builders for static and shared partially linked object files.
1342#
1343###################################################
1344
1345partial_static_builder = Builder(action=SCons.Defaults.LinkAction,
1346                                 src_suffix='$OBJSUFFIX',
1347                                 src_builder=['StaticObject', 'Object'],
1348                                 LINKFLAGS='$PLINKFLAGS',
1349                                 LIBS='')
1350
1351def partial_shared_emitter(target, source, env):
1352    for tgt in target:
1353        tgt.attributes.shared = 1
1354    return (target, source)
1355partial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
1356                                 emitter=partial_shared_emitter,
1357                                 src_suffix='$SHOBJSUFFIX',
1358                                 src_builder='SharedObject',
1359                                 SHLINKFLAGS='$PSHLINKFLAGS',
1360                                 LIBS='')
1361
1362main.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
1363                         'PartialStatic' : partial_static_builder })
1364
1365# builds in ext are shared across all configs in the build root.
1366ext_dir = abspath(joinpath(str(main.root), 'ext'))
1367ext_build_dirs = []
1368for root, dirs, files in os.walk(ext_dir):
1369    if 'SConscript' in files:
1370        build_dir = os.path.relpath(root, ext_dir)
1371        ext_build_dirs.append(build_dir)
1372        main.SConscript(joinpath(root, 'SConscript'),
1373                        variant_dir=joinpath(build_root, build_dir))
1374
1375main.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
1376
1377###################################################
1378#
1379# This builder and wrapper method are used to set up a directory with
1380# switching headers. Those are headers which are in a generic location and
1381# that include more specific headers from a directory chosen at build time
1382# based on the current build settings.
1383#
1384###################################################
1385
1386def build_switching_header(target, source, env):
1387    path = str(target[0])
1388    subdir = str(source[0])
1389    dp, fp = os.path.split(path)
1390    dp = os.path.relpath(os.path.realpath(dp),
1391                         os.path.realpath(env['BUILDDIR']))
1392    with open(path, 'w') as hdr:
1393        print >>hdr, '#include "%s/%s/%s"' % (dp, subdir, fp)
1394
1395switching_header_action = MakeAction(build_switching_header,
1396                                     Transform('GENERATE'))
1397
1398switching_header_builder = Builder(action=switching_header_action,
1399                                   source_factory=Value,
1400                                   single_source=True)
1401
1402main.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
1403
1404def switching_headers(self, headers, source):
1405    for header in headers:
1406        self.SwitchingHeader(header, source)
1407
1408main.AddMethod(switching_headers, 'SwitchingHeaders')
1409
1410# all-isas -> all-deps -> all-environs -> all_targets
1411main.Alias('#all-isas', [])
1412main.Alias('#all-deps', '#all-isas')
1413
1414# Dummy target to ensure all environments are created before telling
1415# SCons what to actually make (the command line arguments).  We attach
1416# them to the dependence graph after the environments are complete.
1417ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1418def environsComplete(target, source, env):
1419    for t in ORIG_BUILD_TARGETS:
1420        main.Depends('#all-targets', t)
1421
1422# Each build/* switching_dir attaches its *-environs target to #all-environs.
1423main.Append(BUILDERS = {'CompleteEnvirons' :
1424                        Builder(action=MakeAction(environsComplete, None))})
1425main.CompleteEnvirons('#all-environs', [])
1426
1427def doNothing(**ignored): pass
1428main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1429
1430# The final target to which all the original targets ultimately get attached.
1431main.Dummy('#all-targets', '#all-environs')
1432BUILD_TARGETS[:] = ['#all-targets']
1433
1434###################################################
1435#
1436# Define build environments for selected configurations.
1437#
1438###################################################
1439
1440def variant_name(path):
1441    return os.path.basename(path).lower().replace('_', '-')
1442main['variant_name'] = variant_name
1443main['VARIANT_NAME'] = '${variant_name(BUILDDIR)}'
1444
1445for variant_path in variant_paths:
1446    if not GetOption('silent'):
1447        print "Building in", variant_path
1448
1449    # Make a copy of the build-root environment to use for this config.
1450    env = main.Clone()
1451    env['BUILDDIR'] = variant_path
1452
1453    # variant_dir is the tail component of build path, and is used to
1454    # determine the build parameters (e.g., 'ALPHA_SE')
1455    (build_root, variant_dir) = splitpath(variant_path)
1456
1457    # Set env variables according to the build directory config.
1458    sticky_vars.files = []
1459    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1460    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1461    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1462    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1463    if isfile(current_vars_file):
1464        sticky_vars.files.append(current_vars_file)
1465        if not GetOption('silent'):
1466            print "Using saved variables file %s" % current_vars_file
1467    elif variant_dir in ext_build_dirs:
1468        # Things in ext are built without a variant directory.
1469        continue
1470    else:
1471        # Build dir-specific variables file doesn't exist.
1472
1473        # Make sure the directory is there so we can create it later
1474        opt_dir = dirname(current_vars_file)
1475        if not isdir(opt_dir):
1476            mkdir(opt_dir)
1477
1478        # Get default build variables from source tree.  Variables are
1479        # normally determined by name of $VARIANT_DIR, but can be
1480        # overridden by '--default=' arg on command line.
1481        default = GetOption('default')
1482        opts_dir = joinpath(main.root.abspath, 'build_opts')
1483        if default:
1484            default_vars_files = [joinpath(build_root, 'variables', default),
1485                                  joinpath(opts_dir, default)]
1486        else:
1487            default_vars_files = [joinpath(opts_dir, variant_dir)]
1488        existing_files = filter(isfile, default_vars_files)
1489        if existing_files:
1490            default_vars_file = existing_files[0]
1491            sticky_vars.files.append(default_vars_file)
1492            print "Variables file %s not found,\n  using defaults in %s" \
1493                  % (current_vars_file, default_vars_file)
1494        else:
1495            print "Error: cannot find variables file %s or " \
1496                  "default file(s) %s" \
1497                  % (current_vars_file, ' or '.join(default_vars_files))
1498            Exit(1)
1499
1500    # Apply current variable settings to env
1501    sticky_vars.Update(env)
1502
1503    help_texts["local_vars"] += \
1504        "Build variables for %s:\n" % variant_dir \
1505                 + sticky_vars.GenerateHelpText(env)
1506
1507    # Process variable settings.
1508
1509    if not have_fenv and env['USE_FENV']:
1510        print "Warning: <fenv.h> not available; " \
1511              "forcing USE_FENV to False in", variant_dir + "."
1512        env['USE_FENV'] = False
1513
1514    if not env['USE_FENV']:
1515        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1516        print "         FP results may deviate slightly from other platforms."
1517
1518    if env['EFENCE']:
1519        env.Append(LIBS=['efence'])
1520
1521    if env['USE_KVM']:
1522        if not have_kvm:
1523            print "Warning: Can not enable KVM, host seems to lack KVM support"
1524            env['USE_KVM'] = False
1525        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1526            print "Info: KVM support disabled due to unsupported host and " \
1527                "target ISA combination"
1528            env['USE_KVM'] = False
1529
1530    if env['USE_TUNTAP']:
1531        if not have_tuntap:
1532            print "Warning: Can't connect EtherTap with a tap device."
1533            env['USE_TUNTAP'] = False
1534
1535    if env['BUILD_GPU']:
1536        env.Append(CPPDEFINES=['BUILD_GPU'])
1537
1538    # Warn about missing optional functionality
1539    if env['USE_KVM']:
1540        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1541            print "Warning: perf_event headers lack support for the " \
1542                "exclude_host attribute. KVM instruction counts will " \
1543                "be inaccurate."
1544
1545    # Save sticky variable settings back to current variables file
1546    sticky_vars.Save(current_vars_file, env)
1547
1548    if env['USE_SSE2']:
1549        env.Append(CCFLAGS=['-msse2'])
1550
1551    # The src/SConscript file sets up the build rules in 'env' according
1552    # to the configured variables.  It returns a list of environments,
1553    # one for each variant build (debug, opt, etc.)
1554    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1555
1556def pairwise(iterable):
1557    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1558    a, b = itertools.tee(iterable)
1559    b.next()
1560    return itertools.izip(a, b)
1561
1562variant_names = [variant_name(path) for path in variant_paths]
1563
1564# Create false dependencies so SCons will parse ISAs, establish
1565# dependencies, and setup the build Environments serially. Either
1566# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1567# greater than 1. It appears to be standard race condition stuff; it
1568# doesn't always fail, but usually, and the behaviors are different.
1569# Every time I tried to remove this, builds would fail in some
1570# creative new way. So, don't do that. You'll want to, though, because
1571# tests/SConscript takes a long time to make its Environments.
1572for t1, t2 in pairwise(sorted(variant_names)):
1573    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1574    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1575
1576# base help text
1577Help('''
1578Usage: scons [scons options] [build variables] [target(s)]
1579
1580Extra scons options:
1581%(options)s
1582
1583Global build variables:
1584%(global_vars)s
1585
1586%(local_vars)s
1587''' % help_texts)
1588