SConstruct revision 7457
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
684202Sbinkertn@umich.edu# Check for recent-enough Python and SCons versions.
695342Sstever@gmail.comtry:
70955SN/A    # Really old versions of scons only take two options for the
715273Sstever@gmail.com    # function, so check once without the revision and once with the
725273Sstever@gmail.com    # 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:
792656Sstever@eecs.umich.edu    http://m5sim.org/wiki/index.php/Compiling_M5
802653Sstever@eecs.umich.edu"""
815227Ssaidi@eecs.umich.edu    raise
825227Ssaidi@eecs.umich.edu
835227Ssaidi@eecs.umich.edu# We ensure the python version early because we have stuff that
845227Ssaidi@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 """
892653Sstever@eecs.umich.eduYou can use a non-default installation of the Python interpreter by
902653Sstever@eecs.umich.edueither (1) rearranging your PATH so that scons finds the non-default
912653Sstever@eecs.umich.edu'python' first or (2) explicitly invoking an alternative interpreter
922653Sstever@eecs.umich.eduon the scons script.
932653Sstever@eecs.umich.edu
944781Snate@binkert.orgFor more details, see:
951852SN/A    http://m5sim.org/wiki/index.php/Using_a_non-default_Python_installation
96955SN/A"""
97955SN/A    raise
98955SN/A
993717Sstever@eecs.umich.edu# Global Python includes
1003716Sstever@eecs.umich.eduimport os
101955SN/Aimport re
1021533SN/Aimport subprocess
1033716Sstever@eecs.umich.eduimport sys
1041533SN/A
1054678Snate@binkert.orgfrom os import mkdir, environ
1064678Snate@binkert.orgfrom os.path import abspath, basename, dirname, expanduser, normpath
1074678Snate@binkert.orgfrom os.path import exists,  isdir, isfile
1084678Snate@binkert.orgfrom os.path import join as joinpath, split as splitpath
1094678Snate@binkert.org
1104678Snate@binkert.org# SCons includes
1114678Snate@binkert.orgimport SCons
1124678Snate@binkert.orgimport SCons.Node
1134678Snate@binkert.org
1144678Snate@binkert.orgextra_python_paths = [
1154678Snate@binkert.org    Dir('src/python').srcnode().abspath, # M5 includes
1164678Snate@binkert.org    Dir('ext/ply').srcnode().abspath, # ply is used by several files
1174678Snate@binkert.org    ]
1184678Snate@binkert.org    
1194678Snate@binkert.orgsys.path[1:1] = extra_python_paths
1204678Snate@binkert.org
1214678Snate@binkert.orgfrom m5.util import compareVersions, readCommand
1224678Snate@binkert.org
1234678Snate@binkert.org########################################################################
1244678Snate@binkert.org#
1254678Snate@binkert.org# Set up the main build environment.
1264973Ssaidi@eecs.umich.edu#
1274678Snate@binkert.org########################################################################
1284678Snate@binkert.orguse_vars = set([ 'AS', 'AR', 'CC', 'CXX', 'HOME', 'LD_LIBRARY_PATH', 'PATH',
1294678Snate@binkert.org                 'PYTHONPATH', 'RANLIB' ])
1304678Snate@binkert.org
1314678Snate@binkert.orguse_env = {}
1324678Snate@binkert.orgfor key,val in os.environ.iteritems():
133955SN/A    if key in use_vars or key.startswith("M5"):
134955SN/A        use_env[key] = val
1352632Sstever@eecs.umich.edu
1362632Sstever@eecs.umich.edumain = Environment(ENV=use_env)
137955SN/Amain.root = Dir(".")         # The current directory (where this file lives).
138955SN/Amain.srcdir = Dir("src")     # The source directory
139955SN/A
140955SN/A# add useful python code PYTHONPATH so it can be used by subprocesses
1412632Sstever@eecs.umich.edu# as well
142955SN/Amain.AppendENVPath('PYTHONPATH', extra_python_paths)
1432632Sstever@eecs.umich.edu
1442632Sstever@eecs.umich.edu########################################################################
1452632Sstever@eecs.umich.edu#
1462632Sstever@eecs.umich.edu# Mercurial Stuff.
1472632Sstever@eecs.umich.edu#
1482632Sstever@eecs.umich.edu# If the M5 directory is a mercurial repository, we should do some
1492632Sstever@eecs.umich.edu# extra things.
1503053Sstever@eecs.umich.edu#
1513053Sstever@eecs.umich.edu########################################################################
1523053Sstever@eecs.umich.edu
1533053Sstever@eecs.umich.eduhgdir = main.root.Dir(".hg")
1543053Sstever@eecs.umich.edu
1553053Sstever@eecs.umich.edumercurial_style_message = """
1563053Sstever@eecs.umich.eduYou're missing the M5 style hook.
1573053Sstever@eecs.umich.eduPlease install the hook so we can ensure that all code fits a common style.
1583053Sstever@eecs.umich.edu
1593053Sstever@eecs.umich.eduAll you'd need to do is add the following lines to your repository .hg/hgrc
1603053Sstever@eecs.umich.eduor your personal .hgrc
1613053Sstever@eecs.umich.edu----------------
1623053Sstever@eecs.umich.edu
1633053Sstever@eecs.umich.edu[extensions]
1643053Sstever@eecs.umich.edustyle = %s/util/style.py
1653053Sstever@eecs.umich.edu
1662632Sstever@eecs.umich.edu[hooks]
1672632Sstever@eecs.umich.edupretxncommit.style = python:style.check_whitespace
1682632Sstever@eecs.umich.edu""" % (main.root)
1692632Sstever@eecs.umich.edu
1702632Sstever@eecs.umich.edumercurial_bin_not_found = """
1712632Sstever@eecs.umich.eduMercurial binary cannot be found, unfortunately this means that we
1723718Sstever@eecs.umich.educannot easily determine the version of M5 that you are running and
1733718Sstever@eecs.umich.eduthis makes error messages more difficult to collect.  Please consider
1743718Sstever@eecs.umich.eduinstalling mercurial if you choose to post an error message
1753718Sstever@eecs.umich.edu"""
1763718Sstever@eecs.umich.edu
1773718Sstever@eecs.umich.edumercurial_lib_not_found = """
1783718Sstever@eecs.umich.eduMercurial libraries cannot be found, ignoring style hook
1793718Sstever@eecs.umich.eduIf you are actually a M5 developer, please fix this and
1803718Sstever@eecs.umich.edurun the style hook. It is important.
1813718Sstever@eecs.umich.edu"""
1823718Sstever@eecs.umich.edu
1833718Sstever@eecs.umich.eduhg_info = "Unknown"
1843718Sstever@eecs.umich.eduif hgdir.exists():
1852634Sstever@eecs.umich.edu    # 1) Grab repository revision if we know it.
1862634Sstever@eecs.umich.edu    cmd = "hg id -n -i -t -b"
1872632Sstever@eecs.umich.edu    try:
1882638Sstever@eecs.umich.edu        hg_info = readCommand(cmd, cwd=main.root.abspath).strip()
1892632Sstever@eecs.umich.edu    except OSError:
1902632Sstever@eecs.umich.edu        print mercurial_bin_not_found
1912632Sstever@eecs.umich.edu
1922632Sstever@eecs.umich.edu    # 2) Ensure that the style hook is in place.
1932632Sstever@eecs.umich.edu    try:
1942632Sstever@eecs.umich.edu        ui = None
1951858SN/A        if ARGUMENTS.get('IGNORE_STYLE') != 'True':
1963716Sstever@eecs.umich.edu            from mercurial import ui
1972638Sstever@eecs.umich.edu            ui = ui.ui()
1982638Sstever@eecs.umich.edu    except ImportError:
1992638Sstever@eecs.umich.edu        print mercurial_lib_not_found
2002638Sstever@eecs.umich.edu
2012638Sstever@eecs.umich.edu    if ui is not None:
2022638Sstever@eecs.umich.edu        ui.readconfig(hgdir.File('hgrc').abspath)
2032638Sstever@eecs.umich.edu        style_hook = ui.config('hooks', 'pretxncommit.style', None)
2043716Sstever@eecs.umich.edu
2052634Sstever@eecs.umich.edu        if not style_hook:
2062634Sstever@eecs.umich.edu            print mercurial_style_message
207955SN/A            sys.exit(1)
2085341Sstever@gmail.comelse:
2095341Sstever@gmail.com    print ".hg directory not found"
2105341Sstever@gmail.com
2115341Sstever@gmail.commain['HG_INFO'] = hg_info
212955SN/A
213955SN/A###################################################
214955SN/A#
215955SN/A# Figure out which configurations to set up based on the path(s) of
216955SN/A# the target(s).
217955SN/A#
218955SN/A###################################################
2191858SN/A
2201858SN/A# Find default configuration & binary.
2212632Sstever@eecs.umich.eduDefault(environ.get('M5_DEFAULT_BINARY', 'build/ALPHA_SE/m5.debug'))
222955SN/A
2234494Ssaidi@eecs.umich.edu# helper function: find last occurrence of element in list
2244494Ssaidi@eecs.umich.edudef rfind(l, elt, offs = -1):
2253716Sstever@eecs.umich.edu    for i in range(len(l)+offs, 0, -1):
2261105SN/A        if l[i] == elt:
2272667Sstever@eecs.umich.edu            return i
2282667Sstever@eecs.umich.edu    raise ValueError, "element not found"
2292667Sstever@eecs.umich.edu
2302667Sstever@eecs.umich.edu# Each target must have 'build' in the interior of the path; the
2312667Sstever@eecs.umich.edu# directory below this will determine the build parameters.  For
2322667Sstever@eecs.umich.edu# example, for target 'foo/bar/build/ALPHA_SE/arch/alpha/blah.do' we
2331869SN/A# recognize that ALPHA_SE specifies the configuration because it
2341869SN/A# follow 'build' in the bulid path.
2351869SN/A
2361869SN/A# Generate absolute paths to targets so we can see where the build dir is
2371869SN/Aif COMMAND_LINE_TARGETS:
2381065SN/A    # Ask SCons which directory it was invoked from
2395341Sstever@gmail.com    launch_dir = GetLaunchDir()
2405341Sstever@gmail.com    # Make targets relative to invocation directory
2415341Sstever@gmail.com    abs_targets = [ normpath(joinpath(launch_dir, str(x))) for x in \
2425341Sstever@gmail.com                    COMMAND_LINE_TARGETS]
2435341Sstever@gmail.comelse:
2445341Sstever@gmail.com    # Default targets are relative to root of tree
2455341Sstever@gmail.com    abs_targets = [ normpath(joinpath(main.root.abspath, str(x))) for x in \
2465341Sstever@gmail.com                    DEFAULT_TARGETS]
2475341Sstever@gmail.com
2485341Sstever@gmail.com
2495341Sstever@gmail.com# Generate a list of the unique build roots and configs that the
2505341Sstever@gmail.com# collected targets reference.
2515341Sstever@gmail.comvariant_paths = []
2525341Sstever@gmail.combuild_root = None
2535341Sstever@gmail.comfor t in abs_targets:
2545341Sstever@gmail.com    path_dirs = t.split('/')
2555341Sstever@gmail.com    try:
2565341Sstever@gmail.com        build_top = rfind(path_dirs, 'build', -2)
2575341Sstever@gmail.com    except:
2585341Sstever@gmail.com        print "Error: no non-leaf 'build' dir found on target path", t
2595341Sstever@gmail.com        Exit(1)
2605341Sstever@gmail.com    this_build_root = joinpath('/',*path_dirs[:build_top+1])
2615341Sstever@gmail.com    if not build_root:
2625341Sstever@gmail.com        build_root = this_build_root
2635341Sstever@gmail.com    else:
2645341Sstever@gmail.com        if this_build_root != build_root:
2655341Sstever@gmail.com            print "Error: build targets not under same build root\n"\
2665341Sstever@gmail.com                  "  %s\n  %s" % (build_root, this_build_root)
2675341Sstever@gmail.com            Exit(1)
2685341Sstever@gmail.com    variant_path = joinpath('/',*path_dirs[:build_top+2])
2695341Sstever@gmail.com    if variant_path not in variant_paths:
2705341Sstever@gmail.com        variant_paths.append(variant_path)
2715341Sstever@gmail.com
2725341Sstever@gmail.com# Make sure build_root exists (might not if this is the first build there)
2735341Sstever@gmail.comif not isdir(build_root):
2745341Sstever@gmail.com    mkdir(build_root)
2755341Sstever@gmail.com
2765341Sstever@gmail.comExport('main')
2775341Sstever@gmail.com
2785341Sstever@gmail.commain.SConsignFile(joinpath(build_root, "sconsign"))
2795341Sstever@gmail.com
2805341Sstever@gmail.com# Default duplicate option is to use hard links, but this messes up
2815341Sstever@gmail.com# when you use emacs to edit a file in the target dir, as emacs moves
2825341Sstever@gmail.com# file to file~ then copies to file, breaking the link.  Symbolic
2835341Sstever@gmail.com# (soft) links work better.
2845341Sstever@gmail.commain.SetOption('duplicate', 'soft-copy')
2855341Sstever@gmail.com
2865341Sstever@gmail.com#
2875341Sstever@gmail.com# Set up global sticky variables... these are common to an entire build
2885344Sstever@gmail.com# tree (not specific to a particular build like ALPHA_SE)
2895341Sstever@gmail.com#
2905341Sstever@gmail.com
2915341Sstever@gmail.com# Variable validators & converters for global sticky variables
2925341Sstever@gmail.comdef PathListMakeAbsolute(val):
2935341Sstever@gmail.com    if not val:
2942632Sstever@eecs.umich.edu        return val
2955199Sstever@gmail.com    f = lambda p: abspath(expanduser(p))
2963918Ssaidi@eecs.umich.edu    return ':'.join(map(f, val.split(':')))
2973918Ssaidi@eecs.umich.edu
2983940Ssaidi@eecs.umich.edudef PathListAllExist(key, val, env):
2994781Snate@binkert.org    if not val:
3004781Snate@binkert.org        return
3013918Ssaidi@eecs.umich.edu    paths = val.split(':')
3024781Snate@binkert.org    for path in paths:
3034781Snate@binkert.org        if not isdir(path):
3043918Ssaidi@eecs.umich.edu            raise SCons.Errors.UserError("Path does not exist: '%s'" % path)
3054781Snate@binkert.org
3064781Snate@binkert.orgglobal_sticky_vars_file = joinpath(build_root, 'variables.global')
3073940Ssaidi@eecs.umich.edu
3083942Ssaidi@eecs.umich.eduglobal_sticky_vars = Variables(global_sticky_vars_file, args=ARGUMENTS)
3093940Ssaidi@eecs.umich.edu
3103918Ssaidi@eecs.umich.eduglobal_sticky_vars.AddVariables(
3113918Ssaidi@eecs.umich.edu    ('CC', 'C compiler', environ.get('CC', main['CC'])),
312955SN/A    ('CXX', 'C++ compiler', environ.get('CXX', main['CXX'])),
3131858SN/A    ('BATCH', 'Use batch pool for build and tests', False),
3143918Ssaidi@eecs.umich.edu    ('BATCH_CMD', 'Batch pool submission command name', 'qdo'),
3153918Ssaidi@eecs.umich.edu    ('EXTRAS', 'Add Extra directories to the compilation', '',
3163918Ssaidi@eecs.umich.edu     PathListAllExist, PathListMakeAbsolute),
3173918Ssaidi@eecs.umich.edu    )
3183940Ssaidi@eecs.umich.edu
3193940Ssaidi@eecs.umich.edu# base help text
3203918Ssaidi@eecs.umich.eduhelp_text = '''
3213918Ssaidi@eecs.umich.eduUsage: scons [scons options] [build options] [target(s)]
3223918Ssaidi@eecs.umich.edu
3233918Ssaidi@eecs.umich.eduGlobal sticky options:
3243918Ssaidi@eecs.umich.edu'''
3253918Ssaidi@eecs.umich.edu
3263918Ssaidi@eecs.umich.edu# Update main environment with values from ARGUMENTS & global_sticky_vars_file
3273918Ssaidi@eecs.umich.eduglobal_sticky_vars.Update(main)
3283918Ssaidi@eecs.umich.edu
3293940Ssaidi@eecs.umich.eduhelp_text += global_sticky_vars.GenerateHelpText(main)
3303918Ssaidi@eecs.umich.edu
3313918Ssaidi@eecs.umich.edu# Save sticky variable settings back to current variables file
3321851SN/Aglobal_sticky_vars.Save(global_sticky_vars_file, main)
3331851SN/A
3341858SN/A# Parse EXTRAS variable to build list of all directories where we're
3355200Sstever@gmail.com# look for sources etc.  This list is exported as base_dir_list.
336955SN/Abase_dir = main.srcdir.abspath
3373053Sstever@eecs.umich.eduif main['EXTRAS']:
3383053Sstever@eecs.umich.edu    extras_dir_list = main['EXTRAS'].split(':')
3393053Sstever@eecs.umich.eduelse:
3403053Sstever@eecs.umich.edu    extras_dir_list = []
3413053Sstever@eecs.umich.edu
3423053Sstever@eecs.umich.eduExport('base_dir')
3433053Sstever@eecs.umich.eduExport('extras_dir_list')
3443053Sstever@eecs.umich.edu
3453053Sstever@eecs.umich.edu# the ext directory should be on the #includes path
3464742Sstever@eecs.umich.edumain.Append(CPPPATH=[Dir('ext')])
3474742Sstever@eecs.umich.edu
3483053Sstever@eecs.umich.eduCXX_version = readCommand([main['CXX'],'--version'], exception=False)
3493053Sstever@eecs.umich.eduCXX_V = readCommand([main['CXX'],'-V'], exception=False)
3503053Sstever@eecs.umich.edu
3513053Sstever@eecs.umich.edumain['GCC'] = CXX_version and CXX_version.find('g++') >= 0
3523053Sstever@eecs.umich.edumain['SUNCC'] = CXX_V and CXX_V.find('Sun C++') >= 0
3533053Sstever@eecs.umich.edumain['ICC'] = CXX_V and CXX_V.find('Intel') >= 0
3543053Sstever@eecs.umich.eduif main['GCC'] + main['SUNCC'] + main['ICC'] > 1:
3553053Sstever@eecs.umich.edu    print 'Error: How can we have two at the same time?'
3563053Sstever@eecs.umich.edu    Exit(1)
3572667Sstever@eecs.umich.edu
3584554Sbinkertn@umich.edu# Set up default C++ compiler flags
3594554Sbinkertn@umich.eduif main['GCC']:
3602667Sstever@eecs.umich.edu    main.Append(CCFLAGS='-pipe')
3614554Sbinkertn@umich.edu    main.Append(CCFLAGS='-fno-strict-aliasing')
3624554Sbinkertn@umich.edu    main.Append(CCFLAGS=['-Wall', '-Wno-sign-compare', '-Wundef'])
3634554Sbinkertn@umich.edu    main.Append(CXXFLAGS='-Wno-deprecated')
3644554Sbinkertn@umich.eduelif main['ICC']:
3654554Sbinkertn@umich.edu    pass #Fix me... add warning flags once we clean up icc warnings
3664554Sbinkertn@umich.eduelif main['SUNCC']:
3674554Sbinkertn@umich.edu    main.Append(CCFLAGS='-Qoption ccfe')
3684781Snate@binkert.org    main.Append(CCFLAGS='-features=gcc')
3694554Sbinkertn@umich.edu    main.Append(CCFLAGS='-features=extensions')
3704554Sbinkertn@umich.edu    main.Append(CCFLAGS='-library=stlport4')
3712667Sstever@eecs.umich.edu    main.Append(CCFLAGS='-xar')
3724554Sbinkertn@umich.edu    #main.Append(CCFLAGS='-instances=semiexplicit')
3734554Sbinkertn@umich.eduelse:
3744554Sbinkertn@umich.edu    print 'Error: Don\'t know what compiler options to use for your compiler.'
3754554Sbinkertn@umich.edu    print '       Please fix SConstruct and src/SConscript and try again.'
3762667Sstever@eecs.umich.edu    Exit(1)
3774554Sbinkertn@umich.edu
3782667Sstever@eecs.umich.edu# Set up common yacc/bison flags (needed for Ruby)
3794554Sbinkertn@umich.edumain['YACCFLAGS'] = '-d'
3804554Sbinkertn@umich.edumain['YACCHXXFILESUFFIX'] = '.hh'
3812667Sstever@eecs.umich.edu
3822638Sstever@eecs.umich.edu# Do this after we save setting back, or else we'll tack on an
3832638Sstever@eecs.umich.edu# extra 'qdo' every time we run scons.
3842638Sstever@eecs.umich.eduif main['BATCH']:
3853716Sstever@eecs.umich.edu    main['CC']     = main['BATCH_CMD'] + ' ' + main['CC']
3863716Sstever@eecs.umich.edu    main['CXX']    = main['BATCH_CMD'] + ' ' + main['CXX']
3871858SN/A    main['AS']     = main['BATCH_CMD'] + ' ' + main['AS']
3885227Ssaidi@eecs.umich.edu    main['AR']     = main['BATCH_CMD'] + ' ' + main['AR']
3895227Ssaidi@eecs.umich.edu    main['RANLIB'] = main['BATCH_CMD'] + ' ' + main['RANLIB']
3905227Ssaidi@eecs.umich.edu
3915227Ssaidi@eecs.umich.eduif sys.platform == 'cygwin':
3925227Ssaidi@eecs.umich.edu    # cygwin has some header file issues...
3935227Ssaidi@eecs.umich.edu    main.Append(CCFLAGS="-Wno-uninitialized")
3945227Ssaidi@eecs.umich.edu
3955227Ssaidi@eecs.umich.edu# Check for SWIG
3965227Ssaidi@eecs.umich.eduif not main.has_key('SWIG'):
3975227Ssaidi@eecs.umich.edu    print 'Error: SWIG utility not found.'
3985227Ssaidi@eecs.umich.edu    print '       Please install (see http://www.swig.org) and retry.'
3995227Ssaidi@eecs.umich.edu    Exit(1)
4005274Ssaidi@eecs.umich.edu
4015227Ssaidi@eecs.umich.edu# Check for appropriate SWIG version
4025227Ssaidi@eecs.umich.eduswig_version = readCommand(('swig', '-version'), exception='').split()
4035227Ssaidi@eecs.umich.edu# First 3 words should be "SWIG Version x.y.z"
4045204Sstever@gmail.comif len(swig_version) < 3 or \
4055204Sstever@gmail.com        swig_version[0] != 'SWIG' or swig_version[1] != 'Version':
4065204Sstever@gmail.com    print 'Error determining SWIG version.'
4075204Sstever@gmail.com    Exit(1)
4085204Sstever@gmail.com
4095204Sstever@gmail.commin_swig_version = '1.3.28'
4105204Sstever@gmail.comif compareVersions(swig_version[2], min_swig_version) < 0:
4115204Sstever@gmail.com    print 'Error: SWIG version', min_swig_version, 'or newer required.'
4125204Sstever@gmail.com    print '       Installed version:', swig_version[2]
4135204Sstever@gmail.com    Exit(1)
4145204Sstever@gmail.com
4155204Sstever@gmail.com# Set up SWIG flags & scanner
4165204Sstever@gmail.comswig_flags=Split('-c++ -python -modern -templatereduce $_CPPINCFLAGS')
4175204Sstever@gmail.commain.Append(SWIGFLAGS=swig_flags)
4185204Sstever@gmail.com
4195204Sstever@gmail.com# filter out all existing swig scanners, they mess up the dependency
4205204Sstever@gmail.com# stuff for some reason
4215204Sstever@gmail.comscanners = []
4225204Sstever@gmail.comfor scanner in main['SCANNERS']:
4233118Sstever@eecs.umich.edu    skeys = scanner.skeys
4243118Sstever@eecs.umich.edu    if skeys == '.i':
4253118Sstever@eecs.umich.edu        continue
4263118Sstever@eecs.umich.edu
4273118Sstever@eecs.umich.edu    if isinstance(skeys, (list, tuple)) and '.i' in skeys:
4283118Sstever@eecs.umich.edu        continue
4293118Sstever@eecs.umich.edu
4303118Sstever@eecs.umich.edu    scanners.append(scanner)
4313118Sstever@eecs.umich.edu
4323118Sstever@eecs.umich.edu# add the new swig scanner that we like better
4333118Sstever@eecs.umich.edufrom SCons.Scanner import ClassicCPP as CPPScanner
4343716Sstever@eecs.umich.eduswig_inc_re = '^[ \t]*[%,#][ \t]*(?:include|import)[ \t]*(<|")([^>"]+)(>|")'
4353118Sstever@eecs.umich.eduscanners.append(CPPScanner("SwigScan", [ ".i" ], "CPPPATH", swig_inc_re))
4363118Sstever@eecs.umich.edu
4373118Sstever@eecs.umich.edu# replace the scanners list that has what we want
4383118Sstever@eecs.umich.edumain['SCANNERS'] = scanners
4393118Sstever@eecs.umich.edu
4403118Sstever@eecs.umich.edu# Add a custom Check function to the Configure context so that we can
4413118Sstever@eecs.umich.edu# figure out if the compiler adds leading underscores to global
4423118Sstever@eecs.umich.edu# variables.  This is needed for the autogenerated asm files that we
4433118Sstever@eecs.umich.edu# use for embedding the python code.
4443716Sstever@eecs.umich.edudef CheckLeading(context):
4453118Sstever@eecs.umich.edu    context.Message("Checking for leading underscore in global variables...")
4463118Sstever@eecs.umich.edu    # 1) Define a global variable called x from asm so the C compiler
4473118Sstever@eecs.umich.edu    #    won't change the symbol at all.
4483118Sstever@eecs.umich.edu    # 2) Declare that variable.
4493118Sstever@eecs.umich.edu    # 3) Use the variable
4503118Sstever@eecs.umich.edu    #
4513118Sstever@eecs.umich.edu    # If the compiler prepends an underscore, this will successfully
4523118Sstever@eecs.umich.edu    # link because the external symbol 'x' will be called '_x' which
4533118Sstever@eecs.umich.edu    # was defined by the asm statement.  If the compiler does not
4543118Sstever@eecs.umich.edu    # prepend an underscore, this will not successfully link because
4553483Ssaidi@eecs.umich.edu    # '_x' will have been defined by assembly, while the C portion of
4563494Ssaidi@eecs.umich.edu    # the code will be trying to use 'x'
4573494Ssaidi@eecs.umich.edu    ret = context.TryLink('''
4583483Ssaidi@eecs.umich.edu        asm(".globl _x; _x: .byte 0");
4593483Ssaidi@eecs.umich.edu        extern int x;
4603483Ssaidi@eecs.umich.edu        int main() { return x; }
4613053Sstever@eecs.umich.edu        ''', extension=".c")
4623053Sstever@eecs.umich.edu    context.env.Append(LEADING_UNDERSCORE=ret)
4633918Ssaidi@eecs.umich.edu    context.Result(ret)
4643053Sstever@eecs.umich.edu    return ret
4653053Sstever@eecs.umich.edu
4663053Sstever@eecs.umich.edu# Platform-specific configuration.  Note again that we assume that all
4673053Sstever@eecs.umich.edu# builds under a given build root run on the same host platform.
4683053Sstever@eecs.umich.educonf = Configure(main,
4691858SN/A                 conf_dir = joinpath(build_root, '.scons_config'),
4701858SN/A                 log_file = joinpath(build_root, 'scons_config.log'),
4711858SN/A                 custom_tests = { 'CheckLeading' : CheckLeading })
4721858SN/A
4731858SN/A# Check for leading underscores.  Don't really need to worry either
4741858SN/A# way so don't need to check the return code.
4751859SN/Aconf.CheckLeading()
4761858SN/A
4771858SN/A# Check if we should compile a 64 bit binary on Mac OS X/Darwin
4781858SN/Atry:
4791859SN/A    import platform
4801859SN/A    uname = platform.uname()
4811862SN/A    if uname[0] == 'Darwin' and compareVersions(uname[2], '9.0.0') >= 0:
4823053Sstever@eecs.umich.edu        if int(readCommand('sysctl -n hw.cpu64bit_capable')[0]):
4833053Sstever@eecs.umich.edu            main.Append(CCFLAGS='-arch x86_64')
4843053Sstever@eecs.umich.edu            main.Append(CFLAGS='-arch x86_64')
4853053Sstever@eecs.umich.edu            main.Append(LINKFLAGS='-arch x86_64')
4861859SN/A            main.Append(ASFLAGS='-arch x86_64')
4871859SN/Aexcept:
4881859SN/A    pass
4891859SN/A
4901859SN/A# Recent versions of scons substitute a "Null" object for Configure()
4911859SN/A# when configuration isn't necessary, e.g., if the "--help" option is
4921859SN/A# present.  Unfortuantely this Null object always returns false,
4931859SN/A# breaking all our configuration checks.  We replace it with our own
4941862SN/A# more optimistic null object that returns True instead.
4951859SN/Aif not conf:
4961859SN/A    def NullCheck(*args, **kwargs):
4971859SN/A        return True
4981858SN/A
4991858SN/A    class NullConf:
5002139SN/A        def __init__(self, env):
5014202Sbinkertn@umich.edu            self.env = env
5024202Sbinkertn@umich.edu        def Finish(self):
5032139SN/A            return self.env
5042155SN/A        def __getattr__(self, mname):
5054202Sbinkertn@umich.edu            return NullCheck
5064202Sbinkertn@umich.edu
5074202Sbinkertn@umich.edu    conf = NullConf(main)
5082155SN/A
5091869SN/A# Find Python include and library directories for embedding the
5101869SN/A# interpreter.  For consistency, we will use the same Python
5111869SN/A# installation used to run scons (and thus this script).  If you want
5121869SN/A# to link in an alternate version, see above for instructions on how
5134202Sbinkertn@umich.edu# to invoke scons with a different copy of the Python interpreter.
5144202Sbinkertn@umich.edufrom distutils import sysconfig
5154202Sbinkertn@umich.edu
5164202Sbinkertn@umich.edupy_getvar = sysconfig.get_config_var
5174202Sbinkertn@umich.edu
5184202Sbinkertn@umich.edupy_debug = getattr(sys, 'pydebug', False)
5194202Sbinkertn@umich.edupy_version = 'python' + py_getvar('VERSION') + (py_debug and "_d" or "")
5204202Sbinkertn@umich.edu
5215341Sstever@gmail.compy_general_include = sysconfig.get_python_inc()
5225341Sstever@gmail.compy_platform_include = sysconfig.get_python_inc(plat_specific=True)
5235341Sstever@gmail.compy_includes = [ py_general_include ]
5245342Sstever@gmail.comif py_platform_include != py_general_include:
5255342Sstever@gmail.com    py_includes.append(py_platform_include)
5264202Sbinkertn@umich.edu
5274202Sbinkertn@umich.edupy_lib_path = [ py_getvar('LIBDIR') ]
5284202Sbinkertn@umich.edu# add the prefix/lib/pythonX.Y/config dir, but only if there is no
5294202Sbinkertn@umich.edu# shared library in prefix/lib/.
5304202Sbinkertn@umich.eduif not py_getvar('Py_ENABLE_SHARED'):
5311869SN/A    py_lib_path.append(py_getvar('LIBPL'))
5324202Sbinkertn@umich.edu
5331869SN/Apy_libs = []
5342508SN/Afor lib in py_getvar('LIBS').split() + py_getvar('SYSLIBS').split():
5352508SN/A    assert lib.startswith('-l')
5362508SN/A    lib = lib[2:]   
5372508SN/A    if lib not in py_libs:
5384202Sbinkertn@umich.edu        py_libs.append(lib)
5391869SN/Apy_libs.append(py_version)
5405385Sstever@gmail.com
5415385Sstever@gmail.commain.Append(CPPPATH=py_includes)
5425385Sstever@gmail.commain.Append(LIBPATH=py_lib_path)
5435385Sstever@gmail.com
5441869SN/A# verify that this stuff works
5451869SN/Aif not conf.CheckHeader('Python.h', '<>'):
5461869SN/A    print "Error: can't find Python.h header in", py_includes
5471869SN/A    Exit(1)
5481869SN/A
5491965SN/Afor lib in py_libs:
5501965SN/A    if not conf.CheckLib(lib):
5511965SN/A        print "Error: can't find library %s required by python" % lib
5521869SN/A        Exit(1)
5531869SN/A
5542733Sktlim@umich.edu# On Solaris you need to use libsocket for socket ops
5551884SN/Aif not conf.CheckLibWithHeader(None, 'sys/socket.h', 'C++', 'accept(0,0,0);'):
5563356Sbinkertn@umich.edu   if not conf.CheckLibWithHeader('socket', 'sys/socket.h', 'C++', 'accept(0,0,0);'):
5573356Sbinkertn@umich.edu       print "Can't find library with socket calls (e.g. accept())"
5583356Sbinkertn@umich.edu       Exit(1)
5594773Snate@binkert.org
5601869SN/A# Check for zlib.  If the check passes, libz will be automatically
5611858SN/A# added to the LIBS environment variable.
5621869SN/Aif not conf.CheckLibWithHeader('z', 'zlib.h', 'C++','zlibVersion();'):
5631869SN/A    print 'Error: did not find needed zlib compression library '\
5641869SN/A          'and/or zlib.h header file.'
5651858SN/A    print '       Please install zlib and try again.'
5662761Sstever@eecs.umich.edu    Exit(1)
5671869SN/A
5685385Sstever@gmail.com# Check for <fenv.h> (C99 FP environment control)
5695385Sstever@gmail.comhave_fenv = conf.CheckHeader('fenv.h', '<>')
5703584Ssaidi@eecs.umich.eduif not have_fenv:
5711869SN/A    print "Warning: Header file <fenv.h> not found."
5721869SN/A    print "         This host has no IEEE FP rounding mode control."
5731869SN/A
5741869SN/A######################################################################
5751869SN/A#
5761869SN/A# Check for mysql.
5771858SN/A#
578955SN/Amysql_config = WhereIs('mysql_config')
579955SN/Ahave_mysql = bool(mysql_config)
5801869SN/A
5811869SN/A# Check MySQL version.
5821869SN/Aif have_mysql:
5831869SN/A    mysql_version = readCommand(mysql_config + ' --version')
5841869SN/A    min_mysql_version = '4.1'
5851869SN/A    if compareVersions(mysql_version, min_mysql_version) < 0:
5861869SN/A        print 'Warning: MySQL', min_mysql_version, 'or newer required.'
5871869SN/A        print '         Version', mysql_version, 'detected.'
5881869SN/A        have_mysql = False
5891869SN/A
5901869SN/A# Set up mysql_config commands.
5911869SN/Aif have_mysql:
5921869SN/A    mysql_config_include = mysql_config + ' --include'
5931869SN/A    if os.system(mysql_config_include + ' > /dev/null') != 0:
5941869SN/A        # older mysql_config versions don't support --include, use
5951869SN/A        # --cflags instead
5961869SN/A        mysql_config_include = mysql_config + ' --cflags | sed s/\\\'//g'
5971869SN/A    # This seems to work in all versions
5981869SN/A    mysql_config_libs = mysql_config + ' --libs'
5991869SN/A
6001869SN/A######################################################################
6011869SN/A#
6021869SN/A# Finish the configuration
6031869SN/A#
6041869SN/Amain = conf.Finish()
6051869SN/A
6061869SN/A######################################################################
6071869SN/A#
6081869SN/A# Collect all non-global variables
6093716Sstever@eecs.umich.edu#
6103356Sbinkertn@umich.edu
6113356Sbinkertn@umich.edu# Define the universe of supported ISAs
6123356Sbinkertn@umich.eduall_isa_list = [ ]
6133356Sbinkertn@umich.eduExport('all_isa_list')
6143356Sbinkertn@umich.edu
6153356Sbinkertn@umich.educlass CpuModel(object):
6164781Snate@binkert.org    '''The CpuModel class encapsulates everything the ISA parser needs to
6171869SN/A    know about a particular CPU model.'''
6181869SN/A
6191869SN/A    # Dict of available CPU model objects.  Accessible as CpuModel.dict.
6201869SN/A    dict = {}
6211869SN/A    list = []
6221869SN/A    defaults = []
6231869SN/A
6242655Sstever@eecs.umich.edu    # Constructor.  Automatically adds models to CpuModel.dict.
6252655Sstever@eecs.umich.edu    def __init__(self, name, filename, includes, strings, default=False):
6262655Sstever@eecs.umich.edu        self.name = name           # name of model
6272655Sstever@eecs.umich.edu        self.filename = filename   # filename for output exec code
6282655Sstever@eecs.umich.edu        self.includes = includes   # include files needed in exec file
6292655Sstever@eecs.umich.edu        # The 'strings' dict holds all the per-CPU symbols we can
6302655Sstever@eecs.umich.edu        # substitute into templates etc.
6312655Sstever@eecs.umich.edu        self.strings = strings
6322655Sstever@eecs.umich.edu
6332655Sstever@eecs.umich.edu        # This cpu is enabled by default
6342655Sstever@eecs.umich.edu        self.default = default
6352655Sstever@eecs.umich.edu
6362655Sstever@eecs.umich.edu        # Add self to dict
6372655Sstever@eecs.umich.edu        if name in CpuModel.dict:
6382655Sstever@eecs.umich.edu            raise AttributeError, "CpuModel '%s' already registered" % name
6392655Sstever@eecs.umich.edu        CpuModel.dict[name] = self
6402655Sstever@eecs.umich.edu        CpuModel.list.append(name)
6412655Sstever@eecs.umich.edu
6422655Sstever@eecs.umich.eduExport('CpuModel')
6432655Sstever@eecs.umich.edu
6442655Sstever@eecs.umich.edu# Sticky variables get saved in the variables file so they persist from
6452655Sstever@eecs.umich.edu# one invocation to the next (unless overridden, in which case the new
6462655Sstever@eecs.umich.edu# value becomes sticky).
6472655Sstever@eecs.umich.edusticky_vars = Variables(args=ARGUMENTS)
6482655Sstever@eecs.umich.eduExport('sticky_vars')
6492655Sstever@eecs.umich.edu
6502638Sstever@eecs.umich.edu# Sticky variables that should be exported
6512638Sstever@eecs.umich.eduexport_vars = []
6523716Sstever@eecs.umich.eduExport('export_vars')
6532638Sstever@eecs.umich.edu
6542638Sstever@eecs.umich.edu# Non-sticky variables only apply to the current build.
6551869SN/Anonsticky_vars = Variables(args=ARGUMENTS)
6561869SN/AExport('nonsticky_vars')
6573546Sgblack@eecs.umich.edu
6583546Sgblack@eecs.umich.edu# Walk the tree and execute all SConsopts scripts that wil add to the
6593546Sgblack@eecs.umich.edu# above variables
6603546Sgblack@eecs.umich.edufor bdir in [ base_dir ] + extras_dir_list:
6614202Sbinkertn@umich.edu    for root, dirs, files in os.walk(bdir):
6623546Sgblack@eecs.umich.edu        if 'SConsopts' in files:
6633546Sgblack@eecs.umich.edu            print "Reading", joinpath(root, 'SConsopts')
6643546Sgblack@eecs.umich.edu            SConscript(joinpath(root, 'SConsopts'))
6653546Sgblack@eecs.umich.edu
6663546Sgblack@eecs.umich.eduall_isa_list.sort()
6674781Snate@binkert.org
6684781Snate@binkert.orgsticky_vars.AddVariables(
6694781Snate@binkert.org    EnumVariable('TARGET_ISA', 'Target ISA', 'alpha', all_isa_list),
6704781Snate@binkert.org    BoolVariable('FULL_SYSTEM', 'Full-system support', False),
6714781Snate@binkert.org    ListVariable('CPU_MODELS', 'CPU models',
6724781Snate@binkert.org                 sorted(n for n,m in CpuModel.dict.iteritems() if m.default),
6734781Snate@binkert.org                 sorted(CpuModel.list)),
6744781Snate@binkert.org    BoolVariable('NO_FAST_ALLOC', 'Disable fast object allocator', False),
6754781Snate@binkert.org    BoolVariable('FAST_ALLOC_DEBUG', 'Enable fast object allocator debugging',
6764781Snate@binkert.org                 False),
6774781Snate@binkert.org    BoolVariable('FAST_ALLOC_STATS', 'Enable fast object allocator statistics',
6784781Snate@binkert.org                 False),
6793546Sgblack@eecs.umich.edu    BoolVariable('EFENCE', 'Link with Electric Fence malloc debugger',
6803546Sgblack@eecs.umich.edu                 False),
6813546Sgblack@eecs.umich.edu    BoolVariable('SS_COMPATIBLE_FP',
6824781Snate@binkert.org                 'Make floating-point results compatible with SimpleScalar',
6833546Sgblack@eecs.umich.edu                 False),
6843546Sgblack@eecs.umich.edu    BoolVariable('USE_SSE2',
6853546Sgblack@eecs.umich.edu                 'Compile for SSE2 (-msse2) to get IEEE FP on x86 hosts',
6863546Sgblack@eecs.umich.edu                 False),
6873546Sgblack@eecs.umich.edu    BoolVariable('USE_MYSQL', 'Use MySQL for stats output', have_mysql),
6883546Sgblack@eecs.umich.edu    BoolVariable('USE_FENV', 'Use <fenv.h> IEEE mode control', have_fenv),
6893546Sgblack@eecs.umich.edu    BoolVariable('USE_CHECKER', 'Use checker for detailed CPU models', False),
6903546Sgblack@eecs.umich.edu    BoolVariable('CP_ANNOTATE', 'Enable critical path annotation capability', False),
6913546Sgblack@eecs.umich.edu    BoolVariable('RUBY', 'Build with Ruby', False),
6923546Sgblack@eecs.umich.edu    )
6934202Sbinkertn@umich.edu
6943546Sgblack@eecs.umich.edunonsticky_vars.AddVariables(
6953546Sgblack@eecs.umich.edu    BoolVariable('update_ref', 'Update test reference outputs', False)
6963546Sgblack@eecs.umich.edu    )
697955SN/A
698955SN/A# These variables get exported to #defines in config/*.hh (see src/SConscript).
699955SN/Aexport_vars += ['FULL_SYSTEM', 'USE_FENV', 'USE_MYSQL',
700955SN/A                'NO_FAST_ALLOC', 'FAST_ALLOC_DEBUG', 'FAST_ALLOC_STATS',
7011858SN/A                'SS_COMPATIBLE_FP', 'USE_CHECKER', 'TARGET_ISA', 'CP_ANNOTATE']
7021858SN/A
7031858SN/A###################################################
7042632Sstever@eecs.umich.edu#
7052632Sstever@eecs.umich.edu# Define a SCons builder for configuration flag headers.
7065343Sstever@gmail.com#
7075343Sstever@gmail.com###################################################
7085343Sstever@gmail.com
7094773Snate@binkert.org# This function generates a config header file that #defines the
7104773Snate@binkert.org# variable symbol to the current variable setting (0 or 1).  The source
7112632Sstever@eecs.umich.edu# operands are the name of the variable and a Value node containing the
7122632Sstever@eecs.umich.edu# value of the variable.
7132632Sstever@eecs.umich.edudef build_config_file(target, source, env):
7142023SN/A    (variable, value) = [s.get_contents() for s in source]
7152632Sstever@eecs.umich.edu    f = file(str(target[0]), 'w')
7162632Sstever@eecs.umich.edu    print >> f, '#define', variable, value
7172632Sstever@eecs.umich.edu    f.close()
7182632Sstever@eecs.umich.edu    return None
7192632Sstever@eecs.umich.edu
7203716Sstever@eecs.umich.edu# Generate the message to be printed when building the config file.
7215342Sstever@gmail.comdef build_config_file_string(target, source, env):
7222632Sstever@eecs.umich.edu    (variable, value) = [s.get_contents() for s in source]
7232632Sstever@eecs.umich.edu    return "Defining %s as %s in %s." % (variable, value, target[0])
7242632Sstever@eecs.umich.edu
7252632Sstever@eecs.umich.edu# Combine the two functions into a scons Action object.
7262023SN/Aconfig_action = Action(build_config_file, build_config_file_string)
7272632Sstever@eecs.umich.edu
7282632Sstever@eecs.umich.edu# The emitter munges the source & target node lists to reflect what
7295342Sstever@gmail.com# we're really doing.
7301889SN/Adef config_emitter(target, source, env):
7312632Sstever@eecs.umich.edu    # extract variable name from Builder arg
7322632Sstever@eecs.umich.edu    variable = str(target[0])
7332632Sstever@eecs.umich.edu    # True target is config header file
7342632Sstever@eecs.umich.edu    target = joinpath('config', variable.lower() + '.hh')
7353716Sstever@eecs.umich.edu    val = env[variable]
7363716Sstever@eecs.umich.edu    if isinstance(val, bool):
7375342Sstever@gmail.com        # Force value to 0/1
7382632Sstever@eecs.umich.edu        val = int(val)
7392632Sstever@eecs.umich.edu    elif isinstance(val, str):
7402632Sstever@eecs.umich.edu        val = '"' + val + '"'
7412632Sstever@eecs.umich.edu
7422632Sstever@eecs.umich.edu    # Sources are variable name & value (packaged in SCons Value nodes)
7432632Sstever@eecs.umich.edu    return ([target], [Value(variable), Value(val)])
7442632Sstever@eecs.umich.edu
7451888SN/Aconfig_builder = Builder(emitter = config_emitter, action = config_action)
7461888SN/A
7471869SN/Amain.Append(BUILDERS = { 'ConfigFile' : config_builder })
7481869SN/A
7491858SN/A# libelf build is shared across all configs in the build root.
7505341Sstever@gmail.commain.SConscript('ext/libelf/SConscript',
7512598SN/A                variant_dir = joinpath(build_root, 'libelf'))
7522598SN/A
7532598SN/A# gzstream build is shared across all configs in the build root.
7542598SN/Amain.SConscript('ext/gzstream/SConscript',
7551858SN/A                variant_dir = joinpath(build_root, 'gzstream'))
7561858SN/A
7571858SN/A###################################################
7581858SN/A#
7591858SN/A# This function is used to set up a directory with switching headers
7601858SN/A#
7611858SN/A###################################################
7621858SN/A
7631858SN/Amain['ALL_ISA_LIST'] = all_isa_list
7641871SN/Adef make_switching_dir(dname, switch_headers, env):
7651858SN/A    # Generate the header.  target[0] is the full path of the output
7661858SN/A    # header to generate.  'source' is a dummy variable, since we get the
7671858SN/A    # list of ISAs from env['ALL_ISA_LIST'].
7681858SN/A    def gen_switch_hdr(target, source, env):
7691858SN/A        fname = str(target[0])
7701858SN/A        f = open(fname, 'w')
7711858SN/A        isa = env['TARGET_ISA'].lower()
7721858SN/A        print >>f, '#include "%s/%s/%s"' % (dname, isa, basename(fname))
7731858SN/A        f.close()
7741858SN/A
7751858SN/A    # String to print when generating header
7761859SN/A    def gen_switch_hdr_string(target, source, env):
7771859SN/A        return "Generating switch header " + str(target[0])
7781869SN/A
7791888SN/A    # Build SCons Action object. 'varlist' specifies env vars that this
7802632Sstever@eecs.umich.edu    # action depends on; when env['ALL_ISA_LIST'] changes these actions
7811869SN/A    # should get re-executed.
7821884SN/A    switch_hdr_action = Action(gen_switch_hdr, gen_switch_hdr_string,
7831884SN/A                               varlist=['ALL_ISA_LIST'])
7841884SN/A
7851884SN/A    # Instantiate actions for each header
7861884SN/A    for hdr in switch_headers:
7871884SN/A        env.Command(hdr, [], switch_hdr_action)
7881965SN/AExport('make_switching_dir')
7891965SN/A
7901965SN/A###################################################
7912761Sstever@eecs.umich.edu#
7921869SN/A# Define build environments for selected configurations.
7931869SN/A#
7942632Sstever@eecs.umich.edu###################################################
7952667Sstever@eecs.umich.edu
7961869SN/Afor variant_path in variant_paths:
7971869SN/A    print "Building in", variant_path
7982929Sktlim@umich.edu
7992929Sktlim@umich.edu    # Make a copy of the build-root environment to use for this config.
8003716Sstever@eecs.umich.edu    env = main.Clone()
8012929Sktlim@umich.edu    env['BUILDDIR'] = variant_path
802955SN/A
8032598SN/A    # variant_dir is the tail component of build path, and is used to
8042598SN/A    # determine the build parameters (e.g., 'ALPHA_SE')
8053546Sgblack@eecs.umich.edu    (build_root, variant_dir) = splitpath(variant_path)
806955SN/A
807955SN/A    # Set env variables according to the build directory config.
808955SN/A    sticky_vars.files = []
8091530SN/A    # Variables for $BUILD_ROOT/$VARIANT_DIR are stored in
810955SN/A    # $BUILD_ROOT/variables/$VARIANT_DIR so you can nuke
811955SN/A    # $BUILD_ROOT/$VARIANT_DIR without losing your variables settings.
812955SN/A    current_vars_file = joinpath(build_root, 'variables', variant_dir)
813    if isfile(current_vars_file):
814        sticky_vars.files.append(current_vars_file)
815        print "Using saved variables file %s" % current_vars_file
816    else:
817        # Build dir-specific variables file doesn't exist.
818
819        # Make sure the directory is there so we can create it later
820        opt_dir = dirname(current_vars_file)
821        if not isdir(opt_dir):
822            mkdir(opt_dir)
823
824        # Get default build variables from source tree.  Variables are
825        # normally determined by name of $VARIANT_DIR, but can be
826        # overriden by 'default=' arg on command line.
827        default_vars_file = joinpath('build_opts',
828                                     ARGUMENTS.get('default', variant_dir))
829        if isfile(default_vars_file):
830            sticky_vars.files.append(default_vars_file)
831            print "Variables file %s not found,\n  using defaults in %s" \
832                  % (current_vars_file, default_vars_file)
833        else:
834            print "Error: cannot find variables file %s or %s" \
835                  % (current_vars_file, default_vars_file)
836            Exit(1)
837
838    # Apply current variable settings to env
839    sticky_vars.Update(env)
840    nonsticky_vars.Update(env)
841
842    help_text += "\nSticky variables for %s:\n" % variant_dir \
843                 + sticky_vars.GenerateHelpText(env) \
844                 + "\nNon-sticky variables for %s:\n" % variant_dir \
845                 + nonsticky_vars.GenerateHelpText(env)
846
847    # Process variable settings.
848
849    if not have_fenv and env['USE_FENV']:
850        print "Warning: <fenv.h> not available; " \
851              "forcing USE_FENV to False in", variant_dir + "."
852        env['USE_FENV'] = False
853
854    if not env['USE_FENV']:
855        print "Warning: No IEEE FP rounding mode control in", variant_dir + "."
856        print "         FP results may deviate slightly from other platforms."
857
858    if env['EFENCE']:
859        env.Append(LIBS=['efence'])
860
861    if env['USE_MYSQL']:
862        if not have_mysql:
863            print "Warning: MySQL not available; " \
864                  "forcing USE_MYSQL to False in", variant_dir + "."
865            env['USE_MYSQL'] = False
866        else:
867            print "Compiling in", variant_dir, "with MySQL support."
868            env.ParseConfig(mysql_config_libs)
869            env.ParseConfig(mysql_config_include)
870
871    # Save sticky variable settings back to current variables file
872    sticky_vars.Save(current_vars_file, env)
873
874    if env['USE_SSE2']:
875        env.Append(CCFLAGS='-msse2')
876
877    # The src/SConscript file sets up the build rules in 'env' according
878    # to the configured variables.  It returns a list of environments,
879    # one for each variant build (debug, opt, etc.)
880    envList = SConscript('src/SConscript', variant_dir = variant_path,
881                         exports = 'env')
882
883    # Set up the regression tests for each build.
884    for e in envList:
885        SConscript('tests/SConscript',
886                   variant_dir = joinpath(variant_path, 'tests', e.Label),
887                   exports = { 'env' : e }, duplicate = False)
888
889Help(help_text)
890