SConstruct revision 11497:bfed9fdf0ac7
1955SN/A# -*- mode:python -*-
2955SN/A
313576Sciro.santilli@arm.com# Copyright (c) 2013, 2015, 2016 ARM Limited
413576Sciro.santilli@arm.com# All rights reserved.
513576Sciro.santilli@arm.com#
613576Sciro.santilli@arm.com# The license below extends only to copyright in the software and shall
713576Sciro.santilli@arm.com# not be construed as granting a license to any other intellectual
813576Sciro.santilli@arm.com# property including but not limited to intellectual property relating
913576Sciro.santilli@arm.com# to a hardware implementation of the functionality of the software
1013576Sciro.santilli@arm.com# licensed hereunder.  You may use the software subject to the license
1113576Sciro.santilli@arm.com# terms below provided that you ensure that this notice is replicated
1213576Sciro.santilli@arm.com# unmodified and in its entirety in all distributions of the software,
1313576Sciro.santilli@arm.com# modified or unmodified, in source code or in binary form.
141762SN/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
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
392665Ssaidi@eecs.umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
404762Snate@binkert.org# (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.
4212563Sgabeblack@google.com#
4312563Sgabeblack@google.com# Authors: Steve Reinhardt
445522Snate@binkert.org#          Nathan Binkert
456143Snate@binkert.org
4612371Sgabeblack@google.com###################################################
474762Snate@binkert.org#
485522Snate@binkert.org# SCons top-level build description (SConstruct) file.
49955SN/A#
505522Snate@binkert.org# While in this directory ('gem5'), just type 'scons' to build the default
5111974Sgabeblack@google.com# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
52955SN/A# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
535522Snate@binkert.org# the optimized full-system version).
544202Sbinkertn@umich.edu#
555742Snate@binkert.org# You can build gem5 in a different directory as long as there is a
56955SN/A# 'build/<CONFIG>' somewhere along the target path.  The build system
574381Sbinkertn@umich.edu# expects that all configs under the same build directory are being
584381Sbinkertn@umich.edu# built for the same host system.
5912246Sgabeblack@google.com#
6012246Sgabeblack@google.com# Examples:
618334Snate@binkert.org#
62955SN/A#   The following two commands are equivalent.  The '-u' option tells
63955SN/A#   scons to search up the directory tree for this SConstruct file.
644202Sbinkertn@umich.edu#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
65955SN/A#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
664382Sbinkertn@umich.edu#
674382Sbinkertn@umich.edu#   The following two commands are equivalent and demonstrate building
684382Sbinkertn@umich.edu#   in a directory outside of the source tree.  The '-C' option tells
696654Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
705517Snate@binkert.org#   file.
718614Sgblack@eecs.umich.edu#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
727674Snate@binkert.org#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
736143Snate@binkert.org#
746143Snate@binkert.org# You can use 'scons -H' to print scons options.  If you're in this
756143Snate@binkert.org# 'gem5' directory (or use -u or -C to tell scons where to find this
7612302Sgabeblack@google.com# file), you can use 'scons -h' to print all the gem5-specific build
7712302Sgabeblack@google.com# options as well.
7812302Sgabeblack@google.com#
7912371Sgabeblack@google.com###################################################
8012371Sgabeblack@google.com
8112371Sgabeblack@google.com# Check for recent-enough Python and SCons versions.
8212371Sgabeblack@google.comtry:
8312371Sgabeblack@google.com    # Really old versions of scons only take two options for the
8412371Sgabeblack@google.com    # function, so check once without the revision and once with the
8512371Sgabeblack@google.com    # revision, the first instance will fail for stuff other than
8612371Sgabeblack@google.com    # 0.98, and the second will fail for 0.98.0
8712371Sgabeblack@google.com    EnsureSConsVersion(0, 98)
8812371Sgabeblack@google.com    EnsureSConsVersion(0, 98, 1)
8912371Sgabeblack@google.comexcept SystemExit, e:
9012371Sgabeblack@google.com    print """
9112371Sgabeblack@google.comFor more details, see:
9212371Sgabeblack@google.com    http://gem5.org/Dependencies
9312371Sgabeblack@google.com"""
9412371Sgabeblack@google.com    raise
9512371Sgabeblack@google.com
9612371Sgabeblack@google.com# We ensure the python version early because because python-config
9712371Sgabeblack@google.com# requires python 2.5
9812371Sgabeblack@google.comtry:
9912371Sgabeblack@google.com    EnsurePythonVersion(2, 5)
10012371Sgabeblack@google.comexcept SystemExit, e:
10112371Sgabeblack@google.com    print """
10212371Sgabeblack@google.comYou can use a non-default installation of the Python interpreter by
10312371Sgabeblack@google.comrearranging your PATH so that scons finds the non-default 'python' and
10412371Sgabeblack@google.com'python-config' first.
10512371Sgabeblack@google.com
10612371Sgabeblack@google.comFor more details, see:
10712371Sgabeblack@google.com    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
10812371Sgabeblack@google.com"""
10912371Sgabeblack@google.com    raise
11012371Sgabeblack@google.com
11112371Sgabeblack@google.com# Global Python includes
11212371Sgabeblack@google.comimport itertools
11312371Sgabeblack@google.comimport os
11412371Sgabeblack@google.comimport re
11512371Sgabeblack@google.comimport shutil
11612371Sgabeblack@google.comimport subprocess
11712371Sgabeblack@google.comimport sys
11812371Sgabeblack@google.com
11912371Sgabeblack@google.comfrom os import mkdir, environ
12012371Sgabeblack@google.comfrom os.path import abspath, basename, dirname, expanduser, normpath
12112371Sgabeblack@google.comfrom os.path import exists,  isdir, isfile
12212371Sgabeblack@google.comfrom os.path import join as joinpath, split as splitpath
12312371Sgabeblack@google.com
12412371Sgabeblack@google.com# SCons includes
12512371Sgabeblack@google.comimport SCons
12612302Sgabeblack@google.comimport SCons.Node
12712371Sgabeblack@google.com
12812302Sgabeblack@google.comextra_python_paths = [
12912371Sgabeblack@google.com    Dir('src/python').srcnode().abspath, # gem5 includes
13012302Sgabeblack@google.com    Dir('ext/ply').srcnode().abspath, # ply is used by several files
13112302Sgabeblack@google.com    ]
13212371Sgabeblack@google.com
13312371Sgabeblack@google.comsys.path[1:1] = extra_python_paths
13412371Sgabeblack@google.com
13512371Sgabeblack@google.comfrom m5.util import compareVersions, readCommand
13612302Sgabeblack@google.comfrom m5.util.terminal import get_termcap
13712371Sgabeblack@google.com
13812371Sgabeblack@google.comhelp_texts = {
13912371Sgabeblack@google.com    "options" : "",
14012371Sgabeblack@google.com    "global_vars" : "",
14111983Sgabeblack@google.com    "local_vars" : ""
1426143Snate@binkert.org}
1438233Snate@binkert.org
14412302Sgabeblack@google.comExport("help_texts")
1456143Snate@binkert.org
1466143Snate@binkert.org
14712302Sgabeblack@google.com# There's a bug in scons in that (1) by default, the help texts from
1484762Snate@binkert.org# AddOption() are supposed to be displayed when you type 'scons -h'
1496143Snate@binkert.org# and (2) you can override the help displayed by 'scons -h' using the
1508233Snate@binkert.org# Help() function, but these two features are incompatible: once
1518233Snate@binkert.org# you've overridden the help text using Help(), there's no way to get
15212302Sgabeblack@google.com# at the help texts from AddOptions.  See:
15312302Sgabeblack@google.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1546143Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
15512362Sgabeblack@google.com# This hack lets us extract the help text from AddOptions and
15612362Sgabeblack@google.com# re-inject it via Help().  Ideally someday this bug will be fixed and
15712362Sgabeblack@google.com# we can just use AddOption directly.
15812362Sgabeblack@google.comdef AddLocalOption(*args, **kwargs):
15912302Sgabeblack@google.com    col_width = 30
16012302Sgabeblack@google.com
16112302Sgabeblack@google.com    help = "  " + ", ".join(args)
16212302Sgabeblack@google.com    if "help" in kwargs:
16312302Sgabeblack@google.com        length = len(help)
16412363Sgabeblack@google.com        if length >= col_width:
16512363Sgabeblack@google.com            help += "\n" + " " * col_width
16612363Sgabeblack@google.com        else:
16712363Sgabeblack@google.com            help += " " * (col_width - length)
16812302Sgabeblack@google.com        help += kwargs["help"]
16912363Sgabeblack@google.com    help_texts["options"] += help + "\n"
17012363Sgabeblack@google.com
17112363Sgabeblack@google.com    AddOption(*args, **kwargs)
17212363Sgabeblack@google.com
17312363Sgabeblack@google.comAddLocalOption('--colors', dest='use_colors', action='store_true',
1748233Snate@binkert.org               help="Add color to abbreviated scons output")
1756143Snate@binkert.orgAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1766143Snate@binkert.org               help="Don't add color to abbreviated scons output")
1776143Snate@binkert.orgAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1786143Snate@binkert.org               action='store_true',
1796143Snate@binkert.org               help="Build with support for C++-based configuration")
1806143Snate@binkert.orgAddLocalOption('--default', dest='default', type='string', action='store',
1816143Snate@binkert.org               help='Override which build_opts file to use for defaults')
1826143Snate@binkert.orgAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1836143Snate@binkert.org               help='Disable style checking hooks')
1847065Snate@binkert.orgAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1856143Snate@binkert.org               help='Disable Link-Time Optimization for fast')
18612362Sgabeblack@google.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
18712362Sgabeblack@google.com               help='Update test reference outputs')
18812362Sgabeblack@google.comAddLocalOption('--verbose', dest='verbose', action='store_true',
18912362Sgabeblack@google.com               help='Print full tool command lines')
19012362Sgabeblack@google.comAddLocalOption('--without-python', dest='without_python',
19112362Sgabeblack@google.com               action='store_true',
19212362Sgabeblack@google.com               help='Build without Python configuration support')
19312362Sgabeblack@google.comAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
19412362Sgabeblack@google.com               action='store_true',
19512362Sgabeblack@google.com               help='Disable linking against tcmalloc')
19612362Sgabeblack@google.comAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
19712362Sgabeblack@google.com               help='Build with Undefined Behavior Sanitizer if available')
1988233Snate@binkert.orgAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1998233Snate@binkert.org               help='Build with Address Sanitizer if available')
2008233Snate@binkert.org
2018233Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
2028233Snate@binkert.org
2038233Snate@binkert.org########################################################################
2048233Snate@binkert.org#
2058233Snate@binkert.org# Set up the main build environment.
2068233Snate@binkert.org#
2078233Snate@binkert.org########################################################################
2088233Snate@binkert.org
2098233Snate@binkert.org# export TERM so that clang reports errors in color
2108233Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2118233Snate@binkert.org                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2128233Snate@binkert.org                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
2138233Snate@binkert.org
2148233Snate@binkert.orguse_prefixes = [
2158233Snate@binkert.org    "ASAN_",           # address sanitizer symbolizer path and settings
2168233Snate@binkert.org    "CCACHE_",         # ccache (caching compiler wrapper) configuration
2178233Snate@binkert.org    "CCC_",            # clang static analyzer configuration
2188233Snate@binkert.org    "DISTCC_",         # distcc (distributed compiler wrapper) configuration
2196143Snate@binkert.org    "INCLUDE_SERVER_", # distcc pump server settings
2206143Snate@binkert.org    "M5",              # M5 configuration (e.g., path to kernels)
2216143Snate@binkert.org    ]
2226143Snate@binkert.org
2236143Snate@binkert.orguse_env = {}
2246143Snate@binkert.orgfor key,val in sorted(os.environ.iteritems()):
2259982Satgutier@umich.edu    if key in use_vars or \
22613576Sciro.santilli@arm.com            any([key.startswith(prefix) for prefix in use_prefixes]):
22713576Sciro.santilli@arm.com        use_env[key] = val
22813576Sciro.santilli@arm.com
22913576Sciro.santilli@arm.com# Tell scons to avoid implicit command dependencies to avoid issues
23013576Sciro.santilli@arm.com# with the param wrappes being compiled twice (see
23113576Sciro.santilli@arm.com# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
23213576Sciro.santilli@arm.commain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
23313576Sciro.santilli@arm.commain.Decider('MD5-timestamp')
23413576Sciro.santilli@arm.commain.root = Dir(".")         # The current directory (where this file lives).
23513576Sciro.santilli@arm.commain.srcdir = Dir("src")     # The source directory
23613576Sciro.santilli@arm.com
23713576Sciro.santilli@arm.commain_dict_keys = main.Dictionary().keys()
23813576Sciro.santilli@arm.com
23913576Sciro.santilli@arm.com# Check that we have a C/C++ compiler
24013576Sciro.santilli@arm.comif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
24113576Sciro.santilli@arm.com    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
24213576Sciro.santilli@arm.com    Exit(1)
24313576Sciro.santilli@arm.com
24413576Sciro.santilli@arm.com# Check that swig is present
24513576Sciro.santilli@arm.comif not 'SWIG' in main_dict_keys:
24613576Sciro.santilli@arm.com    print "swig is not installed (package swig on Ubuntu and RedHat)"
24713576Sciro.santilli@arm.com    Exit(1)
24813576Sciro.santilli@arm.com
24913576Sciro.santilli@arm.com# add useful python code PYTHONPATH so it can be used by subprocesses
25013576Sciro.santilli@arm.com# as well
25113576Sciro.santilli@arm.commain.AppendENVPath('PYTHONPATH', extra_python_paths)
25213576Sciro.santilli@arm.com
25313576Sciro.santilli@arm.com########################################################################
25413576Sciro.santilli@arm.com#
25513576Sciro.santilli@arm.com# Mercurial Stuff.
25613576Sciro.santilli@arm.com#
25713576Sciro.santilli@arm.com# If the gem5 directory is a mercurial repository, we should do some
25813576Sciro.santilli@arm.com# extra things.
25913576Sciro.santilli@arm.com#
26013576Sciro.santilli@arm.com########################################################################
26113576Sciro.santilli@arm.com
26213576Sciro.santilli@arm.comhgdir = main.root.Dir(".hg")
26313576Sciro.santilli@arm.com
26413576Sciro.santilli@arm.com
26513576Sciro.santilli@arm.comstyle_message = """
26613576Sciro.santilli@arm.comYou're missing the gem5 style hook, which automatically checks your code
26713576Sciro.santilli@arm.comagainst the gem5 style rules on %s.
26813576Sciro.santilli@arm.comThis script will now install the hook in your %s.
26913576Sciro.santilli@arm.comPress enter to continue, or ctrl-c to abort: """
27013576Sciro.santilli@arm.com
27113576Sciro.santilli@arm.commercurial_style_message = style_message % ("hg commit and qrefresh commands",
27213576Sciro.santilli@arm.com                                           ".hg/hgrc file")
27313576Sciro.santilli@arm.comgit_style_message = style_message % ("'git commit'",
27413576Sciro.santilli@arm.com                                     ".git/hooks/ directory")
27513576Sciro.santilli@arm.com
27613576Sciro.santilli@arm.commercurial_style_upgrade_message = """
27713576Sciro.santilli@arm.comYour Mercurial style hooks are not up-to-date. This script will now
27813576Sciro.santilli@arm.comtry to automatically update them. A backup of your hgrc will be saved
27913576Sciro.santilli@arm.comin .hg/hgrc.old.
28013576Sciro.santilli@arm.comPress enter to continue, or ctrl-c to abort: """
28113576Sciro.santilli@arm.com
28213576Sciro.santilli@arm.commercurial_style_hook = """
28313576Sciro.santilli@arm.com# The following lines were automatically added by gem5/SConstruct
28413576Sciro.santilli@arm.com# to provide the gem5 style-checking hooks
28513576Sciro.santilli@arm.com[extensions]
28613576Sciro.santilli@arm.comhgstyle = %s/util/hgstyle.py
28713576Sciro.santilli@arm.com
28813576Sciro.santilli@arm.com[hooks]
28913576Sciro.santilli@arm.compretxncommit.style = python:hgstyle.check_style
29013576Sciro.santilli@arm.compre-qrefresh.style = python:hgstyle.check_style
29113576Sciro.santilli@arm.com# End of SConstruct additions
29213576Sciro.santilli@arm.com
29313576Sciro.santilli@arm.com""" % (main.root.abspath)
29413576Sciro.santilli@arm.com
29513576Sciro.santilli@arm.commercurial_lib_not_found = """
29613577Sciro.santilli@arm.comMercurial libraries cannot be found, ignoring style hook.  If
29713577Sciro.santilli@arm.comyou are a gem5 developer, please fix this and run the style
29813577Sciro.santilli@arm.comhook. It is important.
2996143Snate@binkert.org"""
30012302Sgabeblack@google.com
30112302Sgabeblack@google.com# Check for style hook and prompt for installation if it's not there.
30212302Sgabeblack@google.com# Skip this if --ignore-style was specified, there's no interactive
30312302Sgabeblack@google.com# terminal to prompt, or no recognized revision control system can be
30412302Sgabeblack@google.com# found.
30512302Sgabeblack@google.comignore_style = GetOption('ignore_style') or not sys.stdin.isatty()
30612302Sgabeblack@google.com
30712302Sgabeblack@google.com# Try wire up Mercurial to the style hooks
30811983Sgabeblack@google.comif not ignore_style and hgdir.exists():
30911983Sgabeblack@google.com    style_hook = True
31011983Sgabeblack@google.com    style_hooks = tuple()
31112302Sgabeblack@google.com    hgrc = hgdir.File('hgrc')
31212302Sgabeblack@google.com    hgrc_old = hgdir.File('hgrc.old')
31312302Sgabeblack@google.com    try:
31412302Sgabeblack@google.com        from mercurial import ui
31512302Sgabeblack@google.com        ui = ui.ui()
31612302Sgabeblack@google.com        ui.readconfig(hgrc.abspath)
31711983Sgabeblack@google.com        style_hooks = (ui.config('hooks', 'pretxncommit.style', None),
3186143Snate@binkert.org                       ui.config('hooks', 'pre-qrefresh.style', None))
31912305Sgabeblack@google.com        style_hook = all(style_hooks)
32012302Sgabeblack@google.com        style_extension = ui.config('extensions', 'style', None)
32112302Sgabeblack@google.com    except ImportError:
32212302Sgabeblack@google.com        print mercurial_lib_not_found
3236143Snate@binkert.org
3246143Snate@binkert.org    if "python:style.check_style" in style_hooks:
3256143Snate@binkert.org        # Try to upgrade the style hooks
3265522Snate@binkert.org        print mercurial_style_upgrade_message
3276143Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
3286143Snate@binkert.org        try:
3296143Snate@binkert.org            raw_input()
3309982Satgutier@umich.edu        except:
33112302Sgabeblack@google.com            print "Input exception, exiting scons.\n"
33212302Sgabeblack@google.com            sys.exit(1)
33312302Sgabeblack@google.com        shutil.copyfile(hgrc.abspath, hgrc_old.abspath)
3346143Snate@binkert.org        re_style_hook = re.compile(r"^([^=#]+)\.style\s*=\s*([^#\s]+).*")
3356143Snate@binkert.org        re_style_extension = re.compile("style\s*=\s*([^#\s]+).*")
3366143Snate@binkert.org        old, new = open(hgrc_old.abspath, 'r'), open(hgrc.abspath, 'w')
3376143Snate@binkert.org        for l in old:
3385522Snate@binkert.org            m_hook = re_style_hook.match(l)
3395522Snate@binkert.org            m_ext = re_style_extension.match(l)
3405522Snate@binkert.org            if m_hook:
3415522Snate@binkert.org                hook, check = m_hook.groups()
3425604Snate@binkert.org                if check != "python:style.check_style":
3435604Snate@binkert.org                    print "Warning: %s.style is using a non-default " \
3446143Snate@binkert.org                        "checker: %s" % (hook, check)
3456143Snate@binkert.org                if hook not in ("pretxncommit", "pre-qrefresh"):
3464762Snate@binkert.org                    print "Warning: Updating unknown style hook: %s" % hook
3474762Snate@binkert.org
3486143Snate@binkert.org                l = "%s.style = python:hgstyle.check_style\n" % hook
3496727Ssteve.reinhardt@amd.com            elif m_ext and m_ext.group(1) == style_extension:
3506727Ssteve.reinhardt@amd.com                l = "hgstyle = %s/util/hgstyle.py\n" % main.root.abspath
3516727Ssteve.reinhardt@amd.com
3524762Snate@binkert.org            new.write(l)
3536143Snate@binkert.org    elif not style_hook:
3546143Snate@binkert.org        print mercurial_style_message,
3556143Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
3566143Snate@binkert.org        try:
3576727Ssteve.reinhardt@amd.com            raw_input()
3586143Snate@binkert.org        except:
3597674Snate@binkert.org            print "Input exception, exiting scons.\n"
3607674Snate@binkert.org            sys.exit(1)
3615604Snate@binkert.org        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3626143Snate@binkert.org        print "Adding style hook to", hgrc_path, "\n"
3636143Snate@binkert.org        try:
3646143Snate@binkert.org            with open(hgrc_path, 'a') as f:
3654762Snate@binkert.org                f.write(mercurial_style_hook)
3666143Snate@binkert.org        except:
3674762Snate@binkert.org            print "Error updating", hgrc_path
3684762Snate@binkert.org            sys.exit(1)
3694762Snate@binkert.org
3706143Snate@binkert.orgdef install_git_style_hooks():
3716143Snate@binkert.org    try:
3724762Snate@binkert.org        gitdir = Dir(readCommand(
37312302Sgabeblack@google.com            ["git", "rev-parse", "--git-dir"]).strip("\n"))
37412302Sgabeblack@google.com    except Exception, e:
3758233Snate@binkert.org        print "Warning: Failed to find git repo directory: %s" % e
37612302Sgabeblack@google.com        return
3776143Snate@binkert.org
3786143Snate@binkert.org    git_hooks = gitdir.Dir("hooks")
3794762Snate@binkert.org    git_pre_commit_hook = git_hooks.File("pre-commit")
3806143Snate@binkert.org    git_style_script = File("util/git-pre-commit.py")
3814762Snate@binkert.org
3829396Sandreas.hansson@arm.com    if git_pre_commit_hook.exists():
3839396Sandreas.hansson@arm.com        return
3849396Sandreas.hansson@arm.com
38512302Sgabeblack@google.com    print git_style_message,
38612302Sgabeblack@google.com    try:
38712302Sgabeblack@google.com        raw_input()
3889396Sandreas.hansson@arm.com    except:
3899396Sandreas.hansson@arm.com        print "Input exception, exiting scons.\n"
3909396Sandreas.hansson@arm.com        sys.exit(1)
3919396Sandreas.hansson@arm.com
3929396Sandreas.hansson@arm.com    if not git_hooks.exists():
3939396Sandreas.hansson@arm.com        mkdir(git_hooks.get_abspath())
3949396Sandreas.hansson@arm.com
3959930Sandreas.hansson@arm.com    # Use a relative symlink if the hooks live in the source directory
3969930Sandreas.hansson@arm.com    if git_pre_commit_hook.is_under(main.root):
3979396Sandreas.hansson@arm.com        script_path = os.path.relpath(
3986143Snate@binkert.org            git_style_script.get_abspath(),
39912797Sgabeblack@google.com            git_pre_commit_hook.Dir(".").get_abspath())
40012797Sgabeblack@google.com    else:
40112797Sgabeblack@google.com        script_path = git_style_script.get_abspath()
4028235Snate@binkert.org
40312797Sgabeblack@google.com    try:
40412797Sgabeblack@google.com        os.symlink(script_path, git_pre_commit_hook.get_abspath())
40512797Sgabeblack@google.com    except:
40612797Sgabeblack@google.com        print "Error updating git pre-commit hook"
40712797Sgabeblack@google.com        raise
40812797Sgabeblack@google.com
40912797Sgabeblack@google.com# Try to wire up git to the style hooks
41012797Sgabeblack@google.comif not ignore_style and main.root.Entry(".git").exists():
41112797Sgabeblack@google.com    install_git_style_hooks()
41212797Sgabeblack@google.com
41312797Sgabeblack@google.com###################################################
41412797Sgabeblack@google.com#
41512797Sgabeblack@google.com# Figure out which configurations to set up based on the path(s) of
41612797Sgabeblack@google.com# the target(s).
41712797Sgabeblack@google.com#
41812757Sgabeblack@google.com###################################################
41912757Sgabeblack@google.com
42012797Sgabeblack@google.com# Find default configuration & binary.
42112797Sgabeblack@google.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
42212797Sgabeblack@google.com
42312757Sgabeblack@google.com# helper function: find last occurrence of element in list
42412757Sgabeblack@google.comdef rfind(l, elt, offs = -1):
42512757Sgabeblack@google.com    for i in range(len(l)+offs, 0, -1):
42612757Sgabeblack@google.com        if l[i] == elt:
4278235Snate@binkert.org            return i
42812302Sgabeblack@google.com    raise ValueError, "element not found"
4298235Snate@binkert.org
4308235Snate@binkert.org# Take a list of paths (or SCons Nodes) and return a list with all
43112757Sgabeblack@google.com# paths made absolute and ~-expanded.  Paths will be interpreted
4328235Snate@binkert.org# relative to the launch directory unless a different root is provided
4338235Snate@binkert.orgdef makePathListAbsolute(path_list, root=GetLaunchDir()):
4348235Snate@binkert.org    return [abspath(joinpath(root, expanduser(str(p))))
43512757Sgabeblack@google.com            for p in path_list]
43612313Sgabeblack@google.com
43712797Sgabeblack@google.com# Each target must have 'build' in the interior of the path; the
43812797Sgabeblack@google.com# directory below this will determine the build parameters.  For
43912797Sgabeblack@google.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
44012797Sgabeblack@google.com# recognize that ALPHA_SE specifies the configuration because it
44112797Sgabeblack@google.com# follow 'build' in the build path.
44212797Sgabeblack@google.com
44312797Sgabeblack@google.com# The funky assignment to "[:]" is needed to replace the list contents
44412797Sgabeblack@google.com# in place rather than reassign the symbol to a new list, which
44512797Sgabeblack@google.com# doesn't work (obviously!).
44612797Sgabeblack@google.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
44712797Sgabeblack@google.com
44812797Sgabeblack@google.com# Generate a list of the unique build roots and configs that the
44912797Sgabeblack@google.com# collected targets reference.
45012797Sgabeblack@google.comvariant_paths = []
45112797Sgabeblack@google.combuild_root = None
45212797Sgabeblack@google.comfor t in BUILD_TARGETS:
45312797Sgabeblack@google.com    path_dirs = t.split('/')
45412797Sgabeblack@google.com    try:
45512797Sgabeblack@google.com        build_top = rfind(path_dirs, 'build', -2)
45612797Sgabeblack@google.com    except:
45712797Sgabeblack@google.com        print "Error: no non-leaf 'build' dir found on target path", t
45812797Sgabeblack@google.com        Exit(1)
45912797Sgabeblack@google.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
46012797Sgabeblack@google.com    if not build_root:
46112797Sgabeblack@google.com        build_root = this_build_root
46212797Sgabeblack@google.com    else:
46312797Sgabeblack@google.com        if this_build_root != build_root:
46412797Sgabeblack@google.com            print "Error: build targets not under same build root\n"\
46512797Sgabeblack@google.com                  "  %s\n  %s" % (build_root, this_build_root)
46612797Sgabeblack@google.com            Exit(1)
46712797Sgabeblack@google.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
46812797Sgabeblack@google.com    if variant_path not in variant_paths:
46912797Sgabeblack@google.com        variant_paths.append(variant_path)
47012797Sgabeblack@google.com
47112797Sgabeblack@google.com# Make sure build_root exists (might not if this is the first build there)
47212797Sgabeblack@google.comif not isdir(build_root):
47312797Sgabeblack@google.com    mkdir(build_root)
47412797Sgabeblack@google.commain['BUILDROOT'] = build_root
47512797Sgabeblack@google.com
47612797Sgabeblack@google.comExport('main')
47712797Sgabeblack@google.com
47812797Sgabeblack@google.commain.SConsignFile(joinpath(build_root, "sconsign"))
47912797Sgabeblack@google.com
48012797Sgabeblack@google.com# Default duplicate option is to use hard links, but this messes up
48112313Sgabeblack@google.com# when you use emacs to edit a file in the target dir, as emacs moves
48212313Sgabeblack@google.com# file to file~ then copies to file, breaking the link.  Symbolic
48312797Sgabeblack@google.com# (soft) links work better.
48412797Sgabeblack@google.commain.SetOption('duplicate', 'soft-copy')
48512797Sgabeblack@google.com
48612371Sgabeblack@google.com#
4875584Snate@binkert.org# Set up global sticky variables... these are common to an entire build
48812797Sgabeblack@google.com# tree (not specific to a particular build like ALPHA_SE)
48912797Sgabeblack@google.com#
49012797Sgabeblack@google.com
49112797Sgabeblack@google.comglobal_vars_file = joinpath(build_root, 'variables.global')
49212797Sgabeblack@google.com
49312797Sgabeblack@google.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
49412797Sgabeblack@google.com
49512797Sgabeblack@google.comglobal_vars.AddVariables(
49612797Sgabeblack@google.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
49712797Sgabeblack@google.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
49812797Sgabeblack@google.com    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
49912797Sgabeblack@google.com    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
50012797Sgabeblack@google.com    ('BATCH', 'Use batch pool for build and tests', False),
50112797Sgabeblack@google.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
50212797Sgabeblack@google.com    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
50312797Sgabeblack@google.com    ('EXTRAS', 'Add extra directories to the compilation', '')
50412797Sgabeblack@google.com    )
50512797Sgabeblack@google.com
50612797Sgabeblack@google.com# Update main environment with values from ARGUMENTS & global_vars_file
50712797Sgabeblack@google.comglobal_vars.Update(main)
50812797Sgabeblack@google.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
50912797Sgabeblack@google.com
51012797Sgabeblack@google.com# Save sticky variable settings back to current variables file
51112797Sgabeblack@google.comglobal_vars.Save(global_vars_file, main)
51212797Sgabeblack@google.com
51312797Sgabeblack@google.com# Parse EXTRAS variable to build list of all directories where we're
51412797Sgabeblack@google.com# look for sources etc.  This list is exported as extras_dir_list.
51512797Sgabeblack@google.combase_dir = main.srcdir.abspath
51612797Sgabeblack@google.comif main['EXTRAS']:
51712797Sgabeblack@google.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
51812797Sgabeblack@google.comelse:
51912797Sgabeblack@google.com    extras_dir_list = []
52012797Sgabeblack@google.com
52112797Sgabeblack@google.comExport('base_dir')
52212797Sgabeblack@google.comExport('extras_dir_list')
52312797Sgabeblack@google.com
52412797Sgabeblack@google.com# the ext directory should be on the #includes path
52512797Sgabeblack@google.commain.Append(CPPPATH=[Dir('ext')])
5264382Sbinkertn@umich.edu
52713576Sciro.santilli@arm.comdef strip_build_path(path, env):
52813577Sciro.santilli@arm.com    path = str(path)
5294202Sbinkertn@umich.edu    variant_base = env['BUILDROOT'] + os.path.sep
5304382Sbinkertn@umich.edu    if path.startswith(variant_base):
5314382Sbinkertn@umich.edu        path = path[len(variant_base):]
5329396Sandreas.hansson@arm.com    elif path.startswith('build/'):
53312797Sgabeblack@google.com        path = path[6:]
5345584Snate@binkert.org    return path
53512313Sgabeblack@google.com
5364382Sbinkertn@umich.edu# Generate a string of the form:
5374382Sbinkertn@umich.edu#   common/path/prefix/src1, src2 -> tgt1, tgt2
5384382Sbinkertn@umich.edu# to print while building.
5398232Snate@binkert.orgclass Transform(object):
5405192Ssaidi@eecs.umich.edu    # all specific color settings should be here and nowhere else
5418232Snate@binkert.org    tool_color = termcap.Normal
5428232Snate@binkert.org    pfx_color = termcap.Yellow
5438232Snate@binkert.org    srcs_color = termcap.Yellow + termcap.Bold
5445192Ssaidi@eecs.umich.edu    arrow_color = termcap.Blue + termcap.Bold
5458232Snate@binkert.org    tgts_color = termcap.Yellow + termcap.Bold
5465192Ssaidi@eecs.umich.edu
5475799Snate@binkert.org    def __init__(self, tool, max_sources=99):
5488232Snate@binkert.org        self.format = self.tool_color + (" [%8s] " % tool) \
5495192Ssaidi@eecs.umich.edu                      + self.pfx_color + "%s" \
5505192Ssaidi@eecs.umich.edu                      + self.srcs_color + "%s" \
5515192Ssaidi@eecs.umich.edu                      + self.arrow_color + " -> " \
5528232Snate@binkert.org                      + self.tgts_color + "%s" \
5535192Ssaidi@eecs.umich.edu                      + termcap.Normal
5548232Snate@binkert.org        self.max_sources = max_sources
5555192Ssaidi@eecs.umich.edu
5565192Ssaidi@eecs.umich.edu    def __call__(self, target, source, env, for_signature=None):
5575192Ssaidi@eecs.umich.edu        # truncate source list according to max_sources param
5585192Ssaidi@eecs.umich.edu        source = source[0:self.max_sources]
5594382Sbinkertn@umich.edu        def strip(f):
5604382Sbinkertn@umich.edu            return strip_build_path(str(f), env)
5614382Sbinkertn@umich.edu        if len(source) > 0:
5622667Sstever@eecs.umich.edu            srcs = map(strip, source)
5632667Sstever@eecs.umich.edu        else:
5642667Sstever@eecs.umich.edu            srcs = ['']
5652667Sstever@eecs.umich.edu        tgts = map(strip, target)
5662667Sstever@eecs.umich.edu        # surprisingly, os.path.commonprefix is a dumb char-by-char string
5672667Sstever@eecs.umich.edu        # operation that has nothing to do with paths.
5685742Snate@binkert.org        com_pfx = os.path.commonprefix(srcs + tgts)
5695742Snate@binkert.org        com_pfx_len = len(com_pfx)
5705742Snate@binkert.org        if com_pfx:
5715793Snate@binkert.org            # do some cleanup and sanity checking on common prefix
5728334Snate@binkert.org            if com_pfx[-1] == ".":
5735793Snate@binkert.org                # prefix matches all but file extension: ok
5745793Snate@binkert.org                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
5755793Snate@binkert.org                com_pfx = com_pfx[0:-1]
5764382Sbinkertn@umich.edu            elif com_pfx[-1] == "/":
5774762Snate@binkert.org                # common prefix is directory path: OK
5785344Sstever@gmail.com                pass
5794382Sbinkertn@umich.edu            else:
5805341Sstever@gmail.com                src0_len = len(srcs[0])
5815742Snate@binkert.org                tgt0_len = len(tgts[0])
5825742Snate@binkert.org                if src0_len == com_pfx_len:
5835742Snate@binkert.org                    # source is a substring of target, OK
5845742Snate@binkert.org                    pass
5855742Snate@binkert.org                elif tgt0_len == com_pfx_len:
5864762Snate@binkert.org                    # target is a substring of source, need to back up to
5875742Snate@binkert.org                    # avoid empty string on RHS of arrow
5885742Snate@binkert.org                    sep_idx = com_pfx.rfind(".")
58911984Sgabeblack@google.com                    if sep_idx != -1:
5907722Sgblack@eecs.umich.edu                        com_pfx = com_pfx[0:sep_idx]
5915742Snate@binkert.org                    else:
5925742Snate@binkert.org                        com_pfx = ''
5935742Snate@binkert.org                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
5949930Sandreas.hansson@arm.com                    # still splitting at file extension: ok
5959930Sandreas.hansson@arm.com                    pass
5969930Sandreas.hansson@arm.com                else:
5979930Sandreas.hansson@arm.com                    # probably a fluke; ignore it
5989930Sandreas.hansson@arm.com                    com_pfx = ''
5995742Snate@binkert.org        # recalculate length in case com_pfx was modified
6008242Sbradley.danofsky@amd.com        com_pfx_len = len(com_pfx)
6018242Sbradley.danofsky@amd.com        def fmt(files):
6028242Sbradley.danofsky@amd.com            f = map(lambda s: s[com_pfx_len:], files)
6038242Sbradley.danofsky@amd.com            return ', '.join(f)
6045341Sstever@gmail.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
6055742Snate@binkert.org
6067722Sgblack@eecs.umich.eduExport('Transform')
6074773Snate@binkert.org
6086108Snate@binkert.org# enable the regression script to use the termcap
6091858SN/Amain['TERMCAP'] = termcap
6101085SN/A
6116658Snate@binkert.orgif GetOption('verbose'):
6126658Snate@binkert.org    def MakeAction(action, string, *args, **kwargs):
6137673Snate@binkert.org        return Action(action, *args, **kwargs)
6146658Snate@binkert.orgelse:
6156658Snate@binkert.org    MakeAction = Action
61611308Santhony.gutierrez@amd.com    main['CCCOMSTR']        = Transform("CC")
6176658Snate@binkert.org    main['CXXCOMSTR']       = Transform("CXX")
61811308Santhony.gutierrez@amd.com    main['ASCOMSTR']        = Transform("AS")
6196658Snate@binkert.org    main['SWIGCOMSTR']      = Transform("SWIG")
6206658Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
6217673Snate@binkert.org    main['LINKCOMSTR']      = Transform("LINK", 0)
6227673Snate@binkert.org    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
6237673Snate@binkert.org    main['M4COMSTR']        = Transform("M4")
6247673Snate@binkert.org    main['SHCCCOMSTR']      = Transform("SHCC")
6257673Snate@binkert.org    main['SHCXXCOMSTR']     = Transform("SHCXX")
6267673Snate@binkert.orgExport('MakeAction')
6277673Snate@binkert.org
62810467Sandreas.hansson@arm.com# Initialize the Link-Time Optimization (LTO) flags
6296658Snate@binkert.orgmain['LTO_CCFLAGS'] = []
6307673Snate@binkert.orgmain['LTO_LDFLAGS'] = []
63110467Sandreas.hansson@arm.com
63210467Sandreas.hansson@arm.com# According to the readme, tcmalloc works best if the compiler doesn't
63310467Sandreas.hansson@arm.com# assume that we're using the builtin malloc and friends. These flags
63410467Sandreas.hansson@arm.com# are compiler-specific, so we need to set them after we detect which
63510467Sandreas.hansson@arm.com# compiler we're using.
63610467Sandreas.hansson@arm.commain['TCMALLOC_CCFLAGS'] = []
63710467Sandreas.hansson@arm.com
63810467Sandreas.hansson@arm.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
63910467Sandreas.hansson@arm.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
64010467Sandreas.hansson@arm.com
64110467Sandreas.hansson@arm.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
6427673Snate@binkert.orgmain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
6437673Snate@binkert.orgif main['GCC'] + main['CLANG'] > 1:
6447673Snate@binkert.org    print 'Error: How can we have two at the same time?'
6457673Snate@binkert.org    Exit(1)
6467673Snate@binkert.org
6479048SAli.Saidi@ARM.com# Set up default C++ compiler flags
6487673Snate@binkert.orgif main['GCC'] or main['CLANG']:
6497673Snate@binkert.org    # As gcc and clang share many flags, do the common parts here
6507673Snate@binkert.org    main.Append(CCFLAGS=['-pipe'])
6517673Snate@binkert.org    main.Append(CCFLAGS=['-fno-strict-aliasing'])
6526658Snate@binkert.org    # Enable -Wall and -Wextra and then disable the few warnings that
6537756SAli.Saidi@ARM.com    # we consistently violate
6547816Ssteve.reinhardt@amd.com    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
6556658Snate@binkert.org                         '-Wno-sign-compare', '-Wno-unused-parameter'])
65611308Santhony.gutierrez@amd.com    # We always compile using C++11
65711308Santhony.gutierrez@amd.com    main.Append(CXXFLAGS=['-std=c++11'])
65811308Santhony.gutierrez@amd.comelse:
65911308Santhony.gutierrez@amd.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
66011308Santhony.gutierrez@amd.com    print "Don't know what compiler options to use for your compiler."
66111308Santhony.gutierrez@amd.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
66211308Santhony.gutierrez@amd.com    print termcap.Yellow + '       version:' + termcap.Normal,
66311308Santhony.gutierrez@amd.com    if not CXX_version:
66411308Santhony.gutierrez@amd.com        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
66511308Santhony.gutierrez@amd.com               termcap.Normal
66611308Santhony.gutierrez@amd.com    else:
66711308Santhony.gutierrez@amd.com        print CXX_version.replace('\n', '<nl>')
66811308Santhony.gutierrez@amd.com    print "       If you're trying to use a compiler other than GCC"
66911308Santhony.gutierrez@amd.com    print "       or clang, there appears to be something wrong with your"
67011308Santhony.gutierrez@amd.com    print "       environment."
67111308Santhony.gutierrez@amd.com    print "       "
67211308Santhony.gutierrez@amd.com    print "       If you are trying to use a compiler other than those listed"
67311308Santhony.gutierrez@amd.com    print "       above you will need to ease fix SConstruct and "
67411308Santhony.gutierrez@amd.com    print "       src/SConscript to support that compiler."
67511308Santhony.gutierrez@amd.com    Exit(1)
67611308Santhony.gutierrez@amd.com
67711308Santhony.gutierrez@amd.comif main['GCC']:
67811308Santhony.gutierrez@amd.com    # Check for a supported version of gcc. >= 4.7 is chosen for its
67911308Santhony.gutierrez@amd.com    # level of c++11 support. See
68011308Santhony.gutierrez@amd.com    # http://gcc.gnu.org/projects/cxx0x.html for details.
68111308Santhony.gutierrez@amd.com    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
68211308Santhony.gutierrez@amd.com    if compareVersions(gcc_version, "4.7") < 0:
68311308Santhony.gutierrez@amd.com        print 'Error: gcc version 4.7 or newer required.'
68411308Santhony.gutierrez@amd.com        print '       Installed version:', gcc_version
68511308Santhony.gutierrez@amd.com        Exit(1)
68611308Santhony.gutierrez@amd.com
68711308Santhony.gutierrez@amd.com    main['GCC_VERSION'] = gcc_version
68811308Santhony.gutierrez@amd.com
68911308Santhony.gutierrez@amd.com    # gcc from version 4.8 and above generates "rep; ret" instructions
69011308Santhony.gutierrez@amd.com    # to avoid performance penalties on certain AMD chips. Older
69111308Santhony.gutierrez@amd.com    # assemblers detect this as an error, "Error: expecting string
69211308Santhony.gutierrez@amd.com    # instruction after `rep'"
69311308Santhony.gutierrez@amd.com    if compareVersions(gcc_version, "4.8") > 0:
69411308Santhony.gutierrez@amd.com        as_version_raw = readCommand([main['AS'], '-v', '/dev/null'],
69511308Santhony.gutierrez@amd.com                                     exception=False).split()
69611308Santhony.gutierrez@amd.com
69711308Santhony.gutierrez@amd.com        # version strings may contain extra distro-specific
69811308Santhony.gutierrez@amd.com        # qualifiers, so play it safe and keep only what comes before
69911308Santhony.gutierrez@amd.com        # the first hyphen
70011308Santhony.gutierrez@amd.com        as_version = as_version_raw[-1].split('-')[0] if as_version_raw \
7014382Sbinkertn@umich.edu            else None
7024382Sbinkertn@umich.edu
7034762Snate@binkert.org        if not as_version or compareVersions(as_version, "2.23") < 0:
7044762Snate@binkert.org            print termcap.Yellow + termcap.Bold + \
7054762Snate@binkert.org                'Warning: This combination of gcc and binutils have' + \
7066654Snate@binkert.org                ' known incompatibilities.\n' + \
7076654Snate@binkert.org                '         If you encounter build problems, please update ' + \
7085517Snate@binkert.org                'binutils to 2.23.' + \
7095517Snate@binkert.org                termcap.Normal
7105517Snate@binkert.org
7115517Snate@binkert.org    # Make sure we warn if the user has requested to compile with the
7125517Snate@binkert.org    # Undefined Benahvior Sanitizer and this version of gcc does not
7135517Snate@binkert.org    # support it.
7145517Snate@binkert.org    if GetOption('with_ubsan') and \
7155517Snate@binkert.org            compareVersions(gcc_version, '4.9') < 0:
7165517Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
7175517Snate@binkert.org            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
7185517Snate@binkert.org            termcap.Normal
7195517Snate@binkert.org
7205517Snate@binkert.org    # Add the appropriate Link-Time Optimization (LTO) flags
7215517Snate@binkert.org    # unless LTO is explicitly turned off. Note that these flags
7225517Snate@binkert.org    # are only used by the fast target.
7235517Snate@binkert.org    if not GetOption('no_lto'):
7245517Snate@binkert.org        # Pass the LTO flag when compiling to produce GIMPLE
7256654Snate@binkert.org        # output, we merely create the flags here and only append
7265517Snate@binkert.org        # them later
7275517Snate@binkert.org        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
7285517Snate@binkert.org
7295517Snate@binkert.org        # Use the same amount of jobs for LTO as we are running
7305517Snate@binkert.org        # scons with
73111802Sandreas.sandberg@arm.com        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
7325517Snate@binkert.org
7335517Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
7346143Snate@binkert.org                                  '-fno-builtin-realloc', '-fno-builtin-free'])
7356654Snate@binkert.org
7365517Snate@binkert.org    # add option to check for undeclared overrides
7375517Snate@binkert.org    if compareVersions(gcc_version, "5.0") > 0:
7385517Snate@binkert.org        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
7395517Snate@binkert.org
7405517Snate@binkert.orgelif main['CLANG']:
7415517Snate@binkert.org    # Check for a supported version of clang, >= 3.1 is needed to
7425517Snate@binkert.org    # support similar features as gcc 4.7. See
7435517Snate@binkert.org    # http://clang.llvm.org/cxx_status.html for details
7445517Snate@binkert.org    clang_version_re = re.compile(".* version (\d+\.\d+)")
7455517Snate@binkert.org    clang_version_match = clang_version_re.search(CXX_version)
7465517Snate@binkert.org    if (clang_version_match):
7475517Snate@binkert.org        clang_version = clang_version_match.groups()[0]
7485517Snate@binkert.org        if compareVersions(clang_version, "3.1") < 0:
7495517Snate@binkert.org            print 'Error: clang version 3.1 or newer required.'
7506654Snate@binkert.org            print '       Installed version:', clang_version
7516654Snate@binkert.org            Exit(1)
7525517Snate@binkert.org    else:
7535517Snate@binkert.org        print 'Error: Unable to determine clang version.'
7546143Snate@binkert.org        Exit(1)
7556143Snate@binkert.org
7566143Snate@binkert.org    # clang has a few additional warnings that we disable, extraneous
7576727Ssteve.reinhardt@amd.com    # parantheses are allowed due to Ruby's printing of the AST,
7585517Snate@binkert.org    # finally self assignments are allowed as the generated CPU code
7596727Ssteve.reinhardt@amd.com    # is relying on this
7605517Snate@binkert.org    main.Append(CCFLAGS=['-Wno-parentheses',
7615517Snate@binkert.org                         '-Wno-self-assign',
7625517Snate@binkert.org                         # Some versions of libstdc++ (4.8?) seem to
7636654Snate@binkert.org                         # use struct hash and class hash
7646654Snate@binkert.org                         # interchangeably.
7657673Snate@binkert.org                         '-Wno-mismatched-tags',
7666654Snate@binkert.org                         ])
7676654Snate@binkert.org
7686654Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
7696654Snate@binkert.org
7705517Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
7715517Snate@binkert.org    # opposed to libstdc++, as the later is dated.
7725517Snate@binkert.org    if sys.platform == "darwin":
7736143Snate@binkert.org        main.Append(CXXFLAGS=['-stdlib=libc++'])
7745517Snate@binkert.org        main.Append(LIBS=['c++'])
7754762Snate@binkert.org
7765517Snate@binkert.orgelse:
7775517Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
7786143Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
7796143Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
7805517Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
7815517Snate@binkert.org    if not CXX_version:
7825517Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
7835517Snate@binkert.org               termcap.Normal
7845517Snate@binkert.org    else:
7855517Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
7865517Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
7875517Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
7885517Snate@binkert.org    print "       environment."
7896143Snate@binkert.org    print "       "
7905517Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
7916654Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
7926654Snate@binkert.org    print "       src/SConscript to support that compiler."
7936654Snate@binkert.org    Exit(1)
7946654Snate@binkert.org
7956654Snate@binkert.org# Set up common yacc/bison flags (needed for Ruby)
7966654Snate@binkert.orgmain['YACCFLAGS'] = '-d'
7974762Snate@binkert.orgmain['YACCHXXFILESUFFIX'] = '.hh'
7984762Snate@binkert.org
7994762Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
8004762Snate@binkert.org# extra 'qdo' every time we run scons.
8014762Snate@binkert.orgif main['BATCH']:
8027675Snate@binkert.org    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
80310584Sandreas.hansson@arm.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
8044762Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
8054762Snate@binkert.org    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
8064762Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
8074762Snate@binkert.org
8084382Sbinkertn@umich.eduif sys.platform == 'cygwin':
8094382Sbinkertn@umich.edu    # cygwin has some header file issues...
8105517Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
8116654Snate@binkert.org
8125517Snate@binkert.org# Check for the protobuf compiler
8138126Sgblack@eecs.umich.eduprotoc_version = readCommand([main['PROTOC'], '--version'],
8146654Snate@binkert.org                             exception='').split()
8157673Snate@binkert.org
8166654Snate@binkert.org# First two words should be "libprotoc x.y.z"
81711802Sandreas.sandberg@arm.comif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
8186654Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
8196654Snate@binkert.org        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
8206654Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' + \
8216654Snate@binkert.org        termcap.Normal
82211802Sandreas.sandberg@arm.com    main['PROTOC'] = False
8236669Snate@binkert.orgelse:
82411802Sandreas.sandberg@arm.com    # Based on the availability of the compress stream wrappers,
8256669Snate@binkert.org    # require 2.1.0
8266669Snate@binkert.org    min_protoc_version = '2.1.0'
8276669Snate@binkert.org    if compareVersions(protoc_version[1], min_protoc_version) < 0:
8286669Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
8296654Snate@binkert.org            'Warning: protoc version', min_protoc_version, \
8307673Snate@binkert.org            'or newer required.\n' + \
8315517Snate@binkert.org            '         Installed version:', protoc_version[1], \
8328126Sgblack@eecs.umich.edu            termcap.Normal
8335798Snate@binkert.org        main['PROTOC'] = False
8347756SAli.Saidi@ARM.com    else:
8357816Ssteve.reinhardt@amd.com        # Attempt to determine the appropriate include path and
8365798Snate@binkert.org        # library path using pkg-config, that means we also need to
8375798Snate@binkert.org        # check for pkg-config. Note that it is possible to use
8385517Snate@binkert.org        # protobuf without the involvement of pkg-config. Later on we
8395517Snate@binkert.org        # check go a library config check and at that point the test
8407673Snate@binkert.org        # will fail if libprotobuf cannot be found.
8415517Snate@binkert.org        if readCommand(['pkg-config', '--version'], exception=''):
8425517Snate@binkert.org            try:
8437673Snate@binkert.org                # Attempt to establish what linking flags to add for protobuf
8447673Snate@binkert.org                # using pkg-config
8455517Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
8465798Snate@binkert.org            except:
8475798Snate@binkert.org                print termcap.Yellow + termcap.Bold + \
8488333Snate@binkert.org                    'Warning: pkg-config could not get protobuf flags.' + \
8497816Ssteve.reinhardt@amd.com                    termcap.Normal
8505798Snate@binkert.org
8515798Snate@binkert.org# Check for SWIG
8524762Snate@binkert.orgif not main.has_key('SWIG'):
8534762Snate@binkert.org    print 'Error: SWIG utility not found.'
8544762Snate@binkert.org    print '       Please install (see http://www.swig.org) and retry.'
8554762Snate@binkert.org    Exit(1)
8564762Snate@binkert.org
8578596Ssteve.reinhardt@amd.com# Check for appropriate SWIG version
8585517Snate@binkert.orgswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
8595517Snate@binkert.org# First 3 words should be "SWIG Version x.y.z"
86011997Sgabeblack@google.comif len(swig_version) < 3 or \
8615517Snate@binkert.org        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
8625517Snate@binkert.org    print 'Error determining SWIG version.'
8637673Snate@binkert.org    Exit(1)
8648596Ssteve.reinhardt@amd.com
8657673Snate@binkert.orgmin_swig_version = '2.0.4'
8665517Snate@binkert.orgif compareVersions(swig_version[2], min_swig_version) < 0:
86710458Sandreas.hansson@arm.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
86810458Sandreas.hansson@arm.com    print '       Installed version:', swig_version[2]
86910458Sandreas.hansson@arm.com    Exit(1)
87010458Sandreas.hansson@arm.com
87110458Sandreas.hansson@arm.com# Check for known incompatibilities. The standard library shipped with
87210458Sandreas.hansson@arm.com# gcc >= 4.9 does not play well with swig versions prior to 3.0
87310458Sandreas.hansson@arm.comif main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
87410458Sandreas.hansson@arm.com        compareVersions(swig_version[2], '3.0') < 0:
87510458Sandreas.hansson@arm.com    print termcap.Yellow + termcap.Bold + \
87610458Sandreas.hansson@arm.com        'Warning: This combination of gcc and swig have' + \
87710458Sandreas.hansson@arm.com        ' known incompatibilities.\n' + \
87810458Sandreas.hansson@arm.com        '         If you encounter build problems, please update ' + \
8795517Snate@binkert.org        'swig to 3.0 or later.' + \
88011996Sgabeblack@google.com        termcap.Normal
8815517Snate@binkert.org
88211997Sgabeblack@google.com# Set up SWIG flags & scanner
88311996Sgabeblack@google.comswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
8845517Snate@binkert.orgmain.Append(SWIGFLAGS=swig_flags)
8855517Snate@binkert.org
8867673Snate@binkert.org# Check for 'timeout' from GNU coreutils. If present, regressions will
8877673Snate@binkert.org# be run with a time limit. We require version 8.13 since we rely on
88811996Sgabeblack@google.com# support for the '--foreground' option.
88911988Sandreas.sandberg@arm.comtimeout_lines = readCommand(['timeout', '--version'],
8907673Snate@binkert.org                            exception='').splitlines()
8915517Snate@binkert.org# Get the first line and tokenize it
8928596Ssteve.reinhardt@amd.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
8935517Snate@binkert.orgmain['TIMEOUT'] =  timeout_version and \
8945517Snate@binkert.org    compareVersions(timeout_version[-1], '8.13') >= 0
89511997Sgabeblack@google.com
8965517Snate@binkert.org# filter out all existing swig scanners, they mess up the dependency
8975517Snate@binkert.org# stuff for some reason
8987673Snate@binkert.orgscanners = []
8997673Snate@binkert.orgfor scanner in main['SCANNERS']:
9007673Snate@binkert.org    skeys = scanner.skeys
9015517Snate@binkert.org    if skeys == '.i':
90211988Sandreas.sandberg@arm.com        continue
90311997Sgabeblack@google.com
9048596Ssteve.reinhardt@amd.com    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
9058596Ssteve.reinhardt@amd.com        continue
9068596Ssteve.reinhardt@amd.com
90711988Sandreas.sandberg@arm.com    scanners.append(scanner)
9088596Ssteve.reinhardt@amd.com
9098596Ssteve.reinhardt@amd.com# add the new swig scanner that we like better
9108596Ssteve.reinhardt@amd.comfrom SCons.Scanner import ClassicCPP as CPPScanner
9114762Snate@binkert.orgswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
9126143Snate@binkert.orgscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
9136143Snate@binkert.org
9146143Snate@binkert.org# replace the scanners list that has what we want
9154762Snate@binkert.orgmain['SCANNERS'] = scanners
9164762Snate@binkert.org
9174762Snate@binkert.org# Add a custom Check function to test for structure members.
9187756SAli.Saidi@ARM.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
9198596Ssteve.reinhardt@amd.com    context.Message("Checking for member %s in %s..." %
9204762Snate@binkert.org                    (member, decl))
9214762Snate@binkert.org    text = """
92210458Sandreas.hansson@arm.com#include %(header)s
92310458Sandreas.hansson@arm.comint main(){
92410458Sandreas.hansson@arm.com  %(decl)s test;
92510458Sandreas.hansson@arm.com  (void)test.%(member)s;
92610458Sandreas.hansson@arm.com  return 0;
92710458Sandreas.hansson@arm.com};
92810458Sandreas.hansson@arm.com""" % { "header" : include_quotes[0] + include + include_quotes[1],
92910458Sandreas.hansson@arm.com        "decl" : decl,
93010458Sandreas.hansson@arm.com        "member" : member,
93110458Sandreas.hansson@arm.com        }
93210458Sandreas.hansson@arm.com
93310458Sandreas.hansson@arm.com    ret = context.TryCompile(text, extension=".cc")
93410458Sandreas.hansson@arm.com    context.Result(ret)
93510458Sandreas.hansson@arm.com    return ret
93610458Sandreas.hansson@arm.com
93710458Sandreas.hansson@arm.com# Platform-specific configuration.  Note again that we assume that all
93810458Sandreas.hansson@arm.com# builds under a given build root run on the same host platform.
93910458Sandreas.hansson@arm.comconf = Configure(main,
94010458Sandreas.hansson@arm.com                 conf_dir = joinpath(build_root, '.scons_config'),
94110458Sandreas.hansson@arm.com                 log_file = joinpath(build_root, 'scons_config.log'),
94210458Sandreas.hansson@arm.com                 custom_tests = {
94310458Sandreas.hansson@arm.com        'CheckMember' : CheckMember,
94410458Sandreas.hansson@arm.com        })
94510458Sandreas.hansson@arm.com
94610458Sandreas.hansson@arm.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
94710458Sandreas.hansson@arm.comtry:
94810458Sandreas.hansson@arm.com    import platform
94910458Sandreas.hansson@arm.com    uname = platform.uname()
95010458Sandreas.hansson@arm.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
95110458Sandreas.hansson@arm.com        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
95210458Sandreas.hansson@arm.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
95310458Sandreas.hansson@arm.com            main.Append(CFLAGS=['-arch', 'x86_64'])
95410458Sandreas.hansson@arm.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
95510458Sandreas.hansson@arm.com            main.Append(ASFLAGS=['-arch', 'x86_64'])
95610458Sandreas.hansson@arm.comexcept:
95710458Sandreas.hansson@arm.com    pass
95810458Sandreas.hansson@arm.com
95910458Sandreas.hansson@arm.com# Recent versions of scons substitute a "Null" object for Configure()
96010458Sandreas.hansson@arm.com# when configuration isn't necessary, e.g., if the "--help" option is
96110458Sandreas.hansson@arm.com# present.  Unfortuantely this Null object always returns false,
96210458Sandreas.hansson@arm.com# breaking all our configuration checks.  We replace it with our own
96310458Sandreas.hansson@arm.com# more optimistic null object that returns True instead.
96410458Sandreas.hansson@arm.comif not conf:
96510458Sandreas.hansson@arm.com    def NullCheck(*args, **kwargs):
96610458Sandreas.hansson@arm.com        return True
96710458Sandreas.hansson@arm.com
96810458Sandreas.hansson@arm.com    class NullConf:
96910458Sandreas.hansson@arm.com        def __init__(self, env):
97010458Sandreas.hansson@arm.com            self.env = env
97110584Sandreas.hansson@arm.com        def Finish(self):
97210458Sandreas.hansson@arm.com            return self.env
97310458Sandreas.hansson@arm.com        def __getattr__(self, mname):
97410458Sandreas.hansson@arm.com            return NullCheck
97510458Sandreas.hansson@arm.com
97610458Sandreas.hansson@arm.com    conf = NullConf(main)
9774762Snate@binkert.org
9786143Snate@binkert.org# Cache build files in the supplied directory.
9796143Snate@binkert.orgif main['M5_BUILD_CACHE']:
9806143Snate@binkert.org    print 'Using build cache located at', main['M5_BUILD_CACHE']
9814762Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
9824762Snate@binkert.org
98311996Sgabeblack@google.comif not GetOption('without_python'):
9847816Ssteve.reinhardt@amd.com    # Find Python include and library directories for embedding the
9854762Snate@binkert.org    # interpreter. We rely on python-config to resolve the appropriate
9864762Snate@binkert.org    # includes and linker flags. ParseConfig does not seem to understand
9874762Snate@binkert.org    # the more exotic linker flags such as -Xlinker and -export-dynamic so
9884762Snate@binkert.org    # we add them explicitly below. If you want to link in an alternate
9897756SAli.Saidi@ARM.com    # version of python, see above for instructions on how to invoke
9908596Ssteve.reinhardt@amd.com    # scons with the appropriate PATH set.
9914762Snate@binkert.org    #
9924762Snate@binkert.org    # First we check if python2-config exists, else we use python-config
99311988Sandreas.sandberg@arm.com    python_config = readCommand(['which', 'python2-config'],
99411988Sandreas.sandberg@arm.com                                exception='').strip()
99511988Sandreas.sandberg@arm.com    if not os.path.exists(python_config):
99611988Sandreas.sandberg@arm.com        python_config = readCommand(['which', 'python-config'],
99711988Sandreas.sandberg@arm.com                                    exception='').strip()
99811988Sandreas.sandberg@arm.com    py_includes = readCommand([python_config, '--includes'],
99911988Sandreas.sandberg@arm.com                              exception='').split()
100011988Sandreas.sandberg@arm.com    # Strip the -I from the include folders before adding them to the
100111988Sandreas.sandberg@arm.com    # CPPPATH
100211988Sandreas.sandberg@arm.com    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
100311988Sandreas.sandberg@arm.com
10044382Sbinkertn@umich.edu    # Read the linker flags and split them into libraries and other link
10059396Sandreas.hansson@arm.com    # flags. The libraries are added later through the call the CheckLib.
10069396Sandreas.hansson@arm.com    py_ld_flags = readCommand([python_config, '--ldflags'],
10079396Sandreas.hansson@arm.com        exception='').split()
10089396Sandreas.hansson@arm.com    py_libs = []
10099396Sandreas.hansson@arm.com    for lib in py_ld_flags:
10109396Sandreas.hansson@arm.com         if not lib.startswith('-l'):
10119396Sandreas.hansson@arm.com             main.Append(LINKFLAGS=[lib])
10129396Sandreas.hansson@arm.com         else:
10139396Sandreas.hansson@arm.com             lib = lib[2:]
10149396Sandreas.hansson@arm.com             if lib not in py_libs:
10159396Sandreas.hansson@arm.com                 py_libs.append(lib)
10169396Sandreas.hansson@arm.com
10179396Sandreas.hansson@arm.com    # verify that this stuff works
101812302Sgabeblack@google.com    if not conf.CheckHeader('Python.h', '<>'):
10199396Sandreas.hansson@arm.com        print "Error: can't find Python.h header in", py_includes
102012563Sgabeblack@google.com        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
10219396Sandreas.hansson@arm.com        Exit(1)
10229396Sandreas.hansson@arm.com
10238232Snate@binkert.org    for lib in py_libs:
10248232Snate@binkert.org        if not conf.CheckLib(lib):
10258232Snate@binkert.org            print "Error: can't find library %s required by python" % lib
10268232Snate@binkert.org            Exit(1)
10278232Snate@binkert.org
10286229Snate@binkert.org# On Solaris you need to use libsocket for socket ops
102910455SCurtis.Dunham@arm.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10306229Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
103110455SCurtis.Dunham@arm.com       print "Can't find library with socket calls (e.g. accept())"
103210455SCurtis.Dunham@arm.com       Exit(1)
103310455SCurtis.Dunham@arm.com
10345517Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
10355517Snate@binkert.org# added to the LIBS environment variable.
10367673Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
10375517Snate@binkert.org    print 'Error: did not find needed zlib compression library '\
103810455SCurtis.Dunham@arm.com          'and/or zlib.h header file.'
10395517Snate@binkert.org    print '       Please install zlib and try again.'
10405517Snate@binkert.org    Exit(1)
10418232Snate@binkert.org
104210455SCurtis.Dunham@arm.com# If we have the protobuf compiler, also make sure we have the
104310455SCurtis.Dunham@arm.com# development libraries. If the check passes, libprotobuf will be
104410455SCurtis.Dunham@arm.com# automatically added to the LIBS environment variable. After
10457673Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
10467673Snate@binkert.org# got both protoc and libprotobuf available.
104710455SCurtis.Dunham@arm.commain['HAVE_PROTOBUF'] = main['PROTOC'] and \
104810455SCurtis.Dunham@arm.com    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
104910455SCurtis.Dunham@arm.com                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
10505517Snate@binkert.org
105110455SCurtis.Dunham@arm.com# If we have the compiler but not the library, print another warning.
105210455SCurtis.Dunham@arm.comif main['PROTOC'] and not main['HAVE_PROTOBUF']:
105310455SCurtis.Dunham@arm.com    print termcap.Yellow + termcap.Bold + \
105410455SCurtis.Dunham@arm.com        'Warning: did not find protocol buffer library and/or headers.\n' + \
105510455SCurtis.Dunham@arm.com    '       Please install libprotobuf-dev for tracing support.' + \
105610455SCurtis.Dunham@arm.com    termcap.Normal
105710455SCurtis.Dunham@arm.com
105810455SCurtis.Dunham@arm.com# Check for librt.
105910685Sandreas.hansson@arm.comhave_posix_clock = \
106010455SCurtis.Dunham@arm.com    conf.CheckLibWithHeader(None, 'time.h', 'C',
106110685Sandreas.hansson@arm.com                            'clock_nanosleep(0,0,NULL,NULL);') or \
106210455SCurtis.Dunham@arm.com    conf.CheckLibWithHeader('rt', 'time.h', 'C',
10635517Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
106410455SCurtis.Dunham@arm.com
10658232Snate@binkert.orghave_posix_timers = \
10668232Snate@binkert.org    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
10675517Snate@binkert.org                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
10687673Snate@binkert.org
10695517Snate@binkert.orgif not GetOption('without_tcmalloc'):
10708232Snate@binkert.org    if conf.CheckLib('tcmalloc'):
10718232Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
10725517Snate@binkert.org    elif conf.CheckLib('tcmalloc_minimal'):
10738232Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
10748232Snate@binkert.org    else:
10758232Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
10767673Snate@binkert.org              "You can get a 12% performance improvement by "\
10775517Snate@binkert.org              "installing tcmalloc (libgoogle-perftools-dev package "\
10785517Snate@binkert.org              "on Ubuntu or RedHat)." + termcap.Normal
10797673Snate@binkert.org
10805517Snate@binkert.org
108110455SCurtis.Dunham@arm.com# Detect back trace implementations. The last implementation in the
10825517Snate@binkert.org# list will be used by default.
10835517Snate@binkert.orgbacktrace_impls = [ "none" ]
10848232Snate@binkert.org
10858232Snate@binkert.orgif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
10865517Snate@binkert.org                           'backtrace_symbols_fd((void*)0, 0, 0);'):
10878232Snate@binkert.org    backtrace_impls.append("glibc")
10888232Snate@binkert.org
10895517Snate@binkert.orgif backtrace_impls[-1] == "none":
10908232Snate@binkert.org    default_backtrace_impl = "none"
10918232Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
10928232Snate@binkert.org        "No suitable back trace implementation found." + \
10935517Snate@binkert.org        termcap.Normal
10948232Snate@binkert.org
10958232Snate@binkert.orgif not have_posix_clock:
10968232Snate@binkert.org    print "Can't find library for POSIX clocks."
10978232Snate@binkert.org
10988232Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
10998232Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
11005517Snate@binkert.orgif not have_fenv:
11018232Snate@binkert.org    print "Warning: Header file <fenv.h> not found."
11028232Snate@binkert.org    print "         This host has no IEEE FP rounding mode control."
11035517Snate@binkert.org
11048232Snate@binkert.org# Check if we should enable KVM-based hardware virtualization. The API
11057673Snate@binkert.org# we rely on exists since version 2.6.36 of the kernel, but somehow
11065517Snate@binkert.org# the KVM_API_VERSION does not reflect the change. We test for one of
11077673Snate@binkert.org# the types as a fall back.
11085517Snate@binkert.orghave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
11098232Snate@binkert.orgif not have_kvm:
11108232Snate@binkert.org    print "Info: Compatible header file <linux/kvm.h> not found, " \
11118232Snate@binkert.org        "disabling KVM support."
11125192Ssaidi@eecs.umich.edu
111310454SCurtis.Dunham@arm.com# x86 needs support for xsave. We test for the structure here since we
111410454SCurtis.Dunham@arm.com# won't be able to run new tests by the time we know which ISA we're
11158232Snate@binkert.org# targeting.
111610455SCurtis.Dunham@arm.comhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
111710455SCurtis.Dunham@arm.com                                    '#include <linux/kvm.h>') != 0
111810455SCurtis.Dunham@arm.com
111910455SCurtis.Dunham@arm.com# Check if the requested target ISA is compatible with the host
11205192Ssaidi@eecs.umich.edudef is_isa_kvm_compatible(isa):
112111077SCurtis.Dunham@arm.com    try:
112211330SCurtis.Dunham@arm.com        import platform
112311077SCurtis.Dunham@arm.com        host_isa = platform.machine()
112411077SCurtis.Dunham@arm.com    except:
112511077SCurtis.Dunham@arm.com        print "Warning: Failed to determine host ISA."
112611330SCurtis.Dunham@arm.com        return False
112711077SCurtis.Dunham@arm.com
11287674Snate@binkert.org    if not have_posix_timers:
11295522Snate@binkert.org        print "Warning: Can not enable KVM, host seems to lack support " \
11305522Snate@binkert.org            "for POSIX timers"
11317674Snate@binkert.org        return False
11327674Snate@binkert.org
11337674Snate@binkert.org    if isa == "arm":
11347674Snate@binkert.org        return host_isa in ( "armv7l", "aarch64" )
11357674Snate@binkert.org    elif isa == "x86":
11367674Snate@binkert.org        if host_isa != "x86_64":
11377674Snate@binkert.org            return False
11387674Snate@binkert.org
11395522Snate@binkert.org        if not have_kvm_xsave:
11405522Snate@binkert.org            print "KVM on x86 requires xsave support in kernel headers."
11415522Snate@binkert.org            return False
11425517Snate@binkert.org
11435522Snate@binkert.org        return True
11445517Snate@binkert.org    else:
11456143Snate@binkert.org        return False
11466727Ssteve.reinhardt@amd.com
11475522Snate@binkert.org
11485522Snate@binkert.org# Check if the exclude_host attribute is available. We want this to
11495522Snate@binkert.org# get accurate instruction counts in KVM.
11507674Snate@binkert.orgmain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
11515517Snate@binkert.org    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
11527673Snate@binkert.org
11537673Snate@binkert.org
11547674Snate@binkert.org######################################################################
11557673Snate@binkert.org#
11567674Snate@binkert.org# Finish the configuration
11577674Snate@binkert.org#
11587674Snate@binkert.orgmain = conf.Finish()
115913576Sciro.santilli@arm.com
116013576Sciro.santilli@arm.com######################################################################
116111308Santhony.gutierrez@amd.com#
11627673Snate@binkert.org# Collect all non-global variables
11637674Snate@binkert.org#
11647674Snate@binkert.org
11657674Snate@binkert.org# Define the universe of supported ISAs
11667674Snate@binkert.orgall_isa_list = [ ]
11677674Snate@binkert.orgall_gpu_isa_list = [ ]
11687674Snate@binkert.orgExport('all_isa_list')
11697674Snate@binkert.orgExport('all_gpu_isa_list')
11707674Snate@binkert.org
11717811Ssteve.reinhardt@amd.comclass CpuModel(object):
11727674Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
11737673Snate@binkert.org    know about a particular CPU model.'''
11745522Snate@binkert.org
11756143Snate@binkert.org    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
117610453SAndrew.Bardsley@arm.com    dict = {}
11777816Ssteve.reinhardt@amd.com
117812302Sgabeblack@google.com    # Constructor.  Automatically adds models to CpuModel.dict.
11794382Sbinkertn@umich.edu    def __init__(self, name, default=False):
11804382Sbinkertn@umich.edu        self.name = name           # name of model
11814382Sbinkertn@umich.edu
11824382Sbinkertn@umich.edu        # This cpu is enabled by default
11834382Sbinkertn@umich.edu        self.default = default
11844382Sbinkertn@umich.edu
11854382Sbinkertn@umich.edu        # Add self to dict
11864382Sbinkertn@umich.edu        if name in CpuModel.dict:
118712302Sgabeblack@google.com            raise AttributeError, "CpuModel '%s' already registered" % name
11884382Sbinkertn@umich.edu        CpuModel.dict[name] = self
118912797Sgabeblack@google.com
119012797Sgabeblack@google.comExport('CpuModel')
11912655Sstever@eecs.umich.edu
11922655Sstever@eecs.umich.edu# Sticky variables get saved in the variables file so they persist from
11932655Sstever@eecs.umich.edu# one invocation to the next (unless overridden, in which case the new
11942655Sstever@eecs.umich.edu# value becomes sticky).
119512063Sgabeblack@google.comsticky_vars = Variables(args=ARGUMENTS)
11965601Snate@binkert.orgExport('sticky_vars')
11975601Snate@binkert.org
119812222Sgabeblack@google.com# Sticky variables that should be exported
119912222Sgabeblack@google.comexport_vars = []
12005522Snate@binkert.orgExport('export_vars')
12015863Snate@binkert.org
12025601Snate@binkert.org# For Ruby
12035601Snate@binkert.orgall_protocols = []
12045601Snate@binkert.orgExport('all_protocols')
120512302Sgabeblack@google.comprotocol_dirs = []
120610453SAndrew.Bardsley@arm.comExport('protocol_dirs')
120711988Sandreas.sandberg@arm.comslicc_includes = []
120811988Sandreas.sandberg@arm.comExport('slicc_includes')
120910453SAndrew.Bardsley@arm.com
121012302Sgabeblack@google.com# Walk the tree and execute all SConsopts scripts that wil add to the
121110453SAndrew.Bardsley@arm.com# above variables
121211983Sgabeblack@google.comif GetOption('verbose'):
121311983Sgabeblack@google.com    print "Reading SConsopts"
121412302Sgabeblack@google.comfor bdir in [ base_dir ] + extras_dir_list:
121512302Sgabeblack@google.com    if not isdir(bdir):
121612362Sgabeblack@google.com        print "Error: directory '%s' does not exist" % bdir
121712362Sgabeblack@google.com        Exit(1)
121811983Sgabeblack@google.com    for root, dirs, files in os.walk(bdir):
121912302Sgabeblack@google.com        if 'SConsopts' in files:
122012302Sgabeblack@google.com            if GetOption('verbose'):
122111983Sgabeblack@google.com                print "Reading", joinpath(root, 'SConsopts')
122211983Sgabeblack@google.com            SConscript(joinpath(root, 'SConsopts'))
122311983Sgabeblack@google.com
122412362Sgabeblack@google.comall_isa_list.sort()
122512362Sgabeblack@google.comall_gpu_isa_list.sort()
122612310Sgabeblack@google.com
122712063Sgabeblack@google.comsticky_vars.AddVariables(
122812063Sgabeblack@google.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
122912063Sgabeblack@google.com    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
123012310Sgabeblack@google.com    ListVariable('CPU_MODELS', 'CPU models',
123112310Sgabeblack@google.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
123212063Sgabeblack@google.com                 sorted(CpuModel.dict.keys())),
123312063Sgabeblack@google.com    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
123411983Sgabeblack@google.com                 False),
123511983Sgabeblack@google.com    BoolVariable('SS_COMPATIBLE_FP',
123611983Sgabeblack@google.com                 'Make floating-point results compatible with SimpleScalar',
123712310Sgabeblack@google.com                 False),
123812310Sgabeblack@google.com    BoolVariable('USE_SSE2',
123911983Sgabeblack@google.com                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
124011983Sgabeblack@google.com                 False),
124111983Sgabeblack@google.com    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
124211983Sgabeblack@google.com    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
124312310Sgabeblack@google.com    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
124412310Sgabeblack@google.com    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
12456143Snate@binkert.org    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
124612362Sgabeblack@google.com    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
124712306Sgabeblack@google.com                  all_protocols),
124812310Sgabeblack@google.com    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
124910453SAndrew.Bardsley@arm.com                 backtrace_impls[-1], backtrace_impls)
125012362Sgabeblack@google.com    )
125112306Sgabeblack@google.com
125212310Sgabeblack@google.com# These variables get exported to #defines in config/*.hh (see src/SConscript).
12535554Snate@binkert.orgexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
125412797Sgabeblack@google.com                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL',
125512797Sgabeblack@google.com                'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
12565522Snate@binkert.org
12575522Snate@binkert.org###################################################
12585797Snate@binkert.org#
12595797Snate@binkert.org# Define a SCons builder for configuration flag headers.
12605522Snate@binkert.org#
126112797Sgabeblack@google.com###################################################
126212797Sgabeblack@google.com
126312797Sgabeblack@google.com# This function generates a config header file that #defines the
126412797Sgabeblack@google.com# variable symbol to the current variable setting (0 or 1).  The source
126512797Sgabeblack@google.com# operands are the name of the variable and a Value node containing the
12668233Snate@binkert.org# value of the variable.
126712797Sgabeblack@google.comdef build_config_file(target, source, env):
126812797Sgabeblack@google.com    (variable, value) = [s.get_contents() for s in source]
12698235Snate@binkert.org    f = file(str(target[0]), 'w')
127012797Sgabeblack@google.com    print >> f, '#define', variable, value
127112797Sgabeblack@google.com    f.close()
127212797Sgabeblack@google.com    return None
127312370Sgabeblack@google.com
127412797Sgabeblack@google.com# Combine the two functions into a scons Action object.
127512797Sgabeblack@google.comconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
127612313Sgabeblack@google.com
127712797Sgabeblack@google.com# The emitter munges the source & target node lists to reflect what
12786143Snate@binkert.org# we're really doing.
127912797Sgabeblack@google.comdef config_emitter(target, source, env):
12808334Snate@binkert.org    # extract variable name from Builder arg
12818334Snate@binkert.org    variable = str(target[0])
128211993Sgabeblack@google.com    # True target is config header file
128311993Sgabeblack@google.com    target = joinpath('config', variable.lower() + '.hh')
128412223Sgabeblack@google.com    val = env[variable]
128511993Sgabeblack@google.com    if isinstance(val, bool):
12862655Sstever@eecs.umich.edu        # Force value to 0/1
12879225Sandreas.hansson@arm.com        val = int(val)
12889225Sandreas.hansson@arm.com    elif isinstance(val, str):
12899226Sandreas.hansson@arm.com        val = '"' + val + '"'
12909226Sandreas.hansson@arm.com
12919225Sandreas.hansson@arm.com    # Sources are variable name & value (packaged in SCons Value nodes)
12929226Sandreas.hansson@arm.com    return ([target], [Value(variable), Value(val)])
12939226Sandreas.hansson@arm.com
12949226Sandreas.hansson@arm.comconfig_builder = Builder(emitter = config_emitter, action = config_action)
12959226Sandreas.hansson@arm.com
12969226Sandreas.hansson@arm.commain.Append(BUILDERS = { 'ConfigFile' : config_builder })
12979226Sandreas.hansson@arm.com
12989225Sandreas.hansson@arm.com# libelf build is shared across all configs in the build root.
12999227Sandreas.hansson@arm.commain.SConscript('ext/libelf/SConscript',
13009227Sandreas.hansson@arm.com                variant_dir = joinpath(build_root, 'libelf'))
13019227Sandreas.hansson@arm.com
13029227Sandreas.hansson@arm.com# iostream3 build is shared across all configs in the build root.
13038946Sandreas.hansson@arm.commain.SConscript('ext/iostream3/SConscript',
13043918Ssaidi@eecs.umich.edu                variant_dir = joinpath(build_root, 'iostream3'))
13059225Sandreas.hansson@arm.com
13063918Ssaidi@eecs.umich.edu# libfdt build is shared across all configs in the build root.
13079225Sandreas.hansson@arm.commain.SConscript('ext/libfdt/SConscript',
13089225Sandreas.hansson@arm.com                variant_dir = joinpath(build_root, 'libfdt'))
13099227Sandreas.hansson@arm.com
13109227Sandreas.hansson@arm.com# fputils build is shared across all configs in the build root.
13119227Sandreas.hansson@arm.commain.SConscript('ext/fputils/SConscript',
13129226Sandreas.hansson@arm.com                variant_dir = joinpath(build_root, 'fputils'))
13139225Sandreas.hansson@arm.com
13149227Sandreas.hansson@arm.com# DRAMSim2 build is shared across all configs in the build root.
13159227Sandreas.hansson@arm.commain.SConscript('ext/dramsim2/SConscript',
13169227Sandreas.hansson@arm.com                variant_dir = joinpath(build_root, 'dramsim2'))
13179227Sandreas.hansson@arm.com
13188946Sandreas.hansson@arm.com# DRAMPower build is shared across all configs in the build root.
13199225Sandreas.hansson@arm.commain.SConscript('ext/drampower/SConscript',
13209226Sandreas.hansson@arm.com                variant_dir = joinpath(build_root, 'drampower'))
13219226Sandreas.hansson@arm.com
13229226Sandreas.hansson@arm.com# nomali build is shared across all configs in the build root.
13233515Ssaidi@eecs.umich.edumain.SConscript('ext/nomali/SConscript',
132412563Sgabeblack@google.com                variant_dir = joinpath(build_root, 'nomali'))
13254762Snate@binkert.org
13263515Ssaidi@eecs.umich.edu###################################################
13278881Smarc.orr@gmail.com#
13288881Smarc.orr@gmail.com# This function is used to set up a directory with switching headers
13298881Smarc.orr@gmail.com#
13308881Smarc.orr@gmail.com###################################################
13318881Smarc.orr@gmail.com
13329226Sandreas.hansson@arm.commain['ALL_ISA_LIST'] = all_isa_list
13339226Sandreas.hansson@arm.commain['ALL_GPU_ISA_LIST'] = all_gpu_isa_list
13349226Sandreas.hansson@arm.comall_isa_deps = {}
13358881Smarc.orr@gmail.comdef make_switching_dir(dname, switch_headers, env):
13368881Smarc.orr@gmail.com    # Generate the header.  target[0] is the full path of the output
13378881Smarc.orr@gmail.com    # header to generate.  'source' is a dummy variable, since we get the
13388881Smarc.orr@gmail.com    # list of ISAs from env['ALL_ISA_LIST'].
13398881Smarc.orr@gmail.com    def gen_switch_hdr(target, source, env):
13408881Smarc.orr@gmail.com        fname = str(target[0])
13418881Smarc.orr@gmail.com        isa = env['TARGET_ISA'].lower()
13428881Smarc.orr@gmail.com        try:
13438881Smarc.orr@gmail.com            f = open(fname, 'w')
13448881Smarc.orr@gmail.com            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
13458881Smarc.orr@gmail.com            f.close()
13468881Smarc.orr@gmail.com        except IOError:
13478881Smarc.orr@gmail.com            print "Failed to create %s" % fname
13488881Smarc.orr@gmail.com            raise
13498881Smarc.orr@gmail.com
13508881Smarc.orr@gmail.com    # Build SCons Action object. 'varlist' specifies env vars that this
135113508Snikos.nikoleris@arm.com    # action depends on; when env['ALL_ISA_LIST'] changes these actions
135213508Snikos.nikoleris@arm.com    # should get re-executed.
135313508Snikos.nikoleris@arm.com    switch_hdr_action = MakeAction(gen_switch_hdr,
135413508Snikos.nikoleris@arm.com                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
135513508Snikos.nikoleris@arm.com
135613508Snikos.nikoleris@arm.com    # Instantiate actions for each header
135713508Snikos.nikoleris@arm.com    for hdr in switch_headers:
135813508Snikos.nikoleris@arm.com        env.Command(hdr, [], switch_hdr_action)
135913508Snikos.nikoleris@arm.com
136012222Sgabeblack@google.com    isa_target = Dir('.').up().name.lower().replace('_', '-')
136112222Sgabeblack@google.com    env['PHONY_BASE'] = '#'+isa_target
136212222Sgabeblack@google.com    all_isa_deps[isa_target] = None
136312222Sgabeblack@google.com
136412222Sgabeblack@google.comExport('make_switching_dir')
136513508Snikos.nikoleris@arm.com
136613508Snikos.nikoleris@arm.comdef make_gpu_switching_dir(dname, switch_headers, env):
1367955SN/A    # Generate the header.  target[0] is the full path of the output
136812222Sgabeblack@google.com    # header to generate.  'source' is a dummy variable, since we get the
136912222Sgabeblack@google.com    # list of ISAs from env['ALL_ISA_LIST'].
137012222Sgabeblack@google.com    def gen_switch_hdr(target, source, env):
137112222Sgabeblack@google.com        fname = str(target[0])
137212222Sgabeblack@google.com
137313508Snikos.nikoleris@arm.com        isa = env['TARGET_GPU_ISA'].lower()
137413508Snikos.nikoleris@arm.com
1375955SN/A        try:
137612222Sgabeblack@google.com            f = open(fname, 'w')
137712222Sgabeblack@google.com            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
137813508Snikos.nikoleris@arm.com            f.close()
137912222Sgabeblack@google.com        except IOError:
138012222Sgabeblack@google.com            print "Failed to create %s" % fname
138112222Sgabeblack@google.com            raise
138212222Sgabeblack@google.com
138312222Sgabeblack@google.com    # Build SCons Action object. 'varlist' specifies env vars that this
138412222Sgabeblack@google.com    # action depends on; when env['ALL_ISA_LIST'] changes these actions
138512222Sgabeblack@google.com    # should get re-executed.
13861869SN/A    switch_hdr_action = MakeAction(gen_switch_hdr,
138712222Sgabeblack@google.com                          Transform("GENERATE"), varlist=['ALL_ISA_GPU_LIST'])
138812222Sgabeblack@google.com
138912222Sgabeblack@google.com    # Instantiate actions for each header
139012222Sgabeblack@google.com    for hdr in switch_headers:
139112222Sgabeblack@google.com        env.Command(hdr, [], switch_hdr_action)
139213508Snikos.nikoleris@arm.com
139313508Snikos.nikoleris@arm.comExport('make_gpu_switching_dir')
13949226Sandreas.hansson@arm.com
139512222Sgabeblack@google.com# all-isas -> all-deps -> all-environs -> all_targets
139612222Sgabeblack@google.commain.Alias('#all-isas', [])
139712222Sgabeblack@google.commain.Alias('#all-deps', '#all-isas')
139812222Sgabeblack@google.com
139912222Sgabeblack@google.com# Dummy target to ensure all environments are created before telling
140013508Snikos.nikoleris@arm.com# SCons what to actually make (the command line arguments).  We attach
140113508Snikos.nikoleris@arm.com# them to the dependence graph after the environments are complete.
1402ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1403def environsComplete(target, source, env):
1404    for t in ORIG_BUILD_TARGETS:
1405        main.Depends('#all-targets', t)
1406
1407# Each build/* switching_dir attaches its *-environs target to #all-environs.
1408main.Append(BUILDERS = {'CompleteEnvirons' :
1409                        Builder(action=MakeAction(environsComplete, None))})
1410main.CompleteEnvirons('#all-environs', [])
1411
1412def doNothing(**ignored): pass
1413main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1414
1415# The final target to which all the original targets ultimately get attached.
1416main.Dummy('#all-targets', '#all-environs')
1417BUILD_TARGETS[:] = ['#all-targets']
1418
1419###################################################
1420#
1421# Define build environments for selected configurations.
1422#
1423###################################################
1424
1425for variant_path in variant_paths:
1426    if not GetOption('silent'):
1427        print "Building in", variant_path
1428
1429    # Make a copy of the build-root environment to use for this config.
1430    env = main.Clone()
1431    env['BUILDDIR'] = variant_path
1432
1433    # variant_dir is the tail component of build path, and is used to
1434    # determine the build parameters (e.g., 'ALPHA_SE')
1435    (build_root, variant_dir) = splitpath(variant_path)
1436
1437    # Set env variables according to the build directory config.
1438    sticky_vars.files = []
1439    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1440    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1441    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1442    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1443    if isfile(current_vars_file):
1444        sticky_vars.files.append(current_vars_file)
1445        if not GetOption('silent'):
1446            print "Using saved variables file %s" % current_vars_file
1447    else:
1448        # Build dir-specific variables file doesn't exist.
1449
1450        # Make sure the directory is there so we can create it later
1451        opt_dir = dirname(current_vars_file)
1452        if not isdir(opt_dir):
1453            mkdir(opt_dir)
1454
1455        # Get default build variables from source tree.  Variables are
1456        # normally determined by name of $VARIANT_DIR, but can be
1457        # overridden by '--default=' arg on command line.
1458        default = GetOption('default')
1459        opts_dir = joinpath(main.root.abspath, 'build_opts')
1460        if default:
1461            default_vars_files = [joinpath(build_root, 'variables', default),
1462                                  joinpath(opts_dir, default)]
1463        else:
1464            default_vars_files = [joinpath(opts_dir, variant_dir)]
1465        existing_files = filter(isfile, default_vars_files)
1466        if existing_files:
1467            default_vars_file = existing_files[0]
1468            sticky_vars.files.append(default_vars_file)
1469            print "Variables file %s not found,\n  using defaults in %s" \
1470                  % (current_vars_file, default_vars_file)
1471        else:
1472            print "Error: cannot find variables file %s or " \
1473                  "default file(s) %s" \
1474                  % (current_vars_file, ' or '.join(default_vars_files))
1475            Exit(1)
1476
1477    # Apply current variable settings to env
1478    sticky_vars.Update(env)
1479
1480    help_texts["local_vars"] += \
1481        "Build variables for %s:\n" % variant_dir \
1482                 + sticky_vars.GenerateHelpText(env)
1483
1484    # Process variable settings.
1485
1486    if not have_fenv and env['USE_FENV']:
1487        print "Warning: <fenv.h> not available; " \
1488              "forcing USE_FENV to False in", variant_dir + "."
1489        env['USE_FENV'] = False
1490
1491    if not env['USE_FENV']:
1492        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1493        print "         FP results may deviate slightly from other platforms."
1494
1495    if env['EFENCE']:
1496        env.Append(LIBS=['efence'])
1497
1498    if env['USE_KVM']:
1499        if not have_kvm:
1500            print "Warning: Can not enable KVM, host seems to lack KVM support"
1501            env['USE_KVM'] = False
1502        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1503            print "Info: KVM support disabled due to unsupported host and " \
1504                "target ISA combination"
1505            env['USE_KVM'] = False
1506
1507    # Warn about missing optional functionality
1508    if env['USE_KVM']:
1509        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1510            print "Warning: perf_event headers lack support for the " \
1511                "exclude_host attribute. KVM instruction counts will " \
1512                "be inaccurate."
1513
1514    # Save sticky variable settings back to current variables file
1515    sticky_vars.Save(current_vars_file, env)
1516
1517    if env['USE_SSE2']:
1518        env.Append(CCFLAGS=['-msse2'])
1519
1520    # The src/SConscript file sets up the build rules in 'env' according
1521    # to the configured variables.  It returns a list of environments,
1522    # one for each variant build (debug, opt, etc.)
1523    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1524
1525def pairwise(iterable):
1526    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1527    a, b = itertools.tee(iterable)
1528    b.next()
1529    return itertools.izip(a, b)
1530
1531# Create false dependencies so SCons will parse ISAs, establish
1532# dependencies, and setup the build Environments serially. Either
1533# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1534# greater than 1. It appears to be standard race condition stuff; it
1535# doesn't always fail, but usually, and the behaviors are different.
1536# Every time I tried to remove this, builds would fail in some
1537# creative new way. So, don't do that. You'll want to, though, because
1538# tests/SConscript takes a long time to make its Environments.
1539for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1540    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1541    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1542
1543# base help text
1544Help('''
1545Usage: scons [scons options] [build variables] [target(s)]
1546
1547Extra scons options:
1548%(options)s
1549
1550Global build variables:
1551%(global_vars)s
1552
1553%(local_vars)s
1554''' % help_texts)
1555