SConstruct revision 10238
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2013 ARM Limited
4955SN/A# All rights reserved.
5955SN/A#
6955SN/A# The license below extends only to copyright in the software and shall
7955SN/A# not be construed as granting a license to any other intellectual
8955SN/A# property including but not limited to intellectual property relating
9955SN/A# to a hardware implementation of the functionality of the software
10955SN/A# licensed hereunder.  You may use the software subject to the license
11955SN/A# terms below provided that you ensure that this notice is replicated
12955SN/A# unmodified and in its entirety in all distributions of the software,
13955SN/A# modified or unmodified, in source code or in binary form.
14955SN/A#
15955SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
16955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
17955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
18955SN/A# All rights reserved.
19955SN/A#
20955SN/A# Redistribution and use in source and binary forms, with or without
21955SN/A# modification, are permitted provided that the following conditions are
22955SN/A# met: redistributions of source code must retain the above copyright
23955SN/A# notice, this list of conditions and the following disclaimer;
24955SN/A# redistributions in binary form must reproduce the above copyright
25955SN/A# notice, this list of conditions and the following disclaimer in the
26955SN/A# documentation and/or other materials provided with the distribution;
27955SN/A# neither the name of the copyright holders nor the names of its
282665Ssaidi@eecs.umich.edu# contributors may be used to endorse or promote products derived from
292665Ssaidi@eecs.umich.edu# this software without specific prior written permission.
30955SN/A#
31955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
32955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
33955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
34955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
352632Sstever@eecs.umich.edu# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
362632Sstever@eecs.umich.edu# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
372632Sstever@eecs.umich.edu# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
382632Sstever@eecs.umich.edu# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
39955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
402632Sstever@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
412632Sstever@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
422761Sstever@eecs.umich.edu#
432632Sstever@eecs.umich.edu# Authors: Steve Reinhardt
442632Sstever@eecs.umich.edu#          Nathan Binkert
452632Sstever@eecs.umich.edu
462761Sstever@eecs.umich.edu###################################################
472761Sstever@eecs.umich.edu#
482761Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
492632Sstever@eecs.umich.edu#
502632Sstever@eecs.umich.edu# While in this directory ('gem5'), just type 'scons' to build the default
512761Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
522761Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
532761Sstever@eecs.umich.edu# the optimized full-system version).
542761Sstever@eecs.umich.edu#
552761Sstever@eecs.umich.edu# You can build gem5 in a different directory as long as there is a
562632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
572632Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
582632Sstever@eecs.umich.edu# built for the same host system.
592632Sstever@eecs.umich.edu#
602632Sstever@eecs.umich.edu# Examples:
612632Sstever@eecs.umich.edu#
622632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
63955SN/A#   scons to search up the directory tree for this SConstruct file.
64955SN/A#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
65955SN/A#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
66955SN/A#
67955SN/A#   The following two commands are equivalent and demonstrate building
684202Sbinkertn@umich.edu#   in a directory outside of the source tree.  The '-C' option tells
695342Sstever@gmail.com#   scons to chdir to the specified directory to find this SConstruct
70955SN/A#   file.
715273Sstever@gmail.com#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
725273Sstever@gmail.com#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
732656Sstever@eecs.umich.edu#
742656Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
752656Sstever@eecs.umich.edu# 'gem5' directory (or use -u or -C to tell scons where to find this
762656Sstever@eecs.umich.edu# file), you can use 'scons -h' to print all the gem5-specific build
772656Sstever@eecs.umich.edu# options as well.
782656Sstever@eecs.umich.edu#
792656Sstever@eecs.umich.edu###################################################
802653Sstever@eecs.umich.edu
815227Ssaidi@eecs.umich.edu# Check for recent-enough Python and SCons versions.
825227Ssaidi@eecs.umich.edutry:
835227Ssaidi@eecs.umich.edu    # Really old versions of scons only take two options for the
845227Ssaidi@eecs.umich.edu    # function, so check once without the revision and once with the
852653Sstever@eecs.umich.edu    # revision, the first instance will fail for stuff other than
862653Sstever@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
872653Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98)
882653Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98, 1)
892653Sstever@eecs.umich.eduexcept SystemExit, e:
902653Sstever@eecs.umich.edu    print """
912653Sstever@eecs.umich.eduFor more details, see:
922653Sstever@eecs.umich.edu    http://gem5.org/Dependencies
932653Sstever@eecs.umich.edu"""
944781Snate@binkert.org    raise
951852SN/A
96955SN/A# We ensure the python version early because because python-config
97955SN/A# requires python 2.5
98955SN/Atry:
993717Sstever@eecs.umich.edu    EnsurePythonVersion(2, 5)
1003716Sstever@eecs.umich.eduexcept SystemExit, e:
101955SN/A    print """
1021533SN/AYou can use a non-default installation of the Python interpreter by
1033716Sstever@eecs.umich.edurearranging your PATH so that scons finds the non-default 'python' and
1041533SN/A'python-config' first.
1054678Snate@binkert.org
1064678Snate@binkert.orgFor more details, see:
1074678Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
1084678Snate@binkert.org"""
1094678Snate@binkert.org    raise
1104678Snate@binkert.org
1114678Snate@binkert.org# Global Python includes
1124678Snate@binkert.orgimport itertools
1134678Snate@binkert.orgimport os
1144678Snate@binkert.orgimport re
1154678Snate@binkert.orgimport subprocess
1164678Snate@binkert.orgimport sys
1174678Snate@binkert.org
1184678Snate@binkert.orgfrom os import mkdir, environ
1194678Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1204678Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1214678Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1224678Snate@binkert.org
1234678Snate@binkert.org# SCons includes
1244678Snate@binkert.orgimport SCons
1254678Snate@binkert.orgimport SCons.Node
1264973Ssaidi@eecs.umich.edu
1274678Snate@binkert.orgextra_python_paths = [
1284678Snate@binkert.org    Dir('src/python').srcnode().abspath, # gem5 includes
1294678Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1304678Snate@binkert.org    ]
1314678Snate@binkert.org
1324678Snate@binkert.orgsys.path[1:1] = extra_python_paths
133955SN/A
134955SN/Afrom m5.util import compareVersions, readCommand
1352632Sstever@eecs.umich.edufrom m5.util.terminal import get_termcap
1362632Sstever@eecs.umich.edu
137955SN/Ahelp_texts = {
138955SN/A    "options" : "",
139955SN/A    "global_vars" : "",
140955SN/A    "local_vars" : ""
1412632Sstever@eecs.umich.edu}
142955SN/A
1432632Sstever@eecs.umich.eduExport("help_texts")
1442632Sstever@eecs.umich.edu
1452632Sstever@eecs.umich.edu
1462632Sstever@eecs.umich.edu# There's a bug in scons in that (1) by default, the help texts from
1472632Sstever@eecs.umich.edu# AddOption() are supposed to be displayed when you type 'scons -h'
1482632Sstever@eecs.umich.edu# and (2) you can override the help displayed by 'scons -h' using the
1492632Sstever@eecs.umich.edu# Help() function, but these two features are incompatible: once
1503053Sstever@eecs.umich.edu# you've overridden the help text using Help(), there's no way to get
1513053Sstever@eecs.umich.edu# at the help texts from AddOptions.  See:
1523053Sstever@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1533053Sstever@eecs.umich.edu#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1543053Sstever@eecs.umich.edu# This hack lets us extract the help text from AddOptions and
1553053Sstever@eecs.umich.edu# re-inject it via Help().  Ideally someday this bug will be fixed and
1563053Sstever@eecs.umich.edu# we can just use AddOption directly.
1573053Sstever@eecs.umich.edudef AddLocalOption(*args, **kwargs):
1583053Sstever@eecs.umich.edu    col_width = 30
1593053Sstever@eecs.umich.edu
1603053Sstever@eecs.umich.edu    help = "  " + ", ".join(args)
1613053Sstever@eecs.umich.edu    if "help" in kwargs:
1623053Sstever@eecs.umich.edu        length = len(help)
1633053Sstever@eecs.umich.edu        if length >= col_width:
1643053Sstever@eecs.umich.edu            help += "\n" + " " * col_width
1653053Sstever@eecs.umich.edu        else:
1662632Sstever@eecs.umich.edu            help += " " * (col_width - length)
1672632Sstever@eecs.umich.edu        help += kwargs["help"]
1682632Sstever@eecs.umich.edu    help_texts["options"] += help + "\n"
1692632Sstever@eecs.umich.edu
1702632Sstever@eecs.umich.edu    AddOption(*args, **kwargs)
1712632Sstever@eecs.umich.edu
1723718Sstever@eecs.umich.eduAddLocalOption('--colors', dest='use_colors', action='store_true',
1733718Sstever@eecs.umich.edu               help="Add color to abbreviated scons output")
1743718Sstever@eecs.umich.eduAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1753718Sstever@eecs.umich.edu               help="Don't add color to abbreviated scons output")
1763718Sstever@eecs.umich.eduAddLocalOption('--default', dest='default', type='string', action='store',
1773718Sstever@eecs.umich.edu               help='Override which build_opts file to use for defaults')
1783718Sstever@eecs.umich.eduAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1793718Sstever@eecs.umich.edu               help='Disable style checking hooks')
1803718Sstever@eecs.umich.eduAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1813718Sstever@eecs.umich.edu               help='Disable Link-Time Optimization for fast')
1823718Sstever@eecs.umich.eduAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1833718Sstever@eecs.umich.edu               help='Update test reference outputs')
1843718Sstever@eecs.umich.eduAddLocalOption('--verbose', dest='verbose', action='store_true',
1852634Sstever@eecs.umich.edu               help='Print full tool command lines')
1862634Sstever@eecs.umich.edu
1872632Sstever@eecs.umich.edutermcap = get_termcap(GetOption('use_colors'))
1882638Sstever@eecs.umich.edu
1892632Sstever@eecs.umich.edu########################################################################
1902632Sstever@eecs.umich.edu#
1912632Sstever@eecs.umich.edu# Set up the main build environment.
1922632Sstever@eecs.umich.edu#
1932632Sstever@eecs.umich.edu########################################################################
1942632Sstever@eecs.umich.edu
1951858SN/A# export TERM so that clang reports errors in color
1963716Sstever@eecs.umich.eduuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
1972638Sstever@eecs.umich.edu                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PROTOC',
1982638Sstever@eecs.umich.edu                 'PYTHONPATH', 'RANLIB', 'SWIG', 'TERM' ])
1992638Sstever@eecs.umich.edu
2002638Sstever@eecs.umich.eduuse_prefixes = [
2012638Sstever@eecs.umich.edu    "M5",           # M5 configuration (e.g., path to kernels)
2022638Sstever@eecs.umich.edu    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
2032638Sstever@eecs.umich.edu    "CCACHE_",      # ccache (caching compiler wrapper) configuration
2043716Sstever@eecs.umich.edu    "CCC_",         # clang static analyzer configuration
2052634Sstever@eecs.umich.edu    ]
2062634Sstever@eecs.umich.edu
207955SN/Ause_env = {}
2085341Sstever@gmail.comfor key,val in os.environ.iteritems():
2095341Sstever@gmail.com    if key in use_vars or \
2105341Sstever@gmail.com            any([key.startswith(prefix) for prefix in use_prefixes]):
2115341Sstever@gmail.com        use_env[key] = val
212955SN/A
213955SN/Amain = Environment(ENV=use_env)
214955SN/Amain.Decider('MD5-timestamp')
215955SN/Amain.root = Dir(".")         # The current directory (where this file lives).
216955SN/Amain.srcdir = Dir("src")     # The source directory
217955SN/A
218955SN/Amain_dict_keys = main.Dictionary().keys()
2191858SN/A
2201858SN/A# Check that we have a C/C++ compiler
2212632Sstever@eecs.umich.eduif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
222955SN/A    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2234494Ssaidi@eecs.umich.edu    Exit(1)
2244494Ssaidi@eecs.umich.edu
2253716Sstever@eecs.umich.edu# Check that swig is present
2261105SN/Aif not 'SWIG' in main_dict_keys:
2272667Sstever@eecs.umich.edu    print "swig is not installed (package swig on Ubuntu and RedHat)"
2282667Sstever@eecs.umich.edu    Exit(1)
2292667Sstever@eecs.umich.edu
2302667Sstever@eecs.umich.edu# add useful python code PYTHONPATH so it can be used by subprocesses
2312667Sstever@eecs.umich.edu# as well
2322667Sstever@eecs.umich.edumain.AppendENVPath('PYTHONPATH', extra_python_paths)
2331869SN/A
2341869SN/A########################################################################
2351869SN/A#
2361869SN/A# Mercurial Stuff.
2371869SN/A#
2381065SN/A# If the gem5 directory is a mercurial repository, we should do some
2395341Sstever@gmail.com# extra things.
2405341Sstever@gmail.com#
2415341Sstever@gmail.com########################################################################
2425341Sstever@gmail.com
2435341Sstever@gmail.comhgdir = main.root.Dir(".hg")
2445341Sstever@gmail.com
2455341Sstever@gmail.commercurial_style_message = """
2465341Sstever@gmail.comYou're missing the gem5 style hook, which automatically checks your code
2475341Sstever@gmail.comagainst the gem5 style rules on hg commit and qrefresh commands.  This
2485341Sstever@gmail.comscript will now install the hook in your .hg/hgrc file.
2495341Sstever@gmail.comPress enter to continue, or ctrl-c to abort: """
2505341Sstever@gmail.com
2515341Sstever@gmail.commercurial_style_hook = """
2525341Sstever@gmail.com# The following lines were automatically added by gem5/SConstruct
2535341Sstever@gmail.com# to provide the gem5 style-checking hooks
2545341Sstever@gmail.com[extensions]
2555341Sstever@gmail.comstyle = %s/util/style.py
2565341Sstever@gmail.com
2575341Sstever@gmail.com[hooks]
2585341Sstever@gmail.compretxncommit.style = python:style.check_style
2595341Sstever@gmail.compre-qrefresh.style = python:style.check_style
2605341Sstever@gmail.com# End of SConstruct additions
2615341Sstever@gmail.com
2625341Sstever@gmail.com""" % (main.root.abspath)
2635341Sstever@gmail.com
2645341Sstever@gmail.commercurial_lib_not_found = """
2655341Sstever@gmail.comMercurial libraries cannot be found, ignoring style hook.  If
2665341Sstever@gmail.comyou are a gem5 developer, please fix this and run the style
2675341Sstever@gmail.comhook. It is important.
2685341Sstever@gmail.com"""
2695341Sstever@gmail.com
2705341Sstever@gmail.com# Check for style hook and prompt for installation if it's not there.
2715341Sstever@gmail.com# Skip this if --ignore-style was specified, there's no .hg dir to
2725341Sstever@gmail.com# install a hook in, or there's no interactive terminal to prompt.
2735341Sstever@gmail.comif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2745341Sstever@gmail.com    style_hook = True
2755341Sstever@gmail.com    try:
2765341Sstever@gmail.com        from mercurial import ui
2775341Sstever@gmail.com        ui = ui.ui()
2785341Sstever@gmail.com        ui.readconfig(hgdir.File('hgrc').abspath)
2795341Sstever@gmail.com        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2805341Sstever@gmail.com                     ui.config('hooks', 'pre-qrefresh.style', None)
2815341Sstever@gmail.com    except ImportError:
2825341Sstever@gmail.com        print mercurial_lib_not_found
2835341Sstever@gmail.com
2845341Sstever@gmail.com    if not style_hook:
2855341Sstever@gmail.com        print mercurial_style_message,
2865341Sstever@gmail.com        # continue unless user does ctrl-c/ctrl-d etc.
2875341Sstever@gmail.com        try:
2885341Sstever@gmail.com            raw_input()
2895341Sstever@gmail.com        except:
2905341Sstever@gmail.com            print "Input exception, exiting scons.\n"
2915341Sstever@gmail.com            sys.exit(1)
2925341Sstever@gmail.com        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2935341Sstever@gmail.com        print "Adding style hook to", hgrc_path, "\n"
2942632Sstever@eecs.umich.edu        try:
2955199Sstever@gmail.com            hgrc = open(hgrc_path, 'a')
2963918Ssaidi@eecs.umich.edu            hgrc.write(mercurial_style_hook)
2973918Ssaidi@eecs.umich.edu            hgrc.close()
2983940Ssaidi@eecs.umich.edu        except:
2994781Snate@binkert.org            print "Error updating", hgrc_path
3004781Snate@binkert.org            sys.exit(1)
3013918Ssaidi@eecs.umich.edu
3024781Snate@binkert.org
3034781Snate@binkert.org###################################################
3043918Ssaidi@eecs.umich.edu#
3054781Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
3064781Snate@binkert.org# the target(s).
3073940Ssaidi@eecs.umich.edu#
3083942Ssaidi@eecs.umich.edu###################################################
3093940Ssaidi@eecs.umich.edu
3103918Ssaidi@eecs.umich.edu# Find default configuration & binary.
3113918Ssaidi@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
312955SN/A
3131858SN/A# helper function: find last occurrence of element in list
3143918Ssaidi@eecs.umich.edudef rfind(l, elt, offs = -1):
3153918Ssaidi@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
3163918Ssaidi@eecs.umich.edu        if l[i] == elt:
3173918Ssaidi@eecs.umich.edu            return i
3183940Ssaidi@eecs.umich.edu    raise ValueError, "element not found"
3193940Ssaidi@eecs.umich.edu
3203918Ssaidi@eecs.umich.edu# Take a list of paths (or SCons Nodes) and return a list with all
3213918Ssaidi@eecs.umich.edu# paths made absolute and ~-expanded.  Paths will be interpreted
3223918Ssaidi@eecs.umich.edu# relative to the launch directory unless a different root is provided
3233918Ssaidi@eecs.umich.edudef makePathListAbsolute(path_list, root=GetLaunchDir()):
3243918Ssaidi@eecs.umich.edu    return [abspath(joinpath(root, expanduser(str(p))))
3253918Ssaidi@eecs.umich.edu            for p in path_list]
3263918Ssaidi@eecs.umich.edu
3273918Ssaidi@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
3283918Ssaidi@eecs.umich.edu# directory below this will determine the build parameters.  For
3293940Ssaidi@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3303918Ssaidi@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
3313918Ssaidi@eecs.umich.edu# follow 'build' in the build path.
3321851SN/A
3331851SN/A# The funky assignment to "[:]" is needed to replace the list contents
3341858SN/A# in place rather than reassign the symbol to a new list, which
3355200Sstever@gmail.com# doesn't work (obviously!).
336955SN/ABUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3373053Sstever@eecs.umich.edu
3383053Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
3393053Sstever@eecs.umich.edu# collected targets reference.
3403053Sstever@eecs.umich.eduvariant_paths = []
3413053Sstever@eecs.umich.edubuild_root = None
3423053Sstever@eecs.umich.edufor t in BUILD_TARGETS:
3433053Sstever@eecs.umich.edu    path_dirs = t.split('/')
3443053Sstever@eecs.umich.edu    try:
3453053Sstever@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
3464742Sstever@eecs.umich.edu    except:
3474742Sstever@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
3483053Sstever@eecs.umich.edu        Exit(1)
3493053Sstever@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3503053Sstever@eecs.umich.edu    if not build_root:
3513053Sstever@eecs.umich.edu        build_root = this_build_root
3523053Sstever@eecs.umich.edu    else:
3533053Sstever@eecs.umich.edu        if this_build_root != build_root:
3543053Sstever@eecs.umich.edu            print "Error: build targets not under same build root\n"\
3553053Sstever@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
3563053Sstever@eecs.umich.edu            Exit(1)
3572667Sstever@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
3584554Sbinkertn@umich.edu    if variant_path not in variant_paths:
3594554Sbinkertn@umich.edu        variant_paths.append(variant_path)
3602667Sstever@eecs.umich.edu
3614554Sbinkertn@umich.edu# Make sure build_root exists (might not if this is the first build there)
3624554Sbinkertn@umich.eduif not isdir(build_root):
3634554Sbinkertn@umich.edu    mkdir(build_root)
3644554Sbinkertn@umich.edumain['BUILDROOT'] = build_root
3654554Sbinkertn@umich.edu
3664554Sbinkertn@umich.eduExport('main')
3674554Sbinkertn@umich.edu
3684781Snate@binkert.orgmain.SConsignFile(joinpath(build_root, "sconsign"))
3694554Sbinkertn@umich.edu
3704554Sbinkertn@umich.edu# Default duplicate option is to use hard links, but this messes up
3712667Sstever@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
3724554Sbinkertn@umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
3734554Sbinkertn@umich.edu# (soft) links work better.
3744554Sbinkertn@umich.edumain.SetOption('duplicate', 'soft-copy')
3754554Sbinkertn@umich.edu
3762667Sstever@eecs.umich.edu#
3774554Sbinkertn@umich.edu# Set up global sticky variables... these are common to an entire build
3782667Sstever@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
3794554Sbinkertn@umich.edu#
3804554Sbinkertn@umich.edu
3812667Sstever@eecs.umich.eduglobal_vars_file = joinpath(build_root, 'variables.global')
3822638Sstever@eecs.umich.edu
3832638Sstever@eecs.umich.eduglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3842638Sstever@eecs.umich.edu
3853716Sstever@eecs.umich.eduglobal_vars.AddVariables(
3863716Sstever@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3871858SN/A    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3885227Ssaidi@eecs.umich.edu    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3895227Ssaidi@eecs.umich.edu    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3905227Ssaidi@eecs.umich.edu    ('BATCH', 'Use batch pool for build and tests', False),
3915227Ssaidi@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3925227Ssaidi@eecs.umich.edu    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3935227Ssaidi@eecs.umich.edu    ('EXTRAS', 'Add extra directories to the compilation', '')
3945227Ssaidi@eecs.umich.edu    )
3955227Ssaidi@eecs.umich.edu
3965227Ssaidi@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_vars_file
3975227Ssaidi@eecs.umich.eduglobal_vars.Update(main)
3985227Ssaidi@eecs.umich.eduhelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3995227Ssaidi@eecs.umich.edu
4005274Ssaidi@eecs.umich.edu# Save sticky variable settings back to current variables file
4015227Ssaidi@eecs.umich.eduglobal_vars.Save(global_vars_file, main)
4025227Ssaidi@eecs.umich.edu
4035227Ssaidi@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
4045204Sstever@gmail.com# look for sources etc.  This list is exported as extras_dir_list.
4055204Sstever@gmail.combase_dir = main.srcdir.abspath
4065204Sstever@gmail.comif main['EXTRAS']:
4075204Sstever@gmail.com    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
4085204Sstever@gmail.comelse:
4095204Sstever@gmail.com    extras_dir_list = []
4105204Sstever@gmail.com
4115204Sstever@gmail.comExport('base_dir')
4125204Sstever@gmail.comExport('extras_dir_list')
4135204Sstever@gmail.com
4145204Sstever@gmail.com# the ext directory should be on the #includes path
4155204Sstever@gmail.commain.Append(CPPPATH=[Dir('ext')])
4165204Sstever@gmail.com
4175204Sstever@gmail.comdef strip_build_path(path, env):
4185204Sstever@gmail.com    path = str(path)
4195204Sstever@gmail.com    variant_base = env['BUILDROOT'] + os.path.sep
4205204Sstever@gmail.com    if path.startswith(variant_base):
4215204Sstever@gmail.com        path = path[len(variant_base):]
4225204Sstever@gmail.com    elif path.startswith('build/'):
4233118Sstever@eecs.umich.edu        path = path[6:]
4243118Sstever@eecs.umich.edu    return path
4253118Sstever@eecs.umich.edu
4263118Sstever@eecs.umich.edu# Generate a string of the form:
4273118Sstever@eecs.umich.edu#   common/path/prefix/src1, src2 -> tgt1, tgt2
4283118Sstever@eecs.umich.edu# to print while building.
4293118Sstever@eecs.umich.educlass Transform(object):
4303118Sstever@eecs.umich.edu    # all specific color settings should be here and nowhere else
4313118Sstever@eecs.umich.edu    tool_color = termcap.Normal
4323118Sstever@eecs.umich.edu    pfx_color = termcap.Yellow
4333118Sstever@eecs.umich.edu    srcs_color = termcap.Yellow + termcap.Bold
4343716Sstever@eecs.umich.edu    arrow_color = termcap.Blue + termcap.Bold
4353118Sstever@eecs.umich.edu    tgts_color = termcap.Yellow + termcap.Bold
4363118Sstever@eecs.umich.edu
4373118Sstever@eecs.umich.edu    def __init__(self, tool, max_sources=99):
4383118Sstever@eecs.umich.edu        self.format = self.tool_color + (" [%8s] " % tool) \
4393118Sstever@eecs.umich.edu                      + self.pfx_color + "%s" \
4403118Sstever@eecs.umich.edu                      + self.srcs_color + "%s" \
4413118Sstever@eecs.umich.edu                      + self.arrow_color + " -> " \
4423118Sstever@eecs.umich.edu                      + self.tgts_color + "%s" \
4433118Sstever@eecs.umich.edu                      + termcap.Normal
4443716Sstever@eecs.umich.edu        self.max_sources = max_sources
4453118Sstever@eecs.umich.edu
4463118Sstever@eecs.umich.edu    def __call__(self, target, source, env, for_signature=None):
4473118Sstever@eecs.umich.edu        # truncate source list according to max_sources param
4483118Sstever@eecs.umich.edu        source = source[0:self.max_sources]
4493118Sstever@eecs.umich.edu        def strip(f):
4503118Sstever@eecs.umich.edu            return strip_build_path(str(f), env)
4513118Sstever@eecs.umich.edu        if len(source) > 0:
4523118Sstever@eecs.umich.edu            srcs = map(strip, source)
4533118Sstever@eecs.umich.edu        else:
4543118Sstever@eecs.umich.edu            srcs = ['']
4553483Ssaidi@eecs.umich.edu        tgts = map(strip, target)
4563494Ssaidi@eecs.umich.edu        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4573494Ssaidi@eecs.umich.edu        # operation that has nothing to do with paths.
4583483Ssaidi@eecs.umich.edu        com_pfx = os.path.commonprefix(srcs + tgts)
4593483Ssaidi@eecs.umich.edu        com_pfx_len = len(com_pfx)
4603483Ssaidi@eecs.umich.edu        if com_pfx:
4613053Sstever@eecs.umich.edu            # do some cleanup and sanity checking on common prefix
4623053Sstever@eecs.umich.edu            if com_pfx[-1] == ".":
4633918Ssaidi@eecs.umich.edu                # prefix matches all but file extension: ok
4643053Sstever@eecs.umich.edu                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4653053Sstever@eecs.umich.edu                com_pfx = com_pfx[0:-1]
4663053Sstever@eecs.umich.edu            elif com_pfx[-1] == "/":
4673053Sstever@eecs.umich.edu                # common prefix is directory path: OK
4683053Sstever@eecs.umich.edu                pass
4691858SN/A            else:
4701858SN/A                src0_len = len(srcs[0])
4711858SN/A                tgt0_len = len(tgts[0])
4721858SN/A                if src0_len == com_pfx_len:
4731858SN/A                    # source is a substring of target, OK
4741858SN/A                    pass
4751859SN/A                elif tgt0_len == com_pfx_len:
4761858SN/A                    # target is a substring of source, need to back up to
4771858SN/A                    # avoid empty string on RHS of arrow
4781858SN/A                    sep_idx = com_pfx.rfind(".")
4791859SN/A                    if sep_idx != -1:
4801859SN/A                        com_pfx = com_pfx[0:sep_idx]
4811862SN/A                    else:
4823053Sstever@eecs.umich.edu                        com_pfx = ''
4833053Sstever@eecs.umich.edu                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4843053Sstever@eecs.umich.edu                    # still splitting at file extension: ok
4853053Sstever@eecs.umich.edu                    pass
4861859SN/A                else:
4871859SN/A                    # probably a fluke; ignore it
4881859SN/A                    com_pfx = ''
4891859SN/A        # recalculate length in case com_pfx was modified
4901859SN/A        com_pfx_len = len(com_pfx)
4911859SN/A        def fmt(files):
4921859SN/A            f = map(lambda s: s[com_pfx_len:], files)
4931859SN/A            return ', '.join(f)
4941862SN/A        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4951859SN/A
4961859SN/AExport('Transform')
4971859SN/A
4981858SN/A# enable the regression script to use the termcap
4991858SN/Amain['TERMCAP'] = termcap
5002139SN/A
5014202Sbinkertn@umich.eduif GetOption('verbose'):
5024202Sbinkertn@umich.edu    def MakeAction(action, string, *args, **kwargs):
5032139SN/A        return Action(action, *args, **kwargs)
5042155SN/Aelse:
5054202Sbinkertn@umich.edu    MakeAction = Action
5064202Sbinkertn@umich.edu    main['CCCOMSTR']        = Transform("CC")
5074202Sbinkertn@umich.edu    main['CXXCOMSTR']       = Transform("CXX")
5082155SN/A    main['ASCOMSTR']        = Transform("AS")
5091869SN/A    main['SWIGCOMSTR']      = Transform("SWIG")
5101869SN/A    main['ARCOMSTR']        = Transform("AR", 0)
5111869SN/A    main['LINKCOMSTR']      = Transform("LINK", 0)
5121869SN/A    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
5134202Sbinkertn@umich.edu    main['M4COMSTR']        = Transform("M4")
5144202Sbinkertn@umich.edu    main['SHCCCOMSTR']      = Transform("SHCC")
5154202Sbinkertn@umich.edu    main['SHCXXCOMSTR']     = Transform("SHCXX")
5164202Sbinkertn@umich.eduExport('MakeAction')
5174202Sbinkertn@umich.edu
5184202Sbinkertn@umich.edu# Initialize the Link-Time Optimization (LTO) flags
5194202Sbinkertn@umich.edumain['LTO_CCFLAGS'] = []
5204202Sbinkertn@umich.edumain['LTO_LDFLAGS'] = []
5215341Sstever@gmail.com
5225341Sstever@gmail.com# According to the readme, tcmalloc works best if the compiler doesn't
5235341Sstever@gmail.com# assume that we're using the builtin malloc and friends. These flags
5245342Sstever@gmail.com# are compiler-specific, so we need to set them after we detect which
5255342Sstever@gmail.com# compiler we're using.
5264202Sbinkertn@umich.edumain['TCMALLOC_CCFLAGS'] = []
5274202Sbinkertn@umich.edu
5284202Sbinkertn@umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5294202Sbinkertn@umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5304202Sbinkertn@umich.edu
5311869SN/Amain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5324202Sbinkertn@umich.edumain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5331869SN/Aif main['GCC'] + main['CLANG'] > 1:
5342508SN/A    print 'Error: How can we have two at the same time?'
5352508SN/A    Exit(1)
5362508SN/A
5372508SN/A# Set up default C++ compiler flags
5384202Sbinkertn@umich.eduif main['GCC'] or main['CLANG']:
5391869SN/A    # As gcc and clang share many flags, do the common parts here
5401869SN/A    main.Append(CCFLAGS=['-pipe'])
5411869SN/A    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5421869SN/A    # Enable -Wall and then disable the few warnings that we
5431869SN/A    # consistently violate
5441869SN/A    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5451965SN/A    # We always compile using C++11, but only gcc >= 4.7 and clang 3.1
5461965SN/A    # actually use that name, so we stick with c++0x
5471965SN/A    main.Append(CXXFLAGS=['-std=c++0x'])
5481869SN/A    # Add selected sanity checks from -Wextra
5491869SN/A    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5502733Sktlim@umich.edu                          '-Woverloaded-virtual'])
5511884SN/Aelse:
5523356Sbinkertn@umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5533356Sbinkertn@umich.edu    print "Don't know what compiler options to use for your compiler."
5543356Sbinkertn@umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
5554773Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
5561869SN/A    if not CXX_version:
5571858SN/A        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
5581869SN/A               termcap.Normal
5591869SN/A    else:
5601869SN/A        print CXX_version.replace('\n', '<nl>')
5611858SN/A    print "       If you're trying to use a compiler other than GCC"
5622761Sstever@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
5631869SN/A    print "       environment."
5642733Sktlim@umich.edu    print "       "
5653584Ssaidi@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
5661869SN/A    print "       above you will need to ease fix SConstruct and "
5671869SN/A    print "       src/SConscript to support that compiler."
5681869SN/A    Exit(1)
5691869SN/A
5701869SN/Aif main['GCC']:
5711869SN/A    # Check for a supported version of gcc. >= 4.6 is chosen for its
5721858SN/A    # level of c++11 support. See
573955SN/A    # http://gcc.gnu.org/projects/cxx0x.html for details. 4.6 is also
574955SN/A    # the first version with proper LTO support.
5751869SN/A    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5761869SN/A    if compareVersions(gcc_version, "4.6") < 0:
5771869SN/A        print 'Error: gcc version 4.6 or newer required.'
5781869SN/A        print '       Installed version:', gcc_version
5791869SN/A        Exit(1)
5801869SN/A
5811869SN/A    main['GCC_VERSION'] = gcc_version
5821869SN/A
5831869SN/A    # Add the appropriate Link-Time Optimization (LTO) flags
5841869SN/A    # unless LTO is explicitly turned off. Note that these flags
5851869SN/A    # are only used by the fast target.
5861869SN/A    if not GetOption('no_lto'):
5871869SN/A        # Pass the LTO flag when compiling to produce GIMPLE
5881869SN/A        # output, we merely create the flags here and only append
5891869SN/A        # them later/
5901869SN/A        main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
5911869SN/A
5921869SN/A        # Use the same amount of jobs for LTO as we are running
5931869SN/A        # scons with, we hardcode the use of the linker plugin
5941869SN/A        # which requires either gold or GNU ld >= 2.21
5951869SN/A        main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
5961869SN/A                               '-fuse-linker-plugin']
5971869SN/A
5981869SN/A    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin-malloc', '-fno-builtin-calloc',
5991869SN/A                                  '-fno-builtin-realloc', '-fno-builtin-free'])
6001869SN/A
6011869SN/Aelif main['CLANG']:
6021869SN/A    # Check for a supported version of clang, >= 3.0 is needed to
6031869SN/A    # support similar features as gcc 4.6. See
6043716Sstever@eecs.umich.edu    # http://clang.llvm.org/cxx_status.html for details
6053356Sbinkertn@umich.edu    clang_version_re = re.compile(".* version (\d+\.\d+)")
6063356Sbinkertn@umich.edu    clang_version_match = clang_version_re.search(CXX_version)
6073356Sbinkertn@umich.edu    if (clang_version_match):
6083356Sbinkertn@umich.edu        clang_version = clang_version_match.groups()[0]
6093356Sbinkertn@umich.edu        if compareVersions(clang_version, "3.0") < 0:
6103356Sbinkertn@umich.edu            print 'Error: clang version 3.0 or newer required.'
6114781Snate@binkert.org            print '       Installed version:', clang_version
6121869SN/A            Exit(1)
6131869SN/A    else:
6141869SN/A        print 'Error: Unable to determine clang version.'
6151869SN/A        Exit(1)
6161869SN/A
6171869SN/A    # clang has a few additional warnings that we disable,
6181869SN/A    # tautological comparisons are allowed due to unsigned integers
6192655Sstever@eecs.umich.edu    # being compared to constants that happen to be 0, and extraneous
6202655Sstever@eecs.umich.edu    # parantheses are allowed due to Ruby's printing of the AST,
6212655Sstever@eecs.umich.edu    # finally self assignments are allowed as the generated CPU code
6222655Sstever@eecs.umich.edu    # is relying on this
6232655Sstever@eecs.umich.edu    main.Append(CCFLAGS=['-Wno-tautological-compare',
6242655Sstever@eecs.umich.edu                         '-Wno-parentheses',
6252655Sstever@eecs.umich.edu                         '-Wno-self-assign'])
6262655Sstever@eecs.umich.edu
6272655Sstever@eecs.umich.edu    main.Append(TCMALLOC_CCFLAGS=['-fno-builtin'])
6282655Sstever@eecs.umich.edu
6292655Sstever@eecs.umich.edu    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
6302655Sstever@eecs.umich.edu    # opposed to libstdc++, as the later is dated.
6312655Sstever@eecs.umich.edu    if sys.platform == "darwin":
6322655Sstever@eecs.umich.edu        main.Append(CXXFLAGS=['-stdlib=libc++'])
6332655Sstever@eecs.umich.edu        main.Append(LIBS=['c++'])
6342655Sstever@eecs.umich.edu
6352655Sstever@eecs.umich.eduelse:
6362655Sstever@eecs.umich.edu    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
6372655Sstever@eecs.umich.edu    print "Don't know what compiler options to use for your compiler."
6382655Sstever@eecs.umich.edu    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6392655Sstever@eecs.umich.edu    print termcap.Yellow + '       version:' + termcap.Normal,
6402655Sstever@eecs.umich.edu    if not CXX_version:
6412655Sstever@eecs.umich.edu        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6422655Sstever@eecs.umich.edu               termcap.Normal
6432655Sstever@eecs.umich.edu    else:
6442655Sstever@eecs.umich.edu        print CXX_version.replace('\n', '<nl>')
6452638Sstever@eecs.umich.edu    print "       If you're trying to use a compiler other than GCC"
6462638Sstever@eecs.umich.edu    print "       or clang, there appears to be something wrong with your"
6473716Sstever@eecs.umich.edu    print "       environment."
6482638Sstever@eecs.umich.edu    print "       "
6492638Sstever@eecs.umich.edu    print "       If you are trying to use a compiler other than those listed"
6501869SN/A    print "       above you will need to ease fix SConstruct and "
6511869SN/A    print "       src/SConscript to support that compiler."
6523546Sgblack@eecs.umich.edu    Exit(1)
6533546Sgblack@eecs.umich.edu
6543546Sgblack@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
6553546Sgblack@eecs.umich.edumain['YACCFLAGS'] = '-d'
6564202Sbinkertn@umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
6573546Sgblack@eecs.umich.edu
6583546Sgblack@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
6593546Sgblack@eecs.umich.edu# extra 'qdo' every time we run scons.
6603546Sgblack@eecs.umich.eduif main['BATCH']:
6613546Sgblack@eecs.umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6624781Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6634781Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6644781Snate@binkert.org    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6654781Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6664781Snate@binkert.org
6674781Snate@binkert.orgif sys.platform == 'cygwin':
6684781Snate@binkert.org    # cygwin has some header file issues...
6694781Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
6704781Snate@binkert.org
6714781Snate@binkert.org# Check for the protobuf compiler
6724781Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
6734781Snate@binkert.org                             exception='').split()
6743546Sgblack@eecs.umich.edu
6753546Sgblack@eecs.umich.edu# First two words should be "libprotoc x.y.z"
6763546Sgblack@eecs.umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6774781Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
6783546Sgblack@eecs.umich.edu        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6793546Sgblack@eecs.umich.edu        '         Please install protobuf-compiler for tracing support.' + \
6803546Sgblack@eecs.umich.edu        termcap.Normal
6813546Sgblack@eecs.umich.edu    main['PROTOC'] = False
6823546Sgblack@eecs.umich.eduelse:
6833546Sgblack@eecs.umich.edu    # Based on the availability of the compress stream wrappers,
6843546Sgblack@eecs.umich.edu    # require 2.1.0
6853546Sgblack@eecs.umich.edu    min_protoc_version = '2.1.0'
6863546Sgblack@eecs.umich.edu    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6873546Sgblack@eecs.umich.edu        print termcap.Yellow + termcap.Bold + \
6884202Sbinkertn@umich.edu            'Warning: protoc version', min_protoc_version, \
6893546Sgblack@eecs.umich.edu            'or newer required.\n' + \
6903546Sgblack@eecs.umich.edu            '         Installed version:', protoc_version[1], \
6913546Sgblack@eecs.umich.edu            termcap.Normal
692955SN/A        main['PROTOC'] = False
693955SN/A    else:
694955SN/A        # Attempt to determine the appropriate include path and
695955SN/A        # library path using pkg-config, that means we also need to
6961858SN/A        # check for pkg-config. Note that it is possible to use
6971858SN/A        # protobuf without the involvement of pkg-config. Later on we
6981858SN/A        # check go a library config check and at that point the test
6992632Sstever@eecs.umich.edu        # will fail if libprotobuf cannot be found.
7002632Sstever@eecs.umich.edu        if readCommand(['pkg-config', '--version'], exception=''):
7015343Sstever@gmail.com            try:
7025343Sstever@gmail.com                # Attempt to establish what linking flags to add for protobuf
7035343Sstever@gmail.com                # using pkg-config
7044773Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
7054773Snate@binkert.org            except:
7062632Sstever@eecs.umich.edu                print termcap.Yellow + termcap.Bold + \
7072632Sstever@eecs.umich.edu                    'Warning: pkg-config could not get protobuf flags.' + \
7082632Sstever@eecs.umich.edu                    termcap.Normal
7092023SN/A
7102632Sstever@eecs.umich.edu# Check for SWIG
7112632Sstever@eecs.umich.eduif not main.has_key('SWIG'):
7122632Sstever@eecs.umich.edu    print 'Error: SWIG utility not found.'
7132632Sstever@eecs.umich.edu    print '       Please install (see http://www.swig.org) and retry.'
7142632Sstever@eecs.umich.edu    Exit(1)
7153716Sstever@eecs.umich.edu
7165342Sstever@gmail.com# Check for appropriate SWIG version
7172632Sstever@eecs.umich.eduswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
7182632Sstever@eecs.umich.edu# First 3 words should be "SWIG Version x.y.z"
7192632Sstever@eecs.umich.eduif len(swig_version) < 3 or \
7202632Sstever@eecs.umich.edu        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
7212023SN/A    print 'Error determining SWIG version.'
7222632Sstever@eecs.umich.edu    Exit(1)
7232632Sstever@eecs.umich.edu
7245342Sstever@gmail.commin_swig_version = '2.0.4'
7251889SN/Aif compareVersions(swig_version[2], min_swig_version) < 0:
7262632Sstever@eecs.umich.edu    print 'Error: SWIG version', min_swig_version, 'or newer required.'
7272632Sstever@eecs.umich.edu    print '       Installed version:', swig_version[2]
7282632Sstever@eecs.umich.edu    Exit(1)
7292632Sstever@eecs.umich.edu
7303716Sstever@eecs.umich.edu# Set up SWIG flags & scanner
7313716Sstever@eecs.umich.eduswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
7325342Sstever@gmail.commain.Append(SWIGFLAGS=swig_flags)
7332632Sstever@eecs.umich.edu
7342632Sstever@eecs.umich.edu# filter out all existing swig scanners, they mess up the dependency
7352632Sstever@eecs.umich.edu# stuff for some reason
7362632Sstever@eecs.umich.eduscanners = []
7372632Sstever@eecs.umich.edufor scanner in main['SCANNERS']:
7382632Sstever@eecs.umich.edu    skeys = scanner.skeys
7392632Sstever@eecs.umich.edu    if skeys == '.i':
7401888SN/A        continue
7411888SN/A
7421869SN/A    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
7431869SN/A        continue
7441858SN/A
7455341Sstever@gmail.com    scanners.append(scanner)
7462598SN/A
7472598SN/A# add the new swig scanner that we like better
7482598SN/Afrom SCons.Scanner import ClassicCPP as CPPScanner
7492598SN/Aswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
7501858SN/Ascanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
7511858SN/A
7521858SN/A# replace the scanners list that has what we want
7531858SN/Amain['SCANNERS'] = scanners
7541858SN/A
7551858SN/A# Add a custom Check function to the Configure context so that we can
7561858SN/A# figure out if the compiler adds leading underscores to global
7571858SN/A# variables.  This is needed for the autogenerated asm files that we
7581858SN/A# use for embedding the python code.
7591871SN/Adef CheckLeading(context):
7601858SN/A    context.Message("Checking for leading underscore in global variables...")
7611858SN/A    # 1) Define a global variable called x from asm so the C compiler
7621858SN/A    #    won't change the symbol at all.
7631858SN/A    # 2) Declare that variable.
7641858SN/A    # 3) Use the variable
7651858SN/A    #
7661858SN/A    # If the compiler prepends an underscore, this will successfully
7671858SN/A    # link because the external symbol 'x' will be called '_x' which
7681858SN/A    # was defined by the asm statement.  If the compiler does not
7691858SN/A    # prepend an underscore, this will not successfully link because
7701858SN/A    # '_x' will have been defined by assembly, while the C portion of
7711859SN/A    # the code will be trying to use 'x'
7721859SN/A    ret = context.TryLink('''
7731869SN/A        asm(".globl _x; _x: .byte 0");
7741888SN/A        extern int x;
7752632Sstever@eecs.umich.edu        int main() { return x; }
7761869SN/A        ''', extension=".c")
7771884SN/A    context.env.Append(LEADING_UNDERSCORE=ret)
7781884SN/A    context.Result(ret)
7791884SN/A    return ret
7801884SN/A
7811884SN/A# Add a custom Check function to test for structure members.
7821884SN/Adef CheckMember(context, include, decl, member, include_quotes="<>"):
7831965SN/A    context.Message("Checking for member %s in %s..." %
7841965SN/A                    (member, decl))
7851965SN/A    text = """
7862761Sstever@eecs.umich.edu#include %(header)s
7871869SN/Aint main(){
7881869SN/A  %(decl)s test;
7892632Sstever@eecs.umich.edu  (void)test.%(member)s;
7902667Sstever@eecs.umich.edu  return 0;
7911869SN/A};
7921869SN/A""" % { "header" : include_quotes[0] + include + include_quotes[1],
7932929Sktlim@umich.edu        "decl" : decl,
7942929Sktlim@umich.edu        "member" : member,
7953716Sstever@eecs.umich.edu        }
7962929Sktlim@umich.edu
797955SN/A    ret = context.TryCompile(text, extension=".cc")
7982598SN/A    context.Result(ret)
7992598SN/A    return ret
8003546Sgblack@eecs.umich.edu
801955SN/A# Platform-specific configuration.  Note again that we assume that all
802955SN/A# builds under a given build root run on the same host platform.
803955SN/Aconf = Configure(main,
8041530SN/A                 conf_dir = joinpath(build_root, '.scons_config'),
805955SN/A                 log_file = joinpath(build_root, 'scons_config.log'),
806955SN/A                 custom_tests = {
807955SN/A        'CheckLeading' : CheckLeading,
808        'CheckMember' : CheckMember,
809        })
810
811# Check for leading underscores.  Don't really need to worry either
812# way so don't need to check the return code.
813conf.CheckLeading()
814
815# Check if we should compile a 64 bit binary on Mac OS X/Darwin
816try:
817    import platform
818    uname = platform.uname()
819    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
820        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
821            main.Append(CCFLAGS=['-arch', 'x86_64'])
822            main.Append(CFLAGS=['-arch', 'x86_64'])
823            main.Append(LINKFLAGS=['-arch', 'x86_64'])
824            main.Append(ASFLAGS=['-arch', 'x86_64'])
825except:
826    pass
827
828# Recent versions of scons substitute a "Null" object for Configure()
829# when configuration isn't necessary, e.g., if the "--help" option is
830# present.  Unfortuantely this Null object always returns false,
831# breaking all our configuration checks.  We replace it with our own
832# more optimistic null object that returns True instead.
833if not conf:
834    def NullCheck(*args, **kwargs):
835        return True
836
837    class NullConf:
838        def __init__(self, env):
839            self.env = env
840        def Finish(self):
841            return self.env
842        def __getattr__(self, mname):
843            return NullCheck
844
845    conf = NullConf(main)
846
847# Cache build files in the supplied directory.
848if main['M5_BUILD_CACHE']:
849    print 'Using build cache located at', main['M5_BUILD_CACHE']
850    CacheDir(main['M5_BUILD_CACHE'])
851
852# Find Python include and library directories for embedding the
853# interpreter. We rely on python-config to resolve the appropriate
854# includes and linker flags. ParseConfig does not seem to understand
855# the more exotic linker flags such as -Xlinker and -export-dynamic so
856# we add them explicitly below. If you want to link in an alternate
857# version of python, see above for instructions on how to invoke
858# scons with the appropriate PATH set.
859#
860# First we check if python2-config exists, else we use python-config
861python_config = readCommand(['which', 'python2-config'], exception='').strip()
862if not os.path.exists(python_config):
863    python_config = readCommand(['which', 'python-config'],
864                                exception='').strip()
865py_includes = readCommand([python_config, '--includes'],
866                          exception='').split()
867# Strip the -I from the include folders before adding them to the
868# CPPPATH
869main.Append(CPPPATH=map(lambda inc: inc[2:], py_includes))
870
871# Read the linker flags and split them into libraries and other link
872# flags. The libraries are added later through the call the CheckLib.
873py_ld_flags = readCommand([python_config, '--ldflags'], exception='').split()
874py_libs = []
875for lib in py_ld_flags:
876     if not lib.startswith('-l'):
877         main.Append(LINKFLAGS=[lib])
878     else:
879         lib = lib[2:]
880         if lib not in py_libs:
881             py_libs.append(lib)
882
883# verify that this stuff works
884if not conf.CheckHeader('Python.h', '<>'):
885    print "Error: can't find Python.h header in", py_includes
886    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
887    Exit(1)
888
889for lib in py_libs:
890    if not conf.CheckLib(lib):
891        print "Error: can't find library %s required by python" % lib
892        Exit(1)
893
894# On Solaris you need to use libsocket for socket ops
895if not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
896   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
897       print "Can't find library with socket calls (e.g. accept())"
898       Exit(1)
899
900# Check for zlib.  If the check passes, libz will be automatically
901# added to the LIBS environment variable.
902if not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
903    print 'Error: did not find needed zlib compression library '\
904          'and/or zlib.h header file.'
905    print '       Please install zlib and try again.'
906    Exit(1)
907
908# If we have the protobuf compiler, also make sure we have the
909# development libraries. If the check passes, libprotobuf will be
910# automatically added to the LIBS environment variable. After
911# this, we can use the HAVE_PROTOBUF flag to determine if we have
912# got both protoc and libprotobuf available.
913main['HAVE_PROTOBUF'] = main['PROTOC'] and \
914    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
915                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
916
917# If we have the compiler but not the library, print another warning.
918if main['PROTOC'] and not main['HAVE_PROTOBUF']:
919    print termcap.Yellow + termcap.Bold + \
920        'Warning: did not find protocol buffer library and/or headers.\n' + \
921    '       Please install libprotobuf-dev for tracing support.' + \
922    termcap.Normal
923
924# Check for librt.
925have_posix_clock = \
926    conf.CheckLibWithHeader(None, 'time.h', 'C',
927                            'clock_nanosleep(0,0,NULL,NULL);') or \
928    conf.CheckLibWithHeader('rt', 'time.h', 'C',
929                            'clock_nanosleep(0,0,NULL,NULL);')
930
931have_posix_timers = \
932    conf.CheckLibWithHeader([None, 'rt'], [ 'time.h', 'signal.h' ], 'C',
933                            'timer_create(CLOCK_MONOTONIC, NULL, NULL);')
934
935if conf.CheckLib('tcmalloc'):
936    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
937elif conf.CheckLib('tcmalloc_minimal'):
938    main.Append(CCFLAGS=main['TCMALLOC_CCFLAGS'])
939else:
940    print termcap.Yellow + termcap.Bold + \
941          "You can get a 12% performance improvement by installing tcmalloc "\
942          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
943          termcap.Normal
944
945if not have_posix_clock:
946    print "Can't find library for POSIX clocks."
947
948# Check for <fenv.h> (C99 FP environment control)
949have_fenv = conf.CheckHeader('fenv.h', '<>')
950if not have_fenv:
951    print "Warning: Header file <fenv.h> not found."
952    print "         This host has no IEEE FP rounding mode control."
953
954# Check if we should enable KVM-based hardware virtualization. The API
955# we rely on exists since version 2.6.36 of the kernel, but somehow
956# the KVM_API_VERSION does not reflect the change. We test for one of
957# the types as a fall back.
958have_kvm = conf.CheckHeader('linux/kvm.h', '<>') and \
959    conf.CheckTypeSize('struct kvm_xsave', '#include <linux/kvm.h>') != 0
960if not have_kvm:
961    print "Info: Compatible header file <linux/kvm.h> not found, " \
962        "disabling KVM support."
963
964# Check if the requested target ISA is compatible with the host
965def is_isa_kvm_compatible(isa):
966    isa_comp_table = {
967        "arm" : ( "armv7l" ),
968        "x86" : ( "x86_64" ),
969        }
970    try:
971        import platform
972        host_isa = platform.machine()
973    except:
974        print "Warning: Failed to determine host ISA."
975        return False
976
977    return host_isa in isa_comp_table.get(isa, [])
978
979
980# Check if the exclude_host attribute is available. We want this to
981# get accurate instruction counts in KVM.
982main['HAVE_PERF_ATTR_EXCLUDE_HOST'] = conf.CheckMember(
983    'linux/perf_event.h', 'struct perf_event_attr', 'exclude_host')
984
985
986######################################################################
987#
988# Finish the configuration
989#
990main = conf.Finish()
991
992######################################################################
993#
994# Collect all non-global variables
995#
996
997# Define the universe of supported ISAs
998all_isa_list = [ ]
999Export('all_isa_list')
1000
1001class CpuModel(object):
1002    '''The CpuModel class encapsulates everything the ISA parser needs to
1003    know about a particular CPU model.'''
1004
1005    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
1006    dict = {}
1007    list = []
1008    defaults = []
1009
1010    # Constructor.  Automatically adds models to CpuModel.dict.
1011    def __init__(self, name, filename, includes, strings, default=False):
1012        self.name = name           # name of model
1013        self.filename = filename   # filename for output exec code
1014        self.includes = includes   # include files needed in exec file
1015        # The 'strings' dict holds all the per-CPU symbols we can
1016        # substitute into templates etc.
1017        self.strings = strings
1018
1019        # This cpu is enabled by default
1020        self.default = default
1021
1022        # Add self to dict
1023        if name in CpuModel.dict:
1024            raise AttributeError, "CpuModel '%s' already registered" % name
1025        CpuModel.dict[name] = self
1026        CpuModel.list.append(name)
1027
1028Export('CpuModel')
1029
1030# Sticky variables get saved in the variables file so they persist from
1031# one invocation to the next (unless overridden, in which case the new
1032# value becomes sticky).
1033sticky_vars = Variables(args=ARGUMENTS)
1034Export('sticky_vars')
1035
1036# Sticky variables that should be exported
1037export_vars = []
1038Export('export_vars')
1039
1040# For Ruby
1041all_protocols = []
1042Export('all_protocols')
1043protocol_dirs = []
1044Export('protocol_dirs')
1045slicc_includes = []
1046Export('slicc_includes')
1047
1048# Walk the tree and execute all SConsopts scripts that wil add to the
1049# above variables
1050if GetOption('verbose'):
1051    print "Reading SConsopts"
1052for bdir in [ base_dir ] + extras_dir_list:
1053    if not isdir(bdir):
1054        print "Error: directory '%s' does not exist" % bdir
1055        Exit(1)
1056    for root, dirs, files in os.walk(bdir):
1057        if 'SConsopts' in files:
1058            if GetOption('verbose'):
1059                print "Reading", joinpath(root, 'SConsopts')
1060            SConscript(joinpath(root, 'SConsopts'))
1061
1062all_isa_list.sort()
1063
1064sticky_vars.AddVariables(
1065    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
1066    ListVariable('CPU_MODELS', 'CPU models',
1067                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
1068                 sorted(CpuModel.list)),
1069    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
1070                 False),
1071    BoolVariable('SS_COMPATIBLE_FP',
1072                 'Make floating-point results compatible with SimpleScalar',
1073                 False),
1074    BoolVariable('USE_SSE2',
1075                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
1076                 False),
1077    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
1078    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
1079    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
1080    BoolVariable('USE_KVM', 'Enable hardware virtualized (KVM) CPU models', have_kvm),
1081    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
1082                  all_protocols),
1083    )
1084
1085# These variables get exported to #defines in config/*.hh (see src/SConscript).
1086export_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
1087                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF',
1088                'HAVE_PERF_ATTR_EXCLUDE_HOST']
1089
1090###################################################
1091#
1092# Define a SCons builder for configuration flag headers.
1093#
1094###################################################
1095
1096# This function generates a config header file that #defines the
1097# variable symbol to the current variable setting (0 or 1).  The source
1098# operands are the name of the variable and a Value node containing the
1099# value of the variable.
1100def build_config_file(target, source, env):
1101    (variable, value) = [s.get_contents() for s in source]
1102    f = file(str(target[0]), 'w')
1103    print >> f, '#define', variable, value
1104    f.close()
1105    return None
1106
1107# Combine the two functions into a scons Action object.
1108config_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
1109
1110# The emitter munges the source & target node lists to reflect what
1111# we're really doing.
1112def config_emitter(target, source, env):
1113    # extract variable name from Builder arg
1114    variable = str(target[0])
1115    # True target is config header file
1116    target = joinpath('config', variable.lower() + '.hh')
1117    val = env[variable]
1118    if isinstance(val, bool):
1119        # Force value to 0/1
1120        val = int(val)
1121    elif isinstance(val, str):
1122        val = '"' + val + '"'
1123
1124    # Sources are variable name & value (packaged in SCons Value nodes)
1125    return ([target], [Value(variable), Value(val)])
1126
1127config_builder = Builder(emitter = config_emitter, action = config_action)
1128
1129main.Append(BUILDERS = { 'ConfigFile' : config_builder })
1130
1131# libelf build is shared across all configs in the build root.
1132main.SConscript('ext/libelf/SConscript',
1133                variant_dir = joinpath(build_root, 'libelf'))
1134
1135# gzstream build is shared across all configs in the build root.
1136main.SConscript('ext/gzstream/SConscript',
1137                variant_dir = joinpath(build_root, 'gzstream'))
1138
1139# libfdt build is shared across all configs in the build root.
1140main.SConscript('ext/libfdt/SConscript',
1141                variant_dir = joinpath(build_root, 'libfdt'))
1142
1143# fputils build is shared across all configs in the build root.
1144main.SConscript('ext/fputils/SConscript',
1145                variant_dir = joinpath(build_root, 'fputils'))
1146
1147# DRAMSim2 build is shared across all configs in the build root.
1148main.SConscript('ext/dramsim2/SConscript',
1149                variant_dir = joinpath(build_root, 'dramsim2'))
1150
1151###################################################
1152#
1153# This function is used to set up a directory with switching headers
1154#
1155###################################################
1156
1157main['ALL_ISA_LIST'] = all_isa_list
1158all_isa_deps = {}
1159def make_switching_dir(dname, switch_headers, env):
1160    # Generate the header.  target[0] is the full path of the output
1161    # header to generate.  'source' is a dummy variable, since we get the
1162    # list of ISAs from env['ALL_ISA_LIST'].
1163    def gen_switch_hdr(target, source, env):
1164        fname = str(target[0])
1165        isa = env['TARGET_ISA'].lower()
1166        try:
1167            f = open(fname, 'w')
1168            print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1169            f.close()
1170        except IOError:
1171            print "Failed to create %s" % fname
1172            raise
1173
1174    # Build SCons Action object. 'varlist' specifies env vars that this
1175    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1176    # should get re-executed.
1177    switch_hdr_action = MakeAction(gen_switch_hdr,
1178                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1179
1180    # Instantiate actions for each header
1181    for hdr in switch_headers:
1182        env.Command(hdr, [], switch_hdr_action)
1183
1184    isa_target = Dir('.').up().name.lower().replace('_', '-')
1185    env['PHONY_BASE'] = '#'+isa_target
1186    all_isa_deps[isa_target] = None
1187
1188Export('make_switching_dir')
1189
1190# all-isas -> all-deps -> all-environs -> all_targets
1191main.Alias('#all-isas', [])
1192main.Alias('#all-deps', '#all-isas')
1193
1194# Dummy target to ensure all environments are created before telling
1195# SCons what to actually make (the command line arguments).  We attach
1196# them to the dependence graph after the environments are complete.
1197ORIG_BUILD_TARGETS = list(BUILD_TARGETS) # force a copy; gets closure to work.
1198def environsComplete(target, source, env):
1199    for t in ORIG_BUILD_TARGETS:
1200        main.Depends('#all-targets', t)
1201
1202# Each build/* switching_dir attaches its *-environs target to #all-environs.
1203main.Append(BUILDERS = {'CompleteEnvirons' :
1204                        Builder(action=MakeAction(environsComplete, None))})
1205main.CompleteEnvirons('#all-environs', [])
1206
1207def doNothing(**ignored): pass
1208main.Append(BUILDERS = {'Dummy': Builder(action=MakeAction(doNothing, None))})
1209
1210# The final target to which all the original targets ultimately get attached.
1211main.Dummy('#all-targets', '#all-environs')
1212BUILD_TARGETS[:] = ['#all-targets']
1213
1214###################################################
1215#
1216# Define build environments for selected configurations.
1217#
1218###################################################
1219
1220for variant_path in variant_paths:
1221    if not GetOption('silent'):
1222        print "Building in", variant_path
1223
1224    # Make a copy of the build-root environment to use for this config.
1225    env = main.Clone()
1226    env['BUILDDIR'] = variant_path
1227
1228    # variant_dir is the tail component of build path, and is used to
1229    # determine the build parameters (e.g., 'ALPHA_SE')
1230    (build_root, variant_dir) = splitpath(variant_path)
1231
1232    # Set env variables according to the build directory config.
1233    sticky_vars.files = []
1234    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1235    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1236    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1237    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1238    if isfile(current_vars_file):
1239        sticky_vars.files.append(current_vars_file)
1240        if not GetOption('silent'):
1241            print "Using saved variables file %s" % current_vars_file
1242    else:
1243        # Build dir-specific variables file doesn't exist.
1244
1245        # Make sure the directory is there so we can create it later
1246        opt_dir = dirname(current_vars_file)
1247        if not isdir(opt_dir):
1248            mkdir(opt_dir)
1249
1250        # Get default build variables from source tree.  Variables are
1251        # normally determined by name of $VARIANT_DIR, but can be
1252        # overridden by '--default=' arg on command line.
1253        default = GetOption('default')
1254        opts_dir = joinpath(main.root.abspath, 'build_opts')
1255        if default:
1256            default_vars_files = [joinpath(build_root, 'variables', default),
1257                                  joinpath(opts_dir, default)]
1258        else:
1259            default_vars_files = [joinpath(opts_dir, variant_dir)]
1260        existing_files = filter(isfile, default_vars_files)
1261        if existing_files:
1262            default_vars_file = existing_files[0]
1263            sticky_vars.files.append(default_vars_file)
1264            print "Variables file %s not found,\n  using defaults in %s" \
1265                  % (current_vars_file, default_vars_file)
1266        else:
1267            print "Error: cannot find variables file %s or " \
1268                  "default file(s) %s" \
1269                  % (current_vars_file, ' or '.join(default_vars_files))
1270            Exit(1)
1271
1272    # Apply current variable settings to env
1273    sticky_vars.Update(env)
1274
1275    help_texts["local_vars"] += \
1276        "Build variables for %s:\n" % variant_dir \
1277                 + sticky_vars.GenerateHelpText(env)
1278
1279    # Process variable settings.
1280
1281    if not have_fenv and env['USE_FENV']:
1282        print "Warning: <fenv.h> not available; " \
1283              "forcing USE_FENV to False in", variant_dir + "."
1284        env['USE_FENV'] = False
1285
1286    if not env['USE_FENV']:
1287        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1288        print "         FP results may deviate slightly from other platforms."
1289
1290    if env['EFENCE']:
1291        env.Append(LIBS=['efence'])
1292
1293    if env['USE_KVM']:
1294        if not have_kvm:
1295            print "Warning: Can not enable KVM, host seems to lack KVM support"
1296            env['USE_KVM'] = False
1297        elif not have_posix_timers:
1298            print "Warning: Can not enable KVM, host seems to lack support " \
1299                "for POSIX timers"
1300            env['USE_KVM'] = False
1301        elif not is_isa_kvm_compatible(env['TARGET_ISA']):
1302            print "Info: KVM support disabled due to unsupported host and " \
1303                "target ISA combination"
1304            env['USE_KVM'] = False
1305
1306    # Warn about missing optional functionality
1307    if env['USE_KVM']:
1308        if not main['HAVE_PERF_ATTR_EXCLUDE_HOST']:
1309            print "Warning: perf_event headers lack support for the " \
1310                "exclude_host attribute. KVM instruction counts will " \
1311                "be inaccurate."
1312
1313    # Save sticky variable settings back to current variables file
1314    sticky_vars.Save(current_vars_file, env)
1315
1316    if env['USE_SSE2']:
1317        env.Append(CCFLAGS=['-msse2'])
1318
1319    # The src/SConscript file sets up the build rules in 'env' according
1320    # to the configured variables.  It returns a list of environments,
1321    # one for each variant build (debug, opt, etc.)
1322    SConscript('src/SConscript', variant_dir = variant_path, exports = 'env')
1323
1324def pairwise(iterable):
1325    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
1326    a, b = itertools.tee(iterable)
1327    b.next()
1328    return itertools.izip(a, b)
1329
1330# Create false dependencies so SCons will parse ISAs, establish
1331# dependencies, and setup the build Environments serially. Either
1332# SCons (likely) and/or our SConscripts (possibly) cannot cope with -j
1333# greater than 1. It appears to be standard race condition stuff; it
1334# doesn't always fail, but usually, and the behaviors are different.
1335# Every time I tried to remove this, builds would fail in some
1336# creative new way. So, don't do that. You'll want to, though, because
1337# tests/SConscript takes a long time to make its Environments.
1338for t1, t2 in pairwise(sorted(all_isa_deps.iterkeys())):
1339    main.Depends('#%s-deps'     % t2, '#%s-deps'     % t1)
1340    main.Depends('#%s-environs' % t2, '#%s-environs' % t1)
1341
1342# base help text
1343Help('''
1344Usage: scons [scons options] [build variables] [target(s)]
1345
1346Extra scons options:
1347%(options)s
1348
1349Global build variables:
1350%(global_vars)s
1351
1352%(local_vars)s
1353''' % help_texts)
1354