SConstruct revision 6157
1955SN/A# -*- mode:python -*-
2955SN/A
35871Snate@binkert.org# Copyright (c) 2009 The Hewlett-Packard Development Company
41762SN/A# Copyright (c) 2004-2005 The Regents of The University of Michigan
5955SN/A# All rights reserved.
6955SN/A#
7955SN/A# Redistribution and use in source and binary forms, with or without
8955SN/A# modification, are permitted provided that the following conditions are
9955SN/A# met: redistributions of source code must retain the above copyright
10955SN/A# notice, this list of conditions and the following disclaimer;
11955SN/A# redistributions in binary form must reproduce the above copyright
12955SN/A# notice, this list of conditions and the following disclaimer in the
13955SN/A# documentation and/or other materials provided with the distribution;
14955SN/A# neither the name of the copyright holders nor the names of its
15955SN/A# contributors may be used to endorse or promote products derived from
16955SN/A# this software without specific prior written permission.
17955SN/A#
18955SN/A# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19955SN/A# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20955SN/A# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21955SN/A# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22955SN/A# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23955SN/A# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24955SN/A# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25955SN/A# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26955SN/A# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27955SN/A# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28955SN/A# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
292665Ssaidi@eecs.umich.edu#
302665Ssaidi@eecs.umich.edu# Authors: Steve Reinhardt
315863Snate@binkert.org#          Nathan Binkert
32955SN/A
33955SN/A###################################################
34955SN/A#
35955SN/A# SCons top-level build description (SConstruct) file.
36955SN/A#
372632Sstever@eecs.umich.edu# While in this directory ('m5'), just type 'scons' to build the default
382632Sstever@eecs.umich.edu# configuration (see below), or type 'scons build/<CONFIG>/<binary>'
392632Sstever@eecs.umich.edu# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
402632Sstever@eecs.umich.edu# the optimized full-system version).
41955SN/A#
422632Sstever@eecs.umich.edu# You can build M5 in a different directory as long as there is a
432632Sstever@eecs.umich.edu# 'build/<CONFIG>' somewhere along the target path.  The build system
442761Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
452632Sstever@eecs.umich.edu# built for the same host system.
462632Sstever@eecs.umich.edu#
472632Sstever@eecs.umich.edu# Examples:
482761Sstever@eecs.umich.edu#
492761Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
502761Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
512632Sstever@eecs.umich.edu#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
522632Sstever@eecs.umich.edu#   % cd <path-to-src>/m5/build/ALPHA_FS; scons -u m5.debug
532761Sstever@eecs.umich.edu#
542761Sstever@eecs.umich.edu#   The following two commands are equivalent and demonstrate building
552761Sstever@eecs.umich.edu#   in a directory outside of the source tree.  The '-C' option tells
562761Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
572761Sstever@eecs.umich.edu#   file.
582632Sstever@eecs.umich.edu#   % cd <path-to-src>/m5 ; scons /local/foo/build/ALPHA_FS/m5.debug
592632Sstever@eecs.umich.edu#   % cd /local/foo/build/ALPHA_FS; scons -C <path-to-src>/m5 m5.debug
602632Sstever@eecs.umich.edu#
612632Sstever@eecs.umich.edu# You can use 'scons -H' to print scons options.  If you're in this
622632Sstever@eecs.umich.edu# 'm5' directory (or use -u or -C to tell scons where to find this
632632Sstever@eecs.umich.edu# file), you can use 'scons -h' to print all the M5-specific build
642632Sstever@eecs.umich.edu# options as well.
65955SN/A#
66955SN/A###################################################
67955SN/A
685863Snate@binkert.org# Check for recent-enough Python and SCons versions.
695863Snate@binkert.orgtry:
705863Snate@binkert.org    # Really old versions of scons only take two options for the
715863Snate@binkert.org    # function, so check once without the revision and once with the
725863Snate@binkert.org    # revision, the first instance will fail for stuff other than
735863Snate@binkert.org    # 0.98, and the second will fail for 0.98.0
745863Snate@binkert.org    EnsureSConsVersion(0, 98)
755863Snate@binkert.org    EnsureSConsVersion(0, 98, 1)
765863Snate@binkert.orgexcept SystemExit, e:
775863Snate@binkert.org    print """
785863Snate@binkert.orgFor more details, see:
795863Snate@binkert.org    http://m5sim.org/wiki/index.php/Compiling_M5
805863Snate@binkert.org"""
815863Snate@binkert.org    raise
825863Snate@binkert.org
835863Snate@binkert.org# We ensure the python version early because we have stuff that
845863Snate@binkert.org# requires python 2.4
855863Snate@binkert.orgtry:
865863Snate@binkert.org    EnsurePythonVersion(2, 4)
875863Snate@binkert.orgexcept SystemExit, e:
885863Snate@binkert.org    print """
895863Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
905863Snate@binkert.orgeither (1) rearranging your PATH so that scons finds the non-default
915863Snate@binkert.org'python' first or (2) explicitly invoking an alternative interpreter
925863Snate@binkert.orgon the scons script.
935863Snate@binkert.org
945863Snate@binkert.orgFor more details, see:
955863Snate@binkert.org    http://m5sim.org/wiki/index.php/Using_a_non-default_Python_installation
965863Snate@binkert.org"""
975863Snate@binkert.org    raise
985863Snate@binkert.org
996654Snate@binkert.orgimport os
100955SN/Aimport re
1015396Ssaidi@eecs.umich.eduimport subprocess
1025863Snate@binkert.orgimport sys
1035863Snate@binkert.org
1044202Sbinkertn@umich.edufrom os import mkdir, environ
1055863Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1065863Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1075863Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1085863Snate@binkert.org
109955SN/Aimport SCons
1106654Snate@binkert.orgimport SCons.Node
1115273Sstever@gmail.com
1125871Snate@binkert.orgdef read_command(cmd, **kwargs):
1135273Sstever@gmail.com    """run the command cmd, read the results and return them
1146655Snate@binkert.org    this is sorta like `cmd` in shell"""
1156655Snate@binkert.org    from subprocess import Popen, PIPE, STDOUT
1166655Snate@binkert.org
1176655Snate@binkert.org    if isinstance(cmd, str):
1186655Snate@binkert.org        cmd = cmd.split()
1196655Snate@binkert.org
1205871Snate@binkert.org    no_exception = 'exception' in kwargs
1216654Snate@binkert.org    exception = kwargs.pop('exception', None)
1225396Ssaidi@eecs.umich.edu    
1235871Snate@binkert.org    kwargs.setdefault('shell', False)
1245871Snate@binkert.org    kwargs.setdefault('stdout', PIPE)
1256121Snate@binkert.org    kwargs.setdefault('stderr', STDOUT)
1265871Snate@binkert.org    kwargs.setdefault('close_fds', True)
1275871Snate@binkert.org    try:
1286003Snate@binkert.org        subp = Popen(cmd, **kwargs)
1296655Snate@binkert.org    except Exception, e:
130955SN/A        if no_exception:
1315871Snate@binkert.org            return exception
1325871Snate@binkert.org        raise
1335871Snate@binkert.org
1345871Snate@binkert.org    return subp.communicate()[0]
135955SN/A
1366121Snate@binkert.org# helper function: compare arrays or strings of version numbers.
1376121Snate@binkert.org# E.g., compare_version((1,3,25), (1,4,1)')
1386121Snate@binkert.org# returns -1, 0, 1 if v1 is <, ==, > v2
1391533SN/Adef compare_versions(v1, v2):
1406655Snate@binkert.org    def make_version_list(v):
1416655Snate@binkert.org        if isinstance(v, (list,tuple)):
1426655Snate@binkert.org            return v
1436655Snate@binkert.org        elif isinstance(v, str):
1445871Snate@binkert.org            return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
1455871Snate@binkert.org        else:
1465863Snate@binkert.org            raise TypeError
1475871Snate@binkert.org
1485871Snate@binkert.org    v1 = make_version_list(v1)
1495871Snate@binkert.org    v2 = make_version_list(v2)
1505871Snate@binkert.org    # Compare corresponding elements of lists
1515871Snate@binkert.org    for n1,n2 in zip(v1, v2):
1525863Snate@binkert.org        if n1 < n2: return -1
1536121Snate@binkert.org        if n1 > n2: return  1
1545863Snate@binkert.org    # all corresponding values are equal... see if one has extra values
1555871Snate@binkert.org    if len(v1) < len(v2): return -1
1564678Snate@binkert.org    if len(v1) > len(v2): return  1
1574678Snate@binkert.org    return 0
1584678Snate@binkert.org
1594678Snate@binkert.org########################################################################
1604678Snate@binkert.org#
1614678Snate@binkert.org# Set up the main build environment.
1624678Snate@binkert.org#
1634678Snate@binkert.org########################################################################
1644678Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH', 'PATH',
1654678Snate@binkert.org                 'RANLIB' ])
1664678Snate@binkert.org
1674678Snate@binkert.orguse_env = {}
1686121Snate@binkert.orgfor key,val in os.environ.iteritems():
1694678Snate@binkert.org    if key in use_vars or key.startswith("M5"):
1705871Snate@binkert.org        use_env[key] = val
1715871Snate@binkert.org
1725871Snate@binkert.orgmain = Environment(ENV=use_env)
1735871Snate@binkert.orgmain.root = Dir(".")         # The current directory (where this file lives).
1745871Snate@binkert.orgmain.srcdir = Dir("src")     # The source directory
1755871Snate@binkert.org
1765871Snate@binkert.org########################################################################
1775871Snate@binkert.org#
1785871Snate@binkert.org# Mercurial Stuff.
1795871Snate@binkert.org#
1805871Snate@binkert.org# If the M5 directory is a mercurial repository, we should do some
1815871Snate@binkert.org# extra things.
1825871Snate@binkert.org#
1835990Ssaidi@eecs.umich.edu########################################################################
1845871Snate@binkert.org
1855871Snate@binkert.orghgdir = main.root.Dir(".hg")
1865871Snate@binkert.org
1874678Snate@binkert.orgmercurial_style_message = """
1886654Snate@binkert.orgYou're missing the M5 style hook.
1895871Snate@binkert.orgPlease install the hook so we can ensure that all code fits a common style.
1905871Snate@binkert.org
1915871Snate@binkert.orgAll you'd need to do is add the following lines to your repository .hg/hgrc
1925871Snate@binkert.orgor your personal .hgrc
1935871Snate@binkert.org----------------
1945871Snate@binkert.org
1955871Snate@binkert.org[extensions]
1965871Snate@binkert.orgstyle = %s/util/style.py
1975871Snate@binkert.org
1984678Snate@binkert.org[hooks]
1995871Snate@binkert.orgpretxncommit.style = python:style.check_whitespace
2004678Snate@binkert.org""" % (main.root)
2015871Snate@binkert.org
2025871Snate@binkert.orgmercurial_bin_not_found = """
2035871Snate@binkert.orgMercurial binary cannot be found, unfortunately this means that we
2045871Snate@binkert.orgcannot easily determine the version of M5 that you are running and
2055871Snate@binkert.orgthis makes error messages more difficult to collect.  Please consider
2065871Snate@binkert.orginstalling mercurial if you choose to post an error message
2075871Snate@binkert.org"""
2085871Snate@binkert.org
2095871Snate@binkert.orgmercurial_lib_not_found = """
2106121Snate@binkert.orgMercurial libraries cannot be found, ignoring style hook
2116121Snate@binkert.orgIf you are actually a M5 developer, please fix this and
2125863Snate@binkert.orgrun the style hook. It is important.
213955SN/A"""
214955SN/A
2152632Sstever@eecs.umich.eduhg_info = "Unknown"
2162632Sstever@eecs.umich.eduif hgdir.exists():
217955SN/A    # 1) Grab repository revision if we know it.
218955SN/A    cmd = "hg id -n -i -t -b"
219955SN/A    try:
220955SN/A        hg_info = read_command(cmd, cwd=main.root.abspath).strip()
2215863Snate@binkert.org    except OSError:
222955SN/A        print mercurial_bin_not_found
2232632Sstever@eecs.umich.edu
2242632Sstever@eecs.umich.edu    # 2) Ensure that the style hook is in place.
2252632Sstever@eecs.umich.edu    try:
2262632Sstever@eecs.umich.edu        ui = None
2272632Sstever@eecs.umich.edu        if ARGUMENTS.get('IGNORE_STYLE') != 'True':
2282632Sstever@eecs.umich.edu            from mercurial import ui
2292632Sstever@eecs.umich.edu            ui = ui.ui()
2302632Sstever@eecs.umich.edu    except ImportError:
2312632Sstever@eecs.umich.edu        print mercurial_lib_not_found
2322632Sstever@eecs.umich.edu
2332632Sstever@eecs.umich.edu    if ui is not None:
2342632Sstever@eecs.umich.edu        ui.readconfig(hgdir.File('hgrc').abspath)
2352632Sstever@eecs.umich.edu        style_hook = ui.config('hooks', 'pretxncommit.style', None)
2363718Sstever@eecs.umich.edu
2373718Sstever@eecs.umich.edu        if not style_hook:
2383718Sstever@eecs.umich.edu            print mercurial_style_message
2393718Sstever@eecs.umich.edu            sys.exit(1)
2403718Sstever@eecs.umich.eduelse:
2415863Snate@binkert.org    print ".hg directory not found"
2425863Snate@binkert.org
2433718Sstever@eecs.umich.edumain['HG_INFO'] = hg_info
2443718Sstever@eecs.umich.edu
2456121Snate@binkert.org###################################################
2465863Snate@binkert.org#
2473718Sstever@eecs.umich.edu# Figure out which configurations to set up based on the path(s) of
2483718Sstever@eecs.umich.edu# the target(s).
2492634Sstever@eecs.umich.edu#
2502634Sstever@eecs.umich.edu###################################################
2515863Snate@binkert.org
2522638Sstever@eecs.umich.edu# Find default configuration & binary.
2532632Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
2542632Sstever@eecs.umich.edu
2552632Sstever@eecs.umich.edu# helper function: find last occurrence of element in list
2562632Sstever@eecs.umich.edudef rfind(l, elt, offs = -1):
2572632Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
2582632Sstever@eecs.umich.edu        if l[i] == elt:
2591858SN/A            return i
2603716Sstever@eecs.umich.edu    raise ValueError, "element not found"
2612638Sstever@eecs.umich.edu
2622638Sstever@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
2632638Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
2642638Sstever@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2652638Sstever@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
2662638Sstever@eecs.umich.edu# follow 'build' in the bulid path.
2672638Sstever@eecs.umich.edu
2685863Snate@binkert.org# Generate absolute paths to targets so we can see where the build dir is
2695863Snate@binkert.orgif COMMAND_LINE_TARGETS:
2705863Snate@binkert.org    # Ask SCons which directory it was invoked from
271955SN/A    launch_dir = GetLaunchDir()
2725341Sstever@gmail.com    # Make targets relative to invocation directory
2735341Sstever@gmail.com    abs_targets = [ normpath(joinpath(launch_dir, str(x))) for x in \
2745863Snate@binkert.org                    COMMAND_LINE_TARGETS]
2755341Sstever@gmail.comelse:
2766121Snate@binkert.org    # Default targets are relative to root of tree
2774494Ssaidi@eecs.umich.edu    abs_targets = [ normpath(joinpath(main.root.abspath, str(x))) for x in \
2786121Snate@binkert.org                    DEFAULT_TARGETS]
2791105SN/A
2802667Sstever@eecs.umich.edu
2812667Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
2822667Sstever@eecs.umich.edu# collected targets reference.
2832667Sstever@eecs.umich.eduvariant_paths = []
2846121Snate@binkert.orgbuild_root = None
2852667Sstever@eecs.umich.edufor t in abs_targets:
2865341Sstever@gmail.com    path_dirs = t.split('/')
2875863Snate@binkert.org    try:
2885341Sstever@gmail.com        build_top = rfind(path_dirs, 'build', -2)
2895341Sstever@gmail.com    except:
2905341Sstever@gmail.com        print "Error: no non-leaf 'build' dir found on target path", t
2915863Snate@binkert.org        Exit(1)
2925341Sstever@gmail.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2935341Sstever@gmail.com    if not build_root:
2945341Sstever@gmail.com        build_root = this_build_root
2955863Snate@binkert.org    else:
2965341Sstever@gmail.com        if this_build_root != build_root:
2975341Sstever@gmail.com            print "Error: build targets not under same build root\n"\
2985341Sstever@gmail.com                  "  %s\n  %s" % (build_root, this_build_root)
2995341Sstever@gmail.com            Exit(1)
3005341Sstever@gmail.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
3015341Sstever@gmail.com    if variant_path not in variant_paths:
3025341Sstever@gmail.com        variant_paths.append(variant_path)
3035341Sstever@gmail.com
3045341Sstever@gmail.com# Make sure build_root exists (might not if this is the first build there)
3055341Sstever@gmail.comif not isdir(build_root):
3065863Snate@binkert.org    mkdir(build_root)
3075341Sstever@gmail.com
3085863Snate@binkert.orgExport('main')
3095341Sstever@gmail.com
3105863Snate@binkert.orgmain.SConsignFile(joinpath(build_root, "sconsign"))
3116121Snate@binkert.org
3126121Snate@binkert.org# Default duplicate option is to use hard links, but this messes up
3135397Ssaidi@eecs.umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
3145397Ssaidi@eecs.umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
3155341Sstever@gmail.com# (soft) links work better.
3166168Snate@binkert.orgmain.SetOption('duplicate', 'soft-copy')
3176168Snate@binkert.org
3186168Snate@binkert.org#
3195341Sstever@gmail.com# Set up global sticky variables... these are common to an entire build
3205341Sstever@gmail.com# tree (not specific to a particular build like ALPHA_SE)
3215341Sstever@gmail.com#
3225341Sstever@gmail.com
3235341Sstever@gmail.com# Variable validators & converters for global sticky variables
3245863Snate@binkert.orgdef PathListMakeAbsolute(val):
3255341Sstever@gmail.com    if not val:
3265341Sstever@gmail.com        return val
3276121Snate@binkert.org    f = lambda p: abspath(expanduser(p))
3286121Snate@binkert.org    return ':'.join(map(f, val.split(':')))
3295341Sstever@gmail.com
3306814Sgblack@eecs.umich.edudef PathListAllExist(key, val, env):
3316814Sgblack@eecs.umich.edu    if not val:
3325863Snate@binkert.org        return
3336121Snate@binkert.org    paths = val.split(':')
3345341Sstever@gmail.com    for path in paths:
3355863Snate@binkert.org        if not isdir(path):
3365341Sstever@gmail.com            raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
3376121Snate@binkert.org
3386121Snate@binkert.orgglobal_sticky_vars_file = joinpath(build_root, 'variables.global')
3396121Snate@binkert.org
3405742Snate@binkert.orgglobal_sticky_vars = Variables(global_sticky_vars_file, args=ARGUMENTS)
3415742Snate@binkert.org
3425341Sstever@gmail.comglobal_sticky_vars.AddVariables(
3435742Snate@binkert.org    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3445742Snate@binkert.org    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3455341Sstever@gmail.com    ('BATCH', 'Use batch pool for build and tests', False),
3466017Snate@binkert.org    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3476121Snate@binkert.org    ('EXTRAS', 'Add Extra directories to the compilation', '',
3486017Snate@binkert.org     PathListAllExist, PathListMakeAbsolute)
3496654Snate@binkert.org    )    
3506654Snate@binkert.org
3515871Snate@binkert.org# base help text
3526121Snate@binkert.orghelp_text = '''
3536121Snate@binkert.orgUsage: scons [scons options] [build options] [target(s)]
3546121Snate@binkert.org
3556121Snate@binkert.orgGlobal sticky options:
3563940Ssaidi@eecs.umich.edu'''
3573918Ssaidi@eecs.umich.edu
3583918Ssaidi@eecs.umich.eduhelp_text += global_sticky_vars.GenerateHelpText(main)
3591858SN/A
3606121Snate@binkert.org# Update main environment with values from ARGUMENTS & global_sticky_vars_file
3616121Snate@binkert.orgglobal_sticky_vars.Update(main)
3626121Snate@binkert.org
3636143Snate@binkert.org# Save sticky variable settings back to current variables file
3646121Snate@binkert.orgglobal_sticky_vars.Save(global_sticky_vars_file, main)
3656121Snate@binkert.org
3663940Ssaidi@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
3676121Snate@binkert.org# look for sources etc.  This list is exported as base_dir_list.
3686121Snate@binkert.orgbase_dir = main.srcdir.abspath
3696121Snate@binkert.orgif main['EXTRAS']:
3706121Snate@binkert.org    extras_dir_list = main['EXTRAS'].split(':')
3716121Snate@binkert.orgelse:
3726121Snate@binkert.org    extras_dir_list = []
3736121Snate@binkert.org
3743918Ssaidi@eecs.umich.eduExport('base_dir')
3753918Ssaidi@eecs.umich.eduExport('extras_dir_list')
3763940Ssaidi@eecs.umich.edu
3773918Ssaidi@eecs.umich.edu# the ext directory should be on the #includes path
3783918Ssaidi@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
3796157Snate@binkert.org
3806157Snate@binkert.org# M5_PLY is used by isa_parser.py to find the PLY package.
3816157Snate@binkert.orgmain.Append(ENV = { 'M5_PLY' : Dir('ext/ply').abspath })
3826157Snate@binkert.org
3835397Ssaidi@eecs.umich.eduCXX_version = read_command([main['CXX'],'--version'], exception=False)
3845397Ssaidi@eecs.umich.eduCXX_V = read_command([main['CXX'],'-V'], exception=False)
3856121Snate@binkert.org
3866121Snate@binkert.orgmain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3876121Snate@binkert.orgmain['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
3886121Snate@binkert.orgmain['ICC'] = CXX_V and CXX_V.find('Intel') >= 0
3896121Snate@binkert.orgif main['GCC'] + main['SUNCC'] + main['ICC'] > 1:
3906121Snate@binkert.org    print 'Error: How can we have two at the same time?'
3915397Ssaidi@eecs.umich.edu    Exit(1)
3921851SN/A
3931851SN/A# Set up default C++ compiler flags
3946655Snate@binkert.orgif main['GCC']:
395955SN/A    main.Append(CCFLAGS='-pipe')
3963053Sstever@eecs.umich.edu    main.Append(CCFLAGS='-fno-strict-aliasing')
3976121Snate@binkert.org    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
3983053Sstever@eecs.umich.edu    main.Append(CXXFLAGS='-Wno-deprecated')
3993053Sstever@eecs.umich.eduelif main['ICC']:
4003053Sstever@eecs.umich.edu    pass #Fix me... add warning flags once we clean up icc warnings
4013053Sstever@eecs.umich.eduelif main['SUNCC']:
4023053Sstever@eecs.umich.edu    main.Append(CCFLAGS='-Qoption ccfe')
4036654Snate@binkert.org    main.Append(CCFLAGS='-features=gcc')
4043053Sstever@eecs.umich.edu    main.Append(CCFLAGS='-features=extensions')
4054742Sstever@eecs.umich.edu    main.Append(CCFLAGS='-library=stlport4')
4064742Sstever@eecs.umich.edu    main.Append(CCFLAGS='-xar')
4073053Sstever@eecs.umich.edu    #main.Append(CCFLAGS='-instances=semiexplicit')
4083053Sstever@eecs.umich.eduelse:
4093053Sstever@eecs.umich.edu    print 'Error: Don\'t know what compiler options to use for your compiler.'
4103053Sstever@eecs.umich.edu    print '       Please fix SConstruct and src/SConscript and try again.'
4116654Snate@binkert.org    Exit(1)
4123053Sstever@eecs.umich.edu
4133053Sstever@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
4143053Sstever@eecs.umich.edumain['YACCFLAGS'] = '-d'
4153053Sstever@eecs.umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
4162667Sstever@eecs.umich.edu
4174554Sbinkertn@umich.edu# Do this after we save setting back, or else we'll tack on an
4186121Snate@binkert.org# extra 'qdo' every time we run scons.
4192667Sstever@eecs.umich.eduif main['BATCH']:
4204554Sbinkertn@umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
4214554Sbinkertn@umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
4224554Sbinkertn@umich.edu    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
4236121Snate@binkert.org    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
4244554Sbinkertn@umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
4254554Sbinkertn@umich.edu
4264554Sbinkertn@umich.eduif sys.platform == 'cygwin':
4274781Snate@binkert.org    # cygwin has some header file issues...
4284554Sbinkertn@umich.edu    main.Append(CCFLAGS=Split("-Wno-uninitialized"))
4294554Sbinkertn@umich.edu
4302667Sstever@eecs.umich.edu# Check for SWIG
4314554Sbinkertn@umich.eduif not main.has_key('SWIG'):
4324554Sbinkertn@umich.edu    print 'Error: SWIG utility not found.'
4334554Sbinkertn@umich.edu    print '       Please install (see http://www.swig.org) and retry.'
4344554Sbinkertn@umich.edu    Exit(1)
4352667Sstever@eecs.umich.edu
4364554Sbinkertn@umich.edu# Check for appropriate SWIG version
4372667Sstever@eecs.umich.eduswig_version = read_command(('swig', '-version'), exception='').split()
4384554Sbinkertn@umich.edu# First 3 words should be "SWIG Version x.y.z"
4396121Snate@binkert.orgif len(swig_version) < 3 or \
4402667Sstever@eecs.umich.edu        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
4415522Snate@binkert.org    print 'Error determining SWIG version.'
4425522Snate@binkert.org    Exit(1)
4435522Snate@binkert.org
4445522Snate@binkert.orgmin_swig_version = '1.3.28'
4455522Snate@binkert.orgif compare_versions(swig_version[2], min_swig_version) < 0:
4465522Snate@binkert.org    print 'Error: SWIG version', min_swig_version, 'or newer required.'
4475522Snate@binkert.org    print '       Installed version:', swig_version[2]
4485522Snate@binkert.org    Exit(1)
4495522Snate@binkert.org
4505522Snate@binkert.org# Set up SWIG flags & scanner
4515522Snate@binkert.orgswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
4525522Snate@binkert.orgmain.Append(SWIGFLAGS=swig_flags)
4535522Snate@binkert.org
4545522Snate@binkert.org# filter out all existing swig scanners, they mess up the dependency
4555522Snate@binkert.org# stuff for some reason
4565522Snate@binkert.orgscanners = []
4575522Snate@binkert.orgfor scanner in main['SCANNERS']:
4585522Snate@binkert.org    skeys = scanner.skeys
4595522Snate@binkert.org    if skeys == '.i':
4605522Snate@binkert.org        continue
4615522Snate@binkert.org
4625522Snate@binkert.org    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
4635522Snate@binkert.org        continue
4645522Snate@binkert.org
4655522Snate@binkert.org    scanners.append(scanner)
4665522Snate@binkert.org
4672638Sstever@eecs.umich.edu# add the new swig scanner that we like better
4682638Sstever@eecs.umich.edufrom SCons.Scanner import ClassicCPP as CPPScanner
4696121Snate@binkert.orgswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
4703716Sstever@eecs.umich.eduscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
4715522Snate@binkert.org
4725522Snate@binkert.org# replace the scanners list that has what we want
4735522Snate@binkert.orgmain['SCANNERS'] = scanners
4745522Snate@binkert.org
4755522Snate@binkert.org# Add a custom Check function to the Configure context so that we can
4765522Snate@binkert.org# figure out if the compiler adds leading underscores to global
4771858SN/A# variables.  This is needed for the autogenerated asm files that we
4785227Ssaidi@eecs.umich.edu# use for embedding the python code.
4795227Ssaidi@eecs.umich.edudef CheckLeading(context):
4805227Ssaidi@eecs.umich.edu    context.Message("Checking for leading underscore in global variables...")
4815227Ssaidi@eecs.umich.edu    # 1) Define a global variable called x from asm so the C compiler
4826654Snate@binkert.org    #    won't change the symbol at all.
4836654Snate@binkert.org    # 2) Declare that variable.
4846121Snate@binkert.org    # 3) Use the variable
4856121Snate@binkert.org    #
4866121Snate@binkert.org    # If the compiler prepends an underscore, this will successfully
4876121Snate@binkert.org    # link because the external symbol 'x' will be called '_x' which
4885227Ssaidi@eecs.umich.edu    # was defined by the asm statement.  If the compiler does not
4895227Ssaidi@eecs.umich.edu    # prepend an underscore, this will not successfully link because
4905227Ssaidi@eecs.umich.edu    # '_x' will have been defined by assembly, while the C portion of
4915204Sstever@gmail.com    # the code will be trying to use 'x'
4925204Sstever@gmail.com    ret = context.TryLink('''
4935204Sstever@gmail.com        asm(".globl _x; _x: .byte 0");
4945204Sstever@gmail.com        extern int x;
4955204Sstever@gmail.com        int main() { return x; }
4965204Sstever@gmail.com        ''', extension=".c")
4975204Sstever@gmail.com    context.env.Append(LEADING_UNDERSCORE=ret)
4985204Sstever@gmail.com    context.Result(ret)
4995204Sstever@gmail.com    return ret
5005204Sstever@gmail.com
5015204Sstever@gmail.com# Platform-specific configuration.  Note again that we assume that all
5025204Sstever@gmail.com# builds under a given build root run on the same host platform.
5035204Sstever@gmail.comconf = Configure(main,
5045204Sstever@gmail.com                 conf_dir = joinpath(build_root, '.scons_config'),
5055204Sstever@gmail.com                 log_file = joinpath(build_root, 'scons_config.log'),
5065204Sstever@gmail.com                 custom_tests = { 'CheckLeading' : CheckLeading })
5075204Sstever@gmail.com
5086121Snate@binkert.org# Check for leading underscores.  Don't really need to worry either
5095204Sstever@gmail.com# way so don't need to check the return code.
5103118Sstever@eecs.umich.educonf.CheckLeading()
5113118Sstever@eecs.umich.edu
5123118Sstever@eecs.umich.edu# Check if we should compile a 64 bit binary on Mac OS X/Darwin
5133118Sstever@eecs.umich.edutry:
5143118Sstever@eecs.umich.edu    import platform
5155863Snate@binkert.org    uname = platform.uname()
5163118Sstever@eecs.umich.edu    if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
5175863Snate@binkert.org        if int(read_command('sysctl -n hw.cpu64bit_capable')[0]):
5183118Sstever@eecs.umich.edu            main.Append(CCFLAGS='-arch x86_64')
5195863Snate@binkert.org            main.Append(CFLAGS='-arch x86_64')
5205863Snate@binkert.org            main.Append(LINKFLAGS='-arch x86_64')
5215863Snate@binkert.org            main.Append(ASFLAGS='-arch x86_64')
5225863Snate@binkert.orgexcept:
5235863Snate@binkert.org    pass
5245863Snate@binkert.org
5255863Snate@binkert.org# Recent versions of scons substitute a "Null" object for Configure()
5265863Snate@binkert.org# when configuration isn't necessary, e.g., if the "--help" option is
5276003Snate@binkert.org# present.  Unfortuantely this Null object always returns false,
5285863Snate@binkert.org# breaking all our configuration checks.  We replace it with our own
5295863Snate@binkert.org# more optimistic null object that returns True instead.
5305863Snate@binkert.orgif not conf:
5316120Snate@binkert.org    def NullCheck(*args, **kwargs):
5325863Snate@binkert.org        return True
5335863Snate@binkert.org
5345863Snate@binkert.org    class NullConf:
5356120Snate@binkert.org        def __init__(self, env):
5366120Snate@binkert.org            self.env = env
5375863Snate@binkert.org        def Finish(self):
5385863Snate@binkert.org            return self.env
5396120Snate@binkert.org        def __getattr__(self, mname):
5405863Snate@binkert.org            return NullCheck
5416121Snate@binkert.org
5426121Snate@binkert.org    conf = NullConf(main)
5435863Snate@binkert.org
5445863Snate@binkert.org# Find Python include and library directories for embedding the
5453118Sstever@eecs.umich.edu# interpreter.  For consistency, we will use the same Python
5465863Snate@binkert.org# installation used to run scons (and thus this script).  If you want
5473118Sstever@eecs.umich.edu# to link in an alternate version, see above for instructions on how
5483118Sstever@eecs.umich.edu# to invoke scons with a different copy of the Python interpreter.
5495863Snate@binkert.orgfrom distutils import sysconfig
5505863Snate@binkert.org
5515863Snate@binkert.orgpy_getvar = sysconfig.get_config_var
5525863Snate@binkert.org
5533118Sstever@eecs.umich.edupy_version = 'python' + py_getvar('VERSION')
5543483Ssaidi@eecs.umich.edu
5553494Ssaidi@eecs.umich.edupy_general_include = sysconfig.get_python_inc()
5563494Ssaidi@eecs.umich.edupy_platform_include = sysconfig.get_python_inc(plat_specific=True)
5573483Ssaidi@eecs.umich.edupy_includes = [ py_general_include ]
5583483Ssaidi@eecs.umich.eduif py_platform_include != py_general_include:
5593483Ssaidi@eecs.umich.edu    py_includes.append(py_platform_include)
5603053Sstever@eecs.umich.edu
5613053Sstever@eecs.umich.edupy_lib_path = [ py_getvar('LIBDIR') ]
5623918Ssaidi@eecs.umich.edu# add the prefix/lib/pythonX.Y/config dir, but only if there is no
5633053Sstever@eecs.umich.edu# shared library in prefix/lib/.
5643053Sstever@eecs.umich.eduif not py_getvar('Py_ENABLE_SHARED'):
5653053Sstever@eecs.umich.edu    py_lib_path.append(py_getvar('LIBPL'))
5663053Sstever@eecs.umich.edu
5673053Sstever@eecs.umich.edupy_libs = []
5681858SN/Afor lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
5691858SN/A    assert lib.startswith('-l')
5701858SN/A    lib = lib[2:]   
5711858SN/A    if lib not in py_libs:
5721858SN/A        py_libs.append(lib)
5731858SN/Apy_libs.append(py_version)
5745863Snate@binkert.org
5755863Snate@binkert.orgmain.Append(CPPPATH=py_includes)
5761859SN/Amain.Append(LIBPATH=py_lib_path)
5775863Snate@binkert.org
5781858SN/A# verify that this stuff works
5795863Snate@binkert.orgif not conf.CheckHeader('Python.h', '<>'):
5801858SN/A    print "Error: can't find Python.h header in", py_includes
5811859SN/A    Exit(1)
5821859SN/A
5836654Snate@binkert.orgfor lib in py_libs:
5843053Sstever@eecs.umich.edu    if not conf.CheckLib(lib):
5856654Snate@binkert.org        print "Error: can't find library %s required by python" % lib
5863053Sstever@eecs.umich.edu        Exit(1)
5873053Sstever@eecs.umich.edu
5881859SN/A# On Solaris you need to use libsocket for socket ops
5891859SN/Aif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
5901859SN/A   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
5911859SN/A       print "Can't find library with socket calls (e.g. accept())"
5921859SN/A       Exit(1)
5931859SN/A
5941859SN/A# Check for zlib.  If the check passes, libz will be automatically
5951859SN/A# added to the LIBS environment variable.
5961862SN/Aif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
5971859SN/A    print 'Error: did not find needed zlib compression library '\
5981859SN/A          'and/or zlib.h header file.'
5991859SN/A    print '       Please install zlib and try again.'
6005863Snate@binkert.org    Exit(1)
6015863Snate@binkert.org
6025863Snate@binkert.org# Check for <fenv.h> (C99 FP environment control)
6035863Snate@binkert.orghave_fenv = conf.CheckHeader('fenv.h', '<>')
6046121Snate@binkert.orgif not have_fenv:
6051858SN/A    print "Warning: Header file <fenv.h> not found."
6065863Snate@binkert.org    print "         This host has no IEEE FP rounding mode control."
6075863Snate@binkert.org
6085863Snate@binkert.org######################################################################
6095863Snate@binkert.org#
6105863Snate@binkert.org# Check for mysql.
6112139SN/A#
6124202Sbinkertn@umich.edumysql_config = WhereIs('mysql_config')
6134202Sbinkertn@umich.eduhave_mysql = bool(mysql_config)
6142139SN/A
6152155SN/A# Check MySQL version.
6164202Sbinkertn@umich.eduif have_mysql:
6174202Sbinkertn@umich.edu    mysql_version = read_command(mysql_config + ' --version')
6184202Sbinkertn@umich.edu    min_mysql_version = '4.1'
6192155SN/A    if compare_versions(mysql_version, min_mysql_version) < 0:
6205863Snate@binkert.org        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
6211869SN/A        print '         Version', mysql_version, 'detected.'
6221869SN/A        have_mysql = False
6235863Snate@binkert.org
6245863Snate@binkert.org# Set up mysql_config commands.
6254202Sbinkertn@umich.eduif have_mysql:
6266108Snate@binkert.org    mysql_config_include = mysql_config + ' --include'
6276108Snate@binkert.org    if os.system(mysql_config_include + ' > /dev/null') != 0:
6286108Snate@binkert.org        # older mysql_config versions don't support --include, use
6296108Snate@binkert.org        # --cflags instead
6305863Snate@binkert.org        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
6315863Snate@binkert.org    # This seems to work in all versions
6325863Snate@binkert.org    mysql_config_libs = mysql_config + ' --libs'
6334202Sbinkertn@umich.edu
6344202Sbinkertn@umich.edu######################################################################
6355863Snate@binkert.org#
6365742Snate@binkert.org# Finish the configuration
6375742Snate@binkert.org#
6385341Sstever@gmail.commain = conf.Finish()
6395342Sstever@gmail.com
6405342Sstever@gmail.com######################################################################
6414202Sbinkertn@umich.edu#
6424202Sbinkertn@umich.edu# Collect all non-global variables
6434202Sbinkertn@umich.edu#
6444202Sbinkertn@umich.edu
6454202Sbinkertn@umich.edu# Define the universe of supported ISAs
6465863Snate@binkert.orgall_isa_list = [ ]
6475863Snate@binkert.orgExport('all_isa_list')
6485863Snate@binkert.org
6495863Snate@binkert.org# Define the universe of supported CPU models
6505863Snate@binkert.orgall_cpu_list = [ ]
6515863Snate@binkert.orgdefault_cpus = [ ]
6525863Snate@binkert.orgExport('all_cpu_list', 'default_cpus')
6535863Snate@binkert.org
6545863Snate@binkert.org# Sticky variables get saved in the variables file so they persist from
6555863Snate@binkert.org# one invocation to the next (unless overridden, in which case the new
6565863Snate@binkert.org# value becomes sticky).
6575863Snate@binkert.orgsticky_vars = Variables(args=ARGUMENTS)
6585863Snate@binkert.orgExport('sticky_vars')
6595863Snate@binkert.org
6605863Snate@binkert.org# Sticky variables that should be exported
6615863Snate@binkert.orgexport_vars = []
6625863Snate@binkert.orgExport('export_vars')
6635863Snate@binkert.org
6645863Snate@binkert.org# Non-sticky variables only apply to the current build.
6655863Snate@binkert.orgnonsticky_vars = Variables(args=ARGUMENTS)
6665952Ssaidi@eecs.umich.eduExport('nonsticky_vars')
6671869SN/A
6681858SN/A# Walk the tree and execute all SConsopts scripts that wil add to the
6695863Snate@binkert.org# above variables
6705863Snate@binkert.orgfor bdir in [ base_dir ] + extras_dir_list:
6711869SN/A    for root, dirs, files in os.walk(bdir):
6721858SN/A        if 'SConsopts' in files:
6735863Snate@binkert.org            print "Reading", joinpath(root, 'SConsopts')
6746108Snate@binkert.org            SConscript(joinpath(root, 'SConsopts'))
6756108Snate@binkert.org
6766108Snate@binkert.orgall_isa_list.sort()
6771858SN/Aall_cpu_list.sort()
678955SN/Adefault_cpus.sort()
679955SN/A
6801869SN/Asticky_vars.AddVariables(
6811869SN/A    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
6821869SN/A    BoolVariable('FULL_SYSTEM', 'Full-system support', False),
6831869SN/A    ListVariable('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
6841869SN/A    BoolVariable('NO_FAST_ALLOC', 'Disable fast object allocator', False),
6855863Snate@binkert.org    BoolVariable('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
6865863Snate@binkert.org                 False),
6875863Snate@binkert.org    BoolVariable('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
6881869SN/A                 False),
6895863Snate@binkert.org    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
6901869SN/A                 False),
6915863Snate@binkert.org    BoolVariable('SS_COMPATIBLE_FP',
6921869SN/A                 'Make floating-point results compatible with SimpleScalar',
6931869SN/A                 False),
6941869SN/A    BoolVariable('USE_SSE2',
6951869SN/A                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
6961869SN/A                 False),
6975863Snate@binkert.org    BoolVariable('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
6985863Snate@binkert.org    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
6991869SN/A    BoolVariable('USE_CHECKER', 'Use checker for detailed CPU models', False),
7001869SN/A    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
7011869SN/A    )
7021869SN/A
7031869SN/Anonsticky_vars.AddVariables(
7041869SN/A    BoolVariable('update_ref', 'Update test reference outputs', False)
7051869SN/A    )
7065863Snate@binkert.org
7075863Snate@binkert.org# These variables get exported to #defines in config/*.hh (see src/SConscript).
7081869SN/Aexport_vars += ['FULL_SYSTEM', 'USE_FENV', 'USE_MYSQL',
7095863Snate@binkert.org                'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', 'FAST_ALLOC_STATS',
7105863Snate@binkert.org                'SS_COMPATIBLE_FP', 'USE_CHECKER', 'TARGET_ISA', 'CP_ANNOTATE']
7113356Sbinkertn@umich.edu
7123356Sbinkertn@umich.edu###################################################
7133356Sbinkertn@umich.edu#
7143356Sbinkertn@umich.edu# Define a SCons builder for configuration flag headers.
7153356Sbinkertn@umich.edu#
7164781Snate@binkert.org###################################################
7175863Snate@binkert.org
7185863Snate@binkert.org# This function generates a config header file that #defines the
7191869SN/A# variable symbol to the current variable setting (0 or 1).  The source
7201869SN/A# operands are the name of the variable and a Value node containing the
7211869SN/A# value of the variable.
7226121Snate@binkert.orgdef build_config_file(target, source, env):
7231869SN/A    (variable, value) = [s.get_contents() for s in source]
7242638Sstever@eecs.umich.edu    f = file(str(target[0]), 'w')
7256121Snate@binkert.org    print >> f, '#define', variable, value
7266121Snate@binkert.org    f.close()
7272638Sstever@eecs.umich.edu    return None
7285749Scws3k@cs.virginia.edu
7296121Snate@binkert.org# Generate the message to be printed when building the config file.
7306121Snate@binkert.orgdef build_config_file_string(target, source, env):
7315749Scws3k@cs.virginia.edu    (variable, value) = [s.get_contents() for s in source]
7321869SN/A    return "Defining %s as %s in %s." % (variable, value, target[0])
7331869SN/A
7343546Sgblack@eecs.umich.edu# Combine the two functions into a scons Action object.
7353546Sgblack@eecs.umich.educonfig_action = Action(build_config_file, build_config_file_string)
7363546Sgblack@eecs.umich.edu
7373546Sgblack@eecs.umich.edu# The emitter munges the source & target node lists to reflect what
7386121Snate@binkert.org# we're really doing.
7395863Snate@binkert.orgdef config_emitter(target, source, env):
7403546Sgblack@eecs.umich.edu    # extract variable name from Builder arg
7413546Sgblack@eecs.umich.edu    variable = str(target[0])
7423546Sgblack@eecs.umich.edu    # True target is config header file
7433546Sgblack@eecs.umich.edu    target = joinpath('config', variable.lower() + '.hh')
7444781Snate@binkert.org    val = env[variable]
7454781Snate@binkert.org    if isinstance(val, bool):
7466658Snate@binkert.org        # Force value to 0/1
7476658Snate@binkert.org        val = int(val)
7484781Snate@binkert.org    elif isinstance(val, str):
7493546Sgblack@eecs.umich.edu        val = '"' + val + '"'
7503546Sgblack@eecs.umich.edu
7513546Sgblack@eecs.umich.edu    # Sources are variable name & value (packaged in SCons Value nodes)
7524781Snate@binkert.org    return ([target], [Value(variable), Value(val)])
7533546Sgblack@eecs.umich.edu
7543546Sgblack@eecs.umich.educonfig_builder = Builder(emitter = config_emitter, action = config_action)
7553546Sgblack@eecs.umich.edu
7563546Sgblack@eecs.umich.edumain.Append(BUILDERS = { 'ConfigFile' : config_builder })
7573546Sgblack@eecs.umich.edu
7583546Sgblack@eecs.umich.edu# libelf build is shared across all configs in the build root.
7593546Sgblack@eecs.umich.edumain.SConscript('ext/libelf/SConscript',
7603546Sgblack@eecs.umich.edu                variant_dir = joinpath(build_root, 'libelf'))
7613546Sgblack@eecs.umich.edu
7623546Sgblack@eecs.umich.edu# gzstream build is shared across all configs in the build root.
7634202Sbinkertn@umich.edumain.SConscript('ext/gzstream/SConscript',
7643546Sgblack@eecs.umich.edu                variant_dir = joinpath(build_root, 'gzstream'))
7653546Sgblack@eecs.umich.edu
7663546Sgblack@eecs.umich.edu###################################################
767955SN/A#
768955SN/A# This function is used to set up a directory with switching headers
769955SN/A#
770955SN/A###################################################
7715863Snate@binkert.org
7725863Snate@binkert.orgmain['ALL_ISA_LIST'] = all_isa_list
7735343Sstever@gmail.comdef make_switching_dir(dname, switch_headers, env):
7745343Sstever@gmail.com    # Generate the header.  target[0] is the full path of the output
7756121Snate@binkert.org    # header to generate.  'source' is a dummy variable, since we get the
7765863Snate@binkert.org    # list of ISAs from env['ALL_ISA_LIST'].
7774773Snate@binkert.org    def gen_switch_hdr(target, source, env):
7785863Snate@binkert.org        fname = str(target[0])
7792632Sstever@eecs.umich.edu        bname = basename(fname)
7805863Snate@binkert.org        f = open(fname, 'w')
7812023SN/A        f.write('#include "arch/isa_specific.hh"\n')
7825863Snate@binkert.org        cond = '#if'
7835863Snate@binkert.org        for isa in all_isa_list:
7845863Snate@binkert.org            f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
7855863Snate@binkert.org                    % (cond, isa.upper(), dname, isa, bname))
7865863Snate@binkert.org            cond = '#elif'
7875863Snate@binkert.org        f.write('#else\n#error "THE_ISA not set"\n#endif\n')
7885863Snate@binkert.org        f.close()
7895863Snate@binkert.org        return 0
7905863Snate@binkert.org
7912632Sstever@eecs.umich.edu    # String to print when generating header
7925863Snate@binkert.org    def gen_switch_hdr_string(target, source, env):
7932023SN/A        return "Generating switch header " + str(target[0])
7942632Sstever@eecs.umich.edu
7955863Snate@binkert.org    # Build SCons Action object. 'varlist' specifies env vars that this
7965342Sstever@gmail.com    # action depends on; when env['ALL_ISA_LIST'] changes these actions
7975863Snate@binkert.org    # should get re-executed.
7982632Sstever@eecs.umich.edu    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
7995863Snate@binkert.org                               varlist=['ALL_ISA_LIST'])
8005863Snate@binkert.org
8012632Sstever@eecs.umich.edu    # Instantiate actions for each header
8025863Snate@binkert.org    for hdr in switch_headers:
8035863Snate@binkert.org        env.Command(hdr, [], switch_hdr_action)
8045863Snate@binkert.orgExport('make_switching_dir')
8055863Snate@binkert.org
8065863Snate@binkert.org###################################################
8075863Snate@binkert.org#
8082632Sstever@eecs.umich.edu# Define build environments for selected configurations.
8095863Snate@binkert.org#
8105863Snate@binkert.org###################################################
8112632Sstever@eecs.umich.edu
8121888SN/Afor variant_path in variant_paths:
8135863Snate@binkert.org    print "Building in", variant_path
8145863Snate@binkert.org
8155863Snate@binkert.org    # Make a copy of the build-root environment to use for this config.
8161858SN/A    env = main.Clone()
8175863Snate@binkert.org    env['BUILDDIR'] = variant_path
8185863Snate@binkert.org
8195863Snate@binkert.org    # variant_dir is the tail component of build path, and is used to
8205863Snate@binkert.org    # determine the build parameters (e.g., 'ALPHA_SE')
8212598SN/A    (build_root, variant_dir) = splitpath(variant_path)
8225863Snate@binkert.org
8231858SN/A    # Set env variables according to the build directory config.
8241858SN/A    sticky_vars.files = []
8251858SN/A    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
8265863Snate@binkert.org    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
8271858SN/A    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
8281858SN/A    current_vars_file = joinpath(build_root, 'variables', variant_dir)
8291858SN/A    if isfile(current_vars_file):
8305863Snate@binkert.org        sticky_vars.files.append(current_vars_file)
8311871SN/A        print "Using saved variables file %s" % current_vars_file
8321858SN/A    else:
8331858SN/A        # Build dir-specific variables file doesn't exist.
8341858SN/A
8351858SN/A        # Make sure the directory is there so we can create it later
8361858SN/A        opt_dir = dirname(current_vars_file)
8371858SN/A        if not isdir(opt_dir):
8381858SN/A            mkdir(opt_dir)
8395863Snate@binkert.org
8401858SN/A        # Get default build variables from source tree.  Variables are
8411858SN/A        # normally determined by name of $VARIANT_DIR, but can be
8425863Snate@binkert.org        # overriden by 'default=' arg on command line.
8431859SN/A        default_vars_file = joinpath('build_opts',
8441859SN/A                                     ARGUMENTS.get('default', variant_dir))
8451869SN/A        if isfile(default_vars_file):
8465863Snate@binkert.org            sticky_vars.files.append(default_vars_file)
8475863Snate@binkert.org            print "Variables file %s not found,\n  using defaults in %s" \
8481869SN/A                  % (current_vars_file, default_vars_file)
8491965SN/A        else:
8501965SN/A            print "Error: cannot find variables file %s or %s" \
8511965SN/A                  % (current_vars_file, default_vars_file)
8522761Sstever@eecs.umich.edu            Exit(1)
8535863Snate@binkert.org
8541869SN/A    # Apply current variable settings to env
8555863Snate@binkert.org    sticky_vars.Update(env)
8562667Sstever@eecs.umich.edu    nonsticky_vars.Update(env)
8571869SN/A
8581869SN/A    help_text += "\nSticky variables for %s:\n" % variant_dir \
8592929Sktlim@umich.edu                 + sticky_vars.GenerateHelpText(env) \
8602929Sktlim@umich.edu                 + "\nNon-sticky variables for %s:\n" % variant_dir \
8615863Snate@binkert.org                 + nonsticky_vars.GenerateHelpText(env)
8622929Sktlim@umich.edu
863955SN/A    # Process variable settings.
8642598SN/A
865    if not have_fenv and env['USE_FENV']:
866        print "Warning: <fenv.h> not available; " \
867              "forcing USE_FENV to False in", variant_dir + "."
868        env['USE_FENV'] = False
869
870    if not env['USE_FENV']:
871        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
872        print "         FP results may deviate slightly from other platforms."
873
874    if env['EFENCE']:
875        env.Append(LIBS=['efence'])
876
877    if env['USE_MYSQL']:
878        if not have_mysql:
879            print "Warning: MySQL not available; " \
880                  "forcing USE_MYSQL to False in", variant_dir + "."
881            env['USE_MYSQL'] = False
882        else:
883            print "Compiling in", variant_dir, "with MySQL support."
884            env.ParseConfig(mysql_config_libs)
885            env.ParseConfig(mysql_config_include)
886
887    # Save sticky variable settings back to current variables file
888    sticky_vars.Save(current_vars_file, env)
889
890    if env['USE_SSE2']:
891        env.Append(CCFLAGS='-msse2')
892
893    # The src/SConscript file sets up the build rules in 'env' according
894    # to the configured variables.  It returns a list of environments,
895    # one for each variant build (debug, opt, etc.)
896    envList = SConscript('src/SConscript', variant_dir = variant_path,
897                         exports = 'env')
898
899    # Set up the regression tests for each build.
900    for e in envList:
901        SConscript('tests/SConscript',
902                   variant_dir = joinpath(variant_path, 'tests', e.Label),
903                   exports = { 'env' : e }, duplicate = False)
904
905Help(help_text)
906