SConstruct revision 11798
1955SN/A# -*- mode:python -*-
2955SN/A
37816Ssteve.reinhardt@amd.com# Copyright (c) 2013, 2015, 2016 ARM Limited
45871Snate@binkert.org# All rights reserved.
51762SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
28955SN/A# contributors may be used to endorse or promote products derived from
29955SN/A# this software without specific prior written permission.
302665Ssaidi@eecs.umich.edu#
312665Ssaidi@eecs.umich.edu# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
325863Snate@binkert.org# "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,
382632Sstever@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
392632Sstever@eecs.umich.edu# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
402632Sstever@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42955SN/A#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452761Sstever@eecs.umich.edu
462632Sstever@eecs.umich.edu###################################################
472632Sstever@eecs.umich.edu#
482632Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492761Sstever@eecs.umich.edu#
502761Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
522632Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532632Sstever@eecs.umich.edu# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
562761Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572761Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582761Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
632632Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
642632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
652632Sstever@eecs.umich.edu#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
68955SN/A#   in a directory outside of the source tree.  The '-C' option tells
695863Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
705863Snate@binkert.org#   file.
715863Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
725863Snate@binkert.org#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
735863Snate@binkert.org#
745863Snate@binkert.org# You can use 'scons -H' to print scons options.  If you're in this
755863Snate@binkert.org# 'gem5' directory (or use -u or -C to tell scons where to find this
765863Snate@binkert.org# file), you can use 'scons -h' to print all the gem5-specific build
775863Snate@binkert.org# options as well.
785863Snate@binkert.org#
795863Snate@binkert.org###################################################
805863Snate@binkert.org
815863Snate@binkert.org# Check for recent-enough Python and SCons versions.
825863Snate@binkert.orgtry:
835863Snate@binkert.org    # Really old versions of scons only take two options for the
845863Snate@binkert.org    # function, so check once without the revision and once with the
855863Snate@binkert.org    # revision, the first instance will fail for stuff other than
865863Snate@binkert.org    # 0.98, and the second will fail for 0.98.0
875863Snate@binkert.org    EnsureSConsVersion(0, 98)
885863Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
895863Snate@binkert.orgexcept SystemExit, e:
905863Snate@binkert.org    print """
915863Snate@binkert.orgFor more details, see:
925863Snate@binkert.org    http://gem5.org/Dependencies
935863Snate@binkert.org"""
945863Snate@binkert.org    raise
955863Snate@binkert.org
965863Snate@binkert.org# We ensure the python version early because because python-config
975863Snate@binkert.org# requires python 2.5
985863Snate@binkert.orgtry:
995863Snate@binkert.org    EnsurePythonVersion(2, 5)
1006654Snate@binkert.orgexcept SystemExit, e:
101955SN/A    print """
1025396Ssaidi@eecs.umich.eduYou can use a non-default installation of the Python interpreter by
1035863Snate@binkert.orgrearranging your PATH so that scons finds the non-default 'python' and
1045863Snate@binkert.org'python-config' first.
1054202Sbinkertn@umich.edu
1065863Snate@binkert.orgFor more details, see:
1075863Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1085863Snate@binkert.org"""
1095863Snate@binkert.org    raise
110955SN/A
1116654Snate@binkert.org# Global Python includes
1125273Sstever@gmail.comimport itertools
1135871Snate@binkert.orgimport os
1145273Sstever@gmail.comimport re
1156655Snate@binkert.orgimport shutil
1166655Snate@binkert.orgimport subprocess
1176655Snate@binkert.orgimport sys
1186655Snate@binkert.org
1196655Snate@binkert.orgfrom os import mkdir, environ
1206655Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1215871Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1226654Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1235396Ssaidi@eecs.umich.edu
1248120Sgblack@eecs.umich.edu# SCons includes
1258120Sgblack@eecs.umich.eduimport SCons
1268120Sgblack@eecs.umich.eduimport SCons.Node
1278120Sgblack@eecs.umich.edu
1288120Sgblack@eecs.umich.eduextra_python_paths = [
1298120Sgblack@eecs.umich.edu    Dir('src/python').srcnode().abspath, # gem5 includes
1308120Sgblack@eecs.umich.edu    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1318120Sgblack@eecs.umich.edu    ]
1328120Sgblack@eecs.umich.edu
1338120Sgblack@eecs.umich.edusys.path[1:1] = extra_python_paths
1348120Sgblack@eecs.umich.edu
1358120Sgblack@eecs.umich.edufrom m5.util import compareVersions, readCommand
1368120Sgblack@eecs.umich.edufrom m5.util.terminal import get_termcap
1378120Sgblack@eecs.umich.edu
1388120Sgblack@eecs.umich.eduhelp_texts = {
1398120Sgblack@eecs.umich.edu    "options" : "",
1408120Sgblack@eecs.umich.edu    "global_vars" : "",
1418120Sgblack@eecs.umich.edu    "local_vars" : ""
1428120Sgblack@eecs.umich.edu}
1438120Sgblack@eecs.umich.edu
1448120Sgblack@eecs.umich.eduExport("help_texts")
1458120Sgblack@eecs.umich.edu
1468120Sgblack@eecs.umich.edu
1478120Sgblack@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1488120Sgblack@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1498120Sgblack@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1508120Sgblack@eecs.umich.edu# Help() function, but these two features are incompatible: once
1518120Sgblack@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1528120Sgblack@eecs.umich.edu# at the help texts from AddOptions.  See:
1538120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1548120Sgblack@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1558120Sgblack@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1568120Sgblack@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1578120Sgblack@eecs.umich.edu# we can just use AddOption directly.
1588120Sgblack@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1598120Sgblack@eecs.umich.edu    col_width = 30
1607816Ssteve.reinhardt@amd.com
1617816Ssteve.reinhardt@amd.com    help = "  " + ", ".join(args)
1627816Ssteve.reinhardt@amd.com    if "help" in kwargs:
1637816Ssteve.reinhardt@amd.com        length = len(help)
1647816Ssteve.reinhardt@amd.com        if length >= col_width:
1657816Ssteve.reinhardt@amd.com            help += "\n" + " " * col_width
1667816Ssteve.reinhardt@amd.com        else:
1677816Ssteve.reinhardt@amd.com            help += " " * (col_width - length)
1687816Ssteve.reinhardt@amd.com        help += kwargs["help"]
1695871Snate@binkert.org    help_texts["options"] += help + "\n"
1705871Snate@binkert.org
1716121Snate@binkert.org    AddOption(*args, **kwargs)
1725871Snate@binkert.org
1735871Snate@binkert.orgAddLocalOption('--colors', dest='use_colors', action='store_true',
1746003Snate@binkert.org               help="Add color to abbreviated scons output")
1756655Snate@binkert.orgAddLocalOption('--no-colors', dest='use_colors', action='store_false',
176955SN/A               help="Don't add color to abbreviated scons output")
1775871Snate@binkert.orgAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1785871Snate@binkert.org               action='store_true',
1795871Snate@binkert.org               help="Build with support for C++-based configuration")
1805871Snate@binkert.orgAddLocalOption('--default', dest='default', type='string', action='store',
181955SN/A               help='Override which build_opts file to use for defaults')
1826121Snate@binkert.orgAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1836121Snate@binkert.org               help='Disable style checking hooks')
1846121Snate@binkert.orgAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1851533SN/A               help='Disable Link-Time Optimization for fast')
1866655Snate@binkert.orgAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1876655Snate@binkert.org               help='Update test reference outputs')
1886655Snate@binkert.orgAddLocalOption('--verbose', dest='verbose', action='store_true',
1896655Snate@binkert.org               help='Print full tool command lines')
1905871Snate@binkert.orgAddLocalOption('--without-python', dest='without_python',
1915871Snate@binkert.org               action='store_true',
1925863Snate@binkert.org               help='Build without Python configuration support')
1935871Snate@binkert.orgAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1945871Snate@binkert.org               action='store_true',
1955871Snate@binkert.org               help='Disable linking against tcmalloc')
1965871Snate@binkert.orgAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1975871Snate@binkert.org               help='Build with Undefined Behavior Sanitizer if available')
1985863Snate@binkert.orgAddLocalOption('--with-asan', dest='with_asan', action='store_true',
1996121Snate@binkert.org               help='Build with Address Sanitizer if available')
2005863Snate@binkert.org
2015871Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
2028336Ssteve.reinhardt@amd.com
2038336Ssteve.reinhardt@amd.com########################################################################
2048336Ssteve.reinhardt@amd.com#
2058336Ssteve.reinhardt@amd.com# Set up the main build environment.
2064678Snate@binkert.org#
2078336Ssteve.reinhardt@amd.com########################################################################
2088336Ssteve.reinhardt@amd.com
2098336Ssteve.reinhardt@amd.com# export TERM so that clang reports errors in color
2104678Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2114678Snate@binkert.org                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2124678Snate@binkert.org                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
2134678Snate@binkert.org
2147827Snate@binkert.orguse_prefixes = [
2157827Snate@binkert.org    "ASAN_",           # address sanitizer symbolizer path and settings
2168336Ssteve.reinhardt@amd.com    "CCACHE_",         # ccache (caching compiler wrapper) configuration
2174678Snate@binkert.org    "CCC_",            # clang static analyzer configuration
2188336Ssteve.reinhardt@amd.com    "DISTCC_",         # distcc (distributed compiler wrapper) configuration
2198336Ssteve.reinhardt@amd.com    "INCLUDE_SERVER_", # distcc pump server settings
2208336Ssteve.reinhardt@amd.com    "M5",              # M5 configuration (e.g., path to kernels)
2218336Ssteve.reinhardt@amd.com    ]
2228336Ssteve.reinhardt@amd.com
2238336Ssteve.reinhardt@amd.comuse_env = {}
2245871Snate@binkert.orgfor key,val in sorted(os.environ.iteritems()):
2255871Snate@binkert.org    if key in use_vars or \
2268336Ssteve.reinhardt@amd.com            any([key.startswith(prefix) for prefix in use_prefixes]):
2278336Ssteve.reinhardt@amd.com        use_env[key] = val
2288336Ssteve.reinhardt@amd.com
2298336Ssteve.reinhardt@amd.com# Tell scons to avoid implicit command dependencies to avoid issues
2308336Ssteve.reinhardt@amd.com# with the param wrappes being compiled twice (see
2315871Snate@binkert.org# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2328336Ssteve.reinhardt@amd.commain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2338336Ssteve.reinhardt@amd.commain.Decider('MD5-timestamp')
2348336Ssteve.reinhardt@amd.commain.root = Dir(".")         # The current directory (where this file lives).
2358336Ssteve.reinhardt@amd.commain.srcdir = Dir("src")     # The source directory
2368336Ssteve.reinhardt@amd.com
2374678Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
2385871Snate@binkert.org
2394678Snate@binkert.org# Check that we have a C/C++ compiler
2408336Ssteve.reinhardt@amd.comif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2418336Ssteve.reinhardt@amd.com    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2428336Ssteve.reinhardt@amd.com    Exit(1)
2438336Ssteve.reinhardt@amd.com
2448336Ssteve.reinhardt@amd.com# Check that swig is present
2458336Ssteve.reinhardt@amd.comif not 'SWIG' in main_dict_keys:
2468336Ssteve.reinhardt@amd.com    print "swig is not installed (package swig on Ubuntu and RedHat)"
2478336Ssteve.reinhardt@amd.com    Exit(1)
2488336Ssteve.reinhardt@amd.com
2498336Ssteve.reinhardt@amd.com# add useful python code PYTHONPATH so it can be used by subprocesses
2508336Ssteve.reinhardt@amd.com# as well
2518336Ssteve.reinhardt@amd.commain.AppendENVPath('PYTHONPATH', extra_python_paths)
2528336Ssteve.reinhardt@amd.com
2538336Ssteve.reinhardt@amd.com########################################################################
2548336Ssteve.reinhardt@amd.com#
2558336Ssteve.reinhardt@amd.com# Mercurial Stuff.
2568336Ssteve.reinhardt@amd.com#
2575871Snate@binkert.org# If the gem5 directory is a mercurial repository, we should do some
2586121Snate@binkert.org# extra things.
259955SN/A#
260955SN/A########################################################################
2612632Sstever@eecs.umich.edu
2622632Sstever@eecs.umich.eduhgdir = main.root.Dir(".hg")
263955SN/A
264955SN/A
265955SN/Astyle_message = """
266955SN/AYou're missing the gem5 style hook, which automatically checks your code
2675863Snate@binkert.orgagainst the gem5 style rules on %s.
268955SN/AThis script will now install the hook in your %s.
2692632Sstever@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2702632Sstever@eecs.umich.edu
2712632Sstever@eecs.umich.edumercurial_style_message = style_message % ("hg commit and qrefresh commands",
2722632Sstever@eecs.umich.edu                                           ".hg/hgrc file")
2732632Sstever@eecs.umich.edugit_style_message = style_message % ("'git commit'",
2742632Sstever@eecs.umich.edu                                     ".git/hooks/ directory")
2752632Sstever@eecs.umich.edu
2768268Ssteve.reinhardt@amd.commercurial_style_upgrade_message = """
2778268Ssteve.reinhardt@amd.comYour Mercurial style hooks are not up-to-date. This script will now
2788268Ssteve.reinhardt@amd.comtry to automatically update them. A backup of your hgrc will be saved
2798268Ssteve.reinhardt@amd.comin .hg/hgrc.old.
2808268Ssteve.reinhardt@amd.comPress enter to continue, or ctrl-c to abort: """
2818268Ssteve.reinhardt@amd.com
2828268Ssteve.reinhardt@amd.commercurial_style_hook = """
2832632Sstever@eecs.umich.edu# The following lines were automatically added by gem5/SConstruct
2842632Sstever@eecs.umich.edu# to provide the gem5 style-checking hooks
2852632Sstever@eecs.umich.edu[extensions]
2862632Sstever@eecs.umich.eduhgstyle = %s/util/hgstyle.py
2878268Ssteve.reinhardt@amd.com
2882632Sstever@eecs.umich.edu[hooks]
2898268Ssteve.reinhardt@amd.compretxncommit.style = python:hgstyle.check_style
2908268Ssteve.reinhardt@amd.compre-qrefresh.style = python:hgstyle.check_style
2918268Ssteve.reinhardt@amd.com# End of SConstruct additions
2928268Ssteve.reinhardt@amd.com
2933718Sstever@eecs.umich.edu""" % (main.root.abspath)
2942634Sstever@eecs.umich.edu
2952634Sstever@eecs.umich.edumercurial_lib_not_found = """
2965863Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2972638Sstever@eecs.umich.eduyou are a gem5 developer, please fix this and run the style
2988268Ssteve.reinhardt@amd.comhook. It is important.
2992632Sstever@eecs.umich.edu"""
3002632Sstever@eecs.umich.edu
3012632Sstever@eecs.umich.edu# Check for style hook and prompt for installation if it's not there.
3022632Sstever@eecs.umich.edu# Skip this if --ignore-style was specified, there's no interactive
3032632Sstever@eecs.umich.edu# terminal to prompt, or no recognized revision control system can be
3041858SN/A# found.
3053716Sstever@eecs.umich.eduignore_style = GetOption('ignore_style') or not sys.stdin.isatty()
3062638Sstever@eecs.umich.edu
3072638Sstever@eecs.umich.edu# Try wire up Mercurial to the style hooks
3082638Sstever@eecs.umich.eduif not ignore_style and hgdir.exists():
3092638Sstever@eecs.umich.edu    style_hook = True
3102638Sstever@eecs.umich.edu    style_hooks = tuple()
3112638Sstever@eecs.umich.edu    hgrc = hgdir.File('hgrc')
3122638Sstever@eecs.umich.edu    hgrc_old = hgdir.File('hgrc.old')
3135863Snate@binkert.org    try:
3145863Snate@binkert.org        from mercurial import ui
3155863Snate@binkert.org        ui = ui.ui()
316955SN/A        ui.readconfig(hgrc.abspath)
3175341Sstever@gmail.com        style_hooks = (ui.config('hooks', 'pretxncommit.style', None),
3185341Sstever@gmail.com                       ui.config('hooks', 'pre-qrefresh.style', None))
3195863Snate@binkert.org        style_hook = all(style_hooks)
3207756SAli.Saidi@ARM.com        style_extension = ui.config('extensions', 'style', None)
3215341Sstever@gmail.com    except ImportError:
3226121Snate@binkert.org        print mercurial_lib_not_found
3234494Ssaidi@eecs.umich.edu
3246121Snate@binkert.org    if "python:style.check_style" in style_hooks:
3251105SN/A        # Try to upgrade the style hooks
3262667Sstever@eecs.umich.edu        print mercurial_style_upgrade_message
3272667Sstever@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
3282667Sstever@eecs.umich.edu        try:
3292667Sstever@eecs.umich.edu            raw_input()
3306121Snate@binkert.org        except:
3312667Sstever@eecs.umich.edu            print "Input exception, exiting scons.\n"
3325341Sstever@gmail.com            sys.exit(1)
3335863Snate@binkert.org        shutil.copyfile(hgrc.abspath, hgrc_old.abspath)
3345341Sstever@gmail.com        re_style_hook = re.compile(r"^([^=#]+)\.style\s*=\s*([^#\s]+).*")
3355341Sstever@gmail.com        re_style_extension = re.compile("style\s*=\s*([^#\s]+).*")
3365341Sstever@gmail.com        old, new = open(hgrc_old.abspath, 'r'), open(hgrc.abspath, 'w')
3378120Sgblack@eecs.umich.edu        for l in old:
3385341Sstever@gmail.com            m_hook = re_style_hook.match(l)
3398120Sgblack@eecs.umich.edu            m_ext = re_style_extension.match(l)
3405341Sstever@gmail.com            if m_hook:
3418120Sgblack@eecs.umich.edu                hook, check = m_hook.groups()
3426121Snate@binkert.org                if check != "python:style.check_style":
3436121Snate@binkert.org                    print "Warning: %s.style is using a non-default " \
3445397Ssaidi@eecs.umich.edu                        "checker: %s" % (hook, check)
3455397Ssaidi@eecs.umich.edu                if hook not in ("pretxncommit", "pre-qrefresh"):
3467727SAli.Saidi@ARM.com                    print "Warning: Updating unknown style hook: %s" % hook
3478268Ssteve.reinhardt@amd.com
3486168Snate@binkert.org                l = "%s.style = python:hgstyle.check_style\n" % hook
3495341Sstever@gmail.com            elif m_ext and m_ext.group(1) == style_extension:
3508120Sgblack@eecs.umich.edu                l = "hgstyle = %s/util/hgstyle.py\n" % main.root.abspath
3518120Sgblack@eecs.umich.edu
3528120Sgblack@eecs.umich.edu            new.write(l)
3536814Sgblack@eecs.umich.edu    elif not style_hook:
3545863Snate@binkert.org        print mercurial_style_message,
3558120Sgblack@eecs.umich.edu        # continue unless user does ctrl-c/ctrl-d etc.
3565341Sstever@gmail.com        try:
3575863Snate@binkert.org            raw_input()
3588268Ssteve.reinhardt@amd.com        except:
3596121Snate@binkert.org            print "Input exception, exiting scons.\n"
3606121Snate@binkert.org            sys.exit(1)
3618268Ssteve.reinhardt@amd.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3625742Snate@binkert.org        print "Adding style hook to", hgrc_path, "\n"
3635742Snate@binkert.org        try:
3645341Sstever@gmail.com            with open(hgrc_path, 'a') as f:
3655742Snate@binkert.org                f.write(mercurial_style_hook)
3665742Snate@binkert.org        except:
3675341Sstever@gmail.com            print "Error updating", hgrc_path
3686017Snate@binkert.org            sys.exit(1)
3696121Snate@binkert.org
3706017Snate@binkert.orgdef install_git_style_hooks():
3717816Ssteve.reinhardt@amd.com    try:
3727756SAli.Saidi@ARM.com        gitdir = Dir(readCommand(
3737756SAli.Saidi@ARM.com            ["git", "rev-parse", "--git-dir"]).strip("\n"))
3747756SAli.Saidi@ARM.com    except Exception, e:
3757756SAli.Saidi@ARM.com        print "Warning: Failed to find git repo directory: %s" % e
3767756SAli.Saidi@ARM.com        return
3777756SAli.Saidi@ARM.com
3787756SAli.Saidi@ARM.com    git_hooks = gitdir.Dir("hooks")
3797756SAli.Saidi@ARM.com    git_pre_commit_hook = git_hooks.File("pre-commit")
3807816Ssteve.reinhardt@amd.com    git_style_script = File("util/git-pre-commit.py")
3817816Ssteve.reinhardt@amd.com
3827816Ssteve.reinhardt@amd.com    if git_pre_commit_hook.exists():
3837816Ssteve.reinhardt@amd.com        return
3847816Ssteve.reinhardt@amd.com
3857816Ssteve.reinhardt@amd.com    print git_style_message,
3867816Ssteve.reinhardt@amd.com    try:
3877816Ssteve.reinhardt@amd.com        raw_input()
3887816Ssteve.reinhardt@amd.com    except:
3897816Ssteve.reinhardt@amd.com        print "Input exception, exiting scons.\n"
3907756SAli.Saidi@ARM.com        sys.exit(1)
3917816Ssteve.reinhardt@amd.com
3927816Ssteve.reinhardt@amd.com    if not git_hooks.exists():
3937816Ssteve.reinhardt@amd.com        mkdir(git_hooks.get_abspath())
3947816Ssteve.reinhardt@amd.com
3957816Ssteve.reinhardt@amd.com    # Use a relative symlink if the hooks live in the source directory
3967816Ssteve.reinhardt@amd.com    if git_pre_commit_hook.is_under(main.root):
3977816Ssteve.reinhardt@amd.com        script_path = os.path.relpath(
3987816Ssteve.reinhardt@amd.com            git_style_script.get_abspath(),
3997816Ssteve.reinhardt@amd.com            git_pre_commit_hook.Dir(".").get_abspath())
4007816Ssteve.reinhardt@amd.com    else:
4017816Ssteve.reinhardt@amd.com        script_path = git_style_script.get_abspath()
4027816Ssteve.reinhardt@amd.com
4037816Ssteve.reinhardt@amd.com    try:
4047816Ssteve.reinhardt@amd.com        os.symlink(script_path, git_pre_commit_hook.get_abspath())
4057816Ssteve.reinhardt@amd.com    except:
4067816Ssteve.reinhardt@amd.com        print "Error updating git pre-commit hook"
4077816Ssteve.reinhardt@amd.com        raise
4087816Ssteve.reinhardt@amd.com
4097816Ssteve.reinhardt@amd.com# Try to wire up git to the style hooks
4107816Ssteve.reinhardt@amd.comif not ignore_style and main.root.Entry(".git").exists():
4117816Ssteve.reinhardt@amd.com    install_git_style_hooks()
4127816Ssteve.reinhardt@amd.com
4137816Ssteve.reinhardt@amd.com###################################################
4147816Ssteve.reinhardt@amd.com#
4157816Ssteve.reinhardt@amd.com# Figure out which configurations to set up based on the path(s) of
4167816Ssteve.reinhardt@amd.com# the target(s).
4177816Ssteve.reinhardt@amd.com#
4187816Ssteve.reinhardt@amd.com###################################################
4197816Ssteve.reinhardt@amd.com
4207816Ssteve.reinhardt@amd.com# Find default configuration & binary.
4217816Ssteve.reinhardt@amd.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
4227816Ssteve.reinhardt@amd.com
4237816Ssteve.reinhardt@amd.com# helper function: find last occurrence of element in list
4247816Ssteve.reinhardt@amd.comdef rfind(l, elt, offs = -1):
4257816Ssteve.reinhardt@amd.com    for i in range(len(l)+offs, 0, -1):
4267816Ssteve.reinhardt@amd.com        if l[i] == elt:
4277816Ssteve.reinhardt@amd.com            return i
4287816Ssteve.reinhardt@amd.com    raise ValueError, "element not found"
4297816Ssteve.reinhardt@amd.com
4307816Ssteve.reinhardt@amd.com# Take a list of paths (or SCons Nodes) and return a list with all
4317816Ssteve.reinhardt@amd.com# paths made absolute and ~-expanded.  Paths will be interpreted
4327816Ssteve.reinhardt@amd.com# relative to the launch directory unless a different root is provided
4337816Ssteve.reinhardt@amd.comdef makePathListAbsolute(path_list, root=GetLaunchDir()):
4347816Ssteve.reinhardt@amd.com    return [abspath(joinpath(root, expanduser(str(p))))
4357816Ssteve.reinhardt@amd.com            for p in path_list]
4367816Ssteve.reinhardt@amd.com
4377816Ssteve.reinhardt@amd.com# Each target must have 'build' in the interior of the path; the
4387816Ssteve.reinhardt@amd.com# directory below this will determine the build parameters.  For
4397816Ssteve.reinhardt@amd.com# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
4407816Ssteve.reinhardt@amd.com# recognize that ALPHA_SE specifies the configuration because it
4417816Ssteve.reinhardt@amd.com# follow 'build' in the build path.
4427816Ssteve.reinhardt@amd.com
4437816Ssteve.reinhardt@amd.com# The funky assignment to "[:]" is needed to replace the list contents
4447816Ssteve.reinhardt@amd.com# in place rather than reassign the symbol to a new list, which
4457816Ssteve.reinhardt@amd.com# doesn't work (obviously!).
4467816Ssteve.reinhardt@amd.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
4477816Ssteve.reinhardt@amd.com
4487816Ssteve.reinhardt@amd.com# Generate a list of the unique build roots and configs that the
4497816Ssteve.reinhardt@amd.com# collected targets reference.
4507816Ssteve.reinhardt@amd.comvariant_paths = []
4517816Ssteve.reinhardt@amd.combuild_root = None
4527756SAli.Saidi@ARM.comfor t in BUILD_TARGETS:
4538120Sgblack@eecs.umich.edu    path_dirs = t.split('/')
4547756SAli.Saidi@ARM.com    try:
4557756SAli.Saidi@ARM.com        build_top = rfind(path_dirs, 'build', -2)
4567756SAli.Saidi@ARM.com    except:
4577756SAli.Saidi@ARM.com        print "Error: no non-leaf 'build' dir found on target path", t
4587816Ssteve.reinhardt@amd.com        Exit(1)
4597816Ssteve.reinhardt@amd.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
4607816Ssteve.reinhardt@amd.com    if not build_root:
4617816Ssteve.reinhardt@amd.com        build_root = this_build_root
4627816Ssteve.reinhardt@amd.com    else:
4637816Ssteve.reinhardt@amd.com        if this_build_root != build_root:
4647816Ssteve.reinhardt@amd.com            print "Error: build targets not under same build root\n"\
4657816Ssteve.reinhardt@amd.com                  "  %s\n  %s" % (build_root, this_build_root)
4667816Ssteve.reinhardt@amd.com            Exit(1)
4677816Ssteve.reinhardt@amd.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
4687756SAli.Saidi@ARM.com    if variant_path not in variant_paths:
4697756SAli.Saidi@ARM.com        variant_paths.append(variant_path)
4706654Snate@binkert.org
4716654Snate@binkert.org# Make sure build_root exists (might not if this is the first build there)
4725871Snate@binkert.orgif not isdir(build_root):
4736121Snate@binkert.org    mkdir(build_root)
4746121Snate@binkert.orgmain['BUILDROOT'] = build_root
4756121Snate@binkert.org
4768737Skoansin.tan@gmail.comExport('main')
4778737Skoansin.tan@gmail.com
4783940Ssaidi@eecs.umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
4793918Ssaidi@eecs.umich.edu
4803918Ssaidi@eecs.umich.edu# Default duplicate option is to use hard links, but this messes up
4811858SN/A# when you use emacs to edit a file in the target dir, as emacs moves
4826121Snate@binkert.org# file to file~ then copies to file, breaking the link.  Symbolic
4837739Sgblack@eecs.umich.edu# (soft) links work better.
4847739Sgblack@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
4856143Snate@binkert.org
4867739Sgblack@eecs.umich.edu#
4877618SAli.Saidi@arm.com# Set up global sticky variables... these are common to an entire build
4887618SAli.Saidi@arm.com# tree (not specific to a particular build like ALPHA_SE)
4897618SAli.Saidi@arm.com#
4907618SAli.Saidi@arm.com
4918614Sgblack@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
4927618SAli.Saidi@arm.com
4937618SAli.Saidi@arm.comglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
4947618SAli.Saidi@arm.com
4957739Sgblack@eecs.umich.eduglobal_vars.AddVariables(
4966121Snate@binkert.org    ('CC', 'C compiler', environ.get('CC', main['CC'])),
4973940Ssaidi@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
4986121Snate@binkert.org    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
4997739Sgblack@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
5007739Sgblack@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
5017739Sgblack@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
5027739Sgblack@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
5037739Sgblack@eecs.umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
5047739Sgblack@eecs.umich.edu    )
5058737Skoansin.tan@gmail.com
5068737Skoansin.tan@gmail.com# Update main environment with values from ARGUMENTS & global_vars_file
5078737Skoansin.tan@gmail.comglobal_vars.Update(main)
5088737Skoansin.tan@gmail.comhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
5098737Skoansin.tan@gmail.com
5108737Skoansin.tan@gmail.com# Save sticky variable settings back to current variables file
5118737Skoansin.tan@gmail.comglobal_vars.Save(global_vars_file, main)
5128737Skoansin.tan@gmail.com
5138737Skoansin.tan@gmail.com# Parse EXTRAS variable to build list of all directories where we're
5148737Skoansin.tan@gmail.com# look for sources etc.  This list is exported as extras_dir_list.
5158737Skoansin.tan@gmail.combase_dir = main.srcdir.abspath
5168737Skoansin.tan@gmail.comif main['EXTRAS']:
5178737Skoansin.tan@gmail.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
5188737Skoansin.tan@gmail.comelse:
5198737Skoansin.tan@gmail.com    extras_dir_list = []
5208737Skoansin.tan@gmail.com
5218737Skoansin.tan@gmail.comExport('base_dir')
5228737Skoansin.tan@gmail.comExport('extras_dir_list')
5233918Ssaidi@eecs.umich.edu
5243918Ssaidi@eecs.umich.edu# the ext directory should be on the #includes path
5253940Ssaidi@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
5263918Ssaidi@eecs.umich.edu
5273918Ssaidi@eecs.umich.edudef strip_build_path(path, env):
5286157Snate@binkert.org    path = str(path)
5296157Snate@binkert.org    variant_base = env['BUILDROOT'] + os.path.sep
5306157Snate@binkert.org    if path.startswith(variant_base):
5316157Snate@binkert.org        path = path[len(variant_base):]
5325397Ssaidi@eecs.umich.edu    elif path.startswith('build/'):
5335397Ssaidi@eecs.umich.edu        path = path[6:]
5346121Snate@binkert.org    return path
5356121Snate@binkert.org
5366121Snate@binkert.org# Generate a string of the form:
5376121Snate@binkert.org#   common/path/prefix/src1, src2 -> tgt1, tgt2
5386121Snate@binkert.org# to print while building.
5396121Snate@binkert.orgclass Transform(object):
5405397Ssaidi@eecs.umich.edu    # all specific color settings should be here and nowhere else
5411851SN/A    tool_color = termcap.Normal
5421851SN/A    pfx_color = termcap.Yellow
5437739Sgblack@eecs.umich.edu    srcs_color = termcap.Yellow + termcap.Bold
544955SN/A    arrow_color = termcap.Blue + termcap.Bold
5453053Sstever@eecs.umich.edu    tgts_color = termcap.Yellow + termcap.Bold
5466121Snate@binkert.org
5473053Sstever@eecs.umich.edu    def __init__(self, tool, max_sources=99):
5483053Sstever@eecs.umich.edu        self.format = self.tool_color + (" [%8s] " % tool) \
5493053Sstever@eecs.umich.edu                      + self.pfx_color + "%s" \
5503053Sstever@eecs.umich.edu                      + self.srcs_color + "%s" \
5513053Sstever@eecs.umich.edu                      + self.arrow_color + " -> " \
5526654Snate@binkert.org                      + self.tgts_color + "%s" \
5533053Sstever@eecs.umich.edu                      + termcap.Normal
5544742Sstever@eecs.umich.edu        self.max_sources = max_sources
5554742Sstever@eecs.umich.edu
5563053Sstever@eecs.umich.edu    def __call__(self, target, source, env, for_signature=None):
5573053Sstever@eecs.umich.edu        # truncate source list according to max_sources param
5583053Sstever@eecs.umich.edu        source = source[0:self.max_sources]
5593053Sstever@eecs.umich.edu        def strip(f):
5606654Snate@binkert.org            return strip_build_path(str(f), env)
5613053Sstever@eecs.umich.edu        if len(source) > 0:
5623053Sstever@eecs.umich.edu            srcs = map(strip, source)
5633053Sstever@eecs.umich.edu        else:
5643053Sstever@eecs.umich.edu            srcs = ['']
5652667Sstever@eecs.umich.edu        tgts = map(strip, target)
5664554Sbinkertn@umich.edu        # surprisingly, os.path.commonprefix is a dumb char-by-char string
5676121Snate@binkert.org        # operation that has nothing to do with paths.
5682667Sstever@eecs.umich.edu        com_pfx = os.path.commonprefix(srcs + tgts)
5694554Sbinkertn@umich.edu        com_pfx_len = len(com_pfx)
5704554Sbinkertn@umich.edu        if com_pfx:
5714554Sbinkertn@umich.edu            # do some cleanup and sanity checking on common prefix
5726121Snate@binkert.org            if com_pfx[-1] == ".":
5734554Sbinkertn@umich.edu                # prefix matches all but file extension: ok
5744554Sbinkertn@umich.edu                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
5754554Sbinkertn@umich.edu                com_pfx = com_pfx[0:-1]
5764781Snate@binkert.org            elif com_pfx[-1] == "/":
5774554Sbinkertn@umich.edu                # common prefix is directory path: OK
5784554Sbinkertn@umich.edu                pass
5792667Sstever@eecs.umich.edu            else:
5804554Sbinkertn@umich.edu                src0_len = len(srcs[0])
5814554Sbinkertn@umich.edu                tgt0_len = len(tgts[0])
5824554Sbinkertn@umich.edu                if src0_len == com_pfx_len:
5834554Sbinkertn@umich.edu                    # source is a substring of target, OK
5842667Sstever@eecs.umich.edu                    pass
5854554Sbinkertn@umich.edu                elif tgt0_len == com_pfx_len:
5862667Sstever@eecs.umich.edu                    # target is a substring of source, need to back up to
5874554Sbinkertn@umich.edu                    # avoid empty string on RHS of arrow
5886121Snate@binkert.org                    sep_idx = com_pfx.rfind(".")
5892667Sstever@eecs.umich.edu                    if sep_idx != -1:
5905522Snate@binkert.org                        com_pfx = com_pfx[0:sep_idx]
5915522Snate@binkert.org                    else:
5925522Snate@binkert.org                        com_pfx = ''
5935522Snate@binkert.org                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
5945522Snate@binkert.org                    # still splitting at file extension: ok
5955522Snate@binkert.org                    pass
5965522Snate@binkert.org                else:
5975522Snate@binkert.org                    # probably a fluke; ignore it
5985522Snate@binkert.org                    com_pfx = ''
5995522Snate@binkert.org        # recalculate length in case com_pfx was modified
6005522Snate@binkert.org        com_pfx_len = len(com_pfx)
6015522Snate@binkert.org        def fmt(files):
6025522Snate@binkert.org            f = map(lambda s: s[com_pfx_len:], files)
6035522Snate@binkert.org            return ', '.join(f)
6045522Snate@binkert.org        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
6055522Snate@binkert.org
6065522Snate@binkert.orgExport('Transform')
6075522Snate@binkert.org
6085522Snate@binkert.org# enable the regression script to use the termcap
6095522Snate@binkert.orgmain['TERMCAP'] = termcap
6105522Snate@binkert.org
6115522Snate@binkert.orgif GetOption('verbose'):
6125522Snate@binkert.org    def MakeAction(action, string, *args, **kwargs):
6135522Snate@binkert.org        return Action(action, *args, **kwargs)
6145522Snate@binkert.orgelse:
6155522Snate@binkert.org    MakeAction = Action
6162638Sstever@eecs.umich.edu    main['CCCOMSTR']        = Transform("CC")
6172638Sstever@eecs.umich.edu    main['CXXCOMSTR']       = Transform("CXX")
6186121Snate@binkert.org    main['ASCOMSTR']        = Transform("AS")
6193716Sstever@eecs.umich.edu    main['SWIGCOMSTR']      = Transform("SWIG")
6205522Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
6215522Snate@binkert.org    main['LINKCOMSTR']      = Transform("LINK", 0)
6225522Snate@binkert.org    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
6235522Snate@binkert.org    main['M4COMSTR']        = Transform("M4")
6245522Snate@binkert.org    main['SHCCCOMSTR']      = Transform("SHCC")
6255522Snate@binkert.org    main['SHCXXCOMSTR']     = Transform("SHCXX")
6261858SN/AExport('MakeAction')
6275227Ssaidi@eecs.umich.edu
6285227Ssaidi@eecs.umich.edu# Initialize the Link-Time Optimization (LTO) flags
6295227Ssaidi@eecs.umich.edumain['LTO_CCFLAGS'] = []
6305227Ssaidi@eecs.umich.edumain['LTO_LDFLAGS'] = []
6316654Snate@binkert.org
6326654Snate@binkert.org# According to the readme, tcmalloc works best if the compiler doesn't
6337769SAli.Saidi@ARM.com# assume that we're using the builtin malloc and friends. These flags
6347769SAli.Saidi@ARM.com# are compiler-specific, so we need to set them after we detect which
6357769SAli.Saidi@ARM.com# compiler we're using.
6367769SAli.Saidi@ARM.commain['TCMALLOC_CCFLAGS'] = []
6375227Ssaidi@eecs.umich.edu
6385227Ssaidi@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
6395227Ssaidi@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
6405204Sstever@gmail.com
6415204Sstever@gmail.commain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
6425204Sstever@gmail.commain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
6435204Sstever@gmail.comif main['GCC'] + main['CLANG'] > 1:
6445204Sstever@gmail.com    print 'Error: How can we have two at the same time?'
6455204Sstever@gmail.com    Exit(1)
6465204Sstever@gmail.com
6475204Sstever@gmail.com# Set up default C++ compiler flags
6485204Sstever@gmail.comif main['GCC'] or main['CLANG']:
6495204Sstever@gmail.com    # As gcc and clang share many flags, do the common parts here
6505204Sstever@gmail.com    main.Append(CCFLAGS=['-pipe'])
6515204Sstever@gmail.com    main.Append(CCFLAGS=['-fno-strict-aliasing'])
6525204Sstever@gmail.com    # Enable -Wall and -Wextra and then disable the few warnings that
6535204Sstever@gmail.com    # we consistently violate
6545204Sstever@gmail.com    main.Append(CCFLAGS=['-Wall', '-Wundef', '-Wextra',
6555204Sstever@gmail.com                         '-Wno-sign-compare', '-Wno-unused-parameter'])
6565204Sstever@gmail.com    # We always compile using C++11
6576121Snate@binkert.org    main.Append(CXXFLAGS=['-std=c++11'])
6585204Sstever@gmail.comelse:
6593118Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6603118Sstever@eecs.umich.edu    print "Don't know what compiler options to use for your compiler."
6613118Sstever@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6623118Sstever@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
6633118Sstever@eecs.umich.edu    if not CXX_version:
6645863Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6653118Sstever@eecs.umich.edu               termcap.Normal
6665863Snate@binkert.org    else:
6673118Sstever@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
6687457Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
6697457Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
6705863Snate@binkert.org    print "       environment."
6715863Snate@binkert.org    print "       "
6725863Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
6735863Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
6745863Snate@binkert.org    print "       src/SConscript to support that compiler."
6755863Snate@binkert.org    Exit(1)
6765863Snate@binkert.org
6776003Snate@binkert.orgif main['GCC']:
6785863Snate@binkert.org    # Check for a supported version of gcc. >= 4.8 is chosen for its
6795863Snate@binkert.org    # level of c++11 support. See
6805863Snate@binkert.org    # http://gcc.gnu.org/projects/cxx0x.html for details.
6816120Snate@binkert.org    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
6825863Snate@binkert.org    if compareVersions(gcc_version, "4.8") < 0:
6835863Snate@binkert.org        print 'Error: gcc version 4.8 or newer required.'
6845863Snate@binkert.org        print '       Installed version:', gcc_version
6858655Sandreas.hansson@arm.com        Exit(1)
6868655Sandreas.hansson@arm.com
6878655Sandreas.hansson@arm.com    main['GCC_VERSION'] = gcc_version
6888655Sandreas.hansson@arm.com
6898655Sandreas.hansson@arm.com    # gcc from version 4.8 and above generates "rep; ret" instructions
6908655Sandreas.hansson@arm.com    # to avoid performance penalties on certain AMD chips. Older
6918655Sandreas.hansson@arm.com    # assemblers detect this as an error, "Error: expecting string
6928655Sandreas.hansson@arm.com    # instruction after `rep'"
6936120Snate@binkert.org    as_version_raw = readCommand([main['AS'], '-v', '/dev/null'],
6945863Snate@binkert.org                                 exception=False).split()
6956121Snate@binkert.org
6966121Snate@binkert.org    # version strings may contain extra distro-specific
6975863Snate@binkert.org    # qualifiers, so play it safe and keep only what comes before
6987727SAli.Saidi@ARM.com    # the first hyphen
6997727SAli.Saidi@ARM.com    as_version = as_version_raw[-1].split('-')[0] if as_version_raw else None
7007727SAli.Saidi@ARM.com
7017727SAli.Saidi@ARM.com    if not as_version or compareVersions(as_version, "2.23") < 0:
7027727SAli.Saidi@ARM.com        print termcap.Yellow + termcap.Bold + \
7037727SAli.Saidi@ARM.com            'Warning: This combination of gcc and binutils have' + \
7045863Snate@binkert.org            ' known incompatibilities.\n' + \
7053118Sstever@eecs.umich.edu            '         If you encounter build problems, please update ' + \
7065863Snate@binkert.org            'binutils to 2.23.' + \
7073118Sstever@eecs.umich.edu            termcap.Normal
7083118Sstever@eecs.umich.edu
7095863Snate@binkert.org    # Make sure we warn if the user has requested to compile with the
7105863Snate@binkert.org    # Undefined Benahvior Sanitizer and this version of gcc does not
7115863Snate@binkert.org    # support it.
7125863Snate@binkert.org    if GetOption('with_ubsan') and \
7133118Sstever@eecs.umich.edu            compareVersions(gcc_version, '4.9') < 0:
7143483Ssaidi@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
7153494Ssaidi@eecs.umich.edu            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
7163494Ssaidi@eecs.umich.edu            termcap.Normal
7173483Ssaidi@eecs.umich.edu
7183483Ssaidi@eecs.umich.edu    # Add the appropriate Link-Time Optimization (LTO) flags
7193483Ssaidi@eecs.umich.edu    # unless LTO is explicitly turned off. Note that these flags
7203053Sstever@eecs.umich.edu    # are only used by the fast target.
7213053Sstever@eecs.umich.edu    if not GetOption('no_lto'):
7223918Ssaidi@eecs.umich.edu        # Pass the LTO flag when compiling to produce GIMPLE
7233053Sstever@eecs.umich.edu        # output, we merely create the flags here and only append
7243053Sstever@eecs.umich.edu        # them later
7253053Sstever@eecs.umich.edu        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
7263053Sstever@eecs.umich.edu
7273053Sstever@eecs.umich.edu        # Use the same amount of jobs for LTO as we are running
7287840Snate@binkert.org        # scons with
7297865Sgblack@eecs.umich.edu        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
7307865Sgblack@eecs.umich.edu
7317865Sgblack@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
7327865Sgblack@eecs.umich.edu                                  '-fno-builtin-realloc', '-fno-builtin-free'])
7337865Sgblack@eecs.umich.edu
7347840Snate@binkert.org    # add option to check for undeclared overrides
7357840Snate@binkert.org    if compareVersions(gcc_version, "5.0") > 0:
7367840Snate@binkert.org        main.Append(CCFLAGS=['-Wno-error=suggest-override'])
7377840Snate@binkert.org
7381858SN/Aelif main['CLANG']:
7391858SN/A    # Check for a supported version of clang, >= 3.1 is needed to
7401858SN/A    # support similar features as gcc 4.8. See
7411858SN/A    # http://clang.llvm.org/cxx_status.html for details
7421858SN/A    clang_version_re = re.compile(".* version (\d+\.\d+)")
7431858SN/A    clang_version_match = clang_version_re.search(CXX_version)
7445863Snate@binkert.org    if (clang_version_match):
7455863Snate@binkert.org        clang_version = clang_version_match.groups()[0]
7465863Snate@binkert.org        if compareVersions(clang_version, "3.1") < 0:
7475863Snate@binkert.org            print 'Error: clang version 3.1 or newer required.'
7486121Snate@binkert.org            print '       Installed version:', clang_version
7491858SN/A            Exit(1)
7505863Snate@binkert.org    else:
7515863Snate@binkert.org        print 'Error: Unable to determine clang version.'
7525863Snate@binkert.org        Exit(1)
7535863Snate@binkert.org
7545863Snate@binkert.org    # clang has a few additional warnings that we disable, extraneous
7552139SN/A    # parantheses are allowed due to Ruby's printing of the AST,
7564202Sbinkertn@umich.edu    # finally self assignments are allowed as the generated CPU code
7574202Sbinkertn@umich.edu    # is relying on this
7582139SN/A    main.Append(CCFLAGS=['-Wno-parentheses',
7596994Snate@binkert.org                         '-Wno-self-assign',
7606994Snate@binkert.org                         # Some versions of libstdc++ (4.8?) seem to
7616994Snate@binkert.org                         # use struct hash and class hash
7626994Snate@binkert.org                         # interchangeably.
7636994Snate@binkert.org                         '-Wno-mismatched-tags',
7646994Snate@binkert.org                         ])
7656994Snate@binkert.org
7666994Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
7676994Snate@binkert.org
7686994Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
7696994Snate@binkert.org    # opposed to libstdc++, as the later is dated.
7706994Snate@binkert.org    if sys.platform == "darwin":
7716994Snate@binkert.org        main.Append(CXXFLAGS=['-stdlib=libc++'])
7726994Snate@binkert.org        main.Append(LIBS=['c++'])
7736994Snate@binkert.org
7746994Snate@binkert.orgelse:
7756994Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
7766994Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
7776994Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
7786994Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
7796994Snate@binkert.org    if not CXX_version:
7806994Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
7816994Snate@binkert.org               termcap.Normal
7826994Snate@binkert.org    else:
7836994Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
7846994Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
7856994Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
7866994Snate@binkert.org    print "       environment."
7872155SN/A    print "       "
7885863Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
7891869SN/A    print "       above you will need to ease fix SConstruct and "
7901869SN/A    print "       src/SConscript to support that compiler."
7915863Snate@binkert.org    Exit(1)
7925863Snate@binkert.org
7934202Sbinkertn@umich.edu# Set up common yacc/bison flags (needed for Ruby)
7946108Snate@binkert.orgmain['YACCFLAGS'] = '-d'
7956108Snate@binkert.orgmain['YACCHXXFILESUFFIX'] = '.hh'
7966108Snate@binkert.org
7976108Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
7984202Sbinkertn@umich.edu# extra 'qdo' every time we run scons.
7995863Snate@binkert.orgif main['BATCH']:
8008474Sgblack@eecs.umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
8018474Sgblack@eecs.umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
8025742Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
8038268Ssteve.reinhardt@amd.com    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
8048268Ssteve.reinhardt@amd.com    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
8058268Ssteve.reinhardt@amd.com
8065742Snate@binkert.orgif sys.platform == 'cygwin':
8075341Sstever@gmail.com    # cygwin has some header file issues...
8088474Sgblack@eecs.umich.edu    main.Append(CCFLAGS=["-Wno-uninitialized"])
8098474Sgblack@eecs.umich.edu
8105342Sstever@gmail.com# Check for the protobuf compiler
8114202Sbinkertn@umich.eduprotoc_version = readCommand([main['PROTOC'], '--version'],
8124202Sbinkertn@umich.edu                             exception='').split()
8134202Sbinkertn@umich.edu
8145863Snate@binkert.org# First two words should be "libprotoc x.y.z"
8155863Snate@binkert.orgif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
8165863Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
8176994Snate@binkert.org        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
8186994Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' + \
8196994Snate@binkert.org        termcap.Normal
8205863Snate@binkert.org    main['PROTOC'] = False
8218152Ssteve.reinhardt@amd.comelse:
8228152Ssteve.reinhardt@amd.com    # Based on the availability of the compress stream wrappers,
8235863Snate@binkert.org    # require 2.1.0
8245863Snate@binkert.org    min_protoc_version = '2.1.0'
8255863Snate@binkert.org    if compareVersions(protoc_version[1], min_protoc_version) < 0:
8265863Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
8275863Snate@binkert.org            'Warning: protoc version', min_protoc_version, \
8285863Snate@binkert.org            'or newer required.\n' + \
8295863Snate@binkert.org            '         Installed version:', protoc_version[1], \
8305863Snate@binkert.org            termcap.Normal
8315863Snate@binkert.org        main['PROTOC'] = False
8325863Snate@binkert.org    else:
8337840Snate@binkert.org        # Attempt to determine the appropriate include path and
8345863Snate@binkert.org        # library path using pkg-config, that means we also need to
8355863Snate@binkert.org        # check for pkg-config. Note that it is possible to use
8365952Ssaidi@eecs.umich.edu        # protobuf without the involvement of pkg-config. Later on we
8371869SN/A        # check go a library config check and at that point the test
8381858SN/A        # will fail if libprotobuf cannot be found.
8395863Snate@binkert.org        if readCommand(['pkg-config', '--version'], exception=''):
8408297Snate@binkert.org            try:
8418152Ssteve.reinhardt@amd.com                # Attempt to establish what linking flags to add for protobuf
8427840Snate@binkert.org                # using pkg-config
8437840Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
8441858SN/A            except:
845955SN/A                print termcap.Yellow + termcap.Bold + \
846955SN/A                    'Warning: pkg-config could not get protobuf flags.' + \
8471869SN/A                    termcap.Normal
8481869SN/A
8491869SN/A# Check for SWIG
8501869SN/Aif not main.has_key('SWIG'):
8511869SN/A    print 'Error: SWIG utility not found.'
8525863Snate@binkert.org    print '       Please install (see http://www.swig.org) and retry.'
8535863Snate@binkert.org    Exit(1)
8545863Snate@binkert.org
8551869SN/A# Check for appropriate SWIG version
8565863Snate@binkert.orgswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
8571869SN/A# First 3 words should be "SWIG Version x.y.z"
8585863Snate@binkert.orgif len(swig_version) < 3 or \
8591869SN/A        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
8601869SN/A    print 'Error determining SWIG version.'
8611869SN/A    Exit(1)
8621869SN/A
8638483Sgblack@eecs.umich.edumin_swig_version = '2.0.4'
8641869SN/Aif compareVersions(swig_version[2], min_swig_version) < 0:
8651869SN/A    print 'Error: SWIG version', min_swig_version, 'or newer required.'
8661869SN/A    print '       Installed version:', swig_version[2]
8671869SN/A    Exit(1)
8685863Snate@binkert.org
8695863Snate@binkert.org# Check for known incompatibilities. The standard library shipped with
8701869SN/A# gcc >= 4.9 does not play well with swig versions prior to 3.0
8715863Snate@binkert.orgif main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
8725863Snate@binkert.org        compareVersions(swig_version[2], '3.0') < 0:
8733356Sbinkertn@umich.edu    print termcap.Yellow + termcap.Bold + \
8743356Sbinkertn@umich.edu        'Warning: This combination of gcc and swig have' + \
8753356Sbinkertn@umich.edu        ' known incompatibilities.\n' + \
8763356Sbinkertn@umich.edu        '         If you encounter build problems, please update ' + \
8773356Sbinkertn@umich.edu        'swig to 3.0 or later.' + \
8784781Snate@binkert.org        termcap.Normal
8795863Snate@binkert.org
8805863Snate@binkert.org# Set up SWIG flags & scanner
8811869SN/Aswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
8821869SN/Amain.Append(SWIGFLAGS=swig_flags)
8831869SN/A
8846121Snate@binkert.org# Check for 'timeout' from GNU coreutils. If present, regressions will
8851869SN/A# be run with a time limit. We require version 8.13 since we rely on
8862638Sstever@eecs.umich.edu# support for the '--foreground' option.
8876121Snate@binkert.orgtimeout_lines = readCommand(['timeout', '--version'],
8886121Snate@binkert.org                            exception='').splitlines()
8892638Sstever@eecs.umich.edu# Get the first line and tokenize it
8905749Scws3k@cs.virginia.edutimeout_version = timeout_lines[0].split() if timeout_lines else []
8916121Snate@binkert.orgmain['TIMEOUT'] =  timeout_version and \
8926121Snate@binkert.org    compareVersions(timeout_version[-1], '8.13') >= 0
8935749Scws3k@cs.virginia.edu
8941869SN/A# filter out all existing swig scanners, they mess up the dependency
8951869SN/A# stuff for some reason
8963546Sgblack@eecs.umich.eduscanners = []
8973546Sgblack@eecs.umich.edufor scanner in main['SCANNERS']:
8983546Sgblack@eecs.umich.edu    skeys = scanner.skeys
8993546Sgblack@eecs.umich.edu    if skeys == '.i':
9006121Snate@binkert.org        continue
9015863Snate@binkert.org
9023546Sgblack@eecs.umich.edu    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
9033546Sgblack@eecs.umich.edu        continue
9043546Sgblack@eecs.umich.edu
9053546Sgblack@eecs.umich.edu    scanners.append(scanner)
9064781Snate@binkert.org
9074781Snate@binkert.org# add the new swig scanner that we like better
9086658Snate@binkert.orgfrom SCons.Scanner import ClassicCPP as CPPScanner
9096658Snate@binkert.orgswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
9104781Snate@binkert.orgscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
9113546Sgblack@eecs.umich.edu
9123546Sgblack@eecs.umich.edu# replace the scanners list that has what we want
9133546Sgblack@eecs.umich.edumain['SCANNERS'] = scanners
9143546Sgblack@eecs.umich.edu
9157756SAli.Saidi@ARM.com# Add a custom Check function to test for structure members.
9167816Ssteve.reinhardt@amd.comdef CheckMember(context, include, decl, member, include_quotes="<>"):
9173546Sgblack@eecs.umich.edu    context.Message("Checking for member %s in %s..." %
9183546Sgblack@eecs.umich.edu                    (member, decl))
9193546Sgblack@eecs.umich.edu    text = """
9203546Sgblack@eecs.umich.edu#include %(header)s
9214202Sbinkertn@umich.eduint main(){
9223546Sgblack@eecs.umich.edu  %(decl)s test;
9233546Sgblack@eecs.umich.edu  (void)test.%(member)s;
9243546Sgblack@eecs.umich.edu  return 0;
925955SN/A};
926955SN/A""" % { "header" : include_quotes[0] + include + include_quotes[1],
927955SN/A        "decl" : decl,
928955SN/A        "member" : member,
9295863Snate@binkert.org        }
9305863Snate@binkert.org
9315343Sstever@gmail.com    ret = context.TryCompile(text, extension=".cc")
9325343Sstever@gmail.com    context.Result(ret)
9336121Snate@binkert.org    return ret
9345863Snate@binkert.org
9354773Snate@binkert.org# Platform-specific configuration.  Note again that we assume that all
9365863Snate@binkert.org# builds under a given build root run on the same host platform.
9372632Sstever@eecs.umich.educonf = Configure(main,
9385863Snate@binkert.org                 conf_dir = joinpath(build_root, '.scons_config'),
9392023SN/A                 log_file = joinpath(build_root, 'scons_config.log'),
9405863Snate@binkert.org                 custom_tests = {
9415863Snate@binkert.org        'CheckMember' : CheckMember,
9425863Snate@binkert.org        })
9435863Snate@binkert.org
9445863Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
9455863Snate@binkert.orgtry:
9465863Snate@binkert.org    import platform
9475863Snate@binkert.org    uname = platform.uname()
9485863Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
9492632Sstever@eecs.umich.edu        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
9505863Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
9512023SN/A            main.Append(CFLAGS=['-arch', 'x86_64'])
9522632Sstever@eecs.umich.edu            main.Append(LINKFLAGS=['-arch', 'x86_64'])
9535863Snate@binkert.org            main.Append(ASFLAGS=['-arch', 'x86_64'])
9545342Sstever@gmail.comexcept:
9555863Snate@binkert.org    pass
9562632Sstever@eecs.umich.edu
9575863Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
9585863Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
9598267Ssteve.reinhardt@amd.com# present.  Unfortuantely this Null object always returns false,
9608120Sgblack@eecs.umich.edu# breaking all our configuration checks.  We replace it with our own
9618267Ssteve.reinhardt@amd.com# more optimistic null object that returns True instead.
9628267Ssteve.reinhardt@amd.comif not conf:
9638267Ssteve.reinhardt@amd.com    def NullCheck(*args, **kwargs):
9648267Ssteve.reinhardt@amd.com        return True
9658267Ssteve.reinhardt@amd.com
9668267Ssteve.reinhardt@amd.com    class NullConf:
9678267Ssteve.reinhardt@amd.com        def __init__(self, env):
9688267Ssteve.reinhardt@amd.com            self.env = env
9698267Ssteve.reinhardt@amd.com        def Finish(self):
9705863Snate@binkert.org            return self.env
9715863Snate@binkert.org        def __getattr__(self, mname):
9725863Snate@binkert.org            return NullCheck
9732632Sstever@eecs.umich.edu
9748267Ssteve.reinhardt@amd.com    conf = NullConf(main)
9758267Ssteve.reinhardt@amd.com
9768267Ssteve.reinhardt@amd.com# Cache build files in the supplied directory.
9772632Sstever@eecs.umich.eduif main['M5_BUILD_CACHE']:
9781888SN/A    print 'Using build cache located at', main['M5_BUILD_CACHE']
9795863Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
9805863Snate@binkert.org
9811858SN/Aif not GetOption('without_python'):
9828120Sgblack@eecs.umich.edu    # Find Python include and library directories for embedding the
9838120Sgblack@eecs.umich.edu    # interpreter. We rely on python-config to resolve the appropriate
9847756SAli.Saidi@ARM.com    # includes and linker flags. ParseConfig does not seem to understand
9852598SN/A    # the more exotic linker flags such as -Xlinker and -export-dynamic so
9865863Snate@binkert.org    # we add them explicitly below. If you want to link in an alternate
9871858SN/A    # version of python, see above for instructions on how to invoke
9881858SN/A    # scons with the appropriate PATH set.
9891858SN/A    #
9905863Snate@binkert.org    # First we check if python2-config exists, else we use python-config
9911858SN/A    python_config = readCommand(['which', 'python2-config'],
9921858SN/A                                exception='').strip()
9931858SN/A    if not os.path.exists(python_config):
9945863Snate@binkert.org        python_config = readCommand(['which', 'python-config'],
9951871SN/A                                    exception='').strip()
9961858SN/A    py_includes = readCommand([python_config, '--includes'],
9971858SN/A                              exception='').split()
9981858SN/A    # Strip the -I from the include folders before adding them to the
9991858SN/A    # CPPPATH
10005863Snate@binkert.org    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
10015863Snate@binkert.org
10021869SN/A    # Read the linker flags and split them into libraries and other link
10031965SN/A    # flags. The libraries are added later through the call the CheckLib.
10047739Sgblack@eecs.umich.edu    py_ld_flags = readCommand([python_config, '--ldflags'],
10051965SN/A        exception='').split()
10062761Sstever@eecs.umich.edu    py_libs = []
10075863Snate@binkert.org    for lib in py_ld_flags:
10081869SN/A         if not lib.startswith('-l'):
10095863Snate@binkert.org             main.Append(LINKFLAGS=[lib])
10102667Sstever@eecs.umich.edu         else:
10111869SN/A             lib = lib[2:]
10121869SN/A             if lib not in py_libs:
10132929Sktlim@umich.edu                 py_libs.append(lib)
10142929Sktlim@umich.edu
10155863Snate@binkert.org    # verify that this stuff works
10162929Sktlim@umich.edu    if not conf.CheckHeader('Python.h', '<>'):
1017955SN/A        print "Error: can't find Python.h header in", py_includes
10188120Sgblack@eecs.umich.edu        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
10198120Sgblack@eecs.umich.edu        Exit(1)
10208120Sgblack@eecs.umich.edu
10218120Sgblack@eecs.umich.edu    for lib in py_libs:
10228120Sgblack@eecs.umich.edu        if not conf.CheckLib(lib):
10238120Sgblack@eecs.umich.edu            print "Error: can't find library %s required by python" % lib
10248120Sgblack@eecs.umich.edu            Exit(1)
10258120Sgblack@eecs.umich.edu
10268120Sgblack@eecs.umich.edu# On Solaris you need to use libsocket for socket ops
10278120Sgblack@eecs.umich.eduif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10288120Sgblack@eecs.umich.edu   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
10298120Sgblack@eecs.umich.edu       print "Can't find library with socket calls (e.g. accept())"
1030       Exit(1)
1031
1032# Check for zlib.  If the check passes, libz will be automatically
1033# added to the LIBS environment variable.
1034if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
1035    print 'Error: did not find needed zlib compression library '\
1036          'and/or zlib.h header file.'
1037    print '       Please install zlib and try again.'
1038    Exit(1)
1039
1040# If we have the protobuf compiler, also make sure we have the
1041# development libraries. If the check passes, libprotobuf will be
1042# automatically added to the LIBS environment variable. After
1043# this, we can use the HAVE_PROTOBUF flag to determine if we have
1044# got both protoc and libprotobuf available.
1045main['HAVE_PROTOBUF'] = main['PROTOC'] and \
1046    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
1047                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
1048
1049# If we have the compiler but not the library, print another warning.
1050if main['PROTOC'] and not main['HAVE_PROTOBUF']:
1051    print termcap.Yellow + termcap.Bold + \
1052        'Warning: did not find protocol buffer library and/or headers.\n' + \
1053    '       Please install libprotobuf-dev for tracing support.' + \
1054    termcap.Normal
1055
1056# Check for librt.
1057have_posix_clock = \
1058    conf.CheckLibWithHeader(None, 'time.h', 'C',
1059                            'clock_nanosleep(0,0,NULL,NULL);') or \
1060    conf.CheckLibWithHeader('rt', 'time.h', 'C',
1061                            'clock_nanosleep(0,0,NULL,NULL);')
1062
1063have_posix_timers = \
1064    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
1065                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
1066
1067if not GetOption('without_tcmalloc'):
1068    if conf.CheckLib('tcmalloc'):
1069        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
1070    elif conf.CheckLib('tcmalloc_minimal'):
1071        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
1072    else:
1073        print termcap.Yellow + termcap.Bold + \
1074              "You can get a 12% performance improvement by "\
1075              "installing tcmalloc (libgoogle-perftools-dev package "\
1076              "on Ubuntu or RedHat)." + termcap.Normal
1077
1078
1079# Detect back trace implementations. The last implementation in the
1080# list will be used by default.
1081backtrace_impls = [ "none" ]
1082
1083if conf.CheckLibWithHeader(None, 'execinfo.h', 'C',
1084                           'backtrace_symbols_fd((void*)0, 0, 0);'):
1085    backtrace_impls.append("glibc")
1086
1087if backtrace_impls[-1] == "none":
1088    default_backtrace_impl = "none"
1089    print termcap.Yellow + termcap.Bold + \
1090        "No suitable back trace implementation found." + \
1091        termcap.Normal
1092
1093if not have_posix_clock:
1094    print "Can't find library for POSIX clocks."
1095
1096# Check for <fenv.h> (C99 FP environment control)
1097have_fenv = conf.CheckHeader('fenv.h', '<>')
1098if not have_fenv:
1099    print "Warning: Header file <fenv.h> not found."
1100    print "         This host has no IEEE FP rounding mode control."
1101
1102# Check if we should enable KVM-based hardware virtualization. The API
1103# we rely on exists since version 2.6.36 of the kernel, but somehow
1104# the KVM_API_VERSION does not reflect the change. We test for one of
1105# the types as a fall back.
1106have_kvm = conf.CheckHeader('linux/kvm.h', '<>')
1107if not have_kvm:
1108    print "Info: Compatible header file <linux/kvm.h> not found, " \
1109        "disabling KVM support."
1110
1111# x86 needs support for xsave. We test for the structure here since we
1112# won't be able to run new tests by the time we know which ISA we're
1113# targeting.
1114have_kvm_xsave = conf.CheckTypeSize('struct kvm_xsave',
1115                                    '#include <linux/kvm.h>') != 0
1116
1117# Check if the requested target ISA is compatible with the host
1118def is_isa_kvm_compatible(isa):
1119    try:
1120        import platform
1121        host_isa = platform.machine()
1122    except:
1123        print "Warning: Failed to determine host ISA."
1124        return False
1125
1126    if not have_posix_timers:
1127        print "Warning: Can not enable KVM, host seems to lack support " \
1128            "for POSIX timers"
1129        return False
1130
1131    if isa == "arm":
1132        return host_isa in ( "armv7l", "aarch64" )
1133    elif isa == "x86":
1134        if host_isa != "x86_64":
1135            return False
1136
1137        if not have_kvm_xsave:
1138            print "KVM on x86 requires xsave support in kernel headers."
1139            return False
1140
1141        return True
1142    else:
1143        return False
1144
1145
1146# Check if the exclude_host attribute is available. We want this to
1147# get accurate instruction counts in KVM.
1148main['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
1149    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
1150
1151
1152######################################################################
1153#
1154# Finish the configuration
1155#
1156main = conf.Finish()
1157
1158######################################################################
1159#
1160# Collect all non-global variables
1161#
1162
1163# Define the universe of supported ISAs
1164all_isa_list = [ ]
1165all_gpu_isa_list = [ ]
1166Export('all_isa_list')
1167Export('all_gpu_isa_list')
1168
1169class CpuModel(object):
1170    '''The CpuModel class encapsulates everything the ISA parser needs to
1171    know about a particular CPU model.'''
1172
1173    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
1174    dict = {}
1175
1176    # Constructor.  Automatically adds models to CpuModel.dict.
1177    def __init__(self, name, default=False):
1178        self.name = name           # name of model
1179
1180        # This cpu is enabled by default
1181        self.default = default
1182
1183        # Add self to dict
1184        if name in CpuModel.dict:
1185            raise AttributeError, "CpuModel '%s' already registered" % name
1186        CpuModel.dict[name] = self
1187
1188Export('CpuModel')
1189
1190# Sticky variables get saved in the variables file so they persist from
1191# one invocation to the next (unless overridden, in which case the new
1192# value becomes sticky).
1193sticky_vars = Variables(args=ARGUMENTS)
1194Export('sticky_vars')
1195
1196# Sticky variables that should be exported
1197export_vars = []
1198Export('export_vars')
1199
1200# For Ruby
1201all_protocols = []
1202Export('all_protocols')
1203protocol_dirs = []
1204Export('protocol_dirs')
1205slicc_includes = []
1206Export('slicc_includes')
1207
1208# Walk the tree and execute all SConsopts scripts that wil add to the
1209# above variables
1210if GetOption('verbose'):
1211    print "Reading SConsopts"
1212for bdir in [ base_dir ] + extras_dir_list:
1213    if not isdir(bdir):
1214        print "Error: directory '%s' does not exist" % bdir
1215        Exit(1)
1216    for root, dirs, files in os.walk(bdir):
1217        if 'SConsopts' in files:
1218            if GetOption('verbose'):
1219                print "Reading", joinpath(root, 'SConsopts')
1220            SConscript(joinpath(root, 'SConsopts'))
1221
1222all_isa_list.sort()
1223all_gpu_isa_list.sort()
1224
1225sticky_vars.AddVariables(
1226    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
1227    EnumVariable('TARGET_GPU_ISA', 'Target GPU ISA', 'hsail', all_gpu_isa_list),
1228    ListVariable('CPU_MODELS', 'CPU models',
1229                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
1230                 sorted(CpuModel.dict.keys())),
1231    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
1232                 False),
1233    BoolVariable('SS_COMPATIBLE_FP',
1234                 'Make floating-point results compatible with SimpleScalar',
1235                 False),
1236    BoolVariable('USE_SSE2',
1237                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
1238                 False),
1239    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1240    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
1241    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
1242    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
1243    BoolVariable('BUILD_GPU', 'Build the compute-GPU model', False),
1244    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1245                  all_protocols),
1246    EnumVariable('BACKTRACE_IMPL', 'Post-mortem dump implementation',
1247                 backtrace_impls[-1], backtrace_impls)
1248    )
1249
1250# These variables get exported to #defines in config/*.hh (see src/SConscript).
1251export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'TARGET_GPU_ISA',
1252                'CP_ANNOTATE', 'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL',
1253                'HAVE_PROTOBUF', 'HAVE_PERF_ATTR_EXCLUDE_HOST']
1254
1255###################################################
1256#
1257# Define a SCons builder for configuration flag headers.
1258#
1259###################################################
1260
1261# This function generates a config header file that #defines the
1262# variable symbol to the current variable setting (0 or 1).  The source
1263# operands are the name of the variable and a Value node containing the
1264# value of the variable.
1265def build_config_file(target, source, env):
1266    (variable, value) = [s.get_contents() for s in source]
1267    f = file(str(target[0]), 'w')
1268    print >> f, '#define', variable, value
1269    f.close()
1270    return None
1271
1272# Combine the two functions into a scons Action object.
1273config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1274
1275# The emitter munges the source & target node lists to reflect what
1276# we're really doing.
1277def config_emitter(target, source, env):
1278    # extract variable name from Builder arg
1279    variable = str(target[0])
1280    # True target is config header file
1281    target = joinpath('config', variable.lower() + '.hh')
1282    val = env[variable]
1283    if isinstance(val, bool):
1284        # Force value to 0/1
1285        val = int(val)
1286    elif isinstance(val, str):
1287        val = '"' + val + '"'
1288
1289    # Sources are variable name & value (packaged in SCons Value nodes)
1290    return ([target], [Value(variable), Value(val)])
1291
1292config_builder = Builder(emitter = config_emitter, action = config_action)
1293
1294main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1295
1296# libelf build is shared across all configs in the build root.
1297main.SConscript('ext/libelf/SConscript',
1298                variant_dir = joinpath(build_root, 'libelf'))
1299
1300# iostream3 build is shared across all configs in the build root.
1301main.SConscript('ext/iostream3/SConscript',
1302                variant_dir = joinpath(build_root, 'iostream3'))
1303
1304# libfdt build is shared across all configs in the build root.
1305main.SConscript('ext/libfdt/SConscript',
1306                variant_dir = joinpath(build_root, 'libfdt'))
1307
1308# fputils build is shared across all configs in the build root.
1309main.SConscript('ext/fputils/SConscript',
1310                variant_dir = joinpath(build_root, 'fputils'))
1311
1312# DRAMSim2 build is shared across all configs in the build root.
1313main.SConscript('ext/dramsim2/SConscript',
1314                variant_dir = joinpath(build_root, 'dramsim2'))
1315
1316# DRAMPower build is shared across all configs in the build root.
1317main.SConscript('ext/drampower/SConscript',
1318                variant_dir = joinpath(build_root, 'drampower'))
1319
1320# nomali build is shared across all configs in the build root.
1321main.SConscript('ext/nomali/SConscript',
1322                variant_dir = joinpath(build_root, 'nomali'))
1323
1324###################################################
1325#
1326# This function is used to set up a directory with switching headers
1327#
1328###################################################
1329
1330main['ALL_ISA_LIST'] = all_isa_list
1331main['ALL_GPU_ISA_LIST'] = all_gpu_isa_list
1332all_isa_deps = {}
1333def make_switching_dir(dname, switch_headers, env):
1334    # Generate the header.  target[0] is the full path of the output
1335    # header to generate.  'source' is a dummy variable, since we get the
1336    # list of ISAs from env['ALL_ISA_LIST'].
1337    def gen_switch_hdr(target, source, env):
1338        fname = str(target[0])
1339        isa = env['TARGET_ISA'].lower()
1340        try:
1341            f = open(fname, 'w')
1342            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1343            f.close()
1344        except IOError:
1345            print "Failed to create %s" % fname
1346            raise
1347
1348    # Build SCons Action object. 'varlist' specifies env vars that this
1349    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1350    # should get re-executed.
1351    switch_hdr_action = MakeAction(gen_switch_hdr,
1352                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1353
1354    # Instantiate actions for each header
1355    for hdr in switch_headers:
1356        env.Command(hdr, [], switch_hdr_action)
1357
1358    isa_target = Dir('.').up().name.lower().replace('_', '-')
1359    env['PHONY_BASE'] = '#'+isa_target
1360    all_isa_deps[isa_target] = None
1361
1362Export('make_switching_dir')
1363
1364def make_gpu_switching_dir(dname, switch_headers, env):
1365    # Generate the header.  target[0] is the full path of the output
1366    # header to generate.  'source' is a dummy variable, since we get the
1367    # list of ISAs from env['ALL_ISA_LIST'].
1368    def gen_switch_hdr(target, source, env):
1369        fname = str(target[0])
1370
1371        isa = env['TARGET_GPU_ISA'].lower()
1372
1373        try:
1374            f = open(fname, 'w')
1375            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1376            f.close()
1377        except IOError:
1378            print "Failed to create %s" % fname
1379            raise
1380
1381    # Build SCons Action object. 'varlist' specifies env vars that this
1382    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1383    # should get re-executed.
1384    switch_hdr_action = MakeAction(gen_switch_hdr,
1385                          Transform("GENERATE"), varlist=['ALL_ISA_GPU_LIST'])
1386
1387    # Instantiate actions for each header
1388    for hdr in switch_headers:
1389        env.Command(hdr, [], switch_hdr_action)
1390
1391Export('make_gpu_switching_dir')
1392
1393# all-isas -> all-deps -> all-environs -> all_targets
1394main.Alias('#all-isas', [])
1395main.Alias('#all-deps', '#all-isas')
1396
1397# Dummy target to ensure all environments are created before telling
1398# SCons what to actually make (the command line arguments).  We attach
1399# them to the dependence graph after the environments are complete.
1400ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1401def environsComplete(target, source, env):
1402    for t in ORIG_BUILD_TARGETS:
1403        main.Depends('#all-targets', t)
1404
1405# Each build/* switching_dir attaches its *-environs target to #all-environs.
1406main.Append(BUILDERS = {'CompleteEnvirons' :
1407                        Builder(action=MakeAction(environsComplete, None))})
1408main.CompleteEnvirons('#all-environs', [])
1409
1410def doNothing(**ignored): pass
1411main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1412
1413# The final target to which all the original targets ultimately get attached.
1414main.Dummy('#all-targets', '#all-environs')
1415BUILD_TARGETS[:] = ['#all-targets']
1416
1417###################################################
1418#
1419# Define build environments for selected configurations.
1420#
1421###################################################
1422
1423for variant_path in variant_paths:
1424    if not GetOption('silent'):
1425        print "Building in", variant_path
1426
1427    # Make a copy of the build-root environment to use for this config.
1428    env = main.Clone()
1429    env['BUILDDIR'] = variant_path
1430
1431    # variant_dir is the tail component of build path, and is used to
1432    # determine the build parameters (e.g., 'ALPHA_SE')
1433    (build_root, variant_dir) = splitpath(variant_path)
1434
1435    # Set env variables according to the build directory config.
1436    sticky_vars.files = []
1437    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1438    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1439    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1440    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1441    if isfile(current_vars_file):
1442        sticky_vars.files.append(current_vars_file)
1443        if not GetOption('silent'):
1444            print "Using saved variables file %s" % current_vars_file
1445    else:
1446        # Build dir-specific variables file doesn't exist.
1447
1448        # Make sure the directory is there so we can create it later
1449        opt_dir = dirname(current_vars_file)
1450        if not isdir(opt_dir):
1451            mkdir(opt_dir)
1452
1453        # Get default build variables from source tree.  Variables are
1454        # normally determined by name of $VARIANT_DIR, but can be
1455        # overridden by '--default=' arg on command line.
1456        default = GetOption('default')
1457        opts_dir = joinpath(main.root.abspath, 'build_opts')
1458        if default:
1459            default_vars_files = [joinpath(build_root, 'variables', default),
1460                                  joinpath(opts_dir, default)]
1461        else:
1462            default_vars_files = [joinpath(opts_dir, variant_dir)]
1463        existing_files = filter(isfile, default_vars_files)
1464        if existing_files:
1465            default_vars_file = existing_files[0]
1466            sticky_vars.files.append(default_vars_file)
1467            print "Variables file %s not found,\n  using defaults in %s" \
1468                  % (current_vars_file, default_vars_file)
1469        else:
1470            print "Error: cannot find variables file %s or " \
1471                  "default file(s) %s" \
1472                  % (current_vars_file, ' or '.join(default_vars_files))
1473            Exit(1)
1474
1475    # Apply current variable settings to env
1476    sticky_vars.Update(env)
1477
1478    help_texts["local_vars"] += \
1479        "Build variables for %s:\n" % variant_dir \
1480                 + sticky_vars.GenerateHelpText(env)
1481
1482    # Process variable settings.
1483
1484    if not have_fenv and env['USE_FENV']:
1485        print "Warning: <fenv.h> not available; " \
1486              "forcing USE_FENV to False in", variant_dir + "."
1487        env['USE_FENV'] = False
1488
1489    if not env['USE_FENV']:
1490        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1491        print "         FP results may deviate slightly from other platforms."
1492
1493    if env['EFENCE']:
1494        env.Append(LIBS=['efence'])
1495
1496    if env['USE_KVM']:
1497        if not have_kvm:
1498            print "Warning: Can not enable KVM, host seems to lack KVM support"
1499            env['USE_KVM'] = False
1500        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1501            print "Info: KVM support disabled due to unsupported host and " \
1502                "target ISA combination"
1503            env['USE_KVM'] = False
1504
1505    if env['BUILD_GPU']:
1506        env.Append(CPPDEFINES=['BUILD_GPU'])
1507
1508    # Warn about missing optional functionality
1509    if env['USE_KVM']:
1510        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1511            print "Warning: perf_event headers lack support for the " \
1512                "exclude_host attribute. KVM instruction counts will " \
1513                "be inaccurate."
1514
1515    # Save sticky variable settings back to current variables file
1516    sticky_vars.Save(current_vars_file, env)
1517
1518    if env['USE_SSE2']:
1519        env.Append(CCFLAGS=['-msse2'])
1520
1521    # The src/SConscript file sets up the build rules in 'env' according
1522    # to the configured variables.  It returns a list of environments,
1523    # one for each variant build (debug, opt, etc.)
1524    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1525
1526def pairwise(iterable):
1527    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1528    a, b = itertools.tee(iterable)
1529    b.next()
1530    return itertools.izip(a, b)
1531
1532# Create false dependencies so SCons will parse ISAs, establish
1533# dependencies, and setup the build Environments serially. Either
1534# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1535# greater than 1. It appears to be standard race condition stuff; it
1536# doesn't always fail, but usually, and the behaviors are different.
1537# Every time I tried to remove this, builds would fail in some
1538# creative new way. So, don't do that. You'll want to, though, because
1539# tests/SConscript takes a long time to make its Environments.
1540for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1541    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1542    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1543
1544# base help text
1545Help('''
1546Usage: scons [scons options] [build variables] [target(s)]
1547
1548Extra scons options:
1549%(options)s
1550
1551Global build variables:
1552%(global_vars)s
1553
1554%(local_vars)s
1555''' % help_texts)
1556