SConstruct revision 10671:d59e40b074c6
1955SN/A# -*- mode:python -*-
2955SN/A
35871Snate@binkert.org# Copyright (c) 2013 ARM Limited
41762SN/A# All rights reserved.
5955SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
28955SN/A# contributors may be used to endorse or promote products derived from
292665Ssaidi@eecs.umich.edu# this software without specific prior written permission.
302665Ssaidi@eecs.umich.edu#
315863Snate@binkert.org# 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
372632Sstever@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
382632Sstever@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
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
41955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422632Sstever@eecs.umich.edu#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442761Sstever@eecs.umich.edu#          Nathan Binkert
452632Sstever@eecs.umich.edu
462632Sstever@eecs.umich.edu###################################################
472632Sstever@eecs.umich.edu#
482761Sstever@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
512632Sstever@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
532761Sstever@eecs.umich.edu# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
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
582632Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
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
65955SN/A#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
685863Snate@binkert.org#   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:
99955SN/A    EnsurePythonVersion(2, 5)
1005396Ssaidi@eecs.umich.eduexcept SystemExit, e:
1015863Snate@binkert.org    print """
1025863Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
1034202Sbinkertn@umich.edurearranging your PATH so that scons finds the non-default 'python' and
1045863Snate@binkert.org'python-config' first.
1055863Snate@binkert.org
1065863Snate@binkert.orgFor more details, see:
1075863Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
108955SN/A"""
1095273Sstever@gmail.com    raise
1105871Snate@binkert.org
1115273Sstever@gmail.com# Global Python includes
1125871Snate@binkert.orgimport itertools
1135863Snate@binkert.orgimport os
1145863Snate@binkert.orgimport re
1155863Snate@binkert.orgimport subprocess
1165871Snate@binkert.orgimport sys
1175872Snate@binkert.org
1185872Snate@binkert.orgfrom os import mkdir, environ
1195872Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1205871Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1215871Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1225871Snate@binkert.org
1235871Snate@binkert.org# SCons includes
1245871Snate@binkert.orgimport SCons
1255871Snate@binkert.orgimport SCons.Node
1265871Snate@binkert.org
1275871Snate@binkert.orgextra_python_paths = [
1285871Snate@binkert.org    Dir('src/python').srcnode().abspath, # gem5 includes
1295871Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1305871Snate@binkert.org    ]
1315871Snate@binkert.org
1325871Snate@binkert.orgsys.path[1:1] = extra_python_paths
1335871Snate@binkert.org
1345863Snate@binkert.orgfrom m5.util import compareVersions, readCommand
1355227Ssaidi@eecs.umich.edufrom m5.util.terminal import get_termcap
1365396Ssaidi@eecs.umich.edu
1375396Ssaidi@eecs.umich.eduhelp_texts = {
1385396Ssaidi@eecs.umich.edu    "options" : "",
1395396Ssaidi@eecs.umich.edu    "global_vars" : "",
1405396Ssaidi@eecs.umich.edu    "local_vars" : ""
1415396Ssaidi@eecs.umich.edu}
1425396Ssaidi@eecs.umich.edu
1435396Ssaidi@eecs.umich.eduExport("help_texts")
1445588Ssaidi@eecs.umich.edu
1455396Ssaidi@eecs.umich.edu
1465396Ssaidi@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1475396Ssaidi@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1485396Ssaidi@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1495396Ssaidi@eecs.umich.edu# Help() function, but these two features are incompatible: once
1505396Ssaidi@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1515396Ssaidi@eecs.umich.edu# at the help texts from AddOptions.  See:
1525396Ssaidi@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1535396Ssaidi@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1545396Ssaidi@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1555396Ssaidi@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1565396Ssaidi@eecs.umich.edu# we can just use AddOption directly.
1575396Ssaidi@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1585396Ssaidi@eecs.umich.edu    col_width = 30
1595871Snate@binkert.org
1605871Snate@binkert.org    help = "  " + ", ".join(args)
1615871Snate@binkert.org    if "help" in kwargs:
1625871Snate@binkert.org        length = len(help)
1635871Snate@binkert.org        if length >= col_width:
1646003Snate@binkert.org            help += "\n" + " " * col_width
1656003Snate@binkert.org        else:
166955SN/A            help += " " * (col_width - length)
1675871Snate@binkert.org        help += kwargs["help"]
1685871Snate@binkert.org    help_texts["options"] += help + "\n"
1695871Snate@binkert.org
1705871Snate@binkert.org    AddOption(*args, **kwargs)
171955SN/A
1725871Snate@binkert.orgAddLocalOption('--colors', dest='use_colors', action='store_true',
1735871Snate@binkert.org               help="Add color to abbreviated scons output")
1745871Snate@binkert.orgAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1751533SN/A               help="Don't add color to abbreviated scons output")
1765871Snate@binkert.orgAddLocalOption('--with-cxx-config', dest='with_cxx_config',
1775871Snate@binkert.org               action='store_true',
1785863Snate@binkert.org               help="Build with support for C++-based configuration")
1795871Snate@binkert.orgAddLocalOption('--default', dest='default', type='string', action='store',
1805871Snate@binkert.org               help='Override which build_opts file to use for defaults')
1815871Snate@binkert.orgAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1825871Snate@binkert.org               help='Disable style checking hooks')
1835871Snate@binkert.orgAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1845863Snate@binkert.org               help='Disable Link-Time Optimization for fast')
1855871Snate@binkert.orgAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1865863Snate@binkert.org               help='Update test reference outputs')
1875871Snate@binkert.orgAddLocalOption('--verbose', dest='verbose', action='store_true',
1884678Snate@binkert.org               help='Print full tool command lines')
1894678Snate@binkert.orgAddLocalOption('--without-python', dest='without_python',
1904678Snate@binkert.org               action='store_true',
1914678Snate@binkert.org               help='Build without Python configuration support')
1924678Snate@binkert.orgAddLocalOption('--without-tcmalloc', dest='without_tcmalloc',
1934678Snate@binkert.org               action='store_true',
1944678Snate@binkert.org               help='Disable linking against tcmalloc')
1954678Snate@binkert.orgAddLocalOption('--with-ubsan', dest='with_ubsan', action='store_true',
1964678Snate@binkert.org               help='Build with Undefined Behavior Sanitizer if available')
1974678Snate@binkert.org
1984678Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
1994678Snate@binkert.org
2005871Snate@binkert.org########################################################################
2014678Snate@binkert.org#
2025871Snate@binkert.org# Set up the main build environment.
2035871Snate@binkert.org#
2045871Snate@binkert.org########################################################################
2055871Snate@binkert.org
2065871Snate@binkert.org# export TERM so that clang reports errors in color
2075871Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
2085871Snate@binkert.org                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
2095871Snate@binkert.org                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
2105871Snate@binkert.org
2115871Snate@binkert.orguse_prefixes = [
2125871Snate@binkert.org    "M5",           # M5 configuration (e.g., path to kernels)
2135871Snate@binkert.org    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
2145871Snate@binkert.org    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2155990Ssaidi@eecs.umich.edu    "CCC_",         # clang static analyzer configuration
2165871Snate@binkert.org    ]
2175871Snate@binkert.org
2185871Snate@binkert.orguse_env = {}
2194678Snate@binkert.orgfor key,val in sorted(os.environ.iteritems()):
2205871Snate@binkert.org    if key in use_vars or \
2215871Snate@binkert.org            any([key.startswith(prefix) for prefix in use_prefixes]):
2225871Snate@binkert.org        use_env[key] = val
2235871Snate@binkert.org
2245871Snate@binkert.org# Tell scons to avoid implicit command dependencies to avoid issues
2255871Snate@binkert.org# with the param wrappes being compiled twice (see
2265871Snate@binkert.org# http://scons.tigris.org/issues/show_bug.cgi?id=2811)
2275871Snate@binkert.orgmain = Environment(ENV=use_env, IMPLICIT_COMMAND_DEPENDENCIES=0)
2285871Snate@binkert.orgmain.Decider('MD5-timestamp')
2295871Snate@binkert.orgmain.root = Dir(".")         # The current directory (where this file lives).
2304678Snate@binkert.orgmain.srcdir = Dir("src")     # The source directory
2315871Snate@binkert.org
2324678Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
2335871Snate@binkert.org
2345871Snate@binkert.org# Check that we have a C/C++ compiler
2355871Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2365871Snate@binkert.org    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2375871Snate@binkert.org    Exit(1)
2385871Snate@binkert.org
2395871Snate@binkert.org# Check that swig is present
2405871Snate@binkert.orgif not 'SWIG' in main_dict_keys:
2415871Snate@binkert.org    print "swig is not installed (package swig on Ubuntu and RedHat)"
2425990Ssaidi@eecs.umich.edu    Exit(1)
2435863Snate@binkert.org
244955SN/A# add useful python code PYTHONPATH so it can be used by subprocesses
245955SN/A# as well
2462632Sstever@eecs.umich.edumain.AppendENVPath('PYTHONPATH', extra_python_paths)
2472632Sstever@eecs.umich.edu
248955SN/A########################################################################
249955SN/A#
250955SN/A# Mercurial Stuff.
251955SN/A#
2525863Snate@binkert.org# If the gem5 directory is a mercurial repository, we should do some
253955SN/A# extra things.
2542632Sstever@eecs.umich.edu#
2552632Sstever@eecs.umich.edu########################################################################
2562632Sstever@eecs.umich.edu
2572632Sstever@eecs.umich.eduhgdir = main.root.Dir(".hg")
2582632Sstever@eecs.umich.edu
2592632Sstever@eecs.umich.edumercurial_style_message = """
2602632Sstever@eecs.umich.eduYou're missing the gem5 style hook, which automatically checks your code
2612632Sstever@eecs.umich.eduagainst the gem5 style rules on hg commit and qrefresh commands.  This
2622632Sstever@eecs.umich.eduscript will now install the hook in your .hg/hgrc file.
2632632Sstever@eecs.umich.eduPress enter to continue, or ctrl-c to abort: """
2642632Sstever@eecs.umich.edu
2652632Sstever@eecs.umich.edumercurial_style_hook = """
2662632Sstever@eecs.umich.edu# The following lines were automatically added by gem5/SConstruct
2673718Sstever@eecs.umich.edu# to provide the gem5 style-checking hooks
2683718Sstever@eecs.umich.edu[extensions]
2693718Sstever@eecs.umich.edustyle = %s/util/style.py
2703718Sstever@eecs.umich.edu
2713718Sstever@eecs.umich.edu[hooks]
2725863Snate@binkert.orgpretxncommit.style = python:style.check_style
2735863Snate@binkert.orgpre-qrefresh.style = python:style.check_style
2743718Sstever@eecs.umich.edu# End of SConstruct additions
2753718Sstever@eecs.umich.edu
2765863Snate@binkert.org""" % (main.root.abspath)
2775863Snate@binkert.org
2783718Sstever@eecs.umich.edumercurial_lib_not_found = """
2793718Sstever@eecs.umich.eduMercurial libraries cannot be found, ignoring style hook.  If
2802634Sstever@eecs.umich.eduyou are a gem5 developer, please fix this and run the style
2812634Sstever@eecs.umich.eduhook. It is important.
2825863Snate@binkert.org"""
2832638Sstever@eecs.umich.edu
2842632Sstever@eecs.umich.edu# Check for style hook and prompt for installation if it's not there.
2852632Sstever@eecs.umich.edu# Skip this if --ignore-style was specified, there's no .hg dir to
2862632Sstever@eecs.umich.edu# install a hook in, or there's no interactive terminal to prompt.
2872632Sstever@eecs.umich.eduif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2882632Sstever@eecs.umich.edu    style_hook = True
2892632Sstever@eecs.umich.edu    try:
2901858SN/A        from mercurial import ui
2913716Sstever@eecs.umich.edu        ui = ui.ui()
2922638Sstever@eecs.umich.edu        ui.readconfig(hgdir.File('hgrc').abspath)
2932638Sstever@eecs.umich.edu        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2942638Sstever@eecs.umich.edu                     ui.config('hooks', 'pre-qrefresh.style', None)
2952638Sstever@eecs.umich.edu    except ImportError:
2962638Sstever@eecs.umich.edu        print mercurial_lib_not_found
2972638Sstever@eecs.umich.edu
2982638Sstever@eecs.umich.edu    if not style_hook:
2995863Snate@binkert.org        print mercurial_style_message,
3005863Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
3015863Snate@binkert.org        try:
302955SN/A            raw_input()
3035341Sstever@gmail.com        except:
3045341Sstever@gmail.com            print "Input exception, exiting scons.\n"
3055863Snate@binkert.org            sys.exit(1)
3065341Sstever@gmail.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
3074494Ssaidi@eecs.umich.edu        print "Adding style hook to", hgrc_path, "\n"
3084494Ssaidi@eecs.umich.edu        try:
3095863Snate@binkert.org            hgrc = open(hgrc_path, 'a')
3101105SN/A            hgrc.write(mercurial_style_hook)
3112667Sstever@eecs.umich.edu            hgrc.close()
3122667Sstever@eecs.umich.edu        except:
3132667Sstever@eecs.umich.edu            print "Error updating", hgrc_path
3142667Sstever@eecs.umich.edu            sys.exit(1)
3152667Sstever@eecs.umich.edu
3162667Sstever@eecs.umich.edu
3175341Sstever@gmail.com###################################################
3185863Snate@binkert.org#
3195341Sstever@gmail.com# Figure out which configurations to set up based on the path(s) of
3205341Sstever@gmail.com# the target(s).
3215341Sstever@gmail.com#
3225863Snate@binkert.org###################################################
3235341Sstever@gmail.com
3245341Sstever@gmail.com# Find default configuration & binary.
3255341Sstever@gmail.comDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
3265863Snate@binkert.org
3275341Sstever@gmail.com# helper function: find last occurrence of element in list
3285341Sstever@gmail.comdef rfind(l, elt, offs = -1):
3295341Sstever@gmail.com    for i in range(len(l)+offs, 0, -1):
3305341Sstever@gmail.com        if l[i] == elt:
3315341Sstever@gmail.com            return i
3325341Sstever@gmail.com    raise ValueError, "element not found"
3335341Sstever@gmail.com
3345341Sstever@gmail.com# Take a list of paths (or SCons Nodes) and return a list with all
3355341Sstever@gmail.com# paths made absolute and ~-expanded.  Paths will be interpreted
3365341Sstever@gmail.com# relative to the launch directory unless a different root is provided
3375863Snate@binkert.orgdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3385341Sstever@gmail.com    return [abspath(joinpath(root, expanduser(str(p))))
3395863Snate@binkert.org            for p in path_list]
3405341Sstever@gmail.com
3415863Snate@binkert.org# Each target must have 'build' in the interior of the path; the
3425863Snate@binkert.org# directory below this will determine the build parameters.  For
3435863Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3445397Ssaidi@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
3455397Ssaidi@eecs.umich.edu# follow 'build' in the build path.
3465341Sstever@gmail.com
3475341Sstever@gmail.com# The funky assignment to "[:]" is needed to replace the list contents
3485341Sstever@gmail.com# in place rather than reassign the symbol to a new list, which
3495341Sstever@gmail.com# doesn't work (obviously!).
3505341Sstever@gmail.comBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3515341Sstever@gmail.com
3525341Sstever@gmail.com# Generate a list of the unique build roots and configs that the
3535341Sstever@gmail.com# collected targets reference.
3545863Snate@binkert.orgvariant_paths = []
3555341Sstever@gmail.combuild_root = None
3565341Sstever@gmail.comfor t in BUILD_TARGETS:
3575863Snate@binkert.org    path_dirs = t.split('/')
3585341Sstever@gmail.com    try:
3595863Snate@binkert.org        build_top = rfind(path_dirs, 'build', -2)
3605863Snate@binkert.org    except:
3615341Sstever@gmail.com        print "Error: no non-leaf 'build' dir found on target path", t
3625863Snate@binkert.org        Exit(1)
3635863Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3645341Sstever@gmail.com    if not build_root:
3655863Snate@binkert.org        build_root = this_build_root
3665341Sstever@gmail.com    else:
3675871Snate@binkert.org        if this_build_root != build_root:
3685341Sstever@gmail.com            print "Error: build targets not under same build root\n"\
3695742Snate@binkert.org                  "  %s\n  %s" % (build_root, this_build_root)
3705742Snate@binkert.org            Exit(1)
3715742Snate@binkert.org    variant_path = joinpath('/',*path_dirs[:build_top+2])
3725341Sstever@gmail.com    if variant_path not in variant_paths:
3735742Snate@binkert.org        variant_paths.append(variant_path)
3745742Snate@binkert.org
3755341Sstever@gmail.com# Make sure build_root exists (might not if this is the first build there)
3766017Snate@binkert.orgif not isdir(build_root):
3776017Snate@binkert.org    mkdir(build_root)
3786017Snate@binkert.orgmain['BUILDROOT'] = build_root
3792632Sstever@eecs.umich.edu
3806016Snate@binkert.orgExport('main')
3815871Snate@binkert.org
3825871Snate@binkert.orgmain.SConsignFile(joinpath(build_root, "sconsign"))
3835871Snate@binkert.org
3845871Snate@binkert.org# Default duplicate option is to use hard links, but this messes up
3855871Snate@binkert.org# when you use emacs to edit a file in the target dir, as emacs moves
3865871Snate@binkert.org# file to file~ then copies to file, breaking the link.  Symbolic
3875871Snate@binkert.org# (soft) links work better.
3883942Ssaidi@eecs.umich.edumain.SetOption('duplicate', 'soft-copy')
3893940Ssaidi@eecs.umich.edu
3903918Ssaidi@eecs.umich.edu#
3913918Ssaidi@eecs.umich.edu# Set up global sticky variables... these are common to an entire build
3921858SN/A# tree (not specific to a particular build like ALPHA_SE)
3933918Ssaidi@eecs.umich.edu#
3943918Ssaidi@eecs.umich.edu
3953918Ssaidi@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
3963918Ssaidi@eecs.umich.edu
3975571Snate@binkert.orgglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3983940Ssaidi@eecs.umich.edu
3993940Ssaidi@eecs.umich.eduglobal_vars.AddVariables(
4003918Ssaidi@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
4013918Ssaidi@eecs.umich.edu    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
4023918Ssaidi@eecs.umich.edu    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
4033918Ssaidi@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
4043918Ssaidi@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
4053918Ssaidi@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
4065871Snate@binkert.org    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
4073918Ssaidi@eecs.umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
4083918Ssaidi@eecs.umich.edu    )
4093940Ssaidi@eecs.umich.edu
4103918Ssaidi@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
4113918Ssaidi@eecs.umich.eduglobal_vars.Update(main)
4125397Ssaidi@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
4135397Ssaidi@eecs.umich.edu
4145397Ssaidi@eecs.umich.edu# Save sticky variable settings back to current variables file
4155708Ssaidi@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
4165708Ssaidi@eecs.umich.edu
4175708Ssaidi@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
4185708Ssaidi@eecs.umich.edu# look for sources etc.  This list is exported as extras_dir_list.
4195708Ssaidi@eecs.umich.edubase_dir = main.srcdir.abspath
4205397Ssaidi@eecs.umich.eduif main['EXTRAS']:
4211851SN/A    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
4221851SN/Aelse:
4231858SN/A    extras_dir_list = []
424955SN/A
4253053Sstever@eecs.umich.eduExport('base_dir')
4263053Sstever@eecs.umich.eduExport('extras_dir_list')
4273053Sstever@eecs.umich.edu
4283053Sstever@eecs.umich.edu# the ext directory should be on the #includes path
4293053Sstever@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
4303053Sstever@eecs.umich.edu
4313053Sstever@eecs.umich.edudef strip_build_path(path, env):
4325871Snate@binkert.org    path = str(path)
4333053Sstever@eecs.umich.edu    variant_base = env['BUILDROOT'] + os.path.sep
4344742Sstever@eecs.umich.edu    if path.startswith(variant_base):
4354742Sstever@eecs.umich.edu        path = path[len(variant_base):]
4363053Sstever@eecs.umich.edu    elif path.startswith('build/'):
4373053Sstever@eecs.umich.edu        path = path[6:]
4383053Sstever@eecs.umich.edu    return path
4393053Sstever@eecs.umich.edu
4403053Sstever@eecs.umich.edu# Generate a string of the form:
4413053Sstever@eecs.umich.edu#   common/path/prefix/src1, src2 -> tgt1, tgt2
4423053Sstever@eecs.umich.edu# to print while building.
4433053Sstever@eecs.umich.educlass Transform(object):
4443053Sstever@eecs.umich.edu    # all specific color settings should be here and nowhere else
4452667Sstever@eecs.umich.edu    tool_color = termcap.Normal
4464554Sbinkertn@umich.edu    pfx_color = termcap.Yellow
4474554Sbinkertn@umich.edu    srcs_color = termcap.Yellow + termcap.Bold
4482667Sstever@eecs.umich.edu    arrow_color = termcap.Blue + termcap.Bold
4494554Sbinkertn@umich.edu    tgts_color = termcap.Yellow + termcap.Bold
4504554Sbinkertn@umich.edu
4514554Sbinkertn@umich.edu    def __init__(self, tool, max_sources=99):
4524554Sbinkertn@umich.edu        self.format = self.tool_color + (" [%8s] " % tool) \
4534554Sbinkertn@umich.edu                      + self.pfx_color + "%s" \
4544554Sbinkertn@umich.edu                      + self.srcs_color + "%s" \
4554554Sbinkertn@umich.edu                      + self.arrow_color + " -> " \
4564781Snate@binkert.org                      + self.tgts_color + "%s" \
4574554Sbinkertn@umich.edu                      + termcap.Normal
4584554Sbinkertn@umich.edu        self.max_sources = max_sources
4592667Sstever@eecs.umich.edu
4604554Sbinkertn@umich.edu    def __call__(self, target, source, env, for_signature=None):
4614554Sbinkertn@umich.edu        # truncate source list according to max_sources param
4624554Sbinkertn@umich.edu        source = source[0:self.max_sources]
4634554Sbinkertn@umich.edu        def strip(f):
4642667Sstever@eecs.umich.edu            return strip_build_path(str(f), env)
4654554Sbinkertn@umich.edu        if len(source) > 0:
4662667Sstever@eecs.umich.edu            srcs = map(strip, source)
4674554Sbinkertn@umich.edu        else:
4684554Sbinkertn@umich.edu            srcs = ['']
4692667Sstever@eecs.umich.edu        tgts = map(strip, target)
4705522Snate@binkert.org        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4715522Snate@binkert.org        # operation that has nothing to do with paths.
4725522Snate@binkert.org        com_pfx = os.path.commonprefix(srcs + tgts)
4735522Snate@binkert.org        com_pfx_len = len(com_pfx)
4745522Snate@binkert.org        if com_pfx:
4755522Snate@binkert.org            # do some cleanup and sanity checking on common prefix
4765522Snate@binkert.org            if com_pfx[-1] == ".":
4775522Snate@binkert.org                # prefix matches all but file extension: ok
4785522Snate@binkert.org                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4795522Snate@binkert.org                com_pfx = com_pfx[0:-1]
4805522Snate@binkert.org            elif com_pfx[-1] == "/":
4815522Snate@binkert.org                # common prefix is directory path: OK
4825522Snate@binkert.org                pass
4835522Snate@binkert.org            else:
4845522Snate@binkert.org                src0_len = len(srcs[0])
4855522Snate@binkert.org                tgt0_len = len(tgts[0])
4865522Snate@binkert.org                if src0_len == com_pfx_len:
4875522Snate@binkert.org                    # source is a substring of target, OK
4885522Snate@binkert.org                    pass
4895522Snate@binkert.org                elif tgt0_len == com_pfx_len:
4905522Snate@binkert.org                    # target is a substring of source, need to back up to
4915522Snate@binkert.org                    # avoid empty string on RHS of arrow
4925522Snate@binkert.org                    sep_idx = com_pfx.rfind(".")
4935522Snate@binkert.org                    if sep_idx != -1:
4945522Snate@binkert.org                        com_pfx = com_pfx[0:sep_idx]
4955522Snate@binkert.org                    else:
4962638Sstever@eecs.umich.edu                        com_pfx = ''
4972638Sstever@eecs.umich.edu                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4982638Sstever@eecs.umich.edu                    # still splitting at file extension: ok
4993716Sstever@eecs.umich.edu                    pass
5005522Snate@binkert.org                else:
5015522Snate@binkert.org                    # probably a fluke; ignore it
5025522Snate@binkert.org                    com_pfx = ''
5035522Snate@binkert.org        # recalculate length in case com_pfx was modified
5045522Snate@binkert.org        com_pfx_len = len(com_pfx)
5055522Snate@binkert.org        def fmt(files):
5061858SN/A            f = map(lambda s: s[com_pfx_len:], files)
5075227Ssaidi@eecs.umich.edu            return ', '.join(f)
5085227Ssaidi@eecs.umich.edu        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
5095227Ssaidi@eecs.umich.edu
5105227Ssaidi@eecs.umich.eduExport('Transform')
5115227Ssaidi@eecs.umich.edu
5125863Snate@binkert.org# enable the regression script to use the termcap
5135227Ssaidi@eecs.umich.edumain['TERMCAP'] = termcap
5145227Ssaidi@eecs.umich.edu
5155227Ssaidi@eecs.umich.eduif GetOption('verbose'):
5165227Ssaidi@eecs.umich.edu    def MakeAction(action, string, *args, **kwargs):
5175227Ssaidi@eecs.umich.edu        return Action(action, *args, **kwargs)
5185227Ssaidi@eecs.umich.eduelse:
5195227Ssaidi@eecs.umich.edu    MakeAction = Action
5205204Sstever@gmail.com    main['CCCOMSTR']        = Transform("CC")
5215204Sstever@gmail.com    main['CXXCOMSTR']       = Transform("CXX")
5225204Sstever@gmail.com    main['ASCOMSTR']        = Transform("AS")
5235204Sstever@gmail.com    main['SWIGCOMSTR']      = Transform("SWIG")
5245204Sstever@gmail.com    main['ARCOMSTR']        = Transform("AR", 0)
5255204Sstever@gmail.com    main['LINKCOMSTR']      = Transform("LINK", 0)
5265204Sstever@gmail.com    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5275204Sstever@gmail.com    main['M4COMSTR']        = Transform("M4")
5285204Sstever@gmail.com    main['SHCCCOMSTR']      = Transform("SHCC")
5295204Sstever@gmail.com    main['SHCXXCOMSTR']     = Transform("SHCXX")
5305204Sstever@gmail.comExport('MakeAction')
5315204Sstever@gmail.com
5325204Sstever@gmail.com# Initialize the Link-Time Optimization (LTO) flags
5335204Sstever@gmail.commain['LTO_CCFLAGS'] = []
5345204Sstever@gmail.commain['LTO_LDFLAGS'] = []
5355204Sstever@gmail.com
5365204Sstever@gmail.com# According to the readme, tcmalloc works best if the compiler doesn't
5375204Sstever@gmail.com# assume that we're using the builtin malloc and friends. These flags
5385204Sstever@gmail.com# are compiler-specific, so we need to set them after we detect which
5393118Sstever@eecs.umich.edu# compiler we're using.
5403118Sstever@eecs.umich.edumain['TCMALLOC_CCFLAGS'] = []
5413118Sstever@eecs.umich.edu
5423118Sstever@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5433118Sstever@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5445863Snate@binkert.org
5453118Sstever@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5465863Snate@binkert.orgmain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5473118Sstever@eecs.umich.eduif main['GCC'] + main['CLANG'] > 1:
5485863Snate@binkert.org    print 'Error: How can we have two at the same time?'
5495863Snate@binkert.org    Exit(1)
5505863Snate@binkert.org
5515863Snate@binkert.org# Set up default C++ compiler flags
5525863Snate@binkert.orgif main['GCC'] or main['CLANG']:
5535863Snate@binkert.org    # As gcc and clang share many flags, do the common parts here
5545863Snate@binkert.org    main.Append(CCFLAGS=['-pipe'])
5555863Snate@binkert.org    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5566003Snate@binkert.org    # Enable -Wall and then disable the few warnings that we
5575863Snate@binkert.org    # consistently violate
5585863Snate@binkert.org    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5595863Snate@binkert.org    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
5605863Snate@binkert.org    # actually use that name, so we stick with c++0x
5615863Snate@binkert.org    main.Append(CXXFLAGS=['-std=c++0x'])
5625863Snate@binkert.org    # Add selected sanity checks from -Wextra
5635863Snate@binkert.org    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5645863Snate@binkert.org                          '-Woverloaded-virtual'])
5655863Snate@binkert.orgelse:
5665863Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5675863Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
5685863Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5695863Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
5705863Snate@binkert.org    if not CXX_version:
5715863Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5723118Sstever@eecs.umich.edu               termcap.Normal
5735863Snate@binkert.org    else:
5743118Sstever@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
5753118Sstever@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
5765863Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
5775863Snate@binkert.org    print "       environment."
5785863Snate@binkert.org    print "       "
5795863Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
5805863Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
5815863Snate@binkert.org    print "       src/SConscript to support that compiler."
5823118Sstever@eecs.umich.edu    Exit(1)
5833483Ssaidi@eecs.umich.edu
5843494Ssaidi@eecs.umich.eduif main['GCC']:
5853494Ssaidi@eecs.umich.edu    # Check for a supported version of gcc. >= 4.6 is chosen for its
5863483Ssaidi@eecs.umich.edu    # level of c++11 support. See
5873483Ssaidi@eecs.umich.edu    # http://gcc.gnu.org/projects/cxx0x.html for details. 4.6 is also
5883483Ssaidi@eecs.umich.edu    # the first version with proper LTO support.
5893053Sstever@eecs.umich.edu    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5903053Sstever@eecs.umich.edu    if compareVersions(gcc_version, "4.6") < 0:
5913918Ssaidi@eecs.umich.edu        print 'Error: gcc version 4.6 or newer required.'
5923053Sstever@eecs.umich.edu        print '       Installed version:', gcc_version
5933053Sstever@eecs.umich.edu        Exit(1)
5943053Sstever@eecs.umich.edu
5953053Sstever@eecs.umich.edu    main['GCC_VERSION'] = gcc_version
5963053Sstever@eecs.umich.edu
5971858SN/A    # gcc from version 4.8 and above generates "rep; ret" instructions
5981858SN/A    # to avoid performance penalties on certain AMD chips. Older
5991858SN/A    # assemblers detect this as an error, "Error: expecting string
6001858SN/A    # instruction after `rep'"
6011858SN/A    if compareVersions(gcc_version, "4.8") > 0:
6021858SN/A        as_version = readCommand([main['AS'], '-v', '/dev/null'],
6035863Snate@binkert.org                                 exception=False).split()
6045863Snate@binkert.org
6051859SN/A        if not as_version or compareVersions(as_version[-1], "2.23") < 0:
6065863Snate@binkert.org            print termcap.Yellow + termcap.Bold + \
6071858SN/A                'Warning: This combination of gcc and binutils have' + \
6085863Snate@binkert.org                ' known incompatibilities.\n' + \
6091858SN/A                '         If you encounter build problems, please update ' + \
6101859SN/A                'binutils to 2.23.' + \
6111859SN/A                termcap.Normal
6125863Snate@binkert.org
6133053Sstever@eecs.umich.edu    # Make sure we warn if the user has requested to compile with the
6143053Sstever@eecs.umich.edu    # Undefined Benahvior Sanitizer and this version of gcc does not
6153053Sstever@eecs.umich.edu    # support it.
6163053Sstever@eecs.umich.edu    if GetOption('with_ubsan') and \
6171859SN/A            compareVersions(gcc_version, '4.9') < 0:
6181859SN/A        print termcap.Yellow + termcap.Bold + \
6191859SN/A            'Warning: UBSan is only supported using gcc 4.9 and later.' + \
6201859SN/A            termcap.Normal
6211859SN/A
6221859SN/A    # Add the appropriate Link-Time Optimization (LTO) flags
6231859SN/A    # unless LTO is explicitly turned off. Note that these flags
6241859SN/A    # are only used by the fast target.
6251862SN/A    if not GetOption('no_lto'):
6261859SN/A        # Pass the LTO flag when compiling to produce GIMPLE
6271859SN/A        # output, we merely create the flags here and only append
6281859SN/A        # them later
6295863Snate@binkert.org        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6305863Snate@binkert.org
6315863Snate@binkert.org        # Use the same amount of jobs for LTO as we are running
6325863Snate@binkert.org        # scons with
6331858SN/A        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
6341858SN/A
6355863Snate@binkert.org    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
6365863Snate@binkert.org                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6375863Snate@binkert.org
6385863Snate@binkert.orgelif main['CLANG']:
6395863Snate@binkert.org    # Check for a supported version of clang, >= 3.0 is needed to
6405871Snate@binkert.org    # support similar features as gcc 4.6. See
6415871Snate@binkert.org    # http://clang.llvm.org/cxx_status.html for details
6422139SN/A    clang_version_re = re.compile(".* version (\d+\.\d+)")
6434202Sbinkertn@umich.edu    clang_version_match = clang_version_re.search(CXX_version)
6444202Sbinkertn@umich.edu    if (clang_version_match):
6452139SN/A        clang_version = clang_version_match.groups()[0]
6462155SN/A        if compareVersions(clang_version, "3.0") < 0:
6474202Sbinkertn@umich.edu            print 'Error: clang version 3.0 or newer required.'
6484202Sbinkertn@umich.edu            print '       Installed version:', clang_version
6494202Sbinkertn@umich.edu            Exit(1)
6502155SN/A    else:
6515863Snate@binkert.org        print 'Error: Unable to determine clang version.'
6521869SN/A        Exit(1)
6531869SN/A
6545863Snate@binkert.org    # clang has a few additional warnings that we disable,
6555863Snate@binkert.org    # tautological comparisons are allowed due to unsigned integers
6564202Sbinkertn@umich.edu    # being compared to constants that happen to be 0, and extraneous
6575863Snate@binkert.org    # parantheses are allowed due to Ruby's printing of the AST,
6585863Snate@binkert.org    # finally self assignments are allowed as the generated CPU code
6595863Snate@binkert.org    # is relying on this
6604202Sbinkertn@umich.edu    main.Append(CCFLAGS=['-Wno-tautological-compare',
6614202Sbinkertn@umich.edu                         '-Wno-parentheses',
6625863Snate@binkert.org                         '-Wno-self-assign',
6635742Snate@binkert.org                         # Some versions of libstdc++ (4.8?) seem to
6645742Snate@binkert.org                         # use struct hash and class hash
6655341Sstever@gmail.com                         # interchangeably.
6665342Sstever@gmail.com                         '-Wno-mismatched-tags',
6675342Sstever@gmail.com                         ])
6684202Sbinkertn@umich.edu
6694202Sbinkertn@umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6704202Sbinkertn@umich.edu
6714202Sbinkertn@umich.edu    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6724202Sbinkertn@umich.edu    # opposed to libstdc++, as the later is dated.
6735863Snate@binkert.org    if sys.platform == "darwin":
6745863Snate@binkert.org        main.Append(CXXFLAGS=['-stdlib=libc++'])
6755863Snate@binkert.org        main.Append(LIBS=['c++'])
6765863Snate@binkert.org
6775863Snate@binkert.orgelse:
6785863Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6795863Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
6805863Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6815863Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
6825863Snate@binkert.org    if not CXX_version:
6835863Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6845863Snate@binkert.org               termcap.Normal
6855863Snate@binkert.org    else:
6865863Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
6875863Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
6885863Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
6895863Snate@binkert.org    print "       environment."
6905863Snate@binkert.org    print "       "
6915863Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
6925863Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
6935952Ssaidi@eecs.umich.edu    print "       src/SConscript to support that compiler."
6941869SN/A    Exit(1)
6951858SN/A
6965863Snate@binkert.org# Set up common yacc/bison flags (needed for Ruby)
6975863Snate@binkert.orgmain['YACCFLAGS'] = '-d'
6981869SN/Amain['YACCHXXFILESUFFIX'] = '.hh'
6991858SN/A
7005863Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
7015863Snate@binkert.org# extra 'qdo' every time we run scons.
7025863Snate@binkert.orgif main['BATCH']:
7035863Snate@binkert.org    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
7045952Ssaidi@eecs.umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
7051858SN/A    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
706955SN/A    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
707955SN/A    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
7081869SN/A
7091869SN/Aif sys.platform == 'cygwin':
7101869SN/A    # cygwin has some header file issues...
7111869SN/A    main.Append(CCFLAGS=["-Wno-uninitialized"])
7121869SN/A
7135863Snate@binkert.org# Check for the protobuf compiler
7145863Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
7155863Snate@binkert.org                             exception='').split()
7161869SN/A
7175863Snate@binkert.org# First two words should be "libprotoc x.y.z"
7181869SN/Aif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
7195863Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
7201869SN/A        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
7211869SN/A        '         Please install protobuf-compiler for tracing support.' + \
7221869SN/A        termcap.Normal
7231869SN/A    main['PROTOC'] = False
7241869SN/Aelse:
7255863Snate@binkert.org    # Based on the availability of the compress stream wrappers,
7265863Snate@binkert.org    # require 2.1.0
7271869SN/A    min_protoc_version = '2.1.0'
7281869SN/A    if compareVersions(protoc_version[1], min_protoc_version) < 0:
7291869SN/A        print termcap.Yellow + termcap.Bold + \
7301869SN/A            'Warning: protoc version', min_protoc_version, \
7311869SN/A            'or newer required.\n' + \
7321869SN/A            '         Installed version:', protoc_version[1], \
7331869SN/A            termcap.Normal
7345863Snate@binkert.org        main['PROTOC'] = False
7355863Snate@binkert.org    else:
7361869SN/A        # Attempt to determine the appropriate include path and
7375863Snate@binkert.org        # library path using pkg-config, that means we also need to
7385863Snate@binkert.org        # check for pkg-config. Note that it is possible to use
7393356Sbinkertn@umich.edu        # protobuf without the involvement of pkg-config. Later on we
7403356Sbinkertn@umich.edu        # check go a library config check and at that point the test
7413356Sbinkertn@umich.edu        # will fail if libprotobuf cannot be found.
7423356Sbinkertn@umich.edu        if readCommand(['pkg-config', '--version'], exception=''):
7433356Sbinkertn@umich.edu            try:
7444781Snate@binkert.org                # Attempt to establish what linking flags to add for protobuf
7455863Snate@binkert.org                # using pkg-config
7465863Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7471869SN/A            except:
7481869SN/A                print termcap.Yellow + termcap.Bold + \
7491869SN/A                    'Warning: pkg-config could not get protobuf flags.' + \
7501869SN/A                    termcap.Normal
7511869SN/A
7522638Sstever@eecs.umich.edu# Check for SWIG
7532638Sstever@eecs.umich.eduif not main.has_key('SWIG'):
7545871Snate@binkert.org    print 'Error: SWIG utility not found.'
7552638Sstever@eecs.umich.edu    print '       Please install (see http://www.swig.org) and retry.'
7565749Scws3k@cs.virginia.edu    Exit(1)
7575749Scws3k@cs.virginia.edu
7585871Snate@binkert.org# Check for appropriate SWIG version
7595749Scws3k@cs.virginia.eduswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7601869SN/A# First 3 words should be "SWIG Version x.y.z"
7611869SN/Aif len(swig_version) < 3 or \
7623546Sgblack@eecs.umich.edu        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7633546Sgblack@eecs.umich.edu    print 'Error determining SWIG version.'
7643546Sgblack@eecs.umich.edu    Exit(1)
7653546Sgblack@eecs.umich.edu
7664202Sbinkertn@umich.edumin_swig_version = '2.0.4'
7675863Snate@binkert.orgif compareVersions(swig_version[2], min_swig_version) < 0:
7683546Sgblack@eecs.umich.edu    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7693546Sgblack@eecs.umich.edu    print '       Installed version:', swig_version[2]
7703546Sgblack@eecs.umich.edu    Exit(1)
7713546Sgblack@eecs.umich.edu
7724781Snate@binkert.org# Check for known incompatibilities. The standard library shipped with
7735863Snate@binkert.org# gcc >= 4.9 does not play well with swig versions prior to 3.0
7744781Snate@binkert.orgif main['GCC'] and compareVersions(gcc_version, '4.9') >= 0 and \
7754781Snate@binkert.org        compareVersions(swig_version[2], '3.0') < 0:
7764781Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
7774781Snate@binkert.org        'Warning: This combination of gcc and swig have' + \
7784781Snate@binkert.org        ' known incompatibilities.\n' + \
7795863Snate@binkert.org        '         If you encounter build problems, please update ' + \
7804781Snate@binkert.org        'swig to 3.0 or later.' + \
7814781Snate@binkert.org        termcap.Normal
7824781Snate@binkert.org
7834781Snate@binkert.org# Set up SWIG flags & scanner
7843546Sgblack@eecs.umich.eduswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7853546Sgblack@eecs.umich.edumain.Append(SWIGFLAGS=swig_flags)
7863546Sgblack@eecs.umich.edu
7874781Snate@binkert.org# Check for 'timeout' from GNU coreutils.  If present, regressions
7883546Sgblack@eecs.umich.edu# will be run with a time limit.
7893546Sgblack@eecs.umich.eduTIMEOUT_version = readCommand(['timeout', '--version'], exception=False)
7903546Sgblack@eecs.umich.edumain['TIMEOUT'] = TIMEOUT_version and TIMEOUT_version.find('timeout') == 0
7913546Sgblack@eecs.umich.edu
7923546Sgblack@eecs.umich.edu# filter out all existing swig scanners, they mess up the dependency
7933546Sgblack@eecs.umich.edu# stuff for some reason
7943546Sgblack@eecs.umich.eduscanners = []
7953546Sgblack@eecs.umich.edufor scanner in main['SCANNERS']:
7963546Sgblack@eecs.umich.edu    skeys = scanner.skeys
7973546Sgblack@eecs.umich.edu    if skeys == '.i':
7984202Sbinkertn@umich.edu        continue
7993546Sgblack@eecs.umich.edu
8003546Sgblack@eecs.umich.edu    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
8013546Sgblack@eecs.umich.edu        continue
802955SN/A
803955SN/A    scanners.append(scanner)
804955SN/A
805955SN/A# add the new swig scanner that we like better
8061858SN/Afrom SCons.Scanner import ClassicCPP as CPPScanner
8071858SN/Aswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
8081858SN/Ascanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
8095863Snate@binkert.org
8105863Snate@binkert.org# replace the scanners list that has what we want
8115343Sstever@gmail.commain['SCANNERS'] = scanners
8125343Sstever@gmail.com
8135863Snate@binkert.org# Add a custom Check function to the Configure context so that we can
8145863Snate@binkert.org# figure out if the compiler adds leading underscores to global
8154773Snate@binkert.org# variables.  This is needed for the autogenerated asm files that we
8165863Snate@binkert.org# use for embedding the python code.
8172632Sstever@eecs.umich.edudef CheckLeading(context):
8185863Snate@binkert.org    context.Message("Checking for leading underscore in global variables...")
8192023SN/A    # 1) Define a global variable called x from asm so the C compiler
8205863Snate@binkert.org    #    won't change the symbol at all.
8215863Snate@binkert.org    # 2) Declare that variable.
8225863Snate@binkert.org    # 3) Use the variable
8235863Snate@binkert.org    #
8245863Snate@binkert.org    # If the compiler prepends an underscore, this will successfully
8255863Snate@binkert.org    # link because the external symbol 'x' will be called '_x' which
8265863Snate@binkert.org    # was defined by the asm statement.  If the compiler does not
8275863Snate@binkert.org    # prepend an underscore, this will not successfully link because
8285863Snate@binkert.org    # '_x' will have been defined by assembly, while the C portion of
8292632Sstever@eecs.umich.edu    # the code will be trying to use 'x'
8305863Snate@binkert.org    ret = context.TryLink('''
8312023SN/A        asm(".globl _x; _x: .byte 0");
8322632Sstever@eecs.umich.edu        extern int x;
8335863Snate@binkert.org        int main() { return x; }
8345342Sstever@gmail.com        ''', extension=".c")
8355863Snate@binkert.org    context.env.Append(LEADING_UNDERSCORE=ret)
8362632Sstever@eecs.umich.edu    context.Result(ret)
8375863Snate@binkert.org    return ret
8385863Snate@binkert.org
8392632Sstever@eecs.umich.edu# Add a custom Check function to test for structure members.
8405863Snate@binkert.orgdef CheckMember(context, include, decl, member, include_quotes="<>"):
8415863Snate@binkert.org    context.Message("Checking for member %s in %s..." %
8425863Snate@binkert.org                    (member, decl))
8435863Snate@binkert.org    text = """
8445863Snate@binkert.org#include %(header)s
8455863Snate@binkert.orgint main(){
8462632Sstever@eecs.umich.edu  %(decl)s test;
8475863Snate@binkert.org  (void)test.%(member)s;
8485863Snate@binkert.org  return 0;
8492632Sstever@eecs.umich.edu};
8501888SN/A""" % { "header" : include_quotes[0] + include + include_quotes[1],
8515863Snate@binkert.org        "decl" : decl,
8525863Snate@binkert.org        "member" : member,
8535863Snate@binkert.org        }
8541858SN/A
8555863Snate@binkert.org    ret = context.TryCompile(text, extension=".cc")
8565863Snate@binkert.org    context.Result(ret)
8575863Snate@binkert.org    return ret
8585863Snate@binkert.org
8592598SN/A# Platform-specific configuration.  Note again that we assume that all
8605863Snate@binkert.org# builds under a given build root run on the same host platform.
8611858SN/Aconf = Configure(main,
8621858SN/A                 conf_dir = joinpath(build_root, '.scons_config'),
8631858SN/A                 log_file = joinpath(build_root, 'scons_config.log'),
8645863Snate@binkert.org                 custom_tests = {
8651858SN/A        'CheckLeading' : CheckLeading,
8661858SN/A        'CheckMember' : CheckMember,
8671858SN/A        })
8685863Snate@binkert.org
8691871SN/A# Check for leading underscores.  Don't really need to worry either
8701858SN/A# way so don't need to check the return code.
8711858SN/Aconf.CheckLeading()
8721858SN/A
8731858SN/A# Check if we should compile a 64 bit binary on Mac OS X/Darwin
8741858SN/Atry:
8751858SN/A    import platform
8761858SN/A    uname = platform.uname()
8775863Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
8781858SN/A        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
8791858SN/A            main.Append(CCFLAGS=['-arch', 'x86_64'])
8805863Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
8811859SN/A            main.Append(LINKFLAGS=['-arch', 'x86_64'])
8821859SN/A            main.Append(ASFLAGS=['-arch', 'x86_64'])
8831869SN/Aexcept:
8845863Snate@binkert.org    pass
8855863Snate@binkert.org
8861869SN/A# Recent versions of scons substitute a "Null" object for Configure()
8871965SN/A# when configuration isn't necessary, e.g., if the "--help" option is
8881965SN/A# present.  Unfortuantely this Null object always returns false,
8891965SN/A# breaking all our configuration checks.  We replace it with our own
8902761Sstever@eecs.umich.edu# more optimistic null object that returns True instead.
8915863Snate@binkert.orgif not conf:
8921869SN/A    def NullCheck(*args, **kwargs):
8935863Snate@binkert.org        return True
8942667Sstever@eecs.umich.edu
8951869SN/A    class NullConf:
8961869SN/A        def __init__(self, env):
8972929Sktlim@umich.edu            self.env = env
8982929Sktlim@umich.edu        def Finish(self):
8995863Snate@binkert.org            return self.env
9002929Sktlim@umich.edu        def __getattr__(self, mname):
901955SN/A            return NullCheck
9022598SN/A
903    conf = NullConf(main)
904
905# Cache build files in the supplied directory.
906if main['M5_BUILD_CACHE']:
907    print 'Using build cache located at', main['M5_BUILD_CACHE']
908    CacheDir(main['M5_BUILD_CACHE'])
909
910if not GetOption('without_python'):
911    # Find Python include and library directories for embedding the
912    # interpreter. We rely on python-config to resolve the appropriate
913    # includes and linker flags. ParseConfig does not seem to understand
914    # the more exotic linker flags such as -Xlinker and -export-dynamic so
915    # we add them explicitly below. If you want to link in an alternate
916    # version of python, see above for instructions on how to invoke
917    # scons with the appropriate PATH set.
918    #
919    # First we check if python2-config exists, else we use python-config
920    python_config = readCommand(['which', 'python2-config'],
921                                exception='').strip()
922    if not os.path.exists(python_config):
923        python_config = readCommand(['which', 'python-config'],
924                                    exception='').strip()
925    py_includes = readCommand([python_config, '--includes'],
926                              exception='').split()
927    # Strip the -I from the include folders before adding them to the
928    # CPPPATH
929    main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
930
931    # Read the linker flags and split them into libraries and other link
932    # flags. The libraries are added later through the call the CheckLib.
933    py_ld_flags = readCommand([python_config, '--ldflags'],
934        exception='').split()
935    py_libs = []
936    for lib in py_ld_flags:
937         if not lib.startswith('-l'):
938             main.Append(LINKFLAGS=[lib])
939         else:
940             lib = lib[2:]
941             if lib not in py_libs:
942                 py_libs.append(lib)
943
944    # verify that this stuff works
945    if not conf.CheckHeader('Python.h', '<>'):
946        print "Error: can't find Python.h header in", py_includes
947        print "Install Python headers (package python-dev on Ubuntu and RedHat)"
948        Exit(1)
949
950    for lib in py_libs:
951        if not conf.CheckLib(lib):
952            print "Error: can't find library %s required by python" % lib
953            Exit(1)
954
955# On Solaris you need to use libsocket for socket ops
956if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
957   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
958       print "Can't find library with socket calls (e.g. accept())"
959       Exit(1)
960
961# Check for zlib.  If the check passes, libz will be automatically
962# added to the LIBS environment variable.
963if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
964    print 'Error: did not find needed zlib compression library '\
965          'and/or zlib.h header file.'
966    print '       Please install zlib and try again.'
967    Exit(1)
968
969# If we have the protobuf compiler, also make sure we have the
970# development libraries. If the check passes, libprotobuf will be
971# automatically added to the LIBS environment variable. After
972# this, we can use the HAVE_PROTOBUF flag to determine if we have
973# got both protoc and libprotobuf available.
974main['HAVE_PROTOBUF'] = main['PROTOC'] and \
975    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
976                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
977
978# If we have the compiler but not the library, print another warning.
979if main['PROTOC'] and not main['HAVE_PROTOBUF']:
980    print termcap.Yellow + termcap.Bold + \
981        'Warning: did not find protocol buffer library and/or headers.\n' + \
982    '       Please install libprotobuf-dev for tracing support.' + \
983    termcap.Normal
984
985# Check for librt.
986have_posix_clock = \
987    conf.CheckLibWithHeader(None, 'time.h', 'C',
988                            'clock_nanosleep(0,0,NULL,NULL);') or \
989    conf.CheckLibWithHeader('rt', 'time.h', 'C',
990                            'clock_nanosleep(0,0,NULL,NULL);')
991
992have_posix_timers = \
993    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
994                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
995
996if not GetOption('without_tcmalloc'):
997    if conf.CheckLib('tcmalloc'):
998        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
999    elif conf.CheckLib('tcmalloc_minimal'):
1000        main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
1001    else:
1002        print termcap.Yellow + termcap.Bold + \
1003              "You can get a 12% performance improvement by "\
1004              "installing tcmalloc (libgoogle-perftools-dev package "\
1005              "on Ubuntu or RedHat)." + termcap.Normal
1006
1007if not have_posix_clock:
1008    print "Can't find library for POSIX clocks."
1009
1010# Check for <fenv.h> (C99 FP environment control)
1011have_fenv = conf.CheckHeader('fenv.h', '<>')
1012if not have_fenv:
1013    print "Warning: Header file <fenv.h> not found."
1014    print "         This host has no IEEE FP rounding mode control."
1015
1016# Check if we should enable KVM-based hardware virtualization. The API
1017# we rely on exists since version 2.6.36 of the kernel, but somehow
1018# the KVM_API_VERSION does not reflect the change. We test for one of
1019# the types as a fall back.
1020have_kvm = conf.CheckHeader('linux/kvm.h', '<>') and \
1021    conf.CheckTypeSize('struct kvm_xsave', '#include <linux/kvm.h>') != 0
1022if not have_kvm:
1023    print "Info: Compatible header file <linux/kvm.h> not found, " \
1024        "disabling KVM support."
1025
1026# Check if the requested target ISA is compatible with the host
1027def is_isa_kvm_compatible(isa):
1028    isa_comp_table = {
1029        "arm" : ( "armv7l" ),
1030        "x86" : ( "x86_64" ),
1031        }
1032    try:
1033        import platform
1034        host_isa = platform.machine()
1035    except:
1036        print "Warning: Failed to determine host ISA."
1037        return False
1038
1039    return host_isa in isa_comp_table.get(isa, [])
1040
1041
1042# Check if the exclude_host attribute is available. We want this to
1043# get accurate instruction counts in KVM.
1044main['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
1045    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
1046
1047
1048######################################################################
1049#
1050# Finish the configuration
1051#
1052main = conf.Finish()
1053
1054######################################################################
1055#
1056# Collect all non-global variables
1057#
1058
1059# Define the universe of supported ISAs
1060all_isa_list = [ ]
1061Export('all_isa_list')
1062
1063class CpuModel(object):
1064    '''The CpuModel class encapsulates everything the ISA parser needs to
1065    know about a particular CPU model.'''
1066
1067    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
1068    dict = {}
1069
1070    # Constructor.  Automatically adds models to CpuModel.dict.
1071    def __init__(self, name, default=False):
1072        self.name = name           # name of model
1073
1074        # This cpu is enabled by default
1075        self.default = default
1076
1077        # Add self to dict
1078        if name in CpuModel.dict:
1079            raise AttributeError, "CpuModel '%s' already registered" % name
1080        CpuModel.dict[name] = self
1081
1082Export('CpuModel')
1083
1084# Sticky variables get saved in the variables file so they persist from
1085# one invocation to the next (unless overridden, in which case the new
1086# value becomes sticky).
1087sticky_vars = Variables(args=ARGUMENTS)
1088Export('sticky_vars')
1089
1090# Sticky variables that should be exported
1091export_vars = []
1092Export('export_vars')
1093
1094# For Ruby
1095all_protocols = []
1096Export('all_protocols')
1097protocol_dirs = []
1098Export('protocol_dirs')
1099slicc_includes = []
1100Export('slicc_includes')
1101
1102# Walk the tree and execute all SConsopts scripts that wil add to the
1103# above variables
1104if GetOption('verbose'):
1105    print "Reading SConsopts"
1106for bdir in [ base_dir ] + extras_dir_list:
1107    if not isdir(bdir):
1108        print "Error: directory '%s' does not exist" % bdir
1109        Exit(1)
1110    for root, dirs, files in os.walk(bdir):
1111        if 'SConsopts' in files:
1112            if GetOption('verbose'):
1113                print "Reading", joinpath(root, 'SConsopts')
1114            SConscript(joinpath(root, 'SConsopts'))
1115
1116all_isa_list.sort()
1117
1118sticky_vars.AddVariables(
1119    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
1120    ListVariable('CPU_MODELS', 'CPU models',
1121                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
1122                 sorted(CpuModel.dict.keys())),
1123    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
1124                 False),
1125    BoolVariable('SS_COMPATIBLE_FP',
1126                 'Make floating-point results compatible with SimpleScalar',
1127                 False),
1128    BoolVariable('USE_SSE2',
1129                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
1130                 False),
1131    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1132    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
1133    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
1134    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
1135    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1136                  all_protocols),
1137    )
1138
1139# These variables get exported to #defines in config/*.hh (see src/SConscript).
1140export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
1141                'USE_POSIX_CLOCK', 'USE_KVM', 'PROTOCOL', 'HAVE_PROTOBUF',
1142                'HAVE_PERF_ATTR_EXCLUDE_HOST']
1143
1144###################################################
1145#
1146# Define a SCons builder for configuration flag headers.
1147#
1148###################################################
1149
1150# This function generates a config header file that #defines the
1151# variable symbol to the current variable setting (0 or 1).  The source
1152# operands are the name of the variable and a Value node containing the
1153# value of the variable.
1154def build_config_file(target, source, env):
1155    (variable, value) = [s.get_contents() for s in source]
1156    f = file(str(target[0]), 'w')
1157    print >> f, '#define', variable, value
1158    f.close()
1159    return None
1160
1161# Combine the two functions into a scons Action object.
1162config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1163
1164# The emitter munges the source & target node lists to reflect what
1165# we're really doing.
1166def config_emitter(target, source, env):
1167    # extract variable name from Builder arg
1168    variable = str(target[0])
1169    # True target is config header file
1170    target = joinpath('config', variable.lower() + '.hh')
1171    val = env[variable]
1172    if isinstance(val, bool):
1173        # Force value to 0/1
1174        val = int(val)
1175    elif isinstance(val, str):
1176        val = '"' + val + '"'
1177
1178    # Sources are variable name & value (packaged in SCons Value nodes)
1179    return ([target], [Value(variable), Value(val)])
1180
1181config_builder = Builder(emitter = config_emitter, action = config_action)
1182
1183main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1184
1185# libelf build is shared across all configs in the build root.
1186main.SConscript('ext/libelf/SConscript',
1187                variant_dir = joinpath(build_root, 'libelf'))
1188
1189# gzstream build is shared across all configs in the build root.
1190main.SConscript('ext/gzstream/SConscript',
1191                variant_dir = joinpath(build_root, 'gzstream'))
1192
1193# libfdt build is shared across all configs in the build root.
1194main.SConscript('ext/libfdt/SConscript',
1195                variant_dir = joinpath(build_root, 'libfdt'))
1196
1197# fputils build is shared across all configs in the build root.
1198main.SConscript('ext/fputils/SConscript',
1199                variant_dir = joinpath(build_root, 'fputils'))
1200
1201# DRAMSim2 build is shared across all configs in the build root.
1202main.SConscript('ext/dramsim2/SConscript',
1203                variant_dir = joinpath(build_root, 'dramsim2'))
1204
1205# DRAMPower build is shared across all configs in the build root.
1206main.SConscript('ext/drampower/SConscript',
1207                variant_dir = joinpath(build_root, 'drampower'))
1208
1209###################################################
1210#
1211# This function is used to set up a directory with switching headers
1212#
1213###################################################
1214
1215main['ALL_ISA_LIST'] = all_isa_list
1216all_isa_deps = {}
1217def make_switching_dir(dname, switch_headers, env):
1218    # Generate the header.  target[0] is the full path of the output
1219    # header to generate.  'source' is a dummy variable, since we get the
1220    # list of ISAs from env['ALL_ISA_LIST'].
1221    def gen_switch_hdr(target, source, env):
1222        fname = str(target[0])
1223        isa = env['TARGET_ISA'].lower()
1224        try:
1225            f = open(fname, 'w')
1226            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1227            f.close()
1228        except IOError:
1229            print "Failed to create %s" % fname
1230            raise
1231
1232    # Build SCons Action object. 'varlist' specifies env vars that this
1233    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1234    # should get re-executed.
1235    switch_hdr_action = MakeAction(gen_switch_hdr,
1236                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1237
1238    # Instantiate actions for each header
1239    for hdr in switch_headers:
1240        env.Command(hdr, [], switch_hdr_action)
1241
1242    isa_target = Dir('.').up().name.lower().replace('_', '-')
1243    env['PHONY_BASE'] = '#'+isa_target
1244    all_isa_deps[isa_target] = None
1245
1246Export('make_switching_dir')
1247
1248# all-isas -> all-deps -> all-environs -> all_targets
1249main.Alias('#all-isas', [])
1250main.Alias('#all-deps', '#all-isas')
1251
1252# Dummy target to ensure all environments are created before telling
1253# SCons what to actually make (the command line arguments).  We attach
1254# them to the dependence graph after the environments are complete.
1255ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1256def environsComplete(target, source, env):
1257    for t in ORIG_BUILD_TARGETS:
1258        main.Depends('#all-targets', t)
1259
1260# Each build/* switching_dir attaches its *-environs target to #all-environs.
1261main.Append(BUILDERS = {'CompleteEnvirons' :
1262                        Builder(action=MakeAction(environsComplete, None))})
1263main.CompleteEnvirons('#all-environs', [])
1264
1265def doNothing(**ignored): pass
1266main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1267
1268# The final target to which all the original targets ultimately get attached.
1269main.Dummy('#all-targets', '#all-environs')
1270BUILD_TARGETS[:] = ['#all-targets']
1271
1272###################################################
1273#
1274# Define build environments for selected configurations.
1275#
1276###################################################
1277
1278for variant_path in variant_paths:
1279    if not GetOption('silent'):
1280        print "Building in", variant_path
1281
1282    # Make a copy of the build-root environment to use for this config.
1283    env = main.Clone()
1284    env['BUILDDIR'] = variant_path
1285
1286    # variant_dir is the tail component of build path, and is used to
1287    # determine the build parameters (e.g., 'ALPHA_SE')
1288    (build_root, variant_dir) = splitpath(variant_path)
1289
1290    # Set env variables according to the build directory config.
1291    sticky_vars.files = []
1292    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1293    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1294    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1295    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1296    if isfile(current_vars_file):
1297        sticky_vars.files.append(current_vars_file)
1298        if not GetOption('silent'):
1299            print "Using saved variables file %s" % current_vars_file
1300    else:
1301        # Build dir-specific variables file doesn't exist.
1302
1303        # Make sure the directory is there so we can create it later
1304        opt_dir = dirname(current_vars_file)
1305        if not isdir(opt_dir):
1306            mkdir(opt_dir)
1307
1308        # Get default build variables from source tree.  Variables are
1309        # normally determined by name of $VARIANT_DIR, but can be
1310        # overridden by '--default=' arg on command line.
1311        default = GetOption('default')
1312        opts_dir = joinpath(main.root.abspath, 'build_opts')
1313        if default:
1314            default_vars_files = [joinpath(build_root, 'variables', default),
1315                                  joinpath(opts_dir, default)]
1316        else:
1317            default_vars_files = [joinpath(opts_dir, variant_dir)]
1318        existing_files = filter(isfile, default_vars_files)
1319        if existing_files:
1320            default_vars_file = existing_files[0]
1321            sticky_vars.files.append(default_vars_file)
1322            print "Variables file %s not found,\n  using defaults in %s" \
1323                  % (current_vars_file, default_vars_file)
1324        else:
1325            print "Error: cannot find variables file %s or " \
1326                  "default file(s) %s" \
1327                  % (current_vars_file, ' or '.join(default_vars_files))
1328            Exit(1)
1329
1330    # Apply current variable settings to env
1331    sticky_vars.Update(env)
1332
1333    help_texts["local_vars"] += \
1334        "Build variables for %s:\n" % variant_dir \
1335                 + sticky_vars.GenerateHelpText(env)
1336
1337    # Process variable settings.
1338
1339    if not have_fenv and env['USE_FENV']:
1340        print "Warning: <fenv.h> not available; " \
1341              "forcing USE_FENV to False in", variant_dir + "."
1342        env['USE_FENV'] = False
1343
1344    if not env['USE_FENV']:
1345        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1346        print "         FP results may deviate slightly from other platforms."
1347
1348    if env['EFENCE']:
1349        env.Append(LIBS=['efence'])
1350
1351    if env['USE_KVM']:
1352        if not have_kvm:
1353            print "Warning: Can not enable KVM, host seems to lack KVM support"
1354            env['USE_KVM'] = False
1355        elif not have_posix_timers:
1356            print "Warning: Can not enable KVM, host seems to lack support " \
1357                "for POSIX timers"
1358            env['USE_KVM'] = False
1359        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1360            print "Info: KVM support disabled due to unsupported host and " \
1361                "target ISA combination"
1362            env['USE_KVM'] = False
1363
1364    # Warn about missing optional functionality
1365    if env['USE_KVM']:
1366        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1367            print "Warning: perf_event headers lack support for the " \
1368                "exclude_host attribute. KVM instruction counts will " \
1369                "be inaccurate."
1370
1371    # Save sticky variable settings back to current variables file
1372    sticky_vars.Save(current_vars_file, env)
1373
1374    if env['USE_SSE2']:
1375        env.Append(CCFLAGS=['-msse2'])
1376
1377    # The src/SConscript file sets up the build rules in 'env' according
1378    # to the configured variables.  It returns a list of environments,
1379    # one for each variant build (debug, opt, etc.)
1380    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1381
1382def pairwise(iterable):
1383    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1384    a, b = itertools.tee(iterable)
1385    b.next()
1386    return itertools.izip(a, b)
1387
1388# Create false dependencies so SCons will parse ISAs, establish
1389# dependencies, and setup the build Environments serially. Either
1390# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1391# greater than 1. It appears to be standard race condition stuff; it
1392# doesn't always fail, but usually, and the behaviors are different.
1393# Every time I tried to remove this, builds would fail in some
1394# creative new way. So, don't do that. You'll want to, though, because
1395# tests/SConscript takes a long time to make its Environments.
1396for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1397    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1398    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1399
1400# base help text
1401Help('''
1402Usage: scons [scons options] [build variables] [target(s)]
1403
1404Extra scons options:
1405%(options)s
1406
1407Global build variables:
1408%(global_vars)s
1409
1410%(local_vars)s
1411''' % help_texts)
1412