SConstruct revision 6168
1955SN/A# -*- mode:python -*-
2955SN/A
31762SN/A# Copyright (c) 2009 The Hewlett-Packard Development Company
4955SN/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
282665Ssaidi@eecs.umich.edu# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
292665Ssaidi@eecs.umich.edu#
30955SN/A# Authors: Steve Reinhardt
31955SN/A#          Nathan Binkert
32955SN/A
33955SN/A###################################################
34955SN/A#
352632Sstever@eecs.umich.edu# SCons top-level build description (SConstruct) file.
362632Sstever@eecs.umich.edu#
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>'
39955SN/A# to build some other configuration (e.g., 'build/ALPHA_FS/m5.opt' for
402632Sstever@eecs.umich.edu# the optimized full-system version).
412632Sstever@eecs.umich.edu#
422761Sstever@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
442632Sstever@eecs.umich.edu# expects that all configs under the same build directory are being
452632Sstever@eecs.umich.edu# built for the same host system.
462761Sstever@eecs.umich.edu#
472761Sstever@eecs.umich.edu# Examples:
482761Sstever@eecs.umich.edu#
492632Sstever@eecs.umich.edu#   The following two commands are equivalent.  The '-u' option tells
502632Sstever@eecs.umich.edu#   scons to search up the directory tree for this SConstruct file.
512761Sstever@eecs.umich.edu#   % cd <path-to-src>/m5 ; scons build/ALPHA_FS/m5.debug
522761Sstever@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
562632Sstever@eecs.umich.edu#   scons to chdir to the specified directory to find this SConstruct
572632Sstever@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
63955SN/A# file), you can use 'scons -h' to print all the M5-specific build
64955SN/A# options as well.
65955SN/A#
66955SN/A###################################################
67955SN/A
683918Ssaidi@eecs.umich.edu# Check for recent-enough Python and SCons versions.
694202Sbinkertn@umich.edutry:
704678Snate@binkert.org    # Really old versions of scons only take two options for the
71955SN/A    # function, so check once without the revision and once with the
722656Sstever@eecs.umich.edu    # revision, the first instance will fail for stuff other than
732656Sstever@eecs.umich.edu    # 0.98, and the second will fail for 0.98.0
742656Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98)
752656Sstever@eecs.umich.edu    EnsureSConsVersion(0, 98, 1)
762656Sstever@eecs.umich.eduexcept SystemExit, e:
772656Sstever@eecs.umich.edu    print """
782656Sstever@eecs.umich.eduFor more details, see:
792653Sstever@eecs.umich.edu    http://m5sim.org/wiki/index.php/Compiling_M5
802653Sstever@eecs.umich.edu"""
812653Sstever@eecs.umich.edu    raise
822653Sstever@eecs.umich.edu
832653Sstever@eecs.umich.edu# We ensure the python version early because we have stuff that
842653Sstever@eecs.umich.edu# requires python 2.4
852653Sstever@eecs.umich.edutry:
862653Sstever@eecs.umich.edu    EnsurePythonVersion(2, 4)
872653Sstever@eecs.umich.eduexcept SystemExit, e:
882653Sstever@eecs.umich.edu    print """
894781Snate@binkert.orgYou can use a non-default installation of the Python interpreter by
901852SN/Aeither (1) rearranging your PATH so that scons finds the non-default
91955SN/A'python' first or (2) explicitly invoking an alternative interpreter
92955SN/Aon the scons script.
93955SN/A
943717Sstever@eecs.umich.eduFor more details, see:
953716Sstever@eecs.umich.edu    http://m5sim.org/wiki/index.php/Using_a_non-default_Python_installation
96955SN/A"""
971533SN/A    raise
983716Sstever@eecs.umich.edu
991533SN/Aimport os
1004678Snate@binkert.orgimport re
1014678Snate@binkert.orgimport subprocess
1024678Snate@binkert.orgimport sys
1034678Snate@binkert.org
1044678Snate@binkert.orgfrom os import mkdir, environ
1054678Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1064678Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1074678Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1084678Snate@binkert.org
1094678Snate@binkert.orgimport SCons
1104678Snate@binkert.orgimport SCons.Node
1114678Snate@binkert.org
1124678Snate@binkert.orgdef read_command(cmd, **kwargs):
1134678Snate@binkert.org    """run the command cmd, read the results and return them
1144678Snate@binkert.org    this is sorta like `cmd` in shell"""
1154678Snate@binkert.org    from subprocess import Popen, PIPE, STDOUT
1164678Snate@binkert.org
1174678Snate@binkert.org    if isinstance(cmd, str):
1184678Snate@binkert.org        cmd = cmd.split()
1194678Snate@binkert.org
1204678Snate@binkert.org    no_exception = 'exception' in kwargs
1214973Ssaidi@eecs.umich.edu    exception = kwargs.pop('exception', None)
1224678Snate@binkert.org    
1234678Snate@binkert.org    kwargs.setdefault('shell', False)
1244678Snate@binkert.org    kwargs.setdefault('stdout', PIPE)
1254678Snate@binkert.org    kwargs.setdefault('stderr', STDOUT)
1264678Snate@binkert.org    kwargs.setdefault('close_fds', True)
1274678Snate@binkert.org    try:
128955SN/A        subp = Popen(cmd, **kwargs)
129955SN/A    except Exception, e:
1302632Sstever@eecs.umich.edu        if no_exception:
1312632Sstever@eecs.umich.edu            return exception
132955SN/A        raise
133955SN/A
134955SN/A    return subp.communicate()[0]
135955SN/A
1362632Sstever@eecs.umich.edu# helper function: compare arrays or strings of version numbers.
137955SN/A# E.g., compare_version((1,3,25), (1,4,1)')
1382632Sstever@eecs.umich.edu# returns -1, 0, 1 if v1 is <, ==, > v2
1392632Sstever@eecs.umich.edudef compare_versions(v1, v2):
1402632Sstever@eecs.umich.edu    def make_version_list(v):
1412632Sstever@eecs.umich.edu        if isinstance(v, (list,tuple)):
1422632Sstever@eecs.umich.edu            return v
1432632Sstever@eecs.umich.edu        elif isinstance(v, str):
1442632Sstever@eecs.umich.edu            return map(lambda x: int(re.match('\d+', x).group()), v.split('.'))
1453053Sstever@eecs.umich.edu        else:
1463053Sstever@eecs.umich.edu            raise TypeError
1473053Sstever@eecs.umich.edu
1483053Sstever@eecs.umich.edu    v1 = make_version_list(v1)
1493053Sstever@eecs.umich.edu    v2 = make_version_list(v2)
1503053Sstever@eecs.umich.edu    # Compare corresponding elements of lists
1513053Sstever@eecs.umich.edu    for n1,n2 in zip(v1, v2):
1523053Sstever@eecs.umich.edu        if n1 < n2: return -1
1533053Sstever@eecs.umich.edu        if n1 > n2: return  1
1543053Sstever@eecs.umich.edu    # all corresponding values are equal... see if one has extra values
1553053Sstever@eecs.umich.edu    if len(v1) < len(v2): return -1
1563053Sstever@eecs.umich.edu    if len(v1) > len(v2): return  1
1573053Sstever@eecs.umich.edu    return 0
1583053Sstever@eecs.umich.edu
1593053Sstever@eecs.umich.edu########################################################################
1603053Sstever@eecs.umich.edu#
1612632Sstever@eecs.umich.edu# Set up the main build environment.
1622632Sstever@eecs.umich.edu#
1632632Sstever@eecs.umich.edu########################################################################
1642632Sstever@eecs.umich.eduuse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH', 'PATH',
1652632Sstever@eecs.umich.edu                 'RANLIB' ])
1662632Sstever@eecs.umich.edu
1673718Sstever@eecs.umich.eduuse_env = {}
1683718Sstever@eecs.umich.edufor key,val in os.environ.iteritems():
1693718Sstever@eecs.umich.edu    if key in use_vars or key.startswith("M5"):
1703718Sstever@eecs.umich.edu        use_env[key] = val
1713718Sstever@eecs.umich.edu
1723718Sstever@eecs.umich.edumain = Environment(ENV=use_env)
1733718Sstever@eecs.umich.edumain.root = Dir(".")         # The current directory (where this file lives).
1743718Sstever@eecs.umich.edumain.srcdir = Dir("src")     # The source directory
1753718Sstever@eecs.umich.edu
1763718Sstever@eecs.umich.edu########################################################################
1773718Sstever@eecs.umich.edu#
1783718Sstever@eecs.umich.edu# Mercurial Stuff.
1793718Sstever@eecs.umich.edu#
1802634Sstever@eecs.umich.edu# If the M5 directory is a mercurial repository, we should do some
1812634Sstever@eecs.umich.edu# extra things.
1822632Sstever@eecs.umich.edu#
1832638Sstever@eecs.umich.edu########################################################################
1842632Sstever@eecs.umich.edu
1852632Sstever@eecs.umich.eduhgdir = main.root.Dir(".hg")
1862632Sstever@eecs.umich.edu
1872632Sstever@eecs.umich.edumercurial_style_message = """
1882632Sstever@eecs.umich.eduYou're missing the M5 style hook.
1892632Sstever@eecs.umich.eduPlease install the hook so we can ensure that all code fits a common style.
1901858SN/A
1913716Sstever@eecs.umich.eduAll you'd need to do is add the following lines to your repository .hg/hgrc
1922638Sstever@eecs.umich.eduor your personal .hgrc
1932638Sstever@eecs.umich.edu----------------
1942638Sstever@eecs.umich.edu
1952638Sstever@eecs.umich.edu[extensions]
1962638Sstever@eecs.umich.edustyle = %s/util/style.py
1972638Sstever@eecs.umich.edu
1982638Sstever@eecs.umich.edu[hooks]
1993716Sstever@eecs.umich.edupretxncommit.style = python:style.check_whitespace
2002634Sstever@eecs.umich.edu""" % (main.root)
2012634Sstever@eecs.umich.edu
202955SN/Amercurial_bin_not_found = """
203955SN/AMercurial binary cannot be found, unfortunately this means that we
204955SN/Acannot easily determine the version of M5 that you are running and
205955SN/Athis makes error messages more difficult to collect.  Please consider
206955SN/Ainstalling mercurial if you choose to post an error message
207955SN/A"""
208955SN/A
209955SN/Amercurial_lib_not_found = """
2101858SN/AMercurial libraries cannot be found, ignoring style hook
2111858SN/AIf you are actually a M5 developer, please fix this and
2122632Sstever@eecs.umich.edurun the style hook. It is important.
213955SN/A"""
2144781Snate@binkert.org
2153643Ssaidi@eecs.umich.eduhg_info = "Unknown"
2163643Ssaidi@eecs.umich.eduif hgdir.exists():
2173643Ssaidi@eecs.umich.edu    # 1) Grab repository revision if we know it.
2183643Ssaidi@eecs.umich.edu    cmd = "hg id -n -i -t -b"
2193643Ssaidi@eecs.umich.edu    try:
2203643Ssaidi@eecs.umich.edu        hg_info = read_command(cmd, cwd=main.root.abspath).strip()
2213643Ssaidi@eecs.umich.edu    except OSError:
2224494Ssaidi@eecs.umich.edu        print mercurial_bin_not_found
2234494Ssaidi@eecs.umich.edu
2243716Sstever@eecs.umich.edu    # 2) Ensure that the style hook is in place.
2251105SN/A    try:
2262667Sstever@eecs.umich.edu        ui = None
2272667Sstever@eecs.umich.edu        if ARGUMENTS.get('IGNORE_STYLE') != 'True':
2282667Sstever@eecs.umich.edu            from mercurial import ui
2292667Sstever@eecs.umich.edu            ui = ui.ui()
2302667Sstever@eecs.umich.edu    except ImportError:
2312667Sstever@eecs.umich.edu        print mercurial_lib_not_found
2321869SN/A
2331869SN/A    if ui is not None:
2341869SN/A        ui.readconfig(hgdir.File('hgrc').abspath)
2351869SN/A        style_hook = ui.config('hooks', 'pretxncommit.style', None)
2361869SN/A
2371065SN/A        if not style_hook:
2382632Sstever@eecs.umich.edu            print mercurial_style_message
2395199Sstever@gmail.com            sys.exit(1)
2403918Ssaidi@eecs.umich.eduelse:
2413918Ssaidi@eecs.umich.edu    print ".hg directory not found"
2423940Ssaidi@eecs.umich.edu
2434781Snate@binkert.orgmain['HG_INFO'] = hg_info
2444781Snate@binkert.org
2453918Ssaidi@eecs.umich.edu###################################################
2464781Snate@binkert.org#
2474781Snate@binkert.org# Figure out which configurations to set up based on the path(s) of
2483918Ssaidi@eecs.umich.edu# the target(s).
2494781Snate@binkert.org#
2504781Snate@binkert.org###################################################
2513940Ssaidi@eecs.umich.edu
2523942Ssaidi@eecs.umich.edu# Find default configuration & binary.
2533940Ssaidi@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
2543918Ssaidi@eecs.umich.edu
2553918Ssaidi@eecs.umich.edu# helper function: find last occurrence of element in list
256955SN/Adef rfind(l, elt, offs = -1):
2571858SN/A    for i in range(len(l)+offs, 0, -1):
2583918Ssaidi@eecs.umich.edu        if l[i] == elt:
2593918Ssaidi@eecs.umich.edu            return i
2603918Ssaidi@eecs.umich.edu    raise ValueError, "element not found"
2613918Ssaidi@eecs.umich.edu
2623940Ssaidi@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
2633940Ssaidi@eecs.umich.edu# directory below this will determine the build parameters.  For
2643918Ssaidi@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2653918Ssaidi@eecs.umich.edu# recognize that ALPHA_SE specifies the configuration because it
2663918Ssaidi@eecs.umich.edu# follow 'build' in the bulid path.
2673918Ssaidi@eecs.umich.edu
2683918Ssaidi@eecs.umich.edu# Generate absolute paths to targets so we can see where the build dir is
2693918Ssaidi@eecs.umich.eduif COMMAND_LINE_TARGETS:
2703918Ssaidi@eecs.umich.edu    # Ask SCons which directory it was invoked from
2713918Ssaidi@eecs.umich.edu    launch_dir = GetLaunchDir()
2723918Ssaidi@eecs.umich.edu    # Make targets relative to invocation directory
2733940Ssaidi@eecs.umich.edu    abs_targets = [ normpath(joinpath(launch_dir, str(x))) for x in \
2743918Ssaidi@eecs.umich.edu                    COMMAND_LINE_TARGETS]
2753918Ssaidi@eecs.umich.eduelse:
2761851SN/A    # Default targets are relative to root of tree
2771851SN/A    abs_targets = [ normpath(joinpath(main.root.abspath, str(x))) for x in \
2781858SN/A                    DEFAULT_TARGETS]
2795200Sstever@gmail.com
280955SN/A
2813053Sstever@eecs.umich.edu# Generate a list of the unique build roots and configs that the
2823053Sstever@eecs.umich.edu# collected targets reference.
2833053Sstever@eecs.umich.eduvariant_paths = []
2843053Sstever@eecs.umich.edubuild_root = None
2853053Sstever@eecs.umich.edufor t in abs_targets:
2863053Sstever@eecs.umich.edu    path_dirs = t.split('/')
2873053Sstever@eecs.umich.edu    try:
2883053Sstever@eecs.umich.edu        build_top = rfind(path_dirs, 'build', -2)
2893053Sstever@eecs.umich.edu    except:
2904742Sstever@eecs.umich.edu        print "Error: no non-leaf 'build' dir found on target path", t
2914742Sstever@eecs.umich.edu        Exit(1)
2923053Sstever@eecs.umich.edu    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2933053Sstever@eecs.umich.edu    if not build_root:
2943053Sstever@eecs.umich.edu        build_root = this_build_root
2953053Sstever@eecs.umich.edu    else:
2963053Sstever@eecs.umich.edu        if this_build_root != build_root:
2973053Sstever@eecs.umich.edu            print "Error: build targets not under same build root\n"\
2983053Sstever@eecs.umich.edu                  "  %s\n  %s" % (build_root, this_build_root)
2993053Sstever@eecs.umich.edu            Exit(1)
3003053Sstever@eecs.umich.edu    variant_path = joinpath('/',*path_dirs[:build_top+2])
3012667Sstever@eecs.umich.edu    if variant_path not in variant_paths:
3024554Sbinkertn@umich.edu        variant_paths.append(variant_path)
3034554Sbinkertn@umich.edu
3042667Sstever@eecs.umich.edu# Make sure build_root exists (might not if this is the first build there)
3054554Sbinkertn@umich.eduif not isdir(build_root):
3064554Sbinkertn@umich.edu    mkdir(build_root)
3074554Sbinkertn@umich.edu
3084554Sbinkertn@umich.eduExport('main')
3094554Sbinkertn@umich.edu
3104554Sbinkertn@umich.edumain.SConsignFile(joinpath(build_root, "sconsign"))
3114554Sbinkertn@umich.edu
3124781Snate@binkert.org# Default duplicate option is to use hard links, but this messes up
3134554Sbinkertn@umich.edu# when you use emacs to edit a file in the target dir, as emacs moves
3144554Sbinkertn@umich.edu# file to file~ then copies to file, breaking the link.  Symbolic
3152667Sstever@eecs.umich.edu# (soft) links work better.
3164554Sbinkertn@umich.edumain.SetOption('duplicate', 'soft-copy')
3174554Sbinkertn@umich.edu
3184554Sbinkertn@umich.edu#
3194554Sbinkertn@umich.edu# Set up global sticky variables... these are common to an entire build
3202667Sstever@eecs.umich.edu# tree (not specific to a particular build like ALPHA_SE)
3214554Sbinkertn@umich.edu#
3222667Sstever@eecs.umich.edu
3234554Sbinkertn@umich.edu# Variable validators & converters for global sticky variables
3244554Sbinkertn@umich.edudef PathListMakeAbsolute(val):
3252667Sstever@eecs.umich.edu    if not val:
3262638Sstever@eecs.umich.edu        return val
3272638Sstever@eecs.umich.edu    f = lambda p: abspath(expanduser(p))
3282638Sstever@eecs.umich.edu    return ':'.join(map(f, val.split(':')))
3293716Sstever@eecs.umich.edu
3303716Sstever@eecs.umich.edudef PathListAllExist(key, val, env):
3311858SN/A    if not val:
3325204Sstever@gmail.com        return
3335204Sstever@gmail.com    paths = val.split(':')
3345204Sstever@gmail.com    for path in paths:
3355204Sstever@gmail.com        if not isdir(path):
3365204Sstever@gmail.com            raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
3375204Sstever@gmail.com
3385204Sstever@gmail.comglobal_sticky_vars_file = joinpath(build_root, 'variables.global')
3395204Sstever@gmail.com
3405204Sstever@gmail.comglobal_sticky_vars = Variables(global_sticky_vars_file, args=ARGUMENTS)
3415204Sstever@gmail.com
3425204Sstever@gmail.comglobal_sticky_vars.AddVariables(
3435204Sstever@gmail.com    ('CC', 'C compiler', environ.get('CC', main['CC'])),
3445204Sstever@gmail.com    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3455204Sstever@gmail.com    ('BATCH', 'Use batch pool for build and tests', False),
3465204Sstever@gmail.com    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3475204Sstever@gmail.com    ('EXTRAS', 'Add Extra directories to the compilation', '',
3485204Sstever@gmail.com     PathListAllExist, PathListMakeAbsolute),
3495204Sstever@gmail.com    BoolVariable('RUBY', 'Build with Ruby', False),
3505204Sstever@gmail.com    )
3513118Sstever@eecs.umich.edu
3523118Sstever@eecs.umich.edu# base help text
3533118Sstever@eecs.umich.eduhelp_text = '''
3543118Sstever@eecs.umich.eduUsage: scons [scons options] [build options] [target(s)]
3553118Sstever@eecs.umich.edu
3563118Sstever@eecs.umich.eduGlobal sticky options:
3573118Sstever@eecs.umich.edu'''
3583118Sstever@eecs.umich.edu
3593118Sstever@eecs.umich.eduhelp_text += global_sticky_vars.GenerateHelpText(main)
3603118Sstever@eecs.umich.edu
3613118Sstever@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_sticky_vars_file
3623716Sstever@eecs.umich.eduglobal_sticky_vars.Update(main)
3633118Sstever@eecs.umich.edu
3643118Sstever@eecs.umich.edu# Save sticky variable settings back to current variables file
3653118Sstever@eecs.umich.eduglobal_sticky_vars.Save(global_sticky_vars_file, main)
3663118Sstever@eecs.umich.edu
3673118Sstever@eecs.umich.edu# Parse EXTRAS variable to build list of all directories where we're
3683118Sstever@eecs.umich.edu# look for sources etc.  This list is exported as base_dir_list.
3693118Sstever@eecs.umich.edubase_dir = main.srcdir.abspath
3703118Sstever@eecs.umich.eduif main['EXTRAS']:
3713118Sstever@eecs.umich.edu    extras_dir_list = main['EXTRAS'].split(':')
3723716Sstever@eecs.umich.eduelse:
3733118Sstever@eecs.umich.edu    extras_dir_list = []
3743118Sstever@eecs.umich.edu
3753118Sstever@eecs.umich.eduExport('base_dir')
3763118Sstever@eecs.umich.eduExport('extras_dir_list')
3773118Sstever@eecs.umich.edu
3783118Sstever@eecs.umich.edu# the ext directory should be on the #includes path
3793118Sstever@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
3803118Sstever@eecs.umich.edu
3813118Sstever@eecs.umich.edu# M5_PLY is used by isa_parser.py to find the PLY package.
3823118Sstever@eecs.umich.edumain.Append(ENV = { 'M5_PLY' : Dir('ext/ply').abspath })
3833483Ssaidi@eecs.umich.edu
3843494Ssaidi@eecs.umich.eduCXX_version = read_command([main['CXX'],'--version'], exception=False)
3853494Ssaidi@eecs.umich.eduCXX_V = read_command([main['CXX'],'-V'], exception=False)
3863483Ssaidi@eecs.umich.edu
3873483Ssaidi@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3883483Ssaidi@eecs.umich.edumain['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
3893053Sstever@eecs.umich.edumain['ICC'] = CXX_V and CXX_V.find('Intel') >= 0
3903053Sstever@eecs.umich.eduif main['GCC'] + main['SUNCC'] + main['ICC'] > 1:
3913918Ssaidi@eecs.umich.edu    print 'Error: How can we have two at the same time?'
3923053Sstever@eecs.umich.edu    Exit(1)
3933053Sstever@eecs.umich.edu
3943053Sstever@eecs.umich.edu# Set up default C++ compiler flags
3953053Sstever@eecs.umich.eduif main['GCC']:
3963053Sstever@eecs.umich.edu    main.Append(CCFLAGS='-pipe')
3971858SN/A    main.Append(CCFLAGS='-fno-strict-aliasing')
3981858SN/A    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
3991858SN/A    main.Append(CXXFLAGS='-Wno-deprecated')
4001858SN/Aelif main['ICC']:
4011858SN/A    pass #Fix me... add warning flags once we clean up icc warnings
4021858SN/Aelif main['SUNCC']:
4031859SN/A    main.Append(CCFLAGS='-Qoption ccfe')
4041858SN/A    main.Append(CCFLAGS='-features=gcc')
4051858SN/A    main.Append(CCFLAGS='-features=extensions')
4061858SN/A    main.Append(CCFLAGS='-library=stlport4')
4071859SN/A    main.Append(CCFLAGS='-xar')
4081859SN/A    #main.Append(CCFLAGS='-instances=semiexplicit')
4091862SN/Aelse:
4103053Sstever@eecs.umich.edu    print 'Error: Don\'t know what compiler options to use for your compiler.'
4113053Sstever@eecs.umich.edu    print '       Please fix SConstruct and src/SConscript and try again.'
4123053Sstever@eecs.umich.edu    Exit(1)
4133053Sstever@eecs.umich.edu
4141859SN/A# Set up common yacc/bison flags (needed for Ruby)
4151859SN/Amain['YACCFLAGS'] = '-d'
4161859SN/Amain['YACCHXXFILESUFFIX'] = '.hh'
4171859SN/A
4181859SN/A# Do this after we save setting back, or else we'll tack on an
4191859SN/A# extra 'qdo' every time we run scons.
4201859SN/Aif main['BATCH']:
4211859SN/A    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
4221862SN/A    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
4231859SN/A    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
4241859SN/A    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
4251859SN/A    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
4261858SN/A
4271858SN/Aif sys.platform == 'cygwin':
4282139SN/A    # cygwin has some header file issues...
4294202Sbinkertn@umich.edu    main.Append(CCFLAGS=Split("-Wno-uninitialized"))
4304202Sbinkertn@umich.edu
4312139SN/A# Check for SWIG
4322155SN/Aif not main.has_key('SWIG'):
4334202Sbinkertn@umich.edu    print 'Error: SWIG utility not found.'
4344202Sbinkertn@umich.edu    print '       Please install (see http://www.swig.org) and retry.'
4354202Sbinkertn@umich.edu    Exit(1)
4362155SN/A
4371869SN/A# Check for appropriate SWIG version
4381869SN/Aswig_version = read_command(('swig', '-version'), exception='').split()
4391869SN/A# First 3 words should be "SWIG Version x.y.z"
4401869SN/Aif len(swig_version) < 3 or \
4414202Sbinkertn@umich.edu        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
4424202Sbinkertn@umich.edu    print 'Error determining SWIG version.'
4434202Sbinkertn@umich.edu    Exit(1)
4444202Sbinkertn@umich.edu
4454202Sbinkertn@umich.edumin_swig_version = '1.3.28'
4464202Sbinkertn@umich.eduif compare_versions(swig_version[2], min_swig_version) < 0:
4474202Sbinkertn@umich.edu    print 'Error: SWIG version', min_swig_version, 'or newer required.'
4484202Sbinkertn@umich.edu    print '       Installed version:', swig_version[2]
4494202Sbinkertn@umich.edu    Exit(1)
4504202Sbinkertn@umich.edu
4514202Sbinkertn@umich.edu# Set up SWIG flags & scanner
4524202Sbinkertn@umich.eduswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
4534202Sbinkertn@umich.edumain.Append(SWIGFLAGS=swig_flags)
4544202Sbinkertn@umich.edu
4554202Sbinkertn@umich.edu# filter out all existing swig scanners, they mess up the dependency
4564202Sbinkertn@umich.edu# stuff for some reason
4574773Snate@binkert.orgscanners = []
4584775Snate@binkert.orgfor scanner in main['SCANNERS']:
4594775Snate@binkert.org    skeys = scanner.skeys
4604773Snate@binkert.org    if skeys == '.i':
4614773Snate@binkert.org        continue
4624773Snate@binkert.org
4634773Snate@binkert.org    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
4644773Snate@binkert.org        continue
4654773Snate@binkert.org
4661869SN/A    scanners.append(scanner)
4674202Sbinkertn@umich.edu
4681869SN/A# add the new swig scanner that we like better
4692508SN/Afrom SCons.Scanner import ClassicCPP as CPPScanner
4702508SN/Aswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
4712508SN/Ascanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
4722508SN/A
4734202Sbinkertn@umich.edu# replace the scanners list that has what we want
4741869SN/Amain['SCANNERS'] = scanners
4751869SN/A
4761869SN/A# Add a custom Check function to the Configure context so that we can
4771869SN/A# figure out if the compiler adds leading underscores to global
4781869SN/A# variables.  This is needed for the autogenerated asm files that we
4791869SN/A# use for embedding the python code.
4801965SN/Adef CheckLeading(context):
4811965SN/A    context.Message("Checking for leading underscore in global variables...")
4821965SN/A    # 1) Define a global variable called x from asm so the C compiler
4831869SN/A    #    won't change the symbol at all.
4841869SN/A    # 2) Declare that variable.
4852733Sktlim@umich.edu    # 3) Use the variable
4861869SN/A    #
4871884SN/A    # If the compiler prepends an underscore, this will successfully
4881884SN/A    # link because the external symbol 'x' will be called '_x' which
4893356Sbinkertn@umich.edu    # was defined by the asm statement.  If the compiler does not
4903356Sbinkertn@umich.edu    # prepend an underscore, this will not successfully link because
4913356Sbinkertn@umich.edu    # '_x' will have been defined by assembly, while the C portion of
4924773Snate@binkert.org    # the code will be trying to use 'x'
4934773Snate@binkert.org    ret = context.TryLink('''
4944773Snate@binkert.org        asm(".globl _x; _x: .byte 0");
4951869SN/A        extern int x;
4961858SN/A        int main() { return x; }
4971869SN/A        ''', extension=".c")
4981869SN/A    context.env.Append(LEADING_UNDERSCORE=ret)
4991869SN/A    context.Result(ret)
5001858SN/A    return ret
5012761Sstever@eecs.umich.edu
5021869SN/A# Platform-specific configuration.  Note again that we assume that all
5032733Sktlim@umich.edu# builds under a given build root run on the same host platform.
5043584Ssaidi@eecs.umich.educonf = Configure(main,
5051869SN/A                 conf_dir = joinpath(build_root, '.scons_config'),
5061869SN/A                 log_file = joinpath(build_root, 'scons_config.log'),
5071869SN/A                 custom_tests = { 'CheckLeading' : CheckLeading })
5081869SN/A
5091869SN/A# Check for leading underscores.  Don't really need to worry either
5101869SN/A# way so don't need to check the return code.
5111858SN/Aconf.CheckLeading()
512955SN/A
513955SN/A# Check if we should compile a 64 bit binary on Mac OS X/Darwin
5141869SN/Atry:
5151869SN/A    import platform
5161869SN/A    uname = platform.uname()
5171869SN/A    if uname[0] == 'Darwin' and compare_versions(uname[2], '9.0.0') >= 0:
5181869SN/A        if int(read_command('sysctl -n hw.cpu64bit_capable')[0]):
5191869SN/A            main.Append(CCFLAGS='-arch x86_64')
5201869SN/A            main.Append(CFLAGS='-arch x86_64')
5211869SN/A            main.Append(LINKFLAGS='-arch x86_64')
5221869SN/A            main.Append(ASFLAGS='-arch x86_64')
5231869SN/Aexcept:
5241869SN/A    pass
5251869SN/A
5261869SN/A# Recent versions of scons substitute a "Null" object for Configure()
5271869SN/A# when configuration isn't necessary, e.g., if the "--help" option is
5281869SN/A# present.  Unfortuantely this Null object always returns false,
5291869SN/A# breaking all our configuration checks.  We replace it with our own
5301869SN/A# more optimistic null object that returns True instead.
5311869SN/Aif not conf:
5321869SN/A    def NullCheck(*args, **kwargs):
5331869SN/A        return True
5341869SN/A
5351869SN/A    class NullConf:
5361869SN/A        def __init__(self, env):
5371869SN/A            self.env = env
5381869SN/A        def Finish(self):
5391869SN/A            return self.env
5401869SN/A        def __getattr__(self, mname):
5411869SN/A            return NullCheck
5421869SN/A
5433716Sstever@eecs.umich.edu    conf = NullConf(main)
5443356Sbinkertn@umich.edu
5453356Sbinkertn@umich.edu# Find Python include and library directories for embedding the
5463356Sbinkertn@umich.edu# interpreter.  For consistency, we will use the same Python
5473356Sbinkertn@umich.edu# installation used to run scons (and thus this script).  If you want
5483356Sbinkertn@umich.edu# to link in an alternate version, see above for instructions on how
5493356Sbinkertn@umich.edu# to invoke scons with a different copy of the Python interpreter.
5504781Snate@binkert.orgfrom distutils import sysconfig
5511869SN/A
5521869SN/Apy_getvar = sysconfig.get_config_var
5531869SN/A
5541869SN/Apy_version = 'python' + py_getvar('VERSION')
5551869SN/A
5561869SN/Apy_general_include = sysconfig.get_python_inc()
5571869SN/Apy_platform_include = sysconfig.get_python_inc(plat_specific=True)
5582655Sstever@eecs.umich.edupy_includes = [ py_general_include ]
5592655Sstever@eecs.umich.eduif py_platform_include != py_general_include:
5602655Sstever@eecs.umich.edu    py_includes.append(py_platform_include)
5612655Sstever@eecs.umich.edu
5622655Sstever@eecs.umich.edupy_lib_path = [ py_getvar('LIBDIR') ]
5632655Sstever@eecs.umich.edu# add the prefix/lib/pythonX.Y/config dir, but only if there is no
5642655Sstever@eecs.umich.edu# shared library in prefix/lib/.
5652655Sstever@eecs.umich.eduif not py_getvar('Py_ENABLE_SHARED'):
5662655Sstever@eecs.umich.edu    py_lib_path.append(py_getvar('LIBPL'))
5672655Sstever@eecs.umich.edu
5682655Sstever@eecs.umich.edupy_libs = []
5692655Sstever@eecs.umich.edufor lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
5702655Sstever@eecs.umich.edu    assert lib.startswith('-l')
5712655Sstever@eecs.umich.edu    lib = lib[2:]   
5722655Sstever@eecs.umich.edu    if lib not in py_libs:
5732655Sstever@eecs.umich.edu        py_libs.append(lib)
5742655Sstever@eecs.umich.edupy_libs.append(py_version)
5752655Sstever@eecs.umich.edu
5762655Sstever@eecs.umich.edumain.Append(CPPPATH=py_includes)
5772655Sstever@eecs.umich.edumain.Append(LIBPATH=py_lib_path)
5782655Sstever@eecs.umich.edu
5792655Sstever@eecs.umich.edu# verify that this stuff works
5802655Sstever@eecs.umich.eduif not conf.CheckHeader('Python.h', '<>'):
5812655Sstever@eecs.umich.edu    print "Error: can't find Python.h header in", py_includes
5822655Sstever@eecs.umich.edu    Exit(1)
5832655Sstever@eecs.umich.edu
5842634Sstever@eecs.umich.edufor lib in py_libs:
5852634Sstever@eecs.umich.edu    if not conf.CheckLib(lib):
5862634Sstever@eecs.umich.edu        print "Error: can't find library %s required by python" % lib
5872634Sstever@eecs.umich.edu        Exit(1)
5882634Sstever@eecs.umich.edu
5892634Sstever@eecs.umich.edu# On Solaris you need to use libsocket for socket ops
5902638Sstever@eecs.umich.eduif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
5912638Sstever@eecs.umich.edu   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
5923716Sstever@eecs.umich.edu       print "Can't find library with socket calls (e.g. accept())"
5932638Sstever@eecs.umich.edu       Exit(1)
5942638Sstever@eecs.umich.edu
5951869SN/A# Check for zlib.  If the check passes, libz will be automatically
5961869SN/A# added to the LIBS environment variable.
5973546Sgblack@eecs.umich.eduif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
5983546Sgblack@eecs.umich.edu    print 'Error: did not find needed zlib compression library '\
5993546Sgblack@eecs.umich.edu          'and/or zlib.h header file.'
6003546Sgblack@eecs.umich.edu    print '       Please install zlib and try again.'
6014202Sbinkertn@umich.edu    Exit(1)
6023546Sgblack@eecs.umich.edu
6033546Sgblack@eecs.umich.edu# Check for <fenv.h> (C99 FP environment control)
6043546Sgblack@eecs.umich.eduhave_fenv = conf.CheckHeader('fenv.h', '<>')
6053546Sgblack@eecs.umich.eduif not have_fenv:
6063546Sgblack@eecs.umich.edu    print "Warning: Header file <fenv.h> not found."
6074781Snate@binkert.org    print "         This host has no IEEE FP rounding mode control."
6084781Snate@binkert.org
6094781Snate@binkert.org######################################################################
6104781Snate@binkert.org#
6114781Snate@binkert.org# Check for mysql.
6124781Snate@binkert.org#
6134781Snate@binkert.orgmysql_config = WhereIs('mysql_config')
6144781Snate@binkert.orghave_mysql = bool(mysql_config)
6154781Snate@binkert.org
6164781Snate@binkert.org# Check MySQL version.
6174781Snate@binkert.orgif have_mysql:
6184781Snate@binkert.org    mysql_version = read_command(mysql_config + ' --version')
6193546Sgblack@eecs.umich.edu    min_mysql_version = '4.1'
6203546Sgblack@eecs.umich.edu    if compare_versions(mysql_version, min_mysql_version) < 0:
6213546Sgblack@eecs.umich.edu        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
6224781Snate@binkert.org        print '         Version', mysql_version, 'detected.'
6233546Sgblack@eecs.umich.edu        have_mysql = False
6243546Sgblack@eecs.umich.edu
6253546Sgblack@eecs.umich.edu# Set up mysql_config commands.
6263546Sgblack@eecs.umich.eduif have_mysql:
6273546Sgblack@eecs.umich.edu    mysql_config_include = mysql_config + ' --include'
6283546Sgblack@eecs.umich.edu    if os.system(mysql_config_include + ' > /dev/null') != 0:
6293546Sgblack@eecs.umich.edu        # older mysql_config versions don't support --include, use
6303546Sgblack@eecs.umich.edu        # --cflags instead
6313546Sgblack@eecs.umich.edu        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
6323546Sgblack@eecs.umich.edu    # This seems to work in all versions
6334202Sbinkertn@umich.edu    mysql_config_libs = mysql_config + ' --libs'
6343546Sgblack@eecs.umich.edu
6353546Sgblack@eecs.umich.edu######################################################################
6363546Sgblack@eecs.umich.edu#
637955SN/A# Finish the configuration
638955SN/A#
639955SN/Amain = conf.Finish()
640955SN/A
6411858SN/A######################################################################
6421858SN/A#
6431858SN/A# Collect all non-global variables
6442632Sstever@eecs.umich.edu#
6452632Sstever@eecs.umich.edu
6464773Snate@binkert.org# Define the universe of supported ISAs
6474773Snate@binkert.orgall_isa_list = [ ]
6482632Sstever@eecs.umich.eduExport('all_isa_list')
6492632Sstever@eecs.umich.edu
6502632Sstever@eecs.umich.edu# Define the universe of supported CPU models
6512634Sstever@eecs.umich.eduall_cpu_list = [ ]
6522638Sstever@eecs.umich.edudefault_cpus = [ ]
6532023SN/AExport('all_cpu_list', 'default_cpus')
6542632Sstever@eecs.umich.edu
6552632Sstever@eecs.umich.edu# Sticky variables get saved in the variables file so they persist from
6562632Sstever@eecs.umich.edu# one invocation to the next (unless overridden, in which case the new
6572632Sstever@eecs.umich.edu# value becomes sticky).
6582632Sstever@eecs.umich.edusticky_vars = Variables(args=ARGUMENTS)
6593716Sstever@eecs.umich.eduExport('sticky_vars')
6602632Sstever@eecs.umich.edu
6612632Sstever@eecs.umich.edu# Sticky variables that should be exported
6622632Sstever@eecs.umich.eduexport_vars = []
6632632Sstever@eecs.umich.eduExport('export_vars')
6642632Sstever@eecs.umich.edu
6652023SN/A# Non-sticky variables only apply to the current build.
6662632Sstever@eecs.umich.edunonsticky_vars = Variables(args=ARGUMENTS)
6672632Sstever@eecs.umich.eduExport('nonsticky_vars')
6681889SN/A
6691889SN/A# Walk the tree and execute all SConsopts scripts that wil add to the
6702632Sstever@eecs.umich.edu# above variables
6712632Sstever@eecs.umich.edufor bdir in [ base_dir ] + extras_dir_list:
6722632Sstever@eecs.umich.edu    for root, dirs, files in os.walk(bdir):
6732632Sstever@eecs.umich.edu        if 'SConsopts' in files:
6743716Sstever@eecs.umich.edu            print "Reading", joinpath(root, 'SConsopts')
6753716Sstever@eecs.umich.edu            SConscript(joinpath(root, 'SConsopts'))
6762632Sstever@eecs.umich.edu
6772632Sstever@eecs.umich.eduall_isa_list.sort()
6782632Sstever@eecs.umich.eduall_cpu_list.sort()
6792632Sstever@eecs.umich.edudefault_cpus.sort()
6802632Sstever@eecs.umich.edu
6812632Sstever@eecs.umich.edusticky_vars.AddVariables(
6822632Sstever@eecs.umich.edu    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
6832632Sstever@eecs.umich.edu    BoolVariable('FULL_SYSTEM', 'Full-system support', False),
6841888SN/A    ListVariable('CPU_MODELS', 'CPU models', default_cpus, all_cpu_list),
6851888SN/A    BoolVariable('NO_FAST_ALLOC', 'Disable fast object allocator', False),
6861869SN/A    BoolVariable('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
6871869SN/A                 False),
6881858SN/A    BoolVariable('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
6892598SN/A                 False),
6902598SN/A    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
6912598SN/A                 False),
6922598SN/A    BoolVariable('SS_COMPATIBLE_FP',
6932598SN/A                 'Make floating-point results compatible with SimpleScalar',
6941858SN/A                 False),
6951858SN/A    BoolVariable('USE_SSE2',
6961858SN/A                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
6971858SN/A                 False),
6981858SN/A    BoolVariable('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
6991858SN/A    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
7001858SN/A    BoolVariable('USE_CHECKER', 'Use checker for detailed CPU models', False),
7011858SN/A    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
7021858SN/A    )
7031871SN/A
7041858SN/Anonsticky_vars.AddVariables(
7051858SN/A    BoolVariable('update_ref', 'Update test reference outputs', False)
7061858SN/A    )
7071858SN/A
7081858SN/A# These variables get exported to #defines in config/*.hh (see src/SConscript).
7091858SN/Aexport_vars += ['FULL_SYSTEM', 'USE_FENV', 'USE_MYSQL',
7101858SN/A                'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', 'FAST_ALLOC_STATS',
7111858SN/A                'SS_COMPATIBLE_FP', 'USE_CHECKER', 'TARGET_ISA', 'CP_ANNOTATE']
7121858SN/A
7131858SN/A###################################################
7141858SN/A#
7151859SN/A# Define a SCons builder for configuration flag headers.
7161859SN/A#
7171869SN/A###################################################
7181888SN/A
7192632Sstever@eecs.umich.edu# This function generates a config header file that #defines the
7201869SN/A# variable symbol to the current variable setting (0 or 1).  The source
7211884SN/A# operands are the name of the variable and a Value node containing the
7221884SN/A# value of the variable.
7231884SN/Adef build_config_file(target, source, env):
7241884SN/A    (variable, value) = [s.get_contents() for s in source]
7251884SN/A    f = file(str(target[0]), 'w')
7261884SN/A    print >> f, '#define', variable, value
7271965SN/A    f.close()
7281965SN/A    return None
7291965SN/A
7302761Sstever@eecs.umich.edu# Generate the message to be printed when building the config file.
7311869SN/Adef build_config_file_string(target, source, env):
7321869SN/A    (variable, value) = [s.get_contents() for s in source]
7332632Sstever@eecs.umich.edu    return "Defining %s as %s in %s." % (variable, value, target[0])
7342667Sstever@eecs.umich.edu
7351869SN/A# Combine the two functions into a scons Action object.
7361869SN/Aconfig_action = Action(build_config_file, build_config_file_string)
7372929Sktlim@umich.edu
7382929Sktlim@umich.edu# The emitter munges the source & target node lists to reflect what
7393716Sstever@eecs.umich.edu# we're really doing.
7402929Sktlim@umich.edudef config_emitter(target, source, env):
741955SN/A    # extract variable name from Builder arg
7422598SN/A    variable = str(target[0])
7432598SN/A    # True target is config header file
7443546Sgblack@eecs.umich.edu    target = joinpath('config', variable.lower() + '.hh')
745955SN/A    val = env[variable]
746955SN/A    if isinstance(val, bool):
747955SN/A        # Force value to 0/1
7481530SN/A        val = int(val)
749955SN/A    elif isinstance(val, str):
750955SN/A        val = '"' + val + '"'
751955SN/A
752    # Sources are variable name & value (packaged in SCons Value nodes)
753    return ([target], [Value(variable), Value(val)])
754
755config_builder = Builder(emitter = config_emitter, action = config_action)
756
757main.Append(BUILDERS = { 'ConfigFile' : config_builder })
758
759# libelf build is shared across all configs in the build root.
760main.SConscript('ext/libelf/SConscript',
761                variant_dir = joinpath(build_root, 'libelf'))
762
763# gzstream build is shared across all configs in the build root.
764main.SConscript('ext/gzstream/SConscript',
765                variant_dir = joinpath(build_root, 'gzstream'))
766
767###################################################
768#
769# This function is used to set up a directory with switching headers
770#
771###################################################
772
773main['ALL_ISA_LIST'] = all_isa_list
774def make_switching_dir(dname, switch_headers, env):
775    # Generate the header.  target[0] is the full path of the output
776    # header to generate.  'source' is a dummy variable, since we get the
777    # list of ISAs from env['ALL_ISA_LIST'].
778    def gen_switch_hdr(target, source, env):
779        fname = str(target[0])
780        bname = basename(fname)
781        f = open(fname, 'w')
782        f.write('#include "arch/isa_specific.hh"\n')
783        cond = '#if'
784        for isa in all_isa_list:
785            f.write('%s THE_ISA == %s_ISA\n#include "%s/%s/%s"\n'
786                    % (cond, isa.upper(), dname, isa, bname))
787            cond = '#elif'
788        f.write('#else\n#error "THE_ISA not set"\n#endif\n')
789        f.close()
790        return 0
791
792    # String to print when generating header
793    def gen_switch_hdr_string(target, source, env):
794        return "Generating switch header " + str(target[0])
795
796    # Build SCons Action object. 'varlist' specifies env vars that this
797    # action depends on; when env['ALL_ISA_LIST'] changes these actions
798    # should get re-executed.
799    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
800                               varlist=['ALL_ISA_LIST'])
801
802    # Instantiate actions for each header
803    for hdr in switch_headers:
804        env.Command(hdr, [], switch_hdr_action)
805Export('make_switching_dir')
806
807###################################################
808#
809# Define build environments for selected configurations.
810#
811###################################################
812
813for variant_path in variant_paths:
814    print "Building in", variant_path
815
816    # Make a copy of the build-root environment to use for this config.
817    env = main.Clone()
818    env['BUILDDIR'] = variant_path
819
820    # variant_dir is the tail component of build path, and is used to
821    # determine the build parameters (e.g., 'ALPHA_SE')
822    (build_root, variant_dir) = splitpath(variant_path)
823
824    # Set env variables according to the build directory config.
825    sticky_vars.files = []
826    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
827    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
828    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
829    current_vars_file = joinpath(build_root, 'variables', variant_dir)
830    if isfile(current_vars_file):
831        sticky_vars.files.append(current_vars_file)
832        print "Using saved variables file %s" % current_vars_file
833    else:
834        # Build dir-specific variables file doesn't exist.
835
836        # Make sure the directory is there so we can create it later
837        opt_dir = dirname(current_vars_file)
838        if not isdir(opt_dir):
839            mkdir(opt_dir)
840
841        # Get default build variables from source tree.  Variables are
842        # normally determined by name of $VARIANT_DIR, but can be
843        # overriden by 'default=' arg on command line.
844        default_vars_file = joinpath('build_opts',
845                                     ARGUMENTS.get('default', variant_dir))
846        if isfile(default_vars_file):
847            sticky_vars.files.append(default_vars_file)
848            print "Variables file %s not found,\n  using defaults in %s" \
849                  % (current_vars_file, default_vars_file)
850        else:
851            print "Error: cannot find variables file %s or %s" \
852                  % (current_vars_file, default_vars_file)
853            Exit(1)
854
855    # Apply current variable settings to env
856    sticky_vars.Update(env)
857    nonsticky_vars.Update(env)
858
859    help_text += "\nSticky variables for %s:\n" % variant_dir \
860                 + sticky_vars.GenerateHelpText(env) \
861                 + "\nNon-sticky variables for %s:\n" % variant_dir \
862                 + nonsticky_vars.GenerateHelpText(env)
863
864    # Process variable settings.
865
866    if not have_fenv and env['USE_FENV']:
867        print "Warning: <fenv.h> not available; " \
868              "forcing USE_FENV to False in", variant_dir + "."
869        env['USE_FENV'] = False
870
871    if not env['USE_FENV']:
872        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
873        print "         FP results may deviate slightly from other platforms."
874
875    if env['EFENCE']:
876        env.Append(LIBS=['efence'])
877
878    if env['USE_MYSQL']:
879        if not have_mysql:
880            print "Warning: MySQL not available; " \
881                  "forcing USE_MYSQL to False in", variant_dir + "."
882            env['USE_MYSQL'] = False
883        else:
884            print "Compiling in", variant_dir, "with MySQL support."
885            env.ParseConfig(mysql_config_libs)
886            env.ParseConfig(mysql_config_include)
887
888    # Save sticky variable settings back to current variables file
889    sticky_vars.Save(current_vars_file, env)
890
891    if env['USE_SSE2']:
892        env.Append(CCFLAGS='-msse2')
893
894    # The src/SConscript file sets up the build rules in 'env' according
895    # to the configured variables.  It returns a list of environments,
896    # one for each variant build (debug, opt, etc.)
897    envList = SConscript('src/SConscript', variant_dir = variant_path,
898                         exports = 'env')
899
900    # Set up the regression tests for each build.
901    for e in envList:
902        SConscript('tests/SConscript',
903                   variant_dir = joinpath(variant_path, 'tests', e.Label),
904                   exports = { 'env' : e }, duplicate = False)
905
906Help(help_text)
907