SConstruct revision 9552:460cf901acba
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2011 Advanced Micro Devices, Inc.
4955SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
5955SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
6955SN/A# All rights reserved.
7955SN/A#
8955SN/A# Redistribution and use in source and binary forms, with or without
9955SN/A# modification, are permitted provided that the following conditions are
10955SN/A# met: redistributions of source code must retain the above copyright
11955SN/A# notice, this list of conditions and the following disclaimer;
12955SN/A# redistributions in binary form must reproduce the above copyright
13955SN/A# notice, this list of conditions and the following disclaimer in the
14955SN/A# documentation and/or other materials provided with the distribution;
15955SN/A# neither the name of the copyright holders nor the names of its
16955SN/A# contributors may be used to endorse or promote products derived from
17955SN/A# this software without specific prior written permission.
18955SN/A#
19955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
282665Ssaidi@eecs.umich.edu# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
294762Snate@binkert.org# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30955SN/A#
315522Snate@binkert.org# Authors: Steve Reinhardt
326143Snate@binkert.org#          Nathan Binkert
334762Snate@binkert.org
345522Snate@binkert.org###################################################
35955SN/A#
365522Snate@binkert.org# SCons top-level build description (SConstruct) file.
37955SN/A#
385522Snate@binkert.org# While in this directory ('gem5'), just type 'scons' to build the default
394202Sbinkertn@umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
405742Snate@binkert.org# to build some other configuration (e.g., 'build/ALPHA/gem5.opt' for
41955SN/A# the optimized full-system version).
424381Sbinkertn@umich.edu#
434381Sbinkertn@umich.edu# You can build gem5 in a different directory as long as there is a
44955SN/A# 'build/<CONFIG>' somewhere along the target path.  The build system
45955SN/A# expects that all configs under the same build directory are being
46955SN/A# built for the same host system.
474202Sbinkertn@umich.edu#
48955SN/A# Examples:
494382Sbinkertn@umich.edu#
504382Sbinkertn@umich.edu#   The following two commands are equivalent.  The '-u' option tells
514382Sbinkertn@umich.edu#   scons to search up the directory tree for this SConstruct file.
526654Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons build/ALPHA/gem5.debug
535517Snate@binkert.org#   % cd <path-to-src>/gem5/build/ALPHA; scons -u gem5.debug
547674Snate@binkert.org#
557674Snate@binkert.org#   The following two commands are equivalent and demonstrate building
566143Snate@binkert.org#   in a directory outside of the source tree.  The '-C' option tells
576143Snate@binkert.org#   scons to chdir to the specified directory to find this SConstruct
586143Snate@binkert.org#   file.
596143Snate@binkert.org#   % cd <path-to-src>/gem5 ; scons /local/foo/build/ALPHA/gem5.debug
606143Snate@binkert.org#   % cd /local/foo/build/ALPHA; scons -C <path-to-src>/gem5 gem5.debug
616143Snate@binkert.org#
626143Snate@binkert.org# You can use 'scons -H' to print scons options.  If you're in this
636143Snate@binkert.org# 'gem5' directory (or use -u or -C to tell scons where to find this
646143Snate@binkert.org# file), you can use 'scons -h' to print all the gem5-specific build
656143Snate@binkert.org# options as well.
666143Snate@binkert.org#
676143Snate@binkert.org###################################################
686143Snate@binkert.org
696143Snate@binkert.org# Check for recent-enough Python and SCons versions.
706143Snate@binkert.orgtry:
714762Snate@binkert.org    # Really old versions of scons only take two options for the
726143Snate@binkert.org    # function, so check once without the revision and once with the
736143Snate@binkert.org    # revision, the first instance will fail for stuff other than
746143Snate@binkert.org    # 0.98, and the second will fail for 0.98.0
756143Snate@binkert.org    EnsureSConsVersion(0, 98)
766143Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
776143Snate@binkert.orgexcept SystemExit, e:
786143Snate@binkert.org    print """
796143Snate@binkert.orgFor more details, see:
806143Snate@binkert.org    http://gem5.org/Dependencies
816143Snate@binkert.org"""
826143Snate@binkert.org    raise
836143Snate@binkert.org
846143Snate@binkert.org# We ensure the python version early because we have stuff that
856143Snate@binkert.org# requires python 2.4
866143Snate@binkert.orgtry:
876143Snate@binkert.org    EnsurePythonVersion(2, 4)
886143Snate@binkert.orgexcept SystemExit, e:
896143Snate@binkert.org    print """
906143Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
916143Snate@binkert.orgeither (1) rearranging your PATH so that scons finds the non-default
926143Snate@binkert.org'python' first or (2) explicitly invoking an alternative interpreter
937065Snate@binkert.orgon the scons script.
946143Snate@binkert.org
956143Snate@binkert.orgFor more details, see:
966143Snate@binkert.org    http://gem5.org/wiki/index.php/Using_a_non-default_Python_installation
976143Snate@binkert.org"""
986143Snate@binkert.org    raise
996143Snate@binkert.org
1006143Snate@binkert.org# Global Python includes
1016143Snate@binkert.orgimport os
1026143Snate@binkert.orgimport re
1036143Snate@binkert.orgimport subprocess
1046143Snate@binkert.orgimport sys
1056143Snate@binkert.org
1066143Snate@binkert.orgfrom os import mkdir, environ
1076143Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1086143Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1096143Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1106143Snate@binkert.org
1116143Snate@binkert.org# SCons includes
1126143Snate@binkert.orgimport SCons
1136143Snate@binkert.orgimport SCons.Node
1146143Snate@binkert.org
1155522Snate@binkert.orgextra_python_paths = [
1166143Snate@binkert.org    Dir('src/python').srcnode().abspath, # gem5 includes
1176143Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1186143Snate@binkert.org    ]
1196143Snate@binkert.org
1206143Snate@binkert.orgsys.path[1:1] = extra_python_paths
1216143Snate@binkert.org
1226143Snate@binkert.orgfrom m5.util import compareVersions, readCommand
1236143Snate@binkert.orgfrom m5.util.terminal import get_termcap
1246143Snate@binkert.org
1256143Snate@binkert.orghelp_texts = {
1265522Snate@binkert.org    "options" : "",
1275522Snate@binkert.org    "global_vars" : "",
1285522Snate@binkert.org    "local_vars" : ""
1295522Snate@binkert.org}
1305604Snate@binkert.org
1315604Snate@binkert.orgExport("help_texts")
1326143Snate@binkert.org
1336143Snate@binkert.org
1344762Snate@binkert.org# There's a bug in scons in that (1) by default, the help texts from
1354762Snate@binkert.org# AddOption() are supposed to be displayed when you type 'scons -h'
1366143Snate@binkert.org# and (2) you can override the help displayed by 'scons -h' using the
1376727Ssteve.reinhardt@amd.com# Help() function, but these two features are incompatible: once
1386727Ssteve.reinhardt@amd.com# you've overridden the help text using Help(), there's no way to get
1396727Ssteve.reinhardt@amd.com# at the help texts from AddOptions.  See:
1404762Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2356
1416143Snate@binkert.org#     http://scons.tigris.org/issues/show_bug.cgi?id=2611
1426143Snate@binkert.org# This hack lets us extract the help text from AddOptions and
1436143Snate@binkert.org# re-inject it via Help().  Ideally someday this bug will be fixed and
1446143Snate@binkert.org# we can just use AddOption directly.
1456727Ssteve.reinhardt@amd.comdef AddLocalOption(*args, **kwargs):
1466143Snate@binkert.org    col_width = 30
1477674Snate@binkert.org
1487674Snate@binkert.org    help = "  " + ", ".join(args)
1495604Snate@binkert.org    if "help" in kwargs:
1506143Snate@binkert.org        length = len(help)
1516143Snate@binkert.org        if length >= col_width:
1526143Snate@binkert.org            help += "\n" + " " * col_width
1534762Snate@binkert.org        else:
1546143Snate@binkert.org            help += " " * (col_width - length)
1554762Snate@binkert.org        help += kwargs["help"]
1564762Snate@binkert.org    help_texts["options"] += help + "\n"
1574762Snate@binkert.org
1586143Snate@binkert.org    AddOption(*args, **kwargs)
1596143Snate@binkert.org
1604762Snate@binkert.orgAddLocalOption('--colors', dest='use_colors', action='store_true',
1616143Snate@binkert.org               help="Add color to abbreviated scons output")
1626143Snate@binkert.orgAddLocalOption('--no-colors', dest='use_colors', action='store_false',
1636143Snate@binkert.org               help="Don't add color to abbreviated scons output")
1646143Snate@binkert.orgAddLocalOption('--default', dest='default', type='string', action='store',
1654762Snate@binkert.org               help='Override which build_opts file to use for defaults')
1666143Snate@binkert.orgAddLocalOption('--ignore-style', dest='ignore_style', action='store_true',
1674762Snate@binkert.org               help='Disable style checking hooks')
1686143Snate@binkert.orgAddLocalOption('--no-lto', dest='no_lto', action='store_true',
1694762Snate@binkert.org               help='Disable Link-Time Optimization for fast')
1706143Snate@binkert.orgAddLocalOption('--update-ref', dest='update_ref', action='store_true',
1716143Snate@binkert.org               help='Update test reference outputs')
1726143Snate@binkert.orgAddLocalOption('--verbose', dest='verbose', action='store_true',
1736143Snate@binkert.org               help='Print full tool command lines')
1746143Snate@binkert.org
1756143Snate@binkert.orgtermcap = get_termcap(GetOption('use_colors'))
1766143Snate@binkert.org
1776143Snate@binkert.org########################################################################
1786143Snate@binkert.org#
1796143Snate@binkert.org# Set up the main build environment.
1806143Snate@binkert.org#
1816143Snate@binkert.org########################################################################
1826143Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH',
183955SN/A                 'LIBRARY_PATH', 'PATH', 'PKG_CONFIG_PATH', 'PYTHONPATH',
1845584Snate@binkert.org                 'RANLIB', 'SWIG' ])
1855584Snate@binkert.org
1865584Snate@binkert.orguse_prefixes = [
1875584Snate@binkert.org    "M5",           # M5 configuration (e.g., path to kernels)
1886143Snate@binkert.org    "DISTCC_",      # distcc (distributed compiler wrapper) configuration
1896143Snate@binkert.org    "CCACHE_",      # ccache (caching compiler wrapper) configuration
1906143Snate@binkert.org    "CCC_",         # clang static analyzer configuration
1915584Snate@binkert.org    ]
1924382Sbinkertn@umich.edu
1934202Sbinkertn@umich.eduuse_env = {}
1944382Sbinkertn@umich.edufor key,val in os.environ.iteritems():
1954382Sbinkertn@umich.edu    if key in use_vars or \
1964382Sbinkertn@umich.edu            any([key.startswith(prefix) for prefix in use_prefixes]):
1975584Snate@binkert.org        use_env[key] = val
1984382Sbinkertn@umich.edu
1994382Sbinkertn@umich.edumain = Environment(ENV=use_env)
2004382Sbinkertn@umich.edumain.Decider('MD5-timestamp')
2015192Ssaidi@eecs.umich.edumain.root = Dir(".")         # The current directory (where this file lives).
2025192Ssaidi@eecs.umich.edumain.srcdir = Dir("src")     # The source directory
2035799Snate@binkert.org
2045799Snate@binkert.orgmain_dict_keys = main.Dictionary().keys()
2055799Snate@binkert.org
2065192Ssaidi@eecs.umich.edu# Check that we have a C/C++ compiler
2075799Snate@binkert.orgif not ('CC' in main_dict_keys and 'CXX' in main_dict_keys):
2085192Ssaidi@eecs.umich.edu    print "No C++ compiler installed (package g++ on Ubuntu and RedHat)"
2095799Snate@binkert.org    Exit(1)
2105799Snate@binkert.org
2115192Ssaidi@eecs.umich.edu# Check that swig is present
2125192Ssaidi@eecs.umich.eduif not 'SWIG' in main_dict_keys:
2135192Ssaidi@eecs.umich.edu    print "swig is not installed (package swig on Ubuntu and RedHat)"
2145799Snate@binkert.org    Exit(1)
2155192Ssaidi@eecs.umich.edu
2165192Ssaidi@eecs.umich.edu# add useful python code PYTHONPATH so it can be used by subprocesses
2175192Ssaidi@eecs.umich.edu# as well
2185192Ssaidi@eecs.umich.edumain.AppendENVPath('PYTHONPATH', extra_python_paths)
2195192Ssaidi@eecs.umich.edu
2205192Ssaidi@eecs.umich.edu########################################################################
2214382Sbinkertn@umich.edu#
2224382Sbinkertn@umich.edu# Mercurial Stuff.
2234382Sbinkertn@umich.edu#
2242667Sstever@eecs.umich.edu# If the gem5 directory is a mercurial repository, we should do some
2252667Sstever@eecs.umich.edu# extra things.
2262667Sstever@eecs.umich.edu#
2272667Sstever@eecs.umich.edu########################################################################
2282667Sstever@eecs.umich.edu
2292667Sstever@eecs.umich.eduhgdir = main.root.Dir(".hg")
2305742Snate@binkert.org
2315742Snate@binkert.orgmercurial_style_message = """
2325742Snate@binkert.orgYou're missing the gem5 style hook, which automatically checks your code
2335793Snate@binkert.orgagainst the gem5 style rules on hg commit and qrefresh commands.  This
2345793Snate@binkert.orgscript will now install the hook in your .hg/hgrc file.
2355793Snate@binkert.orgPress enter to continue, or ctrl-c to abort: """
2365793Snate@binkert.org
2375793Snate@binkert.orgmercurial_style_hook = """
2384382Sbinkertn@umich.edu# The following lines were automatically added by gem5/SConstruct
2394762Snate@binkert.org# to provide the gem5 style-checking hooks
2405344Sstever@gmail.com[extensions]
2414382Sbinkertn@umich.edustyle = %s/util/style.py
2425341Sstever@gmail.com
2435742Snate@binkert.org[hooks]
2445742Snate@binkert.orgpretxncommit.style = python:style.check_style
2455742Snate@binkert.orgpre-qrefresh.style = python:style.check_style
2465742Snate@binkert.org# End of SConstruct additions
2475742Snate@binkert.org
2484762Snate@binkert.org""" % (main.root.abspath)
2495742Snate@binkert.org
2505742Snate@binkert.orgmercurial_lib_not_found = """
2515742Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook.  If
2525742Snate@binkert.orgyou are a gem5 developer, please fix this and run the style
2535742Snate@binkert.orghook. It is important.
2545742Snate@binkert.org"""
2555742Snate@binkert.org
2565341Sstever@gmail.com# Check for style hook and prompt for installation if it's not there.
2575742Snate@binkert.org# Skip this if --ignore-style was specified, there's no .hg dir to
2585341Sstever@gmail.com# install a hook in, or there's no interactive terminal to prompt.
2594773Snate@binkert.orgif not GetOption('ignore_style') and hgdir.exists() and sys.stdin.isatty():
2606108Snate@binkert.org    style_hook = True
2611858SN/A    try:
2621085SN/A        from mercurial import ui
2636658Snate@binkert.org        ui = ui.ui()
2646658Snate@binkert.org        ui.readconfig(hgdir.File('hgrc').abspath)
2657673Snate@binkert.org        style_hook = ui.config('hooks', 'pretxncommit.style', None) and \
2666658Snate@binkert.org                     ui.config('hooks', 'pre-qrefresh.style', None)
2676658Snate@binkert.org    except ImportError:
2686658Snate@binkert.org        print mercurial_lib_not_found
2696658Snate@binkert.org
2706658Snate@binkert.org    if not style_hook:
2716658Snate@binkert.org        print mercurial_style_message,
2726658Snate@binkert.org        # continue unless user does ctrl-c/ctrl-d etc.
2737673Snate@binkert.org        try:
2747673Snate@binkert.org            raw_input()
2757673Snate@binkert.org        except:
2767673Snate@binkert.org            print "Input exception, exiting scons.\n"
2777673Snate@binkert.org            sys.exit(1)
2787673Snate@binkert.org        hgrc_path = '%s/.hg/hgrc' % main.root.abspath
2797673Snate@binkert.org        print "Adding style hook to", hgrc_path, "\n"
2806658Snate@binkert.org        try:
2817673Snate@binkert.org            hgrc = open(hgrc_path, 'a')
2827673Snate@binkert.org            hgrc.write(mercurial_style_hook)
2837673Snate@binkert.org            hgrc.close()
2847673Snate@binkert.org        except:
2857673Snate@binkert.org            print "Error updating", hgrc_path
2867673Snate@binkert.org            sys.exit(1)
2877673Snate@binkert.org
2887673Snate@binkert.org
2897673Snate@binkert.org###################################################
2907673Snate@binkert.org#
2916658Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
2926658Snate@binkert.org# the target(s).
2936658Snate@binkert.org#
2944382Sbinkertn@umich.edu###################################################
2954382Sbinkertn@umich.edu
2964762Snate@binkert.org# Find default configuration & binary.
2974762Snate@binkert.orgDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA/gem5.debug'))
2984762Snate@binkert.org
2996654Snate@binkert.org# helper function: find last occurrence of element in list
3006654Snate@binkert.orgdef rfind(l, elt, offs = -1):
3015517Snate@binkert.org    for i in range(len(l)+offs, 0, -1):
3025517Snate@binkert.org        if l[i] == elt:
3035517Snate@binkert.org            return i
3045517Snate@binkert.org    raise ValueError, "element not found"
3055517Snate@binkert.org
3065517Snate@binkert.org# Take a list of paths (or SCons Nodes) and return a list with all
3075517Snate@binkert.org# paths made absolute and ~-expanded.  Paths will be interpreted
3085517Snate@binkert.org# relative to the launch directory unless a different root is provided
3095517Snate@binkert.orgdef makePathListAbsolute(path_list, root=GetLaunchDir()):
3105517Snate@binkert.org    return [abspath(joinpath(root, expanduser(str(p))))
3115517Snate@binkert.org            for p in path_list]
3125517Snate@binkert.org
3135517Snate@binkert.org# Each target must have 'build' in the interior of the path; the
3145517Snate@binkert.org# directory below this will determine the build parameters.  For
3155517Snate@binkert.org# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
3165517Snate@binkert.org# recognize that ALPHA_SE specifies the configuration because it
3175517Snate@binkert.org# follow 'build' in the build path.
3186654Snate@binkert.org
3195517Snate@binkert.org# The funky assignment to "[:]" is needed to replace the list contents
3205517Snate@binkert.org# in place rather than reassign the symbol to a new list, which
3215517Snate@binkert.org# doesn't work (obviously!).
3225517Snate@binkert.orgBUILD_TARGETS[:] = makePathListAbsolute(BUILD_TARGETS)
3235517Snate@binkert.org
3245517Snate@binkert.org# Generate a list of the unique build roots and configs that the
3255517Snate@binkert.org# collected targets reference.
3265517Snate@binkert.orgvariant_paths = []
3276143Snate@binkert.orgbuild_root = None
3286654Snate@binkert.orgfor t in BUILD_TARGETS:
3295517Snate@binkert.org    path_dirs = t.split('/')
3305517Snate@binkert.org    try:
3315517Snate@binkert.org        build_top = rfind(path_dirs, 'build', -2)
3325517Snate@binkert.org    except:
3335517Snate@binkert.org        print "Error: no non-leaf 'build' dir found on target path", t
3345517Snate@binkert.org        Exit(1)
3355517Snate@binkert.org    this_build_root = joinpath('/',*path_dirs[:build_top+1])
3365517Snate@binkert.org    if not build_root:
3375517Snate@binkert.org        build_root = this_build_root
3385517Snate@binkert.org    else:
3395517Snate@binkert.org        if this_build_root != build_root:
3405517Snate@binkert.org            print "Error: build targets not under same build root\n"\
3415517Snate@binkert.org                  "  %s\n  %s" % (build_root, this_build_root)
3425517Snate@binkert.org            Exit(1)
3436654Snate@binkert.org    variant_path = joinpath('/',*path_dirs[:build_top+2])
3446654Snate@binkert.org    if variant_path not in variant_paths:
3455517Snate@binkert.org        variant_paths.append(variant_path)
3465517Snate@binkert.org
3476143Snate@binkert.org# Make sure build_root exists (might not if this is the first build there)
3486143Snate@binkert.orgif not isdir(build_root):
3496143Snate@binkert.org    mkdir(build_root)
3506727Ssteve.reinhardt@amd.commain['BUILDROOT'] = build_root
3515517Snate@binkert.org
3526727Ssteve.reinhardt@amd.comExport('main')
3535517Snate@binkert.org
3545517Snate@binkert.orgmain.SConsignFile(joinpath(build_root, "sconsign"))
3555517Snate@binkert.org
3566654Snate@binkert.org# Default duplicate option is to use hard links, but this messes up
3576654Snate@binkert.org# when you use emacs to edit a file in the target dir, as emacs moves
3587673Snate@binkert.org# file to file~ then copies to file, breaking the link.  Symbolic
3596654Snate@binkert.org# (soft) links work better.
3606654Snate@binkert.orgmain.SetOption('duplicate', 'soft-copy')
3616654Snate@binkert.org
3626654Snate@binkert.org#
3635517Snate@binkert.org# Set up global sticky variables... these are common to an entire build
3645517Snate@binkert.org# tree (not specific to a particular build like ALPHA_SE)
3655517Snate@binkert.org#
3666143Snate@binkert.org
3675517Snate@binkert.orgglobal_vars_file = joinpath(build_root, 'variables.global')
3684762Snate@binkert.org
3695517Snate@binkert.orgglobal_vars = Variables(global_vars_file, args=ARGUMENTS)
3705517Snate@binkert.org
3716143Snate@binkert.orgglobal_vars.AddVariables(
3726143Snate@binkert.org    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3735517Snate@binkert.org    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3745517Snate@binkert.org    ('SWIG', 'SWIG tool', environ.get('SWIG', main['SWIG'])),
3755517Snate@binkert.org    ('PROTOC', 'protoc tool', environ.get('PROTOC', 'protoc')),
3765517Snate@binkert.org    ('BATCH', 'Use batch pool for build and tests', False),
3775517Snate@binkert.org    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3785517Snate@binkert.org    ('M5_BUILD_CACHE', 'Cache built objects in this directory', False),
3795517Snate@binkert.org    ('EXTRAS', 'Add extra directories to the compilation', '')
3805517Snate@binkert.org    )
3815517Snate@binkert.org
3825517Snate@binkert.org# Update main environment with values from ARGUMENTS & global_vars_file
3836143Snate@binkert.orgglobal_vars.Update(main)
3845517Snate@binkert.orghelp_texts["global_vars"] += global_vars.GenerateHelpText(main)
3856654Snate@binkert.org
3866654Snate@binkert.org# Save sticky variable settings back to current variables file
3876654Snate@binkert.orgglobal_vars.Save(global_vars_file, main)
3886654Snate@binkert.org
3896654Snate@binkert.org# Parse EXTRAS variable to build list of all directories where we're
3906654Snate@binkert.org# look for sources etc.  This list is exported as extras_dir_list.
3915517Snate@binkert.orgbase_dir = main.srcdir.abspath
3925517Snate@binkert.orgif main['EXTRAS']:
3935517Snate@binkert.org    extras_dir_list = makePathListAbsolute(main['EXTRAS'].split(':'))
3945517Snate@binkert.orgelse:
3955517Snate@binkert.org    extras_dir_list = []
3964762Snate@binkert.org
3974762Snate@binkert.orgExport('base_dir')
3984762Snate@binkert.orgExport('extras_dir_list')
3994762Snate@binkert.org
4004762Snate@binkert.org# the ext directory should be on the #includes path
4014762Snate@binkert.orgmain.Append(CPPPATH=[Dir('ext')])
4026143Snate@binkert.org
4034762Snate@binkert.orgdef strip_build_path(path, env):
4044762Snate@binkert.org    path = str(path)
4054762Snate@binkert.org    variant_base = env['BUILDROOT'] + os.path.sep
4064762Snate@binkert.org    if path.startswith(variant_base):
4074382Sbinkertn@umich.edu        path = path[len(variant_base):]
4084382Sbinkertn@umich.edu    elif path.startswith('build/'):
4095517Snate@binkert.org        path = path[6:]
4106654Snate@binkert.org    return path
4115517Snate@binkert.org
4125798Snate@binkert.org# Generate a string of the form:
4136654Snate@binkert.org#   common/path/prefix/src1, src2 -> tgt1, tgt2
4147673Snate@binkert.org# to print while building.
4156654Snate@binkert.orgclass Transform(object):
4166654Snate@binkert.org    # all specific color settings should be here and nowhere else
4176654Snate@binkert.org    tool_color = termcap.Normal
4186654Snate@binkert.org    pfx_color = termcap.Yellow
4196654Snate@binkert.org    srcs_color = termcap.Yellow + termcap.Bold
4206654Snate@binkert.org    arrow_color = termcap.Blue + termcap.Bold
4216654Snate@binkert.org    tgts_color = termcap.Yellow + termcap.Bold
4226654Snate@binkert.org
4236669Snate@binkert.org    def __init__(self, tool, max_sources=99):
4246669Snate@binkert.org        self.format = self.tool_color + (" [%8s] " % tool) \
4256669Snate@binkert.org                      + self.pfx_color + "%s" \
4266669Snate@binkert.org                      + self.srcs_color + "%s" \
4276669Snate@binkert.org                      + self.arrow_color + " -> " \
4286669Snate@binkert.org                      + self.tgts_color + "%s" \
4296654Snate@binkert.org                      + termcap.Normal
4307673Snate@binkert.org        self.max_sources = max_sources
4315517Snate@binkert.org
4325863Snate@binkert.org    def __call__(self, target, source, env, for_signature=None):
4335798Snate@binkert.org        # truncate source list according to max_sources param
4345798Snate@binkert.org        source = source[0:self.max_sources]
4355798Snate@binkert.org        def strip(f):
4365798Snate@binkert.org            return strip_build_path(str(f), env)
4375517Snate@binkert.org        if len(source) > 0:
4385517Snate@binkert.org            srcs = map(strip, source)
4397673Snate@binkert.org        else:
4405517Snate@binkert.org            srcs = ['']
4415517Snate@binkert.org        tgts = map(strip, target)
4427673Snate@binkert.org        # surprisingly, os.path.commonprefix is a dumb char-by-char string
4437673Snate@binkert.org        # operation that has nothing to do with paths.
4445517Snate@binkert.org        com_pfx = os.path.commonprefix(srcs + tgts)
4455798Snate@binkert.org        com_pfx_len = len(com_pfx)
4465798Snate@binkert.org        if com_pfx:
4475798Snate@binkert.org            # do some cleanup and sanity checking on common prefix
4485798Snate@binkert.org            if com_pfx[-1] == ".":
4495798Snate@binkert.org                # prefix matches all but file extension: ok
4505798Snate@binkert.org                # back up one to change 'foo.cc -> o' to 'foo.cc -> .o'
4514762Snate@binkert.org                com_pfx = com_pfx[0:-1]
4524762Snate@binkert.org            elif com_pfx[-1] == "/":
4534762Snate@binkert.org                # common prefix is directory path: OK
4544762Snate@binkert.org                pass
4554762Snate@binkert.org            else:
4565517Snate@binkert.org                src0_len = len(srcs[0])
4575517Snate@binkert.org                tgt0_len = len(tgts[0])
4585517Snate@binkert.org                if src0_len == com_pfx_len:
4595517Snate@binkert.org                    # source is a substring of target, OK
4605517Snate@binkert.org                    pass
4615517Snate@binkert.org                elif tgt0_len == com_pfx_len:
4627673Snate@binkert.org                    # target is a substring of source, need to back up to
4637673Snate@binkert.org                    # avoid empty string on RHS of arrow
4647673Snate@binkert.org                    sep_idx = com_pfx.rfind(".")
4655517Snate@binkert.org                    if sep_idx != -1:
4665517Snate@binkert.org                        com_pfx = com_pfx[0:sep_idx]
4675517Snate@binkert.org                    else:
4685517Snate@binkert.org                        com_pfx = ''
4695517Snate@binkert.org                elif src0_len > com_pfx_len and srcs[0][com_pfx_len] == ".":
4705517Snate@binkert.org                    # still splitting at file extension: ok
4715517Snate@binkert.org                    pass
4727673Snate@binkert.org                else:
4737673Snate@binkert.org                    # probably a fluke; ignore it
4747673Snate@binkert.org                    com_pfx = ''
4755517Snate@binkert.org        # recalculate length in case com_pfx was modified
4765517Snate@binkert.org        com_pfx_len = len(com_pfx)
4775517Snate@binkert.org        def fmt(files):
4785517Snate@binkert.org            f = map(lambda s: s[com_pfx_len:], files)
4795517Snate@binkert.org            return ', '.join(f)
4805517Snate@binkert.org        return self.format % (com_pfx, fmt(srcs), fmt(tgts))
4815517Snate@binkert.org
4827673Snate@binkert.orgExport('Transform')
4837673Snate@binkert.org
4847673Snate@binkert.org# enable the regression script to use the termcap
4855517Snate@binkert.orgmain['TERMCAP'] = termcap
4865517Snate@binkert.org
4875517Snate@binkert.orgif GetOption('verbose'):
4885517Snate@binkert.org    def MakeAction(action, string, *args, **kwargs):
4895517Snate@binkert.org        return Action(action, *args, **kwargs)
4905517Snate@binkert.orgelse:
4915517Snate@binkert.org    MakeAction = Action
4927673Snate@binkert.org    main['CCCOMSTR']        = Transform("CC")
4937673Snate@binkert.org    main['CXXCOMSTR']       = Transform("CXX")
4947673Snate@binkert.org    main['ASCOMSTR']        = Transform("AS")
4955517Snate@binkert.org    main['SWIGCOMSTR']      = Transform("SWIG")
4964762Snate@binkert.org    main['ARCOMSTR']        = Transform("AR", 0)
4974762Snate@binkert.org    main['LINKCOMSTR']      = Transform("LINK", 0)
4986143Snate@binkert.org    main['RANLIBCOMSTR']    = Transform("RANLIB", 0)
4996143Snate@binkert.org    main['M4COMSTR']        = Transform("M4")
5006143Snate@binkert.org    main['SHCCCOMSTR']      = Transform("SHCC")
5014762Snate@binkert.org    main['SHCXXCOMSTR']     = Transform("SHCXX")
5024762Snate@binkert.orgExport('MakeAction')
5034762Snate@binkert.org
5045517Snate@binkert.org# Initialize the Link-Time Optimization (LTO) flags
5054762Snate@binkert.orgmain['LTO_CCFLAGS'] = []
5064762Snate@binkert.orgmain['LTO_LDFLAGS'] = []
5074762Snate@binkert.org
5085463Snate@binkert.orgCXX_version = readCommand([main['CXX'],'--version'], exception=False)
5095517Snate@binkert.orgCXX_V = readCommand([main['CXX'],'-V'], exception=False)
5106656Snate@binkert.org
5115463Snate@binkert.orgmain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
5125517Snate@binkert.orgmain['CLANG'] = CXX_version and CXX_version.find('clang') >= 0
5134762Snate@binkert.orgif main['GCC'] + main['CLANG'] > 1:
5144762Snate@binkert.org    print 'Error: How can we have two at the same time?'
5154762Snate@binkert.org    Exit(1)
5166143Snate@binkert.org
5176143Snate@binkert.org# Set up default C++ compiler flags
5186143Snate@binkert.orgif main['GCC']:
5194762Snate@binkert.org    # Check for a supported version of gcc, >= 4.4 is needed for c++0x
5204762Snate@binkert.org    # support. See http://gcc.gnu.org/projects/cxx0x.html for details
5215517Snate@binkert.org    gcc_version = readCommand([main['CXX'], '-dumpversion'], exception=False)
5224762Snate@binkert.org    if compareVersions(gcc_version, "4.4") < 0:
5234762Snate@binkert.org        print 'Error: gcc version 4.4 or newer required.'
5244762Snate@binkert.org        print '       Installed version:', gcc_version
5254762Snate@binkert.org        Exit(1)
5265517Snate@binkert.org
5274762Snate@binkert.org    main['GCC_VERSION'] = gcc_version
5284762Snate@binkert.org    main.Append(CCFLAGS=['-pipe'])
5294762Snate@binkert.org    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5304762Snate@binkert.org    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5315517Snate@binkert.org    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5325517Snate@binkert.org                          '-Woverloaded-virtual'])
5335517Snate@binkert.org    main.Append(CXXFLAGS=['-std=c++0x'])
5345517Snate@binkert.org
5355517Snate@binkert.org    # Check for versions with bugs
5365517Snate@binkert.org    if not compareVersions(gcc_version, '4.4.1') or \
5375517Snate@binkert.org       not compareVersions(gcc_version, '4.4.2'):
5385517Snate@binkert.org        print 'Info: Tree vectorizer in GCC 4.4.1 & 4.4.2 is buggy, disabling.'
5395517Snate@binkert.org        main.Append(CCFLAGS=['-fno-tree-vectorize'])
5405517Snate@binkert.org
5415517Snate@binkert.org    # LTO support is only really working properly from 4.6 and beyond
5425517Snate@binkert.org    if compareVersions(gcc_version, '4.6') >= 0:
5435517Snate@binkert.org        # Add the appropriate Link-Time Optimization (LTO) flags
5445517Snate@binkert.org        # unless LTO is explicitly turned off. Note that these flags
5455517Snate@binkert.org        # are only used by the fast target.
5465517Snate@binkert.org        if not GetOption('no_lto'):
5475517Snate@binkert.org            # Pass the LTO flag when compiling to produce GIMPLE
5485517Snate@binkert.org            # output, we merely create the flags here and only append
5495517Snate@binkert.org            # them later/
5505517Snate@binkert.org            main['LTO_CCFLAGS'] = ['-flto=%d' % GetOption('num_jobs')]
5517673Snate@binkert.org
5527673Snate@binkert.org            # Use the same amount of jobs for LTO as we are running
5535517Snate@binkert.org            # scons with, we hardcode the use of the linker plugin
5547673Snate@binkert.org            # which requires either gold or GNU ld >= 2.21
5557673Snate@binkert.org            main['LTO_LDFLAGS'] = ['-flto=%d' % GetOption('num_jobs'),
5567673Snate@binkert.org                                   '-fuse-linker-plugin']
5577673Snate@binkert.org
5585517Snate@binkert.orgelif main['CLANG']:
5595517Snate@binkert.org    # Check for a supported version of clang, >= 2.9 is needed to
5605517Snate@binkert.org    # support similar features as gcc 4.4. See
5615517Snate@binkert.org    # http://clang.llvm.org/cxx_status.html for details
5627673Snate@binkert.org    clang_version_re = re.compile(".* version (\d+\.\d+)")
5637673Snate@binkert.org    clang_version_match = clang_version_re.match(CXX_version)
5647673Snate@binkert.org    if (clang_version_match):
5657673Snate@binkert.org        clang_version = clang_version_match.groups()[0]
5667673Snate@binkert.org        if compareVersions(clang_version, "2.9") < 0:
5677673Snate@binkert.org            print 'Error: clang version 2.9 or newer required.'
5685517Snate@binkert.org            print '       Installed version:', clang_version
5697673Snate@binkert.org            Exit(1)
5707673Snate@binkert.org    else:
5717673Snate@binkert.org        print 'Error: Unable to determine clang version.'
5727673Snate@binkert.org        Exit(1)
5735517Snate@binkert.org
5747673Snate@binkert.org    main.Append(CCFLAGS=['-pipe'])
5757673Snate@binkert.org    main.Append(CCFLAGS=['-fno-strict-aliasing'])
5765517Snate@binkert.org    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
5775517Snate@binkert.org    main.Append(CCFLAGS=['-Wno-tautological-compare'])
5787673Snate@binkert.org    main.Append(CCFLAGS=['-Wno-self-assign'])
5795517Snate@binkert.org    # Ruby makes frequent use of extraneous parantheses in the printing
5807673Snate@binkert.org    # of if-statements
5815517Snate@binkert.org    main.Append(CCFLAGS=['-Wno-parentheses'])
5825517Snate@binkert.org    main.Append(CXXFLAGS=['-Wmissing-field-initializers',
5835610Snate@binkert.org                          '-Woverloaded-virtual'])
5845623Snate@binkert.org    main.Append(CXXFLAGS=['-std=c++0x'])
5855623Snate@binkert.org    # On Mac OS X/Darwin we need to also use libc++ (part of XCode) as
5865610Snate@binkert.org    # opposed to libstdc++ to make the transition from TR1 to
5877673Snate@binkert.org    # C++11. See http://libcxx.llvm.org. However, clang has chosen a
5887673Snate@binkert.org    # strict implementation of the C++11 standard, and does not allow
5895623Snate@binkert.org    # incomplete types in template arguments (besides unique_ptr and
5905623Snate@binkert.org    # shared_ptr), and the libc++ STL containers create problems in
5917673Snate@binkert.org    # combination with the current gem5 code. For now, we stick with
5925623Snate@binkert.org    # libstdc++ and use the TR1 namespace.
5935623Snate@binkert.org    # if sys.platform == "darwin":
5947673Snate@binkert.org    #     main.Append(CXXFLAGS=['-stdlib=libc++'])
5955623Snate@binkert.org
5967673Snate@binkert.orgelse:
5977673Snate@binkert.org    print termcap.Yellow + termcap.Bold + 'Error' + termcap.Normal,
5985610Snate@binkert.org    print "Don't know what compiler options to use for your compiler."
5997673Snate@binkert.org    print termcap.Yellow + '       compiler:' + termcap.Normal, main['CXX']
6007673Snate@binkert.org    print termcap.Yellow + '       version:' + termcap.Normal,
6017673Snate@binkert.org    if not CXX_version:
6025517Snate@binkert.org        print termcap.Yellow + termcap.Bold + "COMMAND NOT FOUND!" +\
6037673Snate@binkert.org               termcap.Normal
6047673Snate@binkert.org    else:
6057673Snate@binkert.org        print CXX_version.replace('\n', '<nl>')
6065517Snate@binkert.org    print "       If you're trying to use a compiler other than GCC"
6077673Snate@binkert.org    print "       or clang, there appears to be something wrong with your"
6087673Snate@binkert.org    print "       environment."
6097673Snate@binkert.org    print "       "
6105517Snate@binkert.org    print "       If you are trying to use a compiler other than those listed"
6117673Snate@binkert.org    print "       above you will need to ease fix SConstruct and "
6125517Snate@binkert.org    print "       src/SConscript to support that compiler."
6134762Snate@binkert.org    Exit(1)
6146143Snate@binkert.org
6156143Snate@binkert.org# Set up common yacc/bison flags (needed for Ruby)
6165463Snate@binkert.orgmain['YACCFLAGS'] = '-d'
6174762Snate@binkert.orgmain['YACCHXXFILESUFFIX'] = '.hh'
6184762Snate@binkert.org
6197674Snate@binkert.org# Do this after we save setting back, or else we'll tack on an
6207674Snate@binkert.org# extra 'qdo' every time we run scons.
6217674Snate@binkert.orgif main['BATCH']:
6227674Snate@binkert.org    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
6237674Snate@binkert.org    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
6247674Snate@binkert.org    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
6257674Snate@binkert.org    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
6267674Snate@binkert.org    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
6277674Snate@binkert.org
6287674Snate@binkert.orgif sys.platform == 'cygwin':
6297674Snate@binkert.org    # cygwin has some header file issues...
6307674Snate@binkert.org    main.Append(CCFLAGS=["-Wno-uninitialized"])
6317674Snate@binkert.org
6327674Snate@binkert.org# Check for the protobuf compiler
6337674Snate@binkert.orgprotoc_version = readCommand([main['PROTOC'], '--version'],
6344762Snate@binkert.org                             exception='').split()
6356143Snate@binkert.org
6366143Snate@binkert.org# First two words should be "libprotoc x.y.z"
6374382Sbinkertn@umich.eduif len(protoc_version) < 2 or protoc_version[0] != 'libprotoc':
6384382Sbinkertn@umich.edu    print termcap.Yellow + termcap.Bold + \
6397674Snate@binkert.org        'Warning: Protocol buffer compiler (protoc) not found.\n' + \
6407674Snate@binkert.org        '         Please install protobuf-compiler for tracing support.' + \
6417674Snate@binkert.org        termcap.Normal
6426143Snate@binkert.org    main['PROTOC'] = False
6436143Snate@binkert.orgelse:
6444382Sbinkertn@umich.edu    # Based on the availability of the compress stream wrappers,
6456229Snate@binkert.org    # require 2.1.0
6466229Snate@binkert.org    min_protoc_version = '2.1.0'
6476229Snate@binkert.org    if compareVersions(protoc_version[1], min_protoc_version) < 0:
6486229Snate@binkert.org        print termcap.Yellow + termcap.Bold + \
6496229Snate@binkert.org            'Warning: protoc version', min_protoc_version, \
6506229Snate@binkert.org            'or newer required.\n' + \
6516229Snate@binkert.org            '         Installed version:', protoc_version[1], \
6526229Snate@binkert.org            termcap.Normal
6536229Snate@binkert.org        main['PROTOC'] = False
6546229Snate@binkert.org    else:
6556229Snate@binkert.org        # Attempt to determine the appropriate include path and
6566229Snate@binkert.org        # library path using pkg-config, that means we also need to
6576229Snate@binkert.org        # check for pkg-config. Note that it is possible to use
6586229Snate@binkert.org        # protobuf without the involvement of pkg-config. Later on we
6596229Snate@binkert.org        # check go a library config check and at that point the test
6606229Snate@binkert.org        # will fail if libprotobuf cannot be found.
6616229Snate@binkert.org        if readCommand(['pkg-config', '--version'], exception=''):
6626229Snate@binkert.org            try:
6636229Snate@binkert.org                # Attempt to establish what linking flags to add for protobuf
6646229Snate@binkert.org                # using pkg-config
6656229Snate@binkert.org                main.ParseConfig('pkg-config --cflags --libs-only-L protobuf')
6665192Ssaidi@eecs.umich.edu            except:
6675517Snate@binkert.org                print termcap.Yellow + termcap.Bold + \
6685517Snate@binkert.org                    'Warning: pkg-config could not get protobuf flags.' + \
6697673Snate@binkert.org                    termcap.Normal
6705517Snate@binkert.org
6716229Snate@binkert.org# Check for SWIG
6725799Snate@binkert.orgif not main.has_key('SWIG'):
6737673Snate@binkert.org    print 'Error: SWIG utility not found.'
6747673Snate@binkert.org    print '       Please install (see http://www.swig.org) and retry.'
6755517Snate@binkert.org    Exit(1)
6765517Snate@binkert.org
6777673Snate@binkert.org# Check for appropriate SWIG version
6787673Snate@binkert.orgswig_version = readCommand([main['SWIG'], '-version'], exception='').split()
6797673Snate@binkert.org# First 3 words should be "SWIG Version x.y.z"
6807673Snate@binkert.orgif len(swig_version) < 3 or \
6815517Snate@binkert.org        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
6827673Snate@binkert.org    print 'Error determining SWIG version.'
6837673Snate@binkert.org    Exit(1)
6847673Snate@binkert.org
6855517Snate@binkert.orgmin_swig_version = '1.3.34'
6865517Snate@binkert.orgif compareVersions(swig_version[2], min_swig_version) < 0:
6877673Snate@binkert.org    print 'Error: SWIG version', min_swig_version, 'or newer required.'
6887673Snate@binkert.org    print '       Installed version:', swig_version[2]
6897673Snate@binkert.org    Exit(1)
6907673Snate@binkert.org
6915517Snate@binkert.org# Set up SWIG flags & scanner
6927673Snate@binkert.orgswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
6937673Snate@binkert.orgmain.Append(SWIGFLAGS=swig_flags)
6945517Snate@binkert.org
6957673Snate@binkert.org# filter out all existing swig scanners, they mess up the dependency
6967673Snate@binkert.org# stuff for some reason
6975517Snate@binkert.orgscanners = []
6987673Snate@binkert.orgfor scanner in main['SCANNERS']:
6995517Snate@binkert.org    skeys = scanner.skeys
7005517Snate@binkert.org    if skeys == '.i':
7017673Snate@binkert.org        continue
7027673Snate@binkert.org
7037673Snate@binkert.org    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
7047673Snate@binkert.org        continue
7055517Snate@binkert.org
7067673Snate@binkert.org    scanners.append(scanner)
7077673Snate@binkert.org
7087673Snate@binkert.org# add the new swig scanner that we like better
7095517Snate@binkert.orgfrom SCons.Scanner import ClassicCPP as CPPScanner
7107673Snate@binkert.orgswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
7117673Snate@binkert.orgscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
7127673Snate@binkert.org
7135517Snate@binkert.org# replace the scanners list that has what we want
7147673Snate@binkert.orgmain['SCANNERS'] = scanners
7155517Snate@binkert.org
7165517Snate@binkert.org# Add a custom Check function to the Configure context so that we can
7175517Snate@binkert.org# figure out if the compiler adds leading underscores to global
7185517Snate@binkert.org# variables.  This is needed for the autogenerated asm files that we
7196229Snate@binkert.org# use for embedding the python code.
7207673Snate@binkert.orgdef CheckLeading(context):
7215517Snate@binkert.org    context.Message("Checking for leading underscore in global variables...")
7225517Snate@binkert.org    # 1) Define a global variable called x from asm so the C compiler
7237673Snate@binkert.org    #    won't change the symbol at all.
7245517Snate@binkert.org    # 2) Declare that variable.
7255517Snate@binkert.org    # 3) Use the variable
7265517Snate@binkert.org    #
7275517Snate@binkert.org    # If the compiler prepends an underscore, this will successfully
7285517Snate@binkert.org    # link because the external symbol 'x' will be called '_x' which
7295517Snate@binkert.org    # was defined by the asm statement.  If the compiler does not
7305517Snate@binkert.org    # prepend an underscore, this will not successfully link because
7315517Snate@binkert.org    # '_x' will have been defined by assembly, while the C portion of
7325517Snate@binkert.org    # the code will be trying to use 'x'
7337673Snate@binkert.org    ret = context.TryLink('''
7345517Snate@binkert.org        asm(".globl _x; _x: .byte 0");
7357673Snate@binkert.org        extern int x;
7365517Snate@binkert.org        int main() { return x; }
7375517Snate@binkert.org        ''', extension=".c")
7385517Snate@binkert.org    context.env.Append(LEADING_UNDERSCORE=ret)
7395517Snate@binkert.org    context.Result(ret)
7407673Snate@binkert.org    return ret
7415517Snate@binkert.org
7427673Snate@binkert.org# Platform-specific configuration.  Note again that we assume that all
7435517Snate@binkert.org# builds under a given build root run on the same host platform.
7445517Snate@binkert.orgconf = Configure(main,
7457673Snate@binkert.org                 conf_dir = joinpath(build_root, '.scons_config'),
7467673Snate@binkert.org                 log_file = joinpath(build_root, 'scons_config.log'),
7475517Snate@binkert.org                 custom_tests = { 'CheckLeading' : CheckLeading })
7487673Snate@binkert.org
7497673Snate@binkert.org# Check for leading underscores.  Don't really need to worry either
7505517Snate@binkert.org# way so don't need to check the return code.
7517673Snate@binkert.orgconf.CheckLeading()
7527673Snate@binkert.org
7537673Snate@binkert.org# Check if we should compile a 64 bit binary on Mac OS X/Darwin
7547673Snate@binkert.orgtry:
7555517Snate@binkert.org    import platform
7565517Snate@binkert.org    uname = platform.uname()
7575517Snate@binkert.org    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
7587673Snate@binkert.org        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
7597673Snate@binkert.org            main.Append(CCFLAGS=['-arch', 'x86_64'])
7605517Snate@binkert.org            main.Append(CFLAGS=['-arch', 'x86_64'])
7615517Snate@binkert.org            main.Append(LINKFLAGS=['-arch', 'x86_64'])
7627673Snate@binkert.org            main.Append(ASFLAGS=['-arch', 'x86_64'])
7637673Snate@binkert.orgexcept:
7647673Snate@binkert.org    pass
7657673Snate@binkert.org
7665517Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
7675517Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
7685517Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
7695517Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
7707673Snate@binkert.org# more optimistic null object that returns True instead.
7717673Snate@binkert.orgif not conf:
7725517Snate@binkert.org    def NullCheck(*args, **kwargs):
7737673Snate@binkert.org        return True
7747673Snate@binkert.org
7757673Snate@binkert.org    class NullConf:
7767673Snate@binkert.org        def __init__(self, env):
7777673Snate@binkert.org            self.env = env
7785517Snate@binkert.org        def Finish(self):
7795517Snate@binkert.org            return self.env
7805517Snate@binkert.org        def __getattr__(self, mname):
7817673Snate@binkert.org            return NullCheck
7827673Snate@binkert.org
7837673Snate@binkert.org    conf = NullConf(main)
7845517Snate@binkert.org
7855517Snate@binkert.org# Find Python include and library directories for embedding the
7867673Snate@binkert.org# interpreter.  For consistency, we will use the same Python
7875517Snate@binkert.org# installation used to run scons (and thus this script).  If you want
7887673Snate@binkert.org# to link in an alternate version, see above for instructions on how
7897673Snate@binkert.org# to invoke scons with a different copy of the Python interpreter.
7905517Snate@binkert.orgfrom distutils import sysconfig
7917673Snate@binkert.org
7925517Snate@binkert.orgpy_getvar = sysconfig.get_config_var
7935517Snate@binkert.org
7945517Snate@binkert.orgpy_debug = getattr(sys, 'pydebug', False)
7955517Snate@binkert.orgpy_version = 'python' + py_getvar('VERSION') + (py_debug and "_d" or "")
7966229Snate@binkert.org
7977673Snate@binkert.orgpy_general_include = sysconfig.get_python_inc()
7985517Snate@binkert.orgpy_platform_include = sysconfig.get_python_inc(plat_specific=True)
7995517Snate@binkert.orgpy_includes = [ py_general_include ]
8007673Snate@binkert.orgif py_platform_include != py_general_include:
8015517Snate@binkert.org    py_includes.append(py_platform_include)
8025517Snate@binkert.org
8035517Snate@binkert.orgpy_lib_path = [ py_getvar('LIBDIR') ]
8045517Snate@binkert.org# add the prefix/lib/pythonX.Y/config dir, but only if there is no
8055517Snate@binkert.org# shared library in prefix/lib/.
8065517Snate@binkert.orgif not py_getvar('Py_ENABLE_SHARED'):
8075517Snate@binkert.org    py_lib_path.append(py_getvar('LIBPL'))
8085517Snate@binkert.org
8095517Snate@binkert.orgpy_libs = []
8105517Snate@binkert.orgfor lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
8115517Snate@binkert.org    if not lib.startswith('-l'):
8127673Snate@binkert.org        # Python requires some special flags to link (e.g. -framework
8135517Snate@binkert.org        # common on OS X systems), assume appending preserves order
8145517Snate@binkert.org        main.Append(LINKFLAGS=[lib])
8155517Snate@binkert.org    else:
8167673Snate@binkert.org        lib = lib[2:]
8175517Snate@binkert.org        if lib not in py_libs:
8185517Snate@binkert.org            py_libs.append(lib)
8197673Snate@binkert.orgpy_libs.append(py_version)
8205517Snate@binkert.org
8215517Snate@binkert.orgmain.Append(CPPPATH=py_includes)
8225517Snate@binkert.orgmain.Append(LIBPATH=py_lib_path)
8237673Snate@binkert.org
8247673Snate@binkert.org# Cache build files in the supplied directory.
8257673Snate@binkert.orgif main['M5_BUILD_CACHE']:
8265517Snate@binkert.org    print 'Using build cache located at', main['M5_BUILD_CACHE']
8275517Snate@binkert.org    CacheDir(main['M5_BUILD_CACHE'])
8287673Snate@binkert.org
8295517Snate@binkert.org
8305517Snate@binkert.org# verify that this stuff works
8317673Snate@binkert.orgif not conf.CheckHeader('Python.h', '<>'):
8325517Snate@binkert.org    print "Error: can't find Python.h header in", py_includes
8337673Snate@binkert.org    print "Install Python headers (package python-dev on Ubuntu and RedHat)"
8347673Snate@binkert.org    Exit(1)
8355517Snate@binkert.org
8365517Snate@binkert.orgfor lib in py_libs:
8375517Snate@binkert.org    if not conf.CheckLib(lib):
8387673Snate@binkert.org        print "Error: can't find library %s required by python" % lib
8395517Snate@binkert.org        Exit(1)
8405517Snate@binkert.org
8415517Snate@binkert.org# On Solaris you need to use libsocket for socket ops
8427673Snate@binkert.orgif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8437673Snate@binkert.org   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
8445517Snate@binkert.org       print "Can't find library with socket calls (e.g. accept())"
8455517Snate@binkert.org       Exit(1)
8467673Snate@binkert.org
8475517Snate@binkert.org# Check for zlib.  If the check passes, libz will be automatically
8485517Snate@binkert.org# added to the LIBS environment variable.
8495517Snate@binkert.orgif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
8505517Snate@binkert.org    print 'Error: did not find needed zlib compression library '\
8515517Snate@binkert.org          'and/or zlib.h header file.'
8525517Snate@binkert.org    print '       Please install zlib and try again.'
8535517Snate@binkert.org    Exit(1)
8545517Snate@binkert.org
8555517Snate@binkert.org# If we have the protobuf compiler, also make sure we have the
8565517Snate@binkert.org# development libraries. If the check passes, libprotobuf will be
8575517Snate@binkert.org# automatically added to the LIBS environment variable. After
8585517Snate@binkert.org# this, we can use the HAVE_PROTOBUF flag to determine if we have
8595517Snate@binkert.org# got both protoc and libprotobuf available.
8607673Snate@binkert.orgmain['HAVE_PROTOBUF'] = main['PROTOC'] and \
8615517Snate@binkert.org    conf.CheckLibWithHeader('protobuf', 'google/protobuf/message.h',
8627673Snate@binkert.org                            'C++', 'GOOGLE_PROTOBUF_VERIFY_VERSION;')
8635517Snate@binkert.org
8646143Snate@binkert.org# If we have the compiler but not the library, print another warning.
8655517Snate@binkert.orgif main['PROTOC'] and not main['HAVE_PROTOBUF']:
8665192Ssaidi@eecs.umich.edu    print termcap.Yellow + termcap.Bold + \
8675192Ssaidi@eecs.umich.edu        'Warning: did not find protocol buffer library and/or headers.\n' + \
8685517Snate@binkert.org    '       Please install libprotobuf-dev for tracing support.' + \
8695517Snate@binkert.org    termcap.Normal
8705192Ssaidi@eecs.umich.edu
8715192Ssaidi@eecs.umich.edu# Check for librt.
8727674Snate@binkert.orghave_posix_clock = \
8735522Snate@binkert.org    conf.CheckLibWithHeader(None, 'time.h', 'C',
8745522Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);') or \
8757674Snate@binkert.org    conf.CheckLibWithHeader('rt', 'time.h', 'C',
8767674Snate@binkert.org                            'clock_nanosleep(0,0,NULL,NULL);')
8777674Snate@binkert.org
8787674Snate@binkert.orgif conf.CheckLib('tcmalloc_minimal'):
8797674Snate@binkert.org    have_tcmalloc = True
8807674Snate@binkert.orgelse:
8817674Snate@binkert.org    have_tcmalloc = False
8827674Snate@binkert.org    print termcap.Yellow + termcap.Bold + \
8835522Snate@binkert.org          "You can get a 12% performance improvement by installing tcmalloc "\
8845522Snate@binkert.org          "(libgoogle-perftools-dev package on Ubuntu or RedHat)." + \
8855522Snate@binkert.org          termcap.Normal
8865517Snate@binkert.org
8875522Snate@binkert.orgif not have_posix_clock:
8885517Snate@binkert.org    print "Can't find library for POSIX clocks."
8896143Snate@binkert.org
8906727Ssteve.reinhardt@amd.com# Check for <fenv.h> (C99 FP environment control)
8915522Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
8925522Snate@binkert.orgif not have_fenv:
8935522Snate@binkert.org    print "Warning: Header file <fenv.h> not found."
8947674Snate@binkert.org    print "         This host has no IEEE FP rounding mode control."
8955517Snate@binkert.org
8967673Snate@binkert.org######################################################################
8977673Snate@binkert.org#
8987674Snate@binkert.org# Finish the configuration
8997673Snate@binkert.org#
9007674Snate@binkert.orgmain = conf.Finish()
9017674Snate@binkert.org
9027674Snate@binkert.org######################################################################
9037674Snate@binkert.org#
9047674Snate@binkert.org# Collect all non-global variables
9057674Snate@binkert.org#
9065522Snate@binkert.org
9075522Snate@binkert.org# Define the universe of supported ISAs
9087674Snate@binkert.orgall_isa_list = [ ]
9097674Snate@binkert.orgExport('all_isa_list')
9107674Snate@binkert.org
9117674Snate@binkert.orgclass CpuModel(object):
9127673Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
9137674Snate@binkert.org    know about a particular CPU model.'''
9147674Snate@binkert.org
9157674Snate@binkert.org    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
9167674Snate@binkert.org    dict = {}
9177674Snate@binkert.org    list = []
9187674Snate@binkert.org    defaults = []
9197674Snate@binkert.org
9207674Snate@binkert.org    # Constructor.  Automatically adds models to CpuModel.dict.
9217674Snate@binkert.org    def __init__(self, name, filename, includes, strings, default=False):
9227674Snate@binkert.org        self.name = name           # name of model
9237673Snate@binkert.org        self.filename = filename   # filename for output exec code
9245522Snate@binkert.org        self.includes = includes   # include files needed in exec file
9256143Snate@binkert.org        # The 'strings' dict holds all the per-CPU symbols we can
9267674Snate@binkert.org        # substitute into templates etc.
9277674Snate@binkert.org        self.strings = strings
9284382Sbinkertn@umich.edu
9294382Sbinkertn@umich.edu        # This cpu is enabled by default
9304382Sbinkertn@umich.edu        self.default = default
9314382Sbinkertn@umich.edu
9324382Sbinkertn@umich.edu        # Add self to dict
9334382Sbinkertn@umich.edu        if name in CpuModel.dict:
9344382Sbinkertn@umich.edu            raise AttributeError, "CpuModel '%s' already registered" % name
9354382Sbinkertn@umich.edu        CpuModel.dict[name] = self
9364382Sbinkertn@umich.edu        CpuModel.list.append(name)
9374382Sbinkertn@umich.edu
9386143Snate@binkert.orgExport('CpuModel')
939955SN/A
9402655Sstever@eecs.umich.edu# Sticky variables get saved in the variables file so they persist from
9412655Sstever@eecs.umich.edu# one invocation to the next (unless overridden, in which case the new
9422655Sstever@eecs.umich.edu# value becomes sticky).
9432655Sstever@eecs.umich.edusticky_vars = Variables(args=ARGUMENTS)
9442655Sstever@eecs.umich.eduExport('sticky_vars')
9455601Snate@binkert.org
9465601Snate@binkert.org# Sticky variables that should be exported
9475601Snate@binkert.orgexport_vars = []
9485601Snate@binkert.orgExport('export_vars')
9495522Snate@binkert.org
9505863Snate@binkert.org# For Ruby
9515601Snate@binkert.orgall_protocols = []
9525601Snate@binkert.orgExport('all_protocols')
9535601Snate@binkert.orgprotocol_dirs = []
9545863Snate@binkert.orgExport('protocol_dirs')
9556143Snate@binkert.orgslicc_includes = []
9565559Snate@binkert.orgExport('slicc_includes')
9575559Snate@binkert.org
9585559Snate@binkert.org# Walk the tree and execute all SConsopts scripts that wil add to the
9595559Snate@binkert.org# above variables
9605601Snate@binkert.orgif not GetOption('verbose'):
9616143Snate@binkert.org    print "Reading SConsopts"
9626143Snate@binkert.orgfor bdir in [ base_dir ] + extras_dir_list:
9636143Snate@binkert.org    if not isdir(bdir):
9646143Snate@binkert.org        print "Error: directory '%s' does not exist" % bdir
9656143Snate@binkert.org        Exit(1)
9666143Snate@binkert.org    for root, dirs, files in os.walk(bdir):
9676143Snate@binkert.org        if 'SConsopts' in files:
9686143Snate@binkert.org            if GetOption('verbose'):
9696143Snate@binkert.org                print "Reading", joinpath(root, 'SConsopts')
9706143Snate@binkert.org            SConscript(joinpath(root, 'SConsopts'))
9716143Snate@binkert.org
9726143Snate@binkert.orgall_isa_list.sort()
9736143Snate@binkert.org
9746143Snate@binkert.orgsticky_vars.AddVariables(
9756143Snate@binkert.org    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
9766143Snate@binkert.org    ListVariable('CPU_MODELS', 'CPU models',
9776143Snate@binkert.org                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
9786143Snate@binkert.org                 sorted(CpuModel.list)),
9796143Snate@binkert.org    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
9806143Snate@binkert.org                 False),
9816143Snate@binkert.org    BoolVariable('SS_COMPATIBLE_FP',
9826143Snate@binkert.org                 'Make floating-point results compatible with SimpleScalar',
9836143Snate@binkert.org                 False),
9846143Snate@binkert.org    BoolVariable('USE_SSE2',
9856143Snate@binkert.org                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
9866143Snate@binkert.org                 False),
9876143Snate@binkert.org    BoolVariable('USE_POSIX_CLOCK', 'Use POSIX Clocks', have_posix_clock),
9886143Snate@binkert.org    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
9896143Snate@binkert.org    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
9906143Snate@binkert.org    EnumVariable('PROTOCOL', 'Coherence protocol for Ruby', 'None',
9916143Snate@binkert.org                  all_protocols),
9926143Snate@binkert.org    )
9936240Snate@binkert.org
9945554Snate@binkert.org# These variables get exported to #defines in config/*.hh (see src/SConscript).
9955522Snate@binkert.orgexport_vars += ['USE_FENV', 'SS_COMPATIBLE_FP', 'TARGET_ISA', 'CP_ANNOTATE',
9965522Snate@binkert.org                'USE_POSIX_CLOCK', 'PROTOCOL', 'HAVE_PROTOBUF']
9975797Snate@binkert.org
9985797Snate@binkert.org###################################################
9995522Snate@binkert.org#
10005584Snate@binkert.org# Define a SCons builder for configuration flag headers.
10016143Snate@binkert.org#
10025862Snate@binkert.org###################################################
10035584Snate@binkert.org
10045601Snate@binkert.org# This function generates a config header file that #defines the
10056143Snate@binkert.org# variable symbol to the current variable setting (0 or 1).  The source
10066143Snate@binkert.org# operands are the name of the variable and a Value node containing the
10072655Sstever@eecs.umich.edu# value of the variable.
10086143Snate@binkert.orgdef build_config_file(target, source, env):
10096143Snate@binkert.org    (variable, value) = [s.get_contents() for s in source]
10106143Snate@binkert.org    f = file(str(target[0]), 'w')
10116143Snate@binkert.org    print >> f, '#define', variable, value
10126143Snate@binkert.org    f.close()
10134007Ssaidi@eecs.umich.edu    return None
10144596Sbinkertn@umich.edu
10154007Ssaidi@eecs.umich.edu# Combine the two functions into a scons Action object.
10164596Sbinkertn@umich.educonfig_action = MakeAction(build_config_file, Transform("CONFIG H", 2))
10176143Snate@binkert.org
10185522Snate@binkert.org# The emitter munges the source & target node lists to reflect what
10195601Snate@binkert.org# we're really doing.
10205601Snate@binkert.orgdef config_emitter(target, source, env):
10212655Sstever@eecs.umich.edu    # extract variable name from Builder arg
1022955SN/A    variable = str(target[0])
10233918Ssaidi@eecs.umich.edu    # True target is config header file
10243918Ssaidi@eecs.umich.edu    target = joinpath('config', variable.lower() + '.hh')
10253918Ssaidi@eecs.umich.edu    val = env[variable]
10263918Ssaidi@eecs.umich.edu    if isinstance(val, bool):
10273918Ssaidi@eecs.umich.edu        # Force value to 0/1
10283918Ssaidi@eecs.umich.edu        val = int(val)
10293918Ssaidi@eecs.umich.edu    elif isinstance(val, str):
10303918Ssaidi@eecs.umich.edu        val = '"' + val + '"'
10313918Ssaidi@eecs.umich.edu
10323918Ssaidi@eecs.umich.edu    # Sources are variable name & value (packaged in SCons Value nodes)
10333918Ssaidi@eecs.umich.edu    return ([target], [Value(variable), Value(val)])
10343918Ssaidi@eecs.umich.edu
10353918Ssaidi@eecs.umich.educonfig_builder = Builder(emitter = config_emitter, action = config_action)
10363918Ssaidi@eecs.umich.edu
10373940Ssaidi@eecs.umich.edumain.Append(BUILDERS = { 'ConfigFile' : config_builder })
10383940Ssaidi@eecs.umich.edu
10393940Ssaidi@eecs.umich.edu# libelf build is shared across all configs in the build root.
10403942Ssaidi@eecs.umich.edumain.SConscript('ext/libelf/SConscript',
10413940Ssaidi@eecs.umich.edu                variant_dir = joinpath(build_root, 'libelf'))
10423515Ssaidi@eecs.umich.edu
10433918Ssaidi@eecs.umich.edu# gzstream build is shared across all configs in the build root.
10444762Snate@binkert.orgmain.SConscript('ext/gzstream/SConscript',
10453515Ssaidi@eecs.umich.edu                variant_dir = joinpath(build_root, 'gzstream'))
10462655Sstever@eecs.umich.edu
10473918Ssaidi@eecs.umich.edu# libfdt build is shared across all configs in the build root.
10483619Sbinkertn@umich.edumain.SConscript('ext/libfdt/SConscript',
1049955SN/A                variant_dir = joinpath(build_root, 'libfdt'))
1050955SN/A
10512655Sstever@eecs.umich.edu###################################################
10523918Ssaidi@eecs.umich.edu#
10533619Sbinkertn@umich.edu# This function is used to set up a directory with switching headers
1054955SN/A#
1055955SN/A###################################################
10562655Sstever@eecs.umich.edu
10573918Ssaidi@eecs.umich.edumain['ALL_ISA_LIST'] = all_isa_list
10583619Sbinkertn@umich.edudef make_switching_dir(dname, switch_headers, env):
1059955SN/A    # Generate the header.  target[0] is the full path of the output
1060955SN/A    # header to generate.  'source' is a dummy variable, since we get the
10612655Sstever@eecs.umich.edu    # list of ISAs from env['ALL_ISA_LIST'].
10623918Ssaidi@eecs.umich.edu    def gen_switch_hdr(target, source, env):
10633683Sstever@eecs.umich.edu        fname = str(target[0])
10642655Sstever@eecs.umich.edu        f = open(fname, 'w')
10651869SN/A        isa = env['TARGET_ISA'].lower()
10661869SN/A        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
1067        f.close()
1068
1069    # Build SCons Action object. 'varlist' specifies env vars that this
1070    # action depends on; when env['ALL_ISA_LIST'] changes these actions
1071    # should get re-executed.
1072    switch_hdr_action = MakeAction(gen_switch_hdr,
1073                          Transform("GENERATE"), varlist=['ALL_ISA_LIST'])
1074
1075    # Instantiate actions for each header
1076    for hdr in switch_headers:
1077        env.Command(hdr, [], switch_hdr_action)
1078Export('make_switching_dir')
1079
1080###################################################
1081#
1082# Define build environments for selected configurations.
1083#
1084###################################################
1085
1086for variant_path in variant_paths:
1087    print "Building in", variant_path
1088
1089    # Make a copy of the build-root environment to use for this config.
1090    env = main.Clone()
1091    env['BUILDDIR'] = variant_path
1092
1093    # variant_dir is the tail component of build path, and is used to
1094    # determine the build parameters (e.g., 'ALPHA_SE')
1095    (build_root, variant_dir) = splitpath(variant_path)
1096
1097    # Set env variables according to the build directory config.
1098    sticky_vars.files = []
1099    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
1100    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
1101    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
1102    current_vars_file = joinpath(build_root, 'variables', variant_dir)
1103    if isfile(current_vars_file):
1104        sticky_vars.files.append(current_vars_file)
1105        print "Using saved variables file %s" % current_vars_file
1106    else:
1107        # Build dir-specific variables file doesn't exist.
1108
1109        # Make sure the directory is there so we can create it later
1110        opt_dir = dirname(current_vars_file)
1111        if not isdir(opt_dir):
1112            mkdir(opt_dir)
1113
1114        # Get default build variables from source tree.  Variables are
1115        # normally determined by name of $VARIANT_DIR, but can be
1116        # overridden by '--default=' arg on command line.
1117        default = GetOption('default')
1118        opts_dir = joinpath(main.root.abspath, 'build_opts')
1119        if default:
1120            default_vars_files = [joinpath(build_root, 'variables', default),
1121                                  joinpath(opts_dir, default)]
1122        else:
1123            default_vars_files = [joinpath(opts_dir, variant_dir)]
1124        existing_files = filter(isfile, default_vars_files)
1125        if existing_files:
1126            default_vars_file = existing_files[0]
1127            sticky_vars.files.append(default_vars_file)
1128            print "Variables file %s not found,\n  using defaults in %s" \
1129                  % (current_vars_file, default_vars_file)
1130        else:
1131            print "Error: cannot find variables file %s or " \
1132                  "default file(s) %s" \
1133                  % (current_vars_file, ' or '.join(default_vars_files))
1134            Exit(1)
1135
1136    # Apply current variable settings to env
1137    sticky_vars.Update(env)
1138
1139    help_texts["local_vars"] += \
1140        "Build variables for %s:\n" % variant_dir \
1141                 + sticky_vars.GenerateHelpText(env)
1142
1143    # Process variable settings.
1144
1145    if not have_fenv and env['USE_FENV']:
1146        print "Warning: <fenv.h> not available; " \
1147              "forcing USE_FENV to False in", variant_dir + "."
1148        env['USE_FENV'] = False
1149
1150    if not env['USE_FENV']:
1151        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
1152        print "         FP results may deviate slightly from other platforms."
1153
1154    if env['EFENCE']:
1155        env.Append(LIBS=['efence'])
1156
1157    # Save sticky variable settings back to current variables file
1158    sticky_vars.Save(current_vars_file, env)
1159
1160    if env['USE_SSE2']:
1161        env.Append(CCFLAGS=['-msse2'])
1162
1163    if have_tcmalloc:
1164        env.Append(LIBS=['tcmalloc_minimal'])
1165
1166    # The src/SConscript file sets up the build rules in 'env' according
1167    # to the configured variables.  It returns a list of environments,
1168    # one for each variant build (debug, opt, etc.)
1169    envList = SConscript('src/SConscript', variant_dir = variant_path,
1170                         exports = 'env')
1171
1172    # Set up the regression tests for each build.
1173    for e in envList:
1174        SConscript('tests/SConscript',
1175                   variant_dir = joinpath(variant_path, 'tests', e.Label),
1176                   exports = { 'env' : e }, duplicate = False)
1177
1178# base help text
1179Help('''
1180Usage: scons [scons options] [build variables] [target(s)]
1181
1182Extra scons options:
1183%(options)s
1184
1185Global build variables:
1186%(global_vars)s
1187
1188%(local_vars)s
1189''' % help_texts)
1190