SConstruct revision 12063
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#
48955SN/A# SCons top-level build description (SConstruct) file.
495522Snate@binkert.org#
50955SN/A# While in this directory ('gem5'), just type 'scons' to build the default
515522Snate@binkert.org# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
524202Sbinkertn@umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
535742Snate@binkert.org# the optimized full-system version).
54955SN/A#
554381Sbinkertn@umich.edu# You can build gem5 in a different directory as long as there is a
564381Sbinkertn@umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
5712246Sgabeblack@google.com# expects that all configs under the same build directory are being
5812246Sgabeblack@google.com# built for the same host system.
598334Snate@binkert.org#
60955SN/A# Examples:
61955SN/A#
624202Sbinkertn@umich.edu#   The following two commands are equivalent.  The '-u' option tells
63955SN/A#   scons to search up the directory tree for this SConstruct file.
644382Sbinkertn@umich.edu#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
654382Sbinkertn@umich.edu#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
664382Sbinkertn@umich.edu#
676654Snate@binkert.org#   The following two commands are equivalent and demonstrate building
685517Snate@binkert.org#   in a directory outside of the source tree.  The '-C' option tells
698614Sgblack@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
707674Snate@binkert.org#   file.
716143Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
726143Snate@binkert.org#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
736143Snate@binkert.org#
7412302Sgabeblack@google.com# You can use 'scons -H' to print scons options.  If you're in this
7512302Sgabeblack@google.com# '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
7712371Sgabeblack@google.com# options as well.
7812371Sgabeblack@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
12412302Sgabeblack@google.com# SCons includes
12512371Sgabeblack@google.comimport SCons
12612302Sgabeblack@google.comimport SCons.Node
12712371Sgabeblack@google.com
12812302Sgabeblack@google.comextra_python_paths = [
12912302Sgabeblack@google.com    Dir('src/python').srcnode().abspath, # gem5 includes
13012371Sgabeblack@google.com    Dir('ext/ply').srcnode().abspath, # ply is used by several files
13112371Sgabeblack@google.com    ]
13212371Sgabeblack@google.com
13312371Sgabeblack@google.comsys.path[1:1] = extra_python_paths
13412302Sgabeblack@google.com
13512371Sgabeblack@google.comfrom m5.util import compareVersions, readCommand
13612371Sgabeblack@google.comfrom m5.util.terminal import get_termcap
13712371Sgabeblack@google.com
13812371Sgabeblack@google.comhelp_texts = {
13911983Sgabeblack@google.com    "options" : "",
1406143Snate@binkert.org    "global_vars" : "",
1418233Snate@binkert.org    "local_vars" : ""
14212302Sgabeblack@google.com}
1436143Snate@binkert.org
1446143Snate@binkert.orgExport("help_texts")
14512302Sgabeblack@google.com
1464762Snate@binkert.org
1476143Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
1488233Snate@binkert.org# AddOption() are supposed to be displayed when you type 'scons -h'
1498233Snate@binkert.org# and (2) you can override the help displayed by 'scons -h' using the
15012302Sgabeblack@google.com# Help() function, but these two features are incompatible: once
15112302Sgabeblack@google.com# you've overridden the help text using Help(), there's no way to get
1526143Snate@binkert.org# at the help texts from AddOptions.  See:
15312362Sgabeblack@google.com#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
15412362Sgabeblack@google.com#     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
15712302Sgabeblack@google.com# we can just use AddOption directly.
15812302Sgabeblack@google.comdef AddLocalOption(*args, **kwargs):
15912302Sgabeblack@google.com    col_width = 30
16012302Sgabeblack@google.com
16112302Sgabeblack@google.com    help = "  " + ", ".join(args)
16212363Sgabeblack@google.com    if "help" in kwargs:
16312363Sgabeblack@google.com        length = len(help)
16412363Sgabeblack@google.com        if length >= col_width:
16512363Sgabeblack@google.com            help += "\n" + " " * col_width
16612302Sgabeblack@google.com        else:
16712363Sgabeblack@google.com            help += " " * (col_width - length)
16812363Sgabeblack@google.com        help += kwargs["help"]
16912363Sgabeblack@google.com    help_texts["options"] += help + "\n"
17012363Sgabeblack@google.com
17112363Sgabeblack@google.com    AddOption(*args, **kwargs)
1728233Snate@binkert.org
1736143Snate@binkert.orgAddLocalOption('--colors', dest='use_colors', action='store_true',
1746143Snate@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')
1827065Snate@binkert.orgAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1836143Snate@binkert.org               help='Disable style checking hooks')
18412362Sgabeblack@google.comAddLocalOption('--no-lto', dest='no_lto', action='store_true',
18512362Sgabeblack@google.com               help='Disable Link-Time Optimization for fast')
18612362Sgabeblack@google.comAddLocalOption('--force-lto', dest='force_lto', action='store_true',
18712362Sgabeblack@google.com               help='Use Link-Time Optimization instead of partial linking' +
18812362Sgabeblack@google.com                    ' when the compiler doesn\'t support using them together.')
18912362Sgabeblack@google.comAddLocalOption('--update-ref', dest='update_ref', action='store_true',
19012362Sgabeblack@google.com               help='Update test reference outputs')
19112362Sgabeblack@google.comAddLocalOption('--verbose', dest='verbose', action='store_true',
19212362Sgabeblack@google.com               help='Print full tool command lines')
19312362Sgabeblack@google.comAddLocalOption('--without-python', dest='without_python',
19412362Sgabeblack@google.com               action='store_true',
19512362Sgabeblack@google.com               help='Build without Python configuration support')
1968233Snate@binkert.orgAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1978233Snate@binkert.org               action='store_true',
1988233Snate@binkert.org               help='Disable linking against tcmalloc')
1998233Snate@binkert.orgAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
2008233Snate@binkert.org               help='Build with Undefined Behavior Sanitizer if available')
2018233Snate@binkert.orgAddLocalOption('--with-asan', dest='with_asan', action='store_true',
2028233Snate@binkert.org               help='Build with Address Sanitizer if available')
2038233Snate@binkert.org
2048233Snate@binkert.orgif GetOption('no_lto') and GetOption('force_lto'):
2058233Snate@binkert.org    print '--no-lto and --force-lto are mutually exclusive'
2068233Snate@binkert.org    Exit(1)
2078233Snate@binkert.org
2088233Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
2098233Snate@binkert.org
2108233Snate@binkert.org########################################################################
2118233Snate@binkert.org#
2128233Snate@binkert.org# Set up the main build environment.
2138233Snate@binkert.org#
2148233Snate@binkert.org########################################################################
2158233Snate@binkert.org
2168233Snate@binkert.org# export TERM so that clang reports errors in color
2176143Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2186143Snate@binkert.org                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2196143Snate@binkert.org                 'PYTHONPATH', 'RANLIB', 'TERM' ])
2206143Snate@binkert.org
2216143Snate@binkert.orguse_prefixes = [
2226143Snate@binkert.org    "ASAN_",           # address sanitizer symbolizer path and settings
2239982Satgutier@umich.edu    "CCACHE_",         # ccache (caching compiler wrapper) configuration
22413576Sciro.santilli@arm.com    "CCC_",            # clang static analyzer configuration
22513576Sciro.santilli@arm.com    "DISTCC_",         # distcc (distributed compiler wrapper) configuration
22613576Sciro.santilli@arm.com    "INCLUDE_SERVER_", # distcc pump server settings
22713576Sciro.santilli@arm.com    "M5",              # M5 configuration (e.g., path to kernels)
22813576Sciro.santilli@arm.com    ]
22913576Sciro.santilli@arm.com
23013576Sciro.santilli@arm.comuse_env = {}
23113576Sciro.santilli@arm.comfor key,val in sorted(os.environ.iteritems()):
23213576Sciro.santilli@arm.com    if key in use_vars or \
23313576Sciro.santilli@arm.com            any([key.startswith(prefix) for prefix in use_prefixes]):
23413576Sciro.santilli@arm.com        use_env[key] = val
23513576Sciro.santilli@arm.com
23613576Sciro.santilli@arm.com# Tell scons to avoid implicit command dependencies to avoid issues
23713576Sciro.santilli@arm.com# with the param wrappes being compiled twice (see
23813576Sciro.santilli@arm.com# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
23913576Sciro.santilli@arm.commain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
24013576Sciro.santilli@arm.commain.Decider('MD5-timestamp')
24113576Sciro.santilli@arm.commain.root = Dir(".")         # The current directory (where this file lives).
24213576Sciro.santilli@arm.commain.srcdir = Dir("src")     # The source directory
24313576Sciro.santilli@arm.com
24413576Sciro.santilli@arm.commain_dict_keys = main.Dictionary().keys()
24513576Sciro.santilli@arm.com
24613576Sciro.santilli@arm.com# Check that we have a C/C++ compiler
24713576Sciro.santilli@arm.comif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
24813576Sciro.santilli@arm.com    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
24913576Sciro.santilli@arm.com    Exit(1)
25013576Sciro.santilli@arm.com
25113576Sciro.santilli@arm.com# add useful python code PYTHONPATH so it can be used by subprocesses
25213576Sciro.santilli@arm.com# as well
25313576Sciro.santilli@arm.commain.AppendENVPath('PYTHONPATH', extra_python_paths)
25413576Sciro.santilli@arm.com
25513576Sciro.santilli@arm.com########################################################################
25613630Sciro.santilli@arm.com#
25713630Sciro.santilli@arm.com# Mercurial Stuff.
25813576Sciro.santilli@arm.com#
25913576Sciro.santilli@arm.com# If the gem5 directory is a mercurial repository, we should do some
26013576Sciro.santilli@arm.com# extra things.
26113576Sciro.santilli@arm.com#
26213576Sciro.santilli@arm.com########################################################################
26313576Sciro.santilli@arm.com
26413576Sciro.santilli@arm.comhgdir = main.root.Dir(".hg")
26513576Sciro.santilli@arm.com
26613576Sciro.santilli@arm.com
26713576Sciro.santilli@arm.comstyle_message = """
26813576Sciro.santilli@arm.comYou're missing the gem5 style hook, which automatically checks your code
26913576Sciro.santilli@arm.comagainst the gem5 style rules on %s.
27013576Sciro.santilli@arm.comThis script will now install the hook in your %s.
27113576Sciro.santilli@arm.comPress enter to continue, or ctrl-c to abort: """
27213576Sciro.santilli@arm.com
27313576Sciro.santilli@arm.commercurial_style_message = """
27413576Sciro.santilli@arm.comYou're missing the gem5 style hook, which automatically checks your code
27513576Sciro.santilli@arm.comagainst the gem5 style rules on hg commit and qrefresh commands.
27613576Sciro.santilli@arm.comThis script will now install the hook in your .hg/hgrc file.
27713576Sciro.santilli@arm.comPress enter to continue, or ctrl-c to abort: """
27813576Sciro.santilli@arm.com
27913576Sciro.santilli@arm.comgit_style_message = """
28013576Sciro.santilli@arm.comYou're missing the gem5 style or commit message hook. These hooks help
28113576Sciro.santilli@arm.comto ensure that your code follows gem5's style rules on git commit.
28213576Sciro.santilli@arm.comThis script will now install the hook in your .git/hooks/ directory.
28313576Sciro.santilli@arm.comPress enter to continue, or ctrl-c to abort: """
28413576Sciro.santilli@arm.com
28513576Sciro.santilli@arm.commercurial_style_upgrade_message = """
28613576Sciro.santilli@arm.comYour Mercurial style hooks are not up-to-date. This script will now
28713576Sciro.santilli@arm.comtry to automatically update them. A backup of your hgrc will be saved
28813576Sciro.santilli@arm.comin .hg/hgrc.old.
28913576Sciro.santilli@arm.comPress enter to continue, or ctrl-c to abort: """
29013576Sciro.santilli@arm.com
29113576Sciro.santilli@arm.commercurial_style_hook = """
29213576Sciro.santilli@arm.com# The following lines were automatically added by gem5/SConstruct
29313576Sciro.santilli@arm.com# to provide the gem5 style-checking hooks
29413576Sciro.santilli@arm.com[extensions]
29513577Sciro.santilli@arm.comhgstyle = %s/util/hgstyle.py
29613577Sciro.santilli@arm.com
29713577Sciro.santilli@arm.com[hooks]
2986143Snate@binkert.orgpretxncommit.style = python:hgstyle.check_style
29912302Sgabeblack@google.compre-qrefresh.style = python:hgstyle.check_style
30012302Sgabeblack@google.com# End of SConstruct additions
30112302Sgabeblack@google.com
30212302Sgabeblack@google.com""" % (main.root.abspath)
30312302Sgabeblack@google.com
30412302Sgabeblack@google.commercurial_lib_not_found = """
30512302Sgabeblack@google.comMercurial libraries cannot be found, ignoring style hook.  If
30612302Sgabeblack@google.comyou are a gem5 developer, please fix this and run the style
30711983Sgabeblack@google.comhook. It is important.
30811983Sgabeblack@google.com"""
30911983Sgabeblack@google.com
31012302Sgabeblack@google.com# Check for style hook and prompt for installation if it's not there.
31112302Sgabeblack@google.com# Skip this if --ignore-style was specified, there's no interactive
31212302Sgabeblack@google.com# terminal to prompt, or no recognized revision control system can be
31312302Sgabeblack@google.com# found.
31412302Sgabeblack@google.comignore_style = GetOption('ignore_style') or not sys.stdin.isatty()
31512302Sgabeblack@google.com
31611983Sgabeblack@google.com# Try wire up Mercurial to the style hooks
3176143Snate@binkert.orgif not ignore_style and hgdir.exists():
31812305Sgabeblack@google.com    style_hook = True
31912302Sgabeblack@google.com    style_hooks = tuple()
32012302Sgabeblack@google.com    hgrc = hgdir.File('hgrc')
32112302Sgabeblack@google.com    hgrc_old = hgdir.File('hgrc.old')
3226143Snate@binkert.org    try:
3236143Snate@binkert.org        from mercurial import ui
3246143Snate@binkert.org        ui = ui.ui()
3255522Snate@binkert.org        ui.readconfig(hgrc.abspath)
3266143Snate@binkert.org        style_hooks = (ui.config('hooks', 'pretxncommit.style', None),
3276143Snate@binkert.org                       ui.config('hooks', 'pre-qrefresh.style', None))
3286143Snate@binkert.org        style_hook = all(style_hooks)
3299982Satgutier@umich.edu        style_extension = ui.config('extensions', 'style', None)
33012302Sgabeblack@google.com    except ImportError:
33112302Sgabeblack@google.com        print mercurial_lib_not_found
33212302Sgabeblack@google.com
3336143Snate@binkert.org    if "python:style.check_style" in style_hooks:
3346143Snate@binkert.org        # Try to upgrade the style hooks
3356143Snate@binkert.org        print mercurial_style_upgrade_message
3366143Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
3375522Snate@binkert.org        try:
3385522Snate@binkert.org            raw_input()
3395522Snate@binkert.org        except:
3405522Snate@binkert.org            print "Input exception, exiting scons.\n"
3415604Snate@binkert.org            sys.exit(1)
3425604Snate@binkert.org        shutil.copyfile(hgrc.abspath, hgrc_old.abspath)
3436143Snate@binkert.org        re_style_hook = re.compile(r"^([^=#]+)\.style\s*=\s*([^#\s]+).*")
3446143Snate@binkert.org        re_style_extension = re.compile("style\s*=\s*([^#\s]+).*")
3454762Snate@binkert.org        old, new = open(hgrc_old.abspath, 'r'), open(hgrc.abspath, 'w')
3464762Snate@binkert.org        for l in old:
3476143Snate@binkert.org            m_hook = re_style_hook.match(l)
3486727Ssteve.reinhardt@amd.com            m_ext = re_style_extension.match(l)
3496727Ssteve.reinhardt@amd.com            if m_hook:
3506727Ssteve.reinhardt@amd.com                hook, check = m_hook.groups()
3514762Snate@binkert.org                if check != "python:style.check_style":
3526143Snate@binkert.org                    print "Warning: %s.style is using a non-default " \
3536143Snate@binkert.org                        "checker: %s" % (hook, check)
3546143Snate@binkert.org                if hook not in ("pretxncommit", "pre-qrefresh"):
3556143Snate@binkert.org                    print "Warning: Updating unknown style hook: %s" % hook
3566727Ssteve.reinhardt@amd.com
3576143Snate@binkert.org                l = "%s.style = python:hgstyle.check_style\n" % hook
3587674Snate@binkert.org            elif m_ext and m_ext.group(1) == style_extension:
3597674Snate@binkert.org                l = "hgstyle = %s/util/hgstyle.py\n" % main.root.abspath
3605604Snate@binkert.org
3616143Snate@binkert.org            new.write(l)
3626143Snate@binkert.org    elif not style_hook:
3636143Snate@binkert.org        print mercurial_style_message,
3644762Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
3656143Snate@binkert.org        try:
3664762Snate@binkert.org            raw_input()
3674762Snate@binkert.org        except:
3684762Snate@binkert.org            print "Input exception, exiting scons.\n"
3696143Snate@binkert.org            sys.exit(1)
3706143Snate@binkert.org        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3714762Snate@binkert.org        print "Adding style hook to", hgrc_path, "\n"
37212302Sgabeblack@google.com        try:
37312302Sgabeblack@google.com            with open(hgrc_path, 'a') as f:
3748233Snate@binkert.org                f.write(mercurial_style_hook)
37512302Sgabeblack@google.com        except:
3766143Snate@binkert.org            print "Error updating", hgrc_path
3776143Snate@binkert.org            sys.exit(1)
3784762Snate@binkert.org
3796143Snate@binkert.orgdef install_git_style_hooks():
3804762Snate@binkert.org    try:
3819396Sandreas.hansson@arm.com        gitdir = Dir(readCommand(
3829396Sandreas.hansson@arm.com            ["git", "rev-parse", "--git-dir"]).strip("\n"))
3839396Sandreas.hansson@arm.com    except Exception, e:
38412302Sgabeblack@google.com        print "Warning: Failed to find git repo directory: %s" % e
38512302Sgabeblack@google.com        return
38612302Sgabeblack@google.com
3879396Sandreas.hansson@arm.com    git_hooks = gitdir.Dir("hooks")
3889396Sandreas.hansson@arm.com    def hook_exists(hook_name):
3899396Sandreas.hansson@arm.com        hook = git_hooks.File(hook_name)
3909396Sandreas.hansson@arm.com        return hook.exists()
3919396Sandreas.hansson@arm.com
3929396Sandreas.hansson@arm.com    def hook_install(hook_name, script):
3939396Sandreas.hansson@arm.com        hook = git_hooks.File(hook_name)
3949930Sandreas.hansson@arm.com        if hook.exists():
3959930Sandreas.hansson@arm.com            print "Warning: Can't install %s, hook already exists." % hook_name
3969396Sandreas.hansson@arm.com            return
3976143Snate@binkert.org
39812797Sgabeblack@google.com        if hook.islink():
39912797Sgabeblack@google.com            print "Warning: Removing broken symlink for hook %s." % hook_name
40012797Sgabeblack@google.com            os.unlink(hook.get_abspath())
4018235Snate@binkert.org
40212797Sgabeblack@google.com        if not git_hooks.exists():
40312797Sgabeblack@google.com            mkdir(git_hooks.get_abspath())
40412797Sgabeblack@google.com            git_hooks.clear()
40512797Sgabeblack@google.com
40612797Sgabeblack@google.com        abs_symlink_hooks = git_hooks.islink() and \
40712797Sgabeblack@google.com            os.path.isabs(os.readlink(git_hooks.get_abspath()))
40812797Sgabeblack@google.com
40912797Sgabeblack@google.com        # Use a relative symlink if the hooks live in the source directory,
41012797Sgabeblack@google.com        # and the hooks directory is not a symlink to an absolute path.
41112797Sgabeblack@google.com        if hook.is_under(main.root) and not abs_symlink_hooks:
41212797Sgabeblack@google.com            script_path = os.path.relpath(
41312797Sgabeblack@google.com                os.path.realpath(script.get_abspath()),
41412797Sgabeblack@google.com                os.path.realpath(hook.Dir(".").get_abspath()))
41512797Sgabeblack@google.com        else:
41612797Sgabeblack@google.com            script_path = script.get_abspath()
41712757Sgabeblack@google.com
41812757Sgabeblack@google.com        try:
41912797Sgabeblack@google.com            os.symlink(script_path, hook.get_abspath())
42012797Sgabeblack@google.com        except:
42112797Sgabeblack@google.com            print "Error updating git %s hook" % hook_name
42212757Sgabeblack@google.com            raise
42312757Sgabeblack@google.com
42412757Sgabeblack@google.com    if hook_exists("pre-commit") and hook_exists("commit-msg"):
42512757Sgabeblack@google.com        return
4268235Snate@binkert.org
42712302Sgabeblack@google.com    print git_style_message,
4288235Snate@binkert.org    try:
4298235Snate@binkert.org        raw_input()
43012757Sgabeblack@google.com    except:
4318235Snate@binkert.org        print "Input exception, exiting scons.\n"
4328235Snate@binkert.org        sys.exit(1)
4338235Snate@binkert.org
43412757Sgabeblack@google.com    git_style_script = File("util/git-pre-commit.py")
43512313Sgabeblack@google.com    git_msg_script = File("ext/git-commit-msg")
43612797Sgabeblack@google.com
43712797Sgabeblack@google.com    hook_install("pre-commit", git_style_script)
43812797Sgabeblack@google.com    hook_install("commit-msg", git_msg_script)
43912797Sgabeblack@google.com
44012797Sgabeblack@google.com# Try to wire up git to the style hooks
44112797Sgabeblack@google.comif not ignore_style and main.root.Entry(".git").exists():
44212797Sgabeblack@google.com    install_git_style_hooks()
44312797Sgabeblack@google.com
44412797Sgabeblack@google.com###################################################
44512797Sgabeblack@google.com#
44612797Sgabeblack@google.com# Figure out which configurations to set up based on the path(s) of
44712797Sgabeblack@google.com# the target(s).
44812797Sgabeblack@google.com#
44912797Sgabeblack@google.com###################################################
45013706Sgabeblack@google.com
45113706Sgabeblack@google.com# Find default configuration & binary.
45213706Sgabeblack@google.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
45313706Sgabeblack@google.com
45412797Sgabeblack@google.com# helper function: find last occurrence of element in list
45512797Sgabeblack@google.comdef rfind(l, elt, offs = -1):
45612797Sgabeblack@google.com    for i in range(len(l)+offs, 0, -1):
45712797Sgabeblack@google.com        if l[i] == elt:
45812797Sgabeblack@google.com            return i
45912797Sgabeblack@google.com    raise ValueError, "element not found"
46012797Sgabeblack@google.com
46112797Sgabeblack@google.com# Take a list of paths (or SCons Nodes) and return a list with all
46212797Sgabeblack@google.com# paths made absolute and ~-expanded.  Paths will be interpreted
46312797Sgabeblack@google.com# relative to the launch directory unless a different root is provided
46412797Sgabeblack@google.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
46512797Sgabeblack@google.com    return [abspath(joinpath(root, expanduser(str(p))))
46612797Sgabeblack@google.com            for p in path_list]
46712797Sgabeblack@google.com
46812797Sgabeblack@google.com# Each target must have 'build' in the interior of the path; the
46912797Sgabeblack@google.com# directory below this will determine the build parameters.  For
47012797Sgabeblack@google.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
47112797Sgabeblack@google.com# recognize that ALPHA_SE specifies the configuration because it
47212797Sgabeblack@google.com# follow 'build' in the build path.
47312797Sgabeblack@google.com
47412797Sgabeblack@google.com# The funky assignment to "[:]" is needed to replace the list contents
47512797Sgabeblack@google.com# in place rather than reassign the symbol to a new list, which
47612797Sgabeblack@google.com# doesn't work (obviously!).
47713656Sgabeblack@google.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
47812797Sgabeblack@google.com
47912797Sgabeblack@google.com# Generate a list of the unique build roots and configs that the
48012797Sgabeblack@google.com# collected targets reference.
48112797Sgabeblack@google.comvariant_paths = []
48212797Sgabeblack@google.combuild_root = None
48312797Sgabeblack@google.comfor t in BUILD_TARGETS:
48412313Sgabeblack@google.com    path_dirs = t.split('/')
48512313Sgabeblack@google.com    try:
48612797Sgabeblack@google.com        build_top = rfind(path_dirs, 'build', -2)
48712797Sgabeblack@google.com    except:
48812797Sgabeblack@google.com        print "Error: no non-leaf 'build' dir found on target path", t
48912371Sgabeblack@google.com        Exit(1)
4905584Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
49112797Sgabeblack@google.com    if not build_root:
49212797Sgabeblack@google.com        build_root = this_build_root
49312797Sgabeblack@google.com    else:
49412797Sgabeblack@google.com        if this_build_root != build_root:
49512797Sgabeblack@google.com            print "Error: build targets not under same build root\n"\
49612797Sgabeblack@google.com                  "  %s\n  %s" % (build_root, this_build_root)
49712797Sgabeblack@google.com            Exit(1)
49812797Sgabeblack@google.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
49912797Sgabeblack@google.com    if variant_path not in variant_paths:
50012797Sgabeblack@google.com        variant_paths.append(variant_path)
50112797Sgabeblack@google.com
50212797Sgabeblack@google.com# Make sure build_root exists (might not if this is the first build there)
50312797Sgabeblack@google.comif not isdir(build_root):
50412797Sgabeblack@google.com    mkdir(build_root)
50512797Sgabeblack@google.commain['BUILDROOT'] = build_root
50612797Sgabeblack@google.com
50712797Sgabeblack@google.comExport('main')
50812797Sgabeblack@google.com
50912797Sgabeblack@google.commain.SConsignFile(joinpath(build_root, "sconsign"))
51012797Sgabeblack@google.com
51112797Sgabeblack@google.com# Default duplicate option is to use hard links, but this messes up
51212797Sgabeblack@google.com# when you use emacs to edit a file in the target dir, as emacs moves
51312797Sgabeblack@google.com# file to file~ then copies to file, breaking the link.  Symbolic
51412797Sgabeblack@google.com# (soft) links work better.
51512797Sgabeblack@google.commain.SetOption('duplicate', 'soft-copy')
51612797Sgabeblack@google.com
51712797Sgabeblack@google.com#
51812797Sgabeblack@google.com# Set up global sticky variables... these are common to an entire build
51912797Sgabeblack@google.com# tree (not specific to a particular build like ALPHA_SE)
52012797Sgabeblack@google.com#
52112797Sgabeblack@google.com
52212797Sgabeblack@google.comglobal_vars_file = joinpath(build_root, 'variables.global')
52312797Sgabeblack@google.com
52412797Sgabeblack@google.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
52512797Sgabeblack@google.com
52612797Sgabeblack@google.comglobal_vars.AddVariables(
52712797Sgabeblack@google.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
52812797Sgabeblack@google.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
5294382Sbinkertn@umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
53013576Sciro.santilli@arm.com    ('BATCH', 'Use batch pool for build and tests', False),
53113577Sciro.santilli@arm.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
5324202Sbinkertn@umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
5334382Sbinkertn@umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
5344382Sbinkertn@umich.edu    )
5359396Sandreas.hansson@arm.com
53612797Sgabeblack@google.com# Update main environment with values from ARGUMENTS & global_vars_file
5375584Snate@binkert.orgglobal_vars.Update(main)
53812313Sgabeblack@google.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
5394382Sbinkertn@umich.edu
5404382Sbinkertn@umich.edu# Save sticky variable settings back to current variables file
5414382Sbinkertn@umich.eduglobal_vars.Save(global_vars_file, main)
5428232Snate@binkert.org
5435192Ssaidi@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
5448232Snate@binkert.org# look for sources etc.  This list is exported as extras_dir_list.
5458232Snate@binkert.orgbase_dir = main.srcdir.abspath
5468232Snate@binkert.orgif main['EXTRAS']:
5475192Ssaidi@eecs.umich.edu    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
5488232Snate@binkert.orgelse:
5495192Ssaidi@eecs.umich.edu    extras_dir_list = []
5505799Snate@binkert.org
5518232Snate@binkert.orgExport('base_dir')
5525192Ssaidi@eecs.umich.eduExport('extras_dir_list')
5535192Ssaidi@eecs.umich.edu
5545192Ssaidi@eecs.umich.edu# the ext directory should be on the #includes path
5558232Snate@binkert.orgmain.Append(CPPPATH=[Dir('ext')])
5565192Ssaidi@eecs.umich.edu
5578232Snate@binkert.orgdef strip_build_path(path, env):
5585192Ssaidi@eecs.umich.edu    path = str(path)
5595192Ssaidi@eecs.umich.edu    variant_base = env['BUILDROOT'] + os.path.sep
5605192Ssaidi@eecs.umich.edu    if path.startswith(variant_base):
5615192Ssaidi@eecs.umich.edu        path = path[len(variant_base):]
5624382Sbinkertn@umich.edu    elif path.startswith('build/'):
5634382Sbinkertn@umich.edu        path = path[6:]
5644382Sbinkertn@umich.edu    return path
5652667Sstever@eecs.umich.edu
5662667Sstever@eecs.umich.edu# Generate a string of the form:
5672667Sstever@eecs.umich.edu#   common/path/prefix/src1, src2 -> tgt1, tgt2
5682667Sstever@eecs.umich.edu# to print while building.
5692667Sstever@eecs.umich.educlass Transform(object):
5702667Sstever@eecs.umich.edu    # all specific color settings should be here and nowhere else
5715742Snate@binkert.org    tool_color = termcap.Normal
5725742Snate@binkert.org    pfx_color = termcap.Yellow
5735742Snate@binkert.org    srcs_color = termcap.Yellow + termcap.Bold
5745793Snate@binkert.org    arrow_color = termcap.Blue + termcap.Bold
5758334Snate@binkert.org    tgts_color = termcap.Yellow + termcap.Bold
5765793Snate@binkert.org
5775793Snate@binkert.org    def __init__(self, tool, max_sources=99):
5785793Snate@binkert.org        self.format = self.tool_color + (" [%8s] " % tool) \
5794382Sbinkertn@umich.edu                      + self.pfx_color + "%s" \
5804762Snate@binkert.org                      + self.srcs_color + "%s" \
5815344Sstever@gmail.com                      + self.arrow_color + " -> " \
5824382Sbinkertn@umich.edu                      + self.tgts_color + "%s" \
5835341Sstever@gmail.com                      + termcap.Normal
5845742Snate@binkert.org        self.max_sources = max_sources
5855742Snate@binkert.org
5865742Snate@binkert.org    def __call__(self, target, source, env, for_signature=None):
5875742Snate@binkert.org        # truncate source list according to max_sources param
5885742Snate@binkert.org        source = source[0:self.max_sources]
5894762Snate@binkert.org        def strip(f):
5905742Snate@binkert.org            return strip_build_path(str(f), env)
5915742Snate@binkert.org        if len(source) > 0:
59211984Sgabeblack@google.com            srcs = map(strip, source)
5937722Sgblack@eecs.umich.edu        else:
5945742Snate@binkert.org            srcs = ['']
5955742Snate@binkert.org        tgts = map(strip, target)
5965742Snate@binkert.org        # surprisingly, os.path.commonprefix is a dumb char-by-char string
5979930Sandreas.hansson@arm.com        # operation that has nothing to do with paths.
5989930Sandreas.hansson@arm.com        com_pfx = os.path.commonprefix(srcs + tgts)
5999930Sandreas.hansson@arm.com        com_pfx_len = len(com_pfx)
6009930Sandreas.hansson@arm.com        if com_pfx:
6019930Sandreas.hansson@arm.com            # do some cleanup and sanity checking on common prefix
6025742Snate@binkert.org            if com_pfx[-1] == ".":
6038242Sbradley.danofsky@amd.com                # prefix matches all but file extension: ok
6048242Sbradley.danofsky@amd.com                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
6058242Sbradley.danofsky@amd.com                com_pfx = com_pfx[0:-1]
6068242Sbradley.danofsky@amd.com            elif com_pfx[-1] == "/":
6075341Sstever@gmail.com                # common prefix is directory path: OK
6085742Snate@binkert.org                pass
6097722Sgblack@eecs.umich.edu            else:
6104773Snate@binkert.org                src0_len = len(srcs[0])
6116108Snate@binkert.org                tgt0_len = len(tgts[0])
6121858SN/A                if src0_len == com_pfx_len:
6131085SN/A                    # source is a substring of target, OK
6146658Snate@binkert.org                    pass
6156658Snate@binkert.org                elif tgt0_len == com_pfx_len:
6167673Snate@binkert.org                    # target is a substring of source, need to back up to
6176658Snate@binkert.org                    # avoid empty string on RHS of arrow
6186658Snate@binkert.org                    sep_idx = com_pfx.rfind(".")
61911308Santhony.gutierrez@amd.com                    if sep_idx != -1:
6206658Snate@binkert.org                        com_pfx = com_pfx[0:sep_idx]
62111308Santhony.gutierrez@amd.com                    else:
6226658Snate@binkert.org                        com_pfx = ''
6236658Snate@binkert.org                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
6247673Snate@binkert.org                    # still splitting at file extension: ok
6257673Snate@binkert.org                    pass
6267673Snate@binkert.org                else:
6277673Snate@binkert.org                    # probably a fluke; ignore it
6287673Snate@binkert.org                    com_pfx = ''
6297673Snate@binkert.org        # recalculate length in case com_pfx was modified
6307673Snate@binkert.org        com_pfx_len = len(com_pfx)
63110467Sandreas.hansson@arm.com        def fmt(files):
6326658Snate@binkert.org            f = map(lambda s: s[com_pfx_len:], files)
6337673Snate@binkert.org            return ', '.join(f)
63410467Sandreas.hansson@arm.com        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
63510467Sandreas.hansson@arm.com
63610467Sandreas.hansson@arm.comExport('Transform')
63710467Sandreas.hansson@arm.com
63810467Sandreas.hansson@arm.com# enable the regression script to use the termcap
63910467Sandreas.hansson@arm.commain['TERMCAP'] = termcap
64010467Sandreas.hansson@arm.com
64110467Sandreas.hansson@arm.comif GetOption('verbose'):
64210467Sandreas.hansson@arm.com    def MakeAction(action, string, *args, **kwargs):
64310467Sandreas.hansson@arm.com        return Action(action, *args, **kwargs)
64410467Sandreas.hansson@arm.comelse:
6457673Snate@binkert.org    MakeAction = Action
6467673Snate@binkert.org    main['CCCOMSTR']        = Transform("CC")
6477673Snate@binkert.org    main['CXXCOMSTR']       = Transform("CXX")
6487673Snate@binkert.org    main['ASCOMSTR']        = Transform("AS")
6497673Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
6509048SAli.Saidi@ARM.com    main['LINKCOMSTR']      = Transform("LINK", 0)
6517673Snate@binkert.org    main['SHLINKCOMSTR']    = Transform("SHLINK", 0)
6527673Snate@binkert.org    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
6537673Snate@binkert.org    main['M4COMSTR']        = Transform("M4")
6547673Snate@binkert.org    main['SHCCCOMSTR']      = Transform("SHCC")
6556658Snate@binkert.org    main['SHCXXCOMSTR']     = Transform("SHCXX")
6567756SAli.Saidi@ARM.comExport('MakeAction')
6577816Ssteve.reinhardt@amd.com
6586658Snate@binkert.org# Initialize the Link-Time Optimization (LTO) flags
65911308Santhony.gutierrez@amd.commain['LTO_CCFLAGS'] = []
66011308Santhony.gutierrez@amd.commain['LTO_LDFLAGS'] = []
66111308Santhony.gutierrez@amd.com
66211308Santhony.gutierrez@amd.com# According to the readme, tcmalloc works best if the compiler doesn't
66311308Santhony.gutierrez@amd.com# assume that we're using the builtin malloc and friends. These flags
66411308Santhony.gutierrez@amd.com# are compiler-specific, so we need to set them after we detect which
66511308Santhony.gutierrez@amd.com# compiler we're using.
66611308Santhony.gutierrez@amd.commain['TCMALLOC_CCFLAGS'] = []
66711308Santhony.gutierrez@amd.com
66811308Santhony.gutierrez@amd.comCXX_version = readCommand([main['CXX'],'--version'], exception=False)
66911308Santhony.gutierrez@amd.comCXX_V = readCommand([main['CXX'],'-V'], exception=False)
67011308Santhony.gutierrez@amd.com
67111308Santhony.gutierrez@amd.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
67211308Santhony.gutierrez@amd.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
67311308Santhony.gutierrez@amd.comif main['GCC'] + main['CLANG'] > 1:
67411308Santhony.gutierrez@amd.com    print 'Error: How can we have two at the same time?'
67511308Santhony.gutierrez@amd.com    Exit(1)
67611308Santhony.gutierrez@amd.com
67711308Santhony.gutierrez@amd.com# Set up default C++ compiler flags
67811308Santhony.gutierrez@amd.comif main['GCC'] or main['CLANG']:
67911308Santhony.gutierrez@amd.com    # As gcc and clang share many flags, do the common parts here
68011308Santhony.gutierrez@amd.com    main.Append(CCFLAGS=['-pipe'])
68111308Santhony.gutierrez@amd.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
68211308Santhony.gutierrez@amd.com    # Enable -Wall and -Wextra and then disable the few warnings that
68311308Santhony.gutierrez@amd.com    # we consistently violate
68411308Santhony.gutierrez@amd.com    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
68511308Santhony.gutierrez@amd.com                         '-Wno-sign-compare', '-Wno-unused-parameter'])
68611308Santhony.gutierrez@amd.com    # We always compile using C++11
68711308Santhony.gutierrez@amd.com    main.Append(CXXFLAGS=['-std=c++11'])
68811308Santhony.gutierrez@amd.com    if sys.platform.startswith('freebsd'):
68911308Santhony.gutierrez@amd.com        main.Append(CCFLAGS=['-I/usr/local/include'])
69011308Santhony.gutierrez@amd.com        main.Append(CXXFLAGS=['-I/usr/local/include'])
69111308Santhony.gutierrez@amd.com
69211308Santhony.gutierrez@amd.com    main['FILTER_PSHLINKFLAGS'] = lambda x: str(x).replace(' -shared', '')
69311308Santhony.gutierrez@amd.com    main['PSHLINKFLAGS'] = main.subst('${FILTER_PSHLINKFLAGS(SHLINKFLAGS)}')
69411308Santhony.gutierrez@amd.com    main['PLINKFLAGS'] = main.subst('${LINKFLAGS}')
69511308Santhony.gutierrez@amd.com    shared_partial_flags = ['-r', '-nostdlib']
69611308Santhony.gutierrez@amd.com    main.Append(PSHLINKFLAGS=shared_partial_flags)
69711308Santhony.gutierrez@amd.com    main.Append(PLINKFLAGS=shared_partial_flags)
69811308Santhony.gutierrez@amd.comelse:
69911308Santhony.gutierrez@amd.com    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
70011308Santhony.gutierrez@amd.com    print "Don't know what compiler options to use for your compiler."
70111308Santhony.gutierrez@amd.com    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
70211308Santhony.gutierrez@amd.com    print termcap.Yellow + '       version:' + termcap.Normal,
70311308Santhony.gutierrez@amd.com    if not CXX_version:
7044382Sbinkertn@umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
7054382Sbinkertn@umich.edu               termcap.Normal
7064762Snate@binkert.org    else:
7074762Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
7084762Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
7096654Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
7106654Snate@binkert.org    print "       environment."
7115517Snate@binkert.org    print "       "
7125517Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
7135517Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
7145517Snate@binkert.org    print "       src/SConscript to support that compiler."
7155517Snate@binkert.org    Exit(1)
7165517Snate@binkert.org
7175517Snate@binkert.orgif main['GCC']:
7185517Snate@binkert.org    # Check for a supported version of gcc. >= 4.8 is chosen for its
7195517Snate@binkert.org    # level of c++11 support. See
7205517Snate@binkert.org    # http://gcc.gnu.org/projects/cxx0x.html for details.
7215517Snate@binkert.org    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
7225517Snate@binkert.org    if compareVersions(gcc_version, "4.8") < 0:
7235517Snate@binkert.org        print 'Error: gcc version 4.8 or newer required.'
7245517Snate@binkert.org        print '       Installed version:', gcc_version
7255517Snate@binkert.org        Exit(1)
7265517Snate@binkert.org
7275517Snate@binkert.org    main['GCC_VERSION'] = gcc_version
7286654Snate@binkert.org
7295517Snate@binkert.org    if compareVersions(gcc_version, '4.9') >= 0:
7305517Snate@binkert.org        # Incremental linking with LTO is currently broken in gcc versions
7315517Snate@binkert.org        # 4.9 and above. A version where everything works completely hasn't
7325517Snate@binkert.org        # yet been identified.
7335517Snate@binkert.org        #
73411802Sandreas.sandberg@arm.com        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67548
7355517Snate@binkert.org        main['BROKEN_INCREMENTAL_LTO'] = True
7365517Snate@binkert.org    if compareVersions(gcc_version, '6.0') >= 0:
7376143Snate@binkert.org        # gcc versions 6.0 and greater accept an -flinker-output flag which
7386654Snate@binkert.org        # selects what type of output the linker should generate. This is
7395517Snate@binkert.org        # necessary for incremental lto to work, but is also broken in
7405517Snate@binkert.org        # current versions of gcc. It may not be necessary in future
7415517Snate@binkert.org        # versions. We add it here since it might be, and as a reminder that
7425517Snate@binkert.org        # it exists. It's excluded if lto is being forced.
7435517Snate@binkert.org        #
7445517Snate@binkert.org        # https://gcc.gnu.org/gcc-6/changes.html
7455517Snate@binkert.org        # https://gcc.gnu.org/ml/gcc-patches/2015-11/msg03161.html
7465517Snate@binkert.org        # https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69866
7475517Snate@binkert.org        if not GetOption('force_lto'):
7485517Snate@binkert.org            main.Append(PSHLINKFLAGS='-flinker-output=rel')
7495517Snate@binkert.org            main.Append(PLINKFLAGS='-flinker-output=rel')
7505517Snate@binkert.org
7515517Snate@binkert.org    # gcc from version 4.8 and above generates "rep; ret" instructions
7525517Snate@binkert.org    # to avoid performance penalties on certain AMD chips. Older
7536654Snate@binkert.org    # assemblers detect this as an error, "Error: expecting string
7546654Snate@binkert.org    # instruction after `rep'"
7555517Snate@binkert.org    as_version_raw = readCommand([main['AS'], '-v', '/dev/null',
7565517Snate@binkert.org                                  '-o', '/dev/null'],
7576143Snate@binkert.org                                 exception=False).split()
7586143Snate@binkert.org
7596143Snate@binkert.org    # version strings may contain extra distro-specific
7606727Ssteve.reinhardt@amd.com    # qualifiers, so play it safe and keep only what comes before
7615517Snate@binkert.org    # the first hyphen
7626727Ssteve.reinhardt@amd.com    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
7635517Snate@binkert.org
7645517Snate@binkert.org    if not as_version or compareVersions(as_version, "2.23") < 0:
7655517Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
7666654Snate@binkert.org            'Warning: This combination of gcc and binutils have' + \
7676654Snate@binkert.org            ' known incompatibilities.\n' + \
7687673Snate@binkert.org            '         If you encounter build problems, please update ' + \
7696654Snate@binkert.org            'binutils to 2.23.' + \
7706654Snate@binkert.org            termcap.Normal
7716654Snate@binkert.org
7726654Snate@binkert.org    # Make sure we warn if the user has requested to compile with the
7735517Snate@binkert.org    # Undefined Benahvior Sanitizer and this version of gcc does not
7745517Snate@binkert.org    # support it.
7755517Snate@binkert.org    if GetOption('with_ubsan') and \
7766143Snate@binkert.org            compareVersions(gcc_version, '4.9') < 0:
7775517Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
7784762Snate@binkert.org            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
7795517Snate@binkert.org            termcap.Normal
7805517Snate@binkert.org
7816143Snate@binkert.org    disable_lto = GetOption('no_lto')
7826143Snate@binkert.org    if not disable_lto and main.get('BROKEN_INCREMENTAL_LTO', False) and \
7835517Snate@binkert.org            not GetOption('force_lto'):
7845517Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
7855517Snate@binkert.org            'Warning: Your compiler doesn\'t support incremental linking' + \
7865517Snate@binkert.org            ' and lto at the same time, so lto is being disabled. To force' + \
7875517Snate@binkert.org            ' lto on anyway, use the --force-lto option. That will disable' + \
7885517Snate@binkert.org            ' partial linking.' + \
7895517Snate@binkert.org            termcap.Normal
7905517Snate@binkert.org        disable_lto = True
7915517Snate@binkert.org
7926143Snate@binkert.org    # Add the appropriate Link-Time Optimization (LTO) flags
7935517Snate@binkert.org    # unless LTO is explicitly turned off. Note that these flags
7946654Snate@binkert.org    # are only used by the fast target.
7956654Snate@binkert.org    if not disable_lto:
7966654Snate@binkert.org        # Pass the LTO flag when compiling to produce GIMPLE
7976654Snate@binkert.org        # output, we merely create the flags here and only append
7986654Snate@binkert.org        # them later
7996654Snate@binkert.org        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
8004762Snate@binkert.org
8014762Snate@binkert.org        # Use the same amount of jobs for LTO as we are running
8024762Snate@binkert.org        # scons with
8034762Snate@binkert.org        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
8044762Snate@binkert.org
8057675Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
80610584Sandreas.hansson@arm.com                                  '-fno-builtin-realloc', '-fno-builtin-free'])
8074762Snate@binkert.org
8084762Snate@binkert.org    # add option to check for undeclared overrides
8094762Snate@binkert.org    if compareVersions(gcc_version, "5.0") > 0:
8104762Snate@binkert.org        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
8114382Sbinkertn@umich.edu
8124382Sbinkertn@umich.eduelif main['CLANG']:
8135517Snate@binkert.org    # Check for a supported version of clang, >= 3.1 is needed to
8146654Snate@binkert.org    # support similar features as gcc 4.8. See
8155517Snate@binkert.org    # http://clang.llvm.org/cxx_status.html for details
8168126Sgblack@eecs.umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
8176654Snate@binkert.org    clang_version_match = clang_version_re.search(CXX_version)
8187673Snate@binkert.org    if (clang_version_match):
8196654Snate@binkert.org        clang_version = clang_version_match.groups()[0]
82011802Sandreas.sandberg@arm.com        if compareVersions(clang_version, "3.1") < 0:
8216654Snate@binkert.org            print 'Error: clang version 3.1 or newer required.'
8226654Snate@binkert.org            print '       Installed version:', clang_version
8236654Snate@binkert.org            Exit(1)
8246654Snate@binkert.org    else:
82511802Sandreas.sandberg@arm.com        print 'Error: Unable to determine clang version.'
8266669Snate@binkert.org        Exit(1)
82713709Sandreas.sandberg@arm.com
8286669Snate@binkert.org    # clang has a few additional warnings that we disable, extraneous
8296669Snate@binkert.org    # parantheses are allowed due to Ruby's printing of the AST,
8306669Snate@binkert.org    # finally self assignments are allowed as the generated CPU code
8316669Snate@binkert.org    # is relying on this
8326654Snate@binkert.org    main.Append(CCFLAGS=['-Wno-parentheses',
8337673Snate@binkert.org                         '-Wno-self-assign',
8345517Snate@binkert.org                         # Some versions of libstdc++ (4.8?) seem to
8358126Sgblack@eecs.umich.edu                         # use struct hash and class hash
8365798Snate@binkert.org                         # interchangeably.
8377756SAli.Saidi@ARM.com                         '-Wno-mismatched-tags',
8387816Ssteve.reinhardt@amd.com                         ])
8395798Snate@binkert.org
8405798Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
8415517Snate@binkert.org
8425517Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
8437673Snate@binkert.org    # opposed to libstdc++, as the later is dated.
8445517Snate@binkert.org    if sys.platform == "darwin":
8455517Snate@binkert.org        main.Append(CXXFLAGS=['-stdlib=libc++'])
8467673Snate@binkert.org        main.Append(LIBS=['c++'])
8477673Snate@binkert.org
8485517Snate@binkert.org    # On FreeBSD we need libthr.
8495798Snate@binkert.org    if sys.platform.startswith('freebsd'):
8505798Snate@binkert.org        main.Append(LIBS=['thr'])
8518333Snate@binkert.org
8527816Ssteve.reinhardt@amd.comelse:
8535798Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
8545798Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
8554762Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
8564762Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
8574762Snate@binkert.org    if not CXX_version:
8584762Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
8594762Snate@binkert.org               termcap.Normal
8608596Ssteve.reinhardt@amd.com    else:
8615517Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
8625517Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
86311997Sgabeblack@google.com    print "       or clang, there appears to be something wrong with your"
8645517Snate@binkert.org    print "       environment."
8655517Snate@binkert.org    print "       "
8667673Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
8678596Ssteve.reinhardt@amd.com    print "       above you will need to ease fix SConstruct and "
8687673Snate@binkert.org    print "       src/SConscript to support that compiler."
8695517Snate@binkert.org    Exit(1)
87010458Sandreas.hansson@arm.com
87110458Sandreas.hansson@arm.com# Set up common yacc/bison flags (needed for Ruby)
87210458Sandreas.hansson@arm.commain['YACCFLAGS'] = '-d'
87310458Sandreas.hansson@arm.commain['YACCHXXFILESUFFIX'] = '.hh'
87410458Sandreas.hansson@arm.com
87510458Sandreas.hansson@arm.com# Do this after we save setting back, or else we'll tack on an
87610458Sandreas.hansson@arm.com# extra 'qdo' every time we run scons.
87710458Sandreas.hansson@arm.comif main['BATCH']:
87810458Sandreas.hansson@arm.com    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
87910458Sandreas.hansson@arm.com    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
88010458Sandreas.hansson@arm.com    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
88110458Sandreas.hansson@arm.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
8825517Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
88311996Sgabeblack@google.com
8845517Snate@binkert.orgif sys.platform == 'cygwin':
88511997Sgabeblack@google.com    # cygwin has some header file issues...
88611996Sgabeblack@google.com    main.Append(CCFLAGS=["-Wno-uninitialized"])
8875517Snate@binkert.org
8885517Snate@binkert.org# Check for the protobuf compiler
8897673Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
8907673Snate@binkert.org                             exception='').split()
89111996Sgabeblack@google.com
89211988Sandreas.sandberg@arm.com# First two words should be "libprotoc x.y.z"
8937673Snate@binkert.orgif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
8945517Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
8958596Ssteve.reinhardt@amd.com        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
8965517Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' + \
8975517Snate@binkert.org        termcap.Normal
89811997Sgabeblack@google.com    main['PROTOC'] = False
8995517Snate@binkert.orgelse:
9005517Snate@binkert.org    # Based on the availability of the compress stream wrappers,
9017673Snate@binkert.org    # require 2.1.0
9027673Snate@binkert.org    min_protoc_version = '2.1.0'
9037673Snate@binkert.org    if compareVersions(protoc_version[1], min_protoc_version) < 0:
9045517Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
90511988Sandreas.sandberg@arm.com            'Warning: protoc version', min_protoc_version, \
90611997Sgabeblack@google.com            'or newer required.\n' + \
9078596Ssteve.reinhardt@amd.com            '         Installed version:', protoc_version[1], \
9088596Ssteve.reinhardt@amd.com            termcap.Normal
9098596Ssteve.reinhardt@amd.com        main['PROTOC'] = False
91011988Sandreas.sandberg@arm.com    else:
9118596Ssteve.reinhardt@amd.com        # Attempt to determine the appropriate include path and
9128596Ssteve.reinhardt@amd.com        # library path using pkg-config, that means we also need to
9138596Ssteve.reinhardt@amd.com        # check for pkg-config. Note that it is possible to use
9144762Snate@binkert.org        # protobuf without the involvement of pkg-config. Later on we
9156143Snate@binkert.org        # check go a library config check and at that point the test
9166143Snate@binkert.org        # will fail if libprotobuf cannot be found.
9176143Snate@binkert.org        if readCommand(['pkg-config', '--version'], exception=''):
9184762Snate@binkert.org            try:
9194762Snate@binkert.org                # Attempt to establish what linking flags to add for protobuf
9204762Snate@binkert.org                # using pkg-config
9217756SAli.Saidi@ARM.com                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
9228596Ssteve.reinhardt@amd.com            except:
9234762Snate@binkert.org                print termcap.Yellow + termcap.Bold + \
9244762Snate@binkert.org                    'Warning: pkg-config could not get protobuf flags.' + \
92510458Sandreas.hansson@arm.com                    termcap.Normal
92610458Sandreas.hansson@arm.com
92710458Sandreas.hansson@arm.com
92810458Sandreas.hansson@arm.com# Check for 'timeout' from GNU coreutils. If present, regressions will
92910458Sandreas.hansson@arm.com# be run with a time limit. We require version 8.13 since we rely on
93010458Sandreas.hansson@arm.com# support for the '--foreground' option.
93110458Sandreas.hansson@arm.comif sys.platform.startswith('freebsd'):
93210458Sandreas.hansson@arm.com    timeout_lines = readCommand(['gtimeout', '--version'],
93310458Sandreas.hansson@arm.com                                exception='').splitlines()
93410458Sandreas.hansson@arm.comelse:
93510458Sandreas.hansson@arm.com    timeout_lines = readCommand(['timeout', '--version'],
93610458Sandreas.hansson@arm.com                                exception='').splitlines()
93710458Sandreas.hansson@arm.com# Get the first line and tokenize it
93810458Sandreas.hansson@arm.comtimeout_version = timeout_lines[0].split() if timeout_lines else []
93910458Sandreas.hansson@arm.commain['TIMEOUT'] =  timeout_version and \
94010458Sandreas.hansson@arm.com    compareVersions(timeout_version[-1], '8.13') >= 0
94110458Sandreas.hansson@arm.com
94210458Sandreas.hansson@arm.com# Add a custom Check function to test for structure members.
94310458Sandreas.hansson@arm.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
94410458Sandreas.hansson@arm.com    context.Message("Checking for member %s in %s..." %
94510458Sandreas.hansson@arm.com                    (member, decl))
94610458Sandreas.hansson@arm.com    text = """
94710458Sandreas.hansson@arm.com#include %(header)s
94810458Sandreas.hansson@arm.comint main(){
94910458Sandreas.hansson@arm.com  %(decl)s test;
95010458Sandreas.hansson@arm.com  (void)test.%(member)s;
95110458Sandreas.hansson@arm.com  return 0;
95210458Sandreas.hansson@arm.com};
95310458Sandreas.hansson@arm.com""" % { "header" : include_quotes[0] + include + include_quotes[1],
95410458Sandreas.hansson@arm.com        "decl" : decl,
95510458Sandreas.hansson@arm.com        "member" : member,
95610458Sandreas.hansson@arm.com        }
95710458Sandreas.hansson@arm.com
95810458Sandreas.hansson@arm.com    ret = context.TryCompile(text, extension=".cc")
95910458Sandreas.hansson@arm.com    context.Result(ret)
96010458Sandreas.hansson@arm.com    return ret
96110458Sandreas.hansson@arm.com
96210458Sandreas.hansson@arm.com# Platform-specific configuration.  Note again that we assume that all
96310458Sandreas.hansson@arm.com# builds under a given build root run on the same host platform.
96410458Sandreas.hansson@arm.comconf = Configure(main,
96510458Sandreas.hansson@arm.com                 conf_dir = joinpath(build_root, '.scons_config'),
96610458Sandreas.hansson@arm.com                 log_file = joinpath(build_root, 'scons_config.log'),
96710458Sandreas.hansson@arm.com                 custom_tests = {
96810458Sandreas.hansson@arm.com        'CheckMember' : CheckMember,
96910458Sandreas.hansson@arm.com        })
97010458Sandreas.hansson@arm.com
97110458Sandreas.hansson@arm.com# Check if we should compile a 64 bit binary on Mac OS X/Darwin
97210458Sandreas.hansson@arm.comtry:
97310458Sandreas.hansson@arm.com    import platform
97410584Sandreas.hansson@arm.com    uname = platform.uname()
97510458Sandreas.hansson@arm.com    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
97610458Sandreas.hansson@arm.com        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
97710458Sandreas.hansson@arm.com            main.Append(CCFLAGS=['-arch', 'x86_64'])
97810458Sandreas.hansson@arm.com            main.Append(CFLAGS=['-arch', 'x86_64'])
97910458Sandreas.hansson@arm.com            main.Append(LINKFLAGS=['-arch', 'x86_64'])
9804762Snate@binkert.org            main.Append(ASFLAGS=['-arch', 'x86_64'])
9816143Snate@binkert.orgexcept:
9826143Snate@binkert.org    pass
9836143Snate@binkert.org
9844762Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
9854762Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
98611996Sgabeblack@google.com# present.  Unfortuantely this Null object always returns false,
9877816Ssteve.reinhardt@amd.com# breaking all our configuration checks.  We replace it with our own
9884762Snate@binkert.org# more optimistic null object that returns True instead.
9894762Snate@binkert.orgif not conf:
9904762Snate@binkert.org    def NullCheck(*args, **kwargs):
9914762Snate@binkert.org        return True
9927756SAli.Saidi@ARM.com
9938596Ssteve.reinhardt@amd.com    class NullConf:
9944762Snate@binkert.org        def __init__(self, env):
9954762Snate@binkert.org            self.env = env
99611988Sandreas.sandberg@arm.com        def Finish(self):
99711988Sandreas.sandberg@arm.com            return self.env
99811988Sandreas.sandberg@arm.com        def __getattr__(self, mname):
99911988Sandreas.sandberg@arm.com            return NullCheck
100011988Sandreas.sandberg@arm.com
100111988Sandreas.sandberg@arm.com    conf = NullConf(main)
100211988Sandreas.sandberg@arm.com
100311988Sandreas.sandberg@arm.com# Cache build files in the supplied directory.
100411988Sandreas.sandberg@arm.comif main['M5_BUILD_CACHE']:
100511988Sandreas.sandberg@arm.com    print 'Using build cache located at', main['M5_BUILD_CACHE']
100611988Sandreas.sandberg@arm.com    CacheDir(main['M5_BUILD_CACHE'])
10074382Sbinkertn@umich.edu
10089396Sandreas.hansson@arm.commain['USE_PYTHON'] = not GetOption('without_python')
10099396Sandreas.hansson@arm.comif main['USE_PYTHON']:
10109396Sandreas.hansson@arm.com    # Find Python include and library directories for embedding the
10119396Sandreas.hansson@arm.com    # interpreter. We rely on python-config to resolve the appropriate
10129396Sandreas.hansson@arm.com    # includes and linker flags. ParseConfig does not seem to understand
10139396Sandreas.hansson@arm.com    # the more exotic linker flags such as -Xlinker and -export-dynamic so
10149396Sandreas.hansson@arm.com    # we add them explicitly below. If you want to link in an alternate
10159396Sandreas.hansson@arm.com    # version of python, see above for instructions on how to invoke
10169396Sandreas.hansson@arm.com    # scons with the appropriate PATH set.
10179396Sandreas.hansson@arm.com    #
10189396Sandreas.hansson@arm.com    # First we check if python2-config exists, else we use python-config
10199396Sandreas.hansson@arm.com    python_config = readCommand(['which', 'python2-config'],
10209396Sandreas.hansson@arm.com                                exception='').strip()
102112302Sgabeblack@google.com    if not os.path.exists(python_config):
10229396Sandreas.hansson@arm.com        python_config = readCommand(['which', 'python-config'],
102312563Sgabeblack@google.com                                    exception='').strip()
10249396Sandreas.hansson@arm.com    py_includes = readCommand([python_config, '--includes'],
10259396Sandreas.hansson@arm.com                              exception='').split()
10268232Snate@binkert.org    # Strip the -I from the include folders before adding them to the
10278232Snate@binkert.org    # CPPPATH
10288232Snate@binkert.org    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
10298232Snate@binkert.org
10308232Snate@binkert.org    # Read the linker flags and split them into libraries and other link
10316229Snate@binkert.org    # flags. The libraries are added later through the call the CheckLib.
103210455SCurtis.Dunham@arm.com    py_ld_flags = readCommand([python_config, '--ldflags'],
10336229Snate@binkert.org        exception='').split()
103410455SCurtis.Dunham@arm.com    py_libs = []
103510455SCurtis.Dunham@arm.com    for lib in py_ld_flags:
103610455SCurtis.Dunham@arm.com         if not lib.startswith('-l'):
10375517Snate@binkert.org             main.Append(LINKFLAGS=[lib])
10385517Snate@binkert.org         else:
10397673Snate@binkert.org             lib = lib[2:]
10405517Snate@binkert.org             if lib not in py_libs:
104110455SCurtis.Dunham@arm.com                 py_libs.append(lib)
10425517Snate@binkert.org
10435517Snate@binkert.org    # verify that this stuff works
10448232Snate@binkert.org    if not conf.CheckHeader('Python.h', '<>'):
104510455SCurtis.Dunham@arm.com        print "Error: can't find Python.h header in", py_includes
104610455SCurtis.Dunham@arm.com        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
104710455SCurtis.Dunham@arm.com        Exit(1)
10487673Snate@binkert.org
10497673Snate@binkert.org    for lib in py_libs:
105010455SCurtis.Dunham@arm.com        if not conf.CheckLib(lib):
105110455SCurtis.Dunham@arm.com            print "Error: can't find library %s required by python" % lib
105210455SCurtis.Dunham@arm.com            Exit(1)
10535517Snate@binkert.org
105410455SCurtis.Dunham@arm.com# On Solaris you need to use libsocket for socket ops
105510455SCurtis.Dunham@arm.comif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
105610455SCurtis.Dunham@arm.com   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
105710455SCurtis.Dunham@arm.com       print "Can't find library with socket calls (e.g. accept())"
105810455SCurtis.Dunham@arm.com       Exit(1)
105910455SCurtis.Dunham@arm.com
106010455SCurtis.Dunham@arm.com# Check for zlib.  If the check passes, libz will be automatically
106110455SCurtis.Dunham@arm.com# added to the LIBS environment variable.
106210685Sandreas.hansson@arm.comif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
106310455SCurtis.Dunham@arm.com    print 'Error: did not find needed zlib compression library '\
106410685Sandreas.hansson@arm.com          'and/or zlib.h header file.'
106510455SCurtis.Dunham@arm.com    print '       Please install zlib and try again.'
10665517Snate@binkert.org    Exit(1)
106710455SCurtis.Dunham@arm.com
10688232Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
10698232Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
10705517Snate@binkert.org# automatically added to the LIBS environment variable. After
10717673Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
10725517Snate@binkert.org# got both protoc and libprotobuf available.
10738232Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
10748232Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
10755517Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
10768232Snate@binkert.org
10778232Snate@binkert.org# If we have the compiler but not the library, print another warning.
10788232Snate@binkert.orgif main['PROTOC'] and not main['HAVE_PROTOBUF']:
10797673Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
10805517Snate@binkert.org        'Warning: did not find protocol buffer library and/or headers.\n' + \
10815517Snate@binkert.org    '       Please install libprotobuf-dev for tracing support.' + \
10827673Snate@binkert.org    termcap.Normal
10835517Snate@binkert.org
108410455SCurtis.Dunham@arm.com# Check for librt.
10855517Snate@binkert.orghave_posix_clock = \
10865517Snate@binkert.org    conf.CheckLibWithHeader(None, 'time.h', 'C',
10878232Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
10888232Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
10895517Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
10908232Snate@binkert.org
10918232Snate@binkert.orghave_posix_timers = \
10925517Snate@binkert.org    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
10938232Snate@binkert.org                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
10948232Snate@binkert.org
10958232Snate@binkert.orgif not GetOption('without_tcmalloc'):
10965517Snate@binkert.org    if conf.CheckLib('tcmalloc'):
10978232Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
10988232Snate@binkert.org    elif conf.CheckLib('tcmalloc_minimal'):
10998232Snate@binkert.org        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
11008232Snate@binkert.org    else:
11018232Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
11028232Snate@binkert.org              "You can get a 12% performance improvement by "\
11035517Snate@binkert.org              "installing tcmalloc (libgoogle-perftools-dev package "\
11048232Snate@binkert.org              "on Ubuntu or RedHat)." + termcap.Normal
11058232Snate@binkert.org
11065517Snate@binkert.org
11078232Snate@binkert.org# Detect back trace implementations. The last implementation in the
11087673Snate@binkert.org# list will be used by default.
11095517Snate@binkert.orgbacktrace_impls = [ "none" ]
11107673Snate@binkert.org
11115517Snate@binkert.orgif conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
11128232Snate@binkert.org                           'backtrace_symbols_fd((void*)0, 0, 0);'):
11138232Snate@binkert.org    backtrace_impls.append("glibc")
11148232Snate@binkert.orgelif conf.CheckLibWithHeader('execinfo', 'execinfo.h', 'C',
11155192Ssaidi@eecs.umich.edu                           'backtrace_symbols_fd((void*)0, 0, 0);'):
111610454SCurtis.Dunham@arm.com    # NetBSD and FreeBSD need libexecinfo.
111710454SCurtis.Dunham@arm.com    backtrace_impls.append("glibc")
11188232Snate@binkert.org    main.Append(LIBS=['execinfo'])
111910455SCurtis.Dunham@arm.com
112010455SCurtis.Dunham@arm.comif backtrace_impls[-1] == "none":
112110455SCurtis.Dunham@arm.com    default_backtrace_impl = "none"
112210455SCurtis.Dunham@arm.com    print termcap.Yellow + termcap.Bold + \
11235192Ssaidi@eecs.umich.edu        "No suitable back trace implementation found." + \
112411077SCurtis.Dunham@arm.com        termcap.Normal
112511330SCurtis.Dunham@arm.com
112611077SCurtis.Dunham@arm.comif not have_posix_clock:
112711077SCurtis.Dunham@arm.com    print "Can't find library for POSIX clocks."
112811077SCurtis.Dunham@arm.com
112911330SCurtis.Dunham@arm.com# Check for <fenv.h> (C99 FP environment control)
113011077SCurtis.Dunham@arm.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
113113730Sandreas.sandberg@arm.comif not have_fenv:
113213730Sandreas.sandberg@arm.com    print "Warning: Header file <fenv.h> not found."
113313730Sandreas.sandberg@arm.com    print "         This host has no IEEE FP rounding mode control."
113413730Sandreas.sandberg@arm.com
113513730Sandreas.sandberg@arm.com# Check if we should enable KVM-based hardware virtualization. The API
11367674Snate@binkert.org# we rely on exists since version 2.6.36 of the kernel, but somehow
11375522Snate@binkert.org# the KVM_API_VERSION does not reflect the change. We test for one of
11385522Snate@binkert.org# the types as a fall back.
11397674Snate@binkert.orghave_kvm = conf.CheckHeader('linux/kvm.h', '<>')
11407674Snate@binkert.orgif not have_kvm:
11417674Snate@binkert.org    print "Info: Compatible header file <linux/kvm.h> not found, " \
11427674Snate@binkert.org        "disabling KVM support."
11437674Snate@binkert.org
11447674Snate@binkert.org# Check if the TUN/TAP driver is available.
11457674Snate@binkert.orghave_tuntap = conf.CheckHeader('linux/if_tun.h', '<>')
11467674Snate@binkert.orgif not have_tuntap:
114713730Sandreas.sandberg@arm.com    print "Info: Compatible header file <linux/if_tun.h> not found."
114813730Sandreas.sandberg@arm.com
114913730Sandreas.sandberg@arm.com# x86 needs support for xsave. We test for the structure here since we
115013730Sandreas.sandberg@arm.com# won't be able to run new tests by the time we know which ISA we're
11515517Snate@binkert.org# targeting.
115213730Sandreas.sandberg@arm.comhave_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
115313730Sandreas.sandberg@arm.com                                    '#include <linux/kvm.h>') != 0
115413730Sandreas.sandberg@arm.com
11555517Snate@binkert.org# Check if the requested target ISA is compatible with the host
115613730Sandreas.sandberg@arm.comdef is_isa_kvm_compatible(isa):
115713730Sandreas.sandberg@arm.com    try:
115813730Sandreas.sandberg@arm.com        import platform
115913730Sandreas.sandberg@arm.com        host_isa = platform.machine()
11605522Snate@binkert.org    except:
11615522Snate@binkert.org        print "Warning: Failed to determine host ISA."
116213730Sandreas.sandberg@arm.com        return False
11637674Snate@binkert.org
11645517Snate@binkert.org    if not have_posix_timers:
11657673Snate@binkert.org        print "Warning: Can not enable KVM, host seems to lack support " \
11667673Snate@binkert.org            "for POSIX timers"
11677674Snate@binkert.org        return False
11687673Snate@binkert.org
11697674Snate@binkert.org    if isa == "arm":
11707674Snate@binkert.org        return host_isa in ( "armv7l", "aarch64" )
11717674Snate@binkert.org    elif isa == "x86":
117213576Sciro.santilli@arm.com        if host_isa != "x86_64":
117313576Sciro.santilli@arm.com            return False
117411308Santhony.gutierrez@amd.com
11757673Snate@binkert.org        if not have_kvm_xsave:
11767674Snate@binkert.org            print "KVM on x86 requires xsave support in kernel headers."
11777674Snate@binkert.org            return False
11787674Snate@binkert.org
11797674Snate@binkert.org        return True
11807674Snate@binkert.org    else:
11817674Snate@binkert.org        return False
11827674Snate@binkert.org
11837674Snate@binkert.org
11847811Ssteve.reinhardt@amd.com# Check if the exclude_host attribute is available. We want this to
11857674Snate@binkert.org# get accurate instruction counts in KVM.
11867673Snate@binkert.orgmain['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
11875522Snate@binkert.org    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
11886143Snate@binkert.org
118913730Sandreas.sandberg@arm.com
11907816Ssteve.reinhardt@amd.com######################################################################
119112302Sgabeblack@google.com#
11924382Sbinkertn@umich.edu# Finish the configuration
11934382Sbinkertn@umich.edu#
11944382Sbinkertn@umich.edumain = conf.Finish()
11954382Sbinkertn@umich.edu
11964382Sbinkertn@umich.edu######################################################################
11974382Sbinkertn@umich.edu#
11984382Sbinkertn@umich.edu# Collect all non-global variables
11994382Sbinkertn@umich.edu#
120012302Sgabeblack@google.com
12014382Sbinkertn@umich.edu# Define the universe of supported ISAs
120212797Sgabeblack@google.comall_isa_list = [ ]
120312797Sgabeblack@google.comall_gpu_isa_list = [ ]
12042655Sstever@eecs.umich.eduExport('all_isa_list')
12052655Sstever@eecs.umich.eduExport('all_gpu_isa_list')
12062655Sstever@eecs.umich.edu
12072655Sstever@eecs.umich.educlass CpuModel(object):
120812063Sgabeblack@google.com    '''The CpuModel class encapsulates everything the ISA parser needs to
12095601Snate@binkert.org    know about a particular CPU model.'''
12105601Snate@binkert.org
121112222Sgabeblack@google.com    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
121212222Sgabeblack@google.com    dict = {}
12135522Snate@binkert.org
12145863Snate@binkert.org    # Constructor.  Automatically adds models to CpuModel.dict.
12155601Snate@binkert.org    def __init__(self, name, default=False):
12165601Snate@binkert.org        self.name = name           # name of model
12175601Snate@binkert.org
121812302Sgabeblack@google.com        # This cpu is enabled by default
121910453SAndrew.Bardsley@arm.com        self.default = default
122011988Sandreas.sandberg@arm.com
122111988Sandreas.sandberg@arm.com        # Add self to dict
122210453SAndrew.Bardsley@arm.com        if name in CpuModel.dict:
122312302Sgabeblack@google.com            raise AttributeError, "CpuModel '%s' already registered" % name
122410453SAndrew.Bardsley@arm.com        CpuModel.dict[name] = self
122511983Sgabeblack@google.com
122611983Sgabeblack@google.comExport('CpuModel')
122712302Sgabeblack@google.com
122812302Sgabeblack@google.com# Sticky variables get saved in the variables file so they persist from
122912362Sgabeblack@google.com# one invocation to the next (unless overridden, in which case the new
123012362Sgabeblack@google.com# value becomes sticky).
123111983Sgabeblack@google.comsticky_vars = Variables(args=ARGUMENTS)
123212302Sgabeblack@google.comExport('sticky_vars')
123312302Sgabeblack@google.com
123411983Sgabeblack@google.com# Sticky variables that should be exported
123511983Sgabeblack@google.comexport_vars = []
123611983Sgabeblack@google.comExport('export_vars')
123712362Sgabeblack@google.com
123812362Sgabeblack@google.com# For Ruby
123912310Sgabeblack@google.comall_protocols = []
124012063Sgabeblack@google.comExport('all_protocols')
124112063Sgabeblack@google.comprotocol_dirs = []
124212063Sgabeblack@google.comExport('protocol_dirs')
124312310Sgabeblack@google.comslicc_includes = []
124412310Sgabeblack@google.comExport('slicc_includes')
124512063Sgabeblack@google.com
124612063Sgabeblack@google.com# Walk the tree and execute all SConsopts scripts that wil add to the
124711983Sgabeblack@google.com# above variables
124811983Sgabeblack@google.comif GetOption('verbose'):
124911983Sgabeblack@google.com    print "Reading SConsopts"
125012310Sgabeblack@google.comfor bdir in [ base_dir ] + extras_dir_list:
125112310Sgabeblack@google.com    if not isdir(bdir):
125211983Sgabeblack@google.com        print "Error: directory '%s' does not exist" % bdir
125311983Sgabeblack@google.com        Exit(1)
125411983Sgabeblack@google.com    for root, dirs, files in os.walk(bdir):
125511983Sgabeblack@google.com        if 'SConsopts' in files:
125612310Sgabeblack@google.com            if GetOption('verbose'):
125712310Sgabeblack@google.com                print "Reading", joinpath(root, 'SConsopts')
12586143Snate@binkert.org            SConscript(joinpath(root, 'SConsopts'))
125912362Sgabeblack@google.com
126012306Sgabeblack@google.comall_isa_list.sort()
126112310Sgabeblack@google.comall_gpu_isa_list.sort()
126210453SAndrew.Bardsley@arm.com
126312362Sgabeblack@google.comsticky_vars.AddVariables(
126412306Sgabeblack@google.com    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
126512310Sgabeblack@google.com    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
12665554Snate@binkert.org    ListVariable('CPU_MODELS', 'CPU models',
126712797Sgabeblack@google.com                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
126812797Sgabeblack@google.com                 sorted(CpuModel.dict.keys())),
12695522Snate@binkert.org    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
12705522Snate@binkert.org                 False),
12715797Snate@binkert.org    BoolVariable('SS_COMPATIBLE_FP',
12725797Snate@binkert.org                 'Make floating-point results compatible with SimpleScalar',
12735522Snate@binkert.org                 False),
127412797Sgabeblack@google.com    BoolVariable('USE_SSE2',
127512797Sgabeblack@google.com                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
127612797Sgabeblack@google.com                 False),
127712797Sgabeblack@google.com    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
127812797Sgabeblack@google.com    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
12798233Snate@binkert.org    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
128012797Sgabeblack@google.com    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
128112797Sgabeblack@google.com    BoolVariable('USE_TUNTAP',
12828235Snate@binkert.org                 'Enable using a tap device to bridge to the host network',
128312797Sgabeblack@google.com                 have_tuntap),
128412797Sgabeblack@google.com    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
128512797Sgabeblack@google.com    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
128612370Sgabeblack@google.com                  all_protocols),
128712797Sgabeblack@google.com    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
128812797Sgabeblack@google.com                 backtrace_impls[-1], backtrace_impls)
128912313Sgabeblack@google.com    )
129012797Sgabeblack@google.com
12916143Snate@binkert.org# These variables get exported to #defines in config/*.hh (see src/SConscript).
129212797Sgabeblack@google.comexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
12938334Snate@binkert.org                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'USE_TUNTAP',
12948334Snate@binkert.org                'PROTOCOL', 'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
129511993Sgabeblack@google.com
129611993Sgabeblack@google.com###################################################
129712223Sgabeblack@google.com#
129811993Sgabeblack@google.com# Define a SCons builder for configuration flag headers.
12992655Sstever@eecs.umich.edu#
13009225Sandreas.hansson@arm.com###################################################
13019225Sandreas.hansson@arm.com
13029226Sandreas.hansson@arm.com# This function generates a config header file that #defines the
13039226Sandreas.hansson@arm.com# variable symbol to the current variable setting (0 or 1).  The source
13049225Sandreas.hansson@arm.com# operands are the name of the variable and a Value node containing the
13059226Sandreas.hansson@arm.com# value of the variable.
13069226Sandreas.hansson@arm.comdef build_config_file(target, source, env):
13079226Sandreas.hansson@arm.com    (variable, value) = [s.get_contents() for s in source]
13089226Sandreas.hansson@arm.com    f = file(str(target[0]), 'w')
13099226Sandreas.hansson@arm.com    print >> f, '#define', variable, value
13109226Sandreas.hansson@arm.com    f.close()
13119225Sandreas.hansson@arm.com    return None
13129227Sandreas.hansson@arm.com
13139227Sandreas.hansson@arm.com# Combine the two functions into a scons Action object.
13149227Sandreas.hansson@arm.comconfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
13159227Sandreas.hansson@arm.com
13168946Sandreas.hansson@arm.com# The emitter munges the source & target node lists to reflect what
13173918Ssaidi@eecs.umich.edu# we're really doing.
13189225Sandreas.hansson@arm.comdef config_emitter(target, source, env):
13193918Ssaidi@eecs.umich.edu    # extract variable name from Builder arg
13209225Sandreas.hansson@arm.com    variable = str(target[0])
13219225Sandreas.hansson@arm.com    # True target is config header file
13229227Sandreas.hansson@arm.com    target = joinpath('config', variable.lower() + '.hh')
13239227Sandreas.hansson@arm.com    val = env[variable]
13249227Sandreas.hansson@arm.com    if isinstance(val, bool):
13259226Sandreas.hansson@arm.com        # Force value to 0/1
13269225Sandreas.hansson@arm.com        val = int(val)
13279227Sandreas.hansson@arm.com    elif isinstance(val, str):
13289227Sandreas.hansson@arm.com        val = '"' + val + '"'
13299227Sandreas.hansson@arm.com
13309227Sandreas.hansson@arm.com    # Sources are variable name & value (packaged in SCons Value nodes)
13318946Sandreas.hansson@arm.com    return ([target], [Value(variable), Value(val)])
13329225Sandreas.hansson@arm.com
13339226Sandreas.hansson@arm.comconfig_builder = Builder(emitter = config_emitter, action = config_action)
13349226Sandreas.hansson@arm.com
13359226Sandreas.hansson@arm.commain.Append(BUILDERS = { 'ConfigFile' : config_builder })
13363515Ssaidi@eecs.umich.edu
133712563Sgabeblack@google.com###################################################
13384762Snate@binkert.org#
13393515Ssaidi@eecs.umich.edu# Builders for static and shared partially linked object files.
13408881Smarc.orr@gmail.com#
13418881Smarc.orr@gmail.com###################################################
13428881Smarc.orr@gmail.com
13438881Smarc.orr@gmail.compartial_static_builder = Builder(action=SCons.Defaults.LinkAction,
13448881Smarc.orr@gmail.com                                 src_suffix='$OBJSUFFIX',
13459226Sandreas.hansson@arm.com                                 src_builder=['StaticObject', 'Object'],
13469226Sandreas.hansson@arm.com                                 LINKFLAGS='$PLINKFLAGS',
13479226Sandreas.hansson@arm.com                                 LIBS='')
13488881Smarc.orr@gmail.com
13498881Smarc.orr@gmail.comdef partial_shared_emitter(target, source, env):
13508881Smarc.orr@gmail.com    for tgt in target:
13518881Smarc.orr@gmail.com        tgt.attributes.shared = 1
13528881Smarc.orr@gmail.com    return (target, source)
135313675Sandreas.sandberg@arm.compartial_shared_builder = Builder(action=SCons.Defaults.ShLinkAction,
13548881Smarc.orr@gmail.com                                 emitter=partial_shared_emitter,
13558881Smarc.orr@gmail.com                                 src_suffix='$SHOBJSUFFIX',
13568881Smarc.orr@gmail.com                                 src_builder='SharedObject',
13578881Smarc.orr@gmail.com                                 SHLINKFLAGS='$PSHLINKFLAGS',
13588881Smarc.orr@gmail.com                                 LIBS='')
13598881Smarc.orr@gmail.com
13608881Smarc.orr@gmail.commain.Append(BUILDERS = { 'PartialShared' : partial_shared_builder,
13618881Smarc.orr@gmail.com                         'PartialStatic' : partial_static_builder })
13628881Smarc.orr@gmail.com
13638881Smarc.orr@gmail.com# builds in ext are shared across all configs in the build root.
136413508Snikos.nikoleris@arm.comext_dir = abspath(joinpath(str(main.root), 'ext'))
136513508Snikos.nikoleris@arm.comext_build_dirs = []
136613508Snikos.nikoleris@arm.comfor root, dirs, files in os.walk(ext_dir):
136713508Snikos.nikoleris@arm.com    if 'SConscript' in files:
136813508Snikos.nikoleris@arm.com        build_dir = os.path.relpath(root, ext_dir)
136913508Snikos.nikoleris@arm.com        ext_build_dirs.append(build_dir)
137013508Snikos.nikoleris@arm.com        main.SConscript(joinpath(root, 'SConscript'),
137113508Snikos.nikoleris@arm.com                        variant_dir=joinpath(build_root, build_dir))
137213508Snikos.nikoleris@arm.com
137312222Sgabeblack@google.commain.Prepend(CPPPATH=Dir('ext/pybind11/include/'))
137412222Sgabeblack@google.com
137512222Sgabeblack@google.com###################################################
137612222Sgabeblack@google.com#
137712222Sgabeblack@google.com# This builder and wrapper method are used to set up a directory with
137813508Snikos.nikoleris@arm.com# switching headers. Those are headers which are in a generic location and
137913508Snikos.nikoleris@arm.com# that include more specific headers from a directory chosen at build time
1380955SN/A# based on the current build settings.
138112222Sgabeblack@google.com#
138212222Sgabeblack@google.com###################################################
138312222Sgabeblack@google.com
138412222Sgabeblack@google.comdef build_switching_header(target, source, env):
138512222Sgabeblack@google.com    path = str(target[0])
138613508Snikos.nikoleris@arm.com    subdir = str(source[0])
138713508Snikos.nikoleris@arm.com    dp, fp = os.path.split(path)
1388955SN/A    dp = os.path.relpath(os.path.realpath(dp),
138912222Sgabeblack@google.com                         os.path.realpath(env['BUILDDIR']))
139012222Sgabeblack@google.com    with open(path, 'w') as hdr:
139113508Snikos.nikoleris@arm.com        print >>hdr, '#include "%s/%s/%s"' % (dp, subdir, fp)
139212222Sgabeblack@google.com
139312222Sgabeblack@google.comswitching_header_action = MakeAction(build_switching_header,
139412222Sgabeblack@google.com                                     Transform('GENERATE'))
139512222Sgabeblack@google.com
139612222Sgabeblack@google.comswitching_header_builder = Builder(action=switching_header_action,
139712222Sgabeblack@google.com                                   source_factory=Value,
139812222Sgabeblack@google.com                                   single_source=True)
13991869SN/A
140012222Sgabeblack@google.commain.Append(BUILDERS = { 'SwitchingHeader': switching_header_builder })
140112222Sgabeblack@google.com
140212222Sgabeblack@google.comdef switching_headers(self, headers, source):
140312222Sgabeblack@google.com    for header in headers:
140412222Sgabeblack@google.com        self.SwitchingHeader(header, source)
140513508Snikos.nikoleris@arm.com
140613508Snikos.nikoleris@arm.commain.AddMethod(switching_headers, 'SwitchingHeaders')
14079226Sandreas.hansson@arm.com
140812222Sgabeblack@google.com# all-isas -> all-deps -> all-environs -> all_targets
140912222Sgabeblack@google.commain.Alias('#all-isas', [])
141012222Sgabeblack@google.commain.Alias('#all-deps', '#all-isas')
141112222Sgabeblack@google.com
141212222Sgabeblack@google.com# Dummy target to ensure all environments are created before telling
141313508Snikos.nikoleris@arm.com# SCons what to actually make (the command line arguments).  We attach
141413508Snikos.nikoleris@arm.com# them to the dependence graph after the environments are complete.
1415ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1416def environsComplete(target, source, env):
1417    for t in ORIG_BUILD_TARGETS:
1418        main.Depends('#all-targets', t)
1419
1420# Each build/* switching_dir attaches its *-environs target to #all-environs.
1421main.Append(BUILDERS = {'CompleteEnvirons' :
1422                        Builder(action=MakeAction(environsComplete, None))})
1423main.CompleteEnvirons('#all-environs', [])
1424
1425def doNothing(**ignored): pass
1426main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1427
1428# The final target to which all the original targets ultimately get attached.
1429main.Dummy('#all-targets', '#all-environs')
1430BUILD_TARGETS[:] = ['#all-targets']
1431
1432###################################################
1433#
1434# Define build environments for selected configurations.
1435#
1436###################################################
1437
1438def variant_name(path):
1439    return os.path.basename(path).lower().replace('_', '-')
1440main['variant_name'] = variant_name
1441main['VARIANT_NAME'] = '${variant_name(BUILDDIR)}'
1442
1443for variant_path in variant_paths:
1444    if not GetOption('silent'):
1445        print "Building in", variant_path
1446
1447    # Make a copy of the build-root environment to use for this config.
1448    env = main.Clone()
1449    env['BUILDDIR'] = variant_path
1450
1451    # variant_dir is the tail component of build path, and is used to
1452    # determine the build parameters (e.g., 'ALPHA_SE')
1453    (build_root, variant_dir) = splitpath(variant_path)
1454
1455    # Set env variables according to the build directory config.
1456    sticky_vars.files = []
1457    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1458    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1459    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1460    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1461    if isfile(current_vars_file):
1462        sticky_vars.files.append(current_vars_file)
1463        if not GetOption('silent'):
1464            print "Using saved variables file %s" % current_vars_file
1465    elif variant_dir in ext_build_dirs:
1466        # Things in ext are built without a variant directory.
1467        continue
1468    else:
1469        # Build dir-specific variables file doesn't exist.
1470
1471        # Make sure the directory is there so we can create it later
1472        opt_dir = dirname(current_vars_file)
1473        if not isdir(opt_dir):
1474            mkdir(opt_dir)
1475
1476        # Get default build variables from source tree.  Variables are
1477        # normally determined by name of $VARIANT_DIR, but can be
1478        # overridden by '--default=' arg on command line.
1479        default = GetOption('default')
1480        opts_dir = joinpath(main.root.abspath, 'build_opts')
1481        if default:
1482            default_vars_files = [joinpath(build_root, 'variables', default),
1483                                  joinpath(opts_dir, default)]
1484        else:
1485            default_vars_files = [joinpath(opts_dir, variant_dir)]
1486        existing_files = filter(isfile, default_vars_files)
1487        if existing_files:
1488            default_vars_file = existing_files[0]
1489            sticky_vars.files.append(default_vars_file)
1490            print "Variables file %s not found,\n  using defaults in %s" \
1491                  % (current_vars_file, default_vars_file)
1492        else:
1493            print "Error: cannot find variables file %s or " \
1494                  "default file(s) %s" \
1495                  % (current_vars_file, ' or '.join(default_vars_files))
1496            Exit(1)
1497
1498    # Apply current variable settings to env
1499    sticky_vars.Update(env)
1500
1501    help_texts["local_vars"] += \
1502        "Build variables for %s:\n" % variant_dir \
1503                 + sticky_vars.GenerateHelpText(env)
1504
1505    # Process variable settings.
1506
1507    if not have_fenv and env['USE_FENV']:
1508        print "Warning: <fenv.h> not available; " \
1509              "forcing USE_FENV to False in", variant_dir + "."
1510        env['USE_FENV'] = False
1511
1512    if not env['USE_FENV']:
1513        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1514        print "         FP results may deviate slightly from other platforms."
1515
1516    if env['EFENCE']:
1517        env.Append(LIBS=['efence'])
1518
1519    if env['USE_KVM']:
1520        if not have_kvm:
1521            print "Warning: Can not enable KVM, host seems to lack KVM support"
1522            env['USE_KVM'] = False
1523        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1524            print "Info: KVM support disabled due to unsupported host and " \
1525                "target ISA combination"
1526            env['USE_KVM'] = False
1527
1528    if env['USE_TUNTAP']:
1529        if not have_tuntap:
1530            print "Warning: Can't connect EtherTap with a tap device."
1531            env['USE_TUNTAP'] = False
1532
1533    if env['BUILD_GPU']:
1534        env.Append(CPPDEFINES=['BUILD_GPU'])
1535
1536    # Warn about missing optional functionality
1537    if env['USE_KVM']:
1538        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1539            print "Warning: perf_event headers lack support for the " \
1540                "exclude_host attribute. KVM instruction counts will " \
1541                "be inaccurate."
1542
1543    # Save sticky variable settings back to current variables file
1544    sticky_vars.Save(current_vars_file, env)
1545
1546    if env['USE_SSE2']:
1547        env.Append(CCFLAGS=['-msse2'])
1548
1549    # The src/SConscript file sets up the build rules in 'env' according
1550    # to the configured variables.  It returns a list of environments,
1551    # one for each variant build (debug, opt, etc.)
1552    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1553
1554def pairwise(iterable):
1555    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1556    a, b = itertools.tee(iterable)
1557    b.next()
1558    return itertools.izip(a, b)
1559
1560variant_names = [variant_name(path) for path in variant_paths]
1561
1562# Create false dependencies so SCons will parse ISAs, establish
1563# dependencies, and setup the build Environments serially. Either
1564# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1565# greater than 1. It appears to be standard race condition stuff; it
1566# doesn't always fail, but usually, and the behaviors are different.
1567# Every time I tried to remove this, builds would fail in some
1568# creative new way. So, don't do that. You'll want to, though, because
1569# tests/SConscript takes a long time to make its Environments.
1570for t1, t2 in pairwise(sorted(variant_names)):
1571    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1572    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1573
1574# base help text
1575Help('''
1576Usage: scons [scons options] [build variables] [target(s)]
1577
1578Extra scons options:
1579%(options)s
1580
1581Global build variables:
1582%(global_vars)s
1583
1584%(local_vars)s
1585''' % help_texts)
1586